public GPUMonitorModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     State         = GlobalState.Instance();
     ConfigBuilder = AdmConfigBuilder.Instance();
     PostponeDark  = false;
     PostponeLight = false;
 }
예제 #2
0
        public override void UpdateSettingsState(object newSettings)
        {
            base.UpdateSettingsState(newSettings);
            AdmConfigBuilder builder = AdmConfigBuilder.Instance();

            themeModeEnabled = builder.Config.WindowsThemeMode.Enabled;
        }
예제 #3
0
        private static void HandleThemeMonitorEvent()
        {
            Logger.Debug("theme switch detected");
            Thread thread = new(() =>
            {
                try
                {
                    GlobalState.Instance().CurrentWindowsThemeName = ThemeHandler.GetCurrentThemeName();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, $"could not update theme name");
                }
            })
            {
                Name = "COMThemeManagerThread"
            };

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            try
            {
                thread.Join();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "error while waiting for thread to stop:");
            }
            if (builder.Config.WindowsThemeMode.MonitorActiveTheme)
            {
                ThemeManager.RequestSwitch(AdmConfigBuilder.Instance(), new(SwitchSource.ExternalThemeSwitch));
            }
        }
예제 #4
0
 /// <summary>
 /// Instantiates a new ModuleWardenModule.
 /// This module registers and deregisters modules automatically based on the AutoDarkModeConfiguration
 /// </summary>
 /// <param name="name">unique name of the module</param>
 public ModuleWardenModule(string name, List <ModuleTimer> timers, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     ConfigBuilder = AdmConfigBuilder.Instance();
     Rtc           = RuntimeConfig.Instance();
     Timers        = timers;
     Priority      = 1;
 }
예제 #5
0
 public GPUMonitorModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     Rtc           = RuntimeConfig.Instance();
     ConfigBuilder = AdmConfigBuilder.Instance();
     Monitor       = false;
     Freeze        = false;
 }
        public static async Task <string> GetCityName()
        {
            AdmConfigBuilder configBuilder = AdmConfigBuilder.Instance();

            Geopoint geopoint = new(new BasicGeoposition
            {
                Latitude = configBuilder.LocationData.Lat,
                Longitude = configBuilder.LocationData.Lon
            });

            try
            {
                MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(geopoint, MapLocationDesiredAccuracy.Low);

                if (result.Status == MapLocationFinderStatus.Success)
                {
                    return(result.Locations[0].Address.Town);
                }
                else
                {
                    return(null);
                }
            }
            catch (SEHException)
            {
                return(string.Format("(~{0,00}, ~{1,00})", geopoint.Position.Latitude, geopoint.Position.Longitude));
            }
        }
 public GPUMonitorModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     State         = GlobalState.Instance();
     ConfigBuilder = AdmConfigBuilder.Instance();
     Monitor       = false;
     Freeze        = false;
 }
예제 #8
0
        public static void CleanUpMonitors()
        {
            AdmConfigBuilder  builder    = AdmConfigBuilder.Instance();
            IDesktopWallpaper handler    = (IDesktopWallpaper) new DesktopWallpaperClass();
            List <string>     monitorIds = new();

            for (uint i = 0; i < handler.GetMonitorDevicePathCount(); i++)
            {
                monitorIds.Add(handler.GetMonitorDevicePathAt(i));
            }
            List <MonitorSettings> connectedSettings = new();

            foreach (string monitorId in monitorIds)
            {
                if (monitorId.Length == 0)
                {
                    continue;
                }
                MonitorSettings settings = builder.Config.WallpaperSwitch.Component.Monitors.Find(m => m.Id == monitorId);
                if (settings != null)
                {
                    connectedSettings.Add(settings);
                }
            }
            int diff = builder.Config.WallpaperSwitch.Component.Monitors.Count - connectedSettings.Count;

            if (diff != 0)
            {
                Logger.Info($"removing {diff} disconnected monitors");
                GlobalState state = GlobalState.Instance();
                state.SkipConfigFileReload = true;
                builder.Config.WallpaperSwitch.Component.Monitors = connectedSettings;
                builder.Save();
            }
        }
