code:
#if (SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION < 3)
static char keytranslation[SDLK_LAST];
#else
static char keytranslation[SDL_NUM_SCANCODES];
#endif
static int32_t buildkeytranslationtable(void);

#if (SDL_MAJOR_VERSION == 1 && SDL_MINOR_VERSION < 3) // SDL 1.2
static int32_t buildkeytranslationtable(void)
{
    memset(keytranslation,0,sizeof(keytranslation));

#define MAP(x,y) keytranslation[x] = y
    MAP(SDLK_BACKSPACE,	0xe);
    MAP(SDLK_TAB,		0xf);
    MAP(SDLK_RETURN,	0x1c);
    MAP(SDLK_PAUSE,		0x59);	// 0x1d + 0x45 + 0x9d + 0xc5
    MAP(SDLK_ESCAPE,	0x1);
    MAP(SDLK_SPACE,		0x39);
    MAP(SDLK_EXCLAIM,	0x2);	// '1'
    MAP(SDLK_QUOTEDBL,	0x28);	// '''
    MAP(SDLK_HASH,		0x4);	// '3'
    MAP(SDLK_DOLLAR,	0x5);	// '4'
    MAP(37,			0x6);	// '5' <-- where's the keysym SDL guys?
    MAP(SDLK_AMPERSAND,	0x8);	// '7'
    MAP(SDLK_QUOTE,		0x28);	// '''
    MAP(SDLK_LEFTPAREN,	0xa);	// '9'
    MAP(SDLK_RIGHTPAREN,	0xb);	// '0'
    MAP(SDLK_ASTERISK,	0x9);	// '8'
    MAP(SDLK_PLUS,		0xd);	// '='
    MAP(SDLK_COMMA,		0x33);
    MAP(SDLK_MINUS,		0xc);
    MAP(SDLK_PERIOD,	0x34);
    MAP(SDLK_SLASH,		0x35);
    MAP(SDLK_0,		0xb);
    MAP(SDLK_1,		0x2);
    MAP(SDLK_2,		0x3);
    MAP(SDLK_3,		0x4);
    MAP(SDLK_4,		0x5);
    MAP(SDLK_5,		0x6);
    MAP(SDLK_6,		0x7);
    MAP(SDLK_7,		0x8);
    MAP(SDLK_8,		0x9);
    MAP(SDLK_9,		0xa);
    MAP(SDLK_COLON,		0x27);
    MAP(SDLK_SEMICOLON,	0x27);
    MAP(SDLK_LESS,		0x56);
    MAP(SDLK_EQUALS,	0xd);
    MAP(SDLK_GREATER,	0x34);
    MAP(SDLK_QUESTION,	0x35);
    MAP(SDLK_AT,		0x3);	// '2'
    MAP(SDLK_LEFTBRACKET,	0x1a);
    MAP(SDLK_BACKSLASH,	0x2b);
    MAP(SDLK_RIGHTBRACKET,	0x1b);
    MAP(SDLK_CARET,		0x7);	// '7'
    MAP(SDLK_UNDERSCORE,	0xc);
    MAP(SDLK_BACKQUOTE,	0x29);
    MAP(SDLK_a,		0x1e);
    MAP(SDLK_b,		0x30);
    MAP(SDLK_c,		0x2e);
    MAP(SDLK_d,		0x20);
    MAP(SDLK_e,		0x12);
    MAP(SDLK_f,		0x21);
    MAP(SDLK_g,		0x22);
    MAP(SDLK_h,		0x23);
    MAP(SDLK_i,		0x17);
    MAP(SDLK_j,		0x24);
    MAP(SDLK_k,		0x25);
    MAP(SDLK_l,		0x26);
    MAP(SDLK_m,		0x32);
    MAP(SDLK_n,		0x31);
    MAP(SDLK_o,		0x18);
    MAP(SDLK_p,		0x19);
    MAP(SDLK_q,		0x10);
    MAP(SDLK_r,		0x13);
    MAP(SDLK_s,		0x1f);
    MAP(SDLK_t,		0x14);
    MAP(SDLK_u,		0x16);
    MAP(SDLK_v,		0x2f);
    MAP(SDLK_w,		0x11);
    MAP(SDLK_x,		0x2d);
    MAP(SDLK_y,		0x15);
    MAP(SDLK_z,		0x2c);
    MAP(SDLK_DELETE,	0xd3);
    MAP(SDLK_KP0,		0x52);
    MAP(SDLK_KP1,		0x4f);
    MAP(SDLK_KP2,		0x50);
    MAP(SDLK_KP3,		0x51);
    MAP(SDLK_KP4,		0x4b);
    MAP(SDLK_KP5,		0x4c);
    MAP(SDLK_KP6,		0x4d);
    MAP(SDLK_KP7,		0x47);
    MAP(SDLK_KP8,		0x48);
    MAP(SDLK_KP9,		0x49);
    MAP(SDLK_KP_PERIOD,	0x53);
    MAP(SDLK_KP_DIVIDE,	0xb5);
    MAP(SDLK_KP_MULTIPLY,	0x37);
    MAP(SDLK_KP_MINUS,	0x4a);
    MAP(SDLK_KP_PLUS,	0x4e);
    MAP(SDLK_KP_ENTER,	0x9c);
    //MAP(SDLK_KP_EQUALS,	);
    MAP(SDLK_UP,		0xc8);
    MAP(SDLK_DOWN,		0xd0);
    MAP(SDLK_RIGHT,		0xcd);
    MAP(SDLK_LEFT,		0xcb);
    MAP(SDLK_INSERT,	0xd2);
    MAP(SDLK_HOME,		0xc7);
    MAP(SDLK_END,		0xcf);
    MAP(SDLK_PAGEUP,	0xc9);
    MAP(SDLK_PAGEDOWN,	0xd1);
    MAP(SDLK_F1,		0x3b);
    MAP(SDLK_F2,		0x3c);
    MAP(SDLK_F3,		0x3d);
    MAP(SDLK_F4,		0x3e);
    MAP(SDLK_F5,		0x3f);
    MAP(SDLK_F6,		0x40);
    MAP(SDLK_F7,		0x41);
    MAP(SDLK_F8,		0x42);
    MAP(SDLK_F9,		0x43);
    MAP(SDLK_F10,		0x44);
    MAP(SDLK_F11,		0x57);
    MAP(SDLK_F12,		0x58);
    MAP(SDLK_NUMLOCK,	0x45);
    MAP(SDLK_CAPSLOCK,	0x3a);
    MAP(SDLK_SCROLLOCK,	0x46);
    MAP(SDLK_RSHIFT,	0x36);
    MAP(SDLK_LSHIFT,	0x2a);
    MAP(SDLK_RCTRL,		0x9d);
    MAP(SDLK_LCTRL,		0x1d);
    MAP(SDLK_RALT,		0xb8);
    MAP(SDLK_LALT,		0x38);
    MAP(SDLK_LSUPER,	0xdb);	// win l
    MAP(SDLK_RSUPER,	0xdc);	// win r
    MAP(SDLK_PRINT,		-2);	// 0xaa + 0xb7
    MAP(SDLK_SYSREQ,	0x54);	// alt+printscr
    MAP(SDLK_BREAK,		0xb7);	// ctrl+pause
    MAP(SDLK_MENU,		0xdd);	// win menu?
#undef MAP

    return 0;
}
#else // if SDL 1.3+
static int32_t buildkeytranslationtable(void)
{
    memset(keytranslation,0,sizeof(keytranslation));

#define MAP(x,y) keytranslation[x] = y
    MAP(SDL_SCANCODE_BACKSPACE,	0xe);
    MAP(SDL_SCANCODE_TAB,		0xf);
    MAP(SDL_SCANCODE_RETURN,	0x1c);
    MAP(SDL_SCANCODE_PAUSE,		0x59);	// 0x1d + 0x45 + 0x9d + 0xc5
    MAP(SDL_SCANCODE_ESCAPE,	0x1);
    MAP(SDL_SCANCODE_SPACE,		0x39);
    MAP(SDL_SCANCODE_COMMA,		0x33);
    MAP(SDL_SCANCODE_NONUSBACKSLASH, 0x56);
    MAP(SDL_SCANCODE_MINUS,		0xc);
    MAP(SDL_SCANCODE_PERIOD,	0x34);
    MAP(SDL_SCANCODE_SLASH,		0x35);
    MAP(SDL_SCANCODE_0,		0xb);
    MAP(SDL_SCANCODE_1,		0x2);
    MAP(SDL_SCANCODE_2,		0x3);
    MAP(SDL_SCANCODE_3,		0x4);
    MAP(SDL_SCANCODE_4,		0x5);
    MAP(SDL_SCANCODE_5,		0x6);
    MAP(SDL_SCANCODE_6,		0x7);
    MAP(SDL_SCANCODE_7,		0x8);
    MAP(SDL_SCANCODE_8,		0x9);
    MAP(SDL_SCANCODE_9,		0xa);
    MAP(SDL_SCANCODE_SEMICOLON,	0x27);
    MAP(SDL_SCANCODE_APOSTROPHE, 0x28);
    MAP(SDL_SCANCODE_EQUALS,	0xd);
    MAP(SDL_SCANCODE_LEFTBRACKET,	0x1a);
    MAP(SDL_SCANCODE_BACKSLASH,	0x2b);
    MAP(SDL_SCANCODE_RIGHTBRACKET,	0x1b);
    MAP(SDL_SCANCODE_A,		0x1e);
    MAP(SDL_SCANCODE_B,		0x30);
    MAP(SDL_SCANCODE_C,		0x2e);
    MAP(SDL_SCANCODE_D,		0x20);
    MAP(SDL_SCANCODE_E,		0x12);
    MAP(SDL_SCANCODE_F,		0x21);
    MAP(SDL_SCANCODE_G,		0x22);
    MAP(SDL_SCANCODE_H,		0x23);
    MAP(SDL_SCANCODE_I,		0x17);
    MAP(SDL_SCANCODE_J,		0x24);
    MAP(SDL_SCANCODE_K,		0x25);
    MAP(SDL_SCANCODE_L,		0x26);
    MAP(SDL_SCANCODE_M,		0x32);
    MAP(SDL_SCANCODE_N,		0x31);
    MAP(SDL_SCANCODE_O,		0x18);
    MAP(SDL_SCANCODE_P,		0x19);
    MAP(SDL_SCANCODE_Q,		0x10);
    MAP(SDL_SCANCODE_R,		0x13);
    MAP(SDL_SCANCODE_S,		0x1f);
    MAP(SDL_SCANCODE_T,		0x14);
    MAP(SDL_SCANCODE_U,		0x16);
    MAP(SDL_SCANCODE_V,		0x2f);
    MAP(SDL_SCANCODE_W,		0x11);
    MAP(SDL_SCANCODE_X,		0x2d);
    MAP(SDL_SCANCODE_Y,		0x15);
    MAP(SDL_SCANCODE_Z,		0x2c);
    MAP(SDL_SCANCODE_DELETE,	0xd3);
    MAP(SDL_SCANCODE_KP_0,		0x52);
    MAP(SDL_SCANCODE_KP_1,		0x4f);
    MAP(SDL_SCANCODE_KP_2,		0x50);
    MAP(SDL_SCANCODE_KP_3,		0x51);
    MAP(SDL_SCANCODE_KP_4,		0x4b);
    MAP(SDL_SCANCODE_KP_5,		0x4c);
    MAP(SDL_SCANCODE_KP_CLEAR,		0x4c);
    MAP(SDL_SCANCODE_CLEAR,		0x4c);
    MAP(SDL_SCANCODE_KP_6,		0x4d);
    MAP(SDL_SCANCODE_KP_7,		0x47);
    MAP(SDL_SCANCODE_KP_8,		0x48);
    MAP(SDL_SCANCODE_KP_9,		0x49);
    MAP(SDL_SCANCODE_KP_PERIOD,	0x53);
    MAP(SDL_SCANCODE_KP_DIVIDE,	0xb5);
    MAP(SDL_SCANCODE_KP_MULTIPLY,	0x37);
    MAP(SDL_SCANCODE_KP_MINUS,	0x4a);
    MAP(SDL_SCANCODE_KP_PLUS,	0x4e);
    MAP(SDL_SCANCODE_KP_ENTER,	0x9c);
    //MAP(SDL_SCANCODE_KP_EQUALS,	);
    MAP(SDL_SCANCODE_UP,		0xc8);
    MAP(SDL_SCANCODE_DOWN,		0xd0);
    MAP(SDL_SCANCODE_RIGHT,		0xcd);
    MAP(SDL_SCANCODE_LEFT,		0xcb);
    MAP(SDL_SCANCODE_INSERT,	0xd2);
    MAP(SDL_SCANCODE_HOME,		0xc7);
    MAP(SDL_SCANCODE_END,		0xcf);
    MAP(SDL_SCANCODE_PAGEUP,	0xc9);
    MAP(SDL_SCANCODE_PAGEDOWN,	0xd1);
    MAP(SDL_SCANCODE_F1,		0x3b);
    MAP(SDL_SCANCODE_F2,		0x3c);
    MAP(SDL_SCANCODE_F3,		0x3d);
    MAP(SDL_SCANCODE_F4,		0x3e);
    MAP(SDL_SCANCODE_F5,		0x3f);
    MAP(SDL_SCANCODE_F6,		0x40);
    MAP(SDL_SCANCODE_F7,		0x41);
    MAP(SDL_SCANCODE_F8,		0x42);
    MAP(SDL_SCANCODE_F9,		0x43);
    MAP(SDL_SCANCODE_F10,		0x44);
    MAP(SDL_SCANCODE_F11,		0x57);
    MAP(SDL_SCANCODE_F12,		0x58);
    MAP(SDL_SCANCODE_NUMLOCKCLEAR,	0x45);
    MAP(SDL_SCANCODE_CAPSLOCK,	0x3a);
    MAP(SDL_SCANCODE_SCROLLLOCK,	0x46);
    MAP(SDL_SCANCODE_RSHIFT,	0x36);
    MAP(SDL_SCANCODE_LSHIFT,	0x2a);
    MAP(SDL_SCANCODE_RCTRL,		0x9d);
    MAP(SDL_SCANCODE_LCTRL,		0x1d);
    MAP(SDL_SCANCODE_RALT,		0xb8);
    MAP(SDL_SCANCODE_LALT,		0x38);
    MAP(SDL_SCANCODE_LGUI,	0xdb);	// win l
    MAP(SDL_SCANCODE_RGUI,	0xdc);	// win r
//    MAP(SDL_SCANCODE_PRINTSCREEN,		-2);	// 0xaa + 0xb7
    MAP(SDL_SCANCODE_SYSREQ,	0x54);	// alt+printscr
//    MAP(SDL_SCANCODE_PAUSE,		0xb7);	// ctrl+pause
    MAP(SDL_SCANCODE_MENU,		0xdd);	// win menu?
    MAP(SDL_SCANCODE_GRAVE,     0x29);  // tilde
#undef MAP

    return 0;
}
#endif


code:
#include "compat.h"
#include "baselayer.h"

#define SJSON_IMPLEMENT

#define sjson_malloc(user, size)       ((UNREFERENCED_PARAMETER(user)), Xmalloc(size))
#define sjson_free(user, ptr)          ((UNREFERENCED_PARAMETER(user)), Xfree(ptr))
#define sjson_realloc(user, ptr, size) ((UNREFERENCED_PARAMETER(user)), Xrealloc(ptr, size))

#define sjson_out_of_memory()		   do { sjson_assert(0 && "Out of memory"); Bexit(EXIT_FAILURE); } while(0)

#include "sjson.h"

repo_name: orochi/nblood

license: mit


code:
// The MIT License (MIT)
//
// 	Copyright (c) 2017-2021 Sergey Makeev
//
// 	Permission is hereby granted, free of charge, to any person obtaining a copy
// 	of this software and associated documentation files (the "Software"), to deal
// 	in the Software without restriction, including without limitation the rights
// 	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// 	copies of the Software, and to permit persons to whom the Software is
// 	furnished to do so, subject to the following conditions:
//
//      The above copyright notice and this permission notice shall be included in
// 	all copies or substantial portions of the Software.
//
// 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// 	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// 	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// 	THE SOFTWARE.
#include "smmalloc.h"
#include "log.h"

namespace sm
{
struct CacheWarmupLink
{
    CacheWarmupLink* pNext;
};

namespace internal
{

void TlsPoolBucket::Init(uint32_t* pCacheStack, uint32_t maxElementsNum, CacheWarmupOptions warmupOptions, Allocator* alloc,
                         size_t bucketIndex)
{
    // assume thread_local variable always initialized with zeroes
    SM_ASSERT(numElementsL0 == 0);
    SM_ASSERT(numElementsL1 == 0);
    SM_ASSERT(pBucket == nullptr);
    SM_ASSERT(pBucketData == nullptr);
    SM_ASSERT(pStorageL1 == nullptr);
    SM_ASSERT(maxElementsCount == 0);

    Allocator::PoolBucket* poolBucket = alloc->GetBucketByIndex(bucketIndex);
    ABORT_IF_F(!poolBucket, "TlsPoolBucket::Init: invalid bucket index");
    SM_ASSERT(maxElementsNum >= SMM_MAX_CACHE_ITEMS_COUNT + 2);
    pStorageL1 = pCacheStack;
    numElementsL1 = 0;
    numElementsL0 = 0;
    maxElementsCount = (maxElementsNum - SMM_MAX_CACHE_ITEMS_COUNT);
    pBucket = poolBucket;
    SM_ASSERT(pBucket);
    pBucketData = pBucket->pData;

    if (warmupOptions == CACHE_COLD)
    {
        return;
    }

    // warmup cache
    uint32_t elementSize = alloc->GetBucketElementSize(bucketIndex);
    uint32_t num = (warmupOptions == CACHE_WARM) ? (maxElementsCount / 2) : (maxElementsCount);

    CacheWarmupLink* pRoot = nullptr;

    for (uint32_t j = 0; j < num; j++)
    {
        // allocate from global (pThreadCache is still nullptr)
        void* p = alloc->Allocate<false>(elementSize, 16);
        if (p == nullptr)
        {
            break;
        }

        // do not steal allocations from different buckets or from generic allocator
        if (alloc->GetBucketIndex(p) != (int32_t)bucketIndex)
        {
            alloc->Free(p);
            break;
        }

        CacheWarmupLink* pItem = (CacheWarmupLink*)p;
        pItem->pNext = pRoot;
        pRoot = pItem;
    }

    // move nodes to cache but passtrhough L0 cache
    CacheWarmupLink* pCurrent = pRoot;
    while (pCurrent)
    {
        CacheWarmupLink* pNext = pCurrent->pNext;
        bool r = alloc->ReleaseToCache<false>(this, pCurrent);
        SMMALLOC_USED_IN_ASSERT(r);
        SM_ASSERT(r);
        pCurrent = pNext;
    }

    SM_ASSERT(GetElementsCount() == num);
}

uint32_t* TlsPoolBucket::Destroy()
{
    // move cached allocations from L0 to L1 (we always has free space for L0 cache inside L1)
    for (uint32_t i = 0; i < numElementsL0; i++)
    {
        pStorageL1[numElementsL1] = storageL0[i];
        numElementsL1++;
    }

    // return all cached elements to master
    if (numElementsL1 > 0)
    {
        ReturnL1CacheToMaster(numElementsL1);
    }

    uint32_t* r = pStorageL1;
    pStorageL1 = nullptr;
    numElementsL0 = 0;
    numElementsL1 = 0;
    maxElementsCount = 0;
    pBucket = nullptr;
    pBucketData = nullptr;
    return r;
}

} // namespace internal

void Allocator::CreateThreadCache(CacheWarmupOptions warmupOptions, std::initializer_list<uint32_t> options)
{
    SM_ASSERT(bucketsCount >= options.size());

    size_t i = 0;
    for (uint32_t _elementsNum : options)
    {
        if (i >= bucketsCount)
        {
            break;
        }

        uint32_t elementsNum = _elementsNum + SMM_MAX_CACHE_ITEMS_COUNT;

        // allocate stack for cache
        uint32_t* localStack = (uint32_t*)GenericAllocator::Alloc(gAllocator, elementsNum * sizeof(uint32_t), 64);

        // initialize
        GetTlsBucket(i)->Init(localStack, elementsNum, warmupOptions, this, i);

        i++;
    }
}

void Allocator::DestroyThreadCache()
{
#if __SANITIZE_ADDRESS__ == 1
        auto buf = this->pBuffer.get();
        ASAN_UNPOISON_MEMORY_REGION(buf, this->pBufferEnd - buf);
#endif
    for (size_t i = 0; i < SMM_MAX_BUCKET_COUNT; i++)
    {
        uint32_t* p = GetTlsBucket(i)->Destroy();
        GenericAllocator::Free(gAllocator, p);
    }
}

void Allocator::PoolBucket::Create(size_t elementSize)
{
    SM_ASSERT(elementSize >= 16 && "Invalid element size");

    // build inplace single linked list
    globalTag.store(0, std::memory_order_relaxed);
    uint8_t* node = pData;

    TaggedIndex headVal;
    headVal.p.tag = globalTag.load(std::memory_order_relaxed);
    headVal.p.offset = (uint32_t)(node - pData);
    head.store(headVal.u);

    while (true)
    {
        uint8_t* next = node + elementSize;
        if ((next + elementSize) <= pBufferEnd)
        {
            TaggedIndex nextVal;
            nextVal.p.tag = globalTag.load(std::memory_order_relaxed);
            ;
            nextVal.p.offset = (uint32_t)(next - pData);
            *((TaggedIndex*)(node)) = nextVal;
        }
        else
        {
            // last node
            ((TaggedIndex*)(node))->u = TaggedIndex::Invalid;
            break;
        }

        node = next;
        globalTag.fetch_add(1, std::memory_order_relaxed);
    }
}

Allocator::Allocator(GenericAllocator::TInstance allocator)
    : bucketsCount(0)
    , bucketSizeInBytes(0)
    , pBufferEnd(nullptr)
    , pBuffer(nullptr, GenericAllocator::Deleter(allocator))
    , gAllocator(allocator)
{
#ifdef SMMALLOC_STATS_SUPPORT
    globalMissCount.store(0);
#endif
}

// Return the next power of 2 higher than the input
// If the input is already a power of 2, the output will be the same as the input.
// Got this from Brian Sharp's SWEng mailing list.
inline int GetNextPow2(uint32_t n)
{
    n -= 1;

    n |= n >> 16;
    n |= n >> 8;
    n |= n >> 4;
    n |= n >> 2;
    n |= n >> 1;

    return n + 1;
}

void Allocator::Init(uint32_t _bucketsCount, size_t _bucketSizeInBytes)
{
    if (bucketsCount > 0)
    {
        // already initialized
        return;
    }

    SM_ASSERT(_bucketsCount > 0 && _bucketsCount <= 64);
    if (_bucketsCount == 0)
    {
        return;
    }

    bucketsCount = _bucketsCount;
    size_t alignmentMax = GetNextPow2((uint32_t)(16 * bucketsCount));
    bucketSizeInBytes = Align(_bucketSizeInBytes, alignmentMax);

    size_t i = 0;
    for (i = 0; i < bucketsDataBegin.size(); i++)
    {
        bucketsDataBegin[i] = nullptr;
    }

    size_t totalBytesCount = bucketSizeInBytes * bucketsCount;
    pBuffer.reset((uint8_t*)GenericAllocator::Alloc(gAllocator, totalBytesCount, alignmentMax));
    pBufferEnd = pBuffer.get() + totalBytesCount + 1;

    size_t elementSize = 16;
    for (i = 0; i < bucketsCount; i++)
    {
        PoolBucket& bucket = buckets[i];
        bucket.pData = pBuffer.get() + i * bucketSizeInBytes;
        SM_ASSERT(IsAligned(size_t(bucket.pData), GetNextPow2(uint32_t(elementSize))) && "Alignment failed");
        bucket.pBufferEnd = bucket.pData + bucketSizeInBytes;
        bucket.Create(elementSize);
        elementSize += 16;
        bucketsDataBegin[i] = bucket.pData;
    }
}

} // namespace sm


