Contains various utility functions
Exemple #1
0
        private int GetSelectionStyle(UInt32 mask, UInt32 effect)
        {
            CHARFORMAT2_STRUCT cf = new CHARFORMAT2_STRUCT();

            cf.cbSize     = (UInt32)Marshal.SizeOf(cf);
            cf.szFaceName = new char[32];

            IntPtr wpar = new IntPtr(SCF_SELECTION);
            IntPtr lpar = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));

            Marshal.StructureToPtr(cf, lpar, false);

            if (!ClassUtils.IsMono()) // Can't send message (and use a DLL) on Mono
            {
                SendMessage(Handle, EM_GETCHARFORMAT, wpar, lpar);
            }

            cf = (CHARFORMAT2_STRUCT)Marshal.PtrToStructure(lpar, typeof(CHARFORMAT2_STRUCT));

            int state;

            // dwMask holds the information which properties are consistent throughout the selection:
            if ((cf.dwMask & mask) == mask)
            {
                state = (cf.dwEffects & effect) == effect ? 1 : 0;
            }
            else
            {
                state = -1;
            }

            Marshal.FreeCoTaskMem(lpar);
            return(state);
        }
Exemple #2
0
        /// <summary>
        /// Form constructor. Takes the git file name whose history is to be shown.
        /// </summary>
        public FormRevisionHistory(string targetFile)
        {
            InitializeComponent();
            ClassWinGeometry.Restore(this);

            // WAR: On Linux, remove status bar resizing grip (since it does not work under X)
            if (ClassUtils.IsMono())
            {
                statusStrip.SizingGrip = false;
            }

            // Apply the same font we use for description of changes
            textDescription.Font = Properties.Settings.Default.commitFont;

            file = targetFile;
            Sha  = String.Empty;

            // Show complete path to the file being examined using the OS specific path separator
            Text = @"Revision History for " + App.Repos.Current.Root.Replace('\\', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar + targetFile.Replace('\\', Path.DirectorySeparatorChar);
            // If the path specifies a folder (for example, user clicked on the root repo name on the view pane), add "..."
            if (Text[Text.Length - 1] == Path.DirectorySeparatorChar)
            {
                Text = Text + "...";
            }
        }
Exemple #3
0
 /// <summary>
 /// The function that actually removes all temp files from the list
 /// </summary>
 public static void RemoveTempFiles()
 {
     foreach (var tempFile in TempFiles)
     {
         ClassUtils.DeleteFile(tempFile);
     }
 }
Exemple #4
0
        /// <summary>
        /// Callback on the command line text ready.
        /// We execute a custom (immediate) command which can be either a direct git
        /// command or a shell (command prompt?) command.
        /// Several commands may be separated by "&&" token. This accomodates Gerrit
        /// code review process and its shortcuts that can be easily pasted.
        /// </summary>
        private void CmdBoxTextReady(object sender, string cmd)
        {
            foreach (string command in cmd.Split(new[] { " && " }, StringSplitOptions.RemoveEmptyEntries))
            {
                // Print out the command itself
                App.PrintStatusMessage(command, MessageType.Command);

                // If the command text started with a command 'git', remove it
                string[] tokens = command.Split(' ');
                string   args   = String.Join(" ", tokens, 1, tokens.Count() - 1);

                // We are guaranteed to have at least one token (by the TextBoxEx control)
                string run;
                if (tokens[0].ToLower() == "git")
                {
                    // Command is a git command: execute it
                    run = ClassGit.Run(args).ToString();
                }
                else
                {
                    // Command is an arbitrary (command line type) command
                    // Use the command shell to execute it
                    run = ClassUtils.ExecuteShellCommand(tokens[0], args);
                }
                App.PrintStatusMessage(run, MessageType.Output);
            }
        }
Exemple #5
0
        /// <summary>
        /// This function is called when text boxes name and URL changed.
        /// It calls delegate back to the caller.
        /// </summary>
        private void SomeTextChanged(object sender, EventArgs e)
        {
            // Remove "git clone" substring from the input text which is commonly pasted from an online repo command
            if (textUrlFetch.Text.Trim().StartsWith("git clone"))
            {
                textUrlFetch.Text = textUrlFetch.Text.Replace("git clone", "").Trim();
            }
            if (textUrlPush.Text.Trim().StartsWith("git clone"))
            {
                textUrlPush.Text = textUrlPush.Text.Replace("git clone", "").Trim();
            }

            // Call the delegate and also reparse our fetch and push URLs
            AnyTextChanged(IsValid());

            // Change enable properties only if we are in editing mode, otherwise controls are grayed out
            if (_isEditing)
            {
                // Enable SSH button if one of the URLs uses SSH connection but only on Windows OS
                btSsh.Enabled = !ClassUtils.IsMono() &
                                ((_fetchUrl.Type == ClassUrl.UrlType.Ssh) || (_pushUrl.Type == ClassUrl.UrlType.Ssh));
                // Enable HTTPS password edit, reveal and manage buttons if one of the URLs use HTTPS connection
                btHttps.Enabled       = (_fetchUrl.Type == ClassUrl.UrlType.Https) || (_pushUrl.Type == ClassUrl.UrlType.Https);
                checkReveal.Enabled   = btHttps.Enabled;
                textPassword.ReadOnly = !btHttps.Enabled;

                btWWW1.Enabled = _fetchUrl.Ok;
                btWWW2.Enabled = _pushUrl.Ok;
            }
        }
Exemple #6
0
        /// <summary>
        /// Constructor creates a shell executable file that echoes the PASSWORD
        /// environment variable when called. When GIT_ASKPASS is present, Git
        /// obtains a password for its HTTPS operations by calling it.
        /// </summary>
        public ClassGitPasswd()
        {
            // WAR: Do a different kind of shell script dependent on the OS)
            if (ClassUtils.IsMono())
            {
                // Mono: Use the Shell script
                pathPasswordBatchHelper = Path.Combine(App.AppHome, "passwd.sh");
                File.WriteAllText(pathPasswordBatchHelper, "echo $PASSWORD" + Environment.NewLine);

                // Set the execute bit
                if (Exec.Run("chmod", "+x " + pathPasswordBatchHelper).Success() == false)
                {
                    App.PrintLogMessage("ClassGitPasswd: Unable to chmod +x on " + pathPasswordBatchHelper, MessageType.Error);
                }
            }
            else
            {
                // Windows: Use the CMD BAT script
                // Note: Using "App.AppHome" directory to host the batch helper file
                //       fails on XP where that directory has spaces in the name ("Documents and Settings")
                //       which git cannot handle in this context. Similarly, git will fail with
                //       any other path that contains a space.
                // This redirection is used to provide the password in an automated way.
                pathPasswordBatchHelper = Path.Combine(Path.GetTempPath(), "passwd.bat");
                File.WriteAllText(pathPasswordBatchHelper, "@echo %PASSWORD%" + Environment.NewLine);
                pathPasswordBatchHelper = ClassUtils.GetShortPathName(pathPasswordBatchHelper);
            }
            ClassUtils.AddEnvar("GIT_ASKPASS", pathPasswordBatchHelper);

            App.PrintLogMessage("Created HTTP password helper file: " + pathPasswordBatchHelper, MessageType.General);
        }
        /// <summary>
        /// User changed the radio button source for the repo
        /// </summary>
        private void RbSourceCheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;

            if (rb.Checked)
            {
                textBoxLocal.ReadOnly = true;
                btNext.Enabled        = btBrowse.Enabled = remoteDisplay.Enabled = false;
                remoteDisplay.Enable(false, false);

                switch (Type = rb.Tag.ToString())
                {
                case "empty":
                    btNext.Enabled = true;
                    break;

                case "local":
                    textBoxLocal.ReadOnly = false;
                    btBrowse.Enabled      = true;
                    btNext.Enabled        = ClassUtils.DirStat(Local) == ClassUtils.DirStatType.Git;
                    break;

                case "remote":
                    remoteDisplay.Enabled = true;
                    remoteDisplay.Enable(true, true);
                    btNext.Enabled = remoteDisplay.IsValid();
                    break;
                }
            }
        }
