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