add olaf's neophyte theme, honor numlock and use kp numerics
[goodguy/history.git] / cinelerra-5.1 / guicast / bcwindowbase.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include "bcbitmap.h"
23 #include "bcclipboard.h"
24 #include "bcdisplay.h"
25 #include "bcdisplayinfo.h"
26 #include "bcmenubar.h"
27 #include "bcpixmap.h"
28 #include "bcpopup.h"
29 #include "bcpopupmenu.h"
30 #include "bcrepeater.h"
31 #include "bcresources.h"
32 #include "bcsignals.h"
33 #include "bcsubwindow.h"
34 #include "bcsynchronous.h"
35 #include "bctimer.h"
36 #include "bcwindowbase.h"
37 #include "bcwindowevents.h"
38 #include "bccmodels.h"
39 #include "bccolors.h"
40 #include "condition.h"
41 #include "cursors.h"
42 #include "bchash.h"
43 #include "fonts.h"
44 #include "keys.h"
45 #include "language.h"
46 #include "mutex.h"
47 #include "sizes.h"
48 #include "vframe.h"
49 #include "workarounds.h"
50
51 #ifdef HAVE_GL
52 #include <GL/gl.h>
53 #endif
54 #include <string.h>
55 #include <unistd.h>
56 #include <wchar.h>
57 #include <typeinfo>
58
59 #include <X11/extensions/Xinerama.h>
60 #include <X11/extensions/Xvlib.h>
61 #include <X11/extensions/shape.h>
62 #include <X11/XF86keysym.h>
63 #include <X11/Sunkeysym.h>
64
65
66 BC_ResizeCall::BC_ResizeCall(int w, int h)
67 {
68         this->w = w;
69         this->h = h;
70 }
71
72
73
74
75
76
77
78 int BC_WindowBase::shm_completion_event = -1;
79
80
81
82 BC_Resources BC_WindowBase::resources;
83
84 Window XGroupLeader = 0;
85
86 Mutex BC_KeyboardHandlerLock::keyboard_listener_mutex("keyboard_listener",0);
87 ArrayList<BC_KeyboardHandler*> BC_KeyboardHandler::listeners;
88
89 BC_WindowBase::BC_WindowBase()
90 {
91 //printf("BC_WindowBase::BC_WindowBase 1\n");
92         BC_WindowBase::initialize();
93 }
94
95 BC_WindowBase::~BC_WindowBase()
96 {
97 #ifdef SINGLE_THREAD
98         BC_Display::lock_display("BC_WindowBase::~BC_WindowBase");
99 #else
100         if(window_type == MAIN_WINDOW)
101                 lock_window("BC_WindowBase::~BC_WindowBase");
102 #endif
103
104 #ifdef HAVE_LIBXXF86VM
105         if(window_type == VIDMODE_SCALED_WINDOW && vm_switched) {
106                 restore_vm();
107         }
108 #endif
109         is_deleting = 1;
110
111         hide_tooltip();
112         if(window_type != MAIN_WINDOW)
113         {
114 // stop event input
115                 XSelectInput(top_level->display, this->win, 0);
116                 XSync(top_level->display,0);
117 #ifndef SINGLE_THREAD
118                 top_level->dequeue_events(win);
119 #endif
120 // drop active window refs to this
121                 if(top_level->active_menubar == this) top_level->active_menubar = 0;
122                 if(top_level->active_popup_menu == this) top_level->active_popup_menu = 0;
123                 if(top_level->active_subwindow == this) top_level->active_subwindow = 0;
124 // drop motion window refs to this
125                 if(top_level->motion_events && top_level->last_motion_win == this->win)
126                         top_level->motion_events = 0;
127
128 // Remove pointer from parent window to this
129                 parent_window->subwindows->remove(this);
130         }
131
132         if(grab_active) grab_active->active_grab = 0;
133         if(icon_window) delete icon_window;
134         if(window_type == POPUP_WINDOW)
135                 parent_window->remove_popup(this);
136
137 // Delete the subwindows
138         if(subwindows)
139         {
140                 while(subwindows->total)
141                 {
142 // Subwindow removes its own pointer
143                         delete subwindows->values[0];
144                 }
145                 delete subwindows;
146         }
147
148         delete pixmap;
149
150 //printf("delete glx=%08x, win=%08x %s\n", (unsigned)glx_win, (unsigned)win, title);
151 #ifdef HAVE_GL
152         if( get_resources()->get_synchronous() && glx_win != 0 ) {
153                 get_resources()->get_synchronous()->delete_window(this);
154         }
155 #endif
156         XDestroyWindow(top_level->display, win);
157
158         if(bg_pixmap && !shared_bg_pixmap) delete bg_pixmap;
159         if(icon_pixmap) delete icon_pixmap;
160         if(temp_bitmap) delete temp_bitmap;
161         top_level->active_bitmaps.remove_buffers(this);
162         if(_7segment_pixmaps)
163         {
164                 for(int i = 0; i < TOTAL_7SEGMENT; i++)
165                         delete _7segment_pixmaps[i];
166
167                 delete [] _7segment_pixmaps;
168         }
169
170
171
172         if(window_type == MAIN_WINDOW)
173         {
174                 XFreeGC(display, gc);
175                 static XFontStruct *BC_WindowBase::*xfont[] = {
176                          &BC_WindowBase::smallfont,
177                          &BC_WindowBase::mediumfont,
178                          &BC_WindowBase::largefont,
179                          &BC_WindowBase::bigfont,
180                          &BC_WindowBase::clockfont,
181                 };
182                 for( int i=sizeof(xfont)/sizeof(xfont[0]); --i>=0; )
183                         XFreeFont(display, this->*xfont[i]);
184
185 #ifdef HAVE_XFT
186 // prevents a bug when Xft closes with unrefd fonts
187                 FcPattern *defaults = FcPatternCreate();
188                 FcPatternAddInteger(defaults, "maxunreffonts", 0);
189                 XftDefaultSet(display, defaults);
190
191                 static void *BC_WindowBase::*xft_font[] = {
192                          &BC_WindowBase::smallfont_xft,
193                          &BC_WindowBase::mediumfont_xft,
194                          &BC_WindowBase::largefont_xft,
195                          &BC_WindowBase::bigfont_xft,
196                          &BC_WindowBase::bold_smallfont_xft,
197                          &BC_WindowBase::bold_mediumfont_xft,
198                          &BC_WindowBase::bold_largefont_xft,
199                          &BC_WindowBase::clockfont_xft,
200                 };
201                 for( int i=sizeof(xft_font)/sizeof(xft_font[0]); --i>=0; ) {
202                         XftFont *xft = (XftFont *)(this->*xft_font[i]);
203                         if( xft ) xftFontClose (display, xft);
204                 }
205 #endif
206                 finit_im();
207                 flush();
208                 sync_display();
209
210                 if( xinerama_info )
211                         XFree(xinerama_info);
212                 xinerama_screens = 0;
213                 xinerama_info = 0;
214                 if( xvideo_port_id >= 0 )
215                         XvUngrabPort(display, xvideo_port_id, CurrentTime);
216
217                 unlock_window();
218 // Must be last reference to display.
219 // _XftDisplayInfo needs a lock.
220                 get_resources()->create_window_lock->lock("BC_WindowBase::~BC_WindowBase");
221                 XCloseDisplay(display);
222                 get_resources()->create_window_lock->unlock();
223
224 // clipboard uses a different display connection
225                 clipboard->stop_clipboard();
226                 delete clipboard;
227         }
228
229         resize_history.remove_all_objects();
230
231 #ifndef SINGLE_THREAD
232         common_events.remove_all_objects();
233         delete event_lock;
234         delete event_condition;
235         delete init_lock;
236 #else
237         top_level->window_lock = 0;
238         BC_Display::unlock_display();
239 #endif
240         delete cursor_timer;
241
242 #if HAVE_GL
243         if( glx_fbcfgs_window ) XFree(glx_fbcfgs_window);
244         if( glx_fbcfgs_pbuffer) XFree(glx_fbcfgs_pbuffer);
245         if( glx_fbcfgs_pixmap ) XFree(glx_fbcfgs_pixmap);
246 #endif
247
248         UNSET_ALL_LOCKS(this)
249 }
250
251 int BC_WindowBase::initialize()
252 {
253         done = 0;
254         done_set = 0;
255         window_running = 0;
256         display_lock_owner = 0;
257         test_keypress = 0;
258         keys_return[0] = 0;
259         is_deleting = 0;
260         window_lock = 0;
261         resend_event_window = 0;
262         x = 0;
263         y = 0;
264         w = 0;
265         h = 0;
266         bg_color = -1;
267         line_width = 1;
268         line_dashes = 0;
269         top_level = 0;
270         parent_window = 0;
271         subwindows = 0;
272         xinerama_info = 0;
273         xinerama_screens = 0;
274         xvideo_port_id = -1;
275         video_on = 0;
276         motion_events = 0;
277         resize_events = 0;
278         translation_events = 0;
279         ctrl_mask = shift_mask = alt_mask = 0;
280         cursor_x = cursor_y = button_number = 0;
281         button_down = 0;
282         button_pressed = 0;
283         button_time1 = 0;
284         button_time2 = 0;
285         button_time3 = 0;
286         double_click = 0;
287         triple_click = 0;
288         event_win = 0;
289         last_motion_win = 0;
290         key_pressed = 0;
291         active_grab = 0;
292         grab_active = 0;
293         active_menubar = 0;
294         active_popup_menu = 0;
295         active_subwindow = 0;
296         cursor_entered = 0;
297         pixmap = 0;
298         bg_pixmap = 0;
299         _7segment_pixmaps = 0;
300         tooltip_text = 0;
301         force_tooltip = 0;
302 //      next_repeat_id = 0;
303         tooltip_popup = 0;
304         current_font = MEDIUMFONT;
305         current_color = BLACK;
306         current_cursor = ARROW_CURSOR;
307         hourglass_total = 0;
308         is_dragging = 0;
309         shared_bg_pixmap = 0;
310         icon_pixmap = 0;
311         icon_window = 0;
312         window_type = MAIN_WINDOW;
313         translation_count = 0;
314         x_correction = y_correction = 0;
315         temp_bitmap = 0;
316         tooltip_on = 0;
317         temp_cursor = 0;
318         toggle_value = 0;
319         toggle_drag = 0;
320         has_focus = 0;
321         is_hourglass = 0;
322         is_transparent = 0;
323 #ifdef HAVE_LIBXXF86VM
324         vm_switched = 0;
325 #endif
326         input_method = 0;
327         input_context = 0;
328
329         smallfont = 0;
330         mediumfont = 0;
331         largefont = 0;
332         bigfont = 0;
333         clockfont = 0;
334
335         smallfont_xft = 0;
336         mediumfont_xft = 0;
337         largefont_xft = 0;
338         bigfont_xft = 0;
339         clockfont_xft = 0;
340
341         bold_smallfont_xft = 0;
342         bold_mediumfont_xft = 0;
343         bold_largefont_xft = 0;
344 #ifdef SINGLE_THREAD
345         completion_lock = new Condition(0, "BC_WindowBase::completion_lock");
346 #else
347 // Need these right away since put_event is called before run_window sometimes.
348         event_lock = new Mutex("BC_WindowBase::event_lock");
349         event_condition = new Condition(0, "BC_WindowBase::event_condition");
350         init_lock = new Condition(0, "BC_WindowBase::init_lock");
351 #endif
352
353         cursor_timer = new Timer;
354         event_thread = 0;
355 #ifdef HAVE_GL
356         glx_fbcfgs_window = 0;  n_fbcfgs_window = 0;
357         glx_fbcfgs_pbuffer = 0; n_fbcfgs_pbuffer = 0;
358         glx_fbcfgs_pixmap = 0;  n_fbcfgs_pixmap = 0;
359
360         glx_fb_config = 0;
361         glx_win_context = 0;
362         glx_win = 0;
363 #endif
364
365         flash_enabled = 1;
366         win = 0;
367         return 0;
368 }
369
370
371
372 #define DEFAULT_EVENT_MASKS EnterWindowMask | \
373                         LeaveWindowMask | \
374                         ButtonPressMask | \
375                         ButtonReleaseMask | \
376                         PointerMotionMask | \
377                         FocusChangeMask
378
379
380 int BC_WindowBase::create_window(BC_WindowBase *parent_window, const char *title,
381                 int x, int y, int w, int h, int minw, int minh, int allow_resize,
382                 int private_color, int hide, int bg_color, const char *display_name,
383                 int window_type, BC_Pixmap *bg_pixmap, int group_it)
384 {
385         XSetWindowAttributes attr;
386         unsigned long mask;
387         XSizeHints size_hints;
388         int root_w;
389         int root_h;
390 #ifdef HAVE_LIBXXF86VM
391         int vm;
392 #endif
393
394         id = get_resources()->get_id();
395         if(parent_window) top_level = parent_window->top_level;
396         if( top_level ) lock_window("BC_WindowBase::create_window");
397         get_resources()->create_window_lock->lock("BC_WindowBase::create_window");
398
399 #ifdef HAVE_LIBXXF86VM
400         if(window_type == VIDMODE_SCALED_WINDOW)
401                 closest_vm(&vm,&w,&h);
402 #endif
403
404         this->x = x;
405         this->y = y;
406         this->w = w;
407         this->h = h;
408         this->bg_color = bg_color;
409         this->window_type = window_type;
410         this->hidden = hide;
411         this->private_color = private_color;
412         this->parent_window = parent_window;
413         this->bg_pixmap = bg_pixmap;
414         this->allow_resize = allow_resize;
415         if(display_name)
416                 strcpy(this->display_name, display_name);
417         else
418                 this->display_name[0] = 0;
419
420         put_title(title);
421         if(bg_pixmap) shared_bg_pixmap = 1;
422
423         subwindows = new BC_SubWindowList;
424
425         if(window_type == MAIN_WINDOW)
426         {
427                 top_level = this;
428                 parent_window = this;
429
430
431 #ifdef SINGLE_THREAD
432                 display = BC_Display::get_display(display_name);
433                 BC_Display::lock_display("BC_WindowBase::create_window");
434 //              BC_Display::display_global->new_window(this);
435 #else
436
437 // get the display connection
438
439 // This function must be the first Xlib
440 // function a multi-threaded program calls
441                 XInitThreads();
442                 display = init_display(display_name);
443                 if( shm_completion_event < 0 ) shm_completion_event =
444                         ShmCompletion + XShmGetEventBase(display);
445 #endif
446                 lock_window("BC_WindowBase::create_window 1");
447
448                 screen = DefaultScreen(display);
449                 rootwin = RootWindow(display, screen);
450 // window placement boundaries
451                 if( !xinerama_screens && XineramaIsActive(display) )
452                         xinerama_info = XineramaQueryScreens(display, &xinerama_screens);
453                 root_w = get_root_w(0);
454                 root_h = get_root_h(0);
455
456 #if HAVE_GL
457                 vis = get_glx_visual(display);
458                 if( !vis )
459 #endif
460                         vis = DefaultVisual(display, screen);
461
462                 default_depth = DefaultDepth(display, screen);
463
464                 client_byte_order = (*(const u_int32_t*)"a   ") & 0x00000001;
465                 server_byte_order = (XImageByteOrder(display) == MSBFirst) ? 0 : 1;
466
467
468 // This must be done before fonts to know if antialiasing is available.
469                 init_colors();
470 // get the resources
471                 if(resources.use_shm < 0) resources.initialize_display(this);
472                 x_correction = BC_DisplayInfo::get_left_border();
473                 y_correction = BC_DisplayInfo::get_top_border();
474
475 // clamp window placement
476                 if(this->x + this->w + x_correction > root_w)
477                         this->x = root_w - this->w - x_correction;
478                 if(this->y + this->h + y_correction > root_h)
479                         this->y = root_h - this->h - y_correction;
480                 if(this->x < 0) this->x = 0;
481                 if(this->y < 0) this->y = 0;
482
483                 if(this->bg_color == -1)
484                         this->bg_color = resources.get_bg_color();
485
486 // printf("bcwindowbase 1 %s\n", title);
487 // if(window_type == MAIN_WINDOW) sleep(1);
488 // printf("bcwindowbase 10\n");
489                 init_fonts();
490                 init_gc();
491                 init_cursors();
492
493 // Create the window
494                 mask = CWEventMask | CWBackPixel | CWColormap | CWCursor;
495
496                 attr.event_mask = DEFAULT_EVENT_MASKS |
497                         StructureNotifyMask |
498                         KeyPressMask |
499                         KeyReleaseMask;
500
501                 attr.background_pixel = get_color(this->bg_color);
502                 attr.colormap = cmap;
503                 attr.cursor = get_cursor_struct(ARROW_CURSOR);
504
505                 win = XCreateWindow(display, rootwin,
506                         this->x, this->y, this->w, this->h, 0,
507                         top_level->default_depth, InputOutput,
508                         vis, mask, &attr);
509                 XGetNormalHints(display, win, &size_hints);
510
511                 size_hints.flags = PSize | PMinSize | PMaxSize;
512                 size_hints.width = this->w;
513                 size_hints.height = this->h;
514                 size_hints.min_width = allow_resize ? minw : this->w;
515                 size_hints.max_width = allow_resize ? 32767 : this->w;
516                 size_hints.min_height = allow_resize ? minh : this->h;
517                 size_hints.max_height = allow_resize ? 32767 : this->h;
518                 if(x > -BC_INFINITY && x < BC_INFINITY)
519                 {
520                         size_hints.flags |= PPosition;
521                         size_hints.x = this->x;
522                         size_hints.y = this->y;
523                 }
524                 XSetWMProperties(display, win, 0, 0, 0, 0, &size_hints, 0, 0);
525                 get_atoms();
526                 set_title(title);
527 #ifndef SINGLE_THREAD
528                 clipboard = new BC_Clipboard(this);
529                 clipboard->start_clipboard();
530 #endif
531
532
533                 if (group_it)
534                 {
535                         Atom ClientLeaderXAtom;
536                         if (XGroupLeader == 0)
537                                 XGroupLeader = win;
538                         const char *instance_name = "cinelerra";
539                         const char *class_name = "Cinelerra";
540                         XClassHint *class_hints = XAllocClassHint();
541                         class_hints->res_name = (char*)instance_name;
542                         class_hints->res_class = (char*)class_name;
543                         XSetClassHint(top_level->display, win, class_hints);
544                         XFree(class_hints);
545                         ClientLeaderXAtom = XInternAtom(display, "WM_CLIENT_LEADER", True);
546                         XChangeProperty(display, win, ClientLeaderXAtom, XA_WINDOW, 32,
547                                 PropModeReplace, (unsigned char *)&XGroupLeader, true);
548                 }
549                 init_im();
550         }
551
552 #ifdef HAVE_LIBXXF86VM
553         if(window_type == VIDMODE_SCALED_WINDOW && vm != -1)
554         {
555                 scale_vm (vm);
556                 vm_switched = 1;
557         }
558 #endif
559
560 #ifdef HAVE_LIBXXF86VM
561         if(window_type == POPUP_WINDOW || window_type == VIDMODE_SCALED_WINDOW)
562 #else
563         if(window_type == POPUP_WINDOW)
564 #endif
565         {
566                 mask = CWEventMask | CWBackPixel | CWColormap |
567                         CWOverrideRedirect | CWSaveUnder | CWCursor;
568
569                 attr.event_mask = DEFAULT_EVENT_MASKS |
570                         KeyPressMask |
571                         KeyReleaseMask;
572
573                 if(this->bg_color == -1)
574                         this->bg_color = resources.get_bg_color();
575                 attr.background_pixel = top_level->get_color(bg_color);
576                 attr.colormap = top_level->cmap;
577                 if(top_level->is_hourglass)
578                         attr.cursor = top_level->get_cursor_struct(HOURGLASS_CURSOR);
579                 else
580                         attr.cursor = top_level->get_cursor_struct(ARROW_CURSOR);
581                 attr.override_redirect = True;
582                 attr.save_under = True;
583
584                 win = XCreateWindow(top_level->display,
585                         top_level->rootwin, this->x, this->y, this->w, this->h, 0,
586                         top_level->default_depth, InputOutput, top_level->vis, mask,
587                         &attr);
588                 top_level->add_popup(this);
589         }
590
591         if(window_type == SUB_WINDOW)
592         {
593                 mask = CWEventMask | CWBackPixel | CWCursor;
594                 attr.event_mask = DEFAULT_EVENT_MASKS;
595                 attr.background_pixel = top_level->get_color(this->bg_color);
596                 if(top_level->is_hourglass)
597                         attr.cursor = top_level->get_cursor_struct(HOURGLASS_CURSOR);
598                 else
599                         attr.cursor = top_level->get_cursor_struct(ARROW_CURSOR);
600                 win = XCreateWindow(top_level->display,
601                         parent_window->win, this->x, this->y, this->w, this->h, 0,
602                         top_level->default_depth, InputOutput, top_level->vis, mask,
603                         &attr);
604                 init_window_shape();
605                 if(!hidden) XMapWindow(top_level->display, win);
606         }
607
608 // Create pixmap for all windows
609         pixmap = new BC_Pixmap(this, this->w, this->h);
610
611 // Set up options for main window
612         if(window_type == MAIN_WINDOW)
613         {
614                 if(get_resources()->bg_image && !bg_pixmap && bg_color < 0)
615                 {
616                         this->bg_pixmap = new BC_Pixmap(this,
617                                 get_resources()->bg_image,
618                                 PIXMAP_OPAQUE);
619                 }
620
621                 if(!hidden) show_window();
622
623         }
624
625         draw_background(0, 0, this->w, this->h);
626
627         flash(-1, -1, -1, -1, 0);
628
629 // Set up options for popup window
630 #ifdef HAVE_LIBXXF86VM
631         if(window_type == POPUP_WINDOW || window_type == VIDMODE_SCALED_WINDOW)
632 #else
633         if(window_type == POPUP_WINDOW)
634 #endif
635         {
636                 init_window_shape();
637                 if(!hidden) show_window();
638         }
639         get_resources()->create_window_lock->unlock();
640         unlock_window();
641
642         return 0;
643 }
644
645 Display* BC_WindowBase::init_display(const char *display_name)
646 {
647         Display* display;
648
649         if(display_name && display_name[0] == 0) display_name = NULL;
650         if((display = XOpenDisplay(display_name)) == NULL) {
651                 printf("BC_WindowBase::init_display: cannot connect to X server %s\n",
652                         display_name);
653                 if(getenv("DISPLAY") == NULL) {
654                         printf(_("'DISPLAY' environment variable not set.\n"));
655                         exit(1);
656                 }
657                 else {
658 // Try again with default display.
659                         if((display = XOpenDisplay(0)) == NULL) {
660                                 printf("BC_WindowBase::init_display: cannot connect to default X server.\n");
661                                 exit(1);
662                         }
663                 }
664         }
665
666         static int xsynch = -1;
667         if( xsynch < 0 ) {
668                 const char *cp = getenv("CIN_XSYNCH");
669                 xsynch = !cp ? 0 : atoi(cp);
670         }
671         if( xsynch > 0 )
672                 XSynchronize(display, True);
673
674         return display;
675 }
676
677 Display* BC_WindowBase::get_display()
678 {
679         return top_level->display;
680 }
681
682 int BC_WindowBase::get_screen()
683 {
684         return top_level->screen;
685 }
686
687 int BC_WindowBase::run_window()
688 {
689         done_set = done = 0;
690         return_value = 0;
691
692
693 // Events may have been sent before run_window so can't initialize them here.
694
695 #ifdef SINGLE_THREAD
696         set_repeat(get_resources()->tooltip_delay);
697         BC_Display::display_global->new_window(this);
698
699 // If the first window created, run the display loop in this thread.
700         if(BC_Display::display_global->is_first(this))
701         {
702                 BC_Display::unlock_display();
703                 BC_Display::display_global->loop();
704         }
705         else
706         {
707                 BC_Display::unlock_display();
708                 completion_lock->lock("BC_WindowBase::run_window");
709         }
710
711         BC_Display::lock_display("BC_WindowBase::run_window");
712         BC_Display::display_global->delete_window(this);
713
714         unset_all_repeaters();
715         hide_tooltip();
716         BC_Display::unlock_display();
717
718 #else // SINGLE_THREAD
719
720
721
722 // Start tooltips
723         set_repeat(get_resources()->tooltip_delay);
724
725 // Start X server events
726         event_thread = new BC_WindowEvents(this);
727         event_thread->start();
728
729 // Release wait lock
730         window_running = 1;
731         init_lock->unlock();
732
733 // Handle common events
734         while(!done)
735         {
736                 dispatch_event(0);
737         }
738
739         unset_all_repeaters();
740         hide_tooltip();
741         delete event_thread;
742         event_thread = 0;
743         event_condition->reset();
744         common_events.remove_all_objects();
745         window_running = 0;
746         done = 0;
747
748 #endif // SINGLE_THREAD
749
750         return return_value;
751 }
752
753 int BC_WindowBase::get_key_masks(unsigned int key_state)
754 {
755 // printf("BC_WindowBase::get_key_masks %llx\n",
756 // event->xkey.state);
757         ctrl_mask = (key_state & ControlMask) ? 1 : 0;  // ctrl key down
758         shift_mask = (key_state & ShiftMask) ? 1 : 0;   // shift key down
759         alt_mask = (key_state & Mod1Mask) ? 1 : 0;      // alt key down
760         return 0;
761 }
762
763
764 void BC_WindowBase::add_keyboard_listener(int(BC_WindowBase::*handler)(BC_WindowBase *))
765 {
766         BC_KeyboardHandlerLock set;
767         BC_KeyboardHandler::listeners.append(new BC_KeyboardHandler(handler, this));
768 }
769
770 void BC_WindowBase::del_keyboard_listener(int(BC_WindowBase::*handler)(BC_WindowBase *))
771 {
772         BC_KeyboardHandlerLock set;
773         int i = BC_KeyboardHandler::listeners.size();
774         while( --i >= 0 && BC_KeyboardHandler::listeners[i]->handler!=handler );
775         if( i >= 0 ) BC_KeyboardHandler::listeners.remove_object_number(i);
776 }
777
778 int BC_KeyboardHandler::run_event(BC_WindowBase *wp)
779 {
780         int result = (win->*handler)(wp);
781         return result;
782 }
783
784 int BC_KeyboardHandler::run_listeners(BC_WindowBase *wp)
785 {
786         int result = 0;
787         BC_KeyboardHandlerLock set;
788         for( int i=0; !result && i<listeners.size(); ++i ) {
789                 BC_KeyboardHandler *listener = listeners[i];
790                 result = listener->run_event(wp);
791         }
792         return result;
793 }
794
795 void BC_KeyboardHandler::kill_grabs()
796 {
797         BC_KeyboardHandlerLock set;
798         for( int i=0; i<listeners.size(); ++i ) {
799                 BC_WindowBase *win = listeners[i]->win;
800                 if( win->get_window_type() != POPUP_WINDOW ) continue;
801                 ((BC_Popup *)win)->ungrab_keyboard();
802         }
803 }
804
805 void BC_ActiveBitmaps::reque(XEvent *event)
806 {
807         XShmCompletionEvent *shm_ev = (XShmCompletionEvent *)event;
808         ShmSeg shmseg = shm_ev->shmseg;
809         Drawable drawable = shm_ev->drawable;
810 //printf("BC_BitmapImage::reque %08lx\n",shmseg);
811         active_lock.lock("BC_BitmapImage::reque");
812         BC_BitmapImage *bfr = first;
813         while( bfr && bfr->get_shmseg() != shmseg ) bfr = bfr->next;
814         if( bfr && bfr->drawable == drawable )
815                 remove_pointer(bfr);
816         active_lock.unlock();
817         if( !bfr ) {
818 // sadly, X reports two drawable completions and creates false reporting, so no boobytrap
819 //              printf("BC_BitmapImage::reque missed shmseg %08x, drawable %08x\n",
820 //                       (int)shmseg, (int)drawable);
821                 return;
822         }
823         if( bfr->drawable != drawable ) return;
824         if( bfr->is_zombie() ) { --BC_Bitmap::zombies; delete bfr; return; }
825         bfr->bitmap->reque(bfr);
826 }
827
828 void BC_ActiveBitmaps::insert(BC_BitmapImage *bfr, Drawable pixmap)
829 {
830         active_lock.lock("BC_BitmapImage::insert");
831         bfr->drawable = pixmap;
832         append(bfr);
833         active_lock.unlock();
834 }
835
836 void BC_ActiveBitmaps::remove_buffers(BC_WindowBase *wdw)
837 {
838         active_lock.lock("BC_ActiveBitmaps::remove");
839         for( BC_BitmapImage *nxt=0, *bfr=first; bfr; bfr=nxt ) {
840                 nxt = bfr->next;
841                 if( bfr->is_zombie() ) { --BC_Bitmap::zombies; delete bfr; continue; }
842                 if( bfr->bitmap->parent_window == wdw ) remove_pointer(bfr);
843         }
844         active_lock.unlock();
845 }
846
847 BC_ActiveBitmaps::BC_ActiveBitmaps()
848 {
849 }
850
851 BC_ActiveBitmaps::~BC_ActiveBitmaps()
852 {
853 }
854
855
856
857 int BC_WindowBase::keysym_lookup(XEvent *event)
858 {
859         for( int i = 0; i < KEYPRESSLEN; ++i ) keys_return[i] = 0;
860         for( int i = 0; i < 4; ++i ) wkey_string[i] = 0;
861
862         if( event->xany.send_event && !event->xany.serial ) {
863                 keysym = (KeySym) event->xkey.keycode;
864                 keys_return[0] = keysym;
865                 return 0;
866         }
867         wkey_string_length = 0;
868
869         if( input_context ) {
870                 wkey_string_length = XwcLookupString(input_context,
871                         (XKeyEvent*)event, wkey_string, 4, &keysym, 0);
872 //printf("keysym_lookup 1 %d %d %lx %x %x %x %x\n", wkey_string_length, keysym,
873 //  wkey_string[0], wkey_string[1], wkey_string[2], wkey_string[3]);
874
875                 Status stat;
876                 int ret = Xutf8LookupString(input_context, (XKeyEvent*)event,
877                                 keys_return, KEYPRESSLEN, &keysym, &stat);
878 //printf("keysym_lookup 2 %d %d %lx %x %x\n", ret, stat, keysym, keys_return[0], keys_return[1]);
879                 if( stat == XLookupBoth ) return ret;
880                 if( stat == XLookupKeySym ) return 0;
881         }
882         int ret = XLookupString((XKeyEvent*)event, keys_return, KEYPRESSLEN, &keysym, 0);
883         wkey_string_length = ret;
884         for( int i=0; i<ret; ++i ) wkey_string[i] = keys_return[i];
885         return ret;
886 }
887
888 pthread_t locking_task = (pthread_t)-1L;
889 int locking_event = -1;
890 int locking_message = -1;
891
892 int BC_WindowBase::dispatch_event(XEvent *event)
893 {
894         Window tempwin;
895         int result;
896         XClientMessageEvent *ptr;
897         int cancel_resize, cancel_translation;
898         const int debug = 0;
899
900         key_pressed = 0;
901
902 #ifndef SINGLE_THREAD
903 // If an event is waiting get it, otherwise
904 // wait for next event only if there are no compressed events.
905         if(get_event_count() ||
906                 (!motion_events && !resize_events && !translation_events))
907         {
908                 event = get_event();
909 // Lock out window deletions
910                 lock_window("BC_WindowBase::dispatch_event 1");
911 locking_event = event->type;
912 locking_task = pthread_self();
913 locking_message = event->xclient.message_type;
914         }
915         else
916 // Handle compressed events
917         {
918                 lock_window("BC_WindowBase::dispatch_event 2");
919                 if(resize_events)
920                         dispatch_resize_event(last_resize_w, last_resize_h);
921                 if(motion_events)
922                         dispatch_motion_event();
923                 if(translation_events)
924                         dispatch_translation_event();
925
926                 unlock_window();
927                 return 0;
928         }
929
930 #endif
931
932
933
934
935 //static const char *event_names[] = {
936 //  "Reply", "Error", "KeyPress", "KeyRelease", "ButtonPress", "ButtonRelease", "MotionNotify",
937 //  "EnterNotify", "LeaveNotify", "FocusIn", "FocusOut", "KeymapNotify", "Expose", "GraphicsExpose",
938 //  "NoExpose", "VisibilityNotify", "CreateNotify", "DestroyNotify", "UnmapNotify", "MapNotify",
939 //  "MapRequest", "ReparentNotify", "ConfigureNotify", "ConfigureRequest", "GravityNotify",
940 //  "ResizeRequest", "CirculateNotify", "CirculateRequest", "PropertyNotify", "SelectionClear",
941 //  "SelectionRequest", "SelectionNotify", "ColormapNotify", "ClientMessage", "MappingNotify",
942 //  "GenericEvent", "LASTEvent",
943 //};
944 //
945 //if(debug)
946 //if(event->type != ClientMessage) {
947 // printf("BC_WindowBase::dispatch_event %d %s %p %d (%s)\n",
948 //__LINE__, title, event, event->type,
949 //  event->type>=0 && event->type<sizeof(event_names)/sizeof(event_names[0]) ?
950 //   event_names[event->type] : "Unknown");
951 //}
952
953         if( active_grab ) {
954                 unlock_window();
955                 active_grab->lock_window("BC_WindowBase::dispatch_event 3");
956                 result = active_grab->grab_event(event);
957                 active_grab->unlock_window();
958                 if( result ) return result;
959                 lock_window("BC_WindowBase::dispatch_event 4");
960         }
961
962         switch(event->type) {
963         case ClientMessage:
964 // Clear the resize buffer
965                 if(resize_events) dispatch_resize_event(last_resize_w, last_resize_h);
966 // Clear the motion buffer since this can clear the window
967                 if(motion_events)
968                 {
969                         dispatch_motion_event();
970                 }
971
972                 ptr = (XClientMessageEvent*)event;
973
974
975                 if(ptr->message_type == ProtoXAtom &&
976                         (Atom)ptr->data.l[0] == DelWinXAtom)
977                 {
978                         close_event();
979                 }
980                 else
981                 if(ptr->message_type == RepeaterXAtom)
982                 {
983                         dispatch_repeat_event(ptr->data.l[0]);
984 // Make sure the repeater still exists.
985 //                              for(int i = 0; i < repeaters.total; i++)
986 //                              {
987 //                                      if(repeaters.values[i]->repeat_id == ptr->data.l[0])
988 //                                      {
989 //                                              dispatch_repeat_event_master(ptr->data.l[0]);
990 //                                              break;
991 //                                      }
992 //                              }
993                 }
994                 else
995                 if(ptr->message_type == SetDoneXAtom)
996                 {
997                         done = 1;
998                         } else
999                         { // We currently use X marshalling for xatom events, we can switch to something else later
1000                                 recieve_custom_xatoms((xatom_event *)ptr);
1001                 }
1002                 break;
1003
1004         case FocusIn:
1005                 has_focus = 1;
1006                 dispatch_focus_in();
1007                 break;
1008
1009         case FocusOut:
1010                 has_focus = 0;
1011                 dispatch_focus_out();
1012                 break;
1013
1014 // Maximized
1015         case MapNotify:
1016                 break;
1017
1018 // Minimized
1019         case UnmapNotify:
1020                 break;
1021
1022         case ButtonPress:
1023                 if(motion_events)
1024                 {
1025                         dispatch_motion_event();
1026                 }
1027                 get_key_masks(event->xbutton.state);
1028                 cursor_x = event->xbutton.x;
1029                 cursor_y = event->xbutton.y;
1030                 button_number = event->xbutton.button;
1031
1032 //printf("BC_WindowBase::dispatch_event %d %d\n", __LINE__, button_number);
1033                 event_win = event->xany.window;
1034                 if (button_number < 6)
1035                 {
1036                         if(button_number < 4)
1037                                 button_down = 1;
1038                         button_pressed = event->xbutton.button;
1039                         button_time1 = button_time2;
1040                         button_time2 = button_time3;
1041                         button_time3 = event->xbutton.time;
1042                         drag_x = cursor_x;
1043                         drag_y = cursor_y;
1044                         drag_win = event_win;
1045                         drag_x1 = cursor_x - get_resources()->drag_radius;
1046                         drag_x2 = cursor_x + get_resources()->drag_radius;
1047                         drag_y1 = cursor_y - get_resources()->drag_radius;
1048                         drag_y2 = cursor_y + get_resources()->drag_radius;
1049
1050                         if((long)(button_time3 - button_time1) < resources.double_click * 2)
1051                         {
1052                                 triple_click = 1;
1053                                 button_time3 = button_time2 = button_time1 = 0;
1054                         }
1055                         if((long)(button_time3 - button_time2) < resources.double_click)
1056                         {
1057                                 double_click = 1;
1058 //                              button_time3 = button_time2 = button_time1 = 0;
1059                         }
1060                         else
1061                         {
1062                                 triple_click = 0;
1063                                 double_click = 0;
1064                         }
1065
1066                         dispatch_button_press();
1067                 }
1068                 break;
1069
1070         case ButtonRelease:
1071                 if(motion_events)
1072                 {
1073                         dispatch_motion_event();
1074                 }
1075                 get_key_masks(event->xbutton.state);
1076                 button_number = event->xbutton.button;
1077                 event_win = event->xany.window;
1078                 if (button_number < 6)
1079                 {
1080                         if(button_number < 4)
1081                                 button_down = 0;
1082 //printf("BC_WindowBase::dispatch_event %d %d\n", __LINE__, button_number);
1083
1084                         dispatch_button_release();
1085                 }
1086                 break;
1087
1088         case Expose:
1089                 event_win = event->xany.window;
1090                 dispatch_expose_event();
1091                 break;
1092
1093         case MotionNotify:
1094                 get_key_masks(event->xmotion.state);
1095 // Dispatch previous motion event if this is a subsequent motion from a different window
1096                 if(motion_events && last_motion_win != event->xany.window)
1097                 {
1098                         dispatch_motion_event();
1099                 }
1100
1101 // Buffer the current motion
1102                 motion_events = 1;
1103                 last_motion_state = event->xmotion.state;
1104                 last_motion_x = event->xmotion.x;
1105                 last_motion_y = event->xmotion.y;
1106                 last_motion_win = event->xany.window;
1107                 break;
1108
1109         case ConfigureNotify:
1110 // printf("BC_WindowBase::dispatch_event %d win=%p this->win=%p\n",
1111 // __LINE__,
1112 // event->xany.window,
1113 // win);
1114 // dump_windows();
1115                 XTranslateCoordinates(top_level->display,
1116                         top_level->win,
1117                         top_level->rootwin,
1118                         0,
1119                         0,
1120                         &last_translate_x,
1121                         &last_translate_y,
1122                         &tempwin);
1123                 last_resize_w = event->xconfigure.width;
1124                 last_resize_h = event->xconfigure.height;
1125
1126                 cancel_resize = 0;
1127                 cancel_translation = 0;
1128
1129 // Resize history prevents responses to recursive resize requests
1130                 for(int i = 0; i < resize_history.total && !cancel_resize; i++)
1131                 {
1132                         if(resize_history.values[i]->w == last_resize_w &&
1133                                 resize_history.values[i]->h == last_resize_h)
1134                         {
1135                                 delete resize_history.values[i];
1136                                 resize_history.remove_number(i);
1137                                 cancel_resize = 1;
1138                         }
1139                 }
1140
1141                 if(last_resize_w == w && last_resize_h == h)
1142                         cancel_resize = 1;
1143
1144                 if(!cancel_resize)
1145                 {
1146                         resize_events = 1;
1147                 }
1148
1149                 if((last_translate_x == x && last_translate_y == y))
1150                         cancel_translation = 1;
1151
1152                 if(!cancel_translation)
1153                 {
1154                         translation_events = 1;
1155                 }
1156
1157                 translation_count++;
1158                 break;
1159
1160         case KeyPress:
1161                 get_key_masks(event->xkey.state);
1162                 keys_return[0] = 0;  keysym = -1;
1163                 if(XFilterEvent(event, win)) {
1164                         break;
1165                 }
1166                 if( keysym_lookup(event) < 0 ) {
1167                         printf("keysym %x\n", (uint32_t)keysym);
1168                         break;
1169                 }
1170
1171 //printf("BC_WindowBase::dispatch_event %d keysym=0x%x\n",
1172 //__LINE__,
1173 //keysym);
1174
1175 // block out control keys
1176                 if(keysym > 0xffe0 && keysym < 0xffff) break;
1177 // block out Alt_GR key
1178                 if(keysym == 0xfe03) break;
1179
1180                 if(test_keypress)
1181                          printf("BC_WindowBase::dispatch_event %x\n", (uint32_t)keysym);
1182
1183 #ifdef X_HAVE_UTF8_STRING
1184 //It's Ascii or UTF8?
1185 //              if (keysym != 0xffff && (keys_return[0] & 0xff) >= 0x7f )
1186 //printf("BC_WindowBase::dispatch_event %d %02x%02x\n", __LINE__, keys_return[0], keys_return[1]);
1187
1188                 if( ((keys_return[1] & 0xff) > 0x80) &&
1189                     ((keys_return[0] & 0xff) > 0xC0) ) {
1190 //printf("BC_WindowBase::dispatch_event %d\n", __LINE__);
1191                         key_pressed = keysym & 0xff;
1192                 }
1193                 else {
1194 #endif
1195
1196                 switch(keysym) {
1197 // block out extra keys
1198                 case XK_Alt_L:
1199                 case XK_Alt_R:
1200                 case XK_Shift_L:
1201                 case XK_Shift_R:
1202                 case XK_Control_L:
1203                 case XK_Control_R:
1204                         key_pressed = 0;
1205                         break;
1206
1207 // Translate key codes
1208                 case XK_Return:         key_pressed = RETURN;   break;
1209                 case XK_Up:             key_pressed = UP;       break;
1210                 case XK_Down:           key_pressed = DOWN;     break;
1211                 case XK_Left:           key_pressed = LEFT;     break;
1212                 case XK_Right:          key_pressed = RIGHT;    break;
1213                 case XK_Next:           key_pressed = PGDN;     break;
1214                 case XK_Prior:          key_pressed = PGUP;     break;
1215                 case XK_BackSpace:      key_pressed = BACKSPACE; break;
1216                 case XK_Escape:         key_pressed = ESC;      break;
1217                 case XK_Tab:
1218                         if(shift_down())
1219                                 key_pressed = LEFTTAB;
1220                         else
1221                                 key_pressed = TAB;
1222                         break;
1223                 case XK_ISO_Left_Tab:   key_pressed = LEFTTAB;  break;
1224                 case XK_underscore:     key_pressed = '_';      break;
1225                 case XK_asciitilde:     key_pressed = '~';      break;
1226                 case XK_Delete:         key_pressed = DELETE;   break;
1227                 case XK_Home:           key_pressed = HOME;     break;
1228                 case XK_End:            key_pressed = END;      break;
1229
1230 // number pad
1231                 case XK_KP_Enter:       key_pressed = KPENTER;  break;
1232                 case XK_KP_Add:         key_pressed = KPPLUS;   break;
1233                 case XK_KP_Subtract:    key_pressed = KPMINUS;  break;
1234                 case XK_KP_Multiply:    key_pressed = KPSTAR;   break;
1235                 case XK_KP_Divide:      key_pressed = KPSLASH;  break;
1236                 case XK_KP_1:           key_pressed = '1';      break;
1237                 case XK_KP_End:         key_pressed = KP1;      break;
1238                 case XK_KP_2:           key_pressed = '2';      break;
1239                 case XK_KP_Down:        key_pressed = KP2;      break;
1240                 case XK_KP_3:           key_pressed = '3';      break;
1241                 case XK_KP_Page_Down:   key_pressed = KP3;      break;
1242                 case XK_KP_4:           key_pressed = '4';      break;
1243                 case XK_KP_Left:        key_pressed = KP4;      break;
1244                 case XK_KP_5:           key_pressed = '5';      break;
1245                 case XK_KP_Begin:       key_pressed = KP5;      break;
1246                 case XK_KP_6:           key_pressed = '6';      break;
1247                 case XK_KP_Right:       key_pressed = KP6;      break;
1248                 case XK_KP_7:           key_pressed = '7';      break;
1249                 case XK_KP_Home:        key_pressed = KP7;      break;
1250                 case XK_KP_8:           key_pressed = '8';      break;
1251                 case XK_KP_Up:          key_pressed = KP8;      break;
1252                 case XK_KP_9:           key_pressed = '9';      break;
1253                 case XK_KP_Page_Up:     key_pressed = KP9;      break;
1254                 case XK_KP_0:           key_pressed = '0';      break;
1255                 case XK_KP_Insert:      key_pressed = KPINS;    break;
1256                 case XK_KP_Decimal:
1257                 case XK_KP_Delete:      key_pressed = KPDEL;    break;
1258
1259                 case XK_F1:             key_pressed = KEY_F1;   break;
1260                 case XK_F2:             key_pressed = KEY_F2;   break;
1261                 case XK_F3:             key_pressed = KEY_F3;   break;
1262                 case XK_F4:             key_pressed = KEY_F4;   break;
1263                 case XK_F5:             key_pressed = KEY_F5;   break;
1264                 case XK_F6:             key_pressed = KEY_F6;   break;
1265                 case XK_F7:             key_pressed = KEY_F7;   break;
1266                 case XK_F8:             key_pressed = KEY_F8;   break;
1267                 case XK_F9:             key_pressed = KEY_F9;   break;
1268                 case XK_F10:            key_pressed = KEY_F10;  break;
1269                 case XK_F11:            key_pressed = KEY_F11;  break;
1270                 case XK_F12:            key_pressed = KEY_F12;  break;
1271
1272                 case XK_Menu:           key_pressed = KPMENU;   break;  /* menu */
1273 // remote control
1274 // above        case XK_KP_Enter:       key_pressed = KPENTER;  break;  /* check */
1275                 case XF86XK_MenuKB:     key_pressed = KPMENU;   break;  /* menu */
1276 // intercepted  case XF86XK_PowerDown: key_pressed = KPPOWER;   break;  /* Power */
1277                 case XF86XK_Launch1:    key_pressed = KPTV;     break;  /* TV */
1278                 case XF86XK_Launch2:    key_pressed = KPDVD;    break;  /* DVD */
1279 // intercepted  case XF86XK_WWW:        key_pressed = KPWWEB;   break;  /* WEB */
1280                 case XF86XK_Launch3:    key_pressed = KPBOOK;   break;  /* book */
1281                 case XF86XK_Launch4:    key_pressed = KPHAND;   break;  /* hand */
1282                 case XF86XK_Reply:      key_pressed = KPTMR;    break;  /* timer */
1283                 case SunXK_Front:       key_pressed = KPMAXW;   break;  /* max */
1284 // above        case XK_Left:           key_pressed = LEFT;     break;  /* left */
1285 // above        case XK_Right:          key_pressed = RIGHT;    break;  /* right */
1286 // above        case XK_Down:           key_pressed = DOWN;     break;  /* down */
1287 // above        case XK_Up:             key_pressed = UP;       break;  /* up */
1288 // above        case XK_SPACE:          key_pressed = KPSPACE;  break;  /* ok */
1289 // intercepted  case XF86XK_AudioRaiseVolume: key_pressed = KPVOLU;     break;  /* VOL + */
1290 // intercepted  case XF86XK_AudioMute: key_pressed = KPMUTE;    break;  /* MUTE */
1291 // intercepted  case XF86XK_AudioLowerVolume: key_pressed = KPVOLD;     break;  /* VOL - */
1292                 case XF86XK_ScrollUp:   key_pressed = KPCHUP;   break;  /* CH + */
1293                 case XF86XK_ScrollDown: key_pressed = KPCHDN;   break;  /* CH - */
1294                 case XF86XK_AudioRecord: key_pressed = KPRECD;  break;  /* ( o) red */
1295                 case XF86XK_Forward:    key_pressed = KPPLAY;   break;  /* ( >) */
1296                 case XK_Redo:           key_pressed = KPFWRD;   break;  /* (>>) */
1297                 case XF86XK_Back:       key_pressed = KPBACK;   break;  /* (<<) */
1298                 case XK_Cancel:         key_pressed = KPSTOP;   break;  /* ([]) */
1299                 case XK_Pause:          key_pressed = KPAUSE;   break;  /* ('') */
1300
1301                 default:
1302                         key_pressed = keysym & 0xff;
1303 #ifdef X_HAVE_UTF8_STRING
1304 //printf("BC_WindowBase::dispatch_event %d\n", __LINE__);
1305                         keys_return[1] = 0;
1306 #endif
1307                         break;
1308                 }
1309 #ifdef X_HAVE_UTF8_STRING
1310                 }
1311                 key_pressed_utf8 = keys_return;
1312 #endif
1313
1314
1315                 result = 0;
1316                 if( top_level == this )
1317                         result = BC_KeyboardHandler::run_listeners(this);
1318
1319 //printf("BC_WindowBase::dispatch_event %d %d %x\n", shift_down(), alt_down(), key_pressed);
1320                 if( !result )
1321                         result = dispatch_keypress_event();
1322 // Handle some default keypresses
1323                 if(!result)
1324                 {
1325                         if(key_pressed == 'w' ||
1326                                 key_pressed == 'W')
1327                         {
1328                                 close_event();
1329                         }
1330                 }
1331                 break;
1332
1333         case KeyRelease:
1334                 XLookupString((XKeyEvent*)event, keys_return, 1, &keysym, 0);
1335                 dispatch_keyrelease_event();
1336 // printf("BC_WindowBase::dispatch_event KeyRelease keysym=0x%x keystate=0x%lld\n",
1337 // keysym, event->xkey.state);
1338                 break;
1339
1340         case LeaveNotify:
1341                 if( cursor_entered && event->xcrossing.window == win ) {
1342                         cursor_entered = 0;
1343                 }
1344                 event_win = event->xany.window;
1345                 dispatch_cursor_leave();
1346                 break;
1347
1348         case EnterNotify:
1349                 if( !cursor_entered && event->xcrossing.window == win ) {
1350                         if( !event->xcrossing.focus && get_resources()->grab_input_focus ) {
1351                                 XSetInputFocus(display, win, RevertToParent, CurrentTime);
1352                         }
1353                         cursor_entered = 1;
1354                 }
1355                 event_win = event->xany.window;
1356                 cursor_x = event->xcrossing.x;
1357                 cursor_y = event->xcrossing.y;
1358                 dispatch_cursor_enter();
1359                 break;
1360
1361         default:
1362                 break;
1363         }
1364 //printf("100 %s %p %d\n", title, event, event->type);
1365 //if(event->type != ClientMessage) dump();
1366
1367 #ifndef SINGLE_THREAD
1368         unlock_window();
1369         if(event) {
1370                 if( resend_event_window ) {
1371                         resend_event_window->put_event(event);
1372                         resend_event_window = 0;
1373                 }
1374                 else
1375                         delete event;
1376         }
1377 #else
1378 //      if(done) completion_lock->unlock();
1379 #endif
1380
1381 if(debug) printf("BC_WindowBase::dispatch_event this=%p %d\n", this, __LINE__);
1382         return 0;
1383 }
1384
1385 int BC_WindowBase::dispatch_expose_event()
1386 {
1387         int result = 0;
1388         for(int i = 0; i < subwindows->total && !result; i++)
1389         {
1390                 result = subwindows->values[i]->dispatch_expose_event();
1391         }
1392
1393 // Propagate to user
1394         if(!result) expose_event();
1395         return result;
1396 }
1397
1398 int BC_WindowBase::dispatch_resize_event(int w, int h)
1399 {
1400 // Can't store new w and h until the event is handles
1401 // because bcfilebox depends on the old w and h to
1402 // reposition widgets.
1403         if( window_type == MAIN_WINDOW ) {
1404                 flash_enabled = 0;
1405                 resize_events = 0;
1406
1407                 delete pixmap;
1408                 pixmap = new BC_Pixmap(this, w, h);
1409                 clear_box(0, 0, w, h);
1410         }
1411
1412 // Propagate to subwindows
1413         for(int i = 0; i < subwindows->total; i++) {
1414                 subwindows->values[i]->dispatch_resize_event(w, h);
1415         }
1416
1417 // Propagate to user
1418         resize_event(w, h);
1419
1420         if( window_type == MAIN_WINDOW ) {
1421                 this->w = w;
1422                 this->h = h;
1423                 dispatch_flash();
1424                 flush();
1425         }
1426         return 0;
1427 }
1428
1429 int BC_WindowBase::dispatch_flash()
1430 {
1431         flash_enabled = 1;
1432         for(int i = 0; i < subwindows->total; i++)
1433                 subwindows->values[i]->dispatch_flash();
1434         return flash(0);
1435 }
1436
1437 int BC_WindowBase::dispatch_translation_event()
1438 {
1439         translation_events = 0;
1440         if(window_type == MAIN_WINDOW)
1441         {
1442                 prev_x = x;
1443                 prev_y = y;
1444                 x = last_translate_x;
1445                 y = last_translate_y;
1446 // Correct for window manager offsets
1447                 x -= x_correction;
1448                 y -= y_correction;
1449         }
1450
1451         for(int i = 0; i < subwindows->total; i++)
1452         {
1453                 subwindows->values[i]->dispatch_translation_event();
1454         }
1455
1456         translation_event();
1457         return 0;
1458 }
1459
1460 int BC_WindowBase::dispatch_motion_event()
1461 {
1462         int result = 0;
1463         unhide_cursor();
1464
1465         if(top_level == this)
1466         {
1467                 motion_events = 0;
1468                 event_win = last_motion_win;
1469                 get_key_masks(last_motion_state);
1470
1471 // Test for grab
1472                 if(get_button_down() && !active_menubar && !active_popup_menu)
1473                 {
1474                         if(!result)
1475                         {
1476                                 cursor_x = last_motion_x;
1477                                 cursor_y = last_motion_y;
1478                                 result = dispatch_drag_motion();
1479                         }
1480
1481                         if(!result &&
1482                                 (last_motion_x < drag_x1 || last_motion_x >= drag_x2 ||
1483                                 last_motion_y < drag_y1 || last_motion_y >= drag_y2))
1484                         {
1485                                 cursor_x = drag_x;
1486                                 cursor_y = drag_y;
1487
1488                                 result = dispatch_drag_start();
1489                         }
1490                 }
1491
1492                 cursor_x = last_motion_x;
1493                 cursor_y = last_motion_y;
1494
1495 // printf("BC_WindowBase::dispatch_motion_event %d %p %p %p\n",
1496 // __LINE__,
1497 // active_menubar,
1498 // active_popup_menu,
1499 // active_subwindow);
1500
1501                 if(active_menubar && !result) result = active_menubar->dispatch_motion_event();
1502                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_motion_event();
1503                 if(active_subwindow && !result) result = active_subwindow->dispatch_motion_event();
1504         }
1505
1506 // Dispatch in stacking order
1507         for(int i = subwindows->size() - 1; i >= 0 && !result; i--)
1508         {
1509                 result = subwindows->values[i]->dispatch_motion_event();
1510         }
1511
1512         if(!result) result = cursor_motion_event();    // give to user
1513         return result;
1514 }
1515
1516 int BC_WindowBase::dispatch_keypress_event()
1517 {
1518         int result = 0;
1519         if(top_level == this)
1520         {
1521                 if(active_subwindow) result = active_subwindow->dispatch_keypress_event();
1522         }
1523
1524         for(int i = 0; i < subwindows->total && !result; i++)
1525         {
1526                 result = subwindows->values[i]->dispatch_keypress_event();
1527         }
1528
1529         if(!result) result = keypress_event();
1530
1531         return result;
1532 }
1533
1534 int BC_WindowBase::dispatch_keyrelease_event()
1535 {
1536         int result = 0;
1537         if(top_level == this)
1538         {
1539                 if(active_subwindow) result = active_subwindow->dispatch_keyrelease_event();
1540         }
1541
1542         for(int i = 0; i < subwindows->total && !result; i++)
1543         {
1544                 result = subwindows->values[i]->dispatch_keyrelease_event();
1545         }
1546
1547         if(!result) result = keyrelease_event();
1548
1549         return result;
1550 }
1551
1552 int BC_WindowBase::dispatch_focus_in()
1553 {
1554         for(int i = 0; i < subwindows->total; i++)
1555         {
1556                 subwindows->values[i]->dispatch_focus_in();
1557         }
1558
1559         focus_in_event();
1560
1561         return 0;
1562 }
1563
1564 int BC_WindowBase::dispatch_focus_out()
1565 {
1566         for(int i = 0; i < subwindows->total; i++)
1567         {
1568                 subwindows->values[i]->dispatch_focus_out();
1569         }
1570
1571         focus_out_event();
1572
1573         return 0;
1574 }
1575
1576 int BC_WindowBase::get_has_focus()
1577 {
1578         return top_level->has_focus;
1579 }
1580
1581 int BC_WindowBase::get_deleting()
1582 {
1583         if(is_deleting) return 1;
1584         if(parent_window && parent_window->get_deleting()) return 1;
1585         return 0;
1586 }
1587
1588 int BC_WindowBase::dispatch_button_press()
1589 {
1590         int result = 0;
1591
1592
1593         if(top_level == this)
1594         {
1595                 if(active_menubar) result = active_menubar->dispatch_button_press();
1596                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_button_press();
1597                 if(active_subwindow && !result) result = active_subwindow->dispatch_button_press();
1598         }
1599
1600         for(int i = 0; i < subwindows->total && !result; i++)
1601         {
1602                 result = subwindows->values[i]->dispatch_button_press();
1603         }
1604
1605         if(!result) result = button_press_event();
1606
1607
1608         return result;
1609 }
1610
1611 int BC_WindowBase::dispatch_button_release()
1612 {
1613         int result = 0;
1614         if(top_level == this)
1615         {
1616                 if(active_menubar) result = active_menubar->dispatch_button_release();
1617                 if(active_popup_menu && !result) result = active_popup_menu->dispatch_button_release();
1618                 if(active_subwindow && !result) result = active_subwindow->dispatch_button_release();
1619                 if(!result && button_number != 4 && button_number != 5)
1620                         result = dispatch_drag_stop();
1621         }
1622
1623         for(int i = 0; i < subwindows->total && !result; i++)
1624         {
1625                 result = subwindows->values[i]->dispatch_button_release();
1626         }
1627
1628         if(!result)
1629         {
1630                 result = button_release_event();
1631         }
1632
1633         return result;
1634 }
1635
1636
1637 int BC_WindowBase::dispatch_repeat_event(int64_t duration)
1638 {
1639
1640 // all repeat event handlers get called and decide based on activity and duration
1641 // whether to respond
1642         for(int i = 0; i < subwindows->total; i++)
1643         {
1644                 subwindows->values[i]->dispatch_repeat_event(duration);
1645         }
1646
1647
1648         repeat_event(duration);
1649
1650
1651
1652 // Unlock next repeat signal
1653         if(window_type == MAIN_WINDOW)
1654         {
1655 #ifdef SINGLE_THREAD
1656                 BC_Display::display_global->unlock_repeaters(duration);
1657 #else
1658                 for(int i = 0; i < repeaters.total; i++)
1659                 {
1660                         if(repeaters.values[i]->delay == duration)
1661                         {
1662                                 repeaters.values[i]->repeat_lock->unlock();
1663                         }
1664                 }
1665 #endif
1666         }
1667         return 0;
1668 }
1669
1670 void BC_WindowBase::unhide_cursor()
1671 {
1672         if(is_transparent)
1673         {
1674                 is_transparent = 0;
1675                 if(top_level->is_hourglass)
1676                         set_cursor(HOURGLASS_CURSOR, 1, 0);
1677                 else
1678                         set_cursor(current_cursor, 1, 0);
1679         }
1680         cursor_timer->update();
1681 }
1682
1683
1684 void BC_WindowBase::update_video_cursor()
1685 {
1686         if(video_on && !is_transparent)
1687         {
1688                 if(cursor_timer->get_difference() > VIDEO_CURSOR_TIMEOUT && !is_transparent)
1689                 {
1690                         is_transparent = 1;
1691                         set_cursor(TRANSPARENT_CURSOR, 1, 1);
1692                         cursor_timer->update();
1693                 }
1694         }
1695         else
1696         {
1697                 cursor_timer->update();
1698         }
1699 }
1700
1701
1702 int BC_WindowBase::dispatch_cursor_leave()
1703 {
1704         unhide_cursor();
1705
1706         for(int i = 0; i < subwindows->total; i++)
1707         {
1708                 subwindows->values[i]->dispatch_cursor_leave();
1709         }
1710
1711         cursor_leave_event();
1712         return 0;
1713 }
1714
1715 int BC_WindowBase::dispatch_cursor_enter()
1716 {
1717         int result = 0;
1718
1719         unhide_cursor();
1720
1721         if(active_menubar) result = active_menubar->dispatch_cursor_enter();
1722         if(!result && active_popup_menu) result = active_popup_menu->dispatch_cursor_enter();
1723         if(!result && active_subwindow) result = active_subwindow->dispatch_cursor_enter();
1724
1725         for(int i = 0; !result && i < subwindows->total; i++)
1726         {
1727                 result = subwindows->values[i]->dispatch_cursor_enter();
1728         }
1729
1730         if(!result) result = cursor_enter_event();
1731         return result;
1732 }
1733
1734 int BC_WindowBase::cursor_enter_event()
1735 {
1736         return 0;
1737 }
1738
1739 int BC_WindowBase::cursor_leave_event()
1740 {
1741         return 0;
1742 }
1743
1744 int BC_WindowBase::close_event()
1745 {
1746         set_done(1);
1747         return 1;
1748 }
1749
1750 int BC_WindowBase::dispatch_drag_start()
1751 {
1752         int result = 0;
1753         if(active_menubar) result = active_menubar->dispatch_drag_start();
1754         if(!result && active_popup_menu) result = active_popup_menu->dispatch_drag_start();
1755         if(!result && active_subwindow) result = active_subwindow->dispatch_drag_start();
1756
1757         for(int i = 0; i < subwindows->total && !result; i++)
1758         {
1759                 result = subwindows->values[i]->dispatch_drag_start();
1760         }
1761
1762         if(!result) result = is_dragging = drag_start_event();
1763         return result;
1764 }
1765
1766 int BC_WindowBase::dispatch_drag_stop()
1767 {
1768         int result = 0;
1769
1770         for(int i = 0; i < subwindows->total && !result; i++)
1771         {
1772                 result = subwindows->values[i]->dispatch_drag_stop();
1773         }
1774
1775         if(is_dragging && !result)
1776         {
1777                 drag_stop_event();
1778                 is_dragging = 0;
1779                 result = 1;
1780         }
1781
1782         return result;
1783 }
1784
1785 int BC_WindowBase::dispatch_drag_motion()
1786 {
1787         int result = 0;
1788         for(int i = 0; i < subwindows->total && !result; i++)
1789         {
1790                 result = subwindows->values[i]->dispatch_drag_motion();
1791         }
1792
1793         if(is_dragging && !result)
1794         {
1795                 drag_motion_event();
1796                 result = 1;
1797         }
1798
1799         return result;
1800 }
1801
1802
1803 int BC_WindowBase::show_tooltip(const char *text, int x, int y, int w, int h)
1804 {
1805 // default text
1806         int forced = !text ? force_tooltip : 1;
1807         if( !text ) text = tooltip_text;
1808         if( !text || (!forced && !get_resources()->tooltips_enabled) ) {
1809                 top_level->hide_tooltip();
1810                 return 1;
1811         }
1812 // default w,h
1813         if(w < 0) w = get_text_width(MEDIUMFONT, text)  + TOOLTIP_MARGIN * 2;
1814         if(h < 0) h = get_text_height(MEDIUMFONT, text) + TOOLTIP_MARGIN * 2;
1815 // default x,y (win relative)
1816         if( x < 0 ) x = get_w();
1817         if( y < 0 ) y = get_h();
1818         int wx, wy;
1819         get_root_coordinates(x, y, &wx, &wy);
1820 // keep the tip inside the window/display
1821         int x0 = top_level->get_x(), x1 = x0 + top_level->get_w();
1822         int x2 = top_level->get_screen_x(0, -1) + top_level->get_screen_w(0, -1);
1823         if( x1 > x2 ) x1 = x2;
1824         if( wx < x0 ) wx = x0;
1825         if( wx >= (x1-=w) ) wx = x1;
1826         int y0 = top_level->get_y(), y1 = y0 + top_level->get_h();
1827         int y2 = top_level->get_root_h(0);
1828         if( y1 > y2 ) y1 = y2;
1829         if( wy < y0 ) wy = y0;
1830         if( wy >= (y1-=h) ) wy = y1;
1831 // avoid tip under cursor (flickers)
1832         int abs_x, abs_y;
1833         get_abs_cursor(abs_x,abs_y, 0);
1834         if( wx < abs_x && abs_x < wx+w && wy < abs_y && abs_y < wy+h ) {
1835                 if( wx-abs_x < wy-abs_y )
1836                         wx = abs_x+1;
1837                 else
1838                         wy = abs_y+1;
1839         }
1840         if( !tooltip_on ) {
1841                 tooltip_on = 1;
1842                 tooltip_popup = new BC_Popup(top_level, wx, wy, w, h,
1843                                 get_resources()->tooltip_bg_color);
1844         }
1845         else
1846                 tooltip_popup->reposition_window(wx, wy, w, h);
1847
1848         draw_tooltip(text);
1849         tooltip_popup->flash();
1850         tooltip_popup->flush();
1851         return 0;
1852 }
1853
1854 int BC_WindowBase::hide_tooltip()
1855 {
1856         if(subwindows)
1857                 for(int i = 0; i < subwindows->total; i++)
1858                 {
1859                         subwindows->values[i]->hide_tooltip();
1860                 }
1861
1862         if(tooltip_on)
1863         {
1864                 tooltip_on = 0;
1865                 delete tooltip_popup;
1866                 tooltip_popup = 0;
1867         }
1868         return 0;
1869 }
1870
1871 const char *BC_WindowBase::get_tooltip()
1872 {
1873         return tooltip_text;
1874 }
1875
1876 int BC_WindowBase::set_tooltip(const char *text)
1877 {
1878         tooltip_text = text;
1879
1880 // Update existing tooltip if it is visible
1881         if(tooltip_on)
1882         {
1883                 draw_tooltip();
1884                 tooltip_popup->flash();
1885         }
1886         return 0;
1887 }
1888 // signal the event handler to repeat
1889 int BC_WindowBase::set_repeat(int64_t duration)
1890 {
1891         if(duration <= 0)
1892         {
1893                 printf("BC_WindowBase::set_repeat duration=%jd\n", duration);
1894                 return 0;
1895         }
1896         if(window_type != MAIN_WINDOW) return top_level->set_repeat(duration);
1897
1898 #ifdef SINGLE_THREAD
1899         BC_Display::display_global->set_repeat(this, duration);
1900 #else
1901 // test repeater database for duplicates
1902         for(int i = 0; i < repeaters.total; i++)
1903         {
1904 // Already exists
1905                 if(repeaters.values[i]->delay == duration)
1906                 {
1907                         repeaters.values[i]->start_repeating(this);
1908                         return 0;
1909                 }
1910         }
1911
1912         BC_Repeater *repeater = new BC_Repeater(this, duration);
1913         repeater->initialize();
1914         repeaters.append(repeater);
1915         repeater->start_repeating();
1916 #endif
1917         return 0;
1918 }
1919
1920 int BC_WindowBase::unset_repeat(int64_t duration)
1921 {
1922         if(window_type != MAIN_WINDOW) return top_level->unset_repeat(duration);
1923
1924 #ifdef SINGLE_THREAD
1925         BC_Display::display_global->unset_repeat(this, duration);
1926 #else
1927         for(int i = 0; i < repeaters.total; i++)
1928         {
1929                 if(repeaters.values[i]->delay == duration)
1930                 {
1931                         repeaters.values[i]->stop_repeating();
1932                 }
1933         }
1934 #endif
1935         return 0;
1936 }
1937
1938
1939 int BC_WindowBase::unset_all_repeaters()
1940 {
1941 #ifdef SINGLE_THREAD
1942         BC_Display::display_global->unset_all_repeaters(this);
1943 #else
1944         for(int i = 0; i < repeaters.total; i++)
1945         {
1946                 repeaters.values[i]->stop_repeating();
1947         }
1948         repeaters.remove_all_objects();
1949 #endif
1950         return 0;
1951 }
1952
1953 // long BC_WindowBase::get_repeat_id()
1954 // {
1955 //      return top_level->next_repeat_id++;
1956 // }
1957
1958 XEvent *BC_WindowBase::new_xevent()
1959 {
1960         XEvent *event = new XEvent;
1961         memset(event, 0, sizeof(*event));
1962         return event;
1963 }
1964
1965 #ifndef SINGLE_THREAD
1966 int BC_WindowBase::arm_repeat(int64_t duration)
1967 {
1968         XEvent *event = new_xevent();
1969         XClientMessageEvent *ptr = (XClientMessageEvent*)event;
1970         ptr->type = ClientMessage;
1971         ptr->message_type = RepeaterXAtom;
1972         ptr->format = 32;
1973         ptr->data.l[0] = duration;
1974
1975 // Couldn't use XSendEvent since it locked up randomly.
1976         put_event(event);
1977         return 0;
1978 }
1979 #endif
1980
1981 int BC_WindowBase::recieve_custom_xatoms(xatom_event *event)
1982 {
1983         return 0;
1984 }
1985
1986 int BC_WindowBase::send_custom_xatom(xatom_event *event)
1987 {
1988 #ifndef SINGLE_THREAD
1989         XEvent *myevent = new_xevent();
1990         XClientMessageEvent *ptr = (XClientMessageEvent*)myevent;
1991         ptr->type = ClientMessage;
1992         ptr->message_type = event->message_type;
1993         ptr->format = event->format;
1994         ptr->data.l[0] = event->data.l[0];
1995         ptr->data.l[1] = event->data.l[1];
1996         ptr->data.l[2] = event->data.l[2];
1997         ptr->data.l[3] = event->data.l[3];
1998         ptr->data.l[4] = event->data.l[4];
1999
2000         put_event(myevent);
2001 #endif
2002         return 0;
2003 }
2004
2005
2006
2007 Atom BC_WindowBase::create_xatom(const char *atom_name)
2008 {
2009         return XInternAtom(display, atom_name, False);
2010 }
2011
2012 int BC_WindowBase::get_atoms()
2013 {
2014         SetDoneXAtom =  XInternAtom(display, "BC_REPEAT_EVENT", False);
2015         RepeaterXAtom = XInternAtom(display, "BC_CLOSE_EVENT", False);
2016         DestroyAtom =   XInternAtom(display, "BC_DESTROY_WINDOW", False);
2017         DelWinXAtom =   XInternAtom(display, "WM_DELETE_WINDOW", False);
2018         if( (ProtoXAtom = XInternAtom(display, "WM_PROTOCOLS", False)) != 0 )
2019                 XChangeProperty(display, win, ProtoXAtom, XA_ATOM, 32,
2020                         PropModeReplace, (unsigned char *)&DelWinXAtom, True);
2021         return 0;
2022
2023 }
2024
2025
2026 void BC_WindowBase::init_cursors()
2027 {
2028         arrow_cursor = XCreateFontCursor(display, XC_top_left_arrow);
2029         cross_cursor = XCreateFontCursor(display, XC_crosshair);
2030         ibeam_cursor = XCreateFontCursor(display, XC_xterm);
2031         vseparate_cursor = XCreateFontCursor(display, XC_sb_v_double_arrow);
2032         hseparate_cursor = XCreateFontCursor(display, XC_sb_h_double_arrow);
2033         move_cursor = XCreateFontCursor(display, XC_fleur);
2034         left_cursor = XCreateFontCursor(display, XC_sb_left_arrow);
2035         right_cursor = XCreateFontCursor(display, XC_sb_right_arrow);
2036         upright_arrow_cursor = XCreateFontCursor(display, XC_arrow);
2037         upleft_resize_cursor = XCreateFontCursor(display, XC_top_left_corner);
2038         upright_resize_cursor = XCreateFontCursor(display, XC_top_right_corner);
2039         downleft_resize_cursor = XCreateFontCursor(display, XC_bottom_left_corner);
2040         downright_resize_cursor = XCreateFontCursor(display, XC_bottom_right_corner);
2041         hourglass_cursor = XCreateFontCursor(display, XC_watch);
2042         grabbed_cursor = create_grab_cursor();
2043
2044         static char cursor_data[] = { 0,0,0,0, 0,0,0,0 };
2045         Colormap colormap = DefaultColormap(display, screen);
2046         Pixmap pixmap_bottom = XCreateBitmapFromData(display,
2047                 rootwin, cursor_data, 8, 8);
2048         XColor black, dummy;
2049         XAllocNamedColor(display, colormap, "black", &black, &dummy);
2050         transparent_cursor = XCreatePixmapCursor(display,
2051                 pixmap_bottom, pixmap_bottom, &black, &black, 0, 0);
2052 //      XDefineCursor(display, win, transparent_cursor);
2053         XFreePixmap(display, pixmap_bottom);
2054 }
2055
2056 int BC_WindowBase::evaluate_color_model(int client_byte_order, int server_byte_order, int depth)
2057 {
2058         int color_model = BC_TRANSPARENCY;
2059         switch(depth)
2060         {
2061                 case 8:
2062                         color_model = BC_RGB8;
2063                         break;
2064                 case 16:
2065                         color_model = (server_byte_order == client_byte_order) ? BC_RGB565 : BC_BGR565;
2066                         break;
2067                 case 24:
2068                         color_model = server_byte_order ? BC_BGR888 : BC_RGB888;
2069                         break;
2070                 case 32:
2071                         color_model = server_byte_order ? BC_BGR8888 : BC_ARGB8888;
2072                         break;
2073         }
2074         return color_model;
2075 }
2076
2077 int BC_WindowBase::init_colors()
2078 {
2079         total_colors = 0;
2080         current_color_value = current_color_pixel = 0;
2081
2082 // Get the real depth
2083         char *data = 0;
2084         XImage *ximage;
2085         ximage = XCreateImage(top_level->display,
2086                                         top_level->vis,
2087                                         top_level->default_depth,
2088                                         ZPixmap,
2089                                         0,
2090                                         data,
2091                                         16,
2092                                         16,
2093                                         8,
2094                                         0);
2095         bits_per_pixel = ximage->bits_per_pixel;
2096         XDestroyImage(ximage);
2097
2098         color_model = evaluate_color_model(client_byte_order,
2099                 server_byte_order,
2100                 bits_per_pixel);
2101 // Get the color model
2102         switch(color_model)
2103         {
2104                 case BC_RGB8:
2105                         if(private_color)
2106                         {
2107                                 cmap = XCreateColormap(display, rootwin, vis, AllocNone);
2108                                 create_private_colors();
2109                         }
2110                         else
2111                         {
2112                                 cmap = DefaultColormap(display, screen);
2113                                 create_shared_colors();
2114                         }
2115
2116                         allocate_color_table();
2117                         break;
2118
2119                 default:
2120                         //cmap = DefaultColormap(display, screen);
2121                         cmap = XCreateColormap(display, rootwin, vis, AllocNone );
2122                         break;
2123         }
2124         return 0;
2125 }
2126
2127 int BC_WindowBase::create_private_colors()
2128 {
2129         int color;
2130         total_colors = 256;
2131
2132         for(int i = 0; i < 255; i++)
2133         {
2134                 color = (i & 0xc0) << 16;
2135                 color += (i & 0x38) << 10;
2136                 color += (i & 0x7) << 5;
2137                 color_table[i][0] = color;
2138         }
2139         create_shared_colors();        // overwrite the necessary colors on the table
2140         return 0;
2141 }
2142
2143
2144 int BC_WindowBase::create_color(int color)
2145 {
2146         if(total_colors == 256)
2147         {
2148 // replace the closest match with an exact match
2149                 color_table[get_color_rgb8(color)][0] = color;
2150         }
2151         else
2152         {
2153 // add the color to the table
2154                 color_table[total_colors][0] = color;
2155                 total_colors++;
2156         }
2157         return 0;
2158 }
2159
2160 int BC_WindowBase::create_shared_colors()
2161 {
2162         create_color(BLACK);
2163         create_color(WHITE);
2164
2165         create_color(LTGREY);
2166         create_color(MEGREY);
2167         create_color(MDGREY);
2168         create_color(DKGREY);
2169
2170         create_color(LTCYAN);
2171         create_color(MECYAN);
2172         create_color(MDCYAN);
2173         create_color(DKCYAN);
2174
2175         create_color(LTGREEN);
2176         create_color(GREEN);
2177         create_color(DKGREEN);
2178
2179         create_color(LTPINK);
2180         create_color(PINK);
2181         create_color(RED);
2182
2183         create_color(LTBLUE);
2184         create_color(BLUE);
2185         create_color(DKBLUE);
2186
2187         create_color(LTYELLOW);
2188         create_color(MEYELLOW);
2189         create_color(MDYELLOW);
2190         create_color(DKYELLOW);
2191
2192         create_color(LTPURPLE);
2193         create_color(MEPURPLE);
2194         create_color(MDPURPLE);
2195         create_color(DKPURPLE);
2196
2197         create_color(FGGREY);
2198         create_color(MNBLUE);
2199         create_color(ORANGE);
2200         create_color(FTGREY);
2201
2202         return 0;
2203 }
2204
2205 Cursor BC_WindowBase::create_grab_cursor()
2206 {
2207         int iw = 23, iw1 = iw-1, iw2 = iw/2;
2208         int ih = 23, ih1 = ih-1, ih2 = ih/2;
2209         VFrame grab(iw,ih,BC_RGB888);
2210         grab.clear_frame();
2211         grab.set_pixel_color(RED);   // fg
2212         grab.draw_smooth(iw2,0,   iw1,0,   iw1,ih2);
2213         grab.draw_smooth(iw1,ih2, iw1,ih1, iw2,ih1);
2214         grab.draw_smooth(iw2,ih1, 0,ih1,   0,ih2);
2215         grab.draw_smooth(0,ih2,   0,0,     iw2,0);
2216         grab.set_pixel_color(WHITE); // bg
2217         grab.draw_line(0,ih2,     iw2-2,ih2);
2218         grab.draw_line(iw2+2,ih2, iw1,ih2);
2219         grab.draw_line(iw2,0,     iw2,ih2-2);
2220         grab.draw_line(iw2,ih2+2, iw2,ih1);
2221
2222         int bpl = (iw+7)/8, isz = bpl * ih;
2223         char img[isz];  memset(img, 0, isz);
2224         char msk[isz];  memset(msk, 0, isz);
2225         unsigned char **rows = grab.get_rows();
2226         for( int iy=0; iy<ih; ++iy ) {
2227                 char *op = img + iy*bpl;
2228                 char *mp = msk + iy*bpl;
2229                 unsigned char *ip = rows[iy];
2230                 for( int ix=0; ix<iw; ++ix,ip+=3 ) {
2231                         if( ip[0] ) mp[ix>>3] |= (1<<(ix&7));
2232                         if( !ip[1] ) op[ix>>3] |= (1<<(ix&7));
2233                 }
2234         }
2235         unsigned long white_pix = WhitePixel(display, screen);
2236         unsigned long black_pix = BlackPixel(display, screen);
2237         Pixmap img_xpm = XCreatePixmapFromBitmapData(display, rootwin,
2238                 img, iw,ih, white_pix,black_pix, 1);
2239         Pixmap msk_xpm = XCreatePixmapFromBitmapData(display, rootwin,
2240                 msk, iw,ih, white_pix,black_pix, 1);
2241
2242         XColor fc, bc;
2243         fc.flags = bc.flags = DoRed | DoGreen | DoBlue;
2244         fc.red = 0xffff; fc.green = fc.blue = 0;  // fg
2245         bc.red = bc.green = bc.blue = 0x0000;     // bg
2246         Cursor cursor = XCreatePixmapCursor(display, img_xpm,msk_xpm, &fc,&bc, iw2,ih2);
2247         XFreePixmap(display, img_xpm);
2248         XFreePixmap(display, msk_xpm);
2249         return cursor;
2250 }
2251
2252 int BC_WindowBase::allocate_color_table()
2253 {
2254         int red, green, blue, color;
2255         XColor col;
2256
2257         for(int i = 0; i < total_colors; i++)
2258         {
2259                 color = color_table[i][0];
2260                 red = (color & 0xFF0000) >> 16;
2261                 green = (color & 0x00FF00) >> 8;
2262                 blue = color & 0xFF;
2263
2264                 col.flags = DoRed | DoGreen | DoBlue;
2265                 col.red   = red<<8   | red;
2266                 col.green = green<<8 | green;
2267                 col.blue  = blue<<8  | blue;
2268
2269                 XAllocColor(display, cmap, &col);
2270                 color_table[i][1] = col.pixel;
2271         }
2272
2273         XInstallColormap(display, cmap);
2274         return 0;
2275 }
2276
2277 int BC_WindowBase::init_window_shape()
2278 {
2279         if(bg_pixmap && bg_pixmap->use_alpha())
2280         {
2281                 XShapeCombineMask(top_level->display,
2282                         this->win, ShapeBounding, 0, 0,
2283                         bg_pixmap->get_alpha(), ShapeSet);
2284         }
2285         return 0;
2286 }
2287
2288
2289 int BC_WindowBase::init_gc()
2290 {
2291         unsigned long gcmask;
2292         gcmask = GCFont | GCGraphicsExposures;
2293
2294         XGCValues gcvalues;
2295         gcvalues.font = mediumfont->fid;        // set the font
2296         gcvalues.graphics_exposures = 0;        // prevent expose events for every redraw
2297         gc = XCreateGC(display, rootwin, gcmask, &gcvalues);
2298
2299 // gcmask = GCCapStyle | GCJoinStyle;
2300 // XGetGCValues(display, gc, gcmask, &gcvalues);
2301 // printf("BC_WindowBase::init_gc %d %d %d\n", __LINE__, gcvalues.cap_style, gcvalues.join_style);
2302         return 0;
2303 }
2304
2305 int BC_WindowBase::init_fonts()
2306 {
2307         if( !(smallfont = XLoadQueryFont(display, _(resources.small_font))) )
2308                 if( !(smallfont = XLoadQueryFont(display, _(resources.small_font2))) )
2309                         smallfont = XLoadQueryFont(display, "fixed");
2310         if( !(mediumfont = XLoadQueryFont(display, _(resources.medium_font))) )
2311                 if( !(mediumfont = XLoadQueryFont(display, _(resources.medium_font2))) )
2312                         mediumfont = XLoadQueryFont(display, "fixed");
2313         if( !(largefont = XLoadQueryFont(display, _(resources.large_font))) )
2314                 if( !(largefont = XLoadQueryFont(display, _(resources.large_font2))) )
2315                         largefont = XLoadQueryFont(display, "fixed");
2316         if( !(bigfont = XLoadQueryFont(display, _(resources.big_font))) )
2317                 if( !(bigfont = XLoadQueryFont(display, _(resources.big_font2))) )
2318                         bigfont = XLoadQueryFont(display, "fixed");
2319
2320         if((clockfont = XLoadQueryFont(display, _(resources.clock_font))) == NULL)
2321                 if((clockfont = XLoadQueryFont(display, _(resources.clock_font2))) == NULL)
2322                         clockfont = XLoadQueryFont(display, "fixed");
2323
2324         init_xft();
2325         if(get_resources()->use_fontset)
2326         {
2327                 char **m, *d;
2328                 int n;
2329
2330 // FIXME: should check the m,d,n values
2331                 smallfontset = XCreateFontSet(display, resources.small_fontset, &m, &n, &d);
2332                 if( !smallfontset )
2333                         smallfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2334                 mediumfontset = XCreateFontSet(display, resources.medium_fontset, &m, &n, &d);
2335                 if( !mediumfontset )
2336                         mediumfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2337                 largefontset = XCreateFontSet(display, resources.large_fontset, &m, &n, &d);
2338                 if( !largefontset )
2339                         largefontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2340                 bigfontset = XCreateFontSet(display, resources.big_fontset, &m, &n, &d);
2341                 if( !bigfontset )
2342                         bigfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2343                 clockfontset = XCreateFontSet(display, resources.clock_fontset, &m, &n, &d);
2344                 if( !clockfontset )
2345                         clockfontset = XCreateFontSet(display, "fixed,*", &m, &n, &d);
2346                 if(clockfontset && bigfontset && largefontset && mediumfontset && smallfontset) {
2347                         curr_fontset = mediumfontset;
2348                         get_resources()->use_fontset = 1;
2349                 }
2350                 else {
2351                         curr_fontset = 0;
2352                         get_resources()->use_fontset = 0;
2353                 }
2354         }
2355
2356         return 0;
2357 }
2358
2359 void BC_WindowBase::init_xft()
2360 {
2361 #ifdef HAVE_XFT
2362         if( !get_resources()->use_xft ) return;
2363 // apparently, xft is not reentrant, more than this is needed
2364 static Mutex xft_init_lock("BC_WindowBase::xft_init_lock", 0);
2365 xft_init_lock.lock("BC_WindowBase::init_xft");
2366         if(!(smallfont_xft =
2367                 (resources.small_font_xft[0] == '-' ?
2368                         xftFontOpenXlfd(display, screen, resources.small_font_xft) :
2369                         xftFontOpenName(display, screen, resources.small_font_xft))) )
2370                 if(!(smallfont_xft =
2371                         xftFontOpenXlfd(display, screen, resources.small_font_xft2)))
2372                         smallfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2373         if(!(mediumfont_xft =
2374                 (resources.medium_font_xft[0] == '-' ?
2375                         xftFontOpenXlfd(display, screen, resources.medium_font_xft) :
2376                         xftFontOpenName(display, screen, resources.medium_font_xft))) )
2377                 if(!(mediumfont_xft =
2378                         xftFontOpenXlfd(display, screen, resources.medium_font_xft2)))
2379                         mediumfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2380         if(!(largefont_xft =
2381                 (resources.large_font_xft[0] == '-' ?
2382                         xftFontOpenXlfd(display, screen, resources.large_font_xft) :
2383                         xftFontOpenName(display, screen, resources.large_font_xft))) )
2384                 if(!(largefont_xft =
2385                         xftFontOpenXlfd(display, screen, resources.large_font_xft2)))
2386                         largefont_xft = xftFontOpenXlfd(display, screen, "fixed");
2387         if(!(bigfont_xft =
2388                 (resources.big_font_xft[0] == '-' ?
2389                         xftFontOpenXlfd(display, screen, resources.big_font_xft) :
2390                         xftFontOpenName(display, screen, resources.big_font_xft))) )
2391                 if(!(bigfont_xft =
2392                         xftFontOpenXlfd(display, screen, resources.big_font_xft2)))
2393                         bigfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2394         if(!(clockfont_xft =
2395                 (resources.clock_font_xft[0] == '-' ?
2396                         xftFontOpenXlfd(display, screen, resources.clock_font_xft) :
2397                         xftFontOpenName(display, screen, resources.clock_font_xft))) )
2398                 clockfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2399
2400
2401         if(!(bold_smallfont_xft =
2402                 (resources.small_b_font_xft[0] == '-' ?
2403                         xftFontOpenXlfd(display, screen, resources.small_b_font_xft) :
2404                         xftFontOpenName(display, screen, resources.small_b_font_xft))) )
2405                 bold_smallfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2406         if(!(bold_mediumfont_xft =
2407                 (resources.medium_b_font_xft[0] == '-' ?
2408                         xftFontOpenXlfd(display, screen, resources.medium_b_font_xft) :
2409                         xftFontOpenName(display, screen, resources.medium_b_font_xft))) )
2410                 bold_mediumfont_xft = xftFontOpenXlfd(display, screen, "fixed");
2411         if(!(bold_largefont_xft =
2412                 (resources.large_b_font_xft[0] == '-' ?
2413                         xftFontOpenXlfd(display, screen, resources.large_b_font_xft) :
2414                         xftFontOpenName(display, screen, resources.large_b_font_xft))) )
2415                 bold_largefont_xft = xftFontOpenXlfd(display, screen, "fixed");
2416
2417         if( !smallfont_xft || !mediumfont_xft || !largefont_xft || !bigfont_xft ||
2418             !bold_largefont_xft || !bold_mediumfont_xft || !bold_largefont_xft ||
2419             !clockfont_xft ) {
2420                 printf("BC_WindowBase::init_fonts: no xft fonts found:"
2421                         " %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n %s=%p\n",
2422                         resources.small_font_xft, smallfont_xft,
2423                         resources.medium_font_xft, mediumfont_xft,
2424                         resources.large_font_xft, largefont_xft,
2425                         resources.big_font_xft, bigfont_xft,
2426                         resources.clock_font_xft, clockfont_xft,
2427                         resources.small_b_font_xft, bold_smallfont_xft,
2428                         resources.medium_b_font_xft, bold_mediumfont_xft,
2429                         resources.large_b_font_xft, bold_largefont_xft);
2430                 get_resources()->use_xft = 0;
2431                 exit(1);
2432         }
2433 // _XftDisplayInfo needs a lock.
2434         xftDefaultHasRender(display);
2435 xft_init_lock.unlock();
2436 #endif // HAVE_XFT
2437 }
2438
2439 void BC_WindowBase::init_im()
2440 {
2441         XIMStyles *xim_styles;
2442         XIMStyle xim_style;
2443
2444         if(!(input_method = XOpenIM(display, NULL, NULL, NULL)))
2445         {
2446                 printf("BC_WindowBase::init_im: Could not open input method.\n");
2447                 exit(1);
2448         }
2449         if(XGetIMValues(input_method, XNQueryInputStyle, &xim_styles, NULL) ||
2450                         xim_styles == NULL)
2451         {
2452                 printf("BC_WindowBase::init_im: Input method doesn't support any styles.\n");
2453                 XCloseIM(input_method);
2454                 exit(1);
2455         }
2456
2457         xim_style = 0;
2458         for(int z = 0;  z < xim_styles->count_styles;  z++)
2459         {
2460                 if(xim_styles->supported_styles[z] == (XIMPreeditNothing | XIMStatusNothing))
2461                 {
2462                         xim_style = xim_styles->supported_styles[z];
2463                         break;
2464                 }
2465         }
2466         XFree(xim_styles);
2467
2468         if(xim_style == 0)
2469         {
2470                 printf("BC_WindowBase::init_im: Input method doesn't support the style we need.\n");
2471                 XCloseIM(input_method);
2472                 exit(1);
2473         }
2474
2475         input_context = XCreateIC(input_method, XNInputStyle, xim_style,
2476                 XNClientWindow, win, XNFocusWindow, win, NULL);
2477         if(!input_context)
2478         {
2479                 printf("BC_WindowBase::init_im: Failed to create input context.\n");
2480                 XCloseIM(input_method);
2481                 exit(1);
2482         }
2483 }
2484
2485 void BC_WindowBase::finit_im()
2486 {
2487         if( input_context ) {
2488                 XDestroyIC(input_context);
2489                 input_context = 0;
2490         }
2491         if( input_method ) {
2492                 XCloseIM(input_method);
2493                 input_method = 0;
2494         }
2495 }
2496
2497
2498 int BC_WindowBase::get_color(int64_t color)
2499 {
2500 // return pixel of color
2501 // use this only for drawing subwindows not for bitmaps
2502          int i, test, difference;
2503
2504         switch(color_model)
2505         {
2506         case BC_RGB8:
2507                 if(private_color)
2508                         return get_color_rgb8(color);
2509 // test last color looked up
2510                 if(current_color_value == color)
2511                         return current_color_pixel;
2512
2513 // look up in table
2514                 current_color_value = color;
2515                 for(i = 0; i < total_colors; i++)
2516                 {
2517                         if(color_table[i][0] == color)
2518                         {
2519                                 current_color_pixel = color_table[i][1];
2520                                 return current_color_pixel;
2521                         }
2522                 }
2523
2524 // find nearest match
2525                 difference = 0xFFFFFF;
2526
2527                 for(i = 0; i < total_colors; i++)
2528                 {
2529                         test = abs((int)(color_table[i][0] - color));
2530
2531                         if(test < difference)
2532                         {
2533                                 current_color_pixel = color_table[i][1];
2534                                 difference = test;
2535                         }
2536                 }
2537                 return current_color_pixel;
2538
2539         case BC_RGB565:
2540                 return get_color_rgb16(color);
2541
2542         case BC_BGR565:
2543                 return get_color_bgr16(color);
2544
2545         case BC_RGB888:
2546         case BC_BGR888:
2547                 return client_byte_order == server_byte_order ?
2548                         color : get_color_bgr24(color);
2549
2550         default:
2551                 return color;
2552         }
2553         return 0;
2554 }
2555
2556 int BC_WindowBase::get_color_rgb8(int color)
2557 {
2558         int pixel;
2559
2560         pixel = (color & 0xc00000) >> 16;
2561         pixel += (color & 0xe000) >> 10;
2562         pixel += (color & 0xe0) >> 5;
2563         return pixel;
2564 }
2565
2566 int64_t BC_WindowBase::get_color_rgb16(int color)
2567 {
2568         int64_t result;
2569         result = (color & 0xf80000) >> 8;
2570         result += (color & 0xfc00) >> 5;
2571         result += (color & 0xf8) >> 3;
2572
2573         return result;
2574 }
2575
2576 int64_t BC_WindowBase::get_color_bgr16(int color)
2577 {
2578         int64_t result;
2579         result = (color & 0xf80000) >> 19;
2580         result += (color & 0xfc00) >> 5;
2581         result += (color & 0xf8) << 8;
2582
2583         return result;
2584 }
2585
2586 int64_t BC_WindowBase::get_color_bgr24(int color)
2587 {
2588         int64_t result;
2589         result = (color & 0xff) << 16;
2590         result += (color & 0xff00);
2591         result += (color & 0xff0000) >> 16;
2592         return result;
2593 }
2594
2595 void BC_WindowBase::start_video()
2596 {
2597         cursor_timer->update();
2598         video_on = 1;
2599 //      set_color(BLACK);
2600 //      draw_box(0, 0, get_w(), get_h());
2601 //      flash();
2602 }
2603
2604 void BC_WindowBase::stop_video()
2605 {
2606         video_on = 0;
2607         unhide_cursor();
2608 }
2609
2610
2611
2612 int64_t BC_WindowBase::get_color()
2613 {
2614         return top_level->current_color;
2615 }
2616
2617 void BC_WindowBase::set_color(int64_t color)
2618 {
2619         top_level->current_color = color;
2620         XSetForeground(top_level->display,
2621                 top_level->gc,
2622                 top_level->get_color(color));
2623 }
2624
2625 void BC_WindowBase::set_opaque()
2626 {
2627         XSetFunction(top_level->display, top_level->gc, GXcopy);
2628 }
2629
2630 void BC_WindowBase::set_inverse()
2631 {
2632         XSetFunction(top_level->display, top_level->gc, GXxor);
2633 }
2634
2635 void BC_WindowBase::set_line_width(int value)
2636 {
2637         this->line_width = value;
2638         XSetLineAttributes(top_level->display, top_level->gc, value,    /* line_width */
2639                 line_dashes == 0 ? LineSolid : LineOnOffDash,           /* line_style */
2640                 line_dashes == 0 ? CapRound : CapNotLast,               /* cap_style */
2641                 JoinMiter);                                             /* join_style */
2642
2643         if(line_dashes > 0) {
2644                 const char dashes = line_dashes;
2645                 XSetDashes(top_level->display, top_level->gc, 0, &dashes, 1);
2646         }
2647
2648 // XGCValues gcvalues;
2649 // unsigned long gcmask;
2650 // gcmask = GCCapStyle | GCJoinStyle;
2651 // XGetGCValues(top_level->display, top_level->gc, gcmask, &gcvalues);
2652 // printf("BC_WindowBase::set_line_width %d %d %d\n", __LINE__, gcvalues.cap_style, gcvalues.join_style);
2653 }
2654
2655 void BC_WindowBase::set_line_dashes(int value)
2656 {
2657         line_dashes = value;
2658 // call XSetLineAttributes
2659         set_line_width(line_width);
2660 }
2661
2662
2663 Cursor BC_WindowBase::get_cursor_struct(int cursor)
2664 {
2665         switch(cursor)
2666         {
2667                 case ARROW_CURSOR:         return top_level->arrow_cursor;
2668                 case CROSS_CURSOR:         return top_level->cross_cursor;
2669                 case IBEAM_CURSOR:         return top_level->ibeam_cursor;
2670                 case VSEPARATE_CURSOR:     return top_level->vseparate_cursor;
2671                 case HSEPARATE_CURSOR:     return top_level->hseparate_cursor;
2672                 case MOVE_CURSOR:          return top_level->move_cursor;
2673                 case LEFT_CURSOR:          return top_level->left_cursor;
2674                 case RIGHT_CURSOR:         return top_level->right_cursor;
2675                 case UPRIGHT_ARROW_CURSOR: return top_level->upright_arrow_cursor;
2676                 case UPLEFT_RESIZE:        return top_level->upleft_resize_cursor;
2677                 case UPRIGHT_RESIZE:       return top_level->upright_resize_cursor;
2678                 case DOWNLEFT_RESIZE:      return top_level->downleft_resize_cursor;
2679                 case DOWNRIGHT_RESIZE:     return top_level->downright_resize_cursor;
2680                 case HOURGLASS_CURSOR:     return top_level->hourglass_cursor;
2681                 case TRANSPARENT_CURSOR:   return top_level->transparent_cursor;
2682                 case GRABBED_CURSOR:       return top_level->grabbed_cursor;
2683         }
2684         return 0;
2685 }
2686
2687 void BC_WindowBase::set_cursor(int cursor, int override, int flush)
2688 {
2689 // inherit cursor from parent
2690         if(cursor < 0)
2691         {
2692                 XUndefineCursor(top_level->display, win);
2693                 current_cursor = cursor;
2694         }
2695         else
2696 // don't change cursor if overridden
2697         if((!top_level->is_hourglass && !is_transparent) ||
2698                 override)
2699         {
2700                 XDefineCursor(top_level->display, win, get_cursor_struct(cursor));
2701                 if(flush) this->flush();
2702         }
2703
2704         if(!override) current_cursor = cursor;
2705 }
2706
2707 void BC_WindowBase::set_x_cursor(int cursor)
2708 {
2709         temp_cursor = XCreateFontCursor(top_level->display, cursor);
2710         XDefineCursor(top_level->display, win, temp_cursor);
2711         current_cursor = cursor;
2712         flush();
2713 }
2714
2715 int BC_WindowBase::get_cursor()
2716 {
2717         return current_cursor;
2718 }
2719
2720 void BC_WindowBase::start_hourglass()
2721 {
2722         top_level->start_hourglass_recursive();
2723         top_level->flush();
2724 }
2725
2726 void BC_WindowBase::stop_hourglass()
2727 {
2728         top_level->stop_hourglass_recursive();
2729         top_level->flush();
2730 }
2731
2732 void BC_WindowBase::start_hourglass_recursive()
2733 {
2734         if(this == top_level)
2735         {
2736                 hourglass_total++;
2737                 is_hourglass = 1;
2738         }
2739
2740         if(!is_transparent)
2741         {
2742                 set_cursor(HOURGLASS_CURSOR, 1, 0);
2743                 for(int i = 0; i < subwindows->total; i++)
2744                 {
2745                         subwindows->values[i]->start_hourglass_recursive();
2746                 }
2747         }
2748 }
2749
2750 void BC_WindowBase::stop_hourglass_recursive()
2751 {
2752         if(this == top_level)
2753         {
2754                 if(hourglass_total == 0) return;
2755                 top_level->hourglass_total--;
2756         }
2757
2758         if(!top_level->hourglass_total)
2759         {
2760                 top_level->is_hourglass = 0;
2761
2762 // Cause set_cursor to perform change
2763                 if(!is_transparent)
2764                         set_cursor(current_cursor, 1, 0);
2765
2766                 for(int i = 0; i < subwindows->total; i++)
2767                 {
2768                         subwindows->values[i]->stop_hourglass_recursive();
2769                 }
2770         }
2771 }
2772
2773
2774
2775
2776 XFontStruct* BC_WindowBase::get_font_struct(int font)
2777 {
2778 // Clear out unrelated flags
2779         if(font & BOLDFACE) font ^= BOLDFACE;
2780
2781         switch(font) {
2782                 case SMALLFONT:  return top_level->smallfont;  break;
2783                 case MEDIUMFONT: return top_level->mediumfont; break;
2784                 case LARGEFONT:  return top_level->largefont;  break;
2785                 case BIGFONT:    return top_level->bigfont;    break;
2786                 case CLOCKFONT:  return top_level->clockfont;  break;
2787         }
2788         return 0;
2789 }
2790
2791 XFontSet BC_WindowBase::get_fontset(int font)
2792 {
2793         XFontSet fs = 0;
2794
2795         if(get_resources()->use_fontset)
2796         {
2797                 switch(font & 0xff) {
2798                         case SMALLFONT:  fs = top_level->smallfontset; break;
2799                         case MEDIUMFONT: fs = top_level->mediumfontset; break;
2800                         case LARGEFONT:  fs = top_level->largefontset; break;
2801                         case BIGFONT:    fs = top_level->bigfontset;   break;
2802                         case CLOCKFONT: fs = top_level->clockfontset; break;
2803                 }
2804         }
2805
2806         return fs;
2807 }
2808
2809 #ifdef HAVE_XFT
2810 XftFont* BC_WindowBase::get_xft_struct(int font)
2811 {
2812         switch(font) {
2813                 case SMALLFONT:    return (XftFont*)top_level->smallfont_xft;
2814                 case MEDIUMFONT:   return (XftFont*)top_level->mediumfont_xft;
2815                 case LARGEFONT:    return (XftFont*)top_level->largefont_xft;
2816                 case BIGFONT:      return (XftFont*)top_level->bigfont_xft;
2817                 case CLOCKFONT:    return (XftFont*)top_level->clockfont_xft;
2818                 case MEDIUMFONT_3D: return (XftFont*)top_level->bold_mediumfont_xft;
2819                 case SMALLFONT_3D:  return (XftFont*)top_level->bold_smallfont_xft;
2820                 case LARGEFONT_3D:  return (XftFont*)top_level->bold_largefont_xft;
2821         }
2822
2823         return 0;
2824 }
2825 #endif
2826
2827
2828 int BC_WindowBase::get_current_font()
2829 {
2830         return top_level->current_font;
2831 }
2832
2833 void BC_WindowBase::set_font(int font)
2834 {
2835         top_level->current_font = font;
2836
2837 #ifdef HAVE_XFT
2838         if(get_resources()->use_xft) {}
2839         else
2840 #endif
2841         if(get_resources()->use_fontset) {
2842                 set_fontset(font);
2843         }
2844
2845         if(get_font_struct(font))
2846         {
2847                 XSetFont(top_level->display, top_level->gc, get_font_struct(font)->fid);
2848         }
2849
2850         return;
2851 }
2852
2853 void BC_WindowBase::set_fontset(int font)
2854 {
2855         XFontSet fs = 0;
2856
2857         if(get_resources()->use_fontset) {
2858                 switch(font) {
2859                         case SMALLFONT:  fs = top_level->smallfontset; break;
2860                         case MEDIUMFONT: fs = top_level->mediumfontset; break;
2861                         case LARGEFONT:  fs = top_level->largefontset; break;
2862                         case BIGFONT:    fs = top_level->bigfontset;   break;
2863                         case CLOCKFONT:  fs = top_level->clockfontset; break;
2864                 }
2865         }
2866
2867         curr_fontset = fs;
2868 }
2869
2870
2871 XFontSet BC_WindowBase::get_curr_fontset(void)
2872 {
2873         if(get_resources()->use_fontset)
2874                 return curr_fontset;
2875         return 0;
2876 }
2877
2878 int BC_WindowBase::get_single_text_width(int font, const char *text, int length)
2879 {
2880 #ifdef HAVE_XFT
2881         if(get_resources()->use_xft && get_xft_struct(font))
2882         {
2883                 XGlyphInfo extents;
2884 #ifdef X_HAVE_UTF8_STRING
2885                 if(get_resources()->locale_utf8)
2886                 {
2887                         xftTextExtentsUtf8(top_level->display,
2888                                 get_xft_struct(font),
2889                                 (const XftChar8 *)text,
2890                                 length,
2891                                 &extents);
2892                 }
2893                 else
2894 #endif
2895                 {
2896                         xftTextExtents8(top_level->display,
2897                                 get_xft_struct(font),
2898                                 (const XftChar8 *)text,
2899                                 length,
2900                                 &extents);
2901                 }
2902                 return extents.xOff;
2903         }
2904         else
2905 #endif
2906         if(get_resources()->use_fontset && top_level->get_fontset(font))
2907                 return XmbTextEscapement(top_level->get_fontset(font), text, length);
2908         else
2909         if(get_font_struct(font))
2910                 return XTextWidth(get_font_struct(font), text, length);
2911         else
2912         {
2913                 int w = 0;
2914                 switch(font)
2915                 {
2916                         case MEDIUM_7SEGMENT:
2917                                 return get_resources()->medium_7segment[0]->get_w() * length;
2918                                 break;
2919
2920                         default:
2921                                 return 0;
2922                 }
2923                 return w;
2924         }
2925 }
2926
2927 int BC_WindowBase::get_text_width(int font, const char *text, int length)
2928 {
2929         int i, j, w = 0, line_w = 0;
2930         if(length < 0) length = strlen(text);
2931
2932         for(i = 0, j = 0; i <= length; i++)
2933         {
2934                 line_w = 0;
2935                 if(text[i] == '\n')
2936                 {
2937                         line_w = get_single_text_width(font, &text[j], i - j);
2938                         j = i + 1;
2939                 }
2940                 else
2941                 if(text[i] == 0)
2942                 {
2943                         line_w = get_single_text_width(font, &text[j], length - j);
2944                 }
2945                 if(line_w > w) w = line_w;
2946         }
2947
2948         if(i > length && w == 0)
2949         {
2950                 w = get_single_text_width(font, text, length);
2951         }
2952
2953         return w;
2954 }
2955
2956 int BC_WindowBase::get_text_width(int font, const wchar_t *text, int length)
2957 {
2958         int i, j, w = 0;
2959         if( length < 0 ) length = wcslen(text);
2960
2961         for( i=j=0; i<length && text[i]; ++i ) {
2962                 if( text[i] != '\n' ) continue;
2963                 if( i > j ) {
2964                         int lw = get_single_text_width(font, &text[j], i-j);
2965                         if( w < lw ) w = lw;
2966                 }
2967                 j = i + 1;
2968         }
2969         if( j < length ) {
2970                 int lw = get_single_text_width(font, &text[j], length-j);
2971                 if( w < lw ) w = lw;
2972         }
2973
2974         return w;
2975 }
2976
2977 int BC_WindowBase::get_text_ascent(int font)
2978 {
2979 #ifdef HAVE_XFT
2980         XftFont *fstruct;
2981         if( (fstruct = get_xft_struct(font)) != 0 )
2982                 return fstruct->ascent;
2983 #endif
2984         if(get_resources()->use_fontset && top_level->get_fontset(font))
2985         {
2986                 XFontSetExtents *extents;
2987
2988                 extents = XExtentsOfFontSet(top_level->get_fontset(font));
2989                 return -extents->max_logical_extent.y;
2990         }
2991
2992         if(get_font_struct(font))
2993                 return top_level->get_font_struct(font)->ascent;
2994
2995         switch(font) {
2996                 case MEDIUM_7SEGMENT:
2997                         return get_resources()->medium_7segment[0]->get_h();
2998         }
2999         return 0;
3000 }
3001
3002 int BC_WindowBase::get_text_descent(int font)
3003 {
3004 #ifdef HAVE_XFT
3005         XftFont *fstruct;
3006         if( (fstruct = get_xft_struct(font)) != 0 )
3007                 return fstruct->descent;
3008 #endif
3009         if(get_resources()->use_fontset && top_level->get_fontset(font)) {
3010                 XFontSetExtents *extents;
3011                 extents = XExtentsOfFontSet(top_level->get_fontset(font));
3012                 return (extents->max_logical_extent.height
3013                         + extents->max_logical_extent.y);
3014         }
3015
3016         if(get_font_struct(font))
3017                 return top_level->get_font_struct(font)->descent;
3018
3019         return 0;
3020 }
3021
3022 int BC_WindowBase::get_text_height(int font, const char *text)
3023 {
3024         int rowh;
3025 #ifdef HAVE_XFT
3026         XftFont *fstruct;
3027         if( (fstruct = get_xft_struct(font)) != 0 )
3028                 rowh = fstruct->height;
3029         else
3030 #endif
3031                 rowh = get_text_ascent(font) + get_text_descent(font);
3032
3033         if(!text) return rowh;
3034
3035 // Add height of lines
3036         int h = 0, i, length = strlen(text);
3037         for(i = 0; i <= length; i++)
3038         {
3039                 if(text[i] == '\n')
3040                         h++;
3041                 else
3042                 if(text[i] == 0)
3043                         h++;
3044         }
3045         return h * rowh;
3046 }
3047
3048 BC_Bitmap* BC_WindowBase::new_bitmap(int w, int h, int color_model)
3049 {
3050         if(color_model < 0) color_model = top_level->get_color_model();
3051         return new BC_Bitmap(top_level, w, h, color_model);
3052 }
3053
3054 void BC_WindowBase::init_wait()
3055 {
3056 #ifndef SINGLE_THREAD
3057         if(window_type != MAIN_WINDOW)
3058                 top_level->init_wait();
3059         init_lock->lock("BC_WindowBase::init_wait");
3060         init_lock->unlock();
3061 #endif
3062 }
3063
3064 int BC_WindowBase::accel_available(int color_model, int lock_it)
3065 {
3066         if( window_type != MAIN_WINDOW )
3067                 return top_level->accel_available(color_model, lock_it);
3068         if( lock_it )
3069                 lock_window("BC_WindowBase::accel_available");
3070
3071         switch(color_model) {
3072         case BC_YUV420P:
3073                 grab_port_id(color_model);
3074                 break;
3075
3076         case BC_YUV422:
3077                 grab_port_id(color_model);
3078                 break;
3079
3080         default:
3081                 break;
3082         }
3083
3084         if( lock_it )
3085                 unlock_window();
3086 //printf("BC_WindowBase::accel_available %d %d\n", color_model, xvideo_port_id);
3087         return xvideo_port_id >= 0 ? 1 : 0;
3088 }
3089
3090
3091 int BC_WindowBase::grab_port_id(int color_model)
3092 {
3093         if( !get_resources()->use_xvideo ||     // disabled
3094             !get_resources()->use_shm )         // Only local server is fast enough.
3095                 return -1;
3096         if( xvideo_port_id >= 0 )
3097                 return xvideo_port_id;
3098
3099         unsigned int ver, rev, reqBase, eventBase, errorBase;
3100         if( Success != XvQueryExtension(display, // XV extension is available
3101                     &ver, &rev, &reqBase, &eventBase, &errorBase) )
3102                 return -1;
3103
3104 // XV adaptors are available
3105         unsigned int numAdapt = 0;
3106         XvAdaptorInfo *info = 0;
3107         XvQueryAdaptors(display, DefaultRootWindow(display), &numAdapt, &info);
3108         if( !numAdapt )
3109                 return -1;
3110
3111 // Translate from color_model to X color model
3112         int x_color_model = BC_CModels::bc_to_x(color_model);
3113
3114 // Get adaptor with desired color model
3115         for( int i = 0; i < (int)numAdapt && xvideo_port_id == -1; i++) {
3116                 if( !(info[i].type & XvImageMask) || !info[i].num_ports ) continue;
3117 // adaptor supports XvImages
3118                 int numFormats = 0, numPorts = info[i].num_ports;
3119                 XvImageFormatValues *formats =
3120                         XvListImageFormats(display, info[i].base_id, &numFormats);
3121                 if( !formats ) continue;
3122
3123                 for( int j=0; j<numFormats && xvideo_port_id<0; ++j ) {
3124                         if( formats[j].id != x_color_model ) continue;
3125 // this adaptor supports the desired format, grab a port
3126                         for( int k=0; k<numPorts; ++k ) {
3127                                 if( Success == XvGrabPort(top_level->display,
3128                                         info[i].base_id+k, CurrentTime) ) {
3129 //printf("BC_WindowBase::grab_port_id %llx\n", info[i].base_id);
3130                                         xvideo_port_id = info[i].base_id + k;
3131                                         break;
3132                                 }
3133                         }
3134                 }
3135                 XFree(formats);
3136         }
3137
3138         XvFreeAdaptorInfo(info);
3139
3140         return xvideo_port_id;
3141 }
3142
3143
3144 int BC_WindowBase::show_window(int flush)
3145 {
3146         for(int i = 0; i < subwindows->size(); i++)
3147         {
3148                 subwindows->get(i)->show_window(0);
3149         }
3150
3151         XMapWindow(top_level->display, win);
3152         if(flush) XFlush(top_level->display);
3153 //      XSync(top_level->display, 0);
3154         hidden = 0;
3155         return 0;
3156 }
3157
3158 int BC_WindowBase::hide_window(int flush)
3159 {
3160         for(int i = 0; i < subwindows->size(); i++)
3161         {
3162                 subwindows->get(i)->hide_window(0);
3163         }
3164
3165         XUnmapWindow(top_level->display, win);
3166         if(flush) this->flush();
3167         hidden = 1;
3168         return 0;
3169 }
3170
3171 BC_MenuBar* BC_WindowBase::add_menubar(BC_MenuBar *menu_bar)
3172 {
3173         subwindows->append((BC_SubWindow*)menu_bar);
3174
3175         menu_bar->parent_window = this;
3176         menu_bar->top_level = this->top_level;
3177         menu_bar->initialize();
3178         return menu_bar;
3179 }
3180
3181 BC_WindowBase* BC_WindowBase::add_popup(BC_WindowBase *window)
3182 {
3183 //printf("BC_WindowBase::add_popup window=%p win=%p\n", window, window->win);
3184         if(this != top_level) return top_level->add_popup(window);
3185         popups.append(window);
3186         return window;
3187 }
3188
3189 void BC_WindowBase::remove_popup(BC_WindowBase *window)
3190 {
3191 //printf("BC_WindowBase::remove_popup %d size=%d window=%p win=%p\n", __LINE__, popups.size(), window, window->win);
3192         if(this != top_level)
3193                 top_level->remove_popup(window);
3194         else
3195                 popups.remove(window);
3196 //printf("BC_WindowBase::remove_popup %d size=%d window=%p win=%p\n", __LINE__, popups.size(), window, window->win);
3197 }
3198
3199
3200 BC_WindowBase* BC_WindowBase::add_subwindow(BC_WindowBase *subwindow)
3201 {
3202         subwindows->append(subwindow);
3203
3204         if(subwindow->bg_color == -1) subwindow->bg_color = this->bg_color;
3205
3206 // parent window must be set before the subwindow initialization
3207         subwindow->parent_window = this;
3208         subwindow->top_level = this->top_level;
3209
3210 // Execute derived initialization
3211         subwindow->initialize();
3212         return subwindow;
3213 }
3214
3215
3216 BC_WindowBase* BC_WindowBase::add_tool(BC_WindowBase *subwindow)
3217 {
3218         return add_subwindow(subwindow);
3219 }
3220
3221 int BC_WindowBase::flash(int x, int y, int w, int h, int flush)
3222 {
3223         if( !top_level->flash_enabled ) return 0;
3224 //printf("BC_WindowBase::flash %d %d %d %d %d\n", __LINE__, w, h, this->w, this->h);
3225         set_opaque();
3226         XSetWindowBackgroundPixmap(top_level->display, win, pixmap->opaque_pixmap);
3227         if(x >= 0)
3228         {
3229                 XClearArea(top_level->display, win, x, y, w, h, 0);
3230         }
3231         else
3232         {
3233                 XClearWindow(top_level->display, win);
3234         }
3235
3236         if(flush)
3237                 this->flush();
3238         return 0;
3239 }
3240
3241 int BC_WindowBase::flash(int flush)
3242 {
3243         flash(-1, -1, -1, -1, flush);
3244         return 0;
3245 }
3246
3247 void BC_WindowBase::flush()
3248 {
3249         //if(!get_window_lock())
3250         //      printf("BC_WindowBase::flush %s not locked\n", top_level->title);
3251         // X gets hosed if Flush/Sync are not user locked (at libX11-1.1.5 / libxcb-1.1.91)
3252         //   _XReply deadlocks in condition_wait waiting for xlib lock when waiters!=-1
3253         int locked  = get_window_lock();
3254         if( !locked ) lock_window("BC_WindowBase::flush");
3255         XFlush(top_level->display);
3256         if( !locked ) unlock_window();
3257 }
3258
3259 void BC_WindowBase::sync_display()
3260 {
3261         int locked  = get_window_lock();
3262         if( !locked ) lock_window("BC_WindowBase::sync_display");
3263         XSync(top_level->display, False);
3264         if( !locked ) unlock_window();
3265 }
3266
3267 int BC_WindowBase::get_window_lock()
3268 {
3269 #ifdef SINGLE_THREAD
3270         return BC_Display::display_global->get_display_locked();
3271 #else
3272         return top_level->window_lock;
3273 #endif
3274 }
3275
3276 int BC_WindowBase::lock_window(const char *location)
3277 {
3278         if(top_level && top_level != this)
3279         {
3280                 top_level->lock_window(location);
3281         }
3282         else
3283         if(top_level)
3284         {
3285                 SET_LOCK(this, title, location);
3286 #ifdef SINGLE_THREAD
3287                 BC_Display::lock_display(location);
3288 #else
3289                 XLockDisplay(top_level->display);
3290                 top_level->display_lock_owner = pthread_self();
3291 #endif
3292                 SET_LOCK2
3293                 ++top_level->window_lock;
3294         }
3295         else
3296         {
3297                 printf("BC_WindowBase::lock_window top_level NULL\n");
3298         }
3299         return 0;
3300 }
3301
3302 int BC_WindowBase::unlock_window()
3303 {
3304         if(top_level && top_level != this)
3305         {
3306                 top_level->unlock_window();
3307         }
3308         else
3309         if(top_level)
3310         {
3311                 UNSET_LOCK(this);
3312
3313 //              if(!top_level->window_lock)
3314 //              {
3315 //                      printf("BC_WindowBase::unlock_window %d %s already unlocked\n",
3316 //                              __LINE__,
3317 //                              title);
3318 //              }
3319                 if( top_level->window_lock > 0 )
3320                         if( --top_level->window_lock == 0 )
3321                                 top_level->display_lock_owner = 0;
3322 #ifdef SINGLE_THREAD
3323                 BC_Display::unlock_display();
3324 #else
3325                 XUnlockDisplay(top_level->display);
3326 #endif
3327         }
3328         else
3329         {
3330                 printf("BC_WindowBase::unlock_window top_level NULL\n");
3331         }
3332         return 0;
3333 }
3334
3335 void BC_WindowBase::set_done(int return_value)
3336 {
3337         if(done_set) return;
3338         done_set = 1;
3339         if(window_type != MAIN_WINDOW)
3340                 top_level->set_done(return_value);
3341         else
3342         {
3343 #ifdef SINGLE_THREAD
3344                 this->return_value = return_value;
3345                 BC_Display::display_global->arm_completion(this);
3346                 completion_lock->unlock();
3347 #else // SINGLE_THREAD
3348                 init_wait();
3349                 if( !event_thread ) return;
3350                 XEvent *event = new_xevent();
3351                 XClientMessageEvent *ptr = (XClientMessageEvent*)event;
3352                 event->type = ClientMessage;
3353                 ptr->message_type = SetDoneXAtom;
3354                 ptr->format = 32;
3355                 this->return_value = return_value;
3356 // May lock up here because XSendEvent doesn't work too well
3357 // asynchronous with XNextEvent.
3358 // This causes BC_WindowEvents to forward a copy of the event to run_window where
3359 // it is deleted.
3360 // Deletion of event_thread is done at the end of BC_WindowBase::run_window() - by calling the destructor
3361                 put_event(event);
3362 #endif
3363         }
3364 }
3365
3366 void BC_WindowBase::close(int return_value)
3367 {
3368         hide_window();  flush();
3369         set_done(return_value);
3370 }
3371
3372 int BC_WindowBase::grab(BC_WindowBase *window)
3373 {
3374         if( window->active_grab && this != window->active_grab ) return 0;
3375         window->active_grab = this;
3376         this->grab_active = window;
3377         return 1;
3378 }
3379 int BC_WindowBase::ungrab(BC_WindowBase *window)
3380 {
3381         if( window->active_grab && this != window->active_grab ) return 0;
3382         window->active_grab = 0;
3383         this->grab_active = 0;
3384         return 1;
3385 }
3386 int BC_WindowBase::grab_event_count()
3387 {
3388         int result = 0;
3389 #ifndef SINGLE_THREAD
3390         result = grab_active->get_event_count();
3391 #endif
3392         return result;
3393 }
3394 int BC_WindowBase::grab_buttons()
3395 {
3396         XSync(top_level->display, False);
3397         if( XGrabButton(top_level->display, AnyButton, AnyModifier,
3398                         top_level->rootwin, True, ButtonPressMask | ButtonReleaseMask,
3399                         GrabModeAsync, GrabModeSync, None, None) == GrabSuccess ) {
3400                 set_active_subwindow(this);
3401                 return 0;
3402         }
3403         return 1;
3404 }
3405 void BC_WindowBase::ungrab_buttons()
3406 {
3407         XUngrabButton(top_level->display, AnyButton, AnyModifier, top_level->rootwin);
3408         set_active_subwindow(0);
3409         unhide_cursor();
3410 }
3411 void BC_WindowBase::grab_cursor()
3412 {
3413         Cursor cursor_grab = get_cursor_struct(GRABBED_CURSOR);
3414         XGrabPointer(top_level->display, top_level->rootwin, True,
3415                 PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
3416                 GrabModeAsync, GrabModeAsync, None, cursor_grab, CurrentTime);
3417 }
3418 void BC_WindowBase::ungrab_cursor()
3419 {
3420        XUngrabPointer(top_level->display, CurrentTime);
3421 }
3422
3423 // for get_root_w/h
3424 //   WidthOfScreen/HeightOfScreen of XDefaultScreenOfDisplay
3425 //   this is the bounding box of all the screens
3426
3427 int BC_WindowBase::get_root_w(int lock_display)
3428 {
3429         if(lock_display) lock_window("BC_WindowBase::get_root_w");
3430         Screen *def_screen = XDefaultScreenOfDisplay(top_level->display);
3431         int result = WidthOfScreen(def_screen);
3432         if(lock_display) unlock_window();
3433         return result;
3434 }
3435
3436 int BC_WindowBase::get_root_h(int lock_display)
3437 {
3438         if(lock_display) lock_window("BC_WindowBase::get_root_h");
3439         Screen *def_screen = XDefaultScreenOfDisplay(top_level->display);
3440         int result = HeightOfScreen(def_screen);
3441         if(lock_display) unlock_window();
3442         return result;
3443 }
3444
3445 XineramaScreenInfo *
3446 BC_WindowBase::get_xinerama_info(int screen)
3447 {
3448         if( !xinerama_info || !xinerama_screens ) return 0;
3449         if( screen >= 0 ) {
3450                 for( int i=0; i<xinerama_screens; ++i )
3451                         if( xinerama_info[i].screen_number == screen )
3452                                 return &xinerama_info[i];
3453                 return 0;
3454         }
3455         int top_x = get_x(), top_y = get_y();
3456         if(  BC_DisplayInfo::left_border >= 0 ) top_x +=  BC_DisplayInfo::left_border;
3457         if(  BC_DisplayInfo::top_border >= 0 ) top_y +=  BC_DisplayInfo::top_border;
3458         for( int i=0; i<xinerama_screens; ++i ) {
3459                 int scr_y = top_y - xinerama_info[i].y_org;
3460                 if( scr_y < 0 || scr_y >= xinerama_info[i].height ) continue;
3461                 int scr_x = top_x - xinerama_info[i].x_org;
3462                 if( scr_x >= 0 && scr_x < xinerama_info[i].width )
3463                         return &xinerama_info[i];
3464         }
3465         return 0;
3466 }
3467
3468 int BC_WindowBase::get_screen_x(int lock_display, int screen)
3469 {
3470         int result = -1;
3471         if(lock_display) lock_window("BC_WindowBase::get_screen_x");
3472         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3473         if( !info ) {
3474                 result = 0;
3475                 int root_w = get_root_w(0);
3476                 int root_h = get_root_h(0);
3477 // Shift X based on position of current window if dual head
3478                 if( (float)root_w/root_h > 1.8 ) {
3479                         root_w = get_screen_w(0, 0);
3480                         if( top_level->get_x() >= root_w )
3481                                 result = root_w;
3482                 }
3483         }
3484         else
3485                 result = info->x_org;
3486         if(lock_display) unlock_window();
3487         return result;
3488 }
3489
3490 int BC_WindowBase::get_screen_y(int lock_display, int screen)
3491 {
3492         if(lock_display) lock_window("BC_WindowBase::get_screen_y");
3493         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3494         int result = !info ? 0 : info->y_org;
3495         if(lock_display) unlock_window();
3496         return result;
3497 }
3498
3499 int BC_WindowBase::get_screen_w(int lock_display, int screen)
3500 {
3501         int result = -1;
3502         if(lock_display) lock_window("BC_WindowBase::get_screen_w");
3503         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3504         if( !info ) {
3505                 int width = get_root_w(0);
3506                 int height = get_root_h(0);
3507                 if( (float)width/height > 1.8 ) {
3508                         // If dual head, the screen width is > 16x9
3509                         // but we only want to fill one screen
3510                         // this code assumes the "big" screen is on the right
3511                         int scr_w0 = width / 2;
3512                         switch( height ) {
3513                         case 600:  scr_w0 = 800;   break;
3514                         case 720:  scr_w0 = 1280;  break;
3515                         case 1024: scr_w0 = 1280;  break;
3516                         case 1200: scr_w0 = 1600;  break;
3517                         case 1080: scr_w0 = 1920;  break;
3518                         }
3519                         int scr_w1 = width - scr_w0;
3520                         result = screen > 0 ? scr_w1 :
3521                                 screen == 0 ? scr_w0 :
3522                                 top_level->get_x() < scr_w0 ? scr_w0 : scr_w1;
3523                 }
3524                 else
3525                         result = width;
3526         }
3527         else
3528                 result = info->width;
3529         if(lock_display) unlock_window();
3530         return result;
3531 }
3532
3533 int BC_WindowBase::get_screen_h(int lock_display, int screen)
3534 {
3535         if(lock_display) lock_window("BC_WindowBase::get_screen_h");
3536         XineramaScreenInfo *info = top_level->get_xinerama_info(screen);
3537         int result = info ? info->height : get_root_h(0);
3538         if(lock_display) unlock_window();
3539         return result;
3540 }
3541
3542 // Bottom right corner
3543 int BC_WindowBase::get_x2()
3544 {
3545         return w + x;
3546 }
3547
3548 int BC_WindowBase::get_y2()
3549 {
3550         return y + h;
3551 }
3552
3553 int BC_WindowBase::get_video_on()
3554 {
3555         return video_on;
3556 }
3557
3558 int BC_WindowBase::get_hidden()
3559 {
3560         return top_level->hidden;
3561 }
3562
3563 int BC_WindowBase::cursor_inside()
3564 {
3565         return (top_level->cursor_x >= 0 &&
3566                         top_level->cursor_y >= 0 &&
3567                         top_level->cursor_x < w &&
3568                         top_level->cursor_y < h);
3569 }
3570
3571 BC_WindowBase* BC_WindowBase::get_top_level()
3572 {
3573         return top_level;
3574 }
3575
3576 BC_WindowBase* BC_WindowBase::get_parent()
3577 {
3578         return parent_window;
3579 }
3580
3581 int BC_WindowBase::get_color_model()
3582 {
3583         return top_level->color_model;
3584 }
3585
3586 BC_Resources* BC_WindowBase::get_resources()
3587 {
3588         return &BC_WindowBase::resources;
3589 }
3590
3591 BC_Synchronous* BC_WindowBase::get_synchronous()
3592 {
3593         return BC_WindowBase::resources.get_synchronous();
3594 }
3595
3596 int BC_WindowBase::get_bg_color()
3597 {
3598         return bg_color;
3599 }
3600
3601 void BC_WindowBase::set_bg_color(int color)
3602 {
3603         this->bg_color = color;
3604 }
3605
3606 BC_Pixmap* BC_WindowBase::get_bg_pixmap()
3607 {
3608         return bg_pixmap;
3609 }
3610
3611 void BC_WindowBase::set_active_subwindow(BC_WindowBase *subwindow)
3612 {
3613         top_level->active_subwindow = subwindow;
3614 }
3615
3616 int BC_WindowBase::activate()
3617 {
3618         return 0;
3619 }
3620
3621 int BC_WindowBase::deactivate()
3622 {
3623         if(window_type == MAIN_WINDOW)
3624         {
3625                 if( top_level->active_menubar ) {
3626                         top_level->active_menubar->deactivate();
3627                         top_level->active_menubar = 0;
3628                 }
3629                 if( top_level->active_popup_menu ) {
3630                         top_level->active_popup_menu->deactivate();
3631                         top_level->active_popup_menu = 0;
3632                 }
3633                 if( top_level->active_subwindow ) {
3634                         top_level->active_subwindow->deactivate();
3635                         top_level->active_subwindow = 0;
3636                 }
3637                 if( top_level->motion_events && top_level->last_motion_win == this->win )
3638                         top_level->motion_events = 0;
3639
3640         }
3641         return 0;
3642 }
3643
3644 int BC_WindowBase::cycle_textboxes(int amount)
3645 {
3646         int result = 0;
3647         BC_WindowBase *new_textbox = 0;
3648
3649         if(amount > 0)
3650         {
3651                 BC_WindowBase *first_textbox = 0;
3652                 find_next_textbox(&first_textbox, &new_textbox, result);
3653                 if(!new_textbox) new_textbox = first_textbox;
3654
3655         }
3656         else
3657         if(amount < 0)
3658         {
3659                 BC_WindowBase *last_textbox = 0;
3660                 find_prev_textbox(&last_textbox, &new_textbox, result);
3661                 if(!new_textbox) new_textbox = last_textbox;
3662
3663         }
3664
3665         if(new_textbox != active_subwindow)
3666         {
3667                 deactivate();
3668                 new_textbox->activate();
3669         }
3670
3671         return 0;
3672 }
3673
3674 int BC_WindowBase::find_next_textbox(BC_WindowBase **first_textbox, BC_WindowBase **next_textbox, int &result)
3675 {
3676 // Search subwindows for textbox
3677         for(int i = 0; i < subwindows->total && result < 2; i++)
3678         {
3679                 BC_WindowBase *test_subwindow = subwindows->values[i];
3680                 test_subwindow->find_next_textbox(first_textbox, next_textbox, result);
3681         }
3682
3683         if(result < 2)
3684         {
3685                 if(uses_text())
3686                 {
3687                         if(!*first_textbox) *first_textbox = this;
3688
3689                         if(result < 1)
3690                         {
3691                                 if(top_level->active_subwindow == this)
3692                                         result++;
3693                         }
3694                         else
3695                         {
3696                                 result++;
3697                                 *next_textbox = this;
3698                         }
3699                 }
3700         }
3701         return 0;
3702 }
3703
3704 int BC_WindowBase::find_prev_textbox(BC_WindowBase **last_textbox, BC_WindowBase **prev_textbox, int &result)
3705 {
3706         if(result < 2)
3707         {
3708                 if(uses_text())
3709                 {
3710                         if(!*last_textbox) *last_textbox = this;
3711
3712                         if(result < 1)
3713                         {
3714                                 if(top_level->active_subwindow == this)
3715                                         result++;
3716                         }
3717                         else
3718                         {
3719                                 result++;
3720                                 *prev_textbox = this;
3721                         }
3722                 }
3723         }
3724
3725 // Search subwindows for textbox
3726         for(int i = subwindows->total - 1; i >= 0 && result < 2; i--)
3727         {
3728                 BC_WindowBase *test_subwindow = subwindows->values[i];
3729                 test_subwindow->find_prev_textbox(last_textbox, prev_textbox, result);
3730         }
3731         return 0;
3732 }
3733
3734 BC_Clipboard* BC_WindowBase::get_clipboard()
3735 {
3736 #ifdef SINGLE_THREAD
3737         return BC_Display::display_global->clipboard;
3738 #else
3739         return top_level->clipboard;
3740 #endif
3741 }
3742
3743 Atom BC_WindowBase::to_clipboard(const char *data, long len, int clipboard_num)
3744 {
3745         return get_clipboard()->to_clipboard(this, data, len, clipboard_num);
3746 }
3747
3748 long BC_WindowBase::from_clipboard(char *data, long maxlen, int clipboard_num)
3749 {
3750         return get_clipboard()->from_clipboard(data, maxlen, clipboard_num);
3751 }
3752
3753 long BC_WindowBase::clipboard_len(int clipboard_num)
3754 {
3755         return get_clipboard()->clipboard_len(clipboard_num);
3756 }
3757
3758 int BC_WindowBase::do_selection_clear(Window win)
3759 {
3760         top_level->event_win = win;
3761         return dispatch_selection_clear();
3762 }
3763
3764 int BC_WindowBase::dispatch_selection_clear()
3765 {
3766         int result = 0;
3767         for( int i=0; i<subwindows->total && !result; ++i )
3768                 result = subwindows->values[i]->dispatch_selection_clear();
3769         if( !result )
3770                 result = selection_clear_event();
3771         return result;
3772 }
3773
3774
3775 void BC_WindowBase::get_relative_cursor(int &x, int &y, int lock_window)
3776 {
3777         int abs_x, abs_y, win_x, win_y;
3778         unsigned int temp_mask;
3779         Window temp_win;
3780
3781         if(lock_window) this->lock_window("BC_WindowBase::get_relative_cursor");
3782         XQueryPointer(top_level->display, top_level->win,
3783            &temp_win, &temp_win, &abs_x, &abs_y, &win_x, &win_y,
3784            &temp_mask);
3785
3786         XTranslateCoordinates(top_level->display, top_level->rootwin,
3787            win, abs_x, abs_y, &x, &y, &temp_win);
3788         if(lock_window) this->unlock_window();
3789 }
3790 int BC_WindowBase::get_relative_cursor_x(int lock_window)
3791 {
3792         int x, y;
3793         get_relative_cursor(x, y, lock_window);
3794         return x;
3795 }
3796 int BC_WindowBase::get_relative_cursor_y(int lock_window)
3797 {
3798         int x, y;
3799         get_relative_cursor(x, y, lock_window);
3800         return y;
3801 }
3802
3803 void BC_WindowBase::get_abs_cursor(int &abs_x, int &abs_y, int lock_window)
3804 {
3805         int win_x, win_y;
3806         unsigned int temp_mask;
3807         Window temp_win;
3808
3809         if(lock_window) this->lock_window("BC_WindowBase::get_abs_cursor");
3810         XQueryPointer(top_level->display, top_level->win,
3811                 &temp_win, &temp_win, &abs_x, &abs_y, &win_x, &win_y,
3812                 &temp_mask);
3813         if(lock_window) this->unlock_window();
3814 }
3815 int BC_WindowBase::get_abs_cursor_x(int lock_window)
3816 {
3817         int abs_x, abs_y;
3818         get_abs_cursor(abs_x, abs_y, lock_window);
3819         return abs_x;
3820 }
3821 int BC_WindowBase::get_abs_cursor_y(int lock_window)
3822 {
3823         int abs_x, abs_y;
3824         get_abs_cursor(abs_x, abs_y, lock_window);
3825         return abs_y;
3826 }
3827
3828 void BC_WindowBase::get_pop_cursor(int &px, int &py, int lock_window)
3829 {
3830         int margin = 100;
3831         get_abs_cursor(px, py, lock_window);
3832         if( px < margin ) px = margin;
3833         if( py < margin ) py = margin;
3834         int wd = get_screen_w(lock_window,-1) - margin;
3835         if( px > wd ) px = wd;
3836         int ht = get_screen_h(lock_window,-1) - margin;
3837         if( py > ht ) py = ht;
3838 }
3839 int BC_WindowBase::get_pop_cursor_x(int lock_window)
3840 {
3841         int px, py;
3842         get_pop_cursor(px, py, lock_window);
3843         return px;
3844 }
3845 int BC_WindowBase::get_pop_cursor_y(int lock_window)
3846 {
3847         int px, py;
3848         get_pop_cursor(px, py, lock_window);
3849         return py;
3850 }
3851
3852 int BC_WindowBase::match_window(Window win)
3853 {
3854         if (this->win == win) return 1;
3855         int result = 0;
3856         for(int i = 0; i < subwindows->total; i++) {
3857                 result = subwindows->values[i]->match_window(win);
3858                 if (result) return result;
3859         }
3860         return 0;
3861
3862 }
3863
3864 int BC_WindowBase::get_cursor_over_window()
3865 {
3866         int abs_x, abs_y, win_x, win_y;
3867         unsigned int mask_return;
3868         Window root_return, child_return;
3869
3870         int ret = XQueryPointer(top_level->display, top_level->rootwin,
3871                 &root_return, &child_return, &abs_x, &abs_y,
3872                 &win_x, &win_y, &mask_return);
3873         if( ret && child_return == None ) ret = 0;
3874         if( ret && win != child_return )
3875                 ret = top_level->match_window(child_return);
3876 // query pointer can return a window manager window with this top_level as a child
3877 //  for kde this can be two levels deep
3878         unsigned int nchildren_return = 0;
3879         Window parent_return, *children_return = 0;
3880         Window top_win = top_level->win;
3881         while( !ret && top_win != top_level->rootwin && top_win != root_return &&
3882                 XQueryTree(top_level->display, top_win, &root_return,
3883                         &parent_return, &children_return, &nchildren_return) ) {
3884                 if( children_return ) XFree(children_return);
3885                 if( (top_win=parent_return) == child_return ) ret = 1;
3886         }
3887         return ret;
3888 }
3889
3890 int BC_WindowBase::cursor_above()
3891 {
3892         int rx, ry;
3893         get_relative_cursor(rx, ry);
3894         return rx < 0 || rx >= get_w() ||
3895                 ry < 0 || ry >= get_h() ? 0 : 1;
3896 }
3897
3898 int BC_WindowBase::get_drag_x()
3899 {
3900         return top_level->drag_x;
3901 }
3902
3903 int BC_WindowBase::get_drag_y()
3904 {
3905         return top_level->drag_y;
3906 }
3907
3908 int BC_WindowBase::get_cursor_x()
3909 {
3910         return top_level->cursor_x;
3911 }
3912
3913 int BC_WindowBase::get_cursor_y()
3914 {
3915         return top_level->cursor_y;
3916 }
3917
3918 int BC_WindowBase::dump_windows()
3919 {
3920         printf("\tBC_WindowBase::dump_windows window=%p win=%p '%s', %dx%d+%d+%d %s\n",
3921                 this, (void*)this->win, title, w,h,x,y, typeid(*this).name());
3922         for(int i = 0; i < subwindows->size(); i++)
3923                 subwindows->get(i)->dump_windows();
3924         for(int i = 0; i < popups.size(); i++) {
3925                 BC_WindowBase *p = popups[i];
3926                 printf("\tBC_WindowBase::dump_windows popup=%p win=%p '%s', %dx%d+%d+%d %s\n",
3927                         p, (void*)p->win, p->title, p->w,p->h,p->x,p->y, typeid(*p).name());
3928         }
3929         return 0;
3930 }
3931
3932 int BC_WindowBase::is_event_win()
3933 {
3934         return this->win == top_level->event_win;
3935 }
3936
3937 void BC_WindowBase::set_dragging(int value)
3938 {
3939         is_dragging = value;
3940 }
3941
3942 int BC_WindowBase::get_dragging()
3943 {
3944         return is_dragging;
3945 }
3946
3947 int BC_WindowBase::get_buttonpress()
3948 {
3949         return top_level->button_number;
3950 }
3951
3952 int BC_WindowBase::get_button_down()
3953 {
3954         return top_level->button_down;
3955 }
3956
3957 int BC_WindowBase::alt_down()
3958 {
3959         return top_level->alt_mask;
3960 }
3961
3962 int BC_WindowBase::shift_down()
3963 {
3964         return top_level->shift_mask;
3965 }
3966
3967 int BC_WindowBase::ctrl_down()
3968 {
3969         return top_level->ctrl_mask;
3970 }
3971
3972 wchar_t* BC_WindowBase::get_wkeystring(int *length)
3973 {
3974         if(length)
3975                 *length = top_level->wkey_string_length;
3976         return top_level->wkey_string;
3977 }
3978
3979 #ifdef X_HAVE_UTF8_STRING
3980 char* BC_WindowBase::get_keypress_utf8()
3981 {
3982         return top_level->key_pressed_utf8;
3983 }
3984 #endif
3985
3986
3987 int BC_WindowBase::get_keypress()
3988 {
3989         return top_level->key_pressed;
3990 }
3991
3992 int BC_WindowBase::get_double_click()
3993 {
3994         return top_level->double_click;
3995 }
3996
3997 int BC_WindowBase::get_triple_click()
3998 {
3999         return top_level->triple_click;
4000 }
4001
4002 int BC_WindowBase::get_bgcolor()
4003 {
4004         return bg_color;
4005 }
4006
4007 int BC_WindowBase::resize_window(int w, int h)
4008 {
4009         if(this->w == w && this->h == h) return 0;
4010
4011         if(window_type == MAIN_WINDOW && !allow_resize)
4012         {
4013                 XSizeHints size_hints;
4014                 size_hints.flags = PSize | PMinSize | PMaxSize;
4015                 size_hints.width = w;
4016                 size_hints.height = h;
4017                 size_hints.min_width = w;
4018                 size_hints.max_width = w;
4019                 size_hints.min_height = h;
4020                 size_hints.max_height = h;
4021                 XSetNormalHints(top_level->display, win, &size_hints);
4022         }
4023         XResizeWindow(top_level->display, win, w, h);
4024
4025         this->w = w;
4026         this->h = h;
4027         delete pixmap;
4028         pixmap = new BC_Pixmap(this, w, h);
4029
4030 // Propagate to menubar
4031         for(int i = 0; i < subwindows->total; i++)
4032         {
4033                 subwindows->values[i]->dispatch_resize_event(w, h);
4034         }
4035
4036         draw_background(0, 0, w, h);
4037         if(top_level == this && get_resources()->recursive_resizing)
4038                 resize_history.append(new BC_ResizeCall(w, h));
4039         return 0;
4040 }
4041
4042 // The only way for resize events to be propagated is by updating the internal w and h
4043 int BC_WindowBase::resize_event(int w, int h)
4044 {
4045         if(window_type == MAIN_WINDOW)
4046         {
4047                 this->w = w;
4048                 this->h = h;
4049         }
4050         return 0;
4051 }
4052
4053 int BC_WindowBase::reposition_window(int x, int y)
4054 {
4055         reposition_window(x, y, -1, -1);
4056         return 0;
4057 }
4058
4059
4060 int BC_WindowBase::reposition_window(int x, int y, int w, int h)
4061 {
4062         int resize = 0;
4063
4064 // Some tools set their own dimensions before calling this, causing the
4065 // resize check to skip.
4066         this->x = x;
4067         this->y = y;
4068
4069         if(w > 0 && w != this->w)
4070         {
4071                 resize = 1;
4072                 this->w = w;
4073         }
4074
4075         if(h > 0 && h != this->h)
4076         {
4077                 resize = 1;
4078                 this->h = h;
4079         }
4080
4081 //printf("BC_WindowBase::reposition_window %d %d %d\n", translation_count, x_correction, y_correction);
4082
4083         if(this->w <= 0)
4084                 printf("BC_WindowBase::reposition_window this->w == %d\n", this->w);
4085         if(this->h <= 0)
4086                 printf("BC_WindowBase::reposition_window this->h == %d\n", this->h);
4087
4088         if(translation_count && window_type == MAIN_WINDOW)
4089         {
4090 // KDE shifts window right and down.
4091 // FVWM leaves window alone and adds border around it.
4092                 XMoveResizeWindow(top_level->display,
4093                         win,
4094                         x - BC_DisplayInfo::auto_reposition_x,
4095                         y - BC_DisplayInfo::auto_reposition_y,
4096                         this->w,
4097                         this->h);
4098         }
4099         else
4100         {
4101                 XMoveResizeWindow(top_level->display,
4102                         win,
4103                         x,
4104                         y,
4105                         this->w,
4106                         this->h);
4107         }
4108
4109         if(resize)
4110         {
4111                 delete pixmap;
4112                 pixmap = new BC_Pixmap(this, this->w, this->h);
4113                 clear_box(0,0, this->w, this->h);
4114 // Propagate to menubar
4115                 for(int i = 0; i < subwindows->total; i++)
4116                 {
4117                         subwindows->values[i]->dispatch_resize_event(this->w, this->h);
4118                 }
4119
4120 //              draw_background(0, 0, w, h);
4121         }
4122
4123         return 0;
4124 }
4125
4126 int BC_WindowBase::reposition_window_relative(int dx, int dy, int w, int h)
4127 {
4128         return reposition_window(get_x()+dx, get_y()+dy, w, h);
4129 }
4130
4131 int BC_WindowBase::reposition_window_relative(int dx, int dy)
4132 {
4133         return reposition_window_relative(dx, dy, -1, -1);
4134 }
4135
4136 void BC_WindowBase::set_tooltips(int v)
4137 {
4138         get_resources()->tooltips_enabled = v;
4139 }
4140
4141 void BC_WindowBase::set_force_tooltip(int v)
4142 {
4143         force_tooltip = v;
4144 }
4145
4146 int BC_WindowBase::raise_window(int do_flush)
4147 {
4148         XRaiseWindow(top_level->display, win);
4149         if(do_flush) XFlush(top_level->display);
4150         return 0;
4151 }
4152
4153 int BC_WindowBase::lower_window(int do_flush)
4154 {
4155         XLowerWindow(top_level->display, win);
4156         if(do_flush) XFlush(top_level->display);
4157         return 0;
4158 }
4159
4160 void BC_WindowBase::set_background(VFrame *bitmap)
4161 {
4162         if(bg_pixmap && !shared_bg_pixmap) delete bg_pixmap;
4163
4164         bg_pixmap = new BC_Pixmap(this, bitmap, PIXMAP_OPAQUE);
4165         shared_bg_pixmap = 0;
4166         draw_background(0, 0, w, h);
4167 }
4168
4169 void BC_WindowBase::put_title(const char *text)
4170 {
4171         char *cp = this->title, *ep = cp+sizeof(this->title)-1;
4172         for( const unsigned char *bp = (const unsigned char *)text; *bp && cp<ep; ++bp )
4173                 *cp++ = *bp >= ' ' ? *bp : ' ';
4174         *cp = 0;
4175 }
4176
4177 void BC_WindowBase::set_title(const char *text, int utf8)
4178 {
4179 // utf8>0: wm + net_wm, utf8=0: wm only,  utf<0: net_wm only
4180         put_title(text);
4181         const unsigned char *wm_title = (const unsigned char *)title;
4182         int title_len = strlen((const char *)title);
4183         if( utf8 >= 0 ) {
4184                 Atom xa_wm_name = XA_WM_NAME;
4185                 Atom xa_icon_name = XA_WM_ICON_NAME;
4186                 Atom xa_string = XA_STRING;
4187                 XChangeProperty(display, win, xa_wm_name, xa_string, 8,
4188                                 PropModeReplace, wm_title, title_len);
4189                 XChangeProperty(display, win, xa_icon_name, xa_string, 8,
4190                                 PropModeReplace, wm_title, title_len);
4191         }
4192         if( utf8 != 0 ) {
4193                 Atom xa_net_wm_name = XInternAtom(display, "_NET_WM_NAME", True);
4194                 Atom xa_net_icon_name = XInternAtom(display, "_NET_WM_ICON_NAME", True);
4195                 Atom xa_utf8_string = XInternAtom(display, "UTF8_STRING", True);
4196                 XChangeProperty(display, win, xa_net_wm_name, xa_utf8_string, 8,
4197                                         PropModeReplace, wm_title, title_len);
4198                 XChangeProperty(display, win, xa_net_icon_name, xa_utf8_string, 8,
4199                                         PropModeReplace, wm_title, title_len);
4200         }
4201         flush();
4202 }
4203
4204 const char *BC_WindowBase::get_title()
4205 {
4206         return title;
4207 }
4208
4209 int BC_WindowBase::get_toggle_value()
4210 {
4211         return toggle_value;
4212 }
4213
4214 int BC_WindowBase::get_toggle_drag()
4215 {
4216         return toggle_drag;
4217 }
4218
4219 int BC_WindowBase::set_icon(VFrame *data)
4220 {
4221         if(icon_pixmap) delete icon_pixmap;
4222         icon_pixmap = new BC_Pixmap(top_level, data, PIXMAP_ALPHA, 1);
4223
4224         if(icon_window) delete icon_window;
4225         icon_window = new BC_Popup(this,
4226                 (int)BC_INFINITY,
4227                 (int)BC_INFINITY,
4228                 icon_pixmap->get_w(),
4229                 icon_pixmap->get_h(),
4230                 -1,
4231                 1, // All windows are hidden initially
4232                 icon_pixmap);
4233
4234         XWMHints wm_hints;
4235         wm_hints.flags = WindowGroupHint | IconPixmapHint | IconMaskHint | IconWindowHint;
4236         wm_hints.icon_pixmap = icon_pixmap->get_pixmap();
4237         wm_hints.icon_mask = icon_pixmap->get_alpha();
4238         wm_hints.icon_window = icon_window->win;
4239         wm_hints.window_group = XGroupLeader;
4240
4241 // for(int i = 0; i < 1000; i++)
4242 // printf("02x ", icon_pixmap->get_alpha()->get_row_pointers()[0][i]);
4243 // printf("\n");
4244
4245         XSetWMHints(top_level->display, top_level->win, &wm_hints);
4246         XSync(top_level->display, 0);
4247         return 0;
4248 }
4249
4250 int BC_WindowBase::set_w(int w)
4251 {
4252         this->w = w;
4253         return 0;
4254 }
4255
4256 int BC_WindowBase::set_h(int h)
4257 {
4258         this->h = h;
4259         return 0;
4260 }
4261
4262 int BC_WindowBase::load_defaults(BC_Hash *defaults)
4263 {
4264         BC_Resources *resources = get_resources();
4265         char string[BCTEXTLEN];
4266         int newest_id = - 1;
4267         for(int i = 0; i < FILEBOX_HISTORY_SIZE; i++)
4268         {
4269                 sprintf(string, "FILEBOX_HISTORY_PATH%d", i);
4270                 resources->filebox_history[i].path[0] = 0;
4271                 defaults->get(string, resources->filebox_history[i].path);
4272                 sprintf(string, "FILEBOX_HISTORY_ID%d", i);
4273                 resources->filebox_history[i].id = defaults->get(string, resources->get_id());
4274                 if(resources->filebox_history[i].id > newest_id)
4275                         newest_id = resources->filebox_history[i].id;
4276         }
4277
4278         resources->filebox_id = newest_id + 1;
4279         resources->filebox_mode = defaults->get("FILEBOX_MODE", get_resources()->filebox_mode);
4280         resources->filebox_w = defaults->get("FILEBOX_W", get_resources()->filebox_w);
4281         resources->filebox_h = defaults->get("FILEBOX_H", get_resources()->filebox_h);
4282         resources->filebox_columntype[0] = defaults->get("FILEBOX_TYPE0", resources->filebox_columntype[0]);
4283         resources->filebox_columntype[1] = defaults->get("FILEBOX_TYPE1", resources->filebox_columntype[1]);
4284         resources->filebox_columntype[2] = defaults->get("FILEBOX_TYPE2", resources->filebox_columntype[2]);
4285         resources->filebox_columntype[3] = defaults->get("FILEBOX_TYPE3", resources->filebox_columntype[3]);
4286         resources->filebox_columnwidth[0] = defaults->get("FILEBOX_WIDTH0", resources->filebox_columnwidth[0]);
4287         resources->filebox_columnwidth[1] = defaults->get("FILEBOX_WIDTH1", resources->filebox_columnwidth[1]);
4288         resources->filebox_columnwidth[2] = defaults->get("FILEBOX_WIDTH2", resources->filebox_columnwidth[2]);
4289         resources->filebox_columnwidth[3] = defaults->get("FILEBOX_WIDTH3", resources->filebox_columnwidth[3]);
4290         resources->filebox_size_format = defaults->get("FILEBOX_SIZE_FORMAT", get_resources()->filebox_size_format);
4291         defaults->get("FILEBOX_FILTER", resources->filebox_filter);
4292         return 0;
4293 }
4294
4295 int BC_WindowBase::save_defaults(BC_Hash *defaults)
4296 {
4297         BC_Resources *resources = get_resources();
4298         char string[BCTEXTLEN];
4299         for(int i = 0; i < FILEBOX_HISTORY_SIZE; i++)
4300         {
4301                 sprintf(string, "FILEBOX_HISTORY_PATH%d", i);
4302                 defaults->update(string, resources->filebox_history[i].path);
4303                 sprintf(string, "FILEBOX_HISTORY_ID%d", i);
4304                 defaults->update(string, resources->filebox_history[i].id);
4305         }
4306         defaults->update("FILEBOX_MODE", resources->filebox_mode);
4307         defaults->update("FILEBOX_W", resources->filebox_w);
4308         defaults->update("FILEBOX_H", resources->filebox_h);
4309         defaults->update("FILEBOX_TYPE0", resources->filebox_columntype[0]);
4310         defaults->update("FILEBOX_TYPE1", resources->filebox_columntype[1]);
4311         defaults->update("FILEBOX_TYPE2", resources->filebox_columntype[2]);
4312         defaults->update("FILEBOX_TYPE3", resources->filebox_columntype[3]);
4313         defaults->update("FILEBOX_WIDTH0", resources->filebox_columnwidth[0]);
4314         defaults->update("FILEBOX_WIDTH1", resources->filebox_columnwidth[1]);
4315         defaults->update("FILEBOX_WIDTH2", resources->filebox_columnwidth[2]);
4316         defaults->update("FILEBOX_WIDTH3", resources->filebox_columnwidth[3]);
4317         defaults->update("FILEBOX_FILTER", resources->filebox_filter);
4318         defaults->update("FILEBOX_SIZE_FORMAT", get_resources()->filebox_size_format);
4319         return 0;
4320 }
4321
4322
4323
4324 // For some reason XTranslateCoordinates can take a long time to return.
4325 // We work around this by only calling it when the event windows are different.
4326 void BC_WindowBase::translate_coordinates(Window src_w,
4327                 Window dest_w,
4328                 int src_x,
4329                 int src_y,
4330                 int *dest_x_return,
4331                 int *dest_y_return)
4332 {
4333         Window tempwin = 0;
4334 //Timer timer;
4335 //timer.update();
4336         if(src_w == dest_w)
4337         {
4338                 *dest_x_return = src_x;
4339                 *dest_y_return = src_y;
4340         }
4341         else
4342         {
4343                 XTranslateCoordinates(top_level->display,
4344                         src_w,
4345                         dest_w,
4346                         src_x,
4347                         src_y,
4348                         dest_x_return,
4349                         dest_y_return,
4350                         &tempwin);
4351 //printf("BC_WindowBase::translate_coordinates 1 %lld\n", timer.get_difference());
4352         }
4353 }
4354
4355 void BC_WindowBase::get_root_coordinates(int x, int y, int *abs_x, int *abs_y)
4356 {
4357         translate_coordinates(win, top_level->rootwin, x, y, abs_x, abs_y);
4358 }
4359
4360 void BC_WindowBase::get_win_coordinates(int abs_x, int abs_y, int *x, int *y)
4361 {
4362         translate_coordinates(top_level->rootwin, win, abs_x, abs_y, x, y);
4363 }
4364
4365
4366
4367
4368
4369
4370 #ifdef HAVE_LIBXXF86VM
4371 void BC_WindowBase::closest_vm(int *vm, int *width, int *height)
4372 {
4373    int foo,bar;
4374    *vm = 0;
4375    if(XF86VidModeQueryExtension(top_level->display,&foo,&bar)) {
4376            int vm_count,i;
4377            XF86VidModeModeInfo **vm_modelines;
4378            XF86VidModeGetAllModeLines(top_level->display,XDefaultScreen(top_level->display),&vm_count,&vm_modelines);
4379            for (i = 0; i < vm_count; i++) {
4380                    if (vm_modelines[i]->hdisplay < vm_modelines[*vm]->hdisplay && vm_modelines[i]->hdisplay >= *width)
4381                            *vm = i;
4382            }
4383            display = top_level->display;
4384            if (vm_modelines[*vm]->hdisplay == *width)
4385                    *vm = -1;
4386            else
4387            {
4388                    *width = vm_modelines[*vm]->hdisplay;
4389                    *height = vm_modelines[*vm]->vdisplay;
4390            }
4391    }
4392 }
4393
4394 void BC_WindowBase::scale_vm(int vm)
4395 {
4396    int foo,bar,dotclock;
4397    if(XF86VidModeQueryExtension(top_level->display,&foo,&bar))
4398    {
4399            int vm_count;
4400            XF86VidModeModeInfo **vm_modelines;
4401            XF86VidModeModeLine vml;
4402            XF86VidModeGetAllModeLines(top_level->display,XDefaultScreen(top_level->display),&vm_count,&vm_modelines);
4403            XF86VidModeGetModeLine(top_level->display,XDefaultScreen(top_level->display),&dotclock,&vml);
4404            orig_modeline.dotclock = dotclock;
4405            orig_modeline.hdisplay = vml.hdisplay;
4406            orig_modeline.hsyncstart = vml.hsyncstart;
4407            orig_modeline.hsyncend = vml.hsyncend;
4408            orig_modeline.htotal = vml.htotal;
4409            orig_modeline.vdisplay = vml.vdisplay;
4410            orig_modeline.vsyncstart = vml.vsyncstart;
4411            orig_modeline.vsyncend = vml.vsyncend;
4412            orig_modeline.vtotal = vml.vtotal;
4413            orig_modeline.flags = vml.flags;
4414            orig_modeline.privsize = vml.privsize;
4415            // orig_modeline.private = vml.private;
4416            XF86VidModeSwitchToMode(top_level->display,XDefaultScreen(top_level->display),vm_modelines[vm]);
4417            XF86VidModeSetViewPort(top_level->display,XDefaultScreen(top_level->display),0,0);
4418            XFlush(top_level->display);
4419    }
4420 }
4421
4422 void BC_WindowBase::restore_vm()
4423 {
4424    XF86VidModeSwitchToMode(top_level->display,XDefaultScreen(top_level->display),&orig_modeline);
4425    XFlush(top_level->display);
4426 }
4427
4428
4429 #endif
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448 #ifndef SINGLE_THREAD
4449 int BC_WindowBase::get_event_count()
4450 {
4451         event_lock->lock("BC_WindowBase::get_event_count");
4452         int result = common_events.total;
4453         event_lock->unlock();
4454         return result;
4455 }
4456
4457 XEvent* BC_WindowBase::get_event()
4458 {
4459         XEvent *result = 0;
4460         while(!done && !result)
4461         {
4462                 event_condition->lock("BC_WindowBase::get_event");
4463                 event_lock->lock("BC_WindowBase::get_event");
4464
4465                 if(common_events.total && !done)
4466                 {
4467                         result = common_events.values[0];
4468                         common_events.remove_number(0);
4469                 }
4470
4471                 event_lock->unlock();
4472         }
4473         return result;
4474 }
4475
4476 void BC_WindowBase::put_event(XEvent *event)
4477 {
4478         event_lock->lock("BC_WindowBase::put_event");
4479         common_events.append(event);
4480         event_lock->unlock();
4481         event_condition->unlock();
4482 }
4483
4484 void BC_WindowBase::dequeue_events(Window win)
4485 {
4486         event_lock->lock("BC_WindowBase::dequeue_events");
4487
4488         int out = 0, total = common_events.size();
4489         for( int in=0; in<total; ++in ) {
4490                 if( common_events[in]->xany.window == win ) continue;
4491                 common_events[out++] = common_events[in];
4492         }
4493         common_events.total = out;
4494
4495         event_lock->unlock();
4496 }
4497
4498 int BC_WindowBase::resend_event(BC_WindowBase *window)
4499 {
4500         if( resend_event_window ) return 1;
4501         resend_event_window = window;
4502         return 0;
4503 }
4504
4505 #else
4506
4507 int BC_WindowBase::resend_event(BC_WindowBase *window)
4508 {
4509         return 1;
4510 }
4511
4512 #endif // SINGLE_THREAD
4513
4514 int BC_WindowBase::get_id()
4515 {
4516         return id;
4517 }
4518
4519
4520 BC_Pixmap *BC_WindowBase::create_pixmap(VFrame *vframe)
4521 {
4522         int w = vframe->get_w(), h = vframe->get_h();
4523         BC_Pixmap *icon = new BC_Pixmap(this, w, h);
4524         icon->draw_vframe(vframe, 0,0, w,h, 0,0);
4525         return icon;
4526 }
4527
4528
4529 void BC_WindowBase::flicker(int n, int ms)
4530 {
4531         int color = get_bg_color();
4532         for( int i=2*n; --i>=0; ) {
4533                 set_inverse();          set_bg_color(WHITE);
4534                 clear_box(0,0, w,h);    flash(1);
4535                 sync_display();         Timer::delay(ms);
4536         }
4537         set_bg_color(color);
4538         set_opaque();
4539 }
4540