// helloWindow.c - GS/OS app that opens a Window Manager window and
// draws a greeting in it.  Runs under real GS/OS 6.0.2 in MAME.
//
// Phase 4.1 migration: NewWindowParm struct + manual zero+fill is now
// uiBuilderOpenWindow().  Event wait still uses raw GetNextEvent since
// this demo brings up only the minimal toolset chain (QD/EM/Sch/Wind)
// and TaskMaster needs Menu/Control/LE/Dialog.  See orcaFrame.c for
// the startdesk-based version that uses iigsEventLoop.

#include "iigs/toolbox.h"
#include "iigs/uiBuilder.h"

#include <stdint.h>


static unsigned char gMsg[] = "\x14Hello from llvm816!";


static unsigned short blockAddr(void *handle) {
    return (unsigned short)(unsigned long)*(void **)handle;
}


int main(void) {
    unsigned short userId = MMStartUp();

    void *dpH = NewHandle(0x900UL, userId, 0xC005, (void *)0);
    unsigned short dpBase = blockAddr(dpH);

    QDStartUp(dpBase, 0, 0xA0, userId);
    EMStartUp((unsigned short)(dpBase + 0x100), 0x14, 0, 0,
              0x14F, 0xC7, userId);
    SchStartUp();
    WindStartUp(userId);

    // fVis+fMove only — fTitle requires Font Manager startup which
    // this minimal demo skips.  Title pointer is set anyway to
    // exercise the R_W65816_BANK16 reloc path even though WM doesn't
    // dereference it without fTitle.
    UiWindowT spec = {
        "llvm816!!",
        UW_VIS | UW_MOVE,
        { 40, 30, 140, 290 },     // v1, h1, v2, h2
        200, 320,
        0,
        (void *)0
    };
    void *win = uiBuilderOpenWindow(&spec);
    if (win) {
        SetPort(win);
        ShowWindow(win);
        MoveTo(20, 30);
        DrawString(gMsg);
    }

    // Brief linger so screen-capture demos can grab a frame.
    for (volatile unsigned long s = 0; s < 400000UL; s++) { }

    // Wait for a keystroke.  Uses raw GetNextEvent (no TaskMaster)
    // because this demo does NOT start the Menu / Control / LE / Dialog
    // chains required by iigsEventLoop's TaskMaster dispatch.
    short evt[8];
    while (1) {
        if (GetNextEvent(0xFFFF, evt)) {
            break;
        }
    }

    SysBeep();
    *(volatile unsigned char *)0x70 = 0x99;
    return 0;
}
