2009-11-12 Jeffrey Stedfast <fejj@novell.com>
[moon.git] / src / brush.cpp
blob830d4f95b49624dfac15768ab43746ee54cbdb43
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3 * brush.cpp: Brushes
5 * Contact:
6 * Moonlight List (moonlight-list@lists.ximian.com)
8 * Copyright 2007, 2008 Novell, Inc. (http://www.novell.com)
10 * See the LICENSE file included with the distribution for details.
14 #include <config.h>
16 #include <cairo.h>
17 #include <glib.h>
19 #include "brush.h"
20 #include "media.h"
21 #include "mediaelement.h"
22 #include "color.h"
23 #include "transform.h"
24 #include "mediaplayer.h"
25 #include "bitmapimage.h"
26 #include "uri.h"
29 // SL-Cairo convertion and helper routines
32 static cairo_extend_t
33 convert_gradient_spread_method (GradientSpreadMethod method)
35 switch (method) {
36 case GradientSpreadMethodPad:
37 return CAIRO_EXTEND_PAD;
38 case GradientSpreadMethodReflect:
39 return CAIRO_EXTEND_REFLECT;
40 // unknown (e.g. bad) values are considered to be Repeat by Silverlight
41 // even if the default, i.e. *no* value) is Pad
42 case GradientSpreadMethodRepeat:
43 default:
44 return CAIRO_EXTEND_REPEAT;
48 static void
49 brush_matrix_invert (cairo_matrix_t *matrix)
51 cairo_status_t status = cairo_matrix_invert (matrix);
52 if (status != CAIRO_STATUS_SUCCESS) {
53 printf ("Moonlight: Error inverting matrix falling back\n");
54 cairo_matrix_init_identity (matrix);
59 // Brush
63 Brush::Brush()
65 SetObjectType (Type::BRUSH);
68 void
69 Brush::SetupBrush (cairo_t *cr, const Rect &area)
71 g_warning ("Brush:SetupBrush has been called. The derived class should have overridden it.");
74 void
75 Brush::Fill (cairo_t *cr, bool preserve)
77 if (preserve)
78 cairo_fill_preserve (cr);
79 else
80 cairo_fill (cr);
83 void
84 Brush::Stroke (cairo_t *cr, bool preserve)
86 if (preserve)
87 cairo_stroke_preserve (cr);
88 else
89 cairo_stroke (cr);
92 void
93 Brush::OnSubPropertyChanged (DependencyProperty *prop, DependencyObject *obj, PropertyChangedEventArgs *subobj_args)
95 // if our transforms change in some fashion, we need to redraw
96 // the element.
97 NotifyListenersOfPropertyChange (Brush::ChangedProperty, NULL);
99 DependencyObject::OnSubPropertyChanged (prop, obj, subobj_args);
102 bool
103 Brush::IsOpaque ()
105 return !IS_TRANSLUCENT (GetOpacity ());
108 bool
109 Brush::IsAnimating ()
111 return FALSE;
114 static void
115 transform_get_absolute_transform (Transform *relative_transform, double width, double height, cairo_matrix_t *result)
117 cairo_matrix_t tm;
119 cairo_matrix_init_scale (result, width, height);
120 relative_transform->GetTransform (&tm);
121 cairo_matrix_multiply (result, &tm, result);
122 cairo_matrix_scale (result, 1.0/width, 1.0/height);
128 // SolidColorBrush
131 SolidColorBrush::SolidColorBrush ()
133 SetObjectType (Type::SOLIDCOLORBRUSH);
136 SolidColorBrush::SolidColorBrush (const char *color)
138 SetObjectType (Type::SOLIDCOLORBRUSH);
139 Color *c = color_from_str (color);
140 SetColor (c);
141 delete c;
144 void
145 SolidColorBrush::SetupBrush (cairo_t *cr, const Rect &area)
147 double opacity = GetOpacity ();
148 Color *color = GetColor ();
150 cairo_set_source_rgba (cr, color->r, color->g, color->b, opacity * color->a);
153 bool
154 SolidColorBrush::IsOpaque ()
156 return Brush::IsOpaque () && !IS_TRANSLUCENT (GetColor ()->a);
161 // GradientBrush
164 GradientBrush::GradientBrush ()
166 SetObjectType (Type::GRADIENTBRUSH);
169 GradientBrush::~GradientBrush ()
173 void
174 GradientBrush::OnCollectionChanged (Collection *col, CollectionChangedEventArgs *args)
176 if (col != GetValue (GradientBrush::GradientStopsProperty)->AsCollection ()) {
177 Brush::OnCollectionChanged (col, args);
178 return;
181 NotifyListenersOfPropertyChange (GradientBrush::GradientStopsProperty, NULL);
184 void
185 GradientBrush::OnCollectionItemChanged (Collection *col, DependencyObject *obj, PropertyChangedEventArgs *args)
187 if (col != GetValue (GradientBrush::GradientStopsProperty)->AsCollection ()) {
188 Brush::OnCollectionItemChanged (col, obj, args);
189 return;
192 NotifyListenersOfPropertyChange (GradientBrush::GradientStopsProperty, NULL);
195 void
196 GradientBrush::SetupGradient (cairo_pattern_t *pattern, const Rect &area, bool single)
198 GradientStopCollection *children = GetGradientStops ();
199 GradientSpreadMethod gsm = GetSpreadMethod ();
200 double opacity = GetOpacity ();
201 GradientStop *stop;
202 double offset;
203 int index;
205 cairo_pattern_set_extend (pattern, convert_gradient_spread_method (gsm));
207 // TODO - ColorInterpolationModeProperty is ignored (map to ?)
208 if (single) {
209 // if a single color is shown (e.g. start == end point) Cairo will,
210 // by default, use the start color while SL use the end color
211 index = children->GetCount () - 1;
212 } else {
213 index = 0;
216 GradientStop *negative_stop = NULL; //the biggest negative stop
217 double neg_offset = 0.0; //the cached associated offset
218 GradientStop *first_stop = NULL; //the smallest positive stop
219 double first_offset = 0.0; //idem
220 GradientStop *last_stop = NULL; //the biggest stop <= 1
221 double last_offset = 0.0; //idem
222 GradientStop *outofbounds_stop = NULL; //the smallest stop > 1
223 double out_offset = 0.0; //idem
225 for ( ; index < children->GetCount (); index++) {
226 stop = children->GetValueAt (index)->AsGradientStop ();
227 offset = stop->GetOffset ();
229 if (offset >= 0.0 && offset <= 1.0) {
230 Color *color = stop->GetColor ();
232 cairo_pattern_add_color_stop_rgba (pattern, offset, color->r, color->g, color->b, color->a * opacity);
234 if (!first_stop || (first_offset != 0.0 && offset < first_offset)) {
235 first_offset = offset;
236 first_stop = stop;
239 if (!last_stop || (last_offset != 1.0 && offset > last_offset)) {
240 last_offset = offset;
241 last_stop = stop;
243 } else if (offset < 0.0 && (!negative_stop || offset > neg_offset)) {
244 negative_stop = stop;
245 neg_offset = offset;
246 } else if (offset > 1.0 && (!outofbounds_stop || offset < out_offset)) {
247 outofbounds_stop = stop;
248 out_offset = offset;
252 if (negative_stop && first_stop && first_offset != 0.0) { //take care of the negative stop
253 Color *neg_color = negative_stop->GetColor ();
254 Color *first_color = first_stop->GetColor ();
255 double ratio = neg_offset / (neg_offset - first_offset);
257 cairo_pattern_add_color_stop_rgba (pattern, 0.0,
258 neg_color->r + ratio * (first_color->r - neg_color->r),
259 neg_color->g + ratio * (first_color->g - neg_color->g),
260 neg_color->b + ratio * (first_color->b - neg_color->b),
261 (neg_color->a + ratio * (first_color->a - neg_color->a)) * opacity);
264 if (outofbounds_stop && last_stop && last_offset != 1.0) { //take care of the >1 stop
265 Color *last_color = last_stop->GetColor ();
266 Color *out_color = outofbounds_stop->GetColor ();
267 double ratio = (1.0 - last_offset) / (out_offset - last_offset);
269 cairo_pattern_add_color_stop_rgba (pattern, 1.0,
270 last_color->r + ratio * (out_color->r - last_color->r),
271 last_color->g + ratio * (out_color->g - last_color->g),
272 last_color->b + ratio * (out_color->b - last_color->b),
273 (last_color->a + ratio * (out_color->a - last_color->a)) * opacity);
276 if (negative_stop && outofbounds_stop && !first_stop && !last_stop) { //only 2 stops, one < 0, the other > 1
277 Color *neg_color = negative_stop->GetColor ();
278 Color *out_color = outofbounds_stop->GetColor ();
279 double ratio = neg_offset / (neg_offset - out_offset);
281 cairo_pattern_add_color_stop_rgba (pattern, 0.0,
282 neg_color->r + ratio * (out_color->r - neg_color->r),
283 neg_color->g + ratio * (out_color->g - neg_color->g),
284 neg_color->b + ratio * (out_color->b - neg_color->b),
285 (neg_color->a + ratio * (out_color->a - neg_color->a)) * opacity);
287 ratio = (1.0 - neg_offset) / (out_offset - neg_offset);
289 cairo_pattern_add_color_stop_rgba (pattern, 1.0,
290 neg_color->r + ratio * (out_color->r - neg_color->r),
291 neg_color->g + ratio * (out_color->g - neg_color->g),
292 neg_color->b + ratio * (out_color->b - neg_color->b),
293 (neg_color->a + ratio * (out_color->a - neg_color->a)) * opacity);
296 if (negative_stop && !outofbounds_stop && !first_stop && !last_stop) { //only negative stops
297 Color *color = negative_stop->GetColor ();
299 cairo_pattern_add_color_stop_rgba (pattern, 0.0, color->r, color->g, color->b, color->a * opacity);
302 if (outofbounds_stop && !negative_stop && !first_stop && !last_stop) { //only > 1 stops
303 Color *color = outofbounds_stop->GetColor ();
305 cairo_pattern_add_color_stop_rgba (pattern, 1.0, color->r, color->g, color->b, color->a * opacity);
309 bool
310 GradientBrush::IsOpaque ()
312 if (!Brush::IsOpaque ())
313 return false;
315 GradientStopCollection *stops = GetGradientStops ();
316 GradientStop *stop;
317 Color *c;
319 for (int i = 0; i < stops->GetCount (); i++) {
320 stop = stops->GetValueAt (i)->AsGradientStop ();
321 c = stop->GetColor ();
322 if (IS_TRANSLUCENT (c->a))
323 return false;
326 return true;
330 // GradientStopCollection
333 GradientStopCollection::GradientStopCollection ()
335 SetObjectType (Type::GRADIENTSTOP_COLLECTION);
338 GradientStopCollection::~GradientStopCollection ()
344 // GradientStop
347 GradientStop::GradientStop()
349 SetObjectType (Type::GRADIENTSTOP);
352 GradientStop::~GradientStop()
357 // LinearGradientBrush
360 LinearGradientBrush::LinearGradientBrush ()
362 SetObjectType (Type::LINEARGRADIENTBRUSH);
365 LinearGradientBrush::~LinearGradientBrush ()
369 void
370 LinearGradientBrush::SetupBrush (cairo_t *cr, const Rect &area)
372 Point *start = GetStartPoint ();
373 Point *end = GetEndPoint ();
374 double x0, y0, x1, y1;
375 cairo_matrix_t offset_matrix;
376 Point p = area.GetTopLeft ();
378 switch (GetMappingMode ()) {
379 // unknown (e.g. bad) values are considered to be Absolute to Silverlight
380 // even if the default, i.e. *no* value) is RelativeToBoundingBox
381 case BrushMappingModeAbsolute:
382 default:
383 y0 = start ? start->y : 0.0;
384 x0 = start ? start->x : 0.0;
385 y1 = end ? end->y : area.height;
386 x1 = end ? end->x : area.width;
387 break;
388 case BrushMappingModeRelativeToBoundingBox:
389 y0 = start ? (start->y * area.height) : 0.0;
390 x0 = start ? (start->x * area.width) : 0.0;
391 y1 = end ? (end->y * area.height) : area.height;
392 x1 = end ? (end->x * area.width) : area.width;
393 break;
396 cairo_pattern_t *pattern = cairo_pattern_create_linear (x0, y0, x1, y1);
398 cairo_matrix_t matrix;
399 cairo_matrix_init_identity (&matrix);
401 Transform *transform = GetTransform ();
402 if (transform) {
403 cairo_matrix_t tm;
405 transform->GetTransform (&tm);
406 // TODO - optimization, check for empty/identity matrix too ?
407 cairo_matrix_multiply (&matrix, &matrix, &tm);
410 Transform *relative_transform = GetRelativeTransform ();
411 if (relative_transform) {
412 cairo_matrix_t tm;
413 transform_get_absolute_transform (relative_transform, area.width, area.height, &tm);
414 cairo_matrix_multiply (&matrix, &matrix, &tm);
417 if (p.x != 0.0 && p.y != 0.0) {
418 cairo_matrix_init_translate (&offset_matrix, p.x, p.y);
419 cairo_matrix_multiply (&matrix, &matrix, &offset_matrix);
422 brush_matrix_invert (&matrix);
423 cairo_pattern_set_matrix (pattern, &matrix);
425 bool only_start = (x0 == x1 && y0 == y1);
426 GradientBrush::SetupGradient (pattern, area, only_start);
428 cairo_set_source (cr, pattern);
429 cairo_pattern_destroy (pattern);
433 // RadialGradientBrush
436 RadialGradientBrush::RadialGradientBrush ()
438 SetObjectType (Type::RADIALGRADIENTBRUSH);
441 RadialGradientBrush::~RadialGradientBrush()
445 void
446 RadialGradientBrush::SetupBrush (cairo_t *cr, const Rect &area)
448 Point *origin = GetGradientOrigin ();
449 double ox = (origin ? origin->x : 0.5);
450 double oy = (origin ? origin->y : 0.5);
451 cairo_matrix_t offset_matrix;
453 Point *center = GetCenter ();
454 double cx = (center ? center->x : 0.5);
455 double cy = (center ? center->y : 0.5);
457 double rx = GetRadiusX ();
458 double ry = GetRadiusY ();
460 cairo_pattern_t *pattern = cairo_pattern_create_radial (ox/rx, oy/ry, 0.0, cx/rx, cy/ry, 1);
462 cairo_matrix_t matrix;
463 switch (GetMappingMode ()) {
464 // unknown (e.g. bad) values are considered to be Absolute to Silverlight
465 // even if the default, i.e. *no* value) is RelativeToBoundingBox
466 case BrushMappingModeAbsolute:
467 default:
468 cairo_matrix_init_translate (&matrix, cx, cy);
469 cairo_matrix_scale (&matrix, rx, ry);
470 cairo_matrix_translate (&matrix, -cx/rx, -cy/ry);
471 break;
472 case BrushMappingModeRelativeToBoundingBox:
473 cairo_matrix_init_translate (&matrix, cx * area.width, cy * area.height);
474 cairo_matrix_scale (&matrix, area.width * rx, area.height * ry );
475 cairo_matrix_translate (&matrix, -cx/rx, -cy/ry);
476 break;
479 Transform *transform = GetTransform ();
480 if (transform) {
481 cairo_matrix_t tm;
483 transform->GetTransform (&tm);
484 // TODO - optimization, check for empty/identity matrix too ?
485 cairo_matrix_multiply (&matrix, &matrix, &tm);
488 Transform *relative_transform = GetRelativeTransform ();
489 if (relative_transform) {
490 cairo_matrix_t tm;
491 transform_get_absolute_transform (relative_transform, area.width, area.height, &tm);
492 // TODO - optimization, check for empty/identity matrix too ?
493 cairo_matrix_multiply (&matrix, &matrix, &tm);
496 if (area.x != 0.0 || area.y != 0.0) {
497 cairo_matrix_init_translate (&offset_matrix, area.x, area.y);
498 cairo_matrix_multiply (&matrix, &matrix, &offset_matrix);
501 brush_matrix_invert (&matrix);
503 cairo_pattern_set_matrix (pattern, &matrix);
504 GradientBrush::SetupGradient (pattern, area);
506 cairo_set_source (cr, pattern);
507 cairo_pattern_destroy (pattern);
511 // ImageBrush
514 ImageBrush::ImageBrush ()
516 SetObjectType (Type::IMAGEBRUSH);
519 ImageBrush::~ImageBrush ()
523 void
524 ImageBrush::Dispose ()
526 BitmapImage *source = (BitmapImage *) GetImageSource ();
528 if (source) {
529 source->RemoveHandler (BitmapImage::DownloadProgressEvent, download_progress, this);
530 source->RemoveHandler (BitmapImage::ImageOpenedEvent, image_opened, this);
531 source->RemoveHandler (BitmapImage::ImageFailedEvent, image_failed, this);
532 source->RemoveHandler (BitmapSource::PixelDataChangedEvent, source_pixel_data_changed, this);
535 TileBrush::Dispose ();
538 void
539 ImageBrush::download_progress (EventObject *sender, EventArgs *calldata, gpointer closure)
541 ImageBrush *media = (ImageBrush *) closure;
543 media->DownloadProgress ();
546 void
547 ImageBrush::image_opened (EventObject *sender, EventArgs *calldata, gpointer closure)
549 ImageBrush *media = (ImageBrush *) closure;
551 media->ImageOpened ();
554 void
555 ImageBrush::image_failed (EventObject *sender, EventArgs *calldata, gpointer closure)
557 ImageBrush *media = (ImageBrush *) closure;
559 media->ImageFailed ((ImageErrorEventArgs*) calldata);
562 void
563 ImageBrush::source_pixel_data_changed (EventObject *sender, EventArgs *calldata, gpointer closure)
565 ImageBrush *media = (ImageBrush *) closure;
567 media->SourcePixelDataChanged ();
570 void
571 ImageBrush::DownloadProgress ()
573 BitmapImage *source = (BitmapImage *) GetImageSource ();
575 SetDownloadProgress (source->GetProgress ());
576 Emit (DownloadProgressChangedEvent);
579 void
580 ImageBrush::ImageOpened ()
582 BitmapImage *source = (BitmapImage*)GetImageSource ();
584 source->RemoveHandler (BitmapImage::DownloadProgressEvent, download_progress, this);
585 source->RemoveHandler (BitmapImage::ImageOpenedEvent, image_opened, this);
586 source->RemoveHandler (BitmapImage::ImageFailedEvent, image_failed, this);
589 void
590 ImageBrush::ImageFailed (ImageErrorEventArgs *args)
592 BitmapImage *source = (BitmapImage*)GetImageSource ();
594 source->RemoveHandler (BitmapImage::DownloadProgressEvent, download_progress, this);
595 source->RemoveHandler (BitmapImage::ImageOpenedEvent, image_opened, this);
596 source->RemoveHandler (BitmapImage::ImageFailedEvent, image_failed, this);
598 args->ref (); // to counter the unref in Emit
599 Emit (ImageFailedEvent, args);
602 void
603 ImageBrush::SourcePixelDataChanged ()
605 NotifyListenersOfPropertyChange (Brush::ChangedProperty, NULL);
608 void
609 ImageBrush::SetSource (Downloader *downloader, const char *PartName)
611 BitmapImage *source = (BitmapImage *) GetImageSource ();
613 if (source == NULL) {
614 source = new BitmapImage ();
615 SetImageSource (source);
618 source->AddHandler (BitmapImage::DownloadProgressEvent, download_progress, this);
619 source->AddHandler (BitmapImage::ImageOpenedEvent, image_opened, this);
620 source->AddHandler (BitmapImage::ImageFailedEvent, image_failed, this);
622 source->SetDownloader (downloader, NULL, PartName);
625 void
626 ImageBrush::OnPropertyChanged (PropertyChangedEventArgs *args, MoonError *error)
628 if (args->GetProperty ()->GetOwnerType() != Type::IMAGEBRUSH) {
629 TileBrush::OnPropertyChanged (args, error);
630 return;
631 } else if (args->GetId () == ImageSourceProperty) {
632 ImageSource *source = args->GetNewValue () ? args->GetNewValue ()->AsImageSource () : NULL;
633 ImageSource *old = args->GetOldValue () ? args->GetOldValue ()->AsImageSource () : NULL;
635 if (old && old->Is(Type::BITMAPSOURCE)) {
636 old->RemoveHandler (BitmapSource::PixelDataChangedEvent, source_pixel_data_changed, this);
638 if (source && source->Is(Type::BITMAPSOURCE)) {
639 source->AddHandler (BitmapSource::PixelDataChangedEvent, source_pixel_data_changed, this);
642 if (old && old->Is(Type::BITMAPIMAGE)) {
643 old->RemoveHandler (BitmapImage::DownloadProgressEvent, download_progress, this);
644 old->RemoveHandler (BitmapImage::ImageOpenedEvent, image_opened, this);
645 old->RemoveHandler (BitmapImage::ImageFailedEvent, image_failed, this);
647 if (source && source->Is(Type::BITMAPIMAGE)) {
648 BitmapImage *bitmap = (BitmapImage *) source;
649 Uri *uri = bitmap->GetUriSource ();
651 source->AddHandler (BitmapImage::DownloadProgressEvent, download_progress, this);
652 source->AddHandler (BitmapImage::ImageOpenedEvent, image_opened, this);
653 source->AddHandler (BitmapImage::ImageFailedEvent, image_failed, this);
655 // can uri ever be null?
656 if (uri != NULL) {
657 ImageErrorEventArgs *args = NULL;
659 if (uri->IsInvalidPath ()) {
660 args = new ImageErrorEventArgs (MoonError (MoonError::ARGUMENT_OUT_OF_RANGE, 0, "invalid path found in uri"));
661 } else if (!bitmap->ValidateDownloadPolicy ()) {
662 args = new ImageErrorEventArgs (MoonError (MoonError::ARGUMENT_OUT_OF_RANGE, 0, "Security Policy Violation"));
665 if (args != NULL) {
666 source->RemoveHandler (BitmapImage::ImageFailedEvent, image_failed, this);
667 EmitAsync (ImageFailedEvent, args);
671 SourcePixelDataChanged ();
674 NotifyListenersOfPropertyChange (args, error);
677 bool
678 ImageBrush::IsOpaque ()
680 // XXX punt for now and return false here.
681 return false;
684 cairo_surface_t *
685 image_brush_create_similar (cairo_t *cairo, int width, int height)
687 #if USE_OPT_IMAGE_ONLY
688 return cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
689 #else
690 return cairo_surface_create_similar (cairo_get_group_target (cairo),
691 CAIRO_CONTENT_COLOR_ALPHA,
692 width,
693 height);
694 #endif
697 void
698 image_brush_compute_pattern_matrix (cairo_matrix_t *matrix, double width, double height, int sw, int sh,
699 Stretch stretch, AlignmentX align_x, AlignmentY align_y, Transform *transform, Transform *relative_transform)
701 // scale required to "fit" for both axes
702 double sx = sw / width;
703 double sy = sh / height;
706 if (width == 0)
707 sx = 1.0;
709 if (height == 0)
710 sy = 1.0;
712 // Fill is the simplest case because AlignementX and AlignmentY don't matter in this case
713 if (stretch == StretchFill) {
714 // fill extents in both axes
715 cairo_matrix_init_scale (matrix, sx, sy);
716 } else {
717 double scale = 1.0;
718 double dx = 0.0;
719 double dy = 0.0;
721 switch (stretch) {
722 case StretchUniform:
723 // fill without cuting the image, center the other axes
724 scale = (sx < sy) ? sy : sx;
725 break;
726 case StretchUniformToFill:
727 // fill by, potentially, cuting the image on one axe, center on both axes
728 scale = (sx < sy) ? sx : sy;
729 break;
730 case StretchNone:
731 break;
732 default:
733 g_warning ("Invalid Stretch value (%d).", stretch);
734 break;
737 switch (align_x) {
738 case AlignmentXLeft:
739 dx = 0.0;
740 break;
741 case AlignmentXCenter:
742 dx = (sw - (scale * width)) / 2;
743 break;
744 // Silverlight+Javascript default to AlignmentXRight for (some) invalid values (others results in an alert)
745 case AlignmentXRight:
746 default:
747 dx = (sw - (scale * width));
748 break;
751 switch (align_y) {
752 case AlignmentYTop:
753 dy = 0.0;
754 break;
755 case AlignmentYCenter:
756 dy = (sh - (scale * height)) / 2;
757 break;
758 // Silverlight+Javascript default to AlignmentXBottom for (some) invalid values (others results in an alert)
759 case AlignmentYBottom:
760 default:
761 dy = (sh - (scale * height));
762 break;
765 if (stretch == StretchNone) {
766 // no strech, no scale
767 cairo_matrix_init_translate (matrix, dx, dy);
768 } else {
769 // otherwise there's both a scale and translation to be done
770 cairo_matrix_init (matrix, scale, 0, 0, scale, dx, dy);
774 if (transform || relative_transform) {
775 if (transform) {
776 cairo_matrix_t tm;
778 transform->GetTransform (&tm);
779 brush_matrix_invert (&tm);
780 cairo_matrix_multiply (matrix, &tm, matrix);
783 if (relative_transform) {
784 cairo_matrix_t tm;
786 transform_get_absolute_transform (relative_transform, width, height, &tm);
787 brush_matrix_invert (&tm);
788 cairo_matrix_multiply (matrix, &tm, matrix);
793 static bool
794 is_stretch_valid (Stretch stretch)
796 switch (stretch) {
797 case StretchNone:
798 case StretchFill:
799 case StretchUniform:
800 case StretchUniformToFill:
801 return true;
802 default:
803 return false;
807 void
808 ImageBrush::SetupBrush (cairo_t *cr, const Rect &area)
810 ImageSource *source = GetImageSource ();
811 cairo_surface_t *surface;
812 cairo_pattern_t *pattern;
813 cairo_matrix_t matrix;
814 Transform *transform;
815 Transform *relative_transform;
816 AlignmentX ax;
817 AlignmentY ay;
818 Stretch stretch;
820 if (!source) goto failed;
822 source->Lock ();
824 surface = source->GetSurface (cr);
826 stretch = GetStretch ();
828 if (!surface || !is_stretch_valid (stretch)) goto failed;
830 ax = GetAlignmentX ();
831 ay = GetAlignmentY ();
833 transform = GetTransform ();
834 relative_transform = GetRelativeTransform ();
836 pattern = cairo_pattern_create_for_surface (surface);
838 image_brush_compute_pattern_matrix (&matrix, area.width, area.height, source->GetPixelWidth (), source->GetPixelHeight (), stretch, ax, ay, transform, relative_transform);
839 cairo_matrix_translate (&matrix, -area.x, -area.y);
840 cairo_pattern_set_matrix (pattern, &matrix);
842 cairo_set_source (cr, pattern);
843 cairo_pattern_destroy (pattern);
845 source->Unlock ();
847 return;
849 failed:
850 cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, 0.0);
851 return;
855 // TileBrush
858 TileBrush::TileBrush ()
860 SetObjectType (Type::TILEBRUSH);
863 TileBrush::~TileBrush ()
867 void
868 TileBrush::Fill (cairo_t *cr, bool preserve)
870 double opacity = GetOpacity ();
872 if (IS_INVISIBLE (opacity)) {
873 if (!preserve)
874 cairo_new_path (cr);
875 return;
878 if (!IS_TRANSLUCENT (opacity)) {
879 Brush::Fill (cr, preserve);
880 return;
883 cairo_save (cr);
884 cairo_clip (cr);
885 cairo_paint_with_alpha (cr, opacity);
886 cairo_restore (cr);
888 if (!preserve)
889 cairo_new_path (cr);
892 void
893 TileBrush::Stroke (cairo_t *cr, bool preserve)
895 double opacity = GetOpacity ();
897 if (IS_INVISIBLE (opacity)) {
898 if (!preserve)
899 cairo_new_path (cr);
900 return;
903 if (!IS_TRANSLUCENT (opacity)) {
904 Brush::Stroke (cr, preserve);
905 return;
908 cairo_save (cr);
909 cairo_push_group_with_content (cr, CAIRO_CONTENT_ALPHA);
910 cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, opacity);
911 cairo_stroke (cr);
913 cairo_pattern_t *mask = cairo_pop_group (cr);
914 cairo_restore (cr);
915 cairo_mask (cr, mask);
916 cairo_pattern_destroy (mask);
918 if (!preserve)
919 cairo_new_path (cr);
923 // VideoBrush
926 VideoBrush::VideoBrush ()
928 SetObjectType (Type::VIDEOBRUSH);
929 media = NULL;
932 VideoBrush::~VideoBrush ()
934 if (media != NULL) {
935 media->RemovePropertyChangeListener (this);
936 media->RemoveHandler (MediaElement::MediaInvalidatedEvent, update_brush, this);
937 media->unref ();
941 void
942 VideoBrush::SetupBrush (cairo_t *cr, const Rect &area)
944 Stretch stretch = GetStretch ();
945 if (!is_stretch_valid (stretch)) {
946 // bad enum value for stretch, nothing should be drawn
947 // XXX Removing this _source_set at all?
948 cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, 0.0);
949 return;
952 MediaPlayer *mplayer = media ? media->GetMediaPlayer () : NULL;
953 Transform *transform = GetTransform ();
954 Transform *relative_transform = GetRelativeTransform ();
955 AlignmentX ax = GetAlignmentX ();
956 AlignmentY ay = GetAlignmentY ();
957 cairo_surface_t *surface;
958 cairo_pattern_t *pattern;
959 cairo_matrix_t matrix;
961 if (media == NULL) {
962 DependencyObject *obj;
963 const char *name;
965 name = GetSourceName ();
967 if (name == NULL || *name == '\0')
968 return;
970 if ((obj = FindName (name)) && obj->Is (Type::MEDIAELEMENT)) {
971 obj->AddPropertyChangeListener (this);
972 media = (MediaElement *) obj;
973 media->AddHandler (MediaElement::MediaInvalidatedEvent, update_brush, this);
974 mplayer = media->GetMediaPlayer ();
975 obj->ref ();
976 } else if (obj == NULL) {
977 printf ("could not find element `%s'\n", name);
978 } else {
979 printf ("obj %p is not of type MediaElement (it is %s)\n", obj,
980 obj->GetTypeName ());
984 if (!mplayer || !(surface = mplayer->GetCairoSurface ())) {
985 // not yet available, draw gray-ish shadow where the brush should be applied
986 cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 0.5);
987 return;
990 pattern = cairo_pattern_create_for_surface (surface);
991 cairo_pattern_set_filter (pattern, CAIRO_FILTER_FAST);
993 image_brush_compute_pattern_matrix (&matrix, area.width, area.height, mplayer->GetVideoWidth (),
994 mplayer->GetVideoHeight (), stretch, ax, ay,
995 transform, relative_transform);
997 cairo_matrix_translate (&matrix, -area.x, -area.y);
998 cairo_pattern_set_matrix (pattern, &matrix);
1000 cairo_set_source (cr, pattern);
1001 cairo_pattern_destroy (pattern);
1004 void
1005 VideoBrush::OnPropertyChanged (PropertyChangedEventArgs *args, MoonError *error)
1007 if (args->GetProperty ()->GetOwnerType() != Type::VIDEOBRUSH) {
1008 TileBrush::OnPropertyChanged (args, error);
1009 return;
1012 if (args->GetId () == VideoBrush::SourceNameProperty) {
1013 char *name = args->GetNewValue() ? args->GetNewValue()->AsString () : NULL;
1014 DependencyObject *obj;
1016 if (media != NULL) {
1017 media->RemovePropertyChangeListener (this);
1018 media->RemoveHandler (MediaElement::MediaInvalidatedEvent, update_brush, this);
1019 media->unref ();
1020 media = NULL;
1023 if (name && (obj = FindName (name)) && obj->Is (Type::MEDIAELEMENT)) {
1024 obj->AddPropertyChangeListener (this);
1025 media = (MediaElement *) obj;
1026 media->AddHandler (MediaElement::MediaInvalidatedEvent, update_brush, this);
1027 obj->ref ();
1028 } else {
1029 // Note: This may have failed because the parser hasn't set the
1030 // toplevel element yet, we'll try again in SetupBrush()
1034 NotifyListenersOfPropertyChange (args, error);
1037 void
1038 VideoBrush::OnSubPropertyChanged (DependencyProperty *prop, DependencyObject *obj, PropertyChangedEventArgs *subobj_args)
1040 /* this is being handled in the base class */
1042 if (subobj_args->GetId () == MediaElement::PositionProperty) {
1043 // We to changes in this MediaElement property so we
1044 // can notify whoever is using us to paint that they
1045 // need to redraw themselves.
1046 NotifyListenersOfPropertyChange (Brush::ChangedProperty);
1050 TileBrush::OnSubPropertyChanged (prop, obj, subobj_args);
1053 void
1054 VideoBrush::SetSource (MediaElement *source)
1056 if (source) {
1057 source->ref ();
1058 source->AddHandler (MediaElement::MediaInvalidatedEvent, update_brush, this);
1061 SetSourceName ("");
1063 if (media != NULL) {
1064 media->RemovePropertyChangeListener (this);
1065 media->RemoveHandler (MediaElement::MediaInvalidatedEvent, update_brush, this);
1066 media->unref ();
1067 media = NULL;
1070 media = source;
1073 bool
1074 VideoBrush::IsOpaque ()
1076 // XXX punt for now and return false here.
1077 return false;
1080 bool
1081 VideoBrush::IsAnimating ()
1083 if (media && media->IsPlaying ())
1084 return true;
1086 return TileBrush::IsAnimating ();
1089 void
1090 VideoBrush::update_brush (EventObject *, EventArgs *, gpointer closure)
1092 VideoBrush *b = (VideoBrush*)closure;
1093 b->NotifyListenersOfPropertyChange (Brush::ChangedProperty, NULL);
1097 // VisualBrush
1100 VisualBrush::VisualBrush ()
1102 SetObjectType (Type::VISUALBRUSH);
1105 VisualBrush::~VisualBrush ()
1109 void
1110 VisualBrush::SetupBrush (cairo_t *cr, const Rect &area)
1112 UIElement *ui = (UIElement *) GetVisual ();
1113 if (!ui) {
1114 // not yet available, draw gray-ish shadow where the brush should be applied
1115 cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 0.5);
1116 return;
1119 // XXX we should cache the surface so that it can be
1120 // used multiple times without having to re-render each time.
1121 Rect bounds = ui->GetSubtreeBounds().RoundOut ();
1123 surface = image_brush_create_similar (cr, (int) bounds.width, (int) bounds.height);
1125 cairo_t *surface_cr = cairo_create (surface);
1126 Region region = Region (0, 0, bounds.width, bounds.height);
1127 ui->Render (surface_cr, &region);
1128 cairo_destroy (surface_cr);
1130 Stretch stretch = GetStretch ();
1132 AlignmentX ax = GetAlignmentX ();
1133 AlignmentY ay = GetAlignmentY ();
1135 Transform *transform = GetTransform ();
1136 Transform *relative_transform = GetRelativeTransform ();
1138 cairo_pattern_t *pattern = cairo_pattern_create_for_surface (surface);
1139 cairo_matrix_t matrix;
1140 image_brush_compute_pattern_matrix (&matrix, area.width, area.height,
1141 (int) bounds.width, (int) bounds.height,
1142 stretch, ax, ay, transform, relative_transform);
1144 cairo_matrix_translate (&matrix, -area.x, -area.y);
1145 cairo_pattern_set_matrix (pattern, &matrix);
1147 cairo_set_source (cr, pattern);
1148 cairo_pattern_destroy (pattern);
1150 cairo_surface_destroy (surface);
1153 void
1154 VisualBrush::update_brush (EventObject *, EventArgs *, gpointer closure)
1156 VisualBrush *b = (VisualBrush*)closure;
1157 b->NotifyListenersOfPropertyChange (Brush::ChangedProperty, NULL);
1160 void
1161 VisualBrush::OnPropertyChanged (PropertyChangedEventArgs *args, MoonError *error)
1163 if (args->GetProperty ()->GetOwnerType() != Type::VISUALBRUSH) {
1164 TileBrush::OnPropertyChanged (args, error);
1165 return;
1168 if (args->GetId () == VisualBrush::VisualProperty) {
1169 // XXX we really need a way to disconnect from the preview visual
1170 UIElement *v = args->GetNewValue()->AsUIElement();
1171 v->AddHandler (((UIElement*)v)->InvalidatedEvent, update_brush, this);
1174 NotifyListenersOfPropertyChange (args, error);
1177 bool
1178 VisualBrush::IsOpaque ()
1180 // XXX punt for now and return false here.
1181 return false;