user32: Don't flush window surfaces while waiting for a sent message reply.
[wine] / dlls / user32 / painting.c
1 /*
2  * Window painting functions
3  *
4  * Copyright 1993, 1994, 1995, 2001, 2004, 2005, 2008 Alexandre Julliard
5  * Copyright 1996, 1997, 1999 Alex Korobka
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <stdarg.h>
27 #include <string.h>
28
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "wingdi.h"
34 #include "winuser.h"
35 #include "wine/server.h"
36 #include "win.h"
37 #include "user_private.h"
38 #include "controls.h"
39 #include "wine/gdi_driver.h"
40 #include "wine/list.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(win);
44
45
46 struct dce
47 {
48     struct list entry;         /* entry in global DCE list */
49     HDC         hdc;
50     HWND        hwnd;
51     HRGN        clip_rgn;
52     DWORD       flags;
53     LONG        count;         /* usage count; 0 or 1 for cache DCEs, always 1 for window DCEs,
54                                   always >= 1 for class DCEs */
55 };
56
57 static struct list dce_list = LIST_INIT(dce_list);
58
59 static BOOL CALLBACK dc_hook( HDC hDC, WORD code, DWORD_PTR data, LPARAM lParam );
60
61 static const WCHAR displayW[] = { 'D','I','S','P','L','A','Y',0 };
62
63
64 /***********************************************************************
65  *           dump_rdw_flags
66  */
67 static void dump_rdw_flags(UINT flags)
68 {
69     TRACE("flags:");
70     if (flags & RDW_INVALIDATE) TRACE(" RDW_INVALIDATE");
71     if (flags & RDW_INTERNALPAINT) TRACE(" RDW_INTERNALPAINT");
72     if (flags & RDW_ERASE) TRACE(" RDW_ERASE");
73     if (flags & RDW_VALIDATE) TRACE(" RDW_VALIDATE");
74     if (flags & RDW_NOINTERNALPAINT) TRACE(" RDW_NOINTERNALPAINT");
75     if (flags & RDW_NOERASE) TRACE(" RDW_NOERASE");
76     if (flags & RDW_NOCHILDREN) TRACE(" RDW_NOCHILDREN");
77     if (flags & RDW_ALLCHILDREN) TRACE(" RDW_ALLCHILDREN");
78     if (flags & RDW_UPDATENOW) TRACE(" RDW_UPDATENOW");
79     if (flags & RDW_ERASENOW) TRACE(" RDW_ERASENOW");
80     if (flags & RDW_FRAME) TRACE(" RDW_FRAME");
81     if (flags & RDW_NOFRAME) TRACE(" RDW_NOFRAME");
82
83 #define RDW_FLAGS \
84     (RDW_INVALIDATE | \
85     RDW_INTERNALPAINT | \
86     RDW_ERASE | \
87     RDW_VALIDATE | \
88     RDW_NOINTERNALPAINT | \
89     RDW_NOERASE | \
90     RDW_NOCHILDREN | \
91     RDW_ALLCHILDREN | \
92     RDW_UPDATENOW | \
93     RDW_ERASENOW | \
94     RDW_FRAME | \
95     RDW_NOFRAME)
96
97     if (flags & ~RDW_FLAGS) TRACE(" %04x", flags & ~RDW_FLAGS);
98     TRACE("\n");
99 #undef RDW_FLAGS
100 }
101
102
103 /***********************************************************************
104  *              update_visible_region
105  *
106  * Set the visible region and X11 drawable for the DC associated to
107  * a given window.
108  */
109 static void update_visible_region( struct dce *dce )
110 {
111     struct window_surface *surface = NULL;
112     NTSTATUS status;
113     HRGN vis_rgn = 0;
114     HWND top_win = 0;
115     DWORD flags = dce->flags;
116     size_t size = 256;
117     RECT win_rect, top_rect;
118     WND *win;
119
120     /* don't clip siblings if using parent clip region */
121     if (flags & DCX_PARENTCLIP) flags &= ~DCX_CLIPSIBLINGS;
122
123     /* fetch the visible region from the server */
124     do
125     {
126         RGNDATA *data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data) + size - 1 );
127         if (!data) return;
128
129         SERVER_START_REQ( get_visible_region )
130         {
131             req->window  = wine_server_user_handle( dce->hwnd );
132             req->flags   = flags;
133             wine_server_set_reply( req, data->Buffer, size );
134             if (!(status = wine_server_call( req )))
135             {
136                 size_t reply_size = wine_server_reply_size( reply );
137                 data->rdh.dwSize   = sizeof(data->rdh);
138                 data->rdh.iType    = RDH_RECTANGLES;
139                 data->rdh.nCount   = reply_size / sizeof(RECT);
140                 data->rdh.nRgnSize = reply_size;
141                 vis_rgn = ExtCreateRegion( NULL, size, data );
142
143                 top_win         = wine_server_ptr_handle( reply->top_win );
144                 win_rect.left   = reply->win_rect.left;
145                 win_rect.top    = reply->win_rect.top;
146                 win_rect.right  = reply->win_rect.right;
147                 win_rect.bottom = reply->win_rect.bottom;
148                 top_rect.left   = reply->top_rect.left;
149                 top_rect.top    = reply->top_rect.top;
150                 top_rect.right  = reply->top_rect.right;
151                 top_rect.bottom = reply->top_rect.bottom;
152             }
153             else size = reply->total_size;
154         }
155         SERVER_END_REQ;
156         HeapFree( GetProcessHeap(), 0, data );
157     } while (status == STATUS_BUFFER_OVERFLOW);
158
159     if (status || !vis_rgn) return;
160
161     USER_Driver->pGetDC( dce->hdc, dce->hwnd, top_win, &win_rect, &top_rect, flags );
162
163     if (dce->clip_rgn) CombineRgn( vis_rgn, vis_rgn, dce->clip_rgn,
164                                    (flags & DCX_INTERSECTRGN) ? RGN_AND : RGN_DIFF );
165
166     if ((win = WIN_GetPtr( top_win )) && win != WND_DESKTOP && win != WND_OTHER_PROCESS)
167     {
168         /* don't use a surface to paint the client area of OpenGL windows */
169         if (!win->pixel_format || (flags & DCX_WINDOW)) surface = win->surface;
170         if (surface) window_surface_add_ref( surface );
171         WIN_ReleasePtr( win );
172     }
173
174     if (!surface) top_rect = get_virtual_screen_rect();
175     __wine_set_visible_region( dce->hdc, vis_rgn, &win_rect, &top_rect, surface );
176     if (surface) window_surface_release( surface );
177 }
178
179
180 /***********************************************************************
181  *              release_dce
182  */
183 static void release_dce( struct dce *dce )
184 {
185     if (!dce->hwnd) return;  /* already released */
186
187     __wine_set_visible_region( dce->hdc, 0, &dummy_surface.rect, &dummy_surface.rect, &dummy_surface );
188     USER_Driver->pReleaseDC( dce->hwnd, dce->hdc );
189
190     if (dce->clip_rgn) DeleteObject( dce->clip_rgn );
191     dce->clip_rgn = 0;
192     dce->hwnd     = 0;
193     dce->flags   &= DCX_CACHE;
194 }
195
196
197 /***********************************************************************
198  *   delete_clip_rgn
199  */
200 static void delete_clip_rgn( struct dce *dce )
201 {
202     if (!dce->clip_rgn) return;  /* nothing to do */
203
204     dce->flags &= ~(DCX_EXCLUDERGN | DCX_INTERSECTRGN);
205     DeleteObject( dce->clip_rgn );
206     dce->clip_rgn = 0;
207
208     /* make it dirty so that the vis rgn gets recomputed next time */
209     SetHookFlags( dce->hdc, DCHF_INVALIDATEVISRGN );
210 }
211
212
213 /***********************************************************************
214  *           alloc_dce
215  *
216  * Allocate a new DCE.
217  */
218 static struct dce *alloc_dce(void)
219 {
220     struct dce *dce;
221
222     if (!(dce = HeapAlloc( GetProcessHeap(), 0, sizeof(*dce) ))) return NULL;
223     if (!(dce->hdc = CreateDCW( displayW, NULL, NULL, NULL )))
224     {
225         HeapFree( GetProcessHeap(), 0, dce );
226         return 0;
227     }
228     dce->hwnd      = 0;
229     dce->clip_rgn  = 0;
230     dce->flags     = 0;
231     dce->count     = 1;
232
233     /* store DCE handle in DC hook data field */
234     SetDCHook( dce->hdc, dc_hook, (DWORD_PTR)dce );
235     SetHookFlags( dce->hdc, DCHF_INVALIDATEVISRGN );
236     return dce;
237 }
238
239
240 /***********************************************************************
241  *              get_window_dce
242  */
243 static struct dce *get_window_dce( HWND hwnd )
244 {
245     struct dce *dce;
246     WND *win = WIN_GetPtr( hwnd );
247
248     if (!win || win == WND_OTHER_PROCESS || win == WND_DESKTOP) return NULL;
249
250     dce = win->dce;
251     if (!dce && (dce = get_class_dce( win->class )))
252     {
253         win->dce = dce;
254         dce->count++;
255     }
256     WIN_ReleasePtr( win );
257
258     if (!dce)  /* try to allocate one */
259     {
260         struct dce *dce_to_free = NULL;
261         LONG class_style = GetClassLongW( hwnd, GCL_STYLE );
262
263         if (class_style & CS_CLASSDC)
264         {
265             if (!(dce = alloc_dce())) return NULL;
266
267             win = WIN_GetPtr( hwnd );
268             if (win && win != WND_OTHER_PROCESS && win != WND_DESKTOP)
269             {
270                 if (win->dce)  /* another thread beat us to it */
271                 {
272                     dce_to_free = dce;
273                     dce = win->dce;
274                 }
275                 else if ((win->dce = set_class_dce( win->class, dce )) != dce)
276                 {
277                     dce_to_free = dce;
278                     dce = win->dce;
279                     dce->count++;
280                 }
281                 else
282                 {
283                     dce->count++;
284                     list_add_tail( &dce_list, &dce->entry );
285                 }
286                 WIN_ReleasePtr( win );
287             }
288             else dce_to_free = dce;
289         }
290         else if (class_style & CS_OWNDC)
291         {
292             if (!(dce = alloc_dce())) return NULL;
293
294             win = WIN_GetPtr( hwnd );
295             if (win && win != WND_OTHER_PROCESS && win != WND_DESKTOP)
296             {
297                 if (win->dwStyle & WS_CLIPCHILDREN) dce->flags |= DCX_CLIPCHILDREN;
298                 if (win->dwStyle & WS_CLIPSIBLINGS) dce->flags |= DCX_CLIPSIBLINGS;
299                 if (win->dce)  /* another thread beat us to it */
300                 {
301                     dce_to_free = dce;
302                     dce = win->dce;
303                 }
304                 else
305                 {
306                     win->dce = dce;
307                     dce->hwnd = hwnd;
308                     dce->count++;
309                     list_add_tail( &dce_list, &dce->entry );
310                 }
311                 WIN_ReleasePtr( win );
312             }
313             else dce_to_free = dce;
314         }
315
316         if (dce_to_free)
317         {
318             SetDCHook( dce_to_free->hdc, NULL, 0 );
319             DeleteDC( dce_to_free->hdc );
320             HeapFree( GetProcessHeap(), 0, dce_to_free );
321             if (dce_to_free == dce)
322                 dce = NULL;
323         }
324     }
325     return dce;
326 }
327
328
329 /***********************************************************************
330  *           free_dce
331  *
332  * Free a class or window DCE.
333  */
334 void free_dce( struct dce *dce, HWND hwnd )
335 {
336     USER_Lock();
337
338     if (dce)
339     {
340         if (!--dce->count)
341         {
342             /* turn it into a cache entry */
343             SetHookFlags( dce->hdc, DCHF_RESETDC );
344             release_dce( dce );
345             dce->flags |= DCX_CACHE;
346         }
347         else if (dce->hwnd == hwnd)
348         {
349             release_dce( dce );
350         }
351     }
352
353     /* now check for cache DCEs */
354
355     if (hwnd)
356     {
357         LIST_FOR_EACH_ENTRY( dce, &dce_list, struct dce, entry )
358         {
359             if (dce->hwnd != hwnd) continue;
360             if (!(dce->flags & DCX_CACHE)) continue;
361
362             if (dce->count) WARN( "GetDC() without ReleaseDC() for window %p\n", hwnd );
363             dce->count = 0;
364             release_dce( dce );
365         }
366     }
367
368     USER_Unlock();
369 }
370
371
372 /***********************************************************************
373  *           make_dc_dirty
374  *
375  * Mark the associated DC as dirty to force a refresh of the visible region
376  */
377 static void make_dc_dirty( struct dce *dce )
378 {
379     if (!dce->count)
380     {
381         /* Don't bother with visible regions of unused DCEs */
382         TRACE("\tpurged %p dce [%p]\n", dce, dce->hwnd);
383         release_dce( dce );
384     }
385     else
386     {
387         /* Set dirty bits in the hDC and DCE structs */
388         TRACE("\tfixed up %p dce [%p]\n", dce, dce->hwnd);
389         SetHookFlags( dce->hdc, DCHF_INVALIDATEVISRGN );
390     }
391 }
392
393
394 /***********************************************************************
395  *   invalidate_dce
396  *
397  * It is called from SetWindowPos() - we have to
398  * mark as dirty all busy DCEs for windows that have pWnd->parent as
399  * an ancestor and whose client rect intersects with specified update
400  * rectangle. In addition, pWnd->parent DCEs may need to be updated if
401  * DCX_CLIPCHILDREN flag is set.
402  */
403 void invalidate_dce( WND *win, const RECT *extra_rect )
404 {
405     RECT window_rect;
406     struct dce *dce;
407
408     if (!win->parent) return;
409
410     GetWindowRect( win->obj.handle, &window_rect );
411
412     TRACE("%p parent %p %s (%s)\n",
413           win->obj.handle, win->parent, wine_dbgstr_rect(&window_rect), wine_dbgstr_rect(extra_rect) );
414
415     /* walk all DCEs and fixup non-empty entries */
416
417     LIST_FOR_EACH_ENTRY( dce, &dce_list, struct dce, entry )
418     {
419         TRACE( "%p: hwnd %p dcx %08x %s %s\n", dce, dce->hwnd, dce->flags,
420                (dce->flags & DCX_CACHE) ? "Cache" : "Owned", dce->count ? "InUse" : "" );
421
422         if (!dce->hwnd) continue;
423         if ((dce->hwnd == win->parent) && !(dce->flags & DCX_CLIPCHILDREN))
424             continue;  /* child window positions don't bother us */
425
426         /* if DCE window is a child of hwnd, it has to be invalidated */
427         if (dce->hwnd == win->obj.handle || IsChild( win->obj.handle, dce->hwnd ))
428         {
429             make_dc_dirty( dce );
430             continue;
431         }
432
433         /* otherwise check if the window rectangle intersects this DCE window */
434         if (win->parent == dce->hwnd || IsChild( win->parent, dce->hwnd ))
435         {
436             RECT dce_rect, tmp;
437             GetWindowRect( dce->hwnd, &dce_rect );
438             if (IntersectRect( &tmp, &dce_rect, &window_rect ) ||
439                 (extra_rect && IntersectRect( &tmp, &dce_rect, extra_rect )))
440                 make_dc_dirty( dce );
441         }
442     }
443 }
444
445 /***********************************************************************
446  *              release_dc
447  *
448  * Implementation of ReleaseDC.
449  */
450 static INT release_dc( HWND hwnd, HDC hdc, BOOL end_paint )
451 {
452     struct dce *dce;
453     BOOL ret = FALSE;
454
455     TRACE("%p %p\n", hwnd, hdc );
456
457     USER_Lock();
458     dce = (struct dce *)GetDCHook( hdc, NULL );
459     if (dce && dce->count)
460     {
461         if (!(dce->flags & DCX_NORESETATTRS)) SetHookFlags( dce->hdc, DCHF_RESETDC );
462         if (end_paint || (dce->flags & DCX_CACHE)) delete_clip_rgn( dce );
463         if (dce->flags & DCX_CACHE) dce->count = 0;
464         ret = TRUE;
465     }
466     USER_Unlock();
467     return ret;
468 }
469
470
471 /***********************************************************************
472  *              dc_hook
473  *
474  * See "Undoc. Windows" for hints (DC, SetDCHook, SetHookFlags)..
475  */
476 static BOOL CALLBACK dc_hook( HDC hDC, WORD code, DWORD_PTR data, LPARAM lParam )
477 {
478     BOOL retv = TRUE;
479     struct dce *dce = (struct dce *)data;
480
481     TRACE("hDC = %p, %u\n", hDC, code);
482
483     if (!dce) return 0;
484     assert( dce->hdc == hDC );
485
486     switch( code )
487     {
488     case DCHC_INVALIDVISRGN:
489         /* GDI code calls this when it detects that the
490          * DC is dirty (usually after SetHookFlags()). This
491          * means that we have to recompute the visible region.
492          */
493         if (dce->count) update_visible_region( dce );
494         else /* non-fatal but shouldn't happen */
495             WARN("DC is not in use!\n");
496         break;
497     case DCHC_DELETEDC:
498         /*
499          * Windows will not let you delete a DC that is busy
500          * (between GetDC and ReleaseDC)
501          */
502         USER_Lock();
503         if (dce->count > 1)
504         {
505             WARN("Application trying to delete a busy DC %p\n", dce->hdc);
506             retv = FALSE;
507         }
508         else
509         {
510             list_remove( &dce->entry );
511             if (dce->clip_rgn) DeleteObject( dce->clip_rgn );
512             HeapFree( GetProcessHeap(), 0, dce );
513         }
514         USER_Unlock();
515         break;
516     }
517     return retv;
518 }
519
520
521 /***********************************************************************
522  *           get_update_region
523  *
524  * Return update region (in screen coordinates) for a window.
525  */
526 static HRGN get_update_region( HWND hwnd, UINT *flags, HWND *child )
527 {
528     HRGN hrgn = 0;
529     NTSTATUS status;
530     RGNDATA *data;
531     size_t size = 256;
532
533     do
534     {
535         if (!(data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data) + size - 1 )))
536         {
537             SetLastError( ERROR_OUTOFMEMORY );
538             return 0;
539         }
540
541         SERVER_START_REQ( get_update_region )
542         {
543             req->window     = wine_server_user_handle( hwnd );
544             req->from_child = wine_server_user_handle( child ? *child : 0 );
545             req->flags      = *flags;
546             wine_server_set_reply( req, data->Buffer, size );
547             if (!(status = wine_server_call( req )))
548             {
549                 size_t reply_size = wine_server_reply_size( reply );
550                 data->rdh.dwSize   = sizeof(data->rdh);
551                 data->rdh.iType    = RDH_RECTANGLES;
552                 data->rdh.nCount   = reply_size / sizeof(RECT);
553                 data->rdh.nRgnSize = reply_size;
554                 hrgn = ExtCreateRegion( NULL, size, data );
555                 if (child) *child = wine_server_ptr_handle( reply->child );
556                 *flags = reply->flags;
557             }
558             else size = reply->total_size;
559         }
560         SERVER_END_REQ;
561         HeapFree( GetProcessHeap(), 0, data );
562     } while (status == STATUS_BUFFER_OVERFLOW);
563
564     if (status) SetLastError( RtlNtStatusToDosError(status) );
565     return hrgn;
566 }
567
568
569 /***********************************************************************
570  *           get_update_flags
571  *
572  * Get only the update flags, not the update region.
573  */
574 static BOOL get_update_flags( HWND hwnd, HWND *child, UINT *flags )
575 {
576     BOOL ret;
577
578     SERVER_START_REQ( get_update_region )
579     {
580         req->window     = wine_server_user_handle( hwnd );
581         req->from_child = wine_server_user_handle( child ? *child : 0 );
582         req->flags      = *flags | UPDATE_NOREGION;
583         if ((ret = !wine_server_call_err( req )))
584         {
585             if (child) *child = wine_server_ptr_handle( reply->child );
586             *flags = reply->flags;
587         }
588     }
589     SERVER_END_REQ;
590     return ret;
591 }
592
593
594 /***********************************************************************
595  *           redraw_window_rects
596  *
597  * Redraw part of a window.
598  */
599 static BOOL redraw_window_rects( HWND hwnd, UINT flags, const RECT *rects, UINT count )
600 {
601     BOOL ret;
602
603     if (!(flags & (RDW_INVALIDATE|RDW_VALIDATE|RDW_INTERNALPAINT|RDW_NOINTERNALPAINT)))
604         return TRUE;  /* nothing to do */
605
606     SERVER_START_REQ( redraw_window )
607     {
608         req->window = wine_server_user_handle( hwnd );
609         req->flags  = flags;
610         wine_server_add_data( req, rects, count * sizeof(RECT) );
611         ret = !wine_server_call_err( req );
612     }
613     SERVER_END_REQ;
614     return ret;
615 }
616
617
618 /***********************************************************************
619  *           send_ncpaint
620  *
621  * Send a WM_NCPAINT message if needed, and return the resulting update region (in screen coords).
622  * Helper for erase_now and BeginPaint.
623  */
624 static HRGN send_ncpaint( HWND hwnd, HWND *child, UINT *flags )
625 {
626     HRGN whole_rgn = get_update_region( hwnd, flags, child );
627     HRGN client_rgn = 0;
628
629     if (child) hwnd = *child;
630
631     if (hwnd == GetDesktopWindow()) return whole_rgn;
632
633     if (whole_rgn)
634     {
635         RECT client, update;
636         INT type;
637
638         /* check if update rgn overlaps with nonclient area */
639         type = GetRgnBox( whole_rgn, &update );
640         WIN_GetRectangles( hwnd, COORDS_SCREEN, 0, &client );
641
642         if ((*flags & UPDATE_NONCLIENT) ||
643             update.left < client.left || update.top < client.top ||
644             update.right > client.right || update.bottom > client.bottom)
645         {
646             client_rgn = CreateRectRgnIndirect( &client );
647             CombineRgn( client_rgn, client_rgn, whole_rgn, RGN_AND );
648
649             /* check if update rgn contains complete nonclient area */
650             if (type == SIMPLEREGION)
651             {
652                 RECT window;
653                 GetWindowRect( hwnd, &window );
654                 if (EqualRect( &window, &update ))
655                 {
656                     DeleteObject( whole_rgn );
657                     whole_rgn = (HRGN)1;
658                 }
659             }
660         }
661         else
662         {
663             client_rgn = whole_rgn;
664             whole_rgn = 0;
665         }
666
667         if (whole_rgn) /* NOTE: WM_NCPAINT allows wParam to be 1 */
668         {
669             if (*flags & UPDATE_NONCLIENT) SendMessageW( hwnd, WM_NCPAINT, (WPARAM)whole_rgn, 0 );
670             if (whole_rgn > (HRGN)1) DeleteObject( whole_rgn );
671         }
672     }
673     return client_rgn;
674 }
675
676
677 /***********************************************************************
678  *           send_erase
679  *
680  * Send a WM_ERASEBKGND message if needed, and optionally return the DC for painting.
681  * If a DC is requested, the region is selected into it. In all cases the region is deleted.
682  * Helper for erase_now and BeginPaint.
683  */
684 static BOOL send_erase( HWND hwnd, UINT flags, HRGN client_rgn,
685                         RECT *clip_rect, HDC *hdc_ret )
686 {
687     BOOL need_erase = (flags & UPDATE_DELAYED_ERASE) != 0;
688     HDC hdc = 0;
689     RECT dummy;
690
691     if (!clip_rect) clip_rect = &dummy;
692     if (hdc_ret || (flags & UPDATE_ERASE))
693     {
694         UINT dcx_flags = DCX_INTERSECTRGN | DCX_USESTYLE;
695         if (IsIconic(hwnd)) dcx_flags |= DCX_WINDOW;
696
697         if ((hdc = GetDCEx( hwnd, client_rgn, dcx_flags )))
698         {
699             INT type = GetClipBox( hdc, clip_rect );
700
701             if (flags & UPDATE_ERASE)
702             {
703                 /* don't erase if the clip box is empty */
704                 if (type != NULLREGION)
705                     need_erase = !SendMessageW( hwnd, WM_ERASEBKGND, (WPARAM)hdc, 0 );
706             }
707             if (!hdc_ret) release_dc( hwnd, hdc, TRUE );
708         }
709
710         if (hdc_ret) *hdc_ret = hdc;
711     }
712     if (!hdc) DeleteObject( client_rgn );
713     return need_erase;
714 }
715
716
717 /***********************************************************************
718  *           erase_now
719  *
720  * Implementation of RDW_ERASENOW behavior.
721  */
722 void erase_now( HWND hwnd, UINT rdw_flags )
723 {
724     HWND child = 0;
725     HRGN hrgn;
726     BOOL need_erase = FALSE;
727
728     /* loop while we find a child to repaint */
729     for (;;)
730     {
731         UINT flags = UPDATE_NONCLIENT | UPDATE_ERASE;
732
733         if (rdw_flags & RDW_NOCHILDREN) flags |= UPDATE_NOCHILDREN;
734         else if (rdw_flags & RDW_ALLCHILDREN) flags |= UPDATE_ALLCHILDREN;
735         if (need_erase) flags |= UPDATE_DELAYED_ERASE;
736
737         if (!(hrgn = send_ncpaint( hwnd, &child, &flags ))) break;
738         need_erase = send_erase( child, flags, hrgn, NULL, NULL );
739
740         if (!flags) break;  /* nothing more to do */
741         if ((rdw_flags & RDW_NOCHILDREN) && !need_erase) break;
742     }
743 }
744
745
746 /***********************************************************************
747  *           move_window_bits
748  *
749  * Move the window bits when a window is resized or its surface recreated.
750  */
751 void move_window_bits( HWND hwnd, struct window_surface *old_surface,
752                        struct window_surface *new_surface,
753                        const RECT *visible_rect, const RECT *old_visible_rect,
754                        const RECT *client_rect, const RECT *valid_rects )
755 {
756     RECT dst = valid_rects[0];
757     RECT src = valid_rects[1];
758
759     if (new_surface != old_surface ||
760         src.left - old_visible_rect->left != dst.left - visible_rect->left ||
761         src.top - old_visible_rect->top != dst.top - visible_rect->top)
762     {
763         char buffer[FIELD_OFFSET( BITMAPINFO, bmiColors[256] )];
764         BITMAPINFO *info = (BITMAPINFO *)buffer;
765         void *bits;
766         UINT flags = UPDATE_NOCHILDREN;
767         HRGN rgn = get_update_region( hwnd, &flags, NULL );
768         HDC hdc = GetDCEx( hwnd, rgn, DCX_CACHE | DCX_EXCLUDERGN );
769
770         OffsetRect( &dst, -client_rect->left, -client_rect->top );
771         TRACE( "copying  %s -> %s\n", wine_dbgstr_rect(&src), wine_dbgstr_rect(&dst) );
772         bits = old_surface->funcs->get_info( old_surface, info );
773         old_surface->funcs->lock( old_surface );
774         SetDIBitsToDevice( hdc, dst.left, dst.top, dst.right - dst.left, dst.bottom - dst.top,
775                            src.left - old_visible_rect->left - old_surface->rect.left,
776                            old_surface->rect.bottom - (src.bottom - old_visible_rect->top),
777                            0, old_surface->rect.bottom - old_surface->rect.top,
778                            bits, info, DIB_RGB_COLORS );
779         old_surface->funcs->unlock( old_surface );
780         ReleaseDC( hwnd, hdc );
781     }
782 }
783
784
785 /***********************************************************************
786  *           update_now
787  *
788  * Implementation of RDW_UPDATENOW behavior.
789  */
790 static void update_now( HWND hwnd, UINT rdw_flags )
791 {
792     HWND child = 0;
793
794     /* desktop window never gets WM_PAINT, only WM_ERASEBKGND */
795     if (hwnd == GetDesktopWindow()) erase_now( hwnd, rdw_flags | RDW_NOCHILDREN );
796
797     /* loop while we find a child to repaint */
798     for (;;)
799     {
800         UINT flags = UPDATE_PAINT | UPDATE_INTERNALPAINT;
801
802         if (rdw_flags & RDW_NOCHILDREN) flags |= UPDATE_NOCHILDREN;
803         else if (rdw_flags & RDW_ALLCHILDREN) flags |= UPDATE_ALLCHILDREN;
804
805         if (!get_update_flags( hwnd, &child, &flags )) break;
806         if (!flags) break;  /* nothing more to do */
807
808         SendMessageW( child, WM_PAINT, 0, 0 );
809         if (rdw_flags & RDW_NOCHILDREN) break;
810     }
811 }
812
813
814 /*************************************************************************
815  *             fix_caret
816  *
817  * Helper for ScrollWindowEx:
818  * If the return value is 0, no special caret handling is necessary.
819  * Otherwise the return value is the handle of the window that owns the
820  * caret. Its caret needs to be hidden during the scroll operation and
821  * moved to new_caret_pos if move_caret is TRUE.
822  */
823 static HWND fix_caret(HWND hWnd, const RECT *scroll_rect, INT dx, INT dy,
824                      UINT flags, LPBOOL move_caret, LPPOINT new_caret_pos)
825 {
826     GUITHREADINFO info;
827     RECT rect, mapped_rcCaret;
828     BOOL hide_caret = FALSE;
829
830     info.cbSize = sizeof(info);
831     if (!GetGUIThreadInfo( GetCurrentThreadId(), &info )) return 0;
832     if (!info.hwndCaret) return 0;
833     
834     if (info.hwndCaret == hWnd)
835     {
836         /* Move the caret if it's (partially) in the source rectangle */
837         if (IntersectRect(&rect, scroll_rect, &info.rcCaret))
838         {
839             *move_caret = TRUE;
840             hide_caret = TRUE;
841             new_caret_pos->x = info.rcCaret.left + dx;
842             new_caret_pos->y = info.rcCaret.top + dy;
843         }
844         else
845         {
846             *move_caret = FALSE;
847             
848             /* Hide the caret if it's in the destination rectangle */
849             rect = *scroll_rect;
850             OffsetRect(&rect, dx, dy);
851             hide_caret = IntersectRect(&rect, &rect, &info.rcCaret);
852         }
853     }
854     else
855     {
856         if ((flags & SW_SCROLLCHILDREN) && IsChild(hWnd, info.hwndCaret))
857         {
858             *move_caret = FALSE;
859             
860             /* Hide the caret if it's in the source or in the destination
861                rectangle */
862             mapped_rcCaret = info.rcCaret;
863             MapWindowPoints(info.hwndCaret, hWnd, (LPPOINT)&mapped_rcCaret, 2);
864             
865             if (IntersectRect(&rect, scroll_rect, &mapped_rcCaret))
866             {
867                 hide_caret = TRUE;
868             }
869             else
870             {
871                 rect = *scroll_rect;
872                 OffsetRect(&rect, dx, dy);
873                 hide_caret = IntersectRect(&rect, &rect, &mapped_rcCaret);
874             }
875         }
876         else
877             return 0;
878     }
879
880     if (hide_caret)
881     {    
882         HideCaret(info.hwndCaret);
883         return info.hwndCaret;
884     }
885     else
886         return 0;
887 }
888
889
890 /***********************************************************************
891  *              BeginPaint (USER32.@)
892  */
893 HDC WINAPI BeginPaint( HWND hwnd, PAINTSTRUCT *lps )
894 {
895     HRGN hrgn;
896     UINT flags = UPDATE_NONCLIENT | UPDATE_ERASE | UPDATE_PAINT | UPDATE_INTERNALPAINT | UPDATE_NOCHILDREN;
897
898     if (!lps) return 0;
899
900     HideCaret( hwnd );
901
902     if (!(hrgn = send_ncpaint( hwnd, NULL, &flags ))) return 0;
903
904     lps->fErase = send_erase( hwnd, flags, hrgn, &lps->rcPaint, &lps->hdc );
905
906     TRACE("hdc = %p box = (%s), fErase = %d\n",
907           lps->hdc, wine_dbgstr_rect(&lps->rcPaint), lps->fErase);
908
909     return lps->hdc;
910 }
911
912
913 /***********************************************************************
914  *              EndPaint (USER32.@)
915  */
916 BOOL WINAPI EndPaint( HWND hwnd, const PAINTSTRUCT *lps )
917 {
918     if (!lps) return FALSE;
919     release_dc( hwnd, lps->hdc, TRUE );
920     ShowCaret( hwnd );
921     flush_window_surfaces( FALSE );
922     return TRUE;
923 }
924
925
926 /***********************************************************************
927  *              GetDCEx (USER32.@)
928  */
929 HDC WINAPI GetDCEx( HWND hwnd, HRGN hrgnClip, DWORD flags )
930 {
931     const DWORD clip_flags = DCX_PARENTCLIP | DCX_CLIPSIBLINGS | DCX_CLIPCHILDREN | DCX_WINDOW;
932     const DWORD user_flags = clip_flags | DCX_NORESETATTRS; /* flags that can be set by user */
933     struct dce *dce;
934     BOOL bUpdateVisRgn = TRUE;
935     HWND parent;
936     LONG window_style = GetWindowLongW( hwnd, GWL_STYLE );
937
938     if (!hwnd) hwnd = GetDesktopWindow();
939     else hwnd = WIN_GetFullHandle( hwnd );
940
941     TRACE("hwnd %p, hrgnClip %p, flags %08x\n", hwnd, hrgnClip, flags);
942
943     if (!IsWindow(hwnd)) return 0;
944
945     /* fixup flags */
946
947     if (flags & (DCX_WINDOW | DCX_PARENTCLIP)) flags |= DCX_CACHE;
948
949     if (flags & DCX_USESTYLE)
950     {
951         flags &= ~(DCX_CLIPCHILDREN | DCX_CLIPSIBLINGS | DCX_PARENTCLIP);
952
953         if (window_style & WS_CLIPSIBLINGS) flags |= DCX_CLIPSIBLINGS;
954
955         if (!(flags & DCX_WINDOW))
956         {
957             if (GetClassLongW( hwnd, GCL_STYLE ) & CS_PARENTDC) flags |= DCX_PARENTCLIP;
958
959             if (window_style & WS_CLIPCHILDREN && !(window_style & WS_MINIMIZE))
960                 flags |= DCX_CLIPCHILDREN;
961         }
962     }
963
964     if (flags & DCX_WINDOW) flags &= ~DCX_CLIPCHILDREN;
965
966     parent = GetAncestor( hwnd, GA_PARENT );
967     if (!parent || (parent == GetDesktopWindow()))
968         flags = (flags & ~DCX_PARENTCLIP) | DCX_CLIPSIBLINGS;
969
970     /* it seems parent clip is ignored when clipping siblings or children */
971     if (flags & (DCX_CLIPSIBLINGS | DCX_CLIPCHILDREN)) flags &= ~DCX_PARENTCLIP;
972
973     if( flags & DCX_PARENTCLIP )
974     {
975         LONG parent_style = GetWindowLongW( parent, GWL_STYLE );
976         if( (window_style & WS_VISIBLE) && (parent_style & WS_VISIBLE) )
977         {
978             flags &= ~DCX_CLIPCHILDREN;
979             if (parent_style & WS_CLIPSIBLINGS) flags |= DCX_CLIPSIBLINGS;
980         }
981     }
982
983     /* find a suitable DCE */
984
985     if ((flags & DCX_CACHE) || !(dce = get_window_dce( hwnd )))
986     {
987         struct dce *dceEmpty = NULL, *dceUnused = NULL;
988
989         /* Strategy: First, we attempt to find a non-empty but unused DCE with
990          * compatible flags. Next, we look for an empty entry. If the cache is
991          * full we have to purge one of the unused entries.
992          */
993         USER_Lock();
994         LIST_FOR_EACH_ENTRY( dce, &dce_list, struct dce, entry )
995         {
996             if ((dce->flags & DCX_CACHE) && !dce->count)
997             {
998                 dceUnused = dce;
999
1000                 if (!dce->hwnd) dceEmpty = dce;
1001                 else if ((dce->hwnd == hwnd) && !((dce->flags ^ flags) & clip_flags))
1002                 {
1003                     TRACE("\tfound valid %p dce [%p], flags %08x\n",
1004                           dce, hwnd, dce->flags );
1005                     bUpdateVisRgn = FALSE;
1006                     break;
1007                 }
1008             }
1009         }
1010
1011         if (&dce->entry == &dce_list)  /* nothing found */
1012             dce = dceEmpty ? dceEmpty : dceUnused;
1013
1014         if (dce) dce->count = 1;
1015
1016         USER_Unlock();
1017
1018         /* if there's no dce empty or unused, allocate a new one */
1019         if (!dce)
1020         {
1021             if (!(dce = alloc_dce())) return 0;
1022             dce->flags = DCX_CACHE;
1023             USER_Lock();
1024             list_add_head( &dce_list, &dce->entry );
1025             USER_Unlock();
1026         }
1027     }
1028     else
1029     {
1030         flags |= DCX_NORESETATTRS;
1031         if (dce->hwnd == hwnd)
1032         {
1033             TRACE("\tskipping hVisRgn update\n");
1034             bUpdateVisRgn = FALSE; /* updated automatically, via DCHook() */
1035         }
1036         else
1037         {
1038             /* we should free dce->clip_rgn here, but Windows apparently doesn't */
1039             dce->flags &= ~(DCX_EXCLUDERGN | DCX_INTERSECTRGN);
1040             dce->clip_rgn = 0;
1041         }
1042     }
1043
1044     if (flags & (DCX_INTERSECTRGN | DCX_EXCLUDERGN))
1045     {
1046         /* if the extra clip region has changed, get rid of the old one */
1047         if (dce->clip_rgn != hrgnClip || ((flags ^ dce->flags) & (DCX_INTERSECTRGN | DCX_EXCLUDERGN)))
1048             delete_clip_rgn( dce );
1049         dce->clip_rgn = hrgnClip;
1050         if (!dce->clip_rgn) dce->clip_rgn = CreateRectRgn( 0, 0, 0, 0 );
1051         dce->flags |= flags & (DCX_INTERSECTRGN | DCX_EXCLUDERGN);
1052         bUpdateVisRgn = TRUE;
1053     }
1054
1055     if (GetWindowLongW( hwnd, GWL_EXSTYLE ) & WS_EX_LAYOUTRTL) SetLayout( dce->hdc, LAYOUT_RTL );
1056
1057     dce->hwnd = hwnd;
1058     dce->flags = (dce->flags & ~user_flags) | (flags & user_flags);
1059
1060     if (SetHookFlags( dce->hdc, DCHF_VALIDATEVISRGN )) bUpdateVisRgn = TRUE;  /* DC was dirty */
1061
1062     if (bUpdateVisRgn) update_visible_region( dce );
1063
1064     TRACE("(%p,%p,0x%x): returning %p\n", hwnd, hrgnClip, flags, dce->hdc);
1065     return dce->hdc;
1066 }
1067
1068
1069 /***********************************************************************
1070  *              GetDC (USER32.@)
1071  *
1072  * Get a device context.
1073  *
1074  * RETURNS
1075  *      Success: Handle to the device context
1076  *      Failure: NULL.
1077  */
1078 HDC WINAPI GetDC( HWND hwnd )
1079 {
1080     if (!hwnd) return GetDCEx( 0, 0, DCX_CACHE | DCX_WINDOW );
1081     return GetDCEx( hwnd, 0, DCX_USESTYLE );
1082 }
1083
1084
1085 /***********************************************************************
1086  *              GetWindowDC (USER32.@)
1087  */
1088 HDC WINAPI GetWindowDC( HWND hwnd )
1089 {
1090     return GetDCEx( hwnd, 0, DCX_USESTYLE | DCX_WINDOW );
1091 }
1092
1093
1094 /***********************************************************************
1095  *              ReleaseDC (USER32.@)
1096  *
1097  * Release a device context.
1098  *
1099  * RETURNS
1100  *      Success: Non-zero. Resources used by hdc are released.
1101  *      Failure: 0.
1102  */
1103 INT WINAPI ReleaseDC( HWND hwnd, HDC hdc )
1104 {
1105     return release_dc( hwnd, hdc, FALSE );
1106 }
1107
1108
1109 /**********************************************************************
1110  *              WindowFromDC (USER32.@)
1111  */
1112 HWND WINAPI WindowFromDC( HDC hdc )
1113 {
1114     struct dce *dce;
1115     HWND hwnd = 0;
1116
1117     USER_Lock();
1118     dce = (struct dce *)GetDCHook( hdc, NULL );
1119     if (dce) hwnd = dce->hwnd;
1120     USER_Unlock();
1121     return hwnd;
1122 }
1123
1124
1125 /***********************************************************************
1126  *              LockWindowUpdate (USER32.@)
1127  *
1128  * Enables or disables painting in the chosen window.
1129  *
1130  * PARAMS
1131  *  hwnd [I] handle to a window.
1132  *
1133  * RETURNS
1134  *  If successful, returns nonzero value. Otherwise,
1135  *  returns 0.
1136  *
1137  * NOTES
1138  *  You can lock only one window at a time.
1139  */
1140 BOOL WINAPI LockWindowUpdate( HWND hwnd )
1141 {
1142     static HWND lockedWnd;
1143
1144     FIXME("(%p), partial stub!\n",hwnd);
1145
1146     USER_Lock();
1147     if (lockedWnd)
1148     {
1149         if (!hwnd)
1150         {
1151             /* Unlock lockedWnd */
1152             /* FIXME: Do something */
1153         }
1154         else
1155         {
1156             /* Attempted to lock a second window */
1157             /* Return FALSE and do nothing */
1158             USER_Unlock();
1159             return FALSE;
1160         }
1161     }
1162     lockedWnd = hwnd;
1163     USER_Unlock();
1164     return TRUE;
1165 }
1166
1167
1168 /***********************************************************************
1169  *              RedrawWindow (USER32.@)
1170  */
1171 BOOL WINAPI RedrawWindow( HWND hwnd, const RECT *rect, HRGN hrgn, UINT flags )
1172 {
1173     static const RECT empty;
1174     BOOL ret;
1175
1176     if (!hwnd) hwnd = GetDesktopWindow();
1177
1178     if (TRACE_ON(win))
1179     {
1180         if (hrgn)
1181         {
1182             RECT r;
1183             GetRgnBox( hrgn, &r );
1184             TRACE( "%p region %p box %s ", hwnd, hrgn, wine_dbgstr_rect(&r) );
1185         }
1186         else if (rect)
1187             TRACE( "%p rect %s ", hwnd, wine_dbgstr_rect(rect) );
1188         else
1189             TRACE( "%p whole window ", hwnd );
1190
1191         dump_rdw_flags(flags);
1192     }
1193
1194     /* process pending expose events before painting */
1195     if (flags & RDW_UPDATENOW) USER_Driver->pMsgWaitForMultipleObjectsEx( 0, NULL, 0, QS_PAINT, 0 );
1196
1197     if (rect && !hrgn)
1198     {
1199         if (IsRectEmpty( rect )) rect = &empty;
1200         ret = redraw_window_rects( hwnd, flags, rect, 1 );
1201     }
1202     else if (!hrgn)
1203     {
1204         ret = redraw_window_rects( hwnd, flags, NULL, 0 );
1205     }
1206     else  /* need to build a list of the region rectangles */
1207     {
1208         DWORD size;
1209         RGNDATA *data = NULL;
1210
1211         if (!(size = GetRegionData( hrgn, 0, NULL ))) return FALSE;
1212         if (!(data = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
1213         GetRegionData( hrgn, size, data );
1214         if (!data->rdh.nCount)  /* empty region -> use a single all-zero rectangle */
1215             ret = redraw_window_rects( hwnd, flags, &empty, 1 );
1216         else
1217             ret = redraw_window_rects( hwnd, flags, (const RECT *)data->Buffer, data->rdh.nCount );
1218         HeapFree( GetProcessHeap(), 0, data );
1219     }
1220
1221     if (flags & RDW_UPDATENOW) update_now( hwnd, flags );
1222     else if (flags & RDW_ERASENOW) erase_now( hwnd, flags );
1223
1224     return ret;
1225 }
1226
1227
1228 /***********************************************************************
1229  *              UpdateWindow (USER32.@)
1230  */
1231 BOOL WINAPI UpdateWindow( HWND hwnd )
1232 {
1233     if (!hwnd)
1234     {
1235         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
1236         return FALSE;
1237     }
1238
1239     return RedrawWindow( hwnd, NULL, 0, RDW_UPDATENOW | RDW_ALLCHILDREN );
1240 }
1241
1242
1243 /***********************************************************************
1244  *              InvalidateRgn (USER32.@)
1245  */
1246 BOOL WINAPI InvalidateRgn( HWND hwnd, HRGN hrgn, BOOL erase )
1247 {
1248     if (!hwnd)
1249     {
1250         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
1251         return FALSE;
1252     }
1253
1254     return RedrawWindow(hwnd, NULL, hrgn, RDW_INVALIDATE | (erase ? RDW_ERASE : 0) );
1255 }
1256
1257
1258 /***********************************************************************
1259  *              InvalidateRect (USER32.@)
1260  *
1261  * MSDN: if hwnd parameter is NULL, InvalidateRect invalidates and redraws
1262  * all windows and sends WM_ERASEBKGND and WM_NCPAINT.
1263  */
1264 BOOL WINAPI InvalidateRect( HWND hwnd, const RECT *rect, BOOL erase )
1265 {
1266     UINT flags = RDW_INVALIDATE | (erase ? RDW_ERASE : 0);
1267
1268     if (!hwnd)
1269     {
1270         flags = RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_FRAME | RDW_ERASE | RDW_ERASENOW;
1271         rect = NULL;
1272     }
1273
1274     return RedrawWindow( hwnd, rect, 0, flags );
1275 }
1276
1277
1278 /***********************************************************************
1279  *              ValidateRgn (USER32.@)
1280  */
1281 BOOL WINAPI ValidateRgn( HWND hwnd, HRGN hrgn )
1282 {
1283     if (!hwnd)
1284     {
1285         SetLastError( ERROR_INVALID_WINDOW_HANDLE );
1286         return FALSE;
1287     }
1288
1289     return RedrawWindow( hwnd, NULL, hrgn, RDW_VALIDATE );
1290 }
1291
1292
1293 /***********************************************************************
1294  *              ValidateRect (USER32.@)
1295  *
1296  * MSDN: if hwnd parameter is NULL, ValidateRect invalidates and redraws
1297  * all windows and sends WM_ERASEBKGND and WM_NCPAINT.
1298  */
1299 BOOL WINAPI ValidateRect( HWND hwnd, const RECT *rect )
1300 {
1301     UINT flags = RDW_VALIDATE;
1302
1303     if (!hwnd)
1304     {
1305         flags = RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_FRAME | RDW_ERASE | RDW_ERASENOW;
1306         rect = NULL;
1307     }
1308
1309     return RedrawWindow( hwnd, rect, 0, flags );
1310 }
1311
1312
1313 /***********************************************************************
1314  *              GetUpdateRgn (USER32.@)
1315  */
1316 INT WINAPI GetUpdateRgn( HWND hwnd, HRGN hrgn, BOOL erase )
1317 {
1318     INT retval = ERROR;
1319     UINT flags = UPDATE_NOCHILDREN;
1320     HRGN update_rgn;
1321
1322     if (erase) flags |= UPDATE_NONCLIENT | UPDATE_ERASE;
1323
1324     if ((update_rgn = send_ncpaint( hwnd, NULL, &flags )))
1325     {
1326         retval = CombineRgn( hrgn, update_rgn, 0, RGN_COPY );
1327         if (send_erase( hwnd, flags, update_rgn, NULL, NULL ))
1328         {
1329             flags = UPDATE_DELAYED_ERASE;
1330             get_update_flags( hwnd, NULL, &flags );
1331         }
1332         /* map region to client coordinates */
1333         map_window_region( 0, hwnd, hrgn );
1334     }
1335     return retval;
1336 }
1337
1338
1339 /***********************************************************************
1340  *              GetUpdateRect (USER32.@)
1341  */
1342 BOOL WINAPI GetUpdateRect( HWND hwnd, LPRECT rect, BOOL erase )
1343 {
1344     UINT flags = UPDATE_NOCHILDREN;
1345     HRGN update_rgn;
1346     BOOL need_erase;
1347
1348     if (erase) flags |= UPDATE_NONCLIENT | UPDATE_ERASE;
1349
1350     if (!(update_rgn = send_ncpaint( hwnd, NULL, &flags ))) return FALSE;
1351
1352     if (rect)
1353     {
1354         if (GetRgnBox( update_rgn, rect ) != NULLREGION)
1355         {
1356             HDC hdc = GetDCEx( hwnd, 0, DCX_USESTYLE );
1357             DWORD layout = SetLayout( hdc, 0 );  /* MapWindowPoints mirrors already */
1358             MapWindowPoints( 0, hwnd, (LPPOINT)rect, 2 );
1359             DPtoLP( hdc, (LPPOINT)rect, 2 );
1360             SetLayout( hdc, layout );
1361             ReleaseDC( hwnd, hdc );
1362         }
1363     }
1364     need_erase = send_erase( hwnd, flags, update_rgn, NULL, NULL );
1365
1366     /* check if we still have an update region */
1367     flags = UPDATE_PAINT | UPDATE_NOCHILDREN;
1368     if (need_erase) flags |= UPDATE_DELAYED_ERASE;
1369     return (get_update_flags( hwnd, NULL, &flags ) && (flags & UPDATE_PAINT));
1370 }
1371
1372
1373 /***********************************************************************
1374  *              ExcludeUpdateRgn (USER32.@)
1375  */
1376 INT WINAPI ExcludeUpdateRgn( HDC hdc, HWND hwnd )
1377 {
1378     HRGN update_rgn = CreateRectRgn( 0, 0, 0, 0 );
1379     INT ret = GetUpdateRgn( hwnd, update_rgn, FALSE );
1380
1381     if (ret != ERROR)
1382     {
1383         POINT pt;
1384
1385         GetDCOrgEx( hdc, &pt );
1386         MapWindowPoints( 0, hwnd, &pt, 1 );
1387         OffsetRgn( update_rgn, -pt.x, -pt.y );
1388         ret = ExtSelectClipRgn( hdc, update_rgn, RGN_DIFF );
1389         DeleteObject( update_rgn );
1390     }
1391     return ret;
1392 }
1393
1394
1395 static INT scroll_window( HWND hwnd, INT dx, INT dy, const RECT *rect, const RECT *clipRect,
1396                           HRGN hrgnUpdate, LPRECT rcUpdate, UINT flags, BOOL is_ex )
1397 {
1398     INT   retVal = NULLREGION;
1399     BOOL  bOwnRgn = TRUE;
1400     BOOL  bUpdate = (rcUpdate || hrgnUpdate || flags & (SW_INVALIDATE | SW_ERASE));
1401     int rdw_flags;
1402     HRGN  hrgnTemp;
1403     HRGN  hrgnWinupd = 0;
1404     HDC   hDC;
1405     RECT  rc, cliprc;
1406     HWND hwndCaret = NULL;
1407     BOOL moveCaret = FALSE;
1408     POINT newCaretPos;
1409
1410     TRACE( "%p, %d,%d hrgnUpdate=%p rcUpdate = %p %s %04x\n",
1411            hwnd, dx, dy, hrgnUpdate, rcUpdate, wine_dbgstr_rect(rect), flags );
1412     TRACE( "clipRect = %s\n", wine_dbgstr_rect(clipRect));
1413     if( flags & ~( SW_SCROLLCHILDREN | SW_INVALIDATE | SW_ERASE))
1414         FIXME("some flags (%04x) are unhandled\n", flags);
1415
1416     rdw_flags = (flags & SW_ERASE) && (flags & SW_INVALIDATE) ?
1417                                 RDW_INVALIDATE | RDW_ERASE  : RDW_INVALIDATE ;
1418
1419     if (!WIN_IsWindowDrawable( hwnd, TRUE )) return ERROR;
1420     hwnd = WIN_GetFullHandle( hwnd );
1421
1422     GetClientRect(hwnd, &rc);
1423
1424     if (clipRect) IntersectRect(&cliprc,&rc,clipRect);
1425     else cliprc = rc;
1426
1427     if (rect) IntersectRect(&rc, &rc, rect);
1428
1429     if( hrgnUpdate ) bOwnRgn = FALSE;
1430     else if( bUpdate ) hrgnUpdate = CreateRectRgn( 0, 0, 0, 0 );
1431
1432     newCaretPos.x = newCaretPos.y = 0;
1433
1434     if( !IsRectEmpty(&cliprc) && (dx || dy)) {
1435         DWORD dcxflags = 0;
1436         DWORD style = GetWindowLongW( hwnd, GWL_STYLE );
1437
1438         hwndCaret = fix_caret(hwnd, &rc, dx, dy, flags, &moveCaret, &newCaretPos);
1439
1440         if (is_ex) dcxflags |= DCX_CACHE;
1441         if( style & WS_CLIPSIBLINGS) dcxflags |= DCX_CLIPSIBLINGS;
1442         if( GetClassLongW( hwnd, GCL_STYLE ) & CS_PARENTDC)
1443             dcxflags |= DCX_PARENTCLIP;
1444         if( !(flags & SW_SCROLLCHILDREN) && (style & WS_CLIPCHILDREN))
1445             dcxflags |= DCX_CLIPCHILDREN;
1446         hDC = GetDCEx( hwnd, 0, dcxflags);
1447         if (hDC)
1448         {
1449             ScrollDC( hDC, dx, dy, &rc, &cliprc, hrgnUpdate, rcUpdate );
1450
1451             ReleaseDC( hwnd, hDC );
1452
1453             if (!bUpdate)
1454                 RedrawWindow( hwnd, NULL, hrgnUpdate, rdw_flags);
1455         }
1456
1457         /* If the windows has an update region, this must be
1458          * scrolled as well. Keep a copy in hrgnWinupd
1459          * to be added to hrngUpdate at the end. */
1460         hrgnTemp = CreateRectRgn( 0, 0, 0, 0 );
1461         retVal = GetUpdateRgn( hwnd, hrgnTemp, FALSE );
1462         if (retVal != NULLREGION)
1463         {
1464             HRGN hrgnClip = CreateRectRgnIndirect(&cliprc);
1465             if( !bOwnRgn) {
1466                 hrgnWinupd = CreateRectRgn( 0, 0, 0, 0);
1467                 CombineRgn( hrgnWinupd, hrgnTemp, 0, RGN_COPY);
1468             }
1469             OffsetRgn( hrgnTemp, dx, dy );
1470             CombineRgn( hrgnTemp, hrgnTemp, hrgnClip, RGN_AND );
1471             if( !bOwnRgn)
1472                 CombineRgn( hrgnWinupd, hrgnWinupd, hrgnTemp, RGN_OR );
1473             RedrawWindow( hwnd, NULL, hrgnTemp, rdw_flags);
1474
1475            /* Catch the case where the scrolling amount exceeds the size of the
1476             * original window. This generated a second update area that is the
1477             * location where the original scrolled content would end up.
1478             * This second region is not returned by the ScrollDC and sets
1479             * ScrollWindowEx apart from just a ScrollDC.
1480             *
1481             * This has been verified with testing on windows.
1482             */
1483             if (abs(dx) > abs(rc.right - rc.left) ||
1484                 abs(dy) > abs(rc.bottom - rc.top))
1485             {
1486                 SetRectRgn( hrgnTemp, rc.left + dx, rc.top + dy, rc.right+dx, rc.bottom + dy);
1487                 CombineRgn( hrgnTemp, hrgnTemp, hrgnClip, RGN_AND );
1488                 CombineRgn( hrgnUpdate, hrgnUpdate, hrgnTemp, RGN_OR );
1489
1490                 if( !bOwnRgn)
1491                     CombineRgn( hrgnWinupd, hrgnWinupd, hrgnTemp, RGN_OR );
1492             }
1493             DeleteObject( hrgnClip );
1494         }
1495         DeleteObject( hrgnTemp );
1496     } else {
1497         /* nothing was scrolled */
1498         if( !bOwnRgn)
1499             SetRectRgn( hrgnUpdate, 0, 0, 0, 0 );
1500         SetRectEmpty( rcUpdate);
1501     }
1502
1503     if( flags & SW_SCROLLCHILDREN )
1504     {
1505         HWND *list = WIN_ListChildren( hwnd );
1506         if (list)
1507         {
1508             int i;
1509             RECT r, dummy;
1510             for (i = 0; list[i]; i++)
1511             {
1512                 WIN_GetRectangles( list[i], COORDS_PARENT, &r, NULL );
1513                 if (!rect || IntersectRect(&dummy, &r, rect))
1514                     SetWindowPos( list[i], 0, r.left + dx, r.top  + dy, 0, 0,
1515                                   SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE |
1516                                   SWP_NOREDRAW | SWP_DEFERERASE );
1517             }
1518             HeapFree( GetProcessHeap(), 0, list );
1519         }
1520     }
1521
1522     if( flags & (SW_INVALIDATE | SW_ERASE) )
1523         RedrawWindow( hwnd, NULL, hrgnUpdate, rdw_flags |
1524                       ((flags & SW_SCROLLCHILDREN) ? RDW_ALLCHILDREN : 0 ) );
1525
1526     if( hrgnWinupd) {
1527         CombineRgn( hrgnUpdate, hrgnUpdate, hrgnWinupd, RGN_OR);
1528         DeleteObject( hrgnWinupd);
1529     }
1530
1531     if( hwndCaret ) {
1532         if ( moveCaret ) SetCaretPos( newCaretPos.x, newCaretPos.y );
1533         ShowCaret(hwndCaret);
1534     }
1535
1536     if( bOwnRgn && hrgnUpdate ) DeleteObject( hrgnUpdate );
1537
1538     return retVal;
1539 }
1540
1541
1542 /*************************************************************************
1543  *              ScrollWindowEx (USER32.@)
1544  *
1545  * Note: contrary to what the doc says, pixels that are scrolled from the
1546  *      outside of clipRect to the inside are NOT painted.
1547  *
1548  */
1549 INT WINAPI ScrollWindowEx( HWND hwnd, INT dx, INT dy,
1550                            const RECT *rect, const RECT *clipRect,
1551                            HRGN hrgnUpdate, LPRECT rcUpdate,
1552                            UINT flags )
1553 {
1554     return scroll_window( hwnd, dx, dy, rect, clipRect, hrgnUpdate, rcUpdate, flags, TRUE );
1555 }
1556
1557 /*************************************************************************
1558  *              ScrollWindow (USER32.@)
1559  *
1560  */
1561 BOOL WINAPI ScrollWindow( HWND hwnd, INT dx, INT dy,
1562                           const RECT *rect, const RECT *clipRect )
1563 {
1564     return scroll_window( hwnd, dx, dy, rect, clipRect, 0, NULL,
1565                           SW_INVALIDATE | SW_ERASE | (rect ? 0 : SW_SCROLLCHILDREN), FALSE ) != ERROR;
1566 }
1567
1568
1569 /*************************************************************************
1570  *              ScrollDC (USER32.@)
1571  *
1572  * dx, dy, lprcScroll and lprcClip are all in logical coordinates (msdn is
1573  * wrong) hrgnUpdate is returned in device coordinates with rcUpdate in
1574  * logical coordinates.
1575  */
1576 BOOL WINAPI ScrollDC( HDC hdc, INT dx, INT dy, const RECT *lprcScroll,
1577                       const RECT *lprcClip, HRGN hrgnUpdate, LPRECT lprcUpdate )
1578
1579 {
1580     return USER_Driver->pScrollDC( hdc, dx, dy, lprcScroll, lprcClip, hrgnUpdate, lprcUpdate );
1581 }
1582
1583 /************************************************************************
1584  *              PrintWindow (USER32.@)
1585  *
1586  */
1587 BOOL WINAPI PrintWindow(HWND hwnd, HDC hdcBlt, UINT nFlags)
1588 {
1589     UINT flags = PRF_CHILDREN | PRF_ERASEBKGND | PRF_OWNED | PRF_CLIENT;
1590     if(!(nFlags & PW_CLIENTONLY))
1591     {
1592         flags |= PRF_NONCLIENT;
1593     }
1594     SendMessageW(hwnd, WM_PRINT, (WPARAM)hdcBlt, flags);
1595     return TRUE;
1596 }