Example #1
0
    /// <summary>
    /// Before Init Modules, coroutine
    /// </summary>
    /// <returns></returns>
    public override IEnumerator OnBeforeInit()
    {
        if (AppConfig.IsDownloadRes)
        {
            var loader = AssetBundleLoader.Load($"uiatlas/{UIModule.Instance.CommonAtlases[0]}", (isOk, ab) =>
            {
                if (isOk && ab)
                {
                    var atlas = ab.LoadAsset <SpriteAtlas>("atlas_common");
                    ABManager.SpriteAtlases["atlas_common"] = atlas;
                }
            });
            while (!loader.IsCompleted)
            {
                yield return(null);
            }
            yield return(StartCoroutine(DownloadManager.Instance.CheckDownload()));

            if (DownloadManager.Instance.ErrorType != UpdateErrorType.None)
            {
                UIMsgBoxInfo info = new UIMsgBoxInfo().GetDefalut(I18N.Get("download_error", DownloadManager.Instance.ErrorType), null, I18N.Get("common_ignore"), I18N.Get("common_exit"));
                info.OkCallback     = () => { DownloadManager.Instance.DownloadFinish = true; };
                info.CancelCallback = KTool.ExitGame;
                var panel = UIModule.Instance.GetOrCreateUI <KUIMsgBox>();
                panel.info = info;
                panel.DisPlay(true);
            }
        }
        else
        {
            DownloadManager.Instance.DownloadFinish = true;
        }
    }
Example #2
0
        static void Main()
        {
            // Check OS since we are using dual-mode socket
            if (!Utils.CheckFIPSAuthentication())
            {
                return;
            }
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, $"Global\\Shadowsocks_{Application.StartupPath.GetHashCode()}"))
            {
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                // handle UI exceptions
                Application.ThreadException += Application_ThreadException;
                // handle non-UI exceptions
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Rallets icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Rallets, make a copy in another directory."),
                                    I18N.GetString("Rallets is already running."));
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG
                Logging.OpenLogFile();

                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#else
                Logging.OpenLogFile();
