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