1 /*
2  * bindings.c
3  *
4  * Functions for dealing with key bindings.
5  *
6  * This file is part of the ckpass project.
7  *
8  * Copyright (C) 2009  Heath N. Caldwell <hncaldwell@gmail.com>
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24 
25 #include <stdlib.h>
26 #include <string.h>
27 
28 #include "bindings.h"
29 
new_binding_set()30 struct binding *new_binding_set()
31 {
32 	struct binding *set;
33 
34 	set = malloc(sizeof(struct binding));
35 	set->key = 0;
36 
37 	return set;
38 }
39 
add_binding(struct binding ** set,int key,const char * command)40 void add_binding(struct binding **set, int key, const char *command)
41 {
42 	struct binding *b;
43 	int i;
44 
45 	/* If a binding for this key already exists, replace it. */
46 	for(b = *set; b->key; b++) {
47 		if(b->key == key) {
48 			b->command = (char *)command;
49 			return;
50 		}
51 	}
52 
53 	/* Keep size of set in i.  Include one for the terminating binding. */
54 	for(b = *set, i = 1; b->key; b++, i++);
55 
56 	*set = realloc(*set, (i + 1) * sizeof(struct binding));
57 	(b+1)->key = 0; /* Make last one be the terminating binding. */
58 
59 	/* Keep bindings sorted by command. */
60 	const char *bcommand=&b->command;
61 	for(b--; b >= *set && strcmp(command, bcommand) < 0; b--) {
62 		(b+1)->key = b->key;
63 		(b+1)->command = b->command;
64 	}
65 
66 	(b+1)->key = key;
67 	(b+1)->command = (char *)command;
68 }
69 
70