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