summaryrefslogtreecommitdiffstats
path: root/terminal.c
blob: 05cdaa1c415bacf481778e45ad71592e208e01f5 (plain)
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/*
 * Copyright © 2008 Kristian Høgsberg
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that copyright
 * notice and this permission notice appear in supporting documentation, and
 * that the name of the copyright holders not be used in advertising or
 * publicity pertaining to distribution of the software without specific,
 * written prior permission.  The copyright holders make no representations
 * about the suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
 * OF THIS SOFTWARE.
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <pty.h>
#include <ctype.h>
#include <cairo.h>
#include <glib.h>
#include <linux/input.h>
#include <cairo-drm.h>

#include "wayland-util.h"
#include "wayland-client.h"
#include "wayland-glib.h"

#include "window.h"

static int option_fullscreen;
static const char gem_device[] = "/dev/dri/card0";
static const char socket_name[] = "\0wayland";

#define MOD_SHIFT	0x01
#define MOD_ALT		0x02
#define MOD_CTRL	0x04

struct terminal {
	struct window *window;
	struct display *display;
	struct wl_compositor *compositor;
	int redraw_scheduled, redraw_pending;
	char *data;
	int width, height, start, row, column;
	int fd, master;
	GIOChannel *channel;
	uint32_t modifiers;
	char escape[64];
	int escape_length;
	int state;
	int margin;
	int fullscreen;
	int focused;
	struct color_scheme *color_scheme;
};

static char *
terminal_get_row(struct terminal *terminal, int row)
{
	int index;

	index = (row + terminal->start) % terminal->height;

	return &terminal->data[index * (terminal->width + 1)];
}

static void
terminal_resize(struct terminal *terminal, int width, int height)
{
	size_t size;
	char *data;
	int i, l, total_rows, start;

	if (terminal->width == width && terminal->height == height)
		return;

	size = (width + 1) * height;
	data = malloc(size);
	memset(data, 0, size);
	if (terminal->data) {
		if (width > terminal->width)
			l = terminal->width;
		else
			l = width;

		if (terminal->height > height) {
			total_rows = height;
			start = terminal->height - height;
		} else {
			total_rows = terminal->height;
			start = 0;
		}

		for (i = 0; i < total_rows; i++)
			memcpy(data + (width + 1) * i,
			       terminal_get_row(terminal, i), l);

		free(terminal->data);
	}

	terminal->width = width;
	terminal->height = height;
	terminal->data = data;

	if (terminal->row >= terminal->height)
		terminal->row = terminal->height - 1;
	if (terminal->column >= terminal->width)
		terminal->column = terminal->width - 1;
	terminal->start = 0;
}

struct color_scheme { struct { double r, g, b, a; } fg, bg; }
	matrix_colors = { { 0, 0.7, 0, 1 }, { 0, 0, 0, 0.9 } },
	jbarnes_colors = { { 1, 1, 1, 1 }, { 0, 0, 0, 1 } };

static void
terminal_draw_contents(struct terminal *terminal)
{
	struct rectangle rectangle;
	cairo_t *cr;
	cairo_font_extents_t extents;
	int i, top_margin, side_margin;
	cairo_surface_t *surface;
	double d;

	window_get_child_rectangle(terminal->window, &rectangle);

	surface = window_create_surface(terminal->window, &rectangle);
	cr = cairo_create(surface);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_set_source_rgba(cr,
			      terminal->color_scheme->bg.r,
			      terminal->color_scheme->bg.g,
			      terminal->color_scheme->bg.b,
			      terminal->color_scheme->bg.a);
	cairo_paint(cr);
	cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
	cairo_set_source_rgba(cr,
			      terminal->color_scheme->fg.r,
			      terminal->color_scheme->fg.g,
			      terminal->color_scheme->fg.b,
			      terminal->color_scheme->fg.a);

	cairo_select_font_face (cr, "mono",
				CAIRO_FONT_SLANT_NORMAL,
				CAIRO_FONT_WEIGHT_NORMAL);
	cairo_set_font_size(cr, 14);

	cairo_font_extents(cr, &extents);
	side_margin = (rectangle.width - terminal->width * extents.max_x_advance) / 2;
	top_margin = (rectangle.height - terminal->height * extents.height) / 2;

	for (i = 0; i < terminal->height; i++) {
		cairo_move_to(cr, side_margin,
			      top_margin + extents.ascent + extents.height * i);
		cairo_show_text(cr, terminal_get_row(terminal, i));
	}

	d = terminal->focused ? 0 : 0.5;

	cairo_set_line_width(cr, 1);
	cairo_move_to(cr, side_margin + terminal->column * extents.max_x_advance + d,
		      top_margin + terminal->row * extents.height + d);
	cairo_rel_line_to(cr, extents.max_x_advance - 2 * d, 0);
	cairo_rel_line_to(cr, 0, extents.height - 2 * d);
	cairo_rel_line_to(cr, -extents.max_x_advance + 2 * d, 0);
	cairo_close_path(cr);

	if (terminal->focused)
		cairo_fill(cr);
	else
		cairo_stroke(cr);

	cairo_destroy(cr);

	window_copy_surface(terminal->window,
			    &rectangle,
			    surface);

	cairo_surface_destroy(surface);
}

static void
terminal_draw(struct terminal *terminal)
{
	struct rectangle rectangle;
	cairo_surface_t *surface;
	cairo_font_extents_t extents;
	cairo_t *cr;
	int32_t width, height;

	window_get_child_rectangle(terminal->window, &rectangle);

	surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
	cr = cairo_create(surface);
	cairo_select_font_face (cr, "mono",
				CAIRO_FONT_SLANT_NORMAL,
				CAIRO_FONT_WEIGHT_NORMAL);
	cairo_set_font_size(cr, 14);
	cairo_font_extents(cr, &extents);
	cairo_destroy(cr);
	cairo_surface_destroy(surface);

	width = (rectangle.width - 2 * terminal->margin) / (int32_t) extents.max_x_advance;
	height = (rectangle.height - 2 * terminal->margin) / (int32_t) extents.height;
	terminal_resize(terminal, width, height);

	if (!terminal->fullscreen) {
		rectangle.width = terminal->width * extents.max_x_advance + 2 * terminal->margin;
		rectangle.height = terminal->height * extents.height + 2 * terminal->margin;
		window_set_child_size(terminal->window, &rectangle);
	}

	window_draw(terminal->window);
	terminal_draw_contents(terminal);
	wl_compositor_commit(terminal->compositor, 0);
}

static gboolean
idle_redraw(void *data)
{
	struct terminal *terminal = data;

	terminal_draw(terminal);

	return FALSE;
}

#define STATE_NORMAL 0
#define STATE_ESCAPE 1

static void
terminal_data(struct terminal *terminal, const char *data, size_t length);

static void
terminal_schedule_redraw(struct terminal *terminal)
{
	if (!terminal->redraw_scheduled) {
		g_idle_add(idle_redraw, terminal);
		terminal->redraw_scheduled = 1;
	} else {
		terminal->redraw_pending = 1;
	}
}

static void
handle_escape(struct terminal *terminal)
{
	char *row, *p;
	int i, count;
	int args[10], set[10] = { 0, };

	terminal->escape[terminal->escape_length++] = '\0';
	i = 0;
	p = &terminal->escape[2];
	while ((isdigit(*p) || *p == ';') && i < 10) {
		if (*p == ';') {
			p++;
			i++;
		} else {
			args[i] = strtol(p, &p, 10);
			set[i] = 1;
		}
	}
	
	switch (*p) {
	case 'A':
		count = set[0] ? args[0] : 1;
		if (terminal->row - count >= 0)
			terminal->row -= count;
		else
			terminal->row = 0;
		break;
	case 'B':
		count = set[0] ? args[0] : 1;
		if (terminal->row + count < terminal->height)
			terminal->row += count;
		else
			terminal->row = terminal->height;
		break;
	case 'C':
		count = set[0] ? args[0] : 1;
		if (terminal->column + count < terminal->width)
			terminal->column += count;
		else
			terminal->column = terminal->width;
		break;
	case 'D':
		count = set[0] ? args[0] : 1;
		if (terminal->column - count >= 0)
			terminal->column -= count;
		else
			terminal->column = 0;
		break;
	case 'J':
		row = terminal_get_row(terminal, terminal->row);
		memset(&row[terminal->column], 0, terminal->width - terminal->column);
		for (i = terminal->row + 1; i < terminal->height; i++)
			memset(terminal_get_row(terminal, i), 0, terminal->width);
		break;
	case 'G':
		if (set[0])
			terminal->column = args[0] - 1;
		break;
	case 'H':
	case 'f':
		terminal->row = set[0] ? args[0] - 1 : 0;
		terminal->column = set[1] ? args[1] - 1 : 0;
		break;
	case 'K':
		row = terminal_get_row(terminal, terminal->row);
		memset(&row[terminal->column], 0, terminal->width - terminal->column);
		break;
	case 'm':
		/* color, blink, bold etc*/
		break;
	case '?':
		if (strcmp(p, "?25l") == 0) {
			/* hide cursor */
		} else if (strcmp(p, "?25h") == 0) {
			/* show cursor */
		}
		break;
	default:
		terminal_data(terminal,
			      terminal->escape + 1,
			      terminal->escape_length - 2);
		break;
	}	
}

