ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/video_x.cpp
Revision: 1.28
Committed: 2004-06-22T19:32:00Z (20 years, 4 months ago) by gbeauche
Branch: MAIN
Changes since 1.27: +4 -1 lines
Log Message:
Fix VideoExit() on OSX, there was no cancellation point in redraw_thread.

File Contents

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