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