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.1 by cebix, 1999-10-03T14:16:25Z vs.
Revision 1.34 by gbeauche, 2001-01-11T16:38:48Z

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines