Example #1
0
        public SettingsForm()
        {
            InitializeComponent();

            SuspendLayout();

            Language.SetControlLang(this);
            foreach (var label in groupColorsGroupBox.Controls.OfType <Label>())
            {
                if (string.IsNullOrEmpty(label.Text) || label.Text.EndsWith(":", StringComparison.Ordinal))
                {
                    continue;
                }
                label.Text += ':';
            }

            Icon = CacheData.GetSystemIcon(ImageResourceSymbol.SystemControl);

            transferPathBox.Text                = EnvironmentEx.GetVariableWithPath(Settings.TransferDir, false, false);
            transferPathBtn.BackgroundImage     = CacheData.GetSystemImage(ImageResourceSymbol.Directory);
            transferPathUndoBtn.BackgroundImage = CacheData.GetSystemImage(ImageResourceSymbol.Undo);
            if (Settings.TransferDir.EqualsEx(CorePaths.TransferDir))
            {
                transferPathUndoBtn.Enabled         = false;
                transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
            }

            ResumeLayout(false);
        }
Example #2
0
 private void TransferPathUndoBtn_Click(object sender, EventArgs e)
 {
     Settings.TransferDir = CorePaths.TransferDir;
     transferPathBox.Text = EnvironmentEx.GetVariableWithPath(Settings.TransferDir, false, false);
     if (transferPathUndoBtn.Enabled)
     {
         transferPathUndoBtn.Enabled         = false;
         transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
     }
     MessageBoxEx.Show(this, Language.GetText(nameof(en_US.OperationCompletedMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
 }
        internal static void UpdateStartMenuShortcuts(IEnumerable <string> longAppNames)
        {
            var appNames = longAppNames?.ToArray();

            if (appNames?.Any() != true)
            {
                return;
            }
            try
            {
                var startMenuDir = PathEx.Combine(Environment.SpecialFolder.StartMenu, "Programs");
                var shortcutPath = Path.Combine(startMenuDir, "Apps Launcher.lnk");
                if (Directory.Exists(startMenuDir))
                {
                    var shortcuts = Directory.GetFiles(startMenuDir, "Apps Launcher*.lnk", SearchOption.TopDirectoryOnly);
                    if (shortcuts.Length > 0)
                    {
                        foreach (var shortcut in shortcuts)
                        {
                            File.Delete(shortcut);
                        }
                    }
                }
                if (!Directory.Exists(startMenuDir))
                {
                    Directory.CreateDirectory(startMenuDir);
                }
                FileEx.CreateShellLink(EnvironmentEx.GetVariableWithPath(PathEx.LocalPath, false), shortcutPath);
                startMenuDir = Path.Combine(startMenuDir, "Portable Apps");
                if (Directory.Exists(startMenuDir))
                {
                    var shortcuts = Directory.GetFiles(startMenuDir, "*.lnk", SearchOption.TopDirectoryOnly);
                    if (shortcuts.Length > 0)
                    {
                        foreach (var shortcut in shortcuts)
                        {
                            File.Delete(shortcut);
                        }
                    }
                }
                if (!Directory.Exists(startMenuDir))
                {
                    Directory.CreateDirectory(startMenuDir);
                }
                Parallel.ForEach(appNames, x => FileEx.CreateShellLink(EnvironmentEx.GetVariableWithPath(CacheData.FindAppData(x)?.FilePath, false, false), Path.Combine(startMenuDir, x)));
            }
            catch (Exception ex) when(ex.IsCaught())
            {
                Log.Write(ex);
            }
        }
Example #4
0
 private void TransferPathBtn_Click(object sender, EventArgs e)
 {
     using (var dialog = new FolderBrowserDialog())
     {
         dialog.SelectedPath = Path.GetTempPath();
         if (dialog.ShowDialog() != DialogResult.OK)
         {
             MessageBoxEx.Show(this, Language.GetText(nameof(en_US.OperationCanceledMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             return;
         }
         var transferDir = dialog.SelectedPath;
         if (transferDir.EqualsEx(Settings.TransferDir))
         {
             MessageBoxEx.Show(this, Language.GetText(nameof(en_US.OperationFailedMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         var currentDrive  = PathEx.LocalPath.ToUpperInvariant().First();
         var transferDrive = transferDir.ToUpperInvariant().First();
         if (currentDrive.Equals(transferDrive))
         {
             MessageBoxEx.Show(this, Language.GetText(nameof(en_US.TransferDirMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         var currentDir = Settings.TransferDir;
         Settings.TransferDir = transferDir;
         var dirChanged = !Settings.TransferDir.EqualsEx(currentDir);
         if (dirChanged)
         {
             transferPathBox.Text = EnvironmentEx.GetVariableWithPath(Settings.TransferDir, false, false);
             if (!transferPathUndoBtn.Enabled)
             {
                 transferPathUndoBtn.Enabled         = true;
                 transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
             }
         }
         MessageBoxEx.Show(this, Language.GetText(dirChanged ? nameof(en_US.OperationCompletedMsg) : nameof(en_US.OperationFailedMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, dirChanged ? MessageBoxIcon.Asterisk : MessageBoxIcon.Warning);
     }
 }
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            var appData = CacheData.FindAppData(appsBox.SelectedItem.ToString());

            if (appData != default)
            {
                if (string.IsNullOrWhiteSpace(fileTypes.Text))
                {
                    appData.Settings.FileTypes = default;
                }
                else
                {
                    if (e == EventArgs.Empty || !FileTypesConflict())
                    {
                        var typesList = new List <string>();
                        foreach (var item in $"{fileTypes.Text},".Split(','))
                        {
                            if (string.IsNullOrWhiteSpace(item))
                            {
                                continue;
                            }
                            var type = new string(item.ToCharArray().Where(c => !Path.GetInvalidFileNameChars().Contains(c) && !char.IsWhiteSpace(c)).ToArray());
                            if (string.IsNullOrWhiteSpace(type) || type.Length < 1)
                            {
                                continue;
                            }
                            if (type.StartsWith(".", StringComparison.Ordinal))
                            {
                                while (type.Contains(".."))
                                {
                                    type = type.Replace("..", ".");
                                }
                                if (typesList.ContainsItem(type) || typesList.ContainsItem(type.Substring(1)))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (typesList.ContainsItem(type) || typesList.ContainsItem($".{type}"))
                                {
                                    continue;
                                }
                            }
                            if (type.Length == 1 && type.StartsWith(".", StringComparison.Ordinal))
                            {
                                continue;
                            }
                            typesList.Add(type);
                        }
                        if (typesList.Any())
                        {
                            var comparer = new AlphaNumericComparer <string>();
                            typesList                  = typesList.OrderBy(x => x, comparer).ToList();
                            fileTypes.Text             = typesList.Join(",");
                            appData.Settings.FileTypes = new Collection <string>(typesList);
                        }
                    }
                    else
                    {
                        fileTypes.Text = appData.Settings.FileTypes.Join(',');
                    }
                }

                appData.Settings.StartArgsFirst = startArgsFirst.Text;
                appData.Settings.StartArgsLast  = startArgsLast.Text;

                appData.Settings.SortArgPaths = sortArgPathsCheck.Checked;
                appData.Settings.NoConfirm    = noConfirmCheck.Checked;
                appData.Settings.RunAsAdmin   = runAsAdminCheck.Checked;
                appData.Settings.NoUpdates    = noUpdatesCheck.Checked;
            }

            if (defBgCheck.Checked)
            {
                if (CacheData.CurrentImageBg != default)
                {
                    CacheData.CurrentImageBg = default;
                    if (Result != DialogResult.Yes)
                    {
                        Result = DialogResult.Yes;
                    }
                }
                bgLayout.SelectedIndex = 1;
            }

            Settings.Window.FadeInEffect   = (Settings.Window.FadeInEffectOptions)fadeInCombo.SelectedIndex;
            Settings.Window.FadeInDuration = (int)fadeInNum.Value;
            Settings.Window.Opacity        = (double)opacityNum.Value;

            Settings.Window.BackgroundImageLayout = (ImageLayout)bgLayout.SelectedIndex;

            Settings.Window.Colors.Base        = mainColorPanel.BackColor;
            Settings.Window.Colors.Control     = controlColorPanel.BackColor;
            Settings.Window.Colors.ControlText = controlTextColorPanel.BackColor;
            Settings.Window.Colors.Button      = btnColorPanel.BackColor;
            Settings.Window.Colors.ButtonHover = btnHoverColorPanel.BackColor;
            Settings.Window.Colors.ButtonText  = btnTextColorPanel.BackColor;

            Settings.Window.HideHScrollBar = hScrollBarCheck.Checked;
            Settings.Window.LargeImages    = showLargeImagesCheck.Checked;

            var dirList = new List <string>();

            if (!string.IsNullOrWhiteSpace(appDirs.Text))
            {
                var tmpDir = appDirs.Text + Environment.NewLine;
                foreach (var item in tmpDir.SplitNewLine())
                {
                    if (string.IsNullOrWhiteSpace(item))
                    {
                        continue;
                    }
                    var dir = PathEx.Combine(item);
                    try
                    {
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        dir = EnvironmentEx.GetVariableWithPath(dir);
                        if (!dirList.ContainsItem(dir))
                        {
                            dirList.Add(dir);
                        }
                    }
                    catch (Exception ex) when(ex.IsCaught())
                    {
                        Log.Write(ex);
                    }
                }
                if (dirList.Count > 0)
                {
                    dirList.Sort();
                    appDirs.Text = dirList.Join(Environment.NewLine);
                }
            }
            Settings.AppDirs = dirList.ToArray();

            Settings.StartMenuIntegration = startMenuIntegration.SelectedIndex > 0;
            if (!Settings.StartMenuIntegration)
            {
                try
                {
                    var shortcutDirs = new[]
                    {
                        Environment.GetFolderPath(Environment.SpecialFolder.SendTo),
                        PathEx.Combine(Environment.SpecialFolder.StartMenu, "Programs")
                    };
                    foreach (var dir in shortcutDirs)
                    {
                        var shortcuts = Directory.GetFiles(dir, "Apps Launcher*.lnk", SearchOption.TopDirectoryOnly);
                        foreach (var shortcut in shortcuts.Where(File.Exists))
                        {
                            File.Delete(shortcut);
                        }
                    }
                    var startMenuDir = Path.Combine(shortcutDirs.Last(), "Portable Apps");
                    if (Directory.Exists(startMenuDir))
                    {
                        Directory.Delete(startMenuDir, true);
                    }
                }
                catch (Exception ex) when(ex.IsCaught())
                {
                    Log.Write(ex);
                }
            }

            Settings.Window.DefaultPosition = defaultPos.SelectedIndex;

            Settings.UpdateCheck   = (Settings.UpdateCheckOptions)updateCheck.SelectedIndex;
            Settings.UpdateChannel = (Settings.UpdateChannelOptions)updateChannel.SelectedIndex;

            var lang = setLang.SelectedItem.ToString();

            if (!Settings.Language.EqualsEx(lang))
            {
                if (Result != DialogResult.Yes)
                {
                    Result = DialogResult.Yes;
                }
                Settings.Language = lang;
                LoadSettings();
            }

            Settings.WriteToFile();

            MessageBoxEx.Show(this, Language.GetText(nameof(en_US.SavedSettings)), MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
        private void LoadSettings()
        {
            if (!setLang.Items.Contains(Settings.Language))
            {
                Settings.Language = "en-US";
            }
            setLang.SelectedItem = Settings.Language;
            Language.UserLang    = Settings.Language;

            Language.SetControlLang(this);

            var title = Language.GetText(nameof(en_US.settingsBtn));

            if (!string.IsNullOrWhiteSpace(title))
            {
                Text = title;
            }

            for (var i = 0; i < fileTypesMenu.Items.Count; i++)
            {
                fileTypesMenu.Items[i].Text = Language.GetText(fileTypesMenu.Items[i].Name);
            }

            var decValue = (decimal)Settings.Window.Opacity;

            opacityNum.Value = decValue >= opacityNum.Minimum && decValue <= opacityNum.Maximum ? decValue : .95m;

            var intValue = (int)Settings.Window.FadeInEffect;

            fadeInCombo.SelectedIndex = intValue < fadeInCombo.Items.Count ? intValue : 0;

            intValue        = Settings.Window.FadeInDuration;
            fadeInNum.Value = intValue >= fadeInNum.Minimum && intValue <= fadeInNum.Maximum ? intValue : 100;

            defBgCheck.Checked = !File.Exists(CachePaths.CurrentImageBg);
            if (bgLayout.Items.Count > 0)
            {
                bgLayout.Items.Clear();
            }
            for (var i = 0; i < 5; i++)
            {
                bgLayout.Items.Add(Language.GetText($"{bgLayout.Name}Option{i}"));
            }

            intValue = (int)Settings.Window.BackgroundImageLayout;
            bgLayout.SelectedIndex = intValue > 0 && intValue < bgLayout.Items.Count ? intValue : 1;

            mainColorPanel.BackColor        = Settings.Window.Colors.Base;
            controlColorPanel.BackColor     = Settings.Window.Colors.Control;
            controlTextColorPanel.BackColor = Settings.Window.Colors.ControlText;
            btnColorPanel.BackColor         = Settings.Window.Colors.Button;
            btnHoverColorPanel.BackColor    = Settings.Window.Colors.ButtonHover;
            btnTextColorPanel.BackColor     = Settings.Window.Colors.ButtonText;

            hScrollBarCheck.Checked      = Settings.Window.HideHScrollBar;
            showLargeImagesCheck.Checked = Settings.Window.LargeImages;

            StylePreviewUpdate();

            appDirs.Text = Settings.AppDirs?.Where(x => !CorePaths.AppDirs.ContainsItem(x)).Select(x => EnvironmentEx.GetVariableWithPath(x)).Join(Environment.NewLine);

            if (startMenuIntegration.Items.Count > 0)
            {
                startMenuIntegration.Items.Clear();
            }
            for (var i = 0; i < 2; i++)
            {
                startMenuIntegration.Items.Add(Language.GetText($"{startMenuIntegration.Name}Option{i}"));
            }
            startMenuIntegration.SelectedIndex = Settings.StartMenuIntegration ? 1 : 0;

            if (defaultPos.Items.Count > 0)
            {
                defaultPos.Items.Clear();
            }
            for (var i = 0; i < 2; i++)
            {
                defaultPos.Items.Add(Language.GetText($"{defaultPos.Name}Option{i}"));
            }

            intValue = Settings.Window.DefaultPosition;
            defaultPos.SelectedIndex = intValue > 0 && intValue < defaultPos.Items.Count ? intValue : 0;
            if (updateCheck.Items.Count > 0)
            {
                updateCheck.Items.Clear();
            }
            for (var i = 0; i < 10; i++)
            {
                updateCheck.Items.Add(Language.GetText($"{updateCheck.Name}Option{i}"));
            }

            intValue = (int)Settings.UpdateCheck;
            updateCheck.SelectedIndex = intValue > 0 && intValue < updateCheck.Items.Count ? intValue : 0;
            if (updateChannel.Items.Count > 0)
            {
                updateChannel.Items.Clear();
            }
            for (var i = 0; i < 2; i++)
            {
                updateChannel.Items.Add(Language.GetText($"{updateChannel.Name}Option{i}"));
            }

            intValue = (int)Settings.UpdateChannel;
            updateChannel.SelectedIndex = intValue > 0 ? 1 : 0;

            if (!saveBtn.Focused)
            {
                saveBtn.Select();
            }
        }
        internal static void Enable(bool enabled, bool quiet = false)
        {
            if (!Elevation.IsAdministrator)
            {
                using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.SystemIntegration} {enabled} {quiet}", true, false))
                    if (process?.HasExited == false)
                    {
                        process.WaitForExit();
                    }
                return;
            }
            var varKey = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
            var varDir = Reg.ReadString(Registry.LocalMachine, varKey, Settings.EnvironmentVariable);
            var curDir = PathEx.LocalDir;

            if (!enabled || !varDir.EqualsEx(curDir))
            {
                var curPath    = EnvironmentEx.GetVariableWithPath(PathEx.LocalPath, false);
                var sendToPath = PathEx.Combine(Environment.SpecialFolder.SendTo, "Apps Launcher.lnk");
                if (enabled)
                {
                    Reg.Write(Registry.LocalMachine, varKey, Settings.EnvironmentVariable, curDir);
                    FileEx.CreateShellLink(curPath, sendToPath);
                }
                else
                {
                    Reg.RemoveEntry(Registry.LocalMachine, varKey, Settings.EnvironmentVariable);
                    PathEx.ForceDelete(sendToPath);
                }
                if (WinApi.NativeHelper.SendNotifyMessage((IntPtr)0xffff, (uint)WinApi.WindowMenuFlags.WmSettingChange, (UIntPtr)0, "Environment"))
                {
                    foreach (var baseKey in new[]
                    {
                        "*",
                        "Folder"
                    })
                    {
                        varKey = Path.Combine(baseKey, "shell\\portableapps");
                        if (enabled)
                        {
                            if (string.IsNullOrWhiteSpace(Reg.ReadString(Registry.ClassesRoot, varKey, null)))
                            {
                                Reg.Write(Registry.ClassesRoot, varKey, null, Language.GetText(nameof(en_US.shellText)));
                            }
                            Reg.Write(Registry.ClassesRoot, varKey, "Icon", $"\"{PathEx.LocalPath}\"");
                        }
                        else
                        {
                            Reg.RemoveSubKey(Registry.ClassesRoot, varKey);
                        }
                        varKey = Path.Combine(varKey, "command");
                        if (enabled)
                        {
                            Reg.Write(Registry.ClassesRoot, varKey, null, $"\"{PathEx.LocalPath}\" \"%1\"");
                        }
                        else
                        {
                            Reg.RemoveSubKey(Registry.ClassesRoot, varKey);
                        }
                    }
                    var desktopPath = PathEx.Combine(Environment.SpecialFolder.Desktop, "Apps Launcher.lnk");
                    if (enabled)
                    {
                        FileEx.CreateShellLink(curPath, desktopPath);
                    }
                    else
                    {
                        PathEx.ForceDelete(sendToPath);
                    }

                    if (enabled)
                    {
                        using (var process = ProcessEx.Start(PathEx.LocalPath, ActionGuid.FileTypeAssociationAll, true, false))
                            if (process?.HasExited == false)
                            {
                                process.WaitForExit();
                            }
                    }

                    if (!quiet)
                    {
                        MessageBox.Show(Language.GetText(nameof(en_US.OperationCompletedMsg)), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    return;
                }
            }
            if (!quiet)
            {
                MessageBox.Show(Language.GetText(nameof(en_US.OperationCanceledMsg)), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        internal static void Associate(LocalAppData appData, bool quiet = false, Form owner = default)
        {
            if (appData?.Settings?.FileTypes?.Any() != true)
            {
                if (!quiet)
                {
                    MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.associateBtnMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                return;
            }

            if (!Elevation.IsAdministrator)
            {
                if (owner != default)
                {
                    owner.TopMost = false;
                    owner.Enabled = false;
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressState.Indeterminate);
                }
                _bw?.Dispose();
                _bw         = new BackgroundWorker();
                _bw.DoWork += (sender, args) =>
                {
                    using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.FileTypeAssociation} \"{appData.Key}\"", true, false))
                        if (!process?.HasExited == true)
                        {
                            process.WaitForExit();
                        }
                };
                _bw.RunWorkerCompleted += (sender, args) =>
                {
                    if (owner == default)
                    {
                        return;
                    }
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressState.NoProgress);
                    if (WinApi.NativeHelper.GetForegroundWindow() != owner.Handle)
                    {
                        WinApi.NativeHelper.SetForegroundWindow(owner.Handle);
                    }
                    owner.Enabled = true;
                    owner.TopMost = true;
                };
                _bw.RunWorkerAsync();
                return;
            }

            var assocData = new FileTypeAssocData
            {
                AppKey    = appData.Key,
                InstallId = Settings.SystemInstallId
            };

            using (var dialog = new IconBrowserDialog(Settings.IconResourcePath, Settings.Window.Colors.BaseDark, Settings.Window.Colors.ControlText, Settings.Window.Colors.Button, Settings.Window.Colors.ButtonText, Settings.Window.Colors.ButtonHover))
            {
                dialog.TopMost = true;
                dialog.Plus();
                dialog.ShowDialog();
                if (!string.IsNullOrEmpty(dialog.IconPath))
                {
                    assocData.IconPath = dialog.IconPath;
                    assocData.IconId   = dialog.IconId.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (!FileEx.Exists(assocData.IconPath) || string.IsNullOrEmpty(assocData.IconId))
            {
                goto Cancel;
            }

            MessageBoxEx.ButtonTextOverrideEnabled = true;
            MessageBoxEx.ButtonText = new MessageBoxButtonText
            {
                Yes    = "App",
                No     = "Launcher",
                Cancel = Language.GetText(nameof(en_US.Cancel))
            };

            var result = !quiet?MessageBoxEx.Show(Language.GetText(nameof(en_US.AssociateAppWayQuestion)), Resources.GlobalTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) : DialogResult.Yes;

            switch (result)
            {
            case DialogResult.Yes:
                assocData.StarterPath = EnvironmentEx.GetVariableWithPath(appData.FilePath, false, false);
                break;

            case DialogResult.No:
                assocData.StarterPath = EnvironmentEx.GetVariableWithPath(PathEx.LocalPath, false, false);
                break;

            default:
                goto Cancel;
            }

            if (FileEx.Exists(assocData.StarterPath))
            {
                appData.Settings.FileTypeAssoc = assocData;
            }
            else
            {
                goto Cancel;
            }

            assocData = appData.Settings?.FileTypeAssoc;
            assocData?.SystemRegistryAccess?.AssociateFileTypes(false);
            return;

Cancel:
            if (!quiet)
            {
                MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.OperationCanceledMsg)), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }