Inheritance: MonoBehaviour
Exemplo n.º 1
0
        public virtual void LoopThroughJobTitles(SimpleHtmlWriter htmlWriter)
        {
            int rowCount = this.table.RowCount;

            Console.WriteLine("The search result page has " + rowCount + " rows.");
            for (int rowIdx = 0; rowIdx < rowCount; rowIdx++)
            {
                try
                {
                    string   vacanciesLinkId = "cphMainContent_OccGrid_lbVacacnyCount_" + rowIdx;
                    TextLink vacanciesLink   = new TextLink(By.Id(vacanciesLinkId));
                    if (vacanciesLink.Exists)
                    {
                        string vacanciesTitle = this.table.GetCell(rowIdx, 0).Text;
                        Console.WriteLine();
                        Console.WriteLine("Clicking the '" + vacanciesTitle + "' vacancies link on row " + rowIdx + " (id=" + vacanciesLinkId + ")");
                        vacanciesLink.Click();

                        (new JobVacancySearchResultsPage()).WaitUntilAvailable().LoopThroughJobVacancies(htmlWriter);

                        Console.WriteLine("Navigate back to the previous (Exams & Job Vacancies Search Results) page");
                        Browser.NavigateBack();
                        WaitUntilAvailable();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    Console.Write(e.StackTrace);
                }
            }
        }
Exemplo n.º 2
0
		void AddDefaultValue (StringBuilder sb, TextLink link, string name)
		{
			if (string.IsNullOrEmpty (variableDecarations[name].Default))
				return;
			link.AddLink (new Segment (sb.Length, variableDecarations[name].Default.Length));
			sb.Append (variableDecarations[name].Default);
		}
        public override void InsertCompletionText(CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier)
        {
            // insert add/remove event handler code after +=/-=
            editor.Replace(initialOffset, editor.Caret.Offset - initialOffset, this.DisplayText + (AddSemicolon ? ";" : ""));

            // Search opening bracket of member
            int pos = callingMember != null?editor.Document.LocationToOffset(callingMember.BodyRegion.Start.Line, callingMember.BodyRegion.Start.Column) : initialOffset;

            while (pos < editor.Document.Length && editor.Document.GetCharAt(pos) != '{')
            {
                pos++;
            }

            // Search closing bracket of member
            pos = editor.Document.GetMatchingBracketOffset(pos) + 1;

            pos = Math.Max(0, Math.Min(pos, editor.Document.Length - 1));

            // Insert new event handler after closing bracket
            string indent = editor.Document.GetLine(callingMember.Location.Line).GetIndentation(editor.Document);

            StringBuilder sb = new StringBuilder();

            sb.Append(editor.EolMarker);
            sb.Append(editor.EolMarker);
            sb.Append(indent);
            if (callingMember.IsStatic)
            {
                sb.Append("static ");
            }
            sb.Append("void ");
            int pos2 = sb.Length;

            sb.Append(this.DisplayText); sb.Append(' '); sb.Append(this.parameterList); sb.Append(editor.EolMarker);
            sb.Append(indent); sb.Append("{"); sb.Append(editor.EolMarker);
            sb.Append(indent); sb.Append(TextEditorProperties.IndentString);
            int cursorPos = pos + sb.Length;

            sb.Append(editor.EolMarker);
            sb.Append(indent); sb.Append("}");
            editor.Insert(pos, sb.ToString());
            editor.Caret.Offset = cursorPos;

            // start text link mode after insert
            List <TextLink> links = new List <TextLink> ();
            TextLink        link  = new TextLink("name");

            link.AddLink(new Segment(0, this.DisplayText.Length));
            link.AddLink(new Segment(pos - initialOffset + pos2, this.DisplayText.Length));
            links.Add(link);

            CompletionTextLinkMode tle = new CompletionTextLinkMode(editor.Parent, initialOffset, links);

            tle.TriggerCodeCompletion = false;
            tle.SetCaretPosition      = true;
            tle.SelectPrimaryLink     = true;
            tle.OldMode = editor.CurrentMode;
            tle.StartMode();
            editor.CurrentMode = tle;
        }
        public override void Run(RefactoringOptions options)
        {
            var data = options.GetTextEditorData();

            SearchMatchingExpressions(options);

            base.Run(options);
            if (selectionEnd >= 0)
            {
                options.Document.Editor.Caret.Offset = selectionEnd;
                options.Document.Editor.SetSelection(selectionStart, selectionEnd);
            }
            else
            {
                Mono.TextEditor.TextEditor editor = data.Parent;
                TextLink link = new TextLink("name");
                if (varName != null)
                {
                    foreach (var offset in offsets)
                    {
                        link.AddLink(new Segment(offset - selectionStart, varName.Length));
                    }
                }
                List <TextLink> links = new List <TextLink> ();
                links.Add(link);
                TextLinkEditMode tle = new TextLinkEditMode(editor, selectionStart, links);
                tle.SetCaretPosition = false;
                if (tle.ShouldStartTextLinkMode)
                {
                    tle.OldMode = data.CurrentMode;
                    tle.StartMode();
                    data.CurrentMode = tle;
                }
            }
        }
Exemplo n.º 5
0
        private void PasteHref_Loaded(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Link))
            {
                if (IsLink(LinkText))
                {
                    Link = LinkText;
                }
                else
                {
                    string clipText = ClipboardHelper.GetText();
                    if (IsLink(clipText))
                    {
                        Link = clipText;
                    }
                }
            }
            if (string.IsNullOrEmpty(LinkText) && !string.IsNullOrEmpty(Link))
            {
                LinkText = Link;
            }

            if (string.IsNullOrEmpty(LinkText))
            {
                TextLinkText.Focus();
            }
            else
            {
                TextLink.Focus();
            }
        }
Exemplo n.º 6
0
        public override Task Link(params AstNode[] nodes)
        {
            var tcs      = new TaskCompletionSource <object> ();
            var segments = new List <TextSegment> (nodes.Select(node => new TextSegment(GetSegment(node))).OrderBy(s => s.Offset));

            var link = new TextLink("name");

            segments.ForEach(s => link.AddLink(s));
            var links = new List <TextLink> ();

            links.Add(link);
            var tle = new TextLinkEditMode(context.TextEditor.Parent, 0, links);

            tle.SetCaretPosition = false;
            if (tle.ShouldStartTextLinkMode)
            {
                operationsRunning++;
                context.TextEditor.Caret.Offset = segments [0].EndOffset;
                tle.OldMode = context.TextEditor.CurrentMode;
                tle.Cancel += (sender, e) => Rollback();
                tle.Exited += (sender, e) => DisposeOnClose();
                tle.StartMode();
                context.TextEditor.CurrentMode = tle;
                if (IdeApp.Workbench.ActiveDocument != null)
                {
                    IdeApp.Workbench.ActiveDocument.ReparseDocument();
                }
            }
            return(tcs.Task);
        }
		public override void Run (RefactoringOptions options)
		{
			base.Run (options);
			
			TextEditorData data = options.GetTextEditorData ();
			Mono.TextEditor.TextEditor editor = data.Parent;
			
			List<TextLink> links = new List<TextLink> ();
			TextLink link = new TextLink ("name");
			int referenceCount = 1;
			MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult;
			IProperty property = resolveResult.ResolvedMember as IProperty;
			if (property.HasGet)
				referenceCount++;
			if (property.HasSet)
				referenceCount++;
			for (int i = refactoringStartOffset; i < data.Document.Length - backingStoreName.Length; i++) {
				if (data.Document.GetTextAt (i, backingStoreName.Length) == backingStoreName) {
					link.AddLink (new Segment (i - refactoringStartOffset, backingStoreName.Length));
					if (link.Count == referenceCount)
						break;
				}
			}
			
			links.Add (link);
			TextLinkEditMode tle = new TextLinkEditMode (editor, refactoringStartOffset, links);
			tle.SetCaretPosition = false;
			if (tle.ShouldStartTextLinkMode) {
				tle.OldMode = data.CurrentMode;
				tle.StartMode ();
				data.CurrentMode = tle;
			}
		}
Exemplo n.º 8
0
        internal static async Task <List <TextLink> > GetTextLinksAsync(Ide.Gui.Document doc, int caretOffset, ISymbol symbol)
        {
            var links = new List <TextLink> ();
            var link  = new TextLink("name");

            var documents = ImmutableHashSet.Create(doc.DocumentContext.AnalysisDocument);

            foreach (var loc in symbol.Locations)
            {
                if (loc.IsInSource && FilePath.PathComparer.Equals(loc.SourceTree.FilePath, doc.FileName))
                {
                    link.AddLink(new TextSegment(loc.SourceSpan.Start, loc.SourceSpan.Length));
                }
            }

            foreach (var mref in await SymbolFinder.FindReferencesAsync(symbol, doc.DocumentContext.AnalysisDocument.Project.Solution, documents, default(CancellationToken)))
            {
                foreach (var loc in mref.Locations)
                {
                    var span    = loc.Location.SourceSpan;
                    var segment = new TextSegment(span.Start, span.Length);
                    if (segment.Offset <= caretOffset && caretOffset <= segment.EndOffset)
                    {
                        link.Links.Insert(0, segment);
                    }
                    else
                    {
                        link.AddLink(segment);
                    }
                }
            }
            links.Add(link);
            return(links);
        }
Exemplo n.º 9
0
        public void RenameCommand()
        {
            if (!renameProvider.HasSegments)
                return; //nothing to rename

            var textSegments = renameProvider.SegmentsToRename;
            TextSegment primarySegment = renameProvider.SelectedTextSegment;

            var link = new TextLink ("name"); //not sure why the link has to be named
            var links = new List<TextLink> ();

            //make sure that the segment where the cursor is is first in the list
            // othewise the document will jump to the location of the first link
            link.AddLink (primarySegment);

            foreach(TextSegment segment in textSegments)
            {
                if (segment != primarySegment)
                    link.AddLink (segment);
            }
            links.Add (link);

            var mode = new TextLinkEditMode (Editor.Parent, 0, links);
            mode.SetCaretPosition = false;
            mode.SelectPrimaryLink = true;

            mode.OldMode = Editor.Parent.CurrentMode;
            mode.Cancel += textLinkEditorCanceled;
            mode.HelpWindow = getHelpWindowFor (renameProvider.SelectedSymbolType);
            mode.StartMode ();
            Editor.Parent.CurrentMode = mode;
        }
