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