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