Exemplo n.º 10
0
        private void SelectLocalLinkFile_Click(object sender, RoutedEventArgs e)
        {
            var fd = new OpenFileDialog
            {
                DefaultExt       = ".html",
                Filter           = "Linkable Files (*.htm,*.html,*.md,*.pdf;*.zip)|*.html;*.htm;*.md;*.pdf;*.zip|All Files (*.*)|*.*",
                CheckFileExists  = true,
                RestoreDirectory = true,
                Multiselect      = false,
                Title            = "Embed a local relative link"
            };

            if (!string.IsNullOrEmpty(MarkdownFile))
            {
                fd.InitialDirectory = System.IO.Path.GetDirectoryName(MarkdownFile);
            }
            else
            {
                fd.InitialDirectory = mmApp.Configuration.LastFolder;
            }

            var res = fd.ShowDialog();

            if (res == null || !res.Value)
            {
                return;
            }

            Link = fd.FileName;

            // Normalize the path relative to the Markdown file
            if (!string.IsNullOrEmpty(MarkdownFile))
            {
                string mdPath = System.IO.Path.GetDirectoryName(MarkdownFile);

                string relPath = fd.FileName;
                try
                {
                    relPath = FileUtils.GetRelativePath(fd.FileName, mdPath);
                }
                catch (Exception ex)
                {
                    mmApp.Log($"Failed to get relative path.\r\nFile: {fd.FileName}, Path: {mdPath}", ex);
                }

                // not relative
                if (!relPath.StartsWith("..\\"))
                {
                    Link = relPath;
                }

                // is it a physical path?
                if (Link.Contains(":\\"))
                {
                    Link = "file:///" + Link;
                }
            }
            mmApp.Configuration.LastFolder = System.IO.Path.GetDirectoryName(fd.FileName);
            TextLink.Focus();
        }
 /// <summary>
 /// expand text
 /// </summary>
 public void ExpandText()
 {
     TextContainer.FakeCssValueStyle = "display: none;";
     if (TextContainer.WaitUntilExists(3).GetAttribute("class").Contains("none"))
     {
         TextLink.Wait(3).Click();
     }
 }
 /// <summary>
 /// collapse text
 /// </summary>
 public void CollapseText()
 {
     TextContainer.FakeAttributeClass = "display: block;";
     if (TextContainer.WaitUntilExists(3).GetAttribute("class").Equals("block"))
     {
         TextLink.Wait(3).Click();
     }
 }
Exemplo n.º 13
0
 private void PasteHref_Activated(object sender, EventArgs e)
 {
     if (string.IsNullOrEmpty(Link))
     {
         string clip = ClipboardHelper.GetText();
         if (IsLink(clip))
         {
             Link = clip.Replace(" ", "%20");
             TextLink.SelectAll();
         }
     }
 }
Exemplo n.º 14
0
        public ActionResult Mapping()
        {
            string tempfileName     = Session["import_file_path"].ToString();
            bool   isFirstRowHeader = Request["IsFirstRowHeader"] == "on" ? true : false;
            string rowDelimiter     = Request["RowDelimiter"];
            string columnDelimiter  = Request["ColumnDelimiter"];
            string tableName        = Request["TableName"];

            ImportInfo imfo = new ImportInfo();

            imfo.DestinationTableName   = tableName;
            imfo.ImportFileLocation     = tempfileName;
            imfo.FirstRowHasColumnNames = isFirstRowHeader;
            imfo.RowDelimiter           = TemplateToString(rowDelimiter);
            imfo.ColumnDelimiter        = TemplateToString(columnDelimiter);

            StringBuilder sbConn = new StringBuilder();

            sbConn.Append("@File=");
            sbConn.Append(tempfileName);
            sbConn.Append(";@Type=Delimited;");
            sbConn.Append("RowSeperator=");
            sbConn.Append(imfo.RowDelimiter);
            sbConn.Append(";ColumnSeperator=");
            sbConn.Append(imfo.ColumnDelimiter);
            sbConn.Append(";FirstRowHasNames=");
            sbConn.Append(imfo.FirstRowHasColumnNames.ToString());

            SqlDataLink sqlLink = new SqlDataLink();

            sqlLink.Initialize(ConfigurationManager.AppSettings["SqlConnection"]);
            sqlLink.Connect();
            ColumnDefinition[] sqlCds = sqlLink.GetSchema("SELECT * FROM " + imfo.DestinationTableName);
            imfo.DestinationColumns = sqlCds;


            TextLink tl = new TextLink();

            tl.Initialize(sbConn.ToString());
            tl.Connect();

            ColumnDefinition[] cds     = tl.GetSchema("");
            List <string>      columns = new List <string>();

            foreach (ColumnDefinition cd in cds)
            {
                columns.Add(cd.ColumnName);
            }
            imfo.SourceColumns = columns.ToArray();
            return(View(imfo));
        }
Exemplo n.º 15
0
        private void LoadDefaultServer()
        {
            if (_modifiedConfiguration.configs.Count == 0)
            {
                Server server = Configuration.GetDefaultServer();

                IPTextBox.Text           = server.server;
                NumServerPort.Value      = server.server_port;
                NumUDPPort.Value         = server.server_udp_port;
                PasswordTextBox.Text     = server.password;
                EncryptionSelect.Text    = server.method;
                TCPProtocolComboBox.Text = server.protocol;
                ObfsComboBox.Text        = server.obfs;
                TextProtocolParam.Text   = server.protocolparam;
                TextObfsParam.Text       = server.obfsparam;
                RemarksTextBox.Text      = server.remarks;
                TextGroup.Text           = server.group;
                CheckUDPoverUDP.Checked  = server.udp_over_tcp;
                //CheckObfsUDP.Checked = server.obfs_udp;
                _SelectedID = server.id;

                if (TCPProtocolComboBox.Text == "origin" && ObfsComboBox.Text == "plain" && !CheckUDPoverUDP.Checked)
                {
                    checkAdvSetting.Checked = false;
                }

                if (checkSSRLink.Checked)
                {
                    TextLink.Text = server.GetSSRLinkForServer();
                }
                else
                {
                    TextLink.Text = server.GetSSLinkForServer();
                }

                if (CheckTCPoverUDP.Checked || CheckUDPoverUDP.Checked || server.server_udp_port != 0)
                {
                    checkAdvSetting.Checked = true;
                }

                Update_SSR_controls_Visable();
                UpdateObfsTextbox();
                TextLink.SelectAll();
                GenQR(TextLink.Text);
            }
        }
Exemplo n.º 16
0
        public override void Run(RefactoringOptions options)
        {
            base.Run(options);

            TextEditorData data = options.GetTextEditorData();

            Mono.TextEditor.TextEditor editor = data.Parent;

            List <TextLink>     links          = new List <TextLink> ();
            TextLink            link           = new TextLink("name");
            int                 referenceCount = 1;
            MemberResolveResult resolveResult  = options.ResolveResult as MemberResolveResult;
            IProperty           property       = resolveResult.ResolvedMember as IProperty;

            if (property.HasGet)
            {
                referenceCount++;
            }
            if (property.HasSet)
            {
                referenceCount++;
            }
            for (int i = refactoringStartOffset; i < data.Document.Length - backingStoreName.Length; i++)
            {
                if (data.Document.GetTextAt(i, backingStoreName.Length) == backingStoreName)
                {
                    link.AddLink(new Segment(i - refactoringStartOffset, backingStoreName.Length));
                    if (link.Count == referenceCount)
                    {
                        break;
                    }
                }
            }

            links.Add(link);
            TextLinkEditMode tle = new TextLinkEditMode(editor, refactoringStartOffset, links);

            tle.SetCaretPosition = false;
            if (tle.ShouldStartTextLinkMode)
            {
                tle.OldMode = data.CurrentMode;
                tle.StartMode();
                data.CurrentMode = tle;
            }
        }
Exemplo n.º 17
0
        private void AddCommand(Panel workItemPanel)
        {
            if (workItemPanel == null)
            {
                return;
            }

            var separator = new Separator();

            separator.Style = (Style)workItemPanel.FindResource("VerticalSeparator");
            workItemPanel.Children.Add(separator);

            var textLink = new TextLink();

            textLink.Text    = "Select last";
            textLink.ToolTip = "Select workitem associated with last changeset";
            textLink.Command = new RelayCommand(SetLastWorkItem);
            workItemPanel.Children.Add(textLink);
        }
Exemplo n.º 18
0
            public override void Perform(Script script)
            {
                List <Segment> segments = new List <Segment> ();

                foreach (var action in script.Actions)
                {
                    if (action == this)
                    {
                        break;
                    }
                    var noa = action as NodeOutputAction;
                    if (noa == null)
                    {
                        continue;
                    }
                    foreach (var astNode in Linked)
                    {
                        NodeOutput.Segment segment;
                        if (noa.NodeOutput.NodeSegments.TryGetValue(astNode, out segment))
                        {
                            segments.Add(new Segment(noa.Offset + segment.Offset, segment.Length));
                        }
                    }
                }
                segments.Sort((x, y) => x.Offset.CompareTo(y.Offset));
                var link = new TextLink("name");

                segments.ForEach(s => link.AddLink(s));
                var links = new List <TextLink> ();

                links.Add(link);
                var tle = new TextLinkEditMode(ctx.Document.Editor.Parent, 0, links);

                tle.SetCaretPosition = false;
                if (tle.ShouldStartTextLinkMode)
                {
                    tle.OldMode = ctx.Document.Editor.CurrentMode;
                    tle.StartMode();
                    ctx.Document.Editor.CurrentMode = tle;
                }
            }
Exemplo n.º 19
0
        static List <TextLink> CreateTextLinks(this TextEditor editor, IEnumerable <SearchResult> references)
        {
            var links = new List <TextLink> ();
            var link  = new TextLink("name");

            foreach (SearchResult reference in references)
            {
                var segment = new TextSegment(reference.Offset, reference.Length);
                if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset)
                {
                    link.Links.Insert(0, segment);
                }
                else
                {
                    link.AddLink(segment);
                }
            }
            links.Add(link);

            return(links);
        }
Exemplo n.º 20
0
        public override void Link(params AstNode[] nodes)
        {
            var segments = new List <TextSegment> (nodes.Select(node => new TextSegment(GetSegment(node))).OrderBy(s => s.Offset));

            var link = new TextLink("name");

            segments.ForEach(s => link.AddLink(s));
            var links = new List <TextLink> ();

            links.Add(link);
            var tle = new TextLinkEditMode(document.Editor.Parent, 0, links);

            tle.SetCaretPosition = false;
            if (tle.ShouldStartTextLinkMode)
            {
                document.Editor.Caret.Offset = segments [0].EndOffset;
                tle.OldMode = document.Editor.CurrentMode;
                tle.StartMode();
                document.Editor.CurrentMode = tle;
            }
        }
 public override void Run(RefactoringOptions options)
 {
     base.Run(options);
     if (selectionEnd >= 0)
     {
         options.Document.TextEditor.CursorPosition = selectionEnd;
         options.Document.TextEditor.Select(selectionStart, selectionEnd);
     }
     else
     {
         TextEditorData             data   = options.GetTextEditorData();
         Mono.TextEditor.TextEditor editor = data.Parent;
         TextLink link = new TextLink("name");
         if (varName != null)
         {
             if (insertOffset >= 0)
             {
                 link.AddLink(new Segment(insertOffset - selectionStart, varName.Length));
             }
             else
             {
                 LoggingService.LogWarning("insert offset not found.");
             }
             if (replaceOffset >= 0)
             {
                 link.AddLink(new Segment(replaceOffset - selectionStart, varName.Length));
             }
         }
         List <TextLink> links = new List <TextLink> ();
         links.Add(link);
         TextLinkEditMode tle = new TextLinkEditMode(editor, selectionStart, links);
         tle.SetCaretPosition = false;
         if (tle.ShouldStartTextLinkMode)
         {
             tle.OldMode = data.CurrentMode;
             tle.StartMode();
             data.CurrentMode = tle;
         }
     }
 }
