-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
UIElement.cs
4848 lines (4201 loc) · 191 KB
/
UIElement.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
using MS.Internal;
using MS.Internal.Interop;
using MS.Internal.KnownBoxes;
using MS.Internal.Media;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Input;
using System.Windows.Input.StylusPlugIns;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using MS.Win32;
namespace System.Windows
{
/// <summary>
/// Visibility - Enum which describes 3 possible visibility options.
/// </summary>
/// <seealso cref="UIElement" />
public enum Visibility : byte
{
/// <summary>
/// Normally visible.
/// </summary>
Visible = 0,
/// <summary>
/// Occupies space in the layout, but is not visible (completely transparent).
/// </summary>
Hidden,
/// <summary>
/// Not visible and does not occupy any space in layout, as if it doesn't exist.
/// </summary>
Collapsed
}
// PreSharp uses message numbers that the C# compiler doesn't know about.
// Disable the C# complaints, per the PreSharp documentation.
#pragma warning disable 1634, 1691
/// <summary>
/// UIElement is the base class for frameworks building on the Windows Presentation Core.
/// </summary>
/// <remarks>
/// UIElement adds to the base visual class "LIFE" - Layout, Input, Focus, and Eventing.
/// UIElement can be considered roughly equivalent to an HWND in Win32, or an Element in Trident.
/// UIElements can render (because they derive from Visual), visually size and position their children,
/// respond to user input (including control of where input is getting sent to),
/// and raise events that traverse the physical tree.<para/>
///
/// UIElement is the most functional type in the Windows Presentation Core.
/// </remarks>
[UidProperty("Uid")]
public partial class UIElement : Visual, IInputElement, IAnimatable
{
static UIElement()
{
UIElement.RegisterEvents(typeof(UIElement));
RenderOptions.EdgeModeProperty.OverrideMetadata(
typeof(UIElement),
new UIPropertyMetadata(new PropertyChangedCallback(EdgeMode_Changed)));
RenderOptions.BitmapScalingModeProperty.OverrideMetadata(
typeof(UIElement),
new UIPropertyMetadata(new PropertyChangedCallback(BitmapScalingMode_Changed)));
RenderOptions.ClearTypeHintProperty.OverrideMetadata(
typeof(UIElement),
new UIPropertyMetadata(new PropertyChangedCallback(ClearTypeHint_Changed)));
TextOptionsInternal.TextHintingModeProperty.OverrideMetadata(
typeof(UIElement),
new UIPropertyMetadata(new PropertyChangedCallback(TextHintingMode_Changed)));
EventManager.RegisterClassHandler(typeof(UIElement), ManipulationStartingEvent, new EventHandler<ManipulationStartingEventArgs>(OnManipulationStartingThunk));
EventManager.RegisterClassHandler(typeof(UIElement), ManipulationStartedEvent, new EventHandler<ManipulationStartedEventArgs>(OnManipulationStartedThunk));
EventManager.RegisterClassHandler(typeof(UIElement), ManipulationDeltaEvent, new EventHandler<ManipulationDeltaEventArgs>(OnManipulationDeltaThunk));
EventManager.RegisterClassHandler(typeof(UIElement), ManipulationInertiaStartingEvent, new EventHandler<ManipulationInertiaStartingEventArgs>(OnManipulationInertiaStartingThunk));
EventManager.RegisterClassHandler(typeof(UIElement), ManipulationBoundaryFeedbackEvent, new EventHandler<ManipulationBoundaryFeedbackEventArgs>(OnManipulationBoundaryFeedbackThunk));
EventManager.RegisterClassHandler(typeof(UIElement), ManipulationCompletedEvent, new EventHandler<ManipulationCompletedEventArgs>(OnManipulationCompletedThunk));
}
/// <summary>
/// Constructor. This form of constructor will encounter a slight perf hit since it needs to initialize Dispatcher for the instance.
/// </summary>
public UIElement()
{
Initialize();
}
private void Initialize()
{
BeginPropertyInitialization();
NeverMeasured = true;
NeverArranged = true;
SnapsToDevicePixelsCache = (bool) SnapsToDevicePixelsProperty.GetDefaultValue(DependencyObjectType);
ClipToBoundsCache = (bool) ClipToBoundsProperty.GetDefaultValue(DependencyObjectType);
VisibilityCache = (Visibility) VisibilityProperty.GetDefaultValue(DependencyObjectType);
SetFlags(true, VisualFlags.IsUIElement);
// Note: IsVisibleCache is false by default.
if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Verbose))
{
PerfService.GetPerfElementID(this);
}
}
#region AllowDrop
/// <summary>
/// The DependencyProperty for the AllowDrop property.
/// </summary>
public static readonly DependencyProperty AllowDropProperty =
DependencyProperty.Register(
"AllowDrop",
typeof(bool),
typeof(UIElement),
new PropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>
/// A dependency property that allows the drop object as DragDrop target.
/// </summary>
public bool AllowDrop
{
get { return (bool) GetValue(AllowDropProperty); }
set { SetValue(AllowDropProperty, BooleanBoxes.Box(value)); }
}
#endregion AllowDrop
/// <summary>
/// Get the StylusPlugInCollection associated with the UIElement
/// </summary>
protected StylusPlugInCollection StylusPlugIns
{
get
{
StylusPlugInCollection stylusCollection = StylusPlugInsField.GetValue(this);
if (stylusCollection == null)
{
stylusCollection = new StylusPlugInCollection(this);
StylusPlugInsField.SetValue(this, stylusCollection);
}
return stylusCollection;
}
}
/// <summary>
/// Returns the size the element computed during the Measure pass.
/// This is only valid if IsMeasureValid is true.
/// </summary>
public Size DesiredSize
{
get
{
if(this.Visibility == Visibility.Collapsed)
return new Size(0,0);
else
return _desiredSize;
}
}
internal Size PreviousConstraint
{
get
{
return _previousAvailableSize;
}
}
// This is needed to prevent dirty elements from drawing and crashing while doing so.
private bool IsRenderable()
{
//elements that were created but never invalidated/measured are clean
//from layout perspective, but we still don't want to render them
//because they don't have state build up enough for that.
if(NeverMeasured || NeverArranged)
return false;
//if element is collapsed, no rendering is needed
//it is not only perf optimization, but also protection from
//UIElement to break itself since RenderSize is reported as (0,0)
//when UIElement is Collapsed
if(ReadFlag(CoreFlags.IsCollapsed))
return false;
return IsMeasureValid && IsArrangeValid;
}
internal void InvalidateMeasureInternal()
{
MeasureDirty = true;
}
internal void InvalidateArrangeInternal()
{
ArrangeDirty = true;
}
/// <summary>
/// Determines if the DesiredSize is valid.
/// </summary>
/// <remarks>
/// A developer can force arrangement to be invalidated by calling InvalidateMeasure.
/// IsArrangeValid and IsMeasureValid are related,
/// in that arrangement cannot be valid without measurement first being valid.
/// </remarks>
public bool IsMeasureValid
{
get { return !MeasureDirty; }
}
/// <summary>
/// Determines if the RenderSize and position of child elements is valid.
/// </summary>
/// <remarks>
/// A developer can force arrangement to be invalidated by calling InvalidateArrange.
/// IsArrangeValid and IsMeasureValid are related, in that arrangement cannot be valid without measurement first
/// being valid.
/// </remarks>
public bool IsArrangeValid
{
get { return !ArrangeDirty; }
}
/// <summary>
/// Invalidates the measurement state for the element.
/// This has the effect of also invalidating the arrange state for the element.
/// The element will be queued for an update layout that will occur asynchronously.
/// </summary>
public void InvalidateMeasure()
{
if( !MeasureDirty
&& !MeasureInProgress )
{
Debug.Assert(MeasureRequest == null, "can't be clean and still have MeasureRequest");
// VerifyAccess();
if(!NeverMeasured) //only measured once elements are allowed in *update* queue
{
ContextLayoutManager ContextLayoutManager = ContextLayoutManager.From(Dispatcher);
if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose))
{
// Knowing when the layout queue goes from clean to dirty is interesting.
if (ContextLayoutManager.MeasureQueue.IsEmpty)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientLayoutInvalidated, EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose, PerfService.GetPerfElementID(this));
}
}
ContextLayoutManager.MeasureQueue.Add(this);
}
MeasureDirty = true;
}
}
/// <summary>
/// Invalidates the arrange state for the element.
/// The element will be queued for an update layout that will occur asynchronously.
/// MeasureCore will not be called unless InvalidateMeasure is also called - or that something
/// else caused the measure state to be invalidated.
/// </summary>
public void InvalidateArrange()
{
if( !ArrangeDirty
&& !ArrangeInProgress)
{
Debug.Assert(ArrangeRequest == null, "can't be clean and still have MeasureRequest");
// VerifyAccess();
if(!NeverArranged)
{
ContextLayoutManager ContextLayoutManager = ContextLayoutManager.From(Dispatcher);
ContextLayoutManager.ArrangeQueue.Add(this);
}
ArrangeDirty = true;
}
}
/// <summary>
/// Invalidates the rendering of the element.
/// Causes <see cref="System.Windows.UIElement.OnRender"/> to be called at a later time.
/// </summary>
public void InvalidateVisual()
{
InvalidateArrange();
RenderingInvalidated = true;
}
/// <summary>
/// Notification that is called by Measure of a child when
/// it ends up with different desired size for the child.
/// </summary>
/// <remarks>
/// Default implementation simply calls invalidateMeasure(), assuming that layout of a
/// parent should be updated after child changed its size.<para/>
/// Finer point: this method can only be called in the scenario when the system calls Measure on a child,
/// not when parent calls it since if parent calls it, it means parent has dirty layout and is recalculating already.
/// </remarks>
protected virtual void OnChildDesiredSizeChanged(UIElement child)
{
if(IsMeasureValid)
{
InvalidateMeasure();
}
}
/// <summary>
/// This event fires every time Layout updates the layout of the trees associated with current Dispatcher.
/// Layout update can happen as a result of some propety change, window resize or explicit user request.
/// </summary>
public event EventHandler LayoutUpdated
{
add
{
LayoutEventList.ListItem item = getLayoutUpdatedHandler(value);
if(item == null)
{
//set a weak ref in LM
item = ContextLayoutManager.From(Dispatcher).LayoutEvents.Add(value);
addLayoutUpdatedHandler(value, item);
}
}
remove
{
LayoutEventList.ListItem item = getLayoutUpdatedHandler(value);
if(item != null)
{
removeLayoutUpdatedHandler(value);
//remove a weak ref from LM
ContextLayoutManager.From(Dispatcher).LayoutEvents.Remove(item);
}
}
}
private void addLayoutUpdatedHandler(EventHandler handler, LayoutEventList.ListItem item)
{
object cachedLayoutUpdatedItems = LayoutUpdatedListItemsField.GetValue(this);
if(cachedLayoutUpdatedItems == null)
{
LayoutUpdatedListItemsField.SetValue(this, item);
LayoutUpdatedHandlersField.SetValue(this, handler);
}
else
{
EventHandler cachedLayoutUpdatedHandler = LayoutUpdatedHandlersField.GetValue(this);
if(cachedLayoutUpdatedHandler != null)
{
//second unique handler is coming in.
//allocate a datastructure
Hashtable list = new Hashtable(2);
//add previously cached handler
list.Add(cachedLayoutUpdatedHandler, cachedLayoutUpdatedItems);
//add new handler
list.Add(handler, item);
LayoutUpdatedHandlersField.ClearValue(this);
LayoutUpdatedListItemsField.SetValue(this,list);
}
else //already have a list
{
Hashtable list = (Hashtable)cachedLayoutUpdatedItems;
list.Add(handler, item);
}
}
}
private LayoutEventList.ListItem getLayoutUpdatedHandler(EventHandler d)
{
object cachedLayoutUpdatedItems = LayoutUpdatedListItemsField.GetValue(this);
if(cachedLayoutUpdatedItems == null)
{
return null;
}
else
{
EventHandler cachedLayoutUpdatedHandler = LayoutUpdatedHandlersField.GetValue(this);
if(cachedLayoutUpdatedHandler != null)
{
if(cachedLayoutUpdatedHandler == d) return (LayoutEventList.ListItem)cachedLayoutUpdatedItems;
}
else //already have a list
{
Hashtable list = (Hashtable)cachedLayoutUpdatedItems;
LayoutEventList.ListItem item = (LayoutEventList.ListItem)(list[d]);
return item;
}
return null;
}
}
private void removeLayoutUpdatedHandler(EventHandler d)
{
object cachedLayoutUpdatedItems = LayoutUpdatedListItemsField.GetValue(this);
EventHandler cachedLayoutUpdatedHandler = LayoutUpdatedHandlersField.GetValue(this);
if(cachedLayoutUpdatedHandler != null) //single handler
{
if(cachedLayoutUpdatedHandler == d)
{
LayoutUpdatedListItemsField.ClearValue(this);
LayoutUpdatedHandlersField.ClearValue(this);
}
}
else //there is an ArrayList allocated
{
Hashtable list = (Hashtable)cachedLayoutUpdatedItems;
list.Remove(d);
}
}
/// <summary>
/// Recursively propagates IsLayoutSuspended flag down to the whole v's sub tree.
/// </summary>
internal static void PropagateSuspendLayout(Visual v)
{
if(v.CheckFlagsAnd(VisualFlags.IsLayoutIslandRoot)) return;
//the subtree is already suspended - happens when already suspended tree is further disassembled
//no need to walk down in this case
if(v.CheckFlagsAnd(VisualFlags.IsLayoutSuspended)) return;
// Assert that a UIElement has not being
// removed from the visual tree while updating layout.
if ( Invariant.Strict
&& v.CheckFlagsAnd(VisualFlags.IsUIElement) )
{
UIElement e = (UIElement)v;
Invariant.Assert(!e.MeasureInProgress && !e.ArrangeInProgress);
}
v.SetFlags(true, VisualFlags.IsLayoutSuspended);
v.TreeLevel = 0;
int count = v.InternalVisualChildrenCount;
for (int i = 0; i < count; i++)
{
Visual cv = v.InternalGetVisualChild(i);
if (cv != null)
{
PropagateSuspendLayout(cv);
}
}
}
/// <summary>
/// Recursively resets IsLayoutSuspended flag on all visuals of the whole v's sub tree.
/// For UIElements also re-inserts the UIElement into Measure and / or Arrange update queues
/// if necessary.
/// </summary>
internal static void PropagateResumeLayout(Visual parent, Visual v)
{
if(v.CheckFlagsAnd(VisualFlags.IsLayoutIslandRoot)) return;
//the subtree is already active - happens when new elements are added to the active tree
//elements are created layout-active so they don't need to be specifically unsuspended
//no need to walk down in this case
//if(!v.CheckFlagsAnd(VisualFlags.IsLayoutSuspended)) return;
//that can be true only on top of recursion, if suspended v is being connected to suspended parent.
bool parentIsSuspended = parent == null ? false : parent.CheckFlagsAnd(VisualFlags.IsLayoutSuspended);
uint parentTreeLevel = parent == null ? 0 : parent.TreeLevel;
if(parentIsSuspended) return;
v.SetFlags(false, VisualFlags.IsLayoutSuspended);
v.TreeLevel = parentTreeLevel + 1;
if (v.CheckFlagsAnd(VisualFlags.IsUIElement))
{
// re-insert UIElement into the update queues
UIElement e = (UIElement)v;
Invariant.Assert(!e.MeasureInProgress && !e.ArrangeInProgress);
bool requireMeasureUpdate = e.MeasureDirty && !e.NeverMeasured && (e.MeasureRequest == null);
bool requireArrangeUpdate = e.ArrangeDirty && !e.NeverArranged && (e.ArrangeRequest == null);
ContextLayoutManager contextLayoutManager = (requireMeasureUpdate || requireArrangeUpdate)
? ContextLayoutManager.From(e.Dispatcher)
: null;
if (requireMeasureUpdate)
{
contextLayoutManager.MeasureQueue.Add(e);
}
if (requireArrangeUpdate)
{
contextLayoutManager.ArrangeQueue.Add(e);
}
}
int count = v.InternalVisualChildrenCount;
for (int i = 0; i < count; i++)
{
Visual cv = v.InternalGetVisualChild(i);
if (cv != null)
{
PropagateResumeLayout(v, cv);
}
}
}
/// <summary>
/// Updates DesiredSize of the UIElement. Must be called by parents from theor MeasureCore, to form recursive update.
/// This is first pass of layout update.
/// </summary>
/// <remarks>
/// Measure is called by parents on their children. Internally, Measure calls MeasureCore override on the same object,
/// giving it opportunity to compute its DesiredSize.<para/>
/// This method will return immediately if child is not Dirty, previously measured
/// and availableSize is the same as cached. <para/>
/// This method also resets the IsMeasureinvalid bit on the child.<para/>
/// In case when "unbounded measure to content" is needed, parent can use availableSize
/// as double.PositiveInfinity. Any returned size is OK in this case.
/// </remarks>
/// <param name="availableSize">Available size that parent can give to the child. May be infinity (when parent wants to
/// measure to content). This is soft constraint. Child can return bigger size to indicate that it wants bigger space and hope
/// that parent can throw in scrolling...</param>
public void Measure(Size availableSize)
{
bool etwTracingEnabled = false;
long perfElementID = 0;
ContextLayoutManager ContextLayoutManager = ContextLayoutManager.From(Dispatcher);
if (ContextLayoutManager.AutomationEvents.Count != 0)
UIElementHelper.InvalidateAutomationAncestors(this);
if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose))
{
perfElementID = PerfService.GetPerfElementID(this);
etwTracingEnabled = true;
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientMeasureElementBegin, EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose, perfElementID, availableSize.Width, availableSize.Height);
}
try
{
// VerifyAccess();
// Disable reentrancy during the measure pass. This is because much work is done
// during measure - such as inflating templates, formatting PTS stuff, creating
// fonts, etc. Generally speaking, we cannot survive reentrancy in these code
// paths.
using (Dispatcher.DisableProcessing())
{
//enforce that Measure can not receive NaN size .
if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height))
throw new InvalidOperationException(SR.UIElement_Layout_NaNMeasure);
bool neverMeasured = NeverMeasured;
if (neverMeasured)
{
switchVisibilityIfNeeded(this.Visibility);
//to make sure effects are set correctly - otherwise it's not used
//simply because it is never pulled by anybody
pushVisualEffects();
}
bool isCloseToPreviousMeasure = DoubleUtil.AreClose(availableSize, _previousAvailableSize);
//if Collapsed, we should not Measure, keep dirty bit but remove request
if (this.Visibility == Visibility.Collapsed
|| ((Visual)this).CheckFlagsAnd(VisualFlags.IsLayoutSuspended))
{
//reset measure request.
if (MeasureRequest != null)
ContextLayoutManager.From(Dispatcher).MeasureQueue.Remove(this);
// remember though that parent tried to measure at this size
// in case when later this element is called to measure incrementally
// it has up-to-date information stored in _previousAvailableSize
if (!isCloseToPreviousMeasure)
{
//this will ensure that element will be actually re-measured at the new available size
//later when it becomes visible.
InvalidateMeasureInternal();
_previousAvailableSize = availableSize;
}
return;
}
//your basic bypass. No reason to calc the same thing.
if (IsMeasureValid //element is clean
&& !neverMeasured //previously measured
&& isCloseToPreviousMeasure) //and contraint matches
{
return;
}
NeverMeasured = false;
Size prevSize = _desiredSize;
//we always want to be arranged, ensure arrange request
//doing it before OnMeasure prevents unneeded requests from children in the queue
InvalidateArrange();
//_measureInProgress prevents OnChildDesiredSizeChange to cause the elements be put
//into the queue.
MeasureInProgress = true;
Size desiredSize = new Size(0, 0);
ContextLayoutManager layoutManager = ContextLayoutManager.From(Dispatcher);
bool gotException = true;
try
{
layoutManager.EnterMeasure();
desiredSize = MeasureCore(availableSize);
gotException = false;
}
finally
{
// reset measure in progress
MeasureInProgress = false;
_previousAvailableSize = availableSize;
layoutManager.ExitMeasure();
if (gotException)
{
// we don't want to reset last exception element on layoutManager if it's been already set.
if (layoutManager.GetLastExceptionElement() == null)
{
layoutManager.SetLastExceptionElement(this);
}
}
}
//enforce that MeasureCore can not return PositiveInfinity size even if given Infinte availabel size.
//Note: NegativeInfinity can not be returned by definition of Size structure.
if (double.IsPositiveInfinity(desiredSize.Width) || double.IsPositiveInfinity(desiredSize.Height))
throw new InvalidOperationException(SR.Format(SR.UIElement_Layout_PositiveInfinityReturned, this.GetType().FullName));
//enforce that MeasureCore can not return NaN size .
if (double.IsNaN(desiredSize.Width) || double.IsNaN(desiredSize.Height))
throw new InvalidOperationException(SR.Format(SR.UIElement_Layout_NaNReturned, this.GetType().FullName));
//reset measure dirtiness
MeasureDirty = false;
//reset measure request.
if (MeasureRequest != null)
ContextLayoutManager.From(Dispatcher).MeasureQueue.Remove(this);
//cache desired size
_desiredSize = desiredSize;
//notify parent if our desired size changed (watefall effect)
if (!MeasureDuringArrange
&& !DoubleUtil.AreClose(prevSize, desiredSize))
{
UIElement p;
IContentHost ich;
GetUIParentOrICH(out p, out ich); //only one will be returned
if (p != null && !p.MeasureInProgress) //this is what differs this code from signalDesiredSizeChange()
p.OnChildDesiredSizeChanged(this);
else if (ich != null)
ich.OnChildDesiredSizeChanged(this);
}
}
}
finally
{
if (etwTracingEnabled == true)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientMeasureElementEnd, EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose, perfElementID, _desiredSize.Width, _desiredSize.Height);
}
}
}
//only one will be returned, whichever found first
internal void GetUIParentOrICH(out UIElement uiParent, out IContentHost ich)
{
ich = null;
uiParent = null;
for(Visual v = VisualTreeHelper.GetParent(this) as Visual; v != null; v = VisualTreeHelper.GetParent(v) as Visual)
{
ich = v as IContentHost;
if (ich != null) break;
if(v.CheckFlagsAnd(VisualFlags.IsUIElement))
{
uiParent = (UIElement)v;
break;
}
}
}
//walks visual tree up to find UIElement parent within Element Layout Island, so stops the walk if the island's root is found
internal UIElement GetUIParentWithinLayoutIsland()
{
UIElement uiParent = null;
for(Visual v = VisualTreeHelper.GetParent(this) as Visual; v != null; v = VisualTreeHelper.GetParent(v) as Visual)
{
if (v.CheckFlagsAnd(VisualFlags.IsLayoutIslandRoot))
{
break;
}
if(v.CheckFlagsAnd(VisualFlags.IsUIElement))
{
uiParent = (UIElement)v;
break;
}
}
return uiParent;
}
/// <summary>
/// Parents or system call this method to arrange the internals of children on a second pass of layout update.
/// </summary>
/// <remarks>
/// This method internally calls ArrangeCore override, giving the derived class opportunity
/// to arrange its children and/or content using final computed size.
/// In their ArrangeCore overrides, derived class is supposed to create its visual structure and
/// prepare itself for rendering. Arrange is called by parents
/// from their implementation of ArrangeCore or by system when needed.
/// This method sets Bounds=finalSize before calling ArrangeCore.
/// </remarks>
/// <param name="finalRect">This is the final size and location that parent or system wants this UIElement to assume.</param>
public void Arrange(Rect finalRect)
{
bool etwTracingEnabled = false;
long perfElementID = 0;
ContextLayoutManager ContextLayoutManager = ContextLayoutManager.From(Dispatcher);
if (ContextLayoutManager.AutomationEvents.Count != 0)
UIElementHelper.InvalidateAutomationAncestors(this);
if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose))
{
perfElementID = PerfService.GetPerfElementID(this);
etwTracingEnabled = true;
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientArrangeElementBegin, EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose, perfElementID, finalRect.Top, finalRect.Left, finalRect.Width, finalRect.Height);
}
try
{
// VerifyAccess();
// Disable reentrancy during the arrange pass. This is because much work is done
// during arrange - such as formatting PTS stuff, creating
// fonts, etc. Generally speaking, we cannot survive reentrancy in these code
// paths.
using (Dispatcher.DisableProcessing())
{
//enforce that Arrange can not come with Infinity size or NaN
if (double.IsPositiveInfinity(finalRect.Width)
|| double.IsPositiveInfinity(finalRect.Height)
|| double.IsNaN(finalRect.Width)
|| double.IsNaN(finalRect.Height)
)
{
DependencyObject parent = GetUIParent() as UIElement;
throw new InvalidOperationException(
SR.Format(
SR.UIElement_Layout_InfinityArrange,
(parent == null ? "" : parent.GetType().FullName),
this.GetType().FullName));
}
//if Collapsed, we should not Arrange, keep dirty bit but remove request
if (this.Visibility == Visibility.Collapsed
|| ((Visual)this).CheckFlagsAnd(VisualFlags.IsLayoutSuspended))
{
//reset arrange request.
if (ArrangeRequest != null)
ContextLayoutManager.From(Dispatcher).ArrangeQueue.Remove(this);
// remember though that parent tried to arrange at this rect
// in case when later this element is called to arrange incrementally
// it has up-to-date information stored in _finalRect
_finalRect = finalRect;
return;
}
//in case parent did not call Measure on a child, we call it now.
//parent can skip calling Measure on a child if it does not care about child's size
//passing finalSize practically means "set size" because that's what Measure(sz)/Arrange(same_sz) means
//Note that in case of IsLayoutSuspended (temporarily out of the tree) the MeasureDirty can be true
//while it does not indicate that we should re-measure - we just came of Measure that did nothing
//because of suspension
if (MeasureDirty
|| NeverMeasured)
{
try
{
MeasureDuringArrange = true;
//If never measured - that means "set size", arrange-only scenario
//Otherwise - the parent previosuly measured the element at constriant
//and the fact that we are arranging the measure-dirty element now means
//we are not in the UpdateLayout loop but rather in manual sequence of Measure/Arrange
//(like in HwndSource when new RootVisual is attached) so there are no loops and there could be
//measure-dirty elements left after previosu single Measure pass) - so need to use cached constraint
if (NeverMeasured)
Measure(finalRect.Size);
else
{
Measure(PreviousConstraint);
}
}
finally
{
MeasureDuringArrange = false;
}
}
//bypass - if clean and rect is the same, no need to re-arrange
if (!IsArrangeValid
|| NeverArranged
|| !DoubleUtil.AreClose(finalRect, _finalRect))
{
bool firstArrange = NeverArranged;
NeverArranged = false;
ArrangeInProgress = true;
ContextLayoutManager layoutManager = ContextLayoutManager.From(Dispatcher);
Size oldSize = RenderSize;
bool sizeChanged = false;
bool gotException = true;
// If using layout rounding, round final size before calling ArrangeCore.
if (CheckFlagsAnd(VisualFlags.UseLayoutRounding))
{
DpiScale dpi = GetDpi();
finalRect = RoundLayoutRect(finalRect, dpi.DpiScaleX, dpi.DpiScaleY);
}
try
{
layoutManager.EnterArrange();
//This has to update RenderSize
ArrangeCore(finalRect);
//to make sure Clip is tranferred to Visual
ensureClip(finalRect.Size);
// see if we need to call OnRenderSizeChanged on this element
sizeChanged = markForSizeChangedIfNeeded(oldSize, RenderSize);
gotException = false;
}
finally
{
ArrangeInProgress = false;
layoutManager.ExitArrange();
if (gotException)
{
// we don't want to reset last exception element on layoutManager if it's been already set.
if (layoutManager.GetLastExceptionElement() == null)
{
layoutManager.SetLastExceptionElement(this);
}
}
}
_finalRect = finalRect;
ArrangeDirty = false;
//reset request.
if (ArrangeRequest != null)
ContextLayoutManager.From(Dispatcher).ArrangeQueue.Remove(this);
if ((sizeChanged || RenderingInvalidated || firstArrange) && IsRenderable())
{
DrawingContext dc = RenderOpen();
try
{
bool etwGeneralEnabled = EventTrace.IsEnabled(EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose);
if (etwGeneralEnabled == true)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientOnRenderBegin, EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose, perfElementID);
}
try
{
OnRender(dc);
}
finally
{
if (etwGeneralEnabled == true)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientOnRenderEnd, EventTrace.Keyword.KeywordGraphics | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose, perfElementID);
}
}
}
finally
{
dc.Close();
RenderingInvalidated = false;
}
updatePixelSnappingGuidelines();
}
if (firstArrange)
{
EndPropertyInitialization();
}
}
}
}
finally
{
if (etwTracingEnabled == true)
{
EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientArrangeElementEnd, EventTrace.Keyword.KeywordLayout, EventTrace.Level.Verbose, perfElementID, finalRect.Top, finalRect.Left, finalRect.Width, finalRect.Height);
}
}
}
/// <summary>
/// OnRender is called by the base class when the rendering instructions of the UIElement are required.
/// Note: the drawing instructions sent to DrawingContext are not rendered immediately on the screen
/// but rather stored and later passed to the rendering engine at proper time.
/// Derived classes override this method to draw the content of the UIElement.
/// </summary>
protected virtual void OnRender(DrawingContext drawingContext)
{
}
private void updatePixelSnappingGuidelines()
{
if((!SnapsToDevicePixels) || (_drawingContent == null))
{
this.VisualXSnappingGuidelines = this.VisualYSnappingGuidelines = null;
}
else
{
DoubleCollection xLines = this.VisualXSnappingGuidelines;
if(xLines == null)
{
xLines = new DoubleCollection();
xLines.Add(0d);
xLines.Add(this.RenderSize.Width);
this.VisualXSnappingGuidelines = xLines;
}
else