static void
terminal_data(struct terminal *terminal, const char *data, size_t length)
{
	int i;
	char *row;

	for (i = 0; i < length; i++) {
		row = terminal_get_row(terminal, terminal->row);

		if (terminal->state == STATE_ESCAPE) {
			terminal->escape[terminal->escape_length++] = data[i];
			if (terminal->escape_length == 2 && data[i] != '[') {
				/* Bad escape sequence. */
				terminal->state = STATE_NORMAL;
				goto cancel_escape;
			}

			if (isalpha(data[i])) {
				terminal->state = STATE_NORMAL;
				handle_escape(terminal);
			} 
			continue;
		}

	cancel_escape:
		switch (data[i]) {
		case '\r':
			terminal->column = 0;
			break;
		case '\n':
			terminal->column = 0;
			if (terminal->row + 1 < terminal->height) {
				terminal->row++;
			} else {
				terminal->start++;
				if (terminal->start == terminal->height)
					terminal->start = 0;
				memset(terminal_get_row(terminal, terminal->row),
							0, terminal->width);
			}

			break;
		case '\t':
			memset(&row[terminal->column], ' ', -terminal->column & 7);
			terminal->column = (terminal->column + 7) & ~7;
			break;
		case '\e':
			terminal->state = STATE_ESCAPE;
			terminal->escape[0] = '\e';
			terminal->escape_length = 1;
			break;
		case '\b':
			if (terminal->column > 0)
				terminal->column--;
			break;
		case '\a':
			/* Bell */
			break;
		default:
			if (terminal->column < terminal->width)
				row[terminal->column++] = data[i] < 32 ? data[i] + 64 : data[i];
			break;
		}
	}

	terminal_schedule_redraw(terminal);
}

