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.2 by cebix, 1999-10-03T16:20:08Z vs.
Revision 1.36 by gbeauche, 2001-01-28T14:05:19Z

# Line 1 | Line 1
1   /*
2   *  video_x.cpp - Video/graphics emulation, X11 specific stuff
3   *
4 < *  Basilisk II (C) 1997-1999 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 34 | Line 34
34   #include <X11/extensions/XShm.h>
35   #include <sys/ipc.h>
36   #include <sys/shm.h>
37 #include <pthread.h>
37   #include <errno.h>
38  
39 + #ifdef HAVE_PTHREADS
40 + # include <pthread.h>
41 + #endif
42 +
43 + #ifdef ENABLE_XF86_DGA
44 + # include <X11/extensions/xf86dga.h>
45 + #endif
46 +
47 + #ifdef ENABLE_XF86_VIDMODE
48 + # include <X11/extensions/xf86vmode.h>
49 + #endif
50 +
51 + #ifdef ENABLE_FBDEV_DGA
52 + # include <sys/mman.h>
53 + #endif
54 +
55 + #ifdef ENABLE_VOSF
56 + # include <unistd.h>
57 + # include <signal.h>
58 + # include <fcntl.h>
59 + # include <sys/mman.h>
60 + #endif
61 +
62   #include "cpu_emulation.h"
63   #include "main.h"
64   #include "adb.h"
# Line 45 | Line 67
67   #include "user_strings.h"
68   #include "video.h"
69  
70 < #define DEBUG 1
70 > #define DEBUG 0
71   #include "debug.h"
72  
51 #if ENABLE_DGA
52 #include <X11/extensions/xf86dga.h>
53 #endif
54
73  
74   // Display types
75   enum {
# Line 59 | Line 77 | enum {
77          DISPLAY_DGA             // DGA fullscreen display
78   };
79  
62
80   // Constants
81 < const char KEYCODE_FILE_NAME[] = SHAREDIR "keycodes";
81 > const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
82 > const char FBDEVICES_FILE_NAME[] = DATADIR "/fbdevices";
83  
84  
85   // Global variables
86 < static int32 frame_skip;
86 > static int32 frame_skip;                                                        // Prefs items
87 > static int16 mouse_wheel_mode = 1;
88 > static int16 mouse_wheel_lines = 3;
89 >
90   static int display_type = DISPLAY_WINDOW;                       // See enum above
91 + static bool local_X11;                                                          // Flag: X server running on local machine?
92   static uint8 *the_buffer;                                                       // Mac frame buffer
93 +
94 + #ifdef HAVE_PTHREADS
95   static bool redraw_thread_active = false;                       // Flag: Redraw thread installed
96   static volatile bool redraw_thread_cancel = false;      // Flag: Cancel Redraw thread
97   static pthread_t redraw_thread;                                         // Redraw thread
98 + #endif
99  
100   static bool has_dga = false;                                            // Flag: Video DGA capable
101 + static bool has_vidmode = false;                                        // Flag: VidMode extension available
102  
103   static bool ctrl_down = false;                                          // Flag: Ctrl key pressed
104 + static bool caps_on = false;                                            // Flag: Caps Lock on
105   static bool quit_full_screen = false;                           // Flag: DGA close requested from redraw thread
106   static bool emerg_quit = false;                                         // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread
107   static bool emul_suspended = false;                                     // Flag: Emulator suspended
# Line 95 | Line 122 | static Colormap cmap[2];                                                       // Two co
122   static XColor black, white;
123   static unsigned long black_pixel, white_pixel;
124   static int eventmask;
125 < static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask;
126 < static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
125 > static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
126 > static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
127 > static Atom WM_DELETE_WINDOW = (Atom)0;
128  
101 static pthread_mutex_t palette_lock = PTHREAD_MUTEX_INITIALIZER;        // Mutex to protect palette
129   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 + #define LOCK_PALETTE pthread_mutex_lock(&palette_lock)
134 + #define UNLOCK_PALETTE pthread_mutex_unlock(&palette_lock)
135 + #else
136 + #define LOCK_PALETTE
137 + #define UNLOCK_PALETTE
138 + #endif
139  
140   // Variables for window mode
141   static GC the_gc;
142   static XImage *img = NULL;
143   static XShmSegmentInfo shminfo;
109 static XImage *cursor_image, *cursor_mask_image;
110 static Pixmap cursor_map, cursor_mask_map;
144   static Cursor mac_cursor;
112 static GC cursor_gc, cursor_mask_gc;
145   static uint8 *the_buffer_copy = NULL;                           // Copy of Mac frame buffer
114 static uint8 the_cursor[64];                                            // Cursor image data
146   static bool have_shm = false;                                           // Flag: SHM extensions available
147 + static bool updt_box[17][17];                                           // Flag for Update
148 + static int nr_boxes;
149 + static const int sm_uptd[] = {4,1,6,3,0,5,2,7};
150 + static int sm_no_boxes[] = {1,8,32,64,128,300};
151  
152 < // Variables for DGA mode
152 > // Variables for XF86 DGA mode
153   static int current_dga_cmap;                                            // Number (0 or 1) of currently installed DGA colormap
154   static Window suspend_win;                                                      // "Suspend" window
155   static void *fb_save = NULL;                                            // Saved frame buffer for suspend
156 <
156 > #ifdef HAVE_PTHREADS
157   static pthread_mutex_t frame_buffer_lock = PTHREAD_MUTEX_INITIALIZER;   // Mutex to protect frame buffer
158 + #define LOCK_FRAME_BUFFER pthread_mutex_lock(&frame_buffer_lock);
159 + #define UNLOCK_FRAME_BUFFER pthread_mutex_unlock(&frame_buffer_lock);
160 + #else
161 + #define LOCK_FRAME_BUFFER
162 + #define UNLOCK_FRAME_BUFFER
163 + #endif
164  
165 + // Variables for fbdev DGA mode
166 + const char FBDEVICE_FILE_NAME[] = "/dev/fb";
167 + static int fbdev_fd;
168 +
169 + #ifdef ENABLE_XF86_VIDMODE
170 + // Variables for XF86 VidMode support
171 + static XF86VidModeModeInfo **x_video_modes;                     // Array of all available modes
172 + static int num_x_video_modes;
173 + #endif
174 +
175 + #ifdef ENABLE_VOSF
176 + static bool use_vosf = true;                                            // Flag: VOSF enabled
177 + #else
178 + static const bool use_vosf = false;                                     // Flag: VOSF enabled
179 + #endif
180 +
181 + #ifdef ENABLE_VOSF
182 + // Variables for Video on SEGV support (taken from the Win32 port)
183 + static uint8 *the_host_buffer;                                          // Host frame buffer in VOSF mode
184 + static uint32 the_buffer_size;                                          // Size of allocated the_buffer
185 +
186 + struct ScreenPageInfo {
187 +    int top, bottom;                    // Mapping between this virtual page and Mac scanlines
188 + };
189 +
190 + struct ScreenInfo {
191 +    uint32 memBase;                             // Real start address
192 +    uint32 memStart;                    // Start address aligned to page boundary
193 +    uint32 memEnd;                              // Address of one-past-the-end of the screen
194 +    uint32 memLength;                   // Length of the memory addressed by the screen pages
195 +    
196 +    uint32 pageSize;                    // Size of a page
197 +    int pageBits;                               // Shift count to get the page number
198 +    uint32 pageCount;                   // Number of pages allocated to the screen
199 +    
200 +        bool dirty;                                     // Flag: set if the frame buffer was touched
201 +    char * dirtyPages;                  // Table of flags set if page was altered
202 +    ScreenPageInfo * pageInfo;  // Table of mappings page -> Mac scanlines
203 + };
204 +
205 + static ScreenInfo mainBuffer;
206 +
207 + #define PFLAG_SET_VALUE                 0x00
208 + #define PFLAG_CLEAR_VALUE               0x01
209 + #define PFLAG_SET_VALUE_4               0x00000000
210 + #define PFLAG_CLEAR_VALUE_4             0x01010101
211 + #define PFLAG_SET(page)                 mainBuffer.dirtyPages[page] = PFLAG_SET_VALUE
212 + #define PFLAG_CLEAR(page)               mainBuffer.dirtyPages[page] = PFLAG_CLEAR_VALUE
213 + #define PFLAG_ISSET(page)               (mainBuffer.dirtyPages[page] == PFLAG_SET_VALUE)
214 + #define PFLAG_ISCLEAR(page)             (mainBuffer.dirtyPages[page] != PFLAG_SET_VALUE)
215 +
216 + #ifdef UNALIGNED_PROFITABLE
217 + # define PFLAG_ISSET_4(page)    (*((uint32 *)(mainBuffer.dirtyPages + (page))) == PFLAG_SET_VALUE_4)
218 + # define PFLAG_ISCLEAR_4(page)  (*((uint32 *)(mainBuffer.dirtyPages + (page))) == PFLAG_CLEAR_VALUE_4)
219 + #else
220 + # define PFLAG_ISSET_4(page) \
221 +                PFLAG_ISSET(page  ) && PFLAG_ISSET(page+1) \
222 +        &&      PFLAG_ISSET(page+2) && PFLAG_ISSET(page+3)
223 + # define PFLAG_ISCLEAR_4(page) \
224 +                PFLAG_ISCLEAR(page  ) && PFLAG_ISCLEAR(page+1) \
225 +        &&      PFLAG_ISCLEAR(page+2) && PFLAG_ISCLEAR(page+3)
226 + #endif
227 +
228 + // Set the selected page range [ first_page, last_page [ into the SET state
229 + #define PFLAG_SET_RANGE(first_page, last_page) \
230 +        memset(mainBuffer.dirtyPages + (first_page), PFLAG_SET_VALUE, \
231 +                (last_page) - (first_page))
232 +
233 + // Set the selected page range [ first_page, last_page [ into the CLEAR state
234 + #define PFLAG_CLEAR_RANGE(first_page, last_page) \
235 +        memset(mainBuffer.dirtyPages + (first_page), PFLAG_CLEAR_VALUE, \
236 +                (last_page) - (first_page))
237 +
238 + #define PFLAG_SET_ALL do { \
239 +        PFLAG_SET_RANGE(0, mainBuffer.pageCount); \
240 +        mainBuffer.dirty = true; \
241 + } while (0)
242 +
243 + #define PFLAG_CLEAR_ALL do { \
244 +        PFLAG_CLEAR_RANGE(0, mainBuffer.pageCount); \
245 +        mainBuffer.dirty = false; \
246 + } while (0)
247 +
248 + // Set the following macro definition to 1 if your system
249 + // provides a really fast strchr() implementation
250 + //#define HAVE_FAST_STRCHR 0
251 +
252 + static inline int find_next_page_set(int page)
253 + {
254 + #if HAVE_FAST_STRCHR
255 +        char *match = strchr(mainBuffer.dirtyPages + page, PFLAG_SET_VALUE);
256 +        return match ? match - mainBuffer.dirtyPages : mainBuffer.pageCount;
257 + #else
258 +        while (PFLAG_ISCLEAR_4(page))
259 +                page += 4;
260 +        while (PFLAG_ISCLEAR(page))
261 +                page++;
262 +        return page;
263 + #endif
264 + }
265 +
266 + static inline int find_next_page_clear(int page)
267 + {
268 + #if HAVE_FAST_STRCHR
269 +        char *match = strchr(mainBuffer.dirtyPages + page, PFLAG_CLEAR_VALUE);
270 +        return match ? match - mainBuffer.dirtyPages : mainBuffer.pageCount;
271 + #else
272 +        while (PFLAG_ISSET_4(page))
273 +                page += 4;
274 +        while (PFLAG_ISSET(page))
275 +                page++;
276 +        return page;
277 + #endif
278 + }
279 +
280 + static int zero_fd = -1;
281 + static bool Screen_fault_handler_init();
282 + static struct sigaction vosf_sa;
283 +
284 + #ifdef HAVE_PTHREADS
285 + static pthread_mutex_t vosf_lock = PTHREAD_MUTEX_INITIALIZER;   // Mutex to protect frame buffer (dirtyPages in fact)
286 + #define LOCK_VOSF pthread_mutex_lock(&vosf_lock);
287 + #define UNLOCK_VOSF pthread_mutex_unlock(&vosf_lock);
288 + #else
289 + #define LOCK_VOSF
290 + #define UNLOCK_VOSF
291 + #endif
292 +
293 + static int log_base_2(uint32 x)
294 + {
295 +        uint32 mask = 0x80000000;
296 +        int l = 31;
297 +        while (l >= 0 && (x & mask) == 0) {
298 +                mask >>= 1;
299 +                l--;
300 +        }
301 +        return l;
302 + }
303 + #endif /* ENABLE_VOSF */
304 +
305 + // VideoRefresh function
306 + void VideoRefreshInit(void);
307 + static void (*video_refresh)(void);
308  
309   // Prototypes
310   static void *redraw_func(void *arg);
311 < static int event2keycode(XKeyEvent *ev);
311 > static int event2keycode(XKeyEvent &ev);
312  
313  
314   // From main_unix.cpp
315 + extern char *x_display_name;
316   extern Display *x_display;
317  
318   // From sys_unix.cpp
319   extern void SysMountFirstFloppy(void);
320  
321 + #ifdef ENABLE_VOSF
322 + # include "video_vosf.h"
323 + #endif
324 +
325  
326   /*
327   *  Initialization
# Line 141 | Line 330 | extern void SysMountFirstFloppy(void);
330   // Set VideoMonitor according to video mode
331   void set_video_monitor(int width, int height, int bytes_per_row, bool native_byte_order)
332   {
333 <        int layout;
333 > #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
334 >        int layout = FLAYOUT_DIRECT;
335          switch (depth) {
336                  case 1:
337                          layout = FLAYOUT_DIRECT;
148                        VideoMonitor.mode = VMODE_1BIT;
338                          break;
339                  case 8:
340                          layout = FLAYOUT_DIRECT;
152                        VideoMonitor.mode = VMODE_8BIT;
341                          break;
342                  case 15:
343                          layout = FLAYOUT_HOST_555;
156                        VideoMonitor.mode = VMODE_16BIT;
344                          break;
345                  case 16:
346                          layout = FLAYOUT_HOST_565;
160                        VideoMonitor.mode = VMODE_16BIT;
347                          break;
348                  case 24:
349                  case 32:
350                          layout = FLAYOUT_HOST_888;
165                        VideoMonitor.mode = VMODE_32BIT;
351                          break;
352          }
168        VideoMonitor.x = width;
169        VideoMonitor.y = height;
170        VideoMonitor.bytes_per_row = bytes_per_row;
353          if (native_byte_order)
354                  MacFrameLayout = layout;
355          else
356                  MacFrameLayout = FLAYOUT_DIRECT;
357 + #endif
358 +        switch (depth) {
359 +                case 1:
360 +                        VideoMonitor.mode = VMODE_1BIT;
361 +                        break;
362 +                case 8:
363 +                        VideoMonitor.mode = VMODE_8BIT;
364 +                        break;
365 +                case 15:
366 +                        VideoMonitor.mode = VMODE_16BIT;
367 +                        break;
368 +                case 16:
369 +                        VideoMonitor.mode = VMODE_16BIT;
370 +                        break;
371 +                case 24:
372 +                case 32:
373 +                        VideoMonitor.mode = VMODE_32BIT;
374 +                        break;
375 +        }
376 +        VideoMonitor.x = width;
377 +        VideoMonitor.y = height;
378 +        VideoMonitor.bytes_per_row = bytes_per_row;
379 + }
380 +
381 + // Set window name and class
382 + static void set_window_name(Window w, int name)
383 + {
384 +        const char *str = GetString(name);
385 +        XStoreName(x_display, w, str);
386 +        XSetIconName(x_display, w, str);
387 +
388 +        XClassHint *hints;
389 +        hints = XAllocClassHint();
390 +        if (hints) {
391 +                hints->res_name = "BasiliskII";
392 +                hints->res_class = "BasiliskII";
393 +                XSetClassHint(x_display, w, hints);
394 +                XFree(hints);
395 +        }
396 + }
397 +
398 + // Set window input focus flag
399 + static void set_window_focus(Window w)
400 + {
401 +        XWMHints *hints = XAllocWMHints();
402 +        if (hints) {
403 +                hints->input = True;
404 +                hints->initial_state = NormalState;
405 +                hints->flags = InputHint | StateHint;
406 +                XSetWMHints(x_display, w, hints);
407 +                XFree(hints);
408 +        }
409 + }
410 +
411 + // Set WM_DELETE_WINDOW protocol on window (preventing it from being destroyed by the WM when clicking on the "close" widget)
412 + static void set_window_delete_protocol(Window w)
413 + {
414 +        WM_DELETE_WINDOW = XInternAtom(x_display, "WM_DELETE_WINDOW", false);
415 +        XSetWMProtocols(x_display, w, &WM_DELETE_WINDOW, 1);
416 + }
417 +
418 + // Wait until window is mapped/unmapped
419 + void wait_mapped(Window w)
420 + {
421 +        XEvent e;
422 +        do {
423 +                XMaskEvent(x_display, StructureNotifyMask, &e);
424 +        } while ((e.type != MapNotify) || (e.xmap.event != w));
425 + }
426 +
427 + void wait_unmapped(Window w)
428 + {
429 +        XEvent e;
430 +        do {
431 +                XMaskEvent(x_display, StructureNotifyMask, &e);
432 +        } while ((e.type != UnmapNotify) || (e.xmap.event != w));
433   }
434  
435   // Trap SHM errors
# Line 190 | Line 448 | static int error_handler(Display *d, XEr
448   // Init window mode
449   static bool init_window(int width, int height)
450   {
451 +        int aligned_width = (width + 15) & ~15;
452 +        int aligned_height = (height + 15) & ~15;
453 +
454          // Set absolute mouse mode
455          ADBSetRelMouseMode(false);
456  
457          // Read frame skip prefs
458          frame_skip = PrefsFindInt32("frameskip");
198        if (frame_skip == 0)
199                frame_skip = 1;
459  
460          // Create window
461          XSetWindowAttributes wattr;
462          wattr.event_mask = eventmask = win_eventmask;
463          wattr.background_pixel = black_pixel;
464 <        wattr.border_pixel = black_pixel;
206 <        wattr.backing_store = Always;
207 <        wattr.backing_planes = xdepth;
464 >        wattr.colormap = cmap[0];
465  
209        XSync(x_display, false);
466          the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
467 <                InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
212 <                CWBackingStore | CWBackingPlanes, &wattr);
213 <        XSync(x_display, false);
214 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
215 <        XMapRaised(x_display, the_win);
216 <        XSync(x_display, false);
467 >                InputOutput, vis, CWEventMask | CWBackPixel | (depth == 8 ? CWColormap : 0), &wattr);
468  
469 <        // Set colormap
470 <        if (depth == 8) {
471 <                XSetWindowColormap(x_display, the_win, cmap[0]);
472 <                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
473 <        }
469 >        // Set window name/class
470 >        set_window_name(the_win, STR_WINDOW_TITLE);
471 >
472 >        // Indicate that we want keyboard input
473 >        set_window_focus(the_win);
474 >
475 >        // Set delete protocol property
476 >        set_window_delete_protocol(the_win);
477  
478          // Make window unresizable
479 <        XSizeHints *hints;
480 <        if ((hints = XAllocSizeHints()) != NULL) {
481 <                hints->min_width = width;
482 <                hints->max_width = width;
483 <                hints->min_height = height;
484 <                hints->max_height = height;
485 <                hints->flags = PMinSize | PMaxSize;
486 <                XSetWMNormalHints(x_display, the_win, hints);
487 <                XFree((char *)hints);
479 >        {
480 >                XSizeHints *hints = XAllocSizeHints();
481 >                if (hints) {
482 >                        hints->min_width = width;
483 >                        hints->max_width = width;
484 >                        hints->min_height = height;
485 >                        hints->max_height = height;
486 >                        hints->flags = PMinSize | PMaxSize;
487 >                        XSetWMNormalHints(x_display, the_win, hints);
488 >                        XFree(hints);
489 >                }
490          }
491 +        
492 +        // Show window
493 +        XMapWindow(x_display, the_win);
494 +        wait_mapped(the_win);
495  
496          // Try to create and attach SHM image
497          have_shm = false;
498 <        if (depth != 1 && XShmQueryExtension(x_display)) {
498 >        if (depth != 1 && local_X11 && XShmQueryExtension(x_display)) {
499  
500                  // Create SHM image ("height + 2" for safety)
501                  img = XShmCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
502 <                shminfo.shmid = shmget(IPC_PRIVATE, (height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
503 <                the_buffer = (uint8 *)shmat(shminfo.shmid, 0, 0);
504 <                shminfo.shmaddr = img->data = (char *)the_buffer;
502 >                shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
503 >                the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
504 >                shminfo.shmaddr = img->data = (char *)the_buffer_copy;
505                  shminfo.readOnly = False;
506  
507                  // Try to attach SHM image, catching errors
# Line 259 | Line 519 | static bool init_window(int width, int h
519                          shmctl(shminfo.shmid, IPC_RMID, 0);
520                  }
521          }
522 <
522 >        
523          // Create normal X image if SHM doesn't work ("height + 2" for safety)
524          if (!have_shm) {
525 <                int bytes_per_row = width;
525 >                int bytes_per_row = aligned_width;
526                  switch (depth) {
527                          case 1:
528                                  bytes_per_row /= 8;
# Line 276 | Line 536 | static bool init_window(int width, int h
536                                  bytes_per_row *= 4;
537                                  break;
538                  }
539 <                the_buffer = (uint8 *)malloc((height + 2) * bytes_per_row);
540 <                img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer, width, height, 32, bytes_per_row);
539 >                the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
540 >                img = XCreateImage(x_display, vis, depth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
541          }
542  
543          // 1-Bit mode is big-endian
# Line 286 | Line 546 | static bool init_window(int width, int h
546                  img->bitmap_bit_order = MSBFirst;
547          }
548  
549 <        // Allocate memory for frame buffer copy
550 <        the_buffer_copy = (uint8 *)malloc((height + 2) * img->bytes_per_line);
549 > #ifdef ENABLE_VOSF
550 >        // Allocate a page-aligned chunk of memory for frame buffer
551 >        the_buffer_size = align_on_page_boundary((aligned_height + 2) * img->bytes_per_line);
552 >        the_host_buffer = the_buffer_copy;
553 >        
554 >        the_buffer_copy = (uint8 *)allocate_framebuffer(the_buffer_size);
555 >        memset(the_buffer_copy, 0, the_buffer_size);
556 >        
557 >        the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
558 >        memset(the_buffer, 0, the_buffer_size);
559 > #else
560 >        // Allocate memory for frame buffer
561 >        the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
562 > #endif
563  
564          // Create GC
565          the_gc = XCreateGC(x_display, the_win, 0, 0);
566          XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
567  
568 <        // Create cursor
569 <        cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)the_cursor, 16, 16, 16, 2);
570 <        cursor_image->byte_order = MSBFirst;
571 <        cursor_image->bitmap_bit_order = MSBFirst;
572 <        cursor_mask_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)the_cursor+32, 16, 16, 16, 2);
573 <        cursor_mask_image->byte_order = MSBFirst;
302 <        cursor_mask_image->bitmap_bit_order = MSBFirst;
303 <        cursor_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
304 <        cursor_mask_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
305 <        cursor_gc = XCreateGC(x_display, cursor_map, 0, 0);
306 <        cursor_mask_gc = XCreateGC(x_display, cursor_mask_map, 0, 0);
307 <        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, 0, 0);
568 >        // Create no_cursor
569 >        mac_cursor = XCreatePixmapCursor(x_display,
570 >           XCreatePixmap(x_display, the_win, 1, 1, 1),
571 >           XCreatePixmap(x_display, the_win, 1, 1, 1),
572 >           &black, &white, 0, 0);
573 >        XDefineCursor(x_display, the_win, mac_cursor);
574  
575          // Set VideoMonitor
576 +        bool native_byte_order;
577   #ifdef WORDS_BIGENDIAN
578 <        set_video_monitor(width, height, img->bytes_per_line, img->bitmap_bit_order == MSBFirst);
578 >        native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
579   #else
580 <        set_video_monitor(width, height, img->bytes_per_line, img->bitmap_bit_order == LSBFirst);
580 >        native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
581   #endif
582 < #if REAL_ADDRESSING
583 <        VideoMonitor.mac_frame_base = (uint32)the_buffer;
584 <        MacFrameLayout = FLAYOUT_DIRECT;
582 > #ifdef ENABLE_VOSF
583 >        Screen_blitter_init(&visualInfo, native_byte_order);
584 > #endif
585 >        set_video_monitor(width, height, img->bytes_per_line, native_byte_order);
586 >        
587 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
588 >        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
589   #else
590          VideoMonitor.mac_frame_base = MacFrameBaseMac;
591   #endif
592          return true;
593   }
594  
595 < // Init DGA display
596 < static bool init_dga(int width, int height)
595 > // Init fbdev DGA display
596 > static bool init_fbdev_dga(char *in_fb_name)
597   {
598 < #if ENABLE_DGA
598 > #ifdef ENABLE_FBDEV_DGA
599 >        // Find the maximum depth available
600 >        int ndepths, max_depth(0);
601 >        int *depths = XListDepths(x_display, screen, &ndepths);
602 >        if (depths == NULL) {
603 >                printf("FATAL: Could not determine the maximal depth available\n");
604 >                return false;
605 >        } else {
606 >                while (ndepths-- > 0) {
607 >                        if (depths[ndepths] > max_depth)
608 >                                max_depth = depths[ndepths];
609 >                }
610 >        }
611 >        
612 >        // Get fbdevices file path from preferences
613 >        const char *fbd_path = PrefsFindString("fbdevicefile");
614 >        
615 >        // Open fbdevices file
616 >        FILE *fp = fopen(fbd_path ? fbd_path : FBDEVICES_FILE_NAME, "r");
617 >        if (fp == NULL) {
618 >                char str[256];
619 >                sprintf(str, GetString(STR_NO_FBDEVICE_FILE_ERR), fbd_path ? fbd_path : FBDEVICES_FILE_NAME, strerror(errno));
620 >                ErrorAlert(str);
621 >                return false;
622 >        }
623 >        
624 >        int fb_depth;           // supported depth
625 >        uint32 fb_offset;       // offset used for mmap(2)
626 >        char fb_name[20];
627 >        char line[256];
628 >        bool device_found = false;
629 >        while (fgets(line, 255, fp)) {
630 >                // Read line
631 >                int len = strlen(line);
632 >                if (len == 0)
633 >                        continue;
634 >                line[len - 1] = '\0';
635 >                
636 >                // Comments begin with "#" or ";"
637 >                if ((line[0] == '#') || (line[0] == ';') || (line[0] == '\0'))
638 >                        continue;
639 >                
640 >                if ((sscanf(line, "%19s %d %x", &fb_name, &fb_depth, &fb_offset) == 3)
641 >                && (strcmp(fb_name, in_fb_name) == 0) && (fb_depth == max_depth)) {
642 >                        device_found = true;
643 >                        break;
644 >                }
645 >        }
646 >        
647 >        // fbdevices file completely read
648 >        fclose(fp);
649 >        
650 >        // Frame buffer name not found ? Then, display warning
651 >        if (!device_found) {
652 >                char str[256];
653 >                sprintf(str, GetString(STR_FBDEV_NAME_ERR), in_fb_name, max_depth);
654 >                ErrorAlert(str);
655 >                return false;
656 >        }
657 >        
658 >        int width = DisplayWidth(x_display, screen);
659 >        int height = DisplayHeight(x_display, screen);
660 >        depth = fb_depth; // max_depth
661 >        
662 >        // Set relative mouse mode
663 >        ADBSetRelMouseMode(false);
664 >        
665 >        // Create window
666 >        XSetWindowAttributes wattr;
667 >        wattr.event_mask = eventmask = dga_eventmask;
668 >        wattr.background_pixel = white_pixel;
669 >        wattr.override_redirect = True;
670 >        wattr.colormap = cmap[0];
671 >        
672 >        the_win = XCreateWindow(x_display, rootwin,
673 >                0, 0, width, height,
674 >                0, xdepth, InputOutput, vis,
675 >                CWEventMask | CWBackPixel | CWOverrideRedirect | (depth == 8 ? CWColormap : 0),
676 >                &wattr);
677 >
678 >        // Set window name/class
679 >        set_window_name(the_win, STR_WINDOW_TITLE);
680 >
681 >        // Indicate that we want keyboard input
682 >        set_window_focus(the_win);
683 >
684 >        // Show window
685 >        XMapRaised(x_display, the_win);
686 >        wait_mapped(the_win);
687 >        
688 >        // Grab mouse and keyboard
689 >        XGrabKeyboard(x_display, the_win, True,
690 >                GrabModeAsync, GrabModeAsync, CurrentTime);
691 >        XGrabPointer(x_display, the_win, True,
692 >                PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
693 >                GrabModeAsync, GrabModeAsync, the_win, None, CurrentTime);
694 >        
695 >        // Set VideoMonitor
696 >        int bytes_per_row = width;
697 >        switch (depth) {
698 >                case 1:
699 >                        bytes_per_row = ((width | 7) & ~7) >> 3;
700 >                        break;
701 >                case 15:
702 >                case 16:
703 >                        bytes_per_row *= 2;
704 >                        break;
705 >                case 24:
706 >                case 32:
707 >                        bytes_per_row *= 4;
708 >                        break;
709 >        }
710 >        
711 >        if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_PRIVATE, fbdev_fd, fb_offset)) == MAP_FAILED) {
712 >                if ((the_buffer = (uint8 *) mmap(NULL, height * bytes_per_row, PROT_READ | PROT_WRITE, MAP_SHARED, fbdev_fd, fb_offset)) == MAP_FAILED) {
713 >                        char str[256];
714 >                        sprintf(str, GetString(STR_FBDEV_MMAP_ERR), strerror(errno));
715 >                        ErrorAlert(str);
716 >                        return false;
717 >                }
718 >        }
719 >        
720 > #if ENABLE_VOSF
721 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
722 >        // Screen_blitter_init() returns TRUE if VOSF is mandatory
723 >        // i.e. the framebuffer update function is not Blit_Copy_Raw
724 >        use_vosf = Screen_blitter_init(&visualInfo, true);
725 >        
726 >        if (use_vosf) {
727 >                the_host_buffer = the_buffer;
728 >                the_buffer_size = align_on_page_boundary((height + 2) * bytes_per_row);
729 >                the_buffer_copy = (uint8 *)malloc(the_buffer_size);
730 >                memset(the_buffer_copy, 0, the_buffer_size);
731 >                the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
732 >                memset(the_buffer, 0, the_buffer_size);
733 >        }
734 > #else
735 >        use_vosf = false;
736 > #endif
737 > #endif
738 >        
739 >        set_video_monitor(width, height, bytes_per_row, true);
740 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
741 >        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
742 > #else
743 >        VideoMonitor.mac_frame_base = MacFrameBaseMac;
744 > #endif
745 >        return true;
746 > #else
747 >        ErrorAlert("Basilisk II has been compiled with fbdev DGA support disabled.");
748 >        return false;
749 > #endif
750 > }
751 >
752 > // Init XF86 DGA display
753 > static bool init_xf86_dga(int width, int height)
754 > {
755 > #ifdef ENABLE_XF86_DGA
756          // Set relative mouse mode
757          ADBSetRelMouseMode(true);
758  
759 + #ifdef ENABLE_XF86_VIDMODE
760 +        // Switch to best mode
761 +        if (has_vidmode) {
762 +                int best = 0;
763 +                for (int i=1; i<num_x_video_modes; i++) {
764 +                        if (x_video_modes[i]->hdisplay >= width && x_video_modes[i]->vdisplay >= height &&
765 +                                x_video_modes[i]->hdisplay <= x_video_modes[best]->hdisplay && x_video_modes[i]->vdisplay <= x_video_modes[best]->vdisplay) {
766 +                                best = i;
767 +                        }
768 +                }
769 +                XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
770 +                XF86VidModeSetViewPort(x_display, screen, 0, 0);
771 +                XSync(x_display, false);
772 +        }
773 + #endif
774 +
775          // Create window
776          XSetWindowAttributes wattr;
777          wattr.event_mask = eventmask = dga_eventmask;
334        wattr.border_pixel = black_pixel;
778          wattr.override_redirect = True;
779  
337        XSync(x_display, false);
780          the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
781 <                InputOutput, vis, CWEventMask | CWBorderPixel | CWOverrideRedirect, &wattr);
782 <        XSync(x_display, false);
783 <        XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
781 >                InputOutput, vis, CWEventMask | CWOverrideRedirect, &wattr);
782 >
783 >        // Set window name/class
784 >        set_window_name(the_win, STR_WINDOW_TITLE);
785 >
786 >        // Indicate that we want keyboard input
787 >        set_window_focus(the_win);
788 >
789 >        // Show window
790          XMapRaised(x_display, the_win);
791 <        XSync(x_display, false);
791 >        wait_mapped(the_win);
792  
793          // Establish direct screen connection
794          XMoveResizeWindow(x_display, the_win, 0, 0, width, height);
# Line 357 | Line 805 | static bool init_dga(int width, int heig
805          // Set colormap
806          if (depth == 8) {
807                  XSetWindowColormap(x_display, the_win, cmap[current_dga_cmap = 0]);
360                XSetWMColormapWindows(x_display, the_win, &the_win, 1);
808                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
809          }
810 +        XSync(x_display, false);
811  
812          // Set VideoMonitor
813          int bytes_per_row = (v_width + 7) & ~7;
# Line 376 | Line 824 | static bool init_dga(int width, int heig
824                          bytes_per_row *= 4;
825                          break;
826          }
827 +        
828 + #if REAL_ADDRESSING || DIRECT_ADDRESSING
829 +        // Screen_blitter_init() returns TRUE if VOSF is mandatory
830 +        // i.e. the framebuffer update function is not Blit_Copy_Raw
831 +        use_vosf = Screen_blitter_init(&visualInfo, true);
832 +        
833 +        if (use_vosf) {
834 +                the_host_buffer = the_buffer;
835 +                the_buffer_size = align_on_page_boundary((height + 2) * bytes_per_row);
836 +                the_buffer_copy = (uint8 *)malloc(the_buffer_size);
837 +                memset(the_buffer_copy, 0, the_buffer_size);
838 +                the_buffer = (uint8 *)allocate_framebuffer(the_buffer_size);
839 +                memset(the_buffer, 0, the_buffer_size);
840 +        }
841 + #elif defined(ENABLE_VOSF)
842 +        // The UAE memory handlers will already handle color conversion, if needed.
843 +        use_vosf = false;
844 + #endif
845 +        
846          set_video_monitor(width, height, bytes_per_row, true);
847 < #if REAL_ADDRESSING
848 <        VideoMonitor.mac_frame_base = (uint32)the_buffer;
849 <        MacFrameLayout = FLAYOUT_DIRECT;
847 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
848 >        VideoMonitor.mac_frame_base = Host2MacAddr(the_buffer);
849 > //      MacFrameLayout = FLAYOUT_DIRECT;
850   #else
851          VideoMonitor.mac_frame_base = MacFrameBaseMac;
852   #endif
853          return true;
854   #else
855 <        ErrorAlert("Basilisk II has been compiled with DGA support disabled.");
855 >        ErrorAlert("Basilisk II has been compiled with XF86 DGA support disabled.");
856          return false;
857   #endif
858   }
# Line 455 | Line 922 | static void keycode_init(void)
922          }
923   }
924  
925 + bool VideoInitBuffer()
926 + {
927 + #ifdef ENABLE_VOSF
928 +        if (use_vosf) {
929 +                const uint32 page_size  = getpagesize();
930 +                const uint32 page_mask  = page_size - 1;
931 +                
932 +                mainBuffer.memBase      = (uint32) the_buffer;
933 +                // Align the frame buffer on page boundary
934 +                mainBuffer.memStart             = (uint32)((((unsigned long) the_buffer) + page_mask) & ~page_mask);
935 +                mainBuffer.memLength    = the_buffer_size;
936 +                mainBuffer.memEnd       = mainBuffer.memStart + mainBuffer.memLength;
937 +
938 +                mainBuffer.pageSize     = page_size;
939 +                mainBuffer.pageCount    = (mainBuffer.memLength + page_mask)/mainBuffer.pageSize;
940 +                mainBuffer.pageBits     = log_base_2(mainBuffer.pageSize);
941 +
942 +                if (mainBuffer.dirtyPages != 0)
943 +                        free(mainBuffer.dirtyPages);
944 +
945 +                mainBuffer.dirtyPages = (char *) malloc(mainBuffer.pageCount + 2);
946 +
947 +                if (mainBuffer.pageInfo != 0)
948 +                        free(mainBuffer.pageInfo);
949 +
950 +                mainBuffer.pageInfo = (ScreenPageInfo *) malloc(mainBuffer.pageCount * sizeof(ScreenPageInfo));
951 +
952 +                if ((mainBuffer.dirtyPages == 0) || (mainBuffer.pageInfo == 0))
953 +                        return false;
954 +                
955 +                mainBuffer.dirty = false;
956 +
957 +                PFLAG_CLEAR_ALL;
958 +                // Safety net to insure the loops in the update routines will terminate
959 +                // See a discussion in <video_vosf.h> for further details
960 +                PFLAG_CLEAR(mainBuffer.pageCount);
961 +                PFLAG_SET(mainBuffer.pageCount+1);
962 +
963 +                uint32 a = 0;
964 +                for (int i = 0; i < mainBuffer.pageCount; i++) {
965 +                        int y1 = a / VideoMonitor.bytes_per_row;
966 +                        if (y1 >= VideoMonitor.y)
967 +                                y1 = VideoMonitor.y - 1;
968 +
969 +                        int y2 = (a + mainBuffer.pageSize) / VideoMonitor.bytes_per_row;
970 +                        if (y2 >= VideoMonitor.y)
971 +                                y2 = VideoMonitor.y - 1;
972 +
973 +                        mainBuffer.pageInfo[i].top = y1;
974 +                        mainBuffer.pageInfo[i].bottom = y2;
975 +
976 +                        a += mainBuffer.pageSize;
977 +                        if (a > mainBuffer.memLength)
978 +                                a = mainBuffer.memLength;
979 +                }
980 +                
981 +                // We can now write-protect the frame buffer
982 +                if (mprotect((caddr_t)mainBuffer.memStart, mainBuffer.memLength, PROT_READ) != 0)
983 +                        return false;
984 +        }
985 + #endif
986 +        return true;
987 + }
988 +
989   bool VideoInit(bool classic)
990   {
991 + #ifdef ENABLE_VOSF
992 +        // Open /dev/zero
993 +        zero_fd = open("/dev/zero", O_RDWR);
994 +        if (zero_fd < 0) {
995 +        char str[256];
996 +                sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
997 +                ErrorAlert(str);
998 +        return false;
999 +        }
1000 +        
1001 +        // Zero the mainBuffer structure
1002 +        mainBuffer.dirtyPages = 0;
1003 +        mainBuffer.pageInfo = 0;
1004 + #endif
1005 +        
1006 +        // Check if X server runs on local machine
1007 +        local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
1008 +                 || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
1009 +    
1010          // Init keycode translation
1011          keycode_init();
1012  
1013 +        // Read prefs
1014 +        mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1015 +        mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1016 +
1017          // Find screen and root window
1018          screen = XDefaultScreen(x_display);
1019          rootwin = XRootWindow(x_display, screen);
1020 <
1020 >        
1021          // Get screen depth
1022          xdepth = DefaultDepth(x_display, screen);
1023 +        
1024 + #ifdef ENABLE_FBDEV_DGA
1025 +        // Frame buffer name
1026 +        char fb_name[20];
1027 +        
1028 +        // Could do fbdev dga ?
1029 +        if ((fbdev_fd = open(FBDEVICE_FILE_NAME, O_RDWR)) != -1)
1030 +                has_dga = true;
1031 +        else
1032 +                has_dga = false;
1033 + #endif
1034  
1035 < #if ENABLE_DGA
1035 > #ifdef ENABLE_XF86_DGA
1036          // DGA available?
1037 <        int dga_flags = 0;
1038 <        XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1039 <        has_dga = dga_flags & XF86DGADirectPresent;
1037 >        int dga_event_base, dga_error_base;
1038 >        if (local_X11 && XF86DGAQueryExtension(x_display, &dga_event_base, &dga_error_base)) {
1039 >                int dga_flags = 0;
1040 >                XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
1041 >                has_dga = dga_flags & XF86DGADirectPresent;
1042 >        } else
1043 >                has_dga = false;
1044   #endif
1045  
1046 + #ifdef ENABLE_XF86_VIDMODE
1047 +        // VidMode available?
1048 +        int vm_event_base, vm_error_base;
1049 +        has_vidmode = XF86VidModeQueryExtension(x_display, &vm_event_base, &vm_error_base);
1050 +        if (has_vidmode)
1051 +                XF86VidModeGetAllModeLines(x_display, screen, &num_x_video_modes, &x_video_modes);
1052 + #endif
1053 +        
1054          // Find black and white colors
1055          XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:00/00/00", &black);
1056          XAllocColor(x_display, DefaultColormap(x_display, screen), &black);
# Line 539 | Line 1116 | bool VideoInit(bool classic)
1116          if (mode_str) {
1117                  if (sscanf(mode_str, "win/%d/%d", &width, &height) == 2)
1118                          display_type = DISPLAY_WINDOW;
1119 <                else if (has_dga && strcmp(mode_str, "dga") == 0) {
1119 > #ifdef ENABLE_FBDEV_DGA
1120 >                else if (has_dga && sscanf(mode_str, "dga/%19s", fb_name) == 1) {
1121 > #else
1122 >                else if (has_dga && sscanf(mode_str, "dga/%d/%d", &width, &height) == 2) {
1123 > #endif
1124                          display_type = DISPLAY_DGA;
1125 +                        if (width > DisplayWidth(x_display, screen))
1126 +                                width = DisplayWidth(x_display, screen);
1127 +                        if (height > DisplayHeight(x_display, screen))
1128 +                                height = DisplayHeight(x_display, screen);
1129 +                }
1130 +                if (width <= 0)
1131                          width = DisplayWidth(x_display, screen);
1132 +                if (height <= 0)
1133                          height = DisplayHeight(x_display, screen);
546                }
1134          }
1135  
1136          // Initialize according to display type
# Line 553 | Line 1140 | bool VideoInit(bool classic)
1140                                  return false;
1141                          break;
1142                  case DISPLAY_DGA:
1143 <                        if (!init_dga(width, height))
1143 > #ifdef ENABLE_FBDEV_DGA
1144 >                        if (!init_fbdev_dga(fb_name))
1145 > #else
1146 >                        if (!init_xf86_dga(width, height))
1147 > #endif
1148                                  return false;
1149                          break;
1150          }
1151  
1152          // Lock down frame buffer
1153 <        pthread_mutex_lock(&frame_buffer_lock);
1153 >        LOCK_FRAME_BUFFER;
1154  
1155 < #if !REAL_ADDRESSING
1155 > #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
1156          // Set variables for UAE memory mapping
1157          MacFrameBaseHost = the_buffer;
1158          MacFrameSize = VideoMonitor.bytes_per_row * VideoMonitor.y;
# Line 571 | Line 1162 | bool VideoInit(bool classic)
1162                  MacFrameLayout = FLAYOUT_NONE;
1163   #endif
1164  
1165 <        // Start redraw/input thread
1165 > #ifdef ENABLE_VOSF
1166 >        if (use_vosf) {
1167 >                // Initialize the mainBuffer structure
1168 >                if (!VideoInitBuffer()) {
1169 >                        // TODO: STR_VOSF_INIT_ERR ?
1170 >                        ErrorAlert("Could not initialize Video on SEGV signals");
1171 >                return false;
1172 >                }
1173 >
1174 >                // Initialize the handler for SIGSEGV
1175 >                if (!Screen_fault_handler_init()) {
1176 >                        // TODO: STR_VOSF_INIT_ERR ?
1177 >                        ErrorAlert("Could not initialize Video on SEGV signals");
1178 >                        return false;
1179 >                }
1180 >        }
1181 > #endif
1182 >        
1183 >        // Initialize VideoRefresh function
1184 >        VideoRefreshInit();
1185 >        
1186          XSync(x_display, false);
1187 +
1188 + #ifdef HAVE_PTHREADS
1189 +        // Start redraw/input thread
1190          redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1191 <        if (!redraw_thread_active)
1191 >        if (!redraw_thread_active) {
1192                  printf("FATAL: cannot create redraw thread\n");
1193 <        return redraw_thread_active;
1193 >                return false;
1194 >        }
1195 > #endif
1196 >        return true;
1197   }
1198  
1199  
# Line 586 | Line 1203 | bool VideoInit(bool classic)
1203  
1204   void VideoExit(void)
1205   {
1206 + #ifdef HAVE_PTHREADS
1207          // Stop redraw thread
1208          if (redraw_thread_active) {
1209                  redraw_thread_cancel = true;
# Line 595 | Line 1213 | void VideoExit(void)
1213                  pthread_join(redraw_thread, NULL);
1214                  redraw_thread_active = false;
1215          }
1216 + #endif
1217  
1218          // Unlock frame buffer
1219 <        pthread_mutex_unlock(&frame_buffer_lock);
1219 >        UNLOCK_FRAME_BUFFER;
1220  
1221          // Close window and server connection
1222          if (x_display != NULL) {
1223                  XSync(x_display, false);
1224  
1225 < #if ENABLE_DGA
1225 > #ifdef ENABLE_XF86_DGA
1226                  if (display_type == DISPLAY_DGA) {
1227                          XF86DGADirectVideo(x_display, screen, 0);
1228                          XUngrabPointer(x_display, CurrentTime);
# Line 611 | Line 1230 | void VideoExit(void)
1230                  }
1231   #endif
1232  
1233 <                if (the_buffer_copy) {
1234 <                        free(the_buffer_copy);
1235 <                        the_buffer_copy = NULL;
1233 > #ifdef ENABLE_XF86_VIDMODE
1234 >                if (has_vidmode && display_type == DISPLAY_DGA)
1235 >                        XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
1236 > #endif
1237 >
1238 > #ifdef ENABLE_FBDEV_DGA
1239 >                if (display_type == DISPLAY_DGA) {
1240 >                        XUngrabPointer(x_display, CurrentTime);
1241 >                        XUngrabKeyboard(x_display, CurrentTime);
1242 >                        close(fbdev_fd);
1243                  }
1244 + #endif
1245  
1246                  XFlush(x_display);
1247                  XSync(x_display, false);
# Line 622 | Line 1249 | void VideoExit(void)
1249                          XFreeColormap(x_display, cmap[0]);
1250                          XFreeColormap(x_display, cmap[1]);
1251                  }
1252 +                
1253 +                if (!use_vosf) {
1254 +                        if (the_buffer) {
1255 +                                free(the_buffer);
1256 +                                the_buffer = NULL;
1257 +                        }
1258 +
1259 +                        if (!have_shm && the_buffer_copy) {
1260 +                                free(the_buffer_copy);
1261 +                                the_buffer_copy = NULL;
1262 +                        }
1263 +                }
1264 + #ifdef ENABLE_VOSF
1265 +                else {
1266 +                        if (the_buffer != (uint8 *)MAP_FAILED) {
1267 +                                munmap((caddr_t)the_buffer, the_buffer_size);
1268 +                                the_buffer = 0;
1269 +                        }
1270 +                        
1271 +                        if (the_buffer_copy != (uint8 *)MAP_FAILED) {
1272 +                                munmap((caddr_t)the_buffer_copy, the_buffer_size);
1273 +                                the_buffer_copy = 0;
1274 +                        }
1275 +                }
1276 + #endif
1277          }
1278 +        
1279 + #ifdef ENABLE_VOSF
1280 +        if (use_vosf) {
1281 +                // Clear mainBuffer data
1282 +                if (mainBuffer.pageInfo) {
1283 +                        free(mainBuffer.pageInfo);
1284 +                        mainBuffer.pageInfo = 0;
1285 +                }
1286 +
1287 +                if (mainBuffer.dirtyPages) {
1288 +                        free(mainBuffer.dirtyPages);
1289 +                        mainBuffer.dirtyPages = 0;
1290 +                }
1291 +        }
1292 +
1293 +        // Close /dev/zero
1294 +        if (zero_fd > 0)
1295 +                close(zero_fd);
1296 + #endif
1297   }
1298  
1299  
# Line 650 | Line 1321 | void VideoInterrupt(void)
1321  
1322          // Temporarily give up frame buffer lock (this is the point where
1323          // we are suspended when the user presses Ctrl-Tab)
1324 <        pthread_mutex_unlock(&frame_buffer_lock);
1325 <        pthread_mutex_lock(&frame_buffer_lock);
1324 >        UNLOCK_FRAME_BUFFER;
1325 >        LOCK_FRAME_BUFFER;
1326   }
1327  
1328  
# Line 661 | Line 1332 | void VideoInterrupt(void)
1332  
1333   void video_set_palette(uint8 *pal)
1334   {
1335 <        pthread_mutex_lock(&palette_lock);
1335 >        LOCK_PALETTE;
1336  
1337          // Convert colors to XColor array
1338          for (int i=0; i<256; i++) {
# Line 675 | Line 1346 | void video_set_palette(uint8 *pal)
1346          // Tell redraw thread to change palette
1347          palette_changed = true;
1348  
1349 <        pthread_mutex_unlock(&palette_lock);
1349 >        UNLOCK_PALETTE;
1350   }
1351  
1352  
# Line 683 | Line 1354 | void video_set_palette(uint8 *pal)
1354   *  Suspend/resume emulator
1355   */
1356  
1357 < #if ENABLE_DGA
1357 > #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1358   static void suspend_emul(void)
1359   {
1360          if (display_type == DISPLAY_DGA) {
# Line 692 | Line 1363 | static void suspend_emul(void)
1363                  ctrl_down = false;
1364  
1365                  // Lock frame buffer (this will stop the MacOS thread)
1366 <                pthread_mutex_lock(&frame_buffer_lock);
1366 >                LOCK_FRAME_BUFFER;
1367  
1368                  // Save frame buffer
1369                  fb_save = malloc(VideoMonitor.y * VideoMonitor.bytes_per_row);
# Line 700 | Line 1371 | static void suspend_emul(void)
1371                          memcpy(fb_save, the_buffer, VideoMonitor.y * VideoMonitor.bytes_per_row);
1372  
1373                  // Close full screen display
1374 + #ifdef ENABLE_XF86_DGA
1375                  XF86DGADirectVideo(x_display, screen, 0);
1376 + #endif
1377                  XUngrabPointer(x_display, CurrentTime);
1378                  XUngrabKeyboard(x_display, CurrentTime);
1379                  XUnmapWindow(x_display, the_win);
1380 <                XSync(x_display, false);
1380 >                wait_unmapped(the_win);
1381  
1382                  // Open "suspend" window
1383                  XSetWindowAttributes wattr;
1384                  wattr.event_mask = KeyPressMask;
1385                  wattr.background_pixel = black_pixel;
1386 <                wattr.border_pixel = black_pixel;
714 <                wattr.backing_store = Always;
715 <                wattr.backing_planes = xdepth;
716 <                wattr.colormap = DefaultColormap(x_display, screen);
717 <                XSync(x_display, false);
1386 >                
1387                  suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1388 <                        InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
1389 <                        CWBackingStore | CWBackingPlanes | (xdepth == 8 ? CWColormap : 0), &wattr);
1390 <                XSync(x_display, false);
1391 <                XStoreName(x_display, suspend_win, GetString(STR_SUSPEND_WINDOW_TITLE));
723 <                XMapRaised(x_display, suspend_win);
724 <                XSync(x_display, false);
1388 >                        InputOutput, vis, CWEventMask | CWBackPixel, &wattr);
1389 >                set_window_name(suspend_win, STR_SUSPEND_WINDOW_TITLE);
1390 >                set_window_focus(suspend_win);
1391 >                XMapWindow(x_display, suspend_win);
1392                  emul_suspended = true;
1393          }
1394   }
# Line 734 | Line 1401 | static void resume_emul(void)
1401  
1402          // Reopen full screen display
1403          XMapRaised(x_display, the_win);
1404 +        wait_mapped(the_win);
1405          XWarpPointer(x_display, None, rootwin, 0, 0, 0, 0, 0, 0);
738        XSync(x_display, false);
1406          XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1407          XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1408 + #ifdef ENABLE_XF86_DGA
1409          XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1410          XF86DGASetViewPort(x_display, screen, 0, 0);
1411 + #endif
1412          XSync(x_display, false);
1413 <
1413 >        
1414 >        // the_buffer already contains the data to restore. i.e. since a temporary
1415 >        // frame buffer is used when VOSF is actually used, fb_save is therefore
1416 >        // not necessary.
1417 > #ifdef ENABLE_VOSF
1418 >        if (use_vosf) {
1419 >                LOCK_VOSF;
1420 >                PFLAG_SET_ALL;
1421 >                UNLOCK_VOSF;
1422 >                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1423 >        }
1424 > #endif
1425 >        
1426          // Restore frame buffer
1427          if (fb_save) {
1428 + #ifdef ENABLE_VOSF
1429 +                // Don't copy fb_save to the temporary frame buffer in VOSF mode
1430 +                if (!use_vosf)
1431 + #endif
1432                  memcpy(the_buffer, fb_save, VideoMonitor.y * VideoMonitor.bytes_per_row);
1433                  free(fb_save);
1434                  fb_save = NULL;
1435          }
1436 +        
1437 + #ifdef ENABLE_XF86_DGA
1438          if (depth == 8)
1439                  XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1440 + #endif
1441  
1442          // Unlock frame buffer (and continue MacOS thread)
1443 <        pthread_mutex_unlock(&frame_buffer_lock);
1443 >        UNLOCK_FRAME_BUFFER;
1444          emul_suspended = false;
1445   }
1446   #endif
# Line 815 | Line 1503 | static int kc_decode(KeySym ks)
1503                  case XK_period: case XK_greater: return 0x2f;
1504                  case XK_slash: case XK_question: return 0x2c;
1505  
1506 < #if ENABLE_DGA
1506 > #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1507                  case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1508   #else
1509                  case XK_Tab: return 0x30;
# Line 907 | Line 1595 | static int kc_decode(KeySym ks)
1595          return -1;
1596   }
1597  
1598 < static int event2keycode(XKeyEvent *ev)
1598 > static int event2keycode(XKeyEvent &ev)
1599   {
1600          KeySym ks;
1601          int as;
1602          int i = 0;
1603  
1604          do {
1605 <                ks = XLookupKeysym(ev, i++);
1605 >                ks = XLookupKeysym(&ev, i++);
1606                  as = kc_decode(ks);
1607                  if (as != -1)
1608                          return as;
# Line 930 | Line 1618 | static int event2keycode(XKeyEvent *ev)
1618  
1619   static void handle_events(void)
1620   {
1621 <        XEvent event;
1622 <        for (;;) {
1623 <                if (!XCheckMaskEvent(x_display, eventmask, &event))
936 <                        break;
1621 >        while (XPending(x_display)) {
1622 >                XEvent event;
1623 >                XNextEvent(x_display, &event);
1624  
1625                  switch (event.type) {
1626                          // Mouse button
1627                          case ButtonPress: {
1628 <                                unsigned int button = ((XButtonEvent *)&event)->button;
1628 >                                unsigned int button = event.xbutton.button;
1629                                  if (button < 4)
1630                                          ADBMouseDown(button - 1);
1631 +                                else if (button < 6) {  // Wheel mouse
1632 +                                        if (mouse_wheel_mode == 0) {
1633 +                                                int key = (button == 5) ? 0x79 : 0x74;  // Page up/down
1634 +                                                ADBKeyDown(key);
1635 +                                                ADBKeyUp(key);
1636 +                                        } else {
1637 +                                                int key = (button == 5) ? 0x3d : 0x3e;  // Cursor up/down
1638 +                                                for(int i=0; i<mouse_wheel_lines; i++) {
1639 +                                                        ADBKeyDown(key);
1640 +                                                        ADBKeyUp(key);
1641 +                                                }
1642 +                                        }
1643 +                                }
1644                                  break;
1645                          }
1646                          case ButtonRelease: {
1647 <                                unsigned int button = ((XButtonEvent *)&event)->button;
1647 >                                unsigned int button = event.xbutton.button;
1648                                  if (button < 4)
1649                                          ADBMouseUp(button - 1);
1650                                  break;
# Line 952 | Line 1652 | static void handle_events(void)
1652  
1653                          // Mouse moved
1654                          case EnterNotify:
955                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
956                                break;
1655                          case MotionNotify:
1656 <                                ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1656 >                                ADBMouseMoved(event.xmotion.x, event.xmotion.y);
1657                                  break;
1658  
1659                          // Keyboard
1660                          case KeyPress: {
1661                                  int code;
1662                                  if (use_keycodes) {
1663 <                                        event2keycode((XKeyEvent *)&event);     // This is called to process the hotkeys
1664 <                                        code = keycode_table[((XKeyEvent *)&event)->keycode & 0xff];
1663 >                                        event2keycode(event.xkey);      // This is called to process the hotkeys
1664 >                                        code = keycode_table[event.xkey.keycode & 0xff];
1665                                  } else
1666 <                                        code = event2keycode((XKeyEvent *)&event);
1666 >                                        code = event2keycode(event.xkey);
1667                                  if (code != -1) {
1668                                          if (!emul_suspended) {
1669 <                                                ADBKeyDown(code);
1669 >                                                if (code == 0x39) {     // Caps Lock pressed
1670 >                                                        if (caps_on) {
1671 >                                                                ADBKeyUp(code);
1672 >                                                                caps_on = false;
1673 >                                                        } else {
1674 >                                                                ADBKeyDown(code);
1675 >                                                                caps_on = true;
1676 >                                                        }
1677 >                                                } else
1678 >                                                        ADBKeyDown(code);
1679                                                  if (code == 0x36)
1680                                                          ctrl_down = true;
1681                                          } else {
1682 < #if ENABLE_DGA
1682 > #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1683                                                  if (code == 0x31)
1684                                                          resume_emul();  // Space wakes us up
1685   #endif
# Line 983 | Line 1690 | static void handle_events(void)
1690                          case KeyRelease: {
1691                                  int code;
1692                                  if (use_keycodes) {
1693 <                                        event2keycode((XKeyEvent *)&event);     // This is called to process the hotkeys
1694 <                                        code = keycode_table[((XKeyEvent *)&event)->keycode & 0xff];
1693 >                                        event2keycode(event.xkey);      // This is called to process the hotkeys
1694 >                                        code = keycode_table[event.xkey.keycode & 0xff];
1695                                  } else
1696 <                                        code = event2keycode((XKeyEvent *)&event);
1697 <                                if (code != -1) {
1696 >                                        code = event2keycode(event.xkey);
1697 >                                if (code != -1 && code != 0x39) {       // Don't propagate Caps Lock releases
1698                                          ADBKeyUp(code);
1699                                          if (code == 0x36)
1700                                                  ctrl_down = false;
# Line 997 | Line 1704 | static void handle_events(void)
1704  
1705                          // Hidden parts exposed, force complete refresh of window
1706                          case Expose:
1707 <                                if (display_type == DISPLAY_WINDOW)
1708 <                                        memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1707 >                                if (display_type == DISPLAY_WINDOW) {
1708 > #ifdef ENABLE_VOSF
1709 >                                        if (use_vosf) {                 // VOSF refresh
1710 >                                                LOCK_VOSF;
1711 >                                                PFLAG_SET_ALL;
1712 >                                                UNLOCK_VOSF;
1713 >                                                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1714 >                                        }
1715 >                                        else
1716 > #endif
1717 >                                        if (frame_skip == 0) {  // Dynamic refresh
1718 >                                                int x1, y1;
1719 >                                                for (y1=0; y1<16; y1++)
1720 >                                                for (x1=0; x1<16; x1++)
1721 >                                                        updt_box[x1][y1] = true;
1722 >                                                nr_boxes = 16 * 16;
1723 >                                        } else                                  // Static refresh
1724 >                                                memset(the_buffer_copy, 0, VideoMonitor.bytes_per_row * VideoMonitor.y);
1725 >                                }
1726 >                                break;
1727 >
1728 >                        // Window "close" widget clicked
1729 >                        case ClientMessage:
1730 >                                if (event.xclient.format == 32 && event.xclient.data.l[0] == WM_DELETE_WINDOW) {
1731 >                                        ADBKeyDown(0x7f);       // Power key
1732 >                                        ADBKeyUp(0x7f);
1733 >                                }
1734                                  break;
1735                  }
1736          }
# Line 1009 | Line 1741 | static void handle_events(void)
1741   *  Window display update
1742   */
1743  
1744 < static void update_display(void)
1744 > // Dynamic display update (variable frame rate for each box)
1745 > static void update_display_dynamic(int ticker)
1746   {
1747 <        // In classic mode, copy the frame buffer from Mac RAM
1748 <        if (classic_mode)
1749 <                memcpy(the_buffer, Mac2HostAddr(0x3fa700), VideoMonitor.bytes_per_row * VideoMonitor.y);
1747 >        int y1, y2, y2s, y2a, i, x1, xm, xmo, ymo, yo, yi, yil, xi;
1748 >        int xil = 0;
1749 >        int rxm = 0, rxmo = 0;
1750 >        int bytes_per_row = VideoMonitor.bytes_per_row;
1751 >        int bytes_per_pixel = VideoMonitor.bytes_per_row / VideoMonitor.x;
1752 >        int rx = VideoMonitor.bytes_per_row / 16;
1753 >        int ry = VideoMonitor.y / 16;
1754 >        int max_box;
1755 >
1756 >        y2s = sm_uptd[ticker % 8];
1757 >        y2a = 8;
1758 >        for (i = 0; i < 6; i++)
1759 >                if (ticker % (2 << i))
1760 >                        break;
1761 >        max_box = sm_no_boxes[i];
1762  
1763 +        if (y2a) {
1764 +                for (y1=0; y1<16; y1++) {
1765 +                        for (y2=y2s; y2 < ry; y2 += y2a) {
1766 +                                i = ((y1 * ry) + y2) * bytes_per_row;
1767 +                                for (x1=0; x1<16; x1++, i += rx) {
1768 +                                        if (updt_box[x1][y1] == false) {
1769 +                                                if (memcmp(&the_buffer_copy[i], &the_buffer[i], rx)) {
1770 +                                                        updt_box[x1][y1] = true;
1771 +                                                        nr_boxes++;
1772 +                                                }
1773 +                                        }
1774 +                                }
1775 +                        }
1776 +                }
1777 +        }
1778 +
1779 +        if ((nr_boxes <= max_box) && (nr_boxes)) {
1780 +                for (y1=0; y1<16; y1++) {
1781 +                        for (x1=0; x1<16; x1++) {
1782 +                                if (updt_box[x1][y1] == true) {
1783 +                                        if (rxm == 0)
1784 +                                                xm = x1;
1785 +                                        rxm += rx;
1786 +                                        updt_box[x1][y1] = false;
1787 +                                }
1788 +                                if (((updt_box[x1+1][y1] == false) || (x1 == 15)) && (rxm)) {
1789 +                                        if ((rxmo != rxm) || (xmo != xm) || (yo != y1 - 1)) {
1790 +                                                if (rxmo) {
1791 +                                                        xi = xmo * rx;
1792 +                                                        yi = ymo * ry;
1793 +                                                        xil = rxmo;
1794 +                                                        yil = (yo - ymo +1) * ry;
1795 +                                                }
1796 +                                                rxmo = rxm;
1797 +                                                xmo = xm;
1798 +                                                ymo = y1;
1799 +                                        }
1800 +                                        rxm = 0;
1801 +                                        yo = y1;
1802 +                                }      
1803 +                                if (xil) {
1804 +                                        i = (yi * bytes_per_row) + xi;
1805 +                                        for (y2=0; y2 < yil; y2++, i += bytes_per_row)
1806 +                                                memcpy(&the_buffer_copy[i], &the_buffer[i], xil);
1807 +                                        if (depth == 1) {
1808 +                                                if (have_shm)
1809 +                                                        XShmPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil, 0);
1810 +                                                else
1811 +                                                        XPutImage(x_display, the_win, the_gc, img, xi * 8, yi, xi * 8, yi, xil * 8, yil);
1812 +                                        } else {
1813 +                                                if (have_shm)
1814 +                                                        XShmPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil, 0);
1815 +                                                else
1816 +                                                        XPutImage(x_display, the_win, the_gc, img, xi / bytes_per_pixel, yi, xi / bytes_per_pixel, yi, xil / bytes_per_pixel, yil);
1817 +                                        }
1818 +                                        xil = 0;
1819 +                                }
1820 +                                if ((x1 == 15) && (y1 == 15) && (rxmo)) {
1821 +                                        x1--;
1822 +                                        xi = xmo * rx;
1823 +                                        yi = ymo * ry;
1824 +                                        xil = rxmo;
1825 +                                        yil = (yo - ymo +1) * ry;
1826 +                                        rxmo = 0;
1827 +                                }
1828 +                        }
1829 +                }
1830 +                nr_boxes = 0;
1831 +        }
1832 + }
1833 +
1834 + // Static display update (fixed frame rate, but incremental)
1835 + static void update_display_static(void)
1836 + {
1837          // Incremental update code
1838          int wide = 0, high = 0, x1, x2, y1, y2, i, j;
1839          int bytes_per_row = VideoMonitor.bytes_per_row;
# Line 1041 | Line 1860 | static void update_display(void)
1860          // Check for first column from left and first column from right that have changed
1861          if (high) {
1862                  if (depth == 1) {
1863 <                        x1 = VideoMonitor.x;
1863 >                        x1 = VideoMonitor.x - 1;
1864                          for (j=y1; j<=y2; j++) {
1865                                  p = &the_buffer[j * bytes_per_row];
1866                                  p2 = &the_buffer_copy[j * bytes_per_row];
# Line 1050 | Line 1869 | static void update_display(void)
1869                                                  x1 = i << 3;
1870                                                  break;
1871                                          }
1872 <                                        p++;
1054 <                                        p2++;
1872 >                                        p++; p2++;
1873                                  }
1874                          }
1875                          x2 = x1;
# Line 1061 | Line 1879 | static void update_display(void)
1879                                  p += bytes_per_row;
1880                                  p2 += bytes_per_row;
1881                                  for (i=(VideoMonitor.x>>3); i>(x2>>3); i--) {
1882 <                                        p--;
1065 <                                        p2--;
1882 >                                        p--; p2--;
1883                                          if (*p != *p2) {
1884 <                                                x2 = i << 3;
1884 >                                                x2 = (i << 3) + 7;
1885                                                  break;
1886                                          }
1887                                  }
1888                          }
1889 <                        wide = x2 - x1;
1889 >                        wide = x2 - x1 + 1;
1890  
1891                          // Update copy of the_buffer
1892                          if (high && wide) {
1893                                  for (j=y1; j<=y2; j++) {
1894                                          i = j * bytes_per_row + (x1 >> 3);
1895 <                                        memcpy(&the_buffer_copy[i], &the_buffer[i], wide >> 3);
1895 >                                        memcpy(the_buffer_copy + i, the_buffer + i, wide >> 3);
1896                                  }
1897                          }
1898  
# Line 1084 | Line 1901 | static void update_display(void)
1901                          for (j=y1; j<=y2; j++) {
1902                                  p = &the_buffer[j * bytes_per_row];
1903                                  p2 = &the_buffer_copy[j * bytes_per_row];
1904 <                                for (i=0; i<x1; i++) {
1905 <                                        if (memcmp(p, p2, bytes_per_pixel)) {
1906 <                                                x1 = i;
1904 >                                for (i=0; i<x1*bytes_per_pixel; i++) {
1905 >                                        if (*p != *p2) {
1906 >                                                x1 = i / bytes_per_pixel;
1907                                                  break;
1908                                          }
1909 <                                        p += bytes_per_pixel;
1093 <                                        p2 += bytes_per_pixel;
1909 >                                        p++; p2++;
1910                                  }
1911                          }
1912                          x2 = x1;
# Line 1099 | Line 1915 | static void update_display(void)
1915                                  p2 = &the_buffer_copy[j * bytes_per_row];
1916                                  p += bytes_per_row;
1917                                  p2 += bytes_per_row;
1918 <                                for (i=VideoMonitor.x; i>x2; i--) {
1919 <                                        p -= bytes_per_pixel;
1920 <                                        p2 -= bytes_per_pixel;
1921 <                                        if (memcmp(p, p2, bytes_per_pixel)) {
1922 <                                                x2 = i;
1918 >                                for (i=VideoMonitor.x*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
1919 >                                        p--;
1920 >                                        p2--;
1921 >                                        if (*p != *p2) {
1922 >                                                x2 = i / bytes_per_pixel;
1923                                                  break;
1924                                          }
1925                                  }
# Line 1114 | Line 1930 | static void update_display(void)
1930                          if (high && wide) {
1931                                  for (j=y1; j<=y2; j++) {
1932                                          i = j * bytes_per_row + x1 * bytes_per_pixel;
1933 <                                        memcpy(&the_buffer_copy[i], &the_buffer[i], bytes_per_pixel * wide);
1933 >                                        memcpy(the_buffer_copy + i, the_buffer + i, bytes_per_pixel * wide);
1934                                  }
1935                          }
1936                  }
# Line 1127 | Line 1943 | static void update_display(void)
1943                  else
1944                          XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
1945          }
1130
1131        // Has the Mac started? (cursor data is not valid otherwise)
1132        if (HasMacStarted()) {
1133
1134                // Set new cursor image if it was changed
1135                if (memcmp(the_cursor, Mac2HostAddr(0x844), 64)) {
1136                        memcpy(the_cursor, Mac2HostAddr(0x844), 64);
1137                        memcpy(cursor_image->data, the_cursor, 32);
1138                        memcpy(cursor_mask_image->data, the_cursor+32, 32);
1139                        XFreeCursor(x_display, mac_cursor);
1140                        XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
1141                        XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
1142                        mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, ReadMacInt8(0x885), ReadMacInt8(0x887));
1143                        XDefineCursor(x_display, the_win, mac_cursor);
1144                }
1145        }
1946   }
1947  
1948  
1949   /*
1950 < *  Thread for screen refresh, input handling etc.
1950 > *      Screen refresh functions
1951   */
1952  
1953 < static void *redraw_func(void *arg)
1954 < {
1955 <        int tick_counter = 0;
1953 > // We suggest the compiler to inline the next two functions so that it
1954 > // may specialise the code according to the current screen depth and
1955 > // display type. A clever compiler would do that job by itself though...
1956  
1957 <        while (!redraw_thread_cancel) {
1957 > // NOTE: update_display_vosf is inlined too
1958  
1959 <                // Wait
1960 < #ifdef HAVE_NANOSLEEP
1961 <                struct timespec req = {0, 16666667};
1962 <                nanosleep(&req, NULL);
1963 < #else
1964 <                usleep(16667);
1959 > static inline void possibly_quit_dga_mode()
1960 > {
1961 > #if defined(ENABLE_XF86_DGA) || defined(ENABLE_FBDEV_DGA)
1962 >        // Quit DGA mode if requested
1963 >        if (quit_full_screen) {
1964 >                quit_full_screen = false;
1965 > #ifdef ENABLE_XF86_DGA
1966 >                XF86DGADirectVideo(x_display, screen, 0);
1967   #endif
1968 +                XUngrabPointer(x_display, CurrentTime);
1969 +                XUngrabKeyboard(x_display, CurrentTime);
1970 +                XUnmapWindow(x_display, the_win);
1971 +                XSync(x_display, false);
1972 +        }
1973 + #endif
1974 + }
1975  
1976 < #if ENABLE_DGA
1977 <                // Quit DGA mode if requested
1978 <                if (quit_full_screen) {
1979 <                        quit_full_screen = false;
1976 > static inline void handle_palette_changes(int depth, int display_type)
1977 > {
1978 >        LOCK_PALETTE;
1979 >
1980 >        if (palette_changed) {
1981 >                palette_changed = false;
1982 >                if (depth == 8) {
1983 >                        XStoreColors(x_display, cmap[0], palette, 256);
1984 >                        XStoreColors(x_display, cmap[1], palette, 256);
1985 >                        XSync(x_display, false);
1986 >                                
1987 > #ifdef ENABLE_XF86_DGA
1988                          if (display_type == DISPLAY_DGA) {
1989 <                                XF86DGADirectVideo(x_display, screen, 0);
1990 <                                XUngrabPointer(x_display, CurrentTime);
1174 <                                XUngrabKeyboard(x_display, CurrentTime);
1175 <                                XUnmapWindow(x_display, the_win);
1176 <                                XSync(x_display, false);
1989 >                                current_dga_cmap ^= 1;
1990 >                                XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1991                          }
1178                }
1992   #endif
1993 +                }
1994 +        }
1995  
1996 <                // Handle X events
1997 <                handle_events();
1996 >        UNLOCK_PALETTE;
1997 > }
1998  
1999 <                // Handle palette changes
2000 <                pthread_mutex_lock(&palette_lock);
2001 <                if (palette_changed) {
2002 <                        palette_changed = false;
2003 <                        if (depth == 8) {
2004 <                                XStoreColors(x_display, cmap[0], palette, 256);
2005 <                                XStoreColors(x_display, cmap[1], palette, 256);
2006 < #if ENABLE_DGA
2007 <                                if (display_type == DISPLAY_DGA) {
2008 <                                        current_dga_cmap ^= 1;
2009 <                                        XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
2010 <                                }
2011 < #endif
2012 <                        }
1999 > static void video_refresh_dga(void)
2000 > {
2001 >        // Quit DGA mode if requested
2002 >        possibly_quit_dga_mode();
2003 >        
2004 >        // Handle X events
2005 >        handle_events();
2006 >        
2007 >        // Handle palette changes
2008 >        handle_palette_changes(depth, DISPLAY_DGA);
2009 > }
2010 >
2011 > #ifdef ENABLE_VOSF
2012 > #if REAL_ADDRESSING || DIRECT_ADDRESSING
2013 > static void video_refresh_dga_vosf(void)
2014 > {
2015 >        // Quit DGA mode if requested
2016 >        possibly_quit_dga_mode();
2017 >        
2018 >        // Handle X events
2019 >        handle_events();
2020 >        
2021 >        // Handle palette changes
2022 >        handle_palette_changes(depth, DISPLAY_DGA);
2023 >        
2024 >        // Update display (VOSF variant)
2025 >        static int tick_counter = 0;
2026 >        if (++tick_counter >= frame_skip) {
2027 >                tick_counter = 0;
2028 >                if (mainBuffer.dirty) {
2029 >                        LOCK_VOSF;
2030 >                        update_display_dga_vosf();
2031 >                        UNLOCK_VOSF;
2032                  }
2033 <                pthread_mutex_unlock(&palette_lock);
2033 >        }
2034 > }
2035 > #endif
2036  
2037 <                // In window mode, update display and mouse pointer
2038 <                if (display_type == DISPLAY_WINDOW) {
2039 <                        tick_counter++;
2040 <                        if (tick_counter >= frame_skip) {
2041 <                                tick_counter = 0;
2042 <                                update_display();
2043 <                        }
2037 > static void video_refresh_window_vosf(void)
2038 > {
2039 >        // Quit DGA mode if requested
2040 >        possibly_quit_dga_mode();
2041 >        
2042 >        // Handle X events
2043 >        handle_events();
2044 >        
2045 >        // Handle palette changes
2046 >        handle_palette_changes(depth, DISPLAY_WINDOW);
2047 >        
2048 >        // Update display (VOSF variant)
2049 >        static int tick_counter = 0;
2050 >        if (++tick_counter >= frame_skip) {
2051 >                tick_counter = 0;
2052 >                if (mainBuffer.dirty) {
2053 >                        LOCK_VOSF;
2054 >                        update_display_window_vosf();
2055 >                        UNLOCK_VOSF;
2056                  }
2057          }
2058 + }
2059 + #endif // def ENABLE_VOSF
2060 +
2061 + static void video_refresh_window_static(void)
2062 + {
2063 +        // Handle X events
2064 +        handle_events();
2065 +        
2066 +        // Handle_palette changes
2067 +        handle_palette_changes(depth, DISPLAY_WINDOW);
2068 +        
2069 +        // Update display (static variant)
2070 +        static int tick_counter = 0;
2071 +        if (++tick_counter >= frame_skip) {
2072 +                tick_counter = 0;
2073 +                update_display_static();
2074 +        }
2075 + }
2076 +
2077 + static void video_refresh_window_dynamic(void)
2078 + {
2079 +        // Handle X events
2080 +        handle_events();
2081 +        
2082 +        // Handle_palette changes
2083 +        handle_palette_changes(depth, DISPLAY_WINDOW);
2084 +        
2085 +        // Update display (dynamic variant)
2086 +        static int tick_counter = 0;
2087 +        tick_counter++;
2088 +        update_display_dynamic(tick_counter);
2089 + }
2090 +
2091 +
2092 + /*
2093 + *  Thread for screen refresh, input handling etc.
2094 + */
2095 +
2096 + void VideoRefreshInit(void)
2097 + {
2098 +        // TODO: set up specialised 8bpp VideoRefresh handlers ?
2099 +        if (display_type == DISPLAY_DGA) {
2100 + #if ENABLE_VOSF && (REAL_ADDRESSING || DIRECT_ADDRESSING)
2101 +                if (use_vosf)
2102 +                        video_refresh = video_refresh_dga_vosf;
2103 +                else
2104 + #endif
2105 +                        video_refresh = video_refresh_dga;
2106 +        }
2107 +        else {
2108 + #ifdef ENABLE_VOSF
2109 +                if (use_vosf)
2110 +                        video_refresh = video_refresh_window_vosf;
2111 +                else
2112 + #endif
2113 +                if (frame_skip == 0)
2114 +                        video_refresh = video_refresh_window_dynamic;
2115 +                else
2116 +                        video_refresh = video_refresh_window_static;
2117 +        }
2118 + }
2119 +
2120 + void VideoRefresh(void)
2121 + {
2122 +        // TODO: make main_unix/VideoRefresh call directly video_refresh() ?
2123 +        video_refresh();
2124 + }
2125 +
2126 + #ifdef HAVE_PTHREADS
2127 + static void *redraw_func(void *arg)
2128 + {
2129 +        uint64 start = GetTicks_usec();
2130 +        int64 ticks = 0;
2131 +        uint64 next = GetTicks_usec();
2132 +        while (!redraw_thread_cancel) {
2133 +                video_refresh();
2134 +                next += 16667;
2135 +                int64 delay = next - GetTicks_usec();
2136 +                if (delay > 0)
2137 +                        Delay_usec(delay);
2138 +                else if (delay < -16667)
2139 +                        next = GetTicks_usec();
2140 +                ticks++;
2141 +        }
2142 +        uint64 end = GetTicks_usec();
2143 +        printf("%Ld ticks in %Ld usec = %Ld ticks/sec\n", ticks, end - start, ticks * 1000000 / (end - start));
2144          return NULL;
2145   }
2146 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines