~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
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
// DispatchService.cs
//
// Author:
//   Todd Berman  <tberman@off.net>
//   Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2005 Todd Berman  <tberman@off.net>
// Copyright (c) 2005 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.Threading;
using System.Collections;
using System.Diagnostics;

using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using System.Collections.Generic;
using System.Linq;

namespace MonoDevelop.Ide
{
	public class DispatchService
	{
		static Queue<GenericMessageContainer> backgroundQueue = new Queue<GenericMessageContainer> ();
		static ManualResetEvent backgroundThreadWait = new ManualResetEvent (false);
		static Queue<GenericMessageContainer> guiQueue = new Queue<GenericMessageContainer> ();
		static Thread thrBackground;
		static uint iIdle = 0;
		static GLib.TimeoutHandler handler;
		static Thread guiThread;
		static GuiSyncContext guiContext;
		static internal bool DispatchDebug;
		const string errormsg = "An exception was thrown while dispatching a method call in the UI thread.";

		internal static void Initialize ()
		{
			guiContext = new GuiSyncContext ();
			guiThread = Thread.CurrentThread;
			
			handler = new GLib.TimeoutHandler (guiDispatcher);
			
			thrBackground = new Thread (new ThreadStart (backgroundDispatcher)) {
				Name = "Background dispatcher",
				IsBackground = true,
				Priority = ThreadPriority.Lowest,
			};
			thrBackground.Start ();
			
			DispatchDebug = Environment.GetEnvironmentVariable ("MONODEVELOP_DISPATCH_DEBUG") != null;
		}
		
		public static void GuiDispatch (MessageHandler cb)
		{
			if (IsGuiThread) {
				cb ();
				return;
			}

			QueueMessage (new GenericMessageContainer (cb, false));
		}

		public static void GuiDispatch (StatefulMessageHandler cb, object state)
		{
			if (IsGuiThread) {
				cb (state);
				return;
			}

			QueueMessage (new StatefulMessageContainer (cb, state, false));
		}

		public static void GuiSyncDispatch (MessageHandler cb)
		{
			if (IsGuiThread) {
				cb ();
				return;
			}

			GenericMessageContainer mc = new GenericMessageContainer (cb, true);
			lock (mc) {
				QueueMessage (mc);
				Monitor.Wait (mc);
			}
			if (mc.Exception != null)
				throw new Exception (errormsg, mc.Exception);
		}
		
		public static void GuiSyncDispatch (StatefulMessageHandler cb, object state)
		{
			if (IsGuiThread) {
				cb (state);
				return;
			}

			StatefulMessageContainer mc = new StatefulMessageContainer (cb, state, true);
			lock (mc) {
				QueueMessage (mc);
				Monitor.Wait (mc);
			}
			if (mc.Exception != null)
				throw new Exception (errormsg, mc.Exception);
		}
		
		static DateTime lastPendingEvents;
		public static void RunPendingEvents ()
		{
			// The loop is limited to 1000 iterations as a workaround for an issue that some users
			// have experienced. Sometimes EventsPending starts return 'true' for all iterations,
			// causing the loop to never end.
			//
			// The loop is also limited to running at most twice a second as some of the classes
			// inheriting from BaseProgressMonitor call RunPendingEvents for every method invocation.
			// This means we pump the main loop dozens of times a second resulting in many screen
			// redraws and significantly slow down the running task.

			int maxLength = 20;
			Gdk.Threads.Enter();
			Stopwatch sw = new Stopwatch ();
			sw.Start ();

			// Check for less than zero in case there's a system time change
			var diff = DateTime.UtcNow - lastPendingEvents;
			if (diff > TimeSpan.FromMilliseconds (500) || diff < TimeSpan.Zero) {
				lastPendingEvents = DateTime.UtcNow;
				while (Gtk.Application.EventsPending () && sw.ElapsedMilliseconds < maxLength) {
					Gtk.Application.RunIteration (false);
				}
			}

			sw.Stop ();

			Gdk.Threads.Leave();
			guiDispatcher ();
		}
		
		static void QueueMessage (GenericMessageContainer msg)
		{
			lock (guiQueue) {
				guiQueue.Enqueue (msg);
				if (iIdle == 0)
					iIdle = GLib.Timeout.Add (0, handler);
			}
		}
		
		public static bool IsGuiThread
		{
			get { return guiThread == Thread.CurrentThread; }
		}
		
