Replace helper methods with readonly bool IsUnixHost and cleanup

This commit is contained in:
YoshiRulz 2019-11-04 14:30:05 +10:00
parent fec63fb66a
commit 8c059aa43c
No known key found for this signature in database
GPG Key ID: C4DE31C245353FB7
26 changed files with 132 additions and 228 deletions

View File

@ -410,21 +410,18 @@ namespace BizHawk.Client.Common
#if true
if (!IsSubfolder(parentPath, absolutePath)) return absolutePath;
return OSTailoredCode.IsWindows()
? absolutePath.Replace(parentPath, ".")
: "./" + OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{parentPath}\" \"{absolutePath}\"", $"invalid path {absolutePath} or missing realpath binary");
return OSTailoredCode.IsUnixHost
? "./" + OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{parentPath}\" \"{absolutePath}\"", $"invalid path {absolutePath} or missing realpath binary")
: absolutePath.Replace(parentPath, ".");
#else // written for Unix port but may be useful for .NET Core
if (!IsSubfolder(parentPath, absolutePath))
{
return OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows
|| parentPath.TrimEnd('.') != $"{absolutePath}/"
? absolutePath
: ".";
return OSTailoredCode.IsUnixHost && parentPath.TrimEnd('.') == $"{absolutePath}/" ? "." : absolutePath;
}
return OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows
? absolutePath.Replace(parentPath, ".")
: absolutePath.Replace(parentPath.TrimEnd('.'), "./");
return OSTailoredCode.IsUnixHost
? absolutePath.Replace(parentPath.TrimEnd('.'), "./")
: absolutePath.Replace(parentPath, ".");
#endif
}
@ -441,40 +438,33 @@ namespace BizHawk.Client.Common
/// <remarks>Algorithm for Windows taken from https://stackoverflow.com/a/7710620/7467292</remarks>
public static bool IsSubfolder(string parentPath, string childPath)
{
if (OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
var parentUri = new Uri(parentPath);
for (var childUri = new DirectoryInfo(childPath).Parent; childUri != null; childUri = childUri?.Parent)
{
if (new Uri(childUri.FullName) == parentUri) return true;
}
return false;
}
#if true
return OSTailoredCode.SimpleSubshell("realpath", $"-L \"{childPath}\"", $"invalid path {childPath} or missing realpath binary")
.StartsWith(OSTailoredCode.SimpleSubshell("realpath", $"-L \"{parentPath}\"", $"invalid path {parentPath} or missing realpath binary"));
#else // written for Unix port but may be useful for .NET Core
{
var parentUri = new Uri(parentPath.TrimEnd('.'));
return OSTailoredCode.SimpleSubshell("realpath", $"-L \"{childPath}\"", $"invalid path {childPath} or missing realpath binary")
.StartsWith(OSTailoredCode.SimpleSubshell("realpath", $"-L \"{parentPath}\"", $"invalid path {parentPath} or missing realpath binary"));
#else // written for Unix port but may be useful for Windows when moving to .NET Core
var parentUriPath = new Uri(parentPath.TrimEnd('.')).AbsolutePath.TrimEnd('/');
try
{
for (var childUri = new DirectoryInfo(childPath).Parent; childUri != null; childUri = childUri?.Parent)
{
if (new Uri(childUri.FullName).AbsolutePath.TrimEnd('/') == parentUri.AbsolutePath.TrimEnd('/')) return true;
if (new Uri(childUri.FullName).AbsolutePath.TrimEnd('/') == parentUriPath) return true;
}
}
catch
{
// ignored
}
return false;
}
#endif
}
var parentUri = new Uri(parentPath);
for (var childUri = new DirectoryInfo(childPath).Parent; childUri != null; childUri = childUri?.Parent)
{
if (new Uri(childUri.FullName) == parentUri) return true;
}
return false;
}
/// <summary>

View File

