Esempio n. 1
0
        private void IconGenerator_DoWork(object sender, DoWorkEventArgs e)
        {
            var results = new Dictionary <string, string>();

            e.Result = results;

            var targetDir = SharedRoutines.GetIconDirectoryPath();

            EnsureDirectoryCreate(targetDir, false);

            foreach (var eachKey in ImageList.Images.Keys)
            {
                var targetPath = Path.Combine(targetDir, eachKey + ".ico");
                var fileInfo   = new FileInfo(targetPath);

                if (fileInfo.Exists && fileInfo.Length > 0L)
                {
                    continue;
                }

                var creationResult = ImagingHelper.ConvertToIcon(ImageList.Images[eachKey], fileInfo.FullName);

                if (!creationResult)
                {
                    results.Add(eachKey, targetPath);
                }
            }
        }
Esempio n. 2
0
        private void ShortcutGenerator_DoWork(object sender, DoWorkEventArgs e)
        {
            var targetDir = SharedRoutines.GetWslShortcutDirectoryPath();

            EnsureDirectoryCreate(targetDir, false);

            var arg = e.Argument as BackgroundWorkerArgument <DistroProperties[]>;

            if (arg?.Argument == null)
            {
                return;
            }

            // Shorcut file may not have icon due to missing icon cache
            var result = new Dictionary <string, string>();

            e.Result = new BackgroundWorkerResult <Dictionary <string, string> >(arg.HasTriggeredByUser, result);

            foreach (var eachItem in arg.Argument)
            {
                var targetFilePath = Path.Combine(targetDir, eachItem.DistroName + ".lnk");
                var creationResult = CreateDistroShortcut(eachItem, targetFilePath);

                if (!creationResult)
                {
                    result.Add(eachItem.DistroName, targetFilePath);
                }
            }
        }
Esempio n. 3
0
        private void DistroListView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            var targetDir = SharedRoutines.GetWslShortcutDirectoryPath();

            EnsureDirectoryCreate(targetDir, false);

            var filesToDrag = new List <string>();

            foreach (var eachItem in DistroListView.SelectedItems)
            {
                var eachDistro = (DistroProperties)eachItem;
                var targetPath = Path.Combine(targetDir, eachDistro.DistroName + ".lnk");

                if (!File.Exists(targetDir))
                {
                    CreateDistroShortcut(eachDistro, targetPath);
                }

                if (File.Exists(targetPath))
                {
                    filesToDrag.Add(targetPath);
                }
            }

            if (filesToDrag.Count > 0)
            {
                this.DistroListView.DoDragDrop(
                    new DataObject(DataFormats.FileDrop, filesToDrag.ToArray()),
                    DragDropEffects.Copy);
            }
        }