예제 #9
0
 /// <summary>
 /// Instantiates a new ModuleWardenModule.
 /// This module registers and deregisters modules automatically based on the AutoDarkModeConfiguration
 /// </summary>
 /// <param name="name">unique name of the module</param>
 public WardenModule(string name, List <ModuleTimer> timers, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     ConfigBuilder = AdmConfigBuilder.Instance();
     State         = GlobalState.Instance();
     State.SetWarden(this);
     Timers   = timers;
     Priority = 1;
 }
 private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
 {
     if (e.Mode == PowerModes.Resume)
     {
         Logger.Info("system resuming from suspended state, refreshing theme");
         ThemeManager.TimedSwitch(AdmConfigBuilder.Instance());
     }
 }
        private void OpenConfigDir(object sender, EventArgs e)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                Arguments = AdmConfigBuilder.Instance().ConfigDir,
                FileName  = "explorer.exe"
            };

            Process.Start(startInfo);
        }
예제 #12
0
        private BasicGeoposition GetUserPosition()
        {
            AdmConfigBuilder configBuilder = AdmConfigBuilder.Instance();
            var position = new BasicGeoposition()
            {
                Latitude  = configBuilder.LocationData.Lat,
                Longitude = configBuilder.LocationData.Lon
            };

            return(position);
        }
 public static void DeregisterThemeEvent()
 {
     try
     {
         PowerManager.BatteryStatusChanged -= PowerManager_BatteryStatusChanged;
         ThemeManager.TimedSwitch(AdmConfigBuilder.Instance());
     }
     catch (InvalidOperationException ex)
     {
         Logger.Error(ex, "while deregistering SystemEvents_PowerModeChanged ");
     }
 }
예제 #14
0
 ComponentManager()
 {
     Builder    = AdmConfigBuilder.Instance();
     Components = new List <ISwitchComponent>
     {
         AppsSwitch,
         ColorFilterSwitch,
         OfficeSwitch,
         SystemSwitch,
         //TaskbarAccentColorSwitch
         WallpaperSwitch
     };
     UpdateSettings();
 }
        private static void PowerManager_BatteryStatusChanged(object sender, object e)
        {
            AdmConfigBuilder builder = AdmConfigBuilder.Instance();

            if (PowerManager.BatteryStatus == BatteryStatus.Discharging)
            {
                Logger.Info("battery discharging, enabling dark mode");
                ThemeManager.SwitchTheme(builder.Config, Theme.Dark, false);
            }
            else
            {
                ThemeManager.TimedSwitch(builder);
            }
        }
예제 #16
0
        private static void PowerManager_BatteryStatusChanged(object sender, object e)
        {
            AdmConfigBuilder builder = AdmConfigBuilder.Instance();

            if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Offline)
            {
                Logger.Info("battery discharging, enabling dark mode");
                ThemeManager.UpdateTheme(builder.Config, Theme.Dark, new(SwitchSource.BatteryStatusChanged));
            }
            else
            {
                ThemeManager.RequestSwitch(builder, new(SwitchSource.BatteryStatusChanged));
            }
        }
        private void SwitchThemeNow(object sender, EventArgs e)
        {
            AdmConfig config = AdmConfigBuilder.Instance().Config;

            Logger.Info("ui signal received: switching theme");
            if (RegistryHandler.AppsUseLightTheme())
            {
                ThemeManager.SwitchTheme(config, Theme.Dark);
            }
            else
            {
                ThemeManager.SwitchTheme(config, Theme.Light);
            }
        }
예제 #18
0
        public int[] CalculateSunTime()
        {
            AdmConfigBuilder configBuilder = AdmConfigBuilder.Instance();

            int[] sundate = new int[4];

            //Add offset to sunrise and sunset hours using Settings
            DateTime sunrise = configBuilder.LocationData.Sunrise.AddMinutes(configBuilder.Config.Location.SunriseOffsetMin);
            DateTime sunset  = configBuilder.LocationData.Sunset.AddMinutes(configBuilder.Config.Location.SunsetOffsetMin);

            sundate[0] = sunrise.Hour;   //sunrise hour
            sundate[1] = sunrise.Minute; //sunrise minute
            sundate[2] = sunset.Hour;    //sunset hour
            sundate[3] = sunset.Minute;  //sunset minute
            return(sundate);
        }
