Cleanup PathExtensions

Fixes f02295455/c731e1168/5c7135d67
This commit is contained in:
YoshiRulz 2020-03-20 13:51:59 +10:00
parent c985dfa96d
commit e1951b9fc5
No known key found for this signature in database
GPG Key ID: C4DE31C245353FB7
30 changed files with 143 additions and 182 deletions

View File

@ -26,7 +26,7 @@ namespace BizHawk.Client.Common
_firmwareUserSpecifications = firmwareUserSpecifications; _firmwareUserSpecifications = firmwareUserSpecifications;
} }
public string DllPath() => PathUtils.GetDllDirectory(); public string DllPath() => PathUtils.DllDirectoryPath;
// Poop // Poop
public string GetRetroSaveRAMDirectory(GameInfo game) public string GetRetroSaveRAMDirectory(GameInfo game)

View File

@ -1082,7 +1082,7 @@ namespace BizHawk.Client.Common
} }
break; break;
case "A78": case "A78":
var gameDbPath = Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "gamedb", "gamedb_a7800.csv"); var gameDbPath = Path.Combine(PathUtils.ExeDirectoryPath, "gamedb", "gamedb_a7800.csv");
nextEmulator = new A7800Hawk(nextComm, game, rom.RomData, gameDbPath, GetCoreSettings<A7800Hawk>(), GetCoreSyncSettings<A7800Hawk>()); nextEmulator = new A7800Hawk(nextComm, game, rom.RomData, gameDbPath, GetCoreSettings<A7800Hawk>(), GetCoreSyncSettings<A7800Hawk>());
break; break;
case "C64": case "C64":

View File