#endif
                Test(); // TODO
                _controller     = ShadowsocksController.one();
                _viewController = MenuViewController.one();
                NotificationRunner.one().Start();
                HotKeys.Init();
                _controller.Start();
                // 程序退出前把代理设置清除
                Application.ApplicationExit += new EventHandler((s, e) => {
                    SystemProxy.Disable();
                });
                Application.Run();
            }
        }
        // Requires UI thread
        private void Initialize(IDictionary <string, ICollection <KeyBinding> > keyBindings)
        {
            ClearKeyBindings();

            foreach (var value in Enum.GetValues(typeof(Command)))
            {
                var command   = (Command)value;
                var viewModel = new KeyBindingsViewModel(command.ToString(), _dialogService, I18N.Translate($"{nameof(Command)}.{command}"), true);
                foreach (var keyBinding in keyBindings[command.ToString()])
                {
                    viewModel.Add(keyBinding);
                }
                viewModel.Edited += OnEdited;
                KeyBindings.Add(viewModel);
            }
        }
 void controller_UpdatePACFromGFWListError(object sender, System.IO.ErrorEventArgs e)
 {
     ShowBalloonTip(I18N.GetString("Failed to update PAC file"), e.GetException().Message, ToolTipIcon.Error, 5000);
     Logging.LogUsefulException(e.GetException());
 }
        private void ScanQRCodeItem_Click(object sender, EventArgs e)
        {
            foreach (Screen screen in Screen.AllScreens)
            {
                using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
                                                     screen.Bounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(fullImage))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         fullImage.Size,
                                         CopyPixelOperation.SourceCopy);
                    }
                    int maxTry = 10;
                    for (int i = 0; i < maxTry; i++)
                    {
                        int       marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
                        int       marginTop  = (int)((double)fullImage.Height * i / 2.5 / maxTry);
                        Rectangle cropRect   = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
                        Bitmap    target     = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);

                        double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
                        using (Graphics g = Graphics.FromImage(target))
                        {
                            g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
                                        cropRect,
                                        GraphicsUnit.Pixel);
                        }
                        var          source = new BitmapLuminanceSource(target);
                        var          bitmap = new BinaryBitmap(new HybridBinarizer(source));
                        QRCodeReader reader = new QRCodeReader();
                        var          result = reader.decode(bitmap);
                        if (result != null)
                        {
                            var success             = controller.AddServerBySSURL(result.Text);
                            QRCodeSplashForm splash = new QRCodeSplashForm();
                            if (success)
                            {
                                splash.FormClosed += splash_FormClosed;
                            }
                            else if (result.Text.StartsWith("http://") || result.Text.StartsWith("https://"))
                            {
                                _urlToOpen         = result.Text;
                                splash.FormClosed += openURLFromQRCode;
                            }
                            else
                            {
                                MessageBox.Show(I18N.GetString("Failed to decode QRCode"));
                                return;
                            }
                            double minX = Int32.MaxValue, minY = Int32.MaxValue, maxX = 0, maxY = 0;
                            foreach (ResultPoint point in result.ResultPoints)
                            {
                                minX = Math.Min(minX, point.X);
                                minY = Math.Min(minY, point.Y);
                                maxX = Math.Max(maxX, point.X);
                                maxY = Math.Max(maxY, point.Y);
                            }
                            minX /= imageScale;
                            minY /= imageScale;
                            maxX /= imageScale;
                            maxY /= imageScale;
                            // make it 20% larger
                            double margin = (maxX - minX) * 0.20f;
                            minX           += -margin + marginLeft;
                            maxX           += margin + marginLeft;
                            minY           += -margin + marginTop;
                            maxY           += margin + marginTop;
                            splash.Location = new Point(screen.Bounds.X, screen.Bounds.Y);
                            // we need a panel because a window has a minimal size
                            // TODO: test on high DPI
                            splash.TargetRect = new Rectangle((int)minX + screen.Bounds.X, (int)minY + screen.Bounds.Y, (int)maxX - (int)minX, (int)maxY - (int)minY);
                            splash.Size       = new Size(fullImage.Width, fullImage.Height);
                            splash.Show();
                            return;
                        }
                    }
                }
            }
            MessageBox.Show(I18N.GetString("No QRCode found. Try to zoom in or move it to the center of the screen."));
        }
 void controller_Errored(object sender, System.IO.ErrorEventArgs e)
 {
     MessageBox.Show(e.GetException().ToString(), String.Format(I18N.GetString("Shadowsocks Error: {0}"), e.GetException().Message));
 }
 private MenuItem CreateMenuItem(string text, EventHandler click)
 {
     return(new MenuItem(I18N.GetString(text), click));
 }
