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.22 by cebix, 2000-10-08T18:41:35Z 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 <math.h> // log()
57 # include <unistd.h>
58 # include <signal.h>
59 # include <fcntl.h>
60 # include <sys/mman.h>
61 #endif
62
55   #include "cpu_emulation.h"
56   #include "main.h"
57   #include "adb.h"
# Line 80 | 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  
95 #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 115 | 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
119 < 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;
126 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask;
127 static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
126  
127 < static XColor palette[256];                                                     // Color palette for 8-bit mode
130 < static bool palette_changed = false;                            // Flag: Palette changed, redraw thread must set new colors
131 < #ifdef HAVE_PTHREADS
132 < static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;        // Mutex to protect palette
133 < #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;
137 < static XImage *img = NULL;
138 < static XShmSegmentInfo shminfo;
139 < static Cursor mac_cursor;
140 < static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer
141 < static bool have_shm = false;                                           // Flag: SHM extensions available
142 < static bool updt_box[17][17];                                           // Flag for Update
143 < static int nr_boxes;
144 < static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
145 < 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
149 < static Window suspend_win;                                                      // "Suspend" window
150 < static void *fb_save = NULL;                                            // Saved frame buffer for suspend
151 < #ifdef HAVE_PTHREADS
152 < 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  
155 // Variables for fbdev DGA mode
156 const char FBDEVICE_FILE_NAME[] = "/dev/fb";
157 static int fbdev_fd;
158
136   #ifdef ENABLE_XF86_VIDMODE
137 < // Variables for XF86 VidMode support
161 < 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
172 < static uint8 * the_host_buffer;                                         // Host frame buffer in VOSF mode
173 < static uint32 the_buffer_size;                                          // Size of allocated the_buffer
174 < #endif
175 <
176 < #ifdef ENABLE_VOSF
177 < // Variables for Video on SEGV support (taken from the Win32 port)
178 < struct ScreenPageInfo {
179 <    int top, bottom;                    // Mapping between this virtual page and Mac scanlines
180 < };
181 <
182 < struct ScreenInfo {
183 <    uint32 memBase;                             // Real start address
184 <    uint32 memStart;                    // Start address aligned to page boundary
185 <    uint32 memEnd;                              // Address of one-past-the-end of the screen
186 <    uint32 memLength;                   // Length of the memory addressed by the screen pages
187 <    
188 <    uint32 pageSize;                    // Size of a page
189 <    int pageBits;                               // Shift count to get the page number
190 <    uint32 pageCount;                   // Number of pages allocated to the screen
191 <    
192 <    uint8 * dirtyPages;                 // Table of flags set if page was altered
193 <    ScreenPageInfo * pageInfo;  // Table of mappings page -> Mac scanlines
194 < };
195 <
196 < static ScreenInfo mainBuffer;
197 <
198 < #define PFLAG_SET(page)                 mainBuffer.dirtyPages[page] = 1
199 < #define PFLAG_CLEAR(page)               mainBuffer.dirtyPages[page] = 0
200 < #define PFLAG_ISSET(page)               mainBuffer.dirtyPages[page]
201 < #define PFLAG_ISCLEAR(page)             (mainBuffer.dirtyPages[page] == 0)
202 < #ifdef UNALIGNED_PROFITABLE
203 < # define PFLAG_ISCLEAR_4(page)  (*((uint32 *)(mainBuffer.dirtyPages + page)) == 0)
204 < #else
205 < # define PFLAG_ISCLEAR_4(page)  \
206 <                (mainBuffer.dirtyPages[page  ] == 0) \
207 <        &&      (mainBuffer.dirtyPages[page+1] == 0) \
208 <        &&      (mainBuffer.dirtyPages[page+2] == 0) \
209 <        &&      (mainBuffer.dirtyPages[page+3] == 0)
210 < #endif
211 < #define PFLAG_CLEAR_ALL                 memset(mainBuffer.dirtyPages, 0, mainBuffer.pageCount)
212 < #define PFLAG_SET_ALL                   memset(mainBuffer.dirtyPages, 1, mainBuffer.pageCount)
213 <
214 < static int zero_fd = -1;
215 < static bool Screen_fault_handler_init();
216 < static struct sigaction vosf_sa;
217 <
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 < #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);
231 <
174 > static int event2keycode(XKeyEvent &ev);
175  
176   // From main_unix.cpp
177   extern char *x_display_name;
# Line 237 | Line 180 | extern Display *x_display;
180   // From sys_unix.cpp
181   extern void SysMountFirstFloppy(void);
182  
240 #ifdef ENABLE_VOSF
241 # include "video_vosf.h"
242 #endif
243
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;
258 <                case 8:
259 <                        layout = FLAYOUT_DIRECT;
260 <                        break;
261 <                case 15:
262 <                        layout = FLAYOUT_HOST_555;
263 <                        break;
264 <                case 16:
265 <                        layout = FLAYOUT_HOST_565;
266 <                        break;
267 <                case 24:
268 <                case 32:
269 <                        layout = FLAYOUT_HOST_888;
270 <                        break;
271 <        }
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 310 | 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  
322        // Read frame skip prefs
323        frame_skip = PrefsFindInt32("frameskip");
324
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;
332 <        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,
336 <                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
337 <                CWBackingStore | CWBackingPlanes, &wattr);
338 <        XSync(x_display, false);
339 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
340 <        XMapRaised(x_display, the_win);
341 <        XSync(x_display, false);
429 >        // Set window name/class
430 >        set_window_name(w, STR_WINDOW_TITLE);
431  
432 <        // Set colormap
433 <        if (depth == 8) {
434 <                XSetWindowColormap(x_display, the_win, cmap[0]);
435 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
436 <        }
432 >        // Indicate that we want keyboard input
433 >        set_window_focus(w);
434 >
435 >        // Set delete protocol property
436 >        set_window_delete_protocol(w);
437  
438          // Make window unresizable
439 <        XSizeHints *hints;
440 <        if ((hints = XAllocSizeHints()) != NULL) {
441 <                hints->min_width = width;
442 <                hints->max_width = width;
443 <                hints->min_height = height;
444 <                hints->max_height = height;
445 <                hints->flags = PMinSize | PMaxSize;
446 <                XSetWMNormalHints(x_display, the_win, hints);
447 <                XFree((char *)hints);
439 >        {
440 >                XSizeHints *hints = XAllocSizeHints();
441 >                if (hints) {
442 >                        hints->min_width = width;
443 >                        hints->max_width = width;
444 >                        hints->min_height = height;
445 >                        hints->max_height = height;
446 >                        hints->flags = PMinSize | PMaxSize;
447 >                        XSetWMNormalHints(x_display, w, hints);
448 >                        XFree(hints);
449 >                }
450          }
451          
452 +        // Show window
453 +        XMapWindow(x_display, w);
454 +        wait_mapped(w);
455 +
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;
363 <        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 387 | 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;
391 <                switch (depth) {
392 <                        case 1:
393 <                                bytes_per_row /= 8;
394 <                                break;
395 <                        case 15:
396 <                        case 16:
397 <                                bytes_per_row *= 2;
398 <                                break;
399 <                        case 24:
400 <                        case 32:
401 <                                bytes_per_row *= 4;
402 <                                break;
403 <                }
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
409 <        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
416 <        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);
421 <        
422 <        the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
423 <        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 483 | 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 503 | 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 515 | 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          
523        int width = DisplayWidth(x_display, screen);
524        int height = DisplayHeight(x_display, screen);
525        depth = fb_depth; // max_depth
526        
527        // Set relative mouse mode
528        ADBSetRelMouseMode(false);
529        
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;
536 <        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);
539 <        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) {
557 <                XSetWindowColormap(x_display, the_win, cmap[0]);
558 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
559 <        }
560 <        
561 <        // Set VideoMonitor
562 <        int bytes_per_row = width;
563 <        switch (depth) {
564 <                case 1:
565 <                        bytes_per_row = ((width | 7) & ~7) >> 3;
566 <                        break;
567 <                case 15:
568 <                case 16:
569 <                        bytes_per_row *= 2;
570 <                        break;
571 <                case 24:
572 <                case 32:
573 <                        bytes_per_row *= 4;
574 <                        break;
575 <        }
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;
590 <        do_update_framebuffer = GET_FBCOPY_FUNC(depth, true, DISPLAY_DGA);
591 <        if (do_update_framebuffer == FBCOPY_FUNC(fbcopy_raw))
592 <                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);
600 <                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 < #elif ENABLE_VOSF
805 > #else
806          use_vosf = false;
807   #endif
605        
606        set_video_monitor(width, height, bytes_per_row, true);
607 #if REAL_ADDRESSING || DIRECT_ADDRESSING
608        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
609 #else
610        VideoMonitor.mac_frame_base = MacFrameBaseMac;
611 #endif
612        return true;
613 #else
614        ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled.");
615        return false;
808   #endif
809 +        
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 635 | 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;
644        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 665 | 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]);
670 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
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) {
677 <                case 1:
678 <                        bytes_per_row /= 8;
679 <                        break;
680 <                case 15:
681 <                case 16:
682 <                        bytes_per_row *= 2;
683 <                        break;
684 <                case 24:
685 <                case 32:
686 <                        bytes_per_row *= 4;
687 <                        break;
688 <        }
689 <        
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;
694 <        do_update_framebuffer = GET_FBCOPY_FUNC(depth, true, DISPLAY_DGA);
695 <        if (do_update_framebuffer == FBCOPY_FUNC(fbcopy_raw))
696 <                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);
704 <                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)
707 <        // The UAE memory handlers will already handle color conversion, if needed.
921 > #else
922          use_vosf = false;
923   #endif
710        
711        set_video_monitor(width, height, bytes_per_row, true);
712 #if REAL_ADDRESSING || DIRECT_ADDRESSING
713        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
714 //      MacFrameLayout = FLAYOUT_DIRECT;
715 #else
716        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 787 | 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     = int( log(mainBuffer.pageSize) / log(2.0) );
1050 <
807 <                if (mainBuffer.dirtyPages != 0)
808 <                        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;
829 <                        if (y2 >= VideoMonitor.y)
830 <                                y2 = VideoMonitor.y - 1;
831 <
832 <                        mainBuffer.pageInfo[i].top = y1;
833 <                        mainBuffer.pageInfo[i].bottom = y2;
834 <
835 <                        a += mainBuffer.pageSize;
836 <                        if (a > mainBuffer.memLength)
837 <                                a = mainBuffer.memLength;
838 <                }
839 <                
840 <                // We can now write-protect the frame buffer
841 <                if (mprotect((caddr_t)mainBuffer.memStart, mainBuffer.memLength, PROT_READ) != 0)
842 <                        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
851        // Open /dev/zero
852        zero_fd = open("/dev/zero", O_RDWR);
853        if (zero_fd < 0) {
854        char str[256];
855                sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
856                ErrorAlert(str);
857        return false;
858        }
859        
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 870 | 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 884 | 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 930 | 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;
952 <        if (classic)
953 <                depth = 1;
954 <        else
955 <                depth = xdepth;
956 <
957 <        // Create color maps for 8 bit mode
958 <        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;
984                        if (width > DisplayWidth(x_display, screen))
985                                width = DisplayWidth(x_display, screen);
986                        if (height > DisplayHeight(x_display, screen))
987                                height = DisplayHeight(x_display, screen);
988                }
989                if (width <= 0)
990                        width = DisplayWidth(x_display, screen);
991                if (height <= 0)
992                        height = DisplayHeight(x_display, screen);
993        }
994
995        // Initialize according to display type
996        switch (display_type) {
997                case DISPLAY_WINDOW:
998                        if (!init_window(width, height))
999                                return false;
1000                        break;
1001                case DISPLAY_DGA:
1002 #ifdef ENABLE_FBDEV_DGA
1003                        if (!init_fbdev_dga(fb_name))
1004 #else
1005                        if (!init_xf86_dga(width, height))
1274   #endif
1275 <                                return false;
1008 <                        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
1013 <        pthread_mutex_lock(&frame_buffer_lock);
1014 < #endif
1015 <
1016 < #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
1017 <        // Set variables for UAE memory mapping
1018 <        MacFrameBaseHost = the_buffer;
1019 <        MacFrameSize = VideoMonitor.bytes_per_row * VideoMonitor.y;
1020 <
1021 <        // No special frame buffer in Classic mode (frame buffer is in Mac RAM)
1022 <        if (classic)
1023 <                MacFrameLayout = FLAYOUT_NONE;
1024 < #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          }
1042 #endif
1043        
1044        // Initialize VideoRefresh function
1045        VideoRefreshInit();
1046        
1047        XSync(x_display, false);
1048
1049 #ifdef HAVE_PTHREADS
1050        // Start redraw/input thread
1051        redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1052        if (!redraw_thread_active) {
1053                printf("FATAL: cannot create redraw thread\n");
1054                return false;
1055        }
1056 #endif
1057        return true;
1337   }
1338  
1339  
# Line 1062 | Line 1341 | bool VideoInit(bool classic)
1341   *  Deinitialization
1342   */
1343  
1344 < void VideoExit(void)
1344 > // Close display
1345 > static void video_close(void)
1346   {
1067 #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);
1075                redraw_thread_active = false;
1355          }
1356   #endif
1357 +        redraw_thread_active = false;
1358  
1079 #ifdef HAVE_PTHREADS
1359          // Unlock frame buffer
1360 <        pthread_mutex_unlock(&frame_buffer_lock);
1361 < #endif
1083 <
1084 <        // Close window and server connection
1085 <        if (x_display != NULL) {
1086 <                XSync(x_display, false);
1087 <
1088 < #ifdef ENABLE_XF86_DGA
1089 <                if (display_type == DISPLAY_DGA) {
1090 <                        XF86DGADirectVideo(x_display, screen, 0);
1091 <                        XUngrabPointer(x_display, CurrentTime);
1092 <                        XUngrabKeyboard(x_display, CurrentTime);
1093 <                }
1094 < #endif
1095 <
1096 < #ifdef ENABLE_XF86_VIDMODE
1097 <                if (has_vidmode && display_type == DISPLAY_DGA)
1098 <                        XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1099 < #endif
1100 <
1101 < #ifdef ENABLE_FBDEV_DGA
1102 <                if (display_type == DISPLAY_DGA) {
1103 <                        XUngrabPointer(x_display, CurrentTime);
1104 <                        XUngrabKeyboard(x_display, CurrentTime);
1105 <                        close(fbdev_fd);
1106 <                }
1107 < #endif
1108 <
1109 <                XFlush(x_display);
1110 <                XSync(x_display, false);
1111 <                if (depth == 8) {
1112 <                        XFreeColormap(x_display, cmap[0]);
1113 <                        XFreeColormap(x_display, cmap[1]);
1114 <                }
1115 <                
1116 <                if (!use_vosf) {
1117 <                        if (the_buffer) {
1118 <                                free(the_buffer);
1119 <                                the_buffer = NULL;
1120 <                        }
1360 >        UNLOCK_FRAME_BUFFER;
1361 >        XSync(x_display, false);
1362  
1122                        if (!have_shm && the_buffer_copy) {
1123                                free(the_buffer_copy);
1124                                the_buffer_copy = NULL;
1125                        }
1126                }
1127 #ifdef ENABLE_VOSF
1128                else {
1129                        if (the_buffer != (uint8 *)MAP_FAILED) {
1130                                munmap((caddr_t)the_buffer, the_buffer_size);
1131                                the_buffer = 0;
1132                        }
1133                        
1134                        if (the_buffer_copy != (uint8 *)MAP_FAILED) {
1135                                munmap((caddr_t)the_buffer_copy, the_buffer_size);
1136                                the_buffer_copy = 0;
1137                        }
1138                }
1139 #endif
1140        }
1141        
1363   #ifdef ENABLE_VOSF
1364 +        // Deinitialize VOSF
1365          if (use_vosf) {
1144                // Clear mainBuffer data
1366                  if (mainBuffer.pageInfo) {
1367                          free(mainBuffer.pageInfo);
1368 <                        mainBuffer.pageInfo = 0;
1368 >                        mainBuffer.pageInfo = NULL;
1369                  }
1149
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 1167 | Line 1419 | void VideoExit(void)
1419   void VideoQuitFullScreen(void)
1420   {
1421          D(bug("VideoQuitFullScreen()\n"));
1422 <        if (display_type == DISPLAY_DGA)
1171 <                quit_full_screen = true;
1422 >        quit_full_screen = true;
1423   }
1424  
1425  
# Line 1182 | Line 1433 | void VideoInterrupt(void)
1433          if (emerg_quit)
1434                  QuitEmulator();
1435  
1185 #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);
1190 < #endif
1438 >        UNLOCK_FRAME_BUFFER;
1439 >        LOCK_FRAME_BUFFER;
1440   }
1441  
1442  
# Line 1197 | Line 1446 | void VideoInterrupt(void)
1446  
1447   void video_set_palette(uint8 *pal)
1448   {
1449 < #ifdef HAVE_PTHREDS
1201 <        pthread_mutex_lock(&palette_lock);
1202 < #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
1217 <        pthread_mutex_unlock(&palette_lock);
1218 < #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)
1227 < static void suspend_emul(void)
1228 < {
1229 <        if (display_type == DISPLAY_DGA) {
1230 <                // Release ctrl key
1231 <                ADBKeyUp(0x36);
1232 <                ctrl_down = false;
1233 <
1234 < #ifdef HAVE_PTHREADS
1235 <                // Lock frame buffer (this will stop the MacOS thread)
1236 <                pthread_mutex_lock(&frame_buffer_lock);
1237 < #endif
1238 <
1239 <                // Save frame buffer
1240 <                fb_save = malloc(VideoMonitor.y * VideoMonitor.bytes_per_row);
1241 <                if (fb_save)
1242 <                        memcpy(fb_save, the_buffer, VideoMonitor.y * VideoMonitor.bytes_per_row);
1243 <
1244 <                // Close full screen display
1245 < #ifdef ENABLE_XF86_DGA
1246 <                XF86DGADirectVideo(x_display, screen, 0);
1247 < #endif
1248 <                XUngrabPointer(x_display, CurrentTime);
1249 <                XUngrabKeyboard(x_display, CurrentTime);
1250 <                XUnmapWindow(x_display, the_win);
1251 <                XSync(x_display, false);
1252 <
1253 <                // Open "suspend" window
1254 <                XSetWindowAttributes wattr;
1255 <                wattr.event_mask = KeyPressMask;
1256 <                wattr.background_pixel = black_pixel;
1257 <                wattr.border_pixel = black_pixel;
1258 <                wattr.backing_store = Always;
1259 <                wattr.backing_planes = xdepth;
1260 <                wattr.colormap = DefaultColormap(x_display, screen);
1261 <                
1262 <                XSync(x_display, false);
1263 <                suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1264 <                        InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
1265 <                        CWBackingStore | CWBackingPlanes | (xdepth == 8 ? CWColormap : 0), &wattr);
1266 <                XSync(x_display, false);
1267 <                XStoreName(x_display, suspend_win, GetString(STR_SUSPEND_WINDOW_TITLE));
1268 <                XMapRaised(x_display, suspend_win);
1269 <                XSync(x_display, false);
1270 <                emul_suspended = true;
1271 <        }
1272 < }
1273 <
1274 < static void resume_emul(void)
1496 > void video_switch_to_mode(const video_mode &mode)
1497   {
1498 <        // Close "suspend" window
1499 <        XDestroyWindow(x_display, suspend_win);
1500 <        XSync(x_display, false);
1498 >        // Close and reopen display
1499 >        video_close();
1500 >        video_open(mode);
1501  
1502 <        // Reopen full screen display
1503 <        XMapRaised(x_display, the_win);
1504 <        XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
1283 <        XSync(x_display, false);
1284 <        XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1285 <        XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1286 < #ifdef ENABLE_XF86_DGA
1287 <        XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1288 <        XF86DGASetViewPort(x_display, screen, 0, 0);
1289 < #endif
1290 <        XSync(x_display, false);
1291 <        
1292 <        // the_buffer already contains the data to restore. i.e. since a temporary
1293 <        // frame buffer is used when VOSF is actually used, fb_save is therefore
1294 <        // not necessary.
1295 < #ifdef ENABLE_VOSF
1296 <        if (use_vosf) {
1297 < #ifdef HAVE_PTHREADS
1298 <                pthread_mutex_lock(&Screen_draw_lock);
1299 < #endif
1300 <                PFLAG_SET_ALL;
1301 < #ifdef HAVE_PTHREADS
1302 <                pthread_mutex_unlock(&Screen_draw_lock);
1303 < #endif
1304 <                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1305 <        }
1306 < #endif
1307 <        
1308 <        // Restore frame buffer
1309 <        if (fb_save) {
1310 < #ifdef ENABLE_VOSF
1311 <                // Don't copy fb_save to the temporary frame buffer in VOSF mode
1312 <                if (!use_vosf)
1313 < #endif
1314 <                memcpy(the_buffer, fb_save, VideoMonitor.y * VideoMonitor.bytes_per_row);
1315 <                free(fb_save);
1316 <                fb_save = NULL;
1502 >        if (drv == NULL) {
1503 >                ErrorAlert(STR_OPEN_WINDOW_ERR);
1504 >                QuitEmulator();
1505          }
1318        
1319 #ifdef ENABLE_XF86_DGA
1320        if (depth == 8)
1321                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1322 #endif
1323
1324 #ifdef HAVE_PTHREADS
1325        // Unlock frame buffer (and continue MacOS thread)
1326        pthread_mutex_unlock(&frame_buffer_lock);
1327        emul_suspended = false;
1328 #endif
1506   }
1330 #endif
1507  
1508  
1509   /*
# Line 1388 | 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 1479 | 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 1502 | 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))
1508 <                        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 1529 | 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 1537 | Line 1712 | static void handle_events(void)
1712  
1713                          // Mouse moved
1714                          case EnterNotify:
1540                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1541                                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 1566 | Line 1739 | static void handle_events(void)
1739                                                  if (code == 0x36)
1740                                                          ctrl_down = true;
1741                                          } else {
1569 #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1742                                                  if (code == 0x31)
1743 <                                                        resume_emul();  // Space wakes us up
1572 < #endif
1743 >                                                        drv->resume();  // Space wakes us up
1744                                          }
1745                                  }
1746                                  break;
# Line 1577 | 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 1594 | 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
1598 <                                                pthread_mutex_lock(&Screen_draw_lock);
1599 < #endif
1768 >                                                LOCK_VOSF;
1769                                                  PFLAG_SET_ALL;
1770 < #ifdef HAVE_PTHREADS
1771 <                                                pthread_mutex_unlock(&Screen_draw_lock);
1603 < #endif
1604 <                                                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 1612 | 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 >                        // 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                  }
# Line 1625 | 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 1687 | 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 1715 | 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 1742 | 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;
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 1761 | 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;
1942 >                                                x2 = (i << 3) + 7;
1943                                                  break;
1944                                          }
1945                                  }
1946                          }
1947 <                        wide = x2 - x1;
1947 >                        wide = x2 - x1 + 1;
1948  
1949                          // Update copy of the_buffer
1950                          if (high && wide) {
# Line 1780 | 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 1798 | 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 1821 | 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 1833 | 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 < //
1841 < // Hmm, in other words, when in direct addressing mode and DGA is requested,
1842 < // we first try to "triple allocate" the address spaces according to the real
1843 < // host frame buffer address. Then, if it fails, we will use a temporary
1844 < // frame buffer thus making the real host frame buffer updated when pages
1845 < // of the temp frame buffer are altered.
1846 < //
1847 < // As a side effect, a little speed gain in screen updates could be noticed
1848 < // for other modes than DGA.
1849 < //
1850 < // The following two functions below are inline so that a clever compiler
1851 < // could specialise the code according to the current screen depth and
1852 < // display type. A more clever compiler would the job by itself though...
1853 < // (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   {
1857 #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);
1863 < #endif
1864 <                XUngrabPointer(x_display, CurrentTime);
1865 <                XUngrabKeyboard(x_display, CurrentTime);
1866 <                XUnmapWindow(x_display, the_win);
1867 <                XSync(x_display, false);
2022 >                delete drv;
2023 >                drv = NULL;
2024          }
1869 #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);
1876 < #endif
2029 >        LOCK_PALETTE;
2030 >
2031          if (palette_changed) {
2032                  palette_changed = false;
2033 <                if (depth == 8) {
1880 <                        XStoreColors(x_display, cmap[0], palette, 256);
1881 <                        XStoreColors(x_display, cmap[1], palette, 256);
1882 <                                
1883 < #ifdef ENABLE_XF86_DGA
1884 <                        if (display_type == DISPLAY_DGA) {
1885 <                                current_dga_cmap ^= 1;
1886 <                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1887 <                        }
1888 < #endif
1889 <                }
2033 >                drv->update_palette();
2034          }
2035 < #ifdef HAVE_PTHREADS
2036 <        pthread_mutex_unlock(&palette_lock);
1893 < #endif
2035 >
2036 >        UNLOCK_PALETTE;
2037   }
2038  
2039   static void video_refresh_dga(void)
# Line 1902 | 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
2052   #if REAL_ADDRESSING || DIRECT_ADDRESSING
2053   static void video_refresh_dga_vosf(void)
2054   {
# Line 1915 | 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
1929 <                pthread_mutex_unlock(&Screen_draw_lock);
1930 < #endif
2068 >                if (mainBuffer.dirty) {
2069 >                        LOCK_VOSF;
2070 >                        update_display_dga_vosf();
2071 >                        UNLOCK_VOSF;
2072 >                }
2073          }
2074   }
2075   #endif
2076  
1935 #ifdef ENABLE_VOSF
2077   static void video_refresh_window_vosf(void)
2078   {
2079          // Quit DGA mode if requested
# Line 1942 | 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);
1957 < #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
2100 > #endif // def ENABLE_VOSF
2101  
2102   static void video_refresh_window_static(void)
2103   {
# Line 1965 | 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 1981 | 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 1994 | 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) {
2141 < #if REAL_ADDRESSING || DIRECT_ADDRESSING
2141 > #if ENABLE_VOSF && (REAL_ADDRESSING || DIRECT_ADDRESSING)
2142                  if (use_vosf)
2143                          video_refresh = video_refresh_dga_vosf;
2144                  else
# Line 2020 | 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 <
2027 < #if 0
2028 < void VideoRefresh(void)
2029 < {
2030 < #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
2031 <        // Quit DGA mode if requested
2032 <        if (quit_full_screen) {
2033 <                quit_full_screen = false;
2034 <                if (display_type == DISPLAY_DGA) {
2035 < #ifdef ENABLE_XF86_DGA
2036 <                        XF86DGADirectVideo(x_display, screen, 0);
2037 < #endif
2038 <                        XUngrabPointer(x_display, CurrentTime);
2039 <                        XUngrabKeyboard(x_display, CurrentTime);
2040 <                        XUnmapWindow(x_display, the_win);
2041 <                        XSync(x_display, false);
2042 <                }
2043 <        }
2044 < #endif
2045 <
2046 <        // Handle X events
2047 <        handle_events();
2048 <
2049 <        // Handle palette changes
2050 < #ifdef HAVE_PTHREADS
2051 <        pthread_mutex_lock(&palette_lock);
2052 < #endif
2053 <        if (palette_changed) {
2054 <                palette_changed = false;
2055 <                if (depth == 8) {
2056 <                        XStoreColors(x_display, cmap[0], palette, 256);
2057 <                        XStoreColors(x_display, cmap[1], palette, 256);
2058 <                                
2059 < #ifdef ENABLE_XF86_DGA
2060 <                        if (display_type == DISPLAY_DGA) {
2061 <                                current_dga_cmap ^= 1;
2062 <                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2063 <                        }
2064 < #endif
2065 <                }
2066 <        }
2067 < #ifdef HAVE_PTHREADS
2068 <        pthread_mutex_unlock(&palette_lock);
2069 < #endif
2070 <
2071 <        // In window mode, update display
2072 <        static int tick_counter = 0;
2073 <        if (display_type == DISPLAY_WINDOW) {
2074 <                tick_counter++;
2075 <                if (frame_skip == 0)
2076 <                        update_display_dynamic(tick_counter);
2077 <                else if (tick_counter >= frame_skip) {
2078 <                        tick_counter = 0;
2079 <                        update_display_static();
2080 <                }
2081 <        }
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   }
2083 #endif
2168  
2169   #ifdef HAVE_PTHREADS
2170   static void *redraw_func(void *arg)
# Line 2089 | Line 2173 | static void *redraw_func(void *arg)
2173          int64 ticks = 0;
2174          uint64 next = GetTicks_usec();
2175          while (!redraw_thread_cancel) {
2092 //              VideoRefresh();
2176                  video_refresh();
2177                  next += 16667;
2178                  int64 delay = next - GetTicks_usec();
# Line 2100 | 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