1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/x11/window.cpp
3 // Purpose:     wxWindow
4 // Author:      Julian Smart
5 // Modified by:
6 // Created:     17/09/98
7 // Copyright:   (c) Julian Smart
8 // Licence:     wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10 
11 // for compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
13 
14 
15 // ============================================================================
16 // declarations
17 // ============================================================================
18 
19 // ----------------------------------------------------------------------------
20 // headers
21 // ----------------------------------------------------------------------------
22 
23 #include "wx/window.h"
24 
25 #ifndef WX_PRECOMP
26     #include "wx/hash.h"
27     #include "wx/log.h"
28     #include "wx/app.h"
29     #include "wx/utils.h"
30     #include "wx/panel.h"
31     #include "wx/frame.h"
32     #include "wx/dc.h"
33     #include "wx/dcclient.h"
34     #include "wx/button.h"
35     #include "wx/menu.h"
36     #include "wx/dialog.h"
37     #include "wx/timer.h"
38     #include "wx/settings.h"
39     #include "wx/msgdlg.h"
40     #include "wx/scrolbar.h"
41     #include "wx/listbox.h"
42     #include "wx/scrolwin.h"
43     #include "wx/layout.h"
44     #include "wx/menuitem.h"
45     #include "wx/module.h"
46 #endif
47 
48 #include "wx/fontutil.h"
49 #include "wx/univ/renderer.h"
50 
51 #if  wxUSE_DRAG_AND_DROP
52     #include "wx/dnd.h"
53 #endif
54 
55 #include "wx/unix/utilsx11.h"
56 
57 #include "wx/x11/private.h"
58 #include "X11/Xutil.h"
59 
60 #include <string.h>
61 
62 // ----------------------------------------------------------------------------
63 // global variables for this module
64 // ----------------------------------------------------------------------------
65 
66 static wxWindowX11* g_captureWindow = NULL;
67 static GC g_eraseGC;
68 // the window that is about to be focused after currently focused
69 // one looses focus:
70 static wxWindow* gs_toBeFocusedWindow = NULL;
71 
72 // ----------------------------------------------------------------------------
73 // macros
74 // ----------------------------------------------------------------------------
75 
76 #define event_left_is_down(x) ((x)->xbutton.state & Button1Mask)
77 #define event_middle_is_down(x) ((x)->xbutton.state & Button2Mask)
78 #define event_right_is_down(x) ((x)->xbutton.state & Button3Mask)
79 
80 // ----------------------------------------------------------------------------
81 // event tables
82 // ----------------------------------------------------------------------------
83 
84 wxIMPLEMENT_ABSTRACT_CLASS(wxWindowX11, wxWindowBase);
85 
86 wxBEGIN_EVENT_TABLE(wxWindowX11, wxWindowBase)
87     EVT_SYS_COLOUR_CHANGED(wxWindowX11::OnSysColourChanged)
88 wxEND_EVENT_TABLE()
89 
90 // ============================================================================
91 // implementation
92 // ============================================================================
93 
94 // ----------------------------------------------------------------------------
95 // helper functions
96 // ----------------------------------------------------------------------------
97 
98 namespace
99 {
100 
101 // Passing size with a 0 component to X11 functions results in a BadValue X
102 // error, so ensure we never do it by using the smallest valid size instead.
EnsureValidXWindowSize(int & x,int & y)103 inline void EnsureValidXWindowSize(int& x, int& y)
104 {
105     if ( x <= 0 )
106         x = 1;
107     if ( y <= 0 )
108         y = 1;
109 }
110 
EnsureValidXWindowSize(wxSize & size)111 inline void EnsureValidXWindowSize(wxSize& size)
112 {
113     EnsureValidXWindowSize(size.x, size.y);
114 }
115 
116 } // anonymous namespace
117 
118 // ----------------------------------------------------------------------------
119 // constructors
120 // ----------------------------------------------------------------------------
121 
Init()122 void wxWindowX11::Init()
123 {
124     // X11-specific
125     m_mainWindow = (WXWindow) 0;
126     m_clientWindow = (WXWindow) 0;
127     m_insertIntoMain = false;
128     m_updateNcArea = false;
129 
130     m_winCaptured = false;
131     m_needsInputFocus = false;
132     m_isShown = true;
133     m_lastTS = 0;
134     m_lastButton = 0;
135 }
136 
137 // real construction (Init() must have been called before!)
Create(wxWindow * parent,wxWindowID id,const wxPoint & pos,const wxSize & size,long style,const wxString & name)138 bool wxWindowX11::Create(wxWindow *parent, wxWindowID id,
139                          const wxPoint& pos,
140                          const wxSize& size,
141                          long style,
142                          const wxString& name)
143 {
144     wxCHECK_MSG( parent, false, wxT("can't create wxWindow without parent") );
145 
146     // Get default border
147     wxBorder border = GetBorder(style);
148     style &= ~wxBORDER_MASK;
149     style |= border;
150 
151     CreateBase(parent, id, pos, size, style, wxDefaultValidator, name);
152 
153     parent->AddChild(this);
154 
155     Display *xdisplay = (Display*) wxGlobalDisplay();
156     int xscreen = DefaultScreen( xdisplay );
157     Visual *xvisual = DefaultVisual( xdisplay, xscreen );
158     Colormap cm = DefaultColormap( xdisplay, xscreen );
159 
160     m_backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
161     m_backgroundColour.CalcPixel( (WXColormap) cm );
162 
163     m_foregroundColour = *wxBLACK;
164     m_foregroundColour.CalcPixel( (WXColormap) cm );
165 
166     Window xparent = (Window) parent->GetClientAreaWindow();
167 
168     // Add window's own scrollbars to main window, not to client window
169     if (parent->GetInsertIntoMain())
170     {
171         // wxLogDebug( "Inserted into main: %s", GetName().c_str() );
172         xparent = (Window) parent->X11GetMainWindow();
173     }
174 
175     wxSize size2(size);
176     EnsureValidXWindowSize(size2);
177 
178     wxPoint pos2(pos);
179     if (pos2.x == wxDefaultCoord)
180         pos2.x = 0;
181     if (pos2.y == wxDefaultCoord)
182         pos2.y = 0;
183 
184     AdjustForParentClientOrigin(pos2.x, pos2.y);
185 
186 #if wxUSE_TWO_WINDOWS
187     bool need_two_windows =
188         ((( wxSUNKEN_BORDER | wxBORDER_THEME | wxRAISED_BORDER | wxSIMPLE_BORDER | wxHSCROLL | wxVSCROLL ) & m_windowStyle) != 0);
189 #else
190     bool need_two_windows = false;
191 #endif
192 
193 #if !wxUSE_NANOX
194     XSetWindowAttributes xattributes;
195     long xattributes_mask = 0;
196 
197     xattributes_mask |= CWBackPixel;
198     xattributes.background_pixel = m_backgroundColour.GetPixel();
199 
200     xattributes_mask |= CWBorderPixel;
201     xattributes.border_pixel = BlackPixel( xdisplay, xscreen );
202 
203     xattributes_mask |= CWEventMask;
204 #endif
205 
206     if (need_two_windows)
207     {
208 #if wxUSE_NANOX
209         long backColor, foreColor;
210         backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue());
211         foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue());
212 
213         Window xwindow = XCreateWindowWithColor( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
214                                     0, 0, InputOutput, xvisual, backColor, foreColor);
215         XSelectInput( xdisplay, xwindow,
216           GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
217           ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
218           KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
219                       PropertyChangeMask );
220 
221 #else
222         // Normal X11
223         xattributes.event_mask =
224             ExposureMask | StructureNotifyMask | ColormapChangeMask;
225 
226         Window xwindow = XCreateWindow( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
227             0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes );
228 
229 #endif
230 
231         XSetWindowBackgroundPixmap( xdisplay, xwindow, None );
232 
233         m_mainWindow = (WXWindow) xwindow;
234         wxAddWindowToTable( xwindow, (wxWindow*) this );
235 
236         XMapWindow( xdisplay, xwindow );
237 
238 #if !wxUSE_NANOX
239         xattributes.event_mask =
240             ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
241             ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
242             KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
243             PropertyChangeMask | VisibilityChangeMask ;
244 
245         if (!HasFlag( wxFULL_REPAINT_ON_RESIZE ))
246         {
247             xattributes_mask |= CWBitGravity;
248             xattributes.bit_gravity = StaticGravity;
249         }
250 #endif
251 
252         if (HasFlag(wxSUNKEN_BORDER) || HasFlag(wxRAISED_BORDER) || HasFlag(wxBORDER_THEME))
253         {
254             pos2.x = 2;
255             pos2.y = 2;
256             size2.x -= 4;
257             size2.y -= 4;
258         }
259         else if (HasFlag( wxSIMPLE_BORDER ))
260         {
261             pos2.x = 1;
262             pos2.y = 1;
263             size2.x -= 2;
264             size2.y -= 2;
265         }
266         else
267         {
268             pos2.x = 0;
269             pos2.y = 0;
270         }
271 
272         // Make again sure the size is nonzero.
273         EnsureValidXWindowSize(size2);
274 
275 #if wxUSE_NANOX
276         backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue());
277         foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue());
278 
279         xwindow = XCreateWindowWithColor( xdisplay, xwindow, pos2.x, pos2.y, size2.x, size2.y,
280                                     0, 0, InputOutput, xvisual, backColor, foreColor);
281         XSelectInput( xdisplay, xwindow,
282           GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
283           ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
284           KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
285                       PropertyChangeMask );
286 
287 #else
288         xwindow = XCreateWindow( xdisplay, xwindow, pos2.x, pos2.y, size2.x, size2.y,
289             0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes );
290 #endif
291 
292         XSetWindowBackgroundPixmap( xdisplay, xwindow, None );
293 
294         m_clientWindow = (WXWindow) xwindow;
295         wxAddClientWindowToTable( xwindow, (wxWindow*) this );
296 
297         XMapWindow( xdisplay, xwindow );
298     }
299     else
300     {
301         // wxLogDebug( "No two windows needed %s", GetName().c_str() );
302 #if wxUSE_NANOX
303         long backColor, foreColor;
304         backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue());
305         foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue());
306 
307         Window xwindow = XCreateWindowWithColor( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
308                                     0, 0, InputOutput, xvisual, backColor, foreColor);
309         XSelectInput( xdisplay, xwindow,
310           GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
311           ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
312           KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
313                       PropertyChangeMask );
314 
315 #else
316         xattributes.event_mask =
317             ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
318             ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
319             KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
320             PropertyChangeMask | VisibilityChangeMask ;
321 
322         if (!HasFlag( wxFULL_REPAINT_ON_RESIZE ))
323         {
324             xattributes_mask |= CWBitGravity;
325             xattributes.bit_gravity = NorthWestGravity;
326         }
327 
328         Window xwindow = XCreateWindow( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
329             0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes );
330 #endif
331 
332         XSetWindowBackgroundPixmap( xdisplay, xwindow, None );
333 
334         m_mainWindow = (WXWindow) xwindow;
335         m_clientWindow = m_mainWindow;
336         wxAddWindowToTable( xwindow, (wxWindow*) this );
337 
338         XMapWindow( xdisplay, xwindow );
339     }
340 
341     // Is a subwindow, so map immediately
342     m_isShown = true;
343 
344     // Without this, the cursor may not be restored properly (e.g. in splitter
345     // sample).
346     SetCursor(*wxSTANDARD_CURSOR);
347     SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
348 
349     // Don't call this, it can have nasty repercussions for composite controls,
350     // for example
351     //    SetSize(pos.x, pos.y, size.x, size.y);
352 
353     return true;
354 }
355 
356 // Destructor
~wxWindowX11()357 wxWindowX11::~wxWindowX11()
358 {
359     SendDestroyEvent();
360 
361     if (g_captureWindow == this)
362         g_captureWindow = NULL;
363 
364     if ( DoFindFocus() == this )
365         KillFocus();
366 
367     DestroyChildren();
368 
369     if (m_clientWindow != m_mainWindow)
370     {
371         // Destroy the client window
372         Window xwindow = (Window) m_clientWindow;
373         wxDeleteClientWindowFromTable( xwindow );
374         XDestroyWindow( wxGlobalDisplay(), xwindow );
375         m_clientWindow = NULL;
376     }
377 
378     // Destroy the window
379     if ( m_mainWindow )
380     {
381         Window xwindow = (Window) m_mainWindow;
382         wxDeleteWindowFromTable( xwindow );
383         XDestroyWindow( wxGlobalDisplay(), xwindow );
384         m_mainWindow = NULL;
385     }
386 }
387 
388 // ---------------------------------------------------------------------------
389 // basic operations
390 // ---------------------------------------------------------------------------
391 
SetFocus()392 void wxWindowX11::SetFocus()
393 {
394     Window xwindow = (Window) m_clientWindow;
395 
396     wxCHECK_RET( xwindow, wxT("invalid window") );
397 
398     // Don't assert; we might be trying to set the focus for a panel
399     // with only static controls, so the panel returns false from AcceptsFocus.
400     // The app should be not be expected to deal with this.
401     if (!AcceptsFocus())
402         return;
403 
404     wxWindow* focusedWindow = DoFindFocus();
405 
406     if ( focusedWindow == (wxWindow*)this )
407         return; // nothing to do, focused already
408 
409     if ( focusedWindow )
410     {
411         gs_toBeFocusedWindow = (wxWindow*)this;
412         focusedWindow->KillFocus();
413         gs_toBeFocusedWindow = NULL;
414     }
415 
416 #if 0
417     if (GetName() == "scrollBar")
418     {
419         char *crash = NULL;
420         *crash = 0;
421     }
422 #endif
423 
424     XWindowAttributes wa;
425     XGetWindowAttributes(wxGlobalDisplay(), xwindow, &wa);
426 
427     if (wa.map_state == IsViewable)
428     {
429         wxLogTrace( wxT("focus"), wxT("wxWindowX11::SetFocus: %s"), GetClassInfo()->GetClassName());
430         //        XSetInputFocus( wxGlobalDisplay(), xwindow, RevertToParent, CurrentTime );
431         XSetInputFocus( wxGlobalDisplay(), xwindow, RevertToNone, CurrentTime );
432         m_needsInputFocus = false;
433     }
434     else
435     {
436         m_needsInputFocus = true;
437     }
438 
439     // notify the parent keeping track of focus for the kbd navigation
440     // purposes that we got it
441     wxChildFocusEvent eventFocus((wxWindow*)this);
442     HandleWindowEvent(eventFocus);
443 
444     wxFocusEvent event(wxEVT_SET_FOCUS, GetId());
445     event.SetEventObject(this);
446     event.SetWindow((wxWindow*)xwindow);
447     HandleWindowEvent(event);
448 
449 }
450 
451 // Kill focus
KillFocus()452 void wxWindowX11::KillFocus()
453 {
454     wxCHECK_RET( DoFindFocus() == this,
455                  "killing focus on window that doesn't have it" );
456 
457     if ( m_isBeingDeleted )
458         return; // don't send any events from dtor
459 
460     wxFocusEvent event(wxEVT_KILL_FOCUS, GetId());
461     event.SetEventObject(this);
462     event.SetWindow(gs_toBeFocusedWindow);
463     HandleWindowEvent(event);
464 }
465 
466 // Get the window with the focus
DoFindFocus()467 wxWindow *wxWindowBase::DoFindFocus()
468 {
469     Window xfocus = (Window) 0;
470     int revert = 0;
471 
472     XGetInputFocus( wxGlobalDisplay(), &xfocus, &revert);
473     if (xfocus)
474     {
475         wxWindow *win = wxGetWindowFromTable( xfocus );
476         if (!win)
477         {
478             win = wxGetClientWindowFromTable( xfocus );
479         }
480 
481         return win;
482     }
483 
484     return NULL;
485 }
486 
487 // Enabling/disabling handled by event loop, and not sending events
488 // if disabled.
Enable(bool enable)489 bool wxWindowX11::Enable(bool enable)
490 {
491     if ( !wxWindowBase::Enable(enable) )
492         return false;
493 
494     return true;
495 }
496 
Show(bool show)497 bool wxWindowX11::Show(bool show)
498 {
499     wxWindowBase::Show(show);
500 
501     Window xwindow = (Window) m_mainWindow;
502     Display *xdisp = wxGlobalDisplay();
503     if (show)
504     {
505         // wxLogDebug( "Mapping window of type %s", GetName().c_str() );
506         XMapWindow(xdisp, xwindow);
507     }
508     else
509     {
510         // wxLogDebug( "Unmapping window of type %s", GetName().c_str() );
511         XUnmapWindow(xdisp, xwindow);
512     }
513 
514     return true;
515 }
516 
517 // Raise the window to the top of the Z order
Raise()518 void wxWindowX11::Raise()
519 {
520     if (m_mainWindow)
521         XRaiseWindow( wxGlobalDisplay(), (Window) m_mainWindow );
522 }
523 
524 // Lower the window to the bottom of the Z order
Lower()525 void wxWindowX11::Lower()
526 {
527     if (m_mainWindow)
528         XLowerWindow( wxGlobalDisplay(), (Window) m_mainWindow );
529 }
530 
DoCaptureMouse()531 void wxWindowX11::DoCaptureMouse()
532 {
533     if ((g_captureWindow != NULL) && (g_captureWindow != this))
534     {
535         wxFAIL_MSG(wxT("Trying to capture before mouse released."));
536 
537         // Core dump now
538         int *tmp = NULL;
539         (*tmp) = 1;
540         return;
541     }
542 
543     if (m_winCaptured)
544         return;
545 
546     Window xwindow = (Window) m_clientWindow;
547 
548     wxCHECK_RET( xwindow, wxT("invalid window") );
549 
550     g_captureWindow = (wxWindow*) this;
551 
552     if (xwindow)
553     {
554         int res = XGrabPointer(wxGlobalDisplay(), xwindow,
555             FALSE,
556             ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
557             GrabModeAsync,
558             GrabModeAsync,
559             None,
560             None, /* cursor */ // TODO: This may need to be set to the cursor of this window
561             CurrentTime );
562 
563         if (res != GrabSuccess)
564         {
565             wxString msg;
566             msg.Printf(wxT("Failed to grab pointer for window %s"), this->GetClassInfo()->GetClassName());
567             wxLogDebug(msg);
568             if (res == GrabNotViewable)
569             {
570                 wxLogDebug( wxT("This is not a viewable window - perhaps not shown yet?") );
571             }
572 
573             g_captureWindow = NULL;
574             return;
575         }
576 
577         m_winCaptured = true;
578     }
579 }
580 
DoReleaseMouse()581 void wxWindowX11::DoReleaseMouse()
582 {
583     g_captureWindow = NULL;
584 
585     if ( !m_winCaptured )
586         return;
587 
588     Window xwindow = (Window) m_clientWindow;
589 
590     if (xwindow)
591     {
592         XUngrabPointer( wxGlobalDisplay(), CurrentTime );
593     }
594 
595     // wxLogDebug( "Ungrabbed pointer in %s", GetName().c_str() );
596 
597     m_winCaptured = false;
598 }
599 
SetFont(const wxFont & font)600 bool wxWindowX11::SetFont(const wxFont& font)
601 {
602     if ( !wxWindowBase::SetFont(font) )
603     {
604         // nothing to do
605         return false;
606     }
607 
608     return true;
609 }
610 
SetCursor(const wxCursor & cursor)611 bool wxWindowX11::SetCursor(const wxCursor& cursor)
612 {
613     if ( !wxWindowBase::SetCursor(cursor) )
614     {
615         // no change
616         return false;
617     }
618 
619     Window xwindow = (Window) m_clientWindow;
620 
621     wxCHECK_MSG( xwindow, false, wxT("invalid window") );
622 
623     wxCursor cursorToUse;
624     if (m_cursor.IsOk())
625         cursorToUse = m_cursor;
626     else
627         cursorToUse = *wxSTANDARD_CURSOR;
628 
629     Cursor xcursor = (Cursor) cursorToUse.GetCursor();
630 
631     XDefineCursor( wxGlobalDisplay(), xwindow, xcursor );
632 
633     return true;
634 }
635 
636 // Coordinates relative to the window
WarpPointer(int x,int y)637 void wxWindowX11::WarpPointer (int x, int y)
638 {
639     Window xwindow = (Window) m_clientWindow;
640 
641     wxCHECK_RET( xwindow, wxT("invalid window") );
642 
643     XWarpPointer( wxGlobalDisplay(), None, xwindow, 0, 0, 0, 0, x, y);
644 }
645 
646 // Does a physical scroll
ScrollWindow(int dx,int dy,const wxRect * rect)647 void wxWindowX11::ScrollWindow(int dx, int dy, const wxRect *rect)
648 {
649     // No scrolling requested.
650     if ((dx == 0) && (dy == 0)) return;
651 
652     if (!m_updateRegion.IsEmpty())
653     {
654         m_updateRegion.Offset( dx, dy );
655 
656         int cw = 0;
657         int ch = 0;
658         GetSize( &cw, &ch );  // GetClientSize() ??
659         m_updateRegion.Intersect( 0, 0, cw, ch );
660     }
661 
662     if (!m_clearRegion.IsEmpty())
663     {
664         m_clearRegion.Offset( dx, dy );
665 
666         int cw = 0;
667         int ch = 0;
668         GetSize( &cw, &ch );  // GetClientSize() ??
669         m_clearRegion.Intersect( 0, 0, cw, ch );
670     }
671 
672     Window xwindow = (Window) GetClientAreaWindow();
673 
674     wxCHECK_RET( xwindow, wxT("invalid window") );
675 
676     Display *xdisplay = wxGlobalDisplay();
677 
678     GC xgc = XCreateGC( xdisplay, xwindow, 0, NULL );
679     XSetGraphicsExposures( xdisplay, xgc, True );
680 
681     int s_x = 0;
682     int s_y = 0;
683     int cw;
684     int ch;
685     if (rect)
686     {
687         s_x = rect->x;
688         s_y = rect->y;
689 
690         cw = rect->width;
691         ch = rect->height;
692     }
693     else
694     {
695         s_x = 0;
696         s_y = 0;
697         GetClientSize( &cw, &ch );
698     }
699 
700 #if wxUSE_TWO_WINDOWS
701     wxPoint offset( 0,0 );
702 #else
703     wxPoint offset = GetClientAreaOrigin();
704     s_x += offset.x;
705     s_y += offset.y;
706 #endif
707 
708     int w = cw - abs(dx);
709     int h = ch - abs(dy);
710 
711     if ((h < 0) || (w < 0))
712     {
713         Refresh();
714     }
715     else
716     {
717         wxRect rect;
718         if (dx < 0) rect.x = cw+dx + offset.x; else rect.x = s_x;
719         if (dy < 0) rect.y = ch+dy + offset.y; else rect.y = s_y;
720         if (dy != 0) rect.width = cw; else rect.width = abs(dx);
721         if (dx != 0) rect.height = ch; else rect.height = abs(dy);
722 
723         int d_x = s_x;
724         int d_y = s_y;
725 
726         if (dx < 0) s_x += -dx;
727         if (dy < 0) s_y += -dy;
728         if (dx > 0) d_x += dx + offset.x;
729         if (dy > 0) d_y += dy + offset.y;
730 
731         XCopyArea( xdisplay, xwindow, xwindow, xgc, s_x, s_y, w, h, d_x, d_y );
732 
733         // wxLogDebug( "Copy: s_x %d s_y %d w %d h %d d_x %d d_y %d", s_x, s_y, w, h, d_x, d_y );
734 
735         // wxLogDebug( "Update: %d %d %d %d", rect.x, rect.y, rect.width, rect.height );
736 
737         m_updateRegion.Union( rect );
738         m_clearRegion.Union( rect );
739     }
740 
741     XFreeGC( xdisplay, xgc );
742 
743     // Move Clients, but not the scrollbars
744     // FIXME: There may be a better method to move a lot of Windows within X11
745     wxScrollBar *sbH = ((wxWindow *) this)->GetScrollbar( wxHORIZONTAL );
746     wxScrollBar *sbV = ((wxWindow *) this)->GetScrollbar( wxVERTICAL );
747     wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
748     while ( node )
749     {
750         // Only propagate to non-top-level windows
751         wxWindow *win = node->GetData();
752         if ( win->GetParent() && win != sbH && win != sbV )
753         {
754             wxPoint pos = win->GetPosition();
755             // Add the delta to the old Position
756             pos.x += dx;
757             pos.y += dy;
758             win->SetPosition(pos);
759         }
760         node = node->GetNext();
761     }
762 }
763 
764 // ---------------------------------------------------------------------------
765 // drag and drop
766 // ---------------------------------------------------------------------------
767 
768 #if wxUSE_DRAG_AND_DROP
769 
SetDropTarget(wxDropTarget * WXUNUSED (pDropTarget))770 void wxWindowX11::SetDropTarget(wxDropTarget * WXUNUSED(pDropTarget))
771 {
772     // TODO
773 }
774 
775 #endif
776 
777 // Old style file-manager drag&drop
DragAcceptFiles(bool WXUNUSED (accept))778 void wxWindowX11::DragAcceptFiles(bool WXUNUSED(accept))
779 {
780     // TODO
781 }
782 
783 // ----------------------------------------------------------------------------
784 // tooltips
785 // ----------------------------------------------------------------------------
786 
787 #if wxUSE_TOOLTIPS
788 
DoSetToolTip(wxToolTip * WXUNUSED (tooltip))789 void wxWindowX11::DoSetToolTip(wxToolTip * WXUNUSED(tooltip))
790 {
791     // TODO
792 }
793 
794 #endif // wxUSE_TOOLTIPS
795 
796 // ---------------------------------------------------------------------------
797 // moving and resizing
798 // ---------------------------------------------------------------------------
799 
PreResize()800 bool wxWindowX11::PreResize()
801 {
802     return true;
803 }
804 
805 // Get total size
DoGetSize(int * x,int * y) const806 void wxWindowX11::DoGetSize(int *x, int *y) const
807 {
808     Window xwindow = (Window) m_mainWindow;
809 
810     wxCHECK_RET( xwindow, wxT("invalid window") );
811 
812     //XSync(wxGlobalDisplay(), False);
813 
814     XWindowAttributes attr;
815     Status status = XGetWindowAttributes( wxGlobalDisplay(), xwindow, &attr );
816     wxASSERT(status);
817 
818     if (status)
819     {
820         *x = attr.width /* + 2*m_borderSize */ ;
821         *y = attr.height /* + 2*m_borderSize */ ;
822     }
823 }
824 
DoGetPosition(int * x,int * y) const825 void wxWindowX11::DoGetPosition(int *x, int *y) const
826 {
827     Window window = (Window) m_mainWindow;
828     if (window)
829     {
830         //XSync(wxGlobalDisplay(), False);
831         XWindowAttributes attr;
832         Status status = XGetWindowAttributes(wxGlobalDisplay(), window, & attr);
833         wxASSERT(status);
834 
835         if (status)
836         {
837             *x = attr.x;
838             *y = attr.y;
839 
840             // We may be faking the client origin. So a window that's really at (0, 30)
841             // may appear (to wxWin apps) to be at (0, 0).
842             if (GetParent())
843             {
844                 wxPoint pt(GetParent()->GetClientAreaOrigin());
845                 *x -= pt.x;
846                 *y -= pt.y;
847             }
848         }
849     }
850 }
851 
DoScreenToClient(int * x,int * y) const852 void wxWindowX11::DoScreenToClient(int *x, int *y) const
853 {
854     Display *display = wxGlobalDisplay();
855     Window rootWindow = RootWindowOfScreen(DefaultScreenOfDisplay(display));
856     Window thisWindow = (Window) m_clientWindow;
857 
858     Window childWindow;
859     int xx = x ? *x : 0;
860     int yy = y ? *y : 0;
861     XTranslateCoordinates(display, rootWindow, thisWindow,
862                           xx, yy, x ? x : &xx, y ? y : &yy,
863                           &childWindow);
864 }
865 
DoClientToScreen(int * x,int * y) const866 void wxWindowX11::DoClientToScreen(int *x, int *y) const
867 {
868     Display *display = wxGlobalDisplay();
869     Window rootWindow = RootWindowOfScreen(DefaultScreenOfDisplay(display));
870     Window thisWindow = (Window) m_clientWindow;
871 
872     Window childWindow;
873     int xx = x ? *x : 0;
874     int yy = y ? *y : 0;
875     XTranslateCoordinates(display, thisWindow, rootWindow,
876                           xx, yy, x ? x : &xx, y ? y : &yy,
877                           &childWindow);
878 }
879 
880 
881 // Get size *available for subwindows* i.e. excluding menu bar etc.
DoGetClientSize(int * x,int * y) const882 void wxWindowX11::DoGetClientSize(int *x, int *y) const
883 {
884     Window window = (Window) m_mainWindow;
885 
886     if (window)
887     {
888         XWindowAttributes attr;
889         Status status = XGetWindowAttributes( wxGlobalDisplay(), window, &attr );
890         wxASSERT(status);
891 
892         if (status)
893         {
894             *x = attr.width ;
895             *y = attr.height ;
896         }
897     }
898 }
899 
DoSetSize(int x,int y,int width,int height,int sizeFlags)900 void wxWindowX11::DoSetSize(int x, int y, int width, int height, int sizeFlags)
901 {
902     //    wxLogDebug("DoSetSize: %s (%ld) %d, %d %dx%d", GetClassInfo()->GetClassName(), GetId(), x, y, width, height);
903 
904     Window xwindow = (Window) m_mainWindow;
905 
906     wxCHECK_RET( xwindow, wxT("invalid window") );
907 
908     XWindowAttributes attr;
909     Status status = XGetWindowAttributes( wxGlobalDisplay(), xwindow, &attr );
910     wxCHECK_RET( status, wxT("invalid window attributes") );
911 
912     int new_x = attr.x;
913     int new_y = attr.y;
914     int new_w = attr.width;
915     int new_h = attr.height;
916 
917     if (x != wxDefaultCoord || (sizeFlags & wxSIZE_ALLOW_MINUS_ONE))
918     {
919         int yy = 0;
920         AdjustForParentClientOrigin( x, yy, sizeFlags);
921         new_x = x;
922     }
923     if (y != wxDefaultCoord || (sizeFlags & wxSIZE_ALLOW_MINUS_ONE))
924     {
925         int xx = 0;
926         AdjustForParentClientOrigin( xx, y, sizeFlags);
927         new_y = y;
928     }
929     if (width != wxDefaultCoord)
930     {
931         new_w = width;
932     }
933     if (height != wxDefaultCoord)
934     {
935         new_h = height;
936     }
937 
938     EnsureValidXWindowSize(new_w, new_h);
939     DoMoveWindow( new_x, new_y, new_w, new_h );
940 }
941 
DoSetClientSize(int width,int height)942 void wxWindowX11::DoSetClientSize(int width, int height)
943 {
944     //    wxLogDebug("DoSetClientSize: %s (%ld) %dx%d", GetClassInfo()->GetClassName(), GetId(), width, height);
945 
946     Window xwindow = (Window) m_mainWindow;
947 
948     wxCHECK_RET( xwindow, wxT("invalid window") );
949 
950     EnsureValidXWindowSize(width, height);
951     XResizeWindow( wxGlobalDisplay(), xwindow, width, height );
952 
953     if (m_mainWindow != m_clientWindow)
954     {
955         xwindow = (Window) m_clientWindow;
956 
957         wxWindow *window = (wxWindow*) this;
958         wxRenderer *renderer = window->GetRenderer();
959         if (renderer)
960         {
961             wxRect border = renderer->GetBorderDimensions( (wxBorder)(m_windowStyle & wxBORDER_MASK) );
962             width -= border.x + border.width;
963             height -= border.y + border.height;
964         }
965 
966         EnsureValidXWindowSize(width, height);
967         XResizeWindow( wxGlobalDisplay(), xwindow, width, height );
968     }
969 }
970 
DoMoveWindow(int x,int y,int width,int height)971 void wxWindowX11::DoMoveWindow(int x, int y, int width, int height)
972 {
973     Window xwindow = (Window) m_mainWindow;
974 
975     wxCHECK_RET( xwindow, wxT("invalid window") );
976 
977 #if !wxUSE_NANOX
978 
979     XMoveResizeWindow( wxGlobalDisplay(), xwindow, x, y, width, height );
980     if (m_mainWindow != m_clientWindow)
981     {
982         xwindow = (Window) m_clientWindow;
983 
984         wxWindow *window = (wxWindow*) this;
985         wxRenderer *renderer = window->GetRenderer();
986         if (renderer)
987         {
988             wxRect border = renderer->GetBorderDimensions( (wxBorder)(m_windowStyle & wxBORDER_MASK) );
989             x = border.x;
990             y = border.y;
991             width -= border.x + border.width;
992             height -= border.y + border.height;
993         }
994         else
995         {
996             x = 0;
997             y = 0;
998         }
999 
1000         wxScrollBar *sb = window->GetScrollbar( wxHORIZONTAL );
1001         if (sb && sb->IsShown())
1002         {
1003             wxSize size = sb->GetSize();
1004             height -= size.y;
1005         }
1006         sb = window->GetScrollbar( wxVERTICAL );
1007         if (sb && sb->IsShown())
1008         {
1009             wxSize size = sb->GetSize();
1010             width -= size.x;
1011         }
1012 
1013         XMoveResizeWindow( wxGlobalDisplay(), xwindow, x, y, wxMax(1, width), wxMax(1, height) );
1014     }
1015 
1016 #else
1017 
1018     XWindowChanges windowChanges;
1019     windowChanges.x = x;
1020     windowChanges.y = y;
1021     windowChanges.width = width;
1022     windowChanges.height = height;
1023     windowChanges.stack_mode = 0;
1024     int valueMask = CWX | CWY | CWWidth | CWHeight;
1025 
1026     XConfigureWindow( wxGlobalDisplay(), xwindow, valueMask, &windowChanges );
1027 
1028 #endif
1029 }
1030 
DoSetSizeHints(int minW,int minH,int maxW,int maxH,int incW,int incH)1031 void wxWindowX11::DoSetSizeHints(int minW, int minH, int maxW, int maxH, int incW, int incH)
1032 {
1033     m_minWidth = minW;
1034     m_minHeight = minH;
1035     m_maxWidth = maxW;
1036     m_maxHeight = maxH;
1037 
1038 #if !wxUSE_NANOX
1039     XSizeHints sizeHints;
1040     sizeHints.flags = 0;
1041 
1042     if (minW > -1 && minH > -1)
1043     {
1044         sizeHints.flags |= PMinSize;
1045         sizeHints.min_width = minW;
1046         sizeHints.min_height = minH;
1047     }
1048     if (maxW > -1 && maxH > -1)
1049     {
1050         sizeHints.flags |= PMaxSize;
1051         sizeHints.max_width = maxW;
1052         sizeHints.max_height = maxH;
1053     }
1054     if (incW > -1 && incH > -1)
1055     {
1056         sizeHints.flags |= PResizeInc;
1057         sizeHints.width_inc = incW;
1058         sizeHints.height_inc = incH;
1059     }
1060 
1061     XSetWMNormalHints(wxGlobalDisplay(), (Window) m_mainWindow, &sizeHints );
1062 #endif
1063 }
1064 
1065 // ---------------------------------------------------------------------------
1066 // text metrics
1067 // ---------------------------------------------------------------------------
1068 
GetCharHeight() const1069 int wxWindowX11::GetCharHeight() const
1070 {
1071     wxFont font(GetFont());
1072     wxCHECK_MSG( font.IsOk(), 0, wxT("valid window font needed") );
1073 
1074 #if wxUSE_UNICODE
1075     // There should be an easier way.
1076     PangoLayout *layout = pango_layout_new( wxTheApp->GetPangoContext() );
1077     pango_layout_set_font_description( layout, font.GetNativeFontInfo()->description );
1078     pango_layout_set_text(layout, "H", 1 );
1079     int w,h;
1080     pango_layout_get_pixel_size(layout, &w, &h);
1081     g_object_unref( G_OBJECT( layout ) );
1082 
1083     return h;
1084 #else
1085     WXFontStructPtr pFontStruct = font.GetFontStruct(1.0, wxGlobalDisplay());
1086 
1087     int direction, ascent, descent;
1088     XCharStruct overall;
1089     XTextExtents ((XFontStruct*) pFontStruct, "x", 1, &direction, &ascent,
1090         &descent, &overall);
1091 
1092     //  return (overall.ascent + overall.descent);
1093     return (ascent + descent);
1094 #endif
1095 }
1096 
GetCharWidth() const1097 int wxWindowX11::GetCharWidth() const
1098 {
1099     wxFont font(GetFont());
1100     wxCHECK_MSG( font.IsOk(), 0, wxT("valid window font needed") );
1101 
1102 #if wxUSE_UNICODE
1103     // There should be an easier way.
1104     PangoLayout *layout = pango_layout_new( wxTheApp->GetPangoContext() );
1105     pango_layout_set_font_description( layout, font.GetNativeFontInfo()->description );
1106     pango_layout_set_text(layout, "H", 1 );
1107     int w,h;
1108     pango_layout_get_pixel_size(layout, &w, &h);
1109     g_object_unref( G_OBJECT( layout ) );
1110 
1111     return w;
1112 #else
1113     WXFontStructPtr pFontStruct = font.GetFontStruct(1.0, wxGlobalDisplay());
1114 
1115     int direction, ascent, descent;
1116     XCharStruct overall;
1117     XTextExtents ((XFontStruct*) pFontStruct, "x", 1, &direction, &ascent,
1118         &descent, &overall);
1119 
1120     return overall.width;
1121 #endif
1122 }
1123 
DoGetTextExtent(const wxString & string,int * x,int * y,int * descent,int * externalLeading,const wxFont * theFont) const1124 void wxWindowX11::DoGetTextExtent(const wxString& string,
1125                                   int *x, int *y,
1126                                   int *descent,
1127                                   int *externalLeading,
1128                                   const wxFont *theFont) const
1129 {
1130     wxFont fontToUse = GetFont();
1131     if (theFont) fontToUse = *theFont;
1132 
1133     wxCHECK_RET( fontToUse.IsOk(), wxT("invalid font") );
1134 
1135     if (string.empty())
1136     {
1137         if (x) (*x) = 0;
1138         if (y) (*y) = 0;
1139         return;
1140     }
1141 
1142 #if wxUSE_UNICODE
1143     PangoLayout *layout = pango_layout_new( wxTheApp->GetPangoContext() );
1144 
1145     PangoFontDescription *desc = fontToUse.GetNativeFontInfo()->description;
1146     pango_layout_set_font_description(layout, desc);
1147 
1148     const wxCharBuffer data = wxConvUTF8.cWC2MB( string.wc_str() );
1149     pango_layout_set_text(layout, (const char*) data, strlen( (const char*) data ));
1150 
1151     PangoLayoutLine *line = (PangoLayoutLine *)pango_layout_get_lines(layout)->data;
1152 
1153 
1154     PangoRectangle rect;
1155     pango_layout_line_get_extents(line, NULL, &rect);
1156 
1157     if (x) (*x) = (wxCoord) (rect.width / PANGO_SCALE);
1158     if (y) (*y) = (wxCoord) (rect.height / PANGO_SCALE);
1159     if (descent)
1160     {
1161         // Do something about metrics here
1162         (*descent) = 0;
1163     }
1164     if (externalLeading) (*externalLeading) = 0;  // ??
1165 
1166     g_object_unref( G_OBJECT( layout ) );
1167 #else
1168     WXFontStructPtr pFontStruct = fontToUse.GetFontStruct(1.0, wxGlobalDisplay());
1169 
1170     int direction, ascent, descent2;
1171     XCharStruct overall;
1172     int slen = string.length();
1173 
1174     XTextExtents((XFontStruct*) pFontStruct, (const char*) string.c_str(), slen,
1175                  &direction, &ascent, &descent2, &overall);
1176 
1177     if ( x )
1178         *x = (overall.width);
1179     if ( y )
1180         *y = (ascent + descent2);
1181     if (descent)
1182         *descent = descent2;
1183     if (externalLeading)
1184         *externalLeading = 0;
1185 #endif
1186 }
1187 
1188 // ----------------------------------------------------------------------------
1189 // painting
1190 // ----------------------------------------------------------------------------
1191 
Refresh(bool eraseBack,const wxRect * rect)1192 void wxWindowX11::Refresh(bool eraseBack, const wxRect *rect)
1193 {
1194     if (eraseBack)
1195     {
1196         if (rect)
1197         {
1198             // Schedule for later Updating in ::Update() or ::OnInternalIdle().
1199             m_clearRegion.Union( rect->x, rect->y, rect->width, rect->height );
1200         }
1201         else
1202         {
1203             int height,width;
1204             GetSize( &width, &height );
1205 
1206             // Schedule for later Updating in ::Update() or ::OnInternalIdle().
1207             m_clearRegion.Clear();
1208             m_clearRegion.Union( 0, 0, width, height );
1209         }
1210     }
1211 
1212     if (rect)
1213     {
1214          // Schedule for later Updating in ::Update() or ::OnInternalIdle().
1215          m_updateRegion.Union( rect->x, rect->y, rect->width, rect->height );
1216     }
1217     else
1218     {
1219         int height,width;
1220         GetSize( &width, &height );
1221 
1222         // Schedule for later Updating in ::Update() or ::OnInternalIdle().
1223         m_updateRegion.Clear();
1224         m_updateRegion.Union( 0, 0, width, height );
1225     }
1226 }
1227 
Update()1228 void wxWindowX11::Update()
1229 {
1230     if (m_updateNcArea)
1231     {
1232         // wxLogDebug("wxWindowX11::UpdateNC: %s", GetClassInfo()->GetClassName());
1233         // Send nc paint events.
1234         SendNcPaintEvents();
1235     }
1236 
1237     if (!m_updateRegion.IsEmpty())
1238     {
1239         // wxLogDebug("wxWindowX11::Update: %s", GetClassInfo()->GetClassName());
1240         // Actually send erase events.
1241         SendEraseEvents();
1242 
1243         // Actually send paint events.
1244         SendPaintEvents();
1245     }
1246 }
1247 
SendEraseEvents()1248 void wxWindowX11::SendEraseEvents()
1249 {
1250     if (m_clearRegion.IsEmpty()) return;
1251 
1252     wxClientDC dc( (wxWindow*)this );
1253     dc.SetDeviceClippingRegion( m_clearRegion );
1254 
1255     wxEraseEvent erase_event( GetId(), &dc );
1256     erase_event.SetEventObject( this );
1257 
1258     if (!HandleWindowEvent(erase_event) )
1259     {
1260         Display *xdisplay = wxGlobalDisplay();
1261         Window xwindow = (Window) GetClientAreaWindow();
1262         XSetForeground( xdisplay, g_eraseGC, m_backgroundColour.GetPixel() );
1263 
1264         wxRegionIterator upd( m_clearRegion );
1265         while (upd)
1266         {
1267             XFillRectangle( xdisplay, xwindow, g_eraseGC,
1268                             upd.GetX(), upd.GetY(), upd.GetWidth(), upd.GetHeight() );
1269             upd ++;
1270         }
1271     }
1272 
1273     m_clearRegion.Clear();
1274 }
1275 
SendPaintEvents()1276 void wxWindowX11::SendPaintEvents()
1277 {
1278     //    wxLogDebug("SendPaintEvents: %s (%ld)", GetClassInfo()->GetClassName(), GetId());
1279 
1280     m_clipPaintRegion = true;
1281 
1282     wxPaintEvent paint_event( this );
1283     HandleWindowEvent( paint_event );
1284 
1285     m_updateRegion.Clear();
1286 
1287     m_clipPaintRegion = false;
1288 }
1289 
SendNcPaintEvents()1290 void wxWindowX11::SendNcPaintEvents()
1291 {
1292     wxWindow *window = (wxWindow*) this;
1293 
1294     // All this for drawing the small square between the scrollbars.
1295     int width = 0;
1296     int height = 0;
1297     int x = 0;
1298     int y = 0;
1299     wxScrollBar *sb = window->GetScrollbar( wxHORIZONTAL );
1300     if (sb && sb->IsShown())
1301     {
1302         height = sb->GetSize().y;
1303         y = sb->GetPosition().y;
1304 
1305         sb = window->GetScrollbar( wxVERTICAL );
1306         if (sb && sb->IsShown())
1307         {
1308             width = sb->GetSize().x;
1309             x = sb->GetPosition().x;
1310 
1311             Display *xdisplay = wxGlobalDisplay();
1312             Window xwindow = (Window) X11GetMainWindow();
1313             Colormap cm = (Colormap) wxTheApp->GetMainColormap( wxGetDisplay() );
1314             wxColour colour = wxSystemSettings::GetColour(wxSYS_COLOUR_APPWORKSPACE);
1315             colour.CalcPixel( (WXColormap) cm );
1316 
1317             XSetForeground( xdisplay, g_eraseGC, colour.GetPixel() );
1318 
1319             XFillRectangle( xdisplay, xwindow, g_eraseGC, x, y, width, height );
1320         }
1321     }
1322 
1323     wxNcPaintEvent nc_paint_event( this );
1324     HandleWindowEvent( nc_paint_event );
1325 
1326     m_updateNcArea = false;
1327 }
1328 
1329 // ----------------------------------------------------------------------------
1330 // event handlers
1331 // ----------------------------------------------------------------------------
1332 
1333 // Responds to colour changes: passes event on to children.
OnSysColourChanged(wxSysColourChangedEvent & event)1334 void wxWindowX11::OnSysColourChanged(wxSysColourChangedEvent& event)
1335 {
1336     wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
1337     while ( node )
1338     {
1339         // Only propagate to non-top-level windows
1340         wxWindow *win = node->GetData();
1341         if ( win->GetParent() )
1342         {
1343             wxSysColourChangedEvent event2;
1344             event.SetEventObject(win);
1345             win->HandleWindowEvent(event2);
1346         }
1347 
1348         node = node->GetNext();
1349     }
1350 }
1351 
1352 // See handler for InFocus case in app.cpp for details.
1353 wxWindow* g_GettingFocus = NULL;
1354 
OnInternalIdle()1355 void wxWindowX11::OnInternalIdle()
1356 {
1357     // Update invalidated regions.
1358     Update();
1359 
1360     wxWindowBase::OnInternalIdle();
1361 
1362     // Set the input focus if couldn't do it before
1363     if (m_needsInputFocus)
1364     {
1365 #if 0
1366         wxString msg;
1367         msg.Printf("Setting focus for %s from OnInternalIdle\n", GetClassInfo()->GetClassName());
1368         printf(msg.c_str());
1369 #endif
1370         SetFocus();
1371 
1372         // If it couldn't set the focus now, there's
1373         // no point in trying again.
1374         m_needsInputFocus = false;
1375     }
1376     g_GettingFocus = NULL;
1377 }
1378 
1379 // ----------------------------------------------------------------------------
1380 // function which maintain the global hash table mapping Widgets to wxWidgets
1381 // ----------------------------------------------------------------------------
1382 
DoAddWindowToTable(wxWindowHash * hash,Window w,wxWindow * win)1383 static bool DoAddWindowToTable(wxWindowHash *hash, Window w, wxWindow *win)
1384 {
1385     if ( !hash->insert(wxWindowHash::value_type(w, win)).second )
1386     {
1387         wxLogDebug( wxT("Widget table clash: new widget is 0x%08x, %s"),
1388                     (unsigned int)w, win->GetClassInfo()->GetClassName());
1389         return false;
1390     }
1391 
1392     wxLogTrace( wxT("widget"), wxT("XWindow 0x%08x <-> window %p (%s)"),
1393                 (unsigned int) w, win, win->GetClassInfo()->GetClassName());
1394 
1395     return true;
1396 }
1397 
DoGetWindowFromTable(wxWindowHash * hash,Window w)1398 static inline wxWindow *DoGetWindowFromTable(wxWindowHash *hash, Window w)
1399 {
1400     wxWindowHash::iterator i = hash->find(w);
1401     return i == hash->end() ? NULL : i->second;
1402 }
1403 
DoDeleteWindowFromTable(wxWindowHash * hash,Window w)1404 static inline void DoDeleteWindowFromTable(wxWindowHash *hash, Window w)
1405 {
1406     wxLogTrace( wxT("widget"), wxT("XWindow 0x%08x deleted"), (unsigned int) w);
1407 
1408     hash->erase(w);
1409 }
1410 
1411 // ----------------------------------------------------------------------------
1412 // public wrappers
1413 // ----------------------------------------------------------------------------
1414 
wxAddWindowToTable(Window w,wxWindow * win)1415 bool wxAddWindowToTable(Window w, wxWindow *win)
1416 {
1417     return DoAddWindowToTable(wxWidgetHashTable, w, win);
1418 }
1419 
wxGetWindowFromTable(Window w)1420 wxWindow *wxGetWindowFromTable(Window w)
1421 {
1422     return DoGetWindowFromTable(wxWidgetHashTable, w);
1423 }
1424 
wxDeleteWindowFromTable(Window w)1425 void wxDeleteWindowFromTable(Window w)
1426 {
1427     DoDeleteWindowFromTable(wxWidgetHashTable, w);
1428 }
1429 
wxAddClientWindowToTable(Window w,wxWindow * win)1430 bool wxAddClientWindowToTable(Window w, wxWindow *win)
1431 {
1432     return DoAddWindowToTable(wxClientWidgetHashTable, w, win);
1433 }
1434 
wxGetClientWindowFromTable(Window w)1435 wxWindow *wxGetClientWindowFromTable(Window w)
1436 {
1437     return DoGetWindowFromTable(wxClientWidgetHashTable, w);
1438 }
1439 
wxDeleteClientWindowFromTable(Window w)1440 void wxDeleteClientWindowFromTable(Window w)
1441 {
1442     DoDeleteWindowFromTable(wxClientWidgetHashTable, w);
1443 }
1444 
1445 // ----------------------------------------------------------------------------
1446 // X11-specific accessors
1447 // ----------------------------------------------------------------------------
1448 
X11GetMainWindow() const1449 WXWindow wxWindowX11::X11GetMainWindow() const
1450 {
1451     return m_mainWindow;
1452 }
1453 
GetClientAreaWindow() const1454 WXWindow wxWindowX11::GetClientAreaWindow() const
1455 {
1456     return m_clientWindow;
1457 }
1458 
1459 // ----------------------------------------------------------------------------
1460 // TranslateXXXEvent() functions
1461 // ----------------------------------------------------------------------------
1462 
wxTranslateMouseEvent(wxMouseEvent & wxevent,wxWindow * win,Window WXUNUSED (window),XEvent * xevent)1463 bool wxTranslateMouseEvent(wxMouseEvent& wxevent,
1464                            wxWindow *win,
1465                            Window WXUNUSED(window),
1466                            XEvent *xevent)
1467 {
1468     switch (XEventGetType(xevent))
1469     {
1470         case EnterNotify:
1471         case LeaveNotify:
1472         case ButtonPress:
1473         case ButtonRelease:
1474         case MotionNotify:
1475         {
1476             wxEventType eventType = wxEVT_NULL;
1477 
1478             if (XEventGetType(xevent) == EnterNotify)
1479             {
1480                 //if (local_event.xcrossing.mode!=NotifyNormal)
1481                 //  return ; // Ignore grab events
1482                 eventType = wxEVT_ENTER_WINDOW;
1483                 //            canvas->GetEventHandler()->OnSetFocus();
1484             }
1485             else if (XEventGetType(xevent) == LeaveNotify)
1486             {
1487                 //if (local_event.xcrossingr.mode!=NotifyNormal)
1488                 //  return ; // Ignore grab events
1489                 eventType = wxEVT_LEAVE_WINDOW;
1490                 //            canvas->GetEventHandler()->OnKillFocus();
1491             }
1492             else if (XEventGetType(xevent) == MotionNotify)
1493             {
1494                 eventType = wxEVT_MOTION;
1495             }
1496             else if (XEventGetType(xevent) == ButtonPress)
1497             {
1498                 wxevent.SetTimestamp(XButtonEventGetTime(xevent));
1499                 int button = 0;
1500                 if (XButtonEventLChanged(xevent))
1501                 {
1502                     eventType = wxEVT_LEFT_DOWN;
1503                     button = 1;
1504                 }
1505                 else if (XButtonEventMChanged(xevent))
1506                 {
1507                     eventType = wxEVT_MIDDLE_DOWN;
1508                     button = 2;
1509                 }
1510                 else if (XButtonEventRChanged(xevent))
1511                 {
1512                     eventType = wxEVT_RIGHT_DOWN;
1513                     button = 3;
1514                 }
1515                 else if ( xevent->xbutton.button == Button4 ||
1516                             xevent->xbutton.button == Button5 )
1517                 {
1518                     // this is the same value as used under wxMSW
1519                     static const int WHEEL_DELTA = 120;
1520 
1521                     eventType = wxEVT_MOUSEWHEEL;
1522                     button = xevent->xbutton.button;
1523 
1524                     wxevent.m_linesPerAction = 3;
1525                     wxevent.m_columnsPerAction = 3;
1526                     wxevent.m_wheelDelta = WHEEL_DELTA;
1527 
1528                     // Button 4 means mousewheel up, 5 means down
1529                     wxevent.m_wheelRotation = button == Button4 ? WHEEL_DELTA
1530                                                                 : -WHEEL_DELTA;
1531                 }
1532 
1533                 // check for a double click
1534                 // TODO: where can we get this value from?
1535                 //long dclickTime = XtGetMultiClickTime(wxGlobalDisplay());
1536                 long dclickTime = 200;
1537                 long ts = wxevent.GetTimestamp();
1538 
1539                 int buttonLast = win->GetLastClickedButton();
1540                 long lastTS = win->GetLastClickTime();
1541                 if ( buttonLast && buttonLast == button && (ts - lastTS) < dclickTime )
1542                 {
1543                     // I have a dclick
1544                     win->SetLastClick(0, ts);
1545                     if ( eventType == wxEVT_LEFT_DOWN )
1546                         eventType = wxEVT_LEFT_DCLICK;
1547                     else if ( eventType == wxEVT_MIDDLE_DOWN )
1548                         eventType = wxEVT_MIDDLE_DCLICK;
1549                     else if ( eventType == wxEVT_RIGHT_DOWN )
1550                         eventType = wxEVT_RIGHT_DCLICK;
1551                 }
1552                 else
1553                 {
1554                     // not fast enough or different button
1555                     win->SetLastClick(button, ts);
1556                 }
1557             }
1558             else if (XEventGetType(xevent) == ButtonRelease)
1559             {
1560                 if (XButtonEventLChanged(xevent))
1561                 {
1562                     eventType = wxEVT_LEFT_UP;
1563                 }
1564                 else if (XButtonEventMChanged(xevent))
1565                 {
1566                     eventType = wxEVT_MIDDLE_UP;
1567                 }
1568                 else if (XButtonEventRChanged(xevent))
1569                 {
1570                     eventType = wxEVT_RIGHT_UP;
1571                 }
1572                 else return false;
1573             }
1574             else
1575             {
1576                 return false;
1577             }
1578 
1579             wxevent.SetEventType(eventType);
1580 
1581             wxevent.m_x = XButtonEventGetX(xevent);
1582             wxevent.m_y = XButtonEventGetY(xevent);
1583 
1584             wxevent.m_leftDown = ((eventType == wxEVT_LEFT_DOWN)
1585                 || (XButtonEventLIsDown(xevent)
1586                 && (eventType != wxEVT_LEFT_UP)));
1587             wxevent.m_middleDown = ((eventType == wxEVT_MIDDLE_DOWN)
1588                 || (XButtonEventMIsDown(xevent)
1589                 && (eventType != wxEVT_MIDDLE_UP)));
1590             wxevent.m_rightDown = ((eventType == wxEVT_RIGHT_DOWN)
1591                 || (XButtonEventRIsDown (xevent)
1592                 && (eventType != wxEVT_RIGHT_UP)));
1593 
1594             wxevent.m_shiftDown = XButtonEventShiftIsDown(xevent);
1595             wxevent.m_controlDown = XButtonEventCtrlIsDown(xevent);
1596             wxevent.m_altDown = XButtonEventAltIsDown(xevent);
1597             wxevent.m_metaDown = XButtonEventMetaIsDown(xevent);
1598 
1599             wxevent.SetId(win->GetId());
1600             wxevent.SetEventObject(win);
1601 
1602             return true;
1603         }
1604     }
1605     return false;
1606 }
1607 
wxTranslateKeyEvent(wxKeyEvent & wxevent,wxWindow * win,Window WXUNUSED (win),XEvent * xevent,bool isAscii)1608 bool wxTranslateKeyEvent(wxKeyEvent& wxevent, wxWindow *win, Window WXUNUSED(win), XEvent *xevent, bool isAscii)
1609 {
1610     switch (XEventGetType(xevent))
1611     {
1612     case KeyPress:
1613     case KeyRelease:
1614         {
1615             char buf[20];
1616 
1617             KeySym keySym;
1618             (void) XLookupString ((XKeyEvent *) xevent, buf, 20, &keySym, NULL);
1619 #if wxUSE_UNICODE
1620             int id = wxUnicodeCharXToWX(keySym);
1621 #else
1622             int id = wxCharCodeXToWX(keySym);
1623 #endif
1624             // id may be WXK_xxx code - these are outside ASCII range, so we
1625             // can't just use toupper() on id.
1626             // Only change this if we want the raw key that was pressed,
1627             // and don't change it if we want an ASCII value.
1628             if (!isAscii && (id >= 'a' && id <= 'z'))
1629             {
1630                 id = id + 'A' - 'a';
1631             }
1632 
1633             wxevent.m_shiftDown = XKeyEventShiftIsDown(xevent);
1634             wxevent.m_controlDown = XKeyEventCtrlIsDown(xevent);
1635             wxevent.m_altDown = XKeyEventAltIsDown(xevent);
1636             wxevent.m_metaDown = XKeyEventMetaIsDown(xevent);
1637             wxevent.SetEventObject(win);
1638 #if wxUSE_UNICODE
1639             wxevent.m_uniChar = id;
1640 #endif
1641             wxevent.m_keyCode = id;
1642 
1643             wxevent.SetTimestamp(XKeyEventGetTime(xevent));
1644 
1645             wxevent.m_x = XKeyEventGetX(xevent);
1646             wxevent.m_y = XKeyEventGetY(xevent);
1647 
1648             return id > -1;
1649         }
1650     default:
1651         break;
1652     }
1653     return false;
1654 }
1655 
1656 // ----------------------------------------------------------------------------
1657 // Colour stuff
1658 // ----------------------------------------------------------------------------
1659 
SetBackgroundColour(const wxColour & col)1660 bool wxWindowX11::SetBackgroundColour(const wxColour& col)
1661 {
1662     if ( !wxWindowBase::SetBackgroundColour(col) )
1663         return false;
1664 
1665     if ( !m_backgroundColour.IsOk() )
1666     {
1667         // Reset to the default colour as we must have a valid background.
1668         m_backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
1669     }
1670 
1671     Display *xdisplay = (Display*) wxGlobalDisplay();
1672     int xscreen = DefaultScreen( xdisplay );
1673     Colormap cm = DefaultColormap( xdisplay, xscreen );
1674 
1675     m_backgroundColour.CalcPixel( (WXColormap) cm );
1676 
1677     // We don't set the background colour as we paint
1678     // the background ourselves.
1679     // XSetWindowBackground( xdisplay, (Window) m_clientWindow, m_backgroundColour.GetPixel() );
1680 
1681     return true;
1682 }
1683 
SetForegroundColour(const wxColour & col)1684 bool wxWindowX11::SetForegroundColour(const wxColour& col)
1685 {
1686     if ( !wxWindowBase::SetForegroundColour(col) )
1687         return false;
1688 
1689     return true;
1690 }
1691 
1692 // ----------------------------------------------------------------------------
1693 // global functions
1694 // ----------------------------------------------------------------------------
1695 
wxGetActiveWindow()1696 wxWindow *wxGetActiveWindow()
1697 {
1698     return wxGetTopLevelParent(wxWindow::FindFocus());
1699 }
1700 
1701 /* static */
GetCapture()1702 wxWindow *wxWindowBase::GetCapture()
1703 {
1704     return (wxWindow *)g_captureWindow;
1705 }
1706 
1707 
1708 // Find the wxWindow at the current mouse position, returning the mouse
1709 // position.
wxFindWindowAtPointer(wxPoint & pt)1710 wxWindow* wxFindWindowAtPointer(wxPoint& pt)
1711 {
1712     pt = wxGetMousePosition();
1713     return wxFindWindowAtPoint(pt);
1714 }
1715 
wxGetMouseState(int & rootX,int & rootY,unsigned & maskReturn)1716 void wxGetMouseState(int& rootX, int& rootY, unsigned& maskReturn)
1717 {
1718 #if wxUSE_NANOX
1719     /* TODO */
1720     rootX = rootY = 0;
1721     maskReturn = 0;
1722 #else
1723     Display *display = wxGlobalDisplay();
1724     Window rootWindow = RootWindowOfScreen (DefaultScreenOfDisplay(display));
1725     Window rootReturn, childReturn;
1726     int winX, winY;
1727 
1728     XQueryPointer (display,
1729                    rootWindow,
1730                    &rootReturn,
1731                    &childReturn,
1732                    &rootX, &rootY, &winX, &winY, &maskReturn);
1733 #endif
1734 }
1735 
1736 // Get the current mouse position.
wxGetMousePosition()1737 wxPoint wxGetMousePosition()
1738 {
1739     int x, y;
1740     unsigned mask;
1741 
1742     wxGetMouseState(x, y, mask);
1743     return wxPoint(x, y);
1744 }
1745 
wxGetMouseState()1746 wxMouseState wxGetMouseState()
1747 {
1748     wxMouseState ms;
1749     int x, y;
1750     unsigned mask;
1751 
1752     wxGetMouseState(x, y, mask);
1753 
1754     ms.SetX(x);
1755     ms.SetY(y);
1756 
1757     ms.SetLeftDown(mask & Button1Mask);
1758     ms.SetMiddleDown(mask & Button2Mask);
1759     ms.SetRightDown(mask & Button3Mask);
1760 
1761     ms.SetControlDown(mask & ControlMask);
1762     ms.SetShiftDown(mask & ShiftMask);
1763     ms.SetAltDown(mask & Mod3Mask);
1764     ms.SetMetaDown(mask & Mod1Mask);
1765 
1766     return ms;
1767 }
1768 
1769 
1770 // ----------------------------------------------------------------------------
1771 // wxNoOptimize: switch off size optimization
1772 // ----------------------------------------------------------------------------
1773 
1774 int wxNoOptimize::ms_count = 0;
1775 
1776 
1777 // ----------------------------------------------------------------------------
1778 // wxDCModule
1779 // ----------------------------------------------------------------------------
1780 
1781 class wxWinModule : public wxModule
1782 {
1783 public:
wxWinModule()1784     wxWinModule()
1785     {
1786         // we must be cleaned up before the display is closed
1787         AddDependency(wxClassInfo::FindClass(wxT("wxX11DisplayModule")));
1788     }
1789 
1790     virtual bool OnInit();
1791     virtual void OnExit();
1792 
1793 private:
1794     wxDECLARE_DYNAMIC_CLASS(wxWinModule);
1795 };
1796 
1797 wxIMPLEMENT_DYNAMIC_CLASS(wxWinModule, wxModule);
1798 
OnInit()1799 bool wxWinModule::OnInit()
1800 {
1801     Display *xdisplay = wxGlobalDisplay();
1802     if ( !xdisplay )
1803     {
1804         // This module may be linked into a console program when using
1805         // monolithic library and in this case it's perfectly normal not to
1806         // have a display, so just return without doing anything and avoid
1807         // crashing below.
1808         return true;
1809     }
1810 
1811     int xscreen = DefaultScreen( xdisplay );
1812     Window xroot = RootWindow( xdisplay, xscreen );
1813     g_eraseGC = XCreateGC( xdisplay, xroot, 0, NULL );
1814     XSetFillStyle( xdisplay, g_eraseGC, FillSolid );
1815 
1816     return true;
1817 }
1818 
OnExit()1819 void wxWinModule::OnExit()
1820 {
1821     Display *xdisplay = wxGlobalDisplay();
1822     XFreeGC( xdisplay, g_eraseGC );
1823 }
1824