Replaced TRUE and FALSE with true and false
[wxWidgets.git] / src / motif / utils.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: utils.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 17/09/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __VMS
24 #define XtDisplay XTDISPLAY
25 #endif
26
27 #include "wx/setup.h"
28 #include "wx/utils.h"
29 #include "wx/apptrait.h"
30 #include "wx/app.h"
31 #include "wx/dcmemory.h"
32 #include "wx/bitmap.h"
33 #include "wx/evtloop.h"
34
35 #include <string.h>
36
37 #if (defined(__SUNCC__) || defined(__CLCC__))
38 #include <sysent.h>
39 #endif
40
41 #ifdef __VMS__
42 #pragma message disable nosimpint
43 #endif
44
45 #include "wx/unix/execute.h"
46
47 #include <Xm/Xm.h>
48 #include <Xm/Frame.h>
49
50 #include "wx/motif/private.h"
51
52 #if wxUSE_RESOURCES
53 #include "X11/Xresource.h"
54 #endif
55
56 #include "X11/Xutil.h"
57
58 #ifdef __VMS__
59 #pragma message enable nosimpint
60 #endif
61
62 // ----------------------------------------------------------------------------
63 // private functions
64 // ----------------------------------------------------------------------------
65
66 // Yuck this is really BOTH site and platform dependent
67 // so we should use some other strategy!
68 #ifdef sun
69 #define DEFAULT_XRESOURCE_DIR "/usr/openwin/lib/app-defaults"
70 #else
71 #define DEFAULT_XRESOURCE_DIR "/usr/lib/X11/app-defaults"
72 #endif
73
74 #if wxUSE_RESOURCES
75 static char *GetIniFile (char *dest, const char *filename);
76 #endif
77
78 // ============================================================================
79 // implementation
80 // ============================================================================
81
82 // ----------------------------------------------------------------------------
83 // async event processing
84 // ----------------------------------------------------------------------------
85
86 // Consume all events until no more left
87 void wxFlushEvents(WXDisplay* wxdisplay)
88 {
89 Display *display = (Display*)wxdisplay;
90 wxEventLoop evtLoop;
91
92 XSync (display, False);
93
94 while (evtLoop.Pending())
95 {
96 XFlush (display);
97 evtLoop.Dispatch();
98 }
99 }
100
101 // ----------------------------------------------------------------------------
102 // wxExecute stuff
103 // ----------------------------------------------------------------------------
104
105 static void xt_notify_end_process(XtPointer data, int *WXUNUSED(fid),
106 XtInputId *id)
107 {
108 wxEndProcessData *proc_data = (wxEndProcessData *)data;
109
110 wxHandleProcessTermination(proc_data);
111
112 // VZ: I think they should be the same...
113 wxASSERT( (int)*id == proc_data->tag );
114
115 XtRemoveInput(*id);
116 }
117
118 int wxAddProcessCallback(wxEndProcessData *proc_data, int fd)
119 {
120 XtInputId id = XtAppAddInput((XtAppContext) wxTheApp->GetAppContext(),
121 fd,
122 (XtPointer *) XtInputReadMask,
123 (XtInputCallbackProc) xt_notify_end_process,
124 (XtPointer) proc_data);
125
126 return (int)id;
127 }
128
129 // ----------------------------------------------------------------------------
130 // misc
131 // ----------------------------------------------------------------------------
132
133 // Emit a beeeeeep
134 #ifndef __EMX__
135 // on OS/2, we use the wxBell from wxBase library (src/os2/utils.cpp)
136 void wxBell()
137 {
138 // Use current setting for the bell
139 XBell (wxGlobalDisplay(), 0);
140 }
141 #endif
142
143 wxToolkitInfo& wxGUIAppTraits::GetToolkitInfo()
144 {
145 static wxToolkitInfo info;
146
147 info.shortName = _T("motif");
148 info.name = _T("wxMotif");
149 #ifdef __WXUNIVERSAL__
150 info.shortName << _T("univ");
151 info.name << _T("/wxUniversal");
152 #endif
153 // FIXME TODO
154 // This code is WRONG!! Does NOT return the
155 // Motif version of the libs but the X protocol
156 // version!
157 Display *display = wxGlobalDisplay();
158 info.versionMajor = ProtocolVersion (display);
159 info.versionMinor = ProtocolRevision (display);
160 info.os = wxMOTIF_X;
161 return info;
162 }
163
164 // ----------------------------------------------------------------------------
165 // Reading and writing resources (eg WIN.INI, .Xdefaults)
166 // ----------------------------------------------------------------------------
167
168 #if wxUSE_RESOURCES
169
170 // Read $HOME for what it says is home, if not
171 // read $USER or $LOGNAME for user name else determine
172 // the Real User, then determine the Real home dir.
173 static char * GetIniFile (char *dest, const char *filename)
174 {
175 char *home = NULL;
176 if (filename && wxIsAbsolutePath(filename))
177 {
178 strcpy(dest, filename);
179 }
180 else if ((home = wxGetUserHome("")) != NULL)
181 {
182 strcpy(dest, home);
183 if (dest[strlen(dest) - 1] != '/')
184 strcat (dest, "/");
185 if (filename == NULL)
186 {
187 if ((filename = getenv ("XENVIRONMENT")) == NULL)
188 filename = ".Xdefaults";
189 }
190 else if (*filename != '.')
191 strcat (dest, ".");
192 strcat (dest, filename);
193 } else
194 {
195 dest[0] = '\0';
196 }
197 return dest;
198 }
199
200 static char *GetResourcePath(char *buf, const char *name, bool create = false)
201 {
202 if (create && wxFileExists (name) ) {
203 strcpy(buf, name);
204 return buf; // Exists so ...
205 }
206
207 if (*name == '/')
208 strcpy(buf, name);
209 else {
210 // Put in standard place for resource files if not absolute
211 strcpy (buf, DEFAULT_XRESOURCE_DIR);
212 strcat (buf, "/");
213 strcat (buf, wxFileNameFromPath (name).c_str());
214 }
215
216 if (create) {
217 // Touch the file to create it
218 FILE *fd = fopen (buf, "w");
219 if (fd) fclose (fd);
220 }
221 return buf;
222 }
223
224 /*
225 * We have a cache for writing different resource files,
226 * which will only get flushed when we call wxFlushResources().
227 * Build up a list of resource databases waiting to be written.
228 *
229 */
230
231 wxList wxResourceCache (wxKEY_STRING);
232
233 void
234 wxFlushResources (void)
235 {
236 char nameBuffer[512];
237
238 wxNode *node = wxResourceCache.First ();
239 while (node)
240 {
241 const char *file = node->GetKeyString();
242 // If file doesn't exist, create it first.
243 (void)GetResourcePath(nameBuffer, file, true);
244
245 XrmDatabase database = (XrmDatabase) node->Data ();
246 XrmPutFileDatabase (database, nameBuffer);
247 XrmDestroyDatabase (database);
248 wxNode *next = node->Next ();
249 delete node;
250 node = next;
251 }
252 }
253
254 static XrmDatabase wxResourceDatabase = 0;
255
256 void wxXMergeDatabases (wxApp * theApp, Display * display);
257
258 bool wxWriteResource(const wxString& section, const wxString& entry, const wxString& value, const wxString& file)
259 {
260 char buffer[500];
261
262 (void) GetIniFile (buffer, file);
263
264 XrmDatabase database;
265 wxNode *node = wxResourceCache.Find (buffer);
266 if (node)
267 database = (XrmDatabase) node->Data ();
268 else
269 {
270 database = XrmGetFileDatabase (buffer);
271 wxResourceCache.Append (buffer, (wxObject *) database);
272 }
273
274 char resName[300];
275 strcpy (resName, section.c_str());
276 strcat (resName, ".");
277 strcat (resName, entry.c_str());
278
279 XrmPutStringResource (&database, resName, value);
280 return true;
281 }
282
283 bool wxWriteResource(const wxString& section, const wxString& entry, float value, const wxString& file)
284 {
285 char buf[50];
286 sprintf(buf, "%.4f", value);
287 return wxWriteResource(section, entry, buf, file);
288 }
289
290 bool wxWriteResource(const wxString& section, const wxString& entry, long value, const wxString& file)
291 {
292 char buf[50];
293 sprintf(buf, "%ld", value);
294 return wxWriteResource(section, entry, buf, file);
295 }
296
297 bool wxWriteResource(const wxString& section, const wxString& entry, int value, const wxString& file)
298 {
299 char buf[50];
300 sprintf(buf, "%d", value);
301 return wxWriteResource(section, entry, buf, file);
302 }
303
304 bool wxGetResource(const wxString& section, const wxString& entry, char **value, const wxString& file)
305 {
306 if (!wxResourceDatabase)
307 {
308 Display *display = wxGlobalDisplay();
309 wxXMergeDatabases (wxTheApp, display);
310 }
311
312 XrmDatabase database;
313
314 if (file != "")
315 {
316 char buffer[500];
317
318 // Is this right? Trying to get it to look in the user's
319 // home directory instead of current directory -- JACS
320 (void) GetIniFile (buffer, file);
321
322 wxNode *node = wxResourceCache.Find (buffer);
323 if (node)
324 database = (XrmDatabase) node->Data ();
325 else
326 {
327 database = XrmGetFileDatabase (buffer);
328 wxResourceCache.Append (buffer, (wxObject *) database);
329 }
330 }
331 else
332 database = wxResourceDatabase;
333
334 XrmValue xvalue;
335 char *str_type[20];
336 char buf[150];
337 strcpy (buf, section);
338 strcat (buf, ".");
339 strcat (buf, entry);
340
341 Bool success = XrmGetResource (database, buf, "*", str_type,
342 &xvalue);
343 // Try different combinations of upper/lower case, just in case...
344 if (!success)
345 {
346 buf[0] = (isupper (buf[0]) ? tolower (buf[0]) : toupper (buf[0]));
347 success = XrmGetResource (database, buf, "*", str_type,
348 &xvalue);
349 }
350 if (success)
351 {
352 if (*value)
353 delete[] *value;
354
355 *value = new char[xvalue.size + 1];
356 strncpy (*value, xvalue.addr, (int) xvalue.size);
357 return true;
358 }
359 return false;
360 }
361
362 bool wxGetResource(const wxString& section, const wxString& entry, float *value, const wxString& file)
363 {
364 char *s = NULL;
365 bool succ = wxGetResource(section, entry, (char **)&s, file);
366 if (succ)
367 {
368 *value = (float)strtod(s, NULL);
369 delete[] s;
370 return true;
371 }
372 else return false;
373 }
374
375 bool wxGetResource(const wxString& section, const wxString& entry, long *value, const wxString& file)
376 {
377 char *s = NULL;
378 bool succ = wxGetResource(section, entry, (char **)&s, file);
379 if (succ)
380 {
381 *value = strtol(s, NULL, 10);
382 delete[] s;
383 return true;
384 }
385 else return false;
386 }
387
388 bool wxGetResource(const wxString& section, const wxString& entry, int *value, const wxString& file)
389 {
390 char *s = NULL;
391 bool succ = wxGetResource(section, entry, (char **)&s, file);
392 if (succ)
393 {
394 // Handle True, False here
395 // True, Yes, Enables, Set or Activated
396 if (*s == 'T' || *s == 'Y' || *s == 'E' || *s == 'S' || *s == 'A')
397 *value = true;
398 // False, No, Disabled, Reset, Cleared, Deactivated
399 else if (*s == 'F' || *s == 'N' || *s == 'D' || *s == 'R' || *s == 'C')
400 *value = false;
401 // Handle as Integer
402 else
403 *value = (int) strtol (s, NULL, 10);
404 delete[] s;
405 return true;
406 }
407 else
408 return false;
409 }
410
411 void wxXMergeDatabases (wxApp * theApp, Display * display)
412 {
413 XrmDatabase homeDB, serverDB, applicationDB;
414 char filenamebuf[1024];
415
416 char *filename = &filenamebuf[0];
417 char *environment;
418 wxString classname = theApp->GetClassName();
419 char name[256];
420 (void) strcpy (name, "/usr/lib/X11/app-defaults/");
421 (void) strcat (name, classname.c_str());
422
423 /* Get application defaults file, if any */
424 applicationDB = XrmGetFileDatabase (name);
425 (void) XrmMergeDatabases (applicationDB, &wxResourceDatabase);
426
427 /* Merge server defaults, created by xrdb, loaded as a property of the root
428 * window when the server initializes and loaded into the display
429 * structure on XOpenDisplay;
430 * if not defined, use .Xdefaults
431 */
432
433 if (XResourceManagerString (display) != NULL)
434 {
435 serverDB = XrmGetStringDatabase (XResourceManagerString (display));
436 }
437 else
438 {
439 (void) GetIniFile (filename, NULL);
440 serverDB = XrmGetFileDatabase (filename);
441 }
442 XrmMergeDatabases (serverDB, &wxResourceDatabase);
443
444 /* Open XENVIRONMENT file, or if not defined, the .Xdefaults,
445 * and merge into existing database
446 */
447
448 if ((environment = getenv ("XENVIRONMENT")) == NULL)
449 {
450 size_t len;
451 environment = GetIniFile (filename, NULL);
452 len = strlen (environment);
453 wxString hostname = wxGetHostName();
454 if ( !!hostname )
455 strncat(environment, hostname, 1024 - len);
456 }
457 homeDB = XrmGetFileDatabase (environment);
458 XrmMergeDatabases (homeDB, &wxResourceDatabase);
459 }
460
461 #if 0
462
463 /*
464 * Not yet used but may be useful.
465 *
466 */
467 void
468 wxSetDefaultResources (const Widget w, const char **resourceSpec, const char *name)
469 {
470 int i;
471 Display *dpy = XtDisplay (w); // Retrieve the display pointer
472
473 XrmDatabase rdb = NULL; // A resource data base
474
475 // Create an empty resource database
476 rdb = XrmGetStringDatabase ("");
477
478 // Add the Component resources, prepending the name of the component
479
480 i = 0;
481 while (resourceSpec[i] != NULL)
482 {
483 char buf[1000];
484
485 sprintf (buf, "*%s%s", name, resourceSpec[i++]);
486 XrmPutLineResource (&rdb, buf);
487 }
488
489 // Merge them into the Xt database, with lowest precendence
490
491 if (rdb)
492 {
493 #if (XlibSpecificationRelease>=5)
494 XrmDatabase db = XtDatabase (dpy);
495 XrmCombineDatabase (rdb, &db, False);
496 #else
497 XrmMergeDatabases (dpy->db, &rdb);
498 dpy->db = rdb;
499 #endif
500 }
501 }
502 #endif
503 // 0
504
505 #endif // wxUSE_RESOURCES
506
507 // ----------------------------------------------------------------------------
508 // display info
509 // ----------------------------------------------------------------------------
510
511 void wxGetMousePosition( int* x, int* y )
512 {
513 #if wxUSE_NANOX
514 // TODO
515 *x = 0;
516 *y = 0;
517 #else
518 XMotionEvent xev;
519 Window root, child;
520 XQueryPointer(wxGlobalDisplay(),
521 DefaultRootWindow(wxGlobalDisplay()),
522 &root, &child,
523 &(xev.x_root), &(xev.y_root),
524 &(xev.x), &(xev.y),
525 &(xev.state));
526 *x = xev.x_root;
527 *y = xev.y_root;
528 #endif
529 };
530
531 // Return true if we have a colour display
532 bool wxColourDisplay()
533 {
534 return wxDisplayDepth() > 1;
535 }
536
537 // Returns depth of screen
538 int wxDisplayDepth()
539 {
540 Display *dpy = wxGlobalDisplay();
541
542 return DefaultDepth (dpy, DefaultScreen (dpy));
543 }
544
545 // Get size of display
546 void wxDisplaySize(int *width, int *height)
547 {
548 Display *dpy = wxGlobalDisplay();
549
550 if ( width )
551 *width = DisplayWidth (dpy, DefaultScreen (dpy));
552 if ( height )
553 *height = DisplayHeight (dpy, DefaultScreen (dpy));
554 }
555
556 void wxDisplaySizeMM(int *width, int *height)
557 {
558 Display *dpy = wxGlobalDisplay();
559
560 if ( width )
561 *width = DisplayWidthMM(dpy, DefaultScreen (dpy));
562 if ( height )
563 *height = DisplayHeightMM(dpy, DefaultScreen (dpy));
564 }
565
566 void wxClientDisplayRect(int *x, int *y, int *width, int *height)
567 {
568 // This is supposed to return desktop dimensions minus any window
569 // manager panels, menus, taskbars, etc. If there is a way to do that
570 // for this platform please fix this function, otherwise it defaults
571 // to the entire desktop.
572 if (x) *x = 0;
573 if (y) *y = 0;
574 wxDisplaySize(width, height);
575 }
576
577
578 // Configurable display in wxX11 and wxMotif
579 static WXDisplay *gs_currentDisplay = NULL;
580 static wxString gs_displayName;
581
582 WXDisplay *wxGetDisplay()
583 {
584 if (gs_currentDisplay)
585 return gs_currentDisplay;
586 else if (wxTheApp)
587 return wxTheApp->GetInitialDisplay();
588 return NULL;
589 }
590
591 bool wxSetDisplay(const wxString& display_name)
592 {
593 gs_displayName = display_name;
594
595 if ( display_name.empty() )
596 {
597 gs_currentDisplay = NULL;
598
599 return true;
600 }
601 else
602 {
603 Cardinal argc = 0;
604
605 Display *display = XtOpenDisplay((XtAppContext) wxTheApp->GetAppContext(),
606 display_name.c_str(),
607 wxTheApp->GetAppName().c_str(),
608 wxTheApp->GetClassName().c_str(),
609 NULL,
610 #if XtSpecificationRelease < 5
611 0, &argc,
612 #else
613 0, (int *)&argc,
614 #endif
615 NULL);
616
617 if (display)
618 {
619 gs_currentDisplay = (WXDisplay*) display;
620 return true;
621 }
622 else
623 return false;
624 }
625 }
626
627 wxString wxGetDisplayName()
628 {
629 return gs_displayName;
630 }
631
632 wxWindow* wxFindWindowAtPoint(const wxPoint& pt)
633 {
634 return wxGenericFindWindowAtPoint(pt);
635 }
636
637 // ----------------------------------------------------------------------------
638 // Some colour manipulation routines
639 // ----------------------------------------------------------------------------
640
641 void wxHSVToXColor(wxHSV *hsv,XColor *rgb)
642 {
643 int h = hsv->h;
644 int s = hsv->s;
645 int v = hsv->v;
646 int r = 0, g = 0, b = 0;
647 int i, f;
648 int p, q, t;
649 s = (s * wxMAX_RGB) / wxMAX_SV;
650 v = (v * wxMAX_RGB) / wxMAX_SV;
651 if (h == 360) h = 0;
652 if (s == 0) { h = 0; r = g = b = v; }
653 i = h / 60;
654 f = h % 60;
655 p = v * (wxMAX_RGB - s) / wxMAX_RGB;
656 q = v * (wxMAX_RGB - s * f / 60) / wxMAX_RGB;
657 t = v * (wxMAX_RGB - s * (60 - f) / 60) / wxMAX_RGB;
658 switch (i)
659 {
660 case 0: r = v, g = t, b = p; break;
661 case 1: r = q, g = v, b = p; break;
662 case 2: r = p, g = v, b = t; break;
663 case 3: r = p, g = q, b = v; break;
664 case 4: r = t, g = p, b = v; break;
665 case 5: r = v, g = p, b = q; break;
666 }
667 rgb->red = r << 8;
668 rgb->green = g << 8;
669 rgb->blue = b << 8;
670 }
671
672 void wxXColorToHSV(wxHSV *hsv,XColor *rgb)
673 {
674 int r = rgb->red >> 8;
675 int g = rgb->green >> 8;
676 int b = rgb->blue >> 8;
677 int maxv = wxMax3(r, g, b);
678 int minv = wxMin3(r, g, b);
679 int h = 0, s, v;
680 v = maxv;
681 if (maxv) s = (maxv - minv) * wxMAX_RGB / maxv;
682 else s = 0;
683 if (s == 0) h = 0;
684 else
685 {
686 int rc, gc, bc, hex = 0;
687 rc = (maxv - r) * wxMAX_RGB / (maxv - minv);
688 gc = (maxv - g) * wxMAX_RGB / (maxv - minv);
689 bc = (maxv - b) * wxMAX_RGB / (maxv - minv);
690 if (r == maxv) { h = bc - gc, hex = 0; }
691 else if (g == maxv) { h = rc - bc, hex = 2; }
692 else if (b == maxv) { h = gc - rc, hex = 4; }
693 h = hex * 60 + (h * 60 / wxMAX_RGB);
694 if (h < 0) h += 360;
695 }
696 hsv->h = h;
697 hsv->s = (s * wxMAX_SV) / wxMAX_RGB;
698 hsv->v = (v * wxMAX_SV) / wxMAX_RGB;
699 }
700
701 void wxAllocNearestColor(Display *d,Colormap cmp,XColor *xc)
702 {
703 #if !wxUSE_NANOX
704 int llp;
705
706 int screen = DefaultScreen(d);
707 int num_colors = DisplayCells(d,screen);
708
709 XColor *color_defs = new XColor[num_colors];
710 for(llp = 0;llp < num_colors;llp++) color_defs[llp].pixel = llp;
711 XQueryColors(d,cmp,color_defs,num_colors);
712
713 wxHSV hsv_defs, hsv;
714 wxXColorToHSV(&hsv,xc);
715
716 int diff, min_diff = 0, pixel = 0;
717
718 for(llp = 0;llp < num_colors;llp++)
719 {
720 wxXColorToHSV(&hsv_defs,&color_defs[llp]);
721 diff = wxSIGN(wxH_WEIGHT * (hsv.h - hsv_defs.h)) +
722 wxSIGN(wxS_WEIGHT * (hsv.s - hsv_defs.s)) +
723 wxSIGN(wxV_WEIGHT * (hsv.v - hsv_defs.v));
724 if (llp == 0) min_diff = diff;
725 if (min_diff > diff) { min_diff = diff; pixel = llp; }
726 if (min_diff == 0) break;
727 }
728
729 xc -> red = color_defs[pixel].red;
730 xc -> green = color_defs[pixel].green;
731 xc -> blue = color_defs[pixel].blue;
732 xc -> flags = DoRed | DoGreen | DoBlue;
733
734 /* FIXME, TODO
735 if (!XAllocColor(d,cmp,xc))
736 cout << "wxAllocNearestColor : Warning : Cannot find nearest color !\n";
737 */
738
739 delete[] color_defs;
740 #endif
741 }
742
743 void wxAllocColor(Display *d,Colormap cmp,XColor *xc)
744 {
745 if (!XAllocColor(d,cmp,xc))
746 {
747 // cout << "wxAllocColor : Warning : Can not allocate color, attempt find nearest !\n";
748 wxAllocNearestColor(d,cmp,xc);
749 }
750 }
751
752 #ifdef __WXDEBUG__
753 wxString wxGetXEventName(XEvent& event)
754 {
755 #if wxUSE_NANOX
756 wxString str(wxT("(some event)"));
757 return str;
758 #else
759 int type = event.xany.type;
760 static char* event_name[] = {
761 "", "unknown(-)", // 0-1
762 "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease", // 2-5
763 "MotionNotify", "EnterNotify", "LeaveNotify", "FocusIn", // 6-9
764 "FocusOut", "KeymapNotify", "Expose", "GraphicsExpose", // 10-13
765 "NoExpose", "VisibilityNotify", "CreateNotify", // 14-16
766 "DestroyNotify", "UnmapNotify", "MapNotify", "MapRequest",// 17-20
767 "ReparentNotify", "ConfigureNotify", "ConfigureRequest", // 21-23
768 "GravityNotify", "ResizeRequest", "CirculateNotify", // 24-26
769 "CirculateRequest", "PropertyNotify", "SelectionClear", // 27-29
770 "SelectionRequest", "SelectionNotify", "ColormapNotify", // 30-32
771 "ClientMessage", "MappingNotify", // 33-34
772 "unknown(+)"}; // 35
773 type = wxMin(35, type); type = wxMax(1, type);
774 wxString str(event_name[type]);
775 return str;
776 #endif
777 }
778 #endif
779
780 // ----------------------------------------------------------------------------
781 // accelerators
782 // ----------------------------------------------------------------------------
783
784 // Find the letter corresponding to the mnemonic, for Motif
785 char wxFindMnemonic (const char *s)
786 {
787 char mnem = 0;
788 int len = strlen (s);
789 int i;
790
791 for (i = 0; i < len; i++)
792 {
793 if (s[i] == '&')
794 {
795 // Carefully handle &&
796 if ((i + 1) <= len && s[i + 1] == '&')
797 i++;
798 else
799 {
800 mnem = s[i + 1];
801 break;
802 }
803 }
804 }
805 return mnem;
806 }
807
808 char* wxFindAccelerator( const char *s )
809 {
810 #if 1
811 // VZ: this function returns incorrect keysym which completely breaks kbd
812 // handling
813 return NULL;
814 #else
815 // The accelerator text is after the \t char.
816 s = strchr( s, '\t' );
817
818 if( !s ) return NULL;
819
820 /*
821 Now we need to format it as X standard:
822
823 input output
824
825 F7 --> <Key>F7
826 Ctrl+N --> Ctrl<Key>N
827 Alt+k --> Meta<Key>k
828 Ctrl+Shift+A --> Ctrl Shift<Key>A
829
830 and handle Ctrl-N & similia
831 */
832
833 static char buf[256];
834
835 buf[0] = '\0';
836 wxString tmp = s + 1; // skip TAB
837 size_t index = 0;
838
839 while( index < tmp.length() )
840 {
841 size_t plus = tmp.find( '+', index );
842 size_t minus = tmp.find( '-', index );
843
844 // neither '+' nor '-', add <Key>
845 if( plus == wxString::npos && minus == wxString::npos )
846 {
847 strcat( buf, "<Key>" );
848 strcat( buf, tmp.c_str() + index );
849
850 return buf;
851 }
852
853 // OK: npos is big and positive
854 size_t sep = wxMin( plus, minus );
855 wxString mod = tmp.substr( index, sep - index );
856
857 // Ctrl -> Ctrl
858 // Shift -> Shift
859 // Alt -> Meta
860 if( mod == "Alt" )
861 mod = "Meta";
862
863 if( buf[0] )
864 strcat( buf, " " );
865
866 strcat( buf, mod.c_str() );
867
868 index = sep + 1;
869 }
870
871 return NULL;
872 #endif
873 }
874
875 XmString wxFindAcceleratorText (const char *s)
876 {
877 #if 1
878 // VZ: this function returns incorrect keysym which completely breaks kbd
879 // handling
880 return NULL;
881 #else
882 // The accelerator text is after the \t char.
883 s = strchr( s, '\t' );
884
885 if( !s ) return NULL;
886
887 return wxStringToXmString( s + 1 ); // skip TAB!
888 #endif
889 }
890
891 // Change a widget's foreground and background colours.
892 void wxDoChangeForegroundColour(WXWidget widget, wxColour& foregroundColour)
893 {
894 // When should we specify the foreground, if it's calculated
895 // by wxComputeColours?
896 // Solution: say we start with the default (computed) foreground colour.
897 // If we call SetForegroundColour explicitly for a control or window,
898 // then the foreground is changed.
899 // Therefore SetBackgroundColour computes the foreground colour, and
900 // SetForegroundColour changes the foreground colour. The ordering is
901 // important.
902
903 XtVaSetValues ((Widget) widget,
904 XmNforeground, foregroundColour.AllocColour(XtDisplay((Widget) widget)),
905 NULL);
906 }
907
908 void wxDoChangeBackgroundColour(WXWidget widget, wxColour& backgroundColour, bool changeArmColour)
909 {
910 wxComputeColours (XtDisplay((Widget) widget), & backgroundColour,
911 (wxColour*) NULL);
912
913 XtVaSetValues ((Widget) widget,
914 XmNbackground, g_itemColors[wxBACK_INDEX].pixel,
915 XmNtopShadowColor, g_itemColors[wxTOPS_INDEX].pixel,
916 XmNbottomShadowColor, g_itemColors[wxBOTS_INDEX].pixel,
917 XmNforeground, g_itemColors[wxFORE_INDEX].pixel,
918 NULL);
919
920 if (changeArmColour)
921 XtVaSetValues ((Widget) widget,
922 XmNarmColor, g_itemColors[wxSELE_INDEX].pixel,
923 NULL);
924 }
925
926 extern void wxDoChangeFont(WXWidget widget, wxFont& font)
927 {
928 // Lesstif 0.87 hangs here, but 0.93 does not
929 #if !wxCHECK_LESSTIF() || wxCHECK_LESSTIF_VERSION( 0, 93 )
930 Widget w = (Widget)widget;
931 XtVaSetValues( w,
932 wxFont::GetFontTag(), font.GetFontType( XtDisplay(w) ),
933 NULL );
934 #endif
935
936 }
937
938 wxString wxXmStringToString( const XmString& xmString )
939 {
940 char *txt;
941 if( XmStringGetLtoR( xmString, XmSTRING_DEFAULT_CHARSET, &txt ) )
942 {
943 wxString str(txt);
944 XtFree (txt);
945 return str;
946 }
947
948 return wxEmptyString;
949 }
950
951 XmString wxStringToXmString( const wxString& str )
952 {
953 return XmStringCreateLtoR((char *)str.c_str(), XmSTRING_DEFAULT_CHARSET);
954 }
955
956 XmString wxStringToXmString( const char* str )
957 {
958 return XmStringCreateLtoR((char *)str, XmSTRING_DEFAULT_CHARSET);
959 }
960
961 // ----------------------------------------------------------------------------
962 // wxBitmap utility functions
963 // ----------------------------------------------------------------------------
964
965 // Creates a bitmap with transparent areas drawn in
966 // the given colour.
967 wxBitmap wxCreateMaskedBitmap(const wxBitmap& bitmap, wxColour& colour)
968 {
969 wxBitmap newBitmap(bitmap.GetWidth(),
970 bitmap.GetHeight(),
971 bitmap.GetDepth());
972 wxMemoryDC destDC;
973 wxMemoryDC srcDC;
974
975 srcDC.SelectObject(bitmap);
976 destDC.SelectObject(newBitmap);
977
978 wxBrush brush(colour, wxSOLID);
979 destDC.SetBackground(brush);
980 destDC.Clear();
981 destDC.Blit(0, 0, bitmap.GetWidth(), bitmap.GetHeight(),
982 &srcDC, 0, 0, wxCOPY, true);
983
984 return newBitmap;
985 }
986
987 // ----------------------------------------------------------------------------
988 // Miscellaneous functions
989 // ----------------------------------------------------------------------------
990
991 WXWidget wxCreateBorderWidget( WXWidget parent, long style )
992 {
993 Widget borderWidget = (Widget)NULL, parentWidget = (Widget)parent;
994
995 if (style & wxSIMPLE_BORDER)
996 {
997 borderWidget = XtVaCreateManagedWidget
998 (
999 "simpleBorder",
1000 xmFrameWidgetClass, parentWidget,
1001 XmNshadowType, XmSHADOW_ETCHED_IN,
1002 XmNshadowThickness, 1,
1003 NULL
1004 );
1005 }
1006 else if (style & wxSUNKEN_BORDER)
1007 {
1008 borderWidget = XtVaCreateManagedWidget
1009 (
1010 "sunkenBorder",
1011 xmFrameWidgetClass, parentWidget,
1012 XmNshadowType, XmSHADOW_IN,
1013 NULL
1014 );
1015 }
1016 else if (style & wxRAISED_BORDER)
1017 {
1018 borderWidget = XtVaCreateManagedWidget
1019 (
1020 "raisedBorder",
1021 xmFrameWidgetClass, parentWidget,
1022 XmNshadowType, XmSHADOW_OUT,
1023 NULL
1024 );
1025 }
1026
1027 return borderWidget;
1028 }