예제 #19
0
 private static void EnsureAutostart()
 {
     try
     {
         AdmConfigBuilder builder = AdmConfigBuilder.Instance();
         builder.Load();
         if (builder.Config.AutoThemeSwitchingEnabled)
         {
             ICommandClient client = new ZeroMQClient(Address.DefaultPort);
             _ = client.SendMessageAndGetReply(Command.AddAutostart);
         }
     }
     catch (Exception ex)
     {
         Trace.WriteLine(ex);
     }
 }
예제 #20
0
 public static void DeregisterThemeEvent()
 {
     try
     {
         if (darkThemeOnBatteryEnabled)
         {
             Logger.Info("disabling event handler for dark mode on battery state discharging");
             PowerManager.BatteryStatusChanged -= PowerManager_BatteryStatusChanged;
             darkThemeOnBatteryEnabled          = false;
             ThemeManager.TimedSwitch(AdmConfigBuilder.Instance());
         }
     }
     catch (InvalidOperationException ex)
     {
         Logger.Error(ex, "while deregistering SystemEvents_PowerModeChanged ");
     }
 }
예제 #21
0
 public static void InvokeFailedUpdateToast()
 {
     Program.ActionQueue.Add(() =>
     {
         string configPath = AdmConfigBuilder.Instance().ConfigDir;
         new ToastContentBuilder()
         .AddText($"Update failed")
         .AddText($"An error occurred while updating.")
         .AddText($"Please see service.log and updater.log for more infos")
         .AddButton(new ToastButton()
                    .SetContent("Open log directory")
                    .SetProtocolActivation(new Uri(configPath)))
         .SetProtocolActivation(new Uri(configPath))
         .Show(toast =>
         {
             toast.Tag = "adm_failed_update";
         });
     });
 }
예제 #22
0
        protected override void ChangeEvent()
        {
            bool geolocatorToggled = newConfig.Location.UseGeolocatorService != oldConfig.Location.UseGeolocatorService;
            bool latChanged        = newConfig.Location.CustomLat != oldConfig.Location.CustomLat;
            bool lonChanged        = newConfig.Location.CustomLon != oldConfig.Location.CustomLon;

            // If geolocator has been toggled, updat the geoposition. Only update for disabled mode when lat or lon has changed
            if (geolocatorToggled || (!geolocatorToggled && !newConfig.Location.UseGeolocatorService && (latChanged || lonChanged)))
            {
                try
                {
                    Task.Run(async() => await LocationHandler.UpdateGeoposition(AdmConfigBuilder.Instance())).Wait();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Error saving location data");
                }
            }
        }
예제 #23
0
        /// <summary>
        /// Adds missing monitors to the configuration file
        /// If a monitor configuration is not found,
        /// it will automatically create a configuration with the respective monitor's current wallpaper
        /// </summary>
        public static void DetectMonitors()
        {
            var monitors = Task.Run(async() => await GetMonitorInfosAsync()).Result;
            AdmConfigBuilder  builder    = AdmConfigBuilder.Instance();
            IDesktopWallpaper handler    = (IDesktopWallpaper) new DesktopWallpaperClass();
            List <string>     monitorIds = new();

            for (uint i = 0; i < handler.GetMonitorDevicePathCount(); i++)
            {
                monitorIds.Add(handler.GetMonitorDevicePathAt(i));
            }
            bool needsUpdate = false;

            foreach (string monitorId in monitorIds)
            {
                if (monitorId.Length == 0)
                {
                    continue;
                }
                MonitorSettings settings = builder.Config.WallpaperSwitch.Component.Monitors.Find(m => m.Id == monitorId);
                if (settings == null)
                {
                    Logger.Info($"missing monitor found, adding new default config for: {monitorId}");
                    builder.Config.WallpaperSwitch.Component.Monitors.Add(new MonitorSettings()
                    {
                        DarkThemeWallpaper  = handler.GetWallpaper(monitorId),
                        LightThemeWallpaper = handler.GetWallpaper(monitorId),
                        Id = monitorId
                    });
                    needsUpdate = true;
                }
            }
            if (needsUpdate)
            {
                GlobalState state = GlobalState.Instance();
                state.SkipConfigFileReload = true;
                builder.Save();
            }
        }
