diff --git a/BasiliskII/src/SDL/video_sdl.cpp b/BasiliskII/src/SDL/video_sdl.cpp index ce2c9ae1..798ed8e8 100755 --- a/BasiliskII/src/SDL/video_sdl.cpp +++ b/BasiliskII/src/SDL/video_sdl.cpp @@ -198,12 +198,12 @@ static void *vm_acquire_framebuffer(uint32 size) // always try to reallocate framebuffer at the same address static void *fb = VM_MAP_FAILED; if (fb != VM_MAP_FAILED) { -// if (vm_acquire_fixed(fb, size) < 0) { + if (vm_acquire_fixed(fb, size) < 0) { #ifndef SHEEPSHAVER printf("FATAL: Could not reallocate framebuffer at previous address\n"); #endif fb = VM_MAP_FAILED; -// } + } } if (fb == VM_MAP_FAILED) fb = vm_acquire(size, VM_MAP_DEFAULT | VM_MAP_32BIT); diff --git a/BasiliskII/src/Unix/Darwin/lowmem.c b/BasiliskII/src/Unix/Darwin/lowmem.c index a40a3661..9d676d2f 100755 --- a/BasiliskII/src/Unix/Darwin/lowmem.c +++ b/BasiliskII/src/Unix/Darwin/lowmem.c @@ -107,8 +107,8 @@ void pagezero_64(struct mach_header_64 *machhead) exit(1); } /* change the permissions */ -// sc_cmd->maxprot = target_uint32(VM_PROT_ALL); -// sc_cmd->initprot = target_uint32(VM_PROT_ALL); + sc_cmd->maxprot = target_uint32(VM_PROT_ALL); + sc_cmd->initprot = target_uint32(VM_PROT_ALL); } #endif diff --git a/SheepShaver/src/MacOSX/SheepShaver_Xcode8.xcodeproj/project.pbxproj b/SheepShaver/src/MacOSX/SheepShaver_Xcode8.xcodeproj/project.pbxproj index 5153cda4..c07d55ff 100755 --- a/SheepShaver/src/MacOSX/SheepShaver_Xcode8.xcodeproj/project.pbxproj +++ b/SheepShaver/src/MacOSX/SheepShaver_Xcode8.xcodeproj/project.pbxproj @@ -16,7 +16,6 @@ 08163339158C121000C449F9 /* dis-asm.h in Headers */ = {isa = PBXBuildFile; fileRef = 08163337158C121000C449F9 /* dis-asm.h */; }; 08163340158C125800C449F9 /* ppc-dis.c in Sources */ = {isa = PBXBuildFile; fileRef = 08163338158C121000C449F9 /* ppc-dis.c */; }; 082AC22D14AA52E900071F5E /* prefs_editor_dummy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 082AC22C14AA52E900071F5E /* prefs_editor_dummy.cpp */; }; - 082AC26214AA59F000071F5E /* lowmem.c in Sources */ = {isa = PBXBuildFile; fileRef = 082AC26114AA59F000071F5E /* lowmem.c */; }; 083E370C16EFE85000CCCA59 /* disk_sparsebundle.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 083E370A16EFE85000CCCA59 /* disk_sparsebundle.cpp */; }; 083E372216EFE87200CCCA59 /* tinyxml2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 083E372016EFE87200CCCA59 /* tinyxml2.cpp */; }; 0846E4B114B1264700574779 /* ieeefp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0856CDF714A99EEF000B1711 /* ieeefp.cpp */; }; @@ -106,6 +105,7 @@ 08CD42E814B7B8AA009CA2A2 /* Carbon.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 08CD42E714B7B8AA009CA2A2 /* Carbon.framework */; }; 08E877521E0640E800A90A2C /* clip_macosx.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0856CE2C14A99EF0000B1711 /* clip_macosx.cpp */; }; A7B1921418C35D4700791D8D /* DiskType.m in Sources */ = {isa = PBXBuildFile; fileRef = A7B1921318C35D4700791D8D /* DiskType.m */; }; + E4302EE31FBFE7FA00A5B500 /* lowmem.c in Sources */ = {isa = PBXBuildFile; fileRef = E4302EE21FBFE7FA00A5B500 /* lowmem.c */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -151,7 +151,6 @@ 08163338158C121000C449F9 /* ppc-dis.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = "ppc-dis.c"; sourceTree = ""; }; 082AC22C14AA52E900071F5E /* prefs_editor_dummy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = prefs_editor_dummy.cpp; sourceTree = ""; }; 082AC25214AA59B600071F5E /* lowmem */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = lowmem; sourceTree = BUILT_PRODUCTS_DIR; }; - 082AC26114AA59F000071F5E /* lowmem.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = lowmem.c; path = ../../../BasiliskII/src/Unix/Darwin/lowmem.c; sourceTree = SOURCE_ROOT; }; 083E370A16EFE85000CCCA59 /* disk_sparsebundle.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = disk_sparsebundle.cpp; path = ../Unix/disk_sparsebundle.cpp; sourceTree = SOURCE_ROOT; }; 083E370B16EFE85000CCCA59 /* disk_unix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = disk_unix.h; path = ../Unix/disk_unix.h; sourceTree = SOURCE_ROOT; }; 083E372016EFE87200CCCA59 /* tinyxml2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = tinyxml2.cpp; path = ../Unix/tinyxml2.cpp; sourceTree = SOURCE_ROOT; }; @@ -379,6 +378,7 @@ 08D93A15159FE174003B04EC /* clip_macosx64.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = clip_macosx64.mm; sourceTree = ""; }; A7B1921218C35D4700791D8D /* DiskType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DiskType.h; sourceTree = ""; }; A7B1921318C35D4700791D8D /* DiskType.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DiskType.m; sourceTree = ""; }; + E4302EE21FBFE7FA00A5B500 /* lowmem.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = lowmem.c; path = Darwin/lowmem.c; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -427,7 +427,7 @@ 082AC25614AA59DA00071F5E /* Darwin */ = { isa = PBXGroup; children = ( - 082AC26114AA59F000071F5E /* lowmem.c */, + E4302EE21FBFE7FA00A5B500 /* lowmem.c */, ); name = Darwin; sourceTree = ""; @@ -1046,7 +1046,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 082AC26214AA59F000071F5E /* lowmem.c in Sources */, + E4302EE31FBFE7FA00A5B500 /* lowmem.c in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/SheepShaver/src/SDL/SDLMain.h b/SheepShaver/src/SDL/SDLMain.h new file mode 100644 index 00000000..c56d90cb --- /dev/null +++ b/SheepShaver/src/SDL/SDLMain.h @@ -0,0 +1,16 @@ +/* SDLMain.m - main entry point for our Cocoa-ized SDL app + Initial Version: Darrell Walisser + Non-NIB-Code & other changes: Max Horn + + Feel free to customize this file to suit your needs +*/ + +#ifndef _SDLMain_h_ +#define _SDLMain_h_ + +#import + +@interface SDLMain : NSObject +@end + +#endif /* _SDLMain_h_ */ diff --git a/SheepShaver/src/SDL/SDLMain.m b/SheepShaver/src/SDL/SDLMain.m new file mode 100644 index 00000000..0f23664d --- /dev/null +++ b/SheepShaver/src/SDL/SDLMain.m @@ -0,0 +1,381 @@ +/* SDLMain.m - main entry point for our Cocoa-ized SDL app + Initial Version: Darrell Walisser + Non-NIB-Code & other changes: Max Horn + + Feel free to customize this file to suit your needs +*/ + +#include "SDL.h" +#include "SDLMain.h" +#include /* for MAXPATHLEN */ +#include + +/* For some reaon, Apple removed setAppleMenu from the headers in 10.4, + but the method still is there and works. To avoid warnings, we declare + it ourselves here. */ +@interface NSApplication(SDL_Missing_Methods) +- (void)setAppleMenu:(NSMenu *)menu; +@end + +/* Use this flag to determine whether we use SDLMain.nib or not */ +#define SDL_USE_NIB_FILE 0 + +/* Use this flag to determine whether we use CPS (docking) or not */ +#define SDL_USE_CPS 1 +#ifdef SDL_USE_CPS +/* Portions of CPS.h */ +typedef struct CPSProcessSerNum +{ + UInt32 lo; + UInt32 hi; +} CPSProcessSerNum; + +extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); +extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); +extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); + +#endif /* SDL_USE_CPS */ + +static int gArgc; +static char **gArgv; +static BOOL gFinderLaunch; +static BOOL gCalledAppMainline = FALSE; + +static NSString *getApplicationName(void) +{ + const NSDictionary *dict; + NSString *appName = 0; + + /* Determine the application name */ + dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); + if (dict) + appName = [dict objectForKey: @"CFBundleName"]; + + if (![appName length]) + appName = [[NSProcessInfo processInfo] processName]; + + return appName; +} + +#if SDL_USE_NIB_FILE +/* A helper category for NSString */ +@interface NSString (ReplaceSubString) +- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString; +@end +#endif + +@interface NSApplication (SDLApplication) +@end + +@implementation NSApplication (SDLApplication) +/* Invoked from the Quit menu item */ +- (void)terminate:(id)sender +{ + /* Post a SDL_QUIT event */ + SDL_Event event; + event.type = SDL_QUIT; + SDL_PushEvent(&event); +} +@end + +/* The main class of the application, the application's delegate */ +@implementation SDLMain + +/* Set the working directory to the .app's parent directory */ +- (void) setupWorkingDirectory:(BOOL)shouldChdir +{ + if (shouldChdir) + { + char parentdir[MAXPATHLEN]; + CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); + CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); + if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) { + chdir(parentdir); /* chdir to the binary app's parent */ + } + CFRelease(url); + CFRelease(url2); + } +} + +#if SDL_USE_NIB_FILE + +/* Fix menu to contain the real app name instead of "SDL App" */ +- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName +{ + NSRange aRange; + NSEnumerator *enumerator; + NSMenuItem *menuItem; + + aRange = [[aMenu title] rangeOfString:@"SDL App"]; + if (aRange.length != 0) + [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; + + enumerator = [[aMenu itemArray] objectEnumerator]; + while ((menuItem = [enumerator nextObject])) + { + aRange = [[menuItem title] rangeOfString:@"SDL App"]; + if (aRange.length != 0) + [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; + if ([menuItem hasSubmenu]) + [self fixMenu:[menuItem submenu] withAppName:appName]; + } +} + +#else + +static void setApplicationMenu(void) +{ + /* warning: this code is very odd */ + NSMenu *appleMenu; + NSMenuItem *menuItem; + NSString *title; + NSString *appName; + + appName = getApplicationName(); + appleMenu = [[NSMenu alloc] initWithTitle:@""]; + + /* Add menu items */ + title = [@"About " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; + + [appleMenu addItem:[NSMenuItem separatorItem]]; + + title = [@"Hide " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; + + menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; + [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; + + [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; + + [appleMenu addItem:[NSMenuItem separatorItem]]; + + title = [@"Quit " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; + + + /* Put menu into the menubar */ + menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; + [menuItem setSubmenu:appleMenu]; + [[NSApp mainMenu] addItem:menuItem]; + + /* Tell the application object that this is now the application menu */ + [NSApp setAppleMenu:appleMenu]; + + /* Finally give up our references to the objects */ + [appleMenu release]; + [menuItem release]; +} + +/* Create a window menu */ +static void setupWindowMenu(void) +{ + NSMenu *windowMenu; + NSMenuItem *windowMenuItem; + NSMenuItem *menuItem; + + windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; + + /* "Minimize" item */ + menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; + [windowMenu addItem:menuItem]; + [menuItem release]; + + /* Put menu into the menubar */ + windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; + [windowMenuItem setSubmenu:windowMenu]; + [[NSApp mainMenu] addItem:windowMenuItem]; + + /* Tell the application object that this is now the window menu */ + [NSApp setWindowsMenu:windowMenu]; + + /* Finally give up our references to the objects */ + [windowMenu release]; + [windowMenuItem release]; +} + +/* Replacement for NSApplicationMain */ +static void CustomApplicationMain (int argc, char **argv) +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + SDLMain *sdlMain; + + /* Ensure the application object is initialised */ + [NSApplication sharedApplication]; + +#ifdef SDL_USE_CPS + { + CPSProcessSerNum PSN; + /* Tell the dock about us */ + if (!CPSGetCurrentProcess(&PSN)) + if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) + if (!CPSSetFrontProcess(&PSN)) + [NSApplication sharedApplication]; + } +#endif /* SDL_USE_CPS */ + + /* Set up the menubar */ + [NSApp setMainMenu:[[[NSMenu alloc] init] autorelease]]; + setApplicationMenu(); + setupWindowMenu(); + + /* Create SDLMain and make it the app delegate */ + sdlMain = [[SDLMain alloc] init]; + [NSApp setDelegate:sdlMain]; + + /* Start the main event loop */ + [NSApp run]; + + [sdlMain release]; + [pool release]; +} + +#endif + + +/* + * Catch document open requests...this lets us notice files when the app + * was launched by double-clicking a document, or when a document was + * dragged/dropped on the app's icon. You need to have a + * CFBundleDocumentsType section in your Info.plist to get this message, + * apparently. + * + * Files are added to gArgv, so to the app, they'll look like command line + * arguments. Previously, apps launched from the finder had nothing but + * an argv[0]. + * + * This message may be received multiple times to open several docs on launch. + * + * This message is ignored once the app's mainline has been called. + */ +- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename +{ + const char *temparg; + size_t arglen; + char *arg; + char **newargv; + + if (!gFinderLaunch) /* MacOS is passing command line args. */ + return FALSE; + + if (gCalledAppMainline) /* app has started, ignore this document. */ + return FALSE; + + temparg = [filename UTF8String]; + arglen = SDL_strlen(temparg) + 1; + arg = (char *) SDL_malloc(arglen); + if (arg == NULL) + return FALSE; + + newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); + if (newargv == NULL) + { + SDL_free(arg); + return FALSE; + } + gArgv = newargv; + + SDL_strlcpy(arg, temparg, arglen); + gArgv[gArgc++] = arg; + gArgv[gArgc] = NULL; + return TRUE; +} + + +/* Called when the internal event loop has just started running */ +- (void) applicationDidFinishLaunching: (NSNotification *) note +{ + int status; + + /* Set the working directory to the .app's parent directory */ + [self setupWorkingDirectory:gFinderLaunch]; + +#if SDL_USE_NIB_FILE + /* Set the main menu to contain the real app name instead of "SDL App" */ + [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; +#endif + + /* Hand off to main application code */ + gCalledAppMainline = TRUE; + status = SDL_main (gArgc, gArgv); + + /* We're done, thank you for playing */ + exit(status); +} +@end + + +@implementation NSString (ReplaceSubString) + +- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString +{ + unsigned int bufferSize; + unsigned int selfLen = [self length]; + unsigned int aStringLen = [aString length]; + unichar *buffer; + NSRange localRange; + NSString *result; + + bufferSize = selfLen + aStringLen - aRange.length; + buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar)); + + /* Get first part into buffer */ + localRange.location = 0; + localRange.length = aRange.location; + [self getCharacters:buffer range:localRange]; + + /* Get middle part into buffer */ + localRange.location = 0; + localRange.length = aStringLen; + [aString getCharacters:(buffer+aRange.location) range:localRange]; + + /* Get last part into buffer */ + localRange.location = aRange.location + aRange.length; + localRange.length = selfLen - localRange.location; + [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; + + /* Build output string */ + result = [NSString stringWithCharacters:buffer length:bufferSize]; + + NSDeallocateMemoryPages(buffer, bufferSize); + + return result; +} + +@end + + + +#ifdef main +# undef main +#endif + + +/* Main entry point to executable - should *not* be SDL_main! */ +int main (int argc, char **argv) +{ + /* Copy the arguments into a global variable */ + /* This is passed if we are launched by double-clicking */ + if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { + gArgv = (char **) SDL_malloc(sizeof (char *) * 2); + gArgv[0] = argv[0]; + gArgv[1] = NULL; + gArgc = 1; + gFinderLaunch = YES; + } else { + int i; + gArgc = argc; + gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); + for (i = 0; i <= argc; i++) + gArgv[i] = argv[i]; + gFinderLaunch = NO; + } + +#if SDL_USE_NIB_FILE + NSApplicationMain (argc, argv); +#else + CustomApplicationMain (argc, argv); +#endif + return 0; +} + diff --git a/SheepShaver/src/SDL/audio_sdl.cpp b/SheepShaver/src/SDL/audio_sdl.cpp new file mode 100644 index 00000000..921beb4c --- /dev/null +++ b/SheepShaver/src/SDL/audio_sdl.cpp @@ -0,0 +1,344 @@ +/* + * audio_sdl.cpp - Audio support, SDL implementation + * + * Basilisk II (C) 1997-2008 Christian Bauer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "sysdeps.h" +#include "cpu_emulation.h" +#include "main.h" +#include "prefs.h" +#include "user_strings.h" +#include "audio.h" +#include "audio_defs.h" + +#include +#include + +#define DEBUG 0 +#include "debug.h" + +#if defined(BINCUE) +#include "bincue_unix.h" +#endif + + +#define MAC_MAX_VOLUME 0x0100 + +// The currently selected audio parameters (indices in audio_sample_rates[] etc. vectors) +static int audio_sample_rate_index = 0; +static int audio_sample_size_index = 0; +static int audio_channel_count_index = 0; + +// Global variables +static SDL_sem *audio_irq_done_sem = NULL; // Signal from interrupt to streaming thread: data block read +static uint8 silence_byte; // Byte value to use to fill sound buffers with silence +static uint8 *audio_mix_buf = NULL; +static int audio_volume = SDL_MIX_MAXVOLUME; +static bool audio_mute = false; + +// Prototypes +static void stream_func(void *arg, uint8 *stream, int stream_len); + + +/* + * Initialization + */ + +// Set AudioStatus to reflect current audio stream format +static void set_audio_status_format(void) +{ + AudioStatus.sample_rate = audio_sample_rates[audio_sample_rate_index]; + AudioStatus.sample_size = audio_sample_sizes[audio_sample_size_index]; + AudioStatus.channels = audio_channel_counts[audio_channel_count_index]; +} + +// Init SDL audio system +static bool open_sdl_audio(void) +{ + // SDL supports a variety of twisted little audio formats, all different + if (audio_sample_sizes.empty()) { + audio_sample_rates.push_back(11025 << 16); + audio_sample_rates.push_back(22050 << 16); + audio_sample_rates.push_back(44100 << 16); + audio_sample_sizes.push_back(8); + audio_sample_sizes.push_back(16); + audio_channel_counts.push_back(1); + audio_channel_counts.push_back(2); + + // Default to highest supported values + audio_sample_rate_index = audio_sample_rates.size() - 1; + audio_sample_size_index = audio_sample_sizes.size() - 1; + audio_channel_count_index = audio_channel_counts.size() - 1; + } + + SDL_AudioSpec audio_spec; + audio_spec.freq = audio_sample_rates[audio_sample_rate_index] >> 16; + audio_spec.format = (audio_sample_sizes[audio_sample_size_index] == 8) ? AUDIO_U8 : AUDIO_S16MSB; + audio_spec.channels = audio_channel_counts[audio_channel_count_index]; + audio_spec.samples = 4096; + audio_spec.callback = stream_func; + audio_spec.userdata = NULL; + + // Open the audio device, forcing the desired format + if (SDL_OpenAudio(&audio_spec, NULL) < 0) { + fprintf(stderr, "WARNING: Cannot open audio: %s\n", SDL_GetError()); + return false; + } + +#if defined(BINCUE) + OpenAudio_bincue(audio_spec.freq, audio_spec.format, audio_spec.channels, + audio_spec.silence); +#endif + + char driver_name[32]; + printf("Using SDL/%s audio output\n", SDL_AudioDriverName(driver_name, sizeof(driver_name) - 1)); + silence_byte = audio_spec.silence; + SDL_PauseAudio(0); + + // Sound buffer size = 4096 frames + audio_frames_per_block = audio_spec.samples; + audio_mix_buf = (uint8*)malloc(audio_spec.size); + return true; +} + +static bool open_audio(void) +{ + // Try to open SDL audio + if (!open_sdl_audio()) { + WarningAlert(GetString(STR_NO_AUDIO_WARN)); + return false; + } + + // Device opened, set AudioStatus + set_audio_status_format(); + + // Everything went fine + audio_open = true; + return true; +} + +void AudioInit(void) +{ + // Init audio status and feature flags + AudioStatus.sample_rate = 44100 << 16; + AudioStatus.sample_size = 16; + AudioStatus.channels = 2; + AudioStatus.mixer = 0; + AudioStatus.num_sources = 0; + audio_component_flags = cmpWantsRegisterMessage | kStereoOut | k16BitOut; + + // Sound disabled in prefs? Then do nothing + if (PrefsFindBool("nosound")) + return; + + // Init semaphore + audio_irq_done_sem = SDL_CreateSemaphore(0); + + // Open and initialize audio device + open_audio(); +} + + +/* + * Deinitialization + */ + +static void close_audio(void) +{ + // Close audio device + SDL_CloseAudio(); + free(audio_mix_buf); + audio_mix_buf = NULL; + audio_open = false; +} + +void AudioExit(void) +{ + // Close audio device + close_audio(); + + // Delete semaphore + if (audio_irq_done_sem) + SDL_DestroySemaphore(audio_irq_done_sem); +} + + +/* + * First source added, start audio stream + */ + +void audio_enter_stream() +{ +} + + +/* + * Last source removed, stop audio stream + */ + +void audio_exit_stream() +{ +} + + +/* + * Streaming function + */ + +static void stream_func(void *arg, uint8 *stream, int stream_len) +{ + if (AudioStatus.num_sources) { + // Trigger audio interrupt to get new buffer + D(bug("stream: triggering irq\n")); + SetInterruptFlag(INTFLAG_AUDIO); + TriggerInterrupt(); + D(bug("stream: waiting for ack\n")); + SDL_SemWait(audio_irq_done_sem); + D(bug("stream: ack received\n")); + + // Get size of audio data + uint32 apple_stream_info = ReadMacInt32(audio_data + adatStreamInfo); + if (apple_stream_info && !audio_mute) { + int work_size = ReadMacInt32(apple_stream_info + scd_sampleCount) * (AudioStatus.sample_size >> 3) * AudioStatus.channels; + D(bug("stream: work_size %d\n", work_size)); + if (work_size > stream_len) + work_size = stream_len; + if (work_size == 0) + goto silence; + + // Send data to audio device + Mac2Host_memcpy(audio_mix_buf, ReadMacInt32(apple_stream_info + scd_buffer), work_size); + memset((uint8 *)stream, silence_byte, stream_len); + SDL_MixAudio(stream, audio_mix_buf, work_size, audio_volume); + + D(bug("stream: data written\n")); + + } else + goto silence; + + } else { + + // Audio not active, play silence +silence: memset(stream, silence_byte, stream_len); + } +#if defined(BINCUE) + MixAudio_bincue(stream, stream_len); +#endif +} + + +/* + * MacOS audio interrupt, read next data block + */ + +void AudioInterrupt(void) +{ + D(bug("AudioInterrupt\n")); + + // Get data from apple mixer + if (AudioStatus.mixer) { + M68kRegisters r; + r.a[0] = audio_data + adatStreamInfo; + r.a[1] = AudioStatus.mixer; + Execute68k(audio_data + adatGetSourceData, &r); + D(bug(" GetSourceData() returns %08lx\n", r.d[0])); + } else + WriteMacInt32(audio_data + adatStreamInfo, 0); + + // Signal stream function + SDL_SemPost(audio_irq_done_sem); + D(bug("AudioInterrupt done\n")); +} + + +/* + * Set sampling parameters + * "index" is an index into the audio_sample_rates[] etc. vectors + * It is guaranteed that AudioStatus.num_sources == 0 + */ + +bool audio_set_sample_rate(int index) +{ + close_audio(); + audio_sample_rate_index = index; + return open_audio(); +} + +bool audio_set_sample_size(int index) +{ + close_audio(); + audio_sample_size_index = index; + return open_audio(); +} + +bool audio_set_channels(int index) +{ + close_audio(); + audio_channel_count_index = index; + return open_audio(); +} + + +/* + * Get/set volume controls (volume values received/returned have the left channel + * volume in the upper 16 bits and the right channel volume in the lower 16 bits; + * both volumes are 8.8 fixed point values with 0x0100 meaning "maximum volume")) + */ + +bool audio_get_main_mute(void) +{ + return audio_mute; +} + +uint32 audio_get_main_volume(void) +{ + uint32 chan = (audio_volume * MAC_MAX_VOLUME / SDL_MIX_MAXVOLUME); + return (chan << 16) + chan; +} + +bool audio_get_speaker_mute(void) +{ + return audio_mute; +} + +uint32 audio_get_speaker_volume(void) +{ + return audio_get_main_volume(); +} + +void audio_set_main_mute(bool mute) +{ + audio_mute = mute; +} + +void audio_set_main_volume(uint32 vol) +{ + // We only have one-channel volume right now. + uint32 avg = ((vol >> 16) + (vol & 0xffff)) / 2; + if (avg > MAC_MAX_VOLUME) + avg = MAC_MAX_VOLUME; + audio_volume = avg * SDL_MIX_MAXVOLUME / MAC_MAX_VOLUME; +} + +void audio_set_speaker_mute(bool mute) +{ +} + +void audio_set_speaker_volume(uint32 vol) +{ +} diff --git a/SheepShaver/src/SDL/keycodes b/SheepShaver/src/SDL/keycodes new file mode 100644 index 00000000..da918560 --- /dev/null +++ b/SheepShaver/src/SDL/keycodes @@ -0,0 +1,464 @@ +# /usr/share/BasiliskII/keycodes +# +# Basilisk II (C) 1997-2005 Christian Bauer +# +# This file is used to translate the (server-specific) scancodes to +# Mac keycodes depending on the window server being used. +# +# The format of this file is as follows: +# +# sdl +# +# +# +# ... +# sdl +# +# +# ... +# +# The "driver string" must match the first part of the SDL driver vendor +# description as reported by SDL_VideoDriverName(). If a match is found, +# the keycode translation table is constructed from the following +# lines. Each line contains an SDL scancode followed by its associated +# Mac keycode. Both keycodes have to be given in decimal. Lines +# beginning with "#" or ";" are treated as comments and ignored. +# + +# +# X11 server +# +sdl x11 +sdl dga +9 53 # Esc +67 122 # F1 +68 120 # F2 +69 99 # F3 +70 118 # F4 +71 96 # F5 +72 97 # F6 +73 98 # F7 +74 100 # F8 +75 101 # F9 +76 109 # F10 +95 103 # F11 +96 111 # F12 +111 105 # PrintScrn +78 107 # Scroll Lock +110 113 # Pause +49 50 # ` +10 18 # 1 +11 19 # 2 +12 20 # 3 +13 21 # 4 +14 23 # 5 +15 22 # 6 +16 26 # 7 +17 28 # 8 +18 25 # 9 +19 29 # 0 +20 27 # - +21 24 # = +22 51 # Backspace +106 114 # Insert +97 115 # Home +99 116 # Page Up +77 71 # Num Lock +112 75 # KP / +63 67 # KP * +82 78 # KP - +23 48 # Tab +24 12 # Q +25 13 # W +26 14 # E +27 15 # R +28 17 # T +29 16 # Y +30 32 # U +31 34 # I +32 31 # O +33 35 # P +34 33 # [ +35 30 # ] +36 36 # Return +107 117 # Delete +103 119 # End +105 121 # Page Down +79 89 # KP 7 +80 91 # KP 8 +81 92 # KP 9 +86 69 # KP + +66 57 # Caps Lock +38 0 # A +39 1 # S +40 2 # D +41 3 # F +42 5 # G +43 4 # H +44 38 # J +45 40 # K +46 37 # L +47 41 # ; +48 39 # ' +83 86 # KP 4 +84 87 # KP 5 +85 88 # KP 6 +50 56 # Shift Left +94 50 # International +52 6 # Z +53 7 # X +54 8 # C +55 9 # V +56 11 # B +57 45 # N +58 46 # M +59 43 # , +60 47 # . +61 44 # / +62 56 # Shift Right +51 42 # \ +98 62 # Cursor Up +87 83 # KP 1 +88 84 # KP 2 +89 85 # KP 3 +108 76 # KP Enter +37 54 # Ctrl Left +115 58 # Logo Left (-> Option) +64 55 # Alt Left (-> Command) +65 49 # Space +113 55 # Alt Right (-> Command) +116 58 # Logo Right (-> Option) +117 50 # Menu (-> International) +109 54 # Ctrl Right +100 59 # Cursor Left +104 61 # Cursor Down +102 60 # Cursor Right +90 82 # KP 0 +91 65 # KP . + +# +# Linux Framebuffer Console +# +sdl fbcon +1 53 # Esc +59 122 # F1 +60 120 # F2 +61 99 # F3 +62 118 # F4 +63 96 # F5 +64 97 # F6 +65 98 # F7 +66 100 # F8 +67 101 # F9 +68 109 # F10 +87 103 # F11 +88 111 # F12 +99 105 # PrintScrn +70 107 # Scroll Lock +119 113 # Pause +41 50 # ` +2 18 # 1 +3 19 # 2 +4 20 # 3 +5 21 # 4 +6 23 # 5 +7 22 # 6 +8 26 # 7 +9 28 # 8 +10 25 # 9 +11 29 # 0 +12 27 # - +13 24 # = +14 51 # Backspace +110 114 # Insert +102 115 # Home +104 116 # Page Up +69 71 # Num Lock +98 75 # KP / +55 67 # KP * +74 78 # KP - +15 48 # Tab +16 12 # Q +17 13 # W +18 14 # E +19 15 # R +20 17 # T +21 16 # Y +22 32 # U +23 34 # I +24 31 # O +25 35 # P +26 33 # [ +27 30 # ] +28 36 # Return +111 117 # Delete +107 119 # End +109 121 # Page Down +71 89 # KP 7 +72 91 # KP 8 +73 92 # KP 9 +78 69 # KP + +58 57 # Caps Lock +30 0 # A +31 1 # S +32 2 # D +33 3 # F +34 5 # G +35 4 # H +36 38 # J +37 40 # K +38 37 # L +39 41 # ; +40 39 # ' +75 86 # KP 4 +76 87 # KP 5 +77 88 # KP 6 +42 56 # Shift Left +86 50 # International +44 6 # Z +45 7 # X +46 8 # C +47 9 # V +48 11 # B +49 45 # N +50 46 # M +51 43 # , +52 47 # . +53 44 # / +54 56 # Shift Right +43 42 # \ +103 62 # Cursor Up +79 83 # KP 1 +80 84 # KP 2 +81 85 # KP 3 +96 76 # KP Enter +29 54 # Ctrl Left +125 58 # Logo Left (-> Option) +56 55 # Alt Left (-> Command) +57 49 # Space +100 55 # Alt Right (-> Command) +126 58 # Logo Right (-> Option) +97 54 # Ctrl Right +105 59 # Cursor Left +108 61 # Cursor Down +106 60 # Cursor Right +82 82 # KP 0 +83 65 # KP . + +# +# Quartz (1:1 translation actually) +# +sdl Quartz +53 53 # Esc +122 122 # F1 +120 120 # F2 +99 99 # F3 +118 118 # F4 +96 96 # F5 +97 97 # F6 +98 98 # F7 +100 100 # F8 +101 101 # F9 +109 109 # F10 +103 103 # F11 +111 111 # F12 +105 105 # F13/PrintScrn +107 107 # F14/Scroll Lock +113 113 # F15/Pause +10 10 # ` +18 18 # 1 +19 19 # 2 +20 20 # 3 +21 21 # 4 +23 23 # 5 +22 22 # 6 +26 26 # 7 +28 28 # 8 +25 25 # 9 +29 29 # 0 +27 27 # - +24 24 # = +51 51 # Backspace +114 114 # Help/Insert +115 115 # Home +116 116 # Page Up +71 71 # Num Lock +81 81 # KP = +75 75 # KP / +67 67 # KP * +48 48 # Tab +12 12 # Q +13 13 # W +14 14 # E +15 15 # R +17 17 # T +16 16 # Y +32 32 # U +34 34 # I +31 31 # O +35 35 # P +33 33 # [ +30 30 # ] +36 36 # Return +117 117 # Delete +119 119 # End +121 121 # Page Down +89 89 # KP 7 +91 91 # KP 8 +92 92 # KP 9 +78 78 # KP - +57 57 # Caps Lock +0 0 # A +1 1 # S +2 2 # D +3 3 # F +5 5 # G +4 4 # H +38 38 # J +40 40 # K +37 37 # L +41 41 # ; +39 39 # ' +42 42 # \ +86 86 # KP 4 +87 87 # KP 5 +88 88 # KP 6 +69 69 # KP + +56 56 # Shift +50 50 # International +6 6 # Z +7 7 # X +8 8 # C +9 9 # V +11 11 # B +45 45 # N +46 46 # M +43 43 # , +47 47 # . +44 44 # / +126 62 # Cursor Up +123 59 # Cursor Left +125 61 # Cursor Down +124 60 # Cursor Right +83 83 # KP 1 +84 84 # KP 2 +85 85 # KP 3 +76 76 # KP Enter +54 54 # Ctrl +58 58 # Option +55 55 # Command +54 54 # Ctrl Left +49 49 # Space +82 82 # KP 0 +65 65 # KP . + +# +# Windows +# +sdl windib +sdl directx +1 53 # Esc +59 122 # F1 +60 120 # F2 +61 99 # F3 +62 118 # F4 +63 96 # F5 +64 97 # F6 +65 98 # F7 +66 100 # F8 +67 101 # F9 +68 109 # F10 +87 103 # F11 +88 111 # F12 +183 105 # PrintScrn +70 107 # Scroll Lock +197 113 # Pause +41 50 # ` +2 18 # 1 +3 19 # 2 +4 20 # 3 +5 21 # 4 +6 23 # 5 +7 22 # 6 +8 26 # 7 +9 28 # 8 +10 25 # 9 +11 29 # 0 +12 27 # - +13 24 # = +14 51 # Backspace +210 114 # Insert +199 115 # Home +201 116 # Page Up +69 71 # Num Lock +181 75 # KP / +55 67 # KP * +74 78 # KP - +15 48 # Tab +16 12 # Q +17 13 # W +18 14 # E +19 15 # R +20 17 # T +21 16 # Y +22 32 # U +23 34 # I +24 31 # O +25 35 # P +26 33 # [ +27 30 # ] +28 36 # Return +211 117 # Delete +207 119 # End +209 121 # Page Down +71 89 # KP 7 +72 91 # KP 8 +73 92 # KP 9 +78 69 # KP + +58 57 # Caps Lock +30 0 # A +31 1 # S +32 2 # D +33 3 # F +34 5 # G +35 4 # H +36 38 # J +37 40 # K +38 37 # L +39 41 # ; +40 39 # ' +75 86 # KP 4 +76 87 # KP 5 +77 88 # KP 6 +42 56 # Shift Left +86 50 # International +44 6 # Z +45 7 # X +46 8 # C +47 9 # V +48 11 # B +49 45 # N +50 46 # M +51 43 # , +52 47 # . +53 44 # / +54 56 # Shift Right +43 42 # \ +200 62 # Cursor Up +79 83 # KP 1 +80 84 # KP 2 +81 85 # KP 3 +156 76 # KP Enter +29 54 # Ctrl Left +219 58 # Logo Left (-> Option) +56 55 # Alt Left (-> Command) +57 49 # Space +184 55 # Alt Right (-> Command) +220 58 # Logo Right (-> Option) +221 50 # Menu (-> International) +157 54 # Ctrl Right +203 59 # Cursor Left +208 61 # Cursor Down +205 60 # Cursor Right +82 82 # KP 0 +83 65 # KP . diff --git a/SheepShaver/src/SDL/video_sdl.cpp b/SheepShaver/src/SDL/video_sdl.cpp new file mode 100755 index 00000000..ce2c9ae1 --- /dev/null +++ b/SheepShaver/src/SDL/video_sdl.cpp @@ -0,0 +1,2264 @@ +/* + * video_sdl.cpp - Video/graphics emulation, SDL specific stuff + * + * Basilisk II (C) 1997-2008 Christian Bauer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * NOTES: + * The Ctrl key works like a qualifier for special actions: + * Ctrl-Tab = suspend DGA mode (TODO) + * Ctrl-Esc = emergency quit + * Ctrl-F1 = mount floppy + * Ctrl-F5 = grab mouse (in windowed mode) + * + * FIXMEs and TODOs: + * - Windows requires an extra mouse event to update the actual cursor image? + * - Ctr-Tab for suspend/resume but how? SDL does not support that for non-Linux + * - Ctrl-Fn doesn't generate SDL_KEYDOWN events (SDL bug?) + * - Mouse acceleration, there is no API in SDL yet for that + * - Gamma tables support is likely to be broken here + * - Events processing is bound to the general emulation thread as SDL requires + * to PumpEvents() within the same thread as the one that called SetVideoMode(). + * Besides, there can't seem to be a way to call SetVideoMode() from a child thread. + * - Backport hw cursor acceleration to Basilisk II? + * - Factor out code + */ + +#include "sysdeps.h" + +#include +#include +#include +#include +#include + +#ifdef WIN32 +#include /* alloca() */ +#endif + +#include "cpu_emulation.h" +#include "main.h" +#include "adb.h" +#include "macos_util.h" +#include "prefs.h" +#include "user_strings.h" +#include "video.h" +#include "video_defs.h" +#include "video_blit.h" +#include "vm_alloc.h" + +#define DEBUG 0 +#include "debug.h" + +// Supported video modes +using std::vector; +static vector VideoModes; + +// Display types +#ifdef SHEEPSHAVER +enum { + DISPLAY_WINDOW = DIS_WINDOW, // windowed display + DISPLAY_SCREEN = DIS_SCREEN // fullscreen display +}; +extern int display_type; // See enum above +#else +enum { + DISPLAY_WINDOW, // windowed display + DISPLAY_SCREEN // fullscreen display +}; +static int display_type = DISPLAY_WINDOW; // See enum above +#endif + +// Constants +#ifdef WIN32 +const char KEYCODE_FILE_NAME[] = "BasiliskII_keycodes"; +#else +const char KEYCODE_FILE_NAME[] = DATADIR "/keycodes"; +#endif + + +// Global variables +static uint32 frame_skip; // Prefs items +static int16 mouse_wheel_mode; +static int16 mouse_wheel_lines; + +static uint8 *the_buffer = NULL; // Mac frame buffer (where MacOS draws into) +static uint8 *the_buffer_copy = NULL; // Copy of Mac frame buffer (for refreshed modes) +static uint32 the_buffer_size; // Size of allocated the_buffer + +static bool redraw_thread_active = false; // Flag: Redraw thread installed +#ifndef USE_CPU_EMUL_SERVICES +static volatile bool redraw_thread_cancel; // Flag: Cancel Redraw thread +static SDL_Thread *redraw_thread = NULL; // Redraw thread +static volatile bool thread_stop_req = false; +static volatile bool thread_stop_ack = false; // Acknowledge for thread_stop_req +#endif + +#ifdef ENABLE_VOSF +static bool use_vosf = false; // Flag: VOSF enabled +#else +static const bool use_vosf = false; // VOSF not possible +#endif + +static bool ctrl_down = false; // Flag: Ctrl key pressed +static bool caps_on = false; // Flag: Caps Lock on +static bool quit_full_screen = false; // Flag: DGA close requested from redraw thread +static bool emerg_quit = false; // Flag: Ctrl-Esc pressed, emergency quit requested from MacOS thread +static bool emul_suspended = false; // Flag: Emulator suspended + +static bool classic_mode = false; // Flag: Classic Mac video mode + +static bool use_keycodes = false; // Flag: Use keycodes rather than keysyms +static int keycode_table[256]; // X keycode -> Mac keycode translation table + +// SDL variables +static int screen_depth; // Depth of current screen +static SDL_Cursor *sdl_cursor; // Copy of Mac cursor +static SDL_Color sdl_palette[256]; // Color palette to be used as CLUT and gamma table +static bool sdl_palette_changed = false; // Flag: Palette changed, redraw thread must set new colors +static bool toggle_fullscreen = false; +static const int sdl_eventmask = SDL_MOUSEEVENTMASK | SDL_KEYEVENTMASK | SDL_VIDEOEXPOSEMASK | SDL_QUITMASK | SDL_ACTIVEEVENTMASK; + +static bool mouse_grabbed = false; + +// Mutex to protect SDL events +static SDL_mutex *sdl_events_lock = NULL; +#define LOCK_EVENTS SDL_LockMutex(sdl_events_lock) +#define UNLOCK_EVENTS SDL_UnlockMutex(sdl_events_lock) + +// Mutex to protect palette +static SDL_mutex *sdl_palette_lock = NULL; +#define LOCK_PALETTE SDL_LockMutex(sdl_palette_lock) +#define UNLOCK_PALETTE SDL_UnlockMutex(sdl_palette_lock) + +// Mutex to protect frame buffer +static SDL_mutex *frame_buffer_lock = NULL; +#define LOCK_FRAME_BUFFER SDL_LockMutex(frame_buffer_lock) +#define UNLOCK_FRAME_BUFFER SDL_UnlockMutex(frame_buffer_lock) + +// Video refresh function +static void VideoRefreshInit(void); +static void (*video_refresh)(void); + + +// Prototypes +static int redraw_func(void *arg); + +// From sys_unix.cpp +extern void SysMountFirstFloppy(void); + + +/* + * SDL surface locking glue + */ + +#ifdef ENABLE_VOSF +#define SDL_VIDEO_LOCK_VOSF_SURFACE(SURFACE) do { \ + if ((SURFACE)->flags & (SDL_HWSURFACE | SDL_FULLSCREEN)) \ + the_host_buffer = (uint8 *)(SURFACE)->pixels; \ +} while (0) +#else +#define SDL_VIDEO_LOCK_VOSF_SURFACE(SURFACE) +#endif + +#define SDL_VIDEO_LOCK_SURFACE(SURFACE) do { \ + if (SDL_MUSTLOCK(SURFACE)) { \ + SDL_LockSurface(SURFACE); \ + SDL_VIDEO_LOCK_VOSF_SURFACE(SURFACE); \ + } \ +} while (0) + +#define SDL_VIDEO_UNLOCK_SURFACE(SURFACE) do { \ + if (SDL_MUSTLOCK(SURFACE)) \ + SDL_UnlockSurface(SURFACE); \ +} while (0) + + +/* + * Framebuffer allocation routines + */ + +static void *vm_acquire_framebuffer(uint32 size) +{ + // always try to reallocate framebuffer at the same address + static void *fb = VM_MAP_FAILED; + if (fb != VM_MAP_FAILED) { +// if (vm_acquire_fixed(fb, size) < 0) { +#ifndef SHEEPSHAVER + printf("FATAL: Could not reallocate framebuffer at previous address\n"); +#endif + fb = VM_MAP_FAILED; +// } + } + if (fb == VM_MAP_FAILED) + fb = vm_acquire(size, VM_MAP_DEFAULT | VM_MAP_32BIT); + return fb; +} + +static inline void vm_release_framebuffer(void *fb, uint32 size) +{ + vm_release(fb, size); +} + +static inline int get_customized_color_depth(int default_depth) +{ + int display_color_depth = PrefsFindInt32("displaycolordepth"); + + D(bug("Get displaycolordepth %d\n", display_color_depth)); + + if(0 == display_color_depth) + return default_depth; + else{ + switch (display_color_depth) { + case 8: + return VIDEO_DEPTH_8BIT; + case 15: case 16: + return VIDEO_DEPTH_16BIT; + case 24: case 32: + return VIDEO_DEPTH_32BIT; + default: + return default_depth; + } + } +} + +/* + * Windows message handler + */ + +#ifdef WIN32 +#include +static WNDPROC sdl_window_proc = NULL; // Window proc used by SDL + +extern void SysMediaArrived(void); +extern void SysMediaRemoved(void); +extern HWND GetMainWindowHandle(void); + +static LRESULT CALLBACK windows_message_handler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) { + case WM_DEVICECHANGE: + if (wParam == DBT_DEVICEREMOVECOMPLETE) { + DEV_BROADCAST_HDR *p = (DEV_BROADCAST_HDR *)lParam; + if (p->dbch_devicetype == DBT_DEVTYP_VOLUME) + SysMediaRemoved(); + } + else if (wParam == DBT_DEVICEARRIVAL) { + DEV_BROADCAST_HDR *p = (DEV_BROADCAST_HDR *)lParam; + if (p->dbch_devicetype == DBT_DEVTYP_VOLUME) + SysMediaArrived(); + } + return 0; + + default: + if (sdl_window_proc) + return CallWindowProc(sdl_window_proc, hwnd, msg, wParam, lParam); + } + + return DefWindowProc(hwnd, msg, wParam, lParam); +} +#endif + + +/* + * SheepShaver glue + */ + +#ifdef SHEEPSHAVER +// Color depth modes type +typedef int video_depth; + +// 1, 2, 4 and 8 bit depths use a color palette +static inline bool IsDirectMode(VIDEO_MODE const & mode) +{ + return IsDirectMode(mode.viAppleMode); +} + +// Abstract base class representing one (possibly virtual) monitor +// ("monitor" = rectangular display with a contiguous frame buffer) +class monitor_desc { +public: + monitor_desc(const vector &available_modes, video_depth default_depth, uint32 default_id) {} + virtual ~monitor_desc() {} + + // Get current Mac frame buffer base address + uint32 get_mac_frame_base(void) const {return screen_base;} + + // Set Mac frame buffer base address (called from switch_to_mode()) + void set_mac_frame_base(uint32 base) {screen_base = base;} + + // Get current video mode + const VIDEO_MODE &get_current_mode(void) const {return VModes[cur_mode];} + + // Called by the video driver to switch the video mode on this display + // (must call set_mac_frame_base()) + virtual void switch_to_current_mode(void) = 0; + + // Called by the video driver to set the color palette (in indexed modes) + // or the gamma table (in direct modes) + virtual void set_palette(uint8 *pal, int num) = 0; +}; + +// Vector of pointers to available monitor descriptions, filled by VideoInit() +static vector VideoMonitors; + +// Find Apple mode matching best specified dimensions +static int find_apple_resolution(int xsize, int ysize) +{ + if (xsize == 640 && ysize == 480) + return APPLE_640x480; + if (xsize == 800 && ysize == 600) + return APPLE_800x600; + if (xsize == 1024 && ysize == 768) + return APPLE_1024x768; + if (xsize == 1152 && ysize == 768) + return APPLE_1152x768; + if (xsize == 1152 && ysize == 900) + return APPLE_1152x900; + if (xsize == 1280 && ysize == 1024) + return APPLE_1280x1024; + if (xsize == 1600 && ysize == 1200) + return APPLE_1600x1200; + return APPLE_CUSTOM; +} + +// Display error alert +static void ErrorAlert(int error) +{ + ErrorAlert(GetString(error)); +} +#endif + + +/* + * monitor_desc subclass for SDL display + */ + +class SDL_monitor_desc : public monitor_desc { +public: + SDL_monitor_desc(const vector &available_modes, video_depth default_depth, uint32 default_id) : monitor_desc(available_modes, default_depth, default_id) {} + ~SDL_monitor_desc() {} + + virtual void switch_to_current_mode(void); + virtual void set_palette(uint8 *pal, int num); + + bool video_open(void); + void video_close(void); +}; + + +/* + * Utility functions + */ + +// Find palette size for given color depth +static int palette_size(int mode) +{ + switch (mode) { + case VIDEO_DEPTH_1BIT: return 2; + case VIDEO_DEPTH_2BIT: return 4; + case VIDEO_DEPTH_4BIT: return 16; + case VIDEO_DEPTH_8BIT: return 256; + case VIDEO_DEPTH_16BIT: return 32; + case VIDEO_DEPTH_32BIT: return 256; + default: return 0; + } +} + +// Map video_mode depth ID to numerical depth value +static int mac_depth_of_video_depth(int video_depth) +{ + int depth = -1; + switch (video_depth) { + case VIDEO_DEPTH_1BIT: + depth = 1; + break; + case VIDEO_DEPTH_2BIT: + depth = 2; + break; + case VIDEO_DEPTH_4BIT: + depth = 4; + break; + case VIDEO_DEPTH_8BIT: + depth = 8; + break; + case VIDEO_DEPTH_16BIT: + depth = 16; + break; + case VIDEO_DEPTH_32BIT: + depth = 32; + break; + default: + abort(); + } + return depth; +} + +// Map video_mode depth ID to SDL screen depth +static int sdl_depth_of_video_depth(int video_depth) +{ + return (video_depth <= VIDEO_DEPTH_8BIT) ? 8 : mac_depth_of_video_depth(video_depth); +} + +// Get screen dimensions +static void sdl_display_dimensions(int &width, int &height) +{ + static int max_width, max_height; + if (max_width == 0 && max_height == 0) { + max_width = 640 ; max_height = 480; + SDL_Rect **modes = SDL_ListModes(NULL, SDL_FULLSCREEN | SDL_HWSURFACE); + if (modes && modes != (SDL_Rect **)-1) { + // It turns out that on some implementations, and contrary to the documentation, + // the returned list is not sorted from largest to smallest (e.g. Windows) + for (int i = 0; modes[i] != NULL; i++) { + const int w = modes[i]->w; + const int h = modes[i]->h; + if (w > max_width && h > max_height) { + max_width = w; + max_height = h; + } + } + } + } + width = max_width; + height = max_height; +} + +static inline int sdl_display_width(void) +{ + int width, height; + sdl_display_dimensions(width, height); + return width; +} + +static inline int sdl_display_height(void) +{ + int width, height; + sdl_display_dimensions(width, height); + return height; +} + +// Check wether specified mode is available +static bool has_mode(int type, int width, int height, int depth) +{ +#ifdef SHEEPSHAVER + // Filter out Classic resolutions + if (width == 512 && height == 384) + return false; +#endif + + // Filter out out-of-bounds resolutions + if (width > sdl_display_width() || height > sdl_display_height()) + return false; + + // Rely on SDL capabilities + return SDL_VideoModeOK(width, height, + sdl_depth_of_video_depth(depth), + SDL_HWSURFACE | (type == DISPLAY_SCREEN ? SDL_FULLSCREEN : 0)) != 0; +} + +// Add mode to list of supported modes +static void add_mode(int type, int width, int height, int resolution_id, int bytes_per_row, int depth) +{ + // Filter out unsupported modes + if (!has_mode(type, width, height, depth)) + return; + + // Fill in VideoMode entry + VIDEO_MODE mode; +#ifdef SHEEPSHAVER + resolution_id = find_apple_resolution(width, height); + mode.viType = type; +#endif + VIDEO_MODE_X = width; + VIDEO_MODE_Y = height; + VIDEO_MODE_RESOLUTION = resolution_id; + VIDEO_MODE_ROW_BYTES = bytes_per_row; + VIDEO_MODE_DEPTH = (video_depth)depth; + VideoModes.push_back(mode); +} + +// Set Mac frame layout and base address (uses the_buffer/MacFrameBaseMac) +static void set_mac_frame_buffer(SDL_monitor_desc &monitor, int depth, bool native_byte_order) +{ +#if !REAL_ADDRESSING && !DIRECT_ADDRESSING + int layout = FLAYOUT_DIRECT; + if (depth == VIDEO_DEPTH_16BIT) + layout = (screen_depth == 15) ? FLAYOUT_HOST_555 : FLAYOUT_HOST_565; + else if (depth == VIDEO_DEPTH_32BIT) + layout = (screen_depth == 24) ? FLAYOUT_HOST_888 : FLAYOUT_DIRECT; + if (native_byte_order) + MacFrameLayout = layout; + else + MacFrameLayout = FLAYOUT_DIRECT; + monitor.set_mac_frame_base(MacFrameBaseMac); + + // Set variables used by UAE memory banking + const VIDEO_MODE &mode = monitor.get_current_mode(); + MacFrameBaseHost = the_buffer; + MacFrameSize = VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y; + InitFrameBufferMapping(); +#else + monitor.set_mac_frame_base(Host2MacAddr(the_buffer)); +#endif + D(bug("monitor.mac_frame_base = %08x\n", monitor.get_mac_frame_base())); +} + +// Set window name and class +static void set_window_name(int name) +{ + const SDL_VideoInfo *vi = SDL_GetVideoInfo(); + if (vi && vi->wm_available) { + const char *str = GetString(name); + SDL_WM_SetCaption(str, str); + } +} + +// Set mouse grab mode +static SDL_GrabMode set_grab_mode(SDL_GrabMode mode) +{ + const SDL_VideoInfo *vi = SDL_GetVideoInfo(); + return (vi && vi->wm_available ? SDL_WM_GrabInput(mode) : SDL_GRAB_OFF); +} + +// Migrate preferences items (XXX to be handled in MigratePrefs()) +static void migrate_screen_prefs(void) +{ +#ifdef SHEEPSHAVER + // Look-up priorities are: "screen", "screenmodes", "windowmodes". + if (PrefsFindString("screen")) + return; + + uint32 window_modes = PrefsFindInt32("windowmodes"); + uint32 screen_modes = PrefsFindInt32("screenmodes"); + int width = 0, height = 0; + if (screen_modes) { + static const struct { + int id; + int width; + int height; + } + modes[] = { + { 1, 640, 480 }, + { 2, 800, 600 }, + { 4, 1024, 768 }, + { 64, 1152, 768 }, + { 8, 1152, 900 }, + { 16, 1280, 1024 }, + { 32, 1600, 1200 }, + { 0, } + }; + for (int i = 0; modes[i].id != 0; i++) { + if (screen_modes & modes[i].id) { + if (width < modes[i].width && height < modes[i].height) { + width = modes[i].width; + height = modes[i].height; + } + } + } + } else { + if (window_modes & 1) + width = 640, height = 480; + if (window_modes & 2) + width = 800, height = 600; + } + if (width && height) { + char str[32]; + sprintf(str, "%s/%d/%d", screen_modes ? "dga" : "win", width, height); + PrefsReplaceString("screen", str); + } +#endif +} + + +/* + * Display "driver" classes + */ + +class driver_base { +public: + driver_base(SDL_monitor_desc &m); + ~driver_base(); + + void init(); // One-time init + void set_video_mode(int flags); + void adapt_to_video_mode(); + + void update_palette(void); + void suspend(void) {} + void resume(void) {} + void toggle_mouse_grab(void); + void mouse_moved(int x, int y) { ADBMouseMoved(x, y); } + + void disable_mouse_accel(void); + void restore_mouse_accel(void); + + void grab_mouse(void); + void ungrab_mouse(void); + +public: + SDL_monitor_desc &monitor; // Associated video monitor + const VIDEO_MODE &mode; // Video mode handled by the driver + + bool init_ok; // Initialization succeeded (we can't use exceptions because of -fomit-frame-pointer) + SDL_Surface *s; // The surface we draw into +}; + +#ifdef ENABLE_VOSF +static void update_display_window_vosf(driver_base *drv); +#endif +static void update_display_static(driver_base *drv); + +static driver_base *drv = NULL; // Pointer to currently used driver object + +#ifdef ENABLE_VOSF +# include "video_vosf.h" +#endif + +driver_base::driver_base(SDL_monitor_desc &m) + : monitor(m), mode(m.get_current_mode()), init_ok(false), s(NULL) +{ + the_buffer = NULL; + the_buffer_copy = NULL; +} + +void driver_base::set_video_mode(int flags) +{ + int depth = sdl_depth_of_video_depth(VIDEO_MODE_DEPTH); + if ((s = SDL_SetVideoMode(VIDEO_MODE_X, VIDEO_MODE_Y, depth, + SDL_HWSURFACE | flags)) == NULL) + return; +#ifdef ENABLE_VOSF + the_host_buffer = (uint8 *)s->pixels; +#endif +} + +void driver_base::init() +{ + set_video_mode(display_type == DISPLAY_SCREEN ? SDL_FULLSCREEN : 0); + int aligned_height = (VIDEO_MODE_Y + 15) & ~15; + +#ifdef ENABLE_VOSF + use_vosf = true; + // Allocate memory for frame buffer (SIZE is extended to page-boundary) + the_buffer_size = page_extend((aligned_height + 2) * s->pitch); + the_buffer = (uint8 *)vm_acquire_framebuffer(the_buffer_size); + the_buffer_copy = (uint8 *)malloc(the_buffer_size); + D(bug("the_buffer = %p, the_buffer_copy = %p, the_host_buffer = %p\n", the_buffer, the_buffer_copy, the_host_buffer)); + + // Check whether we can initialize the VOSF subsystem and it's profitable + if (!video_vosf_init(monitor)) { + WarningAlert(GetString(STR_VOSF_INIT_ERR)); + use_vosf = false; + } + else if (!video_vosf_profitable()) { + video_vosf_exit(); + printf("VOSF acceleration is not profitable on this platform, disabling it\n"); + use_vosf = false; + } + if (!use_vosf) { + free(the_buffer_copy); + vm_release(the_buffer, the_buffer_size); + the_host_buffer = NULL; + } +#endif + if (!use_vosf) { + // Allocate memory for frame buffer + the_buffer_size = (aligned_height + 2) * s->pitch; + the_buffer_copy = (uint8 *)calloc(1, the_buffer_size); + the_buffer = (uint8 *)vm_acquire_framebuffer(the_buffer_size); + D(bug("the_buffer = %p, the_buffer_copy = %p\n", the_buffer, the_buffer_copy)); + } + + // Set frame buffer base + set_mac_frame_buffer(monitor, VIDEO_MODE_DEPTH, true); + + adapt_to_video_mode(); +} + +void driver_base::adapt_to_video_mode() { + ADBSetRelMouseMode(mouse_grabbed); + + // Init blitting routines + SDL_PixelFormat *f = s->format; + VisualFormat visualFormat; + visualFormat.depth = sdl_depth_of_video_depth(VIDEO_MODE_DEPTH); + visualFormat.Rmask = f->Rmask; + visualFormat.Gmask = f->Gmask; + visualFormat.Bmask = f->Bmask; + Screen_blitter_init(visualFormat, true, mac_depth_of_video_depth(VIDEO_MODE_DEPTH)); + + // Load gray ramp to 8->16/32 expand map + if (!IsDirectMode(mode)) + for (int i=0; i<256; i++) + ExpandMap[i] = SDL_MapRGB(f, i, i, i); + + + bool hardware_cursor = false; +#ifdef SHEEPSHAVER + hardware_cursor = video_can_change_cursor(); + if (hardware_cursor) { + // Create cursor + if ((sdl_cursor = SDL_CreateCursor(MacCursor + 4, MacCursor + 36, 16, 16, 0, 0)) != NULL) { + SDL_SetCursor(sdl_cursor); + } + } + // Tell the video driver there's a change in cursor type + if (private_data) + private_data->cursorHardware = hardware_cursor; +#endif + // Hide cursor + SDL_ShowCursor(hardware_cursor); + + // Set window name/class + set_window_name(mouse_grabbed ? STR_WINDOW_TITLE_GRABBED : STR_WINDOW_TITLE); + + // Everything went well + init_ok = true; +} + +driver_base::~driver_base() +{ + ungrab_mouse(); + restore_mouse_accel(); + + if (s) + SDL_FreeSurface(s); + + // the_buffer shall always be mapped through vm_acquire_framebuffer() + if (the_buffer != VM_MAP_FAILED) { + D(bug(" releasing the_buffer at %p (%d bytes)\n", the_buffer, the_buffer_size)); + vm_release_framebuffer(the_buffer, the_buffer_size); + the_buffer = NULL; + } + + // Free frame buffer(s) + if (!use_vosf) { + if (the_buffer_copy) { + free(the_buffer_copy); + the_buffer_copy = NULL; + } + } +#ifdef ENABLE_VOSF + else { + if (the_buffer_copy) { + D(bug(" freeing the_buffer_copy at %p\n", the_buffer_copy)); + free(the_buffer_copy); + the_buffer_copy = NULL; + } + + // Deinitialize VOSF + video_vosf_exit(); + } +#endif + + SDL_ShowCursor(1); +} + +// Palette has changed +void driver_base::update_palette(void) +{ + const VIDEO_MODE &mode = monitor.get_current_mode(); + + if ((int)VIDEO_MODE_DEPTH <= VIDEO_DEPTH_8BIT) + SDL_SetPalette(s, SDL_PHYSPAL, sdl_palette, 0, 256); +} + +// Disable mouse acceleration +void driver_base::disable_mouse_accel(void) +{ +} + +// Restore mouse acceleration to original value +void driver_base::restore_mouse_accel(void) +{ +} + +// Toggle mouse grab +void driver_base::toggle_mouse_grab(void) +{ + if (mouse_grabbed) + ungrab_mouse(); + else + grab_mouse(); +} + +// Grab mouse, switch to relative mouse mode +void driver_base::grab_mouse(void) +{ + if (!mouse_grabbed) { + SDL_GrabMode new_mode = set_grab_mode(SDL_GRAB_ON); + if (new_mode == SDL_GRAB_ON) { + set_window_name(STR_WINDOW_TITLE_GRABBED); + disable_mouse_accel(); + ADBSetRelMouseMode(mouse_grabbed = true); + } + } +} + +// Ungrab mouse, switch to absolute mouse mode +void driver_base::ungrab_mouse(void) +{ + if (mouse_grabbed) { + SDL_GrabMode new_mode = set_grab_mode(SDL_GRAB_OFF); + if (new_mode == SDL_GRAB_OFF) { + set_window_name(STR_WINDOW_TITLE); + restore_mouse_accel(); + ADBSetRelMouseMode(mouse_grabbed = false); + } + } +} + +/* + * Initialization + */ + +// Init keycode translation table +static void keycode_init(void) +{ + bool use_kc = PrefsFindBool("keycodes"); + if (use_kc) { + + // Get keycode file path from preferences + const char *kc_path = PrefsFindString("keycodefile"); + + // Open keycode table + FILE *f = fopen(kc_path ? kc_path : KEYCODE_FILE_NAME, "r"); + if (f == NULL) { + char str[256]; + snprintf(str, sizeof(str), GetString(STR_KEYCODE_FILE_WARN), kc_path ? kc_path : KEYCODE_FILE_NAME, strerror(errno)); + WarningAlert(str); + return; + } + + // Default translation table + for (int i=0; i<256; i++) + keycode_table[i] = -1; + + // Search for server vendor string, then read keycodes + char video_driver[256]; + SDL_VideoDriverName(video_driver, sizeof(video_driver)); + bool video_driver_found = false; + char line[256]; + int n_keys = 0; + while (fgets(line, sizeof(line) - 1, f)) { + // Read line + int len = strlen(line); + if (len == 0) + continue; + line[len-1] = 0; + + // Comments begin with "#" or ";" + if (line[0] == '#' || line[0] == ';' || line[0] == 0) + continue; + + if (video_driver_found) { + // Skip aliases as long as we have read keycodes yet + // Otherwise, it's another mapping and we have to stop + static const char sdl_str[] = "sdl"; + if (strncmp(line, sdl_str, sizeof(sdl_str) - 1) == 0 && n_keys == 0) + continue; + + // Read keycode + int x_code, mac_code; + if (sscanf(line, "%d %d", &x_code, &mac_code) == 2) + keycode_table[x_code & 0xff] = mac_code, n_keys++; + else + break; + } else { + // Search for SDL video driver string + static const char sdl_str[] = "sdl"; + if (strncmp(line, sdl_str, sizeof(sdl_str) - 1) == 0) { + char *p = line + sizeof(sdl_str); + if (strstr(video_driver, p) == video_driver) + video_driver_found = true; + } + } + } + + // Keycode file completely read + fclose(f); + use_keycodes = video_driver_found; + + // Vendor not found? Then display warning + if (!video_driver_found) { + char str[256]; + snprintf(str, sizeof(str), GetString(STR_KEYCODE_VENDOR_WARN), video_driver, kc_path ? kc_path : KEYCODE_FILE_NAME); + WarningAlert(str); + return; + } + + D(bug("Using SDL/%s keycodes table, %d key mappings\n", video_driver, n_keys)); + } +} + +// Open display for current mode +bool SDL_monitor_desc::video_open(void) +{ + D(bug("video_open()\n")); +#if DEBUG + const VIDEO_MODE &mode = get_current_mode(); + D(bug("Current video mode:\n")); + D(bug(" %dx%d (ID %02x), %d bpp\n", VIDEO_MODE_X, VIDEO_MODE_Y, VIDEO_MODE_RESOLUTION, 1 << (VIDEO_MODE_DEPTH & 0x0f))); +#endif + + // Create display driver object of requested type + drv = new(std::nothrow) driver_base(*this); + if (drv == NULL) + return false; + drv->init(); + if (!drv->init_ok) { + delete drv; + drv = NULL; + return false; + } + +#ifdef WIN32 + // Chain in a new message handler for WM_DEVICECHANGE + HWND the_window = GetMainWindowHandle(); + sdl_window_proc = (WNDPROC)GetWindowLongPtr(the_window, GWLP_WNDPROC); + SetWindowLongPtr(the_window, GWLP_WNDPROC, (LONG_PTR)windows_message_handler); +#endif + + // Initialize VideoRefresh function + VideoRefreshInit(); + + // Lock down frame buffer + LOCK_FRAME_BUFFER; + + // Start redraw/input thread +#ifndef USE_CPU_EMUL_SERVICES + redraw_thread_cancel = false; + redraw_thread_active = ((redraw_thread = SDL_CreateThread(redraw_func, NULL)) != NULL); + if (!redraw_thread_active) { + printf("FATAL: cannot create redraw thread\n"); + return false; + } +#else + redraw_thread_active = true; +#endif + return true; +} + +#ifdef SHEEPSHAVER +bool VideoInit(void) +{ + const bool classic = false; +#else +bool VideoInit(bool classic) +{ +#endif + classic_mode = classic; + +#ifdef ENABLE_VOSF + // Zero the mainBuffer structure + mainBuffer.dirtyPages = NULL; + mainBuffer.pageInfo = NULL; +#endif + + // Create Mutexes + if ((sdl_events_lock = SDL_CreateMutex()) == NULL) + return false; + if ((sdl_palette_lock = SDL_CreateMutex()) == NULL) + return false; + if ((frame_buffer_lock = SDL_CreateMutex()) == NULL) + return false; + + // Init keycode translation + keycode_init(); + + // Read prefs + frame_skip = PrefsFindInt32("frameskip"); + mouse_wheel_mode = PrefsFindInt32("mousewheelmode"); + mouse_wheel_lines = PrefsFindInt32("mousewheellines"); + + // Get screen mode from preferences + migrate_screen_prefs(); + const char *mode_str = NULL; + if (classic_mode) + mode_str = "win/512/342"; + else + mode_str = PrefsFindString("screen"); + + // Determine display type and default dimensions + int default_width, default_height; + if (classic) { + default_width = 512; + default_height = 384; + } + else { + default_width = 640; + default_height = 480; + } + display_type = DISPLAY_WINDOW; + if (mode_str) { + if (sscanf(mode_str, "win/%d/%d", &default_width, &default_height) == 2) + display_type = DISPLAY_WINDOW; + else if (sscanf(mode_str, "dga/%d/%d", &default_width, &default_height) == 2) + display_type = DISPLAY_SCREEN; + } + if (default_width <= 0) + default_width = sdl_display_width(); + else if (default_width > sdl_display_width()) + default_width = sdl_display_width(); + if (default_height <= 0) + default_height = sdl_display_height(); + else if (default_height > sdl_display_height()) + default_height = sdl_display_height(); + + // Mac screen depth follows X depth + screen_depth = SDL_GetVideoInfo()->vfmt->BitsPerPixel; + int default_depth; + switch (screen_depth) { + case 8: + default_depth = VIDEO_DEPTH_8BIT; + break; + case 15: case 16: + default_depth = VIDEO_DEPTH_16BIT; + break; + case 24: case 32: + default_depth = VIDEO_DEPTH_32BIT; + break; + default: + default_depth = VIDEO_DEPTH_1BIT; + break; + } + + // Initialize list of video modes to try + struct { + int w; + int h; + int resolution_id; + } + video_modes[] = { + { -1, -1, 0x80 }, + { 512, 384, 0x80 }, + { 640, 480, 0x81 }, + { 800, 600, 0x82 }, + { 1024, 768, 0x83 }, + { 1152, 870, 0x84 }, + { 1280, 1024, 0x85 }, + { 1600, 1200, 0x86 }, + { 0, } + }; + video_modes[0].w = default_width; + video_modes[0].h = default_height; + + // Construct list of supported modes + if (display_type == DISPLAY_WINDOW) { + if (classic) + add_mode(display_type, 512, 342, 0x80, 64, VIDEO_DEPTH_1BIT); + else { + for (int i = 0; video_modes[i].w != 0; i++) { + const int w = video_modes[i].w; + const int h = video_modes[i].h; + if (i > 0 && (w >= default_width || h >= default_height)) + continue; + for (int d = VIDEO_DEPTH_1BIT; d <= default_depth; d++) + add_mode(display_type, w, h, video_modes[i].resolution_id, TrivialBytesPerRow(w, (video_depth)d), d); + } + } + } else if (display_type == DISPLAY_SCREEN) { + for (int i = 0; video_modes[i].w != 0; i++) { + const int w = video_modes[i].w; + const int h = video_modes[i].h; + if (i > 0 && (w >= default_width || h >= default_height)) + continue; + if (w == 512 && h == 384) + continue; + for (int d = VIDEO_DEPTH_1BIT; d <= default_depth; d++) + add_mode(display_type, w, h, video_modes[i].resolution_id, TrivialBytesPerRow(w, (video_depth)d), d); + } + } + + if (VideoModes.empty()) { + ErrorAlert(STR_NO_XVISUAL_ERR); + return false; + } + + // Find requested default mode with specified dimensions + uint32 default_id; + std::vector::const_iterator i, end = VideoModes.end(); + for (i = VideoModes.begin(); i != end; ++i) { + const VIDEO_MODE & mode = (*i); + if (VIDEO_MODE_X == default_width && VIDEO_MODE_Y == default_height && VIDEO_MODE_DEPTH == default_depth) { + default_id = VIDEO_MODE_RESOLUTION; +#ifdef SHEEPSHAVER + std::vector::const_iterator begin = VideoModes.begin(); + cur_mode = distance(begin, i); +#endif + break; + } + } + if (i == end) { // not found, use first available mode + const VIDEO_MODE & mode = VideoModes[0]; + default_depth = VIDEO_MODE_DEPTH; + default_id = VIDEO_MODE_RESOLUTION; +#ifdef SHEEPSHAVER + cur_mode = 0; +#endif + } + +#ifdef SHEEPSHAVER + for (int i = 0; i < VideoModes.size(); i++) + VModes[i] = VideoModes[i]; + VideoInfo *p = &VModes[VideoModes.size()]; + p->viType = DIS_INVALID; // End marker + p->viRowBytes = 0; + p->viXsize = p->viYsize = 0; + p->viAppleMode = 0; + p->viAppleID = 0; +#endif + +#if DEBUG + D(bug("Available video modes:\n")); + for (i = VideoModes.begin(); i != end; ++i) { + const VIDEO_MODE & mode = (*i); + int bits = 1 << VIDEO_MODE_DEPTH; + if (bits == 16) + bits = 15; + else if (bits == 32) + bits = 24; + D(bug(" %dx%d (ID %02x), %d colors\n", VIDEO_MODE_X, VIDEO_MODE_Y, VIDEO_MODE_RESOLUTION, 1 << bits)); + } +#endif + + int color_depth = get_customized_color_depth(default_depth); + + D(bug("Return get_customized_color_depth %d\n", color_depth)); + + // Create SDL_monitor_desc for this (the only) display + SDL_monitor_desc *monitor = new SDL_monitor_desc(VideoModes, (video_depth)color_depth, default_id); + VideoMonitors.push_back(monitor); + + // Open display + return monitor->video_open(); +} + + +/* + * Deinitialization + */ + +// Close display +void SDL_monitor_desc::video_close(void) +{ + D(bug("video_close()\n")); + +#ifdef WIN32 + // Remove message handler for WM_DEVICECHANGE + HWND the_window = GetMainWindowHandle(); + SetWindowLongPtr(the_window, GWLP_WNDPROC, (LONG_PTR)sdl_window_proc); +#endif + + // Stop redraw thread +#ifndef USE_CPU_EMUL_SERVICES + if (redraw_thread_active) { + redraw_thread_cancel = true; + SDL_WaitThread(redraw_thread, NULL); + } +#endif + redraw_thread_active = false; + + // Unlock frame buffer + UNLOCK_FRAME_BUFFER; + D(bug(" frame buffer unlocked\n")); + + // Close display + delete drv; + drv = NULL; +} + +void VideoExit(void) +{ + // Close displays + vector::iterator i, end = VideoMonitors.end(); + for (i = VideoMonitors.begin(); i != end; ++i) + dynamic_cast(*i)->video_close(); + + // Destroy locks + if (frame_buffer_lock) + SDL_DestroyMutex(frame_buffer_lock); + if (sdl_palette_lock) + SDL_DestroyMutex(sdl_palette_lock); + if (sdl_events_lock) + SDL_DestroyMutex(sdl_events_lock); +} + + +/* + * Close down full-screen mode (if bringing up error alerts is unsafe while in full-screen mode) + */ + +void VideoQuitFullScreen(void) +{ + D(bug("VideoQuitFullScreen()\n")); + quit_full_screen = true; +} + +static void do_toggle_fullscreen(void) +{ +#ifndef USE_CPU_EMUL_SERVICES + // pause redraw thread + thread_stop_ack = false; + thread_stop_req = true; + while (!thread_stop_ack) ; +#endif + + // save the mouse position + int x, y; + SDL_GetMouseState(&x, &y); + + // save the screen contents + SDL_Surface *tmp_surface = SDL_ConvertSurface(drv->s, drv->s->format, + drv->s->flags); + + // switch modes + display_type = (display_type == DISPLAY_SCREEN) ? DISPLAY_WINDOW + : DISPLAY_SCREEN; + drv->set_video_mode(display_type == DISPLAY_SCREEN ? SDL_FULLSCREEN : 0); + drv->adapt_to_video_mode(); + + // reset the palette +#ifdef SHEEPSHAVER + video_set_palette(); +#endif + drv->update_palette(); + + // restore the screen contents + SDL_BlitSurface(tmp_surface, NULL, drv->s, NULL); + SDL_FreeSurface(tmp_surface); + SDL_UpdateRect(drv->s, 0, 0, 0, 0); + + // reset the video refresh handler + VideoRefreshInit(); + + // while SetVideoMode is happening, control key up may be missed + ADBKeyUp(0x36); + + // restore the mouse position + SDL_WarpMouse(x, y); + + // resume redraw thread + toggle_fullscreen = false; +#ifndef USE_CPU_EMUL_SERVICES + thread_stop_req = false; +#endif +} + +/* + * Mac VBL interrupt + */ + +/* + * Execute video VBL routine + */ + +#ifdef SHEEPSHAVER +void VideoVBL(void) +{ + // Emergency quit requested? Then quit + if (emerg_quit) + QuitEmulator(); + + if (toggle_fullscreen) + do_toggle_fullscreen(); + + // Temporarily give up frame buffer lock (this is the point where + // we are suspended when the user presses Ctrl-Tab) + UNLOCK_FRAME_BUFFER; + LOCK_FRAME_BUFFER; + + // Execute video VBL + if (private_data != NULL && private_data->interruptsEnabled) + VSLDoInterruptService(private_data->vslServiceID); +} +#else +void VideoInterrupt(void) +{ + // We must fill in the events queue in the same thread that did call SDL_SetVideoMode() + SDL_PumpEvents(); + + // Emergency quit requested? Then quit + if (emerg_quit) + QuitEmulator(); + + if (toggle_fullscreen) + do_toggle_fullscreen(); + + // Temporarily give up frame buffer lock (this is the point where + // we are suspended when the user presses Ctrl-Tab) + UNLOCK_FRAME_BUFFER; + LOCK_FRAME_BUFFER; +} +#endif + + +/* + * Set palette + */ + +#ifdef SHEEPSHAVER +void video_set_palette(void) +{ + monitor_desc * monitor = VideoMonitors[0]; + int n_colors = palette_size(monitor->get_current_mode().viAppleMode); + uint8 pal[256 * 3]; + for (int c = 0; c < n_colors; c++) { + pal[c*3 + 0] = mac_pal[c].red; + pal[c*3 + 1] = mac_pal[c].green; + pal[c*3 + 2] = mac_pal[c].blue; + } + monitor->set_palette(pal, n_colors); +} +#endif + +void SDL_monitor_desc::set_palette(uint8 *pal, int num_in) +{ + const VIDEO_MODE &mode = get_current_mode(); + + // FIXME: how can we handle the gamma ramp? + if ((int)VIDEO_MODE_DEPTH > VIDEO_DEPTH_8BIT) + return; + + LOCK_PALETTE; + + // Convert colors to XColor array + int num_out = 256; + bool stretch = false; + SDL_Color *p = sdl_palette; + for (int i=0; ir = pal[c*3 + 0] * 0x0101; + p->g = pal[c*3 + 1] * 0x0101; + p->b = pal[c*3 + 2] * 0x0101; + p++; + } + + // Recalculate pixel color expansion map + if (!IsDirectMode(mode)) { + for (int i=0; i<256; i++) { + int c = i & (num_in-1); // If there are less than 256 colors, we repeat the first entries (this makes color expansion easier) + ExpandMap[i] = SDL_MapRGB(drv->s->format, pal[c*3+0], pal[c*3+1], pal[c*3+2]); + } + +#ifdef ENABLE_VOSF + if (use_vosf) { + // We have to redraw everything because the interpretation of pixel values changed + LOCK_VOSF; + PFLAG_SET_ALL; + UNLOCK_VOSF; + memset(the_buffer_copy, 0, VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y); + } +#endif + } + + // Tell redraw thread to change palette + sdl_palette_changed = true; + + UNLOCK_PALETTE; +} + + +/* + * Switch video mode + */ + +#ifdef SHEEPSHAVER +int16 video_mode_change(VidLocals *csSave, uint32 ParamPtr) +{ + /* return if no mode change */ + if ((csSave->saveData == ReadMacInt32(ParamPtr + csData)) && + (csSave->saveMode == ReadMacInt16(ParamPtr + csMode))) return noErr; + + /* first find video mode in table */ + for (int i=0; VModes[i].viType != DIS_INVALID; i++) { + if ((ReadMacInt16(ParamPtr + csMode) == VModes[i].viAppleMode) && + (ReadMacInt32(ParamPtr + csData) == VModes[i].viAppleID)) { + csSave->saveMode = ReadMacInt16(ParamPtr + csMode); + csSave->saveData = ReadMacInt32(ParamPtr + csData); + csSave->savePage = ReadMacInt16(ParamPtr + csPage); + + // Disable interrupts and pause redraw thread + DisableInterrupt(); + thread_stop_ack = false; + thread_stop_req = true; + while (!thread_stop_ack) ; + + cur_mode = i; + monitor_desc *monitor = VideoMonitors[0]; + monitor->switch_to_current_mode(); + + WriteMacInt32(ParamPtr + csBaseAddr, screen_base); + csSave->saveBaseAddr=screen_base; + csSave->saveData=VModes[cur_mode].viAppleID;/* First mode ... */ + csSave->saveMode=VModes[cur_mode].viAppleMode; + + // Enable interrupts and resume redraw thread + thread_stop_req = false; + EnableInterrupt(); + return noErr; + } + } + return paramErr; +} +#endif + +void SDL_monitor_desc::switch_to_current_mode(void) +{ + // Close and reopen display + LOCK_EVENTS; + video_close(); + video_open(); + UNLOCK_EVENTS; + + if (drv == NULL) { + ErrorAlert(STR_OPEN_WINDOW_ERR); + QuitEmulator(); + } +} + + +/* + * Can we set the MacOS cursor image into the window? + */ + +#ifdef SHEEPSHAVER +bool video_can_change_cursor(void) +{ + if (display_type != DISPLAY_WINDOW) + return false; + +#if defined(__APPLE__) + static char driver[] = "Quartz?"; + static int quartzok = -1; + + if (quartzok < 0) { + if (SDL_VideoDriverName(driver, sizeof driver) == NULL || strncmp(driver, "Quartz", sizeof driver)) + quartzok = true; + else { + // Quartz driver bug prevents cursor changing in SDL 1.2.11 to 1.2.14. + const SDL_version *vp = SDL_Linked_Version(); + int version = SDL_VERSIONNUM(vp->major, vp->minor, vp->patch); + quartzok = (version <= SDL_VERSIONNUM(1, 2, 10) || version >= SDL_VERSIONNUM(1, 2, 15)); + } + } + + return quartzok; +#else + return true; +#endif +} +#endif + + +/* + * Set cursor image for window + */ + +#ifdef SHEEPSHAVER +void video_set_cursor(void) +{ + // Set new cursor image if it was changed + if (sdl_cursor) { + SDL_FreeCursor(sdl_cursor); + sdl_cursor = SDL_CreateCursor(MacCursor + 4, MacCursor + 36, 16, 16, MacCursor[2], MacCursor[3]); + if (sdl_cursor) { + SDL_ShowCursor(private_data == NULL || private_data->cursorVisible); + SDL_SetCursor(sdl_cursor); + + // XXX Windows apparently needs an extra mouse event to + // make the new cursor image visible. + // On Mac, if mouse is grabbed, SDL_ShowCursor() recenters the + // mouse, we have to put it back. + bool move = false; +#ifdef WIN32 + move = true; +#elif defined(__APPLE__) + move = mouse_grabbed; +#endif + if (move) { + int visible = SDL_ShowCursor(-1); + if (visible) { + int x, y; + SDL_GetMouseState(&x, &y); + SDL_WarpMouse(x, y); + } + } + } + } +} +#endif + + +/* + * Keyboard-related utilify functions + */ + +static bool is_modifier_key(SDL_KeyboardEvent const & e) +{ + switch (e.keysym.sym) { + case SDLK_NUMLOCK: + case SDLK_CAPSLOCK: + case SDLK_SCROLLOCK: + case SDLK_RSHIFT: + case SDLK_LSHIFT: + case SDLK_RCTRL: + case SDLK_LCTRL: + case SDLK_RALT: + case SDLK_LALT: + case SDLK_RMETA: + case SDLK_LMETA: + case SDLK_LSUPER: + case SDLK_RSUPER: + case SDLK_MODE: + case SDLK_COMPOSE: + return true; + } + return false; +} + +static bool is_ctrl_down(SDL_keysym const & ks) +{ + return ctrl_down || (ks.mod & KMOD_CTRL); +} + + +/* + * Translate key event to Mac keycode, returns -1 if no keycode was found + * and -2 if the key was recognized as a hotkey + */ + +static int kc_decode(SDL_keysym const & ks, bool key_down) +{ + switch (ks.sym) { + case SDLK_a: return 0x00; + case SDLK_b: return 0x0b; + case SDLK_c: return 0x08; + case SDLK_d: return 0x02; + case SDLK_e: return 0x0e; + case SDLK_f: return 0x03; + case SDLK_g: return 0x05; + case SDLK_h: return 0x04; + case SDLK_i: return 0x22; + case SDLK_j: return 0x26; + case SDLK_k: return 0x28; + case SDLK_l: return 0x25; + case SDLK_m: return 0x2e; + case SDLK_n: return 0x2d; + case SDLK_o: return 0x1f; + case SDLK_p: return 0x23; + case SDLK_q: return 0x0c; + case SDLK_r: return 0x0f; + case SDLK_s: return 0x01; + case SDLK_t: return 0x11; + case SDLK_u: return 0x20; + case SDLK_v: return 0x09; + case SDLK_w: return 0x0d; + case SDLK_x: return 0x07; + case SDLK_y: return 0x10; + case SDLK_z: return 0x06; + + case SDLK_1: case SDLK_EXCLAIM: return 0x12; + case SDLK_2: case SDLK_AT: return 0x13; + case SDLK_3: case SDLK_HASH: return 0x14; + case SDLK_4: case SDLK_DOLLAR: return 0x15; + case SDLK_5: return 0x17; + case SDLK_6: return 0x16; + case SDLK_7: return 0x1a; + case SDLK_8: return 0x1c; + case SDLK_9: return 0x19; + case SDLK_0: return 0x1d; + + case SDLK_BACKQUOTE: return 0x0a; + case SDLK_MINUS: case SDLK_UNDERSCORE: return 0x1b; + case SDLK_EQUALS: case SDLK_PLUS: return 0x18; + case SDLK_LEFTBRACKET: return 0x21; + case SDLK_RIGHTBRACKET: return 0x1e; + case SDLK_BACKSLASH: return 0x2a; + case SDLK_SEMICOLON: case SDLK_COLON: return 0x29; + case SDLK_QUOTE: case SDLK_QUOTEDBL: return 0x27; + case SDLK_COMMA: case SDLK_LESS: return 0x2b; + case SDLK_PERIOD: case SDLK_GREATER: return 0x2f; + case SDLK_SLASH: case SDLK_QUESTION: return 0x2c; + + case SDLK_TAB: if (is_ctrl_down(ks)) {if (!key_down) drv->suspend(); return -2;} else return 0x30; + case SDLK_RETURN: if (is_ctrl_down(ks)) {if (!key_down) toggle_fullscreen = true; return -2;} else return 0x24; + case SDLK_SPACE: return 0x31; + case SDLK_BACKSPACE: return 0x33; + + case SDLK_DELETE: return 0x75; + case SDLK_INSERT: return 0x72; + case SDLK_HOME: case SDLK_HELP: return 0x73; + case SDLK_END: return 0x77; + case SDLK_PAGEUP: return 0x74; + case SDLK_PAGEDOWN: return 0x79; + + case SDLK_LCTRL: return 0x36; + case SDLK_RCTRL: return 0x36; + case SDLK_LSHIFT: return 0x38; + case SDLK_RSHIFT: return 0x38; +#if (defined(__APPLE__) && defined(__MACH__)) + case SDLK_LALT: return 0x3a; + case SDLK_RALT: return 0x3a; + case SDLK_LMETA: return 0x37; + case SDLK_RMETA: return 0x37; +#else + case SDLK_LALT: return 0x37; + case SDLK_RALT: return 0x37; + case SDLK_LMETA: return 0x3a; + case SDLK_RMETA: return 0x3a; +#endif + case SDLK_LSUPER: return 0x3a; // "Windows" key + case SDLK_RSUPER: return 0x3a; + case SDLK_MENU: return 0x32; + case SDLK_CAPSLOCK: return 0x39; + case SDLK_NUMLOCK: return 0x47; + + case SDLK_UP: return 0x3e; + case SDLK_DOWN: return 0x3d; + case SDLK_LEFT: return 0x3b; + case SDLK_RIGHT: return 0x3c; + + case SDLK_ESCAPE: if (is_ctrl_down(ks)) {if (!key_down) { quit_full_screen = true; emerg_quit = true; } return -2;} else return 0x35; + + case SDLK_F1: if (is_ctrl_down(ks)) {if (!key_down) SysMountFirstFloppy(); return -2;} else return 0x7a; + case SDLK_F2: return 0x78; + case SDLK_F3: return 0x63; + case SDLK_F4: return 0x76; + case SDLK_F5: if (is_ctrl_down(ks)) {if (!key_down) drv->toggle_mouse_grab(); return -2;} else return 0x60; + case SDLK_F6: return 0x61; + case SDLK_F7: return 0x62; + case SDLK_F8: return 0x64; + case SDLK_F9: return 0x65; + case SDLK_F10: return 0x6d; + case SDLK_F11: return 0x67; + case SDLK_F12: return 0x6f; + + case SDLK_PRINT: return 0x69; + case SDLK_SCROLLOCK: return 0x6b; + case SDLK_PAUSE: return 0x71; + + case SDLK_KP0: return 0x52; + case SDLK_KP1: return 0x53; + case SDLK_KP2: return 0x54; + case SDLK_KP3: return 0x55; + case SDLK_KP4: return 0x56; + case SDLK_KP5: return 0x57; + case SDLK_KP6: return 0x58; + case SDLK_KP7: return 0x59; + case SDLK_KP8: return 0x5b; + case SDLK_KP9: return 0x5c; + case SDLK_KP_PERIOD: return 0x41; + case SDLK_KP_PLUS: return 0x45; + case SDLK_KP_MINUS: return 0x4e; + case SDLK_KP_MULTIPLY: return 0x43; + case SDLK_KP_DIVIDE: return 0x4b; + case SDLK_KP_ENTER: return 0x4c; + case SDLK_KP_EQUALS: return 0x51; + } + D(bug("Unhandled SDL keysym: %d\n", ks.sym)); + return -1; +} + +static int event2keycode(SDL_KeyboardEvent const &ev, bool key_down) +{ + return kc_decode(ev.keysym, key_down); +} + +static void force_complete_window_refresh() +{ + if (display_type == DISPLAY_WINDOW) { +#ifdef ENABLE_VOSF + if (use_vosf) { // VOSF refresh + LOCK_VOSF; + PFLAG_SET_ALL; + UNLOCK_VOSF; + } +#endif + // Ensure each byte of the_buffer_copy differs from the_buffer to force a full update. + const VIDEO_MODE &mode = VideoMonitors[0]->get_current_mode(); + const int len = VIDEO_MODE_ROW_BYTES * VIDEO_MODE_Y; + for (int i = 0; i < len; i++) + the_buffer_copy[i] = !the_buffer[i]; + } +} + +/* + * SDL event handling + */ + +static void handle_events(void) +{ + SDL_Event events[10]; + const int n_max_events = sizeof(events) / sizeof(events[0]); + int n_events; + + while ((n_events = SDL_PeepEvents(events, n_max_events, SDL_GETEVENT, sdl_eventmask)) > 0) { + for (int i = 0; i < n_events; i++) { + SDL_Event const & event = events[i]; + switch (event.type) { + + // Mouse button + case SDL_MOUSEBUTTONDOWN: { + unsigned int button = event.button.button; + if (button == SDL_BUTTON_LEFT) + ADBMouseDown(0); + else if (button == SDL_BUTTON_RIGHT) + ADBMouseDown(1); + else if (button == SDL_BUTTON_MIDDLE) + ADBMouseDown(2); + else if (button < 6) { // Wheel mouse + if (mouse_wheel_mode == 0) { + int key = (button == 5) ? 0x79 : 0x74; // Page up/down + ADBKeyDown(key); + ADBKeyUp(key); + } else { + int key = (button == 5) ? 0x3d : 0x3e; // Cursor up/down + for(int i=0; imouse_moved(event.motion.xrel, event.motion.yrel); + } else { + drv->mouse_moved(event.motion.x, event.motion.y); + } + break; + + // Keyboard + case SDL_KEYDOWN: { + int code = -1; + if (use_keycodes && !is_modifier_key(event.key)) { + if (event2keycode(event.key, true) != -2) // This is called to process the hotkeys + code = keycode_table[event.key.keysym.scancode & 0xff]; + } else + code = event2keycode(event.key, true); + if (code >= 0) { + if (!emul_suspended) { + if (code == 0x39) { // Caps Lock pressed + if (caps_on) { + ADBKeyUp(code); + caps_on = false; + } else { + ADBKeyDown(code); + caps_on = true; + } + } else + ADBKeyDown(code); + if (code == 0x36) + ctrl_down = true; + } else { + if (code == 0x31) + drv->resume(); // Space wakes us up + } + } + break; + } + case SDL_KEYUP: { + int code = -1; + if (use_keycodes && !is_modifier_key(event.key)) { + if (event2keycode(event.key, false) != -2) // This is called to process the hotkeys + code = keycode_table[event.key.keysym.scancode & 0xff]; + } else + code = event2keycode(event.key, false); + if (code >= 0) { + if (code == 0x39) { // Caps Lock released + if (caps_on) { + ADBKeyUp(code); + caps_on = false; + } else { + ADBKeyDown(code); + caps_on = true; + } + } else + ADBKeyUp(code); + if (code == 0x36) + ctrl_down = false; + } + break; + } + + // Hidden parts exposed, force complete refresh of window + case SDL_VIDEOEXPOSE: + force_complete_window_refresh(); + break; + + // Window "close" widget clicked + case SDL_QUIT: + ADBKeyDown(0x7f); // Power key + ADBKeyUp(0x7f); + break; + + // Application activate/deactivate + case SDL_ACTIVEEVENT: + // Force a complete window refresh when activating, to avoid redraw artifacts otherwise. + if (event.active.gain && (event.active.state & SDL_APPACTIVE)) + force_complete_window_refresh(); + break; + } + } + } +} + + +/* + * Window display update + */ + +// Static display update (fixed frame rate, but incremental) +static void update_display_static(driver_base *drv) +{ + // Incremental update code + int wide = 0, high = 0; + uint32 x1, x2, y1, y2; + const VIDEO_MODE &mode = drv->mode; + int bytes_per_row = VIDEO_MODE_ROW_BYTES; + uint8 *p, *p2; + + // Check for first line from top and first line from bottom that have changed + y1 = 0; + for (uint32 j = 0; j < VIDEO_MODE_Y; j++) { + if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) { + y1 = j; + break; + } + } + y2 = y1 - 1; + for (uint32 j = VIDEO_MODE_Y; j-- > y1; ) { + if (memcmp(&the_buffer[j * bytes_per_row], &the_buffer_copy[j * bytes_per_row], bytes_per_row)) { + y2 = j; + break; + } + } + high = y2 - y1 + 1; + + // Check for first column from left and first column from right that have changed + if (high) { + if (VIDEO_MODE_DEPTH < VIDEO_DEPTH_8BIT) { + const int src_bytes_per_row = bytes_per_row; + const int dst_bytes_per_row = drv->s->pitch; + const int pixels_per_byte = VIDEO_MODE_X / src_bytes_per_row; + + x1 = VIDEO_MODE_X / pixels_per_byte; + for (uint32 j = y1; j <= y2; j++) { + p = &the_buffer[j * bytes_per_row]; + p2 = &the_buffer_copy[j * bytes_per_row]; + for (uint32 i = 0; i < x1; i++) { + if (*p != *p2) { + x1 = i; + break; + } + p++; p2++; + } + } + x2 = x1; + for (uint32 j = y1; j <= y2; j++) { + p = &the_buffer[j * bytes_per_row]; + p2 = &the_buffer_copy[j * bytes_per_row]; + p += bytes_per_row; + p2 += bytes_per_row; + for (uint32 i = (VIDEO_MODE_X / pixels_per_byte); i > x2; i--) { + p--; p2--; + if (*p != *p2) { + x2 = i; + break; + } + } + } + x1 *= pixels_per_byte; + x2 *= pixels_per_byte; + wide = (x2 - x1 + pixels_per_byte - 1) & -pixels_per_byte; + + // Update copy of the_buffer + if (high && wide) { + + // Lock surface, if required + if (SDL_MUSTLOCK(drv->s)) + SDL_LockSurface(drv->s); + + // Blit to screen surface + int si = y1 * src_bytes_per_row + (x1 / pixels_per_byte); + int di = y1 * dst_bytes_per_row + x1; + for (uint32 j = y1; j <= y2; j++) { + memcpy(the_buffer_copy + si, the_buffer + si, wide / pixels_per_byte); + Screen_blit((uint8 *)drv->s->pixels + di, the_buffer + si, wide / pixels_per_byte); + si += src_bytes_per_row; + di += dst_bytes_per_row; + } + + // Unlock surface, if required + if (SDL_MUSTLOCK(drv->s)) + SDL_UnlockSurface(drv->s); + + // Refresh display + SDL_UpdateRect(drv->s, x1, y1, wide, high); + } + + } else { + const int bytes_per_pixel = VIDEO_MODE_ROW_BYTES / VIDEO_MODE_X; + const int dst_bytes_per_row = drv->s->pitch; + + x1 = VIDEO_MODE_X; + for (uint32 j = y1; j <= y2; j++) { + p = &the_buffer[j * bytes_per_row]; + p2 = &the_buffer_copy[j * bytes_per_row]; + for (uint32 i = 0; i < x1 * bytes_per_pixel; i++) { + if (*p != *p2) { + x1 = i / bytes_per_pixel; + break; + } + p++; p2++; + } + } + x2 = x1; + for (uint32 j = y1; j <= y2; j++) { + p = &the_buffer[j * bytes_per_row]; + p2 = &the_buffer_copy[j * bytes_per_row]; + p += bytes_per_row; + p2 += bytes_per_row; + for (uint32 i = VIDEO_MODE_X * bytes_per_pixel; i > x2 * bytes_per_pixel; i--) { + p--; + p2--; + if (*p != *p2) { + x2 = i / bytes_per_pixel; + break; + } + } + } + wide = x2 - x1; + + // Update copy of the_buffer + if (high && wide) { + + // Lock surface, if required + if (SDL_MUSTLOCK(drv->s)) + SDL_LockSurface(drv->s); + + // Blit to screen surface + for (uint32 j = y1; j <= y2; j++) { + uint32 i = j * bytes_per_row + x1 * bytes_per_pixel; + int dst_i = j * dst_bytes_per_row + x1 * bytes_per_pixel; + memcpy(the_buffer_copy + i, the_buffer + i, bytes_per_pixel * wide); + Screen_blit((uint8 *)drv->s->pixels + dst_i, the_buffer + i, bytes_per_pixel * wide); + } + + // Unlock surface, if required + if (SDL_MUSTLOCK(drv->s)) + SDL_UnlockSurface(drv->s); + + // Refresh display + SDL_UpdateRect(drv->s, x1, y1, wide, high); + } + } + } +} + +// Static display update (fixed frame rate, bounding boxes based) +// XXX use NQD bounding boxes to help detect dirty areas? +static void update_display_static_bbox(driver_base *drv) +{ + const VIDEO_MODE &mode = drv->mode; + + // Allocate bounding boxes for SDL_UpdateRects() + const uint32 N_PIXELS = 64; + const uint32 n_x_boxes = (VIDEO_MODE_X + N_PIXELS - 1) / N_PIXELS; + const uint32 n_y_boxes = (VIDEO_MODE_Y + N_PIXELS - 1) / N_PIXELS; + SDL_Rect *boxes = (SDL_Rect *)alloca(sizeof(SDL_Rect) * n_x_boxes * n_y_boxes); + uint32 nr_boxes = 0; + + // Lock surface, if required + if (SDL_MUSTLOCK(drv->s)) + SDL_LockSurface(drv->s); + + // Update the surface from Mac screen + const uint32 bytes_per_row = VIDEO_MODE_ROW_BYTES; + const uint32 bytes_per_pixel = bytes_per_row / VIDEO_MODE_X; + const uint32 dst_bytes_per_row = drv->s->pitch; + for (uint32 y = 0; y < VIDEO_MODE_Y; y += N_PIXELS) { + uint32 h = N_PIXELS; + if (h > VIDEO_MODE_Y - y) + h = VIDEO_MODE_Y - y; + for (uint32 x = 0; x < VIDEO_MODE_X; x += N_PIXELS) { + uint32 w = N_PIXELS; + if (w > VIDEO_MODE_X - x) + w = VIDEO_MODE_X - x; + const int xs = w * bytes_per_pixel; + const int xb = x * bytes_per_pixel; + bool dirty = false; + for (uint32 j = y; j < (y + h); j++) { + const uint32 yb = j * bytes_per_row; + const uint32 dst_yb = j * dst_bytes_per_row; + if (memcmp(&the_buffer[yb + xb], &the_buffer_copy[yb + xb], xs) != 0) { + memcpy(&the_buffer_copy[yb + xb], &the_buffer[yb + xb], xs); + Screen_blit((uint8 *)drv->s->pixels + dst_yb + xb, the_buffer + yb + xb, xs); + dirty = true; + } + } + if (dirty) { + boxes[nr_boxes].x = x; + boxes[nr_boxes].y = y; + boxes[nr_boxes].w = w; + boxes[nr_boxes].h = h; + nr_boxes++; + } + } + } + + // Unlock surface, if required + if (SDL_MUSTLOCK(drv->s)) + SDL_UnlockSurface(drv->s); + + // Refresh display + if (nr_boxes) + SDL_UpdateRects(drv->s, nr_boxes, boxes); +} + + +// We suggest the compiler to inline the next two functions so that it +// may specialise the code according to the current screen depth and +// display type. A clever compiler would do that job by itself though... + +// NOTE: update_display_vosf is inlined too + +static inline void possibly_quit_dga_mode() +{ + // Quit DGA mode if requested (something terrible has happened and we + // want to give control back to the user) + if (quit_full_screen) { + quit_full_screen = false; + delete drv; + drv = NULL; + } +} + +static inline void possibly_ungrab_mouse() +{ + // Ungrab mouse if requested (something terrible has happened and we + // want to give control back to the user) + if (quit_full_screen) { + quit_full_screen = false; + if (drv) + drv->ungrab_mouse(); + } +} + +static inline void handle_palette_changes(void) +{ + LOCK_PALETTE; + + if (sdl_palette_changed) { + sdl_palette_changed = false; + drv->update_palette(); + } + + UNLOCK_PALETTE; +} + +static void video_refresh_window_static(void); + +static void video_refresh_dga(void) +{ + // Quit DGA mode if requested + possibly_quit_dga_mode(); + video_refresh_window_static(); +} + +#ifdef ENABLE_VOSF +#if REAL_ADDRESSING || DIRECT_ADDRESSING +static void video_refresh_dga_vosf(void) +{ + // Quit DGA mode if requested + possibly_quit_dga_mode(); + + // Update display (VOSF variant) + static uint32 tick_counter = 0; + if (++tick_counter >= frame_skip) { + tick_counter = 0; + if (mainBuffer.dirty) { + LOCK_VOSF; + update_display_dga_vosf(drv); + UNLOCK_VOSF; + } + } +} +#endif + +static void video_refresh_window_vosf(void) +{ + // Ungrab mouse if requested + possibly_ungrab_mouse(); + + // Update display (VOSF variant) + static uint32 tick_counter = 0; + if (++tick_counter >= frame_skip) { + tick_counter = 0; + if (mainBuffer.dirty) { + LOCK_VOSF; + update_display_window_vosf(drv); + UNLOCK_VOSF; + } + } +} +#endif // def ENABLE_VOSF + +static void video_refresh_window_static(void) +{ + // Ungrab mouse if requested + possibly_ungrab_mouse(); + + // Update display (static variant) + static uint32 tick_counter = 0; + if (++tick_counter >= frame_skip) { + tick_counter = 0; + const VIDEO_MODE &mode = drv->mode; + if ((int)VIDEO_MODE_DEPTH >= VIDEO_DEPTH_8BIT) + update_display_static_bbox(drv); + else + update_display_static(drv); + } +} + + +/* + * Thread for screen refresh, input handling etc. + */ + +static void VideoRefreshInit(void) +{ + // TODO: set up specialised 8bpp VideoRefresh handlers ? + if (display_type == DISPLAY_SCREEN) { +#if ENABLE_VOSF && (REAL_ADDRESSING || DIRECT_ADDRESSING) + if (use_vosf) + video_refresh = video_refresh_dga_vosf; + else +#endif + video_refresh = video_refresh_dga; + } + else { +#ifdef ENABLE_VOSF + if (use_vosf) + video_refresh = video_refresh_window_vosf; + else +#endif + video_refresh = video_refresh_window_static; + } +} + +static inline void do_video_refresh(void) +{ + // Handle SDL events + handle_events(); + + // Update display + video_refresh(); + + + // Set new palette if it was changed + handle_palette_changes(); +} + +// This function is called on non-threaded platforms from a timer interrupt +void VideoRefresh(void) +{ + // We need to check redraw_thread_active to inhibit refreshed during + // mode changes on non-threaded platforms + if (!redraw_thread_active) + return; + + // Process pending events and update display + do_video_refresh(); +} + +const int VIDEO_REFRESH_HZ = 60; +const int VIDEO_REFRESH_DELAY = 1000000 / VIDEO_REFRESH_HZ; + +#ifndef USE_CPU_EMUL_SERVICES +static int redraw_func(void *arg) +{ + uint64 start = GetTicks_usec(); + int64 ticks = 0; + uint64 next = GetTicks_usec() + VIDEO_REFRESH_DELAY; + + while (!redraw_thread_cancel) { + + // Wait + next += VIDEO_REFRESH_DELAY; + int32 delay = int32(next - GetTicks_usec()); + if (delay > 0) + Delay_usec(delay); + else if (delay < -VIDEO_REFRESH_DELAY) + next = GetTicks_usec(); + ticks++; + + // Pause if requested (during video mode switches) + if (thread_stop_req) { + thread_stop_ack = true; + continue; + } + + // Process pending events and update display + do_video_refresh(); + } + + uint64 end = GetTicks_usec(); + D(bug("%lld refreshes in %lld usec = %f refreshes/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start))); + return 0; +} +#endif + + +/* + * Record dirty area from NQD + */ + +#ifdef SHEEPSHAVER +void video_set_dirty_area(int x, int y, int w, int h) +{ +#ifdef ENABLE_VOSF + const VIDEO_MODE &mode = drv->mode; + const unsigned screen_width = VIDEO_MODE_X; + const unsigned screen_height = VIDEO_MODE_Y; + const unsigned bytes_per_row = VIDEO_MODE_ROW_BYTES; + + if (use_vosf) { + vosf_set_dirty_area(x, y, w, h, screen_width, screen_height, bytes_per_row); + return; + } +#endif + + // XXX handle dirty bounding boxes for non-VOSF modes +} +#endif diff --git a/SheepShaver/src/Unix/Darwin/lowmem.c b/SheepShaver/src/Unix/Darwin/lowmem.c new file mode 100755 index 00000000..a40a3661 --- /dev/null +++ b/SheepShaver/src/Unix/Darwin/lowmem.c @@ -0,0 +1,254 @@ +/* + * lowmem.c - enable access to low memory globals on Darwin + * + * Copyright (c) 2003 Michael Z. Sliczniak + * + * Basilisk II (C) 1997-2005 Christian Bauer + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char progname[] = "lowmem"; +static const char *filename; + +static int do_swap = 0; + +static uint32_t target_uint32(uint32_t value) +{ + if (do_swap) + value = OSSwapInt32(value); + return value; +} + +void pagezero_32(struct mach_header *machhead) +{ + struct segment_command *sc_cmd; + + if (target_uint32(machhead->filetype) != MH_EXECUTE) { + (void)fprintf(stderr, "%s: %s does not appear to be an executable file\n", + progname, filename); + exit(1); + } + if (machhead->ncmds == 0) { + (void)fprintf(stderr, "%s: %s does not contain any load commands\n", + progname, filename); + exit(1); + } + sc_cmd = (void *)&machhead[1]; + if (target_uint32(sc_cmd->cmd) != LC_SEGMENT){ + (void)fprintf(stderr, "%s: load segment not first command in %s\n", + progname, filename); + exit(1); + } + if (strncmp(sc_cmd->segname, "__PAGEZERO", sizeof (*sc_cmd->segname))) { + (void)fprintf(stderr, "%s: zero page not first segment in %s\n", + progname, filename); + exit(1); + } + /* change the permissions */ + sc_cmd->maxprot = target_uint32(VM_PROT_ALL); + sc_cmd->initprot = target_uint32(VM_PROT_ALL); + +#ifdef MH_PIE + /* disable pie in header */ + machhead->flags = target_uint32(target_uint32(machhead->flags) & ~MH_PIE); +#endif +} + +#if defined(MH_MAGIC_64) +void pagezero_64(struct mach_header_64 *machhead) +{ + struct segment_command_64 *sc_cmd; + + if (target_uint32(machhead->filetype) != MH_EXECUTE) { + (void)fprintf(stderr, "%s: %s does not appear to be an executable file\n", + progname, filename); + exit(1); + } + if (machhead->ncmds == 0) { + (void)fprintf(stderr, "%s: %s does not contain any load commands\n", + progname, filename); + exit(1); + } + sc_cmd = (void *)&machhead[1]; + if (target_uint32(sc_cmd->cmd) != LC_SEGMENT_64) { + (void)fprintf(stderr, "%s: load segment not first command in %s\n", + progname, filename); + exit(1); + } + if (strncmp(sc_cmd->segname, "__PAGEZERO", sizeof(*sc_cmd->segname))) { + (void)fprintf(stderr, "%s: zero page not first segment in %s\n", + progname, filename); + exit(1); + } + /* change the permissions */ +// sc_cmd->maxprot = target_uint32(VM_PROT_ALL); +// sc_cmd->initprot = target_uint32(VM_PROT_ALL); +} +#endif + +/* + * Under Mach there is very little assumed about the memory map of object + * files. It is the job of the loader to create the initial memory map of an + * executable. In a Mach-O executable there will be numerous loader commands + * that the loader must process. Some of these will create the initial memory + * map used by the executable. Under Darwin the static object file linker, + * ld, automatically adds the __PAGEZERO segment to all executables. The + * default size of this segment is the page size of the target system and + * the initial and maximum permissions are set to allow no access. This is so + * that all programs fault on a NULL pointer dereference. Arguably this is + * incorrect and the maximum permissions shoould be rwx so that programs can + * change this default behavior. Then programs could be written that assume + * a null string at the null address, which was the convention on some + * systems. In our case we need to have 8K mapped at zero for the low memory + * globals and this program modifies the segment load command in the + * basiliskII executable so that it can be used for data. + */ + +int +main(int argc, const char *argv[]) +{ + int fd; + char *addr; + size_t file_size; + struct mach_header *machhead; +#if defined(MH_MAGIC_64) + struct mach_header_64 *machhead64; +#endif + struct fat_header *fathead; + struct stat f; + + if (argc != 2) { + (void)fprintf(stderr, "Usage: %s executable\n", progname); + exit(1); + } + + filename = argv[1]; + + if (stat(filename, &f)) { + (void)fprintf(stderr, "%s: could not stat %s: %s\n", + progname, filename, strerror(errno)); + exit(1); + } + file_size = (size_t) f.st_size; + + fd = open(filename, O_RDWR, 0); + if (fd == -1) { + (void)fprintf(stderr, "%s: could not open %s: %s\n", + progname, filename, strerror(errno)); + exit(1); + } + + /* + * Size does not really matter, it will be rounded-up to a multiple + * of the page size automatically. + */ + addr = mmap(NULL, file_size, PROT_READ | PROT_WRITE, + MAP_FILE | MAP_SHARED, fd, 0); + if (addr == NULL || addr == MAP_FAILED) { + (void)fprintf(stderr, "%s: could not mmap %s: %s\n", + progname, filename, strerror(errno)); + exit(1); + } + + /* + * Check to see if the Mach-O magic bytes are in the header. + */ + machhead = (void *)addr; +#if defined(MH_MAGIC_64) + machhead64 = (void *)addr; +#endif + fathead = (void *)addr; + +#if defined(MH_MAGIC_64) + do_swap = machhead->magic == MH_CIGAM || fathead->magic == FAT_CIGAM || machhead64->magic == MH_CIGAM_64; +#else + do_swap = machhead->magic == MH_CIGAM || fathead->magic == FAT_CIGAM; +#endif + + if (target_uint32(machhead->magic) == MH_MAGIC) { + pagezero_32(machhead); +#if defined(MH_MAGIC_64) + } else if (target_uint32(machhead64->magic) == MH_MAGIC_64) { + pagezero_64(machhead64); +#endif + } else if (target_uint32(fathead->magic) == FAT_MAGIC) { + struct fat_arch *arch = (void *)&fathead[1]; + int saved_swap = do_swap; + int i; + for (i = 0; i < target_uint32(fathead->nfat_arch); ++i, ++arch) { + machhead = (void *)(addr + target_uint32(arch->offset)); +#if defined(MH_MAGIC_64) + machhead64 = (void *)(addr + target_uint32(arch->offset)); +#endif +#if defined(MH_MAGIC_64) + do_swap = machhead->magic == MH_CIGAM || machhead64->magic == MH_CIGAM_64; +#else + do_swap = machhead->magic == MH_CIGAM; +#endif + if (target_uint32(machhead->magic) == MH_MAGIC) { + pagezero_32(machhead); +#if defined(MH_MAGIC_64) + } else if (target_uint32(machhead64->magic) == MH_MAGIC_64) { + pagezero_64(machhead64); +#endif + } else { + (void)fprintf(stderr, "%s: %s does not appear to be a Mach-O object file\n", + progname, filename); + exit(1); + } + do_swap = saved_swap; + } + } else { + (void)fprintf(stderr, "%s: %s does not appear to be a Mach-O object file\n", + progname, filename); + exit(1); + } + + /* + * We do not make __PAGEZERO 8K in this program because then + * all of the offsets would be wrong in the object file after + * this segment. Instead we use the -pagezero_size option + * to link the executable. + */ + if (msync(addr, file_size, MS_SYNC) == -1) { + (void)fprintf(stderr, "%s: could not sync %s: %s\n", + progname, filename, strerror(errno)); + exit(1); + } + + if (munmap(addr, file_size) == -1) { + (void)fprintf(stderr, "%s: could not unmap %s: %s\n", + progname, filename, strerror(errno)); + exit(1); + } + + (void)close(fd); + + exit(0); +}