Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CSharpOutlineTextEditorExtension.cs « MonoDevelop.CSharp.ClassOutline « CSharpBinding « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b77c19e772d6dae0251bb3f3d83a7c9058892de7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//
// ClassOutlineTextEditorExtension.cs
//
// Author:
//   Michael Hutchinson <mhutchinson@novell.com>
//
// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using Gtk;

using MonoDevelop.Core;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide;
using MonoDevelop.Components;
using MonoDevelop.Components.Docking;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.DesignerSupport;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.CSharp;
using MonoDevelop.Projects;
using MonoDevelop.Ide.Editor.Extension;
using MonoDevelop.Ide.Editor;

namespace MonoDevelop.CSharp.ClassOutline
{
	/// <summary>
	/// Displays a types and members outline of the current document.
	/// </summary>
	/// <remarks>
	/// Document types and members are displayed in a tree view.
	/// The displayed nodes can be sorted by changing the sorting properties state.
	/// The sort behaviour is serialized into MonoDevelopProperties.xml.
	/// Nodes with lower sortKey value will be sorted before nodes with higher value.
	/// Nodes with equal sortKey will be sorted by string comparison of the name of the nodes.
	/// The string comparison ignores symbols (e.g. sort 'Foo()' next to '~Foo()').
	/// </remarks>
	/// <seealso cref="MonoDevelop.CSharp.ClassOutline.OutlineNodeComparer"/>
	/// <seealso cref="MonoDevelop.CSharp.ClassOutline.OutlineSettings"/>
	class CSharpOutlineTextEditorExtension : TextEditorExtension, IOutlinedDocument
	{
		SemanticModel lastCU = null;

		MonoDevelop.Ide.Gui.Components.PadTreeView outlineTreeView;
		TreeStore outlineTreeStore;
		TreeModelSort outlineTreeModelSort;
		Widget[] toolbarWidgets;
		AstAmbience astAmbience;

		OutlineNodeComparer comparer;
		OutlineSettings settings;

		bool refreshingOutline;
		bool disposed;
		bool outlineReady;


		public override bool IsValidInContext (DocumentContext context)
		{
			var binding = LanguageBindingService.GetBindingPerFileName (context.Name);
			return binding != null && binding is IDotNetLanguageBinding;
		}

		protected override void Initialize ()
		{
			base.Initialize ();

			if (DocumentContext != null)
				DocumentContext.DocumentParsed += UpdateDocumentOutline;
			astAmbience = new AstAmbience (TypeSystemService.Workspace.Options);
		}

		public override void Dispose ()
		{
			if (disposed)
				return;
			disposed = true;
			if (DocumentContext != null)
				DocumentContext.DocumentParsed -= UpdateDocumentOutline;
			RemoveRefillOutlineStoreTimeout ();
			lastCU = null;
			settings = null;
			comparer = null;
			base.Dispose ();
		}

		Widget IOutlinedDocument.GetOutlineWidget ()
		{
			if (outlineTreeView != null)
				return outlineTreeView;

			outlineTreeStore = new TreeStore (typeof(object));
			outlineTreeModelSort = new TreeModelSort (outlineTreeStore);
			
			settings = OutlineSettings.Load ();
			comparer = new OutlineNodeComparer (new AstAmbience (TypeSystemService.Workspace.Options), settings, outlineTreeModelSort);

			outlineTreeModelSort.SetSortFunc (0, comparer.CompareNodes);
			outlineTreeModelSort.SetSortColumnId (0, SortType.Ascending);

			outlineTreeView = new MonoDevelop.Ide.Gui.Components.PadTreeView (outlineTreeStore);

			var pixRenderer = new CellRendererImage ();
			pixRenderer.Xpad = 0;
			pixRenderer.Ypad = 0;

			outlineTreeView.TextRenderer.Xpad = 0;
			outlineTreeView.TextRenderer.Ypad = 0;

			TreeViewColumn treeCol = new TreeViewColumn ();
			treeCol.PackStart (pixRenderer, false);

			treeCol.SetCellDataFunc (pixRenderer, new TreeCellDataFunc (OutlineTreeIconFunc));
			treeCol.PackStart (outlineTreeView.TextRenderer, true);

			treeCol.SetCellDataFunc (outlineTreeView.TextRenderer, new TreeCellDataFunc (OutlineTreeTextFunc));
			outlineTreeView.AppendColumn (treeCol);

			outlineTreeView.HeadersVisible = false;

			outlineTreeView.Selection.Changed += delegate {
				JumpToDeclaration (false);
			};
			
			outlineTreeView.RowActivated += delegate {
				JumpToDeclaration (true);
			};

			var analysisDocument = DocumentContext.ParsedDocument;
			if (analysisDocument != null)
				lastCU = analysisDocument.GetAst<SemanticModel> ();

			outlineTreeView.Realized += delegate { RefillOutlineStore (); };
			UpdateSorting ();

			var sw = new CompactScrolledWindow ();
			sw.Add (outlineTreeView);
			sw.ShowAll ();
			return sw;
		}
		
