st80

Smalltalk-80 (image Xerox de 1983) dans le navigateur, VM du livre bleu en WebAssembly
git clone https://git.schurger.org/st80.git
Log | Files | Refs | README

main.cpp (34965B)


      1 //
      2 //  main.cpp
      3 //  Smalltalk-80
      4 //
      5 //  Created by Dan Banay on 2/20/20.
      6 //  Copyright © 2020 Dan Banay. All rights reserved.
      7 //
      8 //  MIT License
      9 //  Permission is hereby granted, free of charge, to any person obtaining a copy
     10 //  of this software and associated documentation files (the "Software"), to deal
     11 //  in the Software without restriction, including without limitation the rights
     12 //  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     13 //  copies of the Software, and to permit persons to whom the Software is
     14 //  furnished to do so, subject to the following conditions:
     15 //
     16 //  The above copyright notice and this permission notice shall be included in all
     17 //  copies or substantial portions of the Software.
     18 //
     19 //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     20 //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     21 //  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     22 //  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     23 //  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     24 //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     25 //  SOFTWARE.
     26 //
     27 
     28 // If defined, the mouse cursor is rendered by the application rather than the system.
     29 // System rendering is preferred, but on Windows, the cursor didn't always change
     30 // if the left mouse button was being held down. In addition, I found that (again)
     31 // on Windows, on high resolution displays the mouse cursor was tiny
     32 // (it wasn't respecting the display scaling setting).
     33 //
     34 
     35 #ifdef _WIN32
     36 #define SOFTWARE_MOUSE_CURSOR
     37 #endif
     38 
     39 #include <iostream>
     40 #include <fstream>
     41 #include <sstream>
     42 #include <cassert>
     43 #include <stdlib.h>
     44 #include <time.h>
     45 #ifdef _WIN32
     46 #define SDL_MAIN_HANDLED
     47 #include "SDL.h"
     48 #else
     49 #include "SDL2/SDL.h"
     50 #endif
     51 #include "interpreter.h"
     52 #include "posixfilesystem.h"
     53 #include "hal.h"
     54 #include <queue>
     55 
     56 #ifdef __EMSCRIPTEN__
     57 // Port navigateur (st80.schurger.org) : la boucle principale est découpée en trames,
     58 // les caractères viennent de SDL_TEXTINPUT (disposition du clavier respectée) et la page
     59 // pilote la vitesse par les fonctions st80_* exportées (voir web/app.js).
     60 #include <emscripten.h>
     61 static volatile double st80_budget_ms = 10;   // temps d'interprétation par trame
     62 static volatile int    st80_paused = 0;
     63 static double          st80_cycles = 0;       // bytecodes exécutés depuis le départ
     64 class VirtualMachine;
     65 static VirtualMachine *st80_vm = 0;
     66 extern "C" {
     67     EMSCRIPTEN_KEEPALIVE void st80_set_budget(double ms) { st80_budget_ms = ms; }
     68     EMSCRIPTEN_KEEPALIVE void st80_set_paused(int paused) { st80_paused = paused; }
     69     EMSCRIPTEN_KEEPALIVE double st80_cycle_count() { return st80_cycles; }
     70     EMSCRIPTEN_KEEPALIVE const char *st80_image_name();
     71 }
     72 #endif
     73 
     74 
     75 typedef std::uint16_t Pixel;
     76 static const SDL_PixelFormatEnum TextureFormat = SDL_PIXELFORMAT_RGB565;
     77 
     78 
     79 static inline void expand_pixel(Pixel *destPixel, std::uint16_t srcWord, int srcBit)
     80 {
     81     *destPixel = -((srcWord & (1<<srcBit) ) == 0);
     82 }
     83 
     84 struct options
     85 {
     86     std::string root_directory;
     87     std::string snapshot_name;
     88     bool        three_buttons;
     89     int         cycles_per_frame;
     90     int         display_scale;
     91     bool        vsync;
     92     Uint32      novsync_delay;
     93 };
     94 
     95 
     96 class VirtualMachine: public IHardwareAbstractionLayer
     97 {
     98 public:
     99     VirtualMachine(struct options& vm_options) :
    100         vm_options(vm_options),
    101         fileSystem(vm_options.root_directory),
    102         interpreter(this, &fileSystem),
    103         window(0), renderer(0), texture(0),
    104 #ifdef SOFTWARE_MOUSE_CURSOR
    105         mouse_texture(0),
    106 #else
    107         cursor(0),
    108 #endif
    109         display_width(0), display_height(0),
    110         scheduled_semaphore(0), input_semaphore(0), scheduled_time(0),
    111         event_count(0), last_event_time(0),
    112         quit_signalled(false), texture_needs_update(false),
    113         image_name(vm_options.snapshot_name)
    114     {
    115     }
    116     
    117     ~VirtualMachine()
    118     {
    119 #ifdef SOFTWARE_MOUSE_CURSOR
    120         if (mouse_texture)
    121             SDL_DestroyTexture(mouse_texture);
    122 #else
    123         if (cursor)
    124             SDL_FreeCursor(cursor);
    125 
    126 #endif
    127         if (texture)
    128             SDL_DestroyTexture(texture);
    129         if (renderer)
    130             SDL_DestroyRenderer(renderer);
    131         if (window)
    132             SDL_DestroyWindow(window);
    133     }
    134     
    135   
    136     void set_input_semaphore(int semaphore)
    137     {
    138         input_semaphore = semaphore;
    139     }
    140     
    141     // the number of seconds since 00:00 in the morning of January 1, 1901
    142     std::uint32_t get_smalltalk_epoch_time()
    143     {
    144         // Seconds between 1/1/1901 00:00 and 1/1/1970 00:00
    145 
    146         const std::uint32_t TIME_OFFSET = 2177452800;
    147         time_t unix_epoch_time =  time(0);
    148         return (std::uint32_t) unix_epoch_time + TIME_OFFSET;
    149     }
    150     
    151     // the number of milliseconds since the millisecond clock was
    152     // last reset or rolled over (a 32-bit unsigned number)
    153     std::uint32_t get_msclock()
    154     {
    155         return SDL_GetTicks();
    156     }
    157     
    158     void check_scheduled_semaphore()
    159     {
    160         if( scheduled_semaphore && SDL_TICKS_PASSED(SDL_GetTicks(), scheduled_time))
    161         {
    162             interpreter.asynchronousSignal(scheduled_semaphore);
    163             scheduled_semaphore = 0;
    164         }
    165     }
    166 
    167     // Schedule a semaphore to be signaled at a time. Only one outstanding
    168     // request may be scheduled at anytime. When called any outstanding
    169     // request will be replaced (or canceled if semaphore is 0).
    170     // Will signal immediate if scheduled time has passed.
    171     void signal_at(int semaphore, std::uint32_t msClockTime)
    172     {
    173         scheduled_semaphore = semaphore;
    174         scheduled_time = msClockTime;
    175         if (semaphore)
    176         {
    177             // Just in case the time passed
    178             check_scheduled_semaphore();
    179         }
    180     }
    181     
    182     SDL_Cursor *create_cursor(const Uint8* cursor_bits)
    183     {
    184         // Maps a nibble to a byte where each bit is repeated
    185         // e.g. 1010 -> 11001100
    186         static int expandedNibbleToByte[] =
    187         {
    188             0b00000000,  // 0000
    189             0b00000011,  // 0001
    190             0b00001100,  // 0010
    191             0b00001111,  // 0011
    192             0b00110000,  // 0100
    193             0b00110011,  // 0101
    194             0b00111100,  // 0110
    195             0b00111111,  // 0111
    196             0b11000000,  // 1000
    197             0b11000011,  // 1001
    198             0b11001100,  // 1010
    199             0b11001111,  // 1011
    200             0b11110000,  // 1100
    201             0b11110011,  // 1101
    202             0b11111100,  // 1110
    203             0b11111111   // 1111
    204             
    205         };
    206 
    207         SDL_Cursor* new_cursor = 0;
    208         
    209 
    210         if (vm_options.display_scale == 1)
    211         {
    212             new_cursor = SDL_CreateCursor((const Uint8 *) cursor_bits, (const Uint8 *) cursor_bits, 16, 16, 0, 0);
    213 
    214         }
    215         else if (vm_options.display_scale == 2)
    216         {
    217             std::uint8_t image[128];
    218             std::uint8_t *src = (std::uint8_t *) cursor_bits;
    219             int dest = 0;
    220             
    221             // 4 bytes (32-bits) x 32 rows
    222             for(int h = 0; h < 16; h++)
    223             {
    224                 image[dest]   = expandedNibbleToByte[*(src) >> 4];
    225                 image[dest+1] = expandedNibbleToByte[*(src) & 0xf];
    226                 image[dest+2] = expandedNibbleToByte[*(src+1) >> 4];
    227                 image[dest+3] = expandedNibbleToByte[*(src+1) & 0xf];
    228 
    229                 image[dest+4] = image[dest];
    230                 image[dest+5] = image[dest+1];
    231                 image[dest+6] = image[dest+2];
    232                 image[dest+7] = image[dest+3];
    233                 dest += 8;
    234                 src += 2;
    235             }
    236             
    237             new_cursor = SDL_CreateCursor((const Uint8 *) image, (const Uint8 *) image, 32, 32, 0, 0);
    238         }
    239         if (!new_cursor)
    240         {
    241             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Create Cursor failed: %s", SDL_GetError());
    242 
    243         }
    244 
    245         return new_cursor;
    246     }
    247     
    248 #ifdef SOFTWARE_MOUSE_CURSOR
    249     void update_mouse_cursor(const std::uint16_t* cursor_bits)
    250     {
    251         int dest_pitch;
    252         std::uint8_t* pixels;
    253         
    254         int code = SDL_LockTexture(mouse_texture, 0, (void **)&pixels,  &dest_pitch);
    255         if (code < 0)
    256         {
    257             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't LOCK MOUSE TEXTURE SDL: %s", SDL_GetError());
    258             return;
    259         }
    260         
    261         std::uint8_t* dest_row = pixels;
    262         std::uint16_t* source_pixel = (std::uint16_t *) cursor_bits;
    263         for(int h = 0; h < 16; h++)
    264         {
    265             std::uint16_t* dest_pixel = (Pixel *) dest_row;
    266             for(int b = 15; b >= 0; b--)
    267             {
    268                 // Low order bit of a 5551 pixel is alpha
    269                 *dest_pixel = (*source_pixel & (1 << b)) != 0;
    270                 dest_pixel++;
    271             }
    272             source_pixel++;
    273             dest_row += dest_pitch;
    274 
    275         }
    276         SDL_UnlockTexture(mouse_texture);
    277     }
    278 #endif
    279     
    280     // Set the cursor image
    281     // (a 16 word form)
    282     void set_cursor_image(std::uint16_t *image)
    283     {
    284 #ifdef SOFTWARE_MOUSE_CURSOR
    285         
    286         if (!mouse_texture)
    287         {
    288             mouse_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA5551, SDL_TEXTUREACCESS_STREAMING, 16, 16);
    289             SDL_SetTextureBlendMode(mouse_texture, SDL_BLENDMODE_BLEND);
    290         }
    291 
    292         update_mouse_cursor(image);
    293 #else
    294         std::uint16_t cursor_bits[16];
    295 
    296         // SDL uses a MSB format, so swap the bytes
    297         for(int i = 0; i < 16; i++)
    298         {
    299             cursor_bits[i] = ((image[i] & 0xff) << 8) | (image[i] >> 8);
    300         }
    301         
    302         SDL_Cursor* old_cursor = cursor;
    303 
    304         cursor = create_cursor((const Uint8 *) cursor_bits);
    305 
    306         SDL_SetCursor(cursor);
    307 
    308         if (old_cursor)
    309         {
    310             SDL_FreeCursor(old_cursor);
    311         }
    312 #endif
    313 
    314     }
    315     
    316     // Set the mouse cursor location
    317     void set_cursor_location(int x, int y)
    318     {
    319         SDL_WarpMouseInWindow(window, x * vm_options.display_scale, y * vm_options.display_scale);
    320     }
    321     
    322     void get_cursor_location(int *x, int *y)
    323     {
    324         SDL_GetMouseState(x, y);
    325         *x = *x / vm_options.display_scale;
    326         *y = *y / vm_options.display_scale;
    327     }
    328     
    329     void set_link_cursor(bool link)
    330     {
    331     }
    332     
    333     
    334     void initialize_texture()
    335     {
    336         std::uint8_t* dest_row;
    337         int dest_pitch;
    338         
    339         int code = SDL_LockTexture(texture, 0, (void **)&dest_row,  &dest_pitch);
    340         if (code < 0)
    341         {
    342             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't LOCK SDL: %s", SDL_GetError());
    343             return;
    344         }
    345         
    346         // There may be many frames before Smalltalk renders, so initialize the screen texture
    347         // with something that looks like the Smalltalk desktop pattern
    348         for(int h = 0; h < display_height; h++)
    349         {
    350             Pixel* dest_pixel = (Pixel *) dest_row;
    351             
    352             for(int i = 0; i < display_width; i++)
    353             {
    354                 *dest_pixel++ = (h & 1) ^ (i & 1) ? 0 : ~0;
    355             }
    356             dest_row += dest_pitch;
    357         }
    358         SDL_UnlockTexture(texture);
    359     }
    360     
    361     bool set_display_size(int width, int height)
    362     {
    363         if (display_width != width || display_height != height)
    364         {
    365             display_width = width;
    366             display_height = height;
    367             dirty_rect.x = 0;
    368             dirty_rect.y = 0;
    369             dirty_rect.w = width;
    370             dirty_rect.h = height;
    371             
    372             if (window)
    373             {
    374                 SDL_SetWindowSize(window, vm_options.display_scale*display_width, vm_options.display_scale*display_height);
    375                 SDL_DestroyTexture(texture);
    376             }
    377             else
    378             {
    379                 window = SDL_CreateWindow("Smalltalk-80",
    380                                           SDL_WINDOWPOS_UNDEFINED,
    381                                           SDL_WINDOWPOS_UNDEFINED,
    382                                           vm_options.display_scale*display_width, vm_options.display_scale*display_height,
    383                                           0);
    384                 
    385                 Uint32 flags = SDL_RENDERER_ACCELERATED | (vm_options.vsync ? SDL_RENDERER_PRESENTVSYNC : 0);
    386 
    387                 renderer = SDL_CreateRenderer(window, -1, flags );
    388                 if (!renderer) // pas de WebGL (ou pas d'accélération) : rendu logiciel
    389                     renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
    390 
    391 
    392             }
    393             
    394             texture = SDL_CreateTexture(renderer, TextureFormat, SDL_TEXTUREACCESS_STREAMING, display_width, display_height);
    395             initialize_texture();
    396             
    397         }
    398         return true;
    399     }
    400     
    401     void update_texture()
    402     {
    403         int source_word_left = dirty_rect.x / 16;
    404         int source_word_right = ( dirty_rect.x +  dirty_rect.w - 1) / 16;
    405         int display_width_words = (display_width + 15) / 16;
    406         
    407         int source_index_row = source_word_left + (dirty_rect.y * display_width_words);
    408         int update_word_width =  source_word_right - source_word_left + 1;
    409         
    410         // We transfer pixels in groups of WORDS from the display form,
    411         // so we need to set texture update rectangle so the left and right edges are on
    412         // a word boundary
    413         SDL_Rect update_rect;
    414         update_rect.x = source_word_left * 16;
    415         update_rect.y = dirty_rect.y;
    416         update_rect.w = update_word_width * 16;
    417         update_rect.h = dirty_rect.h;
    418         
    419         int displayBitmap = interpreter.getDisplayBits(display_width, display_height);
    420         
    421         if (displayBitmap == 0) return; // bail
    422         
    423         std::uint8_t* pixels;
    424         int dest_pitch;
    425         int code = SDL_LockTexture(texture, &update_rect, (void **)&pixels,  &dest_pitch);
    426         if (code < 0)
    427         {
    428             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't LOCK SDL: %s", SDL_GetError());
    429             return;
    430         }
    431         
    432         std::uint8_t* dest_row = pixels;
    433         
    434         
    435         for(int h = 0; h < update_rect.h; h++)
    436         {
    437             Pixel* dest_pixel = (Pixel *) dest_row;
    438             int source_index = source_index_row;
    439             for(int i = 0; i < update_word_width; i++)
    440             {
    441                 std::uint16_t source_pixel = interpreter.fetchWord_ofDislayBits(source_index, displayBitmap);
    442                 expand_pixel(dest_pixel++, source_pixel, 15);
    443                 expand_pixel(dest_pixel++, source_pixel, 14);
    444                 expand_pixel(dest_pixel++, source_pixel, 13);
    445                 expand_pixel(dest_pixel++, source_pixel, 12);
    446                 expand_pixel(dest_pixel++, source_pixel, 11);
    447                 expand_pixel(dest_pixel++, source_pixel, 10);
    448                 expand_pixel(dest_pixel++, source_pixel, 9);
    449                 expand_pixel(dest_pixel++, source_pixel, 8);
    450                 expand_pixel(dest_pixel++, source_pixel, 7);
    451                 expand_pixel(dest_pixel++, source_pixel, 6);
    452                 expand_pixel(dest_pixel++, source_pixel, 5);
    453                 expand_pixel(dest_pixel++, source_pixel, 4);
    454                 expand_pixel(dest_pixel++, source_pixel, 3);
    455                 expand_pixel(dest_pixel++, source_pixel, 2);
    456                 expand_pixel(dest_pixel++, source_pixel, 1);
    457                 expand_pixel(dest_pixel++, source_pixel, 0);
    458                 
    459                 source_index++;
    460             }
    461             dest_row += dest_pitch;
    462             source_index_row += display_width_words;
    463         }
    464         
    465         SDL_UnlockTexture(texture);
    466     }
    467 
    468     
    469     void display_changed(int x, int y, int width, int height)
    470     {
    471         texture_needs_update = true;
    472         assert(x >= 0 && x < display_width);
    473         assert(y >= 0 && y < display_height);
    474         assert(x + width <= display_width);
    475         assert(y + height <= display_height);
    476         
    477         if (SDL_RectEmpty(&dirty_rect))
    478         {
    479             dirty_rect.x = x;
    480             dirty_rect.y = y;
    481             dirty_rect.w = width;
    482             dirty_rect.h = height;
    483         }
    484         else
    485         {
    486             SDL_Rect update_rect {x, y, width, height};
    487             SDL_UnionRect(&dirty_rect, &update_rect, &dirty_rect);
    488         }
    489     }
    490     
    491 
    492     
    493     void error(const char *message)
    494     {
    495         std::cerr << message << std::endl;
    496         abort();
    497     }
    498     
    499     //Input queue
    500     bool next_input_word(std::uint16_t *word)
    501     {
    502         if (input_queue.size() == 0)
    503             return false;
    504         
    505         *word = input_queue.front();
    506         input_queue.pop();
    507         
    508         return true;
    509     }
    510     
    511     // lifetime
    512     void signal_quit()
    513     {
    514         quit_signalled = true;
    515     }
    516     
    517     const char *get_image_name()
    518     {
    519         return image_name.c_str();
    520     }
    521     
    522     void set_image_name(const char *new_name)
    523     {
    524         image_name = new_name;
    525     }
    526     
    527     
    528     void exit_to_debugger()
    529     {
    530         abort();
    531     }
    532     
    533     bool init()
    534     {
    535 #ifdef __EMSCRIPTEN__
    536         // Le clavier n'est capturé que lorsque le canevas a le focus (la page reste utilisable)
    537         SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, "#canvas");
    538 #endif
    539         if (SDL_Init(SDL_INIT_VIDEO) < 0)
    540         {
    541             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
    542             return false;
    543         }
    544 #ifdef __EMSCRIPTEN__
    545         SDL_StartTextInput();
    546 #endif
    547 
    548 #ifdef SOFTWARE_MOUSE_CURSOR
    549         SDL_ShowCursor(0); // We show our own...
    550         
    551 #endif
    552 
    553         
    554         texture_needs_update = false;
    555         quit_signalled = false;
    556         return interpreter.init();
    557     }
    558     
    559     void queue_input_word(std::uint16_t word)
    560     {
    561         assert(input_semaphore);
    562         input_queue.push(word);
    563         interpreter.asynchronousSignal(input_semaphore);
    564 }
    565     
    566     void queue_input_word(std::uint16_t type, std::uint16_t parameter)
    567     {
    568         queue_input_word(((type & 0xf) << 12) | (parameter & 0xfff));
    569     }
    570     
    571     void queue_input_time_words()
    572     {
    573         std::uint32_t delta_time;
    574         std::uint32_t now = get_msclock();
    575         if (event_count++ == 0)
    576         {
    577             delta_time = 0;
    578         }
    579         else
    580         {
    581             delta_time = now - last_event_time;
    582         }
    583         
    584         if (delta_time <= 4095)
    585         {
    586             // can fit in 12 bits
    587             queue_input_word(0, delta_time);
    588         }
    589         else
    590         {
    591             std::uint32_t abs_time = get_smalltalk_epoch_time();
    592             // too large, use type 5 with absolute time
    593             queue_input_word(5, 0); // parameter is ignored
    594             queue_input_word((abs_time>>16) & 0xffff); // high word first
    595             queue_input_word(abs_time & 0xffff);  // low word next
    596 
    597         }
    598         
    599         last_event_time = now;
    600     }
    601    
    602 #if 0
    603     void paste_clipboard()
    604     {
    605 
    606         if (SDL_HasClipboardText())
    607         {
    608             queue_input_time_words();
    609             for(const char *text = SDL_GetClipboardText(); *text; text++)
    610             {
    611                 int ch = *text;
    612                 if (ch == '\n') ch = '\r';
    613                 queue_input_word(3, ch);
    614                 queue_input_word(4, ch);
    615             }
    616         }
    617     }
    618 #endif
    619     
    620     /*
    621      decoded keyboard:
    622      
    623      A decoded keyboard consists of some independent keys and some “meta" keys (shift and escape)
    624      that cannot be detected on their own, but that change the value of the other keys. The keys
    625      on a decoded keyboard only indicate their down transition, not their up transition.
    626      For a decoded keyboard, the full shifted and “controlled" ASCII should be used as a parameter
    627      and successive type 3 and 4 words should be produced for each keystroke.
    628       
    629      undecoded keyboard:
    630      
    631      (independent keys with up/down detection)
    632      On an undecoded keyboard, the standard keys produce parameters that are the ASCII code
    633      of the character on the keytop without shift or control information (i.e., the key with “A”
    634      on it produces the ASCII for  “a” and the key with “2” and “@“ on it produces the ASCII for “2”).
    635      */
    636     void handle_keyboard_event(const SDL_KeyboardEvent& key)
    637     {
    638 
    639         // Map between a key scan code and it's shifted key value (if any)
    640         static char shift_map[128] = {
    641             0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    642             11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
    643             21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
    644             31, ' ', '!', '"', '#', '$', '%', '&', '"', '(',
    645             ')', '*', '+', '<', '_', '>', '?', ')', '!', '@',
    646             '#', '$', '%', '^', '&', '*', '(', ':', ':', '<',
    647             '+', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F',
    648             'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    649             'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    650             '{', '|', '}', '^', '_', '~', 'A', 'B', 'C', 'D',
    651             'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
    652             'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    653             'Y', 'Z', '{', '|', '}', '~', 127
    654         };
    655         
    656         std::uint16_t type = key.type == SDL_KEYDOWN ? 3 : 4;
    657         std::uint16_t param = 0;
    658         /*
    659          left shift 136 right shift 137 control 138 alpha-lock 139
    660          backspace 8 tab 9 line feed 10 return 13 escape 27 space 32 delete 127
    661 
    662          */
    663 #if 0
    664         if (key.keysym.scancode == SDL_SCANCODE_V && key.keysym.mod == KMOD_LGUI)
    665         {
    666             if (type == 3)
    667                 paste_clipboard();
    668             return;
    669         }
    670 #endif
    671 
    672         // My initial plan was to use go unencoded for everything, but
    673         // when I pressed shift 6, I saw a ~ appear!. It turns out the
    674         // ALTO keyboard has ~ above 6!
    675         // https://www.flickr.com/photos/walkingsf/31415192416
    676         
    677         switch (key.keysym.scancode)
    678         {
    679             case SDL_SCANCODE_LCTRL:
    680             case SDL_SCANCODE_RCTRL:
    681                 param = 138; break;
    682             case SDL_SCANCODE_CAPSLOCK: param = 139; break;
    683             case SDL_SCANCODE_DELETE:   param = 127; break;
    684             default:
    685                 if (key.keysym.sym > 127)
    686                     return;  // Must be ascii
    687 #ifdef __EMSCRIPTEN__
    688                 // Touche sans symbole (touche morte, IME, événement sans « code ») : rien à envoyer,
    689                 // sinon Smalltalk recevrait un caractère NUL.
    690                 if (key.keysym.sym == SDLK_UNKNOWN)
    691                     return;
    692                 // Les caractères imprimables arrivent par SDL_TEXTINPUT (handle_text_input), qui
    693                 // respecte la disposition du clavier ; ici on ne garde que les touches de commande
    694                 // et les combinaisons avec Ctrl, pour lesquelles le navigateur n'émet pas de texte.
    695                 if (key.keysym.sym >= ' ' && key.keysym.sym < 127 && !(key.keysym.mod & KMOD_CTRL))
    696                     return;
    697 #endif
    698                 param = key.keysym.sym & 0x7f;
    699                 break;
    700         }
    701    
    702         if (param < 128)
    703         {
    704             if (type == 3)
    705             {
    706                 if (key.keysym.mod & (KMOD_LGUI|KMOD_RGUI))
    707                     return; // Ignore
    708 
    709                 if (key.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT))
    710                     param = shift_map[param];
    711                 
    712                 /*
    713                  For a decoded keyboard, the full shifted and “controlled" ASCII should be
    714                  used as a parameter and successive type 3 and 4 words should be produced for each keystroke.
    715                  */
    716                 queue_input_time_words();
    717                 queue_input_word(3, param);
    718                 queue_input_word(4, param);
    719             }
    720         }
    721         else
    722         {
    723             // send undecoded
    724             queue_input_time_words();
    725             queue_input_word(type, param);
    726         }
    727     }
    728     
    729 #ifdef __EMSCRIPTEN__
    730     // Texte saisi (clavier « décodé » : un mot type 3 puis type 4 par caractère ASCII)
    731     void handle_text_input(const SDL_TextInputEvent& text)
    732     {
    733         for (const char *p = text.text; *p; p++)
    734         {
    735             unsigned char ch = (unsigned char) *p;
    736             if (ch >= 128) continue; // Smalltalk-80 ne connaît que l'ASCII
    737             queue_input_time_words();
    738             queue_input_word(3, ch);
    739             queue_input_word(4, ch);
    740         }
    741     }
    742 #endif
    743 
    744     void handle_mouse_button_event(const SDL_MouseButtonEvent& mouse)
    745     {
    746         // The bluebook got these wrong!
    747         const int RedButton =    130;  // select
    748         const int YellowButton = 129;  // doit etc.
    749         const int BlueButton =   128;  // frame, close
    750         
    751         unsigned mods;
    752         int smalltalk_button = 0;
    753         int button_index;
    754         
    755         static unsigned button_down_mods[3] = {0}; // modifier state at button down
    756 
    757         switch(mouse.button)
    758         {
    759             case SDL_BUTTON_LEFT:   smalltalk_button = RedButton;    button_index = 0; break;
    760             case SDL_BUTTON_MIDDLE: smalltalk_button = BlueButton;   button_index = 1; break;
    761             case SDL_BUTTON_RIGHT:  smalltalk_button = YellowButton; button_index = 2; break;
    762             default:
    763                 return;
    764         }
    765 
    766         if (mouse.type == SDL_MOUSEBUTTONDOWN)
    767         {
    768             // Save mod state when the button went down
    769             // when the button is released we will use these rather than active one
    770             mods = SDL_GetModState();
    771             button_down_mods[button_index] = mods;
    772         }
    773         else
    774             mods = button_down_mods[button_index];
    775 
    776 
    777         if (vm_options.three_buttons)
    778         {
    779             // Real 3 button mouse
    780             switch(mouse.button)
    781             {
    782                 case SDL_BUTTON_LEFT:   smalltalk_button = RedButton;    break;
    783                 case SDL_BUTTON_MIDDLE: smalltalk_button = YellowButton; break;
    784                 case SDL_BUTTON_RIGHT:  smalltalk_button = BlueButton;   break;
    785                 default:
    786                     return;
    787             }
    788         }
    789         else
    790         {
    791             #ifdef __APPLE__
    792                                 const Uint32 BlueFlags = KMOD_RGUI|KMOD_LGUI;
    793             #else
    794                                 const Uint32 BlueFlags = KMOD_RALT|KMOD_LALT;
    795 
    796             #endif
    797             
    798             /*
    799              Left            = Red
    800              Right/Ctrl+Left = Yellow
    801              Alt+Left(win+linux) /Command+Left(mac)        = Blue
    802              */
    803             switch(mouse.button)
    804             {
    805                 case SDL_BUTTON_LEFT:
    806                     if (mods & BlueFlags)
    807                         smalltalk_button = BlueButton;
    808                     else if (mods & (KMOD_RCTRL|KMOD_LCTRL))
    809                         smalltalk_button = YellowButton;
    810                     else
    811                         smalltalk_button = RedButton;
    812                     break;
    813                 case SDL_BUTTON_RIGHT:
    814                     smalltalk_button = YellowButton;
    815                     break;
    816 #ifdef __EMSCRIPTEN__
    817                 case SDL_BUTTON_MIDDLE:  // molette cliquée = bouton bleu (fenêtres)
    818                     smalltalk_button = BlueButton;
    819                     break;
    820 #endif
    821                 default:
    822                     return;  /* Don't care about this button */
    823             }
    824         }
    825   
    826         if (mouse.type == SDL_MOUSEBUTTONDOWN)
    827         {
    828             queue_input_time_words();
    829             queue_input_word(3, smalltalk_button);
    830         }
    831         else if (mouse.type == SDL_MOUSEBUTTONUP)
    832         {
    833             button_down_mods[button_index] = 0;
    834             queue_input_time_words();
    835             queue_input_word(4, smalltalk_button);
    836         }
    837     }
    838 
    839     void handle_mouse_movement_event(const SDL_MouseMotionEvent& motion)
    840     {
    841         queue_input_time_words();
    842         queue_input_word(1, (std::uint16_t) motion.x);
    843         queue_input_time_words();
    844         queue_input_word(1, (std::uint16_t) motion.y);
    845     }
    846 
    847     
    848     void render()
    849     {
    850         if (renderer)
    851         {
    852             if (texture_needs_update)
    853             {
    854                 update_texture();
    855                 texture_needs_update = false;
    856             }
    857            // SDL_RenderClear(renderer);
    858             if (texture)
    859                 SDL_RenderCopy(renderer, texture, NULL, NULL);
    860             
    861 #ifdef SOFTWARE_MOUSE_CURSOR
    862                 if (mouse_texture)
    863                 {
    864                     static SDL_Rect mouse_src_rect{0,0,16,16};
    865                     int mouseX, mouseY;
    866                     SDL_GetMouseState(&mouseX, &mouseY);
    867 
    868                     SDL_Rect dst = {mouseX, mouseY, 16*vm_options.display_scale, 16*vm_options.display_scale};
    869                     SDL_RenderCopy(renderer, mouse_texture, &mouse_src_rect, &dst);
    870                 }
    871 #endif
    872             
    873             SDL_RenderPresent(renderer);
    874             dirty_rect.x = 0;
    875             dirty_rect.y = 0;
    876             dirty_rect.w = 0;
    877             dirty_rect.h = 0;
    878         }
    879     }
    880     
    881     void process_events()
    882     {
    883         SDL_Event event;
    884         
    885         while (SDL_PollEvent(&event))
    886         {
    887             if(event.type == SDL_QUIT)
    888             {
    889                 quit_signalled = true;
    890                 break;
    891             }
    892             if (input_semaphore)
    893             {
    894                 if (event.type == SDL_KEYUP || event.type == SDL_KEYDOWN)
    895                     handle_keyboard_event(event.key);
    896                 else if (event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEBUTTONDOWN)
    897                     handle_mouse_button_event(event.button);
    898                 else if (event.type == SDL_MOUSEMOTION)
    899                     handle_mouse_movement_event(event.motion);
    900 #ifdef __EMSCRIPTEN__
    901                 else if (event.type == SDL_TEXTINPUT)
    902                     handle_text_input(event.text);
    903 #endif
    904             }
    905         }
    906     }
    907 
    908 #ifdef __EMSCRIPTEN__
    909     // Une trame du navigateur : événements, puis des cycles d'interprétation jusqu'à
    910     // épuisement du budget de temps, puis affichage. Le navigateur appelle frame() par
    911     // requestAnimationFrame ; rien ne bloque jamais.
    912     static void frame_callback(void *arg) { static_cast<VirtualMachine *>(arg)->frame(); }
    913 
    914     void frame()
    915     {
    916         process_events();
    917         check_scheduled_semaphore();
    918         interpreter.checkLowMemoryConditions();
    919 
    920         if (!st80_paused)
    921         {
    922             double start = emscripten_get_now();
    923             do
    924             {
    925                 for(int i = 0; i < vm_options.cycles_per_frame && !quit_signalled; i++)
    926                     interpreter.cycle();
    927                 st80_cycles += vm_options.cycles_per_frame;
    928             }
    929             while (!quit_signalled && emscripten_get_now() - start < st80_budget_ms);
    930         }
    931 
    932         if (quit_signalled)
    933         {
    934             emscripten_cancel_main_loop();
    935             EM_ASM({ if (Module.onQuit) Module.onQuit(); });
    936             return;
    937         }
    938         render();
    939     }
    940 
    941     void run()
    942     {
    943         st80_vm = this;
    944         emscripten_set_main_loop_arg(frame_callback, this, 0, 1);
    945     }
    946 #else
    947     void run()
    948     {
    949         for(;;)
    950         {
    951             process_events();
    952             
    953             check_scheduled_semaphore();
    954             interpreter.checkLowMemoryConditions();
    955             
    956             for(int i = 0; i < vm_options.cycles_per_frame && !quit_signalled; i++)
    957             {
    958                 interpreter.cycle();
    959             }
    960             
    961             if (quit_signalled) break;
    962  
    963             render();
    964             
    965             if (!vm_options.vsync && vm_options.novsync_delay > 0)
    966                 SDL_Delay(vm_options.novsync_delay); // Don't kill CPU
    967         }
    968     }
    969 #endif
    970 
    971     struct options vm_options;
    972 
    973     PosixST80FileSystem fileSystem;
    974 
    975     SDL_Window *window;
    976     SDL_Renderer *renderer;
    977     SDL_Texture *texture;
    978     
    979     
    980 #ifdef SOFTWARE_MOUSE_CURSOR
    981     SDL_Texture *mouse_texture;
    982 #else
    983     SDL_Cursor *cursor;
    984 #endif
    985     
    986     Interpreter interpreter;
    987 
    988     
    989     std::queue<std::uint16_t> input_queue;
    990     std::uint32_t last_event_time;
    991     int event_count;
    992     
    993     int input_semaphore;
    994     bool quit_signalled;
    995     
    996 
    997     bool texture_needs_update;
    998     int display_width, display_height;
    999     
   1000     SDL_Rect dirty_rect;
   1001     
   1002     int scheduled_semaphore;
   1003     std::uint32_t scheduled_time;
   1004     std::string image_name;
   1005     
   1006 };
   1007 
   1008 
   1009 
   1010 #ifdef __EMSCRIPTEN__
   1011 const char *st80_image_name() { return st80_vm ? st80_vm->get_image_name() : ""; }
   1012 #endif
   1013 
   1014 static bool process_args(int argc, const char *argv[], struct options &options)
   1015 {
   1016     if (argc < 3)
   1017         return false;
   1018     
   1019     int arg = 1;
   1020     while (arg < argc)
   1021     {
   1022         // directory option
   1023         if (strcmp(argv[arg], "-directory") == 0 && arg + 1 < argc)
   1024         {
   1025             arg++;
   1026             options.root_directory = argv[arg];
   1027             
   1028             // Remove trailing directory separator (if any) -- Unix and Windows
   1029             if (options.root_directory[options.root_directory.size()-1] == '/' || options.root_directory[options.root_directory.size()-1] == '\\')
   1030                 options.root_directory.pop_back();
   1031         }
   1032         else if (strcmp(argv[arg], "-image") == 0  && arg + 1 < argc)
   1033         {
   1034             arg++;
   1035             options.snapshot_name = argv[arg];
   1036         }
   1037         else if (strcmp(argv[arg], "-delay") == 0  && arg + 1 < argc)
   1038         {
   1039             arg++;
   1040             int delay = atoi(argv[arg]);
   1041             if (delay < 0) return false;
   1042             options.novsync_delay = delay;
   1043         }
   1044         else if (strcmp(argv[arg], "-cycles") == 0  && arg + 1 < argc)
   1045         {
   1046             arg++;
   1047             int cycles = atoi(argv[arg]);
   1048             if (cycles <= 0) return false;
   1049             options.cycles_per_frame = cycles;
   1050         }
   1051         else if (strcmp(argv[arg], "-2x") == 0)
   1052         {
   1053             options.display_scale = 2;
   1054         }
   1055         else if (strcmp(argv[arg], "-vsync") == 0)
   1056         {
   1057             options.vsync = true;
   1058         }
   1059         else if (strcmp(argv[arg], "-three") == 0)
   1060         {
   1061             options.three_buttons = true;
   1062         }
   1063         else
   1064             return false;
   1065         arg++;
   1066     }
   1067     
   1068     // Check for required args
   1069     return options.root_directory.size() > 0;
   1070 }
   1071 
   1072 int main(int argc, const char * argv[]) {
   1073 
   1074     struct options vm_options;
   1075     
   1076     vm_options.snapshot_name = "snapshot.im";
   1077     vm_options.three_buttons = false;
   1078     vm_options.vsync = false;
   1079     vm_options.novsync_delay = 0;  // Try -delay 8 arg if your CPU is unhappy
   1080     vm_options.cycles_per_frame = 1800;
   1081     vm_options.display_scale = 1;
   1082  
   1083     if (!process_args(argc, argv, vm_options))
   1084     {
   1085         std::cerr << "usage: " << argv[0] <<
   1086             " -directory root-directory [-vsync] [-delay ms] [-cycles cycles-per-frame] [-2x] [-image snapshot]"
   1087             << std::endl;
   1088         exit(-1);
   1089     }
   1090     
   1091     VirtualMachine *vm = new VirtualMachine(vm_options);
   1092     if (vm->init())
   1093     {
   1094         vm->run();
   1095     }
   1096     else
   1097     {
   1098         std::cerr << "VM failed to initialize (invalid/missing directory or snapshot?)"  << std::endl;
   1099     }
   1100     delete vm;
   1101 
   1102     return 0;
   1103 }