summaryrefslogtreecommitdiff
path: root/src/cmd.c
blob: 1aaf7615eb3eade7c5e36cc58363bf12bffacc0e (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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/**
 * @file src/cmd.c  Command Interface
 *
 * Copyright (C) 2010 - 2016 Creytiv.com
 */
#include <ctype.h>
#include <string.h>
#include <re.h>
#include <baresip.h>
#include "core.h"


enum {
	KEYCODE_DEL = 0x7f,
	LONG_PREFIX = '/'
};


struct cmds {
	struct le le;
	const struct cmd *cmdv;
	size_t cmdc;
};

struct cmd_ctx {
	struct mbuf *mb;
	const struct cmd *cmd;
	bool is_long;
};

struct commands {
	struct list cmdl;        /**< List of command blocks (struct cmds) */
};


static int cmd_print_all(struct re_printf *pf,
			 const struct commands *commands,
			 bool print_long, bool print_short,
			 const char *match, size_t match_len);


static void destructor(void *arg)
{
	struct cmds *cmds = arg;

	list_unlink(&cmds->le);
}


static void ctx_destructor(void *arg)
{
	struct cmd_ctx *ctx = arg;

	mem_deref(ctx->mb);
}


static void commands_destructor(void *data)
{
	struct commands *commands = data;

	list_flush(&commands->cmdl);
}


static int ctx_alloc(struct cmd_ctx **ctxp, const struct cmd *cmd)
{
	struct cmd_ctx *ctx;

	ctx = mem_zalloc(sizeof(*ctx), ctx_destructor);
	if (!ctx)
		return ENOMEM;

	ctx->mb = mbuf_alloc(32);
	if (!ctx->mb) {
		mem_deref(ctx);
		return ENOMEM;
	}

	ctx->cmd = cmd;

	*ctxp = ctx;

	return 0;
}


struct cmds *cmds_find(const struct commands *commands,
		       const struct cmd *cmdv)
{
	struct le *le;

	if (!commands || !cmdv)
		return NULL;

	for (le = commands->cmdl.head; le; le = le->next) {
		struct cmds *cmds = le->data;

		if (cmds->cmdv == cmdv)
			return cmds;
	}

	return NULL;
}


static const struct cmd *cmd_find_by_key(const struct commands *commands,
					 char key)
{
	struct le *le;

	if (!commands)
		return NULL;

	for (le = commands->cmdl.tail; le; le = le->prev) {

		struct cmds *cmds = le->data;
		size_t i;

		for (i=0; i<cmds->cmdc; i++) {

			const struct cmd *cmd = &cmds->cmdv[i];

			if (cmd->key == key && cmd->h)
				return cmd;
		}
	}

	return NULL;
}


static const char *cmd_name(char *buf, size_t sz, const struct cmd *cmd)
{
	switch (cmd->key) {

	case ' ':   return "SPACE";
	case '\n':  return "ENTER";
	case KEYCODE_ESC:   return "ESC";
	}

	buf[0] = cmd->key;
	buf[1] = '\0';

	if (cmd->flags & CMD_PRM)
		strncat(buf, " ..", sz-1);

	return buf;
}


static size_t get_match_long(const struct commands *commands,
			     const struct cmd **cmdp,
			     const char *str, size_t len)
{
	struct le *le;
	size_t nmatch = 0;

	if (!commands)
		return 0;

	for (le = commands->cmdl.head; le; le = le->next) {

		struct cmds *cmds = le->data;
		size_t i;

		for (i=0; i<cmds->cmdc; i++) {

			const struct cmd *cmd = &cmds->cmdv[i];

			if (!str_isset(cmd->name))
				continue;

			if (str_len(cmd->name) >= len &&
			    0 == memcmp(cmd->name, str, len)) {

				++nmatch;
				*cmdp = cmd;
			}
		}
	}

	return nmatch;
}


static int editor_input(struct commands *commands, struct mbuf *mb, char key,
			struct re_printf *pf, bool *del, bool is_long)
{
	int err = 0;

	switch (key) {

	case KEYCODE_ESC:
		*del = true;
		return re_hprintf(pf, "\nCancel\n");

	case KEYCODE_NONE:
	case KEYCODE_REL:
		break;

	case '\n':
		*del = true;
		return re_hprintf(pf, "\n");

	case '\b':
	case KEYCODE_DEL:
		if (mb->pos > 0) {
			err |= re_hprintf(pf, "\b ");
			mb->pos = mb->end = (mb->pos - 1);
		}
		break;

	case '\t':
		if (is_long) {
			const struct cmd *cmd = NULL;
			size_t n;

			err = re_hprintf(pf,
					 "TAB completion for \"%b\":\n",
					 mb->buf, mb->end);
			if (err)
				return err;

			/* Find all long commands that matches the N
			 * first characters of the input string.
			 *
			 * If the number of matches is exactly one,
			 * we can regard it as TAB completion.
			 */

			err = cmd_print_all(pf, commands, true, false,
					    (char *)mb->buf, mb->end);
			if (err)
				return err;

			n = get_match_long(commands, &cmd,
					   (char *)mb->buf, mb->end);
			if (n == 1 && cmd) {

				mb->pos = 0;
				mbuf_write_str(mb, cmd->name);
			}
			else if (n == 0) {
				err = re_hprintf(pf, "(none)\n");
			}
		}
		else {
			err = mbuf_write_u8(mb, key);
		}
		break;

	default:
		err = mbuf_write_u8(mb, key);
		break;
	}

	if (is_long) {
		err |= re_hprintf(pf, "\r/%b",
				  mb->buf, mb->end);
	}
	else
		err |= re_hprintf(pf, "\r> %32b", mb->buf, mb->end);

	return err;
}


static int cmd_report(const struct cmd *cmd, struct re_printf *pf,
		      struct mbuf *mb, bool compl, void *data)
{
	struct cmd_arg arg;
	int err;

	memset(&arg, 0, sizeof(arg));

	mb->pos = 0;
	err = mbuf_strdup(mb, &arg.prm, mb->end);
	if (err)
		return err;

	arg.key      = cmd->key;
	arg.complete = compl;
	arg.data     = data;

	err = cmd->h(pf, &arg);

	mem_deref(arg.prm);

	return err;
}


int cmd_process_long(struct commands *commands, const char *str, size_t len,
		     struct re_printf *pf_resp, void *data)
{
	struct cmd_arg arg;
	const struct cmd *cmd_long;
	char *name = NULL, *prm = NULL;
	struct pl pl_name, pl_prm;
	int err;

	if (!str || !len)
		return EINVAL;

	memset(&arg, 0, sizeof(arg));

	err = re_regex(str, len, "[^ ]+[ ]*[~]*", &pl_name, NULL, &pl_prm);
	if (err) {
		return err;
	}

	err = pl_strdup(&name, &pl_name);
	if (pl_isset(&pl_prm))
		err |= pl_strdup(&prm, &pl_prm);
	if (err)
		goto out;

	cmd_long = cmd_find_long(commands, name);
	if (cmd_long) {

		arg.key      = LONG_PREFIX;
		arg.prm      = prm;
		arg.complete = true;
		arg.data     = data;

		if (cmd_long->h)
			err = cmd_long->h(pf_resp, &arg);
	}
	else {
		err = re_hprintf(pf_resp, "command not found (%s)\n", name);
	}

 out:
	mem_deref(name);
	mem_deref(prm);

	return err;
}


static int cmd_process_edit(struct commands *commands,
			    struct cmd_ctx **ctxp, char key,
			    struct re_printf *pf, void *data)
{
	struct cmd_ctx *ctx;
	bool compl = (key == '\n'), del = false;
	int err;

	if (!ctxp)
		return EINVAL;

	ctx = *ctxp;

	err = editor_input(commands, ctx->mb, key, pf, &del, ctx->is_long);
	if (err)
		return err;

	if (ctx->is_long) {

		if (compl) {

			err = cmd_process_long(commands,
					       (char *)ctx->mb->buf,
					       ctx->mb->end,
					       pf, data);
		}
	}
	else {
		if (compl ||
		    (ctx->cmd && ctx->cmd->flags & CMD_PROG))
			err = cmd_report(ctx->cmd, pf, ctx->mb, compl, data);
	}

	if (del)
		*ctxp = mem_deref(*ctxp);

	return err;
}


/**
 * Register commands
 *
 * @param commands Commands container
 * @param cmdv     Array of commands
 * @param cmdc     Number of commands
 *
 * @return 0 if success, otherwise errorcode
 */
int cmd_register(struct commands *commands,
		 const struct cmd *cmdv, size_t cmdc)
{
	struct cmds *cmds;
	size_t i;

	if (!commands || !cmdv || !cmdc)
		return EINVAL;

	cmds = cmds_find(commands, cmdv);
	if (cmds)
		return EALREADY;

	/* verify that command is not registered */
	for (i=0; i<cmdc; i++) {
		const struct cmd *cmd = &cmdv[i];

		if (cmd->key) {
			const struct cmd *x = cmd_find_by_key(commands,
							      cmd->key);
			if (x) {
				warning("short command '%c' already"
					" registered as \"%s\"\n",
					x->key, x->desc);
				return EALREADY;
			}
		}

		if (cmd->key == LONG_PREFIX) {
			warning("cmd: cannot register command with"
				" short key '%c'\n", cmd->key);
			return EINVAL;
		}

		if (str_isset(cmd->name) &&
		    cmd_find_long(commands, cmd->name)) {
			warning("cmd: long command '%s' already registered\n",
				cmd->name);
			return EINVAL;
		}
	}

	cmds = mem_zalloc(sizeof(*cmds), destructor);
	if (!cmds)
		return ENOMEM;

	cmds->cmdv = cmdv;
	cmds->cmdc = cmdc;

	list_append(&commands->cmdl, &cmds->le, cmds);

	return 0;
}


/**
 * Unregister commands
 *
 * @param commands Commands container
 * @param cmdv     Array of commands
 */
void cmd_unregister(struct commands *commands, const struct cmd *cmdv)
{
	mem_deref(cmds_find(commands, cmdv));
}


const struct cmd *cmd_find_long(const struct commands *commands,
				const char *name)
{
	struct le *le;

	if (!commands || !name)
		return NULL;

	for (le = commands->cmdl.tail; le; le = le->prev) {

		struct cmds *cmds = le->data;
		size_t i;

		for (i=0; i<cmds->cmdc; i++) {

			const struct cmd *cmd = &cmds->cmdv[i];

			if (0 == str_casecmp(name, cmd->name) && cmd->h)
				return cmd;
		}
	}

	return NULL;
}


/**
 * Process input characters to the command system
 *
 * @param commands Commands container
 * @param ctxp     Pointer to context for editor (optional)
 * @param key      Input character
 * @param pf       Print function
 * @param data     Application data
 *
 * @return 0 if success, otherwise errorcode
 */
int cmd_process(struct commands *commands, struct cmd_ctx **ctxp, char key,
		struct re_printf *pf, void *data)
{
	const struct cmd *cmd;

	if (!commands)
		return EINVAL;

	if (key == KEYCODE_NONE) {
		warning("cmd: process: illegal keycode NONE\n");
		return EINVAL;
	}

	/* are we in edit-mode? */
	if (ctxp && *ctxp) {

		if (key == KEYCODE_REL)
			return 0;

		return cmd_process_edit(commands, ctxp, key, pf, data);
	}

	cmd = cmd_find_by_key(commands, key);
	if (cmd) {
		struct cmd_arg arg;

		/* check for parameters */
		if (cmd->flags & CMD_PRM) {

			int err = 0;

			if (ctxp) {
				err = ctx_alloc(ctxp, cmd);
				if (err)
					return err;
			}

			key = isdigit(key) ? key : KEYCODE_REL;

			return cmd_process_edit(commands, ctxp, key, pf, data);
		}

		arg.key      = key;
		arg.prm      = NULL;
		arg.complete = true;
		arg.data     = data;

		return cmd->h(pf, &arg);
	}
	else if (key == LONG_PREFIX) {

		int err;

		err = re_hprintf(pf, "%c", LONG_PREFIX);
		if (err)
			return err;

		if (!ctxp) {
			warning("cmd: ctxp is required\n");
			return EINVAL;
		}

		err = ctx_alloc(ctxp, cmd);
		if (err)
			return err;

		(*ctxp)->is_long = true;

		return 0;
	}
	else if (key == '\t') {
		return cmd_print_all(pf, commands, false, true, NULL, 0);
	}

	if (key == KEYCODE_REL)
		return 0;

	return cmd_print(pf, commands);
}


struct cmd_sort {
	struct le le;
	const struct cmd *cmd;
};


static bool sort_handler(struct le *le1, struct le *le2, void *arg)
{
	struct cmd_sort *cs1 = le1->data;
	struct cmd_sort *cs2 = le2->data;
	const struct cmd *cmd1 = cs1->cmd;
	const struct cmd *cmd2 = cs2->cmd;
	bool print_long  = *(bool *)arg;

	if (print_long) {
		return str_casecmp(cs2->cmd->name ? cs2->cmd->name : "",
				   cs1->cmd->name ? cs1->cmd->name : "") >= 0;
	}
	else {
		return tolower(cmd2->key) >= tolower(cmd1->key);
	}
}


static int cmd_print_all(struct re_printf *pf,
			 const struct commands *commands,
			 bool print_long, bool print_short,
			 const char *match, size_t match_len)
{
	struct list sortedl = LIST_INIT;
	struct le *le;
	size_t width_long = 1;
	size_t width_short = 5;
	char fmt[64];
	char buf[16];
	int err = 0;

	if (!commands)
		return EINVAL;

	for (le = commands->cmdl.head; le; le = le->next) {

		struct cmds *cmds = le->data;
		size_t i;

		for (i=0; i<cmds->cmdc; i++) {

			const struct cmd *cmd = &cmds->cmdv[i];
			struct cmd_sort *cs;

			if (match && match_len) {

				if (str_len(cmd->name) >= match_len &&
				    0 == memcmp(cmd->name, match, match_len)) {
					/* Match */
				}
				else {
					continue;
				}
			}

			if (!str_isset(cmd->desc))
				continue;

			if (print_short && !print_long) {

				if (cmd->key == KEYCODE_NONE)
					continue;
			}

			cs = mem_zalloc(sizeof(*cs), NULL);
			if (!cs) {
				err = ENOMEM;
				goto out;
			}
			cs->cmd = cmd;

			list_append(&sortedl, &cs->le, cs);

			width_long = max(width_long, 1+str_len(cmd->name)+3);
		}
	}

	list_sort(&sortedl, sort_handler, &print_long);

	if (re_snprintf(fmt, sizeof(fmt),
			"  %%-%zus    %%-%zus    %%s\n",
			width_long, width_short) < 0) {
		err = ENOMEM;
		goto out;
	}

	for (le = sortedl.head; le; le = le->next) {
		struct cmd_sort *cs = le->data;
		const struct cmd *cmd = cs->cmd;
		char namep[64] = "";

		if (print_long && str_isset(cmd->name)) {
			re_snprintf(namep, sizeof(namep), "%c%s%s",
				    LONG_PREFIX, cmd->name,
				    (cmd->flags & CMD_PRM) ? " .." : "");
		}

		err |= re_hprintf(pf, fmt,
				  namep,
				  (print_short && cmd->key)
				    ? cmd_name(buf, sizeof(buf), cmd)
				    : "",
				  cmd->desc);
	}

	err |= re_hprintf(pf, "\n");

 out:
	list_flush(&sortedl);
	return err;
}


/**
 * Print a list of available commands
 *
 * @param pf       Print function
 * @param commands Commands container
 *
 * @return 0 if success, otherwise errorcode
 */
int cmd_print(struct re_printf *pf, const struct commands *commands)
{
	int err = 0;

	if (!pf)
		return EINVAL;

	err |= re_hprintf(pf, "--- Help ---\n");
	err |= cmd_print_all(pf, commands, true, true, NULL, 0);
	err |= re_hprintf(pf, "\n");

	return err;
}


int cmd_init(struct commands **commandsp)
{
	struct commands *commands;

	if (!commandsp)
		return EINVAL;

	commands = mem_zalloc(sizeof(*commands), commands_destructor);
	if (!commands)
		return ENOMEM;

	list_init(&commands->cmdl);

	*commandsp = commands;

	return 0;
}