public static void TerminateTree(this Process process) { if (EnvUtils.RunningOnWindows()) { // Send Ctrl+C NativeMethods.AttachConsole(process.Id); NativeMethods.SetConsoleCtrlHandler(IntPtr.Zero, add: true); NativeMethods.GenerateConsoleCtrlEvent(0, 0); if (!process.HasExited) { process.WaitForExit(500); } } if (!process.HasExited) { process.Kill(); } }
public static void TerminateTree(this Process process) { #if !__MonoCS__ if (EnvUtils.RunningOnWindows()) { // Send Ctrl+C NativeMethods.AttachConsole(process.Id); NativeMethods.SetConsoleCtrlHandler(IntPtr.Zero, true); NativeMethods.GenerateConsoleCtrlEvent(0, 0); if (!process.HasExited) { System.Threading.Thread.Sleep(500); } } #endif if (!process.HasExited) { process.Kill(); } }
public void OnProjectLoaded(Microsoft.Build.Evaluation.Project project, ProjectModel projectModel) { if (projectModel.IsBSIPAProject) { BsipaProjectInSolution = true; } Microsoft.Build.Evaluation.Project userProj = null; try { userProj = EnvUtils.GetProject(project.FullPath + ".user"); if (userProj == null) { return; } } catch (InvalidOperationException) { return; } var installPath = BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath; var projBeatSaberDir = project.GetPropertyValue("BeatSaberDir"); var userBeatSaberDir = userProj.GetPropertyValue("BeatSaberDir"); if (BSMTSettingsManager.Instance.CurrentSettings.GenerateUserFileOnExisting && !string.IsNullOrEmpty(BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath) && projectModel.IsBSIPAProject) { Utilities.EnvUtils.SetReferencePaths(userProj, projectModel, project, null); if (!string.IsNullOrEmpty(userBeatSaberDir) && userBeatSaberDir != BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath) { var prop = userProj.GetProperty("BeatSaberDir"); string message = $"Overriding BeatSaberDir in {projectModel.ProjectName} to \n{prop?.EvaluatedValue}\n(Old path: {userBeatSaberDir})"; VsShellUtilities.ShowMessageBox( this.package, message, $"{projectModel.ProjectName}: Auto Set BeatSaberDir", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } } }
internal static int GetTextWidthAtCharIndex(TextBoxBase textBoxBase, int index, int length) { // TODO! if (!(textBoxBase is RichTextBox richTextBox) || !EnvUtils.RunningOnWindows()) { return(textBoxBase.Font.Height); } NativeMethods.CHARRANGE charRange; charRange.cpMin = index; charRange.cpMax = index + length; NativeMethods.RECT rect; rect.Top = 0; rect.Bottom = (int)AnInch; rect.Left = 0; rect.Right = (int)(richTextBox.ClientSize.Width * AnInch); NativeMethods.RECT rectPage; rectPage.Top = 0; rectPage.Bottom = (int)AnInch; rectPage.Left = 0; rectPage.Right = (int)(richTextBox.ClientSize.Width * AnInch); var canvas = Graphics.FromHwnd(richTextBox.Handle); var canvasHdc = canvas.GetHdc(); var formatRange = GetFormatRange(charRange, canvasHdc, rect, rectPage); NativeMethods.SendMessage( richTextBox.Handle, NativeMethods.EM_FORMATRANGE, IntPtr.Zero, ref formatRange); canvas.ReleaseHdc(canvasHdc); canvas.Dispose(); return((int)((formatRange.rc.Right - formatRange.rc.Left) / AnInch)); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); string title = "Error setting BeatSaberDir:"; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; string message; if (string.IsNullOrEmpty(BSMTSettingsManager.Instance.CurrentSettings.ChosenInstallPath)) { icon = OLEMSGICON.OLEMSGICON_CRITICAL; message = "You don't appear to have a Beat Saber install path chosen in 'Extensions > Beat Saber Modding Tools > Settings'."; } else if (TryGetSelectedProject(package, out ProjectModel projectModel, out Project project, out EnvDTE.Project dteProject)) { if (projectModel.IsBSIPAProject) { if (projectModel.SupportedCapabilities.HasFlag(ProjectCapabilities.BeatSaberDir)) { try { var userProj = EnvUtils.GetProject(projectModel.ProjectPath + ".user"); message = SetBeatSaberDir(userProj, projectModel, project, dteProject); icon = OLEMSGICON.OLEMSGICON_INFO; title = "Set BeatSaberDir:"; } catch (Exception ex) { message = ex.Message; } } else { message = $"Project {projectModel.ProjectName} doesn't support the BeatSaberDir property"; } } else { message = $"Project {projectModel.ProjectName} does not appear to be a BSIPA project."; } }
private bool CheckGitExtensionRegistrySettings() { if (!EnvUtils.RunningOnWindows()) { return(true); } ShellExtensionsRegistered.Visible = true; if (string.IsNullOrEmpty(CommonLogic.GetRegistryValue(Registry.LocalMachine, "Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved", "{3C16B20A-BA16-4156-916F-0A375ECFFE24}")) || string.IsNullOrEmpty(CommonLogic.GetRegistryValue(Registry.ClassesRoot, "*\\shellex\\ContextMenuHandlers\\GitExtensions2", null)) || string.IsNullOrEmpty(CommonLogic.GetRegistryValue(Registry.ClassesRoot, "Directory\\shellex\\ContextMenuHandlers\\GitExtensions2", null)) || string.IsNullOrEmpty(CommonLogic.GetRegistryValue(Registry.ClassesRoot, "Directory\\Background\\shellex\\ContextMenuHandlers\\GitExtensions2", null))) { //Check if shell extensions are installed string path32 = Path.Combine(AppSettings.GetInstallDir(), CommonLogic.GitExtensionsShellEx32Name); string path64 = Path.Combine(AppSettings.GetInstallDir(), CommonLogic.GitExtensionsShellEx64Name); if (!File.Exists(path32) || (IntPtr.Size == 8 && !File.Exists(path64))) { ShellExtensionsRegistered.BackColor = Color.LightGreen; ShellExtensionsRegistered.Text = String.Format(_shellExtNoInstalled.Text); ShellExtensionsRegistered_Fix.Visible = false; return(true); } ShellExtensionsRegistered.BackColor = Color.LightSalmon; ShellExtensionsRegistered.Text = String.Format(_shellExtNeedsToBeRegistered.Text, CommonLogic.GitExtensionsShellEx32Name); ShellExtensionsRegistered_Fix.Visible = true; return(false); } ShellExtensionsRegistered.BackColor = Color.LightGreen; ShellExtensionsRegistered.Text = _shellExtRegistered.Text; ShellExtensionsRegistered_Fix.Visible = false; return(true); }
private bool TryMergeWithScript(string fileName, string baseFileName, string remoteFileName, string localFileName) { if (!EnvUtils.RunningOnWindows()) { return(false); } try { string extension = Path.GetExtension(fileName).ToLower(); if (extension.Length <= 1) { return(false); } string dir = Path.GetDirectoryName(Application.ExecutablePath) + AppSettings.PathSeparator + "Diff-Scripts" + AppSettings.PathSeparator; if (Directory.Exists(dir)) { string mergeScript = ""; if (_mergeScripts.TryGetValue(extension, out mergeScript) && File.Exists(Path.Combine(dir, mergeScript))) { if (MessageBox.Show(this, string.Format(uskUseCustomMergeScript.Text, mergeScript), uskUseCustomMergeScriptCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { UseMergeWithScript(fileName, Path.Combine(dir, mergeScript), baseFileName, remoteFileName, localFileName); return(true); } } } } catch (Exception ex) { MessageBox.Show(this, "Merge using script failed.\n" + ex); } return(false); }
private bool Save() { try { foreach (var settingsPage in SettingsPages) { settingsPage.SaveSettings(); } _commonLogic.ConfigFileSettingsSet.EffectiveSettings.Save(); _commonLogic.RepoDistSettingsSet.EffectiveSettings.Save(); if (EnvUtils.RunningOnWindows()) { FormFixHome.CheckHomePath(); } // TODO: this method has a generic sounding name but only saves some specific settings AppSettings.SaveSettings(); return(true); } catch (SaveSettingsException ex) when(ex.InnerException is not null) { using var dialog = new TaskDialog { OwnerWindowHandle = Handle, Text = ex.InnerException.Message, InstructionText = _cantSaveSettings.Text, Caption = Strings.Error, StandardButtons = TaskDialogStandardButtons.Ok, Icon = TaskDialogStandardIcon.Error, Cancelable = true, }; dialog.Show(); return(false); } }
public bool TryGetProject(string projectFilePath, out ProjectModel projectModel, out Microsoft.Build.Evaluation.Project project) { projectModel = null; project = EnvUtils.GetProject(projectFilePath); bool retVal = false; if (Projects.TryGetValue(projectFilePath, out projectModel)) { retVal = true; } else if (project != null) { projectModel = CreateProjectModel(project); Projects.TryAdd(projectFilePath, projectModel); if (projectModel.IsBSIPAProject) { BsipaProjectInSolution = true; } retVal = true; } return(retVal); }
public bool AutoSolveAllSettings() { if (!EnvUtils.RunningOnWindows()) { return(SolveGitCommand()); } bool valid = true; valid = SolveGitCommand() && valid; valid = SolveLinuxToolsDir() && valid; valid = SolveMergeToolForKDiff() && valid; valid = SolveDiffToolForKDiff() && valid; valid = SolveGitExtensionsDir() && valid; valid = SolveEditor() && valid; valid = SolveGitCredentialStore() && valid; CommonLogic.ConfigFileSettingsSet.EffectiveSettings.Save(); CommonLogic.RepoDistSettingsSet.EffectiveSettings.Save(); return(valid); }
private void buttonGenerate_Click(object sender, EventArgs e) { textBoxResult.Text = string.Empty; if (string.IsNullOrWhiteSpace(textBoxRevFrom.Text)) { MessageBox.Show(this, _fromCommitNotSpecified.Text, _caption.Text); textBoxRevFrom.Focus(); return; } if (string.IsNullOrWhiteSpace(textBoxRevTo.Text)) { MessageBox.Show(this, _toCommitNotSpecified.Text, _caption.Text); textBoxRevTo.Focus(); return; } string logArgs = string.Format(_NO_TRANSLATE_textBoxGitLogArguments.Text, textBoxRevFrom.Text, textBoxRevTo.Text); string result = _gitUiCommands.GitModule.RunGitCmd("log " + logArgs); if (EnvUtils.RunningOnWindows()) { result = string.Join(Environment.NewLine, result.Split(new[] { Environment.NewLine }, StringSplitOptions.None).SelectMany(l => l.Split('\n'))); } textBoxResult.Text = result; try { _lastGeneratedLogLines = _gitLogLineParser.Parse(textBoxResult.Lines); labelRevCount.Text = _lastGeneratedLogLines.Count().ToString(); } catch { labelRevCount.Text = "n/a"; } textBoxResult_TextChanged(null, null); }
private void DiffToolCmdSuggest_Click(object sender, EventArgs e) { if (!EnvUtils.RunningOnWindows()) { return; } CurrentSettings.SetPathValue(string.Format("difftool.{0}.path", GlobalMergeTool.Text.Trim()), MergetoolPath.Text.Trim()); string exeName; string exeFile; if (!String.IsNullOrEmpty(DifftoolPath.Text)) { exeFile = DifftoolPath.Text; exeName = Path.GetFileName(exeFile); } else { exeFile = MergeToolsHelper.FindDiffToolFullPath(ConfigFileSettingsSet, GlobalDiffTool.Text, out exeName); } if (String.IsNullOrEmpty(exeFile)) { DifftoolPath.SelectAll(); DifftoolPath.SelectedText = ""; DifftoolCmd.SelectAll(); DifftoolCmd.SelectedText = ""; if (sender != null) { MessageBox.Show(this, String.Format(CheckSettingsLogic.ToolSuggestPathText.Text, exeName), __diffToolSuggestCaption.Text); } return; } DifftoolPath.SelectAll(); // allow Undo action DifftoolPath.SelectedText = exeFile; DifftoolCmd.SelectAll(); DifftoolCmd.SelectedText = MergeToolsHelper.DiffToolCmdSuggest(GlobalDiffTool.Text, exeFile); }
private void MergeToolCmdSuggest_Click(object sender, EventArgs e) { if (!EnvUtils.RunningOnWindows()) { return; } _gitModule.SetGlobalPathSetting(string.Format("mergetool.{0}.path", GlobalMergeTool.Text.Trim()), MergetoolPath.Text.Trim()); string exeName; string exeFile; if (!String.IsNullOrEmpty(MergetoolPath.Text)) { exeFile = MergetoolPath.Text; exeName = Path.GetFileName(exeFile); } else { exeFile = MergeToolsHelper.FindMergeToolFullPath(GlobalMergeTool.Text, out exeName); } if (String.IsNullOrEmpty(exeFile)) { MergetoolPath.SelectAll(); MergetoolPath.SelectedText = ""; MergeToolCmd.SelectAll(); MergeToolCmd.SelectedText = ""; if (sender != null) { MessageBox.Show(this, String.Format(_checkSettingsLogic.ToolSuggestPathText.Text, exeName), _checkSettingsLogic.MergeToolSuggestCaption.Text); } return; } MergetoolPath.SelectAll(); // allow Undo action MergetoolPath.SelectedText = exeFile; MergeToolCmd.SelectAll(); MergeToolCmd.SelectedText = MergeToolsHelper.MergeToolcmdSuggest(GlobalMergeTool.Text, exeFile); }
public CommitInfo() { InitializeComponent(); Translate(); GitUICommandsSourceSet += (a, uiCommandsSource) => { _sortedRefs = null; }; _commitDataManager = new CommitDataManager(() => Module); IHeaderRenderStyleProvider headerRenderer; IHeaderLabelFormatter labelFormatter; if (EnvUtils.IsMonoRuntime()) { labelFormatter = new MonospacedHeaderLabelFormatter(); headerRenderer = new MonospacedHeaderRenderStyleProvider(); } else { labelFormatter = new TabbedHeaderLabelFormatter(); headerRenderer = new TabbedHeaderRenderStyleProvider(); } _commitDataHeaderRenderer = new CommitDataHeaderRenderer(labelFormatter, _dateFormatter, headerRenderer, _linkFactory); _commitDataBodyRenderer = new CommitDataBodyRenderer(() => Module, _linkFactory); RevisionInfo.Font = AppSettings.Font; using (Graphics g = CreateGraphics()) { _RevisionHeader.Font = _commitDataHeaderRenderer.GetFont(g); } _RevisionHeader.SelectionTabs = _commitDataHeaderRenderer.GetTabStops().ToArray(); Hotkeys = HotkeySettingsManager.LoadHotkeys(FormBrowse.HotkeySettingsName); addNoteToolStripMenuItem.ShortcutKeyDisplayString = GetShortcutKeys((int)FormBrowse.Commands.AddNotes).ToShortcutKeyDisplayString(); }
private bool CheckMergeTool() { MergeTool.Visible = true; if (string.IsNullOrEmpty(CommonLogic.GetGlobalMergeTool())) { RenderSettingUnset(MergeTool, MergeTool_Fix, _configureMergeTool.Text); return(false); } if (EnvUtils.RunningOnWindows()) { if (CommonLogic.IsMergeTool("kdiff3")) { string p = GetGlobalSetting("mergetool.kdiff3.path"); if (string.IsNullOrEmpty(p) || !File.Exists(p)) { RenderSettingUnset(MergeTool, MergeTool_Fix, _kdiffAsMergeConfiguredButNotFound.Text); return(false); } RenderSettingSet(MergeTool, MergeTool_Fix, _kdiffAsMergeConfigured.Text); return(true); } string mergetool = CommonLogic.GetGlobalMergeTool().ToLowerInvariant(); if (mergetool == "p4merge" || mergetool == "tmerge" || mergetool == "meld") { string p = GetGlobalSetting(string.Format("mergetool.{0}.cmd", mergetool)); if (string.IsNullOrEmpty(p)) { RenderSettingUnset(MergeTool, MergeTool_Fix, string.Format(_mergeToolXConfiguredNeedsCmd.Text, mergetool)); return(false); } RenderSettingSet(MergeTool, MergeTool_Fix, string.Format(_customMergeToolXConfigured.Text, mergetool)); return(true); } } RenderSettingSet(MergeTool, MergeTool_Fix, _mergeToolXConfigured.Text); return(true); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private async void Execute(object sender, EventArgs e) { await Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); string message = null; string title = "Error setting Reference Paths:"; bool skipped = false; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; if (TryGetSelectedProject(package, out ProjectModel projectModel, out var project, out EnvDTE.Project dteProject)) { try { //OK = 1, Cancel = 2, Abort = 3, Retry = 4, Ignore = 5, Yes = 6, No = 7 depending on what button is pressed. int forceReference = 6; if (projectModel.SupportedCapabilities.HasFlag(ProjectCapabilities.BeatSaberDir)) { forceReference = VsShellUtilities.ShowMessageBox( this.package, "It looks like this project supports 'BeatSaberDir', are you sure you want to use ReferencePath?", "", OLEMSGICON.OLEMSGICON_QUERY, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND); } if (forceReference == 6 || forceReference == 1) { var userProj = EnvUtils.GetProject(projectModel.ProjectPath + ".user"); message = SetReferencePaths(userProj, projectModel, project, dteProject); icon = OLEMSGICON.OLEMSGICON_INFO; title = "Set Reference Paths:"; } else { skipped = true; } } catch (Exception ex) { message = ex.Message; } }
private void MergeToolCmdSuggest_Click(object sender, EventArgs e) { if (!EnvUtils.RunningOnWindows()) { return; } CurrentSettings.SetPathValue(string.Format("mergetool.{0}.path", _NO_TRANSLATE_GlobalMergeTool.Text.Trim()), MergetoolPath.Text.Trim()); string exeName; string exeFile; if (!String.IsNullOrEmpty(MergetoolPath.Text)) { exeFile = MergetoolPath.Text; exeName = Path.GetFileName(exeFile); } else { exeFile = MergeToolsHelper.FindMergeToolFullPath(ConfigFileSettingsSet, _NO_TRANSLATE_GlobalMergeTool.Text, out exeName); } if (String.IsNullOrEmpty(exeFile)) { MergetoolPath.SelectAll(); MergetoolPath.SelectedText = ""; MergeToolCmd.SelectAll(); MergeToolCmd.SelectedText = ""; if (sender != null) { MessageBox.Show(this, String.Format(_toolSuggestPathText.Text, exeName), _mergeToolSuggestCaption.Text); } return; } MergetoolPath.SelectAll(); // allow Undo action MergetoolPath.SelectedText = exeFile; MergeToolCmd.SelectAll(); MergeToolCmd.SelectedText = MergeToolsHelper.MergeToolcmdSuggest(_NO_TRANSLATE_GlobalMergeTool.Text, exeFile); }
private void ApplyLayout() { var heightRowCommit = 0f; var heightRowTag = 0f; if (EnvUtils.IsMonoRuntime()) { if (txtTagGpgInfo.Visible) { heightRowCommit = heightRowTag = (float)tableLayoutPanel1.Height / 2; } else { heightRowCommit = tableLayoutPanel1.Height; } tableLayoutPanel1.RowStyles[0].SizeType = SizeType.Absolute; tableLayoutPanel1.RowStyles[1].SizeType = SizeType.Absolute; } else { if (txtTagGpgInfo.Visible) { heightRowCommit = 50f; heightRowTag = 50f; } else { heightRowCommit = 100f; } tableLayoutPanel1.RowStyles[0].SizeType = SizeType.Percent; tableLayoutPanel1.RowStyles[1].SizeType = SizeType.Percent; } tableLayoutPanel1.RowStyles[0].Height = heightRowCommit; tableLayoutPanel1.RowStyles[1].Height = heightRowTag; }
private bool CheckGitExtensionsInstall() { if (!EnvUtils.RunningOnWindows()) { return(true); } GitExtensionsInstall.Visible = true; if (string.IsNullOrEmpty(AppSettings.GetInstallDir())) { RenderSettingUnset(GitExtensionsInstall, GitExtensionsInstall_Fix, _registryKeyGitExtensionsMissing.Text); return(false); } if (AppSettings.GetInstallDir() != null && AppSettings.GetInstallDir().EndsWith(".exe")) { RenderSettingUnset(GitExtensionsInstall, GitExtensionsInstall_Fix, _registryKeyGitExtensionsFaulty.Text); return(false); } RenderSettingSet(GitExtensionsInstall, GitExtensionsInstall_Fix, _registryKeyGitExtensionsCorrect.Text); return(true); }
private void SuggestGitCred_Click(object sender, EventArgs e) { string gcsFileName = Path.Combine(AppSettings.GetInstallDir(), @"GitCredentialWinStore\git-credential-winstore.exe"); if (!File.Exists(gcsFileName)) { GitCredPath.Text = ""; return; } if (EnvUtils.RunningOnWindows()) { GitCredPath.Text = "!\"" + gcsFileName + "\""; } else if (EnvUtils.RunningOnMacOSX()) { GitCredPath.Text = "osxkeychain"; } else { GitCredPath.Text = "cache --timeout=300"; // 5 min } }
public static string GetDefaultHomeDir() { // Use the HOME property from the user or machine, as captured at startup if (!string.IsNullOrEmpty(UserHomeDir)) { return(UserHomeDir); } if (EnvUtils.RunningOnWindows()) { // Use the Windows default home directory var homeDrive = Env.GetEnvironmentVariable("HOMEDRIVE"); if (!string.IsNullOrEmpty(homeDrive)) { return(homeDrive + Env.GetEnvironmentVariable("HOMEPATH")); } return(Env.GetEnvironmentVariable("USERPROFILE")); } return(Env.GetFolderPath(Environment.SpecialFolder.Personal)); }
private async void SolutionEvents_OnAfterOpenProject(object sender, Microsoft.VisualStudio.Shell.Events.OpenProjectEventArgs e) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); ProjectModel projModel = null; e.Hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out object projectObj); if (projectObj is EnvDTE.Project project) { var newProject = EnvUtils.GetProject(project.FullName); if (newProject == null) { return; // This event seems to randomly trigger if the project is closed and the csproj file is opened in the editor. } { projModel = CreateProjectModel(newProject); if (Projects.TryAdd(newProject.FullPath, projModel)) { OnProjectLoaded(newProject, projModel); } } } else { var newProjects = ProjectCollection.GlobalProjectCollection.LoadedProjects.Where(p => !Projects.ContainsKey(p.FullPath) && !p.FullPath.EndsWith(".user")).ToList(); foreach (var item in newProjects) { var projectModel = CreateProjectModel(item); if (Projects.TryAdd(item.FullPath, projectModel)) { OnProjectLoaded(item, projectModel); } } } }
private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (EnvUtils.RunningOnWindows()) { NBug.Settings.UIMode = NBug.Enums.UIMode.Full; // Uncomment the following after testing to see that NBug is working as configured NBug.Settings.ReleaseMode = true; NBug.Settings.ExitApplicationImmediately = false; NBug.Settings.WriteLogToDisk = true; NBug.Settings.MaxQueuedReports = 10; NBug.Settings.StopReportingAfter = 90; NBug.Settings.SleepBeforeSend = 30; NBug.Settings.StoragePath = "WindowsTemp"; AppDomain.CurrentDomain.UnhandledException += NBug.Handler.UnhandledException; Application.ThreadException += NBug.Handler.ThreadException; } // required for translation GitUI.PluginLoader.Load(); string[] args = Environment.GetCommandLineArgs(); if (args.Length == 1) { Application.Run(new FormTranslate()); } else if (args.Length == 2 && args[1] == "update") { UpdateAllTranslations(); } else if (args.Length == 2 && args[1] == "status") { ShowStatus(); } }
static AppSettings() { ApplicationDataPath = new Lazy <string>(() => { if (IsPortable()) { return(GetGitExtensionsDirectory()); } else { //Make applicationdatapath version independent return(Application.UserAppDataPath.Replace(Application.ProductVersion, string.Empty)); } } ); SettingsContainer = new SettingsContainer <RepoDistSettings>(null, GitExtSettingsCache.FromCache(SettingsFilePath)); Version version = AppVersion; GitExtensionsVersionString = version.Major.ToString() + '.' + version.Minor.ToString(); if (version.Build > 0) { GitExtensionsVersionString += '.' + version.Build.ToString(); } if (!EnvUtils.RunningOnWindows()) { PathSeparator = '/'; PathSeparatorWrong = '\\'; } GitLog = new CommandLogger(); if (!File.Exists(SettingsFilePath)) { ImportFromRegistry(); } }
private static string GetVsDiffMergePath() { if (!EnvUtils.RunningOnWindows()) { return(ExeName); } // For 2017 (15.0) and later, VsDiffMerge is not installed by default but often included // C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer var vsVersions = new[] { "14.0", "12.0", "11.0" }; foreach (var version in vsVersions) { string registryKeyString = $@"SOFTWARE{(Environment.Is64BitProcess ? @"\Wow6432Node\" : "\\")}Microsoft\VisualStudio\{version}"; using RegistryKey? localMachineKey = Registry.LocalMachine.OpenSubKey(registryKeyString); var path = localMachineKey?.GetValue("InstallDir") as string; if (!Strings.IsNullOrEmpty(path)) { return(Path.Combine(path, ExeName)); } } return(ExeName); }
private async void SolutionEvents_OnAfterLoadProject(object sender, Microsoft.VisualStudio.Shell.Events.LoadProjectEventArgs e) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); ProjectModel projModel = null; e.RealHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out object projectObj); if (projectObj is EnvDTE.Project project) { var interfaces = project.GetType().GetInterfaces(); var newProject = EnvUtils.GetProject(project.FullName); if (newProject != null) { projModel = CreateProjectModel(newProject); if (Projects.TryAdd(newProject.FullPath, projModel)) { OnProjectLoaded(newProject, projModel); } } } else { var newProjects = ProjectCollection.GlobalProjectCollection.LoadedProjects.Where(p => !Projects.ContainsKey(p.FullPath) && !p.FullPath.EndsWith(".user")).ToList(); foreach (var item in newProjects) { var projectModel = CreateProjectModel(item); if (Projects.TryAdd(item.FullPath, projectModel)) { OnProjectLoaded(item, projectModel); } } } }
private void LoadFileHistory() { FileChanges.Visible = true; if (string.IsNullOrEmpty(FileName)) { return; } _asyncLoader.LoadAsync( () => BuildFilter(), filter => { FileChanges.SetFilters(filter); FileChanges.Load(); }); return; (string revision, string path) BuildFilter() { var fileName = FileName; // Replace windows path separator to Linux path separator. // This is needed to keep the file history working when started from file tree in // browse dialog. fileName = fileName.ToPosixPath(); // we will need this later to look up proper casing for the file var fullFilePath = _fullPathResolver.Resolve(fileName); // The section below contains native windows (kernel32) calls // and breaks on Linux. Only use it on Windows. Casing is only // a Windows problem anyway. if (EnvUtils.RunningOnWindows() && File.Exists(fullFilePath)) { // grab the 8.3 file path var shortPath = new StringBuilder(4096); NativeMethods.GetShortPathName(fullFilePath, shortPath, shortPath.Capacity); // use 8.3 file path to get properly cased full file path var longPath = new StringBuilder(4096); NativeMethods.GetLongPathName(shortPath.ToString(), longPath, longPath.Capacity); // remove the working directory and now we have a properly cased file name. fileName = longPath.ToString().Substring(Module.WorkingDir.Length).ToPosixPath(); } if (fileName.StartsWith(Module.WorkingDir, StringComparison.InvariantCultureIgnoreCase)) { fileName = fileName.Substring(Module.WorkingDir.Length); } FileName = fileName; var res = (revision : (string)null, path : $" \"{fileName}\""); if (AppSettings.FollowRenamesInFileHistory && !Directory.Exists(fullFilePath)) { // git log --follow is not working as expected (see http://kerneltrap.org/mailarchive/git/2009/1/30/4856404/thread) // // But we can take a more complicated path to get reasonable results: // 1. use git log --follow to get all previous filenames of the file we are interested in // 2. use git log "list of files names" to get the history graph // // note: This implementation is quite a quick hack (by someone who does not speak C# fluently). // var args = new GitArgumentBuilder("log") { "--format=\"%n\"", "--name-only", "--format", GitCommandHelpers.FindRenamesAndCopiesOpts(), "--", fileName.Quote() }; var listOfFileNames = new StringBuilder(fileName.Quote()); // keep a set of the file names already seen var setOfFileNames = new HashSet <string> { fileName }; var lines = Module.GetGitOutputLines(args, GitModule.LosslessEncoding); foreach (var line in lines.Select(GitModule.ReEncodeFileNameFromLossless)) { if (!string.IsNullOrEmpty(line) && setOfFileNames.Add(line)) { listOfFileNames.Append(" \""); listOfFileNames.Append(line); listOfFileNames.Append('\"'); } } // here we need --name-only to get the previous filenames in the revision graph res.path = listOfFileNames.ToString(); res.revision += " --name-only --parents" + GitCommandHelpers.FindRenamesAndCopiesOpts(); } else if (AppSettings.FollowRenamesInFileHistory) { // history of a directory // --parents doesn't work with --follow enabled, but needed to graph a filtered log res.revision = " " + GitCommandHelpers.FindRenamesOpt() + " --follow --parents"; } else { // rename following disabled res.revision = " --parents"; } if (AppSettings.FullHistoryInFileHistory) { res.revision = string.Concat(" --full-history --simplify-merges ", res.revision); } return(res); } }
public string FormatTextForDrawing(int width, string name, string oldName) { string truncatePathMethod = AppSettings.TruncatePathMethod; if (truncatePathMethod.Equals("fileNameOnly")) { name = name.TrimEnd(AppSettings.PosixPathSeparator); var fileName = Path.GetFileName(name); var oldFileName = Path.GetFileName(oldName); if (fileName.Equals(oldFileName)) { oldFileName = null; } return(fileName.Combine(" ", oldFileName.AddParenthesesNE())); } if ((!truncatePathMethod.Equals("compact", StringComparison.OrdinalIgnoreCase) || !EnvUtils.RunningOnWindows()) && !truncatePathMethod.Equals("trimStart", StringComparison.OrdinalIgnoreCase)) { return(FormatString(name, oldName, 0, false)); } int step = 0; bool isNameBeingTruncated = true; int maxStep = oldName == null ? name.Length : Math.Max(name.Length, oldName.Length) * 2; string result = string.Empty; while (step <= maxStep) { result = FormatString(name, oldName, step, isNameBeingTruncated); if (_graphics.MeasureString(result, _font).Width <= width) { break; } step++; isNameBeingTruncated = !isNameBeingTruncated; } return(result); }
private static void RunApplication() { string[] args = Environment.GetCommandLineArgs(); // This form created to obtain UI synchronization context only using (new Form()) { // Store the shared JoinableTaskContext ThreadHelper.JoinableTaskContext = new JoinableTaskContext(); } AppSettings.LoadSettings(); if (EnvUtils.RunningOnWindows()) { WebBrowserEmulationMode.SetBrowserFeatureControl(); FormFixHome.CheckHomePath(); } if (string.IsNullOrEmpty(AppSettings.Translation)) { using (var formChoose = new FormChooseTranslation()) { formChoose.ShowDialog(); } } try { // Ensure we can find the git command to execute, // unless we are being instructed to uninstall, // or AppSettings.CheckSettings is set to false. if (!(args.Length >= 2 && args[1] == "uninstall")) { if (!CheckSettingsLogic.SolveGitCommand()) { if (!LocateMissingGit()) { Environment.Exit(-1); return; } } if (AppSettings.CheckSettings) { var uiCommands = new GitUICommands(""); var commonLogic = new CommonLogic(uiCommands.Module); var checkSettingsLogic = new CheckSettingsLogic(commonLogic); var fakePageHost = new SettingsPageHostMock(checkSettingsLogic); using (var checklistSettingsPage = SettingsPageBase.Create <ChecklistSettingsPage>(fakePageHost)) { if (!checklistSettingsPage.CheckSettings()) { if (!checkSettingsLogic.AutoSolveAllSettings()) { uiCommands.StartSettingsDialog(); } } } } } } catch { // TODO: remove catch-all } if (EnvUtils.RunningOnWindows()) { MouseWheelRedirector.Active = true; } var commands = new GitUICommands(GetWorkingDir(args)); if (args.Length <= 1) { commands.StartBrowseDialog(); } else { // if we are here args.Length > 1 commands.RunCommand(args); } AppSettings.SaveSettings(); }
private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!EnvUtils.IsMonoRuntime()) { try { NBug.Settings.UIMode = NBug.Enums.UIMode.Full; // Uncomment the following after testing to see that NBug is working as configured NBug.Settings.ReleaseMode = true; NBug.Settings.ExitApplicationImmediately = false; NBug.Settings.WriteLogToDisk = false; NBug.Settings.MaxQueuedReports = 10; NBug.Settings.StopReportingAfter = 90; NBug.Settings.SleepBeforeSend = 30; NBug.Settings.StoragePath = NBug.Enums.StoragePath.WindowsTemp; AppDomain.CurrentDomain.UnhandledException += NBug.Handler.UnhandledException; Application.ThreadException += NBug.Handler.ThreadException; } catch (TypeInitializationException tie) { // is this exception caused by the configuration? if (tie.InnerException != null && tie.InnerException.GetType() .IsSubclassOf(typeof(System.Configuration.ConfigurationException))) { HandleConfigurationException((System.Configuration.ConfigurationException)tie.InnerException); } } } string[] args = Environment.GetCommandLineArgs(); FormSplash.ShowSplash(); //Store here SynchronizationContext.Current, because later sometimes it can be null //see http://stackoverflow.com/questions/11621372/synchronizationcontext-current-is-null-in-continuation-on-the-main-ui-thread GitUIExtensions.UISynchronizationContext = SynchronizationContext.Current; AsyncLoader.DefaultContinuationTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Application.DoEvents(); AppSettings.LoadSettings(); if (EnvUtils.RunningOnWindows()) { WebBrowserEmulationMode.SetBrowserFeatureControl(); //Quick HOME check: FormSplash.SetAction("Checking home path..."); Application.DoEvents(); FormFixHome.CheckHomePath(); } //Register plugins FormSplash.SetAction("Loading plugins..."); Application.DoEvents(); if (string.IsNullOrEmpty(AppSettings.Translation)) { using (var formChoose = new FormChooseTranslation()) { formChoose.ShowDialog(); } } try { if (!(args.Length >= 2 && args[1].Equals("uninstall")) && (AppSettings.CheckSettings || string.IsNullOrEmpty(AppSettings.GitCommandValue) || !File.Exists(AppSettings.GitCommandValue))) { FormSplash.SetAction("Checking settings..."); Application.DoEvents(); GitUICommands uiCommands = new GitUICommands(string.Empty); var commonLogic = new CommonLogic(uiCommands.Module); var checkSettingsLogic = new CheckSettingsLogic(commonLogic); ISettingsPageHost fakePageHost = new SettingsPageHostMock(checkSettingsLogic); using (var checklistSettingsPage = SettingsPageBase.Create <ChecklistSettingsPage>(fakePageHost)) { if (!checklistSettingsPage.CheckSettings()) { if (!checkSettingsLogic.AutoSolveAllSettings()) { uiCommands.StartSettingsDialog(); } } } } } catch { // TODO: remove catch-all } FormSplash.HideSplash(); if (EnvUtils.RunningOnWindows()) { MouseWheelRedirector.Active = true; } GitUICommands uCommands = new GitUICommands(GetWorkingDir(args)); if (args.Length <= 1) { uCommands.StartBrowseDialog(); } else // if we are here args.Length > 1 { uCommands.RunCommand(args); } AppSettings.SaveSettings(); }