Esempio n. 4
0
        private void LaunchHyper(IEnumerable <ListViewItem> distroItems)
        {
            string hyperConfigFile     = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Hyper", ".hyper.js");
            string tempHyperConfigFile = hyperConfigFile + ".tmp";

            if (File.Exists(hyperConfigFile))
            {
                if (distroItems == null || distroItems.Count() < 1)
                {
                    return;
                }

                foreach (DistroProperties eachItem in distroItems.Select(x => x.Tag as DistroProperties))
                {
                    string distroExecutable = Path.Combine(
                        SharedRoutines.GetWslShimDirectoryPath(),
                        eachItem.DistroName + "_simple.exe")
                                              .Replace("\\", "\\\\");

                    StreamReader input  = new StreamReader(hyperConfigFile);
                    StreamWriter output = new StreamWriter(tempHyperConfigFile);
                    string       line;
                    while (null != (line = input.ReadLine()))
                    {
                        if (line.StartsWith("    shell: "))
                        {
                            output.WriteLine("    shell: '" + distroExecutable + "',");
                        }
                        else
                        {
                            output.WriteLine(line);
                        }
                    }
                    input.Close();
                    output.Close();
                    File.Delete(hyperConfigFile);
                    File.Move(tempHyperConfigFile, hyperConfigFile);

                    ProcessStartInfo startInfo;

                    startInfo = new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "hyper", "Hyper.exe"));

                    var proc = Process.Start(startInfo);
                }
            }

            if (!File.Exists(hyperConfigFile))
            {
                MessageBox.Show(this, "Hyper installation not found!\n" +
                                "Hyper can be installed from: https://hyper.is",
                                "Error: Hyper not Installed",
                                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
Esempio n. 5
0
        private void DataSourceRefresher_DoWork(object sender, DoWorkEventArgs e)
        {
            var wslMappings = new Dictionary <string, string>();

            using (var searcher = new ManagementObjectSearcher(
                       @"root\CIMV2",
                       @"SELECT * FROM Win32_MappedLogicalDisk"))
            {
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    var path  = Convert.ToString(queryObj["ProviderName"]);
                    var isWsl = path.StartsWith(@"\\wsl$\");
                    if (!isWsl)
                    {
                        continue;
                    }

                    var distroName  = Path.GetFileName(path);
                    var driveLetter = Convert.ToString(queryObj["Name"]);
                    wslMappings.Add(driveLetter, distroName);
                }
            }

            foreach (var eachLetter in Enumerable.Range('A', 'Z' - 'A' + 1).Select(x => $"{(char)x}:").ToArray())
            {
                var driveInfo = new DriveInfo(eachLetter);

                if (driveInfo.DriveType == DriveType.NoRootDirectory)
                {
                    wslMappings.Add(eachLetter, string.Empty);
                    continue;
                }
            }

            wslMappings = wslMappings.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

            var items = SharedRoutines.LoadDistroList().ToArray();

            e.Result = new MappedDriveQueryResultModel()
            {
                AvailableDrives = new WslMappedDriveInfoCollection(wslMappings.Select(x => new WslMappedDriveInfo()
                {
                    DriveName = x.Key, DistroName = x.Value
                })),
                WslDistroList = items.Select(x => x.DistroName).ToArray(),
            };
        }
Esempio n. 6
0
        private void DistroPropertiesForm_Load(object sender, EventArgs e)
        {
            var model = Model;

            if (model == null)
            {
                return;
            }

            DistroNameText.Text  = model.DistroName;
            DistroIcon.Image     = ImageList.Images[SharedRoutines.GetImageKey(model.DistroName)];
            DistroLocation.Text  = model.BasePath;
            State.Text           = model.DistroName;
            IsDefaultDistro.Text = model.IsDefaultDistro ? "Yes" : "No";
            WSLVersion.Text      = model.WslVersion.ToString();

            var dictionary = new Dictionary <string, object>();

            dictionary.Add("Append NT Path", (model.AppendNtPath ? "Yes" : "No"));
            dictionary.Add("Enable Drive Mounting", (model.EnableDriveMounting ? "Yes" : "No"));
            dictionary.Add("Enable Interop", (model.EnableInterop ? "Yes" : "No"));
            dictionary.Add("Kernel Command Line", model.KernelCommandLine);
            dictionary.Add("Default Environment Variables", model.DefaultEnvironment);
            dictionary.Add("Default User ID", model.DefaultUid.ToString());
            dictionary.Add("Distro Unique ID", model.DistroId);

            DistroPropertyGrid.SelectedObject = new DictionaryPropertyGridAdapter(dictionary);

            var ext4VhdxPath = Path.Combine(
                Path.GetFullPath(model.BasePath),
                "ext4.vhdx");

            if (model.WslVersion < 2 || !File.Exists(ext4VhdxPath))
            {
                DistroSizeCalculator.RunWorkerAsync(DistroLocation.Text);
            }
            else
            {
                DistroSize.Text = $"{(new FileInfo(ext4VhdxPath).Length / 1024 / 1024)} MiB";
            }

            Text = $"{model.DistroName} Properties";
        }
Esempio n. 7
0
        private void ShutdownDistro()
        {
            if (!SharedRoutines.IsWsl2SupportedOS())
            {
                return;
            }

            ProcessStartInfo startInfo;

            startInfo = new ProcessStartInfo(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "wsl.exe"),
                $@"--shutdown")
            {
                UseShellExecute = false,
            };

            var proc = Process.Start(startInfo);

            proc.WaitForExit();
        }
Esempio n. 8
0
        private void ShimGenerator_DoWork(object sender, DoWorkEventArgs e)
        {
            var targetDir = SharedRoutines.GetWslShimDirectoryPath();

            EnsureDirectoryCreate(targetDir, false);

            var arg = e.Argument as BackgroundWorkerArgument <DistroProperties[]>;

            if (arg?.Argument == null)
            {
                return;
            }

            // Shim exe file may not have icon due to missing icon cache
            var result = new Dictionary <string, CompilerResults>();

            e.Result = new BackgroundWorkerResult <Dictionary <string, CompilerResults> >(arg.HasTriggeredByUser, result);

            foreach (var eachItem in arg.Argument)
            {
                var fileName   = eachItem.DistroName;
                var eachResult = WslShimGenerator.CreateWslShim(
                    eachItem.DistroName, false, targetDir, fileName);

                if (eachResult.Errors.HasErrors)
                {
                    result.Add(fileName, eachResult);
                }

                fileName   = eachItem.DistroName + "_simple";
                eachResult = WslShimGenerator.CreateWslShim(
                    eachItem.DistroName, true, targetDir, fileName);

                if (eachResult.Errors.HasErrors)
                {
                    result.Add(fileName, eachResult);
                }
            }
        }
Esempio n. 9
0
        private bool CreateDistroShortcut(DistroProperties selectedDistro, string targetFilePath)
        {
            var shortcut = (IWshShortcut)wscriptShellType.InvokeMember(
                "CreateShortcut",
                BindingFlags.InvokeMethod,
                null, shellObject,
                new object[] { targetFilePath });

            shortcut.Description = selectedDistro.DistroName;
            shortcut.TargetPath  = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.System),
                "wsl.exe");
            shortcut.WorkingDirectory = Environment.GetFolderPath(
                Environment.SpecialFolder.UserProfile);
            shortcut.Arguments    = $@"-d {selectedDistro.DistroName}";
            shortcut.IconLocation = Path.Combine(
                SharedRoutines.GetIconDirectoryPath(),
                SharedRoutines.GetImageKey(selectedDistro.DistroName) + ".ico");
            shortcut.Save();

            return(File.Exists(targetFilePath));
        }