Example #8
0
 public MvxYamlTextProvider(RemoteContentConfig config)
 {
     I18N.Initialize(config);
 }
        public static string GetMessageId(this IPropertyValidator propVal, bool includePropName = false)
        {
            switch (propVal)
            {
            case EmailValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' is not a valid email address.")
                        : I18N.Register("Is not a valid email address."));

            case GreaterThanOrEqualValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be greater than or equal to '{ComparisonValue}'.")
                        : I18N.Register("Must be greater than or equal to '{ComparisonValue}'."));

            case GreaterThanValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be greater than '{ComparisonValue}'.")
                        : I18N.Register("Must be greater than '{ComparisonValue}'."));

            case MinimumLengthValidator _:
                return(includePropName
                        ? I18N.Register("The length of '{PropertyName}' must be at least {MinLength} characters. You entered {TotalLength} characters.")
                        : I18N.Register("The length must be at least {MinLength} characters. You entered {TotalLength} characters."));

            case MaximumLengthValidator _:
                return(includePropName
                        ? I18N.Register("The length of '{PropertyName}' must be {MaxLength} characters or fewer. You entered {TotalLength} characters.")
                        : I18N.Register("The length must be {MaxLength} characters or fewer. You entered {TotalLength} characters."));

            case ExactLengthValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be {MaxLength} characters in length. You entered {TotalLength} characters.")
                        : I18N.Register("Must be {MaxLength} characters in length. You entered {TotalLength} characters."));

            case LengthValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be between {MinLength} and {MaxLength} characters. You entered {TotalLength} characters.")
                        : I18N.Register("Must be between {MinLength} and {MaxLength} characters. You entered {TotalLength} characters."));

            case LessThanOrEqualValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be less than or equal to '{ComparisonValue}'.")
                        : I18N.Register("Must be less than or equal to '{ComparisonValue}'."));

            case LessThanValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be less than '{ComparisonValue}'.")
                        : I18N.Register("Must be less than '{ComparisonValue}'."));

            case NotNullValidator _:
            case NotEmptyValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must not be empty.")
                        : I18N.Register("Must not be empty."));

            case NotEqualValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must not be equal to '{ComparisonValue}'.")
                        : I18N.Register("Must not be equal to '{ComparisonValue}'."));

            case AsyncPredicateValidator _:
            case PredicateValidator _:
                return(includePropName
                        ? I18N.Register("The specified condition was not met for '{PropertyName}'.")
                        : I18N.Register("The specified condition was not met."));

            case RegularExpressionValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' is not in the correct format.")
                        : I18N.Register("Is not in the correct format."));

            case EqualValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be equal to '{ComparisonValue}'.")
                        : I18N.Register("Must be equal to '{ComparisonValue}'."));

            case InclusiveBetweenValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be between {From} and {To}. You entered {Value}.")
                        : I18N.Register("Must be between {From} and {To}. You entered {Value}."));

            case ExclusiveBetweenValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be between {From} and {To} (exclusive). You entered {Value}.")
                        : I18N.Register("Must be between {From} and {To} (exclusive). You entered {Value}."));

            case CreditCardValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' is not a valid credit card number.")
                        : I18N.Register("Is not a valid credit card number."));

            case ScalePrecisionValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must not be more than {ExpectedPrecision} digits in total, with allowance for {ExpectedScale} decimals. {Digits} digits and {ActualScale} decimals were found.")
                        : I18N.Register("Must not be more than {ExpectedPrecision} digits in total, with allowance for {ExpectedScale} decimals. {Digits} digits and {ActualScale} decimals were found."));

            case EmptyValidator _:
            case NullValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' must be empty.")
                        : I18N.Register("Must be empty."));

            case EnumValidator _:
                return(includePropName
                        ? I18N.Register("'{PropertyName}' has a range of values which does not include '{PropertyValue}'.")
                        : I18N.Register("'Has a range of values which does not include '{PropertyValue}'."));

            default:
                throw new NotSupportedException($"Validator of type '{propVal}' has not a predefined localized message. Pass the localized message as parameter");
            }
        }
Example #10
0
 void updateChecker_NewVersionFound(object sender, EventArgs e)
 {
     if (updateChecker.LatestVersionNumber == null || updateChecker.LatestVersionNumber.Length == 0)
     {
         Logging.Log(LogLevel.Error, "connect to update server error");
     }
     else
     {
         ShowBalloonTip(String.Format(I18N.GetString("{0} {1} Update Found"), UpdateChecker.Name, updateChecker.LatestVersionNumber), I18N.GetString("Click here to download"), ToolTipIcon.Info, 5000);
         _notifyIcon.BalloonTipClicked += notifyIcon1_BalloonTipClicked;
     }
     _isFirstRun = false;
 }
Example #11
0
 public MvxYamlTextProvider(AssemblyContentConfig config)
 {
     I18N.Initialize(config);
 }