예제 #24
0
 protected override void ChangeEvent()
 {
     if (newConfig.Hotkeys.Enabled && !oldConfig.Hotkeys.Enabled)
     {
         HotkeyHandler.RegisterAllHotkeys(AdmConfigBuilder.Instance());
     }
     else if (!newConfig.Hotkeys.Enabled && oldConfig.Hotkeys.Enabled)
     {
         HotkeyHandler.UnregisterAllHotkeys();
     }
     else if (newConfig.Hotkeys.Enabled)
     {
         bool darkHotkeyChanged    = newConfig.Hotkeys.ForceDarkHotkey != oldConfig.Hotkeys.ForceDarkHotkey;
         bool lightHotkeyChanged   = newConfig.Hotkeys.ForceLightHotkey != oldConfig.Hotkeys.ForceLightHotkey;
         bool noForceHotkeyChanged = newConfig.Hotkeys.NoForceHotkey != oldConfig.Hotkeys.NoForceHotkey;
         if (darkHotkeyChanged || lightHotkeyChanged || noForceHotkeyChanged)
         {
             HotkeyHandler.UnregisterAllHotkeys();
             HotkeyHandler.RegisterAllHotkeys(AdmConfigBuilder.Instance());
         }
     }
 }
        public void ForceMode(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = sender as ToolStripMenuItem;

            if (mi.Checked)
            {
                Logger.Info("ui signal received: stop forcing specific theme");
                GlobalState rtc = GlobalState.Instance();
                rtc.ForcedTheme = Theme.Undefined;
                ThemeManager.TimedSwitch(AdmConfigBuilder.Instance());
                mi.Checked = false;
            }
            else
            {
                foreach (var item in NotifyIcon.ContextMenuStrip.Items)
                {
                    if (item is ToolStripMenuItem)
                    {
                        (item as ToolStripMenuItem).Checked = false;
                    }
                }
                AdmConfig   config = AdmConfigBuilder.Instance().Config;
                GlobalState rtc    = GlobalState.Instance();
                if (mi.Name == "forceLight")
                {
                    Logger.Info("ui signal received: forcing light theme");
                    rtc.ForcedTheme = Theme.Light;
                    ThemeManager.SwitchTheme(config, Theme.Light);
                }
                else if (mi.Name == "forceDark")
                {
                    Logger.Info("ui signal received: forcing dark theme");
                    rtc.ForcedTheme = Theme.Dark;
                    ThemeManager.SwitchTheme(config, Theme.Dark);
                }
                mi.Checked = true;
            }
        }
        public static void Apply(string themeFilePath)
        {
            Thread thread = new Thread(() =>
            {
                try
                {
                    PowerHandler.DisableEnergySaver(AdmConfigBuilder.Instance().Config);
                    new ThemeManagerClass().ApplyTheme(themeFilePath);
                    RuntimeConfig.Instance().CurrentWindowsThemeName = GetCurrentThemeName();
                    PowerHandler.RestoreEnergySaver(AdmConfigBuilder.Instance().Config);
                    Logger.Info($"applied theme \"{themeFilePath}\" successfully");
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, $"couldn't apply theme \"{themeFilePath}\"");
                }
            })
            {
                Name = "COMThemeManagerThread"
            };

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
예제 #27
0
 /// <summary>
 /// Instantiates a new GeopositionUpdateModule.
 /// This module updates the user's geolocation and saves the updated value to the configuration
 /// </summary>
 /// <param name="name">unique name of the module</param>
 public GeopositionUpdateModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     ConfigBuilder = AdmConfigBuilder.Instance();
 }
