-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathEditingHelper.cs
More file actions
3848 lines (3499 loc) · 142 KB
/
Copy pathEditingHelper.cs
File metadata and controls
3848 lines (3499 loc) · 142 KB
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
// Copyright (c) 2002-2017 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using SIL.LCModel.Core.Cellar;
using SIL.LCModel.Core.Text;
using SIL.LCModel.Core.WritingSystems;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.FieldWorks.Common.ViewsInterfaces;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.RootSites.Properties;
using SIL.Keyboarding;
using SIL.PlatformUtilities;
using SIL.Reporting;
using SIL.LCModel.Utils;
using SIL.Windows.Forms.Keyboarding;
using SIL.LCModel;
namespace SIL.FieldWorks.Common.RootSites
{
#region IEditingCallbacks interface
/// ----------------------------------------------------------------------------------------
/// <summary>
/// This interface, implemented currently by SimpleRootSite and PublicationControl,
/// defines the functions that are not inherited from UserControl which must be
/// implemented by the EditingHelper client. One argument to the constructor for
/// EditingHelper is an IEditingCallbacks. It must be capable of being cast to
/// UserControl.
/// </summary>
/// ----------------------------------------------------------------------------------------
public interface IEditingCallbacks
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// See the comments on m_wsPending for SimpleRootSite. Used to manage
/// writing system changes caused by selecting a system input language.
/// </summary>
/// ------------------------------------------------------------------------------------
int WsPending { get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Typically the AutoScollPosition of the control, SimpleRootSite
/// handles this specially.
/// </summary>
/// ------------------------------------------------------------------------------------
Point ScrollPosition { get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Return an indication of the behavior of some of the special keys (arrows, home,
/// end).
/// </summary>
/// <param name="chw">Key value</param>
/// <param name="ss">Shift status</param>
/// <returns>Return <c>0</c> for physical behavior, <c>1</c> for logical behavior.
/// </returns>
/// <remarks>Physical behavior means that left arrow key goes to the left regardless
/// of the direction of the text; logical behavior means that left arrow key always
/// moves the IP one character (possibly plus diacritics, etc.) in the underlying text,
/// in the direction that is to the left for text in the main paragraph direction.
/// So, in a normal LTR paragraph, left arrow decrements the IP position; in an RTL
/// paragraph, it increments it. Both produce a movement to the left in text whose
/// direction matches the paragraph ("downstream" text). But where there is a segment
/// of upstream text, logical behavior will jump almost to the other end of the
/// segment and then move the 'wrong' way through it.
/// </remarks>
/// ------------------------------------------------------------------------------------
EditingHelper.CkBehavior ComplexKeyBehavior(int chw, VwShiftStatus ss);
/// ------------------------------------------------------------------------------------
/// <summary>
/// Scroll all the way to the top of the document.
/// </summary>
/// ------------------------------------------------------------------------------------
void ScrollToTop();
/// ------------------------------------------------------------------------------------
/// <summary>
/// Scroll all the way to the end of the document.
/// </summary>
/// ------------------------------------------------------------------------------------
void ScrollToEnd();
/// ------------------------------------------------------------------------------------
/// <summary>
/// Show the context menu for the specified root box at the location of
/// its selection (typically an IP).
/// </summary>
/// ------------------------------------------------------------------------------------
void ShowContextMenuAtIp(IVwRootBox rootb);
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the (estimated) height of one line
/// </summary>
/// ------------------------------------------------------------------------------------
int LineHeight { get; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// RootBox currently being edited.
/// </summary>
/// ------------------------------------------------------------------------------------
IVwRootBox EditedRootBox { get; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Flag indicating cache or writing system is available.
/// </summary>
/// ------------------------------------------------------------------------------------
bool GotCacheOrWs { get; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the writing system for the HVO. This could either be the vernacular or
/// analysis writing system.
/// </summary>
/// <param name="hvo">HVO</param>
/// <returns>Writing system</returns>
/// ------------------------------------------------------------------------------------
int GetWritingSystemForHvo(int hvo);
/// ------------------------------------------------------------------------------------
/// <summary>
/// Perform any processing needed immediately prior to a paste operation.
/// </summary>
/// ------------------------------------------------------------------------------------
void PrePasteProcessing();
/// ------------------------------------------------------------------------------------
/// <summary>
/// If we need to make a selection, but we can't because edits haven't been updated in
/// the view, this method requests creation of a selection after the unit of work is
/// complete. It will also scroll the selection into view.
/// Derived classes should implement this if they have any hope of supporting multi-
/// paragraph editing.
/// </summary>
/// <param name="helper">The selection to restore</param>
/// ------------------------------------------------------------------------------------
void RequestVisibleSelectionAtEndOfUow(SelectionHelper helper);
}
#endregion
#region FwPasteFixTssEvent handler and args class
/// <summary></summary>
public delegate void FwPasteFixTssEventHandler(EditingHelper sender, FwPasteFixTssEventArgs e);
/// <summary>
/// This event argument class is used for fixing the text properties of Pasted text in
/// EditingHelper objects whose owning SimpleRootSite object requires specific properties.
/// See LT-1445 for motivation. Other final adjustments to the ITsString value
/// may also be made if there's any such need. The handler function is called just before
/// replacing the selection in the root box with the given ITsString.
/// </summary>
public class FwPasteFixTssEventArgs
{
private readonly TextSelInfo m_tsi;
/// ------------------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="T:FwPasteFixWsEventArgs"/> class.
/// </summary>
/// <param name="tss">The ITsString to paste.</param>
/// <param name="tsi">The TextSelInfo of the selection at the start of the paste.</param>
/// ------------------------------------------------------------------------------------
public FwPasteFixTssEventArgs(ITsString tss, TextSelInfo tsi)
{
TsString = tss;
m_tsi = tsi;
EventHandled = false;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets the TsString to paste (handlers can modify this).
/// </summary>
/// ------------------------------------------------------------------------------------
public ITsString TsString { get; set; }
/// ------------------------------------------------------------------------------------
/// <summary>
/// The TextSelInfo of the selection at the start of the paste
/// </summary>
/// ------------------------------------------------------------------------------------
public TextSelInfo TextSelInfo
{
get { return m_tsi; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets a value indicating whether the event was handled.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool EventHandled { get; set; }
}
#endregion
#region EditingHelper class
/// ----------------------------------------------------------------------------------------
/// <summary>
/// This class encapsulates some of the common behavior of SimpleRootSite and
/// PublicationControl that has to do with forwarding keyboard events to the
/// root box that has focus.
/// </summary>
/// ----------------------------------------------------------------------------------------
public class EditingHelper : IDisposable, ISelectionChangeNotifier
{
#region Events
/// <summary>
/// Event handler for specialized work when the selection changes.
/// </summary>
public event EventHandler<VwSelectionArgs> VwSelectionChanged;
/// <summary>
/// This event allows us to skip unnecessary (and sometimes harmful) keyboard changes when changing keyboards from the ws chooser
/// seen in LT-21200
/// </summary>
private event EventHandler<IVwSelection> DoSetKeyboardForSelection;
#endregion
#region Member variables
private UserControl m_control; // currently either SimpleRootSite or PublicationControl.
/// <summary>Object that provides editing callback methods (in production code, this is usually (always?) the rootsite)</summary>
protected IEditingCallbacks m_callbacks;
/// <summary>The default cursor to use</summary>
private Cursor m_defaultCursor;
/// <summary>
/// This overrides the normal Ibeam cursor when over text (not when over hot links or
/// hot pictures) if the cursor is over something that can't be edited.
/// </summary>
private Cursor m_readOnlyCursor;
/// <summary>True if editing commands should be handled, false otherwise</summary>
private bool m_fEditable = true;
/// <summary>A SelectionHelper that holds the info for the current selection (updated
/// every time the selection changes) Protected to allow for testing - production
/// subclasses should not access this member directly</summary>
protected SelectionHelper m_currentSelection;
/// <summary>Flag to prevent deletion of an object</summary>
protected bool m_preventObjDeletions;
/// <summary>Event for changing properties of a pasted TsString</summary>
public event FwPasteFixTssEventHandler PasteFixTssEvent;
private bool m_fSuppressNextWritingSystemHvoChanged;
private bool m_fSuppressNextBestStyleNameChanged;
private long m_TimestampOfLastGotFocus;
/// <summary>Flag to prevent reentrancy while setting keyboard.</summary>
private bool m_fSettingKeyboards;
#endregion
#region Enumerations
/// <summary>Paste status indicates how writing systems should be handled during a paste</summary>
public enum PasteStatus
{
/// <summary>When pasting, use the writing system at the destination</summary>
UseDestWs,
/// <summary>When pasting, preserve the original writing systems, even if new writing systems
/// would need to be created.</summary>
PreserveWs,
/// <summary>Cancel paste operation.</summary>
CancelPaste
}
/// <summary>Behavior of certain keys like arrow key, home, end...</summary>
/// <see cref="SimpleRootSite.ComplexKeyBehavior"/>
public enum CkBehavior
{
/// <summary>Physical order</summary>
Physical = 0,
/// <summary>Logical order</summary>
Logical = 1
}
#endregion // Enumerations
/// ------------------------------------------------------------------------------------
/// <summary>
/// This constructor is for testing so the class can be mocked.
/// </summary>
/// ------------------------------------------------------------------------------------
public EditingHelper() : this(null)
{
}
/// -----------------------------------------------------------------------------------
/// <summary>
/// Construct one.
/// </summary>
/// <param name="callbacks"></param>
/// -----------------------------------------------------------------------------------
public EditingHelper(IEditingCallbacks callbacks)
{
DoSetKeyboardForSelection += SetKeyboardForSelectionInternal;
m_callbacks = callbacks;
m_control = callbacks as UserControl;
}
#region IDisposable & Co. implementation
// Region last reviewed: never
/// <summary>
/// True, if the object has been disposed.
/// </summary>
private bool m_isDisposed;
/// <summary>
/// See if the object has been disposed.
/// </summary>
public bool IsDisposed
{
get { return m_isDisposed; }
}
/// <summary>
/// Finalizer, in case client doesn't dispose it.
/// Force Dispose(false) if not already called (i.e. m_isDisposed is true)
/// </summary>
/// <remarks>
/// In case some clients forget to dispose it directly.
/// </remarks>
~EditingHelper()
{
Dispose(false);
// The base class finalizer is called automatically.
}
/// <summary>
///
/// </summary>
/// <remarks>Must not be virtual.</remarks>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Executes in two distinct scenarios.
///
/// 1. If disposing is true, the method has been called directly
/// or indirectly by a user's code via the Dispose method.
/// Both managed and unmanaged resources can be disposed.
///
/// 2. If disposing is false, the method has been called by the
/// runtime from inside the finalizer and you should not reference (access)
/// other managed objects, as they already have been garbage collected.
/// Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing"></param>
/// <remarks>
/// If any exceptions are thrown, that is fine.
/// If the method is being done in a finalizer, it will be ignored.
/// If it is thrown by client code calling Dispose,
/// it needs to be handled by fixing the bug.
///
/// If subclasses override this method, they should call the base implementation.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
Debug.WriteLineIf(!disposing, "****************** Missing Dispose() call for " + GetType().Name + " ******************");
// Must not be run more than once.
if (m_isDisposed)
return;
if (disposing)
{
// Dispose managed resources here.
DoSetKeyboardForSelection -= SetKeyboardForSelectionInternal;
}
// Dispose unmanaged resources here, whether disposing is true or false.
m_control = null;
m_callbacks = null;
m_currentSelection = null;
// Don't do this here...causes TsStrings not to copy and paste properly from one view
// to another in Flex (and elsewhere).
//ClearTsStringClipboard();
m_isDisposed = true;
}
/// <summary>
/// Throw if the IsDisposed property is true
/// </summary>
public void CheckDisposed()
{
if (IsDisposed)
throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name));
}
#endregion IDisposable & Co. implementation
#region Writing system methods
/// ------------------------------------------------------------------------------------
/// <summary>
/// Get in the vector the list of writing system identifiers currently installed in the
/// writing system factory for the current root box. The current writing system for the
/// selection is duplicated as the first item in the array (this causes it to be found
/// first in searches).
/// </summary>
/// ------------------------------------------------------------------------------------
public List<int> GetWsList(out ILgWritingSystemFactory wsf)
{
CheckDisposed();
// Get the writing system factory associated with the root box.
wsf = WritingSystemFactory;
int cws = wsf.NumberOfWs;
if (cws == 0)
return null;
using (ArrayPtr ptr = MarshalEx.ArrayToNative<int>(cws))
{
wsf.GetWritingSystems(ptr, cws);
int[] vwsT = MarshalEx.NativeToArray<int>(ptr, cws);
if (cws == 1 && vwsT[0] == 0)
return null; // no writing systems to work with
return new List<int>(vwsT);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Get in the vector the list of writing system identifiers currently installed in the
/// writing system factory for the current root box. The current writing system for the
/// selection is duplicated as the first item in the array (this causes it to be found
/// first in searches).
/// </summary>
/// ------------------------------------------------------------------------------------
public List<int> GetWsListCurrentFirst(IVwSelection vwsel,
out ILgWritingSystemFactory wsf)
{
CheckDisposed();
List<int> writingSystems = GetWsList(out wsf);
if (writingSystems != null)
{
// Put the writing system of the selection first in the list, which gives it
// priority--we'll find it first if it matches.
int wsSel = SelectionHelper.GetFirstWsOfSelection(vwsel);
if (vwsel != null && wsSel != 0)
{
writingSystems.Insert(0, wsSel);
}
else
{
writingSystems.Insert(0, writingSystems[0]);
}
}
return writingSystems;
}
/// -----------------------------------------------------------------------------------
/// <summary>
/// Set the writing system of the current selection.
/// </summary>
/// -----------------------------------------------------------------------------------
public void ApplyWritingSystem(int hvoWsNew)
{
CheckDisposed();
if(Callbacks == null || Callbacks.EditedRootBox == null)
return;
IVwSelection vwsel = Callbacks.EditedRootBox.Selection;
ITsTextProps[] vttp;
IVwPropertyStore[] vvps;
int cttp;
SelectionHelper.GetSelectionProps(vwsel, out vttp, out vvps, out cttp);
bool fChanged = false;
for (int ittp = 0; ittp < cttp; ++ittp)
{
int hvoWsOld, var;
ITsTextProps ttp = vttp[ittp];
// Change the writing system only if it is different and not a user prompt.
hvoWsOld = ttp.GetIntPropValues((int)FwTextPropType.ktptWs, out var);
if (ttp.GetIntPropValues(SimpleRootSite.ktptUserPrompt, out var) == -1 &&
hvoWsOld != hvoWsNew)
{
ITsPropsBldr tpb = ttp.GetBldr();
tpb.SetIntPropValues((int)FwTextPropType.ktptWs, (int)FwTextPropVar.ktpvDefault, hvoWsNew);
vttp[ittp] = tpb.GetTextProps();
fChanged = true;
}
else
{
vttp[ittp] = null;
}
}
if (fChanged)
{
ChangeWritingSystem(vwsel, vttp, cttp);
HandleSelectionChange(Callbacks.EditedRootBox, vwsel);
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Changes the writing system.
/// </summary>
/// <param name="sel">The selection.</param>
/// <param name="props">The properties specifying the new writing system.</param>
/// <param name="numProps">The number of ITsTextProps.</param>
/// ------------------------------------------------------------------------------------
protected virtual void ChangeWritingSystem(IVwSelection sel, ITsTextProps[] props, int numProps)
{
Debug.Assert(sel != null);
Debug.Assert(props != null);
sel.SetSelectionProps(numProps, props);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Determines if all the writing systems in the given writing system factory are
/// defined in the writing system factory of this editing helper.
/// </summary>
/// <param name="wsf">The given writing system factory.</param>
/// <returns><c>true</c> if all writing systems are defined; <c>false</c> otherwise
/// </returns>
/// ------------------------------------------------------------------------------------
protected bool AllWritingSystemsDefined(ILgWritingSystemFactory wsf)
{
// Check to see if all writing systems are defined.
int cws = wsf.NumberOfWs;
using (ArrayPtr ptr = MarshalEx.ArrayToNative<int>(cws))
{
wsf.GetWritingSystems(ptr, cws);
int[] vws = MarshalEx.NativeToArray<int>(ptr, cws);
ILgWritingSystem ws;
for (int iws = 0; iws < cws; iws++)
{
if (vws[iws] == 0)
continue;
ws = wsf.get_EngineOrNull(vws[iws]);
if (ws == null || WritingSystemFactory.GetWsFromStr(ws.Id) == 0)
return false; // found writing system not in current project
}
}
return true;
}
#endregion
#region Character processing methods
/// -----------------------------------------------------------------------------------
/// <summary>
/// Handle a WM_CHAR message.
/// Caller should ensure this is wrapped in a UOW (typically done in an override of
/// OnKeyPress in RootSiteEditingHelper, since SimpleRootSite does not have access
/// to FDO and UOW).
/// </summary>
/// -----------------------------------------------------------------------------------
public virtual void OnKeyPress(KeyPressEventArgs e, Keys modifiers)
{
CheckDisposed();
if (!IsIgnoredKey(e, modifiers) && CanEdit()) // Only process keys that aren't ignored
HandleKeyPress(e.KeyChar, modifiers);
}
// (EberhardB): This code is reimplementing System.Windows.Forms code. See comment on
// OnKeyPress().
// This comment is part of the fix for LT-9049.
///// ------------------------------------------------------------------------------------
///// <summary>
///// Get the next control on the parent form
///// </summary>
///// <param name="control">The control.</param>
///// <param name="fForward">true to look forward; false to look backward</param>
///// <returns>
///// The next control on the owning form which is is a tab stop. If no owning
///// form is found or if no other tab-stop controls exist, <c>this</c> control will be
///// returned.
///// </returns>
///// ------------------------------------------------------------------------------------
//public static Control NextTabStop(Control control, bool fForward)
//{
// Form parentForm = control.FindForm();
// if (parentForm != null)
// {
// Set<Control> visited = new Set<Control>();
// Control nextControl = control;
// visited.Add(nextControl);
// do
// {
// nextControl = parentForm.GetNextControl(nextControl, fForward);
// if (nextControl != null)
// {
// if (visited.Contains(nextControl))
// break;
// visited.Add(nextControl);
// }
// if (nextControl != null && nextControl.Enabled &&
// nextControl.TabStop && nextControl.Visible &&
// // when looking backwards, the first control found will be the parent
// // of the current control. This causes our own control to get selected so
// // keep looking
// (fForward || control.TabIndex != 0 || !IsParentOf(control, nextControl)))
// {
// return nextControl;
// }
// } while (true);
// }
// return control;
//}
///// <summary>
///// Answer true if possibleParent is a parent (even indirectly) of child
///// </summary>
///// <param name="child"></param>
///// <param name="possibleParent"></param>
///// <returns></returns>
//private static bool IsParentOf(Control child, Control possibleParent)
//{
// Control c = child.Parent;
// while (c != null)
// {
// if (c == possibleParent)
// return true;
// c = c.Parent;
// }
// return false;
//}
/// -----------------------------------------------------------------------------------
/// <summary>
/// User pressed a key.
/// </summary>
/// <param name="e"></param>
/// <returns><c>true</c> if we handled the key, <c>false</c> otherwise (e.g. we're
/// already at the end of the rootbox and the user pressed down arrow key).</returns>
/// -----------------------------------------------------------------------------------
public virtual bool OnKeyDown(KeyEventArgs e)
{
CheckDisposed();
if (Callbacks == null || Callbacks.EditedRootBox == null)
return true;
bool fRet = true;
switch (e.KeyCode)
{
case Keys.PageUp:
case Keys.PageDown:
case Keys.End:
case Keys.Home:
case Keys.Left:
case Keys.Up:
case Keys.Right:
case Keys.Down:
case Keys.F7: // the only two function keys currently known to the Views code,
case Keys.F8: // used for left and right arrow by string character amounts.
case Keys.Enter:
VwShiftStatus ss = GetShiftStatus(e.Modifiers);
if (e.KeyCode == Keys.Enter && (ss == VwShiftStatus.kfssShift || !CanEdit()))
return fRet;
int keyVal = e.KeyValue;
if (Control is SimpleRootSite)
keyVal = ((SimpleRootSite)Control).ConvertKeyValue(keyVal);
fRet = CallOnExtendedKey(keyVal, ss);
// REVIEW (EberhardB): I'm not sure if it's generally valid
// to call ScrollSelectionIntoView from HandleKeyDown
HandleKeyDown(e, ss);
// The properties of the selection may be changed by pressing these
// navigation keys even if the selection does not move (e.g. TE-7098
// when the right arrow key is pressed after a chapter number when
// there is no text following the chapter number).
ClearCurrentSelection();
break;
case Keys.Delete:
if (!CanEdit())
return fRet;
// The Microsoft world apparently doesn't know that <DEL> is an ASCII
// character just as much as <BS>, so TranslateMessage generates a
// WM_CHAR message for <BS>, but not for <DEL>! I think the reason for this
// probably has to do with the ability to use Del as a menu command shortcut.
OnKeyPress(new KeyPressEventArgs((char)(int)VwSpecialChars.kscDelForward), e.Modifiers);
break;
case Keys.Space:
if (CanEdit() && (e.Modifiers & Keys.Control) == Keys.Control)
{
e.Handled = true;
RemoveCharFormatting();
}
break;
case Keys.F10:
if (GetShiftStatus(e.Modifiers) == VwShiftStatus.kfssShift)
Callbacks.ShowContextMenuAtIp(Callbacks.EditedRootBox);
break;
case Keys.Apps:
// Handle the user pressing the context menu key (i.e. the Apps. key).
// we display the context menu here manually so that it shows
// at the right location. If we rely on .NET it doesn't display
// it at the IP location.
Callbacks.ShowContextMenuAtIp(Callbacks.EditedRootBox);
break;
case Keys.Tab:
ss = GetShiftStatus(e.Modifiers);
keyVal = e.KeyValue;
if (Control is SimpleRootSite)
keyVal = (Control as SimpleRootSite).ConvertKeyValue(keyVal);
fRet = CallOnExtendedKey(keyVal, ss);
// REVIEW (EberhardB): I'm not sure if it's generally valid
// to call ScrollSelectionIntoView from HandleKeyDown
HandleKeyDown(e, ss);
break;
default:
break;
}
return fRet;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Checks input characters to see if they should be processsed. Static to allow
/// function to be shared with PublicationControl.
/// </summary>
/// <param name="e"></param>
/// <param name="modifiers">Control.ModifierKeys</param>
/// <returns><code>true</code> if character should be ignored on input</returns>
/// ------------------------------------------------------------------------------------
public static bool IsIgnoredKey(KeyPressEventArgs e, Keys modifiers)
{
bool ignoredKey = false;
if ((modifiers & Keys.Alt) == Keys.Alt)
{
// For some languages, Alt is commonly used for keyboard input. See LT-4182.
}
else if ((modifiers & Keys.Control) == Keys.Control)
{
// control-backspace, control-forward delete and control-M (same as return
// key) will be passed on for processing
ignoredKey = !(e.KeyChar == (int)VwSpecialChars.kscBackspace ||
e.KeyChar == (int)VwSpecialChars.kscDelForward ||
e.KeyChar == '\r');
}
// Ignore control characters (most can only be generated using control key, see above; but Escape otherwise gets through...)
// One day we might want to allow tab, though I don't think it comes through this method anyway...
if (e.KeyChar < 0x20 && e.KeyChar != '\r' && e.KeyChar != '\b')
return true;
return ignoredKey;
}
/// -----------------------------------------------------------------------------------
/// <summary>
/// Handle a key press.
/// Caller should ensure this is wrapped in a UOW (typically done in an override of
/// OnKeyPress in RootSiteEditingHelper, since SimpleRootSite does not have access
/// to FDO and UOW).
/// </summary>
/// <param name="keyChar">The pressed character key</param>
/// <param name="modifiers">key modifies - shift status, etc.</param>
/// -----------------------------------------------------------------------------------
public void HandleKeyPress(char keyChar, Keys modifiers)
{
CheckDisposed();
// REVIEW (EberhardB): .NETs Unicode character type is 16bit, whereas AppCore used
// 32bit (int), so how do we handle this?
if (Callbacks != null && Callbacks.EditedRootBox != null)
{
VwShiftStatus ss = GetShiftStatus(modifiers);
StringBuilder buffer = new StringBuilder();
CollectTypedInput(keyChar, buffer);
OnCharAux(buffer.ToString(), ss, modifiers);
}
}
/// -----------------------------------------------------------------------------------
/// <summary>
/// Returns the ShiftStatus that shows if Ctrl and/or Shift keys were pressed
/// </summary>
/// <param name="keys">The key state</param>
/// <returns>The shift status</returns>
/// -----------------------------------------------------------------------------------
public static VwShiftStatus GetShiftStatus(Keys keys)
{
// Test whether the Ctrl and/or Shift keys are also being pressed.
VwShiftStatus ss = VwShiftStatus.kfssNone;
if ((keys & Keys.Shift) == Keys.Shift)
ss = VwShiftStatus.kfssShift;
if ((keys & Keys.Control) == Keys.Control)
{
if (ss != VwShiftStatus.kfssNone)
ss = VwShiftStatus.kgrfssShiftControl;
else
ss = VwShiftStatus.kfssControl;
}
return ss;
}
/// <summary>
/// Allows subclass to be more selective about combining multiple keystrokes into one event.
/// Contract: may always return true if buffer is empty.
/// Must return false if the buffer is not empty and the next WM_CHAR is delete or return.
/// </summary>
/// <param name="nextChar">The next char that will be processed</param>
/// <returns></returns>
public virtual bool KeepCollectingInput(int nextChar)
{
return nextChar >= ' ' && nextChar != (int)VwSpecialChars.kscDelForward;
}
/// -----------------------------------------------------------------------------------
/// <summary>
/// Collect whatever keyboard input is available--whatever the user has typed ahead.
/// Includes backspaces and delete forwards, but not any more special keys like arrow keys.
/// </summary>
/// <param name="chsFirst">the first character the user typed, which started the whole
/// process.</param>
/// <param name="buffer">output is accumulated here (starting with chsFirst, unless
/// it gets deleted by a subsequent backspace).</param>
/// -----------------------------------------------------------------------------------
protected void CollectTypedInput(char chsFirst, StringBuilder buffer)
{
bool needToVerifySurrogates = char.IsSurrogate(chsFirst);
// The first character goes into the buffer
buffer.Append(chsFirst);
if (Platform.IsMono)
return;
// Note: When/if porting to MONO, the following block of code can be removed
// and still work.
if (chsFirst < ' ' || chsFirst == (char)VwSpecialChars.kscDelForward)
return;
if (Control == null)
return;
// We need to disable type-ahead when using a Keyman keyboard since it can
// mess with the keyboard functionality. (FWR-2205)
bool activeKbIsKeyMan = false;
if (Keyboard.Controller != null && Keyboard.Controller.ActiveKeyboard != null)
{
activeKbIsKeyMan =
Keyboard.Controller.ActiveKeyboard.Format == KeyboardFormat.Keyman ||
Keyboard.Controller.ActiveKeyboard.Format == KeyboardFormat.CompiledKeyman;
}
if (activeKbIsKeyMan)
return;
// Collect any characters that are currently in the message queue
Win32.MSG msg = new Win32.MSG();
while (true)
{
if (Win32.PeekMessage(ref msg, Control.Handle, (uint)Win32.WinMsgs.WM_KEYDOWN,
(uint)Win32.WinMsgs.WM_KEYUP, (uint)Win32.PeekFlags.PM_NOREMOVE))
{
// If the key is the delete key, then process it normally because some
// applications may use the DEL as a menu hotkey, which by this time has
// already processed the keydown message. When that happens, the only
// time we would get here for a DEL key is because we found the WM_KEYUP
// message in the queue. In that case, TranslateMessage fails because
// it only works when both the down and up are translated. The worst that
// should happen with this special DEL key processing is that we don't
// collect the delete keys and they happen one at a time.
if ((int)msg.wParam == (int)Keys.Delete)
break;
// Now that we know we're going to translate the message, we need to
// make sure it's removed from the message queue.
Win32.PeekMessage(ref msg, Control.Handle, (uint)Win32.WinMsgs.WM_KEYDOWN,
(uint)Win32.WinMsgs.WM_KEYUP, (uint)Win32.PeekFlags.PM_REMOVE);
Win32.TranslateMessage(ref msg);
}
else if (Win32.PeekMessage(ref msg, Control.Handle, (uint)Win32.WinMsgs.WM_CHAR,
(uint)Win32.WinMsgs.WM_CHAR, (uint)Win32.PeekFlags.PM_NOREMOVE))
{
char nextChar = (char)msg.wParam;
if (!KeepCollectingInput(nextChar))
break;
// Since the previous peek didn't remove the message and by this point
// we know we want to handle the message ourselves, we need to remove
// the keypress from the message queue.
Win32.PeekMessage(ref msg, Control.Handle, (uint)Win32.WinMsgs.WM_CHAR,
(uint)Win32.WinMsgs.WM_CHAR, (uint)Win32.PeekFlags.PM_REMOVE);
switch ((int)nextChar)
{
case (int)VwSpecialChars.kscBackspace:
// handle backspace characters. If there are are characters in
// the buffer then remove the last one. If not, then count
// the backspace so it will be processed later.
if (buffer.Length > 0)
{
if (buffer[0] == 8 || buffer[0] == 0x7f)
throw new InvalidOperationException(
"KeepCollectingInput should not allow more than one backspace");
buffer.Remove(buffer.Length - 1, 1);
}
else
buffer.Append(nextChar);
return; // only one backspace currently allowed (except canceling earlier data)
case (int)VwSpecialChars.kscDelForward:
case '\r':
if (buffer.Length > 0)
{
throw new InvalidOperationException(
"KeepCollectingInput should not allow more than one delete or return");
}
buffer.Append(nextChar);
return; // only one del currently allowed.
default:
needToVerifySurrogates = needToVerifySurrogates || char.IsSurrogate(nextChar);
// regular characters get added to the buffer
buffer.Append(nextChar);
break;
}
}
else
break;
}
// If there were surrogate characters in the typed input verify that they are all matched pairs
// and clear out the buffer if they are not.
if (needToVerifySurrogates)
{
for (var i = 0; i < buffer.Length; ++i)
{
// if we see a trailing surrogate first, or if we see a leading surrogate with no trailing surrogate
// then alert and clear the buffer.
if (char.IsLowSurrogate(buffer[i]) ||
char.IsHighSurrogate(buffer[i]) && (i == buffer.Length || !char.IsLowSurrogate(buffer[i + 1])))
{
MessageBox.Show("Unmatched surrogate found in key presses.");
buffer.Clear();
break;
}
if (char.IsHighSurrogate(buffer[i]))
{
// If we get here we had a valid pair so skip the second half
++i;
}
}
}
}
/// <summary>
/// Helper method that wraps DeleteRangeIfComplex
/// </summary>
internal bool DeleteRangeIfComplex(IVwRootBox rootbox)
{
bool fWasComplex = false;
IVwGraphics vg = GetGraphics();
try
{
rootbox.DeleteRangeIfComplex(vg, out fWasComplex);
}
finally
{
EditedRootBox.Site.ReleaseGraphics(rootbox, vg);
}
return fWasComplex;
}
/// -----------------------------------------------------------------------------------
/// <summary>
/// Handle typed character.
/// Caller should ensure this is wrapped in a UOW (typically done in an override of
/// OnKeyPress in RootSiteEditingHelper, since SimpleRootSite does not have access
/// to FDO and UOW).
/// </summary>
/// <param name="input">input string</param>
/// <param name="shiftStatus">Status of Shift/Control/Alt key</param>
/// <param name="modifiers">key modifiers - shift status, etc.</param>
/// -----------------------------------------------------------------------------------