1 #include "termkey.h"
2 #include "termkey-internal.h"
3 
4 #include <ctype.h>
5 #include <errno.h>
6 #include <poll.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <strings.h>
10 
11 #include <stdio.h>
12 
13 #define strcaseeq(a,b) (strcasecmp(a,b) == 0)
14 
termkey_check_version(int major,int minor)15 void termkey_check_version(int major, int minor)
16 {
17   if(major != TERMKEY_VERSION_MAJOR) {
18     fprintf(stderr, "libtermkey major version mismatch; %d (wants) != %d (library)\n",
19         major, TERMKEY_VERSION_MAJOR);
20     exit(1);
21   }
22 
23   if(minor > TERMKEY_VERSION_MINOR) {
24     fprintf(stderr, "libtermkey minor version mismatch; %d (wants) > %d (library)\n",
25         minor, TERMKEY_VERSION_MINOR);
26     exit(1);
27   }
28 
29   // Happy
30 }
31 
32 static struct TermKeyDriver *drivers[] = {
33   &termkey_driver_ti,
34   &termkey_driver_csi,
35   NULL,
36 };
37 
38 // Forwards for the "protected" methods
39 // static void eat_bytes(TermKey *tk, size_t count);
40 static void emit_codepoint(TermKey *tk, long codepoint, TermKeyKey *key);
41 static TermKeyResult peekkey_simple(TermKey *tk, TermKeyKey *key, int force, size_t *nbytes);
42 static TermKeyResult peekkey_mouse(TermKey *tk, TermKeyKey *key, size_t *nbytes);
43 
44 static TermKeySym register_c0(TermKey *tk, TermKeySym sym, unsigned char ctrl, const char *name);
45 static TermKeySym register_c0_full(TermKey *tk, TermKeySym sym, int modifier_set, int modifier_mask, unsigned char ctrl, const char *name);
46 
47 static struct {
48   TermKeySym sym;
49   const char *name;
50 } keynames[] = {
51   { TERMKEY_SYM_NONE,      "NONE" },
52   { TERMKEY_SYM_BACKSPACE, "Backspace" },
53   { TERMKEY_SYM_TAB,       "Tab" },
54   { TERMKEY_SYM_ENTER,     "Enter" },
55   { TERMKEY_SYM_ESCAPE,    "Escape" },
56   { TERMKEY_SYM_SPACE,     "Space" },
57   { TERMKEY_SYM_DEL,       "DEL" },
58   { TERMKEY_SYM_UP,        "Up" },
59   { TERMKEY_SYM_DOWN,      "Down" },
60   { TERMKEY_SYM_LEFT,      "Left" },
61   { TERMKEY_SYM_RIGHT,     "Right" },
62   { TERMKEY_SYM_BEGIN,     "Begin" },
63   { TERMKEY_SYM_FIND,      "Find" },
64   { TERMKEY_SYM_INSERT,    "Insert" },
65   { TERMKEY_SYM_DELETE,    "Delete" },
66   { TERMKEY_SYM_SELECT,    "Select" },
67   { TERMKEY_SYM_PAGEUP,    "PageUp" },
68   { TERMKEY_SYM_PAGEDOWN,  "PageDown" },
69   { TERMKEY_SYM_HOME,      "Home" },
70   { TERMKEY_SYM_END,       "End" },
71   { TERMKEY_SYM_CANCEL,    "Cancel" },
72   { TERMKEY_SYM_CLEAR,     "Clear" },
73   { TERMKEY_SYM_CLOSE,     "Close" },
74   { TERMKEY_SYM_COMMAND,   "Command" },
75   { TERMKEY_SYM_COPY,      "Copy" },
76   { TERMKEY_SYM_EXIT,      "Exit" },
77   { TERMKEY_SYM_HELP,      "Help" },
78   { TERMKEY_SYM_MARK,      "Mark" },
79   { TERMKEY_SYM_MESSAGE,   "Message" },
80   { TERMKEY_SYM_MOVE,      "Move" },
81   { TERMKEY_SYM_OPEN,      "Open" },
82   { TERMKEY_SYM_OPTIONS,   "Options" },
83   { TERMKEY_SYM_PRINT,     "Print" },
84   { TERMKEY_SYM_REDO,      "Redo" },
85   { TERMKEY_SYM_REFERENCE, "Reference" },
86   { TERMKEY_SYM_REFRESH,   "Refresh" },
87   { TERMKEY_SYM_REPLACE,   "Replace" },
88   { TERMKEY_SYM_RESTART,   "Restart" },
89   { TERMKEY_SYM_RESUME,    "Resume" },
90   { TERMKEY_SYM_SAVE,      "Save" },
91   { TERMKEY_SYM_SUSPEND,   "Suspend" },
92   { TERMKEY_SYM_UNDO,      "Undo" },
93   { TERMKEY_SYM_KP0,       "KP0" },
94   { TERMKEY_SYM_KP1,       "KP1" },
95   { TERMKEY_SYM_KP2,       "KP2" },
96   { TERMKEY_SYM_KP3,       "KP3" },
97   { TERMKEY_SYM_KP4,       "KP4" },
98   { TERMKEY_SYM_KP5,       "KP5" },
99   { TERMKEY_SYM_KP6,       "KP6" },
100   { TERMKEY_SYM_KP7,       "KP7" },
101   { TERMKEY_SYM_KP8,       "KP8" },
102   { TERMKEY_SYM_KP9,       "KP9" },
103   { TERMKEY_SYM_KPENTER,   "KPEnter" },
104   { TERMKEY_SYM_KPPLUS,    "KPPlus" },
105   { TERMKEY_SYM_KPMINUS,   "KPMinus" },
106   { TERMKEY_SYM_KPMULT,    "KPMult" },
107   { TERMKEY_SYM_KPDIV,     "KPDiv" },
108   { TERMKEY_SYM_KPCOMMA,   "KPComma" },
109   { TERMKEY_SYM_KPPERIOD,  "KPPeriod" },
110   { TERMKEY_SYM_KPEQUALS,  "KPEquals" },
111   { 0, NULL },
112 };
113 
114 #define CHARAT(i) (tk->buffer[tk->buffstart + (i)])
115 
116 #ifdef DEBUG
117 /* Some internal deubgging functions */
118 
print_buffer(TermKey * tk)119 static void print_buffer(TermKey *tk)
120 {
121   int i;
122   for(i = 0; i < tk->buffcount && i < 20; i++)
123     fprintf(stderr, "%02x ", CHARAT(i));
124   if(tk->buffcount > 20)
125     fprintf(stderr, "...");
126 }
127 
print_key(TermKey * tk,TermKeyKey * key)128 static void print_key(TermKey *tk, TermKeyKey *key)
129 {
130   switch(key->type) {
131   case TERMKEY_TYPE_UNICODE:
132     fprintf(stderr, "Unicode codepoint=U+%04lx utf8='%s'", key->code.codepoint, key->utf8);
133     break;
134   case TERMKEY_TYPE_FUNCTION:
135     fprintf(stderr, "Function F%d", key->code.number);
136     break;
137   case TERMKEY_TYPE_KEYSYM:
138     fprintf(stderr, "Keysym sym=%d(%s)", key->code.sym, termkey_get_keyname(tk, key->code.sym));
139     break;
140   case TERMKEY_TYPE_MOUSE:
141     {
142       TermKeyMouseEvent ev;
143       int button, line, col;
144       termkey_interpret_mouse(tk, key, &ev, &button, &line, &col);
145       fprintf(stderr, "Mouse ev=%d button=%d pos=(%d,%d)\n", ev, button, line, col);
146     }
147     break;
148   case TERMKEY_TYPE_POSITION:
149     {
150       int line, col;
151       termkey_interpret_position(tk, key, &line, &col);
152       fprintf(stderr, "Position report pos=(%d,%d)\n", line, col);
153     }
154     break;
155   case TERMKEY_TYPE_MODEREPORT:
156     {
157       int initial, mode, value;
158       termkey_interpret_modereport(tk, key, &initial, &mode, &value);
159       fprintf(stderr, "Mode report mode=%s %d val=%d\n", initial == '?' ? "DEC" : "ANSI", mode, value);
160     }
161     break;
162   case TERMKEY_TYPE_DCS:
163     fprintf(stderr, "Device Control String");
164     break;
165   case TERMKEY_TYPE_OSC:
166     fprintf(stderr, "Operating System Control");
167     break;
168   case TERMKEY_TYPE_UNKNOWN_CSI:
169     fprintf(stderr, "unknown CSI\n");
170     break;
171   }
172 
173   int m = key->modifiers;
174   fprintf(stderr, " mod=%s%s%s+%02x",
175       (m & TERMKEY_KEYMOD_CTRL  ? "C" : ""),
176       (m & TERMKEY_KEYMOD_ALT   ? "A" : ""),
177       (m & TERMKEY_KEYMOD_SHIFT ? "S" : ""),
178       m & ~(TERMKEY_KEYMOD_CTRL|TERMKEY_KEYMOD_ALT|TERMKEY_KEYMOD_SHIFT));
179 }
180 
res2str(TermKeyResult res)181 static const char *res2str(TermKeyResult res)
182 {
183   static char errorbuffer[256];
184 
185   switch(res) {
186   case TERMKEY_RES_KEY:
187     return "TERMKEY_RES_KEY";
188   case TERMKEY_RES_EOF:
189     return "TERMKEY_RES_EOF";
190   case TERMKEY_RES_AGAIN:
191     return "TERMKEY_RES_AGAIN";
192   case TERMKEY_RES_NONE:
193     return "TERMKEY_RES_NONE";
194   case TERMKEY_RES_ERROR:
195     snprintf(errorbuffer, sizeof errorbuffer, "TERMKEY_RES_ERROR(errno=%d)\n", errno);
196     return (const char*)errorbuffer;
197   }
198 
199   return "unknown";
200 }
201 #endif
202 
203 /* Similar to snprintf(str, size, "%s", src) except it turns CamelCase into
204  * space separated values
205  */
snprint_cameltospaces(char * str,size_t size,const char * src)206 static int snprint_cameltospaces(char *str, size_t size, const char *src)
207 {
208   int prev_lower = 0;
209   size_t l = 0;
210   while(*src && l < size - 1) {
211     if(isupper(*src) && prev_lower) {
212       if(str)
213         str[l++] = ' ';
214       if(l >= size - 1)
215         break;
216     }
217     prev_lower = islower(*src);
218     str[l++] = tolower(*src++);
219   }
220   str[l] = 0;
221   /* For consistency with snprintf, return the number of bytes that would have
222    * been written, excluding '\0' */
223   while(*src) {
224     if(isupper(*src) && prev_lower) {
225       l++;
226     }
227     prev_lower = islower(*src);
228     src++; l++;
229   }
230   return l;
231 }
232 
233 /* Similar to strcmp(str, strcamel, n) except that:
234  *    it compares CamelCase in strcamel with space separated values in str;
235  *    it takes char**s and updates them
236  * n counts bytes of strcamel, not str
237  */
strpncmp_camel(const char ** strp,const char ** strcamelp,size_t n)238 static int strpncmp_camel(const char **strp, const char **strcamelp, size_t n)
239 {
240   const char *str = *strp, *strcamel = *strcamelp;
241   int prev_lower = 0;
242 
243   for( ; (*str || *strcamel) && n; n--) {
244     char b = tolower(*strcamel);
245     if(isupper(*strcamel) && prev_lower) {
246       if(*str != ' ')
247         break;
248       str++;
249       if(*str != b)
250         break;
251     }
252     else
253       if(*str != b)
254         break;
255 
256     prev_lower = islower(*strcamel);
257 
258     str++;
259     strcamel++;
260   }
261 
262   *strp = str;
263   *strcamelp = strcamel;
264   return *str - *strcamel;
265 }
266 
termkey_alloc(void)267 static TermKey *termkey_alloc(void)
268 {
269   TermKey *tk = malloc(sizeof(TermKey));
270   if(!tk)
271     return NULL;
272 
273   /* Default all the object fields but don't allocate anything */
274 
275   tk->fd         = -1;
276   tk->flags      = 0;
277   tk->canonflags = 0;
278 
279   tk->buffer    = NULL;
280   tk->buffstart = 0;
281   tk->buffcount = 0;
282   tk->buffsize  = 256; /* bytes */
283   tk->hightide  = 0;
284 
285   tk->restore_termios_valid = 0;
286 
287   tk->ti_getstr_hook = NULL;
288   tk->ti_getstr_hook_data = NULL;
289 
290   tk->waittime = 50; /* msec */
291 
292   tk->is_closed = 0;
293   tk->is_started = 0;
294 
295   tk->nkeynames = 64;
296   tk->keynames  = NULL;
297 
298   for(int i = 0; i < 32; i++)
299     tk->c0[i].sym = TERMKEY_SYM_NONE;
300 
301   tk->drivers = NULL;
302 
303   tk->method.emit_codepoint = &emit_codepoint;
304   tk->method.peekkey_simple = &peekkey_simple;
305   tk->method.peekkey_mouse  = &peekkey_mouse;
306 
307   return tk;
308 }
309 
termkey_init(TermKey * tk,const char * term)310 static int termkey_init(TermKey *tk, const char *term)
311 {
312   tk->buffer = malloc(tk->buffsize);
313   if(!tk->buffer)
314     return 0;
315 
316   tk->keynames = malloc(sizeof(tk->keynames[0]) * tk->nkeynames);
317   if(!tk->keynames)
318     goto abort_free_buffer;
319 
320   int i;
321   for(i = 0; i < tk->nkeynames; i++)
322     tk->keynames[i] = NULL;
323 
324   for(i = 0; keynames[i].name; i++)
325     if(termkey_register_keyname(tk, keynames[i].sym, keynames[i].name) == -1)
326       goto abort_free_keynames;
327 
328   register_c0(tk, TERMKEY_SYM_TAB,    0x09, NULL);
329   register_c0(tk, TERMKEY_SYM_ENTER,  0x0d, NULL);
330   register_c0(tk, TERMKEY_SYM_ESCAPE, 0x1b, NULL);
331 
332   struct TermKeyDriverNode *tail = NULL;
333 
334   for(i = 0; drivers[i]; i++) {
335     void *info = (*drivers[i]->new_driver)(tk, term);
336     if(!info)
337       continue;
338 
339 #ifdef DEBUG
340     fprintf(stderr, "Loading the %s driver...\n", drivers[i]->name);
341 #endif
342 
343     struct TermKeyDriverNode *thisdrv = malloc(sizeof(*thisdrv));
344     if(!thisdrv)
345       goto abort_free_drivers;
346 
347     thisdrv->driver = drivers[i];
348     thisdrv->info = info;
349     thisdrv->next = NULL;
350 
351     if(!tail)
352       tk->drivers = thisdrv;
353     else
354       tail->next = thisdrv;
355 
356     tail = thisdrv;
357 
358 #ifdef DEBUG
359     fprintf(stderr, "Loaded %s driver\n", drivers[i]->name);
360 #endif
361   }
362 
363   if(!tk->drivers) {
364     errno = ENOENT;
365     goto abort_free_keynames;
366   }
367 
368   return 1;
369 
370 abort_free_drivers:
371   for(struct TermKeyDriverNode *p = tk->drivers; p; ) {
372     (*p->driver->free_driver)(p->info);
373     struct TermKeyDriverNode *next = p->next;
374     free(p);
375     p = next;
376   }
377 
378 abort_free_keynames:
379   free(tk->keynames);
380 
381 abort_free_buffer:
382   free(tk->buffer);
383 
384   return 0;
385 }
386 
termkey_new(int fd,int flags)387 TermKey *termkey_new(int fd, int flags)
388 {
389   TermKey *tk = termkey_alloc();
390   if(!tk)
391     return NULL;
392 
393   tk->fd = fd;
394 
395   if(!(flags & (TERMKEY_FLAG_RAW|TERMKEY_FLAG_UTF8))) {
396     char *e;
397 
398     /* Most OSes will set .UTF-8. Some will set .utf8. Try to be fairly
399      * generous in parsing these
400      */
401     if(((e = getenv("LANG")) || (e = getenv("LC_MESSAGES")) || (e = getenv("LC_ALL"))) &&
402        (e = strchr(e, '.')) && e++ &&
403        (strcaseeq(e, "UTF-8") || strcaseeq(e, "UTF8")))
404       flags |= TERMKEY_FLAG_UTF8;
405     else
406       flags |= TERMKEY_FLAG_RAW;
407   }
408 
409   termkey_set_flags(tk, flags);
410 
411   const char *term = getenv("TERM");
412 
413   if(!termkey_init(tk, term))
414     goto abort;
415 
416   if(!(flags & TERMKEY_FLAG_NOSTART) && !termkey_start(tk))
417     goto abort;
418 
419   return tk;
420 
421 abort:
422   free(tk);
423   return NULL;
424 }
425 
termkey_new_abstract(const char * term,int flags)426 TermKey *termkey_new_abstract(const char *term, int flags)
427 {
428   TermKey *tk = termkey_alloc();
429   if(!tk)
430     return NULL;
431 
432   tk->fd = -1;
433 
434   termkey_set_flags(tk, flags);
435 
436   if(!termkey_init(tk, term)) {
437     free(tk);
438     return NULL;
439   }
440 
441   if(!(flags & TERMKEY_FLAG_NOSTART) && !termkey_start(tk))
442     goto abort;
443 
444   return tk;
445 
446 abort:
447   free(tk);
448   return NULL;
449 }
450 
termkey_free(TermKey * tk)451 void termkey_free(TermKey *tk)
452 {
453   free(tk->buffer); tk->buffer = NULL;
454   free(tk->keynames); tk->keynames = NULL;
455 
456   struct TermKeyDriverNode *p;
457   for(p = tk->drivers; p; ) {
458     (*p->driver->free_driver)(p->info);
459     struct TermKeyDriverNode *next = p->next;
460     free(p);
461     p = next;
462   }
463 
464   free(tk);
465 }
466 
termkey_destroy(TermKey * tk)467 void termkey_destroy(TermKey *tk)
468 {
469   if(tk->is_started)
470     termkey_stop(tk);
471 
472   termkey_free(tk);
473 }
474 
termkey_hook_terminfo_getstr(TermKey * tk,TermKey_Terminfo_Getstr_Hook * hookfn,void * data)475 void termkey_hook_terminfo_getstr(TermKey *tk, TermKey_Terminfo_Getstr_Hook *hookfn, void *data)
476 {
477   tk->ti_getstr_hook = hookfn;
478   tk->ti_getstr_hook_data = data;
479 }
480 
termkey_start(TermKey * tk)481 int termkey_start(TermKey *tk)
482 {
483   if(tk->is_started)
484     return 1;
485 
486   if(tk->fd != -1 && !(tk->flags & TERMKEY_FLAG_NOTERMIOS)) {
487     struct termios termios;
488     if(tcgetattr(tk->fd, &termios) == 0) {
489       tk->restore_termios = termios;
490       tk->restore_termios_valid = 1;
491 
492       termios.c_iflag &= ~(IXON|INLCR|ICRNL);
493       termios.c_lflag &= ~(ICANON|ECHO
494 #ifdef IEXTEN
495           | IEXTEN
496 #endif
497       );
498       termios.c_cc[VMIN] = 1;
499       termios.c_cc[VTIME] = 0;
500 
501       if(tk->flags & TERMKEY_FLAG_CTRLC)
502         /* want no signal keys at all, so just disable ISIG */
503         termios.c_lflag &= ~ISIG;
504       else {
505         /* Disable Ctrl-\==VQUIT and Ctrl-D==VSUSP but leave Ctrl-C as SIGINT */
506         termios.c_cc[VQUIT] = _POSIX_VDISABLE;
507         termios.c_cc[VSUSP] = _POSIX_VDISABLE;
508         /* Some OSes have Ctrl-Y==VDSUSP */
509 #ifdef VDSUSP
510         termios.c_cc[VDSUSP] = _POSIX_VDISABLE;
511 #endif
512       }
513 
514 #ifdef DEBUG
515       fprintf(stderr, "Setting termios(3) flags\n");
516 #endif
517       tcsetattr(tk->fd, TCSANOW, &termios);
518     }
519   }
520 
521   struct TermKeyDriverNode *p;
522   for(p = tk->drivers; p; p = p->next)
523     if(p->driver->start_driver)
524       if(!(*p->driver->start_driver)(tk, p->info))
525         return 0;
526 
527 #ifdef DEBUG
528   fprintf(stderr, "Drivers started; termkey instance %p is ready\n", tk);
529 #endif
530 
531   tk->is_started = 1;
532   return 1;
533 }
534 
termkey_stop(TermKey * tk)535 int termkey_stop(TermKey *tk)
536 {
537   if(!tk->is_started)
538     return 1;
539 
540   struct TermKeyDriverNode *p;
541   for(p = tk->drivers; p; p = p->next)
542     if(p->driver->stop_driver)
543       (*p->driver->stop_driver)(tk, p->info);
544 
545   if(tk->restore_termios_valid)
546     tcsetattr(tk->fd, TCSANOW, &tk->restore_termios);
547 
548   tk->is_started = 0;
549 
550   return 1;
551 }
552 
termkey_is_started(TermKey * tk)553 int termkey_is_started(TermKey *tk)
554 {
555   return tk->is_started;
556 }
557 
termkey_get_fd(TermKey * tk)558 int termkey_get_fd(TermKey *tk)
559 {
560   return tk->fd;
561 }
562 
termkey_get_flags(TermKey * tk)563 int termkey_get_flags(TermKey *tk)
564 {
565   return tk->flags;
566 }
567 
termkey_set_flags(TermKey * tk,int newflags)568 void termkey_set_flags(TermKey *tk, int newflags)
569 {
570   tk->flags = newflags;
571 
572   if(tk->flags & TERMKEY_FLAG_SPACESYMBOL)
573     tk->canonflags |= TERMKEY_CANON_SPACESYMBOL;
574   else
575     tk->canonflags &= ~TERMKEY_CANON_SPACESYMBOL;
576 }
577 
termkey_set_waittime(TermKey * tk,int msec)578 void termkey_set_waittime(TermKey *tk, int msec)
579 {
580   tk->waittime = msec;
581 }
582 
termkey_get_waittime(TermKey * tk)583 int termkey_get_waittime(TermKey *tk)
584 {
585   return tk->waittime;
586 }
587 
termkey_get_canonflags(TermKey * tk)588 int termkey_get_canonflags(TermKey *tk)
589 {
590   return tk->canonflags;
591 }
592 
termkey_set_canonflags(TermKey * tk,int flags)593 void termkey_set_canonflags(TermKey *tk, int flags)
594 {
595   tk->canonflags = flags;
596 
597   if(tk->canonflags & TERMKEY_CANON_SPACESYMBOL)
598     tk->flags |= TERMKEY_FLAG_SPACESYMBOL;
599   else
600     tk->flags &= ~TERMKEY_FLAG_SPACESYMBOL;
601 }
602 
termkey_get_buffer_size(TermKey * tk)603 size_t termkey_get_buffer_size(TermKey *tk)
604 {
605   return tk->buffsize;
606 }
607 
termkey_set_buffer_size(TermKey * tk,size_t size)608 int termkey_set_buffer_size(TermKey *tk, size_t size)
609 {
610   unsigned char *buffer = realloc(tk->buffer, size);
611   if(!buffer)
612     return 0;
613 
614   tk->buffer = buffer;
615   tk->buffsize = size;
616 
617   return 1;
618 }
619 
termkey_get_buffer_remaining(TermKey * tk)620 size_t termkey_get_buffer_remaining(TermKey *tk)
621 {
622   /* Return the total number of free bytes in the buffer, because that's what
623    * is available to the user. */
624   return tk->buffsize - tk->buffcount;
625 }
626 
eat_bytes(TermKey * tk,size_t count)627 static void eat_bytes(TermKey *tk, size_t count)
628 {
629   if(count >= tk->buffcount) {
630     tk->buffstart = 0;
631     tk->buffcount = 0;
632     return;
633   }
634 
635   tk->buffstart += count;
636   tk->buffcount -= count;
637 }
638 
utf8_seqlen(long codepoint)639 static inline unsigned int utf8_seqlen(long codepoint)
640 {
641   if(codepoint < 0x0000080) return 1;
642   if(codepoint < 0x0000800) return 2;
643   if(codepoint < 0x0010000) return 3;
644   if(codepoint < 0x0200000) return 4;
645   if(codepoint < 0x4000000) return 5;
646   return 6;
647 }
648 
fill_utf8(TermKeyKey * key)649 static void fill_utf8(TermKeyKey *key)
650 {
651   long codepoint = key->code.codepoint;
652   int nbytes = utf8_seqlen(codepoint);
653 
654   key->utf8[nbytes] = 0;
655 
656   // This is easier done backwards
657   int b = nbytes;
658   while(b > 1) {
659     b--;
660     key->utf8[b] = 0x80 | (codepoint & 0x3f);
661     codepoint >>= 6;
662   }
663 
664   switch(nbytes) {
665     case 1: key->utf8[0] =        (codepoint & 0x7f); break;
666     case 2: key->utf8[0] = 0xc0 | (codepoint & 0x1f); break;
667     case 3: key->utf8[0] = 0xe0 | (codepoint & 0x0f); break;
668     case 4: key->utf8[0] = 0xf0 | (codepoint & 0x07); break;
669     case 5: key->utf8[0] = 0xf8 | (codepoint & 0x03); break;
670     case 6: key->utf8[0] = 0xfc | (codepoint & 0x01); break;
671   }
672 }
673 
674 #define UTF8_INVALID 0xFFFD
parse_utf8(const unsigned char * bytes,size_t len,long * cp,size_t * nbytep)675 static TermKeyResult parse_utf8(const unsigned char *bytes, size_t len, long *cp, size_t *nbytep)
676 {
677   unsigned int nbytes;
678 
679   unsigned char b0 = bytes[0];
680 
681   if(b0 < 0x80) {
682     // Single byte ASCII
683     *cp = b0;
684     *nbytep = 1;
685     return TERMKEY_RES_KEY;
686   }
687   else if(b0 < 0xc0) {
688     // Starts with a continuation byte - that's not right
689     *cp = UTF8_INVALID;
690     *nbytep = 1;
691     return TERMKEY_RES_KEY;
692   }
693   else if(b0 < 0xe0) {
694     nbytes = 2;
695     *cp = b0 & 0x1f;
696   }
697   else if(b0 < 0xf0) {
698     nbytes = 3;
699     *cp = b0 & 0x0f;
700   }
701   else if(b0 < 0xf8) {
702     nbytes = 4;
703     *cp = b0 & 0x07;
704   }
705   else if(b0 < 0xfc) {
706     nbytes = 5;
707     *cp = b0 & 0x03;
708   }
709   else if(b0 < 0xfe) {
710     nbytes = 6;
711     *cp = b0 & 0x01;
712   }
713   else {
714     *cp = UTF8_INVALID;
715     *nbytep = 1;
716     return TERMKEY_RES_KEY;
717   }
718 
719   for(unsigned int b = 1; b < nbytes; b++) {
720     unsigned char cb;
721 
722     if(b >= len)
723       return TERMKEY_RES_AGAIN;
724 
725     cb = bytes[b];
726     if(cb < 0x80 || cb >= 0xc0) {
727       *cp = UTF8_INVALID;
728       *nbytep = b;
729       return TERMKEY_RES_KEY;
730     }
731 
732     *cp <<= 6;
733     *cp |= cb & 0x3f;
734   }
735 
736   // Check for overlong sequences
737   if(nbytes > utf8_seqlen(*cp))
738     *cp = UTF8_INVALID;
739 
740   // Check for UTF-16 surrogates or invalid *cps
741   if((*cp >= 0xD800 && *cp <= 0xDFFF) ||
742      *cp == 0xFFFE ||
743      *cp == 0xFFFF)
744     *cp = UTF8_INVALID;
745 
746   *nbytep = nbytes;
747   return TERMKEY_RES_KEY;
748 }
749 
emit_codepoint(TermKey * tk,long codepoint,TermKeyKey * key)750 static void emit_codepoint(TermKey *tk, long codepoint, TermKeyKey *key)
751 {
752   if(codepoint == 0) {
753     // ASCII NUL = Ctrl-Space
754     key->type = TERMKEY_TYPE_KEYSYM;
755     key->code.sym = TERMKEY_SYM_SPACE;
756     key->modifiers = TERMKEY_KEYMOD_CTRL;
757   }
758   else if(codepoint < 0x20) {
759     // C0 range
760     key->code.codepoint = 0;
761     key->modifiers = 0;
762 
763     if(!(tk->flags & TERMKEY_FLAG_NOINTERPRET) && tk->c0[codepoint].sym != TERMKEY_SYM_UNKNOWN) {
764       key->code.sym = tk->c0[codepoint].sym;
765       key->modifiers |= tk->c0[codepoint].modifier_set;
766     }
767 
768     if(!key->code.sym) {
769       key->type = TERMKEY_TYPE_UNICODE;
770       /* Generically modified Unicode ought not report the SHIFT state, or else
771        * we get into complicationg trying to report Shift-; vs : and so on...
772        * In order to be able to represent Ctrl-Shift-A as CTRL modified
773        * unicode A, we need to call Ctrl-A simply 'a', lowercase
774        */
775       if(codepoint+0x40 >= 'A' && codepoint+0x40 <= 'Z')
776         // it's a letter - use lowecase instead
777         key->code.codepoint = codepoint + 0x60;
778       else
779         key->code.codepoint = codepoint + 0x40;
780       key->modifiers = TERMKEY_KEYMOD_CTRL;
781     }
782     else {
783       key->type = TERMKEY_TYPE_KEYSYM;
784     }
785   }
786   else if(codepoint == 0x7f && !(tk->flags & TERMKEY_FLAG_NOINTERPRET)) {
787     // ASCII DEL
788     key->type = TERMKEY_TYPE_KEYSYM;
789     key->code.sym = TERMKEY_SYM_DEL;
790     key->modifiers = 0;
791   }
792   else if(codepoint >= 0x20 && codepoint < 0x80) {
793     // ASCII lowbyte range
794     key->type = TERMKEY_TYPE_UNICODE;
795     key->code.codepoint = codepoint;
796     key->modifiers = 0;
797   }
798   else if(codepoint >= 0x80 && codepoint < 0xa0) {
799     // UTF-8 never starts with a C1 byte. So we can be sure of these
800     key->type = TERMKEY_TYPE_UNICODE;
801     key->code.codepoint = codepoint - 0x40;
802     key->modifiers = TERMKEY_KEYMOD_CTRL|TERMKEY_KEYMOD_ALT;
803   }
804   else {
805     // UTF-8 codepoint
806     key->type = TERMKEY_TYPE_UNICODE;
807     key->code.codepoint = codepoint;
808     key->modifiers = 0;
809   }
810 
811   termkey_canonicalise(tk, key);
812 
813   if(key->type == TERMKEY_TYPE_UNICODE)
814     fill_utf8(key);
815 }
816 
termkey_canonicalise(TermKey * tk,TermKeyKey * key)817 void termkey_canonicalise(TermKey *tk, TermKeyKey *key)
818 {
819   int flags = tk->canonflags;
820 
821   if(flags & TERMKEY_CANON_SPACESYMBOL) {
822     if(key->type == TERMKEY_TYPE_UNICODE && key->code.codepoint == 0x20) {
823       key->type     = TERMKEY_TYPE_KEYSYM;
824       key->code.sym = TERMKEY_SYM_SPACE;
825     }
826   }
827   else {
828     if(key->type == TERMKEY_TYPE_KEYSYM && key->code.sym == TERMKEY_SYM_SPACE) {
829       key->type           = TERMKEY_TYPE_UNICODE;
830       key->code.codepoint = 0x20;
831       fill_utf8(key);
832     }
833   }
834 
835   if(flags & TERMKEY_CANON_DELBS) {
836     if(key->type == TERMKEY_TYPE_KEYSYM && key->code.sym == TERMKEY_SYM_DEL) {
837       key->code.sym = TERMKEY_SYM_BACKSPACE;
838     }
839   }
840 }
841 
peekkey(TermKey * tk,TermKeyKey * key,int force,size_t * nbytep)842 static TermKeyResult peekkey(TermKey *tk, TermKeyKey *key, int force, size_t *nbytep)
843 {
844   int again = 0;
845 
846   if(!tk->is_started) {
847     errno = EINVAL;
848     return TERMKEY_RES_ERROR;
849   }
850 
851 #ifdef DEBUG
852   fprintf(stderr, "getkey(force=%d): buffer ", force);
853   print_buffer(tk);
854   fprintf(stderr, "\n");
855 #endif
856 
857   if(tk->hightide) {
858     tk->buffstart += tk->hightide;
859     tk->buffcount -= tk->hightide;
860     tk->hightide = 0;
861   }
862 
863   TermKeyResult ret;
864   struct TermKeyDriverNode *p;
865   for(p = tk->drivers; p; p = p->next) {
866     ret = (p->driver->peekkey)(tk, p->info, key, force, nbytep);
867 
868 #ifdef DEBUG
869     fprintf(stderr, "Driver %s yields %s\n", p->driver->name, res2str(ret));
870 #endif
871 
872     switch(ret) {
873     case TERMKEY_RES_KEY:
874 #ifdef DEBUG
875       print_key(tk, key); fprintf(stderr, "\n");
876 #endif
877       // Slide the data down to stop it running away
878       {
879         size_t halfsize = tk->buffsize / 2;
880 
881         if(tk->buffstart > halfsize) {
882           memcpy(tk->buffer, tk->buffer + halfsize, halfsize);
883           tk->buffstart -= halfsize;
884         }
885       }
886 
887       /* fallthrough */
888     case TERMKEY_RES_EOF:
889     case TERMKEY_RES_ERROR:
890       return ret;
891 
892     case TERMKEY_RES_AGAIN:
893       if(!force)
894         again = 1;
895 
896       /* fallthrough */
897     case TERMKEY_RES_NONE:
898       break;
899     }
900   }
901 
902   if(again)
903     return TERMKEY_RES_AGAIN;
904 
905   ret = peekkey_simple(tk, key, force, nbytep);
906 
907 #ifdef DEBUG
908   fprintf(stderr, "getkey_simple(force=%d) yields %s\n", force, res2str(ret));
909   if(ret == TERMKEY_RES_KEY) {
910     print_key(tk, key); fprintf(stderr, "\n");
911   }
912 #endif
913 
914   return ret;
915 }
916 
peekkey_simple(TermKey * tk,TermKeyKey * key,int force,size_t * nbytep)917 static TermKeyResult peekkey_simple(TermKey *tk, TermKeyKey *key, int force, size_t *nbytep)
918 {
919   if(tk->buffcount == 0)
920     return tk->is_closed ? TERMKEY_RES_EOF : TERMKEY_RES_NONE;
921 
922   unsigned char b0 = CHARAT(0);
923 
924   if(b0 == 0x1b) {
925     // Escape-prefixed value? Might therefore be Alt+key
926     if(tk->buffcount == 1) {
927       // This might be an <Esc> press, or it may want to be part of a longer
928       // sequence
929       if(!force)
930         return TERMKEY_RES_AGAIN;
931 
932       (*tk->method.emit_codepoint)(tk, b0, key);
933       *nbytep = 1;
934       return TERMKEY_RES_KEY;
935     }
936 
937     // Try another key there
938     tk->buffstart++;
939     tk->buffcount--;
940 
941     // Run the full driver
942     TermKeyResult metakey_result = peekkey(tk, key, force, nbytep);
943 
944     tk->buffstart--;
945     tk->buffcount++;
946 
947     switch(metakey_result) {
948       case TERMKEY_RES_KEY:
949         key->modifiers |= TERMKEY_KEYMOD_ALT;
950         (*nbytep)++;
951         break;
952 
953       case TERMKEY_RES_NONE:
954       case TERMKEY_RES_EOF:
955       case TERMKEY_RES_AGAIN:
956       case TERMKEY_RES_ERROR:
957         break;
958     }
959 
960     return metakey_result;
961   }
962   else if(b0 < 0xa0) {
963     // Single byte C0, G0 or C1 - C1 is never UTF-8 initial byte
964     (*tk->method.emit_codepoint)(tk, b0, key);
965     *nbytep = 1;
966     return TERMKEY_RES_KEY;
967   }
968   else if(tk->flags & TERMKEY_FLAG_UTF8) {
969     // Some UTF-8
970     long codepoint;
971     TermKeyResult res = parse_utf8(tk->buffer + tk->buffstart, tk->buffcount, &codepoint, nbytep);
972 
973     if(res == TERMKEY_RES_AGAIN && force) {
974       /* There weren't enough bytes for a complete UTF-8 sequence but caller
975        * demands an answer. About the best thing we can do here is eat as many
976        * bytes as we have, and emit a UTF8_INVALID. If the remaining bytes
977        * arrive later, they'll be invalid too.
978        */
979       codepoint = UTF8_INVALID;
980       *nbytep = tk->buffcount;
981       res = TERMKEY_RES_KEY;
982     }
983 
984     key->type = TERMKEY_TYPE_UNICODE;
985     key->modifiers = 0;
986     (*tk->method.emit_codepoint)(tk, codepoint, key);
987     return res;
988   }
989   else {
990     // Non UTF-8 case - just report the raw byte
991     key->type = TERMKEY_TYPE_UNICODE;
992     key->code.codepoint = b0;
993     key->modifiers = 0;
994 
995     key->utf8[0] = key->code.codepoint;
996     key->utf8[1] = 0;
997 
998     *nbytep = 1;
999 
1000     return TERMKEY_RES_KEY;
1001   }
1002 }
1003 
peekkey_mouse(TermKey * tk,TermKeyKey * key,size_t * nbytep)1004 static TermKeyResult peekkey_mouse(TermKey *tk, TermKeyKey *key, size_t *nbytep)
1005 {
1006   if(tk->buffcount < 3)
1007     return TERMKEY_RES_AGAIN;
1008 
1009   key->type = TERMKEY_TYPE_MOUSE;
1010   key->code.mouse[0] = CHARAT(0) - 0x20;
1011   key->code.mouse[1] = CHARAT(1) - 0x20;
1012   key->code.mouse[2] = CHARAT(2) - 0x20;
1013   key->code.mouse[3] = 0;
1014 
1015   key->modifiers     = (key->code.mouse[0] & 0x1c) >> 2;
1016   key->code.mouse[0] &= ~0x1c;
1017 
1018   *nbytep = 3;
1019   return TERMKEY_RES_KEY;
1020 }
1021 
termkey_getkey(TermKey * tk,TermKeyKey * key)1022 TermKeyResult termkey_getkey(TermKey *tk, TermKeyKey *key)
1023 {
1024   size_t nbytes = 0;
1025   TermKeyResult ret = peekkey(tk, key, 0, &nbytes);
1026 
1027   if(ret == TERMKEY_RES_KEY)
1028     eat_bytes(tk, nbytes);
1029 
1030   if(ret == TERMKEY_RES_AGAIN)
1031     /* Call peekkey() again in force mode to obtain whatever it can */
1032     (void)peekkey(tk, key, 1, &nbytes);
1033     /* Don't eat it yet though */
1034 
1035   return ret;
1036 }
1037 
termkey_getkey_force(TermKey * tk,TermKeyKey * key)1038 TermKeyResult termkey_getkey_force(TermKey *tk, TermKeyKey *key)
1039 {
1040   size_t nbytes = 0;
1041   TermKeyResult ret = peekkey(tk, key, 1, &nbytes);
1042 
1043   if(ret == TERMKEY_RES_KEY)
1044     eat_bytes(tk, nbytes);
1045 
1046   return ret;
1047 }
1048 
termkey_waitkey(TermKey * tk,TermKeyKey * key)1049 TermKeyResult termkey_waitkey(TermKey *tk, TermKeyKey *key)
1050 {
1051   if(tk->fd == -1) {
1052     errno = EBADF;
1053     return TERMKEY_RES_ERROR;
1054   }
1055 
1056   while(1) {
1057     TermKeyResult ret = termkey_getkey(tk, key);
1058 
1059     switch(ret) {
1060       case TERMKEY_RES_KEY:
1061       case TERMKEY_RES_EOF:
1062       case TERMKEY_RES_ERROR:
1063         return ret;
1064 
1065       case TERMKEY_RES_NONE:
1066         ret = termkey_advisereadable(tk);
1067         if(ret == TERMKEY_RES_ERROR)
1068           return ret;
1069         break;
1070 
1071       case TERMKEY_RES_AGAIN:
1072         {
1073           if(tk->is_closed)
1074             // We're closed now. Never going to get more bytes so just go with
1075             // what we have
1076             return termkey_getkey_force(tk, key);
1077 
1078           struct pollfd fd;
1079 
1080 retry:
1081           fd.fd = tk->fd;
1082           fd.events = POLLIN;
1083 
1084           int pollret = poll(&fd, 1, tk->waittime);
1085           if(pollret == -1) {
1086             if(errno == EINTR && !(tk->flags & TERMKEY_FLAG_EINTR))
1087               goto retry;
1088 
1089             return TERMKEY_RES_ERROR;
1090           }
1091 
1092           if(fd.revents & (POLLIN|POLLHUP|POLLERR))
1093             ret = termkey_advisereadable(tk);
1094           else
1095             ret = TERMKEY_RES_NONE;
1096 
1097           if(ret == TERMKEY_RES_ERROR)
1098             return ret;
1099           if(ret == TERMKEY_RES_NONE)
1100             return termkey_getkey_force(tk, key);
1101         }
1102         break;
1103     }
1104   }
1105 
1106   /* UNREACHABLE */
1107 }
1108 
termkey_advisereadable(TermKey * tk)1109 TermKeyResult termkey_advisereadable(TermKey *tk)
1110 {
1111   ssize_t len;
1112 
1113   if(tk->fd == -1) {
1114     errno = EBADF;
1115     return TERMKEY_RES_ERROR;
1116   }
1117 
1118   if(tk->buffstart) {
1119     memmove(tk->buffer, tk->buffer + tk->buffstart, tk->buffcount);
1120     tk->buffstart = 0;
1121   }
1122 
1123   /* Not expecting it ever to be greater but doesn't hurt to handle that */
1124   if(tk->buffcount >= tk->buffsize) {
1125     errno = ENOMEM;
1126     return TERMKEY_RES_ERROR;
1127   }
1128 
1129 retry:
1130   len = read(tk->fd, tk->buffer + tk->buffcount, tk->buffsize - tk->buffcount);
1131 
1132   if(len == -1) {
1133     if(errno == EAGAIN)
1134       return TERMKEY_RES_NONE;
1135     else if(errno == EINTR && !(tk->flags & TERMKEY_FLAG_EINTR))
1136       goto retry;
1137     else
1138       return TERMKEY_RES_ERROR;
1139   }
1140   else if(len < 1) {
1141     tk->is_closed = 1;
1142     return TERMKEY_RES_NONE;
1143   }
1144   else {
1145     tk->buffcount += len;
1146     return TERMKEY_RES_AGAIN;
1147   }
1148 }
1149 
termkey_push_bytes(TermKey * tk,const char * bytes,size_t len)1150 size_t termkey_push_bytes(TermKey *tk, const char *bytes, size_t len)
1151 {
1152   if(tk->buffstart) {
1153     memmove(tk->buffer, tk->buffer + tk->buffstart, tk->buffcount);
1154     tk->buffstart = 0;
1155   }
1156 
1157   /* Not expecting it ever to be greater but doesn't hurt to handle that */
1158   if(tk->buffcount >= tk->buffsize) {
1159     errno = ENOMEM;
1160     return (size_t)-1;
1161   }
1162 
1163   if(len > tk->buffsize - tk->buffcount)
1164     len = tk->buffsize - tk->buffcount;
1165 
1166   // memcpy(), not strncpy() in case of null bytes in input
1167   memcpy(tk->buffer + tk->buffcount, bytes, len);
1168   tk->buffcount += len;
1169 
1170   return len;
1171 }
1172 
termkey_register_keyname(TermKey * tk,TermKeySym sym,const char * name)1173 TermKeySym termkey_register_keyname(TermKey *tk, TermKeySym sym, const char *name)
1174 {
1175   if(!sym)
1176     sym = tk->nkeynames;
1177 
1178   if(sym >= tk->nkeynames) {
1179     const char **new_keynames = realloc(tk->keynames, sizeof(new_keynames[0]) * (sym + 1));
1180     if(!new_keynames)
1181       return -1;
1182 
1183     tk->keynames = new_keynames;
1184 
1185     // Fill in the hole
1186     for(int i = tk->nkeynames; i < sym; i++)
1187       tk->keynames[i] = NULL;
1188 
1189     tk->nkeynames = sym + 1;
1190   }
1191 
1192   tk->keynames[sym] = name;
1193 
1194   return sym;
1195 }
1196 
termkey_get_keyname(TermKey * tk,TermKeySym sym)1197 const char *termkey_get_keyname(TermKey *tk, TermKeySym sym)
1198 {
1199   if(sym == TERMKEY_SYM_UNKNOWN)
1200     return "UNKNOWN";
1201 
1202   if(sym < tk->nkeynames)
1203     return tk->keynames[sym];
1204 
1205   return "UNKNOWN";
1206 }
1207 
termkey_lookup_keyname_format(TermKey * tk,const char * str,TermKeySym * sym,TermKeyFormat format)1208 static const char *termkey_lookup_keyname_format(TermKey *tk, const char *str, TermKeySym *sym, TermKeyFormat format)
1209 {
1210   /* We store an array, so we can't do better than a linear search. Doesn't
1211    * matter because user won't be calling this too often */
1212 
1213   for(*sym = 0; *sym < tk->nkeynames; (*sym)++) {
1214     const char *thiskey = tk->keynames[*sym];
1215     if(!thiskey)
1216       continue;
1217     size_t len = strlen(thiskey);
1218     if(format & TERMKEY_FORMAT_LOWERSPACE) {
1219       const char *thisstr = str;
1220       if(strpncmp_camel(&thisstr, &thiskey, len) == 0)
1221           return thisstr;
1222     }
1223     else {
1224       if(strncmp(str, thiskey, len) == 0)
1225         return (char *)str + len;
1226     }
1227   }
1228 
1229   return NULL;
1230 }
1231 
termkey_lookup_keyname(TermKey * tk,const char * str,TermKeySym * sym)1232 const char *termkey_lookup_keyname(TermKey *tk, const char *str, TermKeySym *sym)
1233 {
1234   return termkey_lookup_keyname_format(tk, str, sym, 0);
1235 }
1236 
termkey_keyname2sym(TermKey * tk,const char * keyname)1237 TermKeySym termkey_keyname2sym(TermKey *tk, const char *keyname)
1238 {
1239   TermKeySym sym;
1240   const char *endp = termkey_lookup_keyname(tk, keyname, &sym);
1241   if(!endp || endp[0])
1242     return TERMKEY_SYM_UNKNOWN;
1243   return sym;
1244 }
1245 
register_c0(TermKey * tk,TermKeySym sym,unsigned char ctrl,const char * name)1246 static TermKeySym register_c0(TermKey *tk, TermKeySym sym, unsigned char ctrl, const char *name)
1247 {
1248   return register_c0_full(tk, sym, 0, 0, ctrl, name);
1249 }
1250 
register_c0_full(TermKey * tk,TermKeySym sym,int modifier_set,int modifier_mask,unsigned char ctrl,const char * name)1251 static TermKeySym register_c0_full(TermKey *tk, TermKeySym sym, int modifier_set, int modifier_mask, unsigned char ctrl, const char *name)
1252 {
1253   if(ctrl >= 0x20) {
1254     errno = EINVAL;
1255     return -1;
1256   }
1257 
1258   if(name)
1259     sym = termkey_register_keyname(tk, sym, name);
1260 
1261   tk->c0[ctrl].sym = sym;
1262   tk->c0[ctrl].modifier_set = modifier_set;
1263   tk->c0[ctrl].modifier_mask = modifier_mask;
1264 
1265   return sym;
1266 }
1267 
1268 /* Previous name for this function
1269  * No longer declared in termkey.h but it remains in the compiled library for
1270  * backward-compatibility reasons.
1271  */
termkey_snprint_key(TermKey * tk,char * buffer,size_t len,TermKeyKey * key,TermKeyFormat format)1272 size_t termkey_snprint_key(TermKey *tk, char *buffer, size_t len, TermKeyKey *key, TermKeyFormat format)
1273 {
1274   return termkey_strfkey(tk, buffer, len, key, format);
1275 }
1276 
1277 static struct modnames {
1278   const char *shift, *alt, *ctrl;
1279 }
1280 modnames[] = {
1281   { "S",     "A",    "C" },    // 0
1282   { "Shift", "Alt",  "Ctrl" }, // LONGMOD
1283   { "S",     "M",    "C" },    // ALTISMETA
1284   { "Shift", "Meta", "Ctrl" }, // ALTISMETA+LONGMOD
1285   { "s",     "a",    "c" },    // LOWERMOD
1286   { "shift", "alt",  "ctrl" }, // LOWERMOD+LONGMOD
1287   { "s",     "m",    "c" },    // LOWERMOD+ALTISMETA
1288   { "shift", "meta", "ctrl" }, // LOWERMOD+ALTISMETA+LONGMOD
1289 };
1290 
termkey_strfkey(TermKey * tk,char * buffer,size_t len,TermKeyKey * key,TermKeyFormat format)1291 size_t termkey_strfkey(TermKey *tk, char *buffer, size_t len, TermKeyKey *key, TermKeyFormat format)
1292 {
1293   size_t pos = 0;
1294   size_t l = 0;
1295 
1296   struct modnames *mods = &modnames[!!(format & TERMKEY_FORMAT_LONGMOD) +
1297                                     !!(format & TERMKEY_FORMAT_ALTISMETA) * 2 +
1298                                     !!(format & TERMKEY_FORMAT_LOWERMOD) * 4];
1299 
1300   int wrapbracket = (format & TERMKEY_FORMAT_WRAPBRACKET) &&
1301                     (key->type != TERMKEY_TYPE_UNICODE || key->modifiers != 0);
1302 
1303   char sep = (format & TERMKEY_FORMAT_SPACEMOD) ? ' ' : '-';
1304 
1305   if(format & TERMKEY_FORMAT_CARETCTRL &&
1306      key->type == TERMKEY_TYPE_UNICODE &&
1307      key->modifiers == TERMKEY_KEYMOD_CTRL) {
1308     long codepoint = key->code.codepoint;
1309 
1310     // Handle some of the special casesfirst
1311     if(codepoint >= 'a' && codepoint <= 'z') {
1312       l = snprintf(buffer + pos, len - pos, wrapbracket ? "<^%c>" : "^%c", (char)codepoint - 0x20);
1313       if(l <= 0) return pos;
1314       pos += l;
1315       return pos;
1316     }
1317     else if((codepoint >= '@' && codepoint < 'A') ||
1318             (codepoint > 'Z' && codepoint <= '_')) {
1319       l = snprintf(buffer + pos, len - pos, wrapbracket ? "<^%c>" : "^%c", (char)codepoint);
1320       if(l <= 0) return pos;
1321       pos += l;
1322       return pos;
1323     }
1324   }
1325 
1326   if(wrapbracket) {
1327     l = snprintf(buffer + pos, len - pos, "<");
1328     if(l <= 0) return pos;
1329     pos += l;
1330   }
1331 
1332   if(key->modifiers & TERMKEY_KEYMOD_ALT) {
1333     l = snprintf(buffer + pos, len - pos, "%s%c", mods->alt, sep);
1334     if(l <= 0) return pos;
1335     pos += l;
1336   }
1337 
1338   if(key->modifiers & TERMKEY_KEYMOD_CTRL) {
1339     l = snprintf(buffer + pos, len - pos, "%s%c", mods->ctrl, sep);
1340     if(l <= 0) return pos;
1341     pos += l;
1342   }
1343 
1344   if(key->modifiers & TERMKEY_KEYMOD_SHIFT) {
1345     l = snprintf(buffer + pos, len - pos, "%s%c", mods->shift, sep);
1346     if(l <= 0) return pos;
1347     pos += l;
1348   }
1349 
1350   switch(key->type) {
1351   case TERMKEY_TYPE_UNICODE:
1352     if(!key->utf8[0]) // In case of user-supplied key structures
1353       fill_utf8(key);
1354     l = snprintf(buffer + pos, len - pos, "%s", key->utf8);
1355     break;
1356   case TERMKEY_TYPE_KEYSYM:
1357     {
1358       const char *name = termkey_get_keyname(tk, key->code.sym);
1359       if(format & TERMKEY_FORMAT_LOWERSPACE)
1360         l = snprint_cameltospaces(buffer + pos, len - pos, name);
1361       else
1362         l = snprintf(buffer + pos, len - pos, "%s", name);
1363     }
1364     break;
1365   case TERMKEY_TYPE_FUNCTION:
1366     l = snprintf(buffer + pos, len - pos, "%c%d",
1367         (format & TERMKEY_FORMAT_LOWERSPACE ? 'f' : 'F'), key->code.number);
1368     break;
1369   case TERMKEY_TYPE_MOUSE:
1370     {
1371       TermKeyMouseEvent ev;
1372       int button;
1373       int line, col;
1374       termkey_interpret_mouse(tk, key, &ev, &button, &line, &col);
1375 
1376       static const char *evnames[] = { "Unknown", "Press", "Drag", "Release" };
1377 
1378       l = snprintf(buffer + pos, len - pos, "Mouse%s(%d)",
1379           evnames[ev], button);
1380 
1381       if(format & TERMKEY_FORMAT_MOUSE_POS) {
1382         if(l <= 0) return pos;
1383         pos += l;
1384 
1385         l = snprintf(buffer + pos, len - pos, " @ (%u,%u)", col, line);
1386       }
1387     }
1388     break;
1389   case TERMKEY_TYPE_POSITION:
1390     l = snprintf(buffer + pos, len - pos, "Position");
1391     break;
1392   case TERMKEY_TYPE_MODEREPORT:
1393     {
1394       int initial, mode, value;
1395       termkey_interpret_modereport(tk, key, &initial, &mode, &value);
1396       if(initial)
1397         l = snprintf(buffer + pos, len - pos, "Mode(%c%d=%d)", initial, mode, value);
1398       else
1399         l = snprintf(buffer + pos, len - pos, "Mode(%d=%d)", mode, value);
1400     }
1401   case TERMKEY_TYPE_DCS:
1402     l = snprintf(buffer + pos, len - pos, "DCS");
1403     break;
1404   case TERMKEY_TYPE_OSC:
1405     l = snprintf(buffer + pos, len - pos, "OSC");
1406     break;
1407   case TERMKEY_TYPE_UNKNOWN_CSI:
1408     l = snprintf(buffer + pos, len - pos, "CSI %c", key->code.number & 0xff);
1409     break;
1410   }
1411 
1412   if(l <= 0) return pos;
1413   pos += l;
1414 
1415   if(wrapbracket) {
1416     l = snprintf(buffer + pos, len - pos, ">");
1417     if(l <= 0) return pos;
1418     pos += l;
1419   }
1420 
1421   return pos;
1422 }
1423 
termkey_strpkey(TermKey * tk,const char * str,TermKeyKey * key,TermKeyFormat format)1424 const char *termkey_strpkey(TermKey *tk, const char *str, TermKeyKey *key, TermKeyFormat format)
1425 {
1426   struct modnames *mods = &modnames[!!(format & TERMKEY_FORMAT_LONGMOD) +
1427                                     !!(format & TERMKEY_FORMAT_ALTISMETA) * 2 +
1428                                     !!(format & TERMKEY_FORMAT_LOWERMOD) * 4];
1429 
1430   key->modifiers = 0;
1431 
1432   if((format & TERMKEY_FORMAT_CARETCTRL) && str[0] == '^' && str[1]) {
1433     str = termkey_strpkey(tk, str+1, key, format & ~TERMKEY_FORMAT_CARETCTRL);
1434 
1435     if(!str ||
1436        key->type != TERMKEY_TYPE_UNICODE ||
1437        key->code.codepoint < '@' || key->code.codepoint > '_' ||
1438        key->modifiers != 0)
1439       return NULL;
1440 
1441     if(key->code.codepoint >= 'A' && key->code.codepoint <= 'Z')
1442       key->code.codepoint += 0x20;
1443     key->modifiers = TERMKEY_KEYMOD_CTRL;
1444     fill_utf8(key);
1445     return (char *)str;
1446   }
1447 
1448   const char *sep_at;
1449 
1450   while((sep_at = strchr(str, (format & TERMKEY_FORMAT_SPACEMOD) ? ' ' : '-'))) {
1451     size_t n = sep_at - str;
1452 
1453     if(n == strlen(mods->alt) && strncmp(mods->alt, str, n) == 0)
1454       key->modifiers |= TERMKEY_KEYMOD_ALT;
1455     else if(n == strlen(mods->ctrl) && strncmp(mods->ctrl, str, n) == 0)
1456       key->modifiers |= TERMKEY_KEYMOD_CTRL;
1457     else if(n == strlen(mods->shift) && strncmp(mods->shift, str, n) == 0)
1458       key->modifiers |= TERMKEY_KEYMOD_SHIFT;
1459 
1460     else
1461       break;
1462 
1463     str = sep_at + 1;
1464   }
1465 
1466   size_t nbytes;
1467   ssize_t snbytes;
1468   const char *endstr;
1469 
1470   if((endstr = termkey_lookup_keyname_format(tk, str, &key->code.sym, format))) {
1471     key->type = TERMKEY_TYPE_KEYSYM;
1472     str = endstr;
1473   }
1474   else if(sscanf(str, "F%d%zn", &key->code.number, &snbytes) == 1) {
1475     key->type = TERMKEY_TYPE_FUNCTION;
1476     str += snbytes;
1477   }
1478   // Unicode must be last
1479   else if(parse_utf8((unsigned const char *)str, strlen(str), &key->code.codepoint, &nbytes) == TERMKEY_RES_KEY) {
1480     key->type = TERMKEY_TYPE_UNICODE;
1481     fill_utf8(key);
1482     str += nbytes;
1483   }
1484   // TODO: Consider mouse events?
1485   else
1486     return NULL;
1487 
1488   termkey_canonicalise(tk, key);
1489 
1490   return (char *)str;
1491 }
1492 
termkey_keycmp(TermKey * tk,const TermKeyKey * key1p,const TermKeyKey * key2p)1493 int termkey_keycmp(TermKey *tk, const TermKeyKey *key1p, const TermKeyKey *key2p)
1494 {
1495   /* Copy the key structs since we'll be modifying them */
1496   TermKeyKey key1 = *key1p, key2 = *key2p;
1497 
1498   termkey_canonicalise(tk, &key1);
1499   termkey_canonicalise(tk, &key2);
1500 
1501   if(key1.type != key2.type)
1502     return key1.type - key2.type;
1503 
1504   switch(key1.type) {
1505     case TERMKEY_TYPE_UNICODE:
1506       if(key1.code.codepoint != key2.code.codepoint)
1507         return key1.code.codepoint - key2.code.codepoint;
1508       break;
1509     case TERMKEY_TYPE_KEYSYM:
1510       if(key1.code.sym != key2.code.sym)
1511         return key1.code.sym - key2.code.sym;
1512       break;
1513     case TERMKEY_TYPE_FUNCTION:
1514     case TERMKEY_TYPE_UNKNOWN_CSI:
1515       if(key1.code.number != key2.code.number)
1516         return key1.code.number - key2.code.number;
1517       break;
1518     case TERMKEY_TYPE_MOUSE:
1519       {
1520         int cmp = strncmp(key1.code.mouse, key2.code.mouse, 4);
1521         if(cmp != 0)
1522           return cmp;
1523       }
1524       break;
1525     case TERMKEY_TYPE_POSITION:
1526       {
1527         int line1, col1, line2, col2;
1528         termkey_interpret_position(tk, &key1, &line1, &col1);
1529         termkey_interpret_position(tk, &key2, &line2, &col2);
1530         if(line1 != line2)
1531           return line1 - line2;
1532         return col1 - col2;
1533       }
1534       break;
1535     case TERMKEY_TYPE_DCS:
1536     case TERMKEY_TYPE_OSC:
1537       return key1p - key2p;
1538     case TERMKEY_TYPE_MODEREPORT:
1539       {
1540         int initial1, initial2, mode1, mode2, value1, value2;
1541         termkey_interpret_modereport(tk, &key1, &initial1, &mode1, &value1);
1542         termkey_interpret_modereport(tk, &key2, &initial2, &mode2, &value2);
1543         if(initial1 != initial2)
1544           return initial1 - initial2;
1545         if(mode1 != mode2)
1546           return mode1 - mode2;
1547         return value1 - value2;
1548       }
1549   }
1550 
1551   return key1.modifiers - key2.modifiers;
1552 }
1553