ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/video_x.cpp
(Generate patch)

Comparing BasiliskII/src/Unix/video_x.cpp (file contents):
Revision 1.42 by cebix, 2001-06-28T21:20:00Z vs.
Revision 1.59 by cebix, 2001-07-11T17:04:41Z

# Line 24 | Line 24
24   *      Ctrl-Tab = suspend DGA mode
25   *      Ctrl-Esc = emergency quit
26   *      Ctrl-F1 = mount floppy
27 + *      Ctrl-F5 = grab mouse (in windowed mode)
28   */
29  
30   #include "sysdeps.h"
# Line 36 | Line 37
37   #include <sys/shm.h>
38   #include <errno.h>
39  
40 + #include <algorithm>
41 +
42 + #ifndef NO_STD_NAMESPACE
43 + using std::sort;
44 + #endif
45 +
46   #ifdef HAVE_PTHREADS
47   # include <pthread.h>
48   #endif
# Line 72 | Line 79 | enum {
79  
80   // Constants
81   const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
82 < const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
82 >
83 > static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
84 > static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
85  
86  
87   // Global variables
88   static int32 frame_skip;                                                        // Prefs items
89 < static int16 mouse_wheel_mode = 1;
90 < static int16 mouse_wheel_lines = 3;
89 > static int16 mouse_wheel_mode;
90 > static int16 mouse_wheel_lines;
91  
92   static int display_type = DISPLAY_WINDOW;                       // See enum above
93   static bool local_X11;                                                          // Flag: X server running on local machine?
94 < static uint8 *the_buffer;                                                       // Mac frame buffer
94 > static uint8 *the_buffer = NULL;                                        // Mac frame buffer (where MacOS draws into)
95 > static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer (for refreshed modes)
96 > static uint32 the_buffer_size;                                          // Size of allocated the_buffer
97  
87 #ifdef HAVE_PTHREADS
98   static bool redraw_thread_active = false;                       // Flag: Redraw thread installed
99 + #ifdef HAVE_PTHREADS
100   static volatile bool redraw_thread_cancel;                      // Flag: Cancel Redraw thread
101   static pthread_t redraw_thread;                                         // Redraw thread
102   #endif
# Line 93 | Line 104 | static pthread_t redraw_thread;                                                //
104   static bool has_dga = false;                                            // Flag: Video DGA capable
105   static bool has_vidmode = false;                                        // Flag: VidMode extension available
106  
107 + #ifdef ENABLE_VOSF
108 + static bool use_vosf = true;                                            // Flag: VOSF enabled
109 + #else
110 + static const bool use_vosf = false;                                     // VOSF not possible
111 + #endif
112 +
113   static bool ctrl_down = false;                                          // Flag: Ctrl key pressed
114   static bool caps_on = false;                                            // Flag: Caps Lock on
115   static bool quit_full_screen = false;                           // Flag: DGA close requested from redraw thread
# Line 106 | Line 123 | static int keycode_table[256];                                         // X
123  
124   // X11 variables
125   static int screen;                                                                      // Screen number
126 < static int xdepth;                                                                      // Depth of X screen
127 < static Window rootwin, the_win;                                         // Root window and our window
128 < static XVisualInfo visualInfo;
112 < static Visual *vis;
113 < static Colormap cmap[2];                                                        // Two colormaps (DGA) for 8-bit mode
114 < static bool cmap_allocated = false;
126 > static Window rootwin;                                                          // Root window and our window
127 > static int num_depths = 0;                                                      // Number of available X depths
128 > static int *avail_depths = NULL;                                        // List of available X depths
129   static XColor black, white;
130   static unsigned long black_pixel, white_pixel;
131   static int eventmask;
118 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
119 static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
120 static Atom WM_DELETE_WINDOW = (Atom)0;
132  
133 < static XColor palette[256];                                                     // Color palette for 8-bit mode
133 > static int xdepth;                                                                      // Depth of X screen
134 > static XVisualInfo visualInfo;
135 > static Visual *vis;
136 > static int color_class;
137 >
138 > static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
139 >
140 > static Colormap cmap[2] = {0, 0};                                       // Colormaps for indexed modes (DGA needs two of them)
141 >
142 > static XColor palette[256];                                                     // Color palette to be used as CLUT and gamma table
143   static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
144 +
145 + #ifdef ENABLE_FBDEV_DGA
146 + static int fbdev_fd = -1;
147 + #endif
148 +
149 + #ifdef ENABLE_XF86_VIDMODE
150 + static XF86VidModeModeInfo **x_video_modes = NULL;      // Array of all available modes
151 + static int num_x_video_modes;
152 + #endif
153 +
154 + // Mutex to protect palette
155   #ifdef HAVE_PTHREADS
156 < static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;        // Mutex to protect palette
156 > static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;
157   #define LOCK_PALETTE pthread_mutex_lock(&palette_lock)
158   #define UNLOCK_PALETTE pthread_mutex_unlock(&palette_lock)
159   #else
# Line 130 | Line 161 | static pthread_mutex_t palette_lock = PT
161   #define UNLOCK_PALETTE
162   #endif
163  
164 < // Variables for window mode
134 < static GC the_gc;
135 < static XImage *img = NULL;
136 < static XShmSegmentInfo shminfo;
137 < static Cursor mac_cursor;
138 < static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer
139 < static bool have_shm = false;                                           // Flag: SHM extensions available
140 < static bool updt_box[17][17];                                           // Flag for Update
141 < static int nr_boxes;
142 < static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
143 < static int sm_no_boxes[] = {1,8,32,64,128,300};
144 <
145 < // Variables for XF86 DGA mode
146 < static int current_dga_cmap;                                            // Number (0 or 1) of currently installed DGA colormap
147 < static Window suspend_win;                                                      // "Suspend" window
148 < static void *fb_save = NULL;                                            // Saved frame buffer for suspend
164 > // Mutex to protect frame buffer
165   #ifdef HAVE_PTHREADS
166 < static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;   // Mutex to protect frame buffer
166 > static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
167   #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
168   #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
169   #else
# Line 155 | Line 171 | static pthread_mutex_t frame_buffer_lock
171   #define UNLOCK_FRAME_BUFFER
172   #endif
173  
174 < // Variables for fbdev DGA mode
175 < const char FBDEVICE_FILE_NAME[] = "/dev/fb";
176 < static int fbdev_fd;
177 <
178 < #ifdef ENABLE_XF86_VIDMODE
163 < // Variables for XF86 VidMode support
164 < static XF86VidModeModeInfo **x_video_modes;                     // Array of all available modes
165 < static int num_x_video_modes;
166 < #endif
167 <
168 < #ifdef ENABLE_VOSF
169 < static bool use_vosf = true;                                            // Flag: VOSF enabled
170 < #else
171 < static const bool use_vosf = false;                                     // Flag: VOSF enabled
172 < #endif
174 > // Variables for non-VOSF incremental refresh
175 > static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
176 > static int sm_no_boxes[] = {1,8,32,64,128,300};
177 > static bool updt_box[17][17];
178 > static int nr_boxes;
179  
180 < // VideoRefresh function
180 > // Video refresh function
181   static void VideoRefreshInit(void);
182   static void (*video_refresh)(void);
183  
184 +
185   // Prototypes
186   static void *redraw_func(void *arg);
187   static int event2keycode(XKeyEvent &ev);
# Line 187 | Line 194 | extern Display *x_display;
194   extern void SysMountFirstFloppy(void);
195  
196  
197 + /*
198 + *  Utility functions
199 + */
200 +
201 + // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
202 + static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
203 + {
204 +        return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
205 + }
206 +
207 + // Do we have a visual for handling the specified Mac depth? If so, set the
208 + // global variables "xdepth", "visualInfo", "vis" and "color_class".
209 + static bool find_visual_for_depth(video_depth depth)
210 + {
211 +        D(bug("have_visual_for_depth(%d)\n", 1 << depth));
212 +
213 +        // Calculate minimum and maximum supported X depth
214 +        int min_depth = 1, max_depth = 32;
215 +        switch (depth) {
216 +                case VDEPTH_1BIT:       // 1-bit works always and uses default visual
217 +                        min_depth = max_depth = DefaultDepth(x_display, screen);
218 +                        break;
219   #ifdef ENABLE_VOSF
220 < # include "video_vosf.h"
220 >                case VDEPTH_2BIT:
221 >                case VDEPTH_4BIT:       // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
222 >                case VDEPTH_8BIT:
223 >                        min_depth = 8;
224 >                        max_depth = 32;
225 >                        break;
226 > #else
227 >                case VDEPTH_2BIT:
228 >                case VDEPTH_4BIT:       // 2/4-bit requires VOSF blitters
229 >                        return false;
230 >                case VDEPTH_8BIT:       // 8-bit without VOSF requires an 8-bit visual
231 >                        min_depth = 8;
232 >                        max_depth = 8;
233 >                        break;
234   #endif
235 +                case VDEPTH_16BIT:      // 16-bit requires a 15/16-bit visual
236 +                        min_depth = 15;
237 +                        max_depth = 16;
238 +                        break;
239 +                case VDEPTH_32BIT:      // 32-bit requires a 24/32-bit visual
240 +                        min_depth = 24;
241 +                        max_depth = 32;
242 +                        break;
243 +        }
244 +        D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
245  
246 +        // Try to find a visual for one of the color depths
247 +        bool visual_found = false;
248 +        for (int i=0; i<num_depths && !visual_found; i++) {
249 +
250 +                xdepth = avail_depths[i];
251 +                D(bug(" trying to find visual for depth %d\n", xdepth));
252 +                if (xdepth < min_depth || xdepth > max_depth)
253 +                        continue;
254  
255 < /*
256 < *  Initialization
257 < */
255 >                // Determine best color class for this depth
256 >                switch (xdepth) {
257 >                        case 1: // Try StaticGray or StaticColor
258 >                                if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
259 >                                 || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
260 >                                        visual_found = true;
261 >                                break;
262 >                        case 8: // Need PseudoColor
263 >                                if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
264 >                                        visual_found = true;
265 >                                break;
266 >                        case 15:
267 >                        case 16:
268 >                        case 24:
269 >                        case 32: // Try DirectColor first, as this will allow gamma correction
270 >                                if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
271 >                                 || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
272 >                                        visual_found = true;
273 >                                break;
274 >                        default:
275 >                                D(bug("  not a supported depth\n"));
276 >                                break;
277 >                }
278 >        }
279 >        if (!visual_found)
280 >                return false;
281 >
282 >        // Visual was found
283 >        vis = visualInfo.visual;
284 >        color_class = visualInfo.c_class;
285 >        D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
286 > #if DEBUG
287 >        switch (color_class) {
288 >                case StaticGray: D(bug("StaticGray\n")); break;
289 >                case GrayScale: D(bug("GrayScale\n")); break;
290 >                case StaticColor: D(bug("StaticColor\n")); break;
291 >                case PseudoColor: D(bug("PseudoColor\n")); break;
292 >                case TrueColor: D(bug("TrueColor\n")); break;
293 >                case DirectColor: D(bug("DirectColor\n")); break;
294 >        }
295 > #endif
296 >        return true;
297 > }
298  
299   // Add mode to list of supported modes
300   static void add_mode(uint32 width, uint32 height, uint32 resolution_id, uint32 bytes_per_row, video_depth depth)
# Line 208 | Line 308 | static void add_mode(uint32 width, uint3
308          VideoModes.push_back(mode);
309   }
310  
311 + // Add standard list of windowed modes for given color depth
312 + static void add_window_modes(video_depth depth)
313 + {
314 +        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth), depth);
315 +        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth), depth);
316 +        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth), depth);
317 +        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, depth), depth);
318 +        add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, depth), depth);
319 +        add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, depth), depth);
320 +        add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, depth), depth);
321 + }
322 +
323   // Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac)
324   static void set_mac_frame_buffer(video_depth depth, bool native_byte_order)
325   {
# Line 216 | Line 328 | static void set_mac_frame_buffer(video_d
328          if (depth == VDEPTH_16BIT)
329                  layout = (xdepth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565;
330          else if (depth == VDEPTH_32BIT)
331 <                layour = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
331 >                layout = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
332          if (native_byte_order)
333                  MacFrameLayout = layout;
334          else
335                  MacFrameLayout = FLAYOUT_DIRECT;
336          VideoMonitor.mac_frame_base = MacFrameBaseMac;
337 +
338 +        // Set variables used by UAE memory banking
339 +        MacFrameBaseHost = the_buffer;
340 +        MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y;
341 +        InitFrameBufferMapping();
342   #else
343          VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
227        D(bug("Host frame buffer = %p, ", the_buffer));
344   #endif
345          D(bug("VideoMonitor.mac_frame_base = %08x\n", VideoMonitor.mac_frame_base));
346   }
# Line 260 | Line 376 | static void set_window_focus(Window w)
376   }
377  
378   // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
379 + static Atom WM_DELETE_WINDOW = (Atom)0;
380   static void set_window_delete_protocol(Window w)
381   {
382          WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
# Line 296 | Line 413 | static int error_handler(Display *d, XEr
413                  return old_error_handler(d, e);
414   }
415  
416 < // Init window mode
417 < static bool init_window(const video_mode &mode)
416 >
417 > /*
418 > *  Display "driver" classes
419 > */
420 >
421 > class driver_base {
422 > public:
423 >        driver_base();
424 >        virtual ~driver_base();
425 >
426 >        virtual void update_palette(void);
427 >        virtual void suspend(void) {}
428 >        virtual void resume(void) {}
429 >        virtual void toggle_mouse_grab(void) {}
430 >        virtual void mouse_moved(int x, int y) { ADBMouseMoved(x, y); }
431 >
432 >        void disable_mouse_accel(void);
433 >        void restore_mouse_accel(void);
434 >
435 >        virtual void grab_mouse(void) {}
436 >        virtual void ungrab_mouse(void) {}
437 >
438 > public:
439 >        bool init_ok;   // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer)
440 >        Window w;               // The window we draw into
441 >
442 >        int orig_accel_numer, orig_accel_denom, orig_threshold; // Original mouse acceleration
443 > };
444 >
445 > class driver_window;
446 > static void update_display_window_vosf(driver_window *drv);
447 > static void update_display_dynamic(int ticker, driver_window *drv);
448 > static void update_display_static(driver_window *drv);
449 >
450 > class driver_window : public driver_base {
451 >        friend void update_display_window_vosf(driver_window *drv);
452 >        friend void update_display_dynamic(int ticker, driver_window *drv);
453 >        friend void update_display_static(driver_window *drv);
454 >
455 > public:
456 >        driver_window(const video_mode &mode);
457 >        ~driver_window();
458 >
459 >        void toggle_mouse_grab(void);
460 >        void mouse_moved(int x, int y);
461 >
462 >        void grab_mouse(void);
463 >        void ungrab_mouse(void);
464 >
465 > private:
466 >        GC gc;
467 >        XImage *img;
468 >        bool have_shm;                                  // Flag: SHM extensions available
469 >        XShmSegmentInfo shminfo;
470 >        Cursor mac_cursor;
471 >        bool mouse_grabbed;                             // Flag: mouse pointer grabbed, using relative mouse mode
472 >        int mouse_last_x, mouse_last_y; // Last mouse position (for relative mode)
473 > };
474 >
475 > static driver_base *drv = NULL; // Pointer to currently used driver object
476 >
477 > #ifdef ENABLE_VOSF
478 > # include "video_vosf.h"
479 > #endif
480 >
481 > driver_base::driver_base()
482 > : init_ok(false), w(0)
483 > {
484 >        the_buffer = NULL;
485 >        the_buffer_copy = NULL;
486 >        XGetPointerControl(x_display, &orig_accel_numer, &orig_accel_denom, &orig_threshold);
487 > }
488 >
489 > driver_base::~driver_base()
490 > {
491 >        ungrab_mouse();
492 >        restore_mouse_accel();
493 >
494 >        if (w) {
495 >                XUnmapWindow(x_display, w);
496 >                wait_unmapped(w);
497 >                XDestroyWindow(x_display, w);
498 >        }
499 >
500 >        XFlush(x_display);
501 >        XSync(x_display, false);
502 >
503 >        // Free frame buffer(s)
504 >        if (!use_vosf) {
505 >                if (the_buffer) {
506 >                        free(the_buffer);
507 >                        the_buffer = NULL;
508 >                }
509 >                if (the_buffer_copy) {
510 >                        free(the_buffer_copy);
511 >                        the_buffer_copy = NULL;
512 >                }
513 >        }
514 > #ifdef ENABLE_VOSF
515 >        else {
516 >                if (the_host_buffer) {
517 >                        free(the_host_buffer);
518 >                        the_host_buffer = NULL;
519 >                }
520 >                if (the_buffer) {
521 >                        free(the_buffer);
522 >                        the_buffer = NULL;
523 >                }
524 >                if (the_buffer_copy) {
525 >                        free(the_buffer_copy);
526 >                        the_buffer_copy = NULL;
527 >                }
528 >        }
529 > #endif
530 > }
531 >
532 > // Palette has changed
533 > void driver_base::update_palette(void)
534 > {
535 >        if (color_class == PseudoColor || color_class == DirectColor) {
536 >                int num = vis->map_entries;
537 >                if (!IsDirectMode(VideoMonitor.mode) && color_class == DirectColor)
538 >                        return; // Indexed mode on true color screen, don't set CLUT
539 >                XStoreColors(x_display, cmap[0], palette, num);
540 >                XStoreColors(x_display, cmap[1], palette, num);
541 >        }
542 >        XSync(x_display, false);
543 > }
544 >
545 > // Disable mouse acceleration
546 > void driver_base::disable_mouse_accel(void)
547 > {
548 >        XChangePointerControl(x_display, True, False, 1, 1, 0);
549 > }
550 >
551 > // Restore mouse acceleration to original value
552 > void driver_base::restore_mouse_accel(void)
553 > {
554 >        XChangePointerControl(x_display, True, True, orig_accel_numer, orig_accel_denom, orig_threshold);
555 > }
556 >
557 >
558 > /*
559 > *  Windowed display driver
560 > */
561 >
562 > // Open display
563 > driver_window::driver_window(const video_mode &mode)
564 > : gc(0), img(NULL), have_shm(false), mouse_grabbed(false), mac_cursor(0)
565   {
566          int width = mode.x, height = mode.y;
567          int aligned_width = (width + 15) & ~15;
568          int aligned_height = (height + 15) & ~15;
569  
570          // Set absolute mouse mode
571 <        ADBSetRelMouseMode(false);
308 <
309 <        // Read frame skip prefs
310 <        frame_skip = PrefsFindInt32("frameskip");
571 >        ADBSetRelMouseMode(mouse_grabbed);
572  
573 <        // Create window
573 >        // Create window (setting backround_pixel, border_pixel and colormap is
574 >        // mandatory when using a non-default visual; in 1-bit mode we use the
575 >        // default visual, so we can also use the default colormap)
576          XSetWindowAttributes wattr;
577          wattr.event_mask = eventmask = win_eventmask;
578 <        wattr.background_pixel = black_pixel;
579 <        wattr.colormap = cmap[0];
580 <
581 <        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
582 <                InputOutput, vis, CWEventMask | CWBackPixel | ((IsDirectMode(mode) || mode.depth == VDEPTH_1BIT) ? 0 : CWColormap), &wattr);
578 >        wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
579 >        wattr.border_pixel = 0;
580 >        wattr.colormap = (mode.depth == VDEPTH_1BIT ? DefaultColormap(x_display, screen) : cmap[0]);
581 >        w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
582 >                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWColormap, &wattr);
583  
584          // Set window name/class
585 <        set_window_name(the_win, STR_WINDOW_TITLE);
585 >        set_window_name(w, STR_WINDOW_TITLE);
586  
587          // Indicate that we want keyboard input
588 <        set_window_focus(the_win);
588 >        set_window_focus(w);
589  
590          // Set delete protocol property
591 <        set_window_delete_protocol(the_win);
591 >        set_window_delete_protocol(w);
592  
593          // Make window unresizable
594          {
# Line 336 | Line 599 | static bool init_window(const video_mode
599                          hints->min_height = height;
600                          hints->max_height = height;
601                          hints->flags = PMinSize | PMaxSize;
602 <                        XSetWMNormalHints(x_display, the_win, hints);
602 >                        XSetWMNormalHints(x_display, w, hints);
603                          XFree(hints);
604                  }
605          }
606          
607          // Show window
608 <        XMapWindow(x_display, the_win);
609 <        wait_mapped(the_win);
608 >        XMapWindow(x_display, w);
609 >        wait_mapped(w);
610 >
611 >        // 1-bit mode is big-endian; if the X server is little-endian, we can't
612 >        // use SHM because that doesn't allow changing the image byte order
613 >        bool need_msb_image = (mode.depth == VDEPTH_1BIT && XImageByteOrder(x_display) == LSBFirst);
614  
615          // Try to create and attach SHM image
616 <        have_shm = false;
350 <        if (mode.depth != VDEPTH_1BIT && local_X11 && XShmQueryExtension(x_display)) {
616 >        if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
617  
618                  // Create SHM image ("height + 2" for safety)
619                  img = XShmCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
# Line 365 | Line 631 | static bool init_window(const video_mode
631                  if (shm_error) {
632                          shmdt(shminfo.shmaddr);
633                          XDestroyImage(img);
634 +                        img = NULL;
635                          shminfo.shmid = -1;
636                  } else {
637                          have_shm = true;
# Line 374 | Line 641 | static bool init_window(const video_mode
641          
642          // Create normal X image if SHM doesn't work ("height + 2" for safety)
643          if (!have_shm) {
644 <                int bytes_per_row = TrivialBytesPerRow(aligned_width, mode.depth);
644 >                int bytes_per_row = (mode.depth == VDEPTH_1BIT ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth)));
645                  the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
646                  img = XCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
647          }
648  
649 <        // 1-Bit mode is big-endian
383 <        if (mode.depth == VDEPTH_1BIT) {
649 >        if (need_msb_image) {
650                  img->byte_order = MSBFirst;
651                  img->bitmap_bit_order = MSBFirst;
652          }
653  
654   #ifdef ENABLE_VOSF
655 +        use_vosf = true;
656          // Allocate memory for frame buffer (SIZE is extended to page-boundary)
657          the_host_buffer = the_buffer_copy;
658          the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line);
659          the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
660          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
661 +        D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
662   #else
663          // Allocate memory for frame buffer
664          the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
665 +        D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
666   #endif
667  
668          // Create GC
669 <        the_gc = XCreateGC(x_display, the_win, 0, 0);
670 <        XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
669 >        gc = XCreateGC(x_display, w, 0, 0);
670 >        XSetState(x_display, gc, black_pixel, white_pixel, GXcopy, AllPlanes);
671  
672          // Create no_cursor
673          mac_cursor = XCreatePixmapCursor(x_display,
674 <           XCreatePixmap(x_display, the_win, 1, 1, 1),
675 <           XCreatePixmap(x_display, the_win, 1, 1, 1),
674 >           XCreatePixmap(x_display, w, 1, 1, 1),
675 >           XCreatePixmap(x_display, w, 1, 1, 1),
676             &black, &white, 0, 0);
677 <        XDefineCursor(x_display, the_win, mac_cursor);
677 >        XDefineCursor(x_display, w, mac_cursor);
678  
679 <        // Add resolution and set VideoMonitor
679 >        // Init blitting routines
680          bool native_byte_order;
681   #ifdef WORDS_BIGENDIAN
682          native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
# Line 415 | Line 684 | static bool init_window(const video_mode
684          native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
685   #endif
686   #ifdef ENABLE_VOSF
687 <        Screen_blitter_init(&visualInfo, native_byte_order);
687 >        Screen_blitter_init(&visualInfo, native_byte_order, mode.depth);
688   #endif
689 +
690 +        // Set VideoMonitor
691          VideoMonitor.mode = mode;
692          set_mac_frame_buffer(mode.depth, native_byte_order);
693 <        return true;
693 >
694 >        // Everything went well
695 >        init_ok = true;
696   }
697  
698 < // Init fbdev DGA display
699 < static bool init_fbdev_dga(const video_mode &mode)
698 > // Close display
699 > driver_window::~driver_window()
700 > {
701 >        if (have_shm) {
702 >                XShmDetach(x_display, &shminfo);
703 > #ifdef ENABLE_VOSF
704 >                the_host_buffer = NULL; // don't free() in driver_base dtor
705 > #else
706 >                the_buffer_copy = NULL; // don't free() in driver_base dtor
707 > #endif
708 >        }
709 > #ifdef ENABLE_VOSF
710 >        if (use_vosf) {
711 >                // don't free() memory mapped buffers in driver_base dtor
712 >                if (the_buffer != VM_MAP_FAILED) {
713 >                        vm_release(the_buffer, the_buffer_size);
714 >                        the_buffer = NULL;
715 >                }
716 >                if (the_buffer_copy != VM_MAP_FAILED) {
717 >                        vm_release(the_buffer_copy, the_buffer_size);
718 >                        the_buffer_copy = NULL;
719 >                }
720 >        }
721 > #endif
722 >        if (img)
723 >                XDestroyImage(img);
724 >        if (have_shm) {
725 >                shmdt(shminfo.shmaddr);
726 >                shmctl(shminfo.shmid, IPC_RMID, 0);
727 >        }
728 >        if (gc)
729 >                XFreeGC(x_display, gc);
730 > }
731 >
732 > // Toggle mouse grab
733 > void driver_window::toggle_mouse_grab(void)
734   {
735 +        if (mouse_grabbed)
736 +                ungrab_mouse();
737 +        else
738 +                grab_mouse();
739 + }
740 +
741 + // Grab mouse, switch to relative mouse mode
742 + void driver_window::grab_mouse(void)
743 + {
744 +        int result;
745 +        for (int i=0; i<10; i++) {
746 +                result = XGrabPointer(x_display, w, True, 0,
747 +                        GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
748 +                if (result != AlreadyGrabbed)
749 +                        break;
750 +                Delay_usec(100000);
751 +        }
752 +        if (result == GrabSuccess) {
753 +                XStoreName(x_display, w, GetString(STR_WINDOW_TITLE_GRABBED));
754 +                ADBSetRelMouseMode(mouse_grabbed = true);
755 +                disable_mouse_accel();
756 +        }
757 + }
758 +
759 + // Ungrab mouse, switch to absolute mouse mode
760 + void driver_window::ungrab_mouse(void)
761 + {
762 +        if (mouse_grabbed) {
763 +                XUngrabPointer(x_display, CurrentTime);
764 +                XStoreName(x_display, w, GetString(STR_WINDOW_TITLE));
765 +                ADBSetRelMouseMode(mouse_grabbed = false);
766 +                restore_mouse_accel();
767 +        }
768 + }
769 +
770 + // Mouse moved
771 + void driver_window::mouse_moved(int x, int y)
772 + {
773 +        if (!mouse_grabbed) {
774 +                mouse_last_x = x; mouse_last_y = y;
775 +                ADBMouseMoved(x, y);
776 +                return;
777 +        }
778 +
779 +        // Warped mouse motion (this code is taken from SDL)
780 +
781 +        // Post first mouse event
782 +        int width = VideoMonitor.mode.x, height = VideoMonitor.mode.y;
783 +        int delta_x = x - mouse_last_x, delta_y = y - mouse_last_y;
784 +        mouse_last_x = x; mouse_last_y = y;
785 +        ADBMouseMoved(delta_x, delta_y);
786 +
787 +        // Only warp the pointer when it has reached the edge
788 +        const int MOUSE_FUDGE_FACTOR = 8;
789 +        if (x < MOUSE_FUDGE_FACTOR || x > (width - MOUSE_FUDGE_FACTOR)
790 +         || y < MOUSE_FUDGE_FACTOR || y > (height - MOUSE_FUDGE_FACTOR)) {
791 +                XEvent event;
792 +                while (XCheckTypedEvent(x_display, MotionNotify, &event)) {
793 +                        delta_x = x - mouse_last_x; delta_y = y - mouse_last_y;
794 +                        mouse_last_x = x; mouse_last_y = y;
795 +                        ADBMouseMoved(delta_x, delta_y);
796 +                }
797 +                mouse_last_x = width/2;
798 +                mouse_last_y = height/2;
799 +                XWarpPointer(x_display, None, w, 0, 0, 0, 0, mouse_last_x, mouse_last_y);
800 +                for (int i=0; i<10; i++) {
801 +                        XMaskEvent(x_display, PointerMotionMask, &event);
802 +                        if (event.xmotion.x > (mouse_last_x - MOUSE_FUDGE_FACTOR)
803 +                         && event.xmotion.x < (mouse_last_x + MOUSE_FUDGE_FACTOR)
804 +                         && event.xmotion.y > (mouse_last_y - MOUSE_FUDGE_FACTOR)
805 +                         && event.xmotion.y < (mouse_last_y + MOUSE_FUDGE_FACTOR))
806 +                                break;
807 +                }
808 +        }
809 + }
810 +
811 +
812 + #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
813 + /*
814 + *  DGA display driver base class
815 + */
816 +
817 + class driver_dga : public driver_base {
818 + public:
819 +        driver_dga();
820 +        ~driver_dga();
821 +
822 +        void suspend(void);
823 +        void resume(void);
824 +
825 + private:
826 +        Window suspend_win;             // "Suspend" information window
827 +        void *fb_save;                  // Saved frame buffer for suspend/resume
828 + };
829 +
830 + driver_dga::driver_dga()
831 + : suspend_win(0), fb_save(NULL)
832 + {
833 + }
834 +
835 + driver_dga::~driver_dga()
836 + {
837 +        XUngrabPointer(x_display, CurrentTime);
838 +        XUngrabKeyboard(x_display, CurrentTime);
839 + }
840 +
841 + // Suspend emulation
842 + void driver_dga::suspend(void)
843 + {
844 +        // Release ctrl key
845 +        ADBKeyUp(0x36);
846 +        ctrl_down = false;
847 +
848 +        // Lock frame buffer (this will stop the MacOS thread)
849 +        LOCK_FRAME_BUFFER;
850 +
851 +        // Save frame buffer
852 +        fb_save = malloc(VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
853 +        if (fb_save)
854 +                memcpy(fb_save, the_buffer, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
855 +
856 +        // Close full screen display
857 + #ifdef ENABLE_XF86_DGA
858 +        XF86DGADirectVideo(x_display, screen, 0);
859 + #endif
860 +        XUngrabPointer(x_display, CurrentTime);
861 +        XUngrabKeyboard(x_display, CurrentTime);
862 +        restore_mouse_accel();
863 +        XUnmapWindow(x_display, w);
864 +        wait_unmapped(w);
865 +
866 +        // Open "suspend" window
867 +        XSetWindowAttributes wattr;
868 +        wattr.event_mask = KeyPressMask;
869 +        wattr.background_pixel = black_pixel;
870 +                
871 +        suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
872 +                InputOutput, vis, CWEventMask | CWBackPixel, &wattr);
873 +        set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
874 +        set_window_focus(suspend_win);
875 +        XMapWindow(x_display, suspend_win);
876 +        emul_suspended = true;
877 + }
878 +
879 + // Resume emulation
880 + void driver_dga::resume(void)
881 + {
882 +        // Close "suspend" window
883 +        XDestroyWindow(x_display, suspend_win);
884 +        XSync(x_display, false);
885 +
886 +        // Reopen full screen display
887 +        XMapRaised(x_display, w);
888 +        wait_mapped(w);
889 +        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
890 +        XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
891 +        XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
892 +        disable_mouse_accel();
893 + #ifdef ENABLE_XF86_DGA
894 +        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
895 +        XF86DGASetViewPort(x_display, screen, 0, 0);
896 + #endif
897 +        XSync(x_display, false);
898 +        
899 +        // the_buffer already contains the data to restore. i.e. since a temporary
900 +        // frame buffer is used when VOSF is actually used, fb_save is therefore
901 +        // not necessary.
902 + #ifdef ENABLE_VOSF
903 +        if (use_vosf) {
904 +                LOCK_VOSF;
905 +                PFLAG_SET_ALL;
906 +                UNLOCK_VOSF;
907 +                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
908 +        }
909 + #endif
910 +        
911 +        // Restore frame buffer
912 +        if (fb_save) {
913 + #ifdef ENABLE_VOSF
914 +                // Don't copy fb_save to the temporary frame buffer in VOSF mode
915 +                if (!use_vosf)
916 + #endif
917 +                memcpy(the_buffer, fb_save, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
918 +                free(fb_save);
919 +                fb_save = NULL;
920 +        }
921 +        
922 +        // Unlock frame buffer (and continue MacOS thread)
923 +        UNLOCK_FRAME_BUFFER;
924 +        emul_suspended = false;
925 + }
926 + #endif
927 +
928 +
929   #ifdef ENABLE_FBDEV_DGA
930 + /*
931 + *  fbdev DGA display driver
932 + */
933 +
934 + const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
935 + const char FBDEVICE_FILE_NAME[] = "/dev/fb";
936 +
937 + class driver_fbdev : public driver_dga {
938 + public:
939 +        driver_fbdev(const video_mode &mode);
940 +        ~driver_fbdev();
941 + };
942 +
943 + // Open display
944 + driver_fbdev::driver_fbdev(const video_mode &mode)
945 + {
946          int width = mode.x, height = mode.y;
947  
948 +        // Set absolute mouse mode
949 +        ADBSetRelMouseMode(false);
950 +        
951          // Find the maximum depth available
952          int ndepths, max_depth(0);
953          int *depths = XListDepths(x_display, screen, &ndepths);
954          if (depths == NULL) {
955                  printf("FATAL: Could not determine the maximal depth available\n");
956 <                return false;
956 >                return;
957          } else {
958                  while (ndepths-- > 0) {
959                          if (depths[ndepths] > max_depth)
# Line 450 | Line 970 | static bool init_fbdev_dga(const video_m
970                  char str[256];
971                  sprintf(str, GetString(STR_NO_FBDEVICE_FILE_ERR), fbd_path ? fbd_path : FBDEVICES_FILE_NAME, strerror(errno));
972                  ErrorAlert(str);
973 <                return false;
973 >                return;
974          }
975          
976          int fb_depth;           // supported depth
# Line 470 | Line 990 | static bool init_fbdev_dga(const video_m
990                          continue;
991                  
992                  if ((sscanf(line, "%19s %d %x", &fb_name, &fb_depth, &fb_offset) == 3)
993 <                && (strcmp(fb_name, fb_name) == 0) && (fb_depth == max_depth)) {
993 >                 && (strcmp(fb_name, fb_name) == 0) && (fb_depth == max_depth)) {
994                          device_found = true;
995                          break;
996                  }
# Line 484 | Line 1004 | static bool init_fbdev_dga(const video_m
1004                  char str[256];
1005                  sprintf(str, GetString(STR_FBDEV_NAME_ERR), fb_name, max_depth);
1006                  ErrorAlert(str);
1007 <                return false;
1007 >                return;
1008          }
1009          
490        depth = fb_depth;
491        
492        // Set relative mouse mode
493        ADBSetRelMouseMode(false);
494        
1010          // Create window
1011          XSetWindowAttributes wattr;
1012          wattr.event_mask = eventmask = dga_eventmask;
# Line 499 | Line 1014 | static bool init_fbdev_dga(const video_m
1014          wattr.override_redirect = True;
1015          wattr.colormap = cmap[0];
1016          
1017 <        the_win = XCreateWindow(x_display, rootwin,
1017 >        w = XCreateWindow(x_display, rootwin,
1018                  0, 0, width, height,
1019                  0, xdepth, InputOutput, vis,
1020 <                CWEventMask | CWBackPixel | CWOverrideRedirect | (depth == 8 ? CWColormap : 0),
1020 >                CWEventMask | CWBackPixel | CWOverrideRedirect | (fb_depth <= 8 ? CWColormap : 0),
1021                  &wattr);
1022  
1023          // Set window name/class
1024 <        set_window_name(the_win, STR_WINDOW_TITLE);
1024 >        set_window_name(w, STR_WINDOW_TITLE);
1025  
1026          // Indicate that we want keyboard input
1027 <        set_window_focus(the_win);
1027 >        set_window_focus(w);
1028  
1029          // Show window
1030 <        XMapRaised(x_display, the_win);
1031 <        wait_mapped(the_win);
1030 >        XMapRaised(x_display, w);
1031 >        wait_mapped(w);
1032          
1033          // Grab mouse and keyboard
1034 <        XGrabKeyboard(x_display, the_win, True,
1034 >        XGrabKeyboard(x_display, w, True,
1035                  GrabModeAsync, GrabModeAsync, CurrentTime);
1036 <        XGrabPointer(x_display, the_win, True,
1036 >        XGrabPointer(x_display, w, True,
1037                  PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
1038 <                GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime);
1038 >                GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
1039 >        disable_mouse_accel();
1040          
1041          // Calculate bytes per row
1042          int bytes_per_row = TrivialBytesPerRow(mode.x, mode.depth);
1043          
1044          // Map frame buffer
1045 <        if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
1046 <                if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1045 >        the_buffer_size = height * bytes_per_row;
1046 >        if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
1047 >                if ((the_buffer = (uint8 *) mmap(NULL, the_buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
1048                          char str[256];
1049                          sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno));
1050                          ErrorAlert(str);
1051 <                        return false;
1051 >                        return;
1052                  }
1053          }
1054          
# Line 539 | Line 1056 | static bool init_fbdev_dga(const video_m
1056   #if REAL_ADDRESSING || DIRECT_ADDRESSING
1057          // Screen_blitter_init() returns TRUE if VOSF is mandatory
1058          // i.e. the framebuffer update function is not Blit_Copy_Raw
1059 <        use_vosf = Screen_blitter_init(&visualInfo, true);
1059 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
1060          
1061          if (use_vosf) {
1062            // Allocate memory for frame buffer (SIZE is extended to page-boundary)
# Line 554 | Line 1071 | static bool init_fbdev_dga(const video_m
1071   #endif
1072          
1073          // Set VideoMonitor
1074 +        VideoModes[0].bytes_per_row = bytes_per_row;
1075 +        VideoModes[0].depth = DepthModeForPixelDepth(fb_depth);
1076          VideoMonitor.mode = mode;
1077          set_mac_frame_buffer(mode.depth, true);
1078 <        return true;
1079 < #else
1080 <        ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled.");
1081 <        return false;
1078 >
1079 >        // Everything went well
1080 >        init_ok = true;
1081 > }
1082 >
1083 > // Close display
1084 > driver_fbdev::~driver_fbdev()
1085 > {
1086 >        if (!use_vosf) {
1087 >                if (the_buffer != MAP_FAILED) {
1088 >                        // don't free() the screen buffer in driver_base dtor
1089 >                        munmap(the_buffer, the_buffer_size);
1090 >                        the_buffer = NULL;
1091 >                }
1092 >        }
1093 > #ifdef ENABLE_VOSF
1094 >        else {
1095 >                if (the_host_buffer != MAP_FAILED) {
1096 >                        // don't free() the screen buffer in driver_base dtor
1097 >                        munmap(the_host_buffer, the_buffer_size);
1098 >                        the_host_buffer = NULL;
1099 >                }
1100 >                if (the_buffer_copy != VM_MAP_FAILED) {
1101 >                        vm_release(the_buffer_copy, the_buffer_size);
1102 >                        the_buffer_copy = NULL;
1103 >                }
1104 >                if (the_buffer != VM_MAP_FAILED) {
1105 >                        vm_release(the_buffer, the_buffer_size);
1106 >                        the_buffer = NULL;
1107 >                }
1108 >        }
1109   #endif
1110   }
1111 + #endif
1112 +
1113 +
1114 + #ifdef ENABLE_XF86_DGA
1115 + /*
1116 + *  XFree86 DGA display driver
1117 + */
1118 +
1119 + class driver_xf86dga : public driver_dga {
1120 + public:
1121 +        driver_xf86dga(const video_mode &mode);
1122 +        ~driver_xf86dga();
1123 +
1124 +        void update_palette(void);
1125 +        void resume(void);
1126 +
1127 + private:
1128 +        int current_dga_cmap;                                   // Number (0 or 1) of currently installed DGA colormap
1129 + };
1130  
1131 < // Init XF86 DGA display
1132 < static bool init_xf86_dga(const video_mode &mode)
1131 > // Open display
1132 > driver_xf86dga::driver_xf86dga(const video_mode &mode)
1133 > : current_dga_cmap(0)
1134   {
1135          int width = mode.x, height = mode.y;
1136  
571 #ifdef ENABLE_XF86_DGA
1137          // Set relative mouse mode
1138          ADBSetRelMouseMode(true);
1139  
# Line 593 | Line 1158 | static bool init_xf86_dga(const video_mo
1158          wattr.event_mask = eventmask = dga_eventmask;
1159          wattr.override_redirect = True;
1160  
1161 <        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
1161 >        w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
1162                  InputOutput, vis, CWEventMask | CWOverrideRedirect, &wattr);
1163  
1164          // Set window name/class
1165 <        set_window_name(the_win, STR_WINDOW_TITLE);
1165 >        set_window_name(w, STR_WINDOW_TITLE);
1166  
1167          // Indicate that we want keyboard input
1168 <        set_window_focus(the_win);
1168 >        set_window_focus(w);
1169  
1170          // Show window
1171 <        XMapRaised(x_display, the_win);
1172 <        wait_mapped(the_win);
1171 >        XMapRaised(x_display, w);
1172 >        wait_mapped(w);
1173  
1174          // Establish direct screen connection
1175 <        XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
1175 >        XMoveResizeWindow(x_display, w, 0, 0, width, height);
1176          XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1177          XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
1178          XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1179 +        disable_mouse_accel();
1180  
1181          int v_width, v_bank, v_size;
1182          XF86DGAGetVideo(x_display, screen, (char **)&the_buffer, &v_width, &v_bank, &v_size);
# Line 620 | Line 1186 | static bool init_xf86_dga(const video_mo
1186  
1187          // Set colormap
1188          if (!IsDirectMode(mode)) {
1189 <                XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
1189 >                XSetWindowColormap(x_display, w, cmap[current_dga_cmap = 0]);
1190                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1191          }
1192          XSync(x_display, false);
1193  
1194 <        // Set VideoMonitor
1194 >        // Init blitting routines
1195          int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, mode.depth);
1196 <
631 < #ifdef VIDEO_VOSF
1196 > #if VIDEO_VOSF
1197   #if REAL_ADDRESSING || DIRECT_ADDRESSING
1198          // Screen_blitter_init() returns TRUE if VOSF is mandatory
1199          // i.e. the framebuffer update function is not Blit_Copy_Raw
1200 <        use_vosf = Screen_blitter_init(&visualInfo, true);
1200 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
1201          
1202          if (use_vosf) {
1203            // Allocate memory for frame buffer (SIZE is extended to page-boundary)
# Line 646 | Line 1211 | static bool init_xf86_dga(const video_mo
1211   #endif
1212   #endif
1213          
1214 +        // Set VideoMonitor
1215          const_cast<video_mode *>(&mode)->bytes_per_row = bytes_per_row;
1216          VideoMonitor.mode = mode;
1217          set_mac_frame_buffer(mode.depth, true);
1218 <        return true;
1219 < #else
1220 <        ErrorAlert("Basilisk II has been compiled with XF86 DGA support disabled.");
1221 <        return false;
1218 >
1219 >        // Everything went well
1220 >        init_ok = true;
1221 > }
1222 >
1223 > // Close display
1224 > driver_xf86dga::~driver_xf86dga()
1225 > {
1226 >        XF86DGADirectVideo(x_display, screen, 0);
1227 >        if (!use_vosf) {
1228 >                // don't free() the screen buffer in driver_base dtor
1229 >                the_buffer = NULL;
1230 >        }
1231 > #ifdef ENABLE_VOSF
1232 >        else {
1233 >                // don't free() the screen buffer in driver_base dtor
1234 >                the_host_buffer = NULL;
1235 >                
1236 >                if (the_buffer_copy != VM_MAP_FAILED) {
1237 >                        vm_release(the_buffer_copy, the_buffer_size);
1238 >                        the_buffer_copy = NULL;
1239 >                }
1240 >                if (the_buffer != VM_MAP_FAILED) {
1241 >                        vm_release(the_buffer, the_buffer_size);
1242 >                        the_buffer = NULL;
1243 >                }
1244 >        }
1245   #endif
1246 + #ifdef ENABLE_XF86_VIDMODE
1247 +        if (has_vidmode)
1248 +                XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1249 + #endif
1250 + }
1251 +
1252 + // Palette has changed
1253 + void driver_xf86dga::update_palette(void)
1254 + {
1255 +        driver_dga::update_palette();
1256 +        current_dga_cmap ^= 1;
1257 +        if (!IsDirectMode(VideoMonitor.mode) && cmap[current_dga_cmap])
1258 +                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1259   }
1260  
1261 + // Resume emulation
1262 + void driver_xf86dga::resume(void)
1263 + {
1264 +        driver_dga::resume();
1265 +        if (!IsDirectMode(VideoMonitor.mode))
1266 +                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1267 + }
1268 + #endif
1269 +
1270 +
1271 + /*
1272 + *  Initialization
1273 + */
1274 +
1275   // Init keycode translation table
1276   static void keycode_init(void)
1277   {
# Line 724 | Line 1340 | static void keycode_init(void)
1340   // Open display for specified mode
1341   static bool video_open(const video_mode &mode)
1342   {
1343 <        // Create color maps for 8 bit mode
1344 <        if (!IsDirectMode(mode)) {
1343 >        // Find best available X visual
1344 >        if (!find_visual_for_depth(mode.depth)) {
1345 >                ErrorAlert(STR_NO_XVISUAL_ERR);
1346 >                return false;
1347 >        }
1348 >
1349 >        // Create color maps
1350 >        if (color_class == PseudoColor || color_class == DirectColor) {
1351                  cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1352                  cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1353 <                cmap_allocated = true;
1354 <                XInstallColormap(x_display, cmap[0]);
1355 <                XInstallColormap(x_display, cmap[1]);
1353 >        } else {
1354 >                cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
1355 >                cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
1356 >        }
1357 >
1358 >        // Find pixel format of direct modes
1359 >        if (color_class == DirectColor || color_class == TrueColor) {
1360 >                rshift = gshift = bshift = 0;
1361 >                rloss = gloss = bloss = 8;
1362 >                uint32 mask;
1363 >                for (mask=vis->red_mask; !(mask&1); mask>>=1)
1364 >                        ++rshift;
1365 >                for (; mask&1; mask>>=1)
1366 >                        --rloss;
1367 >                for (mask=vis->green_mask; !(mask&1); mask>>=1)
1368 >                        ++gshift;
1369 >                for (; mask&1; mask>>=1)
1370 >                        --gloss;
1371 >                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
1372 >                        ++bshift;
1373 >                for (; mask&1; mask>>=1)
1374 >                        --bloss;
1375 >        }
1376 >
1377 >        // Preset palette pixel values for CLUT or gamma table
1378 >        if (color_class == DirectColor) {
1379 >                int num = vis->map_entries;
1380 >                for (int i=0; i<num; i++) {
1381 >                        int c = (i * 256) / num;
1382 >                        palette[i].pixel = map_rgb(c, c, c);
1383 >                        palette[i].flags = DoRed | DoGreen | DoBlue;
1384 >                }
1385 >        } else if (color_class == PseudoColor) {
1386 >                for (int i=0; i<256; i++) {
1387 >                        palette[i].pixel = i;
1388 >                        palette[i].flags = DoRed | DoGreen | DoBlue;
1389 >                }
1390          }
1391  
1392 <        // Initialize according to display type
1392 >        // Load gray ramp to color map
1393 >        int num = (color_class == DirectColor ? vis->map_entries : 256);
1394 >        for (int i=0; i<num; i++) {
1395 >                int c = (i * 256) / num;
1396 >                palette[i].red = c * 0x0101;
1397 >                palette[i].green = c * 0x0101;
1398 >                palette[i].blue = c * 0x0101;
1399 >        }
1400 >        if (color_class == PseudoColor || color_class == DirectColor) {
1401 >                XStoreColors(x_display, cmap[0], palette, num);
1402 >                XStoreColors(x_display, cmap[1], palette, num);
1403 >        }
1404 >
1405 > #ifdef ENABLE_VOSF
1406 >        // Load gray ramp to 8->16/32 expand map
1407 >        if (!IsDirectMode(mode) && xdepth > 8)
1408 >                for (int i=0; i<256; i++)
1409 >                        ExpandMap[i] = map_rgb(i, i, i);
1410 > #endif
1411 >
1412 >        // Create display driver object of requested type
1413          switch (display_type) {
1414                  case DISPLAY_WINDOW:
1415 <                        if (!init_window(mode))
740 <                                return false;
1415 >                        drv = new driver_window(mode);
1416                          break;
742                case DISPLAY_DGA:
1417   #ifdef ENABLE_FBDEV_DGA
1418 <                        if (!init_fbdev_dga(mode))
1419 < #else
1420 <                        if (!init_xf86_dga(mode))
1418 >                case DISPLAY_DGA:
1419 >                        drv = new driver_fbdev(mode);
1420 >                        break;
1421   #endif
1422 <                                return false;
1422 > #ifdef ENABLE_XF86_DGA
1423 >                case DISPLAY_DGA:
1424 >                        drv = new driver_xf86dga(mode);
1425                          break;
750        }
751
752        // Lock down frame buffer
753        LOCK_FRAME_BUFFER;
754
755 #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
756        // Set variables for UAE memory mapping
757        MacFrameBaseHost = the_buffer;
758        MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y;
759
760        // No special frame buffer in Classic mode (frame buffer is in Mac RAM)
761        if (classic)
762                MacFrameLayout = FLAYOUT_NONE;
1426   #endif
1427 <
1428 <        InitFrameBufferMapping();
1427 >        }
1428 >        if (drv == NULL)
1429 >                return false;
1430 >        if (!drv->init_ok) {
1431 >                delete drv;
1432 >                drv = NULL;
1433 >                return false;
1434 >        }
1435  
1436   #ifdef ENABLE_VOSF
1437          if (use_vosf) {
1438 <                // Initialize the mainBuffer structure
1439 <                if (!video_init_buffer()) {
1440 <                        ErrorAlert(GetString(STR_VOSF_INIT_ERR));
1438 >                // Initialize the VOSF system
1439 >                if (!video_vosf_init()) {
1440 >                        ErrorAlert(STR_VOSF_INIT_ERR);
1441                  return false;
1442                  }
774
775                // Initialize the handler for SIGSEGV
776                if (!sigsegv_install_handler(screen_fault_handler)) {
777                        ErrorAlert("Could not initialize Video on SEGV signals");
778                        return false;
779                }
1443          }
1444   #endif
1445          
1446          // Initialize VideoRefresh function
1447          VideoRefreshInit();
1448 <        
1448 >
1449 >        // Lock down frame buffer
1450          XSync(x_display, false);
1451 +        LOCK_FRAME_BUFFER;
1452  
788 #ifdef HAVE_PTHREADS
1453          // Start redraw/input thread
1454 + #ifdef HAVE_PTHREADS
1455          redraw_thread_cancel = false;
1456          redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1457          if (!redraw_thread_active) {
1458                  printf("FATAL: cannot create redraw thread\n");
1459                  return false;
1460          }
1461 + #else
1462 +        redraw_thread_active = true;
1463   #endif
1464  
1465          return true;
# Line 803 | Line 1470 | bool VideoInit(bool classic)
1470          classic_mode = classic;
1471  
1472   #ifdef ENABLE_VOSF
806        // Open /dev/zero
807        zero_fd = open("/dev/zero", O_RDWR);
808        if (zero_fd < 0) {
809        char str[256];
810                sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
811                ErrorAlert(str);
812        return false;
813        }
814        
1473          // Zero the mainBuffer structure
1474 <        mainBuffer.dirtyPages = 0;
1475 <        mainBuffer.pageInfo = 0;
1474 >        mainBuffer.dirtyPages = NULL;
1475 >        mainBuffer.pageInfo = NULL;
1476   #endif
1477          
1478          // Check if X server runs on local machine
# Line 825 | Line 1483 | bool VideoInit(bool classic)
1483          keycode_init();
1484  
1485          // Read prefs
1486 +        frame_skip = PrefsFindInt32("frameskip");
1487          mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1488          mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1489  
1490          // Find screen and root window
1491          screen = XDefaultScreen(x_display);
1492          rootwin = XRootWindow(x_display, screen);
1493 <        
1494 <        // Get screen depth
1495 <        xdepth = DefaultDepth(x_display, screen);
1493 >
1494 >        // Get sorted list of available depths
1495 >        avail_depths = XListDepths(x_display, screen, &num_depths);
1496 >        if (avail_depths == NULL) {
1497 >                ErrorAlert(STR_UNSUPP_DEPTH_ERR);
1498 >                return false;
1499 >        }
1500 >        sort(avail_depths, avail_depths + num_depths);
1501          
1502   #ifdef ENABLE_FBDEV_DGA
1503          // Frame buffer name
1504          char fb_name[20];
1505          
1506 <        // Could do fbdev dga ?
1506 >        // Could do fbdev DGA?
1507          if ((fbdev_fd = open(FBDEVICE_FILE_NAME, O_RDWR)) != -1)
1508                  has_dga = true;
1509          else
# Line 873 | Line 1537 | bool VideoInit(bool classic)
1537          black_pixel = BlackPixel(x_display, screen);
1538          white_pixel = WhitePixel(x_display, screen);
1539  
876        // Get appropriate visual
877        int color_class;
878        switch (xdepth) {
879                case 1:
880                        color_class = StaticGray;
881                        break;
882                case 8:
883                        color_class = PseudoColor;
884                        break;
885                case 15:
886                case 16:
887                case 24:
888                case 32:
889                        color_class = TrueColor;
890                        break;
891                default:
892                        ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
893                        return false;
894        }
895        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
896                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
897                return false;
898        }
899        if (visualInfo.depth != xdepth) {
900                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
901                return false;
902        }
903        vis = visualInfo.visual;
904
1540          // Get screen mode from preferences
1541          const char *mode_str;
1542          if (classic_mode)
# Line 918 | Line 1553 | bool VideoInit(bool classic)
1553   #ifdef ENABLE_FBDEV_DGA
1554                  } else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1555                          display_type = DISPLAY_DGA;
1556 <                        default_width = -1; default_height = -1;
1557 < #else
1556 >                        default_width = -1; default_height = -1; // use entire screen
1557 > #endif
1558 > #ifdef ENABLE_XF86_DGA
1559                  } else if (has_dga && sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2) {
1560                          display_type = DISPLAY_DGA;
1561   #endif
# Line 934 | Line 1570 | bool VideoInit(bool classic)
1570          else if (default_height > DisplayHeight(x_display, screen))
1571                  default_height = DisplayHeight(x_display, screen);
1572  
1573 <        // Mac screen depth is always 1 bit in Classic mode, but follows X depth otherwise
1574 <        int depth = (classic_mode ? 1 : xdepth);
1575 <        video_depth depth_mode = DepthModeForPixelDepth(depth);
1573 >        // Mac screen depth follows X depth
1574 >        video_depth default_depth = VDEPTH_1BIT;
1575 >        switch (DefaultDepth(x_display, screen)) {
1576 >                case 8:
1577 >                        default_depth = VDEPTH_8BIT;
1578 >                        break;
1579 >                case 15: case 16:
1580 >                        default_depth = VDEPTH_16BIT;
1581 >                        break;
1582 >                case 24: case 32:
1583 >                        default_depth = VDEPTH_32BIT;
1584 >                        break;
1585 >        }
1586  
1587          // Construct list of supported modes
1588          if (display_type == DISPLAY_WINDOW) {
1589                  if (classic)
1590 <                        add_mode(512, 342, 0x80, 64, depth_mode);
1590 >                        add_mode(512, 342, 0x80, 64, VDEPTH_1BIT);
1591                  else {
1592 <                        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, depth_mode), depth_mode);
1593 <                        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, depth_mode), depth_mode);
1594 <                        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, depth_mode), depth_mode);
1595 <                        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, depth_mode), depth_mode);
950 <                        add_mode(1280, 1024, 0x84, TrivialBytesPerRow(1280, depth_mode), depth_mode);
1592 >                        for (unsigned d=VDEPTH_1BIT; d<=VDEPTH_32BIT; d++) {
1593 >                                if (find_visual_for_depth(video_depth(d)))
1594 >                                        add_window_modes(video_depth(d));
1595 >                        }
1596                  }
1597          } else
1598 <                add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, depth_mode), depth_mode);
1598 >                add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, default_depth), default_depth);
1599 >        if (VideoModes.empty()) {
1600 >                ErrorAlert(STR_NO_XVISUAL_ERR);
1601 >                return false;
1602 >        }
1603 >        video_init_depth_list();
1604 >
1605 > #if DEBUG
1606 >        D(bug("Available video modes:\n"));
1607 >        vector<video_mode>::const_iterator i = VideoModes.begin(), end = VideoModes.end();
1608 >        while (i != end) {
1609 >                int bits = 1 << i->depth;
1610 >                if (bits == 16)
1611 >                        bits = 15;
1612 >                else if (bits == 32)
1613 >                        bits = 24;
1614 >                D(bug(" %dx%d (ID %02x), %d colors\n", i->x, i->y, i->resolution_id, 1 << bits));
1615 >                ++i;
1616 >        }
1617 > #endif
1618  
1619          // Find requested default mode and open display
1620          if (VideoModes.size() == 1)
1621                  return video_open(VideoModes[0]);
1622          else {
1623                  // Find mode with specified dimensions
1624 <                std::vector<video_mode>::const_iterator i = VideoModes.begin(), end = VideoModes.end();
1625 <                while (i != end) {
1626 <                        if (i->x == default_width && i->y == default_height)
1624 >                std::vector<video_mode>::const_iterator i, end = VideoModes.end();
1625 >                for (i = VideoModes.begin(); i != end; ++i) {
1626 >                        if (i->x == default_width && i->y == default_height && i->depth == default_depth)
1627                                  return video_open(*i);
964                        ++i;
1628                  }
1629                  return video_open(VideoModes[0]);
1630          }
# Line 975 | Line 1638 | bool VideoInit(bool classic)
1638   // Close display
1639   static void video_close(void)
1640   {
978 #ifdef HAVE_PTHREADS
1641          // Stop redraw thread
1642 + #ifdef HAVE_PTHREADS
1643          if (redraw_thread_active) {
1644                  redraw_thread_cancel = true;
1645   #ifdef HAVE_PTHREAD_CANCEL
1646                  pthread_cancel(redraw_thread);
1647   #endif
1648                  pthread_join(redraw_thread, NULL);
986                redraw_thread_active = false;
1649          }
1650   #endif
1651 +        redraw_thread_active = false;
1652  
1653          // Unlock frame buffer
1654          UNLOCK_FRAME_BUFFER;
1655 +        XSync(x_display, false);
1656  
1657 <        // Close window and server connection
1658 <        if (x_display != NULL) {
1659 <                XSync(x_display, false);
1660 <
1661 < #ifdef ENABLE_XF86_DGA
998 <                if (display_type == DISPLAY_DGA) {
999 <                        XF86DGADirectVideo(x_display, screen, 0);
1000 <                        XUngrabPointer(x_display, CurrentTime);
1001 <                        XUngrabKeyboard(x_display, CurrentTime);
1002 <                }
1003 < #endif
1004 <
1005 < #ifdef ENABLE_XF86_VIDMODE
1006 <                if (has_vidmode && display_type == DISPLAY_DGA)
1007 <                        XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1008 < #endif
1009 <
1010 < #ifdef ENABLE_FBDEV_DGA
1011 <                if (display_type == DISPLAY_DGA) {
1012 <                        XUngrabPointer(x_display, CurrentTime);
1013 <                        XUngrabKeyboard(x_display, CurrentTime);
1014 <                        close(fbdev_fd);
1015 <                }
1657 > #ifdef ENABLE_VOSF
1658 >        if (use_vosf) {
1659 >                // Deinitialize VOSF
1660 >                video_vosf_exit();
1661 >        }
1662   #endif
1663  
1664 <                XFlush(x_display);
1665 <                XSync(x_display, false);
1666 <                XUnmapWindow(x_display, the_win);
1021 <                wait_unmapped(the_win);
1022 <                XDestroyWindow(x_display, the_win);
1023 <
1024 <                if (have_shm) {
1025 <                        XDestroyImage(img);
1026 <                        XShmDetach(x_display, &shminfo);
1027 <                        have_shm = false;
1028 <                } else {
1029 <                        //!! free img
1030 <                }
1031 <                //!! free the_gc
1032 <
1033 <                if (cmap_allocated) {
1034 <                        XFreeColormap(x_display, cmap[0]);
1035 <                        XFreeColormap(x_display, cmap[1]);
1036 <                        cmap_allocated = false;
1037 <                }
1038 <                
1039 <                if (!use_vosf) {
1040 <                        if (the_buffer) {
1041 <                                free(the_buffer);
1042 <                                the_buffer = NULL;
1043 <                        }
1044 <
1045 <                        if (!have_shm && the_buffer_copy) {
1046 <                                free(the_buffer_copy);
1047 <                                the_buffer_copy = NULL;
1048 <                        }
1049 <                }
1050 < #ifdef ENABLE_VOSF
1051 <                else {
1052 <                        //!! uninstall SEGV handler?
1664 >        // Close display
1665 >        delete drv;
1666 >        drv = NULL;
1667  
1668 <                        if (the_buffer != (uint8 *)VM_MAP_FAILED) {
1669 <                                vm_release(the_buffer, the_buffer_size);
1670 <                                the_buffer = 0;
1671 <                        }
1058 <                        
1059 <                        if (the_buffer_copy != (uint8 *)VM_MAP_FAILED) {
1060 <                                vm_release(the_buffer_copy, the_buffer_size);
1061 <                                the_buffer_copy = 0;
1062 <                        }
1063 <                }
1064 < #endif
1668 >        // Free colormaps
1669 >        if (cmap[0]) {
1670 >                XFreeColormap(x_display, cmap[0]);
1671 >                cmap[0] = 0;
1672          }
1673 <        
1674 < #ifdef ENABLE_VOSF
1675 <        if (use_vosf) {
1069 <                // Clear mainBuffer data
1070 <                if (mainBuffer.pageInfo) {
1071 <                        free(mainBuffer.pageInfo);
1072 <                        mainBuffer.pageInfo = 0;
1073 <                }
1074 <
1075 <                if (mainBuffer.dirtyPages) {
1076 <                        free(mainBuffer.dirtyPages);
1077 <                        mainBuffer.dirtyPages = 0;
1078 <                }
1673 >        if (cmap[1]) {
1674 >                XFreeColormap(x_display, cmap[1]);
1675 >                cmap[1] = 0;
1676          }
1080 #endif
1677   }
1678  
1679   void VideoExit(void)
1680   {
1681 +        // Close display
1682          video_close();
1683  
1684 < #ifdef ENABLE_VOSF
1685 <        // Close /dev/zero
1686 <        if (zero_fd > 0)
1687 <                close(zero_fd);
1684 > #ifdef ENABLE_XF86_VIDMODE
1685 >        // Free video mode list
1686 >        if (x_video_modes) {
1687 >                XFree(x_video_modes);
1688 >                x_video_modes = NULL;
1689 >        }
1690   #endif
1691 +
1692 + #ifdef ENABLE_FBDEV_DGA
1693 +        // Close framebuffer device
1694 +        if (fbdev_fd >= 0) {
1695 +                close(fbdev_fd);
1696 +                fbdev_fd = -1;
1697 +        }
1698 + #endif
1699 +
1700 +        // Free depth list
1701 +        if (avail_depths) {
1702 +                XFree(avail_depths);
1703 +                avail_depths = NULL;
1704 +        }
1705   }
1706  
1707  
# Line 1099 | Line 1712 | void VideoExit(void)
1712   void VideoQuitFullScreen(void)
1713   {
1714          D(bug("VideoQuitFullScreen()\n"));
1715 <        if (display_type == DISPLAY_DGA)
1103 <                quit_full_screen = true;
1715 >        quit_full_screen = true;
1716   }
1717  
1718  
# Line 1125 | Line 1737 | void VideoInterrupt(void)
1737   *  Set palette
1738   */
1739  
1740 < void video_set_palette(uint8 *pal)
1740 > void video_set_palette(uint8 *pal, int num_in)
1741   {
1742          LOCK_PALETTE;
1743  
1744          // Convert colors to XColor array
1745 <        for (int i=0; i<256; i++) {
1746 <                palette[i].pixel = i;
1747 <                palette[i].red = pal[i*3] * 0x0101;
1748 <                palette[i].green = pal[i*3+1] * 0x0101;
1749 <                palette[i].blue = pal[i*3+2] * 0x0101;
1750 <                palette[i].flags = DoRed | DoGreen | DoBlue;
1745 >        int num_out = 256;
1746 >        bool stretch = false;
1747 >        if (IsDirectMode(VideoMonitor.mode)) {
1748 >                // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
1749 >                num_out = vis->map_entries;
1750 >                stretch = true;
1751 >        }
1752 >        XColor *p = palette;
1753 >        for (int i=0; i<num_out; i++) {
1754 >                int c = (stretch ? (i * num_in) / num_out : i);
1755 >                p->red = pal[c*3 + 0] * 0x0101;
1756 >                p->green = pal[c*3 + 1] * 0x0101;
1757 >                p->blue = pal[c*3 + 2] * 0x0101;
1758 >                p++;
1759          }
1760  
1761 + #ifdef ENABLE_VOSF
1762 +        // Recalculate pixel color expansion map
1763 +        if (!IsDirectMode(VideoMonitor.mode) && xdepth > 8) {
1764 +                for (int i=0; i<256; i++) {
1765 +                        int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
1766 +                        ExpandMap[i] = map_rgb(pal[c*3+0], pal[c*3+1], pal[c*3+2]);
1767 +                }
1768 +
1769 +                // We have to redraw everything because the interpretation of pixel values changed
1770 +                LOCK_VOSF;
1771 +                PFLAG_SET_ALL;
1772 +                UNLOCK_VOSF;
1773 +                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1774 +        }
1775 + #endif
1776 +
1777          // Tell redraw thread to change palette
1778          palette_changed = true;
1779  
# Line 1151 | Line 1787 | void video_set_palette(uint8 *pal)
1787  
1788   void video_switch_to_mode(const video_mode &mode)
1789   {
1790 +        // Close and reopen display
1791          video_close();
1792          video_open(mode);
1156 }
1157
1158
1159 /*
1160 *  Suspend/resume emulator
1161 */
1162
1163 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1164 static void suspend_emul(void)
1165 {
1166        if (display_type == DISPLAY_DGA) {
1167                // Release ctrl key
1168                ADBKeyUp(0x36);
1169                ctrl_down = false;
1170
1171                // Lock frame buffer (this will stop the MacOS thread)
1172                LOCK_FRAME_BUFFER;
1173
1174                // Save frame buffer
1175                fb_save = malloc(VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
1176                if (fb_save)
1177                        memcpy(fb_save, the_buffer, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
1793  
1794 <                // Close full screen display
1795 < #ifdef ENABLE_XF86_DGA
1796 <                XF86DGADirectVideo(x_display, screen, 0);
1182 < #endif
1183 <                XUngrabPointer(x_display, CurrentTime);
1184 <                XUngrabKeyboard(x_display, CurrentTime);
1185 <                XUnmapWindow(x_display, the_win);
1186 <                wait_unmapped(the_win);
1187 <
1188 <                // Open "suspend" window
1189 <                XSetWindowAttributes wattr;
1190 <                wattr.event_mask = KeyPressMask;
1191 <                wattr.background_pixel = black_pixel;
1192 <                
1193 <                suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1194 <                        InputOutput, vis, CWEventMask | CWBackPixel, &wattr);
1195 <                set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
1196 <                set_window_focus(suspend_win);
1197 <                XMapWindow(x_display, suspend_win);
1198 <                emul_suspended = true;
1199 <        }
1200 < }
1201 <
1202 < static void resume_emul(void)
1203 < {
1204 <        // Close "suspend" window
1205 <        XDestroyWindow(x_display, suspend_win);
1206 <        XSync(x_display, false);
1207 <
1208 <        // Reopen full screen display
1209 <        XMapRaised(x_display, the_win);
1210 <        wait_mapped(the_win);
1211 <        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1212 <        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1213 <        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1214 < #ifdef ENABLE_XF86_DGA
1215 <        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1216 <        XF86DGASetViewPort(x_display, screen, 0, 0);
1217 < #endif
1218 <        XSync(x_display, false);
1219 <        
1220 <        // the_buffer already contains the data to restore. i.e. since a temporary
1221 <        // frame buffer is used when VOSF is actually used, fb_save is therefore
1222 <        // not necessary.
1223 < #ifdef ENABLE_VOSF
1224 <        if (use_vosf) {
1225 <                LOCK_VOSF;
1226 <                PFLAG_SET_ALL;
1227 <                UNLOCK_VOSF;
1228 <                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1229 <        }
1230 < #endif
1231 <        
1232 <        // Restore frame buffer
1233 <        if (fb_save) {
1234 < #ifdef ENABLE_VOSF
1235 <                // Don't copy fb_save to the temporary frame buffer in VOSF mode
1236 <                if (!use_vosf)
1237 < #endif
1238 <                memcpy(the_buffer, fb_save, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
1239 <                free(fb_save);
1240 <                fb_save = NULL;
1794 >        if (drv == NULL) {
1795 >                ErrorAlert(STR_OPEN_WINDOW_ERR);
1796 >                QuitEmulator();
1797          }
1242        
1243 #ifdef ENABLE_XF86_DGA
1244        if (!IsDirectMode(VideoMonitor.mode))
1245                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1246 #endif
1247
1248        // Unlock frame buffer (and continue MacOS thread)
1249        UNLOCK_FRAME_BUFFER;
1250        emul_suspended = false;
1798   }
1252 #endif
1799  
1800  
1801   /*
1802 < *  Translate key event to Mac keycode
1802 > *  Translate key event to Mac keycode, returns -1 if no keycode was found
1803 > *  and -2 if the key was recognized as a hotkey
1804   */
1805  
1806 < static int kc_decode(KeySym ks)
1806 > static int kc_decode(KeySym ks, bool key_down)
1807   {
1808          switch (ks) {
1809                  case XK_A: case XK_a: return 0x00;
# Line 1309 | Line 1856 | static int kc_decode(KeySym ks)
1856                  case XK_period: case XK_greater: return 0x2f;
1857                  case XK_slash: case XK_question: return 0x2c;
1858  
1859 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1313 <                case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1314 < #else
1315 <                case XK_Tab: return 0x30;
1316 < #endif
1859 >                case XK_Tab: if (ctrl_down) {if (key_down) drv->suspend(); return -2;} else return 0x30;
1860                  case XK_Return: return 0x24;
1861                  case XK_space: return 0x31;
1862                  case XK_BackSpace: return 0x33;
# Line 1347 | Line 1890 | static int kc_decode(KeySym ks)
1890                  case XK_Left: return 0x3b;
1891                  case XK_Right: return 0x3c;
1892  
1893 <                case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35;
1893 >                case XK_Escape: if (ctrl_down) {if (key_down) { quit_full_screen = true; emerg_quit = true; } return -2;} else return 0x35;
1894  
1895 <                case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a;
1895 >                case XK_F1: if (ctrl_down) {if (key_down) SysMountFirstFloppy(); return -2;} else return 0x7a;
1896                  case XK_F2: return 0x78;
1897                  case XK_F3: return 0x63;
1898                  case XK_F4: return 0x76;
1899 <                case XK_F5: return 0x60;
1899 >                case XK_F5: if (ctrl_down) {if (key_down) drv->toggle_mouse_grab(); return -2;} else return 0x60;
1900                  case XK_F6: return 0x61;
1901                  case XK_F7: return 0x62;
1902                  case XK_F8: return 0x64;
# Line 1401 | Line 1944 | static int kc_decode(KeySym ks)
1944          return -1;
1945   }
1946  
1947 < static int event2keycode(XKeyEvent &ev)
1947 > static int event2keycode(XKeyEvent &ev, bool key_down)
1948   {
1949          KeySym ks;
1407        int as;
1950          int i = 0;
1951  
1952          do {
1953                  ks = XLookupKeysym(&ev, i++);
1954 <                as = kc_decode(ks);
1955 <                if (as != -1)
1954 >                int as = kc_decode(ks, key_down);
1955 >                if (as >= 0)
1956 >                        return as;
1957 >                if (as == -2)
1958                          return as;
1959          } while (ks != NoSymbol);
1960  
# Line 1429 | Line 1973 | static void handle_events(void)
1973                  XNextEvent(x_display, &event);
1974  
1975                  switch (event.type) {
1976 +
1977                          // Mouse button
1978                          case ButtonPress: {
1979                                  unsigned int button = event.xbutton.button;
# Line 1457 | Line 2002 | static void handle_events(void)
2002                          }
2003  
2004                          // Mouse moved
1460                        case EnterNotify:
2005                          case MotionNotify:
2006 <                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
2006 >                                drv->mouse_moved(event.xmotion.x, event.xmotion.y);
2007 >                                break;
2008 >
2009 >                        // Mouse entered window
2010 >                        case EnterNotify:
2011 >                                if (event.xcrossing.mode != NotifyGrab && event.xcrossing.mode != NotifyUngrab)
2012 >                                        drv->mouse_moved(event.xmotion.x, event.xmotion.y);
2013                                  break;
2014  
2015                          // Keyboard
2016                          case KeyPress: {
2017 <                                int code;
2017 >                                int code = -1;
2018                                  if (use_keycodes) {
2019 <                                        event2keycode(event.xkey);      // This is called to process the hotkeys
2020 <                                        code = keycode_table[event.xkey.keycode & 0xff];
2019 >                                        if (event2keycode(event.xkey, true) != -2)      // This is called to process the hotkeys
2020 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2021                                  } else
2022 <                                        code = event2keycode(event.xkey);
2023 <                                if (code != -1) {
2022 >                                        code = event2keycode(event.xkey, true);
2023 >                                if (code >= 0) {
2024                                          if (!emul_suspended) {
2025                                                  if (code == 0x39) {     // Caps Lock pressed
2026                                                          if (caps_on) {
# Line 1485 | Line 2035 | static void handle_events(void)
2035                                                  if (code == 0x36)
2036                                                          ctrl_down = true;
2037                                          } else {
1488 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2038                                                  if (code == 0x31)
2039 <                                                        resume_emul();  // Space wakes us up
1491 < #endif
2039 >                                                        drv->resume();  // Space wakes us up
2040                                          }
2041                                  }
2042                                  break;
2043                          }
2044                          case KeyRelease: {
2045 <                                int code;
2045 >                                int code = -1;
2046                                  if (use_keycodes) {
2047 <                                        event2keycode(event.xkey);      // This is called to process the hotkeys
2048 <                                        code = keycode_table[event.xkey.keycode & 0xff];
2047 >                                        if (event2keycode(event.xkey, false) != -2)     // This is called to process the hotkeys
2048 >                                                code = keycode_table[event.xkey.keycode & 0xff];
2049                                  } else
2050 <                                        code = event2keycode(event.xkey);
2051 <                                if (code != -1 && code != 0x39) {       // Don't propagate Caps Lock releases
2050 >                                        code = event2keycode(event.xkey, false);
2051 >                                if (code >= 0 && code != 0x39) {        // Don't propagate Caps Lock releases
2052                                          ADBKeyUp(code);
2053                                          if (code == 0x36)
2054                                                  ctrl_down = false;
# Line 1548 | Line 2096 | static void handle_events(void)
2096   */
2097  
2098   // Dynamic display update (variable frame rate for each box)
2099 < static void update_display_dynamic(int ticker)
2099 > static void update_display_dynamic(int ticker, driver_window *drv)
2100   {
2101          int y1, y2, y2s, y2a, i, x1, xm, xmo, ymo, yo, yi, yil, xi;
2102          int xil = 0;
# Line 1611 | Line 2159 | static void update_display_dynamic(int t
2159                                          for (y2=0; y2 < yil; y2++, i += bytes_per_row)
2160                                                  memcpy(&the_buffer_copy[i], &the_buffer[i], xil);
2161                                          if (VideoMonitor.mode.depth == VDEPTH_1BIT) {
2162 <                                                if (have_shm)
2163 <                                                        XShmPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
2162 >                                                if (drv->have_shm)
2163 >                                                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
2164                                                  else
2165 <                                                        XPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
2165 >                                                        XPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
2166                                          } else {
2167 <                                                if (have_shm)
2168 <                                                        XShmPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0);
2167 >                                                if (drv->have_shm)
2168 >                                                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0);
2169                                                  else
2170 <                                                        XPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
2170 >                                                        XPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
2171                                          }
2172                                          xil = 0;
2173                                  }
# Line 1638 | Line 2186 | static void update_display_dynamic(int t
2186   }
2187  
2188   // Static display update (fixed frame rate, but incremental)
2189 < static void update_display_static(void)
2189 > static void update_display_static(driver_window *drv)
2190   {
2191          // Incremental update code
2192          int wide = 0, high = 0, x1, x2, y1, y2, i, j;
# Line 1744 | Line 2292 | static void update_display_static(void)
2292  
2293          // Refresh display
2294          if (high && wide) {
2295 <                if (have_shm)
2296 <                        XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
2295 >                if (drv->have_shm)
2296 >                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high, 0);
2297                  else
2298 <                        XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
2298 >                        XPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high);
2299          }
2300   }
2301  
# Line 1764 | Line 2312 | static void update_display_static(void)
2312  
2313   static inline void possibly_quit_dga_mode()
2314   {
2315 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2316 <        // Quit DGA mode if requested
2315 >        // Quit DGA mode if requested (something terrible has happened and we
2316 >        // want to give control back to the user)
2317          if (quit_full_screen) {
2318                  quit_full_screen = false;
2319 < #ifdef ENABLE_XF86_DGA
2320 <                XF86DGADirectVideo(x_display, screen, 0);
2321 < #endif
2322 <                XUngrabPointer(x_display, CurrentTime);
2323 <                XUngrabKeyboard(x_display, CurrentTime);
2324 <                XUnmapWindow(x_display, the_win);
2325 <                wait_unmapped(the_win);
2319 >                delete drv;
2320 >                drv = NULL;
2321 >        }
2322 > }
2323 >
2324 > static inline void possibly_ungrab_mouse()
2325 > {
2326 >        // Ungrab mouse if requested (something terrible has happened and we
2327 >        // want to give control back to the user)
2328 >        if (quit_full_screen) {
2329 >                quit_full_screen = false;
2330 >                if (drv)
2331 >                        drv->ungrab_mouse();
2332          }
1779 #endif
2333   }
2334  
2335 < static inline void handle_palette_changes(int display_type)
2335 > static inline void handle_palette_changes(void)
2336   {
2337          LOCK_PALETTE;
2338  
2339          if (palette_changed) {
2340                  palette_changed = false;
2341 <                if (!IsDirectMode(VideoMonitor.mode)) {
1789 <                        XStoreColors(x_display, cmap[0], palette, 256);
1790 <                        XStoreColors(x_display, cmap[1], palette, 256);
1791 <                        XSync(x_display, false);
1792 <                                
1793 < #ifdef ENABLE_XF86_DGA
1794 <                        if (display_type == DISPLAY_DGA) {
1795 <                                current_dga_cmap ^= 1;
1796 <                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1797 <                        }
1798 < #endif
1799 <                }
2341 >                drv->update_palette();
2342          }
2343  
2344          UNLOCK_PALETTE;
# Line 1806 | Line 2348 | static void video_refresh_dga(void)
2348   {
2349          // Quit DGA mode if requested
2350          possibly_quit_dga_mode();
1809        
1810        // Handle X events
1811        handle_events();
1812        
1813        // Handle palette changes
1814        handle_palette_changes(DISPLAY_DGA);
2351   }
2352  
2353   #ifdef ENABLE_VOSF
# Line 1821 | Line 2357 | static void video_refresh_dga_vosf(void)
2357          // Quit DGA mode if requested
2358          possibly_quit_dga_mode();
2359          
1824        // Handle X events
1825        handle_events();
1826        
1827        // Handle palette changes
1828        handle_palette_changes(DISPLAY_DGA);
1829        
2360          // Update display (VOSF variant)
2361          static int tick_counter = 0;
2362          if (++tick_counter >= frame_skip) {
# Line 1842 | Line 2372 | static void video_refresh_dga_vosf(void)
2372  
2373   static void video_refresh_window_vosf(void)
2374   {
2375 <        // Quit DGA mode if requested
2376 <        possibly_quit_dga_mode();
1847 <        
1848 <        // Handle X events
1849 <        handle_events();
1850 <        
1851 <        // Handle palette changes
1852 <        handle_palette_changes(DISPLAY_WINDOW);
2375 >        // Ungrab mouse if requested
2376 >        possibly_ungrab_mouse();
2377          
2378          // Update display (VOSF variant)
2379          static int tick_counter = 0;
# Line 1857 | Line 2381 | static void video_refresh_window_vosf(vo
2381                  tick_counter = 0;
2382                  if (mainBuffer.dirty) {
2383                          LOCK_VOSF;
2384 <                        update_display_window_vosf();
2384 >                        update_display_window_vosf(static_cast<driver_window *>(drv));
2385                          UNLOCK_VOSF;
2386                          XSync(x_display, false); // Let the server catch up
2387                  }
# Line 1867 | Line 2391 | static void video_refresh_window_vosf(vo
2391  
2392   static void video_refresh_window_static(void)
2393   {
2394 <        // Handle X events
2395 <        handle_events();
2396 <        
1873 <        // Handle_palette changes
1874 <        handle_palette_changes(DISPLAY_WINDOW);
1875 <        
2394 >        // Ungrab mouse if requested
2395 >        possibly_ungrab_mouse();
2396 >
2397          // Update display (static variant)
2398          static int tick_counter = 0;
2399          if (++tick_counter >= frame_skip) {
2400                  tick_counter = 0;
2401 <                update_display_static();
2401 >                update_display_static(static_cast<driver_window *>(drv));
2402          }
2403   }
2404  
2405   static void video_refresh_window_dynamic(void)
2406   {
2407 <        // Handle X events
2408 <        handle_events();
2409 <        
1889 <        // Handle_palette changes
1890 <        handle_palette_changes(DISPLAY_WINDOW);
1891 <        
2407 >        // Ungrab mouse if requested
2408 >        possibly_ungrab_mouse();
2409 >
2410          // Update display (dynamic variant)
2411          static int tick_counter = 0;
2412          tick_counter++;
2413 <        update_display_dynamic(tick_counter);
2413 >        update_display_dynamic(tick_counter, static_cast<driver_window *>(drv));
2414   }
2415  
2416  
# Line 1924 | Line 2442 | static void VideoRefreshInit(void)
2442          }
2443   }
2444  
2445 + // This function is called on non-threaded platforms from a timer interrupt
2446   void VideoRefresh(void)
2447   {
2448 <        // TODO: make main_unix/VideoRefresh call directly video_refresh() ?
2448 >        // We need to check redraw_thread_active to inhibit refreshed during
2449 >        // mode changes on non-threaded platforms
2450 >        if (!redraw_thread_active)
2451 >                return;
2452 >
2453 >        // Handle X events
2454 >        handle_events();
2455 >
2456 >        // Handle palette changes
2457 >        handle_palette_changes();
2458 >
2459 >        // Update display
2460          video_refresh();
2461   }
2462  
2463 + const int VIDEO_REFRESH_HZ = 60;
2464 + const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
2465 +
2466   #ifdef HAVE_PTHREADS
2467   static void *redraw_func(void *arg)
2468   {
2469 +        int fd = ConnectionNumber(x_display);
2470 +
2471          uint64 start = GetTicks_usec();
2472          int64 ticks = 0;
2473 <        uint64 next = GetTicks_usec();
2473 >        uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2474 >
2475          while (!redraw_thread_cancel) {
2476 <                video_refresh();
1941 <                next += 16667;
2476 >
2477                  int64 delay = next - GetTicks_usec();
2478 <                if (delay > 0)
2479 <                        Delay_usec(delay);
2480 <                else if (delay < -16667)
2478 >                if (delay < -VIDEO_REFRESH_DELAY) {
2479 >
2480 >                        // We are lagging far behind, so we reset the delay mechanism
2481                          next = GetTicks_usec();
2482 <                ticks++;
2482 >
2483 >                } else if (delay <= 0) {
2484 >
2485 >                        // Delay expired, refresh display
2486 >                        handle_events();
2487 >                        handle_palette_changes();
2488 >                        video_refresh();
2489 >                        next += VIDEO_REFRESH_DELAY;
2490 >                        ticks++;
2491 >
2492 >                } else {
2493 >
2494 >                        // No display refresh pending, check for X events
2495 >                        fd_set readfds;
2496 >                        FD_ZERO(&readfds);
2497 >                        FD_SET(fd, &readfds);
2498 >                        struct timeval timeout;
2499 >                        timeout.tv_sec = 0;
2500 >                        timeout.tv_usec = delay;
2501 >                        if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2502 >                                handle_events();
2503 >                }
2504          }
2505 +
2506          uint64 end = GetTicks_usec();
2507 <        // printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start));
2507 >        D(bug("%Ld refreshes in %Ld usec = %f refreshes/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
2508          return NULL;
2509   }
2510   #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines