KeybindTextBox.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System.Runtime.InteropServices;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.Input;
  5. using Avalonia.Interactivity;
  6. using Avalonia.Media;
  7. using Avalonia.Styling;
  8. using Avalonia.Threading;
  9. using PicView.Avalonia.Functions;
  10. using PicView.Avalonia.Input;
  11. using PicView.Avalonia.UI;
  12. using PicView.Core.Localization;
  13. using R3;
  14. namespace PicView.Avalonia.CustomControls;
  15. /// <summary>
  16. /// A custom TextBox control for managing key bindings.
  17. /// </summary>
  18. public class KeybindTextBox : TextBox
  19. {
  20. public static readonly AvaloniaProperty<KeyGesture?> KeybindProperty =
  21. AvaloniaProperty.Register<KeybindTextBox, KeyGesture?>(nameof(Keybind));
  22. public static readonly AvaloniaProperty<string?> MethodNameProperty =
  23. AvaloniaProperty.Register<KeybindTextBox, string?>(nameof(MethodName));
  24. public static readonly AvaloniaProperty<bool?> AltProperty =
  25. AvaloniaProperty.Register<KeybindTextBox, bool?>(nameof(Alt));
  26. private readonly CompositeDisposable _disposables = new();
  27. public KeybindTextBox()
  28. {
  29. SubscribeToMethodNameChanges();
  30. SetupKeyEventHandlers();
  31. GotFocus += OnGotFocus;
  32. LostFocus += OnLostFocus;
  33. }
  34. protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
  35. {
  36. base.OnDetachedFromVisualTree(e);
  37. _disposables.Dispose();
  38. }
  39. protected override Type StyleKeyOverride => typeof(TextBox);
  40. public KeyGesture? Keybind
  41. {
  42. get => GetValue(KeybindProperty) as KeyGesture;
  43. set => SetValue(KeybindProperty, value);
  44. }
  45. public string MethodName
  46. {
  47. get => (string)(GetValue(MethodNameProperty) ?? "");
  48. set => SetValue(MethodNameProperty, value);
  49. }
  50. public bool Alt
  51. {
  52. get => (bool)(GetValue(AltProperty) ?? false);
  53. set => SetValue(AltProperty, value);
  54. }
  55. private void SubscribeToMethodNameChanges()
  56. {
  57. this.GetObservable(MethodNameProperty).ToObservable()
  58. .Subscribe(_ => Text = GetFunctionKey())
  59. .AddTo(_disposables);
  60. }
  61. private void SetupKeyEventHandlers()
  62. {
  63. if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  64. {
  65. var keyUp = Observable.FromEventHandler<KeyEventArgs>(handler => KeyUp += handler, handler => KeyUp -= handler);
  66. keyUp.Select(e => e.e)
  67. .ObserveOn(UIHelper.GetFrameProvider)
  68. .SubscribeAwait(async (e, _) => await AssociateKey(e))
  69. .AddTo(_disposables);
  70. // On macOS, we only get KeyUp because the option to select a different character
  71. // when a key is held down interferes with keyboard shortcuts
  72. }
  73. else
  74. {
  75. var keyDown = Observable.FromEventHandler<KeyEventArgs>(handler => KeyDown += handler, handler => KeyDown -= handler);
  76. keyDown.Select(e => e.e)
  77. .ObserveOn(UIHelper.GetFrameProvider)
  78. .SubscribeAwait(async (e, _) => await AssociateKey(e))
  79. .AddTo(_disposables);
  80. var keyUp = Observable.FromEventHandler<KeyEventArgs>(handler => KeyUp += handler, handler => KeyUp -= handler);
  81. keyUp.Select(e => e.e)
  82. .ObserveOn(UIHelper.GetFrameProvider)
  83. .Subscribe(_ => KeyUpHandler())
  84. .AddTo(_disposables);
  85. }
  86. }
  87. protected override void OnKeyDown(KeyEventArgs e)
  88. {
  89. // Disable keyboard behavior #248
  90. // Fix tab
  91. if (e.Key == Key.Tab)
  92. {
  93. _ = AssociateKey(e);
  94. }
  95. }
  96. private void OnGotFocus(object? sender, GotFocusEventArgs e)
  97. {
  98. if (IsReadOnly)
  99. {
  100. ApplyReadOnlyBorderColor();
  101. return;
  102. }
  103. ApplyEditableForegroundColor();
  104. Text = TranslationManager.Translation.PressKey;
  105. CaretIndex = 0;
  106. MainKeyboardShortcuts.IsEscKeyEnabled = false;
  107. }
  108. private void OnLostFocus(object? sender, RoutedEventArgs e)
  109. {
  110. ApplyDefaultForegroundColor();
  111. Text = GetFunctionKey();
  112. MainKeyboardShortcuts.IsEscKeyEnabled = true;
  113. }
  114. private void KeyUpHandler()
  115. {
  116. ApplyDefaultForegroundColor();
  117. Text = GetFunctionKey();
  118. }
  119. private void ApplyReadOnlyBorderColor()
  120. {
  121. if (this.TryFindResource("MainBorderColor", ThemeVariant.Default, out var borderColor))
  122. {
  123. var borderBrush = new SolidColorBrush((Color)(borderColor ?? Color.Parse("#FFf6f4f4")));
  124. BorderBrush = borderBrush;
  125. }
  126. }
  127. private void ApplyEditableForegroundColor()
  128. {
  129. if (this.TryFindResource("MainTextColorFaded", ThemeVariant.Default, out var color))
  130. {
  131. Foreground = new SolidColorBrush((Color)(color ?? Color.Parse("#d6d4d4")));
  132. }
  133. }
  134. private void ApplyDefaultForegroundColor()
  135. {
  136. if (this.TryFindResource("MainTextColor", ThemeVariant.Default, out var color))
  137. {
  138. Foreground = new SolidColorBrush((Color)(color ?? Color.Parse("#FFf6f4f4")));
  139. }
  140. }
  141. private async Task AssociateKey(KeyEventArgs e)
  142. {
  143. switch (e.Key)
  144. {
  145. case Key.LeftShift:
  146. case Key.RightShift:
  147. case Key.LeftCtrl:
  148. case Key.RightCtrl:
  149. case Key.LeftAlt:
  150. case Key.RightAlt:
  151. case Key.LWin:
  152. case Key.RWin:
  153. return;
  154. }
  155. KeybindingManager.CustomShortcuts.Remove(new KeyGesture(e.Key, e.KeyModifiers));
  156. var function = await FunctionsMapper.GetFunctionByName(MethodName);
  157. if (function == null)
  158. {
  159. return;
  160. }
  161. if (e.Key == Key.Escape)
  162. {
  163. e.Handled = true;
  164. MainKeyboardShortcuts.IsEscKeyEnabled = false;
  165. await Dispatcher.UIThread.InvokeAsync(() => { Text = string.Empty; });
  166. Remove();
  167. await Save();
  168. return;
  169. }
  170. // Handle whether it's an alternative key or not
  171. if (Alt)
  172. {
  173. if (KeybindingManager.CustomShortcuts.ContainsValue(function))
  174. {
  175. // If the main key is not present, add a new entry with the alternative key
  176. var altKey = (Key)Enum.Parse(typeof(Key), e.Key.ToString());
  177. var keyGesture = new KeyGesture(altKey, e.KeyModifiers);
  178. KeybindingManager.CustomShortcuts[keyGesture] = function;
  179. }
  180. else
  181. {
  182. // Update the key and function name in the CustomShortcuts dictionary
  183. var keyGesture = new KeyGesture(e.Key, e.KeyModifiers);
  184. KeybindingManager.CustomShortcuts[keyGesture] = function;
  185. }
  186. }
  187. else
  188. {
  189. // Remove if it already contains
  190. if (KeybindingManager.CustomShortcuts.ContainsValue(function))
  191. {
  192. Remove();
  193. }
  194. var keyGesture = new KeyGesture(e.Key, e.KeyModifiers);
  195. KeybindingManager.CustomShortcuts[keyGesture] = function;
  196. }
  197. if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  198. {
  199. KeyUpHandler();
  200. }
  201. await Save();
  202. return;
  203. async Task Save()
  204. {
  205. await KeybindingManager.UpdateKeyBindingsFile();
  206. }
  207. void Remove()
  208. {
  209. var keys = KeybindingManager.CustomShortcuts.Where(x => x.Value?.Method?.Name == MethodName)
  210. ?.Select(x => x.Key).ToList() ?? null;
  211. if (keys is not null)
  212. {
  213. KeybindingManager.CustomShortcuts.Remove(Alt ? keys.LastOrDefault() : keys.FirstOrDefault());
  214. }
  215. }
  216. }
  217. private string GetFunctionKey()
  218. {
  219. if (string.IsNullOrEmpty(MethodName))
  220. {
  221. return string.Empty;
  222. }
  223. if (IsReadOnly)
  224. {
  225. switch (MethodName)
  226. {
  227. case "ScrollUpInternal":
  228. var rotateRightKey = KeybindingManager.CustomShortcuts.Where(x => x.Value?.Method?.Name == "Up")
  229. ?.Select(x => x.Key).ToList() ?? null;
  230. return rotateRightKey is not { Count: > 0 } ? string.Empty :
  231. Alt ? rotateRightKey.LastOrDefault().ToString() : rotateRightKey.FirstOrDefault().ToString();
  232. case "ScrollDownInternal":
  233. var rotateLeftKey = KeybindingManager.CustomShortcuts.Where(x => x.Value?.Method?.Name == "Down")
  234. ?.Select(x => x.Key).ToList() ?? null;
  235. return rotateLeftKey is not { Count: > 0 } ? string.Empty :
  236. Alt ? rotateLeftKey.LastOrDefault().ToString() : rotateLeftKey.FirstOrDefault().ToString();
  237. }
  238. }
  239. // Find the key associated with the specified function
  240. var keys = KeybindingManager.CustomShortcuts.Where(x => x.Value?.Method?.Name == MethodName)?.Select(x => x.Key)
  241. .ToList() ?? null;
  242. if (keys is null)
  243. {
  244. return string.Empty;
  245. }
  246. return keys.Count switch
  247. {
  248. <= 0 => string.Empty,
  249. 1 => Alt ? string.Empty : FormatPlus(keys.FirstOrDefault().ToString()),
  250. _ => Alt ? FormatPlus(keys.LastOrDefault().ToString()) : FormatPlus(keys.FirstOrDefault().ToString())
  251. };
  252. string FormatPlus(string value)
  253. {
  254. return string.IsNullOrEmpty(value) ? string.Empty : value.Replace("+", " + ");
  255. }
  256. }
  257. }