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 41 kB

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