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