HotkeyConflictHelper.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System; 6 using System.Collections.Generic; 7 using System.Text.Json.Nodes; 8 using Microsoft.PowerToys.Settings.UI.Library; 9 10 namespace Microsoft.PowerToys.Settings.UI.Helpers 11 { 12 public class HotkeyConflictHelper 13 { 14 public delegate void HotkeyConflictCheckCallback(bool hasConflict, HotkeyConflictResponse conflicts); 15 16 private static readonly Dictionary<string, HotkeyConflictCheckCallback> PendingHotkeyConflictChecks = new Dictionary<string, HotkeyConflictCheckCallback>(); 17 private static readonly object LockObject = new object(); 18 19 public static void CheckHotkeyConflict(HotkeySettings hotkeySettings, Func<string, int> ipcMSGCallBackFunc, HotkeyConflictCheckCallback callback) 20 { 21 if (hotkeySettings == null || ipcMSGCallBackFunc == null) 22 { 23 return; 24 } 25 26 string requestId = GenerateRequestId(); 27 28 lock (LockObject) 29 { 30 PendingHotkeyConflictChecks[requestId] = callback; 31 } 32 33 var hotkeyObj = new JsonObject 34 { 35 ["request_id"] = requestId, 36 ["win"] = hotkeySettings.Win, 37 ["ctrl"] = hotkeySettings.Ctrl, 38 ["shift"] = hotkeySettings.Shift, 39 ["alt"] = hotkeySettings.Alt, 40 ["key"] = hotkeySettings.Code, 41 }; 42 43 var requestObject = new JsonObject 44 { 45 ["check_hotkey_conflict"] = hotkeyObj, 46 }; 47 48 ipcMSGCallBackFunc(requestObject.ToString()); 49 } 50 51 public static void HandleHotkeyConflictResponse(HotkeyConflictResponse response) 52 { 53 if (response.AllConflicts.Count == 0) 54 { 55 return; 56 } 57 58 HotkeyConflictCheckCallback callback = null; 59 60 lock (LockObject) 61 { 62 if (PendingHotkeyConflictChecks.TryGetValue(response.RequestId, out callback)) 63 { 64 PendingHotkeyConflictChecks.Remove(response.RequestId); 65 } 66 } 67 68 callback?.Invoke(response.HasConflict, response); 69 } 70 71 private static string GenerateRequestId() => Guid.NewGuid().ToString(); 72 } 73 }