Example #12
0
        void controller_UpdatePACFromGFWListCompleted(object sender, GFWListUpdater.ResultEventArgs e)
        {
            string result = e.Success ? I18N.GetString("PAC updated") : I18N.GetString("No updates found. Please report to GFWList if you have problems with it.");

            ShowBalloonTip(I18N.GetString("Shadowsocks"), result, ToolTipIcon.Info, 1000);
        }
Example #13
0
        private void UpdateTrayIcon()
        {
            int      dpi;
            Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);

            dpi = (int)graphics.DpiX;
            graphics.Dispose();
            Bitmap icon = null;

            if (dpi < 97)
            {
                // dpi = 96;
                icon = Resources.ss16;
            }
            else if (dpi < 121)
            {
                // dpi = 120;
                icon = Resources.ss20;
            }
            else
            {
                icon = Resources.ss24;
            }
            Configuration config  = controller.GetConfiguration();
            bool          enabled = config.enabled;
            bool          global  = config.global;

            if (!enabled)
            {
                Bitmap iconCopy = new Bitmap(icon);
                for (int x = 0; x < iconCopy.Width; x++)
                {
                    for (int y = 0; y < iconCopy.Height; y++)
                    {
                        Color color = icon.GetPixel(x, y);
                        iconCopy.SetPixel(x, y, Color.FromArgb((byte)(color.A / 1.25), color.R, color.G, color.B));
                    }
                }
                icon = iconCopy;
            }
            _notifyIcon.Icon = Icon.FromHandle(icon.GetHicon());

            // we want to show more details but notify icon title is limited to 63 characters
            string text = UpdateChecker.Name + " " + UpdateChecker.FullVersion + "\n" +
                          (enabled ?
                           I18N.GetString("System Proxy On: ") + (global ? I18N.GetString("Global") : I18N.GetString("PAC")) :
                           String.Format(I18N.GetString("Running: Port {0}"), config.localPort)) // this feedback is very important because they need to know Shadowsocks is running
                          + "\n" + config.GetCurrentServer().FriendlyName();

            _notifyIcon.Text = text.Substring(0, Math.Min(63, text.Length));
        }
Example #14
0
        private void UpdateTrayIconAndNotifyText()
        {
            Configuration config  = controller.GetConfigurationCopy();
            bool          enabled = config.enabled;
            bool          global  = config.global;

            Color colorMask = SelectColorMask(enabled, global);
            Size  iconSize  = SelectIconSize();

            UpdateIconSet(colorMask, iconSize, out icon, out icon_in, out icon_out, out icon_both);

            previousIcon     = icon;
            _notifyIcon.Icon = previousIcon;

            string serverInfo = null;

            if (controller.GetCurrentStrategy() != null)
            {
                serverInfo = controller.GetCurrentStrategy().Name;
            }
            else
            {
                serverInfo = config.GetCurrentServer().FriendlyName();
            }
            // show more info by hacking the P/Invoke declaration for NOTIFYICONDATA inside Windows Forms
            string text = I18N.GetString("Shadowsocks") + " " + UpdateChecker.Version + "\n" +
                          (enabled ?
                           I18N.GetString("System Proxy On: ") + (global ? I18N.GetString("Global") : I18N.GetString("PAC")) :
                           I18N.GetString("Running: Port {0}", config.localPort))     // this feedback is very important because they need to know Shadowsocks is running
                          + "\n" + serverInfo;

            if (text.Length > 127)
            {
                text = text.Substring(0, 126 - 3) + "...";
            }
            ViewUtils.SetNotifyIconText(_notifyIcon, text);
        }
