diff --git a/src/UI/_deprecated/MACOSX/ICONAPPO.icns b/rsrc/macOS/ICONAPPO.icns similarity index 100% rename from src/UI/_deprecated/MACOSX/ICONAPPO.icns rename to rsrc/macOS/ICONAPPO.icns diff --git a/src/UI/_deprecated/MACOSX/ICONDSKO.icns b/rsrc/macOS/ICONDSKO.icns similarity index 100% rename from src/UI/_deprecated/MACOSX/ICONDSKO.icns rename to rsrc/macOS/ICONDSKO.icns diff --git a/src/UI/_deprecated/MACOSX/ICONROMO.icns b/rsrc/macOS/ICONROMO.icns similarity index 100% rename from src/UI/_deprecated/MACOSX/ICONROMO.icns rename to rsrc/macOS/ICONROMO.icns diff --git a/src/HW/SOUND/SGLUALSA.h b/src/HW/SOUND/SGLUALSA.h deleted file mode 100644 index 964509a..0000000 --- a/src/HW/SOUND/SGLUALSA.h +++ /dev/null @@ -1,1621 +0,0 @@ -/* - SGLUALSA.h - - Copyright (C) 2012 Stephan Kochen, Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Sound GLUe for ALSA - - ALSA sound support by Stephan Kochen. -*/ - -#include -#include - -#ifndef RaspbianWorkAround -#define RaspbianWorkAround 0 -#endif - -#if 0 - -#include "alsa/asoundlib.h" - /* and link with "-lasound" */ - -#define _snd_pcm_t snd_pcm_t -#define _snd_pcm_hw_params_t snd_pcm_hw_params_t -#define _snd_pcm_sw_params_t snd_pcm_sw_params_t -#define _snd_pcm_state_t snd_pcm_state_t -#if RaspbianWorkAround -#define _snd_pcm_status_t snd_pcm_status_t -#endif - -#define _SND_PCM_STATE_OPEN SND_PCM_STATE_OPEN -#define _SND_PCM_STATE_SETUP SND_PCM_STATE_SETUP -#define _SND_PCM_STATE_PREPARED SND_PCM_STATE_PREPARED -#define _SND_PCM_STATE_RUNNING SND_PCM_STATE_RUNNING -#define _SND_PCM_STATE_XRUN SND_PCM_STATE_XRUN -#define _SND_PCM_STATE_DRAINING SND_PCM_STATE_DRAINING -#define _SND_PCM_STATE_PAUSED SND_PCM_STATE_PAUSED -#define _SND_PCM_STATE_SUSPENDED SND_PCM_STATE_SUSPENDED -#define _SND_PCM_STATE_DISCONNECTED SND_PCM_STATE_DISCONNECTED -#define _SND_PCM_STATE_LAST SND_PCM_STATE_LAST - -#define _snd_pcm_stream_t snd_pcm_stream_t - -#define _SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK -#define _SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE -#define _SND_PCM_STREAM_LAST SND_PCM_STREAM_LAST - -#define _snd_pcm_access_t snd_pcm_access_t - -#define _SND_PCM_ACCESS_MMAP_INTERLEAVED \ - SND_PCM_ACCESS_MMAP_INTERLEAVED -#define _SND_PCM_ACCESS_MMAP_NONINTERLEAVED \ - SND_PCM_ACCESS_MMAP_NONINTERLEAVED -#define _SND_PCM_ACCESS_MMAP_COMPLEX \ - SND_PCM_ACCESS_MMAP_COMPLEX -#define _SND_PCM_ACCESS_RW_INTERLEAVED \ - SND_PCM_ACCESS_RW_INTERLEAVED -#define _SND_PCM_ACCESS_RW_NONINTERLEAVED \ - SND_PCM_ACCESS_RW_NONINTERLEAVED -#define _SND_PCM_ACCESS_LAST \ - SND_PCM_ACCESS_LAST - -#define _snd_pcm_format_t snd_pcm_format_t - -#define _SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN -#define _SND_PCM_FORMAT_S8 SND_PCM_FORMAT_S8 -#define _SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8 -#define _SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE -#define _SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE -#define _SND_PCM_FORMAT_U16_LE SND_PCM_FORMAT_U16_LE -#define _SND_PCM_FORMAT_U16_BE SND_PCM_FORMAT_U16_BE -#define _SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE -#define _SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE -#define _SND_PCM_FORMAT_U24_LE SND_PCM_FORMAT_U24_LE -#define _SND_PCM_FORMAT_U24_BE SND_PCM_FORMAT_U24_BE -#define _SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE -#define _SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE -#define _SND_PCM_FORMAT_U32_LE SND_PCM_FORMAT_U32_LE -#define _SND_PCM_FORMAT_U32_BE SND_PCM_FORMAT_U32_BE -#define _SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE -#define _SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE -#define _SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE -#define _SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE -#define _SND_PCM_FORMAT_IEC958_SUBFRAME_LE \ - SND_PCM_FORMAT_IEC958_SUBFRAME_LE -#define _SND_PCM_FORMAT_IEC958_SUBFRAME_BE \ - SND_PCM_FORMAT_IEC958_SUBFRAME_BE -#define _SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW -#define _SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW -#define _SND_PCM_FORMAT_IMA_ADPCM SND_PCM_FORMAT_IMA_ADPCM -#define _SND_PCM_FORMAT_MPEG SND_PCM_FORMAT_MPEG -#define _SND_PCM_FORMAT_GSM SND_PCM_FORMAT_GSM -#define _SND_PCM_FORMAT_SPECIAL SND_PCM_FORMAT_SPECIAL -#define _SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE -#define _SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE -#define _SND_PCM_FORMAT_U24_3LE SND_PCM_FORMAT_U24_3LE -#define _SND_PCM_FORMAT_U24_3BE SND_PCM_FORMAT_U24_3BE -#define _SND_PCM_FORMAT_S20_3LE SND_PCM_FORMAT_S20_3LE -#define _SND_PCM_FORMAT_S20_3BE SND_PCM_FORMAT_S20_3BE -#define _SND_PCM_FORMAT_U20_3LE SND_PCM_FORMAT_U20_3LE -#define _SND_PCM_FORMAT_U20_3BE SND_PCM_FORMAT_U20_3BE -#define _SND_PCM_FORMAT_S18_3LE SND_PCM_FORMAT_S18_3LE -#define _SND_PCM_FORMAT_S18_3BE SND_PCM_FORMAT_S18_3BE -#define _SND_PCM_FORMAT_U18_3LE SND_PCM_FORMAT_U18_3LE -#define _SND_PCM_FORMAT_U18_3BE SND_PCM_FORMAT_U18_3BE -#define _SND_PCM_FORMAT_LAST SND_PCM_FORMAT_LAST - -#define _SND_PCM_FORMAT_S16 SND_PCM_FORMAT_S16 -#define _SND_PCM_FORMAT_U16 SND_PCM_FORMAT_U16 -#define _SND_PCM_FORMAT_S24 SND_PCM_FORMAT_S24 -#define _SND_PCM_FORMAT_U24 SND_PCM_FORMAT_U24 -#define _SND_PCM_FORMAT_S32 SND_PCM_FORMAT_S32 -#define _SND_PCM_FORMAT_U32 SND_PCM_FORMAT_U32 -#define _SND_PCM_FORMAT_FLOAT SND_PCM_FORMAT_FLOAT -#define _SND_PCM_FORMAT_FLOAT64 SND_PCM_FORMAT_FLOAT64 -#define _SND_PCM_FORMAT_IEC958_SUBFRAME SND_PCM_FORMAT_FLOAT64 - -#define _snd_pcm_uframes_t snd_pcm_uframes_t -#define _snd_pcm_sframes_t snd_pcm_sframes_t - -#define _SND_PCM_NONBLOCK SND_PCM_NONBLOCK - -#define _snd_pcm_open snd_pcm_open -#define Have_snd_pcm_open() (1) - -#define _snd_pcm_close snd_pcm_close -#define Have_snd_pcm_close() (1) - -#define _snd_pcm_hw_params_malloc snd_pcm_hw_params_malloc -#define Have_snd_pcm_hw_params_malloc() (1) - -#define _snd_pcm_hw_params_free snd_pcm_hw_params_free -#define Have_snd_pcm_hw_params_free() (1) - -#define _snd_pcm_hw_params_any snd_pcm_hw_params_any -#define Have_snd_pcm_hw_params_any() (1) - -#define _snd_pcm_hw_params_set_access snd_pcm_hw_params_set_access -#define Have_snd_pcm_hw_params_set_access() (1) - -#define _snd_pcm_hw_params_set_format snd_pcm_hw_params_set_format -#define Have_snd_pcm_hw_params_set_format() (1) - -#define _snd_pcm_hw_params_set_rate_near \ - snd_pcm_hw_params_set_rate_near -#define Have_snd_pcm_hw_params_set_rate_near() (1) - -#define _snd_pcm_hw_params_set_channels \ - snd_pcm_hw_params_set_channels -#define Have_snd_pcm_hw_params_set_channels() (1) - -#define _snd_pcm_hw_params_set_buffer_size_near \ - snd_pcm_hw_params_set_buffer_size_near -#define Have_snd_pcm_hw_params_set_buffer_size_near() (1) - -#define _snd_pcm_hw_params_set_period_size_near \ - snd_pcm_hw_params_set_period_size_near -#define Have_snd_pcm_hw_params_set_period_size_near() (1) - -#define _snd_pcm_hw_params snd_pcm_hw_params -#define Have_snd_pcm_hw_params() (1) - -#define _snd_pcm_sw_params_malloc snd_pcm_sw_params_malloc -#define Have_snd_pcm_sw_params_malloc() (1) - -#define _snd_pcm_sw_params_free snd_pcm_sw_params_free -#define Have_snd_pcm_sw_params_free() (1) - -#define _snd_pcm_sw_params_current snd_pcm_sw_params_current -#define Have_snd_pcm_sw_params_current() (1) - -#define _snd_pcm_sw_params_set_start_threshold \ - snd_pcm_sw_params_set_start_threshold -#define Have_snd_pcm_sw_params_set_start_threshold() (1) - -#define _snd_pcm_sw_params_set_avail_min \ - snd_pcm_sw_params_set_avail_min -#define Have_snd_pcm_sw_params_set_avail_min() (1) - -#define _snd_pcm_sw_params_set_xfer_align \ - snd_pcm_sw_params_set_xfer_align -#define Have_snd_pcm_sw_params_set_xfer_align() (1) - -#define _snd_pcm_sw_params snd_pcm_sw_params -#define Have_snd_pcm_sw_params() (1) - -#define _snd_pcm_nonblock snd_pcm_nonblock -#define Have_snd_pcm_nonblock() (1) - -#define _snd_pcm_state snd_pcm_state -#define Have_snd_pcm_state() (1) - -#define _snd_pcm_prepare snd_pcm_prepare -#define Have_snd_pcm_prepare() (1) - -#define _snd_pcm_start snd_pcm_start -#define Have_snd_pcm_start() (1) - -#define _snd_pcm_resume snd_pcm_resume -#define Have_snd_pcm_resume() (1) - -#define _snd_pcm_avail_update snd_pcm_avail_update -#define Have_snd_pcm_avail_update() (1) - -#define _snd_pcm_writei snd_pcm_writei -#define Have_snd_pcm_writei() (1) - -#define _snd_pcm_drop snd_pcm_drop -#define Have_snd_pcm_drop() (1) - -#if RaspbianWorkAround -#define _snd_pcm_status_malloc snd_pcm_status_malloc -#define Have_snd_pcm_status_malloc() (1) - -#define _snd_pcm_status snd_pcm_status -#define Have_snd_pcm_status() (1) - -#define _snd_pcm_status_get_avail snd_pcm_status_get_avail -#define Have_snd_pcm_status_get_avail() (1) -#endif - -#define _snd_strerror snd_strerror -#define Have_snd_strerror() (1) - -#define CloseAlsaLib() - -#else - -static void *alsa_handle = NULL; - -LOCALVAR bool DidAlsaLib = false; - -LOCALFUNC bool HaveAlsaLib(void) -{ - if (! DidAlsaLib) { - alsa_handle = dlopen("libasound.so.2", RTLD_NOW); - if (NULL == alsa_handle) { - fprintf(stderr, "dlopen libasound failed\n"); - } - DidAlsaLib = true; - } - return (alsa_handle != NULL); -} - -LOCALPROC CloseAlsaLib(void) -{ - if (NULL != alsa_handle) { - if (0 != dlclose(alsa_handle)) { - fprintf(stderr, "dlclose libasound failed\n"); - } - alsa_handle = NULL; - } -} - -/* PCM handle */ -typedef struct __snd_pcm _snd_pcm_t; -/* PCM hardware configuration space container */ -typedef struct __snd_pcm_hw_params _snd_pcm_hw_params_t; -/* PCM software configuration container */ -typedef struct __snd_pcm_sw_params _snd_pcm_sw_params_t; - -#if RaspbianWorkAround -/* PCM status container */ -typedef struct __snd_pcm_status _snd_pcm_status_t; -#endif - -/* PCM state */ -typedef enum __snd_pcm_state { - /* Open */ - _SND_PCM_STATE_OPEN = 0, - /* Setup installed */ - _SND_PCM_STATE_SETUP, - /* Ready to start */ - _SND_PCM_STATE_PREPARED, - /* Running */ - _SND_PCM_STATE_RUNNING, - /* Stopped: underrun (playback) or overrun (capture) detected */ - _SND_PCM_STATE_XRUN, - /* Draining: running (playback) or stopped (capture) */ - _SND_PCM_STATE_DRAINING, - /* Paused */ - _SND_PCM_STATE_PAUSED, - /* Hardware is suspended */ - _SND_PCM_STATE_SUSPENDED, - /* Hardware is disconnected */ - _SND_PCM_STATE_DISCONNECTED, - _SND_PCM_STATE_LAST = _SND_PCM_STATE_DISCONNECTED -} _snd_pcm_state_t; - -/* PCM stream (direction) */ -typedef enum __snd_pcm_stream { - /* Playback stream */ - _SND_PCM_STREAM_PLAYBACK = 0, - /* Capture stream */ - _SND_PCM_STREAM_CAPTURE, - _SND_PCM_STREAM_LAST = _SND_PCM_STREAM_CAPTURE -} _snd_pcm_stream_t; - -/* PCM access type */ -typedef enum __snd_pcm_access { - /* mmap access with simple interleaved channels */ - _SND_PCM_ACCESS_MMAP_INTERLEAVED = 0, - /* mmap access with simple non interleaved channels */ - _SND_PCM_ACCESS_MMAP_NONINTERLEAVED, - /* mmap access with complex placement */ - _SND_PCM_ACCESS_MMAP_COMPLEX, - /* snd_pcm_readi/snd_pcm_writei access */ - _SND_PCM_ACCESS_RW_INTERLEAVED, - /* snd_pcm_readn/snd_pcm_writen access */ - _SND_PCM_ACCESS_RW_NONINTERLEAVED, - _SND_PCM_ACCESS_LAST = _SND_PCM_ACCESS_RW_NONINTERLEAVED -} _snd_pcm_access_t; - -/* PCM sample format */ -typedef enum __snd_pcm_format { - /* Unknown */ - _SND_PCM_FORMAT_UNKNOWN = -1, - /* Signed 8 bit */ - _SND_PCM_FORMAT_S8 = 0, - /* Unsigned 8 bit */ - _SND_PCM_FORMAT_U8, - /* Signed 16 bit Little Endian */ - _SND_PCM_FORMAT_S16_LE, - /* Signed 16 bit Big Endian */ - _SND_PCM_FORMAT_S16_BE, - /* Unsigned 16 bit Little Endian */ - _SND_PCM_FORMAT_U16_LE, - /* Unsigned 16 bit Big Endian */ - _SND_PCM_FORMAT_U16_BE, - /* - Signed 24 bit Little Endian using low three bytes in 32-bit word - */ - _SND_PCM_FORMAT_S24_LE, - /* Signed 24 bit Big Endian using low three bytes in 32-bit word */ - _SND_PCM_FORMAT_S24_BE, - /* - Unsigned 24 bit Little Endian using low three bytes in - 32-bit word - */ - _SND_PCM_FORMAT_U24_LE, - /* - Unsigned 24 bit Big Endian using low three bytes in 32-bit word - */ - _SND_PCM_FORMAT_U24_BE, - /* Signed 32 bit Little Endian */ - _SND_PCM_FORMAT_S32_LE, - /* Signed 32 bit Big Endian */ - _SND_PCM_FORMAT_S32_BE, - /* Unsigned 32 bit Little Endian */ - _SND_PCM_FORMAT_U32_LE, - /* Unsigned 32 bit Big Endian */ - _SND_PCM_FORMAT_U32_BE, - /* Float 32 bit Little Endian, Range -1.0 to 1.0 */ - _SND_PCM_FORMAT_FLOAT_LE, - /* Float 32 bit Big Endian, Range -1.0 to 1.0 */ - _SND_PCM_FORMAT_FLOAT_BE, - /* Float 64 bit Little Endian, Range -1.0 to 1.0 */ - _SND_PCM_FORMAT_FLOAT64_LE, - /* Float 64 bit Big Endian, Range -1.0 to 1.0 */ - _SND_PCM_FORMAT_FLOAT64_BE, - /* IEC-958 Little Endian */ - _SND_PCM_FORMAT_IEC958_SUBFRAME_LE, - /* IEC-958 Big Endian */ - _SND_PCM_FORMAT_IEC958_SUBFRAME_BE, - /* Mu-Law */ - _SND_PCM_FORMAT_MU_LAW, - /* A-Law */ - _SND_PCM_FORMAT_A_LAW, - /* Ima-ADPCM */ - _SND_PCM_FORMAT_IMA_ADPCM, - /* MPEG */ - _SND_PCM_FORMAT_MPEG, - /* GSM */ - _SND_PCM_FORMAT_GSM, - /* Special */ - _SND_PCM_FORMAT_SPECIAL = 31, - /* Signed 24bit Little Endian in 3bytes format */ - _SND_PCM_FORMAT_S24_3LE = 32, - /* Signed 24bit Big Endian in 3bytes format */ - _SND_PCM_FORMAT_S24_3BE, - /* Unsigned 24bit Little Endian in 3bytes format */ - _SND_PCM_FORMAT_U24_3LE, - /* Unsigned 24bit Big Endian in 3bytes format */ - _SND_PCM_FORMAT_U24_3BE, - /* Signed 20bit Little Endian in 3bytes format */ - _SND_PCM_FORMAT_S20_3LE, - /* Signed 20bit Big Endian in 3bytes format */ - _SND_PCM_FORMAT_S20_3BE, - /* Unsigned 20bit Little Endian in 3bytes format */ - _SND_PCM_FORMAT_U20_3LE, - /* Unsigned 20bit Big Endian in 3bytes format */ - _SND_PCM_FORMAT_U20_3BE, - /* Signed 18bit Little Endian in 3bytes format */ - _SND_PCM_FORMAT_S18_3LE, - /* Signed 18bit Big Endian in 3bytes format */ - _SND_PCM_FORMAT_S18_3BE, - /* Unsigned 18bit Little Endian in 3bytes format */ - _SND_PCM_FORMAT_U18_3LE, - /* Unsigned 18bit Big Endian in 3bytes format */ - _SND_PCM_FORMAT_U18_3BE, - _SND_PCM_FORMAT_LAST = _SND_PCM_FORMAT_U18_3BE, - -#if __BYTE_ORDER == __LITTLE_ENDIAN - /* Signed 16 bit CPU endian */ - _SND_PCM_FORMAT_S16 = _SND_PCM_FORMAT_S16_LE, - /* Unsigned 16 bit CPU endian */ - _SND_PCM_FORMAT_U16 = _SND_PCM_FORMAT_U16_LE, - /* Signed 24 bit CPU endian */ - _SND_PCM_FORMAT_S24 = _SND_PCM_FORMAT_S24_LE, - /* Unsigned 24 bit CPU endian */ - _SND_PCM_FORMAT_U24 = _SND_PCM_FORMAT_U24_LE, - /* Signed 32 bit CPU endian */ - _SND_PCM_FORMAT_S32 = _SND_PCM_FORMAT_S32_LE, - /* Unsigned 32 bit CPU endian */ - _SND_PCM_FORMAT_U32 = _SND_PCM_FORMAT_U32_LE, - /* Float 32 bit CPU endian */ - _SND_PCM_FORMAT_FLOAT = _SND_PCM_FORMAT_FLOAT_LE, - /* Float 64 bit CPU endian */ - _SND_PCM_FORMAT_FLOAT64 = _SND_PCM_FORMAT_FLOAT64_LE, - /* IEC-958 CPU Endian */ - _SND_PCM_FORMAT_IEC958_SUBFRAME = - _SND_PCM_FORMAT_IEC958_SUBFRAME_LE -#elif __BYTE_ORDER == __BIG_ENDIAN - /* Signed 16 bit CPU endian */ - _SND_PCM_FORMAT_S16 = _SND_PCM_FORMAT_S16_BE, - /* Unsigned 16 bit CPU endian */ - _SND_PCM_FORMAT_U16 = _SND_PCM_FORMAT_U16_BE, - /* Signed 24 bit CPU endian */ - _SND_PCM_FORMAT_S24 = _SND_PCM_FORMAT_S24_BE, - /* Unsigned 24 bit CPU endian */ - _SND_PCM_FORMAT_U24 = _SND_PCM_FORMAT_U24_BE, - /* Signed 32 bit CPU endian */ - _SND_PCM_FORMAT_S32 = _SND_PCM_FORMAT_S32_BE, - /* Unsigned 32 bit CPU endian */ - _SND_PCM_FORMAT_U32 = _SND_PCM_FORMAT_U32_BE, - /* Float 32 bit CPU endian */ - _SND_PCM_FORMAT_FLOAT = _SND_PCM_FORMAT_FLOAT_BE, - /* Float 64 bit CPU endian */ - _SND_PCM_FORMAT_FLOAT64 = _SND_PCM_FORMAT_FLOAT64_BE, - /* IEC-958 CPU Endian */ - _SND_PCM_FORMAT_IEC958_SUBFRAME = - _SND_PCM_FORMAT_IEC958_SUBFRAME_BE -#else -#error "Unknown endian" -#endif -} _snd_pcm_format_t; - -/* Unsigned frames quantity */ -typedef unsigned long _snd_pcm_uframes_t; -/* Signed frames quantity */ -typedef long _snd_pcm_sframes_t; - -/* Non blocking mode (flag for open mode) \hideinitializer */ -#define _SND_PCM_NONBLOCK 0x00000001 - -typedef int (*snd_pcm_open_ProcPtr) - (_snd_pcm_t **pcm, const char *name, _snd_pcm_stream_t stream, - int mode); -LOCALVAR snd_pcm_open_ProcPtr _snd_pcm_open = NULL; -LOCALVAR bool Did_snd_pcm_open = false; - -LOCALFUNC bool Have_snd_pcm_open(void) -{ - if (! Did_snd_pcm_open) { - if (HaveAlsaLib()) { - _snd_pcm_open = (snd_pcm_open_ProcPtr)dlsym(alsa_handle, - "snd_pcm_open"); - if (NULL == _snd_pcm_open) { - fprintf(stderr, "dlsym snd_pcm_open failed\n"); - } - } - Did_snd_pcm_open = true; - } - return (_snd_pcm_open != NULL); -} - -typedef int (*snd_pcm_close_ProcPtr)(_snd_pcm_t *pcm); -LOCALVAR snd_pcm_close_ProcPtr _snd_pcm_close = NULL; -LOCALVAR bool Did_snd_pcm_close = false; - -LOCALFUNC bool Have_snd_pcm_close(void) -{ - if (! Did_snd_pcm_close) { - if (HaveAlsaLib()) { - _snd_pcm_close = (snd_pcm_close_ProcPtr)dlsym(alsa_handle, - "snd_pcm_close"); - if (NULL == _snd_pcm_close) { - fprintf(stderr, "dlsym snd_pcm_close failed\n"); - } - } - Did_snd_pcm_close = true; - } - return (_snd_pcm_close != NULL); -} - -typedef int (*snd_pcm_hw_params_malloc_ProcPtr) - (_snd_pcm_hw_params_t **ptr); -LOCALVAR snd_pcm_hw_params_malloc_ProcPtr _snd_pcm_hw_params_malloc - = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_malloc = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_malloc(void) -{ - if (! Did_snd_pcm_hw_params_malloc) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_malloc = - (snd_pcm_hw_params_malloc_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_malloc"); - if (NULL == _snd_pcm_hw_params_malloc) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_malloc failed\n"); - } - } - Did_snd_pcm_hw_params_malloc = true; - } - return (_snd_pcm_hw_params_malloc != NULL); -} - -typedef void (*snd_pcm_hw_params_free_ProcPtr) - (_snd_pcm_hw_params_t *obj); -LOCALVAR snd_pcm_hw_params_free_ProcPtr - _snd_pcm_hw_params_free = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_free = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_free(void) -{ - if (! Did_snd_pcm_hw_params_free) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_free = (snd_pcm_hw_params_free_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_free"); - if (NULL == _snd_pcm_hw_params_free) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_free failed\n"); - } - } - Did_snd_pcm_hw_params_free = true; - } - return (_snd_pcm_hw_params_free != NULL); -} - -typedef int (*snd_pcm_hw_params_any_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params); -LOCALVAR snd_pcm_hw_params_any_ProcPtr _snd_pcm_hw_params_any = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_any = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_any(void) -{ - if (! Did_snd_pcm_hw_params_any) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_any = (snd_pcm_hw_params_any_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_any"); - if (NULL == _snd_pcm_hw_params_any) { - fprintf(stderr, "dlsym snd_pcm_hw_params_any failed\n"); - } - } - Did_snd_pcm_hw_params_any = true; - } - return (_snd_pcm_hw_params_any != NULL); -} - -typedef int (*snd_pcm_hw_params_set_access_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params, - _snd_pcm_access_t _access); -LOCALVAR snd_pcm_hw_params_set_access_ProcPtr - _snd_pcm_hw_params_set_access = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_set_access = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_set_access(void) -{ - if (! Did_snd_pcm_hw_params_set_access) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_set_access = - (snd_pcm_hw_params_set_access_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_set_access"); - if (NULL == _snd_pcm_hw_params_set_access) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_set_access failed\n"); - } - } - Did_snd_pcm_hw_params_set_access = true; - } - return (_snd_pcm_hw_params_set_access != NULL); -} - -typedef int (*snd_pcm_hw_params_set_format_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params, - _snd_pcm_format_t val); -LOCALVAR snd_pcm_hw_params_set_format_ProcPtr - _snd_pcm_hw_params_set_format = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_set_format = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_set_format(void) -{ - if (! Did_snd_pcm_hw_params_set_format) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_set_format = - (snd_pcm_hw_params_set_format_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_set_format"); - if (NULL == _snd_pcm_hw_params_set_format) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_set_format failed\n"); - } - } - Did_snd_pcm_hw_params_set_format = true; - } - return (_snd_pcm_hw_params_set_format != NULL); -} - -typedef int (*snd_pcm_hw_params_set_rate_near_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params, - unsigned int *val, int *dir); -LOCALVAR snd_pcm_hw_params_set_rate_near_ProcPtr - _snd_pcm_hw_params_set_rate_near = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_set_rate_near = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_set_rate_near(void) -{ - if (! Did_snd_pcm_hw_params_set_rate_near) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_set_rate_near = - (snd_pcm_hw_params_set_rate_near_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_set_rate_near"); - if (NULL == _snd_pcm_hw_params_set_rate_near) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_set_rate_near failed\n"); - } - } - Did_snd_pcm_hw_params_set_rate_near = true; - } - return (_snd_pcm_hw_params_set_rate_near != NULL); -} - -typedef int (*snd_pcm_hw_params_set_channels_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params, - unsigned int val); -LOCALVAR snd_pcm_hw_params_set_channels_ProcPtr - _snd_pcm_hw_params_set_channels = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_set_channels = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_set_channels(void) -{ - if (! Did_snd_pcm_hw_params_set_channels) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_set_channels = - (snd_pcm_hw_params_set_channels_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params_set_channels"); - if (NULL == _snd_pcm_hw_params_set_channels) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_set_channels failed\n"); - } - } - Did_snd_pcm_hw_params_set_channels = true; - } - return (_snd_pcm_hw_params_set_channels != NULL); -} - -typedef int (*snd_pcm_hw_params_set_buffer_size_near_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params, - _snd_pcm_uframes_t *val); -LOCALVAR snd_pcm_hw_params_set_buffer_size_near_ProcPtr - _snd_pcm_hw_params_set_buffer_size_near = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_set_buffer_size_near = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_set_buffer_size_near(void) -{ - if (! Did_snd_pcm_hw_params_set_buffer_size_near) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_set_buffer_size_near = - (snd_pcm_hw_params_set_buffer_size_near_ProcPtr) - dlsym(alsa_handle, - "snd_pcm_hw_params_set_buffer_size_near"); - if (NULL == _snd_pcm_hw_params_set_buffer_size_near) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_set_buffer_size_near" - " failed\n"); - } - } - Did_snd_pcm_hw_params_set_buffer_size_near = true; - } - return (_snd_pcm_hw_params_set_buffer_size_near != NULL); -} - -typedef int (*snd_pcm_hw_params_set_period_size_near_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params, - _snd_pcm_uframes_t *val, int *dir); -LOCALVAR snd_pcm_hw_params_set_period_size_near_ProcPtr - _snd_pcm_hw_params_set_period_size_near = NULL; -LOCALVAR bool Did_snd_pcm_hw_params_set_period_size_near = false; - -LOCALFUNC bool Have_snd_pcm_hw_params_set_period_size_near(void) -{ - if (! Did_snd_pcm_hw_params_set_period_size_near) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params_set_period_size_near = - (snd_pcm_hw_params_set_period_size_near_ProcPtr) - dlsym(alsa_handle, - "snd_pcm_hw_params_set_period_size_near"); - if (NULL == _snd_pcm_hw_params_set_period_size_near) { - fprintf(stderr, - "dlsym snd_pcm_hw_params_set_period_size_near" - " failed\n"); - } - } - Did_snd_pcm_hw_params_set_period_size_near = true; - } - return (_snd_pcm_hw_params_set_period_size_near != NULL); -} - -typedef int (*snd_pcm_hw_params_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_hw_params_t *params); -LOCALVAR snd_pcm_hw_params_ProcPtr _snd_pcm_hw_params = NULL; -LOCALVAR bool Did_snd_pcm_hw_params = false; - -LOCALFUNC bool Have_snd_pcm_hw_params(void) -{ - if (! Did_snd_pcm_hw_params) { - if (HaveAlsaLib()) { - _snd_pcm_hw_params = (snd_pcm_hw_params_ProcPtr) - dlsym(alsa_handle, "snd_pcm_hw_params"); - if (NULL == _snd_pcm_hw_params) { - fprintf(stderr, "dlsym snd_pcm_hw_params failed\n"); - } - } - Did_snd_pcm_hw_params = true; - } - return (_snd_pcm_hw_params != NULL); -} - -typedef int (*snd_pcm_sw_params_malloc_ProcPtr) - (_snd_pcm_sw_params_t **ptr); -LOCALVAR snd_pcm_sw_params_malloc_ProcPtr - _snd_pcm_sw_params_malloc = NULL; -LOCALVAR bool Did_snd_pcm_sw_params_malloc = false; - -LOCALFUNC bool Have_snd_pcm_sw_params_malloc(void) -{ - if (! Did_snd_pcm_sw_params_malloc) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params_malloc = - (snd_pcm_sw_params_malloc_ProcPtr) - dlsym(alsa_handle, "snd_pcm_sw_params_malloc"); - if (NULL == _snd_pcm_sw_params_malloc) { - fprintf(stderr, - "dlsym snd_pcm_sw_params_malloc failed\n"); - } - } - Did_snd_pcm_sw_params_malloc = true; - } - return (_snd_pcm_sw_params_malloc != NULL); -} - -typedef void (*snd_pcm_sw_params_free_ProcPtr) - (_snd_pcm_sw_params_t *obj); -LOCALVAR snd_pcm_sw_params_free_ProcPtr - _snd_pcm_sw_params_free = NULL; -LOCALVAR bool Did_snd_pcm_sw_params_free = false; - -LOCALFUNC bool Have_snd_pcm_sw_params_free(void) -{ - if (! Did_snd_pcm_sw_params_free) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params_free = (snd_pcm_sw_params_free_ProcPtr) - dlsym(alsa_handle, "snd_pcm_sw_params_free"); - if (NULL == _snd_pcm_sw_params_free) { - fprintf(stderr, - "dlsym snd_pcm_sw_params_free failed\n"); - } - } - Did_snd_pcm_sw_params_free = true; - } - return (_snd_pcm_sw_params_free != NULL); -} - -typedef int (*snd_pcm_sw_params_current_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_sw_params_t *params); -LOCALVAR snd_pcm_sw_params_current_ProcPtr - _snd_pcm_sw_params_current = NULL; -LOCALVAR bool Did_snd_pcm_sw_params_current = false; - -LOCALFUNC bool Have_snd_pcm_sw_params_current(void) -{ - if (! Did_snd_pcm_sw_params_current) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params_current = - (snd_pcm_sw_params_current_ProcPtr) - dlsym(alsa_handle, "snd_pcm_sw_params_current"); - if (NULL == _snd_pcm_sw_params_current) { - fprintf(stderr, - "dlsym snd_pcm_sw_params_current failed\n"); - } - } - Did_snd_pcm_sw_params_current = true; - } - return (_snd_pcm_sw_params_current != NULL); -} - -typedef int (*snd_pcm_sw_params_set_start_threshold_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_sw_params_t *params, - _snd_pcm_uframes_t val); -LOCALVAR snd_pcm_sw_params_set_start_threshold_ProcPtr - _snd_pcm_sw_params_set_start_threshold = NULL; -LOCALVAR bool Did_snd_pcm_sw_params_set_start_threshold = false; - -LOCALFUNC bool Have_snd_pcm_sw_params_set_start_threshold(void) -{ - if (! Did_snd_pcm_sw_params_set_start_threshold) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params_set_start_threshold = - (snd_pcm_sw_params_set_start_threshold_ProcPtr) - dlsym(alsa_handle, - "snd_pcm_sw_params_set_start_threshold"); - if (NULL == _snd_pcm_sw_params_set_start_threshold) { - fprintf(stderr, - "dlsym snd_pcm_sw_params_set_start_threshold" - " failed\n"); - } - } - Did_snd_pcm_sw_params_set_start_threshold = true; - } - return (_snd_pcm_sw_params_set_start_threshold != NULL); -} - -typedef int (*snd_pcm_sw_params_set_avail_min_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_sw_params_t *params, - _snd_pcm_uframes_t val); -LOCALVAR snd_pcm_sw_params_set_avail_min_ProcPtr - _snd_pcm_sw_params_set_avail_min = NULL; -LOCALVAR bool Did_snd_pcm_sw_params_set_avail_min = false; - -LOCALFUNC bool Have_snd_pcm_sw_params_set_avail_min(void) -{ - if (! Did_snd_pcm_sw_params_set_avail_min) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params_set_avail_min = - (snd_pcm_sw_params_set_avail_min_ProcPtr) - dlsym(alsa_handle, "snd_pcm_sw_params_set_avail_min"); - if (NULL == _snd_pcm_sw_params_set_avail_min) { - fprintf(stderr, - "dlsym snd_pcm_sw_params_set_avail_min failed\n"); - } - } - Did_snd_pcm_sw_params_set_avail_min = true; - } - return (_snd_pcm_sw_params_set_avail_min != NULL); -} - -typedef int (*snd_pcm_sw_params_set_xfer_align_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_sw_params_t *params, - _snd_pcm_uframes_t val); -LOCALVAR snd_pcm_sw_params_set_xfer_align_ProcPtr - _snd_pcm_sw_params_set_xfer_align = NULL; -LOCALVAR bool Did_snd_pcm_sw_params_set_xfer_align = false; - -LOCALFUNC bool Have_snd_pcm_sw_params_set_xfer_align(void) -{ - if (! Did_snd_pcm_sw_params_set_xfer_align) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params_set_xfer_align = - (snd_pcm_sw_params_set_xfer_align_ProcPtr) - dlsym(alsa_handle, "snd_pcm_sw_params_set_xfer_align"); - if (NULL == _snd_pcm_sw_params_set_xfer_align) { - fprintf(stderr, - "dlsym snd_pcm_sw_params_set_xfer_align failed\n"); - } - } - Did_snd_pcm_sw_params_set_xfer_align = true; - } - return (_snd_pcm_sw_params_set_xfer_align != NULL); -} - -typedef int (*snd_pcm_sw_params_ProcPtr) - (_snd_pcm_t *pcm, _snd_pcm_sw_params_t *params); -LOCALVAR snd_pcm_sw_params_ProcPtr _snd_pcm_sw_params = NULL; -LOCALVAR bool Did_snd_pcm_sw_params = false; - -LOCALFUNC bool Have_snd_pcm_sw_params(void) -{ - if (! Did_snd_pcm_sw_params) { - if (HaveAlsaLib()) { - _snd_pcm_sw_params = (snd_pcm_sw_params_ProcPtr) - dlsym(alsa_handle, "snd_pcm_sw_params"); - if (NULL == _snd_pcm_sw_params) { - fprintf(stderr, "dlsym snd_pcm_sw_params failed\n"); - } - } - Did_snd_pcm_sw_params = true; - } - return (_snd_pcm_sw_params != NULL); -} - -typedef int (*snd_pcm_nonblock_ProcPtr) - (_snd_pcm_t *pcm, int nonblock); -LOCALVAR snd_pcm_nonblock_ProcPtr _snd_pcm_nonblock = NULL; -LOCALVAR bool Did_snd_pcm_nonblock = false; - -LOCALFUNC bool Have_snd_pcm_nonblock(void) -{ - if (! Did_snd_pcm_nonblock) { - if (HaveAlsaLib()) { - _snd_pcm_nonblock = (snd_pcm_nonblock_ProcPtr) - dlsym(alsa_handle, "snd_pcm_nonblock"); - if (NULL == _snd_pcm_nonblock) { - fprintf(stderr, "dlsym snd_pcm_nonblock failed\n"); - } - } - Did_snd_pcm_nonblock = true; - } - return (_snd_pcm_nonblock != NULL); -} - -typedef _snd_pcm_state_t (*snd_pcm_state_ProcPtr)(_snd_pcm_t *pcm); -LOCALVAR snd_pcm_state_ProcPtr _snd_pcm_state = NULL; -LOCALVAR bool Did_snd_pcm_state = false; - -LOCALFUNC bool Have_snd_pcm_state(void) -{ - if (! Did_snd_pcm_state) { - if (HaveAlsaLib()) { - _snd_pcm_state = (snd_pcm_state_ProcPtr) - dlsym(alsa_handle, "snd_pcm_state"); - if (NULL == _snd_pcm_state) { - fprintf(stderr, "dlsym snd_pcm_state failed\n"); - } - } - Did_snd_pcm_state = true; - } - return (_snd_pcm_state != NULL); -} - -typedef int (*snd_pcm_prepare_ProcPtr)(_snd_pcm_t *pcm); -LOCALVAR snd_pcm_prepare_ProcPtr _snd_pcm_prepare = NULL; -LOCALVAR bool Did_snd_pcm_prepare = false; - -LOCALFUNC bool Have_snd_pcm_prepare(void) -{ - if (! Did_snd_pcm_prepare) { - if (HaveAlsaLib()) { - _snd_pcm_prepare = (snd_pcm_prepare_ProcPtr) - dlsym(alsa_handle, "snd_pcm_prepare"); - if (NULL == _snd_pcm_prepare) { - fprintf(stderr, "dlsym snd_pcm_prepare failed\n"); - } - } - Did_snd_pcm_prepare = true; - } - return (_snd_pcm_prepare != NULL); -} - -typedef int (*snd_pcm_start_ProcPtr)(_snd_pcm_t *pcm); -LOCALVAR snd_pcm_start_ProcPtr _snd_pcm_start = NULL; -LOCALVAR bool Did_snd_pcm_start = false; - -LOCALFUNC bool Have_snd_pcm_start(void) -{ - if (! Did_snd_pcm_start) { - if (HaveAlsaLib()) { - _snd_pcm_start = (snd_pcm_start_ProcPtr) - dlsym(alsa_handle, "snd_pcm_start"); - if (NULL == _snd_pcm_start) { - fprintf(stderr, "dlsym snd_pcm_start failed\n"); - } - } - Did_snd_pcm_start = true; - } - return (_snd_pcm_start != NULL); -} - -typedef int (*snd_pcm_resume_ProcPtr)(_snd_pcm_t *pcm); -LOCALVAR snd_pcm_resume_ProcPtr _snd_pcm_resume = NULL; -LOCALVAR bool Did_snd_pcm_resume = false; - -LOCALFUNC bool Have_snd_pcm_resume(void) -{ - if (! Did_snd_pcm_resume) { - if (HaveAlsaLib()) { - _snd_pcm_resume = (snd_pcm_resume_ProcPtr) - dlsym(alsa_handle, "snd_pcm_resume"); - if (NULL == _snd_pcm_resume) { - fprintf(stderr, "dlsym snd_pcm_resume failed\n"); - } - } - Did_snd_pcm_resume = true; - } - return (_snd_pcm_resume != NULL); -} - -typedef _snd_pcm_sframes_t (*snd_pcm_avail_update_ProcPtr) - (_snd_pcm_t *pcm); -LOCALVAR snd_pcm_avail_update_ProcPtr _snd_pcm_avail_update = NULL; -LOCALVAR bool Did_snd_pcm_avail_update = false; - -LOCALFUNC bool Have_snd_pcm_avail_update(void) -{ - if (! Did_snd_pcm_avail_update) { - if (HaveAlsaLib()) { - _snd_pcm_avail_update = (snd_pcm_avail_update_ProcPtr) - dlsym(alsa_handle, "snd_pcm_avail_update"); - if (NULL == _snd_pcm_avail_update) { - fprintf(stderr, "dlsym snd_pcm_avail_update failed\n"); - } - } - Did_snd_pcm_avail_update = true; - } - return (_snd_pcm_avail_update != NULL); -} - -typedef _snd_pcm_sframes_t (*snd_pcm_writei_ProcPtr) - (_snd_pcm_t *pcm, const void *buffer, _snd_pcm_uframes_t size); -LOCALVAR snd_pcm_writei_ProcPtr _snd_pcm_writei = NULL; -LOCALVAR bool Did_snd_pcm_writei = false; - -LOCALFUNC bool Have_snd_pcm_writei(void) -{ - if (! Did_snd_pcm_writei) { - if (HaveAlsaLib()) { - _snd_pcm_writei = (snd_pcm_writei_ProcPtr) - dlsym(alsa_handle, "snd_pcm_writei"); - if (NULL == _snd_pcm_writei) { - fprintf(stderr, "dlsym snd_pcm_writei failed\n"); - } - } - Did_snd_pcm_writei = true; - } - return (_snd_pcm_writei != NULL); -} - -typedef int (*snd_pcm_drop_ProcPtr)(_snd_pcm_t *pcm); -LOCALVAR snd_pcm_drop_ProcPtr _snd_pcm_drop = NULL; -LOCALVAR bool Did_snd_pcm_drop = false; - -LOCALFUNC bool Have_snd_pcm_drop(void) -{ - if (! Did_snd_pcm_drop) { - if (HaveAlsaLib()) { - _snd_pcm_drop = (snd_pcm_drop_ProcPtr) - dlsym(alsa_handle, "snd_pcm_drop"); - if (NULL == _snd_pcm_drop) { - fprintf(stderr, "dlsym snd_pcm_drop failed\n"); - } - } - Did_snd_pcm_drop = true; - } - return (_snd_pcm_drop != NULL); -} - -#if RaspbianWorkAround -typedef int (*snd_pcm_status_malloc_ProcPtr) - (_snd_pcm_status_t **ptr); -LOCALVAR snd_pcm_status_malloc_ProcPtr _snd_pcm_status_malloc = NULL; -LOCALVAR bool Did_snd_pcm_status_malloc = false; - -LOCALFUNC bool Have_snd_pcm_status_malloc(void) -{ - if (! Did_snd_pcm_status_malloc) { - if (HaveAlsaLib()) { - _snd_pcm_status_malloc = (snd_pcm_status_malloc_ProcPtr) - dlsym(alsa_handle, "snd_pcm_status_malloc"); - if (NULL == _snd_pcm_status_malloc) { - fprintf(stderr, "dlsym snd_pcm_status_malloc failed\n"); - } - } - Did_snd_pcm_status_malloc = true; - } - return (_snd_pcm_status_malloc != NULL); -} -#endif - -#if RaspbianWorkAround -typedef int (*snd_pcm_status_ProcPtr)(_snd_pcm_t *pcm, - _snd_pcm_status_t *status); -LOCALVAR snd_pcm_status_ProcPtr _snd_pcm_status = NULL; -LOCALVAR bool Did_snd_pcm_status = false; - -LOCALFUNC bool Have_snd_pcm_status(void) -{ - if (! Did_snd_pcm_status) { - if (HaveAlsaLib()) { - _snd_pcm_status = (snd_pcm_status_ProcPtr) - dlsym(alsa_handle, "snd_pcm_status"); - if (NULL == _snd_pcm_status) { - fprintf(stderr, "dlsym snd_pcm_status failed\n"); - } - } - Did_snd_pcm_status = true; - } - return (_snd_pcm_status != NULL); -} -#endif - -#if RaspbianWorkAround -typedef _snd_pcm_uframes_t (*snd_pcm_status_get_avail_ProcPtr) - (const _snd_pcm_status_t *obj); -LOCALVAR snd_pcm_status_get_avail_ProcPtr - _snd_pcm_status_get_avail = NULL; -LOCALVAR bool Did_snd_pcm_status_get_avail = false; - -LOCALFUNC bool Have_snd_pcm_status_get_avail(void) -{ - if (! Did_snd_pcm_status_get_avail) { - if (HaveAlsaLib()) { - _snd_pcm_status_get_avail = - (snd_pcm_status_get_avail_ProcPtr) - dlsym(alsa_handle, "snd_pcm_status_get_avail"); - if (NULL == _snd_pcm_status_get_avail) { - fprintf(stderr, - "dlsym snd_pcm_status_get_avail failed\n"); - } - } - Did_snd_pcm_status_get_avail = true; - } - return (_snd_pcm_status_get_avail != NULL); -} -#endif - -typedef const char * (*snd_strerror_ProcPtr)(int errnum); -LOCALVAR snd_strerror_ProcPtr _snd_strerror = NULL; -LOCALVAR bool Did_snd_strerror = false; - -LOCALFUNC bool Have_snd_strerror(void) -{ - if (! Did_snd_strerror) { - if (HaveAlsaLib()) { - _snd_strerror = (snd_strerror_ProcPtr) - dlsym(alsa_handle, "snd_strerror"); - if (NULL == _snd_strerror) { - fprintf(stderr, "dlsym snd_strerror failed\n"); - } - } - Did_snd_strerror = true; - } - return (_snd_strerror != NULL); -} - -#endif - - -/* - The elaborate private buffer is mostly - redundant since alsa has its own ring - buffer. But using it keeps the code - closer to the other ports. And anyway - there is no guarantee just what size - buffer you'll get from alsa. -*/ - - -#if 4 == kLn2SoundSampSz -LOCALPROC ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -#define desired_alsa_buffer_size kAllBuffLen -#define desired_alsa_period_size kOneBuffLen - -LOCALVAR char *alsadev_name = NULL; - -LOCALVAR _snd_pcm_t *pcm_handle = NULL; -LOCALVAR _snd_pcm_uframes_t buffer_size; -LOCALVAR _snd_pcm_uframes_t period_size; - - -LOCALVAR bool Sound_StartPend = false; - -#if RaspbianWorkAround -LOCALVAR _snd_pcm_status_t *status = NULL; - -LOCALFUNC bool HaveStatusAlloc(void) -{ - if (NULL == status) { - if (Have_snd_pcm_status_malloc()) - if (Have_snd_pcm_status()) - if (Have_snd_pcm_status_get_avail()) - { - if (_snd_pcm_status_malloc(&status) < 0) { - status = NULL; /* just to make sure */ - } else { - /* snd_pcm_status_free(status); */ - } - } - } - - return NULL != status; -} -#endif - -LOCALPROC Sound_WriteOut(void) -{ - int retry_count = 32; - -label_retry: - if (--retry_count > 0) { - _snd_pcm_sframes_t avail; - int err; - _snd_pcm_state_t cur_state = _snd_pcm_state(pcm_handle); - - if (_SND_PCM_STATE_PREPARED == cur_state) { - if (! Sound_StartPend) { - if (TheFillOffset - ThePlayOffset >= kAllBuffLen) { - Sound_StartPend = true; - } - } - if (Sound_StartPend) { - cur_state = _SND_PCM_STATE_RUNNING; - } - } - - if (_SND_PCM_STATE_RUNNING != cur_state) { - switch (cur_state) { - case _SND_PCM_STATE_SETUP: - case _SND_PCM_STATE_XRUN: - err = _snd_pcm_prepare(pcm_handle); - if (err < 0) { - fprintf(stderr, "pcm prepare error: %s\n", - _snd_strerror(err)); - } else { - /* fprintf(stderr, "prepare succeeded\n"); */ - goto label_retry; - } - break; - case _SND_PCM_STATE_SUSPENDED: - err = _snd_pcm_resume(pcm_handle); - if (err < 0) { - fprintf(stderr, "pcm resume error: %s\n", - _snd_strerror(err)); - } else { - /* fprintf(stderr, "resume succeeded\n"); */ - goto label_retry; - } - break; - case _SND_PCM_STATE_DISCONNECTED: - /* just abort ? */ - break; - case _SND_PCM_STATE_PREPARED: - /* leave */ - break; - default: - fprintf(stderr, "unknown alsa pcm state\n"); - break; - } - } else if ((avail = _snd_pcm_avail_update(pcm_handle)) < 0) { - fprintf(stderr, "pcm update error: %s\n", - _snd_strerror(avail)); - } else { - tpSoundSamp NextPlayPtr; - uint16_t PlayNowSize = 0; - uint16_t MaskedFillOffset = ThePlayOffset & kOneBuffMask; - -#if RaspbianWorkAround - if ((avail > buffer_size) || (avail < 0)) { - /* - fprintf(stderr, "need avail workaround: %d\n", - (int)avail); - */ - /* work around bug observed in Raspbian */ - if (HaveStatusAlloc()) { - if (_snd_pcm_status(pcm_handle, status) >= 0) { - avail = _snd_pcm_status_get_avail(status); - } - } - } -#endif - - if (! Sound_StartPend) { - _snd_pcm_uframes_t used = buffer_size - avail; - uint16_t TotPendBuffs = used >> kLnOneBuffLen; - - if (TotPendBuffs < MinFilledSoundBuffs) { - MinFilledSoundBuffs = TotPendBuffs; - } - /* fprintf(stderr, "buffer used %d\n", (int)used); */ - } - - if (MaskedFillOffset != 0) { - /* take care of left overs */ - PlayNowSize = kOneBuffLen - MaskedFillOffset; - NextPlayPtr = - TheSoundBuffer + (ThePlayOffset & kAllBuffMask); - } else if (0 != - ((TheFillOffset - ThePlayOffset) >> kLnOneBuffLen)) - { - PlayNowSize = kOneBuffLen; - NextPlayPtr = - TheSoundBuffer + (ThePlayOffset & kAllBuffMask); - } else { - /* nothing to play now */ - } - - if (PlayNowSize > avail) { - /* - This isn't supposed to be needed with nonblock - mode. But in Ubuntu 7.04 running in Parallels, - snd_pcm_writei seemed to block anyway. - */ - PlayNowSize = avail; - } - - if (0 != PlayNowSize) { - err = _snd_pcm_writei( - pcm_handle, NextPlayPtr, PlayNowSize); - if (err < 0) { - if ((- EAGAIN == err) || (- ESTRPIPE == err)) { - /* buffer full, try again later */ - /* fprintf(stderr, "pcm write: EAGAIN\n"); */ - } else if (- EPIPE == err) { - /* buffer seems to have emptied */ - /* fprintf(stderr, "pcm write emptied\n"); */ - goto label_retry; - } else { - fprintf(stderr, "pcm write error: %s\n", - _snd_strerror(err)); - } - } else { - ThePlayOffset += err; - goto label_retry; - } - } else if (Sound_StartPend) { - Sound_StartPend = false; - if ((err = _snd_pcm_start(pcm_handle)) < 0) { - fprintf(stderr, "pcm start error: %s\n", - _snd_strerror(err)); - } - } - } - } -} - -LOCALPROC Sound_Start(void) -{ - if (pcm_handle != NULL) { - Sound_Start0(); - } -} - -LOCALPROC Sound_Stop(void) -{ - if (pcm_handle != NULL) { - _snd_pcm_drop(pcm_handle); - } -} - -LOCALFUNC bool HaveAlsaRoutines(void) -{ - bool IsOk = false; - - if (Have_snd_pcm_open()) - if (Have_snd_pcm_close()) - if (Have_snd_pcm_hw_params_malloc()) - if (Have_snd_pcm_hw_params_free()) - if (Have_snd_pcm_hw_params_any()) - if (Have_snd_pcm_hw_params_set_access()) - if (Have_snd_pcm_hw_params_set_format()) - if (Have_snd_pcm_hw_params_set_rate_near()) - if (Have_snd_pcm_hw_params_set_channels()) - if (Have_snd_pcm_hw_params_set_buffer_size_near()) - if (Have_snd_pcm_hw_params_set_period_size_near()) - if (Have_snd_pcm_hw_params()) - if (Have_snd_pcm_sw_params_malloc()) - if (Have_snd_pcm_sw_params_free()) - if (Have_snd_pcm_sw_params_current()) - if (Have_snd_pcm_sw_params_set_start_threshold()) - if (Have_snd_pcm_sw_params_set_avail_min()) - if (Have_snd_pcm_sw_params()) - if (Have_snd_pcm_nonblock()) - if (Have_snd_pcm_state()) - if (Have_snd_pcm_prepare()) - if (Have_snd_pcm_start()) - if (Have_snd_pcm_resume()) - if (Have_snd_pcm_avail_update()) - if (Have_snd_pcm_writei()) - if (Have_snd_pcm_drop()) - if (Have_snd_strerror()) - { - IsOk = true; - } - - return IsOk; -} - -#if 4 == kLn2SoundSampSz -#define DesiredFormat _SND_PCM_FORMAT_S16 -#else -#define DesiredFormat _SND_PCM_FORMAT_U8 -#endif - -LOCALPROC Sound_Init0(void) -{ - _snd_pcm_hw_params_t *hw_params = NULL; - _snd_pcm_sw_params_t *sw_params = NULL; - unsigned int rrate = SOUND_SAMPLERATE; - int err; - - buffer_size = desired_alsa_buffer_size; - period_size = desired_alsa_period_size; - - /* Open the sound device */ - if (NULL == alsadev_name) { - alsadev_name = getenv("AUDIODEV"); - if (NULL == alsadev_name) { - alsadev_name = strdup("default"); - } - } - - if ((err = _snd_pcm_open(&pcm_handle, alsadev_name, - _SND_PCM_STREAM_PLAYBACK, _SND_PCM_NONBLOCK)) < 0) - { - fprintf(stderr, "cannot open audio device %s (%s)\n", - alsadev_name, _snd_strerror(err)); - pcm_handle = NULL; - } else - /* Set some hardware parameters */ - if ((err = _snd_pcm_hw_params_malloc(&hw_params)) < 0) { - fprintf(stderr, - "cannot allocate hardware parameter structure (%s)\n", - _snd_strerror(err)); - hw_params = NULL; - } else - if ((err = _snd_pcm_hw_params_any(pcm_handle, hw_params)) < 0) { - fprintf(stderr, - "cannot initialize hardware parameter structure (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params_set_access(pcm_handle, - hw_params, _SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) - { - fprintf(stderr, "cannot set access type (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params_set_format(pcm_handle, - hw_params, DesiredFormat)) < 0) - { - fprintf(stderr, "cannot set sample format (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params_set_rate_near(pcm_handle, - hw_params, &rrate, NULL)) < 0) - { - fprintf(stderr, "cannot set sample rate (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params_set_channels(pcm_handle, - hw_params, 1)) < 0) - { - fprintf(stderr, "cannot set channel count (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params_set_buffer_size_near(pcm_handle, - hw_params, &buffer_size)) < 0) - { - fprintf(stderr, "cannot set buffer size count (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params_set_period_size_near(pcm_handle, - hw_params, &period_size, NULL)) < 0) - { - fprintf(stderr, "cannot set period size count (%s)\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_hw_params(pcm_handle, hw_params)) < 0) { - fprintf(stderr, "cannot set parameters (%s)\n", - _snd_strerror(err)); - } else - { - if (rrate != SOUND_SAMPLERATE) { - fprintf(stderr, "Warning: sample rate is off by %i Hz\n", - SOUND_SAMPLERATE - rrate); - } - -#if 0 - if (buffer_size != desired_alsa_buffer_size) { - fprintf(stderr, - "Warning: buffer size is off," - " desired %li, actual %li\n", - desired_alsa_buffer_size, buffer_size); - } - - if (period_size != desired_alsa_period_size) { - fprintf(stderr, - "Warning: period size is off," - " desired %li, actual %li\n", - desired_alsa_period_size, period_size); - } -#endif - - _snd_pcm_hw_params_free(hw_params); - hw_params = NULL; - - /* Set some software parameters */ - if ((err = _snd_pcm_sw_params_malloc(&sw_params)) < 0) { - fprintf(stderr, - "cannot allocate software parameter structure (%s)\n", - _snd_strerror(err)); - sw_params = NULL; - } else - if ((err = _snd_pcm_sw_params_current(pcm_handle, - sw_params)) < 0) - { - fprintf(stderr, - "Unable to determine current" - " sw_params for playback: %s\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_sw_params_set_start_threshold(pcm_handle, - sw_params, 0x7FFFFFFF /* buffer_size - period_size */)) < 0) - { - fprintf(stderr, - "Unable to set start threshold mode for playback: %s\n", - _snd_strerror(err)); - } else -#if 0 - if ((err = _snd_pcm_sw_params_set_avail_min(pcm_handle, - sw_params, period_size)) < 0) - { - fprintf(stderr, - "Unable to set avail min for playback: %s\n", - _snd_strerror(err)); - } else -#endif - /* - snd_pcm_sw_params_set_xfer_align deprecated, but - call if available. According to one report, bad results - in old version of alsa lib if not called. - */ - if (Have_snd_pcm_sw_params_set_xfer_align() - && ((err = _snd_pcm_sw_params_set_xfer_align(pcm_handle, - sw_params, 1)) < 0)) - { - fprintf(stderr, - "Unable to set transfer align for playback: %s\n", - _snd_strerror(err)); - } else - if ((err = _snd_pcm_sw_params(pcm_handle, sw_params)) < 0) { - fprintf(stderr, - "Unable to set sw params for playback: %s\n", - _snd_strerror(err)); - } else - { - _snd_pcm_sw_params_free(sw_params); - sw_params = NULL; - - _snd_pcm_nonblock(pcm_handle, 0); - - goto label_done; /* success */ - } - } - - /* clean up after failure */ - - if (sw_params != NULL) { - _snd_pcm_sw_params_free(sw_params); - } - if (hw_params != NULL) { - _snd_pcm_hw_params_free(hw_params); - } - if (pcm_handle != NULL) { - _snd_pcm_close(pcm_handle); - pcm_handle = NULL; - } - -label_done: - ; -} - -LOCALFUNC bool Sound_Init(void) -{ - if (HaveAlsaRoutines()) { - Sound_Init0(); - } - - return true; /* keep going, even if no sound */ -} - -LOCALPROC Sound_UnInit(void) -{ - if (NULL != pcm_handle) { - if (Have_snd_pcm_close()) { - _snd_pcm_close(pcm_handle); - } - pcm_handle = NULL; - } - CloseAlsaLib(); -} - -GLOBALOSGLUPROC Sound_EndWrite(uint16_t actL) -{ - if (Sound_EndWrite0(actL)) { - ConvertSoundBlockToNative(TheSoundBuffer - + ((TheFillOffset - kOneBuffLen) & kAllBuffMask)); - if (NULL != pcm_handle) { - Sound_WriteOut(); - } - } -} - -LOCALPROC Sound_SecondNotify(void) -{ - if (NULL != pcm_handle) { - Sound_SecondNotify0(); - } -} - -#define UsingAlsa 1 diff --git a/src/HW/SOUND/SGLUDDSP.h b/src/HW/SOUND/SGLUDDSP.h deleted file mode 100644 index 6acb790..0000000 --- a/src/HW/SOUND/SGLUDDSP.h +++ /dev/null @@ -1,228 +0,0 @@ -/* - SGLUDDSP.h - - Copyright (C) 2012 Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Sound GLUe for "/Dev/DSP" - OSS and related, accessed through "/dev/dsp" -*/ - -LOCALVAR int audio_fd = -1; -LOCALVAR bool audio_started; - -#if 4 == kLn2SoundSampSz -LOCALPROC ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -LOCALPROC Sound_WriteOut(void) -{ - int retry_count = 32; - -label_retry: - if (--retry_count > 0) { - int err; - struct audio_buf_info info; - - if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) != 0) { - fprintf(stderr, "SNDCTL_DSP_GETOSPACE fails\n"); - } else { - tpSoundSamp NextPlayPtr; - uint16_t PlayNowSize = 0; - uint16_t MaskedFillOffset = ThePlayOffset & kOneBuffMask; - uint16_t PrivateBuffUsed = TheFillOffset - ThePlayOffset; - int used = (info.fragstotal * info.fragsize) - info.bytes; - - if (audio_started) { - uint16_t TotPendBuffs = used >> kLnOneBuffSz; - - if (TotPendBuffs < MinFilledSoundBuffs) { - MinFilledSoundBuffs = TotPendBuffs; - } - /* fprintf(stderr, "buffer used %d\n", (int)used); */ - } else { - if (PrivateBuffUsed >= kAllBuffLen - kOneBuffLen) { - audio_started = true; - } else { - info.bytes = 0; - } - } - - if (MaskedFillOffset != 0) { - /* take care of left overs */ - PlayNowSize = kOneBuffLen - MaskedFillOffset; - NextPlayPtr = - TheSoundBuffer + (ThePlayOffset & kAllBuffMask); - } else if (0 != - ((TheFillOffset - ThePlayOffset) >> kLnOneBuffLen)) - { - PlayNowSize = kOneBuffLen; - NextPlayPtr = - TheSoundBuffer + (ThePlayOffset & kAllBuffMask); - } else { - /* nothing to play now */ - } - -#if 4 == kLn2SoundSampSz - PlayNowSize <<= 1; -#endif - - if (PlayNowSize > info.bytes) { - PlayNowSize = info.bytes; - } - - if (0 != PlayNowSize) { - err = write( - audio_fd, NextPlayPtr, PlayNowSize); - if (err < 0) { - if (- EAGAIN == err) { - /* buffer full, try again later */ - fprintf(stderr, "pcm write: EAGAIN\n"); - } else if (- EPIPE == err) { - /* buffer seems to have emptied */ - fprintf(stderr, "pcm write emptied\n"); - goto label_retry; - } else { - fprintf(stderr, "audio_fd write error: %d\n", - err); - } - } else { - ThePlayOffset += err -#if 4 == kLn2SoundSampSz - >> 1 -#endif - ; - goto label_retry; - } - } - } - } -} - -LOCALPROC Sound_Start(void) -{ - if (audio_fd >= 0) { - Sound_Start0(); - audio_started = false; - } -} - -LOCALPROC Sound_Stop(void) -{ - if (audio_fd >= 0) { - if (0 != - ioctl(audio_fd, SNDCTL_DSP_RESET /* SNDCTL_DSP_HALT */, - NULL)) - { - fprintf(stderr, "SNDCTL_DSP_RESET fails\n"); - } - } -} - -#if 4 == kLn2SoundSampSz -#define DesiredFormat AFMT_S16_NE -#else -#define DesiredFormat AFMT_U8 -#endif - -LOCALFUNC bool Sound_Init(void) -{ - bool IsOk = false; - - audio_fd = open(AudioDevPath, O_WRONLY, 0); - if (audio_fd < 0) { - fprintf(stderr, "open /dev/dsp fails: %d\n", audio_fd); - } else { - int fragment_value = (16 /* 16 fragments */ << 16) -#if 4 == kLn2SoundSampSz - | 10 /* of 1024 bytes */ -#else - | 9 /* of 512 bytes */ -#endif - ; - int channels_value = 1; - int fmt_value = DesiredFormat; - int speed_value = SOUND_SAMPLERATE; - - /* fprintf(stderr, "open /dev/dsp works\n"); */ - - if (0 != - ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &fragment_value)) - { - fprintf(stderr, "SNDCTL_DSP_SETFRAGMENT fails\n"); - } else if ((0 != - ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &channels_value)) - || (channels_value != 1)) - { - fprintf(stderr, "SNDCTL_DSP_CHANNELS fails\n"); - } else if ((0 != - ioctl(audio_fd, SNDCTL_DSP_SETFMT, &fmt_value)) - || (fmt_value != DesiredFormat)) - { - fprintf(stderr, "SNDCTL_DSP_SETFMT fails\n"); - } else if ((0 != - ioctl(audio_fd, SNDCTL_DSP_SPEED, &speed_value)) - || (speed_value != SOUND_SAMPLERATE)) - { - fprintf(stderr, "SNDCTL_DSP_SPEED fails\n"); - } else - { - IsOk = true; - } - - if (! IsOk) { - (void) close(audio_fd); - audio_fd = -1; - } - } - - return true; /* keep going, even if no sound */ -} - -LOCALPROC Sound_UnInit(void) -{ - if (audio_fd >= 0) { - if (close(audio_fd) != 0) { - fprintf(stderr, "close /dev/dsp fails\n"); - } - audio_fd = -1; - } -} - -GLOBALOSGLUPROC Sound_EndWrite(uint16_t actL) -{ - if (Sound_EndWrite0(actL)) { - ConvertSoundBlockToNative(TheSoundBuffer - + ((TheFillOffset - kOneBuffLen) & kAllBuffMask)); - if (audio_fd >= 0) { - Sound_WriteOut(); - } - } -} - -LOCALPROC Sound_SecondNotify(void) -{ - if (audio_fd >= 0) { - Sound_SecondNotify0(); - } -} diff --git a/src/UI/_deprecated/MACOSX/OSGLUCCO.m b/src/UI/_deprecated/MACOSX/OSGLUCCO.m deleted file mode 100644 index 3a2ece0..0000000 --- a/src/UI/_deprecated/MACOSX/OSGLUCCO.m +++ /dev/null @@ -1,4884 +0,0 @@ -/* - OSGLUCCO.m - - Copyright (C) 2012 Paul C. Pratt, SDL by Sam Lantinga and others - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for mac os CoCOa - - All operating system dependent code for the - Mac OS Cocoa should go here. - - Originally derived from Cocoa port of SDL Library - by Sam Lantinga (but little trace of that remains). -*/ - -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" - -#include "UI/MYOSGLUE.h" - -#include "STRCONST.h" - -/* --- adapting to API/ABI version differences --- */ - - -#ifndef MAC_OS_X_VERSION_10_5 -#define MAC_OS_X_VERSION_10_5 1050 -#endif - -#ifndef MAC_OS_X_VERSION_10_6 -#define MAC_OS_X_VERSION_10_6 1060 -#endif - - -#ifndef WantGraphicsSwitching -#define WantGraphicsSwitching 0 -#endif - -#if MAC_OS_X_VERSION_10_5 > MAC_OS_X_VERSION_MAX_ALLOWED - -typedef unsigned long NSUInteger; -typedef long NSInteger; - -typedef struct __CFError * CFErrorRef; - -#if WantGraphicsSwitching -#define NSOpenGLPFAAllowOfflineRenderers \ - (NSOpenGLPixelFormatAttribute)96 -#endif - -#endif - -#if MAC_OS_X_VERSION_10_6 > MAC_OS_X_VERSION_MAX_ALLOWED - -@protocol NSWindowDelegate @end -@protocol NSApplicationDelegate @end - -#endif - - -LOCALVAR CFBundleRef AppServBunRef; - -LOCALVAR bool DidApplicationServicesBun = false; - -LOCALFUNC bool HaveApplicationServicesBun(void) -{ - if (! DidApplicationServicesBun) { - AppServBunRef = CFBundleGetBundleWithIdentifier( - CFSTR("com.apple.ApplicationServices")); - DidApplicationServicesBun = true; - } - return (AppServBunRef != NULL); -} - -#if MayFullScreen - -LOCALVAR CFBundleRef HIToolboxBunRef; - -LOCALVAR bool DidHIToolboxBunRef = false; - -LOCALFUNC bool HaveHIToolboxBunRef(void) -{ - if (! DidHIToolboxBunRef) { - HIToolboxBunRef = CFBundleGetBundleWithIdentifier( - CFSTR("com.apple.HIToolbox")); - DidHIToolboxBunRef = true; - } - return (HIToolboxBunRef != NULL); -} - -#endif - - -#if MayFullScreen - -/* SetSystemUIModeProcPtr API always not available */ - -typedef UInt32 SystemUIMode; -typedef OptionBits SystemUIOptions; - -enum { - kUIModeNormal = 0, - kUIModeAllHidden = 3 -}; - -enum { - kUIOptionAutoShowMenuBar = 1 << 0, - kUIOptionDisableAppleMenu = 1 << 2, - kUIOptionDisableProcessSwitch = 1 << 3, - kUIOptionDisableForceQuit = 1 << 4, - kUIOptionDisableSessionTerminate = 1 << 5, - kUIOptionDisableHide = 1 << 6 -}; - -typedef OSStatus (*SetSystemUIModeProcPtr) - (SystemUIMode inMode, SystemUIOptions inOptions); -LOCALVAR SetSystemUIModeProcPtr SetSystemUIMode = NULL; -LOCALVAR bool DidSetSystemUIMode = false; - -LOCALFUNC bool HaveSetSystemUIMode(void) -{ - if (! DidSetSystemUIMode) { - if (HaveHIToolboxBunRef()) { - SetSystemUIMode = - (SetSystemUIModeProcPtr) - CFBundleGetFunctionPointerForName( - HIToolboxBunRef, CFSTR("SetSystemUIMode")); - } - DidSetSystemUIMode = true; - } - return (SetSystemUIMode != NULL); -} - -#endif - - -typedef Boolean (*CFURLCopyResourcePropertyForKeyProcPtr) ( - CFURLRef url, - CFStringRef key, - void *propertyValueTypeRefPtr, - CFErrorRef *error - ); -LOCALVAR CFURLCopyResourcePropertyForKeyProcPtr - CFURLCopyResourcePropertyForKey = NULL; -LOCALVAR bool DidCFURLCopyResourcePropertyForKey = false; - -LOCALFUNC bool HaveCFURLCopyResourcePropertyForKey(void) -{ - if (! DidCFURLCopyResourcePropertyForKey) { - if (HaveApplicationServicesBun()) { - CFURLCopyResourcePropertyForKey = - (CFURLCopyResourcePropertyForKeyProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, - CFSTR("CFURLCopyResourcePropertyForKey")); - } - DidCFURLCopyResourcePropertyForKey = true; - } - return (CFURLCopyResourcePropertyForKey != NULL); -} - - -LOCALVAR const CFStringRef *kCFURLIsAliasFileKey - = NULL; -LOCALVAR bool DidkCFURLIsAliasFileKey = false; - -LOCALFUNC bool HavekCFURLIsAliasFileKey(void) -{ - if (! DidkCFURLIsAliasFileKey) { - if (HaveApplicationServicesBun()) { - kCFURLIsAliasFileKey = - (const CFStringRef *) - CFBundleGetDataPointerForName( - AppServBunRef, CFSTR("kCFURLIsAliasFileKey")); - } - DidkCFURLIsAliasFileKey = true; - } - return (kCFURLIsAliasFileKey != NULL); -} - - -LOCALVAR const CFStringRef *kCFURLIsSymbolicLinkKey - = NULL; -LOCALVAR bool DidkCFURLIsSymbolicLinkKey = false; - -LOCALFUNC bool HavekCFURLIsSymbolicLinkKey(void) -{ - if (! DidkCFURLIsSymbolicLinkKey) { - if (HaveApplicationServicesBun()) { - kCFURLIsSymbolicLinkKey = - (const CFStringRef *) - CFBundleGetDataPointerForName( - AppServBunRef, CFSTR("kCFURLIsSymbolicLinkKey")); - } - DidkCFURLIsSymbolicLinkKey = true; - } - return (kCFURLIsSymbolicLinkKey != NULL); -} - - -typedef CFDataRef (*CFURLCreateBookmarkDataFromFileProcPtr) ( - CFAllocatorRef allocator, CFURLRef fileURL, CFErrorRef *errorRef); -LOCALVAR CFURLCreateBookmarkDataFromFileProcPtr - CFURLCreateBookmarkDataFromFile = NULL; -LOCALVAR bool DidCFURLCreateBookmarkDataFromFile = false; - -LOCALFUNC bool HaveCFURLCreateBookmarkDataFromFile(void) -{ - if (! DidCFURLCreateBookmarkDataFromFile) { - if (HaveApplicationServicesBun()) { - CFURLCreateBookmarkDataFromFile = - (CFURLCreateBookmarkDataFromFileProcPtr) - CFBundleGetFunctionPointerForName(AppServBunRef, - CFSTR("CFURLCreateBookmarkDataFromFile")); - } - DidCFURLCreateBookmarkDataFromFile = true; - } - return (CFURLCreateBookmarkDataFromFile != NULL); -} - - -typedef CFOptionFlags CFURLBookmarkResolutionOptions; - -typedef CFURLRef (*CFURLCreateByResolvingBookmarkDataProcPtr) ( - CFAllocatorRef allocator, CFDataRef bookmark, - CFURLBookmarkResolutionOptions options, CFURLRef relativeToURL, - CFArrayRef resourcePropertiesToInclude, - Boolean* isStale, CFErrorRef* error); -LOCALVAR CFURLCreateByResolvingBookmarkDataProcPtr - CFURLCreateByResolvingBookmarkData = NULL; -LOCALVAR bool DidCFURLCreateByResolvingBookmarkData = false; - -LOCALFUNC bool HaveCFURLCreateByResolvingBookmarkData(void) -{ - if (! DidCFURLCreateByResolvingBookmarkData) { - if (HaveApplicationServicesBun()) { - CFURLCreateByResolvingBookmarkData = - (CFURLCreateByResolvingBookmarkDataProcPtr) - CFBundleGetFunctionPointerForName(AppServBunRef, - CFSTR("CFURLCreateByResolvingBookmarkData")); - } - DidCFURLCreateByResolvingBookmarkData = true; - } - return (CFURLCreateByResolvingBookmarkData != NULL); -} - - -typedef boolean_t (*CGCursorIsVisibleProcPtr)(void); - -LOCALVAR CGCursorIsVisibleProcPtr CGCursorIsVisible = NULL; -LOCALVAR bool DidCGCursorIsVisible = false; - -LOCALFUNC bool HaveCGCursorIsVisible(void) -{ - if (! DidCGCursorIsVisible) { - if (HaveApplicationServicesBun()) { - CGCursorIsVisible = - (CGCursorIsVisibleProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGCursorIsVisible")); - } - DidCGCursorIsVisible = true; - } - return (CGCursorIsVisible != NULL); -} - - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memcpy((char *)destPtr, (char *)srcPtr, byteCount); -} - -/* --- control mode and internationalization --- */ - -#define NeedCell2UnicodeMap 1 - -#include "LANG/INTLCHAR.h" - -/* --- sending debugging info to file --- */ - -LOCALVAR NSString *myAppName = nil; -LOCALVAR NSString *DataPath = nil; - -#if dbglog_HAVE - -#define dbglog_ToStdErr 0 - -#if ! dbglog_ToStdErr -LOCALVAR FILE *dbglog_File = NULL; -#endif - -LOCALFUNC bool dbglog_open0(void) -{ -#if dbglog_ToStdErr - return true; -#else - NSString *myLogPath = [DataPath - stringByAppendingPathComponent: @"dbglog.txt"]; - const char *path = [myLogPath fileSystemRepresentation]; - - dbglog_File = fopen(path, "w"); - return (NULL != dbglog_File); -#endif -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ -#if dbglog_ToStdErr - (void) fwrite(s, 1, L, stderr); -#else - if (NULL != dbglog_File) { - (void) fwrite(s, 1, L, dbglog_File); - } -#endif -} - -LOCALPROC dbglog_close0(void) -{ -#if ! dbglog_ToStdErr - if (NULL != dbglog_File) { - fclose(dbglog_File); - dbglog_File = NULL; - } -#endif -} - -#endif - -/* --- information about the environment --- */ - -#define WantColorTransValid 1 - -#include "UI/COMOSGLU.h" - -#define WantKeyboard_RemapMac 1 - -#include "UTILS/PBUFSTDC.h" - -#include "UI/CONTROLM.h" - -/* --- text translation --- */ - -LOCALPROC UniCharStrFromSubstCStr(int *L, unichar *x, char *s) -{ - int i; - int L0; - uint8_t ps[ClStrMaxLength]; - - ClStrFromSubstCStr(&L0, ps, s); - - for (i = 0; i < L0; ++i) { - x[i] = Cell2UnicodeMap[ps[i]]; - } - - *L = L0; -} - -LOCALFUNC NSString * NSStringCreateFromSubstCStr(char *s) -{ - int L; - unichar x[ClStrMaxLength]; - - UniCharStrFromSubstCStr(&L, x, s); - - return [NSString stringWithCharacters:x length:L]; -} - -#if IncludeSonyNameNew -LOCALFUNC bool MacRomanFileNameToNSString(tPbuf i, - NSString **r) -{ - uint8_t * p; - void *Buffer = PbufDat[i]; - uint32_t L = PbufSize[i]; - - p = (uint8_t *)malloc(L /* + 1 */); - if (p != NULL) { - NSData *d; - uint8_t *p0 = (uint8_t *)Buffer; - uint8_t *p1 = (uint8_t *)p; - - if (L > 0) { - uint32_t j = L; - - do { - uint8_t x = *p0++; - if (x < 32) { - x = '-'; - } else if (x >= 128) { - } else { - switch (x) { - case '/': - case '<': - case '>': - case '|': - case ':': - x = '-'; - default: - break; - } - } - *p1++ = x; - } while (--j > 0); - - if ('.' == p[0]) { - p[0] = '-'; - } - } - -#if 0 - *p1 = 0; - *r = [NSString stringWithCString:(char *)p - encoding:NSMacOSRomanStringEncoding]; - /* only as of OS X 10.4 */ - free(p); -#endif - - d = [[NSData alloc] initWithBytesNoCopy:p length:L]; - - *r = [[[NSString alloc] - initWithData:d encoding:NSMacOSRomanStringEncoding] - autorelease]; - - [d release]; - - return true; - } - - return false; -} -#endif - -#if IncludeSonyGetName || IncludeHostTextClipExchange -LOCALFUNC MacErr_t NSStringToRomanPbuf(NSString *string, tPbuf *r) -{ - MacErr_t v = mnvm_miscErr; - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; -#if 0 - const char *s = [s0 - cStringUsingEncoding: NSMacOSRomanStringEncoding]; - uint32_t L = strlen(s); - /* only as of OS X 10.4 */ -#endif -#if 0 - NSData *d0 = [string dataUsingEncoding: NSMacOSRomanStringEncoding]; -#endif - NSData *d0 = [string dataUsingEncoding: NSMacOSRomanStringEncoding - allowLossyConversion: YES]; - const void *s = [d0 bytes]; - NSUInteger L = [d0 length]; - - if (NULL == s) { - v = mnvm_miscErr; - } else { - uint8_t * p = (uint8_t *)malloc(L); - - if (NULL == p) { - v = mnvm_miscErr; - } else { - /* memcpy((char *)p, s, L); */ - uint8_t *p0 = (uint8_t *)s; - uint8_t *p1 = (uint8_t *)p; - int i; - - for (i = L; --i >= 0; ) { - uint8_t v = *p0++; - if (10 == v) { - v = 13; - } - *p1++ = v; - } - - v = PbufNewFromPtr(p, L, r); - } - } - - [pool release]; - - return v; -} -#endif - -/* --- drives --- */ - -LOCALFUNC bool FindNamedChildPath(NSString *parentPath, - char *ChildName, NSString **childPath) -{ - bool v = false; - -#if 0 - NSString *ss = [NSString stringWithCString:s - encoding:NSASCIIStringEncoding]; - /* only as of OS X 10.4 */ -#endif -#if 0 - NSData *d = [NSData dataWithBytes: ChildName - length: strlen(ChildName)]; - NSString *ss = [[[NSString alloc] - initWithData:d encoding:NSASCIIStringEncoding] - autorelease]; -#endif - NSString *ss = NSStringCreateFromSubstCStr(ChildName); - if (nil != ss) { - NSString *r = [parentPath stringByAppendingPathComponent: ss]; - if (nil != r) { - *childPath = r; - v = true; - } - } - - return v; -} - -LOCALFUNC NSString *ResolveAlias(NSString *filePath, - Boolean *targetIsFolder) -{ - NSString *resolvedPath = nil; - CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, - (CFStringRef)filePath, kCFURLPOSIXPathStyle, NO); - - - if (url != NULL) { - if (HaveCFURLCopyResourcePropertyForKey() - && HavekCFURLIsAliasFileKey() - && HavekCFURLIsSymbolicLinkKey() - && HaveCFURLCreateBookmarkDataFromFile() - && HaveCFURLCreateByResolvingBookmarkData()) - { - BOOL isDir; - Boolean isStale; - CFBooleanRef is_alias_file = NULL; - CFBooleanRef is_symbolic_link = NULL; - CFDataRef bookmark = NULL; - CFURLRef resolvedurl = NULL; - - if (CFURLCopyResourcePropertyForKey(url, - *kCFURLIsAliasFileKey, &is_alias_file, NULL)) - if (CFBooleanGetValue(is_alias_file)) - if (CFURLCopyResourcePropertyForKey(url, - *kCFURLIsSymbolicLinkKey, &is_symbolic_link, NULL)) - if (! CFBooleanGetValue(is_symbolic_link)) - if (NULL != (bookmark = CFURLCreateBookmarkDataFromFile( - kCFAllocatorDefault, url, NULL))) - if (NULL != (resolvedurl = - CFURLCreateByResolvingBookmarkData( - kCFAllocatorDefault, - bookmark, - 0 /* CFURLBookmarkResolutionOptions options */, - NULL /* relativeToURL */, - NULL /* resourcePropertiesToInclude */, - &isStale, - NULL /* error */))) - if (nil != (resolvedPath = - (NSString *)CFURLCopyFileSystemPath( - resolvedurl, kCFURLPOSIXPathStyle))) - { - if ([[NSFileManager defaultManager] - fileExistsAtPath: resolvedPath isDirectory: &isDir]) - { - *targetIsFolder = isDir; - } else - { - *targetIsFolder = FALSE; - } - - [resolvedPath autorelease]; - } - - if (NULL != resolvedurl) { - CFRelease(resolvedurl); - } - if (NULL != bookmark) { - CFRelease(bookmark); - } - if (NULL != is_alias_file) { - CFRelease(is_alias_file); - } - if (NULL != is_symbolic_link) { - CFRelease(is_symbolic_link); - } - } else { - FSRef fsRef; - Boolean wasAliased; - - if (CFURLGetFSRef(url, &fsRef)) { - /* - FSResolveAliasFile deprecated in 10.8 - */ - - if ((FSResolveAliasFile(&fsRef, - TRUE /*resolveAliasChains*/, - targetIsFolder, &wasAliased) == noErr) - && wasAliased) - { - CFURLRef resolvedurl = - CFURLCreateFromFSRef(kCFAllocatorDefault, - &fsRef); - if (resolvedurl != NULL) { - resolvedPath = - (NSString *)CFURLCopyFileSystemPath( - resolvedurl, kCFURLPOSIXPathStyle); - [resolvedPath autorelease]; - CFRelease(resolvedurl); - } - } - } - } - - CFRelease(url); - } - - return resolvedPath; -} - -LOCALFUNC bool FindNamedChildDirPath(NSString *parentPath, - char *ChildName, NSString **childPath) -{ - NSString *r; - BOOL isDir; - Boolean isDirectory; - bool v = false; - - if (FindNamedChildPath(parentPath, ChildName, &r)) - if ([[NSFileManager defaultManager] - fileExistsAtPath:r isDirectory: &isDir]) - { - if (isDir) { - *childPath = r; - v = true; - } else { - NSString *RslvPath = ResolveAlias(r, &isDirectory); - if (nil != RslvPath) { - if (isDirectory) { - *childPath = RslvPath; - v = true; - } - } - } - } - - return v; -} - -LOCALFUNC bool FindNamedChildFilePath(NSString *parentPath, - char *ChildName, NSString **childPath) -{ - NSString *r; - BOOL isDir; - Boolean isDirectory; - bool v = false; - - if (FindNamedChildPath(parentPath, ChildName, &r)) - if ([[NSFileManager defaultManager] - fileExistsAtPath:r isDirectory: &isDir]) - { - if (! isDir) { - NSString *RslvPath = ResolveAlias(r, &isDirectory); - if (nil != RslvPath) { - if (! isDirectory) { - *childPath = RslvPath; - v = true; - } - } else { - *childPath = r; - v = true; - } - } - } - - return v; -} - - -#define NotAfileRef NULL - -LOCALVAR FILE *Drives[NumDrives]; /* open disk image files */ -#if IncludeSonyGetName || IncludeSonyNew -LOCALVAR NSString *DriveNames[NumDrives]; -#endif - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; -#if IncludeSonyGetName || IncludeSonyNew - DriveNames[i] = nil; -#endif - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - uint32_t NewSony_Count = 0; - - if (0 == fseek(refnum, Sony_Start, SEEK_SET)) { - if (IsWrite) { - NewSony_Count = fwrite(Buffer, 1, Sony_Count, refnum); - } else { - NewSony_Count = fread(Buffer, 1, Sony_Count, refnum); - } - - if (NewSony_Count == Sony_Count) { - err = mnvm_noErr; - } - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = NewSony_Count; - } - - return err; /*& figure out what really to return &*/ -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - long v; - - if (0 == fseek(refnum, 0, SEEK_END)) { - v = ftell(refnum); - if (v >= 0) { - *Sony_Count = v; - err = mnvm_noErr; - } - } - - return err; /*& figure out what really to return &*/ -} - -#ifndef HaveAdvisoryLocks -#define HaveAdvisoryLocks 1 -#endif - -/* - What is the difference between fcntl(fd, F_SETLK ... - and flock(fd ... ? -*/ - -#if HaveAdvisoryLocks -LOCALFUNC bool LockFile(FILE *refnum) -{ - bool IsOk = false; - -#if 0 - struct flock fl; - int fd = fileno(refnum); - - fl.l_start = 0; /* starting offset */ - fl.l_len = 0; /* len = 0 means until end of file */ - /* fl.pid_t l_pid; */ /* lock owner, don't need to set */ - fl.l_type = F_WRLCK; /* lock type: read/write, etc. */ - fl.l_whence = SEEK_SET; /* type of l_start */ - if (-1 == fcntl(fd, F_SETLK, &fl)) { - MacMsg(kStrImageInUseTitle, kStrImageInUseMessage, - false); - } else { - IsOk = true; - } -#else - int fd = fileno(refnum); - - if (-1 == flock(fd, LOCK_EX | LOCK_NB)) { - if (EWOULDBLOCK == errno) { - /* already locked */ - MacMsg(kStrImageInUseTitle, kStrImageInUseMessage, - false); - } else - { - /* - Failed for other reasons, such as unsupported - for this volume. - Don't prevent opening. - */ - IsOk = true; - } - } else { - IsOk = true; - } -#endif - - return IsOk; -} -#endif - -#if HaveAdvisoryLocks -LOCALPROC UnlockFile(FILE *refnum) -{ -#if 0 - struct flock fl; - int fd = fileno(refnum); - - fl.l_start = 0; /* starting offset */ - fl.l_len = 0; /* len = 0 means until end of file */ - /* fl.pid_t l_pid; */ /* lock owner, don't need to set */ - fl.l_type = F_UNLCK; /* lock type: read/write, etc. */ - fl.l_whence = SEEK_SET; /* type of l_start */ - if (-1 == fcntl(fd, F_SETLK, &fl)) { - /* an error occurred */ - } -#else - int fd = fileno(refnum); - - if (-1 == flock(fd, LOCK_UN)) { - } -#endif -} -#endif - -LOCALFUNC MacErr_t vSonyEject0(tDrive Drive_No, bool deleteit) -{ - FILE *refnum = Drives[Drive_No]; - - DiskEjectedNotify(Drive_No); - -#if HaveAdvisoryLocks - UnlockFile(refnum); -#endif - - fclose(refnum); - Drives[Drive_No] = NotAfileRef; /* not really needed */ - -#if IncludeSonyGetName || IncludeSonyNew - { - NSString *filePath = DriveNames[Drive_No]; - if (NULL != filePath) { - if (deleteit) { - NSAutoreleasePool *pool = - [[NSAutoreleasePool alloc] init]; - const char *s = [filePath fileSystemRepresentation]; - remove(s); - [pool release]; - } - [filePath release]; - DriveNames[Drive_No] = NULL; /* not really needed */ - } - } -#endif - - return mnvm_noErr; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, false); -} - -#if IncludeSonyNew -GLOBALOSGLUFUNC MacErr_t vSonyEjectDelete(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, true); -} -#endif - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -#if IncludeSonyGetName -GLOBALOSGLUFUNC MacErr_t vSonyGetName(tDrive Drive_No, tPbuf *r) -{ - MacErr_t v = mnvm_miscErr; - NSString *filePath = DriveNames[Drive_No]; - if (NULL != filePath) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSString *s0 = [filePath lastPathComponent]; - v = NSStringToRomanPbuf(s0, r); - - [pool release]; - } - - return v; -} -#endif - -LOCALFUNC bool Sony_Insert0(FILE *refnum, bool locked, - NSString *filePath) -{ - tDrive Drive_No; - bool IsOk = false; - - if (! FirstFreeDisk(&Drive_No)) { - MacMsg(kStrTooManyImagesTitle, kStrTooManyImagesMessage, - false); - } else { - /* printf("Sony_Insert0 %d\n", (int)Drive_No); */ - -#if HaveAdvisoryLocks - if (locked || LockFile(refnum)) -#endif - { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); - -#if IncludeSonyGetName || IncludeSonyNew - DriveNames[Drive_No] = [filePath retain]; -#endif - - IsOk = true; - } - } - - if (! IsOk) { - fclose(refnum); - } - - return IsOk; -} - -LOCALFUNC bool Sony_Insert1(NSString *filePath, bool silentfail) -{ - /* const char *drivepath = [filePath UTF8String]; */ - const char *drivepath = [filePath fileSystemRepresentation]; - bool locked = false; - /* printf("Sony_Insert1 %s\n", drivepath); */ - FILE *refnum = fopen(drivepath, "rb+"); - if (NULL == refnum) { - locked = true; - refnum = fopen(drivepath, "rb"); - } - if (NULL == refnum) { - if (! silentfail) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } else { - return Sony_Insert0(refnum, locked, filePath); - } - return false; -} - -LOCALFUNC bool Sony_Insert2(char *s) -{ - NSString *sPath; - - if (! FindNamedChildFilePath(DataPath, s, &sPath)) { - return false; - } else { - return Sony_Insert1(sPath, true); - } -} - -LOCALFUNC MacErr_t LoadMacRomPath(NSString *RomPath) -{ - FILE *ROM_File; - int File_Size; - MacErr_t err = mnvm_fnfErr; - const char *path = [RomPath fileSystemRepresentation]; - - ROM_File = fopen(path, "rb"); - if (NULL != ROM_File) { - File_Size = fread(ROM, 1, kROM_Size, ROM_File); - if (kROM_Size != File_Size) { - if (feof(ROM_File)) { - MacMsgOverride(kStrShortROMTitle, - kStrShortROMMessage); - err = mnvm_eofErr; - } else { - MacMsgOverride(kStrNoReadROMTitle, - kStrNoReadROMMessage); - err = mnvm_miscErr; - } - } else { - err = ROM_IsValid(); - } - fclose(ROM_File); - } - - return err; -} - -LOCALFUNC bool Sony_Insert1a(NSString *filePath) -{ - bool v; - - if (! ROM_loaded) { - v = (mnvm_noErr == LoadMacRomPath(filePath)); - } else { - v = Sony_Insert1(filePath, false); - } - - return v; -} - -LOCALPROC Sony_ResolveInsert(NSString *filePath) -{ - Boolean isDirectory; - NSString *RslvPath = ResolveAlias(filePath, &isDirectory); - if (nil != RslvPath) { - if (! isDirectory) { - (void) Sony_Insert1a(RslvPath); - } - } else { - (void) Sony_Insert1a(filePath); - } -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - bool v; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - v = false; - } else { - char s[] = "disk?.dsk"; - - s[4] = '0' + i; - - v = Sony_Insert2(s); - } - - return v; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - if (! AnyDiskInserted()) { - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - } - - return true; -} - -#if IncludeSonyNew -LOCALFUNC bool WriteZero(FILE *refnum, uint32_t L) -{ -#define ZeroBufferSize 2048 - uint32_t i; - uint8_t buffer[ZeroBufferSize]; - - memset(&buffer, 0, ZeroBufferSize); - - while (L > 0) { - i = (L > ZeroBufferSize) ? ZeroBufferSize : L; - if (fwrite(buffer, 1, i, refnum) != i) { - return false; - } - L -= i; - } - return true; -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDisk0(uint32_t L, NSString *sPath) -{ - bool IsOk = false; - const char *drivepath = [sPath fileSystemRepresentation]; - FILE *refnum = fopen(drivepath, "wb+"); - if (NULL == refnum) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } else { - if (WriteZero(refnum, L)) { - IsOk = Sony_Insert0(refnum, false, sPath); - refnum = NULL; - } - if (refnum != NULL) { - fclose(refnum); - } - if (! IsOk) { - (void) remove(drivepath); - } - } -} -#endif - -/* --- ROM --- */ - -LOCALFUNC MacErr_t LoadMacRomFrom(NSString *parentPath) -{ - NSString *RomPath; - MacErr_t err = mnvm_fnfErr; - - if (FindNamedChildFilePath(parentPath, RomFileName, &RomPath)) { - err = LoadMacRomPath(RomPath); - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromAppDir(void) -{ - return LoadMacRomFrom(DataPath); -} - -LOCALFUNC MacErr_t LoadMacRomFromPrefDir(void) -{ - NSString *PrefsPath; - NSString *GryphelPath; - NSString *RomsPath; - MacErr_t err = mnvm_fnfErr; - NSArray *paths = NSSearchPathForDirectoriesInDomains( - NSLibraryDirectory, NSUserDomainMask, YES); - if ((nil != paths) && ([paths count] > 0)) - { - NSString *LibPath = [paths objectAtIndex:0]; - if (FindNamedChildDirPath(LibPath, "Preferences", &PrefsPath)) - if (FindNamedChildDirPath(PrefsPath, "Gryphel", &GryphelPath)) - if (FindNamedChildDirPath(GryphelPath, "mnvm_rom", &RomsPath)) - { - err = LoadMacRomFrom(RomsPath); - } - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromGlobalDir(void) -{ - NSString *GryphelPath; - NSString *RomsPath; - MacErr_t err = mnvm_fnfErr; - NSArray *paths = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, NSLocalDomainMask, NO); - if ((nil != paths) && ([paths count] > 0)) - { - NSString *LibPath = [paths objectAtIndex:0]; - if (FindNamedChildDirPath(LibPath, "Gryphel", &GryphelPath)) - if (FindNamedChildDirPath(GryphelPath, "mnvm_rom", &RomsPath)) - { - err = LoadMacRomFrom(RomsPath); - } - } - - return err; -} - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if (mnvm_fnfErr == (err = LoadMacRomFromAppDir())) - if (mnvm_fnfErr == (err = LoadMacRomFromPrefDir())) - if (mnvm_fnfErr == (err = LoadMacRomFromGlobalDir())) - { - } - - return true; /* keep launching Mini vMac, regardless */ -} - - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEexport(tPbuf i) -{ - void *Buffer; - uint32_t L; - MacErr_t err = mnvm_miscErr; - - PbufKillToPtr(&Buffer, &L, i); - - if (L > 0) { - int j; - uint8_t *p = (uint8_t *)Buffer; - - for (j = L; --j >= 0; ) { - uint8_t v = *p; - if (13 == v) { - *p = 10; - } - ++p; - } - } - - { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSData *d = [[NSData alloc] - initWithBytesNoCopy: Buffer length: L]; - /* NSData *d = [NSData dataWithBytes: Buffer length: L]; */ - NSString *ss = [[[NSString alloc] - initWithData:d encoding:NSMacOSRomanStringEncoding] - autorelease]; - NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; - NSArray *newTypes = - [NSArray arrayWithObject: NSStringPboardType]; - - (void) [pasteboard declareTypes: newTypes owner: nil]; - if ([pasteboard setString: ss forType: NSStringPboardType]) { - err = mnvm_noErr; - } - - [d release]; - - [pool release]; - } - - return err; -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEimport(tPbuf *r) -{ - MacErr_t err = mnvm_miscErr; - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; - NSArray *supportedTypes = [NSArray - arrayWithObject: NSStringPboardType]; - NSString *available = [pasteboard - availableTypeFromArray: supportedTypes]; - - if (nil != available) { - NSString *string = [pasteboard - stringForType: NSStringPboardType]; - if (nil != string) { - err = NSStringToRomanPbuf(string, r); - } - } - - [pool release]; - - return err; -} -#endif - - -#if EmLocalTalk - -#include "UTIL/BPFILTER.h" - -#endif - - -#define UseCGContextDrawImage 0 - -LOCALVAR NSWindow *Window = nil; -LOCALVAR NSView *NSview = nil; -#if UseCGContextDrawImage -LOCALVAR NSGraphicsContext *NSgfxContext = nil; -LOCALVAR CGContextRef CGcontext = nil; -LOCALVAR void *Pixels = NULL; -LOCALVAR uint16_t Pitch; -LOCALVAR uint8_t BytesPerPixel; -#endif - -LOCALVAR NSOpenGLContext *NSOpnGLCntxt = nil; -LOCALVAR short GLhOffset; -LOCALVAR short GLvOffset; - /* OpenGL coordinates of upper left point of drawing area */ - - -LOCALPROC HideCursor(void) -{ - [NSCursor hide]; -} - -LOCALPROC ShowCursor(void) -{ - if (nil != Window) { - [Window invalidateCursorRectsForView: - NSview]; - } -#if 0 - [cursor->nscursor performSelectorOnMainThread: @selector(set) - withObject: nil waitUntilDone: NO]; -#endif -#if 0 - [[NSCursor arrowCursor] set]; -#endif - [NSCursor unhide]; -} - -#if EnableMoveMouse -LOCALFUNC CGPoint QZ_PrivateSDLToCG(NSPoint *p) -{ - CGPoint cgp; - - *p = [NSview convertPoint: *p toView: nil]; - p->y = [NSview frame].size.height - p->y; - *p = [Window convertBaseToScreen: *p]; - - cgp.x = p->x; - cgp.y = CGDisplayPixelsHigh(kCGDirectMainDisplay) - - p->y; - - return cgp; -} -#endif - -LOCALPROC QZ_GetMouseLocation(NSPoint *p) -{ - /* incorrect while window is being dragged */ - - *p = [NSEvent mouseLocation]; /* global coordinates */ - if (nil != Window) { - *p = [Window convertScreenToBase: *p]; - } - *p = [NSview convertPoint: *p fromView: nil]; - p->y = [NSview frame].size.height - p->y; -} - -/* --- keyboard --- */ - -LOCALVAR NSUInteger CurrentMods = 0; - -/* - Apple documentation says: - "The lower 16 bits of the modifier flags are reserved - for device-dependent bits." - - observed to be: -*/ -#define _NSLShiftKeyMask 0x0002 -#define _NSRShiftKeyMask 0x0004 -#define _NSLControlKeyMask 0x0001 -#define _NSRControlKeyMask 0x2000 -#define _NSLCommandKeyMask 0x0008 -#define _NSRCommandKeyMask 0x0010 -#define _NSLOptionKeyMask 0x0020 -#define _NSROptionKeyMask 0x0040 -/* - Avoid using the above unless it is - really needed. -*/ - -LOCALPROC UpdateKeyboardModifiers(NSUInteger newMods) -{ - NSUInteger changeMask = CurrentMods ^ newMods; - - if (0 != changeMask) { - if (0 != (changeMask & NSAlphaShiftKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_CapsLock, - 0 != (newMods & NSAlphaShiftKeyMask)); - } - -#if MKC_formac_RShift == MKC_formac_Shift - if (0 != (changeMask & NSShiftKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Shift, - 0 != (newMods & NSShiftKeyMask)); - } -#else - if (0 != (changeMask & _NSLShiftKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Shift, - 0 != (newMods & _NSLShiftKeyMask)); - } - if (0 != (changeMask & _NSRShiftKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_RShift, - 0 != (newMods & _NSRShiftKeyMask)); - } -#endif - -#if MKC_formac_RControl == MKC_formac_Control - if (0 != (changeMask & NSControlKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Control, - 0 != (newMods & NSControlKeyMask)); - } -#else - if (0 != (changeMask & _NSLControlKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Control, - 0 != (newMods & _NSLControlKeyMask)); - } - if (0 != (changeMask & _NSRControlKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_RControl, - 0 != (newMods & _NSRControlKeyMask)); - } -#endif - -#if MKC_formac_RCommand == MKC_formac_Command - if (0 != (changeMask & NSCommandKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Command, - 0 != (newMods & NSCommandKeyMask)); - } -#else - if (0 != (changeMask & _NSLCommandKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Command, - 0 != (newMods & _NSLCommandKeyMask)); - } - if (0 != (changeMask & _NSRCommandKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_RCommand, - 0 != (newMods & _NSRCommandKeyMask)); - } -#endif - -#if MKC_formac_ROption == MKC_formac_Option - if (0 != (changeMask & NSAlternateKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Option, - 0 != (newMods & NSAlternateKeyMask)); - } -#else - if (0 != (changeMask & _NSLOptionKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_Option, - 0 != (newMods & _NSLOptionKeyMask)); - } - if (0 != (changeMask & _NSROptionKeyMask)) { - Keyboard_UpdateKeyMap2(MKC_formac_ROption, - 0 != (newMods & _NSROptionKeyMask)); - } -#endif - - CurrentMods = newMods; - } -} - -/* --- mouse --- */ - -/* cursor hiding */ - -LOCALVAR bool WantCursorHidden = false; - -#if MayFullScreen -LOCALVAR short hOffset; - /* number of pixels to left of drawing area in window */ -LOCALVAR short vOffset; - /* number of pixels above drawing area in window */ -#endif - -#if MayFullScreen -LOCALVAR bool GrabMachine = false; -#endif - -#if 1 -LOCALVAR bool UseFullScreen = (0 != WantInitFullScreen); -#endif - -LOCALVAR bool UseMagnify = (0 != WantInitMagnify); -LOCALVAR bool gBackgroundFlag = false; -LOCALVAR bool CurSpeedStopped = true; - -#define MaxScale WindowScale - -LOCALVAR bool HaveCursorHidden = false; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - ShowCursor(); - } -} - -/* cursor moving */ - -#if EnableMoveMouse -LOCALFUNC bool MoveMouse(int16_t h, int16_t v) -{ - NSPoint p; - CGPoint cgp; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h -= ViewHStart; - v -= ViewVStart; - } -#endif - - if (UseMagnify) { - h *= WindowScale; - v *= WindowScale; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h += hOffset; - v += vOffset; - } -#endif - - p = NSMakePoint(h, v); - cgp = QZ_PrivateSDLToCG(&p); - - /* - this is the magic call that fixes cursor "freezing" - after warp - */ - CGAssociateMouseAndMouseCursorPosition(0); - CGWarpMouseCursorPosition(cgp); - CGAssociateMouseAndMouseCursorPosition(1); - -#if 0 - if (noErr != CGSetLocalEventsSuppressionInterval(0.0)) { - /* don't use MacMsg which can call MoveMouse */ - } - if (noErr != CGWarpMouseCursorPosition(cgp)) { - /* don't use MacMsg which can call MoveMouse */ - } -#endif - - return true; -} -#endif - -#if EnableFSMouseMotion -LOCALPROC AdjustMouseMotionGrab(void) -{ -#if MayFullScreen - if (GrabMachine) { - /* - if magnification changes, need to reset, - even if HaveMouseMotion already true - */ - if (MoveMouse(ViewHStart + (ViewHSize / 2), - ViewVStart + (ViewVSize / 2))) - { - SavedMouseH = ViewHStart + (ViewHSize / 2); - SavedMouseV = ViewVStart + (ViewVSize / 2); - HaveMouseMotion = true; - } - } else -#endif - { - if (HaveMouseMotion) { - (void) MoveMouse(CurMouseH, CurMouseV); - HaveMouseMotion = false; - } - } -} -#endif - -#if EnableFSMouseMotion -LOCALPROC MouseConstrain(void) -{ - int16_t shiftdh; - int16_t shiftdv; - - if (SavedMouseH < ViewHStart + (ViewHSize / 4)) { - shiftdh = ViewHSize / 2; - } else if (SavedMouseH > ViewHStart + ViewHSize - (ViewHSize / 4)) { - shiftdh = - ViewHSize / 2; - } else { - shiftdh = 0; - } - if (SavedMouseV < ViewVStart + (ViewVSize / 4)) { - shiftdv = ViewVSize / 2; - } else if (SavedMouseV > ViewVStart + ViewVSize - (ViewVSize / 4)) { - shiftdv = - ViewVSize / 2; - } else { - shiftdv = 0; - } - if ((shiftdh != 0) || (shiftdv != 0)) { - SavedMouseH += shiftdh; - SavedMouseV += shiftdv; - if (! MoveMouse(SavedMouseH, SavedMouseV)) { - HaveMouseMotion = false; - } - } -} -#endif - -/* cursor state */ - -LOCALPROC MousePositionNotify(int NewMousePosh, int NewMousePosv) -{ - bool ShouldHaveCursorHidden = true; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePosh -= hOffset; - NewMousePosv -= vOffset; - } -#endif - - if (UseMagnify) { - NewMousePosh /= WindowScale; - NewMousePosv /= WindowScale; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePosh += ViewHStart; - NewMousePosv += ViewVStart; - } -#endif - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MousePositionSetDelta(NewMousePosh - SavedMouseH, - NewMousePosv - SavedMouseV); - SavedMouseH = NewMousePosh; - SavedMouseV = NewMousePosv; - } else -#endif - { - if (NewMousePosh < 0) { - NewMousePosh = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosh >= vMacScreenWidth) { - NewMousePosh = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePosv < 0) { - NewMousePosv = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosv >= vMacScreenHeight) { - NewMousePosv = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ShouldHaveCursorHidden = true; - } -#endif - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePosh, NewMousePosv); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC CheckMouseState(void) -{ - /* - incorrect while window is being dragged - so only call when needed. - */ - NSPoint p; - - QZ_GetMouseLocation(&p); - MousePositionNotify((int) p.x, (int) p.y); -} - -LOCALVAR bool gTrueBackgroundFlag = false; - - -LOCALVAR uint8_t * ScalingBuff = nullpr; - -LOCALVAR uint8_t * CLUT_final; - -#define CLUT_finalsz1 (256 * 8) - -#define CLUT_finalClrSz (256 << (5 - vMacScreenDepth)) - -#define CLUT_finalsz ((CLUT_finalClrSz > CLUT_finalsz1) \ - ? CLUT_finalClrSz : CLUT_finalsz1) - - -#define ScrnMapr_DoMap UpdateBWLuminanceCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 3 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - - -#define ScrnMapr_DoMap UpdateMappedColorCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnTrns_DoTrans UpdateTransColorCopy -#define ScrnTrns_Src GetCurDrawBuff() -#define ScrnTrns_Dst ScalingBuff -#define ScrnTrns_SrcDepth vMacScreenDepth -#define ScrnTrns_DstDepth 5 -#define ScrnTrns_DstZLo 1 - -#include "HW/SCREEN/SCRNTRNS.h" - -LOCALPROC UpdateLuminanceCopy(int16_t top, int16_t left, - int16_t bottom, int16_t right) -{ - int i; - - if (vMacScreenDepth > 0 && UseColorMode) { - if (vMacScreenDepth < 4) { - if (! ColorTransValid) { - int j; - int k; - uint32_t * p4; - - p4 = (uint32_t *)CLUT_final; - for (i = 0; i < 256; ++i) { - for (k = 1 << (3 - vMacScreenDepth); --k >= 0; ) { - j = (i >> (k << vMacScreenDepth)) & (CLUT_size - 1); - *p4++ = (((long)CLUT_reds[j] & 0xFF00) << 16) - | (((long)CLUT_greens[j] & 0xFF00) << 8) - | ((long)CLUT_blues[j] & 0xFF00); - } - } - ColorTransValid = true; - } - UpdateMappedColorCopy(top, left, bottom, right); - } else { - UpdateTransColorCopy(top, left, bottom, right); - } - - } else { - if (! ColorTransValid) { - int k; - uint8_t * p4 = (uint8_t *)CLUT_final; - - for (i = 0; i < 256; ++i) { - for (k = 8; --k >= 0; ) { - *p4++ = ((i >> k) & 0x01) - 1; - } - } - ColorTransValid = true; - } - - UpdateBWLuminanceCopy(top, left, bottom, right); - } -} - -LOCALPROC DrawWithOpenGL(uint16_t top, uint16_t left, uint16_t bottom, uint16_t right) -{ - if (nil == NSOpnGLCntxt) { - /* oops */ - } else { - int16_t top2; - int16_t left2; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - if (top < ViewVStart) { - top = ViewVStart; - } - if (left < ViewHStart) { - left = ViewHStart; - } - if (bottom > ViewVStart + ViewVSize) { - bottom = ViewVStart + ViewVSize; - } - if (right > ViewHStart + ViewHSize) { - right = ViewHStart + ViewHSize; - } - - if ((top >= bottom) || (left >= right)) { - goto label_exit; - } - } -#endif - - top2 = top; - left2 = left; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - left2 -= ViewHStart; - top2 -= ViewVStart; - } -#endif - - if (UseMagnify) { - top2 *= WindowScale; - left2 *= WindowScale; - } - - [NSOpnGLCntxt makeCurrentContext]; - - UpdateLuminanceCopy(top, left, bottom, right); - glRasterPos2i(GLhOffset + left2, GLvOffset - top2); - if (vMacScreenDepth > 0 && UseColorMode) { - glDrawPixels(right - left, - bottom - top, - GL_RGBA, - GL_UNSIGNED_INT_8_8_8_8, - ScalingBuff + (left + top * vMacScreenWidth) * 4 - ); - } else { - glDrawPixels(right - left, - bottom - top, - GL_LUMINANCE, - GL_UNSIGNED_BYTE, - ScalingBuff + (left + top * vMacScreenWidth) - ); - } - -#if 0 /* a very quick and dirty check of where drawing */ - glDrawPixels(right - left, - 1, - GL_RED, - GL_UNSIGNED_BYTE, - ScalingBuff + (left + top * vMacScreenWidth) - ); - - glDrawPixels(1, - bottom - top, - GL_RED, - GL_UNSIGNED_BYTE, - ScalingBuff + (left + top * vMacScreenWidth) - ); -#endif - - glFlush(); - } - -#if MayFullScreen -label_exit: - ; -#endif -} - -#if UseCGContextDrawImage -LOCALPROC SDL_UpdateRect(int32_t x, int32_t y, uint32_t w, uint32_t h) -{ - if ([Window isMiniaturized]) { - - /* Do nothing if miniaturized */ - - } else { - NSGraphicsContext *ctx = [NSGraphicsContext currentContext]; - if (ctx != NSgfxContext) { - /* uhoh, you might be rendering from another thread... */ - [NSGraphicsContext - setCurrentContext: NSgfxContext]; - ctx = NSgfxContext; - } - CGContextRef cgc = (CGContextRef) [ctx graphicsPort]; - CGContextFlush(CGcontext); - CGImageRef image = CGBitmapContextCreateImage( - CGcontext); - CGRect rectangle = CGRectMake(0, 0, - [NSview frame].size.width, - [NSview frame].size.height); - - CGContextDrawImage(cgc, rectangle, image); - CGImageRelease(image); - CGContextFlush(cgc); - } -} -#endif - -/* --- time, date, location --- */ - -#define dbglog_TimeStuff (0 && dbglog_HAVE) - -LOCALVAR uint32_t TrueEmulatedTime = 0; - -LOCALVAR NSTimeInterval LatestTime; -LOCALVAR NSTimeInterval NextTickChangeTime; - -#define TickDuration (1.0 / 60.14742) - -LOCALVAR uint32_t NewMacDateInSeconds; - -LOCALVAR bool EmulationWasInterrupted = false; - -LOCALPROC UpdateTrueEmulatedTime(void) -{ - NSTimeInterval TimeDiff; - - LatestTime = [NSDate timeIntervalSinceReferenceDate]; - TimeDiff = LatestTime - NextTickChangeTime; - - if (TimeDiff >= 0.0) { - if (TimeDiff > 16 * TickDuration) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - NextTickChangeTime = LatestTime + TickDuration; - - EmulationWasInterrupted = true; -#if dbglog_TimeStuff - dbglog_writelnNum("emulation interrupted", - TrueEmulatedTime); -#endif - } else { - do { -#if 0 && dbglog_TimeStuff - dbglog_writeln("got next tick"); -#endif - ++TrueEmulatedTime; - TimeDiff -= TickDuration; - NextTickChangeTime += TickDuration; - } while (TimeDiff >= 0.0); - } - } else if (TimeDiff < (-16 * TickDuration)) { - /* clock set back, reset */ -#if dbglog_TimeStuff - dbglog_writeln("clock set back"); -#endif - - NextTickChangeTime = LatestTime + TickDuration; - } -} - - -LOCALVAR uint32_t DateDelta; - -LOCALFUNC bool CheckDateTime(void) -{ - NewMacDateInSeconds = ((uint32_t)LatestTime) + DateDelta; - if (CurMacDateInSeconds != NewMacDateInSeconds) { - CurMacDateInSeconds = NewMacDateInSeconds; - return true; - } else { - return false; - } -} - -LOCALPROC StartUpTimeAdjust(void) -{ - LatestTime = [NSDate timeIntervalSinceReferenceDate]; - NextTickChangeTime = LatestTime; -} - -LOCALFUNC bool InitLocationDat(void) -{ - NSTimeZone *Zone = [NSTimeZone localTimeZone]; - uint32_t TzOffSet = (uint32_t)[Zone secondsFromGMT]; -#if AutoTimeZone - BOOL isdst = [Zone isDaylightSavingTime]; -#endif - - DateDelta = TzOffSet - 1233815296; - LatestTime = [NSDate timeIntervalSinceReferenceDate]; - NewMacDateInSeconds = ((uint32_t)LatestTime) + DateDelta; - CurMacDateInSeconds = NewMacDateInSeconds; -#if AutoTimeZone - CurMacDelta = (TzOffSet & 0x00FFFFFF) - | ((isdst ? 0x80 : 0) << 24); -#endif - - return true; -} - -/* --- sound --- */ - -#if SoundEnabled - -#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */ -#define kSoundBuffers (1 << kLn2SoundBuffers) -#define kSoundBuffMask (kSoundBuffers - 1) - -#define DesiredMinFilledSoundBuffs 3 - /* - if too big then sound lags behind emulation. - if too small then sound will have pauses. - */ - -#define kLnOneBuffLen 9 -#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen) -#define kOneBuffLen (1UL << kLnOneBuffLen) -#define kAllBuffLen (1UL << kLnAllBuffLen) -#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3) -#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3) -#define kOneBuffSz (1UL << kLnOneBuffSz) -#define kAllBuffSz (1UL << kLnAllBuffSz) -#define kOneBuffMask (kOneBuffLen - 1) -#define kAllBuffMask (kAllBuffLen - 1) -#define dbhBufferSize (kAllBuffSz + kOneBuffSz) - -#define dbglog_SoundStuff (0 && dbglog_HAVE) -#define dbglog_SoundBuffStats (0 && dbglog_HAVE) - -LOCALVAR tpSoundSamp TheSoundBuffer = nullpr; -static volatile uint16_t ThePlayOffset; -static volatile uint16_t TheFillOffset; -static volatile uint16_t MinFilledSoundBuffs; -#if dbglog_SoundBuffStats -LOCALVAR uint16_t MaxFilledSoundBuffs; -#endif -LOCALVAR uint16_t TheWriteOffset; - -LOCALPROC Sound_Start0(void) -{ - /* Reset variables */ - ThePlayOffset = 0; - TheFillOffset = 0; - TheWriteOffset = 0; - MinFilledSoundBuffs = kSoundBuffers + 1; -#if dbglog_SoundBuffStats - MaxFilledSoundBuffs = 0; -#endif -} - -GLOBALOSGLUFUNC tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL) -{ - uint16_t ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset); - uint16_t WriteBuffContig = - kOneBuffLen - (TheWriteOffset & kOneBuffMask); - - if (WriteBuffContig < n) { - n = WriteBuffContig; - } - if (ToFillLen < n) { - /* overwrite previous buffer */ -#if dbglog_SoundStuff - dbglog_writeln("sound buffer over flow"); -#endif - TheWriteOffset -= kOneBuffLen; - } - - *actL = n; - return TheSoundBuffer + (TheWriteOffset & kAllBuffMask); -} - -#if 4 == kLn2SoundSampSz -LOCALPROC ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -LOCALPROC Sound_WroteABlock(void) -{ -#if (4 == kLn2SoundSampSz) - uint16_t PrevWriteOffset = TheWriteOffset - kOneBuffLen; - tpSoundSamp p = TheSoundBuffer + (PrevWriteOffset & kAllBuffMask); -#endif - -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_WroteABlock"); -#endif - - ConvertSoundBlockToNative(p); - - TheFillOffset = TheWriteOffset; - -#if dbglog_SoundBuffStats - { - uint16_t ToPlayLen = TheFillOffset - - ThePlayOffset; - uint16_t ToPlayBuffs = ToPlayLen >> kLnOneBuffLen; - - if (ToPlayBuffs > MaxFilledSoundBuffs) { - MaxFilledSoundBuffs = ToPlayBuffs; - } - } -#endif -} - -LOCALFUNC bool Sound_EndWrite0(uint16_t actL) -{ - bool v; - - TheWriteOffset += actL; - - if (0 != (TheWriteOffset & kOneBuffMask)) { - v = false; - } else { - /* just finished a block */ - - Sound_WroteABlock(); - - v = true; - } - - return v; -} - -LOCALPROC Sound_SecondNotify0(void) -{ - if (MinFilledSoundBuffs <= kSoundBuffers) { - if (MinFilledSoundBuffs > DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too high"); -#endif - NextTickChangeTime += TickDuration; - } else if (MinFilledSoundBuffs < DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too low"); -#endif - ++TrueEmulatedTime; - } -#if dbglog_SoundBuffStats - dbglog_writelnNum("MinFilledSoundBuffs", - MinFilledSoundBuffs); - dbglog_writelnNum("MaxFilledSoundBuffs", - MaxFilledSoundBuffs); - MaxFilledSoundBuffs = 0; -#endif - MinFilledSoundBuffs = kSoundBuffers + 1; - } -} - -typedef uint16_t trSoundTemp; - -#define kCenterTempSound 0x8000 - -#define AudioStepVal 0x0040 - -#if 3 == kLn2SoundSampSz -#define ConvertTempSoundSampleFromNative(v) ((v) << 8) -#elif 4 == kLn2SoundSampSz -#define ConvertTempSoundSampleFromNative(v) ((v) + kCenterSound) -#else -#error "unsupported kLn2SoundSampSz" -#endif - -#if 3 == kLn2SoundSampSz -#define ConvertTempSoundSampleToNative(v) ((v) >> 8) -#elif 4 == kLn2SoundSampSz -#define ConvertTempSoundSampleToNative(v) ((v) - kCenterSound) -#else -#error "unsupported kLn2SoundSampSz" -#endif - -LOCALPROC SoundRampTo(trSoundTemp *last_val, trSoundTemp dst_val, - tpSoundSamp *stream, int *len) -{ - trSoundTemp diff; - tpSoundSamp p = *stream; - int n = *len; - trSoundTemp v1 = *last_val; - - while ((v1 != dst_val) && (0 != n)) { - if (v1 > dst_val) { - diff = v1 - dst_val; - if (diff > AudioStepVal) { - v1 -= AudioStepVal; - } else { - v1 = dst_val; - } - } else { - diff = dst_val - v1; - if (diff > AudioStepVal) { - v1 += AudioStepVal; - } else { - v1 = dst_val; - } - } - - --n; - *p++ = ConvertTempSoundSampleToNative(v1); - } - - *stream = p; - *len = n; - *last_val = v1; -} - -struct SoundR { - tpSoundSamp fTheSoundBuffer; - volatile uint16_t (*fPlayOffset); - volatile uint16_t (*fFillOffset); - volatile uint16_t (*fMinFilledSoundBuffs); - - volatile trSoundTemp lastv; - - bool enabled; - bool wantplaying; - bool HaveStartedPlaying; - - AudioUnit outputAudioUnit; -}; -typedef struct SoundR SoundR; - -LOCALPROC audio_callback(void *udata, void *stream, int len) -{ - uint16_t ToPlayLen; - uint16_t FilledSoundBuffs; - int i; - SoundR *datp = (SoundR *)udata; - tpSoundSamp CurSoundBuffer = datp->fTheSoundBuffer; - uint16_t CurPlayOffset = *datp->fPlayOffset; - trSoundTemp v0 = datp->lastv; - trSoundTemp v1 = v0; - tpSoundSamp dst = (tpSoundSamp)stream; - -#if kLn2SoundSampSz > 3 - len >>= (kLn2SoundSampSz - 3); -#endif - -#if dbglog_SoundStuff - dbglog_writeln("Enter audio_callback"); - dbglog_writelnNum("len", len); -#endif - -label_retry: - ToPlayLen = *datp->fFillOffset - CurPlayOffset; - FilledSoundBuffs = ToPlayLen >> kLnOneBuffLen; - - if (! datp->wantplaying) { -#if dbglog_SoundStuff - dbglog_writeln("playing end transistion"); -#endif - - SoundRampTo(&v1, kCenterTempSound, &dst, &len); - - ToPlayLen = 0; - } else if (! datp->HaveStartedPlaying) { -#if dbglog_SoundStuff - dbglog_writeln("playing start block"); -#endif - - if ((ToPlayLen >> kLnOneBuffLen) < 8) { - ToPlayLen = 0; - } else { - tpSoundSamp p = datp->fTheSoundBuffer - + (CurPlayOffset & kAllBuffMask); - trSoundTemp v2 = ConvertTempSoundSampleFromNative(*p); - -#if dbglog_SoundStuff - dbglog_writeln("have enough samples to start"); -#endif - - SoundRampTo(&v1, v2, &dst, &len); - - if (v1 == v2) { -#if dbglog_SoundStuff - dbglog_writeln("finished start transition"); -#endif - - datp->HaveStartedPlaying = true; - } - } - } - - if (0 == len) { - /* done */ - - if (FilledSoundBuffs < *datp->fMinFilledSoundBuffs) { - *datp->fMinFilledSoundBuffs = FilledSoundBuffs; - } - } else if (0 == ToPlayLen) { - -#if dbglog_SoundStuff - dbglog_writeln("under run"); -#endif - - for (i = 0; i < len; ++i) { - *dst++ = ConvertTempSoundSampleToNative(v1); - } - *datp->fMinFilledSoundBuffs = 0; - } else { - uint16_t PlayBuffContig = kAllBuffLen - - (CurPlayOffset & kAllBuffMask); - tpSoundSamp p = CurSoundBuffer - + (CurPlayOffset & kAllBuffMask); - - if (ToPlayLen > PlayBuffContig) { - ToPlayLen = PlayBuffContig; - } - if (ToPlayLen > len) { - ToPlayLen = len; - } - - for (i = 0; i < ToPlayLen; ++i) { - *dst++ = *p++; - } - v1 = ConvertTempSoundSampleFromNative(p[-1]); - - CurPlayOffset += ToPlayLen; - len -= ToPlayLen; - - *datp->fPlayOffset = CurPlayOffset; - - goto label_retry; - } - - datp->lastv = v1; -} - -LOCALFUNC OSStatus audioCallback( - void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList *ioData) -{ - AudioBuffer *abuf; - UInt32 i; - UInt32 n = ioData->mNumberBuffers; - -#if dbglog_SoundStuff - dbglog_writeln("Enter audioCallback"); - dbglog_writelnNum("mNumberBuffers", n); -#endif - - for (i = 0; i < n; i++) { - abuf = &ioData->mBuffers[i]; - audio_callback(inRefCon, - abuf->mData, abuf->mDataByteSize); - } - - return 0; -} - -LOCALVAR SoundR cur_audio; - -LOCALPROC ZapAudioVars(void) -{ - memset(&cur_audio, 0, sizeof(SoundR)); -} - -LOCALPROC Sound_Stop(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Stop"); -#endif - - if (cur_audio.wantplaying) { - OSStatus result; - uint16_t retry_limit = 50; /* half of a second */ - - cur_audio.wantplaying = false; - -label_retry: - if (kCenterTempSound == cur_audio.lastv) { -#if dbglog_SoundStuff - dbglog_writeln("reached kCenterTempSound"); -#endif - - /* done */ - } else if (0 == --retry_limit) { -#if dbglog_SoundStuff - dbglog_writeln("retry limit reached"); -#endif - /* done */ - } else - { - /* - give time back, particularly important - if got here on a suspend event. - */ - struct timespec rqt; - struct timespec rmt; - -#if dbglog_SoundStuff - dbglog_writeln("busy, so sleep"); -#endif - - rqt.tv_sec = 0; - rqt.tv_nsec = 10000000; - (void) nanosleep(&rqt, &rmt); - - goto label_retry; - } - - if (noErr != (result = AudioOutputUnitStop( - cur_audio.outputAudioUnit))) - { -#if dbglog_HAVE - dbglog_writeln("AudioOutputUnitStop fails"); -#endif - } - } - -#if dbglog_SoundStuff - dbglog_writeln("leave Sound_Stop"); -#endif -} - -LOCALPROC Sound_Start(void) -{ - OSStatus result; - - if ((! cur_audio.wantplaying) && cur_audio.enabled) { -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Start"); -#endif - - Sound_Start0(); - cur_audio.lastv = kCenterTempSound; - cur_audio.HaveStartedPlaying = false; - cur_audio.wantplaying = true; - - if (noErr != (result = AudioOutputUnitStart( - cur_audio.outputAudioUnit))) - { -#if dbglog_HAVE - dbglog_writeln("AudioOutputUnitStart fails"); -#endif - cur_audio.wantplaying = false; - } - -#if dbglog_SoundStuff - dbglog_writeln("leave Sound_Start"); -#endif - } -} - -LOCALPROC Sound_UnInit(void) -{ - if (cur_audio.enabled) { - OSStatus result; - struct AURenderCallbackStruct callback; - - cur_audio.enabled = false; - - /* Remove the input callback */ - callback.inputProc = 0; - callback.inputProcRefCon = 0; - - if (noErr != (result = AudioUnitSetProperty( - cur_audio.outputAudioUnit, - kAudioUnitProperty_SetRenderCallback, - kAudioUnitScope_Input, - 0, - &callback, - sizeof(callback)))) - { -#if dbglog_HAVE - dbglog_writeln("AudioUnitSetProperty fails" - "(kAudioUnitProperty_SetRenderCallback)"); -#endif - } - - if (noErr != (result = CloseComponent( - cur_audio.outputAudioUnit))) - { -#if dbglog_HAVE - dbglog_writeln("CloseComponent fails in Sound_UnInit"); -#endif - } - } -} - -#define SOUND_SAMPLERATE 22255 /* = round(7833600 * 2 / 704) */ - -LOCALFUNC bool Sound_Init(void) -{ - OSStatus result = noErr; - Component comp; - ComponentDescription desc; - struct AURenderCallbackStruct callback; - AudioStreamBasicDescription requestedDesc; - - cur_audio.fTheSoundBuffer = TheSoundBuffer; - cur_audio.fPlayOffset = &ThePlayOffset; - cur_audio.fFillOffset = &TheFillOffset; - cur_audio.fMinFilledSoundBuffs = &MinFilledSoundBuffs; - cur_audio.wantplaying = false; - - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_DefaultOutput; - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - - requestedDesc.mFormatID = kAudioFormatLinearPCM; - requestedDesc.mFormatFlags = kLinearPCMFormatFlagIsPacked -#if 3 != kLn2SoundSampSz - | kLinearPCMFormatFlagIsSignedInteger -#endif - ; - requestedDesc.mChannelsPerFrame = 1; - requestedDesc.mSampleRate = SOUND_SAMPLERATE; - - requestedDesc.mBitsPerChannel = (1 << kLn2SoundSampSz); -#if 0 - requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; -#endif -#if 0 - requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; -#endif - - requestedDesc.mFramesPerPacket = 1; - requestedDesc.mBytesPerFrame = (requestedDesc.mBitsPerChannel - * requestedDesc.mChannelsPerFrame) >> 3; - requestedDesc.mBytesPerPacket = requestedDesc.mBytesPerFrame - * requestedDesc.mFramesPerPacket; - - - callback.inputProc = audioCallback; - callback.inputProcRefCon = &cur_audio; - - if (NULL == (comp = FindNextComponent(NULL, &desc))) - { -#if dbglog_HAVE - dbglog_writeln("Failed to start CoreAudio: " - "FindNextComponent returned NULL"); -#endif - } else - - if (noErr != (result = OpenAComponent( - comp, &cur_audio.outputAudioUnit))) - { -#if dbglog_HAVE - dbglog_writeln("Failed to start CoreAudio: OpenAComponent"); -#endif - } else - - if (noErr != (result = AudioUnitInitialize( - cur_audio.outputAudioUnit))) - { -#if dbglog_HAVE - dbglog_writeln( - "Failed to start CoreAudio: AudioUnitInitialize"); -#endif - } else - - if (noErr != (result = AudioUnitSetProperty( - cur_audio.outputAudioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - 0, - &requestedDesc, - sizeof(requestedDesc)))) - { -#if dbglog_HAVE - dbglog_writeln("Failed to start CoreAudio: " - "AudioUnitSetProperty(kAudioUnitProperty_StreamFormat)"); -#endif - } else - - if (noErr != (result = AudioUnitSetProperty( - cur_audio.outputAudioUnit, - kAudioUnitProperty_SetRenderCallback, - kAudioUnitScope_Input, - 0, - &callback, - sizeof(callback)))) - { -#if dbglog_HAVE - dbglog_writeln("Failed to start CoreAudio: " - "AudioUnitSetProperty(kAudioUnitProperty_SetInputCallback)" - ); -#endif - } else - - { - cur_audio.enabled = true; - - Sound_Start(); - /* - This should be taken care of by LeaveSpeedStopped, - but since takes a while to get going properly, - start early. - */ - } - - return true; /* keep going, even if no sound */ -} - -GLOBALOSGLUPROC Sound_EndWrite(uint16_t actL) -{ - if (Sound_EndWrite0(actL)) { - } -} - -LOCALPROC Sound_SecondNotify(void) -{ - if (cur_audio.enabled) { - Sound_SecondNotify0(); - } -} - -#endif - -LOCALPROC FinishSubMenu(NSMenu *theMenu, NSMenu *parentMenu, - NSString *sTitle) -{ - NSMenuItem *menuItem = [[NSMenuItem alloc] - initWithTitle: sTitle - action: nil - keyEquivalent: @""]; - - [menuItem setSubmenu: theMenu]; - [parentMenu addItem: menuItem]; - [menuItem release]; -} - -LOCALFUNC NSMenu *setApplicationMenu(NSMenu *mainMenu) -{ - NSMenuItem *menuItem; - NSString *sAppName = NSStringCreateFromSubstCStr("^p"); - /* doesn't matter though, OS X replaces this */ - NSString *sAbout = - NSStringCreateFromSubstCStr(kStrMenuItemAbout); - NSString *sHide = - NSStringCreateFromSubstCStr(kStrAppMenuItemHide); - NSString *sHideOthers = - NSStringCreateFromSubstCStr(kStrAppMenuItemHideOthers); - NSString *sShowAll = - NSStringCreateFromSubstCStr(kStrAppMenuItemShowAll); - NSString *sQuit = - NSStringCreateFromSubstCStr(kStrAppMenuItemQuit); - - NSMenu *appleMenu = [[NSMenu alloc] initWithTitle: sAppName]; - - /* Add menu items */ - menuItem = [appleMenu addItemWithTitle: sAbout - action: @selector(performApplicationAbout:) - keyEquivalent: @"a"]; - [menuItem setKeyEquivalentModifierMask: NSControlKeyMask]; - - [appleMenu addItem:[NSMenuItem separatorItem]]; - - [appleMenu addItemWithTitle: sHide - action: @selector(hide:) keyEquivalent: @""]; - - [appleMenu - addItemWithTitle: sHideOthers - action: @selector(hideOtherApplications:) - keyEquivalent: @""]; - - [appleMenu addItemWithTitle: sShowAll - action: @selector(unhideAllApplications:) - keyEquivalent: @""]; - - [appleMenu addItem: [NSMenuItem separatorItem]]; - - menuItem = [appleMenu addItemWithTitle: sQuit - action: @selector(terminate:) keyEquivalent: @"q"]; - [menuItem setKeyEquivalentModifierMask: NSControlKeyMask]; - - FinishSubMenu(appleMenu, mainMenu, sAppName); - - [appleMenu release]; - - return appleMenu; -} - -/* Create File menu */ -LOCALPROC setupFileMenu(NSMenu *mainMenu) -{ - NSMenu *fileMenu; - NSMenuItem *menuItem; - NSString *sFile = - NSStringCreateFromSubstCStr(kStrMenuFile); - NSString *sOpen = - NSStringCreateFromSubstCStr(kStrMenuItemOpen ";ll"); - - fileMenu = [[NSMenu alloc] initWithTitle: sFile]; - - menuItem = [fileMenu - addItemWithTitle: sOpen - action: @selector(performFileOpen:) - keyEquivalent: @"o"]; - [menuItem setKeyEquivalentModifierMask: NSControlKeyMask]; - - FinishSubMenu(fileMenu, mainMenu, sFile); - - [fileMenu release]; -} - -/* Create Special menu */ -LOCALPROC setupSpecialMenu(NSMenu *mainMenu) -{ - NSMenu *specialMenu; - NSString *sSpecial = - NSStringCreateFromSubstCStr(kStrMenuSpecial); - NSString *sMore = - NSStringCreateFromSubstCStr(kStrMenuItemMore ";ll"); - - specialMenu = [[NSMenu alloc] initWithTitle: sSpecial]; - - [specialMenu - addItemWithTitle: sMore - action: @selector(performSpecialMoreCommands:) - keyEquivalent: @""]; - - FinishSubMenu(specialMenu, mainMenu, sSpecial); - - [specialMenu release]; -} - -LOCALPROC MenuSetup(void) -{ - NSMenu *mainMenu = [[NSMenu alloc] init]; - NSMenu *appleMenu = setApplicationMenu(mainMenu); - - setupFileMenu(mainMenu); - setupSpecialMenu(mainMenu); - - [NSApp setMainMenu: mainMenu]; - - /* - Tell the application object that this is now - the application menu, if this unsupported - call actually exists. Doesn't seem to - be needed anyway, at least in OS X 10.7 - */ - if([NSApp respondsToSelector:@selector(setAppleMenu:)]) { - /* [NSApp setAppleMenu: appleMenu]; */ - [NSApp performSelector: @selector(setAppleMenu:) - withObject:appleMenu]; - } - - [mainMenu release]; -} - - - -/* --- video out --- */ - - -#if ! UseCGContextDrawImage -LOCALPROC HaveChangedScreenBuff(uint16_t top, uint16_t left, - uint16_t bottom, uint16_t right) -{ - if ([NSview lockFocusIfCanDraw]) { - DrawWithOpenGL(top, left, bottom, right); - [NSview unlockFocus]; - } -} -#else -LOCALPROC HaveChangedScreenBuff(uint16_t top, uint16_t left, - uint16_t bottom, uint16_t right) -{ - int i; - int j; - uint8_t *the_data = (uint8_t *)GetCurDrawBuff(); - uint8_t *p; - uint32_t color; - uint32_t black_color = 0; - /* SDL_MapRGB(cur_video.format, 0, 0, 0) */ - uint32_t white_color = 0; - /* SDL_MapRGB(cur_video.format, 255, 255, 255) */ - - switch (BytesPerPixel) { - case 2: /* (1)-5-5-5 RGB */ -#if 0 - rmask = 0x7C00; - gmask = 0x03E0; - bmask = 0x001F; -#endif - break; - case 4: -#if LittleEndianUnaligned -#if 0 - rmask = 0x0000FF00; - gmask = 0x00FF0000; - bmask = 0xFF000000; -#endif - black_color = 0x000000FF; - white_color = 0xFFFFFFFF; -#else -#if 0 - rmask = 0x00FF0000; - gmask = 0x0000FF00; - bmask = 0x000000FF; -#endif - black_color = 0xFF000000; - white_color = 0xFFFFFFFF; -#endif - break; - } - - if (UseMagnify) { - for (i = top * WindowScale; i < bottom * WindowScale; ++i) { - for (j = left * WindowScale; - j < right * WindowScale; ++j) - { - p = the_data + (((i / WindowScale) * vMacScreenWidth - + (j / WindowScale)) / 8); - if (0 != (*p & (1 << ((~ (j / WindowScale)) & 0x7)))) - { - color = black_color; - } else { - color = white_color; - } - switch (BytesPerPixel) { - case 2: { /* Probably 15-bpp or 16-bpp */ - uint16_t *bufp; - - bufp = (uint16_t *)Pixels - + i * Pitch / 2 + j; - *bufp = color; - } - break; - - case 4: { /* Probably 32-bpp */ - uint32_t *bufp; - - bufp = (uint32_t *)Pixels - + i * Pitch / 4 + j; - *bufp = color; - } - break; - } - } - } - } else - { - for (i = top; i < bottom; ++i) { - for (j = left; j < right; ++j) { - p = the_data + ((i * vMacScreenWidth + j) / 8); - if (0 != (*p & (1 << ((~ j) & 0x7)))) { - color = black_color; - } else { - color = white_color; - } - switch (BytesPerPixel) { - case 2: { /* Probably 15-bpp or 16-bpp */ - uint16_t *bufp; - - bufp = (uint16_t *)Pixels - + i * Pitch / 2 + j; - *bufp = color; - } - break; - case 4: { /* Probably 32-bpp */ - uint32_t *bufp; - - bufp = (uint32_t *)Pixels - + i * Pitch / 4 + j; - *bufp = color; - } - break; - } - } - } - } - - if (UseMagnify) { - SDL_UpdateRect(left * WindowScale, - top * WindowScale, - (right - left) * WindowScale, - (bottom - top) * WindowScale); - } else { - SDL_UpdateRect(left, top, - right - left, bottom - top); - } -} -#endif - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ -#if EnableFSMouseMotion - if (HaveMouseMotion) { - AutoScrollScreen(); - } -#endif - DrawChangesAndClear(); -} - -/* --- keyboard input --- */ - -LOCALPROC DisableKeyRepeat(void) -{ -} - -LOCALPROC RestoreKeyRepeat(void) -{ -} - -LOCALPROC ReconnectKeyCodes3(void) -{ -} - -LOCALPROC DisconnectKeyCodes3(void) -{ - DisconnectKeyCodes2(); - MouseButtonSet(false); -} - -/* --- basic dialogs --- */ - -LOCALPROC CheckSavedMacMsg(void) -{ - /* called only on quit, if error saved but not yet reported */ - - if (nullpr != SavedBriefMsg) { - NSString *briefMsg0 = - NSStringCreateFromSubstCStr(SavedBriefMsg); - NSString *longMsg0 = - NSStringCreateFromSubstCStr(SavedLongMsg); - NSString *quitMsg0 = - NSStringCreateFromSubstCStr(kStrCmdQuit); - - (void) NSRunAlertPanel(briefMsg0, @"%@", quitMsg0, nil, nil, - longMsg0); - - SavedBriefMsg = nullpr; - } -} - -/* --- hide/show menubar --- */ - -enum { - NSApplicationPresentationDefault = 0, - NSApplicationPresentationAutoHideDock = (1 << 0), - NSApplicationPresentationHideDock = (1 << 1), - NSApplicationPresentationAutoHideMenuBar = (1 << 2), - NSApplicationPresentationHideMenuBar = (1 << 3), - NSApplicationPresentationDisableAppleMenu = (1 << 4), - NSApplicationPresentationDisableProcessSwitching = (1 << 5), - NSApplicationPresentationDisableForceQuit = (1 << 6), - NSApplicationPresentationDisableSessionTermination = (1 << 7), - NSApplicationPresentationDisableHideApplication = (1 << 8), - NSApplicationPresentationDisableMenuBarTransparency = (1 << 9), - NSApplicationPresentationFullScreen = (1 << 10), - NSApplicationPresentationAutoHideToolbar = (1 << 11) -}; -typedef NSUInteger NSApplicationPresentationOptions; - -@interface NSApplication : NSObject -- (void)setPresentationOptions: - (NSApplicationPresentationOptions)newOptions; -@end - - -#if MayFullScreen -LOCALPROC _HideMenuBar(void) -{ - if ([NSApp respondsToSelector:@selector(setPresentationOptions:)]) { - [((NSApplication *)NSApp) setPresentationOptions: - NSApplicationPresentationHideDock - | NSApplicationPresentationHideMenuBar -#if GrabKeysFullScreen - | NSApplicationPresentationDisableProcessSwitching -#if GrabKeysMaxFullScreen /* dangerous !! */ - | NSApplicationPresentationDisableForceQuit - | NSApplicationPresentationDisableSessionTermination -#endif -#endif - ]; - } else - if (HaveSetSystemUIMode()) { - (void) SetSystemUIMode(kUIModeAllHidden, - kUIOptionDisableAppleMenu -#if GrabKeysFullScreen - | kUIOptionDisableProcessSwitch -#if GrabKeysMaxFullScreen /* dangerous !! */ - | kUIOptionDisableForceQuit - | kUIOptionDisableSessionTerminate -#endif -#endif - ); - } else - { - } -} -#endif - -#if MayFullScreen -LOCALPROC _ShowMenuBar(void) -{ - if ([NSApp respondsToSelector:@selector(setPresentationOptions:)]) { - [((NSApplication *)NSApp) setPresentationOptions: - NSApplicationPresentationDefault]; - } else - if (HaveSetSystemUIMode()) { - (void) SetSystemUIMode(kUIModeNormal, - 0); - } else - { - } -} -#endif - -/* --- event handling for main window --- */ - -LOCALPROC BeginDialog(void) -{ - DisconnectKeyCodes3(); - ForceShowCursor(); -} - -LOCALPROC EndDialog(void) -{ - [Window makeKeyWindow]; - EmulationWasInterrupted = true; -} - -LOCALPROC InsertADisk0(void) -{ - NSOpenPanel *panel = [NSOpenPanel openPanel]; - - [panel setAllowsMultipleSelection: YES]; - - BeginDialog(); - - if (NSOKButton == [panel runModal]) { - int i; - NSArray *a = [panel URLs]; - int n = [a count]; - - for (i = 0; i < n; ++i) { - NSURL *fileURL = [a objectAtIndex: i]; - NSString* filePath = [fileURL path]; - (void) Sony_Insert1a(filePath); - } - } - - EndDialog(); -} - -/* --- main window creation and disposal --- */ - -LOCALFUNC bool Screen_Init(void) -{ -#if 0 - if (noErr != Gestalt(gestaltSystemVersion, - &cur_video.system_version)) - { - cur_video.system_version = 0; - } -#endif - -#if 0 -#define CGMainDisplayID CGMainDisplayID - CGDirectDisplayID CurMainDisplayID = CGMainDisplayID(); - - cur_video.width = (uint32_t) CGDisplayPixelsWide(CurMainDisplayID); - cur_video.height = (uint32_t) CGDisplayPixelsHigh(CurMainDisplayID); -#endif - - InitKeyCodes(); - - return true; -} - -#if MayFullScreen -LOCALPROC AdjustMachineGrab(void) -{ -#if EnableFSMouseMotion - AdjustMouseMotionGrab(); -#endif -} -#endif - -#if MayFullScreen -LOCALPROC UngrabMachine(void) -{ - GrabMachine = false; - AdjustMachineGrab(); -} -#endif - -LOCALPROC AdjustGLforSize(int h, int v) -{ - [NSOpnGLCntxt makeCurrentContext]; - - glClearColor (0.0, 0.0, 0.0, 1.0); - -#if 1 - glViewport(0, 0, h, v); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, h, 0, v, -1.0, 1.0); - glMatrixMode(GL_MODELVIEW); -#endif - - glColor3f(0.0, 0.0, 0.0); - if (UseMagnify) { - glPixelZoom(WindowScale, - WindowScale); - } else { - glPixelZoom(1, -1); - } - glPixelStorei(GL_UNPACK_ROW_LENGTH, vMacScreenWidth); - - glClear(GL_COLOR_BUFFER_BIT); - - [NSOpenGLContext clearCurrentContext]; - - ScreenChangedAll(); -} - -LOCALVAR bool WantScreensChangedCheck = false; - -LOCALPROC UpdateOpenGLContext(void) -{ - if (nil != NSOpnGLCntxt) { - [NSOpnGLCntxt makeCurrentContext]; - [NSOpnGLCntxt update]; - } -} - -LOCALPROC CloseOpenGLContext(void) -{ - if (nil != NSOpnGLCntxt) { - - [NSOpenGLContext clearCurrentContext]; - /* - Only because DrawWithOpenGL doesn't - bother to do this. No one - uses the current context - without settting it first. - */ - } -} - -LOCALFUNC bool GetOpnGLCntxt(void) -{ - bool v = false; - - if (nil == NSOpnGLCntxt) { - NSRect NewWinRect = [NSview frame]; - NSOpenGLPixelFormat *fmt; - -#if WantGraphicsSwitching - { - NSOpenGLPixelFormatAttribute attr0[] = { - NSOpenGLPFAAllowOfflineRenderers, - 0}; - - fmt = - [[NSOpenGLPixelFormat alloc] initWithAttributes:attr0]; - } - if (nil != fmt) { - /* ok */ - } else -#endif - { - NSOpenGLPixelFormatAttribute attr[] = { - 0}; - - fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; - if (nil == fmt) { -#if dbglog_HAVE - dbglog_writeln("Could not create fmt"); -#endif - goto label_exit; - } - } - - NSOpnGLCntxt = [[NSOpenGLContext alloc] - initWithFormat:fmt shareContext:nil]; - - [fmt release]; - - if (nil == NSOpnGLCntxt) { -#if dbglog_HAVE - dbglog_writeln("Could not create NSOpnGLCntxt"); -#endif - goto label_exit; - } - - /* fprintf(stderr, "%s\n", "Got OpenGL context"); */ - - [NSOpnGLCntxt setView: NSview]; - [NSOpnGLCntxt update]; - - AdjustGLforSize(NewWinRect.size.width, - NewWinRect.size.height); - - if (0 != vMacScreenDepth) { ColorModeWorks = true; } - } - v = true; - -label_exit: - return v; -} - -typedef NSUInteger (*modifierFlagsProcPtr) - (id self, SEL cmd); - -/* Subclass of NSWindow to fix genie effect and support resize events */ -@interface ClassWindow : NSWindow -@end - -@implementation ClassWindow - -#if MayFullScreen -- (BOOL)canBecomeKeyWindow -{ - return -#if 1 - (! UseFullScreen) ? [super canBecomeKeyWindow] : -#endif - YES; -} -#endif - -#if MayFullScreen -- (BOOL)canBecomeMainWindow -{ - return -#if 1 - (! UseFullScreen) ? [super canBecomeMainWindow] : -#endif - YES; -} -#endif - -#if MayFullScreen -- (NSRect)constrainFrameRect:(NSRect)frameRect - toScreen:(NSScreen *)screen -{ -#if 1 - if (! UseFullScreen) { - return [super constrainFrameRect:frameRect toScreen:screen]; - } else -#endif - { - return frameRect; - } -} -#endif - -- (NSDragOperation)draggingEntered:(id )sender -{ - /* NSPasteboard *pboard = [sender draggingPasteboard]; */ - NSDragOperation sourceDragMask = - [sender draggingSourceOperationMask]; - NSDragOperation v = NSDragOperationNone; - - if (0 != (sourceDragMask & NSDragOperationGeneric)) { - return NSDragOperationGeneric; - } - - return v; -} - -- (void)draggingExited:(id )sender -{ - /* remove hilighting */ -} - -- (BOOL)prepareForDragOperation:(id )sender -{ - return YES; -} - -- (BOOL)performDragOperation:(id )sender -{ - BOOL v = NO; - NSPasteboard *pboard = [sender draggingPasteboard]; - /* - NSDragOperation sourceDragMask = - [sender draggingSourceOperationMask]; - */ - - if ([[pboard types] containsObject:NSFilenamesPboardType]) { - int i; - NSArray *file_names = - [pboard propertyListForType: NSFilenamesPboardType]; - int n = [file_names count]; - - for (i = 0; i < n; ++i) { - NSString *filePath = [file_names objectAtIndex:i]; - Sony_ResolveInsert(filePath); - } - v = YES; - } else if ([[pboard types] containsObject: NSURLPboardType]) { - NSURL *fileURL = [NSURL URLFromPasteboard: pboard]; - NSString* filePath = [fileURL path]; - Sony_ResolveInsert(filePath); - v = YES; - } - - if (v && gTrueBackgroundFlag) { - { - SEL sel = @selector(modifierFlags); - - if ([NSEvent respondsToSelector:sel]) { - modifierFlagsProcPtr imp = (modifierFlagsProcPtr) - [NSEvent methodForSelector:sel]; - - UpdateKeyboardModifiers(imp([NSEvent class], sel)); - } - } - - [NSApp activateIgnoringOtherApps: YES]; - } - - return v; -} - -- (void) concludeDragOperation:(id )the_sender -{ -} - -@end - -@interface ClassWindowDelegate : NSObject -@end - -@implementation ClassWindowDelegate - -- (BOOL)windowShouldClose:(id)sender -{ - RequestMacOff = true; - return NO; -} - -- (void)windowDidBecomeKey:(NSNotification *)aNotification -{ - gTrueBackgroundFlag = false; -} - -- (void)windowDidResignKey:(NSNotification *)aNotification -{ - gTrueBackgroundFlag = true; -} - -@end - -@interface ClassView : NSView -@end - -@implementation ClassView - -- (void)resetCursorRects -{ - [self addCursorRect: [self visibleRect] - cursor: [NSCursor arrowCursor]]; -} - -- (BOOL)isOpaque -{ - return YES; -} - -- (void)drawRect:(NSRect)dirtyRect -{ - /* - Called upon makeKeyAndOrderFront. Create our - OpenGL context here, because can't do so - before makeKeyAndOrderFront. - And if create after then our content won't - be drawn initially, resulting in flicker. - */ - if (GetOpnGLCntxt()) { - DrawWithOpenGL(0, 0, vMacScreenHeight, vMacScreenWidth); - } -} - -@end - -#if UseCGContextDrawImage -/* absent in 10.3.9. */ -CG_EXTERN CGImageRef CGBitmapContextCreateImage(CGContextRef); -#endif - - -LOCALVAR ClassWindowDelegate *WinDelegate = nil; - -LOCALPROC CloseMainWindow(void) -{ - if (nil != WinDelegate) { - [WinDelegate release]; - WinDelegate = nil; - } - - if (nil != Window) { - [Window close]; - Window = nil; - } - - if (nil != NSview) { - [NSview release]; - NSview = nil; - } - -#if UseCGContextDrawImage - if (nil != CGcontext) { - CGContextFlush(CGcontext); - CGContextRelease(CGcontext); - CGcontext = nil; - } - - if (NULL != Pixels) { - free(Pixels); - Pixels = NULL; - } -#endif - - if (nil != NSOpnGLCntxt) { - [NSOpnGLCntxt release]; - NSOpnGLCntxt = nil; - } -} - -LOCALPROC QZ_SetCaption(void) -{ -#if 0 - NSString *string = - [[NSString alloc] initWithUTF8String: kStrAppName]; -#endif - [Window setTitle: myAppName /* string */]; -#if 0 - [string release]; -#endif -} - -enum { - kMagStateNormal, - kMagStateMagnifgy, - kNumMagStates -}; - -#define kMagStateAuto kNumMagStates - -#if MayNotFullScreen -LOCALVAR int CurWinIndx; -LOCALVAR bool HavePositionWins[kNumMagStates]; -LOCALVAR NSPoint WinPositionWins[kNumMagStates]; -#endif - -LOCALVAR NSRect SavedScrnBounds; - -LOCALFUNC bool CreateMainWindow(void) -{ -#if UseCGContextDrawImage - CGColorSpaceRef cgColorspace; -#endif - unsigned int style; - NSRect MainScrnBounds; - NSRect AllScrnBounds; - NSRect NewWinRect; - NSPoint botleftPos; - int NewWindowHeight = vMacScreenHeight; - int NewWindowWidth = vMacScreenWidth; - bool v = false; - -#if 1 - if (UseFullScreen) { - _HideMenuBar(); - } else { - _ShowMenuBar(); - } -#else -#if MayFullScreen - _HideMenuBar(); -#endif -#endif - - MainScrnBounds = [[NSScreen mainScreen] frame]; - SavedScrnBounds = MainScrnBounds; - { - int i; - NSArray *screens = [NSScreen screens]; - int n = [screens count]; - - AllScrnBounds = MainScrnBounds; - for (i = 0; i < n; ++i) { - AllScrnBounds = NSUnionRect(AllScrnBounds, - [[screens objectAtIndex:i] frame]); - } - } - - if (UseMagnify) { - NewWindowHeight *= WindowScale; - NewWindowWidth *= WindowScale; - } - - botleftPos.x = MainScrnBounds.origin.x - + floor((MainScrnBounds.size.width - - NewWindowWidth) / 2); - botleftPos.y = MainScrnBounds.origin.y - + floor((MainScrnBounds.size.height - - NewWindowHeight) / 2); - if (botleftPos.x < MainScrnBounds.origin.x) { - botleftPos.x = MainScrnBounds.origin.x; - } - if (botleftPos.y < MainScrnBounds.origin.y) { - botleftPos.y = MainScrnBounds.origin.y; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ViewHSize = MainScrnBounds.size.width; - ViewVSize = MainScrnBounds.size.height; - if (UseMagnify) { - ViewHSize /= WindowScale; - ViewVSize /= WindowScale; - } - if (ViewHSize >= vMacScreenWidth) { - ViewHStart = 0; - ViewHSize = vMacScreenWidth; - } else { - ViewHSize &= ~ 1; - } - if (ViewVSize >= vMacScreenHeight) { - ViewVStart = 0; - ViewVSize = vMacScreenHeight; - } else { - ViewVSize &= ~ 1; - } - } -#endif - - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewWinRect = AllScrnBounds; - - GLhOffset = botleftPos.x - AllScrnBounds.origin.x; - GLvOffset = (botleftPos.y - AllScrnBounds.origin.y) - + ((NewWindowHeight < MainScrnBounds.size.height) - ? NewWindowHeight : MainScrnBounds.size.height); - - hOffset = GLhOffset; - vOffset = AllScrnBounds.size.height - GLvOffset; - - style = NSBorderlessWindowMask; - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - int WinIndx; - - if (UseMagnify) { - WinIndx = kMagStateMagnifgy; - } else { - WinIndx = kMagStateNormal; - } - - if (! HavePositionWins[WinIndx]) { - WinPositionWins[WinIndx].x = botleftPos.x; - WinPositionWins[WinIndx].y = botleftPos.y; - HavePositionWins[WinIndx] = true; - NewWinRect = NSMakeRect(botleftPos.x, botleftPos.y, - NewWindowWidth, NewWindowHeight); - } else { - NewWinRect = NSMakeRect(WinPositionWins[WinIndx].x, - WinPositionWins[WinIndx].y, - NewWindowWidth, NewWindowHeight); - } - - GLhOffset = 0; - GLvOffset = NewWindowHeight; - - style = NSTitledWindowMask - | NSMiniaturizableWindowMask | NSClosableWindowMask; - - CurWinIndx = WinIndx; - } -#endif - - /* Manually create a window, avoids having a nib file resource */ - Window = [[ClassWindow alloc] - initWithContentRect: NewWinRect - styleMask: style - backing: NSBackingStoreBuffered - defer: YES]; - - if (nil == Window) { -#if dbglog_HAVE - dbglog_writeln("Could not create the Cocoa window"); -#endif - goto label_exit; - } - - /* [Window setReleasedWhenClosed: YES]; */ - /* - no need to set current_video as it's the - default for NSWindows - */ - QZ_SetCaption(); - [Window setAcceptsMouseMovedEvents: YES]; - [Window setViewsNeedDisplay: NO]; - - [Window registerForDraggedTypes: - [NSArray arrayWithObjects: - NSURLPboardType, NSFilenamesPboardType, nil]]; - - WinDelegate = [[ClassWindowDelegate alloc] init]; - if (nil == WinDelegate) { -#if dbglog_HAVE - dbglog_writeln("Could not create NSview"); -#endif - goto label_exit; - } - [Window setDelegate: WinDelegate]; - - NSview = [[ClassView alloc] init]; - if (nil == NSview) { -#if dbglog_HAVE - dbglog_writeln("Could not create NSview"); -#endif - goto label_exit; - } - [Window setContentView: NSview]; - - [Window makeKeyAndOrderFront: nil]; - - /* just in case drawRect didn't get called */ - if (! GetOpnGLCntxt()) { -#if dbglog_HAVE - dbglog_writeln("Could not GetOpnGLCntxt"); -#endif - goto label_exit; - } - -#if UseCGContextDrawImage - Pitch = 4 * NewWindowWidth; - Pixels = malloc(NewWindowHeight * Pitch); - - cgColorspace = CGColorSpaceCreateDeviceRGB(); - CGcontext = CGBitmapContextCreate(Pixels, - NewWindowWidth, NewWindowHeight, - 8, Pitch, cgColorspace, - kCGImageAlphaNoneSkipFirst); - CGColorSpaceRelease(cgColorspace); - - NSgfxContext = [NSGraphicsContext - graphicsContextWithWindow: Window]; - [NSGraphicsContext setCurrentContext: NSgfxContext]; - - BytesPerPixel = 4; -#endif - - v = true; - -label_exit: - - return v; -} - -#if EnableRecreateW -LOCALPROC ZapWState(void) -{ - Window = nil; - NSview = nil; - WinDelegate = nil; -#if UseCGContextDrawImage - NSgfxContext = nil; - CGcontext = nil; - Pixels = NULL; -#endif - NSOpnGLCntxt = nil; -} -#endif - -#if EnableRecreateW -struct WState { -#if MayFullScreen - uint16_t f_ViewHSize; - uint16_t f_ViewVSize; - uint16_t f_ViewHStart; - uint16_t f_ViewVStart; - short f_hOffset; - short f_vOffset; -#endif -#if 1 - bool f_UseFullScreen; -#endif - bool f_UseMagnify; -#if MayNotFullScreen - int f_CurWinIndx; -#endif - NSWindow *f_Window; - NSView *f_NSview; - ClassWindowDelegate *f_WinDelegate; -#if UseCGContextDrawImage - NSGraphicsContext *f_NSgfxContext; - CGContextRef f_CGcontext; - void *f_Pixels; - uint16_t f_Pitch; - uint8_t f_BytesPerPixel; -#endif - NSOpenGLContext *f_NSOpnGLCntxt; - short f_GLhOffset; - short f_GLvOffset; -}; -typedef struct WState WState; -#endif - -#if EnableRecreateW -LOCALPROC GetWState(WState *r) -{ -#if MayFullScreen - r->f_ViewHSize = ViewHSize; - r->f_ViewVSize = ViewVSize; - r->f_ViewHStart = ViewHStart; - r->f_ViewVStart = ViewVStart; - r->f_hOffset = hOffset; - r->f_vOffset = vOffset; -#endif -#if 1 - r->f_UseFullScreen = UseFullScreen; -#endif - r->f_UseMagnify = UseMagnify; -#if MayNotFullScreen - r->f_CurWinIndx = CurWinIndx; -#endif - r->f_Window = Window; - r->f_NSview = NSview; - r->f_WinDelegate = WinDelegate; -#if UseCGContextDrawImage - r->f_NSgfxContext = NSgfxContext; - r->f_CGcontext = CGcontext; - r->f_Pixels = Pixels; - r->f_Pitch = Pitch; - r->f_BytesPerPixel = BytesPerPixel; -#endif - r->f_NSOpnGLCntxt = NSOpnGLCntxt; - r->f_GLhOffset = GLhOffset; - r->f_GLvOffset = GLvOffset; -} -#endif - -#if EnableRecreateW -LOCALPROC SetWState(WState *r) -{ -#if MayFullScreen - ViewHSize = r->f_ViewHSize; - ViewVSize = r->f_ViewVSize; - ViewHStart = r->f_ViewHStart; - ViewVStart = r->f_ViewVStart; - hOffset = r->f_hOffset; - vOffset = r->f_vOffset; -#endif -#if 1 - UseFullScreen = r->f_UseFullScreen; -#endif - UseMagnify = r->f_UseMagnify; -#if MayNotFullScreen - CurWinIndx = r->f_CurWinIndx; -#endif - Window = r->f_Window; - NSview = r->f_NSview; - WinDelegate = r->f_WinDelegate; -#if UseCGContextDrawImage - NSgfxContext = r->f_NSgfxContext; - CGcontext = r->f_CGcontext; - Pixels = r->f_Pixels; - Pitch = r->f_Pitch; - BytesPerPixel = r->f_BytesPerPixel; -#endif - NSOpnGLCntxt = r->f_NSOpnGLCntxt; - GLhOffset = r->f_GLhOffset; - GLvOffset = r->f_GLvOffset; -} -#endif - -#if EnableRecreateW -LOCALPROC ReCreateMainWindow(void) -{ - WState old_state; - WState new_state; - bool HadCursorHidden = HaveCursorHidden; - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - /* save old position */ - NSRect r = - [NSWindow contentRectForFrameRect: [Window frame] - styleMask: [Window styleMask]]; - WinPositionWins[CurWinIndx] = r.origin; - } -#endif - -#if MayFullScreen - if (GrabMachine) { - GrabMachine = false; - UngrabMachine(); - } -#endif - - CloseOpenGLContext(); - - GetWState(&old_state); - - ZapWState(); - - UseMagnify = WantMagnify; -#if 1 - UseFullScreen = WantFullScreen; -#endif - - if (! CreateMainWindow()) { - CloseMainWindow(); - SetWState(&old_state); - -#if 1 - if (UseFullScreen) { - _HideMenuBar(); - } else { - _ShowMenuBar(); - } -#endif - - /* avoid retry */ -#if 1 - WantFullScreen = UseFullScreen; -#endif - WantMagnify = UseMagnify; - - } else { - GetWState(&new_state); - SetWState(&old_state); - CloseMainWindow(); - SetWState(&new_state); - - if (HadCursorHidden) { - (void) MoveMouse(CurMouseH, CurMouseV); - } - } -} -#endif - -enum { - kWinStateWindowed, - kWinStateFullScreen, - kNumWinStates -}; - -#if 1 -LOCALVAR int WinMagStates[kNumWinStates]; -#endif - -LOCALPROC ZapWinStateVars(void) -{ -#if MayNotFullScreen - { - int i; - - for (i = 0; i < kNumMagStates; ++i) { - HavePositionWins[i] = false; - } - } -#endif -#if 1 - { - int i; - - for (i = 0; i < kNumWinStates; ++i) { - WinMagStates[i] = kMagStateAuto; - } - } -#endif -} - -#if 1 -LOCALPROC ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; - - { - int OldWinState = - UseFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int OldMagState = - UseMagnify ? kMagStateMagnifgy : kMagStateNormal; - int NewWinState = - WantFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int NewMagState = WinMagStates[NewWinState]; - - WinMagStates[OldWinState] = OldMagState; - if (kMagStateAuto != NewMagState) { - WantMagnify = (kMagStateMagnifgy == NewMagState); - } else { - WantMagnify = false; - if (WantFullScreen) { - NSRect MainScrnBounds = [[NSScreen mainScreen] frame]; - - if ((MainScrnBounds.size.width - >= vMacScreenWidth * WindowScale) - && (MainScrnBounds.size.height - >= vMacScreenHeight * WindowScale) - ) - { - WantMagnify = true; - } - } - } - } -} -#endif - -/* --- SavedTasks --- */ - -LOCALPROC LeaveBackground(void) -{ - ReconnectKeyCodes3(); - DisableKeyRepeat(); - EmulationWasInterrupted = true; -} - -LOCALPROC EnterBackground(void) -{ - RestoreKeyRepeat(); - DisconnectKeyCodes3(); - - ForceShowCursor(); -} - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif - - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if SoundEnabled - Sound_Stop(); -#endif -} - -#if IncludeSonyNew && ! SaveDialogEnable -LOCALFUNC bool FindOrMakeNamedChildDirPath(NSString *parentPath, - char *ChildName, NSString **childPath) -{ - NSString *r; - BOOL isDir; - Boolean isDirectory; - NSFileManager *fm = [NSFileManager defaultManager]; - bool v = false; - - if (FindNamedChildPath(parentPath, ChildName, &r)) { - if ([fm fileExistsAtPath:r isDirectory: &isDir]) - { - if (isDir) { - *childPath = r; - v = true; - } else { - NSString *RslvPath = ResolveAlias(r, &isDirectory); - if (nil != RslvPath) { - if (isDirectory) { - *childPath = RslvPath; - v = true; - } - } - } - } else { - if ([fm respondsToSelector:@selector( -createDirectoryAtPath:withIntermediateDirectories:attributes:error: - )]) - { - if ([fm - createDirectoryAtPath:r - withIntermediateDirectories:NO - attributes:nil - error:nil]) - { - *childPath = r; - v = true; - } - } else - if ([fm respondsToSelector: - @selector(createDirectoryAtPath:attributes:)]) - { - if ([fm - createDirectoryAtPath:r - attributes:nil]) - { - *childPath = r; - v = true; - } - } else - { - /* fail */ - } - } - } - - return v; -} -#endif - -@interface NSSavePanel : NSObject -- (NSInteger)runModalForDirectory:(NSString *)path - file:(NSString *)filename; -- (void)setNameFieldStringValue:(NSString *)value; -@end - -#if IncludeSonyNew -LOCALPROC MakeNewDisk(uint32_t L, NSString *drivename) -{ -#if SaveDialogEnable - NSInteger result = NSCancelButton; - NSSavePanel *panel = [NSSavePanel savePanel]; - - BeginDialog(); - - if ([panel respondsToSelector:@selector(setNameFieldStringValue:)]) - { -#if 0 - [panel setNameFieldStringValue: drivename]; - /* available as of OS X 10.6 */ -#endif -#if 0 - [panel performSelector:@selector(setNameFieldStringValue:) - withObject: drivename]; -#endif - [((NSSavePanel *)panel) - setNameFieldStringValue: drivename]; - - result = [panel runModal]; - } else - if ([panel - respondsToSelector: @selector(runModalForDirectory:file:)]) - { -#if 0 - result = [panel runModalForDirectory: nil file: drivename]; - /* - compiler warns deprecated. To avoid warning, and - to still work if removed from SDK, use NSInvocation. - */ -#endif -#if 0 - NSString *sDirName = nil; - SEL sel = @selector(runModalForDirectory:file:); - NSInvocation* invoc = - [NSInvocation invocationWithMethodSignature: - [panel methodSignatureForSelector: sel]]; - [invoc setTarget:panel]; - [invoc setSelector:sel]; - [invoc setArgument:&sDirName atIndex:2]; - [invoc setArgument:&drivename atIndex:3]; - [invoc invoke]; - [invoc getReturnValue: &result]; -#endif - /* an easier way ? seems to work */ - result = [((NSSavePanel *)panel) - runModalForDirectory: nil file: drivename]; - } else - { - /* fail */ - } - - EndDialog(); - - if (NSOKButton == result) { - NSString* filePath = [[panel URL] path]; - MakeNewDisk0(L, filePath); - } -#else /* SaveDialogEnable */ - NSString *sPath; - - if (FindOrMakeNamedChildDirPath(DataPath, "out", &sPath)) { - NSString *filePath = - [sPath stringByAppendingPathComponent: drivename]; - MakeNewDisk0(L, filePath); - } -#endif /* SaveDialogEnable */ -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDiskAtDefault(uint32_t L) -{ - MakeNewDisk(L, @"untitled.dsk"); -} -#endif - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (gTrueBackgroundFlag != gBackgroundFlag) { - gBackgroundFlag = gTrueBackgroundFlag; - if (gTrueBackgroundFlag) { - EnterBackground(); - } else { - LeaveBackground(); - } - } - - if (EmulationWasInterrupted) { - EmulationWasInterrupted = false; - - if (! gTrueBackgroundFlag) { - CheckMouseState(); - } - } - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MouseConstrain(); - } -#endif - -#if 1 - if (gTrueBackgroundFlag && WantFullScreen) { - ToggleWantFullScreen(); - } -#endif - - if (WantScreensChangedCheck) { - WantScreensChangedCheck = false; - - UpdateOpenGLContext(); - -#if 1 - /* - triggered on enter full screen for some - reason in OS X 10.11. so check against - saved rect. - */ - if ((WantFullScreen) - && (! NSEqualRects(SavedScrnBounds, - [[NSScreen mainScreen] frame]))) - { - ToggleWantFullScreen(); - } -#endif - } - - if (CurSpeedStopped != ( - SpeedStopped || (gBackgroundFlag && ! RunInBackground) - )) { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - -#if EnableRecreateW - if (0 - || (UseMagnify != WantMagnify) -#if 1 - || (UseFullScreen != WantFullScreen) -#endif - ) - { - ReCreateMainWindow(); - } -#endif - -#if MayFullScreen - if (GrabMachine != ( -#if 1 - UseFullScreen && -#endif - ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - GrabMachine = ! GrabMachine; - AdjustMachineGrab(); - } -#endif - -#if IncludeSonyNew - if (vSonyNewDiskWanted) { -#if IncludeSonyNameNew - if (vSonyNewDiskName != NotAPbuf) { - NSString *sNewDiskName; - if (MacRomanFileNameToNSString(vSonyNewDiskName, - &sNewDiskName)) - { - MakeNewDisk(vSonyNewDiskSize, sNewDiskName); - } - PbufDispose(vSonyNewDiskName); - vSonyNewDiskName = NotAPbuf; - } else -#endif - { - MakeNewDiskAtDefault(vSonyNewDiskSize); - } - vSonyNewDiskWanted = false; - /* must be done after may have gotten disk */ - } -#endif - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - - if (! gTrueBackgroundFlag) { - if (RequestInsertDisk) { - RequestInsertDisk = false; - InsertADisk0(); - } - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif - - if (HaveCursorHidden != ( -#if MayNotFullScreen - (WantCursorHidden -#if 1 - || UseFullScreen -#endif - ) && -#endif - ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - HaveCursorHidden = ! HaveCursorHidden; - if (HaveCursorHidden) { - HideCursor(); - } else { - ShowCursor(); - } - } - -#if 1 - /* - Check if actual cursor visibility is what it should be. - If move mouse to dock then cursor is made visible, but then - if move directly to our window, cursor is not hidden again. - */ - if (HaveCGCursorIsVisible()) { - /* but only in OS X 10.3 and later */ - /* deprecated in cocoa, but no alternative (?) */ - if (CGCursorIsVisible()) { - if (HaveCursorHidden) { - HideCursor(); - if (CGCursorIsVisible()) { - /* - didn't work, attempt undo so that - hide cursor count won't get large - */ - ShowCursor(); - } - } - } else { - if (! HaveCursorHidden) { - ShowCursor(); - /* - don't check if worked, assume can't decrement - hide cursor count below 0 - */ - } - } - } -#endif -} - -/* --- main program flow --- */ - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -LOCALPROC ProcessEventModifiers(NSEvent *event) -{ - NSUInteger newMods = [event modifierFlags]; - - UpdateKeyboardModifiers(newMods); -} - -LOCALPROC ProcessEventLocation(NSEvent *event) -{ - NSPoint p = [event locationInWindow]; - NSWindow *w = [event window]; - - if (w != Window) { - if (nil != w) { - p = [w convertBaseToScreen: p]; - } - p = [Window convertScreenToBase: p]; - } - p = [NSview convertPoint: p fromView: nil]; - p.y = [NSview frame].size.height - p.y; - MousePositionNotify((int) p.x, (int) p.y); -} - -LOCALPROC ProcessKeyEvent(bool down, NSEvent *event) -{ - uint8_t scancode = [event keyCode]; - - ProcessEventModifiers(event); - Keyboard_UpdateKeyMap2(Keyboard_RemapMac(scancode), down); -} - -LOCALPROC ProcessOneSystemEvent(NSEvent *event) -{ - switch ([event type]) { - case NSLeftMouseDown: - case NSRightMouseDown: - case NSOtherMouseDown: - /* - int button = QZ_OtherMouseButtonToSDL( - [event buttonNumber]); - */ - ProcessEventLocation(event); - ProcessEventModifiers(event); - if (([event window] == Window) - && (! gTrueBackgroundFlag) -#if MayNotFullScreen - && (WantCursorHidden -#if 1 - || UseFullScreen -#endif - ) -#endif - ) - { - MouseButtonSet(true); - } else { - /* doesn't belong to us */ - [NSApp sendEvent: event]; - } - break; - - case NSLeftMouseUp: - case NSRightMouseUp: - case NSOtherMouseUp: - /* - int button = QZ_OtherMouseButtonToSDL( - [event buttonNumber]); - */ - ProcessEventLocation(event); - ProcessEventModifiers(event); - if (! MouseButtonState) { - /* doesn't belong to us */ - [NSApp sendEvent: event]; - } else { - MouseButtonSet(false); - } - break; - - case NSMouseMoved: - { - ProcessEventLocation(event); - ProcessEventModifiers(event); - } - break; - case NSLeftMouseDragged: - case NSRightMouseDragged: - case NSOtherMouseDragged: - if (! MouseButtonState) { - /* doesn't belong to us ? */ - [NSApp sendEvent: event]; - } else { - ProcessEventLocation(event); - ProcessEventModifiers(event); - } - break; - case NSKeyUp: - ProcessKeyEvent(false, event); - break; - case NSKeyDown: - ProcessKeyEvent(true, event); - break; - case NSFlagsChanged: - ProcessEventModifiers(event); - break; - /* case NSScrollWheel: */ - /* case NSSystemDefined: */ - /* case NSAppKitDefined: */ - /* case NSApplicationDefined: */ - /* case NSPeriodic: */ - /* case NSCursorUpdate: */ - default: - [NSApp sendEvent: event]; - } -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ - NSDate *TheUntil; - int i; - NSEvent *event; - NSAutoreleasePool *pool; - - pool = [[NSAutoreleasePool alloc] init]; - - NSDate *TheDistantFuture = [NSDate distantFuture]; - NSDate *TheDistantPast = [NSDate distantPast]; -#if 0 - NSDate *TheNextTick = [NSDate - dateWithTimeIntervalSinceReferenceDate: NextTickChangeTime]; -#endif - - TheUntil = TheDistantPast; - -label_retry: - - i = 32; - while ((--i >= 0) && (nil != (event = - [NSApp nextEventMatchingMask: NSAnyEventMask - untilDate: TheUntil - inMode: NSDefaultRunLoopMode - dequeue: YES]))) - { - ProcessOneSystemEvent(event); - TheUntil = TheDistantPast; - } - - CheckForSavedTasks(); - - if (ForceMacOff) { - goto label_exit; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - TheUntil = TheDistantFuture; - goto label_retry; - } - - if (ExtraTimeNotOver()) { - NSTimeInterval inTimeout = NextTickChangeTime - LatestTime; - if (inTimeout > 0.0) { - struct timespec rqt; - struct timespec rmt; - - rqt.tv_sec = 0; - rqt.tv_nsec = inTimeout * 1000000000.0; - (void) nanosleep(&rqt, &rmt); - } - TheUntil = TheDistantPast; - - goto label_retry; - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - OnTrueTime = TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime); -#endif - -label_exit: - [pool release]; -} - -typedef Boolean (*SecTranslocateIsTranslocatedURL_t)( - CFURLRef path, bool *isTranslocated, CFErrorRef * error); -typedef CFURLRef (*SecTranslocateCreateOriginalPathForURL_t)( - CFURLRef translocatedPath, CFErrorRef * error); - -LOCALFUNC bool setupWorkingDirectory(void) -{ - NSString *myAppDir; - NSString *contentsPath; - NSString *dataPath; - NSBundle *myBundle = [NSBundle mainBundle]; - NSString *myAppPath = [myBundle bundlePath]; - -#if WantUnTranslocate - { - bool isTranslocated; - void *sec_handle = NULL; - SecTranslocateIsTranslocatedURL_t - mySecTranslocateIsTranslocatedURL = NULL; - CFURLRef url = NULL; - SecTranslocateCreateOriginalPathForURL_t - mySecTranslocateCreateOriginalPathForURL = NULL; - CFURLRef untranslocatedURL = NULL; - NSString *realAppPath = NULL; - - if (NULL == (sec_handle = dlopen( - "/System/Library/Frameworks/Security.framework/Security", - RTLD_LAZY))) - { - /* fail */ - } else - if (NULL == (mySecTranslocateIsTranslocatedURL = - dlsym(sec_handle, "SecTranslocateIsTranslocatedURL"))) - { - /* fail */ - } else - if (NULL == (url = - CFURLCreateWithFileSystemPath(kCFAllocatorDefault, - (CFStringRef)myAppPath, kCFURLPOSIXPathStyle, NO))) - { - /* fail */ - } else - if (! mySecTranslocateIsTranslocatedURL(url, &isTranslocated, - NULL)) - { - /* fail */ - } else - if (! isTranslocated) { - /* done */ - } else - if (NULL == (mySecTranslocateCreateOriginalPathForURL = - dlsym(sec_handle, - "SecTranslocateCreateOriginalPathForURL"))) - { - /* fail */ - } else - if (NULL == (untranslocatedURL = - mySecTranslocateCreateOriginalPathForURL(url, NULL))) - { - /* fail */ - } else - if (NULL == (realAppPath = - (NSString *)CFURLCopyFileSystemPath( - untranslocatedURL, kCFURLPOSIXPathStyle))) - { - /* fail */ - } else - { - myAppPath = realAppPath; - } - - if (NULL != realAppPath) { - [realAppPath autorelease]; - } - if (NULL != untranslocatedURL) { - CFRelease(untranslocatedURL); - } - if (NULL != url) { - CFRelease(url); - } - if (NULL != sec_handle) { - if (0 != dlclose(sec_handle)) { - /* dbglog_writeln("dlclose failed"); */ - } - } - } -#endif /* WantUnTranslocate */ - - myAppDir = [myAppPath stringByDeletingLastPathComponent]; - myAppName = [[[myAppPath lastPathComponent] - stringByDeletingPathExtension] retain]; - - DataPath = myAppDir; - if (FindNamedChildDirPath(myAppPath, "Contents", &contentsPath)) - if (FindNamedChildDirPath(contentsPath, "mnvm_dat", &dataPath)) - { - DataPath = dataPath; - } - [DataPath retain]; - - return true; -} - -@interface ClassApplicationDelegate : NSObject -@end - -@implementation ClassApplicationDelegate - -- (BOOL)application:(NSApplication *)theApplication - openFile:(NSString *)filename -{ - (void) Sony_Insert1a(filename); - - return TRUE; -} - -- (void) applicationDidFinishLaunching: (NSNotification *) note -{ - [NSApp stop: nil]; /* stop immediately */ - - { - /* - doesn't actually stop until an event, so make one. - (As suggested by Michiel de Hoon in - http://www.cocoabuilder.com/ post.) - */ - NSEvent* event = [NSEvent - otherEventWithType: NSApplicationDefined - location: NSMakePoint(0, 0) - modifierFlags: 0 - timestamp: 0.0 - windowNumber: 0 - context: nil - subtype: 0 - data1: 0 - data2: 0]; - [NSApp postEvent: event atStart: true]; - } -} - -- (void)applicationDidChangeScreenParameters: - (NSNotification *)aNotification -{ - WantScreensChangedCheck = true; -} - -- (IBAction)performSpecialMoreCommands:(id)sender -{ - DoMoreCommandsMsg(); -} - -- (IBAction)performFileOpen:(id)sender -{ - RequestInsertDisk = true; -} - -- (IBAction)performApplicationAbout:(id)sender -{ - DoAboutMsg(); -} - -@end - -LOCALVAR ClassApplicationDelegate *ApplicationDelegate = nil; - -LOCALFUNC bool InitCocoaStuff(void) -{ - NSApplication *NSApp = [NSApplication sharedApplication]; - /* - in Xcode 6.2, NSApp isn't the same as NSApp, - breaks NSApp setDelegate - */ - - MenuSetup(); - - ApplicationDelegate = [[ClassApplicationDelegate alloc] init]; - [NSApp setDelegate: ApplicationDelegate]; - -#if 0 - [NSApp finishLaunching]; -#endif - /* - If use finishLaunching, after - Hide Mini vMac command, activating from - Dock doesn't bring our window forward. - Using "run" instead fixes this. - As suggested by Hugues De Keyzer in - http://forums.libsdl.org/ post. - SDL 2.0 doesn't use this - technique. Was another solution found? - */ - - [NSApp run]; - /* - our applicationDidFinishLaunching forces - immediate halt. - */ - - return true; -} - -LOCALPROC UnInitCocoaStuff(void) -{ - if (nil != ApplicationDelegate) { - [ApplicationDelegate release]; - } - if (nil != myAppName) { - [myAppName release]; - } - if (nil != DataPath) { - [DataPath release]; - } -} - -/* --- platform independent code can be thought of as going here --- */ - -#include "PROGMAIN.h" - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); - ZapWinStateVars(); -#if SoundEnabled - ZapAudioVars(); -#endif -} - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif - - ReserveAllocOneBlock( - &ScalingBuff, - vMacScreenNumPixels * (vMacScreenDepth > 0) ? 4 : 1, - 5, false - ; - ReserveAllocOneBlock(&CLUT_final, CLUT_finalsz, 5, false); - -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ -#if 0 /* for testing start up error reporting */ - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - return false; -#else - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)calloc(1, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -#endif -} - -LOCALPROC UnallocMemory(void) -{ - if (nullpr != ReserveAllocBigBlock) { - free((char *) ReserveAllocBigBlock); - } -} - -LOCALFUNC bool InitOSGLU(void) -{ - bool IsOk = false; - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - if (AllocMemory()) - if (setupWorkingDirectory()) -#if dbglog_HAVE - if (dbglog_open()) -#endif -#if SoundEnabled - if (Sound_Init()) - /* takes a while to stabilize, do as soon as possible */ -#endif - if (LoadMacRom()) - if (LoadInitialImages()) - if (InitCocoaStuff()) - /* - Can get openFile call backs here - for initial files. - So must load ROM, disk1.dsk, etc first. - */ -#if EmLocalTalk - if (InitLocalTalk()) -#endif - if (InitLocationDat()) - if (Screen_Init()) - if (CreateMainWindow()) - if (WaitForRom()) - { - IsOk = true; - } - - [pool release]; - - return IsOk; -} - -#if dbglog_HAVE && 0 -IMPORTPROC DumpRTC(void); -#endif - -LOCALPROC UnInitOSGLU(void) -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - -#if dbglog_HAVE && 0 - DumpRTC(); -#endif - - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - - RestoreKeyRepeat(); -#if MayFullScreen - UngrabMachine(); -#endif -#if SoundEnabled - Sound_Stop(); -#endif -#if SoundEnabled - Sound_UnInit(); -#endif -#if IncludePbufs - UnInitPbufs(); -#endif - UnInitDrives(); - - ForceShowCursor(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - CheckSavedMacMsg(); - - CloseOpenGLContext(); - CloseMainWindow(); - -#if MayFullScreen - _ShowMenuBar(); -#endif - - UnInitCocoaStuff(); - - UnallocMemory(); - - [pool release]; -} - -int main(int argc, char **argv) -{ - ZapOSGLUVars(); - - if (InitOSGLU()) { - ProgramMain(); - } - UnInitOSGLU(); - - return 0; -} diff --git a/src/UI/_deprecated/MACOSX/OSGLUOSX.c b/src/UI/_deprecated/MACOSX/OSGLUOSX.c deleted file mode 100644 index a8e87bc..0000000 --- a/src/UI/_deprecated/MACOSX/OSGLUOSX.c +++ /dev/null @@ -1,5509 +0,0 @@ -/* - OSGLUOSX.c - - Copyright (C) 2009 Philip Cummins, Richard F. Bannister, - Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for macintosh OS X - - All operating system dependent code for the - Macintosh platform should go here. - - This code is descended from Richard F. Bannister's Macintosh - port of vMac, by Philip Cummins. - - The main entry point 'main' is at the end of this file. -*/ - -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" - -#include "UI/MYOSGLUE.h" - -/* --- adapting to API/ABI version differences --- */ - -/* - if UsingCarbonLib, instead of native Macho, - then some APIs are missing -*/ -#ifndef UsingCarbonLib -#define UsingCarbonLib 0 -#endif - -LOCALVAR CFBundleRef AppServBunRef; - -LOCALVAR bool DidApplicationServicesBun = false; - -LOCALFUNC bool HaveApplicationServicesBun(void) -{ - if (! DidApplicationServicesBun) { - AppServBunRef = CFBundleGetBundleWithIdentifier( - CFSTR("com.apple.ApplicationServices")); - DidApplicationServicesBun = true; - } - return (AppServBunRef != NULL); -} - -#if MayFullScreen || UsingCarbonLib - -LOCALVAR CFBundleRef HIToolboxBunRef; - -LOCALVAR bool DidHIToolboxBunRef = false; - -LOCALFUNC bool HaveHIToolboxBunRef(void) -{ - if (! DidHIToolboxBunRef) { - HIToolboxBunRef = CFBundleGetBundleWithIdentifier( - CFSTR("com.apple.HIToolbox")); - DidHIToolboxBunRef = true; - } - return (HIToolboxBunRef != NULL); -} - -#endif - -LOCALVAR CFBundleRef AGLBunRef; - -LOCALVAR bool DidAGLBunRef = false; - -LOCALFUNC bool HaveAGLBunRef(void) -{ - if (! DidAGLBunRef) { - AGLBunRef = CFBundleGetBundleWithIdentifier( - CFSTR("com.apple.agl")); - DidAGLBunRef = true; - } - return (AGLBunRef != NULL); -} - - -#if MayFullScreen - -/* SetSystemUIModeProcPtr API always not available */ - -typedef UInt32 SystemUIMode; -typedef OptionBits SystemUIOptions; - -enum { - kUIModeNormal = 0, - kUIModeAllHidden = 3 -}; - -enum { - kUIOptionAutoShowMenuBar = 1 << 0, - kUIOptionDisableAppleMenu = 1 << 2, - kUIOptionDisableProcessSwitch = 1 << 3, - kUIOptionDisableForceQuit = 1 << 4, - kUIOptionDisableSessionTerminate = 1 << 5, - kUIOptionDisableHide = 1 << 6 -}; - -typedef OSStatus (*SetSystemUIModeProcPtr) - (SystemUIMode inMode, SystemUIOptions inOptions); -LOCALVAR SetSystemUIModeProcPtr SetSystemUIMode = NULL; -LOCALVAR bool DidSetSystemUIMode = false; - -LOCALFUNC bool HaveSetSystemUIMode(void) -{ - if (! DidSetSystemUIMode) { - if (HaveHIToolboxBunRef()) { - SetSystemUIMode = - (SetSystemUIModeProcPtr) - CFBundleGetFunctionPointerForName( - HIToolboxBunRef, CFSTR("SetSystemUIMode")); - } - DidSetSystemUIMode = true; - } - return (SetSystemUIMode != NULL); -} - -#endif - -/* In 10.1 or later */ - -typedef OSStatus (*LSCopyDisplayNameForRefProcPtr) - (const FSRef *inRef, CFStringRef *outDisplayName); -LOCALVAR LSCopyDisplayNameForRefProcPtr LSCopyDisplayNameForRef - = NULL; -LOCALVAR bool DidLSCopyDisplayNameForRef = false; - -LOCALFUNC bool HaveLSCopyDisplayNameForRef(void) -{ - if (! DidLSCopyDisplayNameForRef) { - if (HaveApplicationServicesBun()) { - LSCopyDisplayNameForRef = - (LSCopyDisplayNameForRefProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("LSCopyDisplayNameForRef")); - } - DidLSCopyDisplayNameForRef = true; - } - return (LSCopyDisplayNameForRef != NULL); -} - -/* In 10.5 or later */ - -typedef GLboolean (*aglSetWindowRefProcPtr) - (AGLContext ctx, WindowRef window); -LOCALVAR aglSetWindowRefProcPtr aglSetWindowRef = NULL; -LOCALVAR bool DidaglSetWindowRef = false; - -LOCALFUNC bool HaveaglSetWindowRef(void) -{ - if (! DidaglSetWindowRef) { - if (HaveAGLBunRef()) { - aglSetWindowRef = - (aglSetWindowRefProcPtr) - CFBundleGetFunctionPointerForName( - AGLBunRef, CFSTR("aglSetWindowRef")); - } - DidaglSetWindowRef = true; - } - return (aglSetWindowRef != NULL); -} - -/* Deprecated as of 10.5 */ - -typedef CGrafPtr _AGLDrawable; -typedef GLboolean (*aglSetDrawableProcPtr) - (AGLContext ctx, _AGLDrawable draw); -LOCALVAR aglSetDrawableProcPtr aglSetDrawable = NULL; -LOCALVAR bool DidaglSetDrawable = false; - -LOCALFUNC bool HaveaglSetDrawable(void) -{ - if (! DidaglSetDrawable) { - if (HaveAGLBunRef()) { - aglSetDrawable = - (aglSetDrawableProcPtr) - CFBundleGetFunctionPointerForName( - AGLBunRef, CFSTR("aglSetDrawable")); - } - DidaglSetDrawable = true; - } - return (aglSetDrawable != NULL); -} - -/* routines not in carbon lib */ - - -#if UsingCarbonLib - -typedef CGDisplayErr -(*CGGetActiveDisplayListProcPtr) ( - CGDisplayCount maxDisplays, - CGDirectDisplayID * activeDspys, - CGDisplayCount * dspyCnt); -LOCALVAR CGGetActiveDisplayListProcPtr CGGetActiveDisplayList = NULL; -LOCALVAR bool DidCGGetActiveDisplayList = false; - -LOCALFUNC bool HaveCGGetActiveDisplayList(void) -{ - if (! DidCGGetActiveDisplayList) { - if (HaveApplicationServicesBun()) { - CGGetActiveDisplayList = - (CGGetActiveDisplayListProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGGetActiveDisplayList")); - } - DidCGGetActiveDisplayList = true; - } - return (CGGetActiveDisplayList != NULL); -} - -#else - -#define HaveCGGetActiveDisplayList() true -#define CGGetActiveDisplayList CGGetActiveDisplayList - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef CGRect -(*CGDisplayBoundsProcPtr) (CGDirectDisplayID display); -LOCALVAR CGDisplayBoundsProcPtr CGDisplayBounds = NULL; -LOCALVAR bool DidCGDisplayBounds = false; - -LOCALFUNC bool HaveCGDisplayBounds(void) -{ - if (! DidCGDisplayBounds) { - if (HaveApplicationServicesBun()) { - CGDisplayBounds = - (CGDisplayBoundsProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGDisplayBounds")); - } - DidCGDisplayBounds = true; - } - return (CGDisplayBounds != NULL); -} - -#else - -#define HaveCGDisplayBounds() true -#define CGDisplayBounds CGDisplayBounds - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef size_t -(*CGDisplayPixelsWideProcPtr) (CGDirectDisplayID display); -LOCALVAR CGDisplayPixelsWideProcPtr CGDisplayPixelsWide = NULL; -LOCALVAR bool DidCGDisplayPixelsWide = false; - -LOCALFUNC bool HaveCGDisplayPixelsWide(void) -{ - if (! DidCGDisplayPixelsWide) { - if (HaveApplicationServicesBun()) { - CGDisplayPixelsWide = - (CGDisplayPixelsWideProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGDisplayPixelsWide")); - } - DidCGDisplayPixelsWide = true; - } - return (CGDisplayPixelsWide != NULL); -} - -#else - -#define HaveCGDisplayPixelsWide() true -#define CGDisplayPixelsWide CGDisplayPixelsWide - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef size_t -(*CGDisplayPixelsHighProcPtr) (CGDirectDisplayID display); -LOCALVAR CGDisplayPixelsHighProcPtr CGDisplayPixelsHigh = NULL; -LOCALVAR bool DidCGDisplayPixelsHigh = false; - -LOCALFUNC bool HaveCGDisplayPixelsHigh(void) -{ - if (! DidCGDisplayPixelsHigh) { - if (HaveApplicationServicesBun()) { - CGDisplayPixelsHigh = - (CGDisplayPixelsHighProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGDisplayPixelsHigh")); - } - DidCGDisplayPixelsHigh = true; - } - return (CGDisplayPixelsHigh != NULL); -} - -#else - -#define HaveCGDisplayPixelsHigh() true -#define CGDisplayPixelsHigh CGDisplayPixelsHigh - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef CGDisplayErr -(*CGDisplayHideCursorProcPtr) (CGDirectDisplayID display); -LOCALVAR CGDisplayHideCursorProcPtr CGDisplayHideCursor = NULL; -LOCALVAR bool DidCGDisplayHideCursor = false; - -LOCALFUNC bool HaveCGDisplayHideCursor(void) -{ - if (! DidCGDisplayHideCursor) { - if (HaveApplicationServicesBun()) { - CGDisplayHideCursor = - (CGDisplayHideCursorProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGDisplayHideCursor")); - } - DidCGDisplayHideCursor = true; - } - return (CGDisplayHideCursor != NULL); -} - -#else - -#define HaveCGDisplayHideCursor() true -#define CGDisplayHideCursor CGDisplayHideCursor - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef CGDisplayErr -(*CGDisplayShowCursorProcPtr) (CGDirectDisplayID display); -LOCALVAR CGDisplayShowCursorProcPtr CGDisplayShowCursor = NULL; -LOCALVAR bool DidCGDisplayShowCursor = false; - -LOCALFUNC bool HaveCGDisplayShowCursor(void) -{ - if (! DidCGDisplayShowCursor) { - if (HaveApplicationServicesBun()) { - CGDisplayShowCursor = - (CGDisplayShowCursorProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGDisplayShowCursor")); - } - DidCGDisplayShowCursor = true; - } - return (CGDisplayShowCursor != NULL); -} - -#else - -#define HaveCGDisplayShowCursor() true -#define CGDisplayShowCursor CGDisplayShowCursor - -#endif /* ! UsingCarbonLib */ - - -#if 0 - -typedef CGDisplayErr (*CGDisplayMoveCursorToPointProcPtr) - (CGDirectDisplayID display, CGPoint point); -LOCALVAR CGDisplayMoveCursorToPointProcPtr CGDisplayMoveCursorToPoint - = NULL; -LOCALVAR bool DidCGDisplayMoveCursorToPoint = false; - -LOCALFUNC bool HaveCGDisplayMoveCursorToPoint(void) -{ - if (! DidCGDisplayMoveCursorToPoint) { - if (HaveApplicationServicesBun()) { - CGDisplayMoveCursorToPoint = - (CGDisplayMoveCursorToPointProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGDisplayMoveCursorToPoint")); - } - DidCGDisplayMoveCursorToPoint = true; - } - return (CGDisplayMoveCursorToPoint != NULL); -} - -#endif /* 0 */ - - -#if UsingCarbonLib - -typedef CGEventErr -(*CGWarpMouseCursorPositionProcPtr) (CGPoint newCursorPosition); -LOCALVAR CGWarpMouseCursorPositionProcPtr CGWarpMouseCursorPosition - = NULL; -LOCALVAR bool DidCGWarpMouseCursorPosition = false; - -LOCALFUNC bool HaveCGWarpMouseCursorPosition(void) -{ - if (! DidCGWarpMouseCursorPosition) { - if (HaveApplicationServicesBun()) { - CGWarpMouseCursorPosition = - (CGWarpMouseCursorPositionProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGWarpMouseCursorPosition")); - } - DidCGWarpMouseCursorPosition = true; - } - return (CGWarpMouseCursorPosition != NULL); -} - -#else - -#define HaveCGWarpMouseCursorPosition() true -#define CGWarpMouseCursorPosition CGWarpMouseCursorPosition - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef CGEventErr -(*CGSetLocalEventsSuppressionIntervalProcPtr) (CFTimeInterval seconds); -LOCALVAR CGSetLocalEventsSuppressionIntervalProcPtr - CGSetLocalEventsSuppressionInterval = NULL; -LOCALVAR bool DidCGSetLocalEventsSuppressionInterval = false; - -LOCALFUNC bool HaveCGSetLocalEventsSuppressionInterval(void) -{ - if (! DidCGSetLocalEventsSuppressionInterval) { - if (HaveApplicationServicesBun()) { - CGSetLocalEventsSuppressionInterval = - (CGSetLocalEventsSuppressionIntervalProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, - CFSTR("CGSetLocalEventsSuppressionInterval")); - } - DidCGSetLocalEventsSuppressionInterval = true; - } - return (CGSetLocalEventsSuppressionInterval != NULL); -} - -#else - -#define HaveCGSetLocalEventsSuppressionInterval() true -#define CGSetLocalEventsSuppressionInterval \ - CGSetLocalEventsSuppressionInterval - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef OSStatus (*CreateStandardAlertProcPtr) ( - AlertType alertType, - CFStringRef error, - CFStringRef explanation, - const AlertStdCFStringAlertParamRec * param, - DialogRef * outAlert -); -LOCALVAR CreateStandardAlertProcPtr CreateStandardAlert = NULL; -LOCALVAR bool DidCreateStandardAlert = false; - -LOCALFUNC bool HaveCreateStandardAlert(void) -{ - if (! DidCreateStandardAlert) { - if (HaveHIToolboxBunRef()) { - CreateStandardAlert = - (CreateStandardAlertProcPtr) - CFBundleGetFunctionPointerForName( - HIToolboxBunRef, CFSTR("CreateStandardAlert")); - } - DidCreateStandardAlert = true; - } - return (CreateStandardAlert != NULL); -} - -#else - -#define HaveCreateStandardAlert() true -#define CreateStandardAlert CreateStandardAlert - -#endif /* ! UsingCarbonLib */ - - -#if UsingCarbonLib - -typedef OSStatus (*RunStandardAlertProcPtr) ( - DialogRef inAlert, - ModalFilterUPP filterProc, - DialogItemIndex * outItemHit -); -LOCALVAR RunStandardAlertProcPtr RunStandardAlert = NULL; -LOCALVAR bool DidRunStandardAlert = false; - -LOCALFUNC bool HaveRunStandardAlert(void) -{ - if (! DidRunStandardAlert) { - if (HaveHIToolboxBunRef()) { - RunStandardAlert = - (RunStandardAlertProcPtr) - CFBundleGetFunctionPointerForName( - HIToolboxBunRef, CFSTR("RunStandardAlert")); - } - DidRunStandardAlert = true; - } - return (RunStandardAlert != NULL); -} - -#else - -#define HaveRunStandardAlert() true -#define RunStandardAlert RunStandardAlert - -#endif /* ! UsingCarbonLib */ - - -typedef CGDirectDisplayID (*CGMainDisplayIDProcPtr)(void); - -LOCALVAR CGMainDisplayIDProcPtr CGMainDisplayID = NULL; -LOCALVAR bool DidCGMainDisplayID = false; - -LOCALFUNC bool HaveCGMainDisplayID(void) -{ - if (! DidCGMainDisplayID) { - if (HaveApplicationServicesBun()) { - CGMainDisplayID = - (CGMainDisplayIDProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGMainDisplayID")); - } - DidCGMainDisplayID = true; - } - return (CGMainDisplayID != NULL); -} - -#ifndef kCGNullDirectDisplay /* not in MPW Headers */ -#define kCGNullDirectDisplay ((CGDirectDisplayID)0) -#endif - -typedef CGError -(*CGDisplayRegisterReconfigurationCallbackProcPtr) ( - CGDisplayReconfigurationCallBack proc, - void *userInfo - ); -LOCALVAR CGDisplayRegisterReconfigurationCallbackProcPtr - CGDisplayRegisterReconfigurationCallback = NULL; -LOCALVAR bool DidCGDisplayRegisterReconfigurationCallback = false; - -LOCALFUNC bool HaveCGDisplayRegisterReconfigurationCallback(void) -{ - if (! DidCGDisplayRegisterReconfigurationCallback) { - if (HaveApplicationServicesBun()) { - CGDisplayRegisterReconfigurationCallback = - (CGDisplayRegisterReconfigurationCallbackProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, - CFSTR("CGDisplayRegisterReconfigurationCallback")); - } - DidCGDisplayRegisterReconfigurationCallback = true; - } - return (CGDisplayRegisterReconfigurationCallback != NULL); -} - - -typedef CGError -(*CGDisplayRemoveReconfigurationCallbackProcPtr) ( - CGDisplayReconfigurationCallBack proc, - void *userInfo - ); -LOCALVAR CGDisplayRemoveReconfigurationCallbackProcPtr - CGDisplayRemoveReconfigurationCallback = NULL; -LOCALVAR bool DidCGDisplayRemoveReconfigurationCallback = false; - -LOCALFUNC bool HaveCGDisplayRemoveReconfigurationCallback(void) -{ - if (! DidCGDisplayRemoveReconfigurationCallback) { - if (HaveApplicationServicesBun()) { - CGDisplayRemoveReconfigurationCallback = - (CGDisplayRemoveReconfigurationCallbackProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, - CFSTR("CGDisplayRemoveReconfigurationCallback")); - } - DidCGDisplayRemoveReconfigurationCallback = true; - } - return (CGDisplayRemoveReconfigurationCallback != NULL); -} - - -typedef boolean_t (*CGCursorIsVisibleProcPtr)(void); - -LOCALVAR CGCursorIsVisibleProcPtr CGCursorIsVisible = NULL; -LOCALVAR bool DidCGCursorIsVisible = false; - -LOCALFUNC bool HaveCGCursorIsVisible(void) -{ - if (! DidCGCursorIsVisible) { - if (HaveApplicationServicesBun()) { - CGCursorIsVisible = - (CGCursorIsVisibleProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGCursorIsVisible")); - } - DidCGCursorIsVisible = true; - } - return (CGCursorIsVisible != NULL); -} - - -/* --- end of adapting to API/ABI version differences --- */ - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memcpy((char *)destPtr, (char *)srcPtr, byteCount); -} - -LOCALPROC PStrFromChar(ps3p r, char x) -{ - r[0] = 1; - r[1] = (char)x; -} - -/* --- mac style errors --- */ - -#define CheckSavetMacErr(result) (mnvm_noErr == (err = (result))) - /* - where 'err' is a variable of type MacErr_t in the function - this is used in - */ - -#define To_tMacErr(result) ((MacErr_t)(uint16_t)(result)) - -#define CheckSaveMacErr(result) (CheckSavetMacErr(To_tMacErr(result))) - - -#include "STRCONST.h" - -#define NeedCell2UnicodeMap 1 - -#include "LANG/INTLCHAR.h" - -LOCALPROC UniCharStrFromSubstCStr(int *L, UniChar *x, char *s) -{ - int i; - int L0; - uint8_t ps[ClStrMaxLength]; - - ClStrFromSubstCStr(&L0, ps, s); - - for (i = 0; i < L0; ++i) { - x[i] = Cell2UnicodeMap[ps[i]]; - } - - *L = L0; -} - -#define NotAfileRef (-1) - -LOCALFUNC MacErr_t MakeFSRefUniChar(FSRef *ParentRef, - UniCharCount fileNameLength, const UniChar *fileName, - bool *isFolder, FSRef *ChildRef) -{ - MacErr_t err; - Boolean isFolder0; - Boolean isAlias; - - if (CheckSaveMacErr(FSMakeFSRefUnicode(ParentRef, - fileNameLength, fileName, kTextEncodingUnknown, - ChildRef))) - if (CheckSaveMacErr(FSResolveAliasFile(ChildRef, - TRUE, &isFolder0, &isAlias))) - { - *isFolder = isFolder0; - } - - return err; -} - -LOCALFUNC MacErr_t MakeFSRefC(FSRef *ParentRef, char *fileName, - bool *isFolder, FSRef *ChildRef) -{ - int L; - UniChar x[ClStrMaxLength]; - - UniCharStrFromSubstCStr(&L, x, fileName); - return MakeFSRefUniChar(ParentRef, L, x, - isFolder, ChildRef); -} - -#if UseActvFile -LOCALFUNC MacErr_t OpenNamedFileInFolderRef(FSRef *ParentRef, - char *fileName, short *refnum) -{ - MacErr_t err; - bool isFolder; - FSRef ChildRef; - HFSUniStr255 forkName; - - if (CheckSavetMacErr(MakeFSRefC(ParentRef, fileName, - &isFolder, &ChildRef))) - if (CheckSaveMacErr(FSGetDataForkName(&forkName))) - if (CheckSaveMacErr(FSOpenFork(&ChildRef, forkName.length, - forkName.unicode, fsRdPerm, refnum))) - { - /* ok */ - } - - return err; -} -#endif - -#if dbglog_HAVE || UseActvFile -LOCALFUNC MacErr_t OpenWriteNamedFileInFolderRef(FSRef *ParentRef, - char *fileName, short *refnum) -{ - MacErr_t err; - bool isFolder; - FSRef ChildRef; - HFSUniStr255 forkName; - int L; - UniChar x[ClStrMaxLength]; - - UniCharStrFromSubstCStr(&L, x, fileName); - err = MakeFSRefUniChar(ParentRef, L, x, &isFolder, &ChildRef); - if (mnvm_fnfErr == err) { - err = To_tMacErr(FSCreateFileUnicode(ParentRef, L, x, 0, NULL, - &ChildRef, NULL)); - } - if (mnvm_noErr == err) { - if (CheckSaveMacErr(FSGetDataForkName(&forkName))) - if (CheckSaveMacErr(FSOpenFork(&ChildRef, forkName.length, - forkName.unicode, fsRdWrPerm, refnum))) - { - /* ok */ - } - } - - return err; -} -#endif - -LOCALFUNC MacErr_t FindNamedChildRef(FSRef *ParentRef, - char *ChildName, FSRef *ChildRef) -{ - MacErr_t err; - bool isFolder; - - if (CheckSavetMacErr(MakeFSRefC(ParentRef, ChildName, - &isFolder, ChildRef))) - { - if (! isFolder) { - err = mnvm_miscErr; - } - } - - return err; -} - -#if UseActvFile || (IncludeSonyNew && ! SaveDialogEnable) -LOCALFUNC MacErr_t FindOrMakeNamedChildRef(FSRef *ParentRef, - char *ChildName, FSRef *ChildRef) -{ - MacErr_t err; - bool isFolder; - int L; - UniChar x[ClStrMaxLength]; - - UniCharStrFromSubstCStr(&L, x, ChildName); - if (CheckSavetMacErr(MakeFSRefUniChar(ParentRef, L, x, - &isFolder, ChildRef))) - { - if (! isFolder) { - err = mnvm_miscErr; - } - } - if (mnvm_fnfErr == err) { - err = To_tMacErr(FSCreateDirectoryUnicode( - ParentRef, L, x, kFSCatInfoNone, NULL, - ChildRef, NULL, NULL)); - } - - return err; -} -#endif - -LOCALVAR FSRef DatDirRef; - -LOCALVAR CFStringRef AppName = NULL; - -LOCALPROC UnInitApplInfo(void) -{ - if (AppName != NULL) { - CFRelease(AppName); - } -} - -LOCALFUNC bool InitApplInfo(void) -{ - ProcessSerialNumber currentProcess = {0, kCurrentProcess}; - FSRef fsRef; - FSRef parentRef; - - if (noErr == GetProcessBundleLocation(¤tProcess, - &fsRef)) - if (noErr == FSGetCatalogInfo(&fsRef, kFSCatInfoNone, - NULL, NULL, NULL, &parentRef)) - { - FSRef ContentsRef; - FSRef DatRef; - - DatDirRef = parentRef; - if (mnvm_noErr == FindNamedChildRef(&fsRef, "Contents", - &ContentsRef)) - if (mnvm_noErr == FindNamedChildRef(&ContentsRef, "mnvm_dat", - &DatRef)) - { - DatDirRef = DatRef; - } - - if (HaveLSCopyDisplayNameForRef()) { - if (noErr == LSCopyDisplayNameForRef(&fsRef, &AppName)) - { - return true; - } - } - - if (noErr == CopyProcessName(¤tProcess, &AppName)) { - return true; - } - } - return false; -} - -/* --- sending debugging info to file --- */ - -#if dbglog_HAVE - -LOCALVAR SInt16 dbglog_File = NotAfileRef; - -LOCALFUNC bool dbglog_open0(void) -{ - MacErr_t err; - - err = OpenWriteNamedFileInFolderRef(&DatDirRef, - "dbglog.txt", &dbglog_File); - - return (mnvm_noErr == err); -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ - ByteCount actualCount; - - if (dbglog_File != NotAfileRef) { - (void) FSWriteFork( - dbglog_File, - fsFromMark, - 0, - L, - s, - &actualCount); - } -} - -LOCALPROC dbglog_close0(void) -{ - if (dbglog_File != NotAfileRef) { - (void) FSSetForkSize(dbglog_File, fsFromMark, 0); - (void) FSCloseFork(dbglog_File); - dbglog_File = NotAfileRef; - } -} - -#endif - -#define WantColorTransValid 1 - -#include "UI/COMOSGLU.h" - -/* --- time, date --- */ - -/* - be sure to avoid getting confused if TickCount - overflows and wraps. -*/ - -#define dbglog_TimeStuff (0 && dbglog_HAVE) - -LOCALVAR uint32_t TrueEmulatedTime = 0; - -LOCALVAR EventTime NextTickChangeTime; - -#define TickDuration (kEventDurationSecond / 60.14742) - -LOCALPROC UpdateTrueEmulatedTime(void) -{ - EventTime LatestTime = GetCurrentEventTime(); - EventTime TimeDiff = LatestTime - NextTickChangeTime; - - if (TimeDiff >= 0.0) { - if (TimeDiff > 16 * TickDuration) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - NextTickChangeTime = LatestTime + TickDuration; - -#if dbglog_TimeStuff - dbglog_writelnNum("emulation interrupted", - TrueEmulatedTime); -#endif - } else { - do { - ++TrueEmulatedTime; - TimeDiff -= TickDuration; - NextTickChangeTime += TickDuration; - } while (TimeDiff >= 0.0); - } - } -} - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -/* LOCALVAR EventTime ETimeBase; */ -LOCALVAR CFAbsoluteTime ATimeBase; -LOCALVAR uint32_t TimeSecBase; - -LOCALFUNC bool CheckDateTime(void) -{ - uint32_t NewMacDateInSecond = TimeSecBase - + (uint32_t)(CFAbsoluteTimeGetCurrent() - ATimeBase); - /* - uint32_t NewMacDateInSecond = TimeSecBase - + (uint32_t)(GetCurrentEventTime() - ETimeBase); - */ - /* - uint32_t NewMacDateInSecond = ((uint32_t)(CFAbsoluteTimeGetCurrent())) - + 3061137600UL; - */ - - if (CurMacDateInSeconds != NewMacDateInSecond) { - CurMacDateInSeconds = NewMacDateInSecond; - return true; - } else { - return false; - } -} - -/* --- parameter buffers --- */ - -#include "UTILS/PBUFSTDC.h" - -/* --- drives --- */ - -LOCALVAR SInt16 Drives[NumDrives]; /* open disk image files */ - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - ByteCount actualCount; - MacErr_t result; - - if (IsWrite) { - result = To_tMacErr(FSWriteFork( - Drives[Drive_No], - fsFromStart, - Sony_Start, - Sony_Count, - Buffer, - &actualCount)); - } else { - result = To_tMacErr(FSReadFork( - Drives[Drive_No], - fsFromStart, - Sony_Start, - Sony_Count, - Buffer, - &actualCount)); - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = actualCount; - } - - return result; -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - SInt64 forkSize; - MacErr_t err = To_tMacErr( - FSGetForkSize(Drives[Drive_No], &forkSize)); - *Sony_Count = forkSize; - return err; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - SInt16 refnum = Drives[Drive_No]; - Drives[Drive_No] = NotAfileRef; - - DiskEjectedNotify(Drive_No); - - (void) FSCloseFork(refnum); - - return mnvm_noErr; -} - -#if IncludeSonyNew -GLOBALOSGLUFUNC MacErr_t vSonyEjectDelete(tDrive Drive_No) -{ - FSRef ref; - MacErr_t err0; - MacErr_t err; - - err0 = To_tMacErr(FSGetForkCBInfo(Drives[Drive_No], 0, - NULL /* iterator */, - NULL /* actualRefNum */, - NULL /* forkInfo */, - &ref /* ref */, - NULL /* outForkName */)); - err = vSonyEject(Drive_No); - - if (mnvm_noErr != err0) { - err = err0; - } else { - (void) FSDeleteObject(&ref); - } - - return err; -} -#endif - -#if IncludeSonyGetName -GLOBALOSGLUFUNC MacErr_t vSonyGetName(tDrive Drive_No, tPbuf *r) -{ - FSRef ref; - HFSUniStr255 outName; - CFStringRef DiskName; - MacErr_t err; - - if (CheckSaveMacErr(FSGetForkCBInfo(Drives[Drive_No], 0, - NULL /* iterator */, - NULL /* actualRefNum */, - NULL /* forkInfo */, - &ref /* ref */, - NULL /* outForkName */))) - if (CheckSaveMacErr(FSGetCatalogInfo(&ref, - kFSCatInfoNone /* whichInfo */, - NULL /* catalogInfo */, - &outName /* outName */, - NULL /* fsSpec */, - NULL /* parentRef */))) - { - DiskName = CFStringCreateWithCharacters( - kCFAllocatorDefault, outName.unicode, - outName.length); - if (NULL != DiskName) { - tPbuf i; - - if (CheckSavetMacErr(PbufNew(outName.length, &i))) { - if (CFStringGetBytes(DiskName, - CFRangeMake(0, outName.length), - kCFStringEncodingMacRoman, - '?', false, - PbufDat[i], - outName.length, - NULL) != outName.length) - { - err = mnvm_miscErr; - } - if (mnvm_noErr != err) { - PbufDispose(i); - } else { - *r = i; - } - } - CFRelease(DiskName); - } - } - - return err; -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEexport(tPbuf i) -{ - MacErr_t err; - ScrapRef scrapRef; - - if (CheckSaveMacErr(ClearCurrentScrap())) - if (CheckSaveMacErr(GetCurrentScrap(&scrapRef))) - if (CheckSaveMacErr(PutScrapFlavor( - scrapRef, - FOUR_CHAR_CODE('TEXT'), - kScrapFlavorMaskNone, - PbufSize[i], - PbufDat[i]))) - { - /* ok */ - } - - PbufDispose(i); - - return err; -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEimport(tPbuf *r) -{ - MacErr_t err; - ScrapRef scrap; - ScrapFlavorFlags flavorFlags; - Size byteCount; - tPbuf i; - - if (CheckSaveMacErr(GetCurrentScrap(&scrap))) - if (CheckSaveMacErr(GetScrapFlavorFlags(scrap, - 'TEXT', &flavorFlags))) - if (CheckSaveMacErr(GetScrapFlavorSize(scrap, - 'TEXT', &byteCount))) - if (CheckSavetMacErr(PbufNew(byteCount, &i))) - { - Size byteCount2 = byteCount; - if (CheckSaveMacErr(GetScrapFlavorData(scrap, - 'TEXT', &byteCount2, - PbufDat[i]))) - { - if (byteCount != byteCount2) { - err = mnvm_miscErr; - } - } - if (mnvm_noErr != err) { - PbufDispose(i); - } else { - *r = i; - } - } - - return err; -} -#endif - - -#if EmLocalTalk - -#include "UTIL/BPFILTER.h" - -#endif - - -/* --- control mode and internationalization --- */ - -#define WantKeyboard_RemapMac 1 - -#include "UI/CONTROLM.h" - - -/* --- video out --- */ - -LOCALVAR WindowPtr gMainWindow = NULL; -LOCALVAR WindowPtr gOldWindow = NULL; - -#if MayFullScreen -LOCALVAR short hOffset; -LOCALVAR short vOffset; -#endif - -#if MayFullScreen -LOCALVAR bool GrabMachine = false; -#endif - -#if 1 -LOCALVAR bool UseFullScreen = (WantInitFullScreen != 0); -#endif - -LOCALVAR bool UseMagnify = (WantInitMagnify != 0); - -LOCALPROC ScaleRect(Rect *r) -{ - r->left *= WindowScale; - r->right *= WindowScale; - r->top *= WindowScale; - r->bottom *= WindowScale; -} - -LOCALPROC SetScrnRectFromCoords(Rect *r, - int16_t top, int16_t left, int16_t bottom, int16_t right) -{ - r->left = left; - r->right = right; - r->top = top; - r->bottom = bottom; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - OffsetRect(r, - ViewHStart, - ViewVStart); - } -#endif - - if (UseMagnify) { - ScaleRect(r); - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - OffsetRect(r, hOffset, vOffset); - } -#endif -} - -LOCALVAR uint8_t * ScalingBuff = nullpr; - -LOCALVAR uint8_t * CLUT_final; - -#define CLUT_finalsz1 (256 * 8) - -#define CLUT_finalClrSz (256 << (5 - vMacScreenDepth)) - -#define CLUT_finalsz ((CLUT_finalClrSz > CLUT_finalsz1) \ - ? CLUT_finalClrSz : CLUT_finalsz1) - -#define CLUT_finalsz CLUT_finalsz1 - - -#define ScrnMapr_DoMap UpdateBWLuminanceCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 3 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - - -#define ScrnMapr_DoMap UpdateMappedColorCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnTrns_DoTrans UpdateTransColorCopy -#define ScrnTrns_Src GetCurDrawBuff() -#define ScrnTrns_Dst ScalingBuff -#define ScrnTrns_SrcDepth vMacScreenDepth -#define ScrnTrns_DstDepth 5 -#define ScrnTrns_DstZLo 1 - -#include "HW/SCREEN/SCRNTRNS.h" - -LOCALPROC UpdateLuminanceCopy(int16_t top, int16_t left, - int16_t bottom, int16_t right) -{ - int i; - - if (vMacScreenDepth > 0 && UseColorMode) { - - if (vMacScreenDepth < 4) { - if (! ColorTransValid) { - int j; - int k; - uint32_t * p4; - - p4 = (uint32_t *)CLUT_final; - for (i = 0; i < 256; ++i) { - for (k = 1 << (3 - vMacScreenDepth); --k >= 0; ) { - j = (i >> (k << vMacScreenDepth)) & (CLUT_size - 1); - *p4++ = (((long)CLUT_reds[j] & 0xFF00) << 16) - | (((long)CLUT_greens[j] & 0xFF00) << 8) - | ((long)CLUT_blues[j] & 0xFF00); - } - } - ColorTransValid = true; - } - UpdateMappedColorCopy(top, left, bottom, right); - } else { - UpdateTransColorCopy(top, left, bottom, right); - } - } else { - if (! ColorTransValid) { - int k; - uint8_t * p4 = (uint8_t *)CLUT_final; - - for (i = 0; i < 256; ++i) { - for (k = 8; --k >= 0; ) { - *p4++ = ((i >> k) & 0x01) - 1; - } - } - ColorTransValid = true; - } - - UpdateBWLuminanceCopy(top, left, bottom, right); - } -} - -LOCALVAR AGLContext ctx = NULL; -LOCALVAR short GLhOffset; -LOCALVAR short GLvOffset; - -#ifndef UseAGLdoublebuff -#define UseAGLdoublebuff 0 -#endif - -LOCALPROC DrawWithOpenGL(uint16_t top, uint16_t left, uint16_t bottom, uint16_t right) -{ - if (NULL == ctx) { - /* oops */ - } else if (GL_TRUE != aglSetCurrentContext(ctx)) { - /* err = aglReportError() */ - } else { - int16_t top2; - int16_t left2; - -#if UseAGLdoublebuff - /* redraw all */ - top = 0; - left = 0; - bottom = vMacScreenHeight; - right = vMacScreenWidth; -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - if (top < ViewVStart) { - top = ViewVStart; - } - if (left < ViewHStart) { - left = ViewHStart; - } - if (bottom > ViewVStart + ViewVSize) { - bottom = ViewVStart + ViewVSize; - } - if (right > ViewHStart + ViewHSize) { - right = ViewHStart + ViewHSize; - } - - if ((top >= bottom) || (left >= right)) { - goto label_exit; - } - } -#endif - - top2 = top; - left2 = left; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - left2 -= ViewHStart; - top2 -= ViewVStart; - } -#endif - - if (UseMagnify) { - top2 *= WindowScale; - left2 *= WindowScale; - } - -#if 0 - glClear(GL_COLOR_BUFFER_BIT); - glBitmap(vMacScreenWidth, - vMacScreenHeight, - 0, - 0, - 0, - 0, - (const GLubyte *)GetCurDrawBuff()); -#endif -#if 1 - UpdateLuminanceCopy(top, left, bottom, right); - glRasterPos2i(GLhOffset + left2, GLvOffset - top2); -#if 0 != vMacScreenDepth - if (UseColorMode) { - glDrawPixels(right - left, - bottom - top, - GL_RGBA, - GL_UNSIGNED_INT_8_8_8_8, - ScalingBuff + (left + top * vMacScreenWidth) * 4 - ); - } else -#endif - { - glDrawPixels(right - left, - bottom - top, - GL_LUMINANCE, - GL_UNSIGNED_BYTE, - ScalingBuff + (left + top * vMacScreenWidth) - ); - } -#endif - -#if 0 /* a very quick and dirty check of where drawing */ - glDrawPixels(right - left, - 1, - GL_RED, - GL_UNSIGNED_BYTE, - ScalingBuff + (left + top * vMacScreenWidth) - ); - - glDrawPixels(1, - bottom - top, - GL_RED, - GL_UNSIGNED_BYTE, - ScalingBuff + (left + top * vMacScreenWidth) - ); -#endif - -#if UseAGLdoublebuff - aglSwapBuffers(ctx); -#else - glFlush(); -#endif - } - -#if MayFullScreen -label_exit: - ; -#endif -} - -LOCALPROC Update_Screen(void) -{ - DrawWithOpenGL(0, 0, vMacScreenHeight, vMacScreenWidth); -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - DrawWithOpenGL(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - - -LOCALVAR bool MouseIsOutside = false; - /* - MouseIsOutside true if sure mouse outside our window. If in - our window, or not sure, set false. - */ - -LOCALVAR bool WantCursorHidden = false; - -LOCALPROC MousePositionNotify(Point NewMousePos) -{ - /* - Not MouseIsOutside includes in the title bar, etc, so have - to check if in content area. - */ - - Rect r; - bool ShouldHaveCursorHidden = ! MouseIsOutside; - - GetWindowBounds(gMainWindow, kWindowContentRgn, &r); - - NewMousePos.h -= r.left; - NewMousePos.v -= r.top; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePos.h -= hOffset; - NewMousePos.v -= vOffset; - } -#endif - - if (UseMagnify) { - NewMousePos.h /= WindowScale; - NewMousePos.v /= WindowScale; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePos.h += ViewHStart; - NewMousePos.v += ViewVStart; - } -#endif - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MousePositionSetDelta(NewMousePos.h - SavedMouseH, - NewMousePos.v - SavedMouseV); - SavedMouseH = NewMousePos.h; - SavedMouseV = NewMousePos.v; - } else -#endif - { - if (NewMousePos.h < 0) { - NewMousePos.h = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePos.h >= vMacScreenWidth) { - NewMousePos.h = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePos.v < 0) { - NewMousePos.v = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePos.v >= vMacScreenHeight) { - NewMousePos.v = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePos.h, NewMousePos.v); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC CheckMouseState(void) -{ - Point NewMousePos; - GetGlobalMouse(&NewMousePos); - /* - Deprecated, but haven't found usable replacement. - Between window deactivate and then reactivate, - mouse can move without getting kEventMouseMoved. - Also no way to get initial position. - (Also don't get kEventMouseMoved after - using menu bar. Or while using menubar, but - that isn't too important.) - */ - MousePositionNotify(NewMousePos); -} - -LOCALVAR bool gLackFocusFlag = false; -LOCALVAR bool gWeAreActive = false; - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ -#if EnableFSMouseMotion - if (HaveMouseMotion) { - AutoScrollScreen(); - } -#endif - DrawChangesAndClear(); -} - -LOCALVAR bool CurSpeedStopped = true; - -/* --- keyboard --- */ - -LOCALVAR UInt32 SavedModifiers = 0; - -LOCALPROC UpdateKeyboardModifiers(UInt32 theModifiers) -{ - UInt32 ChangedModifiers = theModifiers ^ SavedModifiers; - - if (0 != ChangedModifiers) { - if (0 != (ChangedModifiers & shiftKey)) { - Keyboard_UpdateKeyMap2(MKC_formac_Shift, - (shiftKey & theModifiers) != 0); - } - if (0 != (ChangedModifiers & cmdKey)) { - Keyboard_UpdateKeyMap2(MKC_formac_Command, - (cmdKey & theModifiers) != 0); - } - if (0 != (ChangedModifiers & alphaLock)) { - Keyboard_UpdateKeyMap2(MKC_formac_CapsLock, - (alphaLock & theModifiers) != 0); - } - if (0 != (ChangedModifiers & optionKey)) { - Keyboard_UpdateKeyMap2(MKC_formac_Option, - (optionKey & theModifiers) != 0); - } - if (0 != (ChangedModifiers & controlKey)) { - Keyboard_UpdateKeyMap2(MKC_formac_Control, - (controlKey & theModifiers) != 0); - } - - SavedModifiers = theModifiers; - } -} - -LOCALPROC ReconnectKeyCodes3(void) -{ - /* - turn off any modifiers (other than alpha) - that were turned on by drag and drop, - unless still being held down. - */ - - UInt32 theModifiers = GetCurrentKeyModifiers(); - - UpdateKeyboardModifiers(theModifiers - & (SavedModifiers | alphaLock)); - - SavedModifiers = theModifiers; -} - -/* --- display utilities --- */ - -/* DoForEachDisplay adapted from Apple Technical Q&A QA1168 */ - -typedef void -(*ForEachDisplayProcPtr) (CGDirectDisplayID display); - -LOCALPROC DoForEachDisplay0(CGDisplayCount dspCount, - CGDirectDisplayID *displays, ForEachDisplayProcPtr p) -{ - CGDisplayCount i; - - if (noErr == CGGetActiveDisplayList(dspCount, - displays, &dspCount)) - { - for (i = 0; i < dspCount; ++i) { - p(displays[i]); - } - } -} - -LOCALPROC DoForEachDisplay(ForEachDisplayProcPtr p) -{ - CGDisplayCount dspCount = 0; - - if (HaveCGGetActiveDisplayList() - && (noErr == CGGetActiveDisplayList(0, NULL, &dspCount))) - { - if (dspCount <= 2) { - CGDirectDisplayID displays[2]; - DoForEachDisplay0(dspCount, displays, p); - } else { - CGDirectDisplayID *displays = - calloc((size_t)dspCount, sizeof(CGDirectDisplayID)); - if (NULL != displays) { - DoForEachDisplay0(dspCount, displays, p); - free(displays); - } - } - } -} - -LOCALVAR void *datp; - -LOCALPROC MainDisplayIDProc(CGDirectDisplayID display) -{ - CGDirectDisplayID *p = (CGDirectDisplayID *)datp; - - if (kCGNullDirectDisplay == *p) { - *p = display; - } -} - -LOCALFUNC CGDirectDisplayID MainDisplayID(void) -{ - if (HaveCGMainDisplayID()) { - return CGMainDisplayID(); - } else { - /* for before OS X 10.2 */ - CGDirectDisplayID r = kCGNullDirectDisplay; - void *savedatp = datp; - datp = (void *)&r; - DoForEachDisplay(MainDisplayIDProc); - datp = savedatp; - return r; - } -} - -/* --- cursor hiding --- */ - -#if 0 -LOCALPROC ShowCursorProc(CGDirectDisplayID display) -{ - (void) CGDisplayShowCursor(display); -} -#endif - -LOCALPROC ShowCursor(void) -{ -#if 0 - /* ShowCursor(); deprecated */ - DoForEachDisplay(ShowCursorProc); -#endif - if (HaveCGDisplayShowCursor()) { - (void) CGDisplayShowCursor(MainDisplayID()); - /* documentation now claims argument ignored */ - } -} - -#if 0 -LOCALPROC HideCursorProc(CGDirectDisplayID display) -{ - (void) CGDisplayHideCursor(display); -} -#endif - -LOCALPROC HideCursor(void) -{ -#if 0 - /* HideCursor(); deprecated */ - DoForEachDisplay(HideCursorProc); -#endif - if (HaveCGDisplayHideCursor()) { - (void) CGDisplayHideCursor(MainDisplayID()); - /* documentation now claims argument ignored */ - } -} - -LOCALVAR bool HaveCursorHidden = false; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - ShowCursor(); - } -} - -/* --- cursor moving --- */ - -LOCALPROC SetCursorArrow(void) -{ - SetThemeCursor(kThemeArrowCursor); -} - -#if EnableMoveMouse -LOCALFUNC bool MoveMouse(int16_t h, int16_t v) -{ - Point CurMousePos; - Rect r; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h -= ViewHStart; - v -= ViewVStart; - } -#endif - - if (UseMagnify) { - h *= WindowScale; - v *= WindowScale; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h += hOffset; - v += vOffset; - } -#endif - - GetWindowBounds(gMainWindow, kWindowContentRgn, &r); - CurMousePos.h = r.left + h; - CurMousePos.v = r.top + v; - - /* - This method from SDL_QuartzWM.m, "Simple DirectMedia Layer", - Copyright (C) 1997-2003 Sam Lantinga - */ - if (HaveCGSetLocalEventsSuppressionInterval()) { - if (noErr != CGSetLocalEventsSuppressionInterval(0.0)) { - /* don't use MacMsg which can call MoveMouse */ - } - } - if (HaveCGWarpMouseCursorPosition()) { - CGPoint pt; - pt.x = CurMousePos.h; - pt.y = CurMousePos.v; - if (noErr != CGWarpMouseCursorPosition(pt)) { - /* don't use MacMsg which can call MoveMouse */ - } - } -#if 0 - if (HaveCGDisplayMoveCursorToPoint()) { - CGPoint pt; - pt.x = CurMousePos.h; - pt.y = CurMousePos.v; - if (noErr != CGDisplayMoveCursorToPoint( - MainDisplayID(), pt)) - { - /* don't use MacMsg which can call MoveMouse */ - } - } -#endif - - return true; -} -#endif - -#if EnableFSMouseMotion -LOCALPROC AdjustMouseMotionGrab(void) -{ - if (gMainWindow != NULL) { -#if MayFullScreen - if (GrabMachine) { - /* - if magnification changes, need to reset, - even if HaveMouseMotion already true - */ - if (MoveMouse(ViewHStart + (ViewHSize / 2), - ViewVStart + (ViewVSize / 2))) - { - SavedMouseH = ViewHStart + (ViewHSize / 2); - SavedMouseV = ViewVStart + (ViewVSize / 2); - HaveMouseMotion = true; - } - } else -#endif - { - if (HaveMouseMotion) { - (void) MoveMouse(CurMouseH, CurMouseV); - HaveMouseMotion = false; - } - } - } -} -#endif - -#if EnableFSMouseMotion -LOCALPROC MouseConstrain(void) -{ - int16_t shiftdh; - int16_t shiftdv; - - if (SavedMouseH < ViewHStart + (ViewHSize / 4)) { - shiftdh = ViewHSize / 2; - } else if (SavedMouseH > ViewHStart + ViewHSize - (ViewHSize / 4)) { - shiftdh = - ViewHSize / 2; - } else { - shiftdh = 0; - } - if (SavedMouseV < ViewVStart + (ViewVSize / 4)) { - shiftdv = ViewVSize / 2; - } else if (SavedMouseV > ViewVStart + ViewVSize - (ViewVSize / 4)) { - shiftdv = - ViewVSize / 2; - } else { - shiftdv = 0; - } - if ((shiftdh != 0) || (shiftdv != 0)) { - SavedMouseH += shiftdh; - SavedMouseV += shiftdv; - if (! MoveMouse(SavedMouseH, SavedMouseV)) { - HaveMouseMotion = false; - } - } -} -#endif - -#if 0 -LOCALFUNC bool InitMousePosition(void) -{ - /* - Since there doesn't seem to be any nondeprecated - way to get initial cursor position, instead - start by moving cursor to known position. - */ - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - CurMouseH = 16; - CurMouseV = 16; - WantCursorHidden = true; - (void) MoveMouse(CurMouseH, CurMouseV); - } -#endif - - return true; -} -#endif - -/* --- time, date, location, part 2 --- */ - -#include "UTIL/DATE2SEC.h" - -LOCALFUNC bool InitLocationDat(void) -{ -#if AutoLocation || AutoTimeZone - MachineLocation loc; - - ReadLocation(&loc); -#if AutoLocation - CurMacLatitude = (uint32_t)loc.latitude; - CurMacLongitude = (uint32_t)loc.longitude; -#endif -#if AutoTimeZone - CurMacDelta = (uint32_t)loc.u.gmtDelta; -#endif -#endif - - { - CFTimeZoneRef tz = CFTimeZoneCopySystem(); - if (tz) { - /* CFAbsoluteTime */ ATimeBase = CFAbsoluteTimeGetCurrent(); - /* ETimeBase = GetCurrentEventTime(); */ - { - CFGregorianDate d = CFAbsoluteTimeGetGregorianDate( - ATimeBase, tz); - double floorsec = floor(d.second); - ATimeBase -= (d.second - floorsec); - /* ETimeBase -= (d.second - floorsec); */ - TimeSecBase = Date2MacSeconds(floorsec, - d.minute, d.hour, - d.day, d.month, d.year); - - (void) CheckDateTime(); - } - CFRelease(tz); - } - } - - OnTrueTime = TrueEmulatedTime; - - return true; -} - -LOCALPROC StartUpTimeAdjust(void) -{ - NextTickChangeTime = GetCurrentEventTime() + TickDuration; -} - -/* --- sound --- */ - -#if SoundEnabled - -#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */ -#define kSoundBuffers (1 << kLn2SoundBuffers) -#define kSoundBuffMask (kSoundBuffers - 1) - -#define DesiredMinFilledSoundBuffs 3 - /* - if too big then sound lags behind emulation. - if too small then sound will have pauses. - */ - -#define kLnOneBuffLen 9 -#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen) -#define kOneBuffLen (1UL << kLnOneBuffLen) -#define kAllBuffLen (1UL << kLnAllBuffLen) -#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3) -#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3) -#define kOneBuffSz (1UL << kLnOneBuffSz) -#define kAllBuffSz (1UL << kLnAllBuffSz) -#define kOneBuffMask (kOneBuffLen - 1) -#define kAllBuffMask (kAllBuffLen - 1) -#define dbhBufferSize (kAllBuffSz + kOneBuffSz) - -#define dbglog_SoundStuff (0 && dbglog_HAVE) -#define dbglog_SoundBuffStats (0 && dbglog_HAVE) - -LOCALVAR tpSoundSamp TheSoundBuffer = nullpr; -volatile static uint16_t ThePlayOffset; -volatile static uint16_t TheFillOffset; -volatile static uint16_t MinFilledSoundBuffs; -#if dbglog_SoundBuffStats -LOCALVAR uint16_t MaxFilledSoundBuffs; -#endif -LOCALVAR uint16_t TheWriteOffset; - -LOCALPROC Sound_Start0(void) -{ - /* Reset variables */ - ThePlayOffset = 0; - TheFillOffset = 0; - TheWriteOffset = 0; - MinFilledSoundBuffs = kSoundBuffers + 1; -#if dbglog_SoundBuffStats - MaxFilledSoundBuffs = 0; -#endif -} - -GLOBALOSGLUFUNC tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL) -{ - uint16_t ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset); - uint16_t WriteBuffContig = - kOneBuffLen - (TheWriteOffset & kOneBuffMask); - - if (WriteBuffContig < n) { - n = WriteBuffContig; - } - if (ToFillLen < n) { - /* overwrite previous buffer */ -#if dbglog_SoundStuff - dbglog_writeln("sound buffer over flow"); -#endif - TheWriteOffset -= kOneBuffLen; - } - - *actL = n; - return TheSoundBuffer + (TheWriteOffset & kAllBuffMask); -} - -#if 4 == kLn2SoundSampSz -LOCALPROC ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -LOCALPROC Sound_WroteABlock(void) -{ -#if (4 == kLn2SoundSampSz) - uint16_t PrevWriteOffset = TheWriteOffset - kOneBuffLen; - tpSoundSamp p = TheSoundBuffer + (PrevWriteOffset & kAllBuffMask); -#endif - -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_WroteABlock"); -#endif - - ConvertSoundBlockToNative(p); - - TheFillOffset = TheWriteOffset; - -#if dbglog_SoundBuffStats - { - uint16_t ToPlayLen = TheFillOffset - - ThePlayOffset; - uint16_t ToPlayBuffs = ToPlayLen >> kLnOneBuffLen; - - if (ToPlayBuffs > MaxFilledSoundBuffs) { - MaxFilledSoundBuffs = ToPlayBuffs; - } - } -#endif -} - -LOCALFUNC bool Sound_EndWrite0(uint16_t actL) -{ - bool v; - - TheWriteOffset += actL; - - if (0 != (TheWriteOffset & kOneBuffMask)) { - v = false; - } else { - /* just finished a block */ - - Sound_WroteABlock(); - - v = true; - } - - return v; -} - -LOCALPROC Sound_SecondNotify0(void) -{ - if (MinFilledSoundBuffs <= kSoundBuffers) { - if (MinFilledSoundBuffs > DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too high"); -#endif - NextTickChangeTime += TickDuration; - } else if (MinFilledSoundBuffs < DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too low"); -#endif - ++TrueEmulatedTime; - } -#if dbglog_SoundBuffStats - dbglog_writelnNum("MinFilledSoundBuffs", - MinFilledSoundBuffs); - dbglog_writelnNum("MaxFilledSoundBuffs", - MaxFilledSoundBuffs); - MaxFilledSoundBuffs = 0; -#endif - MinFilledSoundBuffs = kSoundBuffers + 1; - } -} - -LOCALPROC RampSound(tpSoundSamp p, - trSoundSamp BeginVal, trSoundSamp EndVal) -{ - int i; - uint32_t v = (((uint32_t)BeginVal) << kLnOneBuffLen) + (kLnOneBuffLen >> 1); - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ = v >> kLnOneBuffLen; - v = v + EndVal - BeginVal; - } -} - -#if 4 == kLn2SoundSampSz -#define ConvertSoundSampleFromNative(v) ((v) + 0x8000) -#else -#define ConvertSoundSampleFromNative(v) (v) -#endif - -struct SoundR { - tpSoundSamp fTheSoundBuffer; - volatile uint16_t (*fPlayOffset); - volatile uint16_t (*fFillOffset); - volatile uint16_t (*fMinFilledSoundBuffs); - - volatile bool PlayingBuffBlock; - volatile trSoundSamp lastv; - volatile bool wantplaying; - volatile bool StartingBlocks; - - CmpSoundHeader /* ExtSoundHeader */ soundHeader; -}; -typedef struct SoundR SoundR; - - -/* - Some of this code descended from CarbonSndPlayDB, an - example from Apple, as found being used in vMac for Mac OS. -*/ - -LOCALPROC InsertSndDoCommand(SndChannelPtr chan, SndCommand * newCmd) -{ - if (-1 == chan->qHead) { - chan->qHead = chan->qTail; - } - - if (1 <= chan->qHead) { - chan->qHead--; - } else { - chan->qHead = chan->qTail; - } - - chan->queue[chan->qHead] = *newCmd; -} - -/* call back */ static pascal void -Sound_CallBack(SndChannelPtr theChannel, SndCommand * theCallBackCmd) -{ - SoundR *datp = - (SoundR *)(theCallBackCmd->param2); - bool wantplaying0 = datp->wantplaying; - trSoundSamp v0 = datp->lastv; - -#if dbglog_SoundStuff - dbglog_writeln("Enter Sound_CallBack"); -#endif - - if (datp->PlayingBuffBlock) { - /* finish with last sample */ -#if dbglog_SoundStuff - dbglog_writeln("done with sample"); -#endif - - *datp->fPlayOffset += kOneBuffLen; - datp->PlayingBuffBlock = false; - } - - if ((! wantplaying0) && (kCenterSound == v0)) { -#if dbglog_SoundStuff - dbglog_writeln("terminating"); -#endif - } else { - SndCommand playCmd; - tpSoundSamp p; - trSoundSamp v1 = v0; - bool WantRamp = false; - uint16_t CurPlayOffset = *datp->fPlayOffset; - uint16_t ToPlayLen = *datp->fFillOffset - CurPlayOffset; - uint16_t FilledSoundBuffs = ToPlayLen >> kLnOneBuffLen; - - if (FilledSoundBuffs < *datp->fMinFilledSoundBuffs) { - *datp->fMinFilledSoundBuffs = FilledSoundBuffs; - } - - if (! wantplaying0) { -#if dbglog_SoundStuff - dbglog_writeln("playing end transistion"); -#endif - v1 = kCenterSound; - - WantRamp = true; - } else - if (datp->StartingBlocks) { -#if dbglog_SoundStuff - dbglog_writeln("playing start block"); -#endif - - if ((ToPlayLen >> kLnOneBuffLen) < 12) { - datp->StartingBlocks = false; -#if dbglog_SoundStuff - dbglog_writeln("have enough samples to start"); -#endif - - p = datp->fTheSoundBuffer - + (CurPlayOffset & kAllBuffMask); - v1 = ConvertSoundSampleFromNative(*p); - } - - WantRamp = true; - } else - if (0 == FilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("playing under run"); -#endif - - WantRamp = true; - } else - { - /* play next sample */ - p = datp->fTheSoundBuffer - + (CurPlayOffset & kAllBuffMask); - datp->PlayingBuffBlock = true; - v1 = - ConvertSoundSampleFromNative(*(p + kOneBuffLen - 1)); -#if dbglog_SoundStuff - dbglog_writeln("playing sample"); -#endif - } - - if (WantRamp) { - p = datp->fTheSoundBuffer + kAllBuffLen; - -#if dbglog_SoundStuff - dbglog_writelnNum("v0", v0); - dbglog_writelnNum("v1", v1); -#endif - - RampSound(p, v0, v1); - ConvertSoundBlockToNative(p); - } - - datp->soundHeader.samplePtr = (Ptr)p; - datp->soundHeader.numFrames = - (unsigned long)kOneBuffLen; - - /* Insert our callback command */ - InsertSndDoCommand (theChannel, theCallBackCmd); - -#if 0 - { - int i; - tpSoundSamp pS = - (tpSoundSamp)datp->soundHeader.samplePtr; - - for (i = datp->soundHeader.numFrames; --i >= 0; ) - { - fprintf(stderr, "%d\n", *pS++); - } - } -#endif - - /* Play the next buffer */ - playCmd.cmd = bufferCmd; - playCmd.param1 = 0; - playCmd.param2 = (long)&(datp->soundHeader); - InsertSndDoCommand (theChannel, &playCmd); - - datp->lastv = v1; - } -} - -LOCALVAR SoundR cur_audio; - -LOCALVAR SndCallBackUPP gCarbonSndPlayDoubleBufferCallBackUPP = NULL; - -LOCALVAR SndChannelPtr sndChannel = NULL; /* our sound channel */ - -LOCALPROC Sound_Start(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("Sound_Start"); -#endif - - if (NULL == sndChannel) { - SndCommand callBack; - SndChannelPtr chan = NULL; - - cur_audio.wantplaying = false; - cur_audio.StartingBlocks = false; - - Sound_Start0(); - - SndNewChannel(&chan, sampledSynth, initMono, nil); - if (NULL != chan) { - sndChannel = chan; - - cur_audio.PlayingBuffBlock = false; - cur_audio.lastv = kCenterSound; - cur_audio.StartingBlocks = true; - cur_audio.wantplaying = true; - - callBack.cmd = callBackCmd; - callBack.param1 = 0; /* unused */ - callBack.param2 = (long)&cur_audio; - - sndChannel->callBack = - gCarbonSndPlayDoubleBufferCallBackUPP; - - (void) SndDoCommand (sndChannel, &callBack, true); - } - } -} - -LOCALPROC Sound_Stop(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Stop"); -#endif - - if (NULL != sndChannel) { - uint16_t retry_limit = 50; /* half of a second */ - SCStatus r; - - cur_audio.wantplaying = false; -#if dbglog_SoundStuff - dbglog_writeln("cleared wantplaying"); -#endif - -label_retry: - r.scChannelBusy = false; /* what is this for? */ - if (noErr != SndChannelStatus(sndChannel, - sizeof(SCStatus), &r)) - { - /* fail */ - } else - if ((! r.scChannelBusy) && (kCenterSound == cur_audio.lastv)) { - /* done */ - - /* - observed reporting not busy unexpectedly, - so also check lastv. - */ - } else - if (0 == --retry_limit) { -#if dbglog_SoundStuff - dbglog_writeln("retry limit reached"); -#endif - /* - don't trust SndChannelStatus, make - sure don't get in infinite loop. - */ - - /* done */ - } else - { - /* - give time back, particularly important - if got here on a suspend event. - */ - struct timespec rqt; - struct timespec rmt; - -#if dbglog_SoundStuff - dbglog_writeln("busy, so sleep"); -#endif - - rqt.tv_sec = 0; - rqt.tv_nsec = 10000000; - (void) nanosleep(&rqt, &rmt); - - goto label_retry; - } - - SndDisposeChannel(sndChannel, true); - sndChannel = NULL; - } - -#if dbglog_SoundStuff - dbglog_writeln("leave Sound_Stop"); -#endif -} - -#define SOUND_SAMPLERATE rate22khz - /* = 0x56EE8BA3 = (7833600 * 2 / 704) << 16 */ - -LOCALFUNC bool Sound_Init(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Init"); -#endif - - cur_audio.fTheSoundBuffer = TheSoundBuffer; - - cur_audio.fPlayOffset = &ThePlayOffset; - cur_audio.fFillOffset = &TheFillOffset; - cur_audio.fMinFilledSoundBuffs = &MinFilledSoundBuffs; - cur_audio.wantplaying = false; - - /* Init basic per channel information */ - cur_audio.soundHeader.sampleRate = SOUND_SAMPLERATE; - /* sample rate */ - cur_audio.soundHeader.numChannels = 1; /* one channel */ - cur_audio.soundHeader.loopStart = 0; - cur_audio.soundHeader.loopEnd = 0; - cur_audio.soundHeader.encode = cmpSH /* extSH */; - cur_audio.soundHeader.baseFrequency = kMiddleC; - cur_audio.soundHeader.numFrames = - (unsigned long)kOneBuffLen; - /* cur_audio.soundHeader.AIFFSampleRate = 0; */ - /* unused */ - cur_audio.soundHeader.markerChunk = nil; - cur_audio.soundHeader.futureUse2 = 0; - cur_audio.soundHeader.stateVars = nil; - cur_audio.soundHeader.leftOverSamples = nil; - cur_audio.soundHeader.compressionID = 0; - /* no compression */ - cur_audio.soundHeader.packetSize = 0; - /* no compression */ - cur_audio.soundHeader.snthID = 0; - cur_audio.soundHeader.sampleSize = (1 << kLn2SoundSampSz); - /* 8 or 16 bits per sample */ - cur_audio.soundHeader.sampleArea[0] = 0; -#if 3 == kLn2SoundSampSz - cur_audio.soundHeader.format = kSoundNotCompressed; -#elif 4 == kLn2SoundSampSz - cur_audio.soundHeader.format = k16BitNativeEndianFormat; -#else -#error "unsupported kLn2SoundSampSz" -#endif - cur_audio.soundHeader.samplePtr = (Ptr)TheSoundBuffer; - - gCarbonSndPlayDoubleBufferCallBackUPP = - NewSndCallBackUPP(Sound_CallBack); - if (gCarbonSndPlayDoubleBufferCallBackUPP != NULL) { - - Sound_Start(); - /* - This should be taken care of by LeaveSpeedStopped, - but since takes a while to get going properly, - start early. - */ - - return true; - } - return false; -} - -GLOBALOSGLUPROC Sound_EndWrite(uint16_t actL) -{ - if (Sound_EndWrite0(actL)) { - } -} - -LOCALPROC Sound_SecondNotify(void) -{ - if (sndChannel != NULL) { - Sound_SecondNotify0(); - } -} - -#endif - - -LOCALPROC AdjustGLforSize(int h, int v) -{ - if (GL_TRUE != aglSetCurrentContext(ctx)) { - /* err = aglReportError() */ - } else { - - glClearColor (0.0, 0.0, 0.0, 1.0); - -#if 1 - glViewport(0, 0, h, v); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, h, 0, v, -1.0, 1.0); - glMatrixMode(GL_MODELVIEW); -#endif - - glColor3f(0.0, 0.0, 0.0); - if (UseMagnify) { - glPixelZoom(WindowScale, - WindowScale); - } else { - glPixelZoom(1, -1); - } - glPixelStorei(GL_UNPACK_ROW_LENGTH, vMacScreenWidth); - - glClear(GL_COLOR_BUFFER_BIT); - - if (GL_TRUE != aglSetCurrentContext(NULL)) { - /* err = aglReportError() */ - } - - ScreenChangedAll(); - } -} - -LOCALVAR bool WantScreensChangedCheck = false; - -LOCALPROC UpdateOpenGLContext(void) -{ - if (NULL == ctx) { - /* oops */ - } else if (GL_TRUE != aglSetCurrentContext(ctx)) { - /* err = aglReportError() */ - } else { - aglUpdateContext(ctx); - } -} - -#if 0 /* some experiments */ -LOCALVAR CGrafPtr GrabbedPort = NULL; -#endif - -#if 0 -LOCALPROC AdjustMainScreenGrab(void) -{ - if (GrabMachine) { - if (NULL == GrabbedPort) { - /* CGDisplayCapture(MainDisplayID()); */ - CGCaptureAllDisplays(); - /* CGDisplayHideCursor( MainDisplayID() ); */ - GrabbedPort = - CreateNewPortForCGDisplayID((UInt32)MainDisplayID()); - LockPortBits (GrabbedPort); - } - } else { - if (GrabbedPort != NULL) { - UnlockPortBits (GrabbedPort); - /* CGDisplayShowCursor( MainDisplayID() ); */ - /* CGDisplayRelease(MainDisplayID()); */ - CGReleaseAllDisplays(); - GrabbedPort = NULL; - } - } -} -#endif - -#if 0 -typedef CGDisplayErr (*CGReleaseAllDisplaysProcPtr) - (void); - -LOCALPROC ReleaseAllDisplays(void) -{ - if (HaveApplicationServicesBun()) { - CGReleaseAllDisplaysProcPtr ReleaseAllDisplaysProc = - (CGReleaseAllDisplaysProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGReleaseAllDisplays")); - if (ReleaseAllDisplaysProc != NULL) { - ReleaseAllDisplaysProc(); - } - } -} - -typedef CGDisplayErr (*CGCaptureAllDisplaysProcPtr) - (void); - -LOCALPROC CaptureAllDisplays(void) -{ - if (HaveApplicationServicesBun()) { - CGCaptureAllDisplaysProcPtr CaptureAllDisplaysProc = - (CGCaptureAllDisplaysProcPtr) - CFBundleGetFunctionPointerForName( - AppServBunRef, CFSTR("CGCaptureAllDisplays")); - if (CaptureAllDisplaysProc != NULL) { - CaptureAllDisplaysProc(); - } - } -} -#endif - -LOCALVAR AGLPixelFormat window_fmt = NULL; -LOCALVAR AGLContext window_ctx = NULL; - -#ifndef UseAGLfullscreen -#define UseAGLfullscreen 0 -#endif - -#if UseAGLfullscreen -LOCALVAR AGLPixelFormat fullscreen_fmt = NULL; -LOCALVAR AGLContext fullscreen_ctx = NULL; -#endif - -#if UseAGLfullscreen -LOCALPROC MaybeFullScreen(void) -{ - if ( -#if 1 - UseFullScreen && -#endif - (NULL == fullscreen_ctx) - && HaveCGDisplayPixelsWide() - && HaveCGDisplayPixelsHigh()) - { - static const GLint fullscreen_attrib[] = {AGL_RGBA, - AGL_NO_RECOVERY, - AGL_FULLSCREEN, - AGL_SINGLE_RENDERER, AGL_ACCELERATED, -#if UseAGLdoublebuff - AGL_DOUBLEBUFFER, -#endif - AGL_NONE}; - GDHandle theDevice; - CGDirectDisplayID CurMainDisplayID = MainDisplayID(); - - DMGetGDeviceByDisplayID( - (DisplayIDType)CurMainDisplayID, &theDevice, false); - fullscreen_fmt = aglChoosePixelFormat( - &theDevice, 1, fullscreen_attrib); - if (NULL == fullscreen_fmt) { - /* err = aglReportError() */ - } else { - fullscreen_ctx = aglCreateContext(fullscreen_fmt, NULL); - if (NULL == fullscreen_ctx) { - /* err = aglReportError() */ - } else { - /* CaptureAllDisplays(); */ - if (GL_TRUE != aglSetFullScreen(fullscreen_ctx, - 0, 0, 0, 0)) - { - /* err = aglReportError() */ - } else { - Rect r; - - int h = CGDisplayPixelsWide(CurMainDisplayID); - int v = CGDisplayPixelsHigh(CurMainDisplayID); - - GetWindowBounds(gMainWindow, kWindowContentRgn, - &r); - - GLhOffset = r.left + hOffset; - GLvOffset = v - (r.top + vOffset); - - ctx = fullscreen_ctx; - AdjustGLforSize(h, v); - return; - } - /* ReleaseAllDisplays(); */ - - if (GL_TRUE != aglDestroyContext(fullscreen_ctx)) { - /* err = aglReportError() */ - } - fullscreen_ctx = NULL; - } - - aglDestroyPixelFormat (fullscreen_fmt); - fullscreen_fmt = NULL; - } - } -} -#endif - -#if UseAGLfullscreen -LOCALPROC NoFullScreen(void) -{ - if (fullscreen_ctx != NULL) { - Rect r; - int h; - int v; - - GetWindowBounds(gMainWindow, kWindowContentRgn, &r); - - h = r.right - r.left; - v = r.bottom - r.top; - - GLhOffset = hOffset; - GLvOffset = v - vOffset; - - ctx = window_ctx; - - AdjustGLforSize(h, v); - - Update_Screen(); - - if (fullscreen_ctx != NULL) { - if (GL_TRUE != aglDestroyContext(fullscreen_ctx)) { - /* err = aglReportError() */ - } - fullscreen_ctx = NULL; - } - if (fullscreen_fmt != NULL) { - aglDestroyPixelFormat(fullscreen_fmt); - fullscreen_fmt = NULL; - } - } -} -#endif - -#if UseAGLfullscreen -LOCALPROC AdjustOpenGLGrab(void) -{ - if (GrabMachine) { - MaybeFullScreen(); - } else { - NoFullScreen(); - } -} -#endif - -#if MayFullScreen -LOCALPROC AdjustMachineGrab(void) -{ -#if EnableFSMouseMotion - AdjustMouseMotionGrab(); -#endif -#if UseAGLfullscreen - AdjustOpenGLGrab(); -#endif -#if 0 - AdjustMainScreenGrab(); -#endif -} -#endif - -#if MayFullScreen -LOCALPROC UngrabMachine(void) -{ - GrabMachine = false; - AdjustMachineGrab(); -} -#endif - -LOCALPROC ClearWeAreActive(void) -{ - if (gWeAreActive) { - gWeAreActive = false; - - DisconnectKeyCodes2(); - - SavedModifiers &= alphaLock; - - MouseButtonSet(false); - -#if MayFullScreen - UngrabMachine(); -#endif - - ForceShowCursor(); - } -} - -/* --- basic dialogs --- */ - -LOCALFUNC CFStringRef CFStringCreateFromSubstCStr(char *s) -{ - int L; - UniChar x[ClStrMaxLength]; - - UniCharStrFromSubstCStr(&L, x, s); - - return CFStringCreateWithCharacters(kCFAllocatorDefault, x, L); -} - -#define kStandardAlert 128 - -LOCALPROC CheckSavedMacMsg(void) -{ - /* called only on quit, if error saved but not yet reported */ - - if (nullpr != SavedBriefMsg) { - if (HaveCreateStandardAlert() && HaveRunStandardAlert()) { - CFStringRef briefMsgu = CFStringCreateFromSubstCStr( - SavedBriefMsg); - if (NULL != briefMsgu) { - CFStringRef longMsgu = CFStringCreateFromSubstCStr( - SavedLongMsg); - if (NULL != longMsgu) { - DialogRef TheAlert; - OSStatus err = CreateStandardAlert( - (SavedFatalMsg) ? kAlertStopAlert - : kAlertCautionAlert, - briefMsgu, longMsgu, NULL, - &TheAlert); - if (noErr == err) { - (void) RunStandardAlert(TheAlert, NULL, NULL); - } - CFRelease(longMsgu); - } - CFRelease(briefMsgu); - } - } - - SavedBriefMsg = nullpr; - } -} - -LOCALVAR bool gTrueBackgroundFlag = false; - -LOCALPROC BeginDialog(void) -{ - ClearWeAreActive(); -} - -LOCALPROC EndDialog(void) -{ -} - -/* --- hide/show menubar --- */ - -#if MayFullScreen -LOCALPROC _HideMenuBar(void) -{ - if (HaveSetSystemUIMode()) { - (void) SetSystemUIMode(kUIModeAllHidden, - kUIOptionDisableAppleMenu -#if GrabKeysFullScreen - | kUIOptionDisableProcessSwitch -#if GrabKeysMaxFullScreen /* dangerous !! */ - | kUIOptionDisableForceQuit - | kUIOptionDisableSessionTerminate -#endif -#endif - ); - } else { - if (IsMenuBarVisible()) { - HideMenuBar(); - } - } -} -#endif - -#if MayFullScreen -LOCALPROC _ShowMenuBar(void) -{ - if (HaveSetSystemUIMode()) { - (void) SetSystemUIMode(kUIModeNormal, - 0); - } else { - if (! IsMenuBarVisible()) { - ShowMenuBar(); - } - } -} -#endif - -/* --- drives, part 2 --- */ - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] - need not have valid value when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; - } -} - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -LOCALFUNC MacErr_t Sony_Insert0(SInt16 refnum, bool locked) -{ - tDrive Drive_No; - - if (! FirstFreeDisk(&Drive_No)) { - (void) FSCloseFork(refnum); - return mnvm_tmfoErr; - } else { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); - return mnvm_noErr; - } -} - -LOCALPROC ReportStandardOpenDiskError(MacErr_t err) -{ - if (mnvm_noErr != err) { - if (mnvm_tmfoErr == err) { - MacMsg(kStrTooManyImagesTitle, - kStrTooManyImagesMessage, false); - } else if (mnvm_opWrErr == err) { - MacMsg(kStrImageInUseTitle, - kStrImageInUseMessage, false); - } else { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } -} - -LOCALFUNC MacErr_t InsertADiskFromFSRef(FSRef *theRef) -{ - MacErr_t err; - HFSUniStr255 forkName; - SInt16 refnum; - bool locked = false; - - if (CheckSaveMacErr(FSGetDataForkName(&forkName))) { - err = To_tMacErr(FSOpenFork(theRef, forkName.length, - forkName.unicode, fsRdWrPerm, &refnum)); - switch (err) { - case mnvm_permErr: - case mnvm_wrPermErr: - case mnvm_afpAccessDenied: - locked = true; - err = To_tMacErr(FSOpenFork(theRef, forkName.length, - forkName.unicode, fsRdPerm, &refnum)); - break; - default: - break; - } - if (mnvm_noErr == err) { - err = Sony_Insert0(refnum, locked); - } - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromRefNum(SInt16 refnum) -{ - MacErr_t err; - ByteCount actualCount; - - if (mnvm_noErr != (err = To_tMacErr( - FSReadFork(refnum, fsFromStart, 0, - kROM_Size, ROM, &actualCount)))) - { - if (mnvm_eofErr == err) { - MacMsgOverride(kStrShortROMTitle, kStrShortROMMessage); - } else { - MacMsgOverride(kStrNoReadROMTitle, kStrNoReadROMMessage); - } - } else - { - err = ROM_IsValid(); - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromFSRef(FSRef *theRef) -{ - MacErr_t err; - HFSUniStr255 forkName; - SInt16 refnum; - - if (mnvm_noErr == (err = - To_tMacErr(FSGetDataForkName(&forkName)))) - if (mnvm_noErr == (err = To_tMacErr( - FSOpenFork(theRef, forkName.length, - forkName.unicode, fsRdPerm, &refnum)))) - { - err = LoadMacRomFromRefNum(refnum); - - (void) FSCloseFork(refnum); - } - - return err; -} - -LOCALFUNC MacErr_t InsertADiskFromFSRef1(FSRef *theRef) -{ - MacErr_t err; - - if (! ROM_loaded) { - err = LoadMacRomFromFSRef(theRef); - } else { - err = InsertADiskFromFSRef(theRef); - } - - return err; -} - -LOCALFUNC MacErr_t InsertDisksFromDocList(AEDescList *docList) -{ - MacErr_t err = mnvm_noErr; - long itemsInList; - long index; - AEKeyword keyword; - DescType typeCode; - FSRef theRef; - Size actualSize; - - if (CheckSaveMacErr(AECountItems(docList, &itemsInList))) { - for (index = 1; index <= itemsInList; ++index) { - if (CheckSaveMacErr(AEGetNthPtr(docList, index, typeFSRef, - &keyword, &typeCode, (Ptr)&theRef, - sizeof(FSRef), &actualSize))) - if (CheckSavetMacErr(InsertADiskFromFSRef1(&theRef))) - { - } - if (mnvm_noErr != err) { - goto label_fail; - } - } - } - -label_fail: - return err; -} - -LOCALFUNC MacErr_t InsertADiskFromNameEtc(FSRef *ParentRef, - char *fileName) -{ - MacErr_t err; - bool isFolder; - FSRef ChildRef; - - if (CheckSavetMacErr(MakeFSRefC(ParentRef, fileName, - &isFolder, &ChildRef))) - { - if (isFolder) { - err = mnvm_miscErr; - } else { - if (CheckSavetMacErr(InsertADiskFromFSRef(&ChildRef))) { - /* ok */ - } - } - } - - return err; -} - -#if IncludeSonyNew -LOCALFUNC MacErr_t WriteZero(SInt16 refnum, uint32_t L) -{ -#define ZeroBufferSize 2048 - MacErr_t err = mnvm_noErr; - uint32_t i; - uint8_t buffer[ZeroBufferSize]; - ByteCount actualCount; - uint32_t offset = 0; - - memset(&buffer, 0, ZeroBufferSize); - - while (L > 0) { - i = (L > ZeroBufferSize) ? ZeroBufferSize : L; - if (! CheckSaveMacErr(FSWriteFork(refnum, - fsFromStart, - offset, - i, - buffer, - &actualCount))) - { - goto label_fail; - } - L -= i; - offset += i; - } - -label_fail: - return err; -} -#endif - -#if IncludeSonyNew -LOCALFUNC MacErr_t CreateFileCFStringRef(FSRef *saveFileParent, - CFStringRef saveFileName, FSRef *NewRef) -{ - MacErr_t err; - UniChar buffer[255]; - - CFIndex len = CFStringGetLength(saveFileName); - - if (len > 255) { - len = 255; - } - - CFStringGetCharacters(saveFileName, CFRangeMake(0, len), buffer); - - err = To_tMacErr(FSMakeFSRefUnicode(saveFileParent, len, - buffer, kTextEncodingUnknown, NewRef)); - if (mnvm_fnfErr == err) { /* file is not there yet - create it */ - err = To_tMacErr(FSCreateFileUnicode(saveFileParent, - len, buffer, 0, NULL, NewRef, NULL)); - } - - return err; -} -#endif - -#if IncludeSonyNew -LOCALFUNC MacErr_t MakeNewDisk0(FSRef *saveFileParent, - CFStringRef saveFileName, uint32_t L) -{ - MacErr_t err; - FSRef NewRef; - HFSUniStr255 forkName; - SInt16 refnum; - - if (CheckSavetMacErr( - CreateFileCFStringRef(saveFileParent, saveFileName, &NewRef))) - { - if (CheckSaveMacErr(FSGetDataForkName(&forkName))) - if (CheckSaveMacErr(FSOpenFork(&NewRef, forkName.length, - forkName.unicode, fsRdWrPerm, &refnum))) - { - SInt64 forkSize = L; - if (CheckSaveMacErr( - FSSetForkSize(refnum, fsFromStart, forkSize))) - /* - zero out fork. It looks like this is already done, - but documentation says this isn't guaranteed. - */ - if (CheckSavetMacErr(WriteZero(refnum, L))) - { - err = Sony_Insert0(refnum, false); - refnum = NotAfileRef; - } - if (NotAfileRef != refnum) { - (void) FSCloseFork(refnum); - } - } - if (mnvm_noErr != err) { - (void) FSDeleteObject(&NewRef); - } - } - - return err; -} -#endif - -#if IncludeSonyNameNew -LOCALFUNC CFStringRef CFStringCreateWithPbuf(tPbuf i) -{ - return CFStringCreateWithBytes(NULL, - (UInt8 *)PbufDat[i], PbufSize[i], - kCFStringEncodingMacRoman, false); -} -#endif - -pascal Boolean NavigationFilterProc( - AEDesc* theItem, void* info, void* NavCallBackUserData, - NavFilterModes theNavFilterModes); -pascal Boolean NavigationFilterProc( - AEDesc* theItem, void* info, void* NavCallBackUserData, - NavFilterModes theNavFilterModes) -{ - /* NavFileOrFolderInfo* theInfo = (NavFileOrFolderInfo*)info; */ - UnusedParam(theItem); - UnusedParam(info); - UnusedParam(theNavFilterModes); - UnusedParam(NavCallBackUserData); - - return true; /* display all items */ -} - - -pascal void NavigationEventProc( - NavEventCallbackMessage callBackSelector, - NavCBRecPtr callBackParms, void *NavCallBackUserData); -pascal void NavigationEventProc( - NavEventCallbackMessage callBackSelector, - NavCBRecPtr callBackParms, void *NavCallBackUserData) -{ - UnusedParam(NavCallBackUserData); - - switch (callBackSelector) { - case kNavCBEvent: /* probably not needed in os x */ - switch (callBackParms->eventData.eventDataParms.event->what) - { - case updateEvt: - { - WindowPtr which = - (WindowPtr)callBackParms - ->eventData.eventDataParms.event - ->message; - - BeginUpdate(which); - - if (which == gMainWindow) { - Update_Screen(); - } - - EndUpdate(which); - } - break; - } - break; -#if 0 - case kNavCBUserAction: - { - NavUserAction userAction = NavDialogGetUserAction( - callBackParms->context); - switch (userAction) { - case kNavUserActionOpen: { - /* got something to open */ - break; - } - } - } - break; - case kNavCBTerminate: - break; -#endif - } -} - -LOCALPROC InsertADisk0(void) -{ - NavDialogRef theOpenDialog; - NavDialogCreationOptions dialogOptions; - NavReplyRecord theReply; - NavTypeListHandle openList = NULL; - NavEventUPP gEventProc = NewNavEventUPP(NavigationEventProc); - NavObjectFilterUPP filterUPP = - NewNavObjectFilterUPP(NavigationFilterProc); - - if (noErr == NavGetDefaultDialogCreationOptions(&dialogOptions)) { - dialogOptions.modality = kWindowModalityAppModal; - dialogOptions.optionFlags |= kNavDontAutoTranslate; - dialogOptions.optionFlags &= ~ kNavAllowPreviews; - if (noErr == NavCreateGetFileDialog(&dialogOptions, - (NavTypeListHandle)openList, - gEventProc, NULL, - filterUPP, NULL, &theOpenDialog)) - { - BeginDialog(); - (void) NavDialogRun(theOpenDialog); - EndDialog(); - if (noErr == NavDialogGetReply(theOpenDialog, - &theReply)) - { - if (theReply.validRecord) { - ReportStandardOpenDiskError( - InsertDisksFromDocList(&theReply.selection)); - } - (void) NavDisposeReply(&theReply); - } - NavDialogDispose(theOpenDialog); - } - } - - DisposeNavEventUPP(gEventProc); - DisposeNavObjectFilterUPP(filterUPP); -} - -#if IncludeSonyNew -LOCALPROC MakeNewDisk(uint32_t L, CFStringRef NewDiskName) -{ -#if SaveDialogEnable - NavDialogRef theSaveDialog; - NavDialogCreationOptions dialogOptions; - NavReplyRecord theReply; - NavEventUPP gEventProc = NewNavEventUPP(NavigationEventProc); - - if (noErr == NavGetDefaultDialogCreationOptions(&dialogOptions)) { - dialogOptions.modality = kWindowModalityAppModal; - dialogOptions.saveFileName = NewDiskName; - if (noErr == NavCreatePutFileDialog(&dialogOptions, - 'TEXT', 'MPS ', - gEventProc, NULL, - &theSaveDialog)) - { - BeginDialog(); - (void) NavDialogRun(theSaveDialog); - EndDialog(); - if (noErr == NavDialogGetReply(theSaveDialog, - &theReply)) - { - if (theReply.validRecord) { - long itemsInList; - AEKeyword keyword; - DescType typeCode; - FSRef theRef; - Size actualSize; - - if (noErr == AECountItems( - &theReply.selection, &itemsInList)) - { - if (itemsInList == 1) { - if (noErr == AEGetNthPtr( - &theReply.selection, 1, typeFSRef, - &keyword, &typeCode, (Ptr)&theRef, - sizeof(FSRef), &actualSize)) - { - ReportStandardOpenDiskError( - MakeNewDisk0(&theRef, - theReply.saveFileName, L)); - } - } - } - } - (void) NavDisposeReply(&theReply); - } - NavDialogDispose(theSaveDialog); - } - } - - DisposeNavEventUPP(gEventProc); -#else /* SaveDialogEnable */ - FSRef OutRef; - - if (mnvm_noErr == FindOrMakeNamedChildRef(&DatDirRef, - "out", &OutRef)) - { - MakeNewDisk0(&OutRef, NewDiskName, L); - } -#endif /* SaveDialogEnable */ -} -#endif - -LOCALFUNC MacErr_t LoadMacRomFromNameFolder(FSRef *ParentRef, - char *fileName) -{ - MacErr_t err; - bool isFolder; - FSRef ChildRef; - - if (mnvm_noErr == (err = - MakeFSRefC(ParentRef, fileName, &isFolder, &ChildRef))) - if (mnvm_noErr == (err = - LoadMacRomFromFSRef(&ChildRef))) - { - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromPrefDir(void) -{ - MacErr_t err; - FSRef PrefRef; - FSRef GryphelRef; - FSRef ROMsRef; - - if (mnvm_noErr == (err = To_tMacErr(FSFindFolder(kUserDomain, - kPreferencesFolderType, kDontCreateFolder, &PrefRef)))) - if (mnvm_noErr == (err = FindNamedChildRef(&PrefRef, - "Gryphel", &GryphelRef))) - if (mnvm_noErr == (err = FindNamedChildRef(&GryphelRef, - "mnvm_rom", &ROMsRef))) - if (mnvm_noErr == (err = LoadMacRomFromNameFolder(&ROMsRef, - RomFileName))) - { - /* ok */ - } - - return err; -} - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if (mnvm_fnfErr == (err = - LoadMacRomFromNameFolder(&DatDirRef, RomFileName))) - if (mnvm_fnfErr == (err = - LoadMacRomFromPrefDir())) - { - } - - return true; /* keep launching Mini vMac, regardless */ -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - MacErr_t err = mnvm_noErr; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - return false; - } else { - char s[16] = "disk?.dsk"; - - s[4] = '0' + i; - - if (! CheckSavetMacErr(InsertADiskFromNameEtc(&DatDirRef, s))) - { - if (mnvm_fnfErr != err) { - ReportStandardOpenDiskError(err); - } - /* stop on first error (including file not found) */ - return false; - } - } - - return true; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - - return true; -} - -#if UseActvFile - -#define ActvCodeFileName "act_1" - -LOCALFUNC MacErr_t OpenActvCodeFile(SInt16 *refnum) -{ - MacErr_t err; - FSRef PrefRef; - FSRef GryphelRef; - FSRef ActRef; - - if (CheckSaveMacErr(FSFindFolder(kUserDomain, - kPreferencesFolderType, kDontCreateFolder, &PrefRef))) - if (CheckSavetMacErr(FindNamedChildRef(&PrefRef, - "Gryphel", &GryphelRef))) - if (CheckSavetMacErr(FindNamedChildRef(&GryphelRef, - "mnvm_act", &ActRef))) - if (CheckSavetMacErr(OpenNamedFileInFolderRef(&ActRef, - ActvCodeFileName, refnum))) - { - /* ok */ - } - - return err; -} - -LOCALFUNC MacErr_t ActvCodeFileLoad(uint8_t * p) -{ - MacErr_t err; - SInt16 refnum; - - if (CheckSavetMacErr(OpenActvCodeFile(&refnum))) { - ByteCount actualCount; - err = To_tMacErr(FSReadFork(refnum, fsFromStart, 0, - ActvCodeFileLen, p, &actualCount)); - (void) FSCloseFork(refnum); - } - - return err; -} - -LOCALFUNC MacErr_t ActvCodeFileSave(uint8_t * p) -{ - MacErr_t err; - SInt16 refnum; - FSRef PrefRef; - FSRef GryphelRef; - FSRef ActRef; - ByteCount count = ActvCodeFileLen; - - if (CheckSaveMacErr(FSFindFolder(kUserDomain, - kPreferencesFolderType, kDontCreateFolder, &PrefRef))) - if (CheckSavetMacErr(FindOrMakeNamedChildRef(&PrefRef, - "Gryphel", &GryphelRef))) - if (CheckSavetMacErr(FindOrMakeNamedChildRef(&GryphelRef, - "mnvm_act", &ActRef))) - if (CheckSavetMacErr(OpenWriteNamedFileInFolderRef(&ActRef, - ActvCodeFileName, &refnum))) - { - ByteCount actualCount; - err = To_tMacErr(FSWriteFork(refnum, fsFromStart, 0, - count, p, &actualCount)); - (void) FSCloseFork(refnum); - } - - return err; -} - -#endif /* UseActvFile */ - -/* --- utilities for adapting to the environment --- */ - -LOCALPROC GetScreenBitsBounds(Rect *r) -{ - if (HaveCGDisplayBounds()) { - CGRect cgr = CGDisplayBounds(MainDisplayID()); - - r->left = cgr.origin.x; - r->top = cgr.origin.y; - r->right = cgr.origin.x + cgr.size.width; - r->bottom = cgr.origin.y + cgr.size.height; - } -} - -#if MayNotFullScreen -LOCALPROC InvalWholeWindow(WindowRef mw) -{ - Rect bounds; - - GetWindowPortBounds(mw, &bounds); - InvalWindowRect(mw, &bounds); -} -#endif - -#if MayNotFullScreen -LOCALPROC SetMacWindContRect(WindowRef mw, Rect *r) -{ - (void) SetWindowBounds (mw, kWindowContentRgn, r); - InvalWholeWindow(mw); -} -#endif - -#if MayNotFullScreen -LOCALFUNC bool GetWindowTitleBounds(WindowRef mw, Rect *r) -{ - return (noErr == GetWindowBounds(mw, kWindowTitleBarRgn, r)); -} -#endif - -#if EnableRecreateW && MayNotFullScreen -LOCALFUNC bool GetWindowContBounds(WindowRef mw, Rect *r) -{ - return (noErr == GetWindowBounds(mw, kWindowContentRgn, r)); -} -#endif - -LOCALPROC GetGrayRgnBounds(Rect *r) -{ - GetRegionBounds(GetGrayRgn(), (Rect *)r); -} - -#define openOnly 1 -#define openPrint 2 - -LOCALFUNC bool GotRequiredParams(AppleEvent *theAppleEvent) -{ - DescType typeCode; - Size actualSize; - OSErr theErr; - - theErr = AEGetAttributePtr(theAppleEvent, keyMissedKeywordAttr, - typeWildCard, &typeCode, NULL, 0, &actualSize); - if (errAEDescNotFound == theErr) { /* No more required params. */ - return true; - } else if (noErr == theErr) { /* More required params! */ - return /* CheckSysCode(errAEEventNotHandled) */ false; - } else { /* Unexpected Error! */ - return /* CheckSysCode(theErr) */ false; - } -} - -LOCALFUNC bool GotRequiredParams0(AppleEvent *theAppleEvent) -{ - DescType typeCode; - Size actualSize; - OSErr theErr; - - theErr = AEGetAttributePtr(theAppleEvent, keyMissedKeywordAttr, - typeWildCard, &typeCode, NULL, 0, &actualSize); - if (errAEDescNotFound == theErr) { /* No more required params. */ - return true; - } else if (noErr == theErr) { /* More required params! */ - return true; /* errAEEventNotHandled; */ /*^*/ - } else { /* Unexpected Error! */ - return /* CheckSysCode(theErr) */ false; - } -} - -/* call back */ static pascal OSErr OpenOrPrintFiles( - AppleEvent *theAppleEvent, AppleEvent *reply, long aRefCon) -{ - /* - Adapted from IM VI: AppleEvent Manager: - Handling Required AppleEvents - */ - AEDescList docList; - - UnusedParam(reply); - UnusedParam(aRefCon); - /* put the direct parameter (a list of descriptors) into docList */ - if (noErr == (AEGetParamDesc(theAppleEvent, keyDirectObject, - typeAEList, &docList))) - { - if (GotRequiredParams0(theAppleEvent)) { - /* Check for missing required parameters */ - /* printIt = (openPrint == aRefCon) */ - ReportStandardOpenDiskError( - InsertDisksFromDocList(&docList)); - } - /* vCheckSysCode */ (void) (AEDisposeDesc(&docList)); - } - - return /* GetASysResultCode() */ 0; -} - -/* call back */ static pascal OSErr DoOpenEvent( - AppleEvent *theAppleEvent, AppleEvent *reply, long aRefCon) -/* - This is the alternative to getting an - open document event on startup. -*/ -{ - UnusedParam(reply); - UnusedParam(aRefCon); - if (GotRequiredParams0(theAppleEvent)) { - } - return /* GetASysResultCode() */ 0; - /* Make sure there are no additional "required" parameters. */ -} - - -/* call back */ static pascal OSErr DoQuitEvent( - AppleEvent *theAppleEvent, AppleEvent *reply, long aRefCon) -{ - UnusedParam(reply); - UnusedParam(aRefCon); - if (GotRequiredParams(theAppleEvent)) { - RequestMacOff = true; - } - - return /* GetASysResultCode() */ 0; -} - -LOCALFUNC bool InstallEventHandler(AEEventClass theAEEventClass, - AEEventID theAEEventID, ProcPtr p, - long handlerRefcon, bool isSysHandler) -{ - return noErr == (AEInstallEventHandler(theAEEventClass, - theAEEventID, NewAEEventHandlerUPP((AEEventHandlerProcPtr)p), - handlerRefcon, isSysHandler)); -} - -LOCALPROC InstallAppleEventHandlers(void) -{ - if (noErr == AESetInteractionAllowed(kAEInteractWithLocal)) - if (InstallEventHandler(kCoreEventClass, kAEOpenApplication, - (ProcPtr)DoOpenEvent, 0, false)) - if (InstallEventHandler(kCoreEventClass, kAEOpenDocuments, - (ProcPtr)OpenOrPrintFiles, openOnly, false)) - if (InstallEventHandler(kCoreEventClass, kAEPrintDocuments, - (ProcPtr)OpenOrPrintFiles, openPrint, false)) - if (InstallEventHandler(kCoreEventClass, kAEQuitApplication, - (ProcPtr)DoQuitEvent, 0, false)) - { - } -} - -static pascal OSErr GlobalTrackingHandler(DragTrackingMessage message, - WindowRef theWindow, void *handlerRefCon, DragReference theDragRef) -{ - RgnHandle hilightRgn; - Rect Bounds; - - UnusedParam(theWindow); - UnusedParam(handlerRefCon); - switch(message) { - case kDragTrackingEnterWindow: - hilightRgn = NewRgn(); - if (hilightRgn != NULL) { - SetScrnRectFromCoords(&Bounds, - 0, 0, vMacScreenHeight, vMacScreenWidth); - RectRgn(hilightRgn, &Bounds); - ShowDragHilite(theDragRef, hilightRgn, true); - DisposeRgn(hilightRgn); - } - break; - case kDragTrackingLeaveWindow: - HideDragHilite(theDragRef); - break; - } - - return noErr; -} - -LOCALFUNC MacErr_t InsertADiskOrAliasFromFSRef(FSRef *theRef) -{ - MacErr_t err; - Boolean isFolder; - Boolean isAlias; - - if (CheckSaveMacErr(FSResolveAliasFile(theRef, true, - &isFolder, &isAlias))) - { - err = InsertADiskFromFSRef1(theRef); - } - - return err; -} - -LOCALFUNC MacErr_t InsertADiskOrAliasFromSpec(FSSpec *spec) -{ - MacErr_t err; - FSRef newRef; - - if (CheckSaveMacErr(FSpMakeFSRef(spec, &newRef))) - if (CheckSavetMacErr(InsertADiskOrAliasFromFSRef(&newRef))) - { - /* ok */ - } - - return err; -} - -static pascal OSErr GlobalReceiveHandler(WindowRef pWindow, - void *handlerRefCon, DragReference theDragRef) -{ - SInt16 mouseUpModifiers; - unsigned short items; - unsigned short index; - ItemReference theItem; - Size SentSize; - HFSFlavor r; - - UnusedParam(pWindow); - UnusedParam(handlerRefCon); - - if (noErr == GetDragModifiers(theDragRef, - NULL, NULL, &mouseUpModifiers)) - { - UpdateKeyboardModifiers(mouseUpModifiers); - } - - if (noErr == CountDragItems(theDragRef, &items)) { - for (index = 1; index <= items; ++index) { - if (noErr == GetDragItemReferenceNumber(theDragRef, - index, &theItem)) - if (noErr == GetFlavorDataSize(theDragRef, - theItem, flavorTypeHFS, &SentSize)) - /* - On very old macs SentSize might only be big enough - to hold the actual file name. Have not seen this - in OS X, but still leave the check - as '<=' instead of '=='. - */ - if (SentSize <= sizeof(HFSFlavor)) - if (noErr == GetFlavorData(theDragRef, theItem, - flavorTypeHFS, (Ptr)&r, &SentSize, 0)) - { - ReportStandardOpenDiskError( - InsertADiskOrAliasFromSpec(&r.fileSpec)); - } - } - -#if 1 - if (gTrueBackgroundFlag) { - ProcessSerialNumber currentProcess = {0, kCurrentProcess}; - - (void) SetFrontProcess(¤tProcess); - } -#endif - } - - return noErr; -} - -LOCALVAR DragTrackingHandlerUPP gGlobalTrackingHandler = NULL; -LOCALVAR DragReceiveHandlerUPP gGlobalReceiveHandler = NULL; - -LOCALPROC UnPrepareForDragging(void) -{ - if (NULL != gGlobalReceiveHandler) { - RemoveReceiveHandler(gGlobalReceiveHandler, gMainWindow); - DisposeDragReceiveHandlerUPP(gGlobalReceiveHandler); - gGlobalReceiveHandler = NULL; - } - if (NULL != gGlobalTrackingHandler) { - RemoveTrackingHandler(gGlobalTrackingHandler, gMainWindow); - DisposeDragTrackingHandlerUPP(gGlobalTrackingHandler); - gGlobalTrackingHandler = NULL; - } -} - -LOCALFUNC bool PrepareForDragging(void) -{ - bool IsOk = false; - - gGlobalTrackingHandler = NewDragTrackingHandlerUPP( - GlobalTrackingHandler); - if (gGlobalTrackingHandler != NULL) { - gGlobalReceiveHandler = NewDragReceiveHandlerUPP( - GlobalReceiveHandler); - if (gGlobalReceiveHandler != NULL) { - if (noErr == InstallTrackingHandler(gGlobalTrackingHandler, - gMainWindow, nil)) - { - if (noErr == InstallReceiveHandler( - gGlobalReceiveHandler, gMainWindow, nil)) - { - IsOk = true; - } - } - } - } - - return IsOk; -} - -LOCALPROC HandleEventLocation(EventRef theEvent) -{ - Point NewMousePos; - - if (! gWeAreActive) { - return; - } - - if (noErr == GetEventParameter(theEvent, - kEventParamMouseLocation, - typeQDPoint, - NULL, - sizeof(NewMousePos), - NULL, - &NewMousePos)) - { - MousePositionNotify(NewMousePos); - } -} - -LOCALPROC HandleEventModifiers(EventRef theEvent) -{ - UInt32 theModifiers; - - if (gWeAreActive) { - GetEventParameter(theEvent, kEventParamKeyModifiers, - typeUInt32, NULL, sizeof(typeUInt32), NULL, &theModifiers); - - UpdateKeyboardModifiers(theModifiers); - } -} - -LOCALVAR bool IsOurMouseMove; - -static pascal OSStatus windowEventHandler( - EventHandlerCallRef nextHandler, EventRef theEvent, - void* userData) -{ - OSStatus result = eventNotHandledErr; - UInt32 eventClass = GetEventClass(theEvent); - UInt32 eventKind = GetEventKind(theEvent); - - UnusedParam(nextHandler); - UnusedParam(userData); - switch(eventClass) { - case kEventClassWindow: - switch(eventKind) { - case kEventWindowClose: - RequestMacOff = true; - result = noErr; - break; - case kEventWindowDrawContent: - Update_Screen(); - result = noErr; - break; - case kEventWindowClickContentRgn: - MouseIsOutside = false; - HandleEventLocation(theEvent); - HandleEventModifiers(theEvent); - MouseButtonSet(true); - result = noErr; - break; - case kEventWindowFocusAcquired: - gLackFocusFlag = false; - result = noErr; - break; - case kEventWindowFocusRelinquish: - { - WindowRef window; - - (void) GetEventParameter(theEvent, - kEventParamDirectObject, typeWindowRef, - NULL, sizeof(WindowRef), NULL, &window); - if ((window == gMainWindow) - && (window != gOldWindow)) - { - ClearWeAreActive(); - gLackFocusFlag = true; - } - } - result = noErr; - break; - } - break; - case kEventClassMouse: - switch(eventKind) { - case kEventMouseMoved: - case kEventMouseDragged: - MouseIsOutside = false; -#if 0 /* don't bother, CheckMouseState will take care of it, better */ - HandleEventLocation(theEvent); - HandleEventModifiers(theEvent); -#endif - IsOurMouseMove = true; - result = noErr; - break; - } - break; - } - - return result; -} - -LOCALFUNC bool CreateNewWindow(Rect *Bounds, WindowPtr *theWindow) -{ - WindowPtr ResultWin; - bool IsOk = false; - - if (noErr == CreateNewWindow( - -#if 1 - UseFullScreen ? -#endif -#if MayFullScreen - /* - appears not to work properly with aglSetWindowRef - at least in OS X 10.5.5 - also doesn't seem to be needed. maybe dates from when - didn't cover all screens in full screen mode. - */ - /* - Oops, no, kDocumentWindowClass doesn't seem to - work quite right if made immediately after - launch, title bar gets moved onscreen. At least - in Intel 10.5.6, doesn't happen in PowerPC 10.4.11. - Oddly, this problem doesn't happen if icon - already in dock before launch, but perhaps - that is just a timing issue. - So use kPlainWindowClass after all. - */ - kPlainWindowClass -#endif -#if 1 - : -#endif -#if MayNotFullScreen - kDocumentWindowClass -#endif - , - -#if 1 - UseFullScreen ? -#endif -#if MayFullScreen - /* kWindowStandardHandlerAttribute */ 0 -#endif -#if 1 - : -#endif -#if MayNotFullScreen - kWindowCloseBoxAttribute - | kWindowCollapseBoxAttribute -#endif - , - - Bounds, &ResultWin - )) - { -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - SetWindowTitleWithCFString(ResultWin, - AppName /* CFSTR("Mini vMac") */); - } -#endif - InstallStandardEventHandler(GetWindowEventTarget(ResultWin)); - { - static const EventTypeSpec windowEvents[] = - { - {kEventClassWindow, kEventWindowClose}, - {kEventClassWindow, kEventWindowDrawContent}, - {kEventClassWindow, kEventWindowClickContentRgn}, - {kEventClassMouse, kEventMouseMoved}, - {kEventClassMouse, kEventMouseDragged}, - {kEventClassWindow, kEventWindowFocusAcquired}, - {kEventClassWindow, kEventWindowFocusRelinquish} - }; - InstallWindowEventHandler(ResultWin, - NewEventHandlerUPP(windowEventHandler), - GetEventTypeCount(windowEvents), - windowEvents, 0, NULL); - } - - *theWindow = ResultWin; - - IsOk = true; - } - - return IsOk; -} - -LOCALPROC CloseAglCurrentContext(void) -{ - if (ctx != NULL) { - /* - Only because DrawWithOpenGL doesn't - bother to do this. No one - uses the CurrentContext - without settting it first. - */ - if (GL_TRUE != aglSetCurrentContext(NULL)) { - /* err = aglReportError() */ - } - ctx = NULL; - } -} - -LOCALPROC CloseMainWindow(void) -{ - UnPrepareForDragging(); - - if (window_ctx != NULL) { - if (GL_TRUE != aglDestroyContext(window_ctx)) { - /* err = aglReportError() */ - } - window_ctx = NULL; - } - - if (window_fmt != NULL) { - aglDestroyPixelFormat(window_fmt); - window_fmt = NULL; - } - - if (gMainWindow != NULL) { - DisposeWindow(gMainWindow); - gMainWindow = NULL; - } -} - -enum { - kMagStateNormal, - kMagStateMagnifgy, - kNumMagStates -}; - -#define kMagStateAuto kNumMagStates - -#if MayNotFullScreen -LOCALVAR int CurWinIndx; -LOCALVAR bool HavePositionWins[kNumMagStates]; -LOCALVAR Point WinPositionWins[kNumMagStates]; -#endif - -LOCALFUNC bool CreateMainWindow(void) -{ -#if MayNotFullScreen - int WinIndx; -#endif - Rect MainScrnBounds; - Rect AllScrnBounds; - Rect NewWinRect; - short leftPos; - short topPos; - short NewWindowHeight = vMacScreenHeight; - short NewWindowWidth = vMacScreenWidth; - bool IsOk = false; - -#if 1 - if (UseFullScreen) { - _HideMenuBar(); - } else { - _ShowMenuBar(); - } -#else -#if MayFullScreen - _HideMenuBar(); -#endif -#endif - - GetGrayRgnBounds(&AllScrnBounds); - GetScreenBitsBounds(&MainScrnBounds); - - if (UseMagnify) { - NewWindowHeight *= WindowScale; - NewWindowWidth *= WindowScale; - } - - leftPos = MainScrnBounds.left - + ((MainScrnBounds.right - MainScrnBounds.left) - - NewWindowWidth) / 2; - topPos = MainScrnBounds.top - + ((MainScrnBounds.bottom - MainScrnBounds.top) - - NewWindowHeight) / 2; - if (leftPos < MainScrnBounds.left) { - leftPos = MainScrnBounds.left; - } - if (topPos < MainScrnBounds.top) { - topPos = MainScrnBounds.top; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ViewHSize = MainScrnBounds.right - MainScrnBounds.left; - ViewVSize = MainScrnBounds.bottom - MainScrnBounds.top; - if (UseMagnify) { - ViewHSize /= WindowScale; - ViewVSize /= WindowScale; - } - if (ViewHSize >= vMacScreenWidth) { - ViewHStart = 0; - ViewHSize = vMacScreenWidth; - } else { - ViewHSize &= ~ 1; - } - if (ViewVSize >= vMacScreenHeight) { - ViewVStart = 0; - ViewVSize = vMacScreenHeight; - } else { - ViewVSize &= ~ 1; - } - } -#endif - - /* Create window rectangle and centre it on the screen */ - SetRect(&MainScrnBounds, 0, 0, NewWindowWidth, NewWindowHeight); - OffsetRect(&MainScrnBounds, leftPos, topPos); - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewWinRect = AllScrnBounds; - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - if (UseMagnify) { - WinIndx = kMagStateMagnifgy; - } else { - WinIndx = kMagStateNormal; - } - - if (! HavePositionWins[WinIndx]) { - WinPositionWins[WinIndx].h = leftPos; - WinPositionWins[WinIndx].v = topPos; - HavePositionWins[WinIndx] = true; - NewWinRect = MainScrnBounds; - } else { - SetRect(&NewWinRect, 0, 0, NewWindowWidth, NewWindowHeight); - OffsetRect(&NewWinRect, - WinPositionWins[WinIndx].h, WinPositionWins[WinIndx].v); - } - } -#endif - -#if MayNotFullScreen - CurWinIndx = WinIndx; -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - hOffset = MainScrnBounds.left - AllScrnBounds.left; - vOffset = MainScrnBounds.top - AllScrnBounds.top; - } -#endif - - if (CreateNewWindow(&NewWinRect, &gMainWindow)) { - static const GLint window_attrib[] = {AGL_RGBA, -#if UseAGLdoublebuff - AGL_DOUBLEBUFFER, -#endif - /* AGL_DEPTH_SIZE, 16, */ - AGL_NONE}; - -#if 0 != vMacScreenDepth - ColorModeWorks = true; -#endif - - window_fmt = aglChoosePixelFormat(NULL, 0, window_attrib); - if (NULL == window_fmt) { - /* err = aglReportError() */ - } else { - window_ctx = aglCreateContext(window_fmt, NULL); - if (NULL == window_ctx) { - /* err = aglReportError() */ - } else { - - ShowWindow(gMainWindow); - - if (GL_TRUE != ( - /* - aglSetDrawable is deprecated, but use it anyway - if at all possible, because aglSetWindowRef - doesn't seeem to work properly on a - kPlainWindowClass window. - Should move to Cocoa. - */ - HaveaglSetDrawable() - ? aglSetDrawable(window_ctx, - GetWindowPort(gMainWindow)) - : - HaveaglSetWindowRef() - ? aglSetWindowRef(window_ctx, gMainWindow) - : - GL_FALSE)) - { - /* err = aglReportError() */ - } else { - ctx = window_ctx; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - int h = NewWinRect.right - NewWinRect.left; - int v = NewWinRect.bottom - NewWinRect.top; - - GLhOffset = hOffset; - GLvOffset = v - vOffset; - AdjustGLforSize(h, v); - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - GLhOffset = 0; - GLvOffset = NewWindowHeight; - AdjustGLforSize(NewWindowWidth, - NewWindowHeight); - } -#endif - -#if UseAGLdoublebuff && 1 - { - GLint agSwapInterval = 1; - if (GL_TRUE != aglSetInteger( - window_ctx, AGL_SWAP_INTERVAL, - &agSwapInterval)) - { - MacMsg("oops", "aglSetInteger failed", - false); - } else { - /* - MacMsg("good", "aglSetInteger ok", - false); - */ - } - } -#endif - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - /* check if window rect valid */ - Rect tr; - - if (GetWindowTitleBounds(gMainWindow, &tr)) - { - if (! RectInRgn(&tr, GetGrayRgn())) { - SetMacWindContRect(gMainWindow, - &MainScrnBounds); - if (GetWindowTitleBounds( - gMainWindow, &tr)) - { - if (! RectInRgn(&tr, GetGrayRgn())) - { - OffsetRect(&MainScrnBounds, 0, - AllScrnBounds.top - tr.top); - SetMacWindContRect( - gMainWindow, - &MainScrnBounds); - } - } - } - } - } -#endif - - (void) PrepareForDragging(); - - IsOk = true; - } - } - } - } - - return IsOk; -} - -#if EnableRecreateW -LOCALPROC ZapWState(void) -{ - gMainWindow = NULL; - window_fmt = NULL; - window_ctx = NULL; - gGlobalReceiveHandler = NULL; - gGlobalTrackingHandler = NULL; -} -#endif - -#if EnableRecreateW -struct WState { - WindowPtr f_MainWindow; - AGLPixelFormat f_fmt; - AGLContext f_ctx; -#if MayFullScreen - short f_hOffset; - short f_vOffset; - uint16_t f_ViewHSize; - uint16_t f_ViewVSize; - uint16_t f_ViewHStart; - uint16_t f_ViewVStart; -#endif -#if 1 - bool f_UseFullScreen; -#endif -#if 1 - bool f_UseMagnify; -#endif -#if MayNotFullScreen - int f_CurWinIndx; -#endif - short f_GLhOffset; - short f_GLvOffset; - DragTrackingHandlerUPP f_gGlobalTrackingHandler; - DragReceiveHandlerUPP f_gGlobalReceiveHandler; -}; -typedef struct WState WState; -#endif - -#if EnableRecreateW -LOCALPROC GetWState(WState *r) -{ - r->f_MainWindow = gMainWindow; - r->f_fmt = window_fmt; - r->f_ctx = window_ctx; -#if MayFullScreen - r->f_hOffset = hOffset; - r->f_vOffset = vOffset; - r->f_ViewHSize = ViewHSize; - r->f_ViewVSize = ViewVSize; - r->f_ViewHStart = ViewHStart; - r->f_ViewVStart = ViewVStart; -#endif -#if 1 - r->f_UseFullScreen = UseFullScreen; -#endif -#if 1 - r->f_UseMagnify = UseMagnify; -#endif -#if MayNotFullScreen - r->f_CurWinIndx = CurWinIndx; -#endif - r->f_GLhOffset = GLhOffset; - r->f_GLvOffset = GLvOffset; - r->f_gGlobalTrackingHandler = gGlobalTrackingHandler; - r->f_gGlobalReceiveHandler = gGlobalReceiveHandler; -} -#endif - -#if EnableRecreateW -LOCALPROC SetWState(WState *r) -{ - gMainWindow = r->f_MainWindow; - window_fmt = r->f_fmt; - window_ctx = r->f_ctx; -#if MayFullScreen - hOffset = r->f_hOffset; - vOffset = r->f_vOffset; - ViewHSize = r->f_ViewHSize; - ViewVSize = r->f_ViewVSize; - ViewHStart = r->f_ViewHStart; - ViewVStart = r->f_ViewVStart; -#endif -#if 1 - UseFullScreen = r->f_UseFullScreen; -#endif -#if 1 - UseMagnify = r->f_UseMagnify; -#endif -#if MayNotFullScreen - CurWinIndx = r->f_CurWinIndx; -#endif - GLhOffset = r->f_GLhOffset; - GLvOffset = r->f_GLvOffset; - gGlobalTrackingHandler = r->f_gGlobalTrackingHandler; - gGlobalReceiveHandler = r->f_gGlobalReceiveHandler; - - ctx = window_ctx; -} -#endif - -#if EnableRecreateW -LOCALFUNC bool ReCreateMainWindow(void) -{ - WState old_state; - WState new_state; - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - /* save old position */ - if (gMainWindow != NULL) { - Rect r; - - if (GetWindowContBounds(gMainWindow, &r)) { - WinPositionWins[CurWinIndx].h = r.left; - WinPositionWins[CurWinIndx].v = r.top; - } - } - } -#endif - -#if MayFullScreen - UngrabMachine(); -#endif - - CloseAglCurrentContext(); - - gOldWindow = gMainWindow; - - GetWState(&old_state); - - ZapWState(); - -#if 1 - UseFullScreen = WantFullScreen; -#endif -#if 1 - UseMagnify = WantMagnify; -#endif - - if (! CreateMainWindow()) { - gOldWindow = NULL; - CloseMainWindow(); - SetWState(&old_state); - -#if 1 - if (UseFullScreen) { - _HideMenuBar(); - } else { - _ShowMenuBar(); - } -#endif - - /* avoid retry */ -#if 1 - WantFullScreen = UseFullScreen; -#endif -#if 1 - WantMagnify = UseMagnify; -#endif - - return false; - } else { - GetWState(&new_state); - SetWState(&old_state); - CloseMainWindow(); - gOldWindow = NULL; - SetWState(&new_state); - - if (HaveCursorHidden) { - (void) MoveMouse(CurMouseH, CurMouseV); - WantCursorHidden = true; - } else { - MouseIsOutside = false; /* don't know */ - } - - return true; - } -} -#endif - -#if 1 && 1 -enum { - kWinStateWindowed, -#if 1 - kWinStateFullScreen, -#endif - kNumWinStates -}; -#endif - -#if 1 && 1 -LOCALVAR int WinMagStates[kNumWinStates]; -#endif - -LOCALPROC ZapWinStateVars(void) -{ -#if MayNotFullScreen - { - int i; - - for (i = 0; i < kNumMagStates; ++i) { - HavePositionWins[i] = false; - } - } -#endif -#if 1 && 1 - { - int i; - - for (i = 0; i < kNumWinStates; ++i) { - WinMagStates[i] = kMagStateAuto; - } - } -#endif -} - -#if 1 -LOCALPROC ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; - -#if 1 - { - int OldWinState = - UseFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int OldMagState = - UseMagnify ? kMagStateMagnifgy : kMagStateNormal; - int NewWinState = - WantFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int NewMagState = WinMagStates[NewWinState]; - - WinMagStates[OldWinState] = OldMagState; - if (kMagStateAuto != NewMagState) { - WantMagnify = (kMagStateMagnifgy == NewMagState); - } else { - WantMagnify = false; - if (WantFullScreen - && HaveCGDisplayPixelsWide() - && HaveCGDisplayPixelsHigh()) - { - CGDirectDisplayID CurMainDisplayID = MainDisplayID(); - - if ((CGDisplayPixelsWide(CurMainDisplayID) - >= vMacScreenWidth * WindowScale) - && (CGDisplayPixelsHigh(CurMainDisplayID) - >= vMacScreenHeight * WindowScale) - ) - { - WantMagnify = true; - } - } - } - } -#endif -} -#endif - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif - - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if SoundEnabled - Sound_Stop(); -#endif -} - -LOCALPROC DoNotInBackgroundTasks(void) -{ -#if 0 - if (HaveCGCursorIsVisible()) { - HaveCursorHidden = ! CGCursorIsVisible(); - - /* - This shouldn't be needed, but have seen - cursor state get messed up in 10.4. - If the os x hide count gets off, this - should fix it within a few ticks. - - oops, no, doesn't seem to be accurate, - and makes things worse. particularly if - cursor in obscured state after typing - into dialog. - */ - /* trying a different approach further below */ - } -#endif - - if (HaveCursorHidden != ( -#if MayNotFullScreen - (WantCursorHidden -#if 1 - || UseFullScreen -#endif - ) && -#endif - gWeAreActive && ! CurSpeedStopped)) - { - HaveCursorHidden = ! HaveCursorHidden; - if (HaveCursorHidden) { - HideCursor(); - } else { - /* - kludge for OS X, where mouse over Dock devider - changes cursor, and never sets it back. - */ - SetCursorArrow(); - - ShowCursor(); - } - } - - /* check if actual cursor visibility is what it should be */ - if (HaveCGCursorIsVisible()) { - /* but only in OS X 10.3 and later */ - if (CGCursorIsVisible()) { - if (HaveCursorHidden) { - HideCursor(); - if (CGCursorIsVisible()) { - /* - didn't work, attempt undo so that - hide cursor count won't get large - */ - ShowCursor(); - } - } - } else { - if (! HaveCursorHidden) { - ShowCursor(); - /* - don't check if worked, assume can't decrement - hide cursor count below 0 - */ - } - } - } -} - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MouseConstrain(); - } -#endif - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (! gWeAreActive) { - if (! (gTrueBackgroundFlag || gLackFocusFlag)) { - gWeAreActive = true; - ReconnectKeyCodes3(); - SetCursorArrow(); - } - } - -#if 1 - if (gTrueBackgroundFlag && WantFullScreen) { - ToggleWantFullScreen(); - } -#endif - - if (CurSpeedStopped != (SpeedStopped || - (gTrueBackgroundFlag && ! RunInBackground))) - { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - -#if EnableRecreateW - if (gWeAreActive) { - if (0 -#if 1 - || (UseMagnify != WantMagnify) -#endif -#if 1 - || (UseFullScreen != WantFullScreen) -#endif - ) - { - (void) ReCreateMainWindow(); - } - } -#endif - -#if MayFullScreen - if (GrabMachine != ( -#if 1 - UseFullScreen && -#endif - gWeAreActive && ! CurSpeedStopped)) - { - GrabMachine = ! GrabMachine; - AdjustMachineGrab(); - } -#endif - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - - if (WantScreensChangedCheck) { - WantScreensChangedCheck = false; - UpdateOpenGLContext(); - } - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - - if (! gWeAreActive) { - /* - dialog during drag and drop hangs if in background - and don't want recursive dialogs - so wait til later to display dialog - */ - } else { -#if IncludeSonyNew - if (vSonyNewDiskWanted) { -#if IncludeSonyNameNew - if (vSonyNewDiskName != NotAPbuf) { - CFStringRef NewDiskName = - CFStringCreateWithPbuf(vSonyNewDiskName); - MakeNewDisk(vSonyNewDiskSize, NewDiskName); - if (NewDiskName != NULL) { - CFRelease(NewDiskName); - } - PbufDispose(vSonyNewDiskName); - vSonyNewDiskName = NotAPbuf; - } else -#endif - { - MakeNewDisk(vSonyNewDiskSize, NULL); - } - vSonyNewDiskWanted = false; - /* must be done after may have gotten disk */ - } -#endif - if (RequestInsertDisk) { - RequestInsertDisk = false; - InsertADisk0(); - } - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif - - if (gWeAreActive) { - DoNotInBackgroundTasks(); - } -} - -#define CheckItem CheckMenuItem - -/* Menu Constants */ - -#define kAppleMenu 128 -#define kFileMenu 129 -#define kSpecialMenu 130 - -enum { - kCmdIdNull, - kCmdIdMoreCommands, - - kNumCmdIds -}; - -LOCALFUNC OSStatus ProcessCommand(MenuCommand inCommandID) -{ - OSStatus result = noErr; - - switch (inCommandID) { - case kHICommandAbout: - DoAboutMsg(); - break; - case kHICommandQuit: - RequestMacOff = true; - break; - case kHICommandOpen: - RequestInsertDisk = true; - break; - case kCmdIdMoreCommands: - DoMoreCommandsMsg(); - break; - default: - result = eventNotHandledErr; - break; - } - - return result; -} - -LOCALFUNC OSStatus Keyboard_UpdateKeyMap3(EventRef theEvent, bool down) -{ - UInt32 uiKeyCode; - - HandleEventModifiers(theEvent); - GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, - sizeof(uiKeyCode), NULL, &uiKeyCode); - Keyboard_UpdateKeyMap2(Keyboard_RemapMac(uiKeyCode & 0x000000FF), - down); - return noErr; -} - -static pascal OSStatus EventHandler(EventHandlerCallRef nextHandler, - EventRef theEvent, void * userData) -{ - OSStatus result = eventNotHandledErr; - UInt32 eventClass = GetEventClass(theEvent); - UInt32 eventKind = GetEventKind(theEvent); - - UnusedParam(userData); - - switch (eventClass) { - case kEventClassMouse: - switch (eventKind) { - case kEventMouseDown: -#if MayFullScreen - if (GrabMachine) { - HandleEventLocation(theEvent); - HandleEventModifiers(theEvent); - MouseButtonSet(true); - result = noErr; - } else -#endif - { - result = CallNextEventHandler( - nextHandler, theEvent); - } - break; - case kEventMouseUp: - HandleEventLocation(theEvent); - HandleEventModifiers(theEvent); - MouseButtonSet(false); -#if MayFullScreen - if (GrabMachine) { - result = noErr; - } else -#endif - { - result = CallNextEventHandler( - nextHandler, theEvent); - } - break; - case kEventMouseMoved: - case kEventMouseDragged: - IsOurMouseMove = false; - result = CallNextEventHandler( - nextHandler, theEvent); - /* - Actually, mousing over window does't seem - to go through here, it goes directly to - the window routine. But since not documented - either way, leave the check in case this - changes. - */ - if (! IsOurMouseMove) { - MouseIsOutside = true; -#if 0 /* don't bother, CheckMouseState will take care of it, better */ - HandleEventLocation(theEvent); - HandleEventModifiers(theEvent); -#endif - } - break; - } - break; - case kEventClassApplication: - switch (eventKind) { - case kEventAppActivated: - gTrueBackgroundFlag = false; - result = noErr; - break; - case kEventAppDeactivated: - gTrueBackgroundFlag = true; - result = noErr; - ClearWeAreActive(); - break; - } - break; - case kEventClassCommand: - switch (eventKind) { - case kEventProcessCommand: - { - HICommand hiCommand; - - GetEventParameter(theEvent, - kEventParamDirectObject, typeHICommand, - NULL, sizeof(HICommand), NULL, &hiCommand); - result = ProcessCommand(hiCommand.commandID); - } - break; - } - break; - case kEventClassKeyboard: - if (! gWeAreActive) { - return CallNextEventHandler(nextHandler, theEvent); - } else { - switch (eventKind) { - case kEventRawKeyDown: - result = Keyboard_UpdateKeyMap3( - theEvent, true); - break; - case kEventRawKeyUp: - result = Keyboard_UpdateKeyMap3( - theEvent, false); - break; - case kEventRawKeyModifiersChanged: - HandleEventModifiers(theEvent); - result = noErr; - break; - default: - break; - } - } - break; - default: - break; - } - return result; -} - -LOCALPROC AppendMenuConvertCStr( - MenuRef menu, - MenuCommand inCommandID, - char *s) -{ - CFStringRef cfStr = CFStringCreateFromSubstCStr(s); - if (NULL != cfStr) { - AppendMenuItemTextWithCFString(menu, cfStr, - 0, inCommandID, NULL); - CFRelease(cfStr); - } -} - -LOCALPROC AppendMenuSep(MenuRef menu) -{ - AppendMenuItemTextWithCFString(menu, NULL, - kMenuItemAttrSeparator, 0, NULL); -} - -LOCALFUNC MenuRef NewMenuFromConvertCStr(short menuID, char *s) -{ - MenuRef menu = NULL; - - CFStringRef cfStr = CFStringCreateFromSubstCStr(s); - if (NULL != cfStr) { - OSStatus err = CreateNewMenu(menuID, 0, &menu); - if (err != noErr) { - menu = NULL; - } else { - (void) SetMenuTitleWithCFString(menu, cfStr); - } - CFRelease(cfStr); - } - - return menu; -} - -LOCALPROC RemoveCommandKeysInMenu(MenuRef theMenu) -{ - MenuRef outHierMenu; - int i; - UInt16 n = CountMenuItems(theMenu); - - for (i = 1; i <= n; ++i) { - SetItemCmd(theMenu, i, 0); - if (noErr == GetMenuItemHierarchicalMenu( - theMenu, i, &outHierMenu) - && (NULL != outHierMenu)) - { - RemoveCommandKeysInMenu(outHierMenu); - } - } -} - -LOCALFUNC bool InstallOurMenus(void) -{ - MenuRef menu; - Str255 s; - - PStrFromChar(s, (char)20); - menu = NewMenu(kAppleMenu, s); - if (menu != NULL) { - AppendMenuConvertCStr(menu, - kHICommandAbout, - kStrMenuItemAbout); - AppendMenuSep(menu); - InsertMenu(menu, 0); - } - - menu = NewMenuFromConvertCStr(kFileMenu, kStrMenuFile); - if (menu != NULL) { - AppendMenuConvertCStr(menu, - kHICommandOpen, - kStrMenuItemOpen ";ll"); - InsertMenu(menu, 0); - } - - menu = NewMenuFromConvertCStr(kSpecialMenu, kStrMenuSpecial); - if (menu != NULL) { - AppendMenuConvertCStr(menu, - kCmdIdMoreCommands, - kStrMenuItemMore ";ll"); - InsertMenu(menu, 0); - } - - { - MenuRef outMenu; - MenuItemIndex outIndex; - - if (noErr == GetIndMenuItemWithCommandID( - NULL, kHICommandQuit, 1, &outMenu, &outIndex)) - { - RemoveCommandKeysInMenu(outMenu); - } - } - - DrawMenuBar(); - - return true; -} - -LOCALFUNC bool InstallOurAppearanceClient(void) -{ - RegisterAppearanceClient(); /* maybe not needed ? */ - return true; -} - -LOCALVAR bool DisplayRegistrationCallBackSuccessful = false; - -static void DisplayRegisterReconfigurationCallback( - CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, - void *userInfo) -{ - UnusedParam(display); - UnusedParam(userInfo); - - if (0 != (flags & kCGDisplayBeginConfigurationFlag)) { - /* fprintf(stderr, "kCGDisplayBeginConfigurationFlag\n"); */ - } else { -#if 0 - if (0 != (flags & kCGDisplayMovedFlag)) { - fprintf(stderr, "kCGDisplayMovedFlag\n"); - } - if (0 != (flags & kCGDisplaySetMainFlag)) { - fprintf(stderr, "kCGDisplaySetMainFlag\n"); - } - if (0 != (flags & kCGDisplaySetModeFlag)) { - fprintf(stderr, "kCGDisplaySetModeFlag\n"); - } - - if (0 != (flags & kCGDisplayAddFlag)) { - fprintf(stderr, "kCGDisplayAddFlag\n"); - } - if (0 != (flags & kCGDisplayRemoveFlag)) { - fprintf(stderr, "kCGDisplayRemoveFlag\n"); - } - - if (0 != (flags & kCGDisplayEnabledFlag)) { - fprintf(stderr, "kCGDisplayEnabledFlag\n"); - } - if (0 != (flags & kCGDisplayDisabledFlag)) { - fprintf(stderr, "kCGDisplayDisabledFlag\n"); - } - - if (0 != (flags & kCGDisplayMirrorFlag)) { - fprintf(stderr, "kCGDisplayMirrorFlag\n"); - } - if (0 != (flags & kCGDisplayUnMirrorFlag)) { - fprintf(stderr, "kCGDisplayMirrorFlag\n"); - } -#endif - - WantScreensChangedCheck = true; - -#if 1 - if (WantFullScreen) { - ToggleWantFullScreen(); - } -#endif - } -} - -LOCALFUNC bool InstallOurEventHandlers(void) -{ - EventTypeSpec eventTypes[] = { - {kEventClassMouse, kEventMouseDown}, - {kEventClassMouse, kEventMouseUp}, - {kEventClassMouse, kEventMouseMoved}, - {kEventClassMouse, kEventMouseDragged}, - {kEventClassKeyboard, kEventRawKeyModifiersChanged}, - {kEventClassKeyboard, kEventRawKeyDown}, - {kEventClassKeyboard, kEventRawKeyUp}, - {kEventClassApplication, kEventAppActivated}, - {kEventClassApplication, kEventAppDeactivated}, - {kEventClassCommand, kEventProcessCommand} - }; - - InstallApplicationEventHandler( - NewEventHandlerUPP(EventHandler), - GetEventTypeCount(eventTypes), - eventTypes, NULL, NULL); - - InitKeyCodes(); - - InstallAppleEventHandlers(); - - if (HaveCGDisplayRegisterReconfigurationCallback()) { - if (kCGErrorSuccess == - CGDisplayRegisterReconfigurationCallback( - DisplayRegisterReconfigurationCallback, NULL)) - { - DisplayRegistrationCallBackSuccessful = true; - } - } - - /* (void) SetMouseCoalescingEnabled(false, NULL); */ - - return true; -} - -LOCALPROC UnInstallOurEventHandlers(void) -{ - if (DisplayRegistrationCallBackSuccessful) { - if (HaveCGDisplayRemoveReconfigurationCallback()) { - CGDisplayRemoveReconfigurationCallback( - DisplayRegisterReconfigurationCallback, NULL); - } - } -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ - OSStatus err; - EventRef theEvent; - uint8_t NumChecks; - EventTimeout inTimeout; - EventTargetRef theTarget = GetEventDispatcherTarget(); - - inTimeout = kEventDurationNoWait; - -label_retry: - NumChecks = 0; - while ((NumChecks < 32) && (noErr == (err = - ReceiveNextEvent(0, NULL, inTimeout, - true, &theEvent)))) - { - (void) SendEventToEventTarget(theEvent, theTarget); - ReleaseEvent(theEvent); - inTimeout = kEventDurationNoWait; - ++NumChecks; - } - - CheckForSavedTasks(); - - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - inTimeout = kEventDurationForever; - goto label_retry; - } - - if (ExtraTimeNotOver()) { - inTimeout = - NextTickChangeTime - GetCurrentEventTime(); - if (inTimeout > 0.0) { -#if 1 - struct timespec rqt; - struct timespec rmt; - - rqt.tv_sec = 0; - rqt.tv_nsec = inTimeout / kEventDurationNanosecond; - (void) nanosleep(&rqt, &rmt); - inTimeout = kEventDurationNoWait; - goto label_retry; -#elif 1 - usleep(inTimeout / kEventDurationMicrosecond); - inTimeout = kEventDurationNoWait; - goto label_retry; -#else - /* - This has higher overhead. - */ - goto label_retry; -#endif - } - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - if (gWeAreActive) { - CheckMouseState(); - } - - OnTrueTime = TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime); -#endif -} - -/* --- platform independent code can be thought of as going here --- */ - -#include "PROGMAIN.h" - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); - ReserveAllocOneBlock(&ScalingBuff, vMacScreenNumPixels -#if 0 != vMacScreenDepth - * 4 -#endif - , 5, false); - ReserveAllocOneBlock(&CLUT_final, CLUT_finalsz, 5, false); -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)calloc(1, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALFUNC bool InitOSGLU(void) -{ - if (AllocMemory()) - if (InitApplInfo()) -#if dbglog_HAVE - if (dbglog_open()) -#endif -#if SoundEnabled - if (Sound_Init()) -#endif - if (InstallOurAppearanceClient()) - if (InstallOurEventHandlers()) - if (InstallOurMenus()) - if (CreateMainWindow()) - if (LoadMacRom()) - if (LoadInitialImages()) -#if EmLocalTalk - if (InitLocalTalk()) -#endif - if (InitLocationDat()) - if (WaitForRom()) - { - return true; - } - return false; -} - -#if dbglog_HAVE && 0 -IMPORTPROC DoDumpTable(void); -#endif -#if dbglog_HAVE && 0 -IMPORTPROC DumpRTC(void); -#endif - -LOCALPROC UnInitOSGLU(void) -{ -#if dbglog_HAVE && 0 - DoDumpTable(); -#endif -#if dbglog_HAVE && 0 - DumpRTC(); -#endif - - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - -#if MayFullScreen - UngrabMachine(); -#endif - -#if SoundEnabled - Sound_Stop(); -#endif - - CloseAglCurrentContext(); - CloseMainWindow(); - -#if MayFullScreen - _ShowMenuBar(); -#endif - -#if IncludePbufs - UnInitPbufs(); -#endif - UnInitDrives(); - - if (! gTrueBackgroundFlag) { - CheckSavedMacMsg(); - } - - UnInstallOurEventHandlers(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - UnInitApplInfo(); - - ForceShowCursor(); -} - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); - ZapWinStateVars(); -} - -/* adapted from Apple "Technical Q&A QA1061" */ - -static pascal OSStatus EventLoopEventHandler( - EventHandlerCallRef inHandlerCallRef, EventRef inEvent, - void *inUserData) -/* - This code contains the standard Carbon event dispatch loop, - as per "Inside Macintosh: Handling Carbon Events", Listing 3-10, - except: - - o this loop supports yielding to cooperative threads based on the - application maintaining the gNumberOfRunningThreads global - variable, and - - o it also works around a problem with the Inside Macintosh code - which unexpectedly quits when run on traditional Mac OS 9. - - See RunApplicationEventLoopWithCooperativeThreadSupport for - an explanation of why this is inside a Carbon event handler. - - The code in Inside Mac has a problem in that it quits the - event loop when ReceiveNextEvent returns an error. This is - wrong because ReceiveNextEvent can return eventLoopQuitErr - when you call WakeUpProcess on traditional Mac OS. So, rather - than relying on an error from ReceiveNextEvent, this routine tracks - whether the application is really quitting by installing a - customer handler for the kEventClassApplication/kEventAppQuit - Carbon event. All the custom handler does is call through - to the previous handler and, if it returns noErr (which indicates - the application is quitting, it sets quitNow so that our event - loop quits. - - Note that this approach continues to support - QuitApplicationEventLoop, which is a simple wrapper that just posts - a kEventClassApplication/kEventAppQuit event to the event loop. -*/ -{ - UnusedParam(inHandlerCallRef); - UnusedParam(inEvent); - UnusedParam(inUserData); - - ProgramMain(); - QuitApplicationEventLoop(); - - return noErr; -} - -LOCALPROC RunApplicationEventLoopWithCooperativeThreadSupport(void) -/* - A reimplementation of RunApplicationEventLoop that supports - yielding time to cooperative threads. -*/ -{ - static const EventTypeSpec eventSpec = {'KWIN', 'KWIN'}; - EventHandlerUPP theEventLoopEventHandlerUPP = nil; - EventHandlerRef installedHandler = NULL; - EventRef dummyEvent = nil; - -/* - Install EventLoopEventHandler, create a dummy event and post it, - and then call RunApplicationEventLoop. The rationale for this - is as follows: We want to unravel RunApplicationEventLoop so - that we can can yield to cooperative threads. In fact, the - core code for RunApplicationEventLoop is pretty easy (you - can see it above in EventLoopEventHandler). However, if you - just execute this code you miss out on all the standard event - handlers. These are relatively easy to reproduce (handling - the quit event and so on), but doing so is a pain because - a) it requires a bunch boilerplate code, and b) if Apple - extends the list of standard event handlers, your application - wouldn't benefit. So, we execute our event loop from within - a Carbon event handler that we cause to be executed by - explicitly posting an event to our event loop. Thus, the - standard event handlers are installed while our event loop runs. -*/ - if (nil == (theEventLoopEventHandlerUPP - = NewEventHandlerUPP(EventLoopEventHandler))) - { - /* fail */ - } else - if (noErr != InstallEventHandler(GetApplicationEventTarget(), - theEventLoopEventHandlerUPP, 1, &eventSpec, nil, - &installedHandler)) - { - /* fail */ - } else - if (noErr != MacCreateEvent(nil, 'KWIN', 'KWIN', - GetCurrentEventTime(), kEventAttributeNone, - &dummyEvent)) - { - /* fail */ - } else - if (noErr != PostEventToQueue(GetMainEventQueue(), - dummyEvent, kEventPriorityHigh)) - { - /* fail */ - } else - { - RunApplicationEventLoop(); - } - - if (nil != dummyEvent) { - ReleaseEvent(dummyEvent); - } - - if (NULL != installedHandler) { - (void) RemoveEventHandler(installedHandler); - } -} - -int main(void) -{ - ZapOSGLUVars(); - if (InitOSGLU()) { - RunApplicationEventLoopWithCooperativeThreadSupport(); - } - UnInitOSGLU(); - - return 0; -} diff --git a/src/UI/_deprecated/NDS/OSGLUNDS.c b/src/UI/_deprecated/NDS/OSGLUNDS.c deleted file mode 100644 index 3452cfc..0000000 --- a/src/UI/_deprecated/NDS/OSGLUNDS.c +++ /dev/null @@ -1,1384 +0,0 @@ -/* - OSGLUNDS.c - - Copyright (C) 2012 Lazyone, Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for Nintendo DS -*/ - -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" - -#include "UI/MYOSGLUE.h" - -#include "STRCONST.h" - -#include "FB1BPP2I.h" - -#define CONSOLE_TRACE() \ - fprintf(stderr, "%s() at line %d\n", __FUNCTION__, __LINE__) - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memcpy((char *)destPtr, (char *)srcPtr, byteCount); -} - -/* - Nintendo DS port globals -*/ -#define DS_ScreenWidth 256 -#define DS_ScreenHeight 192 - -LOCALVAR volatile int VBlankCounter = 0; -LOCALVAR volatile int HBlankCounter = 0; -LOCALVAR volatile unsigned int TimerBaseMSec = 0; -LOCALVAR Keyboard* DSKeyboard = NULL; -LOCALVAR volatile int LastKeyboardKey = NOKEY; -LOCALVAR volatile int KeyboardKey = NOKEY; -LOCALVAR volatile int KeysHeld = 0; -LOCALVAR volatile int CursorX = 0; -LOCALVAR volatile int CursorY = 0; -LOCALVAR int Display_bg2_Main = 0; - -/* --- control mode and internationalization --- */ - -#define NeedCell2PlainAsciiMap 1 - -#include "LANG/INTLCHAR.h" - -/* --- sending debugging info to file --- */ - -#if dbglog_HAVE - -#define dbglog_ToStdErr 1 - -#if ! dbglog_ToStdErr -LOCALVAR FILE *dbglog_File = NULL; -#endif - -LOCALFUNC bool dbglog_open0(void) -{ -#if dbglog_ToStdErr - return true; -#else - dbglog_File = fopen("dbglog.txt", "w"); - return (NULL != dbglog_File); -#endif -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ -#if dbglog_ToStdErr - (void) fwrite(s, 1, L, stderr); -#else - if (dbglog_File != NULL) { - (void) fwrite(s, 1, L, dbglog_File); - } -#endif -} - -LOCALPROC dbglog_close0(void) -{ -#if ! dbglog_ToStdErr - if (dbglog_File != NULL) { - fclose(dbglog_File); - dbglog_File = NULL; - } -#endif -} - -#endif - -/* --- debug settings and utilities --- */ - -#if ! dbglog_HAVE -#define WriteExtraErr(s) -#else -LOCALPROC WriteExtraErr(char *s) -{ - dbglog_writeCStr("*** error: "); - dbglog_writeCStr(s); - dbglog_writeReturn(); -} -#endif - -/* --- information about the environment --- */ - -#define WantColorTransValid 0 - -#include "UI/COMOSGLU.h" -#include "UI/CONTROLM.h" - -LOCALPROC NativeStrFromCStr(char *r, char *s) -{ - uint8_t ps[ClStrMaxLength]; - int i; - int L; - - ClStrFromSubstCStr(&L, ps, s); - - for (i = 0; i < L; ++i) { - r[i] = Cell2PlainAsciiMap[ps[i]]; - } - - r[L] = 0; -} - -/* --- drives --- */ - -#define NotAfileRef NULL - -LOCALVAR FILE *Drives[NumDrives]; /* open disk image files */ -#if IncludeSonyGetName || IncludeSonyNew -LOCALVAR char *DriveNames[NumDrives]; -#endif - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; -#if IncludeSonyGetName || IncludeSonyNew - DriveNames[i] = NULL; -#endif - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - uint32_t NewSony_Count = 0; - - if (0 == fseek(refnum, Sony_Start, SEEK_SET)) { - if (IsWrite) { - NewSony_Count = fwrite(Buffer, 1, Sony_Count, refnum); - } else { - NewSony_Count = fread(Buffer, 1, Sony_Count, refnum); - } - - if (NewSony_Count == Sony_Count) { - err = mnvm_noErr; - } - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = NewSony_Count; - } - - return err; /*& figure out what really to return &*/ -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - long v; - - if (0 == fseek(refnum, 0, SEEK_END)) { - v = ftell(refnum); - if (v >= 0) { - *Sony_Count = v; - err = mnvm_noErr; - } - } - - return err; /*& figure out what really to return &*/ -} - -LOCALFUNC MacErr_t vSonyEject0(tDrive Drive_No, bool deleteit) -{ - FILE *refnum = Drives[Drive_No]; - - DiskEjectedNotify(Drive_No); - - fclose(refnum); - Drives[Drive_No] = NotAfileRef; /* not really needed */ - -#if IncludeSonyGetName || IncludeSonyNew - { - char *s = DriveNames[Drive_No]; - if (NULL != s) { - if (deleteit) { - remove(s); - } - free(s); - DriveNames[Drive_No] = NULL; /* not really needed */ - } - } -#endif - - return mnvm_noErr; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, false); -} - -#if IncludeSonyNew -GLOBALOSGLUFUNC MacErr_t vSonyEjectDelete(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, true); -} -#endif - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -#if IncludeSonyGetName -GLOBALOSGLUFUNC MacErr_t vSonyGetName(tDrive Drive_No, tPbuf *r) -{ - char *drivepath = DriveNames[Drive_No]; - if (NULL == drivepath) { - return mnvm_miscErr; - } else { - char *s = strrchr(drivepath, '/'); - if (NULL == s) { - s = drivepath; - } else { - ++s; - } - return NativeTextToMacRomanPbuf(s, r); - } -} -#endif - -LOCALFUNC bool Sony_Insert0(FILE *refnum, bool locked, - char *drivepath) -{ - tDrive Drive_No; - bool IsOk = false; - - if (! FirstFreeDisk(&Drive_No)) { - MacMsg(kStrTooManyImagesTitle, kStrTooManyImagesMessage, - false); - } else { - /* printf("Sony_Insert0 %d\n", (int)Drive_No); */ - - { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); - -#if IncludeSonyGetName || IncludeSonyNew - { - uint32_t L = strlen(drivepath); - char *p = malloc(L + 1); - if (p != NULL) { - (void) memcpy(p, drivepath, L + 1); - } - DriveNames[Drive_No] = p; - } -#endif - - IsOk = true; - } - } - - if (! IsOk) { - fclose(refnum); - } - - return IsOk; -} - -LOCALFUNC bool Sony_Insert1(char *drivepath, bool silentfail) -{ - bool locked = false; - /* printf("Sony_Insert1 %s\n", drivepath); */ - FILE *refnum = fopen(drivepath, "rb+"); - if (NULL == refnum) { - locked = true; - refnum = fopen(drivepath, "rb"); - CONSOLE_TRACE(); - } - if (NULL == refnum) { - if (! silentfail) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - CONSOLE_TRACE(); - } - } else { - CONSOLE_TRACE(); - return Sony_Insert0(refnum, locked, drivepath); - } - - return false; -} - -#define Sony_Insert2(s) Sony_Insert1(s, true) - -LOCALFUNC bool Sony_InsertIth(int i) -{ - bool v; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - v = false; - } else { - char s[] = "disk?.dsk"; - - s[4] = '0' + i; - - v = Sony_Insert2(s); - } - - return v; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - int i; - - CONSOLE_TRACE(); - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - - return true; -} - -#if IncludeSonyNew -LOCALFUNC bool WriteZero(FILE *refnum, uint32_t L) -{ -#define ZeroBufferSize 2048 - uint32_t i; - uint8_t buffer[ZeroBufferSize]; - - memset(&buffer, 0, ZeroBufferSize); - - while (L > 0) { - i = (L > ZeroBufferSize) ? ZeroBufferSize : L; - if (fwrite(buffer, 1, i, refnum) != i) { - return false; - } - L -= i; - } - return true; -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDisk(uint32_t L, char *drivepath) -{ - bool IsOk = false; - FILE *refnum = fopen(drivepath, "wb+"); - if (NULL == refnum) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } else { - if (WriteZero(refnum, L)) { - IsOk = Sony_Insert0(refnum, false, drivepath); - refnum = NULL; - } - if (refnum != NULL) { - fclose(refnum); - } - if (! IsOk) { - (void) remove(drivepath); - } - } -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDiskAtDefault(uint32_t L) -{ - char s[ClStrMaxLength + 1]; - - NativeStrFromCStr(s, "untitled.dsk"); - MakeNewDisk(L, s); -} -#endif - -/* --- ROM --- */ - -LOCALFUNC MacErr_t LoadMacRomFrom(char *path) -{ - MacErr_t err; - FILE *ROM_File; - int File_Size; - - ROM_File = fopen(path, "rb"); - if (NULL == ROM_File) { - err = mnvm_fnfErr; - } else { - File_Size = fread(ROM, 1, kROM_Size, ROM_File); - if (kROM_Size != File_Size) { - if (feof(ROM_File)) { - MacMsgOverride(kStrShortROMTitle, - kStrShortROMMessage); - err = mnvm_eofErr; - } else { - MacMsgOverride(kStrNoReadROMTitle, - kStrNoReadROMMessage); - err = mnvm_miscErr; - } - } else { - err = ROM_IsValid(); - } - fclose(ROM_File); - } - - return err; -} - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if (mnvm_fnfErr == (err = LoadMacRomFrom(RomFileName))) - { - } - - return true; /* keep launching Mini vMac, regardless */ -} - -/* --- video out --- */ - -#if MayFullScreen -LOCALVAR short hOffset; -LOCALVAR short vOffset; -#endif - -#if 1 -LOCALVAR bool UseFullScreen = (WantInitFullScreen != 0); -#endif - -#if 1 -LOCALVAR bool UseMagnify = (WantInitMagnify != 0); -#endif - -LOCALVAR bool CurSpeedStopped = true; - -#if 1 -#define MaxScale WindowScale -#else -#define MaxScale 1 -#endif - -LOCALPROC HaveChangedScreenBuff(uint16_t top, uint16_t left, - uint16_t bottom, uint16_t right) -{ - /* - Oh god, clean this up. - */ - u8 *octpix = NULL; - u32 *vram = NULL; - - octpix = (u8 *)GetCurDrawBuff(); - vram = (u32 *)BG_BMP_RAM(0); - - octpix += ((top * vMacScreenWidth ) >> 3); - vram += ((top * vMacScreenWidth ) >> 2); - - FB1BPPtoIndexed(vram, octpix, - ((bottom - top) * vMacScreenWidth) >> 3); -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ -#if 0 && EnableFSMouseMotion - if (HaveMouseMotion) { - AutoScrollScreen(); - } -#endif - DrawChangesAndClear(); -} - -/* --- mouse --- */ - -/* cursor state */ - -LOCALPROC CheckMouseState(void) -{ - int32_t MotionX; - int32_t MotionY; - - /* - TODO: - - - Don't hardcode motion values - - Acceleration? - - Allow key remapping - - Handle touchscreen input (non-mouse motion) - - Handle touchscreen input (trackpad style mouse motion) - */ - - if (0 != (KeysHeld & KEY_LEFT)) { - MotionX = -4; - } else if (0 != (KeysHeld & KEY_RIGHT)) { - MotionX = 4; - } - - if (0 != (KeysHeld & KEY_UP)) { - MotionY = -4; - } else if (0 != (KeysHeld & KEY_DOWN)) { - MotionY = 4; - } - - HaveMouseMotion = true; - - MousePositionSetDelta(MotionX, MotionY); - MouseButtonSet(0 != (KeysHeld & KEY_A)); -} - -/* --- keyboard input --- */ - -LOCALVAR uint8_t KC2MKC[256]; - -/* - AHA! - GCC Was turning this into a macro of some sort which of course - broke horribly with libnds's keyboard having some negative values. -*/ -LOCALPROC AssignKeyToMKC(int UKey, int LKey, uint8_t MKC) -{ - if (UKey != NOKEY) { - KC2MKC[UKey] = MKC; - } - - if (LKey != NOKEY) { - KC2MKC[LKey] = MKC; - } -} - -LOCALFUNC bool KC2MKCInit(void) -{ - int i; - - for (i = 0; i < 256; ++i) { - KC2MKC[i] = MKC_None; - } - - AssignKeyToMKC('A', 'a', MKC_A); - AssignKeyToMKC('B', 'b', MKC_B); - AssignKeyToMKC('C', 'c', MKC_C); - AssignKeyToMKC('D', 'd', MKC_D); - AssignKeyToMKC('E', 'e', MKC_E); - AssignKeyToMKC('F', 'f', MKC_F); - AssignKeyToMKC('G', 'g', MKC_G); - AssignKeyToMKC('H', 'h', MKC_H); - AssignKeyToMKC('I', 'i', MKC_I); - AssignKeyToMKC('J', 'j', MKC_J); - AssignKeyToMKC('K', 'k', MKC_K); - AssignKeyToMKC('L', 'l', MKC_L); - AssignKeyToMKC('M', 'm', MKC_M); - AssignKeyToMKC('N', 'n', MKC_N); - AssignKeyToMKC('O', 'o', MKC_O); - AssignKeyToMKC('P', 'p', MKC_P); - AssignKeyToMKC('Q', 'q', MKC_Q); - AssignKeyToMKC('R', 'r', MKC_R); - AssignKeyToMKC('S', 's', MKC_S); - AssignKeyToMKC('T', 't', MKC_T); - AssignKeyToMKC('U', 'u', MKC_U); - AssignKeyToMKC('V', 'v', MKC_V); - AssignKeyToMKC('W', 'w', MKC_W); - AssignKeyToMKC('X', 'x', MKC_X); - AssignKeyToMKC('Y', 'y', MKC_Y); - AssignKeyToMKC('Z', 'z', MKC_Z); - - AssignKeyToMKC(')', '0', MKC_0); - AssignKeyToMKC('!', '1', MKC_1); - AssignKeyToMKC('@', '2', MKC_2); - AssignKeyToMKC('#', '3', MKC_3); - AssignKeyToMKC('$', '4', MKC_4); - AssignKeyToMKC('%', '5', MKC_5); - AssignKeyToMKC('^', '6', MKC_6); - AssignKeyToMKC('&', '7', MKC_7); - AssignKeyToMKC('*', '8', MKC_8); - AssignKeyToMKC('(', '9', MKC_9); - - AssignKeyToMKC('~', '`', MKC_formac_Grave); - AssignKeyToMKC('_', '-', MKC_Minus); - AssignKeyToMKC('+', '=', MKC_Equal); - AssignKeyToMKC(':', ';', MKC_SemiColon); - AssignKeyToMKC('\"', '\'', MKC_SingleQuote); - AssignKeyToMKC('{', '[', MKC_LeftBracket); - AssignKeyToMKC('}', ']', MKC_RightBracket); - AssignKeyToMKC('|', '\\', MKC_formac_BackSlash); - AssignKeyToMKC('<', ',', MKC_Comma); - AssignKeyToMKC('>', '.', MKC_Period); - AssignKeyToMKC('?', '/', MKC_formac_Slash); - - AssignKeyToMKC(NOKEY, DVK_SPACE, MKC_Space); - AssignKeyToMKC(NOKEY, DVK_BACKSPACE, MKC_BackSpace); - AssignKeyToMKC(NOKEY, DVK_ENTER, MKC_formac_Enter); - AssignKeyToMKC(NOKEY, DVK_TAB, MKC_Tab); - - InitKeyCodes(); - - return true; -} - -LOCALPROC DoKeyCode0(int i, bool down) -{ - uint8_t key = KC2MKC[i]; - if (MKC_None != key) { - fprintf(stderr, "%s() :: %c (%d) == %d\n", - __FUNCTION__, (char) i, key, down); - Keyboard_UpdateKeyMap2(key, down); - } -} - -LOCALPROC DoKeyCode(int i, bool down) -{ - if ((i >= 0) && (i < 256)) { - DoKeyCode0(i, down); - } -} - -/* - TODO: - - Rethink keyboard input... - Especially shift and capslock, the libnds keyboard - is weird about those. -*/ - -LOCALVAR bool DS_Keystate_Menu = false; -LOCALVAR bool DS_Keystate_Shift = false; - -LOCALPROC DS_HandleKey(int32_t Key, bool Down) -{ - if (Key == NOKEY) { - return; - } - - switch (Key) { - case DVK_UP: - Keyboard_UpdateKeyMap2(MKC_Up, Down); - break; - - case DVK_DOWN: - Keyboard_UpdateKeyMap2(MKC_Down, Down); - break; - - case DVK_LEFT: - Keyboard_UpdateKeyMap2(MKC_Left, Down); - break; - - case DVK_RIGHT: - Keyboard_UpdateKeyMap2(MKC_Right, Down); - break; - - case DVK_SHIFT: - Keyboard_UpdateKeyMap2(MKC_formac_Shift, true); - break; - - default: - if (Key > 0) { - DoKeyCode(Key, Down); - Keyboard_UpdateKeyMap2(MKC_formac_Shift, false); - } - break; - } -} - -LOCALPROC DS_HandleKeyboard(void) -{ - LastKeyboardKey = KeyboardKey; - KeyboardKey = keyboardUpdate(); - - if ((KeyboardKey == NOKEY) && (LastKeyboardKey != NOKEY)) { - DS_HandleKey(LastKeyboardKey, false); - LastKeyboardKey = NOKEY; - } else { - DS_HandleKey(KeyboardKey, true); - LastKeyboardKey = KeyboardKey; - } -} - -/* --- time, date, location --- */ - -LOCALVAR uint32_t TrueEmulatedTime = 0; - -#include "UTIL/DATE2SEC.h" - -#define TicksPerSecond 1000000 -/* #define TicksPerSecond 1000 */ - -LOCALVAR bool HaveTimeDelta = false; -LOCALVAR uint32_t TimeDelta; - -LOCALVAR uint32_t NewMacDateInSeconds; - -LOCALVAR uint32_t LastTimeSec; -LOCALVAR uint32_t LastTimeUsec; - -LOCALPROC GetCurrentTicks(void) -{ - struct timeval t; - - gettimeofday(&t, NULL); - - /* - HACKHACKHACK - */ - t.tv_usec = TimerBaseMSec + TIMER1_DATA; - t.tv_usec = t.tv_usec * 1000; - - if (! HaveTimeDelta) { - time_t Current_Time; - struct tm *s; - - (void) time(&Current_Time); - s = localtime(&Current_Time); - TimeDelta = Date2MacSeconds(s->tm_sec, s->tm_min, s->tm_hour, - s->tm_mday, 1 + s->tm_mon, 1900 + s->tm_year) - t.tv_sec; -#if 0 && AutoTimeZone /* how portable is this ? */ - CurMacDelta = ((uint32_t)(s->tm_gmtoff) & 0x00FFFFFF) - | ((s->tm_isdst ? 0x80 : 0) << 24); -#endif - HaveTimeDelta = true; - } - - NewMacDateInSeconds = t.tv_sec + TimeDelta; - LastTimeSec = (uint32_t)t.tv_sec; - LastTimeUsec = (uint32_t)t.tv_usec; -} - -/* #define InvTimeStep 16626 */ /* TicksPerSecond / 60.14742 */ -#define InvTimeStep 17 - -LOCALVAR uint32_t NextTimeSec; -LOCALVAR uint32_t NextTimeUsec; - -LOCALPROC IncrNextTime(void) -{ - NextTimeUsec += InvTimeStep; - if (NextTimeUsec >= TicksPerSecond) { - NextTimeUsec -= TicksPerSecond; - NextTimeSec += 1; - } -} - -LOCALPROC InitNextTime(void) -{ - NextTimeSec = LastTimeSec; - NextTimeUsec = LastTimeUsec; - IncrNextTime(); -} - -LOCALPROC StartUpTimeAdjust(void) -{ - GetCurrentTicks(); - InitNextTime(); -} - -LOCALFUNC int32_t GetTimeDiff(void) -{ - return ((int32_t)(LastTimeSec - NextTimeSec)) * TicksPerSecond - + ((int32_t)(LastTimeUsec - NextTimeUsec)); -} - -LOCALPROC UpdateTrueEmulatedTime(void) -{ - int32_t TimeDiff; - - GetCurrentTicks(); - - TimeDiff = GetTimeDiff(); - if (TimeDiff >= 0) { - if (TimeDiff > 4 * InvTimeStep) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - InitNextTime(); - } else { - do { - ++TrueEmulatedTime; - IncrNextTime(); - TimeDiff -= TicksPerSecond; - } while (TimeDiff >= 0); - } - } else if (TimeDiff < - 2 * InvTimeStep) { - /* clock goofed if ever get here, reset */ - InitNextTime(); - } -} - -LOCALFUNC bool CheckDateTime(void) -{ - if (CurMacDateInSeconds != NewMacDateInSeconds) { - CurMacDateInSeconds = NewMacDateInSeconds; - return true; - } else { - return false; - } -} - -LOCALFUNC bool InitLocationDat(void) -{ - GetCurrentTicks(); - CurMacDateInSeconds = NewMacDateInSeconds; - - return true; -} - -/* --- basic dialogs --- */ - -LOCALPROC CheckSavedMacMsg(void) -{ - /* called only on quit, if error saved but not yet reported */ - - if (nullpr != SavedBriefMsg) { - char briefMsg0[ClStrMaxLength + 1]; - char longMsg0[ClStrMaxLength + 1]; - - NativeStrFromCStr(briefMsg0, SavedBriefMsg); - NativeStrFromCStr(longMsg0, SavedLongMsg); - - fprintf(stderr, "%s\n", briefMsg0); - fprintf(stderr, "%s\n", longMsg0); - - SavedBriefMsg = nullpr; - } -} - -/* --- main window creation and disposal --- */ - -/* - Screen_Init - - Mode 5 gives us 2 text backgrounds 0-1 (tiled mode) and - 2 extended rotation backgrounds 2-3. (linear fb) - - Also we need to map 2 banks of vram so we have enough space for - our 512x512 surface. -*/ -LOCALFUNC bool Screen_Init(void) -{ - videoSetMode(MODE_5_2D); - vramSetBankA(VRAM_A_MAIN_BG_0x06000000); - vramSetBankB(VRAM_B_MAIN_BG_0x06020000); - - Display_bg2_Main = bgInit(2, BgType_Bmp8, BgSize_B8_512x512, 0, 0); - - BG_PALETTE[0] = RGB15(31, 31, 31); - BG_PALETTE[1] = RGB15(0, 0, 0); - - return true; -} - -#if 1 -LOCALPROC ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; -} -#endif - -/* --- SavedTasks --- */ - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif - - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if SoundEnabled - Sound_Stop(); -#endif -} - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped != SpeedStopped) { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - -#if IncludeSonyNew - if (vSonyNewDiskWanted) { -#if IncludeSonyNameNew - if (vSonyNewDiskName != NotAPbuf) { - uint8_t * NewDiskNameDat; - if (MacRomanTextToNativePtr(vSonyNewDiskName, true, - &NewDiskNameDat)) - { - MakeNewDisk(vSonyNewDiskSize, (char *)NewDiskNameDat); - free(NewDiskNameDat); - } - PbufDispose(vSonyNewDiskName); - vSonyNewDiskName = NotAPbuf; - } else -#endif - { - MakeNewDiskAtDefault(vSonyNewDiskSize); - } - vSonyNewDiskWanted = false; - /* must be done after may have gotten disk */ - } -#endif - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif -} - -/* --- main program flow --- */ - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -LOCALPROC WaitForTheNextEvent(void) -{ -} - -LOCALPROC CheckForSystemEvents(void) -{ - DS_HandleKeyboard(); -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ -label_retry: - CheckForSystemEvents(); - CheckForSavedTasks(); - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DrawChangesAndClear(); - WaitForTheNextEvent(); - goto label_retry; - } - - if (ExtraTimeNotOver()) { - int32_t TimeDiff = GetTimeDiff(); - if (TimeDiff < 0) { - /* - FIXME: - - Implement this? - - struct timespec rqt; - struct timespec rmt; - - rqt.tv_sec = 0; - rqt.tv_nsec = (- TimeDiff) * 1000; - - (void) nanosleep(&rqt, &rmt); - */ - } - goto label_retry; - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - CheckMouseState(); - - OnTrueTime = TrueEmulatedTime; -} - -/* - DS_ScrollBackground: - - Positions the screen as to center it over the emulated cursor. -*/ -LOCALPROC DS_ScrollBackground(void) -{ - int ScrollX = 0; - int ScrollY = 0; - int Scale = 0; - - /* - TODO: - Lots of magic numbers here. - */ -#if 1 - if (WantMagnify) { - ScrollX = ((int) CurMouseH) - (DS_ScreenWidth / 4); - ScrollY = ((int) CurMouseV) - (DS_ScreenHeight / 4); - Scale = 128; - - ScrollX = ScrollX > vMacScreenWidth - (DS_ScreenWidth / 2) - ? vMacScreenWidth - (DS_ScreenWidth / 2) - : ScrollX; - ScrollY = ScrollY > vMacScreenHeight - (DS_ScreenHeight / 2) - ? vMacScreenHeight - (DS_ScreenHeight / 2) - : ScrollY; - } else -#endif - { - ScrollX = ((int) CurMouseH) - (DS_ScreenWidth / 2); - ScrollY = ((int) CurMouseV) - (DS_ScreenHeight / 2); - Scale = 256; - - ScrollX = ScrollX > vMacScreenWidth - DS_ScreenWidth - ? vMacScreenWidth - DS_ScreenWidth - : ScrollX; - ScrollY = ScrollY > vMacScreenHeight - DS_ScreenHeight - ? vMacScreenHeight - DS_ScreenHeight - : ScrollY; - } - - ScrollX = ScrollX < 0 ? 0 : ScrollX; - ScrollY = ScrollY < 0 ? 0 : ScrollY; - - if (Display_bg2_Main) { - bgSetScale(Display_bg2_Main, Scale, Scale); - bgSetScroll(Display_bg2_Main, ScrollX, ScrollY); - } -} - -/* - DS_Timer1_IRQ - - Called when TIMER0_DATA overflows. -*/ -LOCALPROC DS_Timer1_IRQ(void) -{ - TimerBaseMSec += 65536; -} - -/* - DS_VBlank_IRQ - - Vertical blank interrupt callback. -*/ -LOCALPROC DS_VBlank_IRQ(void) -{ - scanKeys(); - - KeysHeld = keysHeld(); - - if (++VBlankCounter == 60) { - VBlankCounter = 0; - } - - /* - TODO: - Rewrite this at some point, I'm not sure I like it. - */ - if (0 != (KeysHeld & KEY_LEFT)) { - --CursorX; - } else if (0 != (KeysHeld & KEY_RIGHT)) { - ++CursorX; - } - - if (0 != (KeysHeld & KEY_UP)) { - --CursorY; - } else if (0 != (KeysHeld & KEY_DOWN)) { - ++CursorY; - } - - CursorX = CursorX < 0 ? 0 : CursorX; - CursorX = CursorX > vMacScreenWidth ? vMacScreenWidth : CursorX; - - CursorY = CursorY < 0 ? 0 : CursorY; - CursorY = CursorY > vMacScreenHeight ? vMacScreenHeight : CursorY; - - DS_ScrollBackground(); - bgUpdate(); -} - -/* - DS_HBlank_IRQ - - Called at the start of the horizontal blanking period. - This is here mainly as a simple performance test. -*/ -LOCALPROC DS_HBlank_IRQ(void) -{ - ++HBlankCounter; -} - -/* - DS_SysInit - - Initializes DS specific system hardware and interrupts. -*/ -LOCALPROC DS_SysInit(void) -{ - defaultExceptionHandler(); - powerOn(POWER_ALL_2D); - lcdMainOnTop(); - - irqSet(IRQ_VBLANK, DS_VBlank_IRQ); - irqSet(IRQ_HBLANK, DS_HBlank_IRQ); - irqSet(IRQ_TIMER1, DS_Timer1_IRQ); - - irqEnable(IRQ_VBLANK); - irqEnable(IRQ_HBLANK); - irqEnable(IRQ_TIMER1); - - /* - This sets up 2 timers as a milisecond counter. - TIMER0_DATA Will overflow roughly every 1 msec into TIMER1_DATA. - When TIMER1_DATA overflows an interrupt will be generated - and DS_Timer1_IRQ will be called. - */ - TIMER0_DATA = 32768; - - TIMER0_CR = TIMER_DIV_1 | TIMER_ENABLE; - - - - TIMER1_DATA = 0; - - TIMER1_CR = TIMER_ENABLE | TIMER_CASCADE | TIMER_IRQ_REQ; - - /* - Testing. - */ - consoleDemoInit(); - consoleDebugInit(DebugDevice_NOCASH); - - /* - Use the default keyboard until I design a (good) UI... - */ - DSKeyboard = keyboardDemoInit(); - keyboardShow(); - - /* - Drop back to a read only filesystem embedded in the - Mini vMac binary if we cannot open a media device. - */ - if (! fatInitDefault()) { - nitroFSInit(); - } -} - -/* - DS_ClearVRAM: - - Make sure all of the video memory and background/object palettes - are zeroed out just in-case the loader doesn't do it for us. -*/ -LOCALPROC DS_ClearVRAM(void) -{ - vramSetPrimaryBanks(VRAM_A_LCD, VRAM_B_LCD, VRAM_C_LCD, VRAM_D_LCD); - - dmaFillWords(0, (void *) VRAM_A, 128 * 1024 * 4); - dmaFillWords(0, (void *) BG_PALETTE, 256 * 2); - dmaFillWords(0, (void *) BG_PALETTE_SUB, 256 * 2); - dmaFillWords(0, (void *) SPRITE_PALETTE, 256 * 2); - dmaFillWords(0, (void *) SPRITE_PALETTE_SUB, 256 * 2); - - vramDefault(); -} - -/* --- platform independent code can be thought of as going here --- */ - -#include "PROGMAIN.h" - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif - -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)calloc(1, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALPROC UnallocMemory(void) -{ - if (nullpr != ReserveAllocBigBlock) { - free((char *)ReserveAllocBigBlock); - } -} - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); - DS_ClearVRAM(); -} - -LOCALFUNC bool InitOSGLU(void) -{ - DS_SysInit(); - - if (AllocMemory()) -#if dbglog_HAVE - if (dbglog_open()) -#endif - if (LoadMacRom()) - if (LoadInitialImages()) - if (InitLocationDat()) -#if SoundEnabled - if (Sound_Init()) -#endif - if (Screen_Init()) - if (KC2MKCInit()) - if (WaitForRom()) - { - return true; - } - - return false; -} - -LOCALPROC UnInitOSGLU(void) -{ - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - -#if SoundEnabled - Sound_Stop(); -#endif -#if SoundEnabled - Sound_UnInit(); -#endif - - UnInitDrives(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - UnallocMemory(); - CheckSavedMacMsg(); -} - -int main(int argc, char **argv) -{ - ZapOSGLUVars(); - - if (InitOSGLU()) { - iprintf("Entering ProgramMain...\n"); - - ProgramMain(); - - iprintf("Leaving ProgramMain...\n"); - } - - UnInitOSGLU(); - - /* - On some homebrew launchers this could return to - the menu by default. - */ - exit(1); - - while (1) { - swiWaitForVBlank(); - } - - return 0; -} diff --git a/src/UI/_deprecated/OLDMAC/ICONAPPM.r b/src/UI/_deprecated/OLDMAC/ICONAPPM.r deleted file mode 100644 index a314be4..0000000 --- a/src/UI/_deprecated/OLDMAC/ICONAPPM.r +++ /dev/null @@ -1,192 +0,0 @@ -/* - AppIcon.r - - Copyright (C) 2003 Philip Cummins, Richard F. Bannister, - Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -#if SmallIconAPIAvail -resource 'ics#' (AppIconId, purgeable) { - { /* array: 2 elements */ - /* [1] */ - $"0000 1FF8 2004 2FF4 2814 2A94 2B14 2A14" - $"2814 2FF4 2004 2004 20F4 2004 1FF8 1FF8", - /* [2] */ - $"0000 1FF8 3FFC 3FFC 3FFC 3FFC 3FFC 3FFC" - $"3FFC 3FFC 3FFC 3FFC 3FFC 3FFC 1FF8 1FF8" - } -}; -#endif - -#if ColorIconAPIAvail -resource 'ics8' (AppIconId, purgeable) { - $"0000 0000 0000 0000 0000 0000 0000 0000" - $"0000 00FF FFFF FFFF FFFF FFFF FF00 0000" - $"0000 FF2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000" - $"0000 FF2B FCFC FCFC FCFC FCFC 2BFF 0000" - $"0000 FF2B FC2A 2A2A 2A2A 2A00 2BFF 0000" - $"0000 FF2B FC2A EC2A EC2A 2A00 2BFF 0000" - $"0000 FF2B FC2A ECEC 2A2A 2A00 2BFF 0000" - $"0000 FF2B FC2A EC2A 2A2A 2A00 2BFF 0000" - $"0000 FF2B FC2A 2A2A 2A2A 2A00 2BFF 0000" - $"0000 FF2B FA00 0000 0000 0000 2BFF 0000" - $"0000 FF2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000" - $"0000 FF2B E32B 2B2B 2B2B 2B2B 2BFF 0000" - $"0000 FF2B D82B 2B2B FFFF FFFF 2BFF 0000" - $"0000 FF2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000" - $"0000 00FD FDFD FDFD FDFF FFFF FF00 0000" - $"0000 00FF FFFF FFFF FFFF FFFF FF" -}; -#endif - -#if ColorIconAPIAvail -resource 'ics4' (AppIconId, purgeable) { - $"0000 0000 0000 0000 000F FFFF FFFF F000" - $"00FC CCCC CCCC CF00 00FC EEEE EEEE CF00" - $"00FC ED0D 0D0C CF00 00FC E060 60D0 CF00" - $"00FC ED66 0D0C CF00 00FC E060 D0D0 CF00" - $"00FC ED0D 0D0C CF00 00FC D0C0 C0C0 CF00" - $"00FC CCCC CCCC CF00 00FC 8CCC CCCC CF00" - $"00FC 3CCC FFFF CF00 00FC CCCC CCCC CF00" - $"000F FFFF FFFF F000 000F FFFF FFFF F0" -}; -#endif - -resource 'ICN#' (AppIconId, purgeable) { - { /* array: 2 elements */ - /* [1] */ - $"0000 0000 07FF FFE0 0800 0010 0800 0010" - $"08FF FF10 0900 0090 0918 1890 0918 3090" - $"0918 6090 0918 C090 0919 8090 091B 0090" - $"091E 0090 091C 0090 0918 0090 0910 0090" - $"0900 0090 08FF FF10 0800 0010 0800 0010" - $"0800 0010 0800 0010 0800 FF10 0800 0010" - $"0800 0010 0800 0010 0800 0010 07FF FFE0" - $"0400 0020 0400 0020 0400 0020 07FF FFE0", - /* [2] */ - $"0000 0000 07FF FFE0 0FFF FFF0 0FFF FFF0" - $"0FFF FFF0 0FFF FFF0 0FFF FFF0 0FFF FFF0" - $"0FFF FFF0 0FFF FFF0 0FFF FFF0 0FFF FFF0" - $"0FFF FFF0 0FFF FFF0 0FFF FFF0 0FFF FFF0" - $"0FFF FFF0 0FFF FFF0 0FFF FFF0 0FFF FFF0" - $"0FFF FFF0 0FFF FFF0 0FFF FFF0 0FFF FFF0" - $"0FFF FFF0 0FFF FFF0 0FFF FFF0 07FF FFE0" - $"07FF FFE0 07FF FFE0 07FF FFE0 07FF FFE0" - } -}; - -#if ColorIconAPIAvail -resource 'icl8' (AppIconId, purgeable) { - $"0000 0000 0000 0000 0000 0000 0000 0000" - $"0000 0000 0000 0000 0000 0000 0000 0000" - $"0000 0000 00FF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFFF FFFF FFFF FF00 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B FCFC FCFC FCFC FCFC" - $"FCFC FCFC FCFC FCFC 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2A2A 2A2A 2A2A" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A 2A2A" - $"2A2A 2AEC EC2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A 2A2A" - $"2A2A ECEC 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A 2A2A" - $"2AEC EC2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A 2A2A" - $"ECEC 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A 2AEC" - $"EC2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A ECEC" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC ECEC EC2A" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC ECEC 2A2A" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC EC2A 2A2A" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2AEC 2A2A 2A2A" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2BFC 2A2A 2A2A 2A2A 2A2A" - $"2A2A 2A2A 2A2A 2A2A 002B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 0000 0000 0000 0000" - $"0000 0000 0000 0000 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"FFFF FFFF FFFF FFFF 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"0000 0000 0000 0000 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2BE3 E32B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2BD8 D82B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 FF2B 2B2B 2B2B 2B2B 2B2B 2B2B" - $"2B2B 2B2B 2B2B 2B2B 2B2B 2BFF 0000 0000" - $"0000 0000 00FF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFFF FFFF FFFF FF00 0000 0000" - $"0000 0000 00FF FBFB FBFB FBFB FCFC FCFC" - $"FCFD FDFD FDFD FDFD FDFD FF00 0000 0000" - $"0000 0000 00FF FAFA FAFA FAFA FAFA FBFB" - $"FCFC FCFC FDFD FDFD FDFD FF00 0000 0000" - $"0000 0000 00FF F9F9 F9F9 F9F9 F9F9 FAFA" - $"FAFB FBFC FCFC FCFD FDFD FF00 0000 0000" - $"0000 0000 00FF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFFF FFFF FFFF FF" -}; -#endif - -#if ColorIconAPIAvail -resource 'icl4' (AppIconId, purgeable) { - $"0000 0000 0000 0000 0000 0000 0000 0000" - $"0000 0FFF FFFF FFFF FFFF FFFF FFF0 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC EEEE EEEE EEEE EEEE CCCF 0000" - $"0000 FCCE 0D0D 0D0D 0D0D 0D0D 0CCF 0000" - $"0000 FCCE D0D6 60D0 D0D6 60D0 CCCF 0000" - $"0000 FCCE 0D06 6D0D 0D66 0D0D 0CCF 0000" - $"0000 FCCE D0D6 60D0 D660 D0D0 CCCF 0000" - $"0000 FCCE 0D06 6D0D 660D 0D0D 0CCF 0000" - $"0000 FCCE D0D6 60D6 60D0 D0D0 CCCF 0000" - $"0000 FCCE 0D06 6D66 0D0D 0D0D 0CCF 0000" - $"0000 FCCE D0D6 6660 D0D0 D0D0 CCCF 0000" - $"0000 FCCE 0D06 660D 0D0D 0D0D 0CCF 0000" - $"0000 FCCE D0D6 60D0 D0D0 D0D0 CCCF 0000" - $"0000 FCCE 0D06 0D0D 0D0D 0D0D 0CCF 0000" - $"0000 FCCE D0D0 D0D0 D0D0 D0D0 CCCF 0000" - $"0000 FCCC 0C0C 0C0C 0C0C 0C0C 0CCF 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC CCCC CCCC FFFF FFFF CCCF 0000" - $"0000 FCCC CCCC CCCC 0C0C 0C0C CCCF 0000" - $"0000 FCC8 8CCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCC3 3CCC CCCC CCCC CCCC CCCF 0000" - $"0000 FCCC CCCC CCCC CCCC CCCC CCCF 0000" - $"0000 0FFF FFFF FFFF FFFF FFFF FFF0 0000" - $"0000 0FEE EEEE EEEE EEFF FFFF FFF0 0000" - $"0000 0FDD DDDD DDEE EEEE EEFF FFF0 0000" - $"0000 0FDD DDDD DDDD DEEE EEEE EEF0 0000" - $"0000 0FFF FFFF FFFF FFFF FFFF FFF0" -}; -#endif diff --git a/src/UI/_deprecated/OLDMAC/ICONDSKM.r b/src/UI/_deprecated/OLDMAC/ICONDSKM.r deleted file mode 100644 index 1dc99a5..0000000 --- a/src/UI/_deprecated/OLDMAC/ICONDSKM.r +++ /dev/null @@ -1,192 +0,0 @@ -/* - DskIcon.r - - Copyright (C) 2003 Philip Cummins, Richard F. Bannister, - Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -#if SmallIconAPIAvail -resource 'ics#' (DskIconId, purgeable) { - { /* array: 2 elements */ - /* [1] */ - $"7FE0 4030 4028 403C 4004 4004 4004 4FC4" - $"4AA4 4BA4 4824 4BA4 4AA4 4FE4 4004 7FFC", - /* [2] */ - $"7FE0 7FF0 7FF8 7FFC 7FFC 7FFC 7FFC 7FFC" - $"7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC" - } -}; -#endif - -#if ColorIconAPIAvail -resource 'ics8' (DskIconId, purgeable) { - $"00FF FFFF FFFF FFFF FFFF FF00 0000 0000" - $"00FF 0000 0000 0000 0000 FFFF 0000 0000" - $"00FF 0000 0000 0000 0000 FF2A FF00 0000" - $"00FF 0000 0000 0000 0000 FFFF FFFF 0000" - $"00FF 0000 0000 0000 0000 00FA FAFF 0000" - $"00FF 0000 0000 0000 0000 0000 00FF 0000" - $"00FF 0000 0000 0000 0000 0000 00FF 0000" - $"00FF 0000 E0E0 E0E0 E0E0 0000 00FF 0000" - $"00FF 0000 E054 AB2A AB54 E000 00FF 0000" - $"00FF 0000 E054 ABAB AB54 E000 00FF 0000" - $"00FF 0000 E054 5454 5454 E000 00FF 0000" - $"00FF 0000 E054 ABAB AB54 E000 00FF 0000" - $"00FF 0000 E054 AB2A AB54 E000 00FF 0000" - $"00FF 0000 E0FF E0E0 E0E0 E000 00FF 0000" - $"00FF 0000 0000 0000 0000 0000 00FF 0000" - $"00FF FFFF FFFF FFFF FFFF FFFF FFFF" -}; -#endif - -#if ColorIconAPIAvail -resource 'ics4' (DskIconId, purgeable) { - $"0FFF FFFF FFF0 0000 0F00 0000 00FF 0000" - $"0F00 0000 00FC F000 0F00 0000 00FF FF00" - $"0F00 0000 000D DF00 0F00 0000 0000 0F00" - $"0F00 0000 0000 0F00 0F00 FFFF FF00 0F00" - $"0F00 FCE0 ECF0 0F00 0F00 FCEE ECF0 0F00" - $"0F00 FCCC CCF0 0F00 0F00 FCEE ECF0 0F00" - $"0F00 FCE0 ECF0 0F00 0F00 FFFF FFF0 0F00" - $"0F00 0000 0000 0F00 0FFF FFFF FFFF FF" -}; -#endif - -resource 'ICN#' (DskIconId, purgeable) { - { /* array: 2 elements */ - /* [1] */ - $"1FFF F800 1000 0C00 1000 0A00 1000 0900" - $"1000 0880 1000 0840 1000 0820 1000 0FF0" - $"1000 0010 1000 0010 1000 0010 1000 0010" - $"1000 0010 10FF FC10 1120 9210 1121 5110" - $"1121 5110 1121 5110 1120 9110 111F E110" - $"1100 0110 1100 0110 111F F110 1120 0910" - $"1120 0910 1122 8910 1123 0910 1122 0910" - $"1120 0910 10FF FE10 1000 0010 1FFF FFF0", - /* [2] */ - $"1FFF F800 1FFF FC00 1FFF FE00 1FFF FF00" - $"1FFF FF80 1FFF FFC0 1FFF FFE0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - } -}; - -#if ColorIconAPIAvail -resource 'icl8' (DskIconId, purgeable) { - $"0000 00FF FFFF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FF00 0000 0000 0000 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FFFF 0000 0000 0000 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FF2A FF00 0000 0000 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FF2A 2AFF 0000 0000 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FF2A 2A2A FF00 0000 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FF2A 2A2A 2AFF 0000 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FF2A 2A2A 2A2A FF00 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 FFFF FFFF FFFF FFFF 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 00FA FAFA FAFA FAFF 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 0000 0000 0000 00FF 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 0000 0000 0000 00FF 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 0000 0000 0000 00FF 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 0000 0000 0000 00FF 0000 0000" - $"0000 00FF 0000 00F5 E0FF E0E0 E0E0 E0E0" - $"E0E0 E0E0 E0E0 0000 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2AFA" - $"FFFA 2AAB 5454 E000 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2AFF" - $"00FF 2AAB 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2AFF" - $"00FF 2AAB 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2AFF" - $"00FF 2AAB 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2AFA" - $"FFFA 2AAB 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 54AB ABAB ABAB" - $"ABAB AB54 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 5454 5454 5454" - $"5454 5454 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 5454 5454 5454" - $"5454 5454 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 54AB ABAB ABAB" - $"ABAB ABAB 5454 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2A2A" - $"2A2A 2A2A AB54 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2A2A" - $"2A2A 2A2A AB54 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A EC2A" - $"EC2A 2A2A AB54 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A ECEC" - $"2A2A 2A2A AB54 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A EC2A" - $"2A2A 2A2A AB54 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00E0 5454 AB2A 2A2A 2A2A" - $"2A2A 2A2A AB54 54E0 0000 00FF 0000 0000" - $"0000 00FF 0000 00F5 FFFF E0E0 E0E0 E0E0" - $"E0E0 E0E0 FFE0 E0F5 0000 00FF 0000 0000" - $"0000 00FF 0000 0000 0000 0000 0000 0000" - $"0000 0000 0000 0000 0000 00FF 0000 0000" - $"0000 00FF FFFF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFFF FFFF FFFF FFFF" -}; -#endif - -#if ColorIconAPIAvail -resource 'icl4' (DskIconId, purgeable) { - $"000F FFFF FFFF FFFF FFFF F000 0000 0000" - $"000F 0000 0000 0000 0000 FF00 0000 0000" - $"000F 0000 0000 0000 0000 F0F0 0000 0000" - $"000F 0000 0000 0000 0000 FC0F 0000 0000" - $"000F 0000 0000 0000 0000 F0C0 F000 0000" - $"000F 0000 0000 0000 0000 FC0C 0F00 0000" - $"000F 0000 0000 0000 0000 F0C0 C0F0 0000" - $"000F 0000 0000 0000 0000 FFFF FFFF 0000" - $"000F 0000 0000 0000 0000 0DDD DDDF 0000" - $"000F 0000 0000 0000 0000 0000 000F 0000" - $"000F 0000 0000 0000 0000 0000 000F 0000" - $"000F 0000 0000 0000 0000 0000 000F 0000" - $"000F 0000 0000 0000 0000 0000 000F 0000" - $"000F 0000 FFFF FFFF FFFF FF00 000F 0000" - $"000F 000F CCEC 0C0D FD0E CCF0 000F 0000" - $"000F 000F CCE0 C0CF 0FCE CCCF 000F 0000" - $"000F 000F CCEC 0C0F 0F0E CCCF 000F 0000" - $"000F 000F CCE0 C0CF 0FCE CCCF 000F 0000" - $"000F 000F CCEC 0C0D FD0E CCCF 000F 0000" - $"000F 000F CCCE EEEE EEEC CCCF 000F 0000" - $"000F 000F CCCC CCCC CCCC CCCF 000F 0000" - $"000F 000F CCCC CCCC CCCC CCCF 000F 0000" - $"000F 000F CCCE EEEE EEEE CCCF 000F 0000" - $"000F 000F CCEC 0C0C 0C0C ECCF 000F 0000" - $"000F 000F CCE0 C0C0 C0C0 ECCF 000F 0000" - $"000F 000F CCEC 0C6C 6C0C ECCF 000F 0000" - $"000F 000F CCE0 C066 C0C0 ECCF 000F 0000" - $"000F 000F CCEC 0C6C 0C0C ECCF 000F 0000" - $"000F 000F CCE0 C0C0 C0C0 ECCF 000F 0000" - $"000F 0000 FFFF FFFF FFFF FFF0 000F 0000" - $"000F 0000 0000 0000 0000 0000 000F 0000" - $"000F FFFF FFFF FFFF FFFF FFFF FFFF" -}; -#endif diff --git a/src/UI/_deprecated/OLDMAC/ICONROMM.r b/src/UI/_deprecated/OLDMAC/ICONROMM.r deleted file mode 100644 index b65f7f1..0000000 --- a/src/UI/_deprecated/OLDMAC/ICONROMM.r +++ /dev/null @@ -1,192 +0,0 @@ -/* - RomIcon.r - - Copyright (C) 2003 Philip Cummins, Richard F. Bannister, - Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -#if SmallIconAPIAvail -resource 'ics#' (RomIconId, purgeable) { - { /* array: 2 elements */ - /* [1] */ - $"7FE0 4030 4028 403C 4004 5FC4 5FC4 5FC4" - $"5FC4 4004 5FC4 5FC4 5FC4 5FC4 4004 7FFC", - /* [2] */ - $"7FE0 7FF0 7FF8 7FFC 7FFC 7FFC 7FFC 7FFC" - $"7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC 7FFC" - } -}; -#endif - -#if ColorIconAPIAvail -resource 'ics8' (RomIconId, purgeable) { - $"00FF FFFF FFFF FFFF FFFF FF00 0000 0000" - $"00FF F5F5 F5F5 F5F5 F5F5 FFFF 0000 0000" - $"00FF F5F5 F5F5 F5F5 F5F5 FF2B FF00 0000" - $"00FF F5F5 F5F5 F5F5 F5F5 FFFF FFFF 0000" - $"00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5FF FFFF FFFF FFFF F5F5 F5FF 0000" - $"00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000" - $"00FF FFFF FFFF FFFF FFFF FFFF FFFF" -}; -#endif - -#if ColorIconAPIAvail -resource 'ics4' (RomIconId, purgeable) { - $"0FFF FFFF FFF0 0000 0F0C 0C0C 0CFF 0000" - $"0FC0 C0C0 C0FC F000 0F0C 0C0C 0CFF FF00" - $"0FC0 C0C0 C0C0 CF00 0F0F FFFF FF0C 0F00" - $"0FCF FFFF FFC0 CF00 0F0F FFFF FF0C 0F00" - $"0FCF FFFF FFC0 CF00 0F0C 0C0C 0C0C 0F00" - $"0FCF FFFF FFC0 CF00 0F0F FFFF FF0C 0F00" - $"0FCF FFFF FFC0 CF00 0F0F FFFF FF0C 0F00" - $"0FC0 C0C0 C0C0 CF00 0FFF FFFF FFFF FF" -}; -#endif - -resource 'ICN#' (RomIconId, purgeable) { - { /* array: 2 elements */ - /* [1] */ - $"1FFF FC00 1000 0600 1000 0500 1000 0480" - $"1000 0440 1000 0420 1000 07F0 1000 0010" - $"1155 5010 12AA A810 13FF F810 13FF F810" - $"13FF F810 13FF F810 13FF F810 13FF F810" - $"12AA A810 1155 5010 1000 0010 1155 5010" - $"12AA A810 13FF F810 13FF F810 13FF F810" - $"13FF F810 13FF F810 13FF F810 12AA A810" - $"1155 5010 1000 0010 1000 0010 1FFF FFF0", - /* [2] */ - $"1FFF FC00 1FFF FE00 1FFF FF00 1FFF FF80" - $"1FFF FFC0 1FFF FFE0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - $"1FFF FFF0 1FFF FFF0 1FFF FFF0 1FFF FFF0" - } -}; - -#if ColorIconAPIAvail -resource 'icl8' (RomIconId, purgeable) { - $"0000 00FF FFFF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFFF 0000 0000 0000 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5FF FF00 0000 0000 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5FF 2BFF 0000 0000 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5FF 2B2B FF00 0000 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5FF 2B2B 2BFF 0000 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5FF 2B2B 2B2B FF00 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5FF FFFF FFFF FFFF 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5FF F5FF F5FF F5FF F5FF" - $"F5FF F5FF F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FF00 FF00 FF00 FF00 FF00" - $"FF00 FF00 FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FF00 FF00 FF00 FF00 FF00" - $"FF00 FF00 FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5FF F5FF F5FF F5FF F5FF" - $"F5FF F5FF F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5FF F5FF F5FF F5FF F5FF" - $"F5FF F5FF F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FF00 FF00 FF00 FF00 FF00" - $"FF00 FF00 FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 FF00 FF00 FF00 FF00 FF00" - $"FF00 FF00 FFF5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5FF F5FF F5FF F5FF F5FF" - $"F5FF F5FF F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF F5F5 F5F5 F5F5 F5F5 F5F5 F5F5" - $"F5F5 F5F5 F5F5 F5F5 F5F5 F5FF 0000 0000" - $"0000 00FF FFFF FFFF FFFF FFFF FFFF FFFF" - $"FFFF FFFF FFFF FFFF FFFF FFFF" -}; -#endif - -#if ColorIconAPIAvail -resource 'icl4' (RomIconId, purgeable) { - $"000F FFFF FFFF FFFF FFFF FF00 0000 0000" - $"000F 0C0C 0C0C 0C0C 0C0C 0FF0 0000 0000" - $"000F C0C0 C0C0 C0C0 C0C0 CFCF 0000 0000" - $"000F 0C0C 0C0C 0C0C 0C0C 0FCC F000 0000" - $"000F C0C0 C0C0 C0C0 C0C0 CFCC CF00 0000" - $"000F 0C0C 0C0C 0C0C 0C0C 0FCC CCF0 0000" - $"000F C0C0 C0C0 C0C0 C0C0 CFFF FFFF 0000" - $"000F 0C0C 0C0C 0C0C 0C0C 0C0C 0C0F 0000" - $"000F C0CF CFCF CFCF CFCF C0C0 C0CF 0000" - $"000F 0CF0 F0F0 F0F0 F0F0 FC0C 0C0F 0000" - $"000F C0FF FFFF FFFF FFFF F0C0 C0CF 0000" - $"000F 0CFF FFFF FFFF FFFF FC0C 0C0F 0000" - $"000F C0FF FFFF FFFF FFFF F0C0 C0CF 0000" - $"000F 0CFF FFFF FFFF FFFF FC0C 0C0F 0000" - $"000F C0FF FFFF FFFF FFFF F0C0 C0CF 0000" - $"000F 0CFF FFFF FFFF FFFF FC0C 0C0F 0000" - $"000F C0F0 F0F0 F0F0 F0F0 F0C0 C0CF 0000" - $"000F 0C0F 0F0F 0F0F 0F0F 0C0C 0C0F 0000" - $"000F C0C0 C0C0 C0C0 C0C0 C0C0 C0CF 0000" - $"000F 0C0F 0F0F 0F0F 0F0F 0C0C 0C0F 0000" - $"000F C0F0 F0F0 F0F0 F0F0 F0C0 C0CF 0000" - $"000F 0CFF FFFF FFFF FFFF FC0C 0C0F 0000" - $"000F C0FF FFFF FFFF FFFF F0C0 C0CF 0000" - $"000F 0CFF FFFF FFFF FFFF FC0C 0C0F 0000" - $"000F C0FF FFFF FFFF FFFF F0C0 C0CF 0000" - $"000F 0CFF FFFF FFFF FFFF FC0C 0C0F 0000" - $"000F C0FF FFFF FFFF FFFF F0C0 C0CF 0000" - $"000F 0CF0 F0F0 F0F0 F0F0 FC0C 0C0F 0000" - $"000F C0CF CFCF CFCF CFCF C0C0 C0CF 0000" - $"000F 0C0C 0C0C 0C0C 0C0C 0C0C 0C0F 0000" - $"000F C0C0 C0C0 C0C0 C0C0 C0C0 C0CF 0000" - $"000F FFFF FFFF FFFF FFFF FFFF FFFF" -}; -#endif diff --git a/src/UI/_deprecated/OLDMAC/OSGLUMAC.c b/src/UI/_deprecated/OLDMAC/OSGLUMAC.c deleted file mode 100644 index a979912..0000000 --- a/src/UI/_deprecated/OLDMAC/OSGLUMAC.c +++ /dev/null @@ -1,5765 +0,0 @@ -/* - OSGLUMAC.c - - Copyright (C) 2009 Philip Cummins, Richard F. Bannister, - Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for MACintosh - - All operating system dependent code for the - Macintosh (pre OS X) platform should go here. - - This is also the "reference" implementation. General - comments about what the platform dependent code - does should go here, and not be repeated for each - platform. - - This code is descended from Richard F. Bannister's Macintosh - port of vMac, by Philip Cummins. - - The main entry point 'main' is at the end of this file. -*/ - -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" - -#include "UI/MYOSGLUE.h" - -#include "STRCONST.h" - -#ifndef NavigationAvail -#define NavigationAvail 1 -#endif - -#ifndef AppearanceAvail -#define AppearanceAvail 1 -#endif - -#ifndef NewNamesAvail -#define NewNamesAvail 1 -#endif - -#ifndef CALL_NOT_IN_CARBON -#define CALL_NOT_IN_CARBON 1 -#endif /* !defined(CALL_NOT_IN_CARBON) */ - - -/* --- information about the environment --- */ - -/* - code to determine characteristics - of the current run time environment. -*/ - -#define TestBit(i, p) (((uimr)(i) & ((uimr)1 << (p))) != 0) - -#ifndef HaveCPUfamM68K -#define HaveCPUfamM68K 0 -#endif - -#if HaveCPUfamM68K - -/* MACENVRN.i */ - -#ifndef Support64kROM -#define Support64kROM 1 -#endif - -#define Have64kROM() (LMGetROM85() < 0) - -/* -- basic environment checking -- */ - -#ifndef DebugTrapAvailableChecks -#define DebugTrapAvailableChecks 0 -#endif - -LOCALFUNC bool LowToolTrapAvailable(short trap_num) -{ -#if DebugTrapAvailableChecks - if ((trap_num & 0x0800) == 0) { - DebugStr("\pOSTrap in LowToolTrapAvailable"); - return false; - } - if ((trap_num & 0x07ff) >= 0x200) { - DebugStr("\pHiToolTrap in LowToolTrapAvailable"); - return false; - } -#endif - return GetToolTrapAddress(trap_num) != - GetToolTrapAddress(_Unimplemented); -} - -LOCALFUNC bool HiToolTrapAvailable(short trap_num) -{ -#if DebugTrapAvailableChecks - if ((trap_num & 0x0800) == 0) { - DebugStr("\pOSTrap in HiToolTrapAvailable"); - return false; - } - if (((trap_num & 0x07ff) < 0x200) - || ((trap_num & 0x07ff) >= 0x400)) - { - DebugStr("\pLowToolTrap in HiToolTrapAvailable"); - return false; - } -#endif - if (GetToolTrapAddress(_InitGraf) - == GetToolTrapAddress(0xAA6E)) - { - return false; - } else { - return GetToolTrapAddress(trap_num) != - GetToolTrapAddress(_Unimplemented); - } -} - -LOCALFUNC bool OSTrapAvailable(short trap_num) -{ -#if DebugTrapAvailableChecks - if ((trap_num & 0x0800) != 0) { - DebugStr("\pToolTrap in ToolTrapAvailable"); - return false; - } -#endif - return GetOSTrapAddress(trap_num) != - GetToolTrapAddress(_Unimplemented); -} - -LOCALVAR bool EnvrAttrWaitNextEventAvail; -LOCALVAR bool HaveEnvrAttrWaitNextEventAvail = false; - -LOCALFUNC bool HaveWaitNextEventAvail(void) -{ - if (! HaveEnvrAttrWaitNextEventAvail) { - EnvrAttrWaitNextEventAvail = - LowToolTrapAvailable(_WaitNextEvent); - HaveEnvrAttrWaitNextEventAvail = true; - } - return EnvrAttrWaitNextEventAvail; -} - -LOCALVAR bool EnvrAttrGestaltAvail; -LOCALVAR bool HaveEnvrAttrGestaltAvail = false; - -LOCALFUNC bool HaveGestaltAvail(void) -{ - if (! HaveEnvrAttrGestaltAvail) { - EnvrAttrGestaltAvail = - (! Have64kROM()) && - OSTrapAvailable(_Gestalt); - /* - contrary to all the documentation, - TrapAvailable check by itself doesn't - work on 64k ROM, because a tool box trap - has the same trap number, and both - GetOSTrapAddress and GetToolTrapAddress - are the same as GetTrapAddress on a 64k ROM. - */ - HaveEnvrAttrGestaltAvail = true; - } - return EnvrAttrGestaltAvail; -} - -#else - -/* for PowerPC, assume always have these routines */ - -#define HaveWaitNextEventAvail() true -#define HaveGestaltAvail() true - -#endif - -LOCALVAR bool EnvrAttrAliasMgrAvail; -LOCALVAR bool HaveEnvrAttrAliasMgrAvail = false; - -LOCALFUNC bool HaveAliasMgrAvail(void) -{ - if (! HaveEnvrAttrAliasMgrAvail) { - long reply; - - EnvrAttrAliasMgrAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltAliasMgrAttr, &reply)) - && TestBit(reply, gestaltAliasMgrPresent); - HaveEnvrAttrAliasMgrAvail = true; - } - return EnvrAttrAliasMgrAvail; -} - -LOCALVAR bool EnvrAttrAppleEvtMgrAvail; -LOCALVAR bool HaveEnvrAttrAppleEvtMgrAvail = false; - -LOCALFUNC bool HaveAppleEvtMgrAvail(void) -{ - if (! HaveEnvrAttrAppleEvtMgrAvail) { - long reply; - - EnvrAttrAppleEvtMgrAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltAppleEventsAttr, &reply)) - && TestBit(reply, gestaltAppleEventsPresent); - HaveEnvrAttrAppleEvtMgrAvail = true; - } - return EnvrAttrAppleEvtMgrAvail; -} - -#if EnableDragDrop - -LOCALVAR bool EnvrAttrDragMgrAvail; -LOCALVAR bool HaveEnvrAttrDragMgrAvail = false; - -LOCALFUNC bool HaveDragMgrAvail(void) -{ - if (! HaveEnvrAttrDragMgrAvail) { - long reply; - - EnvrAttrDragMgrAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltDragMgrAttr, &reply)) - && TestBit(reply, gestaltDragMgrPresent); - HaveEnvrAttrDragMgrAvail = true; - } - return EnvrAttrDragMgrAvail; -} - -#endif - -#ifndef Windows85APIAvail -#define Windows85APIAvail 1 -#endif - -#if Windows85APIAvail -LOCALVAR bool EnvrAttrHideShowMenuAvail; -LOCALVAR bool HaveEnvrAttrHideShowMenuAvail = false; - -LOCALFUNC bool HaveHideShowMenuAvail(void) -{ - if (! HaveEnvrAttrHideShowMenuAvail) { - long reply; - - EnvrAttrHideShowMenuAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltMenuMgrAttr, &reply)); - HaveEnvrAttrHideShowMenuAvail = true; - } - return EnvrAttrHideShowMenuAvail; -} -#endif - -#if AppearanceAvail -LOCALVAR bool EnvrAttrAppearanceAvail; -LOCALVAR bool HaveEnvrAttrAppearanceAvail = false; - -LOCALFUNC bool HaveAppearanceAvail(void) -{ - if (! HaveEnvrAttrAppearanceAvail) { - long reply; - - EnvrAttrAppearanceAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltAppearanceAttr, &reply)); - HaveEnvrAttrAppearanceAvail = true; - } - return EnvrAttrAppearanceAvail; -} -#endif - -#if HaveCPUfamM68K -LOCALVAR bool EnvrAttrSndMngrAvail; -LOCALVAR bool HaveEnvrAttrSndMngrAvail = false; - -LOCALFUNC bool HaveSndMngrAvail(void) -{ - if (! HaveEnvrAttrSndMngrAvail) { - EnvrAttrSndMngrAvail = LowToolTrapAvailable(_SndNewChannel); - HaveEnvrAttrSndMngrAvail = true; - } - return EnvrAttrSndMngrAvail; -} -#endif - -#if NavigationAvail -LOCALVAR bool EnvrAttrNavServicesAvail; -LOCALVAR bool HaveEnvrAttrNavServicesAvail = false; - -LOCALFUNC bool HaveNavServicesAvail(void) -{ - if (! HaveEnvrAttrNavServicesAvail) { - EnvrAttrNavServicesAvail = NavServicesAvailable(); - HaveEnvrAttrNavServicesAvail = true; - } - return EnvrAttrNavServicesAvail; -} -#endif - -#if HaveCPUfamM68K -LOCALVAR bool EnvrAttrFSSpecCallsAvail; -LOCALVAR bool HaveEnvrAttrFSSpecCallsAvail = false; - -LOCALFUNC bool HaveFSSpecCallsAvail(void) -{ - if (! HaveEnvrAttrFSSpecCallsAvail) { - long reply; - - EnvrAttrFSSpecCallsAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltFSAttr, &reply)) - && TestBit(reply, gestaltHasFSSpecCalls); - HaveEnvrAttrFSSpecCallsAvail = true; - } - return EnvrAttrFSSpecCallsAvail; -} -#endif - -#if Windows85APIAvail -LOCALVAR bool EnvrAttrNewWndMgrAvail; -LOCALVAR bool HaveEnvrAttrNewWndMgrAvail = false; - -LOCALFUNC bool HaveNewWndMgrAvail(void) -{ - if (! HaveEnvrAttrNewWndMgrAvail) { - long reply; - - EnvrAttrNewWndMgrAvail = - HaveGestaltAvail() - && (noErr == Gestalt(gestaltWindowMgrAttr, &reply)) - && TestBit(reply, gestaltWindowMgrPresentBit); - HaveEnvrAttrNewWndMgrAvail = true; - } - return EnvrAttrNewWndMgrAvail; -} -#endif - -/* --- initial initialization --- */ - -#if defined(__SC__) || ((defined(powerc) || defined(__powerc)) \ - && ! defined(__MWERKS__)) - -/* GLOBALVAR */ QDGlobals qd; -#endif - -LOCALFUNC bool InitMacManagers(void) -{ - MaxApplZone(); - - { - int i; - - for (i = 7; --i >= 0; ) { - MoreMasters(); - } - } - - InitGraf(&qd.thePort); - InitFonts(); - InitWindows(); - InitMenus(); - TEInit(); - InitDialogs(NULL); - InitCursor(); - return true; -} - - -/* --- mac style errors --- */ - -#define CheckSavetMacErr(result) (mnvm_noErr == (err = (result))) - /* - where 'err' is a variable of type MacErr_t in the function - this is used in - */ - -#define To_tMacErr(result) ((MacErr_t)(uint16_t)(result)) - -#define CheckSaveMacErr(result) (CheckSavetMacErr(To_tMacErr(result))) - - -/* - define NotAfileRef to some value that is different - from any valid open file reference. -*/ -#define NotAfileRef (-1) - -struct Dir_R { - long DirId; - short VRefNum; -}; -typedef struct Dir_R Dir_R; - -LOCALFUNC MacErr_t OpenNamedFileInFolder(Dir_R *d, - ps3p fileName, short *refnum) -{ - MacErr_t err; - -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - err = To_tMacErr(FSOpen(fileName, d->VRefNum, refnum)); - } else -#endif - { - Boolean isFolder; - Boolean isAlias; - FSSpec spec; - - if (CheckSaveMacErr( - FSMakeFSSpec(d->VRefNum, d->DirId, fileName, &spec))) - if (CheckSaveMacErr( - ResolveAliasFile(&spec, true, &isFolder, &isAlias))) - if (CheckSaveMacErr( - FSpOpenDF(&spec, fsRdPerm, refnum))) - { - } - } - - return err; -} - -/* --- sending debugging info to file --- */ - -#if dbglog_HAVE - -#define Support64kROM 0 -#define tErr MacErr_t - -typedef unsigned char * Ptr; - -LOCALFUNC tErr HGetDir_v2(Dir_R *d) -{ - tErr err; - WDPBRec r; - - r.ioCompletion = NULL; - r.ioNamePtr = NULL; - -#if Support64kROM - if (Have64kROM()) { - err = PBGetVolSync((ParamBlockRec *)&r); - d->VRefNum = r.ioVRefNum; - d->DirId = 0; - } else -#endif - { - err = PBHGetVolSync(&r); - d->VRefNum = r.ioWDVRefNum; - d->DirId = r.ioWDDirID; - } - - return err; -} - -LOCALFUNC tErr WriteBytes_v2(short refNum, Ptr p, uimr L) -{ - ParamBlockRec r; - - r.ioParam.ioCompletion = NULL; - r.ioParam.ioRefNum = refNum; - r.ioParam.ioBuffer = (Ptr)p; - r.ioParam.ioReqCount = L; - r.ioParam.ioPosMode = (short) fsFromMark; - r.ioParam.ioPosOffset = 0; - - return PBWriteSync(&r); -} - -LOCALFUNC tErr CloseFile_v2(short refNum) -{ - ParamBlockRec r; - - r.ioParam.ioCompletion = NULL; - r.ioParam.ioRefNum = refNum; - - return PBCloseSync(&r); -#if 0 - return (tErr)FSClose(refNum); -#endif -} - -#define NotAfileRef (-1) - -/* - Probably should use PBHOpenDF instead - of PBHOpen when it is available. - (System 7 according to Technical Note FL515) -*/ - -LOCALFUNC tErr FileOpen_v2(Dir_R *d, StringPtr s, - char Permssn, short *refnum) -{ - tErr err; - HParamBlockRec r; - - r.ioParam.ioCompletion = NULL; - r.ioParam.ioNamePtr = s; - r.ioParam.ioVRefNum = d->VRefNum; - r.ioParam.ioPermssn = Permssn; - r.ioParam.ioMisc = 0; /* use volume buffer */ - r.ioParam.ioVersNum = 0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = PBOpenSync((ParamBlockRec *)&r); - } else -#endif - { - r.fileParam.ioDirID = d->DirId; - err = PBHOpenSync(&r); - } - - if (noErr == err) { - *refnum = r.ioParam.ioRefNum; - /* - Don't change *refnum unless file opened, - so can initialize to NotAfileRef, and - compare later before closing in uninit. - */ - } - return err; -} - -LOCALFUNC tErr FileOpenWrite_v2(Dir_R *d, StringPtr s, - short *refnum) -{ - return FileOpen_v2(d, s, (char)fsWrPerm, refnum); -} - -LOCALFUNC tErr DeleteFile_v2(Dir_R *d, StringPtr s) -{ - tErr err; - HParamBlockRec r; - - r.fileParam.ioCompletion = NULL; - r.fileParam.ioVRefNum = d->VRefNum; - r.fileParam.ioNamePtr = s; - r.fileParam.ioFVersNum = 0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = PBDeleteSync((ParamBlockRec *)&r); - } else -#endif - { - r.fileParam.ioDirID = d->DirId; - err = PBHDeleteSync(&r); - } - - return err; -} - -LOCALFUNC tErr CreateFile_v2(Dir_R *d, StringPtr s) -{ - tErr err; - HParamBlockRec r; - - r.fileParam.ioFlVersNum = 0; - /* - Think reference says to do this, - but not Inside Mac IV - */ - - r.fileParam.ioCompletion = NULL; - r.fileParam.ioNamePtr = s; - r.fileParam.ioVRefNum = d->VRefNum; - r.fileParam.ioFVersNum = 0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = PBCreateSync((ParamBlockRec *)&r); - } else -#endif - { - r.fileParam.ioDirID = d->DirId; - err = PBHCreateSync(&r); - } - - return err; -} - -LOCALFUNC tErr FileGetInfo_v2(Dir_R *d, StringPtr s, - HParamBlockRec *r) -{ - tErr err; - - r->fileParam.ioCompletion = NULL; - r->fileParam.ioNamePtr = s; - r->fileParam.ioVRefNum = d->VRefNum; - r->fileParam.ioFVersNum = (char)0; /* needed if MFS volume */ - r->fileParam.ioFDirIndex = (short)0; - -#if Support64kROM - if (Have64kROM()) { - err = PBGetFInfoSync((ParamBlockRec *)r); - } else -#endif - { - r->fileParam.ioDirID = d->DirId; - err = PBHGetFInfoSync(r); - } - - return err; -} - -LOCALFUNC tErr FileSetInfo_v2(Dir_R *d, StringPtr s, - HParamBlockRec *r) -{ - tErr err; - - r->fileParam.ioCompletion = NULL; - r->fileParam.ioNamePtr = s; - r->fileParam.ioVRefNum = d->VRefNum; - r->fileParam.ioFVersNum = (char)0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = PBSetFInfoSync((ParamBlockRec *)r); - } else -#endif - { - r->fileParam.ioDirID = d->DirId; - err = PBHSetFInfoSync(r); - } - - return err; -} - -LOCALFUNC tErr FileSetTypeCreator_v2(Dir_R *d, StringPtr s, - OSType creator, OSType fileType) -{ - tErr err; - HParamBlockRec r; - - if (noErr == (err = FileGetInfo_v2(d, s, &r))) { - r.fileParam.ioFlFndrInfo.fdType = fileType; - r.fileParam.ioFlFndrInfo.fdCreator = creator; - err = FileSetInfo_v2(d, s, &r); - } - - return err; -} - -LOCALFUNC tErr CreateFileOverWrite_v2(Dir_R *d, StringPtr s) -{ - tErr err; - - err = CreateFile_v2(d, s); - if (dupFNErr == err) { - if (noErr == (err = DeleteFile_v2(d, s))) { - err = CreateFile_v2(d, s); - } - } - - return err; -} - -LOCALFUNC tErr OpenNewFile_v3(Dir_R *d, StringPtr s, - OSType creator, OSType fileType, - short *refnum) -/* - Deletes old file if already exists. -*/ -{ - tErr err; - - err = CreateFileOverWrite_v2(d, s); - if (noErr == err) { - err = FileSetTypeCreator_v2(d, s, - creator, fileType); - if (noErr == err) { - err = FileOpenWrite_v2(d, s, refnum); - } - - if (noErr != err) { - (void) DeleteFile_v2(d, s); - /* ignore any error, since already got one */ - } - } - - return err; -} - - -LOCALVAR short dbglog_File = NotAfileRef; -LOCALVAR tErr dbglog_err = noErr; - -LOCALFUNC bool dbglog_open0(void) -{ - MacErr_t err; - Dir_R d; - - if (noErr == (err = HGetDir_v2(&d))) { - err = FileOpen_v2(&d, (StringPtr)"\pdbglog", - (char)fsWrPerm, &dbglog_File); - if (mnvm_noErr /* fnfErr */ == err) { - err = SetEOF(dbglog_File, 0); - } else { - err = OpenNewFile_v3(&d, (StringPtr)"\pdbglog", - 'MPS ', 'TEXT', &dbglog_File); - err = mnvm_noErr; - } - - } - - return (mnvm_noErr == err); -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ - if (NotAfileRef != dbglog_File) - if (noErr == dbglog_err) - { - dbglog_err = WriteBytes_v2(dbglog_File, (Ptr)s, L); - } -} - -LOCALPROC dbglog_close0(void) -{ - if (NotAfileRef != dbglog_File) { - (void) CloseFile_v2(dbglog_File); - dbglog_File = NotAfileRef; - } -} - -#endif /* dbglog_HAVE */ - - -/* --- control mode and internationalization --- */ - -#define NeedCell2MacAsciiMap 1 - -#define WantColorTransValid 1 - -#include "LANG/INTLCHAR.h" - -#include "UI/COMOSGLU.h" - -#define WantKeyboard_RemapMac 1 - -#include "UI/CONTROLM.h" - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - BlockMove((Ptr)srcPtr, (Ptr)destPtr, byteCount); -} - -/* don't want to include c libraries, so: */ -LOCALFUNC int32_t CStrLen(char *src) -{ - char *p = src; - while (*p++ != 0) { - } - return ((int32_t)p) - ((int32_t)src) - 1; -} - -#define PStrMaxLength 255 - -LOCALPROC PStrFromCStr(ps3p r, /* CONST */ char *s) -{ - unsigned short L; - - L = CStrLen(s); - if (L > PStrMaxLength) { - L = PStrMaxLength; - } - *r++ = L; - MoveBytes((anyp)s, (anyp)r, L); -} - -LOCALPROC PStrFromChar(ps3p r, char x) -{ - r[0] = 1; - r[1] = (char)x; -} - -LOCALPROC PStrFromHandle(ps3p r, Handle h, uint32_t MaxL) -{ - uint32_t L = GetHandleSize(h); - - if (L > MaxL) { - L = MaxL; - } - - *r++ = L; - BlockMove(*h, (Ptr)r, L); -} - -LOCALFUNC MacErr_t PStrToHand(ps3p s, Handle *r) -{ - return To_tMacErr(PtrToHand((Ptr)(s + 1), r, s[0])); -} - -/* --- utilities for adapting to the environment --- */ - -#ifndef MightNotHaveAppearanceMgrAvail -#define MightNotHaveAppearanceMgrAvail 1 -#endif - -#ifndef MightNotHaveWindows85Avail -#define MightNotHaveWindows85Avail MightNotHaveAppearanceMgrAvail -#endif - -#ifndef LowMemAPIAvail -#define LowMemAPIAvail 1 -#endif - -#ifndef _LMGetTime -#if LowMemAPIAvail -#define _LMGetTime LMGetTime -#else -#define _LMGetTime() (*(SInt32 *)(0x020C)) -#endif -#endif - -#ifndef _LMGetMBarHeight -#if LowMemAPIAvail -#define _LMGetMBarHeight LMGetMBarHeight -#else -#define _LMGetMBarHeight() (*(short *)(0x0BAA)) -#endif -#endif - -#ifndef _GetGrayRgn -#if /* LowMemAPIAvail */ 0 -#define _GetGrayRgn LMGetGrayRgn -#else -#define _GetGrayRgn() (*(RgnHandle *)(0x9EE)) -#endif -#endif - -#ifndef _LMGetCurApName -#if LowMemAPIAvail -#define _LMGetCurApName LMGetCurApName -#else -#define _LMGetCurApName() ((StringPtr) 0x0910) -#endif -#endif - -#define GetScreenBitsBounds(r) (*r) = qd.screenBits.bounds - -#define _GetRegionBounds(region, bounds) *(bounds) = \ - (**(region)).rgnBBox - -#define _GetPortPixMap(p) ((p)->portPixMap) - -#ifndef _WindowRef -#if NewNamesAvail -#define _WindowRef WindowRef -#else -#define _WindowRef WindowPtr -#endif -#endif - -#define _SetPortWindowPort(w) SetPort(w) - -LOCALPROC _InvalWindowRect(_WindowRef mw, Rect *r) -{ - GrafPtr SavePort; - - GetPort(&SavePort); - _SetPortWindowPort(mw); - InvalRect(r); - SetPort(SavePort); -} - -#define _GetWindowPortBounds(w, r) *(r) = ((w)->portRect) - -LOCALPROC InvalWholeWindow(_WindowRef mw) -{ - Rect bounds; - - _GetWindowPortBounds(mw, &bounds); - _InvalWindowRect(mw, &bounds); -} - -LOCALPROC SetMacWindContRect(_WindowRef mw, Rect *r) -{ -#if Windows85APIAvail - if (HaveNewWndMgrAvail()) { - (void) SetWindowBounds (mw, kWindowContentRgn, r); - } else -#endif - { -#if MightNotHaveWindows85Avail - MoveWindow(mw, r->left, r->top, false); - SizeWindow(mw, r->right - r->left, r->bottom - r->top, - true); -#endif - } - InvalWholeWindow(mw); -} - -LOCALFUNC bool GetWindowTitleBounds(_WindowRef mw, Rect *r) -{ -#if Windows85APIAvail - if (HaveNewWndMgrAvail()) { - return (noErr == GetWindowBounds(mw, - kWindowTitleBarRgn, r)); - } else -#endif - { -#if MightNotHaveWindows85Avail - _GetRegionBounds(((WindowPeek)mw)->strucRgn, r); - r->bottom = r->top + 15; - r->left += 4; - r->right -= 4; -#endif - return true; - } -} - -#define topLeft(r) (((Point *) &(r))[0]) -#define botRight(r) (((Point *) &(r))[1]) - -LOCALFUNC bool GetWindowContBounds(_WindowRef mw, Rect *r) -{ -#if Windows85APIAvail - if (HaveNewWndMgrAvail()) { - return (noErr == GetWindowBounds(mw, - kWindowContentRgn, r)); - } else -#endif - { -#if MightNotHaveWindows85Avail - GrafPtr oldPort; - GetPort(&oldPort); - _SetPortWindowPort(mw); - _GetWindowPortBounds(mw, r); - LocalToGlobal(&topLeft(*r)); - LocalToGlobal(&botRight(*r)); - SetPort(oldPort); -#endif - return true; - } -} - -LOCALPROC GetGrayRgnBounds(Rect *r) -{ - _GetRegionBounds(_GetGrayRgn(), (Rect *)r); -} - -/* --- main window data --- */ - -LOCALVAR WindowPtr gMainWindow = NULL; - -#if MayFullScreen -LOCALVAR short hOffset; -LOCALVAR short vOffset; -#endif - -#if MayFullScreen -LOCALVAR bool GrabMachine = false; -#endif - -#if 1 -LOCALVAR bool UseFullScreen = (WantInitFullScreen != 0); -#endif - -#if 1 -LOCALVAR bool UseMagnify = (WantInitMagnify != 0); -#endif - -#if 1 -LOCALPROC ScaleRect(Rect *r) -{ - r->left *= WindowScale; - r->right *= WindowScale; - r->top *= WindowScale; - r->bottom *= WindowScale; -} -#endif - -LOCALPROC SetScrnRectFromCoords(Rect *r, - int16_t top, int16_t left, int16_t bottom, int16_t right) -{ - r->left = left; - r->right = right; - r->top = top; - r->bottom = bottom; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - OffsetRect(r, - ViewHStart, - ViewVStart); - } -#endif - -#if 1 - if (UseMagnify) { - ScaleRect(r); - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - OffsetRect(r, hOffset, vOffset); - } -#endif - -} - -#if 1 -#define ScaledHeight (WindowScale * vMacScreenHeight) -#define ScaledWidth (WindowScale * vMacScreenWidth) -#endif - -#if 1 -LOCALVAR uint8_t * ScalingBuff = nullpr; -#endif - -#if 1 - -LOCALVAR uint8_t * ScalingTabl = nullpr; -#define ScalingTablsz (256 * WindowScale) - -#define ScrnMapr_DoMap UpdateScaledBWCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 0 -#define ScrnMapr_Map ScalingTabl -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - -#if 1 -LOCALPROC SetUpScalingTabl(void) -{ - uint8_t *p4; - int i; - int j; - int k; - uint8_t bitsRemaining; - uint8_t t1; - uint8_t t2; - - p4 = ScalingTabl; - for (i = 0; i < 256; ++i) { - bitsRemaining = 8; - t2 = 0; - for (j = 8; --j >= 0; ) { - t1 = (i >> j) & 1; - for (k = WindowScale; --k >= 0; ) { - t2 = (t2 << 1) | t1; - if (--bitsRemaining == 0) { - *p4++ = t2; - bitsRemaining = 8; - t2 = 0; - } - } - } - } -} -#endif - -LOCALPROC DefaultDrawScreenBuff(int16_t top, int16_t left, - int16_t bottom, int16_t right) -{ - BitMap src; - Rect SrcRect; - Rect DstRect; - - SrcRect.left = left; - SrcRect.right = right; - SrcRect.top = top; - SrcRect.bottom = bottom; - - src.rowBytes = vMacScreenMonoByteWidth; - SetRect(&src.bounds, 0, 0, vMacScreenWidth, vMacScreenHeight); -#if 1 - if (UseMagnify) { - - if (! ColorTransValid) { - SetUpScalingTabl(); - ColorTransValid = true; - } - - UpdateScaledBWCopy(top, left, bottom, right); - - ScaleRect(&SrcRect); - ScaleRect(&src.bounds); - - src.baseAddr = (Ptr)ScalingBuff; - src.rowBytes *= WindowScale; - } else -#endif - { - src.baseAddr = (Ptr)GetCurDrawBuff(); - } - SetScrnRectFromCoords(&DstRect, top, left, bottom, right); - CopyBits(&src, - &gMainWindow->portBits, - &SrcRect, &DstRect, srcCopy, NULL); - /* FrameRect(&SrcRect); for testing */ -} - -LOCALPROC Update_Screen(void) -{ - GrafPtr savePort; - - GetPort(&savePort); - _SetPortWindowPort(gMainWindow); - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - PaintRect(&gMainWindow->portRect); - } -#endif - - DefaultDrawScreenBuff(0, 0, vMacScreenHeight, vMacScreenWidth); - SetPort(savePort); -} - -LOCALPROC HaveChangedScreenBuff(int16_t top, int16_t left, - int16_t bottom, int16_t right) -{ -#if 0 /* experimental code in progress */ - if (UseFullScreen) - { - { - PixMapHandle pm= (**GetMainDevice()).gdPMap; - - /* LockPixels(pm); */ -#if 1 - if (! UseMagnify) { -#define PixelT uint32_t - PixelT *p1 = (PixelT *)GetPixBaseAddr(pm); - int i; - int j; - int k; - uint32_t *p0 = (uint32_t *)GetCurDrawBuff(); - uint32_t SkipBytes = GetPixRowBytes(pm) - - sizeof(PixelT) * vMacScreenWidth; - uint32_t t0; - PixelT a[2]; - - ((Ptr)p1) += (long)GetPixRowBytes(pm) * (top + vOffset); - p1 += hOffset; - p0 += (long)top * vMacScreenWidth / 32; - - a[0] = (PixelT) -1; - a[1] = 0; - -#if 1 - for (i = bottom - top; --i >= 0; ) { - for (j = vMacScreenWidth / 32; --j >= 0; ) { - t0 = *p0++; - - for (k = 32; --k >= 0; ) { - PixelT v = a[(t0 >> k) & 1]; - *p1++ = v; - } - } - ((Ptr)p1) += SkipBytes; - } -#endif - } else { -#define PixelT uint32_t - PixelT *p1 = (PixelT *)GetPixBaseAddr(pm); - int i; - int j; - int k; - uint32_t *p0 = (uint32_t *)GetCurDrawBuff(); - PixelT *p2; - uint32_t t0; - PixelT a[2]; - - p1 += vOffset * ScaledWidth; - p1 += (long)WindowScale * (long)ScaledWidth * top; - p0 += (long)top * vMacScreenWidth / 32; - - a[0] = (PixelT) -1; - a[1] = 0; - -#if 1 - for (i = bottom - top; --i >= 0; ) { - p2 = p1; - for (j = vMacScreenWidth / 32; --j >= 0; ) { - t0 = *p0++; - - for (k = 32; --k >= 0; ) { - PixelT v = a[(t0 >> k) & 1]; - /* ((t0 >> k) & 1) - 1 */ - *p1++ = v; - *p1++ = v; - } - } - for (j = ScaledWidth; --j >= 0; ) { - *p1++ = *p2++; - } - } -#endif - } -#endif - /* UnlockPixels(pm); */ - } - } else -#endif - { - GrafPtr savePort; - - GetPort(&savePort); - _SetPortWindowPort(gMainWindow); - DefaultDrawScreenBuff(top, left, bottom, right); - SetPort(savePort); - } -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ -#if EnableFSMouseMotion - if (HaveMouseMotion) { - AutoScrollScreen(); - } -#endif - DrawChangesAndClear(); -} - -/* --- keyboard --- */ - -LOCALVAR uint32_t LastEmKeys[4]; - -LOCALPROC ZapEmKeys(void) -{ - LastEmKeys[0] = 0; - LastEmKeys[1] = 0; - LastEmKeys[2] = 0; - LastEmKeys[3] = 0; -} - -LOCALPROC CheckKeyBoardState(void) -{ - int i; - int j; - uint32_t NewKeys[4]; - - GetKeys(*(KeyMap *)NewKeys); - - for (j = 0; j < 16; ++j) { - uint8_t k1 = ((uint8_t *)NewKeys)[j]; - uint8_t k2 = ((uint8_t *)LastEmKeys)[j]; - uint8_t k3 = k1 ^ k2; - - if (k3 != 0) { - for (i = 0; i < 8; ++i) { - if ((k3 & (1 << i)) != 0) { - Keyboard_UpdateKeyMap2(Keyboard_RemapMac(j * 8 + i), - (k1 & (1 << i)) != 0); - } - } - } - } - for (i = 0; i < 4; ++i) { - LastEmKeys[i] = NewKeys[i]; - } -} - -LOCALVAR WantCmdOptOnReconnect = false; - -#define KeyMap_TestBit(m, key) \ - ((((uint8_t *)m)[(key) / 8] & (1 << ((key) & 7))) != 0) - -LOCALPROC ReconnectKeyCodes3(void) -/* so keys already pressed will be ignored */ -{ - int i; - int j; - bool oldv; - bool newv; - uint32_t NewKeys[4]; - - GetKeys(*(KeyMap *)NewKeys); - - /* except check CapsLock */ - oldv = KeyMap_TestBit(LastEmKeys, MKC_CapsLock); - newv = KeyMap_TestBit(NewKeys, MKC_CapsLock); - if (oldv != newv) { - Keyboard_UpdateKeyMap2(MKC_formac_CapsLock, newv); - } - - /* and except for command/option on receive drop */ - if (WantCmdOptOnReconnect) { - WantCmdOptOnReconnect = false; - - for (i = 0; i < 16; ++i) { - uint8_t v = ((uint8_t *)NewKeys)[i]; - for (j = 0; j < 8; ++j) { - if (0 != ((1 << j) & v)) { - uint8_t k = i * 8 + j; - if (MKC_CapsLock != k) { - Keyboard_UpdateKeyMap2(Keyboard_RemapMac(k), - true); - } - } - } - } - } - - for (i = 0; i < 4; ++i) { - LastEmKeys[i] = NewKeys[i]; - } -} - -/* --- cursor hiding --- */ - -LOCALVAR bool HaveCursorHidden = false; -LOCALVAR bool WantCursorHidden = false; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - ShowCursor(); - } -} - -LOCALPROC SetCursorArrow(void) -{ - SetCursor(&qd.arrow); -} - -/* --- cursor moving --- */ - -/* - When "EnableFSMouseMotion" the platform - specific code can get relative mouse - motion, instead of absolute coordinates - on the emulated screen. It should - set HaveMouseMotion to true when - it is doing this (normally when in - full screen mode.) - - This can usually be implemented by - hiding the platform specific cursor, - and then keeping it within a box, - moving the cursor back to the center whenever - it leaves the box. This requires the - ability to move the cursor (in MoveMouse). -*/ - -/* - mouse moving code (non OS X) adapted from - MoveMouse.c by Dan Sears, which says that - "Based on code from Jon Wtte, Denis Pelli, - Apple, and a timely suggestion from Bo Lindbergh." - Also says 'For documentation of the CDM, see Apple - Tech Note "HW 01 - ADB (The Untold Story: Space Aliens - ate my mouse)"' -*/ - -#ifndef TARGET_CPU_PPC -#error "TARGET_CPU_PPC undefined" -#endif - -#if TARGET_CPU_PPC -enum { - glueUppCursorDeviceMoveToProcInfo = - kD0DispatchedPascalStackBased | - DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kTwoByteCode) | - RESULT_SIZE(SIZE_CODE(sizeof(OSErr))) | - DISPATCHED_STACK_ROUTINE_PARAMETER(1, - SIZE_CODE(sizeof(CursorDevicePtr))) | - DISPATCHED_STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(long))) | - DISPATCHED_STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(long))), - glueUppCursorDeviceNextDeviceProcInfo = - kD0DispatchedPascalStackBased | - DISPATCHED_STACK_ROUTINE_SELECTOR_SIZE(kTwoByteCode) | - RESULT_SIZE(SIZE_CODE(sizeof(OSErr))) | - DISPATCHED_STACK_ROUTINE_PARAMETER(1, - SIZE_CODE(sizeof(CursorDevicePtr *))) -}; -#endif - -#if TARGET_CPU_PPC -LOCALFUNC OSErr -CallCursorDeviceMoveTo( - CursorDevicePtr ourDevice, - long absX, - long absY) -{ - return CallUniversalProc( - GetToolboxTrapAddress(_CursorDeviceDispatch), - glueUppCursorDeviceMoveToProcInfo, - 1, ourDevice, absX, absY); -} -#else -#define CallCursorDeviceMoveTo CursorDeviceMoveTo -#endif - -#if TARGET_CPU_PPC -LOCALFUNC OSErr -CallCursorDeviceNextDevice( - CursorDevicePtr *ourDevice) -{ - return CallUniversalProc( - GetToolboxTrapAddress(_CursorDeviceDispatch), - glueUppCursorDeviceNextDeviceProcInfo, - 0xB, ourDevice); -} -#else -#define CallCursorDeviceNextDevice CursorDeviceNextDevice -#endif - -#if ! TARGET_CPU_PPC -pascal void CallCursorTask(void) = -{ - 0x2078, 0x08EE, /* MOVE.L jCrsrTask,A0 */ - 0x4E90 /* JSR (A0) */ -}; -#endif - -/* - Low memory globals for the mouse -*/ - -#define RawMouse 0x082C - /* low memory global that has current mouse loc */ -#define MTemp 0x0828 - /* low memory global that has current mouse loc */ -#define CrsrNew 0x08CE - /* set after you change mtemp and rawmouse */ -#define CrsrCouple 0x08CF - /* true if the cursor is tied to the mouse */ - -LOCALFUNC bool MoveMouse(int16_t h, int16_t v) -{ - /* - Move the cursor to the point h, v - on the emulated screen. - if detect that this fails return false, - otherwise return true. - (on some platforms it is possible to - move the curser, but there is no - way to detect failure.) - */ - GrafPtr oldPort; - Point CurMousePos; - Point NewMousePos; - uint32_t difftime; - bool IsOk; - long int StartTime = TickCount(); - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h -= ViewHStart; - v -= ViewVStart; - } -#endif - -#if 1 - if (UseMagnify) { - h *= WindowScale; - v *= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h += hOffset; - v += vOffset; - } -#endif - - CurMousePos.h = h; - CurMousePos.v = v; - - GetPort(&oldPort); - _SetPortWindowPort(gMainWindow); - LocalToGlobal(&CurMousePos); - - do { - -#if HaveCPUfamM68K - if (! HiToolTrapAvailable(_CursorDeviceDispatch)) { - *(Point *)RawMouse = CurMousePos; - *(Point *)MTemp = CurMousePos; - *(Ptr)CrsrNew = *(Ptr)CrsrCouple; -#if ! TARGET_CPU_PPC - CallCursorTask(); -#endif - } else -#endif - { - CursorDevice *firstMouse = NULL; - CallCursorDeviceNextDevice(&firstMouse); - if (firstMouse != NULL) { - CallCursorDeviceMoveTo(firstMouse, - (long) CurMousePos.h, - (long) CurMousePos.v); - } - } - - GetMouse(&NewMousePos); - IsOk = (h == NewMousePos.h) && (v == NewMousePos.v); - difftime = (uint32_t)(TickCount() - StartTime); - } while ((! IsOk) && (difftime < 5)); - - SetPort(oldPort); - return IsOk; -} - -#if EnableFSMouseMotion -LOCALPROC AdjustMouseMotionGrab(void) -{ - if (gMainWindow != NULL) { -#if MayFullScreen - if (GrabMachine) { - /* - if magnification changes, need to reset, - even if HaveMouseMotion already true - */ - if (MoveMouse(ViewHStart + (ViewHSize / 2), - ViewVStart + (ViewVSize / 2))) - { - SavedMouseH = ViewHStart + (ViewHSize / 2); - SavedMouseV = ViewVStart + (ViewVSize / 2); - HaveMouseMotion = true; - } - } else -#endif - { - if (HaveMouseMotion) { - (void) MoveMouse(CurMouseH, CurMouseV); - HaveMouseMotion = false; - } - } - } -} -#endif - -#if EnableFSMouseMotion -LOCALPROC MouseConstrain(void) -{ - int16_t shiftdh; - int16_t shiftdv; - - if (SavedMouseH < ViewHStart + (ViewHSize / 4)) { - shiftdh = ViewHSize / 2; - } else if (SavedMouseH > ViewHStart + ViewHSize - (ViewHSize / 4)) { - shiftdh = - ViewHSize / 2; - } else { - shiftdh = 0; - } - if (SavedMouseV < ViewVStart + (ViewVSize / 4)) { - shiftdv = ViewVSize / 2; - } else if (SavedMouseV > ViewVStart + ViewVSize - (ViewVSize / 4)) { - shiftdv = - ViewVSize / 2; - } else { - shiftdv = 0; - } - if ((shiftdh != 0) || (shiftdv != 0)) { - SavedMouseH += shiftdh; - SavedMouseV += shiftdv; - if (! MoveMouse(SavedMouseH, SavedMouseV)) { - HaveMouseMotion = false; - } - } -} -#endif - -LOCALPROC MousePositionNotify(Point NewMousePos) -{ - bool ShouldHaveCursorHidden = true; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePos.h -= hOffset; - NewMousePos.v -= vOffset; - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - if (! PtInRgn(NewMousePos, gMainWindow->visRgn)) { - ShouldHaveCursorHidden = false; - } - } -#endif - -#if 1 - if (UseMagnify) { - NewMousePos.h /= WindowScale; - NewMousePos.v /= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePos.h += ViewHStart; - NewMousePos.v += ViewVStart; - } -#endif - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MousePositionSetDelta( - NewMousePos.h - SavedMouseH, NewMousePos.v - SavedMouseV); - SavedMouseH = NewMousePos.h; - SavedMouseV = NewMousePos.v; - } else -#endif - { - if (NewMousePos.h < 0) { - NewMousePos.h = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePos.h >= vMacScreenWidth) { - NewMousePos.h = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePos.v < 0) { - NewMousePos.v = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePos.v >= vMacScreenHeight) { - NewMousePos.v = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ShouldHaveCursorHidden = true; - } -#endif - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePos.h, NewMousePos.v); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC MousePositionNotifyFromGlobal(Point NewMousePos) -{ - GrafPtr oldPort; - - GetPort(&oldPort); - _SetPortWindowPort(gMainWindow); - GlobalToLocal(&NewMousePos); - SetPort(oldPort); - - MousePositionNotify(NewMousePos); -} - -LOCALPROC CheckMouseState(void) -{ - Point NewMousePos; - GrafPtr oldPort; - - GetPort(&oldPort); - _SetPortWindowPort(gMainWindow); - GetMouse(&NewMousePos); - SetPort(oldPort); - - MousePositionNotify(NewMousePos); -} - -LOCALPROC DisconnectKeyCodes3(void) -{ - DisconnectKeyCodes2(); - - MouseButtonSet(false); - - ForceShowCursor(); -} - - -/* --- time, date, location --- */ - -#define dbglog_TimeStuff (0 && dbglog_HAVE) - -/* - be sure to avoid getting confused if TickCount - overflows and wraps. -*/ - -LOCALVAR uint32_t TrueEmulatedTime = 0; - /* - The amount of time the program has - been running, measured in Macintosh - "ticks". There are 60.14742 ticks per - second. - - (time when the emulation is - stopped for more than a few ticks - should not be counted.) - */ - -LOCALVAR long int LastTime; - -LOCALPROC StartUpTimeAdjust(void) -{ - /* - prepare to call UpdateTrueEmulatedTime. - - will be called again when haven't been - regularly calling UpdateTrueEmulatedTime, - (such as the emulation has been stopped). - */ - LastTime = TickCount(); -} - -LOCALPROC UpdateTrueEmulatedTime(void) -{ - /* - Update TrueEmulatedTime. usually - need to convert between how the - host operating system measures - time and Macintosh ticks. But - not for this port. - */ - long int LatestTime = TickCount(); - int32_t TimeDiff = LatestTime - LastTime; - - if (TimeDiff != 0) { - LastTime = LatestTime; - - if (TimeDiff >= 0) { - if (TimeDiff > 16) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("emulation interrupted", - TrueEmulatedTime); -#endif - } else { - TrueEmulatedTime += TimeDiff; - } - } - } -} - -LOCALFUNC bool CheckDateTime(void) -{ - /* - Update CurMacDateInSeconds, the number - of seconds since midnight January 1, 1904. - - return true if CurMacDateInSeconds is - different than it was on the last - call to CheckDateTime. - */ - uint32_t NewMacDateInSecond; - - NewMacDateInSecond = _LMGetTime(); - if (CurMacDateInSeconds != NewMacDateInSecond) { - CurMacDateInSeconds = NewMacDateInSecond; - return true; - } else { - return false; - } -} - -LOCALFUNC bool InitLocationDat(void) -{ -#if AutoLocation || AutoTimeZone - MachineLocation loc; - - ReadLocation(&loc); -#if AutoLocation - CurMacLatitude = (uint32_t)loc.latitude; - CurMacLongitude = (uint32_t)loc.longitude; -#endif -#if AutoTimeZone - CurMacDelta = (uint32_t)loc.u.gmtDelta; -#endif -#endif - - (void) CheckDateTime(); - - return true; -} - -/* --- sound --- */ - -#if SoundEnabled - -#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */ -#define kSoundBuffers (1 << kLn2SoundBuffers) -#define kSoundBuffMask (kSoundBuffers - 1) - -#define DesiredMinFilledSoundBuffs 3 - /* - if too big then sound lags behind emulation. - if too small then sound will have pauses. - */ - -#define kLnOneBuffLen 9 -#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen) -#define kOneBuffLen (1UL << kLnOneBuffLen) -#define kAllBuffLen (1UL << kLnAllBuffLen) -#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3) -#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3) -#define kOneBuffSz (1UL << kLnOneBuffSz) -#define kAllBuffSz (1UL << kLnAllBuffSz) -#define kOneBuffMask (kOneBuffLen - 1) -#define kAllBuffMask (kAllBuffLen - 1) -#define dbhBufferSize (kAllBuffSz + kOneBuffSz) - -#define dbglog_SoundStuff (0 && dbglog_HAVE) -#define dbglog_SoundBuffStats (0 && dbglog_HAVE) - -LOCALVAR tpSoundSamp TheSoundBuffer = nullpr; -volatile static uint16_t ThePlayOffset; -volatile static uint16_t TheFillOffset; -volatile static uint16_t MinFilledSoundBuffs; -#if dbglog_SoundBuffStats -LOCALVAR uint16_t MaxFilledSoundBuffs; -#endif -LOCALVAR uint16_t TheWriteOffset; - -LOCALPROC Sound_Start0(void) -{ - /* Reset variables */ - ThePlayOffset = 0; - TheFillOffset = 0; - TheWriteOffset = 0; - MinFilledSoundBuffs = kSoundBuffers + 1; -#if dbglog_SoundBuffStats - MaxFilledSoundBuffs = 0; -#endif -} - -GLOBALOSGLUFUNC tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL) -{ - uint16_t ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset); - uint16_t WriteBuffContig = - kOneBuffLen - (TheWriteOffset & kOneBuffMask); - - if (WriteBuffContig < n) { - n = WriteBuffContig; - } - if (ToFillLen < n) { - /* overwrite previous buffer */ -#if dbglog_SoundStuff - dbglog_writeln("sound buffer over flow"); -#endif - TheWriteOffset -= kOneBuffLen; - } - - *actL = n; - return TheSoundBuffer + (TheWriteOffset & kAllBuffMask); -} - -#if 4 == kLn2SoundSampSz -LOCALPROC ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -LOCALPROC Sound_WroteABlock(void) -{ -#if (4 == kLn2SoundSampSz) - uint16_t PrevWriteOffset = TheWriteOffset - kOneBuffLen; - tpSoundSamp p = TheSoundBuffer + (PrevWriteOffset & kAllBuffMask); -#endif - -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_WroteABlock"); -#endif - - ConvertSoundBlockToNative(p); - - TheFillOffset = TheWriteOffset; - -#if dbglog_SoundBuffStats - { - uint16_t ToPlayLen = TheFillOffset - - ThePlayOffset; - uint16_t ToPlayBuffs = ToPlayLen >> kLnOneBuffLen; - - if (ToPlayBuffs > MaxFilledSoundBuffs) { - MaxFilledSoundBuffs = ToPlayBuffs; - } - } -#endif -} - -LOCALFUNC bool Sound_EndWrite0(uint16_t actL) -{ - bool v; - - TheWriteOffset += actL; - - if (0 != (TheWriteOffset & kOneBuffMask)) { - v = false; - } else { - /* just finished a block */ - - Sound_WroteABlock(); - - v = true; - } - - return v; -} - -LOCALPROC Sound_SecondNotify0(void) -{ - if (MinFilledSoundBuffs <= kSoundBuffers) { - if (MinFilledSoundBuffs > DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too high"); -#endif - ++LastTime; - } else if (MinFilledSoundBuffs < DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too low"); -#endif - ++TrueEmulatedTime; - } -#if dbglog_SoundBuffStats - dbglog_writelnNum("MinFilledSoundBuffs", - MinFilledSoundBuffs); - dbglog_writelnNum("MaxFilledSoundBuffs", - MaxFilledSoundBuffs); - MaxFilledSoundBuffs = 0; -#endif - MinFilledSoundBuffs = kSoundBuffers + 1; - } -} - -LOCALPROC RampSound(tpSoundSamp p, - trSoundSamp BeginVal, trSoundSamp EndVal) -{ - int i; - uint32_t v = (((uint32_t)BeginVal) << kLnOneBuffLen) + (kLnOneBuffLen >> 1); - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ = v >> kLnOneBuffLen; - v = v + EndVal - BeginVal; - } -} - -#if 4 == kLn2SoundSampSz -#define ConvertSoundSampleFromNative(v) ((v) + 0x8000) -#else -#define ConvertSoundSampleFromNative(v) (v) -#endif - -struct SoundR { - tpSoundSamp fTheSoundBuffer; - volatile uint16_t (*fPlayOffset); - volatile uint16_t (*fFillOffset); - volatile uint16_t (*fMinFilledSoundBuffs); - - volatile bool PlayingBuffBlock; - volatile trSoundSamp lastv; - volatile bool wantplaying; - volatile bool StartingBlocks; - - CmpSoundHeader /* ExtSoundHeader */ soundHeader; -}; -typedef struct SoundR SoundR; - - -/* - Some of this code descended from CarbonSndPlayDB, an - example from Apple, as found being used in vMac for Mac OS. -*/ - -LOCALPROC InsertSndDoCommand(SndChannelPtr chan, SndCommand * newCmd) -{ - if (-1 == chan->qHead) { - chan->qHead = chan->qTail; - } - - if (1 <= chan->qHead) { - chan->qHead--; - } else { - chan->qHead = chan->qTail; - } - - chan->queue[chan->qHead] = *newCmd; -} - -/* call back */ static pascal void -Sound_CallBack(SndChannelPtr theChannel, SndCommand * theCallBackCmd) -{ - SoundR *datp = - (SoundR *)(theCallBackCmd->param2); - bool wantplaying0 = datp->wantplaying; - trSoundSamp v0 = datp->lastv; - -#if dbglog_SoundStuff - dbglog_writeln("Enter Sound_CallBack"); -#endif - - if (datp->PlayingBuffBlock) { - /* finish with last sample */ -#if dbglog_SoundStuff - dbglog_writeln("done with sample"); -#endif - - *datp->fPlayOffset += kOneBuffLen; - datp->PlayingBuffBlock = false; - } - - if ((! wantplaying0) && (kCenterSound == v0)) { -#if dbglog_SoundStuff - dbglog_writeln("terminating"); -#endif - } else { - SndCommand playCmd; - tpSoundSamp p; - trSoundSamp v1 = v0; - bool WantRamp = false; - uint16_t CurPlayOffset = *datp->fPlayOffset; - uint16_t ToPlayLen = *datp->fFillOffset - CurPlayOffset; - uint16_t FilledSoundBuffs = ToPlayLen >> kLnOneBuffLen; - - if (FilledSoundBuffs < *datp->fMinFilledSoundBuffs) { - *datp->fMinFilledSoundBuffs = FilledSoundBuffs; - } - - if (! wantplaying0) { -#if dbglog_SoundStuff - dbglog_writeln("playing end transistion"); -#endif - v1 = kCenterSound; - - WantRamp = true; - } else - if (datp->StartingBlocks) { -#if dbglog_SoundStuff - dbglog_writeln("playing start block"); -#endif - - if ((ToPlayLen >> kLnOneBuffLen) < 12) { - datp->StartingBlocks = false; -#if dbglog_SoundStuff - dbglog_writeln("have enough samples to start"); -#endif - - p = datp->fTheSoundBuffer - + (CurPlayOffset & kAllBuffMask); - v1 = ConvertSoundSampleFromNative(*p); - } - - WantRamp = true; - } else - if (0 == FilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("playing under run"); -#endif - - WantRamp = true; - } else - { - /* play next sample */ - p = datp->fTheSoundBuffer - + (CurPlayOffset & kAllBuffMask); - datp->PlayingBuffBlock = true; - v1 = - ConvertSoundSampleFromNative(*(p + kOneBuffLen - 1)); -#if dbglog_SoundStuff - dbglog_writeln("playing sample"); -#endif - } - - if (WantRamp) { - p = datp->fTheSoundBuffer + kAllBuffLen; - -#if dbglog_SoundStuff - dbglog_writelnNum("v0", v0); - dbglog_writelnNum("v1", v1); -#endif - - RampSound(p, v0, v1); - ConvertSoundBlockToNative(p); - } - - datp->soundHeader.samplePtr = (Ptr)p; - datp->soundHeader.numFrames = - (unsigned long)kOneBuffLen; - - /* Insert our callback command */ - InsertSndDoCommand (theChannel, theCallBackCmd); - -#if 0 - { - int i; - tpSoundSamp pS = - (tpSoundSamp)datp->soundHeader.samplePtr; - - for (i = datp->soundHeader.numFrames; --i >= 0; ) - { - fprintf(stderr, "%d\n", *pS++); - } - } -#endif - - /* Play the next buffer */ - playCmd.cmd = bufferCmd; - playCmd.param1 = 0; - playCmd.param2 = (long)&(datp->soundHeader); - InsertSndDoCommand (theChannel, &playCmd); - - datp->lastv = v1; - } -} - -LOCALVAR SoundR cur_audio; - -LOCALVAR SndCallBackUPP gCarbonSndPlayDoubleBufferCallBackUPP = NULL; - -LOCALVAR SndChannelPtr sndChannel = NULL; /* our sound channel */ - -LOCALPROC Sound_Start(void) -{ - if (NULL == sndChannel) -#if HaveCPUfamM68K - if (HaveSndMngrAvail()) -#endif - { - SndCommand callBack; - SndChannelPtr chan = NULL; - - cur_audio.wantplaying = false; - cur_audio.StartingBlocks = false; - - Sound_Start0(); - - SndNewChannel(&chan, sampledSynth, initMono, nil); - if (NULL != chan) { - sndChannel = chan; - - cur_audio.PlayingBuffBlock = false; - cur_audio.lastv = kCenterSound; - cur_audio.StartingBlocks = true; - cur_audio.wantplaying = true; - - callBack.cmd = callBackCmd; - callBack.param1 = 0; /* unused */ - callBack.param2 = (long)&cur_audio; - - sndChannel->callBack = - gCarbonSndPlayDoubleBufferCallBackUPP; - - (void) SndDoCommand (sndChannel, &callBack, true); - } - } -} - -#define IgnorableEventMask \ - (mUpMask | keyDownMask | keyUpMask | autoKeyMask) - -LOCALPROC Sound_Stop(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Stop"); -#endif - - if (NULL != sndChannel) { - uint16_t retry_limit = 50; /* half of a second */ - SCStatus r; - - cur_audio.wantplaying = false; -#if dbglog_SoundStuff - dbglog_writeln("cleared wantplaying"); -#endif - -label_retry: - r.scChannelBusy = false; /* what is this for? */ - if (noErr != SndChannelStatus(sndChannel, - sizeof(SCStatus), &r)) - { - /* fail */ - } else - if ((! r.scChannelBusy) && (kCenterSound == cur_audio.lastv)) { - /* done */ - - /* - observed reporting not busy unexpectedly, - so also check lastv. - */ - } else - if (0 == --retry_limit) { -#if dbglog_SoundStuff - dbglog_writeln("retry limit reached"); -#endif - /* - don't trust SndChannelStatus, make - sure don't get in infinite loop. - */ - - /* done */ - } else - { - /* - give time back, particularly important - if got here on a suspend event. - */ - EventRecord theEvent; - -#if dbglog_SoundStuff - dbglog_writeln("busy, so sleep"); -#endif - -#if HaveCPUfamM68K - if (! HaveWaitNextEventAvail()) { - (void) GetNextEvent(IgnorableEventMask, &theEvent); - } else -#endif - { - (void) WaitNextEvent(IgnorableEventMask, - &theEvent, 1, NULL); - } - goto label_retry; - } - - SndDisposeChannel(sndChannel, true); - sndChannel = NULL; - } - -#if dbglog_SoundStuff - dbglog_writeln("leave Sound_Stop"); -#endif -} - -#define SOUND_SAMPLERATE rate22khz - /* = 0x56EE8BA3 = (7833600 * 2 / 704) << 16 */ - -LOCALFUNC bool Sound_Init(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Init"); -#endif - - cur_audio.fTheSoundBuffer = TheSoundBuffer; - - cur_audio.fPlayOffset = &ThePlayOffset; - cur_audio.fFillOffset = &TheFillOffset; - cur_audio.fMinFilledSoundBuffs = &MinFilledSoundBuffs; - cur_audio.wantplaying = false; - - /* Init basic per channel information */ - cur_audio.soundHeader.sampleRate = SOUND_SAMPLERATE; - /* sample rate */ - cur_audio.soundHeader.numChannels = 1; /* one channel */ - cur_audio.soundHeader.loopStart = 0; - cur_audio.soundHeader.loopEnd = 0; - cur_audio.soundHeader.encode = cmpSH /* extSH */; - cur_audio.soundHeader.baseFrequency = kMiddleC; - cur_audio.soundHeader.numFrames = - (unsigned long)kOneBuffLen; - /* cur_audio.soundHeader.AIFFSampleRate = 0; */ - /* unused */ - cur_audio.soundHeader.markerChunk = nil; - cur_audio.soundHeader.futureUse2 = 0; - cur_audio.soundHeader.stateVars = nil; - cur_audio.soundHeader.leftOverSamples = nil; - cur_audio.soundHeader.compressionID = 0; - /* no compression */ - cur_audio.soundHeader.packetSize = 0; - /* no compression */ - cur_audio.soundHeader.snthID = 0; - cur_audio.soundHeader.sampleSize = (1 << kLn2SoundSampSz); - /* 8 or 16 bits per sample */ - cur_audio.soundHeader.sampleArea[0] = 0; -#if 3 == kLn2SoundSampSz - cur_audio.soundHeader.format = kSoundNotCompressed; -#elif 4 == kLn2SoundSampSz - cur_audio.soundHeader.format = k16BitNativeEndianFormat; -#else -#error "unsupported kLn2SoundSampSz" -#endif - cur_audio.soundHeader.samplePtr = (Ptr)TheSoundBuffer; - - gCarbonSndPlayDoubleBufferCallBackUPP = - NewSndCallBackUPP(Sound_CallBack); - if (gCarbonSndPlayDoubleBufferCallBackUPP != NULL) { - - Sound_Start(); - /* - This should be taken care of by LeaveSpeedStopped, - but since takes a while to get going properly, - start early. - */ - - return true; - } - return false; -} - -GLOBALOSGLUPROC Sound_EndWrite(uint16_t actL) -{ - if (Sound_EndWrite0(actL)) { - } -} - -LOCALPROC Sound_SecondNotify(void) -{ - if (sndChannel != NULL) { - Sound_SecondNotify0(); - } -} - -#endif - -#if MayFullScreen -LOCALPROC AdjustMachineGrab(void) -{ -#if EnableFSMouseMotion - AdjustMouseMotionGrab(); -#endif -#if 0 - AdjustMainScreenGrab(); -#endif -} -#endif - -#if MayFullScreen -LOCALPROC UngrabMachine(void) -{ - GrabMachine = false; - AdjustMachineGrab(); -} -#endif - -/* --- basic dialogs --- */ - -LOCALPROC NativeStrFromCStr(ps3p r, char *s, bool AddEllipsis) -{ - int i; - int L; - uint8_t ps[ClStrMaxLength]; - - ClStrFromSubstCStr(&L, ps, s); - if (AddEllipsis) { - ClStrAppendChar(&L, ps, kCellEllipsis); - } - - if (L > 255) { - L = 255; - } - - for (i = 0; i < L; ++i) { - r[i + 1] = Cell2MacAsciiMap[ps[i]]; - } - - r[0] = L; -} - -#ifndef HogCPU -#define HogCPU 1 -#endif - -#if HogCPU -LOCALVAR long NoEventsCounter = 0; -#endif - -LOCALVAR bool gBackgroundFlag = false; -LOCALVAR bool gTrueBackgroundFlag = false; -LOCALVAR bool CurSpeedStopped = true; - -LOCALVAR bool ADialogIsUp = false; - -LOCALPROC BeginDialog(void) -{ - DisconnectKeyCodes3(); - ADialogIsUp = true; -#if MayFullScreen - UngrabMachine(); -#endif -} - -LOCALPROC EndDialog(void) -{ -#if HogCPU - NoEventsCounter = 0; -#endif - ADialogIsUp = false; - ReconnectKeyCodes3(); -} - - -#define kStandardAlert 128 - -LOCALPROC CheckSavedMacMsg(void) -{ - /* - This is currently only used in the - rare case where there is a message - still pending as the program quits. - */ - Str255 briefMsgp; - Str255 longMsgp; - - if (nullpr != SavedBriefMsg) { - NativeStrFromCStr(briefMsgp, SavedBriefMsg, false); - NativeStrFromCStr(longMsgp, SavedLongMsg, false); -#if AppearanceAvail - if (HaveAppearanceAvail()) { - AlertStdAlertParamRec param; - short itemHit; - - param.movable = 0; - param.filterProc = nil; - param.defaultText = "\pOK"; - param.cancelText = nil; - param.otherText = nil; - param.helpButton = false; - param.defaultButton = kAlertStdAlertOKButton; - param.cancelButton = 0; - param.position = kWindowDefaultPosition; - - StandardAlert( - (SavedFatalMsg) ? kAlertStopAlert : kAlertCautionAlert, - briefMsgp, longMsgp, ¶m, &itemHit); - } else -#endif - { - ParamText(briefMsgp, longMsgp, "\p", "\p"); - if (SavedFatalMsg) { - while (StopAlert(kStandardAlert, NULL) != 1) { - } - } else { - while (CautionAlert(kStandardAlert, NULL) != 1) { - } - } - /* Alert (kStandardAlert, 0L); */ - } - - SavedBriefMsg = nullpr; - } -} - -/* --- hide/show menubar --- */ - -#if MayFullScreen -#if MightNotHaveWindows85Avail -LOCALVAR RgnHandle GrayRgnSave = NULL; -LOCALVAR short mBarHeightSave; -#endif -#endif - -#if MayFullScreen -LOCALPROC _HideMenuBar(void) -{ -#if Windows85APIAvail - if (HaveHideShowMenuAvail()) { - if (IsMenuBarVisible()) { - HideMenuBar(); - } - } else -#endif - { -#if MightNotHaveWindows85Avail - if (NULL == GrayRgnSave) { - RgnHandle mBarRgn = NewRgn(); - if (mBarRgn != NULL) { - GrayRgnSave = NewRgn(); - if (GrayRgnSave != NULL) { - CopyRgn(_GetGrayRgn(), GrayRgnSave); - RectRgn(mBarRgn, &qd.screenBits.bounds); - DiffRgn(mBarRgn, _GetGrayRgn(), mBarRgn); - /* - menu bar rgn, plus corner areas - of main screen - */ - mBarHeightSave = _LMGetMBarHeight(); - LMSetMBarHeight(0); - UnionRgn(_GetGrayRgn(), mBarRgn, _GetGrayRgn()); - PaintBehind(LMGetWindowList(), mBarRgn); - CalcVisBehind(LMGetWindowList(), mBarRgn); -#if 0 - controlStripHidden = false; - if (noErr == Gestalt( - gestaltControlStripVersion, &result)) - { - if (SBIsControlStripVisible()) { - controlStripHidden = true; - SBShowHideControlStrip(false); - } - } -#endif - } - DisposeRgn(mBarRgn); - } - } -#endif - } -} -#endif - -#if MayFullScreen -LOCALPROC _ShowMenuBar(void) -{ -#if Windows85APIAvail - if (HaveHideShowMenuAvail()) { - if (! IsMenuBarVisible()) { - ShowMenuBar(); - } - } else -#endif - { -#if MightNotHaveWindows85Avail - if (GrayRgnSave != NULL) { - LMSetMBarHeight(mBarHeightSave); - CopyRgn(GrayRgnSave, _GetGrayRgn()); - /* - PaintBehind(LMGetWindowList(), GrayRgnSave); - CalcVisBehind(LMGetWindowList(), GrayRgnSave); - */ - DisposeRgn(GrayRgnSave); - DrawMenuBar(); - GrayRgnSave = NULL; -#if 0 - if (controlStripHidden) { - controlStripHidden = false; - if (noErr == - Gestalt(gestaltControlStripVersion, &result)) - { - SBShowHideControlStrip(true); - } - } -#endif - } -#endif - } -} -#endif - -#if IncludePbufs -LOCALVAR Handle PbufDat[NumPbufs]; -#endif - -#if IncludePbufs -LOCALFUNC MacErr_t PbufNewFromHandle(Handle h, uint32_t count, tPbuf *r) -{ - tPbuf i; - MacErr_t err; - - if (! FirstFreePbuf(&i)) { - DisposeHandle(h); - err = mnvm_miscErr; - } else { - *r = i; - PbufDat[i] = h; - PbufNewNotify(i, count); - err = mnvm_noErr; - } - - return err; -} -#endif - -#if IncludePbufs -GLOBALOSGLUFUNC MacErr_t PbufNew(uint32_t count, tPbuf *r) -{ - Handle h; - MacErr_t err = mnvm_miscErr; - - h = NewHandleClear(count); - if (h != NULL) { - err = PbufNewFromHandle(h, count, r); - } - - return err; -} -#endif - -#if IncludePbufs -GLOBALOSGLUPROC PbufDispose(tPbuf i) -{ - DisposeHandle(PbufDat[i]); - PbufDisposeNotify(i); -} -#endif - -#if IncludePbufs -LOCALPROC UnInitPbufs(void) -{ - tPbuf i; - - for (i = 0; i < NumPbufs; ++i) { - if (PbufIsAllocated(i)) { - PbufDispose(i); - } - } -} -#endif - -#if IncludePbufs -#define PbufHaveLock 1 -#endif - -#if IncludePbufs -LOCALFUNC uint8_t * PbufLock(tPbuf i) -{ - uint8_t * p; - - Handle h = PbufDat[i]; - - if (NULL == h) { - p = nullpr; - } else { - HLock(h); - p = (uint8_t *)*h; - } - - return p; -} -#endif - -#if IncludePbufs -LOCALPROC PbufUnlock(tPbuf i) -{ - HUnlock(PbufDat[i]); -} -#endif - -#if IncludePbufs -GLOBALOSGLUPROC PbufTransfer(uint8_t * Buffer, - tPbuf i, uint32_t offset, uint32_t count, bool IsWrite) -{ - Handle h = PbufDat[i]; - - HLock(h); - { - void *p = ((uint8_t *)*h) + offset; - if (IsWrite) { - BlockMove(Buffer, p, count); - } else { - BlockMove(p, Buffer, count); - } - } - HUnlock(h); -} -#endif - -/* --- clipboard --- */ - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEexport(tPbuf i) -{ - /* - PBuf i is an array of macintosh - style characters. (using the - MacRoman character set.) - - Should export this Buffer to the - native clipboard, performing character - set translation, and eof character translation - as needed. (Not needed for this port.) - - return 0 if it succeeds, nonzero (a - Macintosh style error code, but -1 - will do) on failure. - */ - OSErr err; - - err = ZeroScrap(); - if (noErr == err) { - uint32_t L = PbufSize[i]; - Handle h = PbufDat[i]; - HLock(h); - err = PutScrap(L, 'TEXT', *h); - HUnlock(h); - } - - PbufDispose(i); - - return (MacErr_t)err; -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEimport(tPbuf *r) -{ - /* - Import the native clipboard as text, - and convert it to Macintosh format, - in a Pbuf. - - return 0 if it succeeds, nonzero (a - Macintosh style error code, but -1 - will do) on failure. - */ - - long off; - long v; - Handle h; - OSErr err = (OSErr)mnvm_miscErr; - - h = NewHandle(0); - if (h != NULL) { - v = GetScrap(h, 'TEXT', &off); - if (v < 0) { - err = v; - } else { - err = (OSErr)PbufNewFromHandle(h, v, r); - h = NULL; - } - if (NULL != h) { - DisposeHandle(h); - } - } - - return (MacErr_t)err; -} -#endif - -/* --- drives --- */ - -LOCALVAR short Drives[NumDrives]; /* open disk image files */ -#if (IncludeSonyGetName || IncludeSonyNew) && HaveCPUfamM68K -LOCALVAR Handle DriveNames[NumDrives]; -#endif - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; -#if (IncludeSonyGetName || IncludeSonyNew) && HaveCPUfamM68K - DriveNames[i] = NULL; -#endif - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - /* - return 0 if it succeeds, nonzero (a - Macintosh style error code, but -1 - will do) on failure. - */ - MacErr_t result; - uint32_t NewSony_Count = Sony_Count; - - result = - (MacErr_t)SetFPos(Drives[Drive_No], fsFromStart, Sony_Start); - if (mnvm_noErr == result) { - if (IsWrite) { - /* - write Sony_Count bytes from Buffer, to disk image - number Drive_No, starting at offset Sony_Start. - */ - - result = (MacErr_t)FSWrite(Drives[Drive_No], - (long *)&NewSony_Count, Buffer); - } else { - /* - read Sony_Count bytes into Buffer, from disk image - number Drive_No, starting at offset Sony_Start. - */ - - result = (MacErr_t)FSRead(Drives[Drive_No], - (long *)&NewSony_Count, Buffer); - } - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = NewSony_Count; - } - - return result; -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - /* - set Sony_Count to the size of disk image number Drive_No. - - return 0 if it succeeds, nonzero (a - Macintosh style error code, but -1 - will do) on failure. - */ - return GetEOF(Drives[Drive_No], (long *)Sony_Count); -} - -LOCALFUNC OSErr vSonyEject0(tDrive Drive_No) -{ - /* - close disk image number Drive_No. - - return 0 if it succeeds, nonzero (a - Macintosh style error code, but -1 - will do) on failure. - */ - short refnum = Drives[Drive_No]; - Drives[Drive_No] = NotAfileRef; /* not really needed */ - - DiskEjectedNotify(Drive_No); - -#if (IncludeSonyGetName || IncludeSonyNew) && HaveCPUfamM68K - { - Handle h = DriveNames[Drive_No]; - if (NULL != h) { - DisposeHandle(h); - DriveNames[Drive_No] = NULL; /* not really needed */ - } - } -#endif - - return FSClose(refnum); -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - OSErr result; - short vRefNum; - bool DidEject = false; - short refnum = Drives[Drive_No]; - - result = GetVRefNum(refnum, &vRefNum); - if (noErr == result) { - DidEject = true; - result = vSonyEject0(Drive_No); - (void) FlushVol(NULL, vRefNum); - } - - if (! DidEject) { - result = vSonyEject0(Drive_No); - } - - return (MacErr_t)result; -} - -#if IncludeSonyNew -GLOBALOSGLUFUNC MacErr_t vSonyEjectDelete(tDrive Drive_No) -{ - OSErr result; - Str255 s; - bool DidEject = false; - short refnum = Drives[Drive_No]; - -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - Handle h = DriveNames[Drive_No]; - if (NULL != h) { - short vRefNum; - result = GetVRefNum(refnum, &vRefNum); - if (noErr == result) { - PStrFromHandle(s, h, 255); - result = vSonyEject0(Drive_No); - DidEject = true; - (void) FSDelete(s, vRefNum); - } - } - } else -#endif - { - FCBPBRec b; - - b.ioCompletion = NULL; - b.ioNamePtr = (StringPtr)s; - b.ioVRefNum = 0; - b.ioRefNum = refnum; - b.ioFCBIndx = 0; - result = PBGetFCBInfoSync(&b); - if (noErr == result) { - FSSpec spec; - result = FSMakeFSSpec(b.ioFCBVRefNum, b.ioFCBParID, - s, &spec); - if (noErr == result) { - result = vSonyEject0(Drive_No); - DidEject = true; - (void) FSpDelete(&spec); - } - } - } - - if (! DidEject) { - (void) vSonyEject0(Drive_No); - } - - return (MacErr_t)result; -} -#endif - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -#if IncludeSonyGetName -GLOBALOSGLUFUNC MacErr_t vSonyGetName(tDrive Drive_No, tPbuf *r) -{ - FCBPBRec b; - Str255 s; - MacErr_t err = mnvm_miscErr; - -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - Handle h = DriveNames[Drive_No]; - if (NULL != h) { - PStrFromHandle(s, h, 255); - err = mnvm_noErr; - } - } else -#endif - { - b.ioCompletion = NULL; - b.ioNamePtr = (StringPtr)s; - b.ioVRefNum = 0; - b.ioRefNum = Drives[Drive_No]; - b.ioFCBIndx = 0; - err = To_tMacErr(PBGetFCBInfoSync(&b)); - } - - if (mnvm_noErr == err) { - Handle h; - err = PStrToHand(s, &h); - if (noErr == err) { - err = PbufNewFromHandle(h, s[0], r); - } - } - - return err; -} -#endif - -LOCALFUNC MacErr_t Sony_Insert0(short refnum, bool locked, ps3p s) -{ - /* - Given reference to open file, mount it as - a disk image file. if "locked", then mount - it as a locked disk. - */ - - tDrive Drive_No; - -#if ! ((IncludeSonyGetName || IncludeSonyNew) && HaveCPUfamM68K) - UnusedParam(s); -#endif - - if (! FirstFreeDisk(&Drive_No)) { - (void) FSClose(refnum); - return mnvm_tmfoErr; /* too many files open */ - } else { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); -#if (IncludeSonyGetName || IncludeSonyNew) && HaveCPUfamM68K - if (s != NULL) { - Handle h; - - if (mnvm_noErr != PStrToHand(s, &h)) { - h = NULL; - } - DriveNames[Drive_No] = h; - } -#endif - return mnvm_noErr; - } -} - -LOCALPROC ReportStandardOpenDiskError(MacErr_t err) -{ - if (mnvm_noErr != err) { - if (mnvm_tmfoErr == err) { - MacMsg(kStrTooManyImagesTitle, - kStrTooManyImagesMessage, false); - } else if (mnvm_opWrErr == err) { - MacMsg(kStrImageInUseTitle, - kStrImageInUseMessage, false); - } else { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } -} - -LOCALFUNC MacErr_t InsertADiskFromFileRef(FSSpec *spec) -{ - short refnum; - MacErr_t err; - bool locked = false; - - err = To_tMacErr(FSpOpenDF(spec, fsRdWrPerm, &refnum)); - switch (err) { - case mnvm_permErr: - case mnvm_wrPermErr: - case mnvm_afpAccessDenied: - locked = true; - err = To_tMacErr(FSpOpenDF(spec, fsRdPerm, &refnum)); - break; - default: - break; - } - if (mnvm_noErr == err) { - err = Sony_Insert0(refnum, locked, NULL); - } - - return err; -} - -#if HaveCPUfamM68K -LOCALFUNC MacErr_t InsertADiskFromNamevRef(ConstStr255Param fileName, - short vRefNum) -{ - ParamBlockRec R; - MacErr_t err; - bool locked = false; - - R.ioParam.ioCompletion = NULL; - R.ioParam.ioNamePtr = (StringPtr)fileName; - R.ioParam.ioVRefNum = vRefNum; - R.ioParam.ioVersNum = 0; - R.ioParam.ioPermssn = fsRdWrPerm; - R.ioParam.ioMisc = NULL; - err = To_tMacErr(PBOpen(&R, false)); - switch (err) { - case mnvm_permErr: - case mnvm_wrPermErr: - case mnvm_afpAccessDenied: - locked = true; - R.ioParam.ioPermssn = fsRdPerm; - err = To_tMacErr(PBOpen(&R, false)); - break; - default: - break; - } - if (mnvm_noErr == err) { - err = Sony_Insert0(R.ioParam.ioRefNum, locked, (ps3p)fileName); - } - - return err; -} -#endif - -LOCALFUNC MacErr_t LoadMacRomFromRefNum(short refnum) -{ - /* - load the ROM image file into ptr ROM - */ - MacErr_t err; - long count = kROM_Size; - - if (mnvm_noErr != (err = To_tMacErr( - FSRead(refnum, &count, ROM)))) - { - if (mnvm_eofErr == err) { - MacMsgOverride(kStrShortROMTitle, kStrShortROMMessage); - } else { - MacMsgOverride(kStrNoReadROMTitle, kStrNoReadROMMessage); - } - } else - { - err = ROM_IsValid(); - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromFSSpec(FSSpec *spec) -{ - MacErr_t err; - short refnum; - - if (mnvm_noErr == (err = - To_tMacErr(FSpOpenDF(spec, fsRdPerm, &refnum)))) - { - err = LoadMacRomFromRefNum(refnum); - (void) FSClose(refnum); - } - - return err; -} - -#if HaveCPUfamM68K -LOCALFUNC MacErr_t LoadMacRomFromNamevRef(ConstStr255Param fileName, - short vRefNum) -{ - MacErr_t err; - ParamBlockRec R; - - R.ioParam.ioCompletion = NULL; - R.ioParam.ioNamePtr = (StringPtr)fileName; - R.ioParam.ioVRefNum = vRefNum; - R.ioParam.ioVersNum = 0; - R.ioParam.ioPermssn = fsRdPerm; - R.ioParam.ioMisc = NULL; - if (mnvm_noErr == (err = To_tMacErr(PBOpen(&R, false)))) { - err = LoadMacRomFromRefNum(R.ioParam.ioRefNum); - (void) FSClose(R.ioParam.ioRefNum); - } - - return err; -} -#endif - -#if HaveCPUfamM68K -LOCALFUNC MacErr_t InsertADiskFromNamevRef1(ConstStr255Param fileName, - short vRefNum) -{ - MacErr_t err; - - if (! ROM_loaded) { - err = LoadMacRomFromNamevRef(fileName, vRefNum); - } else { - err = InsertADiskFromNamevRef(fileName, vRefNum); - } - - return err; -} -#endif - -LOCALFUNC MacErr_t InsertADiskOrAliasFromSpec(FSSpec *spec, - bool MaybeROM, bool MaybeAlias) -{ - Boolean isFolder; - Boolean isAlias; - MacErr_t err; - - if ((! MaybeAlias) - || CheckSaveMacErr(ResolveAliasFile(spec, true, - &isFolder, &isAlias))) - { - if (MaybeROM && ! ROM_loaded) { - err = LoadMacRomFromFSSpec(spec); - } else { - err = InsertADiskFromFileRef(spec); - } - } - - return err; -} - -LOCALFUNC MacErr_t InsertDisksFromDocList(AEDescList *docList) -{ - MacErr_t err = mnvm_noErr; - long itemsInList; - long index; - AEKeyword keyword; - DescType typeCode; - FSSpec spec; - Size actualSize; - - if (CheckSaveMacErr(AECountItems(docList, &itemsInList))) { - for (index = 1; index <= itemsInList; ++index) { - if (CheckSaveMacErr(AEGetNthPtr(docList, index, typeFSS, - &keyword, &typeCode, (Ptr)&spec, sizeof(FSSpec), - &actualSize))) - if (CheckSavetMacErr(InsertADiskOrAliasFromSpec(&spec, - true, false))) - { - } - if (mnvm_noErr != err) { - goto label_fail; - } - } - } - -label_fail: - return err; -} - -LOCALFUNC MacErr_t InsertADiskFromNameEtc(Dir_R *d, - ConstStr255Param fileName) -{ - MacErr_t err; - -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - err = InsertADiskFromNamevRef(fileName, d->VRefNum); - } else -#endif - { - FSSpec spec; - - if (CheckSaveMacErr( - FSMakeFSSpec(d->VRefNum, d->DirId, fileName, &spec))) - { - err = InsertADiskOrAliasFromSpec(&spec, - false, true); - } - } - - return err; -} - -#if NavigationAvail -pascal Boolean NavigationFilterProc( - AEDesc* theItem, void* info, void* NavCallBackUserData, - NavFilterModes theNavFilterModes); -pascal Boolean NavigationFilterProc( - AEDesc* theItem, void* info, void* NavCallBackUserData, - NavFilterModes theNavFilterModes) -{ - Boolean display = true; - NavFileOrFolderInfo* theInfo = (NavFileOrFolderInfo*)info; - UnusedParam(theNavFilterModes); - UnusedParam(NavCallBackUserData); - - if (typeFSS == theItem->descriptorType) { - if (! theInfo->isFolder) { - /* - use: - 'theInfo->fileAndFolder.fileInfo.finderInfo.fdType' - to check for the file type you want to filter. - */ - } - } - return display; -} -#endif - - -#if NavigationAvail -pascal void NavigationEventProc( - NavEventCallbackMessage callBackSelector, - NavCBRecPtr callBackParms, void *NavCallBackUserData); -pascal void NavigationEventProc( - NavEventCallbackMessage callBackSelector, - NavCBRecPtr callBackParms, void *NavCallBackUserData) -{ - UnusedParam(NavCallBackUserData); - - if (kNavCBEvent == callBackSelector) { - switch (callBackParms->eventData.eventDataParms.event->what) { - case updateEvt: - { - WindowPtr which = - (WindowPtr)callBackParms - ->eventData.eventDataParms.event - ->message; - - BeginUpdate(which); - - if (which == gMainWindow) { - Update_Screen(); - } - - EndUpdate(which); - } - break; - } - } -} -#endif - -#define PStrConstBlank ((ps3p)"\000") - -LOCALPROC InsertADisk0(void) -{ -#if NavigationAvail -#define DisposeNavEventUPP(userUPP) \ - DisposeRoutineDescriptor(userUPP) -#define DisposeNavObjectFilterUPP(userUPP) \ - DisposeRoutineDescriptor(userUPP) -#define NewNavObjectFilterUPP NewNavObjectFilterProc -#define NewNavEventUPP NewNavEventProc - - if (HaveNavServicesAvail()) { - NavReplyRecord theReply; - NavDialogOptions dialogOptions; - OSErr theErr = noErr; - NavTypeListHandle openList = NULL; - NavObjectFilterUPP filterUPP = - NewNavObjectFilterUPP( - /* (NavObjectFilterProcPtr) */ NavigationFilterProc); - NavEventUPP eventUPP = NewNavEventUPP( - /* (NavEventProcPtr) */ NavigationEventProc); - - theErr = NavGetDefaultDialogOptions(&dialogOptions); - - dialogOptions.dialogOptionFlags |= kNavDontAutoTranslate; - /* - dialogOptions.dialogOptionFlags &= ~ kNavAllowMultipleFiles; - */ - dialogOptions.dialogOptionFlags &= ~ kNavAllowPreviews; - - BeginDialog(); - theErr = NavGetFile(NULL, - &theReply, - &dialogOptions, - /* NULL */ eventUPP, - NULL, - filterUPP, - (NavTypeListHandle)openList, - NULL); - EndDialog(); - - DisposeNavObjectFilterUPP(filterUPP); - DisposeNavEventUPP(eventUPP); - - - if (noErr == theErr) { - if (theReply.validRecord) { - ReportStandardOpenDiskError(InsertDisksFromDocList( - &theReply.selection)); - } - - NavDisposeReply(&theReply); - } - - } else -#endif -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - Point where; - SFReply reply; - - where.h = 50; - where.v = 50; - BeginDialog(); - SFGetFile(*(Point *)&where, PStrConstBlank, NULL, - -1 /* kNumFileTypes */, NULL /* fileTypes */, - NULL, &reply); - EndDialog(); - if (reply.good) { - ReportStandardOpenDiskError( - InsertADiskFromNamevRef1(reply.fName, reply.vRefNum)); - } - } else -#endif - { - StandardFileReply reply; - - BeginDialog(); - StandardGetFile(0L, -1, 0L, &reply); - EndDialog(); - if (reply.sfGood) { - ReportStandardOpenDiskError( - InsertADiskOrAliasFromSpec(&reply.sfFile, - true, false)); - } - } -} - -#ifndef AppIsBundle -#define AppIsBundle 0 -#endif - -LOCALVAR Dir_R DatDir; - -#if AppIsBundle -LOCALFUNC bool DirectorySpec2DirId(FSSpec *spec, long *dirID) -{ - CInfoPBRec b; - - b.hFileInfo.ioCompletion = NULL; - b.hFileInfo.ioNamePtr = (StringPtr)spec->name; - b.hFileInfo.ioVRefNum = spec->vRefNum; - b.dirInfo.ioFDirIndex = 0; - b.dirInfo.ioDrDirID = spec->parID; - if (noErr == PBGetCatInfo(&b, false)) { - *dirID = b.dirInfo.ioDrDirID; - return true; - } else { - return false; - } -} -#endif - -#if AppIsBundle -LOCALFUNC bool FindNamedChildDirId(short TrueParentVol, - long ParentDirId, StringPtr ChildName, - short *TrueChildVol, long *ChildDirId) -{ - - FSSpec temp_spec; - Boolean isFolder; - Boolean isAlias; - - if (noErr == FSMakeFSSpec(TrueParentVol, ParentDirId, - ChildName, &temp_spec)) - if (noErr == ResolveAliasFile(&temp_spec, true, - &isFolder, &isAlias)) - if (isFolder) - if (DirectorySpec2DirId(&temp_spec, ChildDirId)) - { - *TrueChildVol = temp_spec.vRefNum; - return true; - } - return false; -} -#endif - -LOCALFUNC bool InitApplInfo(void) -{ -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - if (noErr == GetVol(NULL, &DatDir.VRefNum)) { - DatDir.DirId = 0; - return true; - } - } else -#endif - { - FCBPBRec pb; - Str255 fileName; - - pb.ioCompletion = NULL; - pb.ioNamePtr = fileName; - pb.ioVRefNum = 0; - pb.ioRefNum = CurResFile(); - pb.ioFCBIndx = 0; - if (noErr == PBGetFCBInfoSync(&pb)) { - DatDir.VRefNum = pb.ioFCBVRefNum; - DatDir.DirId = pb.ioFCBParID; - return true; - } - } - - return false; -} - -LOCALFUNC MacErr_t DirFromWD_v2(short VRefNum, Dir_R *d) -{ - MacErr_t err; - Str63 s; - WDPBRec pb; - -#if Support64kROM - if (Have64kROM()) { - d->VRefNum = VRefNum; - d->DirId = 0; - err = mnvm_noErr; - } else -#endif - { - pb.ioCompletion = NULL; - pb.ioNamePtr = s; - pb.ioVRefNum = VRefNum; - pb.ioWDIndex = 0; - pb.ioWDProcID = 0; - err = To_tMacErr(PBGetWDInfoSync(&pb)); - if (mnvm_noErr == err) { - d->VRefNum = pb.ioWDVRefNum; - d->DirId = pb.ioWDDirID; - } - } - - return err; -} - -LOCALFUNC MacErr_t FindPrefFolder(Dir_R *d) -{ - MacErr_t err; - long reply; - - if (HaveGestaltAvail() - && (noErr == Gestalt(gestaltFindFolderAttr, &reply)) - && TestBit(reply, gestaltFindFolderPresent) - ) - { - err = To_tMacErr(FindFolder( - kOnSystemDisk, - kPreferencesFolderType, - kDontCreateFolder, - &d->VRefNum, - &d->DirId)); - } else { - SysEnvRec info; - - err = To_tMacErr(SysEnvirons(1, &info)); - if (mnvm_noErr == err) { - err = DirFromWD_v2(info.sysVRefNum, d); - } - } - - return err; -} - -#define CatInfoIsFolder(cPB) \ - (((cPB)->hFileInfo.ioFlAttrib & kioFlAttribDirMask) != 0) - -#define PStrLength(s) (*(s)) -#define SizeOfListChar(n) (n) -#define PStrToTotSize(s) (SizeOfListChar(PStrLength(s) + 1)) - /* + 1 for length byte */ - -LOCALPROC PStrCopy(ps3p r, ps3p s) -{ - MoveBytes((anyp)s, (anyp)r, PStrToTotSize(s)); -} - -LOCALFUNC MacErr_t FindNamedChildDir_v2(Dir_R *src_d, StringPtr s, - Dir_R *dst_d) -{ - MacErr_t err; - Str255 NameBuffer; - CInfoPBRec cPB; - - cPB.hFileInfo.ioCompletion = NULL; - cPB.hFileInfo.ioVRefNum = src_d->VRefNum; - cPB.dirInfo.ioDrDirID = src_d->DirId; - cPB.hFileInfo.ioNamePtr = NameBuffer; - PStrCopy(NameBuffer, s); - cPB.dirInfo.ioFDirIndex = 0; - - err = To_tMacErr(PBGetCatInfoSync(&cPB)); - - if (mnvm_noErr == err) { - if (! CatInfoIsFolder(&cPB)) { - err = mnvm_dirNFErr; - } else { - dst_d->VRefNum = cPB.hFileInfo.ioVRefNum; - dst_d->DirId = cPB.dirInfo.ioDrDirID; - } - } - - return err; -} - -LOCALFUNC MacErr_t ResolveAliasDir_v2(Dir_R *src_d, StringPtr s, - Dir_R *dst_d) -{ - MacErr_t err; - FSSpec spec; - Boolean isFolder; - Boolean isAlias; - Dir_R src2_d; - - spec.vRefNum = src_d->VRefNum; - spec.parID = src_d->DirId; - PStrCopy(spec.name, s); - err = To_tMacErr( - ResolveAliasFile(&spec, true, &isFolder, &isAlias)); - if (mnvm_noErr == err) { - if (! isAlias) { - err = mnvm_dirNFErr; - } else { - src2_d.VRefNum = spec.vRefNum; - src2_d.DirId = spec.parID; - err = FindNamedChildDir_v2(&src2_d, spec.name, dst_d); - } - } - - return err; -} - -LOCALFUNC MacErr_t ResolveNamedChildDir_v2(Dir_R *src_d, StringPtr s, - Dir_R *dst_d) -{ - MacErr_t err; - - err = FindNamedChildDir_v2(src_d, s, dst_d); - if (mnvm_dirNFErr == err) { - if (HaveAliasMgrAvail()) { - err = ResolveAliasDir_v2(src_d, s, dst_d); - } - } - - return err; -} - -LOCALFUNC MacErr_t OpenNamedFileInFolderCStr(Dir_R *d, - char *s, short *refnum) -{ - Str255 fileName; - - PStrFromCStr(fileName, s); - return OpenNamedFileInFolder(d, fileName, refnum); -} - -LOCALFUNC MacErr_t ResolveNamedChildDirCStr(Dir_R *src_d, - char *s, Dir_R *dst_d) -{ - Str255 fileName; - - PStrFromCStr(fileName, s); - return ResolveNamedChildDir_v2(src_d, fileName, dst_d); -} - -LOCALFUNC MacErr_t LoadMacRomFromNameFolder(Dir_R *d, - char *s) -{ - MacErr_t err; - short refnum; - - if (mnvm_noErr == (err = - OpenNamedFileInFolderCStr(d, s, &refnum))) - { - err = LoadMacRomFromRefNum(refnum); - (void) FSClose(refnum); - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromPrefDir(void) -{ - MacErr_t err; - Dir_R PrefRef; - Dir_R GryphelRef; - Dir_R ROMsRef; - - if (mnvm_noErr == (err = FindPrefFolder(&PrefRef))) - if (mnvm_noErr == (err = ResolveNamedChildDirCStr(&PrefRef, - "Gryphel", &GryphelRef))) - if (mnvm_noErr == (err = ResolveNamedChildDirCStr(&GryphelRef, - "mnvm_rom", &ROMsRef))) - if (mnvm_noErr == (err = LoadMacRomFromNameFolder(&ROMsRef, - RomFileName))) - { - /* ok */ - } - - return err; -} - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if (mnvm_fnfErr == (err = - LoadMacRomFromNameFolder(&DatDir, RomFileName))) - if (mnvm_fnfErr == (err = - LoadMacRomFromPrefDir())) - { - } - - return true; /* keep launching Mini vMac, regardless */ -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - return false; - } else { - Str255 s; - MacErr_t err = mnvm_noErr; - - PStrFromCStr(s, "disk?.dsk"); - - s[5] = '0' + i; - if (! CheckSavetMacErr(InsertADiskFromNameEtc(&DatDir, s))) { - if (mnvm_fnfErr != err) { - ReportStandardOpenDiskError(err); - } - return false; - } - - return true; - } -} - -LOCALFUNC bool LoadInitialImages(void) -{ - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - - return true; -} - -#if IncludeSonyNew -LOCALFUNC MacErr_t WriteZero(SInt16 refnum, uint32_t L) -{ -#define ZeroBufferSize 2048 - MacErr_t err; - uint32_t i; - uint8_t buffer[ZeroBufferSize]; - - if (CheckSaveMacErr(SetFPos(refnum, fsFromStart, 0))) { - - for (i = 0; i < ZeroBufferSize; ++i) { - buffer[i] = 0; - } - while (L > 0) { - i = (L > ZeroBufferSize) ? ZeroBufferSize : L; - err = To_tMacErr(FSWrite(refnum, (long *)&i, buffer)); - if (mnvm_noErr != err) { - goto label_fail; - } - L -= i; - } - } - -label_fail: - return err; -} -#endif - -#if HaveCPUfamM68K && IncludeSonyNew -LOCALPROC MakeNewDiskFromNamevRef(ps3p Name, short vRefNum, - uint32_t L) -{ - short refNum; - MacErr_t err; - - err = To_tMacErr(Create(Name, vRefNum, '????', '????')); - if (mnvm_dupFNErr == err) { - if (CheckSaveMacErr(FSDelete(Name, vRefNum))) { - err = To_tMacErr(Create(Name, vRefNum, '????', '????')); - } - } - if (mnvm_noErr == err) { - if (CheckSaveMacErr(FSOpen(Name, vRefNum, &refNum))) { - if (CheckSaveMacErr(SetEOF(refNum, L))) { - if (CheckSavetMacErr(WriteZero(refNum, L))) { - err = Sony_Insert0(refNum, false, Name); - ReportStandardOpenDiskError(err); - refNum = NotAfileRef; - } - } - if (NotAfileRef != refNum) { - (void) FSClose(refNum); - } - } - if (mnvm_noErr != err) { - (void) FSDelete(Name, vRefNum); - } - } -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDiskFromSpec(FSSpec *NewFileSpec, - uint32_t L) -{ - short refNum; - MacErr_t err; - - err = To_tMacErr(FSpCreate(NewFileSpec, - '????', '????', smSystemScript)); - if (mnvm_dupFNErr == err) { - err = To_tMacErr(FSpDelete(NewFileSpec)); - if (mnvm_noErr == err) { - err = To_tMacErr(FSpCreate(NewFileSpec, - '????', '????', smSystemScript)); - } - } - if (mnvm_noErr == err) { - if (CheckSaveMacErr( - FSpOpenDF(NewFileSpec, fsRdWrPerm, &refNum))) - { - if (CheckSaveMacErr(SetEOF(refNum, L))) { - if (CheckSavetMacErr(WriteZero(refNum, L))) { - err = Sony_Insert0(refNum, false, NULL); - ReportStandardOpenDiskError(err); - refNum = NotAfileRef; - } - } - if (NotAfileRef != refNum) { - (void) FSClose(refNum); - } - } - if (mnvm_noErr != err) { - (void) FSpDelete(NewFileSpec); - } - } -} -#endif - -#if UseActvFile || (IncludeSonyNew && ! SaveDialogEnable) -LOCALFUNC MacErr_t MakeNamedDir_v2(Dir_R *d, StringPtr s, - Dir_R *new_d) -{ - MacErr_t err; - HParamBlockRec r; - - r.fileParam.ioCompletion = NULL; - r.fileParam.ioVRefNum = d->VRefNum; - r.fileParam.ioDirID = d->DirId; - r.fileParam.ioNamePtr = s; - err = To_tMacErr(PBDirCreateSync(&r)); - if (mnvm_noErr == err) { - new_d->VRefNum = d->VRefNum; - new_d->DirId = r.fileParam.ioDirID; - } - - return err; -} -#endif - -#if UseActvFile || (IncludeSonyNew && ! SaveDialogEnable) -LOCALFUNC MacErr_t FindOrMakeMakeNamedDir_v2(Dir_R *new_d, - Dir_R *d, StringPtr s) -{ - MacErr_t err; - - err = ResolveNamedChildDir_v2(d, s, new_d); - if (mnvm_fnfErr == err) { - err = MakeNamedDir_v2(d, s, new_d); - } - - return err; -} -#endif - -#if UseActvFile || (IncludeSonyNew && ! SaveDialogEnable) -LOCALFUNC MacErr_t FindOrMakeChildDirCStr(Dir_R *new_d, - Dir_R *d, char *name) -{ - Str255 s; - - PStrFromCStr(s, name); - return FindOrMakeMakeNamedDir_v2(new_d, d, s); -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDisk(uint32_t L, Handle NewDiskName) -{ -#if SaveDialogEnable - OSErr theErr; - -#if NavigationAvail - if (HaveNavServicesAvail()) { - NavReplyRecord theReply; - NavDialogOptions dialogOptions; - NavEventUPP eventUPP = NewNavEventUPP( - /* (NavEventProcPtr) */ NavigationEventProc); - - theErr = NavGetDefaultDialogOptions(&dialogOptions); - dialogOptions.dialogOptionFlags |= kNavNoTypePopup; -#if IncludeSonyNameNew - if (NewDiskName != NULL) { - PStrFromHandle(dialogOptions.savedFileName, - NewDiskName, 255); - } -#endif - BeginDialog(); - theErr = NavPutFile(NULL, &theReply, &dialogOptions, - /* NULL */ eventUPP, '????', '????', NULL); - EndDialog(); - - DisposeNavEventUPP(eventUPP); - - if (noErr == theErr) { - if (theReply.validRecord) { - long itemsInList; - AEKeyword keyword; - DescType typeCode; - Size actualSize; - FSSpec NewFileSpec; - - if (noErr == - AECountItems(&theReply.selection, &itemsInList)) - if (1 == itemsInList) - if (noErr == AEGetNthPtr(&theReply.selection, - 1, typeFSS, &keyword, &typeCode, - (Ptr)&NewFileSpec, sizeof(FSSpec), &actualSize)) - { - MakeNewDiskFromSpec(&NewFileSpec, L); - } - } - NavDisposeReply(&theReply); - } - } else -#endif - { - Str255 Title; - Str255 prompt; - -#if IncludeSonyNameNew - if (NewDiskName != NULL) { - PStrFromHandle(Title, NewDiskName, 255); - } else -#endif - { - NativeStrFromCStr(Title, "untitled", false); - } - NativeStrFromCStr(prompt, "Please select a file", false); - -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - Point where; - SFReply reply; - - where.h = 50; - where.v = 50; - BeginDialog(); - SFPutFile(*(Point *)&where, prompt, Title, NULL, &reply); - EndDialog(); - - if (reply.good) { - MakeNewDiskFromNamevRef(reply.fName, - reply.vRefNum, L); - } - } else -#endif - { - StandardFileReply reply; - - BeginDialog(); - StandardPutFile(prompt, Title, &reply); - EndDialog(); - - if (reply.sfGood) { - MakeNewDiskFromSpec(&reply.sfFile, L); - } - } - } -#else /* SaveDialogEnable */ - MacErr_t err; - Str255 Title; - Dir_R OutDir; - FSSpec spec; - -#if IncludeSonyNameNew - if (NewDiskName != NULL) { - PStrFromHandle(Title, NewDiskName, 255); - } else -#endif - { - NativeStrFromCStr(Title, "untitled", false); - } - - if (mnvm_noErr == (err = FindOrMakeChildDirCStr(&OutDir, - &DatDir, "out"))) - { -#if HaveCPUfamM68K - if (! HaveFSSpecCallsAvail()) { - MakeNewDiskFromNamevRef(Title, OutDir.VRefNum, L); - } else -#endif - { - err = To_tMacErr(FSMakeFSSpec(OutDir.VRefNum, OutDir.DirId, - Title, &spec)); - if ((mnvm_noErr == err) || (mnvm_fnfErr == err)) { - MakeNewDiskFromSpec(&spec, L); - } - } - } -#endif /* SaveDialogEnable */ -} -#endif - -#if UseActvFile - -LOCALFUNC MacErr_t CreateFile_v2(Dir_R *d, StringPtr s) -{ - MacErr_t err; - HParamBlockRec r; - - r.fileParam.ioFlVersNum = 0; - /* - Think reference says to do this, - but not Inside Mac IV - */ - - r.fileParam.ioCompletion = NULL; - r.fileParam.ioNamePtr = s; - r.fileParam.ioVRefNum = d->VRefNum; - r.fileParam.ioFVersNum = 0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = To_tMacErr(PBCreateSync((ParamBlockRec *)&r)); - } else -#endif - { - r.fileParam.ioDirID = d->DirId; - err = To_tMacErr(PBHCreateSync(&r)); - } - - return err; -} - -LOCALFUNC MacErr_t DeleteFile_v2(Dir_R *d, StringPtr s) -{ - MacErr_t err; - HParamBlockRec r; - - r.fileParam.ioCompletion = NULL; - r.fileParam.ioVRefNum = d->VRefNum; - r.fileParam.ioNamePtr = s; - r.fileParam.ioFVersNum = 0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = To_tMacErr(PBDeleteSync((ParamBlockRec *)&r)); - } else -#endif - { - r.fileParam.ioDirID = d->DirId; - err = To_tMacErr(PBHDeleteSync(&r)); - } - - return err; -} - -LOCALFUNC MacErr_t CreateFileOverWrite_v2(Dir_R *d, StringPtr s) -{ - MacErr_t err; - - err = CreateFile_v2(d, s); - if (mnvm_dupFNErr == err) { - if (mnvm_noErr == (err = DeleteFile_v2(d, s))) { - err = CreateFile_v2(d, s); - } - } - - return err; -} - -LOCALFUNC MacErr_t FileOpen_v2(Dir_R *d, StringPtr s, - char Permssn, short *refnum) -{ - MacErr_t err; - HParamBlockRec r; - - r.ioParam.ioCompletion = NULL; - r.ioParam.ioNamePtr = s; - r.ioParam.ioVRefNum = d->VRefNum; - r.ioParam.ioPermssn = Permssn; - r.ioParam.ioMisc = 0; /* use volume buffer */ - r.ioParam.ioVersNum = 0; /* needed if MFS volume */ - -#if Support64kROM - if (Have64kROM()) { - err = To_tMacErr(PBOpenSync((ParamBlockRec *)&r)); - } else -#endif - { - r.fileParam.ioDirID = d->DirId; - err = To_tMacErr(PBHOpenSync(&r)); - } - - if (noErr == err) { - *refnum = r.ioParam.ioRefNum; - /* - Don't change *refnum unless file opened, - so can initialize to NotAfileRef, and - compare later before closing in uninit. - */ - } - return err; -} - -LOCALFUNC MacErr_t FileOpenWrite_v2(Dir_R *d, StringPtr s, - short *refnum) -{ - return FileOpen_v2(d, s, (char)fsWrPerm, refnum); -} - -LOCALFUNC MacErr_t OpenOverWriteFile_v2(Dir_R *d, StringPtr s, - short *refnum) -{ - MacErr_t err; - - err = CreateFileOverWrite_v2(d, s); - if (mnvm_noErr == err) { - err = FileOpenWrite_v2(d, s, refnum); - - if (mnvm_noErr != err) { - (void) DeleteFile_v2(d, s); - /* ignore any error, since already got one */ - } - } - - return err; -} - -LOCALFUNC MacErr_t OpenOverWriteFileCStr(Dir_R *d, char *name, - short *refnum) -{ - Str255 s; - - PStrFromCStr(s, name); - return OpenOverWriteFile_v2(d, s, refnum); -} - -#define ActvCodeFileName "act_1" - -LOCALFUNC MacErr_t OpenActvCodeFile(short *refnum) -{ - MacErr_t err; - Dir_R PrefRef; - Dir_R GryphelRef; - Dir_R ActRef; - - if (mnvm_noErr == (err = FindPrefFolder(&PrefRef))) - if (mnvm_noErr == (err = ResolveNamedChildDirCStr(&PrefRef, - "Gryphel", &GryphelRef))) - if (mnvm_noErr == (err = ResolveNamedChildDirCStr(&GryphelRef, - "mnvm_act", &ActRef))) - if (mnvm_noErr == (err = OpenNamedFileInFolderCStr(&ActRef, - ActvCodeFileName, refnum))) - { - /* ok */ - } - - return err; -} - -LOCALFUNC MacErr_t ActvCodeFileLoad(uint8_t * p) -{ - MacErr_t err; - short refnum; - - if (CheckSavetMacErr(OpenActvCodeFile(&refnum))) { - long count = ActvCodeFileLen; - err = To_tMacErr(FSRead(refnum, &count, p)); - (void) FSClose(refnum); - } - - return err; -} - -LOCALFUNC MacErr_t ActvCodeFileSave(uint8_t * p) -{ - MacErr_t err; - short refnum; - Dir_R PrefRef; - Dir_R GryphelRef; - Dir_R ActRef; - long count = ActvCodeFileLen; - - if (mnvm_noErr == (err = FindPrefFolder(&PrefRef))) - if (mnvm_noErr == (err = FindOrMakeChildDirCStr(&GryphelRef, - &PrefRef, "Gryphel"))) - if (mnvm_noErr == (err = FindOrMakeChildDirCStr(&ActRef, - &GryphelRef, "mnvm_act"))) - if (mnvm_noErr == (err = OpenOverWriteFileCStr(&ActRef, - ActvCodeFileName, &refnum))) - { - err = To_tMacErr(FSWrite(refnum, &count, p)); - (void) FSClose(refnum); - } - - return err; - /* return mnvm_miscErr; */ -} - -#endif /* UseActvFile */ - -#define openOnly 1 -#define openPrint 2 - -LOCALFUNC bool GotRequiredParams(AppleEvent *theAppleEvent) -{ - DescType typeCode; - Size actualSize; - OSErr theErr; - - theErr = AEGetAttributePtr(theAppleEvent, keyMissedKeywordAttr, - typeWildCard, &typeCode, NULL, 0, &actualSize); - if (errAEDescNotFound == theErr) { /* No more required params. */ - return true; - } else if (noErr == theErr) { /* More required params! */ - return /* CheckSysCode(errAEEventNotHandled) */ false; - } else { /* Unexpected Error! */ - return /* CheckSysCode(theErr) */ false; - } -} - -LOCALFUNC bool GotRequiredParams0(AppleEvent *theAppleEvent) -{ - DescType typeCode; - Size actualSize; - OSErr theErr; - - theErr = AEGetAttributePtr(theAppleEvent, keyMissedKeywordAttr, - typeWildCard, &typeCode, NULL, 0, &actualSize); - if (errAEDescNotFound == theErr) { /* No more required params. */ - return true; - } else if (noErr == theErr) { /* More required params! */ - return true; /* errAEEventNotHandled; */ /*^*/ - } else { /* Unexpected Error! */ - return /* CheckSysCode(theErr) */ false; - } -} - -/* call back */ static pascal OSErr OpenOrPrintFiles( - AppleEvent *theAppleEvent, AppleEvent *reply, long aRefCon) -{ - /* - Adapted from IM VI: AppleEvent Manager: - Handling Required AppleEvents - */ - AEDescList docList; - - UnusedParam(reply); - UnusedParam(aRefCon); - /* put the direct parameter (a list of descriptors) into docList */ - if (noErr == (AEGetParamDesc(theAppleEvent, - keyDirectObject, typeAEList, &docList))) - { - if (GotRequiredParams0(theAppleEvent)) { - /* Check for missing required parameters */ - /* printIt = (openPrint == aRefCon) */ - ReportStandardOpenDiskError( - InsertDisksFromDocList(&docList)); - } - /* vCheckSysCode */ (void) (AEDisposeDesc(&docList)); - } - return /* GetASysResultCode() */ 0; -} - -/* call back */ static pascal OSErr DoOpenEvent( - AppleEvent *theAppleEvent, AppleEvent *reply, long aRefCon) -/* - This is the alternative to getting an - open document event on startup. -*/ -{ - UnusedParam(reply); - UnusedParam(aRefCon); - if (GotRequiredParams0(theAppleEvent)) { - } - return /* GetASysResultCode() */ 0; - /* Make sure there are no additional "required" parameters. */ -} - - -/* call back */ static pascal OSErr DoQuitEvent( - AppleEvent *theAppleEvent, AppleEvent *reply, long aRefCon) -{ - UnusedParam(reply); - UnusedParam(aRefCon); - if (GotRequiredParams(theAppleEvent)) { - RequestMacOff = true; - } - - return /* GetASysResultCode() */ 0; -} - -#define NewAEEventHandlerUPP NewAEEventHandlerProc - -LOCALFUNC bool InstallEventHandler(AEEventClass theAEEventClass, - AEEventID theAEEventID, ProcPtr p, - long handlerRefcon, bool isSysHandler) -{ - return noErr == (AEInstallEventHandler(theAEEventClass, - theAEEventID, -#if /* useUPP */ 1 - NewAEEventHandlerUPP((AEEventHandlerProcPtr)p), -#else - (AEEventHandlerUPP)p, -#endif - handlerRefcon, isSysHandler)); -} - -LOCALPROC InstallAppleEventHandlers(void) -{ - if (noErr == AESetInteractionAllowed(kAEInteractWithLocal)) - if (InstallEventHandler(kCoreEventClass, kAEOpenApplication, - (ProcPtr)DoOpenEvent, 0, false)) - if (InstallEventHandler(kCoreEventClass, kAEOpenDocuments, - (ProcPtr)OpenOrPrintFiles, openOnly, false)) - if (InstallEventHandler(kCoreEventClass, kAEPrintDocuments, - (ProcPtr)OpenOrPrintFiles, openPrint, false)) - if (InstallEventHandler(kCoreEventClass, kAEQuitApplication, - (ProcPtr)DoQuitEvent, 0, false)) - { - } -} - -#if EnableDragDrop -static pascal OSErr GlobalTrackingHandler(short message, - WindowRef pWindow, void *handlerRefCon, DragReference theDragRef) -{ - RgnHandle hilightRgn; - Rect Bounds; - - UnusedParam(pWindow); - UnusedParam(handlerRefCon); - if (! ADialogIsUp) { - switch(message) { - case kDragTrackingEnterWindow: - hilightRgn = NewRgn(); - if (hilightRgn != NULL) { - SetScrnRectFromCoords(&Bounds, - 0, 0, vMacScreenHeight, vMacScreenWidth); - RectRgn(hilightRgn, &Bounds); - ShowDragHilite(theDragRef, hilightRgn, true); - DisposeRgn(hilightRgn); - } - break; - case kDragTrackingLeaveWindow: - HideDragHilite(theDragRef); - break; - } - } - - return noErr; -} -#endif - -#if EnableDragDrop -static DragTrackingHandlerUPP gGlobalTrackingHandler = NULL; -#endif - -#if EnableDragDrop -static pascal OSErr GlobalReceiveHandler(WindowRef pWindow, - void *handlerRefCon, DragReference theDragRef) -{ - unsigned short items; - unsigned short index; - ItemReference theItem; - Size SentSize; - HFSFlavor r; - - UnusedParam(pWindow); - UnusedParam(handlerRefCon); - if (! ADialogIsUp) - if (noErr == CountDragItems(theDragRef, &items)) - { - for (index = 1; index <= items; ++index) { - if (noErr == GetDragItemReferenceNumber(theDragRef, - index, &theItem)) - if (noErr == GetFlavorDataSize(theDragRef, - theItem, flavorTypeHFS, &SentSize)) - /* - On very old macs SentSize might only be big enough - to hold the actual file name. Have not seen this - in OS X, but still leave the check - as '<=' instead of '=='. - */ - if (SentSize <= sizeof(HFSFlavor)) - if (noErr == GetFlavorData(theDragRef, theItem, - flavorTypeHFS, (Ptr)&r, &SentSize, 0)) - { - ReportStandardOpenDiskError( - InsertADiskOrAliasFromSpec(&r.fileSpec, - true, true)); - } - } - - if (gTrueBackgroundFlag) { - ProcessSerialNumber currentProcess = {0, kCurrentProcess}; - - (void) SetFrontProcess(¤tProcess); - - WantCmdOptOnReconnect = true; - } - } - - return noErr; -} -#endif - -#if EnableDragDrop -static DragReceiveHandlerUPP gGlobalReceiveHandler = NULL; -#endif - -#if EnableDragDrop -#define NewDragTrackingHandlerUPP NewDragTrackingHandlerProc -#define NewDragReceiveHandlerUPP NewDragReceiveHandlerProc -#if ! OPAQUE_UPP_TYPES -#define DisposeDragReceiveHandlerUPP(userUPP) \ - DisposeRoutineDescriptor(userUPP) -#define DisposeDragTrackingHandlerUPP(userUPP) \ - DisposeRoutineDescriptor(userUPP) -#else -#define DisposeDragReceiveHandlerUPP DisposeDragReceiveHandlerUPP -#define DisposeDragTrackingHandlerUPP DisposeDragTrackingHandlerUPP -#endif -#endif - -#if EnableDragDrop -LOCALPROC UnPrepareForDragging(void) -{ - if (NULL != gGlobalReceiveHandler) { - RemoveReceiveHandler(gGlobalReceiveHandler, gMainWindow); - DisposeDragReceiveHandlerUPP(gGlobalReceiveHandler); - gGlobalReceiveHandler = NULL; - } - if (NULL != gGlobalTrackingHandler) { - RemoveTrackingHandler(gGlobalTrackingHandler, gMainWindow); - DisposeDragTrackingHandlerUPP(gGlobalTrackingHandler); - gGlobalTrackingHandler = NULL; - } -} -#endif - -#if EnableDragDrop -LOCALFUNC bool PrepareForDragging(void) -{ - bool IsOk = false; - - gGlobalTrackingHandler = NewDragTrackingHandlerUPP( - GlobalTrackingHandler); - if (gGlobalTrackingHandler != NULL) { - gGlobalReceiveHandler = NewDragReceiveHandlerUPP( - GlobalReceiveHandler); - if (gGlobalReceiveHandler != NULL) { - if (noErr == InstallTrackingHandler(gGlobalTrackingHandler, - gMainWindow, nil)) - { - if (noErr == InstallReceiveHandler( - gGlobalReceiveHandler, gMainWindow, nil)) - { - IsOk = true; - } - } - } - } - - return IsOk; -} -#endif - -#if 1 -#define ScaleBuffSzMult (WindowScale * WindowScale) -#endif - -LOCALFUNC bool CreateNewWindow(Rect *Bounds, WindowPtr *theWindow) -{ - WindowPtr ResultWin; - bool IsOk = false; - - ResultWin = NewWindow( - 0L, Bounds, LMGetCurApName() /* "\pMini vMac" */, false, - noGrowDocProc, /* Could use kWindowSimpleProc for Full Screen */ - (WindowPtr) -1, true, 0); - if (ResultWin != NULL) { - *theWindow = ResultWin; - - IsOk = true; - } - - return IsOk; -} - -LOCALPROC ZapWState(void) -{ - gMainWindow = NULL; - gGlobalReceiveHandler = NULL; - gGlobalTrackingHandler = NULL; -} - -LOCALPROC CloseMainWindow(void) -{ - /* - Dispose of anything set up by CreateMainWindow. - */ - -#if EnableDragDrop - UnPrepareForDragging(); -#endif - - if (gMainWindow != NULL) { - DisposeWindow(gMainWindow); - gMainWindow = NULL; - } -} - -enum { - kMagStateNormal, -#if 1 - kMagStateMagnifgy, -#endif - kNumMagStates -}; - -#define kMagStateAuto kNumMagStates - -#if MayNotFullScreen -LOCALVAR int CurWinIndx; -LOCALVAR bool HavePositionWins[kNumMagStates]; -LOCALVAR Point WinPositionWins[kNumMagStates]; -#endif - -LOCALFUNC bool CreateMainWindow(void) -{ - /* - Set up somewhere for us to draw the emulated screen and - receive mouse input. i.e. usually a window, as is the case - for this port. - - The window should not be resizeable. - - Should look at the current value of UseMagnify and - UseFullScreen. - - */ -#if MayNotFullScreen - int WinIndx; -#endif - Rect MainScrnBounds; - Rect AllScrnBounds; - Rect NewWinRect; - short leftPos; - short topPos; - short NewWindowHeight = vMacScreenHeight; - short NewWindowWidth = vMacScreenWidth; - bool IsOk = false; - -#if 1 - if (UseFullScreen) { - _HideMenuBar(); - } else { - _ShowMenuBar(); - } -#else -#if MayFullScreen - _HideMenuBar(); -#endif -#endif - - GetGrayRgnBounds(&AllScrnBounds); - GetScreenBitsBounds(&MainScrnBounds); - -#if 1 - if (UseMagnify) { - NewWindowHeight *= WindowScale; - NewWindowWidth *= WindowScale; - } -#endif - - leftPos = MainScrnBounds.left - + ((MainScrnBounds.right - MainScrnBounds.left) - - NewWindowWidth) / 2; - topPos = MainScrnBounds.top - + ((MainScrnBounds.bottom - MainScrnBounds.top) - - NewWindowHeight) / 2; - if (leftPos < MainScrnBounds.left) { - leftPos = MainScrnBounds.left; - } - if (topPos < MainScrnBounds.top) { - topPos = MainScrnBounds.top; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ViewHSize = MainScrnBounds.right - MainScrnBounds.left; - ViewVSize = MainScrnBounds.bottom - MainScrnBounds.top; -#if 1 - if (UseMagnify) { - ViewHSize /= WindowScale; - ViewVSize /= WindowScale; - } -#endif - if (ViewHSize >= vMacScreenWidth) { - ViewHStart = 0; - ViewHSize = vMacScreenWidth; - } else { - ViewHSize &= ~ 1; - } - if (ViewVSize >= vMacScreenHeight) { - ViewVStart = 0; - ViewVSize = vMacScreenHeight; - } else { - ViewVSize &= ~ 1; - } - } -#endif - - /* Create window rectangle and centre it on the screen */ - SetRect(&MainScrnBounds, 0, 0, NewWindowWidth, NewWindowHeight); - OffsetRect(&MainScrnBounds, leftPos, topPos); - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewWinRect = AllScrnBounds; - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { -#if 1 - if (UseMagnify) { - WinIndx = kMagStateMagnifgy; - } else -#endif - { - WinIndx = kMagStateNormal; - } - - if (! HavePositionWins[WinIndx]) { - WinPositionWins[WinIndx].h = leftPos; - WinPositionWins[WinIndx].v = topPos; - HavePositionWins[WinIndx] = true; - NewWinRect = MainScrnBounds; - } else { - SetRect(&NewWinRect, 0, 0, NewWindowWidth, NewWindowHeight); - OffsetRect(&NewWinRect, - WinPositionWins[WinIndx].h, WinPositionWins[WinIndx].v); - } - } -#endif - -#if MayNotFullScreen - CurWinIndx = WinIndx; -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - hOffset = MainScrnBounds.left - AllScrnBounds.left; - vOffset = MainScrnBounds.top - AllScrnBounds.top; - } -#endif - - if (CreateNewWindow(&NewWinRect, &gMainWindow)) { - ShowWindow(gMainWindow); - - /* check if window rect valid */ -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - Rect tr; - - if (GetWindowTitleBounds(gMainWindow, &tr)) { - if (! RectInRgn(&tr, _GetGrayRgn())) { - SetMacWindContRect(gMainWindow, - &MainScrnBounds); - if (GetWindowTitleBounds(gMainWindow, &tr)) { - if (! RectInRgn(&tr, _GetGrayRgn())) { - OffsetRect(&MainScrnBounds, - 0, AllScrnBounds.top - tr.top); - SetMacWindContRect(gMainWindow, - &MainScrnBounds); - } - } - } - } - } -#endif - -#if EnableDragDrop - if (HaveDragMgrAvail()) { - (void) PrepareForDragging(); - } -#endif - - IsOk = true; - } - - return IsOk; -} - -struct WState { - WindowPtr f_MainWindow; -#if MayFullScreen - short f_hOffset; - short f_vOffset; - uint16_t f_ViewHSize; - uint16_t f_ViewVSize; - uint16_t f_ViewHStart; - uint16_t f_ViewVStart; -#endif -#if 1 - bool f_UseFullScreen; -#endif -#if 1 - bool f_UseMagnify; -#endif -#if MayNotFullScreen - int f_CurWinIndx; -#endif - DragTrackingHandlerUPP f_gGlobalTrackingHandler; - DragReceiveHandlerUPP f_gGlobalReceiveHandler; -}; -typedef struct WState WState; - -LOCALPROC GetWState(WState *r) -{ - r->f_MainWindow = gMainWindow; -#if MayFullScreen - r->f_hOffset = hOffset; - r->f_vOffset = vOffset; - r->f_ViewHSize = ViewHSize; - r->f_ViewVSize = ViewVSize; - r->f_ViewHStart = ViewHStart; - r->f_ViewVStart = ViewVStart; -#endif -#if 1 - r->f_UseFullScreen = UseFullScreen; -#endif -#if 1 - r->f_UseMagnify = UseMagnify; -#endif -#if MayNotFullScreen - r->f_CurWinIndx = CurWinIndx; -#endif - r->f_gGlobalTrackingHandler = gGlobalTrackingHandler; - r->f_gGlobalReceiveHandler = gGlobalReceiveHandler; -} - -LOCALPROC SetWState(WState *r) -{ - gMainWindow = r->f_MainWindow; -#if MayFullScreen - hOffset = r->f_hOffset; - vOffset = r->f_vOffset; - ViewHSize = r->f_ViewHSize; - ViewVSize = r->f_ViewVSize; - ViewHStart = r->f_ViewHStart; - ViewVStart = r->f_ViewVStart; -#endif -#if 1 - UseFullScreen = r->f_UseFullScreen; -#endif -#if 1 - UseMagnify = r->f_UseMagnify; -#endif -#if MayNotFullScreen - CurWinIndx = r->f_CurWinIndx; -#endif - gGlobalTrackingHandler = r->f_gGlobalTrackingHandler; - gGlobalReceiveHandler = r->f_gGlobalReceiveHandler; -} - -LOCALFUNC bool ReCreateMainWindow(void) -{ - /* - Like CreateMainWindow (which it calls), except may be - called when already have window, without CloseMainWindow - being called first. (Usually with different - values of WantMagnify and WantFullScreen than - on the previous call.) - - If there is existing window, and fail to create - the new one, then existing window must be left alone, - in valid state. (and return false. otherwise, - if succeed, return true) - - i.e. can allocate the new one before disposing - of the old one. - */ - WState old_state; - WState new_state; - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - /* save old position */ - if (gMainWindow != NULL) { - Rect r; - - if (GetWindowContBounds(gMainWindow, &r)) { - WinPositionWins[CurWinIndx].h = r.left; - WinPositionWins[CurWinIndx].v = r.top; - } - } - } -#endif - -#if MayFullScreen - UngrabMachine(); -#endif - - GetWState(&old_state); - - ZapWState(); - -#if 1 - UseFullScreen = WantFullScreen; -#endif -#if 1 - UseMagnify = WantMagnify; -#endif - - ColorTransValid = false; - - if (! CreateMainWindow()) { - CloseMainWindow(); - SetWState(&old_state); - -#if 1 - if (UseFullScreen) { - _HideMenuBar(); - } else { - _ShowMenuBar(); - } -#endif - - /* avoid retry */ -#if 1 - WantFullScreen = UseFullScreen; -#endif -#if 1 - WantMagnify = UseMagnify; -#endif - - return false; - } else { - GetWState(&new_state); - SetWState(&old_state); - CloseMainWindow(); - SetWState(&new_state); - - if (HaveCursorHidden) { - (void) MoveMouse(CurMouseH, CurMouseV); - WantCursorHidden = true; - } - - return true; - } -} - -#if 1 && 1 -enum { - kWinStateWindowed, -#if 1 - kWinStateFullScreen, -#endif - kNumWinStates -}; -#endif - -#if 1 && 1 -LOCALVAR int WinMagStates[kNumWinStates]; -#endif - -LOCALPROC ZapWinStateVars(void) -{ -#if MayNotFullScreen - { - int i; - - for (i = 0; i < kNumMagStates; ++i) { - HavePositionWins[i] = false; - } - } -#endif -#if 1 && 1 - { - int i; - - for (i = 0; i < kNumWinStates; ++i) { - WinMagStates[i] = kMagStateAuto; - } - } -#endif -} - -#if 1 -LOCALPROC ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; - -#if 1 - { - int OldWinState = - UseFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int OldMagState = - UseMagnify ? kMagStateMagnifgy : kMagStateNormal; - int NewWinState = - WantFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int NewMagState = WinMagStates[NewWinState]; - - WinMagStates[OldWinState] = OldMagState; - if (kMagStateAuto != NewMagState) { - WantMagnify = (kMagStateMagnifgy == NewMagState); - } else { - WantMagnify = false; - if (WantFullScreen) { - Rect r; - - GetScreenBitsBounds(&r); - if (((r.right - r.left) - >= vMacScreenWidth * WindowScale) - && ((r.bottom - r.top) - >= vMacScreenHeight * WindowScale) - ) - { - WantMagnify = true; - } - } - } - } -#endif -} -#endif - -LOCALPROC LeaveBackground(void) -{ -#if HogCPU - NoEventsCounter = 0; -#endif - - SetCursorArrow(); - ReconnectKeyCodes3(); -} - -LOCALPROC EnterBackground(void) -{ - DisconnectKeyCodes3(); - -#if 1 - if (WantFullScreen) { - ToggleWantFullScreen(); - } -#endif -} - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif - - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if SoundEnabled - Sound_Stop(); -#endif -} - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MouseConstrain(); - } -#endif - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (gTrueBackgroundFlag != gBackgroundFlag) { - gBackgroundFlag = gTrueBackgroundFlag; - if (gTrueBackgroundFlag) { - EnterBackground(); - } else { - LeaveBackground(); - } - } - - if (CurSpeedStopped != (SpeedStopped || - (gBackgroundFlag && ! RunInBackground))) - { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - -#if EnableRecreateW - if (! (gTrueBackgroundFlag)) { - if (0 -#if 1 - || (UseMagnify != WantMagnify) -#endif -#if 1 - || (UseFullScreen != WantFullScreen) -#endif - ) - { - (void) ReCreateMainWindow(); -#if HogCPU - NoEventsCounter = 0; -#endif - } - } -#endif - -#if MayFullScreen - if (GrabMachine != ( -#if 1 - UseFullScreen && -#endif - ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - GrabMachine = ! GrabMachine; - AdjustMachineGrab(); - } -#endif - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - - if (gTrueBackgroundFlag) { - /* - dialog during drag and drop hangs if in background - and don't want recursive dialogs - so wait til later to display dialog - */ - } else { -#if IncludeSonyNew - if (vSonyNewDiskWanted) { -#if IncludeSonyNameNew - if (vSonyNewDiskName != NotAPbuf) { - MakeNewDisk(vSonyNewDiskSize, - PbufDat[vSonyNewDiskName]); - PbufDispose(vSonyNewDiskName); - vSonyNewDiskName = NotAPbuf; - } else -#endif - { - MakeNewDisk(vSonyNewDiskSize, NULL); - } - vSonyNewDiskWanted = false; - /* must be done after may have gotten disk */ - } -#endif - if (RequestInsertDisk) { - RequestInsertDisk = false; - InsertADisk0(); - } - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif - - if (HaveCursorHidden != (WantCursorHidden - && ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - HaveCursorHidden = ! HaveCursorHidden; - if (HaveCursorHidden) { - HideCursor(); - } else { - ShowCursor(); - } - } -} - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -#define CheckItem CheckMenuItem - -/* Menu Constants */ - -#define kAppleMenu 128 -#define kFileMenu 129 -#define kSpecialMenu 130 - -/* Apple */ - -enum { - kAppleNull, - - kAppleAboutItem, - kAppleSep1, - - kNumAppleItems -}; - -/* File */ - -enum { - kFileNull, - - kFileOpenDiskImage, - kFileSep1, - kFileQuitItem, - - kNumFileItems -}; - -/* Special */ - -enum { - kSpecialNull, - - kSpecialMoreCommandsItem, - - kNumSpecialItems -}; - -LOCALPROC DoOpenDA(short menuItem) -{ - Str32 name; - GrafPtr savePort; - - GetPort(&savePort); - GetMenuItemText(GetMenuHandle(kAppleMenu), menuItem, name); - OpenDeskAcc(name); - SystemTask(); - SetPort(savePort); -} - -LOCALPROC MacOS_HandleMenu(short menuID, short menuItem) -{ - switch (menuID) { - case kAppleMenu: - if (kAppleAboutItem == menuItem) { - DoAboutMsg(); - } else { - DoOpenDA(menuItem); - } - break; - - case kFileMenu: - switch (menuItem) { - case kFileOpenDiskImage: - RequestInsertDisk = true; - break; - - case kFileQuitItem: - RequestMacOff = true; - break; - } - break; - - case kSpecialMenu: - switch (menuItem) { - case kSpecialMoreCommandsItem: - DoMoreCommandsMsg(); - break; - } - break; - - default: - /* if 0 == menuID, then no command chosen from menu */ - /* do nothing */ - break; - } -} - -LOCALPROC HandleMacEvent(EventRecord *theEvent) -{ - WindowPtr whichWindow; - GrafPtr savePort; - - switch(theEvent->what) { - case mouseDown: - switch (FindWindow(theEvent->where, &whichWindow)) { - case inSysWindow: - SystemClick(theEvent, whichWindow); - break; - case inMenuBar: - ForceShowCursor(); - { - long menuSelection = - MenuSelect(theEvent->where); - MacOS_HandleMenu(HiWord(menuSelection), - LoWord(menuSelection)); - } - HiliteMenu(0); - break; - - case inDrag: - { - Rect r; - - GetScreenBitsBounds(&r); - DragWindow(whichWindow, theEvent->where, &r); - } - break; - - case inContent: - if (FrontWindow() != whichWindow) { - SelectWindow(whichWindow); - } - if (whichWindow == gMainWindow) { - MousePositionNotifyFromGlobal(theEvent->where); - MouseButtonSet(true); - } - break; - - case inGoAway: - if (TrackGoAway(whichWindow, theEvent->where)) { - RequestMacOff = true; - } - break; - - case inZoomIn: - case inZoomOut: - /* Zoom Boxes */ - break; - } - break; - case mouseUp: - MousePositionNotifyFromGlobal(theEvent->where); - MouseButtonSet(false); - break; - - case updateEvt: - GetPort(&savePort); - BeginUpdate((WindowPtr) theEvent->message); - - if ((WindowPtr)theEvent->message == gMainWindow) { - Update_Screen(); - } - - EndUpdate((WindowPtr) theEvent->message); - SetPort(savePort); - break; - - case keyDown: - case autoKey: - case keyUp: - /* ignore it */ - break; - case osEvt: - if ((theEvent->message >> 24) & suspendResumeMessage) { - if (theEvent->message & 1) { - gTrueBackgroundFlag = false; - } else { - gTrueBackgroundFlag = true; - } - } - break; - case kHighLevelEvent: - if (kCoreEventClass == (AEEventClass)theEvent->message) { - if (/* CheckSysCode */ noErr == - (AEProcessAppleEvent(theEvent))) - { - } - } else { - /* vCheckSysCode(errAENotAppleEvent); */ - } - break; - } -} - -LOCALPROC WaitForTheNextEvent(void) -{ - /* - Wait for the next event - from the operating system, we have nothing better - to do. Call HandleTheEvent and return (only - wait for one event). - */ - - EventRecord theEvent; - - if ( -#if HaveCPUfamM68K - (! HaveWaitNextEventAvail()) ? - GetNextEvent(everyEvent, &theEvent) : -#endif - WaitNextEvent(everyEvent, &theEvent, - (gTrueBackgroundFlag && ! RunInBackground) - ? 5 * 60 * 60 - : 5, - /* - still need to check for - control key when SpeedStopped, - don't get event - */ - NULL)) - { - HandleMacEvent(&theEvent); - } -} - -LOCALPROC DontWaitForEvent(void) -{ - /* we're busy, but see what system wants */ - - EventRecord theEvent; - int i = 0; - -#if 0 /* this seems to cause crashes on some machines */ - if (EventAvail(everyEvent, &theEvent)) { - NoEventsCounter = 0; -#endif - - while (( -#if HaveCPUfamM68K - (! HaveWaitNextEventAvail()) ? - GetNextEvent(everyEvent, &theEvent) : -#endif - WaitNextEvent(everyEvent, &theEvent, 0, NULL)) - && (i < 10)) - { - HandleMacEvent(&theEvent); -#if HogCPU - NoEventsCounter = 0; -#endif - ++i; - } -#if 0 - } -#endif -} - -#define PrivateEventMask \ - (mDownMask | mUpMask | keyDownMask | keyUpMask | autoKeyMask) - -#define IsPowOf2(x) (0 == ((x) & ((x) - 1))) - -LOCALPROC CheckForSystemEvents(void) -{ - /* - Handle any events that are waiting for us. - Return immediately when no more events - are waiting, don't wait for more. - */ - -#if HogCPU && MayFullScreen - /* - only hog cpu in full screen mode - */ - if ( -#if 1 - UseFullScreen && -#endif - ((uint8_t) -1 == SpeedValue) && ! CurSpeedStopped) - { - EventRecord theEvent; - - if (! OSEventAvail(everyEvent, &theEvent)) { - /* - if no OSEvent now, and not looking for aftermath of - event, assume there is no event of any kind we need - to look at - */ - if (NoEventsCounter < 256) { - ++NoEventsCounter; - if (IsPowOf2(NoEventsCounter)) { - DontWaitForEvent(); - } - } - } else { - WindowPtr whichWindow; - - bool PrivateEvent = false; - switch (theEvent.what) { - case keyDown: - case autoKey: - case keyUp: - case mouseUp: - PrivateEvent = true; - break; - case mouseDown: - if ((inContent == - FindWindow(theEvent.where, &whichWindow)) - && (whichWindow == gMainWindow) - && (FrontWindow() == whichWindow)) - { - PrivateEvent = true; - } - break; - } - if (PrivateEvent) { - /* - if event can effect only us, and not looking out - for aftermath of another event, then hog the cpu - */ - if (GetOSEvent(PrivateEventMask, &theEvent)) { - HandleMacEvent(&theEvent); - } - } else { - NoEventsCounter = 0; - /* - Have an Event, so reset NoEventsCounter, no matter - what. WaitNextEvent can return false, even if it did - handle an event. Such as a click in the collapse - box. In this case we need to look out for update - events. - */ - DontWaitForEvent(); - } - } - } else -#endif - { - DontWaitForEvent(); - } - - if (! gBackgroundFlag) { - CheckKeyBoardState(); - } -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ -label_retry: - CheckForSystemEvents(); - CheckForSavedTasks(); - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - WaitForTheNextEvent(); - goto label_retry; - } - - /* - Wait until the end of the current - tick, then emulate the next tick. - */ - - if (ExtraTimeNotOver()) { -#if HaveCPUfamM68K - if (HaveWaitNextEventAvail()) -#endif - { - EventRecord theEvent; - - if (WaitNextEvent(everyEvent, &theEvent, 1, NULL)) { - HandleMacEvent(&theEvent); -#if HogCPU - NoEventsCounter = 0; -#endif - } - } - goto label_retry; - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - if (! (gBackgroundFlag)) { - CheckMouseState(); - } - - OnTrueTime = TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime); -#endif -} - -#include "PROGMAIN.h" - -LOCALPROC AppendMenuCStr(MenuHandle menu, char *s) -{ - Str255 t; - - PStrFromCStr(t, s); - AppendMenu(menu, t); -} - -LOCALPROC AppendMenuConvertCStr(MenuHandle menu, - char *s, bool WantEllipsis) -{ - Str255 t; - - NativeStrFromCStr(t, s, WantEllipsis); - AppendMenu(menu, t); -} - -LOCALPROC AppendMenuSep(MenuHandle menu) -{ - AppendMenuCStr(menu, "(-"); -} - -LOCALFUNC MenuHandle NewMenuFromConvertCStr(short menuID, char *s) -{ - Str255 r; - - NativeStrFromCStr(r, s, false); - return NewMenu(menuID, r); -} - -LOCALFUNC bool InstallOurMenus(void) -{ - MenuHandle menu; - Str255 s; - - PStrFromChar(s, (char)20); - menu = NewMenu(kAppleMenu, s); - if (menu != NULL) { - AppendMenuConvertCStr(menu, - kStrMenuItemAbout, true); - AppendMenuSep(menu); - AppendResMenu(menu, 'DRVR'); - InsertMenu(menu, 0); - } - - menu = NewMenuFromConvertCStr(kFileMenu, kStrMenuFile); - if (menu != NULL) { - AppendMenuConvertCStr(menu, - kStrMenuItemOpen, true); - { - AppendMenuSep(menu); - AppendMenuConvertCStr(menu, - kStrMenuItemQuit, false); - } - InsertMenu(menu, 0); - } - - menu = NewMenuFromConvertCStr(kSpecialMenu, kStrMenuSpecial); - if (menu != NULL) { - AppendMenuConvertCStr(menu, - kStrMenuItemMore, true); - InsertMenu(menu, 0); - } - - DrawMenuBar(); - - return true; -} - -#if AppearanceAvail -LOCALFUNC bool InstallOurAppearanceClient(void) -{ - if (HaveAppearanceAvail()) { - RegisterAppearanceClient(); - } - return true; -} -#endif - -LOCALFUNC bool InstallOurEventHandlers(void) -{ - InitKeyCodes(); - - if (HaveAppleEvtMgrAvail()) { - InstallAppleEventHandlers(); - } - return true; -} - -LOCALPROC ZapOSGLUVars(void) -{ - /* - Set initial values of variables for - platform dependent code, where not - done using c initializers. (such - as for arrays.) - */ - - ZapEmKeys(); - InitDrives(); - ZapWinStateVars(); -} - -LOCALPROC ReserveAllocAll(void) -{ - /* !! must match ChooseTotMemSize in build system !! */ - -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif -#if 1 - ReserveAllocOneBlock(&ScalingBuff, - vMacScreenNumBytes * (ScaleBuffSzMult), 5, false); - ReserveAllocOneBlock(&ScalingTabl, - ScalingTablsz, 5, false); -#endif -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)NewPtr(n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALFUNC bool InitOSGLU(void) -{ - /* - run all the initializations - needed for the program. - */ - - if (InitMacManagers()) - if (AllocMemory()) - if (InitApplInfo()) -#if dbglog_HAVE - if (dbglog_open()) -#endif -#if AppearanceAvail - if (InstallOurAppearanceClient()) -#endif - if (InstallOurEventHandlers()) - if (InstallOurMenus()) -#if SoundEnabled - if (Sound_Init()) -#endif - if (ReCreateMainWindow()) - if (LoadMacRom()) - if (LoadInitialImages()) - if (InitLocationDat()) - if (WaitForRom()) - { - return true; - } - return false; -} - -LOCALPROC UnInitOSGLU(void) -{ - /* - Do all clean ups needed - before the program quits. - */ - - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - -#if MayFullScreen - UngrabMachine(); -#endif - -#if SoundEnabled - Sound_Stop(); -#endif - - CloseMainWindow(); - -#if MayFullScreen - _ShowMenuBar(); -#endif - -#if IncludePbufs - UnInitPbufs(); -#endif - UnInitDrives(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - ForceShowCursor(); - - if (! gTrueBackgroundFlag) { - CheckSavedMacMsg(); - } -} - -#ifndef MainReturnsInt -#define MainReturnsInt 0 -#endif - -#ifndef NeedLongGlue -#define NeedLongGlue 0 -#endif - -#if NeedLongGlue -#define main long_main -#endif - -#if MainReturnsInt -int -#else -void -#endif -main(void) -{ - ZapOSGLUVars(); - if (InitOSGLU()) { - ProgramMain(); - } - UnInitOSGLU(); - -#if MainReturnsInt - return 0; -#endif -} diff --git a/src/UI/_deprecated/OLDMAC/main.r b/src/UI/_deprecated/OLDMAC/main.r deleted file mode 100644 index 253b478..0000000 --- a/src/UI/_deprecated/OLDMAC/main.r +++ /dev/null @@ -1,55 +0,0 @@ -/* - main.r - - Copyright (C) 2003 Philip Cummins, Richard F. Bannister, - Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -#include "CNFGRSRC.h" - -/* Alerts Constants */ - -#define kStandardAlert 128 - -resource 'DITL' (kStandardAlert, purgeable) { - { /* array DITLarray: 2 elements */ - /* [1] */ - {177, 293, 197, 351}, - Button { - enabled, - "OK" - }, - /* [2] */ - {10, 72, 162, 353}, - StaticText { - disabled, - "^0\n\n^1^2^3" - } - } -}; - -resource 'ALRT' (kStandardAlert, "Non Fatal Error", purgeable) { - {40, 43, 249, 405}, - kStandardAlert, - { /* array: 4 elements */ - /* [1] */ - OK, visible, sound1, - /* [2] */ - OK, visible, sound1, - /* [3] */ - OK, visible, sound1, - /* [4] */ - OK, visible, sound1 - }, - alertPositionMainScreen -}; diff --git a/src/UI/_deprecated/README.md b/src/UI/_deprecated/README.md deleted file mode 100644 index 66ef455..0000000 --- a/src/UI/_deprecated/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Deprecated targets - -Targets that I'm not in a position to maintain right now. Perhaps they'll come -back from the dead one day. (MACOSX especially; I don't own any computer that -runs that at the moment...) - -Do not expect any of these targets to build. - -- `MACOSX`: macOS / Mac OS X -- `NDS`: Nintendo DS -- `OLDMAC`: Classic Mac OS -- `UNIX`: raw X11 -- `XPLAT/OSGLUGTK.c`: GTK (Linux) -- `XPLAT/OSGLUSDL.c`: SDL 1.2 (or lower?); might be useful for archaic systems - -While compatibility with old/esoteric operating systems is neat, the primary -focus will be on SDL2 moving forwards. diff --git a/src/UI/_deprecated/UNIX/OSGLUXWN.c b/src/UI/_deprecated/UNIX/OSGLUXWN.c deleted file mode 100644 index ee0cc36..0000000 --- a/src/UI/_deprecated/UNIX/OSGLUXWN.c +++ /dev/null @@ -1,4753 +0,0 @@ -/* - OSGLUXWN.c - - Copyright (C) 2009 Michael Hanni, Christian Bauer, - Stephan Kochen, Paul C. Pratt, and others - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for X WiNdow system - - All operating system dependent code for the - X Window System should go here. - - This code is descended from Michael Hanni's X - port of vMac, by Philip Cummins. - I learned more about how X programs work by - looking at other programs such as Basilisk II, - the UAE Amiga Emulator, Bochs, QuakeForge, - DooM Legacy, and the FLTK. A few snippets - from them are used here. - - Drag and Drop support is based on the specification - "XDND: Drag-and-Drop Protocol for the X Window System" - developed by John Lindal at New Planet Software, and - looking at included examples, one by Paul Sheer. -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "CNFGGLOB.h" -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" -#include "UI/MYOSGLUE.h" -#include "STRCONST.h" - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memcpy((char *)destPtr, (char *)srcPtr, byteCount); -} - -/* --- control mode and internationalization --- */ - -#define NeedCell2PlainAsciiMap 1 - -#include "LANG/INTLCHAR.h" - - -LOCALVAR char *d_arg = NULL; -LOCALVAR char *n_arg = NULL; - -#ifdef CanGetAppPath -LOCALVAR char *app_parent = NULL; -LOCALVAR char *app_name = NULL; -#endif - -LOCALFUNC MacErr_t ChildPath(char *x, char *y, char **r) -{ - MacErr_t err = mnvm_miscErr; - int nx = strlen(x); - int ny = strlen(y); - { - if ((nx > 0) && ('/' == x[nx - 1])) { - --nx; - } - { - int nr = nx + 1 + ny; - char *p = malloc(nr + 1); - if (p != NULL) { - char *p2 = p; - (void) memcpy(p2, x, nx); - p2 += nx; - *p2++ = '/'; - (void) memcpy(p2, y, ny); - p2 += ny; - *p2 = 0; - *r = p; - err = mnvm_noErr; - } - } - } - - return err; -} - -#if IncludeSonyNew -LOCALFUNC MacErr_t FindOrMakeChild(char *x, char *y, char **r) -{ - MacErr_t err; - struct stat folder_info; - char *r0; - - if (mnvm_noErr == (err = ChildPath(x, y, &r0))) { - if (0 != stat(r0, &folder_info)) { - if (0 != mkdir(r0, S_IRWXU)) { - err = mnvm_miscErr; - } else { - *r = r0; - err = mnvm_noErr; - } - } else { - if (! S_ISDIR(folder_info.st_mode)) { - err = mnvm_miscErr; - } else { - *r = r0; - err = mnvm_noErr; - } - } - } - - return err; -} -#endif - -LOCALPROC MayFree(char *p) -{ - if (NULL != p) { - free(p); - } -} - -/* --- sending debugging info to file --- */ - -#if dbglog_HAVE - -#define dbglog_ToStdErr 0 - -#if ! dbglog_ToStdErr -LOCALVAR FILE *dbglog_File = NULL; -#endif - -LOCALFUNC bool dbglog_open0(void) -{ -#if dbglog_ToStdErr - return true; -#else - dbglog_File = fopen("dbglog.txt", "w"); - return (NULL != dbglog_File); -#endif -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ -#if dbglog_ToStdErr - (void) fwrite(s, 1, L, stderr); -#else - if (dbglog_File != NULL) { - (void) fwrite(s, 1, L, dbglog_File); - } -#endif -} - -LOCALPROC dbglog_close0(void) -{ -#if ! dbglog_ToStdErr - if (dbglog_File != NULL) { - fclose(dbglog_File); - dbglog_File = NULL; - } -#endif -} - -#endif - -/* --- debug settings and utilities --- */ - -#if ! dbglog_HAVE -#define WriteExtraErr(s) -#else -LOCALPROC WriteExtraErr(char *s) -{ - dbglog_writeCStr("*** error: "); - dbglog_writeCStr(s); - dbglog_writeReturn(); -} -#endif - -LOCALVAR Display *x_display = NULL; - -#define DbgEvents (dbglog_HAVE && 0) - -#if DbgEvents -LOCALPROC WriteDbgAtom(char *s, Atom x) -{ - char *name = XGetAtomName(x_display, x); - if (name != NULL) { - dbglog_writeCStr("Atom "); - dbglog_writeCStr(s); - dbglog_writeCStr(": "); - dbglog_writeCStr(name); - dbglog_writeReturn(); - XFree(name); - } -} -#endif - -/* --- information about the environment --- */ - -LOCALVAR Atom XA_DeleteW = (Atom)0; -#if EnableDragDrop -LOCALVAR Atom XA_UriList = (Atom)0; -LOCALVAR Atom XA_DndAware = (Atom)0; -LOCALVAR Atom XA_DndEnter = (Atom)0; -LOCALVAR Atom XA_DndLeave = (Atom)0; -LOCALVAR Atom XA_DndDrop = (Atom)0; -LOCALVAR Atom XA_DndPosition = (Atom)0; -LOCALVAR Atom XA_DndStatus = (Atom)0; -LOCALVAR Atom XA_DndActionCopy = (Atom)0; -LOCALVAR Atom XA_DndActionPrivate = (Atom)0; -LOCALVAR Atom XA_DndSelection = (Atom)0; -LOCALVAR Atom XA_DndFinished = (Atom)0; -LOCALVAR Atom XA_MinivMac_DndXchng = (Atom)0; -LOCALVAR Atom XA_NetActiveWindow = (Atom)0; -LOCALVAR Atom XA_NetSupported = (Atom)0; -#endif -#if IncludeHostTextClipExchange -LOCALVAR Atom XA_CLIPBOARD = (Atom)0; -LOCALVAR Atom XA_TARGETS = (Atom)0; -LOCALVAR Atom XA_MinivMac_Clip = (Atom)0; -#endif - -LOCALPROC LoadXA(void) -{ - XA_DeleteW = XInternAtom(x_display, "WM_DELETE_WINDOW", False); -#if EnableDragDrop - XA_UriList = XInternAtom (x_display, "text/uri-list", False); - XA_DndAware = XInternAtom (x_display, "XdndAware", False); - XA_DndEnter = XInternAtom(x_display, "XdndEnter", False); - XA_DndLeave = XInternAtom(x_display, "XdndLeave", False); - XA_DndDrop = XInternAtom(x_display, "XdndDrop", False); - XA_DndPosition = XInternAtom(x_display, "XdndPosition", False); - XA_DndStatus = XInternAtom(x_display, "XdndStatus", False); - XA_DndActionCopy = XInternAtom(x_display, - "XdndActionCopy", False); - XA_DndActionPrivate = XInternAtom(x_display, - "XdndActionPrivate", False); - XA_DndSelection = XInternAtom(x_display, "XdndSelection", False); - XA_DndFinished = XInternAtom(x_display, "XdndFinished", False); - XA_MinivMac_DndXchng = XInternAtom(x_display, - "_MinivMac_DndXchng", False); - XA_NetActiveWindow = XInternAtom(x_display, - "_NET_ACTIVE_WINDOW", False); - XA_NetSupported = XInternAtom(x_display, - "_NET_SUPPORTED", False); -#endif -#if IncludeHostTextClipExchange - XA_CLIPBOARD = XInternAtom(x_display, "CLIPBOARD", False); - XA_TARGETS = XInternAtom(x_display, "TARGETS", False); - XA_MinivMac_Clip = XInternAtom(x_display, - "_MinivMac_Clip", False); -#endif -} - -#if EnableDragDrop -LOCALFUNC bool NetSupportedContains(Atom x) -{ - /* - Note that the window manager could be replaced at - any time, so don't cache results of this function. - */ - Atom ret_type; - int ret_format; - unsigned long ret_item; - unsigned long remain_byte; - unsigned long i; - unsigned char *s = 0; - bool foundit = false; - Window rootwin = XRootWindow(x_display, - DefaultScreen(x_display)); - - if (Success != XGetWindowProperty(x_display, rootwin, - XA_NetSupported, - 0, 65535, False, XA_ATOM, &ret_type, &ret_format, - &ret_item, &remain_byte, &s)) - { - WriteExtraErr("XGetWindowProperty failed"); - } else if (! s) { - WriteExtraErr("XGetWindowProperty failed"); - } else if (ret_type != XA_ATOM) { - WriteExtraErr("XGetWindowProperty returns wrong type"); - } else { - Atom *v = (Atom *)s; - - for (i = 0; i < ret_item; ++i) { - if (v[i] == x) { - foundit = true; - /* fprintf(stderr, "found the hint\n"); */ - } - } - } - if (s) { - XFree(s); - } - return foundit; -} -#endif - -#define WantColorTransValid 1 - -#include "UI/COMOSGLU.h" -#include "UTIL/PBUFSTDC.h" -#include "UI/CONTROLM.h" - -/* --- text translation --- */ - -#if IncludePbufs -/* this is table for Windows, any changes needed for X? */ -LOCALVAR const uint8_t Native2MacRomanTab[] = { - 0xAD, 0xB0, 0xE2, 0xC4, 0xE3, 0xC9, 0xA0, 0xE0, - 0xF6, 0xE4, 0xB6, 0xDC, 0xCE, 0xB2, 0xB3, 0xB7, - 0xB8, 0xD4, 0xD5, 0xD2, 0xD3, 0xA5, 0xD0, 0xD1, - 0xF7, 0xAA, 0xC5, 0xDD, 0xCF, 0xB9, 0xC3, 0xD9, - 0xCA, 0xC1, 0xA2, 0xA3, 0xDB, 0xB4, 0xBA, 0xA4, - 0xAC, 0xA9, 0xBB, 0xC7, 0xC2, 0xBD, 0xA8, 0xF8, - 0xA1, 0xB1, 0xC6, 0xD7, 0xAB, 0xB5, 0xA6, 0xE1, - 0xFC, 0xDA, 0xBC, 0xC8, 0xDE, 0xDF, 0xF0, 0xC0, - 0xCB, 0xE7, 0xE5, 0xCC, 0x80, 0x81, 0xAE, 0x82, - 0xE9, 0x83, 0xE6, 0xE8, 0xED, 0xEA, 0xEB, 0xEC, - 0xF5, 0x84, 0xF1, 0xEE, 0xEF, 0xCD, 0x85, 0xF9, - 0xAF, 0xF4, 0xF2, 0xF3, 0x86, 0xFA, 0xFB, 0xA7, - 0x88, 0x87, 0x89, 0x8B, 0x8A, 0x8C, 0xBE, 0x8D, - 0x8F, 0x8E, 0x90, 0x91, 0x93, 0x92, 0x94, 0x95, - 0xFD, 0x96, 0x98, 0x97, 0x99, 0x9B, 0x9A, 0xD6, - 0xBF, 0x9D, 0x9C, 0x9E, 0x9F, 0xFE, 0xFF, 0xD8 -}; -#endif - -#if IncludePbufs -LOCALFUNC MacErr_t NativeTextToMacRomanPbuf(char *x, tPbuf *r) -{ - if (NULL == x) { - return mnvm_miscErr; - } else { - uint8_t * p; - uint32_t L = strlen(x); - - p = (uint8_t *)malloc(L); - if (NULL == p) { - return mnvm_miscErr; - } else { - uint8_t *p0 = (uint8_t *)x; - uint8_t *p1 = (uint8_t *)p; - int i; - - for (i = L; --i >= 0; ) { - uint8_t v = *p0++; - if (v >= 128) { - v = Native2MacRomanTab[v - 128]; - } else if (10 == v) { - v = 13; - } - *p1++ = v; - } - - return PbufNewFromPtr(p, L, r); - } - } -} -#endif - -#if IncludePbufs -/* this is table for Windows, any changes needed for X? */ -LOCALVAR const uint8_t MacRoman2NativeTab[] = { - 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, - 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, - 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, - 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, - 0x86, 0xB0, 0xA2, 0xA3, 0xA7, 0x95, 0xB6, 0xDF, - 0xAE, 0xA9, 0x99, 0xB4, 0xA8, 0x80, 0xC6, 0xD8, - 0x81, 0xB1, 0x8D, 0x8E, 0xA5, 0xB5, 0x8A, 0x8F, - 0x90, 0x9D, 0xA6, 0xAA, 0xBA, 0xAD, 0xE6, 0xF8, - 0xBF, 0xA1, 0xAC, 0x9E, 0x83, 0x9A, 0xB2, 0xAB, - 0xBB, 0x85, 0xA0, 0xC0, 0xC3, 0xD5, 0x8C, 0x9C, - 0x96, 0x97, 0x93, 0x94, 0x91, 0x92, 0xF7, 0xB3, - 0xFF, 0x9F, 0xB9, 0xA4, 0x8B, 0x9B, 0xBC, 0xBD, - 0x87, 0xB7, 0x82, 0x84, 0x89, 0xC2, 0xCA, 0xC1, - 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, - 0xBE, 0xD2, 0xDA, 0xDB, 0xD9, 0xD0, 0x88, 0x98, - 0xAF, 0xD7, 0xDD, 0xDE, 0xB8, 0xF0, 0xFD, 0xFE -}; -#endif - -#if IncludePbufs -LOCALFUNC bool MacRomanTextToNativePtr(tPbuf i, bool IsFileName, - uint8_t * *r) -{ - uint8_t * p; - void *Buffer = PbufDat[i]; - uint32_t L = PbufSize[i]; - - p = (uint8_t *)malloc(L + 1); - if (p != NULL) { - uint8_t *p0 = (uint8_t *)Buffer; - uint8_t *p1 = (uint8_t *)p; - int j; - - if (IsFileName) { - for (j = L; --j >= 0; ) { - uint8_t x = *p0++; - if (x < 32) { - x = '-'; - } else if (x >= 128) { - x = MacRoman2NativeTab[x - 128]; - } else { - switch (x) { - case '/': - case '<': - case '>': - case '|': - case ':': - x = '-'; - default: - break; - } - } - *p1++ = x; - } - if ('.' == p[0]) { - p[0] = '-'; - } - } else { - for (j = L; --j >= 0; ) { - uint8_t x = *p0++; - if (x >= 128) { - x = MacRoman2NativeTab[x - 128]; - } else if (13 == x) { - x = '\n'; - } - *p1++ = x; - } - } - *p1 = 0; - - *r = p; - return true; - } - return false; -} -#endif - -LOCALPROC NativeStrFromCStr(char *r, char *s) -{ - uint8_t ps[ClStrMaxLength]; - int i; - int L; - - ClStrFromSubstCStr(&L, ps, s); - - for (i = 0; i < L; ++i) { - r[i] = Cell2PlainAsciiMap[ps[i]]; - } - - r[L] = 0; -} - -/* --- drives --- */ - -#define NotAfileRef NULL - -LOCALVAR FILE *Drives[NumDrives]; /* open disk image files */ -#if IncludeSonyGetName || IncludeSonyNew -LOCALVAR char *DriveNames[NumDrives]; -#endif - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; -#if IncludeSonyGetName || IncludeSonyNew - DriveNames[i] = NULL; -#endif - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - uint32_t NewSony_Count = 0; - - if (0 == fseek(refnum, Sony_Start, SEEK_SET)) { - if (IsWrite) { - NewSony_Count = fwrite(Buffer, 1, Sony_Count, refnum); - } else { - NewSony_Count = fread(Buffer, 1, Sony_Count, refnum); - } - - if (NewSony_Count == Sony_Count) { - err = mnvm_noErr; - } - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = NewSony_Count; - } - - return err; /*& figure out what really to return &*/ -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - long v; - - if (0 == fseek(refnum, 0, SEEK_END)) { - v = ftell(refnum); - if (v >= 0) { - *Sony_Count = v; - err = mnvm_noErr; - } - } - - return err; /*& figure out what really to return &*/ -} - -#ifndef HaveAdvisoryLocks -#define HaveAdvisoryLocks 1 -#endif - -/* - What is the difference between fcntl(fd, F_SETLK ... - and flock(fd ... ? -*/ - -#if HaveAdvisoryLocks -LOCALFUNC bool LockFile(FILE *refnum) -{ - bool IsOk = false; - -#if 1 - struct flock fl; - int fd = fileno(refnum); - - fl.l_start = 0; /* starting offset */ - fl.l_len = 0; /* len = 0 means until end of file */ - /* fl.pid_t l_pid; */ /* lock owner, don't need to set */ - fl.l_type = F_WRLCK; /* lock type: read/write, etc. */ - fl.l_whence = SEEK_SET; /* type of l_start */ - if (-1 == fcntl(fd, F_SETLK, &fl)) { - MacMsg(kStrImageInUseTitle, kStrImageInUseMessage, - false); - } else { - IsOk = true; - } -#else - int fd = fileno(refnum); - - if (-1 == flock(fd, LOCK_EX | LOCK_NB)) { - MacMsg(kStrImageInUseTitle, kStrImageInUseMessage, - false); - } else { - IsOk = true; - } -#endif - - return IsOk; -} -#endif - -#if HaveAdvisoryLocks -LOCALPROC UnlockFile(FILE *refnum) -{ -#if 1 - struct flock fl; - int fd = fileno(refnum); - - fl.l_start = 0; /* starting offset */ - fl.l_len = 0; /* len = 0 means until end of file */ - /* fl.pid_t l_pid; */ /* lock owner, don't need to set */ - fl.l_type = F_UNLCK; /* lock type: read/write, etc. */ - fl.l_whence = SEEK_SET; /* type of l_start */ - if (-1 == fcntl(fd, F_SETLK, &fl)) { - /* an error occurred */ - } -#else - int fd = fileno(refnum); - - if (-1 == flock(fd, LOCK_UN)) { - } -#endif -} -#endif - -LOCALFUNC MacErr_t vSonyEject0(tDrive Drive_No, bool deleteit) -{ - FILE *refnum = Drives[Drive_No]; - - DiskEjectedNotify(Drive_No); - -#if HaveAdvisoryLocks - UnlockFile(refnum); -#endif - - fclose(refnum); - Drives[Drive_No] = NotAfileRef; /* not really needed */ - -#if IncludeSonyGetName || IncludeSonyNew - { - char *s = DriveNames[Drive_No]; - if (NULL != s) { - if (deleteit) { - remove(s); - } - free(s); - DriveNames[Drive_No] = NULL; /* not really needed */ - } - } -#endif - - return mnvm_noErr; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, false); -} - -#if IncludeSonyNew -GLOBALOSGLUFUNC MacErr_t vSonyEjectDelete(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, true); -} -#endif - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -#if IncludeSonyGetName -GLOBALOSGLUFUNC MacErr_t vSonyGetName(tDrive Drive_No, tPbuf *r) -{ - char *drivepath = DriveNames[Drive_No]; - if (NULL == drivepath) { - return mnvm_miscErr; - } else { - char *s = strrchr(drivepath, '/'); - if (NULL == s) { - s = drivepath; - } else { - ++s; - } - return NativeTextToMacRomanPbuf(s, r); - } -} -#endif - -LOCALFUNC bool Sony_Insert0(FILE *refnum, bool locked, - char *drivepath) -{ - tDrive Drive_No; - bool IsOk = false; - - if (! FirstFreeDisk(&Drive_No)) { - MacMsg(kStrTooManyImagesTitle, kStrTooManyImagesMessage, - false); - } else { - /* printf("Sony_Insert0 %d\n", (int)Drive_No); */ - -#if HaveAdvisoryLocks - if (locked || LockFile(refnum)) -#endif - { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); - -#if IncludeSonyGetName || IncludeSonyNew - { - uint32_t L = strlen(drivepath); - char *p = malloc(L + 1); - if (p != NULL) { - (void) memcpy(p, drivepath, L + 1); - } - DriveNames[Drive_No] = p; - } -#endif - - IsOk = true; - } - } - - if (! IsOk) { - fclose(refnum); - } - - return IsOk; -} - -LOCALFUNC bool Sony_Insert1(char *drivepath, bool silentfail) -{ - bool locked = false; - /* printf("Sony_Insert1 %s\n", drivepath); */ - FILE *refnum = fopen(drivepath, "rb+"); - if (NULL == refnum) { - locked = true; - refnum = fopen(drivepath, "rb"); - } - if (NULL == refnum) { - if (! silentfail) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } else { - return Sony_Insert0(refnum, locked, drivepath); - } - return false; -} - -LOCALFUNC MacErr_t LoadMacRomFrom(char *path) -{ - MacErr_t err; - FILE *ROM_File; - int File_Size; - - ROM_File = fopen(path, "rb"); - if (NULL == ROM_File) { - err = mnvm_fnfErr; - } else { - File_Size = fread(ROM, 1, kROM_Size, ROM_File); - if (kROM_Size != File_Size) { - if (feof(ROM_File)) { - MacMsgOverride(kStrShortROMTitle, - kStrShortROMMessage); - err = mnvm_eofErr; - } else { - MacMsgOverride(kStrNoReadROMTitle, - kStrNoReadROMMessage); - err = mnvm_miscErr; - } - } else { - err = ROM_IsValid(); - } - fclose(ROM_File); - } - - return err; -} - -LOCALFUNC bool Sony_Insert1a(char *drivepath, bool silentfail) -{ - bool v; - - if (! ROM_loaded) { - v = (mnvm_noErr == LoadMacRomFrom(drivepath)); - } else { - v = Sony_Insert1(drivepath, silentfail); - } - - return v; -} - -LOCALFUNC bool Sony_Insert2(char *s) -{ - char *d = -#ifdef CanGetAppPath - (NULL == d_arg) ? app_parent : -#endif - d_arg; - bool IsOk = false; - - if (NULL == d) { - IsOk = Sony_Insert1(s, true); - } else { - char *t; - - if (mnvm_noErr == ChildPath(d, s, &t)) { - IsOk = Sony_Insert1(t, true); - free(t); - } - } - - return IsOk; -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - bool v; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - v = false; - } else { - char s[] = "disk?.dsk"; - - s[4] = '0' + i; - - v = Sony_Insert2(s); - } - - return v; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - if (! AnyDiskInserted()) { - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - } - - return true; -} - -#if IncludeSonyNew -LOCALFUNC bool WriteZero(FILE *refnum, uint32_t L) -{ -#define ZeroBufferSize 2048 - uint32_t i; - uint8_t buffer[ZeroBufferSize]; - - memset(&buffer, 0, ZeroBufferSize); - - while (L > 0) { - i = (L > ZeroBufferSize) ? ZeroBufferSize : L; - if (fwrite(buffer, 1, i, refnum) != i) { - return false; - } - L -= i; - } - return true; -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDisk0(uint32_t L, char *drivepath) -{ - bool IsOk = false; - FILE *refnum = fopen(drivepath, "wb+"); - if (NULL == refnum) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } else { - if (WriteZero(refnum, L)) { - IsOk = Sony_Insert0(refnum, false, drivepath); - refnum = NULL; - } - if (refnum != NULL) { - fclose(refnum); - } - if (! IsOk) { - (void) remove(drivepath); - } - } -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDisk(uint32_t L, char *drivename) -{ - char *d = -#ifdef CanGetAppPath - (NULL == d_arg) ? app_parent : -#endif - d_arg; - - if (NULL == d) { - MakeNewDisk0(L, drivename); /* in current directory */ - } else { - MacErr_t err; - char *t = NULL; - char *t2 = NULL; - - if (mnvm_noErr == (err = FindOrMakeChild(d, "out", &t))) - if (mnvm_noErr == (err = ChildPath(t, drivename, &t2))) - { - MakeNewDisk0(L, t2); - } - - MayFree(t2); - MayFree(t); - } -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDiskAtDefault(uint32_t L) -{ - char s[ClStrMaxLength + 1]; - - NativeStrFromCStr(s, "untitled.dsk"); - MakeNewDisk(L, s); -} -#endif - -/* --- ROM --- */ - -LOCALVAR char *rom_path = NULL; - -#if 0 -#include -#include -#endif - -LOCALFUNC MacErr_t FindUserHomeFolder(char **r) -{ - MacErr_t err; - char *s; -#if 0 - struct passwd *user; -#endif - - if (NULL != (s = getenv("HOME"))) { - *r = s; - err = mnvm_noErr; - } else -#if 0 - if ((NULL != (user = getpwuid(getuid()))) - && (NULL != (s = user->pw_dir))) - { - /* - From getpwuid man page: - "An application that wants to determine its user's - home directory should inspect the value of HOME - (rather than the value getpwuid(getuid())->pw_dir) - since this allows the user to modify their notion of - "the home directory" during a login session." - - But it is possible for HOME to not be set. - Some sources say to use getpwuid in that case. - */ - *r = s; - err = mnvm_noErr; - } else -#endif - { - err = mnvm_fnfErr; - } - - return err; -} - -LOCALFUNC MacErr_t LoadMacRomFromHome(void) -{ - MacErr_t err; - char *s; - char *t = NULL; - char *t2 = NULL; - char *t3 = NULL; - - if (mnvm_noErr == (err = FindUserHomeFolder(&s))) - if (mnvm_noErr == (err = ChildPath(s, ".gryphel", &t))) - if (mnvm_noErr == (err = ChildPath(t, "mnvm_rom", &t2))) - if (mnvm_noErr == (err = ChildPath(t2, RomFileName, &t3))) - { - err = LoadMacRomFrom(t3); - } - - MayFree(t3); - MayFree(t2); - MayFree(t); - - return err; -} - -#ifdef CanGetAppPath -LOCALFUNC MacErr_t LoadMacRomFromAppPar(void) -{ - MacErr_t err; - char *d = -#ifdef CanGetAppPath - (NULL == d_arg) ? app_parent : -#endif - d_arg; - char *t = NULL; - - if (NULL == d) { - err = mnvm_fnfErr; - } else { - if (mnvm_noErr == (err = ChildPath(d, RomFileName, - &t))) - { - err = LoadMacRomFrom(t); - } - } - - MayFree(t); - - return err; -} -#endif - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if ((NULL == rom_path) - || (mnvm_fnfErr == (err = LoadMacRomFrom(rom_path)))) -#ifdef CanGetAppPath - if (mnvm_fnfErr == (err = LoadMacRomFromAppPar())) -#endif - if (mnvm_fnfErr == (err = LoadMacRomFromHome())) - if (mnvm_fnfErr == (err = LoadMacRomFrom(RomFileName))) - { - } - - return true; /* keep launching Mini vMac, regardless */ -} - -/* --- video out --- */ - -LOCALVAR Window main_wind = 0; -LOCALVAR GC gc = NULL; -LOCALVAR bool NeedFinishOpen1 = false; -LOCALVAR bool NeedFinishOpen2 = false; - -LOCALVAR XColor x_black; -LOCALVAR XColor x_white; - -#if MayFullScreen -LOCALVAR short hOffset; -LOCALVAR short vOffset; -#endif - -#if 1 -LOCALVAR bool UseFullScreen = (WantInitFullScreen != 0); -#endif - -#if 1 -LOCALVAR bool UseMagnify = (WantInitMagnify != 0); -#endif - -LOCALVAR bool gBackgroundFlag = false; -LOCALVAR bool gTrueBackgroundFlag = false; -LOCALVAR bool CurSpeedStopped = true; - -#ifndef UseColorImage -#define UseColorImage (0 != vMacScreenDepth) -#endif - -LOCALVAR XImage *image = NULL; - -#if 1 -LOCALVAR XImage *Scaled_image = NULL; -#endif - -#if 1 -#define MaxScale WindowScale -#else -#define MaxScale 1 -#endif - -#define WantScalingTabl (1 || UseColorImage) - -#if WantScalingTabl - -LOCALVAR uint8_t * ScalingTabl = nullpr; - -#define ScalingTablsz1 (256 * MaxScale) - -#if UseColorImage -#define ScalingTablsz (ScalingTablsz1 << 5) -#else -#define ScalingTablsz ScalingTablsz1 -#endif - -#endif /* WantScalingTabl */ - - -#define WantScalingBuff (1 || UseColorImage) - -#if WantScalingBuff - -LOCALVAR uint8_t * ScalingBuff = nullpr; - - -#if UseColorImage -#define ScalingBuffsz \ - (vMacScreenNumPixels * 4 * MaxScale * MaxScale) -#else -#define ScalingBuffsz ((long)vMacScreenMonoNumBytes \ - * MaxScale * MaxScale) -#endif - -#endif /* WantScalingBuff */ - - -#if 1 && ! UseColorImage -LOCALPROC SetUpScalingTabl(void) -{ - uint8_t *p4; - int i; - int j; - int k; - uint8_t bitsRemaining; - uint8_t t1; - uint8_t t2; - - p4 = ScalingTabl; - for (i = 0; i < 256; ++i) { - bitsRemaining = 8; - t2 = 0; - for (j = 8; --j >= 0; ) { - t1 = (i >> j) & 1; - for (k = WindowScale; --k >= 0; ) { - t2 = (t2 << 1) | t1; - if (--bitsRemaining == 0) { - *p4++ = t2; - bitsRemaining = 8; - t2 = 0; - } - } - } - } -} -#endif - -//#if 1 && (0 != vMacScreenDepth) && (vMacScreenDepth < 4) -LOCALPROC SetUpColorScalingTabl(void) -{ - int i; - int j; - int k; - int a; - uint32_t v; - uint32_t * p4; - - p4 = (uint32_t *)ScalingTabl; - for (i = 0; i < 256; ++i) { - for (k = 1 << (3 - vMacScreenDepth); --k >= 0; ) { - j = (i >> (k << vMacScreenDepth)) & (CLUT_size - 1); - v = (((long)CLUT_reds[j] & 0xFF00) << 8) - | ((long)CLUT_greens[j] & 0xFF00) - | (((long)CLUT_blues[j] & 0xFF00) >> 8); - for (a = WindowScale; --a >= 0; ) { - *p4++ = v; - } - } - } -} - -//#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) -LOCALPROC SetUpColorTabl(void) -{ - int i; - int j; - int k; - uint32_t * p4; - - p4 = (uint32_t *)ScalingTabl; - for (i = 0; i < 256; ++i) { - for (k = 1 << (3 - vMacScreenDepth); --k >= 0; ) { - j = (i >> (k << vMacScreenDepth)) & (CLUT_size - 1); - *p4++ = (((long)CLUT_reds[j] & 0xFF00) << 8) - | ((long)CLUT_greens[j] & 0xFF00) - | (((long)CLUT_blues[j] & 0xFF00) >> 8); - } - } -} - -//#if 1 && UseColorImage -LOCALPROC SetUpBW2ColorScalingTabl(void) -{ - int i; - int k; - int a; - uint32_t v; - uint32_t * p4; - - p4 = (uint32_t *)ScalingTabl; - for (i = 0; i < 256; ++i) { - for (k = 8; --k >= 0; ) { - if (0 != ((i >> k) & 1)) { - v = 0; - } else { - v = 0xFFFFFF; - } - - for (a = WindowScale; --a >= 0; ) { - *p4++ = v; - } - } - } -} - -//#if UseColorImage -LOCALPROC SetUpBW2ColorTabl(void) -{ - int i; - int k; - uint32_t v; - uint32_t * p4; - - p4 = (uint32_t *)ScalingTabl; - for (i = 0; i < 256; ++i) { - for (k = 8; --k >= 0; ) { - if (0 != ((i >> k) & 1)) { - v = 0; - } else { - v = 0xFFFFFF; - } - *p4++ = v; - } - } -} - - -#if 1 && ! UseColorImage - -#define ScrnMapr_DoMap UpdateScaledBWCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 0 -#define ScrnMapr_Map ScalingTabl -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - - -#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - -#define ScrnMapr_DoMap UpdateMappedColorCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map ScalingTabl - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - - -#if 1 && (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - -#define ScrnMapr_DoMap UpdateMappedScaledColorCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map ScalingTabl -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - - -#if vMacScreenDepth >= 4 - -#define ScrnTrns_DoTrans UpdateTransColorCopy -#define ScrnTrns_Src GetCurDrawBuff() -#define ScrnTrns_Dst ScalingBuff -#define ScrnTrns_SrcDepth vMacScreenDepth -#define ScrnTrns_DstDepth 5 - -#include "HW/SCREEN/SCRNTRNS.h" - -#endif - -#if 1 && (vMacScreenDepth >= 4) - -#define ScrnTrns_DoTrans UpdateTransScaledColorCopy -#define ScrnTrns_Src GetCurDrawBuff() -#define ScrnTrns_Dst ScalingBuff -#define ScrnTrns_SrcDepth vMacScreenDepth -#define ScrnTrns_DstDepth 5 -#define ScrnTrns_Scale WindowScale - -#include "HW/SCREEN/SCRNTRNS.h" - -#endif - - -#if 1 && UseColorImage - -#define ScrnMapr_DoMap UpdateMappedScaledBW2ColorCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map ScalingTabl -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - - -#if UseColorImage - -#define ScrnMapr_DoMap UpdateMappedBW2ColorCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map ScalingTabl - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - - -LOCALPROC HaveChangedScreenBuff(uint16_t top, uint16_t left, - uint16_t bottom, uint16_t right) -{ - int XDest; - int YDest; - char *the_data; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - if (top < ViewVStart) { - top = ViewVStart; - } - if (left < ViewHStart) { - left = ViewHStart; - } - if (bottom > ViewVStart + ViewVSize) { - bottom = ViewVStart + ViewVSize; - } - if (right > ViewHStart + ViewHSize) { - right = ViewHStart + ViewHSize; - } - - if ((top >= bottom) || (left >= right)) { - goto label_exit; - } - } -#endif - - XDest = left; - YDest = top; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - XDest -= ViewHStart; - YDest -= ViewVStart; - } -#endif - -#if 1 - if (UseMagnify) { - XDest *= WindowScale; - YDest *= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - XDest += hOffset; - YDest += vOffset; - } -#endif - -#if 1 - if (UseMagnify) { -#if UseColorImage -#if 0 != vMacScreenDepth - if (UseColorMode) { -#if vMacScreenDepth < 4 - if (! ColorTransValid) { - SetUpColorScalingTabl(); - ColorTransValid = true; - } - - UpdateMappedScaledColorCopy(top, left, bottom, right); -#else - UpdateTransScaledColorCopy(top, left, bottom, right); -#endif - } else -#endif /* 0 != vMacScreenDepth */ - { - if (! ColorTransValid) { - SetUpBW2ColorScalingTabl(); - ColorTransValid = true; - } - - UpdateMappedScaledBW2ColorCopy(top, left, bottom, right); - } -#else /* ! UseColorImage */ - /* assume 0 == vMacScreenDepth */ - { - if (! ColorTransValid) { - SetUpScalingTabl(); - ColorTransValid = true; - } - - UpdateScaledBWCopy(top, left, bottom, right); - } -#endif /* UseColorImage */ - - { - char *saveData = Scaled_image->data; - Scaled_image->data = (char *)ScalingBuff; - - XPutImage(x_display, main_wind, gc, Scaled_image, - left * WindowScale, top * WindowScale, - XDest, YDest, - (right - left) * WindowScale, - (bottom - top) * WindowScale); - - Scaled_image->data = saveData; - } - } else -#endif /* 1 */ - { -#if UseColorImage -#if 0 != vMacScreenDepth - if (UseColorMode) { -#if vMacScreenDepth < 4 - - if (! ColorTransValid) { - SetUpColorTabl(); - ColorTransValid = true; - } - - UpdateMappedColorCopy(top, left, bottom, right); - - the_data = (char *)ScalingBuff; -#else - /* - if vMacScreenDepth == 5 and MSBFirst, could - copy directly with the_data = (char *)GetCurDrawBuff(); - */ - UpdateTransColorCopy(top, left, bottom, right); - - the_data = (char *)ScalingBuff; -#endif - } else -#endif /* 0 != vMacScreenDepth */ - { - if (! ColorTransValid) { - SetUpBW2ColorTabl(); - ColorTransValid = true; - } - - UpdateMappedBW2ColorCopy(top, left, bottom, right); - - the_data = (char *)ScalingBuff; - } -#else /* ! UseColorImage */ - { - the_data = (char *)GetCurDrawBuff(); - } -#endif /* UseColorImage */ - - { - char *saveData = image->data; - image->data = the_data; - - XPutImage(x_display, main_wind, gc, image, - left, top, XDest, YDest, - right - left, bottom - top); - - image->data = saveData; - } - } - -#if MayFullScreen -label_exit: - ; -#endif -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -/* --- mouse --- */ - -/* cursor hiding */ - -LOCALVAR bool HaveCursorHidden = false; -LOCALVAR bool WantCursorHidden = false; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - if (main_wind) { - XUndefineCursor(x_display, main_wind); - } - } -} - -LOCALVAR Cursor blankCursor = None; - -LOCALFUNC bool CreateBlankCursor(Window rootwin) -/* - adapted from X11_CreateNullCursor in context.x11.c - in quakeforge 0.5.5, copyright Id Software, Inc. - Zephaniah E. Hull, and Jeff Teunissen. -*/ -{ - Pixmap cursormask; - XGCValues xgc; - GC gc; - bool IsOk = false; - - cursormask = XCreatePixmap(x_display, rootwin, 1, 1, 1); - if (None == cursormask) { - WriteExtraErr("XCreatePixmap failed."); - } else { - xgc.function = GXclear; - gc = XCreateGC(x_display, cursormask, GCFunction, &xgc); - if (None == gc) { - WriteExtraErr("XCreateGC failed."); - } else { - XFillRectangle(x_display, cursormask, gc, 0, 0, 1, 1); - XFreeGC(x_display, gc); - - blankCursor = XCreatePixmapCursor(x_display, cursormask, - cursormask, &x_black, &x_white, 0, 0); - if (None == blankCursor) { - WriteExtraErr("XCreatePixmapCursor failed."); - } else { - IsOk = true; - } - } - - XFreePixmap(x_display, cursormask); - /* - assuming that XCreatePixmapCursor doesn't think it - owns the pixmaps passed to it. I've seen code that - assumes this, and other code that seems to assume - the opposite. - */ - } - return IsOk; -} - -/* cursor moving */ - -#if EnableMoveMouse -LOCALFUNC bool MoveMouse(int16_t h, int16_t v) -{ - int NewMousePosh; - int NewMousePosv; - int root_x_return; - int root_y_return; - Window root_return; - Window child_return; - unsigned int mask_return; - bool IsOk; - int attempts = 0; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h -= ViewHStart; - v -= ViewVStart; - } -#endif - -#if 1 - if (UseMagnify) { - h *= WindowScale; - v *= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - h += hOffset; - v += vOffset; - } -#endif - - do { - XWarpPointer(x_display, None, main_wind, 0, 0, 0, 0, h, v); - XQueryPointer(x_display, main_wind, - &root_return, &child_return, - &root_x_return, &root_y_return, - &NewMousePosh, &NewMousePosv, - &mask_return); - IsOk = (h == NewMousePosh) && (v == NewMousePosv); - ++attempts; - } while ((! IsOk) && (attempts < 10)); - return IsOk; -} -#endif - -#if EnableFSMouseMotion -LOCALPROC StartSaveMouseMotion(void) -{ - if (! HaveMouseMotion) { - if (MoveMouse(ViewHStart + (ViewHSize / 2), - ViewVStart + (ViewVSize / 2))) - { - SavedMouseH = ViewHStart + (ViewHSize / 2); - SavedMouseV = ViewVStart + (ViewVSize / 2); - HaveMouseMotion = true; - } - } -} -#endif - -#if EnableFSMouseMotion -LOCALPROC StopSaveMouseMotion(void) -{ - if (HaveMouseMotion) { - (void) MoveMouse(CurMouseH, CurMouseV); - HaveMouseMotion = false; - } -} -#endif - -/* cursor state */ - -#if EnableFSMouseMotion -LOCALPROC MouseConstrain(void) -{ - int16_t shiftdh; - int16_t shiftdv; - - if (SavedMouseH < ViewHStart + (ViewHSize / 4)) { - shiftdh = ViewHSize / 2; - } else if (SavedMouseH > ViewHStart + ViewHSize - (ViewHSize / 4)) { - shiftdh = - ViewHSize / 2; - } else { - shiftdh = 0; - } - if (SavedMouseV < ViewVStart + (ViewVSize / 4)) { - shiftdv = ViewVSize / 2; - } else if (SavedMouseV > ViewVStart + ViewVSize - (ViewVSize / 4)) { - shiftdv = - ViewVSize / 2; - } else { - shiftdv = 0; - } - if ((shiftdh != 0) || (shiftdv != 0)) { - SavedMouseH += shiftdh; - SavedMouseV += shiftdv; - if (! MoveMouse(SavedMouseH, SavedMouseV)) { - HaveMouseMotion = false; - } - } -} -#endif - -LOCALPROC MousePositionNotify(int NewMousePosh, int NewMousePosv) -{ - bool ShouldHaveCursorHidden = true; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePosh -= hOffset; - NewMousePosv -= vOffset; - } -#endif - -#if 1 - if (UseMagnify) { - NewMousePosh /= WindowScale; - NewMousePosv /= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePosh += ViewHStart; - NewMousePosv += ViewVStart; - } -#endif - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MousePositionSetDelta(NewMousePosh - SavedMouseH, - NewMousePosv - SavedMouseV); - SavedMouseH = NewMousePosh; - SavedMouseV = NewMousePosv; - } else -#endif - { - if (NewMousePosh < 0) { - NewMousePosh = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosh >= vMacScreenWidth) { - NewMousePosh = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePosv < 0) { - NewMousePosv = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosv >= vMacScreenHeight) { - NewMousePosv = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ShouldHaveCursorHidden = true; - } -#endif - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePosh, NewMousePosv); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC CheckMouseState(void) -{ - int NewMousePosh; - int NewMousePosv; - int root_x_return; - int root_y_return; - Window root_return; - Window child_return; - unsigned int mask_return; - - XQueryPointer(x_display, main_wind, - &root_return, &child_return, - &root_x_return, &root_y_return, - &NewMousePosh, &NewMousePosv, - &mask_return); - MousePositionNotify(NewMousePosh, NewMousePosv); -} - -/* --- keyboard input --- */ - -LOCALVAR KeyCode TheCapsLockCode; - -LOCALVAR uint8_t KC2MKC[256]; - -LOCALPROC KC2MKCAssignOne(KeySym ks, uint8_t key) -{ - KeyCode code = XKeysymToKeycode(x_display, ks); - if (code != NoSymbol) { - KC2MKC[code] = key; - } -#if 0 - fprintf(stderr, "%d %d %d\n", (int)ks, key, (int)code); -#endif -} - -LOCALFUNC bool KC2MKCInit(void) -{ - int i; - - for (i = 0; i < 256; ++i) { - KC2MKC[i] = MKC_None; - } - -#if 0 /* find Keysym for a code */ - for (i = 0; i < 64 * 1024; ++i) { - KeyCode code = XKeysymToKeycode(x_display, i); - if (115 == code) { - fprintf(stderr, "i %d\n", i); - } - } -#endif - - /* - start with redundant mappings, should get overwritten - by main mappings but define them just in case - */ - -#ifdef XK_KP_Insert - KC2MKCAssignOne(XK_KP_Insert, MKC_KP0); -#endif -#ifdef XK_KP_End - KC2MKCAssignOne(XK_KP_End, MKC_KP1); -#endif -#ifdef XK_KP_Down - KC2MKCAssignOne(XK_KP_Down, MKC_KP2); -#endif -#ifdef XK_KP_Next - KC2MKCAssignOne(XK_KP_Next, MKC_KP3); -#endif -#ifdef XK_KP_Left - KC2MKCAssignOne(XK_KP_Left, MKC_KP4); -#endif -#ifdef XK_KP_Begin - KC2MKCAssignOne(XK_KP_Begin, MKC_KP5); -#endif -#ifdef XK_KP_Right - KC2MKCAssignOne(XK_KP_Right, MKC_KP6); -#endif -#ifdef XK_KP_Home - KC2MKCAssignOne(XK_KP_Home, MKC_KP7); -#endif -#ifdef XK_KP_Up - KC2MKCAssignOne(XK_KP_Up, MKC_KP8); -#endif -#ifdef XK_KP_Prior - KC2MKCAssignOne(XK_KP_Prior, MKC_KP9); -#endif -#ifdef XK_KP_Delete - KC2MKCAssignOne(XK_KP_Delete, MKC_Decimal); -#endif - - KC2MKCAssignOne(XK_asciitilde, MKC_formac_Grave); - KC2MKCAssignOne(XK_underscore, MKC_Minus); - KC2MKCAssignOne(XK_plus, MKC_Equal); - KC2MKCAssignOne(XK_braceleft, MKC_LeftBracket); - KC2MKCAssignOne(XK_braceright, MKC_RightBracket); - KC2MKCAssignOne(XK_bar, MKC_formac_BackSlash); - KC2MKCAssignOne(XK_colon, MKC_SemiColon); - KC2MKCAssignOne(XK_quotedbl, MKC_SingleQuote); - KC2MKCAssignOne(XK_less, MKC_Comma); - KC2MKCAssignOne(XK_greater, MKC_Period); - KC2MKCAssignOne(XK_question, MKC_formac_Slash); - - KC2MKCAssignOne(XK_a, MKC_A); - KC2MKCAssignOne(XK_b, MKC_B); - KC2MKCAssignOne(XK_c, MKC_C); - KC2MKCAssignOne(XK_d, MKC_D); - KC2MKCAssignOne(XK_e, MKC_E); - KC2MKCAssignOne(XK_f, MKC_F); - KC2MKCAssignOne(XK_g, MKC_G); - KC2MKCAssignOne(XK_h, MKC_H); - KC2MKCAssignOne(XK_i, MKC_I); - KC2MKCAssignOne(XK_j, MKC_J); - KC2MKCAssignOne(XK_k, MKC_K); - KC2MKCAssignOne(XK_l, MKC_L); - KC2MKCAssignOne(XK_m, MKC_M); - KC2MKCAssignOne(XK_n, MKC_N); - KC2MKCAssignOne(XK_o, MKC_O); - KC2MKCAssignOne(XK_p, MKC_P); - KC2MKCAssignOne(XK_q, MKC_Q); - KC2MKCAssignOne(XK_r, MKC_R); - KC2MKCAssignOne(XK_s, MKC_S); - KC2MKCAssignOne(XK_t, MKC_T); - KC2MKCAssignOne(XK_u, MKC_U); - KC2MKCAssignOne(XK_v, MKC_V); - KC2MKCAssignOne(XK_w, MKC_W); - KC2MKCAssignOne(XK_x, MKC_X); - KC2MKCAssignOne(XK_y, MKC_Y); - KC2MKCAssignOne(XK_z, MKC_Z); - - /* - main mappings - */ - - KC2MKCAssignOne(XK_F1, MKC_formac_F1); - KC2MKCAssignOne(XK_F2, MKC_formac_F2); - KC2MKCAssignOne(XK_F3, MKC_formac_F3); - KC2MKCAssignOne(XK_F4, MKC_formac_F4); - KC2MKCAssignOne(XK_F5, MKC_formac_F5); - KC2MKCAssignOne(XK_F6, MKC_F6); - KC2MKCAssignOne(XK_F7, MKC_F7); - KC2MKCAssignOne(XK_F8, MKC_F8); - KC2MKCAssignOne(XK_F9, MKC_F9); - KC2MKCAssignOne(XK_F10, MKC_F10); - KC2MKCAssignOne(XK_F11, MKC_F11); - KC2MKCAssignOne(XK_F12, MKC_F12); - -#ifdef XK_Delete - KC2MKCAssignOne(XK_Delete, MKC_formac_ForwardDel); -#endif -#ifdef XK_Insert - KC2MKCAssignOne(XK_Insert, MKC_formac_Help); -#endif -#ifdef XK_Help - KC2MKCAssignOne(XK_Help, MKC_formac_Help); -#endif -#ifdef XK_Home - KC2MKCAssignOne(XK_Home, MKC_formac_Home); -#endif -#ifdef XK_End - KC2MKCAssignOne(XK_End, MKC_formac_End); -#endif - -#ifdef XK_Page_Up - KC2MKCAssignOne(XK_Page_Up, MKC_formac_PageUp); -#else -#ifdef XK_Prior - KC2MKCAssignOne(XK_Prior, MKC_formac_PageUp); -#endif -#endif - -#ifdef XK_Page_Down - KC2MKCAssignOne(XK_Page_Down, MKC_formac_PageDown); -#else -#ifdef XK_Next - KC2MKCAssignOne(XK_Next, MKC_formac_PageDown); -#endif -#endif - -#ifdef XK_Print - KC2MKCAssignOne(XK_Print, MKC_Print); -#endif -#ifdef XK_Scroll_Lock - KC2MKCAssignOne(XK_Scroll_Lock, MKC_ScrollLock); -#endif -#ifdef XK_Pause - KC2MKCAssignOne(XK_Pause, MKC_Pause); -#endif - - KC2MKCAssignOne(XK_KP_Add, MKC_KPAdd); - KC2MKCAssignOne(XK_KP_Subtract, MKC_KPSubtract); - KC2MKCAssignOne(XK_KP_Multiply, MKC_KPMultiply); - KC2MKCAssignOne(XK_KP_Divide, MKC_KPDevide); - KC2MKCAssignOne(XK_KP_Enter, MKC_formac_Enter); - KC2MKCAssignOne(XK_KP_Equal, MKC_KPEqual); - - KC2MKCAssignOne(XK_KP_0, MKC_KP0); - KC2MKCAssignOne(XK_KP_1, MKC_KP1); - KC2MKCAssignOne(XK_KP_2, MKC_KP2); - KC2MKCAssignOne(XK_KP_3, MKC_KP3); - KC2MKCAssignOne(XK_KP_4, MKC_KP4); - KC2MKCAssignOne(XK_KP_5, MKC_KP5); - KC2MKCAssignOne(XK_KP_6, MKC_KP6); - KC2MKCAssignOne(XK_KP_7, MKC_KP7); - KC2MKCAssignOne(XK_KP_8, MKC_KP8); - KC2MKCAssignOne(XK_KP_9, MKC_KP9); - KC2MKCAssignOne(XK_KP_Decimal, MKC_Decimal); - - KC2MKCAssignOne(XK_Left, MKC_Left); - KC2MKCAssignOne(XK_Right, MKC_Right); - KC2MKCAssignOne(XK_Up, MKC_Up); - KC2MKCAssignOne(XK_Down, MKC_Down); - - KC2MKCAssignOne(XK_grave, MKC_formac_Grave); - KC2MKCAssignOne(XK_minus, MKC_Minus); - KC2MKCAssignOne(XK_equal, MKC_Equal); - KC2MKCAssignOne(XK_bracketleft, MKC_LeftBracket); - KC2MKCAssignOne(XK_bracketright, MKC_RightBracket); - KC2MKCAssignOne(XK_backslash, MKC_formac_BackSlash); - KC2MKCAssignOne(XK_semicolon, MKC_SemiColon); - KC2MKCAssignOne(XK_apostrophe, MKC_SingleQuote); - KC2MKCAssignOne(XK_comma, MKC_Comma); - KC2MKCAssignOne(XK_period, MKC_Period); - KC2MKCAssignOne(XK_slash, MKC_formac_Slash); - - KC2MKCAssignOne(XK_Escape, MKC_formac_Escape); - - KC2MKCAssignOne(XK_Tab, MKC_Tab); - KC2MKCAssignOne(XK_Return, MKC_Return); - KC2MKCAssignOne(XK_space, MKC_Space); - KC2MKCAssignOne(XK_BackSpace, MKC_BackSpace); - - KC2MKCAssignOne(XK_Caps_Lock, MKC_formac_CapsLock); - KC2MKCAssignOne(XK_Num_Lock, MKC_Clear); - - KC2MKCAssignOne(XK_Meta_L, MKC_formac_Command); - - KC2MKCAssignOne(XK_Meta_R, MKC_formac_RCommand); - - KC2MKCAssignOne(XK_Mode_switch, MKC_formac_Option); - KC2MKCAssignOne(XK_Menu, MKC_formac_Option); - KC2MKCAssignOne(XK_Super_L, MKC_formac_Option); - KC2MKCAssignOne(XK_Super_R, MKC_formac_ROption); - KC2MKCAssignOne(XK_Hyper_L, MKC_formac_Option); - KC2MKCAssignOne(XK_Hyper_R, MKC_formac_ROption); - - KC2MKCAssignOne(XK_F13, MKC_formac_Option); - /* - seen being used in Mandrake Linux 9.2 - for windows key - */ - - KC2MKCAssignOne(XK_Shift_L, MKC_formac_Shift); - KC2MKCAssignOne(XK_Shift_R, MKC_formac_RShift); - - KC2MKCAssignOne(XK_Alt_L, MKC_formac_Command); - - KC2MKCAssignOne(XK_Alt_R, MKC_formac_RCommand); - - KC2MKCAssignOne(XK_Control_L, MKC_formac_Control); - - KC2MKCAssignOne(XK_Control_R, MKC_formac_RControl); - - KC2MKCAssignOne(XK_1, MKC_1); - KC2MKCAssignOne(XK_2, MKC_2); - KC2MKCAssignOne(XK_3, MKC_3); - KC2MKCAssignOne(XK_4, MKC_4); - KC2MKCAssignOne(XK_5, MKC_5); - KC2MKCAssignOne(XK_6, MKC_6); - KC2MKCAssignOne(XK_7, MKC_7); - KC2MKCAssignOne(XK_8, MKC_8); - KC2MKCAssignOne(XK_9, MKC_9); - KC2MKCAssignOne(XK_0, MKC_0); - - KC2MKCAssignOne(XK_A, MKC_A); - KC2MKCAssignOne(XK_B, MKC_B); - KC2MKCAssignOne(XK_C, MKC_C); - KC2MKCAssignOne(XK_D, MKC_D); - KC2MKCAssignOne(XK_E, MKC_E); - KC2MKCAssignOne(XK_F, MKC_F); - KC2MKCAssignOne(XK_G, MKC_G); - KC2MKCAssignOne(XK_H, MKC_H); - KC2MKCAssignOne(XK_I, MKC_I); - KC2MKCAssignOne(XK_J, MKC_J); - KC2MKCAssignOne(XK_K, MKC_K); - KC2MKCAssignOne(XK_L, MKC_L); - KC2MKCAssignOne(XK_M, MKC_M); - KC2MKCAssignOne(XK_N, MKC_N); - KC2MKCAssignOne(XK_O, MKC_O); - KC2MKCAssignOne(XK_P, MKC_P); - KC2MKCAssignOne(XK_Q, MKC_Q); - KC2MKCAssignOne(XK_R, MKC_R); - KC2MKCAssignOne(XK_S, MKC_S); - KC2MKCAssignOne(XK_T, MKC_T); - KC2MKCAssignOne(XK_U, MKC_U); - KC2MKCAssignOne(XK_V, MKC_V); - KC2MKCAssignOne(XK_W, MKC_W); - KC2MKCAssignOne(XK_X, MKC_X); - KC2MKCAssignOne(XK_Y, MKC_Y); - KC2MKCAssignOne(XK_Z, MKC_Z); - - TheCapsLockCode = XKeysymToKeycode(x_display, XK_Caps_Lock); - - InitKeyCodes(); - - return true; -} - -LOCALPROC CheckTheCapsLock(void) -{ - int NewMousePosh; - int NewMousePosv; - int root_x_return; - int root_y_return; - Window root_return; - Window child_return; - unsigned int mask_return; - - XQueryPointer(x_display, main_wind, - &root_return, &child_return, - &root_x_return, &root_y_return, - &NewMousePosh, &NewMousePosv, - &mask_return); - - Keyboard_UpdateKeyMap2(MKC_formac_CapsLock, - (mask_return & LockMask) != 0); -} - -LOCALPROC DoKeyCode0(int i, bool down) -{ - uint8_t key = KC2MKC[i]; - if (MKC_None != key) { - Keyboard_UpdateKeyMap2(key, down); - } -} - -LOCALPROC DoKeyCode(int i, bool down) -{ - if (i == TheCapsLockCode) { - CheckTheCapsLock(); - } else if (i >= 0 && i < 256) { - DoKeyCode0(i, down); - } -} - -#if MayFullScreen && GrabKeysFullScreen -LOCALVAR bool KeyboardIsGrabbed = false; -#endif - -#if MayFullScreen && GrabKeysFullScreen -LOCALPROC GrabKeyboard(void) -{ - if (! KeyboardIsGrabbed) { - (void) XGrabKeyboard(x_display, main_wind, - False, GrabModeAsync, GrabModeAsync, - CurrentTime); - KeyboardIsGrabbed = true; - } -} -#endif - -#if MayFullScreen && GrabKeysFullScreen -LOCALPROC UnGrabKeyboard(void) -{ - if (KeyboardIsGrabbed && main_wind) { - XUngrabKeyboard(x_display, CurrentTime); - KeyboardIsGrabbed = false; - } -} -#endif - -LOCALVAR bool NoKeyRepeat = false; -LOCALVAR int SaveKeyRepeat; - -LOCALPROC DisableKeyRepeat(void) -{ - XKeyboardState r; - XKeyboardControl k; - - if ((! NoKeyRepeat) && (x_display != NULL)) { - NoKeyRepeat = true; - - XGetKeyboardControl(x_display, &r); - SaveKeyRepeat = r.global_auto_repeat; - - k.auto_repeat_mode = AutoRepeatModeOff; - XChangeKeyboardControl(x_display, KBAutoRepeatMode, &k); - } -} - -LOCALPROC RestoreKeyRepeat(void) -{ - XKeyboardControl k; - - if (NoKeyRepeat && (x_display != NULL)) { - NoKeyRepeat = false; - - k.auto_repeat_mode = SaveKeyRepeat; - XChangeKeyboardControl(x_display, KBAutoRepeatMode, &k); - } -} - -LOCALVAR bool WantCmdOptOnReconnect = false; - -LOCALPROC GetTheDownKeys(void) -{ - char keys_return[32]; - int i; - int v; - int j; - - XQueryKeymap(x_display, keys_return); - - for (i = 0; i < 32; ++i) { - v = keys_return[i]; - for (j = 0; j < 8; ++j) { - if (0 != ((1 << j) & v)) { - int k = i * 8 + j; - if (k != TheCapsLockCode) { - DoKeyCode0(k, true); - } - } - } - } -} - -LOCALPROC ReconnectKeyCodes3(void) -{ - CheckTheCapsLock(); - - if (WantCmdOptOnReconnect) { - WantCmdOptOnReconnect = false; - - GetTheDownKeys(); - } -} - -LOCALPROC DisconnectKeyCodes3(void) -{ - DisconnectKeyCodes2(); - MouseButtonSet(false); -} - -/* --- time, date, location --- */ - -#define dbglog_TimeStuff (0 && dbglog_HAVE) - -LOCALVAR uint32_t TrueEmulatedTime = 0; - -#include "UTIL/DATE2SEC.h" - -#define TicksPerSecond 1000000 - -LOCALVAR bool HaveTimeDelta = false; -LOCALVAR uint32_t TimeDelta; - -LOCALVAR uint32_t NewMacDateInSeconds; - -LOCALVAR uint32_t LastTimeSec; -LOCALVAR uint32_t LastTimeUsec; - -LOCALPROC GetCurrentTicks(void) -{ - struct timeval t; - - gettimeofday(&t, NULL); - if (! HaveTimeDelta) { - time_t Current_Time; - struct tm *s; - - (void) time(&Current_Time); - s = localtime(&Current_Time); - TimeDelta = Date2MacSeconds(s->tm_sec, s->tm_min, s->tm_hour, - s->tm_mday, 1 + s->tm_mon, 1900 + s->tm_year) - t.tv_sec; -#if 0 && AutoTimeZone /* how portable is this ? */ - CurMacDelta = ((uint32_t)(s->tm_gmtoff) & 0x00FFFFFF) - | ((s->tm_isdst ? 0x80 : 0) << 24); -#endif - HaveTimeDelta = true; - } - - NewMacDateInSeconds = t.tv_sec + TimeDelta; - LastTimeSec = (uint32_t)t.tv_sec; - LastTimeUsec = (uint32_t)t.tv_usec; -} - -#define InvTimeStep 16626 /* TicksPerSecond / 60.14742 */ - -LOCALVAR uint32_t NextTimeSec; -LOCALVAR uint32_t NextTimeUsec; - -LOCALPROC IncrNextTime(void) -{ - NextTimeUsec += InvTimeStep; - if (NextTimeUsec >= TicksPerSecond) { - NextTimeUsec -= TicksPerSecond; - NextTimeSec += 1; - } -} - -LOCALPROC InitNextTime(void) -{ - NextTimeSec = LastTimeSec; - NextTimeUsec = LastTimeUsec; - IncrNextTime(); -} - -LOCALPROC StartUpTimeAdjust(void) -{ - GetCurrentTicks(); - InitNextTime(); -} - -LOCALFUNC int32_t GetTimeDiff(void) -{ - return ((int32_t)(LastTimeSec - NextTimeSec)) * TicksPerSecond - + ((int32_t)(LastTimeUsec - NextTimeUsec)); -} - -LOCALPROC UpdateTrueEmulatedTime(void) -{ - int32_t TimeDiff; - - GetCurrentTicks(); - - TimeDiff = GetTimeDiff(); - if (TimeDiff >= 0) { - if (TimeDiff > 16 * InvTimeStep) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - InitNextTime(); - -#if dbglog_TimeStuff - dbglog_writelnNum("emulation interrupted", - TrueEmulatedTime); -#endif - } else { - do { - ++TrueEmulatedTime; - IncrNextTime(); - TimeDiff -= TicksPerSecond; - } while (TimeDiff >= 0); - } - } else if (TimeDiff < - 16 * InvTimeStep) { - /* clock goofed if ever get here, reset */ -#if dbglog_TimeStuff - dbglog_writeln("clock set back"); -#endif - - InitNextTime(); - } -} - -LOCALFUNC bool CheckDateTime(void) -{ - if (CurMacDateInSeconds != NewMacDateInSeconds) { - CurMacDateInSeconds = NewMacDateInSeconds; - return true; - } else { - return false; - } -} - -LOCALFUNC bool InitLocationDat(void) -{ - GetCurrentTicks(); - CurMacDateInSeconds = NewMacDateInSeconds; - - return true; -} - -/* --- sound --- */ - -#if SoundEnabled - -#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */ -#define kSoundBuffers (1 << kLn2SoundBuffers) -#define kSoundBuffMask (kSoundBuffers - 1) - -#define DesiredMinFilledSoundBuffs 3 - /* - if too big then sound lags behind emulation. - if too small then sound will have pauses. - */ - -#define kLnOneBuffLen 9 -#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen) -#define kOneBuffLen (1UL << kLnOneBuffLen) -#define kAllBuffLen (1UL << kLnAllBuffLen) -#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3) -#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3) -#define kOneBuffSz (1UL << kLnOneBuffSz) -#define kAllBuffSz (1UL << kLnAllBuffSz) -#define kOneBuffMask (kOneBuffLen - 1) -#define kAllBuffMask (kAllBuffLen - 1) -#define dbhBufferSize (kAllBuffSz + kOneBuffSz) - -#define dbglog_SoundStuff (0 && dbglog_HAVE) -#define dbglog_SoundBuffStats (0 && dbglog_HAVE) - -LOCALVAR tpSoundSamp TheSoundBuffer = nullpr; -LOCALVAR uint16_t ThePlayOffset; -LOCALVAR uint16_t TheFillOffset; -LOCALVAR uint16_t TheWriteOffset; -LOCALVAR uint16_t MinFilledSoundBuffs; - -LOCALPROC Sound_Start0(void) -{ - /* Reset variables */ - ThePlayOffset = 0; - TheFillOffset = 0; - TheWriteOffset = 0; - MinFilledSoundBuffs = kSoundBuffers; -} - -GLOBALOSGLUFUNC tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL) -{ - uint16_t ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset); - uint16_t WriteBuffContig = - kOneBuffLen - (TheWriteOffset & kOneBuffMask); - - if (WriteBuffContig < n) { - n = WriteBuffContig; - } - if (ToFillLen < n) { - /* overwrite previous buffer */ -#if dbglog_SoundStuff - dbglog_writeln("sound buffer over flow"); -#endif - TheWriteOffset -= kOneBuffLen; - } - - *actL = n; - return TheSoundBuffer + (TheWriteOffset & kAllBuffMask); -} - -LOCALFUNC bool Sound_EndWrite0(uint16_t actL) -{ - bool v; - - TheWriteOffset += actL; - - if (0 != (TheWriteOffset & kOneBuffMask)) { - v = false; - } else { - /* just finished a block */ - - TheFillOffset = TheWriteOffset; - - v = true; - } - - return v; -} - -LOCALPROC Sound_SecondNotify0(void) -{ - if (MinFilledSoundBuffs > DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too high"); -#endif - IncrNextTime(); - } else if (MinFilledSoundBuffs < DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too low"); -#endif - ++TrueEmulatedTime; - } - MinFilledSoundBuffs = kSoundBuffers; -} - -#define SOUND_SAMPLERATE 22255 /* = round(7833600 * 2 / 704) */ - -//#include "SOUNDGLU.h" -#include "HW/SOUND/SGLUALSA.h" - -#endif - -/* --- basic dialogs --- */ - -LOCALPROC CheckSavedMacMsg(void) -{ - /* called only on quit, if error saved but not yet reported */ - - if (nullpr != SavedBriefMsg) { - char briefMsg0[ClStrMaxLength + 1]; - char longMsg0[ClStrMaxLength + 1]; - - NativeStrFromCStr(briefMsg0, SavedBriefMsg); - NativeStrFromCStr(longMsg0, SavedLongMsg); - - fprintf(stderr, "%s\n", briefMsg0); - fprintf(stderr, "%s\n", longMsg0); - - SavedBriefMsg = nullpr; - } -} - -/* --- clipboard --- */ - -#if IncludeHostTextClipExchange -LOCALVAR uint8_t * ClipBuffer = NULL; -#endif - -#if IncludeHostTextClipExchange -LOCALPROC FreeClipBuffer(void) -{ - if (ClipBuffer != NULL) { - free(ClipBuffer); - ClipBuffer = NULL; - } -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEexport(tPbuf i) -{ - MacErr_t err = mnvm_miscErr; - - FreeClipBuffer(); - if (MacRomanTextToNativePtr(i, false, - &ClipBuffer)) - { - XSetSelectionOwner(x_display, XA_CLIPBOARD, - main_wind, CurrentTime); - err = mnvm_noErr; - } - - PbufDispose(i); - - return err; -} -#endif - -#if IncludeHostTextClipExchange -LOCALFUNC bool WaitForClipboardSelection(XEvent *xevent) -{ - struct timespec rqt; - struct timespec rmt; - int i; - - for (i = 100; --i >= 0; ) { - while (XCheckTypedWindowEvent(x_display, main_wind, - SelectionNotify, xevent)) - { - if (xevent->xselection.selection != XA_CLIPBOARD) { - /* - not what we were looking for. lose it. - (and hope it wasn't too important). - */ - WriteExtraErr("Discarding unwanted SelectionNotify"); - } else { - /* this is our event */ - return true; - } - } - - rqt.tv_sec = 0; - rqt.tv_nsec = 10000000; - (void) nanosleep(&rqt, &rmt); - } - return false; -} -#endif - -#if IncludeHostTextClipExchange -LOCALPROC HTCEimport_do(void) -{ - Window w = XGetSelectionOwner(x_display, XA_CLIPBOARD); - - if (w == main_wind) { - /* We own the clipboard, already have ClipBuffer */ - } else { - FreeClipBuffer(); - if (w != None) { - XEvent xevent; - - XDeleteProperty(x_display, main_wind, - XA_MinivMac_Clip); - XConvertSelection(x_display, XA_CLIPBOARD, XA_STRING, - XA_MinivMac_Clip, main_wind, CurrentTime); - - if (WaitForClipboardSelection(&xevent)) { - if (None == xevent.xselection.property) { - /* oops, target not supported */ - } else { - if (xevent.xselection.property - != XA_MinivMac_Clip) - { - /* not where we expected it */ - } else { - Atom ret_type; - int ret_format; - unsigned long ret_item; - unsigned long remain_byte; - unsigned char *s = NULL; - - if ((Success != XGetWindowProperty( - x_display, main_wind, XA_MinivMac_Clip, - 0, 65535, False, AnyPropertyType, &ret_type, - &ret_format, &ret_item, &remain_byte, &s)) - || (ret_type != XA_STRING) - || (ret_format != 8) - || (NULL == s)) - { - WriteExtraErr( - "XGetWindowProperty failed" - " in HTCEimport_do"); - } else { - ClipBuffer = (uint8_t *)malloc(ret_item + 1); - if (NULL == ClipBuffer) { - MacMsg(kStrOutOfMemTitle, - kStrOutOfMemMessage, false); - } else { - MoveBytes((anyp)s, (anyp)ClipBuffer, - ret_item); - ClipBuffer[ret_item] = 0; - } - XFree(s); - } - } - XDeleteProperty(x_display, main_wind, - XA_MinivMac_Clip); - } - } - } - } -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEimport(tPbuf *r) -{ - HTCEimport_do(); - - return NativeTextToMacRomanPbuf((char *)ClipBuffer, r); -} -#endif - -#if IncludeHostTextClipExchange -LOCALFUNC bool HandleSelectionRequestClipboard(XEvent *theEvent) -{ - bool RequestFilled = false; - -#if DbgEvents - dbglog_writeln("Requested XA_CLIPBOARD"); -#endif - - if (NULL == ClipBuffer) { - /* our clipboard is empty */ - } else if (theEvent->xselectionrequest.target == XA_TARGETS) { - Atom a[2]; - - a[0] = XA_TARGETS; - a[1] = XA_STRING; - - XChangeProperty(x_display, - theEvent->xselectionrequest.requestor, - theEvent->xselectionrequest.property, - XA_TARGETS, - 32, - /* - most, but not all, other programs I've - look at seem to use 8 here, but that - can't be right. can it? - */ - PropModeReplace, - (unsigned char *)a, - sizeof(a) / sizeof(Atom)); - - RequestFilled = true; - } else if (theEvent->xselectionrequest.target == XA_STRING) { - XChangeProperty(x_display, - theEvent->xselectionrequest.requestor, - theEvent->xselectionrequest.property, - XA_STRING, - 8, - PropModeReplace, - (unsigned char *)ClipBuffer, - strlen((char *)ClipBuffer)); - - RequestFilled = true; - } - - return RequestFilled; -} -#endif - -/* --- drag and drop --- */ - -#if EnableDragDrop -LOCALPROC ActivateWind(Time time) -{ - if (NetSupportedContains(XA_NetActiveWindow)) { - XEvent xevent; - Window rootwin = XRootWindow(x_display, - DefaultScreen(x_display)); - - memset(&xevent, 0, sizeof (xevent)); - - xevent.xany.type = ClientMessage; - xevent.xclient.send_event = True; - xevent.xclient.window = main_wind; - xevent.xclient.message_type = XA_NetActiveWindow; - xevent.xclient.format = 32; - xevent.xclient.data.l[0] = 1; - xevent.xclient.data.l[1]= time; - - if (0 == XSendEvent(x_display, rootwin, 0, - SubstructureRedirectMask | SubstructureNotifyMask, - &xevent)) - { - WriteExtraErr("XSendEvent failed in ActivateWind"); - } - } - - XRaiseWindow(x_display, main_wind); - /* - In RedHat 7.1, _NET_ACTIVE_WINDOW supported, - but XSendEvent of _NET_ACTIVE_WINDOW - doesn't raise the window. So just always - call XRaiseWindow. Hopefully calling - XRaiseWindow won't do any harm on window - managers where it isn't needed. - (Such as in Ubuntu 5.10) - */ - XSetInputFocus(x_display, main_wind, - RevertToPointerRoot, time); - /* And call this always too, just in case */ -} -#endif - -#if EnableDragDrop -LOCALPROC ParseOneUri(char *s) -{ - /* printf("ParseOneUri %s\n", s); */ - if (('f' == s[0]) && ('i' == s[1]) && ('l' == s[2]) - && ('e' == s[3]) && (':' == s[4])) - { - s += 5; - if (('/' == s[0]) && ('/' == s[1])) { - /* skip hostname */ - char c; - - s += 2; - while ((c = *s) != '/') { - if (0 == c) { - return; - } - ++s; - } - } - (void) Sony_Insert1a(s, false); - } -} -#endif - -#if EnableDragDrop -LOCALFUNC int HexChar2Nib(char x) -{ - if ((x >= '0') && (x <= '9')) { - return x - '0'; - } else if ((x >= 'A') && (x <= 'F')) { - return x - 'A' + 10; - } else if ((x >= 'a') && (x <= 'f')) { - return x - 'a' + 10; - } else { - return -1; - } -} -#endif - -#if EnableDragDrop -LOCALPROC ParseUriList(char *s) -{ - char *p1 = s; - char *p0 = s; - char *p = s; - char c; - - /* printf("ParseUriList %s\n", s); */ - while ((c = *p++) != 0) { - if ('%' == c) { - int a; - int b; - - if (((a = HexChar2Nib(p[0])) >= 0) && - ((b = HexChar2Nib(p[1])) >= 0)) - { - p += 2; - *p1++ = (a << 4) + b; - } else { - *p1++ = c; - } - } else if (('\n' == c) || ('\r' == c)) { - *p1++ = 0; - ParseOneUri(p0); - p0 = p1; - } else { - *p1++ = c; - } - } - *p1++ = 0; - ParseOneUri(p0); -} -#endif - -#if EnableDragDrop -LOCALVAR Window PendingDragWindow = None; -#endif - -#if EnableDragDrop -LOCALPROC HandleSelectionNotifyDnd(XEvent *theEvent) -{ - bool DropOk = false; - -#if DbgEvents - dbglog_writeln("Got XA_DndSelection"); -#endif - - if ((theEvent->xselection.property == XA_MinivMac_DndXchng) - && (theEvent->xselection.target == XA_UriList)) - { - Atom ret_type; - int ret_format; - unsigned long ret_item; - unsigned long remain_byte; - unsigned char *s = NULL; - - if ((Success != XGetWindowProperty(x_display, main_wind, - XA_MinivMac_DndXchng, - 0, 65535, False, XA_UriList, &ret_type, &ret_format, - &ret_item, &remain_byte, &s)) - || (NULL == s)) - { - WriteExtraErr( - "XGetWindowProperty failed in SelectionNotify"); - } else { - ParseUriList((char *)s); - DropOk = true; - XFree(s); - } - } else { - WriteExtraErr("Got Unknown SelectionNotify"); - } - - XDeleteProperty(x_display, main_wind, - XA_MinivMac_DndXchng); - - if (PendingDragWindow != None) { - XEvent xevent; - - memset(&xevent, 0, sizeof(xevent)); - - xevent.xany.type = ClientMessage; - xevent.xany.display = x_display; - xevent.xclient.window = PendingDragWindow; - xevent.xclient.message_type = XA_DndFinished; - xevent.xclient.format = 32; - - xevent.xclient.data.l[0] = main_wind; - if (DropOk) { - xevent.xclient.data.l[1] = 1; - } - xevent.xclient.data.l[2] = XA_DndActionPrivate; - - if (0 == XSendEvent(x_display, - PendingDragWindow, 0, 0, &xevent)) - { - WriteExtraErr("XSendEvent failed in SelectionNotify"); - } - } - if (DropOk && gTrueBackgroundFlag) { - ActivateWind(theEvent->xselection.time); - - WantCmdOptOnReconnect = true; - } -} -#endif - -#if EnableDragDrop -LOCALPROC HandleClientMessageDndPosition(XEvent *theEvent) -{ - XEvent xevent; - int xr; - int yr; - unsigned int dr; - unsigned int wr; - unsigned int hr; - unsigned int bwr; - Window rr; - Window srcwin = theEvent->xclient.data.l[0]; - -#if DbgEvents - dbglog_writeln("Got XdndPosition"); -#endif - - XGetGeometry(x_display, main_wind, - &rr, &xr, &yr, &wr, &hr, &bwr, &dr); - memset (&xevent, 0, sizeof(xevent)); - xevent.xany.type = ClientMessage; - xevent.xany.display = x_display; - xevent.xclient.window = srcwin; - xevent.xclient.message_type = XA_DndStatus; - xevent.xclient.format = 32; - - xevent.xclient.data.l[0] = theEvent->xclient.window; - /* Target Window */ - xevent.xclient.data.l[1] = 1; /* Accept */ - xevent.xclient.data.l[2] = ((xr) << 16) | ((yr) & 0xFFFFUL); - xevent.xclient.data.l[3] = ((wr) << 16) | ((hr) & 0xFFFFUL); - xevent.xclient.data.l[4] = XA_DndActionPrivate; /* Action */ - - if (0 == XSendEvent(x_display, srcwin, 0, 0, &xevent)) { - WriteExtraErr( - "XSendEvent failed in HandleClientMessageDndPosition"); - } -} -#endif - -#if EnableDragDrop -LOCALPROC HandleClientMessageDndDrop(XEvent *theEvent) -{ - Time timestamp = theEvent->xclient.data.l[2]; - PendingDragWindow = (Window) theEvent->xclient.data.l[0]; - -#if DbgEvents - dbglog_writeln("Got XdndDrop"); -#endif - - XConvertSelection(x_display, XA_DndSelection, XA_UriList, - XA_MinivMac_DndXchng, main_wind, timestamp); -} -#endif - -#define UseMotionEvents 1 - -#if UseMotionEvents -LOCALVAR bool CaughtMouse = false; -#endif - -#if MayNotFullScreen -LOCALVAR int SavedTransH; -LOCALVAR int SavedTransV; -#endif - -/* --- event handling for main window --- */ - -LOCALPROC HandleTheEvent(XEvent *theEvent) -{ - if (theEvent->xany.display != x_display) { - WriteExtraErr("Got event for some other display"); - } else switch(theEvent->type) { - case KeyPress: - if (theEvent->xkey.window != main_wind) { - WriteExtraErr("Got KeyPress for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - KeyPress"); -#endif - - MousePositionNotify(theEvent->xkey.x, theEvent->xkey.y); - DoKeyCode(theEvent->xkey.keycode, true); - } - break; - case KeyRelease: - if (theEvent->xkey.window != main_wind) { - WriteExtraErr("Got KeyRelease for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - KeyRelease"); -#endif - - MousePositionNotify(theEvent->xkey.x, theEvent->xkey.y); - DoKeyCode(theEvent->xkey.keycode, false); - } - break; - case ButtonPress: - /* any mouse button, we don't care which */ - if (theEvent->xbutton.window != main_wind) { - WriteExtraErr("Got ButtonPress for some other window"); - } else { - /* - could check some modifiers, but don't bother for now - Keyboard_UpdateKeyMap2(MKC_formac_CapsLock, - (theEvent->xbutton.state & LockMask) != 0); - */ - MousePositionNotify( - theEvent->xbutton.x, theEvent->xbutton.y); - MouseButtonSet(true); - } - break; - case ButtonRelease: - /* any mouse button, we don't care which */ - if (theEvent->xbutton.window != main_wind) { - WriteExtraErr( - "Got ButtonRelease for some other window"); - } else { - MousePositionNotify( - theEvent->xbutton.x, theEvent->xbutton.y); - MouseButtonSet(false); - } - break; -#if UseMotionEvents - case MotionNotify: - if (theEvent->xmotion.window != main_wind) { - WriteExtraErr("Got MotionNotify for some other window"); - } else { - MousePositionNotify( - theEvent->xmotion.x, theEvent->xmotion.y); - } - break; - case EnterNotify: - if (theEvent->xcrossing.window != main_wind) { - WriteExtraErr("Got EnterNotify for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - EnterNotify"); -#endif - - CaughtMouse = true; - MousePositionNotify( - theEvent->xcrossing.x, theEvent->xcrossing.y); - } - break; - case LeaveNotify: - if (theEvent->xcrossing.window != main_wind) { - WriteExtraErr("Got LeaveNotify for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - LeaveNotify"); -#endif - - MousePositionNotify( - theEvent->xcrossing.x, theEvent->xcrossing.y); - CaughtMouse = false; - } - break; -#endif - case Expose: - if (theEvent->xexpose.window != main_wind) { - WriteExtraErr( - "Got SelectionRequest for some other window"); - } else { - int x0 = theEvent->xexpose.x; - int y0 = theEvent->xexpose.y; - int x1 = x0 + theEvent->xexpose.width; - int y1 = y0 + theEvent->xexpose.height; - -#if 0 && DbgEvents - dbglog_writeln("- event - Expose"); -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - x0 -= hOffset; - y0 -= vOffset; - x1 -= hOffset; - y1 -= vOffset; - } -#endif - -#if 1 - if (UseMagnify) { - x0 /= WindowScale; - y0 /= WindowScale; - x1 = (x1 + (WindowScale - 1)) / WindowScale; - y1 = (y1 + (WindowScale - 1)) / WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - x0 += ViewHStart; - y0 += ViewVStart; - x1 += ViewHStart; - y1 += ViewVStart; - } -#endif - - if (x0 < 0) { - x0 = 0; - } - if (x1 > vMacScreenWidth) { - x1 = vMacScreenWidth; - } - if (y0 < 0) { - y0 = 0; - } - if (y1 > vMacScreenHeight) { - y1 = vMacScreenHeight; - } - if ((x0 < x1) && (y0 < y1)) { - HaveChangedScreenBuff(y0, x0, y1, x1); - } - - NeedFinishOpen1 = false; - } - break; -#if IncludeHostTextClipExchange - case SelectionRequest: - if (theEvent->xselectionrequest.owner != main_wind) { - WriteExtraErr( - "Got SelectionRequest for some other window"); - } else { - XEvent xevent; - bool RequestFilled = false; - -#if DbgEvents - dbglog_writeln("- event - SelectionRequest"); - WriteDbgAtom("selection", - theEvent->xselectionrequest.selection); - WriteDbgAtom("target", - theEvent->xselectionrequest.target); - WriteDbgAtom("property", - theEvent->xselectionrequest.property); -#endif - - if (theEvent->xselectionrequest.selection == - XA_CLIPBOARD) - { - RequestFilled = - HandleSelectionRequestClipboard(theEvent); - } - - - memset(&xevent, 0, sizeof(xevent)); - xevent.xselection.type = SelectionNotify; - xevent.xselection.display = x_display; - xevent.xselection.requestor = - theEvent->xselectionrequest.requestor; - xevent.xselection.selection = - theEvent->xselectionrequest.selection; - xevent.xselection.target = - theEvent->xselectionrequest.target; - xevent.xselection.property = (! RequestFilled) ? None - : theEvent->xselectionrequest.property ; - xevent.xselection.time = - theEvent->xselectionrequest.time; - - if (0 == XSendEvent(x_display, - xevent.xselection.requestor, False, 0, &xevent)) - { - WriteExtraErr( - "XSendEvent failed in SelectionRequest"); - } - } - break; - case SelectionClear: - if (theEvent->xselectionclear.window != main_wind) { - WriteExtraErr( - "Got SelectionClear for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - SelectionClear"); - WriteDbgAtom("selection", - theEvent->xselectionclear.selection); -#endif - - if (theEvent->xselectionclear.selection == - XA_CLIPBOARD) - { - FreeClipBuffer(); - } - } - break; -#endif -#if EnableDragDrop - case SelectionNotify: - if (theEvent->xselection.requestor != main_wind) { - WriteExtraErr( - "Got SelectionNotify for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - SelectionNotify"); - WriteDbgAtom("selection", - theEvent->xselection.selection); - WriteDbgAtom("target", theEvent->xselection.target); - WriteDbgAtom("property", theEvent->xselection.property); -#endif - - if (theEvent->xselection.selection == XA_DndSelection) - { - HandleSelectionNotifyDnd(theEvent); - } else { - WriteExtraErr( - "Got Unknown selection in SelectionNotify"); - } - } - break; -#endif - case ClientMessage: - if (theEvent->xclient.window != main_wind) { - WriteExtraErr( - "Got ClientMessage for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - ClientMessage"); - WriteDbgAtom("message_type", - theEvent->xclient.message_type); -#endif - -#if EnableDragDrop - if (theEvent->xclient.message_type == XA_DndEnter) { - /* printf("Got XdndEnter\n"); */ - } else if (theEvent->xclient.message_type == - XA_DndLeave) - { - /* printf("Got XdndLeave\n"); */ - } else if (theEvent->xclient.message_type == - XA_DndPosition) - { - HandleClientMessageDndPosition(theEvent); - } else if (theEvent->xclient.message_type == - XA_DndDrop) - { - HandleClientMessageDndDrop(theEvent); - } else -#endif - { - if ((32 == theEvent->xclient.format) && - (theEvent->xclient.data.l[0] == XA_DeleteW)) - { - /* - I would think that should test that - WM_PROTOCOLS == message_type - but none of the other programs I looked - at did. - */ - RequestMacOff = true; - } - } - } - break; - case FocusIn: - if (theEvent->xfocus.window != main_wind) { - WriteExtraErr("Got FocusIn for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - FocusIn"); -#endif - - gTrueBackgroundFlag = false; -#if UseMotionEvents - CheckMouseState(); - /* - Doesn't help on x11 for OS X, - can't get new mouse position - in any fashion until mouse moves. - */ -#endif - } - break; - case FocusOut: - if (theEvent->xfocus.window != main_wind) { - WriteExtraErr("Got FocusOut for some other window"); - } else { -#if DbgEvents - dbglog_writeln("- event - FocusOut"); -#endif - - gTrueBackgroundFlag = true; - } - break; - default: - break; - } -} - -/* --- main window creation and disposal --- */ - -LOCALVAR int argc; -LOCALVAR char **argv; - -LOCALVAR char *display_name = NULL; - -LOCALFUNC bool Screen_Init(void) -{ - Window rootwin; - int screen; - Colormap Xcmap; - Visual *Xvisual; - - x_display = XOpenDisplay(display_name); - if (NULL == x_display) { - fprintf(stderr, "Cannot connect to X server.\n"); - return false; - } - - screen = DefaultScreen(x_display); - - rootwin = XRootWindow(x_display, screen); - - Xcmap = DefaultColormap(x_display, screen); - - Xvisual = DefaultVisual(x_display, screen); - - LoadXA(); - - XParseColor(x_display, Xcmap, "#000000", &x_black); - if (! XAllocColor(x_display, Xcmap, &x_black)) { - WriteExtraErr("XParseColor black fails"); - } - XParseColor(x_display, Xcmap, "#ffffff", &x_white); - if (! XAllocColor(x_display, Xcmap, &x_white)) { - WriteExtraErr("XParseColor white fails"); - } - - if (! CreateBlankCursor(rootwin)) { - return false; - } - -#if ! UseColorImage - image = XCreateImage(x_display, Xvisual, 1, XYBitmap, 0, - NULL /* (char *)image_Mem1 */, - vMacScreenWidth, vMacScreenHeight, 32, - vMacScreenMonoByteWidth); - if (NULL == image) { - fprintf(stderr, "XCreateImage failed.\n"); - return false; - } - -#if 0 - fprintf(stderr, "bitmap_bit_order = %d\n", - (int)image->bitmap_bit_order); - fprintf(stderr, "byte_order = %d\n", (int)image->byte_order); -#endif - - image->bitmap_bit_order = MSBFirst; - image->byte_order = MSBFirst; -#endif - -#if UseColorImage - image = XCreateImage(x_display, Xvisual, 24, ZPixmap, 0, - NULL /* (char *)image_Mem1 */, - vMacScreenWidth, vMacScreenHeight, 32, - 4 * (uint32_t)vMacScreenWidth); - if (NULL == image) { - fprintf(stderr, "XCreateImage Color failed.\n"); - return false; - } - -#if 0 - fprintf(stderr, "DefaultDepth = %d\n", - (int)DefaultDepth(x_display, screen)); - - fprintf(stderr, "MSBFirst = %d\n", (int)MSBFirst); - fprintf(stderr, "LSBFirst = %d\n", (int)LSBFirst); - - fprintf(stderr, "bitmap_bit_order = %d\n", - (int)image->bitmap_bit_order); - fprintf(stderr, "byte_order = %d\n", - (int)image->byte_order); - fprintf(stderr, "bitmap_unit = %d\n", - (int)image->bitmap_unit); - fprintf(stderr, "bits_per_pixel = %d\n", - (int)image->bits_per_pixel); - fprintf(stderr, "red_mask = %d\n", - (int)image->red_mask); - fprintf(stderr, "green_mask = %d\n", - (int)image->green_mask); - fprintf(stderr, "blue_mask = %d\n", - (int)image->blue_mask); -#endif - -#endif /* UseColorImage */ - -#if 1 && (! UseColorImage) - Scaled_image = XCreateImage(x_display, Xvisual, - 1, XYBitmap, 0, - NULL /* (char *)image_Mem1 */, - vMacScreenWidth * WindowScale, - vMacScreenHeight * WindowScale, - 32, vMacScreenMonoByteWidth * WindowScale); - if (NULL == Scaled_image) { - fprintf(stderr, "XCreateImage failed.\n"); - return false; - } - - Scaled_image->bitmap_bit_order = MSBFirst; - Scaled_image->byte_order = MSBFirst; -#endif - -#if 1 && UseColorImage - Scaled_image = XCreateImage(x_display, Xvisual, - 24, ZPixmap, 0, - NULL /* (char *)image_Mem1 */, - vMacScreenWidth * WindowScale, - vMacScreenHeight * WindowScale, - 32, 4 * (uint32_t)vMacScreenWidth * WindowScale); - if (NULL == Scaled_image) { - fprintf(stderr, "XCreateImage Scaled failed.\n"); - return false; - } -#endif - -#if 0 != vMacScreenDepth - ColorModeWorks = true; -#endif - - DisableKeyRepeat(); - - return true; -} - -LOCALPROC CloseMainWindow(void) -{ - if (gc != NULL) { - XFreeGC(x_display, gc); - gc = NULL; - } - if (main_wind) { - XDestroyWindow(x_display, main_wind); - main_wind = 0; - } -} - -enum { - kMagStateNormal, -#if 1 - kMagStateMagnifgy, -#endif - kNumMagStates -}; - -#define kMagStateAuto kNumMagStates - -#if MayNotFullScreen -LOCALVAR int CurWinIndx; -LOCALVAR bool HavePositionWins[kNumMagStates]; -LOCALVAR int WinPositionWinsH[kNumMagStates]; -LOCALVAR int WinPositionWinsV[kNumMagStates]; -#endif - -#if EnableRecreateW -LOCALPROC ZapWState(void) -{ - main_wind = 0; - gc = NULL; -} -#endif - -LOCALFUNC bool CreateMainWindow(void) -{ - Window rootwin; - int screen; - int xr; - int yr; - unsigned int dr; - unsigned int wr; - unsigned int hr; - unsigned int bwr; - Window rr; - int leftPos; - int topPos; -#if MayNotFullScreen - int WinIndx; -#endif -#if EnableDragDrop - long int xdnd_version = 5; -#endif - int NewWindowHeight = vMacScreenHeight; - int NewWindowWidth = vMacScreenWidth; - - /* Get connection to X Server */ - screen = DefaultScreen(x_display); - - rootwin = XRootWindow(x_display, screen); - - XGetGeometry(x_display, rootwin, - &rr, &xr, &yr, &wr, &hr, &bwr, &dr); - -#if 1 - if (UseMagnify) { - NewWindowHeight *= WindowScale; - NewWindowWidth *= WindowScale; - } -#endif - - if (wr > NewWindowWidth) { - leftPos = (wr - NewWindowWidth) / 2; - } else { - leftPos = 0; - } - if (hr > NewWindowHeight) { - topPos = (hr - NewWindowHeight) / 2; - } else { - topPos = 0; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ViewHSize = wr; - ViewVSize = hr; -#if 1 - if (UseMagnify) { - ViewHSize /= WindowScale; - ViewVSize /= WindowScale; - } -#endif - if (ViewHSize >= vMacScreenWidth) { - ViewHStart = 0; - ViewHSize = vMacScreenWidth; - } else { - ViewHSize &= ~ 1; - } - if (ViewVSize >= vMacScreenHeight) { - ViewVStart = 0; - ViewVSize = vMacScreenHeight; - } else { - ViewVSize &= ~ 1; - } - } -#endif - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { -#if 1 - if (UseMagnify) { - WinIndx = kMagStateMagnifgy; - } else -#endif - { - WinIndx = kMagStateNormal; - } - - if (! HavePositionWins[WinIndx]) { - WinPositionWinsH[WinIndx] = leftPos; - WinPositionWinsV[WinIndx] = topPos; - HavePositionWins[WinIndx] = true; - } else { - leftPos = WinPositionWinsH[WinIndx]; - topPos = WinPositionWinsV[WinIndx]; - } - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - XSetWindowAttributes xattr; - xattr.override_redirect = True; - xattr.background_pixel = x_black.pixel; - xattr.border_pixel = x_white.pixel; - - main_wind = XCreateWindow(x_display, rr, - 0, 0, wr, hr, 0, - CopyFromParent, /* depth */ - InputOutput, /* class */ - CopyFromParent, /* visual */ - CWOverrideRedirect | CWBackPixel | CWBorderPixel, - /* valuemask */ - &xattr /* attributes */); - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - main_wind = XCreateSimpleWindow(x_display, rootwin, - leftPos, - topPos, - NewWindowWidth, NewWindowHeight, 4, - x_white.pixel, - x_black.pixel); - } -#endif - - if (! main_wind) { - WriteExtraErr("XCreateSimpleWindow failed."); - return false; - } else { - char *win_name = - (NULL != n_arg) ? n_arg : ( -#ifdef CanGetAppPath - (NULL != app_name) ? app_name : -#endif - kStrAppName); - XSelectInput(x_display, main_wind, - ExposureMask | KeyPressMask | KeyReleaseMask - | ButtonPressMask | ButtonReleaseMask -#if UseMotionEvents - | PointerMotionMask | EnterWindowMask | LeaveWindowMask -#endif - | FocusChangeMask); - - XStoreName(x_display, main_wind, win_name); - XSetIconName(x_display, main_wind, win_name); - - { - XClassHint *hints = XAllocClassHint(); - if (hints) { - hints->res_name = kStrAppName; - hints->res_class = kStrAppName; - XSetClassHint(x_display, main_wind, hints); - XFree(hints); - } - } - - { - XWMHints *hints = XAllocWMHints(); - if (hints) { - hints->input = True; - hints->initial_state = NormalState; - hints->flags = InputHint | StateHint; - XSetWMHints(x_display, main_wind, hints); - XFree(hints); - } - - } - - XSetCommand(x_display, main_wind, argv, argc); - - /* let us handle a click on the close box */ - XSetWMProtocols(x_display, main_wind, &XA_DeleteW, 1); - -#if EnableDragDrop - XChangeProperty (x_display, main_wind, XA_DndAware, - XA_ATOM, 32, PropModeReplace, - (unsigned char *) &xdnd_version, 1); -#endif - - gc = XCreateGC(x_display, main_wind, 0, NULL); - if (NULL == gc) { - WriteExtraErr("XCreateGC failed."); - return false; - } - XSetState(x_display, gc, x_black.pixel, x_white.pixel, - GXcopy, AllPlanes); - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - XSizeHints *hints = XAllocSizeHints(); - if (hints) { - hints->min_width = NewWindowWidth; - hints->max_width = NewWindowWidth; - hints->min_height = NewWindowHeight; - hints->max_height = NewWindowHeight; - - /* - Try again to say where the window ought to go. - I've seen this described as obsolete, but it - seems to work on all x implementations tried - so far, and nothing else does. - */ - hints->x = leftPos; - hints->y = topPos; - hints->width = NewWindowWidth; - hints->height = NewWindowHeight; - - hints->flags = PMinSize | PMaxSize | PPosition | PSize; - XSetWMNormalHints(x_display, main_wind, hints); - XFree(hints); - } - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - hOffset = leftPos; - vOffset = topPos; - } -#endif - - DisconnectKeyCodes3(); - /* since will lose keystrokes to old window */ - -#if MayNotFullScreen - CurWinIndx = WinIndx; -#endif - - XMapRaised(x_display, main_wind); - -#if 0 - XSync(x_display, 0); -#endif - -#if 0 - /* - This helps in Red Hat 9 to get the new window - activated, and I've seen other programs - do similar things. - */ - /* - In current scheme, haven't closed old window - yet. If old window full screen, never receive - expose event for new one. - */ - { - XEvent event; - - do { - XNextEvent(x_display, &event); - HandleTheEvent(&event); - } while (! ((Expose == event.type) - && (event.xexpose.window == main_wind))); - } -#endif - - NeedFinishOpen1 = true; - NeedFinishOpen2 = true; - - return true; - } -} - -#if MayFullScreen -LOCALVAR bool GrabMachine = false; -#endif - -#if MayFullScreen -LOCALPROC GrabTheMachine(void) -{ -#if EnableFSMouseMotion - StartSaveMouseMotion(); -#endif -#if GrabKeysFullScreen - GrabKeyboard(); -#endif -} -#endif - -#if MayFullScreen -LOCALPROC UngrabMachine(void) -{ -#if EnableFSMouseMotion - StopSaveMouseMotion(); -#endif -#if GrabKeysFullScreen - UnGrabKeyboard(); -#endif -} -#endif - -#if EnableRecreateW -struct WState { - Window f_main_wind; - GC f_gc; -#if MayFullScreen - short f_hOffset; - short f_vOffset; - uint16_t f_ViewHSize; - uint16_t f_ViewVSize; - uint16_t f_ViewHStart; - uint16_t f_ViewVStart; -#endif -#if 1 - bool f_UseFullScreen; -#endif -#if 1 - bool f_UseMagnify; -#endif -}; -typedef struct WState WState; -#endif - -#if EnableRecreateW -LOCALPROC GetWState(WState *r) -{ - r->f_main_wind = main_wind; - r->f_gc = gc; -#if MayFullScreen - r->f_hOffset = hOffset; - r->f_vOffset = vOffset; - r->f_ViewHSize = ViewHSize; - r->f_ViewVSize = ViewVSize; - r->f_ViewHStart = ViewHStart; - r->f_ViewVStart = ViewVStart; -#endif -#if 1 - r->f_UseFullScreen = UseFullScreen; -#endif -#if 1 - r->f_UseMagnify = UseMagnify; -#endif -} -#endif - -#if EnableRecreateW -LOCALPROC SetWState(WState *r) -{ - main_wind = r->f_main_wind; - gc = r->f_gc; -#if MayFullScreen - hOffset = r->f_hOffset; - vOffset = r->f_vOffset; - ViewHSize = r->f_ViewHSize; - ViewVSize = r->f_ViewVSize; - ViewHStart = r->f_ViewHStart; - ViewVStart = r->f_ViewVStart; -#endif -#if 1 - UseFullScreen = r->f_UseFullScreen; -#endif -#if 1 - UseMagnify = r->f_UseMagnify; -#endif -} -#endif - -#if EnableRecreateW -LOCALVAR bool WantRestoreCursPos = false; -LOCALVAR uint16_t RestoreMouseH; -LOCALVAR uint16_t RestoreMouseV; -#endif - -#if EnableRecreateW -LOCALFUNC bool ReCreateMainWindow(void) -{ - WState old_state; - WState new_state; -#if IncludeHostTextClipExchange - bool OwnClipboard = false; -#endif - - if (HaveCursorHidden) { - WantRestoreCursPos = true; - RestoreMouseH = CurMouseH; - RestoreMouseV = CurMouseV; - } - - ForceShowCursor(); /* hide/show cursor api is per window */ - -#if MayNotFullScreen -#if 1 - if (! UseFullScreen) -#endif - if (main_wind) - if (! NeedFinishOpen2) - { - /* save old position */ - int xr; - int yr; - unsigned int dr; - unsigned int wr; - unsigned int hr; - unsigned int bwr; - Window rr; - Window rr2; - - /* Get connection to X Server */ - int screen = DefaultScreen(x_display); - - Window rootwin = XRootWindow(x_display, screen); - - XGetGeometry(x_display, rootwin, - &rr, &xr, &yr, &wr, &hr, &bwr, &dr); - - /* - Couldn't reliably find out where window - is now, due to what seem to be some - broken X implementations, and so instead - track how far window has moved. - */ - XSync(x_display, 0); - if (XTranslateCoordinates(x_display, main_wind, rootwin, - 0, 0, &xr, &yr, &rr2)) - { - int newposh = - WinPositionWinsH[CurWinIndx] + (xr - SavedTransH); - int newposv = - WinPositionWinsV[CurWinIndx] + (yr - SavedTransV); - if ((newposv > 0) && (newposv < hr) && (newposh < wr)) { - WinPositionWinsH[CurWinIndx] = newposh; - WinPositionWinsV[CurWinIndx] = newposv; - SavedTransH = xr; - SavedTransV = yr; - } - } - } -#endif - -#if MayFullScreen - if (GrabMachine) { - GrabMachine = false; - UngrabMachine(); - } -#endif - - GetWState(&old_state); - ZapWState(); - -#if 1 - UseMagnify = WantMagnify; -#endif -#if 1 - UseFullScreen = WantFullScreen; -#endif - - ColorTransValid = false; - - if (! CreateMainWindow()) { - CloseMainWindow(); - SetWState(&old_state); - - /* avoid retry */ -#if 1 - WantFullScreen = UseFullScreen; -#endif -#if 1 - WantMagnify = UseMagnify; -#endif - - return false; - } else { - GetWState(&new_state); - SetWState(&old_state); - -#if IncludeHostTextClipExchange - if (main_wind) { - if (XGetSelectionOwner(x_display, XA_CLIPBOARD) == - main_wind) - { - OwnClipboard = true; - } - } -#endif - - CloseMainWindow(); - - SetWState(&new_state); - -#if IncludeHostTextClipExchange - if (OwnClipboard) { - XSetSelectionOwner(x_display, XA_CLIPBOARD, - main_wind, CurrentTime); - } -#endif - } - - return true; -} -#endif - -#if 1 && 1 -enum { - kWinStateWindowed, -#if 1 - kWinStateFullScreen, -#endif - kNumWinStates -}; -#endif - -#if 1 && 1 -LOCALVAR int WinMagStates[kNumWinStates]; -#endif - -LOCALPROC ZapWinStateVars(void) -{ -#if MayNotFullScreen - { - int i; - - for (i = 0; i < kNumMagStates; ++i) { - HavePositionWins[i] = false; - } - } -#endif -#if 1 && 1 - { - int i; - - for (i = 0; i < kNumWinStates; ++i) { - WinMagStates[i] = kMagStateAuto; - } - } -#endif -} - -#if 1 -LOCALPROC ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; - -#if 1 - { - int OldWinState = - UseFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int OldMagState = - UseMagnify ? kMagStateMagnifgy : kMagStateNormal; - int NewWinState = - WantFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int NewMagState = WinMagStates[NewWinState]; - - WinMagStates[OldWinState] = OldMagState; - if (kMagStateAuto != NewMagState) { - WantMagnify = (kMagStateMagnifgy == NewMagState); - } else { - WantMagnify = false; - if (WantFullScreen) { - Window rootwin; - int xr; - int yr; - unsigned int dr; - unsigned int wr; - unsigned int hr; - unsigned int bwr; - Window rr; - - rootwin = - XRootWindow(x_display, DefaultScreen(x_display)); - XGetGeometry(x_display, rootwin, - &rr, &xr, &yr, &wr, &hr, &bwr, &dr); - if ((wr >= vMacScreenWidth * WindowScale) - && (hr >= vMacScreenHeight * WindowScale) - ) - { - WantMagnify = true; - } - } - } - } -#endif -} -#endif - -/* --- SavedTasks --- */ - -LOCALPROC LeaveBackground(void) -{ - ReconnectKeyCodes3(); - DisableKeyRepeat(); -} - -LOCALPROC EnterBackground(void) -{ - RestoreKeyRepeat(); - DisconnectKeyCodes3(); - - ForceShowCursor(); -} - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif - - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if SoundEnabled - Sound_Stop(); -#endif -} - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - - if (NeedFinishOpen2 && ! NeedFinishOpen1) { - NeedFinishOpen2 = false; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - XSetInputFocus(x_display, main_wind, - RevertToPointerRoot, CurrentTime); - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - Window rr; - int screen = DefaultScreen(x_display); - Window rootwin = XRootWindow(x_display, screen); -#if 0 - /* - This doesn't work right in Red Hat 6, and may not - be needed anymore, now that using PPosition hint. - */ - XMoveWindow(x_display, main_wind, - leftPos, topPos); - /* - Needed after XMapRaised, because some window - managers will apparently ignore where the - window was asked to be put. - */ -#endif - - XSync(x_display, 0); - /* - apparently, XTranslateCoordinates can be inaccurate - without this - */ - XTranslateCoordinates(x_display, main_wind, rootwin, - 0, 0, &SavedTransH, &SavedTransV, &rr); - } -#endif - -#if EnableRecreateW - if (WantRestoreCursPos) { -#if EnableFSMouseMotion - if (! HaveMouseMotion) -#endif - { - (void) MoveMouse(RestoreMouseH, RestoreMouseV); - WantCursorHidden = true; - } - WantRestoreCursPos = false; - } -#endif - } - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MouseConstrain(); - } -#endif - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (gTrueBackgroundFlag != gBackgroundFlag) { - gBackgroundFlag = gTrueBackgroundFlag; - if (gTrueBackgroundFlag) { - EnterBackground(); - } else { - LeaveBackground(); - } - } - - if (CurSpeedStopped != (SpeedStopped || - (gBackgroundFlag && ! RunInBackground))) - { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - -#if MayFullScreen - if (gTrueBackgroundFlag -#if 1 - && WantFullScreen -#endif - ) - { - /* - Since often get here on Ubuntu Linux 5.10 - running on a slow machine (emulated) when - attempt to enter full screen, don't abort - full screen, but try to fix it. - */ -#if 0 - ToggleWantFullScreen(); -#else - XRaiseWindow(x_display, main_wind); - XSetInputFocus(x_display, main_wind, - RevertToPointerRoot, CurrentTime); -#endif - } -#endif - -#if EnableRecreateW - if (0 -#if 1 - || (UseMagnify != WantMagnify) -#endif -#if 1 - || (UseFullScreen != WantFullScreen) -#endif - ) - { - (void) ReCreateMainWindow(); - } -#endif - - -#if MayFullScreen - if (GrabMachine != ( -#if 1 - UseFullScreen && -#endif - ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - GrabMachine = ! GrabMachine; - if (GrabMachine) { - GrabTheMachine(); - } else { - UngrabMachine(); - } - } -#endif - -#if IncludeSonyNew - if (vSonyNewDiskWanted) { -#if IncludeSonyNameNew - if (vSonyNewDiskName != NotAPbuf) { - uint8_t * NewDiskNameDat; - if (MacRomanTextToNativePtr(vSonyNewDiskName, true, - &NewDiskNameDat)) - { - MakeNewDisk(vSonyNewDiskSize, (char *)NewDiskNameDat); - free(NewDiskNameDat); - } - PbufDispose(vSonyNewDiskName); - vSonyNewDiskName = NotAPbuf; - } else -#endif - { - MakeNewDiskAtDefault(vSonyNewDiskSize); - } - vSonyNewDiskWanted = false; - /* must be done after may have gotten disk */ - } -#endif - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif - - if (HaveCursorHidden != (WantCursorHidden - && ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - HaveCursorHidden = ! HaveCursorHidden; - if (HaveCursorHidden) { - XDefineCursor(x_display, main_wind, blankCursor); - } else { - XUndefineCursor(x_display, main_wind); - } - } -} - -/* --- command line parsing --- */ - -LOCALFUNC bool ScanCommandLine(void) -{ - char *pa; - int i = 1; - -label_retry: - if (i < argc) { - pa = argv[i++]; - if ('-' == pa[0]) { - if ((0 == strcmp(pa, "--display")) - || (0 == strcmp(pa, "-display"))) - { - if (i < argc) { - display_name = argv[i++]; - goto label_retry; - } - } else - if ((0 == strcmp(pa, "--rom")) - || (0 == strcmp(pa, "-r"))) - { - if (i < argc) { - rom_path = argv[i++]; - goto label_retry; - } - } else - if (0 == strcmp(pa, "-n")) - { - if (i < argc) { - n_arg = argv[i++]; - goto label_retry; - } - } else - if (0 == strcmp(pa, "-d")) - { - if (i < argc) { - d_arg = argv[i++]; - goto label_retry; - } - } else -#ifndef UsingAlsa -#define UsingAlsa 0 -#endif - -#if UsingAlsa - if ((0 == strcmp(pa, "--alsadev")) - || (0 == strcmp(pa, "-alsadev"))) - { - if (i < argc) { - alsadev_name = argv[i++]; - goto label_retry; - } - } else -#endif -#if 0 - if (0 == strcmp(pa, "-l")) { - SpeedValue = 0; - goto label_retry; - } else -#endif - { - MacMsg(kStrBadArgTitle, kStrBadArgMessage, false); - } - } else { - (void) Sony_Insert1(pa, false); - goto label_retry; - } - } - - return true; -} - -/* --- main program flow --- */ - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ -#if EnableFSMouseMotion - if (HaveMouseMotion) { - AutoScrollScreen(); - } -#endif - DrawChangesAndClear(); - XFlush(x_display); -} - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -LOCALPROC WaitForTheNextEvent(void) -{ - XEvent event; - - XNextEvent(x_display, &event); - HandleTheEvent(&event); -} - -LOCALPROC CheckForSystemEvents(void) -{ - int i = 10; - - while ((XEventsQueued(x_display, QueuedAfterReading) > 0) - && (--i >= 0)) - { - WaitForTheNextEvent(); - } -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ -label_retry: - CheckForSystemEvents(); - CheckForSavedTasks(); - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - WaitForTheNextEvent(); - goto label_retry; - } - - if (ExtraTimeNotOver()) { - struct timespec rqt; - struct timespec rmt; - - int32_t TimeDiff = GetTimeDiff(); - if (TimeDiff < 0) { - rqt.tv_sec = 0; - rqt.tv_nsec = (- TimeDiff) * 1000; - (void) nanosleep(&rqt, &rmt); - } - goto label_retry; - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - if ((! gBackgroundFlag) -#if UseMotionEvents - && (! CaughtMouse) -#endif - ) - { - CheckMouseState(); - } - - OnTrueTime = TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime); -#endif -} - -/* --- platform independent code can be thought of as going here --- */ - -#include "PROGMAIN.h" - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); - ZapWinStateVars(); -} - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif -#if WantScalingBuff - ReserveAllocOneBlock(&ScalingBuff, - ScalingBuffsz, 5, false); -#endif -#if WantScalingTabl - ReserveAllocOneBlock(&ScalingTabl, - ScalingTablsz, 5, false); -#endif - -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)calloc(1, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALPROC UnallocMemory(void) -{ - if (nullpr != ReserveAllocBigBlock) { - free((char *)ReserveAllocBigBlock); - } -} - -#ifdef HaveAppPathLink -LOCALFUNC bool ReadLink_Alloc(char *path, char **r) -{ - /* - This should work to find size: - - struct stat r; - - if (lstat(path, &r) != -1) { - r = r.st_size; - IsOk = true; - } - - But observed to return 0 in Ubuntu 10.04 x86-64 - */ - - char *s; - int sz; - char *p; - bool IsOk = false; - size_t s_alloc = 256; - -label_retry: - s = (char *)malloc(s_alloc); - if (NULL == s) { - fprintf(stderr, "malloc failed.\n"); - } else { - sz = readlink(path, s, s_alloc); - if ((sz < 0) || (sz >= s_alloc)) { - free(s); - if (sz == s_alloc) { - s_alloc <<= 1; - goto label_retry; - } else { - fprintf(stderr, "readlink failed.\n"); - } - } else { - /* ok */ - p = (char *)malloc(sz + 1); - if (NULL == p) { - fprintf(stderr, "malloc failed.\n"); - } else { - (void) memcpy(p, s, sz); - p[sz] = 0; - *r = p; - IsOk = true; - } - free(s); - } - } - - return IsOk; -} -#endif - -#ifdef HaveSysctlPath -LOCALFUNC bool ReadKernProcPathname(char **r) -{ - size_t s_alloc; - char *s; - int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PATHNAME, - -1 - }; - bool IsOk = false; - - if (0 != sysctl(mib, sizeof(mib) / sizeof(int), - NULL, &s_alloc, NULL, 0)) - { - fprintf(stderr, "sysctl failed.\n"); - } else { - s = (char *)malloc(s_alloc); - if (NULL == s) { - fprintf(stderr, "malloc failed.\n"); - } else { - if (0 != sysctl(mib, sizeof(mib) / sizeof(int), - s, &s_alloc, NULL, 0)) - { - fprintf(stderr, "sysctl 2 failed.\n"); - } else { - *r = s; - IsOk = true; - } - if (! IsOk) { - free(s); - } - } - } - - return IsOk; -} -#endif - -#ifdef CanGetAppPath -LOCALFUNC bool Path2ParentAndName(char *path, - char **parent, char **name) -{ - bool IsOk = false; - - char *t = strrchr(path, '/'); - if (NULL == t) { - fprintf(stderr, "no directory.\n"); - } else { - int par_sz = t - path; - char *par = (char *)malloc(par_sz + 1); - if (NULL == par) { - fprintf(stderr, "malloc failed.\n"); - } else { - (void) memcpy(par, path, par_sz); - par[par_sz] = 0; - { - int s_sz = strlen(path); - int child_sz = s_sz - par_sz - 1; - char *child = (char *)malloc(child_sz + 1); - if (NULL == child) { - fprintf(stderr, "malloc failed.\n"); - } else { - (void) memcpy(child, t + 1, child_sz); - child[child_sz] = 0; - - *name = child; - IsOk = true; - /* free(child); */ - } - } - if (! IsOk) { - free(par); - } else { - *parent = par; - } - } - } - - return IsOk; -} -#endif - -#ifdef CanGetAppPath -LOCALFUNC bool InitWhereAmI(void) -{ - char *s; - - if (! -#ifdef HaveAppPathLink - ReadLink_Alloc(TheAppPathLink, &s) -#endif -#ifdef HaveSysctlPath - ReadKernProcPathname(&s) -#endif - ) - { - fprintf(stderr, "InitWhereAmI fails.\n"); - } else { - if (! Path2ParentAndName(s, &app_parent, &app_name)) { - fprintf(stderr, "Path2ParentAndName fails.\n"); - } else { - /* ok */ - /* - fprintf(stderr, "parent = %s.\n", app_parent); - fprintf(stderr, "name = %s.\n", app_name); - */ - } - - free(s); - } - - return true; /* keep going regardless */ -} -#endif - -#ifdef CanGetAppPath -LOCALPROC UninitWhereAmI(void) -{ - MayFree(app_parent); - MayFree(app_name); -} -#endif - -LOCALFUNC bool InitOSGLU(void) -{ - if (AllocMemory()) -#ifdef CanGetAppPath - if (InitWhereAmI()) -#endif -#if dbglog_HAVE - if (dbglog_open()) -#endif - if (ScanCommandLine()) - if (LoadMacRom()) - if (LoadInitialImages()) - if (InitLocationDat()) -#if SoundEnabled - if (Sound_Init()) -#endif - if (Screen_Init()) - if (CreateMainWindow()) - if (KC2MKCInit()) - if (WaitForRom()) - { - return true; - } - return false; -} - -LOCALPROC UnInitOSGLU(void) -{ - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - - RestoreKeyRepeat(); -#if MayFullScreen - UngrabMachine(); -#endif -#if SoundEnabled - Sound_Stop(); -#endif -#if SoundEnabled - Sound_UnInit(); -#endif -#if IncludeHostTextClipExchange - FreeClipBuffer(); -#endif -#if IncludePbufs - UnInitPbufs(); -#endif - UnInitDrives(); - - ForceShowCursor(); - if (blankCursor != None) { - XFreeCursor(x_display, blankCursor); - } - - if (image != NULL) { - XDestroyImage(image); - } -#if 1 - if (Scaled_image != NULL) { - XDestroyImage(Scaled_image); - } -#endif - - CloseMainWindow(); - if (x_display != NULL) { - XCloseDisplay(x_display); - } - -#if dbglog_HAVE - dbglog_close(); -#endif - -#ifdef CanGetAppPath - UninitWhereAmI(); -#endif - UnallocMemory(); - - CheckSavedMacMsg(); -} - -int main(int argc, char **argv) -{ - argc = argc; - argv = argv; - - ZapOSGLUVars(); - if (InitOSGLU()) { - ProgramMain(); - } - UnInitOSGLU(); - - return 0; -} diff --git a/src/UI/_deprecated/WIN32/DBGLOG.c b/src/UI/_deprecated/WIN32/DBGLOG.c deleted file mode 100644 index bbf90ef..0000000 --- a/src/UI/_deprecated/WIN32/DBGLOG.c +++ /dev/null @@ -1,79 +0,0 @@ -/* --- sending debugging info to file --- */ - -#include -#include -#include "SYSDEPNS.h" -#include "UI/WIN32/OSGLUWIN.h" - -#if dbglog_HAVE - -LOCALVAR HANDLE dbglog_File = INVALID_HANDLE_VALUE; - -LOCALFUNC bool dbglog_open0(void) -{ - TCHAR pathName[_MAX_PATH]; - TCHAR Child0[] = TEXT("\\dbglog.txt"); - size_t newlen; - - if (GetAppDir(pathName)) { - newlen = _tcslen(pathName) + _tcslen(Child0); - if (newlen + 1 < _MAX_PATH) { - _tcscat(pathName, Child0); - - dbglog_File = CreateFile( - pathName, /* pointer to name of the file */ - GENERIC_READ + GENERIC_WRITE, - /* access (read-write) mode */ - 0, /* share mode */ - NULL, /* pointer to security descriptor */ - OPEN_ALWAYS, /* how to create */ - FILE_ATTRIBUTE_NORMAL, /* file attributes */ - NULL /* handle to file with attributes to copy */ - ); - if (INVALID_HANDLE_VALUE == dbglog_File) { - /* report error (how?) */ - } else if (SetFilePointer( - dbglog_File, /* handle of file */ - 0, /* number of bytes to move file pointer */ - nullpr, - /* address of high-order word of distance to move */ - FILE_BEGIN /* how to move */ - ) != 0) - { - /* report error (how?) */ - } - } - } - - return (INVALID_HANDLE_VALUE != dbglog_File); -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ - DWORD BytesWritten; - - if (INVALID_HANDLE_VALUE != dbglog_File) { - if (! WriteFile(dbglog_File, /* handle of file to read */ - (LPVOID)s, /* address of buffer that receives data */ - (DWORD)L, /* number of bytes to read */ - &BytesWritten, /* address of number of bytes read */ - nullpr) /* address of structure for data */ - || ((uint32_t)BytesWritten != L)) - { - /* report error (how?) */ - } - } -} - -LOCALPROC dbglog_close0(void) -{ - if (INVALID_HANDLE_VALUE != dbglog_File) { - if (! SetEndOfFile(dbglog_File)) { - /* report error (how?) */ - } - (void) CloseHandle(dbglog_File); - dbglog_File = INVALID_HANDLE_VALUE; - } -} - -#endif diff --git a/src/UI/_deprecated/WIN32/INTLKBRD.c b/src/UI/_deprecated/WIN32/INTLKBRD.c deleted file mode 100644 index 391349c..0000000 --- a/src/UI/_deprecated/WIN32/INTLKBRD.c +++ /dev/null @@ -1,1129 +0,0 @@ -/* keyboard */ - -#include -#include -#include "SYSDEPNS.h" -#include "UI/WIN32/OSGLUWIN.h" - -#if ItnlKyBdFix -LOCALPROC VkSwapZY(void) -{ - VkMapA['Z'] = 'Y'; - VkMapA['Y'] = 'Z'; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkSwapGraveQuote(void) -{ - VkMapA[myVK_Grave] = myVK_SingleQuote; - VkMapA[myVK_SingleQuote] = myVK_Grave; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkSwapSlashSubtract(void) -{ - VkMapA[myVK_Slash] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkSwapAQZWGraveQuote(void) -{ - VkSwapGraveQuote(); - VkMapA['A'] = 'Q'; - VkMapA['Q'] = 'A'; - VkMapA['Z'] = 'W'; - VkMapA['W'] = 'Z'; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapBelgian(void) -{ - VkSwapAQZWGraveQuote(); - VkMapA['M'] = myVK_SemiColon; - VkMapA[myVK_SemiColon] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Equal; - VkMapA[myVK_Equal] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_Period; - VkMapA[myVK_Period] = myVK_Comma; - VkMapA[myVK_Comma] = 'M'; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapSwiss(void) -{ - VkSwapZY(); - VkMapA[myVK_OEM_8] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_SingleQuote; - VkMapA[myVK_SingleQuote] = myVK_SemiColon; - VkMapA[myVK_SemiColon] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_Grave; - VkMapA[myVK_Grave] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_Equal; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapDanish(void) -{ - VkMapA[myVK_Equal] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_Grave; - VkMapA[myVK_Grave] = myVK_SemiColon; - VkMapA[myVK_SemiColon] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Equal; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapBritish(void) -{ - VkMapA[myVK_OEM_8] = myVK_Grave; - VkMapA[myVK_Grave] = myVK_SingleQuote; - VkMapA[myVK_SingleQuote] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_OEM_102; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapSpanish(void) -{ - VkMapA[myVK_SemiColon] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_Grave; - VkMapA[myVK_Grave] = myVK_SemiColon; - - VkMapA[myVK_RightBracket] = myVK_Equal; - VkMapA[myVK_Equal] = myVK_RightBracket; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapDutch(void) -{ - VkSwapGraveQuote(); - VkMapA[myVK_SemiColon] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_Equal; - VkMapA[myVK_Equal] = myVK_SemiColon; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapGreekIBM(void) -{ - VkSwapSlashSubtract(); - VkMapA[myVK_LeftBracket] = myVK_Equal; - VkMapA[myVK_Equal] = myVK_LeftBracket; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapFrench(void) -{ - VkSwapAQZWGraveQuote(); - VkMapA['M'] = myVK_SemiColon; - VkMapA[myVK_SemiColon] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_Comma] = 'M'; - VkMapA[myVK_Period] = myVK_Comma; - VkMapA[myVK_Slash] = myVK_Period; - VkMapA[myVK_OEM_8] = myVK_Slash; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapGerman(void) -{ - VkSwapZY(); - VkMapSpanish(); -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapBosnian(void) -{ - VkSwapZY(); - /* not in Windows 95 */ - VkSwapSlashSubtract(); -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapBulgarian(void) -{ - VkMapA[myVK_OEM_8] = myVK_Comma; - VkMapA[myVK_Comma] = 'Q'; - VkMapA['Q'] = myVK_Period; - VkMapA[myVK_Period] = myVK_Equal; -} -#endif - -#if ItnlKyBdFix -LOCALPROC VkMapFromLayout(uimr sv) -{ - int i; - - for (i = 0; i < 256; ++i) { - VkMapA[i] = i; - } - - switch (sv) { - case 0x00000409: - /* United States 101 */ - break; - case 0x0000041c: - /* Albanian; */ - VkSwapZY(); - break; - case 0x0000042B: - /* Armenian Eastern; */ - VkMapDutch(); - break; - case 0x0001042B: - /* Armenian Western; */ - VkMapDutch(); - break; - case 0x0000042C: - /* not in Windows 95 */ - /* Azeri Latin */ - VkMapBritish(); - break; - case 0x0001080C: - /* Belgian (comma) */ - VkMapBelgian(); - break; - case 0x0000080c: - /* Belgian French */ - VkMapBelgian(); - break; - case 0x00000813: - /* not in Windows 95 */ - /* Belgian (period); */ - VkMapBelgian(); - break; - case 0x0000141A: - /* not in Windows 95 */ - /* Bosnian */ - VkMapBosnian(); - break; - case 0x00000809: - /* British / United Kingdom */ - VkMapBritish(); - break; - case 0x00000452: - /* not in Windows 95 */ - /* United Kingdom Extended */ - VkMapBritish(); - break; - case 0x00000402: - /* Bulgarian */ - /* not same in Windows 95 */ - VkMapBulgarian(); - break; - case 0x00030402: - /* Bulgarian */ - VkMapBulgarian(); - break; - case 0x00020402: - /* Bulgarian (Phonetic) */ - VkMapBosnian(); - break; - case 0x00001009: - /* Canadian Multilingual */ - /* not in Windows 95 */ - VkSwapGraveQuote(); - break; - case 0x00011009: - /* Canadian Standard */ - VkSwapGraveQuote(); - break; - case 0x0000041a: - /* Croatian */ - VkMapBosnian(); - break; - case 0x00000405: - /* Czech */ - VkMapBosnian(); -#if 0 - /* but Windows 7 gives */ - VkSwapZY(); - VkMapA[myVK_Equal] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_Equal; -#endif - break; - case 0x00020405: - /* Czech (Programmers) */ - /* only in Windows 95 */ - /* VkSwapZY(); */ - break; - case 0x00010405: - /* Czech (Qwerty) */ - /* only in Windows 95 */ - /* VkSwapZY(); */ - break; - case 0x00000406: - /* Danish */ - VkMapDanish(); - break; - case 0x00000413: - /* Dutch */ - VkMapDutch(); - break; - case 0x00000425: - /* Estonian */ - VkMapA[myVK_Grave] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_SingleQuote; - VkMapA[myVK_SingleQuote] = myVK_Grave; - /* only in Windows 95 ? */ - /* VkMapA[VK_DECIMAL] = VK_DELETE; */ - break; - case 0x00000438: - /* Faeroe Islands */ - VkMapDanish(); - break; - case 0x0000040b: - /* Finnish */ - VkMapDanish(); - break; - case 0x0001083B: - /* not in Windows 95 */ - /* Finnish with Sami */ - VkMapDanish(); - break; - case 0x0000040c: - /* v = kKbdFrench; */ - /* French */ - VkMapFrench(); - break; - case 0x00000c0c: - /* French Canadian */ - VkSwapGraveQuote(); - break; - case 0x00011809: - /* not in Windows 95 */ - /* Gaelic */ - VkMapBritish(); - break; - case 0x00010407: - /* German (IBM) */ - VkMapGerman(); - break; - case 0x00000407: - /* German (Standard) */ - VkMapGerman(); - break; - case 0x00010408: - /* Greek IBM 220 */ - /* not in Windows 95 */ - VkMapGreekIBM(); - break; - case 0x00030408: - /* Greek IBM 319 */ - /* not in Windows 95 */ - VkMapGreekIBM(); - break; - case 0x00020408: - /* Greek Latin IBM 220 */ - /* not in Windows 95 */ - VkSwapSlashSubtract(); - break; - case 0x00040408: - /* Greek Latin IBM 319 */ - /* not in Windows 95 */ - VkSwapSlashSubtract(); - break; - case 0x0000040e: - /* Hungarian */ - VkMapBosnian(); - VkMapA[myVK_Grave] = '0'; - VkMapA['0'] = myVK_Grave; - break; - case 0x0001040E: - /* Hungarian (101 Keys) */ - VkMapA[myVK_Grave] = '0'; - VkMapA['0'] = myVK_Grave; - break; - case 0x0000040f: - /* Icelandic */ - VkMapDanish(); - break; - case 0x00001809: - /* Irish */ - VkMapBritish(); - break; - case 0x00000410: - /* Italian */ - VkMapSpanish(); - break; - case 0x00010410: - /* Italian 142 */ - VkMapSpanish(); - break; - case 0x0000080a: - /* Latin American */ - VkMapSpanish(); - break; - case 0x0000046E: - /* Luxembourgish */ - VkMapSwiss(); - break; - case 0x00000414: - /* Norwegian */ - VkMapDanish(); - break; - case 0x0000043B: - /* Norwegian with Sami */ - VkMapDanish(); - break; - case 0x00010415: - /* Polish (214) */ - VkSwapZY(); - /* not in windows 95 */ - VkMapA[myVK_Equal] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_Equal; - break; - case 0x00010416: - /* Porguguese (Brazilian ABNT2) */ - /* VkMapA[myVK_OEM_8] = ??; */ - /* VkMapA[VK_SEPARATOR] = ??; */ - break; - case 0x00000816: - /* Porguguese (Standard) */ - VkMapA[myVK_SemiColon] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_Equal; - VkMapA[myVK_Equal] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_Grave; - VkMapA[myVK_Grave] = myVK_SemiColon; - break; - case 0x00000418: - /* Romanian (Legacy) */ - VkSwapZY(); - /* only in Windows 95 */ - /* VkSwapSlashSubtract(); */ - break; - case 0x0002083B: - /* Sami Extended Finland-Sweden */ - VkMapDanish(); - break; - case 0x0001043B: - /* Sami Extended Norway */ - VkMapDanish(); - break; - case 0x00010C1A: - /* in Windows 95 */ - /* Serbian (Latin) */ - VkSwapZY(); - break; - case 0x0000081A: - /* not in Windows 95 */ - /* Serbian (Latin) */ - VkMapBosnian(); - break; - case 0x0000041b: - /* Slovak */ - VkMapBosnian(); - /* not in Windows 95 */ - VkMapA[myVK_OEM_8] = myVK_Equal; - break; - case 0x00000424: - /* Slovenian */ - VkMapBosnian(); - break; - case 0x0000040A: - /* Spanish, not windows 95 */ - VkMapSpanish(); - break; - case 0x0001040A: - /* Spanish Variation, not windows 95 */ - VkMapA[myVK_OEM_8] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_Grave; - VkMapA[myVK_Grave] = myVK_SemiColon; - VkMapA[myVK_SemiColon] = myVK_RightBracket; - VkMapA[myVK_RightBracket] = myVK_LeftBracket; - VkMapA[myVK_LeftBracket] = myVK_Equal; - break; - case 0x00000c0a: - /* kKbdSpanish; */ - /* Spanish Modern, windows 95 */ - VkMapSpanish(); - break; - case 0x00000403: - /* Spanish Traditional */ - VkMapSpanish(); - break; - case 0x0000041d: - /* Swedish */ - VkMapDanish(); - break; - case 0x0000083B: - /* not in windows 95 */ - /* Swedish with Sami */ - VkMapDanish(); - break; - case 0x0000100c: - /* Swiss French */ - VkMapSwiss(); - break; - case 0x00000807: - /* Swiss German */ - VkMapSwiss(); - break; - case 0x0000085D: - /* Inuktitut Latin */ - /* in windows 7, not XP */ - VkMapBritish(); - break; - case 0x0001045D: - /* Inuktitut - Naqittaut */ - VkMapBritish(); - break; - case 0x0000046F: - /* Greenlandic */ - VkMapDanish(); - break; - case 0x00020427: - /* Lithuanian Standard */ - VkMapDanish(); - break; - case 0x0000042f: - /* Macedonian (FYROM) - Standard */ - VkMapBosnian(); - break; - case 0x0000042E: - /* Sorbian Standard (Legacy) */ - VkMapGerman(); - break; - case 0x0001042E: - /* Sorbian Extended */ - VkMapGerman(); - break; - case 0x0002042E: - /* Sorbian Standard */ - VkMapGerman(); - break; - case 0x00000488: - /* Wolof */ - VkMapFrench(); - break; - case 0x0000041f: - /* Turkish (Q type) */ - /* windows 95 */ - /* VkMapA[myVK_Equal] = myVK_Subtract; */ - /* VkMapA[myVK_Subtract] = myVK_Equal; */ - /* not windows 95 */ - VkMapA[myVK_OEM_8] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Equal; - - VkMapA[myVK_Comma] = myVK_BackSlash; - VkMapA[myVK_BackSlash] = myVK_Period; - VkMapA[myVK_Period] = myVK_Slash; - VkMapA[myVK_Slash] = myVK_Comma; - break; - case 0x00010409: - /* United States Dvorak */ - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_RightBracket] = myVK_Equal; - VkMapA[myVK_SingleQuote] = 'Q'; - VkMapA[myVK_Comma] = 'W'; - VkMapA[myVK_Period] = 'E'; - VkMapA['P'] = 'R'; - VkMapA['Y'] = 'T'; - VkMapA['F'] = 'Y'; - VkMapA['G'] = 'U'; - VkMapA['C'] = 'I'; - VkMapA['R'] = 'O'; - VkMapA['L'] = 'P'; - VkMapA[myVK_Slash] = myVK_LeftBracket; - VkMapA[myVK_Equal] = myVK_RightBracket; - VkMapA['O'] = 'S'; - VkMapA['E'] = 'D'; - VkMapA['U'] = 'F'; - VkMapA['I'] = 'G'; - VkMapA['D'] = 'H'; - VkMapA['H'] = 'J'; - VkMapA['T'] = 'K'; - VkMapA['N'] = 'L'; - VkMapA['S'] = myVK_SemiColon; - VkMapA[myVK_Subtract] = myVK_SingleQuote; - VkMapA[myVK_SemiColon] = 'Z'; - VkMapA['Q'] = 'X'; - VkMapA['J'] = 'C'; - VkMapA['K'] = 'V'; - VkMapA['X'] = 'B'; - VkMapA['B'] = 'N'; - VkMapA['W'] = myVK_Comma; - VkMapA['V'] = myVK_Period; - VkMapA['Z'] = myVK_Slash; - break; -#if 0 - /* too complicated, don't bother with */ - case 0x0x00000426: - /* Latvian */ - VkMapA['F'] = myVK_Equal; - VkMapA['G'] = 'W'; - VkMapA['J'] = 'E'; - VkMapA['M'] = 'T'; - VkMapA['V'] = 'Y'; - VkMapA['N'] = 'U'; - VkMapA['Z'] = 'I'; - VkMapA['W'] = 'O'; - VkMapA['X'] = 'P'; - VkMapA['Y'] = myVK_LeftBracket; - VkMapA['H'] = myVK_RightBracket; - VkMapA[myVK_SemiColon] = 'A'; - VkMapA['U'] = 'S'; - VkMapA['S'] = 'D'; - VkMapA['I'] = 'F'; - VkMapA['L'] = 'G'; - VkMapA['D'] = 'H'; - VkMapA['A'] = 'J'; - VkMapA['T'] = 'K'; - VkMapA['E'] = 'L'; - VkMapA['C'] = myVK_SemiColon; - VkMapA[myVK_LeftBracket] = 'Z'; - VkMapA['B'] = 'X'; - VkMapA[myVK_RightBracket] = 'C'; - VkMapA['K'] = 'V'; - VkMapA['P'] = 'B'; - VkMapA['O'] = 'N'; - VkMapA[myVK_OEM_8] = 'M'; - break; - case 0x0001041F: - /* Turkish (F type) */ - - VkMapA[myVK_Equal] = myVK_Subtract; - VkMapA[myVK_Subtract] = myVK_Equal; - VkMapA['F'] = 'Q'; - VkMapA['G'] = 'W'; - VkMapA[myVK_SemiColon] = 'E'; - VkMapA['I'] = 'R'; - VkMapA['O'] = 'T'; - VkMapA['D'] = 'Y'; - VkMapA['R'] = 'U'; - VkMapA['N'] = 'I'; - VkMapA['H'] = 'O'; - VkMapA['Q'] = myVK_LeftBracket; - VkMapA['W'] = myVK_RightBracket; - VkMapA['U'] = 'A'; - VkMapA[myVK_LeftBracket] = 'S'; - VkMapA['E'] = 'D'; - VkMapA['A'] = 'F'; - VkMapA[myVK_RightBracket] = 'G'; - VkMapA['T'] = 'H'; - VkMapA['K'] = 'J'; - VkMapA['M'] = 'K'; - VkMapA['Y'] = myVK_SemiColon; - VkMapA['X'] = myVK_BackSlash; - VkMapA['J'] = 'Z'; - VkMapA[myVK_BackSlash] = 'X'; - VkMapA['V'] = 'C'; - VkMapA['C'] = 'V'; - VkMapA[myVK_Slash] = 'B'; - VkMapA['Z'] = 'N'; - VkMapA['S'] = 'M'; - VkMapA['B'] = myVK_Comma; - VkMapA[myVK_Comma] = myVK_Slash; - break; - case 0x00030409: - /* United States LH Dvorak */ - VkMapA[myVK_LeftBracket] = '1'; - VkMapA[myVK_RightBracket] = '2'; - VkMapA[myVK_Slash] = '3'; - VkMapA['P'] = '4'; - VkMapA['F'] = '5'; - VkMapA['M'] = '6'; - VkMapA['L'] = '7'; - VkMapA['J'] = '8'; - VkMapA['4'] = '9'; - VkMapA['3'] = '0'; - VkMapA['2'] = myVK_Subtract; - VkMapA['1'] = myVK_Equal; - VkMapA[myVK_SemiColon] = 'Q'; - VkMapA['Q'] = 'W'; - VkMapA['B'] = 'E'; - VkMapA['Y'] = 'R'; - VkMapA['U'] = 'T'; - VkMapA['R'] = 'Y'; - VkMapA['S'] = 'U'; - VkMapA['O'] = 'I'; - VkMapA[myVK_Period] = 'O'; - VkMapA['6'] = 'P'; - VkMapA['5'] = myVK_LeftBracket; - VkMapA[myVK_Equal] = myVK_RightBracket; - VkMapA[myVK_Subtract] = 'A'; - VkMapA['K'] = 'S'; - VkMapA['C'] = 'D'; - VkMapA['D'] = 'F'; - VkMapA['T'] = 'G'; - VkMapA['E'] = 'J'; - VkMapA['A'] = 'K'; - VkMapA['Z'] = 'L'; - VkMapA['8'] = myVK_SemiColon; - VkMapA['7'] = myVK_SingleQuote; - VkMapA[myVK_SingleQuote] = 'Z'; - VkMapA['G'] = 'C'; - VkMapA['W'] = 'B'; - VkMapA['I'] = 'M'; - VkMapA['0'] = myVK_Period; - VkMapA['9'] = myVK_Slash; - break; - case 0x00040409: - /* United States RH Dvorak */ - VkMapA['J'] = '5'; - VkMapA['L'] = '6'; - VkMapA['M'] = '7'; - VkMapA['F'] = '8'; - VkMapA['P'] = '9'; - VkMapA[myVK_Slash] = '0'; - VkMapA[myVK_LeftBracket] = myVK_Subtract; - VkMapA[myVK_RightBracket] = myVK_Equal; - VkMapA['5'] = 'Q'; - VkMapA['6'] = 'W'; - VkMapA['Q'] = 'E'; - VkMapA[myVK_Period] = 'R'; - VkMapA['O'] = 'T'; - VkMapA['R'] = 'Y'; - VkMapA['S'] = 'U'; - VkMapA['U'] = 'I'; - VkMapA['Y'] = 'O'; - VkMapA['B'] = 'P'; - VkMapA[myVK_SemiColon] = myVK_LeftBracket; - VkMapA[myVK_Equal] = myVK_RightBracket; - VkMapA['7'] = 'A'; - VkMapA['8'] = 'S'; - VkMapA['Z'] = 'D'; - VkMapA['A'] = 'F'; - VkMapA['E'] = 'G'; - VkMapA['T'] = 'J'; - VkMapA['D'] = 'K'; - VkMapA['C'] = 'L'; - VkMapA['K'] = myVK_SemiColon; - VkMapA[myVK_Subtract] = myVK_SingleQuote; - VkMapA['9'] = 'Z'; - VkMapA['0'] = 'X'; - VkMapA['X'] = 'C'; - VkMapA[myVK_Comma] = 'V'; - VkMapA['I'] = 'B'; - VkMapA['W'] = 'M'; - VkMapA['V'] = myVK_Comma; - VkMapA['G'] = myVK_Period; - VkMapA[myVK_SingleQuote] = myVK_Slash; - break; -#endif -#if 0 - case 0x0000082C: - /* not in Windows 95 */ - /* Azeri Cyrillic */ - break; - case 0x00000423: - /* Belarusian */ - break; - case 0x00000445: - /* not in Windows 95 */ - /* Bengali */ - break; - case 0x00010445: - /* not in Windows 95 */ - /* Bengali (Inscript) */ - break; - case 0x0000201A: - /* not in Windows 95 */ - /* Bosnian Cyrillic*/ - break; - case 0x00010402: - /* Bulgarian Latin */ -#if 0 /* Only in Windows 95 */ - VkMapA['J'] = 'Q'; - VkMapA['C'] = 'W'; - VkMapA['U'] = 'E'; - VkMapA['K'] = 'R'; - VkMapA['E'] = 'T'; - VkMapA['N'] = 'Y'; - VkMapA['G'] = 'U'; - VkMapA[myVK_SemiColon] = 'I'; - VkMapA[myVK_OEM_102] = 'O'; - VkMapA['Z'] = 'P'; - VkMapA['H'] = myVK_LeftBracket; - VkMapA['F'] = 'A'; - VkMapA['Y'] = 'S'; - VkMapA['W'] = 'D'; - VkMapA['A'] = 'F'; - VkMapA['P'] = 'G'; - VkMapA['R'] = 'H'; - VkMapA['O'] = 'J'; - VkMapA['L'] = 'K'; - VkMapA['D'] = 'L'; - VkMapA['V'] = myVK_SemiColon; - VkMapA[myVK_LeftBracket] = 'Z'; - VkMapA['S'] = 'X'; - VkMapA['M'] = 'C'; - VkMapA['I'] = 'V'; - VkMapA['T'] = 'B'; - VkMapA['X'] = 'N'; - VkMapA['B'] = 'M'; - VkMapA['Q'] = myVK_OEM_102; -#endif - break; - case 0x00000408: - /* Greek */ - break; - case 0x00050408: - /* Greek Latin */ - break; - case 0x00060408: - /* Greek Polytonic */ - break; - case 0x0000043F: - /* Kazakh */ - break; - case 0x00000440: - /* Kyrgyz Cyrillic */ - break; - case 0x00010426: - /* Latvian Latin */ - break; - case 0x00010427: - /* Lithuanian */ - break; - case 0x00000427: - /* Lithuanian (IBM) */ - break; - case 0x0000044C: - /* Malayalam */ - break; - case 0x0000042f: - /* Macedonian (FYROM) */ - break; - case 0x0000043A: - /* Maltese 47-key */ - break; - case 0x0001043A: - /* Maltese 48-key */ - break; - case 0x00000481: - /* Maori */ - break; - case 0x00000450: - /* Mongolian Cyrillic */ - break; - case 0x00000461: - /* Nepali */ - break; - case 0x00000463: - /* Pashto */ - break; - case 0x00000415: - /* Polish (Programmers) */ - break; - case 0x00000416: - /* Porguguese (Brazilian standard) */ - break; - case 0x00000419: - /* Russian */ - break; - case 0x00010419: - /* Russian (Typewriter) */ - break; - case 0x00000c1a: - /* Serbian */ - break; - case 0x0001041B: - /* Slovak (Qwerty) */ - break; - case 0x00000444: - /* Tatar */ - break; - case 0x00000422: - /* Ukrainian */ - break; - case 0x00020409: - /* United States International */ - break; - case 0x00000843: - /* Uzbek Cyrillic */ - break; - case 0x00010418: - /* Romanian (Standard) */ - break; - case 0x00020418: - /* Romanian (Programmers) */ - break; - case 0x00000401: - /* Arabic (101) */ - break; - case 0x00010401: - /* Arabic (102) */ - break; - case 0x0000044D: - /* Assamese - INSCRIPT */ - break; - case 0x0000046D: - /* Bashkir */ - break; - case 0x00040402: - /* Bulgarian (Phonetic Traditional) */ - break; - case 0x00000404: - /* Chinese (Traditional) */ - break; - case 0x00000804: - /* Chinese (Simplified) */ - break; - case 0x00000C04: - /* Chinese (Traditional, Hong Kong S.A.R.) */ - break; - case 0x00001004: - /* Chinese (Simplified, Singapore) */ - break; - case 0x00001404: - /* Chinese (Traditional, Macao S.A.R.) */ - break; - case 0x0000040D: - /* Hebrew */ - break; - case 0x00000447: - /* Gujarati */ - break; - case 0x00000468: - /* Hausa */ - break; - case 0x00010439: - /* Hindi Traditional */ - break; - case 0x00000439: - /* Devanagari - INSCRIPT */ - break; - case 0x00000465: - /* Divehi Phonetic */ - break; - case 0x00010465: - /* Divehi Typewriter */ - break; - case 0x00000437: - /* Georgian */ - break; - case 0x00010437: - /* Georgian (QWERTY) */ - break; - case 0x00020437: - /* Georgian (Ergonomic) */ - break; - case 0x00000470: - /* Igbo */ - break; - case 0x00000411: - /* Japanese */ - /* VkMapA[??] = ??; */ - break; - case 0x00000412: - /* Korean */ - /* VkMapA[VK_ZOOM] = ??; */ - /* VkMapA[VK_HELP] = VK_ZOOM; */ - /* VkMapA[??] = VK_HELP; */ - /* VkMapA[??] = ??; */ - break; - case 0x0000044B: - /* Kannada */ - break; - case 0x00000453: - /* Khmer */ - break; - case 0x00000454: - /* Lao */ - break; - case 0x00000448: - /* Oriya */ - break; - case 0x0000044E: - /* Marathi */ - break; - case 0x00000850: - /* Mongolian (Mongolian Script) */ - break; - case 0x00000429: - /* Persion */ - break; - case 0x00000446: - /* Punjabi */ - break; - case 0x0000046C: - /* Sesotho sa Leboa */ - break; - case 0x00000432: - /* Setswana */ - break; - case 0x0000045B: - /* Sinhala */ - break; - case 0x0001045B: - /* Sinhala - Wij 9 */ - break; - case 0x0000045A: - /* Syriac */ - break; - case 0x0001045A: - /* Syriac Phonetic */ - break; - case 0x00000428: - /* Tajik */ - break; - case 0x00000449: - /* Tamil */ - break; - case 0x0000044A: - /* Telugu */ - break; - case 0x0000041E: - /* Thai Kedmanee */ - break; - case 0x0001041E: - /* Thai Pattachote */ - break; - case 0x0002041E: - /* Thai Kedmanee (non-ShiftLock) */ - break; - case 0x0003041E: - /* Thai Pattachote (non-ShiftLock) */ - break; - case 0x00000451: - /* Tibetan (PRC) */ - break; - case 0x00000442: - /* Turkmen */ - break; - case 0x00020422: - /* Ukrainian (Enhanced) */ - break; - case 0x00000420: - /* Urdu */ - break; - case 0x00050409: - /* US English Table for IBM Arabic 238_L */ - break; - case 0x00000480: - /* Uyghur (Legacy) */ - break; - case 0x00010480: - /* Uyghur */ - break; - case 0x0000042A: - /* Vietnamese */ - break; - case 0x00000485: - /* Yakut */ - break; - case 0x0000046A: - /* Yoruba */ - break; -#endif - } -} -#endif - -#if ItnlKyBdFix -LOCALVAR uimr CurKyBdLytNm = 0; -#endif - -#if ItnlKyBdFix -LOCALFUNC bool tStrIsHex(TCHAR *s, int n, uimr *r) -{ - short i; - TCHAR c1; - TCHAR *p = s; - uimr v = 0; - - for (i = n; --i >= 0; ) { - v <<= 4; - c1 = *p++; - if ((c1 >= '0') && (c1 <= '9')) { - v += c1 - '0'; - } else if ((c1 >= 'A') && (c1 <= 'F')) { - v += c1 - ('A' - 10); - } else if ((c1 >= 'a') && (c1 <= 'f')) { - v += c1 - ('a' - 10); - } else { - return false; - } - } - - *r = v; - return true; -} -#endif - -#if ItnlKyBdFix -LOCALFUNC bool GetKeyboardLayoutHex(uimr *r) -{ - TCHAR s[KL_NAMELENGTH]; - bool IsOk = false; - - if (! GetKeyboardLayoutName(s)) { - /* ReportWinLastError(); */ - } else { - size_t n = _tcslen(s); - - if (8 != n) { - /* fail */ - } else { - IsOk = tStrIsHex(s, n, r); - } - } - - return IsOk; -} -#endif - -#if ItnlKyBdFix -void CheckKeyboardLayout(void) -{ - uimr sv; - - if (! GetKeyboardLayoutHex(&sv)) { - } else if (sv == CurKyBdLytNm) { - /* no change */ - } else { - CurKyBdLytNm = sv; - - VkMapFromLayout(sv); - } -} - -void InitCheckKeyboardLayout(void) -{ - uimr sv; - - if (! GetKeyboardLayoutHex(&sv)) { - sv = 0x00000409; - } - - CurKyBdLytNm = sv; - - VkMapFromLayout(sv); -} -#endif - diff --git a/src/UI/_deprecated/WIN32/KEYBOARD.c b/src/UI/_deprecated/WIN32/KEYBOARD.c deleted file mode 100644 index ba9c310..0000000 --- a/src/UI/_deprecated/WIN32/KEYBOARD.c +++ /dev/null @@ -1,435 +0,0 @@ -#include -#include "SYSDEPNS.h" -#include "CNFGGLOB.h" -#include "CNFGRAPI.h" -#include "HW/KBRD/KEYCODES.h" -#include "UI/COMOSGLU.h" -#include "UI/WIN32/OSGLUWIN.h" -#include "UI/CONTROLM.h" -#include "UTIL/ENDIANAC.h" - -/* keyboard */ - -static uint8_t WinKey2Mac[256]; - -static inline void AssignOneMacKey(uint8_t WinKey, uint8_t MacKey) -{ - WinKey2Mac[WinKey] = MacKey; -} - -bool InitWinKey2Mac(void) -{ - memset(WinKey2Mac, MKC_None, sizeof(WinKey2Mac)); - - AssignOneMacKey('A', MKC_A); - AssignOneMacKey('S', MKC_S); - AssignOneMacKey('D', MKC_D); - AssignOneMacKey('F', MKC_F); - AssignOneMacKey('H', MKC_H); - AssignOneMacKey('G', MKC_G); - AssignOneMacKey('Z', MKC_Z); - AssignOneMacKey('X', MKC_X); - AssignOneMacKey('C', MKC_C); - AssignOneMacKey('V', MKC_V); - AssignOneMacKey('B', MKC_B); - AssignOneMacKey('Q', MKC_Q); - AssignOneMacKey('W', MKC_W); - AssignOneMacKey('E', MKC_E); - AssignOneMacKey('R', MKC_R); - AssignOneMacKey('Y', MKC_Y); - AssignOneMacKey('T', MKC_T); - AssignOneMacKey('1', MKC_1); - AssignOneMacKey('2', MKC_2); - AssignOneMacKey('3', MKC_3); - AssignOneMacKey('4', MKC_4); - AssignOneMacKey('6', MKC_6); - AssignOneMacKey('5', MKC_5); - AssignOneMacKey(myVK_Equal, MKC_Equal); - AssignOneMacKey('9', MKC_9); - AssignOneMacKey('7', MKC_7); - AssignOneMacKey(myVK_Subtract, MKC_Minus); - AssignOneMacKey('8', MKC_8); - AssignOneMacKey('0', MKC_0); - AssignOneMacKey(myVK_RightBracket, MKC_RightBracket); - AssignOneMacKey('O', MKC_O); - AssignOneMacKey('U', MKC_U); - AssignOneMacKey(myVK_LeftBracket, MKC_LeftBracket); - AssignOneMacKey('I', MKC_I); - AssignOneMacKey('P', MKC_P); - AssignOneMacKey(VK_RETURN, MKC_Return); - AssignOneMacKey('L', MKC_L); - AssignOneMacKey('J', MKC_J); - AssignOneMacKey(myVK_SingleQuote, MKC_SingleQuote); - AssignOneMacKey('K', MKC_K); - AssignOneMacKey(myVK_SemiColon, MKC_SemiColon); - AssignOneMacKey(myVK_BackSlash, MKC_formac_BackSlash); - AssignOneMacKey(myVK_Comma, MKC_Comma); - AssignOneMacKey(myVK_Slash, MKC_formac_Slash); - AssignOneMacKey('N', MKC_N); - AssignOneMacKey('M', MKC_M); - AssignOneMacKey(myVK_Period, MKC_Period); - - AssignOneMacKey(VK_TAB, MKC_Tab); - AssignOneMacKey(VK_SPACE, MKC_Space); - AssignOneMacKey(myVK_Grave, MKC_formac_Grave); - AssignOneMacKey(VK_BACK, MKC_BackSpace); - AssignOneMacKey(VK_ESCAPE, MKC_formac_Escape); - - AssignOneMacKey(VK_MENU, MKC_formac_Command); - - AssignOneMacKey(VK_LMENU, MKC_formac_Command); - - AssignOneMacKey(VK_RMENU, MKC_formac_RCommand); - - AssignOneMacKey(VK_SHIFT, MKC_formac_Shift); - AssignOneMacKey(VK_LSHIFT, MKC_formac_Shift); - AssignOneMacKey(VK_RSHIFT, MKC_formac_RShift); - - AssignOneMacKey(VK_CAPITAL, MKC_formac_CapsLock); - - AssignOneMacKey(VK_APPS, MKC_formac_ROption); - AssignOneMacKey(VK_LWIN, MKC_formac_Option); - AssignOneMacKey(VK_RWIN, MKC_formac_ROption); - AssignOneMacKey(VK_CONTROL, MKC_formac_Control); - AssignOneMacKey(VK_LCONTROL, MKC_formac_Control); - AssignOneMacKey(VK_RCONTROL, MKC_formac_RControl); - - AssignOneMacKey(VK_F1, MKC_formac_F1); - AssignOneMacKey(VK_F2, MKC_formac_F2); - AssignOneMacKey(VK_F3, MKC_formac_F3); - AssignOneMacKey(VK_F4, MKC_formac_F4); - AssignOneMacKey(VK_F5, MKC_formac_F5); - AssignOneMacKey(VK_F6, MKC_F6); - AssignOneMacKey(VK_F7, MKC_F7); - AssignOneMacKey(VK_F8, MKC_F8); - AssignOneMacKey(VK_F9, MKC_F9); - AssignOneMacKey(VK_F10, MKC_F10); - AssignOneMacKey(VK_F11, MKC_F11); - AssignOneMacKey(VK_F12, MKC_F12); - - AssignOneMacKey(VK_DECIMAL, MKC_Decimal); - AssignOneMacKey(VK_DELETE, MKC_Decimal); - /* AssignOneMacKey(VK_RIGHT, 0x42); */ - AssignOneMacKey(VK_MULTIPLY, MKC_KPMultiply); - AssignOneMacKey(VK_ADD, MKC_KPAdd); - /* AssignOneMacKey(VK_LEFT, 0x46); */ - AssignOneMacKey(VK_NUMLOCK, MKC_Clear); - - /* AssignOneMacKey(VK_DOWN, 0x48); */ - AssignOneMacKey(VK_DIVIDE, MKC_KPDevide); - /* AssignOneMacKey(VK_RETURN, MKC_formac_Enter); */ - /* AssignOneMacKey(VK_UP, 0x4D); */ - AssignOneMacKey(VK_DIVIDE, MKC_KPDevide); - AssignOneMacKey(VK_SUBTRACT, MKC_KPSubtract); - - AssignOneMacKey(VK_SEPARATOR, MKC_KPEqual); - AssignOneMacKey(VK_NUMPAD0, MKC_KP0); - AssignOneMacKey(VK_NUMPAD1, MKC_KP1); - AssignOneMacKey(VK_NUMPAD2, MKC_KP2); - AssignOneMacKey(VK_NUMPAD3, MKC_KP3); - AssignOneMacKey(VK_NUMPAD4, MKC_KP4); - AssignOneMacKey(VK_NUMPAD5, MKC_KP5); - - AssignOneMacKey(VK_NUMPAD6, MKC_KP6); - AssignOneMacKey(VK_NUMPAD7, MKC_KP7); - AssignOneMacKey(VK_NUMPAD8, MKC_KP8); - AssignOneMacKey(VK_NUMPAD9, MKC_KP9); - - AssignOneMacKey(VK_LEFT, MKC_Left); - AssignOneMacKey(VK_RIGHT, MKC_Right); - AssignOneMacKey(VK_DOWN, MKC_Down); - AssignOneMacKey(VK_UP, MKC_Up); - - AssignOneMacKey(myVK_PRIOR, MKC_formac_PageUp); - AssignOneMacKey(myVK_NEXT, MKC_formac_PageDown); - AssignOneMacKey(myVK_END, MKC_formac_End); - AssignOneMacKey(myVK_HOME, MKC_formac_Home); - AssignOneMacKey(myVK_INSERT, MKC_formac_Help); - AssignOneMacKey(myVK_DELETE, MKC_formac_ForwardDel); - AssignOneMacKey(myVK_HELP, MKC_formac_Help); - AssignOneMacKey(myVK_SNAPSHOT, MKC_Print); - AssignOneMacKey(myVK_SCROLL, MKC_ScrollLock); - AssignOneMacKey(myVK_PAUSE, MKC_Pause); - - AssignOneMacKey(myVK_OEM_102, MKC_AngleBracket); - - InitKeyCodes(); - -#if ItnlKyBdFix - InitCheckKeyboardLayout(); -#endif - - return true; -} - -LOCALPROC DoKeyCode(int i, bool down) -{ - uint8_t key = WinKey2Mac[ItnlKyBdFix ? VkMapA[i] : i]; - if (MKC_None != key) { - Keyboard_UpdateKeyMap2(key, down); - } -} - -#if EnableGrabSpecialKeys -LOCALVAR bool HaveSetSysParam = false; -#endif - -LOCALPROC CheckTheCapsLock(void) -{ - DoKeyCode(VK_CAPITAL, (GetKeyState(VK_CAPITAL) & 1) != 0); -} - -#if EnableGrabSpecialKeys -LOCALVAR bool VK_LWIN_pressed = false; -LOCALVAR bool VK_RWIN_pressed = false; - -void CheckForLostKeyUps(void) -{ - if (HaveSetSysParam) { - /* check for lost key ups */ - if (VK_LWIN_pressed) { - if ((GetAsyncKeyState(VK_LWIN) & 0x8000) == 0) { - DoKeyCode(VK_LWIN, false); - VK_LWIN_pressed = false; - } - } - if (VK_RWIN_pressed) { - if ((GetAsyncKeyState(VK_RWIN) & 0x8000) == 0) { - DoKeyCode(VK_RWIN, false); - VK_RWIN_pressed = false; - } - } - } -} -#endif - -LOCALPROC DoVKcode0(int i, bool down) -{ -#if EnableGrabSpecialKeys - if (HaveSetSysParam) { - /* will need to check for lost key ups */ - if (VK_LWIN == i) { - VK_LWIN_pressed = down; - } else if (VK_RWIN == i) { - VK_RWIN_pressed = down; - } - } -#endif - DoKeyCode(i, down); -} - -void DoVKcode(int i, uint8_t flags, bool down) -{ - switch (i) { -#if MKC_formac_Control != MKC_formac_RControl - case VK_CONTROL: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_RControl : MKC_formac_Control, - down); - break; -#endif -#if MKC_formac_RCommand != MKC_formac_Command - case VK_MENU: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_RCommand : MKC_formac_Command, - down); - break; -#endif - case VK_RETURN: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_Enter : MKC_Return, - down); - break; - case myVK_HOME: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_Home : MKC_KP7, - down); - break; - case VK_UP: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_Up : MKC_KP8, - down); - break; - case myVK_PRIOR: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_PageUp : MKC_KP9, - down); - break; - case VK_LEFT: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_Left : MKC_KP4, - down); - break; - case myVK_CLEAR: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_Clear : MKC_KP5, - down); - break; - case VK_RIGHT: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_Right : MKC_KP6, - down); - break; - case myVK_END: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_End : MKC_KP1, - down); - break; - case VK_DOWN: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_Down : MKC_KP2, - down); - break; - case myVK_NEXT: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_PageDown : MKC_KP3, - down); - break; - case myVK_INSERT: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_Help : MKC_KP0, - down); - break; - case myVK_DELETE: - Keyboard_UpdateKeyMap2(TestBit(flags, 0) - ? MKC_formac_ForwardDel : MKC_Decimal, - down); - break; - case VK_CAPITAL: - CheckTheCapsLock(); - break; - default: - if ((i >= 0) && (i < 256)) { - DoVKcode0(i, down); - } - break; - } -} - -bool WantCmdOptOnReconnect = false; - -void ReconnectKeyCodes3(void) -{ - int i; - - CheckTheCapsLock(); - - if (WantCmdOptOnReconnect) { - WantCmdOptOnReconnect = false; - - for (i = 0; i < 256; ++i) { - if ((GetKeyState(i) & 0x8000) != 0) { - if ((VK_CAPITAL != i) - && (VK_RETURN != i)) - { - DoVKcode0(i, true); - } - } - } - } -} - -void DisconnectKeyCodes3(void) -{ - DisconnectKeyCodes2(); - SetCurMouseButton(false); -} - -#if EnableGrabSpecialKeys -static HHOOK hKeyHook = NULL; -#endif - -#if EnableGrabSpecialKeys -typedef struct { - DWORD vkCode; - DWORD scanCode; - DWORD flags; - DWORD time; - DWORD dwExtraInfo; -} _KBDLLHOOKSTRUCT; -#endif - -#if EnableGrabSpecialKeys -LRESULT CALLBACK LowLevelKeyboardProc( - int nCode, /* hook code */ - WPARAM wParam, /* message identifier */ - LPARAM lParam /* pointer to structure with message data */ -); -#endif - -#if EnableGrabSpecialKeys -LRESULT CALLBACK LowLevelKeyboardProc( - int nCode, /* hook code */ - WPARAM wParam, /* message identifier */ - LPARAM lParam /* pointer to structure with message data */ -) -{ - if (nCode == HC_ACTION) { - _KBDLLHOOKSTRUCT *p = (_KBDLLHOOKSTRUCT *)lParam; - if (p->vkCode != VK_CAPITAL) { - switch (wParam) { - case WM_KEYDOWN: - case WM_SYSKEYDOWN: - DoVKcode(p->vkCode, p->flags, true); - return 1; - break; - case WM_KEYUP: - case WM_SYSKEYUP: - DoVKcode(p->vkCode, p->flags, false); - return 1; - break; - } - } - } - return CallNextHookEx(hKeyHook, /* handle to current hook */ - nCode, /* hook code passed to hook procedure */ - wParam, /* value passed to hook procedure */ - lParam /* value passed to hook procedure */ - ); - -} -#endif - -#if EnableGrabSpecialKeys -#define _WH_KEYBOARD_LL 13 -#define _SPI_SETSCREENSAVERRUNNING 0x0061 -#endif - -#if EnableGrabSpecialKeys -LOCALVAR UINT nPreviousState; -#endif - -#if EnableGrabSpecialKeys -void GrabSpecialKeys(void) -{ - if ((hKeyHook == NULL) && ! HaveSetSysParam) { - /* this works on Windows XP */ - hKeyHook = SetWindowsHookEx( - _WH_KEYBOARD_LL, /* type of hook to install */ - (HOOKPROC)LowLevelKeyboardProc, - /* address of hook procedure */ - AppInstance, /* handle to application instance */ - 0 /* identity of thread to install hook for */ - ); - if (hKeyHook == NULL) { - /* this works on Windows 95/98 */ - SystemParametersInfo(_SPI_SETSCREENSAVERRUNNING, TRUE, - &nPreviousState, 0); - HaveSetSysParam = true; - } - } -} - -void UnGrabSpecialKeys(void) -{ - if (hKeyHook != NULL) { - (void) UnhookWindowsHookEx(hKeyHook); - hKeyHook = NULL; - } - if (HaveSetSysParam) { - SystemParametersInfo(_SPI_SETSCREENSAVERRUNNING, FALSE, - &nPreviousState, 0); - HaveSetSysParam = false; - } -} -#endif diff --git a/src/UI/_deprecated/WIN32/OSGLUWIN.c b/src/UI/_deprecated/WIN32/OSGLUWIN.c deleted file mode 100644 index 4de7e50..0000000 --- a/src/UI/_deprecated/WIN32/OSGLUWIN.c +++ /dev/null @@ -1,3255 +0,0 @@ -/* - OSGLUWIN.c - - Copyright (C) 2009 Philip Cummins, Weston Pawlowski, - Bradford L. Barrett, Paul C. Pratt, Fabio Concas - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for microsoft WINdows - - All operating system dependent code for the - Microsoft Windows platform should go here. - - This code is descended from Weston Pawlowski's Windows - port of vMac, by Philip Cummins. - - The main entry point '_tWinMain' is at the end of this file. -*/ - -#include -#include -#include -#include - -#include "CNFGRAPI.h" -#include "CNFGGLOB.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" -#include "UTIL/DATE2SEC.h" - -#include "UI/COMOSGLU.h" -#include "UI/MYOSGLUE.h" -#include "UI/CONTROLM.h" -#include "UI/WIN32/OSGLUWIN.h" - - -/* --- adapting to API/ABI version differences --- */ - -#define _CSIDL_APPDATA 0x001a - -typedef BOOL (WINAPI *SHGetSpecialFolderPathProcPtr) ( - HWND hwndOwner, - LPTSTR lpszPath, - int nFolder, - BOOL fCreate -); -LOCALVAR SHGetSpecialFolderPathProcPtr MySHGetSpecialFolderPath = NULL; -LOCALVAR bool DidSHGetSpecialFolderPath = false; - -LOCALFUNC bool HaveMySHGetSpecialFolderPath(void) -{ - if (! DidSHGetSpecialFolderPath) { - HMODULE hLibModule = LoadLibrary(TEXT("shell32.dll")); - if (NULL != hLibModule) { - MySHGetSpecialFolderPath = - (SHGetSpecialFolderPathProcPtr) - GetProcAddress(hLibModule, -#if UseUni - TEXT("SHGetSpecialFolderPathW") -#else - TEXT("SHGetSpecialFolderPathA") -#endif - ); - /* FreeLibrary(hLibModule); */ - } - DidSHGetSpecialFolderPath = true; - } - return (MySHGetSpecialFolderPath != NULL); -} - - -/* --- end of adapting to API/ABI version differences --- */ - -#include "STRCONST.h" - -#if UseUni -#define NeedCell2UnicodeMap 1 -#else -#define NeedCell2WinAsciiMap 1 -#endif - -#include "LANG/INTLCHAR.h" - - -LOCALPROC NativeStrFromCStr(LPTSTR r, char *s, bool AddEllipsis) -{ - uint8_t ps[ClStrMaxLength]; - int i; - int L; - - ClStrFromSubstCStr(&L, ps, s); - - for (i = 0; i < L; ++i) { - r[i] = (TCHAR) -#if UseUni - Cell2UnicodeMap[ps[i]]; -#else - Cell2WinAsciiMap[ps[i]]; -#endif - } - - if (AddEllipsis) { -#if UseUni - r[L++] = 0x2026; -#else - r[L++] = '.'; - r[L++] = '.'; - r[L++] = '.'; -#endif - } - - r[L] = '\0'; -} - -LOCALFUNC LPTSTR FindLastTerm(LPTSTR s, TCHAR delim) -{ - TCHAR c; - LPTSTR p0 = s; - LPTSTR p = (LPTSTR)nullpr; - - while ((c = *p0++) != (TCHAR)('\0')) { - if (c == delim) { - p = p0; - } - } - - return p; -} - -bool GetAppDir(LPTSTR pathName) -/* be sure at least _MAX_PATH long! */ -{ - if (GetModuleFileName(AppInstance, pathName, _MAX_PATH) == 0) { - /* MacMsg("error", "GetModuleFileName failed", false); */ - } else { - LPTSTR p = FindLastTerm(pathName, (TCHAR)('\\')); - if (p == nullpr) { - /* MacMsg("error", "strrchr failed", false); */ - } else { - *--p = (TCHAR)('\0'); - return true; - } - } - return false; -} - - -/* --- some simple utilities --- */ - -#define TestBit(i, p) (((unsigned long)(i) & PowOf2(p)) != 0) - -/* must work even if blocks overlap in memory */ -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memmove((char *)destPtr, (char *)srcPtr, byteCount); -} - -/* --- Parameter buffers --- */ - -#if IncludePbufs -LOCALFUNC MacErr_t PbufNewFromHandle(HGLOBAL h, uint32_t count, tPbuf *r) -{ - tPbuf i; - MacErr_t err; - - if (!FirstFreePbuf(&i)) { - (void) GlobalFree(h); - err = mnvm_miscErr; - } else { - *r = i; - PbufDat[i] = h; - PbufNewNotify(i, count); - err = mnvm_noErr; - } - - return err; -} - -GLOBALOSGLUFUNC MacErr_t PbufNew(uint32_t count, tPbuf *r) -{ - HGLOBAL h; - MacErr_t err = mnvm_miscErr; - - h = GlobalAlloc(GMEM_DDESHARE | GMEM_ZEROINIT, count); - if (h != NULL) { - /* need to clear h */ - err = PbufNewFromHandle(h, count, r); - } - - return err; -} - -GLOBALOSGLUPROC PbufDispose(tPbuf i) -{ - (void) GlobalFree(PbufDat[i]); - PbufDisposeNotify(i); -} - -LOCALPROC UnInitPbufs(void) -{ - tPbuf i; - - for (i = 0; i < NumPbufs; ++i) { - if (PbufIsAllocated(i)) { - PbufDispose(i); - } - } -} - -LOCALFUNC uint8_t * PbufLock(tPbuf i) -{ - HGLOBAL h = PbufDat[i]; - return (uint8_t *)GlobalLock(h); -} - -LOCALPROC PbufUnlock(tPbuf i) -{ - (void) GlobalUnlock(PbufDat[i]); -} - -GLOBALOSGLUPROC PbufTransfer(uint8_t * Buffer, - tPbuf i, uint32_t offset, uint32_t count, bool IsWrite) -{ - HGLOBAL h = PbufDat[i]; - uint8_t * p0 = GlobalLock(h); - if (p0 != NULL) { - void *p = p0 + offset; - if (IsWrite) { - (void) memcpy(p, Buffer, count); - } else { - (void) memcpy(Buffer, p, count); - } - } - (void) GlobalUnlock(h); -} -#endif - -/* main window info */ - -HWND MainWnd = NULL; -bool UseFullScreen = (WantInitFullScreen != 0); -bool UseMagnify = (WantInitMagnify != 0); - -/* cursor hiding */ - -bool HaveCursorHidden = false; -bool WantCursorHidden = false; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - (void) ShowCursor(TRUE); - SetCursor(LoadCursor(NULL, IDC_ARROW)); - } -} - -/* cursor moving */ - -bool MouseCaptured = false; - -LOCALFUNC bool MoveMouse(int16_t h, int16_t v) -{ - POINT NewMousePos; - uint32_t difftime; - bool IsOk; - DWORD StartTime = GetTickCount(); - LONG x = h; - LONG y = v; - - if (UseFullScreen && MayFullScreen) { - x -= ViewHStart; - y -= ViewVStart; - } - - if (UseMagnify) { - x *= WindowScale; - y *= WindowScale; - } - - if (UseFullScreen && MayFullScreen) { - x += hOffset; - y += vOffset; - } - - x += WndX; - y += WndY; - - do { - (void) SetCursorPos(x, y); - if (! GetCursorPos(&NewMousePos)) { - IsOk = false; - } else { - IsOk = (x == NewMousePos.x) && (y == NewMousePos.y); - } - difftime = (uint32_t)(GetTickCount() - StartTime); - } while ((! IsOk) && (difftime < 100)); - return IsOk; -} - -LOCALPROC MouseCaptureSet(bool v) -{ - if (v != MouseCaptured) { - if (v) { - (void) SetCapture(MainWnd); - } else { - (void) ReleaseCapture(); - } - MouseCaptured = v; - } -} - -void SetCurMouseButton(bool v) -{ - MouseButtonSet(v); - MouseCaptureSet(v); -} - -/* --- priority --- */ - -#ifndef EnableChangePriority -#define EnableChangePriority MayFullScreen -#endif /* EnableChangePriority */ - -#if EnableChangePriority -LOCALVAR bool PriorityRaised = false; -#endif - -#if EnableChangePriority -LOCALPROC RaisePriority(void) -{ - if (! PriorityRaised) { - if (! SetPriorityClass( - GetCurrentProcess(), /* handle to the process */ - HIGH_PRIORITY_CLASS - /* REALTIME_PRIORITY_CLASS (not, killer) */ - /* priority class value */ - )) - { - /* - not recursive: - MacMsg("SetPriorityClass failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } - PriorityRaised = true; - } -} -#endif - -#if EnableChangePriority -LOCALPROC LowerPriority(void) -{ - if (PriorityRaised) { - if (! SetPriorityClass( - GetCurrentProcess(), /* handle to the process */ - NORMAL_PRIORITY_CLASS /* priority class value */ - )) - { - /* - not recursive: - MacMsg("SetPriorityClass failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } - PriorityRaised = false; - } -} -#endif - - -/* --- overall grab --- */ - -#if MayFullScreen -LOCALPROC GrabTheMachine(void) -{ -#if EnableChangePriority - if ((uint8_t) -1 == SpeedValue) { - RaisePriority(); - } -#endif -#if EnableGrabSpecialKeys - GrabSpecialKeys(); -#endif -} -#endif - -#if MayFullScreen -LOCALPROC UnGrabTheMachine(void) -{ -#if EnableGrabSpecialKeys - UnGrabSpecialKeys(); -#endif -#if EnableChangePriority - LowerPriority(); -#endif -} -#endif - -#if MayFullScreen -LOCALVAR bool GrabMachine = false; -#endif - -#if MayFullScreen -LOCALPROC AdjustMachineGrab(void) -{ - if (GrabMachine) { - if (MainWnd != NULL) { - GrabTheMachine(); - } - } else { - UnGrabTheMachine(); - } -} -#endif - -/* --- basic dialogs --- */ - -LOCALPROC MyBeginDialog(void) -{ - DisconnectKeyCodes3(); -#if MayFullScreen - GrabMachine = false; - UnGrabTheMachine(); -#endif - ForceShowCursor(); -} - -LOCALPROC MyEndDialog(void) -{ - ReconnectKeyCodes3(); -} - -LOCALPROC CheckSavedMacMsg(void) -{ - if (nullpr != SavedBriefMsg) { - TCHAR briefMsg0[ClStrMaxLength + 1]; - TCHAR longMsg0[ClStrMaxLength + 1]; - - NativeStrFromCStr(briefMsg0, SavedBriefMsg, false); - NativeStrFromCStr(longMsg0, SavedLongMsg, false); - - MessageBox(MainWnd, longMsg0, briefMsg0, - MB_APPLMODAL | MB_OK | (SavedFatalMsg ? MB_ICONSTOP : 0)); - - SavedBriefMsg = nullpr; - } -} - -/* --- main window --- */ - -enum { - ID_MENU_NULL = 256, - ID_FILE_INSERTDISK1, - ID_FILE_QUIT, - ID_SPECIAL_MORECOMMANDS, - ID_HELP_ABOUT, - - kNum_ID_MENU -}; - - -#define EnableScalingBuff 1 -LOCALVAR uint8_t * ScalingBuff = NULL; - -LOCALVAR HDC MainWndDC = NULL; - -LOCALVAR int32_t CmdShow; - -LOCALVAR TCHAR WndTitle[_MAX_PATH]; -LOCALVAR const TCHAR WndClassName[] = TEXT(kStrAppName); - -LOCALVAR bool gBackgroundFlag = false; -LOCALVAR bool gTrueBackgroundFlag = false; -LOCALVAR bool CurSpeedStopped = true; - -LOCALPROC GetWndTitle(void) -{ - TCHAR pathName[_MAX_PATH]; - WIN32_FIND_DATA fd; - bool IsOk = false; - - if (GetModuleFileName(AppInstance, pathName, _MAX_PATH) != 0) { - HANDLE hf = FindFirstFile(pathName, &fd); - - if (hf != INVALID_HANDLE_VALUE) { - /* get rid of extension, presumably '.exe' */ - LPTSTR p = FindLastTerm(fd.cFileName, - (TCHAR)('.')); - if (p != nullpr) { - *--p = (TCHAR)('\0'); - } - - _tcscpy(WndTitle, fd.cFileName); - IsOk = true; - FindClose(hf); - } - } - if (! IsOk) { - _tcscpy(WndTitle, TEXT(kStrAppName)); - } -} - -LOCALPROC DisposeMainWindow(void) -{ - if (MainWndDC != NULL) { - ReleaseDC(MainWnd, MainWndDC); - } - if (MainWnd != NULL) { - DestroyWindow(MainWnd); - MainWnd = NULL; /* so MacMsg will still work */ - } -} - -enum { - kMagStateNormal, -#if 1 - kMagStateMagnifgy, -#endif - kNumMagStates -}; - -#define kMagStateAuto kNumMagStates - -#if MayNotFullScreen -LOCALVAR int CurWinIndx; -LOCALVAR bool HavePositionWins[kNumMagStates]; -LOCALVAR POINT WinPositionWins[kNumMagStates]; -#endif - -#if MayNotFullScreen -LOCALPROC AppendConvertMenuItem(HMENU hMenu, - UINT uIDNewItem, char *s, bool AddEllipsis) -{ - TCHAR ts[ClStrMaxLength + 1]; - - NativeStrFromCStr(ts, s, AddEllipsis); - - (void) AppendMenu(hMenu, MF_ENABLED + MF_STRING, - uIDNewItem, ts); -} -#endif - -#if MayNotFullScreen -LOCALPROC AppendSubmenuConvertName(HMENU hMenu, - HMENU hSubMenu, char *s) -{ - TCHAR ts[ClStrMaxLength + 1]; - MENUITEMINFO mii; - - NativeStrFromCStr(ts, s, false); - -#if 0 - (void) InsertMenu(hMenu, 0xFFFFFFFF, - MF_BYPOSITION + MF_POPUP + MF_STRING + MF_ENABLED, - (UINT)hSubMenu, ts); -#endif - - memset(&mii, 0, sizeof(MENUITEMINFO)); - mii.cbSize = sizeof(MENUITEMINFO); - mii.fMask = MIIM_TYPE | MIIM_SUBMENU; - mii.fType = MFT_STRING; - mii.hSubMenu = hSubMenu; - mii.dwTypeData = ts; - mii.cch = (UINT)_tcslen(ts); - (void) InsertMenuItem(hMenu, (UINT) -1, TRUE, - &mii); -} -#endif - -#ifndef kStrMenuFile_win -#define kStrMenuFile_win kStrMenuFile -#endif - -LOCALFUNC bool ReCreateMainWindow(void) -{ -#if MayNotFullScreen - HMENU m; - int DfltWndX; - int DfltWndY; - int WinIndx; -#endif - HMENU mb; - HWND NewMainWindow; - HDC NewMainWndDC = NULL; - int ScreenX = GetSystemMetrics(SM_CXSCREEN); - int ScreenY = GetSystemMetrics(SM_CYSCREEN); - short NewWindowHeight = vMacScreenHeight; - short NewWindowWidth = vMacScreenWidth; - HWND OldMainWindow = MainWnd; - HDC OldMainWndDC = MainWndDC; - RECT NewWinR; - DWORD WStyle; - DWORD WExStyle; - -#if 1 - if (! UseFullScreen) -#endif -#if MayNotFullScreen - { - /* save old position */ - if (OldMainWindow != NULL) { - WinPositionWins[CurWinIndx].x = WndX; - WinPositionWins[CurWinIndx].y = WndY; - } - } -#endif - -#if MayNotFullScreen -#if 1 - if (WantMagnify) { - WinIndx = kMagStateMagnifgy; - } else -#endif - { - WinIndx = kMagStateNormal; - } -#endif - -#if 1 - if (WantMagnify) { - NewWindowHeight *= WindowScale; - NewWindowWidth *= WindowScale; - } -#endif - -#if 1 - if (WantFullScreen) -#endif -#if MayFullScreen - { - WStyle = WS_VISIBLE | WS_POPUP; - WExStyle = WS_EX_TOPMOST; - - hOffset = (ScreenX - NewWindowWidth) / 2; - vOffset = (ScreenY - NewWindowHeight) / 2; - if (hOffset < 0) { - hOffset = 0; - } - if (vOffset < 0) { - vOffset = 0; - } - - NewWinR.left = 0; - NewWinR.top = 0; - NewWinR.right = ScreenX; - NewWinR.bottom = ScreenY; - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - WStyle = WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU - | WS_MINIMIZEBOX; - WExStyle = WS_EX_ACCEPTFILES; - - DfltWndX = (ScreenX - NewWindowWidth) / 2; - DfltWndY = (ScreenY - NewWindowHeight) / 2; - - if (DfltWndX < 0) { - DfltWndX = 0; - } - if (DfltWndY < 0) { - DfltWndY = 0; - } - - if (! HavePositionWins[WinIndx]) { - WinPositionWins[WinIndx].x = DfltWndX; - WinPositionWins[WinIndx].y = DfltWndY; - HavePositionWins[WinIndx] = true; - } - - NewWinR.left = WinPositionWins[WinIndx].x; - NewWinR.top = WinPositionWins[WinIndx].y; - NewWinR.right = NewWinR.left + NewWindowWidth; - NewWinR.bottom = NewWinR.top + NewWindowHeight; - - (void) AdjustWindowRectEx(&NewWinR, WStyle, TRUE, WExStyle); - - if ((NewWinR.right <= 0) - || (NewWinR.left >= ScreenX) - || (NewWinR.bottom <= 0) - || (NewWinR.top >= ScreenY)) - { - NewWinR.left = DfltWndX; - NewWinR.top = DfltWndY; - NewWinR.right = DfltWndX + NewWindowWidth; - NewWinR.bottom = DfltWndY + NewWindowHeight; - - (void) AdjustWindowRectEx(&NewWinR, - WStyle, TRUE, WExStyle); - } - } -#endif - - if ((OldMainWindow == NULL) -#if 1 - || (WantFullScreen != UseFullScreen) -#endif - ) - { - -#if 1 - if (WantFullScreen) -#endif -#if MayFullScreen - { - mb = NULL; - } -#endif -#if 1 - else -#endif -#if MayNotFullScreen - { - mb = CreateMenu(); - if (mb != NULL) { - m = CreateMenu(); - if (m != NULL) { - AppendConvertMenuItem(m, ID_FILE_INSERTDISK1, - kStrMenuItemOpen, true); - (void) AppendMenu(m, MF_SEPARATOR, 0, NULL); - AppendConvertMenuItem(m, ID_FILE_QUIT, - kStrMenuItemQuit, false); - AppendSubmenuConvertName(mb, m, kStrMenuFile_win); - } - m = CreateMenu(); - if (m != NULL) { - AppendConvertMenuItem(m, ID_SPECIAL_MORECOMMANDS, - kStrMenuItemMore, true); - AppendSubmenuConvertName(mb, m, kStrMenuSpecial); - } - m = CreateMenu(); - if (m != NULL) { - AppendConvertMenuItem(m, ID_HELP_ABOUT, - kStrMenuItemAbout, true); - AppendSubmenuConvertName(mb, m, kStrMenuHelp); - } - } - } -#endif - - NewMainWindow = CreateWindowEx( - WExStyle, - WndClassName, - WndTitle, - WStyle, - NewWinR.left, NewWinR.top, - NewWinR.right - NewWinR.left, NewWinR.bottom - NewWinR.top, - NULL, - mb, - AppInstance, NULL); - if (NewMainWindow == NULL) { - MacMsg("CreateWindow failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - return false; - } - - NewMainWndDC = GetDC(NewMainWindow); - if (NewMainWndDC == NULL) { - MacMsg("GetDC failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - DestroyWindow(NewMainWindow); - return false; - } - } else { - NewMainWndDC = OldMainWndDC; - NewMainWindow = OldMainWindow; - (void) MoveWindow(NewMainWindow, NewWinR.left, NewWinR.top, - NewWinR.right - NewWinR.left, NewWinR.bottom - NewWinR.top, - TRUE); - } - - if (0 != vMacScreenDepth) { - ColorModeWorks = true; - } - - { - POINT p; - - /* - Find out where the window really went, on - the off chance that the WM_MOVE message wasn't - called on CreateWindowEx/MoveWindow, or that - the window wasn't put where asked for. - */ - p.x = 0; - p.y = 0; - (void) MapWindowPoints(NewMainWindow, NULL, &p, 1); - WndX = (int16_t)p.x; - WndY = (int16_t)p.y; - } - -#if MayFullScreen - GrabMachine = false; - UnGrabTheMachine(); -#endif - -#if MayNotFullScreen - CurWinIndx = WinIndx; -#endif - - MainWnd = NewMainWindow; - MainWndDC = NewMainWndDC; - gTrueBackgroundFlag = false; - UseFullScreen = WantFullScreen; - UseMagnify = WantMagnify; - - if (UseFullScreen) -#if MayFullScreen - { - ViewHSize = ScreenX; - ViewVSize = ScreenY; - if (UseMagnify) { - ViewHSize /= WindowScale; - ViewVSize /= WindowScale; - } - if (ViewHSize >= vMacScreenWidth) { - ViewHStart = 0; - ViewHSize = vMacScreenWidth; - } else { - ViewHSize &= ~ 1; - } - if (ViewVSize >= vMacScreenHeight) { - ViewVStart = 0; - ViewVSize = vMacScreenHeight; - } else { - ViewVSize &= ~ 1; - } - } -#endif - - if (NewMainWindow != OldMainWindow) { - ShowWindow(NewMainWindow, SW_SHOW /* CmdShow */); - if (OldMainWndDC != NULL) { - ReleaseDC(MainWnd, OldMainWndDC); - } - if (OldMainWindow != NULL) { - /* ShowWindow(OldMainWindow, SW_HIDE); */ - DestroyWindow(OldMainWindow); - } - - DisconnectKeyCodes3(); - /* since key events per window */ - } else { - (void) InvalidateRgn(MainWnd, NULL, FALSE); - } - if (HaveCursorHidden) { - (void) MoveMouse(CurMouseH, CurMouseV); - WantCursorHidden = true; - } - - return true; -} - -typedef struct BITMAPINFOHEADER256 { - BITMAPINFOHEADER bmi; - RGBQUAD colors[CLUT_size]; - //RGBQUAD colors[2]; -} BITMAPINFOHEADER256; - -#define ScaledHeight (WindowScale * vMacScreenHeight) -#define ScaledWidth (WindowScale * vMacScreenWidth) - -LOCALPROC HaveChangedScreenBuff(int16_t top, int16_t left, - int16_t bottom, int16_t right) -{ - BITMAPINFOHEADER256 bmh; - uint8_t *cdb = GetCurDrawBuff(); - int XDest; - int YDest; - - if (UseFullScreen) -#if MayFullScreen - { - if (top < ViewVStart) { - top = ViewVStart; - } - if (left < ViewHStart) { - left = ViewHStart; - } - if (bottom > ViewVStart + ViewVSize) { - bottom = ViewVStart + ViewVSize; - } - if (right > ViewHStart + ViewHSize) { - right = ViewHStart + ViewHSize; - } - - if ((top >= bottom) || (left >= right)) { - goto label_exit; - } - } -#endif - - XDest = left; - YDest = top; - - if (UseFullScreen) -#if MayFullScreen - { - XDest -= ViewHStart; - YDest -= ViewVStart; - } -#endif - - if (UseMagnify) { - XDest *= WindowScale; - YDest *= WindowScale; - } - if (UseFullScreen) -#if MayFullScreen - { - XDest += hOffset; - YDest += vOffset; - } -#endif - - if (vMacScreenDepth > 0 && UseColorMode) { - int i; - int nDestWidth = (right - left); - int nDestHeight = (bottom - top); - uint8_t *p; - if (vMacScreenDepth == 1) { - p = ScalingBuff + ((uint32_t)vMacScreenWidth / 4) * top; - } else if (vMacScreenDepth >= 4) { - p = ScalingBuff + (uint32_t)vMacScreenByteWidth * top; - } else { - p = cdb + (uint32_t)vMacScreenByteWidth * top; - } - - memset(&bmh, 0, sizeof (bmh)); - bmh.bmi.biSize = sizeof(BITMAPINFOHEADER); - bmh.bmi.biWidth = vMacScreenWidth; - bmh.bmi.biHeight = - (bottom - top); - bmh.bmi.biPlanes = 1; - if (1 == vMacScreenDepth) { - bmh.bmi.biBitCount = 4; - } else { - bmh.bmi.biBitCount = (1 << vMacScreenDepth); - } - bmh.bmi.biCompression= BI_RGB; - bmh.bmi.biSizeImage = 0; - bmh.bmi.biXPelsPerMeter = 0; - bmh.bmi.biYPelsPerMeter = 0; - if (vMacScreenDepth == 1) { - bmh.bmi.biClrUsed = 4; - } else { - bmh.bmi.biClrUsed = 0; - } - bmh.bmi.biClrImportant = 0; - - if (vMacScreenDepth < 4) { - for (i = 0; i < CLUT_size; ++i) { - bmh.colors[i].rgbRed = CLUT_reds[i] >> 8; - bmh.colors[i].rgbGreen = CLUT_greens[i] >> 8; - bmh.colors[i].rgbBlue = CLUT_blues[i] >> 8; - bmh.colors[i].rgbReserved = 0; - } - } - - if (1 == vMacScreenDepth) { - int j; - uint8_t *p1 = (uint8_t *)(cdb + (uint32_t)vMacScreenByteWidth * top); - uint16_t *p2 = (uint16_t *)p; - for (i = bottom - top; --i >= 0; ) { - for (j = vMacScreenWidth / 4; --j >= 0; ) { - uint16_t t0 = *p1++; - *p2 ++ - = ((t0 & 0xC0) >> 2) - | ((t0 & 0x30) >> 4) - | ((t0 & 0x0C) << 10) - | ((t0 & 0x03) << 8); - } - } - } else if (4 == vMacScreenDepth) { - int j; - uint16_t *p1 = (uint16_t *)(cdb + (uint32_t)vMacScreenByteWidth * top); - uint16_t *p2 = (uint16_t *)p; - for (i = bottom - top; --i >= 0; ) { - for (j = vMacScreenWidth; --j >= 0; ) { - uint16_t t0 = *p1++; - *p2 ++ = - ((t0 & 0xFF00) >> 8) | ((t0 & 0x00FF) << 8); - } - } - } else if (5 == vMacScreenDepth) { - int j; - uint32_t *p1 = (uint32_t *)(cdb + (uint32_t)vMacScreenByteWidth * top); - uint32_t *p2 = (uint32_t *)p; - for (i = bottom - top; --i >= 0; ) { - for (j = vMacScreenWidth; --j >= 0; ) { - uint32_t t0 = *p1++; - *p2++ - = ((t0 & 0xFF000000) >> 24) - | ((t0 & 0x00FF0000) >> 8) - | ((t0 & 0x0000FF00) << 8) - | ((t0 & 0x000000FF) << 24); - } - } - } - - if (UseMagnify) { - nDestWidth *= WindowScale; - nDestHeight *= WindowScale; - } - - if (StretchDIBits( - MainWndDC, /* handle of device context */ - XDest, - /* x-coordinate of upper-left corner of dest. rect. */ - YDest, - /* y-coordinate of upper-left corner of dest. rect. */ - nDestWidth, /* dest. rectangle width */ - nDestHeight, /* dest. rectangle height */ - left, - /* x-coordinate of lower-left corner of source rect. */ - 0, /* y-coordinate of lower-left corner of source rect. */ - (right - left), /* source rectangle width */ - (bottom - top), /* source rectangle height */ - (CONST VOID *)p, /* address of array with DIB bits */ - (const struct tagBITMAPINFO *)&bmh, - /* address of structure with bitmap info. */ - DIB_RGB_COLORS, /* RGB or palette indices */ - SRCCOPY - ) == 0) { - /* ReportWinLastError(); */ - } - } else { - uint8_t *p = cdb + (uint32_t)vMacScreenMonoByteWidth * top; - - memset(&bmh, 0, sizeof (bmh)); - bmh.bmi.biSize = sizeof(BITMAPINFOHEADER); - bmh.bmi.biWidth = vMacScreenWidth; - bmh.bmi.biHeight = - (bottom - top); - bmh.bmi.biPlanes = 1; - bmh.bmi.biBitCount = 1; - bmh.bmi.biCompression= BI_RGB; - bmh.bmi.biSizeImage = 0; - bmh.bmi.biXPelsPerMeter = 0; - bmh.bmi.biYPelsPerMeter = 0; - bmh.bmi.biClrUsed = 0; - bmh.bmi.biClrImportant = 0; - bmh.colors[0].rgbRed = 255; - bmh.colors[0].rgbGreen = 255; - bmh.colors[0].rgbBlue = 255; - bmh.colors[0].rgbReserved = 0; - bmh.colors[1].rgbRed = 0; - bmh.colors[1].rgbGreen = 0; - bmh.colors[1].rgbBlue = 0; - bmh.colors[1].rgbReserved = 0; - - if (UseMagnify) { -#if EnableScalingBuff - if (ScalingBuff != NULL) { - int i; - int j; - int k; - uint16_t left1 = left & (~ 7); - uint16_t right1 = (right + 7) & (~ 7); - uint16_t jn = (right1 - left1) / 8; - uint8_t *p1 = - cdb + ((left1 + vMacScreenWidth * (uint32_t)top) / 8); - uint8_t *p2 = ScalingBuff - /* - + ((left1 + vMacScreenWidth * WindowScale - * (uint32_t)top) - * WindowScale / 8) - */ - ; - uint8_t *p3; - uint8_t t0; - uint8_t t1; - uint8_t t2; - uint8_t m; - - for (i = bottom - top; --i >= 0; ) { - p3 = p2; - for (j = jn; --j >= 0; ) { - t0 = *p1++; - t1 = t0; - m = 0x80; - t2 = 0; - for (k = 4; --k >= 0; ) { - t2 |= t1 & m; - t1 >>= 1; - m >>= 2; - } - *p2++ = t2 | (t2 >> 1); - - t1 = t0 << 4; - m = 0x80; - t2 = 0; - for (k = 4; --k >= 0; ) { - t2 |= t1 & m; - t1 >>= 1; - m >>= 2; - } - *p2++ = t2 | (t2 >> 1); - } - p1 += vMacScreenWidth / 8 - jn; - p2 += ScaledWidth / 8 - (WindowScale * jn); - for (j = WindowScale * jn; --j >= 0; ) { - *p2++ = *p3++; - } - p2 += ScaledWidth / 8 - (WindowScale * jn); - } - - bmh.bmi.biWidth = vMacScreenWidth * WindowScale; - bmh.bmi.biHeight = - ((bottom - top) * WindowScale); - if (SetDIBitsToDevice( - MainWndDC, /* handle of device context */ - XDest, - /* - x-coordinate of upper-left corner - of dest. rect. - */ - YDest, - /* - y-coordinate of upper-left corner - of dest. rect. - */ - (right - left) * WindowScale, - /* source rectangle width */ - (bottom - top) * WindowScale, - /* source rectangle height */ - (left & 7) * WindowScale, - /* - x-coordinate of lower-left corner - of source rect. - */ - 0, - /* - y-coordinate of lower-left corner - of source rect. - */ - 0, /* first scan line in array */ - (bottom - top) * WindowScale, - /* number of scan lines */ - (CONST VOID *)ScalingBuff, - /* address of array with DIB bits */ - (const struct tagBITMAPINFO *)&bmh, - /* address of structure with bitmap info. */ - DIB_RGB_COLORS /* RGB or palette indices */ - ) == 0) { - /* ReportWinLastError(); */ - } - } - } else -#endif - - { - if (SetDIBitsToDevice( - MainWndDC, /* handle of device context */ - XDest, - /* - x-coordinate of upper-left corner of dest. rect. - */ - YDest, - /* - y-coordinate of upper-left corner of dest. rect. - */ - (right - left), /* source rectangle width */ - (bottom - top), /* source rectangle height */ - left, - /* - x-coordinate of lower-left corner - of source rect. - */ - 0, - /* - y-coordinate of lower-left corner - of source rect. - */ - 0, /* first scan line in array */ - (bottom - top), /* number of scan lines */ - (CONST VOID *)p, /* address of array with DIB bits */ - (const struct tagBITMAPINFO *)&bmh, - /* address of structure with bitmap info. */ - DIB_RGB_COLORS /* RGB or palette indices */ - ) == 0) { - /* ReportWinLastError(); */ - } - } - } - -#if MayFullScreen -label_exit: - ; -#endif -} - -LOCALPROC Screen_DrawAll(void) -{ - HaveChangedScreenBuff(0, 0, vMacScreenHeight, vMacScreenWidth); -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ - DrawChangesAndClear(); -} - -LOCALFUNC bool InitTheCursor(void) -{ - SetCursor(LoadCursor(NULL, IDC_ARROW)); - return true; -} - -LOCALPROC MousePositionNotify(LONG NewMousePosx, LONG NewMousePosy) -{ - bool ShouldHaveCursorHidden = true; - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePosx -= hOffset; - NewMousePosy -= vOffset; - } -#endif - -#if 1 - if (UseMagnify) { - NewMousePosx /= WindowScale; - NewMousePosy /= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - NewMousePosx += ViewHStart; - NewMousePosy += ViewVStart; - } -#endif - { - if (NewMousePosx < 0) { - NewMousePosx = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosx > vMacScreenWidth) { - NewMousePosx = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePosy < 0) { - NewMousePosy = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosy > vMacScreenHeight) { - NewMousePosy = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ShouldHaveCursorHidden = true; - } -#endif - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePosx, NewMousePosy); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC CheckMouseState(void) -{ - POINT NewMousePos; - - GetCursorPos(&NewMousePos); - NewMousePos.x -= WndX; - NewMousePos.y -= WndY; - MousePositionNotify(NewMousePos.x, NewMousePos.y); -} - -LOCALVAR const uint8_t Native2MacRomanTab[] = { - 0xAD, 0xB0, 0xE2, 0xC4, 0xE3, 0xC9, 0xA0, 0xE0, - 0xF6, 0xE4, 0xB6, 0xDC, 0xCE, 0xB2, 0xB3, 0xB7, - 0xB8, 0xD4, 0xD5, 0xD2, 0xD3, 0xA5, 0xD0, 0xD1, - 0xF7, 0xAA, 0xC5, 0xDD, 0xCF, 0xB9, 0xC3, 0xD9, - 0xCA, 0xC1, 0xA2, 0xA3, 0xDB, 0xB4, 0xBA, 0xA4, - 0xAC, 0xA9, 0xBB, 0xC7, 0xC2, 0xBD, 0xA8, 0xF8, - 0xA1, 0xB1, 0xC6, 0xD7, 0xAB, 0xB5, 0xA6, 0xE1, - 0xFC, 0xDA, 0xBC, 0xC8, 0xDE, 0xDF, 0xF0, 0xC0, - 0xCB, 0xE7, 0xE5, 0xCC, 0x80, 0x81, 0xAE, 0x82, - 0xE9, 0x83, 0xE6, 0xE8, 0xED, 0xEA, 0xEB, 0xEC, - 0xF5, 0x84, 0xF1, 0xEE, 0xEF, 0xCD, 0x85, 0xF9, - 0xAF, 0xF4, 0xF2, 0xF3, 0x86, 0xFA, 0xFB, 0xA7, - 0x88, 0x87, 0x89, 0x8B, 0x8A, 0x8C, 0xBE, 0x8D, - 0x8F, 0x8E, 0x90, 0x91, 0x93, 0x92, 0x94, 0x95, - 0xFD, 0x96, 0x98, 0x97, 0x99, 0x9B, 0x9A, 0xD6, - 0xBF, 0x9D, 0x9C, 0x9E, 0x9F, 0xFE, 0xFF, 0xD8 -}; - -#if IncludePbufs -LOCALFUNC MacErr_t NativeTextToMacRomanPbuf(HGLOBAL x, tPbuf *r) -{ -#if UseUni -#define UnsignedChar uint16_t -#else -#define UnsignedChar uint8_t -#endif - HGLOBAL h; - LPTSTR p1; - uint32_t n; - UnsignedChar v; - MacErr_t err = mnvm_miscErr; - - p1 = GlobalLock(x); - if (p1 != NULL) { - n = 0; - while ((v = *p1++) != 0) { - if (v != 10) { - ++n; - } - } - (void) GlobalUnlock(x); - - h = GlobalAlloc(GMEM_DDESHARE, n); - if (h != NULL) { - p1 = GlobalLock(x); - if (p1 != NULL) { - uint8_t *p2 = GlobalLock(h); - if (p2 != NULL) { - while ((v = (UnsignedChar)*p1++) != 0) { - if (v >= 128) { - *p2++ = Native2MacRomanTab[v & 0x7F]; - /* - if UseUni, then for gives - garbage for v > 256. - */ - } else if (v != 10) { - *p2++ = v; - } - } - - err = mnvm_noErr; - - (void) GlobalUnlock(h); - } - (void) GlobalUnlock(x); - } - - if (mnvm_noErr != err) { - (void) GlobalFree(h); - } else { - err = PbufNewFromHandle(h, n, r); - } - } - } - - return err; -} -#endif - -LOCALVAR const uint8_t MacRoman2NativeTab[] = { - 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, - 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, - 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, - 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, - 0x86, 0xB0, 0xA2, 0xA3, 0xA7, 0x95, 0xB6, 0xDF, - 0xAE, 0xA9, 0x99, 0xB4, 0xA8, 0x80, 0xC6, 0xD8, - 0x81, 0xB1, 0x8D, 0x8E, 0xA5, 0xB5, 0x8A, 0x8F, - 0x90, 0x9D, 0xA6, 0xAA, 0xBA, 0xAD, 0xE6, 0xF8, - 0xBF, 0xA1, 0xAC, 0x9E, 0x83, 0x9A, 0xB2, 0xAB, - 0xBB, 0x85, 0xA0, 0xC0, 0xC3, 0xD5, 0x8C, 0x9C, - 0x96, 0x97, 0x93, 0x94, 0x91, 0x92, 0xF7, 0xB3, - 0xFF, 0x9F, 0xB9, 0xA4, 0x8B, 0x9B, 0xBC, 0xBD, - 0x87, 0xB7, 0x82, 0x84, 0x89, 0xC2, 0xCA, 0xC1, - 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, - 0xBE, 0xD2, 0xDA, 0xDB, 0xD9, 0xD0, 0x88, 0x98, - 0xAF, 0xD7, 0xDD, 0xDE, 0xB8, 0xF0, 0xFD, 0xFE -}; - -#if IncludePbufs -LOCALFUNC bool MacRomanTextToNativeHand(tPbuf Pbuf_no, - bool IsFileName, HGLOBAL *r) -{ - HGLOBAL h; - uint32_t i; - uint32_t rn = 0; - HGLOBAL bh = PbufDat[Pbuf_no]; - uint32_t L = PbufSize[Pbuf_no]; - bool IsOk = false; - - if (IsFileName) { - if (L > 255) { - L = 255; - } - } else { - uint8_t *Buffer = (uint8_t *)GlobalLock(bh); - if (Buffer != NULL) { - for (i = 0; i < L; ++i) { - if (Buffer[i] == 13) { - ++rn; - } - } - (void) GlobalUnlock(bh); - } - } - - h = GlobalAlloc(GMEM_DDESHARE, (L + rn + 1) * sizeof(TCHAR)); - if (h != NULL) { - uint8_t *Buffer = (uint8_t *)GlobalLock(bh); - if (Buffer != NULL) { - LPTSTR p1 = GlobalLock(h); - if (p1 != NULL) { - for (i = 0; i < L; ++i) { - TCHAR y; - uint8_t x = ((uint8_t *)Buffer)[i]; - if (x >= 128) { - y = (TCHAR)MacRoman2NativeTab[x - 128]; - } else { - if (IsFileName) { - if ((x < 32) - || ('\\' == x) || ('/' == x) - || (':' == x) || ('*' == x) - || ('?' == x) || ('"' == x) - || ('<' == x) || ('>' == x) - || ('|' == x)) - { - y = (TCHAR)('-'); - } else { - y = (TCHAR)x; - } - } else { - if (13 == x) { - *p1++ = (TCHAR)(13); - y = (TCHAR)(10); - } else { - y = (TCHAR)x; - } - } - } - *p1++ = y; - } - *p1++ = (TCHAR) 0; /* null character */ - - *r = h; - IsOk = true; - - (void) GlobalUnlock(h); - } - (void) GlobalUnlock(bh); - } - if (! IsOk) { - (void) GlobalFree(h); - } - } - - return IsOk; -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEexport(tPbuf i) -{ - HGLOBAL h; - MacErr_t err = mnvm_miscErr; - - if (MacRomanTextToNativeHand(i, false, &h)) { - if (! OpenClipboard(MainWnd)) { - /* ReportGetLastError(); */ - } else { - if (! EmptyClipboard()) { - /* ReportGetLastError(); */ - } - if (SetClipboardData(CF_TEXT, h) == NULL) { - /* ReportGetLastError(); */ - } else { - err = mnvm_noErr; - } - h = NULL; - if (! CloseClipboard()) { - /* ReportGetLastError(); */ - } - } - if (h != NULL) { - (void) GlobalFree(h); - } - } - - PbufDispose(i); - - return err; -} -#endif - -#if IncludeHostTextClipExchange -GLOBALOSGLUFUNC MacErr_t HTCEimport(tPbuf *r) -{ - MacErr_t err = mnvm_miscErr; - - if (IsClipboardFormatAvailable(CF_TEXT)) { - if (! OpenClipboard(MainWnd)) { - /* ReportGetLastError(); */ - } else { - HGLOBAL h = GetClipboardData(CF_TEXT); - if (h == NULL) { - /* ReportGetLastError(); */ - } else { - err = NativeTextToMacRomanPbuf(h, r); - } - if (! CloseClipboard()) { - /* ReportGetLastError(); */ - } - } - } - - return err; -} -#endif - -/* --- drives --- */ - -#define NotAfileRef INVALID_HANDLE_VALUE - -LOCALVAR HANDLE Drives[NumDrives]; /* open disk image files */ - -#define NeedDriveNames (IncludeSonyGetName || IncludeSonyNew) - -#if NeedDriveNames -LOCALVAR HGLOBAL DriveNames[NumDrives]; - /* - It is supposed to be possible to use - GetMappedFileName to get name of open file, - but that seems ugly kludge, so instead - save the name on open. - */ -#endif - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; -#if NeedDriveNames - DriveNames[i] = NULL; -#endif - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - HANDLE refnum; - DWORD newL; - MacErr_t result; - DWORD BytesTransferred = 0; - - refnum = Drives[Drive_No]; - newL = SetFilePointer( - refnum, /* handle of file */ - Sony_Start, /* number of bytes to move file pointer */ - nullpr, /* address of high-order word of distance to move */ - FILE_BEGIN /* how to move */ - ); - if (newL == 0xFFFFFFFF) { - result = mnvm_miscErr; /*& figure out what really to return &*/ - } else if (Sony_Start != (uint32_t)newL) { - /* not supposed to get here */ - result = mnvm_miscErr; /*& figure out what really to return &*/ - } else { - if (IsWrite) { - if (! WriteFile(refnum, /* handle of file to read */ - (LPVOID)Buffer - , /* address of buffer that receives data */ - (DWORD)Sony_Count, /* number of bytes to read */ - &BytesTransferred, /* address of number of bytes read */ - nullpr)) /* address of structure for data */ - { - result = mnvm_miscErr; - /*& figure out what really to return &*/ - } else if ((uint32_t)BytesTransferred != Sony_Count) { - result = mnvm_miscErr; - /*& figure out what really to return &*/ - } else { - result = mnvm_noErr; - } - } else { - if (! ReadFile(refnum, /* handle of file to read */ - (LPVOID)Buffer, - /* address of buffer that receives data */ - (DWORD)Sony_Count, /* number of bytes to read */ - &BytesTransferred, - /* address of number of bytes read */ - nullpr)) /* address of structure for data */ - { - result = mnvm_miscErr; - /*& figure out what really to return &*/ - } else if ((uint32_t)BytesTransferred != Sony_Count) { - result = mnvm_miscErr; - /*& figure out what really to return &*/ - } else { - result = mnvm_noErr; - } - } - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = BytesTransferred; - } - - return result; -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - MacErr_t result; - DWORD L; - - L = GetFileSize(Drives[Drive_No], nullpr); - if (L == 0xFFFFFFFF) { - result = mnvm_miscErr; /*& figure out what really to return &*/ - } else { - *Sony_Count = L; - result = mnvm_noErr; - } - - return result; -} - -LOCALFUNC MacErr_t vSonyEject0(tDrive Drive_No, bool deleteit) -{ - HANDLE refnum = Drives[Drive_No]; - -#if ! NeedDriveNames - UnusedParam(deleteit); -#endif - - Drives[Drive_No] = NotAfileRef; /* not really needed */ - - DiskEjectedNotify(Drive_No); - - (void) FlushFileBuffers(refnum); - (void) CloseHandle(refnum); - -#if NeedDriveNames - { - HGLOBAL h = DriveNames[Drive_No]; - if (NULL != h) { - if (deleteit) { - LPTSTR drivepath = GlobalLock(h); - if (drivepath != NULL) { - (void) DeleteFile(drivepath); - (void) GlobalUnlock(h); - } - } - (void) GlobalFree(h); - DriveNames[Drive_No] = NULL; /* not really needed */ - } - } -#endif - - return mnvm_noErr; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, false); -} - -#if IncludeSonyNew -GLOBALOSGLUFUNC MacErr_t vSonyEjectDelete(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, true); -} -#endif - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -#if NeedDriveNames -LOCALFUNC bool LPTSTRtoHand(LPTSTR s, HGLOBAL *r) -{ - bool IsOk = false; - - size_t L = _tcslen(s); - HGLOBAL h = GlobalAlloc(GMEM_DDESHARE, - (L + 1) * sizeof(TCHAR)); - if (h != NULL) { - LPTSTR p = GlobalLock(h); - if (p != NULL) { - _tcscpy(p, s); - IsOk = true; - (void) GlobalUnlock(h); - } - if (! IsOk) { - (void) GlobalFree(h); - } else { - *r = h; - } - } - - return IsOk; -} -#endif - -#if IncludeSonyGetName -GLOBALOSGLUFUNC MacErr_t vSonyGetName(tDrive Drive_No, tPbuf *r) -{ - WIN32_FIND_DATA fd; - MacErr_t err = mnvm_miscErr; - HGLOBAL ph = DriveNames[Drive_No]; - if (NULL != ph) { - LPTSTR drivepath = GlobalLock(ph); - if (drivepath != NULL) { - HANDLE hf = FindFirstFile(drivepath, &fd); - (void) GlobalUnlock(ph); - - if (hf != INVALID_HANDLE_VALUE) { - HGLOBAL h; - if (LPTSTRtoHand(fd.cFileName, &h)) { - err = NativeTextToMacRomanPbuf(h, r); - } - FindClose(hf); - } - } - } - - return err; -} -#endif - -LOCALFUNC bool Sony_Insert0(HANDLE refnum, bool locked, - LPTSTR drivepath) -{ - tDrive Drive_No; - -#if ! NeedDriveNames - UnusedParam(drivepath); -#endif - - if (! FirstFreeDisk(&Drive_No)) { - (void) CloseHandle(refnum); - MacMsg(kStrTooManyImagesTitle, - kStrTooManyImagesMessage, false); - return false; - } else { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); -#if NeedDriveNames - { - HGLOBAL h; - - if (! LPTSTRtoHand(drivepath, &h)) { - h = NULL; - } - - DriveNames[Drive_No] = h; - } -#endif - return true; - } -} - -LOCALFUNC bool Sony_Insert1(LPTSTR drivepath, bool SilentOnMissing) -{ - bool locked = false; - HANDLE refnum = CreateFile( - drivepath, /* pointer to name of the file */ - GENERIC_READ + GENERIC_WRITE, /* access (read-write) mode */ - 0, /* share mode */ - nullpr, /* pointer to security descriptor */ - OPEN_EXISTING, /* how to create */ - FILE_ATTRIBUTE_NORMAL, /* file attributes */ - nullpr /* handle to file with attributes to copy */ - ); - if (refnum == INVALID_HANDLE_VALUE) { - if (ERROR_ACCESS_DENIED == GetLastError()) { - locked = true; - refnum = CreateFile( - drivepath, /* pointer to name of the file */ - GENERIC_READ, /* access (read-write) mode */ - FILE_SHARE_READ, /* share mode */ - nullpr, /* pointer to security descriptor */ - OPEN_EXISTING, /* how to create */ - FILE_ATTRIBUTE_NORMAL, /* file attributes */ - nullpr /* handle to file with attributes to copy */ - ); - } - } - if (refnum == INVALID_HANDLE_VALUE) { - DWORD err = GetLastError(); - if (ERROR_SHARING_VIOLATION == err) { - MacMsg(kStrImageInUseTitle, - kStrImageInUseMessage, false); - } else if ((ERROR_FILE_NOT_FOUND == err) && SilentOnMissing) { - /* ignore it */ - } else { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } else { - return Sony_Insert0(refnum, locked, drivepath); - } - return false; -} - -LOCALFUNC bool LoadMacRomFromPath(LPTSTR drivepath) -{ - HANDLE refnum = INVALID_HANDLE_VALUE; - bool IsOk = false; - - refnum = CreateFile( - drivepath, /* pointer to name of the file */ - GENERIC_READ, /* access (read-write) mode */ - FILE_SHARE_READ, /* share mode */ - nullpr, /* pointer to security descriptor */ - OPEN_EXISTING, /* how to create */ - FILE_ATTRIBUTE_NORMAL, /* file attributes */ - nullpr /* handle to file with attributes to copy */ - ); - - if (refnum == INVALID_HANDLE_VALUE) { - /* MacMsg(kStrNoROMTitle, kStrNoROMMessage, true); */ - } else { - DWORD BytesRead; - - if (! ReadFile(refnum, /* handle of file to read */ - (LPVOID)ROM, /* address of buffer that receives data */ - (DWORD)kROM_Size, /* number of bytes to read */ - &BytesRead, /* address of number of bytes read */ - nullpr)) /* address of structure for data */ - { - MacMsgOverride(kStrNoReadROMTitle, kStrNoReadROMMessage); - } else - if ((uint32_t)BytesRead != kROM_Size) { - MacMsgOverride(kStrShortROMTitle, kStrShortROMMessage); - } else - { - IsOk = (mnvm_noErr == ROM_IsValid()); - } - (void) CloseHandle(refnum); - } - - return IsOk; -} - -#ifndef EnableShellLinks -#define EnableShellLinks 1 -#endif - -#if EnableShellLinks -LOCALVAR bool COMinited = false; -LOCALVAR bool COMinitedOK; -#endif - -#if EnableShellLinks -LOCALPROC UninitCOM(void) -{ - if (COMinited) { - CoUninitialize(); - } -} -#endif - -#if EnableShellLinks -LOCALFUNC bool NeedCOM(void) -{ - HRESULT hres; - - if (! COMinited) { - COMinitedOK = false; - hres = CoInitialize(NULL); - if (SUCCEEDED(hres)) { - COMinitedOK = true; - } - - COMinited = true; - } - return COMinitedOK; -} -#endif - -#if EnableShellLinks -LOCALFUNC bool ResolveShortcut(LPTSTR FilePath, bool *directory) -/* adapted from Microsoft example code */ -{ - HRESULT hres; - IShellLink *psl; - IPersistFile* ppf; - TCHAR szGotPath[MAX_PATH]; - WIN32_FIND_DATA wfd; - bool IsOk = false; - - if (NeedCOM()) { - hres = CoCreateInstance(&CLSID_ShellLink, NULL, - CLSCTX_INPROC_SERVER, &IID_IShellLink, - (LPVOID *)(void *)&psl); - /* - the (void *) prevents a compiler warning - from gcc - */ - if (SUCCEEDED(hres)) { - /* Get a pointer to the IPersistFile interface. */ - hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, - (void **)(void *)&ppf); - if (SUCCEEDED(hres)) { - /* Ensure that the string is Unicode. */ -#if UseUni -#define wsz FilePath -#else - WORD wsz[MAX_PATH]; - MultiByteToWideChar(CP_ACP, 0, FilePath, -1, wsz, - MAX_PATH); -#endif - - /* Load the shortcut. */ - hres = ppf->lpVtbl->Load(ppf, wsz, STGM_READ); - if (SUCCEEDED(hres)) { - /* Resolve the link. */ - hres = psl->lpVtbl->Resolve(psl, MainWnd, - SLR_ANY_MATCH); - if (SUCCEEDED(hres)) { - /* Get the path to the link target. */ - hres = psl->lpVtbl->GetPath(psl, szGotPath, - MAX_PATH, &wfd, - SLGP_SHORTPATH); - if (SUCCEEDED(hres)) { - /* - This is in the sample code, but doesn't - seem to be needed: - Get the description of the target. - char szDescription[MAX_PATH]; - hres = psl->lpVtbl->GetDescription(psl, - szDescription, MAX_PATH); - if (SUCCEEDED(hres)) { - } - */ - lstrcpy(FilePath, szGotPath); - if (NULL != directory) { - *directory = (0 != (wfd.dwFileAttributes - & FILE_ATTRIBUTE_DIRECTORY)); - } - IsOk = true; - } - } - } - - ppf->lpVtbl->Release(ppf); - } - psl->lpVtbl->Release(psl); - } - } - return IsOk; -} -#endif - -#if EnableShellLinks -LOCALFUNC bool FileIsLink(LPTSTR drivepath) -{ - LPTSTR p = FindLastTerm(drivepath, (TCHAR)('.')); - - if (p != nullpr) { - if (_tcscmp(p, TEXT("lnk")) == 0) { - return true; - } - } - return false; -} -#endif - -LOCALFUNC bool InsertDiskOrAlias(LPTSTR drivepath, - bool MaybeROM, bool MaybeAlias) -{ -#if EnableShellLinks - if (MaybeAlias && FileIsLink(drivepath)) { - if (! ResolveShortcut(drivepath, NULL)) { - return false; - } - } -#endif - - if (MaybeROM && ! ROM_loaded) { - return LoadMacRomFromPath(drivepath); - } else { - return Sony_Insert1(drivepath, false); - } -} - -LOCALFUNC bool FileExists(LPTSTR pathName, bool *directory) -{ - WIN32_FIND_DATA fd; - HANDLE hf = FindFirstFile(pathName, &fd); - bool IsOk = false; - - if (hf != INVALID_HANDLE_VALUE) { - if (NULL != directory) { - *directory = - (0 != (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)); - } - IsOk = true; - FindClose(hf); - } - - return IsOk; -} - -LOCALFUNC MacErr_t ResolveNamedChild0(LPTSTR pathName, - LPTSTR Child, bool *directory) -{ - size_t newlen; - size_t oldlen = _tcslen(pathName); - MacErr_t err = mnvm_miscErr; - - newlen = oldlen + 1 + _tcslen(Child); - if (newlen + 1 < _MAX_PATH) { - _tcscat(pathName, TEXT("\\")); - _tcscat(pathName, Child); - - if (FileExists(pathName, directory)) { - err = mnvm_noErr; - } else { - err = mnvm_fnfErr; -#if EnableShellLinks - if (newlen + 5 < _MAX_PATH) { - _tcscat(pathName, TEXT(".lnk")); - if (FileExists(pathName, NULL)) - if (ResolveShortcut(pathName, directory)) - { - err = mnvm_noErr; - } - if (mnvm_noErr != err) { - pathName[newlen] = (TCHAR)('\0'); - } - } -#endif - } - } - - return err; -} - -LOCALFUNC MacErr_t ResolveNamedChild(LPTSTR pathName, - char *Child, bool *directory) -{ - TCHAR Child0[ClStrMaxLength + 1]; - - NativeStrFromCStr(Child0, Child, false); - - return ResolveNamedChild0(pathName, Child0, directory); -} - -LOCALFUNC bool ResolveNamedChildDir(LPTSTR pathName, char *Child) -{ - bool directory; - - return (mnvm_noErr == ResolveNamedChild( - pathName, Child, &directory)) - && directory; -} - -LOCALFUNC bool ResolveNamedChildFile(LPTSTR pathName, char *Child) -{ - bool directory; - - return (mnvm_noErr == ResolveNamedChild( - pathName, Child, &directory)) - && ! directory; -} - -#if (IncludeSonyNew && ! SaveDialogEnable) -LOCALFUNC bool MakeNamedChildDir(LPTSTR pathName, char *Child) -{ - bool directory; - bool IsOk = false; - MacErr_t err = ResolveNamedChild(pathName, Child, &directory); - - if (mnvm_noErr == err) { - IsOk = directory; - } else if (mnvm_fnfErr == err) { - if (CreateDirectory(pathName, NULL)) { - IsOk = true; - } - } - - return IsOk; -} -#endif - -LOCALFUNC bool GetAppDataPath(LPTSTR lpszPath, - BOOL fCreate) -{ - bool IsOk = false; - - if (HaveMySHGetSpecialFolderPath()) - if (MySHGetSpecialFolderPath( - NULL /* HWND hwndOwner */, - lpszPath, _CSIDL_APPDATA, fCreate)) - { - IsOk = true; - } - /* - if not available, could perhaps - use GetWindowsDirectory. - */ - /* - SHGetFolderPath is more recent, - could perhaps check for it first. - might also be in "SHFolder.dll". - - SHGetKnownFolderPath is even - more recent. - */ - - return IsOk; -} - -LOCALPROC InsertADisk0(void) -{ - OPENFILENAME ofn; - TCHAR szDirName[256]; - TCHAR szFile[256]; - TCHAR szFileTitle[256]; - UINT i; - size_t cbString; - TCHAR chReplace; - TCHAR szFilter[256]; - bool IsOk; - - szDirName[0] = (TCHAR)('\0'); - szFile[0] = (TCHAR)('\0'); - _tcscpy(szFilter, - TEXT("Disk images|*.dsk;*.HF?;*.IMG;*.IMA;*.IMAGE") - TEXT("|All files (*.*)|*.*|\0")); - - cbString = _tcslen(szFilter); - - chReplace = szFilter[cbString - 1]; - - for (i = 0; szFilter[i] != (TCHAR)('\0'); ++i) - { - if (szFilter[i] == chReplace) { - szFilter[i] = (TCHAR)('\0'); - } - } - - memset(&ofn, 0, sizeof(OPENFILENAME)); - - ofn.lStructSize = sizeof(OPENFILENAME); - ofn.hwndOwner = MainWnd; - ofn.lpstrFilter = szFilter; - ofn.nFilterIndex = 2; - ofn.lpstrFile= szFile; - ofn.nMaxFile = sizeof(szFile); - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = sizeof(szFileTitle); - ofn.lpstrInitialDir = szDirName; - ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST - | OFN_HIDEREADONLY; - - MyBeginDialog(); - IsOk = GetOpenFileName(&ofn); - MyEndDialog(); - - if(! IsOk) { - /* report error */ - } else { - (void) InsertDiskOrAlias(ofn.lpstrFile, - true, false); - } -} - -LOCALFUNC bool LoadInitialImageFromName(char *ImageName) -{ - TCHAR ImageFile[_MAX_PATH]; - - if (GetAppDir(ImageFile)) - if (ResolveNamedChildFile(ImageFile, ImageName)) - if (Sony_Insert1(ImageFile, true)) - { - return true; - } - return false; -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - bool v; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - v = false; - } else { - char s[] = "disk?.dsk"; - - s[4] = '0' + i; - - /* stop on first error (including file not found) */ - v = LoadInitialImageFromName(s); - } - - return v; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - if (! AnyDiskInserted()) { - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - } - - return true; -} - -#if IncludeSonyNew -LOCALFUNC bool WriteZero(HANDLE refnum, uint32_t L) -{ - if (SetFilePointer( - refnum, /* handle of file */ - 0, /* number of bytes to move file pointer */ - nullpr, /* address of high-order word of distance to move */ - FILE_BEGIN /* how to move */ - ) != 0) - { - return false; - } else { -#define ZeroBufferSize 2048 - uint32_t i; - uint8_t buffer[ZeroBufferSize]; - DWORD BytesWritten; - - memset(&buffer, 0, ZeroBufferSize); - - while (L > 0) { - i = (L > ZeroBufferSize) ? ZeroBufferSize : L; - if (! WriteFile(refnum, /* handle of file to read */ - (LPVOID)buffer, - /* address of buffer that receives data */ - (DWORD)i, /* number of bytes to read */ - &BytesWritten, /* address of number of bytes read */ - nullpr) /* address of structure for data */ - || ((uint32_t)BytesWritten != i)) - { - return false; - } - L -= i; - } - return true; - } -} -#endif - -#define MaxSavePathSize MAX_PATH - -#if IncludeSonyNew -LOCALPROC MakeNewDisk0(uint32_t L, LPTSTR pathName) -{ - bool IsOk = false; - HANDLE newrefNum; - - IsOk = false; - newrefNum = CreateFile( - pathName, /* pointer to name of the file */ - GENERIC_READ + GENERIC_WRITE, /* access (read-write) mode */ - 0, /* share mode */ - NULL, /* pointer to security descriptor */ - CREATE_ALWAYS, /* how to create */ - FILE_ATTRIBUTE_NORMAL, /* file attributes */ - NULL /* handle to file with attributes to copy */ - ); - if (newrefNum == INVALID_HANDLE_VALUE) { - /* report error */ - } else { - if (SetFilePointer( - newrefNum, /* handle of file */ - L, /* number of bytes to move file pointer */ - nullpr, - /* address of high-order word of distance to move */ - FILE_BEGIN /* how to move */ - ) != L) - { - /* report error */ - } else if (! SetEndOfFile(newrefNum)) { - /* report error */ - } else if (! WriteZero(newrefNum, L)) { - /* report error */ - } else { - IsOk = - Sony_Insert0(newrefNum, false, pathName); - newrefNum = INVALID_HANDLE_VALUE; - } - if (INVALID_HANDLE_VALUE != newrefNum) { - (void) CloseHandle(newrefNum); - } - if (! IsOk) { - (void) DeleteFile(pathName); - } - } -} -#endif - -#if IncludeSonyNew -LOCALPROC MakeNewDisk(uint32_t L, HGLOBAL NewDiskNameDat) -{ -#if SaveDialogEnable - OPENFILENAME ofn; - bool IsOk = false; - TCHAR szFile[MaxSavePathSize]; - TCHAR szFileTitle[MaxSavePathSize]; - - memset(&ofn, 0, sizeof(OPENFILENAME)); - szFile[0] = 0; - szFileTitle[0] = 0; - -#if IncludeSonyGetName - if (NewDiskNameDat != NULL) { - LPTSTR p = GlobalLock(NewDiskNameDat); - if (p != NULL) { - _tcscpy(szFile, p); - (void) GlobalUnlock(NewDiskNameDat); - } - } else -#endif - { - NativeStrFromCStr(szFile, "untitled", false); - } - - ofn.lStructSize = sizeof(OPENFILENAME); - ofn.lpstrFile = szFile; - ofn.hwndOwner = MainWnd; - /* ofn.lpstrFilter = "All\0*.*\0Text\0*.txt\0Datafile\0*.dsk\0"; */ - /* ofn.lpstrFilter = NULL; */ /* szFilter */ - ofn.nMaxFile = MaxSavePathSize; - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = MaxSavePathSize; - ofn.lpstrInitialDir = NULL; - ofn.Flags = OFN_OVERWRITEPROMPT + OFN_HIDEREADONLY; - /* + OFN_SHOWHELP */ - - MyBeginDialog(); - IsOk = GetSaveFileName(&ofn); - MyEndDialog(); - - if (! IsOk) { - /* report error */ - } else { - MakeNewDisk0(L, ofn.lpstrFile); - } -#else /* SaveDialogEnable */ - TCHAR pathName[MaxSavePathSize]; - - if (GetAppDir(pathName)) - if (MakeNamedChildDir(pathName, "out")) - { - bool directory; - LPTSTR p = GlobalLock(NewDiskNameDat); - - if (p != NULL) { - MacErr_t err = ResolveNamedChild0(pathName, p, - &directory); - - if (mnvm_fnfErr == err) { - err = mnvm_noErr; - } else if (mnvm_noErr == err) { - if (directory) { - err = mnvm_miscErr; - } - } - - if (mnvm_noErr == err) { - MakeNewDisk0(L, pathName); - } - - (void) GlobalUnlock(NewDiskNameDat); - } - } -#endif /* SaveDialogEnable */ -} -#endif - -LOCALFUNC bool LoadMacRom(void) -{ - TCHAR ROMFile[_MAX_PATH]; - bool IsOk = false; - - if (GetAppDir(ROMFile)) - if (ResolveNamedChildFile(ROMFile, RomFileName)) - { - IsOk = true; - } - - if (! IsOk) { - if (GetAppDataPath(ROMFile, FALSE)) - if (ResolveNamedChildDir(ROMFile, "Gryphel")) - if (ResolveNamedChildDir(ROMFile, "mnvm_rom")) - if (ResolveNamedChildFile(ROMFile, RomFileName)) - { - IsOk = true; - } - - } - - if (IsOk) { - IsOk = LoadMacRomFromPath(ROMFile); - } - - return true; -} - -#if InstallFileIcons -LOCALPROC SetRegKey(HKEY hKeyRoot, - LPTSTR strRegKey, LPTSTR strRegValue) -{ - HKEY RegKey; - DWORD dwDisposition; - - if (ERROR_SUCCESS == RegCreateKeyEx(hKeyRoot, strRegKey, 0, NULL, - REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, - NULL, &RegKey, &dwDisposition)) - { - RegSetValueEx(RegKey, NULL, 0, REG_SZ, - (CONST BYTE *)strRegValue, - (DWORD)((_tcslen(strRegValue) + 1) * sizeof(TCHAR))); - RegCloseKey(RegKey); - } -} - -LOCALPROC RegisterShellFileType(LPTSTR AppPath, LPTSTR strFilterExt, - LPTSTR strFileTypeId, LPTSTR strFileTypeName, - LPTSTR strIconId, bool CanOpen) -{ - TCHAR strRegKey[_MAX_PATH]; - TCHAR strRegValue[_MAX_PATH + 2]; - /* extra room for ","{strIconId} */ - - SetRegKey(HKEY_CLASSES_ROOT, strFileTypeId, strFileTypeName); - SetRegKey(HKEY_CLASSES_ROOT, strFilterExt, strFileTypeId); - - _tcscpy(strRegKey, strFileTypeId); - _tcscat(strRegKey, TEXT("\\DefaultIcon")); - _tcscpy(strRegValue, TEXT("\"")); - _tcscat(strRegValue, AppPath); - _tcscat(strRegValue, TEXT("\",")); - _tcscat(strRegValue, strIconId); - SetRegKey(HKEY_CLASSES_ROOT, strRegKey, strRegValue); - - if (CanOpen) { - _tcscpy(strRegKey, strFileTypeId); - _tcscat(strRegKey, TEXT("\\shell\\open\\command")); - _tcscpy(strRegValue, TEXT("\"")); - _tcscat(strRegValue, AppPath); - _tcscat(strRegValue, TEXT("\" \"%1\"")); - SetRegKey(HKEY_CLASSES_ROOT, strRegKey, strRegValue); - } -} - -LOCALFUNC bool RegisterInRegistry(void) -{ - TCHAR AppPath[_MAX_PATH]; - - GetModuleFileName(NULL, AppPath, _MAX_PATH); -#if 0 - GetShortPathName(AppPath, AppPath, _MAX_PATH); -#endif - - RegisterShellFileType(AppPath, TEXT(".rom"), TEXT("minivmac.rom"), - TEXT("Mini vMac ROM Image"), TEXT("1"), false); - RegisterShellFileType(AppPath, TEXT(".dsk"), TEXT("minivmac.dsk"), - TEXT("Mini vMac Disk Image"), TEXT("2"), true); - - return true; -} -#endif - -LOCALVAR LPTSTR CommandLine; - -LOCALFUNC bool ScanCommandLine(void) -{ - TCHAR *p = CommandLine; - TCHAR *p1; - TCHAR *p2; - TCHAR v; - size_t L; - - v = *p; - while (0 != v) { - if (' ' == v) { - v = *++p; - } else { - if ('\"' == v) { - v = *++p; - p1 = p; - while (('\"' != v) && (0 != v)) { - v = *++p; - } - p2 = p; - if ('\"' == v) { - v = *++p; - } - } else { - p1 = p; - while ((' ' != v) && (0 != v)) { - v = *++p; - } - p2 = p; - } - L = p2 - p1; - if (L + 1 <= _MAX_PATH) { - TCHAR fileName[_MAX_PATH]; - TCHAR *filePtr = fileName; - size_t i = L; - - while (i > 0) { - *filePtr++ = *p1++; - --i; - } - *filePtr = (char)0; - - if ((L > 0) - && (('/' == fileName[0]) || ('-' == fileName[0]))) - { -#if 0 - TCHAR *p3 = &fileName[1]; - if (0 == _tcscmp(p3, TEXT("l"))) { - SpeedValue = 0; - } else -#endif - { - MacMsg(kStrBadArgTitle, kStrBadArgMessage, - false); - } - } else { - (void) InsertDiskOrAlias(fileName, - false, true); - } - } - } - } - - return true; -} - -#if EnableRecreateW -LOCALPROC CheckMagnifyAndFullScreen(void) -{ - if ( -#if 1 - (UseMagnify != WantMagnify) -#endif -#if 1 && 1 - || -#endif -#if 1 - (UseFullScreen != WantFullScreen) -#endif - ) - { - (void) ReCreateMainWindow(); - } -} -#endif - -#if 1 && 1 -enum { - kWinStateWindowed, -#if 1 - kWinStateFullScreen, -#endif - kNumWinStates -}; -#endif - -#if 1 && 1 -LOCALVAR int WinMagStates[kNumWinStates]; -#endif - -LOCALPROC ZapWinStateVars(void) -{ -#if MayNotFullScreen - { - int i; - - for (i = 0; i < kNumMagStates; ++i) { - HavePositionWins[i] = false; - } - } -#endif -#if 1 && 1 - { - int i; - - for (i = 0; i < kNumWinStates; ++i) { - WinMagStates[i] = kMagStateAuto; - } - } -#endif -} - -#if 1 -void ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; - -#if 1 - { - int OldWinState = - UseFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int OldMagState = - UseMagnify ? kMagStateMagnifgy : kMagStateNormal; - int NewWinState = - WantFullScreen ? kWinStateFullScreen : kWinStateWindowed; - int NewMagState = WinMagStates[NewWinState]; - - WinMagStates[OldWinState] = OldMagState; - if (kMagStateAuto != NewMagState) { - WantMagnify = (kMagStateMagnifgy == NewMagState); - } else { - WantMagnify = false; - if (WantFullScreen) { - if ((GetSystemMetrics(SM_CXSCREEN) - >= vMacScreenWidth * WindowScale) - && (GetSystemMetrics(SM_CYSCREEN) - >= vMacScreenHeight * WindowScale) - ) - { - WantMagnify = true; - } - } - } - } -#endif -} -#endif - -#if EnableDragDrop -LOCALPROC DragFunc(HDROP hDrop) -{ - WORD n; - WORD i; - TCHAR a[_MAX_PATH]; - - n = DragQueryFile(hDrop, (UINT) -1, NULL, 0); - for (i = 0; i < n; ++i) { - if (DragQueryFile(hDrop, i, NULL, 0) < _MAX_PATH - 1) { - (void) DragQueryFile(hDrop, i, a, _MAX_PATH); - (void) InsertDiskOrAlias(a, true, true); - } - } - - DragFinish(hDrop); - - if (gTrueBackgroundFlag) { - if (! SetForegroundWindow(MainWnd)) { - /* error message here ? */ - } - - WantCmdOptOnReconnect = true; - } -} -#endif - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ -#if SoundEnabled - SoundCheckVeryOften(); -#endif - (void) UpdateTrueEmulatedTime(); - return (TrueEmulatedTime == OnTrueTime); -} - -/* --- platform independent code can be thought of as going here --- */ - -LOCALPROC LeaveBackground(void) -{ - ReconnectKeyCodes3(); -} - -LOCALPROC EnterBackground(void) -{ - DisconnectKeyCodes3(); - -#if 1 - if (WantFullScreen) { - ToggleWantFullScreen(); - } -#endif -} - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif -#if (TimeResolution != 0) - Timer_Resume(); -#endif -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if (TimeResolution != 0) - Timer_Suspend(); -#endif -#if SoundEnabled - Sound_Stop(); -#endif -} - -LOCALPROC CheckForSavedTasks(void) -{ - /* - Check for things to do that rather wouldn't - have done at an awkward time. - */ - - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (gTrueBackgroundFlag != gBackgroundFlag) { - gBackgroundFlag = gTrueBackgroundFlag; - if (gTrueBackgroundFlag) { - EnterBackground(); - } else { - LeaveBackground(); - } - } - - if (CurSpeedStopped != (SpeedStopped || - (gBackgroundFlag && ! RunInBackground))) - { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - -#if EnableRecreateW - if (! (gTrueBackgroundFlag)) { - CheckMagnifyAndFullScreen(); - } -#endif - -#if MayFullScreen - if (GrabMachine != ( -#if 1 - UseFullScreen && -#endif - ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - GrabMachine = ! GrabMachine; - AdjustMachineGrab(); - } -#endif - - if (gTrueBackgroundFlag) { - /* - wait til later - */ - } else { -#if IncludeSonyNew - if (vSonyNewDiskWanted) { -#if IncludeSonyNameNew - if (vSonyNewDiskName != NotAPbuf) { - HGLOBAL NewDiskNameDat; - if (MacRomanTextToNativeHand(vSonyNewDiskName, true, - &NewDiskNameDat)) - { - MakeNewDisk(vSonyNewDiskSize, NewDiskNameDat); - GlobalFree(NewDiskNameDat); - } - PbufDispose(vSonyNewDiskName); - vSonyNewDiskName = NotAPbuf; - } else -#endif - { - MakeNewDisk(vSonyNewDiskSize, NULL); - } - vSonyNewDiskWanted = false; - /* must be done after may have gotten disk */ - } -#endif - if (RequestInsertDisk) { - RequestInsertDisk = false; - InsertADisk0(); - } - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif - - if (HaveCursorHidden != (WantCursorHidden - && ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - HaveCursorHidden = ! HaveCursorHidden; - if (HaveCursorHidden) { - (void) ShowCursor(FALSE); - } else { - (void) ShowCursor(TRUE); - SetCursor(LoadCursor(NULL, IDC_ARROW)); - } - } - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } -} - -LRESULT CALLBACK Win32WMProc(HWND hwnd, - UINT uMessage, WPARAM wparam, LPARAM lparam); - -LRESULT CALLBACK Win32WMProc(HWND hwnd, - UINT uMessage, WPARAM wparam, LPARAM lparam) -{ - switch (uMessage) - { - case WM_PAINT: - { - PAINTSTRUCT ps; - - BeginPaint(hwnd, (LPPAINTSTRUCT)&ps); -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - if (! FillRect(ps.hdc, - &ps.rcPaint, - GetStockObject(BLACK_BRUSH))) - { - /* ReportGetLastError(); */ - } - } -#endif - if (MainWnd == hwnd) { - Screen_DrawAll(); - } - EndPaint(hwnd, (LPPAINTSTRUCT)&ps); - } - break; - - case WM_KEYDOWN: - case WM_SYSKEYDOWN: - if (! TestBit(lparam, 30)) { /* ignore repeats */ - DoVKcode(wparam, lparam >> 24, true); - } - break; - case WM_KEYUP: - case WM_SYSKEYUP: - DoVKcode(wparam, lparam >> 24, false); - break; -#if ItnlKyBdFix - case WM_INPUTLANGCHANGE: - CheckKeyboardLayout(); - return TRUE; - break; -#endif - - case WM_CLOSE: - RequestMacOff = true; - break; - case WM_QUERYENDSESSION: - if (AnyDiskInserted()) { - RequestMacOff = true; - return FALSE; - } else { - return TRUE; - } - break; - case WM_ACTIVATE: - if (MainWnd == hwnd) { - gTrueBackgroundFlag = (LOWORD(wparam) == WA_INACTIVE); - } - break; - case WM_COMMAND: - switch(LOWORD(wparam)) - { - case ID_FILE_INSERTDISK1: - RequestInsertDisk = true; - break; - case ID_FILE_QUIT: - RequestMacOff = true; - break; - case ID_SPECIAL_MORECOMMANDS: - DoMoreCommandsMsg(); - break; - case ID_HELP_ABOUT: - DoAboutMsg(); - break; - } - break; - case WM_MOVE: - WndX = (int16_t) LOWORD(lparam); - WndY = (int16_t) HIWORD(lparam); - break; - case WM_SYSCHAR: - case WM_CHAR: - /* prevent any further processing */ - break; - case WM_LBUTTONDOWN: - case WM_RBUTTONDOWN: - MousePositionNotify(LOWORD (lparam), HIWORD (lparam)); - SetCurMouseButton(true); - break; - case WM_LBUTTONUP: - case WM_RBUTTONUP: - MousePositionNotify(LOWORD (lparam), HIWORD (lparam)); - SetCurMouseButton(false); - break; - case WM_MOUSEMOVE: - /* windows may have messed up cursor */ - /* - there is no notification when the mouse moves - outside the window, and the cursor is automatically - changed - */ - if (! HaveCursorHidden) { - /* SetCursor(LoadCursor(NULL, IDC_ARROW)); */ - } - break; -#if EnableDragDrop - case WM_CREATE: - DragAcceptFiles(hwnd, TRUE); - break; - case WM_DROPFILES: - DragFunc((HDROP) wparam); - break; - case WM_DESTROY: - DragAcceptFiles(hwnd, FALSE); - break; -#endif - default: - return DefWindowProc(hwnd, uMessage, wparam, lparam); - } - return 0; -} - -LOCALFUNC bool RegisterOurClass(void) -{ - WNDCLASS wc; - - wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; - wc.lpfnWndProc = (WNDPROC)Win32WMProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = AppInstance; - wc.hIcon = LoadIcon(AppInstance, MAKEINTRESOURCE(IDI_VMAC)); - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = GetStockObject(BLACK_BRUSH); - wc.lpszMenuName = NULL; - wc.lpszClassName = WndClassName; - - if (! RegisterClass(&wc)) { - MacMsg("RegisterClass failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - return false; - } else { - return true; - } -} - -LOCALPROC WaitForTheNextEvent(void) -{ - MSG msg; - - if (-1 != GetMessage(&msg, NULL, 0, 0)) { - DispatchMessage(&msg); - } -} - -LOCALPROC CheckForSystemEvents(void) -{ - MSG msg; - uint8_t i = 0; - - while ((i < 32) && (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))) { - DispatchMessage(&msg); - ++i; - } -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ -label_retry: - CheckForSystemEvents(); - CheckForSavedTasks(); - - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - WaitForTheNextEvent(); - goto label_retry; - } - - if (ExtraTimeNotOver()) { - Sleep(NextIntTime - LastTime); - goto label_retry; - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - if (! (gBackgroundFlag)) { - CheckMouseState(); - -#if EnableGrabSpecialKeys - CheckForLostKeyUps(); -#endif - } - - OnTrueTime = TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime); -#endif -} - -#include "PROGMAIN.h" - -/* ************************ */ - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); - ZapWinStateVars(); -} - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif -#if EnableScalingBuff - { - uint32_t n = vMacScreenMonoNumBytes -#if 1 - * WindowScale * WindowScale -#endif - ; - if ((vMacScreenDepth == 1) && (vMacScreenNumBytes * 2 > n)) { - n = vMacScreenNumBytes * 2; - } - else if ((vMacScreenDepth >= 4) && (vMacScreenNumBytes > n)) { - n = vMacScreenNumBytes; - } - ReserveAllocOneBlock(&ScalingBuff, n, 5, false); - } -#endif -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = - (uint8_t *)GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALPROC UnallocMemory(void) -{ - if (nullpr != ReserveAllocBigBlock) { - if (GlobalFree(ReserveAllocBigBlock) != NULL) { - MacMsg("error", "GlobalFree failed", false); - } - } -} - -LOCALFUNC bool InitOSGLU(void) -{ - if (AllocMemory()) -#if dbglog_HAVE - if (dbglog_open()) -#endif - if (RegisterOurClass()) - if (ScanCommandLine()) - if (LoadInitialImages()) -#if InstallFileIcons - if (RegisterInRegistry()) -#endif - if (LoadMacRom()) - if (ReCreateMainWindow()) - if (InitWinKey2Mac()) - if (InitTheCursor()) - if (Init60thCheck()) - if (WaitForRom()) - { - return true; - } - return false; -} - -LOCALPROC UnInitOSGLU(void) -{ -#if (TimeResolution != 0) - Timer_Suspend(); -#endif - MouseCaptureSet(false); - - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - -#if MayFullScreen - UnGrabTheMachine(); -#endif -#if SoundEnabled - Sound_Stop(); -#endif -#if IncludePbufs - UnInitPbufs(); -#endif - UnInitDrives(); - - ForceShowCursor(); - -#if EnableShellLinks - UninitCOM(); -#endif - - if (! gTrueBackgroundFlag) { - CheckSavedMacMsg(); - } - - DisposeMainWindow(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - UnallocMemory(); -} - -int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, int nCmdShow) -{ - UnusedParam(hPrevInstance); - AppInstance = hInstance; - CmdShow = nCmdShow; - CommandLine = lpCmdLine; - - GetWndTitle(); - ZapOSGLUVars(); - if (InitOSGLU()) { - ProgramMain(); - } - UnInitOSGLU(); - - return(0); -} diff --git a/src/UI/_deprecated/WIN32/OSGLUWIN.h b/src/UI/_deprecated/WIN32/OSGLUWIN.h deleted file mode 100644 index 9b6bcf3..0000000 --- a/src/UI/_deprecated/WIN32/OSGLUWIN.h +++ /dev/null @@ -1,150 +0,0 @@ -#ifndef OSGLUWIN_H -#define OSGLUWIN_H - -#include "SYSDEPNS.h" -#include "CNFGRAPI.h" -#include "CNFGGLOB.h" -#include "UI/COMOSGLU.h" -#include "UI/CONTROLM.h" -#include "UI/WIN32/SOUND.h" - -/* Define the undefined */ - -#ifndef ItnlKyBdFix -#define ItnlKyBdFix 0 -#endif - -#ifdef UNICODE -#define UseUni 1 -#else -#define UseUni 0 -#endif - -#ifndef InstallFileIcons -#define InstallFileIcons 0 -#endif - -#ifndef EnableGrabSpecialKeys -#define EnableGrabSpecialKeys (MayFullScreen && GrabKeysFullScreen) -#endif /* EnableGrabSpecialKeys */ - -/* Resource Ids */ - -#define IDI_VMAC 256 -#if InstallFileIcons -#define IDI_ROM 257 -#define IDI_DISK 258 -#endif - -/* API differences */ - -bool GetAppDir(LPTSTR pathName); - -/* Utilities (move?) */ - -#define TestBit(i, p) (((unsigned long)(i) & PowOf2(p)) != 0) - -/* Parameter buffers */ - -#if IncludePbufs -#define PbufHaveLock 1 -HGLOBAL PbufDat[NumPbufs]; -#endif - -/* Main window info */ - -extern HWND MainWnd; -HINSTANCE AppInstance; -int WndX; -int WndY; -extern bool UseFullScreen; -extern bool UseMagnify; - -#if MayFullScreen -short hOffset; -short vOffset; -#endif - -void ToggleWantFullScreen(void); - -/* cursor */ - -extern bool HaveCursorHidden; -extern bool WantCursorHidden; -extern bool MouseCaptured; - -void SetCurMouseButton(bool v); - -/* Keyboard */ - -#ifdef ItnlKyBdFix -uint8_t VkMapA[256]; -void InitCheckKeyboardLayout(void); -void CheckKeyboardLayout(void); -#endif - -/* these constants weren't in the header files I have */ -#define myVK_Subtract 0xBD -#define myVK_Equal 0xBB -#define myVK_BackSlash 0xDC -#define myVK_Comma 0xBC -#define myVK_Period 0xBE -#define myVK_Slash 0xBF -#define myVK_SemiColon 0xBA -#define myVK_SingleQuote 0xDE -#define myVK_LeftBracket 0xDB -#define myVK_RightBracket 0xDD -#define myVK_Grave 0xC0 - -/* some new ones, need to check if in all header versions */ -#define myVK_PRIOR 0x21 -#define myVK_NEXT 0x22 -#define myVK_END 0x23 -#define myVK_HOME 0x24 -#define myVK_INSERT 0x2D -#define myVK_DELETE 0x2E -#define myVK_HELP 0x2F -#define myVK_SCROLL 0x91 -#define myVK_SNAPSHOT 0x2C -#define myVK_PAUSE 0x13 -#define myVK_CLEAR 0x0C - -#define myVK_OEM_8 0xDF -#define myVK_OEM_102 0xE2 - -extern bool WantCmdOptOnReconnect; - -void DoVKcode(int i, uint8_t flags, bool down); -void DisconnectKeyCodes3(void); -void ReconnectKeyCodes3(void); -bool InitWinKey2Mac(void); - -#if EnableGrabSpecialKeys -void GrabSpecialKeys(void); -void UnGrabSpecialKeys(void); -void CheckForLostKeyUps(void); -#endif - -/* --- time, date, location --- */ - -#define dbglog_TimeStuff (0 && dbglog_HAVE) - -extern uint32_t TrueEmulatedTime; - -#define InvTimeDivPow 16 -#define InvTimeDiv (1 << InvTimeDivPow) -#define InvTimeDivMask (InvTimeDiv - 1) -#define InvTimeStep 1089590 /* 1000 / 60.14742 * InvTimeDiv */ - -DWORD LastTime; -DWORD NextIntTime; - -void IncrNextTime(void); -void InitNextTime(void); -bool UpdateTrueEmulatedTime(void); -bool CheckDateTime(void); -bool Init60thCheck(void); -void Timer_Suspend(void); -void Timer_Resume(void); - -#endif // OSGLUWIN_H diff --git a/src/UI/_deprecated/WIN32/SOUND.c b/src/UI/_deprecated/WIN32/SOUND.c deleted file mode 100644 index 464174c..0000000 --- a/src/UI/_deprecated/WIN32/SOUND.c +++ /dev/null @@ -1,292 +0,0 @@ -/* --- sound --- */ - -#include "OSGLUWIN.h" - -#if SoundEnabled -#include "UI/WIN32/SOUND.h" -tpSoundSamp TheSoundBuffer = nullpr; -HWAVEOUT hWaveOut = NULL; - -void FillWithSilence(tpSoundSamp p, int n, trSoundSamp v) -{ - int i; - - for (i = n; --i >= 0; ) { - *p++ = v; - } -} - -void Sound_BeginPlaying(void) -{ -#if dbglog_SoundStuff - fprintf(stderr, "Sound_BeginPlaying\n"); -#endif -} - -void Sound_Start(void) -{ - if (hWaveOut == NULL) { - WAVEFORMATEX wfex; - MMRESULT mmr; - int i; - tpSoundSamp p; - WAVEHDR *pwh; - - wfex.wFormatTag = WAVE_FORMAT_PCM; - wfex.nChannels = 1; - wfex.nSamplesPerSec = SOUND_SAMPLERATE; - wfex.nAvgBytesPerSec = SOUND_SAMPLERATE; -#if 3 == kLn2SoundSampSz - wfex.nBlockAlign = 1; - wfex.wBitsPerSample = 8; -#elif 4 == kLn2SoundSampSz - wfex.nBlockAlign = 2; - wfex.wBitsPerSample = 16; -#else -#error "unsupported audio format" -#endif - wfex.cbSize = 0; - mmr = waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfex, 0, - 0 /* (DWORD) AppInstance */, CALLBACK_NULL); - if (mmr != MMSYSERR_NOERROR) { - /* - not recursive: - MacMsg("waveOutOpen failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } else { - p = TheSoundBuffer; - pwh = whdr; - for (i = 0; i < kSoundBuffers; ++i) { - pwh->lpData = (LPSTR)p; - pwh->dwBufferLength = kOneBuffSz; - pwh->dwBytesRecorded = 0; - pwh->dwUser = 0; - pwh->dwFlags = 0; - pwh->dwLoops = 0; - mmr = waveOutPrepareHeader(hWaveOut, pwh, - sizeof(WAVEHDR)); - if (mmr != MMSYSERR_NOERROR) { - /* - not recursive: - MacMsg("waveOutPrepareHeader failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } else { - pwh->dwFlags |= WHDR_DONE; - } - p += kOneBuffLen; - ++pwh; - } - - TheFillOffset = 0; - ThePlayOffset = 0; - TheWriteOffset = 0; - MinFilledSoundBuffs = kSoundBuffers; - wantplaying = false; - } - } -} - -void Sound_Stop(void) -{ - MMRESULT mmr; - int i; - - wantplaying = false; - if (hWaveOut != NULL) { - DWORD StartTime = GetTickCount(); - for (i = 0; i < kSoundBuffers; ++i) { - while (((whdr[i].dwFlags & WHDR_DONE) == 0) - && ((uint32_t)(GetTickCount() - StartTime) < 1000)) - { - Sleep(1); - } - - mmr = waveOutUnprepareHeader(hWaveOut, &whdr[i], - sizeof(WAVEHDR)); - if (mmr != MMSYSERR_NOERROR) { - /* - not recursive: - MacMsg("waveOutUnprepareHeader failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } - } - - mmr = waveOutClose(hWaveOut); - if (mmr != MMSYSERR_NOERROR) { - /* - MacMsg("waveOutClose failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } - hWaveOut = NULL; - } -} - -void SoundCheckVeryOften(void) -{ - if ((hWaveOut != NULL) && (wantplaying)) { -label_retry: - { - uint16_t FilledSoundBuffs; - uint16_t ToPlaySize = TheFillOffset - ThePlayOffset; - uint16_t CurPlayBuffer = - (ThePlayOffset >> kLnOneBuffLen) & kSoundBuffMask; - - if ((ToPlaySize > kOneBuffLen) - && ((whdr[CurPlayBuffer].dwFlags & WHDR_DONE) != 0)) - { - ThePlayOffset += kOneBuffLen; - goto label_retry; - } - FilledSoundBuffs = ToPlaySize >> kLnOneBuffLen; - - if (FilledSoundBuffs < MinFilledSoundBuffs) { - MinFilledSoundBuffs = FilledSoundBuffs; - } - - if (FilledSoundBuffs < 2) { - MMRESULT mmr; - uint16_t PrevPlayOffset = ThePlayOffset - kOneBuffLen; - uint16_t PrevPlayBuffer = - (PrevPlayOffset >> kLnOneBuffLen) & kSoundBuffMask; - uint16_t LastPlayedOffset = - ((TheFillOffset >> kLnOneBuffLen) << kLnOneBuffLen) - - 1; - - FillWithSilence( - TheSoundBuffer + (PrevPlayOffset & kAllBuffMask), - kOneBuffLen, - *(TheSoundBuffer - + (LastPlayedOffset & kAllBuffMask))); - mmr = waveOutWrite( - hWaveOut, &whdr[PrevPlayBuffer], sizeof(WAVEHDR)); - if (mmr != MMSYSERR_NOERROR) { - whdr[PrevPlayBuffer].dwFlags |= WHDR_DONE; - /* - not recursive: - MacMsg("waveOutWrite failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - } - ThePlayOffset = PrevPlayOffset; - goto label_retry; - } - } - } -} - -#if 4 == kLn2SoundSampSz -void ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -void Sound_FilledBlocks(void) -{ - while (0 != ((TheWriteOffset - TheFillOffset) >> kLnOneBuffLen)) { - uint16_t CurFillBuffer = - (TheFillOffset >> kLnOneBuffLen) & kSoundBuffMask; - bool IsOk = false; - - ConvertSoundBlockToNative((tpSoundSamp) - whdr[CurFillBuffer].lpData); - - if (hWaveOut != NULL) { - MMRESULT mmr = waveOutWrite(hWaveOut, - &whdr[CurFillBuffer], sizeof(WAVEHDR)); - if (mmr == MMSYSERR_NOERROR) { - IsOk = true; - } - } - - if (! IsOk) { - /* - not recursive: - MacMsg("waveOutWrite failed", - "Sorry, Mini vMac encountered errors" - " and cannot continue.", true); - */ - whdr[CurFillBuffer].dwFlags |= WHDR_DONE; - } - - TheFillOffset += kOneBuffLen; - } -} - -void Sound_WroteABlock(void) -{ - if (wantplaying) { - Sound_FilledBlocks(); - } else if (((TheWriteOffset - ThePlayOffset) >> kLnOneBuffLen) < 12) - { - /* just wait */ - } else { - Sound_FilledBlocks(); - wantplaying = true; - Sound_BeginPlaying(); - } -} - -void Sound_EndWrite(uint16_t actL) -{ - TheWriteOffset += actL; - - if (0 == (TheWriteOffset & kOneBuffMask)) { - /* just finished a block */ - - Sound_WroteABlock(); - } -} - -tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL) -{ - uint16_t ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset); - uint16_t WriteBuffContig = - kOneBuffLen - (TheWriteOffset & kOneBuffMask); - - if (WriteBuffContig < n) { - n = WriteBuffContig; - } - if (ToFillLen < n) { - /* overwrite previous buffer */ - TheWriteOffset -= kOneBuffLen; - } - - *actL = n; - return TheSoundBuffer + (TheWriteOffset & kAllBuffMask); -} - -void Sound_SecondNotify(void) -{ - if (hWaveOut != NULL) { - if (MinFilledSoundBuffs > DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too high"); -#endif - IncrNextTime(); - } else if (MinFilledSoundBuffs < DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too low"); -#endif - ++TrueEmulatedTime; - } - MinFilledSoundBuffs = kSoundBuffers; - } -} - -#endif diff --git a/src/UI/_deprecated/WIN32/SOUND.h b/src/UI/_deprecated/WIN32/SOUND.h deleted file mode 100644 index 501308b..0000000 --- a/src/UI/_deprecated/WIN32/SOUND.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef WIN32_SOUND_H -#define WIN32_SOUND_H - -#include - -#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */ -#define kSoundBuffers (1 << kLn2SoundBuffers) -#define kSoundBuffMask (kSoundBuffers - 1) - -#define DesiredMinFilledSoundBuffs 3 - /* - if too big then sound lags behind emulation. - if too small then sound will have pauses. - */ - -#define kLnOneBuffLen 9 -#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen) -#define kOneBuffLen (1UL << kLnOneBuffLen) -#define kAllBuffLen (1UL << kLnAllBuffLen) -#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3) -#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3) -#define kOneBuffSz (1UL << kLnOneBuffSz) -#define kAllBuffSz (1UL << kLnAllBuffSz) -#define kOneBuffMask (kOneBuffLen - 1) -#define kAllBuffMask (kAllBuffLen - 1) -#define dbhBufferSize (kAllBuffSz + kOneBuffSz) - -#define dbglog_SoundStuff (0 && dbglog_HAVE) -#define dbglog_SoundBuffStats (0 && dbglog_HAVE) - -extern tpSoundSamp TheSoundBuffer; -uint16_t ThePlayOffset; -uint16_t TheFillOffset; -bool wantplaying; -uint16_t MinFilledSoundBuffs; -uint16_t TheWriteOffset; - -extern HWAVEOUT hWaveOut; -WAVEHDR whdr[kSoundBuffers]; - -#define SOUND_SAMPLERATE /* 22050 */ 22255 - /* = round(7833600 * 2 / 704) */ - -void FillWithSilence(tpSoundSamp p, int n, trSoundSamp v); -void Sound_BeginPlaying(void); -void Sound_Start(void); -void Sound_Stop(void); -void SoundCheckVeryOften(void); -void ConvertSoundBlockToNative(tpSoundSamp p); -void Sound_FilledBlocks(void); -void Sound_WroteABlock(void); -void Sound_EndWrite(uint16_t actL); -tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL); -void Sound_SecondNotify(void); - -#endif diff --git a/src/UI/_deprecated/WIN32/TIMEDATE.c b/src/UI/_deprecated/WIN32/TIMEDATE.c deleted file mode 100644 index 5e28b6e..0000000 --- a/src/UI/_deprecated/WIN32/TIMEDATE.c +++ /dev/null @@ -1,167 +0,0 @@ -#include "OSGLUWIN.h" - -/* --- time, date, location --- */ - -uint32_t TrueEmulatedTime = 0; -LOCALVAR uint32_t TimeSecBase; -LOCALVAR DWORD TimeMilliBase; -LOCALVAR uint32_t NextFracTime; -bool HaveSetTimeResolution = false; - -// API wrapper defines - -/* - Timer resolution, as used by timeBeginPeriod(), in milliseconds. - Setting TimeResolution to 1 seems to drastically slow down - the clock in Virtual PC 7.0.2 for Mac. Using 3 is more polite - anyway, and should not cause much observable difference. - (note that 1/60 of a frame is 16.7 milliseconds) -*/ -#ifndef TimeResolution -#define TimeResolution 3 -#endif -/* - Windows NT: The default precision of the timeGetTime function can be five - milliseconds or more, depending on the machine. You can use the - timeBeginPeriod and timeEndPeriod functions to increase the precision of - timeGetTime. If you do so, the minimum difference between successive values - returned by timeGetTime can be as large as the minimum period value set using - timeBeginPeriod and timeEndPeriod. Use the QueryPerformanceCounter and - QueryPerformanceFrequency functions to measure short time intervals at a high - resolution. (MSDN for Visual Studio '97) - (TODO: use QueryPerformanceCounter instead? Always works on WinXP+) -*/ -#define GetTimeMillisec timeGetTime - -void IncrNextTime(void) -{ - NextFracTime += InvTimeStep; - NextIntTime += (NextFracTime >> InvTimeDivPow); - NextFracTime &= InvTimeDivMask; -} - -void InitNextTime(void) -{ - NextIntTime = LastTime; - NextFracTime = 0; - IncrNextTime(); -} - -bool UpdateTrueEmulatedTime(void) -{ - DWORD LatestTime; - int32_t TimeDiff; - - LatestTime = GetTimeMillisec(); - if (LatestTime != LastTime) { - LastTime = LatestTime; - TimeDiff = (LatestTime - NextIntTime); - /* this should work even when time wraps */ - if (TimeDiff >= 0) { - if (TimeDiff > 256) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - InitNextTime(); - -#if dbglog_TimeStuff - dbglog_writelnNum( - "emulation interrupted", - TrueEmulatedTime - ); -#endif - } else { - do { - ++TrueEmulatedTime; - IncrNextTime(); - TimeDiff = (LatestTime - NextIntTime); - } while (TimeDiff >= 0); - } - return true; - } else if (TimeDiff < -256) { - /* clock goofed if ever get here, reset */ -#if dbglog_TimeStuff - dbglog_writeln("clock set back"); -#endif - - InitNextTime(); - } - } - return false; -} - -// Check that emulated clock equals real clock -bool CheckDateTime(void) -{ - uint32_t NewMacDateInSecond; - - NewMacDateInSecond = - ((uint32_t)(LastTime - TimeMilliBase)) / 1000 + TimeSecBase; - if (CurMacDateInSeconds != NewMacDateInSecond) { - CurMacDateInSeconds = NewMacDateInSecond; - return true; - } else { - return false; - } -} - -// Initialize emulated RTC check -bool Init60thCheck(void) -{ - SYSTEMTIME s; - TIME_ZONE_INFORMATION r; - DWORD v; - DWORD t; - - GetLocalTime(&s); - t = GetTimeMillisec(); - - TimeSecBase = Date2MacSeconds( - s.wSecond, s.wMinute, s.wHour, - s.wDay, s.wMonth, s.wYear - ); - TimeMilliBase = t - s.wMilliseconds; - - if (AutoTimeZone) { - v = GetTimeZoneInformation(&r); - if ((v != 0xFFFFFFFF) && (v != TIME_ZONE_ID_UNKNOWN)) { - int32_t dlsBias = \ - (v != TIME_ZONE_ID_DAYLIGHT) ? r.StandardBias : r.DaylightBias; - CurMacDelta = \ - (((uint32_t)(- (r.Bias + dlsBias) * 60)) & 0x00FFFFFF) - | (((v != TIME_ZONE_ID_DAYLIGHT) ? 0 : 0x80) << 24 ); - } - } - - LastTime = GetTimeMillisec(); - InitNextTime(); - - OnTrueTime = TrueEmulatedTime; - - (void) CheckDateTime(); - - return true; -} - -void Timer_Suspend(void) -{ - // If using higher-precision timer, stop - if (HaveSetTimeResolution) { - (void) timeEndPeriod(TimeResolution); - HaveSetTimeResolution = false; - } -} - -void Timer_Resume(void) -{ - TIMECAPS tc; - - // Try to use higher-precision timer - if ( - timeGetDevCaps(&tc, sizeof(TIMECAPS)) == TIMERR_NOERROR && - (TimeResolution >= tc.wPeriodMin) && - (TimeResolution <= tc.wPeriodMax) && - timeBeginPeriod(TimeResolution) == TIMERR_NOERROR - ) { - HaveSetTimeResolution = true; - } -} diff --git a/src/UI/_deprecated/XPLAT/OSGLUGTK.c b/src/UI/_deprecated/XPLAT/OSGLUGTK.c deleted file mode 100644 index abeb2ef..0000000 --- a/src/UI/_deprecated/XPLAT/OSGLUGTK.c +++ /dev/null @@ -1,1757 +0,0 @@ -/* - OSGLUGTK.c - - Copyright (C) 2009 Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for GTK - - All operating system dependent code for the - GIMP Toolkit should go here. -*/ - -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" - -#include "UI/MYOSGLUE.h" - -#include "STRCONST.h" - -#include "UI/COMOSGLU.h" - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memcpy((char *)destPtr, (char *)srcPtr, byteCount); -} - -/* --- control mode and internationalization --- */ - -#define NeedCell2PlainAsciiMap 1 - -#include "LANG/INTLCHAR.h" - -#include "UI/CONTROLM.h" - -/* --- sending debugging info to file --- */ - -#if dbglog_HAVE - -#define dbglog_ToStdErr 0 - -#if ! dbglog_ToStdErr -LOCALVAR FILE *dbglog_File = NULL; -#endif - -LOCALFUNC bool dbglog_open0(void) -{ -#if dbglog_ToStdErr - return true; -#else - dbglog_File = fopen("dbglog.txt", "w"); - return (NULL != dbglog_File); -#endif -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ -#if dbglog_ToStdErr - (void) fwrite(s, 1, L, stderr); -#else - if (dbglog_File != NULL) { - (void) fwrite(s, 1, L, dbglog_File); - } -#endif -} - -LOCALPROC dbglog_close0(void) -{ -#if ! dbglog_ToStdErr - if (dbglog_File != NULL) { - fclose(dbglog_File); - dbglog_File = NULL; - } -#endif -} - -#endif - -/* --- debug settings and utilities --- */ - -#define DbgEvents (dbglog_HAVE && 1) - -#if ! dbglog_HAVE -#define WriteExtraErr(s) -#else -LOCALPROC WriteExtraErr(char *s) -{ - dbglog_writeCStr("*** error: "); - dbglog_writeCStr(s); - dbglog_writeReturn(); -} -#endif - -/* --- text translation --- */ - -LOCALPROC NativeStrFromCStr(char *r, char *s, bool AddEllipsis) -{ - uint8_t ps[ClStrMaxLength]; - int i; - int L; - - ClStrFromSubstCStr(&L, ps, s); - - for (i = 0; i < L; ++i) { - r[i] = Cell2PlainAsciiMap[ps[i]]; - } - - if (AddEllipsis) { - r[L] = '.'; - ++L; - r[L] = '.'; - ++L; - r[L] = '.'; - ++L; - } - - r[L] = 0; -} - -/* --- drives --- */ - -#define NotAfileRef NULL - -LOCALVAR FILE *Drives[NumDrives]; /* open disk image files */ - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - uint32_t NewSony_Count = Sony_Count; - - fseek(Drives[Drive_No], Sony_Start, SEEK_SET); - - if (IsWrite) { - fwrite(Buffer, 1, NewSony_Count, Drives[Drive_No]); - } else { - fread(Buffer, 1, NewSony_Count, Drives[Drive_No]); - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = NewSony_Count; - } - - return mnvm_noErr; /*& figure out what really to return &*/ -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - fseek(Drives[Drive_No], 0, SEEK_END); - *Sony_Count = ftell(Drives[Drive_No]); - return mnvm_noErr; /*& figure out what really to return &*/ -} - -LOCALFUNC MacErr_t vSonyEject0(tDrive Drive_No, bool deleteit) -{ - DiskEjectedNotify(Drive_No); - - fclose(Drives[Drive_No]); - Drives[Drive_No] = NotAfileRef; /* not really needed */ - - - return mnvm_noErr; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, false); -} - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -LOCALFUNC bool Sony_Insert0(FILE *refnum, bool locked, - char *drivepath) -{ - tDrive Drive_No; - - if (! FirstFreeDisk(&Drive_No)) { - fclose(refnum); - MacMsg(kStrTooManyImagesTitle, - kStrTooManyImagesMessage, false); - return false; - } else { - /* printf("Sony_Insert0 %d\n", (int)Drive_No); */ - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); - - return true; - } -} - -LOCALFUNC bool Sony_Insert1(char *drivepath, bool silentfail) -{ - bool locked = false; - /* printf("Sony_Insert1 %s\n", drivepath); */ - FILE *refnum = fopen(drivepath, "rb+"); - if (NULL == refnum) { - locked = true; - refnum = fopen(drivepath, "rb"); - } - if (NULL == refnum) { - if (! silentfail) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } else { - return Sony_Insert0(refnum, locked, drivepath); - } - return false; -} - -LOCALFUNC MacErr_t LoadMacRomFrom(char *path) -{ - MacErr_t err; - FILE *ROM_File; - int File_Size; - - ROM_File = fopen(path, "rb"); - if (NULL == ROM_File) { - err = mnvm_fnfErr; - } else { - File_Size = fread(ROM, 1, kROM_Size, ROM_File); - if (kROM_Size != File_Size) { - if (feof(ROM_File)) { - MacMsgOverride(kStrShortROMTitle, - kStrShortROMMessage); - err = mnvm_eofErr; - } else { - MacMsgOverride(kStrNoReadROMTitle, - kStrNoReadROMMessage); - err = mnvm_miscErr; - } - } else { - err = ROM_IsValid(); - } - fclose(ROM_File); - } - - return err; -} - -LOCALFUNC bool Sony_Insert1a(char *drivepath, bool silentfail) -{ - bool v; - - if (! ROM_loaded) { - v = (mnvm_noErr == LoadMacRomFrom(drivepath)); - } else { - v = Sony_Insert1(drivepath, silentfail); - } - - return v; -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - bool v; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - v = false; - } else { - char s[] = "disk?.dsk"; - - s[4] = '0' + i; - - v = Sony_Insert1(s, true); - } - - return v; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - - return true; -} - -/* --- ROM --- */ - -LOCALVAR char *rom_path = NULL; - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if ((NULL == rom_path) - || (mnvm_fnfErr == (err = LoadMacRomFrom(rom_path)))) - if (mnvm_fnfErr == (err = LoadMacRomFrom(RomFileName))) - { - } - - return true; -} - -/* --- video out --- */ - -static GtkWidget *drawing_area; - -LOCALVAR bool gBackgroundFlag = false; -LOCALVAR bool gTrueBackgroundFlag = false; -LOCALVAR bool CurSpeedStopped = true; - -LOCALPROC HaveChangedScreenBuff(int16_t top, int16_t left, - int16_t bottom, int16_t right) -{ - guchar graybuf[vMacScreenWidth * vMacScreenHeight]; - - { - int i; - int j; - int k; - uint8_t *p1 = GetCurDrawBuff() - + (uint32_t)vMacScreenWidth / 8 * top; - uint8_t *p2 = (uint8_t *)graybuf + (uint32_t)vMacScreenWidth * top; - uint32_t t0; - - UnusedParam(left); - UnusedParam(right); - for (i = bottom - top; --i >= 0; ) { - for (j = vMacScreenWidth / 8; --j >= 0; ) { - t0 = *p1++; - for (k = 8; --k >= 0; ) { - *p2++ = ((t0 >> k) & 0x01) - 1; - } - } - } - } - - gdk_draw_gray_image(drawing_area->window, - drawing_area->style->fg_gc[GTK_WIDGET_STATE(drawing_area)], - left /* x */, - top /* y */, - right - left /* width */, - bottom - top /* height */, - GDK_RGB_DITHER_NONE, - graybuf + left + (uint32_t)vMacScreenWidth * top, - vMacScreenWidth); -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ - DrawChangesAndClear(); -} - -/* --- mouse --- */ - -LOCALVAR bool HaveCursorHidden = false; -LOCALVAR bool WantCursorHidden = false; - -static GdkCursor *blank_cursor; -static GtkWidget *window = NULL; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - - if (window) { - gdk_window_set_cursor(window->window, NULL); - } - } -} - -/* cursor state */ - -LOCALPROC MousePositionNotify(int NewMousePosh, int NewMousePosv) -{ - bool ShouldHaveCursorHidden = true; - - { - if (NewMousePosh < 0) { - NewMousePosh = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosh >= vMacScreenWidth) { - NewMousePosh = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePosv < 0) { - NewMousePosv = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosv >= vMacScreenHeight) { - NewMousePosv = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePosh, NewMousePosv); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC CheckMouseState(void) -{ -#if 0 - gint x; - gint y; - gint x0; - gint y0; - - gdk_display_get_pointer(gdk_drawable_get_display(window), - NULL, &x, &y, NULL); - (void) gdk_window_get_origin(window, &x0, &y0); - MousePositionNotify(x - x0, y - y0); -#endif - gint x; - gint y; - - gtk_widget_get_pointer(drawing_area, &x, &y); - /* (void) gdk_window_get_pointer(window, &x, &y, NULL); */ - MousePositionNotify(x, y); -} - -/* --- keyboard input --- */ - -#define MaxNumKeycode 256 -#define KeyCodeMask (MaxNumKeycode - 1) - /* - assume keycodes >= 0 and < MaxNumKeycode, which - isn't promised by gtk documentation. - */ - - -LOCALVAR uint8_t KC2MKC[MaxNumKeycode]; - -LOCALPROC KC2MKCAssignOne(guint keyval, uint8_t key) -{ - GdkKeymapKey *keys; - gint n_keys; - int i; - - if (gdk_keymap_get_entries_for_keyval(NULL, - keyval, &keys, &n_keys)) - { - for (i = 0; i < n_keys; i++) { - KC2MKC[keys[i].keycode & KeyCodeMask] = key; - } - g_free(keys); - } -#if 0 - fprintf(stderr, "%d %d %d\n", (int)ks, key, (int)code); -#endif -} - -LOCALFUNC bool KC2MKCInit(void) -{ - int i; - - for (i = 0; i < 256; ++i) { - KC2MKC[i] = MKC_None; - } - -#ifdef GDK_KP_Insert - KC2MKCAssignOne(GDK_KP_Insert, MKC_KP0); -#endif -#ifdef GDK_KP_End - KC2MKCAssignOne(GDK_KP_End, MKC_KP1); -#endif -#ifdef GDK_KP_Down - KC2MKCAssignOne(GDK_KP_Down, MKC_KP2); -#endif -#ifdef GDK_KP_Next - KC2MKCAssignOne(GDK_KP_Next, MKC_KP3); -#endif -#ifdef GDK_KP_Left - KC2MKCAssignOne(GDK_KP_Left, MKC_KP4); -#endif -#ifdef GDK_KP_Begin - KC2MKCAssignOne(GDK_KP_Begin, MKC_KP5); -#endif -#ifdef GDK_KP_Right - KC2MKCAssignOne(GDK_KP_Right, MKC_KP6); -#endif -#ifdef GDK_KP_Home - KC2MKCAssignOne(GDK_KP_Home, MKC_KP7); -#endif -#ifdef GDK_KP_Up - KC2MKCAssignOne(GDK_KP_Up, MKC_KP8); -#endif -#ifdef GDK_KP_Prior - KC2MKCAssignOne(GDK_KP_Prior, MKC_KP9); -#endif -#ifdef GDK_KP_Delete - KC2MKCAssignOne(GDK_KP_Delete, MKC_Decimal); -#endif - - KC2MKCAssignOne(GDK_asciitilde, MKC_formac_Grave); - KC2MKCAssignOne(GDK_underscore, MKC_Minus); - KC2MKCAssignOne(GDK_plus, MKC_Equal); - KC2MKCAssignOne(GDK_braceleft, MKC_LeftBracket); - KC2MKCAssignOne(GDK_braceright, MKC_RightBracket); - KC2MKCAssignOne(GDK_bar, MKC_formac_BackSlash); - KC2MKCAssignOne(GDK_colon, MKC_SemiColon); - KC2MKCAssignOne(GDK_quotedbl, MKC_SingleQuote); - KC2MKCAssignOne(GDK_less, MKC_Comma); - KC2MKCAssignOne(GDK_greater, MKC_Period); - KC2MKCAssignOne(GDK_question, MKC_formac_Slash); - - KC2MKCAssignOne(GDK_a, MKC_A); - KC2MKCAssignOne(GDK_b, MKC_B); - KC2MKCAssignOne(GDK_c, MKC_C); - KC2MKCAssignOne(GDK_d, MKC_D); - KC2MKCAssignOne(GDK_e, MKC_E); - KC2MKCAssignOne(GDK_f, MKC_F); - KC2MKCAssignOne(GDK_g, MKC_G); - KC2MKCAssignOne(GDK_h, MKC_H); - KC2MKCAssignOne(GDK_i, MKC_I); - KC2MKCAssignOne(GDK_j, MKC_J); - KC2MKCAssignOne(GDK_k, MKC_K); - KC2MKCAssignOne(GDK_l, MKC_L); - KC2MKCAssignOne(GDK_m, MKC_M); - KC2MKCAssignOne(GDK_n, MKC_N); - KC2MKCAssignOne(GDK_o, MKC_O); - KC2MKCAssignOne(GDK_p, MKC_P); - KC2MKCAssignOne(GDK_q, MKC_Q); - KC2MKCAssignOne(GDK_r, MKC_R); - KC2MKCAssignOne(GDK_s, MKC_S); - KC2MKCAssignOne(GDK_t, MKC_T); - KC2MKCAssignOne(GDK_u, MKC_U); - KC2MKCAssignOne(GDK_v, MKC_V); - KC2MKCAssignOne(GDK_w, MKC_W); - KC2MKCAssignOne(GDK_x, MKC_X); - KC2MKCAssignOne(GDK_y, MKC_Y); - KC2MKCAssignOne(GDK_z, MKC_Z); - - /* - main mappings - */ - - KC2MKCAssignOne(GDK_F1, MKC_formac_F1); - KC2MKCAssignOne(GDK_F2, MKC_formac_F2); - KC2MKCAssignOne(GDK_F3, MKC_formac_F3); - KC2MKCAssignOne(GDK_F4, MKC_formac_F4); - KC2MKCAssignOne(GDK_F5, MKC_formac_F5); - KC2MKCAssignOne(GDK_F6, MKC_F6); - KC2MKCAssignOne(GDK_F7, MKC_F7); - KC2MKCAssignOne(GDK_F8, MKC_F8); - KC2MKCAssignOne(GDK_F9, MKC_F9); - KC2MKCAssignOne(GDK_F10, MKC_F10); - KC2MKCAssignOne(GDK_F11, MKC_F11); - KC2MKCAssignOne(GDK_F12, MKC_F12); - -#ifdef GDK_Delete - KC2MKCAssignOne(GDK_Delete, MKC_formac_ForwardDel); -#endif -#ifdef GDK_Insert - KC2MKCAssignOne(GDK_Insert, MKC_formac_Help); -#endif -#ifdef GDK_Help - KC2MKCAssignOne(GDK_Help, MKC_formac_Help); -#endif -#ifdef GDK_Home - KC2MKCAssignOne(GDK_Home, MKC_formac_Home); -#endif -#ifdef GDK_End - KC2MKCAssignOne(GDK_End, MKC_formac_End); -#endif - -#ifdef GDK_Page_Up - KC2MKCAssignOne(GDK_Page_Up, MKC_formac_PageUp); -#else -#ifdef GDK_Prior - KC2MKCAssignOne(GDK_Prior, MKC_formac_PageUp); -#endif -#endif - -#ifdef GDK_Page_Down - KC2MKCAssignOne(GDK_Page_Down, MKC_formac_PageDown); -#else -#ifdef GDK_Next - KC2MKCAssignOne(GDK_Next, MKC_formac_PageDown); -#endif -#endif - -#ifdef GDK_Print - KC2MKCAssignOne(GDK_Print, MKC_Print); -#endif -#ifdef GDK_Scroll_Lock - KC2MKCAssignOne(GDK_Scroll_Lock, MKC_ScrollLock); -#endif -#ifdef GDK_Pause - KC2MKCAssignOne(GDK_Pause, MKC_Pause); -#endif - - KC2MKCAssignOne(GDK_KP_Add, MKC_KPAdd); - KC2MKCAssignOne(GDK_KP_Subtract, MKC_KPSubtract); - KC2MKCAssignOne(GDK_KP_Multiply, MKC_KPMultiply); - KC2MKCAssignOne(GDK_KP_Divide, MKC_KPDevide); - KC2MKCAssignOne(GDK_KP_Enter, MKC_formac_Enter); - KC2MKCAssignOne(GDK_KP_Equal, MKC_KPEqual); - - KC2MKCAssignOne(GDK_KP_0, MKC_KP0); - KC2MKCAssignOne(GDK_KP_1, MKC_KP1); - KC2MKCAssignOne(GDK_KP_2, MKC_KP2); - KC2MKCAssignOne(GDK_KP_3, MKC_KP3); - KC2MKCAssignOne(GDK_KP_4, MKC_KP4); - KC2MKCAssignOne(GDK_KP_5, MKC_KP5); - KC2MKCAssignOne(GDK_KP_6, MKC_KP6); - KC2MKCAssignOne(GDK_KP_7, MKC_KP7); - KC2MKCAssignOne(GDK_KP_8, MKC_KP8); - KC2MKCAssignOne(GDK_KP_9, MKC_KP9); - KC2MKCAssignOne(GDK_KP_Decimal, MKC_Decimal); - - KC2MKCAssignOne(GDK_Left, MKC_Left); - KC2MKCAssignOne(GDK_Right, MKC_Right); - KC2MKCAssignOne(GDK_Up, MKC_Up); - KC2MKCAssignOne(GDK_Down, MKC_Down); - - KC2MKCAssignOne(GDK_grave, MKC_formac_Grave); - KC2MKCAssignOne(GDK_minus, MKC_Minus); - KC2MKCAssignOne(GDK_equal, MKC_Equal); - KC2MKCAssignOne(GDK_bracketleft, MKC_LeftBracket); - KC2MKCAssignOne(GDK_bracketright, MKC_RightBracket); - KC2MKCAssignOne(GDK_backslash, MKC_formac_BackSlash); - KC2MKCAssignOne(GDK_semicolon, MKC_SemiColon); - KC2MKCAssignOne(GDK_apostrophe, MKC_SingleQuote); - KC2MKCAssignOne(GDK_comma, MKC_Comma); - KC2MKCAssignOne(GDK_period, MKC_Period); - KC2MKCAssignOne(GDK_slash, MKC_formac_Slash); - - KC2MKCAssignOne(GDK_Escape, MKC_formac_Escape); - - KC2MKCAssignOne(GDK_Tab, MKC_Tab); - KC2MKCAssignOne(GDK_Return, MKC_Return); - KC2MKCAssignOne(GDK_space, MKC_Space); - KC2MKCAssignOne(GDK_BackSpace, MKC_BackSpace); - - KC2MKCAssignOne(GDK_Caps_Lock, MKC_formac_CapsLock); - KC2MKCAssignOne(GDK_Num_Lock, MKC_Clear); - - KC2MKCAssignOne(GDK_Meta_L, MKC_formac_Command); - - KC2MKCAssignOne(GDK_Meta_R, MKC_formac_RCommand); - - KC2MKCAssignOne(GDK_Mode_switch, MKC_formac_Option); - KC2MKCAssignOne(GDK_Menu, MKC_formac_Option); - KC2MKCAssignOne(GDK_Super_L, MKC_formac_Option); - KC2MKCAssignOne(GDK_Super_R, MKC_formac_ROption); - KC2MKCAssignOne(GDK_Hyper_L, MKC_formac_Option); - KC2MKCAssignOne(GDK_Hyper_R, MKC_formac_ROption); - - KC2MKCAssignOne(GDK_F13, MKC_formac_Option); - /* - seen being used in Mandrake Linux 9.2 - for windows key - */ - - KC2MKCAssignOne(GDK_Shift_L, MKC_formac_Shift); - KC2MKCAssignOne(GDK_Shift_R, MKC_formac_RShift); - - KC2MKCAssignOne(GDK_Alt_L, MKC_formac_Command); - - KC2MKCAssignOne(GDK_Alt_R, MKC_formac_RCommand); - - KC2MKCAssignOne(GDK_Control_L, MKC_formac_Control); - - KC2MKCAssignOne(GDK_Control_R, MKC_formac_RControl); - - KC2MKCAssignOne(GDK_1, MKC_1); - KC2MKCAssignOne(GDK_2, MKC_2); - KC2MKCAssignOne(GDK_3, MKC_3); - KC2MKCAssignOne(GDK_4, MKC_4); - KC2MKCAssignOne(GDK_5, MKC_5); - KC2MKCAssignOne(GDK_6, MKC_6); - KC2MKCAssignOne(GDK_7, MKC_7); - KC2MKCAssignOne(GDK_8, MKC_8); - KC2MKCAssignOne(GDK_9, MKC_9); - KC2MKCAssignOne(GDK_0, MKC_0); - - KC2MKCAssignOne(GDK_A, MKC_A); - KC2MKCAssignOne(GDK_B, MKC_B); - KC2MKCAssignOne(GDK_C, MKC_C); - KC2MKCAssignOne(GDK_D, MKC_D); - KC2MKCAssignOne(GDK_E, MKC_E); - KC2MKCAssignOne(GDK_F, MKC_F); - KC2MKCAssignOne(GDK_G, MKC_G); - KC2MKCAssignOne(GDK_H, MKC_H); - KC2MKCAssignOne(GDK_I, MKC_I); - KC2MKCAssignOne(GDK_J, MKC_J); - KC2MKCAssignOne(GDK_K, MKC_K); - KC2MKCAssignOne(GDK_L, MKC_L); - KC2MKCAssignOne(GDK_M, MKC_M); - KC2MKCAssignOne(GDK_N, MKC_N); - KC2MKCAssignOne(GDK_O, MKC_O); - KC2MKCAssignOne(GDK_P, MKC_P); - KC2MKCAssignOne(GDK_Q, MKC_Q); - KC2MKCAssignOne(GDK_R, MKC_R); - KC2MKCAssignOne(GDK_S, MKC_S); - KC2MKCAssignOne(GDK_T, MKC_T); - KC2MKCAssignOne(GDK_U, MKC_U); - KC2MKCAssignOne(GDK_V, MKC_V); - KC2MKCAssignOne(GDK_W, MKC_W); - KC2MKCAssignOne(GDK_X, MKC_X); - KC2MKCAssignOne(GDK_Y, MKC_Y); - KC2MKCAssignOne(GDK_Z, MKC_Z); - - InitKeyCodes(); - - return true; -} - -LOCALPROC CheckTheCapsLock(void) -{ - GdkModifierType mask; - - (void) gdk_window_get_pointer(window->window, NULL, NULL, &mask); - - Keyboard_UpdateKeyMap2(MKC_formac_CapsLock, - (mask & GDK_LOCK_MASK) != 0); -} - -LOCALPROC DoKeyCode(guint keycode, bool down) -{ - if (GDK_Caps_Lock == keycode) { - CheckTheCapsLock(); - } else { - uint8_t key = KC2MKC[keycode & KeyCodeMask]; - - if (MKC_None != key) { - Keyboard_UpdateKeyMap2(key, down); - } - } -} - -/* --- time, date, location --- */ - -LOCALVAR uint32_t TrueEmulatedTime = 0; - -#include "UTIL/DATE2SEC.h" - -#define TicksPerSecond 1000000 - -LOCALVAR bool HaveTimeDelta = false; -LOCALVAR uint32_t TimeDelta; - -LOCALVAR uint32_t NewMacDateInSeconds; - -LOCALVAR uint32_t LastTimeSec; -LOCALVAR uint32_t LastTimeUsec; - -LOCALPROC GetCurrentTicks(void) -{ - GTimeVal t; - - g_get_current_time(&t); - if (! HaveTimeDelta) { - time_t Current_Time; - struct tm *s; - -#if 0 - GDate *date; - date = g_date_new(); - g_date_set_time_val(date, &t); - g_date_free(date); -#endif - (void) time(&Current_Time); - s = localtime(&Current_Time); - TimeDelta = Date2MacSeconds(s->tm_sec, s->tm_min, s->tm_hour, - s->tm_mday, 1 + s->tm_mon, 1900 + s->tm_year) - t.tv_sec; -#if 0 && AutoTimeZone /* how portable is this ? */ - CurMacDelta = ((uint32_t)(s->tm_gmtoff) & 0x00FFFFFF) - | ((s->tm_isdst ? 0x80 : 0) << 24); -#endif - HaveTimeDelta = true; - } - - NewMacDateInSeconds = t.tv_sec + TimeDelta; - LastTimeSec = (uint32_t)t.tv_sec; - LastTimeUsec = (uint32_t)t.tv_usec; -} - -#define InvTimeStep 16626 /* TicksPerSecond / 60.14742 */ - -LOCALVAR uint32_t NextTimeSec; -LOCALVAR uint32_t NextTimeUsec; - -LOCALPROC IncrNextTime(void) -{ - NextTimeUsec += InvTimeStep; - if (NextTimeUsec >= TicksPerSecond) { - NextTimeUsec -= TicksPerSecond; - NextTimeSec += 1; - } -} - -LOCALPROC InitNextTime(void) -{ - NextTimeSec = LastTimeSec; - NextTimeUsec = LastTimeUsec; - IncrNextTime(); -} - -LOCALPROC StartUpTimeAdjust(void) -{ - GetCurrentTicks(); - InitNextTime(); -} - -LOCALFUNC int32_t GetTimeDiff(void) -{ - return ((int32_t)(LastTimeSec - NextTimeSec)) * TicksPerSecond - + ((int32_t)(LastTimeUsec - NextTimeUsec)); -} - -LOCALPROC UpdateTrueEmulatedTime(void) -{ - int32_t TimeDiff; - - GetCurrentTicks(); - - TimeDiff = GetTimeDiff(); - if (TimeDiff >= 0) { - if (TimeDiff > 4 * InvTimeStep) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - InitNextTime(); - } else { - do { - ++TrueEmulatedTime; - IncrNextTime(); - TimeDiff -= TicksPerSecond; - } while (TimeDiff >= 0); - } - } else if (TimeDiff < - 2 * InvTimeStep) { - /* clock goofed if ever get here, reset */ - InitNextTime(); - } -} - -LOCALFUNC bool CheckDateTime(void) -{ - if (CurMacDateInSeconds != NewMacDateInSeconds) { - CurMacDateInSeconds = NewMacDateInSeconds; - return true; - } else { - return false; - } -} - -LOCALFUNC bool InitLocationDat(void) -{ - GetCurrentTicks(); - CurMacDateInSeconds = NewMacDateInSeconds; - - return true; -} - -/* --- basic dialogs --- */ - -LOCALPROC CheckSavedMacMsg(void) -{ - if (nullpr != SavedBriefMsg) { - char briefMsg0[ClStrMaxLength + 1]; - char longMsg0[ClStrMaxLength + 1]; - - NativeStrFromCStr(briefMsg0, SavedBriefMsg, false); - NativeStrFromCStr(longMsg0, SavedLongMsg, false); - - fprintf(stderr, "%s\n", briefMsg0); - fprintf(stderr, "%s\n", longMsg0); - - SavedBriefMsg = nullpr; - } -} - -LOCALVAR bool CaughtMouse = false; - -/* --- main window creation and disposal --- */ - -LOCALVAR int argc; -LOCALVAR char **argv; - -/* Create a new backing pixmap of the appropriate size */ -static gboolean configure_event(GtkWidget *widget, - GdkEventConfigure *event) -{ - return TRUE; -} - -/* Redraw the screen from the backing pixmap */ -static gboolean expose_event(GtkWidget *widget, - GdkEventExpose *event, - gpointer user_data) -{ - int x0 = event->area.x; - int y0 = event->area.y; - int x1 = x0 + event->area.width; - int y1 = y0 + event->area.height; - -#if 0 && DbgEvents - fprintf(stderr, "- event - Expose\n"); -#endif - - if (x0 < 0) { - x0 = 0; - } - if (x1 > vMacScreenWidth) { - x1 = vMacScreenWidth; - } - if (y0 < 0) { - y0 = 0; - } - if (y1 > vMacScreenHeight) { - y1 = vMacScreenHeight; - } - if ((x0 < x1) && (y0 < y1)) { - HaveChangedScreenBuff(y0, x0, y1, x1); - } - - return FALSE; -} - -static gboolean button_press_event(GtkWidget *widget, - GdkEventButton *event, - gpointer user_data) -{ - MousePositionNotify(event->x, event->y); - MouseButtonSet(true); - - return TRUE; -} - -static gboolean button_release_event(GtkWidget *widget, - GdkEventButton *event, - gpointer user_data) -{ - MousePositionNotify(event->x, event->y); - MouseButtonSet(false); - - return TRUE; -} - -static gboolean motion_notify_event(GtkWidget *widget, - GdkEventMotion *event, - gpointer user_data) -{ - int x; - int y; - GdkModifierType state; - - if (event->is_hint) { - gdk_window_get_pointer(event->window, &x, &y, &state); - } else { - x = event->x; - y = event->y; - state = event->state; - } - - MousePositionNotify(x, y); - MouseButtonSet((state & GDK_BUTTON1_MASK) != 0); - - return TRUE; -} - -static gboolean enter_notify_event(GtkWidget *widget, - GdkEventCrossing *event, - gpointer user_data) -{ - CaughtMouse = true; - - MousePositionNotify(event->x, event->y); - MouseButtonSet((event->state & GDK_BUTTON1_MASK) != 0); - - return TRUE; -} - -static gboolean leave_notify_event(GtkWidget *widget, - GdkEventCrossing *event, - gpointer user_data) -{ - MousePositionNotify(event->x, event->y); - MouseButtonSet((event->state & GDK_BUTTON1_MASK) != 0); - - CaughtMouse = false; - - return TRUE; -} - -static gboolean delete_event(GtkWidget *widget, - GdkEventMotion *event) -{ - RequestMacOff = true; - - return TRUE; -} - -LOCALPROC ReconnectKeyCodes3(void) -{ - CheckTheCapsLock(); - -#if 0 - if (WantCmdOptOnReconnect) { - WantCmdOptOnReconnect = false; - - GetTheDownKeys(); - } -#endif -} - -LOCALPROC DisconnectKeyCodes3(void) -{ - DisconnectKeyCodes2(); - MouseButtonSet(false); -} - -LOCALVAR bool ADialogIsUp = false; - -LOCALPROC BeginDialog(void) -{ - DisconnectKeyCodes3(); - ADialogIsUp = true; - ForceShowCursor(); -} - -LOCALPROC EndDialog(void) -{ - ADialogIsUp = false; - ReconnectKeyCodes3(); -} - -/* --- SavedTasks --- */ - -LOCALPROC LeaveBackground(void) -{ - ReconnectKeyCodes3(); -#if 0 - DisableKeyRepeat(); -#endif -} - -LOCALPROC EnterBackground(void) -{ -#if 0 - RestoreKeyRepeat(); -#endif - DisconnectKeyCodes3(); - - ForceShowCursor(); -} - -LOCALPROC LeaveSpeedStopped(void) -{ - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -} - -static void InsertADisk0(void) -{ - char ts[ClStrMaxLength + 1]; - GtkWidget *dialog; - - NativeStrFromCStr(ts, kStrMenuItemOpen, false); - - BeginDialog(); - dialog = gtk_file_chooser_dialog_new(ts, - GTK_WINDOW(window), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - EndDialog(); - - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename; - - filename = - gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - (void) Sony_Insert1a(filename, false); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (gTrueBackgroundFlag != gBackgroundFlag) { - gBackgroundFlag = gTrueBackgroundFlag; - if (gTrueBackgroundFlag) { - EnterBackground(); - } else { - LeaveBackground(); - } - } - - if (CurSpeedStopped != (SpeedStopped || - (gBackgroundFlag && ! RunInBackground))) - { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - - if (HaveCursorHidden != (WantCursorHidden && CaughtMouse - && ! (gTrueBackgroundFlag || ADialogIsUp || CurSpeedStopped))) - { - HaveCursorHidden = ! HaveCursorHidden; - if (HaveCursorHidden) { - gdk_window_set_cursor(window->window, blank_cursor); - } else { - gdk_window_set_cursor(window->window, NULL); - } - } - - if (gTrueBackgroundFlag || ADialogIsUp) { - } else { - if (RequestInsertDisk) { - RequestInsertDisk = false; - InsertADisk0(); - } - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif -} - -/* --- command line parsing --- */ - -LOCALFUNC bool ScanCommandLine(void) -{ - int i; - - for (i = 1; i < argc; ++i) { - if ('-' == argv[i][0]) { -#if 0 - if ((0 == strcmp(argv[i], "--display")) || - (0 == strcmp(argv[i], "-display"))) - { - ++i; - if (i < argc) { - display_name = argv[i]; - } - } else -#endif - if ((0 == strcmp(argv[i], "--rom")) || - (0 == strcmp(argv[i], "-r"))) - { - ++i; - if (i < argc) { - rom_path = argv[i]; - } - } else -#if 0 - if (0 == strcmp(argv[i], "-l")) { - SpeedValue = 0; - } else -#endif - { - MacMsg(kStrBadArgTitle, kStrBadArgMessage, false); - } - } else { - (void) Sony_Insert1(argv[i], false); - } - } - return true; -} - -/* --- main program flow --- */ - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -LOCALPROC WaitForTheNextEvent(void) -{ - (void) gtk_main_iteration_do(TRUE); -} - -LOCALPROC CheckForSystemEvents(void) -{ - int i = 10; - - while (gtk_events_pending() && (--i >= 0)) { - (void) gtk_main_iteration_do(FALSE); - } -#if 0 - XFlush(x_display); -#endif -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ -label_retry: - CheckForSystemEvents(); - CheckForSavedTasks(); - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - WaitForTheNextEvent(); - goto label_retry; - } - - if (ExtraTimeNotOver()) { - int32_t TimeDiff = GetTimeDiff(); - if (TimeDiff < 0) { - g_usleep(- TimeDiff); - } - goto label_retry; - } - - if (CheckDateTime()) { - } - - if ((! gBackgroundFlag || ADialogIsUp) - && (! CaughtMouse) - ) - { - CheckMouseState(); - } - - OnTrueTime = TrueEmulatedTime; -} - -#include "PROGMAIN.h" - -static gboolean -MainEventLoop0(gpointer data) -{ - (void) data; - fprintf(stderr, "hello from MainEventLoop0\n"); - ProgramMain(); - if (ForceMacOff) { - goto Label_01; - } -#if 0 - while (! gtk_main_iteration_do(FALSE)) { - if (! gtk_events_pending()) { - fprintf(stderr, "sleep\n"); - g_usleep(1000000); - } - } -#endif -Label_01: - fprintf(stderr, "leaving MainEventLoop0\n"); - - gtk_main_quit(); - - return FALSE; -} - -static gboolean -focus_in_event(GtkWidget *widget, GdkEvent *event, - gpointer data) -{ - gTrueBackgroundFlag = false; - - CheckMouseState(); - - return FALSE; -} - -static gboolean -focus_out_event(GtkWidget *widget, GdkEvent *event, - gpointer data) -{ - gTrueBackgroundFlag = true; - return FALSE; -} - -static gboolean key_press_event(GtkWidget *widget, - GdkEventKey *event, - gpointer user_data) -{ -#if 0 - fprintf(stderr, "hello from key_press_event\n"); - fprintf(stderr, "keyval %d\n", event->keyval); - fprintf(stderr, "hardware_keycode %d\n", event->hardware_keycode); -#endif -#if 0 - { - GdkKeymapKey *keys; - gint n_keys; - int i; - - if (gdk_keymap_get_entries_for_keyval(NULL, - event->keyval, &keys, &n_keys)) - { - for (i = 0; i < n_keys; i++) { - fprintf(stderr, "keycode %d\n", keys[i].keycode); - } - g_free(keys); - } - } -#endif - DoKeyCode(event->hardware_keycode, true); - - return TRUE; -} - -static gboolean key_release_event(GtkWidget *widget, - GdkEventKey *event, - gpointer user_data) -{ -#if 0 - fprintf(stderr, "hello from key_release_event\n"); - fprintf(stderr, "keyval %d\n", event->keyval); - fprintf(stderr, "hardware_keycode %d\n", event->hardware_keycode); -#endif - DoKeyCode(event->hardware_keycode, false); - - return TRUE; -} - -static void drag_data_received(GtkWidget *widget, - GdkDragContext *drag_context, - gint x, - gint y, - GtkSelectionData *data, - guint info, - guint time, - gpointer user_data) -{ - char **uris; - char *file; - int i; - gboolean handled = FALSE; - - uris = g_strsplit((char *)data->data, "\r\n", -1); - if (uris != NULL) { - for (i = 0; uris[i] != NULL; i++) { - file = g_filename_from_uri(uris[i], NULL, NULL); - /* file = gnome_vfs_get_local_path_from_uri(uris[i]); */ - if (file != NULL) { - (void) Sony_Insert1a(file, false); - handled = TRUE; - g_free(file); - } - } - g_strfreev(uris); - } - gtk_drag_finish(drag_context, handled, FALSE, time); - if (handled) { - gtk_window_present_with_time(GTK_WINDOW(window), time); - } -} - -static void do_more_commands_item(GtkAction *action, gpointer user_data) -{ - DoMoreCommandsMsg(); -} - -static void do_about_item(GtkAction *action, gpointer user_data) -{ - DoAboutMsg(); -} - -static void do_quit_item(GtkAction *action, gpointer user_data) -{ - RequestMacOff = true; -} - -static void do_open_item(GtkAction *action, gpointer user_data) -{ - RequestInsertDisk = true; -} - -LOCALPROC AppendConvertMenuItem(GtkWidget *the_menu, - GCallback c_handler, gpointer gobject, char *s, bool AddEllipsis) -{ - char ts[ClStrMaxLength + 1]; - GtkWidget *the_item; - - NativeStrFromCStr(ts, s, AddEllipsis); - the_item = gtk_menu_item_new_with_label(ts); - g_signal_connect(G_OBJECT(the_item), "activate", - c_handler, gobject); - gtk_menu_shell_append(GTK_MENU_SHELL(the_menu), the_item); -} - -LOCALPROC AppendSubmenuConvertName(GtkWidget *menubar, - GtkWidget *the_menu, char *s) -{ - char ts[ClStrMaxLength + 1]; - GtkWidget *the_item; - - NativeStrFromCStr(ts, s, false); - the_item = gtk_menu_item_new_with_label(ts); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(the_item), the_menu); - gtk_menu_shell_append(GTK_MENU_SHELL(menubar), the_item); -} - -static GdkPixmap *blank_pixmap; -static GdkColor blank_color = { - 0, 0, 0, 0 -}; - -static gchar blank_cursor_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -}; - -static GtkTargetEntry dnd_target = -{ - "text/uri-list", 0, 0 -}; - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); -#if 0 - { - int i; - - for (i = 0; i < kNumMagStates; ++i) { - HavePositionWins[i] = false; - } - } -#endif -} - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)calloc(1, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALPROC UnallocMemory(void) -{ - if (nullpr != ReserveAllocBigBlock) { - free((char *)ReserveAllocBigBlock); - } -} - -LOCALFUNC bool InitOSGLU(void) -{ - if (AllocMemory()) -#if dbglog_HAVE - if (dbglog_open()) -#endif - if (ScanCommandLine()) - if (LoadMacRom()) - if (LoadInitialImages()) - if (InitLocationDat()) - /* if (ReCreateMainWindow()) */ - if (KC2MKCInit()) - if (WaitForRom()) - { - return true; - } - return false; -} - -LOCALPROC UnInitOSGLU(void) -{ - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - - UnInitDrives(); - - ForceShowCursor(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - UnallocMemory(); - - CheckSavedMacMsg(); -} - -int main(int argc, char *argv[]) -{ - GtkWidget *vbox; - -#if 0 - GtkWidget *button; -#endif - - GtkWidget *menubar; - GtkWidget *the_menu; - GtkWidget *the_item; - - gtk_init(&argc, &argv); - - window = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_widget_set_name(window, "Test Input"); - gtk_window_set_resizable(GTK_WINDOW(window), FALSE); - - vbox = gtk_vbox_new(FALSE, 0); - gtk_container_add(GTK_CONTAINER(window), vbox); - gtk_widget_show(vbox); - - g_signal_connect(G_OBJECT(window), "delete-event", - G_CALLBACK(delete_event), NULL); - g_signal_connect(G_OBJECT(window), "focus-out-event", - (GCallback)focus_out_event, - NULL); - g_signal_connect(G_OBJECT(window), "focus-in-event", - (GCallback)focus_in_event, NULL); - - g_signal_connect(G_OBJECT(window), "key-press-event", - G_CALLBACK(key_press_event), NULL); - g_signal_connect(G_OBJECT(window), "key-release-event", - G_CALLBACK(key_release_event), NULL); - - menubar = gtk_menu_bar_new(); - - the_menu = gtk_menu_new(); - - AppendConvertMenuItem(the_menu, - G_CALLBACK(do_open_item), NULL, kStrMenuItemOpen, true); - - the_item = gtk_separator_menu_item_new(); - gtk_menu_shell_append(GTK_MENU_SHELL(the_menu), the_item); - - AppendConvertMenuItem(the_menu, - G_CALLBACK(do_quit_item), NULL, kStrMenuItemQuit, false); - - AppendSubmenuConvertName(menubar, the_menu, kStrMenuFile); - - the_menu = gtk_menu_new(); - - AppendConvertMenuItem(the_menu, G_CALLBACK(do_more_commands_item), - NULL, kStrMenuItemMore, true); - - AppendSubmenuConvertName(menubar, the_menu, kStrMenuSpecial); - - the_menu = gtk_menu_new(); - - AppendConvertMenuItem(the_menu, - G_CALLBACK(do_about_item), NULL, kStrMenuItemAbout, true); - - AppendSubmenuConvertName(menubar, the_menu, kStrMenuHelp); - - gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 0); - - gtk_widget_show_all(menubar); - - - /* Create the drawing area */ - - drawing_area = gtk_drawing_area_new(); - gtk_widget_set_size_request(GTK_WIDGET(drawing_area), - vMacScreenWidth, vMacScreenHeight); - gtk_box_pack_start(GTK_BOX(vbox), drawing_area, TRUE, TRUE, 0); - - gtk_widget_show(drawing_area); - - /* Signals used to handle backing pixmap */ - - g_signal_connect(G_OBJECT(drawing_area), "expose-event", - G_CALLBACK(expose_event), NULL); - g_signal_connect(G_OBJECT(drawing_area), "configure-event", - G_CALLBACK(configure_event), NULL); - - /* Event signals */ - - g_signal_connect(G_OBJECT(drawing_area), "motion-notify-event", - G_CALLBACK(motion_notify_event), NULL); - g_signal_connect(G_OBJECT(drawing_area), "enter-notify-event", - G_CALLBACK(enter_notify_event), NULL); - g_signal_connect(G_OBJECT(drawing_area), "leave-notify-event", - G_CALLBACK(leave_notify_event), NULL); - - g_signal_connect(G_OBJECT(drawing_area), "button-press-event", - G_CALLBACK(button_press_event), NULL); - g_signal_connect(G_OBJECT(drawing_area), "button-release-event", - G_CALLBACK(button_release_event), NULL); - - gtk_widget_add_events(window, - GDK_KEY_PRESS_MASK - | GDK_KEY_RELEASE_MASK - ); - - gtk_widget_set_events(drawing_area, GDK_EXPOSURE_MASK - | GDK_LEAVE_NOTIFY_MASK - | GDK_BUTTON_PRESS_MASK - | GDK_BUTTON_RELEASE_MASK - | GDK_POINTER_MOTION_MASK - | GDK_ENTER_NOTIFY_MASK - | GDK_LEAVE_NOTIFY_MASK - | GDK_FOCUS_CHANGE_MASK - | GDK_KEY_PRESS_MASK - | GDK_KEY_RELEASE_MASK - /* | GDK_POINTER_MOTION_HINT_MASK */ - ); - -#if 0 - /* .. And a quit button */ - button = gtk_button_new_with_label("Quit"); - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0); - - g_signal_connect_swapped(G_OBJECT(button), "clicked", - G_CALLBACK(delete_event), NULL - /* - G_CALLBACK(gtk_widget_destroy), - G_OBJECT(window) - */ - ); - gtk_widget_show(button); -#endif - - gtk_drag_dest_set(drawing_area, GTK_DEST_DEFAULT_ALL, - &dnd_target, 1, - GDK_ACTION_COPY); - g_signal_connect(GTK_OBJECT(drawing_area), "drag-data-received", - G_CALLBACK(drag_data_received), NULL); - - gtk_widget_show(window); - - blank_pixmap = gdk_bitmap_create_from_data(NULL, - blank_cursor_bits, 16, 16); - blank_cursor = gdk_cursor_new_from_pixmap(blank_pixmap, - blank_pixmap, &blank_color, &blank_color, 8, 8); - gdk_pixmap_unref(blank_pixmap); - - gdk_window_set_cursor(window->window, blank_cursor); - - g_idle_add(MainEventLoop0, NULL); - - argc = argc; - argv = argv; - - ZapOSGLUVars(); - if (InitOSGLU()) { - gtk_main (); - } - UnInitOSGLU(); - - return 0; -} diff --git a/src/UI/_deprecated/XPLAT/OSGLUSDL.c b/src/UI/_deprecated/XPLAT/OSGLUSDL.c deleted file mode 100644 index 9c7bb04..0000000 --- a/src/UI/_deprecated/XPLAT/OSGLUSDL.c +++ /dev/null @@ -1,2317 +0,0 @@ -/* - OSGLUSDL.c - - Copyright (C) 2012 Paul C. Pratt - - You can redistribute this file and/or modify it under the terms - of version 2 of the GNU General Public License as published by - the Free Software Foundation. You should have received a copy - of the license along with this file; see the file COPYING. - - This file is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - license for more details. -*/ - -/* - Operating System GLUe for SDL library - - All operating system dependent code for the - SDL Library should go here. -*/ - -#include "CNFGRAPI.h" -#include "SYSDEPNS.h" -#include "UTIL/ENDIANAC.h" - -#include "UI/MYOSGLUE.h" - -#include "STRCONST.h" - -/* --- some simple utilities --- */ - -GLOBALOSGLUPROC MoveBytes(anyp srcPtr, anyp destPtr, int32_t byteCount) -{ - (void) memcpy((char *)destPtr, (char *)srcPtr, byteCount); -} - -/* --- control mode and internationalization --- */ - -#define NeedCell2PlainAsciiMap 1 - -#include "LANG/INTLCHAR.h" - -/* --- sending debugging info to file --- */ - -#if dbglog_HAVE - -#define dbglog_ToStdErr 0 - -#if ! dbglog_ToStdErr -LOCALVAR FILE *dbglog_File = NULL; -#endif - -LOCALFUNC bool dbglog_open0(void) -{ -#if dbglog_ToStdErr - return true; -#else - dbglog_File = fopen("dbglog.txt", "w"); - return (NULL != dbglog_File); -#endif -} - -LOCALPROC dbglog_write0(char *s, uimr L) -{ -#if dbglog_ToStdErr - (void) fwrite(s, 1, L, stderr); -#else - if (dbglog_File != NULL) { - (void) fwrite(s, 1, L, dbglog_File); - } -#endif -} - -LOCALPROC dbglog_close0(void) -{ -#if ! dbglog_ToStdErr - if (dbglog_File != NULL) { - fclose(dbglog_File); - dbglog_File = NULL; - } -#endif -} - -#endif - -/* --- information about the environment --- */ - -#define WantColorTransValid 0 - -#include "UI/COMOSGLU.h" - -#include "UTILS/PBUFSTDC.h" - -#include "UI/CONTROLM.h" - -/* --- text translation --- */ - -LOCALPROC NativeStrFromCStr(char *r, char *s) -{ - uint8_t ps[ClStrMaxLength]; - int i; - int L; - - ClStrFromSubstCStr(&L, ps, s); - - for (i = 0; i < L; ++i) { - r[i] = Cell2PlainAsciiMap[ps[i]]; - } - - r[L] = 0; -} - -/* --- drives --- */ - -#define NotAfileRef NULL - -LOCALVAR FILE *Drives[NumDrives]; /* open disk image files */ - -LOCALPROC InitDrives(void) -{ - /* - This isn't really needed, Drives[i] and DriveNames[i] - need not have valid values when not vSonyIsInserted[i]. - */ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - Drives[i] = NotAfileRef; - } -} - -GLOBALOSGLUFUNC MacErr_t vSonyTransfer(bool IsWrite, uint8_t * Buffer, - tDrive Drive_No, uint32_t Sony_Start, uint32_t Sony_Count, - uint32_t *Sony_ActCount) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - uint32_t NewSony_Count = 0; - - if (0 == fseek(refnum, Sony_Start, SEEK_SET)) { - if (IsWrite) { - NewSony_Count = fwrite(Buffer, 1, Sony_Count, refnum); - } else { - NewSony_Count = fread(Buffer, 1, Sony_Count, refnum); - } - - if (NewSony_Count == Sony_Count) { - err = mnvm_noErr; - } - } - - if (nullpr != Sony_ActCount) { - *Sony_ActCount = NewSony_Count; - } - - return err; /*& figure out what really to return &*/ -} - -GLOBALOSGLUFUNC MacErr_t vSonyGetSize(tDrive Drive_No, uint32_t *Sony_Count) -{ - MacErr_t err = mnvm_miscErr; - FILE *refnum = Drives[Drive_No]; - long v; - - if (0 == fseek(refnum, 0, SEEK_END)) { - v = ftell(refnum); - if (v >= 0) { - *Sony_Count = v; - err = mnvm_noErr; - } - } - - return err; /*& figure out what really to return &*/ -} - -LOCALFUNC MacErr_t vSonyEject0(tDrive Drive_No, bool deleteit) -{ - FILE *refnum = Drives[Drive_No]; - - DiskEjectedNotify(Drive_No); - - fclose(refnum); - Drives[Drive_No] = NotAfileRef; /* not really needed */ - - return mnvm_noErr; -} - -GLOBALOSGLUFUNC MacErr_t vSonyEject(tDrive Drive_No) -{ - return vSonyEject0(Drive_No, false); -} - -LOCALPROC UnInitDrives(void) -{ - tDrive i; - - for (i = 0; i < NumDrives; ++i) { - if (vSonyIsInserted(i)) { - (void) vSonyEject(i); - } - } -} - -LOCALFUNC bool Sony_Insert0(FILE *refnum, bool locked, - char *drivepath) -{ - tDrive Drive_No; - bool IsOk = false; - - if (! FirstFreeDisk(&Drive_No)) { - MacMsg(kStrTooManyImagesTitle, kStrTooManyImagesMessage, - false); - } else { - /* printf("Sony_Insert0 %d\n", (int)Drive_No); */ - - { - Drives[Drive_No] = refnum; - DiskInsertNotify(Drive_No, locked); - - IsOk = true; - } - } - - if (! IsOk) { - fclose(refnum); - } - - return IsOk; -} - -LOCALFUNC bool Sony_Insert1(char *drivepath, bool silentfail) -{ - bool locked = false; - /* printf("Sony_Insert1 %s\n", drivepath); */ - FILE *refnum = fopen(drivepath, "rb+"); - if (NULL == refnum) { - locked = true; - refnum = fopen(drivepath, "rb"); - } - if (NULL == refnum) { - if (! silentfail) { - MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, false); - } - } else { - return Sony_Insert0(refnum, locked, drivepath); - } - return false; -} - -LOCALFUNC MacErr_t LoadMacRomFrom(char *path) -{ - MacErr_t err; - FILE *ROM_File; - int File_Size; - - ROM_File = fopen(path, "rb"); - if (NULL == ROM_File) { - err = mnvm_fnfErr; - } else { - File_Size = fread(ROM, 1, kROM_Size, ROM_File); - if (File_Size != kROM_Size) { - if (feof(ROM_File)) { - MacMsgOverride(kStrShortROMTitle, - kStrShortROMMessage); - err = mnvm_eofErr; - } else { - MacMsgOverride(kStrNoReadROMTitle, - kStrNoReadROMMessage); - err = mnvm_miscErr; - } - } else { - err = ROM_IsValid(); - } - fclose(ROM_File); - } - - return err; -} - -#if 0 /* no drag and drop to make use of this */ -LOCALFUNC bool Sony_Insert1a(char *drivepath, bool silentfail) -{ - bool v; - - if (! ROM_loaded) { - v = (mnvm_noErr == LoadMacRomFrom(drivepath)); - } else { - v = Sony_Insert1(drivepath, silentfail); - } - - return v; -} -#endif - -LOCALFUNC bool Sony_Insert2(char *s) -{ - return Sony_Insert1(s, true); -} - -LOCALFUNC bool Sony_InsertIth(int i) -{ - bool v; - - if ((i > 9) || ! FirstFreeDisk(nullpr)) { - v = false; - } else { - char s[] = "disk?.dsk"; - - s[4] = '0' + i; - - v = Sony_Insert2(s); - } - - return v; -} - -LOCALFUNC bool LoadInitialImages(void) -{ - if (! AnyDiskInserted()) { - int i; - - for (i = 1; Sony_InsertIth(i); ++i) { - /* stop on first error (including file not found) */ - } - } - - return true; -} - -/* --- ROM --- */ - -LOCALVAR char *rom_path = NULL; - -LOCALFUNC bool LoadMacRom(void) -{ - MacErr_t err; - - if ((NULL == rom_path) - || (mnvm_fnfErr == (err = LoadMacRomFrom(rom_path)))) - if (mnvm_fnfErr == (err = LoadMacRomFrom(RomFileName))) - { - } - - return true; /* keep launching Mini vMac, regardless */ -} - -/* --- video out --- */ - -#if 1 -LOCALVAR bool UseFullScreen = (WantInitFullScreen != 0); -#endif - -#if 1 -LOCALVAR bool UseMagnify = (WantInitMagnify != 0); -#endif - -LOCALVAR bool gBackgroundFlag = false; -LOCALVAR bool gTrueBackgroundFlag = false; -LOCALVAR bool CurSpeedStopped = true; - -#if 1 -#define MaxScale WindowScale -#else -#define MaxScale 1 -#endif - - -LOCALVAR SDL_Surface *surface = nullpr; - -LOCALVAR uint8_t * ScalingBuff = nullpr; - -LOCALVAR uint8_t * CLUT_final; - -#define CLUT_finalsz (256 * 8 * 4 * MaxScale) - /* - 256 possible values of one byte - 8 pixels per byte maximum (when black and white) - 4 bytes per destination pixel maximum - multiplied by WindowScale if 1 - */ - -#define ScrnMapr_DoMap UpdateBWDepth3Copy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 3 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateBWDepth4Copy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 4 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateBWDepth5Copy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateBWDepth3ScaledCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 3 -#define ScrnMapr_Map CLUT_final -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateBWDepth4ScaledCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 4 -#define ScrnMapr_Map CLUT_final -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateBWDepth5ScaledCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth 0 -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map CLUT_final -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - - -#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - -#define ScrnMapr_DoMap UpdateColorDepth3Copy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 3 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateColorDepth4Copy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 4 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateColorDepth5Copy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map CLUT_final - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateColorDepth3ScaledCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 3 -#define ScrnMapr_Map CLUT_final -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateColorDepth4ScaledCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 4 -#define ScrnMapr_Map CLUT_final -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#define ScrnMapr_DoMap UpdateColorDepth5ScaledCopy -#define ScrnMapr_Src GetCurDrawBuff() -#define ScrnMapr_Dst ScalingBuff -#define ScrnMapr_SrcDepth vMacScreenDepth -#define ScrnMapr_DstDepth 5 -#define ScrnMapr_Map CLUT_final -#define ScrnMapr_Scale WindowScale - -#include "HW/SCREEN/SCRNMAPR.h" - -#endif - - -LOCALPROC HaveChangedScreenBuff(uint16_t top, uint16_t left, - uint16_t bottom, uint16_t right) -{ - int i; - int j; - uint8_t *p; - Uint32 pixel; -#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - Uint32 CLUT_pixel[CLUT_size]; -#endif - Uint32 BWLUT_pixel[2]; - uint32_t top2 = top; - uint32_t left2 = left; - uint32_t bottom2 = bottom; - uint32_t right2 = right; - -#if 1 - if (UseMagnify) { - top2 *= WindowScale; - left2 *= WindowScale; - bottom2 *= WindowScale; - right2 *= WindowScale; - } -#endif - - if (SDL_MUSTLOCK(surface)) { - if (SDL_LockSurface(surface) < 0) { - return; - } - } - - { - - int bpp = surface->format->BytesPerPixel; - uint32_t ExpectedPitch = vMacScreenWidth * bpp; - -#if 1 - if (UseMagnify) { - ExpectedPitch *= WindowScale; - } -#endif - -#if 0 != vMacScreenDepth - if (UseColorMode) { -#if vMacScreenDepth < 4 - for (i = 0; i < CLUT_size; ++i) { - CLUT_pixel[i] = SDL_MapRGB(surface->format, - CLUT_reds[i] >> 8, - CLUT_greens[i] >> 8, - CLUT_blues[i] >> 8); - } -#endif - } else -#endif - { - BWLUT_pixel[1] = SDL_MapRGB(surface->format, 0, 0, 0); - /* black */ - BWLUT_pixel[0] = SDL_MapRGB(surface->format, 255, 255, 255); - /* white */ - } - - if ((0 == ((bpp - 1) & bpp)) /* a power of 2 */ - && (surface->pitch == ExpectedPitch) -#if (vMacScreenDepth > 3) - && ! UseColorMode -#endif - ) - { - int k; - Uint32 v; -#if 1 - int a; -#endif - int PixPerByte = -#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - UseColorMode ? (1 << (3 - vMacScreenDepth)) : -#endif - 8; - Uint8 *p4 = (Uint8 *)CLUT_final; - - for (i = 0; i < 256; ++i) { - for (k = PixPerByte; --k >= 0; ) { - -#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - if (UseColorMode) { - v = CLUT_pixel[ -#if 3 == vMacScreenDepth - i -#else - (i >> (k << vMacScreenDepth)) - & (CLUT_size - 1) -#endif - ]; - } else -#endif - { - v = BWLUT_pixel[(i >> k) & 1]; - } - -#if 1 - for (a = UseMagnify ? WindowScale : 1; --a >= 0; ) -#endif - { - switch (bpp) { - case 1: /* Assuming 8-bpp */ - *p4++ = v; - break; - case 2: /* Probably 15-bpp or 16-bpp */ - *(Uint16 *)p4 = v; - p4 += 2; - break; - case 4: /* Probably 32-bpp */ - *(Uint32 *)p4 = v; - p4 += 4; - break; - } - } - } - } - - ScalingBuff = (uint8_t *)surface->pixels; - -#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4) - if (UseColorMode) { -#if 1 - if (UseMagnify) { - switch (bpp) { - case 1: - UpdateColorDepth3ScaledCopy( - top, left, bottom, right); - break; - case 2: - UpdateColorDepth4ScaledCopy( - top, left, bottom, right); - break; - case 4: - UpdateColorDepth5ScaledCopy( - top, left, bottom, right); - break; - } - } else -#endif - { - switch (bpp) { - case 1: - UpdateColorDepth3Copy(top, left, bottom, right); - break; - case 2: - UpdateColorDepth4Copy(top, left, bottom, right); - break; - case 4: - UpdateColorDepth5Copy(top, left, bottom, right); - break; - } - } - } else -#endif - { -#if 1 - if (UseMagnify) { - switch (bpp) { - case 1: - UpdateBWDepth3ScaledCopy( - top, left, bottom, right); - break; - case 2: - UpdateBWDepth4ScaledCopy( - top, left, bottom, right); - break; - case 4: - UpdateBWDepth5ScaledCopy( - top, left, bottom, right); - break; - } - } else -#endif - { - switch (bpp) { - case 1: - UpdateBWDepth3Copy(top, left, bottom, right); - break; - case 2: - UpdateBWDepth4Copy(top, left, bottom, right); - break; - case 4: - UpdateBWDepth5Copy(top, left, bottom, right); - break; - } - } - } - - } else { - uint8_t *the_data = (uint8_t *)GetCurDrawBuff(); - - /* adapted from putpixel in SDL documentation */ - - for (i = top2; i < bottom2; ++i) { - for (j = left2; j < right2; ++j) { - int i0 = i; - int j0 = j; - Uint8 *bufp = (Uint8 *)surface->pixels - + i * surface->pitch + j * bpp; - -#if 1 - if (UseMagnify) { - i0 /= WindowScale; - j0 /= WindowScale; - } -#endif - -#if 0 != vMacScreenDepth - if (UseColorMode) { -#if vMacScreenDepth < 4 - p = the_data + ((i0 * vMacScreenWidth + j0) - >> (3 - vMacScreenDepth)); - { - uint8_t k = (*p >> (((~ j0) - & ((1 << (3 - vMacScreenDepth)) - 1)) - << vMacScreenDepth)) - & (CLUT_size - 1); - pixel = CLUT_pixel[k]; - } -#elif 4 == vMacScreenDepth - p = the_data + ((i0 * vMacScreenWidth + j0) << 1); - { - uint16_t t0 = do_get_mem_word(p); - pixel = SDL_MapRGB(surface->format, - ((t0 & 0x7C00) >> 7) - | ((t0 & 0x7000) >> 12), - ((t0 & 0x03E0) >> 2) - | ((t0 & 0x0380) >> 7), - ((t0 & 0x001F) << 3) - | ((t0 & 0x001C) >> 2)); - } -#elif 5 == vMacScreenDepth - p = the_data + ((i0 * vMacScreenWidth + j0) << 2); - pixel = SDL_MapRGB(surface->format, - p[1], - p[2], - p[3]); -#endif - } else -#endif - { - p = the_data + ((i0 * vMacScreenWidth + j0) / 8); - pixel = BWLUT_pixel[(*p >> ((~ j0) & 0x7)) & 1]; - } - - switch (bpp) { - case 1: /* Assuming 8-bpp */ - *bufp = pixel; - break; - case 2: /* Probably 15-bpp or 16-bpp */ - *(Uint16 *)bufp = pixel; - break; - case 3: - /* Slow 24-bpp mode, usually not used */ - if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { - bufp[0] = (pixel >> 16) & 0xff; - bufp[1] = (pixel >> 8) & 0xff; - bufp[2] = pixel & 0xff; - } else { - bufp[0] = pixel & 0xff; - bufp[1] = (pixel >> 8) & 0xff; - bufp[2] = (pixel >> 16) & 0xff; - } - break; - case 4: /* Probably 32-bpp */ - *(Uint32 *)bufp = pixel; - break; - } - } - } - } - - } - - if (SDL_MUSTLOCK(surface)) { - SDL_UnlockSurface(surface); - } - - SDL_UpdateRect(surface, left2, top2, - right2 - left2, bottom2 - top2); -} - -LOCALPROC DrawChangesAndClear(void) -{ - if (ScreenChangedBottom > ScreenChangedTop) { - HaveChangedScreenBuff(ScreenChangedTop, ScreenChangedLeft, - ScreenChangedBottom, ScreenChangedRight); - ScreenClearChanges(); - } -} - -GLOBALOSGLUPROC DoneWithDrawingForTick(void) -{ -#if EnableFSMouseMotion - if (HaveMouseMotion) { - AutoScrollScreen(); - } -#endif - DrawChangesAndClear(); -} - -/* --- mouse --- */ - -/* cursor hiding */ - -LOCALVAR bool HaveCursorHidden = false; -LOCALVAR bool WantCursorHidden = false; - -LOCALPROC ForceShowCursor(void) -{ - if (HaveCursorHidden) { - HaveCursorHidden = false; - (void) SDL_ShowCursor(SDL_ENABLE); - } -} - -/* cursor moving */ - -LOCALFUNC bool MoveMouse(int16_t h, int16_t v) -{ -#if 1 - if (UseMagnify) { - h *= WindowScale; - v *= WindowScale; - } -#endif - - SDL_WarpMouse(h, v); - - return true; -} - -/* cursor state */ - -LOCALPROC MousePositionNotify(int NewMousePosh, int NewMousePosv) -{ - bool ShouldHaveCursorHidden = true; - -#if 1 - if (UseMagnify) { - NewMousePosh /= WindowScale; - NewMousePosv /= WindowScale; - } -#endif - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MousePositionSetDelta(NewMousePosh - SavedMouseH, - NewMousePosv - SavedMouseV); - SavedMouseH = NewMousePosh; - SavedMouseV = NewMousePosv; - } else -#endif - { - if (NewMousePosh < 0) { - NewMousePosh = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosh >= vMacScreenWidth) { - NewMousePosh = vMacScreenWidth - 1; - ShouldHaveCursorHidden = false; - } - if (NewMousePosv < 0) { - NewMousePosv = 0; - ShouldHaveCursorHidden = false; - } else if (NewMousePosv >= vMacScreenHeight) { - NewMousePosv = vMacScreenHeight - 1; - ShouldHaveCursorHidden = false; - } - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - ShouldHaveCursorHidden = true; - } -#endif - - /* if (ShouldHaveCursorHidden || CurMouseButton) */ - /* - for a game like arkanoid, would like mouse to still - move even when outside window in one direction - */ - MousePositionSet(NewMousePosh, NewMousePosv); - } - - WantCursorHidden = ShouldHaveCursorHidden; -} - -LOCALPROC CheckMouseState(void) -{ - /* - this doesn't work as desired, doesn't get mouse movements - when outside of our window. - */ - int x; - int y; - - (void) SDL_GetMouseState(&x, &y); - MousePositionNotify(x, y); -} - -/* --- keyboard input --- */ - -LOCALFUNC uint8_t SDLKey2MacKeyCode(SDLKey i) -{ - uint8_t v = MKC_None; - - switch (i) { - case SDLK_BACKSPACE: v = MKC_BackSpace; break; - case SDLK_TAB: v = MKC_Tab; break; - case SDLK_CLEAR: v = MKC_Clear; break; - case SDLK_RETURN: v = MKC_Return; break; - case SDLK_PAUSE: v = MKC_Pause; break; - case SDLK_ESCAPE: v = MKC_formac_Escape; break; - case SDLK_SPACE: v = MKC_Space; break; - case SDLK_EXCLAIM: /* ? */ break; - case SDLK_QUOTEDBL: /* ? */ break; - case SDLK_HASH: /* ? */ break; - case SDLK_DOLLAR: /* ? */ break; - case SDLK_AMPERSAND: /* ? */ break; - case SDLK_QUOTE: v = MKC_SingleQuote; break; - case SDLK_LEFTPAREN: /* ? */ break; - case SDLK_RIGHTPAREN: /* ? */ break; - case SDLK_ASTERISK: /* ? */ break; - case SDLK_PLUS: /* ? */ break; - case SDLK_COMMA: v = MKC_Comma; break; - case SDLK_MINUS: v = MKC_Minus; break; - case SDLK_PERIOD: v = MKC_Period; break; - case SDLK_SLASH: v = MKC_formac_Slash; break; - case SDLK_0: v = MKC_0; break; - case SDLK_1: v = MKC_1; break; - case SDLK_2: v = MKC_2; break; - case SDLK_3: v = MKC_3; break; - case SDLK_4: v = MKC_4; break; - case SDLK_5: v = MKC_5; break; - case SDLK_6: v = MKC_6; break; - case SDLK_7: v = MKC_7; break; - case SDLK_8: v = MKC_8; break; - case SDLK_9: v = MKC_9; break; - case SDLK_COLON: /* ? */ break; - case SDLK_SEMICOLON: v = MKC_SemiColon; break; - case SDLK_LESS: /* ? */ break; - case SDLK_EQUALS: v = MKC_Equal; break; - case SDLK_GREATER: /* ? */ break; - case SDLK_QUESTION: /* ? */ break; - case SDLK_AT: /* ? */ break; - - case SDLK_LEFTBRACKET: v = MKC_LeftBracket; break; - case SDLK_BACKSLASH: v = MKC_formac_BackSlash; break; - case SDLK_RIGHTBRACKET: v = MKC_RightBracket; break; - case SDLK_CARET: /* ? */ break; - case SDLK_UNDERSCORE: /* ? */ break; - case SDLK_BACKQUOTE: v = MKC_formac_Grave; break; - - case SDLK_a: v = MKC_A; break; - case SDLK_b: v = MKC_B; break; - case SDLK_c: v = MKC_C; break; - case SDLK_d: v = MKC_D; break; - case SDLK_e: v = MKC_E; break; - case SDLK_f: v = MKC_F; break; - case SDLK_g: v = MKC_G; break; - case SDLK_h: v = MKC_H; break; - case SDLK_i: v = MKC_I; break; - case SDLK_j: v = MKC_J; break; - case SDLK_k: v = MKC_K; break; - case SDLK_l: v = MKC_L; break; - case SDLK_m: v = MKC_M; break; - case SDLK_n: v = MKC_N; break; - case SDLK_o: v = MKC_O; break; - case SDLK_p: v = MKC_P; break; - case SDLK_q: v = MKC_Q; break; - case SDLK_r: v = MKC_R; break; - case SDLK_s: v = MKC_S; break; - case SDLK_t: v = MKC_T; break; - case SDLK_u: v = MKC_U; break; - case SDLK_v: v = MKC_V; break; - case SDLK_w: v = MKC_W; break; - case SDLK_x: v = MKC_X; break; - case SDLK_y: v = MKC_Y; break; - case SDLK_z: v = MKC_Z; break; - - case SDLK_KP0: v = MKC_KP0; break; - case SDLK_KP1: v = MKC_KP1; break; - case SDLK_KP2: v = MKC_KP2; break; - case SDLK_KP3: v = MKC_KP3; break; - case SDLK_KP4: v = MKC_KP4; break; - case SDLK_KP5: v = MKC_KP5; break; - case SDLK_KP6: v = MKC_KP6; break; - case SDLK_KP7: v = MKC_KP7; break; - case SDLK_KP8: v = MKC_KP8; break; - case SDLK_KP9: v = MKC_KP9; break; - - case SDLK_KP_PERIOD: v = MKC_Decimal; break; - case SDLK_KP_DIVIDE: v = MKC_KPDevide; break; - case SDLK_KP_MULTIPLY: v = MKC_KPMultiply; break; - case SDLK_KP_MINUS: v = MKC_KPSubtract; break; - case SDLK_KP_PLUS: v = MKC_KPAdd; break; - case SDLK_KP_ENTER: v = MKC_formac_Enter; break; - case SDLK_KP_EQUALS: v = MKC_KPEqual; break; - - case SDLK_UP: v = MKC_Up; break; - case SDLK_DOWN: v = MKC_Down; break; - case SDLK_RIGHT: v = MKC_Right; break; - case SDLK_LEFT: v = MKC_Left; break; - case SDLK_INSERT: v = MKC_formac_Help; break; - case SDLK_HOME: v = MKC_formac_Home; break; - case SDLK_END: v = MKC_formac_End; break; - case SDLK_PAGEUP: v = MKC_formac_PageUp; break; - case SDLK_PAGEDOWN: v = MKC_formac_PageDown; break; - - case SDLK_F1: v = MKC_formac_F1; break; - case SDLK_F2: v = MKC_formac_F2; break; - case SDLK_F3: v = MKC_formac_F3; break; - case SDLK_F4: v = MKC_formac_F4; break; - case SDLK_F5: v = MKC_formac_F5; break; - case SDLK_F6: v = MKC_F6; break; - case SDLK_F7: v = MKC_F7; break; - case SDLK_F8: v = MKC_F8; break; - case SDLK_F9: v = MKC_F9; break; - case SDLK_F10: v = MKC_F10; break; - case SDLK_F11: v = MKC_F11; break; - case SDLK_F12: v = MKC_F12; break; - - case SDLK_F13: /* ? */ break; - case SDLK_F14: /* ? */ break; - case SDLK_F15: /* ? */ break; - - case SDLK_NUMLOCK: v = MKC_formac_ForwardDel; break; - case SDLK_CAPSLOCK: v = MKC_formac_CapsLock; break; - case SDLK_SCROLLOCK: v = MKC_ScrollLock; break; - case SDLK_RSHIFT: v = MKC_formac_RShift; break; - case SDLK_LSHIFT: v = MKC_formac_Shift; break; - case SDLK_RCTRL: v = MKC_formac_RControl; break; - case SDLK_LCTRL: v = MKC_formac_Control; break; - case SDLK_RALT: v = MKC_formac_RCommand; break; - case SDLK_LALT: v = MKC_formac_Command; break; - case SDLK_RMETA: v = MKC_formac_RCommand; break; - case SDLK_LMETA: v = MKC_formac_Command; break; - case SDLK_LSUPER: v = MKC_formac_Option; break; - case SDLK_RSUPER: v = MKC_formac_ROption; break; - - case SDLK_MODE: /* ? */ break; - case SDLK_COMPOSE: /* ? */ break; - - case SDLK_HELP: v = MKC_formac_Help; break; - case SDLK_PRINT: v = MKC_Print; break; - - case SDLK_SYSREQ: /* ? */ break; - case SDLK_BREAK: /* ? */ break; - case SDLK_MENU: /* ? */ break; - case SDLK_POWER: /* ? */ break; - case SDLK_EURO: /* ? */ break; - case SDLK_UNDO: /* ? */ break; - - default: - break; - } - - return v; -} - -LOCALPROC DoKeyCode(SDL_keysym *r, bool down) -{ - uint8_t v = SDLKey2MacKeyCode(r->sym); - if (MKC_None != v) { - Keyboard_UpdateKeyMap2(v, down); - } -} - -LOCALPROC DisableKeyRepeat(void) -{ -} - -LOCALPROC RestoreKeyRepeat(void) -{ -} - -LOCALPROC ReconnectKeyCodes3(void) -{ -} - -LOCALPROC DisconnectKeyCodes3(void) -{ - DisconnectKeyCodes2(); - MouseButtonSet(false); -} - -/* --- time, date, location --- */ - -#define dbglog_TimeStuff (0 && dbglog_HAVE) - -LOCALVAR uint32_t TrueEmulatedTime = 0; - -#define InvTimeDivPow 16 -#define InvTimeDiv (1 << InvTimeDivPow) -#define InvTimeDivMask (InvTimeDiv - 1) -#define InvTimeStep 1089590 /* 1000 / 60.14742 * InvTimeDiv */ - -LOCALVAR Uint32 LastTime; - -LOCALVAR Uint32 NextIntTime; -LOCALVAR uint32_t NextFracTime; - -LOCALPROC IncrNextTime(void) -{ - NextFracTime += InvTimeStep; - NextIntTime += (NextFracTime >> InvTimeDivPow); - NextFracTime &= InvTimeDivMask; -} - -LOCALPROC InitNextTime(void) -{ - NextIntTime = LastTime; - NextFracTime = 0; - IncrNextTime(); -} - -LOCALVAR uint32_t NewMacDateInSeconds; - -LOCALFUNC bool UpdateTrueEmulatedTime(void) -{ - Uint32 LatestTime; - int32_t TimeDiff; - - LatestTime = SDL_GetTicks(); - if (LatestTime != LastTime) { - - NewMacDateInSeconds = LatestTime / 1000; - /* no date and time api in SDL */ - - LastTime = LatestTime; - TimeDiff = (LatestTime - NextIntTime); - /* this should work even when time wraps */ - if (TimeDiff >= 0) { - if (TimeDiff > 256) { - /* emulation interrupted, forget it */ - ++TrueEmulatedTime; - InitNextTime(); - -#if dbglog_TimeStuff - dbglog_writelnNum("emulation interrupted", - TrueEmulatedTime); -#endif - } else { - do { - ++TrueEmulatedTime; - IncrNextTime(); - TimeDiff = (LatestTime - NextIntTime); - } while (TimeDiff >= 0); - } - return true; - } else { - if (TimeDiff < -256) { -#if dbglog_TimeStuff - dbglog_writeln("clock set back"); -#endif - /* clock goofed if ever get here, reset */ - InitNextTime(); - } - } - } - return false; -} - - -LOCALFUNC bool CheckDateTime(void) -{ - if (CurMacDateInSeconds != NewMacDateInSeconds) { - CurMacDateInSeconds = NewMacDateInSeconds; - return true; - } else { - return false; - } -} - -LOCALPROC StartUpTimeAdjust(void) -{ - LastTime = SDL_GetTicks(); - InitNextTime(); -} - -LOCALFUNC bool InitLocationDat(void) -{ - LastTime = SDL_GetTicks(); - InitNextTime(); - NewMacDateInSeconds = LastTime / 1000; - CurMacDateInSeconds = NewMacDateInSeconds; - - return true; -} - -/* --- sound --- */ - -#if SoundEnabled - -#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */ -#define kSoundBuffers (1 << kLn2SoundBuffers) -#define kSoundBuffMask (kSoundBuffers - 1) - -#define DesiredMinFilledSoundBuffs 3 - /* - if too big then sound lags behind emulation. - if too small then sound will have pauses. - */ - -#define kLnOneBuffLen 9 -#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen) -#define kOneBuffLen (1UL << kLnOneBuffLen) -#define kAllBuffLen (1UL << kLnAllBuffLen) -#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3) -#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3) -#define kOneBuffSz (1UL << kLnOneBuffSz) -#define kAllBuffSz (1UL << kLnAllBuffSz) -#define kOneBuffMask (kOneBuffLen - 1) -#define kAllBuffMask (kAllBuffLen - 1) -#define dbhBufferSize (kAllBuffSz + kOneBuffSz) - -#define dbglog_SoundStuff (0 && dbglog_HAVE) -#define dbglog_SoundBuffStats (0 && dbglog_HAVE) - -LOCALVAR tpSoundSamp TheSoundBuffer = nullpr; -volatile static uint16_t ThePlayOffset; -volatile static uint16_t TheFillOffset; -volatile static uint16_t MinFilledSoundBuffs; -#if dbglog_SoundBuffStats -LOCALVAR uint16_t MaxFilledSoundBuffs; -#endif -LOCALVAR uint16_t TheWriteOffset; - -LOCALPROC Sound_Init0(void) -{ - ThePlayOffset = 0; - TheFillOffset = 0; - TheWriteOffset = 0; -} - -LOCALPROC Sound_Start0(void) -{ - /* Reset variables */ - MinFilledSoundBuffs = kSoundBuffers + 1; -#if dbglog_SoundBuffStats - MaxFilledSoundBuffs = 0; -#endif -} - -GLOBALOSGLUFUNC tpSoundSamp Sound_BeginWrite(uint16_t n, uint16_t *actL) -{ - uint16_t ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset); - uint16_t WriteBuffContig = - kOneBuffLen - (TheWriteOffset & kOneBuffMask); - - if (WriteBuffContig < n) { - n = WriteBuffContig; - } - if (ToFillLen < n) { - /* overwrite previous buffer */ -#if dbglog_SoundStuff - dbglog_writeln("sound buffer over flow"); -#endif - TheWriteOffset -= kOneBuffLen; - } - - *actL = n; - return TheSoundBuffer + (TheWriteOffset & kAllBuffMask); -} - -#if 4 == kLn2SoundSampSz -LOCALPROC ConvertSoundBlockToNative(tpSoundSamp p) -{ - int i; - - for (i = kOneBuffLen; --i >= 0; ) { - *p++ -= 0x8000; - } -} -#else -#define ConvertSoundBlockToNative(p) -#endif - -LOCALPROC Sound_WroteABlock(void) -{ -#if (4 == kLn2SoundSampSz) - uint16_t PrevWriteOffset = TheWriteOffset - kOneBuffLen; - tpSoundSamp p = TheSoundBuffer + (PrevWriteOffset & kAllBuffMask); -#endif - -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_WroteABlock"); -#endif - - ConvertSoundBlockToNative(p); - - TheFillOffset = TheWriteOffset; - -#if dbglog_SoundBuffStats - { - uint16_t ToPlayLen = TheFillOffset - - ThePlayOffset; - uint16_t ToPlayBuffs = ToPlayLen >> kLnOneBuffLen; - - if (ToPlayBuffs > MaxFilledSoundBuffs) { - MaxFilledSoundBuffs = ToPlayBuffs; - } - } -#endif -} - -LOCALFUNC bool Sound_EndWrite0(uint16_t actL) -{ - bool v; - - TheWriteOffset += actL; - - if (0 != (TheWriteOffset & kOneBuffMask)) { - v = false; - } else { - /* just finished a block */ - - Sound_WroteABlock(); - - v = true; - } - - return v; -} - -LOCALPROC Sound_SecondNotify0(void) -{ - if (MinFilledSoundBuffs <= kSoundBuffers) { - if (MinFilledSoundBuffs > DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too high"); -#endif - IncrNextTime(); - } else if (MinFilledSoundBuffs < DesiredMinFilledSoundBuffs) { -#if dbglog_SoundStuff - dbglog_writeln("MinFilledSoundBuffs too low"); -#endif - ++TrueEmulatedTime; - } -#if dbglog_SoundBuffStats - dbglog_writelnNum("MinFilledSoundBuffs", - MinFilledSoundBuffs); - dbglog_writelnNum("MaxFilledSoundBuffs", - MaxFilledSoundBuffs); - MaxFilledSoundBuffs = 0; -#endif - MinFilledSoundBuffs = kSoundBuffers + 1; - } -} - -typedef uint16_t trSoundTemp; - -#define kCenterTempSound 0x8000 - -#define AudioStepVal 0x0040 - -#if 3 == kLn2SoundSampSz -#define ConvertTempSoundSampleFromNative(v) ((v) << 8) -#elif 4 == kLn2SoundSampSz -#define ConvertTempSoundSampleFromNative(v) ((v) + kCenterSound) -#else -#error "unsupported kLn2SoundSampSz" -#endif - -#if 3 == kLn2SoundSampSz -#define ConvertTempSoundSampleToNative(v) ((v) >> 8) -#elif 4 == kLn2SoundSampSz -#define ConvertTempSoundSampleToNative(v) ((v) - kCenterSound) -#else -#error "unsupported kLn2SoundSampSz" -#endif - -LOCALPROC SoundRampTo(trSoundTemp *last_val, trSoundTemp dst_val, - tpSoundSamp *stream, int *len) -{ - trSoundTemp diff; - tpSoundSamp p = *stream; - int n = *len; - trSoundTemp v1 = *last_val; - - while ((v1 != dst_val) && (0 != n)) { - if (v1 > dst_val) { - diff = v1 - dst_val; - if (diff > AudioStepVal) { - v1 -= AudioStepVal; - } else { - v1 = dst_val; - } - } else { - diff = dst_val - v1; - if (diff > AudioStepVal) { - v1 += AudioStepVal; - } else { - v1 = dst_val; - } - } - - --n; - *p++ = ConvertTempSoundSampleToNative(v1); - } - - *stream = p; - *len = n; - *last_val = v1; -} - -struct SoundR { - tpSoundSamp fTheSoundBuffer; - volatile uint16_t (*fPlayOffset); - volatile uint16_t (*fFillOffset); - volatile uint16_t (*fMinFilledSoundBuffs); - - volatile trSoundTemp lastv; - - bool wantplaying; - bool HaveStartedPlaying; -}; -typedef struct SoundR SoundR; - -static void audio_callback(void *udata, Uint8 *stream, int len) -{ - uint16_t ToPlayLen; - uint16_t FilledSoundBuffs; - int i; - SoundR *datp = (SoundR *)udata; - tpSoundSamp CurSoundBuffer = datp->fTheSoundBuffer; - uint16_t CurPlayOffset = *datp->fPlayOffset; - trSoundTemp v0 = datp->lastv; - trSoundTemp v1 = v0; - tpSoundSamp dst = (tpSoundSamp)stream; - -#if kLn2SoundSampSz > 3 - len >>= (kLn2SoundSampSz - 3); -#endif - -#if dbglog_SoundStuff - dbglog_writeln("Enter audio_callback"); - dbglog_writelnNum("len", len); -#endif - -label_retry: - ToPlayLen = *datp->fFillOffset - CurPlayOffset; - FilledSoundBuffs = ToPlayLen >> kLnOneBuffLen; - - if (! datp->wantplaying) { -#if dbglog_SoundStuff - dbglog_writeln("playing end transistion"); -#endif - - SoundRampTo(&v1, kCenterTempSound, &dst, &len); - - ToPlayLen = 0; - } else if (! datp->HaveStartedPlaying) { -#if dbglog_SoundStuff - dbglog_writeln("playing start block"); -#endif - - if ((ToPlayLen >> kLnOneBuffLen) < 8) { - ToPlayLen = 0; - } else { - tpSoundSamp p = datp->fTheSoundBuffer - + (CurPlayOffset & kAllBuffMask); - trSoundTemp v2 = ConvertTempSoundSampleFromNative(*p); - -#if dbglog_SoundStuff - dbglog_writeln("have enough samples to start"); -#endif - - SoundRampTo(&v1, v2, &dst, &len); - - if (v1 == v2) { -#if dbglog_SoundStuff - dbglog_writeln("finished start transition"); -#endif - - datp->HaveStartedPlaying = true; - } - } - } - - if (0 == len) { - /* done */ - - if (FilledSoundBuffs < *datp->fMinFilledSoundBuffs) { - *datp->fMinFilledSoundBuffs = FilledSoundBuffs; - } - } else if (0 == ToPlayLen) { - -#if dbglog_SoundStuff - dbglog_writeln("under run"); -#endif - - for (i = 0; i < len; ++i) { - *dst++ = ConvertTempSoundSampleToNative(v1); - } - *datp->fMinFilledSoundBuffs = 0; - } else { - uint16_t PlayBuffContig = kAllBuffLen - - (CurPlayOffset & kAllBuffMask); - tpSoundSamp p = CurSoundBuffer - + (CurPlayOffset & kAllBuffMask); - - if (ToPlayLen > PlayBuffContig) { - ToPlayLen = PlayBuffContig; - } - if (ToPlayLen > len) { - ToPlayLen = len; - } - - for (i = 0; i < ToPlayLen; ++i) { - *dst++ = *p++; - } - v1 = ConvertTempSoundSampleFromNative(p[-1]); - - CurPlayOffset += ToPlayLen; - len -= ToPlayLen; - - *datp->fPlayOffset = CurPlayOffset; - - goto label_retry; - } - - datp->lastv = v1; -} - -LOCALVAR SoundR cur_audio; - -LOCALVAR bool HaveSoundOut = false; - -LOCALPROC Sound_Stop(void) -{ -#if dbglog_SoundStuff - dbglog_writeln("enter Sound_Stop"); -#endif - - if (cur_audio.wantplaying && HaveSoundOut) { - uint16_t retry_limit = 50; /* half of a second */ - - cur_audio.wantplaying = false; - -label_retry: - if (kCenterTempSound == cur_audio.lastv) { -#if dbglog_SoundStuff - dbglog_writeln("reached kCenterTempSound"); -#endif - - /* done */ - } else if (0 == --retry_limit) { -#if dbglog_SoundStuff - dbglog_writeln("retry limit reached"); -#endif - /* done */ - } else - { - /* - give time back, particularly important - if got here on a suspend event. - */ - -#if dbglog_SoundStuff - dbglog_writeln("busy, so sleep"); -#endif - - (void) SDL_Delay(10); - - goto label_retry; - } - - SDL_PauseAudio(1); - } - -#if dbglog_SoundStuff - dbglog_writeln("leave Sound_Stop"); -#endif -} - -LOCALPROC Sound_Start(void) -{ - if ((! cur_audio.wantplaying) && HaveSoundOut) { - Sound_Start0(); - cur_audio.lastv = kCenterTempSound; - cur_audio.HaveStartedPlaying = false; - cur_audio.wantplaying = true; - - SDL_PauseAudio(0); - } -} - -LOCALPROC Sound_UnInit(void) -{ - if (HaveSoundOut) { - SDL_CloseAudio(); - } -} - -#define SOUND_SAMPLERATE 22255 /* = round(7833600 * 2 / 704) */ - -LOCALFUNC bool Sound_Init(void) -{ - SDL_AudioSpec desired; - - Sound_Init0(); - - cur_audio.fTheSoundBuffer = TheSoundBuffer; - cur_audio.fPlayOffset = &ThePlayOffset; - cur_audio.fFillOffset = &TheFillOffset; - cur_audio.fMinFilledSoundBuffs = &MinFilledSoundBuffs; - cur_audio.wantplaying = false; - - desired.freq = SOUND_SAMPLERATE; - -#if 3 == kLn2SoundSampSz - desired.format = AUDIO_U8; -#elif 4 == kLn2SoundSampSz - desired.format = AUDIO_S16SYS; -#else -#error "unsupported audio format" -#endif - - desired.channels = 1; - desired.samples = 1024; - desired.callback = audio_callback; - desired.userdata = (void *)&cur_audio; - - /* Open the audio device */ - if (SDL_OpenAudio(&desired, NULL) < 0) { - fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); - } else { - HaveSoundOut = true; - - Sound_Start(); - /* - This should be taken care of by LeaveSpeedStopped, - but since takes a while to get going properly, - start early. - */ - } - - return true; /* keep going, even if no sound */ -} - -GLOBALOSGLUPROC Sound_EndWrite(uint16_t actL) -{ - if (Sound_EndWrite0(actL)) { - } -} - -LOCALPROC Sound_SecondNotify(void) -{ - if (HaveSoundOut) { - Sound_SecondNotify0(); - } -} - -#endif - -/* --- basic dialogs --- */ - -LOCALPROC CheckSavedMacMsg(void) -{ - /* called only on quit, if error saved but not yet reported */ - - if (nullpr != SavedBriefMsg) { - char briefMsg0[ClStrMaxLength + 1]; - char longMsg0[ClStrMaxLength + 1]; - - NativeStrFromCStr(briefMsg0, SavedBriefMsg); - NativeStrFromCStr(longMsg0, SavedLongMsg); - - fprintf(stderr, "%s\n", briefMsg0); - fprintf(stderr, "%s\n", longMsg0); - - SavedBriefMsg = nullpr; - } -} - -/* --- clipboard --- */ - -#define UseMotionEvents 1 - -#if UseMotionEvents -LOCALVAR bool CaughtMouse = false; -#endif - -/* --- event handling for main window --- */ - -LOCALPROC HandleTheEvent(SDL_Event *event) -{ - switch (event->type) { - case SDL_QUIT: - RequestMacOff = true; - break; - case SDL_ACTIVEEVENT: - switch (event->active.state) { - case SDL_APPINPUTFOCUS: - gTrueBackgroundFlag = (0 == event->active.gain); -#if 0 && UseMotionEvents - if (! gTrueBackgroundFlag) { - CheckMouseState(); - } -#endif - break; - case SDL_APPMOUSEFOCUS: - CaughtMouse = (0 != event->active.gain); - break; - } - break; - case SDL_MOUSEMOTION: - MousePositionNotify( - event->motion.x, event->motion.y); - break; - case SDL_MOUSEBUTTONDOWN: - /* any mouse button, we don't care which */ - MousePositionNotify( - event->button.x, event->button.y); - MouseButtonSet(true); - break; - case SDL_MOUSEBUTTONUP: - MousePositionNotify( - event->button.x, event->button.y); - MouseButtonSet(false); - break; - case SDL_KEYDOWN: - DoKeyCode(&event->key.keysym, true); - break; - case SDL_KEYUP: - DoKeyCode(&event->key.keysym, false); - break; -#if 0 - case Expose: /* SDL doesn't have an expose event */ - int x0 = event->expose.x; - int y0 = event->expose.y; - int x1 = x0 + event->expose.width; - int y1 = y0 + event->expose.height; - - if (x0 < 0) { - x0 = 0; - } - if (x1 > vMacScreenWidth) { - x1 = vMacScreenWidth; - } - if (y0 < 0) { - y0 = 0; - } - if (y1 > vMacScreenHeight) { - y1 = vMacScreenHeight; - } - if ((x0 < x1) && (y0 < y1)) { - HaveChangedScreenBuff(y0, x0, y1, x1); - } - break; -#endif - } -} - -/* --- main window creation and disposal --- */ - -LOCALVAR int argc; -LOCALVAR char **argv; - -LOCALFUNC bool Screen_Init(void) -{ - bool v = false; - - InitKeyCodes(); - - if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) - { - fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); - } else { - SDL_WM_SetCaption(kStrAppName, NULL); - v = true; - } - - return v; -} - -#if MayFullScreen -LOCALVAR bool GrabMachine = false; -#endif - -#if MayFullScreen -LOCALPROC GrabTheMachine(void) -{ -#if GrabKeysFullScreen - (void) SDL_WM_GrabInput(SDL_GRAB_ON); -#endif - -#if EnableFSMouseMotion - /* - if magnification changes, need to reset, - even if HaveMouseMotion already true - */ - if (MoveMouse(ViewHStart + (ViewHSize / 2), - ViewVStart + (ViewVSize / 2))) - { - SavedMouseH = ViewHStart + (ViewHSize / 2); - SavedMouseV = ViewVStart + (ViewVSize / 2); - HaveMouseMotion = true; - } -#endif -} -#endif - -#if MayFullScreen -LOCALPROC UngrabMachine(void) -{ -#if EnableFSMouseMotion - if (HaveMouseMotion) { - (void) MoveMouse(CurMouseH, CurMouseV); - HaveMouseMotion = false; - } -#endif - -#if GrabKeysFullScreen - (void) SDL_WM_GrabInput(SDL_GRAB_OFF); -#endif -} -#endif - -#if EnableFSMouseMotion -LOCALPROC MouseConstrain(void) -{ - int16_t shiftdh; - int16_t shiftdv; - - if (SavedMouseH < ViewHStart + (ViewHSize / 4)) { - shiftdh = ViewHSize / 2; - } else if (SavedMouseH > ViewHStart + ViewHSize - (ViewHSize / 4)) { - shiftdh = - ViewHSize / 2; - } else { - shiftdh = 0; - } - if (SavedMouseV < ViewVStart + (ViewVSize / 4)) { - shiftdv = ViewVSize / 2; - } else if (SavedMouseV > ViewVStart + ViewVSize - (ViewVSize / 4)) { - shiftdv = - ViewVSize / 2; - } else { - shiftdv = 0; - } - if ((shiftdh != 0) || (shiftdv != 0)) { - SavedMouseH += shiftdh; - SavedMouseV += shiftdv; - if (! MoveMouse(SavedMouseH, SavedMouseV)) { - HaveMouseMotion = false; - } - } -} -#endif - -LOCALFUNC bool CreateMainWindow(void) -{ - int NewWindowHeight = vMacScreenHeight; - int NewWindowWidth = vMacScreenWidth; - Uint32 flags = SDL_SWSURFACE; - bool v = false; - -#if 1 && 1 - if (UseMagnify) { - NewWindowHeight *= WindowScale; - NewWindowWidth *= WindowScale; - } -#endif - -#if 1 - if (UseFullScreen) -#endif -#if MayFullScreen - { - flags |= SDL_FULLSCREEN; - } -#endif - - ViewHStart = 0; - ViewVStart = 0; - ViewHSize = vMacScreenWidth; - ViewVSize = vMacScreenHeight; - - surface = SDL_SetVideoMode(NewWindowWidth, NewWindowHeight, -#if 0 != vMacScreenDepth - 32, -#else - /* 32 */ /* 24 */ /* 16 */ 8, -#endif - flags); - if (NULL == surface) { - fprintf(stderr, "SDL_SetVideoMode fails: %s\n", - SDL_GetError()); - } else { -#if 0 != vMacScreenDepth - ColorModeWorks = true; -#endif - v = true; - } - - return v; -} - -#if EnableRecreateW -LOCALFUNC bool ReCreateMainWindow(void) -{ - ForceShowCursor(); /* hide/show cursor api is per window */ - -#if MayFullScreen - if (GrabMachine) { - GrabMachine = false; - UngrabMachine(); - } -#endif - -#if 1 - UseMagnify = WantMagnify; -#endif -#if 1 - UseFullScreen = WantFullScreen; -#endif - - (void) CreateMainWindow(); - - if (HaveCursorHidden) { - (void) MoveMouse(CurMouseH, CurMouseV); - } - - return true; -} -#endif - -LOCALPROC ZapWinStateVars(void) -{ -} - -#if 1 -LOCALPROC ToggleWantFullScreen(void) -{ - WantFullScreen = ! WantFullScreen; -} -#endif - -/* --- SavedTasks --- */ - -LOCALPROC LeaveBackground(void) -{ - ReconnectKeyCodes3(); - DisableKeyRepeat(); -} - -LOCALPROC EnterBackground(void) -{ - RestoreKeyRepeat(); - DisconnectKeyCodes3(); - - ForceShowCursor(); -} - -LOCALPROC LeaveSpeedStopped(void) -{ -#if SoundEnabled - Sound_Start(); -#endif - - StartUpTimeAdjust(); -} - -LOCALPROC EnterSpeedStopped(void) -{ -#if SoundEnabled - Sound_Stop(); -#endif -} - -LOCALPROC CheckForSavedTasks(void) -{ - if (EvtQNeedRecover) { - EvtQNeedRecover = false; - - /* attempt cleanup, EvtQNeedRecover may get set again */ - EvtQTryRecoverFromFull(); - } - -#if EnableFSMouseMotion - if (HaveMouseMotion) { - MouseConstrain(); - } -#endif - - if (RequestMacOff) { - RequestMacOff = false; - if (AnyDiskInserted()) { - MacMsgOverride(kStrQuitWarningTitle, - kStrQuitWarningMessage); - } else { - ForceMacOff = true; - } - } - - if (ForceMacOff) { - return; - } - - if (gTrueBackgroundFlag != gBackgroundFlag) { - gBackgroundFlag = gTrueBackgroundFlag; - if (gTrueBackgroundFlag) { - EnterBackground(); - } else { - LeaveBackground(); - } - } - - if (CurSpeedStopped != (SpeedStopped || - (gBackgroundFlag && ! RunInBackground))) - { - CurSpeedStopped = ! CurSpeedStopped; - if (CurSpeedStopped) { - EnterSpeedStopped(); - } else { - LeaveSpeedStopped(); - } - } - - if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) { - MacMsgDisplayOn(); - } - -#if EnableRecreateW - if (0 -#if 1 - || (UseMagnify != WantMagnify) -#endif -#if 1 - || (UseFullScreen != WantFullScreen) -#endif - ) - { - (void) ReCreateMainWindow(); - } -#endif - -#if MayFullScreen - if (GrabMachine != ( -#if 1 - UseFullScreen && -#endif - ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - GrabMachine = ! GrabMachine; - if (GrabMachine) { - GrabTheMachine(); - } else { - UngrabMachine(); - } - } -#endif - - if (NeedWholeScreenDraw) { - NeedWholeScreenDraw = false; - ScreenChangedAll(); - } - -#if NeedRequestIthDisk - if (0 != RequestIthDisk) { - Sony_InsertIth(RequestIthDisk); - RequestIthDisk = 0; - } -#endif - - if (HaveCursorHidden != (WantCursorHidden - && ! (gTrueBackgroundFlag || CurSpeedStopped))) - { - HaveCursorHidden = ! HaveCursorHidden; - (void) SDL_ShowCursor( - HaveCursorHidden ? SDL_DISABLE : SDL_ENABLE); - } -} - -/* --- command line parsing --- */ - -LOCALFUNC bool ScanCommandLine(void) -{ - char *pa; - int i = 1; - -label_retry: - if (i < argc) { - pa = argv[i++]; - if ('-' == pa[0]) { - if ((0 == strcmp(pa, "--rom")) - || (0 == strcmp(pa, "-r"))) - { - if (i < argc) { - rom_path = argv[i++]; - goto label_retry; - } - } else - { - MacMsg(kStrBadArgTitle, kStrBadArgMessage, false); - } - } else { - (void) Sony_Insert1(pa, false); - goto label_retry; - } - } - - return true; -} - -/* --- main program flow --- */ - -GLOBALOSGLUFUNC bool ExtraTimeNotOver(void) -{ - UpdateTrueEmulatedTime(); - return TrueEmulatedTime == OnTrueTime; -} - -LOCALPROC WaitForTheNextEvent(void) -{ - SDL_Event event; - - if (SDL_WaitEvent(&event)) { - HandleTheEvent(&event); - } -} - -LOCALPROC CheckForSystemEvents(void) -{ - SDL_Event event; - int i = 10; - - while ((--i >= 0) && SDL_PollEvent(&event)) { - HandleTheEvent(&event); - } -} - -GLOBALOSGLUPROC WaitForNextTick(void) -{ -label_retry: - CheckForSystemEvents(); - CheckForSavedTasks(); - - if (ForceMacOff) { - return; - } - - if (CurSpeedStopped) { - DoneWithDrawingForTick(); - WaitForTheNextEvent(); - goto label_retry; - } - - if (ExtraTimeNotOver()) { - (void) SDL_Delay(NextIntTime - LastTime); - goto label_retry; - } - - if (CheckDateTime()) { -#if SoundEnabled - Sound_SecondNotify(); -#endif - } - - if ((! gBackgroundFlag) -#if UseMotionEvents - && (! CaughtMouse) -#endif - ) - { - CheckMouseState(); - } - - OnTrueTime = TrueEmulatedTime; - -#if dbglog_TimeStuff - dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime); -#endif -} - -/* --- platform independent code can be thought of as going here --- */ - -#include "PROGMAIN.h" - -LOCALPROC ZapOSGLUVars(void) -{ - InitDrives(); - ZapWinStateVars(); -} - -LOCALPROC ReserveAllocAll(void) -{ -#if dbglog_HAVE - dbglog_ReserveAlloc(); -#endif - ReserveAllocOneBlock(&ROM, kROM_Size, 5, false); - - ReserveAllocOneBlock(&screencomparebuff, - vMacScreenNumBytes, 5, true); -#if UseControlKeys - ReserveAllocOneBlock(&CntrlDisplayBuff, - vMacScreenNumBytes, 5, false); -#endif - - ReserveAllocOneBlock(&CLUT_final, CLUT_finalsz, 5, false); -#if SoundEnabled - ReserveAllocOneBlock((uint8_t * *)&TheSoundBuffer, - dbhBufferSize, 5, false); -#endif - - EmulationReserveAlloc(); -} - -LOCALFUNC bool AllocMemory(void) -{ - uimr n; - bool IsOk = false; - - ReserveAllocOffset = 0; - ReserveAllocBigBlock = nullpr; - ReserveAllocAll(); - n = ReserveAllocOffset; - ReserveAllocBigBlock = (uint8_t *)calloc(1, n); - if (NULL == ReserveAllocBigBlock) { - MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, true); - } else { - ReserveAllocOffset = 0; - ReserveAllocAll(); - if (n != ReserveAllocOffset) { - /* oops, program error */ - } else { - IsOk = true; - } - } - - return IsOk; -} - -LOCALPROC UnallocMemory(void) -{ - if (nullpr != ReserveAllocBigBlock) { - free((char *)ReserveAllocBigBlock); - } -} - -LOCALFUNC bool InitOSGLU(void) -{ - if (AllocMemory()) -#if dbglog_HAVE - if (dbglog_open()) -#endif - if (ScanCommandLine()) - if (LoadMacRom()) - if (LoadInitialImages()) - if (InitLocationDat()) -#if SoundEnabled - if (Sound_Init()) -#endif - if (Screen_Init()) - if (CreateMainWindow()) - if (WaitForRom()) - { - return true; - } - return false; -} - -LOCALPROC UnInitOSGLU(void) -{ - if (MacMsgDisplayed) { - MacMsgDisplayOff(); - } - - RestoreKeyRepeat(); -#if MayFullScreen - UngrabMachine(); -#endif -#if SoundEnabled - Sound_Stop(); -#endif -#if SoundEnabled - Sound_UnInit(); -#endif -#if IncludePbufs - UnInitPbufs(); -#endif - UnInitDrives(); - - ForceShowCursor(); - -#if dbglog_HAVE - dbglog_close(); -#endif - - UnallocMemory(); - - CheckSavedMacMsg(); - - SDL_Quit(); -} - -int main(int argc, char **argv) -{ - argc = argc; - argv = argv; - - ZapOSGLUVars(); - if (InitOSGLU()) { - ProgramMain(); - } - UnInitOSGLU(); - - return 0; -}