示例#1
0
        /// <summary>
        /// Calculate sundates based on a user configurable offset found in AutoDarkModeConfig.
        /// Call this method to generate the final sunrise and sunset times if location based switching is enabled
        /// </summary>
        /// <param name="config">AutoDarkMoeConfig object</param>
        /// <param name="sunrise_out"></param>
        /// <param name="sunset_out"></param>
        public static void GetSunTimes(AdmConfigBuilder builder, out DateTime sunrise_out, out DateTime sunset_out)
        {
            //Add offset to sunrise and sunset hours using Settings
            DateTime sunrise = builder.LocationData.Sunrise;

            sunrise = sunrise.AddMinutes(builder.Config.Location.SunriseOffsetMin);

            DateTime sunset = builder.LocationData.Sunset;

            sunset = sunset.AddMinutes(builder.Config.Location.SunsetOffsetMin);

            sunrise_out = sunrise;
            sunset_out  = sunset;
        }
示例#2
0
 ComponentManager()
 {
     Builder    = AdmConfigBuilder.Instance();
     Components = new List <ISwitchComponent>
     {
         AppsSwitch,
         ColorFilterSwitch,
         OfficeSwitch,
         SystemSwitch,
         //TaskbarAccentColorSwitch
         WallpaperSwitch
     };
     UpdateSettings();
 }
示例#3
0
        public static void RequestSwitch(AdmConfigBuilder builder, SwitchEventArgs e)
        {
            if (state.ForcedTheme == Theme.Dark)
            {
                UpdateTheme(builder.Config, Theme.Dark, e);
                return;
            }
            else if (state.ForcedTheme == Theme.Light)
            {
                UpdateTheme(builder.Config, Theme.Light, e);
                return;
            }

            if (builder.Config.Events.DarkThemeOnBattery)
            {
                if (PowerManager.BatteryStatus == BatteryStatus.Discharging)
                {
                    UpdateTheme(builder.Config, Theme.Dark, e);
                    return;
                }
                if (!builder.Config.AutoThemeSwitchingEnabled)
                {
                    UpdateTheme(builder.Config, Theme.Light, e);
                    return;
                }
            }

            if (builder.Config.AutoThemeSwitchingEnabled)
            {
                DateTime sunrise = builder.Config.Sunrise;
                DateTime sunset  = builder.Config.Sunset;
                if (builder.Config.Location.Enabled)
                {
                    LocationHandler.GetSunTimes(builder, out sunrise, out sunset);
                }
                //the time bewteen sunrise and sunset, aka "day"
                if (Extensions.NowIsBetweenTimes(sunrise.TimeOfDay, sunset.TimeOfDay))
                {
                    UpdateTheme(builder.Config, Theme.Light, e, sunrise);
                }
                else
                {
                    UpdateTheme(builder.Config, Theme.Dark, e, sunset);
                }
            }
            else
            {
                UpdateTheme(builder.Config, state.LastRequestedTheme, e);
            }
        }
示例#4
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));
            }
        }
示例#5
0
        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);
            }
        }
示例#6
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);
        }
示例#7
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 ");
     }
 }
示例#8
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);
     }
 }
        private static async Task <bool> UpdateWithGeolocator(AdmConfigBuilder configBuilder)
        {
            bool success    = false;
            var  permission = await Geolocator.RequestAccessAsync();

            void SetLatAndLon(BasicGeoposition position)
            {
                configBuilder.LocationData.Lon                    = position.Longitude;
                configBuilder.LocationData.Lat                    = position.Latitude;
                configBuilder.LocationData.LastUpdate             = DateTime.Now;
                configBuilder.LocationData.DataSourceIsGeolocator = true;
                Logger.Debug($"retrieved latitude {position.Latitude} and longitude {position.Longitude}");
                Logger.Info("updated geoposition via geolocator");
                success = true;
            }

            switch (permission)
            {
            case GeolocationAccessStatus.Allowed:
                Geolocator  locator  = new Geolocator();
                Geoposition location = await locator.GetGeopositionAsync();

                BasicGeoposition position = location.Coordinate.Point.Position;

                SetLatAndLon(position);

                break;

            default:
                if (Geolocator.DefaultGeoposition.HasValue)
                {
                    BasicGeoposition defaultPosition = Geolocator.DefaultGeoposition.Value;
                    SetLatAndLon(defaultPosition);
                }
                else
                {
                    configBuilder.Config.Location.Enabled = false;
                    Logger.Warn($"no geolocation access, please enable in system settings");
                }

                break;
            }
            return(success);
        }
