19646fb031c09186752325f531ef07abfe41f294
[framework/graphics/cairo.git] / src / cairo-os2-surface.c
1 /* vim: set sw=4 sts=4 et cin: */
2 /* cairo - a vector graphics library with display and print output
3  *
4  * Copyright (c) 2005-2006 netlabs.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it either under the terms of the GNU Lesser General Public
8  * License version 2.1 as published by the Free Software Foundation
9  * (the "LGPL") or, at your option, under the terms of the Mozilla
10  * Public License Version 1.1 (the "MPL"). If you do not alter this
11  * notice, a recipient may use your version of this file under either
12  * the MPL or the LGPL.
13  *
14  * You should have received a copy of the LGPL along with this library
15  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
17  * You should have received a copy of the MPL along with this library
18  * in the file COPYING-MPL-1.1
19  *
20  * The contents of this file are subject to the Mozilla Public License
21  * Version 1.1 (the "License"); you may not use this file except in
22  * compliance with the License. You may obtain a copy of the License at
23  * http://www.mozilla.org/MPL/
24  *
25  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
26  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
27  * the specific language governing rights and limitations.
28  *
29  * The Original Code is the cairo graphics library.
30  *
31  * The Initial Developer of the Original Code is
32  *     Doodle <doodle@scenergy.dfmk.hu>
33  *
34  * Contributor(s):
35  *     Peter Weilbacher <mozilla@Weilbacher.org>
36  *     Rich Walsh <dragtext@e-vertise.com>
37  */
38
39 #include "cairoint.h"
40
41 #include "cairo-os2-private.h"
42 #include "cairo-default-context-private.h"
43 #include "cairo-error-private.h"
44 #include "cairo-surface-fallback-private.h"
45 #include "cairo-image-surface-private.h"
46
47 #if CAIRO_HAS_FC_FONT
48 #include <fontconfig/fontconfig.h>
49 #endif
50
51 #include <float.h>
52 #ifdef BUILD_CAIRO_DLL
53 # include "cairo-os2.h"
54 # ifndef __WATCOMC__
55 #  include <emx/startup.h>
56 # endif
57 #endif
58
59 /*
60  * Here comes the extra API for the OS/2 platform. Currently it consists
61  * of two extra functions, the cairo_os2_init() and the
62  * cairo_os2_fini(). Both of them are called automatically if
63  * Cairo is compiled to be a DLL file, but you have to call them before
64  * using the Cairo API if you link to Cairo statically!
65  *
66  * You'll also find the code in here which deals with DLL initialization
67  * and termination, if the code is built to be a DLL.
68  * (if BUILD_CAIRO_DLL is defined)
69  */
70
71 /* Initialization counter: */
72 static int cairo_os2_initialization_count = 0;
73
74 static inline void
75 DisableFPUException (void)
76 {
77     unsigned short usCW;
78
79     /* Some OS/2 PM API calls modify the FPU Control Word,
80      * but forget to restore it.
81      *
82      * This can result in XCPT_FLOAT_INVALID_OPCODE exceptions,
83      * so to be sure, we disable Invalid Opcode FPU exception
84      * before using FPU stuffs.
85      */
86     usCW = _control87 (0, 0);
87     usCW = usCW | EM_INVALID | 0x80;
88     _control87 (usCW, MCW_EM | 0x80);
89 }
90
91 /**
92  * cairo_os2_init:
93  *
94  * Initializes the Cairo library. This function is automatically called if
95  * Cairo was compiled to be a DLL (however it's not a problem if it's called
96  * multiple times). But if you link to Cairo statically, you have to call it
97  * once to set up Cairo's internal structures and mutexes.
98  *
99  * Since: 1.4
100  **/
101 cairo_public void
102 cairo_os2_init (void)
103 {
104     /* This may initialize some stuffs, like create mutex semaphores etc.. */
105
106     cairo_os2_initialization_count++;
107     if (cairo_os2_initialization_count > 1) return;
108
109     DisableFPUException ();
110
111 #if CAIRO_HAS_FC_FONT
112     /* Initialize FontConfig */
113     FcInit ();
114 #endif
115
116     CAIRO_MUTEX_INITIALIZE ();
117 }
118
119 /**
120  * cairo_os2_fini:
121  *
122  * Uninitializes the Cairo library. This function is automatically called if
123  * Cairo was compiled to be a DLL (however it's not a problem if it's called
124  * multiple times). But if you link to Cairo statically, you have to call it
125  * once to shut down Cairo, to let it free all the resources it has allocated.
126  *
127  * Since: 1.4
128  **/
129 cairo_public void
130 cairo_os2_fini (void)
131 {
132     /* This has to uninitialize some stuffs, like destroy mutex semaphores etc.. */
133
134     if (cairo_os2_initialization_count <= 0) return;
135     cairo_os2_initialization_count--;
136     if (cairo_os2_initialization_count > 0) return;
137
138     DisableFPUException ();
139
140     cairo_debug_reset_static_data ();
141
142 #if CAIRO_HAS_FC_FONT
143 # if HAVE_FCFINI
144     /* Uninitialize FontConfig */
145     FcFini ();
146 # endif
147 #endif
148
149 #ifdef __WATCOMC__
150     /* It can happen that the libraries we use have memory leaks,
151      * so there are still memory chunks allocated at this point.
152      * In these cases, Watcom might still have a bigger memory chunk,
153      * called "the heap" allocated from the OS.
154      * As we want to minimize the memory we lose from the point of
155      * view of the OS, we call this function to shrink that heap
156      * as much as possible.
157      */
158     _heapshrink ();
159 #else
160     /* GCC has a heapmin function that approximately corresponds to
161      * what the Watcom function does
162      */
163     _heapmin ();
164 #endif
165 }
166
167 /*
168  * This function calls the allocation function depending on which
169  * method was compiled into the library: it can be native allocation
170  * (DosAllocMem/DosFreeMem) or C-Library based allocation (malloc/free).
171  * Actually, for pixel buffers that we use this function for, cairo
172  * uses _cairo_malloc_abc, so we use that here, too. And use the
173  * change to check the size argument
174  */
175 void *_buffer_alloc (size_t a, size_t b, const unsigned int size)
176 {
177     size_t nbytes;
178     void  *buffer = NULL;
179
180     if (!a || !b || !size ||
181         a >= INT32_MAX / b || a*b >= INT32_MAX / size) {
182         return NULL;
183     }
184     nbytes = a * b * size;
185
186 #ifdef OS2_USE_PLATFORM_ALLOC
187     /* Using OBJ_ANY on a machine that isn't configured for hi-mem
188      * will cause ERROR_INVALID_PARAMETER.  If this occurs, or this
189      * build doesn't have hi-mem enabled, fall back to using lo-mem.
190      */
191 #ifdef OS2_HIGH_MEMORY
192     if (!DosAllocMem (&buffer, nbytes,
193                       OBJ_ANY | PAG_READ | PAG_WRITE | PAG_COMMIT))
194         return buffer;
195 #endif
196     if (DosAllocMem (&buffer, nbytes,
197                      PAG_READ | PAG_WRITE | PAG_COMMIT))
198         return NULL;
199 #else
200     /* Clear the malloc'd buffer the way DosAllocMem() does. */
201     buffer = malloc (nbytes);
202     if (buffer) {
203         memset (buffer, 0, nbytes);
204     }
205 #endif
206     return buffer;
207 }
208
209 /*
210  * This function selects the free function depending on which
211  * allocation method was compiled into the library
212  */
213 void _buffer_free (void *buffer)
214 {
215 #ifdef OS2_USE_PLATFORM_ALLOC
216     DosFreeMem (buffer);
217 #else
218     free (buffer);
219 #endif
220 }
221
222 /* XXX
223  * The cairo_os2_ini() and cairo_os2_fini() functions should be removed and
224  * the LibMain code moved to cairo-system.c.  It should also call
225  * cairo_debug_reset_static_data() instead of duplicating its logic...
226  */
227
228 #ifdef BUILD_CAIRO_DLL
229 /* The main DLL entry for DLL initialization and uninitialization */
230 /* Only include this code if we're about to build a DLL.          */
231
232 #ifdef __WATCOMC__
233 unsigned _System
234 LibMain (unsigned hmod,
235          unsigned termination)
236 #else
237 unsigned long _System
238 _DLL_InitTerm (unsigned long hModule,
239                unsigned long termination)
240 #endif
241 {
242     if (termination) {
243         /* Unloading the DLL */
244         cairo_os2_fini ();
245
246 #ifndef __WATCOMC__
247         /* Uninitialize RTL of GCC */
248         __ctordtorTerm ();
249         _CRT_term ();
250 #endif
251         return 1;
252     } else {
253         /* Loading the DLL */
254 #ifndef __WATCOMC__
255         /* Initialize RTL of GCC */
256         if (_CRT_init () != 0)
257             return 0;
258         __ctordtorInit ();
259 #endif
260
261         cairo_os2_init ();
262         return 1;
263     }
264 }
265
266 #endif /* BUILD_CAIRO_DLL */
267
268 /*
269  * The following part of the source file contains the code which might
270  * be called the "core" of the OS/2 backend support. This contains the
271  * OS/2 surface support functions and structures.
272  */
273
274 /* Forward declaration */
275 static const cairo_surface_backend_t cairo_os2_surface_backend;
276
277 /* Unpublished API:
278  *   GpiEnableYInversion = PMGPI.723
279  *   GpiQueryYInversion = PMGPI.726
280  *   BOOL APIENTRY GpiEnableYInversion (HPS hps, LONG lHeight);
281  *   LONG APIENTRY GpiQueryYInversion (HPS hps);
282  */
283 BOOL APIENTRY GpiEnableYInversion (HPS hps, LONG lHeight);
284 LONG APIENTRY GpiQueryYInversion (HPS hps);
285
286 #ifdef __WATCOMC__
287 /* Function declaration for GpiDrawBits () (missing from OpenWatcom headers) */
288 LONG APIENTRY GpiDrawBits (HPS hps,
289                            PVOID pBits,
290                            PBITMAPINFO2 pbmiInfoTable,
291                            LONG lCount,
292                            PPOINTL aptlPoints,
293                            LONG lRop,
294                            ULONG flOptions);
295 #endif
296
297 static void
298 _cairo_os2_surface_blit_pixels (cairo_os2_surface_t *surface,
299                                 HPS                  hps_begin_paint,
300                                 PRECTL               prcl_begin_paint_rect)
301 {
302     POINTL aptlPoints[4];
303     LONG   lOldYInversion;
304     LONG   rc = GPI_OK;
305
306     /* Check the limits (may not be necessary) */
307     if (prcl_begin_paint_rect->xLeft < 0)
308         prcl_begin_paint_rect->xLeft = 0;
309     if (prcl_begin_paint_rect->yBottom < 0)
310         prcl_begin_paint_rect->yBottom = 0;
311     if (prcl_begin_paint_rect->xRight > (LONG) surface->bitmap_info.cx)
312         prcl_begin_paint_rect->xRight = (LONG) surface->bitmap_info.cx;
313     if (prcl_begin_paint_rect->yTop > (LONG) surface->bitmap_info.cy)
314         prcl_begin_paint_rect->yTop = (LONG) surface->bitmap_info.cy;
315
316     /* Exit if the rectangle is empty */
317     if (prcl_begin_paint_rect->xLeft   >= prcl_begin_paint_rect->xRight ||
318         prcl_begin_paint_rect->yBottom >= prcl_begin_paint_rect->yTop)
319         return;
320
321     /* Set the Target & Source coordinates */
322     *((PRECTL)&aptlPoints[0]) = *prcl_begin_paint_rect;
323     *((PRECTL)&aptlPoints[2]) = *prcl_begin_paint_rect;
324
325     /* Make the Target coordinates non-inclusive */
326     aptlPoints[1].x -= 1;
327     aptlPoints[1].y -= 1;
328
329     /* Enable Y Inversion for the HPS, so  GpiDrawBits will
330      * work with upside-top image, not with upside-down image!
331      */
332     lOldYInversion = GpiQueryYInversion (hps_begin_paint);
333     GpiEnableYInversion (hps_begin_paint, surface->bitmap_info.cy-1);
334
335     /* Debug code to draw rectangle limits */
336 #if 0
337     {
338         int x, y;
339         unsigned char *pixels;
340
341         pixels = surface->pixels;
342         for (x = 0; x < surface->bitmap_info.cx; x++) {
343             for (y = 0; y < surface->bitmap_info.cy; y++) {
344                 if ((x == 0) ||
345                     (y == 0) ||
346                     (x == y) ||
347                     (x >= surface->bitmap_info.cx-1) ||
348                     (y >= surface->bitmap_info.cy-1))
349                 {
350                     pixels[y*surface->bitmap_info.cx*4+x*4] = 255;
351                 }
352             }
353         }
354     }
355 #endif
356     if (!surface->use_24bpp) {
357         rc = GpiDrawBits (hps_begin_paint,
358                           surface->pixels,
359                           &(surface->bitmap_info),
360                           4,
361                           aptlPoints,
362                           ROP_SRCCOPY,
363                           BBO_IGNORE);
364         if (rc != GPI_OK)
365             surface->use_24bpp = TRUE;
366     }
367
368     if (surface->use_24bpp) {
369         /* If GpiDrawBits () failed then this is most likely because the
370          * display driver could not handle a 32bit bitmap. So we need to
371          * - create a buffer that only contains 3 bytes per pixel
372          * - change the bitmap info header to contain 24bit
373          * - pass the new buffer to GpiDrawBits () again
374          * - clean up the new buffer
375          */
376         BITMAPINFO2       bmpinfo;
377         unsigned char    *pchPixBuf;
378         unsigned char    *pchTarget;
379         ULONG            *pulSource;
380         ULONG             ulX;
381         ULONG             ulY;
382         ULONG             ulPad;
383
384         /* Set up the bitmap header, but this time for 24bit depth. */
385         bmpinfo = surface->bitmap_info;
386         bmpinfo.cBitCount = 24;
387
388         /* The start of each row has to be DWORD aligned.  Calculate the
389          * of number aligned bytes per row, the total size of the bitmap,
390          * and the number of padding bytes at the end of each row.
391          */
392         ulX = (((bmpinfo.cx * bmpinfo.cBitCount) + 31) / 32) * 4;
393         bmpinfo.cbImage = ulX * bmpinfo.cy;
394         ulPad = ulX - bmpinfo.cx * 3;
395
396         /* Allocate temporary pixel buffer.  If the rows don't need
397          * padding, it has to be 1 byte larger than the size of the
398          * bitmap  or else the high-order byte from the last source
399          * row will end up in unallocated memory.
400          */
401         pchPixBuf = (unsigned char *)_buffer_alloc (1, 1,
402                                         bmpinfo.cbImage + (ulPad ? 0 : 1));
403
404         if (pchPixBuf) {
405             /* Copy 4 bytes from the source but advance the target ptr only
406              * 3 bytes, so the high-order alpha byte will be overwritten by
407              * the next copy. At the end of each row, skip over the padding.
408              */
409             pchTarget = pchPixBuf;
410             pulSource = (ULONG*)surface->pixels;
411             for (ulY = bmpinfo.cy; ulY; ulY--) {
412                 for (ulX = bmpinfo.cx; ulX; ulX--) {
413                     *((ULONG*)pchTarget) = *pulSource++;
414                     pchTarget += 3;
415                 }
416                 pchTarget += ulPad;
417             }
418
419             rc = GpiDrawBits (hps_begin_paint,
420                               pchPixBuf,
421                               &bmpinfo,
422                               4,
423                               aptlPoints,
424                               ROP_SRCCOPY,
425                               BBO_IGNORE);
426             if (rc != GPI_OK)
427                 surface->use_24bpp = FALSE;
428
429             _buffer_free (pchPixBuf);
430         }
431     }
432
433     /* Restore Y inversion */
434     GpiEnableYInversion (hps_begin_paint, lOldYInversion);
435 }
436
437 static void
438 _cairo_os2_surface_get_pixels_from_screen (cairo_os2_surface_t *surface,
439                                            HPS                  hps_begin_paint,
440                                            PRECTL               prcl_begin_paint_rect)
441 {
442     HPS hps;
443     HDC hdc;
444     SIZEL sizlTemp;
445     HBITMAP hbmpTemp;
446     BITMAPINFO2 bmi2Temp;
447     POINTL aptlPoints[4];
448     int y;
449     unsigned char *pchTemp;
450
451     /* To copy pixels from screen to our buffer, we do the following steps:
452      *
453      * - Blit pixels from screen to a HBITMAP:
454      *   -- Create Memory Device Context
455      *   -- Create a PS into it
456      *   -- Create a HBITMAP
457      *   -- Select HBITMAP into memory PS
458      *   -- Blit dirty pixels from screen to HBITMAP
459      * - Copy HBITMAP lines (pixels) into our buffer
460      * - Free resources
461      */
462
463     /* Create a memory device context */
464     hdc = DevOpenDC (0, OD_MEMORY,"*",0L, NULL, NULLHANDLE);
465     if (!hdc) {
466         return;
467     }
468
469     /* Create a memory PS */
470     sizlTemp.cx = prcl_begin_paint_rect->xRight - prcl_begin_paint_rect->xLeft;
471     sizlTemp.cy = prcl_begin_paint_rect->yTop - prcl_begin_paint_rect->yBottom;
472     hps = GpiCreatePS (0,
473                        hdc,
474                        &sizlTemp,
475                        PU_PELS | GPIT_NORMAL | GPIA_ASSOC);
476     if (!hps) {
477         DevCloseDC (hdc);
478         return;
479     }
480
481     /* Create an uninitialized bitmap. */
482     /* Prepare BITMAPINFO2 structure for our buffer */
483     memset (&bmi2Temp, 0, sizeof (bmi2Temp));
484     bmi2Temp.cbFix = sizeof (BITMAPINFOHEADER2);
485     bmi2Temp.cx = sizlTemp.cx;
486     bmi2Temp.cy = sizlTemp.cy;
487     bmi2Temp.cPlanes = 1;
488     bmi2Temp.cBitCount = 32;
489
490     hbmpTemp = GpiCreateBitmap (hps,
491                                 (PBITMAPINFOHEADER2) &bmi2Temp,
492                                 0,
493                                 NULL,
494                                 NULL);
495
496     if (!hbmpTemp) {
497         GpiDestroyPS (hps);
498         DevCloseDC (hdc);
499         return;
500     }
501
502     /* Select the bitmap into the memory device context. */
503     GpiSetBitmap (hps, hbmpTemp);
504
505     /* Target coordinates (Noninclusive) */
506     aptlPoints[0].x = 0;
507     aptlPoints[0].y = 0;
508
509     aptlPoints[1].x = sizlTemp.cx;
510     aptlPoints[1].y = sizlTemp.cy;
511
512     /* Source coordinates (Inclusive) */
513     aptlPoints[2].x = prcl_begin_paint_rect->xLeft;
514     aptlPoints[2].y = surface->bitmap_info.cy - prcl_begin_paint_rect->yBottom;
515
516     aptlPoints[3].x = prcl_begin_paint_rect->xRight;
517     aptlPoints[3].y = surface->bitmap_info.cy - prcl_begin_paint_rect->yTop;
518
519     /* Blit pixels from screen to bitmap */
520     GpiBitBlt (hps,
521                hps_begin_paint,
522                4,
523                aptlPoints,
524                ROP_SRCCOPY,
525                BBO_IGNORE);
526
527     /* Now we have to extract the pixels from the bitmap. */
528     pchTemp =
529         surface->pixels +
530         (prcl_begin_paint_rect->yBottom)*surface->bitmap_info.cx*4 +
531         prcl_begin_paint_rect->xLeft*4;
532     for (y = 0; y < sizlTemp.cy; y++) {
533         /* Get one line of pixels */
534         GpiQueryBitmapBits (hps,
535                             sizlTemp.cy - y - 1, /* lScanStart */
536                             1,                   /* lScans */
537                             (PBYTE)pchTemp,
538                             &bmi2Temp);
539
540         /* Go for next line */
541         pchTemp += surface->bitmap_info.cx*4;
542     }
543
544     /* Clean up resources */
545     GpiSetBitmap (hps, (HBITMAP) NULL);
546     GpiDeleteBitmap (hbmpTemp);
547     GpiDestroyPS (hps);
548     DevCloseDC (hdc);
549 }
550
551 static cairo_status_t
552 _cairo_os2_surface_acquire_source_image (void                   *abstract_surface,
553                                          cairo_image_surface_t **image_out,
554                                          void                  **image_extra)
555 {
556     cairo_os2_surface_t *surface = (cairo_os2_surface_t *) abstract_surface;
557
558     DosRequestMutexSem (surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT);
559
560     /* Increase lend counter */
561     surface->pixel_array_lend_count++;
562
563     *image_out = surface->image_surface;
564     *image_extra = NULL;
565
566     DosReleaseMutexSem (surface->hmtx_use_private_fields);
567
568     return CAIRO_STATUS_SUCCESS;
569 }
570
571 static void
572 _cairo_os2_surface_release_source_image (void                  *abstract_surface,
573                                          cairo_image_surface_t *image,
574                                          void                  *image_extra)
575 {
576     cairo_os2_surface_t *surface = (cairo_os2_surface_t *) abstract_surface;
577
578     /* Decrease Lend counter! */
579     DosRequestMutexSem (surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT);
580
581     if (surface->pixel_array_lend_count > 0)
582         surface->pixel_array_lend_count--;
583     DosPostEventSem (surface->hev_pixel_array_came_back);
584
585     DosReleaseMutexSem (surface->hmtx_use_private_fields);
586 }
587
588 static cairo_surface_t *
589 _cairo_os2_surface_map_to_image (void *abstract_surface,
590                                  const cairo_rectangle_int_t *extents)
591 {
592     cairo_os2_surface_t *surface = (cairo_os2_surface_t *) abstract_surface;
593
594     DosRequestMutexSem (surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT);
595     /* Increase lend counter */
596     surface->pixel_array_lend_count++;
597     DosReleaseMutexSem (local_os2_surface->hmtx_use_private_fields);
598
599     *image_out = _cairo_surface_create_for_rectangle_int (surface->image_surface,
600                                                           extents);
601
602     return CAIRO_STATUS_SUCCESS;
603 }
604
605 static cairo_int_status_t
606 _cairo_os2_surface_unmap_image (void *abstract_surface,
607                                 cairo_image_surface_t *image)
608 {
609     cairo_os2_surface_t *surface = (cairo_os2_surface_t *) abstract_surface;
610
611     /* So, we got back the image, and if all goes well, then
612      * something has been changed inside the interest_rect.
613      * So, we blit it to the screen!
614      */
615     if (surface->blit_as_changes) {
616         RECTL rclToBlit;
617
618         /* Get mutex, we'll work with the pixel array! */
619         if (DosRequestMutexSem (surface->hmtx_use_private_fields,
620                                 SEM_INDEFINITE_WAIT) != NO_ERROR)
621         {
622             /* Could not get mutex! */
623             return;
624         }
625
626         rclToBlit.xLeft = image->base.device_transform_inverse.x0;
627         rclToBlit.xRight = rclToBlit.xLeft + image->width; /* Noninclusive */
628         rclToBlit.yTop = image->base.device_transform_inverse.y0;
629         rclToBlit.yBottom = rclToBlit.yTop + image->height; /* Noninclusive */
630
631         if (surface->hwnd_client_window) {
632             /* We know the HWND, so let's invalidate the window region,
633              * so the application will redraw itself, using the
634              * cairo_os2_surface_refresh_window () API from its own PM thread.
635              *
636              * This is the safe method, which should be preferred every time.
637              */
638             rclToBlit.yTop = surface->bitmap_info.cy - rclToBlit.yTop;
639             rclToBlit.yBottom = surface->bitmap_info.cy - rclToBlit.yTop;
640             WinInvalidateRect (surface->hwnd_client_window,
641                                &rclToBlit,
642                                FALSE);
643         } else {
644             /* We don't know the HWND, so try to blit the pixels from here!
645              * Please note that it can be problematic if this is not the PM thread!
646              *
647              * It can cause internal PM stuffs to be screwed up, for some reason.
648              * Please always tell the HWND to the surface using the
649              * cairo_os2_surface_set_hwnd () API, and call cairo_os2_surface_refresh_window ()
650              * from your WM_PAINT, if it's possible!
651              */
652             _cairo_os2_surface_blit_pixels (surface,
653                                             surface->hps_client_window,
654                                             &rclToBlit);
655         }
656
657         DosReleaseMutexSem (surface->hmtx_use_private_fields);
658     }
659     /* Also decrease Lend counter! */
660     DosRequestMutexSem (surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT);
661
662     if (surface->pixel_array_lend_count > 0)
663         surface->pixel_array_lend_count--;
664     DosPostEventSem (surface->hev_pixel_array_came_back);
665
666     DosReleaseMutexSem (surface->hmtx_use_private_fields);
667 }
668
669 static cairo_bool_t
670 _cairo_os2_surface_get_extents (void                    *abstract_surface,
671                                 cairo_rectangle_int_t   *rectangle)
672 {
673     cairo_os2_surface_t *surface = (cairo_os2_surface_t *) abstract_surface;
674
675     rectangle->x = 0;
676     rectangle->y = 0;
677     rectangle->width  = surface->bitmap_info.cx;
678     rectangle->height = surface->bitmap_info.cy;
679
680     return TRUE;
681 }
682
683 /**
684  * cairo_os2_surface_create:
685  * @hps_client_window: the presentation handle to bind the surface to
686  * @width: the width of the surface
687  * @height: the height of the surface
688  *
689  * Create a Cairo surface which is bound to a given presentation space (HPS).
690  * The caller retains ownership of the HPS and must dispose of it after the
691  * the surface has been destroyed.  The surface will be created to have the
692  * given size. By default every change to the surface will be made visible
693  * immediately by blitting it into the window. This can be changed with
694  * cairo_os2_surface_set_manual_window_refresh().
695  * Note that the surface will contain garbage when created, so the pixels
696  * have to be initialized by hand first. You can use the Cairo functions to
697  * fill it with black, or use cairo_surface_mark_dirty() to fill the surface
698  * with pixels from the window/HPS.
699  *
700  * Return value: the newly created surface
701  *
702  * Since: 1.4
703  **/
704 cairo_surface_t *
705 cairo_os2_surface_create (HPS hps_client_window,
706                           int width,
707                           int height)
708 {
709     cairo_os2_surface_t *local_os2_surface = 0;
710     cairo_status_t status;
711     int rc;
712
713     /* Check the size of the window */
714     if ((width <= 0) || (height <= 0)) {
715         status = _cairo_error (CAIRO_STATUS_INVALID_SIZE);
716         goto error_exit;
717     }
718
719     /* Allocate an OS/2 surface structure. */
720     local_os2_surface = (cairo_os2_surface_t *) malloc (sizeof (cairo_os2_surface_t));
721     if (!local_os2_surface) {
722         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
723         goto error_exit;
724     }
725
726     memset(local_os2_surface, 0, sizeof(cairo_os2_surface_t));
727
728     /* Allocate resources:  mutex & event semaphores and the pixel buffer */
729     if (DosCreateMutexSem (NULL,
730                            &(local_os2_surface->hmtx_use_private_fields),
731                            0,
732                            FALSE))
733     {
734         status = _cairo_error (CAIRO_STATUS_DEVICE_ERROR);
735         goto error_exit;
736     }
737
738     if (DosCreateEventSem (NULL,
739                            &(local_os2_surface->hev_pixel_array_came_back),
740                            0,
741                            FALSE))
742     {
743         status = _cairo_error (CAIRO_STATUS_DEVICE_ERROR);
744         goto error_exit;
745     }
746
747     local_os2_surface->pixels = (unsigned char *) _buffer_alloc (height, width, 4);
748     if (!local_os2_surface->pixels) {
749         status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
750         goto error_exit;
751     }
752
753     /* Create image surface from pixel array */
754     local_os2_surface->image_surface = (cairo_image_surface_t *)
755         cairo_image_surface_create_for_data (local_os2_surface->pixels,
756                                              CAIRO_FORMAT_ARGB32,
757                                              width,      /* Width */
758                                              height,     /* Height */
759                                              width * 4); /* Rowstride */
760     status = local_os2_surface->image_surface->base.status;
761     if (status)
762         goto error_exit;
763
764     /* Set values for OS/2-specific data that aren't zero/NULL/FALSE.
765      * Note: hps_client_window may be null if this was called by
766      * cairo_os2_surface_create_for_window().
767      */
768     local_os2_surface->hps_client_window = hps_client_window;
769     local_os2_surface->blit_as_changes = TRUE;
770
771     /* Prepare BITMAPINFO2 structure for our buffer */
772     local_os2_surface->bitmap_info.cbFix = sizeof (BITMAPINFOHEADER2);
773     local_os2_surface->bitmap_info.cx = width;
774     local_os2_surface->bitmap_info.cy = height;
775     local_os2_surface->bitmap_info.cPlanes = 1;
776     local_os2_surface->bitmap_info.cBitCount = 32;
777
778     /* Initialize base surface */
779     _cairo_surface_init (&local_os2_surface->base,
780                          &cairo_os2_surface_backend,
781                          NULL, /* device */
782                          _cairo_content_from_format (CAIRO_FORMAT_ARGB32));
783
784     /* Successful exit */
785     return (cairo_surface_t *)local_os2_surface;
786
787  error_exit:
788
789     /* This point will only be reached if an error occurred */
790
791     if (local_os2_surface) {
792         if (local_os2_surface->pixels)
793             _buffer_free (local_os2_surface->pixels);
794         if (local_os2_surface->hev_pixel_array_came_back)
795             DosCloseEventSem (local_os2_surface->hev_pixel_array_came_back);
796         if (local_os2_surface->hmtx_use_private_fields)
797             DosCloseMutexSem (local_os2_surface->hmtx_use_private_fields);
798         free (local_os2_surface);
799     }
800
801     return _cairo_surface_create_in_error (status);
802 }
803
804 /**
805  * cairo_os2_surface_create_for_window:
806  * @hwnd_client_window: the window handle to bind the surface to
807  * @width: the width of the surface
808  * @height: the height of the surface
809  *
810  * Create a Cairo surface which is bound to a given window; the caller retains
811  * ownership of the window.  This is a convenience function for use with
812  * windows that will only be updated when cairo_os2_surface_refresh_window()
813  * is called (usually in response to a WM_PAINT message).  It avoids the need
814  * to create a persistent HPS for every window and assumes that one will be
815  * supplied by the caller when a cairo function needs one.  If it isn't, an
816  * HPS will be created on-the-fly and released before the function which needs
817  * it returns.
818  *
819  * Return value: the newly created surface
820  *
821  * Since: 1.10
822  **/
823 cairo_surface_t *
824 cairo_os2_surface_create_for_window (HWND hwnd_client_window,
825                                      int width,
826                                      int height)
827 {
828     cairo_os2_surface_t *local_os2_surface;
829
830     /* A window handle must be provided. */
831     if (!hwnd_client_window) {
832         return _cairo_surface_create_in_error (
833                                 _cairo_error (CAIRO_STATUS_NO_MEMORY));
834     }
835
836     /* Create the surface. */
837     local_os2_surface = (cairo_os2_surface_t *)
838         cairo_os2_surface_create (0, width, height);
839
840     /* If successful, save the hwnd & turn off automatic repainting. */
841     if (!local_os2_surface->image_surface->base.status) {
842         local_os2_surface->hwnd_client_window = hwnd_client_window;
843         local_os2_surface->blit_as_changes = FALSE;
844     }
845
846     return (cairo_surface_t *)local_os2_surface;
847 }
848
849 /**
850  * cairo_os2_surface_set_size:
851  * @surface: the cairo surface to resize
852  * @new_width: the new width of the surface
853  * @new_height: the new height of the surface
854  * @timeout: timeout value in milliseconds
855  *
856  * When the client window is resized, call this API to set the new size in the
857  * underlying surface accordingly. This function will reallocate everything,
858  * so you'll have to redraw everything in the surface after this call.
859  * The surface will contain garbage after the resizing. So the notes of
860  * cairo_os2_surface_create() apply here, too.
861  *
862  * The timeout value specifies how long the function should wait on other parts
863  * of the program to release the buffers. It is necessary, because it can happen
864  * that Cairo is just drawing something into the surface while we want to
865  * destroy and recreate it.
866  *
867  * Return value: %CAIRO_STATUS_SUCCESS if the surface could be resized,
868  * %CAIRO_STATUS_SURFACE_TYPE_MISMATCH if the surface is not an OS/2 surface,
869  * %CAIRO_STATUS_INVALID_SIZE for invalid sizes
870  * %CAIRO_STATUS_NO_MEMORY if the new size could not be allocated, or if the
871  * timeout happened before all the buffers were released
872  *
873  * Since: 1.4
874  **/
875 int
876 cairo_os2_surface_set_size (cairo_surface_t *surface,
877                             int              new_width,
878                             int              new_height,
879                             int              timeout)
880 {
881     cairo_os2_surface_t *local_os2_surface;
882     unsigned char *pchNewPixels;
883     int rc;
884     cairo_image_surface_t *pNewImageSurface;
885
886     local_os2_surface = (cairo_os2_surface_t *) surface;
887     if ((!local_os2_surface) ||
888         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
889     {
890         /* Invalid parameter (wrong surface)! */
891         return _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
892     }
893
894     if ((new_width <= 0) ||
895         (new_height <= 0))
896     {
897         /* Invalid size! */
898         return _cairo_error (CAIRO_STATUS_INVALID_SIZE);
899     }
900
901     /* Allocate memory for new stuffs */
902     pchNewPixels = (unsigned char *) _buffer_alloc (new_height, new_width, 4);
903     if (!pchNewPixels) {
904         /* Not enough memory for the pixels!
905          * Everything remains the same!
906          */
907         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
908     }
909
910     /* Create image surface from new pixel array */
911     pNewImageSurface = (cairo_image_surface_t *)
912         cairo_image_surface_create_for_data (pchNewPixels,
913                                              CAIRO_FORMAT_ARGB32,
914                                              new_width,      /* Width */
915                                              new_height,     /* Height */
916                                              new_width * 4); /* Rowstride */
917
918     if (pNewImageSurface->base.status) {
919         /* Could not create image surface!
920          * Everything remains the same!
921          */
922         _buffer_free (pchNewPixels);
923         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
924     }
925
926     /* Okay, new memory allocated, so it's time to swap old buffers
927      * to new ones!
928      */
929     if (DosRequestMutexSem (local_os2_surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT)!=NO_ERROR) {
930         /* Could not get mutex!
931          * Everything remains the same!
932          */
933         cairo_surface_destroy ((cairo_surface_t *) pNewImageSurface);
934         _buffer_free (pchNewPixels);
935         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
936     }
937
938     /* We have to make sure that we won't destroy a surface which
939      * is lent to some other code (Cairo is drawing into it)!
940      */
941     while (local_os2_surface->pixel_array_lend_count > 0) {
942         ULONG ulPostCount;
943         DosResetEventSem (local_os2_surface->hev_pixel_array_came_back, &ulPostCount);
944         DosReleaseMutexSem (local_os2_surface->hmtx_use_private_fields);
945         /* Wait for somebody to return the pixels! */
946         rc = DosWaitEventSem (local_os2_surface->hev_pixel_array_came_back, timeout);
947         if (rc != NO_ERROR) {
948             /* Either timeout or something wrong... Exit. */
949             cairo_surface_destroy ((cairo_surface_t *) pNewImageSurface);
950             _buffer_free (pchNewPixels);
951             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
952         }
953         /* Okay, grab mutex and check counter again! */
954         if (DosRequestMutexSem (local_os2_surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT)
955             != NO_ERROR)
956         {
957             /* Could not get mutex!
958              * Everything remains the same!
959              */
960             cairo_surface_destroy ((cairo_surface_t *) pNewImageSurface);
961             _buffer_free (pchNewPixels);
962             return _cairo_error (CAIRO_STATUS_NO_MEMORY);
963         }
964     }
965
966     /* Destroy old image surface */
967     cairo_surface_destroy ((cairo_surface_t *) (local_os2_surface->image_surface));
968     /* Destroy old pixel buffer */
969     _buffer_free (local_os2_surface->pixels);
970     /* Set new image surface */
971     local_os2_surface->image_surface = pNewImageSurface;
972     /* Set new pixel buffer */
973     local_os2_surface->pixels = pchNewPixels;
974     /* Change bitmap2 structure */
975     local_os2_surface->bitmap_info.cx = new_width;
976     local_os2_surface->bitmap_info.cy = new_height;
977
978     DosReleaseMutexSem (local_os2_surface->hmtx_use_private_fields);
979     return CAIRO_STATUS_SUCCESS;
980 }
981
982 /**
983  * cairo_os2_surface_refresh_window:
984  * @surface: the cairo surface to refresh
985  * @hps_begin_paint: the presentation handle of the window to refresh
986  * @prcl_begin_paint_rect: the rectangle to redraw
987  *
988  * This function can be used to force a repaint of a given area of the client
989  * window. It should usually be called from the WM_PAINT processing of the
990  * window procedure. However, it can be called any time a given part of the
991  * window has to be updated.
992  *
993  * The HPS and RECTL to be passed can be taken from the usual WinBeginPaint call
994  * of the window procedure, but you can also get the HPS using WinGetPS, and you
995  * can assemble your own update rectangle by hand.
996  * If hps_begin_paint is %NULL, the function will use the HPS passed into
997  * cairo_os2_surface_create(). If @prcl_begin_paint_rect is %NULL, the function
998  * will query the current window size and repaint the whole window.
999  *
1000  * Cairo assumes that if you set the HWND to the surface using
1001  * cairo_os2_surface_set_hwnd(), this function will be called by the application
1002  * every time it gets a WM_PAINT for that HWND. If the HWND is set in the
1003  * surface, Cairo uses this function to handle dirty areas too.
1004  *
1005  * Since: 1.4
1006  **/
1007 void
1008 cairo_os2_surface_refresh_window (cairo_surface_t *surface,
1009                                   HPS              hps_begin_paint,
1010                                   PRECTL           prcl_begin_paint_rect)
1011 {
1012     cairo_os2_surface_t *local_os2_surface;
1013     RECTL rclTemp;
1014     HPS hpsTemp = 0;
1015
1016     local_os2_surface = (cairo_os2_surface_t *) surface;
1017     if ((!local_os2_surface) ||
1018         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1019     {
1020         /* Invalid parameter (wrong surface)! */
1021         return;
1022     }
1023
1024     /* If an HPS wasn't provided, see if we can get one. */
1025     if (!hps_begin_paint) {
1026         hps_begin_paint = local_os2_surface->hps_client_window;
1027         if (!hps_begin_paint) {
1028             if (local_os2_surface->hwnd_client_window) {
1029                 hpsTemp = WinGetPS(local_os2_surface->hwnd_client_window);
1030                 hps_begin_paint = hpsTemp;
1031             }
1032             /* No HPS & no way to get one, so exit */
1033             if (!hps_begin_paint)
1034                 return;
1035         }
1036     }
1037
1038     if (prcl_begin_paint_rect == NULL) {
1039         /* Update the whole window! */
1040         rclTemp.xLeft = 0;
1041         rclTemp.xRight = local_os2_surface->bitmap_info.cx;
1042         rclTemp.yTop = local_os2_surface->bitmap_info.cy;
1043         rclTemp.yBottom = 0;
1044     } else {
1045         /* Use the rectangle we got passed as parameter! */
1046         rclTemp.xLeft = prcl_begin_paint_rect->xLeft;
1047         rclTemp.xRight = prcl_begin_paint_rect->xRight;
1048         rclTemp.yTop = local_os2_surface->bitmap_info.cy - prcl_begin_paint_rect->yBottom;
1049         rclTemp.yBottom = local_os2_surface->bitmap_info.cy - prcl_begin_paint_rect->yTop ;
1050     }
1051
1052     /* Get mutex, we'll work with the pixel array! */
1053     if (DosRequestMutexSem (local_os2_surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT)
1054         != NO_ERROR)
1055     {
1056         /* Could not get mutex! */
1057         if (hpsTemp)
1058             WinReleasePS(hpsTemp);
1059         return;
1060     }
1061
1062     if ((local_os2_surface->dirty_area_present) &&
1063         (local_os2_surface->rcl_dirty_area.xLeft == rclTemp.xLeft) &&
1064         (local_os2_surface->rcl_dirty_area.xRight == rclTemp.xRight) &&
1065         (local_os2_surface->rcl_dirty_area.yTop == rclTemp.yTop) &&
1066         (local_os2_surface->rcl_dirty_area.yBottom == rclTemp.yBottom))
1067     {
1068         /* Aha, this call was because of a dirty area, so in this case we
1069          * have to blit the pixels from the screen to the surface!
1070          */
1071         local_os2_surface->dirty_area_present = FALSE;
1072         _cairo_os2_surface_get_pixels_from_screen (local_os2_surface,
1073                                                    hps_begin_paint,
1074                                                    &rclTemp);
1075     } else {
1076         /* Okay, we have the surface, have the HPS
1077          * (might be from WinBeginPaint () or from WinGetPS () )
1078          * Now blit there the stuffs!
1079          */
1080         _cairo_os2_surface_blit_pixels (local_os2_surface,
1081                                         hps_begin_paint,
1082                                         &rclTemp);
1083     }
1084
1085     DosReleaseMutexSem (local_os2_surface->hmtx_use_private_fields);
1086
1087     if (hpsTemp)
1088         WinReleasePS(hpsTemp);
1089 }
1090
1091 static cairo_status_t
1092 _cairo_os2_surface_finish (void *abstract_surface)
1093 {
1094     cairo_os2_surface_t *local_os2_surface;
1095
1096     local_os2_surface = (cairo_os2_surface_t *) abstract_surface;
1097     if ((!local_os2_surface) ||
1098         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1099     {
1100         /* Invalid parameter (wrong surface)! */
1101         return _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1102     }
1103
1104     DosRequestMutexSem (local_os2_surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT);
1105
1106     /* Destroy old image surface */
1107     cairo_surface_destroy ((cairo_surface_t *) (local_os2_surface->image_surface));
1108     /* Destroy old pixel buffer */
1109     _buffer_free (local_os2_surface->pixels);
1110     DosCloseMutexSem (local_os2_surface->hmtx_use_private_fields);
1111     DosCloseEventSem (local_os2_surface->hev_pixel_array_came_back);
1112
1113     /* The memory itself will be free'd by the cairo_surface_destroy ()
1114      * who called us.
1115      */
1116
1117     return CAIRO_STATUS_SUCCESS;
1118 }
1119
1120 /**
1121  * cairo_os2_surface_set_hwnd:
1122  * @surface: the cairo surface to associate with the window handle
1123  * @hwnd_client_window: the window handle of the client window
1124  *
1125  * Sets window handle for surface; the caller retains ownership of the window.
1126  * If Cairo wants to blit into the window because it is set to blit as the
1127  * surface changes (see cairo_os2_surface_set_manual_window_refresh()), then
1128  * there are two ways it can choose:
1129  * If it knows the HWND of the surface, then it invalidates that area, so the
1130  * application will get a WM_PAINT message and it can call
1131  * cairo_os2_surface_refresh_window() to redraw that area. Otherwise cairo itself
1132  * will use the HPS it got at surface creation time, and blit the pixels itself.
1133  * It's also a solution, but experience shows that if this happens from a non-PM
1134  * thread, then it can screw up PM internals.
1135  *
1136  * So, best solution is to set the HWND for the surface after the surface
1137  * creation, so every blit will be done from application's message processing
1138  * loop, which is the safest way to do.
1139  *
1140  * Since: 1.4
1141  **/
1142 void
1143 cairo_os2_surface_set_hwnd (cairo_surface_t *surface,
1144                             HWND             hwnd_client_window)
1145 {
1146     cairo_os2_surface_t *local_os2_surface;
1147
1148     local_os2_surface = (cairo_os2_surface_t *) surface;
1149     if ((!local_os2_surface) ||
1150         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1151     {
1152         /* Invalid parameter (wrong surface)! */
1153         return;
1154     }
1155
1156     if (DosRequestMutexSem (local_os2_surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT)
1157         != NO_ERROR)
1158     {
1159         /* Could not get mutex! */
1160         return;
1161     }
1162
1163     local_os2_surface->hwnd_client_window = hwnd_client_window;
1164
1165     DosReleaseMutexSem (local_os2_surface->hmtx_use_private_fields);
1166 }
1167
1168 /**
1169  * cairo_os2_surface_set_manual_window_refresh:
1170  * @surface: the cairo surface to set the refresh mode for
1171  * @manual_refresh: the switch for manual surface refresh
1172  *
1173  * This API can tell Cairo if it should show every change to this surface
1174  * immediately in the window or if it should be cached and will only be visible
1175  * once the user calls cairo_os2_surface_refresh_window() explicitly. If the
1176  * HWND was not set in the cairo surface, then the HPS will be used to blit the
1177  * graphics. Otherwise it will invalidate the given window region so the user
1178  * will get the WM_PAINT message to redraw that area of the window.
1179  *
1180  * So, if you're only interested in displaying the final result after several
1181  * drawing operations, you might get better performance if you put the surface
1182  * into manual refresh mode by passing a true value to this function. Then call
1183  * cairo_os2_surface_refresh() whenever desired.
1184  *
1185  * Since: 1.4
1186  **/
1187 void
1188 cairo_os2_surface_set_manual_window_refresh (cairo_surface_t *surface,
1189                                              cairo_bool_t     manual_refresh)
1190 {
1191     cairo_os2_surface_t *local_os2_surface;
1192
1193     local_os2_surface = (cairo_os2_surface_t *) surface;
1194     if ((!local_os2_surface) ||
1195         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1196     {
1197         /* Invalid parameter (wrong surface)! */
1198         return;
1199     }
1200
1201     local_os2_surface->blit_as_changes = !manual_refresh;
1202 }
1203
1204 /**
1205  * cairo_os2_surface_get_manual_window_refresh:
1206  * @surface: the cairo surface to query the refresh mode from
1207  *
1208  * This space left intentionally blank.
1209  *
1210  * Return value: current refresh mode of the surface (true by default)
1211  *
1212  * Since: 1.4
1213  **/
1214 cairo_bool_t
1215 cairo_os2_surface_get_manual_window_refresh (cairo_surface_t *surface)
1216 {
1217     cairo_os2_surface_t *local_os2_surface;
1218
1219     local_os2_surface = (cairo_os2_surface_t *) surface;
1220     if ((!local_os2_surface) ||
1221         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1222     {
1223         /* Invalid parameter (wrong surface)! */
1224         return FALSE;
1225     }
1226
1227     return !(local_os2_surface->blit_as_changes);
1228 }
1229
1230 /**
1231  * cairo_os2_surface_get_hps:
1232  * @surface: the cairo surface to be querued
1233  * @hps: HPS currently associated with the surface (if any)
1234  *
1235  * This API retrieves the HPS associated with the surface.
1236  *
1237  * Return value: %CAIRO_STATUS_SUCCESS if the hps could be retrieved,
1238  * %CAIRO_STATUS_SURFACE_TYPE_MISMATCH if the surface is not an OS/2 surface,
1239  * %CAIRO_STATUS_NULL_POINTER if the hps argument is null
1240  *
1241  * Since: 1.10
1242  **/
1243 cairo_status_t
1244 cairo_os2_surface_get_hps (cairo_surface_t *surface,
1245                            HPS             *hps)
1246 {
1247     cairo_os2_surface_t *local_os2_surface;
1248
1249     local_os2_surface = (cairo_os2_surface_t *) surface;
1250     if ((!local_os2_surface) ||
1251         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1252     {
1253         /* Invalid parameter (wrong surface)! */
1254         return _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1255     }
1256     if (!hps)
1257     {
1258         return _cairo_error (CAIRO_STATUS_NULL_POINTER);
1259     }
1260     *hps = local_os2_surface->hps_client_window;
1261
1262     return CAIRO_STATUS_SUCCESS;
1263 }
1264
1265 /**
1266  * cairo_os2_surface_set_hps:
1267  * @surface: the cairo surface to associate with the HPS
1268  * @hps: new HPS to be associated with the surface (the HPS may be null)
1269  *
1270  * This API replaces the HPS associated with the surface with a new one.
1271  * The caller retains ownership of the HPS and must dispose of it after
1272  * the surface has been destroyed or it has been replaced by another
1273  * call to this function.
1274  *
1275  * Return value: %CAIRO_STATUS_SUCCESS if the hps could be replaced,
1276  * %CAIRO_STATUS_SURFACE_TYPE_MISMATCH if the surface is not an OS/2 surface,
1277  *
1278  * Since: 1.10
1279  **/
1280 cairo_status_t
1281 cairo_os2_surface_set_hps (cairo_surface_t *surface,
1282                            HPS              hps)
1283 {
1284     cairo_os2_surface_t *local_os2_surface;
1285
1286     local_os2_surface = (cairo_os2_surface_t *) surface;
1287     if ((!local_os2_surface) ||
1288         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1289     {
1290         /* Invalid parameter (wrong surface)! */
1291         return _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1292     }
1293     local_os2_surface->hps_client_window = hps;
1294
1295     return CAIRO_STATUS_SUCCESS;
1296 }
1297
1298 static cairo_status_t
1299 _cairo_os2_surface_mark_dirty_rectangle (void *surface,
1300                                          int   x,
1301                                          int   y,
1302                                          int   width,
1303                                          int   height)
1304 {
1305     cairo_os2_surface_t *local_os2_surface;
1306     RECTL rclToBlit;
1307
1308     local_os2_surface = (cairo_os2_surface_t *) surface;
1309     if ((!local_os2_surface) ||
1310         (local_os2_surface->base.backend != &cairo_os2_surface_backend))
1311     {
1312         /* Invalid parameter (wrong surface)! */
1313         return _cairo_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
1314     }
1315
1316     /* Get mutex, we'll work with the pixel array! */
1317     if (DosRequestMutexSem (local_os2_surface->hmtx_use_private_fields, SEM_INDEFINITE_WAIT)
1318         != NO_ERROR)
1319     {
1320         /* Could not get mutex! */
1321         return CAIRO_STATUS_NO_MEMORY;
1322     }
1323
1324     /* Check for defaults */
1325     if (width < 0)
1326         width = local_os2_surface->bitmap_info.cx;
1327     if (height < 0)
1328         height = local_os2_surface->bitmap_info.cy;
1329
1330     if (local_os2_surface->hwnd_client_window) {
1331         /* We know the HWND, so let's invalidate the window region,
1332          * so the application will redraw itself, using the
1333          * cairo_os2_surface_refresh_window () API from its own PM thread.
1334          * From that function we'll note that it's not a redraw but a
1335          * dirty-rectangle deal stuff, so we'll handle the things from
1336          * there.
1337          *
1338          * This is the safe method, which should be preferred every time.
1339          */
1340         rclToBlit.xLeft = x;
1341         rclToBlit.xRight = x + width; /* Noninclusive */
1342         rclToBlit.yTop = local_os2_surface->bitmap_info.cy - (y);
1343         rclToBlit.yBottom = local_os2_surface->bitmap_info.cy - (y + height); /* Noninclusive */
1344
1345 #if 0
1346         if (local_os2_surface->dirty_area_present) {
1347             /* Yikes, there is already a dirty area which should be
1348              * cleaned up, but we'll overwrite it. Sorry.
1349              * TODO: Something clever should be done here.
1350              */
1351         }
1352 #endif
1353
1354         /* Set up dirty area reminder stuff */
1355         memcpy (&(local_os2_surface->rcl_dirty_area), &rclToBlit, sizeof (RECTL));
1356         local_os2_surface->dirty_area_present = TRUE;
1357
1358         /* Invalidate window area */
1359         WinInvalidateRect (local_os2_surface->hwnd_client_window,
1360                            &rclToBlit,
1361                            FALSE);
1362     } else {
1363         /* We don't know the HWND, so try to blit the pixels from here!
1364          * Please note that it can be problematic if this is not the PM thread!
1365          *
1366          * It can cause internal PM stuffs to be scewed up, for some reason.
1367          * Please always tell the HWND to the surface using the
1368          * cairo_os2_surface_set_hwnd () API, and call cairo_os2_surface_refresh_window ()
1369          * from your WM_PAINT, if it's possible!
1370          */
1371
1372         rclToBlit.xLeft = x;
1373         rclToBlit.xRight = x + width; /* Noninclusive */
1374         rclToBlit.yBottom = y;
1375         rclToBlit.yTop = y + height; /* Noninclusive */
1376         /* Now get the pixels from the screen! */
1377         _cairo_os2_surface_get_pixels_from_screen (local_os2_surface,
1378                                                    local_os2_surface->hps_client_window,
1379                                                    &rclToBlit);
1380     }
1381
1382     DosReleaseMutexSem (local_os2_surface->hmtx_use_private_fields);
1383
1384     return CAIRO_STATUS_SUCCESS;
1385 }
1386
1387 static const cairo_surface_backend_t cairo_os2_surface_backend = {
1388     CAIRO_SURFACE_TYPE_OS2,
1389     _cairo_os2_surface_finish,
1390     _cairo_default_context_create,
1391
1392     NULL, /* create_similar */
1393     NULL, /* create_similar_image */
1394     _cairo_os2_surface_map_to_image,
1395     _cairo_os2_surface_unmap_image,
1396
1397     _cairo_surface_default_source,
1398     _cairo_os2_surface_acquire_source_image,
1399     _cairo_os2_surface_release_source_image,
1400     NULL, /* snapshot */
1401
1402     _cairo_os2_surface_get_extents,
1403     NULL, /* get_font_options */
1404
1405     NULL, /* flush */
1406     _cairo_os2_surface_mark_dirty_rectangle,
1407
1408     _cairo_surface_fallback_paint,
1409     _cairo_surface_fallback_mask,
1410     _cairo_surface_fallback_fill,
1411     _cairo_surface_fallback_stroke,
1412     NULL, /* fill/stroke */
1413     _cairo_surface_fallback_glyphs,
1414 };