Exemplo n.º 22
0
        public static TextLink FindChildTextLink(DependencyObject depObj, string childName, string linkText)
        {
            // Confirm obj is valid.
            if (depObj == null)
            {
                return(null);
            }

            // success case
            if (depObj is TextLink
                //&& depObj is FrameworkElement
                && ((FrameworkElement)depObj).Name == childName)
            {
                string depObjDesc = depObj.ToString();
                if (depObjDesc.Equals($"Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TextLink: {linkText}"))
                {
                    return(depObj as TextLink);
                }
            }

            int childrenCount = VisualTreeHelper.GetChildrenCount(depObj);

            for (int i = 0; i < childrenCount; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

                //DFS
                TextLink obj = FindChildTextLink(child, childName, linkText);

                if (obj != null)
                {
                    return(obj);
                }
            }

            return(null);
        }
		public override void Run (RefactoringOptions options)
		{
			if (options.SelectedItem is IVariable) {
				var field = options.SelectedItem as IField;
				if (field != null && field.Accessibility != Accessibility.Private) {
					MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
					return;
				}

				var col = ReferenceFinder.FindReferences (options.SelectedItem, true);
				if (col == null)
					return;
				var data = options.Document != null ? options.GetTextEditorData () : IdeApp.Workbench.ActiveDocument.Editor;
				var editor = data.Parent;
				if (editor == null) {
					MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
					return;
				}
				
				var links = new List<TextLink> ();
				var link = new TextLink ("name");
				int baseOffset = Int32.MaxValue;
				foreach (var r in col) {
					baseOffset = Math.Min (baseOffset, r.Offset);
				}
				foreach (MemberReference r in col) {
					var segment = new TextSegment (r.Offset - baseOffset, r.Length);
					if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) {
						link.Links.Insert (0, segment); 
					} else {
						link.AddLink (segment);
					}
				}
				
				links.Add (link);
				if (editor.CurrentMode is TextLinkEditMode)
					((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode ();
				TextLinkEditMode tle = new TextLinkEditMode (editor, baseOffset, links);
				tle.SetCaretPosition = false;
				tle.SelectPrimaryLink = true;
				if (tle.ShouldStartTextLinkMode) {
					var helpWindow = new TableLayoutModeHelpWindow ();
					helpWindow.TransientFor = IdeApp.Workbench.RootWindow;
					helpWindow.TitleText = options.SelectedItem is IVariable ? GettextCatalog.GetString ("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString ("<b>Parameter -- Renaming</b>");
					helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Key</b>"), GettextCatalog.GetString ("<b>Behavior</b>")));
					helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Return</b>"), GettextCatalog.GetString ("<b>Accept</b> this refactoring.")));
					helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Esc</b>"), GettextCatalog.GetString ("<b>Cancel</b> this refactoring.")));
					tle.HelpWindow = helpWindow;
					tle.Cancel += delegate {
						if (tle.HasChangedText)
							editor.Document.Undo ();
					};
					tle.OldMode = data.CurrentMode;
					tle.StartMode ();
					data.CurrentMode = tle;
				}
			} else {
				MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
			}
		}
Exemplo n.º 24
0
		public override void Run (RefactoringOptions options)
		{
			if (options.SelectedItem is LocalVariable || options.SelectedItem is IParameter) {
				MemberReferenceCollection col = GetReferences (options);
				if (col == null)
					return;
				TextEditorData data = options.GetTextEditorData ();
				Mono.TextEditor.TextEditor editor = data.Parent;
				if (editor == null) {
					MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
					return;
				}

				
				List<TextLink> links = new List<TextLink> ();
				TextLink link = new TextLink ("name");
				int baseOffset = Int32.MaxValue;
				foreach (MemberReference r in col) {
					baseOffset = Math.Min (baseOffset, data.Document.LocationToOffset (r.Line, r.Column));
				}
				foreach (MemberReference r in col) {
					Segment segment = new Segment (data.Document.LocationToOffset (r.Line, r.Column) - baseOffset, r.Name.Length);
					if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) {
						link.Links.Insert (0, segment); 
					} else {
						link.AddLink (segment);
					}
				}
				
				links.Add (link);
				TextLinkEditMode tle = new TextLinkEditMode (editor, baseOffset, links);
				tle.SetCaretPosition = false;
				tle.SelectPrimaryLink = true;
				if (tle.ShouldStartTextLinkMode) {
					ModeHelpWindow helpWindow = new ModeHelpWindow ();
					helpWindow.TransientFor = IdeApp.Workbench.RootWindow;
					helpWindow.TitleText = options.SelectedItem is LocalVariable ? GettextCatalog.GetString ("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString ("<b>Parameter -- Renaming</b>");
					helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Key</b>"), GettextCatalog.GetString ("<b>Behavior</b>")));
					helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Return</b>"), GettextCatalog.GetString ("<b>Accept</b> this refactoring.")));
					helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Esc</b>"), GettextCatalog.GetString ("<b>Cancel</b> this refactoring.")));
					tle.HelpWindow = helpWindow;
					tle.Cancel += delegate {
						editor.Document.Undo ();
					};
					tle.OldMode = data.CurrentMode;
					tle.StartMode ();
					data.CurrentMode = tle;
				}
			} else {
				MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
			}
		}
Exemplo n.º 25
0
			public override void Perform (Script script)
			{
				List<Segment> segments = new List<Segment> ();
				foreach (var action in script.Actions) {
					if (action == this)
						break;
					var noa = action as NodeOutputAction;
					if (noa == null)
						continue;
					foreach (var astNode in Linked) {
						NodeOutput.Segment segment;
						if (noa.NodeOutput.NodeSegments.TryGetValue (astNode, out segment))
							segments.Add (new Segment (noa.Offset + segment.Offset, segment.Length));
					}
				}
				segments.Sort ((x, y) => x.Offset.CompareTo (y.Offset));
				var link = new TextLink ("name");
				segments.ForEach (s => link.AddLink (s));
				var links = new List<TextLink> ();
				links.Add (link);
				var tle = new TextLinkEditMode (ctx.Document.Editor.Parent, 0, links);
				tle.SetCaretPosition = false;
				if (tle.ShouldStartTextLinkMode) {
					tle.OldMode = ctx.Document.Editor.CurrentMode;
					tle.StartMode ();
					ctx.Document.Editor.CurrentMode = tle;
				}
			}
			async Task TryStartRenameSession (Workspace workspace, Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
			{
				var changedDocuments = GetChangedDocuments (newSolution, oldSolution);
				foreach (var documentId in changedDocuments) {
					var document = newSolution.GetDocument (documentId);
					var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
					SyntaxToken? renameTokenOpt = root.GetAnnotatedNodesAndTokens (RenameAnnotation.Kind)
													  .Where (s => s.IsToken)
													  .Select (s => s.AsToken ())
													  .Cast<SyntaxToken?> ()
													  .FirstOrDefault ();
					if (renameTokenOpt.HasValue) {
						var latestDocument = workspace.CurrentSolution.GetDocument (documentId);
						var latestModel = await latestDocument.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
						var latestRoot = await latestDocument.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
						await Runtime.RunInMainThread (async delegate {
							try {
								var node = latestRoot.FindNode (renameTokenOpt.Value.Parent.Span, false, false);
								if (node == null)
									return;
								var info = latestModel.GetSymbolInfo (node);
								var sym = info.Symbol ?? latestModel.GetDeclaredSymbol (node);
								if (sym != null) {
									await new MonoDevelop.Refactoring.Rename.RenameRefactoring ().Rename (sym);
								} else {
									var links = new List<TextLink> ();
									var link = new TextLink ("name");
									link.AddLink (new TextSegment (node.Span.Start, node.Span.Length));
									links.Add (link);
									var oldVersion = editor.Version;
									editor.StartTextLinkMode (new TextLinkModeOptions (links, (arg) => {
										//If user cancel renaming revert changes
										if (!arg.Success) {
											var textChanges = editor.Version.GetChangesTo (oldVersion).ToList ();
											foreach (var v in textChanges) {
												editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
											}
										}
									}));
								}
							} catch (Exception ex) {
								LoggingService.LogError ("Error while renaming " + renameTokenOpt.Value.Parent, ex);
							}
						});
						return;
					}
				}
			}
Exemplo n.º 27
0
		public TemplateResult FillVariables (TemplateContext context)
		{
			ExpansionObject expansion = CodeTemplateService.GetExpansionObject (this);
			TemplateResult result = new TemplateResult ();
			StringBuilder sb = new StringBuilder ();
			int lastOffset = 0;
			string code = context.Document.Editor.FormatString (context.InsertPosition, context.TemplateCode);
			
			result.TextLinks = new List<TextLink> ();
			foreach (Match match in variableRegEx.Matches (code)) {
				string name = match.Groups[1].Value;
				sb.Append (code.Substring (lastOffset, match.Index - lastOffset));
				lastOffset = match.Index + match.Length;
				if (string.IsNullOrEmpty (name)) { // $$ is interpreted as $
					sb.Append ("$");
				} else if (name == "end") {
					result.CaretEndOffset = sb.Length;
				} else if (name == "selected") {
					if (!string.IsNullOrEmpty (context.SelectedText)) {
						string indent = GetIndent (sb);
						string selection = Reindent (context.SelectedText, indent);
						sb.Append (selection);
					}
				}
				if (!variableDecarations.ContainsKey (name))
					continue;
				TextLink link = result.TextLinks.Find (l => l.Name == name);
				bool isNew = link == null;
				if (isNew) {
					link         = new TextLink (name);
					if (!string.IsNullOrEmpty (variableDecarations[name].ToolTip))
						link.Tooltip = GettextCatalog.GetString (variableDecarations[name].ToolTip);
					link.Values  = new CodeTemplateListDataProvider (variableDecarations[name].Values);
					if (!string.IsNullOrEmpty (variableDecarations[name].Function)) {
						link.Values  = expansion.RunFunction (context, null, variableDecarations[name].Function);
					}
					result.TextLinks.Add (link);
				}
				link.IsEditable = variableDecarations[name].IsEditable;
				link.IsIdentifier = variableDecarations[name].IsIdentifier;
				if (!string.IsNullOrEmpty (variableDecarations[name].Function)) {
					IListDataProvider<string> functionResult = expansion.RunFunction (context, null, variableDecarations[name].Function);
					if (functionResult != null && functionResult.Count > 0) {
						string s = (string)functionResult[functionResult.Count - 1];
						if (s == null) {
							if (variableDecarations.ContainsKey (name)) 
								s = variableDecarations[name].Default;
						}
						if (s != null) {
							link.AddLink (new Segment (sb.Length, s.Length));
							if (isNew) {
								link.GetStringFunc = delegate (Func<string, string> callback) {
									return expansion.RunFunction (context, callback, variableDecarations[name].Function);
								};
							}
							sb.Append (s);
						}
					} else {
						AddDefaultValue (sb, link, name);
					}
				} else  {
					AddDefaultValue (sb, link, name);
				}
			}
			sb.Append (code.Substring (lastOffset, code.Length - lastOffset));
			result.Code = sb.ToString ();
			return result;
		}
Exemplo n.º 28
0
        public void LoopThroughJobVacancies(SimpleHtmlWriter htmlWriter)
        {
            // Find the list of pages at the table foot.
            IReadOnlyCollection <IWebElement> resultPages = this.table.FindElements(By.CssSelector("tfoot table td"));
            int numOfPages = resultPages.Count;

            if (resultPages.Count == 0)
            {
                numOfPages = 1;
                Console.WriteLine("This 'Job Vacancy Search Results' has only 1 page.");
            }
            else
            {
                numOfPages = resultPages.Count;
                Console.WriteLine("This 'Job Vacancy Search Results' has " + numOfPages + " pages.");
            }

            for (int pageIdx = 0; pageIdx < numOfPages; pageIdx++)
            {
                if (pageIdx > 0)
                {
                    Console.WriteLine("Clicking link to page " + (pageIdx + 1));
                    try
                    {
                        GotoPage(pageIdx);
                    }
                    catch (NoSuchElementException e)
                    {
                        Console.WriteLine("Failed to go into page " + (pageIdx + 1) + " due to exception; skip this page.");
                        Console.WriteLine(e.ToString());
                        Console.Write(e.StackTrace);
                        Console.WriteLine();
                    }
                }
                Console.WriteLine();
                Console.WriteLine("Start parsing page " + (pageIdx + 1));
                int rowCount = this.table.RowCount;
                Console.WriteLine("Page " + (pageIdx + 1) + " lists " + rowCount + " vacancies.");

                for (int rowIdx = 0; rowIdx < rowCount; rowIdx++)
                {
                    try
                    {
                        var    textList        = this.table.GetRow(rowIdx).CellTexts;
                        string jobTitle        = textList[0];
                        string salary          = textList[1];
                        string jobType         = textList[2];
                        string deptAndLocation = textList[3];
                        string postedDate      = textList[4];
                        string deadline        = textList[5];

                        Console.WriteLine("Clicking vacancy " + (rowIdx + 1) + " on page " + (pageIdx + 1));
                        string   postingLinkId = "cphMainContent_grdVacancy_hypJobTitle_" + rowIdx;
                        TextLink postingLink   = new TextLink(By.Id(postingLinkId));
                        postingLink.Click();

                        JobPostPage jobPostPage = new JobPostPage();
                        jobPostPage.WaitUntilAvailable();

                        var details = jobPostPage.GetDetails(jobTitle);
                        jobTitle = details.Item1;
                        string         jobCtrlNumber = details.Item2;
                        IList <string> jobDescTexts  = details.Item3;

                        Console.WriteLine("Writing " + jobCtrlNumber + ": " + jobTitle);
                        var basicInfo = new List <string> {
                            jobCtrlNumber, jobTitle, salary, jobType, deptAndLocation, postedDate, deadline
                        };
                        htmlWriter.WriteTableRow(basicInfo);

                        htmlWriter.Write("<tr><td colspan=\"" + basicInfo.Count + "\">");
                        foreach (string desc in jobDescTexts)
                        {
                            htmlWriter.WriteLine("<p>" + desc + "</p>");
                        }
                        htmlWriter.WriteLine("</td></tr>");

                        Console.WriteLine("Navigate back to the previous (Job Vacancy Search Results) page");
                        Browser.NavigateBack();
                        WaitUntilAvailable();
                    }
                    catch (NoSuchElementException e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.Write(e.StackTrace);
                        //browser.takeScreenShot();
                    }
                }
            }
        }
		public override void Link (Action continuation, params AstNode[] nodes)
		{
			var segments = new List<TextSegment> (nodes.Select (node => new TextSegment (GetSegment (node))).OrderBy (s => s.Offset));
			
			var link = new TextLink ("name");
			segments.ForEach (s => link.AddLink (s));
			var links = new List<TextLink> ();
			links.Add (link);
			var tle = new TextLinkEditMode (context.TextEditor.Parent, 0, links);
			tle.SetCaretPosition = false;
			if (tle.ShouldStartTextLinkMode) {
				operationsRunning++;
				context.TextEditor.Caret.Offset = segments [0].EndOffset;
				tle.OldMode = context.TextEditor.CurrentMode;
				tle.Cancel += (sender, e) => Rollback ();
				tle.Exited += (sender, e) => DisposeOnClose (); 
				tle.StartMode ();
				context.TextEditor.CurrentMode = tle;
				if (IdeApp.Workbench.ActiveDocument != null)
					IdeApp.Workbench.ActiveDocument.ReparseDocument ();
			}
			if (continuation != null)
				continuation ();
		}
Exemplo n.º 30
0
		void AddDefaultValue (StringBuilder sb, TextLink link, string name)
		{
			if (string.IsNullOrEmpty (variableDecarations [name].Default))
				return;
			link.AddLink (new TextSegment (sb.Length, variableDecarations[name].Default.Length));
			sb.Append (variableDecarations[name].Default);
		}
Exemplo n.º 31
0
        public TemplateResult FillVariables(TemplateContext context)
        {
            var    expansion  = CodeTemplateService.GetExpansionObject(this);
            var    result     = new TemplateResult();
            var    sb         = StringBuilderCache.Allocate();
            int    lastOffset = 0;
            string code       = context.Editor.FormatString(context.InsertPosition, context.TemplateCode);

            result.TextLinks = new List <TextLink> ();
            foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups [1].Value;
                sb.Append(code, lastOffset, match.Index - lastOffset);
                lastOffset = match.Index + match.Length;
                if (string.IsNullOrEmpty(name))                    // $$ is interpreted as $
                {
                    sb.Append("$");
                }
                else
                {
                    switch (name)
                    {
                    case "end":
                        result.CaretEndOffset = sb.Length;
                        break;

                    case "selected":
                        if (!string.IsNullOrEmpty(context.SelectedText))
                        {
                            string indent    = GetIndent(sb);
                            string selection = Reindent(context.SelectedText, indent);
                            sb.Append(selection);
                        }
                        break;

                    case "TM_CURRENT_LINE":
                        sb.Append(context.Editor.CaretLine);
                        break;

                    case "TM_CURRENT_WORD":
                        sb.Append("");
                        break;

                    case "TM_FILENAME":
                        sb.Append(context.Editor.FileName);
                        break;

                    case "TM_FILEPATH":
                        sb.Append(Path.GetDirectoryName(context.Editor.FileName));
                        break;

                    case "TM_FULLNAME":
                        sb.Append(AuthorInformation.Default.Name);
                        break;

                    case "TM_LINE_INDEX":
                        sb.Append(context.Editor.CaretColumn - 1);
                        break;

                    case "TM_LINE_NUMBER":
                        sb.Append(context.Editor.CaretLine);
                        break;

                    case "TM_SOFT_TABS":
                        sb.Append(context.Editor.Options.TabsToSpaces ? "YES" : "NO");                          // Note: these strings need no translation.
                        break;

                    case "TM_TAB_SIZE":
                        sb.Append(context.Editor.Options.TabSize);
                        break;
                    }
                }
                if (!variableDecarations.ContainsKey(name))
                {
                    continue;
                }
                var  link  = result.TextLinks.Find(l => l.Name == name);
                bool isNew = link == null;
                if (isNew)
                {
                    link = new TextLink(name);
                    if (!string.IsNullOrEmpty(variableDecarations [name].ToolTip))
                    {
                        link.Tooltip = GettextCatalog.GetString(variableDecarations [name].ToolTip);
                    }
                    link.Values = new CodeTemplateListDataProvider(variableDecarations [name].Values);
                    if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                    {
                        link.Values = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    }
                    result.TextLinks.Add(link);
                }
                link.IsEditable   = variableDecarations [name].IsEditable;
                link.IsIdentifier = variableDecarations [name].IsIdentifier;
                if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                {
                    var functionResult = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    if (functionResult != null && functionResult.Count > 0)
                    {
                        string s = (string)functionResult [functionResult.Count - 1];
                        if (s == null)
                        {
                            if (variableDecarations.ContainsKey(name))
                            {
                                s = variableDecarations [name].Default;
                            }
                        }
                        if (s != null)
                        {
                            link.AddLink(new TextSegment(sb.Length, s.Length));
                            if (isNew)
                            {
                                link.GetStringFunc = delegate(Func <string, string> callback) {
                                    return(expansion.RunFunction(context, callback, variableDecarations [name].Function));
                                };
                            }
                            sb.Append(s);
                        }
                    }
                    else
                    {
                        AddDefaultValue(sb, link, name);
                    }
                }
                else
                {
                    AddDefaultValue(sb, link, name);
                }
            }
            sb.Append(code, lastOffset, code.Length - lastOffset);

            // format & indent template code
            var data = TextEditorFactory.CreateNewDocument();

            data.Text         = StringBuilderCache.ReturnAndFree(sb);
            data.TextChanged += delegate(object sender, MonoDevelop.Core.Text.TextChangeEventArgs e) {
                for (int i = 0; i < e.TextChanges.Count; ++i)
                {
                    var change = e.TextChanges[i];
                    int delta  = change.InsertionLength - change.RemovalLength;

                    foreach (var link in result.TextLinks)
                    {
                        link.Links = link.Links.AdjustSegments(e).ToList();
                    }
                    if (result.CaretEndOffset > change.Offset)
                    {
                        result.CaretEndOffset += delta;
                    }
                }
            };

            IndentCode(data, context.LineIndent);
            result.Code = data.Text;
            return(result);
        }
Exemplo n.º 32
0
        public async Task Rename(ISymbol symbol)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
            var ws       = TypeSystemService.GetWorkspace(solution);

            var currentSolution = ws.CurrentSolution;
            var cts             = new CancellationTokenSource();
            var newSolution     = await MessageService.ExecuteTaskAndShowWaitDialog(Task.Run(() => Renamer.RenameSymbolAsync(currentSolution, symbol, "_" + symbol.Name + "_", ws.Options, cts.Token)), GettextCatalog.GetString("Looking for all references"), cts);

            var projectChanges   = currentSolution.GetChanges(newSolution).GetProjectChanges().ToList();
            var changedDocuments = new HashSet <string> ();

            foreach (var change in projectChanges)
            {
                foreach (var changedDoc in change.GetChangedDocuments())
                {
                    changedDocuments.Add(ws.CurrentSolution.GetDocument(changedDoc).FilePath);
                }
            }

            if (changedDocuments.Count > 1)
            {
                using (var dlg = new RenameItemDialog(symbol, this))
                    MessageService.ShowCustomDialog(dlg);
                return;
            }

            var projectChange = projectChanges [0];
            var changes       = projectChange.GetChangedDocuments().ToList();

            if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType)
            {
                using (var dlg = new RenameItemDialog(symbol, this))
                    MessageService.ShowCustomDialog(dlg);
                return;
            }
            var doc    = IdeApp.Workbench.ActiveDocument;
            var editor = doc.Editor;

            var links = new List <TextLink> ();
            var link  = new TextLink("name");

            var cd         = changes [0];
            var oldDoc     = projectChange.OldProject.GetDocument(cd);
            var newDoc     = projectChange.NewProject.GetDocument(cd);
            var oldVersion = editor.Version;

            foreach (var textChange in await oldDoc.GetTextChangesAsync(newDoc))
            {
                var segment = new TextSegment(textChange.Span.Start, textChange.Span.Length);
                if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset)
                {
                    link.Links.Insert(0, segment);
                }
                else
                {
                    link.AddLink(segment);
                }
            }

            links.Add(link);
            editor.StartTextLinkMode(new TextLinkModeOptions(links, (arg) => {
                //If user cancel renaming revert changes
                if (!arg.Success)
                {
                    var textChanges = editor.Version.GetChangesTo(oldVersion).ToList();
                    foreach (var v in textChanges)
                    {
                        editor.ReplaceText(v.Offset, v.RemovalLength, v.InsertedText);
                    }
                }
            }));
        }
		public override void InsertCompletionText (CompletionListWindow window, ref KeyActions ka, Gdk.Key closeChar, char keyChar, Gdk.ModifierType modifier)
		{
			// insert add/remove event handler code after +=/-=
			editor.Replace (initialOffset, editor.Caret.Offset - initialOffset, this.DisplayText + (AddSemicolon ? ";" : ""));
			
			// Search opening bracket of member
			int pos = callingMember != null ? editor.Document.LocationToOffset (callingMember.BodyRegion.BeginLine, callingMember.BodyRegion.BeginColumn) : initialOffset;
			while (pos < editor.Document.TextLength && editor.Document.GetCharAt (pos) != '{') {
				pos++;
			}
			
			// Search closing bracket of member
			pos = editor.Document.GetMatchingBracketOffset (pos) + 1;
			
			pos = Math.Max (0, Math.Min (pos, editor.Document.TextLength - 1));
			
			// Insert new event handler after closing bracket
			var line = callingMember != null ? editor.Document.GetLine (callingMember.Region.BeginLine) : editor.Document.GetLineByOffset (initialOffset);
			string indent = line.GetIndentation (editor.Document);
			
			StringBuilder sb = new StringBuilder ();
			sb.Append (editor.EolMarker);
			sb.Append (editor.EolMarker);
			sb.Append (indent);
			if (callingMember != null && callingMember.IsStatic)
				sb.Append ("static ");
			sb.Append ("void ");
			int pos2 = sb.Length;
			sb.Append (this.DisplayText);
			sb.Append (' ');
			sb.Append (this.parameterList);
			sb.Append (editor.EolMarker);
			sb.Append (indent);
			sb.Append ("{");
			sb.Append (editor.EolMarker);
			sb.Append (indent);
			sb.Append (editor.Options.IndentationString);
			int cursorPos = pos + sb.Length;
			sb.Append (editor.EolMarker);
			sb.Append (indent);
			sb.Append ("}");
			editor.Insert (pos, sb.ToString ());
			editor.Caret.Offset = cursorPos;
			
			// start text link mode after insert
			List<TextLink> links = new List<TextLink> ();
			TextLink link = new TextLink ("name");
			
			link.AddLink (new TextSegment (0, this.DisplayText.Length));
			link.AddLink (new TextSegment (pos - initialOffset + pos2, this.DisplayText.Length));
			links.Add (link);
			
			var tle = new TextLinkEditMode (editor.Parent, initialOffset, links);
			tle.TextLinkMode = TextLinkMode.EditIdentifier;
			tle.SetCaretPosition = true;
			tle.SelectPrimaryLink = true;
			tle.OldMode = editor.CurrentMode;
			tle.StartMode ();
			editor.CurrentMode = tle;
		}