code:
// The MIT License (MIT)
//
// 	Copyright (c) 2017-2021 Sergey Makeev
//
// 	Permission is hereby granted, free of charge, to any person obtaining a copy
// 	of this software and associated documentation files (the "Software"), to deal
// 	in the Software without restriction, including without limitation the rights
// 	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// 	copies of the Software, and to permit persons to whom the Software is
// 	furnished to do so, subject to the following conditions:
//
//      The above copyright notice and this permission notice shall be included in
// 	all copies or substantial portions of the Software.
//
// 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// 	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// 	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// 	THE SOFTWARE.
#include "mimalloc-new-delete.h"

#if __SANITIZE_ADDRESS__ != 1

#include "compat.h"
#include "mimalloc-override.h"
#include "smmalloc.h"
#include <stdlib.h>

struct Header
{
    void* p;
    size_t size;
};

sm::GenericAllocator::TInstance sm::GenericAllocator::Invalid() { return nullptr; }

bool sm::GenericAllocator::IsValid(TInstance instance)
{
    SMMALLOC_UNUSED(instance);
    return true;
}

sm::GenericAllocator::TInstance sm::GenericAllocator::Create() { return nullptr; }

void sm::GenericAllocator::Destroy(sm::GenericAllocator::TInstance instance) { SMMALLOC_UNUSED(instance); }

void* sm::GenericAllocator::Alloc(sm::GenericAllocator::TInstance instance, size_t bytesCount, size_t alignment)
{
    SMMALLOC_UNUSED(instance);
    if (alignment < sm::Allocator::kMinValidAlignment)
    {
        alignment = sm::Allocator::kMinValidAlignment;
    }
    void* p;
    void** p2;
    size_t offset = alignment - 1 + sizeof(Header);
    if ((p = (void*)
#ifdef MIMALLOC_OVERRIDE_H
        mi_malloc_aligned(bytesCount + offset, alignment)
#else
        std::malloc(bytesCount + offset)
#endif
        ) == NULL)
    {
        return NULL;
    }
    p2 = (void**)(((size_t)(p) + offset) & ~(alignment - 1));

    Header* h = reinterpret_cast<Header*>(reinterpret_cast<char*>(p2) - sizeof(Header));
    h->p = p;
    h->size = bytesCount;
    return p2;
}

void sm::GenericAllocator::Free(sm::GenericAllocator::TInstance instance, void* p)
{
    SMMALLOC_UNUSED(instance);
    if (!p)
    {
        return;
    }
    Header* h = reinterpret_cast<Header*>(reinterpret_cast<char*>(p) - sizeof(Header));
#ifdef MIMALLOC_OVERRIDE_H
    mi_free(h->p);
#else
    std::free(h->p);
#endif
}

void* sm::GenericAllocator::Realloc(sm::GenericAllocator::TInstance instance, void* p, size_t bytesCount, size_t alignment)
{
    SMMALLOC_UNUSED(instance);

    void* p2 = Alloc(instance, bytesCount, alignment);
    if (!p2)
    {
        // https://en.cppreference.com/w/c/memory/realloc
        // If there is not enough memory, the old memory block is not freed and null pointer is returned.
        return nullptr;
    }

    if (p)
    {
        size_t oldBlockSize = GetUsableSpace(instance, p);
        std::memmove(p2, p, std::min(oldBlockSize, bytesCount));
    }

    Free(instance, p);
    return p2;
}

size_t sm::GenericAllocator::GetUsableSpace(sm::GenericAllocator::TInstance instance, void* p)
{
    SMMALLOC_UNUSED(instance);

    if (!p)
    {
        return 0;
    }

    Header* h = reinterpret_cast<Header*>(reinterpret_cast<char*>(p) - sizeof(Header));
    return h->size;
}
#endif // __SANITIZE_ADDRESS__


code:
// The MIT License (MIT)
//
// 	Copyright (c) 2017-2021 Sergey Makeev
//
// 	Permission is hereby granted, free of charge, to any person obtaining a copy
// 	of this software and associated documentation files (the "Software"), to deal
// 	in the Software without restriction, including without limitation the rights
// 	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// 	copies of the Software, and to permit persons to whom the Software is
// 	furnished to do so, subject to the following conditions:
//
//      The above copyright notice and this permission notice shall be included in
// 	all copies or substantial portions of the Software.
//
// 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// 	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// 	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// 	THE SOFTWARE.
#include "smmalloc.h"

thread_local sm::internal::TlsPoolBucket tlsCacheBuckets[SMM_MAX_BUCKET_COUNT];
// sm::internal::TlsPoolBucket tlsCacheBuckets[SMM_MAX_BUCKET_COUNT];

namespace sm
{

sm::internal::TlsPoolBucket* GetTlsBucket(size_t index) { return &tlsCacheBuckets[index]; }

} // namespace sm


code:
/*
 * softsurface.cpp
 *  An 8-bit rendering surface that can quickly upscale and blit 8-bit paletted buffers to an external 32-bit buffer.
 *
 * Copyright � 2018, Alex Dawson. All rights reserved.
 */

#include "softsurface.h"

#include "pragmas.h"
#include "build.h"

static int bufferSize;
static uint8_t* buffer;
static vec2_t bufferRes;

static vec2_t destBufferRes;

static uint32_t xScale16;
static uint32_t yScale16;
static uint32_t recXScale16;

static uint32_t pPal[256];

// lookup table to find the source position within a scanline
static uint16_t* scanPosLookupTable;

template <uint32_t multiple>
static uint32_t roundUp(uint32_t num)
{
    return (num+multiple-1)/multiple * multiple;
}

static uint32_t countTrailingZeros(uint32_t u)
{
#if (defined __GNUC__  && __GNUC__>=3) || defined __clang__
    return __builtin_ctz(u);
#elif defined _MSC_VER
    DWORD result;
    _BitScanForward(&result, u);
    return result;
#else
    uint32_t last = u;
    for (; u != 0; last = u, u >>= 1);
    return last;
#endif
}

bool softsurface_initialize(vec2_t bufferResolution,
                            vec2_t destBufferResolution)
{
    if (buffer)
        softsurface_destroy();

    bufferRes = bufferResolution;
    destBufferRes = destBufferResolution;

    xScale16 = divscale16(destBufferRes.x, bufferRes.x);
    yScale16 = divscale16(destBufferRes.y, bufferRes.y);
    recXScale16 = divscale16(bufferRes.x, destBufferRes.x);

    // allocate one continuous block of memory large enough to hold the buffer, the palette,
    // and the scanPosLookupTable while maintaining alignment for each
    uint32_t newBufferSize = roundUp<16>(bufferRes.x * bufferRes.y);

    bufferSize = newBufferSize + sizeof(uint16_t) * destBufferRes.x;
    buffer     = (uint8_t *)Xmalloc(bufferSize);

    scanPosLookupTable = (uint16_t *)(buffer + newBufferSize);

    // calculate the scanPosLookupTable for horizontal scaling
    uint32_t incr = recXScale16;
    for (int32_t i = 0; i < destBufferRes.x; ++i)
    {
        scanPosLookupTable[i] = incr >> 16;
        incr += recXScale16;
    }

    return true;
}

void softsurface_destroy()
{
    if (!buffer)
        return;

    DO_FREE_AND_NULL(buffer);

    scanPosLookupTable = 0;

    xScale16 = 0;
    yScale16 = 0;
    recXScale16 = 0;

    bufferRes = {};
    destBufferRes = {};
}

void softsurface_setPalette(void* pPalette,
                            uint32_t destRedMask,
                            uint32_t destGreenMask,
                            uint32_t destBlueMask)
{
    if (!buffer)
        return;
    if (!pPalette)
        return;

    uint32_t destRedShift = countTrailingZeros(destRedMask);
    uint32_t destRedLoss = 8 - countTrailingZeros((destRedMask>>destRedShift)+1);
    uint32_t destGreenShift = countTrailingZeros(destGreenMask);
    uint32_t destGreenLoss = 8 - countTrailingZeros((destGreenMask>>destGreenShift)+1);
    uint32_t destBlueShift = countTrailingZeros(destBlueMask);
    uint32_t destBlueLoss = 8 - countTrailingZeros((destBlueMask>>destBlueShift)+1);

    uint8_t* pUI8Palette = (uint8_t*) pPalette;
    for (int i = 0; i < 256; ++i)
    {
        pPal[i] = ((pUI8Palette[sizeof(uint32_t)*i] >> destRedLoss << destRedShift) & destRedMask) |
                  ((pUI8Palette[sizeof(uint32_t)*i+1] >> destGreenLoss << destGreenShift) & destGreenMask) |
                  ((pUI8Palette[sizeof(uint32_t)*i+2] >> destBlueLoss << destBlueShift) & destBlueMask);
    }
}

uint8_t* softsurface_getBuffer()
{
    return buffer;
}

vec2_t softsurface_getBufferResolution()
{
    return bufferRes;
}

vec2_t softsurface_getDestinationBufferResolution()
{
    return destBufferRes;
}

#define BLIT(x) pDst[x] = *((UINTTYPE*)(pPal+pSrc[pScanPos[x]]))
#define BLIT2(x) BLIT(x); BLIT(x+1)
#define BLIT4(x) BLIT2(x); BLIT2(x+2)
#define BLIT8(x) BLIT4(x); BLIT4(x+4)
#define BLIT16(x) BLIT8(x); BLIT8(x+8)
#define BLIT32(x) BLIT16(x); BLIT16(x+16)
#define BLIT64(x) BLIT32(x); BLIT32(x+32)
template <typename UINTTYPE>
void softsurface_blitBufferInternal(UINTTYPE* destBuffer)
{
    const uint8_t* __restrict pSrc = buffer;
    UINTTYPE* __restrict pDst = destBuffer;
    const UINTTYPE* const pEnd = destBuffer+destBufferRes.x*mulscale16(yScale16, bufferRes.y);
    uint32_t remainder = 0;
    while (pDst < pEnd)
    {
        uint16_t* __restrict pScanPos = scanPosLookupTable;
        UINTTYPE* const pScanEnd = pDst+destBufferRes.x;
        while (pDst < pScanEnd-64)
        {
            BLIT64(0);
            pDst += 64;
            pScanPos += 64;
        }
        while (pDst < pScanEnd)
        {
            BLIT(0);
            ++pDst;
            ++pScanPos;
        }
        pSrc += bufferRes.x;

        static const uint32_t MASK16 = (1<<16)-1;
        uint32_t linesCopied = 1;
        uint32_t linesToCopy = yScale16+remainder;
        remainder = linesToCopy & MASK16;
        linesToCopy = (linesToCopy >> 16)-1;
        const UINTTYPE* const __restrict pScanLineSrc = pDst-destBufferRes.x;
        while (linesToCopy)
        {
            uint32_t lines = min(linesCopied, linesToCopy);
            memcpy(pDst, pScanLineSrc, sizeof(UINTTYPE)*lines*destBufferRes.x);
            pDst += lines*destBufferRes.x;
            linesToCopy -= lines;
        }
    }
}

void softsurface_blitBuffer(uint32_t* destBuffer,
                            uint32_t destBpp)
{
    if (!buffer)
        return;
    if (!destBuffer)
        return;

    switch (destBpp)
    {
    case 15:
    case 16:
        softsurface_blitBufferInternal<uint16_t>((uint16_t*) destBuffer);
        break;
    case 24:
    case 32:
        softsurface_blitBufferInternal<uint32_t>(destBuffer);
        break;
    default:
        return;
    }
}


