]> git.saurik.com Git - wxWidgets.git/blob - src/gtk/utilsgtk.cpp
Better handling for asserts in non-main threads.
[wxWidgets.git] / src / gtk / utilsgtk.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/gtk/utilsgtk.cpp
3 // Purpose:
4 // Author: Robert Roebling
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #include "wx/utils.h"
14
15 #ifndef WX_PRECOMP
16 #include "wx/string.h"
17 #include "wx/intl.h"
18 #include "wx/log.h"
19 #endif
20
21 #include "wx/apptrait.h"
22 #include "wx/process.h"
23 #include "wx/sysopt.h"
24 #include "wx/unix/execute.h"
25
26 #include "wx/gtk/private/timer.h"
27 #include "wx/evtloop.h"
28
29 #if wxDEBUG_LEVEL
30 #include "wx/gtk/assertdlg_gtk.h"
31 #if wxUSE_STACKWALKER
32 #include "wx/stackwalk.h"
33 #endif // wxUSE_STACKWALKER
34 #endif // wxDEBUG_LEVEL
35
36 #include <stdarg.h>
37 #include <string.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <sys/wait.h> // for WNOHANG
41 #include <unistd.h>
42
43 #include "glib.h"
44 #include "gdk/gdk.h"
45 #include "gtk/gtk.h"
46 #include "gdk/gdkx.h"
47
48 #if wxUSE_DETECT_SM
49 #include "X11/Xlib.h"
50 #include "X11/SM/SMlib.h"
51 #endif
52
53 //-----------------------------------------------------------------------------
54 // data
55 //-----------------------------------------------------------------------------
56
57 extern GtkWidget *wxGetRootWindow();
58
59 //----------------------------------------------------------------------------
60 // misc.
61 //----------------------------------------------------------------------------
62 #ifndef __EMX__
63 // on OS/2, we use the wxBell from wxBase library
64
65 void wxBell()
66 {
67 gdk_beep();
68 }
69 #endif
70
71 // ----------------------------------------------------------------------------
72 // display characterstics
73 // ----------------------------------------------------------------------------
74
75 void *wxGetDisplay()
76 {
77 return GDK_DISPLAY();
78 }
79
80 void wxDisplaySize( int *width, int *height )
81 {
82 if (width) *width = gdk_screen_width();
83 if (height) *height = gdk_screen_height();
84 }
85
86 void wxDisplaySizeMM( int *width, int *height )
87 {
88 if (width) *width = gdk_screen_width_mm();
89 if (height) *height = gdk_screen_height_mm();
90 }
91
92 void wxGetMousePosition( int* x, int* y )
93 {
94 gdk_window_get_pointer( NULL, x, y, NULL );
95 }
96
97 bool wxColourDisplay()
98 {
99 return true;
100 }
101
102 int wxDisplayDepth()
103 {
104 return gdk_drawable_get_visual( wxGetRootWindow()->window )->depth;
105 }
106
107 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
108 {
109 return wxGenericFindWindowAtPoint(pt);
110 }
111
112 #if !wxUSE_UNICODE
113
114 WXDLLIMPEXP_CORE wxCharBuffer
115 wxConvertToGTK(const wxString& s, wxFontEncoding enc)
116 {
117 wxWCharBuffer wbuf;
118 if ( enc == wxFONTENCODING_SYSTEM || enc == wxFONTENCODING_DEFAULT )
119 {
120 wbuf = wxConvUI->cMB2WC(s.c_str());
121 }
122 else // another encoding, use generic conversion class
123 {
124 wbuf = wxCSConv(enc).cMB2WC(s.c_str());
125 }
126
127 if ( !wbuf && !s.empty() )
128 {
129 // conversion failed, but we still want to show something to the user
130 // even if it's going to be wrong it is better than nothing
131 //
132 // we choose ISO8859-1 here arbitrarily, it's just the most common
133 // encoding probably and, also importantly here, conversion from it
134 // never fails as it's done internally by wxCSConv
135 wbuf = wxCSConv(wxFONTENCODING_ISO8859_1).cMB2WC(s.c_str());
136 }
137
138 return wxConvUTF8.cWC2MB(wbuf);
139 }
140
141 WXDLLIMPEXP_CORE wxCharBuffer
142 wxConvertFromGTK(const wxString& s, wxFontEncoding enc)
143 {
144 // this conversion should never fail as GTK+ always uses UTF-8 internally
145 // so there are no complications here
146 const wxWCharBuffer wbuf(wxConvUTF8.cMB2WC(s.c_str()));
147 if ( enc == wxFONTENCODING_SYSTEM )
148 return wxConvUI->cWC2MB(wbuf);
149
150 return wxCSConv(enc).cWC2MB(wbuf);
151 }
152
153 #endif // !wxUSE_UNICODE
154
155 // Returns NULL if version is certainly greater or equal than major.minor.micro
156 // Returns string describing the error if version is lower than
157 // major.minor.micro OR it cannot be determined and one should not rely on the
158 // availability of pango version major.minor.micro, nor the non-availability
159 const gchar *wx_pango_version_check (int major, int minor, int micro)
160 {
161 // NOTE: you don't need to use this macro to check for Pango features
162 // added in pango-1.4 or earlier since GTK 2.4 (our minimum requirement
163 // for GTK lib) required pango 1.4...
164
165 #ifdef PANGO_VERSION_MAJOR
166 if (!gtk_check_version (2,11,0))
167 {
168 // GTK+ 2.11 requires Pango >= 1.15.3 and pango_version_check
169 // was added in Pango 1.15.2 thus we know for sure the pango lib we're
170 // using has the pango_version_check function:
171 return pango_version_check (major, minor, micro);
172 }
173
174 return "can't check";
175 #else // !PANGO_VERSION_MAJOR
176 wxUnusedVar(major);
177 wxUnusedVar(minor);
178 wxUnusedVar(micro);
179
180 return "too old headers";
181 #endif
182 }
183
184
185 // ----------------------------------------------------------------------------
186 // subprocess routines
187 // ----------------------------------------------------------------------------
188
189 extern "C" {
190 static
191 void GTK_EndProcessDetector(gpointer data, gint source,
192 GdkInputCondition WXUNUSED(condition))
193 {
194 wxEndProcessData * const
195 proc_data = static_cast<wxEndProcessData *>(data);
196
197 // child exited, end waiting
198 close(source);
199
200 // don't call us again!
201 gdk_input_remove(proc_data->tag);
202
203 wxHandleProcessTermination(proc_data);
204 }
205 }
206
207 int wxGUIAppTraits::AddProcessCallback(wxEndProcessData *proc_data, int fd)
208 {
209 int tag = gdk_input_add(fd,
210 GDK_INPUT_READ,
211 GTK_EndProcessDetector,
212 (gpointer)proc_data);
213
214 return tag;
215 }
216
217
218
219 // ----------------------------------------------------------------------------
220 // wxPlatformInfo-related
221 // ----------------------------------------------------------------------------
222
223 wxPortId wxGUIAppTraits::GetToolkitVersion(int *verMaj, int *verMin) const
224 {
225 if ( verMaj )
226 *verMaj = gtk_major_version;
227 if ( verMin )
228 *verMin = gtk_minor_version;
229
230 return wxPORT_GTK;
231 }
232
233 #if wxUSE_TIMER
234
235 wxTimerImpl *wxGUIAppTraits::CreateTimerImpl(wxTimer *timer)
236 {
237 return new wxGTKTimerImpl(timer);
238 }
239
240 #endif // wxUSE_TIMER
241
242 #if wxUSE_DETECT_SM
243 static wxString GetSM()
244 {
245 class Dpy
246 {
247 public:
248 Dpy() { m_dpy = XOpenDisplay(NULL); }
249 ~Dpy() { if ( m_dpy ) XCloseDisplay(m_dpy); }
250
251 operator Display *() const { return m_dpy; }
252 private:
253 Display *m_dpy;
254 } dpy;
255
256 if ( !dpy )
257 return wxEmptyString;
258
259 char smerr[256];
260 char *client_id;
261 SmcConn smc_conn = SmcOpenConnection(NULL, NULL,
262 999, 999,
263 0 /* mask */, NULL /* callbacks */,
264 NULL, &client_id,
265 WXSIZEOF(smerr), smerr);
266
267 if ( !smc_conn )
268 {
269 wxLogDebug("Failed to connect to session manager: %s", smerr);
270 return wxEmptyString;
271 }
272
273 char *vendor = SmcVendor(smc_conn);
274 wxString ret = wxString::FromAscii( vendor );
275 free(vendor);
276
277 SmcCloseConnection(smc_conn, 0, NULL);
278 free(client_id);
279
280 return ret;
281 }
282 #endif // wxUSE_DETECT_SM
283
284
285 //-----------------------------------------------------------------------------
286 // wxGUIAppTraits
287 //-----------------------------------------------------------------------------
288
289 wxEventLoopBase *wxGUIAppTraits::CreateEventLoop()
290 {
291 return new wxEventLoop();
292 }
293
294
295 #if wxUSE_INTL
296 void wxGUIAppTraits::SetLocale()
297 {
298 gtk_set_locale();
299 wxUpdateLocaleIsUtf8();
300 }
301 #endif
302
303 #if wxDEBUG_LEVEL && wxUSE_STACKWALKER
304
305 // private helper class
306 class StackDump : public wxStackWalker
307 {
308 public:
309 StackDump(GtkAssertDialog *dlg) { m_dlg=dlg; }
310
311 protected:
312 virtual void OnStackFrame(const wxStackFrame& frame)
313 {
314 wxString fncname = frame.GetName();
315 wxString fncargs = fncname;
316
317 size_t n = fncname.find(wxT('('));
318 if (n != wxString::npos)
319 {
320 // remove arguments from function name
321 fncname.erase(n);
322
323 // remove function name and brackets from arguments
324 fncargs = fncargs.substr(n+1, fncargs.length()-n-2);
325 }
326 else
327 fncargs = wxEmptyString;
328
329 // append this stack frame's info in the dialog
330 if (!frame.GetFileName().empty() || !fncname.empty())
331 gtk_assert_dialog_append_stack_frame(m_dlg,
332 fncname.mb_str(),
333 fncargs.mb_str(),
334 frame.GetFileName().mb_str(),
335 frame.GetLine());
336 }
337
338 private:
339 GtkAssertDialog *m_dlg;
340 };
341
342 // the callback functions must be extern "C" to comply with GTK+ declarations
343 extern "C"
344 {
345 void get_stackframe_callback(StackDump *dump)
346 {
347 // skip over frames up to including wxOnAssert()
348 dump->ProcessFrames(3);
349 }
350 }
351
352 #endif // wxDEBUG_LEVEL && wxUSE_STACKWALKER
353
354 bool wxGUIAppTraits::ShowAssertDialog(const wxString& msg)
355 {
356 #if wxDEBUG_LEVEL
357 // we can't show the dialog from another thread
358 if ( wxIsMainThread() )
359 {
360 // under GTK2 we prefer to use a dialog widget written using directly
361 // in GTK+ as use a dialog written using wxWidgets would need the
362 // wxWidgets idle processing to work correctly which might not be the
363 // case when assert happens
364 GtkWidget *dialog = gtk_assert_dialog_new();
365 gtk_assert_dialog_set_message(GTK_ASSERT_DIALOG(dialog), msg.mb_str());
366
367 #if wxUSE_STACKWALKER
368 // don't show more than maxLines or we could get a dialog too tall to
369 // be shown on screen: 20 should be ok everywhere as even with 15 pixel
370 // high characters it is still only 300 pixels...
371 static const int maxLines = 20;
372
373 // save current stack frame...
374 StackDump dump(GTK_ASSERT_DIALOG(dialog));
375 dump.SaveStack(maxLines);
376
377 // ...but process it only if the user needs it
378 gtk_assert_dialog_set_backtrace_callback
379 (
380 GTK_ASSERT_DIALOG(dialog),
381 (GtkAssertDialogStackFrameCallback)get_stackframe_callback,
382 &dump
383 );
384 #endif // wxUSE_STACKWALKER
385
386 gint result = gtk_dialog_run(GTK_DIALOG (dialog));
387 bool returnCode = false;
388 switch (result)
389 {
390 case GTK_ASSERT_DIALOG_STOP:
391 wxTrap();
392 break;
393 case GTK_ASSERT_DIALOG_CONTINUE:
394 // nothing to do
395 break;
396 case GTK_ASSERT_DIALOG_CONTINUE_SUPPRESSING:
397 // no more asserts
398 returnCode = true;
399 break;
400
401 default:
402 wxFAIL_MSG( wxT("unexpected return code from GtkAssertDialog") );
403 }
404
405 gtk_widget_destroy(dialog);
406 return returnCode;
407 }
408 #endif // wxDEBUG_LEVEL
409
410 return wxAppTraitsBase::ShowAssertDialog(msg);
411 }
412
413 wxString wxGUIAppTraits::GetDesktopEnvironment() const
414 {
415 wxString de = wxSystemOptions::GetOption(wxT("gtk.desktop"));
416 #if wxUSE_DETECT_SM
417 if ( de.empty() )
418 {
419 static const wxString s_SM = GetSM();
420
421 if (s_SM == wxT("GnomeSM"))
422 de = wxT("GNOME");
423 else if (s_SM == wxT("KDE"))
424 de = wxT("KDE");
425 }
426 #endif // wxUSE_DETECT_SM
427
428 return de;
429 }
430
431 #ifdef __WXGTK26__
432
433 // see the hack below in wxCmdLineParser::GetUsageString().
434 // TODO: replace this hack with a g_option_group_get_entries()
435 // call as soon as such function exists;
436 // see http://bugzilla.gnome.org/show_bug.cgi?id=431021 for the relative
437 // feature request
438 struct _GOptionGroup
439 {
440 gchar *name;
441 gchar *description;
442 gchar *help_description;
443
444 GDestroyNotify destroy_notify;
445 gpointer user_data;
446
447 GTranslateFunc translate_func;
448 GDestroyNotify translate_notify;
449 gpointer translate_data;
450
451 GOptionEntry *entries;
452 gint n_entries;
453
454 GOptionParseFunc pre_parse_func;
455 GOptionParseFunc post_parse_func;
456 GOptionErrorFunc error_func;
457 };
458
459 wxString wxGetNameFromGtkOptionEntry(const GOptionEntry *opt)
460 {
461 wxString ret;
462
463 if (opt->short_name)
464 ret << wxT("-") << opt->short_name;
465 if (opt->long_name)
466 {
467 if (!ret.empty())
468 ret << wxT(", ");
469 ret << wxT("--") << opt->long_name;
470
471 if (opt->arg_description)
472 ret << wxT("=") << opt->arg_description;
473 }
474
475 return wxT(" ") + ret;
476 }
477
478 #endif // __WXGTK26__
479
480 wxString
481 wxGUIAppTraits::GetStandardCmdLineOptions(wxArrayString& names,
482 wxArrayString& desc) const
483 {
484 wxString usage;
485
486 #ifdef __WXGTK26__
487 if (!gtk_check_version(2,6,0))
488 {
489 // since GTK>=2.6, we can use the glib_check_version() symbol...
490
491 // check whether GLib version is greater than 2.6 but also lower than 2.19
492 // because, as we use the undocumented _GOptionGroup struct, we don't want
493 // to run this code with future versions which might change it (2.19 is the
494 // latest one at the time of this writing)
495 if (!glib_check_version(2,6,0) && glib_check_version(2,20,0))
496 {
497 usage << _("The following standard GTK+ options are also supported:\n");
498
499 // passing true here means that the function can open the default
500 // display while parsing (not really used here anyhow)
501 GOptionGroup *gtkOpts = gtk_get_option_group(true);
502
503 // WARNING: here we access the internals of GOptionGroup:
504 GOptionEntry *entries = ((_GOptionGroup*)gtkOpts)->entries;
505 unsigned int n_entries = ((_GOptionGroup*)gtkOpts)->n_entries;
506 wxArrayString namesOptions, descOptions;
507
508 for ( size_t n = 0; n < n_entries; n++ )
509 {
510 if ( entries[n].flags & G_OPTION_FLAG_HIDDEN )
511 continue; // skip
512
513 names.push_back(wxGetNameFromGtkOptionEntry(&entries[n]));
514
515 const gchar * const entryDesc = entries[n].description;
516 desc.push_back(wxString(entryDesc));
517 }
518
519 g_option_group_free (gtkOpts);
520 }
521 }
522 #else
523 wxUnusedVar(names);
524 wxUnusedVar(desc);
525 #endif // __WXGTK26__
526
527 return usage;
528 }
529