ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/SDL/video_sdl.cpp
Revision: 1.13
Committed: 2004-11-28T19:31:11Z (19 years, 7 months ago) by gbeauche
Branch: MAIN
Changes since 1.12: +53 -21 lines
Log Message:
Always use vm_acquire* to allocate frame buffers, so that cygwin/x86 version
can have a chance in case VOSF is not profitable (on video mode switches)
Improve video mode switches in SheepShaver/SDL, aka avoid crashes on win32
as there is apparently no thread canceleation algorithm used in SDL/win32.

File Contents

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