Exemplo n.º 34
0
		public TemplateResult FillVariables (TemplateContext context)
		{
			ExpansionObject expansion = CodeTemplateService.GetExpansionObject (this);
			TemplateResult result = new TemplateResult ();
			StringBuilder sb = new StringBuilder ();
			int lastOffset = 0;
			string code = context.Document.Editor.FormatString (context.InsertPosition, context.TemplateCode);
			result.TextLinks = new List<TextLink> ();
			foreach (Match match in variableRegEx.Matches (code)) {
				string name = match.Groups [1].Value;
				sb.Append (code.Substring (lastOffset, match.Index - lastOffset));
				lastOffset = match.Index + match.Length;
				if (string.IsNullOrEmpty (name)) { // $$ is interpreted as $
					sb.Append ("$");
				} else if (name == "end") {
					result.CaretEndOffset = sb.Length;
				} else if (name == "selected") {
					if (!string.IsNullOrEmpty (context.SelectedText)) {
						string indent = GetIndent (sb);
						string selection = Reindent (context.SelectedText, indent);
						sb.Append (selection);
					}
				}
				if (!variableDecarations.ContainsKey (name))
					continue;
				TextLink link = result.TextLinks.Find (l => l.Name == name);
				bool isNew = link == null;
				if (isNew) {
					link = new TextLink (name);
					if (!string.IsNullOrEmpty (variableDecarations [name].ToolTip))
						link.Tooltip = GettextCatalog.GetString (variableDecarations [name].ToolTip);
					link.Values = new CodeTemplateListDataProvider (variableDecarations [name].Values);
					if (!string.IsNullOrEmpty (variableDecarations [name].Function)) {
						link.Values = expansion.RunFunction (context, null, variableDecarations [name].Function);
					}
					result.TextLinks.Add (link);
				}
				link.IsEditable = variableDecarations [name].IsEditable;
				link.IsIdentifier = variableDecarations [name].IsIdentifier;
				if (!string.IsNullOrEmpty (variableDecarations [name].Function)) {
					IListDataProvider<string > functionResult = expansion.RunFunction (context, null, variableDecarations [name].Function);
					if (functionResult != null && functionResult.Count > 0) {
						string s = (string)functionResult [functionResult.Count - 1];
						if (s == null) {
							if (variableDecarations.ContainsKey (name)) 
								s = variableDecarations [name].Default;
						}
						if (s != null) {
							link.AddLink (new Segment (sb.Length, s.Length));
							if (isNew) {
								link.GetStringFunc = delegate (Func<string, string> callback) {
									return expansion.RunFunction (context, callback, variableDecarations [name].Function);
								};
							}
							sb.Append (s);
						}
					} else {
						AddDefaultValue (sb, link, name);
					}
				} else {
					AddDefaultValue (sb, link, name);
				}
			}
			sb.Append (code.Substring (lastOffset, code.Length - lastOffset));
			
			// format & indent template code
			TextEditorData data = new TextEditorData ();
			data.Text = sb.ToString ();
			data.Document.TextReplaced += delegate(object sender, ReplaceEventArgs e) {
				int delta = -e.Count + (e.Value != null ? e.Value.Length : 0);
				foreach (var link in result.TextLinks) {
					foreach (var segment in link.Links) {
						if (segment.Offset > e.Offset) {
							segment.Offset += delta;
						}
					}
				}
				if (result.CaretEndOffset > e.Offset)
					result.CaretEndOffset += delta;
			};
			
			var formatter = CodeFormatterService.GetFormatter (context.Document.Editor.Document.MimeType);
			if (formatter != null && context.Document.HasProject) {
				formatter.OnTheFlyFormat (context.Document.Project.Policies, data, 0, data.Length);
			}
			
			IndentCode (data, context.LineIndent);
			result.Code = data.Text;
			data.Dispose ();
			return result;
		}
