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