From bc162af76ead83edda7a3f245feb43e9c1da5119 Mon Sep 17 00:00:00 2001 From: Vincent Maas Date: Sat, 23 Mar 2024 17:38:37 +0100 Subject: [PATCH] remove all old logic from main form and fix issues --- ColorControl/Forms/OptionsPanel.cs | 15 +- ColorControl/IModulePanel.cs | 1 + ColorControl/MainForm.Designer.cs | 1 - ColorControl/MainForm.cs | 615 ++---------------- ColorControl/MainWorker.cs | 18 +- ColorControl/Program.cs | 21 +- ColorControl/Services/AMD/AmdPanel.cs | 31 +- ColorControl/Services/AMD/AmdService.cs | 11 +- .../Services/Common/ElevationService.cs | 46 +- .../Services/Common/NotifyIconManager.cs | 12 +- ColorControl/Services/Common/ServiceBase.cs | 12 +- .../Services/Common/ServiceManager.cs | 24 +- ColorControl/Services/Common/UpdateManager.cs | 23 +- .../Services/GameLauncher/GamePanel.cs | 53 +- .../Services/GameLauncher/GameService.cs | 9 +- ColorControl/Services/LG/LgPanel.cs | 85 +-- ColorControl/Services/LG/LgService.cs | 66 +- ColorControl/Services/NVIDIA/NvDitherPanel.cs | 4 + ColorControl/Services/NVIDIA/NvInfoPanel.cs | 4 + ColorControl/Services/NVIDIA/NvPanel.cs | 54 +- ColorControl/Services/NVIDIA/NvService.cs | 44 +- ColorControl/Services/Samsung/SamsungPanel.cs | 65 +- .../Services/Samsung/SamsungService.cs | 13 +- Shared/Common/KeyboardShortcutManager.cs | 333 ---------- .../KeyboardShortcutDispatcher.cs | 25 + .../WindowMessageDispatcher.cs | 18 + Shared/Forms/FormUtils.cs | 13 + Shared/Forms/MessageForms.cs | 6 +- Shared/Services/RpcClientService.cs | 5 +- 29 files changed, 478 insertions(+), 1149 deletions(-) delete mode 100644 Shared/Common/KeyboardShortcutManager.cs diff --git a/ColorControl/Forms/OptionsPanel.cs b/ColorControl/Forms/OptionsPanel.cs index 76bb7c3..83812fe 100644 --- a/ColorControl/Forms/OptionsPanel.cs +++ b/ColorControl/Forms/OptionsPanel.cs @@ -1,6 +1,7 @@ using ColorControl.Services.Common; using ColorControl.Shared.Common; using ColorControl.Shared.Contracts; +using ColorControl.Shared.EventDispatcher; using ColorControl.Shared.Forms; using ColorControl.Shared.Services; using ColorControl.XForms; @@ -17,15 +18,17 @@ public partial class OptionsPanel : UserControl private readonly WinApiAdminService _winApiAdminService; private readonly AppContextProvider _appContextProvider; private readonly ElevationService _elevationService; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; private bool _initialized; private Config _config; - public OptionsPanel(WinApiService winApiService, WinApiAdminService winApiAdminService, AppContextProvider appContextProvider, ElevationService elevationService) + public OptionsPanel(WinApiService winApiService, WinApiAdminService winApiAdminService, AppContextProvider appContextProvider, ElevationService elevationService, KeyboardShortcutDispatcher keyboardShortcutDispatcher) { _winApiService = winApiService; _winApiAdminService = winApiAdminService; _appContextProvider = appContextProvider; _elevationService = elevationService; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; _config = appContextProvider.GetAppContext().Config; InitializeComponent(); @@ -118,26 +121,26 @@ public partial class OptionsPanel : UserControl private void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private void btnSetShortcutScreenSaver_Click(object sender, EventArgs e) { var shortcut = edtBlankScreenSaverShortcut.Text.Trim(); - if (!KeyboardShortcutManager.ValidateShortcut(shortcut)) + if (!KeyboardShortcutDispatcher.ValidateShortcut(shortcut)) { return; } _config.ScreenSaverShortcut = shortcut; - KeyboardShortcutManager.RegisterShortcut(MainForm.SHORTCUTID_SCREENSAVER, shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(MainWorker.SHORTCUTID_SCREENSAVER, shortcut); } private void chkFixChromeFonts_CheckedChanged(object sender, EventArgs e) @@ -320,7 +323,7 @@ Currently ColorControl is {(_winApiService.IsAdministrator() ? "" : "not ")}runn _config.UseRawInput = useRawInputField.ValueAsBool; _config.SetMinTmlAndMaxTml = setMinTmlAndMaxTmlField.ValueAsBool; - KeyboardShortcutManager.SetUseRawInput(_config.UseRawInput); + _keyboardShortcutDispatcher.SetUseRawInput(_config.UseRawInput); } private void btnOptionsLog_Click(object sender, EventArgs e) diff --git a/ColorControl/IModulePanel.cs b/ColorControl/IModulePanel.cs index d4ec004..0857f9f 100644 --- a/ColorControl/IModulePanel.cs +++ b/ColorControl/IModulePanel.cs @@ -3,5 +3,6 @@ internal interface IModulePanel { public void UpdateInfo(); + public void Init(); } } diff --git a/ColorControl/MainForm.Designer.cs b/ColorControl/MainForm.Designer.cs index 6df3652..4bb9b5c 100644 --- a/ColorControl/MainForm.Designer.cs +++ b/ColorControl/MainForm.Designer.cs @@ -103,7 +103,6 @@ Activated += MainForm_Activated; Deactivate += MainForm_Deactivate; FormClosing += MainForm_FormClosing; - FormClosed += MainForm_FormClosed; Shown += MainForm_Shown; ResizeBegin += MainForm_ResizeBegin; ResizeEnd += MainForm_ResizeEnd; diff --git a/ColorControl/MainForm.cs b/ColorControl/MainForm.cs index 7d56c5b..5d1a19d 100644 --- a/ColorControl/MainForm.cs +++ b/ColorControl/MainForm.cs @@ -12,18 +12,12 @@ using ColorControl.Shared.EventDispatcher; using ColorControl.Shared.Forms; using ColorControl.Shared.Native; using ColorControl.Shared.Services; -using Linearstar.Windows.RawInput; using Microsoft.Extensions.DependencyInjection; using NLog; using NWin32; using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; using System.Drawing; -using System.IO; using System.Linq; -using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows.Forms; @@ -33,45 +27,30 @@ namespace ColorControl { private static bool SystemShutdown = false; private static bool EndSession = false; - public static int SHORTCUTID_SCREENSAVER = -100; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly PowerEventDispatcher _powerEventDispatcher; private readonly ServiceManager _serviceManager; private readonly IServiceProvider _serviceProvider; - private readonly WinApiAdminService _winApiAdminService; - private readonly WinApiService _winApiService; private readonly ElevationService _elevationService; - private string _dataDir; private NvPanel _nvPanel; public NotifyIconManager _notifyIconManager; - private bool _initialized = false; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; + private readonly UpdateManager _updateManager; private Config _config; private bool _setVisibleCalled = false; private LgPanel _lgPanel; private SamsungPanel _samsungPanel; - private StartUpParams StartUpParams { get; } - public string _lgTabMessage { get; private set; } - private AmdPanel _amdPanel; private bool _skipResize; - private bool _checkedForUpdates = false; - private string _updateHtmlUrl; - private string _downloadUrl; private GamePanel _gamePanel; - private IntPtr _screenStateNotify; - - private Dictionary _shortcuts = new(); - private Dictionary> _modules = new(); - - public MainForm(AppContextProvider appContextProvider, PowerEventDispatcher powerEventDispatcher, ServiceManager serviceManager, - IServiceProvider serviceProvider, WinApiAdminService winApiAdminService, WinApiService winApiService, ElevationService elevationService, NotifyIconManager notifyIconManager) + public MainForm(AppContextProvider appContextProvider, ServiceManager serviceManager, + IServiceProvider serviceProvider, ElevationService elevationService, NotifyIconManager notifyIconManager, KeyboardShortcutDispatcher keyboardShortcutDispatcher, UpdateManager updateManager) { InitializeComponent(); @@ -79,53 +58,24 @@ namespace ColorControl var appContext = appContextProvider.GetAppContext(); - if (appContext.MainHandle == 0) - { - appContext.MainHandle = Handle; - } - KeyboardShortcutManager.MainHandle = Handle; - - StartUpParams = appContext.StartUpParams; - appContext.SynchronizationContext = AsyncOperationManager.SynchronizationContext; - - _powerEventDispatcher = powerEventDispatcher; _serviceManager = serviceManager; _serviceProvider = serviceProvider; - _winApiAdminService = winApiAdminService; - _winApiService = winApiService; _elevationService = elevationService; _notifyIconManager = notifyIconManager; - _dataDir = Program.DataDir; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; + _updateManager = updateManager; _config = Program.Config; Text = appContext.ApplicationTitleAdmin; LoadConfig(); - KeyboardShortcutManager.SetUseRawInput(_config.UseRawInput); - - LoadModules(); - MessageForms.MainForm = this; _notifyIconManager.Build(); - InitShortcut(SHORTCUTID_SCREENSAVER, _config.ScreenSaverShortcut, StartScreenSaver); - InitModules(); - // Auto-apply fix if desired but not currently installed - if (_config.FixChromeFonts && _winApiService.IsChromeInstalled() && !_winApiService.IsChromeFixInstalled()) - { - _winApiAdminService.InstallChromeFix(true, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); - } - - _screenStateNotify = WinApi.RegisterPowerSettingNotification(appContext.MainHandle, ref Utils.GUID_CONSOLE_DISPLAY_STATE, 0); - - //Scale(new SizeF(1.25F, 1.25F)); - - _initialized = true; - Task.Run(AfterInitialized); if (_config.UseDarkMode) @@ -134,215 +84,52 @@ namespace ColorControl } } - private void LoadModules() - { - _modules.Add("NVIDIA controller", InitNvService); - _modules.Add("AMD controller", InitAmdService); - _modules.Add("LG controller", InitLgService); - _modules.Add("Samsung controller", InitSamsungService); - _modules.Add("Game launcher", InitGameService); - - foreach (var keyValue in _modules) - { - var existingModule = _config.Modules.FirstOrDefault(m => m.DisplayName == keyValue.Key); - - if (existingModule == null) - { - existingModule = new Module { DisplayName = keyValue.Key, IsActive = true, InitAction = keyValue.Value }; - _config.Modules.Add(existingModule); - } - else - { - existingModule.InitAction = keyValue.Value; - } - } - - var names = _modules.Select(m => m.Key).ToList(); - - _config.Modules = _config.Modules.OrderBy(m => names.IndexOf(m.DisplayName)).ToList(); - } - private void InitModules() { - var tabIndex = 0; - var _ = tcMain.Handle; - foreach (var module in _config.Modules.Where(m => m.IsActive)) - { - var control = module.InitAction(); - - if (control == null) - { - continue; - } - - var tabPage = new TabPage(module.DisplayName); - tcMain.TabPages.Insert(tabIndex, tabPage); - //tcMain.TabPages.Add(tabPage); - - tabPage.Controls.Add(control); - - control.Size = tabPage.ClientSize; - control.BackColor = SystemColors.Window; - - tabIndex++; - } + _nvPanel = InitPanel("NVIDIA controller"); + _amdPanel = InitPanel("AMD controller"); + _lgPanel = InitPanel("LG controller"); + _samsungPanel = InitPanel("Samsung controller"); + _gamePanel = InitPanel("Game launcher"); tcMain.SelectedIndex = 0; } - private UserControl InitNvService() + private T InitPanel(string displayName) where T : UserControl, IModulePanel { + var module = _config.Modules.FirstOrDefault(m => m.IsActive && m.DisplayName == displayName); + if (module == null) + { + return default; + } + try { - //throw new Exception("bla"); - Logger.Debug("Initializing NVIDIA..."); - var appContextProvider = _serviceProvider.GetRequiredService(); - _serviceManager.NvService = _serviceProvider.GetRequiredService(); - Logger.Debug("Initializing NVIDIA...Done."); + var panel = _serviceProvider.GetRequiredService(); + panel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - var rpcService = _serviceProvider.GetRequiredService(); - var winAdminService = _serviceProvider.GetRequiredService(); + panel.Init(); - _nvPanel = new NvPanel(_serviceManager.NvService, _notifyIconManager.NotifyIcon, appContextProvider, rpcService, winAdminService); - _nvPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + var tabPage = new TabPage(module.DisplayName); + tcMain.TabPages.Insert(tcMain.TabPages.Count - 2, tabPage); - InitShortcut(NvPanel.SHORTCUTID_NVQA, _config.NvQuickAccessShortcut, _serviceManager.NvService.ToggleQuickAccessForm); + tabPage.Controls.Add(panel); - return _nvPanel; + panel.Size = tabPage.ClientSize; + panel.BackColor = SystemColors.Window; + + return panel; } catch (Exception ex) { - //Logger.Error("Error initializing NvService: " + e.ToLogString()); - Logger.Debug($"No NVIDIA device detected: {ex.ToLogString()}"); + Logger.Debug($"Error creating panel {typeof(T).Name}: {ex.ToLogString()}"); return null; } } - private UserControl InitAmdService() - { - try - { - _serviceManager.AmdService = _serviceProvider.GetRequiredService(); - - var appContextProvider = _serviceProvider.GetRequiredService(); - _amdPanel = new AmdPanel(_serviceManager.AmdService, _notifyIconManager.NotifyIcon, appContextProvider); - _amdPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - - InitShortcut(AmdPanel.SHORTCUTID_AMDQA, _config.AmdQuickAccessShortcut, _serviceManager.AmdService.ToggleQuickAccessForm); - - return _amdPanel; - } - catch (Exception) - { - //Logger.Error("Error initializing AmdService: " + e.ToLogString()); - Logger.Debug("No AMD device detected"); - - return null; - } - } - - private UserControl InitGameService() - { - try - { - _serviceManager.GameService = _serviceProvider.GetRequiredService(); - - var appContextProvider = _serviceProvider.GetRequiredService(); - _gamePanel = new GamePanel(_serviceManager.GameService, _serviceManager.NvService, _serviceManager.AmdService, _serviceManager.LgService, _serviceManager.SamsungService, _notifyIconManager.NotifyIcon, appContextProvider); - _gamePanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - - InitShortcut(GamePanel.SHORTCUTID_GAMEQA, _config.GameQuickAccessShortcut, _serviceManager.GameService.ToggleQuickAccessForm); - - return _gamePanel; - } - catch (Exception e) - { - Logger.Error("Error initializing GameService: " + e.ToLogString()); - - return null; - } - } - - private void InitShortcut(int shortcutId, string shortcut, Action action) - { - _shortcuts.Add(shortcutId, action); - - if (!string.IsNullOrEmpty(shortcut)) - { - KeyboardShortcutManager.RegisterShortcut(shortcutId, shortcut); - } - } - - private UserControl InitLgService() - { - try - { - _serviceManager.LgService = _serviceProvider.GetRequiredService(); - - var appContextProvider = _serviceProvider.GetRequiredService(); - _lgPanel = new LgPanel(_serviceManager.LgService, _serviceManager.NvService, _serviceManager.AmdService, _notifyIconManager.NotifyIcon, _powerEventDispatcher, appContextProvider); - _lgPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - - _lgPanel.Init(); - - InitShortcut(LgPanel.SHORTCUTID_GAMEBAR, _serviceManager.LgService.Config.GameBarShortcut, _lgPanel.ToggleGameBar); - InitShortcut(LgPanel.SHORTCUTID_LGQA, _serviceManager.LgService.Config.QuickAccessShortcut, _serviceManager.LgService.ToggleQuickAccessForm); - - return _lgPanel; - } - catch (Exception e) - { - Logger.Error("Error initializing LgService: " + e.ToLogString()); - - return null; - } - } - - private UserControl InitSamsungService() - { - try - { - _serviceManager.SamsungService = _serviceProvider.GetRequiredService(); - - var appContextProvider = _serviceProvider.GetRequiredService(); - _samsungPanel = new SamsungPanel(_serviceManager.SamsungService, _serviceManager.NvService, _serviceManager.AmdService, _powerEventDispatcher, appContextProvider); - _samsungPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - - _samsungPanel.Init(); - - InitShortcut(SamsungPanel.SHORTCUTID_SAMSUNGQA, _serviceManager.SamsungService.Config.QuickAccessShortcut, _serviceManager.SamsungService.ToggleQuickAccessForm); - - return _samsungPanel; - } - catch (Exception e) - { - Logger.Error("Error initializing SamsungService: " + e.ToLogString()); - - return null; - } - } - - private void OpenForm(object sender, EventArgs e) - { - Show(); - WindowState = FormWindowState.Normal; - Activate(); - } - - void Exit(object sender, EventArgs e) - { - Program.UserExit = true; - Close(); - } - - void Restart(object sender, EventArgs e) - { - Program.Restart(); - } - public void OpenForm() { Show(); @@ -350,20 +137,6 @@ namespace ColorControl Activate(); } - private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e) - { - Show(); - WindowState = FormWindowState.Normal; - } - - private void trayIconBalloonTip_Clicked(object sender, EventArgs e) - { - if (_updateHtmlUrl != null) - { - _winApiAdminService.StartProcess(_updateHtmlUrl); - } - } - private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (!(SystemShutdown || EndSession || Program.UserExit) && _config.MinimizeOnClose) @@ -380,7 +153,7 @@ namespace ColorControl { Logger.Debug($"MainForm_FormClosing: SystemShutdown"); - _powerEventDispatcher.SendEvent(PowerEventDispatcher.Event_Shutdown); + //_powerEventDispatcher.SendEvent(PowerEventDispatcher.Event_Shutdown); } } @@ -397,79 +170,9 @@ namespace ColorControl SaveConfig(); } - private Control FindFocusedControl() - { - ContainerControl container = this; - Control control = null; - while (container != null) - { - control = container.ActiveControl; - container = control as ContainerControl; - } - - return control; - } - - private bool IsShortcutControlFocused() - { - if (Form.ActiveForm?.GetType().Name.Equals("MessageForm") == true) - { - return true; - } - var control = FindFocusedControl(); - return control?.Name.Contains("Shortcut") ?? false; - } - protected override void WndProc(ref Message m) { - // 5. Catch when a HotKey is pressed ! - if (m.Msg == NativeConstants.WM_HOTKEY && !IsShortcutControlFocused()) - { - var id = (int)m.WParam; - - if (_shortcuts.TryGetValue(id, out var action)) - { - action(); - } - // 6. Handle what will happen once a respective hotkey is pressed - else - { - var preset = _serviceManager.NvService?.GetPresets().FirstOrDefault(x => x.id == id); - if (preset != null) - { - _serviceManager.NvService?.ApplyPresetUi(preset); - } - - var amdPreset = _serviceManager.AmdService?.GetPresets().FirstOrDefault(x => x.id == id); - if (amdPreset != null) - { - _serviceManager.AmdService?.ApplyPresetUi(amdPreset); - } - - var lgPreset = _serviceManager.LgService?.GetPresets().FirstOrDefault(x => x.id == id); - if (lgPreset != null) - { - _serviceManager.LgService?.ApplyPresetUi(lgPreset); - } - - var samsungPreset = _serviceManager.SamsungService?.GetPresets().FirstOrDefault(x => x.id == id); - if (samsungPreset != null) - { - _serviceManager.SamsungService?.ApplyPresetUi(samsungPreset); - } - } - } - else if (m.Msg == NativeConstants.WM_INPUT) - { - // Create an RawInputData from the handle stored in lParam. - var data = RawInputData.FromHandle(m.LParam); - - if (data is RawInputKeyboardData keyboard) - { - KeyboardShortcutManager.HandleRawKeyboardInput(keyboard); - } - } - else if (m.Msg == NativeConstants.WM_QUERYENDSESSION) + if (m.Msg == NativeConstants.WM_QUERYENDSESSION) { SystemShutdown = true; } @@ -480,45 +183,12 @@ namespace ColorControl else if (m.Msg == Utils.WM_BRINGTOFRONT) { Logger.Debug("WM_BRINGTOFRONT message received, opening form"); - OpenForm(this, EventArgs.Empty); - } - else if (m.Msg == NativeConstants.WM_POWERBROADCAST) - { - //Logger.Debug($"WM_POWERBROADCAST: {m.WParam.ToInt32()}"); - - if (m.WParam.ToInt32() == WinApi.PBT_POWERSETTINGCHANGE) - { - var ps = Marshal.PtrToStructure(m.LParam); - - var power = (WindowsMonitorPowerSetting)ps.Data; - - Logger.Debug($"PBT_POWERSETTINGCHANGE: {power}"); - - _powerEventDispatcher.SendEvent(power == WindowsMonitorPowerSetting.Off ? PowerEventDispatcher.Event_MonitorOff : PowerEventDispatcher.Event_MonitorOn); - } + OpenForm(); } base.WndProc(ref m); } - private void StartScreenSaver() - { - var screenSaver = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "scrnsave.scr"); - Process.Start("explorer.exe", screenSaver); - } - - private void MainForm_FormClosed(object sender, FormClosedEventArgs e) - { - // Hide tray icon, otherwise it will remain shown until user mouses over it - _notifyIconManager.HideIcon(); - - if (_screenStateNotify != IntPtr.Zero) - { - WinApi.UnregisterPowerSettingNotification(_screenStateNotify); - _screenStateNotify = IntPtr.Zero; - } - } - private void MainForm_Resize(object sender, EventArgs e) { if (_skipResize) @@ -568,66 +238,24 @@ namespace ColorControl private async void MainForm_Shown(object sender, EventArgs e) { InitSelectedTab(); - await CheckForUpdates(); - CheckElevationMethod(); - } - - private void CheckElevationMethod() - { - if (_winApiService.IsAdministrator()) - { - return; - } - - if (_config.ElevationMethodAsked) - { - if (Debugger.IsAttached) - { - return; - } - - if (_config.ElevationMethod == ElevationMethod.UseService && !_winApiService.IsServiceInstalled() && - (MessageForms.QuestionYesNo("The elevation method is set to Windows Service but it is not installed. Do you want to install it now?") == DialogResult.Yes)) - { - _winApiAdminService.InstallService(); - } - else if (_config.ElevationMethod == ElevationMethod.UseService && !_winApiService.IsServiceRunning() && - (MessageForms.QuestionYesNo("The elevation method is set to Windows Service but it is not running. Do you want to start it now?") == DialogResult.Yes)) - { - _winApiAdminService.StartService(); - } - - return; - } - - var result = MessageForms.QuestionYesNo(Utils.ELEVATION_MSG + @" - -Do you want to install and start the Windows Service now? You can always change this on the Options-tab page. - -NOTE: installing the service may cause a User Account Control popup."); - if (result == DialogResult.Yes) - { - _elevationService.SetElevationMethod(ElevationMethod.UseService); - } - - _config.ElevationMethodAsked = true; + _elevationService.CheckElevationMethod(); } protected override void SetVisibleCore(bool value) { - if (!_setVisibleCalled && _config.StartMinimized && !Debugger.IsAttached) - { - _setVisibleCalled = true; - if (_config.MinimizeToTray) - { - value = false; - } - else - { - WindowState = FormWindowState.Minimized; - } - } + //if (!_setVisibleCalled && _config.StartMinimized && !Debugger.IsAttached) + //{ + // _setVisibleCalled = true; + // if (_config.MinimizeToTray) + // { + // value = false; + // } + // else + // { + // WindowState = FormWindowState.Minimized; + // } + //} if (!IsDisposed) { base.SetVisibleCore(value); @@ -695,8 +323,6 @@ NOTE: installing the service may cause a User Account Control popup."); private async Task AfterInitialized() { - await _powerEventDispatcher.SendEventAsync(PowerEventDispatcher.Event_Startup); - if (_nvPanel != null) { await _nvPanel.AfterInitialized(); @@ -711,148 +337,11 @@ NOTE: installing the service may cause a User Account Control popup."); //} } - private async Task CheckForUpdates() - { - if (!_config.CheckForUpdates || _checkedForUpdates || Debugger.IsAttached) - { - return; - } - - _checkedForUpdates = true; - - await Utils.GetRestJsonAsync("https://api.github.com/repos/maassoft/colorcontrol/releases/latest", InitHandleCheckForUpdates); - } - - private void InitHandleCheckForUpdates(dynamic latest) - { - BeginInvoke(() => HandleCheckForUpdates(latest)); - } - - private void HandleCheckForUpdates(dynamic latest) - { - if (latest?.tag_name == null) - { - return; - } - - var currentVersion = Application.ProductVersion; - var cvParts = currentVersion.Split("."); - - var newVersion = (string)latest.tag_name.Value.Substring(1); - var nvParts = newVersion.Split("."); - - bool CompareVersions() - { - var result = true; - var aNumberIsLarger = false; - - for (var i = 0; i < nvParts.Length; i++) - { - var part = Utils.ParseInt(nvParts[i]); - var cvPart = Utils.ParseInt(cvParts[i]); - - if (part > cvPart) - { - aNumberIsLarger = true; - break; - } - - if (part == cvPart) - { - continue; - } - - result = false; - break; - } - - return result && aNumberIsLarger; - } - - if (nvParts.Length != cvParts.Length || CompareVersions()) - { - _updateHtmlUrl = latest.html_url.Value; - - if (latest.assets != null && _winApiService.IsServiceRunning()) - { - var asset = latest.assets[0]; - _downloadUrl = asset.browser_download_url.Value; - - if (_config.AutoInstallUpdates) - { - InstallUpdate(_downloadUrl); - - return; - } - - btnUpdate.Visible = true; - - if (_notifyIconManager.NotifyIcon.Visible) - { - _notifyIconManager.NotifyIcon.ShowBalloonTip(5000, "Update available", $"Version {newVersion} is available. Click on the Update-button to update", ToolTipIcon.Info); - } - else - { - MessageForms.InfoOk($"New version {newVersion} is available. Click on the Update-button to update", "Update available", $"https://github.com/Maassoft/ColorControl/releases/tag/v{newVersion}"); - } - - return; - } - - if (_notifyIconManager.NotifyIcon.Visible) - { - _notifyIconManager.NotifyIcon.ShowBalloonTip(5000, "Update available", $"Version {newVersion} is available. Click to open the GitHub page", ToolTipIcon.Info); - } - else - { - MessageForms.InfoOk($"New version {newVersion} is available. Click on the Help-button to open the GitHub page.", "Update available", $"https://github.com/Maassoft/ColorControl/releases/tag/v{newVersion}"); - } - } - } - - private void InstallUpdate(string downloadUrl) - { - var message = new SvcInstallUpdateMessage - { - DownloadUrl = downloadUrl, - ClientPath = new FileInfo(Application.ExecutablePath).Directory.FullName - }; - - var result = PipeUtils.SendMessage(message, 30000); - - if (result != null && !result.Result) - { - MessageForms.ErrorOk($"Error while updating: {result.ErrorMessage}"); - - return; - } - - PipeUtils.SendMessage(SvcMessageType.RestartAfterUpdate); - - if (MessageForms.QuestionYesNo("Update installed successfully. Do you want to restart the application?") == DialogResult.Yes) - { - Program.Restart(); - } - else - { - _downloadUrl = null; - btnUpdate.Visible = true; - } - } - private void MainForm_Deactivate(object sender, EventArgs e) { GlobalSave(); } - private bool ShortCutExists(string shortcut, int presetId = 0) - { - return - (_serviceManager.NvService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false) || - (_serviceManager.AmdService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false) || - (_serviceManager.LgService?.GetPresets().Any(x => x.id != presetId && shortcut.Equals(x.shortcut)) ?? false); - } - private void MainForm_ResizeBegin(object sender, EventArgs e) { SuspendLayout(); @@ -890,12 +379,7 @@ NOTE: installing the service may cause a User Account Control popup."); private void btnUpdate_Click(object sender, EventArgs e) { - if (_downloadUrl != null) - { - InstallUpdate(_downloadUrl); - - return; - } + _updateManager.InstallUpdate(); Program.Restart(); } @@ -903,20 +387,19 @@ NOTE: installing the service may cause a User Account Control popup."); internal void CloseForRestart() { Hide(); - _notifyIconManager.NotifyIcon.Visible = false; } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if ((keyData == (Keys.Control | Keys.PageUp) || keyData == (Keys.Control | Keys.PageDown)) && IsShortcutControlFocused()) + if ((keyData == (Keys.Control | Keys.PageUp) || keyData == (Keys.Control | Keys.PageDown)) && KeyboardShortcutDispatcher.IsShortcutControlFocused()) { - var control = FindFocusedControl() as TextBox; + var control = this.FindFocusedControl() as TextBox; if (control != null) { var keyEvent = new KeyEventArgs(keyData); - control.Text = KeyboardShortcutManager.FormatKeyboardShortcut(keyEvent); + control.Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(keyEvent); } return true; diff --git a/ColorControl/MainWorker.cs b/ColorControl/MainWorker.cs index f522b67..290b87d 100644 --- a/ColorControl/MainWorker.cs +++ b/ColorControl/MainWorker.cs @@ -98,11 +98,12 @@ internal class MainWorker _screenStateNotify = WinApi.RegisterPowerSettingNotification(_windowMessageDispatcher.MessageForm.Handle, ref Utils.GUID_CONSOLE_DISPLAY_STATE, 0); _keyboardShortcutDispatcher.SetUseRawInput(_config.UseRawInput); - - _serviceManager.LoadModules(); + MessageForms.KeyboardShortcutDispatcher = _keyboardShortcutDispatcher; _notifyIconManager.Build(); + _serviceManager.LoadModules(); + // Auto-apply fix if desired but not currently installed if (_config.FixChromeFonts && _winApiService.IsChromeInstalled() && !_winApiService.IsChromeFixInstalled()) { @@ -128,9 +129,14 @@ internal class MainWorker _startupSent = true; - var _ = _powerEventDispatcher.SendEventAsync(PowerEventDispatcher.Event_Startup); + _ = _powerEventDispatcher.SendEventAsync(PowerEventDispatcher.Event_Startup); - var x = _updateManager.CheckForUpdates(); + _ = _updateManager.CheckForUpdates(); + + if (!_config.StartMinimized /*|| Debugger.IsAttached*/) + { + Program.OpenMainForm(); + } } private void HandlePowerBroadcastEvent(object sender, WindowMessageEventArgs e) @@ -151,12 +157,16 @@ internal class MainWorker { if (_queryEndSession) { + Logger.Debug($"MainWorker: SystemShutdown"); + _powerEventDispatcher.SendEvent(PowerEventDispatcher.Event_Shutdown); } } private void HandleQueryEndSessionEvent(object sender, WindowMessageEventArgs e) { + Logger.Debug("MainWorker: QueryEndSession"); + _queryEndSession = true; } diff --git a/ColorControl/Program.cs b/ColorControl/Program.cs index 71fae67..6c2f7c3 100644 --- a/ColorControl/Program.cs +++ b/ColorControl/Program.cs @@ -40,7 +40,6 @@ namespace ColorControl public static bool IsRestarting { get; private set; } public static bool UserExit = false; - public static bool UseWorker = true; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static Mutex _mutex; @@ -158,19 +157,9 @@ namespace ColorControl } } - if (UseWorker) - { - var worker = ServiceProvider.GetRequiredService(); + var worker = ServiceProvider.GetRequiredService(); - await worker.DoWork(); - - //Application.Run(); - } - else - { - _mainForm = ServiceProvider.GetRequiredService(); - Application.Run(_mainForm); - } + await worker.DoWork(); if (Debugger.IsAttached && !IsRestarting) { @@ -298,6 +287,12 @@ namespace ColorControl services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); }); } private static async Task RunService(string[] args) diff --git a/ColorControl/Services/AMD/AmdPanel.cs b/ColorControl/Services/AMD/AmdPanel.cs index 3be1ac4..6a8f323 100644 --- a/ColorControl/Services/AMD/AmdPanel.cs +++ b/ColorControl/Services/AMD/AmdPanel.cs @@ -1,6 +1,7 @@ using ATI.ADL; -using ColorControl.Shared.Common; +using ColorControl.Services.Common; using ColorControl.Shared.Contracts; +using ColorControl.Shared.EventDispatcher; using ColorControl.Shared.Forms; using ColorControl.Shared.Native; using ColorControl.Shared.Services; @@ -17,19 +18,19 @@ namespace ColorControl.Services.AMD { public partial class AmdPanel : UserControl, IModulePanel { - public static readonly int SHORTCUTID_AMDQA = -201; - private readonly AmdService _amdService; - private readonly NotifyIcon _trayIcon; + private readonly NotifyIconManager _notifyIconManager; private readonly AppContextProvider _appContextProvider; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; private Config _config; private string _lastDisplayRefreshRates = string.Empty; - internal AmdPanel(AmdService amdService, NotifyIcon trayIcon, AppContextProvider appContextProvider) + internal AmdPanel(AmdService amdService, NotifyIconManager notifyIconManager, AppContextProvider appContextProvider, KeyboardShortcutDispatcher keyboardShortcutDispatcher) { _amdService = amdService; - _trayIcon = trayIcon; + _notifyIconManager = notifyIconManager; _appContextProvider = appContextProvider; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; _config = Shared.Common.GlobalContext.CurrentContext.Config; InitializeComponent(); @@ -55,7 +56,7 @@ namespace ColorControl.Services.AMD foreach (var preset in _amdService.GetPresets()) { AddOrUpdateItemAmd(preset); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } } @@ -112,7 +113,7 @@ namespace ColorControl.Services.AMD text += "\n" + displayInfo.InfoLine; } - FormUtils.SetNotifyIconText(_trayIcon, text); + _notifyIconManager.SetText(text); } private void AddOrUpdateItemAmd(AmdPreset preset = null) @@ -171,12 +172,12 @@ namespace ColorControl.Services.AMD private void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private AmdPreset GetSelectedAmdPreset() @@ -253,7 +254,7 @@ namespace ColorControl.Services.AMD { var shortcut = edtAmdShortcut.Text.Trim(); - if (!KeyboardShortcutManager.ValidateShortcut(shortcut)) + if (!KeyboardShortcutDispatcher.ValidateShortcut(shortcut)) { return; } @@ -280,7 +281,7 @@ namespace ColorControl.Services.AMD AddOrUpdateItemAmd(); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } private void btnCloneAmd_Click(object sender, EventArgs e) @@ -584,12 +585,16 @@ namespace ColorControl.Services.AMD _config.AmdQuickAccessShortcut = shortcut; - KeyboardShortcutManager.RegisterShortcut(SHORTCUTID_AMDQA, _config.AmdQuickAccessShortcut); + _keyboardShortcutDispatcher.RegisterShortcut(AmdService.SHORTCUTID_AMDQA, _config.AmdQuickAccessShortcut); } private void lvLgPresets_ColumnClick(object sender, ColumnClickEventArgs e) { FormUtils.ListViewSort(sender, e); } + + public void Init() + { + } } } diff --git a/ColorControl/Services/AMD/AmdService.cs b/ColorControl/Services/AMD/AmdService.cs index 1591d1e..4b1a9c9 100644 --- a/ColorControl/Services/AMD/AmdService.cs +++ b/ColorControl/Services/AMD/AmdService.cs @@ -22,11 +22,11 @@ namespace ColorControl.Services.AMD private ADLDisplayInfo _currentDisplay; + public static readonly int SHORTCUTID_AMDQA = -201; + public AmdService(AppContextProvider appContextProvider) : base(appContextProvider) { LoadPresets(); - - SetShortcuts(-201, _appContextProvider.GetAppContext().Config.AmdQuickAccessShortcut); } public static async Task ExecutePresetAsync(string idOrName) @@ -53,6 +53,13 @@ namespace ColorControl.Services.AMD } } + public override void InstallEventHandlers() + { + base.InstallEventHandlers(); + + SetShortcuts(SHORTCUTID_AMDQA, _appContextProvider.GetAppContext().Config.AmdQuickAccessShortcut); + } + protected override List GetDefaultPresets() { return AmdPreset.GetDefaultPresets(); diff --git a/ColorControl/Services/Common/ElevationService.cs b/ColorControl/Services/Common/ElevationService.cs index 0d8c0c7..c0cdbb0 100644 --- a/ColorControl/Services/Common/ElevationService.cs +++ b/ColorControl/Services/Common/ElevationService.cs @@ -1,6 +1,9 @@ -using ColorControl.Shared.Contracts; +using ColorControl.Shared.Common; +using ColorControl.Shared.Contracts; using ColorControl.Shared.Forms; using ColorControl.Shared.Services; +using System.Diagnostics; +using System.Windows.Forms; namespace ColorControl.Services.Common; @@ -40,6 +43,47 @@ public class ElevationService _winApiAdminService.RegisterTask(Program.TS_TASKNAME, enabled, _config.ElevationMethod == ElevationMethod.RunAsAdmin ? Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest : Microsoft.Win32.TaskScheduler.TaskRunLevel.LUA); } + public void CheckElevationMethod() + { + if (_winApiService.IsAdministrator()) + { + return; + } + + if (_config.ElevationMethodAsked) + { + if (Debugger.IsAttached) + { + return; + } + + if (_config.ElevationMethod == ElevationMethod.UseService && !_winApiService.IsServiceInstalled() && + (MessageForms.QuestionYesNo("The elevation method is set to Windows Service but it is not installed. Do you want to install it now?") == DialogResult.Yes)) + { + _winApiAdminService.InstallService(); + } + else if (_config.ElevationMethod == ElevationMethod.UseService && !_winApiService.IsServiceRunning() && + (MessageForms.QuestionYesNo("The elevation method is set to Windows Service but it is not running. Do you want to start it now?") == DialogResult.Yes)) + { + _winApiAdminService.StartService(); + } + + return; + } + + var result = MessageForms.QuestionYesNo(Utils.ELEVATION_MSG + @" + +Do you want to install and start the Windows Service now? You can always change this on the Options-tab page. + +NOTE: installing the service may cause a User Account Control popup."); + if (result == DialogResult.Yes) + { + SetElevationMethod(ElevationMethod.UseService); + } + + _config.ElevationMethodAsked = true; + } + private bool SetElevationMethodNone(bool startAfterLoginChecked = false) { if (startAfterLoginChecked) diff --git a/ColorControl/Services/Common/NotifyIconManager.cs b/ColorControl/Services/Common/NotifyIconManager.cs index d37b719..108588d 100644 --- a/ColorControl/Services/Common/NotifyIconManager.cs +++ b/ColorControl/Services/Common/NotifyIconManager.cs @@ -54,10 +54,11 @@ public class NotifyIconManager { Icon = Resources.AppIcon, ContextMenuStrip = new ContextMenuStrip(), - Visible = _config.MinimizeToTray, - Text = _appContextProvider.GetAppContext().ApplicationTitleAdmin + Visible = _config.MinimizeToTray }; + SetText(); + NotifyIcon.ContextMenuStrip.Items.AddRange(new ToolStripItem[] { _nvTrayMenu, _novideoTrayMenu, @@ -230,4 +231,11 @@ public class NotifyIconManager await _serviceManager.SamsungService?.ApplyPresetUi(preset); } + + internal void SetText(string text = null) + { + var fullText = $"{_appContextProvider.GetAppContext().ApplicationTitleAdmin}{(text == null ? "" : $"\n{text}")}"; + + FormUtils.SetNotifyIconText(NotifyIcon, fullText.Trim()); + } } diff --git a/ColorControl/Services/Common/ServiceBase.cs b/ColorControl/Services/Common/ServiceBase.cs index 1c229cc..cc45ff6 100644 --- a/ColorControl/Services/Common/ServiceBase.cs +++ b/ColorControl/Services/Common/ServiceBase.cs @@ -112,15 +112,15 @@ namespace ColorControl.Services.Common protected void SetShortcuts(int quickAccessShortcutId = 0, string shortcut = null) { - if (!Program.UseWorker) + _quickAccessShortcutId = quickAccessShortcutId; + + var keyboardShortcutDispatcher = _appContextProvider.GetAppContext().ServiceProvider.GetService(); + + if (keyboardShortcutDispatcher == null) { return; } - _quickAccessShortcutId = quickAccessShortcutId; - - var keyboardShortcutDispatcher = _appContextProvider.GetAppContext().ServiceProvider.GetRequiredService(); - if (quickAccessShortcutId != 0 && !shortcut.IsNullOrWhiteSpace()) { keyboardShortcutDispatcher.RegisterShortcut(quickAccessShortcutId, shortcut); @@ -294,7 +294,7 @@ namespace ColorControl.Services.Common return; } - Logger.Debug($"Executing event presets count: {triggerPresets.Count}"); + Logger.Debug($"Executing event: {string.Join(',', triggerTypes)}, presets count: {triggerPresets.Count}"); foreach (var preset in triggerPresets) { diff --git a/ColorControl/Services/Common/ServiceManager.cs b/ColorControl/Services/Common/ServiceManager.cs index 6e08d6a..3890689 100644 --- a/ColorControl/Services/Common/ServiceManager.cs +++ b/ColorControl/Services/Common/ServiceManager.cs @@ -37,17 +37,17 @@ public class ServiceManager public void LoadModules() { - AddModule("NVIDIA controller"); - AddModule("AMD controller"); - AddModule("LG controller"); - AddModule("Samsung controller"); - AddModule("Game launcher"); + NvService = AddModule("NVIDIA controller"); + AmdService = AddModule("AMD controller"); + LgService = AddModule("LG controller"); + SamsungService = AddModule("Samsung controller"); + GameService = AddModule("Game launcher"); var names = Modules.Select(m => m.Key).ToList(); _config.Modules = _config.Modules.OrderBy(m => names.IndexOf(m.DisplayName)).ToList(); } - private void AddModule(string displayName) where T : class, IServiceBase + private T AddModule(string displayName) where T : class, IServiceBase { var moduleEx = new ModuleEx { DisplayName = displayName }; Modules.Add(displayName, moduleEx); @@ -66,16 +66,10 @@ public class ServiceManager service?.InstallEventHandlers(); - object _ = service switch - { - NvService nvService => NvService = nvService, - AmdService amdService => AmdService = amdService, - LgService lgService => LgService = lgService, - SamsungService samsungService => SamsungService = samsungService, - GameService gameService => GameService = gameService, - _ => throw new InvalidOperationException("Unknown module") - }; + return service; } + + return default; } public async Task HandleExternalServiceAsync(string serviceName, string[] parameters) diff --git a/ColorControl/Services/Common/UpdateManager.cs b/ColorControl/Services/Common/UpdateManager.cs index 0073845..9524bef 100644 --- a/ColorControl/Services/Common/UpdateManager.cs +++ b/ColorControl/Services/Common/UpdateManager.cs @@ -2,6 +2,7 @@ using ColorControl.Shared.Contracts; using ColorControl.Shared.Forms; using ColorControl.Shared.Services; +using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; @@ -15,21 +16,31 @@ public class UpdateManager private readonly ServiceManager _serviceManager; private readonly NotifyIconManager _notifyIconManager; private readonly WinApiService _winApiService; + private readonly WinApiAdminService _winApiAdminService; private readonly Config _config; private bool _checkedForUpdates; private string _updateHtmlUrl; private string _downloadUrl; - public UpdateManager(AppContextProvider appContextProvider, ServiceManager serviceManager, NotifyIconManager notifyIconManager, WinApiService winApiService) + public UpdateManager(AppContextProvider appContextProvider, ServiceManager serviceManager, NotifyIconManager notifyIconManager, WinApiService winApiService, WinApiAdminService winApiAdminService) { _appContextProvider = appContextProvider; _serviceManager = serviceManager; _notifyIconManager = notifyIconManager; _winApiService = winApiService; + _winApiAdminService = winApiAdminService; _config = appContextProvider.GetAppContext().Config; } + private void trayIconBalloonTip_Clicked(object sender, EventArgs e) + { + if (_updateHtmlUrl != null) + { + _winApiAdminService.StartProcess(_updateHtmlUrl); + } + } + public async Task CheckForUpdates() { if (!_config.CheckForUpdates || _checkedForUpdates || Debugger.IsAttached) @@ -92,6 +103,8 @@ public class UpdateManager if (nvParts.Length != cvParts.Length || CompareVersions()) { + _notifyIconManager.NotifyIcon.BalloonTipClicked += trayIconBalloonTip_Clicked; + _updateHtmlUrl = latest.html_url.Value; if (latest.assets != null && _winApiService.IsServiceRunning()) @@ -101,7 +114,7 @@ public class UpdateManager if (_config.AutoInstallUpdates) { - InstallUpdate(_downloadUrl); + InstallUpdate(); return; } @@ -131,11 +144,13 @@ public class UpdateManager } } - private void InstallUpdate(string downloadUrl) + public void InstallUpdate() { + if (_downloadUrl == null) { return; } + var message = new SvcInstallUpdateMessage { - DownloadUrl = downloadUrl, + DownloadUrl = _downloadUrl, ClientPath = new FileInfo(Application.ExecutablePath).Directory.FullName }; diff --git a/ColorControl/Services/GameLauncher/GamePanel.cs b/ColorControl/Services/GameLauncher/GamePanel.cs index 8f05b68..0b5d0b1 100644 --- a/ColorControl/Services/GameLauncher/GamePanel.cs +++ b/ColorControl/Services/GameLauncher/GamePanel.cs @@ -1,10 +1,7 @@ -using ColorControl.Services.AMD; -using ColorControl.Services.Common; -using ColorControl.Services.LG; -using ColorControl.Services.NVIDIA; -using ColorControl.Services.Samsung; +using ColorControl.Services.Common; using ColorControl.Shared.Common; using ColorControl.Shared.Contracts; +using ColorControl.Shared.EventDispatcher; using ColorControl.Shared.Forms; using ColorControl.Shared.Native; using ColorControl.Shared.Services; @@ -20,30 +17,22 @@ using System.Windows.Forms; namespace ColorControl.Services.GameLauncher { - public partial class GamePanel : UserControl, IModulePanel + partial class GamePanel : UserControl, IModulePanel { - public static readonly int SHORTCUTID_GAMEQA = -203; - //private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private Config _config; private GameService _gameService; - private NotifyIcon _trayIcon; + private readonly ServiceManager _serviceManager; private readonly AppContextProvider _appContextProvider; - private NvService _nvService; - private AmdService _amdService; - private LgService _lgService; - private SamsungService _samsungService; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; - internal GamePanel(GameService gameService, NvService nvService, AmdService amdService, LgService lgService, SamsungService samsungService, NotifyIcon trayIcon, AppContextProvider appContextProvider) + public GamePanel(GameService gameService, ServiceManager serviceManager, AppContextProvider appContextProvider, KeyboardShortcutDispatcher keyboardShortcutDispatcher) { _gameService = gameService; - _trayIcon = trayIcon; + _serviceManager = serviceManager; _appContextProvider = appContextProvider; - _nvService = nvService; - _amdService = amdService; - _lgService = lgService; - _samsungService = samsungService; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; _config = Shared.Common.GlobalContext.CurrentContext.Config; InitializeComponent(); @@ -60,7 +49,7 @@ namespace ColorControl.Services.GameLauncher foreach (var preset in _gameService.GetPresets()) { AddOrUpdateItemGame(preset); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } } @@ -76,12 +65,12 @@ namespace ColorControl.Services.GameLauncher private void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private GamePreset GetSelectedGamePreset() @@ -192,7 +181,7 @@ namespace ColorControl.Services.GameLauncher private void SaveGamePreset() { var shortcut = string.Empty; - if (!KeyboardShortcutManager.ValidateShortcut(shortcut)) + if (!KeyboardShortcutDispatcher.ValidateShortcut(shortcut)) { return; } @@ -229,7 +218,7 @@ namespace ColorControl.Services.GameLauncher AddOrUpdateItemGame(); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } private void btnGameBrowse_Click(object sender, EventArgs e) @@ -279,10 +268,10 @@ namespace ColorControl.Services.GameLauncher private void mnuGameAddStep_Opening(object sender, CancelEventArgs e) { - ServiceFormUtils.BuildServicePresetsMenu(mnuGameNvidiaPresets, _nvService, "NVIDIA", miGameAddPreset_Click); - ServiceFormUtils.BuildServicePresetsMenu(mnuGameAmdPresets, _amdService, "AMD", miGameAddPreset_Click); - ServiceFormUtils.BuildServicePresetsMenu(mnuGameLgPresets, _lgService, "LG", miGameAddPreset_Click); - ServiceFormUtils.BuildServicePresetsMenu(mnuGameSamsungPresets, _samsungService, "Samsung", miGameAddPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuGameNvidiaPresets, _serviceManager.NvService, "NVIDIA", miGameAddPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuGameAmdPresets, _serviceManager.AmdService, "AMD", miGameAddPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuGameLgPresets, _serviceManager.LgService, "LG", miGameAddPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuGameSamsungPresets, _serviceManager.SamsungService, "Samsung", miGameAddPreset_Click); } private void miGameAddPreset_Click(object sender, EventArgs e) @@ -372,7 +361,7 @@ namespace ColorControl.Services.GameLauncher _config.GameQuickAccessShortcut = shortcut; - KeyboardShortcutManager.RegisterShortcut(SHORTCUTID_GAMEQA, _config.GameQuickAccessShortcut); + _keyboardShortcutDispatcher.RegisterShortcut(GameService.SHORTCUTID_GAMEQA, _config.GameQuickAccessShortcut); _gameService.Config.ApplyExternallyLaunched = applyExternallyLaunched.ValueAsBool; @@ -381,7 +370,7 @@ namespace ColorControl.Services.GameLauncher private void mnuGameActions_Opening(object sender, CancelEventArgs e) { - mnuGameNvInspector.Visible = _nvService != null; + mnuGameNvInspector.Visible = _serviceManager.NvService != null; } private void lvGamePresets_ItemChecked(object sender, ItemCheckedEventArgs e) @@ -543,5 +532,9 @@ namespace ColorControl.Services.GameLauncher preset.AutoSettings.AllowAutoApply = allowAutoApplyField.ValueAsBool; preset.AutoSettings.ProcessAutoAction = processActionField.ValueAsEnum(); } + + public void Init() + { + } } } diff --git a/ColorControl/Services/GameLauncher/GameService.cs b/ColorControl/Services/GameLauncher/GameService.cs index 9cbf2b5..89d992e 100644 --- a/ColorControl/Services/GameLauncher/GameService.cs +++ b/ColorControl/Services/GameLauncher/GameService.cs @@ -32,6 +32,8 @@ namespace ColorControl.Services.GameLauncher public GameServiceConfig Config { get; private set; } + public static readonly int SHORTCUTID_GAMEQA = -203; + public GameService(AppContextProvider appContextProvider, ServiceManager serviceManager, ProcessEventDispatcher processEventDispatcher, WinApiAdminService winApiAdminService, WinApiService winApiService) : base(appContextProvider) { LoadConfig(); @@ -41,8 +43,13 @@ namespace ColorControl.Services.GameLauncher _winApiAdminService = winApiAdminService; _winApiService = winApiService; _processEventDispatcher.RegisterAsyncEventHandler(ProcessEventDispatcher.Event_ProcessChanged, ProcessChanged); + } - SetShortcuts(-203, _appContextProvider.GetAppContext().Config.GameQuickAccessShortcut); + public override void InstallEventHandlers() + { + base.InstallEventHandlers(); + + SetShortcuts(SHORTCUTID_GAMEQA, _appContextProvider.GetAppContext().Config.GameQuickAccessShortcut); } private async Task ProcessChanged(object sender, ProcessChangedEventArgs e, CancellationToken token) diff --git a/ColorControl/Services/LG/LgPanel.cs b/ColorControl/Services/LG/LgPanel.cs index 4b39232..d729b9b 100644 --- a/ColorControl/Services/LG/LgPanel.cs +++ b/ColorControl/Services/LG/LgPanel.cs @@ -14,7 +14,6 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; @@ -22,31 +21,23 @@ namespace ColorControl.Services.LG { public partial class LgPanel : UserControl, IModulePanel { - public static readonly int SHORTCUTID_LGQA = -202; - public static readonly int SHORTCUTID_GAMEBAR = -101; - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private Config _config; private LgService _lgService; - private NvService _nvService; - private AmdService _amdService; - private readonly PowerEventDispatcher _powerEventDispatcher; + private readonly ServiceManager _serviceManager; private readonly AppContextProvider _appContextProvider; - private NotifyIcon _trayIcon; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; private string _lgTabMessage; private bool _disableEvents = false; - private LgGameBar _gameBarForm; - internal LgPanel(LgService lgService, NvService nvService, AmdService amdService, NotifyIcon trayIcon, PowerEventDispatcher powerEventDispatcher, AppContextProvider appContextProvider) + internal LgPanel(LgService lgService, ServiceManager serviceManager, AppContextProvider appContextProvider, KeyboardShortcutDispatcher keyboardShortcutDispatcher) { _lgService = lgService; - _nvService = nvService; - _amdService = amdService; - _trayIcon = trayIcon; - _powerEventDispatcher = powerEventDispatcher; + _serviceManager = serviceManager; _appContextProvider = appContextProvider; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; _config = Shared.Common.GlobalContext.CurrentContext.Config; InitializeComponent(); @@ -76,15 +67,8 @@ namespace ColorControl.Services.LG public void Init() { - var _ = Handle; - - _powerEventDispatcher.RegisterAsyncEventHandler(PowerEventDispatcher.Event_Startup, PowerStateChanged); - _lgService.InstallEventHandlers(); - } - - private async Task PowerStateChanged(object sender, PowerStateChangedEventArgs e, CancellationToken token) - { - await _lgService.RefreshDevices(afterStartUp: true).ContinueWith((_) => FormUtils.BeginInvokeCheck(this, AfterLgServiceRefreshDevices)); + _ = Handle; + _ = AfterLgServiceRefreshDevices(); } private void _lgService_SelectedDeviceChangedEvent(object sender, EventArgs e) @@ -114,12 +98,6 @@ namespace ColorControl.Services.LG await _lgService.ApplyPreset(startUpParams.LgPresetName); return; } - - - if (startUpParams.RunningFromScheduledTask) - { - await _lgService.ExecuteEventPresets(PresetTriggerType.Startup); - } } internal void Save() @@ -129,12 +107,12 @@ namespace ColorControl.Services.LG private void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private void FillLgPresets() @@ -144,7 +122,7 @@ namespace ColorControl.Services.LG foreach (var preset in _lgService.GetPresets()) { AddOrUpdateItemLg(preset); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } } @@ -259,7 +237,7 @@ namespace ColorControl.Services.LG private void btnSetShortcutLg_Click(object sender, EventArgs e) { var shortcut = edtShortcutLg.Text.Trim(); - if (!KeyboardShortcutManager.ValidateShortcut(shortcut)) + if (!KeyboardShortcutDispatcher.ValidateShortcut(shortcut)) { return; } @@ -314,7 +292,7 @@ namespace ColorControl.Services.LG AddOrUpdateItemLg(); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } public void UpdateInfo() @@ -795,8 +773,8 @@ You can also activate this option by using the Expert-button and selecting Wake- var device = _lgService.GetPresetDevice(preset); BuildLgActionMenu(device, mnuLgActions.DropDownItems, mnuLgActions.Name, miLgAddAction_Click); - ServiceFormUtils.BuildServicePresetsMenu(mnuLgNvPresets, _nvService, "NVIDIA", miLgAddNvPreset_Click); - ServiceFormUtils.BuildServicePresetsMenu(mnuLgAmdPresets, _amdService, "AMD", miLgAddAmdPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuLgNvPresets, _serviceManager.NvService, "NVIDIA", miLgAddNvPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuLgAmdPresets, _serviceManager.AmdService, "AMD", miLgAddAmdPreset_Click); } private void btnLgDeviceConvertToCustom_Click(object sender, EventArgs e) @@ -1048,42 +1026,19 @@ Do you want to continue?" edtLgPresetTriggerConditions.Text = Utils.GetDescriptions((int)value).Join(", "); } - public void ToggleGameBar() - { - if (_gameBarForm == null || !_gameBarForm.Visible) - { - if (_gameBarForm == null || _gameBarForm.IsDisposed) - { - if (_lgService?.SelectedDevice == null) - { - return; - } - - _gameBarForm = new LgGameBar(_lgService); - } - - _gameBarForm.Show(); - _gameBarForm.Activate(); - } - else - { - _gameBarForm?.Hide(); - } - } - private void btnLgGameBar_Click(object sender, EventArgs e) { - ToggleGameBar(); + _lgService.ToggleGameBar(); } private void edtLgGameBarShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtLgGameBarShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private void btnLgDeviceOptionsHelp_Click(object sender, EventArgs e) @@ -1245,7 +1200,7 @@ Do you want to continue?"; _lgService.Config.QuickAccessShortcut = shortcutQA; - KeyboardShortcutManager.RegisterShortcut(SHORTCUTID_LGQA, _lgService.Config.QuickAccessShortcut); + _keyboardShortcutDispatcher.RegisterShortcut(LgService.SHORTCUTID_LGQA, _lgService.Config.QuickAccessShortcut); var shortcutGB = gameBarShortcutField.Value.ToString(); _lgService.Config.GameBarShortcut = shortcutGB; @@ -1253,11 +1208,11 @@ Do you want to continue?"; if (string.IsNullOrEmpty(shortcutGB)) { - WinApi.UnregisterHotKey(_appContextProvider.GetAppContext().MainHandle, SHORTCUTID_GAMEBAR); + WinApi.UnregisterHotKey(_appContextProvider.GetAppContext().MainHandle, LgService.SHORTCUTID_GAMEBAR); } else { - KeyboardShortcutManager.RegisterShortcut(SHORTCUTID_GAMEBAR, shortcutGB); + _keyboardShortcutDispatcher.RegisterShortcut(LgService.SHORTCUTID_GAMEBAR, shortcutGB); } _lgService.Config.ShowAdvancedActions = advancedField.ValueAsBool; diff --git a/ColorControl/Services/LG/LgService.cs b/ColorControl/Services/LG/LgService.cs index ece2fba..3c56583 100644 --- a/ColorControl/Services/LG/LgService.cs +++ b/ColorControl/Services/LG/LgService.cs @@ -63,9 +63,13 @@ namespace ColorControl.Services.LG private readonly WinApiService _winApiService; private readonly WinApiAdminService _winApiAdminService; private SynchronizationContext _syncContext; + private LgGameBar _gameBarForm; public ProcessChangedEventArgs CurrentProcessEvent => _processEventDispatcher?.MonitorContext; + public static readonly int SHORTCUTID_LGQA = -202; + public static readonly int SHORTCUTID_GAMEBAR = -101; + public LgService(AppContextProvider appContextProvider, PowerEventDispatcher powerEventDispatcher, SessionSwitchDispatcher sessionSwitchDispatcher, ProcessEventDispatcher processEventDispatcher, ServiceManager serviceManager, RestartDetector restartDetector, WinApiService winApiService, WinApiAdminService winApiAdminService) : base(appContextProvider) { _allowPowerOn = appContextProvider.GetAppContext().StartUpParams.RunningFromScheduledTask; @@ -91,6 +95,17 @@ namespace ColorControl.Services.LG GlobalSave(); } + protected override async Task HotKeyPressed(object sender, KeyboardShortcutEventArgs e, CancellationToken _) + { + await base.HotKeyPressed(sender, e, _); + + if (e.HotKeyId == SHORTCUTID_GAMEBAR) + { + ToggleGameBar(); + return; + } + } + public static async Task ExecutePresetAsync(string presetName) { try @@ -429,20 +444,36 @@ namespace ColorControl.Services.LG { base.InstallEventHandlers(); + SetShortcuts(SHORTCUTID_LGQA, Config.QuickAccessShortcut); + + var keyboardShortcutDispatcher = _appContextProvider.GetAppContext().ServiceProvider.GetService(); + if (keyboardShortcutDispatcher != null) + { + keyboardShortcutDispatcher.RegisterShortcut(SHORTCUTID_GAMEBAR, Config.GameBarShortcut); + } + + _powerEventDispatcher.RegisterAsyncEventHandler(PowerEventDispatcher.Event_Startup, PowerStateChanged); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_Suspend, PowerModeChanged); _powerEventDispatcher.RegisterAsyncEventHandler(PowerEventDispatcher.Event_Resume, PowerModeResume); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_Shutdown, PowerModeChanged); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_MonitorOff, PowerModeChanged); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_MonitorOn, PowerModeChanged); - //SystemEvents.SessionEnded -= SessionEnded; - //SystemEvents.SessionEnded += SessionEnded; - _sessionSwitchDispatcher.RegisterEventHandler(SessionSwitchDispatcher.Event_SessionSwitch, SessionSwitched); _processEventDispatcher.RegisterAsyncEventHandler(ProcessEventDispatcher.Event_ProcessChanged, ProcessChanged); } + private async Task PowerStateChanged(object sender, PowerStateChangedEventArgs e, CancellationToken token) + { + await RefreshDevices(afterStartUp: true); + + if (_appContextProvider.GetAppContext().StartUpParams.RunningFromScheduledTask) + { + await ExecutePresetsForEvent(PresetTriggerType.Startup); + } + } + private void SessionSwitched(object sender, SessionSwitchEventArgs e) { if (!_sessionSwitchDispatcher.UserLocalSession) @@ -469,7 +500,7 @@ namespace ColorControl.Services.LG await WakeAfterStartupOrResume(PowerOnOffState.Resume); - ExecutePresetsForEvent(PresetTriggerType.Resume); + await ExecutePresetsForEvent(PresetTriggerType.Resume); } private void PowerModeChanged(object sender, PowerStateChangedEventArgs e) @@ -517,7 +548,7 @@ namespace ColorControl.Services.LG } } - private void ExecutePresetsForEvent(PresetTriggerType triggerType) + private async Task ExecutePresetsForEvent(PresetTriggerType triggerType) { var presets = _presets.Where(p => p.Triggers.Any(t => t.Trigger == triggerType)).ToList(); @@ -534,7 +565,7 @@ namespace ColorControl.Services.LG return; } - var _ = Task.WhenAll(ExecuteEventPresets(_serviceManager, new[] { triggerType }, isHDRActive: applicableDevices.Any(d => d.IsUsingHDRPictureMode()))).ConfigureAwait(true); + await ExecuteEventPresets(_serviceManager, new[] { triggerType }, isHDRActive: applicableDevices.Any(d => d.IsUsingHDRPictureMode())).ConfigureAwait(true); } private void SessionEnded(object sender, SessionEndedEventArgs e) @@ -956,5 +987,28 @@ namespace ColorControl.Services.LG { await ExecuteEventPresets(_serviceManager, new[] { triggerType }); } + + public void ToggleGameBar() + { + if (_gameBarForm == null || !_gameBarForm.Visible) + { + if (_gameBarForm == null || _gameBarForm.IsDisposed) + { + if (SelectedDevice == null) + { + return; + } + + _gameBarForm = new LgGameBar(this); + } + + _gameBarForm.Show(); + _gameBarForm.Activate(); + } + else + { + _gameBarForm?.Hide(); + } + } } } \ No newline at end of file diff --git a/ColorControl/Services/NVIDIA/NvDitherPanel.cs b/ColorControl/Services/NVIDIA/NvDitherPanel.cs index 68f17a9..f1a042c 100644 --- a/ColorControl/Services/NVIDIA/NvDitherPanel.cs +++ b/ColorControl/Services/NVIDIA/NvDitherPanel.cs @@ -165,5 +165,9 @@ namespace ColorControl.Services.NVIDIA MessageForms.ErrorOk("There was an error writing the dither settings to the registry. See the log for more details."); } } + + public void Init() + { + } } } diff --git a/ColorControl/Services/NVIDIA/NvInfoPanel.cs b/ColorControl/Services/NVIDIA/NvInfoPanel.cs index 8f52011..fff474a 100644 --- a/ColorControl/Services/NVIDIA/NvInfoPanel.cs +++ b/ColorControl/Services/NVIDIA/NvInfoPanel.cs @@ -22,6 +22,10 @@ namespace ColorControl.Services.NVIDIA RefreshInfo(); } + public void Init() + { + } + public void UpdateInfo() { RefreshInfo(); diff --git a/ColorControl/Services/NVIDIA/NvPanel.cs b/ColorControl/Services/NVIDIA/NvPanel.cs index 94f371b..bd29477 100644 --- a/ColorControl/Services/NVIDIA/NvPanel.cs +++ b/ColorControl/Services/NVIDIA/NvPanel.cs @@ -2,6 +2,7 @@ using ColorControl.Shared.Common; using ColorControl.Shared.Contracts; using ColorControl.Shared.Contracts.NVIDIA; +using ColorControl.Shared.EventDispatcher; using ColorControl.Shared.Forms; using ColorControl.Shared.Native; using ColorControl.Shared.Services; @@ -28,26 +29,26 @@ namespace ColorControl.Services.NVIDIA { partial class NvPanel : UserControl, IModulePanel { - public static readonly int SHORTCUTID_NVQA = -200; - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private Config _config; private NvService _nvService; + private readonly NotifyIconManager _notifyIconManager; private readonly AppContextProvider _appContextProvider; private string _lastDisplayRefreshRates = string.Empty; - private NotifyIcon _trayIcon; private RpcClientService _rpcService; private readonly WinApiAdminService _winApiAdminService; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; - public NvPanel(NvService nvService, NotifyIcon trayIcon, AppContextProvider appContextProvider, RpcClientService rpcService, WinApiAdminService winApiAdminService) + public NvPanel(NvService nvService, NotifyIconManager notifyIconManager, AppContextProvider appContextProvider, RpcClientService rpcService, WinApiAdminService winApiAdminService, KeyboardShortcutDispatcher keyboardShortcutDispatcher) { _nvService = nvService; - _trayIcon = trayIcon; + _notifyIconManager = notifyIconManager; _appContextProvider = appContextProvider; _config = appContextProvider.GetAppContext().Config; _rpcService = rpcService; _winApiAdminService = winApiAdminService; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; _rpcService.Name = "NvService"; InitializeComponent(); @@ -57,13 +58,6 @@ namespace ColorControl.Services.NVIDIA FormUtils.InitSortState(lvNvPresets, _config.NvPresetsSortState); _nvService.AfterApplyPreset += NvServiceAfterApplyPreset; - - MainViewModel.ConfigPath = _appContextProvider.GetAppContext().DataPath; - - if (_nvService.Config.ApplyNovideoOnStartup) - { - MainWindow.CreateAndShow(false); - } } private void lvLgPresets_ColumnClick(object sender, ColumnClickEventArgs e) @@ -112,12 +106,20 @@ namespace ColorControl.Services.NVIDIA { FormUtils.InitListView(lvNvPresets, NvPreset.GetColumnNames()); - UpdateDisplayInfoItems(); - - foreach (var preset in _nvService.GetPresets()) + lvNvPresets.BeginUpdate(); + try { - AddOrUpdateItem(preset); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + UpdateDisplayInfoItems(); + + foreach (var preset in _nvService.GetPresets()) + { + AddOrUpdateItem(preset); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); + } + } + finally + { + lvNvPresets.EndUpdate(); } } @@ -177,7 +179,7 @@ namespace ColorControl.Services.NVIDIA UpdateNvGpuInfo(); - FormUtils.SetNotifyIconText(_trayIcon, text); + _notifyIconManager.SetText(text); } private void UpdateNvGpuInfo(List gpus = null) @@ -1271,14 +1273,14 @@ namespace ColorControl.Services.NVIDIA private void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void btnSetShortcut_Click(object sender, EventArgs e) { var shortcut = edtShortcut.Text.Trim(); - if (!KeyboardShortcutManager.ValidateShortcut(shortcut)) + if (!KeyboardShortcutDispatcher.ValidateShortcut(shortcut)) { return; } @@ -1305,12 +1307,12 @@ namespace ColorControl.Services.NVIDIA AddOrUpdateItem(); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } private void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private void edtShortcut_TextChanged(object sender, EventArgs e) @@ -1552,7 +1554,7 @@ namespace ColorControl.Services.NVIDIA _config.NvQuickAccessShortcut = shortcut; - KeyboardShortcutManager.RegisterShortcut(SHORTCUTID_NVQA, _config.NvQuickAccessShortcut); + _keyboardShortcutDispatcher.RegisterShortcut(NvService.SHORTCUTID_NVQA, _config.NvQuickAccessShortcut); _nvService.Config.ShowOverclocking = enableOcField.ValueAsBool; _nvService.Config.ApplyNovideoOnStartup = enableNovideoField.ValueAsBool; @@ -1856,7 +1858,7 @@ namespace ColorControl.Services.NVIDIA AddOrUpdateItem(); } - private async Task ApplyNvPresetOnStartup(int attempts = 5) + private async Task ApplyNvPresetOnStartup() { var startUpParams = Shared.Common.GlobalContext.CurrentContext.StartUpParams; @@ -2052,5 +2054,9 @@ namespace ColorControl.Services.NVIDIA AddOrUpdateItem(); } + + public void Init() + { + } } } diff --git a/ColorControl/Services/NVIDIA/NvService.cs b/ColorControl/Services/NVIDIA/NvService.cs index 20c2057..c9fba39 100644 --- a/ColorControl/Services/NVIDIA/NvService.cs +++ b/ColorControl/Services/NVIDIA/NvService.cs @@ -218,30 +218,36 @@ namespace ColorControl.Services.NVIDIA private readonly RpcClientService _rpcClientService; private readonly PowerEventDispatcher _powerEventDispatcher; private readonly ServiceManager _serviceManager; - private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; private static NvService ServiceInstance; public static readonly int SHORTCUTID_NVQA = -200; - public NvService(AppContextProvider appContextProvider, WinApiService winApiService, RpcClientService rpcClientService, PowerEventDispatcher powerEventDispatcher, ServiceManager serviceManager, KeyboardShortcutDispatcher keyboardShortcutDispatcher) : base(appContextProvider) + public NvService(AppContextProvider appContextProvider, WinApiService winApiService, RpcClientService rpcClientService, PowerEventDispatcher powerEventDispatcher, ServiceManager serviceManager) : base(appContextProvider) { _winApiService = winApiService; _rpcClientService = rpcClientService; _powerEventDispatcher = powerEventDispatcher; _serviceManager = serviceManager; - _keyboardShortcutDispatcher = keyboardShortcutDispatcher; _rpcClientService.Name = nameof(NvService); NvPreset.NvService = this; AddJsonConverter(new ColorDataConverter()); LoadConfig(); LoadPresets(); - - SetShortcuts(SHORTCUTID_NVQA, _appContextProvider.GetAppContext().Config.NvQuickAccessShortcut); } - public void InstallEventHandlers() + public override void InstallEventHandlers() { + SetShortcuts(SHORTCUTID_NVQA, _appContextProvider.GetAppContext().Config.NvQuickAccessShortcut); + + GetDisplayInfos(false); + + MainViewModel.ConfigPath = _appContextProvider.GetAppContext().DataPath; + if (Config.ApplyNovideoOnStartup) + { + MainWindow.CreateAndShow(false); + } + // TODO: implement later //_powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_Suspend, PowerModeChanged); //_powerEventDispatcher.RegisterAsyncEventHandler(PowerEventDispatcher.Event_Resume, PowerModeResume); @@ -513,6 +519,7 @@ namespace ColorControl.Services.NVIDIA preset.IsStartupPreset = false; PresetApplied(); + GetDisplayInfos(false); return result; } @@ -1426,15 +1433,17 @@ namespace ColorControl.Services.NVIDIA return list; } - public List GetDisplayInfos() + public List GetDisplayInfos(bool refreshSettings = true) { try { var displays = GetDisplays(); var list = new List(); - RefreshProfileSettings(); - var settings = GetVisibleSettings(); + if (refreshSettings) + { + RefreshProfileSettings(); + } foreach (var display in displays) { @@ -1446,6 +1455,13 @@ namespace ColorControl.Services.NVIDIA list.Add(displayInfo); } + var notifyIconManager = _appContextProvider.GetAppContext().ServiceProvider.GetService(); + + if (notifyIconManager != null) + { + notifyIconManager.SetText(string.Join("\n", list.Select(i => i.InfoLine))); + } + return list; } catch (Exception e) @@ -1745,7 +1761,7 @@ namespace ColorControl.Services.NVIDIA // Wait await Task.Delay(30000); - ExecutePresetsForEvent(PresetTriggerType.Resume); + await ExecutePresetsForEvent(PresetTriggerType.Resume); } private void PowerModeChanged(object sender, PowerStateChangedEventArgs e) @@ -1756,18 +1772,18 @@ namespace ColorControl.Services.NVIDIA { case PowerOnOffState.StandBy: { - ExecutePresetsForEvent(PresetTriggerType.Standby); + _ = ExecutePresetsForEvent(PresetTriggerType.Standby); break; } case PowerOnOffState.ShutDown: { - ExecutePresetsForEvent(PresetTriggerType.Shutdown); + _ = ExecutePresetsForEvent(PresetTriggerType.Shutdown); break; } } } - private void ExecutePresetsForEvent(PresetTriggerType triggerType) + private async Task ExecutePresetsForEvent(PresetTriggerType triggerType) { Logger.Debug($"Executing presets for event {triggerType}"); @@ -1778,7 +1794,7 @@ namespace ColorControl.Services.NVIDIA return; } - ExecuteEventPresets(_serviceManager, new[] { triggerType }).Wait(); + await ExecuteEventPresets(_serviceManager, new[] { triggerType }).ConfigureAwait(true); } private static uint MAKE_NVAPI_VERSION(int version) diff --git a/ColorControl/Services/Samsung/SamsungPanel.cs b/ColorControl/Services/Samsung/SamsungPanel.cs index d5169c8..9266f1b 100644 --- a/ColorControl/Services/Samsung/SamsungPanel.cs +++ b/ColorControl/Services/Samsung/SamsungPanel.cs @@ -13,34 +13,29 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ColorControl.Services.Samsung { - public partial class SamsungPanel : UserControl, IModulePanel + partial class SamsungPanel : UserControl, IModulePanel { - public static readonly int SHORTCUTID_SAMSUNGQA = -204; - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private Config _config; private SamsungService _samsungService; - private NvService _nvService; - private AmdService _amdService; - private readonly PowerEventDispatcher _powerEventDispatcher; private readonly AppContextProvider _appContextProvider; + private readonly KeyboardShortcutDispatcher _keyboardShortcutDispatcher; + private readonly ServiceManager _serviceManager; private string _tabMessage; private bool _disableEvents = false; - internal SamsungPanel(SamsungService samsungService, NvService nvService, AmdService amdService, PowerEventDispatcher powerEventDispatcher, AppContextProvider appContextProvider) + public SamsungPanel(SamsungService samsungService, AppContextProvider appContextProvider, KeyboardShortcutDispatcher keyboardShortcutDispatcher, ServiceManager serviceManager) { _samsungService = samsungService; - _nvService = nvService; - _amdService = amdService; - _powerEventDispatcher = powerEventDispatcher; _appContextProvider = appContextProvider; + _keyboardShortcutDispatcher = keyboardShortcutDispatcher; + _serviceManager = serviceManager; _config = Shared.Common.GlobalContext.CurrentContext.Config; InitializeComponent(); @@ -72,17 +67,15 @@ namespace ColorControl.Services.Samsung public void Init() { - var _ = Handle; - //_powerEventDispatcher.RegisterAsyncEventHandler(PowerEventDispatcher.Event_Startup, PowerStateChanged); + _ = Handle; - //_samsungService.InstallEventHandlers(); + if (_samsungService.Devices == null) + { + RefreshSamsungDevices(); + return; + } - var x = AfterSamsungServiceRefreshDevices(); - } - - private async Task PowerStateChanged(object sender, PowerStateChangedEventArgs e, CancellationToken token) - { - await _samsungService.RefreshDevices(afterStartUp: true).ContinueWith((_) => FormUtils.BeginInvokeCheck(this, AfterSamsungServiceRefreshDevices)); + _ = AfterSamsungServiceRefreshDevices(); } private void _samsungService_SelectedDeviceChangedEvent(object sender, EventArgs e) @@ -112,11 +105,6 @@ namespace ColorControl.Services.Samsung await _samsungService.ApplyPreset(startUpParams.SamsungPresetName); return; } - - if (startUpParams.RunningFromScheduledTask) - { - await _samsungService.ExecuteEventPresets(PresetTriggerType.Startup); - } } internal void Save() @@ -126,12 +114,12 @@ namespace ColorControl.Services.Samsung private void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private void FillPresets() @@ -141,7 +129,7 @@ namespace ColorControl.Services.Samsung foreach (var preset in _samsungService.GetPresets()) { AddOrUpdateItem(preset); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } } @@ -256,7 +244,7 @@ namespace ColorControl.Services.Samsung private void btnSetShortcutLg_Click(object sender, EventArgs e) { var shortcut = edtShortcutLg.Text.Trim(); - if (!KeyboardShortcutManager.ValidateShortcut(shortcut)) + if (!KeyboardShortcutDispatcher.ValidateShortcut(shortcut)) { return; } @@ -311,7 +299,7 @@ namespace ColorControl.Services.Samsung AddOrUpdateItem(); - KeyboardShortcutManager.RegisterShortcut(preset.id, preset.shortcut); + _keyboardShortcutDispatcher.RegisterShortcut(preset.id, preset.shortcut); } public void UpdateInfo() @@ -348,6 +336,11 @@ namespace ColorControl.Services.Samsung { var devices = _samsungService.Devices; + if (devices == null) + { + return; + } + cbxSamsungDevices.Items.Clear(); cbxSamsungDevices.Items.AddRange(devices.ToArray()); @@ -681,7 +674,7 @@ Use 'Settings > Test power off/on' to test this functionality." if (e.Index == 10) { - _samsungService.RefreshDevices().ContinueWith((_) => FormUtils.BeginInvokeCheck(this, () => FillSamsungDevices())); + RefreshSamsungDevices(); } }); } @@ -784,8 +777,8 @@ Use 'Settings > Test power off/on' to test this functionality." var device = _samsungService.GetPresetDevice(preset); BuildActionMenu(device, mnuLgActions.DropDownItems, mnuLgActions.Name, miLgAddAction_Click, _samsungService.Config.ShowAdvancedActions); - ServiceFormUtils.BuildServicePresetsMenu(mnuLgNvPresets, _nvService, "NVIDIA", miLgAddNvPreset_Click); - ServiceFormUtils.BuildServicePresetsMenu(mnuLgAmdPresets, _amdService, "AMD", miLgAddAmdPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuLgNvPresets, _serviceManager.NvService, "NVIDIA", miLgAddNvPreset_Click); + ServiceFormUtils.BuildServicePresetsMenu(mnuLgAmdPresets, _serviceManager.AmdService, "AMD", miLgAddAmdPreset_Click); } private void btnSamsungDeviceConvertToCustom_Click(object sender, EventArgs e) @@ -872,12 +865,12 @@ Do you want to continue?" private void edtSamsungGameBarShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = _keyboardShortcutDispatcher.FormatKeyboardShortcut(e); } private void edtSamsungGameBarShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + _keyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } private void btnSamsungDeviceOptionsHelp_Click(object sender, EventArgs e) @@ -1026,7 +1019,7 @@ Do you want to continue?"; _samsungService.Config.QuickAccessShortcut = shortcutQA; - KeyboardShortcutManager.RegisterShortcut(SHORTCUTID_SAMSUNGQA, _samsungService.Config.QuickAccessShortcut); + _keyboardShortcutDispatcher.RegisterShortcut(SamsungService.SHORTCUTID_SAMSUNGQA, _samsungService.Config.QuickAccessShortcut); _samsungService.Config.SetSelectedDeviceByPowerOn = setDeviceField.ValueAsBool; _samsungService.Config.ShowAdvancedActions = showAdvancedField.ValueAsBool; diff --git a/ColorControl/Services/Samsung/SamsungService.cs b/ColorControl/Services/Samsung/SamsungService.cs index d14cc1d..5f7133b 100644 --- a/ColorControl/Services/Samsung/SamsungService.cs +++ b/ColorControl/Services/Samsung/SamsungService.cs @@ -42,6 +42,8 @@ namespace ColorControl.Services.Samsung public List Devices { get; private set; } + public static readonly int SHORTCUTID_SAMSUNGQA = -204; + public SamsungService(AppContextProvider appContextProvider, ServiceManager serviceManager, PowerEventDispatcher powerEventDispatcher, SessionSwitchDispatcher sessionSwitchDispatcher, RestartDetector restartDetector, ProcessEventDispatcher processEventDispatcher, WinApiAdminService winApiAdminService) : base(appContextProvider) { _appContext = appContextProvider.GetAppContext(); @@ -56,8 +58,6 @@ namespace ColorControl.Services.Samsung LoadConfig(); LoadPresets(); - - SetShortcuts(-204, Config.QuickAccessShortcut); } public static async Task ExecutePresetAsync(string presetName) @@ -88,6 +88,8 @@ namespace ColorControl.Services.Samsung { base.InstallEventHandlers(); + SetShortcuts(SHORTCUTID_SAMSUNGQA, Config.QuickAccessShortcut); + _powerEventDispatcher.RegisterAsyncEventHandler(PowerEventDispatcher.Event_Startup, PowerStateChanged); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_MonitorOn, PowerModeChanged); _powerEventDispatcher.RegisterEventHandler(PowerEventDispatcher.Event_MonitorOff, PowerModeChanged); @@ -100,6 +102,11 @@ namespace ColorControl.Services.Samsung private async Task PowerStateChanged(object sender, PowerStateChangedEventArgs e, CancellationToken token) { await RefreshDevices(afterStartUp: true); + + if (_appContext.StartUpParams.RunningFromScheduledTask) + { + await ExecutePresetsForEvent(PresetTriggerType.Startup); + } } private void LoadConfig() @@ -194,7 +201,7 @@ namespace ColorControl.Services.Samsung return; } - await ExecuteEventPresets(_serviceManager, new[] { triggerType }); + await ExecuteEventPresets(_serviceManager, new[] { triggerType }).ConfigureAwait(true); } public async Task RefreshDevices(bool connect = true, bool afterStartUp = false) diff --git a/Shared/Common/KeyboardShortcutManager.cs b/Shared/Common/KeyboardShortcutManager.cs deleted file mode 100644 index d747e75..0000000 --- a/Shared/Common/KeyboardShortcutManager.cs +++ /dev/null @@ -1,333 +0,0 @@ -using ColorControl.Shared.Forms; -using Linearstar.Windows.RawInput; -using Linearstar.Windows.RawInput.Native; -using NWin32; - -namespace ColorControl.Shared.Common -{ - public class KeyboardShortcutManager - { - [Flags] - public enum ModKeys : int - { - None = 0, - Alt = 1, - Control = 2, - Shift = 4, - Win = 8 - } - - public static nint MainHandle { get; set; } - public static bool UseRawInput { get; private set; } - - private static bool WinKeyDown = false; - - private static List KeysWithoutModifiers = new List { Keys.F13, Keys.F14, Keys.F15, Keys.F16, Keys.F17, Keys.F18, Keys.F19, Keys.F20, Keys.F21, Keys.F22, Keys.F23, Keys.F24 }; - private static List Modifiers = new List { Keys.ControlKey, Keys.Menu, Keys.ShiftKey, Keys.LWin }; - - private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); - - private static readonly HashSet _downModifierKeys = new HashSet(); - private static readonly HashSet _downKeys = new HashSet(); - - private static readonly object _modifiersLock = new object(); - - private static Dictionary _registeredShortcuts = new Dictionary(); - - public static void SetUseRawInput(bool useRawInput) - { - if (UseRawInput == useRawInput) - { - return; - } - - UseRawInput = useRawInput; - - if (useRawInput) - { - UnregisterHotKeys(); - - RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, MainHandle); - } - else - { - RawInputDevice.UnregisterDevice(HidUsageAndPage.Keyboard); - - RegisterHotKeys(); - } - } - - private static void UnregisterHotKeys() - { - foreach (var shortcut in _registeredShortcuts.Values.Where(s => s.HotKeyRegistered).ToList()) - { - shortcut.UnregisterHotKey(MainHandle); - } - } - - private static void RegisterHotKeys() - { - foreach (var shortcut in _registeredShortcuts.Values.Where(s => !s.HotKeyRegistered).ToList()) - { - shortcut.RegisterHotKey(MainHandle); - } - } - - public static void HandleRawKeyboardInput(RawInputKeyboardData data) - { - var keyboard = data.Keyboard; - - //Debug.WriteLine($"Key: {keyboard}"); - - var add = !keyboard.Flags.HasFlag(RawKeyboardFlags.Up); - - var keys = (Keys)keyboard.VirutalKey; - - var isModifier = Modifiers.Contains(keys); - var modKey = KeysToModKeys(keys); - var changed = false; - - lock (_modifiersLock) - { - if (add) - { - if (isModifier) - { - changed = _downModifierKeys.Add(modKey); - } - else - { - changed = _downKeys.Add((Keys)keyboard.VirutalKey); - } - } - else - { - if (isModifier) - { - changed = _downModifierKeys.Remove(modKey); - } - else - { - changed = _downKeys.Remove((Keys)keyboard.VirutalKey); - } - } - } - - if (!changed || _downKeys.Count != 1 || !(_downModifierKeys.Any() || KeysWithoutModifiers.Contains(_downKeys.First()))) - { - return; - } - - var sum = _downModifierKeys.Sum(k => (int)k) * 1000; - sum += _downKeys.Sum(k => (int)k); - - var shortcut = _registeredShortcuts.Values.FirstOrDefault(s => (s.Modifiers * 1000 + s.VirtualKeyCode) == sum); - - if (shortcut == null) - { - return; - } - - NativeMethods.SendMessageW(MainHandle, NativeConstants.WM_HOTKEY, (uint)shortcut.Id, 0); - } - - public static bool RegisterShortcut(int id, string shortcut) - { - var clear = string.IsNullOrWhiteSpace(shortcut); - - var shortcutStruct = GetShortcutById(id); - - if (shortcutStruct == null) - { - if (clear) - { - return true; - } - - var (mods, key) = ParseShortcut(shortcut); - - shortcutStruct = new ShortcutStruct(mods, key, id, shortcut); - - _registeredShortcuts[id] = shortcutStruct; - } - else if (clear) - { - shortcutStruct.UnregisterHotKey(id); - - _registeredShortcuts.Remove(id); - - return true; - } - else - { - var (mods, key) = ParseShortcut(shortcut); - - if (shortcutStruct.Modifiers == mods && shortcutStruct.VirtualKeyCode == key) - { - return true; - } - - shortcutStruct.SetModifiers(mods); - shortcutStruct.SetKey(key); - shortcutStruct.SetShortcut(shortcut); - shortcutStruct.UnregisterHotKey(MainHandle); - } - - //if (UseRawInput) - //{ - // return true; - //} - - return shortcutStruct.RegisterHotKey(MainHandle); - } - - private static ShortcutStruct GetShortcutById(int id) - { - if (_registeredShortcuts.TryGetValue(id, out var shortcut)) - { - return shortcut; - } - - return null; - } - - public static (int mods, int key) ParseShortcut(string shortcut) - { - int mods = 0; - var key = 0; - - shortcut = shortcut.Replace(",", ""); - shortcut = shortcut.Replace("+", ""); - shortcut = shortcut.Replace(" ", " "); - var parts = shortcut.Split(' '); - - if (parts.Length > 0) - { - for (int i = 0; i + 1 < parts.Length; i++) - { - switch (parts[i]) - { - case "Alt": - mods += (int)ModKeys.Alt; - break; - case "Control": - mods += (int)ModKeys.Control; - break; - case "Shift": - mods += (int)ModKeys.Shift; - break; - case "Win": - mods += (int)ModKeys.Win; - break; - } - } - - var keyName = parts[parts.Length - 1]; - - key = (int)Enum.Parse(typeof(Keys), keyName); - } - - return (mods, key); - } - - public static Keys ShortcutToKeys(string shortcut) - { - var (mods, key) = ParseShortcut(shortcut); - - var keys = Keys.None; - - if (((uint)mods & (uint)ModKeys.Alt) > 0) - { - keys |= Keys.Alt; - } - if (((uint)mods & (uint)ModKeys.Control) > 0) - { - keys |= Keys.Control; - } - if (((uint)mods & (uint)ModKeys.Shift) > 0) - { - keys |= Keys.Shift; - } - if (((uint)mods & (uint)ModKeys.Win) > 0) - { - keys |= Keys.Control; - } - - keys |= (Keys)key; - - return keys; - } - - public static ModKeys KeysToModKeys(Keys key) - { - return key switch - { - Keys.ControlKey => ModKeys.Control, - Keys.Menu => ModKeys.Alt, - Keys.ShiftKey => ModKeys.Shift, - Keys.LWin => ModKeys.Win, - _ => ModKeys.None, - }; - } - - public static string FormatKeyboardShortcut(KeyEventArgs keyEvent) - { - var pressedModifiers = keyEvent.Modifiers; - - //Debug.WriteLine("KD: " + e.Modifiers + ", " + e.KeyCode); - - var shortcutString = pressedModifiers > 0 ? pressedModifiers.ToString() : ""; - if (keyEvent.KeyCode == Keys.LWin || WinKeyDown) - { - WinKeyDown = true; - if (!string.IsNullOrEmpty(shortcutString)) - { - shortcutString += ", "; - } - shortcutString += "Win"; - } - - var empty = string.IsNullOrEmpty(shortcutString); - if ((!empty || KeysWithoutModifiers.Contains(keyEvent.KeyCode)) && keyEvent.KeyCode != Keys.ControlKey && keyEvent.KeyCode != Keys.ShiftKey && keyEvent.KeyCode != Keys.Menu && keyEvent.KeyCode != Keys.LWin) - { - if (!empty) - { - shortcutString += " + "; - } - shortcutString += keyEvent.KeyCode.ToString(); - } - - if (string.IsNullOrEmpty(shortcutString)) - { - keyEvent.SuppressKeyPress = true; - } - - return shortcutString; - } - - public static bool ValidateShortcut(string shortcut) - { - var valid = string.IsNullOrWhiteSpace(shortcut) || shortcut.Contains("+") || ShortcutIsAllowedWithoutModifier(shortcut); - - if (!valid) - { - MessageForms.WarningOk("Invalid shortcut. The shortcut should have modifiers and a normal key or be F13-F24."); - } - - return valid; - } - - public static bool ShortcutIsAllowedWithoutModifier(string shortcut) - { - return Enum.TryParse(shortcut, out var key) && KeysWithoutModifiers.Contains(key); - } - - public static void HandleKeyboardShortcutUp(KeyEventArgs keyEvent) - { - if (keyEvent.KeyCode == Keys.LWin) - { - WinKeyDown = false; - } - } - } -} diff --git a/Shared/EventDispatcher/KeyboardShortcutDispatcher.cs b/Shared/EventDispatcher/KeyboardShortcutDispatcher.cs index 298c591..cc65fd0 100644 --- a/Shared/EventDispatcher/KeyboardShortcutDispatcher.cs +++ b/Shared/EventDispatcher/KeyboardShortcutDispatcher.cs @@ -53,11 +53,21 @@ public class KeyboardShortcutDispatcher : EventDispatcher s.Key != presetId && s.Value.Shortcut == shortcut); + } + public void SetUseRawInput(bool useRawInput) { if (UseRawInput == useRawInput) diff --git a/Shared/EventDispatcher/WindowMessageDispatcher.cs b/Shared/EventDispatcher/WindowMessageDispatcher.cs index ab52712..3a0fb5f 100644 --- a/Shared/EventDispatcher/WindowMessageDispatcher.cs +++ b/Shared/EventDispatcher/WindowMessageDispatcher.cs @@ -58,12 +58,25 @@ public class WindowMessageDispatcher : EventDispatcher { public event EventHandler OnMessage; + private bool _systemShutdown; + public DummyForm() { FormBorderStyle = FormBorderStyle.None; ShowInTaskbar = false; Load += DummyForm_Load; Shown += DummyForm_Shown; + FormClosing += DummyForm_FormClosing; + } + + private void DummyForm_FormClosing(object sender, FormClosingEventArgs e) + { + Logger.Debug($"FormClosing: {_systemShutdown}"); + + if (_systemShutdown) + { + OnMessage?.Invoke(this, new Message { Msg = NativeConstants.WM_CLOSE }); + } } private void DummyForm_Shown(object sender, EventArgs e) @@ -78,6 +91,11 @@ public class WindowMessageDispatcher : EventDispatcher protected override void WndProc(ref Message m) { + if (m.Msg == NativeConstants.WM_QUERYENDSESSION) + { + _systemShutdown = true; + } + OnMessage?.Invoke(this, m); base.WndProc(ref m); diff --git a/Shared/Forms/FormUtils.cs b/Shared/Forms/FormUtils.cs index 48deded..634daf9 100644 --- a/Shared/Forms/FormUtils.cs +++ b/Shared/Forms/FormUtils.cs @@ -65,6 +65,19 @@ namespace ColorControl.Shared.Forms contextMenu.Show(control, control.PointToClient(Cursor.Position)); } + public static Control FindFocusedControl(this Form form) + { + ContainerControl container = form ?? Form.ActiveForm; + Control control = null; + while (container != null) + { + control = container.ActiveControl; + container = control as ContainerControl; + } + + return control; + } + public static ToolStripMenuItem BuildDropDownMenuEx(ToolStripItemCollection items, string parentName, string name, Type enumType, EventHandler clickEvent, object tag = null, int min = 0, int max = 0, bool noSubItems = false) { var subMenuName = $"{parentName}_{name}"; diff --git a/Shared/Forms/MessageForms.cs b/Shared/Forms/MessageForms.cs index 32d9a94..da5a246 100644 --- a/Shared/Forms/MessageForms.cs +++ b/Shared/Forms/MessageForms.cs @@ -1,4 +1,5 @@ using ColorControl.Shared.Common; +using ColorControl.Shared.EventDispatcher; using System.Data; using System.Globalization; @@ -73,12 +74,12 @@ namespace ColorControl.Shared.Forms public void edtShortcut_KeyDown(object sender, KeyEventArgs e) { - ((TextBox)sender).Text = KeyboardShortcutManager.FormatKeyboardShortcut(e); + ((TextBox)sender).Text = MessageForms.KeyboardShortcutDispatcher.FormatKeyboardShortcut(e); } public void edtShortcut_KeyUp(object sender, KeyEventArgs e) { - KeyboardShortcutManager.HandleKeyboardShortcutUp(e); + MessageForms.KeyboardShortcutDispatcher.HandleKeyboardShortcutUp(e); } public void TrackBar_Scroll(object sender, EventArgs e) @@ -113,6 +114,7 @@ namespace ColorControl.Shared.Forms public class MessageForms { public static Form MainForm; + public static KeyboardShortcutDispatcher KeyboardShortcutDispatcher; public static string Title = null; public static void WarningOk(string text) diff --git a/Shared/Services/RpcClientService.cs b/Shared/Services/RpcClientService.cs index fa20b55..4362881 100644 --- a/Shared/Services/RpcClientService.cs +++ b/Shared/Services/RpcClientService.cs @@ -46,9 +46,10 @@ public class RpcClientService { message.ServiceName = Name; - if (Debugger.IsAttached) + if (Debugger.IsAttached && !_winApiService.IsServiceRunning()) { - return PipeUtils.SendRpcMessage(message, pipeName: PipeUtils.ElevatedPipe); + //return PipeUtils.SendRpcMessage(message, pipeName: PipeUtils.ElevatedPipe); + return ExecuteViaElevatedProcess(message); } if (!_winApiService.IsServiceRunning())