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.35 by gbeauche, 2001-01-11T18:00:40Z

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines