Debian Codegraph @

gtk/shell_main.cc

raw ◀ ▶
1 Debian patch touch this file
1 ///////////////////////////////////////////////////////////////////////////////
2 // Free42 -- an HP-42S calculator simulator
3 // Copyright (C) 2004-2026 Thomas Okken
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License, version 2,
7 // as published by the Free Software Foundation.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, see http://www.gnu.org/licenses/.
16 ///////////////////////////////////////////////////////////////////////////////
17
18 #include <gtk/gtk.h>
19 #include <gdk/gdkkeysyms.h>
20 #include <errno.h>
21 #include <locale.h>
22 #include <pwd.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <dirent.h>
31 #include <unistd.h>
32 #include <time.h>
33
34 #include "shell.h"
35 #include "shell_main.h"
36 #include "shell_skin.h"
37 #include "shell_spool.h"
38 #include "core_main.h"
39 #include "core_display.h"
40
41 #ifndef _POSIX_HOST_NAME_MAX
42 #define _POSIX_HOST_NAME_MAX 255
43 #endif
44 #ifndef _POSIX_LOGIN_NAME_MAX
45 #define _POSIX_LOGIN_NAME_MAX 255
46 #endif
47
48 #ifdef AUDIO_ALSA
49 #include "audio_alsa.h"
50 #endif
51
52
53 /* These are global because the skin code uses them a lot */
54
55 GtkWidget *calc_widget;
56 GtkWidget *mainwindow;
57 bool allow_paint = false;
58 int menu_bar_height = -1;
59
60 state_type state;
61 char free42dirname[FILENAMELEN];
62
63
64 /* PRINT_LINES is limited to an even lower value than in the Motif version.
65 * It appears that GTK does not allow the SUM of a widget's height and its
66 * container's height to exceed 32k, which means that as the print widget's
67 * height approaches that magical number, the top-level window is forced to
68 * become shorter and shorter. So, I set the limit at 30000 instead of
69 * 32768; if we're reading a print-out file from Free42/Motif which has more
70 * than 30000 pixels, we chop off the excess from the top.
71 */
72 #define PRINT_LINES 30000
73 #define PRINT_BYTESPERLINE 36
74 #define PRINT_SIZE 1080000
75 // Room for PRINT_LINES / 18 lines, plus two, plus one byte
76 #define PRINT_TEXT_SIZE 41726
77
78
79 static unsigned char *print_bitmap;
80 static int printout_top;
81 static int printout_bottom;
82 static unsigned char *print_text;
83 static int print_text_top;
84 static int print_text_bottom;
85 static int print_text_pixel_height;
86 static bool quit_flag = false;
87 static bool enqueued;
88
89
90 /* Private globals */
91
92 static FILE *print_txt = NULL;
93 static FILE *print_gif = NULL;
94 static char print_gif_name[FILENAMELEN];
95 static int gif_seq = -1;
96 static int gif_lines;
97
98 static int pype[2];
99
100 static GtkApplication *app = NULL;
101 static GtkWidget *printwindow;
102 static GtkWidget *print_widget;
103 //static GdkGC *print_gc = NULL;
104 static GtkAdjustment *print_adj;
105 static GdkPixbuf *icon_128;
106 static GdkPixbuf *icon_48;
107 static guint resize_timeout_id = 0;
108
109 int ckey = 0;
110 int skey = -1;
111 static unsigned char *macro;
112 static int macro_type;
113 static bool mouse_key;
114 static guint16 active_keycode = 0;
115 static bool just_pressed_shift = false;
116 static guint timeout_id = 0;
117 static guint timeout3_id = 0;
118
119 static int keymap_length = 0;
120 static keymap_entry *keymap = NULL;
121
122 static guint reminder_id = 0;
123 static FILE *statefile = NULL;
124 static char statefilename[FILENAMELEN];
125 static char printfilename[FILENAMELEN];
126 static char keymapfilename[FILENAMELEN];
127
128 int ann_updown = 0;
129 int ann_shift = 0;
130 int ann_print = 0;
131 int ann_run = 0;
132 int ann_battery = 0;
133 int ann_g = 0;
134 int ann_rad = 0;
135 static guint ann_print_timeout_id = 0;
136
137 void get_keymap(keymap_entry **map, int *length) {
138 *map = keymap;
139 *length = keymap_length;
140 }
141
142 static bool keyboardShortcutsShowing = false;
143 static GtkCheckMenuItem *keyboardShortcutsMenuItem;
144
145
146 /* Private functions */
147
148 static void read_key_map(const char *keymapfilename);
149 static void init_shell_state(int4 version);
150 static int read_shell_state(int4 *version);
151 static int write_shell_state();
152 static void int_term_handler(int sig);
153 static gboolean gt_signal_handler(GIOChannel *source, GIOCondition condition,
154 gpointer data);
155 static void quit();
156 static char *strclone(const char *s);
157 static bool file_exists(const char *name);
158 static void show_message(const char *title, const char *message, GtkWidget *parent = mainwindow);
159 static void no_mwm_resize_borders(GtkWidget *window);
160 static void no_mwm_zoom_box(GtkWidget *window);
161 static void scroll_printout_to_bottom();
162 static void quitCB();
163 static void statesCB();
164 static void showPrintOutCB();
165 static void exportProgramCB();
166 static GtkWidget *make_file_select_dialog(
167 const char *title, const char *pattern, bool save, GtkWidget *owner);
168 static void importProgramCB();
169 static void paperAdvanceCB();
170 static void copyPrintAsTextCB();
171 static void copyPrintAsImageCB();
172 static void clearPrintOutCB();
173 static void preferencesCB();
174 static void appendSuffix(char *path, const char *suffix);
175 static void copyCB();
176 static void pasteCB();
177 static void documentationCB();
178 static void websiteCB();
179 static void otherWebsiteCB();
180 static void keyboardShortcutsCB();
181 static void editKeymapCB();
182 static void aboutCB();
183 static gboolean delete_cb(GtkWidget *w, GdkEventAny *ev);
184 static gboolean delete_print_cb(GtkWidget *w, GdkEventAny *ev);
185 static gboolean draw_cb(GtkWidget *w, cairo_t *cr, gpointer cd);
186 static gboolean print_draw_cb(GtkWidget *w, cairo_t *cr, gpointer cd);
187 static gboolean print_key_cb(GtkWidget *w, GdkEventKey *event, gpointer cd);
188 static gboolean button_cb(GtkWidget *w, GdkEventButton *event, gpointer cd);
189 static gboolean key_cb(GtkWidget *w, GdkEventKey *event, gpointer cd);
190 static void enable_reminder();
191 static void disable_reminder();
192 static gboolean repeater(gpointer cd);
193 static gboolean timeout1(gpointer cd);
194 static gboolean timeout2(gpointer cd);
195 static gboolean timeout3(gpointer cd);
196 static gboolean battery_checker(gpointer cd);
197 static void repaint_printout(cairo_t *cr, bool dark);
198 static gboolean reminder(gpointer cd);
199 static void txt_writer(const char *text, int length);
200 static void txt_newliner();
201 static void gif_seeker(int4 pos);
202 static void gif_writer(const char *text, int length);
203
204
205 #ifdef BCD_MATH
206 #define TITLE "Free42 Decimal"
•207 #define APPID "com.thomasokken.Free42dec"
208 #else
209 #define TITLE "Free42 Binary"
•210 #define APPID "com.thomasokken.Free42bin"
211 #endif
212
213 static const char *mainWindowXml =
214 "<?xml version='1.0' encoding='UTF-8'?>"
215 "<interface>"
216 "<!-- interface-requires gtk+ 3.0 -->"
217 "<object class='GtkApplicationWindow' id='window'>"
218 "<child>"
219 "<object class='GtkVBox' id='box'>"
220 "<child>"
221 "<object class='GtkMenuBar' id='menubar'>"
222 "<child>"
223 "%s" // Additional menu level goes here when using -compactmenu
224 "<object class='GtkMenuItem' id='file_item'>"
225 "<property name='label'>File</property>"
226 "<child type='submenu'>"
227 "<object class='GtkMenu' id='file_menu'>"
228 "<child>"
229 "<object class='GtkMenuItem' id='states_item'>"
230 "<property name='label'>States...</property>"
231 "</object>"
232 "</child>"
233 "<child>"
234 "<object class='GtkSeparatorMenuItem' id='sep_1'>"
235 "</object>"
236 "</child>"
237 "<child>"
238 "<object class='GtkMenuItem' id='show_printout_item'>"
239 "<property name='label'>Show Print-Out</property>"
240 "</object>"
241 "</child>"
242 "<child>"
243 "<object class='GtkMenuItem' id='paper_advance_item'>"
244 "<property name='label'>Paper Advance</property>"
245 "<accelerator key='A' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
246 "</object>"
247 "</child>"
248 "<child>"
249 "<object class='GtkSeparatorMenuItem' id='sep_2'>"
250 "</object>"
251 "</child>"
252 "<child>"
253 "<object class='GtkMenuItem' id='import_programs_item'>"
254 "<property name='label'>Import Programs...</property>"
255 "</object>"
256 "</child>"
257 "<child>"
258 "<object class='GtkMenuItem' id='export_programs_item'>"
259 "<property name='label'>Export Programs...</property>"
260 "</object>"
261 "</child>"
262 "<child>"
263 "<object class='GtkSeparatorMenuItem' id='sep_3'>"
264 "</object>"
265 "</child>"
266 "<child>"
267 "<object class='GtkMenuItem' id='preferences_item'>"
268 "<property name='label'>Preferences...</property>"
269 "</object>"
270 "</child>"
271 "<child>"
272 "<object class='GtkSeparatorMenuItem' id='sep_4'>"
273 "</object>"
274 "</child>"
275 "<child>"
276 "<object class='GtkMenuItem' id='quit_item'>"
277 "<property name='label'>Quit</property>"
278 "<accelerator key='Q' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
279 "</object>"
280 "</child>"
281 "</object>"
282 "</child>"
283 "</object>"
284 "</child>"
285 "<child>"
286 "<object class='GtkMenuItem' id='edit_item'>"
287 "<property name='label'>Edit</property>"
288 "<child type='submenu'>"
289 "<object class='GtkMenu' id='edit_menu'>"
290 "<child>"
291 "<object class='GtkMenuItem' id='copy_item'>"
292 "<property name='label'>Copy</property>"
293 "<accelerator key='C' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
294 "</object>"
295 "</child>"
296 "<child>"
297 "<object class='GtkMenuItem' id='paste_item'>"
298 "<property name='label'>Paste</property>"
299 "<accelerator key='V' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
300 "</object>"
301 "</child>"
302 "<child>"
303 "<object class='GtkSeparatorMenuItem' id='sep_5'>"
304 "</object>"
305 "</child>"
306 "<child>"
307 "<object class='GtkMenuItem' id='copy_printout_as_text_item'>"
308 "<property name='label'>Copy Print-Out as Text</property>"
309 "<accelerator key='T' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
310 "</object>"
311 "</child>"
312 "<child>"
313 "<object class='GtkMenuItem' id='copy_printout_as_image_item'>"
314 "<property name='label'>Copy Print-Out as Image</property>"
315 "<accelerator key='I' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
316 "</object>"
317 "</child>"
318 "<child>"
319 "<object class='GtkMenuItem' id='clear_printout_item'>"
320 "<property name='label'>Clear Print-Out</property>"
321 "<accelerator key='D' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
322 "</object>"
323 "</child>"
324 "</object>"
325 "</child>"
326 "</object>"
327 "</child>"
328 "<child>"
329 "<object class='GtkMenuItem' id='skin_item'>"
330 "<property name='label'>Skin</property>"
331 "<child type='submenu'>"
332 "<object class='GtkMenu' id='skin_menu'>"
333 "<!-- Skin items inserted programmatically here -->"
334 "</object>"
335 "</child>"
336 "</object>"
337 "</child>"
338 "<child>"
339 "<object class='GtkMenuItem' id='help_item'>"
340 "<property name='label'>Help</property>"
341 "<child type='submenu'>"
342 "<object class='GtkMenu' id='help_menu'>"
343 "<child>"
344 "<object class='GtkMenuItem' id='documentation_item'>"
345 "<property name='label'>Documentation</property>"
346 "</object>"
347 "</child>"
348 "<child>"
349 "<object class='GtkMenuItem' id='website_item'>"
350 "<property name='label'>Web Site</property>"
351 "</object>"
352 "</child>"
353 "<child>"
354 "<object class='GtkMenuItem' id='other_website_item'>"
355 "<property name='label'>Plus42 Web Site</property>"
356 "</object>"
357 "</child>"
358 "<child>"
359 "<object class='GtkSeparatorMenuItem' id='sep_6'>"
360 "</object>"
361 "</child>"
362 "<child>"
363 "<object class='GtkCheckMenuItem' id='keyboard_shortcuts_item'>"
364 "<property name='label'>Keyboard Shortcuts</property>"
365 "<accelerator key='K' signal='activate' modifiers='GDK_CONTROL_MASK'/>"
366 "</object>"
367 "</child>"
368 "<child>"
369 "<object class='GtkMenuItem' id='edit_keymap_item'>"
370 "<property name='label'>Edit Keyboard Map</property>"
371 "</object>"
372 "</child>"
373 "<child>"
374 "<object class='GtkSeparatorMenuItem' id='sep_7'>"
375 "</object>"
376 "</child>"
377 "<child>"
378 "<object class='GtkMenuItem' id='about_item'>"
379 "<property name='label'>About Free42...</property>"
380 "</object>"
381 "</child>"
382 "</object>"
383 "</child>"
384 "</object>"
385 "%s"
386 "</child>"
387 "</object>"
388 "<packing>"
389 "<property name='expand'>FALSE</property>"
390 "<property name='fill'>TRUE</property>"
391 "</packing>"
392 "</child>"
393 "</object>"
394 "</child>"
395 "</object>"
396 "</interface>";
397
398 static const char *compactMenuIntroXml =
399 "<object class='GtkMenuItem' id='top_item'>"
400 "<property name='label'>Menu</property>"
401 "<child type='submenu'>"
402 "<object class='GtkMenu' id='top_menu'>"
403 "<child>";
404
405 static const char *compactMenuOutroXml =
406 "</child>"
407 "</object>"
408 "</child>"
409 "</object>";
410
411 static int use_compactmenu = 0;
412 static char *skin_arg = NULL;
413
414 static char cached_number_format[9];
415
416 static void activate(GtkApplication *theApp, gpointer userData);
417 static void menubar_resized(GtkWidget *w, GtkAllocation *allocation, gpointer data);
418 static void calc_resized(GtkWidget *w, GtkAllocation *allocation, gpointer data);
419
420 int main(int argc, char *argv[]) {
421 for (int i = 1; i < argc; i++) {
422 if (strcmp(argv[i], "-skin") == 0)
423 skin_arg = ++i < argc ? argv[i] : NULL;
424 else if (strcmp(argv[i], "-compactmenu") == 0)
425 use_compactmenu = 1;
426 else {
427 fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
428 exit(1);
429 }
430 }
431
432 GtkApplication *app;
433 int status;
•434 app = gtk_application_new(APPID, G_APPLICATION_FLAGS_NONE);
435
436 GValue gv = G_VALUE_INIT;
437 g_value_init(&gv, G_TYPE_BOOLEAN);
438 g_value_set_boolean(&gv, true);
439 g_object_set_property(G_OBJECT(app), "register-session", &gv);
440
441 g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
442 status = g_application_run(G_APPLICATION(app), 0, NULL);
443
444 // We'll only get here if the app is being shut down
445 // by the session manager. Note that the quit() call
446 // does not return.
447 quit();
448
449 g_object_unref(app);
450 return status;
451 }
452
453 static void copy_one_utf8_char(char *dst, const char *src) {
454 int n, c = *src & 255;
455 if (c == 0)
456 return;
457 else if ((c & 0x80) == 0)
458 n = 1;
459 else if ((c & 0xc0) == 0x80)
460 return;
461 else if ((c & 0xe0) == 0xc0)
462 n = 2;
463 else if ((c & 0xf0) == 0xe0)
464 n = 3;
465 else
466 return;
467 strncat(dst, src, n);
468 }
469
470 static void activate(GtkApplication *theApp, gpointer userData) {
471
472 if (app != NULL) {
473 gtk_window_present(GTK_WINDOW(mainwindow));
474 gdk_window_focus(gtk_widget_get_window(mainwindow), GDK_CURRENT_TIME);
475 return;
476 }
477
478 app = theApp;
479
480 // Capture number format, which may have been changed by
481 // gtk_init(), and then set it to the C locale, because the binary/decimal
482 // conversions expect a decimal point, not a comma.
483 struct lconv *loc = localeconv();
484 cached_number_format[0] = 0;
485 copy_one_utf8_char(cached_number_format, loc->decimal_point);
486 if (loc->thousands_sep[0] != 0) {
487 int g1 = loc->grouping[0];
488 if (g1 != 0) {
489 int g2 = loc->grouping[1];
490 if (g2 == 0)
491 g2 = g1;
492 copy_one_utf8_char(cached_number_format, loc->thousands_sep);
493 char g[2];
494 g[0] = '0' + g1;
495 g[1] = '0' + g2;
496 strncat(cached_number_format, g, 2);
497 }
498 }
499 setlocale(LC_NUMERIC, "C");
500
501
502 /*************************************************************/
503 /***** Try to create the $XDG_DATA_HOME/free42 directory *****/
504 /*************************************************************/
505
506 char *xdg_data_home = getenv("XDG_DATA_HOME");
507 char *home = getenv("HOME");
508
509 if (xdg_data_home == NULL || xdg_data_home[0] == 0)
510 snprintf(free42dirname, FILENAMELEN, "%s/.local/share/free42", home);
511 else
512 snprintf(free42dirname, FILENAMELEN, "%s/free42", xdg_data_home);
513
514 if (!file_exists(free42dirname)) {
515 // The Free42 directory does not exist yet. Before trying to do
516 // anything else, make sure the Free42 directory path starts with a slash.
517 if (free42dirname[0] != '/') {
518 fprintf(stderr, "Fatal: XDG_DATA_HOME or HOME are invalid; must start with '/'\n");
519 exit(1);
520 }
521 // If $HOME/.free42 does exist, move it to the new location.
522 char old_free42dirname[FILENAMELEN];
523 snprintf(old_free42dirname, FILENAMELEN, "%s/.free42", home);
524 bool have_old = false;
525 struct stat st;
526 if (lstat(old_free42dirname, &st) == 0) {
527 if (S_ISLNK(st.st_mode)) {
528 const char *dest;
529 if (xdg_data_home == NULL || xdg_data_home[0] == 0)
530 dest = "$HOME/.local/share/free42";
531 else
532 dest = "$XDG_DATA_HOME/free42";
533 fprintf(stderr, "$HOME/.free42 is a symlink; not moving it to %s\n", dest);
534 strcpy(free42dirname, old_free42dirname);
535 goto dir_done;
536 }
537 have_old = S_ISDIR(st.st_mode);
538 }
539 if (have_old) {
540 // Temporarily remove the "/free42" part from the end of the path,
541 // leaving the path of the parent, which we will create
542 free42dirname[strlen(free42dirname) - 7] = 0;
543 }
544 // The Free42 directory does not exist yet. Trying to create it,
545 // and all its ancestors. We're not checking for errors here, since
546 // either XDG_DATA_HOME or else HOME really should be set to
547 // something sane, and besides, trying to create the first few
548 // components of this path is *expected* to return errors, because
549 // they will already exist.
550 char *slash = free42dirname;
551 do {
552 *slash = '/';
553 char *nextSlash = strchr(slash + 1, '/');
554 if (nextSlash != NULL)
555 *nextSlash = 0;
556 mkdir(free42dirname, 0755);
557 slash = nextSlash;
558 } while (slash != NULL);
559 // Now, move the $HOME/.free42 directory, if it exists
560 if (have_old) {
561 strcat(free42dirname, "/free42");
562 if (rename(old_free42dirname, free42dirname) != 0) {
563 int err = errno;
564 const char *dest;
565 if (xdg_data_home == NULL || xdg_data_home[0] == 0)
566 dest = "$HOME/.local/share/free42";
567 else
568 dest = "$XDG_DATA_HOME/free42";
569 fprintf(stderr, "Unable to move $HOME/.free42 to %s: %s (%d)\n", dest, strerror(err), err);
570 strcpy(free42dirname, old_free42dirname);
571 goto dir_done;
572 }
573 // Create a symlink so the old directory will not appear
574 // to have just vanished without a trace.
575 // If XDG_DATA_HOME is a subdirectory of HOME, make
576 // the symlink relative.
577 int len = strlen(home);
578 if (strncmp(free42dirname, home, len) == 0 && free42dirname[len] == '/')
579 symlink(free42dirname + len + 1, old_free42dirname);
580 else
581 symlink(free42dirname, old_free42dirname);
582 }
583 }
584
585 dir_done:
586 snprintf(statefilename, FILENAMELEN, "%s/state", free42dirname);
587 snprintf(printfilename, FILENAMELEN, "%s/print", free42dirname);
588 snprintf(keymapfilename, FILENAMELEN, "%s/keymap.txt", free42dirname);
589
590 if (!file_exists(keymapfilename)) {
591 char oldkeymapfilename[FILENAMELEN];
592 strcpy(oldkeymapfilename, keymapfilename);
593 oldkeymapfilename[strlen(oldkeymapfilename) - 4] = 0;
594 if (file_exists(oldkeymapfilename))
595 rename(oldkeymapfilename, keymapfilename);
596 }
597
598
599 /****************************/
600 /***** Read the key map *****/
601 /****************************/
602
603 read_key_map(keymapfilename);
604
605
606 /***********************************************************/
607 /***** Open the state file and read the shell settings *****/
608 /***********************************************************/
609
610 int4 version;
611 int init_mode;
612 char core_state_file_name[FILENAMELEN];
613 int core_state_file_offset = 0;
614
615 statefile = fopen(statefilename, "r");
616 if (statefile != NULL) {
617 if (read_shell_state(&version)) {
618 if (skin_arg != NULL) {
619 strncpy(state.skinName, skin_arg, FILENAMELEN - 1);
620 state.skinName[FILENAMELEN - 1] = 0;
621 }
622 init_mode = 1;
623 } else {
624 init_shell_state(-1);
625 init_mode = 2;
626 }
627 } else {
628 init_shell_state(-1);
629 init_mode = 0;
630 }
631 if (init_mode == 1) {
632 if (version > 25) {
633 snprintf(core_state_file_name, FILENAMELEN, "%s/%s.f42", free42dirname, state.coreName);
634 core_state_file_offset = 0;
635 } else {
636 strcpy(core_state_file_name, statefilename);
637 core_state_file_offset = ftell(statefile);
638 }
639 fclose(statefile);
640 } else {
641 // The shell state was missing or corrupt, but there
642 // may still be a valid core state...
643 snprintf(core_state_file_name, FILENAMELEN, "%s/%s.f42", free42dirname, state.coreName);
644 if (file_exists(core_state_file_name)) {
645 // Core state "Untitled.f42" exists; let's try to read it
646 core_state_file_offset = 0;
647 init_mode = 1;
648 version = 26;
649 }
650 }
651
652 /*********************************/
653 /***** Build the main window *****/
654 /*********************************/
655
656 char *xml = (char *) malloc(10240);
657 if (use_compactmenu)
658 snprintf(xml, 10240, mainWindowXml, compactMenuIntroXml, compactMenuOutroXml);
659 else
660 snprintf(xml, 10240, mainWindowXml, "", "");
661 GtkBuilder *builder = gtk_builder_new();
662 gtk_builder_add_from_string(builder, xml, -1, NULL);
663 free(xml);
664 GObject *obj = gtk_builder_get_object(builder, "window");
665 mainwindow = GTK_WIDGET(obj);
666 gtk_window_set_application(GTK_WINDOW(mainwindow), app);
667
668 icon_128 = gdk_pixbuf_new_from_resource("/icons/icon-128x128.png", NULL);
669 icon_48 = gdk_pixbuf_new_from_resource("/icons/icon-48x48.png", NULL);
670
671 gtk_window_set_icon(GTK_WINDOW(mainwindow), icon_128);
672 gtk_window_set_title(GTK_WINDOW(mainwindow), TITLE);
673 gtk_window_set_role(GTK_WINDOW(mainwindow), "Free42 Calculator");
674 //gtk_window_set_resizable(GTK_WINDOW(mainwindow), FALSE);
675 no_mwm_zoom_box(mainwindow);
676 g_signal_connect(G_OBJECT(mainwindow), "delete_event",
677 G_CALLBACK(delete_cb), NULL);
678 if (state.mainWindowKnown)
679 gtk_window_move(GTK_WINDOW(mainwindow), state.mainWindowX,
680 state.mainWindowY);
681
682 GtkWidget *menubar = GTK_WIDGET(gtk_builder_get_object(builder, "menubar"));
683 g_signal_connect(G_OBJECT(menubar), "size-allocate", G_CALLBACK(menubar_resized), NULL);
684
685 // The "Skin" menu is dynamic; we don't populate any items in it here.
686 // Instead, we attach a callback which scans the .free42 directory for
687 // available skins; this callback is invoked when the menu is about to
688 // be mapped.
689 GtkMenuItem *item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "skin_item"));
690 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(skin_menu_update), NULL);
691
692 // With GTK 2 and GTK 3.4, the above logic worked fine, but with 3.24,
693 // it appears that the pop-up shell is laid out *before* the 'activate'
694 // callback is invoked. The result is that you do end up with the correct
695 // menu items, but they don't fit in the pop-up and so are cut off.
696 // Can't think of a proper way around this, but this at least will fix the
697 // Skin menu appearance in the most common use case, i.e. when the set of
698 // skins does not change while Free42 is running.
699 skin_menu_update(GTK_WIDGET(item));
700
701 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "states_item"));
702 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(statesCB), NULL);
703 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "show_printout_item"));
704 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(showPrintOutCB), NULL);
705 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "paper_advance_item"));
706 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(paperAdvanceCB), NULL);
707 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "import_programs_item"));
708 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(importProgramCB), NULL);
709 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "export_programs_item"));
710 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(exportProgramCB), NULL);
711 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "preferences_item"));
712 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(preferencesCB), NULL);
713 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "quit_item"));
714 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(quitCB), NULL);
715 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "copy_item"));
716 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(copyCB), NULL);
717 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "paste_item"));
718 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(pasteCB), NULL);
719 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "copy_printout_as_text_item"));
720 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(copyPrintAsTextCB), NULL);
721 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "copy_printout_as_image_item"));
722 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(copyPrintAsImageCB), NULL);
723 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "clear_printout_item"));
724 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(clearPrintOutCB), NULL);
725 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "documentation_item"));
726 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(documentationCB), NULL);
727 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "website_item"));
728 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(websiteCB), NULL);
729 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "other_website_item"));
730 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(otherWebsiteCB), NULL);
731 keyboardShortcutsMenuItem = GTK_CHECK_MENU_ITEM(gtk_builder_get_object(builder, "keyboard_shortcuts_item"));
732 g_signal_connect(G_OBJECT(keyboardShortcutsMenuItem), "activate", G_CALLBACK(keyboardShortcutsCB), NULL);
733 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "edit_keymap_item"));
734 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(editKeymapCB), NULL);
735 item = GTK_MENU_ITEM(gtk_builder_get_object(builder, "about_item"));
736 g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(aboutCB), NULL);
737
738
739 /****************************************/
740 /* Drawing area for the calculator skin */
741 /****************************************/
742
743 GtkWidget *box = GTK_WIDGET(gtk_builder_get_object(builder, "box"));
744
745 int win_width, win_height;
746 skin_load(&win_width, &win_height);
747 skin_set_window_size(win_width, win_height);
748 if (state.mainWindowWidth != 0)
749 skin_set_window_size(state.mainWindowWidth, state.mainWindowHeight);
750 GtkWidget *w = gtk_drawing_area_new();
751 gtk_box_pack_start(GTK_BOX(box), w, TRUE, TRUE, 0);
752 g_signal_connect(G_OBJECT(w), "draw", G_CALLBACK(draw_cb), NULL);
753 gtk_widget_add_events(w, GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);
754 g_signal_connect(G_OBJECT(w), "button-press-event", G_CALLBACK(button_cb), NULL);
755 g_signal_connect(G_OBJECT(w), "button-release-event", G_CALLBACK(button_cb), NULL);
756 gtk_widget_set_can_focus(w, TRUE);
757 g_signal_connect(G_OBJECT(w), "key-press-event", G_CALLBACK(key_cb), NULL);
758 g_signal_connect(G_OBJECT(w), "key-release-event", G_CALLBACK(key_cb), NULL);
759 g_signal_connect(G_OBJECT(w), "size-allocate", G_CALLBACK(calc_resized), NULL);
760 gtk_widget_set_size_request(w, 160, 160);
761 calc_widget = w;
762
763 /*
764 GdkGeometry geom;
765 geom.min_width = 160;
766 geom.min_height = 160;
767 gtk_window_set_geometry_hints(GTK_WINDOW(mainwindow), w, &geom, GdkWindowHints(GDK_HINT_MIN_SIZE));
768 */
769
770
771 /**************************************/
772 /***** Build the print-out window *****/
773 /**************************************/
774
775 // In the Motif version, I create an XImage and read the bitmap data into
776 // it; in the GTK version, that approach is not practical, since pixbuf
777 // only comes in 24-bit and 32-bit flavors -- which would mean wasting
778 // 25 megabytes for a 286x32768 pixbuf. So, instead, I use a 1 bpp buffer,
779 // and simply create pixbufs on the fly whenever I have to repaint.
780 print_bitmap = (unsigned char *) malloc(PRINT_SIZE);
781 print_text = (unsigned char *) malloc(PRINT_TEXT_SIZE);
782 // TODO - handle memory allocation failure
783
784 FILE *printfile = fopen(printfilename, "r");
785 if (printfile != NULL) {
786 int n = fread(&printout_bottom, 1, sizeof(int), printfile);
787 if (n == sizeof(int)) {
788 if (printout_bottom > PRINT_LINES) {
789 int excess = (printout_bottom - PRINT_LINES) * PRINT_BYTESPERLINE;
790 fseek(printfile, excess, SEEK_CUR);
791 printout_bottom = PRINT_LINES;
792 }
793 int bytes = printout_bottom * PRINT_BYTESPERLINE;
794 n = fread(print_bitmap, 1, bytes, printfile);
795 if (n == bytes) {
796 n = fread(&print_text_bottom, 1, sizeof(int), printfile);
797 int n2 = fread(&print_text_pixel_height, 1, sizeof(int), printfile);
798 if (n == sizeof(int) && n2 == sizeof(int)) {
799 n = fread(print_text, 1, print_text_bottom, printfile);
800 if (n != print_text_bottom) {
801 print_text_bottom = 0;
802 print_text_pixel_height = 0;
803 }
804 } else {
805 print_text_bottom = 0;
806 print_text_pixel_height = 0;
807 }
808 } else {
809 printout_bottom = 0;
810 print_text_bottom = 0;
811 print_text_pixel_height = 0;
812 }
813 } else {
814 printout_bottom = 0;
815 print_text_bottom = 0;
816 print_text_pixel_height = 0;
817 }
818 fclose(printfile);
819 } else {
820 printout_bottom = 0;
821 print_text_bottom = 0;
822 print_text_pixel_height = 0;
823 }
824 printout_top = 0;
825 print_text_top = 0;
826
827 printwindow = gtk_application_window_new(GTK_APPLICATION(app));
828 gtk_window_set_icon(GTK_WINDOW(printwindow), icon_128);
829 gtk_window_set_title(GTK_WINDOW(printwindow), "Free42 Print-Out");
830 gtk_window_set_role(GTK_WINDOW(printwindow), "Free42 Print-Out");
831 g_signal_connect(G_OBJECT(printwindow), "delete_event",
832 G_CALLBACK(delete_print_cb), NULL);
833
834 GtkWidget *scroll = gtk_scrolled_window_new(NULL, NULL);
835 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
836 gtk_container_add(GTK_CONTAINER(printwindow), scroll);
837 GtkWidget *view = gtk_viewport_new(NULL, NULL);
838 gtk_container_add(GTK_CONTAINER(scroll), view);
839 print_widget = gtk_drawing_area_new();
840 gtk_widget_set_size_request(print_widget, 358, printout_bottom);
841 gtk_container_add(GTK_CONTAINER(view), print_widget);
842 print_adj = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(scroll));
843 g_signal_connect(G_OBJECT(print_widget), "draw", G_CALLBACK(print_draw_cb), NULL);
844 gtk_widget_set_can_focus(print_widget, TRUE);
845 g_signal_connect(G_OBJECT(print_widget), "key-press-event", G_CALLBACK(print_key_cb), NULL);
846
847 gtk_widget_show(print_widget);
848 gtk_widget_show(view);
849 gtk_widget_show(scroll);
850
851 GdkGeometry geom;
852 geom.min_width = 358;
853 geom.max_width = 358;
854 geom.min_height = 18;
855 geom.max_height = 32767;
856 geom.width_inc = 1;
857 geom.height_inc = 18;
858 gtk_window_set_geometry_hints(GTK_WINDOW(printwindow), NULL, &geom, GdkWindowHints(GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE | GDK_HINT_RESIZE_INC));
859
860 if (state.printWindowKnown)
861 gtk_window_move(GTK_WINDOW(printwindow), state.printWindowX,
862 state.printWindowY);
863 gint width, height;
864 gtk_window_get_size(GTK_WINDOW(printwindow), &width, &height);
865 gtk_window_resize(GTK_WINDOW(printwindow), width,
866 state.printWindowKnown ? state.printWindowHeight : 600);
867
868 gtk_widget_realize(printwindow);
869 gtk_widget_realize(print_widget);
870 scroll_printout_to_bottom();
871
872
873 /*************************************************/
874 /***** Show main window & start the emulator *****/
875 /*************************************************/
876
877 if (state.printWindowKnown && state.printWindowMapped)
878 gtk_widget_show(printwindow);
879 gtk_widget_show_all(mainwindow);
880 gtk_widget_show(mainwindow);
881
882 core_init(init_mode, version, core_state_file_name, core_state_file_offset);
883 if (core_powercycle())
884 enable_reminder();
885
886 /* Check if /proc/apm exists and is readable, and if so,
887 * start the battery checker "thread" that keeps the battery
888 * annunciator on the calculator display up to date.
889 */
890 FILE *apm = fopen("/proc/apm", "r");
891 if (apm != NULL) {
892 fclose(apm);
893 shell_low_battery();
894 g_timeout_add(60000, battery_checker, NULL);
895 } else {
896 /* Check if /sys/class/power_supply exists */
897 DIR *d = opendir("/sys/class/power_supply");
898 if (d != NULL) {
899 closedir(d);
900 shell_low_battery();
901 g_timeout_add(60000, battery_checker, NULL);
902 }
903 }
904
905 if (pipe(pype) != 0)
906 fprintf(stderr, "Could not create pipe for signal handler; not catching signals.\n");
907 else {
908 GIOChannel *channel = g_io_channel_unix_new(pype[0]);
909 GError *err = NULL;
910 g_io_channel_set_encoding(channel, NULL, &err);
911 g_io_channel_set_flags(channel,
912 (GIOFlags) (g_io_channel_get_flags(channel) | G_IO_FLAG_NONBLOCK), &err);
913 g_io_add_watch(channel, G_IO_IN, gt_signal_handler, NULL);
914
915 struct sigaction act;
916 act.sa_handler = int_term_handler;
917 sigemptyset(&act.sa_mask);
918 sigaddset(&act.sa_mask, SIGINT);
919 sigaddset(&act.sa_mask, SIGTERM);
920 act.sa_flags = 0;
921 sigaction(SIGINT, &act, NULL);
922 sigaction(SIGTERM, &act, NULL);
923 }
924 }
925
926 static void menubar_resized(GtkWidget *w, GtkAllocation *allocation, gpointer data) {
927 if (menu_bar_height == allocation->height)
928 return;
929 menu_bar_height = allocation->height;
930 int win_width, win_height;
931 skin_get_window_size(&win_width, &win_height);
932 int mh = menu_bar_height >= 2 ? menu_bar_height : 0;
933 gtk_window_resize(GTK_WINDOW(mainwindow), win_width, win_height + mh);
934 }
935
936 static gboolean resizer(gpointer cd) {
937 int win_width, win_height;
938 skin_get_window_size(&win_width, &win_height);
939 int mh = menu_bar_height >= 2 ? menu_bar_height : 0;
940 gtk_window_resize(GTK_WINDOW(mainwindow), win_width, win_height + mh);
941 resize_timeout_id = 0;
942 return FALSE;
943 }
944
945 static void calc_resized(GtkWidget *w, GtkAllocation *allocation, gpointer data) {
946 int skin_width, skin_height;
947 skin_get_size(&skin_width, &skin_height);
948 int win_width = allocation->width;
949 int win_height = allocation->height;
950 double hScale = ((double) win_width) / skin_width;
951 double vScale = ((double) win_height) / skin_height;
952 if (hScale > vScale)
953 win_width = (int) (skin_width * vScale + 0.5);
954 else if (vScale > hScale)
955 win_height = (int) (skin_height * hScale + 0.5);
956 skin_set_window_size(win_width, win_height);
957 if (resize_timeout_id != 0)
958 g_source_remove(resize_timeout_id);
959 resize_timeout_id = g_timeout_add(250, resizer, NULL);
960 }
961
962 keymap_entry *parse_keymap_entry(char *line, int lineno) {
963 char *p;
964 static keymap_entry entry;
965
966 p = strchr(line, '#');
967 if (p != NULL)
968 *p = 0;
969 p = strchr(line, '\n');
970 if (p != NULL)
971 *p = 0;
972 p = strchr(line, '\r');
973 if (p != NULL)
974 *p = 0;
975
976 p = strchr(line, ':');
977 if (p != NULL) {
978 char *val = p + 1;
979 char *tok;
980 bool ctrl = false;
981 bool alt = false;
982 bool shift = false;
983 bool cshift = false;
984 guint keyval = GDK_KEY_VoidSymbol;
985 bool done = false;
986 unsigned char macrobuf[KEYMAP_MAX_MACRO_LENGTH + 1];
987 int macrolen = 0;
988
989 /* Parse keysym */
990 *p = 0;
991 tok = strtok(line, " \t");
992 while (tok != NULL) {
993 if (done) {
994 fprintf(stderr, "Keymap, line %d: Excess tokens in key spec.\n", lineno);
995 return NULL;
996 }
997 if (strcasecmp(tok, "ctrl") == 0)
998 ctrl = true;
999 else if (strcasecmp(tok, "alt") == 0)
1000 alt = true;
1001 else if (strcasecmp(tok, "shift") == 0)
1002 shift = true;
1003 else if (strcasecmp(tok, "cshift") == 0)
1004 cshift = true;
1005 else {
1006 keyval = gdk_keyval_from_name(tok);
1007 if (keyval == GDK_KEY_VoidSymbol) {
1008 fprintf(stderr, "Keymap, line %d: Unrecognized KeyName.\n", lineno);
1009 return NULL;
1010 }
1011 done = true;
1012 }
1013 tok = strtok(NULL, " \t");
1014 }
1015 if (!done) {
1016 fprintf(stderr, "Keymap, line %d: Unrecognized KeyName.\n", lineno);
1017 return NULL;
1018 }
1019
1020 /* Parse macro */
1021 tok = strtok(val, " \t");
1022 while (tok != NULL) {
1023 char *endptr;
1024 long k = strtol(tok, &endptr, 10);
1025 if (*endptr != 0 || k < 1 || k > 255) {
1026 fprintf(stderr, "Keymap, line %d: Bad value (%s) in macro.\n", lineno, tok);
1027 return NULL;
1028 } else if (macrolen == KEYMAP_MAX_MACRO_LENGTH) {
1029 fprintf(stderr, "Keymap, line %d: Macro too long (max=%d).\n", lineno, KEYMAP_MAX_MACRO_LENGTH);
1030 return NULL;
1031 } else
1032 macrobuf[macrolen++] = k;
1033 tok = strtok(NULL, " \t");
1034 }
1035 macrobuf[macrolen] = 0;
1036
1037 entry.ctrl = ctrl;
1038 entry.alt = alt;
1039 entry.shift = shift;
1040 entry.cshift = cshift;
1041 entry.keyval = keyval;
1042 strcpy((char *) entry.macro, (const char *) macrobuf);
1043 return &entry;
1044 } else
1045 return NULL;
1046 }
1047
1048 static void read_key_map(const char *keymapfilename) {
1049 FILE *keymapfile = fopen(keymapfilename, "r");
1050 int kmcap = 0;
1051 char line[1024];
1052 int lineno = 0;
1053
1054 if (keymapfile == NULL) {
1055 /* Try to create default keymap file */
1056 extern const long keymap_filesize;
1057 extern const char keymap_filedata[];
1058 long n;
1059
1060 keymapfile = fopen(keymapfilename, "wb");
1061 if (keymapfile == NULL)
1062 return;
1063 n = fwrite(keymap_filedata, 1, keymap_filesize, keymapfile);
1064 if (n != keymap_filesize) {
1065 int err = errno;
1066 fprintf(stderr, "Error writing \"%s\": %s (%d)\n",
1067 keymapfilename, strerror(err), err);
1068 }
1069 fclose(keymapfile);
1070
1071 keymapfile = fopen(keymapfilename, "r");
1072 if (keymapfile == NULL)
1073 return;
1074 }
1075
1076 while (fgets(line, 1024, keymapfile) != NULL) {
1077 keymap_entry *entry = parse_keymap_entry(line, ++lineno);
1078 if (entry == NULL)
1079 continue;
1080 /* Create new keymap entry */
1081 if (keymap_length == kmcap) {
1082 kmcap += 50;
1083 keymap = (keymap_entry *) realloc(keymap, kmcap * sizeof(keymap_entry));
1084 // TODO - handle memory allocation failure
1085 }
1086 memcpy(keymap + (keymap_length++), entry, sizeof(keymap_entry));
1087 }
1088
1089 fclose(keymapfile);
1090 }
1091
1092 static void init_shell_state(int4 version) {
1093 switch (version) {
1094 case -1:
1095 state.extras = 0;
1096 /* fall through */
1097 case 0:
1098 state.printerToTxtFile = 0;
1099 state.printerToGifFile = 0;
1100 state.printerTxtFileName[0] = 0;
1101 state.printerGifFileName[0] = 0;
1102 state.printerGifMaxLength = 256;
1103 /* fall through */
1104 case 1:
1105 state.mainWindowKnown = 0;
1106 state.printWindowKnown = 0;
1107 /* fall through */
1108 case 2:
1109 state.skinName[0] = 0;
1110 /* fall through */
1111 case 3:
1112 state.singleInstance = 1;
1113 /* fall through */
1114 case 4:
1115 strcpy(state.coreName, "Untitled");
1116 /* fall through */
1117 case 5:
1118 core_settings.matrix_singularmatrix = false;
1119 core_settings.matrix_outofrange = false;
1120 core_settings.auto_repeat = true;
1121 /* fall through */
1122 case 6:
1123 state.old_repaint = true;
1124 /* fall through */
1125 case 7:
1126 core_settings.allow_big_stack = false;
1127 /* fall through */
1128 case 8:
1129 /* fall through */
1130 case 9:
1131 core_settings.localized_copy_paste = true;
1132 /* fall through */
1133 case 10:
1134 state.mainWindowWidth = 0;
1135 state.mainWindowHeight = 0;
1136 // fall through
1137 case 11:
1138 /* current version (SHELL_VERSION = 11),
1139 * so nothing to do here since everything
1140 * was initialized from the state file.
1141 */
1142 ;
1143 }
1144 }
1145
1146 static int read_shell_state(int4 *ver) {
1147 int4 magic;
1148 int4 version;
1149 int4 state_size;
1150 int4 state_version;
1151
1152 if (fread(&magic, 1, sizeof(int4), statefile) != sizeof(int4))
1153 return 0;
1154 if (magic != FREE42_MAGIC)
1155 return 0;
1156
1157 if (fread(&version, 1, sizeof(int4), statefile) != sizeof(int4))
1158 return 0;
1159 if (version == 0) {
1160 /* State file version 0 does not contain shell state,
1161 * only core state, so we just hard-init the shell.
1162 */
1163 init_shell_state(-1);
1164 *ver = version;
1165 return 1;
1166 }
1167
1168 if (fread(&state_size, 1, sizeof(int4), statefile) != sizeof(int4))
1169 return 0;
1170 if (fread(&state_version, 1, sizeof(int4), statefile) != sizeof(int4))
1171 return 0;
1172 if (state_version < 0 || state_version > SHELL_VERSION)
1173 /* Unknown shell state version */
1174 return 0;
1175 if (fread(&state, 1, state_size, statefile) != (size_t) state_size)
1176 return 0;
1177 if (state_version >= 6) {
1178 core_settings.matrix_singularmatrix = state.matrix_singularmatrix;
1179 core_settings.matrix_outofrange = state.matrix_outofrange;
1180 core_settings.auto_repeat = state.auto_repeat;
1181 }
1182 if (state_version >= 7)
1183 core_settings.allow_big_stack = state.allow_big_stack;
1184 if (state_version >= 10)
1185 core_settings.localized_copy_paste = state.localized_copy_paste;
1186
1187 init_shell_state(state_version);
1188 *ver = version;
1189 return 1;
1190 }
1191
1192 static int write_shell_state() {
1193 int4 magic = FREE42_MAGIC;
1194 int4 version = 27;
1195 int4 state_size = sizeof(state_type);
1196 int4 state_version = SHELL_VERSION;
1197
1198 if (fwrite(&magic, 1, sizeof(int4), statefile) != sizeof(int4))
1199 return 0;
1200 if (fwrite(&version, 1, sizeof(int4), statefile) != sizeof(int4))
1201 return 0;
1202 if (fwrite(&state_size, 1, sizeof(int4), statefile) != sizeof(int4))
1203 return 0;
1204 if (fwrite(&state_version, 1, sizeof(int4), statefile) != sizeof(int4))
1205 return 0;
1206 state.matrix_singularmatrix = core_settings.matrix_singularmatrix;
1207 state.matrix_outofrange = core_settings.matrix_outofrange;
1208 state.auto_repeat = core_settings.auto_repeat;
1209 state.allow_big_stack = core_settings.allow_big_stack;
1210 state.localized_copy_paste = core_settings.localized_copy_paste;
1211 if (fwrite(&state, 1, sizeof(state_type), statefile) != sizeof(state_type))
1212 return 0;
1213
1214 return 1;
1215 }
1216
1217 static void int_term_handler(int sig) {
1218 write(pype[1], "1\n", 2);
1219 }
1220
1221 static gboolean gt_signal_handler(GIOChannel *source, GIOCondition condition,
1222 gpointer data) {
1223 quit();
1224 return TRUE;
1225 }
1226
1227 static void quit() {
1228 FILE *printfile;
1229 int n, length;
1230
1231 printfile = fopen(printfilename, "w");
1232 if (printfile != NULL) {
1233 // Write bitmap
1234 length = printout_bottom - printout_top;
1235 if (length < 0)
1236 length += PRINT_LINES;
1237 n = fwrite(&length, 1, sizeof(int), printfile);
1238 if (n != sizeof(int))
1239 goto failed;
1240 if (printout_bottom >= printout_top) {
1241 n = fwrite(print_bitmap + PRINT_BYTESPERLINE * printout_top,
1242 1, PRINT_BYTESPERLINE * length, printfile);
1243 if (n != PRINT_BYTESPERLINE * length)
1244 goto failed;
1245 } else {
1246 n = fwrite(print_bitmap + PRINT_BYTESPERLINE * printout_top,
1247 1, PRINT_SIZE - PRINT_BYTESPERLINE * printout_top,
1248 printfile);
1249 if (n != PRINT_SIZE - PRINT_BYTESPERLINE * printout_top)
1250 goto failed;
1251 n = fwrite(print_bitmap, 1,
1252 PRINT_BYTESPERLINE * printout_bottom, printfile);
1253 if (n != PRINT_BYTESPERLINE * printout_bottom)
1254 goto failed;
1255 }
1256 // Write text
1257 length = print_text_bottom - print_text_top;
1258 if (length < 0)
1259 length += PRINT_TEXT_SIZE;
1260 n = fwrite(&length, 1, sizeof(int), printfile);
1261 if (n != sizeof(int))
1262 goto failed;
1263 n = fwrite(&print_text_pixel_height, 1, sizeof(int), printfile);
1264 if (n != sizeof(int))
1265 goto failed;
1266 if (print_text_bottom >= print_text_top) {
1267 n = fwrite(print_text + print_text_top, 1, length, printfile);
1268 if (n != length)
1269 goto failed;
1270 } else {
1271 n = fwrite(print_text + print_text_top, 1, PRINT_TEXT_SIZE - print_text_top, printfile);
1272 if (n != PRINT_TEXT_SIZE - print_text_top)
1273 goto failed;
1274 n = fwrite(print_text, 1, print_text_bottom, printfile);
1275 if (n != print_text_bottom)
1276 goto failed;
1277 }
1278
1279 fclose(printfile);
1280 goto done;
1281
1282 failed:
1283 fclose(printfile);
1284 remove(printfilename);
1285
1286 done:
1287 ;
1288 }
1289
1290 if (print_txt != NULL)
1291 fclose(print_txt);
1292
1293 if (print_gif != NULL) {
1294 shell_finish_gif(gif_seeker, gif_writer);
1295 fclose(print_gif);
1296 }
1297
1298 gint x, y;
1299 gtk_window_get_position(GTK_WINDOW(mainwindow), &x, &y);
1300 state.mainWindowKnown = 1;
1301 state.mainWindowX = x;
1302 state.mainWindowY = y;
1303 int w, h;
1304 skin_get_window_size(&w, &h);
1305 state.mainWindowWidth = w;
1306 state.mainWindowHeight = h;
1307
1308 if (state.printWindowMapped) {
1309 gtk_window_get_position(GTK_WINDOW(printwindow), &x, &y);
1310 state.printWindowX = x;
1311 state.printWindowY = y;
1312 }
1313 if (state.printWindowKnown) {
1314 gtk_window_get_size(GTK_WINDOW(printwindow), &x, &y);
1315 state.printWindowHeight = y;
1316 }
1317
1318 statefile = fopen(statefilename, "w");
1319 if (statefile != NULL) {
1320 write_shell_state();
1321 fclose(statefile);
1322 }
1323 char corefilename[FILENAMELEN];
1324 snprintf(corefilename, FILENAMELEN, "%s/%s.f42", free42dirname, state.coreName);
1325 core_save_state(corefilename);
1326 core_cleanup();
1327
1328 shell_spool_exit();
1329
1330 exit(0);
1331 }
1332
1333 static char *strclone(const char *s) {
1334 char *s2 = (char *) malloc(strlen(s) + 1);
1335 if (s2 != NULL)
1336 strcpy(s2, s);
1337 return s2;
1338 }
1339
1340 static bool file_exists(const char *name) {
1341 struct stat st;
1342 return stat(name, &st) == 0;
1343 }
1344
1345 static void show_message(const char *title, const char *message, GtkWidget *parent) {
1346 GtkWidget *msg = gtk_message_dialog_new(GTK_WINDOW(parent),
1347 GTK_DIALOG_MODAL,
1348 GTK_MESSAGE_ERROR,
1349 GTK_BUTTONS_OK,
1350 "%s",
1351 message);
1352 gtk_window_set_title(GTK_WINDOW(msg), title);
1353 gtk_window_set_role(GTK_WINDOW(msg), "Free42 Dialog");
1354 gtk_dialog_run(GTK_DIALOG(msg));
1355 gtk_widget_destroy(msg);
1356 }
1357
1358 static void no_mwm_resize_helper(GtkWidget *w, gpointer cd) {
1359 GdkWindow *win = gtk_widget_get_window(w);
1360 gdk_window_set_decorations(win, GdkWMDecoration(GDK_DECOR_ALL
1361 | GDK_DECOR_RESIZEH | GDK_DECOR_MAXIMIZE));
1362 gdk_window_set_functions(win, GdkWMFunction(GDK_FUNC_ALL
1363 | GDK_FUNC_RESIZE | GDK_FUNC_MAXIMIZE));
1364 }
1365
1366 static void no_mwm_resize_borders(GtkWidget *window) {
1367 // gtk_window_set_resizable(w, FALSE) only sets the WM size hints, so that
1368 // the minimum and maximum sizes coincide with the actual size. While this
1369 // certainly has the desired effect of making the window non-resizable, it
1370 // does not deal with the way mwm visually distinguishes resizable and
1371 // non-resizable windows; the result is that, when running under mwm, you
1372 // have a window with resize borders and a maximize button, none of which
1373 // actually let you resize the window.
1374 // So, we use an additional GDK call to set the appropriate mwm properties.
1375 g_signal_connect(G_OBJECT(window), "realize",
1376 G_CALLBACK(no_mwm_resize_helper), NULL);
1377 }
1378
1379 static void no_mwm_zoom_helper(GtkWidget *w, gpointer cd) {
1380 GdkWindow *win = gtk_widget_get_window(w);
1381 gdk_window_set_decorations(win, GdkWMDecoration(GDK_DECOR_ALL
1382 | GDK_DECOR_MAXIMIZE));
1383 gdk_window_set_functions(win, GdkWMFunction(GDK_FUNC_ALL
1384 | GDK_FUNC_MAXIMIZE));
1385 }
1386
1387 static void no_mwm_zoom_box(GtkWidget *window) {
1388 g_signal_connect(G_OBJECT(window), "realize",
1389 G_CALLBACK(no_mwm_zoom_helper), NULL);
1390 }
1391
1392 static void scroll_printout_to_bottom() {
1393 gdouble upper = gtk_adjustment_get_upper(print_adj);
1394 gdouble page_size = gtk_adjustment_get_page_size(print_adj);
1395 gtk_adjustment_set_value(print_adj, upper - page_size);
1396 }
1397
1398 static void quitCB() {
1399 quit();
1400 }
1401
1402 ////////////////////////////////////
1403 ///// States stuff starts here /////
1404 ////////////////////////////////////
1405
1406 static int currentStateIndex;
1407 static int selectedStateIndex;
1408 static char **state_names;
1409 static GtkWidget *statesMenuItems[6];
1410
1411 static void states_changed_cb(GtkWidget *w, gpointer p) {
1412 selectedStateIndex = -1;
1413 GList *rows = gtk_tree_selection_get_selected_rows(GTK_TREE_SELECTION(w), NULL);
1414 if (rows != NULL) {
1415 GtkTreePath *path = (GtkTreePath *) rows->data;
1416 sscanf(gtk_tree_path_to_string(path), "%d", &selectedStateIndex);
1417 }
1418 g_list_free(rows);
1419 GtkWidget *btn = (GtkWidget *) p;
1420 if (selectedStateIndex == -1) {
1421 gtk_widget_set_sensitive(btn, false);
1422 gtk_button_set_label(GTK_BUTTON(btn), "Switch To");
1423 gtk_widget_set_sensitive(statesMenuItems[1], false);
1424 gtk_widget_set_sensitive(statesMenuItems[2], false);
1425 gtk_widget_set_sensitive(statesMenuItems[3], false);
1426 gtk_widget_set_sensitive(statesMenuItems[5], false);
1427 } else if (selectedStateIndex == currentStateIndex) {
1428 gtk_widget_set_sensitive(btn, true);
1429 gtk_button_set_label(GTK_BUTTON(btn), "Revert");
1430 gtk_widget_set_sensitive(statesMenuItems[1], true);
1431 gtk_widget_set_sensitive(statesMenuItems[2], true);
1432 gtk_widget_set_sensitive(statesMenuItems[3], false);
1433 gtk_widget_set_sensitive(statesMenuItems[5], true);
1434 } else {
1435 gtk_widget_set_sensitive(btn, true);
1436 gtk_button_set_label(GTK_BUTTON(btn), "Switch To");
1437 gtk_widget_set_sensitive(statesMenuItems[1], true);
1438 gtk_widget_set_sensitive(statesMenuItems[2], true);
1439 gtk_widget_set_sensitive(statesMenuItems[3], true);
1440 gtk_widget_set_sensitive(statesMenuItems[5], true);
1441 }
1442 }
1443
1444 static GtkWidget *dlg;
1445
1446 static char *get_state_name(const char *prompt, const char *initialName) {
1447 static GtkWidget *state_name_dialog = NULL;
1448 static GtkWidget *promptLabel;
1449 static GtkWidget *name;
1450
1451 if (state_name_dialog == NULL) {
1452 state_name_dialog = gtk_dialog_new_with_buttons(
1453 "State Name",
1454 GTK_WINDOW(dlg),
1455 GTK_DIALOG_MODAL,
1456 "_OK", GTK_RESPONSE_ACCEPT,
1457 "_Cancel", GTK_RESPONSE_CANCEL,
1458 NULL);
1459 gtk_window_set_resizable(GTK_WINDOW(state_name_dialog), FALSE);
1460 no_mwm_resize_borders(state_name_dialog);
1461 GtkWidget *container = gtk_bin_get_child(GTK_BIN(state_name_dialog));
1462 GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
1463 gtk_container_add(GTK_CONTAINER(container), box);
1464
1465 promptLabel = gtk_label_new("Enter state name:");
1466 gtk_box_pack_start(GTK_BOX(box), promptLabel, FALSE, FALSE, 10);
1467
1468 name = gtk_entry_new();
1469 gtk_box_pack_start(GTK_BOX(box), name, FALSE, FALSE, 10);
1470
1471 gtk_widget_show_all(state_name_dialog);
1472 }
1473
1474 gtk_window_set_role(GTK_WINDOW(state_name_dialog), "Free42 Dialog");
1475 gtk_label_set_text(GTK_LABEL(promptLabel), prompt);
1476 gtk_entry_set_text(GTK_ENTRY(name), initialName);
1477 gtk_editable_select_region(GTK_EDITABLE(name), 0, -1);
1478
1479 char *result = NULL;
1480 while (true) {
1481 gtk_window_set_focus(GTK_WINDOW(state_name_dialog), name);
1482 gtk_widget_grab_focus(GTK_WIDGET(name));
1483 int response = gtk_dialog_run(GTK_DIALOG(state_name_dialog));
1484 if (response == GTK_RESPONSE_ACCEPT) {
1485 const char *tmp = gtk_entry_get_text(GTK_ENTRY(name));
1486 if (strchr(tmp, '/') != NULL) {
1487 show_message("Message", "That name is not valid.", state_name_dialog);
1488 continue;
1489 }
1490 char path[FILENAMELEN];
1491 snprintf(path, FILENAMELEN, "%s/%s.f42", free42dirname, tmp);
1492 if (file_exists(path)) {
1493 show_message("Message", "That name is already in use.", state_name_dialog);
1494 continue;
1495 }
1496 result = (char *) malloc(strlen(tmp) + 1);
1497 strcpy(result, tmp);
1498 }
1499 break;
1500 }
1501
1502 gtk_widget_hide(state_name_dialog);
1503 return result;
1504 }
1505
1506 static bool switchTo(const char *selectedStateName) {
1507 char path[FILENAMELEN];
1508 if (strcmp(selectedStateName, state.coreName) == 0) {
1509 GtkWidget *msg = gtk_message_dialog_new(GTK_WINDOW(dlg),
1510 GTK_DIALOG_MODAL,
1511 GTK_MESSAGE_QUESTION,
1512 GTK_BUTTONS_YES_NO,
1513 "Are you sure you want to revert the state \"%s\" to the last version saved?",
1514 selectedStateName);
1515 gtk_window_set_title(GTK_WINDOW(msg), "Revert State?");
1516 gtk_window_set_role(GTK_WINDOW(msg), "Free42 Dialog");
1517 bool cancelled = gtk_dialog_run(GTK_DIALOG(msg)) != GTK_RESPONSE_YES;
1518 gtk_widget_destroy(msg);
1519 if (cancelled)
1520 return false;
1521 } else {
1522 snprintf(path, FILENAMELEN, "%s/%s.f42", free42dirname, state.coreName);
1523 core_save_state(path);
1524 }
1525 core_cleanup();
1526 strncpy(state.coreName, selectedStateName, FILENAMELEN);
1527 state.coreName[FILENAMELEN - 1] = 0;
1528 snprintf(path, FILENAMELEN, "%s/%s.f42", free42dirname, state.coreName);
1529 core_init(1, 26, path, 0);
1530 if (core_powercycle())
1531 enable_reminder();
1532 return true;
1533 }
1534
1535 static void states_menu_new() {
1536 char *name = get_state_name("New state name:", "");
1537 if (name == NULL)
1538 return;
1539 char path[FILENAMELEN];
1540 snprintf(path, FILENAMELEN, "%s/%s.f42", free42dirname, name);
1541 FILE *f = fopen(path, "w");
1542 fprintf(f, FREE42_MAGIC_STR);
1543 fclose(f);
1544 free(name);
1545 gtk_dialog_response(GTK_DIALOG(dlg), 4);
1546 }
1547
1548 static bool copy_state(const char *orig_name, const char *copy_name) {
1549 FILE *fin = fopen(orig_name, "r");
1550 FILE *fout = fopen(copy_name, "w");
1551 if (fin != NULL && fout != NULL) {
1552 char buf[1024];
1553 int n;
1554 while ((n = fread(buf, 1, 1024, fin)) > 0)
1555 fwrite(buf, 1, n, fout);
1556 if (ferror(fin) || ferror(fout))
1557 goto duplication_failed;
1558 fclose(fin);
1559 fclose(fout);
1560 return true;
1561 } else {
1562 duplication_failed:
1563 if (fin != NULL)
1564 fclose(fin);
1565 if (fout != NULL)
1566 fclose(fout);
1567 remove(copy_name);
1568 return false;
1569 }
1570 }
1571
1572 static void states_menu_duplicate() {
1573 if (selectedStateIndex == -1)
1574 return;
1575 char copyName[FILENAMELEN];
1576 strcpy(copyName, state_names[selectedStateIndex]);
1577 int n = 0;
1578
1579 // We're naming duplicates by appending " copy" or " copy NNN" to the name
1580 // of the original, but if the name of the original already ends with " copy"
1581 // or " copy NNN", it seems more elegant to continue the sequence rather than
1582 // add another " copy" suffix.
1583 int len = strlen(copyName);
1584 if (len > 5 && strcmp(copyName + len - 5, " copy") == 0) {
1585 copyName[len - 5] = 0;
1586 n = 1;
1587 } else if (len > 7) {
1588 int pos = len - 7;
1589 int m = 0;
1590 int p = 1;
1591 while (pos > 0) {
1592 char c = copyName[pos + 6];
1593 if (c < '0' || c > '9')
1594 goto not_a_copy;
1595 m += p * (c - '0');
1596 p *= 10;
1597 if (strncmp(copyName + pos, " copy ", 6) == 0) {
1598 n = m;
1599 copyName[pos] = 0;
1600 break;
1601 } else
1602 pos--;
1603 }
1604 not_a_copy:;
1605 }
1606
1607 char finalName[FILENAMELEN];
1608 int flen;
1609 while (true) {
1610 n++;
1611 if (n == 1)
1612 flen = snprintf(finalName, FILENAMELEN, "%s/%s copy.f42", free42dirname, copyName);
1613 else
1614 flen = snprintf(finalName, FILENAMELEN, "%s/%s copy %d.f42", free42dirname, copyName, n);
1615 if (flen >= FILENAMELEN) {
1616 show_message("Message", "The name of that state is too long to copy.", dlg);
1617 return;
1618 }
1619 if (!file_exists(finalName))
1620 // File does not exist; that means we have a usable name
1621 break;
1622 }
1623
1624 // Once we get here, finalName contains a valid name for creating the duplicate.
1625 // What we do next depends on whether the selected state is the currently active
1626 // one. If it is, we'll call core_save_state(), to make sure the duplicate
1627 // actually matches the most up-to-date state; otherwise, we can simply copy
1628 // the existing state file.
1629 if (strcmp(state_names[selectedStateIndex], state.coreName) == 0)
1630 core_save_state(finalName);
1631 else {
1632 char origName[FILENAMELEN];
1633 snprintf(origName, FILENAMELEN, "%s/%s.f42", free42dirname, state_names[selectedStateIndex]);
1634 if (!copy_state(origName, finalName)) {
1635 show_message("Message", "State duplication failed.", dlg);
1636 return;
1637 }
1638 }
1639 gtk_dialog_response(GTK_DIALOG(dlg), 4);
1640 }
1641
1642 static void states_menu_rename() {
1643 if (selectedStateIndex == -1)
1644 return;
1645 char prompt[FILENAMELEN];
1646 snprintf(prompt, FILENAMELEN, "Rename \"%s\" to:", state_names[selectedStateIndex]);
1647 char *newname = get_state_name(prompt, state_names[selectedStateIndex]);
1648 if (newname == NULL)
1649 return;
1650 char oldpath[FILENAMELEN];
1651 snprintf(oldpath, FILENAMELEN, "%s/%s.f42", free42dirname, state_names[selectedStateIndex]);
1652 char newpath[FILENAMELEN];
1653 snprintf(newpath, FILENAMELEN, "%s/%s.f42", free42dirname, newname);
1654 rename(oldpath, newpath);
1655 if (strcmp(state_names[selectedStateIndex], state.coreName) == 0)
1656 strncpy(state.coreName, newname, FILENAMELEN);
1657 gtk_dialog_response(GTK_DIALOG(dlg), 4);
1658 }
1659
1660 static void states_menu_delete() {
1661 if (selectedStateIndex == -1)
1662 return;
1663 const char *stateName = state_names[selectedStateIndex];
1664 if (strcmp(stateName, state.coreName) == 0)
1665 return;
1666 GtkWidget *msg = gtk_message_dialog_new(GTK_WINDOW(dlg),
1667 GTK_DIALOG_MODAL,
1668 GTK_MESSAGE_QUESTION,
1669 GTK_BUTTONS_YES_NO,
1670 "Are you sure you want to delete the state \"%s\"?",
1671 stateName);
1672 gtk_window_set_title(GTK_WINDOW(msg), "Delete State?");
1673 gtk_window_set_role(GTK_WINDOW(msg), "Free42 Dialog");
1674 bool cancelled = gtk_dialog_run(GTK_DIALOG(msg)) != GTK_RESPONSE_YES;
1675 gtk_widget_destroy(msg);
1676 if (cancelled)
1677 return;
1678 char statePath[FILENAMELEN];
1679 snprintf(statePath, FILENAMELEN, "%s/%s.f42", free42dirname, stateName);
1680 remove(statePath);
1681 gtk_dialog_response(GTK_DIALOG(dlg), 4);
1682 }
1683
1684 static void states_menu_import() {
1685 static GtkWidget *dialog = NULL;
1686
1687 if (dialog == NULL)
1688 dialog = make_file_select_dialog("Import State",
1689 "Free42 State (*.f42)\0*.[Ff]42\0All Files (*.*)\0*\0",
1690 false, dlg);
1691
1692 gtk_window_set_role(GTK_WINDOW(dialog), "Free42 Dialog");
1693 bool cancelled = gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT;
1694 gtk_widget_hide(dialog);
1695 if (cancelled)
1696 return;
1697
1698 char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
1699 if (filename == NULL)
1700 return;
1701
1702 char name[FILENAMELEN];
1703 char *p = strrchr(filename, '/');
1704 if (p == NULL)
1705 strncpy(name, filename, FILENAMELEN);
1706 else
1707 strncpy(name, p + 1, FILENAMELEN);
1708 name[FILENAMELEN - 1] = 0;
1709 int len = strlen(name);
1710 if (len > 4 && strcmp(name + len - 4, ".f42") == 0)
1711 name[len - 4] = 0;
1712 char destPath[FILENAMELEN];
1713 snprintf(destPath, FILENAMELEN, "%s/%s.f42", free42dirname, name);
1714 bool success = false;
1715 if (file_exists(destPath)) {
1716 char msg[FILENAMELEN];
1717 snprintf(msg, FILENAMELEN, "A state named \"%s\" already exists.", name);
1718 show_message("Message", msg, dlg);
1719 } else if (!copy_state(filename, destPath)) {
1720 show_message("Message", "State import failed.", dlg);
1721 } else {
1722 success = true;
1723 }
1724 g_free(filename);
1725 if (success)
1726 gtk_dialog_response(GTK_DIALOG(dlg), 4);
1727 }
1728
1729 static void states_menu_export() {
1730 if (selectedStateIndex == -1)
1731 return;
1732
1733 static GtkWidget *save_dialog = NULL;
1734 if (save_dialog == NULL)
1735 save_dialog = make_file_select_dialog("Export State",
1736 "Free42 State (*.f42)\0*.[Ff]42\0All Files (*.*)\0*\0",
1737 true, dlg);
1738
1739 char *filename = NULL;
1740 gtk_window_set_role(GTK_WINDOW(save_dialog), "Free42 Dialog");
1741 char export_file_name[FILENAMELEN];
1742 strcpy(export_file_name, state_names[selectedStateIndex]);
1743 export_file_name[FILENAMELEN - 5] = 0;
1744 strcat(export_file_name, ".f42");
1745 gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(save_dialog), export_file_name);
1746 if (gtk_dialog_run(GTK_DIALOG(save_dialog)) == GTK_RESPONSE_ACCEPT)
1747 filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(save_dialog));
1748 gtk_widget_hide(GTK_WIDGET(save_dialog));
1749 if (filename == NULL)
1750 return;
1751
1752 strcpy(export_file_name, filename);
1753 g_free(filename);
1754 if (strncmp(gtk_file_filter_get_name(
1755 gtk_file_chooser_get_filter(
1756 GTK_FILE_CHOOSER(save_dialog))), "All", 3) != 0)
1757 appendSuffix(export_file_name, ".f42");
1758
1759 if (file_exists(export_file_name)) {
1760 GtkWidget *msg = gtk_message_dialog_new(GTK_WINDOW(mainwindow),
1761 GTK_DIALOG_MODAL,
1762 GTK_MESSAGE_QUESTION,
1763 GTK_BUTTONS_YES_NO,
1764 "Replace existing \"%s\"?",
1765 export_file_name);
1766 gtk_window_set_title(GTK_WINDOW(msg), "Replace?");
1767 gtk_window_set_role(GTK_WINDOW(msg), "Free42 Dialog");
1768 bool cancelled = gtk_dialog_run(GTK_DIALOG(msg)) != GTK_RESPONSE_YES;
1769 gtk_widget_destroy(msg);
1770 if (cancelled)
1771 return;
1772 }
1773
1774 if (selectedStateIndex == currentStateIndex)
1775 core_save_state(export_file_name);
1776 else {
1777 char orig_path[FILENAMELEN];
1778 snprintf(orig_path, FILENAMELEN, "%s/%s.f42", free42dirname, state_names[selectedStateIndex]);
1779 if (!copy_state(orig_path, export_file_name))
1780 show_message("Message", "State export failed.", dlg);
1781 }
1782 }
1783
1784 static void states_menu_cb(GtkWidget *w, gpointer p) {
1785 switch ((size_t) p) {
1786 case 0:
1787 states_menu_new();
1788 break;
1789 case 1:
1790 states_menu_duplicate();
1791 break;
1792 case 2:
1793 states_menu_rename();
1794 break;
1795 case 3:
1796 states_menu_delete();
1797 break;
1798 case 4:
1799 states_menu_import();
1800 break;
1801 case 5:
1802 states_menu_export();
1803 break;
1804 }
1805 }
1806
1807 static int case_insens_comparator(const void *a, const void *b) {
1808 return strcasecmp(*(const char **) a, *(const char **) b);
1809 }
1810
1811 static void row_activated_cb(GtkWidget *w, gpointer p) {
1812 gtk_dialog_response(GTK_DIALOG(dlg), 1);
1813 }
1814
1815 static void states_menu_pos_func(GtkMenu *menu, gint *x, gint *y, gboolean *push_in, gpointer data) {
1816 GtkWidget *btn = GTK_WIDGET(data);
1817 gdk_window_get_origin(gtk_widget_get_window(btn), x, y);
1818 GtkAllocation allocation;
1819 gtk_widget_get_allocation(btn, &allocation);
1820 *x += allocation.x;
1821 *y += allocation.y + allocation.height;
1822 *push_in = true;
1823 }
1824
1825 static void statesCB() {
1826 static GtkWidget *states_dialog = NULL;
1827 static GtkTreeView *tree;
1828 static GtkTreeSelection *select;
1829 static GtkWidget *currentLabel;
1830 static GtkWidget *menu;
1831 char buf[FILENAMELEN];
1832
1833 if (states_dialog == NULL) {
1834 // Pop-up menu for "More" button
1835 menu = gtk_menu_new();
1836 statesMenuItems[0] = gtk_menu_item_new_with_label("New");
1837 statesMenuItems[1] = gtk_menu_item_new_with_label("Duplicate");
1838 statesMenuItems[2] = gtk_menu_item_new_with_label("Rename");
1839 statesMenuItems[3] = gtk_menu_item_new_with_label("Delete");
1840 statesMenuItems[4] = gtk_menu_item_new_with_label("Import");
1841 statesMenuItems[5] = gtk_menu_item_new_with_label("Export");
1842 for (int i = 0; i < 6; i++) {
1843 g_signal_connect(G_OBJECT(statesMenuItems[i]), "activate", G_CALLBACK(states_menu_cb), (gpointer) (size_t) i);
1844 gtk_menu_shell_append(GTK_MENU_SHELL(menu), statesMenuItems[i]);
1845 gtk_widget_show(statesMenuItems[i]);
1846 }
1847 gtk_widget_show_all(menu);
1848
1849 // This is where the actual dialog starts
1850 states_dialog = gtk_dialog_new_with_buttons(
1851 "States",
1852 GTK_WINDOW(mainwindow),
1853 GTK_DIALOG_MODAL,
1854 "Switch To", 1,
1855 "More", 2,
1856 "Done", 3,
1857 NULL);
1858 for (int i = 1; i <= 3; i++) {
1859 GtkWidget *btn = gtk_dialog_get_widget_for_response(GTK_DIALOG(states_dialog), i);
1860 gtk_widget_set_can_default(btn, false);
1861 }
1862 gtk_window_set_resizable(GTK_WINDOW(states_dialog), FALSE);
1863 no_mwm_resize_borders(states_dialog);
1864 GtkWidget *container = gtk_bin_get_child(GTK_BIN(states_dialog));
1865 GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
1866 gtk_container_add(GTK_CONTAINER(container), box);
1867
1868 currentLabel = gtk_label_new("Current:");
1869 gtk_box_pack_start(GTK_BOX(box), currentLabel, FALSE, FALSE, 10);
1870
1871 GtkWidget *scroll = gtk_scrolled_window_new(NULL, NULL);
1872 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
1873 tree = (GtkTreeView *) gtk_tree_view_new();
1874 select = gtk_tree_view_get_selection(tree);
1875 gtk_tree_selection_set_mode(select, GTK_SELECTION_SINGLE);
1876 GtkWidget *switchToBtn = gtk_dialog_get_widget_for_response(GTK_DIALOG(states_dialog), 1);
1877 g_signal_connect(G_OBJECT(select), "changed", G_CALLBACK(states_changed_cb), (gpointer) switchToBtn);
1878 // When I try to pass the dialog pointer as closure data, it gets mangled?!?
1879 // Most be a casting issue, but I don't get it... So just passing it in a global.
1880 dlg = states_dialog;
1881 g_signal_connect(G_OBJECT(tree), "row-activated", G_CALLBACK(row_activated_cb), NULL);
1882 GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
1883 //gtk_cell_renderer_text_set_fixed_height_from_font((GtkCellRendererText *) renderer, 12);
1884 GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("Foo", renderer, "text", 0, NULL);
1885 gtk_tree_view_append_column(tree, column);
1886 gtk_tree_view_set_headers_visible(tree, FALSE);
1887 gtk_container_add(GTK_CONTAINER(scroll), GTK_WIDGET(tree));
1888 gtk_widget_set_size_request(scroll, -1, 200);
1889 gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(scroll), FALSE, FALSE, 10);
1890
1891 gtk_widget_show_all(states_dialog);
1892 }
1893
1894 load_state_names:
1895
1896 // Make sure a file exists for the current state. This isn't necessarily
1897 // the case, specifically, right after starting up with a version <= 25
1898 // state file.
1899 snprintf(buf, FILENAMELEN, "%s/%s.f42", free42dirname, state.coreName);
1900 if (!file_exists(buf)) {
1901 FILE *f = fopen(buf, "w");
1902 fwrite(FREE42_MAGIC_STR, 1, 4, f);
1903 fclose(f);
1904 }
1905
1906 snprintf(buf, FILENAMELEN, "Current: %s", state.coreName);
1907 gtk_label_set_text(GTK_LABEL(currentLabel), buf);
1908
1909 state_names = (char **) malloc(16 * sizeof(char *));
1910 int state_size = 0, state_capacity = 16;
1911 DIR *dir = opendir(free42dirname);
1912 if (dir != NULL) {
1913 struct dirent *dent;
1914 while ((dent = readdir(dir)) != NULL) {
1915 int namelen = strlen(dent->d_name);
1916 if (namelen < 4)
1917 continue;
1918 if (strcmp(dent->d_name + namelen - 4, ".f42") != 0)
1919 continue;
1920 char *stn = (char *) malloc(namelen - 3);
1921 memcpy(stn, dent->d_name, namelen - 4);
1922 stn[namelen - 4] = 0;
1923 if (state_size == state_capacity) {
1924 state_capacity += 16;
1925 state_names = (char **) realloc(state_names, state_capacity * sizeof(char *));
1926 }
1927 state_names[state_size++] = stn;
1928 }
1929 closedir(dir);
1930 qsort(state_names, state_size, sizeof(char *), case_insens_comparator);
1931 }
1932
1933 currentStateIndex = -1;
1934 GtkListStore *model = gtk_list_store_new(1, G_TYPE_STRING);
1935 GtkTreeIter iter;
1936 for (int i = 0; i < state_size; i++) {
1937 gtk_list_store_append(model, &iter);
1938 gtk_list_store_set(model, &iter, 0, state_names[i], -1);
1939 if (strcmp(state_names[i], state.coreName) == 0)
1940 currentStateIndex = i;
1941 }
1942 gtk_tree_view_set_model(tree, GTK_TREE_MODEL(model));
1943
1944 // TODO: does this leak list-stores? Or is everything taken case of by the
1945 // GObject reference-counting stuff?
1946
1947 gtk_window_set_role(GTK_WINDOW(states_dialog), "Free42 Dialog");
1948 while (true) {
1949 int response = gtk_dialog_run(GTK_DIALOG(states_dialog));
1950 if (response == 3 || response == GTK_RESPONSE_DELETE_EVENT)
1951 break;
1952 else if (response == 1) {
1953 GtkWidget *btn = gtk_dialog_get_widget_for_response(GTK_DIALOG(states_dialog), 1);
1954 if (!gtk_widget_get_sensitive(btn))
1955 // User double-clicked on a row, but the Switch To button is disabled
1956 continue;
1957 GList *rows = gtk_tree_selection_get_selected_rows(select, NULL);
1958 if (rows != NULL) {
1959 GtkTreePath *path = (GtkTreePath *) rows->data;
1960 int sel;
1961 sscanf(gtk_tree_path_to_string(path), "%d", &sel);
1962 g_list_free(rows);
1963 if (switchTo(state_names[sel]))
1964 break;
1965 }
1966 } else if (response == 2) {
1967 GtkWidget *btn = gtk_dialog_get_widget_for_response(GTK_DIALOG(states_dialog), 2);
1968 gtk_menu_popup(GTK_MENU(menu), NULL, NULL, states_menu_pos_func, btn, 0, GDK_CURRENT_TIME);
1969 } else if (response == 4) {
1970 for (int i = 0; i < state_size; i++)
1971 free(state_names[i]);
1972 free(state_names);
1973 goto load_state_names;
1974 }
1975 }
1976
1977 gtk_widget_hide(states_dialog);
1978
1979 for (int i = 0; i < state_size; i++)
1980 free(state_names[i]);
1981 free(state_names);
1982 }
1983
1984 //////////////////////////////////
1985 ///// States stuff ends here /////
1986 //////////////////////////////////
1987
1988 static void showPrintOutCB() {
1989 gtk_window_present(GTK_WINDOW(printwindow));
1990 gdk_window_focus(gtk_widget_get_window(printwindow), GDK_CURRENT_TIME);
1991 state.printWindowKnown = 1;
1992 state.printWindowMapped = 1;
1993 }
1994
1995 static void exportProgramCB() {
1996 static GtkWidget *sel_dialog = NULL;
1997 static GtkTreeView *tree;
1998 static GtkTreeSelection *select;
1999
2000 if (sel_dialog == NULL) {
2001 sel_dialog = gtk_dialog_new_with_buttons(
2002 "Export Programs",
2003 GTK_WINDOW(mainwindow),
2004 GTK_DIALOG_MODAL,
2005 "_OK", GTK_RESPONSE_ACCEPT,
2006 "_Cancel", GTK_RESPONSE_CANCEL,
2007 NULL);
2008 gtk_window_set_resizable(GTK_WINDOW(sel_dialog), FALSE);
2009 no_mwm_resize_borders(sel_dialog);
2010 GtkWidget *container = gtk_bin_get_child(GTK_BIN(sel_dialog));
2011 GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
2012 gtk_container_add(GTK_CONTAINER(container), box);
2013
2014 GtkWidget *label = gtk_label_new("Select Programs to Export:");
2015 gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 10);
2016
2017 GtkWidget *scroll = gtk_scrolled_window_new(NULL, NULL);
2018 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
2019 tree = (GtkTreeView *) gtk_tree_view_new();
2020 select = gtk_tree_view_get_selection(tree);
2021 gtk_tree_selection_set_mode(select, GTK_SELECTION_MULTIPLE);
2022 GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
2023 GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("Foo", renderer, "text", 0, NULL);
2024 gtk_tree_view_append_column(tree, column);
2025 gtk_tree_view_set_headers_visible(tree, FALSE);
2026 gtk_container_add(GTK_CONTAINER(scroll), GTK_WIDGET(tree));
2027 gtk_widget_set_size_request(scroll, -1, 200);
2028 gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(scroll), FALSE, FALSE, 10);
2029
2030 gtk_widget_show_all(GTK_WIDGET(sel_dialog));
2031 }
2032
2033 char *buf = core_list_programs();
2034
2035 GtkListStore *model = gtk_list_store_new(1, G_TYPE_STRING);
2036 if (buf != NULL) {
2037 int count = ((buf[0] & 255) << 24) | ((buf[1] & 255) << 16) | ((buf[2] & 255) << 8) | (buf[3] & 255);
2038 char *p = buf + 4;
2039 GtkTreeIter iter;
2040 while (count-- > 0) {
2041 gtk_list_store_append(model, &iter);
2042 gtk_list_store_set(model, &iter, 0, p, -1);
2043 p += strlen(p) + 1;
2044 }
2045 }
2046 gtk_tree_view_set_model(tree, GTK_TREE_MODEL(model));
2047
2048 // TODO: does this leak list-stores? Or is everything taken case of by the
2049 // GObject reference-counting stuff?
2050
2051 gtk_window_set_role(GTK_WINDOW(sel_dialog), "Free42 Dialog");
2052 bool cancelled = gtk_dialog_run(GTK_DIALOG(sel_dialog)) != GTK_RESPONSE_ACCEPT;
2053 gtk_widget_hide(sel_dialog);
2054 if (cancelled) {
2055 free(buf);
2056 return;
2057 }
2058
2059 int count = gtk_tree_selection_count_selected_rows(select);
2060 if (count == 0) {
2061 free(buf);
2062 return;
2063 }
2064
2065 int *p2 = (int *) malloc(count * sizeof(int));
2066 // TODO - handle memory allocation failure
2067 GList *rows = gtk_tree_selection_get_selected_rows(select, NULL);
2068 GList *item = rows;
2069 int i = 0;
2070 while (item != NULL) {
2071 GtkTreePath *path = (GtkTreePath *) item->data;
2072 char *pathstring = gtk_tree_path_to_string(path);
2073 sscanf(pathstring, "%d", p2 + i);
2074 item = item->next;
2075 i++;
2076 }
2077 g_list_free(rows);
2078
2079 char suggested_name[50] = "Untitled.raw";
2080 char *p = buf + 4;
2081 int sel = p2[0];
2082 while (sel > 0) {
2083 p += strlen(p) + 1;
2084 sel--;
2085 }
2086 if (p[0] == '"') {
2087 char *closing_quote = strchr(p + 1, '"');
2088 if (closing_quote != NULL) {
2089 int len = closing_quote - p - 1;
2090 for (int i = 0; i < len; i++) {
2091 char c = p[i + 1];
2092 if (c == '/' || c == 10)
2093 c = '_';
2094 suggested_name[i] = c;
2095 }
2096 suggested_name[len] = 0;
2097 strcat(suggested_name, ".raw");
2098 }
2099 }
2100 free(buf);
2101
2102 static GtkWidget *save_dialog = NULL;
2103 if (save_dialog == NULL)
2104 save_dialog = make_file_select_dialog("Export Programs",
2105 "Program Files (*.raw)\0*.[Rr][Aa][Ww]\0All Files (*.*)\0*\0",
2106 true, mainwindow);
2107
2108 char *filename = NULL;
2109 gtk_window_set_role(GTK_WINDOW(save_dialog), "Free42 Dialog");
2110 gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(save_dialog), suggested_name);
2111 if (gtk_dialog_run(GTK_DIALOG(save_dialog)) == GTK_RESPONSE_ACCEPT)
2112 filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(save_dialog));
2113 gtk_widget_hide(GTK_WIDGET(save_dialog));
2114 if (filename == NULL) {
2115 free(p2);
2116 return;
2117 }
2118
2119 char export_file_name[FILENAMELEN];
2120 strcpy(export_file_name, filename);
2121 g_free(filename);
2122 if (strncmp(gtk_file_filter_get_name(
2123 gtk_file_chooser_get_filter(
2124 GTK_FILE_CHOOSER(save_dialog))), "All", 3) != 0)
2125 appendSuffix(export_file_name, ".raw");
2126
2127 if (file_exists(export_file_name)) {
2128 GtkWidget *msg = gtk_message_dialog_new(GTK_WINDOW(mainwindow),
2129 GTK_DIALOG_MODAL,
2130 GTK_MESSAGE_QUESTION,
2131 GTK_BUTTONS_YES_NO,
2132 "Replace existing \"%s\"?",
2133 export_file_name);
2134 gtk_window_set_title(GTK_WINDOW(msg), "Replace?");
2135 gtk_window_set_role(GTK_WINDOW(msg), "Free42 Dialog");
2136 cancelled = gtk_dialog_run(GTK_DIALOG(msg)) != GTK_RESPONSE_YES;
2137 gtk_widget_destroy(msg);
2138 if (cancelled) {
2139 free(p2);
2140 return;
2141 }
2142 }
2143
2144 core_export_programs(count, p2, export_file_name);
2145 free(p2);
2146 }
2147
2148 static GtkWidget *make_file_select_dialog(const char *title,
2149 const char *pattern,
2150 bool save,
2151 GtkWidget *owner) {
2152 GtkWidget *dialog = gtk_file_chooser_dialog_new(
2153 title,
2154 GTK_WINDOW(owner),
2155 save ? GTK_FILE_CHOOSER_ACTION_SAVE
2156 : GTK_FILE_CHOOSER_ACTION_OPEN,
2157 "_Cancel", GTK_RESPONSE_CANCEL,
2158 save ? "_Save" : "_Open",
2159 GTK_RESPONSE_ACCEPT,
2160 NULL);
2161 const char *p = pattern;
2162 while (1) {
2163 const char *descr, *ext;
2164 int n = strlen(p);
2165 if (n == 0)
2166 break;
2167 descr = p;
2168 p += n + 1;
2169 n = strlen(p);
2170 if (n == 0)
2171 break;
2172 ext = p;
2173 p += n + 1;
2174
2175 GtkFileFilter *filter = gtk_file_filter_new();
2176 gtk_file_filter_add_pattern(filter, ext);
2177 gtk_file_filter_set_name(filter, descr);
2178 gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
2179 }
2180 return dialog;
2181 }
2182
2183 static void importProgramCB() {
2184 static GtkWidget *dialog = NULL;
2185
2186 if (dialog == NULL)
2187 dialog = make_file_select_dialog("Import Programs",
2188 "Program Files (*.raw)\0*.[Rr][Aa][Ww]\0All Files (*.*)\0*\0",
2189 false, mainwindow);
2190
2191 gtk_window_set_role(GTK_WINDOW(dialog), "Free42 Dialog");
2192 bool cancelled = gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT;
2193 gtk_widget_hide(dialog);
2194 if (cancelled)
2195 return;
2196
2197 char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
2198 if (filename == NULL)
2199 return;
2200
2201 char filenamebuf[FILENAMELEN];
2202 strncpy(filenamebuf, filename, FILENAMELEN);
2203 filenamebuf[FILENAMELEN - 1] = 0;
2204 g_free(filename);
2205
2206 if (strncmp(gtk_file_filter_get_name(
2207 gtk_file_chooser_get_filter(
2208 GTK_FILE_CHOOSER(dialog))), "All", 3) != 0)
2209 appendSuffix(filenamebuf, ".raw");
2210
2211 core_import_programs(0, filenamebuf);
2212 redisplay();
2213 }
2214
2215 static void paperAdvanceCB() {
2216 static const char *bits = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
2217 shell_print("", 0, bits, 18, 0, 0, 143, 9);
2218 }
2219
2220 static char *tb;
2221 static int tblen, tbcap;
2222
2223 static void tbwriter(const char *text, int length) {
2224 if (tblen + length > tbcap) {
2225 tbcap += length + 8192;
2226 tb = (char *) realloc(tb, tbcap);
2227 }
2228 if (tb != NULL) {
2229 memcpy(tb + tblen, text, length);
2230 tblen += length;
2231 }
2232 }
2233
2234 static void tbnewliner() {
2235 tbwriter("\n", 1);
2236 }
2237
2238 static void tbnonewliner() {
2239 // No-op
2240 }
2241
2242 static void copyPrintAsTextCB() {
2243 tb = NULL;
2244 tblen = tbcap = 0;
2245
2246 int len = print_text_bottom - print_text_top;
2247 if (len < 0)
2248 len += PRINT_TEXT_SIZE;
2249 // Calculate effective top, since printout_top can point
2250 // at a truncated line, and we want to skip those when
2251 // copying
2252 int top = printout_bottom - 2 * print_text_pixel_height;
2253 if (top < 0)
2254 top += PRINT_LINES;
2255 int p = print_text_top;
2256 int pixel_v = 0;
2257 while (len > 0) {
2258 int z = print_text[p++];
2259 if (z == 255) {
2260 char buf[34];
2261 for (int v = 0; v < 16; v += 2) {
2262 for (int vv = 0; vv < 2; vv++) {
2263 int V = top + (pixel_v + v + vv) * 2;
2264 if (V >= PRINT_LINES)
2265 V -= PRINT_LINES;
2266 for (int h = 0; h < 17; h++) {
2267 unsigned char a = print_bitmap[V * PRINT_BYTESPERLINE + 2 * h + 1];
2268 unsigned char b = print_bitmap[V * PRINT_BYTESPERLINE + 2 * h];
2269 buf[vv * 17 + h] = (a & 128) | ((a & 32) << 1) | ((a & 8) << 2) | ((a & 2) << 3) | ((b & 128) >> 4) | ((b & 32) >> 3) | ((b & 8) >> 2) | ((b & 2) >> 1);
2270 }
2271 }
2272 shell_spool_bitmap_to_txt(buf, 17, 0, 0, 131, 2, tbwriter, tbnewliner);
2273 }
2274 pixel_v += 16;
2275 } else {
2276 if (p + z < PRINT_TEXT_SIZE) {
2277 shell_spool_txt((const char *) (print_text + p), z, tbwriter, tbnewliner);
2278 p += z;
2279 } else {
2280 int d = PRINT_TEXT_SIZE - p;
2281 shell_spool_txt((const char *) (print_text + p), d, tbwriter, tbnonewliner);
2282 shell_spool_txt((const char *) print_text, z - d, tbwriter, tbnewliner);
2283 p = z - d;
2284 }
2285 len -= z;
2286 pixel_v += 9;
2287 }
2288 len--;
2289 }
2290 tbwriter("\0", 1);
2291
2292 GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
2293 gtk_clipboard_set_text(clip, tb, -1);
2294 clip = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
2295 gtk_clipboard_set_text(clip, tb, -1);
2296 free(tb);
2297 }
2298
2299 static void copyPrintAsImageCB() {
2300 int length = printout_bottom - printout_top;
2301 if (length < 0)
2302 length += PRINT_LINES;
2303 bool empty = length == 0;
2304 if (empty)
2305 length += 2;
2306
2307 GdkPixbuf *buf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE,
2308 8, 358, length);
2309 int d_bpl = gdk_pixbuf_get_rowstride(buf);
2310 guchar *d1 = gdk_pixbuf_get_pixels(buf);
2311
2312 if (empty) {
2313 memset(d1, 255, 2148);
2314 } else {
2315 for (int v = 0; v < length; v++) {
2316 int v2 = printout_top + v;
2317 if (v2 >= PRINT_LINES)
2318 v2 -= PRINT_LINES;
2319 int v3 = v2 * 36;
2320 guchar *dst = d1;
2321 for (int h = 0; h < 358; h++) {
2322 unsigned char c;
2323 if (h < 36 || h >= 322)
2324 c = 255;
2325 else if ((print_bitmap[v3 + ((h - 36) >> 3)] & (1 << ((h - 36) & 7))) == 0)
2326 c = 255;
2327 else
2328 c = 0;
2329 *dst++ = c;
2330 *dst++ = c;
2331 *dst++ = c;
2332 }
2333 d1 += d_bpl;
2334 }
2335 }
2336
2337 GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
2338 gtk_clipboard_set_image(clip, buf);
2339 }
2340
2341 static void clearPrintOutCB() {
2342 printout_top = 0;
2343 printout_bottom = 0;
2344 print_text_top = 0;
2345 print_text_bottom = 0;
2346 print_text_pixel_height = 0;
2347 gtk_widget_set_size_request(print_widget, 358, 1);
2348
2349 if (print_gif != NULL) {
2350 shell_finish_gif(gif_seeker, gif_writer);
2351 fclose(print_gif);
2352 print_gif = NULL;
2353 }
2354 }
2355
2356 struct browse_file_info {
2357 const char *title;
2358 const char *patterns;
2359 GtkWidget *textfield;
2360 browse_file_info(const char *t, const char *p, GtkWidget *tf)
2361 : title(t), patterns(p), textfield(tf) {}
2362 };
2363
2364 static void browse_file(GtkButton *button, gpointer cd) {
2365 browse_file_info *info = (browse_file_info *) cd;
2366 GtkWidget *dialog = gtk_widget_get_toplevel(GTK_WIDGET(button));
2367 GtkWidget *save_dialog = make_file_select_dialog(
2368 info->title, info->patterns, true, dialog);
2369 const char *filename = gtk_entry_get_text(GTK_ENTRY(info->textfield));
2370 if (filename[0] == '/')
2371 gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(save_dialog), filename);
2372 gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(save_dialog), filename);
2373
2374 gtk_window_set_role(GTK_WINDOW(save_dialog), "Free42 Dialog");
2375 if (gtk_dialog_run(GTK_DIALOG(save_dialog)) == GTK_RESPONSE_ACCEPT) {
2376 filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(save_dialog));
2377
2378 char filenamebuf[FILENAMELEN];
2379 strncpy(filenamebuf, filename, FILENAMELEN);
2380 filenamebuf[FILENAMELEN - 1] = 0;
2381 const gchar *filtername =
2382 gtk_file_filter_get_name(
2383 gtk_file_chooser_get_filter(
2384 GTK_FILE_CHOOSER(save_dialog)));
2385 if (strncmp(filtername, "Text", 4) == 0)
2386 appendSuffix(filenamebuf, ".txt");
2387 else if (strncmp(filtername, "GIF", 3) == 0)
2388 appendSuffix(filenamebuf, ".gif");
2389
2390 gtk_entry_set_text(GTK_ENTRY(info->textfield), filenamebuf);
2391 }
2392 gtk_widget_destroy(GTK_WIDGET(save_dialog));
2393 }
2394
2395 static void preferencesCB() {
2396 static GtkWidget *dialog = NULL;
2397 static GtkWidget *singularmatrix;
2398 static GtkWidget *matrixoutofrange;
2399 static GtkWidget *autorepeat;
2400 static GtkWidget *allowbigstack;
2401 static GtkWidget *localizedcopypaste;
2402 static GtkWidget *repaintwholedisplay;
2403 static GtkWidget *printtotext;
2404 static GtkWidget *textpath;
2405 static GtkWidget *printtogif;
2406 static GtkWidget *gifpath;
2407 static GtkWidget *gifheight;
2408
2409 if (dialog == NULL) {
2410 dialog = gtk_dialog_new_with_buttons(
2411 "Preferences",
2412 GTK_WINDOW(mainwindow),
2413 GTK_DIALOG_MODAL,
2414 "_OK", GTK_RESPONSE_ACCEPT,
2415 "_Cancel", GTK_RESPONSE_CANCEL,
2416 NULL);
2417 gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
2418 no_mwm_resize_borders(dialog);
2419 GtkWidget *container = gtk_bin_get_child(GTK_BIN(dialog));
2420 GtkWidget *grid = gtk_grid_new();
2421 gtk_container_add(GTK_CONTAINER(container), grid);
2422
2423 singularmatrix = gtk_check_button_new_with_label("Inverting or solving a singular matrix yields \"Singular Matrix\" error");
2424 gtk_grid_attach(GTK_GRID(grid), singularmatrix, 0, 0, 4, 1);
2425 matrixoutofrange = gtk_check_button_new_with_label("Overflows during matrix operations yield \"Out of Range\" error");
2426 gtk_grid_attach(GTK_GRID(grid), matrixoutofrange, 0, 1, 4, 1);
2427 autorepeat = gtk_check_button_new_with_label("Auto-repeat for number entry and ALPHA mode");
2428 gtk_grid_attach(GTK_GRID(grid), autorepeat, 0, 2, 4, 1);
2429 allowbigstack = gtk_check_button_new_with_label("Allow Big Stack (NSTK) mode");
2430 gtk_grid_attach(GTK_GRID(grid), allowbigstack, 0, 3, 4, 1);
2431 localizedcopypaste = gtk_check_button_new_with_label("Localized Copy & Paste");
2432 gtk_grid_attach(GTK_GRID(grid), localizedcopypaste, 0, 4, 4, 1);
2433 repaintwholedisplay = gtk_check_button_new_with_label("Always repaint entire display");
2434 gtk_grid_attach(GTK_GRID(grid), repaintwholedisplay, 0, 5, 4, 1);
2435 printtotext = gtk_check_button_new_with_label("Print to text file:");
2436 gtk_grid_attach(GTK_GRID(grid), printtotext, 0, 6, 1, 1);
2437 textpath = gtk_entry_new();
2438 gtk_grid_attach(GTK_GRID(grid), textpath, 1, 6, 2, 1);
2439 GtkWidget *browse1 = gtk_button_new_with_label("Browse...");
2440 gtk_grid_attach(GTK_GRID(grid), browse1, 3, 6, 1, 1);
2441 printtogif = gtk_check_button_new_with_label("Print to GIF file:");
2442 gtk_grid_attach(GTK_GRID(grid), printtogif, 0, 7, 1, 1);
2443 gifpath = gtk_entry_new();
2444 gtk_grid_attach(GTK_GRID(grid), gifpath, 1, 7, 2, 1);
2445 GtkWidget *browse2 = gtk_button_new_with_label("Browse...");
2446 gtk_grid_attach(GTK_GRID(grid), browse2, 3, 7, 1, 1);
2447 GtkWidget *label = gtk_label_new("Maximum GIF height (pixels):");
2448 gtk_grid_attach(GTK_GRID(grid), label, 1, 8, 1, 1);
2449 gifheight = gtk_entry_new();
2450 gtk_entry_set_max_length(GTK_ENTRY(gifheight), 5);
2451 gtk_grid_attach(GTK_GRID(grid), gifheight, 2, 8, 1, 1);
2452
2453 g_signal_connect(G_OBJECT(browse1), "clicked", G_CALLBACK(browse_file),
2454 (gpointer) new browse_file_info("Select Text File Name",
2455 "Text (*.txt)\0*.[Tt][Xx][Tt]\0All Files (*.*)\0*\0",
2456 textpath));
2457 g_signal_connect(G_OBJECT(browse2), "clicked", G_CALLBACK(browse_file),
2458 (gpointer) new browse_file_info("Select GIF File Name",
2459 "GIF (*.gif)\0*.[Gg][Ii][Ff]\0All Files (*.*)\0*\0",
2460 gifpath));
2461
2462 gtk_widget_show_all(GTK_WIDGET(dialog));
2463 }
2464
2465 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(singularmatrix), core_settings.matrix_singularmatrix);
2466 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(matrixoutofrange), core_settings.matrix_outofrange);
2467 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(autorepeat), core_settings.auto_repeat);
2468 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(allowbigstack), core_settings.allow_big_stack);
2469 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(localizedcopypaste), core_settings.localized_copy_paste);
2470 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(printtotext), state.printerToTxtFile);
2471 gtk_entry_set_text(GTK_ENTRY(textpath), state.printerTxtFileName);
2472 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(printtogif), state.printerToGifFile);
2473 gtk_entry_set_text(GTK_ENTRY(gifpath), state.printerGifFileName);
2474 char maxlen[6];
2475 snprintf(maxlen, 6, "%d", state.printerGifMaxLength);
2476 gtk_entry_set_text(GTK_ENTRY(gifheight), maxlen);
2477 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(repaintwholedisplay), !state.old_repaint);
2478
2479 gtk_window_set_role(GTK_WINDOW(dialog), "Free42 Dialog");
2480 if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
2481 core_settings.matrix_singularmatrix = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(singularmatrix));
2482 core_settings.matrix_outofrange = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(matrixoutofrange));
2483 core_settings.auto_repeat = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autorepeat));
2484 bool oldBigStack = core_settings.allow_big_stack;
2485 core_settings.allow_big_stack = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(allowbigstack));
2486 if (oldBigStack != core_settings.allow_big_stack)
2487 core_update_allow_big_stack();
2488 core_settings.localized_copy_paste = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(localizedcopypaste));
2489
2490 state.printerToTxtFile = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(printtotext));
2491 char *old = strclone(state.printerTxtFileName);
2492 const char *s = gtk_entry_get_text(GTK_ENTRY(textpath));
2493 strncpy(state.printerTxtFileName, s, FILENAMELEN);
2494 state.printerTxtFileName[FILENAMELEN - 1] = 0;
2495 appendSuffix(state.printerTxtFileName, ".txt");
2496 if (print_txt != NULL && (!state.printerToTxtFile || strcmp(state.printerTxtFileName, old) != 0)) {
2497 fclose(print_txt);
2498 print_txt = NULL;
2499 }
2500 free(old);
2501
2502 state.printerToGifFile = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(printtogif));
2503 old = strclone(state.printerGifFileName);
2504 s = gtk_entry_get_text(GTK_ENTRY(gifpath));
2505 strncpy(state.printerGifFileName, s, FILENAMELEN);
2506 state.printerGifFileName[FILENAMELEN - 1] = 0;
2507 appendSuffix(state.printerGifFileName, ".gif");
2508 if (print_gif != NULL && (!state.printerToGifFile || strcmp(state.printerGifFileName, old) != 0)) {
2509 shell_finish_gif(gif_seeker, gif_writer);
2510 fclose(print_gif);
2511 print_gif = NULL;
2512 gif_seq = -1;
2513 }
2514 free(old);
2515
2516 s = gtk_entry_get_text(GTK_ENTRY(gifheight));
2517 if (sscanf(s, "%d", &state.printerGifMaxLength) == 1) {
2518 if (state.printerGifMaxLength < 16)
2519 state.printerGifMaxLength = 16;
2520 else if (state.printerGifMaxLength > 32767) state.printerGifMaxLength = 32767;
2521 } else
2522 state.printerGifMaxLength = 256;
2523
2524 state.old_repaint = !gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(repaintwholedisplay));
2525 }
2526
2527 gtk_widget_hide(GTK_WIDGET(dialog));
2528 }
2529
2530 static void appendSuffix(char *path, const char *suffix) {
2531 int len = strlen(path);
2532 int slen = strlen(suffix);
2533 if (len == 0 || len >= FILENAMELEN - slen)
2534 return;
2535 if (len >= slen && strcasecmp(path + len - slen, suffix) != 0)
2536 strcat(path, suffix);
2537 }
2538
2539 static void copyCB() {
2540 char *buf = core_copy();
2541 GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
2542 gtk_clipboard_set_text(clip, buf, -1);
2543 clip = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
2544 gtk_clipboard_set_text(clip, buf, -1);
2545 free(buf);
2546 }
2547
2548 static void paste2(GtkClipboard *clip, const gchar *text, gpointer cd) {
2549 if (text != NULL) {
2550 core_paste(text);
2551 redisplay();
2552 // GTK will free the text once the callback returns.
2553 }
2554 }
2555
2556 static void pasteCB() {
2557 GtkClipboard *clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
2558 gtk_clipboard_request_text(clip, paste2, NULL);
2559 }
2560
2561 static bool focus_ok_button(GtkWindow *window, GtkWidget *container) {
2562 GList *children = gtk_container_get_children(GTK_CONTAINER(container));
2563 if (children == NULL)
2564 return false;
2565 GList *child = children;
2566 while (child != NULL) {
2567 GtkWidget *w = (GtkWidget *) child->data;
2568 if (GTK_IS_BUTTON(w) && !GTK_IS_LINK_BUTTON(w)) {
2569 gtk_window_set_focus(window, w);
2570 g_list_free(children);
2571 return true;
2572 } else if (GTK_IS_CONTAINER(w)) {
2573 if (focus_ok_button(window, w)) {
2574 g_list_free(children);
2575 return true;
2576 }
2577 }
2578 child = child->next;
2579 }
2580 g_list_free(children);
2581 return false;
2582 }
2583
2584 static void documentationCB() {
2585 #if GTK_MINOR_VERSION >= 22
2586 gtk_show_uri_on_window(GTK_WINDOW(mainwindow), "https://thomasokken.com/free42/#doc", GDK_CURRENT_TIME, NULL);
2587 #else
2588 gtk_show_uri(gtk_widget_get_screen(mainwindow), "https://thomasokken.com/free42/#doc", GDK_CURRENT_TIME, NULL);
2589 #endif
2590 }
2591
2592 static void websiteCB() {
2593 #if GTK_MINOR_VERSION >= 22
2594 gtk_show_uri_on_window(GTK_WINDOW(mainwindow), "https://thomasokken.com/free42/", GDK_CURRENT_TIME, NULL);
2595 #else
2596 gtk_show_uri(gtk_widget_get_screen(mainwindow), "https://thomasokken.com/free42/", GDK_CURRENT_TIME, NULL);
2597 #endif
2598 }
2599
2600 static void otherWebsiteCB() {
2601 #if GTK_MINOR_VERSION >= 22
2602 gtk_show_uri_on_window(GTK_WINDOW(mainwindow), "https://thomasokken.com/plus42/", GDK_CURRENT_TIME, NULL);
2603 #else
2604 gtk_show_uri(gtk_widget_get_screen(mainwindow), "https://thomasokken.com/plus42/", GDK_CURRENT_TIME, NULL);
2605 #endif
2606 }
2607
2608 static void keyboardShortcutsCB() {
2609 keyboardShortcutsShowing = !keyboardShortcutsShowing;
2610 gtk_check_menu_item_set_active(keyboardShortcutsMenuItem, keyboardShortcutsShowing);
2611 GdkWindow *win = gtk_widget_get_window(calc_widget);
2612 gdk_window_invalidate_rect(win, NULL, FALSE);
2613 }
2614
2615 static void editKeymapCB() {
2616 char cmd[FILENAMELEN + 12];
2617 snprintf(cmd, FILENAMELEN + 12, "xdg-open '%s'", keymapfilename);
2618 system(cmd);
2619 }
2620
2621 static void aboutCB() {
2622 static GtkWidget *about = NULL;
2623
2624 if (about == NULL) {
2625 about = gtk_dialog_new_with_buttons(
2626 "About Free42",
2627 GTK_WINDOW(mainwindow),
2628 GTK_DIALOG_MODAL,
2629 "_OK",
2630 GTK_RESPONSE_ACCEPT,
2631 NULL);
2632 gtk_window_set_resizable(GTK_WINDOW(about), FALSE);
2633 no_mwm_resize_borders(about);
2634 GtkWidget *container = gtk_bin_get_child(GTK_BIN(about));
2635 GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
2636 gtk_container_add(GTK_CONTAINER(container), box);
2637 GtkWidget *image = gtk_image_new_from_pixbuf(icon_48);
2638 gtk_box_pack_start(GTK_BOX(box), image, FALSE, FALSE, 10);
2639 GtkWidget *box2 = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
2640 GtkWidget *version = gtk_label_new("Free42 " VERSION);
2641 gtk_misc_set_alignment(GTK_MISC(version), 0, 0);
2642 gtk_box_pack_start(GTK_BOX(box2), version, FALSE, FALSE, 10);
2643 GtkWidget *author = gtk_label_new("\302\251 2004-2026 Thomas Okken");
2644 gtk_misc_set_alignment(GTK_MISC(author), 0, 0);
2645 gtk_box_pack_start(GTK_BOX(box2), author, FALSE, FALSE, 0);
2646 GtkWidget *websitelink = gtk_link_button_new("https://thomasokken.com/free42/");
2647 GtkWidget *websitebox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
2648 gtk_box_pack_start(GTK_BOX(websitebox), websitelink, FALSE, FALSE, 0);
2649 gtk_box_pack_start(GTK_BOX(box2), websitebox, FALSE, FALSE, 0);
2650 GtkWidget *forumlink = gtk_link_button_new("https://thomasokken.com/free42/#doc");
2651 GtkWidget *forumbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
2652 gtk_box_pack_start(GTK_BOX(forumbox), forumlink, FALSE, FALSE, 0);
2653 gtk_box_pack_start(GTK_BOX(box2), forumbox, FALSE, FALSE, 0);
2654 GtkWidget *plus42 = gtk_label_new("Plus42: Free42 Enhanced");
2655 gtk_misc_set_alignment(GTK_MISC(plus42), 0, 0);
2656 gtk_box_pack_start(GTK_BOX(box2), plus42, FALSE, FALSE, 0);
2657 GtkWidget *websiteplus42link = gtk_link_button_new("https://thomasokken.com/plus42/");
2658 GtkWidget *websiteplus42box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
2659 gtk_box_pack_start(GTK_BOX(websiteplus42box), websiteplus42link, FALSE, FALSE, 0);
2660 gtk_box_pack_start(GTK_BOX(box2), websiteplus42box, FALSE, FALSE, 0);
2661 gtk_box_pack_start(GTK_BOX(box), box2, FALSE, FALSE, 0);
2662 focus_ok_button(GTK_WINDOW(about), container);
2663 gtk_widget_show_all(GTK_WIDGET(about));
2664 } else {
2665 GtkWidget *container = gtk_bin_get_child(GTK_BIN(about));
2666 focus_ok_button(GTK_WINDOW(about), container);
2667 }
2668
2669 gtk_window_set_role(GTK_WINDOW(about), "Free42 Dialog");
2670 gtk_dialog_run(GTK_DIALOG(about));
2671 gtk_widget_hide(GTK_WIDGET(about));
2672 }
2673
2674 static gboolean delete_cb(GtkWidget *w, GdkEventAny *ev) {
2675 quit();
2676 return TRUE;
2677 }
2678
2679 static gboolean delete_print_cb(GtkWidget *w, GdkEventAny *ev) {
2680 gint x, y;
2681 gtk_window_get_position(GTK_WINDOW(printwindow), &x, &y);
2682 state.printWindowX = x;
2683 state.printWindowY = y;
2684 state.printWindowMapped = 0;
2685 state.printWindowKnown = 1;
2686 gtk_widget_hide(GTK_WIDGET(printwindow));
2687 return TRUE;
2688 }
2689
2690 static bool is_dark(GtkWidget *w) {
2691 GtkStyle *style = gtk_widget_get_style(w);
2692 GdkColor c = style->bg[GTK_STATE_NORMAL];
2693 return 0.299 * c.red + 0.587 * c.green + 0.114 * c.blue < 32768;
2694 }
2695
2696 static gboolean draw_cb(GtkWidget *w, cairo_t *cr, gpointer cd) {
2697 cairo_save(cr);
2698 int win_width, win_height, skin_width, skin_height;
2699 skin_get_window_size(&win_width, &win_height);
2700 skin_get_size(&skin_width, &skin_height);
2701 cairo_scale(cr, ((double) win_width) / skin_width, ((double) win_height) / skin_height);
2702
2703 allow_paint = true;
2704 bool only_disp = need_to_paint_only_display(cr);
2705 if (!only_disp)
2706 skin_repaint(cr);
2707 skin_repaint_display(cr);
2708 if (!only_disp) {
2709 if (ann_updown)
2710 skin_repaint_annunciator(cr, 1);
2711 if (ann_shift)
2712 skin_repaint_annunciator(cr, 2);
2713 if (ann_print)
2714 skin_repaint_annunciator(cr, 3);
2715 if (ann_run)
2716 skin_repaint_annunciator(cr, 4);
2717 if (ann_battery)
2718 skin_repaint_annunciator(cr, 5);
2719 if (ann_g)
2720 skin_repaint_annunciator(cr, 6);
2721 if (ann_rad)
2722 skin_repaint_annunciator(cr, 7);
2723 if (ckey != 0)
2724 skin_repaint_key(cr, skey, 1);
2725 } else {
2726 if (skey >= -7 && skey <= -2)
2727 skin_repaint_key(cr, skey, 1);
2728 }
2729
2730 if (keyboardShortcutsShowing)
2731 skin_draw_keyboard_shortcuts(cr);
2732 if (is_dark(w))
2733 skin_make_darker(cr);
2734
2735 cairo_restore(cr);
2736 return TRUE;
2737 }
2738
2739 static gboolean print_draw_cb(GtkWidget *w, cairo_t *cr, gpointer cd) {
2740 repaint_printout(cr, is_dark(w));
2741 return TRUE;
2742 }
2743
2744 static gboolean print_key_cb(GtkWidget *w, GdkEventKey *event, gpointer cd) {
2745
2746 // This is a bit hacky, but I want the Ctrl-<Key>
2747 // shortcuts to work even when the Print-Out window
2748 // is on top.
2749
2750 if (event->type != GDK_KEY_PRESS)
2751 return TRUE;
2752
2753 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
2754 bool alt = (event->state & GDK_MOD1_MASK) != 0;
2755 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
2756 if (!ctrl || alt || shift)
2757 return TRUE;
2758
2759 switch (event->keyval) {
2760 case GDK_KEY_a:
2761 paperAdvanceCB();
2762 break;
2763 case GDK_KEY_t:
2764 copyPrintAsTextCB();
2765 break;
2766 case GDK_KEY_i:
2767 copyPrintAsImageCB();
2768 break;
2769 case GDK_KEY_d:
2770 clearPrintOutCB();
2771 break;
2772 case GDK_KEY_q:
2773 quit();
2774 break;
2775 case GDK_KEY_c:
2776 copyCB();
2777 break;
2778 case GDK_KEY_v:
2779 pasteCB();
2780 break;
2781 }
2782 return TRUE;
2783 }
2784
2785 static void shell_keydown(bool cshift) {
2786 GdkWindow *win = gtk_widget_get_window(calc_widget);
2787
2788 int repeat;
2789 bool keep_running;
2790 if (skey == -1)
2791 skey = skin_find_skey(ckey, cshift);
2792 skin_invalidate_key(win, skey);
2793 if (timeout3_id != 0 && (macro != NULL || ckey != 28 /* KEY_SHIFT */)) {
2794 g_source_remove(timeout3_id);
2795 timeout3_id = 0;
2796 core_timeout3(false);
2797 }
2798
2799 if (macro != NULL) {
2800 if (macro_type != 0) {
2801 keep_running = core_keydown_command((const char *) macro, macro_type == 2, &enqueued, &repeat);
2802 } else {
2803 if (*macro == 0) {
2804 squeak();
2805 return;
2806 }
2807 bool one_key_macro = macro[1] == 0 || (macro[2] == 0 && macro[0] == 28);
2808 if (one_key_macro) {
2809 while (*macro != 0) {
2810 keep_running = core_keydown(*macro++, &enqueued, &repeat);
2811 if (*macro != 0 && !enqueued)
2812 core_keyup();
2813 }
2814 } else {
2815 bool waitForProgram = !program_running();
2816 while (*macro != 0) {
2817 keep_running = core_keydown(*macro++, &enqueued, &repeat);
2818 if (*macro != 0 && !enqueued)
2819 keep_running = core_keyup();
2820 while (waitForProgram && keep_running)
2821 keep_running = core_keydown(0, &enqueued, &repeat);
2822 }
2823 repeat = 0;
2824 }
2825 }
2826 } else
2827 keep_running = core_keydown(ckey, &enqueued, &repeat);
2828
2829 if (quit_flag)
2830 quit();
2831 if (keep_running)
2832 enable_reminder();
2833 else {
2834 disable_reminder();
2835 if (timeout_id != 0)
2836 g_source_remove(timeout_id);
2837 if (repeat != 0)
2838 timeout_id = g_timeout_add(repeat == 1 ? 1000 : 500, repeater, NULL);
2839 else if (!enqueued)
2840 timeout_id = g_timeout_add(250, timeout1, NULL);
2841 }
2842 }
2843
2844 static void shell_keyup() {
2845 GdkWindow *win = gtk_widget_get_window(calc_widget);
2846 skin_invalidate_key(win, skey);
2847
2848 ckey = 0;
2849 skey = -1;
2850 if (timeout_id != 0) {
2851 g_source_remove(timeout_id);
2852 timeout_id = 0;
2853 }
2854 if (!enqueued) {
2855 bool keep_running = core_keyup();
2856 if (quit_flag)
2857 quit();
2858 if (keep_running)
2859 enable_reminder();
2860 else
2861 disable_reminder();
2862 }
2863 }
2864
2865 static gboolean button_cb(GtkWidget *w, GdkEventButton *event, gpointer cd) {
2866 if (event->type == GDK_BUTTON_PRESS) {
2867 if (ckey == 0) {
2868 int win_width, win_height, skin_width, skin_height;
2869 skin_get_window_size(&win_width, &win_height);
2870 skin_get_size(&skin_width, &skin_height);
2871 int x = (int) (event->x * skin_width / win_width);
2872 int y = (int) (event->y * skin_height / win_height);
2873 skin_find_key(x, y, ann_shift != 0, &skey, &ckey);
2874 if (ckey != 0) {
2875 macro = skin_find_macro(ckey, &macro_type);
2876 shell_keydown(ann_shift != 0);
2877 mouse_key = true;
2878 }
2879 }
2880 } else if (event->type == GDK_BUTTON_RELEASE) {
2881 if (ckey != 0 && mouse_key)
2882 shell_keyup();
2883 }
2884 return TRUE;
2885 }
2886
2887 static gboolean key_cb(GtkWidget *w, GdkEventKey *event, gpointer cd) {
2888 if (event->type == GDK_KEY_PRESS) {
2889 if (event->hardware_keycode == active_keycode)
2890 // Auto-repeat
2891 return TRUE;
2892 if (ckey == 0 || !mouse_key) {
2893 int i;
2894
2895 bool printable = event->length == 1 && event->string[0] >= 32 && event->string[0] <= 126;
2896 just_pressed_shift = false;
2897
2898 if (event->keyval == GDK_KEY_Shift_L || event->keyval == GDK_KEY_Shift_R) {
2899 just_pressed_shift = true;
2900 return TRUE;
2901 }
2902 bool ctrl = (event->state & GDK_CONTROL_MASK) != 0;
2903 bool alt = (event->state & GDK_MOD1_MASK) != 0;
2904 bool shift = (event->state & GDK_SHIFT_MASK) != 0;
2905 bool cshift = ann_shift != 0;
2906
2907 if (ckey != 0) {
2908 shell_keyup();
2909 active_keycode = 0;
2910 }
2911
2912 bool exact;
2913 unsigned char *key_macro = skin_keymap_lookup(event->keyval,
2914 printable, ctrl, alt, shift, cshift, &exact);
2915 if (key_macro == NULL || !exact) {
2916 for (i = 0; i < keymap_length; i++) {
2917 keymap_entry *entry = keymap + i;
2918 if (ctrl == entry->ctrl
2919 && alt == entry->alt
2920 && (printable || shift == entry->shift)
2921 && event->keyval == entry->keyval) {
2922 if (shift == entry->shift && cshift == entry->cshift) {
2923 key_macro = entry->macro;
2924 break;
2925 } else {
2926 if ((shift || !entry->shift) && (cshift || !entry->cshift) && key_macro == NULL)
2927 key_macro = entry->macro;
2928 }
2929 }
2930 }
2931 }
2932
2933 if (key_macro == NULL || (key_macro[0] != 36 || key_macro[1] != 0)
2934 && (key_macro[0] != 28 || key_macro[1] != 36 || key_macro[2] != 0)) {
2935 // The test above is to make sure that whatever mapping is in
2936 // effect for R/S will never be overridden by the special cases
2937 // for the ALPHA and A..F menus.
2938 if (!ctrl && !alt) {
2939 char c = event->string[0];
2940 if (printable && core_alpha_menu()) {
2941 if (c >= 'a' && c <= 'z')
2942 c = c + 'A' - 'a';
2943 else if (c >= 'A' && c <= 'Z')
2944 c = c + 'a' - 'A';
2945 ckey = 1024 + c;
2946 skey = -1;
2947 macro = NULL;
2948 shell_keydown(false);
2949 mouse_key = false;
2950 active_keycode = event->hardware_keycode;
2951 return TRUE;
2952 } else if (core_hex_menu() && ((c >= 'a' && c <= 'f')
2953 || (c >= 'A' && c <= 'F'))) {
2954 if (c >= 'a' && c <= 'f')
2955 ckey = c - 'a' + 1;
2956 else
2957 ckey = c - 'A' + 1;
2958 skey = -1;
2959 macro = NULL;
2960 shell_keydown(false);
2961 mouse_key = false;
2962 active_keycode = event->hardware_keycode;
2963 return TRUE;
2964 } else if (event->keyval == GDK_KEY_Left
2965 || event->keyval == GDK_KEY_Right
2966 || event->keyval == GDK_KEY_Delete) {
2967 int which;
2968 if (event->keyval == GDK_KEY_Left)
2969 which = shift ? 2 : 1;
2970 else if (event->keyval == GDK_KEY_Right)
2971 which = shift ? 4 : 3;
2972 else if (event->keyval == GDK_KEY_Delete)
2973 which = 5;
2974 else
2975 which = 0;
2976 if (which != 0) {
2977 which = core_special_menu_key(which);
2978 if (which != 0) {
2979 ckey = which;
2980 skey = -1;
2981 macro = NULL;
2982 shell_keydown(false);
2983 mouse_key = false;
2984 active_keycode = event->hardware_keycode;
2985 return TRUE;
2986 }
2987 }
2988 }
2989 }
2990 }
2991
2992 if (key_macro != NULL) {
2993 // A keymap entry is a sequence of zero or more calculator
2994 // keystrokes (1..37) and/or macros (38..255). We expand
2995 // macros here before invoking shell_keydown().
2996 // If the keymap entry is one key, or two keys with the
2997 // first being 'shift', we highlight the key in question
2998 // by setting ckey; otherwise, we set ckey to -10, which
2999 // means no skin key will be highlighted.
3000 ckey = -10;
3001 skey = -1;
3002 bool skin_shift = cshift;
3003 if (key_macro[0] != 0)
3004 if (key_macro[1] == 0)
3005 ckey = key_macro[0];
3006 else if (key_macro[2] == 0 && key_macro[0] == 28) {
3007 ckey = key_macro[1];
3008 skin_shift = true;
3009 }
3010 bool needs_expansion = false;
3011 for (int j = 0; key_macro[j] != 0; j++)
3012 if (key_macro[j] > 37) {
3013 needs_expansion = true;
3014 break;
3015 }
3016 if (needs_expansion) {
3017 static unsigned char macrobuf[1024];
3018 int p = 0;
3019 for (int j = 0; key_macro[j] != 0 && p < 1023; j++) {
3020 int c = key_macro[j];
3021 if (c <= 37)
3022 macrobuf[p++] = c;
3023 else {
3024 unsigned char *m = skin_find_macro(c, &macro_type);
3025 if (m != NULL)
3026 while (*m != 0 && p < 1023)
3027 macrobuf[p++] = *m++;
3028 }
3029 }
3030 macrobuf[p] = 0;
3031 macro = macrobuf;
3032 } else {
3033 macro = key_macro;
3034 macro_type = 0;
3035 }
3036 shell_keydown(skin_shift);
3037 mouse_key = false;
3038 active_keycode = event->hardware_keycode;
3039 }
3040 }
3041 } else if (event->type == GDK_KEY_RELEASE) {
3042 if (ckey == 0) {
3043 if (just_pressed_shift && (event->keyval == GDK_KEY_Shift_L
3044 || event->keyval == GDK_KEY_Shift_R)) {
3045 ckey = 28;
3046 skey = -1;
3047 macro = NULL;
3048 shell_keydown(false);
3049 shell_keyup();
3050 }
3051 } else {
3052 if (!mouse_key && event->hardware_keycode == active_keycode) {
3053 shell_keyup();
3054 active_keycode = 0;
3055 }
3056 }
3057 }
3058 return TRUE;
3059 }
3060
3061 static void enable_reminder() {
3062 if (reminder_id == 0)
3063 reminder_id = g_idle_add(reminder, NULL);
3064 if (timeout_id != 0) {
3065 g_source_remove(timeout_id);
3066 timeout_id = 0;
3067 }
3068 }
3069
3070 static void disable_reminder() {
3071 if (reminder_id != 0) {
3072 g_source_remove(reminder_id);
3073 reminder_id = 0;
3074 }
3075 }
3076
3077 static gboolean repeater(gpointer cd) {
3078 int repeat = core_repeat();
3079 if (repeat != 0)
3080 timeout_id = g_timeout_add(repeat == 1 ? 200 : 100, repeater, NULL);
3081 else
3082 timeout_id = g_timeout_add(250, timeout1, NULL);
3083 return FALSE;
3084 }
3085
3086 static gboolean timeout1(gpointer cd) {
3087 if (ckey != 0) {
3088 core_keytimeout1();
3089 timeout_id = g_timeout_add(1750, timeout2, NULL);
3090 } else
3091 timeout_id = 0;
3092 return FALSE;
3093 }
3094
3095 static gboolean timeout2(gpointer cd) {
3096 if (ckey != 0)
3097 core_keytimeout2();
3098 timeout_id = 0;
3099 return FALSE;
3100 }
3101
3102 static gboolean timeout3(gpointer cd) {
3103 bool keep_running = core_timeout3(true);
3104 timeout3_id = 0;
3105 if (keep_running)
3106 enable_reminder();
3107 return FALSE;
3108 }
3109
3110 static gboolean battery_checker(gpointer cd) {
3111 shell_low_battery();
3112 return TRUE;
3113 }
3114
3115 static void repaint_printout(cairo_t *cr, bool dark) {
3116 GdkRectangle clip;
3117 if (!gdk_cairo_get_clip_rectangle(cr, &clip))
3118 gtk_widget_get_allocation(print_widget, &clip);
3119
3120 GdkPixbuf *buf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE,
3121 8, clip.width, clip.height);
3122 int d_bpl = gdk_pixbuf_get_rowstride(buf);
3123 guchar *d1 = gdk_pixbuf_get_pixels(buf);
3124 int length = printout_bottom - printout_top;
3125 if (length < 0)
3126 length += PRINT_LINES;
3127
3128 for (int v = clip.y; v < clip.y + clip.height; v++) {
3129 int v2 = printout_top + v;
3130 if (v2 >= PRINT_LINES)
3131 v2 -= PRINT_LINES;
3132 int v3 = v2 * 36;
3133 guchar *dst = d1;
3134 for (int h = clip.x; h < clip.x + clip.width; h++) {
3135 unsigned char c;
3136 if (v >= length)
3137 c = dark ? 64 : 192;
3138 else if (h < 36 || h >= 322)
3139 c = dark ? 18 : 255;
3140 else if ((print_bitmap[v3 + ((h - 36) >> 3)] & (1 << ((h - 36) & 7))) == 0)
3141 c = dark ? 18 : 255;
3142 else
3143 c = dark ? 219 : 0;
3144 *dst++ = c;
3145 *dst++ = c;
3146 *dst++ = c;
3147 }
3148 d1 += d_bpl;
3149 }
3150
3151 gdk_cairo_set_source_pixbuf(cr, buf, clip.x, clip.y);
3152 cairo_paint(cr);
3153 g_object_unref(G_OBJECT(buf));
3154 }
3155
3156 static gboolean reminder(gpointer cd) {
3157 bool dummy1;
3158 int dummy2;
3159 bool keep_running = core_keydown(0, &dummy1, &dummy2);
3160 if (quit_flag)
3161 quit();
3162 if (keep_running)
3163 return TRUE;
3164 else {
3165 reminder_id = 0;
3166 return FALSE;
3167 }
3168 }
3169
3170 /* Callbacks used by shell_print() and shell_spool_txt() / shell_spool_gif() */
3171
3172 static void txt_writer(const char *text, int length) {
3173 int n;
3174 if (print_txt == NULL)
3175 return;
3176 n = fwrite(text, 1, length, print_txt);
3177 if (n != length) {
3178 char buf[1000];
3179 state.printerToTxtFile = 0;
3180 fclose(print_txt);
3181 print_txt = NULL;
3182 snprintf(buf, 1000, "Error while writing to \"%s\".\nPrinting to text file disabled", state.printerTxtFileName);
3183 show_message("Message", buf);
3184 }
3185 }
3186
3187 static void txt_newliner() {
3188 if (print_txt == NULL)
3189 return;
3190 fputc('\r', print_txt);
3191 fputc('\n', print_txt);
3192 fflush(print_txt);
3193 }
3194
3195 static void gif_seeker(int4 pos) {
3196 if (print_gif == NULL)
3197 return;
3198 if (fseek(print_gif, pos, SEEK_SET) == -1) {
3199 char buf[1000];
3200 state.printerToGifFile = 0;
3201 fclose(print_gif);
3202 print_gif = NULL;
3203 snprintf(buf, 1000, "Error while seeking \"%s\".\nPrinting to GIF file disabled", print_gif_name);
3204 show_message("Message", buf);
3205 }
3206 }
3207
3208 static void gif_writer(const char *text, int length) {
3209 int n;
3210 if (print_gif == NULL)
3211 return;
3212 n = fwrite(text, 1, length, print_gif);
3213 if (n != length) {
3214 char buf[1000];
3215 state.printerToGifFile = 0;
3216 fclose(print_gif);
3217 print_gif = NULL;
3218 snprintf(buf, 1000, "Error while writing to \"%s\".\nPrinting to GIF file disabled", print_gif_name);
3219 show_message("Message", buf);
3220 }
3221 }
3222
3223 void shell_blitter(const char *bits, int bytesperline, int x, int y,
3224 int width, int height) {
3225 if (state.old_repaint) {
3226 GdkWindow *win = gtk_widget_get_window(calc_widget);
3227
3228 skin_display_invalidater(win, bits, bytesperline, x, y, width, height);
3229 if (skey >= -7 && skey <= -2)
3230 skin_invalidate_key(win, skey);
3231 } else {
3232 skin_display_invalidater(NULL, bits, bytesperline, x, y, width, height);
3233 }
3234 }
3235
3236 void shell_beeper(int tone) {
3237 #ifdef AUDIO_ALSA
3238 const char *display_name = gdk_display_get_name(gdk_display_get_default());
3239 if (display_name == NULL || display_name[0] == ':' || strchr(display_name, ':') == NULL) {
3240 const int tone_freqs[] = { 165, 220, 247, 277, 294, 330, 370, 415, 440, 554, 1865 };
3241 int frequency = tone_freqs[tone];
3242 int duration = tone == 10 ? 125 : 250;
3243 if (!alsa_beeper(frequency, duration))
3244 gdk_display_beep(gdk_display_get_default());
3245 } else
3246 gdk_display_beep(gdk_display_get_default());
3247 #else
3248 gdk_display_beep(gdk_display_get_default());
3249 #endif
3250 }
3251
3252 static gboolean ann_print_timeout(gpointer cd) {
3253 GdkWindow *win = gtk_widget_get_window(calc_widget);
3254
3255 ann_print_timeout_id = 0;
3256 ann_print = 0;
3257 skin_invalidate_annunciator(win, 3);
3258
3259 return FALSE;
3260 }
3261
3262 const char *shell_platform() {
3263 return VERSION " " VERSION_PLATFORM;
3264 }
3265
3266 void shell_annunciators(int updn, int shf, int prt, int run, int g, int rad) {
3267 GdkWindow *win = gtk_widget_get_window(calc_widget);
3268
3269 if (updn != -1 && ann_updown != updn) {
3270 ann_updown = updn;
3271 skin_invalidate_annunciator(win, 1);
3272 }
3273 if (shf != -1 && ann_shift != shf) {
3274 ann_shift = shf;
3275 skin_invalidate_annunciator(win, 2);
3276 }
3277 if (prt != -1) {
3278 if (ann_print_timeout_id != 0) {
3279 g_source_remove(ann_print_timeout_id);
3280 ann_print_timeout_id = 0;
3281 }
3282 if (ann_print != prt)
3283 if (prt) {
3284 ann_print = 1;
3285 skin_invalidate_annunciator(win, 3);
3286 } else {
3287 ann_print_timeout_id = g_timeout_add(1000, ann_print_timeout, NULL);
3288 }
3289 }
3290 if (run != -1 && ann_run != run) {
3291 ann_run = run;
3292 skin_invalidate_annunciator(win, 4);
3293 }
3294 if (g != -1 && ann_g != g) {
3295 ann_g = g;
3296 skin_invalidate_annunciator(win, 6);
3297 }
3298 if (rad != -1 && ann_rad != rad) {
3299 ann_rad = rad;
3300 skin_invalidate_annunciator(win, 7);
3301 }
3302 }
3303
3304 bool shell_wants_cpu() {
3305 static uint4 lastCount = 0;
3306 struct timeval tv;
3307 gettimeofday(&tv, NULL);
3308 uint4 count = tv.tv_sec * 1000L + tv.tv_usec / 1000;
3309 if (count - lastCount < 10)
3310 return false;
3311 lastCount = count;
3312 return g_main_context_pending(NULL);
3313 }
3314
3315 void shell_delay(int duration) {
3316 gdk_display_flush(gdk_display_get_default());
3317 g_usleep(duration * 1000);
3318 }
3319
3320 void shell_request_timeout3(int delay) {
3321 if (timeout3_id != 0)
3322 g_source_remove(timeout3_id);
3323 timeout3_id = g_timeout_add(delay, timeout3, NULL);
3324 }
3325
3326 uint8 shell_get_mem() {
3327 FILE *meminfo = fopen("/proc/meminfo", "r");
3328 char line[1024];
3329 uint8 bytes = 0;
3330 if (meminfo == NULL)
3331 return 0;
3332 while (fgets(line, 1024, meminfo) != NULL) {
3333 if (strncmp(line, "MemFree:", 8) == 0) {
3334 uint8 kbytes;
3335 if (sscanf(line + 8, "%llu", &kbytes) == 1)
3336 bytes = 1024 * kbytes;
3337 break;
3338 }
3339 }
3340 fclose(meminfo);
3341 return bytes;
3342 }
3343
3344 bool shell_low_battery() {
3345
3346 int lowbat = 0;
3347 FILE *apm = fopen("/proc/apm", "r");
3348 if (apm != NULL) {
3349 /* /proc/apm partial legend:
3350 *
3351 * 1.16 1.2 0x03 0x01 0x03 0x09 9% -1 ?
3352 * ^^^^ ^^^^
3353 * | +-- Battery status (0 = full, 1 = low,
3354 * | 2 = critical, 3 = charging)
3355 * +------- AC status (0 = offline, 1 = online)
3356 */
3357 char line[1024];
3358 int ac_stat, bat_stat;
3359 if (fgets(line, 1024, apm) == NULL)
3360 goto done1;
3361 if (sscanf(line, "%*s %*s %*s %x %x", &ac_stat, &bat_stat) == 2)
3362 lowbat = ac_stat != 1 && (bat_stat == 1 || bat_stat == 2);
3363 done1:
3364 fclose(apm);
3365 } else {
3366 /* Battery considered low if
3367 *
3368 * /sys/class/power_supply/BATn/status == "Discharging"
3369 * and
3370 * /sys/class/power_supply/BATn/capacity <= 10
3371 *
3372 * Assuming status will always be "Discharging" when the system is
3373 * actually running on battery (it could also be "Full", but then it is
3374 * definitely not low!), and that capacity is a number between 0 and
3375 * 100. The choice of 10% or less as being "low" is completely
3376 * arbitrary.
3377 * Checking BATn where n = 0, 1, or 2. Some docs suggest BAT0 should
3378 * exist, others suggest 1 should exist; I'm playing safe and trying
3379 * both, and throwing in BAT2 just for the fun of it.
3380 */
3381 char status_filename[50];
3382 char capacity_filename[50];
3383 char line[50];
3384 for (int n = 0; n <= 2; n++) {
3385 snprintf(status_filename, 50, "/sys/class/power_supply/BAT%d/status", n);
3386 FILE *status_file = fopen(status_filename, "r");
3387 if (status_file == NULL)
3388 continue;
3389 snprintf(capacity_filename, 50, "/sys/class/power_supply/BAT%d/capacity", n);
3390 FILE *capacity_file = fopen(capacity_filename, "r");
3391 if (capacity_file == NULL) {
3392 fclose(status_file);
3393 continue;
3394 }
3395 bool discharging = fgets(line, 50, status_file) != NULL && strncasecmp(line, "discharging", 11) == 0;
3396 int capacity;
3397 if (fscanf(capacity_file, "%d", &capacity) != 1)
3398 capacity = 100;
3399 fclose(status_file);
3400 fclose(capacity_file);
3401 lowbat = discharging && capacity <= 10;
3402 break;
3403 }
3404 }
3405 if (lowbat != ann_battery) {
3406 ann_battery = lowbat;
3407 if (allow_paint) {
3408 GdkWindow *win = gtk_widget_get_window(calc_widget);
3409 skin_invalidate_annunciator(win, 5);
3410 }
3411 }
3412 return lowbat != 0;
3413 }
3414
3415 void shell_powerdown() {
3416 /* We defer the actual shutdown so the emulator core can
3417 * return from core_keyup() or core_keydown() and isn't
3418 * asked to save its state while still in the middle of
3419 * executing the OFF instruction...
3420 */
3421 quit_flag = true;
3422 }
3423
3424 void shell_message(const char *message) {
3425 show_message("Core", message);
3426 }
3427
3428 int8 shell_random_seed() {
3429 struct timeval tv;
3430 gettimeofday(&tv, NULL);
3431 return tv.tv_sec * 1000LL + tv.tv_usec / 1000;
3432 }
3433
3434 uint4 shell_milliseconds() {
3435 struct timeval tv;
3436 gettimeofday(&tv, NULL);
3437 return (uint4) (tv.tv_sec * 1000L + tv.tv_usec / 1000);
3438 }
3439
3440 const char *shell_number_format() {
3441 return cached_number_format;
3442 }
3443
3444 int shell_date_format() {
3445 struct tm t;
3446 t.tm_sec = 0;
3447 t.tm_min = 0;
3448 t.tm_hour = 0;
3449 t.tm_mday = 22; // 22
3450 t.tm_mon = 10; // 11
3451 t.tm_year = 1433; // 3333
3452 t.tm_wday = 0;
3453 t.tm_yday = 0;
3454 t.tm_isdst = 0;
3455
3456 char buf[32];
3457 strftime(buf, 32, "%x", &t);
3458
3459 int y = strstr(buf, "3") - buf;
3460 int m = strstr(buf, "1") - buf;
3461 int d = strstr(buf, "2") - buf;
3462
3463 if (d < m && m < y)
3464 return 1;
3465 else if (y < m && m < d)
3466 return 2;
3467 else
3468 return 0;
3469 }
3470
3471 bool shell_clk24() {
3472 struct tm t;
3473 t.tm_sec = 0;
3474 t.tm_min = 0;
3475 t.tm_hour = 0;
3476 t.tm_mday = 22; // 22
3477 t.tm_mon = 10; // 11
3478 t.tm_year = 1433; // 3333
3479 t.tm_wday = 0;
3480 t.tm_yday = 0;
3481 t.tm_isdst = 0;
3482
3483 char buf[32];
3484 strftime(buf, 32, "%X", &t);
3485
3486 return strstr(buf, "A") == NULL;
3487 }
3488
3489 struct print_growth_info {
3490 int y, height;
3491 print_growth_info(int yy, int hheight) : y(yy), height(hheight) {}
3492 };
3493
3494 static gboolean print_widget_grew(GtkWidget *w, GdkEventConfigure *event,
3495 gpointer cd) {
3496 print_growth_info *info = (print_growth_info *) cd;
3497 scroll_printout_to_bottom();
3498 GdkRectangle clip;
3499 clip.x = 0;
3500 clip.y = info->y;
3501 clip.width = 358;
3502 clip.height = info->height;
3503 GdkWindow *win = gtk_widget_get_window(print_widget);
3504 gdk_window_invalidate_rect(win, &clip, FALSE);
3505 g_signal_handlers_disconnect_by_func(G_OBJECT(w), (gpointer) print_widget_grew, cd);
3506 delete info;
3507 return FALSE;
3508 }
3509
3510 void shell_print(const char *text, int length,
3511 const char *bits, int bytesperline,
3512 int x, int y, int width, int height) {
3513 int xx, yy;
3514 int oldlength, newlength;
3515
3516 for (yy = 0; yy < height; yy++) {
3517 int4 Y = (printout_bottom + 2 * yy) % PRINT_LINES;
3518 for (xx = 0; xx < 143; xx++) {
3519 int bit, px, py;
3520 if (xx < width) {
3521 char c = bits[(y + yy) * bytesperline + ((x + xx) >> 3)];
3522 bit = (c & (1 << ((x + xx) & 7))) != 0;
3523 } else
3524 bit = 0;
3525 for (px = xx * 2; px < (xx + 1) * 2; px++)
3526 for (py = Y; py < Y + 2; py++)
3527 if (bit)
3528 print_bitmap[py * PRINT_BYTESPERLINE + (px >> 3)]
3529 |= 1 << (px & 7);
3530 else
3531 print_bitmap[py * PRINT_BYTESPERLINE + (px >> 3)]
3532 &= ~(1 << (px & 7));
3533 }
3534 }
3535
3536 oldlength = printout_bottom - printout_top;
3537 if (oldlength < 0)
3538 oldlength += PRINT_LINES;
3539 printout_bottom = (printout_bottom + 2 * height) % PRINT_LINES;
3540 newlength = oldlength + 2 * height;
3541
3542 if (newlength >= PRINT_LINES) {
3543 printout_top = (printout_bottom + 2) % PRINT_LINES;
3544 newlength = PRINT_LINES - 2;
3545 if (newlength != oldlength)
3546 gtk_widget_set_size_request(print_widget, 358, newlength);
3547 scroll_printout_to_bottom();
3548 gtk_widget_queue_draw(print_widget);
3549 } else {
3550 gtk_widget_set_size_request(print_widget, 358, newlength);
3551 // The resize request does not take effect immediately;
3552 // if I call scroll_printout_to_bottom() now, the scrolling will take
3553 // place *before* the resizing, leaving the scroll bar in the wrong
3554 // position.
3555 // I work around this by using a callback to finish the job.
3556 g_signal_connect(G_OBJECT(print_widget), "configure-event",
3557 G_CALLBACK(print_widget_grew),
3558 (gpointer) new print_growth_info(oldlength, 2 * height));
3559 }
3560
3561 if (state.printerToTxtFile) {
3562 int err;
3563 char buf[1000];
3564
3565 if (print_txt == NULL) {
3566 print_txt = fopen(state.printerTxtFileName, "a");
3567 if (print_txt == NULL) {
3568 err = errno;
3569 state.printerToTxtFile = 0;
3570 snprintf(buf, 1000, "Can't open \"%s\" for output:\n%s (%d)\nPrinting to text file disabled.", state.printerTxtFileName, strerror(err), err);
3571 show_message("Message", buf);
3572 goto done_print_txt;
3573 }
3574 }
3575
3576 if (text != NULL)
3577 shell_spool_txt(text, length, txt_writer, txt_newliner);
3578 else
3579 shell_spool_bitmap_to_txt(bits, bytesperline, x, y, width, height, txt_writer, txt_newliner);
3580 done_print_txt:;
3581 }
3582
3583 if (state.printerToGifFile) {
3584 int err;
3585 char buf[1000];
3586
3587 if (print_gif != NULL
3588 && gif_lines + height > state.printerGifMaxLength) {
3589 shell_finish_gif(gif_seeker, gif_writer);
3590 fclose(print_gif);
3591 print_gif = NULL;
3592 }
3593
3594 if (print_gif == NULL) {
3595 while (1) {
3596 int len, p;
3597
3598 gif_seq = (gif_seq + 1) % 10000;
3599
3600 strcpy(print_gif_name, state.printerGifFileName);
3601 len = strlen(print_gif_name);
3602
3603 /* Strip ".gif" extension, if present */
3604 if (len >= 4 &&
3605 strcasecmp(print_gif_name + len - 4, ".gif") == 0) {
3606 len -= 4;
3607 print_gif_name[len] = 0;
3608 }
3609
3610 /* Strip ".[0-9]+", if present */
3611 p = len;
3612 while (p > 0 && print_gif_name[p] >= '0'
3613 && print_gif_name[p] <= '9')
3614 p--;
3615 if (p < len && p >= 0 && print_gif_name[p] == '.')
3616 print_gif_name[p] = 0;
3617
3618 /* Make sure we have enough space for the ".nnnn.gif" */
3619 p = FILENAMELEN - 10;
3620 print_gif_name[p] = 0;
3621 p = strlen(print_gif_name);
3622 snprintf(print_gif_name + p, 6, ".%04d", gif_seq);
3623 strcat(print_gif_name, ".gif");
3624
3625 if (!file_exists(print_gif_name))
3626 break;
3627 }
3628 print_gif = fopen(print_gif_name, "w+");
3629 if (print_gif == NULL) {
3630 err = errno;
3631 state.printerToGifFile = 0;
3632 snprintf(buf, 1000, "Can't open \"%s\" for output:\n%s (%d)\nPrinting to GIF file disabled.", print_gif_name, strerror(err), err);
3633 show_message("Message", buf);
3634 goto done_print_gif;
3635 }
3636 if (!shell_start_gif(gif_writer, 143, state.printerGifMaxLength)) {
3637 state.printerToGifFile = 0;
3638 show_message("Message", "Not enough memory for the GIF encoder.\nPrinting to GIF file disabled.");
3639 goto done_print_gif;
3640 }
3641 gif_lines = 0;
3642 }
3643
3644 shell_spool_gif(bits, bytesperline, x, y, width, height, gif_writer);
3645 gif_lines += height;
3646
3647 if (print_gif != NULL && gif_lines + 9 > state.printerGifMaxLength) {
3648 shell_finish_gif(gif_seeker, gif_writer);
3649 fclose(print_gif);
3650 print_gif = NULL;
3651 }
3652 done_print_gif:;
3653 }
3654
3655 print_text[print_text_bottom++] = (char) (text == NULL ? 255 : length);
3656 if (print_text_bottom == PRINT_TEXT_SIZE)
3657 print_text_bottom = 0;
3658 if (text != NULL) {
3659 if (print_text_bottom + length < PRINT_TEXT_SIZE) {
3660 memcpy(print_text + print_text_bottom, text, length);
3661 print_text_bottom += length;
3662 } else {
3663 int part = PRINT_TEXT_SIZE - print_text_bottom;
3664 memcpy(print_text + print_text_bottom, text, part);
3665 memcpy(print_text, text + part, length - part);
3666 print_text_bottom = length - part;
3667 }
3668 }
3669 print_text_pixel_height += text == NULL ? 16 : 9;
3670 while (print_text_pixel_height > PRINT_LINES / 2 - 1) {
3671 int tll = print_text[print_text_top] == 255 ? 16 : 9;
3672 print_text_pixel_height -= tll;
3673 print_text_top += tll == 16 ? 1 : (print_text[print_text_top] + 1);
3674 if (print_text_top >= PRINT_TEXT_SIZE)
3675 print_text_top -= PRINT_TEXT_SIZE;
3676 }
3677 }
3678
3679 static FILE *logfile = NULL;
3680
3681 void shell_log(const char *message) {
3682 if (logfile == NULL)
3683 logfile = fopen("free42.log", "w");
3684 fprintf(logfile, "%s\n", message);
3685 fflush(logfile);
3686 }
3687
3688 void shell_get_time_date(uint4 *time, uint4 *date, int *weekday) {
3689 struct timeval tv;
3690 gettimeofday(&tv, NULL);
3691 struct tm tms;
3692 localtime_r(&tv.tv_sec, &tms);
3693 if (time != NULL)
3694 *time = ((tms.tm_hour * 100 + tms.tm_min) * 100 + tms.tm_sec) * 100 + tv.tv_usec / 10000;
3695 if (date != NULL)
3696 *date = ((tms.tm_year + 1900) * 100 + tms.tm_mon + 1) * 100 + tms.tm_mday;
3697 if (weekday != NULL)
3698 *weekday = tms.tm_wday;
3699 }