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