示例#10
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");
                }
            }
        }
示例#11
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";
         });
     });
 }
示例#12
0
        public static void TimedSwitch(AdmConfigBuilder builder)
        {
            RuntimeConfig rtc = RuntimeConfig.Instance();

            if (rtc.ForcedTheme == Theme.Dark)
            {
                SwitchTheme(builder.Config, Theme.Dark);
                return;
            }
            else if (rtc.ForcedTheme == Theme.Light)
            {
                SwitchTheme(builder.Config, Theme.Light);
                return;
            }

            DateTime sunrise = builder.Config.Sunrise;
            DateTime sunset  = builder.Config.Sunset;

            if (builder.Config.Location.Enabled)
            {
                LocationHandler.GetSunTimesWithOffset(builder, out sunrise, out sunset);
            }
            //the time bewteen sunrise and sunset, aka "day"
            if (Extensions.NowIsBetweenTimes(sunrise.TimeOfDay, sunset.TimeOfDay))
            {
                // ensure that the theme doesn't switch to light mode if the battery is discharging
                if (builder.Config.Events.DarkThemeOnBattery && PowerManager.BatteryStatus != BatteryStatus.Discharging)
                {
                    SwitchTheme(builder.Config, Theme.Light, true, sunset, sunrise);
                }
                else if (!builder.Config.Events.DarkThemeOnBattery)
                {
                    SwitchTheme(builder.Config, Theme.Light, true, sunset, sunrise);
                }
            }
            else
            {
                SwitchTheme(builder.Config, Theme.Dark, true, sunset, sunrise);
            }
        }
示例#13
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();
            }
        }
        public static void EnforceNoMonitorUpdates(AdmConfigBuilder builder, GlobalState state, Theme theme)
        {
            string themePath = "";

            switch (theme)
            {
            case Theme.Light:
                themePath = Path.GetFileNameWithoutExtension(builder.Config.WindowsThemeMode.LightThemePath);
                break;

            case Theme.Dark:
                themePath = Path.GetFileNameWithoutExtension(builder.Config.WindowsThemeMode.DarkThemePath);
                break;
            }
            if (builder.Config.WindowsThemeMode.Enabled &&
                !builder.Config.WindowsThemeMode.MonitorActiveTheme &&
                state.CurrentWindowsThemeName == themePath)
            {
                Logger.Debug("enforcing theme refresh with disabled MonitorActiveTheme");
                state.CurrentWindowsThemeName = "";
            }
        }
 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;
            }
        }