Exemplo n.º 35
0
        public async Task Rename(ISymbol symbol)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
            var ws       = TypeSystemService.GetWorkspace(solution);

            var currentSolution = ws.CurrentSolution;
            var cts             = new CancellationTokenSource();
            var newSolution     = await MessageService.ExecuteTaskAndShowWaitDialog(Task.Run(() => Renamer.RenameSymbolAsync(currentSolution, symbol, "_" + symbol.Name + "_", ws.Options, cts.Token)), GettextCatalog.GetString("Looking for all references"), cts);

            var projectChanges   = currentSolution.GetChanges(newSolution).GetProjectChanges().ToList();
            var changedDocuments = new HashSet <string> ();

            foreach (var change in projectChanges)
            {
                foreach (var changedDoc in change.GetChangedDocuments())
                {
                    changedDocuments.Add(ws.CurrentSolution.GetDocument(changedDoc).FilePath);
                }
            }

            if (changedDocuments.Count > 1)
            {
                using (var dlg = new RenameItemDialog(symbol, this))
                    MessageService.ShowCustomDialog(dlg);
                return;
            }

            var projectChange = projectChanges [0];
            var changes       = projectChange.GetChangedDocuments().ToList();

            if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType)
            {
                using (var dlg = new RenameItemDialog(symbol, this))
                    MessageService.ShowCustomDialog(dlg);
                return;
            }
            var doc        = IdeApp.Workbench.ActiveDocument;
            var editor     = doc.Editor;
            var oldVersion = editor.Version;

            var links = new List <TextLink> ();
            var link  = new TextLink("name");

            var documents = ImmutableHashSet.Create(doc.AnalysisDocument);

            foreach (var loc in symbol.Locations)
            {
                if (loc.IsInSource && FilePath.PathComparer.Equals(loc.SourceTree.FilePath, doc.FileName))
                {
                    link.AddLink(new TextSegment(loc.SourceSpan.Start, loc.SourceSpan.Length));
                }
            }

            foreach (var mref in await SymbolFinder.FindReferencesAsync(symbol, TypeSystemService.Workspace.CurrentSolution, documents, default(CancellationToken)))
            {
                foreach (var loc in mref.Locations)
                {
                    TextSpan span   = loc.Location.SourceSpan;
                    var      root   = loc.Location.SourceTree.GetRoot();
                    var      node   = root.FindNode(loc.Location.SourceSpan);
                    var      trivia = root.FindTrivia(loc.Location.SourceSpan.Start);
                    if (!trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia))
                    {
                        span = node.Span;
                    }
                    if (span.Start != loc.Location.SourceSpan.Start)
                    {
                        span = loc.Location.SourceSpan;
                    }
                    var segment = new TextSegment(span.Start, span.Length);
                    if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset)
                    {
                        link.Links.Insert(0, segment);
                    }
                    else
                    {
                        link.AddLink(segment);
                    }
                }
            }
            links.Add(link);

            editor.StartTextLinkMode(new TextLinkModeOptions(links, (arg) => {
                //If user cancel renaming revert changes
                if (!arg.Success)
                {
                    var textChanges = editor.Version.GetChangesTo(oldVersion).ToList();
                    foreach (var v in textChanges)
                    {
                        editor.ReplaceText(v.Offset, v.RemovalLength, v.InsertedText);
                    }
                }
            })
            {
                TextLinkPurpose = TextLinkPurpose.Rename
            });
        }
Exemplo n.º 36
0
		public void Rename (ISymbol symbol)
		{

			var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
			var ws = TypeSystemService.GetWorkspace (solution);

			var currentSolution = ws.CurrentSolution;
			var newSolution = Renamer.RenameSymbolAsync (currentSolution, symbol, "_" + symbol.Name + "_", ws.Options).Result;
			var projectChanges = currentSolution.GetChanges (newSolution).GetProjectChanges ().ToList ();

			if (projectChanges.Count != 1) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}

			var projectChange = projectChanges [0];
			var changes = projectChange.GetChangedDocuments ().ToList ();
			if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}
			var doc = IdeApp.Workbench.ActiveDocument;
			var editor = doc.Editor;
			
			var links = new List<TextLink> ();
			var link = new TextLink ("name");

			var cd = changes [0];
			var oldDoc = projectChange.OldProject.GetDocument (cd);
			var newDoc = projectChange.NewProject.GetDocument (cd);
			var oldVersion = editor.Version;
			foreach (var textChange in oldDoc.GetTextChangesAsync (newDoc).Result) {
				var segment = new TextSegment (textChange.Span.Start, textChange.Span.Length);
				if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset) {
					link.Links.Insert (0, segment); 
				} else {
					link.AddLink (segment);
				}
			}
			
			links.Add (link);
			editor.StartTextLinkMode (new TextLinkModeOptions (links, args => {
				if (!args.Success)
					return;

				var version = editor.Version;
				var span = symbol.Locations.First ().SourceSpan;
				var newName = link.CurrentText;
				var textChanges = version.GetChangesTo (oldVersion).ToList ();
				foreach (var v in textChanges) {
					editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
				}
				var parsedDocument = doc.UpdateParseDocument ().Result;
				if (parsedDocument == null) {
					Rollback (editor, textChanges);
					return;
				}
				var model = parsedDocument.GetAst<SemanticModel> ();
				if (model == null) {
					Rollback (editor, textChanges);
					return;
				}
				var node = model.SyntaxTree.GetRoot ().FindNode (span);
				if (node == null) {
					Rollback (editor, textChanges);
					return;
				}
				var sym = model.GetDeclaredSymbol (node);
				if (sym == null) {
					Rollback (editor, textChanges);
					return;
				}
				if (!Rename (sym, newName))
					Rollback (editor, textChanges);
			}));
		}