		public static void AssertGuiThread ()
		{
			if (guiThread != Thread.CurrentThread)
				throw new InvalidOperationException ("This method can only be called in the GUI thread");
		}
		
		public static Delegate GuiDispatch (Delegate del)
		{
			return guiContext.CreateSynchronizedDelegate (del);
		}
		
		public static T GuiDispatch<T> (T theDelegate)
		{
			if (guiContext == null)
				return theDelegate;
			Delegate del = (Delegate)(object)theDelegate;
			return (T)(object)guiContext.CreateSynchronizedDelegate (del);
		}
		
		/// <summary>
		/// Runs the provided delegate in the background, but waits until finished, pumping the
		/// message queue if necessary.
		/// </summary>
		public static void BackgroundDispatchAndWait (MessageHandler cb)
		{
			object eventObject = new object ();
			lock (eventObject) {
				BackgroundDispatch (delegate {
					try {
						cb ();
					} finally {
						lock (eventObject) {
							Monitor.Pulse (eventObject);
						}
					}
				});
				if (IsGuiThread) {
					while (true) {
						if (Monitor.Wait (eventObject, 50))
							return;
						RunPendingEvents ();
					}
				}
				else {
					Monitor.Wait (eventObject);
				}
			}
		}
		
		public static void BackgroundDispatch (MessageHandler cb)
		{
			QueueBackground (new GenericMessageContainer (cb, false));
		}

		public static void BackgroundDispatch (StatefulMessageHandler cb, object state)
		{
			QueueBackground (new StatefulMessageContainer (cb, state, false));
		}
		
		static void QueueBackground (GenericMessageContainer c)
		{
			lock (backgroundQueue) {
				backgroundQueue.Enqueue (c);
				if (backgroundQueue.Count == 1)
					backgroundThreadWait.Set ();
			}
		}
		
		public static void ThreadDispatch (MessageHandler cb)
		{
			GenericMessageContainer smc = new GenericMessageContainer (cb, false);
			Thread t = new Thread (new ThreadStart (smc.Run));
			t.Name = "Message dispatcher";
			t.IsBackground = true;
			t.Start ();
		}

		public static void ThreadDispatch (StatefulMessageHandler cb, object state)
		{
			StatefulMessageContainer smc = new StatefulMessageContainer (cb, state, false);
			Thread t = new Thread (new ThreadStart (smc.Run));
			t.Name = "Message dispatcher";
			t.IsBackground = true;
			t.Start ();
		}

		static bool guiDispatcher ()
		{
			GenericMessageContainer msg;
			int iterCount;
			
			lock (guiQueue) {
				iterCount = guiQueue.Count;
				if (iterCount == 0) {
					iIdle = 0;
					return false;
				}
			}
			
			for (int n=0; n<iterCount; n++) {
				lock (guiQueue) {
					if (guiQueue.Count == 0) {
						iIdle = 0;
						return false;
					}
					msg = guiQueue.Dequeue ();
				}
				
				msg.Run ();
				
				if (msg.IsSynchronous)
					lock (msg) Monitor.PulseAll (msg);
				else if (msg.Exception != null)
					HandlerError (msg);
			}
			
			lock (guiQueue) {
				if (guiQueue.Count == 0) {
					iIdle = 0;
					return false;
				} else
					return true;
			}
		}

		static void backgroundDispatcher ()
		{
			while (true) {
				GenericMessageContainer msg = null;
				bool wait = false;
				lock (backgroundQueue) {
					if (backgroundQueue.Count == 0) {
						backgroundThreadWait.Reset ();
						wait = true;
					} else
						msg = backgroundQueue.Dequeue ();
				}
				
				if (wait) {
					backgroundThreadWait.WaitOne ();
					continue;
				}
				
				if (msg != null) {
					msg.Run ();
					if (msg.Exception != null)
						HandlerError (msg);
				}
			}
		}
		
		static void HandlerError (GenericMessageContainer msg)
		{
			if (msg.CallerStack != null) {
				LoggingService.LogError ("{0} {1}\nCaller stack:{2}", errormsg, msg.Exception.ToString (), msg.CallerStack);
			}
			else
				LoggingService.LogError ("{0} {1}\nCaller stack not available. Define the environment variable MONODEVELOP_DISPATCH_DEBUG to enable caller stack capture.", errormsg, msg.Exception.ToString ());
		}

