FabGL2 2.0.0
ESP32 Display Controller and Graphics Library for ESP-IDF
Loading...
Searching...
No Matches
VIC20

Emulator of the Commodore VIC-20 home computer: MOS 6502 CPU, VIC 6561 video and sound chip (PAL), two VIA 6522, memory expansions up to 35 KB, cartridges, joystick and an emulated disk drive. It includes 22 programs (games and demos) and can download many more from the Internet. Watch it on YouTube.

Getting started

At boot the emulator copies the included programs into the VIC20Store directory (on the SD card if present, otherwise on the internal SPIFFS partition) and shows the configuration screen:

  • on the left, the program list (the VIC20Store directory)
  • on the right, the buttons and the settings
  • at the bottom, the free space and the download buttons

Select a program and press Enter (or double-click it, or press Load): the emulator sets the needed RAM expansion, loads the program and runs it. Press F12 to go back to the configuration screen at any time, and F12 (or Esc) again to return to the VIC-20.

Configuration screen

Control Function
Run [F12] Runs (or resumes) the VIC-20
Load Loads and runs the selected program
Soft Reset Resets the VIC-20 (the cartridge stays inserted)
Hard Reset Removes the cartridge and resets the VIC-20
HELP [F1] Shows the keyboard shortcuts
Keyboard Layout Layout of the PS/2 keyboard (US, UK, DE, IT, ...)
RAM Expansion Unexpanded, 3K, 8K, 16K, 24K, 27K (24K+3K), 32K, 35K (32K+3K). Set automatically from the file name when a program is loaded
Joystick None, Cursor Keys or Mouse (see below)
Download From: Web Downloads all the programs listed in main/progs/weblist.h (about 90 games and cartridges from zimmers.net). Asks for the WiFi network the first time
Download From: URL Downloads a single program: type the URL and then the file name to give it (see the naming rules below)

In the program list, Del deletes the selected file or directory (asks a confirmation).

Program files and naming rules

Programs are .PRG files (loaded in RAM and started with RUN) or .CRT files (cartridge images, inserted and started with a reset). The file name tells the emulator how to load the program:

PROGNAME [EXP] [ADDRESS].EXT
Part Meaning
PROGNAME Program name
EXP RAM expansion needed: 3K, 8K, 16K, 24K, 27K, 32K, 35K. Omit it for unexpanded programs
ADDRESS Cartridges only: load address 20 (2000h), 40 (4000h), 60 (6000h) or A0 (A000h, default)
EXT PRG or CRT

Examples: Popeye 32K.PRG, Quikman 8K.PRG, Aggressor.CRT.

Cartridges made of several ROM files: give all the parts the same name with a different address, for example Battlezone 60.CRT and Battlezone A0.CRT; loading one of them loads all the parts.

You can also copy .PRG and .CRT files to the VIC20Store directory of the SD card from a PC.

Included programs: Arukanoido, Astro Panic, Blue Star, Dragonwing, Frogger07, Froggie, Kikstart, Kweepout, Nibbler, Omega Fury, Pooyan, Popeye, Pulse, Quikman, Spikes, Splatform, Tank Battalion, Tammerfors, Tetris+, and the demos Bah Bah, Birthday, Digit.

Emulated disk drive

The VIC-20 sees the VIC20Store directory as disk drive 8:

LOAD "$",8 (directory)
LIST
LOAD "NAME",8
SAVE "NAME",8

Keys while the VIC-20 runs

PC key VIC-20 key / action
F12 Back to the configuration screen
Esc RUN/STOP
Home CLR/HOME
Backspace INST/DEL
Delete RESTORE
Left Win CBM (Commodore key)
F1 ... F8 F1 ... F8
^ Up arrow
_ Left arrow
~ Pi
Left Alt + A / S / W / Z Move the screen left / right / up / down (to center it on the monitor)

Joystick

Joystick mode Move Fire
None Right Alt + cursor keys Right Alt + Menu
Cursor Keys Cursor keys Menu (the key next to the right Ctrl)
Mouse Move the mouse Any mouse button

What it demonstrates

Hardware

  • VGA output (default pins)
  • Audio output on GPIO25
  • PS/2 keyboard on port 0, optional PS/2 mouse on port 1
  • Optional SD card (TTGO VGA32 slot)

Build

The example ships a partitions.csv (3 MB application + SPIFFS). See Building the examples.

Source code

Main file of the example, main/VIC20.cpp. The complete project is in the examples/VGA/VIC20 folder.