Exemplo n.º 37
0
        public void Rename(ISymbol symbol)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
            var ws       = TypeSystemService.GetWorkspace(solution);

            var currentSolution = ws.CurrentSolution;
            var newSolution     = Renamer.RenameSymbolAsync(currentSolution, symbol, "_" + symbol.Name + "_", ws.Options).Result;
            var projectChanges  = currentSolution.GetChanges(newSolution).GetProjectChanges().ToList();

            if (projectChanges.Count != 1)
            {
                using (var dlg = new RenameItemDialog(symbol, this))
                    MessageService.ShowCustomDialog(dlg);
                return;
            }

            var projectChange = projectChanges [0];
            var changes       = projectChange.GetChangedDocuments().ToList();

            if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType)
            {
                using (var dlg = new RenameItemDialog(symbol, this))
                    MessageService.ShowCustomDialog(dlg);
                return;
            }
            var doc    = IdeApp.Workbench.ActiveDocument;
            var editor = doc.Editor;

            var links = new List <TextLink> ();
            var link  = new TextLink("name");

            var cd         = changes [0];
            var oldDoc     = projectChange.OldProject.GetDocument(cd);
            var newDoc     = projectChange.NewProject.GetDocument(cd);
            var oldVersion = editor.Version;

            foreach (var textChange in oldDoc.GetTextChangesAsync(newDoc).Result)
            {
                var segment = new TextSegment(textChange.Span.Start, textChange.Span.Length);
                if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset)
                {
                    link.Links.Insert(0, segment);
                }
                else
                {
                    link.AddLink(segment);
                }
            }

            links.Add(link);
            editor.StartTextLinkMode(new TextLinkModeOptions(links, args => {
                if (!args.Success)
                {
                    return;
                }

                var version     = editor.Version;
                var span        = symbol.Locations.First().SourceSpan;
                var newName     = link.CurrentText;
                var textChanges = version.GetChangesTo(oldVersion).ToList();
                foreach (var v in textChanges)
                {
                    editor.ReplaceText(v.Offset, v.RemovalLength, v.InsertedText);
                }
                var parsedDocument = doc.UpdateParseDocument().Result;
                if (parsedDocument == null)
                {
                    Rollback(editor, textChanges);
                    return;
                }
                var model = parsedDocument.GetAst <SemanticModel> ();
                if (model == null)
                {
                    Rollback(editor, textChanges);
                    return;
                }
                var node = model.SyntaxTree.GetRoot().FindNode(span);
                if (node == null)
                {
                    Rollback(editor, textChanges);
                    return;
                }
                var sym = model.GetDeclaredSymbol(node);
                if (sym == null)
                {
                    Rollback(editor, textChanges);
                    return;
                }
                if (!Rename(sym, newName))
                {
                    Rollback(editor, textChanges);
                }
            }));
        }
Exemplo n.º 38
0
            async Task TryStartRenameSession(Workspace workspace, Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
            {
                var changedDocuments = GetChangedDocuments(newSolution, oldSolution);

                foreach (var documentId in changedDocuments)
                {
                    var document = newSolution.GetDocument(documentId);
                    var root     = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                    SyntaxToken?renameTokenOpt = root.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind)
                                                 .Where(s => s.IsToken)
                                                 .Select(s => s.AsToken())
                                                 .Cast <SyntaxToken?> ()
                                                 .FirstOrDefault();
                    if (renameTokenOpt.HasValue)
                    {
                        var latestDocument = workspace.CurrentSolution.GetDocument(documentId);
                        var latestModel    = await latestDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                        var latestRoot = await latestDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                        await Runtime.RunInMainThread(async delegate {
                            try {
                                var node = latestRoot.FindNode(renameTokenOpt.Value.Parent.Span, false, false);
                                if (node == null)
                                {
                                    return;
                                }
                                var info = latestModel.GetSymbolInfo(node);
                                var sym  = info.Symbol ?? latestModel.GetDeclaredSymbol(node);
                                if (sym != null)
                                {
                                    await new Refactoring.Rename.RenameRefactoring().Rename(sym);
                                }
                                else
                                {
                                    var links = new List <TextLink> ();
                                    var link  = new TextLink("name");
                                    link.AddLink(new TextSegment(node.Span.Start, node.Span.Length));
                                    links.Add(link);
                                    var oldVersion = editor.Version;
                                    editor.StartTextLinkMode(new TextLinkModeOptions(links, (arg) => {
                                        //If user cancel renaming revert changes
                                        if (!arg.Success)
                                        {
                                            var textChanges = editor.Version.GetChangesTo(oldVersion).ToList();
                                            foreach (var change in textChanges)
                                            {
                                                foreach (var v in change.TextChanges.Reverse())
                                                {
                                                    editor.ReplaceText(v.Offset, v.RemovalLength, v.InsertedText);
                                                }
                                            }
                                        }
                                    })
                                    {
                                        TextLinkPurpose = TextLinkPurpose.Rename
                                    });
                                }
                            } catch (Exception ex) {
                                LoggingService.LogError("Error while renaming " + renameTokenOpt.Value.Parent, ex);
                            }
                        });

                        return;
                    }
                }
            }
Exemplo n.º 39
0
		public TemplateResult FillVariables (TemplateContext context)
		{
			var expansion = CodeTemplateService.GetExpansionObject (this);
			var result = new TemplateResult ();
			var sb = new StringBuilder ();
			int lastOffset = 0;
			string code = context.Editor.FormatString (context.InsertPosition, context.TemplateCode);
			result.TextLinks = new List<TextLink> ();
			foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches (code)) {
				string name = match.Groups [1].Value;
				sb.Append (code.Substring (lastOffset, match.Index - lastOffset));
				lastOffset = match.Index + match.Length;
				if (string.IsNullOrEmpty (name)) { // $$ is interpreted as $
					sb.Append ("$");
				} else if (name == "end") {
					result.CaretEndOffset = sb.Length;
				} else if (name == "selected") {
					if (!string.IsNullOrEmpty (context.SelectedText)) {
						string indent = GetIndent (sb);
						string selection = Reindent (context.SelectedText, indent);
						sb.Append (selection);
					}
				}
				if (!variableDecarations.ContainsKey (name))
					continue;
				var link = result.TextLinks.Find (l => l.Name == name);
				bool isNew = link == null;
				if (isNew) {
					link = new TextLink (name);
					if (!string.IsNullOrEmpty (variableDecarations [name].ToolTip))
						link.Tooltip = GettextCatalog.GetString (variableDecarations [name].ToolTip);
					link.Values = new CodeTemplateListDataProvider (variableDecarations [name].Values);
					if (!string.IsNullOrEmpty (variableDecarations [name].Function)) {
						link.Values = expansion.RunFunction (context, null, variableDecarations [name].Function);
					}
					result.TextLinks.Add (link);
				}
				link.IsEditable = variableDecarations [name].IsEditable;
				link.IsIdentifier = variableDecarations [name].IsIdentifier;
				if (!string.IsNullOrEmpty (variableDecarations [name].Function)) {
					IListDataProvider<string > functionResult = expansion.RunFunction (context, null, variableDecarations [name].Function);
					if (functionResult != null && functionResult.Count > 0) {
						string s = (string)functionResult [functionResult.Count - 1];
						if (s == null) {
							if (variableDecarations.ContainsKey (name)) 
								s = variableDecarations [name].Default;
						}
						if (s != null) {
							link.AddLink (new TextSegment (sb.Length, s.Length));
							if (isNew) {
								link.GetStringFunc = delegate (Func<string, string> callback) {
									return expansion.RunFunction (context, callback, variableDecarations [name].Function);
								};
							}
							sb.Append (s);
						}
					} else {
						AddDefaultValue (sb, link, name);
					}
				} else {
					AddDefaultValue (sb, link, name);
				}
			}
			sb.Append (code.Substring (lastOffset, code.Length - lastOffset));
			
			// format & indent template code
			var data = TextEditorFactory.CreateNewDocument ();
			data.Text = sb.ToString ();
			data.TextChanged += delegate(object sender, MonoDevelop.Core.Text.TextChangeEventArgs e) {
				int delta = e.InsertionLength - e.RemovalLength;

				foreach (var link in result.TextLinks) {
					link.Links = link.Links.AdjustSegments (e).ToList ();
				}
				if (result.CaretEndOffset > e.Offset)
					result.CaretEndOffset += delta;
			};

			IndentCode (data, context.LineIndent);
			result.Code = data.Text;
			return result;
		}
		public override void InsertCompletionText (CompletionListWindow window)
		{
			// insert add/remove event handler code after +=/-=
			editor.Replace (initialOffset, editor.Caret.Offset - initialOffset, this.DisplayText + ";");
			
			// Search opening bracket of member
			int pos = callingMember != null ? editor.Document.LocationToOffset (callingMember.BodyRegion.Start.Line, callingMember.BodyRegion.Start.Column) : initialOffset;
			while (pos < editor.Document.Length && editor.Document.GetCharAt (pos) != '{') {
				pos++;
			}
			
			// Search closing bracket of member
			pos = editor.Document.GetMatchingBracketOffset (pos) + 1;
			
			pos = Math.Max (0, Math.Min (pos, editor.Document.Length - 1));
			
			// Insert new event handler after closing bracket
			string indent = editor.Document.GetLine (callingMember.Location.Line).GetIndentation (editor.Document);
			
			StringBuilder sb = new StringBuilder ();
			sb.Append (editor.EolMarker);
			sb.Append (editor.EolMarker);
			sb.Append (indent);
			if (callingMember.IsStatic)
				sb.Append ("static ");
			sb.Append ("void ");
			int pos2 = sb.Length;
			sb.Append (this.DisplayText);sb.Append (' ');sb.Append (this.parameterList);sb.Append (editor.EolMarker);
			sb.Append (indent);sb.Append ("{");sb.Append (editor.EolMarker);
			sb.Append (indent);sb.Append (TextEditorProperties.IndentString);
			int cursorPos = pos + sb.Length;
			sb.Append (editor.EolMarker);
			sb.Append (indent);sb.Append ("}");
			editor.Insert (pos, sb.ToString ());
			editor.Caret.Offset = cursorPos;
			
			// start text link mode after insert
			List<TextLink> links = new List<TextLink> ();
			TextLink link = new TextLink ("name");
			
			link.AddLink (new Segment (0, this.DisplayText.Length));
			link.AddLink (new Segment (pos - initialOffset + pos2, this.DisplayText.Length));
			links.Add (link);
			
			CompletionTextLinkMode tle = new CompletionTextLinkMode (editor.Parent, initialOffset, links);
			tle.TriggerCodeCompletion = false;
			tle.SetCaretPosition = true;
			tle.SelectPrimaryLink = true;
			tle.OldMode = editor.CurrentMode;
			tle.StartMode ();
			editor.CurrentMode = tle;
		}
		public void Rename (ISymbol symbol)
		{

			var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
			var ws = TypeSystemService.GetWorkspace (solution);

			var currentSolution = ws.CurrentSolution;
			var newSolution = Renamer.RenameSymbolAsync (currentSolution, symbol, "_" + symbol.Name + "_", ws.Options).Result;
			var projectChanges = currentSolution.GetChanges (newSolution).GetProjectChanges ().ToList ();
			var changedDocuments = new HashSet<string> ();
			foreach (var change in projectChanges)
				foreach (var changedDoc in change.GetChangedDocuments ()) {
					changedDocuments.Add (ws.CurrentSolution.GetDocument (changedDoc).FilePath);
				}
			if (changedDocuments.Count > 1) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}

			var projectChange = projectChanges [0];
			var changes = projectChange.GetChangedDocuments ().ToList ();
			if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}
			var doc = IdeApp.Workbench.ActiveDocument;
			var editor = doc.Editor;
			
			var links = new List<TextLink> ();
			var link = new TextLink ("name");

			var cd = changes [0];
			var oldDoc = projectChange.OldProject.GetDocument (cd);
			var newDoc = projectChange.NewProject.GetDocument (cd);
			var oldVersion = editor.Version;
			foreach (var textChange in oldDoc.GetTextChangesAsync (newDoc).Result) {
				var segment = new TextSegment (textChange.Span.Start, textChange.Span.Length);
				if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset) {
					link.Links.Insert (0, segment); 
				} else {
					link.AddLink (segment);
				}
			}

			links.Add (link);
			editor.StartTextLinkMode (new TextLinkModeOptions (links, (arg) => {
				//If user cancel renaming revert changes
				if (!arg.Success) {
					var textChanges = editor.Version.GetChangesTo (oldVersion).ToList ();
					foreach (var v in textChanges) {
						editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
					}
				}
			}));
		}
