-
Notifications
You must be signed in to change notification settings - Fork 0
/
frontend.c
592 lines (515 loc) · 17.3 KB
/
frontend.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/* Collascii - a canvas-based collaborative ascii text editor.
*
* ___ ___ _ _ _ ___ ___ ___ ___
* / __/ _ \| | | | /_\ / __|/ __|_ _|_ _|
* | (_| (_) | |__| |__ / _ \\__ \ (__ | | | |
* \___\___/|____|____/_/ \_\___/\___|___|___|
*
* The Future Editor of Yesterday, Tomorrow!
*
* By Matthew Beaudouin-Lafon, Evan New-Schmidt, Adam Novotny
*
* General layout of interface:
* +------------------------------------------+ canvas_win
* | 0 -- X, COLS |
* | | |
* | Y, ROWS |
* | |
* | |
* | |
* | |
* | |
* | |
* +------------------------------------------+ status_interface/status_win:
* |Saved to file "art.txt" [INSERT](2,6)WxH| msg_win info_win
* |step: ON, transparent: OFF | mode_win
* +------------------------------------------+
*
* What all these "wins" are:
* - canvas_win: where the ascii canvas is drawn
* - status_interface: grouping of all status-related wins, which live in
* - status_win:
* - msg_win: displays general messages to user
* - info_win: state-specific info (see update_info_win)
* - mode_win: mode-specific information
*/
#include "frontend.h"
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "canvas.h"
#include "cursor.h"
#include "fe_modes.h"
#include "mode_id.h"
#include "network.h"
#include "state.h"
#include "util.h"
WINDOW *canvas_win;
status_interface_t *status_interface;
Cursor *cursor;
View *view;
bool networked = false;
int INFO_WIDTH = 24; // max width of the info window
char *DEFAULT_FILEPATH = "art.txt";
// signals to be caught with finish() function
int caught_signals[] = {SIGINT, SIGTERM, SIGKILL, SIGABRT,
SIGSEGV, SIGQUIT, SIGSTOP};
// #define LOG_TO_FILE // redirect stderr to "out.txt"
// mouse movements options (only use one)
// #define ENABLE_MOUSE_MOVEMENT 1003 // all move updates
#define ENABLE_MOUSE_MOVEMENT 1002 // move updates when buttons are pressed
// #define ENABLE_MOUSE_MOVEMENT 0 // don't send any charcodes
#ifdef DEBUG
#define LOG_TO_FILE
#endif
#ifdef LOG_TO_FILE
char *logfile_path = "out.txt";
FILE *logfile = NULL;
#endif
int main(int argc, char *argv[]) {
// setup finish() signal handler
for (int i = 0; i < sizeof(caught_signals) / sizeof(int); i++) {
signal(caught_signals[i], finish);
}
#ifdef LOG_TO_FILE
logfile = fopen(logfile_path, "a");
if (logfile == NULL) {
perror("logfile fopen:");
exit(1);
}
if (-1 == dup2(fileno(logfile), fileno(stderr))) {
perror("stderr dup2:");
exit(1);
}
#endif
logd("Starting frontend\n");
// init canvas from file
// run before ncurses init so stdin will read correctly
Canvas *canvas;
// load canvas from file if argument exists
char *in_filename = "";
fd_set testfds;
int fd;
Net_cfg *net_cfg;
if (argc > 1) {
/* If connecting to server */
if (!strcmp(argv[1], "-s")) {
networked = true;
if (argc == 3) {
canvas = net_init(argv[2], "");
} else if (argc == 4) {
canvas = net_init(argv[2], argv[3]);
} else {
printf("Usage:\ncollascii [filename]\ncollascii -s hostname [port]\n");
exit(1);
}
net_cfg = net_getcfg();
/* If reading from std in */
} else if (strcmp(argv[1], "-") == 0) {
// read from stdin if specified
logd("Reading from stdin\n");
canvas = canvas_readf_norewind(stdin);
// reopen stdin b/c EOF has been sent
// `/dev/tty` points to current terminal
// note that this is NOT portable
freopen("/dev/tty", "rw", stdin);
/* If reading from file */
} else {
in_filename = argv[1];
FILE *f = fopen(in_filename, "r");
logd("Reading from '%s'\n", in_filename);
if (f == NULL) {
printf("cannot read file %s\n", in_filename);
printf("Usage:\ncollascii [filename]\ncollascii -s hostname [port]\n");
exit(1);
}
canvas = canvas_readf(f);
fclose(f);
}
// canvas_resize(&canvas, 100, 100);
} else {
logd("making blank canvas\n");
canvas = canvas_new_blank(100, 100);
}
/* initialize your non-curses data structures here */
(void)initscr(); /* initialize the curses library */
keypad(stdscr, TRUE); /* enable keyboard mapping */
(void)nonl(); /* tell curses not to do NL->CR/NL on output */
(void)cbreak(); /* take input chars one at a time, no wait for \n */
(void)noecho(); /* don't print on getch() */
curs_set(2);
define_key("\r", KEY_ENTER); // Bind the <Enter> key properly
if (has_colors()) {
setup_colors();
}
// ENABLE MOUSE INPUT
// grab only mouse movement and left mouse press/release
mmask_t mmask = BUTTON1_PRESSED | BUTTON1_RELEASED;
#ifdef ENABLE_MOUSE_MOVEMENT
mmask |= REPORT_MOUSE_POSITION;
#endif
mmask_t return_mask = mousemask(mmask, NULL);
logd("Returned mouse mask: %li\n", return_mask);
// get mouse updates faster at the expense of not registering "clicks"
mouseinterval(0);
#ifdef ENABLE_MOUSE_MOVEMENT
// Make the terminal report mouse movement events, in a not-great way.
// Printing the escape code should bump it into `1003` mode, where an update
// is sent whenever the mouse moves between cells. Also of note: `1002` only
// sends movement updates when a mouse button is held down. Supposedly you can
// configure this in xterm, but I couldn't get it working.
// The $TERM variable should show some info about what mode is emulated.
// Running `cat -v` in a shell will show the escaped character codes that are
// sent and reveal if your shell is configured to send mouse input.
// https://gist.github.com/sylt/93d3f7b77e7f3a881603
// https://stackoverflow.com/q/29020638
// https://stackoverflow.com/q/7462850
//
// disabling mouse event charcodes is done in finish()
if (ENABLE_MOUSE_MOVEMENT == 1002) {
printf("\033[?1002h\n");
} else if (ENABLE_MOUSE_MOVEMENT == 1003) {
printf("\033[?1003h\n");
}
#endif
canvas_win = create_canvas_win();
status_interface = create_status_interface();
cursor = cursor_new();
Cursor *last_cursor = cursor_new();
view = view_new_startpos(canvas, 0, 0);
// Enable keyboard mapping
keypad(canvas_win, TRUE);
keypad(status_interface->status_win, TRUE);
//// Main loop
State new_state = {
.ch_in = OK,
.cursor = cursor,
// .current_mode = MODE_PICKER,
.current_mode = MODE_INSERT,
// .current_mode = MODE_FREE_LINE,
// .current_mode = MODE_BRUSH,
.last_arrow_direction = KEY_RIGHT,
.last_canvas_mode = MODE_INSERT,
.view = view,
.last_cursor = last_cursor,
.filepath = in_filename[0] == '\0' ? DEFAULT_FILEPATH : in_filename,
};
State *state = &new_state;
// update the screen size first. This clears the status window on any changes
// (including the first time it's run), so refreshing after updating the
// status will clear it otherwise
update_screen_size();
#ifdef DEBUG
mvwprintw(status_interface->msg_win, 0, 0, "MSG (debug)");
mvwprintw(status_interface->info_win, 0, 0, "INFO (debug)");
mvwprintw(status_interface->mode_win, 0, 0, "MODE (debug)");
#endif
char welcome_msg[] = "COLLASCII: <TAB> to switch modes, <CTRL-C> to quit";
print_msg_win(welcome_msg);
// bootstrap initial UI
call_mode(state->current_mode, START, state);
update_info_win_state(state);
// Move cursor to starting location and redraw canvases
refresh_screen();
// If connected to server, check both network and keyboard streams
if (networked) {
logd("Running networked loop\n");
while (1) {
testfds = net_cfg->clientfds;
select(FD_SETSIZE, &testfds, NULL, NULL, NULL);
for (fd = 0; fd < FD_SETSIZE; fd++) {
if (FD_ISSET(fd, &testfds)) {
if (networked &&
fd == net_cfg->sockfd) { // Accept data from open socket
logd("recv network\n");
// If server disconnects
if (net_handler(view) != 0) {
networked = false;
print_msg_win("Server Disconnect!");
};
redraw_canvas_win(); // TODO: draw single char update
refresh_screen();
} else if (fd == 0) { // process keyboard activity
master_handler(state, canvas_win, status_interface->info_win);
refresh_screen();
}
}
}
}
// If local, process keyboard stream
} else {
logd("Running local loop\n");
while (1) {
master_handler(state, canvas_win, status_interface->info_win);
refresh_screen();
}
}
// Cleanup
cursor_free(cursor);
destroy_status_interface(status_interface);
destroy_win(canvas_win);
finish(0);
}
void setup_colors() {
start_color();
// TODO: Use #define to get colors for standard uses
// Assign color codes
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_BLUE, COLOR_BLACK);
init_pair(4, COLOR_CYAN, COLOR_BLACK);
init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
init_pair(6, COLOR_YELLOW, COLOR_BLACK);
init_pair(7, COLOR_BLACK, COLOR_WHITE);
}
/* Update canvas with character at cursor current position.
*
* Changes the canvas and updates the ncurses `canvas_win` with the change.
*/
void front_setcharcursor(char ch) {
canvas_scharyx(view->canvas, cursor->y + view->y, cursor->x + view->x, ch);
mvwaddch(canvas_win, cursor_y_to_canvas(cursor), cursor_x_to_canvas(cursor),
ch);
if (networked) {
net_send_char(cursor->y + view->y, cursor->x + view->x, ch);
}
}
void redraw_canvas_win() {
// find max ranges to draw canvas
int max_x = view_max_x;
int max_y = view_max_y;
if (max_x >= view->canvas->num_cols - view->x)
(max_x = view->canvas->num_cols - view->x);
if (max_y >= view->canvas->num_rows - view->y)
(max_y = view->canvas->num_rows - view->y);
// draw canvas onto window
for (int x = 0; x < max_x; x++) {
for (int y = 0; y < max_y; y++) {
mvwaddch(canvas_win, y + 1, x + 1,
canvas_gcharyx(view->canvas, y + view->y, x + view->x));
}
}
// draw fill in rest of window
for (int x = max_x; x < view_max_x; x++) {
for (int y = 0; y < view_max_y; y++) {
mvwaddch(canvas_win, y + 1, x + 1, ACS_CKBOARD);
}
}
for (int y = max_y; y < view_max_y; y++) {
for (int x = 0; x < max_x; x++) {
mvwaddch(canvas_win, y + 1, x + 1, ACS_CKBOARD);
}
}
}
void refresh_screen() {
update_screen_size();
wmove(canvas_win, cursor_y_to_canvas(cursor), cursor_x_to_canvas(cursor));
wrefresh(status_interface->msg_win);
wrefresh(status_interface->info_win);
wrefresh(status_interface->mode_win);
wrefresh(canvas_win); // Refresh Canvas last so it gets the cursor
}
void update_screen_size() {
static int window_h_old, window_w_old;
int window_h_new, window_w_new;
getmaxyx(stdscr, window_h_new, window_w_new);
if (window_h_new != window_h_old || window_w_new != window_w_old) {
window_h_old = window_h_new;
window_w_old = window_w_new;
wresize(canvas_win, window_h_new - (STATUS_HEIGHT + 1), window_w_new);
wclear(stdscr);
wclear(canvas_win);
destroy_status_interface(status_interface);
status_interface = create_status_interface();
// Redraw borders
wborder(status_interface->status_win, ACS_VLINE, ACS_VLINE, ACS_HLINE,
ACS_HLINE, // Sides: ls, rs, ts, bs,
ACS_LTEE, ACS_RTEE, ACS_LLCORNER,
ACS_LRCORNER); // Corners: tl, tr, bl, br
wborder(canvas_win, ACS_VLINE, ACS_VLINE, ACS_HLINE,
ACS_HLINE, // Sides: ls, rs, ts, bs,
ACS_ULCORNER, ACS_URCORNER, ACS_LTEE,
ACS_RTEE); // Corners: tl, tr, bl, br
// Move cursor inside the canvas
if (cursor->x >= view_max_x) {
cursor->x = view_max_x;
}
if (cursor->y >= view_max_y) {
cursor->y = view_max_y;
}
redraw_canvas_win();
}
}
WINDOW *create_canvas_win() {
WINDOW *local_win;
// + 1 due to bottom border
local_win = newwin(LINES - (STATUS_HEIGHT + 1), COLS, 0, 0);
wborder(local_win, ACS_VLINE, ACS_VLINE, ACS_HLINE,
ACS_HLINE, // Sides: ls, rs, ts, bs,
ACS_ULCORNER, ACS_URCORNER, ACS_LTEE,
ACS_RTEE); // Corners: tl, tr, bl, br
wrefresh(local_win);
return local_win;
}
WINDOW *create_status_win() {
WINDOW *local_win;
// + 2 due to horizontal borders
local_win = newwin(STATUS_HEIGHT + 2, COLS, LINES - (STATUS_HEIGHT + 2), 0);
wborder(local_win, ACS_VLINE, ACS_VLINE, ACS_HLINE,
ACS_HLINE, // Sides: ls, rs, ts, bs,
ACS_LTEE, ACS_RTEE, ACS_LLCORNER,
ACS_LRCORNER); // Corners: tl, tr, bl, br
wrefresh(local_win);
return local_win;
}
WINDOW *create_msg_win(WINDOW *status_win) {
int sw = getmaxx(status_win) + 1;
int x, y;
getbegyx(status_win, y, x);
return newwin(1, sw - 2 - INFO_WIDTH, y + 1, x + 1);
}
WINDOW *create_info_win(WINDOW *status_win) {
int sw = getmaxx(status_win) + 1;
int x, y;
getbegyx(status_win, y, x);
return newwin(1, INFO_WIDTH, y + 1, x + 1 + sw - INFO_WIDTH - 3);
}
WINDOW *create_mode_win(WINDOW *status_win) {
int sw = getmaxx(status_win) + 1;
int x, y;
getbegyx(status_win, y, x);
return newwin(1, sw - 3, y + 2, x + 1);
}
status_interface_t *create_status_interface() {
WINDOW *sw = create_status_win();
status_interface_t *si = malloc(sizeof(status_interface_t));
*si = (status_interface_t){
.status_win = sw,
.msg_win = create_msg_win(sw),
.info_win = create_info_win(sw),
.mode_win = create_mode_win(sw),
};
wborder(si->status_win, ACS_VLINE, ACS_VLINE, ACS_HLINE,
ACS_HLINE, // Sides: ls, rs, ts, bs,
ACS_LTEE, ACS_RTEE, ACS_LLCORNER,
ACS_LRCORNER); // Corners: tl, tr, bl, br
return si;
}
void destroy_status_interface(status_interface_t *si) {
destroy_win(si->msg_win);
destroy_win(si->info_win);
destroy_win(si->mode_win);
destroy_win(si->status_win);
free(si);
}
void destroy_win(WINDOW *local_win) {
// Clear borders explicitly
wborder(local_win, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
wrefresh(local_win);
delwin(local_win);
}
/* Prints to status_win, similar to printf
*/
int print_msg_win(char *format, ...) {
// there isn't a va_list version of mvw_printw, so move to status_win first
// and then use vw_printw
WINDOW *mw = status_interface->msg_win;
wclear(mw);
wmove(mw, 0, 0);
va_list argp;
va_start(argp, format);
int res = vw_printw(mw, format, argp);
va_end(argp);
return res;
}
/* Prints to status_win, similar to printf
*/
int print_info_win(char *format, ...) {
// there isn't a va_list version of mvw_printw, so move to status_win first
// and then use vw_printw
WINDOW *mw = status_interface->info_win;
wclear(mw);
wmove(mw, 0, 0);
va_list argp;
va_start(argp, format);
int res = vw_printw(mw, format, argp);
va_end(argp);
return res;
}
/* Prints to status_win, similar to printf
*/
int print_mode_win(char *format, ...) {
// there isn't a va_list version of mvw_printw, so move to status_win first
// and then use vw_printw
WINDOW *mw = status_interface->mode_win;
wclear(mw);
wmove(mw, 0, 0);
va_list argp;
va_start(argp, format);
int res = vw_printw(mw, format, argp);
va_end(argp);
return res;
}
/* Reverse-video the text starting at x in mode window, for num_ch characters.
*/
void highlight_mode_text(int x, int num_ch) {
mvwchgat(status_interface->mode_win, 0, x, num_ch, A_REVERSE, 0, NULL);
}
/* Update the info subwindow in status_win with relevant info.
*
* Prints the current mode, cursor coordinates, and canvas dimensions
* right-aligned.
*
* "[MODE] (X,Y) WxH"
*/
void update_info_win(const Mode_ID current_mode, const int x, const int y,
const int w, const int h) {
WINDOW *mw = status_interface->info_win;
char buffer[INFO_WIDTH + 1];
const char *mode_name = modes[current_mode].name;
int width = snprintf(buffer, INFO_WIDTH + 1, "[%s](%i,%i)%ix%i", mode_name, x,
y, w, h);
wclear(mw);
wmove(mw, 0, INFO_WIDTH - width);
waddnstr(mw, buffer, INFO_WIDTH);
}
/* Signal handler for exiting
*
* Turns of ncurses, disables mouse moves commands, closes the logfile.
*
* If sig is 0 or SIGINT, exits normally, otherwise prints the signal
* information to stderr and exits with sig.
*/
void finish(int sig) {
endwin();
// Disable mouse events charcode
#ifdef ENABLE_MOUSE_MOVEMENT
if (ENABLE_MOUSE_MOVEMENT == 1002) {
printf("\033[?1002l\n");
} else if (ENABLE_MOUSE_MOVEMENT == 1003) {
printf("\033[?1003l\n");
}
#endif
/* do your non-curses wrapup here */
#ifdef LOG_TO_FILE
if (logfile != NULL) {
fclose(logfile);
}
#endif
// decide how to exit based on signal
switch (sig) {
case 0: // normal
case SIGINT: // user CTRL-C
eprintf("Exiting\n");
exit(0);
break;
default: // problems
eprintf("Exited with signal %d (%s)\n", sig, strsignal(sig));
exit(sig);
break;
}
}