@ -8,9 +8,9 @@ namespace BizHawk.Client.Common
{ {
public class Config public class Config
{ {
public static string ControlDefaultPath => Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "defctrl.json"); public static string ControlDefaultPath => Path.Combine(PathUtils.ExeDirectoryPath, "defctrl.json");
public static string DefaultIniPath { get; private set; } = Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "config.ini"); public static string DefaultIniPath { get; private set; } = Path.Combine(PathUtils.ExeDirectoryPath, "config.ini");
// Shenanigans // Shenanigans
public static void SetDefaultIniPath(string newDefaultIniPath) public static void SetDefaultIniPath(string newDefaultIniPath)

View File

@ -26,7 +26,7 @@ namespace BizHawk.Client.Common
// if %exe% prefixed then substitute exe path and repeat // if %exe% prefixed then substitute exe path and repeat
if (globalBase.StartsWith("%exe%", StringComparison.InvariantCultureIgnoreCase)) if (globalBase.StartsWith("%exe%", StringComparison.InvariantCultureIgnoreCase))
{ {
globalBase = PathUtils.GetExeDirectoryAbsolute() + globalBase.Substring(5); globalBase = PathUtils.ExeDirectoryPath + globalBase.Substring(5);
} }
// rooted paths get returned without change // rooted paths get returned without change
@ -37,7 +37,7 @@ namespace BizHawk.Client.Common
} }
// not-rooted things are relative to exe path // not-rooted things are relative to exe path
globalBase = Path.Combine(PathUtils.GetExeDirectoryAbsolute(), globalBase); globalBase = Path.Combine(PathUtils.ExeDirectoryPath, globalBase);
return globalBase; return globalBase;
} }
@ -94,7 +94,7 @@ namespace BizHawk.Client.Common
if (path.StartsWith("%exe%")) if (path.StartsWith("%exe%"))
{ {
return PathUtils.GetExeDirectoryAbsolute() + path.Substring(5); return PathUtils.ExeDirectoryPath + path.Substring(5);
} }
if (path.StartsWith("%rom%")) if (path.StartsWith("%rom%"))
@ -133,7 +133,7 @@ namespace BizHawk.Client.Common
//handling of file:// or file:\\ was removed (can Path.GetFullPath handle it? not sure) //handling of file:// or file:\\ was removed (can Path.GetFullPath handle it? not sure)
// all bad paths default to EXE // all bad paths default to EXE
return PathUtils.GetExeDirectoryAbsolute(); return PathUtils.ExeDirectoryPath;
} }
public static string MovieAbsolutePath(this PathEntryCollection collection) public static string MovieAbsolutePath(this PathEntryCollection collection)
@ -224,7 +224,7 @@ namespace BizHawk.Client.Common
public static string SaveRamAbsolutePath(this PathEntryCollection collection, GameInfo game, bool movieIsActive) public static string SaveRamAbsolutePath(this PathEntryCollection collection, GameInfo game, bool movieIsActive)
{ {
var name = game.Name.FilesystemSafeName(); var name = game.FilesystemSafeName();
if (movieIsActive) if (movieIsActive)
{ {
name += $".{Path.GetFileNameWithoutExtension(Global.MovieSession.Movie.Filename)}"; name += $".{Path.GetFileNameWithoutExtension(Global.MovieSession.Movie.Filename)}";
@ -239,11 +239,11 @@ namespace BizHawk.Client.Common
// Shenanigans // Shenanigans
public static string RetroSaveRamAbsolutePath(this PathEntryCollection collection, GameInfo game, bool movieIsActive, string movieFilename) public static string RetroSaveRamAbsolutePath(this PathEntryCollection collection, GameInfo game, bool movieIsActive, string movieFilename)
{ {
var name = game.Name.FilesystemSafeName(); var name = game.FilesystemSafeName();
name = Path.GetDirectoryName(name); name = Path.GetDirectoryName(name);
if (name == "") if (name == "")
{ {
name = game.Name.FilesystemSafeName(); name = game.FilesystemSafeName();
} }
if (movieIsActive) if (movieIsActive)
@ -260,11 +260,11 @@ namespace BizHawk.Client.Common
// Shenanigans // Shenanigans
public static string RetroSystemAbsolutePath(this PathEntryCollection collection, GameInfo game) public static string RetroSystemAbsolutePath(this PathEntryCollection collection, GameInfo game)
{ {
var name = game.Name.FilesystemSafeName(); var name = game.FilesystemSafeName();
name = Path.GetDirectoryName(name); name = Path.GetDirectoryName(name);
if (string.IsNullOrEmpty(name)) if (string.IsNullOrEmpty(name))
{ {
name = game.Name.FilesystemSafeName(); name = game.FilesystemSafeName();
} }
var pathEntry = collection[game.System, "System"] var pathEntry = collection[game.System, "System"]
@ -312,31 +312,11 @@ namespace BizHawk.Client.Common
/// Takes an absolute path and attempts to convert it to a relative, based on the system, /// Takes an absolute path and attempts to convert it to a relative, based on the system,
/// or global base if no system is supplied, if it is not a subfolder of the base, it will return the path unaltered /// or global base if no system is supplied, if it is not a subfolder of the base, it will return the path unaltered
/// </summary> /// </summary>
public static string TryMakeRelative(this PathEntryCollection collection, string absolutePath, string system = null) public static string TryMakeRelative(this PathEntryCollection collection, string absolutePath, string system = null) => absolutePath.MakeRelativeTo(
{ string.IsNullOrWhiteSpace(system)
var parentPath = string.IsNullOrWhiteSpace(system)
? collection.GlobalBaseAbsolutePath() ? collection.GlobalBaseAbsolutePath()
: collection.AbsolutePathFor(collection.BaseFor(system), system); : collection.AbsolutePathFor(collection.BaseFor(system), system)
#if true );
if (!absolutePath.IsSubfolderOf(parentPath))
{
return absolutePath;
}
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.IsUnixHost && parentPath.TrimEnd('.') == $"{absolutePath}/" ? "." : absolutePath;
}
return OSTailoredCode.IsUnixHost
? absolutePath.Replace(parentPath.TrimEnd('.'), "./")
: absolutePath.Replace(parentPath, ".");
#endif
}
/// <summary> /// <summary>
/// Puts the currently configured temp path into the environment for use as actual temp directory /// Puts the currently configured temp path into the environment for use as actual temp directory

View File

@ -293,7 +293,7 @@ namespace BizHawk.Client.Common.MovieConversionExtensions
if (Global.Game != null) if (Global.Game != null)
{ {
movie.GameName = Global.Game.Name.FilesystemSafeName(); movie.GameName = Global.Game.FilesystemSafeName();
movie.Hash = Global.Game.Hash; movie.Hash = Global.Game.Hash;
if (Global.Game.FirmwareHash != null) if (Global.Game.FirmwareHash != null)
{ {

View File

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

View File

@ -6,7 +6,7 @@ using System.Windows.Forms;
using BizHawk.Bizware.BizwareGL; using BizHawk.Bizware.BizwareGL;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -33,7 +33,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var ofd = new OpenFileDialog var ofd = new OpenFileDialog
{ {
FileName = $"{Global.Game.Name.FilesystemSafeName()}.syncless.txt", FileName = $"{Global.Game.FilesystemSafeName()}.syncless.txt",
InitialDirectory = Global.Config.PathEntries.AvAbsolutePath() InitialDirectory = Global.Config.PathEntries.AvAbsolutePath()
}; };

View File

@ -82,17 +82,17 @@ namespace BizHawk.Client.EmuHawk
if (GL is IGL_TK || GL is IGL_SlimDX9) if (GL is IGL_TK || GL is IGL_SlimDX9)
{ {
var fiHq2x = new FileInfo(Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "Shaders/BizHawk/hq2x.cgp")); var fiHq2x = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/hq2x.cgp"));
if (fiHq2x.Exists) if (fiHq2x.Exists)
{ {
using var stream = fiHq2x.OpenRead(); using var stream = fiHq2x.OpenRead();
ShaderChain_hq2x = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); ShaderChain_hq2x = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk"));
} }
var fiScanlines = new FileInfo(Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "Shaders/BizHawk/BizScanlines.cgp")); var fiScanlines = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/BizScanlines.cgp"));
if (fiScanlines.Exists) if (fiScanlines.Exists)
{ {
using var stream = fiScanlines.OpenRead(); using var stream = fiScanlines.OpenRead();
ShaderChain_scanlines = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); ShaderChain_scanlines = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk"));
} }
string bicubicPath = "Shaders/BizHawk/bicubic-fast.cgp"; string bicubicPath = "Shaders/BizHawk/bicubic-fast.cgp";
@ -100,11 +100,11 @@ namespace BizHawk.Client.EmuHawk
{ {
bicubicPath = "Shaders/BizHawk/bicubic-normal.cgp"; bicubicPath = "Shaders/BizHawk/bicubic-normal.cgp";
} }
var fiBicubic = new FileInfo(Path.Combine(PathUtils.GetExeDirectoryAbsolute(), bicubicPath)); var fiBicubic = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, bicubicPath));
if (fiBicubic.Exists) if (fiBicubic.Exists)
{ {
using var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read); using var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
ShaderChain_bicubic = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); ShaderChain_bicubic = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk"));
} }
} }

View File

@ -156,7 +156,7 @@ namespace BizHawk.Client.EmuHawk
if (result.IsOk()) if (result.IsOk())
{ {
var gameDbEntry = Emulator.AsGameDBEntryGenerator().GenerateGameDbEntry(); var gameDbEntry = Emulator.AsGameDBEntryGenerator().GenerateGameDbEntry();
var userDb = Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "gamedb", "gamedb_user.txt"); var userDb = Path.Combine(PathUtils.ExeDirectoryPath, "gamedb", "gamedb_user.txt");
Global.Game.Status = gameDbEntry.Status = picker.PickedStatus; Global.Game.Status = gameDbEntry.Status = picker.PickedStatus;
Database.SaveDatabaseEntry(userDb, gameDbEntry); Database.SaveDatabaseEntry(userDb, gameDbEntry);
MainForm.UpdateDumpIcon(); MainForm.UpdateDumpIcon();

View File

@ -536,7 +536,7 @@ namespace BizHawk.Client.EmuHawk
var filename = MovieSession.Movie.Filename; var filename = MovieSession.Movie.Filename;
if (string.IsNullOrWhiteSpace(filename)) if (string.IsNullOrWhiteSpace(filename))
{ {
filename = Game.Name.FilesystemSafeName(); filename = Game.FilesystemSafeName();
} }
var file = ToolFormBase.SaveFileDialog( var file = ToolFormBase.SaveFileDialog(

View File

@ -237,8 +237,8 @@ namespace BizHawk.Client.EmuHawk
// we could background thread this later instead if we wanted to be real clever // we could background thread this later instead if we wanted to be real clever
BootGodDb.GetDatabaseBytes = () => BootGodDb.GetDatabaseBytes = () =>
{ {
string xmlPath = Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.xml"); string xmlPath = Path.Combine(PathUtils.ExeDirectoryPath, "gamedb", "NesCarts.xml");
string x7zPath = Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.7z"); string x7zPath = Path.Combine(PathUtils.ExeDirectoryPath, "gamedb", "NesCarts.7z");
bool loadXml = File.Exists(xmlPath); bool loadXml = File.Exists(xmlPath);
using var nesCartFile = new HawkFile(loadXml ? xmlPath : x7zPath); using var nesCartFile = new HawkFile(loadXml ? xmlPath : x7zPath);
if (!loadXml) if (!loadXml)
@ -259,11 +259,11 @@ namespace BizHawk.Client.EmuHawk
MessageBox.Show(e.Message); MessageBox.Show(e.Message);
} }
Database.LoadDatabase(Path.Combine(PathUtils.GetExeDirectoryAbsolute(), "gamedb", "gamedb.txt")); Database.LoadDatabase(Path.Combine(PathUtils.ExeDirectoryPath, "gamedb", "gamedb.txt"));
// TODO GL - a lot of disorganized wiring-up here // TODO GL - a lot of disorganized wiring-up here
// installed separately on Unix (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(PathUtils.GetDllDirectory(), "cgc.exe"); CGC.CGCBinPath = OSTailoredCode.IsUnixHost ? "cgc" : Path.Combine(PathUtils.DllDirectoryPath, "cgc.exe");
PresentationPanel = new PresentationPanel(this, Config, GlobalWin.GL) PresentationPanel = new PresentationPanel(this, Config, GlobalWin.GL)
{ {
GraphicsControl = { MainWindow = true } GraphicsControl = { MainWindow = true }
@ -1045,7 +1045,7 @@ namespace BizHawk.Client.EmuHawk
private string ScreenshotPrefix() private string ScreenshotPrefix()
{ {
var screenPath = Config.PathEntries.ScreenshotAbsolutePathFor(Game.System); var screenPath = Config.PathEntries.ScreenshotAbsolutePathFor(Game.System);
var name = Game.Name.FilesystemSafeName(); var name = Game.FilesystemSafeName();
return Path.Combine(screenPath, name); return Path.Combine(screenPath, name);
} }
@ -3241,7 +3241,7 @@ namespace BizHawk.Client.EmuHawk
using var sfd = new SaveFileDialog(); using var sfd = new SaveFileDialog();
if (Game != null) if (Game != null)
{ {
sfd.FileName = $"{Game.Name.FilesystemSafeName()}.{ext}"; // don't use Path.ChangeExtension, it might wreck game names with dots in them sfd.FileName = $"{Game.FilesystemSafeName()}.{ext}"; // don't use Path.ChangeExtension, it might wreck game names with dots in them
sfd.InitialDirectory = Config.PathEntries.AvAbsolutePath(); sfd.InitialDirectory = Config.PathEntries.AvAbsolutePath();
} }
else else
@ -3467,7 +3467,7 @@ namespace BizHawk.Client.EmuHawk
public string SaveStatePrefix() public string SaveStatePrefix()
{ {
var name = Game.Name.FilesystemSafeName(); var name = Game.FilesystemSafeName();
// Neshawk and Quicknes have incompatible savestates, store the name to keep them separate // Neshawk and Quicknes have incompatible savestates, store the name to keep them separate
if (Emulator.SystemId == "NES") if (Emulator.SystemId == "NES")

View File

@ -8,7 +8,7 @@ using System.Windows.Forms;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common; using BizHawk.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -103,7 +103,7 @@ namespace BizHawk.Client.EmuHawk
using var sfd = new SaveFileDialog using var sfd = new SaveFileDialog
{ {
FileName = $"{Global.Game.Name.FilesystemSafeName()}-Palettes", FileName = $"{Global.Game.FilesystemSafeName()}-Palettes",
InitialDirectory = path, InitialDirectory = path,
Filter = FilesystemFilterSet.Screenshots.ToString(), Filter = FilesystemFilterSet.Screenshots.ToString(),
RestoreDirectory = true RestoreDirectory = true

View File

@ -168,7 +168,7 @@ namespace BizHawk.Client.EmuHawk
// Pull out matching names // Pull out matching names
for (var i = 0; i < _movieList.Count; i++) for (var i = 0; i < _movieList.Count; i++)
{ {
if (_game.Name.FilesystemSafeName() == _movieList[i].GameName) if (_game.FilesystemSafeName() == _movieList[i].GameName)
{ {
indices.Add(i); indices.Add(i);
} }

View File

@ -198,7 +198,7 @@ namespace BizHawk.Client.EmuHawk
private void RecordMovie_Load(object sender, EventArgs e) private void RecordMovie_Load(object sender, EventArgs e)
{ {
RecordBox.Text = _game.Name.FilesystemSafeName(); RecordBox.Text = _game.FilesystemSafeName();
StartFromCombo.SelectedIndex = 0; StartFromCombo.SelectedIndex = 0;
DefaultAuthorCheckBox.Checked = _config.UseDefaultAuthor; DefaultAuthorCheckBox.Checked = _config.UseDefaultAuthor;
if (_config.UseDefaultAuthor) if (_config.UseDefaultAuthor)

View File

@ -494,7 +494,7 @@ namespace BizHawk.Client.EmuHawk
try try
{ {
_autoloading = true; _autoloading = true;
var autoResumeFile = $"{Global.Game.Name.FilesystemSafeName()}.cdl"; var autoResumeFile = $"{Global.Game.FilesystemSafeName()}.cdl";
var autoResumeDir = Config.PathEntries.LogAbsolutePath(); var autoResumeDir = Config.PathEntries.LogAbsolutePath();
var autoResumePath = Path.Combine(autoResumeDir, autoResumeFile); var autoResumePath = Path.Combine(autoResumeDir, autoResumeFile);
if (File.Exists(autoResumePath)) if (File.Exists(autoResumePath))

View File

@ -970,7 +970,7 @@ namespace BizHawk.Client.EmuHawk
, FileName = , FileName =
_domain.Name == "File on Disk" _domain.Name == "File on Disk"
? RomName ? RomName
: Global.Game.Name.FilesystemSafeName() : Global.Game.FilesystemSafeName()
}; };
var result = sfd.ShowHawkDialog(); var result = sfd.ShowHawkDialog();
@ -983,7 +983,7 @@ namespace BizHawk.Client.EmuHawk
{ {
FileName = _domain.Name == "File on Disk" FileName = _domain.Name == "File on Disk"
? $"{Path.GetFileNameWithoutExtension(RomName)}.txt" ? $"{Path.GetFileNameWithoutExtension(RomName)}.txt"
: Global.Game.Name.FilesystemSafeName(), : Global.Game.FilesystemSafeName(),
Filter = new FilesystemFilterSet(FilesystemFilter.TextFiles).ToString(), Filter = new FilesystemFilterSet(FilesystemFilter.TextFiles).ToString(),
InitialDirectory = RomDirectory, InitialDirectory = RomDirectory,
RestoreDirectory = true RestoreDirectory = true

View File

@ -570,7 +570,7 @@ namespace BizHawk.Client.EmuHawk
} }
else if (Global.Game != null) else if (Global.Game != null)
{ {
sfd.FileName = Global.Game.Name.FilesystemSafeName(); sfd.FileName = Global.Game.FilesystemSafeName();
sfd.InitialDirectory = Config.PathEntries.LuaAbsolutePath(); sfd.InitialDirectory = Config.PathEntries.LuaAbsolutePath();
} }
else else

View File

@ -280,7 +280,7 @@ namespace BizHawk.Client.EmuHawk
{ {
return Config.PathEntries.AbsolutePathFor(Path.Combine( return Config.PathEntries.AbsolutePathFor(Path.Combine(
Config.PathEntries["Global", "Macros"].Path, Config.PathEntries["Global", "Macros"].Path,
Global.Game.Name.FilesystemSafeName()), null); Global.Game.FilesystemSafeName()), null);
} }
#endregion #endregion

View File

@ -240,7 +240,7 @@ namespace BizHawk.Client.EmuHawk
filename = NameBox.Text; filename = NameBox.Text;
if (string.IsNullOrWhiteSpace(filename)) if (string.IsNullOrWhiteSpace(filename))
{ {
filename = Path.ChangeExtension(Global.Game.Name.FilesystemSafeName(), ".xml"); filename = Path.ChangeExtension(Global.Game.FilesystemSafeName(), ".xml");
} }
initialDirectory = Path.GetDirectoryName(filename); initialDirectory = Path.GetDirectoryName(filename);
@ -265,27 +265,9 @@ namespace BizHawk.Client.EmuHawk
/// <remarks>Algorithm for Windows taken from https://stackoverflow.com/a/485516/7467292</remarks> /// <remarks>Algorithm for Windows taken from https://stackoverflow.com/a/485516/7467292</remarks>
public static string GetRelativePath(string fromPath, string toPath) public static string GetRelativePath(string fromPath, string toPath)
{ {
if (OSTailoredCode.IsUnixHost) if (OSTailoredCode.IsUnixHost) return fromPath.MakeRelativeTo(toPath);
{
#if true
return fromPath.IsSubfolderOf(toPath)
? "./" + 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;
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;
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
}
//TODO merge this with the Windows implementation in PathExtensions.MakeRelativeTo
static FileAttributes GetPathAttribute(string path1) static FileAttributes GetPathAttribute(string path1)
{ {
var di = new DirectoryInfo(path1.Split('|').First()); var di = new DirectoryInfo(path1.Split('|').First());

View File

@ -4,7 +4,7 @@ using System.IO;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -69,7 +69,7 @@ namespace BizHawk.Client.EmuHawk
{ {
using var sfd = new SaveFileDialog using var sfd = new SaveFileDialog
{ {
FileName = $"{Global.Game.Name.FilesystemSafeName()}-Nametables", FileName = $"{Global.Game.FilesystemSafeName()}-Nametables",
InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"), InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"),
Filter = FilesystemFilterSet.Screenshots.ToString(), Filter = FilesystemFilterSet.Screenshots.ToString(),
RestoreDirectory = true RestoreDirectory = true

View File

@ -4,7 +4,7 @@ using System.IO;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -75,7 +75,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var sfd = new SaveFileDialog var sfd = new SaveFileDialog
{ {
FileName = $"{Global.Game.Name.FilesystemSafeName()}-Palettes", FileName = $"{Global.Game.FilesystemSafeName()}-Palettes",
InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"), InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"),
Filter = FilesystemFilterSet.Screenshots.ToString(), Filter = FilesystemFilterSet.Screenshots.ToString(),
RestoreDirectory = true RestoreDirectory = true

View File

@ -4,7 +4,7 @@ using System.IO;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -37,7 +37,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var sfd = new SaveFileDialog var sfd = new SaveFileDialog
{ {
FileName = $"{Global.Game.Name.FilesystemSafeName()}-Patterns", FileName = $"{Global.Game.FilesystemSafeName()}-Patterns",
InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"), InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"),
Filter = FilesystemFilterSet.Screenshots.ToString(), Filter = FilesystemFilterSet.Screenshots.ToString(),
RestoreDirectory = true RestoreDirectory = true

View File

@ -4,7 +4,7 @@ using System.IO;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using BizHawk.Client.Common; using BizHawk.Client.Common;
using BizHawk.Common.PathExtensions; using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk namespace BizHawk.Client.EmuHawk
{ {
@ -39,7 +39,7 @@ namespace BizHawk.Client.EmuHawk
{ {
var sfd = new SaveFileDialog var sfd = new SaveFileDialog
{ {
FileName = $"{Global.Game.Name.FilesystemSafeName()}-Sprites", FileName = $"{Global.Game.FilesystemSafeName()}-Sprites",
InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"), InitialDirectory = Global.Config.PathEntries.ScreenshotAbsolutePathFor("NES"),
Filter = FilesystemFilterSet.Screenshots.ToString(), Filter = FilesystemFilterSet.Screenshots.ToString(),
RestoreDirectory = true RestoreDirectory = true

View File

@ -867,7 +867,7 @@ namespace BizHawk.Client.EmuHawk
{ {
return Path.Combine( return Path.Combine(
Global.Config.PathEntries.MovieAbsolutePath(), Global.Config.PathEntries.MovieAbsolutePath(),
$"{Global.Game.Name.FilesystemSafeName()}.{TasMovie.Extension}"); $"{Global.Game.FilesystemSafeName()}.{TasMovie.Extension}");
} }
private void SaveTas() private void SaveTas()

View File

@ -26,7 +26,7 @@ namespace BizHawk.Client.EmuHawk
{ {
FileName = !string.IsNullOrWhiteSpace(currentFile) FileName = !string.IsNullOrWhiteSpace(currentFile)
? Path.GetFileName(currentFile) ? Path.GetFileName(currentFile)
: $"{Global.Game.Name.FilesystemSafeName()}.{fileExt}", : $"{Global.Game.FilesystemSafeName()}.{fileExt}",
InitialDirectory = path, InitialDirectory = path,
Filter = new FilesystemFilterSet(new FilesystemFilter(fileType, new[] { fileExt })).ToString(), Filter = new FilesystemFilterSet(new FilesystemFilter(fileType, new[] { fileExt })).ToString(),
RestoreDirectory = true RestoreDirectory = true
@ -52,7 +52,7 @@ namespace BizHawk.Client.EmuHawk
{ {
FileName = !string.IsNullOrWhiteSpace(currentFile) FileName = !string.IsNullOrWhiteSpace(currentFile)
? Path.GetFileName(currentFile) ? Path.GetFileName(currentFile)
: $"{Global.Game.Name.FilesystemSafeName()}.{fileExt}", : $"{Global.Game.FilesystemSafeName()}.{fileExt}",
InitialDirectory = path, InitialDirectory = path,
Filter = new FilesystemFilterSet(new FilesystemFilter(fileType, new[] { fileExt })).ToString(), Filter = new FilesystemFilterSet(new FilesystemFilter(fileType, new[] { fileExt })).ToString(),
RestoreDirectory = true, RestoreDirectory = true,

View File

@ -871,7 +871,7 @@ namespace BizHawk.Client.EmuHawk
f.Directory.Create(); f.Directory.Create();
} }
return Path.Combine(path, $"{Global.Game.Name.FilesystemSafeName()}.cht"); return Path.Combine(path, $"{Global.Game.FilesystemSafeName()}.cht");
} }
public void UpdateCheatRelatedTools(object sender, CheatCollection.CheatListEventArgs e) public void UpdateCheatRelatedTools(object sender, CheatCollection.CheatListEventArgs e)

View File

@ -285,12 +285,12 @@ namespace BizHawk.Client.EmuHawk
using var sfd = new SaveFileDialog(); using var sfd = new SaveFileDialog();
if (LogFile == null) if (LogFile == null)
{ {
sfd.FileName = Global.Game.Name.FilesystemSafeName() + _extension; sfd.FileName = Global.Game.FilesystemSafeName() + _extension;
sfd.InitialDirectory = Config.PathEntries.LogAbsolutePath(); sfd.InitialDirectory = Config.PathEntries.LogAbsolutePath();
} }
else if (!string.IsNullOrWhiteSpace(LogFile.FullName)) else if (!string.IsNullOrWhiteSpace(LogFile.FullName))
{ {
sfd.FileName = Global.Game.Name.FilesystemSafeName(); sfd.FileName = Global.Game.FilesystemSafeName();
sfd.InitialDirectory = Path.GetDirectoryName(LogFile.FullName); sfd.InitialDirectory = Path.GetDirectoryName(LogFile.FullName);
} }
else else
@ -458,7 +458,7 @@ namespace BizHawk.Client.EmuHawk
{ {
FileBox.Visible = true; FileBox.Visible = true;
BrowseBox.Visible = true; BrowseBox.Visible = true;
var name = Global.Game.Name.FilesystemSafeName(); var name = Global.Game.FilesystemSafeName();
var filename = Path.Combine(Config.PathEntries.LogAbsolutePath(), name) + _extension; var filename = Path.Combine(Config.PathEntries.LogAbsolutePath(), name) + _extension;
LogFile = new FileInfo(filename); LogFile = new FileInfo(filename);
if (LogFile.Directory != null && !LogFile.Directory.Exists) if (LogFile.Directory != null && !LogFile.Directory.Exists)

View File

@ -1,32 +1,20 @@
#nullable disable using System;
using System;
using System.Linq;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using BizHawk.Common.StringExtensions;
namespace BizHawk.Common.PathExtensions namespace BizHawk.Common.PathExtensions
{ {
public static class PathExtensions public static class PathExtensions
{ {
public static string RemoveInvalidFileSystemChars(this string name) /// <returns><see langword="true"/> iff <paramref name="childPath"/> indicates a child of <paramref name="parentPath"/>, with <see langword="false"/> being returned if either path is <see langword="null"/></returns>
/// <remarks>algorithm for Windows taken from https://stackoverflow.com/a/7710620/7467292</remarks>
public static bool IsSubfolderOf(this string? childPath, string? parentPath)
{ {
var newStr = name; if (childPath == null || parentPath == null) return false;
var chars = Path.GetInvalidFileNameChars(); if (childPath == parentPath || childPath.StartsWith($"{parentPath}{Path.DirectorySeparatorChar}")) return true;
return chars.Aggregate(newStr, (current, c) => current.Replace(c.ToString(), ""));
}
/// <summary>
/// Decides if a path is non-empty, not . and not .\
/// </summary>
public static bool PathIsSet(this string? path)
{
return !string.IsNullOrWhiteSpace(path) && path != "." && path != ".\\";
}
/// <remarks>Algorithm for Windows taken from https://stackoverflow.com/a/7710620/7467292</remarks>
public static bool IsSubfolderOf(this string childPath, string parentPath)
{
if (OSTailoredCode.IsUnixHost) if (OSTailoredCode.IsUnixHost)
{ {
#if true #if true
@ -36,7 +24,7 @@ namespace BizHawk.Common.PathExtensions
var parentUriPath = new Uri(parentPath.TrimEnd('.')).AbsolutePath.TrimEnd('/'); var parentUriPath = new Uri(parentPath.TrimEnd('.')).AbsolutePath.TrimEnd('/');
try try
{ {
for (var childUri = new DirectoryInfo(childPath).Parent; childUri != null; childUri = childUri?.Parent) for (var childUri = new DirectoryInfo(childPath).Parent; childUri != null; childUri = childUri.Parent)
{ {
if (new Uri(childUri.FullName).AbsolutePath.TrimEnd('/') == parentUriPath) return true; if (new Uri(childUri.FullName).AbsolutePath.TrimEnd('/') == parentUriPath) return true;
} }
@ -54,80 +42,69 @@ namespace BizHawk.Common.PathExtensions
{ {
if (new Uri(childUri.FullName) == parentUri) return true; if (new Uri(childUri.FullName) == parentUri) return true;
} }
return false; return false;
} }
public static string MakeRelativeTo(this string absolutePath, string basePath) /// <returns>the absolute path equivalent to <paramref name="path"/> which contains <c>%exe%</c> (expanded) as a prefix</returns>
/// <remarks>
/// returned string omits trailing slash<br/>
/// note that the returned string is an absolute path and not a relative path; but TODO it was intended to be relative
/// </remarks>
public static string MakeProgramRelativePath(this string path) => Path.Combine(PathUtils.ExeDirectoryPath, path);
/// <returns>the relative path which is equivalent to <paramref name="absolutePath"/> when the CWD is <paramref name="basePath"/>, or <see langword="null"/> if either path is <see langword="null"/></returns>
/// <remarks>returned string omits trailing slash; implementation calls <see cref="IsSubfolderOf"/> for you</remarks>
public static string? MakeRelativeTo(this string? absolutePath, string? basePath)
{ {
if (absolutePath.IsSubfolderOf(basePath)) if (absolutePath == null || basePath == null) return null;
{ if (!absolutePath.IsSubfolderOf(basePath)) return absolutePath;
return absolutePath.Replace(basePath, "."); if (!OSTailoredCode.IsUnixHost) return absolutePath.Replace(basePath, ".").RemoveSuffix(Path.DirectorySeparatorChar);
#if true // Unix implementation using realpath
var realpathOutput = OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{basePath}\" \"{absolutePath}\"", $"invalid path {absolutePath}, invalid path {basePath}, or missing realpath binary");
return !realpathOutput.StartsWith("../") && realpathOutput != "." && realpathOutput != ".." ? $"./{realpathOutput}" : realpathOutput;
#else // for some reason there were two Unix implementations in the codebase before me? --yoshi
// alt. #1
if (!IsSubfolder(basePath, absolutePath)) return OSTailoredCode.IsUnixHost && basePath.TrimEnd('.') == $"{absolutePath}/" ? "." : absolutePath;
return OSTailoredCode.IsUnixHost ? absolutePath.Replace(basePath.TrimEnd('.'), "./") : absolutePath.Replace(basePath, ".");
// alt. #2; algorithm taken from https://stackoverflow.com/a/340454/7467292
var dirSepChar = Path.DirectorySeparatorChar;
var fromUri = new Uri(absolutePath.EndsWith(dirSepChar.ToString()) ? absolutePath : absolutePath + dirSepChar);
var toUri = new Uri(basePath.EndsWith(dirSepChar.ToString()) ? basePath : basePath + dirSepChar);
if (fromUri.Scheme != toUri.Scheme) return basePath;
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
} }
return absolutePath; /// <returns><see langword="false"/> iff <paramref name="path"/> is blank, or is <c>"."</c> (relative path to CWD), regardless of trailing slash</returns>
} public static bool PathIsSet(this string path) => !string.IsNullOrWhiteSpace(path) && path != "." && path != "./" && path != ".\\";
public static string FilesystemSafeName(this string name) public static string RemoveInvalidFileSystemChars(this string name) => string.Concat(name.Split(Path.GetInvalidFileNameChars()));
{
name ??= "";
var filesystemSafeName = name
.Replace("|", "+")
.Replace(":", " -") // Path.GetFileName scraps everything to the left of a colon unfortunately, so we need this hack here
.Replace("\"", "") // Ivan IronMan Stewart's Super Off-Road has quotes in game name
.Replace("/", "+"); // Mario Bros / Duck hunt has a slash in the name which GetDirectoryName and GetFileName treat as if it were a folder
// zero 06-nov-2015 - regarding the below, i changed my mind. for libretro i want subdirectories here.
var filesystemDir = Path.GetDirectoryName(filesystemSafeName);
filesystemSafeName = Path.GetFileName(filesystemSafeName);
filesystemSafeName = filesystemSafeName.RemoveInvalidFileSystemChars();
// zero 22-jul-2012 - i don't think this is used the same way it used to. game.Name shouldn't be a path, so this stuff is illogical.
// if game.Name is a path, then someone should have made it not-a-path already.
// return Path.Combine(Path.GetDirectoryName(filesystemSafeName), Path.GetFileNameWithoutExtension(filesystemSafeName));
// adelikat:
// This hack is to prevent annoying things like Super Mario Bros..bk2
if (filesystemSafeName.EndsWith("."))
{
filesystemSafeName = filesystemSafeName.Remove(filesystemSafeName.Length - 1, 1);
}
return Path.Combine(filesystemDir, filesystemSafeName);
}
// TODO: this always makes an absolute path!
// Needs to be fixed, the intent was to turn an absolute path
// into one relative to the exe
// for instance: C:\BizHawk\Lua becomes .\Lua (if EmuHawk.Exe is in C:\BizHawk)
/// <summary>
/// Makes a path relative to the %exe% directory
/// </summary>
public static string MakeProgramRelativePath(this string path)
{
return Path.Combine(PathUtils.GetExeDirectoryAbsolute(), path);
}
} }
public static class PathUtils public static class PathUtils
{ {
public static string GetExeDirectoryAbsolute() /// <returns>absolute path of the dll dir (sibling of EmuHawk.exe)</returns>
{ /// <remarks>returned string omits trailing slash</remarks>
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); public static readonly string DllDirectoryPath;
if (path.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
path = path.Remove(path.Length - 1, 1);
}
return path; /// <returns>absolute path of the parent dir of DiscoHawk.exe/EmuHawk.exe, commonly referred to as <c>%exe%</c> though none of our code adds it to the environment</returns>
} /// <remarks>returned string omits trailing slash</remarks>
public static readonly string ExeDirectoryPath;
public static string GetDllDirectory() static PathUtils()
{ {
return Path.Combine(GetExeDirectoryAbsolute(), "dll"); var dirPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
ExeDirectoryPath = OSTailoredCode.IsUnixHost
? (string.IsNullOrEmpty(dirPath) || dirPath == "/" ? string.Empty : dirPath)
: (string.IsNullOrEmpty(dirPath) ? throw new Exception("failed to get location of executable, very bad things must have happened") : dirPath.RemoveSuffix('\\'));
DllDirectoryPath = Path.Combine(OSTailoredCode.IsUnixHost && ExeDirectoryPath == string.Empty ? "/" : ExeDirectoryPath, "dll");
// yes, this is a lot of extra code to make sure BizHawk can run in `/` on Unix, but I've made up for it by caching these for the program lifecycle --yoshi
} }
} }
} }

View File

@ -201,5 +201,11 @@ namespace BizHawk.Common.StringExtensions
} }
#pragma warning restore CS8602 #pragma warning restore CS8602
/// <returns><paramref name="str"/> with the last char removed (iff the last char is <paramref name="suffix"/>, otherwise <paramref name="str"/> unmodified)</returns>
public static string RemoveSuffix(this string str, char suffix) => str[str.Length - 1] == suffix ? str.Substring(0, str.Length - 1) : str;
/// <returns><paramref name="str"/> with the trailing substring <paramref name="suffix"/> removed (iff <paramref name="str"/> ends with <paramref name="suffix"/>, otherwise <paramref name="str"/> unmodified)</returns>
public static string RemoveSuffix(this string str, string suffix) => str.EndsWith(suffix) ? str.Substring(0, str.Length - suffix.Length) : str;
} }
} }

View File

@ -1,9 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using BizHawk.Common.PathExtensions;
using BizHawk.Common.StringExtensions;
namespace BizHawk.Emulation.Common namespace BizHawk.Emulation.Common
{ {
public static class EmulatorExtensions public static class EmulatorExtensions
@ -341,5 +345,17 @@ namespace BizHawk.Emulation.Common
return buttons; return buttons;
} }
public static string FilesystemSafeName(this GameInfo game)
{
var pass1 = game.Name
.Replace('/', '+') // '/' is the path dir separator, obviously (methods in Path will treat it as such, even on Windows)
.Replace('|', '+') // '|' is the filename-member separator for archives in HawkFile
.Replace(":", " -") // ':' is the path separator in lists (Path.GetFileName will drop all but the last entry in such a list)
.Replace("\"", ""); // '"' is just annoying as it needs escaping on the command-line
var filesystemDir = Path.GetDirectoryName(pass1);
var pass2 = Path.GetFileName(pass1).RemoveInvalidFileSystemChars();
return Path.Combine(filesystemDir, pass2.RemoveSuffix('.')); // trailing '.' would be duplicated when file extension is added
}
} }
} }