ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/video_x.cpp
Revision: 1.13
Committed: 2004-04-10T23:15:21Z (20 years, 7 months ago) by gbeauche
Branch: MAIN
Changes since 1.12: +460 -177 lines
Log Message:
Merge run-time depth switching code from Basilisk II.

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * video_x.cpp - Video/graphics emulation, X11 specific stuff
3     *
4 cebix 1.11 * SheepShaver (C) 1997-2004 Marc Hellwig and Christian Bauer
5 cebix 1.1 *
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
8     * the Free Software Foundation; either version 2 of the License, or
9     * (at your option) any later version.
10     *
11     * This program is distributed in the hope that it will be useful,
12     * but WITHOUT ANY WARRANTY; without even the implied warranty of
13     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14     * GNU General Public License for more details.
15     *
16     * You should have received a copy of the GNU General Public License
17     * along with this program; if not, write to the Free Software
18     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19     */
20    
21 gbeauche 1.6 #include "sysdeps.h"
22    
23 cebix 1.1 #include <X11/Xlib.h>
24     #include <X11/Xutil.h>
25     #include <X11/keysym.h>
26     #include <X11/extensions/XShm.h>
27     #include <sys/ipc.h>
28     #include <sys/shm.h>
29 gbeauche 1.6 #include <errno.h>
30 gbeauche 1.7 #include <pthread.h>
31 gbeauche 1.6
32 gbeauche 1.13 #include <algorithm>
33    
34 gbeauche 1.6 #ifdef ENABLE_XF86_DGA
35     #include <X11/extensions/xf86dga.h>
36     #endif
37    
38     #ifdef ENABLE_XF86_VIDMODE
39     # include <X11/extensions/xf86vmode.h>
40     #endif
41 cebix 1.1
42     #include "main.h"
43     #include "adb.h"
44     #include "prefs.h"
45     #include "user_strings.h"
46     #include "about_window.h"
47     #include "video.h"
48     #include "video_defs.h"
49    
50     #define DEBUG 0
51     #include "debug.h"
52    
53 gbeauche 1.13 #ifndef NO_STD_NAMESPACE
54     using std::sort;
55     #endif
56    
57 cebix 1.1
58 gbeauche 1.6 // Constants
59     const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
60 cebix 1.1
61     // Global variables
62     static int32 frame_skip;
63 gbeauche 1.8 static int16 mouse_wheel_mode;
64     static int16 mouse_wheel_lines;
65 cebix 1.1 static bool redraw_thread_active = false; // Flag: Redraw thread installed
66     static pthread_t redraw_thread; // Redraw thread
67    
68 gbeauche 1.4 static bool local_X11; // Flag: X server running on local machine?
69 cebix 1.1 static volatile bool thread_stop_req = false;
70     static volatile bool thread_stop_ack = false; // Acknowledge for thread_stop_req
71    
72     static bool has_dga = false; // Flag: Video DGA capable
73     static bool has_vidmode = false; // Flag: VidMode extension available
74    
75 gbeauche 1.3 #ifdef ENABLE_VOSF
76     static bool use_vosf = true; // Flag: VOSF enabled
77     #else
78     static const bool use_vosf = false; // VOSF not possible
79     #endif
80    
81 cebix 1.1 static bool palette_changed = false; // Flag: Palette changed, redraw thread must update palette
82     static bool ctrl_down = false; // Flag: Ctrl key pressed
83     static bool quit_full_screen = false; // Flag: DGA close requested from redraw thread
84     static volatile bool quit_full_screen_ack = false; // Acknowledge for quit_full_screen
85     static bool emerg_quit = false; // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread
86    
87     static bool emul_suspended = false; // Flag: emulator suspended
88     static Window suspend_win; // "Suspend" window
89     static void *fb_save = NULL; // Saved frame buffer for suspend
90 gbeauche 1.6 static bool use_keycodes = false; // Flag: Use keycodes rather than keysyms
91     static int keycode_table[256]; // X keycode -> Mac keycode translation table
92 cebix 1.1
93     // X11 variables
94     static int screen; // Screen number
95     static int xdepth; // Depth of X screen
96     static int depth; // Depth of Mac frame buffer
97     static Window rootwin, the_win; // Root window and our window
98 gbeauche 1.13 static int num_depths = 0; // Number of available X depths
99     static int *avail_depths = NULL; // List of available X depths
100 cebix 1.1 static XVisualInfo visualInfo;
101     static Visual *vis;
102 gbeauche 1.13 static int color_class;
103     static int rshift, rloss, gshift, gloss, bshift, bloss; // Pixel format of DirectColor/TrueColor modes
104 cebix 1.1 static Colormap cmap[2]; // Two colormaps (DGA) for 8-bit mode
105 gbeauche 1.13 static XColor x_palette[256]; // Color palette to be used as CLUT and gamma table
106    
107 cebix 1.1 static XColor black, white;
108     static unsigned long black_pixel, white_pixel;
109     static int eventmask;
110 gbeauche 1.13 static const int win_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | EnterWindowMask | ExposureMask | StructureNotifyMask;
111     static const int dga_eventmask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
112 cebix 1.1
113     // Variables for window mode
114     static GC the_gc;
115     static XImage *img = NULL;
116     static XShmSegmentInfo shminfo;
117     static XImage *cursor_image, *cursor_mask_image;
118     static Pixmap cursor_map, cursor_mask_map;
119     static Cursor mac_cursor;
120     static GC cursor_gc, cursor_mask_gc;
121     static bool cursor_changed = false; // Flag: Cursor changed, window_func must update cursor
122     static bool have_shm = false; // Flag: SHM present and usable
123 gbeauche 1.3 static uint8 *the_buffer = NULL; // Pointer to Mac frame buffer
124 cebix 1.1 static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer
125 gbeauche 1.3 static uint32 the_buffer_size; // Size of allocated the_buffer
126 cebix 1.1
127     // Variables for DGA mode
128     static char *dga_screen_base;
129     static int dga_fb_width;
130     static int current_dga_cmap;
131    
132     #ifdef ENABLE_XF86_VIDMODE
133     // Variables for XF86 VidMode support
134     static XF86VidModeModeInfo **x_video_modes; // Array of all available modes
135     static int num_x_video_modes;
136     #endif
137    
138 gbeauche 1.13 // Mutex to protect palette
139     #ifdef HAVE_SPINLOCKS
140     static spinlock_t x_palette_lock = SPIN_LOCK_UNLOCKED;
141     #define LOCK_PALETTE spin_lock(&x_palette_lock)
142     #define UNLOCK_PALETTE spin_unlock(&x_palette_lock)
143     #elif defined(HAVE_PTHREADS)
144     static pthread_mutex_t x_palette_lock = PTHREAD_MUTEX_INITIALIZER;
145     #define LOCK_PALETTE pthread_mutex_lock(&x_palette_lock)
146     #define UNLOCK_PALETTE pthread_mutex_unlock(&x_palette_lock)
147     #else
148     #define LOCK_PALETTE
149     #define UNLOCK_PALETTE
150     #endif
151    
152 cebix 1.1
153     // Prototypes
154     static void *redraw_func(void *arg);
155    
156    
157 gbeauche 1.4 // From main_unix.cpp
158     extern char *x_display_name;
159 cebix 1.1 extern Display *x_display;
160    
161     // From sys_unix.cpp
162     extern void SysMountFirstFloppy(void);
163    
164 gbeauche 1.9 // From clip_unix.cpp
165     extern void ClipboardSelectionClear(XSelectionClearEvent *);
166     extern void ClipboardSelectionRequest(XSelectionRequestEvent *);
167    
168 cebix 1.1
169 gbeauche 1.3 // Video acceleration through SIGSEGV
170     #ifdef ENABLE_VOSF
171     # include "video_vosf.h"
172     #endif
173    
174    
175 cebix 1.1 /*
176 gbeauche 1.13 * Utility functions
177     */
178    
179     // Get current video mode
180     static inline int get_current_mode(void)
181     {
182     return VModes[cur_mode].viAppleMode;
183     }
184    
185     // Find palette size for given color depth
186     static int palette_size(int mode)
187     {
188     switch (mode) {
189     case APPLE_1_BIT: return 2;
190     case APPLE_2_BIT: return 4;
191     case APPLE_4_BIT: return 16;
192     case APPLE_8_BIT: return 256;
193     case APPLE_16_BIT: return 32;
194     case APPLE_32_BIT: return 256;
195     default: return 0;
196     }
197     }
198    
199     // Map video_mode depth ID to numerical depth value
200     static inline int depth_of_video_mode(int mode)
201     {
202     int depth = -1;
203     switch (mode) {
204     case APPLE_1_BIT:
205     depth = 1;
206     break;
207     case APPLE_2_BIT:
208     depth = 2;
209     break;
210     case APPLE_4_BIT:
211     depth = 4;
212     break;
213     case APPLE_8_BIT:
214     depth = 8;
215     break;
216     case APPLE_16_BIT:
217     depth = 16;
218     break;
219     case APPLE_32_BIT:
220     depth = 32;
221     break;
222     default:
223     abort();
224     }
225     return depth;
226     }
227    
228     // Map RGB color to pixel value (this only works in TrueColor/DirectColor visuals)
229     static inline uint32 map_rgb(uint8 red, uint8 green, uint8 blue)
230     {
231     return ((red >> rloss) << rshift) | ((green >> gloss) << gshift) | ((blue >> bloss) << bshift);
232     }
233    
234    
235     // Do we have a visual for handling the specified Mac depth? If so, set the
236     // global variables "xdepth", "visualInfo", "vis" and "color_class".
237     static bool find_visual_for_depth(int depth)
238     {
239     D(bug("have_visual_for_depth(%d)\n", depth_of_video_mode(depth)));
240    
241     // 1-bit works always and uses default visual
242     if (depth == APPLE_1_BIT) {
243     vis = DefaultVisual(x_display, screen);
244     visualInfo.visualid = XVisualIDFromVisual(vis);
245     int num = 0;
246     XVisualInfo *vi = XGetVisualInfo(x_display, VisualIDMask, &visualInfo, &num);
247     visualInfo = vi[0];
248     XFree(vi);
249     xdepth = visualInfo.depth;
250     color_class = visualInfo.c_class;
251     D(bug(" found visual ID 0x%02x, depth %d\n", visualInfo.visualid, xdepth));
252     return true;
253     }
254    
255     // Calculate minimum and maximum supported X depth
256     int min_depth = 1, max_depth = 32;
257     switch (depth) {
258     #ifdef ENABLE_VOSF
259     case APPLE_2_BIT:
260     case APPLE_4_BIT: // VOSF blitters can convert 2/4/8-bit -> 8/16/32-bit
261     case APPLE_8_BIT:
262     min_depth = 8;
263     max_depth = 32;
264     break;
265     #else
266     case APPLE_2_BIT:
267     case APPLE_4_BIT: // 2/4-bit requires VOSF blitters
268     return false;
269     case APPLE_8_BIT: // 8-bit without VOSF requires an 8-bit visual
270     min_depth = 8;
271     max_depth = 8;
272     break;
273     #endif
274     case APPLE_16_BIT: // 16-bit requires a 15/16-bit visual
275     min_depth = 15;
276     max_depth = 16;
277     break;
278     case APPLE_32_BIT: // 32-bit requires a 24/32-bit visual
279     min_depth = 24;
280     max_depth = 32;
281     break;
282     }
283     D(bug(" minimum required X depth is %d, maximum supported X depth is %d\n", min_depth, max_depth));
284    
285     // Try to find a visual for one of the color depths
286     bool visual_found = false;
287     for (int i=0; i<num_depths && !visual_found; i++) {
288    
289     xdepth = avail_depths[i];
290     D(bug(" trying to find visual for depth %d\n", xdepth));
291     if (xdepth < min_depth || xdepth > max_depth)
292     continue;
293    
294     // Determine best color class for this depth
295     switch (xdepth) {
296     case 1: // Try StaticGray or StaticColor
297     if (XMatchVisualInfo(x_display, screen, xdepth, StaticGray, &visualInfo)
298     || XMatchVisualInfo(x_display, screen, xdepth, StaticColor, &visualInfo))
299     visual_found = true;
300     break;
301     case 8: // Need PseudoColor
302     if (XMatchVisualInfo(x_display, screen, xdepth, PseudoColor, &visualInfo))
303     visual_found = true;
304     break;
305     case 15:
306     case 16:
307     case 24:
308     case 32: // Try DirectColor first, as this will allow gamma correction
309     if (XMatchVisualInfo(x_display, screen, xdepth, DirectColor, &visualInfo)
310     || XMatchVisualInfo(x_display, screen, xdepth, TrueColor, &visualInfo))
311     visual_found = true;
312     break;
313     default:
314     D(bug(" not a supported depth\n"));
315     break;
316     }
317     }
318     if (!visual_found)
319     return false;
320    
321     // Visual was found
322     vis = visualInfo.visual;
323     color_class = visualInfo.c_class;
324     D(bug(" found visual ID 0x%02x, depth %d, class ", visualInfo.visualid, xdepth));
325     #if DEBUG
326     switch (color_class) {
327     case StaticGray: D(bug("StaticGray\n")); break;
328     case GrayScale: D(bug("GrayScale\n")); break;
329     case StaticColor: D(bug("StaticColor\n")); break;
330     case PseudoColor: D(bug("PseudoColor\n")); break;
331     case TrueColor: D(bug("TrueColor\n")); break;
332     case DirectColor: D(bug("DirectColor\n")); break;
333     }
334     #endif
335     return true;
336     }
337    
338    
339     /*
340 cebix 1.1 * Open display (window or fullscreen)
341     */
342    
343 gbeauche 1.13 // Wait until window is mapped/unmapped
344     void wait_mapped(Window w)
345     {
346     XEvent e;
347     do {
348     XMaskEvent(x_display, StructureNotifyMask, &e);
349     } while ((e.type != MapNotify) || (e.xmap.event != w));
350     }
351    
352     void wait_unmapped(Window w)
353     {
354     XEvent e;
355     do {
356     XMaskEvent(x_display, StructureNotifyMask, &e);
357     } while ((e.type != UnmapNotify) || (e.xmap.event != w));
358     }
359    
360 cebix 1.1 // Trap SHM errors
361     static bool shm_error = false;
362     static int (*old_error_handler)(Display *, XErrorEvent *);
363    
364     static int error_handler(Display *d, XErrorEvent *e)
365     {
366     if (e->error_code == BadAccess) {
367     shm_error = true;
368     return 0;
369     } else
370     return old_error_handler(d, e);
371     }
372    
373     // Open window
374     static bool open_window(int width, int height)
375     {
376 gbeauche 1.3 int aligned_width = (width + 15) & ~15;
377     int aligned_height = (height + 15) & ~15;
378    
379 cebix 1.1 // Set absolute mouse mode
380     ADBSetRelMouseMode(false);
381    
382     // Create window
383     XSetWindowAttributes wattr;
384     wattr.event_mask = eventmask = win_eventmask;
385 gbeauche 1.13 wattr.background_pixel = (vis == DefaultVisual(x_display, screen) ? black_pixel : 0);
386     wattr.border_pixel = 0;
387 cebix 1.1 wattr.backing_store = NotUseful;
388 gbeauche 1.13 wattr.colormap = (depth == 1 ? DefaultColormap(x_display, screen) : cmap[0]);
389     the_win = XCreateWindow(x_display, rootwin, 0, 0, width, height, 0, xdepth,
390     InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel | CWBackingStore | CWColormap, &wattr);
391 cebix 1.1
392 gbeauche 1.13 // Set window name
393 cebix 1.1 XStoreName(x_display, the_win, GetString(STR_WINDOW_TITLE));
394    
395     // Make window unresizable
396     XSizeHints *hints;
397     if ((hints = XAllocSizeHints()) != NULL) {
398     hints->min_width = width;
399     hints->max_width = width;
400     hints->min_height = height;
401     hints->max_height = height;
402     hints->flags = PMinSize | PMaxSize;
403     XSetWMNormalHints(x_display, the_win, hints);
404     XFree((char *)hints);
405     }
406    
407 gbeauche 1.13 // Show window
408     XMapWindow(x_display, the_win);
409     wait_mapped(the_win);
410    
411 gbeauche 1.5 // 1-bit mode is big-endian; if the X server is little-endian, we can't
412     // use SHM because that doesn't allow changing the image byte order
413     bool need_msb_image = (depth == 1 && XImageByteOrder(x_display) == LSBFirst);
414    
415 cebix 1.1 // Try to create and attach SHM image
416     have_shm = false;
417 gbeauche 1.5 if (local_X11 && !need_msb_image && XShmQueryExtension(x_display)) {
418 cebix 1.1
419     // Create SHM image ("height + 2" for safety)
420 gbeauche 1.5 img = XShmCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, &shminfo, width, height);
421 gbeauche 1.13 shminfo.shmid = shmget(IPC_PRIVATE, (aligned_height + 2) * img->bytes_per_line, IPC_CREAT | 0777);
422     D(bug(" shm image created\n"));
423 gbeauche 1.3 the_buffer_copy = (uint8 *)shmat(shminfo.shmid, 0, 0);
424     shminfo.shmaddr = img->data = (char *)the_buffer_copy;
425 cebix 1.1 shminfo.readOnly = False;
426    
427     // Try to attach SHM image, catching errors
428     shm_error = false;
429     old_error_handler = XSetErrorHandler(error_handler);
430     XShmAttach(x_display, &shminfo);
431     XSync(x_display, false);
432     XSetErrorHandler(old_error_handler);
433     if (shm_error) {
434     shmdt(shminfo.shmaddr);
435     XDestroyImage(img);
436     shminfo.shmid = -1;
437     } else {
438     have_shm = true;
439     shmctl(shminfo.shmid, IPC_RMID, 0);
440     }
441 gbeauche 1.13 D(bug(" shm image attached\n"));
442 cebix 1.1 }
443    
444     // Create normal X image if SHM doesn't work ("height + 2" for safety)
445     if (!have_shm) {
446 gbeauche 1.13 int bytes_per_row = depth == 1 ? aligned_width/8 : TrivialBytesPerRow(aligned_width, DepthModeForPixelDepth(xdepth));
447 gbeauche 1.3 the_buffer_copy = (uint8 *)malloc((aligned_height + 2) * bytes_per_row);
448     img = XCreateImage(x_display, vis, depth == 1 ? 1 : xdepth, depth == 1 ? XYBitmap : ZPixmap, 0, (char *)the_buffer_copy, aligned_width, aligned_height, 32, bytes_per_row);
449 gbeauche 1.13 D(bug(" X image created\n"));
450 cebix 1.1 }
451    
452     // 1-Bit mode is big-endian
453 gbeauche 1.13 if (need_msb_image) {
454 cebix 1.1 img->byte_order = MSBFirst;
455     img->bitmap_bit_order = MSBFirst;
456     }
457    
458 gbeauche 1.3 #ifdef ENABLE_VOSF
459     use_vosf = true;
460     // Allocate memory for frame buffer (SIZE is extended to page-boundary)
461     the_host_buffer = the_buffer_copy;
462     the_buffer_size = page_extend((aligned_height + 2) * img->bytes_per_line);
463     the_buffer = (uint8 *)vm_acquire(the_buffer_size);
464     the_buffer_copy = (uint8 *)malloc(the_buffer_size);
465     D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
466     #else
467     // Allocate memory for frame buffer
468     the_buffer = (uint8 *)malloc((aligned_height + 2) * img->bytes_per_line);
469     D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
470     #endif
471     screen_base = (uint32)the_buffer;
472 cebix 1.1
473     // Create GC
474     the_gc = XCreateGC(x_display, the_win, 0, 0);
475 gbeauche 1.13 XSetState(x_display, the_gc, black_pixel, white_pixel, GXcopy, AllPlanes);
476 cebix 1.1
477     // Create cursor
478     cursor_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 4, 16, 16, 16, 2);
479     cursor_image->byte_order = MSBFirst;
480     cursor_image->bitmap_bit_order = MSBFirst;
481     cursor_mask_image = XCreateImage(x_display, vis, 1, XYPixmap, 0, (char *)MacCursor + 36, 16, 16, 16, 2);
482     cursor_mask_image->byte_order = MSBFirst;
483     cursor_mask_image->bitmap_bit_order = MSBFirst;
484     cursor_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
485     cursor_mask_map = XCreatePixmap(x_display, the_win, 16, 16, 1);
486     cursor_gc = XCreateGC(x_display, cursor_map, 0, 0);
487     cursor_mask_gc = XCreateGC(x_display, cursor_mask_map, 0, 0);
488     mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, 0, 0);
489     cursor_changed = false;
490    
491 gbeauche 1.3 // Init blitting routines
492     bool native_byte_order;
493     #ifdef WORDS_BIGENDIAN
494     native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
495     #else
496     native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
497     #endif
498     #ifdef ENABLE_VOSF
499     Screen_blitter_init(&visualInfo, native_byte_order, depth);
500     #endif
501    
502 cebix 1.1 // Set bytes per row
503     XSync(x_display, false);
504     return true;
505     }
506    
507     // Open DGA display (!! should use X11 VidMode extensions to set mode)
508     static bool open_dga(int width, int height)
509     {
510     #ifdef ENABLE_XF86_DGA
511     // Set relative mouse mode
512     ADBSetRelMouseMode(true);
513    
514     #ifdef ENABLE_XF86_VIDMODE
515     // Switch to best mode
516     if (has_vidmode) {
517     int best = 0;
518     for (int i=1; i<num_x_video_modes; i++) {
519     if (x_video_modes[i]->hdisplay >= width && x_video_modes[i]->vdisplay >= height &&
520     x_video_modes[i]->hdisplay <= x_video_modes[best]->hdisplay && x_video_modes[i]->vdisplay <= x_video_modes[best]->vdisplay) {
521     best = i;
522     }
523     }
524     XF86VidModeSwitchToMode(x_display, screen, x_video_modes[best]);
525     XF86VidModeSetViewPort(x_display, screen, 0, 0);
526     }
527     #endif
528    
529     // Establish direct screen connection
530     XGrabKeyboard(x_display, rootwin, True, GrabModeAsync, GrabModeAsync, CurrentTime);
531     XGrabPointer(x_display, rootwin, True, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
532     XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
533     XF86DGASetViewPort(x_display, screen, 0, 0);
534     XF86DGASetVidPage(x_display, screen, 0);
535    
536     // Set colormap
537     if (depth == 8)
538     XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
539    
540     // Set bytes per row
541 gbeauche 1.13 int bytes_per_row = TrivialBytesPerRow((dga_fb_width + 7) & ~7, DepthModeForPixelDepth(depth));
542 gbeauche 1.3
543     #if ENABLE_VOSF
544     bool native_byte_order;
545     #ifdef WORDS_BIGENDIAN
546     native_byte_order = (XImageByteOrder(x_display) == MSBFirst);
547     #else
548     native_byte_order = (XImageByteOrder(x_display) == LSBFirst);
549     #endif
550     #if REAL_ADDRESSING || DIRECT_ADDRESSING
551     // Screen_blitter_init() returns TRUE if VOSF is mandatory
552     // i.e. the framebuffer update function is not Blit_Copy_Raw
553     use_vosf = Screen_blitter_init(&visualInfo, native_byte_order, depth);
554    
555     if (use_vosf) {
556     // Allocate memory for frame buffer (SIZE is extended to page-boundary)
557     the_host_buffer = the_buffer;
558     the_buffer_size = page_extend((height + 2) * bytes_per_row);
559     the_buffer_copy = (uint8 *)malloc(the_buffer_size);
560     the_buffer = (uint8 *)vm_acquire(the_buffer_size);
561     }
562     #else
563     use_vosf = false;
564     the_buffer = dga_screen_base;
565     #endif
566     #endif
567     screen_base = (uint32)the_buffer;
568    
569 cebix 1.1 VModes[cur_mode].viRowBytes = bytes_per_row;
570     XSync(x_display, false);
571     return true;
572     #else
573     ErrorAlert("SheepShaver has been compiled with DGA support disabled.");
574     return false;
575     #endif
576     }
577    
578     static bool open_display(void)
579     {
580 gbeauche 1.13 D(bug("open_display()\n"));
581     const VideoInfo &mode = VModes[cur_mode];
582    
583     // Find best available X visual
584     if (!find_visual_for_depth(mode.viAppleMode)) {
585     ErrorAlert(GetString(STR_NO_XVISUAL_ERR));
586     return false;
587     }
588    
589     // Create color maps
590     if (color_class == PseudoColor || color_class == DirectColor) {
591     cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocAll);
592     cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocAll);
593     } else {
594     cmap[0] = XCreateColormap(x_display, rootwin, vis, AllocNone);
595     cmap[1] = XCreateColormap(x_display, rootwin, vis, AllocNone);
596     }
597    
598     // Find pixel format of direct modes
599     if (color_class == DirectColor || color_class == TrueColor) {
600     rshift = gshift = bshift = 0;
601     rloss = gloss = bloss = 8;
602     uint32 mask;
603     for (mask=vis->red_mask; !(mask&1); mask>>=1)
604     ++rshift;
605     for (; mask&1; mask>>=1)
606     --rloss;
607     for (mask=vis->green_mask; !(mask&1); mask>>=1)
608     ++gshift;
609     for (; mask&1; mask>>=1)
610     --gloss;
611     for (mask=vis->blue_mask; !(mask&1); mask>>=1)
612     ++bshift;
613     for (; mask&1; mask>>=1)
614     --bloss;
615     }
616    
617     // Preset palette pixel values for CLUT or gamma table
618     if (color_class == DirectColor) {
619     int num = vis->map_entries;
620     for (int i=0; i<num; i++) {
621     int c = (i * 256) / num;
622     x_palette[i].pixel = map_rgb(c, c, c);
623     x_palette[i].flags = DoRed | DoGreen | DoBlue;
624     }
625     } else if (color_class == PseudoColor) {
626     for (int i=0; i<256; i++) {
627     x_palette[i].pixel = i;
628     x_palette[i].flags = DoRed | DoGreen | DoBlue;
629     }
630     }
631    
632     // Load gray ramp to color map
633     int num = (color_class == DirectColor ? vis->map_entries : 256);
634     for (int i=0; i<num; i++) {
635     int c = (i * 256) / num;
636     x_palette[i].red = c * 0x0101;
637     x_palette[i].green = c * 0x0101;
638     x_palette[i].blue = c * 0x0101;
639     }
640     if (color_class == PseudoColor || color_class == DirectColor) {
641     XStoreColors(x_display, cmap[0], x_palette, num);
642     XStoreColors(x_display, cmap[1], x_palette, num);
643 cebix 1.1 }
644 gbeauche 1.3
645 gbeauche 1.13 #ifdef ENABLE_VOSF
646     // Load gray ramp to 8->16/32 expand map
647     if (!IsDirectMode(get_current_mode()) && xdepth > 8)
648     for (int i=0; i<256; i++)
649     ExpandMap[i] = map_rgb(i, i, i);
650     #endif
651    
652     // Create display of requested type
653     display_type = mode.viType;
654     depth = depth_of_video_mode(mode.viAppleMode);
655    
656 gbeauche 1.3 bool display_open = false;
657 cebix 1.1 if (display_type == DIS_SCREEN)
658 gbeauche 1.3 display_open = open_dga(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
659 cebix 1.1 else if (display_type == DIS_WINDOW)
660 gbeauche 1.3 display_open = open_window(VModes[cur_mode].viXsize, VModes[cur_mode].viYsize);
661    
662     #ifdef ENABLE_VOSF
663     if (use_vosf) {
664     // Initialize the VOSF system
665     if (!video_vosf_init()) {
666     ErrorAlert(GetString(STR_VOSF_INIT_ERR));
667     return false;
668     }
669     }
670     #endif
671    
672     return display_open;
673 cebix 1.1 }
674    
675    
676     /*
677     * Close display
678     */
679    
680     // Close window
681     static void close_window(void)
682     {
683 gbeauche 1.3 if (have_shm) {
684     XShmDetach(x_display, &shminfo);
685     #ifdef ENABLE_VOSF
686     the_host_buffer = NULL; // don't free() in driver_base dtor
687     #else
688     the_buffer_copy = NULL; // don't free() in driver_base dtor
689     #endif
690     }
691     if (img) {
692     if (!have_shm)
693     img->data = NULL;
694     XDestroyImage(img);
695     }
696     if (have_shm) {
697     shmdt(shminfo.shmaddr);
698     shmctl(shminfo.shmid, IPC_RMID, 0);
699     }
700     if (the_gc)
701     XFreeGC(x_display, the_gc);
702    
703 cebix 1.1 // Close window
704 gbeauche 1.13 if (the_win) {
705     XUnmapWindow(x_display, the_win);
706     wait_unmapped(the_win);
707     XDestroyWindow(x_display, the_win);
708     }
709    
710     XFlush(x_display);
711     XSync(x_display, false);
712 cebix 1.1 }
713    
714     // Close DGA mode
715     static void close_dga(void)
716     {
717     #ifdef ENABLE_XF86_DGA
718     XF86DGADirectVideo(x_display, screen, 0);
719     XUngrabPointer(x_display, CurrentTime);
720     XUngrabKeyboard(x_display, CurrentTime);
721     #endif
722    
723     #ifdef ENABLE_XF86_VIDMODE
724     if (has_vidmode)
725     XF86VidModeSwitchToMode(x_display, screen, x_video_modes[0]);
726     #endif
727 gbeauche 1.3
728     if (!use_vosf) {
729     // don't free() the screen buffer in driver_base dtor
730     the_buffer = NULL;
731     }
732     #ifdef ENABLE_VOSF
733     else {
734     // don't free() the screen buffer in driver_base dtor
735     the_host_buffer = NULL;
736     }
737     #endif
738 cebix 1.1 }
739    
740     static void close_display(void)
741     {
742     if (display_type == DIS_SCREEN)
743     close_dga();
744     else if (display_type == DIS_WINDOW)
745     close_window();
746 gbeauche 1.3
747 gbeauche 1.13 // Free colormaps
748     if (cmap[0]) {
749     XFreeColormap(x_display, cmap[0]);
750     cmap[0] = 0;
751     }
752     if (cmap[1]) {
753     XFreeColormap(x_display, cmap[1]);
754     cmap[1] = 0;
755     }
756    
757 gbeauche 1.3 #ifdef ENABLE_VOSF
758     if (use_vosf) {
759     // Deinitialize VOSF
760     video_vosf_exit();
761     }
762     #endif
763    
764     // Free frame buffer(s)
765     if (!use_vosf) {
766     if (the_buffer_copy) {
767     free(the_buffer_copy);
768     the_buffer_copy = NULL;
769     }
770     }
771     #ifdef ENABLE_VOSF
772     else {
773     // the_buffer shall always be mapped through vm_acquire() so that we can vm_protect() it at will
774     if (the_buffer != VM_MAP_FAILED) {
775     D(bug(" releasing the_buffer at %p (%d bytes)\n", the_buffer, the_buffer_size));
776     vm_release(the_buffer, the_buffer_size);
777     the_buffer = NULL;
778     }
779     if (the_host_buffer) {
780     D(bug(" freeing the_host_buffer at %p\n", the_host_buffer));
781     free(the_host_buffer);
782     the_host_buffer = NULL;
783     }
784     if (the_buffer_copy) {
785     D(bug(" freeing the_buffer_copy at %p\n", the_buffer_copy));
786     free(the_buffer_copy);
787     the_buffer_copy = NULL;
788     }
789     }
790     #endif
791 cebix 1.1 }
792    
793    
794     /*
795     * Initialization
796     */
797    
798 gbeauche 1.6 // Init keycode translation table
799     static void keycode_init(void)
800     {
801     bool use_kc = PrefsFindBool("keycodes");
802     if (use_kc) {
803    
804     // Get keycode file path from preferences
805     const char *kc_path = PrefsFindString("keycodefile");
806    
807     // Open keycode table
808     FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r");
809     if (f == NULL) {
810     char str[256];
811     sprintf(str, GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno));
812     WarningAlert(str);
813     return;
814     }
815    
816     // Default translation table
817     for (int i=0; i<256; i++)
818     keycode_table[i] = -1;
819    
820     // Search for server vendor string, then read keycodes
821     const char *vendor = ServerVendor(x_display);
822     bool vendor_found = false;
823     char line[256];
824     while (fgets(line, 255, f)) {
825     // Read line
826     int len = strlen(line);
827     if (len == 0)
828     continue;
829     line[len-1] = 0;
830    
831     // Comments begin with "#" or ";"
832     if (line[0] == '#' || line[0] == ';' || line[0] == 0)
833     continue;
834    
835     if (vendor_found) {
836     // Read keycode
837     int x_code, mac_code;
838     if (sscanf(line, "%d %d", &x_code, &mac_code) == 2)
839     keycode_table[x_code & 0xff] = mac_code;
840     else
841     break;
842     } else {
843     // Search for vendor string
844     if (strstr(vendor, line) == vendor)
845     vendor_found = true;
846     }
847     }
848    
849     // Keycode file completely read
850     fclose(f);
851     use_keycodes = vendor_found;
852    
853     // Vendor not found? Then display warning
854     if (!vendor_found) {
855     char str[256];
856     sprintf(str, GetString(STR_KEYCODE_VENDOR_WARN), vendor, kc_path ? kc_path : KEYCODE_FILE_NAME);
857     WarningAlert(str);
858     return;
859     }
860     }
861     }
862    
863 gbeauche 1.13 // Add mode to list of supported modes
864     static void add_mode(VideoInfo *&p, uint32 allow, uint32 test, int apple_mode, int apple_id, int type)
865 cebix 1.1 {
866     if (allow & test) {
867     p->viType = type;
868     switch (apple_id) {
869     case APPLE_W_640x480:
870     case APPLE_640x480:
871     p->viXsize = 640;
872     p->viYsize = 480;
873     break;
874     case APPLE_W_800x600:
875     case APPLE_800x600:
876     p->viXsize = 800;
877     p->viYsize = 600;
878     break;
879     case APPLE_1024x768:
880     p->viXsize = 1024;
881     p->viYsize = 768;
882     break;
883     case APPLE_1152x900:
884     p->viXsize = 1152;
885     p->viYsize = 900;
886     break;
887     case APPLE_1280x1024:
888     p->viXsize = 1280;
889     p->viYsize = 1024;
890     break;
891     case APPLE_1600x1200:
892     p->viXsize = 1600;
893     p->viYsize = 1200;
894     break;
895     }
896 gbeauche 1.13 p->viRowBytes = TrivialBytesPerRow(p->viXsize, apple_mode);
897 cebix 1.1 p->viAppleMode = apple_mode;
898     p->viAppleID = apple_id;
899     p++;
900     }
901     }
902    
903 gbeauche 1.13 // Add standard list of windowed modes for given color depth
904     static void add_window_modes(VideoInfo *&p, int window_modes, int mode)
905     {
906     add_mode(p, window_modes, 1, mode, APPLE_W_640x480, DIS_WINDOW);
907     add_mode(p, window_modes, 2, mode, APPLE_W_800x600, DIS_WINDOW);
908     }
909    
910 cebix 1.1 static bool has_mode(int x, int y)
911     {
912     #ifdef ENABLE_XF86_VIDMODE
913     for (int i=0; i<num_x_video_modes; i++)
914     if (x_video_modes[i]->hdisplay >= x && x_video_modes[i]->vdisplay >= y)
915     return true;
916     return false;
917     #else
918     return DisplayWidth(x_display, screen) >= x && DisplayHeight(x_display, screen) >= y;
919     #endif
920     }
921    
922     bool VideoInit(void)
923     {
924 gbeauche 1.3 #ifdef ENABLE_VOSF
925     // Zero the mainBuffer structure
926     mainBuffer.dirtyPages = NULL;
927     mainBuffer.pageInfo = NULL;
928     #endif
929    
930 gbeauche 1.4 // Check if X server runs on local machine
931     local_X11 = (strncmp(XDisplayName(x_display_name), ":", 1) == 0)
932     || (strncmp(XDisplayName(x_display_name), "unix:", 5) == 0);
933    
934 gbeauche 1.6 // Init keycode translation
935     keycode_init();
936    
937 gbeauche 1.8 // Read frame skip prefs
938     frame_skip = PrefsFindInt32("frameskip");
939     if (frame_skip == 0)
940     frame_skip = 1;
941    
942     // Read mouse wheel prefs
943     mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
944     mouse_wheel_lines = PrefsFindInt32("mousewheellines");
945    
946 cebix 1.1 // Init variables
947     private_data = NULL;
948     video_activated = true;
949    
950     // Find screen and root window
951     screen = XDefaultScreen(x_display);
952     rootwin = XRootWindow(x_display, screen);
953    
954 gbeauche 1.13 // Get sorted list of available depths
955     avail_depths = XListDepths(x_display, screen, &num_depths);
956     if (avail_depths == NULL) {
957     ErrorAlert(GetString(STR_UNSUPP_DEPTH_ERR));
958     return false;
959     }
960     sort(avail_depths, avail_depths + num_depths);
961    
962 cebix 1.1 // Get screen depth
963     xdepth = DefaultDepth(x_display, screen);
964    
965     #ifdef ENABLE_XF86_DGA
966     // DGA available?
967     int event_base, error_base;
968 gbeauche 1.4 if (local_X11 && XF86DGAQueryExtension(x_display, &event_base, &error_base)) {
969 cebix 1.1 int dga_flags = 0;
970     XF86DGAQueryDirectVideo(x_display, screen, &dga_flags);
971     has_dga = dga_flags & XF86DGADirectPresent;
972     } else
973     has_dga = false;
974     #endif
975    
976     #ifdef ENABLE_XF86_VIDMODE
977     // VidMode available?
978     int vm_event_base, vm_error_base;
979     has_vidmode = XF86VidModeQueryExtension(x_display, &vm_event_base, &vm_error_base);
980     if (has_vidmode)
981     XF86VidModeGetAllModeLines(x_display, screen, &num_x_video_modes, &x_video_modes);
982     #endif
983    
984     // Find black and white colors
985     XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:00/00/00", &black);
986     XAllocColor(x_display, DefaultColormap(x_display, screen), &black);
987     XParseColor(x_display, DefaultColormap(x_display, screen), "rgb:ff/ff/ff", &white);
988     XAllocColor(x_display, DefaultColormap(x_display, screen), &white);
989     black_pixel = BlackPixel(x_display, screen);
990     white_pixel = WhitePixel(x_display, screen);
991    
992     // Mac screen depth follows X depth (for now)
993 gbeauche 1.13 int default_mode = APPLE_8_BIT;
994     switch (DefaultDepth(x_display, screen)) {
995     case 1:
996     default_mode = APPLE_1_BIT;
997     break;
998     case 8:
999     default_mode = APPLE_8_BIT;
1000     break;
1001     case 15: case 16:
1002     default_mode = APPLE_16_BIT;
1003     break;
1004     case 24: case 32:
1005     default_mode = APPLE_32_BIT;
1006     break;
1007 cebix 1.1 }
1008    
1009     // Construct video mode table
1010     uint32 window_modes = PrefsFindInt32("windowmodes");
1011     uint32 screen_modes = PrefsFindInt32("screenmodes");
1012     if (!has_dga)
1013     screen_modes = 0;
1014     if (window_modes == 0 && screen_modes == 0)
1015     window_modes |= 3; // Allow at least 640x480 and 800x600 window modes
1016    
1017     VideoInfo *p = VModes;
1018 gbeauche 1.13 for (unsigned int d = APPLE_1_BIT; d <= APPLE_32_BIT; d++)
1019     if (find_visual_for_depth(d))
1020     add_window_modes(p, window_modes, d);
1021    
1022 cebix 1.1 if (has_vidmode) {
1023     if (has_mode(640, 480))
1024 gbeauche 1.13 add_mode(p, screen_modes, 1, default_mode, APPLE_640x480, DIS_SCREEN);
1025 cebix 1.1 if (has_mode(800, 600))
1026 gbeauche 1.13 add_mode(p, screen_modes, 2, default_mode, APPLE_800x600, DIS_SCREEN);
1027 cebix 1.1 if (has_mode(1024, 768))
1028 gbeauche 1.13 add_mode(p, screen_modes, 4, default_mode, APPLE_1024x768, DIS_SCREEN);
1029 cebix 1.1 if (has_mode(1152, 900))
1030 gbeauche 1.13 add_mode(p, screen_modes, 8, default_mode, APPLE_1152x900, DIS_SCREEN);
1031 cebix 1.1 if (has_mode(1280, 1024))
1032 gbeauche 1.13 add_mode(p, screen_modes, 16, default_mode, APPLE_1280x1024, DIS_SCREEN);
1033 cebix 1.1 if (has_mode(1600, 1200))
1034 gbeauche 1.13 add_mode(p, screen_modes, 32, default_mode, APPLE_1600x1200, DIS_SCREEN);
1035 cebix 1.1 } else if (screen_modes) {
1036     int xsize = DisplayWidth(x_display, screen);
1037     int ysize = DisplayHeight(x_display, screen);
1038     int apple_id;
1039     if (xsize < 800)
1040     apple_id = APPLE_640x480;
1041     else if (xsize < 1024)
1042     apple_id = APPLE_800x600;
1043     else if (xsize < 1152)
1044     apple_id = APPLE_1024x768;
1045     else if (xsize < 1280)
1046     apple_id = APPLE_1152x900;
1047     else if (xsize < 1600)
1048     apple_id = APPLE_1280x1024;
1049     else
1050     apple_id = APPLE_1600x1200;
1051     p->viType = DIS_SCREEN;
1052     p->viRowBytes = 0;
1053     p->viXsize = xsize;
1054     p->viYsize = ysize;
1055 gbeauche 1.13 p->viAppleMode = default_mode;
1056 cebix 1.1 p->viAppleID = apple_id;
1057     p++;
1058     }
1059     p->viType = DIS_INVALID; // End marker
1060     p->viRowBytes = 0;
1061     p->viXsize = p->viYsize = 0;
1062     p->viAppleMode = 0;
1063     p->viAppleID = 0;
1064    
1065 gbeauche 1.13 // Find default mode (window 640x480)
1066     cur_mode = -1;
1067     for (p = VModes; p->viType != DIS_INVALID; p++) {
1068     if (p->viType == DIS_WINDOW
1069     && p->viAppleID == APPLE_W_640x480
1070     && p->viAppleMode == default_mode) {
1071     cur_mode = p - VModes;
1072     break;
1073     }
1074     }
1075     assert(cur_mode != -1);
1076    
1077     #if DEBUG
1078     D(bug("Available video modes:\n"));
1079     for (p = VModes; p->viType != DIS_INVALID; p++) {
1080     int bits = depth_of_video_mode(p->viAppleMode);
1081     D(bug(" %dx%d (ID %02x), %d colors\n", p->viXsize, p->viYsize, p->viAppleID, 1 << bits));
1082     }
1083     #endif
1084    
1085 cebix 1.1 #ifdef ENABLE_XF86_DGA
1086     if (has_dga && screen_modes) {
1087     int v_bank, v_size;
1088     XF86DGAGetVideo(x_display, screen, &dga_screen_base, &dga_fb_width, &v_bank, &v_size);
1089     D(bug("DGA screen_base %p, v_width %d\n", dga_screen_base, dga_fb_width));
1090     }
1091     #endif
1092    
1093     // Open window/screen
1094     if (!open_display())
1095     return false;
1096    
1097     #if 0
1098     // Ignore errors from now on
1099     XSetErrorHandler(ignore_errors);
1100     #endif
1101    
1102     // Start periodic thread
1103     XSync(x_display, false);
1104     redraw_thread_active = (pthread_create(&redraw_thread, NULL, redraw_func, NULL) == 0);
1105     D(bug("Redraw thread installed (%ld)\n", redraw_thread));
1106     return true;
1107     }
1108    
1109    
1110     /*
1111     * Deinitialization
1112     */
1113    
1114     void VideoExit(void)
1115     {
1116     // Stop redraw thread
1117     if (redraw_thread_active) {
1118     pthread_cancel(redraw_thread);
1119     pthread_join(redraw_thread, NULL);
1120     redraw_thread_active = false;
1121     }
1122    
1123 gbeauche 1.3 #ifdef ENABLE_VOSF
1124     if (use_vosf) {
1125     // Deinitialize VOSF
1126     video_vosf_exit();
1127     }
1128     #endif
1129    
1130 cebix 1.1 // Close window and server connection
1131     if (x_display != NULL) {
1132     XSync(x_display, false);
1133     close_display();
1134     XFlush(x_display);
1135     XSync(x_display, false);
1136     }
1137     }
1138    
1139    
1140     /*
1141     * Suspend/resume emulator
1142     */
1143    
1144     extern void PauseEmulator(void);
1145     extern void ResumeEmulator(void);
1146    
1147     static void suspend_emul(void)
1148     {
1149     if (display_type == DIS_SCREEN) {
1150     // Release ctrl key
1151     ADBKeyUp(0x36);
1152     ctrl_down = false;
1153    
1154     // Pause MacOS thread
1155     PauseEmulator();
1156     emul_suspended = true;
1157    
1158     // Save frame buffer
1159     fb_save = malloc(VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1160     if (fb_save)
1161     memcpy(fb_save, (void *)screen_base, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1162    
1163     // Close full screen display
1164     #ifdef ENABLE_XF86_DGA
1165     XF86DGADirectVideo(x_display, screen, 0);
1166     XUngrabPointer(x_display, CurrentTime);
1167     XUngrabKeyboard(x_display, CurrentTime);
1168     #endif
1169     XSync(x_display, false);
1170    
1171     // Open "suspend" window
1172     XSetWindowAttributes wattr;
1173     wattr.event_mask = KeyPressMask;
1174     wattr.background_pixel = black_pixel;
1175     wattr.border_pixel = black_pixel;
1176     wattr.backing_store = Always;
1177     wattr.backing_planes = xdepth;
1178     wattr.colormap = DefaultColormap(x_display, screen);
1179     XSync(x_display, false);
1180     suspend_win = XCreateWindow(x_display, rootwin, 0, 0, 512, 1, 0, xdepth,
1181     InputOutput, vis, CWEventMask | CWBackPixel | CWBorderPixel |
1182     CWBackingStore | CWBackingPlanes | (xdepth == 8 ? CWColormap : 0), &wattr);
1183     XSync(x_display, false);
1184     XStoreName(x_display, suspend_win, GetString(STR_SUSPEND_WINDOW_TITLE));
1185     XMapRaised(x_display, suspend_win);
1186     XSync(x_display, false);
1187     }
1188     }
1189    
1190     static void resume_emul(void)
1191     {
1192     // Close "suspend" window
1193     XDestroyWindow(x_display, suspend_win);
1194     XSync(x_display, false);
1195    
1196     // Reopen full screen display
1197     XGrabKeyboard(x_display, rootwin, 1, GrabModeAsync, GrabModeAsync, CurrentTime);
1198     XGrabPointer(x_display, rootwin, 1, PointerMotionMask | ButtonPressMask | ButtonReleaseMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
1199 gbeauche 1.12 #ifdef ENABLE_XF86_DGA
1200 cebix 1.1 XF86DGADirectVideo(x_display, screen, XF86DGADirectGraphics | XF86DGADirectKeyb | XF86DGADirectMouse);
1201     XF86DGASetViewPort(x_display, screen, 0, 0);
1202 gbeauche 1.12 #endif
1203 cebix 1.1 XSync(x_display, false);
1204    
1205 gbeauche 1.3 // the_buffer already contains the data to restore. i.e. since a temporary
1206     // frame buffer is used when VOSF is actually used, fb_save is therefore
1207     // not necessary.
1208     #ifdef ENABLE_VOSF
1209     if (use_vosf) {
1210     LOCK_VOSF;
1211     PFLAG_SET_ALL;
1212     UNLOCK_VOSF;
1213     memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1214     }
1215     #endif
1216    
1217 cebix 1.1 // Restore frame buffer
1218     if (fb_save) {
1219 gbeauche 1.3 #ifdef ENABLE_VOSF
1220     // Don't copy fb_save to the temporary frame buffer in VOSF mode
1221     if (!use_vosf)
1222     #endif
1223 cebix 1.1 memcpy((void *)screen_base, fb_save, VModes[cur_mode].viYsize * VModes[cur_mode].viRowBytes);
1224     free(fb_save);
1225     fb_save = NULL;
1226     }
1227     if (depth == 8)
1228     palette_changed = true;
1229    
1230     // Resume MacOS thread
1231     emul_suspended = false;
1232     ResumeEmulator();
1233     }
1234    
1235    
1236     /*
1237     * Close screen in full-screen mode
1238     */
1239    
1240     void VideoQuitFullScreen(void)
1241     {
1242     D(bug("VideoQuitFullScreen()\n"));
1243     if (display_type == DIS_SCREEN) {
1244     quit_full_screen = true;
1245     while (!quit_full_screen_ack) ;
1246     }
1247     }
1248    
1249    
1250     /*
1251     * X11 event handling
1252     */
1253    
1254     // Translate key event to Mac keycode
1255     static int kc_decode(KeySym ks)
1256     {
1257     switch (ks) {
1258     case XK_A: case XK_a: return 0x00;
1259     case XK_B: case XK_b: return 0x0b;
1260     case XK_C: case XK_c: return 0x08;
1261     case XK_D: case XK_d: return 0x02;
1262     case XK_E: case XK_e: return 0x0e;
1263     case XK_F: case XK_f: return 0x03;
1264     case XK_G: case XK_g: return 0x05;
1265     case XK_H: case XK_h: return 0x04;
1266     case XK_I: case XK_i: return 0x22;
1267     case XK_J: case XK_j: return 0x26;
1268     case XK_K: case XK_k: return 0x28;
1269     case XK_L: case XK_l: return 0x25;
1270     case XK_M: case XK_m: return 0x2e;
1271     case XK_N: case XK_n: return 0x2d;
1272     case XK_O: case XK_o: return 0x1f;
1273     case XK_P: case XK_p: return 0x23;
1274     case XK_Q: case XK_q: return 0x0c;
1275     case XK_R: case XK_r: return 0x0f;
1276     case XK_S: case XK_s: return 0x01;
1277     case XK_T: case XK_t: return 0x11;
1278     case XK_U: case XK_u: return 0x20;
1279     case XK_V: case XK_v: return 0x09;
1280     case XK_W: case XK_w: return 0x0d;
1281     case XK_X: case XK_x: return 0x07;
1282     case XK_Y: case XK_y: return 0x10;
1283     case XK_Z: case XK_z: return 0x06;
1284    
1285     case XK_1: case XK_exclam: return 0x12;
1286     case XK_2: case XK_at: return 0x13;
1287     case XK_3: case XK_numbersign: return 0x14;
1288     case XK_4: case XK_dollar: return 0x15;
1289     case XK_5: case XK_percent: return 0x17;
1290     case XK_6: return 0x16;
1291     case XK_7: return 0x1a;
1292     case XK_8: return 0x1c;
1293     case XK_9: return 0x19;
1294     case XK_0: return 0x1d;
1295    
1296     case XK_grave: case XK_asciitilde: return 0x0a;
1297     case XK_minus: case XK_underscore: return 0x1b;
1298     case XK_equal: case XK_plus: return 0x18;
1299     case XK_bracketleft: case XK_braceleft: return 0x21;
1300     case XK_bracketright: case XK_braceright: return 0x1e;
1301     case XK_backslash: case XK_bar: return 0x2a;
1302     case XK_semicolon: case XK_colon: return 0x29;
1303     case XK_apostrophe: case XK_quotedbl: return 0x27;
1304     case XK_comma: case XK_less: return 0x2b;
1305     case XK_period: case XK_greater: return 0x2f;
1306     case XK_slash: case XK_question: return 0x2c;
1307    
1308     case XK_Tab: if (ctrl_down) {suspend_emul(); return -1;} else return 0x30;
1309     case XK_Return: return 0x24;
1310     case XK_space: return 0x31;
1311     case XK_BackSpace: return 0x33;
1312    
1313     case XK_Delete: return 0x75;
1314     case XK_Insert: return 0x72;
1315     case XK_Home: case XK_Help: return 0x73;
1316     case XK_End: return 0x77;
1317     #ifdef __hpux
1318     case XK_Prior: return 0x74;
1319     case XK_Next: return 0x79;
1320     #else
1321     case XK_Page_Up: return 0x74;
1322     case XK_Page_Down: return 0x79;
1323     #endif
1324    
1325     case XK_Control_L: return 0x36;
1326     case XK_Control_R: return 0x36;
1327     case XK_Shift_L: return 0x38;
1328     case XK_Shift_R: return 0x38;
1329     case XK_Alt_L: return 0x37;
1330     case XK_Alt_R: return 0x37;
1331     case XK_Meta_L: return 0x3a;
1332     case XK_Meta_R: return 0x3a;
1333     case XK_Menu: return 0x32;
1334     case XK_Caps_Lock: return 0x39;
1335     case XK_Num_Lock: return 0x47;
1336    
1337     case XK_Up: return 0x3e;
1338     case XK_Down: return 0x3d;
1339     case XK_Left: return 0x3b;
1340     case XK_Right: return 0x3c;
1341    
1342     case XK_Escape: if (ctrl_down) {quit_full_screen = true; emerg_quit = true; return -1;} else return 0x35;
1343    
1344     case XK_F1: if (ctrl_down) {SysMountFirstFloppy(); return -1;} else return 0x7a;
1345     case XK_F2: return 0x78;
1346     case XK_F3: return 0x63;
1347     case XK_F4: return 0x76;
1348     case XK_F5: return 0x60;
1349     case XK_F6: return 0x61;
1350     case XK_F7: return 0x62;
1351     case XK_F8: return 0x64;
1352     case XK_F9: return 0x65;
1353     case XK_F10: return 0x6d;
1354     case XK_F11: return 0x67;
1355     case XK_F12: return 0x6f;
1356    
1357     case XK_Print: return 0x69;
1358     case XK_Scroll_Lock: return 0x6b;
1359     case XK_Pause: return 0x71;
1360    
1361     #if defined(XK_KP_Prior) && defined(XK_KP_Left) && defined(XK_KP_Insert) && defined (XK_KP_End)
1362     case XK_KP_0: case XK_KP_Insert: return 0x52;
1363     case XK_KP_1: case XK_KP_End: return 0x53;
1364     case XK_KP_2: case XK_KP_Down: return 0x54;
1365     case XK_KP_3: case XK_KP_Next: return 0x55;
1366     case XK_KP_4: case XK_KP_Left: return 0x56;
1367     case XK_KP_5: case XK_KP_Begin: return 0x57;
1368     case XK_KP_6: case XK_KP_Right: return 0x58;
1369     case XK_KP_7: case XK_KP_Home: return 0x59;
1370     case XK_KP_8: case XK_KP_Up: return 0x5b;
1371     case XK_KP_9: case XK_KP_Prior: return 0x5c;
1372     case XK_KP_Decimal: case XK_KP_Delete: return 0x41;
1373     #else
1374     case XK_KP_0: return 0x52;
1375     case XK_KP_1: return 0x53;
1376     case XK_KP_2: return 0x54;
1377     case XK_KP_3: return 0x55;
1378     case XK_KP_4: return 0x56;
1379     case XK_KP_5: return 0x57;
1380     case XK_KP_6: return 0x58;
1381     case XK_KP_7: return 0x59;
1382     case XK_KP_8: return 0x5b;
1383     case XK_KP_9: return 0x5c;
1384     case XK_KP_Decimal: return 0x41;
1385     #endif
1386     case XK_KP_Add: return 0x45;
1387     case XK_KP_Subtract: return 0x4e;
1388     case XK_KP_Multiply: return 0x43;
1389     case XK_KP_Divide: return 0x4b;
1390     case XK_KP_Enter: return 0x4c;
1391     case XK_KP_Equal: return 0x51;
1392     }
1393     return -1;
1394     }
1395    
1396 gbeauche 1.6 static int event2keycode(XKeyEvent &ev)
1397 cebix 1.1 {
1398     KeySym ks;
1399     int as;
1400     int i = 0;
1401    
1402     do {
1403 gbeauche 1.6 ks = XLookupKeysym(&ev, i++);
1404 cebix 1.1 as = kc_decode(ks);
1405     if (as != -1)
1406     return as;
1407     } while (ks != NoSymbol);
1408    
1409     return -1;
1410     }
1411    
1412     static void handle_events(void)
1413     {
1414     // Handle events
1415     for (;;) {
1416     XEvent event;
1417    
1418 gbeauche 1.10 XDisplayLock();
1419 gbeauche 1.9 if (!XCheckMaskEvent(x_display, eventmask, &event)) {
1420     // Handle clipboard events
1421     if (XCheckTypedEvent(x_display, SelectionRequest, &event))
1422     ClipboardSelectionRequest(&event.xselectionrequest);
1423     else if (XCheckTypedEvent(x_display, SelectionClear, &event))
1424     ClipboardSelectionClear(&event.xselectionclear);
1425 gbeauche 1.10
1426     XDisplayUnlock();
1427 cebix 1.1 break;
1428 gbeauche 1.9 }
1429 gbeauche 1.10 XDisplayUnlock();
1430 cebix 1.1
1431     switch (event.type) {
1432     // Mouse button
1433     case ButtonPress: {
1434     unsigned int button = ((XButtonEvent *)&event)->button;
1435     if (button < 4)
1436     ADBMouseDown(button - 1);
1437 gbeauche 1.8 else if (button < 6) { // Wheel mouse
1438     if (mouse_wheel_mode == 0) {
1439     int key = (button == 5) ? 0x79 : 0x74; // Page up/down
1440     ADBKeyDown(key);
1441     ADBKeyUp(key);
1442     } else {
1443     int key = (button == 5) ? 0x3d : 0x3e; // Cursor up/down
1444     for(int i=0; i<mouse_wheel_lines; i++) {
1445     ADBKeyDown(key);
1446     ADBKeyUp(key);
1447     }
1448     }
1449     }
1450 cebix 1.1 break;
1451     }
1452     case ButtonRelease: {
1453     unsigned int button = ((XButtonEvent *)&event)->button;
1454     if (button < 4)
1455     ADBMouseUp(button - 1);
1456     break;
1457     }
1458    
1459     // Mouse moved
1460     case EnterNotify:
1461     ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1462     break;
1463     case MotionNotify:
1464     ADBMouseMoved(((XMotionEvent *)&event)->x, ((XMotionEvent *)&event)->y);
1465     break;
1466    
1467     // Keyboard
1468     case KeyPress: {
1469 gbeauche 1.6 int code = event2keycode(event.xkey);
1470     if (use_keycodes && code != -1)
1471     code = keycode_table[event.xkey.keycode & 0xff];
1472     if (code != -1) {
1473 cebix 1.1 if (!emul_suspended) {
1474     ADBKeyDown(code);
1475     if (code == 0x36)
1476     ctrl_down = true;
1477     } else {
1478     if (code == 0x31)
1479     resume_emul(); // Space wakes us up
1480     }
1481     }
1482     break;
1483     }
1484     case KeyRelease: {
1485 gbeauche 1.6 int code = event2keycode(event.xkey);
1486     if (use_keycodes && code != 1)
1487     code = keycode_table[event.xkey.keycode & 0xff];
1488     if (code != -1) {
1489 cebix 1.1 ADBKeyUp(code);
1490     if (code == 0x36)
1491     ctrl_down = false;
1492     }
1493     break;
1494     }
1495    
1496     // Hidden parts exposed, force complete refresh
1497     case Expose:
1498 gbeauche 1.3 #ifdef ENABLE_VOSF
1499     if (use_vosf) { // VOSF refresh
1500     LOCK_VOSF;
1501     PFLAG_SET_ALL;
1502     UNLOCK_VOSF;
1503     }
1504     #endif
1505 cebix 1.1 memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1506     break;
1507     }
1508     }
1509     }
1510    
1511    
1512     /*
1513     * Execute video VBL routine
1514     */
1515    
1516     void VideoVBL(void)
1517     {
1518     if (emerg_quit)
1519     QuitEmulator();
1520    
1521     // Execute video VBL
1522     if (private_data != NULL && private_data->interruptsEnabled)
1523     VSLDoInterruptService(private_data->vslServiceID);
1524     }
1525    
1526    
1527     /*
1528     * Install graphics acceleration
1529     */
1530    
1531     #if 0
1532     // Rectangle blitting
1533     static void accl_bitblt(accl_params *p)
1534     {
1535     D(bug("accl_bitblt\n"));
1536    
1537     // Get blitting parameters
1538     int16 src_X = p->src_rect[1] - p->src_bounds[1];
1539     int16 src_Y = p->src_rect[0] - p->src_bounds[0];
1540     int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1541     int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1542     int16 width = p->dest_rect[3] - p->dest_rect[1] - 1;
1543     int16 height = p->dest_rect[2] - p->dest_rect[0] - 1;
1544     D(bug(" src X %d, src Y %d, dest X %d, dest Y %d\n", src_X, src_Y, dest_X, dest_Y));
1545     D(bug(" width %d, height %d\n", width, height));
1546    
1547     // And perform the blit
1548     bitblt_hook(src_X, src_Y, dest_X, dest_Y, width, height);
1549     }
1550    
1551     static bool accl_bitblt_hook(accl_params *p)
1552     {
1553     D(bug("accl_draw_hook %p\n", p));
1554    
1555     // Check if we can accelerate this bitblt
1556     if (p->src_base_addr == screen_base && p->dest_base_addr == screen_base &&
1557     display_type == DIS_SCREEN && bitblt_hook != NULL &&
1558     ((uint32 *)p)[0x18 >> 2] + ((uint32 *)p)[0x128 >> 2] == 0 &&
1559     ((uint32 *)p)[0x130 >> 2] == 0 &&
1560     p->transfer_mode == 0 &&
1561     p->src_row_bytes > 0 && ((uint32 *)p)[0x15c >> 2] > 0) {
1562    
1563     // Yes, set function pointer
1564     p->draw_proc = accl_bitblt;
1565     return true;
1566     }
1567     return false;
1568     }
1569    
1570     // Rectangle filling/inversion
1571     static void accl_fillrect8(accl_params *p)
1572     {
1573     D(bug("accl_fillrect8\n"));
1574    
1575     // Get filling parameters
1576     int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1577     int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1578     int16 dest_X_max = p->dest_rect[3] - p->dest_bounds[1] - 1;
1579     int16 dest_Y_max = p->dest_rect[2] - p->dest_bounds[0] - 1;
1580     uint8 color = p->pen_mode == 8 ? p->fore_pen : p->back_pen;
1581     D(bug(" dest X %d, dest Y %d\n", dest_X, dest_Y));
1582     D(bug(" dest X max %d, dest Y max %d\n", dest_X_max, dest_Y_max));
1583    
1584     // And perform the fill
1585     fillrect8_hook(dest_X, dest_Y, dest_X_max, dest_Y_max, color);
1586     }
1587    
1588     static void accl_fillrect32(accl_params *p)
1589     {
1590     D(bug("accl_fillrect32\n"));
1591    
1592     // Get filling parameters
1593     int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1594     int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1595     int16 dest_X_max = p->dest_rect[3] - p->dest_bounds[1] - 1;
1596     int16 dest_Y_max = p->dest_rect[2] - p->dest_bounds[0] - 1;
1597     uint32 color = p->pen_mode == 8 ? p->fore_pen : p->back_pen;
1598     D(bug(" dest X %d, dest Y %d\n", dest_X, dest_Y));
1599     D(bug(" dest X max %d, dest Y max %d\n", dest_X_max, dest_Y_max));
1600    
1601     // And perform the fill
1602     fillrect32_hook(dest_X, dest_Y, dest_X_max, dest_Y_max, color);
1603     }
1604    
1605     static void accl_invrect(accl_params *p)
1606     {
1607     D(bug("accl_invrect\n"));
1608    
1609     // Get inversion parameters
1610     int16 dest_X = p->dest_rect[1] - p->dest_bounds[1];
1611     int16 dest_Y = p->dest_rect[0] - p->dest_bounds[0];
1612     int16 dest_X_max = p->dest_rect[3] - p->dest_bounds[1] - 1;
1613     int16 dest_Y_max = p->dest_rect[2] - p->dest_bounds[0] - 1;
1614     D(bug(" dest X %d, dest Y %d\n", dest_X, dest_Y));
1615     D(bug(" dest X max %d, dest Y max %d\n", dest_X_max, dest_Y_max));
1616    
1617     //!!?? pen_mode == 14
1618    
1619     // And perform the inversion
1620     invrect_hook(dest_X, dest_Y, dest_X_max, dest_Y_max);
1621     }
1622    
1623     static bool accl_fillrect_hook(accl_params *p)
1624     {
1625     D(bug("accl_fillrect_hook %p\n", p));
1626    
1627     // Check if we can accelerate this fillrect
1628     if (p->dest_base_addr == screen_base && ((uint32 *)p)[0x284 >> 2] != 0 && display_type == DIS_SCREEN) {
1629     if (p->transfer_mode == 8) {
1630     // Fill
1631     if (p->dest_pixel_size == 8 && fillrect8_hook != NULL) {
1632     p->draw_proc = accl_fillrect8;
1633     return true;
1634     } else if (p->dest_pixel_size == 32 && fillrect32_hook != NULL) {
1635     p->draw_proc = accl_fillrect32;
1636     return true;
1637     }
1638     } else if (p->transfer_mode == 10 && invrect_hook != NULL) {
1639     // Invert
1640     p->draw_proc = accl_invrect;
1641     return true;
1642     }
1643     }
1644     return false;
1645     }
1646    
1647     // Wait for graphics operation to finish
1648     static bool accl_sync_hook(void *arg)
1649     {
1650     D(bug("accl_sync_hook %p\n", arg));
1651     if (sync_hook != NULL)
1652     sync_hook();
1653     return true;
1654     }
1655    
1656     static struct accl_hook_info bitblt_hook_info = {accl_bitblt_hook, accl_sync_hook, ACCL_BITBLT};
1657     static struct accl_hook_info fillrect_hook_info = {accl_fillrect_hook, accl_sync_hook, ACCL_FILLRECT};
1658     #endif
1659    
1660     void VideoInstallAccel(void)
1661     {
1662     // Install acceleration hooks
1663     if (PrefsFindBool("gfxaccel")) {
1664     D(bug("Video: Installing acceleration hooks\n"));
1665     //!! NQDMisc(6, &bitblt_hook_info);
1666     // NQDMisc(6, &fillrect_hook_info);
1667     }
1668     }
1669    
1670    
1671     /*
1672     * Change video mode
1673     */
1674    
1675     int16 video_mode_change(VidLocals *csSave, uint32 ParamPtr)
1676     {
1677     /* return if no mode change */
1678     if ((csSave->saveData == ReadMacInt32(ParamPtr + csData)) &&
1679     (csSave->saveMode == ReadMacInt16(ParamPtr + csMode))) return noErr;
1680    
1681     /* first find video mode in table */
1682     for (int i=0; VModes[i].viType != DIS_INVALID; i++) {
1683     if ((ReadMacInt16(ParamPtr + csMode) == VModes[i].viAppleMode) &&
1684     (ReadMacInt32(ParamPtr + csData) == VModes[i].viAppleID)) {
1685     csSave->saveMode = ReadMacInt16(ParamPtr + csMode);
1686     csSave->saveData = ReadMacInt32(ParamPtr + csData);
1687     csSave->savePage = ReadMacInt16(ParamPtr + csPage);
1688    
1689     // Disable interrupts and pause redraw thread
1690     DisableInterrupt();
1691     thread_stop_ack = false;
1692     thread_stop_req = true;
1693     while (!thread_stop_ack) ;
1694    
1695     /* close old display */
1696     close_display();
1697    
1698     /* open new display */
1699     cur_mode = i;
1700     bool ok = open_display();
1701    
1702     /* opening the screen failed? Then bail out */
1703     if (!ok) {
1704     ErrorAlert(GetString(STR_FULL_SCREEN_ERR));
1705     QuitEmulator();
1706     }
1707    
1708     WriteMacInt32(ParamPtr + csBaseAddr, screen_base);
1709     csSave->saveBaseAddr=screen_base;
1710     csSave->saveData=VModes[cur_mode].viAppleID;/* First mode ... */
1711     csSave->saveMode=VModes[cur_mode].viAppleMode;
1712    
1713     // Enable interrupts and resume redraw thread
1714     thread_stop_req = false;
1715     EnableInterrupt();
1716     return noErr;
1717     }
1718     }
1719     return paramErr;
1720     }
1721    
1722    
1723     /*
1724     * Set color palette
1725     */
1726    
1727     void video_set_palette(void)
1728     {
1729 gbeauche 1.13 LOCK_PALETTE;
1730    
1731     // Convert colors to XColor array
1732     int mode = get_current_mode();
1733     int num_in = palette_size(mode);
1734     int num_out = 256;
1735     bool stretch = false;
1736     if (IsDirectMode(mode)) {
1737     // If X is in 565 mode we have to stretch the gamma table from 32 to 64 entries
1738     num_out = vis->map_entries;
1739     stretch = true;
1740     }
1741     XColor *p = x_palette;
1742     for (int i=0; i<num_out; i++) {
1743     int c = (stretch ? (i * num_in) / num_out : i);
1744     p->red = mac_pal[c].red * 0x0101;
1745     p->green = mac_pal[c].green * 0x0101;
1746     p->blue = mac_pal[c].blue * 0x0101;
1747     p++;
1748     }
1749    
1750     #ifdef ENABLE_VOSF
1751     // Recalculate pixel color expansion map
1752     if (!IsDirectMode(mode) && xdepth > 8) {
1753     for (int i=0; i<256; i++) {
1754     int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
1755     ExpandMap[i] = map_rgb(mac_pal[c].red, mac_pal[c].green, mac_pal[c].blue);
1756     }
1757    
1758     // We have to redraw everything because the interpretation of pixel values changed
1759     LOCK_VOSF;
1760     PFLAG_SET_ALL;
1761     UNLOCK_VOSF;
1762     memset(the_buffer_copy, 0, VModes[cur_mode].viRowBytes * VModes[cur_mode].viYsize);
1763     }
1764     #endif
1765    
1766     // Tell redraw thread to change palette
1767 cebix 1.1 palette_changed = true;
1768 gbeauche 1.13
1769     UNLOCK_PALETTE;
1770 cebix 1.1 }
1771    
1772    
1773     /*
1774     * Set cursor image for window
1775     */
1776    
1777     void video_set_cursor(void)
1778     {
1779     cursor_changed = true;
1780     }
1781    
1782    
1783     /*
1784     * Thread for window refresh, event handling and other periodic actions
1785     */
1786    
1787     static void update_display(void)
1788     {
1789     // Incremental update code
1790     int wide = 0, high = 0, x1, x2, y1, y2, i, j;
1791     int bytes_per_row = VModes[cur_mode].viRowBytes;
1792     int bytes_per_pixel = VModes[cur_mode].viRowBytes / VModes[cur_mode].viXsize;
1793     uint8 *p, *p2;
1794    
1795     // Check for first line from top and first line from bottom that have changed
1796     y1 = 0;
1797     for (j=0; j<VModes[cur_mode].viYsize; j++) {
1798     if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1799     y1 = j;
1800     break;
1801     }
1802     }
1803     y2 = y1 - 1;
1804     for (j=VModes[cur_mode].viYsize-1; j>=y1; j--) {
1805     if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1806     y2 = j;
1807     break;
1808     }
1809     }
1810     high = y2 - y1 + 1;
1811    
1812     // Check for first column from left and first column from right that have changed
1813     if (high) {
1814     if (depth == 1) {
1815     x1 = VModes[cur_mode].viXsize;
1816     for (j=y1; j<=y2; j++) {
1817     p = &the_buffer[j * bytes_per_row];
1818     p2 = &the_buffer_copy[j * bytes_per_row];
1819     for (i=0; i<(x1>>3); i++) {
1820     if (*p != *p2) {
1821     x1 = i << 3;
1822     break;
1823     }
1824     p++;
1825     p2++;
1826     }
1827     }
1828     x2 = x1;
1829     for (j=y1; j<=y2; j++) {
1830     p = &the_buffer[j * bytes_per_row];
1831     p2 = &the_buffer_copy[j * bytes_per_row];
1832     p += bytes_per_row;
1833     p2 += bytes_per_row;
1834     for (i=(VModes[cur_mode].viXsize>>3); i>(x2>>3); i--) {
1835     p--;
1836     p2--;
1837     if (*p != *p2) {
1838     x2 = i << 3;
1839     break;
1840     }
1841     }
1842     }
1843     wide = x2 - x1;
1844    
1845     // Update copy of the_buffer
1846     if (high && wide) {
1847     for (j=y1; j<=y2; j++) {
1848     i = j * bytes_per_row + (x1 >> 3);
1849     memcpy(&the_buffer_copy[i], &the_buffer[i], wide >> 3);
1850     }
1851     }
1852    
1853     } else {
1854     x1 = VModes[cur_mode].viXsize;
1855     for (j=y1; j<=y2; j++) {
1856     p = &the_buffer[j * bytes_per_row];
1857     p2 = &the_buffer_copy[j * bytes_per_row];
1858     for (i=0; i<x1; i++) {
1859     if (memcmp(p, p2, bytes_per_pixel)) {
1860     x1 = i;
1861     break;
1862     }
1863     p += bytes_per_pixel;
1864     p2 += bytes_per_pixel;
1865     }
1866     }
1867     x2 = x1;
1868     for (j=y1; j<=y2; j++) {
1869     p = &the_buffer[j * bytes_per_row];
1870     p2 = &the_buffer_copy[j * bytes_per_row];
1871     p += bytes_per_row;
1872     p2 += bytes_per_row;
1873     for (i=VModes[cur_mode].viXsize; i>x2; i--) {
1874     p -= bytes_per_pixel;
1875     p2 -= bytes_per_pixel;
1876     if (memcmp(p, p2, bytes_per_pixel)) {
1877     x2 = i;
1878     break;
1879     }
1880     }
1881     }
1882     wide = x2 - x1;
1883    
1884     // Update copy of the_buffer
1885     if (high && wide) {
1886     for (j=y1; j<=y2; j++) {
1887     i = j * bytes_per_row + x1 * bytes_per_pixel;
1888     memcpy(&the_buffer_copy[i], &the_buffer[i], bytes_per_pixel * wide);
1889     }
1890     }
1891     }
1892     }
1893    
1894     // Refresh display
1895     if (high && wide) {
1896 gbeauche 1.10 XDisplayLock();
1897 cebix 1.1 if (have_shm)
1898     XShmPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high, 0);
1899     else
1900     XPutImage(x_display, the_win, the_gc, img, x1, y1, x1, y1, wide, high);
1901 gbeauche 1.10 XDisplayUnlock();
1902 cebix 1.1 }
1903     }
1904    
1905 gbeauche 1.10 const int VIDEO_REFRESH_HZ = 60;
1906     const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
1907    
1908 gbeauche 1.13 static void handle_palette_changes(void)
1909     {
1910     LOCK_PALETTE;
1911    
1912     if (palette_changed && !emul_suspended) {
1913     palette_changed = false;
1914    
1915     int mode = get_current_mode();
1916     if (color_class == PseudoColor || color_class == DirectColor) {
1917     int num = vis->map_entries;
1918     bool set_clut = true;
1919     if (!IsDirectMode(mode) && color_class == DirectColor) {
1920     if (display_type == DIS_WINDOW)
1921     set_clut = false; // Indexed mode on true color screen, don't set CLUT
1922     }
1923    
1924     if (set_clut) {
1925     XDisplayLock();
1926     XStoreColors(x_display, cmap[0], x_palette, num);
1927     XStoreColors(x_display, cmap[1], x_palette, num);
1928     XSync(x_display, false);
1929     XDisplayUnlock();
1930     }
1931     }
1932    
1933     #ifdef ENABLE_XF86_DGA
1934     if (display_type == DIS_SCREEN) {
1935     current_dga_cmap ^= 1;
1936     if (!IsDirectMode(mode) && cmap[current_dga_cmap])
1937     XF86DGAInstallColormap(x_display, screen, cmap[current_dga_cmap]);
1938     }
1939     #endif
1940     }
1941    
1942     UNLOCK_PALETTE;
1943     }
1944    
1945 cebix 1.1 static void *redraw_func(void *arg)
1946     {
1947 gbeauche 1.10 int fd = ConnectionNumber(x_display);
1948    
1949     uint64 start = GetTicks_usec();
1950     int64 ticks = 0;
1951     uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
1952 cebix 1.1
1953     for (;;) {
1954    
1955     // Pause if requested (during video mode switches)
1956     while (thread_stop_req)
1957     thread_stop_ack = true;
1958    
1959 gbeauche 1.10 int64 delay = next - GetTicks_usec();
1960     if (delay < -VIDEO_REFRESH_DELAY) {
1961    
1962     // We are lagging far behind, so we reset the delay mechanism
1963     next = GetTicks_usec();
1964 cebix 1.1
1965 gbeauche 1.10 } else if (delay <= 0) {
1966    
1967     // Delay expired, refresh display
1968     next += VIDEO_REFRESH_DELAY;
1969     ticks++;
1970    
1971     // Handle X11 events
1972     handle_events();
1973    
1974     // Quit DGA mode if requested
1975     if (quit_full_screen) {
1976     quit_full_screen = false;
1977     if (display_type == DIS_SCREEN) {
1978     XDisplayLock();
1979 cebix 1.1 #ifdef ENABLE_XF86_DGA
1980 gbeauche 1.10 XF86DGADirectVideo(x_display, screen, 0);
1981     XUngrabPointer(x_display, CurrentTime);
1982     XUngrabKeyboard(x_display, CurrentTime);
1983     #endif
1984     XSync(x_display, false);
1985     XDisplayUnlock();
1986     quit_full_screen_ack = true;
1987     return NULL;
1988     }
1989 cebix 1.1 }
1990    
1991 gbeauche 1.10 // Refresh display and set cursor image in window mode
1992     static int tick_counter = 0;
1993     if (display_type == DIS_WINDOW) {
1994     tick_counter++;
1995     if (tick_counter >= frame_skip) {
1996     tick_counter = 0;
1997 cebix 1.1
1998 gbeauche 1.10 // Update display
1999 gbeauche 1.3 #ifdef ENABLE_VOSF
2000 gbeauche 1.10 if (use_vosf) {
2001     XDisplayLock();
2002     if (mainBuffer.dirty) {
2003     LOCK_VOSF;
2004     update_display_window_vosf();
2005     UNLOCK_VOSF;
2006     XSync(x_display, false); // Let the server catch up
2007     }
2008     XDisplayUnlock();
2009 gbeauche 1.3 }
2010 gbeauche 1.10 else
2011 gbeauche 1.3 #endif
2012 gbeauche 1.10 update_display();
2013 cebix 1.1
2014 gbeauche 1.10 // Set new cursor image if it was changed
2015     if (cursor_changed) {
2016     cursor_changed = false;
2017     memcpy(cursor_image->data, MacCursor + 4, 32);
2018     memcpy(cursor_mask_image->data, MacCursor + 36, 32);
2019     XDisplayLock();
2020     XFreeCursor(x_display, mac_cursor);
2021     XPutImage(x_display, cursor_map, cursor_gc, cursor_image, 0, 0, 0, 0, 16, 16);
2022     XPutImage(x_display, cursor_mask_map, cursor_mask_gc, cursor_mask_image, 0, 0, 0, 0, 16, 16);
2023     mac_cursor = XCreatePixmapCursor(x_display, cursor_map, cursor_mask_map, &black, &white, MacCursor[2], MacCursor[3]);
2024     XDefineCursor(x_display, the_win, mac_cursor);
2025     XDisplayUnlock();
2026     }
2027 cebix 1.1 }
2028     }
2029 gbeauche 1.3 #ifdef ENABLE_VOSF
2030 gbeauche 1.10 else if (use_vosf) {
2031     // Update display (VOSF variant)
2032     if (++tick_counter >= frame_skip) {
2033     tick_counter = 0;
2034     if (mainBuffer.dirty) {
2035     LOCK_VOSF;
2036     update_display_dga_vosf();
2037     UNLOCK_VOSF;
2038     }
2039 gbeauche 1.3 }
2040     }
2041     #endif
2042 cebix 1.1
2043 gbeauche 1.10 // Set new palette if it was changed
2044 gbeauche 1.13 handle_palette_changes();
2045 gbeauche 1.10
2046     } else {
2047    
2048     // No display refresh pending, check for X events
2049     fd_set readfds;
2050     FD_ZERO(&readfds);
2051     FD_SET(fd, &readfds);
2052     struct timeval timeout;
2053     timeout.tv_sec = 0;
2054     timeout.tv_usec = delay;
2055     if (select(fd+1, &readfds, NULL, NULL, &timeout) > 0)
2056     handle_events();
2057 cebix 1.1 }
2058     }
2059     return NULL;
2060     }