ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/SDL/video_sdl.cpp
Revision: 1.42
Committed: 2011-12-28T22:15:10Z (12 years, 6 months ago) by asvitkine
Branch: MAIN
Changes since 1.41: +10 -0 lines
Log Message:
fix SDL leak by wrapping video_refresh() call with an NSAutoReleasePool

File Contents

# Content
1 /*
2 * video_sdl.cpp - Video/graphics emulation, SDL specific stuff
3 *
4 * Basilisk II (C) 1997-2008 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 /*
22 * NOTES:
23 * The Ctrl key works like a qualifier for special actions:
24 * Ctrl-Tab = suspend DGA mode (TODO)
25 * Ctrl-Esc = emergency quit
26 * Ctrl-F1 = mount floppy
27 * Ctrl-F5 = grab mouse (in windowed mode)
28 *
29 * FIXMEs and TODOs:
30 * - Windows requires an extra mouse event to update the actual cursor image?
31 * - Ctr-Tab for suspend/resume but how? SDL does not support that for non-Linux
32 * - Ctrl-Fn doesn't generate SDL_KEYDOWN events (SDL bug?)
33 * - Mouse acceleration, there is no API in SDL yet for that
34 * - Force relative mode in Grab mode even if SDL provides absolute coordinates?
35 * - Gamma tables support is likely to be broken here
36 * - Events processing is bound to the general emulation thread as SDL requires
37 * to PumpEvents() within the same thread as the one that called SetVideoMode().
38 * Besides, there can't seem to be a way to call SetVideoMode() from a child thread.
39 * - Backport hw cursor acceleration to Basilisk II?
40 * - Factor out code
41 */
42
43 #include "sysdeps.h"
44
45 #include <SDL.h>
46 #include <SDL_mutex.h>
47 #include <SDL_thread.h>
48 #include <errno.h>
49 #include <vector>
50
51 #ifdef WIN32
52 #include <malloc.h> /* alloca() */
53 #endif
54
55 #include "cpu_emulation.h"
56 #include "main.h"
57 #include "adb.h"
58 #include "macos_util.h"
59 #include "prefs.h"
60 #include "user_strings.h"
61 #include "video.h"
62 #include "video_defs.h"
63 #include "video_blit.h"
64 #include "vm_alloc.h"
65
66 #define DEBUG 0
67 #include "debug.h"
68
69 #if (defined(__APPLE__) && defined(__MACH__))
70 extern "C" {
71 void NSAutoReleasePool_wrap(void (*fn)(void));
72 }
73 #endif
74
75 // Supported video modes
76 using std::vector;
77 static vector<VIDEO_MODE> VideoModes;
78
79 // Display types
80 #ifdef SHEEPSHAVER
81 enum {
82 DISPLAY_WINDOW = DIS_WINDOW, // windowed display
83 DISPLAY_SCREEN = DIS_SCREEN // fullscreen display
84 };
85 extern int display_type; // See enum above
86 #else
87 enum {
88 DISPLAY_WINDOW, // windowed display
89 DISPLAY_SCREEN // fullscreen display
90 };
91 static int display_type = DISPLAY_WINDOW; // See enum above
92 #endif
93
94 // Constants
95 #ifdef WIN32
96 const char KEYCODE_FILE_NAME[] = "BasiliskII_keycodes";
97 #else
98 const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes";
99 #endif
100
101
102 // Global variables
103 static int32 frame_skip; // Prefs items
104 static int16 mouse_wheel_mode;
105 static int16 mouse_wheel_lines;
106
107 static uint8 *the_buffer = NULL; // Mac frame buffer (where MacOS draws into)
108 static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer (for refreshed modes)
109 static uint32 the_buffer_size; // Size of allocated the_buffer
110
111 static bool redraw_thread_active = false; // Flag: Redraw thread installed
112 #ifndef USE_CPU_EMUL_SERVICES
113 static volatile bool redraw_thread_cancel; // Flag: Cancel Redraw thread
114 static SDL_Thread *redraw_thread = NULL; // Redraw thread
115 #ifdef SHEEPSHAVER
116 static volatile bool thread_stop_req = false;
117 static volatile bool thread_stop_ack = false; // Acknowledge for thread_stop_req
118 #endif
119 #endif
120
121 #ifdef ENABLE_VOSF
122 static bool use_vosf = false; // Flag: VOSF enabled
123 #else
124 static const bool use_vosf = false; // VOSF not possible
125 #endif
126
127 static bool ctrl_down = false; // Flag: Ctrl key pressed
128 static bool caps_on = false; // Flag: Caps Lock on
129 static bool quit_full_screen = false; // Flag: DGA close requested from redraw thread
130 static bool emerg_quit = false; // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread
131 static bool emul_suspended = false; // Flag: Emulator suspended
132
133 static bool classic_mode = false; // Flag: Classic Mac video mode
134
135 static bool use_keycodes = false; // Flag: Use keycodes rather than keysyms
136 static int keycode_table[256]; // X keycode -> Mac keycode translation table
137
138 // SDL variables
139 static int screen_depth; // Depth of current screen
140 static SDL_Cursor *sdl_cursor; // Copy of Mac cursor
141 static volatile bool cursor_changed = false; // Flag: cursor changed, redraw_func must update the cursor
142 static SDL_Color sdl_palette[256]; // Color palette to be used as CLUT and gamma table
143 static bool sdl_palette_changed = false; // Flag: Palette changed, redraw thread must set new colors
144 static const int sdl_eventmask = SDL_MOUSEEVENTMASK | SDL_KEYEVENTMASK | SDL_VIDEOEXPOSEMASK | SDL_QUITMASK | SDL_ACTIVEEVENTMASK;
145
146 // Mutex to protect SDL events
147 static SDL_mutex *sdl_events_lock = NULL;
148 #define LOCK_EVENTS SDL_LockMutex(sdl_events_lock)
149 #define UNLOCK_EVENTS SDL_UnlockMutex(sdl_events_lock)
150
151 // Mutex to protect palette
152 static SDL_mutex *sdl_palette_lock = NULL;
153 #define LOCK_PALETTE SDL_LockMutex(sdl_palette_lock)
154 #define UNLOCK_PALETTE SDL_UnlockMutex(sdl_palette_lock)
155
156 // Mutex to protect frame buffer
157 static SDL_mutex *frame_buffer_lock = NULL;
158 #define LOCK_FRAME_BUFFER SDL_LockMutex(frame_buffer_lock)
159 #define UNLOCK_FRAME_BUFFER SDL_UnlockMutex(frame_buffer_lock)
160
161 // Video refresh function
162 static void VideoRefreshInit(void);
163 static void (*video_refresh)(void);
164
165
166 // Prototypes
167 static int redraw_func(void *arg);
168
169 // From sys_unix.cpp
170 extern void SysMountFirstFloppy(void);
171
172
173 /*
174 * SDL surface locking glue
175 */
176
177 #ifdef ENABLE_VOSF
178 #define SDL_VIDEO_LOCK_VOSF_SURFACE(SURFACE) do { \
179 if ((SURFACE)->flags & (SDL_HWSURFACE | SDL_FULLSCREEN)) \
180 the_host_buffer = (uint8 *)(SURFACE)->pixels; \
181 } while (0)
182 #else
183 #define SDL_VIDEO_LOCK_VOSF_SURFACE(SURFACE)
184 #endif
185
186 #define SDL_VIDEO_LOCK_SURFACE(SURFACE) do { \
187 if (SDL_MUSTLOCK(SURFACE)) { \
188 SDL_LockSurface(SURFACE); \
189 SDL_VIDEO_LOCK_VOSF_SURFACE(SURFACE); \
190 } \
191 } while (0)
192
193 #define SDL_VIDEO_UNLOCK_SURFACE(SURFACE) do { \
194 if (SDL_MUSTLOCK(SURFACE)) \
195 SDL_UnlockSurface(SURFACE); \
196 } while (0)
197
198
199 /*
200 * Framebuffer allocation routines
201 */
202
203 static void *vm_acquire_framebuffer(uint32 size)
204 {
205 // always try to reallocate framebuffer at the same address
206 static void *fb = VM_MAP_FAILED;
207 if (fb != VM_MAP_FAILED) {
208 if (vm_acquire_fixed(fb, size) < 0) {
209 #ifndef SHEEPSHAVER
210 printf("FATAL: Could not reallocate framebuffer at previous address\n");
211 #endif
212 fb = VM_MAP_FAILED;
213 }
214 }
215 if (fb == VM_MAP_FAILED)
216 fb = vm_acquire(size, VM_MAP_DEFAULT | VM_MAP_32BIT);
217 return fb;
218 }
219
220 static inline void vm_release_framebuffer(void *fb, uint32 size)
221 {
222 vm_release(fb, size);
223 }
224
225
226 /*
227 * Windows message handler
228 */
229
230 #ifdef WIN32
231 #include <dbt.h>
232 static WNDPROC sdl_window_proc = NULL; // Window proc used by SDL
233
234 extern void SysMediaArrived(void);
235 extern void SysMediaRemoved(void);
236 extern HWND GetMainWindowHandle(void);
237
238 static LRESULT CALLBACK windows_message_handler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
239 {
240 switch (msg) {
241 case WM_DEVICECHANGE:
242 if (wParam == DBT_DEVICEREMOVECOMPLETE) {
243 DEV_BROADCAST_HDR *p = (DEV_BROADCAST_HDR *)lParam;
244 if (p->dbch_devicetype == DBT_DEVTYP_VOLUME)
245 SysMediaRemoved();
246 }
247 else if (wParam == DBT_DEVICEARRIVAL) {
248 DEV_BROADCAST_HDR *p = (DEV_BROADCAST_HDR *)lParam;
249 if (p->dbch_devicetype == DBT_DEVTYP_VOLUME)
250 SysMediaArrived();
251 }
252 return 0;
253
254 default:
255 if (sdl_window_proc)
256 return CallWindowProc(sdl_window_proc, hwnd, msg, wParam, lParam);
257 }
258
259 return DefWindowProc(hwnd, msg, wParam, lParam);
260 }
261 #endif
262
263
264 /*
265 * SheepShaver glue
266 */
267
268 #ifdef SHEEPSHAVER
269 // Color depth modes type
270 typedef int video_depth;
271
272 // 1, 2, 4 and 8 bit depths use a color palette
273 static inline bool IsDirectMode(VIDEO_MODE const & mode)
274 {
275 return IsDirectMode(mode.viAppleMode);
276 }
277
278 // Abstract base class representing one (possibly virtual) monitor
279 // ("monitor" = rectangular display with a contiguous frame buffer)
280 class monitor_desc {
281 public:
282 monitor_desc(const vector<VIDEO_MODE> &available_modes, video_depth default_depth, uint32 default_id) {}
283 virtual ~monitor_desc() {}
284
285 // Get current Mac frame buffer base address
286 uint32 get_mac_frame_base(void) const {return screen_base;}
287
288 // Set Mac frame buffer base address (called from switch_to_mode())
289 void set_mac_frame_base(uint32 base) {screen_base = base;}
290
291 // Get current video mode
292 const VIDEO_MODE &get_current_mode(void) const {return VModes[cur_mode];}
293
294 // Called by the video driver to switch the video mode on this display
295 // (must call set_mac_frame_base())
296 virtual void switch_to_current_mode(void) = 0;
297
298 // Called by the video driver to set the color palette (in indexed modes)
299 // or the gamma table (in direct modes)
300 virtual void set_palette(uint8 *pal, int num) = 0;
301 };
302
303 // Vector of pointers to available monitor descriptions, filled by VideoInit()
304 static vector<monitor_desc *> VideoMonitors;
305
306 // Find Apple mode matching best specified dimensions
307 static int find_apple_resolution(int xsize, int ysize)
308 {
309 if (xsize == 640 && ysize == 480)
310 return APPLE_640x480;
311 if (xsize == 800 && ysize == 600)
312 return APPLE_800x600;
313 if (xsize == 1024 && ysize == 768)
314 return APPLE_1024x768;
315 if (xsize == 1152 && ysize == 768)
316 return APPLE_1152x768;
317 if (xsize == 1152 && ysize == 900)
318 return APPLE_1152x900;
319 if (xsize == 1280 && ysize == 1024)
320 return APPLE_1280x1024;
321 if (xsize == 1600 && ysize == 1200)
322 return APPLE_1600x1200;
323 return APPLE_CUSTOM;
324 }
325
326 // Display error alert
327 static void ErrorAlert(int error)
328 {
329 ErrorAlert(GetString(error));
330 }
331
332 // Display warning alert
333 static void WarningAlert(int warning)
334 {
335 WarningAlert(GetString(warning));
336 }
337 #endif
338
339
340 /*
341 * monitor_desc subclass for SDL display
342 */
343
344 class SDL_monitor_desc : public monitor_desc {
345 public:
346 SDL_monitor_desc(const vector<VIDEO_MODE> &available_modes, video_depth default_depth, uint32 default_id) : monitor_desc(available_modes, default_depth, default_id) {}
347 ~SDL_monitor_desc() {}
348
349 virtual void switch_to_current_mode(void);
350 virtual void set_palette(uint8 *pal, int num);
351
352 bool video_open(void);
353 void video_close(void);
354 };
355
356
357 /*
358 * Utility functions
359 */
360
361 // Find palette size for given color depth
362 static int palette_size(int mode)
363 {
364 switch (mode) {
365 case VIDEO_DEPTH_1BIT: return 2;
366 case VIDEO_DEPTH_2BIT: return 4;
367 case VIDEO_DEPTH_4BIT: return 16;
368 case VIDEO_DEPTH_8BIT: return 256;
369 case VIDEO_DEPTH_16BIT: return 32;
370 case VIDEO_DEPTH_32BIT: return 256;
371 default: return 0;
372 }
373 }
374
375 // Return bytes per pixel for requested depth
376 static inline int bytes_per_pixel(int depth)
377 {
378 int bpp;
379 switch (depth) {
380 case 8:
381 bpp = 1;
382 break;
383 case 15: case 16:
384 bpp = 2;
385 break;
386 case 24: case 32:
387 bpp = 4;
388 break;
389 default:
390 abort();
391 }
392 return bpp;
393 }
394
395 // Map video_mode depth ID to numerical depth value
396 static int mac_depth_of_video_depth(int video_depth)
397 {
398 int depth = -1;
399 switch (video_depth) {
400 case VIDEO_DEPTH_1BIT:
401 depth = 1;
402 break;
403 case VIDEO_DEPTH_2BIT:
404 depth = 2;
405 break;
406 case VIDEO_DEPTH_4BIT:
407 depth = 4;
408 break;
409 case VIDEO_DEPTH_8BIT:
410 depth = 8;
411 break;
412 case VIDEO_DEPTH_16BIT:
413 depth = 16;
414 break;
415 case VIDEO_DEPTH_32BIT:
416 depth = 32;
417 break;
418 default:
419 abort();
420 }
421 return depth;
422 }
423
424 // Map video_mode depth ID to SDL screen depth
425 static int sdl_depth_of_video_depth(int video_depth)
426 {
427 return (video_depth <= VIDEO_DEPTH_8BIT) ? 8 : mac_depth_of_video_depth(video_depth);
428 }
429
430 // Get screen dimensions
431 static void sdl_display_dimensions(int &width, int &height)
432 {
433 static int max_width, max_height;
434 if (max_width == 0 && max_height == 0) {
435 max_width = 640 ; max_height = 480;
436 SDL_Rect **modes = SDL_ListModes(NULL, SDL_FULLSCREEN | SDL_HWSURFACE);
437 if (modes && modes != (SDL_Rect **)-1) {
438 // It turns out that on some implementations, and contrary to the documentation,
439 // the returned list is not sorted from largest to smallest (e.g. Windows)
440 for (int i = 0; modes[i] != NULL; i++) {
441 const int w = modes[i]->w;
442 const int h = modes[i]->h;
443 if (w > max_width && h > max_height) {
444 max_width = w;
445 max_height = h;
446 }
447 }
448 }
449 }
450 width = max_width;
451 height = max_height;
452 }
453
454 static inline int sdl_display_width(void)
455 {
456 int width, height;
457 sdl_display_dimensions(width, height);
458 return width;
459 }
460
461 static inline int sdl_display_height(void)
462 {
463 int width, height;
464 sdl_display_dimensions(width, height);
465 return height;
466 }
467
468 // Check wether specified mode is available
469 static bool has_mode(int type, int width, int height, int depth)
470 {
471 #ifdef SHEEPSHAVER
472 // Filter out Classic resolutions
473 if (width == 512 && height == 384)
474 return false;
475 #endif
476
477 // Filter out out-of-bounds resolutions
478 if (width > sdl_display_width() || height > sdl_display_height())
479 return false;
480
481 // Rely on SDL capabilities
482 return SDL_VideoModeOK(width, height,
483 sdl_depth_of_video_depth(depth),
484 SDL_HWSURFACE | (type == DISPLAY_SCREEN ? SDL_FULLSCREEN : 0));
485 }
486
487 // Add mode to list of supported modes
488 static void add_mode(int type, int width, int height, int resolution_id, int bytes_per_row, int depth)
489 {
490 // Filter out unsupported modes
491 if (!has_mode(type, width, height, depth))
492 return;
493
494 // Fill in VideoMode entry
495 VIDEO_MODE mode;
496 #ifdef SHEEPSHAVER
497 resolution_id = find_apple_resolution(width, height);
498 mode.viType = type;
499 #endif
500 VIDEO_MODE_X = width;
501 VIDEO_MODE_Y = height;
502 VIDEO_MODE_RESOLUTION = resolution_id;
503 VIDEO_MODE_ROW_BYTES = bytes_per_row;
504 VIDEO_MODE_DEPTH = (video_depth)depth;
505 VideoModes.push_back(mode);
506 }
507
508 // Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac)
509 static void set_mac_frame_buffer(SDL_monitor_desc &monitor, int depth, bool native_byte_order)
510 {
511 #if !REAL_ADDRESSING && !DIRECT_ADDRESSING
512 int layout = FLAYOUT_DIRECT;
513 if (depth == VIDEO_DEPTH_16BIT)
514 layout = (screen_depth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565;
515 else if (depth == VIDEO_DEPTH_32BIT)
516 layout = (screen_depth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT;
517 if (native_byte_order)
518 MacFrameLayout = layout;
519 else
520 MacFrameLayout = FLAYOUT_DIRECT;
521 monitor.set_mac_frame_base(MacFrameBaseMac);
522
523 // Set variables used by UAE memory banking
524 const VIDEO_MODE &mode = monitor.get_current_mode();
525 MacFrameBaseHost = the_buffer;
526 MacFrameSize = VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y;
527 InitFrameBufferMapping();
528 #else
529 monitor.set_mac_frame_base(Host2MacAddr(the_buffer));
530 #endif
531 D(bug("monitor.mac_frame_base = %08x\n", monitor.get_mac_frame_base()));
532 }
533
534 // Set window name and class
535 static void set_window_name(int name)
536 {
537 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
538 if (vi && vi->wm_available) {
539 const char *str = GetString(name);
540 SDL_WM_SetCaption(str, str);
541 }
542 }
543
544 // Set mouse grab mode
545 static SDL_GrabMode set_grab_mode(SDL_GrabMode mode)
546 {
547 const SDL_VideoInfo *vi = SDL_GetVideoInfo();
548 return (vi && vi->wm_available ? SDL_WM_GrabInput(mode) : SDL_GRAB_OFF);
549 }
550
551 // Migrate preferences items (XXX to be handled in MigratePrefs())
552 static void migrate_screen_prefs(void)
553 {
554 #ifdef SHEEPSHAVER
555 // Look-up priorities are: "screen", "screenmodes", "windowmodes".
556 if (PrefsFindString("screen"))
557 return;
558
559 uint32 window_modes = PrefsFindInt32("windowmodes");
560 uint32 screen_modes = PrefsFindInt32("screenmodes");
561 int width = 0, height = 0;
562 if (screen_modes) {
563 static const struct {
564 int id;
565 int width;
566 int height;
567 }
568 modes[] = {
569 { 1, 640, 480 },
570 { 2, 800, 600 },
571 { 4, 1024, 768 },
572 { 64, 1152, 768 },
573 { 8, 1152, 900 },
574 { 16, 1280, 1024 },
575 { 32, 1600, 1200 },
576 { 0, }
577 };
578 for (int i = 0; modes[i].id != 0; i++) {
579 if (screen_modes & modes[i].id) {
580 if (width < modes[i].width && height < modes[i].height) {
581 width = modes[i].width;
582 height = modes[i].height;
583 }
584 }
585 }
586 } else {
587 if (window_modes & 1)
588 width = 640, height = 480;
589 if (window_modes & 2)
590 width = 800, height = 600;
591 }
592 if (width && height) {
593 char str[32];
594 sprintf(str, "%s/%d/%d", screen_modes ? "dga" : "win", width, height);
595 PrefsReplaceString("screen", str);
596 }
597 #endif
598 }
599
600
601 /*
602 * Display "driver" classes
603 */
604
605 class driver_base {
606 public:
607 driver_base(SDL_monitor_desc &m);
608 virtual ~driver_base();
609
610 virtual void update_palette(void);
611 virtual void suspend(void) {}
612 virtual void resume(void) {}
613 virtual void toggle_mouse_grab(void) {}
614 virtual void mouse_moved(int x, int y) { ADBMouseMoved(x, y); }
615
616 void disable_mouse_accel(void);
617 void restore_mouse_accel(void);
618
619 virtual void grab_mouse(void) {}
620 virtual void ungrab_mouse(void) {}
621
622 public:
623 SDL_monitor_desc &monitor; // Associated video monitor
624 const VIDEO_MODE &mode; // Video mode handled by the driver
625
626 bool init_ok; // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer)
627 SDL_Surface *s; // The surface we draw into
628 };
629
630 class driver_window;
631 static void update_display_window_vosf(driver_window *drv);
632 static void update_display_dynamic(int ticker, driver_window *drv);
633 static void update_display_static(driver_base *drv);
634
635 class driver_window : public driver_base {
636 friend void update_display_window_vosf(driver_window *drv);
637 friend void update_display_dynamic(int ticker, driver_window *drv);
638 friend void update_display_static(driver_base *drv);
639
640 public:
641 driver_window(SDL_monitor_desc &monitor);
642 ~driver_window();
643
644 void toggle_mouse_grab(void);
645 void mouse_moved(int x, int y);
646
647 void grab_mouse(void);
648 void ungrab_mouse(void);
649
650 private:
651 bool mouse_grabbed; // Flag: mouse pointer grabbed, using relative mouse mode
652 int mouse_last_x, mouse_last_y; // Last mouse position (for relative mode)
653 };
654
655 class driver_fullscreen : public driver_base {
656 public:
657 driver_fullscreen(SDL_monitor_desc &monitor);
658 ~driver_fullscreen();
659 };
660
661 static driver_base *drv = NULL; // Pointer to currently used driver object
662
663 #ifdef ENABLE_VOSF
664 # include "video_vosf.h"
665 #endif
666
667 driver_base::driver_base(SDL_monitor_desc &m)
668 : monitor(m), mode(m.get_current_mode()), init_ok(false), s(NULL)
669 {
670 the_buffer = NULL;
671 the_buffer_copy = NULL;
672 }
673
674 driver_base::~driver_base()
675 {
676 ungrab_mouse();
677 restore_mouse_accel();
678
679 if (s)
680 SDL_FreeSurface(s);
681
682 // the_buffer shall always be mapped through vm_acquire_framebuffer()
683 if (the_buffer != VM_MAP_FAILED) {
684 D(bug(" releasing the_buffer at %p (%d bytes)\n", the_buffer, the_buffer_size));
685 vm_release_framebuffer(the_buffer, the_buffer_size);
686 the_buffer = NULL;
687 }
688
689 // Free frame buffer(s)
690 if (!use_vosf) {
691 if (the_buffer_copy) {
692 free(the_buffer_copy);
693 the_buffer_copy = NULL;
694 }
695 }
696 #ifdef ENABLE_VOSF
697 else {
698 if (the_host_buffer) {
699 D(bug(" freeing the_host_buffer at %p\n", the_host_buffer));
700 free(the_host_buffer);
701 the_host_buffer = NULL;
702 }
703 if (the_buffer_copy) {
704 D(bug(" freeing the_buffer_copy at %p\n", the_buffer_copy));
705 free(the_buffer_copy);
706 the_buffer_copy = NULL;
707 }
708
709 // Deinitialize VOSF
710 video_vosf_exit();
711 }
712 #endif
713 }
714
715 // Palette has changed
716 void driver_base::update_palette(void)
717 {
718 const VIDEO_MODE &mode = monitor.get_current_mode();
719
720 if ((int)VIDEO_MODE_DEPTH <= VIDEO_DEPTH_8BIT)
721 SDL_SetPalette(s, SDL_PHYSPAL, sdl_palette, 0, 256);
722 }
723
724 // Disable mouse acceleration
725 void driver_base::disable_mouse_accel(void)
726 {
727 }
728
729 // Restore mouse acceleration to original value
730 void driver_base::restore_mouse_accel(void)
731 {
732 }
733
734
735 /*
736 * Windowed display driver
737 */
738
739 static bool SDL_display_opened = false;
740
741 // Open display
742 driver_window::driver_window(SDL_monitor_desc &m)
743 : driver_base(m), mouse_grabbed(false)
744 {
745 int width = VIDEO_MODE_X, height = VIDEO_MODE_Y;
746 int aligned_width = (width + 15) & ~15;
747 int aligned_height = (height + 15) & ~15;
748
749 // Set absolute mouse mode
750 ADBSetRelMouseMode(mouse_grabbed);
751
752 // This is ugly:
753 // If we're switching resolutions (ie, not setting it for the first time),
754 // there's a bug in SDL where the SDL_Surface created will not be properly
755 // setup. The solution is to SDL_QuitSubSystem(SDL_INIT_VIDEO) before calling
756 // SDL_SetVideoMode for the second time (SDL_SetVideoMode will call SDL_Init()
757 // and all will be well). Without this, the video becomes corrupted (at least
758 // on Mac OS X), after the resolution switch.
759 if (SDL_display_opened)
760 SDL_QuitSubSystem(SDL_INIT_VIDEO);
761
762 // Create surface
763 int depth = sdl_depth_of_video_depth(VIDEO_MODE_DEPTH);
764 if ((s = SDL_SetVideoMode(width, height, depth, SDL_HWSURFACE)) == NULL)
765 return;
766
767 SDL_display_opened = true;
768
769 #ifdef ENABLE_VOSF
770 use_vosf = true;
771 // Allocate memory for frame buffer (SIZE is extended to page-boundary)
772 the_host_buffer = (uint8 *)s->pixels;
773 the_buffer_size = page_extend((aligned_height + 2) * s->pitch);
774 the_buffer = (uint8 *)vm_acquire_framebuffer(the_buffer_size);
775 the_buffer_copy = (uint8 *)malloc(the_buffer_size);
776 D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
777
778 // Check whether we can initialize the VOSF subsystem and it's profitable
779 if (!video_vosf_init(m)) {
780 WarningAlert(STR_VOSF_INIT_ERR);
781 use_vosf = false;
782 }
783 else if (!video_vosf_profitable()) {
784 video_vosf_exit();
785 printf("VOSF acceleration is not profitable on this platform, disabling it\n");
786 use_vosf = false;
787 }
788 if (!use_vosf) {
789 free(the_buffer_copy);
790 vm_release(the_buffer, the_buffer_size);
791 the_host_buffer = NULL;
792 }
793 #endif
794 if (!use_vosf) {
795 // Allocate memory for frame buffer
796 the_buffer_size = (aligned_height + 2) * s->pitch;
797 the_buffer_copy = (uint8 *)calloc(1, the_buffer_size);
798 the_buffer = (uint8 *)vm_acquire_framebuffer(the_buffer_size);
799 D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
800 }
801
802 #ifdef SHEEPSHAVER
803 // Create cursor
804 if ((sdl_cursor = SDL_CreateCursor(MacCursor + 4, MacCursor + 36, 16, 16, 0, 0)) != NULL) {
805 SDL_SetCursor(sdl_cursor);
806 cursor_changed = false;
807 }
808 #else
809 // Hide cursor
810 SDL_ShowCursor(0);
811 #endif
812
813 // Set window name/class
814 set_window_name(STR_WINDOW_TITLE);
815
816 // Init blitting routines
817 SDL_PixelFormat *f = s->format;
818 VisualFormat visualFormat;
819 visualFormat.depth = depth;
820 visualFormat.Rmask = f->Rmask;
821 visualFormat.Gmask = f->Gmask;
822 visualFormat.Bmask = f->Bmask;
823 Screen_blitter_init(visualFormat, true, mac_depth_of_video_depth(VIDEO_MODE_DEPTH));
824
825 // Load gray ramp to 8->16/32 expand map
826 if (!IsDirectMode(mode))
827 for (int i=0; i<256; i++)
828 ExpandMap[i] = SDL_MapRGB(f, i, i, i);
829
830 // Set frame buffer base
831 set_mac_frame_buffer(monitor, VIDEO_MODE_DEPTH, true);
832
833 // Everything went well
834 init_ok = true;
835 }
836
837 // Close display
838 driver_window::~driver_window()
839 {
840 #ifdef ENABLE_VOSF
841 if (use_vosf)
842 the_host_buffer = NULL; // don't free() in driver_base dtor
843 #endif
844 if (s)
845 SDL_FreeSurface(s);
846 }
847
848 // Toggle mouse grab
849 void driver_window::toggle_mouse_grab(void)
850 {
851 if (mouse_grabbed)
852 ungrab_mouse();
853 else
854 grab_mouse();
855 }
856
857 // Grab mouse, switch to relative mouse mode
858 void driver_window::grab_mouse(void)
859 {
860 if (!mouse_grabbed) {
861 SDL_GrabMode new_mode = set_grab_mode(SDL_GRAB_ON);
862 if (new_mode == SDL_GRAB_ON) {
863 set_window_name(STR_WINDOW_TITLE_GRABBED);
864 disable_mouse_accel();
865 mouse_grabbed = true;
866 }
867 }
868 }
869
870 // Ungrab mouse, switch to absolute mouse mode
871 void driver_window::ungrab_mouse(void)
872 {
873 if (mouse_grabbed) {
874 SDL_GrabMode new_mode = set_grab_mode(SDL_GRAB_OFF);
875 if (new_mode == SDL_GRAB_OFF) {
876 set_window_name(STR_WINDOW_TITLE);
877 restore_mouse_accel();
878 mouse_grabbed = false;
879 }
880 }
881 }
882
883 // Mouse moved
884 void driver_window::mouse_moved(int x, int y)
885 {
886 mouse_last_x = x; mouse_last_y = y;
887 ADBMouseMoved(x, y);
888 }
889
890
891 /*
892 * Full-screen display driver
893 */
894
895 // Open display
896 driver_fullscreen::driver_fullscreen(SDL_monitor_desc &m)
897 : driver_base(m)
898 {
899 int width = VIDEO_MODE_X, height = VIDEO_MODE_Y;
900 int aligned_width = (width + 15) & ~15;
901 int aligned_height = (height + 15) & ~15;
902
903 // Set absolute mouse mode
904 ADBSetRelMouseMode(false);
905
906 // Create surface
907 int depth = sdl_depth_of_video_depth(VIDEO_MODE_DEPTH);
908 if ((s = SDL_SetVideoMode(width, height, depth, SDL_HWSURFACE | SDL_FULLSCREEN)) == NULL)
909 return;
910
911 #ifdef ENABLE_VOSF
912 use_vosf = true;
913 // Allocate memory for frame buffer (SIZE is extended to page-boundary)
914 the_host_buffer = (uint8 *)s->pixels;
915 the_buffer_size = page_extend((aligned_height + 2) * s->pitch);
916 the_buffer = (uint8 *)vm_acquire_framebuffer(the_buffer_size);
917 the_buffer_copy = (uint8 *)malloc(the_buffer_size);
918 D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer));
919
920 // Check whether we can initialize the VOSF subsystem and it's profitable
921 if (!video_vosf_init(m)) {
922 WarningAlert(STR_VOSF_INIT_ERR);
923 use_vosf = false;
924 }
925 else if (!video_vosf_profitable()) {
926 video_vosf_exit();
927 printf("VOSF acceleration is not profitable on this platform, disabling it\n");
928 use_vosf = false;
929 }
930 if (!use_vosf) {
931 free(the_buffer_copy);
932 vm_release(the_buffer, the_buffer_size);
933 the_host_buffer = NULL;
934 }
935 #endif
936 if (!use_vosf) {
937 // Allocate memory for frame buffer
938 the_buffer_size = (aligned_height + 2) * s->pitch;
939 the_buffer_copy = (uint8 *)calloc(1, the_buffer_size);
940 the_buffer = (uint8 *)vm_acquire_framebuffer(the_buffer_size);
941 D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy));
942 }
943
944 // Hide cursor
945 SDL_ShowCursor(0);
946
947 // Init blitting routines
948 SDL_PixelFormat *f = s->format;
949 VisualFormat visualFormat;
950 visualFormat.depth = depth;
951 visualFormat.Rmask = f->Rmask;
952 visualFormat.Gmask = f->Gmask;
953 visualFormat.Bmask = f->Bmask;
954 Screen_blitter_init(visualFormat, true, mac_depth_of_video_depth(VIDEO_MODE_DEPTH));
955
956 // Load gray ramp to 8->16/32 expand map
957 if (!IsDirectMode(mode))
958 for (int i=0; i<256; i++)
959 ExpandMap[i] = SDL_MapRGB(f, i, i, i);
960
961 // Set frame buffer base
962 set_mac_frame_buffer(monitor, VIDEO_MODE_DEPTH, true);
963
964 // Everything went well
965 init_ok = true;
966 }
967
968 // Close display
969 driver_fullscreen::~driver_fullscreen()
970 {
971 #ifdef ENABLE_VOSF
972 if (use_vosf)
973 the_host_buffer = NULL; // don't free() in driver_base dtor
974 #endif
975 if (s)
976 SDL_FreeSurface(s);
977
978 // Show cursor
979 SDL_ShowCursor(1);
980 }
981
982
983 /*
984 * Initialization
985 */
986
987 // Init keycode translation table
988 static void keycode_init(void)
989 {
990 bool use_kc = PrefsFindBool("keycodes");
991 if (use_kc) {
992
993 // Get keycode file path from preferences
994 const char *kc_path = PrefsFindString("keycodefile");
995
996 // Open keycode table
997 FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r");
998 if (f == NULL) {
999 char str[256];
1000 sprintf(str, GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno));
1001 WarningAlert(str);
1002 return;
1003 }
1004
1005 // Default translation table
1006 for (int i=0; i<256; i++)
1007 keycode_table[i] = -1;
1008
1009 // Search for server vendor string, then read keycodes
1010 char video_driver[256];
1011 SDL_VideoDriverName(video_driver, sizeof(video_driver));
1012 bool video_driver_found = false;
1013 char line[256];
1014 int n_keys = 0;
1015 while (fgets(line, sizeof(line) - 1, f)) {
1016 // Read line
1017 int len = strlen(line);
1018 if (len == 0)
1019 continue;
1020 line[len-1] = 0;
1021
1022 // Comments begin with "#" or ";"
1023 if (line[0] == '#' || line[0] == ';' || line[0] == 0)
1024 continue;
1025
1026 if (video_driver_found) {
1027 // Skip aliases as long as we have read keycodes yet
1028 // Otherwise, it's another mapping and we have to stop
1029 static const char sdl_str[] = "sdl";
1030 if (strncmp(line, sdl_str, sizeof(sdl_str) - 1) == 0 && n_keys == 0)
1031 continue;
1032
1033 // Read keycode
1034 int x_code, mac_code;
1035 if (sscanf(line, "%d %d", &x_code, &mac_code) == 2)
1036 keycode_table[x_code & 0xff] = mac_code, n_keys++;
1037 else
1038 break;
1039 } else {
1040 // Search for SDL video driver string
1041 static const char sdl_str[] = "sdl";
1042 if (strncmp(line, sdl_str, sizeof(sdl_str) - 1) == 0) {
1043 char *p = line + sizeof(sdl_str);
1044 if (strstr(video_driver, p) == video_driver)
1045 video_driver_found = true;
1046 }
1047 }
1048 }
1049
1050 // Keycode file completely read
1051 fclose(f);
1052 use_keycodes = video_driver_found;
1053
1054 // Vendor not found? Then display warning
1055 if (!video_driver_found) {
1056 char str[256];
1057 sprintf(str, GetString(STR_KEYCODE_VENDOR_WARN), video_driver, kc_path ? kc_path : KEYCODE_FILE_NAME);
1058 WarningAlert(str);
1059 return;
1060 }
1061
1062 D(bug("Using SDL/%s keycodes table, %d key mappings\n", video_driver, n_keys));
1063 }
1064 }
1065
1066 // Open display for current mode
1067 bool SDL_monitor_desc::video_open(void)
1068 {
1069 D(bug("video_open()\n"));
1070 const VIDEO_MODE &mode = get_current_mode();
1071 #if DEBUG
1072 D(bug("Current video mode:\n"));
1073 D(bug(" %dx%d (ID %02x), %d bpp\n", VIDEO_MODE_X, VIDEO_MODE_Y, VIDEO_MODE_RESOLUTION, 1 << (VIDEO_MODE_DEPTH & 0x0f)));
1074 #endif
1075
1076 // Create display driver object of requested type
1077 switch (display_type) {
1078 case DISPLAY_WINDOW:
1079 drv = new(std::nothrow) driver_window(*this);
1080 break;
1081 case DISPLAY_SCREEN:
1082 drv = new(std::nothrow) driver_fullscreen(*this);
1083 break;
1084 }
1085 if (drv == NULL)
1086 return false;
1087 if (!drv->init_ok) {
1088 delete drv;
1089 drv = NULL;
1090 return false;
1091 }
1092
1093 #ifdef WIN32
1094 // Chain in a new message handler for WM_DEVICECHANGE
1095 HWND the_window = GetMainWindowHandle();
1096 sdl_window_proc = (WNDPROC)GetWindowLongPtr(the_window, GWLP_WNDPROC);
1097 SetWindowLongPtr(the_window, GWLP_WNDPROC, (LONG_PTR)windows_message_handler);
1098 #endif
1099
1100 // Initialize VideoRefresh function
1101 VideoRefreshInit();
1102
1103 // Lock down frame buffer
1104 LOCK_FRAME_BUFFER;
1105
1106 // Start redraw/input thread
1107 #ifndef USE_CPU_EMUL_SERVICES
1108 redraw_thread_cancel = false;
1109 redraw_thread_active = ((redraw_thread = SDL_CreateThread(redraw_func, NULL)) != NULL);
1110 if (!redraw_thread_active) {
1111 printf("FATAL: cannot create redraw thread\n");
1112 return false;
1113 }
1114 #else
1115 redraw_thread_active = true;
1116 #endif
1117 return true;
1118 }
1119
1120 #ifdef SHEEPSHAVER
1121 bool VideoInit(void)
1122 {
1123 const bool classic = false;
1124 #else
1125 bool VideoInit(bool classic)
1126 {
1127 #endif
1128 classic_mode = classic;
1129
1130 #ifdef ENABLE_VOSF
1131 // Zero the mainBuffer structure
1132 mainBuffer.dirtyPages = NULL;
1133 mainBuffer.pageInfo = NULL;
1134 #endif
1135
1136 // Create Mutexes
1137 if ((sdl_events_lock = SDL_CreateMutex()) == NULL)
1138 return false;
1139 if ((sdl_palette_lock = SDL_CreateMutex()) == NULL)
1140 return false;
1141 if ((frame_buffer_lock = SDL_CreateMutex()) == NULL)
1142 return false;
1143
1144 // Init keycode translation
1145 keycode_init();
1146
1147 // Read prefs
1148 frame_skip = PrefsFindInt32("frameskip");
1149 mouse_wheel_mode = PrefsFindInt32("mousewheelmode");
1150 mouse_wheel_lines = PrefsFindInt32("mousewheellines");
1151
1152 // Get screen mode from preferences
1153 migrate_screen_prefs();
1154 const char *mode_str = NULL;
1155 if (classic_mode)
1156 mode_str = "win/512/342";
1157 else
1158 mode_str = PrefsFindString("screen");
1159
1160 // Determine display type and default dimensions
1161 int default_width, default_height;
1162 if (classic) {
1163 default_width = 512;
1164 default_height = 384;
1165 }
1166 else {
1167 default_width = 640;
1168 default_height = 480;
1169 }
1170 display_type = DISPLAY_WINDOW;
1171 if (mode_str) {
1172 if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2)
1173 display_type = DISPLAY_WINDOW;
1174 else if (sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2)
1175 display_type = DISPLAY_SCREEN;
1176 }
1177 if (default_width <= 0)
1178 default_width = sdl_display_width();
1179 else if (default_width > sdl_display_width())
1180 default_width = sdl_display_width();
1181 if (default_height <= 0)
1182 default_height = sdl_display_height();
1183 else if (default_height > sdl_display_height())
1184 default_height = sdl_display_height();
1185
1186 // Mac screen depth follows X depth
1187 screen_depth = SDL_GetVideoInfo()->vfmt->BitsPerPixel;
1188 int default_depth;
1189 switch (screen_depth) {
1190 case 8:
1191 default_depth = VIDEO_DEPTH_8BIT;
1192 break;
1193 case 15: case 16:
1194 default_depth = VIDEO_DEPTH_16BIT;
1195 break;
1196 case 24: case 32:
1197 default_depth = VIDEO_DEPTH_32BIT;
1198 break;
1199 default:
1200 default_depth = VIDEO_DEPTH_1BIT;
1201 break;
1202 }
1203
1204 // Initialize list of video modes to try
1205 struct {
1206 int w;
1207 int h;
1208 int resolution_id;
1209 }
1210 video_modes[] = {
1211 { -1, -1, 0x80 },
1212 { 512, 384, 0x80 },
1213 { 640, 480, 0x81 },
1214 { 800, 600, 0x82 },
1215 { 1024, 768, 0x83 },
1216 { 1152, 870, 0x84 },
1217 { 1280, 1024, 0x85 },
1218 { 1600, 1200, 0x86 },
1219 { 0, }
1220 };
1221 video_modes[0].w = default_width;
1222 video_modes[0].h = default_height;
1223
1224 // Construct list of supported modes
1225 if (display_type == DISPLAY_WINDOW) {
1226 if (classic)
1227 add_mode(display_type, 512, 342, 0x80, 64, VIDEO_DEPTH_1BIT);
1228 else {
1229 for (int i = 0; video_modes[i].w != 0; i++) {
1230 const int w = video_modes[i].w;
1231 const int h = video_modes[i].h;
1232 if (i > 0 && (w >= default_width || h >= default_height))
1233 continue;
1234 for (int d = VIDEO_DEPTH_1BIT; d <= default_depth; d++)
1235 add_mode(display_type, w, h, video_modes[i].resolution_id, TrivialBytesPerRow(w, (video_depth)d), d);
1236 }
1237 }
1238 } else if (display_type == DISPLAY_SCREEN) {
1239 for (int i = 0; video_modes[i].w != 0; i++) {
1240 const int w = video_modes[i].w;
1241 const int h = video_modes[i].h;
1242 if (i > 0 && (w >= default_width || h >= default_height))
1243 continue;
1244 if (w == 512 && h == 384)
1245 continue;
1246 for (int d = VIDEO_DEPTH_1BIT; d <= default_depth; d++)
1247 add_mode(display_type, w, h, video_modes[i].resolution_id, TrivialBytesPerRow(w, (video_depth)d), d);
1248 }
1249 }
1250
1251 if (VideoModes.empty()) {
1252 ErrorAlert(STR_NO_XVISUAL_ERR);
1253 return false;
1254 }
1255
1256 // Find requested default mode with specified dimensions
1257 uint32 default_id;
1258 std::vector<VIDEO_MODE>::const_iterator i, end = VideoModes.end();
1259 for (i = VideoModes.begin(); i != end; ++i) {
1260 const VIDEO_MODE & mode = (*i);
1261 if (VIDEO_MODE_X == default_width && VIDEO_MODE_Y == default_height && VIDEO_MODE_DEPTH == default_depth) {
1262 default_id = VIDEO_MODE_RESOLUTION;
1263 #ifdef SHEEPSHAVER
1264 std::vector<VIDEO_MODE>::const_iterator begin = VideoModes.begin();
1265 cur_mode = distance(begin, i);
1266 #endif
1267 break;
1268 }
1269 }
1270 if (i == end) { // not found, use first available mode
1271 const VIDEO_MODE & mode = VideoModes[0];
1272 default_depth = VIDEO_MODE_DEPTH;
1273 default_id = VIDEO_MODE_RESOLUTION;
1274 #ifdef SHEEPSHAVER
1275 cur_mode = 0;
1276 #endif
1277 }
1278
1279 #ifdef SHEEPSHAVER
1280 for (int i = 0; i < VideoModes.size(); i++)
1281 VModes[i] = VideoModes[i];
1282 VideoInfo *p = &VModes[VideoModes.size()];
1283 p->viType = DIS_INVALID; // End marker
1284 p->viRowBytes = 0;
1285 p->viXsize = p->viYsize = 0;
1286 p->viAppleMode = 0;
1287 p->viAppleID = 0;
1288 #endif
1289
1290 #if DEBUG
1291 D(bug("Available video modes:\n"));
1292 for (i = VideoModes.begin(); i != end; ++i) {
1293 const VIDEO_MODE & mode = (*i);
1294 int bits = 1 << VIDEO_MODE_DEPTH;
1295 if (bits == 16)
1296 bits = 15;
1297 else if (bits == 32)
1298 bits = 24;
1299 D(bug(" %dx%d (ID %02x), %d colors\n", VIDEO_MODE_X, VIDEO_MODE_Y, VIDEO_MODE_RESOLUTION, 1 << bits));
1300 }
1301 #endif
1302
1303 // Create SDL_monitor_desc for this (the only) display
1304 SDL_monitor_desc *monitor = new SDL_monitor_desc(VideoModes, (video_depth)default_depth, default_id);
1305 VideoMonitors.push_back(monitor);
1306
1307 // Open display
1308 return monitor->video_open();
1309 }
1310
1311
1312 /*
1313 * Deinitialization
1314 */
1315
1316 // Close display
1317 void SDL_monitor_desc::video_close(void)
1318 {
1319 D(bug("video_close()\n"));
1320
1321 #ifdef WIN32
1322 // Remove message handler for WM_DEVICECHANGE
1323 HWND the_window = GetMainWindowHandle();
1324 SetWindowLongPtr(the_window, GWLP_WNDPROC, (LONG_PTR)sdl_window_proc);
1325 #endif
1326
1327 // Stop redraw thread
1328 #ifndef USE_CPU_EMUL_SERVICES
1329 if (redraw_thread_active) {
1330 redraw_thread_cancel = true;
1331 SDL_WaitThread(redraw_thread, NULL);
1332 }
1333 #endif
1334 redraw_thread_active = false;
1335
1336 // Unlock frame buffer
1337 UNLOCK_FRAME_BUFFER;
1338 D(bug(" frame buffer unlocked\n"));
1339
1340 // Close display
1341 delete drv;
1342 drv = NULL;
1343 }
1344
1345 void VideoExit(void)
1346 {
1347 // Close displays
1348 vector<monitor_desc *>::iterator i, end = VideoMonitors.end();
1349 for (i = VideoMonitors.begin(); i != end; ++i)
1350 dynamic_cast<SDL_monitor_desc *>(*i)->video_close();
1351
1352 // Destroy locks
1353 if (frame_buffer_lock)
1354 SDL_DestroyMutex(frame_buffer_lock);
1355 if (sdl_palette_lock)
1356 SDL_DestroyMutex(sdl_palette_lock);
1357 if (sdl_events_lock)
1358 SDL_DestroyMutex(sdl_events_lock);
1359 }
1360
1361
1362 /*
1363 * Close down full-screen mode (if bringing up error alerts is unsafe while in full-screen mode)
1364 */
1365
1366 void VideoQuitFullScreen(void)
1367 {
1368 D(bug("VideoQuitFullScreen()\n"));
1369 quit_full_screen = true;
1370 }
1371
1372
1373 /*
1374 * Mac VBL interrupt
1375 */
1376
1377 /*
1378 * Execute video VBL routine
1379 */
1380
1381 #ifdef SHEEPSHAVER
1382 void VideoVBL(void)
1383 {
1384 // Emergency quit requested? Then quit
1385 if (emerg_quit)
1386 QuitEmulator();
1387
1388 // Temporarily give up frame buffer lock (this is the point where
1389 // we are suspended when the user presses Ctrl-Tab)
1390 UNLOCK_FRAME_BUFFER;
1391 LOCK_FRAME_BUFFER;
1392
1393 // Execute video VBL
1394 if (private_data != NULL && private_data->interruptsEnabled)
1395 VSLDoInterruptService(private_data->vslServiceID);
1396 }
1397 #else
1398 void VideoInterrupt(void)
1399 {
1400 // We must fill in the events queue in the same thread that did call SDL_SetVideoMode()
1401 SDL_PumpEvents();
1402
1403 // Emergency quit requested? Then quit
1404 if (emerg_quit)
1405 QuitEmulator();
1406
1407 // Temporarily give up frame buffer lock (this is the point where
1408 // we are suspended when the user presses Ctrl-Tab)
1409 UNLOCK_FRAME_BUFFER;
1410 LOCK_FRAME_BUFFER;
1411 }
1412 #endif
1413
1414
1415 /*
1416 * Set palette
1417 */
1418
1419 #ifdef SHEEPSHAVER
1420 void video_set_palette(void)
1421 {
1422 monitor_desc * monitor = VideoMonitors[0];
1423 int n_colors = palette_size(monitor->get_current_mode().viAppleMode);
1424 uint8 pal[256 * 3];
1425 for (int c = 0; c < n_colors; c++) {
1426 pal[c*3 + 0] = mac_pal[c].red;
1427 pal[c*3 + 1] = mac_pal[c].green;
1428 pal[c*3 + 2] = mac_pal[c].blue;
1429 }
1430 monitor->set_palette(pal, n_colors);
1431 }
1432 #endif
1433
1434 void SDL_monitor_desc::set_palette(uint8 *pal, int num_in)
1435 {
1436 const VIDEO_MODE &mode = get_current_mode();
1437
1438 // FIXME: how can we handle the gamma ramp?
1439 if ((int)VIDEO_MODE_DEPTH > VIDEO_DEPTH_8BIT)
1440 return;
1441
1442 LOCK_PALETTE;
1443
1444 // Convert colors to XColor array
1445 int num_out = 256;
1446 bool stretch = false;
1447 SDL_Color *p = sdl_palette;
1448 for (int i=0; i<num_out; i++) {
1449 int c = (stretch ? (i * num_in) / num_out : i);
1450 p->r = pal[c*3 + 0] * 0x0101;
1451 p->g = pal[c*3 + 1] * 0x0101;
1452 p->b = pal[c*3 + 2] * 0x0101;
1453 p++;
1454 }
1455
1456 // Recalculate pixel color expansion map
1457 if (!IsDirectMode(mode)) {
1458 for (int i=0; i<256; i++) {
1459 int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier)
1460 ExpandMap[i] = SDL_MapRGB(drv->s->format, pal[c*3+0], pal[c*3+1], pal[c*3+2]);
1461 }
1462
1463 #ifdef ENABLE_VOSF
1464 if (use_vosf) {
1465 // We have to redraw everything because the interpretation of pixel values changed
1466 LOCK_VOSF;
1467 PFLAG_SET_ALL;
1468 UNLOCK_VOSF;
1469 memset(the_buffer_copy, 0, VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y);
1470 }
1471 #endif
1472 }
1473
1474 // Tell redraw thread to change palette
1475 sdl_palette_changed = true;
1476
1477 UNLOCK_PALETTE;
1478 }
1479
1480
1481 /*
1482 * Switch video mode
1483 */
1484
1485 #ifdef SHEEPSHAVER
1486 int16 video_mode_change(VidLocals *csSave, uint32 ParamPtr)
1487 {
1488 /* return if no mode change */
1489 if ((csSave->saveData == ReadMacInt32(ParamPtr + csData)) &&
1490 (csSave->saveMode == ReadMacInt16(ParamPtr + csMode))) return noErr;
1491
1492 /* first find video mode in table */
1493 for (int i=0; VModes[i].viType != DIS_INVALID; i++) {
1494 if ((ReadMacInt16(ParamPtr + csMode) == VModes[i].viAppleMode) &&
1495 (ReadMacInt32(ParamPtr + csData) == VModes[i].viAppleID)) {
1496 csSave->saveMode = ReadMacInt16(ParamPtr + csMode);
1497 csSave->saveData = ReadMacInt32(ParamPtr + csData);
1498 csSave->savePage = ReadMacInt16(ParamPtr + csPage);
1499
1500 // Disable interrupts and pause redraw thread
1501 DisableInterrupt();
1502 thread_stop_ack = false;
1503 thread_stop_req = true;
1504 while (!thread_stop_ack) ;
1505
1506 cur_mode = i;
1507 monitor_desc *monitor = VideoMonitors[0];
1508 monitor->switch_to_current_mode();
1509
1510 WriteMacInt32(ParamPtr + csBaseAddr, screen_base);
1511 csSave->saveBaseAddr=screen_base;
1512 csSave->saveData=VModes[cur_mode].viAppleID;/* First mode ... */
1513 csSave->saveMode=VModes[cur_mode].viAppleMode;
1514
1515 // Enable interrupts and resume redraw thread
1516 thread_stop_req = false;
1517 EnableInterrupt();
1518 return noErr;
1519 }
1520 }
1521 return paramErr;
1522 }
1523 #endif
1524
1525 void SDL_monitor_desc::switch_to_current_mode(void)
1526 {
1527 // Close and reopen display
1528 LOCK_EVENTS;
1529 video_close();
1530 video_open();
1531 UNLOCK_EVENTS;
1532
1533 if (drv == NULL) {
1534 ErrorAlert(STR_OPEN_WINDOW_ERR);
1535 QuitEmulator();
1536 }
1537 }
1538
1539
1540 /*
1541 * Can we set the MacOS cursor image into the window?
1542 */
1543
1544 #ifdef SHEEPSHAVER
1545 bool video_can_change_cursor(void)
1546 {
1547 static char driver[] = "Quartz?";
1548 static int quartzok = -1;
1549
1550 if (display_type != DISPLAY_WINDOW)
1551 return false;
1552
1553 if (quartzok < 0) {
1554 if (SDL_VideoDriverName(driver, sizeof driver) == NULL || strncmp(driver, "Quartz", sizeof driver))
1555 quartzok = true;
1556 else {
1557 // Quartz driver bug prevents cursor changing in SDL 1.2.11 and later
1558 const SDL_version *vp = SDL_Linked_Version();
1559 quartzok = SDL_VERSIONNUM(vp->major, vp->minor, vp->patch) <= SDL_VERSIONNUM(1, 2, 10);
1560 }
1561 }
1562
1563 return quartzok;
1564 }
1565 #endif
1566
1567
1568 /*
1569 * Set cursor image for window
1570 */
1571
1572 #ifdef SHEEPSHAVER
1573 void video_set_cursor(void)
1574 {
1575 cursor_changed = true;
1576 }
1577 #endif
1578
1579
1580 /*
1581 * Keyboard-related utilify functions
1582 */
1583
1584 static bool is_modifier_key(SDL_KeyboardEvent const & e)
1585 {
1586 switch (e.keysym.sym) {
1587 case SDLK_NUMLOCK:
1588 case SDLK_CAPSLOCK:
1589 case SDLK_SCROLLOCK:
1590 case SDLK_RSHIFT:
1591 case SDLK_LSHIFT:
1592 case SDLK_RCTRL:
1593 case SDLK_LCTRL:
1594 case SDLK_RALT:
1595 case SDLK_LALT:
1596 case SDLK_RMETA:
1597 case SDLK_LMETA:
1598 case SDLK_LSUPER:
1599 case SDLK_RSUPER:
1600 case SDLK_MODE:
1601 case SDLK_COMPOSE:
1602 return true;
1603 }
1604 return false;
1605 }
1606
1607 static bool is_ctrl_down(SDL_keysym const & ks)
1608 {
1609 return ctrl_down || (ks.mod & KMOD_CTRL);
1610 }
1611
1612
1613 /*
1614 * Translate key event to Mac keycode, returns -1 if no keycode was found
1615 * and -2 if the key was recognized as a hotkey
1616 */
1617
1618 static int kc_decode(SDL_keysym const & ks, bool key_down)
1619 {
1620 switch (ks.sym) {
1621 case SDLK_a: return 0x00;
1622 case SDLK_b: return 0x0b;
1623 case SDLK_c: return 0x08;
1624 case SDLK_d: return 0x02;
1625 case SDLK_e: return 0x0e;
1626 case SDLK_f: return 0x03;
1627 case SDLK_g: return 0x05;
1628 case SDLK_h: return 0x04;
1629 case SDLK_i: return 0x22;
1630 case SDLK_j: return 0x26;
1631 case SDLK_k: return 0x28;
1632 case SDLK_l: return 0x25;
1633 case SDLK_m: return 0x2e;
1634 case SDLK_n: return 0x2d;
1635 case SDLK_o: return 0x1f;
1636 case SDLK_p: return 0x23;
1637 case SDLK_q: return 0x0c;
1638 case SDLK_r: return 0x0f;
1639 case SDLK_s: return 0x01;
1640 case SDLK_t: return 0x11;
1641 case SDLK_u: return 0x20;
1642 case SDLK_v: return 0x09;
1643 case SDLK_w: return 0x0d;
1644 case SDLK_x: return 0x07;
1645 case SDLK_y: return 0x10;
1646 case SDLK_z: return 0x06;
1647
1648 case SDLK_1: case SDLK_EXCLAIM: return 0x12;
1649 case SDLK_2: case SDLK_AT: return 0x13;
1650 case SDLK_3: case SDLK_HASH: return 0x14;
1651 case SDLK_4: case SDLK_DOLLAR: return 0x15;
1652 case SDLK_5: return 0x17;
1653 case SDLK_6: return 0x16;
1654 case SDLK_7: return 0x1a;
1655 case SDLK_8: return 0x1c;
1656 case SDLK_9: return 0x19;
1657 case SDLK_0: return 0x1d;
1658
1659 case SDLK_BACKQUOTE: return 0x0a;
1660 case SDLK_MINUS: case SDLK_UNDERSCORE: return 0x1b;
1661 case SDLK_EQUALS: case SDLK_PLUS: return 0x18;
1662 case SDLK_LEFTBRACKET: return 0x21;
1663 case SDLK_RIGHTBRACKET: return 0x1e;
1664 case SDLK_BACKSLASH: return 0x2a;
1665 case SDLK_SEMICOLON: case SDLK_COLON: return 0x29;
1666 case SDLK_QUOTE: case SDLK_QUOTEDBL: return 0x27;
1667 case SDLK_COMMA: case SDLK_LESS: return 0x2b;
1668 case SDLK_PERIOD: case SDLK_GREATER: return 0x2f;
1669 case SDLK_SLASH: case SDLK_QUESTION: return 0x2c;
1670
1671 case SDLK_TAB: if (is_ctrl_down(ks)) {if (!key_down) drv->suspend(); return -2;} else return 0x30;
1672 case SDLK_RETURN: return 0x24;
1673 case SDLK_SPACE: return 0x31;
1674 case SDLK_BACKSPACE: return 0x33;
1675
1676 case SDLK_DELETE: return 0x75;
1677 case SDLK_INSERT: return 0x72;
1678 case SDLK_HOME: case SDLK_HELP: return 0x73;
1679 case SDLK_END: return 0x77;
1680 case SDLK_PAGEUP: return 0x74;
1681 case SDLK_PAGEDOWN: return 0x79;
1682
1683 case SDLK_LCTRL: return 0x36;
1684 case SDLK_RCTRL: return 0x36;
1685 case SDLK_LSHIFT: return 0x38;
1686 case SDLK_RSHIFT: return 0x38;
1687 #if (defined(__APPLE__) && defined(__MACH__))
1688 case SDLK_LALT: return 0x3a;
1689 case SDLK_RALT: return 0x3a;
1690 case SDLK_LMETA: return 0x37;
1691 case SDLK_RMETA: return 0x37;
1692 #else
1693 case SDLK_LALT: return 0x37;
1694 case SDLK_RALT: return 0x37;
1695 case SDLK_LMETA: return 0x3a;
1696 case SDLK_RMETA: return 0x3a;
1697 #endif
1698 case SDLK_LSUPER: return 0x3a; // "Windows" key
1699 case SDLK_RSUPER: return 0x3a;
1700 case SDLK_MENU: return 0x32;
1701 case SDLK_CAPSLOCK: return 0x39;
1702 case SDLK_NUMLOCK: return 0x47;
1703
1704 case SDLK_UP: return 0x3e;
1705 case SDLK_DOWN: return 0x3d;
1706 case SDLK_LEFT: return 0x3b;
1707 case SDLK_RIGHT: return 0x3c;
1708
1709 case SDLK_ESCAPE: if (is_ctrl_down(ks)) {if (!key_down) { quit_full_screen = true; emerg_quit = true; } return -2;} else return 0x35;
1710
1711 case SDLK_F1: if (is_ctrl_down(ks)) {if (!key_down) SysMountFirstFloppy(); return -2;} else return 0x7a;
1712 case SDLK_F2: return 0x78;
1713 case SDLK_F3: return 0x63;
1714 case SDLK_F4: return 0x76;
1715 case SDLK_F5: if (is_ctrl_down(ks)) {if (!key_down) drv->toggle_mouse_grab(); return -2;} else return 0x60;
1716 case SDLK_F6: return 0x61;
1717 case SDLK_F7: return 0x62;
1718 case SDLK_F8: return 0x64;
1719 case SDLK_F9: return 0x65;
1720 case SDLK_F10: return 0x6d;
1721 case SDLK_F11: return 0x67;
1722 case SDLK_F12: return 0x6f;
1723
1724 case SDLK_PRINT: return 0x69;
1725 case SDLK_SCROLLOCK: return 0x6b;
1726 case SDLK_PAUSE: return 0x71;
1727
1728 case SDLK_KP0: return 0x52;
1729 case SDLK_KP1: return 0x53;
1730 case SDLK_KP2: return 0x54;
1731 case SDLK_KP3: return 0x55;
1732 case SDLK_KP4: return 0x56;
1733 case SDLK_KP5: return 0x57;
1734 case SDLK_KP6: return 0x58;
1735 case SDLK_KP7: return 0x59;
1736 case SDLK_KP8: return 0x5b;
1737 case SDLK_KP9: return 0x5c;
1738 case SDLK_KP_PERIOD: return 0x41;
1739 case SDLK_KP_PLUS: return 0x45;
1740 case SDLK_KP_MINUS: return 0x4e;
1741 case SDLK_KP_MULTIPLY: return 0x43;
1742 case SDLK_KP_DIVIDE: return 0x4b;
1743 case SDLK_KP_ENTER: return 0x4c;
1744 case SDLK_KP_EQUALS: return 0x51;
1745 }
1746 D(bug("Unhandled SDL keysym: %d\n", ks.sym));
1747 return -1;
1748 }
1749
1750 static int event2keycode(SDL_KeyboardEvent const &ev, bool key_down)
1751 {
1752 return kc_decode(ev.keysym, key_down);
1753 }
1754
1755
1756 /*
1757 * SDL event handling
1758 */
1759
1760 static void handle_events(void)
1761 {
1762 SDL_Event events[10];
1763 const int n_max_events = sizeof(events) / sizeof(events[0]);
1764 int n_events;
1765
1766 while ((n_events = SDL_PeepEvents(events, n_max_events, SDL_GETEVENT, sdl_eventmask)) > 0) {
1767 for (int i = 0; i < n_events; i++) {
1768 SDL_Event const & event = events[i];
1769 switch (event.type) {
1770
1771 // Mouse button
1772 case SDL_MOUSEBUTTONDOWN: {
1773 unsigned int button = event.button.button;
1774 if (button == SDL_BUTTON_LEFT)
1775 ADBMouseDown(0);
1776 else if (button == SDL_BUTTON_RIGHT)
1777 ADBMouseDown(1);
1778 else if (button == SDL_BUTTON_MIDDLE)
1779 ADBMouseDown(2);
1780 else if (button < 6) { // Wheel mouse
1781 if (mouse_wheel_mode == 0) {
1782 int key = (button == 5) ? 0x79 : 0x74; // Page up/down
1783 ADBKeyDown(key);
1784 ADBKeyUp(key);
1785 } else {
1786 int key = (button == 5) ? 0x3d : 0x3e; // Cursor up/down
1787 for(int i=0; i<mouse_wheel_lines; i++) {
1788 ADBKeyDown(key);
1789 ADBKeyUp(key);
1790 }
1791 }
1792 }
1793 break;
1794 }
1795 case SDL_MOUSEBUTTONUP: {
1796 unsigned int button = event.button.button;
1797 if (button == SDL_BUTTON_LEFT)
1798 ADBMouseUp(0);
1799 else if (button == SDL_BUTTON_RIGHT)
1800 ADBMouseUp(1);
1801 else if (button == SDL_BUTTON_MIDDLE)
1802 ADBMouseUp(2);
1803 break;
1804 }
1805
1806 // Mouse moved
1807 case SDL_MOUSEMOTION:
1808 drv->mouse_moved(event.motion.x, event.motion.y);
1809 break;
1810
1811 // Keyboard
1812 case SDL_KEYDOWN: {
1813 int code = -1;
1814 if (use_keycodes && !is_modifier_key(event.key)) {
1815 if (event2keycode(event.key, true) != -2) // This is called to process the hotkeys
1816 code = keycode_table[event.key.keysym.scancode & 0xff];
1817 } else
1818 code = event2keycode(event.key, true);
1819 if (code >= 0) {
1820 if (!emul_suspended) {
1821 if (code == 0x39) { // Caps Lock pressed
1822 if (caps_on) {
1823 ADBKeyUp(code);
1824 caps_on = false;
1825 } else {
1826 ADBKeyDown(code);
1827 caps_on = true;
1828 }
1829 } else
1830 ADBKeyDown(code);
1831 if (code == 0x36)
1832 ctrl_down = true;
1833 } else {
1834 if (code == 0x31)
1835 drv->resume(); // Space wakes us up
1836 }
1837 }
1838 break;
1839 }
1840 case SDL_KEYUP: {
1841 int code = -1;
1842 if (use_keycodes && !is_modifier_key(event.key)) {
1843 if (event2keycode(event.key, false) != -2) // This is called to process the hotkeys
1844 code = keycode_table[event.key.keysym.scancode & 0xff];
1845 } else
1846 code = event2keycode(event.key, false);
1847 if (code >= 0) {
1848 if (code == 0x39) { // Caps Lock released
1849 if (caps_on) {
1850 ADBKeyUp(code);
1851 caps_on = false;
1852 } else {
1853 ADBKeyDown(code);
1854 caps_on = true;
1855 }
1856 } else
1857 ADBKeyUp(code);
1858 if (code == 0x36)
1859 ctrl_down = false;
1860 }
1861 break;
1862 }
1863
1864 // Hidden parts exposed, force complete refresh of window
1865 case SDL_VIDEOEXPOSE:
1866 if (display_type == DISPLAY_WINDOW) {
1867 const VIDEO_MODE &mode = VideoMonitors[0]->get_current_mode();
1868 #ifdef ENABLE_VOSF
1869 if (use_vosf) { // VOSF refresh
1870 LOCK_VOSF;
1871 PFLAG_SET_ALL;
1872 UNLOCK_VOSF;
1873 memset(the_buffer_copy, 0, VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y);
1874 }
1875 else
1876 #endif
1877 memset(the_buffer_copy, 0, VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y);
1878 }
1879 break;
1880
1881 // Window "close" widget clicked
1882 case SDL_QUIT:
1883 ADBKeyDown(0x7f); // Power key
1884 ADBKeyUp(0x7f);
1885 break;
1886
1887 // Application activate/deactivate; consume the event but otherwise ignore it
1888 case SDL_ACTIVEEVENT:
1889 break;
1890 }
1891 }
1892 }
1893 }
1894
1895
1896 /*
1897 * Window display update
1898 */
1899
1900 // Static display update (fixed frame rate, but incremental)
1901 static void update_display_static(driver_base *drv)
1902 {
1903 // Incremental update code
1904 int wide = 0, high = 0, x1, x2, y1, y2, i, j;
1905 const VIDEO_MODE &mode = drv->mode;
1906 int bytes_per_row = VIDEO_MODE_ROW_BYTES;
1907 uint8 *p, *p2;
1908
1909 // Check for first line from top and first line from bottom that have changed
1910 y1 = 0;
1911 for (j=0; j<VIDEO_MODE_Y; j++) {
1912 if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1913 y1 = j;
1914 break;
1915 }
1916 }
1917 y2 = y1 - 1;
1918 for (j=VIDEO_MODE_Y-1; j>=y1; j--) {
1919 if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) {
1920 y2 = j;
1921 break;
1922 }
1923 }
1924 high = y2 - y1 + 1;
1925
1926 // Check for first column from left and first column from right that have changed
1927 if (high) {
1928 if ((int)VIDEO_MODE_DEPTH < VIDEO_DEPTH_8BIT) {
1929 const int src_bytes_per_row = bytes_per_row;
1930 const int dst_bytes_per_row = drv->s->pitch;
1931 const int pixels_per_byte = VIDEO_MODE_X / src_bytes_per_row;
1932
1933 x1 = VIDEO_MODE_X / pixels_per_byte;
1934 for (j = y1; j <= y2; j++) {
1935 p = &the_buffer[j * bytes_per_row];
1936 p2 = &the_buffer_copy[j * bytes_per_row];
1937 for (i = 0; i < x1; i++) {
1938 if (*p != *p2) {
1939 x1 = i;
1940 break;
1941 }
1942 p++; p2++;
1943 }
1944 }
1945 x2 = x1;
1946 for (j = y1; j <= y2; j++) {
1947 p = &the_buffer[j * bytes_per_row];
1948 p2 = &the_buffer_copy[j * bytes_per_row];
1949 p += bytes_per_row;
1950 p2 += bytes_per_row;
1951 for (i = (VIDEO_MODE_X / pixels_per_byte); i > x2; i--) {
1952 p--; p2--;
1953 if (*p != *p2) {
1954 x2 = i;
1955 break;
1956 }
1957 }
1958 }
1959 x1 *= pixels_per_byte;
1960 x2 *= pixels_per_byte;
1961 wide = (x2 - x1 + pixels_per_byte - 1) & -pixels_per_byte;
1962
1963 // Update copy of the_buffer
1964 if (high && wide) {
1965
1966 // Lock surface, if required
1967 if (SDL_MUSTLOCK(drv->s))
1968 SDL_LockSurface(drv->s);
1969
1970 // Blit to screen surface
1971 int si = y1 * src_bytes_per_row + (x1 / pixels_per_byte);
1972 int di = y1 * dst_bytes_per_row + x1;
1973 for (j = y1; j <= y2; j++) {
1974 memcpy(the_buffer_copy + si, the_buffer + si, wide / pixels_per_byte);
1975 Screen_blit((uint8 *)drv->s->pixels + di, the_buffer + si, wide / pixels_per_byte);
1976 si += src_bytes_per_row;
1977 di += dst_bytes_per_row;
1978 }
1979
1980 // Unlock surface, if required
1981 if (SDL_MUSTLOCK(drv->s))
1982 SDL_UnlockSurface(drv->s);
1983
1984 // Refresh display
1985 SDL_UpdateRect(drv->s, x1, y1, wide, high);
1986 }
1987
1988 } else {
1989 const int bytes_per_pixel = VIDEO_MODE_ROW_BYTES / VIDEO_MODE_X;
1990 const int dst_bytes_per_row = drv->s->pitch;
1991
1992 x1 = VIDEO_MODE_X;
1993 for (j=y1; j<=y2; j++) {
1994 p = &the_buffer[j * bytes_per_row];
1995 p2 = &the_buffer_copy[j * bytes_per_row];
1996 for (i=0; i<x1*bytes_per_pixel; i++) {
1997 if (*p != *p2) {
1998 x1 = i / bytes_per_pixel;
1999 break;
2000 }
2001 p++; p2++;
2002 }
2003 }
2004 x2 = x1;
2005 for (j=y1; j<=y2; j++) {
2006 p = &the_buffer[j * bytes_per_row];
2007 p2 = &the_buffer_copy[j * bytes_per_row];
2008 p += bytes_per_row;
2009 p2 += bytes_per_row;
2010 for (i=VIDEO_MODE_X*bytes_per_pixel; i>x2*bytes_per_pixel; i--) {
2011 p--;
2012 p2--;
2013 if (*p != *p2) {
2014 x2 = i / bytes_per_pixel;
2015 break;
2016 }
2017 }
2018 }
2019 wide = x2 - x1;
2020
2021 // Update copy of the_buffer
2022 if (high && wide) {
2023
2024 // Lock surface, if required
2025 if (SDL_MUSTLOCK(drv->s))
2026 SDL_LockSurface(drv->s);
2027
2028 // Blit to screen surface
2029 for (j=y1; j<=y2; j++) {
2030 i = j * bytes_per_row + x1 * bytes_per_pixel;
2031 int dst_i = j * dst_bytes_per_row + x1 * bytes_per_pixel;
2032 memcpy(the_buffer_copy + i, the_buffer + i, bytes_per_pixel * wide);
2033 Screen_blit((uint8 *)drv->s->pixels + dst_i, the_buffer + i, bytes_per_pixel * wide);
2034 }
2035
2036 // Unlock surface, if required
2037 if (SDL_MUSTLOCK(drv->s))
2038 SDL_UnlockSurface(drv->s);
2039
2040 // Refresh display
2041 SDL_UpdateRect(drv->s, x1, y1, wide, high);
2042 }
2043 }
2044 }
2045 }
2046
2047 // Static display update (fixed frame rate, bounding boxes based)
2048 // XXX use NQD bounding boxes to help detect dirty areas?
2049 static void update_display_static_bbox(driver_base *drv)
2050 {
2051 const VIDEO_MODE &mode = drv->mode;
2052
2053 // Allocate bounding boxes for SDL_UpdateRects()
2054 const int N_PIXELS = 64;
2055 const int n_x_boxes = (VIDEO_MODE_X + N_PIXELS - 1) / N_PIXELS;
2056 const int n_y_boxes = (VIDEO_MODE_Y + N_PIXELS - 1) / N_PIXELS;
2057 SDL_Rect *boxes = (SDL_Rect *)alloca(sizeof(SDL_Rect) * n_x_boxes * n_y_boxes);
2058 int nr_boxes = 0;
2059
2060 // Lock surface, if required
2061 if (SDL_MUSTLOCK(drv->s))
2062 SDL_LockSurface(drv->s);
2063
2064 // Update the surface from Mac screen
2065 const int bytes_per_row = VIDEO_MODE_ROW_BYTES;
2066 const int bytes_per_pixel = bytes_per_row / VIDEO_MODE_X;
2067 const int dst_bytes_per_row = drv->s->pitch;
2068 int x, y;
2069 for (y = 0; y < VIDEO_MODE_Y; y += N_PIXELS) {
2070 int h = N_PIXELS;
2071 if (h > VIDEO_MODE_Y - y)
2072 h = VIDEO_MODE_Y - y;
2073 for (x = 0; x < VIDEO_MODE_X; x += N_PIXELS) {
2074 int w = N_PIXELS;
2075 if (w > VIDEO_MODE_X - x)
2076 w = VIDEO_MODE_X - x;
2077 const int xs = w * bytes_per_pixel;
2078 const int xb = x * bytes_per_pixel;
2079 bool dirty = false;
2080 for (int j = y; j < (y + h); j++) {
2081 const int yb = j * bytes_per_row;
2082 const int dst_yb = j * dst_bytes_per_row;
2083 if (memcmp(&the_buffer[yb + xb], &the_buffer_copy[yb + xb], xs) != 0) {
2084 memcpy(&the_buffer_copy[yb + xb], &the_buffer[yb + xb], xs);
2085 Screen_blit((uint8 *)drv->s->pixels + dst_yb + xb, the_buffer + yb + xb, xs);
2086 dirty = true;
2087 }
2088 }
2089 if (dirty) {
2090 boxes[nr_boxes].x = x;
2091 boxes[nr_boxes].y = y;
2092 boxes[nr_boxes].w = w;
2093 boxes[nr_boxes].h = h;
2094 nr_boxes++;
2095 }
2096 }
2097 }
2098
2099 // Unlock surface, if required
2100 if (SDL_MUSTLOCK(drv->s))
2101 SDL_UnlockSurface(drv->s);
2102
2103 // Refresh display
2104 if (nr_boxes)
2105 SDL_UpdateRects(drv->s, nr_boxes, boxes);
2106 }
2107
2108
2109 // We suggest the compiler to inline the next two functions so that it
2110 // may specialise the code according to the current screen depth and
2111 // display type. A clever compiler would do that job by itself though...
2112
2113 // NOTE: update_display_vosf is inlined too
2114
2115 static inline void possibly_quit_dga_mode()
2116 {
2117 // Quit DGA mode if requested (something terrible has happened and we
2118 // want to give control back to the user)
2119 if (quit_full_screen) {
2120 quit_full_screen = false;
2121 delete drv;
2122 drv = NULL;
2123 }
2124 }
2125
2126 static inline void possibly_ungrab_mouse()
2127 {
2128 // Ungrab mouse if requested (something terrible has happened and we
2129 // want to give control back to the user)
2130 if (quit_full_screen) {
2131 quit_full_screen = false;
2132 if (drv)
2133 drv->ungrab_mouse();
2134 }
2135 }
2136
2137 static inline void handle_palette_changes(void)
2138 {
2139 LOCK_PALETTE;
2140
2141 if (sdl_palette_changed) {
2142 sdl_palette_changed = false;
2143 drv->update_palette();
2144 }
2145
2146 UNLOCK_PALETTE;
2147 }
2148
2149 static void video_refresh_window_static(void);
2150
2151 static void video_refresh_dga(void)
2152 {
2153 // Quit DGA mode if requested
2154 possibly_quit_dga_mode();
2155 video_refresh_window_static();
2156 }
2157
2158 #ifdef ENABLE_VOSF
2159 #if REAL_ADDRESSING || DIRECT_ADDRESSING
2160 static void video_refresh_dga_vosf(void)
2161 {
2162 // Quit DGA mode if requested
2163 possibly_quit_dga_mode();
2164
2165 // Update display (VOSF variant)
2166 static int tick_counter = 0;
2167 if (++tick_counter >= frame_skip) {
2168 tick_counter = 0;
2169 if (mainBuffer.dirty) {
2170 LOCK_VOSF;
2171 update_display_dga_vosf(static_cast<driver_fullscreen *>(drv));
2172 UNLOCK_VOSF;
2173 }
2174 }
2175 }
2176 #endif
2177
2178 static void video_refresh_window_vosf(void)
2179 {
2180 // Ungrab mouse if requested
2181 possibly_ungrab_mouse();
2182
2183 // Update display (VOSF variant)
2184 static int tick_counter = 0;
2185 if (++tick_counter >= frame_skip) {
2186 tick_counter = 0;
2187 if (mainBuffer.dirty) {
2188 LOCK_VOSF;
2189 update_display_window_vosf(static_cast<driver_window *>(drv));
2190 UNLOCK_VOSF;
2191 }
2192 }
2193 }
2194 #endif // def ENABLE_VOSF
2195
2196 static void video_refresh_window_static(void)
2197 {
2198 // Ungrab mouse if requested
2199 possibly_ungrab_mouse();
2200
2201 // Update display (static variant)
2202 static int tick_counter = 0;
2203 if (++tick_counter >= frame_skip) {
2204 tick_counter = 0;
2205 const VIDEO_MODE &mode = drv->mode;
2206 if ((int)VIDEO_MODE_DEPTH >= VIDEO_DEPTH_8BIT)
2207 update_display_static_bbox(drv);
2208 else
2209 update_display_static(drv);
2210 }
2211 }
2212
2213
2214 /*
2215 * Thread for screen refresh, input handling etc.
2216 */
2217
2218 static void VideoRefreshInit(void)
2219 {
2220 // TODO: set up specialised 8bpp VideoRefresh handlers ?
2221 if (display_type == DISPLAY_SCREEN) {
2222 #if ENABLE_VOSF && (REAL_ADDRESSING || DIRECT_ADDRESSING)
2223 if (use_vosf)
2224 video_refresh = video_refresh_dga_vosf;
2225 else
2226 #endif
2227 video_refresh = video_refresh_dga;
2228 }
2229 else {
2230 #ifdef ENABLE_VOSF
2231 if (use_vosf)
2232 video_refresh = video_refresh_window_vosf;
2233 else
2234 #endif
2235 video_refresh = video_refresh_window_static;
2236 }
2237 }
2238
2239 static inline void do_video_refresh(void)
2240 {
2241 // Handle SDL events
2242 handle_events();
2243
2244 // Update display
2245 #if (defined(__APPLE__) && defined(__MACH__))
2246 // SDL expects an auto-release pool to be present.
2247 NSAutoReleasePool_wrap(video_refresh);
2248 #else
2249 video_refresh();
2250 #endif
2251
2252 #ifdef SHEEPSHAVER
2253 // Set new cursor image if it was changed
2254 if (cursor_changed && sdl_cursor) {
2255 cursor_changed = false;
2256 LOCK_EVENTS;
2257 SDL_FreeCursor(sdl_cursor);
2258 sdl_cursor = SDL_CreateCursor(MacCursor + 4, MacCursor + 36, 16, 16, MacCursor[2], MacCursor[3]);
2259 if (sdl_cursor) {
2260 SDL_ShowCursor(private_data == NULL || private_data->cursorVisible);
2261 SDL_SetCursor(sdl_cursor);
2262 #ifdef WIN32
2263 // XXX Windows apparently needs an extra mouse event to
2264 // make the new cursor image visible
2265 int visible = SDL_ShowCursor(-1);
2266 if (visible) {
2267 int x, y;
2268 SDL_GetMouseState(&x, &y);
2269 SDL_WarpMouse(x, y);
2270 }
2271 #endif
2272 }
2273 UNLOCK_EVENTS;
2274 }
2275 #endif
2276
2277 // Set new palette if it was changed
2278 handle_palette_changes();
2279 }
2280
2281 // This function is called on non-threaded platforms from a timer interrupt
2282 void VideoRefresh(void)
2283 {
2284 // We need to check redraw_thread_active to inhibit refreshed during
2285 // mode changes on non-threaded platforms
2286 if (!redraw_thread_active)
2287 return;
2288
2289 // Process pending events and update display
2290 do_video_refresh();
2291 }
2292
2293 const int VIDEO_REFRESH_HZ = 60;
2294 const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ;
2295
2296 #ifndef USE_CPU_EMUL_SERVICES
2297 static int redraw_func(void *arg)
2298 {
2299 uint64 start = GetTicks_usec();
2300 int64 ticks = 0;
2301 uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY;
2302
2303 while (!redraw_thread_cancel) {
2304
2305 // Wait
2306 next += VIDEO_REFRESH_DELAY;
2307 int64 delay = next - GetTicks_usec();
2308 if (delay > 0)
2309 Delay_usec(delay);
2310 else if (delay < -VIDEO_REFRESH_DELAY)
2311 next = GetTicks_usec();
2312 ticks++;
2313
2314 #ifdef SHEEPSHAVER
2315 // Pause if requested (during video mode switches)
2316 if (thread_stop_req) {
2317 thread_stop_ack = true;
2318 continue;
2319 }
2320 #endif
2321
2322 // Process pending events and update display
2323 do_video_refresh();
2324 }
2325
2326 uint64 end = GetTicks_usec();
2327 D(bug("%lld refreshes in %lld usec = %f refreshes/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
2328 return 0;
2329 }
2330 #endif
2331
2332
2333 /*
2334 * Record dirty area from NQD
2335 */
2336
2337 #ifdef SHEEPSHAVER
2338 void video_set_dirty_area(int x, int y, int w, int h)
2339 {
2340 #ifdef ENABLE_VOSF
2341 const VIDEO_MODE &mode = drv->mode;
2342 const int screen_width = VIDEO_MODE_X;
2343 const int screen_height = VIDEO_MODE_Y;
2344 const int bytes_per_row = VIDEO_MODE_ROW_BYTES;
2345
2346 if (use_vosf) {
2347 vosf_set_dirty_area(x, y, w, h, screen_width, screen_height, bytes_per_row);
2348 return;
2349 }
2350 #endif
2351
2352 // XXX handle dirty bounding boxes for non-VOSF modes
2353 }
2354 #endif