Example #15
0
    public IEnumerator CheckDownload()
    {
        ClearData();
        var loadingPanel = UIModule.Instance.GetOrCreateUI <LoadingPanel>();

        loadingPanel.SetProgress(I18N.Get("download_check"));
        loadingPanel.DisPlay(true);
        string url = AppConfig.resUrl + AppConfig.VersionTxtName;

        Log.LogToFile($"读取远程version.txt:{url}");
        var loader = KWWWLoader.Load(url);

        while (!loader.IsCompleted)
        {
            yield return(null);
        }

        if (!loader.IsError)
        {
            ParseText(loader.Www.text, remoteVersion);
            remoteVersion.TryGetValue("filelist.txt", out filelistVersion);
        }
        else
        {
            ErrorType = UpdateErrorType.RemoteVersionError;
            yield break;
        }

        url = KResourceModule.GetResourceFullPath(AppConfig.VersionTxtName, false);
        Log.LogToFile($"读取本地version.txt:{url}");
        loader = KWWWLoader.Load(url);
        while (!loader.IsCompleted)
        {
            yield return(null);
        }

        if (!loader.IsError)
        {
            ParseText(loader.Www.text, localVersion);
        }
        else
        {
            ErrorType = UpdateErrorType.LocalVersionError;
            yield break;
        }

        loader.Dispose();
        loader = null;
        CompareVersion("lua.zip");
        CompareVersion("setting.zip");
        bool filelistSame = CompareVersion("filelist.txt", false);

        if (filelistSame == false)
        {
            //对比ab列表
            string remote_filelist = null;
            url    = AppConfig.resUrl + AppConfig.FilelistName;
            loader = KWWWLoader.Load(url);
            while (!loader.IsCompleted)
            {
                yield return(null);
            }

            if (!loader.IsError)
            {
                remote_filelist = loader.Www.text;
            }
            else
            {
                ErrorType = UpdateErrorType.FilelistnError;
            }
            url    = KResourceModule.GetResourceFullPath(AppConfig.FilelistName, false);
            loader = KWWWLoader.Load(url);
            while (!loader.IsCompleted)
            {
                yield return(null);
            }

            //开始对比两个filelist
            if (!loader.IsError)
            {
                GetDownloadFromFilelist(loader.Www.text, remote_filelist);
            }
            else
            {
                ErrorType = UpdateErrorType.LocalFilelistnError;
            }
        }

        if (downloadFiles.Count > 0)
        {
            var          panel = UIModule.Instance.GetOrCreateUI <KUIMsgBox>();
            UIMsgBoxInfo info  = new UIMsgBoxInfo().GetDefalut(I18N.Get("download_msg", KTool.FormatFileSize(downloadTotalSize)), strCancel: I18N.Get("common_skip"));
            info.OkCallback     = () => { Game.Instance.StartCoroutine(StartUpdate()); };
            info.CancelCallback = IngoreDownload;
            panel.info          = info;
            panel.DisPlay(true);
        }
        else
        {
            Log.LogToFile($"本次启动无资源更新,跳过下载");
            ClearData();
            DownloadFinish = true;
        }
    }
        private void UpdateTrayIcon()
        {
            int      dpi;
            Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);

            dpi = (int)graphics.DpiX;
            graphics.Dispose();
            Bitmap icon = null;

            if (dpi < 97)
            {
                // dpi = 96;
                icon = Resources.ss16;
            }
            else if (dpi < 121)
            {
                // dpi = 120;
                icon = Resources.ss20;
            }
            else
            {
                icon = Resources.ss24;
            }
            bool enabled = controller.GetConfiguration().enabled;

            if (!enabled)
            {
                Bitmap iconCopy = new Bitmap(icon);
                for (int x = 0; x < iconCopy.Width; x++)
                {
                    for (int y = 0; y < iconCopy.Height; y++)
                    {
                        Color color = icon.GetPixel(x, y);
                        iconCopy.SetPixel(x, y, Color.FromArgb((byte)(color.A / 1.25), color.R, color.G, color.B));
                    }
                }
                icon = iconCopy;
            }
            _notifyIcon.Icon = Icon.FromHandle(icon.GetHicon());

            string text = I18N.GetString("Shadowsocks") + " " + UpdateChecker.Version + "\n" + (enabled ? I18N.GetString("Enabled") : I18N.GetString("Disabled")) + "\n" + controller.GetCurrentServer().FriendlyName();

            _notifyIcon.Text = text.Substring(0, Math.Min(63, text.Length));
        }
