diff --git a/.gitignore b/.gitignore index e6db76e6f..08d3fe47f 100644 --- a/.gitignore +++ b/.gitignore @@ -7,11 +7,11 @@ StardewInjector/bin/ StardewInjector/obj/ packages/ steamapps/ - + *.symlink *.lnk !*.exe -!*.dll +!*.dll ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. diff --git a/README.md b/README.md index eb21f3794..311c6d0e9 100644 --- a/README.md +++ b/README.md @@ -6,12 +6,15 @@ with the game. It's safely installed alongside the game's executable, and doesn' your game files. ## Contents -* [For players](#for-players) -* [For mod developers](#for-mod-developers) +* **[For players](#for-players)** +* **[For mod developers](#for-mod-developers)** * [For SMAPI developers](#for-smapi-developers) * [Compiling from source](#compiling-from-source) * [Debugging a local build](#debugging-a-local-build) * [Preparing a release](#preparing-a-release) +* [Advanced usage](#advanced-usage) + * [Configuration file](#configuration-file) + * [Command-line arguments](#command-line-arguments) ## For players * [How to install SMAPI & use mods](http://canimod.com/guides/using-mods#installing-smapi) @@ -36,10 +39,10 @@ If you'd like to compile SMAPI from source, you can do that on any platform usin [Visual Studio](https://www.visualstudio.com/vs/community/) or [MonoDevelop](http://www.monodevelop.com/). SMAPI uses build configuration derived from the [crosswiki mod config](https://github.com/Pathoschild/Stardew.ModBuildConfig#readme) to detect your current OS automatically and load the correct references. Compile output will be -placed in a `bin` directory at the root of the git repository. +placed in a `bin` folder at the root of the git repository. ### Debugging a local build -Rebuilding the solution in debug mode will copy the SMAPI files into your game directory. Starting +Rebuilding the solution in debug mode will copy the SMAPI files into your game folder. Starting the `StardewModdingAPI` project with debugging will launch SMAPI with the debugger attached, so you can intercept errors and step through the code being executed. @@ -47,7 +50,7 @@ can intercept errors and step through the code being executed. To prepare a crossplatform SMAPI release, you'll need to compile it on two platforms. See _[crossplatforming a SMAPI mod](http://canimod.com/guides/crossplatforming-a-smapi-mod#preparing-a-mod-release)_ for the first-time setup. For simplicity, all paths are relative to the root of the repository (the -directory containing `src`). +folder containing `src`). 1. Update the version number in `GlobalAssemblyInfo.cs` and `Constants::Version`. Make sure you use a [semantic version](http://semver.org). Recommended format: @@ -61,14 +64,14 @@ directory containing `src`). 2. In Windows: 1. Rebuild the solution in _Release_ mode. 2. Rename `bin/Packaged` to `SMAPI-` (e.g. `SMAPI-1.0`). - 2. Transfer the `SMAPI-` directory to Linux or Mac. + 2. Transfer the `SMAPI-` folder to Linux or Mac. _This adds the installer executable and Windows files. We'll do the rest in Linux or Mac, since we need to set Unix file permissions that Windows won't save._ 2. In Linux or Mac: 1. Rebuild the solution in _Release_ mode. - 2. Copy `bin/Packaged/Mono` into the `SMAPI-` directory. - 3. If you did everything right so far, you should have a directory like this: + 2. Copy `bin/Packaged/Mono` into the `SMAPI-` folder. + 3. If you did everything right so far, you should have a folder like this: ``` SMAPI-1.x/ @@ -101,10 +104,29 @@ directory containing `src`). install.exe readme.txt ``` - 4. Open a terminal in the `SMAPI-` directory and run `chmod 755 Mono/StardewModdingAPI`. - 5. Copy & paste the `SMAPI-` directory as `SMAPI--for-developers`. - 6. In the `SMAPI-` directory, delete the following files: + 4. Open a terminal in the `SMAPI-` folder and run `chmod 755 Mono/StardewModdingAPI`. + 5. Copy & paste the `SMAPI-` folder as `SMAPI--for-developers`. + 6. In the `SMAPI-` folder, delete the following files: * `Mono/StardewModdingAPI.config.json` * `Windows/StardewModdingAPI.config.json` * `Windows/StardewModdingAPI.xml` - 7. Compress the two folders into `SMAPI-.zip` and `SMAPI--for-developers.zip`. \ No newline at end of file + 7. Compress the two folders into `SMAPI-.zip` and `SMAPI--for-developers.zip`. + +## Advanced usage +### Configuration file +You can customise the SMAPI behaviour by editing the `StardewModdingAPI.config.json` file in your +game folder. If it's missing, it'll be generated automatically next time SMAPI runs. It contains +these fields: + +field | purpose +----- | ------- +`DeveloperMode` | Default `false` (except in _SMAPI for developers_ releases). Whether to enable features intended for mod developers. Currently this only makes `TRACE`-level messages appear in the console. +`CheckForUpdates` | Default `true`. Whether SMAPI should check for a newer version when you load the game. If a new version is available, a small message will appear in the console. This doesn't affect the load time even if your connection is offline or slow, because it happens in the background. + +### Command-line arguments +SMAPI recognises the following command-line arguments. These are intended for internal use and may +change without warning. + +argument | purpose +-------- | ------- +`--no-terminal` | SMAPI won't write anything to the console window. (Messages will still be written to the log file.) \ No newline at end of file diff --git a/release-notes.md b/release-notes.md index a11d9ea88..6945a71ac 100644 --- a/release-notes.md +++ b/release-notes.md @@ -1,5 +1,30 @@ # Release notes +## 1.6 +See [log](https://github.com/Pathoschild/SMAPI/compare/1.5...1.6). + +For players: +* Added console commands to open the game/data folders. +* Updated list of incompatible mods. +* Fixed `config.json` values being duplicated in some cases. +* Fixed some Linux users not being able to launch SMAPI from Steam. +* Fixed the installer not finding custom install paths on 32-bit Windows. +* Fixed error when loading a mod which was released with a `.cache` folder for a different platform. +* Fixed error when the console doesn't support colour. +* Fixed error when a mod reads a custom JSON file from a directory that doesn't exist. + +For mod developers: +* Added three events: `SaveEvents.BeforeSave`, `SaveEvents.AfterSave`, and `SaveEvents.AfterLoad`. +* Deprecated three events: + * `TimeEvents.OnNewDay` is unreliable; use `TimeEvents.DayOfMonthChanged` or `SaveEvents` instead. + * `PlayerEvents.LoadedGame` is replaced by `SaveEvents.AfterLoad`. + * `PlayerEvents.FarmerChanged` serves no purpose. + +For SMAPI developers: + * Added support for specifying a lower bound in mod incompatibility data. + * Added support for custom incompatible-mod error text. + * Fixed issue where `TrainerMod` used older logic to detect the game path. + ## 1.5 See [log](https://github.com/Pathoschild/SMAPI/compare/1.4...1.5). diff --git a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs index 5f89caf2a..ef813eb32 100644 --- a/src/StardewModdingAPI.Installer/InteractiveInstaller.cs +++ b/src/StardewModdingAPI.Installer/InteractiveInstaller.cs @@ -77,6 +77,9 @@ private IEnumerable DefaultInstallPaths "StardewModdingAPI-settings.json" // 1.0-1.4 }; + /// Whether the current console supports color formatting. + private static readonly bool ConsoleSupportsColor = InteractiveInstaller.GetConsoleSupportsColor(); + /********* ** Public methods @@ -253,18 +256,18 @@ public void Run(string[] args) /**** ** exit ****/ - Console.ForegroundColor = ConsoleColor.DarkGreen; - Console.WriteLine("Done!"); + this.PrintColor("Done!", ConsoleColor.DarkGreen); if (platform == Platform.Windows) { - Console.WriteLine(action == ScriptAction.Install - ? "Don't forget to launch StardewModdingAPI.exe instead of the normal game executable. See the readme.txt for details." - : "If you manually changed shortcuts or Steam to launch SMAPI, don't forget to change those back." + this.PrintColor( + action == ScriptAction.Install + ? "Don't forget to launch StardewModdingAPI.exe instead of the normal game executable. See the readme.txt for details." + : "If you manually changed shortcuts or Steam to launch SMAPI, don't forget to change those back.", + ConsoleColor.DarkGreen ); } else if (action == ScriptAction.Install) - Console.WriteLine("You can launch the game the same way as before to play with mods."); - Console.ResetColor(); + this.PrintColor("You can launch the game the same way as before to play with mods.", ConsoleColor.DarkGreen); Console.ReadKey(); } @@ -287,6 +290,20 @@ private Platform DetectPlatform() } } + /// Test whether the current console supports color formatting. + private static bool GetConsoleSupportsColor() + { + try + { + Console.ForegroundColor = Console.ForegroundColor; + return true; + } + catch (Exception) + { + return false; // Mono bug + } + } + #if SMAPI_FOR_WINDOWS /// Get the value of a key in the Windows registry. /// The full path of the registry key relative to HKLM. @@ -306,30 +323,39 @@ private string GetLocalMachineRegistryValue(string key, string name) /// The text to print. private void PrintDebug(string text) { - Console.ForegroundColor = ConsoleColor.DarkGray; - Console.WriteLine(text); - Console.ResetColor(); + this.PrintColor(text, ConsoleColor.DarkGray); } /// Print a warning message. /// The text to print. private void PrintWarning(string text) { - Console.ForegroundColor = ConsoleColor.DarkYellow; - Console.WriteLine(text); - Console.ResetColor(); + this.PrintColor(text, ConsoleColor.DarkYellow); } /// Print an error and pause the console if needed. /// The error text. private void ExitError(string error) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine(error); - Console.ResetColor(); + this.PrintColor(error, ConsoleColor.Red); Console.ReadLine(); } + /// Print a message to the console. + /// The message text. + /// The text foreground color. + private void PrintColor(string text, ConsoleColor color) + { + if (InteractiveInstaller.ConsoleSupportsColor) + { + Console.ForegroundColor = color; + Console.WriteLine(text); + Console.ResetColor(); + } + else + Console.WriteLine(text); + } + /// Interactively ask the user to choose a value. /// The message to print. /// The allowed options (not case sensitive). diff --git a/src/StardewModdingAPI.sln b/src/StardewModdingAPI.sln index 6e13b16b4..7229cf307 100644 --- a/src/StardewModdingAPI.sln +++ b/src/StardewModdingAPI.sln @@ -41,11 +41,13 @@ Global {28480467-1A48-46A7-99F8-236D95225359}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Debug|x86.ActiveCfg = Debug|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Debug|x86.Build.0 = Debug|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Release|Any CPU.ActiveCfg = Release|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Release|Any CPU.Build.0 = Release|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Release|Mixed Platforms.Build.0 = Release|Any CPU {28480467-1A48-46A7-99F8-236D95225359}.Release|x86.ActiveCfg = Release|Any CPU + {28480467-1A48-46A7-99F8-236D95225359}.Release|x86.Build.0 = Release|Any CPU {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU {F1A573B0-F436-472C-AE29-0B91EA6B9F8F}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 diff --git a/src/StardewModdingAPI/Events/PlayerEvents.cs b/src/StardewModdingAPI/Events/PlayerEvents.cs index 3f301b071..dd3ff2208 100644 --- a/src/StardewModdingAPI/Events/PlayerEvents.cs +++ b/src/StardewModdingAPI/Events/PlayerEvents.cs @@ -14,9 +14,11 @@ public static class PlayerEvents ** Events *********/ /// Raised after the player loads a saved game. + [Obsolete("Use " + nameof(SaveEvents) + "." + nameof(SaveEvents.AfterLoad) + " instead")] public static event EventHandler LoadedGame; /// Raised after the game assigns a new player character. This happens just before ; it's unclear how this would happen any other time. + [Obsolete("should no longer be used")] public static event EventHandler FarmerChanged; /// Raised after the player's inventory changes in any way (added or removed item, sorted, etc). @@ -34,7 +36,14 @@ public static class PlayerEvents /// Whether the save has been loaded. This is always true. internal static void InvokeLoadedGame(IMonitor monitor, EventArgsLoadedGameChanged loaded) { - monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}", PlayerEvents.LoadedGame?.GetInvocationList(), null, loaded); + if (PlayerEvents.LoadedGame == null) + return; + + string name = $"{nameof(PlayerEvents)}.{nameof(PlayerEvents.LoadedGame)}"; + Delegate[] handlers = PlayerEvents.LoadedGame.GetInvocationList(); + + Program.DeprecationManager.WarnForEvent(handlers, name, "1.6", DeprecationLevel.Notice); + monitor.SafelyRaiseGenericEvent(name, handlers, null, loaded); } /// Raise a event. @@ -43,7 +52,14 @@ internal static void InvokeLoadedGame(IMonitor monitor, EventArgsLoadedGameChang /// The new player character. internal static void InvokeFarmerChanged(IMonitor monitor, Farmer priorFarmer, Farmer newFarmer) { - monitor.SafelyRaiseGenericEvent($"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}", PlayerEvents.FarmerChanged?.GetInvocationList(), null, new EventArgsFarmerChanged(priorFarmer, newFarmer)); + if (PlayerEvents.FarmerChanged == null) + return; + + string name = $"{nameof(PlayerEvents)}.{nameof(PlayerEvents.FarmerChanged)}"; + Delegate[] handlers = PlayerEvents.FarmerChanged.GetInvocationList(); + + Program.DeprecationManager.WarnForEvent(handlers, name, "1.6", DeprecationLevel.Notice); + monitor.SafelyRaiseGenericEvent(name, handlers, null, new EventArgsFarmerChanged(priorFarmer, newFarmer)); } /// Raise an event. diff --git a/src/StardewModdingAPI/Events/SaveEvents.cs b/src/StardewModdingAPI/Events/SaveEvents.cs new file mode 100644 index 000000000..2921003a5 --- /dev/null +++ b/src/StardewModdingAPI/Events/SaveEvents.cs @@ -0,0 +1,46 @@ +using System; +using StardewModdingAPI.Framework; + +namespace StardewModdingAPI.Events +{ + /// Events raised before and after the player saves/loads the game. + public static class SaveEvents + { + /********* + ** Events + *********/ + /// Raised before the game begins writes data to the save file. + public static event EventHandler BeforeSave; + + /// Raised after the game finishes writing data to the save file. + public static event EventHandler AfterSave; + + /// Raised after the player loads a save slot. + public static event EventHandler AfterLoad; + + + /********* + ** Internal methods + *********/ + /// Raise a event. + /// Encapsulates monitoring and logging. + internal static void InvokeBeforeSave(IMonitor monitor) + { + monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.BeforeSave)}", SaveEvents.BeforeSave?.GetInvocationList(), null, EventArgs.Empty); + } + + /// Raise a event. + /// Encapsulates monitoring and logging. + internal static void InvokeAfterSave(IMonitor monitor) + { + monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.AfterSave)}", SaveEvents.AfterSave?.GetInvocationList(), null, EventArgs.Empty); + } + + /// Raise a event. + /// Encapsulates monitoring and logging. + internal static void InvokeAfterLoad(IMonitor monitor) + { + monitor.SafelyRaisePlainEvent($"{nameof(SaveEvents)}.{nameof(SaveEvents.AfterLoad)}", SaveEvents.AfterLoad?.GetInvocationList(), null, EventArgs.Empty); + } + } +} diff --git a/src/StardewModdingAPI/Events/TimeEvents.cs b/src/StardewModdingAPI/Events/TimeEvents.cs index 1b367230a..dedd7e775 100644 --- a/src/StardewModdingAPI/Events/TimeEvents.cs +++ b/src/StardewModdingAPI/Events/TimeEvents.cs @@ -22,6 +22,7 @@ public static class TimeEvents public static event EventHandler SeasonOfYearChanged; /// Raised when the player is transitioning to a new day and the game is performing its day update logic. This event is triggered twice: once after the game starts transitioning, and again after it finishes. + [Obsolete("Use " + nameof(TimeEvents) + "." + nameof(DayOfMonthChanged) + " or " + nameof(SaveEvents) + " instead")] public static event EventHandler OnNewDay; @@ -71,7 +72,14 @@ internal static void InvokeSeasonOfYearChanged(IMonitor monitor, string priorSea /// Whether the game just started the transition (true) or finished it (false). internal static void InvokeOnNewDay(IMonitor monitor, int priorDay, int newDay, bool isTransitioning) { - monitor.SafelyRaiseGenericEvent($"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}", TimeEvents.OnNewDay?.GetInvocationList(), null, new EventArgsNewDay(priorDay, newDay, isTransitioning)); + if (TimeEvents.OnNewDay == null) + return; + + string name = $"{nameof(TimeEvents)}.{nameof(TimeEvents.OnNewDay)}"; + Delegate[] handlers = TimeEvents.OnNewDay.GetInvocationList(); + + Program.DeprecationManager.WarnForEvent(handlers, name, "1.6", DeprecationLevel.Notice); + monitor.SafelyRaiseGenericEvent(name, handlers, null, new EventArgsNewDay(priorDay, newDay, isTransitioning)); } } } diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs index a747eaa86..4c3b86fef 100644 --- a/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs +++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs @@ -1,4 +1,5 @@ using System.IO; +using StardewModdingAPI.AssemblyRewriters; namespace StardewModdingAPI.Framework.AssemblyRewriting { @@ -14,6 +15,12 @@ internal class CacheEntry /// The SMAPI version used to rewrite the assembly. public readonly string ApiVersion; + /// The target platform. + public readonly Platform Platform; + + /// The value for the machine used to rewrite the assembly. + public readonly string MachineName; + /// Whether to use the cached assembly instead of the original assembly. public readonly bool UseCachedAssembly; @@ -24,11 +31,15 @@ internal class CacheEntry /// Construct an instance. /// The MD5 hash for the original assembly. /// The SMAPI version used to rewrite the assembly. + /// The target platform. + /// The value for the machine used to rewrite the assembly. /// Whether to use the cached assembly instead of the original assembly. - public CacheEntry(string hash, string apiVersion, bool useCachedAssembly) + public CacheEntry(string hash, string apiVersion, Platform platform, string machineName, bool useCachedAssembly) { this.Hash = hash; this.ApiVersion = apiVersion; + this.Platform = platform; + this.MachineName = machineName; this.UseCachedAssembly = useCachedAssembly; } @@ -36,10 +47,14 @@ public CacheEntry(string hash, string apiVersion, bool useCachedAssembly) /// The paths for the cached assembly. /// The MD5 hash of the original assembly. /// The current SMAPI version. - public bool IsUpToDate(CachePaths paths, string hash, ISemanticVersion currentVersion) + /// The target platform. + /// The value for the machine reading the assembly. + public bool IsUpToDate(CachePaths paths, string hash, ISemanticVersion currentVersion, Platform platform, string machineName) { return hash == this.Hash && this.ApiVersion == currentVersion.ToString() + && this.Platform == platform + && this.MachineName == machineName && (!this.UseCachedAssembly || File.Exists(paths.Assembly)); } } diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs index 415785d98..c4bd2d353 100644 --- a/src/StardewModdingAPI/Framework/InternalExtensions.cs +++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs @@ -86,5 +86,26 @@ public static string GetLogSummary(this Exception exception) // anything else return exception.ToString(); } + + /**** + ** Deprecation + ****/ + /// Log a deprecation warning for mods using an event. + /// The deprecation manager to extend. + /// The event handlers. + /// A noun phrase describing what is deprecated. + /// The SMAPI version which deprecated it. + /// How deprecated the code is. + public static void WarnForEvent(this DeprecationManager deprecationManager, Delegate[] handlers, string nounPhrase, string version, DeprecationLevel severity) + { + if (handlers == null || !handlers.Any()) + return; + + foreach (Delegate handler in handlers) + { + string modName = Program.ModRegistry.GetModFrom(handler) ?? "an unknown mod"; // suppress stack trace for unknown mods, not helpful here + deprecationManager.Warn(modName, nounPhrase, version, severity); + } + } } } diff --git a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs index a2c4ac234..e4760398f 100644 --- a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs +++ b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs @@ -29,6 +29,8 @@ internal class ModAssemblyLoader /// Encapsulates monitoring and logging. private readonly IMonitor Monitor; + /// The current game platform. + private readonly Platform TargetPlatform; /********* ** Public methods @@ -40,6 +42,7 @@ internal class ModAssemblyLoader public ModAssemblyLoader(string cacheDirName, Platform targetPlatform, IMonitor monitor) { this.CacheDirName = cacheDirName; + this.TargetPlatform = targetPlatform; this.Monitor = monitor; this.AssemblyMap = Constants.GetAssemblyMap(targetPlatform); this.AssemblyTypeRewriter = new AssemblyTypeRewriter(this.AssemblyMap, monitor); @@ -58,7 +61,7 @@ public RewriteResult ProcessAssemblyUnlessCached(string assemblyPath) CachePaths cachePaths = this.GetCachePaths(assemblyPath); { CacheEntry cacheEntry = File.Exists(cachePaths.Metadata) ? JsonConvert.DeserializeObject(File.ReadAllText(cachePaths.Metadata)) : null; - if (cacheEntry != null && cacheEntry.IsUpToDate(cachePaths, hash, Constants.ApiVersion)) + if (cacheEntry != null && cacheEntry.IsUpToDate(cachePaths, hash, Constants.ApiVersion, this.TargetPlatform, Environment.MachineName)) return new RewriteResult(assemblyPath, cachePaths, assemblyBytes, cacheEntry.Hash, cacheEntry.UseCachedAssembly, isNewerThanCache: false); // no rewrite needed } this.Monitor.Log($"Preprocessing {Path.GetFileName(assemblyPath)} for compatibility...", LogLevel.Trace); @@ -99,7 +102,7 @@ public void WriteCache(IEnumerable results, bool forceCacheAssemb // cache all results foreach (RewriteResult result in results) { - CacheEntry cacheEntry = new CacheEntry(result.Hash, Constants.ApiVersion.ToString(), forceCacheAssemblies || result.UseCachedAssembly); + CacheEntry cacheEntry = new CacheEntry(result.Hash, Constants.ApiVersion.ToString(), this.TargetPlatform, Environment.MachineName, forceCacheAssemblies || result.UseCachedAssembly); File.WriteAllText(result.CachePaths.Metadata, JsonConvert.SerializeObject(cacheEntry)); if (forceCacheAssemblies || result.UseCachedAssembly) File.WriteAllBytes(result.CachePaths.Assembly, result.AssemblyBytes); diff --git a/src/StardewModdingAPI/Framework/ModRegistry.cs b/src/StardewModdingAPI/Framework/ModRegistry.cs index b593142d7..51ec7123b 100644 --- a/src/StardewModdingAPI/Framework/ModRegistry.cs +++ b/src/StardewModdingAPI/Framework/ModRegistry.cs @@ -36,6 +36,34 @@ public IEnumerable GetMods() return (from mod in this.Mods select mod); } + /// Get the friendly mod name which handles a delegate. + /// The delegate to follow. + /// Returns the mod name, or null if the delegate isn't implemented by a known mod. + public string GetModFrom(Delegate @delegate) + { + return @delegate?.Target != null + ? this.GetModFrom(@delegate.Target.GetType()) + : null; + } + + /// Get the friendly mod name which defines a type. + /// The type to check. + /// Returns the mod name, or null if the type isn't part of a known mod. + public string GetModFrom(Type type) + { + // null + if (type == null) + return null; + + // known type + string assemblyName = type.Assembly.FullName; + if (this.ModNamesByAssembly.ContainsKey(assemblyName)) + return this.ModNamesByAssembly[assemblyName]; + + // not found + return null; + } + /// Get the friendly name for the closest assembly registered as a source of deprecation warnings. /// Returns the source name, or null if no registered assemblies were found. public string GetModFromStack() @@ -49,16 +77,10 @@ public string GetModFromStack() // search stack for a source assembly foreach (StackFrame frame in frames) { - // get assembly name MethodBase method = frame.GetMethod(); - Type type = method.ReflectedType; - if (type == null) - continue; - string assemblyName = type.Assembly.FullName; - - // get name if it's a registered source - if (this.ModNamesByAssembly.ContainsKey(assemblyName)) - return this.ModNamesByAssembly[assemblyName]; + string name = this.GetModFrom(method.ReflectedType); + if (name != null) + return name; } // no known assembly found diff --git a/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs b/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs index 9bf06552b..bcf5639c9 100644 --- a/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs +++ b/src/StardewModdingAPI/Framework/Models/IncompatibleMod.cs @@ -14,8 +14,11 @@ internal class IncompatibleMod /// The mod name. public string Name { get; set; } + /// The oldest incompatible mod version, or null for all past versions. + public string LowerVersion { get; set; } + /// The most recent incompatible mod version. - public string Version { get; set; } + public string UpperVersion { get; set; } /// The URL the user can check for an official updated version. public string UpdateUrl { get; set; } @@ -23,9 +26,13 @@ internal class IncompatibleMod /// The URL the user can check for an unofficial updated version. public string UnofficialUpdateUrl { get; set; } - /// A regular expression matching version strings to consider compatible, even if they technically precede . + /// A regular expression matching version strings to consider compatible, even if they technically precede . public string ForceCompatibleVersion { get; set; } + /// The reason phrase to show in the warning, or null to use the default value. + /// "this version is incompatible with the latest version of the game" + public string ReasonPhrase { get; set; } + /********* ** Public methods @@ -34,14 +41,17 @@ internal class IncompatibleMod /// The current version of the matching mod. public bool IsCompatible(ISemanticVersion version) { - ISemanticVersion incompatibleVersion = new SemanticVersion(this.Version); + ISemanticVersion lowerVersion = this.LowerVersion != null ? new SemanticVersion(this.LowerVersion) : null; + ISemanticVersion upperVersion = new SemanticVersion(this.UpperVersion); - // allow newer versions - if (version.IsNewerThan(incompatibleVersion)) + // ignore versions not in range + if (lowerVersion != null && version.IsOlderThan(lowerVersion)) + return true; + if (version.IsNewerThan(upperVersion)) return true; // allow versions matching override return !string.IsNullOrWhiteSpace(this.ForceCompatibleVersion) && Regex.IsMatch(version.ToString(), this.ForceCompatibleVersion, RegexOptions.IgnoreCase); } } -} \ No newline at end of file +} diff --git a/src/StardewModdingAPI/Framework/Monitor.cs b/src/StardewModdingAPI/Framework/Monitor.cs index cf46a474b..39b567d88 100644 --- a/src/StardewModdingAPI/Framework/Monitor.cs +++ b/src/StardewModdingAPI/Framework/Monitor.cs @@ -34,9 +34,15 @@ internal class Monitor : IMonitor /********* ** Accessors *********/ + /// Whether the current console supports color codes. + internal static readonly bool ConsoleSupportsColor = Monitor.GetConsoleSupportsColor(); + /// Whether to show trace messages in the console. internal bool ShowTraceInConsole { get; set; } + /// Whether to write anything to the console. This should be disabled if no console is available. + internal bool WriteToConsole { get; set; } = true; + /********* ** Public methods @@ -108,13 +114,32 @@ private void LogImpl(string source, string message, ConsoleColor color, LogLevel message = $"[{DateTime.Now:HH:mm:ss} {levelStr} {source}] {message}"; // log - if (this.ShowTraceInConsole || level != LogLevel.Trace) + if (this.WriteToConsole && (this.ShowTraceInConsole || level != LogLevel.Trace)) { - Console.ForegroundColor = color; - Console.WriteLine(message); - Console.ResetColor(); + if (Monitor.ConsoleSupportsColor) + { + Console.ForegroundColor = color; + Console.WriteLine(message); + Console.ResetColor(); + } + else + Console.WriteLine(message); } this.LogFile.WriteLine(message); } + + /// Test whether the current console supports color formatting. + private static bool GetConsoleSupportsColor() + { + try + { + Console.ForegroundColor = Console.ForegroundColor; + return true; + } + catch (Exception) + { + return false; // Mono bug + } + } } } \ No newline at end of file diff --git a/src/StardewModdingAPI/Inheritance/SGame.cs b/src/StardewModdingAPI/Inheritance/SGame.cs index 16803a73b..8e87bac6e 100644 --- a/src/StardewModdingAPI/Inheritance/SGame.cs +++ b/src/StardewModdingAPI/Inheritance/SGame.cs @@ -913,10 +913,17 @@ private void UpdateEventCalls() // raise menu changed if (Game1.activeClickableMenu != this.PreviousActiveMenu) { - // raise events IClickableMenu previousMenu = this.PreviousActiveMenu; IClickableMenu newMenu = Game1.activeClickableMenu; - if (Game1.activeClickableMenu != null) + + // raise save events + if (newMenu is SaveGameMenu) + SaveEvents.InvokeBeforeSave(this.Monitor); + else if (previousMenu is SaveGameMenu) + SaveEvents.InvokeAfterSave(this.Monitor); + + // raise menu events + if (newMenu != null) MenuEvents.InvokeMenuChanged(this.Monitor, previousMenu, newMenu); else MenuEvents.InvokeMenuClosed(this.Monitor, previousMenu); @@ -1024,6 +1031,7 @@ private void UpdateEventCalls() // raise player loaded save (in the following tick to let the game finish updating first) if (this.FireLoadedGameEvent) { + SaveEvents.InvokeAfterLoad(this.Monitor); PlayerEvents.InvokeLoadedGame(this.Monitor, new EventArgsLoadedGameChanged(Game1.hasLoadedGame)); this.FireLoadedGameEvent = false; } diff --git a/src/StardewModdingAPI/LogWriter.cs b/src/StardewModdingAPI/LogWriter.cs index 058fa649a..9c2ef515f 100644 --- a/src/StardewModdingAPI/LogWriter.cs +++ b/src/StardewModdingAPI/LogWriter.cs @@ -42,9 +42,14 @@ public void WriteToLog(LogInfo message) string output = $"[{message.LogTime}] {message.Message}"; if (message.PrintConsole) { - Console.ForegroundColor = message.Colour; - Console.WriteLine(message); - Console.ForegroundColor = ConsoleColor.Gray; + if (Monitor.ConsoleSupportsColor) + { + Console.ForegroundColor = message.Colour; + Console.WriteLine(message); + Console.ResetColor(); + } + else + Console.WriteLine(message); } this.LogFile.WriteLine(output); } diff --git a/src/StardewModdingAPI/Manifest.cs b/src/StardewModdingAPI/Manifest.cs index 018b31aea..07dd35413 100644 --- a/src/StardewModdingAPI/Manifest.cs +++ b/src/StardewModdingAPI/Manifest.cs @@ -8,6 +8,7 @@ namespace StardewModdingAPI internal class ManifestImpl : Manifest, IManifest { /// The mod version. + [JsonProperty("Version", ObjectCreationHandling = ObjectCreationHandling.Auto/* avoids issue where Json.NET can't determine concrete type for interface */)] public new ISemanticVersion Version { get { return base.Version; } diff --git a/src/StardewModdingAPI/ModHelper.cs b/src/StardewModdingAPI/ModHelper.cs index 1fcc01820..78b3eefa8 100644 --- a/src/StardewModdingAPI/ModHelper.cs +++ b/src/StardewModdingAPI/ModHelper.cs @@ -10,6 +10,17 @@ namespace StardewModdingAPI [Obsolete("Use " + nameof(IModHelper) + " instead.")] // only direct mod access to this class is obsolete public class ModHelper : IModHelper { + /********* + ** Properties + *********/ + /// The JSON settings to use when serialising and deserialising files. + private readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + ObjectCreationHandling = ObjectCreationHandling.Replace // avoid issue where default ICollection values are duplicated each time the config is loaded + }; + + /********* ** Accessors *********/ @@ -76,13 +87,13 @@ public TModel ReadJsonFile(string path) { json = File.ReadAllText(fullPath); } - catch (FileNotFoundException) + catch (Exception ex) when (ex is DirectoryNotFoundException || ex is FileNotFoundException) { return null; } // deserialise model - TModel model = JsonConvert.DeserializeObject(json); + TModel model = JsonConvert.DeserializeObject(json, this.JsonSettings); if (model is IConfigFile) { var wrapper = (IConfigFile)model; @@ -108,7 +119,7 @@ public void WriteJsonFile(string path, TModel model) Directory.CreateDirectory(dir); // write file - string json = JsonConvert.SerializeObject(model, Formatting.Indented); + string json = JsonConvert.SerializeObject(model, this.JsonSettings); File.WriteAllText(path, json); } } diff --git a/src/StardewModdingAPI/Program.cs b/src/StardewModdingAPI/Program.cs index 090098ca1..e5c27e717 100644 --- a/src/StardewModdingAPI/Program.cs +++ b/src/StardewModdingAPI/Program.cs @@ -93,12 +93,14 @@ public class Program ** Public methods *********/ /// The main entry point which hooks into and launches the game. - private static void Main() + /// The command-line arguments. + private static void Main(string[] args) { - // set thread culture for consistent log formatting - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); + // set log options + Program.Monitor.WriteToConsole = !args.Contains("--no-terminal"); + Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); // for consistent log formatting - // add info header + // add info headers Program.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Game1.version} on {Environment.OSVersion}", LogLevel.Info); // initialise user settings @@ -123,9 +125,11 @@ private static void Main() } if (!Program.Settings.CheckForUpdates) Program.Monitor.Log($"You configured SMAPI to not check for updates. Running an old version of SMAPI is not recommended. You can enable update checks by editing or deleting {Constants.ApiConfigPath}.", LogLevel.Warn); + if (!Program.Monitor.WriteToConsole) + Program.Monitor.Log($"Writing to the terminal is disabled because the --no-terminal argument was received. This usually means launching the terminal failed.", LogLevel.Warn); // initialise legacy log - Log.Monitor = new Monitor("legacy mod", Program.LogFile) { ShowTraceInConsole = Program.Settings.DeveloperMode }; + Log.Monitor = Program.GetSecondaryMonitor("legacy mod"); Log.ModRegistry = Program.ModRegistry; // hook into & launch the game @@ -183,7 +187,7 @@ internal static void ExitGameImmediately(string module, string reason) internal static IMonitor GetLegacyMonitorForMod() { string modName = Program.ModRegistry.GetModFromStack() ?? "unknown"; - return new Monitor(modName, Program.LogFile); + return Program.GetSecondaryMonitor(modName); } @@ -398,7 +402,8 @@ private static void LoadMods() { if (!compatibility.IsCompatible(manifest.Version)) { - string warning = $"Skipped {compatibility.Name} ≤v{compatibility.Version} because this version is not compatible with the latest version of the game. Please check for a newer version of the mod here:"; + string reasonPhrase = compatibility.ReasonPhrase ?? "this version is not compatible with the latest version of the game"; + string warning = $"Skipped {compatibility.Name} {manifest.Version} because {reasonPhrase}. Please check for a newer version of the mod here:"; if (!string.IsNullOrWhiteSpace(compatibility.UpdateUrl)) warning += $"{Environment.NewLine}- official mod: {compatibility.UpdateUrl}"; if (!string.IsNullOrWhiteSpace(compatibility.UnofficialUpdateUrl)) @@ -518,7 +523,7 @@ private static void LoadMods() // inject data mod.ModManifest = manifest; mod.Helper = helper; - mod.Monitor = new Monitor(manifest.Name, Program.LogFile) { ShowTraceInConsole = Program.Settings.DeveloperMode }; + mod.Monitor = Program.GetSecondaryMonitor(manifest.Name); mod.PathOnDisk = directory; // track mod @@ -590,5 +595,12 @@ private static void PressAnyKeyToExit() Console.ReadKey(); Environment.Exit(0); } + + /// Get a monitor instance derived from SMAPI's current settings. + /// The name of the module which will log messages with this instance. + private static Monitor GetSecondaryMonitor(string name) + { + return new Monitor(name, Program.LogFile) { WriteToConsole = Program.Monitor.WriteToConsole, ShowTraceInConsole = Program.Settings.DeveloperMode }; + } } } diff --git a/src/StardewModdingAPI/StardewModdingAPI.csproj b/src/StardewModdingAPI/StardewModdingAPI.csproj index 07b1ff5e5..125f287e3 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.csproj +++ b/src/StardewModdingAPI/StardewModdingAPI.csproj @@ -152,6 +152,7 @@ + diff --git a/src/StardewModdingAPI/StardewModdingAPI.data.json b/src/StardewModdingAPI/StardewModdingAPI.data.json index 49b450189..3295336fa 100644 --- a/src/StardewModdingAPI/StardewModdingAPI.data.json +++ b/src/StardewModdingAPI/StardewModdingAPI.data.json @@ -6,18 +6,19 @@ This file contains advanced metadata for SMAPI. You shouldn't change this file. */ [ + /* versions not compatible with Stardew Valley 1.1+ */ { "ID": "SPDSprinklersMod", "Name": "Better Sprinklers", - "Version": "2.1", + "UpperVersion": "2.1", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/41", "UnofficialUpdateUrl": "http://community.playstarbound.com/threads/125031", - "ForceCompatibleVersion": "^2.1-EntoPatch" + "ForceCompatibleVersion": "^2.1-EntoPatch" }, { "ID": "SPDChestLabel", "Name": "Chest Label System", - "Version": "1.5", + "UpperVersion": "1.5", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/242", "UnofficialUpdateUrl": "http://community.playstarbound.com/threads/125031", "ForceCompatibleVersion": "^1.5-EntoPatch" @@ -25,17 +26,25 @@ This file contains advanced metadata for SMAPI. You shouldn't change this file. { "ID": "CJBCheatsMenu", "Name": "CJB Cheats Menu", - "Version": "1.12", + "UpperVersion": "1.12", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/4", - "UnofficialUpdateUrl": "http://community.playstarbound.com/threads/125031", "ForceCompatibleVersion": "^1.12-EntoPatch" }, { "ID": "CJBItemSpawner", "Name": "CJB Item Spawner", - "Version": "1.5", + "UpperVersion": "1.5", "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/93", - "UnofficialUpdateUrl": "http://community.playstarbound.com/threads/125031", "ForceCompatibleVersion": "^1.5-EntoPatch" + }, + + /* versions which crash the game */ + { + "ID": "NPCMapLocationsMod", + "Name": "NPC Map Locations", + "LowerVersion": "1.42", + "UpperVersion": "1.43", + "UpdateUrl": "http://www.nexusmods.com/stardewvalley/mods/239", + "ReasonPhrase": "this version has an update check error which crashes the game" } ] diff --git a/src/StardewModdingAPI/unix-launcher.sh b/src/StardewModdingAPI/unix-launcher.sh index 93e33c78e..bf0e9d5ef 100644 --- a/src/StardewModdingAPI/unix-launcher.sh +++ b/src/StardewModdingAPI/unix-launcher.sh @@ -64,4 +64,12 @@ else else $LAUNCHER fi + + # some Linux users get error 127 (command not found) from the above block, even though + # `command -v` indicates the command is valid. As a fallback, launch SMAPI without a terminal when + # that happens and pass in an argument indicating SMAPI shouldn't try writing to the terminal + # (which can be slow if there is none). + if [ $? -eq 127 ]; then + $LAUNCHER --no-terminal + fi fi diff --git a/src/TrainerMod/TrainerMod.cs b/src/TrainerMod/TrainerMod.cs index f0c7549fb..c76bb78ce 100644 --- a/src/TrainerMod/TrainerMod.cs +++ b/src/TrainerMod/TrainerMod.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using Microsoft.Xna.Framework; using StardewModdingAPI; @@ -108,6 +109,9 @@ private void RegisterCommands() Command.RegisterCommand("world_setseason", "Sets the season to the specified value | world_setseason ", new[] { "(winter, spring, summer, fall) The target season" }).CommandFired += this.HandleWorldSetSeason; Command.RegisterCommand("world_downminelevel", "Goes down one mine level? | world_downminelevel", new[] { "" }).CommandFired += this.HandleWorldDownMineLevel; Command.RegisterCommand("world_setminelevel", "Sets mine level? | world_setminelevel", new[] { "(Int32) The target level" }).CommandFired += this.HandleWorldSetMineLevel; + + Command.RegisterCommand("show_game_files", "Opens the game folder. | show_game_files").CommandFired += this.HandleShowGameFiles; + Command.RegisterCommand("show_data_files", "Opens the folder containing the save and log files. | show_data_files").CommandFired += this.HandleShowDataFiles; } /**** @@ -695,6 +699,22 @@ private void HandleWorldSetMineLevel(object sender, EventArgsCommand e) this.LogValueNotSpecified(); } + /// The event raised when the 'show_game_files' command is triggered. + /// The event sender. + /// The event arguments. + private void HandleShowGameFiles(object sender, EventArgsCommand e) + { + Process.Start(Constants.ExecutionPath); + } + + /// The event raised when the 'show_data_files' command is triggered. + /// The event sender. + /// The event arguments. + private void HandleShowDataFiles(object sender, EventArgsCommand e) + { + Process.Start(Constants.DataPath); + } + /**** ** Helpers ****/ diff --git a/src/TrainerMod/TrainerMod.csproj b/src/TrainerMod/TrainerMod.csproj index e262e1359..1457ac2bf 100644 --- a/src/TrainerMod/TrainerMod.csproj +++ b/src/TrainerMod/TrainerMod.csproj @@ -37,54 +37,6 @@ true x86 - - - $(HOME)/GOG Games/Stardew Valley/game - $(HOME)/.local/share/Steam/steamapps/common/Stardew Valley - - $(HOME)/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS - - C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley - C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley - - - - - - False - - - False - - - $(GamePath)\Stardew Valley.exe - False - - - $(GamePath)\xTile.dll - False - False - - - - - - - $(GamePath)\MonoGame.Framework.dll - False - False - - - $(GamePath)\StardewValley.exe - False - - - $(GamePath)\xTile.dll - False - - - - ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll @@ -123,15 +75,12 @@ + - - - - diff --git a/src/crossplatform.targets b/src/crossplatform.targets index 0eb1c7769..ef2d341f7 100644 --- a/src/crossplatform.targets +++ b/src/crossplatform.targets @@ -8,8 +8,8 @@ C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley - $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 413150@InstallLocation) - $(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GOG.com\Games\1453375253@PATH) + $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\GOG.com\Games\1453375253', 'PATH', null, RegistryView.Registry32)) + $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 413150', 'InstallLocation', null, RegistryView.Registry64, RegistryView.Registry32))