-
Notifications
You must be signed in to change notification settings - Fork 12
/
Calculator.swift
300 lines (256 loc) · 7.08 KB
/
Calculator.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//
// Calculator.swift
// my41
//
// Created by Miroslav Perovic on 2/14/15.
// Copyright (c) 2015 iPera. All rights reserved.
//
import Foundation
let MAX_RAM_SIZE = 0x400
let epromAddress = 0x4000
var TRACE = 0
var SYNCHRONYZE = false
var SOUND = false
enum HPPort: String, CaseIterable {
case port1 = "ModulePort1"
case port2 = "ModulePort2"
case port3 = "ModulePort3"
case port4 = "ModulePort4"
func getFilePath() -> String? {
guard let module = UserDefaults.standard.string(forKey: self.rawValue) else { return nil }
return Bundle.main.resourcePath! + "/" + module
}
}
enum HPCalculator: String, CaseIterable, Identifiable {
case hp41c = "HP 41C"
case hp41cv = "HP 41CV"
case hp41cx = "HP 41CX"
var id: String { rawValue }
}
let hpCalculatorType = "CalculatorType"
let HPPrinterAvailable = "PrinterAvailable"
let HPCardReaderAvailable = "CardReaderAvailable"
let HPDisplayDebug = "DisplayDebug"
let HPConsoleForegroundColor = "ConsoleForegroundColor"
let HPConsoleBackgroundColor = "ConsoleBackgroundColor"
let HPResetCalculator = "ResetCalculator"
class Calculator: ObservableObject {
var calculatorMod = MOD(memoryCheck: false)
var portMod: [MOD?] = [nil, nil, nil, nil]
var calculatorType: HPCalculator?
var executionTimer: Foundation.Timer?
var timerModule: Timer?
var display: Display?
var alphaMode = false
var prgmMode = false
init() {
timerModule = Timer()
calculatorMod = MOD(memoryCheck: false)
resetCalculator(restoringMemory: true)
}
func resetCalculator(restoringMemory: Bool) {
bus.memModules = 0
bus.XMemModules = 0
cpu.setRunning(false)
cpu.reset()
bus.removeAllRomChips()
self.installBuiltinRoms()
self.installExternalModules()
emptyRAM()
if restoringMemory {
restoreCPU()
restoreMemory()
} else {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "cpu")
defaults.removeObject(forKey: "reg")
defaults.removeObject(forKey: "memory")
defaults.synchronize()
}
cpu.setRunning(true)
self.startExecutionTimer()
}
func installBuiltinRoms() {
self.readCalculatorDescriptionFromDefaults()
let debugSupportRom = RomChip()
debugSupportRom.writable = true
debugSupportRom[0] = 0x3E0
debugSupportRom.writable = false
bus.installRomChip(
debugSupportRom,
inSlot: byte(epromAddress >> 12),
andBank: byte(0)
)
if self.calculatorMod.data != nil {
// Install ROMs which came with the calculator module
do {
try bus.installMod(self.calculatorMod)
} catch MODError.freeSpace {
displayAlert("No free space")
} catch {
}
}
}
func installExternalModules() {
for idx in 0...3 {
if self.portMod[idx]?.data != nil {
do {
try bus.installMod(self.portMod[idx]!)
} catch MODError.freeSpace {
displayAlert("No free space")
} catch {
}
}
}
}
func emptyRAM() {
bus.ram = [Digits14](repeating: Digits14(), count: MAX_RAM_SIZE)
}
let timeSliceInterval = 0.01
func startExecutionTimer() {
cpu.setPowerMode(.powerOn)
executionTimer = Foundation.Timer.scheduledTimer(
timeInterval: timeSliceInterval,
target: self,
selector: #selector(Calculator.timeSlice(_:)),
userInfo: nil,
repeats: true
)
}
func saveMemory() {
let defaults = UserDefaults.standard
do {
let data = try JSONEncoder().encode(bus.ram)
defaults.set(data, forKey: "memory")
defaults.synchronize()
} catch {
print(error)
}
}
func saveCPU() {
do {
let defaults = UserDefaults.standard
let cpu = try JSONEncoder().encode(CPU.sharedInstance)
defaults.set(cpu, forKey: "cpu")
let reg = try JSONEncoder().encode(CPU.sharedInstance.reg)
defaults.set(reg, forKey: "reg")
defaults.synchronize()
} catch {
print(error)
}
}
func restoreMemory() {
if let data = UserDefaults.standard.object(forKey: "memory") as? Data {
let decoder = JSONDecoder()
do {
bus.ram = try decoder.decode([Digits14].self, from: data)
} catch {
print(error)
}
}
}
func restoreCPU() {
if let archivedCPU = UserDefaults.standard.object(forKey: "cpu") as? Data {
let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(CPU.self, from: archivedCPU)
cpu.currentTyte = decoded.currentTyte
cpu.savedPC = decoded.savedPC
cpu.lastOpCode = decoded.lastOpCode
cpu.powerOffFlag = decoded.powerOffFlag
cpu.opcode = decoded.opcode
cpu.prevPT = decoded.prevPT
} catch {
print(error)
}
}
if let archivedCPURegisters = UserDefaults.standard.object(forKey: "reg") as? Data {
let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(CPURegisters.self, from: archivedCPURegisters)
cpu.reg.A = decoded.A
cpu.reg.B = decoded.B
cpu.reg.C = decoded.C
cpu.reg.M = decoded.M
cpu.reg.N = decoded.N
cpu.reg.P = decoded.P
cpu.reg.Q = decoded.Q
cpu.reg.PC = decoded.PC
cpu.reg.G = decoded.G
cpu.reg.ST = decoded.ST
cpu.reg.T = decoded.T
cpu.reg.FI = decoded.FI
cpu.reg.XST = decoded.XST
cpu.reg.stack = decoded.stack
cpu.reg.R = decoded.R
cpu.reg.mode = decoded.mode
cpu.reg.ramAddress = decoded.ramAddress
cpu.reg.peripheral = decoded.peripheral
} catch {
print(error)
}
}
}
private func getMemoryContents() -> [Digits14] {
var memoryArray = [Digits14](repeating: Digits14(), count: MAX_RAM_SIZE)
for addr in 0..<MAX_RAM_SIZE {
do {
let tmpReg = try bus.readRamAddress(Bits12(addr))
memoryArray[Int(addr)] = tmpReg
print("save from \(addr): \(tmpReg)")
} catch {
if TRACE != 0 {
print("error RAM address: \(addr)")
}
}
}
return memoryArray
}
func readCalculatorDescriptionFromDefaults() {
let defaults = UserDefaults.standard
readROMModule(defaults.string(forKey: hpCalculatorType) ?? "")
// Now we fill each port
var portNo = 0
HPPort.allCases.forEach {
do {
portMod[portNo] = MOD(memoryCheck: true)
if let modName = defaults.string(forKey: $0.rawValue) {
try portMod[portNo]?.readModFromFile(Bundle.main.resourcePath! + "/" + modName, withMemoryCheck: true)
}
portNo += 1
} catch _ {
}
}
}
func readROMModule(_ cType: String) {
var filename: String
switch cType {
case HPCalculator.hp41c.rawValue:
calculatorType = .hp41c
filename = Bundle.main.resourcePath! + "/" + "nut-c.mod"
case HPCalculator.hp41cv.rawValue:
calculatorType = .hp41cv
filename = Bundle.main.resourcePath! + "/" + "nut-cv.mod"
case HPCalculator.hp41cx.rawValue:
calculatorType = .hp41cx
filename = Bundle.main.resourcePath! + "/" + "nut-cx.mod"
default:
// Make sure I have a default for next time
calculatorType = .hp41cx
let defaults = UserDefaults.standard
defaults.set(HPCalculator.hp41cx.rawValue, forKey: hpCalculatorType)
filename = Bundle.main.resourcePath! + "/" + "nut-cx.mod"
defaults.synchronize()
}
do {
try calculatorMod.readModFromFile(filename, withMemoryCheck: true)
} catch let error as NSError {
displayAlert(error.description)
}
}
@objc func timeSlice(_ timer: Foundation.Timer) {
cpu.timeSlice(timer)
display?.timeSlice(timer)
timerModule?.timeSlice(timer)
}
}