static void
resize_handler(struct window *window, void *data)
{
	struct terminal *terminal = data;

	terminal_schedule_redraw(terminal);
}

static void
handle_acknowledge(void *data,
		   struct wl_compositor *compositor,
		   uint32_t key, uint32_t frame)
{
	struct terminal *terminal = data;

	terminal->redraw_scheduled = 0;
	if (terminal->redraw_pending) {
		terminal->redraw_pending = 0;
		terminal_schedule_redraw(terminal);
	}
}

static void
handle_frame(void *data,
	     struct wl_compositor *compositor,
	     uint32_t frame, uint32_t timestamp)
{
}

static const struct wl_compositor_listener compositor_listener = {
	handle_acknowledge,
	handle_frame,
};

static void
key_handler(struct window *window, uint32_t key, uint32_t unicode,
	    uint32_t state, uint32_t modifiers, void *data)
{
	struct terminal *terminal = data;
	char ch = unicode;

	switch (key) {
	case KEY_F11:
		if (!state)
			break;
		terminal->fullscreen ^= 1;
		window_set_fullscreen(window, terminal->fullscreen);
		terminal_schedule_redraw(terminal);
		break;
	default:
		if (state && unicode)
			write(terminal->master, &ch, 1);
		break;
	}
}

static void
keyboard_focus_handler(struct window *window,
		       struct wl_input_device *device, void *data)
{
	struct terminal *terminal = data;