		#region Animations

		/// <summary>
		/// Runs a delegate at regular intervals 
		/// </summary>
		/// <returns>
		/// An animation object. It can be disposed to stop the animation.
		/// </returns>
		/// <param name='animation'>
		/// The delegate to run. The return value if the number of milliseconds to wait until the delegate is run again.
		/// The execution will stop if the deletgate returns 0
		/// </param>
		public static IDisposable RunAnimation (Func<int> animation)
		{
			var ainfo = new AnimationInfo () {
				AnimationFunc = animation,
				NextDueTime = DateTime.Now
			};

			activeAnimations.Add (ainfo);
			
			// Don't immediately run the animation if we are going to do it in less than 20ms
			if (animationHandle == 0 || currentAnimationSpan > 20)
				ProcessAnimations ();
			return ainfo;
		}
		
		static List<AnimationInfo> activeAnimations = new List<AnimationInfo> ();
		static uint animationHandle;
		static DateTime nextDueTime;
		static int currentAnimationSpan;

		class AnimationInfo: IDisposable {
			public Func<int> AnimationFunc;
			public DateTime NextDueTime;

			public void Dispose ()
			{
				DispatchService.StopAnimation (this);
			}
		}

		static bool ProcessAnimations ()
		{
			List<AnimationInfo> toDelete = null;

			DateTime now = DateTime.Now;
			nextDueTime = DateTime.MaxValue;

			foreach (var a in activeAnimations) {
				if (a.NextDueTime <= now) {
					int ms = a.AnimationFunc ();
					if (ms <= 0) {
						if (toDelete == null)
							toDelete = new List<AnimationInfo> ();
						toDelete.Add (a);
						a.NextDueTime = DateTime.MaxValue;
					} else
						a.NextDueTime = DateTime.Now + TimeSpan.FromMilliseconds (ms);
				}
				if (a.NextDueTime < nextDueTime)
					nextDueTime = a.NextDueTime;
			}

			if (toDelete != null) {
				foreach (var a in toDelete)
					activeAnimations.Remove (a);
			}

			if (nextDueTime == DateTime.MaxValue) {
				// No more animations
				animationHandle = 0;
				return false;
			}

			int nms = (int) (nextDueTime - DateTime.Now).TotalMilliseconds;
			if (nms < 20)
				nms = 20;

			// Don't re-schedule if the current time span is more or less the same as the previous one
			if (animationHandle != 0 && Math.Abs (nms - currentAnimationSpan) <= 3)
				return true;

			currentAnimationSpan = nms;
			animationHandle = GLib.Timeout.Add ((uint)currentAnimationSpan, ProcessAnimations);
			return false;
		}

		static void StopAnimation (AnimationInfo a)
		{
			activeAnimations.Remove (a);
			if (activeAnimations.Count == 0 && animationHandle != 0) {
				GLib.Source.Remove (animationHandle);
				animationHandle = 0;
			}
		}

		#endregion
	}

	public delegate void MessageHandler ();
	public delegate void StatefulMessageHandler (object state);

	class GenericMessageContainer
	{
		MessageHandler callback;
		protected Exception ex;
		protected bool isSynchronous;
		protected string callerStack;

		protected GenericMessageContainer () { }

		public GenericMessageContainer (MessageHandler cb, bool isSynchronous)
		{
			callback = cb;
			this.isSynchronous = isSynchronous;
			if (DispatchService.DispatchDebug) callerStack = Environment.StackTrace;
		}

		public virtual void Run ( )
		{
			try {
				callback ();
			}
			catch (Exception e) {
				ex = e;
			}
		}
		
		public Exception Exception
		{
			get { return ex; }
		}
		
		public bool IsSynchronous
		{
			get { return isSynchronous; }
		}
		
		public string CallerStack
		{
			get { return callerStack; }
		}
	}

	class StatefulMessageContainer : GenericMessageContainer
	{
		object data;
		StatefulMessageHandler callback;

		public StatefulMessageContainer (StatefulMessageHandler cb, object state, bool isSynchronous)
		{
			data = state;
			callback = cb;
			this.isSynchronous = isSynchronous;
			if (DispatchService.DispatchDebug) callerStack = Environment.StackTrace;
		}

		public override void Run ( )
		{
			try {
				callback (data);
			}
			catch (Exception e) {
				ex = e;
			}
		}
	}

}