~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

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
// 
// ResultsEditorExtension.cs
//  
// Author:
//       Michael Hutchinson <mhutchinson@novell.com>
// 
// Copyright (c) 2010 Novell, Inc.
// 
// 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 MonoDevelop.Ide.Gui.Content;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using Mono.TextEditor;
using System.Linq;
using MonoDevelop.SourceEditor.QuickTasks;
using ICSharpCode.NRefactory.CSharp;

namespace MonoDevelop.AnalysisCore.Gui
{
	public class ResultsEditorExtension : TextEditorExtension, IQuickTaskProvider
	{
		bool disposed;
		
		public override void Initialize ()
		{
			base.Initialize ();

			AnalysisOptions.AnalysisEnabled.Changed += AnalysisOptionsChanged;
			AnalysisOptionsChanged (null, null);
		}

		void AnalysisOptionsChanged (object sender, EventArgs e)
		{
			Enabled = AnalysisOptions.AnalysisEnabled;
		}
		
		public override void Dispose ()
		{
			if (disposed) 
				return;
			enabled = false;
			Document.DocumentParsed -= OnDocumentParsed;
			CancelTask ();
			AnalysisOptions.AnalysisEnabled.Changed -= AnalysisOptionsChanged;
			while (markers.Count > 0)
				Document.Editor.Document.RemoveMarker (markers.Dequeue ());
			tasks.Clear ();
			disposed = true;
		}
		
		bool enabled;
		
		public bool Enabled {
			get { return enabled; }
			set {
				if (enabled != value) {
					if (value)
						Enable ();
					else
						Disable ();
				}
			}
		}
		
		void Enable ()
		{
			if (enabled)
				return;
			enabled = true;
			Document.DocumentParsed += OnDocumentParsed;
			if (Document.ParsedDocument != null)
				OnDocumentParsed (null, null);
		}

		void CancelTask ()
		{
			if (src != null) {
				src.Cancel ();
				try {
					oldTask.Wait ();
				} catch (TaskCanceledException) {
				} catch (AggregateException ex) {
					ex.Handle (e => e is TaskCanceledException);
				}
			}
		}
		
		void Disable ()
		{
			if (!enabled)
				return;
			enabled = false;
			Document.DocumentParsed -= OnDocumentParsed;
			CancelTask ();
			new ResultsUpdater (this, new Result[0], CancellationToken.None).Update ();
		}
		
		Task oldTask;
		CancellationTokenSource src = null;
		//FIXME: rate-limit this, so we don't send multiple new documents while it's processing
		void OnDocumentParsed (object sender, EventArgs args)
		{
			if (!QuickTaskStrip.EnableFancyFeatures)
				return;
			var doc = Document.ParsedDocument;
			if (doc == null)
				return;
			lock (this) {
				CancelTask ();
				src = new CancellationTokenSource ();
				var treeType = new RuleTreeType ("Document", Path.GetExtension (doc.FileName));
				var task = AnalysisService.QueueAnalysis (Document, treeType, src.Token);
				oldTask = task.ContinueWith (t => new ResultsUpdater (this, t.Result, src.Token).Update (), src.Token);
			}
		}
		
		class ResultsUpdater 
		{
			readonly ResultsEditorExtension ext;
			readonly CancellationToken cancellationToken;
			
			//the number of markers at the head of the queue that need tp be removed
			int oldMarkers;
			IEnumerator<Result> enumerator;
			
			public ResultsUpdater (ResultsEditorExtension ext, IEnumerable<Result> results, CancellationToken cancellationToken)
			{
				if (ext == null)
					throw new ArgumentNullException ("ext");
				if (results == null)
					throw new ArgumentNullException ("results");
				this.ext = ext;
				this.cancellationToken = cancellationToken;
				this.oldMarkers = ext.markers.Count;
				enumerator = ((IEnumerable<Result>)results).GetEnumerator ();
			}
			
			public void Update ()
			{
				if (!QuickTaskStrip.EnableFancyFeatures || cancellationToken.IsCancellationRequested)
					return;
				ext.tasks.Clear ();
				GLib.Idle.Add (IdleHandler);
			}
			
			//this runs as a glib idle handler so it can add/remove text editor markers
			//in order to to block the GUI thread, we batch them in UPDATE_COUNT
			bool IdleHandler ()
			{
				if (cancellationToken.IsCancellationRequested)
					return false;
				var editor = ext.Editor;
				if (editor == null || editor.Document == null)
					return false;
				//clear the old results out at the same rate we add in the new ones
				for (int i = 0; oldMarkers > 0 && i < UPDATE_COUNT; i++) {
					if (cancellationToken.IsCancellationRequested)
						return false;
					editor.Document.RemoveMarker (ext.markers.Dequeue ());
					oldMarkers--;
				}
				//add in the new markers
				for (int i = 0; i < UPDATE_COUNT; i++) {
					if (!enumerator.MoveNext ()) {
						ext.OnTasksUpdated (EventArgs.Empty);
						return false;
					}
					if (cancellationToken.IsCancellationRequested)
						return false;
					var currentResult = (Result)enumerator.Current;
					
					if (currentResult.InspectionMark != IssueMarker.None) {
						int start = editor.LocationToOffset (currentResult.Region.Begin);
						int end = editor.LocationToOffset (currentResult.Region.End);

						if (currentResult.InspectionMark == IssueMarker.GrayOut) {
							var marker = new GrayOutMarker (currentResult, TextSegment.FromBounds (start, end));
							marker.IsVisible = currentResult.Underline;
							editor.Document.AddMarker (marker);
							ext.markers.Enqueue (marker);
							editor.Parent.TextViewMargin.RemoveCachedLine (editor.GetLineByOffset (start));
							editor.Parent.QueueDraw ();
						} else {
							var marker = new ResultMarker (currentResult, TextSegment.FromBounds (start, end));
							marker.IsVisible = currentResult.Underline;
							editor.Document.AddMarker (marker);
							ext.markers.Enqueue (marker);
						}
					}
					
					ext.tasks.Add (new QuickTask (currentResult.Message, currentResult.Region.Begin, currentResult.Level));
				}
				
				return true;
			}
		}
		
		//all markers known to be in the editor
		Queue<ResultMarker> markers = new Queue<ResultMarker> ();
		
		const int UPDATE_COUNT = 20;
		
		public IList<Result> GetResultsAtOffset (int offset, CancellationToken token = default (CancellationToken))
		{
//			var location = Editor.Document.OffsetToLocation (offset);
//			var line = Editor.GetLineByOffset (offset);
			
			var list = new List<Result> ();
			foreach (var marker in Editor.Document.GetTextSegmentMarkersAt (offset)) {
				if (token.IsCancellationRequested)
					break;
				var resultMarker = marker as ResultMarker;
				if (resultMarker != null)
					list.Add (resultMarker.Result);
			}
			return list;
		}
		
		public IEnumerable<Result> GetResults ()
		{
			return markers.Select (m => m.Result);
		}

		#region IQuickTaskProvider implementation
		List<QuickTask> tasks = new List<QuickTask> ();

		public event EventHandler TasksUpdated;

		protected virtual void OnTasksUpdated (EventArgs e)
		{
			EventHandler handler = this.TasksUpdated;
			if (handler != null)
				handler (this, e);
		}
		
		public IEnumerable<QuickTask> QuickTasks {
			get {
				return tasks;
			}
		}
		
		#endregion
	}
}