code:
#include "gtkpixdata.h"

#include "dynamicgtk.h"

#include "build.h"
#include "editor.h"
#include "baselayer.h"

enum
{
    TAB_CONFIG,
    TAB_MESSAGES,
};

static struct
{
    GtkWidget *startwin;
    GtkWidget *hlayout;
    GtkWidget *banner;
    GtkWidget *vlayout;
    GtkWidget *tabs;
    GtkWidget *configtlayout;
    GtkWidget *vmode3dlabel;
    GtkWidget *vmode3dcombo;
    GtkWidget *fullscreencheck;
    GtkWidget *emptyhlayout;
    GtkWidget *alwaysshowcheck;
    GtkWidget *usecwdcheck;
    GtkWidget *configtab;
    GtkWidget *messagesscroll;
    GtkWidget *messagestext;
    GtkWidget *messagestab;
    GtkWidget *buttons;
    GtkWidget *cancelbutton;
    GtkWidget *cancelbuttonalign;
    GtkWidget *cancelbuttonlayout;
    GtkWidget *cancelbuttonicon;
    GtkWidget *cancelbuttonlabel;
    GtkWidget *startbutton;
    GtkWidget *startbuttonalign;
    GtkWidget *startbuttonlayout;
    GtkWidget *startbuttonicon;
    GtkWidget *startbuttonlabel;
    GtkAccelGroup *accel_group;
} stwidgets;

static struct
{
    int32_t fullscreen;
    int32_t xdim3d, ydim3d, bpp3d;
    int32_t forcesetup, usecwd;
} settings;

static int32_t retval = -1, mode = TAB_MESSAGES;
extern int32_t gtkenabled;
static void PopulateForm(void);

// -- EVENT CALLBACKS AND CREATION STUFF --------------------------------------

static void on_vmode3dcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    GtkTreeModel *data;
    GtkTreeIter iter;
    int32_t val;
    UNREFERENCED_PARAMETER(user_data);
    if (!gtk_combo_box_get_active_iter(combobox, &iter)) return;
    if (!(data = gtk_combo_box_get_model(combobox))) return;
    gtk_tree_model_get(data, &iter, 1, &val, -1);
    settings.xdim3d = validmode[val].xdim;
    settings.ydim3d = validmode[val].ydim;
    settings.bpp3d = validmode[val].bpp;
}

static void on_fullscreencheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.fullscreen = (gtk_toggle_button_get_active(togglebutton) == TRUE);
    PopulateForm();
}

static void on_alwaysshowcheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.forcesetup = (gtk_toggle_button_get_active(togglebutton) == TRUE);
}

static void on_usecwdcheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.usecwd = (gtk_toggle_button_get_active(togglebutton) == TRUE);
}

static void on_cancelbutton_clicked(GtkButton *button, gpointer user_data)
{
    UNREFERENCED_PARAMETER(button);
    UNREFERENCED_PARAMETER(user_data);
    if (mode == TAB_CONFIG) { retval = 0; gtk_main_quit(); }
    else quitevent++;
}

static void on_startbutton_clicked(GtkButton *button, gpointer user_data)
{
    UNREFERENCED_PARAMETER(button);
    UNREFERENCED_PARAMETER(user_data);
    retval = 1;
    gtk_main_quit();
}

static gboolean on_startwin_delete_event(GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
    UNREFERENCED_PARAMETER(widget);
    UNREFERENCED_PARAMETER(event);
    UNREFERENCED_PARAMETER(user_data);
    if (mode == TAB_CONFIG) { retval = 0; gtk_main_quit(); }
    else quitevent++;
    return TRUE;	// FALSE would let the event go through. we want the game to decide when to close
}

// -- SUPPORT FUNCTIONS -------------------------------------------------------

static GdkPixbuf *load_banner(void)
{
    return gdk_pixbuf_from_pixdata((GdkPixdata const *)&startbanner_pixdata, FALSE, NULL);
}

static void SetPage(int32_t n)
{
    if (!gtkenabled || !stwidgets.startwin) return;
    mode = n;
    gtk_notebook_set_current_page(GTK_NOTEBOOK(stwidgets.tabs), n);

    // each control in the config page vertical layout plus the start button should be made (in)sensitive
    if (n == TAB_CONFIG) n = TRUE; else n = FALSE;
    gtk_widget_set_sensitive(stwidgets.startbutton, n);
    gtk_container_foreach(GTK_CONTAINER(stwidgets.configtlayout),
                          (GtkCallback)gtk_widget_set_sensitive,
                          (gpointer)&n);
}

static void PopulateForm(void)
{
    int32_t mode3d, i;
    GtkListStore *modes3d;
    GtkTreeIter iter;
    GtkComboBox *box3d;
    char buf[64];

    mode3d = videoCheckMode(&settings.xdim3d, &settings.ydim3d, settings.bpp3d, settings.fullscreen, 1);
    if (mode3d < 0)
    {
        int32_t i, cd[] = { 32, 24, 16, 15, 8, 0 };
        for (i=0; cd[i];) { if (cd[i] >= settings.bpp3d) i++; else break; }
        for (; cd[i]; i++)
        {
            mode3d = videoCheckMode(&settings.xdim3d, &settings.ydim3d, cd[i], settings.fullscreen, 1);
            if (mode3d < 0) continue;
            settings.bpp3d = cd[i];
            break;
        }
    }

    box3d = GTK_COMBO_BOX(stwidgets.vmode3dcombo);
    modes3d = GTK_LIST_STORE(gtk_combo_box_get_model(box3d));
    gtk_list_store_clear(modes3d);

    for (i=0; i<validmodecnt; i++)
    {
        if (validmode[i].fs != settings.fullscreen) continue;

        // all modes get added to the 3D mode list
        Bsprintf(buf, "%dx%d %s", validmode[i].xdim, validmode[i].ydim, validmode[i].bpp == 8 ? "software" : "OpenGL");
        gtk_list_store_append(modes3d, &iter);
        gtk_list_store_set(modes3d, &iter, 0,buf, 1,i, -1);
        if (i == mode3d)
        {
            g_signal_handlers_block_by_func(box3d, (gpointer)on_vmode3dcombo_changed, NULL);
            gtk_combo_box_set_active_iter(box3d, &iter);
            g_signal_handlers_unblock_by_func(box3d, (gpointer)on_vmode3dcombo_changed, NULL);
        }
    }

    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.fullscreencheck), settings.fullscreen);
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.alwaysshowcheck), settings.forcesetup);
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.usecwdcheck), settings.usecwd);
}