Example #17
0
    IEnumerator StartUpdate()
    {
        //更新下载进度
        var loadingPanel = UIModule.Instance.GetOrCreateUI <LoadingPanel>();

        loadingPanel.DisPlay(true);

        var appDataPath = KResourceModule.AppDataPath;
        //TODO 是否所有资源都下载成功
        var total = downloadFiles.Count;

        for (int i = 0; i < total; i++)
        {
            yield return(Game.Instance.StartCoroutine(DownloadItem(downloadFiles[i], appDataPath)));
        }

        Log.LogToFile(total > 0 ? "下载更新资源完成" : "本次无需下载新资源");
        try
        {
            //更新filelist
            if (filelistBuilder.Length > 0)
            {
                var dirName = Path.GetDirectoryName(appDataPath + AppConfig.FilelistName);
                if (Directory.Exists(dirName) == false)
                {
                    Directory.CreateDirectory(dirName);
                }
                File.WriteAllText(appDataPath + AppConfig.FilelistName, filelistBuilder.ToString());
                Log.LogToFile("filelist更新完成");
            }
            else
            {
                Log.LogToFile("本次filelist无需更新");
            }

            //更新version
            if (versionBuilder.Length > 0)
            {
                if (filelistVersion == null)
                {
                    Log.LogError("更新version.txt中的filelist.txt version 失败,data is null");
                }
                if (filelistVersion != null)
                {
                    versionBuilder.AppendLine(filelistVersion.ToFilelistFormat());
                }
                var dirName = Path.GetDirectoryName(appDataPath + AppConfig.VersionTxtName);
                if (Directory.Exists(dirName) == false)
                {
                    Directory.CreateDirectory(dirName);
                }
                File.WriteAllText(appDataPath + AppConfig.VersionTxtName, versionBuilder.ToString());
                Log.LogToFile("version更新完成");
            }
            else
            {
                Log.LogToFile("本次version无需更新");
            }
        }
        catch (Exception e)
        {
            Log.LogError($"保存filelist出错,{e.Message}");
            ErrorType = UpdateErrorType.DownloadError;
        }

        //解压可以放在多线程中
        loadingPanel.SetProgress(I18N.Get("download_unpackzip"));
        bool waitLua = true, waitSetting = true;

        if (needUnpackLua)
        {
            KAsync.Start().Thread(() => UnpackZip(appDataPath + "/lua.zip", appDataPath + "/Lua/", () => waitLua = false));
        }
        else
        {
            waitLua = false;
        }

        if (needUnpackSetting)
        {
            KAsync.Start().Thread(() => UnpackZip(appDataPath + "/setting.zip", appDataPath + "/Setting/", () => waitSetting = false));
        }
        else
        {
            waitSetting = false;
        }

        loadingPanel = UIModule.Instance.GetExistUI <LoadingPanel>();
        loadingPanel?.SetFixProgress(1 - zipPercent, 1.0f);
        WaitForSeconds wait = new WaitForSeconds(0.05f);

        while (waitLua || waitSetting)
        {
            loadingPanel?.UpdateFixedProgress();
            yield return(wait);
        }

        DownloadFinish = true;
        if (needUnpackLua || needUnpackSetting)
        {
            Log.LogToFile("解压更新资源完成");
        }
        ClearData();
    }
