summaryrefslogtreecommitdiff
path: root/rcm-server-keymap.c
blob: a5c194ea3ca9800209ee6b21c8710a827ce4c73c (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
#define _GNU_SOURCE
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>

#include "utils.h"
#include "rcm-server.h"
#include "rcm-server-keymap.h"

struct keymap *
find_keymap_by_name(struct device *dev, const char *name)
{
	struct keymap *keymap;

	list_for_each_entry(keymap, &dev->keymaps, list)
		if (!strcmp(keymap->name, name))
			return keymap;

	return NULL;
}

static struct keymap *
keymap_read(int dfd, const char *name)
{
	int fd;
	struct keymap *keymap;
	unsigned i;

	if (dfd < 0 || !name)
		return NULL;

	fd = openat(dfd, name, O_RDONLY);
	if (fd < 0)
		return NULL;

	keymap = zmalloc(sizeof(*keymap) + (8 * 3) * sizeof(struct keycode));
	if (!keymap) {
		close(fd);
		return NULL;
	}

	keymap->name = strdup(name);
	if (!keymap->name) {
		close(fd);
		free(keymap);
		return NULL;
	}

	keymap->cols = 3;
	keymap->rows = 8;

	for (i = 0; i < (keymap->cols * keymap->rows); i++) {
		keymap->keycodes[i].name = "key-1-2";
		keymap->keycodes[i].value = "KEY_COFFEE";
	}
	/* FIXME: Actually read the keymap :) */

	close(fd);
	return keymap;
}

static int
keymaps_load_dir(struct device *device, const char *path)
{
	DIR *dir;
	int dfd;
	struct dirent *dent;
	struct keymap *keymap;

	dir = opendir(path);
	if (!dir)
		return -1;

	dfd = dirfd(dir);
	if (dfd < 0) {
		closedir(dir);
		return -1;
	}

	while ((dent = readdir(dir))) {
		switch (dent->d_type) {
		case DT_REG:
		case DT_LNK:
		case DT_UNKNOWN:
			keymap = keymap_read(dfd, dent->d_name);
			if (keymap)
				list_add(&keymap->list, &device->keymaps);
			break;
		default:
			break;
		}
	}

	if (closedir(dir) < 0)
		return -1;

	return 0;
}

int
keymaps_load(struct device *device)
{
	char pdpath[strlen("./keymaps/per-device/") + strlen(device->name) + 1];

	sprintf(pdpath, "./keymaps/per-device/%s", device->name);

	printf("Loading per-device keymaps...\n");
	keymaps_load_dir(device, pdpath);
	printf("Loading default keymaps...\n");
	keymaps_load_dir(device, "./keymaps/default");

	return 0;
}