static GtkWidget *create_window(void)
{
    stwidgets.accel_group = gtk_accel_group_new();

    // Basic window
    stwidgets.startwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(stwidgets.startwin), apptitle);	// NOTE: use global app title
    gtk_window_set_position(GTK_WINDOW(stwidgets.startwin), GTK_WIN_POS_CENTER);
    gtk_window_set_resizable(GTK_WINDOW(stwidgets.startwin), FALSE);
    gtk_window_set_type_hint(GTK_WINDOW(stwidgets.startwin), GDK_WINDOW_TYPE_HINT_DIALOG);

    // Horizontal layout of banner and controls
    stwidgets.hlayout = gtk_hbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.startwin), stwidgets.hlayout);

    // banner
    {
        GdkPixbuf *pixbuf = load_banner();
        stwidgets.banner = gtk_image_new_from_pixbuf(pixbuf);
        g_object_unref((gpointer)pixbuf);
    }
    gtk_box_pack_start(GTK_BOX(stwidgets.hlayout), stwidgets.banner, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(stwidgets.banner), 0.5, 0);

    // Vertical layout of tab control and start+cancel buttons
    stwidgets.vlayout = gtk_vbox_new(FALSE, 0);
    gtk_box_pack_start(GTK_BOX(stwidgets.hlayout), stwidgets.vlayout, TRUE, TRUE, 0);

    // Tab control
    stwidgets.tabs = gtk_notebook_new();
    gtk_box_pack_start(GTK_BOX(stwidgets.vlayout), stwidgets.tabs, TRUE, TRUE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.tabs), 4);

    // layout table of config page
    stwidgets.configtlayout = gtk_table_new(4, 3, FALSE);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.configtlayout);

    // Fullscreen checkbox
    stwidgets.fullscreencheck = gtk_check_button_new_with_mnemonic("_Fullscreen");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.fullscreencheck, 2,3, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 24);
    gtk_widget_add_accelerator(stwidgets.fullscreencheck, "grab_focus", stwidgets.accel_group,
                               GDK_F, GDK_MOD1_MASK,
                               GTK_ACCEL_VISIBLE);

    // Video mode label
    stwidgets.vmode3dlabel = gtk_label_new_with_mnemonic("_Video mode:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.vmode3dlabel), 0.3, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dlabel, 0,1, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 24);

    // Video mode combo
    {
        GtkListStore *list = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT);
        GtkCellRenderer *cell;

        stwidgets.vmode3dcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.vmode3dcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.vmode3dcombo), cell, "text", 0, nullptr);
    }
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dcombo, 1,2, 0,1,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 0);
    gtk_widget_add_accelerator(stwidgets.vmode3dcombo, "grab_focus", stwidgets.accel_group,
                               GDK_V, GDK_MOD1_MASK,
                               GTK_ACCEL_VISIBLE);

    // Empty horizontal layout
    stwidgets.emptyhlayout = gtk_hbox_new(TRUE, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.emptyhlayout, 0,1, 2,3, (GtkAttachOptions)0,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 0, 0);

    // Always show config checkbox
    stwidgets.alwaysshowcheck = gtk_check_button_new_with_mnemonic("_Always show configuration on start");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.alwaysshowcheck, 0,2, 3,4, GTK_FILL, (GtkAttachOptions)0, 4, 6);
    gtk_widget_add_accelerator(stwidgets.alwaysshowcheck, "grab_focus", stwidgets.accel_group,
                               GDK_A, GDK_MOD1_MASK,
                               GTK_ACCEL_VISIBLE);

    // "Working directory only" checkbox
    stwidgets.usecwdcheck = gtk_check_button_new_with_mnemonic("_Working directory only");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.usecwdcheck, 0,2, 4,5, GTK_FILL, (GtkAttachOptions)0, 4, 6);
    gtk_widget_add_accelerator(stwidgets.usecwdcheck, "grab_focus", stwidgets.accel_group,
                               GDK_W, GDK_MOD1_MASK,
                               GTK_ACCEL_VISIBLE);

    // Configuration tab
    stwidgets.configtab = gtk_label_new("Configuration");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 0), stwidgets.configtab);

    // Messages scrollable area
    stwidgets.messagesscroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.messagesscroll);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(stwidgets.messagesscroll), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);

    // Messages text area
    stwidgets.messagestext = gtk_text_view_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.messagesscroll), stwidgets.messagestext);
    gtk_text_view_set_editable(GTK_TEXT_VIEW(stwidgets.messagestext), FALSE);
    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(stwidgets.messagestext), GTK_WRAP_WORD);
    gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(stwidgets.messagestext), FALSE);
    gtk_text_view_set_left_margin(GTK_TEXT_VIEW(stwidgets.messagestext), 2);
    gtk_text_view_set_right_margin(GTK_TEXT_VIEW(stwidgets.messagestext), 2);

    // Messages tab
    stwidgets.messagestab = gtk_label_new("Messages");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 1), stwidgets.messagestab);

    // Dialogue box buttons layout
    stwidgets.buttons = gtk_hbutton_box_new();
    gtk_box_pack_start(GTK_BOX(stwidgets.vlayout), stwidgets.buttons, FALSE, TRUE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.buttons), 3);
    gtk_button_box_set_layout(GTK_BUTTON_BOX(stwidgets.buttons), GTK_BUTTONBOX_END);

    // Cancel button
    stwidgets.cancelbutton = gtk_button_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.buttons), stwidgets.cancelbutton);
    GTK_WIDGET_SET_FLAGS(stwidgets.cancelbutton, GTK_CAN_DEFAULT);
    gtk_widget_add_accelerator(stwidgets.cancelbutton, "grab_focus", stwidgets.accel_group,
                               GDK_C, GDK_MOD1_MASK,
                               GTK_ACCEL_VISIBLE);
    gtk_widget_add_accelerator(stwidgets.cancelbutton, "clicked", stwidgets.accel_group,
                               GDK_Escape, (GdkModifierType)0,
                               GTK_ACCEL_VISIBLE);

    stwidgets.cancelbuttonalign = gtk_alignment_new(0.5, 0.5, 0, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.cancelbutton), stwidgets.cancelbuttonalign);

    stwidgets.cancelbuttonlayout = gtk_hbox_new(FALSE, 2);
    gtk_container_add(GTK_CONTAINER(stwidgets.cancelbuttonalign), stwidgets.cancelbuttonlayout);

    stwidgets.cancelbuttonicon = gtk_image_new_from_stock("gtk-cancel", GTK_ICON_SIZE_BUTTON);
    gtk_box_pack_start(GTK_BOX(stwidgets.cancelbuttonlayout), stwidgets.cancelbuttonicon, FALSE, FALSE, 0);

    stwidgets.cancelbuttonlabel = gtk_label_new_with_mnemonic("_Cancel");
    gtk_box_pack_start(GTK_BOX(stwidgets.cancelbuttonlayout), stwidgets.cancelbuttonlabel, FALSE, FALSE, 0);

    // Start button
    stwidgets.startbutton = gtk_button_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.buttons), stwidgets.startbutton);
    GTK_WIDGET_SET_FLAGS(stwidgets.startbutton, GTK_CAN_DEFAULT);
    gtk_widget_add_accelerator(stwidgets.startbutton, "grab_focus", stwidgets.accel_group,
                               GDK_S, GDK_MOD1_MASK,
                               GTK_ACCEL_VISIBLE);
    gtk_widget_add_accelerator(stwidgets.startbutton, "clicked", stwidgets.accel_group,
                               GDK_Return, (GdkModifierType)0,
                               GTK_ACCEL_VISIBLE);

    stwidgets.startbuttonalign = gtk_alignment_new(0.5, 0.5, 0, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.startbutton), stwidgets.startbuttonalign);

    stwidgets.startbuttonlayout = gtk_hbox_new(FALSE, 2);
    gtk_container_add(GTK_CONTAINER(stwidgets.startbuttonalign), stwidgets.startbuttonlayout);

    stwidgets.startbuttonicon = gtk_image_new_from_stock("gtk-execute", GTK_ICON_SIZE_BUTTON);
    gtk_box_pack_start(GTK_BOX(stwidgets.startbuttonlayout), stwidgets.startbuttonicon, FALSE, FALSE, 0);

    stwidgets.startbuttonlabel = gtk_label_new_with_mnemonic("_Start");
    gtk_box_pack_start(GTK_BOX(stwidgets.startbuttonlayout), stwidgets.startbuttonlabel, FALSE, FALSE, 0);

    // Wire up the signals
    g_signal_connect((gpointer) stwidgets.startwin, "delete_event",
                     G_CALLBACK(on_startwin_delete_event),
                     NULL);
    g_signal_connect((gpointer) stwidgets.vmode3dcombo, "changed",
                     G_CALLBACK(on_vmode3dcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.fullscreencheck, "toggled",
                     G_CALLBACK(on_fullscreencheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.alwaysshowcheck, "toggled",
                     G_CALLBACK(on_alwaysshowcheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.usecwdcheck, "toggled",
                     G_CALLBACK(on_usecwdcheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.cancelbutton, "clicked",
                     G_CALLBACK(on_cancelbutton_clicked),
                     NULL);
    g_signal_connect((gpointer) stwidgets.startbutton, "clicked",
                     G_CALLBACK(on_startbutton_clicked),
                     NULL);

    // Associate labels with their controls
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.vmode3dlabel), stwidgets.vmode3dcombo);

    gtk_window_add_accel_group(GTK_WINDOW(stwidgets.startwin), stwidgets.accel_group);

    return stwidgets.startwin;
}

// -- BUILD ENTRY POINTS ------------------------------------------------------

bool startwin_isopen(void)
{
    return gtkenabled && stwidgets.startwin;
}

int32_t startwin_open(void)
{
    if (!gtkenabled) return 0;
    if (stwidgets.startwin) return 1;

    stwidgets.startwin = create_window();
    if (stwidgets.startwin)
    {
        SetPage(TAB_MESSAGES);
        gtk_widget_show_all(stwidgets.startwin);
        gtk_main_iteration_do(FALSE);
        return 0;
    }
    return -1;
}

int32_t startwin_close(void)
{
    if (!gtkenabled) return 0;
    if (!stwidgets.startwin) return 1;
    gtk_widget_destroy(stwidgets.startwin);
    stwidgets.startwin = NULL;
    return 0;
}

int32_t startwin_puts(const char *str)
{
    GtkWidget *textview;
    GtkTextBuffer *textbuffer;
    GtkTextIter enditer;
    GtkTextMark *mark;
    const char *aptr, *bptr;

    if (!gtkenabled || !str) return 0;
    if (!stwidgets.startwin) return 1;
    if (!(textview = stwidgets.messagestext)) return -1;
    textbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));

    gtk_text_buffer_get_end_iter(textbuffer, &enditer);
    for (aptr = bptr = str; *aptr != 0;)
    {
        switch (*bptr)
        {
        case '\b':
            if (bptr > aptr)
                gtk_text_buffer_insert(textbuffer, &enditer, (const gchar *)aptr, (gint)(bptr-aptr)-1);
#if GTK_CHECK_VERSION(2,6,0)
            gtk_text_buffer_backspace(textbuffer, &enditer, FALSE, TRUE);
#else
            {
                GtkTextIter iter2 = enditer;
                gtk_text_iter_backward_cursor_position(&iter2);
                //FIXME: this seems be deleting one too many chars somewhere!
                if (!gtk_text_iter_equal(&iter2, &enditer))
                    gtk_text_buffer_delete_interactive(textbuffer, &iter2, &enditer, TRUE);
            }
#endif
            aptr = ++bptr;
            break;
        case 0:
            if (bptr > aptr)
                gtk_text_buffer_insert(textbuffer, &enditer, (const gchar *)aptr, (gint)(bptr-aptr));
            aptr = bptr;
            break;
        case '\r':	// FIXME
        default:
            bptr++;
            break;
        }
    }

    mark = gtk_text_buffer_create_mark(textbuffer, NULL, &enditer, 1);
    gtk_text_view_scroll_to_mark(GTK_TEXT_VIEW(textview), mark, 0.0, FALSE, 0.0, 1.0);
    gtk_text_buffer_delete_mark(textbuffer, mark);

    return 0;
}

int32_t startwin_settitle(const char *title)
{
    if (!gtkenabled) return 0;
    if (!stwidgets.startwin) return 1;
    gtk_window_set_title(GTK_WINDOW(stwidgets.startwin), title);
    return 0;
}

int32_t startwin_idle(void *s)
{
    UNREFERENCED_PARAMETER(s);
    if (!gtkenabled) return 0;
    //if (!stwidgets.startwin) return 1;
    gtk_main_iteration_do(FALSE);
    return 0;
}

int32_t startwin_run(void)
{
    if (!gtkenabled) return 1;
    if (!stwidgets.startwin) return 1;

    SetPage(TAB_CONFIG);

    settings.fullscreen = fullscreen;
    settings.xdim3d = xdim;
    settings.ydim3d = ydim;
    settings.bpp3d = bpp;
    settings.forcesetup = forcesetup;
    settings.usecwd = g_useCwd;
    PopulateForm();

    gtk_main();

    SetPage(TAB_MESSAGES);
    if (retval)
    {
        fullscreen = settings.fullscreen;
        xdim = settings.xdim3d;
        ydim = settings.ydim3d;
        bpp = settings.bpp3d;
        forcesetup = settings.forcesetup;
        g_useCwd = settings.usecwd;
    }

    return retval;
}


code:
#import <Cocoa/Cocoa.h>

#include "compat.h"
#include "baselayer.h"
#include "build.h"
#include "editor.h"
#include "osxbits.h"

#ifndef MAC_OS_X_VERSION_10_5
# define NSImageScaleNone NSScaleNone
#endif

#ifndef MAC_OS_X_VERSION_10_12
# define NSEventModifierFlagOption NSAlternateKeyMask
# define NSEventModifierFlagCommand NSCommandKeyMask
# define NSEventMaskAny NSAnyEventMask
# define NSWindowStyleMaskTitled NSTitledWindowMask
# define NSWindowStyleMaskClosable NSClosableWindowMask
# define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
# define NSWindowStyleMaskResizable NSResizableWindowMask
# define NSAlertStyleInformational NSInformationalAlertStyle
# define NSControlSizeSmall NSSmallControlSize
#endif

#ifndef MAC_OS_X_VERSION_10_14
# define NSButtonTypeSwitch NSSwitchButton
# define NSBezelStyleRounded NSRoundedBezelStyle
# define NSControlStateValueOn NSOnState
# define NSControlStateValueOff NSOffState
#endif

static inline NSRect NSRectChangeXY(NSRect const rect, CGFloat const x, CGFloat const y)
{
    return NSMakeRect(x, y, rect.size.width, rect.size.height);
}
static inline NSRect NSSizeAddXY(NSSize const size, CGFloat const x, CGFloat const y)
{
    return NSMakeRect(x, y, size.width, size.height);
}
static inline CGFloat NSRightEdge(NSRect rect)
{
    return rect.origin.x + rect.size.width;
}
static inline CGFloat NSTopEdge(NSRect rect)
{
    return rect.origin.y + rect.size.height;
}

static inline void setFontToSmall(id control)
{
    [control setFont:[NSFont fontWithDescriptor:[[control font] fontDescriptor] size:[NSFont smallSystemFontSize]]];
}

static inline void setControlToSmall(id control)
{
    [control setControlSize:NSControlSizeSmall];
}

static inline NSTextField * makeLabel(NSString * labelText)
{
    NSTextField *textField = [[NSTextField alloc] init];
    setFontToSmall(textField);
    setControlToSmall([textField cell]);
    [textField setStringValue:labelText];
    [textField setBezeled:NO];
    [textField setDrawsBackground:NO];
    [textField setEditable:NO];
    [textField setSelectable:NO];
    [textField sizeToFit];
    return textField;
}

static inline NSButton * makeCheckbox(NSString * labelText)
{
    NSButton *checkbox = [[NSButton alloc] init];
    setFontToSmall(checkbox);
    setControlToSmall([checkbox cell]);
    [checkbox setTitle:labelText];
    [checkbox setButtonType:NSButtonTypeSwitch];
    [checkbox sizeToFit];
    return checkbox;
}

static inline NSPopUpButton * makeComboBox(void)
{
    NSPopUpButton *comboBox = [[NSPopUpButton alloc] init];
    [comboBox setPullsDown:NO];
    setFontToSmall(comboBox);
    setControlToSmall([comboBox cell]);
    [comboBox setBezelStyle:NSBezelStyleRounded];
    [comboBox setPreferredEdge:NSMaxYEdge];
    [[comboBox cell] setArrowPosition:NSPopUpArrowAtCenter];
    [comboBox sizeToFit];
    return comboBox;
}

/* setAppleMenu disappeared from the headers in 10.4 */
@interface NSApplication(NSAppleMenu)
- (void)setAppleMenu:(NSMenu *)menu;
@end

static inline NSString * GetApplicationName(void)
{
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    if (!appName)
        appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
    if (![appName length])
        appName = [[NSProcessInfo processInfo] processName];

    return appName;
}