Example #18
0
 internal void Reload(TableFileRow row)
 {
     Id    = row.Get_string(row.Values[0], "");
     Value = row.Get_I18N(row.Values[1], "");
 }
        private void UpdateTrayIcon()
        {
            int      dpi;
            Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);

            dpi = (int)graphics.DpiX;
            graphics.Dispose();
            icon_baseBitmap = null;
            if (dpi < 97)
            {
                // dpi = 96;
                icon_baseBitmap = Resources.ss16;
            }
            else if (dpi < 121)
            {
                // dpi = 120;
                icon_baseBitmap = Resources.ss20;
            }
            else
            {
                icon_baseBitmap = Resources.ss24;
            }
            Configuration config  = controller.GetConfigurationCopy();
            bool          enabled = config.enabled;
            bool          global  = config.global;

            icon_baseBitmap = getTrayIconByState(icon_baseBitmap, enabled, global);

            icon_base        = Icon.FromHandle(icon_baseBitmap.GetHicon());
            targetIcon       = icon_base;
            icon_in          = Icon.FromHandle(AddBitmapOverlay(icon_baseBitmap, Resources.ssIn24).GetHicon());
            icon_out         = Icon.FromHandle(AddBitmapOverlay(icon_baseBitmap, Resources.ssOut24).GetHicon());
            icon_both        = Icon.FromHandle(AddBitmapOverlay(icon_baseBitmap, Resources.ssIn24, Resources.ssOut24).GetHicon());
            _notifyIcon.Icon = targetIcon;

            string serverInfo = null;

            if (controller.GetCurrentStrategy() != null)
            {
                serverInfo = controller.GetCurrentStrategy().Name;
            }
            else
            {
                serverInfo = config.GetCurrentServer().FriendlyName();
            }
            // show more info by hacking the P/Invoke declaration for NOTIFYICONDATA inside Windows Forms
            string text = I18N.GetString("Shadowsocks") + " " + AssemblyInfo.FullVersion + "\n" +
                          (enabled ?
                           I18N.GetString("System Proxy On: ") + (global ? I18N.GetString("Global") : I18N.GetString("PAC")) :
                           String.Format(I18N.GetString("Running: Port {0}"), config.localPort))     // this feedback is very important because they need to know Shadowsocks is running
                          + "\n" + serverInfo;

            ViewUtils.SetNotifyIconText(_notifyIcon, text);
        }
        static void Main()
        {
            // Check OS since we are using dual-mode socket
            if (!Utils.IsWinVistaOrHigher())
            {
                MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check .NET Framework version
            if (!Utils.IsSupportedRuntimeVersion())
            {
                MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to 4.6.2 or later."),
                                "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Process.Start(
                    "http://dotnetsocial.cloudapp.net/GetDotnet?tfm=.NETFramework,Version=v4.6.2");
                return;
            }

            Utils.ReleaseMemory(true);
            using (Mutex mutex = new Mutex(false, $"Global\\Shadowsocks_{Application.StartupPath.GetHashCode()}"))
            {
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                // handle UI exceptions
                Application.ThreadException += Application_ThreadException;
                // handle non-UI exceptions
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Application.ApplicationExit   += Application_ApplicationExit;
                SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.")
                                    + Environment.NewLine
                                    + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                                    I18N.GetString("Shadowsocks is already running."));
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
#if DEBUG
                Logging.OpenLogFile();

                // truncate privoxy log file while debugging
                string privoxyLogFilename = Utils.GetTempPath("privoxy.log");
                if (File.Exists(privoxyLogFilename))
                {
                    using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { }
                }
#else
                Logging.OpenLogFile();
#endif
                MainController = new ShadowsocksController();
                MenuController = new MenuViewController(MainController);
                HotKeys.Init(MainController);
                MainController.Start();
                Application.Run();
            }
        }
 private MenuItem CreateMenuGroup(string text, MenuItem[] items)
 {
     return(new MenuItem(I18N.GetString(text), items));
 }
 private void UpdateTitle()
 {
     Title = $@"{I18N.GetString(@"ServerLog")}({(_controller.GetCurrentConfiguration().shareOverLan ? I18N.GetString(@"Any") : I18N.GetString(@"Local"))}:{_controller.GetCurrentConfiguration().localPort} {I18N.GetString(@"Version")}{UpdateChecker.FullVersion})";
 }
 void updateChecker_CheckUpdateCompleted(object sender, EventArgs e)
 {
     if (updateChecker.NewVersionFound)
     {
         ShowBalloonTip(String.Format(I18N.GetString("Shadowsocks {0} Update Found"), updateChecker.LatestVersionNumber + updateChecker.LatestVersionSuffix), I18N.GetString("Click here to update"), ToolTipIcon.Info, 5000);
     }
     else if (!_isStartupChecking)
     {
         ShowBalloonTip(I18N.GetString("Shadowsocks"), I18N.GetString("No update is available"), ToolTipIcon.Info, 5000);
     }
     _isStartupChecking = false;
 }
