You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

HotkeySettingsForm.cs 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using Shadowsocks.Controller;
  9. using Shadowsocks.Model;
  10. using Shadowsocks.Properties;
  11. using Shadowsocks.Util;
  12. namespace Shadowsocks.View
  13. {
  14. public partial class HotkeySettingsForm : Form
  15. {
  16. private ShadowsocksController _controller;
  17. // this is a copy of configuration that we are working on
  18. private HotkeyConfig _modifiedConfig;
  19. private StringBuilder _sb = new StringBuilder();
  20. private IEnumerable<TextBox> _allTextBoxes;
  21. private static Label _lb = null;
  22. private static HotKeys.HotKeyCallBackHandler _callBack = null;
  23. public HotkeySettingsForm(ShadowsocksController controller)
  24. {
  25. InitializeComponent();
  26. UpdateTexts();
  27. this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon());
  28. _controller = controller;
  29. _controller.ConfigChanged += controller_ConfigChanged;
  30. LoadCurrentConfiguration();
  31. // get all textboxes belong to this form
  32. _allTextBoxes = HotKeys.GetChildControls<TextBox>(this.tableLayoutPanel1);
  33. if (!_allTextBoxes.Any()) throw new Exception("Cannot get all textboxes");
  34. }
  35. private void controller_ConfigChanged(object sender, EventArgs e)
  36. {
  37. LoadCurrentConfiguration();
  38. }
  39. private void LoadCurrentConfiguration()
  40. {
  41. _modifiedConfig = _controller.GetConfigurationCopy().hotkey;
  42. LoadConfiguration(_modifiedConfig);
  43. }
  44. private void LoadConfiguration(HotkeyConfig config)
  45. {
  46. SwitchSystemProxyTextBox.Text = config.SwitchSystemProxy;
  47. ChangeToPacTextBox.Text = config.ChangeToPac;
  48. ChangeToGlobalTextBox.Text = config.ChangeToGlobal;
  49. SwitchAllowLanTextBox.Text = config.SwitchAllowLan;
  50. ShowLogsTextBox.Text = config.ShowLogs;
  51. ServerMoveUpTextBox.Text = config.ServerMoveUp;
  52. ServerMoveDownTextBox.Text = config.ServerMoveDown;
  53. }
  54. private void UpdateTexts()
  55. {
  56. // I18N stuff
  57. SwitchSystemProxyLabel.Text = I18N.GetString("Switch system proxy");
  58. ChangeToPacLabel.Text = I18N.GetString("Switch to PAC mode");
  59. ChangeToGlobalLabel.Text = I18N.GetString("Switch to Global mode");
  60. SwitchAllowLanLabel.Text = I18N.GetString("Switch share over LAN");
  61. ShowLogsLabel.Text = I18N.GetString("Show Logs");
  62. ServerMoveUpLabel.Text = I18N.GetString("Switch to prev server");
  63. ServerMoveDownLabel.Text = I18N.GetString("Switch to next server");
  64. btnOK.Text = I18N.GetString("OK");
  65. btnCancel.Text = I18N.GetString("Cancel");
  66. btnRegisterAll.Text = I18N.GetString("Reg All");
  67. this.Text = I18N.GetString("Edit Hotkeys...");
  68. }
  69. /// <summary>
  70. /// Capture hotkey - Press key
  71. /// </summary>
  72. private void HotkeyDown(object sender, KeyEventArgs e)
  73. {
  74. _sb.Length = 0;
  75. //Combination key only
  76. if (e.Modifiers != 0)
  77. {
  78. // XXX: Hotkey parsing depends on the sequence, more specifically, ModifierKeysConverter.
  79. // Windows key is reserved by operating system, we deny this key.
  80. if (e.Control)
  81. {
  82. _sb.Append("Ctrl+");
  83. }
  84. if (e.Alt)
  85. {
  86. _sb.Append("Alt+");
  87. }
  88. if (e.Shift)
  89. {
  90. _sb.Append("Shift+");
  91. }
  92. Keys keyvalue = (Keys) e.KeyValue;
  93. if ((keyvalue >= Keys.PageUp && keyvalue <= Keys.Down) ||
  94. (keyvalue >= Keys.A && keyvalue <= Keys.Z) ||
  95. (keyvalue >= Keys.F1 && keyvalue <= Keys.F12))
  96. {
  97. _sb.Append(e.KeyCode);
  98. }
  99. else if (keyvalue >= Keys.D0 && keyvalue <= Keys.D9)
  100. {
  101. _sb.Append('D').Append((char) e.KeyValue);
  102. }
  103. else if (keyvalue >= Keys.NumPad0 && keyvalue <= Keys.NumPad9)
  104. {
  105. _sb.Append("NumPad").Append((char) (e.KeyValue - 48));
  106. }
  107. }
  108. ((TextBox) sender).Text = _sb.ToString();
  109. }
  110. /// <summary>
  111. /// Capture hotkey - Release key
  112. /// </summary>
  113. private void HotkeyUp(object sender, KeyEventArgs e)
  114. {
  115. TextBox tb = sender as TextBox;
  116. string content = tb.Text.TrimEnd();
  117. if (content.Length >= 1 && content[content.Length - 1] == '+')
  118. {
  119. tb.Text = "";
  120. }
  121. }
  122. private void TextBox_TextChanged(object sender, EventArgs e)
  123. {
  124. TextBox tb = sender as TextBox;
  125. if (tb.Text == "")
  126. {
  127. // unreg
  128. UnregHotkey(tb);
  129. }
  130. }
  131. private void UnregHotkey(TextBox tb)
  132. {
  133. PrepareForHotkey(tb, out _callBack, out _lb);
  134. UnregPrevHotkey(_callBack);
  135. }
  136. private void CancelButton_Click(object sender, EventArgs e)
  137. {
  138. this.Close();
  139. }
  140. private void OKButton_Click(object sender, EventArgs e)
  141. {
  142. // try to register, notify to change settings if failed
  143. foreach (var tb in _allTextBoxes)
  144. {
  145. if (tb.Text.IsNullOrEmpty())
  146. {
  147. continue;
  148. }
  149. if (!TryRegHotkey(tb))
  150. {
  151. MessageBox.Show(I18N.GetString("Register hotkey failed"));
  152. return;
  153. }
  154. }
  155. // All check passed, saving
  156. SaveConfig();
  157. this.Close();
  158. }
  159. private void RegisterAllButton_Click(object sender, EventArgs e)
  160. {
  161. foreach (var tb in _allTextBoxes)
  162. {
  163. if (tb.Text.IsNullOrEmpty())
  164. {
  165. continue;
  166. }
  167. TryRegHotkey(tb);
  168. }
  169. }
  170. private bool TryRegHotkey(TextBox tb)
  171. {
  172. var hotkey = HotKeys.Str2HotKey(tb.Text);
  173. if (hotkey == null)
  174. {
  175. MessageBox.Show(string.Format(I18N.GetString("Cannot parse hotkey: {0}"), tb.Text));
  176. tb.Clear();
  177. return false;
  178. }
  179. PrepareForHotkey(tb, out _callBack, out _lb);
  180. UnregPrevHotkey(_callBack);
  181. // try to register keys
  182. // if already registered by other progs
  183. // notify to change
  184. // use the corresponding label color to indicate
  185. // reg result.
  186. // Green: not occupied by others and operation succeed
  187. // Yellow: already registered by other program and need action: disable by clear the content
  188. // or change to another one
  189. // Transparent without color: first run or empty config
  190. bool regResult = HotKeys.Regist(hotkey, _callBack);
  191. _lb.BackColor = regResult ? Color.Green : Color.Yellow;
  192. return regResult;
  193. }
  194. private static void UnregPrevHotkey(HotKeys.HotKeyCallBackHandler cb)
  195. {
  196. GlobalHotKey.HotKey prevHotKey;
  197. if (HotKeys.IsCallbackExists(cb, out prevHotKey))
  198. {
  199. // unregister previous one
  200. HotKeys.UnRegist(prevHotKey);
  201. }
  202. }
  203. private void SaveConfig()
  204. {
  205. _modifiedConfig.SwitchSystemProxy = SwitchSystemProxyTextBox.Text;
  206. _modifiedConfig.ChangeToPac = ChangeToPacTextBox.Text;
  207. _modifiedConfig.ChangeToGlobal = ChangeToGlobalTextBox.Text;
  208. _modifiedConfig.SwitchAllowLan = SwitchAllowLanTextBox.Text;
  209. _modifiedConfig.ShowLogs = ShowLogsTextBox.Text;
  210. _modifiedConfig.ServerMoveUp = ServerMoveUpTextBox.Text;
  211. _modifiedConfig.ServerMoveDown = ServerMoveDownTextBox.Text;
  212. _controller.SaveHotkeyConfig(_modifiedConfig);
  213. }
  214. #region Callbacks
  215. private void SwitchSystemProxyCallback()
  216. {
  217. bool enabled = _controller.GetConfigurationCopy().enabled;
  218. _controller.ToggleEnable(!enabled);
  219. }
  220. private void ChangeToPacCallback()
  221. {
  222. bool enabled = _controller.GetConfigurationCopy().enabled;
  223. if (enabled == false) return;
  224. _controller.ToggleGlobal(false);
  225. }
  226. private void ChangeToGlobalCallback()
  227. {
  228. bool enabled = _controller.GetConfigurationCopy().enabled;
  229. if (enabled == false) return;
  230. _controller.ToggleGlobal(true);
  231. }
  232. private void SwitchAllowLanCallback()
  233. {
  234. var status = _controller.GetConfigurationCopy().shareOverLan;
  235. _controller.ToggleShareOverLAN(!status);
  236. }
  237. private void ShowLogsCallback()
  238. {
  239. // Get the current MenuViewController in this program via reflection
  240. FieldInfo fi = Assembly.GetExecutingAssembly().GetType("Shadowsocks.Program")
  241. .GetField("_viewController",
  242. BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase);
  243. // To retrieve the value of a static field, pass null here
  244. var mvc = fi.GetValue(null) as MenuViewController;
  245. mvc.ShowLogForm_HotKey();
  246. }
  247. private void ServerMoveUpCallback()
  248. {
  249. int currIndex;
  250. int serverCount;
  251. GetCurrServerInfo(out currIndex, out serverCount);
  252. if (currIndex - 1 < 0)
  253. {
  254. // revert to last server
  255. currIndex = serverCount - 1;
  256. }
  257. else
  258. {
  259. currIndex -= 1;
  260. }
  261. _controller.SelectServerIndex(currIndex);
  262. }
  263. private void ServerMoveDownCallback()
  264. {
  265. int currIndex;
  266. int serverCount;
  267. GetCurrServerInfo(out currIndex, out serverCount);
  268. if (currIndex + 1 == serverCount)
  269. {
  270. // revert to first server
  271. currIndex = 0;
  272. }
  273. else
  274. {
  275. currIndex += 1;
  276. }
  277. _controller.SelectServerIndex(currIndex);
  278. }
  279. private void GetCurrServerInfo(out int currIndex, out int serverCount)
  280. {
  281. var currConfig = _controller.GetCurrentConfiguration();
  282. currIndex = currConfig.index;
  283. serverCount = currConfig.configs.Count;
  284. }
  285. #endregion
  286. #region Prepare hotkey
  287. /// <summary>
  288. /// Find correct callback and corresponding label
  289. /// </summary>
  290. /// <param name="tb"></param>
  291. /// <param name="cb"></param>
  292. /// <param name="lb"></param>
  293. private void PrepareForHotkey(TextBox tb, out HotKeys.HotKeyCallBackHandler cb, out Label lb)
  294. {
  295. /*
  296. * XXX: The labelName, TextBoxName and callbackName
  297. * must follow this rule to make use of reflection
  298. *
  299. * <BaseName><Control-Type-Name>
  300. */
  301. if (tb == null)
  302. throw new ArgumentNullException(nameof(tb));
  303. var pos = tb.Name.LastIndexOf("TextBox", StringComparison.OrdinalIgnoreCase);
  304. var rawName = tb.Name.Substring(0, pos);
  305. var labelName = rawName + "Label";
  306. var callbackName = rawName + "Callback";
  307. var callback = GetDelegateViaMethodName(this.GetType(), callbackName);
  308. if (callback == null)
  309. {
  310. throw new Exception($"{callbackName} not found");
  311. }
  312. cb = callback as HotKeys.HotKeyCallBackHandler;
  313. object label = GetFieldViaName(this.GetType(), labelName, this);
  314. if (label == null)
  315. {
  316. throw new Exception($"{labelName} not found");
  317. }
  318. lb = label as Label;
  319. }
  320. /// <summary>
  321. ///
  322. /// </summary>
  323. /// <param name="type">from which type</param>
  324. /// <param name="name">field name</param>
  325. /// <param name="obj">pass null if static field</param>
  326. /// <returns></returns>
  327. private static object GetFieldViaName(Type type, string name, object obj)
  328. {
  329. if (type == null) throw new ArgumentNullException(nameof(type));
  330. if (name.IsNullOrEmpty()) throw new ArgumentException(nameof(name));
  331. // In general, TextBoxes and Labels are private
  332. FieldInfo fi = type.GetField(name,
  333. BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Static);
  334. return fi == null ? null : fi.GetValue(obj);
  335. }
  336. /// <summary>
  337. /// Create hotkey callback handler delegate based on callback name
  338. /// </summary>
  339. /// <param name="type"></param>
  340. /// <param name="methodname"></param>
  341. /// <returns></returns>
  342. private Delegate GetDelegateViaMethodName(Type type, string methodname)
  343. {
  344. if (type == null) throw new ArgumentNullException(nameof(type));
  345. if (methodname.IsNullOrEmpty()) throw new ArgumentException(nameof(methodname));
  346. //HotkeySettingsForm form = new HotkeySettingsForm(_controller);
  347. Type delegateType = Type.GetType("Shadowsocks.Util.HotKeys").GetNestedType("HotKeyCallBackHandler");
  348. MethodInfo dynMethod = type.GetMethod(methodname,
  349. BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
  350. return dynMethod == null ? null : Delegate.CreateDelegate(delegateType, this, dynMethod);
  351. }
  352. #endregion
  353. }
  354. }