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