]> git.ozlabs.org Git - petitboot/blob - ui/common/joystick.c
discover/pxe-parser: Recognise plugin sources
[petitboot] / ui / common / joystick.c
1 /*
2  *  Copyright (C) 2009 Sony Computer Entertainment Inc.
3  *  Copyright 2009 Sony Corp.
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; version 2 of the License.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19 #if defined(HAVE_CONFIG_H)
20 #include "config.h"
21 #endif
22
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <string.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29
30 #include "log/log.h"
31 #include "talloc/talloc.h"
32 #include "joystick.h"
33
34 /**
35  * pjs_process_event - Read joystick event and map to UI key code.
36  *
37  * Returns a map routine UI key code or zero.
38  */
39
40 int pjs_process_event(const struct pjs *pjs)
41 {
42         int result;
43         struct js_event e;
44
45         assert(pjs->fd);
46
47         result = read(pjs->fd, &e, sizeof(e));
48
49         if (result != sizeof(e)) {
50                 pb_log("%s: read failed: %s\n", __func__, strerror(errno));
51                 return 0;
52         }
53
54         return pjs->map(&e);
55 }
56
57 /**
58  * pjs_destructor - The talloc destructor for a joystick handler.
59  */
60
61 static int pjs_destructor(void *arg)
62 {
63         struct pjs *pjs = pjs_from_arg(arg);
64
65         close(pjs->fd);
66         pjs->fd = 0;
67
68         return 0;
69 }
70
71 /**
72  * pjs_init - Initialize the joystick event handler.
73  */
74
75 struct pjs *pjs_init(void *ctx, int (*map)(const struct js_event *))
76 {
77         static const char dev_name[] = "/dev/input/js0";
78         struct pjs *pjs;
79
80         pjs = talloc_zero(ctx, struct pjs);
81
82         if (!pjs)
83                 return NULL;
84
85         pjs->map = map;
86         pjs->fd = open(dev_name, O_RDONLY | O_NONBLOCK);
87
88         if (pjs->fd < 0) {
89                 pb_log("%s: open %s failed: %s\n", __func__, dev_name,
90                         strerror(errno));
91                 goto out_err;
92         }
93
94         talloc_set_destructor(pjs, pjs_destructor);
95
96         pb_debug("%s: using %s\n", __func__, dev_name);
97
98         return pjs;
99
100 out_err:
101         if (pjs->fd >= 0)
102                 close(pjs->fd);
103         talloc_free(pjs);
104         return NULL;
105 }