diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 0000000..8c81e05 --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,7 @@ +# All files +[*] +guidelines = 80 + +# C# files +[*.cs] +guidelines = 80, 120 diff --git a/src/AboutDialog.cs b/src/AboutDialog.cs index edf529c..dafd992 100644 --- a/src/AboutDialog.cs +++ b/src/AboutDialog.cs @@ -18,8 +18,7 @@ namespace WinDynamicDesktop public partial class AboutDialog : Form { private static readonly Func _ = Localization.GetTranslation; - private static readonly string websiteLink = - "https://github.com/t1m0thyj/WinDynamicDesktop"; + private static readonly string websiteLink = "https://github.com/t1m0thyj/WinDynamicDesktop"; private static readonly string donateLink = "https://paypal.me/t1m0thyj"; public AboutDialog() @@ -41,8 +40,7 @@ public AboutDialog() websiteLabel.Width = minWidth; } - minWidth = minWidth + (descriptionLabel.Width - minWidth) / 2 + - descriptionLabel.Location.X * 2; + minWidth = minWidth + (descriptionLabel.Width - minWidth) / 2 + descriptionLabel.Location.X * 2; if (this.Size.Width < minWidth) { diff --git a/src/AppContext.cs b/src/AppContext.cs index 565db79..16bb8c0 100644 --- a/src/AppContext.cs +++ b/src/AppContext.cs @@ -66,9 +66,8 @@ private void HandleMultiInstance() } else { - MessageDialog.ShowWarning(_("Another instance of WinDynamicDesktop is " + - "already running. You can access it by clicking on the icon in the " + - "system tray."), _("Error")); + MessageDialog.ShowWarning(_("Another instance of WinDynamicDesktop is already running. You can " + + "access it by clicking on the icon in the system tray."), _("Error")); } Environment.Exit(0); @@ -96,15 +95,13 @@ public static void ShowPopup(string message, string title = null) notifyIcon.ShowBalloonTip(10000); } - private void OnNamedPipeClientMessage(NamedPipeConnection conn, - string message) + private void OnNamedPipeClientMessage(NamedPipeConnection conn, string message) { ThemeManager.importPaths.AddRange(message.Split('|')); if (!ThemeManager.importMode) { - notifyIcon.ContextMenuStrip.BeginInvoke( - new Action(() => ThemeManager.SelectTheme())); + notifyIcon.ContextMenuStrip.BeginInvoke(new Action(() => ThemeManager.SelectTheme())); } } @@ -133,6 +130,7 @@ private void OnApplicationExit(object sender, EventArgs e) } _namedPipe?.Stop(); + _mutex?.Dispose(); } } } diff --git a/src/DebugLogger.cs b/src/DebugLogger.cs index fc47305..b03817e 100644 --- a/src/DebugLogger.cs +++ b/src/DebugLogger.cs @@ -47,8 +47,7 @@ public static void WriteLogFile() if (Directory.Exists("themes")) { - foreach (string path in Directory.EnumerateFiles("themes", "*", - SearchOption.AllDirectories)) + foreach (string path in Directory.EnumerateFiles("themes", "*", SearchOption.AllDirectories)) { debugLog.WriteLine("./" + path.Replace('\\', '/')); diff --git a/src/DefaultThemes.cs b/src/DefaultThemes.cs index 7315cce..0c84d4c 100644 --- a/src/DefaultThemes.cs +++ b/src/DefaultThemes.cs @@ -17,11 +17,11 @@ class DefaultThemes public static string[] GetDefaultThemes() { string yamlText = Encoding.UTF8.GetString(Properties.Resources.default_themes); - yamlLines = yamlText.Split(new[] { Environment.NewLine }, - StringSplitOptions.RemoveEmptyEntries).Select((line) => line.Trim()).ToArray(); + yamlLines = yamlText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) + .Select((line) => line.Trim()).ToArray(); - return yamlLines.Where((line) => !line.StartsWith("-")).Select( - (line) => line.Substring(0, line.Length - 1)).ToArray(); + return yamlLines.Where((line) => !line.StartsWith("-")) + .Select((line) => line.Substring(0, line.Length - 1)).ToArray(); } public static Uri[] GetThemeUriList(string themeId) @@ -31,8 +31,7 @@ public static Uri[] GetThemeUriList(string themeId) while ((startIndex < yamlLines.Length) && yamlLines[startIndex].StartsWith("-")) { - uriList.Add(new Uri(yamlLines[startIndex].Substring( - yamlLines[startIndex].LastIndexOf(" ") + 1))); + uriList.Add(new Uri(yamlLines[startIndex].Substring(yamlLines[startIndex].LastIndexOf(" ") + 1))); startIndex++; } diff --git a/src/DesktopHelper.cs b/src/DesktopHelper.cs index 8f3feb3..9cb0a6f 100644 --- a/src/DesktopHelper.cs +++ b/src/DesktopHelper.cs @@ -15,8 +15,7 @@ namespace WinDynamicDesktop { class DesktopHelper : PlatformHelper { - private const string registryStartupLocation = - @"Software\Microsoft\Windows\CurrentVersion\Run"; + private const string registryStartupLocation = @"Software\Microsoft\Windows\CurrentVersion\Run"; private const string updateLink = "https://github.com/t1m0thyj/WinDynamicDesktop/releases"; private bool startOnBoot; diff --git a/src/DownloadDialog.cs b/src/DownloadDialog.cs index 531f42f..15455ad 100644 --- a/src/DownloadDialog.cs +++ b/src/DownloadDialog.cs @@ -44,8 +44,7 @@ public void InitDownload(ThemeConfig theme) { ThemeManager.downloadMode = true; this.Invoke(new Action(() => - label1.Text = string.Format(_("Downloading images for '{0}'..."), - ThemeManager.GetThemeName(theme)))); + label1.Text = string.Format(_("Downloading images for '{0}'..."), ThemeManager.GetThemeName(theme)))); imagesZipDest = theme.themeId + "_images.zip"; themeUris = DefaultThemes.GetThemeUriList(theme.themeId).ToList(); @@ -70,8 +69,7 @@ private void UpdatePercentage(int percentage) private bool EnsureZipNotHtml() { // Handle case where HTML page gets downloaded instead of ZIP - return (File.Exists(imagesZipDest) && - ((new FileInfo(imagesZipDest)).Length > 1024 * 1024)); + return (File.Exists(imagesZipDest) && ((new FileInfo(imagesZipDest)).Length > 1024 * 1024)); } private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) @@ -104,8 +102,7 @@ public async void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs if ((e.Error == null) && EnsureZipNotHtml()) { cancelButton.Enabled = false; - ThemeResult result = await Task.Run( - () => ThemeLoader.ExtractTheme(imagesZipDest, theme.themeId)); + ThemeResult result = await Task.Run(() => ThemeLoader.ExtractTheme(imagesZipDest, theme.themeId)); result.Match(ThemeLoader.HandleError, newTheme => { int themeIndex = ThemeManager.themeSettings.FindIndex(t => t.themeId == newTheme.themeId); diff --git a/src/DpiHelper.cs b/src/DpiHelper.cs index 1a7d4d0..1e49d05 100644 --- a/src/DpiHelper.cs +++ b/src/DpiHelper.cs @@ -23,10 +23,10 @@ private enum ProcessDpiAwareness private enum DpiAwarenessContext { - DpiAwarenessContextUnaware = -1, - DpiAwarenessContextSystemAware = -2, - DpiAwarenessContextPerMonitorAware = -3, - DpiAwarenessContextPerMonitorAwareV2 = -4 + DpiAwarenessUnaware = -1, + DpiAwarenessSystemAware = -2, + DpiAwarenessPerMonitorAware = -3, + DpiAwarenessPerMonitorAwareV2 = -4 } [DllImport("user32.dll", SetLastError = true)] @@ -38,10 +38,10 @@ private enum DpiAwarenessContext [DllImport("user32.dll")] private static extern bool SetProcessDPIAware(); - [DllImport("kernel32.dll", SetLastError = true)] + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr LoadLibrary(string fileName); - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)] + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); public static void SetDpiAwareness() @@ -51,8 +51,8 @@ public static void SetDpiAwareness() if (method != IntPtr.Zero) { - if (SetProcessDpiAwarenessContext((IntPtr)DpiAwarenessContext.DpiAwarenessContextPerMonitorAwareV2) || - SetProcessDpiAwarenessContext((IntPtr)DpiAwarenessContext.DpiAwarenessContextPerMonitorAware)) + if (SetProcessDpiAwarenessContext((IntPtr)DpiAwarenessContext.DpiAwarenessPerMonitorAwareV2) || + SetProcessDpiAwarenessContext((IntPtr)DpiAwarenessContext.DpiAwarenessPerMonitorAware)) { return; } diff --git a/src/FullScreenApi.cs b/src/FullScreenApi.cs index 8bb9dea..2c69080 100644 --- a/src/FullScreenApi.cs +++ b/src/FullScreenApi.cs @@ -46,16 +46,18 @@ private struct RECT private static extern bool UnhookWinEvent(IntPtr hWinEventHook); [DllImport("user32.dll")] - private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags); + private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, + WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags); private const uint WINEVENT_OUTOFCONTEXT = 0; private const uint EVENT_SYSTEM_FOREGROUND = 3; - private delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime); + private delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, + int idChild, uint dwEventThread, uint dwmsEventTime); public FullScreenApi(WallpaperChangeScheduler wcs) { - timerEventHandler = new Action(() => { wcs.HandleTimerEvent(true); }); + timerEventHandler = new Action(() => wcs.HandleTimerEvent(true)); if (JsonConfig.settings.fullScreenPause) { @@ -76,8 +78,8 @@ private void SetFullScreenPause(bool fullScreenPause) if (fullScreenPause) { winEventProc = new WinEventDelegate(WinEventProc); - winEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, - IntPtr.Zero, winEventProc, 0, 0, WINEVENT_OUTOFCONTEXT); + winEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, + winEventProc, 0, 0, WINEVENT_OUTOFCONTEXT); } else { @@ -109,8 +111,8 @@ private bool IsRunningFullScreen() return false; } - private void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, - int idChild, uint dwEventThread, uint dwmsEventTime) + private void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, + uint dwEventThread, uint dwmsEventTime) { runningFullScreen = IsRunningFullScreen(); diff --git a/src/ImportDialog.cs b/src/ImportDialog.cs index bd5f61f..2cfa276 100644 --- a/src/ImportDialog.cs +++ b/src/ImportDialog.cs @@ -59,8 +59,7 @@ private void ImportNext() { string themePath = importQueue.Peek(); this.Invoke(new Action(() => - label1.Text = string.Format(_("Importing theme from {0}..."), - Path.GetFileName(themePath)))); + label1.Text = string.Format(_("Importing theme from {0}..."), Path.GetFileName(themePath)))); ThemeResult result = ThemeManager.ImportTheme(themePath); result.Match(e => this.Invoke(new Action(() => ThemeLoader.HandleError(e))), diff --git a/src/JsonConfig.cs b/src/JsonConfig.cs index 233b83e..6a406fb 100644 --- a/src/JsonConfig.cs +++ b/src/JsonConfig.cs @@ -87,8 +87,8 @@ public static void LoadConfig() } catch (JsonReaderException) { - MessageDialog.ShowWarning("Your WinDynamicDesktop configuration file was " + - "corrupt and has been reset to the default settings.", "Warning"); + MessageDialog.ShowWarning("Your WinDynamicDesktop configuration file was corrupt and has been " + + "reset to the default settings.", "Warning"); firstRun = true; } } diff --git a/src/LanguageDialog.cs b/src/LanguageDialog.cs index 956c9c0..6b672df 100644 --- a/src/LanguageDialog.cs +++ b/src/LanguageDialog.cs @@ -57,9 +57,8 @@ private void okButton_Click(object sender, EventArgs e) if (AppContext.notifyIcon != null) { - DialogResult result = MessageDialog.ShowQuestion(_("WinDynamicDesktop needs " + - "to restart for the language to change. Do you want to restart the app " + - "now?"), _("Question")); + DialogResult result = MessageDialog.ShowQuestion(_("WinDynamicDesktop needs to restart for the " + + "language to change. Do you want to restart the app now?"), _("Question")); if (result == DialogResult.Yes) { diff --git a/src/LaunchSequence.cs b/src/LaunchSequence.cs index 54eb834..c362544 100644 --- a/src/LaunchSequence.cs +++ b/src/LaunchSequence.cs @@ -18,13 +18,11 @@ public static bool IsLocationReady() { if (!JsonConfig.settings.dontUseLocation) { - return (JsonConfig.settings.latitude != null && - JsonConfig.settings.longitude != null); + return (JsonConfig.settings.latitude != null && JsonConfig.settings.longitude != null); } else { - return (JsonConfig.settings.sunriseTime != null && - JsonConfig.settings.sunsetTime != null); + return (JsonConfig.settings.sunriseTime != null && JsonConfig.settings.sunsetTime != null); } } @@ -42,8 +40,8 @@ public static void NextStep(bool themeReadyOverride = false) if (JsonConfig.firstRun) { - AppContext.ShowPopup(_("Welcome! Please enter your location so the app can " + - "determine sunrise and sunset times.")); + AppContext.ShowPopup(_("Welcome! Please enter your location so the app can determine sunrise and " + + "sunset times.")); } } else if (!IsThemeReady() && !themeReadyOverride) // Override if theme=None chosen @@ -52,8 +50,8 @@ public static void NextStep(bool themeReadyOverride = false) } else if (JsonConfig.firstRun) { - AppContext.ShowPopup(_("The app is still running in the background. You can " + - "access it at any time by clicking on the icon in the system tray.")); + AppContext.ShowPopup(_("The app is still running in the background. You can access it at any time by " + + "clicking on the icon in the system tray.")); JsonConfig.firstRun = false; // Don't show this message again } diff --git a/src/LocationIQ.cs b/src/LocationIQ.cs index b601178..0a30223 100644 --- a/src/LocationIQ.cs +++ b/src/LocationIQ.cs @@ -24,9 +24,8 @@ private static void HandleLocationSuccess(LocationIQData data, ScheduleDialog di JsonConfig.settings.longitude = data.lon; SolarData solarData = SunriseSunsetService.GetSolarData(DateTime.Today); - DialogResult result = MessageDialog.ShowQuestion(string.Format(_("Is this location " + - "correct?\n\n{0}\n{1}"), data.display_name, - SunriseSunsetService.GetSunriseSunsetString(solarData)), _("Question"), true); + DialogResult result = MessageDialog.ShowQuestion(string.Format(_("Is this location correct?\n\n{0}\n{1}"), + data.display_name, SunriseSunsetService.GetSunriseSunsetString(solarData)), _("Question"), true); if (result == DialogResult.Yes) { @@ -54,10 +53,9 @@ public static void GetLocationData(string locationStr, ScheduleDialog dialog) } else { - MessageDialog.ShowWarning(_("The location you entered was invalid, or you " + - "are not connected to the Internet. Check your Internet connection and " + - "try a different location. You can use a complete address or just the " + - "name of your city/region."), _("Error")); + MessageDialog.ShowWarning(_("The location you entered was invalid, or you are not connected to " + + "the Internet. Check your Internet connection and try a different location. You can use a " + + "complete address or just the name of your city/region."), _("Error")); } }); } diff --git a/src/MessageDialog.cs b/src/MessageDialog.cs index 4adda3b..0c1d4cd 100644 --- a/src/MessageDialog.cs +++ b/src/MessageDialog.cs @@ -15,20 +15,16 @@ class MessageDialog { public static DialogResult ShowError(string message, string title = null) { - return MessageBox.Show(message, title ?? "WinDynamicDesktop", MessageBoxButtons.OK, - MessageBoxIcon.Error); + return MessageBox.Show(message, title ?? "WinDynamicDesktop", MessageBoxButtons.OK, MessageBoxIcon.Error); } - public static DialogResult ShowInfo(string message, string title = null, - bool cancelButton = false) + public static DialogResult ShowInfo(string message, string title = null, bool cancelButton = false) { return MessageBox.Show(message, title ?? "WinDynamicDesktop", - cancelButton ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK, - MessageBoxIcon.Information); + cancelButton ? MessageBoxButtons.OKCancel : MessageBoxButtons.OK, MessageBoxIcon.Information); } - public static DialogResult ShowQuestion(string message, string title = null, - bool useWarningIcon = false) + public static DialogResult ShowQuestion(string message, string title = null, bool useWarningIcon = false) { return MessageBox.Show(message, title ?? "WinDynamicDesktop", MessageBoxButtons.YesNo, useWarningIcon ? MessageBoxIcon.Warning : MessageBoxIcon.Question); @@ -36,8 +32,7 @@ public static DialogResult ShowQuestion(string message, string title = null, public static DialogResult ShowWarning(string message, string title = null) { - return MessageBox.Show(message, title ?? "WinDynamicDesktop", MessageBoxButtons.OK, - MessageBoxIcon.Warning); + return MessageBox.Show(message, title ?? "WinDynamicDesktop", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } diff --git a/src/Program.cs b/src/Program.cs index af0adcf..1139ef8 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -22,10 +22,8 @@ static class Program static void Main(string[] args) { string localFolder = UwpDesktop.GetHelper().GetLocalFolder(); - Application.ThreadException += - (sender, e) => OnThreadException(sender, e, localFolder); - AppDomain.CurrentDomain.UnhandledException += - (sender, e) => OnUnhandledException(sender, e, localFolder); + Application.ThreadException += (sender, e) => OnThreadException(sender, e, localFolder); + AppDomain.CurrentDomain.UnhandledException += (sender, e) => OnUnhandledException(sender, e, localFolder); string cwd = localFolder; if (File.Exists(Path.Combine(localFolder, "WinDynamicDesktop.pth"))) @@ -54,23 +52,20 @@ static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e, s static void LogError(string cwd, Exception exc) { string errorMessage = exc.ToString(); - string logFilename = Path.Combine(cwd, - Path.GetFileName(Environment.GetCommandLineArgs()[0]) + ".log"); + string logFilename = Path.Combine(cwd, Path.GetFileName(Environment.GetCommandLineArgs()[0]) + ".log"); try { - string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", - CultureInfo.InvariantCulture); - File.AppendAllText(logFilename, - string.Format("[{0}] {1}\n\n", timestamp, errorMessage)); + string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture); + File.AppendAllText(logFilename, string.Format("[{0}] {1}\n\n", timestamp, errorMessage)); - MessageDialog.ShowError("See the logfile '" + logFilename + "' for details", + MessageDialog.ShowError(string.Format("See the logfile '{0}' for details", logFilename), "Errors occurred"); } catch { - MessageDialog.ShowError("The logfile '" + logFilename + "' could not be " + - "opened:\n " + errorMessage, "Errors occurred"); + MessageDialog.ShowError(string.Format("The logfile '{0}' could not be opened:\n {1}", logFilename, + errorMessage), "Errors occurred"); } } } diff --git a/src/ProxyServer.cs b/src/ProxyServer.cs index f86cc63..919aa13 100644 --- a/src/ProxyServer.cs +++ b/src/ProxyServer.cs @@ -35,8 +35,8 @@ private static WebProxy GetProxy() if (proxyCredentials.Contains("://")) { - string[] schemeAndCredentials = proxyCredentials.Split( - new string[] { "://" }, 2, StringSplitOptions.None); + string[] schemeAndCredentials = proxyCredentials.Split(new string[] { "://" }, 2, + StringSplitOptions.None); proxyAddress = schemeAndCredentials[0] + "://" + proxyAddress; proxyCredentials = schemeAndCredentials[1]; } @@ -61,8 +61,7 @@ private static ICredentials GetCredentials() if (!proxyCredentials.Contains(':')) { - proxyCredentials = Encoding.UTF8.GetString( - Convert.FromBase64String(proxyCredentials)); + proxyCredentials = Encoding.UTF8.GetString(Convert.FromBase64String(proxyCredentials)); } userAndPass = proxyCredentials.Split(new char[] { ':' }, 2); diff --git a/src/ScheduleDialog.cs b/src/ScheduleDialog.cs index 5b3ce17..d7d369a 100644 --- a/src/ScheduleDialog.cs +++ b/src/ScheduleDialog.cs @@ -107,10 +107,8 @@ private void InputDialog_Load(object sender, EventArgs e) if (JsonConfig.settings.sunriseTime != null && JsonConfig.settings.sunsetTime != null) { - sunriseTimePicker.Value = DateTime.Parse(JsonConfig.settings.sunriseTime, - CultureInfo.InvariantCulture); - sunsetTimePicker.Value = DateTime.Parse(JsonConfig.settings.sunsetTime, - CultureInfo.InvariantCulture); + sunriseTimePicker.Value = DateTime.Parse(JsonConfig.settings.sunriseTime, CultureInfo.InvariantCulture); + sunsetTimePicker.Value = DateTime.Parse(JsonConfig.settings.sunsetTime, CultureInfo.InvariantCulture); } else { @@ -178,8 +176,7 @@ private async void okButton_Click(object sender, EventArgs e) { hasLocationPermission = UwpLocation.HasAccess(); UpdateLocationState(); - MessageDialog.ShowWarning(_("Failed to get location from Windows location " + - "service."), _("Error")); + MessageDialog.ShowWarning(_("Failed to get location from Windows location service."), _("Error")); } } else if (radioButton3.Checked) @@ -202,10 +199,9 @@ private void OnFormClosing(object sender, FormClosingEventArgs e) { if (!LaunchSequence.IsLocationReady()) { - DialogResult result = MessageDialog.ShowQuestion(_("WinDynamicDesktop cannot " + - "display wallpapers until you have entered a valid location, so that it can " + - "calculate sunrise and sunset times for your location. Are you sure you " + - "want to cancel and quit the program?"), _("Question"), true); + DialogResult result = MessageDialog.ShowQuestion(_("WinDynamicDesktop cannot display wallpapers " + + "until you have entered a valid location, so that it can calculate sunrise and sunset times for " + + "your location. Are you sure you want to cancel and quit the program?"), _("Question"), true); if (result == DialogResult.Yes) { diff --git a/src/ScriptManager.cs b/src/ScriptManager.cs index 4e9fc1f..848f2f0 100644 --- a/src/ScriptManager.cs +++ b/src/ScriptManager.cs @@ -72,10 +72,9 @@ private static void RunScript(string path, ScriptArgs args) if (ps.Streams.Error.Count > 0) { - MessageDialog.ShowWarning(string.Format( - _("Error(s) running PowerShell script '{0}':\n\n{1}"), path, - string.Join("\n\n", ps.Streams.Error.ReadAll().Select( - (er) => er.Exception.ToString()))), _("Script Error")); + MessageDialog.ShowWarning(string.Format(_("Error(s) running PowerShell script '{0}':\n\n{1}"), path, + string.Join("\n\n", ps.Streams.Error.ReadAll().Select((er) => er.Exception.ToString()))), + _("Script Error")); } } } diff --git a/src/SunriseSunset.cs b/src/SunriseSunset.cs index ea84cc4..dd40bc2 100644 --- a/src/SunriseSunset.cs +++ b/src/SunriseSunset.cs @@ -29,10 +29,9 @@ class SunriseSunsetService private static SolarData GetUserProvidedSolarData() { SolarData data = new SolarData(); - data.sunriseTime = DateTime.Parse(JsonConfig.settings.sunriseTime, - CultureInfo.InvariantCulture); - data.sunsetTime = DateTime.Parse(JsonConfig.settings.sunsetTime, - CultureInfo.InvariantCulture); + data.sunriseTime = DateTime.Parse(JsonConfig.settings.sunriseTime, CultureInfo.InvariantCulture); + data.sunsetTime = DateTime.Parse(JsonConfig.settings.sunsetTime, CultureInfo.InvariantCulture); + int halfSunriseSunsetDuration = JsonConfig.settings.sunriseSunsetDuration * 30; data.solarTimes = new DateTime[4] { @@ -41,20 +40,18 @@ private static SolarData GetUserProvidedSolarData() data.sunsetTime.AddSeconds(-halfSunriseSunsetDuration), data.sunsetTime.AddSeconds(halfSunriseSunsetDuration) }; + return data; } - private static List GetSunPhases(DateTime date, double latitude, - double longitude) + private static List GetSunPhases(DateTime date, double latitude, double longitude) { - return SunCalcNet.SunCalc.GetSunPhases(date.AddHours(12).ToUniversalTime(), - latitude, longitude).ToList(); + return SunCalcNet.SunCalc.GetSunPhases(date.AddHours(12).ToUniversalTime(), latitude, longitude).ToList(); } private static DateTime GetSolarTime(List sunPhases, SunPhaseName desiredPhase) { - return sunPhases.Single(sunPhase => - sunPhase.Name.Value == desiredPhase.Value).PhaseTime.ToLocalTime(); + return sunPhases.Single(sunPhase => sunPhase.Name.Value == desiredPhase.Value).PhaseTime.ToLocalTime(); } public static SolarData GetSolarData(DateTime date) @@ -64,10 +61,8 @@ public static SolarData GetSolarData(DateTime date) return GetUserProvidedSolarData(); } - double latitude = double.Parse(JsonConfig.settings.latitude, - CultureInfo.InvariantCulture); - double longitude = double.Parse(JsonConfig.settings.longitude, - CultureInfo.InvariantCulture); + double latitude = double.Parse(JsonConfig.settings.latitude, CultureInfo.InvariantCulture); + double longitude = double.Parse(JsonConfig.settings.longitude, CultureInfo.InvariantCulture); var sunPhases = GetSunPhases(date, latitude, longitude); SolarData data = new SolarData(); @@ -86,8 +81,8 @@ public static SolarData GetSolarData(DateTime date) catch (InvalidOperationException) // Handle polar day/night { DateTime solarNoon = GetSolarTime(sunPhases, SunPhaseName.SolarNoon); - double sunAltitude = SunCalcNet.SunCalc.GetSunPosition(solarNoon.ToUniversalTime(), - latitude, longitude).Altitude; + double sunAltitude = SunCalcNet.SunCalc.GetSunPosition(solarNoon.ToUniversalTime(), latitude, + longitude).Altitude; if (sunAltitude > 0) { @@ -111,8 +106,7 @@ public static string GetSunriseSunsetString(SolarData solarData) case PolarPeriod.PolarNight: return _("Sunrise/Sunset: Down all day"); default: - return string.Format(_("Sunrise: {0}, Sunset: {1}"), - solarData.sunriseTime.ToShortTimeString(), + return string.Format(_("Sunrise: {0}, Sunset: {1}"), solarData.sunriseTime.ToShortTimeString(), solarData.sunsetTime.ToShortTimeString()); } } diff --git a/src/TaskbarProgress.cs b/src/TaskbarProgress.cs index 05b01b2..dfd83fa 100644 --- a/src/TaskbarProgress.cs +++ b/src/TaskbarProgress.cs @@ -42,8 +42,7 @@ private interface ITaskbarList3 // ITaskbarList2 [PreserveSig] - void MarkFullscreenWindow(IntPtr hwnd, - [MarshalAs(UnmanagedType.Bool)] bool fFullscreen); + void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen); // ITaskbarList3 [PreserveSig] @@ -74,8 +73,7 @@ public static void SetValue(IntPtr windowHandle, double progressValue, double pr { if (taskbarSupported) { - taskbarInstance.SetProgressValue(windowHandle, (ulong)progressValue, - (ulong)progressMax); + taskbarInstance.SetProgressValue(windowHandle, (ulong)progressValue, (ulong)progressMax); } } } diff --git a/src/ThemeDialog.cs b/src/ThemeDialog.cs index 1ffcb2e..4dbc416 100644 --- a/src/ThemeDialog.cs +++ b/src/ThemeDialog.cs @@ -63,9 +63,9 @@ public void ImportThemes(List themePaths) if (duplicateThemeNames.Count > 0) { - DialogResult result = MessageDialog.ShowQuestion(string.Format(_("The following " + - "themes are already installed:\n\t{0}\n\nDo you want to overwrite them?"), - string.Join("\n\t", duplicateThemeNames)), _("Question"), true); + DialogResult result = MessageDialog.ShowQuestion(string.Format(_("The following themes are already " + + "installed:\n\t{0}\n\nDo you want to overwrite them?"), string.Join("\n\t", duplicateThemeNames)), + _("Question"), true); if (result != DialogResult.Yes) { @@ -146,12 +146,10 @@ private void LoadPreviewImage(int imageNumber) ThemeConfig theme = ThemeManager.themeSettings[selectedIndex - 1]; int imageId = ThemeManager.GetThemeImageList(theme)[imageNumber - 1]; string imageFilename = theme.imageFilename.Replace("*", imageId.ToString()); - LoadPreviewImage(new Bitmap(Path.Combine("themes", theme.themeId, - imageFilename))); + LoadPreviewImage(new Bitmap(Path.Combine("themes", theme.themeId, imageFilename))); } - imageNumberLabel.Text = string.Format(_("Image {0} of {1}"), imageNumber, - maxImageNumber); + imageNumberLabel.Text = string.Format(_("Image {0} of {1}"), imageNumber, maxImageNumber); firstButton.Enabled = imageNumber > 1; previousButton.Enabled = imageNumber > 1; nextButton.Enabled = imageNumber < maxImageNumber; @@ -191,13 +189,12 @@ private void LoadImportedThemes(List themes, ImportDialog importDia themeNames.Sort(); int itemIndex = themeNames.IndexOf(themeName) + 1; - using (Image thumbnailImage = ThemeThumbLoader.GetThumbnailImage(themes[i], - thumbnailSize, false)) + using (Image thumbnailImage = ThemeThumbLoader.GetThumbnailImage(themes[i], thumbnailSize, false)) { this.Invoke(new Action(() => { - imageListView1.Items.Insert(itemIndex, - ThemeManager.GetThemeName(themes[i]), thumbnailImage); + imageListView1.Items.Insert(itemIndex, ThemeManager.GetThemeName(themes[i]), + thumbnailImage); newItem = imageListView1.Items[itemIndex]; newItem.Tag = themes[i].themeId; })); @@ -240,8 +237,7 @@ private void UpdateSelectedItem() if (selectedIndex > 0) { string themeId = (string)imageListView1.Items[selectedIndex].Tag; - selectedIndex = ThemeManager.themeSettings.FindIndex( - t => t.themeId == themeId) + 1; + selectedIndex = ThemeManager.themeSettings.FindIndex(t => t.themeId == themeId) + 1; ThemeConfig theme = ThemeManager.themeSettings[selectedIndex - 1]; themeDownloaded = ThemeManager.IsThemeDownloaded(theme); @@ -253,8 +249,7 @@ private void UpdateSelectedItem() } else { - LoadPreviewImage((Image)Properties.Resources.ResourceManager.GetObject( - themeId + "_thumbnail")); + LoadPreviewImage((Image)Properties.Resources.ResourceManager.GetObject(themeId + "_thumbnail")); } } @@ -282,8 +277,7 @@ private void ThemeDialog_Load(object sender, EventArgs e) Size thumbnailSize = ThemeThumbLoader.GetThumbnailSize(this); imageListView1.ThumbnailSize = thumbnailSize; - imageListView1.Items.Add(_("None"), ThemeThumbLoader.ScaleImage(windowsWallpaper, - thumbnailSize)); + imageListView1.Items.Add(_("None"), ThemeThumbLoader.ScaleImage(windowsWallpaper, thumbnailSize)); string currentTheme = ThemeManager.currentTheme?.themeId; ImageListViewItem focusItem = null; @@ -309,8 +303,7 @@ private void ThemeDialog_Load(object sender, EventArgs e) themeNames.Sort(); int itemIndex = themeNames.IndexOf(themeName) + 1; - using (Image thumbnailImage = ThemeThumbLoader.GetThumbnailImage(theme, - thumbnailSize, true)) + using (Image thumbnailImage = ThemeThumbLoader.GetThumbnailImage(theme, thumbnailSize, true)) { this.Invoke(new Action(() => { imageListView1.Items.Insert(itemIndex, themeName, thumbnailImage); @@ -412,8 +405,7 @@ private void applyButton_Click(object sender, EventArgs e) if (selectedIndex > 0) { - themeDownloaded = ThemeManager.IsThemeDownloaded( - ThemeManager.themeSettings[selectedIndex - 1]); + themeDownloaded = ThemeManager.IsThemeDownloaded(ThemeManager.themeSettings[selectedIndex - 1]); } if (!themeDownloaded) @@ -439,8 +431,7 @@ private void closeButton_Click(object sender, EventArgs e) private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { - imageListView1.HitTest(imageListView1.PointToClient(Cursor.Position), - out var hitTestInfo); + imageListView1.HitTest(imageListView1.PointToClient(Cursor.Position), out var hitTestInfo); int itemIndex = hitTestInfo.ItemIndex; string themeId = (string)imageListView1.Items[itemIndex].Tag; @@ -467,9 +458,8 @@ private void removeToolStripMenuItem_Click(object sender, EventArgs e) string themeId = (string)imageListView1.Items[itemIndex].Tag; ThemeConfig theme = ThemeManager.themeSettings.Find(t => t.themeId == themeId); - DialogResult result = MessageDialog.ShowQuestion(string.Format(_("Are you sure you " + - "want to remove the '{0}' theme?"), ThemeManager.GetThemeName(theme)), - _("Question"), true); + DialogResult result = MessageDialog.ShowQuestion(string.Format(_("Are you sure you want to remove the " + + "'{0}' theme?"), ThemeManager.GetThemeName(theme)), _("Question"), true); if (result == DialogResult.Yes) { @@ -522,9 +512,9 @@ private void OnFormClosing(object sender, FormClosingEventArgs e) { if (JsonConfig.firstRun && ThemeManager.currentTheme == null) { - DialogResult result = MessageDialog.ShowQuestion(_("WinDynamicDesktop cannot " + - "dynamically update your wallpaper until you have selected a theme. Are you " + - "sure you want to continue without a theme selected?"), _("Question"), true); + DialogResult result = MessageDialog.ShowQuestion(_("WinDynamicDesktop cannot dynamically update your " + + "wallpaper until you have selected a theme. Are you sure you want to continue without a theme " + + "selected?"), _("Question"), true); if (result != DialogResult.Yes) { diff --git a/src/ThemeError.cs b/src/ThemeError.cs index 6179dd2..ca561fd 100644 --- a/src/ThemeError.cs +++ b/src/ThemeError.cs @@ -58,8 +58,7 @@ class InvalidZIP : ThemeError { public InvalidZIP(string themeId, string zipPath) : base(themeId) { - errorMsg = string.Format(_("Could not read ZIP file at {0} because its format is " + - "invalid"), zipPath); + errorMsg = string.Format(_("Could not read ZIP file at {0} because its format is invalid"), zipPath); } } @@ -67,9 +66,8 @@ class MissingFieldsInThemeJSON : ThemeError { public MissingFieldsInThemeJSON(string themeId) : base(themeId) { - errorMsg = _("Theme JSON file is missing one or more of these required fields: " + - "'dayImageList', 'imageFilename', 'nightImageList', 'sunriseImageList', " + - "'sunsetImageList'"); + errorMsg = _("Theme JSON file is missing one or more of these required fields: 'dayImageList', " + + "'imageFilename', 'nightImageList', 'sunriseImageList', 'sunsetImageList'"); } } diff --git a/src/ThemeListViewRenderer.cs b/src/ThemeListViewRenderer.cs index f0e7292..c88db5c 100644 --- a/src/ThemeListViewRenderer.cs +++ b/src/ThemeListViewRenderer.cs @@ -80,7 +80,8 @@ public override void DrawItem(Graphics g, ImageListViewItem item, ItemState stat Image img = item.GetCachedImage(CachedImageType.Thumbnail); if (img != null) { - Rectangle pos = Utility.GetSizedImageBounds(img, new Rectangle(bounds.Location + itemPadding, ImageListView.ThumbnailSize)); + Rectangle pos = Utility.GetSizedImageBounds(img, new Rectangle(bounds.Location + itemPadding, + ImageListView.ThumbnailSize)); g.DrawImage(img, pos); } @@ -98,9 +99,13 @@ public override void DrawItem(Graphics g, ImageListViewItem item, ItemState stat foreColor = ImageListView.Colors.UnFocusedForeColor; } Size szt = System.Windows.Forms.TextRenderer.MeasureText(item.Text, ImageListView.Font); - Rectangle rt = new Rectangle(bounds.Left + itemPadding.Width, bounds.Top + 2 * itemPadding.Height + ImageListView.ThumbnailSize.Height, ImageListView.ThumbnailSize.Width, szt.Height); + Rectangle rt = new Rectangle(bounds.Left + itemPadding.Width, + bounds.Top + 2 * itemPadding.Height + ImageListView.ThumbnailSize.Height, + ImageListView.ThumbnailSize.Width, szt.Height); System.Windows.Forms.TextRenderer.DrawText(g, item.Text, ImageListView.Font, rt, foreColor, - System.Windows.Forms.TextFormatFlags.EndEllipsis | System.Windows.Forms.TextFormatFlags.HorizontalCenter | System.Windows.Forms.TextFormatFlags.VerticalCenter | System.Windows.Forms.TextFormatFlags.SingleLine); + System.Windows.Forms.TextFormatFlags.EndEllipsis | + System.Windows.Forms.TextFormatFlags.HorizontalCenter | + System.Windows.Forms.TextFormatFlags.VerticalCenter | System.Windows.Forms.TextFormatFlags.SingleLine); g.Clip = oldClip; } diff --git a/src/ThemeLoader.cs b/src/ThemeLoader.cs index 0dbacb0..428f2bf 100644 --- a/src/ThemeLoader.cs +++ b/src/ThemeLoader.cs @@ -41,9 +41,9 @@ private static ThemeResult ValidateThemeJSON(ThemeConfig theme) { return new ThemeResult(new InvalidThemeJSON(theme.themeId)); } - else if (string.IsNullOrEmpty(theme.imageFilename) || - IsNullOrEmpty(theme.sunriseImageList) || IsNullOrEmpty(theme.dayImageList) || - IsNullOrEmpty(theme.sunsetImageList) || IsNullOrEmpty(theme.nightImageList)) + else if (string.IsNullOrEmpty(theme.imageFilename) || IsNullOrEmpty(theme.sunriseImageList) || + IsNullOrEmpty(theme.dayImageList) || IsNullOrEmpty(theme.sunsetImageList) || + IsNullOrEmpty(theme.nightImageList)) { return new ThemeResult(new MissingFieldsInThemeJSON(theme.themeId)); } @@ -60,14 +60,14 @@ public static void HandleError(ThemeError e) if (ThemeManager.downloadMode || ThemeManager.importMode) { - MessageDialog.ShowWarning(string.Format(_("Failed to import '{0}' theme:\n{1}"), - e.themeId, e.errorMsg), _("Error")); + MessageDialog.ShowWarning(string.Format(_("Failed to import '{0}' theme:\n{1}"), e.themeId, e.errorMsg), + _("Error")); } else { - DialogResult result = MessageDialog.ShowQuestion(string.Format(_("Failed to " + - "load '{0}' theme:\n{1}\n\nDo you want to disable this theme to prevent the " + - "error from happening again?"), e.themeId, e.errorMsg), _("Error"), true); + DialogResult result = MessageDialog.ShowQuestion(string.Format(_("Failed to load '{0}' theme:\n{1}\n" + + "\nDo you want to disable this theme to prevent the error from happening again?"), e.themeId, + e.errorMsg), _("Error"), true); ThemeManager.DisableTheme(e.themeId, result == DialogResult.Yes); } @@ -171,8 +171,7 @@ public static ThemeResult CopyLocalTheme(string jsonPath, string themeId) { try { - File.Copy(imagePath, Path.Combine(themePath, Path.GetFileName(imagePath)), - true); + File.Copy(imagePath, Path.Combine(themePath, Path.GetFileName(imagePath)), true); } catch { diff --git a/src/ThemeManager.cs b/src/ThemeManager.cs index e255bed..9db0f3e 100644 --- a/src/ThemeManager.cs +++ b/src/ThemeManager.cs @@ -33,8 +33,7 @@ public static void Initialize() defaultThemes = DefaultThemes.GetDefaultThemes(); List themeIds = new List(); - foreach (string filePath in Directory.EnumerateFiles("themes", "*.json", - SearchOption.AllDirectories)) + foreach (string filePath in Directory.EnumerateFiles("themes", "*.json", SearchOption.AllDirectories)) { string themeId = Path.GetFileName(Path.GetDirectoryName(filePath)); @@ -75,8 +74,7 @@ public static string GetThemeName(ThemeConfig theme) public static bool IsThemeDownloaded(ThemeConfig theme) { string themePath = Path.Combine("themes", theme.themeId); - return (Directory.Exists(themePath) && - (Directory.GetFiles(themePath, theme.imageFilename).Length > 0)); + return (Directory.Exists(themePath) && (Directory.GetFiles(themePath, theme.imageFilename).Length > 0)); } public static List GetThemeImageList(ThemeConfig theme) @@ -169,23 +167,21 @@ private static void LoadInstalledThemes(List themeIds) { foreach (string themeId in themeIds) { - ThemeLoader.TryLoad(themeId).Match(ThemeLoader.HandleError, - theme => { - themeSettings.Add(theme); - - if (theme.themeId == JsonConfig.settings.themeName) - { - currentTheme = theme; - } + ThemeLoader.TryLoad(themeId).Match(ThemeLoader.HandleError, theme => { + themeSettings.Add(theme); + + if (theme.themeId == JsonConfig.settings.themeName) + { + currentTheme = theme; } - ); + }); } foreach (string themeId in defaultThemes) { if (!themeIds.Contains(themeId)) { - themeSettings.Add(new ThemeConfig() { themeId = themeId }); + themeSettings.Add(new ThemeConfig { themeId = themeId }); } } } diff --git a/src/ThemeThumbLoader.cs b/src/ThemeThumbLoader.cs index 6794c9c..19ec2db 100644 --- a/src/ThemeThumbLoader.cs +++ b/src/ThemeThumbLoader.cs @@ -83,8 +83,7 @@ public static Image GetThumbnailImage(ThemeConfig theme, Size size, bool useCach } int imageId1 = theme.dayHighlight ?? theme.dayImageList[theme.dayImageList.Length / 2]; - int imageId2 = theme.nightHighlight ?? theme.nightImageList[ - theme.nightImageList.Length / 2]; + int imageId2 = theme.nightHighlight ?? theme.nightImageList[theme.nightImageList.Length / 2]; string imageFilename1 = theme.imageFilename.Replace("*", imageId1.ToString()); string imageFilename2 = theme.imageFilename.Replace("*", imageId2.ToString()); @@ -94,8 +93,7 @@ public static Image GetThumbnailImage(ThemeConfig theme, Size size, bool useCach using (Graphics g = Graphics.FromImage(bmp2)) { - g.DrawImage(bmp1, 0, 0, new Rectangle(0, 0, bmp1.Width / 2, bmp1.Height), - GraphicsUnit.Pixel); + g.DrawImage(bmp1, 0, 0, new Rectangle(0, 0, bmp1.Width / 2, bmp1.Height), GraphicsUnit.Pixel); } bmp2.Save(thumbnailPath, ImageFormat.Png); diff --git a/src/UpdateChecker.cs b/src/UpdateChecker.cs index d4a2583..e1f9ce6 100644 --- a/src/UpdateChecker.cs +++ b/src/UpdateChecker.cs @@ -35,8 +35,8 @@ public static List GetMenuItems() { if (!UwpDesktop.IsRunningAsUwp()) { - menuItem = new ToolStripMenuItem(_("Check for &updates automatically once a week"), - null, OnAutoUpdateItemClick); + menuItem = new ToolStripMenuItem(_("Check for &updates automatically once a week"), null, + OnAutoUpdateItemClick); menuItem.Checked = !JsonConfig.settings.disableAutoUpdate; return new List() { @@ -86,15 +86,14 @@ public static void CheckManual() if (latestVersion == null) { - MessageDialog.ShowWarning(_("WinDynamicDesktop could not connect to the " + - "Internet to check for updates."), _("Error")); + MessageDialog.ShowWarning(_("WinDynamicDesktop could not connect to the Internet to check for " + + "updates."), _("Error")); } else if (IsUpdateAvailable(currentVersion, latestVersion)) { - DialogResult result = MessageDialog.ShowQuestion(string.Format(_("There is a " + - "newer version of WinDynamicDesktop available. Do you want to download the " + - "update now?\n\nCurrent Version: {0}\nLatest Version: {1}"), currentVersion, - latestVersion), _("Update Available")); + DialogResult result = MessageDialog.ShowQuestion(string.Format(_("There is a newer version of " + + "WinDynamicDesktop available. Do you want to download the update now?\n\nCurrent Version: {0}\n" + + "Latest Version: {1}"), currentVersion, latestVersion), _("Update Available")); if (result == DialogResult.Yes) { @@ -103,8 +102,8 @@ public static void CheckManual() } else { - MessageDialog.ShowInfo(_("You already have the latest version of " + - "WinDynamicDesktop installed."), _("Up To Date")); + MessageDialog.ShowInfo(_("You already have the latest version of WinDynamicDesktop installed."), + _("Up To Date")); } } @@ -119,8 +118,8 @@ private static void CheckAuto() } else if (IsUpdateAvailable(currentVersion, latestVersion)) { - AppContext.ShowPopup(string.Format(_("WinDynamicDesktop {0} is available. Click " + - "here to download it."), latestVersion), _("Update Available")); + AppContext.ShowPopup(string.Format(_("WinDynamicDesktop {0} is available. Click here to download it."), + latestVersion), _("Update Available")); } JsonConfig.settings.lastUpdateCheck = DateTime.Now.ToString( diff --git a/src/UpdateHandler.cs b/src/UpdateHandler.cs index 326bda5..e9f925b 100644 --- a/src/UpdateHandler.cs +++ b/src/UpdateHandler.cs @@ -114,17 +114,20 @@ class UpdateHandler public static void CompatibilizeThemes() // Added 2019-10-10 { - if (Directory.Exists(Path.Combine("themes", "Catalina")) && !File.Exists(Path.Combine("themes", "Catalina", "theme.json"))) + if (Directory.Exists(Path.Combine("themes", "Catalina")) && + !File.Exists(Path.Combine("themes", "Catalina", "theme.json"))) { File.WriteAllText(Path.Combine("themes", "Catalina", "theme.json"), Catalina_JSON); } - if (Directory.Exists(Path.Combine("themes", "Mojave_Desert")) && !File.Exists(Path.Combine("themes", "Mojave_Desert", "theme.json"))) + if (Directory.Exists(Path.Combine("themes", "Mojave_Desert")) && + !File.Exists(Path.Combine("themes", "Mojave_Desert", "theme.json"))) { File.WriteAllText(Path.Combine("themes", "Mojave_Desert", "theme.json"), Mojave_Desert_JSON); } - if (Directory.Exists(Path.Combine("themes", "Solar_Gradients")) && !File.Exists(Path.Combine("themes", "Solar_Gradients", "theme.json"))) + if (Directory.Exists(Path.Combine("themes", "Solar_Gradients")) && + !File.Exists(Path.Combine("themes", "Solar_Gradients", "theme.json"))) { File.WriteAllText(Path.Combine("themes", "Solar_Gradients", "theme.json"), Solar_Gradients_JSON); } @@ -186,20 +189,18 @@ public static void UpdateToVersion4() // Added 2020-01-01 } string jsonText = File.ReadAllText("settings.conf"); LegacyConfig settings = JsonConvert.DeserializeObject(jsonText); - bool legacySettingsEnabled = (settings.changeSystemTheme || - settings.changeAppTheme || settings.changeLockScreen || - settings.useAutoBrightness || settings.useCustomAutoBrightness); + bool legacySettingsEnabled = (settings.changeSystemTheme || settings.changeAppTheme || + settings.changeLockScreen || settings.useAutoBrightness || settings.useCustomAutoBrightness); if (legacySettingsEnabled) { - jsonText = JsonConvert.SerializeObject( - JsonConvert.DeserializeObject(jsonText), Formatting.Indented); + jsonText = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(jsonText), + Formatting.Indented); File.WriteAllText("settings.conf", jsonText); - MessageDialog.ShowInfo("Updated to WinDynamicDesktop 4.0 successfully. Some " + - "features you were using have been disabled because they were removed from " + - "the core app. You were using one or more of the following features:\n\n* " + - "Change Windows 10 app/system theme\n* Change screen brightness\n* Change " + - "lockscreen image\n\nTo re-enable these features, install scripts for them " + - "from here: https://windd.info/scripts/"); + MessageDialog.ShowInfo("Updated to WinDynamicDesktop 4.0 successfully. Some features you were using " + + "have been disabled because they were removed from the core app. You were using one or more of " + + "the following features:\n\n* Change Windows 10 app/system theme\n* Change screen brightness\n* " + + "Change lockscreen image\n\nTo re-enable these features, install scripts for them from here: " + + "https://windd.info/scripts/"); } } } diff --git a/src/UwpHelper.cs b/src/UwpHelper.cs index 5569924..96d9968 100644 --- a/src/UwpHelper.cs +++ b/src/UwpHelper.cs @@ -21,8 +21,7 @@ public override string GetLocalFolder() public override async void CheckStartOnBoot() { - var startupTask = await Windows.ApplicationModel.StartupTask.GetAsync( - "WinDynamicDesktopUwp"); + var startupTask = await Windows.ApplicationModel.StartupTask.GetAsync("WinDynamicDesktopUwp"); switch (startupTask.State) { @@ -43,8 +42,7 @@ public override async void CheckStartOnBoot() public override async void ToggleStartOnBoot() { - var startupTask = await Windows.ApplicationModel.StartupTask.GetAsync( - "WinDynamicDesktopUwp"); + var startupTask = await Windows.ApplicationModel.StartupTask.GetAsync("WinDynamicDesktopUwp"); if (!startOnBoot) { @@ -71,18 +69,15 @@ public override async void ToggleStartOnBoot() public override async void OpenUpdateLink() { - await Windows.System.Launcher.LaunchUriAsync( - new Uri("ms-windows-store://downloadsandupdates")); + await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store://downloadsandupdates")); } public override async void SetWallpaper(string imageFilename) { - var uri = new Uri("ms-appdata:///local/themes/" + ThemeManager.currentTheme.themeId + - "/" + imageFilename); + var uri = new Uri("ms-appdata:///local/themes/" + ThemeManager.currentTheme.themeId + "/" + imageFilename); var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); - var profileSettings = - Windows.System.UserProfile.UserProfilePersonalizationSettings.Current; + var profileSettings = Windows.System.UserProfile.UserProfilePersonalizationSettings.Current; await profileSettings.TrySetWallpaperImageAsync(file); } } diff --git a/src/UwpLocation.cs b/src/UwpLocation.cs index 949c6f5..ca42b2d 100644 --- a/src/UwpLocation.cs +++ b/src/UwpLocation.cs @@ -45,12 +45,10 @@ public static async Task RequestAccess() if (!hasAccess) { - AppContext.ShowPopup(_("In Windows 10 location settings, grant location access " + - "to WinDynamicDesktop. Then return to the app and click \"Check for " + - "Permission\".")); + AppContext.ShowPopup(_("In Windows 10 location settings, grant location access to WinDynamicDesktop. " + + "Then return to the app and click \"Check for Permission\".")); - await Windows.System.Launcher.LaunchUriAsync( - new Uri("ms-settings:privacy-location")); + await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location")); } return hasAccess; @@ -60,8 +58,8 @@ private static async Task UnsafeUpdateGeoposition() { var geolocator = new Windows.Devices.Geolocation.Geolocator(); - var geoposition = await geolocator.GetGeopositionAsync( - maximumAge: TimeSpan.FromMinutes(1), timeout: TimeSpan.FromSeconds(10)); + var geoposition = await geolocator.GetGeopositionAsync(maximumAge: TimeSpan.FromMinutes(1), + timeout: TimeSpan.FromSeconds(10)); return geoposition.Coordinate.Point.Position; } @@ -72,8 +70,7 @@ public static async Task UpdateGeoposition() { var pos = await UnsafeUpdateGeoposition(); JsonConfig.settings.latitude = pos.Latitude.ToString(CultureInfo.InvariantCulture); - JsonConfig.settings.longitude = pos.Longitude.ToString( - CultureInfo.InvariantCulture); + JsonConfig.settings.longitude = pos.Longitude.ToString(CultureInfo.InvariantCulture); return true; } diff --git a/src/WallpaperApi.cs b/src/WallpaperApi.cs index 4b35965..575b3ac 100644 --- a/src/WallpaperApi.cs +++ b/src/WallpaperApi.cs @@ -158,10 +158,8 @@ public enum ComponentModify : int ORIGINAL_CSI = 0x00001000, RESTORED_CSI = 0x00002000, CURITEMSTATE = 0x00004000, - ALL = TYPE | CHECKED | DIRTY | NOSCROLL | POS_LEFT | SIZE_WIDTH | - SIZE_HEIGHT | POS_ZINDEX | SOURCE | - FRIENDLYNAME | POS_TOP | SUBSCRIBEDURL | ORIGINAL_CSI | - RESTORED_CSI | CURITEMSTATE + ALL = TYPE | CHECKED | DIRTY | NOSCROLL | POS_LEFT | SIZE_WIDTH | SIZE_HEIGHT | POS_ZINDEX | SOURCE | + FRIENDLYNAME | POS_TOP | SUBSCRIBEDURL | ORIGINAL_CSI | RESTORED_CSI | CURITEMSTATE } [Flags] @@ -178,8 +176,8 @@ public interface IActiveDesktop [PreserveSig] int ApplyChanges(AD_Apply dwFlags); [PreserveSig] - int GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszWallpaper, - int cchWallpaper, int dwReserved); + int GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszWallpaper, int cchWallpaper, + int dwReserved); [PreserveSig] int SetWallpaper([MarshalAs(UnmanagedType.LPWStr)] string pwszWallpaper, int dwReserved); [PreserveSig] @@ -187,8 +185,8 @@ int GetWallpaper([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pws [PreserveSig] int SetWallpaperOptions(ref WALLPAPEROPT pwpo, int dwReserved); [PreserveSig] - int GetPattern([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszPattern, - int cchPattern, int dwReserved); + int GetPattern([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszPattern, int cchPattern, + int dwReserved); [PreserveSig] int SetPattern([MarshalAs(UnmanagedType.LPWStr)] string pwszPattern, int dwReserved); [PreserveSig] @@ -210,20 +208,19 @@ int GetPattern([MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pwszP [PreserveSig] int GetDesktopItemByID(IntPtr dwID, ref COMPONENT pcomp, int dwReserved); [PreserveSig] - int GenerateDesktopItemHtml([MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, - ref COMPONENT pcomp, int dwReserved); + int GenerateDesktopItemHtml([MarshalAs(UnmanagedType.LPWStr)] string pwszFileName, ref COMPONENT pcomp, + int dwReserved); [PreserveSig] - int AddUrl(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszSource, - ref COMPONENT pcomp, AddURL dwFlags); + int AddUrl(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszSource, ref COMPONENT pcomp, + AddURL dwFlags); [PreserveSig] - int GetDesktopItemBySource([MarshalAs(UnmanagedType.LPWStr)] string pwszSource, - ref COMPONENT pcomp, int dwReserved); + int GetDesktopItemBySource([MarshalAs(UnmanagedType.LPWStr)] string pwszSource, ref COMPONENT pcomp, + int dwReserved); } public class ActiveDesktopWrapper { - static readonly Guid CLSID_ActiveDesktop = - new Guid("{75048700-EF1F-11D0-9888-006097DEACF9}"); + static readonly Guid CLSID_ActiveDesktop = new Guid("{75048700-EF1F-11D0-9888-006097DEACF9}"); public static IActiveDesktop GetActiveDesktop() { @@ -234,18 +231,17 @@ public static IActiveDesktop GetActiveDesktop() public class WallpaperApi { - [DllImport("user32.dll", SetLastError = true)] + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] - private static extern int SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, - IntPtr lParam, uint fuFlags, uint uTimeout, out IntPtr result); + private static extern int SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, uint fuFlags, + uint uTimeout, out IntPtr result); public static void EnableTransitions() { IntPtr result = IntPtr.Zero; - SendMessageTimeout(FindWindow("Progman", null), 0x52c, IntPtr.Zero, IntPtr.Zero, - 0, 500, out result); + SendMessageTimeout(FindWindow("Progman", null), 0x52c, IntPtr.Zero, IntPtr.Zero, 0, 500, out result); } public static void SetWallpaper(string imagePath) diff --git a/src/WallpaperChangeScheduler.cs b/src/WallpaperChangeScheduler.cs index f6f3464..4e37cc8 100644 --- a/src/WallpaperChangeScheduler.cs +++ b/src/WallpaperChangeScheduler.cs @@ -101,8 +101,7 @@ public void RunScheduler(bool forceImageUpdate = false) } else { - SolarData tomorrowsData = SunriseSunsetService.GetSolarData( - DateTime.Today.AddDays(1)); + SolarData tomorrowsData = SunriseSunsetService.GetSolarData(DateTime.Today.AddDays(1)); nextUpdateTime = tomorrowsData.sunriseTime; } @@ -198,16 +197,14 @@ public SchedulerState GetImageData(SolarData data, ThemeConfig theme) if (DateTime.Now < data.solarTimes[0]) { - SolarData yesterdaysData = SunriseSunsetService.GetSolarData( - DateTime.Today.AddDays(-1)); + SolarData yesterdaysData = SunriseSunsetService.GetSolarData(DateTime.Today.AddDays(-1)); segmentStart = yesterdaysData.solarTimes[3]; segmentEnd = data.solarTimes[0]; } else { segmentStart = data.solarTimes[3]; - SolarData tomorrowsData = SunriseSunsetService.GetSolarData( - DateTime.Today.AddDays(1)); + SolarData tomorrowsData = SunriseSunsetService.GetSolarData(DateTime.Today.AddDays(1)); segmentEnd = tomorrowsData.solarTimes[0]; } @@ -230,16 +227,14 @@ public SchedulerState GetImageData(SolarData data, ThemeConfig theme) } else if (DateTime.Now < data.sunriseTime) { - SolarData yesterdaysData = SunriseSunsetService.GetSolarData( - DateTime.Today.AddDays(-1)); + SolarData yesterdaysData = SunriseSunsetService.GetSolarData(DateTime.Today.AddDays(-1)); segmentStart = yesterdaysData.sunsetTime; segmentEnd = data.sunriseTime; } else { segmentStart = data.sunsetTime; - SolarData tomorrowsData = SunriseSunsetService.GetSolarData( - DateTime.Today.AddDays(1)); + SolarData tomorrowsData = SunriseSunsetService.GetSolarData(DateTime.Today.AddDays(1)); segmentEnd = tomorrowsData.sunriseTime; } } @@ -259,8 +254,7 @@ public SchedulerState GetImageData(SolarData data, ThemeConfig theme) private void SetWallpaper(int imageId) { - string imageFilename = ThemeManager.currentTheme.imageFilename.Replace("*", - imageId.ToString()); + string imageFilename = ThemeManager.currentTheme.imageFilename.Replace("*", imageId.ToString()); string imagePath = Path.Combine(Directory.GetCurrentDirectory(), "themes", ThemeManager.currentTheme.themeId, imageFilename); diff --git a/src/WallpaperShuffler.cs b/src/WallpaperShuffler.cs index 9678f9b..27b3204 100644 --- a/src/WallpaperShuffler.cs +++ b/src/WallpaperShuffler.cs @@ -31,8 +31,7 @@ public static void AddThemeToHistory(string themeId, bool clearHistory = false) shuffleHistory.Add(themeId); JsonConfig.settings.shuffleHistory = shuffleHistory.ToArray(); - JsonConfig.settings.lastShuffleDate = DateTime.Now.ToString( - CultureInfo.InvariantCulture); + JsonConfig.settings.lastShuffleDate = DateTime.Now.ToString(CultureInfo.InvariantCulture); } public static void MaybeShuffleWallpaper()