		IEnumerable<Widget> IOutlinedDocument.GetToolbarWidgets ()
		{
			if (toolbarWidgets != null)
				return toolbarWidgets;
			
			var groupToggleButton = new ToggleButton {
				Image = new Image (Ide.Gui.Stock.GroupByCategory, IconSize.Menu),
				TooltipText = GettextCatalog.GetString ("Group entries by type"),
				Active = settings.IsGrouped,
			};	
			groupToggleButton.Toggled += delegate {
				if (groupToggleButton.Active == settings.IsGrouped)
					return;
				settings.IsGrouped = groupToggleButton.Active;
				UpdateSorting ();
			};

			var sortAlphabeticallyToggleButton = new ToggleButton {
				Image = new Image (Ide.Gui.Stock.SortAlphabetically, IconSize.Menu),
				TooltipText = GettextCatalog.GetString ("Sort entries alphabetically"),
				Active = settings.IsSorted,
			};	
			sortAlphabeticallyToggleButton.Toggled += delegate {
				if (sortAlphabeticallyToggleButton.Active == settings.IsSorted)
					return;
				settings.IsSorted = sortAlphabeticallyToggleButton.Active;
				UpdateSorting ();
			};

			var preferencesButton = new DockToolButton (Ide.Gui.Stock.Options) {
				TooltipText = GettextCatalog.GetString ("Open preferences dialog"),
			};
			preferencesButton.Clicked += delegate {
				var dialog = new OutlineSortingPreferencesDialog (settings);
				try {
					if (MessageService.ShowCustomDialog (dialog) == (int)ResponseType.Ok) {
						dialog.SaveSettings ();
						comparer = new OutlineNodeComparer (new AstAmbience (TypeSystemService.Workspace.Options), settings, outlineTreeModelSort);
						UpdateSorting ();
					}
				} finally {
					dialog.Destroy ();
				}
			};
			
			return toolbarWidgets = new Widget[] {
				groupToggleButton,
				sortAlphabeticallyToggleButton,
				new VSeparator (),
				preferencesButton,
			};
		}
		
		void JumpToDeclaration (bool focusEditor)
		{
			if (!outlineReady)
				return;
			TreeIter iter;
			if (!outlineTreeView.Selection.GetSelected (out iter))
				return;

			var o = outlineTreeStore.GetValue (IsSorting () ? outlineTreeModelSort.ConvertIterToChildIter (iter) : iter, 0);

			var syntaxNode = o as SyntaxNode;
			if (syntaxNode != null) {
				Editor.CaretOffset = syntaxNode.SpanStart;
			} else {
				Editor.CaretOffset = ((SyntaxTrivia)o).SpanStart;
			}

			if (focusEditor)
				Editor.GrabFocus ();
		}

		static void OutlineTreeIconFunc (TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			var pixRenderer = (CellRendererImage)cell;
			object o = model.GetValue (iter, 0);
			if (o is SyntaxNode) {
				pixRenderer.Image = ImageService.GetIcon (((SyntaxNode)o).GetStockIcon (), IconSize.Menu);
			} else if (o is SyntaxTrivia) {
				pixRenderer.Image = ImageService.GetIcon (Ide.Gui.Stock.Add, IconSize.Menu);
			}
		}

