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