Esempio n. 10
0
        private void PerformRefreshDistroList(bool triggeredByUser)
        {
            var items = SharedRoutines.LoadDistroList().ToArray();

            DistroListView.Items.Clear();
            foreach (var eachItem in items)
            {
                var lvItem = new ListViewItem(
                    eachItem.Properties.Select(x => x.Value).ToArray(),
                    eachItem.ImageKey)
                {
                    Tag = eachItem,
                };

                DistroListView.Items.Add(lvItem);
            }
            TotalCountLabel.Text = $"{items.Length} item{(items.Length > 1 ? "s" : "")}";

            if (DistroListView.Items.Count < 1)
            {
                DistroListView.Visible = false;
                emptyLabel.Visible     = true;
            }
            else
            {
                DistroListView.Visible = true;
                emptyLabel.Visible     = false;
            }

            if (!ShimGenerator.IsBusy)
            {
                ShimGenerator.RunWorkerAsync(new BackgroundWorkerArgument <DistroProperties[]>(triggeredByUser, items));
            }

            if (!ShortcutGenerator.IsBusy)
            {
                ShortcutGenerator.RunWorkerAsync(new BackgroundWorkerArgument <DistroProperties[]>(triggeredByUser, items));
            }
        }
Esempio n. 11
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            if (Environment.OSVersion.Version < new Version(10, 0, 18362))
            {
                MessageBox.Show(this, "This program only works on Windows 10 19H1 or later. Please upgrade to the latest OS version.",
                                Text, MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                Close();
                return;
            }

            DistroListView.Columns.Clear();
            foreach (var eachProperty in typeof(DistroProperties).GetProperties())
            {
                var browsableAttr = eachProperty.GetCustomAttribute <BrowsableAttribute>();
                if (browsableAttr != null && !browsableAttr.Browsable)
                {
                    continue;
                }

                var colItem = new ColumnHeader();

                var displayNameAttr = eachProperty.GetCustomAttribute <DisplayNameAttribute>();
                if (displayNameAttr != null)
                {
                    colItem.Text = displayNameAttr.DisplayName;
                }
                else
                {
                    colItem.Text = eachProperty.Name;
                }

                DistroListView.Columns.Add(colItem);
            }

            if (!SharedRoutines.IsWsl2SupportedOS())
            {
                shutdownAllDistrosToolStripMenuItem.Visible = false;
            }

            if (!File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "wsl.exe")))
            {
                MessageBox.Show(this, "This program is only available when Windows Subsystem for Linux is enabled. Check the system settings.",
                                Text, MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
                Close();
                return;
            }

            this.emptyLabel = new Label()
            {
                Parent      = this,
                Text        = "No WSL distro installed.",
                TextAlign   = ContentAlignment.MiddleCenter,
                Font        = new Font(this.Font.FontFamily, 18f, FontStyle.Bold),
                Dock        = DockStyle.Fill,
                UseMnemonic = false,
                Visible     = false,
            };

            refreshToolStripMenuItem.PerformClick();

            if (!IconGenerator.IsBusy)
            {
                IconGenerator.RunWorkerAsync();
            }
        }