		void OutlineTreeTextFunc (TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			var txtRenderer = (CellRendererText)cell;
			object o = model.GetValue (iter, 0);
			var syntaxNode = o as SyntaxNode;
			if (syntaxNode != null) {
				txtRenderer.Text = astAmbience.GetEntityMarkup (syntaxNode);
			} else if (o is SyntaxTrivia) {
				txtRenderer.Text = ((SyntaxTrivia)o).ToString ();
			}
		}

		void IOutlinedDocument.ReleaseOutlineWidget ()
		{
			if (outlineTreeView == null)
				return;
			var w = (ScrolledWindow)outlineTreeView.Parent;
			w.Destroy ();
			if (outlineTreeModelSort != null) {
				outlineTreeModelSort.Dispose ();
				outlineTreeModelSort = null;
			}
			if (outlineTreeStore != null) {
				outlineTreeStore.Dispose ();
				outlineTreeStore = null;
			}
			outlineTreeView = null;
			settings = null;
			foreach (var tw in toolbarWidgets)
				tw.Destroy ();
			toolbarWidgets = null;
			comparer = null;
		}

		void RemoveRefillOutlineStoreTimeout ()
		{
			if (refillOutlineStoreId == 0)
				return;
			GLib.Source.Remove (refillOutlineStoreId);
			refillOutlineStoreId = 0;
		}

		uint refillOutlineStoreId;
		void UpdateDocumentOutline (object sender, EventArgs args)
		{
			var analysisDocument = DocumentContext.ParsedDocument;
			if (analysisDocument == null)
				return;
			lastCU = analysisDocument.GetAst<SemanticModel> ();
			//limit update rate to 3s
			if (!refreshingOutline) {
				refreshingOutline = true;
				refillOutlineStoreId = GLib.Timeout.Add (3000, RefillOutlineStore);
			}
		}

		bool RefillOutlineStore ()
		{
			DispatchService.AssertGuiThread ();
			Gdk.Threads.Enter ();
			refreshingOutline = false;
			if (outlineTreeStore == null || !outlineTreeView.IsRealized) {
				refillOutlineStoreId = 0;
				return false;
			}
			
			outlineReady = false;
			outlineTreeStore.Clear ();
			if (lastCU != null) {
				BuildTreeChildren (outlineTreeStore, TreeIter.Zero, lastCU);
				TreeIter it;
				if (IsSorting ()) {
					if (outlineTreeModelSort.GetIterFirst (out it))
						outlineTreeView.Selection.SelectIter (it);
				} else {
					if (outlineTreeStore.GetIterFirst (out it))
						outlineTreeView.Selection.SelectIter (it);
				}

				outlineTreeView.ExpandAll ();
			}
			outlineReady = true;

			Gdk.Threads.Leave ();

			//stop timeout handler
			refillOutlineStoreId = 0;
			return false;
		}

		class TreeVisitor : CSharpSyntaxWalker
		{
			TreeStore store;
			TreeIter curIter;

			public TreeVisitor (TreeStore store, TreeIter curIter) : base (SyntaxWalkerDepth.Trivia)
			{
				this.store = store;
				this.curIter = curIter;
			}

			TreeIter Append (object node) 
			{
				if (!curIter.Equals (TreeIter.Zero))
					return store.AppendValues (curIter, node);
				return store.AppendValues (node);
			}

			public override void VisitTrivia (SyntaxTrivia trivia)
			{
				switch (trivia.Kind ()) {
				case SyntaxKind.RegionDirectiveTrivia:
					curIter = Append (trivia);
					break;
				case SyntaxKind.EndRegionDirectiveTrivia:
					TreeIter parent;
					if (store.IterParent (out parent, curIter))
						curIter = parent;
					break;
				}
				base.VisitTrivia (trivia);
			}