示例#17
0
        /// <summary>
        /// Refreshes sunrise and sunset based on latitude and longitude found in the configuration file.
        /// </summary>
        /// <param name="configBuilder">config builder for the AutoDarkModeConfig to allow saving</param>
        private static void UpdateSunTime(AdmConfigBuilder configBuilder)
        {
            Sunriset.SunriseSunset(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, configBuilder.LocationData.Lat, configBuilder.LocationData.Lon, out double tsunrise, out double tsunset);
            TimeSpan sunriseTime = TimeSpan.FromHours(tsunrise);
            TimeSpan sunsetTime  = TimeSpan.FromHours(tsunset);

            DateTime today      = new(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            DateTime sunriseUTC = today + sunriseTime;
            DateTime sunsetUTC  = today + sunsetTime;

            if (sunriseUTC > sunsetUTC)
            {
                sunsetUTC = sunsetUTC.AddDays(1);
            }

            /*
             * SunriseCalc sunCalc = new SunriseCalc(configBuilder.LocationData.Lat, configBuilder.LocationData.Lon);
             * _ = sunCalc.GetRiseAndSet(out DateTime sunriseUTC, out DateTime sunsetUTC);
             */
            configBuilder.LocationData.Sunrise = TimeZoneInfo.ConvertTimeFromUtc(sunriseUTC, TimeZoneInfo.Local);
            configBuilder.LocationData.Sunset  = TimeZoneInfo.ConvertTimeFromUtc(sunsetUTC, TimeZoneInfo.Local);
            Logger.Info($"new sunrise ({configBuilder.LocationData.Sunrise:HH:mm}) and new sunset ({configBuilder.LocationData.Sunset:HH:mm})");
        }
        /// <summary>
        /// Updates the user's geoposition (latitude and longitude) and save to the config
        /// </summary>
        /// <param name="configBuilder">config builder for the AutoDarkModeConfig</param>
        /// <returns></returns>
        public static async Task <bool> UpdateGeoposition(AdmConfigBuilder configBuilder)
        {
            var permission = await Geolocator.RequestAccessAsync();

            var success = false;

            switch (permission)
            {
            case GeolocationAccessStatus.Allowed:
                Geolocator  locator  = new Geolocator();
                Geoposition location = await locator.GetGeopositionAsync();

                BasicGeoposition position = location.Coordinate.Point.Position;
                configBuilder.LocationData.Lon        = position.Longitude;
                configBuilder.LocationData.Lat        = position.Latitude;
                configBuilder.LocationData.LastUpdate = DateTime.Now;
                Logger.Info($"retrieved latitude {position.Latitude} and longitude {position.Longitude}");
                success = true;
                break;

            default:
                configBuilder.Config.Location.Enabled = false;
                Logger.Warn($"no geolocation access, please enable in system settings");
                break;
            }
            UpdateSunTime(configBuilder);
            try
            {
                configBuilder.SaveLocationData();
            }
            catch (Exception e)
            {
                Logger.Error(e, "could not update configuration file while retrieving location");
            }

            return(success);
        }
        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();
        }
        /// <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 Properties = AdmConfigBuilder.Instance();
            RuntimeConfig    rtc        = RuntimeConfig.Instance();

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

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

                case Command.AddAutostart:
                    Logger.Info("signal received: adding service to autostart");
                    RegistryHandler.AddAutoStart();
                    SendResponse(Command.Ok);
                    break;

                case Command.RemoveAutostart:
                    Logger.Info("signal received: removing service from autostart");
                    RegistryHandler.RemoveAutoStart();
                    SendResponse(Command.Ok);
                    break;

                case Command.CreateTask:
                    Logger.Info("signal received: creating win scheduler based time switch task");
                    try
                    {
                        DateTime sunrise = Convert.ToDateTime(Properties.Config.Sunrise);
                        DateTime sunset  = Convert.ToDateTime(Properties.Config.Sunset);
                        if (Properties.Config.Location.Enabled)
                        {
                            LocationHandler.GetSunTimesWithOffset(Properties, out sunrise, out sunset);
                        }
                        TaskSchdHandler.CreateSwitchTask(sunrise.Hour, sunrise.Minute, sunset.Hour, sunset.Minute);
                        SendResponse(Command.Ok);
                    }
                    catch (FormatException e)
                    {
                        Logger.Error(e, "could not create win scheduler tasks");
                        SendResponse(Command.Err);
                        Console.WriteLine(e);
                    }
                    break;

                case Command.RemoveTask:

                    Logger.Info("signal received: removing win tasks");
                    TaskSchdHandler.RemoveTasks();
                    SendResponse(Command.Ok);
                    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(Command.Ok);
                    }
                    else
                    {
                        SendResponse(Command.NoLocAccess);
                    }
                    break;

                case Command.UpdateConfig:
                    Logger.Info("signal received: updating configuration files");
                    try
                    {
                        AdmConfigBuilder.Instance().Load();
                        AdmConfigBuilder.Instance().LoadLocationData();
                        SendResponse(Command.Ok);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "could not read config file");
                        SendResponse(Command.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(Command.Ok);
                    service.Exit(null, null);
                    break;

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

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

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

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

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

                default:
                    Logger.Debug("unknown message received");
                    SendResponse(Command.Err);
                    break;
                }
            });
        }
