2009-11-08 Chris Toshok <toshok@ximian.com>
[moon.git] / src / uielement.cpp
blob5c99a5feacadd187eb56af51023c2bf973f0f9d7
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3 * uielement.cpp
5 * Copyright 2007 Novell, Inc. (http://www.novell.com)
7 * See the LICENSE file included with the distribution for details.
8 *
9 */
11 #include <config.h>
13 #include <stdlib.h>
14 #include <math.h>
16 #include "trigger.h"
17 #include "uielement.h"
18 #include "collection.h"
19 #include "canvas.h"
20 #include "brush.h"
21 #include "transform.h"
22 #include "runtime.h"
23 #include "geometry.h"
24 #include "shape.h"
25 #include "dirty.h"
26 #include "eventargs.h"
27 #include "timemanager.h"
28 #include "media.h"
29 #include "resources.h"
30 #include "popup.h"
31 #include "provider.h"
33 //#define DEBUG_INVALIDATE 0
34 #define MIN_FRONT_TO_BACK_COUNT 25
36 UIElement::UIElement ()
38 SetObjectType (Type::UIELEMENT);
40 visual_level = 0;
41 visual_parent = NULL;
42 subtree_object = NULL;
43 opacityMask = NULL;
45 flags = UIElement::RENDER_VISIBLE | UIElement::HIT_TEST_VISIBLE;
47 bounds = Rect (0,0,0,0);
48 cairo_matrix_init_identity (&absolute_xform);
50 emitting_loaded = false;
51 dirty_flags = DirtyMeasure;
52 up_dirty_node = down_dirty_node = NULL;
53 force_invalidate_of_new_bounds = false;
54 dirty_region = new Region ();
56 desired_size = Size (0, 0);
57 render_size = Size (0, 0);
59 ComputeLocalTransform ();
60 ComputeTotalRenderVisibility ();
61 ComputeTotalHitTestVisibility ();
64 UIElement::~UIElement()
66 delete dirty_region;
69 bool
70 UIElement::IsSubtreeLoaded (UIElement *element)
72 while (element && !element->IsLoaded ())
73 element = element->GetVisualParent ();
74 return element;
77 void
78 UIElement::Dispose()
80 TriggerCollection *triggers = GetTriggers ();
82 if (triggers != NULL) {
83 for (int i = 0; i < triggers->GetCount (); i++)
84 triggers->GetValueAt (i)->AsEventTrigger ()->RemoveTarget (this);
87 if (!IsDisposed ()) {
88 VisualTreeWalker walker (this);
89 while (UIElement *child = walker.Step ())
90 child->SetVisualParent (NULL);
93 if (subtree_object) {
94 subtree_object->unref ();
95 subtree_object = NULL;
98 DependencyObject::Dispose();
101 void
102 UIElement::SetSurface (Surface *s)
104 if (GetSurface() == s)
105 return;
107 if (s == NULL && GetSurface()) {
108 /* we're losing our surface, delete ourselves from the dirty list if we're on it */
109 GetSurface()->RemoveDirtyElement (this);
112 if (subtree_object != NULL && subtree_object->Is(Type::UIELEMENT))
113 subtree_object->SetSurface (s);
115 DependencyObject::SetSurface (s);
118 Rect
119 UIElement::IntersectBoundsWithClipPath (Rect unclipped, bool transform)
121 Geometry *clip = GetClip ();
122 Geometry *layout_clip = transform ? NULL : LayoutInformation::GetLayoutClip (this);
123 Rect box;
125 if (!clip && !layout_clip)
126 return unclipped;
128 if (clip)
129 box = clip->GetBounds ();
130 else
131 box = layout_clip->GetBounds ();
133 if (layout_clip)
134 box = box.Intersection (layout_clip->GetBounds());
136 if (!GetRenderVisible())
137 box = Rect (0,0,0,0);
139 if (transform)
140 box = box.Transform (&absolute_xform);
142 return box.Intersection (unclipped);
145 void
146 UIElement::RenderClipPath (cairo_t *cr, bool path_only)
148 cairo_new_path (cr);
149 cairo_set_matrix (cr, &absolute_xform);
151 Geometry *geometry = GetClip();
152 if (!geometry)
153 return;
155 geometry->Draw (cr);
156 if (!path_only)
157 cairo_clip (cr);
160 void
161 UIElement::OnPropertyChanged (PropertyChangedEventArgs *args, MoonError *error)
163 if (args->GetProperty ()->GetOwnerType() != Type::UIELEMENT) {
164 DependencyObject::OnPropertyChanged (args, error);
165 return;
168 if (args->GetId () == UIElement::OpacityProperty) {
169 InvalidateVisibility ();
170 } else if (args->GetId () == UIElement::VisibilityProperty) {
171 // note: invalid enum values are only validated in 1.1 (managed code),
172 // the default value for VisibilityProperty is VisibilityCollapsed
173 // (see bug #340799 for more details)
174 if (args->GetNewValue()->AsInt32() == VisibilityVisible)
175 flags |= UIElement::RENDER_VISIBLE;
176 else
177 flags &= ~UIElement::RENDER_VISIBLE;
179 InvalidateVisibility ();
180 InvalidateMeasure ();
181 if (GetVisualParent ())
182 GetVisualParent ()->InvalidateMeasure ();
183 } else if (args->GetId () == UIElement::IsHitTestVisibleProperty) {
184 if (args->GetNewValue()->AsBool())
185 flags |= UIElement::HIT_TEST_VISIBLE;
186 else
187 flags &= ~UIElement::HIT_TEST_VISIBLE;
189 UpdateTotalHitTestVisibility();
190 } else if (args->GetId () == UIElement::ClipProperty) {
191 InvalidateClip ();
192 } else if (args->GetId () == UIElement::OpacityMaskProperty) {
193 opacityMask = args->GetNewValue() ? args->GetNewValue()->AsBrush() : NULL;
194 InvalidateMask ();
195 } else if (args->GetId () == UIElement::RenderTransformProperty
196 || args->GetId () == UIElement::RenderTransformOriginProperty) {
197 UpdateTransform ();
199 else if (args->GetId () == UIElement::TriggersProperty) {
200 if (args->GetOldValue()) {
201 // remove the old trigger targets
202 TriggerCollection *triggers = args->GetOldValue()->AsTriggerCollection();
203 for (int i = 0; i < triggers->GetCount (); i++)
204 triggers->GetValueAt (i)->AsEventTrigger ()->RemoveTarget (this);
207 if (args->GetNewValue()) {
208 // set the new ones
209 TriggerCollection *triggers = args->GetNewValue()->AsTriggerCollection();
210 for (int i = 0; i < triggers->GetCount (); i++)
211 triggers->GetValueAt (i)->AsEventTrigger ()->SetTarget (this);
213 } else if (args->GetId () == UIElement::UseLayoutRoundingProperty) {
214 InvalidateMeasure ();
215 InvalidateArrange ();
218 NotifyListenersOfPropertyChange (args, error);
221 void
222 UIElement::OnCollectionChanged (Collection *col, CollectionChangedEventArgs *args)
224 if (col == GetTriggers ()) {
225 switch (args->GetChangedAction()) {
226 case CollectionChangedActionReplace:
227 args->GetOldItem()->AsEventTrigger ()->RemoveTarget (this);
228 // fall thru to Add
229 case CollectionChangedActionAdd:
230 args->GetNewItem()->AsEventTrigger ()->SetTarget (this);
231 break;
232 case CollectionChangedActionRemove:
233 args->GetOldItem()->AsEventTrigger ()->RemoveTarget (this);
234 break;
235 case CollectionChangedActionClearing:
236 for (int i = 0; i < col->GetCount (); i++)
237 col->GetValueAt (i)->AsEventTrigger ()->RemoveTarget (this);
238 break;
239 case CollectionChangedActionCleared:
240 // nothing needed here.
241 break;
244 else {
245 DependencyObject::OnCollectionChanged (col, args);
249 #if 1
251 UIElement::DumpHierarchy (UIElement *obj)
253 if (obj == NULL)
254 return 0;
256 int n = DumpHierarchy (obj->GetVisualParent ());
257 for (int i = 0; i < n; i++)
258 putchar (' ');
259 printf ("%s (%p)\n", obj->GetTypeName(), obj);
260 return n + 4;
262 #endif
264 void
265 UIElement::UpdateBounds (bool force_redraw)
267 //InvalidateMeasure ();
268 //InvalidateArrange ();
270 Surface *surface = GetSurface ();
271 if (surface)
272 surface->AddDirtyElement (this, DirtyBounds);
274 force_invalidate_of_new_bounds |= force_redraw;
277 void
278 UIElement::UpdateTotalRenderVisibility ()
280 Surface *surface = GetSurface ();
281 if (surface)
282 surface->AddDirtyElement (this, DirtyRenderVisibility);
285 void
286 UIElement::UpdateTotalHitTestVisibility ()
288 VisualTreeWalker walker (this);
289 while (UIElement *child = walker.Step ())
290 child->UpdateTotalHitTestVisibility ();
292 if (GetSurface())
293 GetSurface ()->AddDirtyElement (this, DirtyHitTestVisibility);
296 bool
297 UIElement::GetActualTotalRenderVisibility ()
299 bool visible = (flags & UIElement::RENDER_VISIBLE) != 0;
300 bool parent_visible = true;
302 total_opacity = GetOpacity ();
304 if (GetVisualParent ()) {
305 GetVisualParent ()->ComputeTotalRenderVisibility ();
306 parent_visible = visible && GetVisualParent ()->GetRenderVisible ();
307 total_opacity *= GetVisualParent ()->total_opacity;
310 visible = visible && parent_visible;
312 return visible;
315 void
316 UIElement::ComputeTotalRenderVisibility ()
318 if (GetActualTotalRenderVisibility ())
319 flags |= UIElement::TOTAL_RENDER_VISIBLE;
320 else
321 flags &= ~UIElement::TOTAL_RENDER_VISIBLE;
324 bool
325 UIElement::GetActualTotalHitTestVisibility ()
327 bool visible = (flags & UIElement::HIT_TEST_VISIBLE) != 0;
329 if (visible && GetVisualParent ()) {
330 GetVisualParent ()->ComputeTotalHitTestVisibility ();
331 visible = visible && GetVisualParent ()->GetHitTestVisible ();
334 return visible;
337 void
338 UIElement::ComputeTotalHitTestVisibility ()
340 if (GetActualTotalHitTestVisibility ())
341 flags |= UIElement::TOTAL_HIT_TEST_VISIBLE;
342 else
343 flags &= ~UIElement::TOTAL_HIT_TEST_VISIBLE;
346 void
347 UIElement::UpdateTransform ()
349 InvalidateArrange ();
351 if (GetSurface()) {
352 GetSurface()->AddDirtyElement (this, DirtyLocalTransform);
356 void
357 UIElement::ComputeLocalTransform ()
359 Transform *transform = GetRenderTransform ();
360 Point transform_origin = GetTransformOrigin ();
361 cairo_matrix_t render;
363 cairo_matrix_init_identity (&render);
364 cairo_matrix_init_identity (&local_xform);
366 if (transform == NULL)
367 return;
369 transform->GetTransform (&render);
370 cairo_matrix_translate (&local_xform, transform_origin.x, transform_origin.y);
371 cairo_matrix_multiply (&local_xform, &render, &local_xform);
372 cairo_matrix_translate (&local_xform, -transform_origin.x, -transform_origin.y);
375 void
376 UIElement::TransformBounds (cairo_matrix_t *old, cairo_matrix_t *current)
378 Rect updated;
380 cairo_matrix_t tween = *old;
381 cairo_matrix_invert (&tween);
382 cairo_matrix_multiply (&tween, &tween, current);
384 Point p0 (0,0);
385 Point p1 (1,0);
386 Point p2 (1,1);
387 Point p3 (0,1);
389 p0 = p0 - p0.Transform (&tween);
390 p1 = p1 - p1.Transform (&tween);
391 p2 = p2 - p2.Transform (&tween);
392 p3 = p3 - p3.Transform (&tween);
394 if (p0 == p1 && p1 == p2 && p2 == p3) {
395 //printf ("shifting position\n");
396 ShiftPosition (bounds.GetTopLeft ().Transform (&tween));
397 return;
400 UpdateBounds ();
403 void
404 UIElement::ComputeTransform ()
406 cairo_matrix_t old = absolute_xform;
407 cairo_matrix_init_identity (&absolute_xform);
409 if (GetVisualParent () != NULL) {
410 absolute_xform = GetVisualParent ()->absolute_xform;
411 } else if (GetParent () != NULL && GetParent ()->Is (Type::POPUP)) {
412 // FIXME we shouldn't be examing a subclass type here but we'll do this
413 // for now to get popups in something approaching the right place while
414 // we figure out a cleaner way to handle it long term.
415 Popup *popup = (Popup *)GetParent ();
416 absolute_xform = popup->absolute_xform;
417 cairo_matrix_translate (&absolute_xform, popup->GetHorizontalOffset (), popup->GetVerticalOffset ());
420 cairo_matrix_multiply (&absolute_xform, &layout_xform, &absolute_xform);
421 cairo_matrix_multiply (&absolute_xform, &local_xform, &absolute_xform);
423 if (moonlight_flags & RUNTIME_INIT_USE_UPDATE_POSITION)
424 TransformBounds (&old, &absolute_xform);
425 else {
426 UpdateBounds ();
430 void
431 UIElement::ComputeBounds ()
433 g_warning ("UIElement:ComputeBounds has been called. The derived class %s should have overridden it.",
434 GetTypeName ());
437 void
438 UIElement::ShiftPosition (Point p)
440 bounds.x = p.x;
441 bounds.y = p.y;
444 void
445 UIElement::OnSubPropertyChanged (DependencyProperty *prop, DependencyObject *obj, PropertyChangedEventArgs *subobj_args)
447 if (prop && prop->GetId () == UIElement::RenderTransformProperty) {
448 UpdateTransform ();
450 else if (prop && prop->GetId () == UIElement::ClipProperty) {
451 InvalidateClip ();
453 else if (prop && prop->GetId () == UIElement::OpacityMaskProperty) {
454 InvalidateMask ();
457 DependencyObject::OnSubPropertyChanged (prop, obj, subobj_args);
460 void
461 UIElement::CacheInvalidateHint ()
463 VisualTreeWalker walker (this);
464 while (UIElement *child = walker.Step ())
465 child->CacheInvalidateHint ();
468 void
469 UIElement::SetVisualParent (UIElement *visual_parent)
471 this->visual_parent = visual_parent;
473 if (visual_parent && visual_parent->GetSurface () != GetSurface())
474 SetSurface (visual_parent->GetSurface());
477 void
478 UIElement::SetSubtreeObject (DependencyObject *value)
480 if (subtree_object == value)
481 return;
483 if (subtree_object)
484 subtree_object->unref ();
486 subtree_object = value;
488 if (subtree_object)
489 subtree_object->ref ();
492 void
493 UIElement::ElementRemoved (UIElement *item)
495 // Invalidate ourself in the size of the item's subtree
496 Invalidate (item->GetSubtreeBounds());
498 if (GetSurface ())
499 GetSurface()->RemoveDirtyElement (item);
500 item->SetVisualParent (NULL);
501 item->CacheInvalidateHint ();
502 item->ClearLoaded ();
504 InvalidateMeasure ();
507 void
508 UIElement::ElementAdded (UIElement *item)
510 item->SetVisualLevel (GetVisualLevel() + 1);
511 item->SetVisualParent (this);
512 item->UpdateTotalRenderVisibility ();
513 item->UpdateTotalHitTestVisibility ();
514 //item->UpdateBounds (true);
515 item->Invalidate ();
517 if (0 != (flags & (UIElement::IS_LOADED | UIElement::PENDING_LOADED))) {
518 InheritedPropertyValueProvider::PropagateInheritedPropertiesOnAddingToTree (item);
520 bool post = false;
522 item->WalkTreeForLoadedHandlers (&post, true, false);
524 if (post)
525 Deployment::GetCurrent()->PostLoaded ();
528 UpdateBounds (true);
530 InvalidateMeasure ();
531 item->SetRenderSize (Size (0,0));
532 item->UpdateTransform ();
533 item->InvalidateMeasure ();
534 item->InvalidateArrange ();
537 void
538 UIElement::InvalidateMeasure ()
540 dirty_flags |= DirtyMeasure;
542 Surface *surface;
543 if ((surface = GetSurface ()))
544 surface->needs_measure = true;
548 void
549 UIElement::InvalidateArrange ()
551 dirty_flags |= DirtyArrange;
553 Surface *surface;
554 if ((surface = GetSurface ()))
555 surface->needs_arrange = true;
558 void
559 UIElement::DoMeasure ()
561 Size *last = LayoutInformation::GetPreviousConstraint (this);
562 UIElement *parent = GetVisualParent ();
563 Size infinite (INFINITY, INFINITY);
565 if (!GetSurface () && !last && !parent && IsLayoutContainer ()) {
566 last = &infinite;
569 if (last) {
570 Size previous_desired = GetDesiredSize ();
572 // This will be a noop on non layout elements
573 Measure (*last);
575 if (previous_desired == GetDesiredSize ())
576 return;
579 // a canvas doesn't care about the child size changing like this
580 if (parent && (!parent->Is (Type::CANVAS) || IsLayoutContainer ()))
581 parent->InvalidateMeasure ();
583 dirty_flags &= ~DirtyMeasure;
586 void
587 UIElement::DoArrange ()
589 Rect *last = LayoutInformation::GetLayoutSlot (this);
590 Size previous_render = Size ();
591 UIElement *parent = GetVisualParent ();
592 Rect viewport;
594 if (!parent) {
595 Size desired = Size ();
596 Size available = Size ();
597 Surface *surface = GetSurface ();
599 if (IsLayoutContainer ()) {
600 desired = GetDesiredSize ();
601 if (surface && this == surface->GetToplevel ()) {
602 Size *measure = LayoutInformation::GetPreviousConstraint (this);
603 if (measure)
604 desired = desired.Max (*LayoutInformation::GetPreviousConstraint (this));
605 else
606 desired = Size (surface->GetWindow ()->GetWidth (), surface->GetWindow ()->GetHeight ());
608 } else {
609 FrameworkElement *fe = (FrameworkElement*)this;
610 desired = Size (fe->GetActualWidth (), fe->GetActualHeight ());
613 viewport = Rect (Canvas::GetLeft (this),
614 Canvas::GetTop (this),
615 desired.width, desired.height);
617 last = &viewport;
620 if (last) {
621 previous_render = GetRenderSize ();
622 Arrange (*last);
624 if (previous_render == GetRenderSize ())
625 return;
628 if (parent && (!parent->Is (Type::CANVAS) || (IsLayoutContainer () || !last)))
629 parent->InvalidateArrange ();
631 if (!last)
632 return;
634 LayoutInformation::SetLastRenderSize (this, &previous_render);
637 bool
638 UIElement::InsideClip (cairo_t *cr, double x, double y)
640 Geometry* clip;
641 bool ret = false;
642 double nx = x;
643 double ny = y;
645 clip = GetClip ();
647 if (clip == NULL) {
648 return true;
651 TransformPoint (&nx, &ny);
652 if (!clip->GetBounds ().PointInside (nx, ny))
653 return false;
655 cairo_save (cr);
656 clip->Draw (cr);
658 if (cairo_in_fill (cr, nx, ny))
659 ret = true;
661 cairo_new_path (cr);
662 cairo_restore (cr);
664 return ret;
667 bool
668 UIElement::InsideObject (cairo_t *cr, double x, double y)
670 return InsideClip (cr, x, y);
674 UIElement::RemoveHandler (int event_id, EventHandler handler, gpointer data)
676 int token = DependencyObject::RemoveHandler (event_id, handler, data);
678 if (event_id == UIElement::LoadedEvent && token != -1)
679 Deployment::GetCurrent()->RemoveLoadedHandler (this, token);
681 return token;
684 void
685 UIElement::RemoveHandler (int event_id, int token)
687 DependencyObject::RemoveHandler (event_id, token);
689 if (event_id == UIElement::LoadedEvent)
690 Deployment::GetCurrent()->RemoveLoadedHandler (this, token);
693 void
694 UIElement::WalkTreeForLoadedHandlers (bool *post, bool only_unemitted, bool force_walk_up)
696 List *walk_list = new List();
697 bool post_loaded = false;
699 DeepTreeWalker *walker = new DeepTreeWalker (this);
701 // we need to make sure to apply the default style to all
702 // controls in the subtree
703 while (UIElement *element = (UIElement*)walker->Step ()) {
704 if (element->Is(Type::CONTROL)) {
705 Control *control = (Control*)element;
706 if (!control->default_style_applied) {
707 ManagedTypeInfo *key = control->GetDefaultStyleKey ();
708 if (key) {
709 if (Application::GetCurrent () == NULL)
710 g_warning ("attempting to use a null application when applying default style when emitting Loaded event.");
711 else
712 Application::GetCurrent()->ApplyDefaultStyle (control, key);
716 if (!control->GetTemplateRoot () /* we only need to worry about this if the template hasn't been expanded */
717 && control->GetTemplate())
718 post_loaded = true; //control->ReadLocalValue (Control::TemplateProperty) == NULL;
721 element->flags |= UIElement::PENDING_LOADED;
722 element->OnLoaded ();
723 if (element->HasHandlers (UIElement::LoadedEvent))
724 post_loaded = true;
727 if (force_walk_up || !post_loaded || HasHandlers (UIElement::LoadedEvent)) {
728 // we need to walk back up to the root to collect all loaded events
729 UIElement *parent = this;
730 while (parent->GetVisualParent())
731 parent = parent->GetVisualParent();
732 delete walker;
733 walker = new DeepTreeWalker (parent, Logical/*Reverse*/);
735 else {
736 // otherwise we only copy the events from the subtree
737 delete walker;
738 walker = new DeepTreeWalker (this, Logical/*Reverse*/);
741 while (UIElement *element = (UIElement*)walker->Step ()) {
742 walk_list->Prepend (new UIElementNode (element));
745 while (UIElementNode *ui = (UIElementNode*)walk_list->First ()) {
746 // remove it from the walk list
747 walk_list->Unlink (ui);
749 Deployment::GetCurrent()->AddAllLoadedHandlers (ui->uielement, only_unemitted);
752 if (post)
753 *post = post_loaded;
755 delete walker;
756 delete walk_list;
760 void
761 UIElement::OnLoaded ()
763 flags |= UIElement::IS_LOADED;
764 flags &= ~UIElement::PENDING_LOADED;
767 void
768 UIElement::ClearLoaded ()
770 UIElement *e = NULL;
771 Surface *s = Deployment::GetCurrent ()->GetSurface ();
772 if (s->GetFocusedElement () == this)
773 s->FocusElement (NULL);
775 ClearForeachGeneration (UIElement::LoadedEvent);
777 if (!IsLoaded ())
778 return;
780 flags &= ~UIElement::IS_LOADED;
782 VisualTreeWalker walker (this);
783 while ((e = walker.Step ()))
784 e->ClearLoaded ();
787 bool
788 UIElement::Focus (bool recurse)
790 return false;
794 // Queues the invalidate for the current region, performs any
795 // updates to the RenderTransform (optional) and queues a
796 // new redraw with the new bounding box
798 void
799 UIElement::FullInvalidate (bool rendertransform)
801 Invalidate ();
802 if (rendertransform)
803 UpdateTransform ();
804 UpdateBounds (true /* force an invalidate here, even if the bounds don't change */);
807 void
808 UIElement::Invalidate (Rect r)
810 if (!GetRenderVisible() || IS_INVISIBLE(total_opacity))
811 return;
813 #ifdef DEBUG_INVALIDATE
814 printf ("Requesting invalidate for object %p %s (%s) at %f %f - %f %f\n",
815 this, GetName(), GetTypeName(),
816 r.x, r.y,
817 r.w, r.h);
818 #endif
821 if (GetSurface ()) {
822 GetSurface()->AddDirtyElement (this, DirtyInvalidate);
824 dirty_region->Union (r);
826 GetSurface()->GetTimeManager()->NeedRedraw ();
828 Emit (InvalidatedEvent);
832 void
833 UIElement::Invalidate (Region *region)
835 if (!GetRenderVisible () || IS_INVISIBLE (total_opacity))
836 return;
838 if (GetSurface ()) {
839 GetSurface()->AddDirtyElement (this, DirtyInvalidate);
841 dirty_region->Union (region);
843 GetSurface()->GetTimeManager()->NeedRedraw ();
845 Emit (InvalidatedEvent);
849 void
850 UIElement::Invalidate ()
852 Invalidate (bounds);
856 void
857 UIElement::InvalidatePaint ()
859 Invalidate ();
863 void
864 UIElement::InvalidateSubtreePaint ()
866 Invalidate (GetSubtreeBounds ());
869 void
870 UIElement::InvalidateClip ()
872 InvalidateSubtreePaint ();
873 UpdateBounds (true);
876 void
877 UIElement::InvalidateMask ()
879 InvalidateSubtreePaint ();
882 void
883 UIElement::InvalidateVisibility ()
885 UpdateTotalRenderVisibility ();
886 InvalidateSubtreePaint ();
890 void
891 UIElement::InvalidateIntrisicSize ()
893 InvalidateMeasure ();
894 InvalidateArrange ();
895 UpdateBounds (true);
899 void
900 UIElement::HitTest (cairo_t *cr, Point p, List *uielement_list)
902 uielement_list->Prepend (new UIElementNode (this));
905 void
906 UIElement::HitTest (cairo_t *cr, Rect r, List *uielement_list)
910 void
911 UIElement::FindElementsInHostCoordinates_p (Point p, HitTestCollection *uielement_list)
913 List *list = new List ();
914 cairo_t *ctx = measuring_context_create ();
916 FindElementsInHostCoordinates (ctx, p, list);
918 UIElementNode *node = (UIElementNode *) list->First ();
919 while (node) {
920 uielement_list->Add (new Value (node->uielement));
921 node = (UIElementNode *) node->next;
924 delete list;
925 measuring_context_destroy (ctx);
929 void
930 UIElement::FindElementsInHostCoordinates (cairo_t *cr, Point P, List *uielement_list)
932 uielement_list->Prepend (new UIElementNode (this));
936 void
937 UIElement::FindElementsInHostCoordinates_r (Rect r, HitTestCollection *uielement_list)
939 List *list = new List ();
940 cairo_t *ctx = measuring_context_create ();
942 FindElementsInHostCoordinates (ctx, r, list);
944 UIElementNode *node = (UIElementNode *) list->First ();
945 while (node) {
946 uielement_list->Add (new Value (node->uielement));
947 node = (UIElementNode *) node->next;
950 delete list;
951 measuring_context_destroy (ctx);
954 void
955 UIElement::FindElementsInHostCoordinates (cairo_t *cr, Rect r, List *uielement_list)
957 uielement_list->Prepend (new UIElementNode (this));
960 bool
961 UIElement::EmitKeyDown (GdkEventKey *event)
963 return Emit (KeyDownEvent, new KeyEventArgs (event));
966 bool
967 UIElement::EmitKeyUp (GdkEventKey *event)
969 return Emit (KeyUpEvent, new KeyEventArgs (event));
972 bool
973 UIElement::EmitGotFocus ()
975 return Emit (GotFocusEvent, new RoutedEventArgs (this));
978 bool
979 UIElement::EmitLostFocus ()
981 return Emit (LostFocusEvent, new RoutedEventArgs (this));
984 bool
985 UIElement::EmitLostMouseCapture ()
987 MouseEventArgs *e = new MouseEventArgs ();
988 e->SetSource (this);
989 return Emit (LostMouseCaptureEvent, e);
992 bool
993 UIElement::CaptureMouse ()
995 Surface *s = GetSurface ();
996 if (s == NULL)
997 return false;
999 return s->SetMouseCapture (this);
1002 void
1003 UIElement::ReleaseMouseCapture ()
1005 Surface *s = GetSurface ();
1006 if (s == NULL)
1007 return;
1009 s->ReleaseMouseCapture (this);
1012 void
1013 UIElement::DoRender (cairo_t *cr, Region *parent_region)
1015 Region *region = new Region (GetSubtreeBounds ());
1016 region->Intersect (parent_region);
1018 if (!GetRenderVisible() || IS_INVISIBLE (total_opacity) || region->IsEmpty ()) {
1019 delete region;
1020 return;
1023 #if FRONT_TO_BACK_STATS
1024 GetSurface()->uielements_rendered_back_to_front ++;
1025 #endif
1027 STARTTIMER (UIElement_render, Type::Find (GetObjectType())->name);
1029 PreRender (cr, region, false);
1031 Render (cr, region);
1033 PostRender (cr, region, false);
1035 ENDTIMER (UIElement_render, Type::Find (GetObjectType())->name);
1037 delete region;
1040 bool
1041 UIElement::UseBackToFront ()
1043 return VisualTreeWalker (this).GetCount () < MIN_FRONT_TO_BACK_COUNT;
1046 void
1047 UIElement::FrontToBack (Region *surface_region, List *render_list)
1049 double local_opacity = GetOpacity ();
1051 if (surface_region->RectIn (GetSubtreeBounds().RoundOut()) == GDK_OVERLAP_RECTANGLE_OUT)
1052 return;
1054 if (!GetRenderVisible ()
1055 || IS_INVISIBLE (local_opacity))
1056 return;
1058 if (!UseBackToFront ()) {
1059 Region *self_region = new Region (surface_region);
1060 self_region->Intersect (GetSubtreeBounds().RoundOut());
1062 // we need to include our children in this one, since
1063 // we'll be rendering them in the PostRender method.
1064 if (!self_region->IsEmpty())
1065 render_list->Prepend (new RenderNode (this, self_region, true,
1066 UIElement::CallPreRender, UIElement::CallPostRender));
1067 // don't remove the region from surface_region because
1068 // there are likely holes in it
1069 return;
1072 Region *region;
1073 bool delete_region;
1074 bool can_subtract_self;
1076 if (!GetClip ()
1077 && !GetOpacityMask ()
1078 && !IS_TRANSLUCENT (GetOpacity ())) {
1079 region = surface_region;
1080 delete_region = false;
1081 can_subtract_self = true;
1083 else {
1084 region = new Region (surface_region);
1085 delete_region = true;
1086 can_subtract_self = false;
1089 RenderNode *cleanup_node = new RenderNode (this, NULL, false, NULL, UIElement::CallPostRender);
1091 render_list->Prepend (cleanup_node);
1093 Region *self_region = new Region (region);
1095 VisualTreeWalker walker (this, ZReverse);
1096 while (UIElement *child = walker.Step ())
1097 child->FrontToBack (region, render_list);
1099 if (!GetOpacityMask () && !IS_TRANSLUCENT (local_opacity)) {
1100 delete self_region;
1101 if (GetRenderBounds().IsEmpty ()) { // empty bounds mean that this element draws nothing itself
1102 self_region = new Region ();
1104 else {
1105 self_region = new Region (region);
1106 self_region->Intersect (GetRenderBounds().RoundOut ()); // note the RoundOut
1108 } else {
1109 self_region->Intersect (GetSubtreeBounds().RoundOut ()); // note the RoundOut
1112 if (self_region->IsEmpty() && render_list->First() == cleanup_node) {
1113 /* we don't intersect the surface region, and none of
1114 our children did either, remove the cleanup node */
1115 render_list->Remove (render_list->First());
1116 delete self_region;
1117 if (delete_region)
1118 delete region;
1119 return;
1122 render_list->Prepend (new RenderNode (this, self_region, !self_region->IsEmpty(), UIElement::CallPreRender, NULL));
1124 if (!self_region->IsEmpty()) {
1125 if (((absolute_xform.yx == 0 && absolute_xform.xy == 0) /* no skew/rotation */
1126 || (absolute_xform.xx == 0 && absolute_xform.yy == 0)) /* allow 90 degree rotations */
1127 && can_subtract_self)
1128 region->Subtract (GetCoverageBounds ());
1131 if (delete_region)
1132 delete region;
1135 void
1136 UIElement::PreRender (cairo_t *cr, Region *region, bool skip_children)
1138 double local_opacity = GetOpacity ();
1140 cairo_save (cr);
1142 cairo_set_matrix (cr, &absolute_xform);
1143 RenderClipPath (cr);
1145 if (opacityMask || IS_TRANSLUCENT (local_opacity)) {
1146 Rect r = GetSubtreeBounds ().RoundOut();
1147 cairo_identity_matrix (cr);
1149 // we need this check because ::PreRender can (and
1150 // will) be called for elements with empty regions.
1152 // The region passed in here is the redraw region
1153 // intersected with the render bounds of a given
1154 // element. For Panels with no width/height specified
1155 // in the xaml, this region will be empty. (check
1156 // panel.cpp::FrontToBack - we insert the ::PreRender
1157 // calling node if either the panel background or any
1158 // of the children intersect the redraw region.) We
1159 // can't clip to the empty region, obviously, as it
1160 // will keep all descendents from drawing to the
1161 // screen.
1163 if (!region->IsEmpty()) {
1164 region->Draw (cr);
1165 cairo_clip (cr);
1167 r.Draw (cr);
1168 cairo_clip (cr);
1170 cairo_set_matrix (cr, &absolute_xform);
1173 if (ClipToExtents ()) {
1174 extents.Draw (cr);
1175 cairo_clip (cr);
1179 if (IS_TRANSLUCENT (local_opacity))
1180 cairo_push_group (cr);
1182 if (opacityMask != NULL)
1183 cairo_push_group (cr);
1186 void
1187 UIElement::PostRender (cairo_t *cr, Region *region, bool front_to_back)
1189 // if we didn't render front to back, then render the children here
1190 if (!front_to_back) {
1191 VisualTreeWalker walker (this, ZForward);
1192 while (UIElement *child = walker.Step ())
1193 child->DoRender (cr, region);
1196 double local_opacity = GetOpacity ();
1198 if (opacityMask != NULL) {
1199 cairo_pattern_t *mask;
1200 cairo_pattern_t *data = cairo_pop_group (cr);
1201 Point p = GetOriginPoint ();
1202 Rect area = Rect (p.x, p.y, 0.0, 0.0);
1203 GetSizeForBrush (cr, &(area.width), &(area.height));
1204 opacityMask->SetupBrush (cr, area);
1205 mask = cairo_get_source (cr);
1206 cairo_pattern_reference (mask);
1207 cairo_set_source (cr, data);
1208 cairo_mask (cr, mask);
1209 cairo_pattern_destroy (mask);
1210 cairo_pattern_destroy (data);
1213 if (IS_TRANSLUCENT (local_opacity)) {
1214 cairo_pop_group_to_source (cr);
1215 cairo_paint_with_alpha (cr, local_opacity);
1218 cairo_restore (cr);
1220 if (moonlight_flags & RUNTIME_INIT_SHOW_CLIPPING) {
1221 cairo_save (cr);
1222 cairo_new_path (cr);
1223 cairo_set_matrix (cr, &absolute_xform);
1224 cairo_set_line_width (cr, 1);
1226 Geometry *geometry = GetClip ();
1227 if (geometry) {
1228 geometry->Draw (cr);
1229 cairo_set_source_rgba (cr, 0.0, 1.0, 1.0, 1.0);
1230 cairo_stroke (cr);
1233 cairo_restore (cr);
1236 if (moonlight_flags & RUNTIME_INIT_SHOW_BOUNDING_BOXES) {
1237 cairo_save (cr);
1238 cairo_new_path (cr);
1239 //RenderClipPath (cr);
1240 cairo_identity_matrix (cr);
1241 cairo_set_source_rgba (cr, 1.0, 0.5, 0.2, 1.0);
1242 cairo_set_line_width (cr, 1);
1243 cairo_rectangle (cr, bounds.x + .5, bounds.y + .5, bounds.width - .5, bounds.height - .5);
1244 cairo_stroke (cr);
1245 cairo_restore (cr);
1249 void
1250 UIElement::Paint (cairo_t *ctx, Region *region, cairo_matrix_t *xform)
1252 // FIXME xform is ignored for now
1253 if (xform)
1254 g_warning ("passing a transform to UIElement::Paint is not yet supported");
1256 #if FRONT_TO_BACK_STATS
1257 uielements_rendered_front_to_back = 0;
1258 uielements_rendered_back_to_front = 0;
1259 #endif
1261 bool did_front_to_back = false;
1262 List *render_list = new List ();
1264 if (moonlight_flags & RUNTIME_INIT_RENDER_FRONT_TO_BACK) {
1265 Region *copy = new Region (region);
1266 FrontToBack (copy, render_list);
1268 if (!render_list->IsEmpty ()) {
1269 while (RenderNode *node = (RenderNode*)render_list->First()) {
1270 #if FRONT_TO_BACK_STATS
1271 uielements_rendered_front_to_back ++;
1272 #endif
1273 node->Render (ctx);
1275 render_list->Remove (node);
1278 did_front_to_back = true;
1281 delete render_list;
1282 delete copy;
1285 if (!did_front_to_back) {
1286 DoRender (ctx, region);
1289 #if FRONT_TO_BACK_STATS
1290 printf ("UIElements rendered front-to-back for: %s(%p)\n", uielements_rendered_front_to_back, GetName (), this);
1291 printf ("UIElements rendered back-to-front for: %s(%p)\n", uielements_rendered_back_to_front, GetName (), this);
1292 #endif
1295 void
1296 UIElement::CallPreRender (cairo_t *cr, UIElement *element, Region *region, bool front_to_back)
1298 element->PreRender (cr, region, front_to_back);
1301 void
1302 UIElement::CallPostRender (cairo_t *cr, UIElement *element, Region *region, bool front_to_back)
1304 element->PostRender (cr, region, front_to_back);
1307 void
1308 UIElement::Render (cairo_t *cr, Region *region, bool path_only)
1310 /* do nothing by default */
1313 void
1314 UIElement::GetSizeForBrush (cairo_t *cr, double *width, double *height)
1316 g_warning ("UIElement:GetSizeForBrush has been called. The derived class %s should have overridden it.",
1317 GetTypeName ());
1318 *height = *width = 0.0;
1321 TimeManager *
1322 UIElement::GetTimeManager ()
1324 Surface *surface = GetSurface ();
1325 Deployment *deployment;
1327 if (surface == NULL) {
1328 deployment = GetDeployment ();
1329 if (deployment != NULL)
1330 surface = deployment->GetSurface ();
1333 return surface ? surface->GetTimeManager() : NULL;
1336 GeneralTransform *
1337 UIElement::GetTransformToUIElementWithError (UIElement *to_element, MoonError *error)
1339 /* walk from this up to the root. if we hit null before we hit the toplevel, it's an error */
1340 UIElement *visual = this;
1341 bool ok = false;
1343 if (visual && GetSurface()) {
1344 while (visual) {
1345 if (GetSurface()->IsTopLevel (visual))
1346 ok = true;
1347 visual = visual->GetVisualParent ();
1351 if (!ok || (to_element && !to_element->GetSurface ())) {
1352 MoonError::FillIn (error, MoonError::ARGUMENT, 1001,
1353 "visual");
1354 return NULL;
1357 if (to_element && !to_element->GetSurface()->IsTopLevel (to_element)) {
1358 /* if @to_element is specified we also need to make sure there's a path to the root from it */
1359 ok = false;
1360 visual = to_element->GetVisualParent ();
1361 if (visual && to_element->GetSurface()) {
1362 while (visual) {
1363 if (to_element->GetSurface()->IsTopLevel (visual))
1364 ok = true;
1365 visual = visual->GetVisualParent ();
1369 if (!ok) {
1370 MoonError::FillIn (error, MoonError::ARGUMENT, 1001,
1371 "visual");
1372 return NULL;
1376 cairo_matrix_t result;
1377 // A = From, B = To, M = what we want
1378 // A = M * B
1379 // => M = A * inv (B)
1380 if (to_element) {
1381 cairo_matrix_t inverse = to_element->absolute_xform;
1382 cairo_matrix_invert (&inverse);
1383 cairo_matrix_multiply (&result, &absolute_xform, &inverse);
1385 else {
1386 result = absolute_xform;
1389 Matrix *matrix = new Matrix (&result);
1391 MatrixTransform *transform = new MatrixTransform ();
1392 transform->SetValue (MatrixTransform::MatrixProperty, matrix);
1393 matrix->unref ();
1395 return transform;
1398 void
1399 UIElement::TransformPoint (double *x, double *y)
1401 cairo_matrix_t inverse = absolute_xform;
1402 cairo_matrix_invert (&inverse);
1404 cairo_matrix_transform_point (&inverse, x, y);