Exemplo n.º 42
0
        private void AddCommand(Panel workItemPanel)
        {
            if (workItemPanel == null)
                return;

            var separator = new Separator();
            separator.Style = (Style)workItemPanel.FindResource("VerticalSeparator");
            workItemPanel.Children.Add(separator);

            var textLink = new TextLink();
            textLink.Text = "Select last";
            textLink.ToolTip = "Select workitem associated with last changeset";
            textLink.Command = new RelayCommand(SetLastWorkItem);
            workItemPanel.Children.Add(textLink);
        }
		public override void Run (RefactoringOptions options)
		{
			if (options.SelectedItem is LocalVariable || options.SelectedItem is IParameter) {
				MemberReferenceCollection col = GetReferences (options);
				if (col == null)
					return;
				TextEditorData data = options.GetTextEditorData ();
				Mono.TextEditor.TextEditor editor = data.Parent;
				if (editor == null) {
					MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
					return;
				}

				
				List<TextLink> links = new List<TextLink> ();
				TextLink link = new TextLink ("name");
				int baseOffset = Int32.MaxValue;
				foreach (MemberReference r in col) {
					baseOffset = Math.Min (baseOffset, data.Document.LocationToOffset (r.Line - 1, r.Column - 1));
				}
				foreach (MemberReference r in col) {
					Segment segment = new Segment (data.Document.LocationToOffset (r.Line - 1, r.Column - 1) - baseOffset, r.Name.Length);
					if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) {
						link.Links.Insert (0, segment); 
					} else {
						link.AddLink (segment);
					}
				}
				
				links.Add (link);
				TextLinkEditMode tle = new TextLinkEditMode (editor, baseOffset, links);
				tle.SetCaretPosition = false;
				tle.SelectPrimaryLink = true;
				if (tle.ShouldStartTextLinkMode) {
					tle.OldMode = data.CurrentMode;
					tle.StartMode ();
					data.CurrentMode = tle;
				}
			} else {
				MessageService.ShowCustomDialog (new RenameItemDialog (options, this));
			}
		}
Exemplo n.º 44
0
		public override void Run (RefactoringOptions options)
		{
			base.Run (options);
			if (selectionEnd >= 0) {
				options.Document.Editor.Caret.Offset = selectionEnd;
				options.Document.Editor.SetSelection (selectionStart, selectionEnd);
			} else {
				TextEditorData data = options.GetTextEditorData ();
				Mono.TextEditor.TextEditor editor = data.Parent;
				TextLink link = new TextLink ("name");
				if (varName != null) {
					if (insertOffset >= 0) {
						link.AddLink (new Segment (insertOffset - selectionStart, varName.Length));
					} else {
						LoggingService.LogWarning ("insert offset not found.");
					}
					if (replaceOffset >= 0)
						link.AddLink (new Segment (replaceOffset - selectionStart, varName.Length));
				}
				List<TextLink> links = new List<TextLink> ();
				links.Add (link);
				TextLinkEditMode tle = new TextLinkEditMode (editor, selectionStart, links);
				tle.SetCaretPosition = false;
				if (tle.ShouldStartTextLinkMode) {
					tle.OldMode = data.CurrentMode;
					tle.StartMode ();
					data.CurrentMode = tle;
				}
			}
		}
Exemplo n.º 45
0
		public override void Link (params AstNode[] nodes)
		{
			var segments = new List<TextSegment> (nodes.Select (node => new TextSegment (GetSegment (node))).OrderBy (s => s.Offset));

			var link = new TextLink ("name");
			segments.ForEach (s => link.AddLink (s));
			var links = new List<TextLink> ();
			links.Add (link);
			var tle = new TextLinkEditMode (document.Editor.Parent, 0, links);
			tle.SetCaretPosition = false;
			if (tle.ShouldStartTextLinkMode) {
				document.Editor.Caret.Offset = segments [0].EndOffset;
				tle.OldMode = document.Editor.CurrentMode;
				tle.StartMode ();
				document.Editor.CurrentMode = tle;
			}
		}
Exemplo n.º 46
0
		public override Task Link (params AstNode[] nodes)
		{
			var tcs = new TaskCompletionSource<object> ();
			var segments = new List<TextSegment> (nodes.Select (node => new TextSegment (GetSegment (node))).OrderBy (s => s.Offset));
			
			var link = new TextLink ("name");
			segments.ForEach (s => link.AddLink (s));
			var links = new List<TextLink> ();
			links.Add (link);
			var tle = new TextLinkEditMode (document.Editor.Parent, 0, links);
			tle.SetCaretPosition = false;
			if (tle.ShouldStartTextLinkMode) {
				operationsRunning++;
				document.Editor.Caret.Offset = segments [0].EndOffset;
				tle.OldMode = document.Editor.CurrentMode;
				tle.Cancel += (sender, e) => Rollback ();
				tle.Exited += (sender, e) => DisposeOnClose (); 
				tle.StartMode ();
				document.Editor.CurrentMode = tle;
			}
			return tcs.Task;
		}
Exemplo n.º 47
0
        public override void Run(RefactoringOptions options)
        {
            if (options.SelectedItem is IVariable)
            {
                var field = options.SelectedItem as IField;
                if (field != null && (field.Accessibility != Accessibility.Private || field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Parts.Count > 1))
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                var par = options.SelectedItem as IParameter;
                if (par != null && par.Owner != null && (par.Owner.Accessibility != Accessibility.Private || par.Owner.DeclaringTypeDefinition != null && par.Owner.DeclaringTypeDefinition.Parts.Count > 1))
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                var col = ReferenceFinder.FindReferences(options.SelectedItem, true);
                if (col == null)
                {
                    return;
                }
                var data = options.Document != null?options.GetTextEditorData() : IdeApp.Workbench.ActiveDocument.Editor;

                var editor = data.Parent;
                if (editor == null)
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                var links      = new List <TextLink> ();
                var link       = new TextLink("name");
                int baseOffset = Int32.MaxValue;
                foreach (var r in col)
                {
                    baseOffset = Math.Min(baseOffset, r.Offset);
                }
                foreach (MemberReference r in col)
                {
                    var segment = new TextSegment(r.Offset - baseOffset, r.Length);
                    if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset)
                    {
                        link.Links.Insert(0, segment);
                    }
                    else
                    {
                        link.AddLink(segment);
                    }
                }

                links.Add(link);
                if (editor.CurrentMode is TextLinkEditMode)
                {
                    ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode();
                }
                TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links);
                tle.SetCaretPosition  = false;
                tle.SelectPrimaryLink = true;
                if (tle.ShouldStartTextLinkMode)
                {
                    var helpWindow = new TableLayoutModeHelpWindow();
                    helpWindow.TitleText = options.SelectedItem is IVariable?GettextCatalog.GetString("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString("<b>Parameter -- Renaming</b>");

                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>")));
                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Return</b>"), GettextCatalog.GetString("<b>Accept</b> this refactoring.")));
                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring.")));
                    tle.HelpWindow = helpWindow;
                    tle.Cancel    += delegate {
                        if (tle.HasChangedText)
                        {
                            editor.Document.Undo();
                        }
                    };
                    tle.OldMode = data.CurrentMode;
                    tle.StartMode();
                    data.CurrentMode = tle;
                }
            }
            else
            {
                MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
            }
        }
Exemplo n.º 48
0
		public override void Run (RefactoringOptions options)
		{
			if (options.SelectedItem is IVariable) {
				var field = options.SelectedItem as IField;
				if (field != null && (field.Accessibility != Accessibility.Private || field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Parts.Count > 1)) {
					using (var dlg = new RenameItemDialog (options, this))
						MessageService.ShowCustomDialog (dlg);
					return;
				}

				var par = options.SelectedItem as IParameter;
				if (par != null && par.Owner != null && (par.Owner.Accessibility != Accessibility.Private || par.Owner.DeclaringTypeDefinition != null && par.Owner.DeclaringTypeDefinition.Parts.Count > 1)) {
					using (var dlg = new RenameItemDialog (options, this))
						MessageService.ShowCustomDialog (dlg);
					return;
				}

				var col = ReferenceFinder.FindReferences (options.SelectedItem, true);
				if (col == null)
					return;
				var data = options.Document != null ? options.GetTextEditorData () : IdeApp.Workbench.ActiveDocument.Editor;
				var editor = data.Parent;
				if (editor == null) {
					using (var dlg = new RenameItemDialog (options, this))
						MessageService.ShowCustomDialog (dlg);
					return;
				}
				
				var links = new List<TextLink> ();
				var link = new TextLink ("name");
				int baseOffset = Int32.MaxValue;
				foreach (var r in col) {
					baseOffset = Math.Min (baseOffset, r.Offset);
				}
				foreach (MemberReference r in col) {
					var segment = new TextSegment (r.Offset - baseOffset, r.Length);
					if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset) {
						link.Links.Insert (0, segment); 
					} else {
						link.AddLink (segment);
					}
				}
				
				links.Add (link);
				if (editor.CurrentMode is TextLinkEditMode)
					((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode ();
				TextLinkEditMode tle = new TextLinkEditMode (editor, baseOffset, links);
				tle.SetCaretPosition = false;
				tle.SelectPrimaryLink = true;
				if (tle.ShouldStartTextLinkMode) {
					tle.Cancel += delegate {
						if (tle.HasChangedText)
							editor.Document.Undo ();
					};
					tle.OldMode = data.CurrentMode;
					tle.StartMode ();
					data.CurrentMode = tle;
				}
			} else {
				using (var dlg = new RenameItemDialog (options, this))
					MessageService.ShowCustomDialog (dlg);
			}
		}
Exemplo n.º 49
0
        public TemplateResult FillVariables(TemplateContext context)
        {
            var    expansion  = CodeTemplateService.GetExpansionObject(this);
            var    result     = new TemplateResult();
            var    sb         = new StringBuilder();
            int    lastOffset = 0;
            string code       = context.Editor.FormatString(context.InsertPosition, context.TemplateCode);

            result.TextLinks = new List <TextLink> ();
            foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups [1].Value;
                sb.Append(code, lastOffset, match.Index - lastOffset);
                lastOffset = match.Index + match.Length;
                if (string.IsNullOrEmpty(name))                    // $$ is interpreted as $
                {
                    sb.Append("$");
                }
                else if (name == "end")
                {
                    result.CaretEndOffset = sb.Length;
                }
                else if (name == "selected")
                {
                    if (!string.IsNullOrEmpty(context.SelectedText))
                    {
                        string indent    = GetIndent(sb);
                        string selection = Reindent(context.SelectedText, indent);
                        sb.Append(selection);
                    }
                }
                if (!variableDecarations.ContainsKey(name))
                {
                    continue;
                }
                var  link  = result.TextLinks.Find(l => l.Name == name);
                bool isNew = link == null;
                if (isNew)
                {
                    link = new TextLink(name);
                    if (!string.IsNullOrEmpty(variableDecarations [name].ToolTip))
                    {
                        link.Tooltip = GettextCatalog.GetString(variableDecarations [name].ToolTip);
                    }
                    link.Values = new CodeTemplateListDataProvider(variableDecarations [name].Values);
                    if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                    {
                        link.Values = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    }
                    result.TextLinks.Add(link);
                }
                link.IsEditable   = variableDecarations [name].IsEditable;
                link.IsIdentifier = variableDecarations [name].IsIdentifier;
                if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                {
                    var functionResult = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    if (functionResult != null && functionResult.Count > 0)
                    {
                        string s = (string)functionResult [functionResult.Count - 1];
                        if (s == null)
                        {
                            if (variableDecarations.ContainsKey(name))
                            {
                                s = variableDecarations [name].Default;
                            }
                        }
                        if (s != null)
                        {
                            link.AddLink(new TextSegment(sb.Length, s.Length));
                            if (isNew)
                            {
                                link.GetStringFunc = delegate(Func <string, string> callback) {
                                    return(expansion.RunFunction(context, callback, variableDecarations [name].Function));
                                };
                            }
                            sb.Append(s);
                        }
                    }
                    else
                    {
                        AddDefaultValue(sb, link, name);
                    }
                }
                else
                {
                    AddDefaultValue(sb, link, name);
                }
            }
            sb.Append(code, lastOffset, code.Length - lastOffset);

            // format & indent template code
            var data = TextEditorFactory.CreateNewDocument();

            data.Text         = sb.ToString();
            data.TextChanged += delegate(object sender, MonoDevelop.Core.Text.TextChangeEventArgs e) {
                int delta = e.InsertionLength - e.RemovalLength;

                foreach (var link in result.TextLinks)
                {
                    link.Links = link.Links.AdjustSegments(e).ToList();
                }
                if (result.CaretEndOffset > e.Offset)
                {
                    result.CaretEndOffset += delta;
                }
            };

            IndentCode(data, context.LineIndent);
            result.Code = data.Text;
            return(result);
        }
