]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - converter/adb_usb/matrix.c
adb_usb: Change mouse acceleration according to cpi
[max/tmk_keyboard.git] / converter / adb_usb / matrix.c
1 /*
2 Copyright 2011 Jun Wako <wakojun@gmail.com>
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
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, see <http://www.gnu.org/licenses/>.
16 */
17
18 /*
19  * scan matrix
20  */
21 #include <stdint.h>
22 #include <stdbool.h>
23 #include <avr/io.h>
24 #include <util/delay.h>
25 #include "print.h"
26 #include "util.h"
27 #include "debug.h"
28 #include "adb.h"
29 #include "matrix.h"
30 #include "report.h"
31 #include "host.h"
32 #include "led.h"
33 #include "timer.h"
34
35
36
37
38 static bool has_media_keys = false;
39 static bool is_iso_layout = false;
40 static uint8_t mouse_handler = ADB_HANDLER_CLASSIC1_MOUSE;
41 static uint16_t mouse_cpi = 100;
42
43 // matrix state buffer(1:on, 0:off)
44 static matrix_row_t matrix[MATRIX_ROWS];
45
46 static void register_key(uint8_t key);
47
48
49 void matrix_init(void)
50 {
51     // LED on
52     DDRD |= (1<<6); PORTD |= (1<<6);
53
54     adb_host_init();
55     // wait for keyboard to boot up and receive command
56     _delay_ms(2000);
57
58     // device scan
59     xprintf("\nScan:\n");
60     for (uint8_t addr = 1; addr < 16; addr++) {
61         uint16_t reg3 = adb_host_talk(addr, ADB_REG_3);
62         if (reg3) {
63             xprintf(" addr:%d, reg3:%04X\n", addr, reg3);
64         }
65         _delay_ms(20);
66     }
67
68
69     //
70     // Keyboard
71     //
72     xprintf("\nKeyboard:\n");
73     // Determine ISO keyboard by handler id
74     // http://lxr.free-electrons.com/source/drivers/macintosh/adbhid.c?v=4.4#L815
75     uint8_t handler_id = (uint8_t) adb_host_talk(ADB_ADDR_KEYBOARD, ADB_REG_3);
76     switch (handler_id) {
77     case 0x04: case 0x05: case 0x07: case 0x09: case 0x0D:
78     case 0x11: case 0x14: case 0x19: case 0x1D: case 0xC1:
79     case 0xC4: case 0xC7:
80         is_iso_layout = true;
81         break;
82     default:
83         is_iso_layout = false;
84         break;
85     }
86     xprintf("hadler: %02X, ISO: %s\n", handler_id, (is_iso_layout ? "yes" : "no"));
87
88     // Adjustable keyboard media keys: address=0x07 and handlerID=0x02
89     has_media_keys = (0x02 == (adb_host_talk(ADB_ADDR_APPLIANCE, ADB_REG_3) & 0xff));
90     if (has_media_keys) {
91         xprintf("Media keys\n");
92     }
93
94     // Enable keyboard left/right modifier distinction
95     // Listen Register3
96     //  upper byte: reserved bits 0000, keyboard address 0010
97     //  lower byte: device handler 00000011
98     adb_host_listen(ADB_ADDR_KEYBOARD, ADB_REG_3, ADB_ADDR_KEYBOARD, ADB_HANDLER_EXTENDED_KEYBOARD);
99
100
101     #ifdef ADB_MOUSE_ENABLE
102     //
103     // Mouse
104     //
105     // https://developer.apple.com/library/archive/technotes/hw/hw_01.html#Extended
106     xprintf("\nMouse:\n");
107
108     // Some old mouses seems to need wait between commands.
109     _delay_ms(20);
110     adb_host_listen(ADB_ADDR_MOUSE, ADB_REG_3, ADB_ADDR_MOUSE, ADB_HANDLER_CLASSIC2_MOUSE);
111
112     _delay_ms(20);
113     adb_host_listen(ADB_ADDR_MOUSE, ADB_REG_3, ADB_ADDR_MOUSE, ADB_HANDLER_EXTENDED_MOUSE);
114
115     _delay_ms(20);
116     mouse_handler = adb_host_talk(ADB_ADDR_MOUSE, ADB_REG_3) & 0xff;
117     mouse_handler = mouse_handler ? mouse_handler : ADB_HANDLER_CLASSIC1_MOUSE;
118
119     if (mouse_handler == ADB_HANDLER_CLASSIC1_MOUSE) { mouse_cpi = 100; }
120     if (mouse_handler == ADB_HANDLER_CLASSIC2_MOUSE) { mouse_cpi = 200; }
121
122     // Extended Mouse Protocol
123     if (mouse_handler == ADB_HANDLER_EXTENDED_MOUSE) {
124         // Device info format(reg1 8-byte data)
125         // 0-3: device id
126         // 4-5: resolution in units/inch (0xC8=200upi)
127         // 6  : device class      (0: Tablet, 1: Mouse, 2: Trackball)
128         // 7  : num of buttons
129         uint8_t len;
130         uint8_t buf[8];
131         len = adb_host_talk_buf(ADB_ADDR_MOUSE, ADB_REG_1, buf, sizeof(buf));
132         if (len) {
133             xprintf("Devinfo: [", len);
134             for (int8_t i = 0; i < len; i++) xprintf("%02X ", buf[i]);
135             xprintf("]\n");
136         }
137
138         if (len > 5) {
139             mouse_cpi = (buf[4]<<8) | buf[5];
140         } else {
141             mouse_cpi = 100;
142         }
143
144         // Kensington Turbo Mouse 5
145         if (len == 8 && buf[0] == 0x4B && buf[1] == 0x4D && buf[2] == 0x4C && buf[3] == 0x31) {
146             xprintf("Turbo Mouse 5\n");
147
148             // Turbo Mouse command sequence to enable four buttons
149             // https://elixir.bootlin.com/linux/v4.4/source/drivers/macintosh/adbhid.c#L1176
150             // https://github.com/NetBSD/src/blob/64b8a48e1288eb3902ed73113d157af50b2ec596/sys/arch/macppc/dev/ams.c#L261
151             static uint8_t cmd1[] = { 0xE7, 0x8C, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x94 };
152             static uint8_t cmd2[] = { 0xA5, 0x14, 0x00, 0x00, 0x69, 0xFF, 0xFF, 0x27 };
153
154             // configure with new address 9
155             adb_host_listen(ADB_ADDR_MOUSE, ADB_REG_3, 0x69, 0xFE);
156             adb_host_flush(9);
157
158             adb_host_flush(ADB_ADDR_MOUSE);
159             adb_host_listen_buf(ADB_ADDR_MOUSE, ADB_REG_2, cmd1, sizeof(cmd1));
160             adb_host_flush(ADB_ADDR_MOUSE);
161             adb_host_listen_buf(ADB_ADDR_MOUSE, ADB_REG_2, cmd2, sizeof(cmd2));
162         }
163
164         // Add device specific init here
165     }
166     mouse_handler = adb_host_talk(ADB_ADDR_MOUSE, ADB_REG_3) & 0xff;
167     mouse_handler = mouse_handler ? mouse_handler : ADB_HANDLER_CLASSIC1_MOUSE;
168     xprintf("handler: %d\n", mouse_handler);
169     xprintf("cpi: %d\n", mouse_cpi);
170     #endif
171
172
173     xprintf("\nScan:\n");
174     for (uint8_t addr = 1; addr < 16; addr++) {
175         uint16_t reg3 = adb_host_talk(addr, ADB_REG_3);
176         if (reg3) {
177             xprintf(" addr:%d, reg3:%04X\n", addr, reg3);
178         }
179         _delay_ms(20);
180     }
181
182     // initialize matrix state: all keys off
183     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
184
185     led_set(host_keyboard_leds());
186
187     debug_enable = true;
188     //debug_matrix = true;
189     //debug_keyboard = true;
190     debug_mouse = true;
191
192     // LED off
193     DDRD |= (1<<6); PORTD &= ~(1<<6);
194     return;
195 }
196
197 #ifdef ADB_MOUSE_ENABLE
198
199 #ifdef MAX
200 #undef MAX
201 #endif
202 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
203
204 static report_mouse_t mouse_report = {};
205
206 void adb_mouse_task(void)
207 {
208     uint8_t len;
209     uint8_t buf[5];
210     int16_t x, y;
211     static int8_t mouseacc;
212
213     /* tick of last polling */
214     static uint16_t tick_ms;
215
216     // polling with 12ms interval
217     if (timer_elapsed(tick_ms) < 12) return;
218     tick_ms = timer_read();
219
220     // Extended Mouse Protocol data can be 2-5 bytes
221     // https://developer.apple.com/library/archive/technotes/hw/hw_01.html#Extended
222     //
223     //   Byte 0: b00 y06 y05 y04 y03 y02 y01 y00
224     //   Byte 1: b01 x06 x05 x04 x03 x02 x01 x00
225     //   Byte 2: b02 y09 y08 y07 b03 x09 x08 x07
226     //   Byte 3: b04 y12 y11 y10 b05 x12 x11 x10
227     //   Byte 4: b06 y15 y14 y13 b07 x15 x14 x13
228     //
229     //   b--: Button state.(0: on, 1: off)
230     //   x--: X axis movement.
231     //   y--: Y axis movement.
232     len = adb_host_talk_buf(ADB_ADDR_MOUSE, ADB_REG_0, buf, sizeof(buf));
233
234     // If nothing received reset mouse acceleration, and quit.
235     if (len < 2) {
236         mouseacc = 1;
237         return;
238     };
239
240     // Store off-buttons and 0-movements in unused bytes
241     bool xneg = false;
242     bool yneg = false;
243     if (len == 2) {
244         if (buf[0] & 0x40) yneg = true;
245         if (buf[1] & 0x40) xneg = true;
246     } else {
247         if (buf[len - 1] & 0x40) yneg = true;
248         if (buf[len - 1] & 0x04) xneg = true;
249     }
250
251     for (int8_t i = len; i < sizeof(buf); i++) {
252         buf[i] = 0x88;
253         if (yneg) buf[i] |= 0x70;
254         if (xneg) buf[i] |= 0x07;
255     }
256
257     // 8 buttons at max
258     // TODO: Fix HID report descriptor for mouse to support button6-8
259     uint8_t buttons = 0;
260     if (!(buf[4] & 0x08)) buttons |= MOUSE_BTN8;
261     if (!(buf[4] & 0x80)) buttons |= MOUSE_BTN7;
262     if (!(buf[3] & 0x08)) buttons |= MOUSE_BTN6;
263     if (!(buf[3] & 0x80)) buttons |= MOUSE_BTN5;
264     if (!(buf[2] & 0x08)) buttons |= MOUSE_BTN4;
265     if (!(buf[2] & 0x80)) buttons |= MOUSE_BTN3;
266     if (!(buf[1] & 0x80)) buttons |= MOUSE_BTN2;
267     if (!(buf[0] & 0x80)) buttons |= MOUSE_BTN1;
268     mouse_report.buttons = buttons;
269
270     int16_t xx, yy;
271     yy = (buf[0] & 0x7F) | (buf[2] & 0x70) << 3 | (buf[3] & 0x70) << 6 | (buf[4] & 0x70) << 9;
272     xx = (buf[1] & 0x7F) | (buf[2] & 0x07) << 7 | (buf[3] & 0x07) << 10 | (buf[4] & 0x07) << 13;
273
274     // Accelerate mouse. (They weren't meant to be used on screens larger than 320x200).
275     x = xx * mouseacc;
276     y = yy * mouseacc;
277
278     // TODO: Fix HID report descriptor for mouse to support finer resolution
279     // Cap our two bytes per axis to one byte.
280     // Easier with a MIN-function, but since -MAX(-a,-b) = MIN(a,b)...
281     // I.E. MIN(MAX(x,-127),127) = -MAX(-MAX(x, -127), -127) = MIN(-MIN(-x,127),127)
282     mouse_report.x = -MAX(-MAX(x, -127), -127);
283     mouse_report.y = -MAX(-MAX(y, -127), -127);
284
285     if (debug_mouse) {
286         xprintf("Mouse: [");
287         for (int8_t i = 0; i < len; i++) xprintf("%02X ", buf[i]);
288         xprintf("] ");
289         xprintf("[B:%02X, X:%d(%d), Y:%d(%d), A:%d]\n", mouse_report.buttons, mouse_report.x, xx, mouse_report.y, yy, mouseacc);
290     }
291
292     // Send result by usb.
293     host_mouse_send(&mouse_report);
294
295     // TODO: acceleration curve is needed for precise operation?
296     // increase acceleration of mouse
297     mouseacc += ( mouseacc < (mouse_cpi < 200 ? ADB_MOUSE_MAXACC : ADB_MOUSE_MAXACC/2) ? 1 : 0 );
298
299     return;
300 }
301 #endif
302
303 uint8_t matrix_scan(void)
304 {
305     /* extra_key is volatile and more convoluted than necessary because gcc refused
306     to generate valid code otherwise. Making extra_key uint8_t and constructing codes
307     here via codes = extra_key<<8 | 0xFF; would consistently fail to even LOAD
308     extra_key from memory, and leave garbage in the high byte of codes. I tried
309     dozens of code variations and it kept generating broken assembly output. So
310     beware if attempting to make extra_key code more logical and efficient. */
311     static volatile uint16_t extra_key = 0xFFFF;
312     uint16_t codes;
313     uint8_t key0, key1;
314
315     /* tick of last polling */
316     static uint16_t tick_ms;
317
318     codes = extra_key;
319     extra_key = 0xFFFF;
320
321     if ( codes == 0xFFFF )
322     {
323         // polling with 12ms interval
324         if (timer_elapsed(tick_ms) < 12) return 0;
325         tick_ms = timer_read();
326
327         codes = adb_host_kbd_recv(ADB_ADDR_KEYBOARD);
328
329         // Adjustable keybaord media keys
330         if (codes == 0 && has_media_keys &&
331                 (codes = adb_host_kbd_recv(ADB_ADDR_APPLIANCE))) {
332             // key1
333             switch (codes & 0x7f ) {
334             case 0x00:  // Mic
335                 codes = (codes & ~0x007f) | 0x42;
336                 break;
337             case 0x01:  // Mute
338                 codes = (codes & ~0x007f) | 0x4a;
339                 break;
340             case 0x02:  // Volume down
341                 codes = (codes & ~0x007f) | 0x49;
342                 break;
343             case 0x03:  // Volume Up
344                 codes = (codes & ~0x007f) | 0x48;
345                 break;
346             case 0x7F:  // no code
347                 break;
348             default:
349                 xprintf("ERROR: media key1\n");
350                 return 0x11;
351             }
352             // key0
353             switch ((codes >> 8) & 0x7f ) {
354             case 0x00:  // Mic
355                 codes = (codes & ~0x7f00) | (0x42 << 8);
356                 break;
357             case 0x01:  // Mute
358                 codes = (codes & ~0x7f00) | (0x4a << 8);
359                 break;
360             case 0x02:  // Volume down
361                 codes = (codes & ~0x7f00) | (0x49 << 8);
362                 break;
363             case 0x03:  // Volume Up
364                 codes = (codes & ~0x7f00) | (0x48 << 8);
365                 break;
366             default:
367                 xprintf("ERROR: media key0\n");
368                 return 0x10;
369             }
370         }
371     }
372     key0 = codes>>8;
373     key1 = codes&0xFF;
374
375     if (debug_matrix && codes) {
376         print("adb_host_kbd_recv: "); phex16(codes); print("\n");
377     }
378
379     if (codes == 0) {                           // no keys
380         return 0;
381     } else if (codes == 0x7F7F) {   // power key press
382         register_key(0x7F);
383     } else if (codes == 0xFFFF) {   // power key release
384         register_key(0xFF);
385     } else if (key0 == 0xFF) {      // error
386         xprintf("adb_host_kbd_recv: ERROR(%d)\n", codes);
387         // something wrong or plug-in
388         matrix_init();
389         return key1;
390     } else {
391         /* Swap codes for ISO keyboard
392          * https://github.com/tmk/tmk_keyboard/issues/35
393          *
394          * ANSI
395          * ,-----------    ----------.
396          * | *a|  1|  2     =|Backspa|
397          * |-----------    ----------|
398          * |Tab  |  Q|     |  ]|   *c|
399          * |-----------    ----------|
400          * |CapsLo|  A|    '|Return  |
401          * |-----------    ----------|
402          * |Shift   |      Shift     |
403          * `-----------    ----------'
404          *
405          * ISO
406          * ,-----------    ----------.
407          * | *a|  1|  2     =|Backspa|
408          * |-----------    ----------|
409          * |Tab  |  Q|     |  ]|Retur|
410          * |-----------    -----`    |
411          * |CapsLo|  A|    '| *c|    |
412          * |-----------    ----------|
413          * |Shif| *b|      Shift     |
414          * `-----------    ----------'
415          *
416          *         ADB scan code   USB usage
417          *         -------------   ---------
418          * Key     ANSI    ISO     ANSI    ISO
419          * ---------------------------------------------
420          * *a      0x32    0x0A    0x35    0x35
421          * *b      ----    0x32    ----    0x64
422          * *c      0x2A    0x2A    0x31    0x31(or 0x32)
423          */
424         if (is_iso_layout) {
425             if ((key0 & 0x7F) == 0x32) {
426                 key0 = (key0 & 0x80) | 0x0A;
427             } else if ((key0 & 0x7F) == 0x0A) {
428                 key0 = (key0 & 0x80) | 0x32;
429             }
430         }
431         register_key(key0);
432         if (key1 != 0xFF)       // key1 is 0xFF when no second key.
433             extra_key = key1<<8 | 0xFF; // process in a separate call
434     }
435
436     return 1;
437 }
438
439 inline
440 matrix_row_t matrix_get_row(uint8_t row)
441 {
442     return matrix[row];
443 }
444
445 inline
446 static void register_key(uint8_t key)
447 {
448     uint8_t col, row;
449     col = key&0x07;
450     row = (key>>3)&0x0F;
451     if (key&0x80) {
452         matrix[row] &= ~(1<<col);
453     } else {
454         matrix[row] |=  (1<<col);
455     }
456 }
457
458 void led_set(uint8_t usb_led)
459 {
460     adb_host_kbd_led(ADB_ADDR_KEYBOARD, ~usb_led);
461 }