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.

MenuViewController.cs 38 kB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. using System;
  2. using System.Diagnostics;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Windows.Forms;
  6. using ZXing;
  7. using ZXing.Common;
  8. using ZXing.QrCode;
  9. using Shadowsocks.Controller;
  10. using Shadowsocks.Model;
  11. using Shadowsocks.Properties;
  12. using Shadowsocks.Util;
  13. using System.Linq;
  14. using Microsoft.Win32;
  15. using System.Windows.Interop;
  16. namespace Shadowsocks.View
  17. {
  18. public class MenuViewController
  19. {
  20. // yes this is just a menu view controller
  21. // when config form is closed, it moves away from RAM
  22. // and it should just do anything related to the config form
  23. private ShadowsocksController controller;
  24. private UpdateChecker updateChecker;
  25. private NotifyIcon _notifyIcon;
  26. private Icon icon, icon_in, icon_out, icon_both, previousIcon;
  27. private bool _isFirstRun;
  28. private bool _isStartupChecking;
  29. private string _urlToOpen;
  30. private ContextMenu contextMenu1;
  31. private MenuItem disableItem;
  32. private MenuItem AutoStartupItem;
  33. private MenuItem ShareOverLANItem;
  34. private MenuItem SeperatorItem;
  35. private MenuItem ConfigItem;
  36. private MenuItem ServersItem;
  37. private MenuItem globalModeItem;
  38. private MenuItem PACModeItem;
  39. private MenuItem localPACItem;
  40. private MenuItem onlinePACItem;
  41. private MenuItem editLocalPACItem;
  42. private MenuItem updateFromGFWListItem;
  43. private MenuItem editGFWUserRuleItem;
  44. private MenuItem editOnlinePACItem;
  45. private MenuItem secureLocalPacUrlToggleItem;
  46. private MenuItem autoCheckUpdatesToggleItem;
  47. private MenuItem checkPreReleaseToggleItem;
  48. private MenuItem proxyItem;
  49. private MenuItem hotKeyItem;
  50. private MenuItem VerboseLoggingToggleItem;
  51. private ConfigForm configForm;
  52. private ProxyForm proxyForm;
  53. private LogForm logForm;
  54. private HotkeySettingsForm hotkeySettingsForm;
  55. // color definition for icon color transformation
  56. private readonly Color colorMaskBlue = Color.FromArgb(255, 25, 125, 191);
  57. private readonly Color colorMaskDarkSilver = Color.FromArgb(128, 192, 192, 192);
  58. private readonly Color colorMaskLightSilver = Color.FromArgb(192, 192, 192, 192);
  59. private readonly Color colorMaskEclipse = Color.FromArgb(192, 64, 64, 64);
  60. public MenuViewController(ShadowsocksController controller)
  61. {
  62. this.controller = controller;
  63. LoadMenu();
  64. controller.EnableStatusChanged += controller_EnableStatusChanged;
  65. controller.ConfigChanged += controller_ConfigChanged;
  66. controller.PACFileReadyToOpen += controller_FileReadyToOpen;
  67. controller.UserRuleFileReadyToOpen += controller_FileReadyToOpen;
  68. controller.ShareOverLANStatusChanged += controller_ShareOverLANStatusChanged;
  69. controller.VerboseLoggingStatusChanged += controller_VerboseLoggingStatusChanged;
  70. controller.EnableGlobalChanged += controller_EnableGlobalChanged;
  71. controller.Errored += controller_Errored;
  72. controller.UpdatePACFromGFWListCompleted += controller_UpdatePACFromGFWListCompleted;
  73. controller.UpdatePACFromGFWListError += controller_UpdatePACFromGFWListError;
  74. _notifyIcon = new NotifyIcon();
  75. UpdateTrayIconAndNotifyText();
  76. _notifyIcon.Visible = true;
  77. _notifyIcon.ContextMenu = contextMenu1;
  78. _notifyIcon.BalloonTipClicked += notifyIcon1_BalloonTipClicked;
  79. _notifyIcon.MouseClick += notifyIcon1_Click;
  80. _notifyIcon.MouseDoubleClick += notifyIcon1_DoubleClick;
  81. _notifyIcon.BalloonTipClosed += _notifyIcon_BalloonTipClosed;
  82. controller.TrafficChanged += controller_TrafficChanged;
  83. this.updateChecker = new UpdateChecker();
  84. updateChecker.CheckUpdateCompleted += updateChecker_CheckUpdateCompleted;
  85. LoadCurrentConfiguration();
  86. Configuration config = controller.GetConfigurationCopy();
  87. if (config.isDefault)
  88. {
  89. _isFirstRun = true;
  90. ShowConfigForm();
  91. }
  92. else if (config.autoCheckUpdate)
  93. {
  94. _isStartupChecking = true;
  95. updateChecker.CheckUpdate(config, 3000);
  96. }
  97. }
  98. private void controller_TrafficChanged(object sender, EventArgs e)
  99. {
  100. if (icon == null)
  101. return;
  102. Icon newIcon;
  103. bool hasInbound = controller.trafficPerSecondQueue.Last().inboundIncreasement > 0;
  104. bool hasOutbound = controller.trafficPerSecondQueue.Last().outboundIncreasement > 0;
  105. if (hasInbound && hasOutbound)
  106. newIcon = icon_both;
  107. else if (hasInbound)
  108. newIcon = icon_in;
  109. else if (hasOutbound)
  110. newIcon = icon_out;
  111. else
  112. newIcon = icon;
  113. if (newIcon != this.previousIcon)
  114. {
  115. this.previousIcon = newIcon;
  116. _notifyIcon.Icon = newIcon;
  117. }
  118. }
  119. void controller_Errored(object sender, System.IO.ErrorEventArgs e)
  120. {
  121. MessageBox.Show(e.GetException().ToString(), I18N.GetString("Shadowsocks Error: {0}", e.GetException().Message));
  122. }
  123. #region Tray Icon
  124. private void UpdateTrayIconAndNotifyText()
  125. {
  126. Configuration config = controller.GetConfigurationCopy();
  127. bool enabled = config.enabled;
  128. bool global = config.global;
  129. Color colorMask = SelectColorMask(enabled, global);
  130. Size iconSize = SelectIconSize();
  131. UpdateIconSet(colorMask, iconSize, out icon, out icon_in, out icon_out, out icon_both);
  132. previousIcon = icon;
  133. _notifyIcon.Icon = previousIcon;
  134. string serverInfo = null;
  135. if (controller.GetCurrentStrategy() != null)
  136. {
  137. serverInfo = controller.GetCurrentStrategy().Name;
  138. }
  139. else
  140. {
  141. serverInfo = config.GetCurrentServer().FriendlyName();
  142. }
  143. // show more info by hacking the P/Invoke declaration for NOTIFYICONDATA inside Windows Forms
  144. string text = I18N.GetString("Shadowsocks") + " " + UpdateChecker.Version + "\n" +
  145. (enabled ?
  146. I18N.GetString("System Proxy On: ") + (global ? I18N.GetString("Global") : I18N.GetString("PAC")) :
  147. I18N.GetString("Running: Port {0}", config.localPort)) // this feedback is very important because they need to know Shadowsocks is running
  148. + "\n" + serverInfo;
  149. if (text.Length > 127)
  150. {
  151. text = text.Substring(0, 126 - 3) + "...";
  152. }
  153. ViewUtils.SetNotifyIconText(_notifyIcon, text);
  154. }
  155. /// <summary>
  156. /// Determine the icon size based on the screen DPI.
  157. /// </summary>
  158. /// <returns></returns>
  159. /// https://stackoverflow.com/a/40851713/2075611
  160. private Size SelectIconSize()
  161. {
  162. Size size = new Size(32, 32);
  163. int dpi = ViewUtils.GetScreenDpi();
  164. if (dpi < 97)
  165. {
  166. // dpi = 96;
  167. size = new Size(16, 16);
  168. }
  169. else if (dpi < 121)
  170. {
  171. // dpi = 120;
  172. size = new Size(20, 20);
  173. }
  174. else if (dpi < 145)
  175. {
  176. // dpi = 144;
  177. size = new Size(24, 24);
  178. }
  179. else
  180. {
  181. // dpi = 168;
  182. size = new Size(28, 28);
  183. }
  184. return size;
  185. }
  186. private Color SelectColorMask(bool isProxyEnabled, bool isGlobalProxy)
  187. {
  188. Color colorMask = Color.White;
  189. Utils.WindowsThemeMode currentWindowsThemeMode = Utils.GetWindows10SystemThemeSetting();
  190. if (isProxyEnabled)
  191. {
  192. if (isGlobalProxy) // global
  193. {
  194. colorMask = colorMaskBlue;
  195. }
  196. else // PAC
  197. {
  198. if (currentWindowsThemeMode == Utils.WindowsThemeMode.Light)
  199. {
  200. colorMask = colorMaskEclipse;
  201. }
  202. }
  203. }
  204. else // disabled
  205. {
  206. if (currentWindowsThemeMode == Utils.WindowsThemeMode.Light)
  207. {
  208. colorMask = colorMaskDarkSilver;
  209. }
  210. else
  211. {
  212. colorMask = colorMaskLightSilver;
  213. }
  214. }
  215. return colorMask;
  216. }
  217. private void UpdateIconSet(Color colorMask, Size size,
  218. out Icon icon, out Icon icon_in, out Icon icon_out, out Icon icon_both)
  219. {
  220. Bitmap iconBitmap;
  221. // generate the base icon
  222. iconBitmap = ViewUtils.ChangeBitmapColor(Resources.ss32Fill, colorMask);
  223. iconBitmap = ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32Outline);
  224. icon = Icon.FromHandle(ViewUtils.ResizeBitmap(iconBitmap, size.Width, size.Height).GetHicon());
  225. icon_in = Icon.FromHandle(ViewUtils.ResizeBitmap(ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32In), size.Width, size.Height).GetHicon());
  226. icon_out = Icon.FromHandle(ViewUtils.ResizeBitmap(ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32In), size.Width, size.Height).GetHicon());
  227. icon_both = Icon.FromHandle(ViewUtils.ResizeBitmap(ViewUtils.AddBitmapOverlay(iconBitmap, Resources.ss32In, Resources.ss32Out), size.Width, size.Height).GetHicon());
  228. }
  229. #endregion
  230. #region MenuItems and MenuGroups
  231. private MenuItem CreateMenuItem(string text, EventHandler click)
  232. {
  233. return new MenuItem(I18N.GetString(text), click);
  234. }
  235. private MenuItem CreateMenuGroup(string text, MenuItem[] items)
  236. {
  237. return new MenuItem(I18N.GetString(text), items);
  238. }
  239. private void LoadMenu()
  240. {
  241. this.contextMenu1 = new ContextMenu(new MenuItem[] {
  242. CreateMenuGroup("System Proxy", new MenuItem[] {
  243. this.disableItem = CreateMenuItem("Disable", new EventHandler(this.EnableItem_Click)),
  244. this.PACModeItem = CreateMenuItem("PAC", new EventHandler(this.PACModeItem_Click)),
  245. this.globalModeItem = CreateMenuItem("Global", new EventHandler(this.GlobalModeItem_Click))
  246. }),
  247. this.ServersItem = CreateMenuGroup("Servers", new MenuItem[] {
  248. this.SeperatorItem = new MenuItem("-"),
  249. this.ConfigItem = CreateMenuItem("Edit Servers...", new EventHandler(this.Config_Click)),
  250. CreateMenuItem("Statistics Config...", StatisticsConfigItem_Click),
  251. new MenuItem("-"),
  252. CreateMenuItem("Share Server Config...", new EventHandler(this.QRCodeItem_Click)),
  253. CreateMenuItem("Scan QRCode from Screen...", new EventHandler(this.ScanQRCodeItem_Click)),
  254. CreateMenuItem("Import URL from Clipboard...", new EventHandler(this.ImportURLItem_Click))
  255. }),
  256. CreateMenuGroup("PAC ", new MenuItem[] {
  257. this.localPACItem = CreateMenuItem("Local PAC", new EventHandler(this.LocalPACItem_Click)),
  258. this.onlinePACItem = CreateMenuItem("Online PAC", new EventHandler(this.OnlinePACItem_Click)),
  259. new MenuItem("-"),
  260. this.editLocalPACItem = CreateMenuItem("Edit Local PAC File...", new EventHandler(this.EditPACFileItem_Click)),
  261. this.updateFromGFWListItem = CreateMenuItem("Update Local PAC from GFWList", new EventHandler(this.UpdatePACFromGFWListItem_Click)),
  262. this.editGFWUserRuleItem = CreateMenuItem("Edit User Rule for GFWList...", new EventHandler(this.EditUserRuleFileForGFWListItem_Click)),
  263. this.secureLocalPacUrlToggleItem = CreateMenuItem("Secure Local PAC", new EventHandler(this.SecureLocalPacUrlToggleItem_Click)),
  264. CreateMenuItem("Copy Local PAC URL", new EventHandler(this.CopyLocalPacUrlItem_Click)),
  265. this.editOnlinePACItem = CreateMenuItem("Edit Online PAC URL...", new EventHandler(this.UpdateOnlinePACURLItem_Click)),
  266. }),
  267. this.proxyItem = CreateMenuItem("Forward Proxy...", new EventHandler(this.proxyItem_Click)),
  268. new MenuItem("-"),
  269. this.AutoStartupItem = CreateMenuItem("Start on Boot", new EventHandler(this.AutoStartupItem_Click)),
  270. this.ShareOverLANItem = CreateMenuItem("Allow other Devices to connect", new EventHandler(this.ShareOverLANItem_Click)),
  271. new MenuItem("-"),
  272. this.hotKeyItem = CreateMenuItem("Edit Hotkeys...", new EventHandler(this.hotKeyItem_Click)),
  273. CreateMenuGroup("Help", new MenuItem[] {
  274. CreateMenuItem("Show Logs...", new EventHandler(this.ShowLogItem_Click)),
  275. this.VerboseLoggingToggleItem = CreateMenuItem( "Verbose Logging", new EventHandler(this.VerboseLoggingToggleItem_Click) ),
  276. CreateMenuGroup("Updates...", new MenuItem[] {
  277. CreateMenuItem("Check for Updates...", new EventHandler(this.checkUpdatesItem_Click)),
  278. new MenuItem("-"),
  279. this.autoCheckUpdatesToggleItem = CreateMenuItem("Check for Updates at Startup", new EventHandler(this.autoCheckUpdatesToggleItem_Click)),
  280. this.checkPreReleaseToggleItem = CreateMenuItem("Check Pre-release Version", new EventHandler(this.checkPreReleaseToggleItem_Click)),
  281. }),
  282. CreateMenuItem("About...", new EventHandler(this.AboutItem_Click)),
  283. }),
  284. new MenuItem("-"),
  285. CreateMenuItem("Quit", new EventHandler(this.Quit_Click))
  286. });
  287. }
  288. #endregion
  289. private void controller_ConfigChanged(object sender, EventArgs e)
  290. {
  291. LoadCurrentConfiguration();
  292. UpdateTrayIconAndNotifyText();
  293. }
  294. private void controller_EnableStatusChanged(object sender, EventArgs e)
  295. {
  296. disableItem.Checked = !controller.GetConfigurationCopy().enabled;
  297. }
  298. void controller_ShareOverLANStatusChanged(object sender, EventArgs e)
  299. {
  300. ShareOverLANItem.Checked = controller.GetConfigurationCopy().shareOverLan;
  301. }
  302. void controller_VerboseLoggingStatusChanged(object sender, EventArgs e)
  303. {
  304. VerboseLoggingToggleItem.Checked = controller.GetConfigurationCopy().isVerboseLogging;
  305. }
  306. void controller_EnableGlobalChanged(object sender, EventArgs e)
  307. {
  308. globalModeItem.Checked = controller.GetConfigurationCopy().global;
  309. PACModeItem.Checked = !globalModeItem.Checked;
  310. }
  311. void controller_FileReadyToOpen(object sender, ShadowsocksController.PathEventArgs e)
  312. {
  313. string argument = @"/select, " + e.Path;
  314. System.Diagnostics.Process.Start("explorer.exe", argument);
  315. }
  316. void ShowBalloonTip(string title, string content, ToolTipIcon icon, int timeout)
  317. {
  318. _notifyIcon.BalloonTipTitle = title;
  319. _notifyIcon.BalloonTipText = content;
  320. _notifyIcon.BalloonTipIcon = icon;
  321. _notifyIcon.ShowBalloonTip(timeout);
  322. }
  323. void controller_UpdatePACFromGFWListError(object sender, System.IO.ErrorEventArgs e)
  324. {
  325. ShowBalloonTip(I18N.GetString("Failed to update PAC file"), e.GetException().Message, ToolTipIcon.Error, 5000);
  326. Logging.LogUsefulException(e.GetException());
  327. }
  328. void controller_UpdatePACFromGFWListCompleted(object sender, GFWListUpdater.ResultEventArgs e)
  329. {
  330. string result = e.Success
  331. ? I18N.GetString("PAC updated")
  332. : I18N.GetString("No updates found. Please report to GFWList if you have problems with it.");
  333. ShowBalloonTip(I18N.GetString("Shadowsocks"), result, ToolTipIcon.Info, 1000);
  334. }
  335. void updateChecker_CheckUpdateCompleted(object sender, EventArgs e)
  336. {
  337. if (updateChecker.NewVersionFound)
  338. {
  339. ShowBalloonTip(I18N.GetString("Shadowsocks {0} Update Found", updateChecker.LatestVersionNumber + updateChecker.LatestVersionSuffix), I18N.GetString("Click here to update"), ToolTipIcon.Info, 5000);
  340. }
  341. else if (!_isStartupChecking)
  342. {
  343. ShowBalloonTip(I18N.GetString("Shadowsocks"), I18N.GetString("No update is available"), ToolTipIcon.Info, 5000);
  344. }
  345. _isStartupChecking = false;
  346. }
  347. void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
  348. {
  349. if (updateChecker.NewVersionFound)
  350. {
  351. updateChecker.NewVersionFound = false; /* Reset the flag */
  352. if (System.IO.File.Exists(updateChecker.LatestVersionLocalName))
  353. {
  354. string argument = "/select, \"" + updateChecker.LatestVersionLocalName + "\"";
  355. System.Diagnostics.Process.Start("explorer.exe", argument);
  356. }
  357. }
  358. }
  359. private void _notifyIcon_BalloonTipClosed(object sender, EventArgs e)
  360. {
  361. if (updateChecker.NewVersionFound)
  362. {
  363. updateChecker.NewVersionFound = false; /* Reset the flag */
  364. }
  365. }
  366. private void LoadCurrentConfiguration()
  367. {
  368. Configuration config = controller.GetConfigurationCopy();
  369. UpdateServersMenu();
  370. UpdateSystemProxyItemsEnabledStatus(config);
  371. ShareOverLANItem.Checked = config.shareOverLan;
  372. VerboseLoggingToggleItem.Checked = config.isVerboseLogging;
  373. AutoStartupItem.Checked = AutoStartup.Check();
  374. onlinePACItem.Checked = onlinePACItem.Enabled && config.useOnlinePac;
  375. localPACItem.Checked = !onlinePACItem.Checked;
  376. secureLocalPacUrlToggleItem.Checked = config.secureLocalPac;
  377. UpdatePACItemsEnabledStatus();
  378. UpdateUpdateMenu();
  379. }
  380. private void UpdateServersMenu()
  381. {
  382. var items = ServersItem.MenuItems;
  383. while (items[0] != SeperatorItem)
  384. {
  385. items.RemoveAt(0);
  386. }
  387. int i = 0;
  388. foreach (var strategy in controller.GetStrategies())
  389. {
  390. MenuItem item = new MenuItem(strategy.Name);
  391. item.Tag = strategy.ID;
  392. item.Click += AStrategyItem_Click;
  393. items.Add(i, item);
  394. i++;
  395. }
  396. // user wants a seperator item between strategy and servers menugroup
  397. items.Add(i++, new MenuItem("-"));
  398. int strategyCount = i;
  399. Configuration configuration = controller.GetConfigurationCopy();
  400. foreach (var server in configuration.configs)
  401. {
  402. if (Configuration.ChecksServer(server))
  403. {
  404. MenuItem item = new MenuItem(server.FriendlyName());
  405. item.Tag = i - strategyCount;
  406. item.Click += AServerItem_Click;
  407. items.Add(i, item);
  408. i++;
  409. }
  410. }
  411. foreach (MenuItem item in items)
  412. {
  413. if (item.Tag != null && (item.Tag.ToString() == configuration.index.ToString() || item.Tag.ToString() == configuration.strategy))
  414. {
  415. item.Checked = true;
  416. }
  417. }
  418. }
  419. private void ShowConfigForm()
  420. {
  421. if (configForm != null)
  422. {
  423. configForm.Activate();
  424. }
  425. else
  426. {
  427. configForm = new ConfigForm(controller);
  428. configForm.Show();
  429. configForm.Activate();
  430. configForm.FormClosed += configForm_FormClosed;
  431. }
  432. }
  433. private void ShowProxyForm()
  434. {
  435. if (proxyForm != null)
  436. {
  437. proxyForm.Activate();
  438. }
  439. else
  440. {
  441. proxyForm = new ProxyForm(controller);
  442. proxyForm.Show();
  443. proxyForm.Activate();
  444. proxyForm.FormClosed += proxyForm_FormClosed;
  445. }
  446. }
  447. private void ShowHotKeySettingsForm()
  448. {
  449. if (hotkeySettingsForm != null)
  450. {
  451. hotkeySettingsForm.Activate();
  452. }
  453. else
  454. {
  455. hotkeySettingsForm = new HotkeySettingsForm(controller);
  456. hotkeySettingsForm.Show();
  457. hotkeySettingsForm.Activate();
  458. hotkeySettingsForm.FormClosed += hotkeySettingsForm_FormClosed;
  459. }
  460. }
  461. private void ShowLogForm()
  462. {
  463. if (logForm != null)
  464. {
  465. logForm.Activate();
  466. }
  467. else
  468. {
  469. logForm = new LogForm(controller, Logging.LogFilePath);
  470. logForm.Show();
  471. logForm.Activate();
  472. logForm.FormClosed += logForm_FormClosed;
  473. }
  474. }
  475. void logForm_FormClosed(object sender, FormClosedEventArgs e)
  476. {
  477. logForm.Dispose();
  478. logForm = null;
  479. Utils.ReleaseMemory(true);
  480. }
  481. void configForm_FormClosed(object sender, FormClosedEventArgs e)
  482. {
  483. configForm.Dispose();
  484. configForm = null;
  485. Utils.ReleaseMemory(true);
  486. if (_isFirstRun)
  487. {
  488. CheckUpdateForFirstRun();
  489. ShowFirstTimeBalloon();
  490. _isFirstRun = false;
  491. }
  492. }
  493. void proxyForm_FormClosed(object sender, FormClosedEventArgs e)
  494. {
  495. proxyForm.Dispose();
  496. proxyForm = null;
  497. Utils.ReleaseMemory(true);
  498. }
  499. void hotkeySettingsForm_FormClosed(object sender, FormClosedEventArgs e)
  500. {
  501. hotkeySettingsForm.Dispose();
  502. hotkeySettingsForm = null;
  503. Utils.ReleaseMemory(true);
  504. }
  505. private void Config_Click(object sender, EventArgs e)
  506. {
  507. ShowConfigForm();
  508. }
  509. private void Quit_Click(object sender, EventArgs e)
  510. {
  511. controller.Stop();
  512. _notifyIcon.Visible = false;
  513. Application.Exit();
  514. }
  515. private void CheckUpdateForFirstRun()
  516. {
  517. Configuration config = controller.GetConfigurationCopy();
  518. if (config.isDefault) return;
  519. _isStartupChecking = true;
  520. updateChecker.CheckUpdate(config, 3000);
  521. }
  522. private void ShowFirstTimeBalloon()
  523. {
  524. _notifyIcon.BalloonTipTitle = I18N.GetString("Shadowsocks is here");
  525. _notifyIcon.BalloonTipText = I18N.GetString("You can turn on/off Shadowsocks in the context menu");
  526. _notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
  527. _notifyIcon.ShowBalloonTip(0);
  528. }
  529. private void AboutItem_Click(object sender, EventArgs e)
  530. {
  531. Process.Start("https://github.com/shadowsocks/shadowsocks-windows");
  532. }
  533. private void notifyIcon1_Click(object sender, MouseEventArgs e)
  534. {
  535. UpdateTrayIconAndNotifyText();
  536. if (e.Button == MouseButtons.Middle)
  537. {
  538. ShowLogForm();
  539. }
  540. }
  541. private void notifyIcon1_DoubleClick(object sender, MouseEventArgs e)
  542. {
  543. if (e.Button == MouseButtons.Left)
  544. {
  545. ShowConfigForm();
  546. }
  547. }
  548. private void EnableItem_Click(object sender, EventArgs e)
  549. {
  550. controller.ToggleEnable(false);
  551. Configuration config = controller.GetConfigurationCopy();
  552. UpdateSystemProxyItemsEnabledStatus(config);
  553. }
  554. private void UpdateSystemProxyItemsEnabledStatus(Configuration config)
  555. {
  556. disableItem.Checked = !config.enabled;
  557. if (!config.enabled)
  558. {
  559. globalModeItem.Checked = false;
  560. PACModeItem.Checked = false;
  561. }
  562. else
  563. {
  564. globalModeItem.Checked = config.global;
  565. PACModeItem.Checked = !config.global;
  566. }
  567. }
  568. private void GlobalModeItem_Click(object sender, EventArgs e)
  569. {
  570. controller.ToggleEnable(true);
  571. controller.ToggleGlobal(true);
  572. Configuration config = controller.GetConfigurationCopy();
  573. UpdateSystemProxyItemsEnabledStatus(config);
  574. }
  575. private void PACModeItem_Click(object sender, EventArgs e)
  576. {
  577. controller.ToggleEnable(true);
  578. controller.ToggleGlobal(false);
  579. Configuration config = controller.GetConfigurationCopy();
  580. UpdateSystemProxyItemsEnabledStatus(config);
  581. }
  582. private void ShareOverLANItem_Click(object sender, EventArgs e)
  583. {
  584. ShareOverLANItem.Checked = !ShareOverLANItem.Checked;
  585. controller.ToggleShareOverLAN(ShareOverLANItem.Checked);
  586. }
  587. private void EditPACFileItem_Click(object sender, EventArgs e)
  588. {
  589. controller.TouchPACFile();
  590. }
  591. private void UpdatePACFromGFWListItem_Click(object sender, EventArgs e)
  592. {
  593. controller.UpdatePACFromGFWList();
  594. }
  595. private void EditUserRuleFileForGFWListItem_Click(object sender, EventArgs e)
  596. {
  597. controller.TouchUserRuleFile();
  598. }
  599. private void AServerItem_Click(object sender, EventArgs e)
  600. {
  601. MenuItem item = (MenuItem)sender;
  602. controller.SelectServerIndex((int)item.Tag);
  603. }
  604. private void AStrategyItem_Click(object sender, EventArgs e)
  605. {
  606. MenuItem item = (MenuItem)sender;
  607. controller.SelectStrategy((string)item.Tag);
  608. }
  609. private void VerboseLoggingToggleItem_Click(object sender, EventArgs e)
  610. {
  611. VerboseLoggingToggleItem.Checked = !VerboseLoggingToggleItem.Checked;
  612. controller.ToggleVerboseLogging(VerboseLoggingToggleItem.Checked);
  613. }
  614. private void StatisticsConfigItem_Click(object sender, EventArgs e)
  615. {
  616. StatisticsStrategyConfigurationForm form = new StatisticsStrategyConfigurationForm(controller);
  617. form.Show();
  618. }
  619. private void QRCodeItem_Click(object sender, EventArgs e)
  620. {
  621. QRCodeForm qrCodeForm = new QRCodeForm(controller.GetServerURLForCurrentServer());
  622. //qrCodeForm.Icon = this.Icon;
  623. // TODO
  624. qrCodeForm.Show();
  625. }
  626. private void ScanQRCodeItem_Click(object sender, EventArgs e)
  627. {
  628. foreach (Screen screen in Screen.AllScreens)
  629. {
  630. using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
  631. screen.Bounds.Height))
  632. {
  633. using (Graphics g = Graphics.FromImage(fullImage))
  634. {
  635. g.CopyFromScreen(screen.Bounds.X,
  636. screen.Bounds.Y,
  637. 0, 0,
  638. fullImage.Size,
  639. CopyPixelOperation.SourceCopy);
  640. }
  641. int maxTry = 10;
  642. for (int i = 0; i < maxTry; i++)
  643. {
  644. int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
  645. int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry);
  646. Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
  647. Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);
  648. double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
  649. using (Graphics g = Graphics.FromImage(target))
  650. {
  651. g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
  652. cropRect,
  653. GraphicsUnit.Pixel);
  654. }
  655. var source = new BitmapLuminanceSource(target);
  656. var bitmap = new BinaryBitmap(new HybridBinarizer(source));
  657. QRCodeReader reader = new QRCodeReader();
  658. var result = reader.decode(bitmap);
  659. if (result != null)
  660. {
  661. var success = controller.AddServerBySSURL(result.Text);
  662. QRCodeSplashForm splash = new QRCodeSplashForm();
  663. if (success)
  664. {
  665. splash.FormClosed += splash_FormClosed;
  666. }
  667. else if (result.Text.ToLower().StartsWith("http://") || result.Text.ToLower().StartsWith("https://"))
  668. {
  669. _urlToOpen = result.Text;
  670. splash.FormClosed += openURLFromQRCode;
  671. }
  672. else
  673. {
  674. MessageBox.Show(I18N.GetString("Failed to decode QRCode"));
  675. return;
  676. }
  677. double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0;
  678. foreach (ResultPoint point in result.ResultPoints)
  679. {
  680. minX = Math.Min(minX, point.X);
  681. minY = Math.Min(minY, point.Y);
  682. maxX = Math.Max(maxX, point.X);
  683. maxY = Math.Max(maxY, point.Y);
  684. }
  685. minX /= imageScale;
  686. minY /= imageScale;
  687. maxX /= imageScale;
  688. maxY /= imageScale;
  689. // make it 20% larger
  690. double margin = (maxX - minX) * 0.20f;
  691. minX += -margin + marginLeft;
  692. maxX += margin + marginLeft;
  693. minY += -margin + marginTop;
  694. maxY += margin + marginTop;
  695. splash.Location = new Point(screen.Bounds.X, screen.Bounds.Y);
  696. // we need a panel because a window has a minimal size
  697. // TODO: test on high DPI
  698. splash.TargetRect = new Rectangle((int)minX, (int)minY, (int)maxX - (int)minX, (int)maxY - (int)minY);
  699. splash.Size = new Size(fullImage.Width, fullImage.Height);
  700. splash.Show();
  701. return;
  702. }
  703. }
  704. }
  705. }
  706. MessageBox.Show(I18N.GetString("No QRCode found. Try to zoom in or move it to the center of the screen."));
  707. }
  708. private void ImportURLItem_Click(object sender, EventArgs e)
  709. {
  710. var success = controller.AddServerBySSURL(Clipboard.GetText(TextDataFormat.Text));
  711. if (success)
  712. {
  713. ShowConfigForm();
  714. }
  715. }
  716. void splash_FormClosed(object sender, FormClosedEventArgs e)
  717. {
  718. ShowConfigForm();
  719. }
  720. void openURLFromQRCode(object sender, FormClosedEventArgs e)
  721. {
  722. Process.Start(_urlToOpen);
  723. }
  724. private void AutoStartupItem_Click(object sender, EventArgs e)
  725. {
  726. AutoStartupItem.Checked = !AutoStartupItem.Checked;
  727. if (!AutoStartup.Set(AutoStartupItem.Checked))
  728. {
  729. MessageBox.Show(I18N.GetString("Failed to update registry"));
  730. }
  731. }
  732. private void LocalPACItem_Click(object sender, EventArgs e)
  733. {
  734. if (!localPACItem.Checked)
  735. {
  736. localPACItem.Checked = true;
  737. onlinePACItem.Checked = false;
  738. controller.UseOnlinePAC(false);
  739. UpdatePACItemsEnabledStatus();
  740. }
  741. }
  742. private void OnlinePACItem_Click(object sender, EventArgs e)
  743. {
  744. if (!onlinePACItem.Checked)
  745. {
  746. if (controller.GetConfigurationCopy().pacUrl.IsNullOrEmpty())
  747. {
  748. UpdateOnlinePACURLItem_Click(sender, e);
  749. }
  750. if (!controller.GetConfigurationCopy().pacUrl.IsNullOrEmpty())
  751. {
  752. localPACItem.Checked = false;
  753. onlinePACItem.Checked = true;
  754. controller.UseOnlinePAC(true);
  755. }
  756. UpdatePACItemsEnabledStatus();
  757. }
  758. }
  759. private void UpdateOnlinePACURLItem_Click(object sender, EventArgs e)
  760. {
  761. string origPacUrl = controller.GetConfigurationCopy().pacUrl;
  762. string pacUrl = Microsoft.VisualBasic.Interaction.InputBox(
  763. I18N.GetString("Please input PAC Url"),
  764. I18N.GetString("Edit Online PAC URL"),
  765. origPacUrl, -1, -1);
  766. if (!pacUrl.IsNullOrEmpty() && pacUrl != origPacUrl)
  767. {
  768. controller.SavePACUrl(pacUrl);
  769. }
  770. }
  771. private void SecureLocalPacUrlToggleItem_Click(object sender, EventArgs e)
  772. {
  773. Configuration configuration = controller.GetConfigurationCopy();
  774. controller.ToggleSecureLocalPac(!configuration.secureLocalPac);
  775. }
  776. private void CopyLocalPacUrlItem_Click(object sender, EventArgs e)
  777. {
  778. controller.CopyPacUrl();
  779. }
  780. private void UpdatePACItemsEnabledStatus()
  781. {
  782. if (this.localPACItem.Checked)
  783. {
  784. this.editLocalPACItem.Enabled = true;
  785. this.updateFromGFWListItem.Enabled = true;
  786. this.editGFWUserRuleItem.Enabled = true;
  787. this.editOnlinePACItem.Enabled = false;
  788. }
  789. else
  790. {
  791. this.editLocalPACItem.Enabled = false;
  792. this.updateFromGFWListItem.Enabled = false;
  793. this.editGFWUserRuleItem.Enabled = false;
  794. this.editOnlinePACItem.Enabled = true;
  795. }
  796. }
  797. private void UpdateUpdateMenu()
  798. {
  799. Configuration configuration = controller.GetConfigurationCopy();
  800. autoCheckUpdatesToggleItem.Checked = configuration.autoCheckUpdate;
  801. checkPreReleaseToggleItem.Checked = configuration.checkPreRelease;
  802. }
  803. private void autoCheckUpdatesToggleItem_Click(object sender, EventArgs e)
  804. {
  805. Configuration configuration = controller.GetConfigurationCopy();
  806. controller.ToggleCheckingUpdate(!configuration.autoCheckUpdate);
  807. UpdateUpdateMenu();
  808. }
  809. private void checkPreReleaseToggleItem_Click(object sender, EventArgs e)
  810. {
  811. Configuration configuration = controller.GetConfigurationCopy();
  812. controller.ToggleCheckingPreRelease(!configuration.checkPreRelease);
  813. UpdateUpdateMenu();
  814. }
  815. private void checkUpdatesItem_Click(object sender, EventArgs e)
  816. {
  817. updateChecker.CheckUpdate(controller.GetConfigurationCopy());
  818. }
  819. private void proxyItem_Click(object sender, EventArgs e)
  820. {
  821. ShowProxyForm();
  822. }
  823. private void hotKeyItem_Click(object sender, EventArgs e)
  824. {
  825. ShowHotKeySettingsForm();
  826. }
  827. private void ShowLogItem_Click(object sender, EventArgs e)
  828. {
  829. ShowLogForm();
  830. }
  831. public void ShowLogForm_HotKey()
  832. {
  833. ShowLogForm();
  834. }
  835. }
  836. }