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