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

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