/** * Constants */ const byte BLACK = 0; const byte WHITE = 255; const byte DARK_GRAY = 73; const byte GRAY = 146; const byte LIGHT_GRAY = 182; byte selected_color = 255; interface Device { nat handle; } plex Screen implements Device { nat handle; nat width; nat height; nat buffer_size; byte[] screen_buffer; init() { this.handle = open("/dev/screen/0", 0); } } plex Mouse implements Device { nat handle; nat x; nat y; bool left; bool right; bool middle; bool btn4; nat size; init() { this.handle = open("/dev/mouse/0", 0); } } /** * Main function */ function main() { Screen screen(); Mouse mouse(); outline_swatch(screen, BLACK, 1, 1, 8); outline_swatch(screen, WHITE, 21, 1, 8); screen.draw(); loop { mouse.read(); if (not mouse.left) continue; int box_size = 20; int x = 1; int y = 1; byte color = BLACK; outlined_swatch(screen, color, x, y); set_color(box_size, x, y, mouse.x, mouse.y, color); color = WHITE; x = 21; outlined_swatch(screen, color, x, y); set_color(box_size, x, y, mouse.x, mouse.y, color); screen.draw(); draw_box(screen, selected_color, x, y, 5, 5); } exit(0); } /** * Checks if the click is within the bound and update the selected color if so. */ function set_color(int mouse_x, int mouse_y, int box_x, int box_y, nat color, nat box_size) { int right = box_x + box_size; int bottom = box_y + box_size; if (mouse_x < box_x) return; if (mouse_x > right) return; if (mouse_y < box_y) return; if (mouse_y > bottom) return; selected_color = color; } /** * Draw a color box with a grey outline, if selected use a darker color */ function outline_swatch(Device screen, byte color, int x, int y) { byte bg_color = GRAY; if (selected_color == color) { bg_color = DARK_GRAY; } draw_box(screen, bg_color, x, y, 20, 20); draw_box(screen, color, x + 2, y + 2, 17, 17); } /** * Draw a box */ function draw_box(Device screen, int screen_width, byte color, int x, int y, int width, int height) { // we need unsafe because we are using `ptr` and `memset` directly // unsafe takes the guardrails off and allows you to access/modify memory directly unsafe { int pixel = y * screen_width + x + screen.buffer.ptr + 4; do (int i = height; i > 0; i--) { int row = pixel + width; memset(screen.buffer.ptr, row, color, width); pixel += screen_width; } } }