Exemple #8
0
        public ExecResult Run(string args, bool async)
        {
            ExecResult output = new ExecResult();

            try
            {
                Directory.SetCurrentDirectory(Root);

                // Set the HTTPS password
                string password = Remotes.GetPassword("");
                ClassUtils.AddEnvar("PASSWORD", password);

                // The Windows limit to the command line argument length is about 8K
                // We may hit that limit when doing operations on a large number of files.
                //
                // However, when sending a long list of files, git was hanging unless
                // the total length was much less than that, so I set it to about 2000 chars
                // which seemed to work fine.

                if (args.Length < 2000)
                {
                    return(ClassGit.Run(args, async));
                }

                // Partition the args into "[command] -- [set of file chunks < 2000 chars]"
                // Basically we have to rebuild the command into multiple instances with
                // same command but with file lists not larger than about 2K
                int    i   = args.IndexOf(" -- ") + 3;
                string cmd = args.Substring(0, i + 1);
                args = args.Substring(i);       // We separate git command up to and until the list of files

                App.PrintLogMessage("Processing large amount of files: please wait...", MessageType.General);

                // Add files individually up to the length limit using the starting " file delimiter
                string[] files = args.Split(new [] { " \"" }, StringSplitOptions.RemoveEmptyEntries);
                // Note: files in the list are now stripped from their initial " character!
                i = 0;
                do
                {
                    StringBuilder batch = new StringBuilder(2100);
                    while (batch.Length < 2000 && i < files.Length)
                    {
                        batch.Append("\"" + files[i++] + " ");
                    }

                    output = ClassGit.Run(cmd + batch, async);
                    if (output.Success() == false)
                    {
                        break;
                    }
                } while (i < files.Length);
            }
            catch (Exception ex)
            {
                App.PrintLogMessage(ex.Message, MessageType.Error);
            }

            return(output);
        }
