added MouseWheel event support for Silverlight 3.0
[moon.git] / cairo / src / cairo-misc.c
blob27050a242098aed4bed985ad8f7650bdef126c2a
1 /* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
2 /* cairo - a vector graphics library with display and print output
4 * Copyright © 2002 University of Southern California
5 * Copyright © 2005 Red Hat, Inc.
6 * Copyright © 2007 Adrian Johnson
8 * This library is free software; you can redistribute it and/or
9 * modify it either under the terms of the GNU Lesser General Public
10 * License version 2.1 as published by the Free Software Foundation
11 * (the "LGPL") or, at your option, under the terms of the Mozilla
12 * Public License Version 1.1 (the "MPL"). If you do not alter this
13 * notice, a recipient may use your version of this file under either
14 * the MPL or the LGPL.
16 * You should have received a copy of the LGPL along with this library
17 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 * You should have received a copy of the MPL along with this library
20 * in the file COPYING-MPL-1.1
22 * The contents of this file are subject to the Mozilla Public License
23 * Version 1.1 (the "License"); you may not use this file except in
24 * compliance with the License. You may obtain a copy of the License at
25 * http://www.mozilla.org/MPL/
27 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
28 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
29 * the specific language governing rights and limitations.
31 * The Original Code is the cairo graphics library.
33 * The Initial Developer of the Original Code is University of Southern
34 * California.
36 * Contributor(s):
37 * Carl D. Worth <cworth@cworth.org>
38 * Adrian Johnson <ajohnson@redneon.com>
41 #include "cairoint.h"
43 COMPILE_TIME_ASSERT (CAIRO_STATUS_LAST_STATUS < CAIRO_INT_STATUS_UNSUPPORTED);
44 COMPILE_TIME_ASSERT (CAIRO_INT_STATUS_LAST_STATUS <= 127);
46 /* Public stuff */
48 /**
49 * cairo_status_to_string:
50 * @status: a cairo status
52 * Provides a human-readable description of a #cairo_status_t.
54 * Returns: a string representation of the status
56 const char *
57 cairo_status_to_string (cairo_status_t status)
59 switch (status) {
60 case CAIRO_STATUS_SUCCESS:
61 return "success";
62 case CAIRO_STATUS_NO_MEMORY:
63 return "out of memory";
64 case CAIRO_STATUS_INVALID_RESTORE:
65 return "cairo_restore without matching cairo_save";
66 case CAIRO_STATUS_INVALID_POP_GROUP:
67 return "cairo_pop_group without matching cairo_push_group";
68 case CAIRO_STATUS_NO_CURRENT_POINT:
69 return "no current point defined";
70 case CAIRO_STATUS_INVALID_MATRIX:
71 return "invalid matrix (not invertible)";
72 case CAIRO_STATUS_INVALID_STATUS:
73 return "invalid value for an input cairo_status_t";
74 case CAIRO_STATUS_NULL_POINTER:
75 return "NULL pointer";
76 case CAIRO_STATUS_INVALID_STRING:
77 return "input string not valid UTF-8";
78 case CAIRO_STATUS_INVALID_PATH_DATA:
79 return "input path data not valid";
80 case CAIRO_STATUS_READ_ERROR:
81 return "error while reading from input stream";
82 case CAIRO_STATUS_WRITE_ERROR:
83 return "error while writing to output stream";
84 case CAIRO_STATUS_SURFACE_FINISHED:
85 return "the target surface has been finished";
86 case CAIRO_STATUS_SURFACE_TYPE_MISMATCH:
87 return "the surface type is not appropriate for the operation";
88 case CAIRO_STATUS_PATTERN_TYPE_MISMATCH:
89 return "the pattern type is not appropriate for the operation";
90 case CAIRO_STATUS_INVALID_CONTENT:
91 return "invalid value for an input cairo_content_t";
92 case CAIRO_STATUS_INVALID_FORMAT:
93 return "invalid value for an input cairo_format_t";
94 case CAIRO_STATUS_INVALID_VISUAL:
95 return "invalid value for an input Visual*";
96 case CAIRO_STATUS_FILE_NOT_FOUND:
97 return "file not found";
98 case CAIRO_STATUS_INVALID_DASH:
99 return "invalid value for a dash setting";
100 case CAIRO_STATUS_INVALID_DSC_COMMENT:
101 return "invalid value for a DSC comment";
102 case CAIRO_STATUS_INVALID_INDEX:
103 return "invalid index passed to getter";
104 case CAIRO_STATUS_CLIP_NOT_REPRESENTABLE:
105 return "clip region not representable in desired format";
106 case CAIRO_STATUS_TEMP_FILE_ERROR:
107 return "error creating or writing to a temporary file";
108 case CAIRO_STATUS_INVALID_STRIDE:
109 return "invalid value for stride";
110 case CAIRO_STATUS_FONT_TYPE_MISMATCH:
111 return "the font type is not appropriate for the operation";
112 case CAIRO_STATUS_USER_FONT_IMMUTABLE:
113 return "the user-font is immutable";
114 case CAIRO_STATUS_USER_FONT_ERROR:
115 return "error occurred in a user-font callback function";
116 case CAIRO_STATUS_NEGATIVE_COUNT:
117 return "negative number used where it is not allowed";
118 case CAIRO_STATUS_INVALID_CLUSTERS:
119 return "input clusters do not represent the accompanying text and glyph arrays";
120 case CAIRO_STATUS_INVALID_SLANT:
121 return "invalid value for an input #cairo_font_slant_t";
122 case CAIRO_STATUS_INVALID_WEIGHT:
123 return "input value for an input #cairo_font_weight_t";
126 return "<unknown error status>";
131 * cairo_glyph_allocate:
132 * @num_glyphs: number of glyphs to allocate
134 * Allocates an array of #cairo_glyph_t's.
135 * This function is only useful in implementations of
136 * #cairo_user_scaled_font_text_to_glyphs_func_t where the user
137 * needs to allocate an array of glyphs that cairo will free.
138 * For all other uses, user can use their own allocation method
139 * for glyphs.
141 * This function returns %NULL if @num_glyphs is not positive,
142 * or if out of memory. That means, the %NULL return value
143 * signals out-of-memory only if @num_glyphs was positive.
145 * Returns: the newly allocated array of glyphs that should be
146 * freed using cairo_glyph_free()
148 * Since: 1.8
150 cairo_glyph_t *
151 cairo_glyph_allocate (int num_glyphs)
153 if (num_glyphs <= 0)
154 return NULL;
156 return _cairo_malloc_ab (num_glyphs, sizeof (cairo_glyph_t));
158 slim_hidden_def (cairo_glyph_allocate);
161 * cairo_glyph_free:
162 * @glyphs: array of glyphs to free, or %NULL
164 * Frees an array of #cairo_glyph_t's allocated using cairo_glyph_allocate().
165 * This function is only useful to free glyph array returned
166 * by cairo_scaled_font_text_to_glyphs() where cairo returns
167 * an array of glyphs that the user will free.
168 * For all other uses, user can use their own allocation method
169 * for glyphs.
171 * Since: 1.8
173 void
174 cairo_glyph_free (cairo_glyph_t *glyphs)
176 if (glyphs)
177 free (glyphs);
179 slim_hidden_def (cairo_glyph_free);
182 * cairo_text_cluster_allocate:
183 * @num_clusters: number of text_clusters to allocate
185 * Allocates an array of #cairo_text_cluster_t's.
186 * This function is only useful in implementations of
187 * #cairo_user_scaled_font_text_to_glyphs_func_t where the user
188 * needs to allocate an array of text clusters that cairo will free.
189 * For all other uses, user can use their own allocation method
190 * for text clusters.
192 * This function returns %NULL if @num_clusters is not positive,
193 * or if out of memory. That means, the %NULL return value
194 * signals out-of-memory only if @num_clusters was positive.
196 * Returns: the newly allocated array of text clusters that should be
197 * freed using cairo_text_cluster_free()
199 * Since: 1.8
201 cairo_text_cluster_t *
202 cairo_text_cluster_allocate (int num_clusters)
204 if (num_clusters <= 0)
205 return NULL;
207 return _cairo_malloc_ab (num_clusters, sizeof (cairo_text_cluster_t));
209 slim_hidden_def (cairo_text_cluster_allocate);
212 * cairo_text_cluster_free:
213 * @clusters: array of text clusters to free, or %NULL
215 * Frees an array of #cairo_text_cluster's allocated using cairo_text_cluster_allocate().
216 * This function is only useful to free text cluster array returned
217 * by cairo_scaled_font_text_to_glyphs() where cairo returns
218 * an array of text clusters that the user will free.
219 * For all other uses, user can use their own allocation method
220 * for text clusters.
222 * Since: 1.8
224 void
225 cairo_text_cluster_free (cairo_text_cluster_t *clusters)
227 if (clusters)
228 free (clusters);
230 slim_hidden_def (cairo_text_cluster_free);
233 /* Private stuff */
236 * _cairo_validate_text_clusters:
237 * @utf8: UTF-8 text
238 * @utf8_len: length of @utf8 in bytes
239 * @glyphs: array of glyphs
240 * @num_glyphs: number of glyphs
241 * @clusters: array of cluster mapping information
242 * @num_clusters: number of clusters in the mapping
243 * @cluster_flags: cluster flags
245 * Check that clusters cover the entire glyphs and utf8 arrays,
246 * and that cluster boundaries are UTF-8 boundaries.
248 * Return value: %CAIRO_STATUS_SUCCESS upon success, or
249 * %CAIRO_STATUS_INVALID_CLUSTERS on error.
250 * The error is either invalid UTF-8 input,
251 * or bad cluster mapping.
253 cairo_status_t
254 _cairo_validate_text_clusters (const char *utf8,
255 int utf8_len,
256 const cairo_glyph_t *glyphs,
257 int num_glyphs,
258 const cairo_text_cluster_t *clusters,
259 int num_clusters,
260 cairo_text_cluster_flags_t cluster_flags)
262 cairo_status_t status;
263 unsigned int n_bytes = 0;
264 unsigned int n_glyphs = 0;
265 int i;
267 for (i = 0; i < num_clusters; i++) {
268 int cluster_bytes = clusters[i].num_bytes;
269 int cluster_glyphs = clusters[i].num_glyphs;
271 if (cluster_bytes < 0 || cluster_glyphs < 0)
272 goto BAD;
274 /* A cluster should cover at least one character or glyph.
275 * I can't see any use for a 0,0 cluster.
276 * I can't see an immediate use for a zero-text cluster
277 * right now either, but they don't harm.
278 * Zero-glyph clusters on the other hand are useful for
279 * things like U+200C ZERO WIDTH NON-JOINER */
280 if (cluster_bytes == 0 && cluster_glyphs == 0)
281 goto BAD;
283 /* Since n_bytes and n_glyphs are unsigned, but the rest of
284 * values involved are signed, we can detect overflow easily */
285 if (n_bytes+cluster_bytes > (unsigned int)utf8_len || n_glyphs+cluster_glyphs > (unsigned int)num_glyphs)
286 goto BAD;
288 /* Make sure we've got valid UTF-8 for the cluster */
289 status = _cairo_utf8_to_ucs4 (utf8+n_bytes, cluster_bytes, NULL, NULL);
290 if (status)
291 return CAIRO_STATUS_INVALID_CLUSTERS;
293 n_bytes += cluster_bytes ;
294 n_glyphs += cluster_glyphs;
297 if (n_bytes != (unsigned int) utf8_len || n_glyphs != (unsigned int) num_glyphs) {
298 BAD:
299 return CAIRO_STATUS_INVALID_CLUSTERS;
302 return CAIRO_STATUS_SUCCESS;
306 * _cairo_operator_bounded_by_mask:
307 * @op: a #cairo_operator_t
309 * A bounded operator is one where mask pixel
310 * of zero results in no effect on the destination image.
312 * Unbounded operators often require special handling; if you, for
313 * example, draw trapezoids with an unbounded operator, the effect
314 * extends past the bounding box of the trapezoids.
316 * Return value: %TRUE if the operator is bounded by the mask operand
318 cairo_bool_t
319 _cairo_operator_bounded_by_mask (cairo_operator_t op)
321 switch (op) {
322 case CAIRO_OPERATOR_CLEAR:
323 case CAIRO_OPERATOR_SOURCE:
324 case CAIRO_OPERATOR_OVER:
325 case CAIRO_OPERATOR_ATOP:
326 case CAIRO_OPERATOR_DEST:
327 case CAIRO_OPERATOR_DEST_OVER:
328 case CAIRO_OPERATOR_DEST_OUT:
329 case CAIRO_OPERATOR_XOR:
330 case CAIRO_OPERATOR_ADD:
331 case CAIRO_OPERATOR_SATURATE:
332 return TRUE;
333 case CAIRO_OPERATOR_OUT:
334 case CAIRO_OPERATOR_IN:
335 case CAIRO_OPERATOR_DEST_IN:
336 case CAIRO_OPERATOR_DEST_ATOP:
337 return FALSE;
340 ASSERT_NOT_REACHED;
341 return FALSE;
345 * _cairo_operator_bounded_by_source:
346 * @op: a #cairo_operator_t
348 * A bounded operator is one where source pixels of zero
349 * (in all four components, r, g, b and a) effect no change
350 * in the resulting destination image.
352 * Unbounded operators often require special handling; if you, for
353 * example, copy a surface with the SOURCE operator, the effect
354 * extends past the bounding box of the source surface.
356 * Return value: %TRUE if the operator is bounded by the source operand
358 cairo_bool_t
359 _cairo_operator_bounded_by_source (cairo_operator_t op)
361 switch (op) {
362 case CAIRO_OPERATOR_OVER:
363 case CAIRO_OPERATOR_ATOP:
364 case CAIRO_OPERATOR_DEST:
365 case CAIRO_OPERATOR_DEST_OVER:
366 case CAIRO_OPERATOR_DEST_OUT:
367 case CAIRO_OPERATOR_XOR:
368 case CAIRO_OPERATOR_ADD:
369 case CAIRO_OPERATOR_SATURATE:
370 return TRUE;
371 case CAIRO_OPERATOR_CLEAR:
372 case CAIRO_OPERATOR_SOURCE:
373 case CAIRO_OPERATOR_OUT:
374 case CAIRO_OPERATOR_IN:
375 case CAIRO_OPERATOR_DEST_IN:
376 case CAIRO_OPERATOR_DEST_ATOP:
377 return FALSE;
380 ASSERT_NOT_REACHED;
381 return FALSE;
385 void
386 _cairo_restrict_value (double *value, double min, double max)
388 if (*value < min)
389 *value = min;
390 else if (*value > max)
391 *value = max;
394 /* This function is identical to the C99 function lround(), except that it
395 * performs arithmetic rounding (instead of away-from-zero rounding) and
396 * has a valid input range of (INT_MIN, INT_MAX] instead of
397 * [INT_MIN, INT_MAX]. It is much faster on both x86 and FPU-less systems
398 * than other commonly used methods for rounding (lround, round, rint, lrint
399 * or float (d + 0.5)).
401 * The reason why this function is much faster on x86 than other
402 * methods is due to the fact that it avoids the fldcw instruction.
403 * This instruction incurs a large performance penalty on modern Intel
404 * processors due to how it prevents efficient instruction pipelining.
406 * The reason why this function is much faster on FPU-less systems is for
407 * an entirely different reason. All common rounding methods involve multiple
408 * floating-point operations. Each one of these operations has to be
409 * emulated in software, which adds up to be a large performance penalty.
410 * This function doesn't perform any floating-point calculations, and thus
411 * avoids this penalty.
414 _cairo_lround (double d)
416 uint32_t top, shift_amount, output;
417 union {
418 double d;
419 uint64_t ui64;
420 uint32_t ui32[2];
421 } u;
423 u.d = d;
425 /* If the integer word order doesn't match the float word order, we swap
426 * the words of the input double. This is needed because we will be
427 * treating the whole double as a 64-bit unsigned integer. Notice that we
428 * use WORDS_BIGENDIAN to detect the integer word order, which isn't
429 * exactly correct because WORDS_BIGENDIAN refers to byte order, not word
430 * order. Thus, we are making the assumption that the byte order is the
431 * same as the integer word order which, on the modern machines that we
432 * care about, is OK.
434 #if ( defined(FLOAT_WORDS_BIGENDIAN) && !defined(WORDS_BIGENDIAN)) || \
435 (!defined(FLOAT_WORDS_BIGENDIAN) && defined(WORDS_BIGENDIAN))
437 uint32_t temp = u.ui32[0];
438 u.ui32[0] = u.ui32[1];
439 u.ui32[1] = temp;
441 #endif
443 #ifdef WORDS_BIGENDIAN
444 #define MSW (0) /* Most Significant Word */
445 #define LSW (1) /* Least Significant Word */
446 #else
447 #define MSW (1)
448 #define LSW (0)
449 #endif
451 /* By shifting the most significant word of the input double to the
452 * right 20 places, we get the very "top" of the double where the exponent
453 * and sign bit lie.
455 top = u.ui32[MSW] >> 20;
457 /* Here, we calculate how much we have to shift the mantissa to normalize
458 * it to an integer value. We extract the exponent "top" by masking out the
459 * sign bit, then we calculate the shift amount by subtracting the exponent
460 * from the bias. Notice that the correct bias for 64-bit doubles is
461 * actually 1075, but we use 1053 instead for two reasons:
463 * 1) To perform rounding later on, we will first need the target
464 * value in a 31.1 fixed-point format. Thus, the bias needs to be one
465 * less: (1075 - 1: 1074).
467 * 2) To avoid shifting the mantissa as a full 64-bit integer (which is
468 * costly on certain architectures), we break the shift into two parts.
469 * First, the upper and lower parts of the mantissa are shifted
470 * individually by a constant amount that all valid inputs will require
471 * at the very least. This amount is chosen to be 21, because this will
472 * allow the two parts of the mantissa to later be combined into a
473 * single 32-bit representation, on which the remainder of the shift
474 * will be performed. Thus, we decrease the bias by an additional 21:
475 * (1074 - 21: 1053).
477 shift_amount = 1053 - (top & 0x7FF);
479 /* We are done with the exponent portion in "top", so here we shift it off
480 * the end.
482 top >>= 11;
484 /* Before we perform any operations on the mantissa, we need to OR in
485 * the implicit 1 at the top (see the IEEE-754 spec). We needn't mask
486 * off the sign bit nor the exponent bits because these higher bits won't
487 * make a bit of difference in the rest of our calculations.
489 u.ui32[MSW] |= 0x100000;
491 /* If the input double is negative, we have to decrease the mantissa
492 * by a hair. This is an important part of performing arithmetic rounding,
493 * as negative numbers must round towards positive infinity in the
494 * halfwase case of -x.5. Since "top" contains only the sign bit at this
495 * point, we can just decrease the mantissa by the value of "top".
497 u.ui64 -= top;
499 /* By decrementing "top", we create a bitmask with a value of either
500 * 0x0 (if the input was negative) or 0xFFFFFFFF (if the input was positive
501 * and thus the unsigned subtraction underflowed) that we'll use later.
503 top--;
505 /* Here, we shift the mantissa by the constant value as described above.
506 * We can emulate a 64-bit shift right by 21 through shifting the top 32
507 * bits left 11 places and ORing in the bottom 32 bits shifted 21 places
508 * to the right. Both parts of the mantissa are now packed into a single
509 * 32-bit integer. Although we severely truncate the lower part in the
510 * process, we still have enough significant bits to perform the conversion
511 * without error (for all valid inputs).
513 output = (u.ui32[MSW] << 11) | (u.ui32[LSW] >> 21);
515 /* Next, we perform the shift that converts the X.Y fixed-point number
516 * currently found in "output" to the desired 31.1 fixed-point format
517 * needed for the following rounding step. It is important to consider
518 * all possible values for "shift_amount" at this point:
520 * - {shift_amount < 0} Since shift_amount is an unsigned integer, it
521 * really can't have a value less than zero. But, if the shift_amount
522 * calculation above caused underflow (which would happen with
523 * input > INT_MAX or input <= INT_MIN) then shift_amount will now be
524 * a very large number, and so this shift will result in complete
525 * garbage. But that's OK, as the input was out of our range, so our
526 * output is undefined.
528 * - {shift_amount > 31} If the magnitude of the input was very small
529 * (i.e. |input| << 1.0), shift_amount will have a value greater than
530 * 31. Thus, this shift will also result in garbage. After performing
531 * the shift, we will zero-out "output" if this is the case.
533 * - {0 <= shift_amount < 32} In this case, the shift will properly convert
534 * the mantissa into a 31.1 fixed-point number.
536 output >>= shift_amount;
538 /* This is where we perform rounding with the 31.1 fixed-point number.
539 * Since what we're after is arithmetic rounding, we simply add the single
540 * fractional bit into the integer part of "output", and just keep the
541 * integer part.
543 output = (output >> 1) + (output & 1);
545 /* Here, we zero-out the result if the magnitude if the input was very small
546 * (as explained in the section above). Notice that all input out of the
547 * valid range is also caught by this condition, which means we produce 0
548 * for all invalid input, which is a nice side effect.
550 * The most straightforward way to do this would be:
552 * if (shift_amount > 31)
553 * output = 0;
555 * But we can use a little trick to avoid the potential branch. The
556 * expression (shift_amount > 31) will be either 1 or 0, which when
557 * decremented will be either 0x0 or 0xFFFFFFFF (unsigned underflow),
558 * which can be used to conditionally mask away all the bits in "output"
559 * (in the 0x0 case), effectively zeroing it out. Certain, compilers would
560 * have done this for us automatically.
562 output &= ((shift_amount > 31) - 1);
564 /* If the input double was a negative number, then we have to negate our
565 * output. The most straightforward way to do this would be:
567 * if (!top)
568 * output = -output;
570 * as "top" at this point is either 0x0 (if the input was negative) or
571 * 0xFFFFFFFF (if the input was positive). But, we can use a trick to
572 * avoid the branch. Observe that the following snippet of code has the
573 * same effect as the reference snippet above:
575 * if (!top)
576 * output = 0 - output;
577 * else
578 * output = output - 0;
580 * Armed with the bitmask found in "top", we can condense the two statements
581 * into the following:
583 * output = (output & top) - (output & ~top);
585 * where, in the case that the input double was negative, "top" will be 0,
586 * and the statement will be equivalent to:
588 * output = (0) - (output);
590 * and if the input double was positive, "top" will be 0xFFFFFFFF, and the
591 * statement will be equivalent to:
593 * output = (output) - (0);
595 * Which, as pointed out earlier, is equivalent to the original reference
596 * snippet.
598 output = (output & top) - (output & ~top);
600 return output;
601 #undef MSW
602 #undef LSW
606 #ifdef _WIN32
608 #define WIN32_LEAN_AND_MEAN
609 /* We require Windows 2000 features such as ETO_PDY */
610 #if !defined(WINVER) || (WINVER < 0x0500)
611 # define WINVER 0x0500
612 #endif
613 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
614 # define _WIN32_WINNT 0x0500
615 #endif
617 #include <windows.h>
618 #include <io.h>
620 /* tmpfile() replacment for Windows.
622 * On Windows tmpfile() creates the file in the root directory. This
623 * may fail due to unsufficient privileges.
625 FILE *
626 _cairo_win32_tmpfile (void)
628 DWORD path_len;
629 WCHAR path_name[MAX_PATH + 1];
630 WCHAR file_name[MAX_PATH + 1];
631 HANDLE handle;
632 int fd;
633 FILE *fp;
635 path_len = GetTempPathW (MAX_PATH, path_name);
636 if (path_len <= 0 || path_len >= MAX_PATH)
637 return NULL;
639 if (GetTempFileNameW (path_name, L"ps_", 0, file_name) == 0)
640 return NULL;
642 handle = CreateFileW (file_name,
643 GENERIC_READ | GENERIC_WRITE,
645 NULL,
646 CREATE_ALWAYS,
647 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,
648 NULL);
649 if (handle == INVALID_HANDLE_VALUE) {
650 DeleteFileW (file_name);
651 return NULL;
654 fd = _open_osfhandle((intptr_t) handle, 0);
655 if (fd < 0) {
656 CloseHandle (handle);
657 return NULL;
660 fp = fdopen(fd, "w+b");
661 if (fp == NULL) {
662 _close(fd);
663 return NULL;
666 return fp;
669 #endif /* _WIN32 */