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