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