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

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