Exemplo n.º 50
0
        public TemplateResult FillVariables(TemplateContext context)
        {
            ExpansionObject expansion  = CodeTemplateService.GetExpansionObject(this);
            TemplateResult  result     = new TemplateResult();
            StringBuilder   sb         = new StringBuilder();
            int             lastOffset = 0;
            string          code       = context.Document.Editor.FormatString(context.InsertPosition, context.TemplateCode);

            result.TextLinks = new List <TextLink> ();
            foreach (Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups [1].Value;
                sb.Append(code.Substring(lastOffset, match.Index - lastOffset));
                lastOffset = match.Index + match.Length;
                if (string.IsNullOrEmpty(name))                    // $$ is interpreted as $
                {
                    sb.Append("$");
                }
                else if (name == "end")
                {
                    result.CaretEndOffset = sb.Length;
                }
                else if (name == "selected")
                {
                    if (!string.IsNullOrEmpty(context.SelectedText))
                    {
                        string indent    = GetIndent(sb);
                        string selection = Reindent(context.SelectedText, indent);
                        sb.Append(selection);
                    }
                }
                if (!variableDecarations.ContainsKey(name))
                {
                    continue;
                }
                TextLink link  = result.TextLinks.Find(l => l.Name == name);
                bool     isNew = link == null;
                if (isNew)
                {
                    link = new TextLink(name);
                    if (!string.IsNullOrEmpty(variableDecarations [name].ToolTip))
                    {
                        link.Tooltip = GettextCatalog.GetString(variableDecarations [name].ToolTip);
                    }
                    link.Values = new CodeTemplateListDataProvider(variableDecarations [name].Values);
                    if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                    {
                        link.Values = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    }
                    result.TextLinks.Add(link);
                }
                link.IsEditable   = variableDecarations [name].IsEditable;
                link.IsIdentifier = variableDecarations [name].IsIdentifier;
                if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                {
                    IListDataProvider <string> functionResult = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    if (functionResult != null && functionResult.Count > 0)
                    {
                        string s = (string)functionResult [functionResult.Count - 1];
                        if (s == null)
                        {
                            if (variableDecarations.ContainsKey(name))
                            {
                                s = variableDecarations [name].Default;
                            }
                        }
                        if (s != null)
                        {
                            link.AddLink(new Segment(sb.Length, s.Length));
                            if (isNew)
                            {
                                link.GetStringFunc = delegate(Func <string, string> callback) {
                                    return(expansion.RunFunction(context, callback, variableDecarations [name].Function));
                                };
                            }
                            sb.Append(s);
                        }
                    }
                    else
                    {
                        AddDefaultValue(sb, link, name);
                    }
                }
                else
                {
                    AddDefaultValue(sb, link, name);
                }
            }
            sb.Append(code.Substring(lastOffset, code.Length - lastOffset));

            // format & indent template code
            TextEditorData data = new TextEditorData();

            data.Text = sb.ToString();
            data.Document.TextReplaced += delegate(object sender, ReplaceEventArgs e) {
                int delta = -e.Count + (e.Value != null ? e.Value.Length : 0);
                foreach (var link in result.TextLinks)
                {
                    foreach (var segment in link.Links)
                    {
                        if (segment.Offset > e.Offset)
                        {
                            segment.Offset += delta;
                        }
                    }
                }
                if (result.CaretEndOffset > e.Offset)
                {
                    result.CaretEndOffset += delta;
                }
            };

            var formatter = CodeFormatterService.GetFormatter(context.Document.Editor.Document.MimeType);

            if (formatter != null && context.Document.HasProject)
            {
                formatter.OnTheFlyFormat(context.Document.Project.Policies, data, 0, data.Length);
            }

            IndentCode(data, context.LineIndent);
            result.Code = data.Text;
            data.Dispose();
            return(result);
        }
        private void LoadSelectedServer()
        {
            if (ServersListBox.SelectedIndex >= 0 && ServersListBox.SelectedIndex < _modifiedConfiguration.configs.Count)
            {
                Server server = _modifiedConfiguration.configs[ServersListBox.SelectedIndex];

                IPTextBox.Text        = server.server;
                NumServerPort.Value   = server.server_port;
                NumUDPPort.Value      = server.server_udp_port;
                PasswordTextBox.Text  = server.password;
                EncryptionSelect.Text = server.method ?? "aes-256-cfb";
                if (string.IsNullOrEmpty(server.protocol))
                {
                    TCPProtocolComboBox.Text = "origin";
                }
                else
                {
                    TCPProtocolComboBox.Text = server.protocol ?? "origin";
                }
                string obfs_text = server.obfs ?? "plain";
                ObfsCombo.Text          = obfs_text;
                TextProtocolParam.Text  = server.protocolparam;
                TextObfsParam.Text      = server.obfsparam;
                RemarksTextBox.Text     = server.remarks;
                TextGroup.Text          = server.group;
                CheckUDPoverUDP.Checked = server.udp_over_tcp;
                //CheckObfsUDP.Checked = server.obfs_udp;
                _SelectedID = server.id;

                ServerGroupBox.Visible = true;

                if (TCPProtocolComboBox.Text == "origin" &&
                    obfs_text == "plain" &&
                    !CheckUDPoverUDP.Checked
                    )
                {
                    checkAdvSetting.Checked = false;
                }

                if (checkSSRLink.Checked)
                {
                    TextLink.Text = server.GetSSRLinkForServer();
                }
                else
                {
                    TextLink.Text = server.GetSSLinkForServer();
                }

                if (CheckTCPoverUDP.Checked || CheckUDPoverUDP.Checked || server.server_udp_port != 0)
                {
                    checkAdvSetting.Checked = true;
                }

                //PasswordLabel.Checked = false;
                //IPLabel.Checked = false;
                Update_SSR_controls_Visable();
                UpdateObfsTextbox();
                TextLink.SelectAll();
                GenQR(TextLink.Text);
            }
            else
            {
                ServerGroupBox.Visible = false;
            }
        }
Exemplo n.º 52
0
		public async Task Rename (ISymbol symbol)
		{
			var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
			var ws = TypeSystemService.GetWorkspace (solution);

			var currentSolution = ws.CurrentSolution;
			var cts = new CancellationTokenSource ();
			var newSolution = await MessageService.ExecuteTaskAndShowWaitDialog (Task.Run (() => Renamer.RenameSymbolAsync (currentSolution, symbol, "_" + symbol.Name + "_", ws.Options, cts.Token)), GettextCatalog.GetString ("Looking for all references"), cts);
			var projectChanges = currentSolution.GetChanges (newSolution).GetProjectChanges ().ToList ();
			var changedDocuments = new HashSet<string> ();
			foreach (var change in projectChanges) {
				foreach (var changedDoc in change.GetChangedDocuments ()) {
					changedDocuments.Add (ws.CurrentSolution.GetDocument (changedDoc).FilePath);
				}
			}

			if (changedDocuments.Count > 1) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}

			var projectChange = projectChanges [0];
			var changes = projectChange.GetChangedDocuments ().ToList ();
			if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}
			var doc = IdeApp.Workbench.ActiveDocument;
			var editor = doc.Editor;
			var oldVersion = editor.Version;
			
			var links = new List<TextLink> ();
			var link = new TextLink ("name");

			var documents = ImmutableHashSet.Create (doc.AnalysisDocument);

			foreach (var loc in symbol.Locations) {
				if (loc.IsInSource && FilePath.PathComparer.Equals (loc.SourceTree.FilePath, doc.FileName)) {
					link.AddLink (new TextSegment (loc.SourceSpan.Start, loc.SourceSpan.Length));
				}
			}

			foreach (var mref in await SymbolFinder.FindReferencesAsync (symbol, TypeSystemService.Workspace.CurrentSolution, documents, default(CancellationToken))) {
				foreach (var loc in mref.Locations) {
					TextSpan span = loc.Location.SourceSpan;
					var root = loc.Location.SourceTree.GetRoot ();
					var node = root.FindNode (loc.Location.SourceSpan);
					var trivia = root.FindTrivia (loc.Location.SourceSpan.Start);
					if (!trivia.IsKind (SyntaxKind.SingleLineDocumentationCommentTrivia)) {
						span = node.Span;
					}
					if (span.Start != loc.Location.SourceSpan.Start) {
						span = loc.Location.SourceSpan;
					}
					var segment = new TextSegment (span.Start, span.Length);
					if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset) {
						link.Links.Insert (0, segment);
					} else {
						link.AddLink (segment);
					}
				}
			}
			links.Add (link);

			editor.StartTextLinkMode (new TextLinkModeOptions (links, (arg) => {
				//If user cancel renaming revert changes
				if (!arg.Success) {
					var textChanges = editor.Version.GetChangesTo (oldVersion).ToList ();
					foreach (var v in textChanges) {
						editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
					}
				}
			}));
		}