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

RichTextViewBackend.cs « Xwt.GtkBackend « Xwt.Gtk - github.com/mono/xwt.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 88977cbde547392eb01760aae38925e1bd1a3eeb (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
//
// RichTextViewBackend.cs
//
// Author:
//       Jérémie Laval <jeremie.laval@xamarin.com>
//
// Copyright (c) 2012 Xamarin, 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 Xwt;
using Xwt.Backends;
using Xwt.Drawing;

namespace Xwt.GtkBackend
{
	public class RichTextViewBackend : WidgetBackend, IRichTextViewBackend
	{
		Gtk.TextTagTable table;

		double ParagraphSpacing {
			get {
				var font = Font as Pango.FontDescription;
				var size = font.SizeIsAbsolute ? font.Size : font.Size / Pango.Scale.PangoScale;
				return size / 2; // default to 1/2 of the font/line size
			}
		}

		public RichTextViewBackend ()
		{
			Widget = new GtkTextView ();
			Widget.Show ();
			ReadOnly = true;
			Widget.WrapMode = Gtk.WrapMode.Word;
			InitTagTable ();
		}

		void InitTagTable ()
		{
			table = new Gtk.TextTagTable ();
			table.Add (new Gtk.TextTag ("bold") {
				Weight = Pango.Weight.Bold
			});
			table.Add (new Gtk.TextTag ("italic") {
				Style = Pango.Style.Italic
			});
			table.Add (new Gtk.TextTag ("tt") {
				Family = "Monospace"
			});
			table.Add (new Gtk.TextTag ("li") {
				LeftMargin = 14
			});
			table.Add (new Gtk.TextTag ("h1") {
				Weight = Pango.Weight.Bold,
				Scale = Pango.Scale.XXLarge
			});
			table.Add (new Gtk.TextTag ("h2") {
				Weight = Pango.Weight.Bold,
				Scale = Pango.Scale.XLarge
			});
			table.Add (new Gtk.TextTag ("h3") {
				Weight = Pango.Weight.Bold,
				Scale = Pango.Scale.Large
			});
			table.Add (new Gtk.TextTag ("h4") {
				Scale = Pango.Scale.Large
			});
			table.Add (new Gtk.TextTag ("pre") {
				Family = "Monospace",
				Indent = 14,
				WrapMode = Gtk.WrapMode.None
			});
			table.Add (new Gtk.TextTag ("p") {
				SizePoints = Math.Max (LineSpacing, ParagraphSpacing),
			});
		}

		private new GtkTextView Widget {
			get {
				return (GtkTextView)base.Widget;
			}
			set {
				base.Widget = value;
			}
		}

		public override void EnableEvent (object eventId)
		{
			base.EnableEvent (eventId);
			if (eventId is RichTextViewEvent) {
				switch ((RichTextViewEvent) eventId) {
				case RichTextViewEvent.NavigateToUrl:
					Widget.NavigateToUrl += HandleNavigateToUrl;
					break;
				}
			}
		}

		public override void DisableEvent (object eventId)
		{
			base.DisableEvent (eventId);
			if (eventId is RichTextViewEvent) {
				switch ((RichTextViewEvent) eventId) {
				case RichTextViewEvent.NavigateToUrl:
					Widget.NavigateToUrl -= HandleNavigateToUrl;
					break;
				}
			}
		}

		public IRichTextBuffer CreateBuffer ()
		{
			return new RichTextBuffer (table);
		}

		public void SetBuffer (IRichTextBuffer buffer)
		{
			var buf = buffer as RichTextBuffer;
			if (buf == null)
				throw new ArgumentException ("Passed buffer is of incorrect type", "buffer");

			Widget.Buffer = buf;
		}

		public IRichTextBuffer CurrentBuffer {
			get {
				return Widget.Buffer as RichTextBuffer;
			}
		}

		public bool ReadOnly { 
			get { 
				return !Widget.Editable;
			}
			set {
				Widget.Editable = !value;
				Widget.CursorVisible = !value;
			}
		}

		public bool Selectable {
			get {
				return Widget.Selectable;
			}
			set {
				Widget.Selectable = value;
			}
		}

		public int LineSpacing {
			get {
				return Widget.PixelsInsideWrap;
			}
			set {
				Widget.PixelsInsideWrap = value;
				Widget.PixelsBelowLines = value;
				var tag = table.Lookup ("p");
				tag.SizePoints = Math.Max (value, ParagraphSpacing);
			}
		}

		public override object Font {
			get {
				return base.Font;
			}
			set {
				base.Font = value;
				var tag = table.Lookup ("p");
				tag.SizePoints = Math.Max (LineSpacing, ParagraphSpacing);
			}
		}

		protected override void OnSetBackgroundColor(Drawing.Color color)
		{
			base.OnSetBackgroundColor(color);
			Widget.SetBackgroundColor(Gtk.StateType.Normal, color);
			Widget.SetBackgroundColor(Gtk.StateType.Insensitive, color);
			#if !XWT_GTK3
			Widget.ModifyBase(Gtk.StateType.Normal, color.ToGtkValue());
			Widget.ModifyBase(Gtk.StateType.Insensitive, color.ToGtkValue());
			#endif
		}

		void HandleNavigateToUrl (object sender, NavigateToUrlEventArgs e)
		{
			ApplicationContext.InvokeUserCode (delegate {
				((IRichTextViewEventSink)EventSink).OnNavigateToUrl (e.Uri);
			});
		}

		class Link {
			public string Title;
			public Uri Href;
			public Gtk.TextMark StartMark;
		}

		class RichTextBuffer : Gtk.TextBuffer, IRichTextBuffer
		{
			const string NewLine = "\n";

			bool needsParagraphBreak;
			bool needsListBreak;

			void BreakParagraph ()
			{
				if (needsParagraphBreak) {
					var iterEnd = EndIter;
					Insert (ref iterEnd, NewLine);

					var m = CreateMark (null, iterEnd, true);
					Insert (ref iterEnd, NewLine);
					var iterStart = GetIterAtMark (m);
					ApplyTag ("p", iterStart, iterEnd);
					DeleteMark (m);

					needsParagraphBreak = false;
					return;
				}
			}

			void BreakList ()
			{
				if (needsListBreak) {
					var end = EndIter;
					Insert (ref end, NewLine);
					needsListBreak = false;
					return;
				}
			}

			public Dictionary<Gtk.TextTag, Link> Links {
				get; private set;
			}

			struct StartState {
				public Gtk.TextMark Mark;
				public int Data;
				public StartState (Gtk.TextMark mark, int data)
				{
					Mark = mark;
					Data = data;
				}
			}
			Stack<StartState> openHeaders;
			Stack<Link> openLinks;

			public RichTextBuffer (Gtk.TextTagTable table) : base (table)
			{
				Links = new Dictionary<Gtk.TextTag, Link> ();
				openHeaders = new Stack<StartState> ();
				openLinks = new Stack<Link> ();
			}

			public string PlainText {
				get {
					return Text;
				}
			}

			public void EmitText (string text, RichTextInlineStyle style)
			{
				var iterEnd = EndIter;
				var m = CreateMark (null, iterEnd, true);
				Insert (ref iterEnd, text);
				var iterStart = GetIterAtMark (m);

				if ((style & RichTextInlineStyle.Bold) != 0)
					ApplyTag ("bold", iterStart, iterEnd);

				if ((style & RichTextInlineStyle.Italic) != 0)
					ApplyTag ("italic", iterStart, iterEnd);

				if ((style & RichTextInlineStyle.Monospace) != 0)
					ApplyTag ("tt", iterStart, iterEnd);

				DeleteMark (m);
			}

			public void EmitStartHeader (int level)
			{
				BreakParagraph ();
				var iter = EndIter;
				openHeaders.Push (new StartState (CreateMark (null, iter, true), level));
			}

			public void EmitEndHeader ()
			{
				var start = openHeaders.Pop ();
				var iterStart = GetIterAtMark (start.Mark);
				var iterEnd = EndIter;
				ApplyTag ("h" + start.Data, iterStart, iterEnd);
				DeleteMark (start.Mark);
				needsParagraphBreak = true;
			}

			public void EmitStartParagraph (int indentLevel)
			{
				BreakParagraph ();
				//FIXME: support indentLevel
			}

			public void EmitEndParagraph ()
			{
				needsParagraphBreak = true;
			}

			public void EmitOpenList ()
			{
				BreakParagraph ();
			}

			public void EmitOpenBullet ()
			{
				BreakList ();
				var iter = EndIter;
				InsertWithTagsByName (ref iter, "• ", "li");
			}

			public void EmitCloseBullet ()
			{
				needsListBreak = true;
			}

			public void EmitCloseList ()
			{
				needsListBreak = false;
				needsParagraphBreak = true;
			}

			public void EmitStartLink (string href, string title)
			{
				var iter = EndIter;

				Uri uri;
				if (!Uri.TryCreate (href, UriKind.RelativeOrAbsolute, out uri))
					uri = null;

				openLinks.Push (new Link ()
				{
					Title = title,
					Href = uri,
					StartMark = CreateMark (null, iter, true),
				});
			}

			public void EmitEndLink ()
			{
				var link = openLinks.Pop ();
				var tag = new Gtk.TextTag (null);
				tag.Underline = Pango.Underline.Single;
				tag.ForegroundGdk = Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToGtkValue ();
				TagTable.Add (tag);
				ApplyTag (tag, GetIterAtMark (link.StartMark), EndIter);
				Links[tag] = link;
			}

			public void EmitCodeBlock (string code)
			{
				BreakParagraph ();
				var iter = EndIter;
				InsertWithTagsByName (ref iter, code.Trim (), "pre");
				needsParagraphBreak = true;
			}

			public void EmitHorizontalRuler ()
			{
				//FIXME
			}

			public void EmitText (FormattedText markup)
			{
				var iterEnd = EndIter;
				var textmark = CreateMark (null, iterEnd, true);
				Insert (ref iterEnd, markup.Text);

				foreach (var attr in markup.Attributes) {
					var iterEndAttr = GetIterAtMark (textmark);
					iterEndAttr.ForwardChars (attr.StartIndex);
					var attrStart = CreateMark (null, iterEndAttr, true);
					iterEndAttr.ForwardChars (attr.Count);

					var tag = new Gtk.TextTag (null);

					if (attr is BackgroundTextAttribute) {
						var xa = (BackgroundTextAttribute)attr;
						tag.BackgroundGdk = xa.Color.ToGtkValue ();
					} else if (attr is ColorTextAttribute) {
						var xa = (ColorTextAttribute)attr;
						tag.ForegroundGdk = xa.Color.ToGtkValue ();
					} else if (attr is FontWeightTextAttribute) {
						var xa = (FontWeightTextAttribute)attr;
						tag.Weight = (Pango.Weight)(int)xa.Weight;
					} else if (attr is FontStyleTextAttribute) {
						var xa = (FontStyleTextAttribute)attr;
						tag.Style = (Pango.Style)(int)xa.Style;
					} else if (attr is UnderlineTextAttribute) {
						var xa = (UnderlineTextAttribute)attr;
						tag.Underline = xa.Underline ? Pango.Underline.Single : Pango.Underline.None;
					} else if (attr is StrikethroughTextAttribute) {
						var xa = (StrikethroughTextAttribute)attr;
						tag.Strikethrough = xa.Strikethrough;
					} else if (attr is FontTextAttribute) {
						var xa = (FontTextAttribute)attr;
						tag.FontDesc = (Pango.FontDescription)Toolkit.GetBackend (xa.Font);
					} else if (attr is LinkTextAttribute) {
						var xa = (LinkTextAttribute)attr;
						Uri uri = xa.Target;
						if (uri == null)
							Uri.TryCreate (markup.Text.Substring (xa.StartIndex, xa.Count), UriKind.RelativeOrAbsolute, out uri);
						var link = new Link { Href = uri };
						tag.Underline = Pango.Underline.Single;
						tag.ForegroundGdk = Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToGtkValue ();
						Links [tag] = link;
					}

					TagTable.Add (tag);
					ApplyTag (tag, GetIterAtMark (attrStart), iterEndAttr);
					DeleteMark (attrStart);
				}
				DeleteMark (textmark);
			}
		}

		class GtkTextView : Gtk.TextView
		{
			bool selectable = true;
			Link activeLink;
			Gdk.Cursor defaultCursor, handCursor;

			public bool Selectable {
				get {
					return selectable;
				}
				set {
					selectable = value;
					UpdateBackground ();
				}
			}

			public new RichTextBuffer Buffer {
				get {
					return base.Buffer as RichTextBuffer;
				}
				set {
					var buffer = value as RichTextBuffer;
					if (buffer == null)
						throw new InvalidOperationException ();
					base.Buffer = buffer;
				}
			}

			public event EventHandler<NavigateToUrlEventArgs> NavigateToUrl;

			Gdk.Cursor DefaultCursor {
				get {
					if (defaultCursor == null)
						defaultCursor = new Gdk.Cursor (Gdk.CursorType.Xterm);
					return defaultCursor;
				}
			}

			Gdk.Cursor HandCursor {
				get {
					if (handCursor == null)
						handCursor = new Gdk.Cursor (Gdk.CursorType.Hand1);
					return handCursor;
				}
			}

			protected override bool OnMotionNotifyEvent (Gdk.EventMotion evnt)
			{
				Link link = GetLinkAtPos (evnt.X, evnt.Y);
				if (link != null) {
					if (activeLink == null) {
						TooltipText = link.Title;

						GetWindow (Gtk.TextWindowType.Text).Cursor = HandCursor;
					} else if (activeLink.Title != link.Title) {
						TooltipText = link.Title;
					}
					activeLink = link;
				} else if (activeLink != null) {
					activeLink = null;
					TooltipText = null;
					SetDefaultCursor ();
				}

				if (selectable)
					return base.OnMotionNotifyEvent (evnt);
				return false;
			}

			protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
			{
				if (selectable)
					return base.OnButtonPressEvent (evnt);
				return false;
			}

			protected override bool OnButtonReleaseEvent (Gdk.EventButton evnt)
			{
				if (NavigateToUrl != null && (PointerButton)evnt.Button == PointerButton.Left) {
					Link link = activeLink ?? GetLinkAtPos (evnt.X, evnt.Y);

					if (link?.Href != null)
						NavigateToUrl?.Invoke (this, new NavigateToUrlEventArgs (link.Href));
				}
				if (selectable)
					return base.OnButtonReleaseEvent (evnt);
				return false;
			}

			Link GetLinkAtPos (double mousex, double mousey)
			{
				int x, y;
				WindowToBufferCoords (Gtk.TextWindowType.Text, (int)mousex, (int)mousey, out x, out y);
				var iter = GetIterAtLocation (x, y);
				if (Buffer != null) {
					foreach (var l in Buffer.Links) {
						if (iter.HasTag (l.Key)) {
							return l.Value;
						}
					}
				}
				return null;
			}

			protected override void OnStateChanged (Gtk.StateType previous_state)
			{
				base.OnStateChanged (previous_state);
				SetDefaultCursor ();
				UpdateBackground ();
			}

			protected override void OnGrabNotify (bool was_grabbed)
			{
				base.OnGrabNotify (was_grabbed);
				if (!was_grabbed)
					SetDefaultCursor ();
			}

			protected override void OnRealized ()
			{
				base.OnRealized ();
				SetDefaultCursor ();
				UpdateBackground ();
				UpdateLinkColor ();
			}

			protected override void OnStyleSet (Gtk.Style previous_style)
			{
				base.OnStyleSet (previous_style);
				UpdateLinkColor ();
			}

			void SetDefaultCursor ()
			{
				if (!IsRealized)
					return;
				Gdk.Cursor cursor = Sensitive && Selectable ? DefaultCursor : null;
				GetWindow (Gtk.TextWindowType.Text).Cursor = cursor;

			}

			void UpdateLinkColor ()
			{
				if (!IsRealized)
					return;
				var objColor = StyleGetProperty ("link-color");
				var color = Gdk.Color.Zero;
				if (objColor != null)
					color = (Gdk.Color) objColor;
				if (color.Equals (Gdk.Color.Zero))
					color = Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToGtkValue ();
				if (Buffer != null)
					foreach (var linkTag in Buffer.Links.Keys)
						linkTag.ForegroundGdk = color;
			}

			void UpdateBackground ()
			{
				if (!IsRealized)
					return;
				var state = Selectable ? State : Gtk.StateType.Insensitive;

				var bg = Style.Background (state);
				var bbg = Style.Base (state);

				GetWindow (Gtk.TextWindowType.Widget).Background = bg;
				GetWindow (Gtk.TextWindowType.Text).Background = bbg;
			}
		}
	}
}