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