Exemple #9
0
        /// <summary>
        /// Callback that handles process printing to stdout
        /// </summary>
        private void PStdout(String message)
        {
            textStdout.AppendText(ClassUtils.ToPlainAscii(message) + Environment.NewLine);

            // Keep the newly added text visible
            textStdout.SelectionStart = textStdout.TextLength;
            textStdout.ScrollToCaret();
        }
Exemple #10
0
 /// <summary>
 /// Mask flickering on TreeView:
 /// http://stackoverflow.com/questions/10362988/treeview-flickering
 /// </summary>
 protected override void OnHandleCreated(EventArgs e)
 {
     if (!ClassUtils.IsMono()) // Can't send message (and use a DLL) on Mono
     {
         SendMessage(this.Handle, TVM_SETEXTENDEDSTYLE, (IntPtr)TVS_EX_DOUBLEBUFFER, (IntPtr)TVS_EX_DOUBLEBUFFER);
     }
     base.OnHandleCreated(e);
 }
Exemple #11
0
        /// <summary>
        /// Callback that handles process printing to stderr.
        /// Prints the stderr to a log window.
        /// </summary>
        private void PStderr(String message)
        {
            // Remove CSI [ or ESC [ + single character sequence
            if (message.StartsWith("\u001b["))
            {
                message = message.Remove(0, 3);
            }

            // This is a workaround for Linux Mono:
            // On Windows, when we clone a remote repo, we receive each status line as a separate message
            // On Linux, it is all clumped together without any newlines (or 0A), so we inject them
            if (ClassUtils.IsMono())
            {
                // A bit of a hack since we simply hard-code recognized types of messages. Oh, well...
                message = message.Replace("remote:", Environment.NewLine + "remote:");
                message = message.Replace("Receiving", Environment.NewLine + "Receiving");
                message = message.Replace("Resolving", Environment.NewLine + "Resolving");
            }
            textStdout.AppendText(ClassUtils.ToPlainAscii(message) + Environment.NewLine, Color.Red);

            // Keep the newly added text visible
            textStdout.SelectionStart = textStdout.TextLength;
            textStdout.ScrollToCaret();

            // This hack recognizes a common problem where the host RSA key was not added to the list
            // of known hosts. Help the user by telling him that and (on Windows) offering to open the
            // Manage Keys dialog.
            if (message.Contains("key fingerprint is"))
            {
                // On Linux / Mono, we don't have a Manage SSH dialog
                if (ClassUtils.IsMono())
                {
                    MessageBox.Show(@"The remote server RSA key was not added to the list of known hosts.", @"Host Key error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    DialogResult response = MessageBox.Show(@"The remote server RSA key was not added to the list of known hosts." + Environment.NewLine +
                                                            @"Would you like to open the Manage SSH Keys dialog to add the host in the Remote Keys tab?", @"Host Key error",
                                                            MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                    if (response == DialogResult.Yes)
                    {
                        FormSSH formSsh = new FormSSH();
                        formSsh.ShowDialog();
                    }
                }
            }

            // This hack recognizes a common HTTPS authentication error message
            if (message.Contains(@"fatal: Authentication failed for 'https:"))
            {
                MessageBox.Show(@"The remote server refused to authenticate you." + Environment.NewLine +
                                @"You need to set your full HTTPS credentials (user name and password) to access this repo.",
                                @"HTTPS Authentication error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            // Append the stderr stream message to a log window
            App.PrintLogMessage("stderr: " + message, MessageType.Error);
        }
Exemple #12
0
        /// <summary>
        /// Checks the path to git and checks that the git executable is functional. This call
        /// should be made only once upon the program start.
        /// It returns true if git executable can be run, false otherwise.
        /// </summary>
        public bool Initialize()
        {
            bool retValue = true;

            // Check that we have a functional version of git at an already set path
            gitPath = Properties.Settings.Default.GitPath;
            if (Exec.Run(gitPath, "--version").stdout.Contains("git version") == false)
            {
                // If we are running on Linux, get the git path by 'which' command
                if (ClassUtils.IsMono())
                {
                    gitPath = Exec.Run("which", "git").stdout.Trim();
                    if (Exec.Run(gitPath, "--version").stdout.Contains("git version") == false)
                    {
                        MessageBox.Show(
                            "Could not locate 'git'!\n\nPlease install git by running 'sudo apt-get install git'\nMake sure it is on your path, then rerun this application.",
                            "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        retValue = false;
                    }
                }
                else
                {
                    // Check if a version of git is installed at a known location (or guess a location)
                    string programFilesPath = Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ??
                                              Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                    // If a git executable does not exist at the default location, try the 64-bit program file folder instead
                    if (!File.Exists(programFilesPath) && programFilesPath.Contains(" (x86)"))
                    {
                        programFilesPath = programFilesPath.Replace(" (x86)", "");
                    }

                    gitPath = Path.Combine(programFilesPath, @"Git\bin\git.exe");
                    if (Exec.Run(gitPath, "--version").stdout.Contains("git version") == false)
                    {
                        // Ask user to show us where the git is installed
                        FormPathToGit formPath = new FormPathToGit(programFilesPath, gitPath);
                        while (retValue = (formPath.ShowDialog() == DialogResult.OK))
                        {
                            gitPath = formPath.PathToGit;
                            if (Exec.Run(gitPath, "--version").stdout.Contains("git version"))
                            {
                                break;
                            }
                        }
                    }
                }
            }
            if (retValue)
            {
                // Run the version again to get the version code (for simplicity did not save it earlier)
                string version = string.Format("Using {0} at {1}", Exec.Run(gitPath, "--version"), gitPath);
                App.PrintLogMessage(version, MessageType.General);
                Properties.Settings.Default.GitPath = gitPath;
            }
            return(retValue);
        }
Exemple #13
0
        /// <summary>
        /// Constructor class function, create batch file helper in the temp space
        /// </summary>
        public ClassSSH()
        {
            string pathHelpertLong = ClassUtils.WriteResourceToFile(Path.GetTempPath(), "git_ssh_helper.sh", Properties.Resources.git_ssh_helper);

            pathHelper = ClassUtils.GetShortPathName(pathHelpertLong);
            // Make the batch file executable: this trick will only work with Mono
            File.SetAttributes(pathHelper, (FileAttributes)((uint)File.GetAttributes(pathHelper) | 0x80000000));
            App.PrintLogMessage("SSH helper path:" + pathHelper, MessageType.Error);
            ClassUtils.AddEnvar("GIT_SSH", pathHelper);
        }
Exemple #14
0
        /// <summary>
        /// Handler for the view file menus.
        /// The tag of the sender specifies the operation on a selected file: null will open a file
        /// using the default association, while any other tag specifies a program to run.
        /// </summary>
        private void MenuViewEditClick(object sender, EventArgs e)
        {
            // Create a temp file on the selected git file version
            string temp = GetTempFile(file, listRev.SelectedItems[0].Name);

            if (!string.IsNullOrEmpty(temp))
            {
                ClassUtils.FileOpenFromMenu(sender, temp);
            }
        }
Exemple #15
0
 /// <summary>
 /// Control is double-clicked. Open the selected item for viewing.
 /// Depending on the saved options, we either do nothing ("0"), open a file
 /// using a default Explorer file association ("1"), or open a file using a
 /// specified application ("2")
 /// </summary>
 private void ListRevDoubleClick(object sender, EventArgs e)
 {
     if (listRev.SelectedIndices.Count == 1)
     {
         // Create a temp file and open the file
         string temp = GetTempFile(file, listRev.SelectedItems[0].Name);
         if (!string.IsNullOrEmpty(temp))
         {
             ClassUtils.FileDoubleClick(temp);
         }
     }
 }
Exemple #16
0
        public FormDiffMissing()
        {
            InitializeComponent();

            if (!ClassUtils.IsMono())
            {
                // Disabling the auto-download of KDiff3 for now until I figure out
                // how to pick up a file from that SF site...
                //
                // labelInfo.Text += "If you prefer, I can download and install KDiff3 for you.";
                // btInstall.Visible = true;
            }
        }
 /// <summary>
 /// Text changed in the destination path, validate it.
 /// </summary>
 private void TextBoxRepoPathTextChanged(object sender, EventArgs e)
 {
     // Target folder needs to be a valid directory, with or without files in it
     ClassUtils.DirStatType type = ClassUtils.DirStat(textBoxRepoPath.Text);
     btOK.Enabled = type == ClassUtils.DirStatType.Empty || type == ClassUtils.DirStatType.Nongit;
     // Additional checks for clone operations (where CheckTargetDirEmpty is true)
     if (CheckTargetDirEmpty)
     {
         // If the project name is specified, that complete path should not exist
         if (textBoxProjectName.Text.Trim().Length > 0)
         {
             btOK.Enabled &= ClassUtils.DirStat(Destination) == ClassUtils.DirStatType.Invalid;
         }
     }
 }
Exemple #18
0
        /// <summary>
        /// Constructor class function, create executables in the temp space
        /// </summary>
        public ClassPutty()
        {
            string pathPageantLong  = ClassUtils.WriteResourceToFile(Path.GetTempPath(), "pageant.exe", Properties.Resources.pageant);
            string pathPlinkLong    = ClassUtils.WriteResourceToFile(Path.GetTempPath(), "plink.exe", Properties.Resources.plink);
            string pathPuttyGenLong = ClassUtils.WriteResourceToFile(Path.GetTempPath(), "puttygen.exe", Properties.Resources.puttygen);

            pathPageant  = ClassUtils.GetShortPathName(pathPageantLong);
            pathPlink    = ClassUtils.GetShortPathName(pathPlinkLong);
            pathPuttyGen = ClassUtils.GetShortPathName(pathPuttyGenLong);

            ClassUtils.AddEnvar("PLINK_PROTOCOL", "ssh");
            ClassUtils.AddEnvar("GIT_SSH", pathPlink);

            // Run the daemon process, update keys
            RunPageantUpdateKeys();
        }
Exemple #19
0
        /// <summary>
        /// Run plink program with the given arguments
        /// </summary>
        public void RunPLink(string args)
        {
            // Start a console process
            Process proc = new Process();

            proc.StartInfo.FileName        = ClassUtils.GetShellExecCmd();
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow  = false;

            // We need to keep the CMD/SHELL window open, so start the process using
            // the CMD/SHELL as the root process and pass it our command to execute
            proc.StartInfo.Arguments = string.Format("{0} \"{1}\" {2}",
                                                     ClassUtils.GetShellExecFlags(), pathPlink, args);

            App.PrintLogMessage(proc.StartInfo.Arguments, MessageType.Command);

            proc.Start();
        }
Exemple #20
0
        /// <summary>
        /// User clicked on the "web" button to the left of the git repo address.
        /// Find the canonical web site and open it
        /// </summary>
        private void BtWwwClick(object sender, EventArgs e)
        {
            string key = ((Button)sender).Tag.ToString();

            ClassUrl.Url url = key == "Fetch" ? _fetchUrl : _pushUrl;
            // Find a generic host name
            string target = "http://" + url.Host;

            // Detect some special hosts for which we can form a complete path
            if (url.Host.Contains("github"))
            {
                target += "/" + url.Path;
            }
            if (url.Host.Contains(".code.sf.net"))
            {
                target = "https://sourceforge.net/projects/" + url.Name;
            }
            ClassUtils.OpenWebLink(target);
        }
Exemple #21
0
        /// <summary>
        /// Class constructor starts a new version check thread.
        /// </summary>
        public ClassVersion()
        {
#if !DEBUG
            // Create a web request object
            request         = WebRequest.Create("http://sourceforge.net/projects/gitforce/");
            request.Timeout = 5000;

            string query = "?v=" + GetVersion() + (ClassUtils.IsMono() ? "&r=Mono" : "&r=.NET") + "&u=" + Environment.UserName;
            altRequest         = WebRequest.Create("http://baltazarstudios.com/uc/GitForce/index.php" + query);
            altRequest.Timeout = 5000;

            // Create and start the thread to check for the new version
            threadCheck = new Thread(ThreadVersionCheck);
            threadCheck.Start();

            altThreadCheck = new Thread(AltThreadVersionCheck);
            altThreadCheck.Start();
#endif
        }
        /// <summary>
        /// Selection of the repo items has changed
        /// Update button enables and common path fields correspondingly
        /// </summary>
        private void ListSelectedIndexChanged(object sender, EventArgs e)
        {
            // Delete button is enabled when one or more repos are selected
            btDelete.Enabled = list.SelectedItems.Count > 0;

            // Enable buttons that are defined to work when only one repo is selected
            btLocate.Enabled = btCreate.Enabled = list.SelectedItems.Count == 1;

            // Create repo should be disabled on a valid git repo
            if (btCreate.Enabled)
            {
                btCreate.Enabled = ClassUtils.DirStat(list.SelectedItems[0].Text) != ClassUtils.DirStatType.Git;
            }

            // Extract common path prefix of all selected repos - only if 2 or more repos are selected
            btBrowse.Enabled  = list.SelectedItems.Count > 1;
            textRootPath.Text = "";
            if (list.SelectedItems.Count > 1)
            {
                // Use the first path as the longest known so far
                List <String> commonPath = list.SelectedItems[0].Text.Split(Path.DirectorySeparatorChar).ToList();
                // Each successive path will make the "commonPath" shorter
                for (int i = 1; i < list.SelectedItems.Count; i++)
                {
                    String[]      nextStr   = list.SelectedItems[i].Text.Split(Path.DirectorySeparatorChar);
                    List <String> newCommon = new List <string>();
                    for (int j = 0; j < nextStr.Count() && j < commonPath.Count(); j++)
                    {
                        if (commonPath[j] == nextStr[j])
                        {
                            newCommon.Add(commonPath[j]);
                        }
                        else
                        {
                            break;
                        }
                    }
                    commonPath = newCommon;
                }
                textRootPath.Text = String.Join(Path.DirectorySeparatorChar.ToString(), commonPath.ToArray());
                btBrowse.Enabled  = commonPath.Count > 0;
            }
        }
Exemple #23
0
        /// <summary>
        /// Form constructor
        /// </summary>
        public FormHttps()
        {
            InitializeComponent();
            ClassWinGeometry.Restore(this);

            // Add button click handlers that will expand the list of existing fetch and push URLs
            _menuHosts.ItemClicked += MenuHostsItemClicked;

            string user = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            netrcfilename = Path.Combine(user, ClassUtils.IsMono() ? ".netrc" : "_netrc");
            App.PrintStatusMessage("Using file " + netrcfilename, MessageType.Debug);

            // Load the .netrc file if it exists, ignore if it does not (we will create it on save)
            if (File.Exists(netrcfilename))
            {
                LoadNetrc(netrcfilename);
                PopulateNetrcView();
            }
        }
Exemple #24
0
        private void SetSelectionStyle(UInt32 mask, UInt32 effect)
        {
            CHARFORMAT2_STRUCT cf = new CHARFORMAT2_STRUCT();

            cf.cbSize    = (UInt32)Marshal.SizeOf(cf);
            cf.dwMask    = mask;
            cf.dwEffects = effect;

            IntPtr wpar = new IntPtr(SCF_SELECTION);
            IntPtr lpar = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));

            Marshal.StructureToPtr(cf, lpar, false);

            if (!ClassUtils.IsMono()) // Can't send message (and use a DLL) on Mono
            {
                SendMessage(Handle, EM_SETCHARFORMAT, wpar, lpar);
            }

            Marshal.FreeCoTaskMem(lpar);
        }
Exemple #25
0
        public Exec(string cmd, string args)
        {
            Proc = new Process {
                StartInfo =
                {
                    FileName               = cmd,
                    Arguments              = args,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    WorkingDirectory       = Directory.GetCurrentDirectory()
                }
            };

            Proc.OutputDataReceived += POutputDataReceived;
            Proc.ErrorDataReceived  += PErrorDataReceived;

            // TODO: This is a hack for mergetool: We need to show the window to ask the user if the merge succeeded.
            // The problem is with .NET (and MONO!) buffering of streams prevents us to catching the question on time.
            if (args.StartsWith("mergetool "))
            {
                Proc.StartInfo.CreateNoWindow         = false;
                Proc.StartInfo.RedirectStandardOutput = false;
                Proc.StartInfo.RedirectStandardError  = false;
            }

            // Add all environment variables registered for our process environment
            foreach (var variable in ClassUtils.GetEnvars())
            {
                // If a variable with that name already exists, update it
                if (Proc.StartInfo.EnvironmentVariables.ContainsKey(variable.Key))
                {
                    Proc.StartInfo.EnvironmentVariables[variable.Key] = variable.Value;
                }
                else
                {
                    Proc.StartInfo.EnvironmentVariables.Add(variable.Key, variable.Value);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Class constructor starts a new version check thread.
        /// </summary>
        public ClassVersion()
        {
#if !DEBUG
            // Create a web request object
            ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };
            ServicePointManager.SecurityProtocol |= (SecurityProtocolType)0x00000C00; // SecurityProtocolType.Tls12;
            request         = WebRequest.Create("https://sourceforge.net/projects/gitforce/files/");
            request.Timeout = 5000;

            string query = "?v=" + GetVersion() + (ClassUtils.IsMono() ? "&r=Mono" : "&r=.NET") + "&u=" + Environment.UserName;
            altRequest         = WebRequest.Create("http://baltazarstudios.com/uc/GitForce/index.php" + query);
            altRequest.Timeout = 5000;

            // Create and start the thread to check for the new version
            threadCheck = new Thread(() => ThreadVersionCheck(request));
            threadCheck.Start();

            altThreadCheck = new Thread(() => ThreadVersionCheck(altRequest));
            altThreadCheck.Start();
#endif
        }
Exemple #27
0
        public FormEditTools(ClassTool tool)
        {
            InitializeComponent();
            ClassWinGeometry.Restore(this);
            Tool = (ClassTool)tool.Clone();

            textName.Text = tool.Name;
            textCmd.Text  = tool.Cmd;
            textArgs.Text = tool.Args;
            textDir.Text  = tool.Dir;
            textDesc.Text = tool.Desc;
            checkAddToContextMenu.Checked = tool.IsAddToContextMenu;
            checkConsoleApp.Checked       = tool.IsConsoleApp;
            checkWriteToStatus.Checked    = tool.IsWriteOutput;
            checkCloseUponExit.Checked    = tool.IsCloseWindowOnExit;
            checkRefresh.Checked          = tool.IsRefresh;
            checkPrompt.Checked           = tool.IsPromptForArgs;
            checkBrowse.Checked           = tool.IsAddBrowse;

            // TODO: Running a command line tool largely does not work on Linux at the moment
            if (ClassUtils.IsMono())
            {
                checkWriteToStatus.Enabled = checkCloseUponExit.Enabled = false;
                checkWriteToStatus.Checked = checkCloseUponExit.Checked = false;
                checkConsoleApp.Checked    = true; // FIXME: Some success when this is checked
            }

            // Adjust the enables (in this order)
            CheckCloseUponExitCheckedChanged(null, null);
            CheckConsoleAppCheckedChanged(null, null);

            // Set the width of drop-down portions of help combo box so when it expands (down)
            // it will show horizontally the complete text from all pre-defined lines.
            // Also set their tags to point to the buddy edit boxes into which to insert selected tokens.
            SetComboBoxWidth(comboHelpArg);
            comboHelpArg.Tag = textArgs;
            SetComboBoxWidth(comboHelpDir);
            comboHelpDir.Tag = textDir;
        }
Exemple #28
0
        public FormLog()
        {
            InitializeComponent();
            ClassWinGeometry.Restore(this);

            // Add our main print function callback delegate
            App.PrintLogMessage += Print;

            // WAR: On Linux, remove status bar resizing grip (since it does not work under X)
            if (ClassUtils.IsMono())
            {
                statusStrip.SizingGrip = false;
            }

            if (App.AppLog != null)
            {
                Print("Logging: " + App.AppLog, MessageType.General);
            }

            // Prints only in Debug build...
            Debug("Debug build.");
        }
Exemple #29
0
        /// <summary>
        /// Class constructor that also pre-sets the command and argument to be run
        /// </summary>
        public FormGitRun(string cmd, string args)
        {
            InitializeComponent();
            ClassWinGeometry.Restore(this);
            checkAutoclose.Checked = Properties.Settings.Default.AutoCloseGitOnSuccess;

            // WAR: On Linux, remove status bar resizing grip (since it does not work under X)
            if (ClassUtils.IsMono())
            {
                statusStrip.SizingGrip = false;
            }

            // Detect URL in this text box
            textStdout.DetectUrls = true;

            job = new Exec(cmd, args);

            // Reuse the same font selected as fixed-pitch
            textStdout.Font  = Properties.Settings.Default.commitFont;
            textStdout.Text += cmd + Environment.NewLine;
            textStdout.Text += args + Environment.NewLine;
        }
Exemple #30
0
        /// <summary>
        /// This function is called when text boxes name and URL changed.
        /// It calls delegate back to the caller.
        /// </summary>
        private void SomeTextChanged(object sender, EventArgs e)
        {
            // Call the delegate and also reparse our fetch and push URLs
            AnyTextChanged(IsValid());

            // Enable SSH button if one of the URLs uses SSH connection
            btSsh.Enabled = false;
            if (_fetchUrl.Ok && _fetchUrl.Type == ClassUrl.UrlType.Ssh)
            {
                btSsh.Enabled = true;
            }
            if (_pushUrl.Ok && _pushUrl.Type == ClassUrl.UrlType.Ssh)
            {
                btSsh.Enabled = true;
            }
            btWWW1.Enabled = _fetchUrl.Ok;
            btWWW2.Enabled = _pushUrl.Ok;

            textPassword.ReadOnly = !(_fetchUrl.Type == ClassUrl.UrlType.Https || _pushUrl.Type == ClassUrl.UrlType.Https);

            // WAR: Permanently disable SSH button if not on Windows OS
            btSsh.Enabled = !ClassUtils.IsMono();
        }