示例#21
0
        static void Main(string[] args)
        {
            try
            {
                //Set up Logger
                var config    = new NLog.Config.LoggingConfiguration();
                var configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AutoDarkMode");

                // Targets where to log to: File and Console
                var logfile = new NLog.Targets.FileTarget("logfile")
                {
                    FileName = Path.Combine(configDir, "service.log"),
                    Layout   = @"${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level} | " +
                               "${callsite:includeNamespace=False:" +
                               "cleanNamesOfAnonymousDelegates=true:" +
                               "cleanNamesOfAsyncContinuations=true}: ${message} ${exception:separator=|}"
                };
                var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole")
                {
                    Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level} | " +
                             "${callsite:includeNamespace=False:" +
                             "cleanNamesOfAnonymousDelegates=true:" +
                             "cleanNamesOfAsyncContinuations=true}: ${message} ${exception:separator=|}"
                };

                List <string> argsList;
                if (args.Length > 0)
                {
                    argsList = new List <string>(args);
                }
                else
                {
                    argsList = new List <string>();
                }

                // Rules for mapping loggers to targets
                config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
                if (argsList.Contains("/debug"))
                {
                    config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
                }
                else
                {
                    config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile);
                }
                // Apply config
                LogManager.Configuration = config;

                try
                {
                    Directory.CreateDirectory(configDir);
                }
                catch (Exception e)
                {
                    Logger.Fatal(e, "could not create config directory");
                }

                try
                {
                    if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
                    {
                        Logger.Debug("app instance already open");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "failed getting mutex, " + ex.Message);
                    return;
                }

                //Instantiate Runtime config
                GlobalState.Instance();

                //Populate configuration
                AdmConfigBuilder Builder = AdmConfigBuilder.Instance();
                try
                {
                    Builder.Load();
                    Builder.LoadLocationData();
                    Logger.Debug("config builder instantiated and configuration loaded");
                }
                catch (Exception e)
                {
                    Logger.Fatal(e, "could not read config file. shutting down application!");
                    LogManager.Shutdown();
                    Environment.Exit(-1);
                }

                if (Builder.Config.Tunable.Debug && !argsList.Contains("/debug"))
                {
                    config = new NLog.Config.LoggingConfiguration();
                    config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
                    config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
                    LogManager.Configuration = config;
                }

                Logger.Debug("config file loaded");

                //if a path is set to null, set it to the currently actvie theme for convenience reasons
                bool configUpdateNeeded = false;
                if (!Builder.Config.ClassicMode)
                {
                    if (!File.Exists(Builder.Config.DarkThemePath) || Builder.Config.DarkThemePath == null)
                    {
                        Builder.Config.DarkThemePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
                                                                    + @"\Microsoft\Windows\Themes", ThemeHandler.GetCurrentThemeName() + ".theme");
                        configUpdateNeeded = true;
                    }
                    if (!File.Exists(Builder.Config.DarkThemePath) || Builder.Config.LightThemePath == null)
                    {
                        Builder.Config.LightThemePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
                                                                     + @"\Microsoft\Windows\Themes", ThemeHandler.GetCurrentThemeName() + ".theme");
                        configUpdateNeeded = true;
                    }
                    if (configUpdateNeeded)
                    {
                        Logger.Warn("one or more theme paths not set at program start, reinstantiation needed");
                        try
                        {
                            Builder.Save();
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex, "couldn't save configuration file");
                        }
                    }
                }

                int timerMillis = 0;
                if (args.Length != 0)
                {
                    int.TryParse(args[0], out timerMillis);
                }
                timerMillis = (timerMillis == 0) ? TimerFrequency.Short : timerMillis;
                Application.SetHighDpiMode(HighDpiMode.SystemAware);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Service = new Service(timerMillis);
                Application.Run(Service);
            }
            finally
            {
                //clean shutdown
                if (Service != null)
                {
                    Service.Cleanup();
                }
                mutex.Dispose();
            }
        }
示例#22
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();
 }
示例#23
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();
 }
示例#24
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;
                }
            });
        }
 public EventModule(string name, bool fireOnRegistration) : base(name, fireOnRegistration)
 {
     builder = AdmConfigBuilder.Instance();
 }
 /// <summary>
 /// Creates a task scheduler entry invoking the thin server for time based switching.
 /// NOT IMPLEMENTED YET!
 /// </summary>
 /// <param name="configBuilder"></param>
 public static void CreateLocationTask(AdmConfigBuilder configBuilder)
 {
     UpdateSunTime(configBuilder);
     GetSunTimesWithOffset(configBuilder, out DateTime Sunrise, out DateTime Sunset);
     TaskSchdHandler.CreateSwitchTask(Sunrise.Hour, Sunrise.Minute, Sunset.Hour, Sunset.Minute);
 }