static inline void CreateApplicationMenus(void)
{
    NSString *appName;
    NSString *title;
    NSMenu *rootMenu;
    NSMenu *serviceMenu;
    NSMenuItem *menuItem;

    NSMenu *mainMenu = [[NSMenu alloc] init];

    /* Create the application menu */
    appName = GetApplicationName();
    rootMenu = [[NSMenu alloc] init];

    /* Put menu into the menubar */
    menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
    [menuItem setSubmenu:rootMenu];
    [mainMenu addItem:menuItem];
    [menuItem release];

    /* Add menu items */
    title = [@"About " stringByAppendingString:appName];
    [rootMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];

    [rootMenu addItem:[NSMenuItem separatorItem]];

    serviceMenu = [[NSMenu alloc] init];
    menuItem = (NSMenuItem *)[rootMenu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
    [menuItem setSubmenu:serviceMenu];

    [nsapp setServicesMenu:serviceMenu];
    [serviceMenu release];

    [rootMenu addItem:[NSMenuItem separatorItem]];

    title = [@"Hide " stringByAppendingString:appName];
    [rootMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];

    menuItem = (NSMenuItem *)[rootMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
    [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];

    [rootMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];

    [rootMenu addItem:[NSMenuItem separatorItem]];

    title = [@"Quit " stringByAppendingString:appName];
    [rootMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];

    /* Create the main menu bar */
    [nsapp setMainMenu:mainMenu];
    [mainMenu release];  /* we're done with it, let NSApp own it. */

    /* Tell the application object that this is now the application menu */
    [nsapp setAppleMenu:rootMenu];
    [rootMenu release];
}

static int retval = -1;

static struct {
    int fullscreen;
    int xdim2d, ydim2d;
    int xdim3d, ydim3d, bpp3d;
    int forcesetup;
} settings;

@interface StartupWindow : NSWindow <NSWindowDelegate>
{
    NSMutableArray *modeslist2d;
    NSMutableArray *modeslist3d;

    NSButton *alwaysShowButton;
    NSButton *fullscreenButton;
    NSTextView *messagesView;
    NSTabView *tabView;
    NSTabViewItem *tabViewItemSetup;
    NSTabViewItem *tabViewItemMessageLog;
    NSPopUpButton *videoMode2DPUButton;
    NSPopUpButton *videoMode3DPUButton;

    NSButton *cancelButton;
    NSButton *startButton;
}

- (StartupWindow *)init;

- (void)dealloc;
- (void)populateVideoModes:(BOOL)firstTime;

- (void)fullscreenClicked:(id)sender;

- (void)cancel:(id)sender;
- (void)start:(id)sender;

- (void)setupRunMode;
- (void)setupMessagesMode;

- (void)putsMessage:(NSString *)str;

@end

@implementation StartupWindow : NSWindow

- (StartupWindow *)init
{
    NSUInteger const style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
    NSRect const windowFrame = NSMakeRect(0, 0, 480, 280);
    self = [super initWithContentRect:windowFrame styleMask:style backing:NSBackingStoreBuffered defer:NO];

    if (self)
    {
        // window properties
        [self setDelegate:self];
        [self setReleasedWhenClosed:NO];
#if defined MAC_OS_X_VERSION_10_3 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
        [self setContentMinSize:[[self contentView] frame].size];
#else
        [self setMinSize:[NSWindow frameRectForContentRect:[[self contentView] frame] styleMask:[self styleMask]].size];
#endif

        // image on the left
        NSRect const imageFrame = NSMakeRect(0, 0, 100, 280);
        NSImageView * imageView = [[NSImageView alloc] initWithFrame:imageFrame];
        [imageView setImageScaling:NSImageScaleNone];
        [imageView setImage:[NSImage imageNamed:@"build"]];
        [[self contentView] addSubview:imageView];
        [imageView setAutoresizingMask:NSViewMaxXMargin | NSViewHeightSizable];

        // buttons
        CGFloat const buttonWidth = 80;
        CGFloat const buttonHeight = 32;

        NSRect const startButtonFrame = NSMakeRect(windowFrame.size.width - buttonWidth, 0, buttonWidth, buttonHeight);
        startButton = [[NSButton alloc] initWithFrame:startButtonFrame];
        [[self contentView] addSubview:startButton];
        [startButton setTitle:@"Start"];
        [startButton setTarget:self];
        [startButton setAction:@selector(start:)];
        [startButton setBezelStyle:NSBezelStyleRounded];
        [startButton setKeyEquivalent:@"\r"];
        [startButton setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin];

        NSRect const cancelButtonFrame = NSMakeRect(startButtonFrame.origin.x - buttonWidth, 0, buttonWidth, buttonHeight);
        cancelButton = [[NSButton alloc] initWithFrame:cancelButtonFrame];
        [[self contentView] addSubview:cancelButton];
        [cancelButton setTitle:@"Cancel"];
        [cancelButton setTarget:self];
        [cancelButton setAction:@selector(cancel:)];
        [cancelButton setBezelStyle:NSBezelStyleRounded];
        [cancelButton setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin];

        // tab frame
        NSRect const tabViewFrame = NSMakeRect(imageFrame.size.width, buttonHeight, windowFrame.size.width - imageFrame.size.width, windowFrame.size.height - buttonHeight - 5);
        tabView = [[NSTabView alloc] initWithFrame:tabViewFrame];
        [[self contentView] addSubview:tabView];
        setFontToSmall(tabView);
        setControlToSmall(tabView);
        [tabView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

        // setup tab

        tabViewItemSetup = [[NSTabViewItem alloc] init];
        [tabView addTabViewItem:tabViewItemSetup];
        [tabViewItemSetup setLabel:@"Setup"];
        NSRect const tabViewItemSetupFrame = [[tabViewItemSetup view] frame];

        // always show checkbox
        alwaysShowButton = makeCheckbox(@"Always show this window at startup");
        [[tabViewItemSetup view] addSubview:alwaysShowButton];
        NSSize const alwaysShowButtonSize = [alwaysShowButton frame].size;
        NSRect const alwaysShowButtonFrame = NSSizeAddXY(alwaysShowButtonSize, tabViewItemSetupFrame.size.width - alwaysShowButtonSize.width, 0);
        [alwaysShowButton setFrame:alwaysShowButtonFrame];
        [alwaysShowButton setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin];

        // video mode selectors and labels
        NSTextField * label2DVideoMode = makeLabel(@"2D Video mode:");
        [[tabViewItemSetup view] addSubview:label2DVideoMode];
        NSSize const label2DVideoModeSize = [label2DVideoMode frame].size;
        [label2DVideoMode setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];

        NSTextField * label3DVideoMode = makeLabel(@"3D Video mode:");
        [[tabViewItemSetup view] addSubview:label3DVideoMode];
        NSSize const label3DVideoModeSize = [label3DVideoMode frame].size;
        [label3DVideoMode setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];

        fullscreenButton = makeCheckbox(@"Fullscreen");
        [[tabViewItemSetup view] addSubview:fullscreenButton];
        NSSize const fullscreenButtonSize = [fullscreenButton frame].size;
        [fullscreenButton setAction:@selector(fullscreenClicked:)];
        [fullscreenButton setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];

        CGFloat const labelsVideoModeRightEdge = max(label2DVideoModeSize.width, label3DVideoModeSize.width);

        videoMode2DPUButton = makeComboBox();
        [[tabViewItemSetup view] addSubview:videoMode2DPUButton];
        NSSize const videoMode2DPUButtonSize = [videoMode2DPUButton frame].size;
        CGFloat const videoMode2DButtonX = labelsVideoModeRightEdge;
        NSRect const videoMode2DPUButtonFrame = NSMakeRect(videoMode2DButtonX, tabViewItemSetupFrame.size.height - videoMode2DPUButtonSize.height, tabViewItemSetupFrame.size.width - videoMode2DButtonX - fullscreenButtonSize.width, videoMode2DPUButtonSize.height);
        [videoMode2DPUButton setFrame:videoMode2DPUButtonFrame];
        [videoMode2DPUButton setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];

        videoMode3DPUButton = makeComboBox();
        [[tabViewItemSetup view] addSubview:videoMode3DPUButton];
        NSSize const videoMode3DPUButtonSize = [videoMode3DPUButton frame].size;
        CGFloat const videoMode3DButtonX = labelsVideoModeRightEdge;
        NSRect const videoMode3DPUButtonFrame = NSMakeRect(videoMode3DButtonX, videoMode2DPUButtonFrame.origin.y - videoMode3DPUButtonSize.height, tabViewItemSetupFrame.size.width - videoMode3DButtonX - fullscreenButtonSize.width, videoMode3DPUButtonSize.height);
        [videoMode3DPUButton setFrame:videoMode3DPUButtonFrame];
        [videoMode3DPUButton setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];

        NSRect const label2DVideoModeFrame = NSSizeAddXY(label2DVideoModeSize, 0, videoMode2DPUButtonFrame.origin.y + rintf((videoMode2DPUButtonSize.height - label2DVideoModeSize.height) * 0.5f) + 1);
        [label2DVideoMode setFrame:label2DVideoModeFrame];

        NSRect const label3DVideoModeFrame = NSSizeAddXY(label3DVideoModeSize, 0, videoMode3DPUButtonFrame.origin.y + rintf((videoMode3DPUButtonSize.height - label3DVideoModeSize.height) * 0.5f) + 1);
        [label3DVideoMode setFrame:label3DVideoModeFrame];

        NSRect const fullscreenButtonFrame = NSSizeAddXY(fullscreenButtonSize, tabViewItemSetupFrame.size.width - fullscreenButtonSize.width, videoMode3DPUButtonFrame.origin.y + rintf((videoMode3DPUButtonSize.height - fullscreenButtonSize.height) * 0.5f) + 1);
        [fullscreenButton setFrame:fullscreenButtonFrame];

        // message log tab

        tabViewItemMessageLog = [[NSTabViewItem alloc] init];
        [tabView addTabViewItem:tabViewItemMessageLog];
        [tabViewItemMessageLog setLabel:@"Message Log"];
        NSRect const tabViewItemMessageLogFrame = [[tabViewItemMessageLog view] frame];

        // message log
        NSScrollView * messagesScrollView = [[NSScrollView alloc] initWithFrame:NSRectChangeXY(tabViewItemMessageLogFrame, 0, 0)];
        [[tabViewItemMessageLog view] addSubview:messagesScrollView];
        [messagesScrollView setBorderType:NSBezelBorder];
        [messagesScrollView setHasVerticalScroller:YES];
        [messagesScrollView setHasHorizontalScroller:NO];
        setControlToSmall([[messagesScrollView verticalScroller] cell]);
        NSSize const messagesScrollViewContentSize = [messagesScrollView contentSize];
        [messagesScrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

        messagesView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, messagesScrollViewContentSize.width, messagesScrollViewContentSize.height)];
        [messagesScrollView setDocumentView:messagesView];
        [messagesView setEditable:NO];
        [messagesView setRichText:NO];
        setFontToSmall(messagesView);
        [messagesView setMinSize:NSMakeSize(0.0, messagesScrollViewContentSize.height)];
        [messagesView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
        [messagesView setVerticallyResizable:YES];
        [messagesView setHorizontallyResizable:NO];
        [messagesView setAutoresizingMask:NSViewWidthSizable];

        [[messagesView textContainer] setContainerSize:NSMakeSize(messagesScrollViewContentSize.width, FLT_MAX)];
        [[messagesView textContainer] setWidthTracksTextView:YES];
    }

    return self;
}

- (BOOL)canBecomeKeyWindow
{
    return YES;
}

- (BOOL)canBecomeMainWindow
{
    return YES;
}

- (BOOL) windowShouldClose:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    retval = 0;

    return YES;
}

- (void)dealloc
{
    [modeslist3d release];
    [super dealloc];
}

- (void)populateVideoModes:(BOOL)firstTime
{
    int i, mode3d, fullscreen = ([fullscreenButton state] == NSControlStateValueOn);
    int mode2d, idx2d = -1;
    int idx3d = -1;
    int xdim2d = 0, ydim2d = 0;
    int const bpp2d = 8;
    int xdim = 0, ydim = 0, bpp = 0;

    if (firstTime) {
        xdim2d = settings.xdim2d;
        ydim2d = settings.ydim2d;
        xdim = settings.xdim3d;
        ydim = settings.ydim3d;
        bpp  = settings.bpp3d;
    } else {
        mode2d = [[modeslist2d objectAtIndex:[videoMode2DPUButton indexOfSelectedItem]] intValue];
        if (mode2d >= 0) {
            xdim2d = validmode[mode2d].xdim;
            ydim2d = validmode[mode2d].ydim;
        }

        mode3d = [[modeslist3d objectAtIndex:[videoMode3DPUButton indexOfSelectedItem]] intValue];
        if (mode3d >= 0) {
            xdim = validmode[mode3d].xdim;
            ydim = validmode[mode3d].ydim;
            bpp = validmode[mode3d].bpp;
        }
    }

    mode2d = videoCheckMode(&xdim2d, &ydim2d, bpp2d, fullscreen, 1);

    [modeslist2d release];
    [videoMode2DPUButton removeAllItems];

    modeslist2d = [[NSMutableArray alloc] init];

    for (i = 0; i < validmodecnt; i++) {
        if (fullscreen == validmode[i].fs) {
            if (i == mode2d) idx2d = [modeslist2d count];
            [modeslist2d addObject:[NSNumber numberWithInt:i]];
            [videoMode2DPUButton addItemWithTitle:[NSString stringWithFormat:@"%d %C %d",
                                                   validmode[i].xdim, 0xd7, validmode[i].ydim]];
        }
    }

    if (idx2d >= 0) [videoMode2DPUButton selectItemAtIndex:idx2d];

    mode3d = videoCheckMode(&xdim, &ydim, bpp, fullscreen, 1);
    if (mode3d < 0) {
        int i, cd[] = { 32, 24, 16, 15, 8, 0 };
        for (i=0; cd[i]; ) { if (cd[i] >= bpp) i++; else break; }
        for ( ; cd[i]; i++) {
            mode3d = videoCheckMode(&xdim, &ydim, cd[i], fullscreen, 1);
            if (mode3d < 0) continue;
            break;
        }
    }

    [modeslist3d release];
    [videoMode3DPUButton removeAllItems];

    modeslist3d = [[NSMutableArray alloc] init];

    for (i = 0; i < validmodecnt; i++) {
        if (fullscreen == validmode[i].fs) {
            if (i == mode3d) idx3d = [modeslist3d count];
            [modeslist3d addObject:[NSNumber numberWithInt:i]];
            [videoMode3DPUButton addItemWithTitle:[NSString stringWithFormat:@"%d %C %d %d-bpp",
                                                   validmode[i].xdim, 0xd7, validmode[i].ydim, validmode[i].bpp]];
        }
    }

    if (idx3d >= 0) [videoMode3DPUButton selectItemAtIndex:idx3d];
}

- (void)fullscreenClicked:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    [self populateVideoModes:NO];
}

- (void)cancel:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    retval = 0;
}