@ -346,11 +346,9 @@ namespace BizHawk.Client.Common
/// <remarks>
/// warning: we dont even want to deal with changing this at runtime. but we want it changed here for config purposes. so dont check this variable. check in GlobalWin or something like that.
/// force DX for Windows and GDI+ for Unix when a new config is generated
/// force DX for Windows and OpenGL for Unix when a new config is generated
/// </remarks>
public EDispMethod DispMethod = OSTailoredCode.IsWindows()
? EDispMethod.SlimDX9
: EDispMethod.GdiPlus;
public EDispMethod DispMethod = OSTailoredCode.IsUnixHost ? EDispMethod.OpenGL : EDispMethod.SlimDX9;
public int DispChrome_FrameWindowed = 2;
public bool DispChrome_StatusBarWindowed = true;
@ -378,9 +376,7 @@ namespace BizHawk.Client.Common
public int DispCropBottom = 0;
// Sound options
public ESoundOutputMethod SoundOutputMethod = OSTailoredCode.IsWindows()
? ESoundOutputMethod.DirectSound
: ESoundOutputMethod.OpenAL; // force OpenAL for Unix when config is generated
public ESoundOutputMethod SoundOutputMethod = OSTailoredCode.IsUnixHost ? ESoundOutputMethod.OpenAL : ESoundOutputMethod.DirectSound; // force OpenAL for Unix when config is generated
public bool SoundEnabled = true;
public bool SoundEnabledNormal = true;
public bool SoundEnabledRWFF = true;

View File

@ -43,37 +43,30 @@ namespace BizHawk.Client.Common
return true;
}
if (OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
// WARNING: setting the current directory is SLOW!!! security checks for some reason.
// so we're bypassing it with windows hacks
fixed (byte* pstr = &System.Text.Encoding.Unicode.GetBytes($"{target}\0")[0])
return SetCurrentDirectoryW(pstr);
if (System.IO.Directory.Exists(_currentDirectory)) //TODO is this necessary with Mono? extra TODO: is this necessary with .NET Core on Windows?
{
Environment.CurrentDirectory = _currentDirectory;
return true;
}
return false;
}
if (System.IO.Directory.Exists(_currentDirectory)) // race condition for great justice
{
Environment.CurrentDirectory = _currentDirectory; // that's right, you can't set a directory as current that doesnt exist because .net's got to do SENSELESS SLOW-ASS SECURITY CHECKS on it and it can't do that on a NONEXISTENT DIRECTORY
return true;
}
return false;
//HACK to bypass Windows security checks triggered by setting the current directory, which only slow us down
fixed (byte* pstr = &System.Text.Encoding.Unicode.GetBytes($"{target}\0")[0])
return SetCurrentDirectoryW(pstr);
}
private string CoolGetCurrentDirectory()
{
if (OSTailoredCode.IsWindows())
{
// GUESS WHAT!
// .NET DOES A SECURITY CHECK ON THE DIRECTORY WE JUST RETRIEVED
// AS IF ASKING FOR THE CURRENT DIRECTORY IS EQUIVALENT TO TRYING TO ACCESS IT
// SCREW YOU
var buf = new byte[32768];
fixed (byte* pBuf = &buf[0])
return System.Text.Encoding.Unicode.GetString(buf, 0, 2 * (int) GetCurrentDirectoryW(32767, pBuf));
}
if (OSTailoredCode.IsUnixHost) return Environment.CurrentDirectory;
return Environment.CurrentDirectory;
//HACK to bypass Windows security checks triggered by *getting* the current directory (why), which only slow us down
var buf = new byte[32768];
fixed (byte* pBuf = &buf[0])
return System.Text.Encoding.Unicode.GetString(buf, 0, 2 * (int) GetCurrentDirectoryW(32767, pBuf));
}
private void Sandbox(Action callback, Action exceptionCallback)

View File

