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.26 by cebix, 2000-10-27T17:01:40Z vs.
Revision 1.49 by cebix, 2001-07-01T19:57:55Z

# Line 1 | Line 1
1   /*
2   *  video_x.cpp - Video/graphics emulation, X11 specific stuff
3   *
4 < *  Basilisk II (C) 1997-2000 Christian Bauer
4 > *  Basilisk II (C) 1997-2001 Christian Bauer
5   *
6   *  This program is free software; you can redistribute it and/or modify
7   *  it under the terms of the GNU General Public License as published by
# Line 52 | Line 52
52   # include <sys/mman.h>
53   #endif
54  
55 #ifdef ENABLE_VOSF
56 # include <unistd.h>
57 # include <signal.h>
58 # include <fcntl.h>
59 # include <sys/mman.h>
60 #endif
61
55   #include "cpu_emulation.h"
56   #include "main.h"
57   #include "adb.h"
# Line 79 | Line 72 | enum {
72  
73   // Constants
74   const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
75 < const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
75 >
76 > static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
77 > static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
78  
79  
80   // Global variables
81   static int32 frame_skip;                                                        // Prefs items
82 < static int16 mouse_wheel_mode = 1;
83 < static int16 mouse_wheel_lines = 3;
82 > static int16 mouse_wheel_mode;
83 > static int16 mouse_wheel_lines;
84  
85   static int display_type = DISPLAY_WINDOW;                       // See enum above
86   static bool local_X11;                                                          // Flag: X server running on local machine?
87 < static uint8 *the_buffer;                                                       // Mac frame buffer
87 > static uint8 *the_buffer = NULL;                                        // Mac frame buffer (where MacOS draws into)
88 > static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer (for refreshed modes)
89  
94 #ifdef HAVE_PTHREADS
90   static bool redraw_thread_active = false;                       // Flag: Redraw thread installed
91 < static volatile bool redraw_thread_cancel = false;      // Flag: Cancel Redraw thread
91 > #ifdef HAVE_PTHREADS
92 > static volatile bool redraw_thread_cancel;                      // Flag: Cancel Redraw thread
93   static pthread_t redraw_thread;                                         // Redraw thread
94   #endif
95  
96   static bool has_dga = false;                                            // Flag: Video DGA capable
97   static bool has_vidmode = false;                                        // Flag: VidMode extension available
98  
99 + #ifdef ENABLE_VOSF
100 + static bool use_vosf = true;                                            // Flag: VOSF enabled
101 + #else
102 + static const bool use_vosf = false;                                     // VOSF not possible
103 + #endif
104 +
105   static bool ctrl_down = false;                                          // Flag: Ctrl key pressed
106   static bool caps_on = false;                                            // Flag: Caps Lock on
107   static bool quit_full_screen = false;                           // Flag: DGA close requested from redraw thread
# Line 114 | Line 116 | static int keycode_table[256];                                         // X
116   // X11 variables
117   static int screen;                                                                      // Screen number
118   static int xdepth;                                                                      // Depth of X screen
119 < static int depth;                                                                       // Depth of Mac frame buffer
118 < static Window rootwin, the_win;                                         // Root window and our window
119 > static Window rootwin;                                                          // Root window and our window
120   static XVisualInfo visualInfo;
121   static Visual *vis;
122 < static Colormap cmap[2];                                                        // Two colormaps (DGA) for 8-bit mode
122 > static Colormap cmap[2] = {0, 0};                                       // Colormaps for indexed modes (DGA needs two of them)
123   static XColor black, white;
124   static unsigned long black_pixel, white_pixel;
125   static int eventmask;
125 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | FocusChangeMask | ExposureMask;
126 static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
126  
127 < static XColor palette[256];                                                     // Color palette for 8-bit mode
129 < static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
130 < #ifdef HAVE_PTHREADS
131 < static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;        // Mutex to protect palette
132 < #endif
127 > static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
128  
129 < // Variables for window mode
130 < static GC the_gc;
136 < static XImage *img = NULL;
137 < static XShmSegmentInfo shminfo;
138 < static Cursor mac_cursor;
139 < static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer
140 < static bool have_shm = false;                                           // Flag: SHM extensions available
141 < static bool updt_box[17][17];                                           // Flag for Update
142 < static int nr_boxes;
143 < static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
144 < static int sm_no_boxes[] = {1,8,32,64,128,300};
129 > static XColor palette[256];                                                     // Color palette to be used as CLUT and gamma table
130 > static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
131  
132 < // Variables for XF86 DGA mode
133 < static int current_dga_cmap;                                            // Number (0 or 1) of currently installed DGA colormap
148 < static Window suspend_win;                                                      // "Suspend" window
149 < static void *fb_save = NULL;                                            // Saved frame buffer for suspend
150 < #ifdef HAVE_PTHREADS
151 < static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;   // Mutex to protect frame buffer
132 > #ifdef ENABLE_FBDEV_DGA
133 > static int fbdev_fd = -1;
134   #endif
135  
154 // Variables for fbdev DGA mode
155 const char FBDEVICE_FILE_NAME[] = "/dev/fb";
156 static int fbdev_fd;
157
136   #ifdef ENABLE_XF86_VIDMODE
137 < // Variables for XF86 VidMode support
160 < static XF86VidModeModeInfo **x_video_modes;                     // Array of all available modes
137 > static XF86VidModeModeInfo **x_video_modes = NULL;      // Array of all available modes
138   static int num_x_video_modes;
139   #endif
140  
141 < #ifdef ENABLE_VOSF
142 < static bool use_vosf = true;                                            // Flag: VOSF enabled
141 > // Mutex to protect palette
142 > #ifdef HAVE_PTHREADS
143 > static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;
144 > #define LOCK_PALETTE pthread_mutex_lock(&palette_lock)
145 > #define UNLOCK_PALETTE pthread_mutex_unlock(&palette_lock)
146   #else
147 < static const bool use_vosf = false;                                     // Flag: VOSF enabled
147 > #define LOCK_PALETTE
148 > #define UNLOCK_PALETTE
149   #endif
150  
151 < #ifdef ENABLE_VOSF
171 < static uint8 * the_host_buffer;                                         // Host frame buffer in VOSF mode
172 < static uint32 the_buffer_size;                                          // Size of allocated the_buffer
173 < #endif
174 <
175 < #ifdef ENABLE_VOSF
176 < // Variables for Video on SEGV support (taken from the Win32 port)
177 < struct ScreenPageInfo {
178 <    int top, bottom;                    // Mapping between this virtual page and Mac scanlines
179 < };
180 <
181 < struct ScreenInfo {
182 <    uint32 memBase;                             // Real start address
183 <    uint32 memStart;                    // Start address aligned to page boundary
184 <    uint32 memEnd;                              // Address of one-past-the-end of the screen
185 <    uint32 memLength;                   // Length of the memory addressed by the screen pages
186 <    
187 <    uint32 pageSize;                    // Size of a page
188 <    int pageBits;                               // Shift count to get the page number
189 <    uint32 pageCount;                   // Number of pages allocated to the screen
190 <    
191 <    uint8 * dirtyPages;                 // Table of flags set if page was altered
192 <    ScreenPageInfo * pageInfo;  // Table of mappings page -> Mac scanlines
193 < };
194 <
195 < static ScreenInfo mainBuffer;
196 <
197 < #define PFLAG_SET(page)                 mainBuffer.dirtyPages[page] = 1
198 < #define PFLAG_CLEAR(page)               mainBuffer.dirtyPages[page] = 0
199 < #define PFLAG_ISSET(page)               mainBuffer.dirtyPages[page]
200 < #define PFLAG_ISCLEAR(page)             (mainBuffer.dirtyPages[page] == 0)
201 < #ifdef UNALIGNED_PROFITABLE
202 < # define PFLAG_ISCLEAR_4(page)  (*((uint32 *)(mainBuffer.dirtyPages + page)) == 0)
203 < #else
204 < # define PFLAG_ISCLEAR_4(page)  \
205 <                (mainBuffer.dirtyPages[page  ] == 0) \
206 <        &&      (mainBuffer.dirtyPages[page+1] == 0) \
207 <        &&      (mainBuffer.dirtyPages[page+2] == 0) \
208 <        &&      (mainBuffer.dirtyPages[page+3] == 0)
209 < #endif
210 < #define PFLAG_CLEAR_ALL                 memset(mainBuffer.dirtyPages, 0, mainBuffer.pageCount)
211 < #define PFLAG_SET_ALL                   memset(mainBuffer.dirtyPages, 1, mainBuffer.pageCount)
212 <
213 < static int zero_fd = -1;
214 < static bool Screen_fault_handler_init();
215 < static struct sigaction vosf_sa;
216 <
151 > // Mutex to protect frame buffer
152   #ifdef HAVE_PTHREADS
153 < static pthread_mutex_t Screen_draw_lock = PTHREAD_MUTEX_INITIALIZER;    // Mutex to protect frame buffer (dirtyPages in fact)
153 > static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
154 > #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
155 > #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
156 > #else
157 > #define LOCK_FRAME_BUFFER
158 > #define UNLOCK_FRAME_BUFFER
159   #endif
160  
161 < static int log_base_2(uint32 x)
162 < {
163 <        uint32 mask = 0x80000000;
164 <        int l = 31;
165 <        while (l >= 0 && (x & mask) == 0) {
226 <                mask >>= 1;
227 <                l--;
228 <        }
229 <        return l;
230 < }
231 <
232 < #endif
161 > // Variables for non-VOSF incremental refresh
162 > static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
163 > static int sm_no_boxes[] = {1,8,32,64,128,300};
164 > static bool updt_box[17][17];
165 > static int nr_boxes;
166  
167 < // VideoRefresh function
168 < void VideoRefreshInit(void);
167 > // Video refresh function
168 > static void VideoRefreshInit(void);
169   static void (*video_refresh)(void);
170  
171 +
172   // Prototypes
173   static void *redraw_func(void *arg);
174 < static int event2keycode(XKeyEvent *ev);
241 <
174 > static int event2keycode(XKeyEvent &ev);
175  
176   // From main_unix.cpp
177   extern char *x_display_name;
# Line 247 | Line 180 | extern Display *x_display;
180   // From sys_unix.cpp
181   extern void SysMountFirstFloppy(void);
182  
250 #ifdef ENABLE_VOSF
251 # include "video_vosf.h"
252 #endif
253
183  
184   /*
185 < *  Initialization
185 > *  Utility functions
186   */
187  
188 < // Set VideoMonitor according to video mode
189 < void set_video_monitor(int width, int height, int bytes_per_row, bool native_byte_order)
188 > // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
189 > static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
190 > {
191 >        return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
192 > }
193 >
194 > // Add mode to list of supported modes
195 > static void add_mode(uint32 width, uint32 height, uint32 resolution_id, uint32 bytes_per_row, video_depth depth)
196 > {
197 >        video_mode mode;
198 >        mode.x = width;
199 >        mode.y = height;
200 >        mode.resolution_id = resolution_id;
201 >        mode.bytes_per_row = bytes_per_row;
202 >        mode.depth = depth;
203 >        VideoModes.push_back(mode);
204 > }
205 >
206 > // Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac)
207 > static void set_mac_frame_buffer(video_depth depth, bool native_byte_order)
208   {
209   #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
210          int layout = FLAYOUT_DIRECT;
211 <        switch (depth) {
212 <                case 1:
213 <                        layout = FLAYOUT_DIRECT;
214 <                        break;
268 <                case 8:
269 <                        layout = FLAYOUT_DIRECT;
270 <                        break;
271 <                case 15:
272 <                        layout = FLAYOUT_HOST_555;
273 <                        break;
274 <                case 16:
275 <                        layout = FLAYOUT_HOST_565;
276 <                        break;
277 <                case 24:
278 <                case 32:
279 <                        layout = FLAYOUT_HOST_888;
280 <                        break;
281 <        }
211 >        if (depth == VDEPTH_16BIT)
212 >                layout = (xdepth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565;
213 >        else if (depth == VDEPTH_32BIT)
214 >                layout = (xdepth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
215          if (native_byte_order)
216                  MacFrameLayout = layout;
217          else
218                  MacFrameLayout = FLAYOUT_DIRECT;
219 +        VideoMonitor.mac_frame_base = MacFrameBaseMac;
220 +
221 +        // Set variables used by UAE memory banking
222 +        MacFrameBaseHost = the_buffer;
223 +        MacFrameSize = VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y;
224 +        InitFrameBufferMapping();
225 + #else
226 +        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
227 +        D(bug("Host frame buffer = %p, ", the_buffer));
228   #endif
229 <        switch (depth) {
230 <                case 1:
231 <                        VideoMonitor.mode = VMODE_1BIT;
232 <                        break;
233 <                case 8:
234 <                        VideoMonitor.mode = VMODE_8BIT;
235 <                        break;
236 <                case 15:
237 <                        VideoMonitor.mode = VMODE_16BIT;
238 <                        break;
239 <                case 16:
240 <                        VideoMonitor.mode = VMODE_16BIT;
241 <                        break;
242 <                case 24:
243 <                case 32:
244 <                        VideoMonitor.mode = VMODE_32BIT;
245 <                        break;
229 >        D(bug("VideoMonitor.mac_frame_base = %08x\n", VideoMonitor.mac_frame_base));
230 > }
231 >
232 > // Set window name and class
233 > static void set_window_name(Window w, int name)
234 > {
235 >        const char *str = GetString(name);
236 >        XStoreName(x_display, w, str);
237 >        XSetIconName(x_display, w, str);
238 >
239 >        XClassHint *hints;
240 >        hints = XAllocClassHint();
241 >        if (hints) {
242 >                hints->res_name = "BasiliskII";
243 >                hints->res_class = "BasiliskII";
244 >                XSetClassHint(x_display, w, hints);
245 >                XFree(hints);
246          }
247 <        VideoMonitor.x = width;
248 <        VideoMonitor.y = height;
249 <        VideoMonitor.bytes_per_row = bytes_per_row;
247 > }
248 >
249 > // Set window input focus flag
250 > static void set_window_focus(Window w)
251 > {
252 >        XWMHints *hints = XAllocWMHints();
253 >        if (hints) {
254 >                hints->input = True;
255 >                hints->initial_state = NormalState;
256 >                hints->flags = InputHint | StateHint;
257 >                XSetWMHints(x_display, w, hints);
258 >                XFree(hints);
259 >        }
260 > }
261 >
262 > // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
263 > static Atom WM_DELETE_WINDOW = (Atom)0;
264 > static void set_window_delete_protocol(Window w)
265 > {
266 >        WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
267 >        XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
268 > }
269 >
270 > // Wait until window is mapped/unmapped
271 > void wait_mapped(Window w)
272 > {
273 >        XEvent e;
274 >        do {
275 >                XMaskEvent(x_display, StructureNotifyMask, &e);
276 >        } while ((e.type != MapNotify) || (e.xmap.event != w));
277 > }
278 >
279 > void wait_unmapped(Window w)
280 > {
281 >        XEvent e;
282 >        do {
283 >                XMaskEvent(x_display, StructureNotifyMask, &e);
284 >        } while ((e.type != UnmapNotify) || (e.xmap.event != w));
285   }
286  
287   // Trap SHM errors
# Line 320 | Line 297 | static int error_handler(Display *d, XEr
297                  return old_error_handler(d, e);
298   }
299  
300 < // Init window mode
301 < static bool init_window(int width, int height)
300 >
301 > /*
302 > *  Display "driver" classes
303 > */
304 >
305 > class driver_base {
306 > public:
307 >        driver_base();
308 >        virtual ~driver_base();
309 >
310 >        virtual void update_palette(void);
311 >        virtual void suspend(void) {}
312 >        virtual void resume(void) {}
313 >
314 > public:
315 >        bool init_ok;   // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer)
316 >        Window w;               // The window we draw into
317 > };
318 >
319 > class driver_window;
320 > static void update_display_window_vosf(driver_window *drv);
321 > static void update_display_dynamic(int ticker, driver_window *drv);
322 > static void update_display_static(driver_window *drv);
323 >
324 > class driver_window : public driver_base {
325 >        friend void update_display_window_vosf(driver_window *drv);
326 >        friend void update_display_dynamic(int ticker, driver_window *drv);
327 >        friend void update_display_static(driver_window *drv);
328 >
329 > public:
330 >        driver_window(const video_mode &mode);
331 >        ~driver_window();
332 >
333 > private:
334 >        GC gc;
335 >        XImage *img;
336 >        bool have_shm;                          // Flag: SHM extensions available
337 >        XShmSegmentInfo shminfo;
338 >        Cursor mac_cursor;
339 > };
340 >
341 > static driver_base *drv = NULL; // Pointer to currently used driver object
342 >
343 > #ifdef ENABLE_VOSF
344 > # include "video_vosf.h"
345 > #endif
346 >
347 > driver_base::driver_base()
348 > : init_ok(false), w(0)
349   {
350 +        the_buffer = NULL;
351 +        the_buffer_copy = NULL;
352 + }
353 +
354 + driver_base::~driver_base()
355 + {
356 +        if (w) {
357 +                XUnmapWindow(x_display, w);
358 +                wait_unmapped(w);
359 +                XDestroyWindow(x_display, w);
360 +        }
361 +
362 +        XFlush(x_display);
363 +        XSync(x_display, false);
364 +
365 +        // Free frame buffer(s)
366 +        if (!use_vosf) {
367 +                if (the_buffer) {
368 +                        free(the_buffer);
369 +                        the_buffer = NULL;
370 +                }
371 +                if (the_buffer_copy) {
372 +                        free(the_buffer_copy);
373 +                        the_buffer_copy = NULL;
374 +                }
375 +        }
376 + #ifdef ENABLE_VOSF
377 +        else {
378 +                if (the_buffer != (uint8 *)VM_MAP_FAILED) {
379 +                        vm_release(the_buffer, the_buffer_size);
380 +                        the_buffer = NULL;
381 +                }
382 +                if (the_buffer_copy != (uint8 *)VM_MAP_FAILED) {
383 +                        vm_release(the_buffer_copy, the_buffer_size);
384 +                        the_buffer_copy = NULL;
385 +                }
386 +        }
387 + #endif
388 + }
389 +
390 + // Palette has changed
391 + void driver_base::update_palette(void)
392 + {
393 +        if (cmap[0] && cmap[1]) {
394 +                int num = 256;
395 +                if (IsDirectMode(VideoMonitor.mode))
396 +                        num = vis->map_entries; // Palette is gamma table
397 +                else if (vis->c_class == DirectColor)
398 +                        return; // Indexed mode on true color screen, don't set CLUT
399 +                XStoreColors(x_display, cmap[0], palette, num);
400 +                XStoreColors(x_display, cmap[1], palette, num);
401 +        }
402 +        XSync(x_display, false);
403 + }
404 +
405 +
406 + /*
407 + *  Windowed display driver
408 + */
409 +
410 + // Open display
411 + driver_window::driver_window(const video_mode &mode)
412 + : gc(0), img(NULL), have_shm(false), mac_cursor(0)
413 + {
414 +        int width = mode.x, height = mode.y;
415          int aligned_width = (width + 15) & ~15;
416          int aligned_height = (height + 15) & ~15;
417  
418          // Set absolute mouse mode
419          ADBSetRelMouseMode(false);
420  
332        // Read frame skip prefs
333        frame_skip = PrefsFindInt32("frameskip");
334
421          // Create window
422          XSetWindowAttributes wattr;
423          wattr.event_mask = eventmask = win_eventmask;
424          wattr.background_pixel = black_pixel;
425 <        wattr.border_pixel = black_pixel;
426 <        wattr.backing_store = NotUseful;
427 <        wattr.save_under = false;
342 <        wattr.backing_planes = xdepth;
425 >        wattr.colormap = (mode.depth == VDEPTH_1BIT && vis->c_class == PseudoColor ? DefaultColormap(x_display, screen) : cmap[0]);
426 >        w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
427 >                InputOutput, vis, CWEventMask | CWBackPixel | (vis->c_class == PseudoColor || vis->c_class == DirectColor ? CWColormap : 0), &wattr);
428  
429 <        XSync(x_display, false);
430 <        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
346 <                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
347 <                CWBackingStore | CWBackingPlanes, &wattr);
429 >        // Set window name/class
430 >        set_window_name(w, STR_WINDOW_TITLE);
431  
432          // Indicate that we want keyboard input
433 <        {
434 <                XWMHints *hints = XAllocWMHints();
435 <                if (hints) {
436 <                        hints->input = True;
354 <                        hints->flags = InputHint;
355 <                        XSetWMHints(x_display, the_win, hints);
356 <                        XFree((char *)hints);
357 <                }
358 <        }
433 >        set_window_focus(w);
434 >
435 >        // Set delete protocol property
436 >        set_window_delete_protocol(w);
437  
438          // Make window unresizable
439          {
# Line 366 | Line 444 | static bool init_window(int width, int h
444                          hints->min_height = height;
445                          hints->max_height = height;
446                          hints->flags = PMinSize | PMaxSize;
447 <                        XSetWMNormalHints(x_display, the_win, hints);
448 <                        XFree((char *)hints);
447 >                        XSetWMNormalHints(x_display, w, hints);
448 >                        XFree(hints);
449                  }
450          }
451          
374        // Set window title
375        {
376                XTextProperty title_prop;
377                const char *title = GetString(STR_WINDOW_TITLE);
378                XStringListToTextProperty((char **)&title, 1, &title_prop);
379                XSetWMName(x_display, the_win, &title_prop);
380                XFree(title_prop.value);
381        }
382
383        // Set window class
384        {
385                XClassHint *hints;
386                hints = XAllocClassHint();
387                if (hints) {
388                        hints->res_name = "BasiliskII";
389                        hints->res_class = "BasiliskII";
390                        XSetClassHint(x_display, the_win, hints);
391                        XFree((char *)hints);
392                }
393        }
394
452          // Show window
453 <        XSync(x_display, false);
454 <        XMapRaised(x_display, the_win);
398 <        XFlush(x_display);
453 >        XMapWindow(x_display, w);
454 >        wait_mapped(w);
455  
456 <        // Set colormap
457 <        if (depth == 8)
458 <                XSetWindowColormap(x_display, the_win, cmap[0]);
456 >        // 1-bit mode is big-endian; if the X server is little-endian, we can't
457 >        // use SHM because that doesn't allow changing the image byte order
458 >        bool need_msb_image = (mode.depth == VDEPTH_1BIT && XImageByteOrder(x_display) == LSBFirst);
459  
460          // Try to create and attach SHM image
461 <        have_shm = false;
406 <        if (depth != 1 && local_X11 && XShmQueryExtension(x_display)) {
461 >        if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
462  
463                  // Create SHM image ("height + 2" for safety)
464 <                img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
464 >                img = XShmCreateImage(x_display, vis, mode.depth == VDEPTH_1BIT ? 1 : xdepth, mode.depth == VDEPTH_1BIT ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
465                  shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
466                  the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
467                  shminfo.shmaddr = img->data = (char *)the_buffer_copy;
# Line 430 | Line 485 | static bool init_window(int width, int h
485          
486          // Create normal X image if SHM doesn't work ("height + 2" for safety)
487          if (!have_shm) {
488 <                int bytes_per_row = aligned_width;
434 <                switch (depth) {
435 <                        case 1:
436 <                                bytes_per_row /= 8;
437 <                                break;
438 <                        case 15:
439 <                        case 16:
440 <                                bytes_per_row *= 2;
441 <                                break;
442 <                        case 24:
443 <                        case 32:
444 <                                bytes_per_row *= 4;
445 <                                break;
446 <                }
488 >                int bytes_per_row = (mode.depth == VDEPTH_1BIT ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth)));
489                  the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
490 <                img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
490 >                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);
491          }
492  
493 <        // 1-Bit mode is big-endian
452 <        if (depth == 1) {
493 >        if (need_msb_image) {
494                  img->byte_order = MSBFirst;
495                  img->bitmap_bit_order = MSBFirst;
496          }
497  
498   #ifdef ENABLE_VOSF
499 <        // Allocate a page-aligned chunk of memory for frame buffer
459 <        the_buffer_size = align_on_page_boundary((aligned_height + 2) * img->bytes_per_line);
499 >        // Allocate memory for frame buffer (SIZE is extended to page-boundary)
500          the_host_buffer = the_buffer_copy;
501 <        
502 <        the_buffer_copy = (uint8 *)allocate_framebuffer(the_buffer_size);
503 <        memset(the_buffer_copy, 0, the_buffer_size);
464 <        
465 <        the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
466 <        memset(the_buffer, 0, the_buffer_size);
501 >        the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line);
502 >        the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
503 >        the_buffer = (uint8 *)vm_acquire(the_buffer_size);
504   #else
505          // Allocate memory for frame buffer
506          the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
507   #endif
508  
509          // Create GC
510 <        the_gc = XCreateGC(x_display, the_win, 0, 0);
511 <        XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
510 >        gc = XCreateGC(x_display, w, 0, 0);
511 >        XSetState(x_display, gc, black_pixel, white_pixel, GXcopy, AllPlanes);
512  
513          // Create no_cursor
514          mac_cursor = XCreatePixmapCursor(x_display,
515 <           XCreatePixmap(x_display, the_win, 1, 1, 1),
516 <           XCreatePixmap(x_display, the_win, 1, 1, 1),
515 >           XCreatePixmap(x_display, w, 1, 1, 1),
516 >           XCreatePixmap(x_display, w, 1, 1, 1),
517             &black, &white, 0, 0);
518 <        XDefineCursor(x_display, the_win, mac_cursor);
518 >        XDefineCursor(x_display, w, mac_cursor);
519  
520 <        // Set VideoMonitor
520 >        // Init blitting routines
521          bool native_byte_order;
522   #ifdef WORDS_BIGENDIAN
523 <        native_byte_order = (img->bitmap_bit_order == MSBFirst);
523 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
524   #else
525 <        native_byte_order = (img->bitmap_bit_order == LSBFirst);
525 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
526   #endif
527   #ifdef ENABLE_VOSF
528 <        do_update_framebuffer = GET_FBCOPY_FUNC(depth, native_byte_order, DISPLAY_WINDOW);
528 >        Screen_blitter_init(&visualInfo, native_byte_order, mode.depth);
529   #endif
530 <        set_video_monitor(width, height, img->bytes_per_line, native_byte_order);
531 <        
532 < #if REAL_ADDRESSING || DIRECT_ADDRESSING
533 <        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
534 < #else
535 <        VideoMonitor.mac_frame_base = MacFrameBaseMac;
530 >
531 >        // Set VideoMonitor
532 >        VideoMonitor.mode = mode;
533 >        set_mac_frame_buffer(mode.depth, native_byte_order);
534 >
535 >        // Everything went well
536 >        init_ok = true;
537 > }
538 >
539 > // Close display
540 > driver_window::~driver_window()
541 > {
542 >        if (img)
543 >                XDestroyImage(img);
544 >        if (have_shm) {
545 >                XShmDetach(x_display, &shminfo);
546 >                the_buffer_copy = NULL; // don't free() in driver_base dtor
547 >        }
548 >        if (gc)
549 >                XFreeGC(x_display, gc);
550 > }
551 >
552 >
553 > #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
554 > /*
555 > *  DGA display driver base class
556 > */
557 >
558 > class driver_dga : public driver_base {
559 > public:
560 >        driver_dga();
561 >        ~driver_dga();
562 >
563 >        void suspend(void);
564 >        void resume(void);
565 >
566 > private:
567 >        Window suspend_win;             // "Suspend" information window
568 >        void *fb_save;                  // Saved frame buffer for suspend/resume
569 > };
570 >
571 > driver_dga::driver_dga()
572 > : suspend_win(0), fb_save(NULL)
573 > {
574 > }
575 >
576 > driver_dga::~driver_dga()
577 > {
578 >        XUngrabPointer(x_display, CurrentTime);
579 >        XUngrabKeyboard(x_display, CurrentTime);
580 > }
581 >
582 > // Suspend emulation
583 > void driver_dga::suspend(void)
584 > {
585 >        // Release ctrl key
586 >        ADBKeyUp(0x36);
587 >        ctrl_down = false;
588 >
589 >        // Lock frame buffer (this will stop the MacOS thread)
590 >        LOCK_FRAME_BUFFER;
591 >
592 >        // Save frame buffer
593 >        fb_save = malloc(VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
594 >        if (fb_save)
595 >                memcpy(fb_save, the_buffer, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
596 >
597 >        // Close full screen display
598 > #ifdef ENABLE_XF86_DGA
599 >        XF86DGADirectVideo(x_display, screen, 0);
600   #endif
601 <        return true;
601 >        XUngrabPointer(x_display, CurrentTime);
602 >        XUngrabKeyboard(x_display, CurrentTime);
603 >        XUnmapWindow(x_display, w);
604 >        wait_unmapped(w);
605 >
606 >        // Open "suspend" window
607 >        XSetWindowAttributes wattr;
608 >        wattr.event_mask = KeyPressMask;
609 >        wattr.background_pixel = black_pixel;
610 >                
611 >        suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
612 >                InputOutput, vis, CWEventMask | CWBackPixel, &wattr);
613 >        set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
614 >        set_window_focus(suspend_win);
615 >        XMapWindow(x_display, suspend_win);
616 >        emul_suspended = true;
617   }
618  
619 < // Init fbdev DGA display
620 < static bool init_fbdev_dga(char *in_fb_name)
619 > // Resume emulation
620 > void driver_dga::resume(void)
621   {
622 +        // Close "suspend" window
623 +        XDestroyWindow(x_display, suspend_win);
624 +        XSync(x_display, false);
625 +
626 +        // Reopen full screen display
627 +        XMapRaised(x_display, w);
628 +        wait_mapped(w);
629 +        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
630 +        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
631 +        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
632 + #ifdef ENABLE_XF86_DGA
633 +        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
634 +        XF86DGASetViewPort(x_display, screen, 0, 0);
635 + #endif
636 +        XSync(x_display, false);
637 +        
638 +        // the_buffer already contains the data to restore. i.e. since a temporary
639 +        // frame buffer is used when VOSF is actually used, fb_save is therefore
640 +        // not necessary.
641 + #ifdef ENABLE_VOSF
642 +        if (use_vosf) {
643 +                LOCK_VOSF;
644 +                PFLAG_SET_ALL;
645 +                UNLOCK_VOSF;
646 +                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
647 +        }
648 + #endif
649 +        
650 +        // Restore frame buffer
651 +        if (fb_save) {
652 + #ifdef ENABLE_VOSF
653 +                // Don't copy fb_save to the temporary frame buffer in VOSF mode
654 +                if (!use_vosf)
655 + #endif
656 +                memcpy(the_buffer, fb_save, VideoMonitor.mode.y * VideoMonitor.mode.bytes_per_row);
657 +                free(fb_save);
658 +                fb_save = NULL;
659 +        }
660 +        
661 +        // Unlock frame buffer (and continue MacOS thread)
662 +        UNLOCK_FRAME_BUFFER;
663 +        emul_suspended = false;
664 + }
665 + #endif
666 +
667 +
668   #ifdef ENABLE_FBDEV_DGA
669 + /*
670 + *  fbdev DGA display driver
671 + */
672 +
673 + const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
674 + const char FBDEVICE_FILE_NAME[] = "/dev/fb";
675 +
676 + class driver_fbdev : public driver_dga {
677 + public:
678 +        driver_fbdev(const video_mode &mode);
679 +        ~driver_fbdev();
680 + };
681 +
682 + // Open display
683 + driver_fbdev::driver_fbdev(const video_mode &mode)
684 + {
685 +        int width = mode.x, height = mode.y;
686 +
687 +        // Set absolute mouse mode
688 +        ADBSetRelMouseMode(false);
689 +        
690          // Find the maximum depth available
691          int ndepths, max_depth(0);
692          int *depths = XListDepths(x_display, screen, &ndepths);
693          if (depths == NULL) {
694                  printf("FATAL: Could not determine the maximal depth available\n");
695 <                return false;
695 >                return;
696          } else {
697                  while (ndepths-- > 0) {
698                          if (depths[ndepths] > max_depth)
# Line 526 | Line 709 | static bool init_fbdev_dga(char *in_fb_n
709                  char str[256];
710                  sprintf(str, GetString(STR_NO_FBDEVICE_FILE_ERR), fbd_path ? fbd_path : FBDEVICES_FILE_NAME, strerror(errno));
711                  ErrorAlert(str);
712 <                return false;
712 >                return;
713          }
714          
715          int fb_depth;           // supported depth
# Line 546 | Line 729 | static bool init_fbdev_dga(char *in_fb_n
729                          continue;
730                  
731                  if ((sscanf(line, "%19s %d %x", &fb_name, &fb_depth, &fb_offset) == 3)
732 <                && (strcmp(fb_name, in_fb_name) == 0) && (fb_depth == max_depth)) {
732 >                 && (strcmp(fb_name, fb_name) == 0) && (fb_depth == max_depth)) {
733                          device_found = true;
734                          break;
735                  }
# Line 558 | Line 741 | static bool init_fbdev_dga(char *in_fb_n
741          // Frame buffer name not found ? Then, display warning
742          if (!device_found) {
743                  char str[256];
744 <                sprintf(str, GetString(STR_FBDEV_NAME_ERR), in_fb_name, max_depth);
744 >                sprintf(str, GetString(STR_FBDEV_NAME_ERR), fb_name, max_depth);
745                  ErrorAlert(str);
746 <                return false;
746 >                return;
747          }
748          
566        int width = DisplayWidth(x_display, screen);
567        int height = DisplayHeight(x_display, screen);
568        depth = fb_depth; // max_depth
569        
570        // Set relative mouse mode
571        ADBSetRelMouseMode(false);
572        
749          // Create window
750          XSetWindowAttributes wattr;
751 <        wattr.override_redirect = True;
752 <        wattr.backing_store             = NotUseful;
753 <        wattr.background_pixel  = white_pixel;
754 <        wattr.border_pixel              = black_pixel;
579 <        wattr.event_mask                = eventmask = dga_eventmask;
751 >        wattr.event_mask = eventmask = dga_eventmask;
752 >        wattr.background_pixel = white_pixel;
753 >        wattr.override_redirect = True;
754 >        wattr.colormap = cmap[0];
755          
756 <        XSync(x_display, false);
582 <        the_win = XCreateWindow(x_display, rootwin,
756 >        w = XCreateWindow(x_display, rootwin,
757                  0, 0, width, height,
758                  0, xdepth, InputOutput, vis,
759 <                CWEventMask|CWBackPixel|CWBorderPixel|CWOverrideRedirect|CWBackingStore,
759 >                CWEventMask | CWBackPixel | CWOverrideRedirect | (fb_depth <= 8 ? CWColormap : 0),
760                  &wattr);
761 <        XSync(x_display, false);
762 <        XMapRaised(x_display, the_win);
763 <        XSync(x_display, false);
761 >
762 >        // Set window name/class
763 >        set_window_name(w, STR_WINDOW_TITLE);
764 >
765 >        // Indicate that we want keyboard input
766 >        set_window_focus(w);
767 >
768 >        // Show window
769 >        XMapRaised(x_display, w);
770 >        wait_mapped(w);
771          
772          // Grab mouse and keyboard
773 <        XGrabKeyboard(x_display, the_win, True,
773 >        XGrabKeyboard(x_display, w, True,
774                  GrabModeAsync, GrabModeAsync, CurrentTime);
775 <        XGrabPointer(x_display, the_win, True,
775 >        XGrabPointer(x_display, w, True,
776                  PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
777 <                GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime);
777 >                GrabModeAsync, GrabModeAsync, w, None, CurrentTime);
778          
779 <        // Set colormap
780 <        if (depth == 8)
600 <                XSetWindowColormap(x_display, the_win, cmap[0]);
601 <        
602 <        // Set VideoMonitor
603 <        int bytes_per_row = width;
604 <        switch (depth) {
605 <                case 1:
606 <                        bytes_per_row = ((width | 7) & ~7) >> 3;
607 <                        break;
608 <                case 15:
609 <                case 16:
610 <                        bytes_per_row *= 2;
611 <                        break;
612 <                case 24:
613 <                case 32:
614 <                        bytes_per_row *= 4;
615 <                        break;
616 <        }
779 >        // Calculate bytes per row
780 >        int bytes_per_row = TrivialBytesPerRow(mode.x, mode.depth);
781          
782 +        // Map frame buffer
783          if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
784                  if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
785                          char str[256];
786                          sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno));
787                          ErrorAlert(str);
788 <                        return false;
788 >                        return;
789                  }
790          }
791          
792   #if ENABLE_VOSF
793   #if REAL_ADDRESSING || DIRECT_ADDRESSING
794 <        // If the blit function is null, i.e. just a copy of the buffer,
795 <        // we first try to avoid the allocation of a temporary frame buffer
796 <        use_vosf = true;
632 <        do_update_framebuffer = GET_FBCOPY_FUNC(depth, true, DISPLAY_DGA);
633 <        if (do_update_framebuffer == FBCOPY_FUNC(fbcopy_raw))
634 <                use_vosf = false;
794 >        // Screen_blitter_init() returns TRUE if VOSF is mandatory
795 >        // i.e. the framebuffer update function is not Blit_Copy_Raw
796 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
797          
798          if (use_vosf) {
799 <                the_host_buffer = the_buffer;
800 <                the_buffer_size = align_on_page_boundary((height + 2) * bytes_per_row);
801 <                the_buffer_copy = (uint8 *)malloc(the_buffer_size);
802 <                memset(the_buffer_copy, 0, the_buffer_size);
803 <                the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
642 <                memset(the_buffer, 0, the_buffer_size);
799 >          // Allocate memory for frame buffer (SIZE is extended to page-boundary)
800 >          the_host_buffer = the_buffer;
801 >          the_buffer_size = page_extend((height + 2) * bytes_per_row);
802 >          the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
803 >          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
804          }
805   #else
806          use_vosf = false;
807   #endif
808   #endif
809          
810 <        set_video_monitor(width, height, bytes_per_row, true);
811 < #if REAL_ADDRESSING || DIRECT_ADDRESSING
812 <        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
813 < #else
814 <        VideoMonitor.mac_frame_base = MacFrameBaseMac;
815 < #endif
816 <        return true;
817 < #else
657 <        ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled.");
658 <        return false;
659 < #endif
810 >        // Set VideoMonitor
811 >        VideoModes[0].bytes_per_row = bytes_per_row;
812 >        VideoModes[0].depth = DepthModeForPixelDepth(fb_depth);
813 >        VideoMonitor.mode = mode;
814 >        set_mac_frame_buffer(mode.depth, true);
815 >
816 >        // Everything went well
817 >        init_ok = true;
818   }
819  
820 < // Init XF86 DGA display
821 < static bool init_xf86_dga(int width, int height)
820 > // Close display
821 > driver_fbdev::~driver_fbdev()
822   {
823 + }
824 + #endif
825 +
826 +
827   #ifdef ENABLE_XF86_DGA
828 + /*
829 + *  XFree86 DGA display driver
830 + */
831 +
832 + class driver_xf86dga : public driver_dga {
833 + public:
834 +        driver_xf86dga(const video_mode &mode);
835 +        ~driver_xf86dga();
836 +
837 +        void update_palette(void);
838 +        void resume(void);
839 +
840 + private:
841 +        int current_dga_cmap;                                   // Number (0 or 1) of currently installed DGA colormap
842 + };
843 +
844 + // Open display
845 + driver_xf86dga::driver_xf86dga(const video_mode &mode)
846 + : current_dga_cmap(0)
847 + {
848 +        int width = mode.x, height = mode.y;
849 +
850          // Set relative mouse mode
851          ADBSetRelMouseMode(true);
852  
# Line 678 | Line 862 | static bool init_xf86_dga(int width, int
862                  }
863                  XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
864                  XF86VidModeSetViewPort(x_display, screen, 0, 0);
865 +                XSync(x_display, false);
866          }
867   #endif
868  
869          // Create window
870          XSetWindowAttributes wattr;
871          wattr.event_mask = eventmask = dga_eventmask;
687        wattr.border_pixel = black_pixel;
872          wattr.override_redirect = True;
873  
874 <        XSync(x_display, false);
875 <        the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
876 <                InputOutput, vis, CWEventMask | CWBorderPixel | CWOverrideRedirect, &wattr);
877 <        XSync(x_display, false);
878 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
879 <        XMapRaised(x_display, the_win);
880 <        XSync(x_display, false);
874 >        w = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
875 >                InputOutput, vis, CWEventMask | CWOverrideRedirect, &wattr);
876 >
877 >        // Set window name/class
878 >        set_window_name(w, STR_WINDOW_TITLE);
879 >
880 >        // Indicate that we want keyboard input
881 >        set_window_focus(w);
882 >
883 >        // Show window
884 >        XMapRaised(x_display, w);
885 >        wait_mapped(w);
886  
887          // Establish direct screen connection
888 <        XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
888 >        XMoveResizeWindow(x_display, w, 0, 0, width, height);
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);
# Line 708 | Line 897 | static bool init_xf86_dga(int width, int
897          XF86DGASetVidPage(x_display, screen, 0);
898  
899          // Set colormap
900 <        if (depth == 8) {
901 <                XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
900 >        if (!IsDirectMode(mode)) {
901 >                XSetWindowColormap(x_display, w, cmap[current_dga_cmap = 0]);
902                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
903          }
904 +        XSync(x_display, false);
905  
906 <        // Set VideoMonitor
907 <        int bytes_per_row = (v_width + 7) & ~7;
908 <        switch (depth) {
719 <                case 1:
720 <                        bytes_per_row /= 8;
721 <                        break;
722 <                case 15:
723 <                case 16:
724 <                        bytes_per_row *= 2;
725 <                        break;
726 <                case 24:
727 <                case 32:
728 <                        bytes_per_row *= 4;
729 <                        break;
730 <        }
731 <        
906 >        // Init blitting routines
907 >        int bytes_per_row = TrivialBytesPerRow((v_width + 7) & ~7, mode.depth);
908 > #ifdef VIDEO_VOSF
909   #if REAL_ADDRESSING || DIRECT_ADDRESSING
910 <        // If the blit function is null, i.e. just a copy of the buffer,
911 <        // we first try to avoid the allocation of a temporary frame buffer
912 <        use_vosf = true;
736 <        do_update_framebuffer = GET_FBCOPY_FUNC(depth, true, DISPLAY_DGA);
737 <        if (do_update_framebuffer == FBCOPY_FUNC(fbcopy_raw))
738 <                use_vosf = false;
910 >        // Screen_blitter_init() returns TRUE if VOSF is mandatory
911 >        // i.e. the framebuffer update function is not Blit_Copy_Raw
912 >        use_vosf = Screen_blitter_init(&visualInfo, true, mode.depth);
913          
914          if (use_vosf) {
915 <                the_host_buffer = the_buffer;
916 <                the_buffer_size = align_on_page_boundary((height + 2) * bytes_per_row);
917 <                the_buffer_copy = (uint8 *)malloc(the_buffer_size);
918 <                memset(the_buffer_copy, 0, the_buffer_size);
919 <                the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
746 <                memset(the_buffer, 0, the_buffer_size);
915 >          // Allocate memory for frame buffer (SIZE is extended to page-boundary)
916 >          the_host_buffer = the_buffer;
917 >          the_buffer_size = page_extend((height + 2) * bytes_per_row);
918 >          the_buffer_copy = (uint8 *)vm_acquire(the_buffer_size);
919 >          the_buffer = (uint8 *)vm_acquire(the_buffer_size);
920          }
921 < #elif defined(ENABLE_VOSF)
749 <        // The UAE memory handlers will already handle color conversion, if needed.
921 > #else
922          use_vosf = false;
923   #endif
752        
753        set_video_monitor(width, height, bytes_per_row, true);
754 #if REAL_ADDRESSING || DIRECT_ADDRESSING
755        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
756 //      MacFrameLayout = FLAYOUT_DIRECT;
757 #else
758        VideoMonitor.mac_frame_base = MacFrameBaseMac;
924   #endif
925 <        return true;
926 < #else
927 <        ErrorAlert("Basilisk II has been compiled with XF86 DGA support disabled.");
928 <        return false;
925 >        
926 >        // Set VideoMonitor
927 >        const_cast<video_mode *>(&mode)->bytes_per_row = bytes_per_row;
928 >        VideoMonitor.mode = mode;
929 >        set_mac_frame_buffer(mode.depth, true);
930 >
931 >        // Everything went well
932 >        init_ok = true;
933 > }
934 >
935 > // Close display
936 > driver_xf86dga::~driver_xf86dga()
937 > {
938 >        XF86DGADirectVideo(x_display, screen, 0);
939 > #ifdef ENABLE_XF86_VIDMODE
940 >        if (has_vidmode)
941 >                XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
942   #endif
943   }
944  
945 + // Palette has changed
946 + void driver_xf86dga::update_palette(void)
947 + {
948 +        driver_dga::update_palette();
949 +        current_dga_cmap ^= 1;
950 +        if (!IsDirectMode(VideoMonitor.mode) && cmap[current_dga_cmap])
951 +                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
952 + }
953 +
954 + // Resume emulation
955 + void driver_xf86dga::resume(void)
956 + {
957 +        driver_dga::resume();
958 +        if (!IsDirectMode(VideoMonitor.mode))
959 +                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
960 + }
961 + #endif
962 +
963 +
964 + /*
965 + *  Initialization
966 + */
967 +
968   // Init keycode translation table
969   static void keycode_init(void)
970   {
# Line 829 | Line 1030 | static void keycode_init(void)
1030          }
1031   }
1032  
1033 < bool VideoInitBuffer()
1033 > // Open display for specified mode
1034 > static bool video_open(const video_mode &mode)
1035   {
1036 < #ifdef ENABLE_VOSF
1037 <        if (use_vosf) {
1038 <                const uint32 page_size  = getpagesize();
1039 <                const uint32 page_mask  = page_size - 1;
1040 <                
1041 <                mainBuffer.memBase      = (uint32) the_buffer;
1042 <                // Align the frame buffer on page boundary
1043 <                mainBuffer.memStart             = (uint32)((((unsigned long) the_buffer) + page_mask) & ~page_mask);
1044 <                mainBuffer.memLength    = the_buffer_size;
1045 <                mainBuffer.memEnd       = mainBuffer.memStart + mainBuffer.memLength;
1046 <
1047 <                mainBuffer.pageSize     = page_size;
1048 <                mainBuffer.pageCount    = (mainBuffer.memLength + page_mask)/mainBuffer.pageSize;
1049 <                mainBuffer.pageBits     = log_base_2(mainBuffer.pageSize);
1050 <
849 <                if (mainBuffer.dirtyPages != 0)
850 <                        free(mainBuffer.dirtyPages);
1036 >        // Load gray ramp to color map
1037 >        int num = (vis->c_class == DirectColor ? vis->map_entries : 256);
1038 >        for (int i=0; i<num; i++) {
1039 >                int c = (i * 256) / num;
1040 >                palette[i].red = c * 0x0101;
1041 >                palette[i].green = c * 0x0101;
1042 >                palette[i].blue = c * 0x0101;
1043 >                if (vis->c_class == PseudoColor)
1044 >                        palette[i].pixel = i;
1045 >                palette[i].flags = DoRed | DoGreen | DoBlue;
1046 >        }
1047 >        if (cmap[0] && cmap[1]) {
1048 >                XStoreColors(x_display, cmap[0], palette, num);
1049 >                XStoreColors(x_display, cmap[1], palette, num);
1050 >        }
1051  
1052 <                mainBuffer.dirtyPages = (uint8 *) malloc(mainBuffer.pageCount);
1052 > #ifdef ENABLE_VOSF
1053 >        // Load gray ramp to 8->16/32 expand map
1054 >        if (!IsDirectMode(mode) && (vis->c_class == TrueColor || vis->c_class == DirectColor))
1055 >                for (int i=0; i<256; i++)
1056 >                        ExpandMap[i] = map_rgb(i, i, i);
1057 > #endif
1058  
1059 <                if (mainBuffer.pageInfo != 0)
1060 <                        free(mainBuffer.pageInfo);
1059 >        // Create display driver object of requested type
1060 >        switch (display_type) {
1061 >                case DISPLAY_WINDOW:
1062 >                        drv = new driver_window(mode);
1063 >                        break;
1064 > #ifdef ENABLE_FBDEV_DGA
1065 >                case DISPLAY_DGA:
1066 >                        drv = new driver_fbdev(mode);
1067 >                        break;
1068 > #endif
1069 > #ifdef ENABLE_XF86_DGA
1070 >                case DISPLAY_DGA:
1071 >                        drv = new driver_xf86dga(mode);
1072 >                        break;
1073 > #endif
1074 >        }
1075 >        if (drv == NULL)
1076 >                return false;
1077 >        if (!drv->init_ok) {
1078 >                delete drv;
1079 >                drv = NULL;
1080 >                return false;
1081 >        }
1082  
1083 <                mainBuffer.pageInfo = (ScreenPageInfo *) malloc(mainBuffer.pageCount * sizeof(ScreenPageInfo));
1083 > #ifdef ENABLE_VOSF
1084 >        if (use_vosf) {
1085 >                // Initialize the mainBuffer structure
1086 >                if (!video_init_buffer()) {
1087 >                        ErrorAlert(STR_VOSF_INIT_ERR);
1088 >                return false;
1089 >                }
1090  
1091 <                if ((mainBuffer.dirtyPages == 0) || (mainBuffer.pageInfo == 0))
1091 >                // Initialize the handler for SIGSEGV
1092 >                if (!sigsegv_install_handler(screen_fault_handler)) {
1093 >                        ErrorAlert("Could not initialize Video on SEGV signals");
1094                          return false;
1095 +                }
1096 +        }
1097 + #endif
1098 +        
1099 +        // Initialize VideoRefresh function
1100 +        VideoRefreshInit();
1101  
1102 <                PFLAG_CLEAR_ALL;
1102 >        // Lock down frame buffer
1103 >        XSync(x_display, false);
1104 >        LOCK_FRAME_BUFFER;
1105  
1106 <                uint32 a = 0;
1107 <                for (int i = 0; i < mainBuffer.pageCount; i++) {
1108 <                        int y1 = a / VideoMonitor.bytes_per_row;
1109 <                        if (y1 >= VideoMonitor.y)
1110 <                                y1 = VideoMonitor.y - 1;
1111 <
1112 <                        int y2 = (a + mainBuffer.pageSize) / VideoMonitor.bytes_per_row;
871 <                        if (y2 >= VideoMonitor.y)
872 <                                y2 = VideoMonitor.y - 1;
873 <
874 <                        mainBuffer.pageInfo[i].top = y1;
875 <                        mainBuffer.pageInfo[i].bottom = y2;
876 <
877 <                        a += mainBuffer.pageSize;
878 <                        if (a > mainBuffer.memLength)
879 <                                a = mainBuffer.memLength;
880 <                }
881 <                
882 <                // We can now write-protect the frame buffer
883 <                if (mprotect((caddr_t)mainBuffer.memStart, mainBuffer.memLength, PROT_READ) != 0)
884 <                        return false;
1106 >        // Start redraw/input thread
1107 > #ifdef HAVE_PTHREADS
1108 >        redraw_thread_cancel = false;
1109 >        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1110 >        if (!redraw_thread_active) {
1111 >                printf("FATAL: cannot create redraw thread\n");
1112 >                return false;
1113          }
1114 + #else
1115 +        redraw_thread_active = true;
1116   #endif
1117 +
1118          return true;
1119   }
1120  
1121   bool VideoInit(bool classic)
1122   {
1123 +        classic_mode = classic;
1124 +
1125   #ifdef ENABLE_VOSF
893        // Open /dev/zero
894        zero_fd = open("/dev/zero", O_RDWR);
895        if (zero_fd < 0) {
896        char str[256];
897                sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
898                ErrorAlert(str);
899        return false;
900        }
901        
1126          // Zero the mainBuffer structure
1127 <        mainBuffer.dirtyPages = 0;
1128 <        mainBuffer.pageInfo = 0;
1127 >        mainBuffer.dirtyPages = NULL;
1128 >        mainBuffer.pageInfo = NULL;
1129   #endif
1130          
1131          // Check if X server runs on local machine
# Line 912 | Line 1136 | bool VideoInit(bool classic)
1136          keycode_init();
1137  
1138          // Read prefs
1139 <        mouse_wheel_mode = PrefsFindInt16("mousewheelmode");
1140 <        mouse_wheel_lines = PrefsFindInt16("mousewheellines");
1139 >        frame_skip = PrefsFindInt32("frameskip");
1140 >        mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1141 >        mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1142  
1143          // Find screen and root window
1144          screen = XDefaultScreen(x_display);
# Line 926 | Line 1151 | bool VideoInit(bool classic)
1151          // Frame buffer name
1152          char fb_name[20];
1153          
1154 <        // Could do fbdev dga ?
1154 >        // Could do fbdev DGA?
1155          if ((fbdev_fd = open(FBDEVICE_FILE_NAME, O_RDWR)) != -1)
1156                  has_dga = true;
1157          else
# Line 972 | Line 1197 | bool VideoInit(bool classic)
1197                  case 15:
1198                  case 16:
1199                  case 24:
1200 <                case 32:
1201 <                        color_class = TrueColor;
1200 >                case 32: // Try DirectColor first, as this will allow gamma correction
1201 >                        color_class = DirectColor;
1202 >                        if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo))
1203 >                                color_class = TrueColor;
1204                          break;
1205                  default:
1206 <                        ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
1206 >                        ErrorAlert(STR_UNSUPP_DEPTH_ERR);
1207                          return false;
1208          }
1209          if (!XMatchVisualInfo(x_display, screen, xdepth, color_class, &visualInfo)) {
1210 <                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
1210 >                ErrorAlert(STR_NO_XVISUAL_ERR);
1211                  return false;
1212          }
1213          if (visualInfo.depth != xdepth) {
1214 <                ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
1214 >                ErrorAlert(STR_NO_XVISUAL_ERR);
1215                  return false;
1216          }
1217          vis = visualInfo.visual;
1218  
1219 <        // Mac screen depth is always 1 bit in Classic mode, but follows X depth otherwise
1220 <        classic_mode = classic;
994 <        if (classic)
995 <                depth = 1;
996 <        else
997 <                depth = xdepth;
998 <
999 <        // Create color maps for 8 bit mode
1000 <        if (depth == 8) {
1219 >        // Create color maps
1220 >        if (color_class == PseudoColor || color_class == DirectColor) {
1221                  cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1222                  cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
1223 <                XInstallColormap(x_display, cmap[0]);
1224 <                XInstallColormap(x_display, cmap[1]);
1223 >        }
1224 >
1225 >        // Find pixel format of direct modes
1226 >        if (color_class == DirectColor || color_class == TrueColor) {
1227 >                rshift = gshift = bshift = 0;
1228 >                rloss = gloss = bloss = 8;
1229 >                uint32 mask;
1230 >                for (mask=vis->red_mask; !(mask&1); mask>>=1)
1231 >                        ++rshift;
1232 >                for (; mask&1; mask>>=1)
1233 >                        --rloss;
1234 >                for (mask=vis->green_mask; !(mask&1); mask>>=1)
1235 >                        ++gshift;
1236 >                for (; mask&1; mask>>=1)
1237 >                        --gloss;
1238 >                for (mask=vis->blue_mask; !(mask&1); mask>>=1)
1239 >                        ++bshift;
1240 >                for (; mask&1; mask>>=1)
1241 >                        --bloss;
1242 >        }
1243 >
1244 >        // Preset palette pixel values for gamma table
1245 >        if (color_class == DirectColor) {
1246 >                int num = vis->map_entries;
1247 >                for (int i=0; i<num; i++) {
1248 >                        int c = (i * 256) / num;
1249 >                        palette[i].pixel = map_rgb(c, c, c);
1250 >                }
1251          }
1252  
1253          // Get screen mode from preferences
1254          const char *mode_str;
1255 <        if (classic)
1255 >        if (classic_mode)
1256                  mode_str = "win/512/342";
1257          else
1258                  mode_str = PrefsFindString("screen");
1259  
1260 <        // Determine type and mode
1261 <        int width = 512, height = 384;
1260 >        // Determine display type and default dimensions
1261 >        int default_width = 512, default_height = 384;
1262          display_type = DISPLAY_WINDOW;
1263          if (mode_str) {
1264 <                if (sscanf(mode_str, "win/%d/%d", &width, &height) == 2)
1264 >                if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2) {
1265                          display_type = DISPLAY_WINDOW;
1266   #ifdef ENABLE_FBDEV_DGA
1267 <                else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1268 < #else
1269 <                else if (has_dga && sscanf(mode_str, "dga/%d/%d", &width, &height) == 2) {
1267 >                } else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1268 >                        display_type = DISPLAY_DGA;
1269 >                        default_width = -1; default_height = -1; // use entire screen
1270   #endif
1271 + #ifdef ENABLE_XF86_DGA
1272 +                } else if (has_dga && sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2) {
1273                          display_type = DISPLAY_DGA;
1026                        if (width > DisplayWidth(x_display, screen))
1027                                width = DisplayWidth(x_display, screen);
1028                        if (height > DisplayHeight(x_display, screen))
1029                                height = DisplayHeight(x_display, screen);
1030                }
1031                if (width <= 0)
1032                        width = DisplayWidth(x_display, screen);
1033                if (height <= 0)
1034                        height = DisplayHeight(x_display, screen);
1035        }
1036
1037        // Initialize according to display type
1038        switch (display_type) {
1039                case DISPLAY_WINDOW:
1040                        if (!init_window(width, height))
1041                                return false;
1042                        break;
1043                case DISPLAY_DGA:
1044 #ifdef ENABLE_FBDEV_DGA
1045                        if (!init_fbdev_dga(fb_name))
1046 #else
1047                        if (!init_xf86_dga(width, height))
1274   #endif
1275 <                                return false;
1050 <                        break;
1275 >                }
1276          }
1277 +        if (default_width <= 0)
1278 +                default_width = DisplayWidth(x_display, screen);
1279 +        else if (default_width > DisplayWidth(x_display, screen))
1280 +                default_width = DisplayWidth(x_display, screen);
1281 +        if (default_height <= 0)
1282 +                default_height = DisplayHeight(x_display, screen);
1283 +        else if (default_height > DisplayHeight(x_display, screen))
1284 +                default_height = DisplayHeight(x_display, screen);
1285  
1286 < #ifdef HAVE_PTHREADS
1287 <        // Lock down frame buffer
1055 <        pthread_mutex_lock(&frame_buffer_lock);
1056 < #endif
1057 <
1058 < #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
1059 <        // Set variables for UAE memory mapping
1060 <        MacFrameBaseHost = the_buffer;
1061 <        MacFrameSize = VideoMonitor.bytes_per_row * VideoMonitor.y;
1062 <
1063 <        // No special frame buffer in Classic mode (frame buffer is in Mac RAM)
1064 <        if (classic)
1065 <                MacFrameLayout = FLAYOUT_NONE;
1066 < #endif
1286 >        // Mac screen depth follows X depth
1287 >        video_depth default_depth = DepthModeForPixelDepth(xdepth);
1288  
1289 +        // Construct list of supported modes
1290 +        if (display_type == DISPLAY_WINDOW) {
1291 +                if (classic)
1292 +                        add_mode(512, 342, 0x80, 64, VDEPTH_1BIT);
1293 +                else {
1294 +                        if (default_depth != VDEPTH_1BIT) { // 1-bit modes are always available
1295 +                                add_mode(512, 384, 0x80, TrivialBytesPerRow(512, VDEPTH_1BIT), VDEPTH_1BIT);
1296 +                                add_mode(640, 480, 0x81, TrivialBytesPerRow(640, VDEPTH_1BIT), VDEPTH_1BIT);
1297 +                                add_mode(800, 600, 0x82, TrivialBytesPerRow(800, VDEPTH_1BIT), VDEPTH_1BIT);
1298 +                                add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, VDEPTH_1BIT), VDEPTH_1BIT);
1299 +                                add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, VDEPTH_1BIT), VDEPTH_1BIT);
1300 +                                add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, VDEPTH_1BIT), VDEPTH_1BIT);
1301 +                                add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, VDEPTH_1BIT), VDEPTH_1BIT);
1302 +                        }
1303   #ifdef ENABLE_VOSF
1304 <        if (use_vosf) {
1305 <                // Initialize the mainBuffer structure
1306 <                if (!VideoInitBuffer()) {
1307 <                        // TODO: STR_VOSF_INIT_ERR ?
1308 <                        ErrorAlert("Could not initialize Video on SEGV signals");
1309 <                return false;
1304 >                        if (default_depth > VDEPTH_8BIT) { // 8-bit modes are also possible on 16/32-bit screens with VOSF blitters
1305 >                                add_mode(512, 384, 0x80, TrivialBytesPerRow(512, VDEPTH_8BIT), VDEPTH_8BIT);
1306 >                                add_mode(640, 480, 0x81, TrivialBytesPerRow(640, VDEPTH_8BIT), VDEPTH_8BIT);
1307 >                                add_mode(800, 600, 0x82, TrivialBytesPerRow(800, VDEPTH_8BIT), VDEPTH_8BIT);
1308 >                                add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, VDEPTH_8BIT), VDEPTH_8BIT);
1309 >                                add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, VDEPTH_8BIT), VDEPTH_8BIT);
1310 >                                add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, VDEPTH_8BIT), VDEPTH_8BIT);
1311 >                                add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, VDEPTH_8BIT), VDEPTH_8BIT);
1312 >                        }
1313 > #endif
1314 >                        add_mode(512, 384, 0x80, TrivialBytesPerRow(512, default_depth), default_depth);
1315 >                        add_mode(640, 480, 0x81, TrivialBytesPerRow(640, default_depth), default_depth);
1316 >                        add_mode(800, 600, 0x82, TrivialBytesPerRow(800, default_depth), default_depth);
1317 >                        add_mode(1024, 768, 0x83, TrivialBytesPerRow(1024, default_depth), default_depth);
1318 >                        add_mode(1152, 870, 0x84, TrivialBytesPerRow(1152, default_depth), default_depth);
1319 >                        add_mode(1280, 1024, 0x85, TrivialBytesPerRow(1280, default_depth), default_depth);
1320 >                        add_mode(1600, 1200, 0x86, TrivialBytesPerRow(1600, default_depth), default_depth);
1321                  }
1322 +        } else
1323 +                add_mode(default_width, default_height, 0x80, TrivialBytesPerRow(default_width, default_depth), default_depth);
1324  
1325 <                // Initialize the handler for SIGSEGV
1326 <                if (!Screen_fault_handler_init()) {
1327 <                        // TODO: STR_VOSF_INIT_ERR ?
1328 <                        ErrorAlert("Could not initialize Video on SEGV signals");
1329 <                        return false;
1325 >        // Find requested default mode and open display
1326 >        if (VideoModes.size() == 1)
1327 >                return video_open(VideoModes[0]);
1328 >        else {
1329 >                // Find mode with specified dimensions
1330 >                std::vector<video_mode>::const_iterator i, end = VideoModes.end();
1331 >                for (i = VideoModes.begin(); i != end; ++i) {
1332 >                        if (i->x == default_width && i->y == default_height && i->depth == default_depth)
1333 >                                return video_open(*i);
1334                  }
1335 +                return video_open(VideoModes[0]);
1336          }
1084 #endif
1085        
1086        // Initialize VideoRefresh function
1087        VideoRefreshInit();
1088        
1089        XSync(x_display, false);
1090
1091 #ifdef HAVE_PTHREADS
1092        // Start redraw/input thread
1093        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1094        if (!redraw_thread_active) {
1095                printf("FATAL: cannot create redraw thread\n");
1096                return false;
1097        }
1098 #endif
1099        return true;
1337   }
1338  
1339  
# Line 1104 | Line 1341 | bool VideoInit(bool classic)
1341   *  Deinitialization
1342   */
1343  
1344 < void VideoExit(void)
1344 > // Close display
1345 > static void video_close(void)
1346   {
1109 #ifdef HAVE_PTHREADS
1347          // Stop redraw thread
1348 + #ifdef HAVE_PTHREADS
1349          if (redraw_thread_active) {
1350                  redraw_thread_cancel = true;
1351   #ifdef HAVE_PTHREAD_CANCEL
1352                  pthread_cancel(redraw_thread);
1353   #endif
1354                  pthread_join(redraw_thread, NULL);
1117                redraw_thread_active = false;
1355          }
1356   #endif
1357 +        redraw_thread_active = false;
1358  
1121 #ifdef HAVE_PTHREADS
1359          // Unlock frame buffer
1360 <        pthread_mutex_unlock(&frame_buffer_lock);
1361 < #endif
1125 <
1126 <        // Close window and server connection
1127 <        if (x_display != NULL) {
1128 <                XSync(x_display, false);
1129 <
1130 < #ifdef ENABLE_XF86_DGA
1131 <                if (display_type == DISPLAY_DGA) {
1132 <                        XF86DGADirectVideo(x_display, screen, 0);
1133 <                        XUngrabPointer(x_display, CurrentTime);
1134 <                        XUngrabKeyboard(x_display, CurrentTime);
1135 <                }
1136 < #endif
1137 <
1138 < #ifdef ENABLE_XF86_VIDMODE
1139 <                if (has_vidmode && display_type == DISPLAY_DGA)
1140 <                        XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1141 < #endif
1142 <
1143 < #ifdef ENABLE_FBDEV_DGA
1144 <                if (display_type == DISPLAY_DGA) {
1145 <                        XUngrabPointer(x_display, CurrentTime);
1146 <                        XUngrabKeyboard(x_display, CurrentTime);
1147 <                        close(fbdev_fd);
1148 <                }
1149 < #endif
1150 <
1151 <                XFlush(x_display);
1152 <                XSync(x_display, false);
1153 <                if (depth == 8) {
1154 <                        XFreeColormap(x_display, cmap[0]);
1155 <                        XFreeColormap(x_display, cmap[1]);
1156 <                }
1157 <                
1158 <                if (!use_vosf) {
1159 <                        if (the_buffer) {
1160 <                                free(the_buffer);
1161 <                                the_buffer = NULL;
1162 <                        }
1360 >        UNLOCK_FRAME_BUFFER;
1361 >        XSync(x_display, false);
1362  
1164                        if (!have_shm && the_buffer_copy) {
1165                                free(the_buffer_copy);
1166                                the_buffer_copy = NULL;
1167                        }
1168                }
1169 #ifdef ENABLE_VOSF
1170                else {
1171                        if (the_buffer != (uint8 *)MAP_FAILED) {
1172                                munmap((caddr_t)the_buffer, the_buffer_size);
1173                                the_buffer = 0;
1174                        }
1175                        
1176                        if (the_buffer_copy != (uint8 *)MAP_FAILED) {
1177                                munmap((caddr_t)the_buffer_copy, the_buffer_size);
1178                                the_buffer_copy = 0;
1179                        }
1180                }
1181 #endif
1182        }
1183        
1363   #ifdef ENABLE_VOSF
1364 +        // Deinitialize VOSF
1365          if (use_vosf) {
1186                // Clear mainBuffer data
1366                  if (mainBuffer.pageInfo) {
1367                          free(mainBuffer.pageInfo);
1368 <                        mainBuffer.pageInfo = 0;
1368 >                        mainBuffer.pageInfo = NULL;
1369                  }
1191
1370                  if (mainBuffer.dirtyPages) {
1371                          free(mainBuffer.dirtyPages);
1372 <                        mainBuffer.dirtyPages = 0;
1372 >                        mainBuffer.dirtyPages = NULL;
1373                  }
1374          }
1375 + #endif
1376 +
1377 +        // Close display
1378 +        delete drv;
1379 +        drv = NULL;
1380 + }
1381 +
1382 + void VideoExit(void)
1383 + {
1384 +        // Close display
1385 +        video_close();
1386 +
1387 +        // Free colormaps
1388 +        if (cmap[0]) {
1389 +                XFreeColormap(x_display, cmap[0]);
1390 +                cmap[0] = 0;
1391 +        }
1392 +        if (cmap[1]) {
1393 +                XFreeColormap(x_display, cmap[1]);
1394 +                cmap[1] = 0;
1395 +        }
1396  
1397 <        // Close /dev/zero
1398 <        if (zero_fd > 0)
1399 <                close(zero_fd);
1397 > #ifdef ENABLE_XF86_VIDMODE
1398 >        // Free video mode list
1399 >        if (x_video_modes) {
1400 >                XFree(x_video_modes);
1401 >                x_video_modes = NULL;
1402 >        }
1403 > #endif
1404 >
1405 > #ifdef ENABLE_FBDEV_DGA
1406 >        // Close framebuffer device
1407 >        if (fbdev_fd >= 0) {
1408 >                close(fbdev_fd);
1409 >                fbdev_fd = -1;
1410 >        }
1411   #endif
1412   }
1413  
# Line 1209 | Line 1419 | void VideoExit(void)
1419   void VideoQuitFullScreen(void)
1420   {
1421          D(bug("VideoQuitFullScreen()\n"));
1422 <        if (display_type == DISPLAY_DGA)
1213 <                quit_full_screen = true;
1422 >        quit_full_screen = true;
1423   }
1424  
1425  
# Line 1224 | Line 1433 | void VideoInterrupt(void)
1433          if (emerg_quit)
1434                  QuitEmulator();
1435  
1227 #ifdef HAVE_PTHREADS
1436          // Temporarily give up frame buffer lock (this is the point where
1437          // we are suspended when the user presses Ctrl-Tab)
1438 <        pthread_mutex_unlock(&frame_buffer_lock);
1439 <        pthread_mutex_lock(&frame_buffer_lock);
1232 < #endif
1438 >        UNLOCK_FRAME_BUFFER;
1439 >        LOCK_FRAME_BUFFER;
1440   }
1441  
1442  
# Line 1239 | Line 1446 | void VideoInterrupt(void)
1446  
1447   void video_set_palette(uint8 *pal)
1448   {
1449 < #ifdef HAVE_PTHREDS
1243 <        pthread_mutex_lock(&palette_lock);
1244 < #endif
1449 >        LOCK_PALETTE;
1450  
1451          // Convert colors to XColor array
1452 <        for (int i=0; i<256; i++) {
1453 <                palette[i].pixel = i;
1454 <                palette[i].red = pal[i*3] * 0x0101;
1455 <                palette[i].green = pal[i*3+1] * 0x0101;
1456 <                palette[i].blue = pal[i*3+2] * 0x0101;
1457 <                palette[i].flags = DoRed | DoGreen | DoBlue;
1452 >        int num_in = 256, num_out = 256;
1453 >        if (VideoMonitor.mode.depth == VDEPTH_16BIT)
1454 >                num_in = 32;
1455 >        if (IsDirectMode(VideoMonitor.mode)) {
1456 >                // If X is in 565 mode we have to stretch the palette from 32 to 64 entries
1457 >                num_out = vis->map_entries;
1458 >        }
1459 >        XColor *p = palette;
1460 >        for (int i=0; i<num_out; i++) {
1461 >                int c = (i * num_in) / num_out;
1462 >                p->red = pal[c*3 + 0] * 0x0101;
1463 >                p->green = pal[c*3 + 1] * 0x0101;
1464 >                p->blue = pal[c*3 + 2] * 0x0101;
1465 >                if (vis->c_class == PseudoColor)
1466 >                        p->pixel = i;
1467 >                p->flags = DoRed | DoGreen | DoBlue;
1468 >                p++;
1469          }
1470  
1471 + #ifdef ENABLE_VOSF
1472 +        // Recalculate pixel color expansion map
1473 +        if (!IsDirectMode(VideoMonitor.mode) && (vis->c_class == TrueColor || vis->c_class == DirectColor)) {
1474 +                for (int i=0; i<256; i++)
1475 +                        ExpandMap[i] = map_rgb(pal[i*3+0], pal[i*3+1], pal[i*3+2]);
1476 +
1477 +                // We have to redraw everything because the interpretation of pixel values changed
1478 +                LOCK_VOSF;
1479 +                PFLAG_SET_ALL;
1480 +                UNLOCK_VOSF;
1481 +                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1482 +        }
1483 + #endif
1484 +
1485          // Tell redraw thread to change palette
1486          palette_changed = true;
1487  
1488 < #ifdef HAVE_PTHREADS
1259 <        pthread_mutex_unlock(&palette_lock);
1260 < #endif
1488 >        UNLOCK_PALETTE;
1489   }
1490  
1491  
1492   /*
1493 < *  Suspend/resume emulator
1493 > *  Switch video mode
1494   */
1495  
1496 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1269 < static void suspend_emul(void)
1496 > void video_switch_to_mode(const video_mode &mode)
1497   {
1498 <        if (display_type == DISPLAY_DGA) {
1499 <                // Release ctrl key
1500 <                ADBKeyUp(0x36);
1274 <                ctrl_down = false;
1275 <
1276 < #ifdef HAVE_PTHREADS
1277 <                // Lock frame buffer (this will stop the MacOS thread)
1278 <                pthread_mutex_lock(&frame_buffer_lock);
1279 < #endif
1280 <
1281 <                // Save frame buffer
1282 <                fb_save = malloc(VideoMonitor.y * VideoMonitor.bytes_per_row);
1283 <                if (fb_save)
1284 <                        memcpy(fb_save, the_buffer, VideoMonitor.y * VideoMonitor.bytes_per_row);
1285 <
1286 <                // Close full screen display
1287 < #ifdef ENABLE_XF86_DGA
1288 <                XF86DGADirectVideo(x_display, screen, 0);
1289 < #endif
1290 <                XUngrabPointer(x_display, CurrentTime);
1291 <                XUngrabKeyboard(x_display, CurrentTime);
1292 <                XUnmapWindow(x_display, the_win);
1293 <                XSync(x_display, false);
1498 >        // Close and reopen display
1499 >        video_close();
1500 >        video_open(mode);
1501  
1502 <                // Open "suspend" window
1503 <                XSetWindowAttributes wattr;
1504 <                wattr.event_mask = KeyPressMask;
1298 <                wattr.background_pixel = black_pixel;
1299 <                wattr.border_pixel = black_pixel;
1300 <                wattr.backing_store = Always;
1301 <                wattr.backing_planes = xdepth;
1302 <                wattr.colormap = DefaultColormap(x_display, screen);
1303 <                
1304 <                XSync(x_display, false);
1305 <                suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1306 <                        InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
1307 <                        CWBackingStore | CWBackingPlanes | (xdepth == 8 ? CWColormap : 0), &wattr);
1308 <                XSync(x_display, false);
1309 <                XStoreName(x_display, suspend_win, GetString(STR_SUSPEND_WINDOW_TITLE));
1310 <                XMapRaised(x_display, suspend_win);
1311 <                XSync(x_display, false);
1312 <                emul_suspended = true;
1313 <        }
1314 < }
1315 <
1316 < static void resume_emul(void)
1317 < {
1318 <        // Close "suspend" window
1319 <        XDestroyWindow(x_display, suspend_win);
1320 <        XSync(x_display, false);
1321 <
1322 <        // Reopen full screen display
1323 <        XMapRaised(x_display, the_win);
1324 <        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1325 <        XSync(x_display, false);
1326 <        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1327 <        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1328 < #ifdef ENABLE_XF86_DGA
1329 <        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1330 <        XF86DGASetViewPort(x_display, screen, 0, 0);
1331 < #endif
1332 <        XSync(x_display, false);
1333 <        
1334 <        // the_buffer already contains the data to restore. i.e. since a temporary
1335 <        // frame buffer is used when VOSF is actually used, fb_save is therefore
1336 <        // not necessary.
1337 < #ifdef ENABLE_VOSF
1338 <        if (use_vosf) {
1339 < #ifdef HAVE_PTHREADS
1340 <                pthread_mutex_lock(&Screen_draw_lock);
1341 < #endif
1342 <                PFLAG_SET_ALL;
1343 < #ifdef HAVE_PTHREADS
1344 <                pthread_mutex_unlock(&Screen_draw_lock);
1345 < #endif
1346 <                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1347 <        }
1348 < #endif
1349 <        
1350 <        // Restore frame buffer
1351 <        if (fb_save) {
1352 < #ifdef ENABLE_VOSF
1353 <                // Don't copy fb_save to the temporary frame buffer in VOSF mode
1354 <                if (!use_vosf)
1355 < #endif
1356 <                memcpy(the_buffer, fb_save, VideoMonitor.y * VideoMonitor.bytes_per_row);
1357 <                free(fb_save);
1358 <                fb_save = NULL;
1502 >        if (drv == NULL) {
1503 >                ErrorAlert(STR_OPEN_WINDOW_ERR);
1504 >                QuitEmulator();
1505          }
1360        
1361 #ifdef ENABLE_XF86_DGA
1362        if (depth == 8)
1363                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1364 #endif
1365
1366 #ifdef HAVE_PTHREADS
1367        // Unlock frame buffer (and continue MacOS thread)
1368        pthread_mutex_unlock(&frame_buffer_lock);
1369        emul_suspended = false;
1370 #endif
1506   }
1372 #endif
1507  
1508  
1509   /*
# Line 1430 | Line 1564 | static int kc_decode(KeySym ks)
1564                  case XK_slash: case XK_question: return 0x2c;
1565  
1566   #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1567 <                case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1567 >                case XK_Tab: if (ctrl_down) {drv->suspend(); return -1;} else return 0x30;
1568   #else
1569                  case XK_Tab: return 0x30;
1570   #endif
# Line 1521 | Line 1655 | static int kc_decode(KeySym ks)
1655          return -1;
1656   }
1657  
1658 < static int event2keycode(XKeyEvent *ev)
1658 > static int event2keycode(XKeyEvent &ev)
1659   {
1660          KeySym ks;
1661          int as;
1662          int i = 0;
1663  
1664          do {
1665 <                ks = XLookupKeysym(ev, i++);
1665 >                ks = XLookupKeysym(&ev, i++);
1666                  as = kc_decode(ks);
1667                  if (as != -1)
1668                          return as;
# Line 1544 | Line 1678 | static int event2keycode(XKeyEvent *ev)
1678  
1679   static void handle_events(void)
1680   {
1681 <        XEvent event;
1682 <        for (;;) {
1683 <                if (!XCheckMaskEvent(x_display, eventmask, &event))
1550 <                        break;
1681 >        while (XPending(x_display)) {
1682 >                XEvent event;
1683 >                XNextEvent(x_display, &event);
1684  
1685                  switch (event.type) {
1686                          // Mouse button
1687                          case ButtonPress: {
1688 <                                unsigned int button = ((XButtonEvent *)&event)->button;
1688 >                                unsigned int button = event.xbutton.button;
1689                                  if (button < 4)
1690                                          ADBMouseDown(button - 1);
1691                                  else if (button < 6) {  // Wheel mouse
# Line 1571 | Line 1704 | static void handle_events(void)
1704                                  break;
1705                          }
1706                          case ButtonRelease: {
1707 <                                unsigned int button = ((XButtonEvent *)&event)->button;
1707 >                                unsigned int button = event.xbutton.button;
1708                                  if (button < 4)
1709                                          ADBMouseUp(button - 1);
1710                                  break;
# Line 1579 | Line 1712 | static void handle_events(void)
1712  
1713                          // Mouse moved
1714                          case EnterNotify:
1582                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1583                                break;
1715                          case MotionNotify:
1716 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1716 >                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1717                                  break;
1718  
1719                          // Keyboard
1720                          case KeyPress: {
1721                                  int code;
1722                                  if (use_keycodes) {
1723 <                                        event2keycode((XKeyEvent *)&event);     // This is called to process the hotkeys
1724 <                                        code = keycode_table[((XKeyEvent *)&event)->keycode & 0xff];
1723 >                                        event2keycode(event.xkey);      // This is called to process the hotkeys
1724 >                                        code = keycode_table[event.xkey.keycode & 0xff];
1725                                  } else
1726 <                                        code = event2keycode((XKeyEvent *)&event);
1726 >                                        code = event2keycode(event.xkey);
1727                                  if (code != -1) {
1728                                          if (!emul_suspended) {
1729                                                  if (code == 0x39) {     // Caps Lock pressed
# Line 1608 | Line 1739 | static void handle_events(void)
1739                                                  if (code == 0x36)
1740                                                          ctrl_down = true;
1741                                          } else {
1611 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1742                                                  if (code == 0x31)
1743 <                                                        resume_emul();  // Space wakes us up
1614 < #endif
1743 >                                                        drv->resume();  // Space wakes us up
1744                                          }
1745                                  }
1746                                  break;
# Line 1619 | Line 1748 | static void handle_events(void)
1748                          case KeyRelease: {
1749                                  int code;
1750                                  if (use_keycodes) {
1751 <                                        event2keycode((XKeyEvent *)&event);     // This is called to process the hotkeys
1752 <                                        code = keycode_table[((XKeyEvent *)&event)->keycode & 0xff];
1751 >                                        event2keycode(event.xkey);      // This is called to process the hotkeys
1752 >                                        code = keycode_table[event.xkey.keycode & 0xff];
1753                                  } else
1754 <                                        code = event2keycode((XKeyEvent *)&event);
1754 >                                        code = event2keycode(event.xkey);
1755                                  if (code != -1 && code != 0x39) {       // Don't propagate Caps Lock releases
1756                                          ADBKeyUp(code);
1757                                          if (code == 0x36)
# Line 1636 | Line 1765 | static void handle_events(void)
1765                                  if (display_type == DISPLAY_WINDOW) {
1766   #ifdef ENABLE_VOSF
1767                                          if (use_vosf) {                 // VOSF refresh
1768 < #ifdef HAVE_PTHREADS
1640 <                                                pthread_mutex_lock(&Screen_draw_lock);
1641 < #endif
1768 >                                                LOCK_VOSF;
1769                                                  PFLAG_SET_ALL;
1770 < #ifdef HAVE_PTHREADS
1771 <                                                pthread_mutex_unlock(&Screen_draw_lock);
1645 < #endif
1646 <                                                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1770 >                                                UNLOCK_VOSF;
1771 >                                                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1772                                          }
1773                                          else
1774   #endif
# Line 1654 | Line 1779 | static void handle_events(void)
1779                                                          updt_box[x1][y1] = true;
1780                                                  nr_boxes = 16 * 16;
1781                                          } else                                  // Static refresh
1782 <                                                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1782 >                                                memset(the_buffer_copy, 0, VideoMonitor.mode.bytes_per_row * VideoMonitor.mode.y);
1783                                  }
1784                                  break;
1785  
1786 <                        case FocusIn:
1787 <                        case FocusOut:
1786 >                        // Window "close" widget clicked
1787 >                        case ClientMessage:
1788 >                                if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
1789 >                                        ADBKeyDown(0x7f);       // Power key
1790 >                                        ADBKeyUp(0x7f);
1791 >                                }
1792                                  break;
1793                  }
1794          }
# Line 1671 | Line 1800 | static void handle_events(void)
1800   */
1801  
1802   // Dynamic display update (variable frame rate for each box)
1803 < static void update_display_dynamic(int ticker)
1803 > static void update_display_dynamic(int ticker, driver_window *drv)
1804   {
1805          int y1, y2, y2s, y2a, i, x1, xm, xmo, ymo, yo, yi, yil, xi;
1806          int xil = 0;
1807          int rxm = 0, rxmo = 0;
1808 <        int bytes_per_row = VideoMonitor.bytes_per_row;
1809 <        int bytes_per_pixel = VideoMonitor.bytes_per_row / VideoMonitor.x;
1810 <        int rx = VideoMonitor.bytes_per_row / 16;
1811 <        int ry = VideoMonitor.y / 16;
1808 >        int bytes_per_row = VideoMonitor.mode.bytes_per_row;
1809 >        int bytes_per_pixel = VideoMonitor.mode.bytes_per_row / VideoMonitor.mode.x;
1810 >        int rx = VideoMonitor.mode.bytes_per_row / 16;
1811 >        int ry = VideoMonitor.mode.y / 16;
1812          int max_box;
1813  
1814          y2s = sm_uptd[ticker % 8];
# Line 1733 | Line 1862 | static void update_display_dynamic(int t
1862                                          i = (yi * bytes_per_row) + xi;
1863                                          for (y2=0; y2 < yil; y2++, i += bytes_per_row)
1864                                                  memcpy(&the_buffer_copy[i], &the_buffer[i], xil);
1865 <                                        if (depth == 1) {
1866 <                                                if (have_shm)
1867 <                                                        XShmPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
1865 >                                        if (VideoMonitor.mode.depth == VDEPTH_1BIT) {
1866 >                                                if (drv->have_shm)
1867 >                                                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
1868                                                  else
1869 <                                                        XPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
1869 >                                                        XPutImage(x_display, drv->w, drv->gc, drv->img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
1870                                          } else {
1871 <                                                if (have_shm)
1872 <                                                        XShmPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0);
1871 >                                                if (drv->have_shm)
1872 >                                                        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);
1873                                                  else
1874 <                                                        XPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
1874 >                                                        XPutImage(x_display, drv->w, drv->gc, drv->img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
1875                                          }
1876                                          xil = 0;
1877                                  }
# Line 1761 | Line 1890 | static void update_display_dynamic(int t
1890   }
1891  
1892   // Static display update (fixed frame rate, but incremental)
1893 < static void update_display_static(void)
1893 > static void update_display_static(driver_window *drv)
1894   {
1895          // Incremental update code
1896          int wide = 0, high = 0, x1, x2, y1, y2, i, j;
1897 <        int bytes_per_row = VideoMonitor.bytes_per_row;
1898 <        int bytes_per_pixel = VideoMonitor.bytes_per_row / VideoMonitor.x;
1897 >        int bytes_per_row = VideoMonitor.mode.bytes_per_row;
1898 >        int bytes_per_pixel = VideoMonitor.mode.bytes_per_row / VideoMonitor.mode.x;
1899          uint8 *p, *p2;
1900  
1901          // Check for first line from top and first line from bottom that have changed
1902          y1 = 0;
1903 <        for (j=0; j<VideoMonitor.y; j++) {
1903 >        for (j=0; j<VideoMonitor.mode.y; j++) {
1904                  if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1905                          y1 = j;
1906                          break;
1907                  }
1908          }
1909          y2 = y1 - 1;
1910 <        for (j=VideoMonitor.y-1; j>=y1; j--) {
1910 >        for (j=VideoMonitor.mode.y-1; j>=y1; j--) {
1911                  if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1912                          y2 = j;
1913                          break;
# Line 1788 | Line 1917 | static void update_display_static(void)
1917  
1918          // Check for first column from left and first column from right that have changed
1919          if (high) {
1920 <                if (depth == 1) {
1921 <                        x1 = VideoMonitor.x - 1;
1920 >                if (VideoMonitor.mode.depth == VDEPTH_1BIT) {
1921 >                        x1 = VideoMonitor.mode.x - 1;
1922                          for (j=y1; j<=y2; j++) {
1923                                  p = &the_buffer[j * bytes_per_row];
1924                                  p2 = &the_buffer_copy[j * bytes_per_row];
# Line 1807 | Line 1936 | static void update_display_static(void)
1936                                  p2 = &the_buffer_copy[j * bytes_per_row];
1937                                  p += bytes_per_row;
1938                                  p2 += bytes_per_row;
1939 <                                for (i=(VideoMonitor.x>>3); i>(x2>>3); i--) {
1939 >                                for (i=(VideoMonitor.mode.x>>3); i>(x2>>3); i--) {
1940                                          p--; p2--;
1941                                          if (*p != *p2) {
1942                                                  x2 = (i << 3) + 7;
# Line 1826 | Line 1955 | static void update_display_static(void)
1955                          }
1956  
1957                  } else {
1958 <                        x1 = VideoMonitor.x;
1958 >                        x1 = VideoMonitor.mode.x;
1959                          for (j=y1; j<=y2; j++) {
1960                                  p = &the_buffer[j * bytes_per_row];
1961                                  p2 = &the_buffer_copy[j * bytes_per_row];
# Line 1844 | Line 1973 | static void update_display_static(void)
1973                                  p2 = &the_buffer_copy[j * bytes_per_row];
1974                                  p += bytes_per_row;
1975                                  p2 += bytes_per_row;
1976 <                                for (i=VideoMonitor.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
1976 >                                for (i=VideoMonitor.mode.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
1977                                          p--;
1978                                          p2--;
1979                                          if (*p != *p2) {
# Line 1867 | Line 1996 | static void update_display_static(void)
1996  
1997          // Refresh display
1998          if (high && wide) {
1999 <                if (have_shm)
2000 <                        XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
1999 >                if (drv->have_shm)
2000 >                        XShmPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high, 0);
2001                  else
2002 <                        XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
2002 >                        XPutImage(x_display, drv->w, drv->gc, drv->img, x1, y1, x1, y1, wide, high);
2003          }
2004   }
2005  
# Line 1879 | Line 2008 | static void update_display_static(void)
2008   *      Screen refresh functions
2009   */
2010  
2011 < // The specialisations hereunder are meant to enable VOSF with DGA in direct
2012 < // addressing mode in case the address spaces (RAM, ROM, FrameBuffer) could
2013 < // not get mapped correctly with respect to the predetermined host frame
2014 < // buffer base address.
2015 < //
1887 < // Hmm, in other words, when in direct addressing mode and DGA is requested,
1888 < // we first try to "triple allocate" the address spaces according to the real
1889 < // host frame buffer address. Then, if it fails, we will use a temporary
1890 < // frame buffer thus making the real host frame buffer updated when pages
1891 < // of the temp frame buffer are altered.
1892 < //
1893 < // As a side effect, a little speed gain in screen updates could be noticed
1894 < // for other modes than DGA.
1895 < //
1896 < // The following two functions below are inline so that a clever compiler
1897 < // could specialise the code according to the current screen depth and
1898 < // display type. A more clever compiler would the job by itself though...
1899 < // (update_display_vosf is inlined as well)
2011 > // We suggest the compiler to inline the next two functions so that it
2012 > // may specialise the code according to the current screen depth and
2013 > // display type. A clever compiler would do that job by itself though...
2014 >
2015 > // NOTE: update_display_vosf is inlined too
2016  
2017   static inline void possibly_quit_dga_mode()
2018   {
1903 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2019          // Quit DGA mode if requested
2020          if (quit_full_screen) {
2021                  quit_full_screen = false;
2022 < #ifdef ENABLE_XF86_DGA
2023 <                XF86DGADirectVideo(x_display, screen, 0);
1909 < #endif
1910 <                XUngrabPointer(x_display, CurrentTime);
1911 <                XUngrabKeyboard(x_display, CurrentTime);
1912 <                XUnmapWindow(x_display, the_win);
1913 <                XSync(x_display, false);
2022 >                delete drv;
2023 >                drv = NULL;
2024          }
1915 #endif
2025   }
2026  
2027 < static inline void handle_palette_changes(int depth, int display_type)
2027 > static inline void handle_palette_changes(void)
2028   {
2029 < #ifdef HAVE_PTHREADS
2030 <        pthread_mutex_lock(&palette_lock);
1922 < #endif
2029 >        LOCK_PALETTE;
2030 >
2031          if (palette_changed) {
2032                  palette_changed = false;
2033 <                if (depth == 8) {
1926 <                        XStoreColors(x_display, cmap[0], palette, 256);
1927 <                        XStoreColors(x_display, cmap[1], palette, 256);
1928 <                                
1929 < #ifdef ENABLE_XF86_DGA
1930 <                        if (display_type == DISPLAY_DGA) {
1931 <                                current_dga_cmap ^= 1;
1932 <                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1933 <                        }
1934 < #endif
1935 <                }
2033 >                drv->update_palette();
2034          }
2035 < #ifdef HAVE_PTHREADS
2036 <        pthread_mutex_unlock(&palette_lock);
1939 < #endif
2035 >
2036 >        UNLOCK_PALETTE;
2037   }
2038  
2039   static void video_refresh_dga(void)
# Line 1948 | Line 2045 | static void video_refresh_dga(void)
2045          handle_events();
2046          
2047          // Handle palette changes
2048 <        handle_palette_changes(depth, DISPLAY_DGA);
2048 >        handle_palette_changes();
2049   }
2050  
2051   #ifdef ENABLE_VOSF
# Line 1962 | Line 2059 | static void video_refresh_dga_vosf(void)
2059          handle_events();
2060          
2061          // Handle palette changes
2062 <        handle_palette_changes(depth, DISPLAY_DGA);
2062 >        handle_palette_changes();
2063          
2064          // Update display (VOSF variant)
2065          static int tick_counter = 0;
2066          if (++tick_counter >= frame_skip) {
2067                  tick_counter = 0;
2068 < #ifdef HAVE_PTHREADS
2069 <                pthread_mutex_lock(&Screen_draw_lock);
2070 < #endif
2071 <                update_display_dga_vosf();
2072 < #ifdef HAVE_PTHREADS
1976 <                pthread_mutex_unlock(&Screen_draw_lock);
1977 < #endif
2068 >                if (mainBuffer.dirty) {
2069 >                        LOCK_VOSF;
2070 >                        update_display_dga_vosf();
2071 >                        UNLOCK_VOSF;
2072 >                }
2073          }
2074   }
2075   #endif
# Line 1988 | Line 2083 | static void video_refresh_window_vosf(vo
2083          handle_events();
2084          
2085          // Handle palette changes
2086 <        handle_palette_changes(depth, DISPLAY_WINDOW);
2086 >        handle_palette_changes();
2087          
2088          // Update display (VOSF variant)
2089          static int tick_counter = 0;
2090          if (++tick_counter >= frame_skip) {
2091                  tick_counter = 0;
2092 < #ifdef HAVE_PTHREADS
2093 <                pthread_mutex_lock(&Screen_draw_lock);
2094 < #endif
2095 <                update_display_window_vosf();
2096 < #ifdef HAVE_PTHREADS
2097 <                pthread_mutex_unlock(&Screen_draw_lock);
2003 < #endif
2092 >                if (mainBuffer.dirty) {
2093 >                        LOCK_VOSF;
2094 >                        update_display_window_vosf(static_cast<driver_window *>(drv));
2095 >                        UNLOCK_VOSF;
2096 >                        XSync(x_display, false); // Let the server catch up
2097 >                }
2098          }
2099   }
2100   #endif // def ENABLE_VOSF
# Line 2011 | Line 2105 | static void video_refresh_window_static(
2105          handle_events();
2106          
2107          // Handle_palette changes
2108 <        handle_palette_changes(depth, DISPLAY_WINDOW);
2108 >        handle_palette_changes();
2109          
2110          // Update display (static variant)
2111          static int tick_counter = 0;
2112          if (++tick_counter >= frame_skip) {
2113                  tick_counter = 0;
2114 <                update_display_static();
2114 >                update_display_static(static_cast<driver_window *>(drv));
2115          }
2116   }
2117  
# Line 2027 | Line 2121 | static void video_refresh_window_dynamic
2121          handle_events();
2122          
2123          // Handle_palette changes
2124 <        handle_palette_changes(depth, DISPLAY_WINDOW);
2124 >        handle_palette_changes();
2125          
2126          // Update display (dynamic variant)
2127          static int tick_counter = 0;
2128          tick_counter++;
2129 <        update_display_dynamic(tick_counter);
2129 >        update_display_dynamic(tick_counter, static_cast<driver_window *>(drv));
2130   }
2131  
2132  
# Line 2040 | Line 2134 | static void video_refresh_window_dynamic
2134   *  Thread for screen refresh, input handling etc.
2135   */
2136  
2137 < void VideoRefreshInit(void)
2137 > static void VideoRefreshInit(void)
2138   {
2139          // TODO: set up specialised 8bpp VideoRefresh handlers ?
2140          if (display_type == DISPLAY_DGA) {
# Line 2066 | Line 2160 | void VideoRefreshInit(void)
2160  
2161   void VideoRefresh(void)
2162   {
2163 <        // TODO: make main_unix/VideoRefresh call directly video_refresh() ?
2164 <        video_refresh();
2165 < }
2166 <
2073 < #if 0
2074 < void VideoRefresh(void)
2075 < {
2076 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2077 <        // Quit DGA mode if requested
2078 <        if (quit_full_screen) {
2079 <                quit_full_screen = false;
2080 <                if (display_type == DISPLAY_DGA) {
2081 < #ifdef ENABLE_XF86_DGA
2082 <                        XF86DGADirectVideo(x_display, screen, 0);
2083 < #endif
2084 <                        XUngrabPointer(x_display, CurrentTime);
2085 <                        XUngrabKeyboard(x_display, CurrentTime);
2086 <                        XUnmapWindow(x_display, the_win);
2087 <                        XSync(x_display, false);
2088 <                }
2089 <        }
2090 < #endif
2091 <
2092 <        // Handle X events
2093 <        handle_events();
2094 <
2095 <        // Handle palette changes
2096 < #ifdef HAVE_PTHREADS
2097 <        pthread_mutex_lock(&palette_lock);
2098 < #endif
2099 <        if (palette_changed) {
2100 <                palette_changed = false;
2101 <                if (depth == 8) {
2102 <                        XStoreColors(x_display, cmap[0], palette, 256);
2103 <                        XStoreColors(x_display, cmap[1], palette, 256);
2104 <                                
2105 < #ifdef ENABLE_XF86_DGA
2106 <                        if (display_type == DISPLAY_DGA) {
2107 <                                current_dga_cmap ^= 1;
2108 <                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2109 <                        }
2110 < #endif
2111 <                }
2112 <        }
2113 < #ifdef HAVE_PTHREADS
2114 <        pthread_mutex_unlock(&palette_lock);
2115 < #endif
2116 <
2117 <        // In window mode, update display
2118 <        static int tick_counter = 0;
2119 <        if (display_type == DISPLAY_WINDOW) {
2120 <                tick_counter++;
2121 <                if (frame_skip == 0)
2122 <                        update_display_dynamic(tick_counter);
2123 <                else if (tick_counter >= frame_skip) {
2124 <                        tick_counter = 0;
2125 <                        update_display_static();
2126 <                }
2127 <        }
2163 >        // We need to check redraw_thread_active to inhibit refreshed during
2164 >        // mode changes on non-threaded platforms
2165 >        if (redraw_thread_active)
2166 >                video_refresh();
2167   }
2129 #endif
2168  
2169   #ifdef HAVE_PTHREADS
2170   static void *redraw_func(void *arg)
# Line 2135 | Line 2173 | static void *redraw_func(void *arg)
2173          int64 ticks = 0;
2174          uint64 next = GetTicks_usec();
2175          while (!redraw_thread_cancel) {
2138 //              VideoRefresh();
2176                  video_refresh();
2177                  next += 16667;
2178                  int64 delay = next - GetTicks_usec();
# Line 2146 | Line 2183 | static void *redraw_func(void *arg)
2183                  ticks++;
2184          }
2185          uint64 end = GetTicks_usec();
2186 <        printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, (end - start) / ticks);
2186 >        // printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start));
2187          return NULL;
2188   }
2189   #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines