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