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