reduce the number of repaintings by repaiting (rect) union of all invalidated areas...
[wxWidgets.git] / src / dfb / toplevel.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/dfb/toplevel.cpp
3 // Purpose: Top level window, abstraction of wxFrame and wxDialog
4 // Author: Vaclav Slavik
5 // Created: 2006-08-10
6 // RCS-ID: $Id$
7 // Copyright: (c) 2006 REA Elektronik GmbH
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13
14 #include "wx/toplevel.h"
15
16 #ifndef WX_PRECOMP
17 #include "wx/app.h"
18 #endif // WX_PRECOMP
19
20 #include "wx/hashmap.h"
21 #include "wx/evtloop.h"
22 #include "wx/dfb/private.h"
23
24 #define TRACE_EVENTS _T("events")
25 #define TRACE_PAINT _T("paint")
26
27 // ============================================================================
28 // globals
29 // ============================================================================
30
31 // mapping of DirectFB windows to wxTLWs:
32 WX_DECLARE_HASH_MAP(DFBWindowID, wxTopLevelWindowDFB*,
33 wxIntegerHash, wxIntegerEqual,
34 wxDfbWindowsMap);
35 static wxDfbWindowsMap gs_dfbWindowsMap;
36
37 // ============================================================================
38 // helpers
39 // ============================================================================
40
41 // Queue of paint requests
42 class wxDfbQueuedPaintRequests
43 {
44 public:
45 ~wxDfbQueuedPaintRequests() { Clear(); }
46
47 // Adds paint request to the queue
48 void Add(const wxRect& rect)
49 {
50 // We use a simple implementation here for now: all refresh requests
51 // are merged together into single rectangle that is superset of
52 // all the requested rectangles. This wastes some blitting and painting
53 // time, but OTOH, EVT_PAINT handler is called only once per window.
54 m_invalidated.Union(rect);
55 }
56
57 // Is the queue empty?
58 bool IsEmpty() const { return m_invalidated.IsEmpty(); }
59
60 // Empties the queue
61 void Clear() { m_invalidated = wxRect(); }
62
63 // Gets the next request in the queue, returns true if there was one,
64 // false if the queue was empty
65 bool GetNext(wxRect& rect)
66 {
67 if ( m_invalidated.IsEmpty() )
68 return false;
69
70 rect = m_invalidated;
71 Clear(); // there's only one item in the queue
72 return true;
73 }
74
75 private:
76 // currently invalidated region
77 wxRect m_invalidated;
78 };
79
80 // ============================================================================
81 // wxTopLevelWindowDFB
82 // ============================================================================
83
84 // ----------------------------------------------------------------------------
85 // creation & destruction
86 // ----------------------------------------------------------------------------
87
88 void wxTopLevelWindowDFB::Init()
89 {
90 m_isShown = false;
91 m_isMaximized = false;
92 m_fsIsShowing = false;
93 m_sizeSet = false;
94 m_opacity = 255;
95 m_toPaint = new wxDfbQueuedPaintRequests;
96 m_isPainting = false;
97 }
98
99 bool wxTopLevelWindowDFB::Create(wxWindow *parent,
100 wxWindowID id,
101 const wxString& title,
102 const wxPoint& posOrig,
103 const wxSize& sizeOrig,
104 long style,
105 const wxString &name)
106 {
107 m_tlw = this;
108
109 // always create a frame of some reasonable, even if arbitrary, size (at
110 // least for MSW compatibility)
111 wxSize size(sizeOrig);
112 if ( size.x == wxDefaultCoord || size.y == wxDefaultCoord )
113 {
114 wxSize sizeDefault = GetDefaultSize();
115 if ( size.x == wxDefaultCoord )
116 size.x = sizeDefault.x;
117 if ( size.y == wxDefaultCoord )
118 size.y = sizeDefault.y;
119 }
120
121 wxPoint pos(posOrig);
122 if ( pos.x == wxDefaultCoord )
123 pos.x = 0;
124 if ( pos.y == wxDefaultCoord )
125 pos.y = 0;
126
127 // create DirectFB window:
128 wxIDirectFBDisplayLayerPtr layer(wxIDirectFB::Get()->GetDisplayLayer());
129 wxCHECK_MSG( layer, false, _T("no display layer") );
130
131 DFBWindowDescription desc;
132 desc.flags = (DFBWindowDescriptionFlags)
133 (DWDESC_CAPS |
134 DWDESC_WIDTH | DWDESC_HEIGHT | DWDESC_POSX | DWDESC_POSY);
135 desc.caps = DWCAPS_DOUBLEBUFFER;
136 desc.posx = pos.x;
137 desc.posy = pos.y;
138 desc.width = size.x;
139 desc.height = size.y;
140 m_dfbwin = layer->CreateWindow(&desc);
141 if ( !layer )
142 return false;
143
144 // add the new TLW to DFBWindowID->wxTLW map:
145 DFBWindowID winid;
146 if ( !m_dfbwin->GetID(&winid) )
147 return false;
148 gs_dfbWindowsMap[winid] = this;
149
150 // TLWs are created initially hidden:
151 if ( !m_dfbwin->SetOpacity(wxALPHA_TRANSPARENT) )
152 return false;
153
154 if ( !wxWindow::Create(NULL, id, pos, size, style, name) )
155 return false;
156
157 SetParent(parent);
158 if ( parent )
159 parent->AddChild(this);
160
161 wxTopLevelWindows.Append(this);
162 m_title = title;
163
164 if ( style & (wxSTAY_ON_TOP | wxPOPUP_WINDOW) )
165 {
166 m_dfbwin->SetStackingClass(DWSC_UPPER);
167 }
168
169 // direct events in this window to the global event buffer:
170 m_dfbwin->AttachEventBuffer(wxEventLoop::GetDirectFBEventBuffer());
171
172 return true;
173 }
174
175 wxTopLevelWindowDFB::~wxTopLevelWindowDFB()
176 {
177 m_isBeingDeleted = true;
178
179 wxTopLevelWindows.DeleteObject(this);
180
181 if ( wxTheApp->GetTopWindow() == this )
182 wxTheApp->SetTopWindow(NULL);
183
184 if ( wxTopLevelWindows.empty() && wxTheApp->GetExitOnFrameDelete() )
185 {
186 wxTheApp->ExitMainLoop();
187 }
188
189 wxDELETE(m_toPaint);
190
191 // remove the TLW from DFBWindowID->wxTLW map:
192 DFBWindowID winid;
193 if ( m_dfbwin->GetID(&winid) )
194 gs_dfbWindowsMap.erase(winid);
195 }
196
197 // ----------------------------------------------------------------------------
198 // window size & position
199 // ----------------------------------------------------------------------------
200
201 void wxTopLevelWindowDFB::DoGetPosition(int *x, int *y) const
202 {
203 m_dfbwin->GetPosition(x, y);
204 }
205
206 void wxTopLevelWindowDFB::DoGetSize(int *width, int *height) const
207 {
208 m_dfbwin->GetSize(width, height);
209 }
210
211 void wxTopLevelWindowDFB::DoMoveWindow(int x, int y, int width, int height)
212 {
213 wxPoint curpos = GetPosition();
214 if ( curpos.x != x || curpos.y != y )
215 {
216 m_dfbwin->MoveTo(x, y);
217 }
218
219 wxSize cursize = GetSize();
220 if ( cursize.x != width || cursize.y != height )
221 {
222 // changing window's size changes its surface:
223 InvalidateDfbSurface();
224
225 m_dfbwin->Resize(width, height);
226
227 // we must repaint the window after it changed size:
228 if ( IsShown() )
229 DoRefreshWindow();
230 }
231 }
232
233 // ----------------------------------------------------------------------------
234 // showing and hiding
235 // ----------------------------------------------------------------------------
236
237 #warning "FIXME: the rest of this file is almost same as for MGL, merge it"
238 bool wxTopLevelWindowDFB::ShowFullScreen(bool show, long style)
239 {
240 if (show == m_fsIsShowing) return false; // return what?
241
242 m_fsIsShowing = show;
243
244 if (show)
245 {
246 m_fsSaveStyle = m_windowStyle;
247 m_fsSaveFlag = style;
248 GetPosition(&m_fsSaveFrame.x, &m_fsSaveFrame.y);
249 GetSize(&m_fsSaveFrame.width, &m_fsSaveFrame.height);
250
251 if ( style & wxFULLSCREEN_NOCAPTION )
252 m_windowStyle &= ~wxCAPTION;
253 if ( style & wxFULLSCREEN_NOBORDER )
254 m_windowStyle = wxSIMPLE_BORDER;
255
256 int x, y;
257 wxDisplaySize(&x, &y);
258 SetSize(0, 0, x, y);
259 }
260 else
261 {
262 m_windowStyle = m_fsSaveStyle;
263 SetSize(m_fsSaveFrame.x, m_fsSaveFrame.y,
264 m_fsSaveFrame.width, m_fsSaveFrame.height);
265 }
266
267 return true;
268 }
269
270 bool wxTopLevelWindowDFB::Show(bool show)
271 {
272 if ( !wxTopLevelWindowBase::Show(show) )
273 return false;
274
275 // hide/show the window by setting its opacity to 0/full:
276 m_dfbwin->SetOpacity(show ? m_opacity : 0);
277
278 // If this is the first time Show was called, send size event,
279 // so that the frame can adjust itself (think auto layout or single child)
280 if ( !m_sizeSet )
281 {
282 m_sizeSet = true;
283 wxSizeEvent event(GetSize(), GetId());
284 event.SetEventObject(this);
285 GetEventHandler()->ProcessEvent(event);
286 }
287
288 if ( show )
289 {
290 wxWindow *focused = wxWindow::FindFocus();
291 if ( focused && focused->GetTLW() == this )
292 {
293 SetDfbFocus();
294 }
295 else if ( AcceptsFocus() )
296 {
297 // FIXME: we should probably always call SetDfbFocus instead
298 // and call SetFocus() from wxActivateEvent/DWET_GOTFOCUS
299 // handler
300 SetFocus();
301 }
302 }
303
304 return true;
305 }
306
307 bool wxTopLevelWindowDFB::SetTransparent(wxByte alpha)
308 {
309 if ( IsShown() )
310 {
311 if ( !m_dfbwin->SetOpacity(alpha) )
312 return false;
313 }
314
315 m_opacity = alpha;
316 return true;
317 }
318
319 // ----------------------------------------------------------------------------
320 // maximize, minimize etc.
321 // ----------------------------------------------------------------------------
322
323 void wxTopLevelWindowDFB::Maximize(bool maximize)
324 {
325 int x, y, w, h;
326 wxClientDisplayRect(&x, &y, &w, &h);
327
328 if ( maximize && !m_isMaximized )
329 {
330 m_isMaximized = true;
331
332 GetPosition(&m_savedFrame.x, &m_savedFrame.y);
333 GetSize(&m_savedFrame.width, &m_savedFrame.height);
334
335 SetSize(x, y, w, h);
336 }
337 else if ( !maximize && m_isMaximized )
338 {
339 m_isMaximized = false;
340 SetSize(m_savedFrame.x, m_savedFrame.y,
341 m_savedFrame.width, m_savedFrame.height);
342 }
343 }
344
345 bool wxTopLevelWindowDFB::IsMaximized() const
346 {
347 return m_isMaximized;
348 }
349
350 void wxTopLevelWindowDFB::Restore()
351 {
352 if ( IsMaximized() )
353 {
354 Maximize(false);
355 }
356 }
357
358 void wxTopLevelWindowDFB::Iconize(bool WXUNUSED(iconize))
359 {
360 wxFAIL_MSG(wxT("Iconize not supported under wxDFB"));
361 }
362
363 bool wxTopLevelWindowDFB::IsIconized() const
364 {
365 return false;
366 }
367
368
369 // ----------------------------------------------------------------------------
370 // surfaces and painting
371 // ----------------------------------------------------------------------------
372
373 wxIDirectFBSurfacePtr wxTopLevelWindowDFB::ObtainDfbSurface() const
374 {
375 return m_dfbwin->GetSurface();
376 }
377
378 void wxTopLevelWindowDFB::HandleQueuedPaintRequests()
379 {
380 if ( m_toPaint->IsEmpty() )
381 return; // nothing to do
382
383 if ( IsFrozen() || !IsShown() )
384 {
385 // nothing to do if the window is frozen or hidden; clear the queue
386 // and return (note that it's OK to clear the queue even if the window
387 // is frozen, because Thaw() calls Refresh()):
388 m_toPaint->Clear();
389 return;
390 }
391
392 // process queued paint requests:
393 wxRect winRect(wxPoint(0, 0), GetSize());
394 wxRect paintedRect;
395
396 // important note: all DCs created from now until m_isPainting is reset to
397 // false will not update the front buffer as this flag indicates that we'll
398 // blit the entire back buffer to front soon
399 m_isPainting = true;
400
401 #ifdef __WXDEBUG__
402 int requestsCount = 0;
403 #endif
404
405 wxRect request;
406 while ( m_toPaint->GetNext(request) )
407 {
408 #ifdef __WXDEBUG__
409 requestsCount++;
410 #endif
411 wxRect clipped(request);
412 clipped.Intersect(winRect);
413 if ( clipped.IsEmpty() )
414 continue; // nothing to refresh
415
416 wxLogTrace(TRACE_PAINT,
417 _T("%p ('%s'): processing paint request [%i,%i,%i,%i]"),
418 this, GetName().c_str(),
419 clipped.x, clipped.y, clipped.GetRight(), clipped.GetBottom());
420
421 PaintWindow(clipped);
422
423 // remember rectangle covering all repainted areas:
424 if ( paintedRect.IsEmpty() )
425 paintedRect = clipped;
426 else
427 paintedRect.Union(clipped);
428 }
429
430 m_isPainting = false;
431
432 m_toPaint->Clear();
433
434 if ( paintedRect.IsEmpty() )
435 return; // no painting occurred, no need to flip
436
437 // Flip the surface to make the changes visible. Note that the rectangle we
438 // flip is *superset* of the union of repainted rectangles (created as
439 // "rectangles union" by wxRect::Union) and so some parts of the back
440 // buffer that we didn't touch in this HandleQueuedPaintRequests call will
441 // be copied to the front buffer as well. This is safe/correct thing to do
442 // *only* because wx always use wxIDirectFBSurface::FlipToFront() and so
443 // the back and front buffers contain the same data.
444 //
445 // Note that we do _not_ split m_toPaint into disjoint rectangles and
446 // do FlipToFront() for each of them, because that could result in visible
447 // updating of the screen; instead, we prefer to flip everything at once.
448
449 DFBRegion r = {paintedRect.GetLeft(), paintedRect.GetTop(),
450 paintedRect.GetRight(), paintedRect.GetBottom()};
451 DFBRegion *rptr = (winRect == paintedRect) ? NULL : &r;
452
453 GetDfbSurface()->FlipToFront(rptr);
454
455 wxLogTrace(TRACE_PAINT,
456 _T("%p ('%s'): processed %i paint requests, flipped surface: [%i,%i,%i,%i]"),
457 this, GetName().c_str(),
458 requestsCount,
459 paintedRect.x, paintedRect.y,
460 paintedRect.GetRight(), paintedRect.GetBottom());
461 }
462
463 void wxTopLevelWindowDFB::DoRefreshRect(const wxRect& rect)
464 {
465 // don't overlap outside of the window (NB: 'rect' is in window coords):
466 wxRect r(rect);
467 r.Intersect(wxRect(GetSize()));
468 if ( r.IsEmpty() )
469 return;
470
471 wxLogTrace(TRACE_PAINT,
472 _T("%p ('%s'): [TLW] refresh rect [%i,%i,%i,%i]"),
473 this, GetName().c_str(),
474 rect.x, rect.y, rect.GetRight(), rect.GetBottom());
475
476 // defer painting until idle time or until Update() is called:
477 m_toPaint->Add(rect);
478 }
479
480 void wxTopLevelWindowDFB::Update()
481 {
482 HandleQueuedPaintRequests();
483 }
484
485 // ---------------------------------------------------------------------------
486 // events handling
487 // ---------------------------------------------------------------------------
488
489 void wxTopLevelWindowDFB::SetDfbFocus()
490 {
491 wxCHECK_RET( IsShown(), _T("cannot set focus to hidden window") );
492 wxASSERT_MSG( FindFocus() && FindFocus()->GetTLW() == this,
493 _T("setting DirectFB focus to unexpected window") );
494
495 GetDirectFBWindow()->RequestFocus();
496 }
497
498 /* static */
499 void wxTopLevelWindowDFB::HandleDFBWindowEvent(const wxDFBWindowEvent& event_)
500 {
501 const DFBWindowEvent& event = event_;
502
503 if ( gs_dfbWindowsMap.find(event.window_id) == gs_dfbWindowsMap.end() )
504 {
505 wxLogTrace(TRACE_EVENTS,
506 _T("received event for unknown DirectFB window, ignoring"));
507 return;
508 }
509
510 wxTopLevelWindowDFB *tlw = gs_dfbWindowsMap[event.window_id];
511 wxWindow *recipient = NULL;
512 void (wxWindow::*handlerFunc)(const wxDFBWindowEvent&) = NULL;
513
514 switch ( event.type )
515 {
516 case DWET_KEYDOWN:
517 case DWET_KEYUP:
518 {
519 recipient = wxWindow::FindFocus();
520 handlerFunc = &wxWindowDFB::HandleKeyEvent;
521 break;
522 }
523
524 case DWET_NONE:
525 case DWET_ALL:
526 {
527 wxFAIL_MSG( _T("invalid event type") );
528 break;
529 }
530 }
531
532 if ( !recipient )
533 {
534 wxLogTrace(TRACE_EVENTS, _T("ignoring event: no recipient window"));
535 return;
536 }
537
538 wxCHECK_RET( recipient && recipient->GetTLW() == tlw,
539 _T("event recipient not in TLW which received the event") );
540
541 // process the event:
542 (recipient->*handlerFunc)(event_);
543 }
544
545 // ---------------------------------------------------------------------------
546 // idle events processing
547 // ---------------------------------------------------------------------------
548
549 void wxTopLevelWindowDFB::OnInternalIdle()
550 {
551 wxTopLevelWindowBase::OnInternalIdle();
552 HandleQueuedPaintRequests();
553 }