	terminal->focused = (device != NULL);
	terminal_schedule_redraw(terminal);
}

static struct terminal *
terminal_create(struct display *display, int fullscreen)
{
	struct terminal *terminal;

	terminal = malloc(sizeof *terminal);
	if (terminal == NULL)
		return terminal;

	memset(terminal, 0, sizeof *terminal);
	terminal->fullscreen = fullscreen;
	terminal->color_scheme = &jbarnes_colors;
	terminal->window = window_create(display, "Wayland Terminal",
					 500, 100, 500, 400);
	terminal->display = display;
	terminal->redraw_scheduled = 1;
	terminal->margin = 5;

	terminal->compositor = display_get_compositor(display);
	window_set_fullscreen(terminal->window, terminal->fullscreen);
	window_set_resize_handler(terminal->window, resize_handler, terminal);

	wl_compositor_add_listener(terminal->compositor,
				   &compositor_listener, terminal);

	window_set_key_handler(terminal->window, key_handler, terminal);
	window_set_keyboard_focus_handler(terminal->window,
					  keyboard_focus_handler, terminal);

	terminal_draw(terminal);

	return terminal;
}

static gboolean
io_handler(GIOChannel   *source,
	   GIOCondition  condition,
	   gpointer      data)
{
	struct terminal *terminal = data;
	gchar buffer[256];
	gsize bytes_read;
	GError *error = NULL;

	g_io_channel_read_chars(source, buffer, sizeof buffer,
				&bytes_read, &error);

	terminal_data(terminal, buffer, bytes_read);

	return TRUE;
}

static int
terminal_run(struct terminal *terminal, const char *path)
{
	int master;
	pid_t pid;

	pid = forkpty(&master, NULL, NULL, NULL);
	if (pid == 0) {
		setenv("TERM", "vt100", 1);
		if (execl(path, path, NULL)) {
			printf("exec failed: %m\n");
			exit(EXIT_FAILURE);
		}
	} else if (pid < 0) {
		fprintf(stderr, "failed to fork and create pty (%m).\n");
		return -1;
	}

	terminal->master = master;
	terminal->channel = g_io_channel_unix_new(master);
	fcntl(master, F_SETFL, O_NONBLOCK);
	g_io_add_watch(terminal->channel, G_IO_IN,
		       io_handler, terminal);

	return 0;
}

static const GOptionEntry option_entries[] = {
	{ "fullscreen", 'f', 0, G_OPTION_ARG_NONE,
	  &option_fullscreen, "Run in fullscreen mode" },
	{ NULL }
};

int main(int argc, char *argv[])
{
	struct wl_display *display;
	int fd;
	GMainLoop *loop;
	GSource *source;
	struct display *d;
	struct terminal *terminal;
	GOptionContext *context;
	GError *error;

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, option_entries, "Wayland Terminal");
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		fprintf(stderr, "option parsing failed: %s\n", error->message);
		exit(EXIT_FAILURE);
	}

	fd = open(gem_device, O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "drm open failed: %m\n");
		return -1;
	}

	display = wl_display_create(socket_name, sizeof socket_name);
	if (display == NULL) {
		fprintf(stderr, "failed to create display: %m\n");
		return -1;
	}

	d = display_create(display, fd);
	loop = g_main_loop_new(NULL, FALSE);
	source = wl_glib_source_new(display);
	g_source_attach(source, NULL);

	terminal = terminal_create(d, option_fullscreen);
	if (terminal_run(terminal, "/bin/bash"))
		exit(EXIT_FAILURE);

	g_main_loop_run(loop);

	return 0;
}