Add a screen saver host and After Dark modules for the classic Mac OS

The classic Mac OS has no screen saver host. port/saver/macos adds one:
- Screen Saver Engine, a faceless background application in the
  Extensions folder. It starts the selected screen saver from the
  Screen Savers folder of the System Folder when the Mac is idle.
- Screen Saver, a control panel that selects the screen saver and the
  idle time, and tests the screen saver.
- An After Dark module (68k code resource) for each screen saver. It
  starts the program at Initialize and stops it at Close.

tools/build-sdk-samples.py builds them for the classic Mac OS, and
gives each screen saver its display name. tests/macos-saver has a test
screen saver and a small After Dark host. On Mac OS 9.2.1 in QEMU, the
engine starts the saver after the idle time, and the After Dark host
test passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSAH13um7pGRV7gwws
This commit is contained in:
Claude committed 2026-11-26 20:00:00 +00:00
1 parent c2281678b4
commit c3a126ed92
13 files changed
+1419 -3

No files matched your search

+2 -1
View File
@@ -426,7 +426,8 @@ OpenGL programs draw through `OpenGL.framework`. See
[docs/macosx-10.4.md](docs/macosx-10.4.md).
`tools/build-sdk-samples.py` builds samples of a Win32 SDK, such as
MULTIPAD and the OpenGL screen savers. The screen savers also become
`.saver` bundles for System Preferences. See
`.saver` bundles for System Preferences. On the classic Mac OS, a
screen saver host and After Dark modules start them. See
[docs/sdk-samples.md](docs/sdk-samples.md) and
[docs/screensavers.md](docs/screensavers.md).
+1 -1
View File
@@ -14,7 +14,7 @@ C++ libraries of [clang-retro/mac-sdk](https://github.com/clang-retro/mac-sdk).
| Window classes | Build. The Toolbox backend shows the top-level windows (see [Windows](#windows)). |
| Sockets (`CAsyncSocket`, `CSocket`) and WinInet (`CInternetSession`) | Build, over the sockets of mac-sdk's C library (MacTCP). `tests/socktest.cpp` passes on a 68020. `tests/inettest.cpp` passes its HTTP and FTP checks, but it does not finish in the simulator's step limit. HTTPS is not available (no OpenSSL). |
| OpenGL (`wgl`, `GL/gl.h`, `GL/glu.h`) | Over Apple OpenGL and AGL on PowerPC, and over the generic implementation (a software renderer) on 68k. Passes `tests/gltest.cpp` on both. See [OpenGL](#opengl). |
| Screen savers (`scrnsave.h`) | Pass `tests/sstest.cpp`. See [screensavers.md](screensavers.md). |
| Screen savers (`scrnsave.h`) | Pass `tests/sstest.cpp`. A screen saver host (a control panel and a background engine) and After Dark modules start them when the Mac is idle. See [screensavers.md](screensavers.md#system-screen-savers-on-the-classic-mac-os). |
| COM between programs | Not available. COM in one program works. |
## Windows
+62
View File
@@ -117,6 +117,68 @@ resources come from the bundle, not from the engine.
- Each bundle has a different name for its Objective-C classes, because
System Preferences loads all bundles in one process.
## System screen savers on the classic Mac OS
The classic Mac OS (System 7 to Mac OS 9) has no screen saver host of
its own. The layer gives one in `port/saver/macos`:
| File | Type | Folder | What it does |
| --- | --- | --- | --- |
| Screen Saver Engine | `appe` (faceless background application) | Extensions | Monitors the mouse and the keyboard. After the idle time, starts the selected screen saver. |
| Screen Saver | `APPC` (control panel) | Control Panels | Selects the screen saver and the idle time, and has a "Test" button. Writes "Screen Saver Preferences" in the Preferences folder. |
| The screen savers | `APPL` | Screen Savers (in the System Folder) | The `.scr` programs, built for the classic Mac OS. |
| The After Dark modules | `ADgm` | After Dark Files | Optional. One module for each screen saver, for After Dark. |
`tools/build-sdk-samples.py` makes all of them for the classic Mac OS
(fat programs and 68k modules). It gives each screen saver the name
that the control panel shows (for example `3D Pipes`).
### Install
1. Copy "Screen Saver Engine" to the Extensions folder.
2. Copy "Screen Saver" to the Control Panels folder.
3. Copy the screen savers to the folder "Screen Savers" in the System
Folder. The control panel makes this folder when it does not exist.
4. Restart the Mac. Open the control panel, then select a screen saver
and the idle time.
### How it works
- The engine reads the position of the mouse, the keys and the mouse
button every half second. When they do not change for the idle time,
it starts the screen saver with `LaunchApplication`. The engine reads
the settings again when the control panel changes them.
- The program gets no arguments. Thus the layer gives it `/S`, and it
runs over the whole screen. It stops when the mouse moves, or when the
user clicks or presses a key. Then the idle time starts again.
- An After Dark module is a 68k code resource (`ad_module.c`). At
`Initialize`, it starts the screen saver of the same name from the
"Screen Savers" folder. At `Close`, it sends the Apple event "quit" to
the program if the program did not stop itself. The module does not
draw. mac-sdk's `macapp.py --code-resource` links it.
### Tests
`tests/macos-saver` has a small screen saver (`testsaver.c`) and a small
After Dark host (`adhost.c`). The host calls a module as After Dark
does, moves the code of the module in memory between two calls, and
checks that the module starts and stops the screen saver. On Mac OS 9.2.1
in QEMU:
- The engine and the control panel start with the Mac. The engine
starts the screen saver after one minute without input, and the
screen saver stops when the mouse moves.
- `adhost` gives "ADHOST PASSED".
### Limits
- The After Dark modules are not tested with After Dark itself.
- The control panel cannot open the settings dialog of a screen saver.
To change the settings, open the screen saver with the Option key held
down.
- On a locked startup disk (a CD), the control panel cannot save the
settings. It shows the error.
## Limits
- OpenGL screen savers draw through the OpenGL of the system (Mac OS X,
+31
View File
@@ -0,0 +1,31 @@
; ad_entry.S - the entry point of an After Dark module (68k code
; resource 'ADgm').
;
; After Dark calls the module with the Pascal calling convention:
; pascal OSErr main(Handle *storage, RgnHandle blankRgn, short message,
; GMParamBlockPtr params);
; The caller pushes the space of the result, then the arguments from left
; to right. The callee removes the arguments. mac-sdk's start-coderes.S
; relocates the module and jumps here with the stack of the caller. This
; code calls ADModuleMain (C calling convention), puts the result into the
; space of the result and removes the arguments.
;
; The stack at entry:
; 0(sp) return address 4(sp) params 8(sp) message (word)
; 10(sp) blankRgn 14(sp) storage 18(sp) result (word)
.text
.globl main
main:
move.l (4, %sp), -(%sp) ; params
move.w (12, %sp), %d0 ; message
ext.l %d0
move.l %d0, -(%sp)
move.l (18, %sp), -(%sp) ; blankRgn
move.l (26, %sp), -(%sp) ; storage
jsr ADModuleMain
lea (16, %sp), %sp
move.w %d0, (18, %sp) ; the result
move.l (%sp)+, %a0 ; the return address
lea (14, %sp), %sp ; remove the arguments
jmp (%a0)
+110
View File
@@ -0,0 +1,110 @@
/* ad_module.c - an After Dark module that starts a screen saver program.
*
* After Dark loads a graphics module (file type 'ADgm', creator 'ADrk')
* and calls its code resource 'ADgm' with a message: Initialize, Blank,
* DrawFrame (again and again) and Close. This module does not draw. At
* Initialize, it starts the screen saver program SAVER_NAME from the
* "Screen Savers" folder of the System Folder. The program shows itself
* over the whole screen. At Close, the module stops the program (if the
* program did not stop itself).
*
* Build one module for each screen saver, with -DSAVER_NAME="\"name\""
* (the file name of the program). See ad_entry.S for the entry point.
*/
#include "saver_common.h"
#include <Memory.h>
#include <Quickdraw.h>
#ifndef SAVER_NAME
#error "define SAVER_NAME as the file name of the screen saver program"
#endif
/* The messages of After Dark. */
enum {
kInitialize = 0,
kClose = 1,
kBlank = 2,
kDrawFrame = 3,
kModuleSelected = 4,
kDoAbout = 5
};
/* The result for an error: After Dark shows params->errorMessage. */
enum { kModuleError = -1 };
/* The parameter block of After Dark (68k alignment). Only errorMessage is
* used. */
#pragma pack(push, 2)
typedef struct GMParamBlock {
short controlValues[4];
void *monitors;
Boolean colorQDAvail;
short systemConfig;
void *qdGlobalsCopy;
short brightness;
Rect demoRect;
StringPtr errorMessage;
void *sndChannel;
short adVersion;
void *extensions;
} GMParamBlock;
#pragma pack(pop)
/* Copies the C string s into the Pascal string p. */
static void CToP(StringPtr p, const char *s) {
short n = 0;
while (s[n] && n < 255) { p[n + 1] = (unsigned char)s[n]; n++; }
p[0] = (unsigned char)n;
}
/* Puts the message text into the error message of After Dark and gives
* the error result. */
static OSErr Fail(GMParamBlock *params, const char *text) {
if (params && params->errorMessage) CToP(params->errorMessage, text);
return kModuleError;
}
/* Starts the screen saver program, and keeps its process in *storage. */
static OSErr StartSaver(Handle *storage, GMParamBlock *params) {
Str63 name;
FSSpec spec;
ProcessSerialNumber psn;
Handle h;
CToP(name, SAVER_NAME);
if (SaverFind(name, &spec) != noErr)
return Fail(params, "The program \"" SAVER_NAME "\" is not in the "
"Screen Savers folder of the System Folder.");
if (!SaverFindProcess(&spec, &psn) && SaverLaunch(&spec, &psn) != noErr)
return Fail(params, "The program \"" SAVER_NAME "\" did not start.");
h = NewHandle(sizeof psn);
if (!h) return Fail(params, "There is not enough memory.");
BlockMoveData(&psn, *h, sizeof psn);
*storage = h;
return noErr;
}
/* Stops the screen saver program if it still runs, and frees *storage. */
static OSErr StopSaver(Handle storage) {
ProcessSerialNumber psn;
if (!storage) return noErr;
BlockMoveData(*storage, &psn, sizeof psn);
if (SaverRunning(&psn)) SaverQuit(&psn);
DisposeHandle(storage);
return noErr;
}
/* The module: ad_entry.S calls this function for each message. */
OSErr ADModuleMain(Handle *storage, RgnHandle blankRgn, long message,
GMParamBlock *params) {
(void)blankRgn;
switch (message) {
case kInitialize:
return StartSaver(storage, params);
case kClose:
return StopSaver(*storage);
default:
/* Blank, DrawFrame and the others: the program draws by itself. */
return noErr;
}
}
+235
View File
@@ -0,0 +1,235 @@
/* saver_common.c - shared code of the screen saver host of the classic
* Mac OS. See saver_common.h. */
#include "saver_common.h"
#include <AppleEvents.h>
#include <Folders.h>
#include <Memory.h>
/* The name of the folder of the screen savers, in the System Folder. */
static const unsigned char kFolderName[] = "\x0D" "Screen Savers";
/* The name of the settings file, in the Preferences folder. */
static const unsigned char kPrefsName[] = "\x18" "Screen Saver Preferences";
/* Copies the Pascal string src into dst. */
void SaverCopyPString(StringPtr dst, ConstStr255Param src) {
BlockMoveData(src, dst, src[0] + 1);
}
/* Gives true when the Pascal strings a and b are equal. */
Boolean SaverEqualPString(ConstStr255Param a, ConstStr255Param b) {
short i;
if (a[0] != b[0]) return false;
for (i = 1; i <= a[0]; i++)
if (a[i] != b[i]) return false;
return true;
}
/* Puts the default settings into prefs: on, 5 minutes, no screen saver. */
void SaverPrefsDefault(SaverPrefs *prefs) {
prefs->magic = SAVER_PREFS_MAGIC;
prefs->version = SAVER_PREFS_VERSION;
prefs->enabled = 1;
prefs->delayMinutes = 5;
prefs->saverName[0] = 0;
}
/* Makes the FSSpec of the settings file. The file does not need to
* exist. */
static OSErr PrefsSpec(FSSpec *spec) {
short vRefNum;
long dirID;
OSErr err = FindFolder(kOnSystemDisk, kPreferencesFolderType, true,
&vRefNum, &dirID);
if (err != noErr) return err;
err = FSMakeFSSpec(vRefNum, dirID, kPrefsName, spec);
return err == fnfErr ? noErr : err;
}
/* Gives the modification date of the settings file, or 0. */
unsigned long SaverPrefsDate(void) {
FSSpec spec;
CInfoPBRec pb;
if (PrefsSpec(&spec) != noErr) return 0;
BlockZero(&pb, sizeof pb);
pb.hFileInfo.ioNamePtr = spec.name;
pb.hFileInfo.ioVRefNum = spec.vRefNum;
pb.hFileInfo.ioDirID = spec.parID;
if (PBGetCatInfoSync(&pb) != noErr) return 0;
return pb.hFileInfo.ioFlMdDat;
}
/* Reads the settings file into prefs. */
OSErr SaverPrefsRead(SaverPrefs *prefs, unsigned long *modDate) {
FSSpec spec;
short ref;
long count = sizeof *prefs;
OSErr err;
if (modDate) *modDate = SaverPrefsDate();
err = PrefsSpec(&spec);
if (err == noErr) err = FSpOpenDF(&spec, fsRdPerm, &ref);
if (err == noErr) {
err = FSRead(ref, &count, prefs);
FSClose(ref);
}
if (err == noErr && (count != sizeof *prefs ||
prefs->magic != SAVER_PREFS_MAGIC ||
prefs->version != SAVER_PREFS_VERSION ||
prefs->saverName[0] > 63))
err = eofErr;
if (err != noErr) SaverPrefsDefault(prefs);
return err;
}
/* Writes prefs into the settings file. */
OSErr SaverPrefsWrite(const SaverPrefs *prefs) {
FSSpec spec;
short ref;
long count = sizeof *prefs;
OSErr err = PrefsSpec(&spec);
if (err != noErr) return err;
err = FSpCreate(&spec, SAVER_CREATOR, SAVER_PREFS_TYPE, smSystemScript);
if (err != noErr && err != dupFNErr) return err;
err = FSpOpenDF(&spec, fsRdWrPerm, &ref);
if (err != noErr) return err;
err = SetEOF(ref, 0);
if (err == noErr) err = FSWrite(ref, &count, prefs);
FSClose(ref);
return err;
}
/* Finds the "Screen Savers" folder in the System Folder. */
OSErr SaverFolder(short *vRefNum, long *dirID, Boolean create) {
long sysDir;
CInfoPBRec pb;
Str63 name;
OSErr err = FindFolder(kOnSystemDisk, kSystemFolderType, false, vRefNum,
&sysDir);
if (err != noErr) return err;
SaverCopyPString(name, kFolderName);
BlockZero(&pb, sizeof pb);
pb.dirInfo.ioNamePtr = name;
pb.dirInfo.ioVRefNum = *vRefNum;
pb.dirInfo.ioDrDirID = sysDir;
err = PBGetCatInfoSync(&pb);
if (err == noErr) {
if (!(pb.dirInfo.ioFlAttrib & ioDirMask)) return dirNFErr;
*dirID = pb.dirInfo.ioDrDirID;
return noErr;
}
if (err != fnfErr || !create) return err;
return DirCreate(*vRefNum, sysDir, kFolderName, dirID);
}
/* Finds the screen saver program with the file name name. */
OSErr SaverFind(ConstStr255Param name, FSSpec *spec) {
short vRefNum;
long dirID;
OSErr err;
if (name[0] == 0) return fnfErr;
err = SaverFolder(&vRefNum, &dirID, false);
if (err != noErr) return err;
return FSMakeFSSpec(vRefNum, dirID, name, spec);
}
/* Compares the Pascal strings a and b by their characters. Gives a
* negative number, 0 or a positive number. */
static short ComparePString(ConstStr255Param a, ConstStr255Param b) {
short i, n = a[0] < b[0] ? a[0] : b[0];
for (i = 1; i <= n; i++)
if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1;
return a[0] - b[0];
}
/* Puts the names of the applications in the "Screen Savers" folder into
* names, sorted. */
short SaverList(Str63 names[], short max) {
short vRefNum, count = 0, index, i;
long dirID;
CInfoPBRec pb;
Str63 name;
if (SaverFolder(&vRefNum, &dirID, false) != noErr) return 0;
for (index = 1; count < max; index++) {
BlockZero(&pb, sizeof pb);
pb.hFileInfo.ioNamePtr = name;
pb.hFileInfo.ioVRefNum = vRefNum;
pb.hFileInfo.ioDirID = dirID;
pb.hFileInfo.ioFDirIndex = index;
if (PBGetCatInfoSync(&pb) != noErr) break;
if (pb.hFileInfo.ioFlAttrib & ioDirMask) continue;
if (pb.hFileInfo.ioFlFndrInfo.fdType != 'APPL') continue;
/* Insertion sort: the folder is small. */
for (i = count; i > 0 && ComparePString(names[i - 1], name) > 0; i--)
SaverCopyPString(names[i], names[i - 1]);
SaverCopyPString(names[i], name);
count++;
}
return count;
}
/* Starts the program spec in the background. */
OSErr SaverLaunch(FSSpec *spec, ProcessSerialNumber *psn) {
LaunchParamBlockRec pb;
OSErr err;
BlockZero(&pb, sizeof pb);
pb.launchBlockID = extendedBlock;
pb.launchEPBLength = extendedBlockLen;
/* launchContinue: this program keeps running. launchNoFileFlags: do
* not read the flags of the file (it is an application). */
pb.launchControlFlags = launchContinue | 0x0800;
pb.launchAppSpec = spec;
err = LaunchApplication(&pb);
if (err != noErr) return err;
/* When the caller is the front process (for example After Dark or the
* control panel), the new process can stay in the background, behind
* the windows of the caller. A screen saver must be in front. */
SetFrontProcess(&pb.launchProcessSN);
if (psn) *psn = pb.launchProcessSN;
return noErr;
}
/* Gives true when the process psn is running. */
Boolean SaverRunning(ProcessSerialNumber *psn) {
ProcessInfoRec info;
BlockZero(&info, sizeof info);
info.processInfoLength = sizeof info;
return GetProcessInformation(psn, &info) == noErr;
}
/* Finds the running process of the program spec. */
Boolean SaverFindProcess(const FSSpec *spec, ProcessSerialNumber *psn) {
ProcessSerialNumber p;
ProcessInfoRec info;
FSSpec app;
p.highLongOfPSN = 0;
p.lowLongOfPSN = kNoProcess;
while (GetNextProcess(&p) == noErr) {
BlockZero(&info, sizeof info);
info.processInfoLength = sizeof info;
info.processAppSpec = &app;
if (GetProcessInformation(&p, &info) != noErr) continue;
if (app.vRefNum == spec->vRefNum && app.parID == spec->parID &&
SaverEqualPString(app.name, spec->name)) {
*psn = p;
return true;
}
}
return false;
}
/* Sends the Apple event "quit" to the process psn. */
OSErr SaverQuit(ProcessSerialNumber *psn) {
AEAddressDesc target;
AppleEvent event, reply;
OSErr err = AECreateDesc(typeProcessSerialNumber, psn, sizeof *psn,
&target);
if (err != noErr) return err;
err = AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &target,
kAutoGenerateReturnID, kAnyTransactionID, &event);
AEDisposeDesc(&target);
if (err != noErr) return err;
err = AESend(&event, &reply, kAENoReply, kAENormalPriority,
kAEDefaultTimeout, NULL, NULL);
AEDisposeDesc(&event);
return err;
}
+79
View File
@@ -0,0 +1,79 @@
/* saver_common.h - shared code of the screen saver host of the classic
* Mac OS: the settings file, the "Screen Savers" folder, and the start
* and stop of a screen saver program.
*
* The control panel ("Screen Saver"), the background engine ("Screen
* Saver Engine") and the After Dark modules use this code. A screen saver
* is an application in the folder "Screen Savers" of the System Folder.
*/
#ifndef SAVER_COMMON_H
#define SAVER_COMMON_H
#include <Files.h>
#include <Processes.h>
#define SAVER_CREATOR 'WPss' /* creator of the host files */
#define SAVER_PREFS_TYPE 'pref'
#define SAVER_PREFS_MAGIC 'WPsp'
#define SAVER_PREFS_VERSION 1
#define SAVER_MAX 32 /* most screen savers in the menu */
/* The settings. The control panel writes them; the engine reads them. The
* layout is the same on 68k and PowerPC (2-byte alignment), so that the
* two can share the file. */
#pragma pack(push, 2)
typedef struct SaverPrefs {
OSType magic; /* SAVER_PREFS_MAGIC */
short version; /* SAVER_PREFS_VERSION */
short enabled; /* 1: the engine starts the screen saver */
short delayMinutes; /* idle time before the start */
Str63 saverName; /* file name of the screen saver program */
} SaverPrefs;
#pragma pack(pop)
/* Puts the default settings into prefs. */
void SaverPrefsDefault(SaverPrefs *prefs);
/* Reads the settings file into prefs. Gives the modification date of the
* file in modDate (when modDate is not NULL). When there is no valid
* file, puts the defaults into prefs and gives an error. */
OSErr SaverPrefsRead(SaverPrefs *prefs, unsigned long *modDate);
/* Writes prefs into the settings file. Makes the file when necessary. */
OSErr SaverPrefsWrite(const SaverPrefs *prefs);
/* Gives the modification date of the settings file, or 0. */
unsigned long SaverPrefsDate(void);
/* Finds the "Screen Savers" folder in the System Folder. Makes the folder
* when create is true and the folder does not exist. */
OSErr SaverFolder(short *vRefNum, long *dirID, Boolean create);
/* Finds the screen saver program with the file name name. */
OSErr SaverFind(ConstStr255Param name, FSSpec *spec);
/* Puts the names of the applications in the "Screen Savers" folder into
* names, sorted. Gives the number of names (at most max). */
short SaverList(Str63 names[], short max);
/* Starts the program spec in the background. Puts its process into psn. */
OSErr SaverLaunch(FSSpec *spec, ProcessSerialNumber *psn);
/* Gives true when the process psn is running. */
Boolean SaverRunning(ProcessSerialNumber *psn);
/* Finds the running process of the program spec. Gives true and puts the
* process into psn when it runs. */
Boolean SaverFindProcess(const FSSpec *spec, ProcessSerialNumber *psn);
/* Sends the Apple event "quit" to the process psn. */
OSErr SaverQuit(ProcessSerialNumber *psn);
/* Copies the Pascal string src into dst. */
void SaverCopyPString(StringPtr dst, ConstStr255Param src);
/* Gives true when the Pascal strings a and b are equal (the case of the
* letters is significant). */
Boolean SaverEqualPString(ConstStr255Param a, ConstStr255Param b);
#endif
+134
View File
@@ -0,0 +1,134 @@
/* saver_engine.c - "Screen Saver Engine", the background part of the
* screen saver host of the classic Mac OS.
*
* The engine is a faceless background application (file type 'appe').
* The Process Manager starts it from the Extensions folder when the Mac
* starts. It monitors the mouse and the keyboard. When the user does not
* use them for the time in the settings, it starts the selected screen
* saver program from the "Screen Savers" folder. The screen saver stops
* itself when the user moves the mouse or presses a key.
*/
#include "saver_common.h"
#include <AppleEvents.h>
#include <Events.h>
#include <Memory.h>
#include <OSUtils.h>
#define POLL_TICKS 30 /* time between two checks (half a second) */
#define PREFS_TICKS 180 /* time between two checks of the settings */
static Boolean gQuit;
/* Handles the Apple event "quit": stops the engine. */
static pascal OSErr QuitHandler(const AppleEvent *event, AppleEvent *reply,
long refcon) {
(void)event; (void)reply; (void)refcon;
gQuit = true;
return noErr;
}
/* Handles the other required Apple events. They have nothing to do. */
static pascal OSErr IgnoreHandler(const AppleEvent *event, AppleEvent *reply,
long refcon) {
(void)event; (void)reply; (void)refcon;
return noErr;
}
/* Installs the handlers of the required Apple events. */
static void InstallHandlers(void) {
AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
NewAEEventHandlerUPP(QuitHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
}
/* The state of the mouse and the keyboard at the last check. */
typedef struct InputState {
Point mouse;
unsigned char keys[16];
Boolean button;
} InputState;
/* Reads the state of the mouse and the keyboard into state. */
static void ReadInput(InputState *state) {
state->mouse = LMGetMouseLocation();
GetKeys(state->keys);
state->button = Button();
}
/* Gives true when the states a and b are different (the user did
* something). */
static Boolean InputChanged(const InputState *a, const InputState *b) {
short i;
if (a->mouse.h != b->mouse.h || a->mouse.v != b->mouse.v) return true;
if (a->button != b->button) return true;
for (i = 0; i < 16; i++)
if (a->keys[i] != b->keys[i]) return true;
return false;
}
/* The engine: monitors the input and starts the screen saver. */
int main(void) {
SaverPrefs prefs;
unsigned long prefsDate, lastPrefsCheck;
unsigned long lastActivity;
InputState last, now;
ProcessSerialNumber saver;
Boolean saverOn = false;
EventRecord event;
MaxApplZone();
InstallHandlers();
SaverPrefsRead(&prefs, &prefsDate);
lastPrefsCheck = TickCount();
ReadInput(&last);
lastActivity = TickCount();
while (!gQuit) {
if (WaitNextEvent(everyEvent, &event, POLL_TICKS, NULL) &&
event.what == kHighLevelEvent)
AEProcessAppleEvent(&event);
ReadInput(&now);
if (InputChanged(&now, &last)) lastActivity = TickCount();
last = now;
/* The control panel changed the settings. */
if (TickCount() - lastPrefsCheck >= PREFS_TICKS) {
unsigned long date = SaverPrefsDate();
if (date != prefsDate) {
SaverPrefsRead(&prefs, &prefsDate);
lastActivity = TickCount();
}
lastPrefsCheck = TickCount();
}
if (saverOn) {
/* The screen saver stopped (the user moved the mouse). The idle
* time starts again. */
if (!SaverRunning(&saver)) {
saverOn = false;
lastActivity = TickCount();
}
continue;
}
if (prefs.enabled && prefs.delayMinutes > 0 &&
TickCount() - lastActivity >=
(unsigned long)prefs.delayMinutes * 3600) {
FSSpec spec;
if (SaverFind(prefs.saverName, &spec) == noErr) {
if (SaverFindProcess(&spec, &saver) ||
SaverLaunch(&spec, &saver) == noErr)
saverOn = true;
}
/* Also when the start failed: try again after the next idle time. */
lastActivity = TickCount();
}
}
return 0;
}
+352
View File
@@ -0,0 +1,352 @@
/* saver_panel.c - "Screen Saver", the control panel of the screen saver
* host of the classic Mac OS.
*
* The control panel is an application (file type 'APPC') in the Control
* Panels folder. It shows the screen saver programs of the "Screen
* Savers" folder, and writes the selected screen saver and the idle time
* into the settings file. The engine ("Screen Saver Engine") reads the
* settings file. The button "Test" starts the screen saver at once.
*/
#include "saver_common.h"
#include <AppleEvents.h>
#include <Controls.h>
#include <Dialogs.h>
#include <Events.h>
#include <Folders.h>
#include <Fonts.h>
#include <Memory.h>
#include <Menus.h>
#include <OSUtils.h>
#include <Quickdraw.h>
#include <TextEdit.h>
#include <Windows.h>
QDGlobals qd;
enum { kAppleMenu = 128, kFileMenu = 129, kSaverMenu = 130, kDelayMenu = 131 };
enum { kPopupProc = 1008 }; /* popupMenuProc */
enum { kEngineCreator = 'WPse' };
static const short kDelays[] = {1, 2, 3, 5, 10, 15, 20, 30, 45, 60};
#define DELAY_COUNT (short)(sizeof kDelays / sizeof kDelays[0])
static WindowPtr gWindow;
static ControlHandle gEnabled, gSaverPopup, gDelayPopup, gTest;
static MenuHandle gSaverMenu, gDelayMenu;
static Str63 gSavers[SAVER_MAX];
static short gSaverCount;
static SaverPrefs gPrefs;
static Boolean gQuit;
static OSErr gSaveError; /* the result of the last write of the settings */
/* Copies the C string s into the Pascal string p. */
static void CToP(StringPtr p, const char *s) {
short n = 0;
while (s[n] && n < 255) { p[n + 1] = (unsigned char)s[n]; n++; }
p[0] = (unsigned char)n;
}
/* Gives true when the engine runs. */
static Boolean EngineRunning(void) {
ProcessSerialNumber p = {0, kNoProcess};
ProcessInfoRec info;
while (GetNextProcess(&p) == noErr) {
BlockZero(&info, sizeof info);
info.processInfoLength = sizeof info;
if (GetProcessInformation(&p, &info) == noErr &&
info.processSignature == kEngineCreator)
return true;
}
return false;
}
/* Starts the engine from the Extensions folder when it does not run (for
* example just after the user installed it). */
static void StartEngine(void) {
short vRefNum;
long dirID;
FSSpec spec;
Str63 name;
if (EngineRunning()) return;
if (FindFolder(kOnSystemDisk, kExtensionFolderType, false, &vRefNum,
&dirID) != noErr)
return;
CToP(name, "Screen Saver Engine");
if (FSMakeFSSpec(vRefNum, dirID, name, &spec) == noErr)
SaverLaunch(&spec, NULL);
}
/* Saves the settings that the controls show. */
static void SaveSettings(void) {
short item = GetControlValue(gSaverPopup);
gPrefs.enabled = GetControlValue(gEnabled);
gPrefs.delayMinutes = kDelays[GetControlValue(gDelayPopup) - 1];
if (gSaverCount > 0 && item >= 1 && item <= gSaverCount)
SaverCopyPString(gPrefs.saverName, gSavers[item - 1]);
gSaveError = SaverPrefsWrite(&gPrefs);
}
/* Starts the selected screen saver at once. */
static void TestSaver(void) {
FSSpec spec;
if (SaverFind(gPrefs.saverName, &spec) == noErr)
SaverLaunch(&spec, NULL);
}
/* Makes the menu bar: the Apple menu and the File menu. */
static void MakeMenus(void) {
Str255 s;
MenuHandle m;
s[0] = 1; s[1] = 0x14; /* the apple character */
m = NewMenu(kAppleMenu, s);
CToP(s, "About Screen Saver...");
AppendMenu(m, s);
AppendMenu(m, (ConstStringPtr)"\x02(-");
AppendResMenu(m, 'DRVR');
InsertMenu(m, 0);
CToP(s, "File");
m = NewMenu(kFileMenu, s);
CToP(s, "Close/W");
AppendMenu(m, s);
CToP(s, "Quit/Q");
AppendMenu(m, s);
InsertMenu(m, 0);
DrawMenuBar();
}
/* Makes the window and its controls from the settings. */
static void MakeWindow(void) {
Rect r;
Str255 s;
short i, value;
SetRect(&r, 0, 0, 360, 170);
OffsetRect(&r, 60, 80);
CToP(s, "Screen Saver");
gWindow = NewWindow(NULL, &r, s, false, noGrowDocProc, (WindowPtr)-1,
true, 0);
SetPort(gWindow);
TextFont(0);
TextSize(12);
SetRect(&r, 20, 16, 340, 34);
CToP(s, "Start the screen saver when the Mac is idle");
gEnabled = NewControl(gWindow, &r, s, true, gPrefs.enabled ? 1 : 0, 0, 1,
checkBoxProc, 0);
/* The menus of the popups: not in the menu bar (InsertMenu -1). */
CToP(s, "Saver");
gSaverMenu = NewMenu(kSaverMenu, s);
value = 1;
gSaverCount = SaverList(gSavers, SAVER_MAX);
for (i = 0; i < gSaverCount; i++) {
AppendMenu(gSaverMenu, (ConstStringPtr)"\x01 ");
SetMenuItemText(gSaverMenu, i + 1, gSavers[i]);
if (SaverEqualPString(gSavers[i], gPrefs.saverName)) value = i + 1;
}
if (gSaverCount == 0) {
CToP(s, "(no screen savers)");
AppendMenu(gSaverMenu, (ConstStringPtr)"\x01 ");
SetMenuItemText(gSaverMenu, 1, s);
} else if (gPrefs.saverName[0] == 0) {
SaverCopyPString(gPrefs.saverName, gSavers[0]);
}
InsertMenu(gSaverMenu, -1);
CToP(s, "Delay");
gDelayMenu = NewMenu(kDelayMenu, s);
for (i = 0; i < DELAY_COUNT; i++) {
char text[16];
short n = kDelays[i], k = 0;
const char *unit = n == 1 ? " minute" : " minutes";
if (n >= 10) text[k++] = (char)('0' + n / 10);
text[k++] = (char)('0' + n % 10);
while (*unit) text[k++] = *unit++;
text[k] = 0;
CToP(s, text);
AppendMenu(gDelayMenu, (ConstStringPtr)"\x01 ");
SetMenuItemText(gDelayMenu, i + 1, s);
}
InsertMenu(gDelayMenu, -1);
/* A popup control: min is the menu ID, max is the width of the title. */
SetRect(&r, 20, 46, 340, 66);
CToP(s, "Screen saver:");
gSaverPopup = NewControl(gWindow, &r, s, true, popupTitleLeftJust,
kSaverMenu, 110, kPopupProc, 0);
SetControlValue(gSaverPopup, value);
SetRect(&r, 20, 76, 340, 96);
CToP(s, "Start after:");
gDelayPopup = NewControl(gWindow, &r, s, true, popupTitleLeftJust,
kDelayMenu, 110, kPopupProc, 0);
value = 4; /* 5 minutes */
for (i = 0; i < DELAY_COUNT; i++)
if (kDelays[i] == gPrefs.delayMinutes) value = i + 1;
SetControlValue(gDelayPopup, value);
SetRect(&r, 250, 106, 340, 126);
CToP(s, "Test");
gTest = NewControl(gWindow, &r, s, true, 0, 0, 1, pushButProc, 0);
ShowWindow(gWindow);
}
/* Draws the text of the window that is not part of a control. */
static void DrawStatus(void) {
Str255 s;
Rect r;
SetRect(&r, 20, 128, 340, 160);
EraseRect(&r);
MoveTo(20, 142);
CToP(s, EngineRunning() ? "The engine is running."
: "The engine is not running.");
DrawString(s);
MoveTo(20, 158);
if (gSaveError != noErr) {
/* For example a locked startup disk. */
short n = gSaveError < 0 ? -gSaveError : gSaveError, k;
CToP(s, "The settings were not saved (error -");
for (k = 1000; k > 0; k /= 10)
if (n >= k || k == 1) s[++s[0]] = (unsigned char)('0' + n / k % 10);
s[++s[0]] = ')';
s[++s[0]] = '.';
} else {
CToP(s, "Savers: System Folder:Screen Savers");
}
DrawString(s);
}
/* Handles a click in the content of the window. */
static void ContentClick(Point where) {
ControlHandle control;
short part;
SetPort(gWindow);
GlobalToLocal(&where);
part = FindControl(where, gWindow, &control);
if (!part) return;
if (control == gSaverPopup || control == gDelayPopup) {
TrackControl(control, where, (ControlActionUPP)-1);
SaveSettings();
} else if (TrackControl(control, where, NULL)) {
if (control == gEnabled) {
SetControlValue(gEnabled, !GetControlValue(gEnabled));
SaveSettings();
} else if (control == gTest) {
TestSaver();
}
}
}
/* Handles a command of the menu bar. */
static void DoMenuCommand(long command) {
short menu = (short)(command >> 16), item = (short)command;
if (menu == kAppleMenu) {
if (item > 2) {
Str255 name;
GetMenuItemText(GetMenuHandle(kAppleMenu), item, name);
OpenDeskAcc(name);
}
} else if (menu == kFileMenu) {
gQuit = true;
}
HiliteMenu(0);
}
/* Handles the Apple event "quit". */
static pascal OSErr QuitHandler(const AppleEvent *event, AppleEvent *reply,
long refcon) {
(void)event; (void)reply; (void)refcon;
gQuit = true;
return noErr;
}
/* Handles the other required Apple events. */
static pascal OSErr IgnoreHandler(const AppleEvent *event, AppleEvent *reply,
long refcon) {
(void)event; (void)reply; (void)refcon;
return noErr;
}
/* The control panel: shows the window and handles the events. */
int main(void) {
EventRecord event;
WindowPtr window;
long lastStatus = 0;
MaxApplZone();
InitGraf(&qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(NULL);
InitCursor();
AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
NewAEEventHandlerUPP(QuitHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
/* Make the "Screen Savers" folder, so that the user can find it. */
{
short vRefNum;
long dirID;
SaverFolder(&vRefNum, &dirID, true);
}
SaverPrefsRead(&gPrefs, NULL);
StartEngine();
MakeMenus();
MakeWindow();
SaveSettings(); /* writes the file when it did not exist */
while (!gQuit) {
if (!WaitNextEvent(everyEvent, &event, 30, NULL)) {
/* Show a change of the state of the engine. */
if (TickCount() - lastStatus > 120) {
SetPort(gWindow);
DrawStatus();
lastStatus = TickCount();
}
continue;
}
switch (event.what) {
case mouseDown:
switch (FindWindow(event.where, &window)) {
case inMenuBar:
DoMenuCommand(MenuSelect(event.where));
break;
case inSysWindow:
SystemClick(&event, window);
break;
case inDrag:
DragWindow(window, event.where, &qd.screenBits.bounds);
break;
case inGoAway:
if (TrackGoAway(window, event.where)) gQuit = true;
break;
case inContent:
if (window != FrontWindow()) SelectWindow(window);
else ContentClick(event.where);
break;
}
break;
case keyDown:
if (event.modifiers & cmdKey)
DoMenuCommand(MenuKey((char)(event.message & charCodeMask)));
break;
case updateEvt:
window = (WindowPtr)event.message;
BeginUpdate(window);
SetPort(window);
DrawControls(window);
DrawStatus();
EndUpdate(window);
break;
case kHighLevelEvent:
AEProcessAppleEvent(&event);
break;
}
}
return 0;
}
+212
View File
@@ -0,0 +1,212 @@
/* adhost.c - a small After Dark host, to test the After Dark modules of
* port/saver/macos/ad_module.c without After Dark.
*
* It opens the module "System Folder:Screen Savers:Test Saver AD", calls
* it as After Dark does (Initialize, Blank, DrawFrame, Close), and checks
* that the module starts and stops the program "Test Saver". Between two
* calls, it moves the code of the module in memory, to test the
* relocation of the code resource. It shows the results in its window and
* ends with "ADHOST PASSED" or "ADHOST FAILED".
*/
#include <Events.h>
#include <Fonts.h>
#include <Memory.h>
#include <Menus.h>
#include <Processes.h>
#include <Quickdraw.h>
#include <Resources.h>
#include <TextEdit.h>
#include <Dialogs.h>
#include <Windows.h>
#include "../../port/saver/macos/saver_common.h"
QDGlobals qd;
short CallModule(Ptr code, Handle *storage, RgnHandle blankRgn,
short message, void *params);
#define MAX_LINES 32
static WindowPtr gWindow;
static Str255 gLines[MAX_LINES]; /* the log, to draw it again */
static short gLineCount;
static short gFails;
/* The parameter block of After Dark (68k alignment). */
#pragma pack(push, 2)
typedef struct GMParamBlock {
short controlValues[4];
void *monitors;
Boolean colorQDAvail;
short systemConfig;
void *qdGlobalsCopy;
short brightness;
Rect demoRect;
StringPtr errorMessage;
void *sndChannel;
short adVersion;
void *extensions;
} GMParamBlock;
#pragma pack(pop)
/* Copies the C string s into the Pascal string p. */
static void CToP(StringPtr p, const char *s) {
short n = 0;
while (s[n] && n < 255) { p[n + 1] = (unsigned char)s[n]; n++; }
p[0] = (unsigned char)n;
}
/* Draws the log into the window. */
static void DrawLog(void) {
short i;
SetPort(gWindow);
for (i = 0; i < gLineCount; i++) {
MoveTo(10, 20 + 15 * i);
DrawString(gLines[i]);
}
}
/* Adds a line of text, and the number n in hexadecimal when n is not -1,
* to the log, and draws it. */
static void Log(const char *text, long n) {
StringPtr s;
if (gLineCount == MAX_LINES) return;
s = gLines[gLineCount];
CToP(s, text);
if (n != -1) {
short sh;
s[++s[0]] = ' ';
for (sh = 28; sh >= 0; sh -= 4)
s[++s[0]] = "0123456789ABCDEF"[(n >> sh) & 15];
}
SetPort(gWindow);
MoveTo(10, 20 + 15 * gLineCount);
DrawString(s);
gLineCount++;
}
/* Writes the result of a check, and counts the failures. */
static void Check(const char *text, Boolean ok) {
Log(text, -1);
Log(ok ? " ok" : " FAIL", -1);
if (!ok) gFails++;
}
/* Lets the other programs run for the time ticks. Handles the update
* events: the Process Manager brings another program to the front only
* when this program has no events left. */
static void Wait(long ticks) {
unsigned long end = TickCount() + ticks;
EventRecord event;
while (TickCount() < end) {
if (WaitNextEvent(everyEvent, &event, 6, NULL) &&
event.what == updateEvt) {
BeginUpdate((WindowPtr)event.message);
DrawLog();
EndUpdate((WindowPtr)event.message);
}
}
}
/* Gives true when the program "Test Saver" runs. */
static Boolean SaverIsRunning(void) {
Str63 name;
FSSpec spec;
ProcessSerialNumber psn;
CToP(name, "Test Saver");
return SaverFind(name, &spec) == noErr && SaverFindProcess(&spec, &psn);
}
/* Moves the locked handle h to another address, and locks it again. */
static void MoveCode(Handle h) {
Handle block = NewHandle(4096);
HUnlock(h);
MoveHHi(h);
HLock(h);
if (block) DisposeHandle(block);
}
/* The host: calls the module and shows the results. */
int main(void) {
Rect r;
Str255 s, error;
short vRefNum, ref, result, i;
long dirID;
FSSpec spec;
Handle code, storage = NULL;
RgnHandle rgn;
GMParamBlock params;
Ptr first;
MaxApplZone();
InitGraf(&qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(NULL);
InitCursor();
SetRect(&r, 40, 60, 600, 440);
CToP(s, "After Dark host test");
gWindow = NewWindow(NULL, &r, s, true, noGrowDocProc, (WindowPtr)-1,
false, 0);
SetPort(gWindow);
TextFont(4); /* Monaco */
TextSize(9);
if (SaverFolder(&vRefNum, &dirID, false) != noErr) {
Check("Screen Savers folder", false);
goto done;
}
CToP(s, "Test Saver AD");
FSMakeFSSpec(vRefNum, dirID, s, &spec);
ref = FSpOpenResFile(&spec, fsRdPerm);
Check("open the module file", ref != -1);
if (ref == -1) goto done;
code = Get1IndResource('ADgm', 1);
Check("code resource ADgm", code != NULL);
if (!code) goto done;
HNoPurge(code);
HLock(code);
first = *code;
Log("module at", (long)first);
rgn = NewRgn();
RectRgn(rgn, &qd.screenBits.bounds);
BlockZero(&params, sizeof params);
error[0] = 0;
params.errorMessage = error;
params.adVersion = 0x0300;
params.colorQDAvail = true;
result = CallModule(*code, &storage, rgn, 0 /* Initialize */, &params);
Log("Initialize gives", result);
if (error[0] && gLineCount < MAX_LINES)
SaverCopyPString(gLines[gLineCount++], error);
Check("Initialize gives noErr", result == 0 && storage != NULL);
Wait(240);
Check("Test Saver runs", SaverIsRunning());
result = CallModule(*code, &storage, rgn, 2 /* Blank */, &params);
Check("Blank gives noErr", result == 0);
MoveCode(code);
Log("module now at", (long)*code);
for (i = 0; i < 10; i++) {
result = CallModule(*code, &storage, rgn, 3 /* DrawFrame */, &params);
if (result != 0) break;
Wait(6);
}
Check("DrawFrame gives noErr", result == 0);
result = CallModule(*code, &storage, rgn, 1 /* Close */, &params);
Check("Close gives noErr", result == 0);
Wait(300);
Check("Test Saver stopped", !SaverIsRunning());
CloseResFile(ref);
done:
SelectWindow(gWindow);
Log(gFails ? "ADHOST FAILED" : "ADHOST PASSED", -1);
while (!Button()) Wait(30);
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
; call_module.S - calls an After Dark module with the Pascal calling
; convention, for adhost.c:
; short CallModule(Ptr code, Handle *storage, RgnHandle blankRgn,
; short message, void *params);
; C arguments (each in 4 bytes): 4(sp) code, 8 storage, 12 blankRgn,
; 16 message (the word at 18), 20 params.
.text
.globl CallModule
CallModule:
movem.l %d2-%d7/%a2-%a6, -(%sp) ; 44 bytes
clr.w -(%sp) ; space of the result
move.l (54, %sp), -(%sp) ; storage
move.l (62, %sp), -(%sp) ; blankRgn
move.w (72, %sp), -(%sp) ; message
move.l (76, %sp), -(%sp) ; params
move.l (64, %sp), %a0 ; code
jsr (%a0)
move.w (%sp)+, %d0 ; the result
ext.l %d0
movem.l (%sp)+, %d2-%d7/%a2-%a6
rts
+115
View File
@@ -0,0 +1,115 @@
/* testsaver.c - "Test Saver", a small screen saver program for the tests
* of the screen saver host of the classic Mac OS.
*
* It covers the screen with a black window and draws colored rectangles.
* It stops when the mouse moves more than 4 pixels, when the user clicks
* or presses a key, and at the Apple event "quit", as the screen savers
* of the portable layer do.
*/
#include <AppleEvents.h>
#include <Dialogs.h>
#include <Events.h>
#include <Fonts.h>
#include <Memory.h>
#include <Menus.h>
#include <OSUtils.h>
#include <Quickdraw.h>
#include <TextEdit.h>
#include <Windows.h>
#include <Processes.h>
QDGlobals qd;
static Boolean gQuit;
/* Handles the Apple event "quit". */
static pascal OSErr QuitHandler(const AppleEvent *event, AppleEvent *reply,
long refcon) {
(void)event; (void)reply; (void)refcon;
gQuit = true;
return noErr;
}
/* Handles the other required Apple events. */
static pascal OSErr IgnoreHandler(const AppleEvent *event, AppleEvent *reply,
long refcon) {
(void)event; (void)reply; (void)refcon;
return noErr;
}
/* Draws one rectangle of a random size and color. */
static void DrawFrame(const Rect *bounds) {
Rect r;
RGBColor c;
short w = bounds->right - bounds->left, h = bounds->bottom - bounds->top;
short x = (short)((unsigned short)Random() % w);
short y = (short)((unsigned short)Random() % h);
SetRect(&r, x, y, x + 20 + (unsigned short)Random() % 80,
y + 20 + (unsigned short)Random() % 60);
c.red = (unsigned short)Random();
c.green = (unsigned short)Random();
c.blue = (unsigned short)Random();
RGBForeColor(&c);
PaintRect(&r);
}
/* The screen saver: one window over the whole screen. */
int main(void) {
WindowPtr window;
Rect bounds;
Point start, now;
EventRecord event;
RgnHandle menuBar = NULL;
MaxApplZone();
InitGraf(&qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(NULL);
AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
NewAEEventHandlerUPP(QuitHandler), 0, false);
AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
NewAEEventHandlerUPP(IgnoreHandler), 0, false);
qd.randSeed = (long)TickCount();
bounds = qd.screenBits.bounds;
window = NewCWindow(NULL, &bounds, (ConstStringPtr)"\x00", true, plainDBox,
(WindowPtr)-1, false, 0);
SetPort(window);
/* Draw over the menu bar too. */
(void)menuBar;
BackColor(blackColor);
EraseRect(&window->portRect);
HideCursor();
GetMouse(&start);
LocalToGlobal(&start);
while (!gQuit) {
if (WaitNextEvent(everyEvent, &event, 2, NULL)) {
switch (event.what) {
case mouseDown:
case keyDown:
gQuit = true;
break;
case kHighLevelEvent:
AEProcessAppleEvent(&event);
break;
case updateEvt:
BeginUpdate((WindowPtr)event.message);
EraseRect(&window->portRect);
EndUpdate((WindowPtr)event.message);
break;
}
}
SetPort(window);
DrawFrame(&window->portRect);
GetMouse(&now);
LocalToGlobal(&now);
if (now.h - start.h > 4 || start.h - now.h > 4 ||
now.v - start.v > 4 || start.v - now.v > 4)
gQuit = true;
}
ShowCursor();
ExitToShell();
return 0;
}
+64 -1
View File
@@ -63,6 +63,10 @@ SAVER_NAMES = {
"text3d": "3D Text",
}
SAVER_BUNDLE_SRC = os.path.join(ROOT, "port", "saver", "saver_bundle.mm")
# On the classic Mac OS, the screen saver host (port/saver/macos): the
# control panel and the background engine, and one After Dark module for
# each screen saver.
MACOS_SAVER_DIR = os.path.join(ROOT, "port", "saver", "macos")
COCOA_BACKEND_SRC = os.path.join(ROOT, "port", "src", "backend_cocoa.mm")
INFO_PLIST = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -507,9 +511,14 @@ def build_sample(sample, sdk, out, env, log):
# are objects already.
cxxlibs = [os.path.join(env["MACSDK"], "lib", "m68k" if cpu == "68k" else "ppc", n) for n in ("libstdc++.a", "libunwind.a")]
link_env = dict(os.environ, CLANG=env["CC"])
# A screen saver has the name that the control panel of the host
# shows (for example "3D Pipes").
title = SAVER_NAMES.get(name, os.path.splitext(program)[0]) if saver else os.path.splitext(program)[0]
run([sys.executable, os.path.join(env["MACSDK"], "tools", "macapp.py"), "--cpu", cpu,
"--lib", os.path.join(env["MACSDK"], "lib"), "--size", "8192", "--large",
"--name", os.path.splitext(program)[0], "-o", exe, "--"] + objects + libs + cxxlibs, log, link_env)
"--name", title, "-o", exe, "--"] + objects + libs + cxxlibs, log, link_env)
if saver:
build_ad_module(title, os.path.dirname(exe), env, log)
return exe
if env["DOS"]:
exe = os.path.splitext(exe)[0] + ".exe"
@@ -557,6 +566,53 @@ def build_saver_bundle(name, program, objects, libs, objdir, env, log):
# Reads the compilers and flags from the environment.
# Runs mac-sdk's tools/macapp.py with the arguments args, with the
# compiler of env, without the C library.
def macapp(args, env, log):
link_env = dict(os.environ, CLANG=env["CC"])
run([sys.executable, os.path.join(env["MACSDK"], "tools", "macapp.py"), "--no-libc",
"--lib", os.path.join(env["MACSDK"], "lib")] + args, log, link_env)
# Adds the resources res, as (type, ID, bytes), to the MacBinary file path.
def add_resources(path, res, env):
sys.path.insert(0, os.path.join(env["MACSDK"], "tools", "link"))
import macres
name, ftype, creator, data, rsrc = macres.read_macbinary(open(path, "rb").read())
resources = macres.read_resource_fork(rsrc) + res
with open(path, "wb") as f:
f.write(macres.macbinary(name, ftype, creator, data, macres.resource_fork(resources)))
# Builds the After Dark module of the screen saver title (out/TITLE.ADgm.bin):
# a 68k code resource that starts the program from the "Screen Savers"
# folder (port/saver/macos/ad_module.c).
def build_ad_module(title, out, env, log):
module = os.path.join(out, title + ".ADgm.bin")
macapp(["--cpu", "68k", "--code-resource", "ADgm,0", "--type", "ADgm", "--creator", "ADrk",
"--name", title, "-o", module, "--", '-DSAVER_NAME="%s"' % title,
os.path.join(MACOS_SAVER_DIR, "ad_entry.S"), os.path.join(MACOS_SAVER_DIR, "ad_module.c"),
os.path.join(MACOS_SAVER_DIR, "saver_common.c")], env, log)
credit = ("Starts %s from the Screen Savers folder." % title).encode("mac_roman")
# 'Cals': the messages that the module wants (Initialize, Blank,
# DrawFrame and Close). 'STR ' 128: the credit line.
add_resources(module, [(b"Cals", 1, b"\x0f"), (b"STR ", 128, bytes([len(credit)]) + credit)], env)
return module
# Builds the screen saver host of the classic Mac OS, for 68k and PowerPC:
# the control panel (out/Screen Saver.bin) and the background engine
# (out/Screen Saver Engine.bin).
def build_saver_host(out, env, log):
common = os.path.join(MACOS_SAVER_DIR, "saver_common.c")
macapp(["--type", "APPC", "--creator", "WPsc", "--size", "256", "--name", "Screen Saver",
"-o", os.path.join(out, "Screen Saver.bin"), "--",
os.path.join(MACOS_SAVER_DIR, "saver_panel.c"), common], env, log)
macapp(["--type", "appe", "--creator", "WPse", "--background-only", "--size", "128",
"--name", "Screen Saver Engine", "-o", os.path.join(out, "Screen Saver Engine.bin"), "--",
os.path.join(MACOS_SAVER_DIR, "saver_engine.c"), common], env, log)
def environment():
bindir = os.environ.get("BIN", "")
tool = lambda n: os.path.join(bindir, n) if bindir else n
@@ -610,6 +666,13 @@ def main():
except RuntimeError as e:
failed += 1
print("FAIL %s (%s)" % (sample[0], e))
if env["CLASSIC"] and any(s[3] and (not only or s[0] in only) for s in SAMPLES):
try:
build_saver_host(os.path.join(args.out, "bin"), env, log)
print("ok saver host: %s" % os.path.join(args.out, "bin"))
except RuntimeError as e:
failed += 1
print("FAIL saver host (%s)" % e)
sys.exit(1 if failed else 0)