shithub: microui

ref: 4fd28b3c945e170a4e67ffb2dac95aa60b0633db
dir: /demo/plan9.c/

View raw version
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <mouse.h>
#include <keyboard.h>
#include <thread.h>
#include <bio.h>
#include <microui.h>

void process_frame(void);

void
threadmain(int argc, char **argv)
{
	Mousectl *mctl;
	char *s;
	Biobuf *snarf;
	Keyboardctl *kctl;
	int redraw;
	Rune key;
	Mouse m;
	Alt a[] = {
		{ nil, &m, CHANRCV },
		{ nil, nil, CHANRCV },
		{ nil, &key, CHANRCV },
		{ nil, nil,  CHANEND},
	};
	int oldbuttons, b, nkey, gotevent;
	char text[5];

	USED(argc); USED(argv);

	if (initdraw(nil, nil, "microui demo") < 0)
		sysfatal("initdraw: %r");
	if ((mctl = initmouse(nil, screen)) == nil)
		sysfatal("initmouse: %r");
	if ((kctl = initkeyboard(nil)) == nil)
		sysfatal("initkeyboard: %r");

	a[0].c = mctl->c;
	a[1].c = mctl->resizec;
	a[2].c = kctl->c;

	srand(time(0));
	threadsetname("microui demo");

	mu_init();
	mu_style.font = font;
	mu_style.size.y = font->height;
	mu_style.title_height = mu_style.size.y + 6;
	process_frame();

	oldbuttons = 0;
	redraw = 0;
	for (;;) {
		process_frame();
		if (mu_render(redraw))
			flushimage(display, 1);

		redraw = 0;
		gotevent = 1;
		switch (alt(a)) {
		case 0: /* mouse */
			m.xy.x -= screen->r.min.x;
			m.xy.y -= screen->r.min.y;
			mu_input_mousemove(m.xy.x, m.xy.y);
			if ((b = (m.buttons & 1)) != (oldbuttons & 1))
				(b ? mu_input_mousedown : mu_input_mouseup)(m.xy.x, m.xy.y, MU_MOUSE_LEFT);
			else if ((b = (m.buttons & 2)) != (oldbuttons & 2))
				(b ? mu_input_mousedown : mu_input_mouseup)(m.xy.x, m.xy.y, MU_MOUSE_MIDDLE);
			else if ((b = (m.buttons & 4)) != (oldbuttons & 4))
				(b ? mu_input_mousedown : mu_input_mouseup)(m.xy.x, m.xy.y, MU_MOUSE_RIGHT);
			if (m.buttons == 5 && (snarf = Bopen("/dev/snarf", OREAD)) != nil) {
				if ((s = Brdstr(snarf, 0, 1)) != nil) {
					mu_input_text(s);
					free(s);
				}
				Bterm(snarf);
			}
			oldbuttons = m.buttons;
			break;

		case 1: /* resize */
			getwindow(display, Refnone);
			redraw = 1;
			break;

		case 2: /* keyboard */
			nkey = -1;
			switch (key) {
			case Kdel: goto end;
			case Kshift: nkey = MU_KEY_SHIFT; break;
			case Kbs: nkey = MU_KEY_BACKSPACE; break;
			case '\n': nkey = MU_KEY_RETURN; break;
			case Knack: nkey = MU_KEY_NACK; break;
			case Kleft: nkey = MU_KEY_LEFT; break;
			case Kright: nkey = MU_KEY_RIGHT; break;
			case Kesc: mu_set_focus(0); break;
			default:
				if (key < 0xf000 || key > 0xffff) {
					memset(text, 0, sizeof(text));
					if (runetochar(text, &key) > 0)
						mu_input_text(text);
				}
				break;
			}
			if (nkey >= 0) {
				mu_input_keydown(nkey);
				mu_input_keyup(nkey);
			}
			break;

		default:
			gotevent = 0;
			break;
		}

		if (gotevent)
			process_frame();
	}

end:
	threadexitsall(nil);
}