MutexGui calls in WakeUpIdle are not needed under GTK2, fixing the long-standing...
[wxWidgets.git] / src / gtk / app.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: app.cpp
3 // Purpose:
4 // Author: Robert Roebling
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling, Julian Smart
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
11 #pragma implementation "app.h"
12 #endif
13
14 #ifdef __VMS
15 // vms_jackets.h should for proper working be included before anything else
16 # include <vms_jackets.h>
17 #undef ConnectionNumber
18 #endif
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #include "wx/app.h"
24 #include "wx/gdicmn.h"
25 #include "wx/utils.h"
26 #include "wx/intl.h"
27 #include "wx/log.h"
28 #include "wx/memory.h"
29 #include "wx/font.h"
30 #include "wx/settings.h"
31 #include "wx/dialog.h"
32 #include "wx/msgdlg.h"
33 #include "wx/file.h"
34 #include "wx/filename.h"
35 #include "wx/module.h"
36 #include "wx/image.h"
37
38 #ifdef __WXGPE__
39 #include <gpe/init.h>
40 #endif
41
42 #ifdef __WXUNIVERSAL__
43 #include "wx/univ/theme.h"
44 #include "wx/univ/renderer.h"
45 #endif
46
47 #if wxUSE_THREADS
48 #include "wx/thread.h"
49 #endif
50
51 #include <unistd.h>
52
53 #ifdef HAVE_POLL
54 #if defined(__VMS)
55 #include <poll.h>
56 #else
57 // bug in the OpenBSD headers: at least in 3.1 there is no extern "C"
58 // in neither poll.h nor sys/poll.h which results in link errors later
59 #ifdef __OPENBSD__
60 extern "C"
61 {
62 #endif
63
64 #include <sys/poll.h>
65
66 #ifdef __OPENBSD__
67 };
68 #endif
69 #endif // platform
70 #else // !HAVE_POLL
71 // we implement poll() ourselves using select() which is supposed exist in
72 // all modern Unices
73 #include <sys/types.h>
74 #include <sys/time.h>
75 #include <unistd.h>
76 #endif // HAVE_POLL/!HAVE_POLL
77
78 #include "wx/gtk/win_gtk.h"
79
80 #include <gtk/gtk.h>
81
82
83 //-----------------------------------------------------------------------------
84 // global data
85 //-----------------------------------------------------------------------------
86
87 bool g_mainThreadLocked = FALSE;
88 gint g_pendingTag = 0;
89
90 static GtkWidget *gs_RootWindow = (GtkWidget*) NULL;
91
92 //-----------------------------------------------------------------------------
93 // idle system
94 //-----------------------------------------------------------------------------
95
96 extern bool g_isIdle;
97
98 void wxapp_install_idle_handler();
99
100 //-----------------------------------------------------------------------------
101 // wxYield
102 //-----------------------------------------------------------------------------
103
104 // not static because used by textctrl.cpp
105 //
106 // MT-FIXME
107 bool wxIsInsideYield = FALSE;
108
109 bool wxApp::Yield(bool onlyIfNeeded)
110 {
111 if ( wxIsInsideYield )
112 {
113 if ( !onlyIfNeeded )
114 {
115 wxFAIL_MSG( wxT("wxYield called recursively" ) );
116 }
117
118 return FALSE;
119 }
120
121 #if wxUSE_THREADS
122 if ( !wxThread::IsMain() )
123 {
124 // can't call gtk_main_iteration() from other threads like this
125 return TRUE;
126 }
127 #endif // wxUSE_THREADS
128
129 wxIsInsideYield = TRUE;
130
131 if (!g_isIdle)
132 {
133 // We need to remove idle callbacks or the loop will
134 // never finish.
135 gtk_idle_remove( m_idleTag );
136 m_idleTag = 0;
137 g_isIdle = TRUE;
138 }
139
140 // disable log flushing from here because a call to wxYield() shouldn't
141 // normally result in message boxes popping up &c
142 wxLog::Suspend();
143
144 while (gtk_events_pending())
145 gtk_main_iteration();
146
147 // It's necessary to call ProcessIdle() to update the frames sizes which
148 // might have been changed (it also will update other things set from
149 // OnUpdateUI() which is a nice (and desired) side effect). But we
150 // call ProcessIdle() only once since this is not meant for longish
151 // background jobs (controlled by wxIdleEvent::RequestMore() and the
152 // return value of Processidle().
153 ProcessIdle();
154
155 // let the logs be flashed again
156 wxLog::Resume();
157
158 wxIsInsideYield = FALSE;
159
160 return TRUE;
161 }
162
163 //-----------------------------------------------------------------------------
164 // wxWakeUpIdle
165 //-----------------------------------------------------------------------------
166
167 // RR/KH: The wxMutexGui calls are not needed on GTK2 according to
168 // the GTK faq, http://www.gtk.org/faq/#AEN500
169 // The calls to gdk_threads_enter() and leave() are specifically noted
170 // as not being necessary. The MutexGui calls are still left in for GTK1.
171 // Eliminating the MutexGui calls fixes the long-standing "random" lockup
172 // when using wxPostEvent (which calls WakeUpIdle) from a thread.
173
174 void wxApp::WakeUpIdle()
175 {
176 #ifndef __WXGTK20__
177 #if wxUSE_THREADS
178 if (!wxThread::IsMain())
179 wxMutexGuiEnter();
180 #endif // wxUSE_THREADS_
181 #endif // __WXGTK2__
182
183 if (g_isIdle)
184 wxapp_install_idle_handler();
185
186 #ifndef __WXGTK20__
187 #if wxUSE_THREADS
188 if (!wxThread::IsMain())
189 wxMutexGuiLeave();
190 #endif // wxUSE_THREADS_
191 #endif // __WXGTK2__
192 }
193
194 //-----------------------------------------------------------------------------
195 // local functions
196 //-----------------------------------------------------------------------------
197
198 // the callback functions must be extern "C" to comply with GTK+ declarations
199 extern "C"
200 {
201
202 static gint wxapp_pending_callback( gpointer WXUNUSED(data) )
203 {
204 if (!wxTheApp) return TRUE;
205
206 // When getting called from GDK's time-out handler
207 // we are no longer within GDK's grab on the GUI
208 // thread so we must lock it here ourselves.
209 gdk_threads_enter();
210
211 // Sent idle event to all who request them.
212 wxTheApp->ProcessPendingEvents();
213
214 g_pendingTag = 0;
215
216 // Flush the logged messages if any.
217 #if wxUSE_LOG
218 wxLog::FlushActive();
219 #endif // wxUSE_LOG
220
221 // Release lock again
222 gdk_threads_leave();
223
224 // Return FALSE to indicate that no more idle events are
225 // to be sent (single shot instead of continuous stream)
226 return FALSE;
227 }
228
229 static gint wxapp_idle_callback( gpointer WXUNUSED(data) )
230 {
231 if (!wxTheApp)
232 return TRUE;
233
234 #ifdef __WXDEBUG__
235 // don't generate the idle events while the assert modal dialog is shown,
236 // this completely confuses the apps which don't expect to be reentered
237 // from some safely-looking functions
238 if ( wxTheApp->IsInAssert() )
239 {
240 // But repaint the assertion message if necessary
241 if (wxTopLevelWindows.GetCount() > 0)
242 {
243 wxWindow* win = (wxWindow*) wxTopLevelWindows.GetLast()->GetData();
244 #ifdef __WXGTK20__
245 if (win->IsKindOf(CLASSINFO(wxMessageDialog)))
246 #else
247 if (win->IsKindOf(CLASSINFO(wxGenericMessageDialog)))
248 #endif
249 win->OnInternalIdle();
250 }
251 return TRUE;
252 }
253 #endif // __WXDEBUG__
254
255 // When getting called from GDK's time-out handler
256 // we are no longer within GDK's grab on the GUI
257 // thread so we must lock it here ourselves.
258 gdk_threads_enter();
259
260 // Indicate that we are now in idle mode and event handlers
261 // will have to reinstall the idle handler again.
262 g_isIdle = TRUE;
263 wxTheApp->m_idleTag = 0;
264
265 // Send idle event to all who request them as long as
266 // no events have popped up in the event queue.
267 while (wxTheApp->ProcessIdle() && (gtk_events_pending() == 0))
268 ;
269
270 // Release lock again
271 gdk_threads_leave();
272
273 // Return FALSE to indicate that no more idle events are
274 // to be sent (single shot instead of continuous stream).
275 return FALSE;
276 }
277
278 #if wxUSE_THREADS
279
280 #ifdef HAVE_POLL
281 #define wxPoll poll
282 #define wxPollFd pollfd
283 #else // !HAVE_POLL
284
285 typedef GPollFD wxPollFd;
286
287 int wxPoll(wxPollFd *ufds, unsigned int nfds, int timeout)
288 {
289 // convert timeout from ms to struct timeval (s/us)
290 timeval tv_timeout;
291 tv_timeout.tv_sec = timeout/1000;
292 tv_timeout.tv_usec = (timeout%1000)*1000;
293
294 // remember the highest fd used here
295 int fdMax = -1;
296
297 // and fill the sets for select()
298 fd_set readfds;
299 fd_set writefds;
300 fd_set exceptfds;
301 FD_ZERO(&readfds);
302 FD_ZERO(&writefds);
303 FD_ZERO(&exceptfds);
304
305 unsigned int i;
306 for ( i = 0; i < nfds; i++ )
307 {
308 wxASSERT_MSG( ufds[i].fd < FD_SETSIZE, _T("fd out of range") );
309
310 if ( ufds[i].events & G_IO_IN )
311 FD_SET(ufds[i].fd, &readfds);
312
313 if ( ufds[i].events & G_IO_PRI )
314 FD_SET(ufds[i].fd, &exceptfds);
315
316 if ( ufds[i].events & G_IO_OUT )
317 FD_SET(ufds[i].fd, &writefds);
318
319 if ( ufds[i].fd > fdMax )
320 fdMax = ufds[i].fd;
321 }
322
323 fdMax++;
324 int res = select(fdMax, &readfds, &writefds, &exceptfds, &tv_timeout);
325
326 // translate the results back
327 for ( i = 0; i < nfds; i++ )
328 {
329 ufds[i].revents = 0;
330
331 if ( FD_ISSET(ufds[i].fd, &readfds ) )
332 ufds[i].revents |= G_IO_IN;
333
334 if ( FD_ISSET(ufds[i].fd, &exceptfds ) )
335 ufds[i].revents |= G_IO_PRI;
336
337 if ( FD_ISSET(ufds[i].fd, &writefds ) )
338 ufds[i].revents |= G_IO_OUT;
339 }
340
341 return res;
342 }
343
344 #endif // HAVE_POLL/!HAVE_POLL
345
346 static gint wxapp_poll_func( GPollFD *ufds, guint nfds, gint timeout )
347 {
348 gdk_threads_enter();
349
350 wxMutexGuiLeave();
351 g_mainThreadLocked = TRUE;
352
353 // we rely on the fact that glib GPollFD struct is really just pollfd but
354 // I wonder how wise is this in the long term (VZ)
355 gint res = wxPoll( (wxPollFd *) ufds, nfds, timeout );
356
357 wxMutexGuiEnter();
358 g_mainThreadLocked = FALSE;
359
360 gdk_threads_leave();
361
362 return res;
363 }
364
365 #endif // wxUSE_THREADS
366
367 } // extern "C"
368
369 void wxapp_install_idle_handler()
370 {
371 // GD: this assert is raised when using the thread sample (which works)
372 // so the test is probably not so easy. Can widget callbacks be
373 // triggered from child threads and, if so, for which widgets?
374 // wxASSERT_MSG( wxThread::IsMain() || gs_WakeUpIdle, wxT("attempt to install idle handler from widget callback in child thread (should be exclusively from wxWakeUpIdle)") );
375
376 wxASSERT_MSG( wxTheApp->m_idleTag == 0, wxT("attempt to install idle handler twice") );
377
378 g_isIdle = FALSE;
379
380 if (g_pendingTag == 0)
381 g_pendingTag = gtk_idle_add_priority( 900, wxapp_pending_callback, (gpointer) NULL );
382
383 // This routine gets called by all event handlers
384 // indicating that the idle is over. It may also
385 // get called from other thread for sending events
386 // to the main thread (and processing these in
387 // idle time). Very low priority.
388 wxTheApp->m_idleTag = gtk_idle_add_priority( 1000, wxapp_idle_callback, (gpointer) NULL );
389 }
390
391 //-----------------------------------------------------------------------------
392 // Access to the root window global
393 //-----------------------------------------------------------------------------
394
395 GtkWidget* wxGetRootWindow()
396 {
397 if (gs_RootWindow == NULL)
398 {
399 gs_RootWindow = gtk_window_new( GTK_WINDOW_TOPLEVEL );
400 gtk_widget_realize( gs_RootWindow );
401 }
402 return gs_RootWindow;
403 }
404
405 //-----------------------------------------------------------------------------
406 // wxApp
407 //-----------------------------------------------------------------------------
408
409 IMPLEMENT_DYNAMIC_CLASS(wxApp,wxEvtHandler)
410
411 BEGIN_EVENT_TABLE(wxApp, wxEvtHandler)
412 EVT_IDLE(wxAppBase::OnIdle)
413 END_EVENT_TABLE()
414
415 wxApp::wxApp()
416 {
417 #ifdef __WXDEBUG__
418 m_isInAssert = FALSE;
419 #endif // __WXDEBUG__
420
421 m_idleTag = 0;
422 wxapp_install_idle_handler();
423
424 #if wxUSE_THREADS
425 g_main_set_poll_func( wxapp_poll_func );
426 #endif
427
428 m_colorCube = (unsigned char*) NULL;
429
430 // this is NULL for a "regular" wxApp, but is set (and freed) by a wxGLApp
431 m_glVisualInfo = (void *) NULL;
432 }
433
434 wxApp::~wxApp()
435 {
436 if (m_idleTag) gtk_idle_remove( m_idleTag );
437
438 if (m_colorCube) free(m_colorCube);
439 }
440
441 bool wxApp::OnInitGui()
442 {
443 if ( !wxAppBase::OnInitGui() )
444 return FALSE;
445
446 GdkVisual *visual = gdk_visual_get_system();
447
448 // if this is a wxGLApp (derived from wxApp), and we've already
449 // chosen a specific visual, then derive the GdkVisual from that
450 if (m_glVisualInfo != NULL)
451 {
452 #ifdef __WXGTK20__
453 // seems gtk_widget_set_default_visual no longer exists?
454 GdkVisual* vis = gtk_widget_get_default_visual();
455 #else
456 GdkVisual* vis = gdkx_visual_get(
457 ((XVisualInfo *) m_glVisualInfo) ->visualid );
458 gtk_widget_set_default_visual( vis );
459 #endif
460
461 GdkColormap *colormap = gdk_colormap_new( vis, FALSE );
462 gtk_widget_set_default_colormap( colormap );
463
464 visual = vis;
465 }
466
467 // On some machines, the default visual is just 256 colours, so
468 // we make sure we get the best. This can sometimes be wasteful.
469
470 else
471 if ((gdk_visual_get_best() != gdk_visual_get_system()) && (m_useBestVisual))
472 {
473 #ifdef __WXGTK20__
474 /* seems gtk_widget_set_default_visual no longer exists? */
475 GdkVisual* vis = gtk_widget_get_default_visual();
476 #else
477 GdkVisual* vis = gdk_visual_get_best();
478 gtk_widget_set_default_visual( vis );
479 #endif
480
481 GdkColormap *colormap = gdk_colormap_new( vis, FALSE );
482 gtk_widget_set_default_colormap( colormap );
483
484 visual = vis;
485 }
486
487 // Nothing to do for 15, 16, 24, 32 bit displays
488 if (visual->depth > 8) return TRUE;
489
490 // initialize color cube for 8-bit color reduction dithering
491
492 GdkColormap *cmap = gtk_widget_get_default_colormap();
493
494 m_colorCube = (unsigned char*)malloc(32 * 32 * 32);
495
496 for (int r = 0; r < 32; r++)
497 {
498 for (int g = 0; g < 32; g++)
499 {
500 for (int b = 0; b < 32; b++)
501 {
502 int rr = (r << 3) | (r >> 2);
503 int gg = (g << 3) | (g >> 2);
504 int bb = (b << 3) | (b >> 2);
505
506 int index = -1;
507
508 GdkColor *colors = cmap->colors;
509 if (colors)
510 {
511 int max = 3 * 65536;
512
513 for (int i = 0; i < cmap->size; i++)
514 {
515 int rdiff = ((rr << 8) - colors[i].red);
516 int gdiff = ((gg << 8) - colors[i].green);
517 int bdiff = ((bb << 8) - colors[i].blue);
518 int sum = ABS (rdiff) + ABS (gdiff) + ABS (bdiff);
519 if (sum < max)
520 {
521 index = i; max = sum;
522 }
523 }
524 }
525 else
526 {
527 // assume 8-bit true or static colors. this really exists
528 GdkVisual* vis = gdk_colormap_get_visual( cmap );
529 index = (r >> (5 - vis->red_prec)) << vis->red_shift;
530 index |= (g >> (5 - vis->green_prec)) << vis->green_shift;
531 index |= (b >> (5 - vis->blue_prec)) << vis->blue_shift;
532 }
533 m_colorCube[ (r*1024) + (g*32) + b ] = index;
534 }
535 }
536 }
537
538 return TRUE;
539 }
540
541 GdkVisual *wxApp::GetGdkVisual()
542 {
543 GdkVisual *visual = NULL;
544
545 if (m_glVisualInfo)
546 visual = gdkx_visual_get( ((XVisualInfo *) m_glVisualInfo)->visualid );
547 else
548 visual = gdk_window_get_visual( wxGetRootWindow()->window );
549
550 wxASSERT( visual );
551
552 return visual;
553 }
554
555 bool wxApp::Initialize(int& argc, wxChar **argv)
556 {
557 bool init_result;
558
559 #if wxUSE_THREADS
560 // GTK 1.2 up to version 1.2.3 has broken threads
561 if ((gtk_major_version == 1) &&
562 (gtk_minor_version == 2) &&
563 (gtk_micro_version < 4))
564 {
565 printf( "wxWidgets warning: GUI threading disabled due to outdated GTK version\n" );
566 }
567 else
568 {
569 if (!g_thread_supported())
570 g_thread_init(NULL);
571 }
572 #endif // wxUSE_THREADS
573
574 gtk_set_locale();
575
576 // We should have the wxUSE_WCHAR_T test on the _outside_
577 #if wxUSE_WCHAR_T
578 #if defined(__WXGTK20__)
579 // gtk+ 2.0 supports Unicode through UTF-8 strings
580 wxConvCurrent = &wxConvUTF8;
581 #else // GTK 1.x
582 if (!wxOKlibc())
583 wxConvCurrent = &wxConvLocal;
584 #endif
585 #else // !wxUSE_WCHAR_T
586 if (!wxOKlibc())
587 wxConvCurrent = (wxMBConv*) NULL;
588 #endif // wxUSE_WCHAR_T/!wxUSE_WCHAR_T
589
590 #if wxUSE_UNICODE
591 // gtk_init() wants UTF-8, not wchar_t, so convert
592 int i;
593 char **argvGTK = new char *[argc + 1];
594 for ( i = 0; i < argc; i++ )
595 {
596 argvGTK[i] = wxStrdupA(wxConvUTF8.cWX2MB(argv[i]));
597 }
598
599 argvGTK[argc] = NULL;
600
601 int argcGTK = argc;
602
603 #ifdef __WXGPE__
604 init_result = true; // is there a _check() version of this?
605 gpe_application_init( &argcGTK, &argvGTK );
606 #else
607 init_result = gtk_init_check( &argcGTK, &argvGTK );
608 #endif
609
610 if ( argcGTK != argc )
611 {
612 // we have to drop the parameters which were consumed by GTK+
613 for ( i = 0; i < argcGTK; i++ )
614 {
615 while ( strcmp(wxConvUTF8.cWX2MB(argv[i]), argvGTK[i]) != 0 )
616 {
617 memmove(argv + i, argv + i + 1, argc - i);
618 }
619 }
620
621 argc = argcGTK;
622 }
623 //else: gtk_init() didn't modify our parameters
624
625 // free our copy
626 for ( i = 0; i < argcGTK; i++ )
627 {
628 free(argvGTK[i]);
629 }
630
631 delete [] argvGTK;
632 #else // !wxUSE_UNICODE
633 // gtk_init() shouldn't actually change argv itself (just its contents) so
634 // it's ok to pass pointer to it
635 init_result = gtk_init_check( &argc, &argv );
636 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
637
638 if (!init_result) {
639 wxLogError(wxT("Unable to initialize gtk, is DISPLAY set properly?"));
640 return false;
641 }
642
643 // we can not enter threads before gtk_init is done
644 gdk_threads_enter();
645
646 if ( !wxAppBase::Initialize(argc, argv) )
647 {
648 gdk_threads_leave();
649
650 return false;
651 }
652
653 wxSetDetectableAutoRepeat( TRUE );
654
655 #if wxUSE_INTL
656 wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
657 #endif
658
659 return true;
660 }
661
662 void wxApp::CleanUp()
663 {
664 gdk_threads_leave();
665
666 wxAppBase::CleanUp();
667 }
668
669 #ifdef __WXDEBUG__
670
671 void wxApp::OnAssert(const wxChar *file, int line, const wxChar* cond, const wxChar *msg)
672 {
673 m_isInAssert = TRUE;
674
675 wxAppBase::OnAssert(file, line, cond, msg);
676
677 m_isInAssert = FALSE;
678 }
679
680 #endif // __WXDEBUG__
681