Example #24
0
 public override string ToString()
 {
     return(index + "[" + I18N.Get(content) + "]  action=" + action + "[" + actionParam + "," + actionParam2 + "]  ->" + next);
 }
Example #25
0
 internal void Reload(TableRow row)
 { 
     Id = row.Get_string(row.Values[0], ""); 
     Value = row.Get_I18N(row.Values[1], ""); 
 }
Example #26
0
        private void UpdateTexts()
        {
            Text = $@"{I18N.GetString("Edit Servers")}({(_controller.GetCurrentConfiguration().shareOverLan ? I18N.GetString("Any") : I18N.GetString("Local"))}:{_controller.GetCurrentConfiguration().localPort} {I18N.GetString("Version")}:{UpdateChecker.FullVersion})";

            btnAdd.Text    = I18N.GetString("&Add");
            btnDelete.Text = I18N.GetString("&Delete");
            btnUp.Text     = I18N.GetString("Up");
            btnDown.Text   = I18N.GetString("Down");

            const string mark_str = "*";

            chkIP.Text          = mark_str + I18N.GetString("Server IP");
            lblServerPort.Text  = mark_str + I18N.GetString("Server Port");
            lblUDPPort.Text     = I18N.GetString("UDP Port");
            chkPassword.Text    = mark_str + I18N.GetString("Password");
            lblEncryption.Text  = mark_str + I18N.GetString("Encryption");
            lblTCPProtocol.Text = mark_str + I18N.GetString(lblTCPProtocol.Text);
            lblObfs.Text        = mark_str + I18N.GetString(lblObfs.Text);
            lblRemarks.Text     = I18N.GetString("Remarks");
            lblGroup.Text       = I18N.GetString("Group");

            chkAdvSetting.Text    = I18N.GetString(chkAdvSetting.Text);
            lblTcpOverUdp.Text    = I18N.GetString(lblTcpOverUdp.Text);
            lblUdpOverTcp.Text    = I18N.GetString(lblUdpOverTcp.Text);
            lblProtocolParam.Text = I18N.GetString(lblProtocolParam.Text);
            lblObfsParam.Text     = I18N.GetString(lblObfsParam.Text);
            lblObfsUdp.Text       = I18N.GetString(lblObfsUdp.Text);
            LabelNote.Text        = I18N.GetString(LabelNote.Text);
            chkTcpOverUdp.Text    = I18N.GetString(chkTcpOverUdp.Text);
            chkUdpOverTcp.Text    = I18N.GetString(chkUdpOverTcp.Text);
            chkObfsUDP.Text       = I18N.GetString(chkObfsUDP.Text);
            chkSSRLink.Text       = I18N.GetString(chkSSRLink.Text);
            for (int i = 0; i < cmbTcpProtocol.Items.Count; ++i)
            {
                cmbTcpProtocol.Items[i] = I18N.GetString(cmbTcpProtocol.Items[i].ToString());
            }

            ServerGroupBox.Text = I18N.GetString("Server");

            btnOK.Text            = I18N.GetString("OK");
            btnCancel.Text        = I18N.GetString("Cancel");
            llbUpdate.MaximumSize = new Size(lstServers.Width, lstServers.Height);
            llbUpdate.Text        = string.Format(I18N.GetString("New version {0} {1} available"), UpdateChecker.Name, _updateChecker.LatestVersionNumber);
        }