- (void)start:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    int mode2d = [[modeslist2d objectAtIndex:[videoMode2DPUButton indexOfSelectedItem]] intValue];
    if (mode2d >= 0) {
        settings.xdim2d = validmode[mode2d].xdim;
        settings.ydim2d = validmode[mode2d].ydim;
        settings.fullscreen = validmode[mode2d].fs;
    }

    int mode = [[modeslist3d objectAtIndex:[videoMode3DPUButton indexOfSelectedItem]] intValue];
    if (mode >= 0) {
        settings.xdim3d = validmode[mode].xdim;
        settings.ydim3d = validmode[mode].ydim;
        settings.bpp3d = validmode[mode].bpp;
        settings.fullscreen = validmode[mode].fs;
    }

    settings.forcesetup = [alwaysShowButton state] == NSControlStateValueOn;

    retval = 1;
}

- (void)setupRunMode
{
    videoGetModes();

    [fullscreenButton setState: (settings.fullscreen ? NSControlStateValueOn : NSControlStateValueOff)];
    [alwaysShowButton setState: (settings.forcesetup ? NSControlStateValueOn : NSControlStateValueOff)];
    [self populateVideoModes:YES];

    // enable all the controls on the Configuration page
    NSEnumerator *enumerator = [[[tabViewItemSetup view] subviews] objectEnumerator];
    NSControl *control;
    while ((control = [enumerator nextObject]))
    {
        if ([control respondsToSelector:@selector(setEnabled:)])
            [control setEnabled:true];
    }

    [cancelButton setEnabled:true];
    [startButton setEnabled:true];

    [tabView selectTabViewItem:tabViewItemSetup];
    [NSCursor unhide]; // Why should I need to do this?
}

- (void)setupMessagesMode
{
    [tabView selectTabViewItem:tabViewItemMessageLog];

    // disable all the controls on the Configuration page except "always show", so the
    // user can enable it if they want to while waiting for something else to happen
    NSEnumerator *enumerator = [[[tabViewItemSetup view] subviews] objectEnumerator];
    NSControl *control;
    while ((control = [enumerator nextObject]))
    {
        if (control != alwaysShowButton && [control respondsToSelector:@selector(setEnabled:)])
            [control setEnabled:false];
    }

    [cancelButton setEnabled:false];
    [startButton setEnabled:false];
}

- (void)putsMessage:(NSString *)str
{
    NSRange end;
    NSTextStorage *text = [messagesView textStorage];
    BOOL shouldAutoScroll;

    shouldAutoScroll = ((int)NSMaxY([messagesView bounds]) == (int)NSMaxY([messagesView visibleRect]));

    end.location = [text length];
    end.length = 0;

    [text beginEditing];
    [messagesView replaceCharactersInRange:end withString:str];
    [text endEditing];

    if (shouldAutoScroll) {
        end.location = [text length];
        end.length = 0;
        [messagesView scrollRangeToVisible:end];
    }
}

@end

static StartupWindow *startwin = nil;

int startwin_open(void)
{
    if (startwin != nil) return 1;

    startwin = [[StartupWindow alloc] init];
    if (startwin == nil) return -1;

    [startwin setupMessagesMode];

    [startwin center];
    [startwin makeKeyAndOrderFront:nil];

    CreateApplicationMenus();

    return 0;
}

int startwin_close(void)
{
    if (startwin == nil) return 1;

    [startwin close];
    [startwin release];
    startwin = nil;

    return 0;
}

int startwin_puts(const char *s)
{
    NSString *ns;

    if (!s) return -1;
    if (startwin == nil) return 1;

    ns = [NSString stringWithUTF8String:s];
    [startwin putsMessage:ns];
    [ns release];

    return 0;
}

int startwin_settitle(const char *s)
{
    NSString *ns;

    if (!s) return -1;
    if (startwin == nil) return 1;

    ns = [NSString stringWithUTF8String:s];
    [startwin setTitle:ns];
    [ns release];

    return 0;
}

int startwin_idle(void *v)
{
    UNREFERENCED_PARAMETER(v);

    if (startwin)
    {
        NSEvent *event;
        do
        {
            event = [nsapp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate date] inMode:NSDefaultRunLoopMode dequeue:YES];
            [nsapp sendEvent:event];
        }
        while (event != nil);

        [startwin displayIfNeeded];
        [nsapp updateWindows];
    }

    return 0;
}

int startwin_run(void)
{
    if (startwin == nil) return 0;

    settings.fullscreen = fullscreen;
    settings.xdim2d = xdim2d;
    settings.ydim2d = ydim2d;
    settings.xdim3d = xdimgame;
    settings.ydim3d = ydimgame;
    settings.bpp3d = bppgame;
    settings.forcesetup = forcesetup;

    [startwin setupRunMode];

    do
    {
        NSEvent *event = [nsapp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
        [nsapp sendEvent:event];
        [nsapp updateWindows];
    }
    while (retval == -1);

    [startwin setupMessagesMode];
    [nsapp updateWindows];

    if (retval) {
        fullscreen = settings.fullscreen;
        xdim2d = settings.xdim2d;
        ydim2d = settings.ydim2d;
        xdimgame = settings.xdim3d;
        ydimgame = settings.ydim3d;
        bppgame = settings.bpp3d;
        forcesetup = settings.forcesetup;
    }

    return retval;
}


code:
#ifndef _WIN32
#error Only for Windows
#endif

#include "compat.h"

#define NEED_WINDOWSX_H
#define NEED_COMMCTRL_H
#include "windows_inc.h"

#include "renderlayer.h"

#ifdef STARTUP_SETUP_WINDOW

#include "build.h"
#include "editor.h"
#include "winlayer.h"

#include "startwin.editor.h"

#define TAB_CONFIG 0
#define TAB_MESSAGES 1

static struct
{
    int32_t fullscreen;
    int32_t xdim3d, ydim3d, bpp3d;
    int32_t forcesetup, usecwd;
} settings;

static HWND startupdlg = NULL;
static HWND pages[2] = { NULL, NULL};
static int32_t done = -1, mode = TAB_CONFIG;

static void PopulateForm(void)
{
    int32_t i,j;
    char buf[64];
    int32_t mode3d;
    HWND hwnd3d;

    hwnd3d = GetDlgItem(pages[TAB_CONFIG], IDC3DVMODE);

    mode3d = videoCheckMode(&settings.xdim3d, &settings.ydim3d, settings.bpp3d, settings.fullscreen, 1);
    if (mode3d < 0)
    {
        int32_t cd[] = { 32, 24, 16, 15, 8, 0 };
        for (i=0; cd[i];) { if (cd[i] >= settings.bpp3d) i++; else break; }
        for (; cd[i]; i++)
        {
            mode3d = videoCheckMode(&settings.xdim3d, &settings.ydim3d, cd[i], settings.fullscreen, 1);
            if (mode3d < 0) continue;
            settings.bpp3d = cd[i];
            break;
        }
    }

    Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCFULLSCREEN), (settings.fullscreen ? BST_CHECKED : BST_UNCHECKED));
    Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCALWAYSSHOW), (settings.forcesetup ? BST_CHECKED : BST_UNCHECKED));
    Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCCWD), (settings.usecwd ? BST_CHECKED : BST_UNCHECKED));

    (void)ComboBox_ResetContent(hwnd3d);
    for (i=0; i<validmodecnt; i++)
    {
        if (validmode[i].fs != settings.fullscreen) continue;

        // all modes get added to the 3D mode list
        Bsprintf(buf, "%dx%d %s", validmode[i].xdim, validmode[i].ydim, validmode[i].bpp == 8 ? "software" : "OpenGL");
        j = ComboBox_AddString(hwnd3d, buf);
        (void)ComboBox_SetItemData(hwnd3d, j, i);
        if (i == mode3d)(void)ComboBox_SetCurSel(hwnd3d, j);
    }
}

static INT_PTR CALLBACK ConfigPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDCFULLSCREEN:
            settings.fullscreen = !settings.fullscreen;
            PopulateForm();
            return TRUE;
        case IDC3DVMODE:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int32_t i;
                i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    settings.xdim3d = validmode[i].xdim;
                    settings.ydim3d = validmode[i].ydim;
                    settings.bpp3d  = validmode[i].bpp;
                }
            }
            return TRUE;
        case IDCALWAYSSHOW:
            settings.forcesetup = IsDlgButtonChecked(hwndDlg, IDCALWAYSSHOW) == BST_CHECKED;
            return TRUE;
        case IDCCWD:
            settings.usecwd = IsDlgButtonChecked(hwndDlg, IDCCWD) == BST_CHECKED;
            return TRUE;
        default:
            break;
        }
        break;
    default:
        break;
    }
    return FALSE;
}

static void SetPage(int32_t n)
{
    HWND tab;
    int32_t cur;
    tab = GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL);
    cur = (int32_t)SendMessage(tab, TCM_GETCURSEL,0,0);
    ShowWindow(pages[cur],SW_HIDE);
    SendMessage(tab, TCM_SETCURSEL, n, 0);
    ShowWindow(pages[n],SW_SHOW);
    mode = n;

    SetFocus(GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL));
}

