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

StatusBar.cs « MainToolbar « MacPlatform « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bbc28308a28d22e2492e4e35bb8f36901e535208 (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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
//
// StatusBar.cs
//
// Author:
//       Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.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 System.Linq;
using System.Timers;
using AppKit;
using Foundation;
using CoreAnimation;
using CoreGraphics;
using MonoDevelop.Components;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Components.MainToolbar;
using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui.Components;
using MonoDevelop.Ide.Tasks;
using MonoDevelop.Components.Mac;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using MonoDevelop.MacInterop;
using MonoDevelop.Components.AtkCocoaHelper;

namespace MonoDevelop.MacIntegration.MainToolbar
{
	class StatusIcon : NSButton, StatusBarIcon
	{
		StatusBar bar;
		readonly ObjCRuntime.Selector OnButtonClickedSelector = new ObjCRuntime.Selector ("OnButtonActivated:");

		public StatusIcon (StatusBar bar) : base (CGRect.Empty)
		{
			Bordered = false;
			var trackingArea = new NSTrackingArea (CGRect.Empty, NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.InVisibleRect | NSTrackingAreaOptions.MouseEnteredAndExited, this, null);
			AddTrackingArea (trackingArea);

			Target = this;
			Action = OnButtonClickedSelector;

			this.bar = bar;
		}

		public override CGRect Frame {
			get {
				return base.Frame;
			}
			set {
				base.Frame = value;
			}
		}

		public void SetAlertMode (int seconds)
		{
			// Create fade-out fade-in animation.
		}

		public new void Dispose ()
		{
			bar.RemoveStatusIcon (this);
			RemoveFromSuperview ();
			base.Dispose ();
		}

		string tooltip;
		public new string ToolTip {
			get {
				return tooltip;
			}

			set {
				tooltip = value;
				AccessibilityTitle = tooltip;
				AccessibilityValue = new NSString (tooltip);
			}
		}

		string help;
		public string Help {
			get {
				return help;
			}

			set {
				help = value;
				AccessibilityHelp = value;
			}
		}

		public new string Title { get; set; }
		public override string AccessibilityLabel {
			get {
				return Title;
			}
		}

		Xwt.Drawing.Image image;
		public new Xwt.Drawing.Image Image {
			get { return image; }
			set {
				image = value;
				base.Image = value.ToNSImage ();
				SetFrameSize (new CGSize (image.Width, image.Height));
			}
		}

		public override void MouseEntered (NSEvent theEvent)
		{
			Entered?.Invoke (this, EventArgs.Empty);
		}

		public override void MouseExited (NSEvent theEvent)
		{
			Exited?.Invoke (this, EventArgs.Empty);
		}

		[Export ("OnButtonActivated:")]
		void ButtonClicked (NSObject sender)
		{
			NotifyClicked (Xwt.PointerButton.Left);
		}

		internal void NotifyClicked (Xwt.PointerButton button)
		{
			Clicked?.Invoke (this, new StatusBarIconClickedEventArgs {
				Button = button,
			});
		}

		public override bool AccessibilityPerformPress ()
		{
			NotifyClicked (Xwt.PointerButton.Left);

			return true;
		}

		public event EventHandler<StatusBarIconClickedEventArgs> Clicked;
		public event EventHandler<EventArgs> Entered;
		public event EventHandler<EventArgs> Exited;

		public override bool AcceptsFirstResponder ()
		{
			return true;
		}

		public override bool BecomeFirstResponder ()
		{
			Entered?.Invoke (this, EventArgs.Empty);
			return true;
		}

		public override bool ResignFirstResponder ()
		{
			Exited?.Invoke (this, EventArgs.Empty);
			return true;
		}
	}

	class BuildResultsView : NSView, INSAccessibilityStaticText
	{
		public enum ResultsType
		{
			Warning,
			Error
		};

		public ResultsType Type { get; set; }

		NSAttributedString resultString;
		int resultCount;
		public int ResultCount {
			get {
				return resultCount;
			}
			set {
				resultCount = value;
				resultString = new NSAttributedString (value.ToString (), foregroundColor: Styles.BaseForegroundColor.ToNSColor (),
					font: NSFont.SystemFontOfSize (NSFont.SmallSystemFontSize - 1));
				ResizeToFit ();
			}
		}

		NSImage iconImage;
		public NSImage IconImage {
			get {
				return iconImage;
			}
			set {
				iconImage = value;
				ResizeToFit ();
			}
		}

		public BuildResultsView () : base (new CGRect (0, 0, 0, 0))
		{
			AccessibilityIdentifier = "MainToolbar.StatusDisplay.BuildResults";
			AccessibilityHelp = "Number of errors or warnings in the current project";
		}

		public override void DrawRect (CGRect dirtyRect)
		{
			if (iconImage == null || resultString == null) {
				return;
			}

			iconImage.Draw (new CGRect (0, (Frame.Size.Height - iconImage.Size.Height) / 2, iconImage.Size.Width, iconImage.Size.Height));
			resultString.DrawAtPoint (new CGPoint (iconImage.Size.Width, (Frame.Size.Height - resultString.Size.Height) / 2));
		}

		void ResizeToFit ()
		{
			if (iconImage == null || resultString == null) {
				return;
			}

			var stringSize = resultString.GetSize ();
			Frame = new CGRect (Frame.X, Frame.Y, iconImage.Size.Width + stringSize.Width, Frame.Height);
			NeedsDisplay = true;
		}

		public override void MouseDown (NSEvent theEvent)
		{
			IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ErrorListPad> ().BringToFront ();
		}

		string INSAccessibilityStaticText.AccessibilityValue {
			get {
				if (Type == ResultsType.Warning) {
					return GettextCatalog.GetPluralString ("{0} warning", "%d warnings", resultCount, resultCount);
				} else {
					return GettextCatalog.GetPluralString ("{0} error", "%d errors", resultCount, resultCount);
				}
			}
		}
	}

	// We need a separate layer backed view to put over the NSTextFields because the NSTextField draws itself differently
	// if it is layer backed so we can't make it or its superview layer backed.
	class ProgressView : NSView, INSAccessibilityProgressIndicator
	{
		const string ProgressLayerFadingId = "ProgressLayerFading";
		const string growthAnimationKey = "bounds";

		CALayer progressLayer;
		Stack<double> progressMarks = new Stack<double> ();
		bool inProgress;
		double oldFraction;

		const int barHeight = 2;
		const int barY = 0;

		public ProgressView ()
		{
			int barWidth = 0;

#if DEBUG_PROGRESSBAR
			barWidth = 100;
#endif
			WantsLayer = true;
			Layer.CornerRadius = MacSystemInformation.OsVersion >= MacSystemInformation.ElCapitan ? 3 : 4;

			progressLayer = new CALayer ();
			Layer.AddSublayer (progressLayer);
			Layer.BorderWidth = 0;

			var xamBlue = NSColor.FromRgba (52f / 255, 152f / 255, 219f / 255, 1f);
			progressLayer.BackgroundColor = xamBlue.CGColor;
			progressLayer.BorderWidth = 0;
			progressLayer.FillMode = CAFillMode.Forwards;
			progressLayer.Frame = new CGRect (0, barY, barWidth, barHeight);
			progressLayer.AnchorPoint = new CGPoint (0, 0);

			AccessibilityIdentifier = "MainToolbar.StatusDisplay.Progress";
			AccessibilityHelp = "The progress of the current action";
			AccessibilityHidden = true;
		}

		NSNumber INSAccessibilityProgressIndicator.AccessibilityValue {
			get {
				// Convert the number to a percentage
				var percent = (int)(oldFraction * 100.0f);
				return new NSNumber (percent);
			}
		}

		void SetProgressValue (double p)
		{
			oldFraction = p;
			var percent = (int)(oldFraction * 100.0f);
			((INSAccessibility)this).AccessibilityValue = new NSNumber (percent);
		}

		public void BeginProgress ()
		{
			SetProgressValue (0.0);
			progressLayer.RemoveAllAnimations ();

			progressLayer.Hidden = false;
			progressLayer.Opacity = 1;
			progressLayer.Frame = new CGRect (0, barY, 0, barHeight);

			AccessibilityHidden = false;
		}

		public void SetProgressFraction (double work)
		{
			if (oldFraction == work)
				return;

			progressMarks.Push (work);
			if (!inProgress) {
				inProgress = true;
				StartProgress (progressMarks.Peek ());
			}
		}

		public void EndProgress ()
		{
			progressMarks.Clear ();
			if (progressLayer != null) {
				progressLayer.RemoveAnimation (growthAnimationKey);
				progressLayer.Hidden = true;
				AccessibilityHidden = true;

				// We don't set the progress to 0 here, because EndProgress can be called many times
				// for a single task, and if we do then the progress bar pulses from 0 every time
			}
			inProgress = false;
		}

		CAAnimation CreateMoveAndGrowAnimation (CALayer progress, double growToFraction)
		{
			CABasicAnimation grow = CABasicAnimation.FromKeyPath ("bounds");
			grow.Duration = 0.2;
			grow.FillMode = CAFillMode.Forwards;
			grow.RemovedOnCompletion = false;
			grow.From = NSValue.FromCGRect (new CGRect (0, barY, Frame.Width * (nfloat)oldFraction, barHeight));
			grow.To = NSValue.FromCGRect (new CGRect (0, barY, Frame.Width * (nfloat)growToFraction, barHeight));
			return grow;
		}

		CAAnimation CreateAutoPulseAnimation ()
		{
			CABasicAnimation move = CABasicAnimation.FromKeyPath ("position.x");
			move.From = NSNumber.FromDouble (-frameAutoPulseWidth);
			move.To = NSNumber.FromDouble (Frame.Width + frameAutoPulseWidth);
			move.RepeatCount = float.PositiveInfinity;
			move.RemovedOnCompletion = false;
			move.Duration = 4;
			return move;
		}

		void AttachFadeoutAnimation (CALayer progress, CAAnimation animation, Func<bool> fadeoutVerifier)
		{
			animation.AnimationStopped += (sender, e) => {
				if (!fadeoutVerifier ()) {
					return;
				}

				if (!e.Finished) {
					return;
				}

				CABasicAnimation fadeout = CABasicAnimation.FromKeyPath ("opacity");
				fadeout.From = NSNumber.FromDouble (1);
				fadeout.To = NSNumber.FromDouble (0);
				fadeout.Duration = 0.5;
				fadeout.FillMode = CAFillMode.Forwards;
				fadeout.RemovedOnCompletion = false;
				fadeout.AnimationStopped += (sender2, e2) => {
					if (!e2.Finished)
						return;

					// Reset all the properties.
					inProgress = false;

					progress.Hidden = true;

					progress.Opacity = 1;
					progress.Frame = new CGRect (0, barY, 0, barHeight);
					progress.RemoveAllAnimations ();
					SetProgressValue (0.0);

					progress.Hidden = false;
				};
				progress.Name = ProgressLayerFadingId;
				progress.AddAnimation (fadeout, "opacity");
			};
			progress.AddAnimation (animation, growthAnimationKey);
		}

		public void StartProgress (double newFraction)
		{
			progressMarks.Clear ();
			var grp = CreateMoveAndGrowAnimation (progressLayer, newFraction);

			SetProgressValue (newFraction);

			AttachFadeoutAnimation (progressLayer, grp, () => {
				if (oldFraction < 1 && inProgress) {
					if (progressMarks.Count != 0) {
						StartProgress (progressMarks.Peek ());
					} else {
						inProgress = false;
					}
					return false;
				}
				return true;
			});
		}

		const double frameAutoPulseWidth = 100;

		public void StartProgressAutoPulse ()
		{
			var move = CreateAutoPulseAnimation ();
			AttachFadeoutAnimation (progressLayer, move, () => true);
		}
	}

	class CancelButton : NSButton, INSAccessibilityButton
	{
		readonly NSImage stopIcon = MultiResImage.CreateMultiResImage ("status-stop-16", string.Empty);

		public CancelButton ()
		{
			Image = stopIcon;
			Hidden = true;
			Bordered = false;
			ImagePosition = NSCellImagePosition.ImageOnly;
			SetButtonType (NSButtonType.MomentaryChange);
			AddTrackingArea (new NSTrackingArea (CGRect.Empty, NSTrackingAreaOptions.MouseEnteredAndExited | NSTrackingAreaOptions.ActiveAlways | NSTrackingAreaOptions.InVisibleRect, this, null));

			AccessibilityHelp = GettextCatalog.GetString ("Cancel the current operation");
			AccessibilityTitle = GettextCatalog.GetString ("Cancel");

			var nsa = (INSAccessibility) this;
			nsa.AccessibilityIdentifier = "MainToolbar.StatusDisplay.Cancel";
		}

		string INSAccessibilityButton.AccessibilityLabel {
			get {
				return GettextCatalog.GetString ("Cancel");
			}
		}

		public override bool AcceptsFirstResponder ()
		{
			return true;
		}
	}

	[Register]
	class StatusBar : NSFocusButton, MonoDevelop.Ide.ITestableStatusBar
	{
		public enum MessageType
		{
			Ready,
			Information,
			Warning,
			Error,
		}

		const string ProgressLayerFadingId = "ProgressLayerFading";
		const string growthAnimationKey = "bounds";
		StatusBarContextHandler ctxHandler;
		string text;
		MessageType messageType;
		NSColor textColor;
		NSImage image;
		IconId icon;
		AnimatedIcon iconAnimation;
		IDisposable xwtAnimation;
		readonly BuildResultsView buildResults;
		readonly CancelButton cancelButton;

		SearchBar searchBar;
		internal SearchBar SearchBar {
			get => searchBar;
			set {
				searchBar = value;
				cancelButton.NextKeyView = value;
			}
		}

		NSAttributedString GetStatusString (string text, NSColor color)
		{
			nfloat fontSize = NSFont.SystemFontSize;
			if (Window != null && Window.Screen != null) {
				fontSize -= Window.Screen.BackingScaleFactor == 2 ? 2 : 1;
			} else {
				fontSize -= 1;
			}

			return new NSAttributedString (text, new NSStringAttributes {
				ForegroundColor = color,
				ParagraphStyle = new NSMutableParagraphStyle {
					HeadIndent = imageView.Frame.Width,
					LineBreakMode = NSLineBreakMode.TruncatingMiddle,
				},
				Font = NSFont.SystemFontOfSize (fontSize),
			});
		}

		readonly NSImageView imageView = new NSImageView {
			ImageFrameStyle = NSImageFrameStyle.None,
			Editable = false,
		};

		readonly NSTextField textField = new NSTextField {
			AllowsEditingTextAttributes = true,
			Bordered = false,
			DrawsBackground = false,
			Bezeled = false,
			Editable = false,
			Selectable = false,
		};
		NSTrackingArea textFieldArea;
		ProgressView progressView;

		TaskEventHandler updateHandler;
		public StatusBar ()
		{
			var nsa = (INSAccessibility)this;

			// Pretend that this button is a Group
			AccessibilityRole = NSAccessibilityRoles.GroupRole;
			nsa.AccessibilityIdentifier = "MainToolbar.StatusDisplay";

			Cell = new ColoredButtonCell ();
			BezelStyle = NSBezelStyle.TexturedRounded;
			Title = "";
			Enabled = false;

			LoadStyles ();

			// We don't need to resize the Statusbar here as a style change will trigger a complete relayout of the Awesomebar
			Ide.Gui.Styles.Changed += LoadStyles;

			textField.Cell = new VerticallyCenteredTextFieldCell (0f);
			textField.Cell.StringValue = "";

			textField.AccessibilityRole = NSAccessibilityRoles.StaticTextRole;
			textField.AccessibilityEnabled = true;
			textField.AccessibilityHelp = GettextCatalog.GetString ("Status of the current operation");

			var tfNSA = (INSAccessibility)textField;
			tfNSA.AccessibilityIdentifier = "MainToolbar.StatusDisplay.Status";

			UpdateApplicationNamePlaceholderText ();

			// The rect is empty because we use InVisibleRect to track the whole of the view.
			textFieldArea = new NSTrackingArea (CGRect.Empty, NSTrackingAreaOptions.MouseEnteredAndExited | NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.InVisibleRect, this, null);
			textField.AddTrackingArea (textFieldArea);

			imageView.Frame = new CGRect (0.5, 0, 0, 0);
			imageView.Image = ImageService.GetIcon (Stock.StatusSteady).ToNSImage ();

			// Hide this image from accessibility
			imageView.AccessibilityElement = false;

			buildResults = new BuildResultsView ();
			buildResults.Hidden = true;

			cancelButton = new CancelButton ();
			cancelButton.Activated += (o, e) => {
				cts?.Cancel ();
			};

			NextKeyView = cancelButton;

			ctxHandler = new StatusBarContextHandler (this);

			updateHandler = delegate {
				int ec = 0, wc = 0;

				foreach (var t in IdeServices.TaskService.Errors) {
					if (t.Severity == TaskSeverity.Error)
						ec++;
					else if (t.Severity == TaskSeverity.Warning)
						wc++;
				}

				Runtime.RunInMainThread (delegate {
					buildResults.Hidden = (ec == 0 && wc == 0);
					buildResults.ResultCount = ec > 0 ? ec : wc;
					buildResults.Type = ec > 0 ? BuildResultsView.ResultsType.Error : BuildResultsView.ResultsType.Warning;

					buildImageId = ec > 0 ? "md-status-error-count" : "md-status-warning-count";
					buildResults.IconImage = ImageService.GetIcon (buildImageId, Gtk.IconSize.Menu).ToNSImage ();

					RepositionStatusIcons ();
				});
			};

			updateHandler (null, null);

			IdeServices.TaskService.Errors.TasksAdded += updateHandler;
			IdeServices.TaskService.Errors.TasksRemoved += updateHandler;
			BrandingService.ApplicationNameChanged += ApplicationNameChanged;

			AddSubview (cancelButton);
			AddSubview (buildResults);
			AddSubview (imageView);
			AddSubview (textField);

			progressView = new ProgressView ();
			AddSubview (progressView);

			var newChildren = new NSObject [] {
				textField, buildResults, progressView
			};
			AccessibilityChildren = newChildren;
		}

		void UpdateApplicationNamePlaceholderText ()
		{
			textField.Cell.PlaceholderAttributedString = GetStatusString (BrandingService.ApplicationLongName, ColorForType (MessageType.Ready));

			var nsa = (INSAccessibility)textField;
			nsa.AccessibilityValue = new NSString (BrandingService.ApplicationLongName);
		}

		void ApplicationNameChanged (object sender, EventArgs e)
		{
			UpdateApplicationNamePlaceholderText ();
		}

		public override void DidChangeBackingProperties ()
		{
			base.DidChangeBackingProperties ();
			ReconstructString ();
			RepositionContents ();
		}

		void LoadStyles (object sender = null, EventArgs args = null)
		{
			Appearance = IdeTheme.GetAppearance ();

			UpdateApplicationNamePlaceholderText ();
			textColor = ColorForType (messageType);
			ReconstructString ();
		}

		protected override void Dispose (bool disposing)
		{
			IdeServices.TaskService.Errors.TasksAdded -= updateHandler;
			IdeServices.TaskService.Errors.TasksRemoved -= updateHandler;
			Ide.Gui.Styles.Changed -= LoadStyles;
			BrandingService.ApplicationNameChanged -= ApplicationNameChanged;
			base.Dispose (disposing);
		}

		static void DrawSeparator (nfloat x, CGRect dirtyRect)
		{
			var sepRect = new CGRect (x - 6.5, MacSystemInformation.OsVersion >= MacSystemInformation.ElCapitan ? 4 : 3, 1, 16);
			if (sepRect.IntersectsWith (dirtyRect)) {
				NSColor.LightGray.SetFill ();
				NSBezierPath.FillRect (sepRect);
			}
		}

		public override void DrawRect (CGRect dirtyRect)
		{
			base.DrawRect (dirtyRect);

			if (statusIcons.Count != 0 && !buildResults.Hidden)
				DrawSeparator (LeftMostStatusItemX (), dirtyRect);

			if (statusIcons.Count != 0 || !buildResults.Hidden) {
				if (cancelButton.Hidden)
					return;

				DrawSeparator (LeftMostBuildResultX (), dirtyRect);
			}
		}

		public override void ViewDidMoveToWindow ()
		{
			base.ViewDidMoveToWindow ();

			ReconstructString ();
			RepositionContents ();
		}

		NSImage statusReadyImage = ImageService.GetIcon (Stock.StatusSteady).ToNSImage ();
		void ReconstructString ()
		{
			var updatePopover = popoverForStatus && popover != null;
			if (string.IsNullOrEmpty (text)) {
				textField.AttributedStringValue = new NSAttributedString ("");
				UpdateApplicationNamePlaceholderText ();
				imageView.Image = statusReadyImage;
				if (updatePopover) {
					DestroyPopover (null, null);
				}
			} else {
				textField.AttributedStringValue = GetStatusString (text, textColor);
				imageView.Image = image;
				if (updatePopover) {
					DestroyPopover (null, null);

					// Window will be null if the StatusBar has been removed from its parent
					// In that case we want to destroy the popover, but we don't want to show
					// it again
					if (Window != null) {
						ShowPopoverForStatusBar ();
					}
				}
			}
		}

		// Used by AutoTest.
		string [] ITestableStatusBar.CurrentIcons => statusIcons.Select (x => x.ToolTip).ToArray ();
		string ITestableStatusBar.CurrentText => text;

		readonly List<StatusIcon> statusIcons = new List<StatusIcon> ();

		internal void RemoveStatusIcon (StatusIcon icon)
		{
			// For keyboard focus the icons are the reverse of the order they're stored in the list
			// because they're displayed in order right to left
			var index = statusIcons.IndexOf (icon);
			if (index != -1) {
				if (index == statusIcons.Count - 1) {
					cancelButton.NextKeyView = statusIcons.Count > 1 ? (NSView)statusIcons[index - 1] : (NSView)SearchBar;
				} else {
					var previous = statusIcons[index + 1];
					var next = index > 0 ? (NSView)statusIcons[index - 1] : (NSView)cancelButton;

					previous.NextKeyView = next;
				}
			}

			statusIcons.Remove (icon);

			icon.Entered -= ShowPopoverForIcon;
			icon.Exited -= DestroyPopover;
			icon.Clicked -= DestroyPopover;

			if (!popoverForStatus && popover != null)
				DestroyPopover (null, null);

			RepositionStatusIcons ();
		}

		nfloat LeftMostStatusItemX ()
		{
			if (statusIcons.Count == 0) {
				return Frame.Width;
			}

			return statusIcons.Last ().Frame.X;
		}

		nfloat LeftMostBuildResultX ()
		{
			if (buildResults.Hidden)
				return LeftMostStatusItemX ();

			return buildResults.Frame.X;
		}

		nfloat DrawSeparatorIfNeededBuildResults (nfloat right)
		{
			NeedsDisplay = true;

			if (statusIcons.Count == 0) {
				return right;
			}

			return right - 12;
		}

		nfloat DrawSeparatorIfNeededCancelButton (nfloat right)
		{
			NeedsDisplay = true;

			if (!buildResults.Hidden)
				return buildResults.Frame.X - 12;

			if (statusIcons.Count == 0)
				return right;

			return right - 12;
		}

		IconId buildImageId;

		void PositionBuildResults (nfloat right)
		{
			right = DrawSeparatorIfNeededBuildResults (right);
			right -= buildResults.Frame.Width;
			buildResults.SetFrameOrigin (new CGPoint (right, buildResults.Frame.Y));
		}

		void PositionCancelButton (nfloat right)
		{
			right = DrawSeparatorIfNeededCancelButton (right);
			right -= cancelButton.Frame.Width;
			cancelButton.SetFrameOrigin (new CGPoint (right, cancelButton.Frame.Y));
		}

		internal void RepositionStatusIcons ()
		{
			nfloat right = Frame.Width - 6;

			foreach (var item in statusIcons) {
				right -= item.Bounds.Width + 1;
				item.Frame = new CGRect (right, MacSystemInformation.OsVersion >= MacSystemInformation.ElCapitan ? 4 : 3, item.Bounds.Width, item.Bounds.Height);
			}

			PositionBuildResults (right);
			PositionCancelButton (right);

			right -= 2;

			if (!cancelButton.Hidden) { // We have a cancel button.
				right = cancelButton.Frame.X;
			} else if (!buildResults.Hidden) { // We have a build result layer.
				right = buildResults.Frame.X;
			}

			textField.SetFrameSize (new CGSize (right - 3 - textField.Frame.Left, Frame.Height));
		}

		public StatusBarIcon ShowStatusIcon (Xwt.Drawing.Image pixbuf)
		{
			var statusIcon = new StatusIcon (this) {
				Image = pixbuf,
			};
			statusIcons.Add (statusIcon);

			if (statusIcons.Count == 1) {
				statusIcon.NextKeyView = SearchBar;
			} else {
				var previousIcon = statusIcons[statusIcons.Count - 2];
				statusIcon.NextKeyView = previousIcon;
			}
			cancelButton.NextKeyView = statusIcon;

			statusIcon.Entered += ShowPopoverForIcon;
			statusIcon.Exited += DestroyPopover;

			// We need to destroy the popover otherwise the window doesn't come up correctly
			statusIcon.Clicked += DestroyPopover;

			AddSubview (statusIcon);
			RepositionStatusIcons ();

			return statusIcon;
		}

		public StatusBarContext CreateContext ()
		{
			return ctxHandler.CreateContext ();
		}

		public void ShowReady ()
		{
			ShowMessage (null, "", false, MessageType.Ready);
			SetMessageSourcePad (null);
		}

		static Pad sourcePad;
		public void SetMessageSourcePad (Pad pad)
		{
			sourcePad = pad;
		}

		public void ShowError (string error)
		{
			ShowMessage (Stock.StatusError, error, false, MessageType.Error);

		}

		public void ShowWarning (string warning)
		{
			ShowMessage (Stock.StatusWarning, warning, false, MessageType.Warning);
		}

		public void ShowMessage (string message)
		{
			ShowMessage (null, message, false, MessageType.Information);
		}

		public void ShowMessage (string message, bool isMarkup)
		{
			ShowMessage (null, message, true, MessageType.Information);
		}

		public void ShowMessage (IconId image, string message)
		{
			ShowMessage (image, message, false, MessageType.Information);
		}

		public void ShowMessage (IconId image, string message, bool isMarkup)
		{
			ShowMessage (image, message, isMarkup, MessageType.Information);
		}

		public void ShowMessage (IconId image, string message, bool isMarkup, MessageType statusType)
		{
			Runtime.AssertMainThread ();

			bool changed = LoadText (message, isMarkup, statusType);
			LoadPixbuf (image);
			if (changed) {
				ReconstructString ();
				// announce new status if vo/a11y is enabled
				if (IdeServices.DesktopService.AccessibilityInUse) {
					IdeServices.DesktopService.MakeAccessibilityAnnouncement (text);
				}
			}
		}

		bool LoadText (string message, bool isMarkup, MessageType statusType)
		{
			message = message ?? "";
			message = message.Replace (Environment.NewLine, " ").Replace ("\n", " ").Trim ();

			if (message == text)
				return false;

			text = message;
			messageType = statusType;
			textColor = ColorForType (statusType);

			var nsa = (INSAccessibility)textField;
			nsa.AccessibilityValue = new NSString (message);

			return true;
		}

		NSColor ColorForType (MessageType messageType)
		{
			switch (messageType) {
				case MessageType.Error:
					return Styles.StatusErrorTextColor.ToNSColor ();
				case MessageType.Warning:
					return Styles.StatusWarningTextColor.ToNSColor ();
				case MessageType.Ready:
					return Styles.StatusReadyTextColor.ToNSColor ();
				default:
					return Styles.BaseForegroundColor.ToNSColor ();
			}
		}

		static bool iconLoaded;
		void LoadPixbuf (IconId iconId)
		{
			// We dont need to load the same image twice
			if (icon == iconId && iconLoaded)
				return;

			icon = iconId;
			iconAnimation = null;

			// clean up previous running animation
			if (xwtAnimation != null) {
				xwtAnimation.Dispose ();
				xwtAnimation = null;
			}

			// if we have nothing, use the default icon
			if (iconId == IconId.Null)
				iconId = Stock.StatusSteady;

			// load image now
			if (ImageService.IsAnimation (iconId, Gtk.IconSize.Menu)) {
				iconAnimation = ImageService.GetAnimatedIcon (iconId, Gtk.IconSize.Menu);
				image = iconAnimation.FirstFrame.ToNSImage ();
				xwtAnimation = iconAnimation.StartAnimation (p => {
					image = p.ToNSImage ();
					ReconstructString ();
				});
			} else {
				image = ImageService.GetIcon (iconId).ToNSImage ();
			}

			iconLoaded = true;
		}

		public void BeginProgress (string name)
		{
			BeginProgress (null, name);
		}

		public void BeginProgress (IconId image, string name)
		{
			EndProgress ();
			ShowMessage (image, name);

			if (AutoPulse)
				progressView.StartProgressAutoPulse ();
			else
				progressView.BeginProgress ();
		}


		public void SetProgressFraction (double work)
		{
			progressView.SetProgressFraction (work);
		}

		public void EndProgress ()
		{
			progressView.EndProgress ();
		}

		public void Pulse ()
		{
			// Nothing to do here.
		}

		public MonoDevelop.Ide.StatusBar MainContext {
			get {
				return ctxHandler.MainContext;
			}
		}

		public bool AutoPulse {
			get;
			set;
		}

		static NSAttributedString GetPopoverString (string text)
		{
			return new NSAttributedString (text, new NSStringAttributes {
				ParagraphStyle = new NSMutableParagraphStyle {
					Alignment = NSTextAlignment.Center,
				},
				Font = NSFont.SystemFontOfSize (NSFont.SystemFontSize - 1),
			});
		}

		NSPopover popover;
		bool popoverForStatus;

		void CreatePopoverCommon (nfloat width, string text)
		{
			popover = new NSPopover {
				ContentViewController = new NSViewController (null, null),
				Animates = false
			};

			var attrString = GetPopoverString (text);

			var height = attrString.BoundingRectWithSize (new CGSize (width, nfloat.MaxValue),
				NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin).Height;
			
			popover.ContentViewController.View = new NSTextField {
				Frame = new CGRect (0, 0, width, height + 14),
				DrawsBackground = false,
				Bezeled = true,
				Editable = false,
				Cell = new VerticallyCenteredTextFieldCell (yOffset: -1),
			};
			((NSTextField)popover.ContentViewController.View).AttributedStringValue = attrString;
		}

		bool CreatePopoverForIcon (StatusBarIcon icon)
		{
			string tooltip = icon.ToolTip;
			if (tooltip == null)
				return false;

			CreatePopoverCommon (230, tooltip);
			return true;
		}

		void CreatePopoverForStatusBar ()
		{
			CreatePopoverCommon (Frame.Width, textField.AttributedStringValue.Value);
		}

		void ShowPopoverForIcon (object sender, EventArgs args)
		{
			if (popover != null)
				return;

			popoverForStatus = false;
			var icon = (StatusIcon) sender;

			if (!CreatePopoverForIcon (icon))
				return;

			popover.Show (icon.Frame, this, NSRectEdge.MinYEdge);
		}

		void ShowPopoverForStatusBar ()
		{
			if (popover != null)
				return;

			popoverForStatus = true;
			CreatePopoverForStatusBar ();
			popover.Show (textField.Frame, this, NSRectEdge.MinYEdge);
		}

		void DestroyPopover (object sender, EventArgs args)
		{
			if (popover != null)
				popover.Close ();
			popover = null;
		}
			
		public override void MouseEntered (NSEvent theEvent)
		{
			base.MouseEntered (theEvent);

			var width = textField.AttributedStringValue.BoundingRectWithSize (new CGSize (nfloat.MaxValue, textField.Frame.Height),
				NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin).Width;
			if (width > textField.Frame.Width) {
				ShowPopoverForStatusBar ();
			}
		}

		public override void MouseExited (NSEvent theEvent)
		{
			base.MouseExited (theEvent);
			DestroyPopover (null, null);
		}

		internal static Xwt.PointerButton NSEventButtonToXwt (NSEvent theEvent)
		{
			Xwt.PointerButton button = Xwt.PointerButton.Left;
			switch ((NSEventType)(long)theEvent.ButtonNumber) {
			case NSEventType.LeftMouseDown:
				button = Xwt.PointerButton.Left;
				break;
			case NSEventType.RightMouseDown:
				button = Xwt.PointerButton.Right;
				break;
			case NSEventType.OtherMouseDown:
				button = Xwt.PointerButton.Middle;
				break;
			}

			return button;
		}

		public override void MouseDown (NSEvent theEvent)
		{
			base.MouseDown (theEvent);

			CGPoint location = ConvertPointFromView (theEvent.LocationInWindow, null);
			if (textField.IsMouseInRect (location, textField.Frame) && sourcePad != null) {
				sourcePad.BringToFront (true);
			}
		}

		bool isFirstResponder;
		public override void KeyDown (NSEvent theEvent)
		{
			if (isFirstResponder && (theEvent.KeyCode == (ushort) KeyCodes.Enter || theEvent.KeyCode == (ushort)KeyCodes.Space)) {
				sourcePad?.BringToFront (true);
				return;
			}
			base.KeyDown (theEvent);
		}

		public override bool AcceptsFirstResponder ()
		{
			return true;
		}

		public override bool BecomeFirstResponder ()
		{
			isFirstResponder = true;
			return true;
		}

		public override bool ResignFirstResponder ()
		{
			isFirstResponder = false;
			return base.ResignFirstResponder ();
		}

		public override CGRect Frame {
			get {
				return base.Frame;
			}
			set {
				base.Frame = value;
				RepositionContents ();
			}
		}

		CancellationTokenSource cts;
		public void SetCancellationTokenSource (CancellationTokenSource source)
		{
			cts = source;

			bool willHide = cts == null;
			cancelButton.ToolTip = willHide ? string.Empty : GettextCatalog.GetString ("Cancel operation");
			if (cancelButton.Hidden != willHide) {
				cancelButton.Hidden = willHide;
				RepositionStatusIcons ();
			}
		}

		void RepositionContents ()
		{
			nfloat yOffset = 0f;
			if (Window != null && Window.Screen != null && Window.Screen.BackingScaleFactor == 2) {
				yOffset = 0.5f;
			}

			imageView.Frame = new CGRect (6, 0, 16, Frame.Height);
			textField.Frame = new CGRect (imageView.Frame.Right, yOffset, Frame.Width - 16, Frame.Height);

			buildResults.Frame = new CGRect (buildResults.Frame.X, buildResults.Frame.Y, buildResults.Frame.Width, Frame.Height);
			cancelButton.Frame = new CGRect (cancelButton.Frame.X, cancelButton.Frame.Y, 16, Frame.Height);
			RepositionStatusIcons ();

			progressView.Frame = new CGRect (0.5f, Frame.Height - 2f, Frame.Width - 2, 2);
		}
	}
}