-
Notifications
You must be signed in to change notification settings - Fork 277
/
TextTool.cs
1222 lines (946 loc) · 34.7 KB
/
TextTool.cs
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
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
// //
// Ported to Pinta by: Olivier Dufour <[email protected]> //
// Jonathan Pobst <[email protected]> //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading.Tasks;
using Cairo;
using Pango;
using Pinta.Core;
namespace Pinta.Tools;
public sealed class TextTool : BaseTool
{
// Variables for dragging
private PointD start_mouse_xy;
private PointI start_click_point;
private bool tracking;
private readonly Gdk.Cursor cursor_move = GdkExtensions.CursorFromName (Pinta.Resources.StandardCursors.Move);
private readonly Gdk.Cursor cursor_invalid = GdkExtensions.CursorFromName (Pinta.Resources.StandardCursors.NotAllowed);
private PointI click_point;
private bool is_editing;
private RectangleI old_cursor_bounds = RectangleI.Zero;
//This is used to temporarily store the UserLayer's and TextLayer's previous ImageSurface states.
private Cairo.ImageSurface? text_undo_surface;
private Cairo.ImageSurface? user_undo_surface;
private TextEngine? undo_engine;
// The last pre-editing string, if pre-editing is active.
private string? preedit_string;
// The selection from when editing started. This ensures that text doesn't suddenly disappear/appear
// if the selection changes before the text is finalized.
private DocumentSelection? selection;
private readonly Gtk.IMMulticontext im_context;
private readonly TextLayout layout;
private static RectangleI CurrentTextBounds {
get => PintaCore.Workspace.ActiveDocument.Layers.CurrentUserLayer.TextBounds;
set {
PintaCore.Workspace.ActiveDocument.Layers.CurrentUserLayer.PreviousTextBounds = PintaCore.Workspace.ActiveDocument.Layers.CurrentUserLayer.TextBounds;
PintaCore.Workspace.ActiveDocument.Layers.CurrentUserLayer.TextBounds = value;
}
}
private static TextEngine CurrentTextEngine {
get {
if (!PintaCore.Workspace.HasOpenDocuments)
throw new InvalidOperationException ("Attempting to get CurrentTextEngine when there are no open documents");
return PintaCore.Workspace.ActiveDocument.Layers.CurrentUserLayer.TextEngine;
}
}
private Pinta.Core.TextLayout CurrentTextLayout {
get {
if (layout.Engine != CurrentTextEngine)
layout.Engine = CurrentTextEngine;
return layout;
}
}
//While this is true, text will not be finalized upon Surface.Clone calls.
private bool ignore_clone_finalizations = false;
//Whether or not either (or both) of the Ctrl keys are pressed.
private bool ctrl_key = false;
//Store the most recent mouse position.
private PointI last_mouse_position = new (0, 0);
//Whether or not the previous TextTool mouse cursor shown was the normal one.
private bool previous_mouse_cursor_normal = true;
public override string Name
=> Translations.GetString ("Text");
private static string FinalizeName
=> Translations.GetString ("Text - Finalize");
public override string Icon
=> Pinta.Resources.Icons.ToolText;
public override Gdk.Key ShortcutKey
=> Gdk.Key.T;
public override int Priority
=> 35;
public override string StatusBarText
=> Translations.GetString ("Left click to place cursor, then type desired text. Text color is primary color.");
public override Gdk.Cursor DefaultCursor
=> GdkExtensions.CursorFromName (Pinta.Resources.StandardCursors.Text);
protected override bool ShowAntialiasingButton => true;
private readonly IWorkspaceService workspace;
private readonly IPaletteService palette;
private readonly LayerManager layers;
#region Constructor
public TextTool (IServiceProvider services) : base (services)
{
workspace = services.GetService<IWorkspaceService> ();
palette = services.GetService<IPaletteService> ();
layers = services.GetService<LayerManager> ();
im_context = Gtk.IMMulticontext.New ();
im_context.OnCommit += OnIMCommit;
im_context.OnPreeditStart += OnPreeditStart;
im_context.OnPreeditChanged += OnPreeditChanged;
im_context.OnPreeditEnd += OnPreeditEnd;
layout = new Pinta.Core.TextLayout ();
}
#endregion
#region ToolBar
// NRT - Created by OnBuildToolBar
private Gtk.Label font_label = null!;
private Gtk.FontButton font_button = null!;
private Gtk.ToggleButton bold_btn = null!;
private Gtk.ToggleButton italic_btn = null!;
private Gtk.ToggleButton underscore_btn = null!;
private Gtk.ToggleButton left_alignment_btn = null!;
private Gtk.ToggleButton center_alignment_btn = null!;
private Gtk.ToggleButton right_alignment_btn = null!;
private Gtk.Label fill_label = null!;
private ToolBarDropDownButton fill_button = null!;
private Gtk.Separator fill_sep = null!;
private Gtk.Separator outline_sep = null!;
private Gtk.SpinButton outline_width = null!;
private Gtk.Label outline_width_label = null!;
private const string FONT_SETTING = "text-font";
private const string BOLD_SETTING = "text-bold";
private const string ITALIC_SETTING = "text-italic";
private const string UNDERLINE_SETTING = "text-underline";
private const string ALIGNMENT_SETTING = "text-alignment";
private const string STYLE_SETTING = "text-style";
private const string OUTLINE_WIDTH_SETTING = "text-outline-width";
protected override void OnBuildToolBar (Gtk.Box tb)
{
base.OnBuildToolBar (tb);
if (font_label == null) {
string fontText = Translations.GetString ("Font");
font_label = Gtk.Label.New ($" {fontText}: ");
}
tb.Append (font_label);
if (font_button == null) {
font_button = new Gtk.FontButton {
UseSize = false,
UseFont = true,
CanFocus = false, // Default to Arial if possible.
Font = Settings.GetSetting (FONT_SETTING, "Arial 12"),
};
font_button.OnFontSet += HandleFontChanged;
}
tb.Append (font_button);
tb.Append (GtkExtensions.CreateToolBarSeparator ());
if (bold_btn == null) {
bold_btn = new Gtk.ToggleButton {
IconName = Pinta.Resources.StandardIcons.FormatTextBold,
TooltipText = Translations.GetString ("Bold"),
CanFocus = false,
Active = Settings.GetSetting (BOLD_SETTING, false),
};
bold_btn.OnToggled += HandleBoldButtonToggled;
}
tb.Append (bold_btn);
if (italic_btn == null) {
italic_btn = new Gtk.ToggleButton {
IconName = Pinta.Resources.StandardIcons.FormatTextItalic,
TooltipText = Translations.GetString ("Italic"),
CanFocus = false,
Active = Settings.GetSetting (ITALIC_SETTING, false),
};
italic_btn.OnToggled += HandleItalicButtonToggled;
}
tb.Append (italic_btn);
if (underscore_btn == null) {
underscore_btn = new Gtk.ToggleButton {
IconName = Pinta.Resources.StandardIcons.FormatTextUnderline,
TooltipText = Translations.GetString ("Underline"),
CanFocus = false,
Active = Settings.GetSetting (UNDERLINE_SETTING, false),
};
underscore_btn.OnToggled += HandleUnderscoreButtonToggled;
}
tb.Append (underscore_btn);
tb.Append (GtkExtensions.CreateToolBarSeparator ());
var alignment = (TextAlignment) Settings.GetSetting (ALIGNMENT_SETTING, (int) TextAlignment.Left);
if (left_alignment_btn == null) {
left_alignment_btn = new Gtk.ToggleButton {
IconName = Pinta.Resources.StandardIcons.FormatJustifyLeft,
TooltipText = Translations.GetString ("Left Align"),
CanFocus = false,
Active = alignment == TextAlignment.Left,
};
left_alignment_btn.OnToggled += HandleLeftAlignmentButtonToggled;
}
tb.Append (left_alignment_btn);
if (center_alignment_btn == null) {
center_alignment_btn = new Gtk.ToggleButton {
IconName = Pinta.Resources.StandardIcons.FormatJustifyCenter,
TooltipText = Translations.GetString ("Center Align"),
CanFocus = false,
Active = alignment == TextAlignment.Center,
};
center_alignment_btn.OnToggled += HandleCenterAlignmentButtonToggled;
}
tb.Append (center_alignment_btn);
if (right_alignment_btn == null) {
right_alignment_btn = new Gtk.ToggleButton {
IconName = Pinta.Resources.StandardIcons.FormatJustifyRight,
TooltipText = Translations.GetString ("Right Align"),
CanFocus = false,
Active = alignment == TextAlignment.Right,
};
right_alignment_btn.OnToggled += HandleRightAlignmentButtonToggled;
}
tb.Append (right_alignment_btn);
fill_sep ??= GtkExtensions.CreateToolBarSeparator ();
tb.Append (fill_sep);
if (fill_label == null) {
string textStyleText = Translations.GetString ("Text Style");
fill_label = Gtk.Label.New ($" {textStyleText}: ");
}
tb.Append (fill_label);
if (fill_button == null) {
fill_button = new ToolBarDropDownButton ();
fill_button.AddItem (Translations.GetString ("Normal"), Pinta.Resources.Icons.FillStyleFill, 0);
fill_button.AddItem (Translations.GetString ("Normal and Outline"), Pinta.Resources.Icons.FillStyleOutlineFill, 1);
fill_button.AddItem (Translations.GetString ("Outline"), Pinta.Resources.Icons.FillStyleOutline, 2);
fill_button.AddItem (Translations.GetString ("Fill Background"), Pinta.Resources.Icons.FillStyleBackground, 3);
fill_button.SelectedIndex = Settings.GetSetting (STYLE_SETTING, 0);
fill_button.SelectedItemChanged += HandleBoldButtonToggled;
}
tb.Append (fill_button);
outline_sep ??= GtkExtensions.CreateToolBarSeparator ();
tb.Append (outline_sep);
if (outline_width_label == null) {
string outlineWidthText = Translations.GetString ("Outline width");
outline_width_label = Gtk.Label.New ($" {outlineWidthText}: ");
}
tb.Append (outline_width_label);
if (outline_width == null) {
outline_width = GtkExtensions.CreateToolBarSpinButton (1, 1e5, 1, Settings.GetSetting (OUTLINE_WIDTH_SETTING, 2));
outline_width.OnValueChanged += HandleFontChanged;
}
tb.Append (outline_width);
outline_width.Visible = outline_width_label.Visible = outline_sep.Visible = StrokeText;
UpdateFont ();
if (workspace.HasOpenDocuments) {
//Make sure the event handler is never added twice.
workspace.ActiveDocument.LayerCloned -= FinalizeText;
//When an ImageSurface is Cloned, finalize the re-editable text (if applicable).
workspace.ActiveDocument.LayerCloned += FinalizeText;
}
}
protected override void OnSaveSettings (ISettingsService settings)
{
base.OnSaveSettings (settings);
if (font_button is not null)
settings.PutSetting (FONT_SETTING, font_button.Font!);
if (bold_btn is not null)
settings.PutSetting (BOLD_SETTING, bold_btn.Active);
if (italic_btn is not null)
settings.PutSetting (ITALIC_SETTING, italic_btn.Active);
if (underscore_btn is not null)
settings.PutSetting (UNDERLINE_SETTING, underscore_btn.Active);
if (left_alignment_btn is not null)
settings.PutSetting (ALIGNMENT_SETTING, (int) Alignment);
if (fill_button is not null)
settings.PutSetting (STYLE_SETTING, fill_button.SelectedIndex);
if (outline_width is not null)
settings.PutSetting (OUTLINE_WIDTH_SETTING, outline_width.GetValueAsInt ());
}
private void HandleFontChanged (object? sender, EventArgs e)
{
if (workspace.HasOpenDocuments)
workspace.ActiveDocument.Workspace.Canvas.GrabFocus ();
UpdateFont ();
}
private TextAlignment Alignment {
get {
if (right_alignment_btn.Active)
return TextAlignment.Right;
else if (center_alignment_btn.Active)
return TextAlignment.Center;
else
return TextAlignment.Left;
}
}
private void HandlePintaCorePalettePrimaryColorChanged (object? sender, EventArgs e)
{
if (is_editing || (workspace.HasOpenDocuments && CurrentTextEngine.State == TextMode.NotFinalized))
RedrawText (is_editing, true);
}
private void HandleLeftAlignmentButtonToggled (object? sender, EventArgs e)
{
if (left_alignment_btn.Active) {
right_alignment_btn.Active = false;
center_alignment_btn.Active = false;
} else if (!right_alignment_btn.Active && !center_alignment_btn.Active) {
left_alignment_btn.Active = true;
}
UpdateFont ();
}
private void HandleCenterAlignmentButtonToggled (object? sender, EventArgs e)
{
if (center_alignment_btn.Active) {
right_alignment_btn.Active = false;
left_alignment_btn.Active = false;
} else if (!right_alignment_btn.Active && !left_alignment_btn.Active) {
center_alignment_btn.Active = true;
}
UpdateFont ();
}
private void HandleRightAlignmentButtonToggled (object? sender, EventArgs e)
{
if (right_alignment_btn.Active) {
center_alignment_btn.Active = false;
left_alignment_btn.Active = false;
} else if (!center_alignment_btn.Active && !left_alignment_btn.Active) {
right_alignment_btn.Active = true;
}
UpdateFont ();
}
private void HandleUnderscoreButtonToggled (object? sender, EventArgs e)
{
UpdateFont ();
}
private void HandleItalicButtonToggled (object? sender, EventArgs e)
{
UpdateFont ();
}
private void HandleBoldButtonToggled (object? sender, EventArgs e)
{
outline_width.Visible = outline_width_label.Visible = outline_sep.Visible = StrokeText;
UpdateFont ();
}
private void HandleSelectedLayerChanged (object? sender, EventArgs e)
{
UpdateFont ();
}
protected override void OnAntialiasingChanged ()
{
UpdateFont ();
}
private void UpdateFont ()
{
if (workspace.HasOpenDocuments) {
var font = font_button.GetFontDesc ()!.Copy ()!; // NRT: Only nullable when nullptr is passed.
font.SetWeight (bold_btn.Active ? Pango.Weight.Bold : Pango.Weight.Normal);
font.SetStyle (italic_btn.Active ? Pango.Style.Italic : Pango.Style.Normal);
CurrentTextEngine.SetFont (font, Alignment, underscore_btn.Active);
}
if (is_editing || (workspace.HasOpenDocuments && CurrentTextEngine.State == TextMode.NotFinalized))
RedrawText (is_editing, true);
}
private int OutlineWidth
=> outline_width.GetValueAsInt ();
private bool StrokeText
=> fill_button.SelectedItem.GetTagOrDefault (0) >= 1 && fill_button.SelectedItem.GetTagOrDefault (0) != 3;
private bool FillText
=> fill_button.SelectedItem.GetTagOrDefault (0) <= 1 || fill_button.SelectedItem.GetTagOrDefault (0) == 3;
private bool BackgroundFill
=> fill_button.SelectedItem.GetTagOrDefault (0) == 3;
#endregion
#region Activation/Deactivation
protected override void OnActivated (Document? document)
{
base.OnActivated (document);
// We may need to redraw our text when the color changes
palette.PrimaryColorChanged += HandlePintaCorePalettePrimaryColorChanged;
palette.SecondaryColorChanged += HandlePintaCorePalettePrimaryColorChanged;
layers.LayerAdded += HandleSelectedLayerChanged;
layers.LayerRemoved += HandleSelectedLayerChanged;
layers.SelectedLayerChanged += HandleSelectedLayerChanged;
// We always start off not in edit mode
is_editing = false;
}
protected override void OnCommit (Document? document)
{
im_context.FocusOut ();
StopEditing (false);
}
protected override void OnDeactivated (Document? document, BaseTool? newTool)
{
base.OnDeactivated (document, newTool);
// Stop listening for color change events
palette.PrimaryColorChanged -= HandlePintaCorePalettePrimaryColorChanged;
palette.SecondaryColorChanged -= HandlePintaCorePalettePrimaryColorChanged;
layers.LayerAdded -= HandleSelectedLayerChanged;
layers.LayerRemoved -= HandleSelectedLayerChanged;
layers.SelectedLayerChanged -= HandleSelectedLayerChanged;
StopEditing (false);
}
#endregion
#region Mouse Handlers
protected override void OnMouseDown (Document document, ToolMouseEventArgs e)
{
ctrl_key = e.IsControlPressed;
im_context.FocusIn (); // Grab focus so we can get keystrokes
selection = document.Selection.Clone ();
switch (e.MouseButton) {
case MouseButton.Right:
HandleRightClick (e);
break;
case MouseButton.Left:
HandleLeftClick (document, e);
break;
}
}
private void HandleLeftClick (Document document, ToolMouseEventArgs e)
{
//Store the mouse position.
PointI pt = e.Point;
// If the user is [editing or holding down Ctrl] and clicked
//within the text, move the cursor to the click location
if ((is_editing || ctrl_key) && CurrentTextBounds.Contains (pt)) {
StartEditing ();
//Change the position of the cursor to where the mouse clicked.
TextPosition p = CurrentTextLayout.PointToTextPosition (pt);
CurrentTextEngine.SetCursorPosition (p, true);
//Redraw the text with the new cursor position.
RedrawText (true, true);
return;
}
// We're already editing and the user clicked outside the text,
// commit the user's work, and start a new edit
switch (CurrentTextEngine.State) {
// We were editing, save and stop
case TextMode.Uncommitted:
StopEditing (true);
break;
// We were editing, but nothing had been
// keyed. Stop editing.
case TextMode.Unchanged:
StopEditing (false);
break;
}
if (ctrl_key) {
//Go through every UserLayer.
foreach (UserLayer ul in document.Layers.UserLayers) {
//Check each UserLayer's editable text boundaries to see if they contain the mouse position.
if (!ul.TextBounds.Contains (pt))
continue;
//The mouse clicked on editable text.
//Change the current UserLayer to the Layer that contains the text that was clicked on.
document.Layers.SetCurrentUserLayer (ul);
//The user is editing text now.
is_editing = true;
//Set the cursor in the editable text where the mouse was clicked.
TextPosition p = CurrentTextLayout.PointToTextPosition (pt);
CurrentTextEngine.SetCursorPosition (p, true);
//Redraw the editable text with the cursor.
RedrawText (true, true);
//Don't check any more UserLayers - stop at the first UserLayer that has editable text containing the mouse position.
return;
}
} else {
if (CurrentTextEngine.State == TextMode.NotFinalized) {
//The user is making a new text and the old text hasn't been finalized yet.
FinalizeText ();
}
if (!is_editing) {
// Start editing at the cursor location
click_point = pt;
CurrentTextEngine.Clear ();
UpdateFont ();
click_point = click_point with { Y = click_point.Y - (CurrentTextLayout.FontHeight / 2) };
CurrentTextEngine.Origin = click_point;
StartEditing ();
RedrawText (true, true);
}
}
}
private void HandleRightClick (ToolMouseEventArgs e)
{
// A right click allows you to move the text around
//The user is dragging text with the right mouse button held down, so track the mouse as it moves.
tracking = true;
//Remember the position of the mouse before the text is dragged.
start_mouse_xy = e.PointDouble;
start_click_point = click_point;
//Change the cursor to indicate that the text is being dragged.
SetCursor (cursor_move);
}
protected override void OnMouseMove (Document document, ToolMouseEventArgs e)
{
ctrl_key = e.IsControlPressed;
last_mouse_position = e.Point;
// If we're dragging the text around, do that
if (tracking) {
PointD delta = new (
e.PointDouble.X - start_mouse_xy.X,
e.PointDouble.Y - start_mouse_xy.Y);
click_point = new PointI ((int) (start_click_point.X + delta.X), (int) (start_click_point.Y + delta.Y));
CurrentTextEngine.Origin = click_point;
RedrawText (true, true);
} else {
UpdateMouseCursor (document);
}
}
protected override void OnMouseUp (Document document, ToolMouseEventArgs e)
{
// If we were dragging the text around, finish that up
if (!tracking)
return;
PointD delta = new (e.PointDouble.X - start_mouse_xy.X, e.PointDouble.Y - start_mouse_xy.Y);
click_point = new PointI ((int) (start_click_point.X + delta.X), (int) (start_click_point.Y + delta.Y));
CurrentTextEngine.Origin = click_point;
RedrawText (false, true);
tracking = false;
SetCursor (null);
}
private void UpdateMouseCursor (Document document)
{
//Whether or not to show the normal text cursor.
bool showNormalCursor = false;
if (ctrl_key && workspace.HasOpenDocuments) {
//Go through every UserLayer.
foreach (UserLayer ul in document.Layers.UserLayers) {
//Check each UserLayer's editable text boundaries to see if they contain the mouse position.
if (ul.TextBounds.Contains (last_mouse_position)) {
//The mouse is over editable text.
showNormalCursor = true;
}
}
} else {
showNormalCursor = true;
}
if (showNormalCursor) {
if (!previous_mouse_cursor_normal) {
SetCursor (DefaultCursor);
previous_mouse_cursor_normal = showNormalCursor;
if (workspace.HasOpenDocuments)
RedrawText (is_editing, true);
}
} else {
if (previous_mouse_cursor_normal) {
SetCursor (cursor_invalid);
previous_mouse_cursor_normal = showNormalCursor;
RedrawText (is_editing, true);
}
}
}
#endregion
#region Keyboard Handlers
protected override bool OnKeyDown (Document document, ToolKeyEventArgs e)
{
if (!workspace.HasOpenDocuments)
return false;
// If we are dragging the text, we
// aren't going to handle key presses
if (tracking)
return false;
// Ignore anything with Alt pressed
if (e.IsAltPressed)
return false;
ctrl_key = e.Key.IsControlKey ();
UpdateMouseCursor (document);
bool keyHandled = false;
if (is_editing) {
if (preedit_string is not null && e.Event is not null) {
// When pre-editing is active, the input method should consume all keystrokes first.
// (e.g. Enter might be used to finish pre-editing)
keyHandled = TryHandleChar (e.Event);
}
if (!keyHandled) {
// Assume that we are going to handle the key
keyHandled = true;
switch (e.Key) {
case Gdk.Key.BackSpace:
CurrentTextEngine.PerformBackspace ();
break;
case Gdk.Key.Delete:
CurrentTextEngine.PerformDelete ();
break;
case Gdk.Key.KP_Enter:
case Gdk.Key.Return:
CurrentTextEngine.PerformEnter ();
break;
case Gdk.Key.Left:
CurrentTextEngine.PerformLeft (e.IsControlPressed, e.IsShiftPressed);
break;
case Gdk.Key.Right:
CurrentTextEngine.PerformRight (e.IsControlPressed, e.IsShiftPressed);
break;
case Gdk.Key.Up:
CurrentTextEngine.PerformUp (e.IsShiftPressed);
break;
case Gdk.Key.Down:
CurrentTextEngine.PerformDown (e.IsShiftPressed);
break;
case Gdk.Key.Home:
CurrentTextEngine.PerformHome (e.IsControlPressed, e.IsShiftPressed);
break;
case Gdk.Key.End:
CurrentTextEngine.PerformEnd (e.IsControlPressed, e.IsShiftPressed);
break;
case Gdk.Key.Next:
case Gdk.Key.Prior:
break;
case Gdk.Key.Escape:
StopEditing (false);
return true;
case Gdk.Key.Insert:
if (e.IsShiftPressed) {
CurrentTextEngine.PerformPaste (GdkExtensions.GetDefaultClipboard ()).Wait ();
} else if (e.IsControlPressed) {
CurrentTextEngine.PerformCopy (GdkExtensions.GetDefaultClipboard ());
}
break;
default:
if (e.IsControlPressed) {
if (e.Key == Gdk.Key.z) {
//Ctrl + Z for undo while editing.
OnHandleUndo (document);
if (workspace.ActiveDocument.History.CanUndo)
workspace.ActiveDocument.History.Undo ();
return true;
} else if (e.Key == Gdk.Key.i) {
italic_btn.Toggle ();
UpdateFont ();
} else if (e.Key == Gdk.Key.b) {
bold_btn.Toggle ();
UpdateFont ();
} else if (e.Key == Gdk.Key.u) {
underscore_btn.Toggle ();
UpdateFont ();
} else if (e.Key == Gdk.Key.a) {
// Select all of the text.
CurrentTextEngine.PerformHome (false, false);
CurrentTextEngine.PerformEnd (true, true);
} else {
//Ignore command shortcut.
return false;
}
} else {
if (e.Event is not null)
keyHandled = TryHandleChar (e.Event);
}
break;
}
}
if (keyHandled)
RedrawText (true, true);
}
return keyHandled;
}
protected override bool OnKeyUp (Document document, ToolKeyEventArgs e)
{
if (e.Key.IsControlKey () || e.IsControlPressed) {
ctrl_key = false;
UpdateMouseCursor (document);
}
return false;
}
private bool TryHandleChar (Gdk.Event eventKey)
{
// Try to handle it as a character
if (im_context.FilterKeypress (eventKey))
return true;
// We didn't handle the key
return false;
}
private void OnIMCommit (object o, Gtk.IMContext.CommitSignalArgs args)
{
try {
// Reset the pre-edit string. Depending on the platform there might still be
// a preedit-changed signal (setting it to the empty string) after the commit, rather than before.
UpdatePreeditString (string.Empty, redraw: false);
CurrentTextEngine.InsertText (args.Str);
RedrawText (true, true);
} finally {
im_context.Reset ();
}
}
private void OnPreeditStart (object o, EventArgs args)
{
// Initialize to empty string (null means pre-editing is inactive).
preedit_string = string.Empty;
}
private void OnPreeditEnd (object o, EventArgs args)
{
// Reset to indicate that pre-editing is done. There should have previously been
// a preedit-changed signal to erase the last preedited string.
preedit_string = null;
}
private void OnPreeditChanged (object o, EventArgs args)
{
// TODO - use the Pango.AttrList argument to better visualize the pre-edited text vs the regular text.
im_context.GetPreeditString (out string updated_str, out _, out _);
UpdatePreeditString (updated_str, redraw: true);
}
private void UpdatePreeditString (string updated, bool redraw)
{
// Remove the previous preedit string.
for (int i = 0; i < preedit_string?.Length; ++i)
CurrentTextEngine.PerformBackspace ();
// Insert the new string.
preedit_string = updated;
CurrentTextEngine.InsertText (preedit_string);
RedrawText (true, true);
}
#endregion
#region Start/Stop Editing
private void StartEditing ()
{
is_editing = true;
im_context.SetClientWidget (workspace.ActiveWorkspace.Canvas);
selection ??= workspace.ActiveDocument.Selection.Clone ();
//Start ignoring any Surface.Clone calls from this point on (so that it doesn't start to loop).
ignore_clone_finalizations = true;
//Store the previous state of the current UserLayer's and TextLayer's ImageSurfaces.
user_undo_surface = workspace.ActiveDocument.Layers.CurrentUserLayer.Surface.Clone ();
text_undo_surface = workspace.ActiveDocument.Layers.CurrentUserLayer.TextLayer.Layer.Surface.Clone ();
//Store the previous state of the Text Engine.
undo_engine = CurrentTextEngine.Clone ();
//Stop ignoring any Surface.Clone calls from this point on.
ignore_clone_finalizations = false;
}
private void StopEditing (bool finalize)
{
im_context.SetClientWidget (null);
if (!workspace.HasOpenDocuments)
return;
if (!is_editing)
return;
is_editing = false;
//Make sure that neither undo surface is null, the user is editing, and there are uncommitted changes.
if (text_undo_surface != null && user_undo_surface != null && CurrentTextEngine.State == TextMode.Uncommitted) {
Document doc = workspace.ActiveDocument;
RedrawText (false, true);
//Start ignoring any Surface.Clone calls from this point on (so that it doesn't start to loop).
ignore_clone_finalizations = true;
//Create a new TextHistoryItem so that the committing of text can be undone.
doc.History.PushNewItem (
new TextHistoryItem (
Icon,
Name,
text_undo_surface.Clone (),
user_undo_surface.Clone (),
undo_engine!.Clone (), // NRT - Set in StartEditing
doc.Layers.CurrentUserLayer
)
);
//Stop ignoring any Surface.Clone calls from this point on.
ignore_clone_finalizations = false;
//Now that the text has been committed, change its state.
CurrentTextEngine.State = TextMode.NotFinalized;
}
RedrawText (false, true);
if (finalize) {
FinalizeText ();
}
}
#endregion
#region Text Drawing Methods
/// <summary>
/// Clears the entire TextLayer and redraw the previous text boundary.
/// </summary>
private void ClearTextLayer ()
{
//Clear the TextLayer.
workspace.ActiveDocument.Layers.CurrentUserLayer.TextLayer.Layer.Surface.Clear ();
//Redraw the previous text boundary.
InflateAndInvalidate (workspace.ActiveDocument.Layers.CurrentUserLayer.PreviousTextBounds);
}
/// <summary>
/// Draws the text.
/// </summary>
/// <param name="showCursor">Whether or not to show the mouse cursor in the drawing.</param>
/// <param name="useTextLayer">Whether or not to use the TextLayer (as opposed to the Userlayer).</param>
private void RedrawText (bool showCursor, bool useTextLayer)
{
RectangleI r = CurrentTextLayout.GetLayoutBounds ();
r = r.Inflated (10 + OutlineWidth, 10 + OutlineWidth);
InflateAndInvalidate (r);
CurrentTextBounds = r;
RectangleI cursorBounds = RectangleI.Zero;
Cairo.ImageSurface surf;
if (!useTextLayer) {
//Draw text on the current UserLayer's surface as finalized text.
surf = workspace.ActiveDocument.Layers.CurrentUserLayer.Surface;
} else {
//Draw text on the current UserLayer's TextLayer's surface as re-editable text.
surf = workspace.ActiveDocument.Layers.CurrentUserLayer.TextLayer.Layer.Surface;
ClearTextLayer ();
}
Cairo.Context g = new (surf);
var options = new Cairo.FontOptions ();
if (UseAntialiasing) {
// Adjusts antialiasing JUST for the outline brush
g.Antialias = Cairo.Antialias.Gray;
// Adjusts antialiasing for PangoCairo's text draw function
options.Antialias = Antialias.Gray;
} else {
g.Antialias = Cairo.Antialias.None;
options.Antialias = Antialias.None;
}