1/*
2 Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
3 Copyright (c) 2019-2026 Fabrizio Di Vittorio.
4 All rights reserved.
5
6
7* Please contact fdivitto2013@gmail.com if you need a commercial license.
8
9
10* This library and related software is available under GPL v3.
11
12 FabGL is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 FabGL is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with FabGL. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27/*
28 * Optional SD Card connections:
29 * MISO => GPIO 16 (2 for PICO-D4)
30 * MOSI => GPIO 17 (12 for PICO-D4)
31 * CLK => GPIO 14
32 * CS => GPIO 13
33 *
34 * To change above assignment fill other paramaters of FileBrowser::mountSDCard().
35 */
36
37
38#include "freertos/FreeRTOS.h"
39#include "freertos/task.h"
40#include <stdio.h>
41
42#include "fabgl.h"
43#include "fabutils.h"
44#include "network/netutils.h"
45
46#include "src/machine.h"
47
48
49
50// embedded (free) games
51#include "progs/embedded/blue_star.h"
52#include "progs/embedded/omega_fury.h"
53#include "progs/embedded/quikman.h"
54#include "progs/embedded/splatform.h"
55#include "progs/embedded/demo_birthday.h"
56#include "progs/embedded/arukanoido.h"
57#include "progs/embedded/demo_bah_bah_final.h"
58#include "progs/embedded/demo_digit.h"
59#include "progs/embedded/dragonwing.h"
60#include "progs/embedded/kikstart.h"
61#include "progs/embedded/kweepoutmc.h"
62#include "progs/embedded/nibbler.h"
63#include "progs/embedded/pooyan.h"
64#include "progs/embedded/popeye.h"
65#include "progs/embedded/pulse.h"
66#include "progs/embedded/spikes.h"
67#include "progs/embedded/tank_battalion.h"
68#include "progs/embedded/tetris_plus.h"
69#include "progs/embedded/astro-panic.h"
70#include "progs/embedded/frogger07.h"
71#include "progs/embedded/froggie.h"
72#include "progs/embedded/tammerfors.h"
73
74// from the web
75#include "progs/weblist.h"
76
77
78// Flash and SDCard configuration
79#define FORMAT_ON_FAIL true
80#define SPIFFS_MOUNT_PATH "/flash"
81#define SDCARD_MOUNT_PATH "/SD"
82
83
84// base path (can be SPIFFS_MOUNT_PATH or SDCARD_MOUNT_PATH depending from what was successfully mounted first)
85char const * basepath = nullptr;
86
87
88// name of embedded programs directory
89char const * EMBDIR = "VIC20Store";
90
91// name of downloaded programs directory
92char const * DOWNDIR = "VIC20Store";
93
94// name of user directory (where LOAD and SAVE works)
95char const * USERDIR = "VIC20Store"; // same of EMBDIR
96
97
98struct EmbeddedProgDef {
99 char const * filename;
100 uint8_t const * data;
101 int size;
102};
103
104
105// Embedded programs
106// To convert a PRG to header file use...
107// xxd -i myprogram.prg >myprogram.h
108// ...modify like files in progs/embedded, and put filename and binary data in following list.
109const EmbeddedProgDef embeddedProgs[] = {
110 { arukanoido_filename, arukanoido_prg, sizeof(arukanoido_prg) },
111 { nibbler_filename, nibbler_prg, sizeof(nibbler_prg) },
112 { pooyan_filename, pooyan_prg, sizeof(pooyan_prg) },
113 { popeye_filename, popeye_prg, sizeof(popeye_prg) },
114 { tetris_plus_filename, tetris_plus_prg, sizeof(tetris_plus_prg) },
115 { spikes_filename, spikes_prg, sizeof(spikes_prg) },
116 { astro_panic_filename, astro_panic_prg, sizeof(astro_panic_prg) },
117 { splatform_filename, splatform_prg, sizeof(splatform_prg) },
118 { kweepoutmc_filename, kweepoutmc_prg, sizeof(kweepoutmc_prg) },
119 { dragonwing_filename, dragonwing_prg, sizeof(dragonwing_prg) },
120 { tank_battalion_filename, tank_battalion_prg, sizeof(tank_battalion_prg) },
121 { blue_star_filename, blue_star_prg, sizeof(blue_star_prg) },
122 { quikman_filename, quikman_prg, sizeof(quikman_prg) },
123 { frogger07_filename, frogger07_prg, sizeof(frogger07_prg) },
124 { tammerfors_filename, tammerfors_prg, sizeof(tammerfors_prg) },
125 { pulse_filename, pulse_prg, sizeof(pulse_prg) },
126 { omega_fury_filename, omega_fury_prg, sizeof(omega_fury_prg) },
127};
128
129
130#if DEBUGMACHINE
131static volatile int scycles = 0;
132static volatile bool restart = false;
133void vTimerCallback1SecExpired(xTimerHandle pxTimer)
134{
135 printf("%d - ", scycles / 5);
136 printf("Free memory (total, min, largest): %d, %d, %d\n", heap_caps_get_free_size(0), heap_caps_get_minimum_free_size(0), heap_caps_get_largest_free_block(0));
137 restart = true;
138}
139#endif
140
141
142fabgl::VGAController DisplayController;
143fabgl::PS2Controller PS2Controller;
144
145
146// where to store WiFi info, etc...
147Preferences preferences;
149
150
151// copies embedded programs into SPIFFS/SDCard
152void copyEmbeddedPrograms()
153{
154 FileBrowser dir(basepath);
155 if (!dir.exists(EMBDIR, false)) {
156 // there isn't a EMBDIR folder, create and populate it
157 dir.makeDirectory(EMBDIR);
158 dir.changeDirectory(EMBDIR);
159 for (int i = 0; i < sizeof(embeddedProgs) / sizeof(EmbeddedProgDef); ++i) {
160 int fullpathlen = dir.getFullPath(embeddedProgs[i].filename);
161 char fullpath[fullpathlen];
162 dir.getFullPath(embeddedProgs[i].filename, fullpath, fullpathlen);
163 FILE * f = fopen(fullpath, "wb");
164 if (f) {
165 fwrite(embeddedProgs[i].data, 1, embeddedProgs[i].size, f);
166 fclose(f);
167 }
168 }
169 }
170}
171
172
173enum { STYLE_NONE, STYLE_LABEL, STYLE_STATICLABEL, STYLE_LABELGROUP, STYLE_BUTTON, STYLE_BUTTONHELP, STYLE_COMBOBOX, STYLE_CHECKBOX, STYLE_FILEBROWSER};
174
175
176#define BACKGROUND_COLOR RGB888(0, 0, 0)
177
178
179struct DialogStyle : uiStyle {
180 void setStyle(uiObject * object, uint32_t styleClassID) {
181 switch (styleClassID) {
182 case STYLE_LABEL:
183 ((uiLabel*)object)->labelStyle().textFont = &fabgl::FONT_std_12;
184 ((uiLabel*)object)->labelStyle().backgroundColor = BACKGROUND_COLOR;
185 ((uiLabel*)object)->labelStyle().textColor = RGB888(255, 255, 255);
186 break;
187 case STYLE_STATICLABEL:
188 ((uiStaticLabel*)object)->labelStyle().textFont = &fabgl::FONT_std_12;
189 ((uiStaticLabel*)object)->labelStyle().backgroundColor = BACKGROUND_COLOR;
190 ((uiStaticLabel*)object)->labelStyle().textColor = RGB888(255, 255, 255);
191 break;
192 case STYLE_LABELGROUP:
193 ((uiStaticLabel*)object)->labelStyle().textFont = &fabgl::FONT_std_12;
194 ((uiStaticLabel*)object)->labelStyle().backgroundColor = BACKGROUND_COLOR;
195 ((uiStaticLabel*)object)->labelStyle().textColor = RGB888(255, 128, 0);
196 break;
197 case STYLE_BUTTON:
198 ((uiButton*)object)->windowStyle().borderColor = RGB888(255, 255, 255);
199 ((uiButton*)object)->buttonStyle().backgroundColor = RGB888(128, 128, 128);
200 break;
201 case STYLE_BUTTONHELP:
202 ((uiButton*)object)->windowStyle().borderColor = RGB888(255, 255, 255);
203 ((uiButton*)object)->buttonStyle().backgroundColor = RGB888(255, 255, 128);
204 break;
205 case STYLE_COMBOBOX:
206 ((uiFrame*)object)->windowStyle().borderColor = RGB888(255, 255, 255);
207 ((uiFrame*)object)->windowStyle().borderSize = 1;
208 break;
209 case STYLE_CHECKBOX:
210 ((uiFrame*)object)->windowStyle().borderColor = RGB888(255, 255, 255);
211 break;
212 case STYLE_FILEBROWSER:
213 ((uiListBox*)object)->windowStyle().borderColor = RGB888(128, 128, 128);
214 ((uiListBox*)object)->windowStyle().focusedBorderColor = RGB888(255, 255, 255);
215 ((uiListBox*)object)->listBoxStyle().backgroundColor = RGB888(0, 255, 255);
216 ((uiListBox*)object)->listBoxStyle().focusedBackgroundColor = RGB888(0, 255, 255);
217 ((uiListBox*)object)->listBoxStyle().selectedBackgroundColor = RGB888(128, 64, 0);
218 ((uiListBox*)object)->listBoxStyle().focusedSelectedBackgroundColor = RGB888(255, 128, 0);
219 ((uiListBox*)object)->listBoxStyle().textColor = RGB888(0, 0, 128);
220 ((uiListBox*)object)->listBoxStyle().selectedTextColor = RGB888(0, 0, 255);
221 ((uiListBox*)object)->listBoxStyle().textFont = &fabgl::FONT_SLANT_8x14;
222 break;
223 }
224 }
225} dialogStyle;
226
227
228
229struct DownloadProgressFrame : public uiFrame {
230
231 uiLabel * label1;
232 uiLabel * label2;
233 uiButton * button;
234
235 DownloadProgressFrame(uiFrame * parent)
236 : uiFrame(parent, "Download", UIWINDOW_PARENTCENTER, Size(150, 110), false) {
237 frameProps().resizeable = false;
238 frameProps().moveable = false;
239 frameProps().hasCloseButton = false;
240 frameProps().hasMaximizeButton = false;
241 frameProps().hasMinimizeButton = false;
242
243 label1 = new uiLabel(this, "Connecting...", Point(10, 25));
244 label2 = new uiLabel(this, "", Point(10, 45));
245 button = new uiButton(this, "Abort", Point(50, 75), Size(50, 20));
246 button->onClick = [&]() { exitModal(1); };
247 }
248
249};
250
251
252
253struct HelpFame : public uiFrame {
254
255 HelpFame(uiFrame * parent)
256 : uiFrame(parent, "Help", UIWINDOW_PARENTCENTER, Size(218, 335), false) {
257
258 auto button = new uiButton(this, "OK", Point(84, 305), Size(50, 20));
259 button->onClick = [&]() { exitModal(0); };
260
261 onPaint = [&]() {
262 auto cv = canvas();
263 cv->selectFont(&fabgl::FONT_6x8);
264 int x = 4;
265 int y = 10;
266 cv->setPenColor(Color::Green);
267 cv->drawText(x, y += 14, "Keyboard Shortcuts:");
268 cv->setPenColor(Color::Black);
269 cv->setBrushColor(Color::White);
270 cv->drawText(x, y += 14, " F12 > Run or Config");
271 cv->drawText(x, y += 14, " DEL > Delete File/Folder");
272 cv->drawText(x, y += 14, " ALT + ASWZ > Move Screen");
273 cv->setPenColor(Color::Blue);
274 cv->drawText(x, y += 18, "\"None\" Joystick Mode:");
275 cv->setPenColor(Color::Black);
276 cv->drawText(x, y += 14, " ALT + MENU > Joystick Fire");
277 cv->drawText(x, y += 14, " ALT + CURSOR > Joystick Move");
278 cv->setPenColor(Color::Red);
279 cv->drawText(x, y += 18, "\"Cursor Keys\" Joystick Mode:");
280 cv->setPenColor(Color::Black);
281 cv->drawText(x, y += 14, " MENU > Joystick Fire");
282 cv->drawText(x, y += 14, " CURSOR > Joystick Move");
283 cv->setPenColor(Color::Magenta);
284 cv->drawText(x, y += 18, "Emulated keyboard:");
285 cv->setPenColor(Color::Black);
286 cv->drawText(x, y += 14, " HOME > CLR/HOME");
287 cv->drawText(x, y += 14, " ESC > RUN/STOP");
288 cv->drawText(x, y += 14, " Left Win Key > CBM");
289 cv->drawText(x, y += 14, " DELETE > RESTORE");
290 cv->drawText(x, y += 14, " BACKSPACE > INST/DEL");
291 cv->drawText(x, y += 14, " Caret ^ > UP ARROW");
292 cv->drawText(x, y += 14, " Underscore _ > LEFT ARROW");
293 cv->drawText(x, y += 14, " Tilde ~ > M_PI");
294 };
295 }
296
297};
298
299
300
301class Menu : public uiApp {
302
303 uiFileBrowser * fileBrowser;
304 uiComboBox * RAMExpComboBox;
305 uiComboBox * kbdComboBox;
306 uiLabel * freeSpaceLbl;
307
308 // Main machine
309 Machine * machine;
310
311
312 void init() {
313 machine = new Machine(&DisplayController);
314
315 setStyle(&dialogStyle);
316
317 rootWindow()->frameStyle().backgroundColor = BACKGROUND_COLOR;
318
319 // some static text
320 rootWindow()->onPaint = [&]() {
321 auto cv = canvas();
322 cv->selectFont(&fabgl::FONT_SLANT_8x14);
323 cv->setPenColor(RGB888(0, 128, 255));
324 cv->drawText(136, 345, "VIC20 Emulator");
325
326 cv->selectFont(&fabgl::FONT_std_12);
327 cv->setPenColor(RGB888(255, 128, 0));
328 cv->drawText(160, 358, "www.fabgl.com");
329 cv->drawText(130, 371, "2019/26 by Fabrizio Di Vittorio");
330 };
331
332 // programs list
333 fileBrowser = new uiFileBrowser(rootWindow(), Point(5, 10), Size(140, 290), true, STYLE_FILEBROWSER);
334 fileBrowser->setDirectory(basepath); // set absolute path
335 fileBrowser->changeDirectory( fileBrowser->content().exists(DOWNDIR, false) ? DOWNDIR : EMBDIR ); // set relative path
336 fileBrowser->onChange = [&]() {
337 setSelectedProgramConf();
338 };
339
340 // handles following keys:
341 // F1 -> show help
342 // ESC or F12 -> run the emulator
343 rootWindow()->onKeyUp = [&](uiKeyEventInfo const & key) {
344 switch (key.VK) {
345 // F1
346 case VirtualKey::VK_F1:
347 showHelp();
348 break;
349 // ESC or F12
350 case VirtualKey::VK_ESCAPE:
351 case VirtualKey::VK_F12:
352 runVIC20();
353 break;
354 // just to avoid compiler warning
355 default:
356 break;
357 }
358 };
359
360 // handles following keys in filebrowser:
361 // RETURN -> load selected program and return to vic
362 // DELETE -> remove selected dir or file
363 fileBrowser->onKeyUp = [&](uiKeyEventInfo const & key) {
364 switch (key.VK) {
365 // RETURN
366 case VirtualKey::VK_RETURN:
367 if (!fileBrowser->isDirectory() && loadSelectedProgram())
368 runVIC20();
369 break;
370 // DELETE
371 case VirtualKey::VK_DELETE:
372 if (messageBox("Delete Item", "Are you sure?", "Yes", "Cancel") == uiMessageBoxResult::Button1) {
373 fileBrowser->content().remove( fileBrowser->filename() );
374 fileBrowser->update();
375 updateFreeSpaceLabel();
376 }
377 break;
378 // just to avoid compiler warning
379 default:
380 break;
381 }
382 };
383
384 // handles double click on program list
385 fileBrowser->onDblClick = [&]() {
386 if (!fileBrowser->isDirectory() && loadSelectedProgram())
387 runVIC20();
388 };
389
390 int x = 158;
391
392 // "Run" button - run the VIC20
393 auto VIC20Button = new uiButton(rootWindow(), "Run [F12]", Point(x, 10), Size(75, 19), uiButtonKind::Button, true, STYLE_BUTTON);
394 VIC20Button->onClick = [&]() {
395 runVIC20();
396 };
397
398 // "Load" button
399 auto loadButton = new uiButton(rootWindow(), "Load", Point(x, 35), Size(75, 19), uiButtonKind::Button, true, STYLE_BUTTON);
400 loadButton->onClick = [&]() {
401 if (loadSelectedProgram())
402 runVIC20();
403 };
404
405 // "reset" button
406 auto resetButton = new uiButton(rootWindow(), "Soft Reset", Point(x, 60), Size(75, 19), uiButtonKind::Button, true, STYLE_BUTTON);
407 resetButton->onClick = [&]() {
408 machine->reset();
409 runVIC20();
410 };
411
412 // "Hard Reset" button
413 auto hresetButton = new uiButton(rootWindow(), "Hard Reset", Point(x, 85), Size(75, 19), uiButtonKind::Button, true, STYLE_BUTTON);
414 hresetButton->onClick = [&]() {
415 machine->removeCRT();
416 machine->reset();
417 runVIC20();
418 };
419
420 // "help" button
421 auto helpButton = new uiButton(rootWindow(), "HELP [F1]", Point(x, 110), Size(75, 19), uiButtonKind::Button, true, STYLE_BUTTONHELP);
422 helpButton->onClick = [&]() {
423 showHelp();
424 };
425
426 // select keyboard layout
427 int y = 145;
428 new uiStaticLabel(rootWindow(), "Keyboard Layout:", Point(150, y), true, STYLE_LABELGROUP);
429 kbdComboBox = new uiComboBox(rootWindow(), Point(158, y + 20), Size(75, 20), 70, true, STYLE_COMBOBOX);
430 kbdComboBox->items().append(SupportedLayouts::names(), SupportedLayouts::count());
431 kbdComboBox->onChange = [&]() {
432 preferences.putInt("kbdLayout", kbdComboBox->selectedItem());
433 updateKbdLayout();
434 };
435 kbdComboBox->selectItem(updateKbdLayout());
436
437 // RAM expansion options
438 y += 50;
439 new uiStaticLabel(rootWindow(), "RAM Expansion:", Point(150, y), true, STYLE_LABELGROUP);
440 RAMExpComboBox = new uiComboBox(rootWindow(), Point(158, y + 20), Size(75, 19), 130, true, STYLE_COMBOBOX);
441 char const * RAMOPTS[] = { "Unexpanded", "3K", "8K", "16K", "24K", "27K (24K+3K)", "32K", "35K (32K+3K)" };
442 for (int i = 0; i < 8; ++i)
443 RAMExpComboBox->items().append(RAMOPTS[i]);
444 RAMExpComboBox->selectItem((int)machine->RAMExpansion());
445 RAMExpComboBox->onChange = [&]() {
446 machine->setRAMExpansion((RAMExpansionOption)(RAMExpComboBox->selectedItem()));
447 };
448
449 // joystick emulation options
450 y += 50;
451 new uiStaticLabel(rootWindow(), "Joystick:", Point(150, y), true, STYLE_LABELGROUP);
452 new uiStaticLabel(rootWindow(), "None", Point(180, y + 21), true, STYLE_STATICLABEL);
453 auto radioJNone = new uiCheckBox(rootWindow(), Point(158, y + 20), Size(16, 16), uiCheckBoxKind::RadioButton, true, STYLE_CHECKBOX);
454 new uiStaticLabel(rootWindow(), "Cursor Keys", Point(180, y + 41), true, STYLE_STATICLABEL);
455 auto radioJCurs = new uiCheckBox(rootWindow(), Point(158, y + 40), Size(16, 16), uiCheckBoxKind::RadioButton, true, STYLE_CHECKBOX);
456 new uiStaticLabel(rootWindow(), "Mouse", Point(180, y + 61), true, STYLE_STATICLABEL);
457 auto radioJMous = new uiCheckBox(rootWindow(), Point(158, y + 60), Size(16, 16), uiCheckBoxKind::RadioButton, true, STYLE_CHECKBOX);
458 radioJNone->setGroupIndex(1);
459 radioJCurs->setGroupIndex(1);
460 radioJMous->setGroupIndex(1);
461 radioJNone->setChecked(machine->joyEmu() == JE_None);
462 radioJCurs->setChecked(machine->joyEmu() == JE_CursorKeys);
463 radioJMous->setChecked(machine->joyEmu() == JE_Mouse);
464 radioJNone->onChange = [&]() { machine->setJoyEmu(JE_None); };
465 radioJCurs->onChange = [&]() { machine->setJoyEmu(JE_CursorKeys); };
466 radioJMous->onChange = [&]() { machine->setJoyEmu(JE_Mouse); };
467
468 // free space label
469 freeSpaceLbl = new uiLabel(rootWindow(), "", Point(5, 304), Size(0, 0), true, STYLE_LABEL);
470 updateFreeSpaceLabel();
471
472 // "Download From" label
473 new uiStaticLabel(rootWindow(), "Download From:", Point(5, 326), true, STYLE_LABELGROUP);
474
475 // Download Web button (download programs listed and linked in weblist.h)
476 auto downloadProgsBtn = new uiButton(rootWindow(), "Web", Point(13, 345), Size(27, 20), uiButtonKind::Button, true, STYLE_BUTTON);
477 downloadProgsBtn->onClick = [&]() {
478 if (checkWiFi() && messageBox("Download Programs listed in \"weblist.h\"", "Check your local laws for restrictions", "OK", "Cancel", nullptr, uiMessageBoxIcon::Warning) == uiMessageBoxResult::Button1) {
479 auto pframe = new DownloadProgressFrame(rootWindow());
480 auto modalStatus = initModalWindow(pframe);
481 processModalWindowEvents(modalStatus, 100);
482 prepareForDownload();
483 char const * const * plist = WEB_LIST;
484 int count = sizeof(WEB_LIST) / (2 * sizeof(char const *));
485 int dcount = 0;
486 for (int i = 0; i < count; ++i) {
487 char const * filename = *plist++;
488 char const * URL = *plist++;
489 pframe->label1->setText(filename);
490 if (!processModalWindowEvents(modalStatus, 100))
491 break;
492 if (downloadURL(URL, filename))
493 ++dcount;
494 pframe->label2->setTextFmt("Downloaded %d/%d", dcount, count);
495 }
496 // modify "abort" button to "OK"
497 pframe->button->setText("OK");
498 pframe->button->repaint();
499 // wait for OK
500 processModalWindowEvents(modalStatus, -1);
501 endModalWindow(modalStatus);
502 destroyWindow(pframe);
503 fileBrowser->update();
504 updateFreeSpaceLabel();
505 }
506 wifi.disconnect();
507 };
508
509 // Download from URL
510 auto downloadURLBtn = new uiButton(rootWindow(), "URL", Point(48, 345), Size(27, 20), uiButtonKind::Button, true, STYLE_BUTTON);
511 downloadURLBtn->onClick = [&]() {
512 if (checkWiFi()) {
513 char * URL = new char[128];
514 char * filename = new char[25];
515 strcpy(URL, "http://");
516 if (inputBox("Download From URL", "URL", URL, 127, "OK", "Cancel") == uiMessageBoxResult::Button1) {
517 char * lastslash = strrchr(URL, '/');
518 if (lastslash) {
519 strcpy(filename, lastslash + 1);
520 if (inputBox("Download From URL", "Filename", filename, 24, "OK", "Cancel") == uiMessageBoxResult::Button1) {
521 if (downloadURL(URL, filename)) {
522 messageBox("Success", "Download OK!", "OK", nullptr, nullptr);
523 fileBrowser->update();
524 updateFreeSpaceLabel();
525 } else
526 messageBox("Error", "Download Failed!", "OK", nullptr, nullptr, uiMessageBoxIcon::Error);
527 }
528 }
529 }
530 delete [] filename;
531 delete [] URL;
532 wifi.disconnect();
533 }
534 };
535
536 // focus on programs list
537 setFocusedWindow(fileBrowser);
538 }
539
540 // this is the main loop where 6502 instructions are executed until F12 has been pressed
541 void runVIC20()
542 {
543 auto keyboard = PS2Controller.keyboard();
544
545 enableKeyboardAndMouseEvents(false);
546 keyboard->emptyVirtualKeyQueue();
547 machine->VIC().enableAudio(true);
548
549 // setup user directory
550 machine->fileBrowser()->setDirectory(basepath);
551 if (!machine->fileBrowser()->exists(USERDIR, false))
552 machine->fileBrowser()->makeDirectory(USERDIR);
553 machine->fileBrowser()->changeDirectory(USERDIR);
554
555 auto cv = canvas();
556 cv->setBrushColor(0, 0, 0);
557 cv->clear();
558 cv->waitCompletion();
559
560 bool run = true;
561 while (run) {
562
563 #if DEBUGMACHINE
564 int cycles = machine->run();
565 if (restart) {
566 scycles = cycles;
567 restart = false;
568 } else
569 scycles += cycles;
570 #else
571 machine->run();
572 #endif
573
574 // read keyboard
575 if (keyboard->virtualKeyAvailable()) {
576 bool keyDown;
577 VirtualKey vk = keyboard->getNextVirtualKey(&keyDown);
578 switch (vk) {
579
580 // F12 - stop running
581 case VirtualKey::VK_F12:
582 if (!keyDown)
583 run = false; // exit loop
584 break;
585
586 // other keys
587 default:
588 // send to emulated machine
589 machine->setKeyboard(vk, keyDown);
590 break;
591 }
592 }
593
594 }
595 machine->VIC().enableAudio(false);
596 keyboard->emptyVirtualKeyQueue();
597 enableKeyboardAndMouseEvents(true);
598 rootWindow()->repaint();
599 }
600
601 // extract required RAM size from selected filename (a space and 3K, 8K...)
602 void setSelectedProgramConf()
603 {
604 char const * fname = fileBrowser->filename();
605 if (fname) {
606 // select required memory expansion
607 static char const * EXP[8] = { "", " 3K", " 8K", " 16K", " 24K", " 27K", " 32K", " 35K" };
608 int r = 0;
609 for (int i = 1; i < 8; ++i)
610 if (strstr(fname, EXP[i])) {
611 r = i;
612 break;
613 }
614 RAMExpComboBox->selectItem(r);
615 }
616 }
617
618 // extract address from selected filename. "20"=0x2000, "40"=0x4000, "60"=0x6000 or "A0"=0xA000, "A0" or automatic is the default
619 // addrPos if specified will contain where address has been found
620 int getAddress(char * filename, char * * addrPos = nullptr)
621 {
622 static char const * ASTR[] = { " 20", " 40", " 60", " a0", " A0" };
623 static const int ADDR[] = { 0x2000, 0x4000, 0x6000, 0xa000, 0xa000 };
624 for (int i = 0; i < sizeof(ADDR) / sizeof(int); ++i) {
625 auto p = strstr(filename, ASTR[i]);
626 if (p) {
627 if (addrPos)
628 *addrPos = p + 1;
629 return ADDR[i];
630 }
631 }
632 return -1;
633 }
634
635 // configuration given by filename:
636 // PROGNAME[EXP][ADDRESS].EXT
637 // PROGNAME : program name (not included extension)
638 // EXP : expansion ("3K", "8K", "16K", "24K", "27K", "32K", "35K")
639 // ADDRESS : hex address ("20"=0x2000, "40"=0x4000, "60"=0x6000 or "A0"=0xA000), "A0" or automatic is the default
640 // EXT : "CRT" or "PRG"
641 bool loadSelectedProgram()
642 {
643 bool backToVIC = false;
644 char const * fname = fileBrowser->filename();
645 if (fname) {
646 FileBrowser & dir = fileBrowser->content();
647
648 bool isPRG = strstr(fname, ".PRG") || strstr(fname, ".prg");
649 bool isCRT = strstr(fname, ".CRT") || strstr(fname, ".crt");
650
651 if (isPRG || isCRT) {
652
653 machine->removeCRT();
654
655 int fullpathlen = dir.getFullPath(fname);
656 char fullpath[fullpathlen];
657 dir.getFullPath(fname, fullpath, fullpathlen);
658
659 if (isPRG) {
660 // this is a PRG, just reset, load and run
661 machine->loadPRG(fullpath, true, true);
662 } else if (isCRT) {
663 // this a CRT, find other parts, load and reset
664 char * addrPos = nullptr;
665 int addr = getAddress(fullpath, &addrPos);
666 if (addrPos) {
667 // address specified, try to load all possible positions (2000, 4000, 6000 and a000)
668 static const char * POS = { "246Aa" }; // 2=2000, 4=4000, 6=6000, A=a000
669 for (int i = 0; i < sizeof(POS); ++i) {
670 *addrPos = POS[i]; // actually replaces char inside "fullpath"
671 machine->loadCRT(fullpath, true, getAddress(fullpath));
672 }
673 } else {
674 // no address specified, just load it
675 machine->loadCRT(fullpath, true, addr);
676 }
677 }
678 backToVIC = true;
679 }
680 }
681 return backToVIC;
682 }
683
684 // true if WiFi is has been connected
685 bool checkWiFi() {
687 return true;
688 char SSID[32] = "";
689 char psw[32] = "";
690 if (!preferences.getString("SSID", SSID, sizeof(SSID)) || !preferences.getString("WiFiPsw", psw, sizeof(psw))) {
691 // ask user for SSID and password
692 if (inputBox("WiFi Connect", "WiFi Name", SSID, sizeof(SSID), "OK", "Cancel") == uiMessageBoxResult::Button1 &&
693 inputBox("WiFi Connect", "Password", psw, sizeof(psw), "OK", "Cancel") == uiMessageBoxResult::Button1) {
694 preferences.putString("SSID", SSID);
695 preferences.putString("WiFiPsw", psw);
696 } else
697 return false;
698 }
699 bool connected = (wifi.connect(SSID, psw, 16000) == fabgl::WiFiConnectionState::Connected);
700 if (!connected) {
701 messageBox("Network Error", "Failed to connect WiFi. Try again!", "OK", nullptr, nullptr, uiMessageBoxIcon::Error);
702 preferences.remove("WiFiPsw");
703 }
704 return connected;
705 }
706
707 // creates List folder and makes it current
708 void prepareForDownload()
709 {
710 FileBrowser & dir = fileBrowser->content();
711 dir.setDirectory(basepath);
712 dir.makeDirectory(DOWNDIR);
713 dir.changeDirectory(DOWNDIR);
714 }
715
716 // download specified filename from URL
717 bool downloadURL(char const * URL, char const * filename)
718 {
719 //printf("Downloading %s from %s\n", filename, URL);
720 FileBrowser & dir = fileBrowser->content();
721 if (dir.exists(filename, false)) {
722 return true;
723 }
724 bool success = false;
725 fabgl::HTTPRequest http;
726 int httpCode = http.open(URL);
727 if (httpCode == 200) {
728
729 int fullpathLen = dir.getFullPath(filename);
730 char fullpath[fullpathLen];
731 dir.getFullPath(filename, fullpath, fullpathLen);
732 FILE * f = fopen(fullpath, "wb");
733
734 if (f) {
735 int len = http.contentLength();
736 constexpr int BUFSIZE = 1024;
737 uint8_t * buf = (uint8_t*) malloc(BUFSIZE);
738 int dsize = 0;
739 while (len > 0 || len == -1) {
740 int c = http.read(buf, BUFSIZE);
741 if (c <= 0)
742 break;
743 fwrite(buf, c, 1, f);
744 dsize += c;
745 if (len > 0)
746 len -= c;
747 }
748 free(buf);
749 fclose(f);
750 success = (len == 0 || (len == -1 && dsize > 0));
751 if (!success)
752 remove(fullpath); // don't leave a partial file, it would look already downloaded
753 }
754 }
755 //printf("Download %s\n", success ? "OK" : "Failed");
756 return success;
757 }
758
759 // show free SPIFFS space
760 void updateFreeSpaceLabel() {
761 int64_t total, used;
762 FileBrowser::getFSInfo(fileBrowser->content().getCurrentDriveType(), 0, &total, &used);
763 freeSpaceLbl->setTextFmt("%lld KiB Free", (total - used) / 1024);
764 freeSpaceLbl->update();
765 }
766
767 int updateKbdLayout() {
768 auto curLayoutIdx = preferences.getInt("kbdLayout", 3); // default US
769 PS2Controller.keyboard()->setLayout(SupportedLayouts::layouts()[curLayoutIdx]);
770 return curLayoutIdx;
771 }
772
773 void showHelp() {
774 auto hframe = new HelpFame(rootWindow());
775 showModalWindow(hframe);
776 destroyWindow(hframe);
777 }
778
779
780};
781
782
783
786
787
788
789
790void setup()
791{
792 #if DEBUG
793 vTaskDelay(pdMS_TO_TICKS(500)); printf("\n\n\nReset\n"); // for debug purposes
794 #endif
795
796 preferences.begin("VIC20", false);
797 //preferences.clear();
798
799 PS2Controller.begin(PS2Preset::KeyboardPort0_MousePort1, KbdMode::CreateVirtualKeysQueue);
800
801 DisplayController.begin();
802 DisplayController.setResolution(VGA_256x384_60Hz);
803
804 // this improves user interface speed - check possible drawbacks before enabling definitively
805 //DisplayController.enableBackgroundPrimitiveExecution(false);
806
807 // adjust this to center screen in your monitor
808 //DisplayController.moveScreen(20, -2);
809
810 Canvas cv(&DisplayController);
811 cv.selectFont(&fabgl::FONT_6x8);
812
813 cv.clear();
814 cv.drawText(25, 10, "Initializing...");
815 cv.waitCompletion();
816
817 if (FileBrowser::mountSDCard(FORMAT_ON_FAIL, SDCARD_MOUNT_PATH))
818 basepath = SDCARD_MOUNT_PATH;
819 else if (FileBrowser::mountSPIFFS(FORMAT_ON_FAIL, SPIFFS_MOUNT_PATH))
820 basepath = SPIFFS_MOUNT_PATH;
821
822 cv.drawText(25, 30, "Copying embedded programs...");
823 cv.waitCompletion();
824 copyEmbeddedPrograms();
825}
826
827
828void loop()
829{
830 #if DEBUGMACHINE
831 TimerHandle_t xtimer = xTimerCreate("", pdMS_TO_TICKS(5000), pdTRUE, (void*)0, vTimerCallback1SecExpired);
832 xTimerStart(xtimer, 0);
833 #endif
834
835 auto menu = new Menu;
836 menu->run(&DisplayController);
837}
838
839
840extern "C" void app_main()
841{
842 setup();
843 while (true)
844 loop();
845}
Provides a set of drawing methods.
Definition canvas.h:73
static bool mountSPIFFS(bool formatOnFail, char const *mountPath, size_t maxFiles=4)
Mounts the SPIFFS (Flash) filesystem.
void changeDirectory(const char *subdir)
Changes to a directory relative to the current one.
Definition fabutils.cpp:833
static bool mountSDCard(bool formatOnFail, char const *mountPath, size_t maxFiles=4, int allocationUnitSize=16 *1024, int MISO=16, int MOSI=17, int CLK=14, int CS=13)
Mounts the filesystem of the SD Card.
bool setDirectory(const char *path)
Sets the absolute directory path.
Definition fabutils.cpp:812
int getFullPath(char const *name, char *outPath=nullptr, int maxlen=0)
Builds the full file path of a relative name.
void remove(char const *name)
Removes a file or directory.
DriveType getCurrentDriveType()
Returns the drive type of the current directory.
bool exists(char const *name, bool caseSensitive=true)
Determines whether a file or directory exists.
Definition fabutils.cpp:896
static bool getFSInfo(DriveType driveType, int drive, int64_t *total, int64_t *used)
Gets the total and used space of a filesystem.
void makeDirectory(char const *dirname)
Creates a directory.
FileBrowser provides basic file system operations (directory listing, mkdir, remove and rename).
Definition fabutils.h:698
bool remove(char const *key)
Removes the specified key.
size_t getString(char const *key, char *value, size_t maxLen)
Gets a string.
bool begin(char const *name, bool readOnly=false)
Opens the specified namespace.
Simple key/value storage in non-volatile flash (NVS).
Definition preferences.h:61
int open(char const *URL, int64_t rangeStart=0)
Opens a streaming GET request (follows redirects).
Definition netutils.cpp:477
int contentLength()
Gets the content length.
Definition netutils.h:303
int read(void *buffer, int length)
Reads content after a successful open().
Definition netutils.cpp:519
void setLayout(KeyboardLayout const *layout)
Sets the keyboard layout.
Definition keyboard.cpp:224
static Keyboard * keyboard()
Returns the Keyboard object automatically created by PS2Controller.
static void begin(gpio_num_t port0_clkGPIO, gpio_num_t port0_datGPIO, gpio_num_t port1_clkGPIO=GPIO_UNUSED, gpio_num_t port1_datGPIO=GPIO_UNUSED)
Initializes the PS/2 device controller.
PS/2 device controller.
void begin(gpio_num_t redGPIO, gpio_num_t greenGPIO, gpio_num_t blueGPIO, gpio_num_t HSyncGPIO, gpio_num_t VSyncGPIO)
Initializer for 8 colors (5 GPIOs).
VGA bitmapped display controller (64 colors).
WiFiConnectionState connect(char const *ssid, char const *password, int waitConnectionTimeOutMS=10000)
Tries to connect to a WiFi network.
Definition netutils.cpp:201
WiFiConnectionState state()
Returns the connection state.
Definition netutils.h:191
void disconnect()
Disconnects from the WiFi network.
Definition netutils.cpp:249
WiFi connection helper class.
Definition netutils.h:163
Delegate onChange
Change event delegate.
Definition fabui.h:2498
int selectedItem()
Represents currently selected item.
Definition fabui.h:2481
void selectItem(int index)
Selects an item.
Definition fabui.cpp:4502
Delegate onChange
Change event delegate.
Definition fabui.h:2142
Delegate< uiKeyEventInfo const & > onKeyUp
Key-up event delegate.
Definition fabui.h:2157
Delegate onDblClick
Mouse double click event delegate.
Definition fabui.h:2172
Represents the whole application base class.
Definition fabui.h:4323
uiButton(uiWindow *parent, char const *text, const Point &pos, const Size &size, uiButtonKind kind=uiButtonKind::Button, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:2537
Delegate onClick
Mouse click event delegate.
Definition fabui.h:1376
uiCheckBox(uiWindow *parent, const Point &pos, const Size &size, uiCheckBoxKind kind=uiCheckBoxKind::CheckBox, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:4771
StringList & items()
A list of strings representing items of the combobox.
Definition fabui.h:2570
uiComboBox(uiWindow *parent, const Point &pos, const Size &size, int listHeight, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:4694
FileBrowser & content()
Contains current directory representation.
Definition fabui.h:2334
void changeDirectory(char const *path)
Changes current directory as relative path.
Definition fabui.cpp:4390
void setDirectory(char const *path)
Sets current directory as absolute path.
Definition fabui.cpp:4382
char const * filename()
Currently selected filename.
Definition fabui.cpp:4398
bool isDirectory()
Determines whether currently selected item is a directory.
Definition fabui.cpp:4404
void update()
Reloads current directory content and repaints.
Definition fabui.cpp:4424
uiFileBrowser(uiWindow *parent, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:4349
A frame is a window with a title bar, maximize/minimize/close buttons and that is resizable or movabl...
Definition fabui.h:854
void setTextFmt(const char *format,...)
Sets label formatted text.
Definition fabui.cpp:3224
uiLabel(uiWindow *parent, char const *text, const Point &pos, const Size &size=Size(0, 0), bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:3188
void update()
Updates the label content.
Definition fabui.cpp:3240
uiStaticLabel(uiWindow *parent, char const *text, const Point &pos, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:3304
VirtualKey
Represents each possible real or derived (SHIFT + real) key.
Definition fabutils.h:1374
Single include file of the FabGL library.
#define VGA_256x384_60Hz
Definition fabglconf.h:175
This file contains utility classes and functions.
This file contains the fabgl::WiFiScanner, fabgl::WiFiConnection, fabgl::HTTPRequest and fabgl::TCPCl...
Base class for application styles.
Definition fabui.h:4244