@ -86,9 +86,7 @@ namespace BizHawk.Client.EmuHawk
try
{
_ffmpeg = OSTailoredCode.ConstructSubshell(
OSTailoredCode.IsWindows()
? Path.Combine(PathManager.GetDllDirectory(), "ffmpeg.exe")
: "ffmpeg",
OSTailoredCode.IsUnixHost ? "ffmpeg" : Path.Combine(PathManager.GetDllDirectory(), "ffmpeg.exe"),
$"-y -f nut -i - {_token.Commandline} \"{_baseName}{(_segment == 0 ? string.Empty : $"_{_segment}")}{_ext}\"",
checkStdout: false,
checkStderr: true // ffmpeg sends informative display to stderr, and nothing to stdout

View File

@ -83,14 +83,7 @@ namespace BizHawk.Client.EmuHawk
SetStyle(ControlStyles.Opaque, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
if (OSTailoredCode.IsWindows())
{
_renderer = new GdiRenderer();
}
else
{
_renderer = new GdiPlusRenderer();
}
_renderer = OSTailoredCode.IsUnixHost ? (IControlRenderer) new GdiPlusRenderer() : new GdiRenderer();
using (var g = CreateGraphics())
using (_renderer.LockGraphics(g, Width, Height))

View File

@ -128,24 +128,24 @@ namespace BizHawk.Client.EmuHawk
public static void Initialize()
{
if (OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
OTK_Keyboard.Initialize();
OTK_GamePad.Initialize();
}
else
{
KeyInput.Initialize();
IPCKeyInput.Initialize();
GamePad.Initialize();
GamePad360.Initialize();
}
else
{
OTK_Keyboard.Initialize();
OTK_GamePad.Initialize();
}
Instance = new Input();
}
public static void Cleanup()
{
if (OSTailoredCode.IsWindows())
if (!OSTailoredCode.IsUnixHost)
{
KeyInput.Cleanup();
GamePad.Cleanup();
@ -339,17 +339,17 @@ namespace BizHawk.Client.EmuHawk
{
while (true)
{
var keyEvents = OSTailoredCode.IsWindows()
? KeyInput.Update().Concat(IPCKeyInput.Update())
: OTK_Keyboard.Update();
if (OSTailoredCode.IsWindows())
var keyEvents = OSTailoredCode.IsUnixHost
? OTK_Keyboard.Update()
: KeyInput.Update().Concat(IPCKeyInput.Update());
if (OSTailoredCode.IsUnixHost)
{
GamePad.UpdateAll();
GamePad360.UpdateAll();
OTK_GamePad.UpdateAll();
}
else
{
OTK_GamePad.UpdateAll();
GamePad.UpdateAll();
GamePad360.UpdateAll();
}
//this block is going to massively modify data structures that the binding method uses, so we have to lock it all

View File

@ -1436,7 +1436,7 @@ namespace BizHawk.Client.EmuHawk
private void RamSearchMenuItem_Click(object sender, EventArgs e)
{
var ramSearch = GlobalWin.Tools.Load<RamSearch>();
if (!OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
// this is apparently needed for weird mono-forms-on-different-thread issues
// don't do .Show() within Load<T>() for RamSearch - instead put an instance of it here on MainForm, then show here

View File

@ -165,12 +165,11 @@ namespace BizHawk.Client.EmuHawk
Database.LoadDatabase(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "gamedb.txt"));
// TODO GL - a lot of disorganized wiring-up here
CGC.CGCBinPath = OSTailoredCode.IsWindows()
? Path.Combine(PathManager.GetDllDirectory(), "cgc.exe")
: "cgc"; // installed separately (via package manager or from https://developer.nvidia.com/cg-toolkit-download), look in $PATH
// installed separately on Unix (via package manager or from https://developer.nvidia.com/cg-toolkit-download), look in $PATH
CGC.CGCBinPath = OSTailoredCode.IsUnixHost ? "cgc" : Path.Combine(PathManager.GetDllDirectory(), "cgc.exe");
PresentationPanel = new PresentationPanel
{
GraphicsControl = {MainWindow = true}
GraphicsControl = { MainWindow = true }
};
GlobalWin.DisplayManager = new DisplayManager(PresentationPanel);
Controls.Add(PresentationPanel);
@ -1049,7 +1048,7 @@ namespace BizHawk.Client.EmuHawk
// (this could be determined with more work; other side affects of the fullscreen mode include: corrupted TaskBar, no modal boxes on top of GL control, no screenshots)
// At any rate, we can solve this by adding a 1px black border around the GL control
// Please note: It is important to do this before resizing things, otherwise momentarily a GL control without WS_BORDER will be at the magic dimensions and cause the flakeout
if (OSTailoredCode.IsWindows()
if (!OSTailoredCode.IsUnixHost
&& Global.Config.DispFullscreenHacks
&& Global.Config.DispMethod == Config.EDispMethod.OpenGL)
{
@ -1078,7 +1077,7 @@ namespace BizHawk.Client.EmuHawk
WindowState = FormWindowState.Normal;
if (OSTailoredCode.IsWindows())
if (!OSTailoredCode.IsUnixHost)
{
// do this even if DispFullscreenHacks aren't enabled, to restore it in case it changed underneath us or something
Padding = new Padding(0);

View File

@ -21,7 +21,12 @@ namespace BizHawk.Client.EmuHawk
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (EXE_PROJECT.OSTailoredCode.IsWindows())
if (EXE_PROJECT.OSTailoredCode.IsUnixHost)
{
// for Unix, skip everything else and just wire up the event handler
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
else
{
var libLoader = EXE_PROJECT.OSTailoredCode.LinkedLibManager;
@ -72,18 +77,13 @@ namespace BizHawk.Client.EmuHawk
//We need to do it here too... otherwise people get exceptions when externaltools we distribute try to startup
}
else
{
// for Unix, skip everything else and just wire up the event handler
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
}
[STAThread]
private static int Main(string[] args)
{
var exitCode = SubMain(args);
if (EXE_PROJECT.OSTailoredCode.IsLinux())
if (EXE_PROJECT.OSTailoredCode.IsUnixHost)
{
Console.WriteLine("BizHawk has completed its shutdown routines, killing process...");
Process.GetCurrentProcess().Kill();
@ -99,7 +99,7 @@ namespace BizHawk.Client.EmuHawk
// and there was a TypeLoadException before the first line of SubMain was reached (some static ColorType init?)
// zero 25-dec-2012 - only do for public builds. its annoying during development
// and don't bother when installed from a package manager i.e. not Windows --yoshi
if (!VersionInfo.DeveloperBuild && EXE_PROJECT.OSTailoredCode.IsWindows())
if (!VersionInfo.DeveloperBuild && !EXE_PROJECT.OSTailoredCode.IsUnixHost)
{
var thisversion = typeof(Program).Assembly.GetName().Version;
var utilversion = Assembly.Load(new AssemblyName("Bizhawk.Client.Common")).GetName().Version;
@ -150,10 +150,7 @@ namespace BizHawk.Client.EmuHawk
GlobalWin.GLManager = GLManager.Instance;
//now create the "GL" context for the display method. we can reuse the IGL_TK context if opengl display method is chosen
if (!EXE_PROJECT.OSTailoredCode.IsWindows())
Global.Config.DispMethod = Config.EDispMethod.GdiPlus;
REDO_DISPMETHOD:
REDO_DISPMETHOD:
if (Global.Config.DispMethod == Config.EDispMethod.GdiPlus)
GlobalWin.GL = new Bizware.BizwareGL.Drivers.GdiPlus.IGL_GdiPlus();
else if (Global.Config.DispMethod == Config.EDispMethod.SlimDX9)
@ -198,7 +195,7 @@ namespace BizHawk.Client.EmuHawk
goto REDO_DISPMETHOD;
}
if (EXE_PROJECT.OSTailoredCode.IsWindows())
if (!EXE_PROJECT.OSTailoredCode.IsUnixHost)
{
//WHY do we have to do this? some intel graphics drivers (ig7icd64.dll 10.18.10.3304 on an unknown chip on win8.1) are calling SetDllDirectory() for the process, which ruins stuff.
//The relevant initialization happened just before in "create IGL context".
@ -319,7 +316,7 @@ namespace BizHawk.Client.EmuHawk
//so.. we're going to resort to something really bad.
//avert your eyes.
var configPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.ini");
if (EXE_PROJECT.OSTailoredCode.IsWindows() // LuaInterface is not currently working on Mono
if (!EXE_PROJECT.OSTailoredCode.IsUnixHost // LuaInterface is not currently working on Mono
&& File.Exists(configPath)
&& (Array.Find(File.ReadAllLines(configPath), line => line.Contains(" \"UseNLua\": ")) ?? string.Empty)
.Contains("false"))

View File

@ -45,9 +45,9 @@ namespace BizHawk.Client.EmuHawk
public int Duration { get; set; } = 0; //TODO implementation
}
private static readonly IScreenBlankTimer _screenBlankTimer = OSTailoredCode.IsWindows()
? (IScreenBlankTimer) new Win32ScreenBlankTimer()
: new UnixScreenBlankTimer();
private static readonly IScreenBlankTimer _screenBlankTimer = OSTailoredCode.IsUnixHost
? (IScreenBlankTimer) new UnixScreenBlankTimer()
: new Win32ScreenBlankTimer();
private static int ctr;

View File

@ -23,7 +23,12 @@ namespace BizHawk.Client.EmuHawk
public Sound(IntPtr mainWindowHandle)
{
if (OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
// at the moment unix/mono can only support OpenAL (so ignore whatever is set in the config)
_outputDevice = new OpenALSoundOutput(this);
}
else
{
if (Global.Config.SoundOutputMethod == Config.ESoundOutputMethod.OpenAL)
_outputDevice = new OpenALSoundOutput(this);
@ -32,7 +37,6 @@ namespace BizHawk.Client.EmuHawk
if (Global.Config.SoundOutputMethod == Config.ESoundOutputMethod.XAudio2)
_outputDevice = new XAudio2SoundOutput(this);
}
else _outputDevice = new OpenALSoundOutput(this); // at the moment unix/mono can only support OpenAL (so ignore whatever is set in the config)
if (_outputDevice == null)
_outputDevice = new DummySoundOutput(this);

View File

@ -160,9 +160,7 @@ namespace BizHawk.Client.EmuHawk
return ms;
}
}
static readonly PlatformSpecificSysTimer sysTimer = OSTailoredCode.IsWindows()
? (PlatformSpecificSysTimer) new WinSysTimer()
: new UnixMonoSysTimer();
static readonly PlatformSpecificSysTimer sysTimer = OSTailoredCode.IsUnixHost ? (PlatformSpecificSysTimer) new UnixMonoSysTimer() : new WinSysTimer();
static uint TimeBeginPeriod(uint ms)
{
return sysTimer.TimeBeginPeriod(ms);

View File

@ -93,7 +93,7 @@ namespace BizHawk.Client.EmuHawk
RefreshAspectRatioOptions();
if (!OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
// Disable SlimDX on Unix
rbD3D9.Enabled = false;

View File

@ -356,16 +356,7 @@ namespace BizHawk.Client.EmuHawk
DoScan();
}
private void tbbOpenFolder_Click(object sender, EventArgs e)
{
var frmWares = PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null);
if (!OSTailoredCode.IsWindows() && !Directory.Exists(frmWares))
{
Directory.CreateDirectory(frmWares);
}
System.Diagnostics.Process.Start(frmWares);
}
private void tbbOpenFolder_Click(object sender, EventArgs e) => System.Diagnostics.Process.Start(PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null));
private void lvFirmwares_KeyDown(object sender, KeyEventArgs e)
{

View File

@ -67,11 +67,7 @@ namespace BizHawk.Client.EmuHawk
protected override void OnMouseClick(MouseEventArgs e)
{
if (OSTailoredCode.IsWindows())
{
HideCaret(Handle);
}
if (!OSTailoredCode.IsUnixHost) HideCaret(Handle);
base.OnMouseClick(e);
}
@ -263,10 +259,7 @@ namespace BizHawk.Client.EmuHawk
protected override void OnGotFocus(EventArgs e)
{
if (OSTailoredCode.IsWindows())
{
HideCaret(Handle);
}
if (!OSTailoredCode.IsUnixHost) HideCaret(Handle);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)

View File

@ -220,9 +220,10 @@ namespace BizHawk.Client.EmuHawk
DialogResult result;
string selectedPath;
if (OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows)
if (OSTailoredCode.IsUnixHost)
{
using var f = new FolderBrowserEx
// FolderBrowserEx doesn't work in Mono for obvious reasons
using var f = new FolderBrowserDialog
{
Description = $"Set the directory for {name}",
SelectedPath = PathManager.MakeAbsolutePath(box.Text, system)
@ -232,8 +233,7 @@ namespace BizHawk.Client.EmuHawk
}
else
{
// FolderBrowserEx doesn't work in Mono for obvious reasons
using var f = new FolderBrowserDialog
using var f = new FolderBrowserEx
{
Description = $"Set the directory for {name}",
SelectedPath = PathManager.MakeAbsolutePath(box.Text, system)

View File

@ -26,7 +26,7 @@ namespace BizHawk.Client.EmuHawk
cbEnableRWFF.Checked = Global.Config.SoundEnabledRWFF;
cbMuteFrameAdvance.Checked = Global.Config.MuteFrameAdvance;
if (!OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
// Disable DirectSound and XAudio2 on Mono
rbOutputMethodDirectSound.Enabled = false;
@ -88,7 +88,7 @@ namespace BizHawk.Client.EmuHawk
private void PopulateDeviceList()
{
IEnumerable<string> deviceNames = Enumerable.Empty<string>();
if (OSTailoredCode.IsWindows())
if (!OSTailoredCode.IsUnixHost)
{
if (rbOutputMethodDirectSound.Checked) deviceNames = DirectSoundSoundOutput.GetDeviceNames();
if (rbOutputMethodXAudio2.Checked) deviceNames = XAudio2SoundOutput.GetDeviceNames();

View File

@ -17,8 +17,7 @@ namespace BizHawk.Client.EmuHawk
{
public EmuLuaLibrary()
{
Docs = new LuaDocumentation();
//if(NLua.Lua.WhichLua == "NLua")
// if (NLua.Lua.WhichLua == "NLua")
_lua["keepalives"] = _lua.NewTable();
}

View File

@ -10,23 +10,15 @@ namespace BizHawk.Client.EmuHawk
{
public abstract class PlatformEmuLuaLibrary
{
public LuaDocumentation Docs { get; protected set; }
public readonly LuaDocumentation Docs = new LuaDocumentation();
public GuiLuaLibrary GuiLibrary => (GuiLuaLibrary) Libraries[typeof(GuiLuaLibrary)];
protected readonly Dictionary<Type, LuaLibraryBase> Libraries = new Dictionary<Type, LuaLibraryBase>();
public IEnumerable<LuaFile> RunningScripts => ScriptList.Where(lf => lf.Enabled);
public readonly LuaFileList ScriptList = new LuaFileList();
public bool IsRebootingCore { get; set; } // pretty hacky.. we dont want a lua script to be able to restart itself by rebooting the core
protected readonly Dictionary<Type, LuaLibraryBase> Libraries = new Dictionary<Type, LuaLibraryBase>();
public EventWaitHandle LuaWait { get; protected set; }
public IEnumerable<LuaFile> RunningScripts
{
get { return ScriptList.Where(lf => lf.Enabled); }
}
public readonly LuaFileList ScriptList = new LuaFileList();
public abstract void CallExitEvent(LuaFile lf);
public abstract void CallFrameAfterEvent();
public abstract void CallFrameBeforeEvent();

View File

@ -185,13 +185,8 @@ namespace BizHawk.Client.EmuHawk
}
var currentScripts = LuaImp?.ScriptList; // Temp fix for now
LuaImp = OSTailoredCode.IsWindows()
? (PlatformEmuLuaLibrary)new EmuLuaLibrary(Emulator.ServiceProvider)
: (PlatformEmuLuaLibrary)new NotReallyLuaLibrary();
if (currentScripts != null)
{
LuaImp.ScriptList.AddRange(currentScripts);
}
LuaImp = OSTailoredCode.IsUnixHost ? (PlatformEmuLuaLibrary) new NotReallyLuaLibrary() : new EmuLuaLibrary(Emulator.ServiceProvider);
LuaImp.ScriptList.AddRange(currentScripts ?? Enumerable.Empty<LuaFile>());
InputBox.AutoCompleteCustomSource.AddRange(LuaImp.Docs.Select(a => $"{a.Library}.{a.Name}").ToArray());

View File

@ -268,56 +268,31 @@ namespace BizHawk.Client.EmuHawk
/// <remarks>Algorithm for Windows taken from https://stackoverflow.com/a/485516/7467292</remarks>
public static string GetRelativePath(string fromPath, string toPath)
{
if (OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
Win32.FileAttributes fromAttr = GetPathAttribute(fromPath);
Win32.FileAttributes toAttr = GetPathAttribute(toPath);
var path = new StringBuilder(260); // MAX_PATH
if (Win32.PathRelativePathTo(
path,
fromPath,
fromAttr,
toPath,
toAttr) == false)
{
throw new ArgumentException("Paths must have a common prefix");
}
return path.ToString();
}
#if true
return PathManager.IsSubfolder(toPath, fromPath)
? "./" + OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{toPath}\" \"{fromPath}\"", $"invalid path {fromPath} or missing realpath binary")
: fromPath;
return PathManager.IsSubfolder(toPath, fromPath)
? "./" + OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{toPath}\" \"{fromPath}\"", $"invalid path {fromPath} or missing realpath binary")
: fromPath;
#else // written for Unix port but may be useful for .NET Core
// algorithm taken from https://stackoverflow.com/a/340454/7467292
var dirSepChar = Path.DirectorySeparatorChar;
string from = !fromPath.EndsWith(dirSepChar.ToString())
? fromPath + dirSepChar
: fromPath;
string to = !toPath.EndsWith(dirSepChar.ToString())
? toPath + dirSepChar
: toPath;
// algorithm taken from https://stackoverflow.com/a/340454/7467292
var dirSepChar = Path.DirectorySeparatorChar;
var fromUri = new Uri(fromPath.EndsWith(dirSepChar.ToString()) ? fromPath : fromPath + dirSepChar);
var toUri = new Uri(toPath.EndsWith(dirSepChar.ToString()) ? toPath : toPath + dirSepChar);
if (fromUri.Scheme != toUri.Scheme) return toPath;
Uri fromUri = new Uri(from);
Uri toUri = new Uri(to);
if (fromUri.Scheme != toUri.Scheme)
{
return toPath;
}
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath.TrimEnd(dirSepChar);
var relativePath = Uri.UnescapeDataString(fromUri.MakeRelativeUri(toUri).ToString());
return (toUri.Scheme.Equals(Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase)
? relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
: relativePath
).TrimEnd(dirSepChar);
#endif
}
var path = new StringBuilder(260 /* = MAX_PATH */);
return Win32.PathRelativePathTo(path, fromPath, GetPathAttribute(fromPath), toPath, GetPathAttribute(toPath))
? path.ToString()
: throw new ArgumentException("Paths must have a common prefix");
}
/// <seealso cref="GetRelativePath"/>

View File

@ -157,7 +157,7 @@ namespace BizHawk.Client.EmuHawk
}
newTool.Restart();
if (!OSTailoredCode.IsWindows() && newTool is RamSearch)
if (OSTailoredCode.IsUnixHost && newTool is RamSearch)
{
// the mono winforms implementation is buggy, skip to the return statement and call Show in MainForm instead
}
@ -748,8 +748,7 @@ namespace BizHawk.Client.EmuHawk
public bool IsAvailable(Type tool)
{
if (!ServiceInjector.IsAvailable(Global.Emulator.ServiceProvider, tool)
|| !lazyAsmTypes.Value.Contains(tool.AssemblyQualifiedName) // not a tool
|| (tool == typeof(LuaConsole) && !OSTailoredCode.IsWindows())) // simply doesn't work (for now)
|| !lazyAsmTypes.Value.Contains(tool.AssemblyQualifiedName)) // not a tool
{
return false;
}

View File

@ -95,9 +95,9 @@ namespace BizHawk.Common.BizInvoke
}
/// <summary>allocate <paramref name="size"/> bytes starting at a particular address <paramref name="start"/></summary>
public static MemoryBlockBase CallPlatformCtor(ulong start, ulong size) => OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows
? (MemoryBlockBase) new MemoryBlock(start, size)
: new MemoryBlockUnix(start, size);
public static MemoryBlockBase CallPlatformCtor(ulong start, ulong size) => OSTailoredCode.IsUnixHost
? (MemoryBlockBase) new MemoryBlockUnix(start, size)
: new MemoryBlock(start, size);
/// <summary>allocate <paramref name="size"/> bytes at any address</summary>
public static MemoryBlockBase CallPlatformCtor(ulong size) => CallPlatformCtor(0, size);

View File

@ -17,15 +17,7 @@ namespace BizHawk.Common
? SimpleSubshell("uname", "-s", "Can't determine OS") == "Darwin" ? DistinctOS.macOS : DistinctOS.Linux
: DistinctOS.Windows;
public static bool IsWindows()
{
return CurrentOS == DistinctOS.Windows;
}
public static bool IsLinux()
{
return CurrentOS == DistinctOS.Linux;
}
public static readonly bool IsUnixHost = CurrentOS != DistinctOS.Windows;
private static readonly Lazy<ILinkedLibManager> _LinkedLibManager = new Lazy<ILinkedLibManager>(() =>
{

View File

@ -93,13 +93,13 @@ namespace BizHawk.Common
{
try
{
if (OSTailoredCode.IsWindows())
if (OSTailoredCode.IsUnixHost)
{
DeleteFileW(fi.FullName); // SHUT. UP. THE. EXCEPTIONS.
fi.Delete(); // naive deletion, Mono doesn't care
}
else
{
fi.Delete();
DeleteFileW(fi.FullName); // SHUT. UP. THE. EXCEPTIONS.
}
}
catch

View File

@ -22,7 +22,7 @@ namespace BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES
{
static QuickNES()
{
Resolver = new DynamicLibraryImportResolver($"libquicknes{(OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows ? ".dll" : ".dll.so.0.7.0")}");
Resolver = new DynamicLibraryImportResolver($"libquicknes{(OSTailoredCode.IsUnixHost ? ".dll.so.0.7.0" : ".dll")}");
QN = BizInvoker.GetInvoker<LibQuickNES>(Resolver, CallingConventionAdapters.Native);
QN.qn_setup_mappers();
}
@ -30,9 +30,9 @@ namespace BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES
[CoreConstructor("NES")]
public QuickNES(CoreComm comm, byte[] file, object settings, object syncSettings)
{
FP = OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows
? (IFPCtrl) new Win32_FPCtrl()
: new Unix_FPCtrl();
FP = OSTailoredCode.IsUnixHost
? (IFPCtrl) new Unix_FPCtrl()
: new Win32_FPCtrl();
using (FP.Save())
{