예제 #28
0
        /// <summary>
        /// Parses a command message and invokes a callback function delegate for status reporting
        /// </summary>
        /// <param name="msg">list of messages to parse</param>
        /// <param name="SendResponse">Callback taking a string as parameter to report return values back to sender</param>
        /// <param name="service">Service class for invoking application exit</param>
        public static void Parse(List <string> msg, Action <string> SendResponse, Service service)
        {
            AdmConfigBuilder builder = AdmConfigBuilder.Instance();
            RuntimeConfig    rtc     = RuntimeConfig.Instance();

            msg.ForEach(message =>
            {
                switch (message)
                {
                case Command.Switch:
                    Logger.Info("signal received: time based theme switch");
                    ThemeManager.TimedSwitch(builder);
                    SendResponse(Response.Ok);
                    break;

                case Command.Swap:
                    Logger.Info("signal received: swap themes");
                    if (RegistryHandler.AppsUseLightTheme())
                    {
                        ThemeManager.SwitchTheme(builder.Config, Theme.Dark);
                    }
                    else
                    {
                        ThemeManager.SwitchTheme(builder.Config, Theme.Light);
                    }
                    SendResponse(Response.Ok);
                    break;

                case Command.AddAutostart:
                    Logger.Info("signal received: adding service to autostart");
                    bool regOk;
                    bool taskOk;
                    if (builder.Config.Tunable.UseLogonTask)
                    {
                        regOk  = RegistryHandler.RemoveAutoStart();
                        taskOk = TaskSchdHandler.CreateLogonTask();
                    }
                    else
                    {
                        taskOk = TaskSchdHandler.RemoveLogonTask();
                        regOk  = RegistryHandler.AddAutoStart();
                    }
                    if (regOk && taskOk)
                    {
                        SendResponse(Response.Ok);
                    }
                    else
                    {
                        SendResponse(Response.Err);
                    }
                    break;

                case Command.RemoveAutostart:
                    Logger.Info("signal received: removing service from autostart");
                    bool ok;
                    if (builder.Config.Tunable.UseLogonTask)
                    {
                        ok = TaskSchdHandler.RemoveLogonTask();
                    }
                    else
                    {
                        ok = RegistryHandler.RemoveAutoStart();
                    }
                    if (ok)
                    {
                        SendResponse(Response.Ok);
                    }
                    else
                    {
                        SendResponse(Response.Err);
                    }
                    break;

                case Command.Location:
                    Logger.Info("signal received: request location update");
                    Task <bool> geoTask = Task.Run(() => LocationHandler.UpdateGeoposition(AdmConfigBuilder.Instance()));
                    geoTask.Wait();
                    var result = geoTask.Result;
                    if (result)
                    {
                        SendResponse(Response.Ok);
                    }
                    else
                    {
                        SendResponse(Response.NoLocAccess);
                    }
                    break;

                case Command.UpdateConfig:
                    Logger.Info("signal received: updating configuration files");
                    try
                    {
                        AdmConfigBuilder.Instance().Load();
                        AdmConfigBuilder.Instance().LoadLocationData();
                        SendResponse(Response.Ok);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "could not read config file");
                        SendResponse(Response.Err);
                    }
                    break;

                case Command.Update:
                    Logger.Info("signal received: checking for update");
                    SendResponse(UpdateHandler.CheckNewVersion());
                    break;

                case Command.Shutdown:
                    Logger.Info("signal received, exiting");
                    SendResponse(Response.Ok);
                    service.Exit(null, null);
                    break;

                case Command.TestError:
                    Logger.Info("signal received: test error");
                    SendResponse(Response.Err);
                    break;

                case Command.Alive:
                    Logger.Info("signal received: request for running status");
                    SendResponse(Response.Ok);
                    break;

                case Command.Light:
                    Logger.Info("signal received: force light theme");
                    rtc.ForcedTheme = Theme.Light;
                    ThemeManager.SwitchTheme(builder.Config, Theme.Light);
                    SendResponse(Response.Ok);
                    break;

                case Command.Dark:
                    Logger.Info("signal received: force dark theme");
                    rtc.ForcedTheme = Theme.Dark;
                    ThemeManager.SwitchTheme(builder.Config, Theme.Dark);
                    SendResponse(Response.Ok);
                    break;

                case Command.NoForce:
                    Logger.Info("signal received: resetting forced modes");
                    rtc.ForcedTheme = Theme.Undefined;
                    ThemeManager.TimedSwitch(builder);
                    SendResponse(Response.Ok);
                    break;

                default:
                    Logger.Debug("unknown message received");
                    SendResponse(Response.Err);
                    break;
                }
            });
        }
예제 #29
0
 public EventModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     builder = AdmConfigBuilder.Instance();
 }
예제 #30
0
 /// <summary>
 /// Instantiates a new TimeSwitchModule.
 /// This module switches themes based on system time and sunrise/sunset
 /// </summary>
 /// <param name="name">unique name of the module</param>
 public TimeSwitchModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     ConfigBuilder = AdmConfigBuilder.Instance();
 }