			void VisitBody (SyntaxNode node)
			{
				var oldIter = curIter;

				foreach (var syntaxNodeOrToken in node.ChildNodesAndTokens ()) {
					var syntaxNode = syntaxNodeOrToken.AsNode ();
					if (syntaxNode != null) {
						Visit (syntaxNode);
					} else {
						var syntaxToken = syntaxNodeOrToken.AsToken ();
						if (syntaxToken.Kind () == SyntaxKind.OpenBraceToken)
							curIter = Append (node);
						VisitToken (syntaxToken);
					}
				}
				curIter = oldIter;

			}

			public override void VisitNamespaceDeclaration (NamespaceDeclarationSyntax node)
			{
				VisitBody (node);
			}

			public override void VisitClassDeclaration (ClassDeclarationSyntax node)
			{
				VisitBody (node);
			}

			public override void VisitStructDeclaration (StructDeclarationSyntax node)
			{
				VisitBody (node);
			}

			public override void VisitEnumDeclaration (EnumDeclarationSyntax node)
			{
				VisitBody (node);
			}

			public override void VisitInterfaceDeclaration (InterfaceDeclarationSyntax node)
			{
				VisitBody (node);
			}

			public override void VisitDelegateDeclaration (DelegateDeclarationSyntax node)
			{
				base.VisitDelegateDeclaration (node);
				Append (node);
			}

			public override void VisitFieldDeclaration (FieldDeclarationSyntax node)
			{
				base.VisitFieldDeclaration (node);
				foreach (var v in node.Declaration.Variables)
					Append (v);
			}

			public override void VisitPropertyDeclaration (PropertyDeclarationSyntax node)
			{
				base.VisitPropertyDeclaration (node);
				Append (node);
			}

			public override void VisitIndexerDeclaration (IndexerDeclarationSyntax node)
			{
				base.VisitIndexerDeclaration (node);
				Append (node);
			}

			public override void VisitMethodDeclaration (MethodDeclarationSyntax node)
			{
				base.VisitMethodDeclaration (node);
				Append (node);
			}

			public override void VisitOperatorDeclaration (OperatorDeclarationSyntax node)
			{
				base.VisitOperatorDeclaration (node);
				Append (node);
			}

			public override void VisitConstructorDeclaration (ConstructorDeclarationSyntax node)
			{
				base.VisitConstructorDeclaration (node);
				Append (node);
			}

			public override void VisitDestructorDeclaration (DestructorDeclarationSyntax node)
			{
				base.VisitDestructorDeclaration (node);
				Append (node);
			}

			public override void VisitEventDeclaration (EventDeclarationSyntax node)
			{
				base.VisitEventDeclaration (node);
				Append (node);
			}

			public override void VisitEventFieldDeclaration (EventFieldDeclarationSyntax node)
			{
				base.VisitEventFieldDeclaration (node);
				foreach (var v in node.Declaration.Variables)
					Append (v);
			}

			public override void VisitEnumMemberDeclaration (EnumMemberDeclarationSyntax node)
			{
				base.VisitEnumMemberDeclaration (node);
				Append (node);
			}

			public override void VisitBlock (BlockSyntax node)
			{
				// skip
			}
		}


		static void BuildTreeChildren (TreeStore store, TreeIter parent, SemanticModel parsedDocument)
		{
			if (parsedDocument == null)
				return;

			var root = parsedDocument.SyntaxTree.GetRoot ();

			var visitor = new TreeVisitor (store, parent);
			visitor.Visit (root); 
		}

		void UpdateSorting ()
		{
			if (IsSorting ()) {
				// Sort the model, sort keys may have changed.
				// Only setting the column again does not re-sort so we set the function instead.
				outlineTreeModelSort.SetSortFunc (0, comparer.CompareNodes);
				outlineTreeView.Model = outlineTreeModelSort;
			} else {
				outlineTreeView.Model = outlineTreeStore;
			}

			// Because sorting the tree by setting the sort function also collapses the tree view we expand
			// the whole tree.
			outlineTreeView.ExpandAll ();
		}

		bool IsSorting ()
		{
			return settings.IsGrouped || settings.IsSorted;
		}
	}
}