static void EnableConfig(int32_t n)
{
    //EnableWindow(GetDlgItem(startupdlg, WIN_STARTWIN_CANCEL), n);
    EnableWindow(GetDlgItem(startupdlg, WIN_STARTWIN_START), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCFULLSCREEN), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDC3DVMODE), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCCWD), n);
}

static INT_PTR CALLBACK startup_dlgproc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    static HBITMAP hbmp = NULL;
    HDC hdc;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        HWND hwnd;
        RECT r, rdlg, chrome, rtab, rcancel, rstart;
        int32_t xoffset = 0, yoffset = 0;

        // Fetch the positions (in screen coordinates) of all the windows we need to tweak
        ZeroMemory(&chrome, sizeof(chrome));
        AdjustWindowRect(&chrome, GetWindowLongPtr(hwndDlg, GWL_STYLE), FALSE);
        GetWindowRect(hwndDlg, &rdlg);
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL), &rtab);
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_CANCEL), &rcancel);
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_START), &rstart);

        // Knock off the non-client area of the main dialogue to give just the client area
        rdlg.left -= chrome.left; rdlg.top -= chrome.top;
        rdlg.right -= chrome.right; rdlg.bottom -= chrome.bottom;

        // Translate them to client-relative coordinates wrt the main dialogue window
        rtab.right -= rtab.left - 1; rtab.bottom -= rtab.top - 1;
        rtab.left  -= rdlg.left; rtab.top -= rdlg.top;

        rcancel.right -= rcancel.left - 1; rcancel.bottom -= rcancel.top - 1;
        rcancel.left -= rdlg.left; rcancel.top -= rdlg.top;

        rstart.right -= rstart.left - 1; rstart.bottom -= rstart.top - 1;
        rstart.left -= rdlg.left; rstart.top -= rdlg.top;

        // And then convert the main dialogue coordinates to just width/length
        rdlg.right -= rdlg.left - 1; rdlg.bottom -= rdlg.top - 1;
        rdlg.left = 0; rdlg.top = 0;

        // Load the bitmap into the bitmap control and fetch its dimensions
        hbmp = LoadBitmap((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(RSRC_BMP));
        hwnd = GetDlgItem(hwndDlg,WIN_STARTWIN_BITMAP);
        SendMessage(hwnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hbmp);
        GetClientRect(hwnd, &r);
        xoffset = r.right;
        yoffset = r.bottom - rdlg.bottom;

        // Shift and resize the controls that require it
        rtab.left += xoffset; rtab.bottom += yoffset;
        rcancel.left += xoffset; rcancel.top += yoffset;
        rstart.left += xoffset; rstart.top += yoffset;
        rdlg.right += xoffset;
        rdlg.bottom += yoffset;

        // Move the controls to their new positions
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL), rtab.left, rtab.top, rtab.right, rtab.bottom, FALSE);
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_CANCEL), rcancel.left, rcancel.top, rcancel.right, rcancel.bottom, FALSE);
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_START), rstart.left, rstart.top, rstart.right, rstart.bottom, FALSE);

        // Move the main dialogue to the centre of the screen
        hdc = GetDC(NULL);
        rdlg.left = (GetDeviceCaps(hdc, HORZRES) - rdlg.right) / 2;
        rdlg.top = (GetDeviceCaps(hdc, VERTRES) - rdlg.bottom) / 2;
        ReleaseDC(NULL, hdc);
        MoveWindow(hwndDlg, rdlg.left + chrome.left, rdlg.top + chrome.left,
                   rdlg.right + (-chrome.left+chrome.right), rdlg.bottom + (-chrome.top+chrome.bottom), TRUE);

        // Add tabs to the tab control
        {
            TCITEM tab;

            hwnd = GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL);

            ZeroMemory(&tab, sizeof(tab));
            tab.mask = TCIF_TEXT;
            static char textSetup[] = TEXT("Setup");
            tab.pszText = textSetup;
            SendMessage(hwnd, TCM_INSERTITEM, (WPARAM)0, (LPARAM)&tab);
            tab.mask = TCIF_TEXT;
            static char textMessageLog[] = TEXT("Message Log");
            tab.pszText = textMessageLog;
            SendMessage(hwnd, TCM_INSERTITEM, (WPARAM)1, (LPARAM)&tab);
            // Work out the position and size of the area inside the tab control for the pages
            ZeroMemory(&r, sizeof(r));
            GetClientRect(hwnd, &r);
            SendMessage(hwnd, TCM_ADJUSTRECT, FALSE, (LPARAM)&r);
            r.right -= r.left-1;
            r.bottom -= r.top-1;
            r.top += rtab.top;
            r.left += rtab.left;

            // Create the pages and position them in the tab control, but hide them
            pages[TAB_CONFIG] = CreateDialog((HINSTANCE)win_gethinstance(),
                                             MAKEINTRESOURCE(WIN_STARTWINPAGE_CONFIG), hwndDlg, ConfigPageProc);
            pages[TAB_MESSAGES] = GetDlgItem(hwndDlg, WIN_STARTWIN_MESSAGES);
            SetWindowPos(pages[TAB_CONFIG], hwnd,r.left,r.top,r.right,r.bottom,SWP_HIDEWINDOW);
            SetWindowPos(pages[TAB_MESSAGES], hwnd,r.left,r.top,r.right,r.bottom,SWP_HIDEWINDOW);

            // Tell the editfield acting as the console to exclude the width of the scrollbar
            GetClientRect(pages[TAB_MESSAGES],&r);
            r.right -= GetSystemMetrics(SM_CXVSCROLL)+4;
            r.left = r.top = 0;
            SendMessage(pages[TAB_MESSAGES], EM_SETRECTNP,0,(LPARAM)&r);

            SetFocus(GetDlgItem(hwndDlg, WIN_STARTWIN_START));
        }
        return FALSE;
    }

    case WM_NOTIFY:
    {
        LPNMHDR nmhdr = (LPNMHDR)lParam;
        int32_t cur;
        if (nmhdr->idFrom != WIN_STARTWIN_TABCTL) break;
        cur = (int32_t)SendMessage(nmhdr->hwndFrom, TCM_GETCURSEL,0,0);
        switch (nmhdr->code)
        {
        case TCN_SELCHANGING:
        {
            if (cur < 0 || !pages[cur]) break;
            ShowWindow(pages[cur],SW_HIDE);
            return TRUE;
        }
        case TCN_SELCHANGE:
        {
            if (cur < 0 || !pages[cur]) break;
            ShowWindow(pages[cur],SW_SHOW);
            return TRUE;
        }
        }
        break;
    }

    case WM_CLOSE:
        if (mode == TAB_CONFIG) done = 0;
        else quitevent++;
        return TRUE;

    case WM_DESTROY:
        if (hbmp)
        {
            DeleteObject(hbmp);
            hbmp = NULL;
        }

        if (pages[TAB_CONFIG])
        {
            DestroyWindow(pages[TAB_CONFIG]);
            pages[TAB_CONFIG] = NULL;
        }

        startupdlg = NULL;
        return TRUE;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case WIN_STARTWIN_CANCEL:
            if (mode == TAB_CONFIG) done = 0;
            else quitevent++;
            return TRUE;
        case WIN_STARTWIN_START:
            done = 1; return TRUE;
        }
        return FALSE;

    case WM_CTLCOLORSTATIC:
        if ((HWND)lParam == pages[TAB_MESSAGES])
            return (BOOL)(intptr_t)GetSysColorBrush(COLOR_WINDOW);
        break;

    default:
        break;
    }

    return FALSE;
}

bool startwin_isopen(void)
{
    return !!startupdlg;
}

int32_t startwin_open(void)
{
    INITCOMMONCONTROLSEX icc;
    if (startupdlg) return 1;
    icc.dwSize = sizeof(icc);
    icc.dwICC = ICC_TAB_CLASSES;
    InitCommonControlsEx(&icc);
    startupdlg = CreateDialog((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(WIN_STARTWIN), NULL, startup_dlgproc);
    if (startupdlg)
    {
        SetPage(TAB_MESSAGES);
        EnableConfig(0);
        return 0;
    }
    return -1;
}

int32_t startwin_close(void)
{
    if (!startupdlg) return 1;
    DestroyWindow(startupdlg);
    startupdlg = NULL;
    return 0;
}

int32_t startwin_puts(const char *buf)
{
    const char *p = NULL, *q = NULL;
    static char workbuf[1024];
    static int32_t newline = 0;
    int32_t curlen, linesbefore, linesafter;
    HWND edctl;
    int32_t vis;
    static HWND dactrl = NULL;

    if (!startupdlg) return 1;

    edctl = pages[TAB_MESSAGES];
    if (!edctl) return -1;

    if (!dactrl) dactrl = GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL);

    vis = ((int32_t)SendMessage(dactrl, TCM_GETCURSEL,0,0) == TAB_MESSAGES);

    if (vis) SendMessage(edctl, WM_SETREDRAW, FALSE,0);
    curlen = SendMessage(edctl, WM_GETTEXTLENGTH, 0,0);
    SendMessage(edctl, EM_SETSEL, (WPARAM)curlen, (LPARAM)curlen);
    linesbefore = SendMessage(edctl, EM_GETLINECOUNT, 0,0);
    p = buf;
    while (*p)
    {
        if (newline)
        {
            SendMessage(edctl, EM_REPLACESEL, 0, (LPARAM)"\r\n");
            newline = 0;
        }
        q = p;
        while (*q && *q != '\n') q++;
        Bmemcpy(workbuf, p, q-p);
        if (*q == '\n')
        {
            if (!q[1])
            {
                newline = 1;
                workbuf[q-p] = 0;
            }
            else
            {
                workbuf[q-p] = '\r';
                workbuf[q-p+1] = '\n';
                workbuf[q-p+2] = 0;
            }
            p = q+1;
        }
        else
        {
            workbuf[q-p] = 0;
            p = q;
        }
        SendMessage(edctl, EM_REPLACESEL, 0, (LPARAM)workbuf);
    }
    linesafter = SendMessage(edctl, EM_GETLINECOUNT, 0,0);
    SendMessage(edctl, EM_LINESCROLL, 0, linesafter-linesbefore);
    if (vis) SendMessage(edctl, WM_SETREDRAW, TRUE,0);
    return 0;
}

int32_t startwin_settitle(const char *str)
{
    if (!startupdlg) return 1;
    SetWindowText(startupdlg, str);
    return 0;
}

int32_t startwin_idle(void *v)
{
    if (!startupdlg || !IsWindow(startupdlg)) return 0;
    if (IsDialogMessage(startupdlg, (MSG *)v)) return 1;
    return 0;
}

int32_t startwin_run(void)
{
    MSG msg;
    if (!startupdlg) return 1;

    done = -1;

    SetPage(TAB_CONFIG);
    EnableConfig(1);

    settings.fullscreen = fullscreen;
    settings.xdim3d = xdim;
    settings.ydim3d = ydim;
    settings.bpp3d = bpp;
    settings.forcesetup = forcesetup;
    settings.usecwd = g_useCwd;
    PopulateForm();

    while (done < 0)
    {
        switch (GetMessage(&msg, NULL, 0,0))
        {
        case 0:
            done = 1; break;
        case -1:
            return -1;
        default:
            if (IsWindow(startupdlg) && IsDialogMessage(startupdlg, &msg)) break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            break;
        }
    }

    SetPage(TAB_MESSAGES);
    EnableConfig(0);
    if (done)
    {
        fullscreen = settings.fullscreen;
        bppgame = settings.bpp3d;
        xdim = settings.xdim3d;
        ydim = settings.ydim3d;
        forcesetup = settings.forcesetup;
        g_useCwd = settings.usecwd;
    }

    return done;
}

#endif // STARTUP_SETUP_WINDOW