summaryrefslogtreecommitdiff
path: root/main.cpp
blob: 45eef83608af8c56fe759551f589c596ce582e07 (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
#include <iostream>
#include <sstream>
#include <memory>
#include <vector>
#include <unordered_map>
#include <variant>
#include <stdexcept>
#include <functional>
#include <filesystem>
#include <cstring>
#include <cassert>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include "command.h"


std::string trim(const std::string &s) {
	size_t left = 0;
	while (left < s.size() && isspace(s[left])) left++;
	size_t right = s.size() - 1;
	while (right >= left && isspace(s[right])) right--;
	return s.substr(left, right - left + 1);
}

class X_keycode {
public:
	X_keycode() : code{0} {}
	X_keycode(unsigned int code) : code{code} {}
	explicit operator unsigned int() const { return code; }
	bool operator==(X_keycode other) const { return code == other.code; }
private: unsigned int code;
};

template <>
struct std::hash<X_keycode> {
	size_t operator()(X_keycode code) const {
		return std::hash<unsigned int>{}((unsigned int)code);
	}
};

class X_keysym {
public:
	X_keysym() : sym{0} {}
	X_keysym(unsigned int sym) : sym{sym} {}
	explicit operator unsigned int() const { return sym; }
	X_keycode toCode(Display *dpy) const { return XKeysymToKeycode(dpy, sym); }
	bool operator==(X_keysym other) const { return sym == other.sym; }
private: unsigned int sym;
};

template <>
struct std::hash<X_keysym> {
	size_t operator()(X_keysym sym) const {
		return std::hash<unsigned int>{}((unsigned int)sym);
	}
};

void bel(Display *dpy) {
	XkbBell(dpy, None, 100, None);
}

template <typename Cleanup>
class UponExit {
public:
	UponExit(Cleanup cleanup) : cleanup{cleanup} {}
	~UponExit() {
		if (cleanup) (*cleanup)();
	}
	UponExit(const UponExit&) = delete;
	UponExit(UponExit &&other) : cleanup{move(other.cleanup)} {
		other.cleanup.reset();
	}
	UponExit& operator=(const UponExit&) = delete;
	UponExit& operator=(UponExit &&other) {
		cleanup = move(other.cleanup);
		other.cleanup.reset();
	}

private:
	std::optional<Cleanup> cleanup;
};

auto XGrabKeyRAII(Display *dpy, X_keycode code, int modifier, Window win) {
	XGrabKey(dpy, (unsigned int)code, modifier, win, False, GrabModeAsync, GrabModeAsync);
	return UponExit{[dpy, code, modifier, win]() {
		XUngrabKey(dpy, (unsigned int)code, modifier, win);
		XSync(dpy, False);
	}};
}

auto XGrabKeyboardRAII(Display *dpy, Window win) {
	int ret = XGrabKeyboard(dpy, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);
	if (ret == AlreadyGrabbed) {
		XUngrabKeyboard(dpy, CurrentTime);
		XSync(dpy, False);
		throw std::runtime_error("Cannot grab keyboard: already grabbed");
	}
	return UponExit{[dpy]() {
		XUngrabKeyboard(dpy, CurrentTime);
		XSync(dpy, False);
	}};
}

auto XOpenDisplayRAII(const char *name) {
	Display *dpy = XOpenDisplay(name);
	if (dpy == nullptr) {
		std::cerr << "Cannot open X display" << std::endl;
		exit(1);
	}
	return std::make_pair(dpy, UponExit{[dpy]() {
		XCloseDisplay(dpy);
	}});
}

template <typename F>  // return true to stop watch and loop
void globalKeyWatch(Display *dpy, X_keysym headerSym, F callback) {
	const Window root = DefaultRootWindow(dpy);
	const X_keycode headerCode = headerSym.toCode(dpy);

	auto guard = XGrabKeyRAII(dpy, headerCode, AnyModifier, root);

	XSelectInput(dpy, root, KeyPressMask);
	while (true) {
		XEvent ev;
		XNextEvent(dpy, &ev);
		if (ev.type == KeyPress && ev.xkey.keycode == (unsigned int)headerCode) {
			if (callback(ev.xkey)) return;
		}
	}
}

template <typename F>  // return true to lose grab and loop
void globalKeyboardGrab(Display *dpy, F callback) {
	const Window root = DefaultRootWindow(dpy);

	try {
		auto guard = XGrabKeyboardRAII(dpy, root);

		while (true) {
			XEvent ev;
			XNextEvent(dpy, &ev);
			if (ev.type == KeyPress) {
				if (callback(ev.xkey)) return;
			}
		}
	} catch (std::exception &e) {
		std::cerr << e.what() << std::endl;
	}
}

class SeqMatcher {
public:
	using Callback = std::function<void()>;

	struct SymSequence {
		std::vector<X_keysym> syms;
		Callback callback;
	};

	SeqMatcher(Display *dpy) : dpy{dpy} {}

	SeqMatcher(Display *dpy, std::vector<SymSequence> seqs)
			: dpy{dpy} {
		for (const auto &seq : seqs) addSequence(seq.syms, seq.callback);
	}

	void addSequence(const std::vector<X_keysym> &syms, Callback callback) {
		if (syms.empty()) {
			throw std::logic_error("Cannot register empty key sequence");
		}

		Node *current = &rootNode;
		for (X_keysym sym : syms) {
			if (std::holds_alternative<Callback>(current->v)) {
				throw std::logic_error("Overlapping key sequences (second is longer)");
			} else {
				if (!std::holds_alternative<NodeMap>(current->v)) {
					current->v.emplace<NodeMap>();
				}
				NodeMap &map = std::get<NodeMap>(current->v);
				X_keycode code = sym.toCode(dpy);
				auto it = map.find(code);
				if (it != map.end()) {
					current = it->second.get();
				} else {
					current = map.emplace(sym.toCode(dpy), std::make_unique<Node>()).first->second.get();
				}
			}
		}

		if (auto *map = std::get_if<NodeMap>(&current->v)) {
			if (!map->empty()) {
				throw std::logic_error("Overlapping key sequences (second is shorter)");
			}
		}
		if (std::holds_alternative<Callback>(current->v)) {
			throw std::logic_error("Overlapping key sequences (equally long)");
		}
		current->v.emplace<Callback>(callback);
	}

	// Returns bel()-running callback if unrecognised sequence is given
	std::optional<Callback> observe(const XKeyEvent &ev) {
		auto *map = std::get_if<NodeMap>(&curNode->v);
		assert(map);

		auto it = map->find(X_keycode{ev.keycode});
		if (it == map->end()) {
			// Sequence not found
			reset();
			return [dpy = dpy]() { bel(dpy); };
		}

		curNode = it->second.get();

		if (auto *cb = std::get_if<Callback>(&curNode->v)) {
			// Sequence completed
			reset();
			return *cb;
		}

		// Need more keys
		return std::nullopt;
	}

	void reset() {
		curNode = &rootNode;
	}

private:
	struct Node;
	using NodeMap = std::unordered_map<X_keycode, std::unique_ptr<Node>>;
	struct Node {
		std::variant<NodeMap, Callback> v;
	};

	Display *const dpy;
	Node rootNode;
	Node *curNode = &rootNode;
};

namespace sqlite {
	std::vector<std::vector<std::string>> parseCSV(std::string output) {
		std::istringstream ss{output};
		std::vector<std::vector<std::string>> table;

		std::string line;
		while (std::getline(ss, line)) {
			while (!line.empty() && strchr("\r\n", line.back()) != nullptr)
				line.pop_back();

			table.emplace_back();

			if (line.empty()) continue;

			std::vector<std::string> &row = table.back();
			row.emplace_back();
			bool inString = false;
			for (size_t i = 0; i < line.size(); i++) {
				switch (line[i]) {
					case '"':
						if (inString) {
							if (i + 1 < line.size() && line[i+1] == '"') {
								row.back().push_back('"');
								i++;
							} else {
								inString = false;
							}
						} else {
							inString = true;
						}
						break;

					case ',':
						if (inString) {
							row.back().push_back(',');
						} else {
							row.emplace_back();
						}
						break;

					default:
						row.back().push_back(line[i]);
						break;
				}
			}
		}

		return table;
	}
}

namespace got {
	std::string getDBpath() {
		return std::string{getenv("HOME")} + "/.timetrap.db";
	}

	// Returns {sheet, note}
	std::optional<std::pair<std::string, std::string>> getRunning() {
		std::string output = runCommand({"sqlite3", getDBpath(), ".mode csv", "select sheet, note from entries where end is null"});
		auto table = sqlite::parseCSV(move(output));
		if (table.empty()) return std::nullopt;
		else return std::make_pair(table[0][0], table[0][1]);
	}

	std::vector<std::string> getSheets() {
		std::string output = runCommand({"sqlite3", getDBpath(), "select distinct sheet from entries"});
		std::istringstream ss{output};
		std::vector<std::string> lines;
		std::string line;
		while (std::getline(ss, line)) {
			if (line.size() > 0) lines.push_back(move(line));
		}
		std::sort(lines.begin(), lines.end());
		return lines;
	}

	void editRunning(const std::string &descr) {
		runCommand({"got", "edit", descr});
	}

	void checkOut() {
		runCommand({"got", "out"});
	}

	void checkIn(const std::string &sheet) {
		runCommand({"got", "sheet", sheet});
		runCommand({"got", "in"});
	}
}

namespace gui {
	void showNotification(const std::string &message) {
		runCommand({"zenity", "--notification", "--text", message});
	}

	std::optional<std::string> promptText(const std::string &message) {
		auto result = readCommand({"zenity", "--entry", "--text", message});
		if (result.first == 0) return result.second;
		else return std::nullopt;
	}

	std::optional<std::string> chooseList(const std::string &message, const std::string &header, const std::vector<std::string> &options) {
		std::vector<std::string> args{
			"zenity", "--list", "--text", message, "--column", header
		};
		args.insert(args.end(), options.begin(), options.end());
		auto result = readCommand(args);
		if (result.first == 0) return trim(result.second);
		else return std::nullopt;
	}
}

int main(int argc, char **argv) {
	if (argc >= 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
		std::cout <<
			"GUI for GOT (https://github.com/lieuwex/got), which is a rewrite of Timetrap.\n"
			"This thing runs as a daemon; it gets activated with the Pause/Break key on\n"
			"your keyboard. The following sequences trigger actions:\n"
			"  <break> E        -- Edit the note for the currently running activity\n"
			"  <break> I        -- Check into a sheet\n"
			"  <break> O        -- Check out of the current activity\n"
			"  <break> <space>  -- Switch and check into the 'misc' sheet\n"
			"  <break> Q        -- Quit this program (killing it also works of course)\n"
			<< std::flush;
		return 0;
	}

	if (!std::filesystem::exists(got::getDBpath())) {
		std::cerr << "The GOT database (" << got::getDBpath() << ") doesn't exist!" << std::endl;
		std::cerr << "Please run 'got' at least once before using this tool." << std::endl;
		return 1;
	}

	auto dpy_pair = XOpenDisplayRAII(nullptr);
	Display *dpy = dpy_pair.first;

	bool quitRequested = false;

	SeqMatcher matcher{dpy};

	matcher.addSequence({XK_E}, []() {
		if (got::getRunning()) {
			if (auto descr = gui::promptText("Edit currently running entry's text:")) {
				got::editRunning(*descr);
			}
		} else {
			gui::showNotification("Cannot edit if not checked in");
		}
	});

	matcher.addSequence({XK_I}, []() {
		std::vector<std::string> sheets = got::getSheets();
		auto choice = gui::chooseList("Check in", "Sheet", sheets);
		if (choice) {
			auto current = got::getRunning();
			if (current) {
				got::checkOut();
				gui::showNotification("Checked out of sheet '" + current->first + "'");
			}
			got::checkIn(*choice);
			gui::showNotification("Checked in to sheet '" + *choice + "'");
		}
	});

	matcher.addSequence({XK_O}, []() {
		auto current = got::getRunning();
		if (current) {
			got::checkOut();
			gui::showNotification("Checked out of sheet '" + current->first + "'");
		} else {
			gui::showNotification("Cannot check out if not checked in");
		}
	});

	matcher.addSequence({XK_space}, []() {
		if (got::getRunning()) got::checkOut();
		got::checkIn("misc");
		gui::showNotification("Switched to 'misc'");
	});

	matcher.addSequence({XK_Break}, []() {
		auto current = got::getRunning();
		if (!current) {
			gui::showNotification("Currently checked out");
		} else {
			gui::showNotification(
				"Checked into '" + current->first + "'" +
				(current->second.empty() ? current->second : " (" + current->second + ")")
			);
		}
	});

	matcher.addSequence({XK_Q}, [&quitRequested]() {
		gui::showNotification("GOT GUI is quitting");
		quitRequested = true;
	});

	globalKeyWatch(
		dpy, XK_Break,
		[dpy, &matcher, &quitRequested](const XKeyEvent&) -> bool {
			matcher.reset();

			SeqMatcher::Callback cb;

			globalKeyboardGrab(dpy, [&matcher, &cb](const XKeyEvent &ev) -> bool {
				auto opt_cb = matcher.observe(ev);
				if (opt_cb) {
					cb = *opt_cb;
					return true;
				} else {
					return false;
				}
			});

			if (cb) cb();

			return quitRequested;
		}
	);
}