2 // Copyright 2013 Eric Messick (FixedImagePhoto.com/Contact)
3 // reworked 2019 for cinelerra-gg by William Morrow
5 // keys.h collides with linux/input_events.h
20 #include <sys/types.h>
24 #include <X11/keysym.h>
26 static Time milliTimeClock()
30 return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
33 KeySymMapping KeySymMapping::key_sym_mapping[] = {
34 { "XK_Button_1", XK_Button_1 },
35 { "XK_Button_2", XK_Button_2 },
36 { "XK_Button_3", XK_Button_3 },
37 { "XK_Scroll_Up", XK_Scroll_Up },
38 { "XK_Scroll_Down", XK_Scroll_Down },
39 #include "shuttle_keys.h"
43 KeySym KeySymMapping::to_keysym(const char *str)
45 for( KeySymMapping *ksp = &key_sym_mapping[0]; ksp->str; ++ksp )
46 if( !strcmp(str, ksp->str) ) return ksp->sym;
50 const char *KeySymMapping::to_string(KeySym ks)
52 for( KeySymMapping *ksp = &key_sym_mapping[0]; ksp->sym; ++ksp )
53 if( ksp->sym == ks ) return ksp->str;
57 TransName::TransName(int cin, const char *nm, const char *re)
60 this->name = cstrdup(nm);
61 this->err = regcomp(&this->regex, re, REG_NOSUB);
63 fprintf(stderr, "error compiling regex for [%s]: %s\n", name, re);
65 regerror(err, ®ex, emsg, sizeof(emsg));
66 fprintf(stderr, "regerror: %s\n", emsg);
69 TransName::~TransName()
75 void Translation::init(int def)
79 first_release_stroke = 0;
85 Translation::Translation(Shuttle *shuttle)
87 { // initial default translation
89 this->shuttle = shuttle;
90 this->name = cstrdup("Default");
91 names.append(new TransName(FOCUS_DEFAULT, name, ""));
92 key_down[K6].add_stroke(XK_Button_1, 1);
93 key_up[K6].add_stroke(XK_Button_1, 0);
94 key_down[K7].add_stroke(XK_Button_2, 1);
95 key_up[K7].add_stroke(XK_Button_2, 0);
96 key_down[K8].add_stroke(XK_Button_3, 1);
97 key_up[K8].add_stroke(XK_Button_3, 0);
98 jog[JL].add_stroke(XK_Scroll_Up, 1);
99 jog[JL].add_stroke(XK_Scroll_Up, 0);
100 jog[JR].add_stroke(XK_Scroll_Down, 0);
101 jog[JR].add_stroke(XK_Scroll_Down, 1);
104 Translation::Translation(Shuttle *shuttle, const char *name)
108 this->shuttle = shuttle;
109 this->name = cstrdup(name);
112 Translation::~Translation()
117 void Translation::clear()
119 names.remove_all_objects();
121 for( int i=0; i<NUM_KEYS; ++i ) key_down[i].clear();
122 for( int i=0; i<NUM_KEYS; ++i ) key_up[i].clear();
123 for( int i=0; i<NUM_SHUTTLES; ++i ) shuttles[i].clear();
124 for( int i=0; i<NUM_JOGS; ++i ) jog[i].clear();
127 void Translation::append_stroke(KeySym sym, int press)
129 Stroke *s = pressed_strokes->append();
134 void Translation::add_keysym(KeySym sym, int press_release)
136 //printf("add_keysym(0x%x, %d)\n", (int)sym, press_release);
137 switch( press_release ) {
139 append_stroke(sym, 1);
140 modifiers.mark_as_down(sym, 0);
143 append_stroke(sym, 0);
144 modifiers.mark_as_up(sym);
147 append_stroke(sym, 1);
148 modifiers.mark_as_down(sym, 1);
152 if( first_release_stroke ) {
153 modifiers.re_press();
154 first_release_stroke = 0;
157 append_stroke(keysym_down, 0);
159 append_stroke(sym, 1);
165 void Translation::add_release(int all_keys)
167 //printf("add_release(%d)\n", all_keys);
168 modifiers.release(all_keys);
170 pressed_strokes = released_strokes;
173 append_stroke(keysym_down, 0);
176 first_release_stroke = 1;
179 void Translation::add_keystroke(const char *keySymName, int press_release)
183 if( is_key && !strncmp(keySymName, "RELEASE", 8) ) {
187 sym = KeySymMapping::to_keysym(keySymName);
189 add_keysym(sym, press_release);
192 fprintf(stderr, "unrecognized KeySym: %s\n", keySymName);
195 void Translation::add_string(const char *str)
197 while( str && *str ) {
198 if( *str >= ' ' && *str <= '~' )
199 add_keysym((KeySym)(*str), PRESS_RELEASE);
204 int Translation::start_line(const char *key)
207 released_strokes = 0;
208 pressed = released = 0;
210 if( !strcasecmp("JL", key) ) {
213 else if( !strcasecmp("JR", key) ) {
217 char c = 0; int k = -1, n = 0;
218 if( sscanf(key, "%c%d%n", &c, &k, &n) != 2 ) return 1;
222 if( k >= K1 && k <= K15 ) {
223 pressed = &key_down[k];
224 released = &key_up[k];
229 if( k >= S_7 && k <= S7 ) {
230 pressed = &shuttles[k-S_7];
235 fprintf(stderr, "bad key name: [%s]%s\n", name, key);
238 if( pressed->first ) {
239 fprintf(stderr, "dupl key name: [%s]%s\n", name, key);
243 pressed_strokes = pressed;
244 released_strokes = released;
248 void Translation::print_stroke(Stroke *s)
251 const char *cp = KeySymMapping::to_string(s->keysym);
252 if( !cp ) { printf("0x%x", (int)s->keysym); cp = "???"; }
253 printf("%s/%c ", cp, s->press ? 'D' : 'U');
256 void Translation::print_strokes(const char *name, const char *up_dn, Strokes *strokes)
258 printf("%s[%s]: ", name, up_dn);
259 for( Stroke *s=strokes->first; s; s=s->next )
264 void Translation::finish_line()
266 //printf("finish_line()\n");
273 void Translation::print_line(const char *key)
276 print_strokes(key, "D", pressed_strokes);
277 print_strokes(key, "U", released_strokes);
280 print_strokes(key, "", pressed_strokes);
285 // press values in Modifiers:
288 // PRESS_RELEASE -> released, but to be re-pressed if necessary
291 void Modifiers::mark_as_down(KeySym sym, int hold)
293 Modifiers &modifiers = *this;
294 for( int i=0; i<size(); ++i ) {
295 Stroke &s = modifiers[i];
296 if( s.keysym == sym ) {
297 s.press = hold ? HOLD : PRESS;
301 Stroke &s = append();
303 s.press = hold ? HOLD : PRESS;
306 void Modifiers::mark_as_up(KeySym sym)
308 Modifiers &modifiers = *this;
309 for( int i=0; i<size(); ++i ) {
310 Stroke &s = modifiers[i];
311 if( s.keysym == sym ) {
318 void Modifiers::release(int allkeys)
320 Modifiers &modifiers = *this;
321 for( int i=0; i<size(); ++i ) {
322 Stroke &s = modifiers[i];
323 if( s.press == PRESS ) {
324 trans->append_stroke(s.keysym, 0);
325 s.press = PRESS_RELEASE;
327 else if( allkeys && s.press == HOLD ) {
328 trans->append_stroke(s.keysym, 0);
334 void Modifiers::re_press()
336 Modifiers &modifiers = *this;
337 for( int i=0; i<size(); ++i ) {
338 Stroke &s = modifiers[i];
339 if( s.press == PRESS_RELEASE ) {
340 trans->append_stroke(s.keysym, 1);
347 Shuttle::Shuttle(MWindow *mwindow)
350 this->mwindow = mwindow;
359 shuttlevalue = 0xffff;
360 last_shuttle.tv_sec = 0;
361 last_shuttle.tv_usec = 0;
362 need_synthetic_shuttle = 0;
369 last_translation = 0;
372 default_translation = new Translation(this);
381 delete default_translation;
382 delete [] config_path;
385 int Shuttle::send_button(unsigned int button, int press)
388 printf("btn: %u %d\n", button, press);
389 XButtonEvent *b = new XButtonEvent();
390 memset(b, 0, sizeof(*b));
391 b->type = press ? ButtonPress : ButtonRelease;
392 b->time = milliTimeClock();
393 b->display = wdw->top_level->display;
394 b->root = wdw->top_level->rootwin;
403 wdw->top_level->put_event((XEvent *) b);
406 int Shuttle::send_key(KeySym keysym, int press)
408 KeyCode keycode = XKeysymToKeycode(wdw->top_level->display, keysym);
410 printf("key: %04x %d\n", (unsigned)keycode, press);
411 XKeyEvent *k = new XKeyEvent();
412 memset(k, 0, sizeof(*k));
413 k->type = press ? KeyPress : KeyRelease;
414 k->time = milliTimeClock();
415 k->display = wdw->top_level->display;
416 k->root = wdw->top_level->rootwin;
423 k->keycode = keycode;
425 wdw->top_level->put_event((XEvent *) k);
429 int Shuttle::send_keysym(KeySym keysym, int press)
431 return keysym >= XK_Button_1 && keysym <= XK_Scroll_Down ?
432 send_button((unsigned int)keysym - XK_Button_0, press) :
433 send_key(keysym, press ? True : False);
437 static Stroke *fetch_stroke(Translation *translation, int kjs, int index)
443 case KJS_KEY_DOWN: ret = translation->key_down[index].first; break;
444 case KJS_KEY_UP: ret = translation->key_up[index].first; break;
445 case KJS_JOG: ret = translation->jog[index].first; break;
446 case KJS_SHUTTLE: ret = translation->shuttles[index].first; break;
452 void Shuttle::send_stroke_sequence(int kjs, int index)
455 Stroke *s = fetch_stroke(tr, kjs, index);
456 if( !s ) s = fetch_stroke(default_translation, kjs, index);
458 send_keysym(s->keysym, s->press);
463 void Shuttle::key(unsigned short code, unsigned int value)
465 code -= EVENT_CODE_KEY1;
466 if( code >= NUM_KEYS ) {
467 fprintf(stderr, "key(%d, %d) out of range\n", code + EVENT_CODE_KEY1, value);
470 send_stroke_sequence(value ? KJS_KEY_DOWN : KJS_KEY_UP, code);
474 void Shuttle:: shuttle(int value)
476 if( value < S_7 || value > S7 ) {
477 fprintf(stderr, "shuttle(%d) out of range\n", value);
480 gettimeofday(&last_shuttle, 0);
481 need_synthetic_shuttle = value != 0;
482 if( value != shuttlevalue ) {
483 shuttlevalue = value;
484 send_stroke_sequence(KJS_SHUTTLE, value+7);
488 // Due to a bug (?) in the way Linux HID handles the ShuttlePro, the
489 // center position is not reported for the shuttle wheel. Instead,
490 // a jog event is generated immediately when it returns. We check to
491 // see if the time since the last shuttle was more than a few ms ago
492 // and generate a shuttle of 0 if so.
494 // Note, this fails if jogvalue happens to be 0, as we don't see that
496 void Shuttle::jog(unsigned int value)
500 struct timeval delta;
502 // We should generate a synthetic event for the shuttle going
503 // to the home position if we have not seen one recently
504 if( need_synthetic_shuttle ) {
505 gettimeofday( &now, 0 );
506 timersub( &now, &last_shuttle, &delta );
508 if( delta.tv_sec >= 1 || delta.tv_usec >= 5000 ) {
510 need_synthetic_shuttle = 0;
514 if( jogvalue != 0xffff ) {
515 value = value & 0xff;
516 direction = ((value - jogvalue) & 0x80) ? -1 : 1;
517 while( jogvalue != value ) {
518 // driver fails to send an event when jogvalue == 0
519 if( jogvalue != 0 ) {
520 send_stroke_sequence(KJS_JOG, direction > 0 ? 1 : 0);
522 jogvalue = (jogvalue + direction) & 0xff;
528 void Shuttle::jogshuttle(unsigned short code, unsigned int value)
534 case EVENT_CODE_SHUTTLE:
538 fprintf(stderr, "jogshuttle(%d, %d) invalid code\n", code, value);
543 const char *Shuttle::probe()
546 static const char *shuttle_devs[] = {
547 "/dev/input/by-id/usb-Contour_Design_ShuttleXpress-event-if00",
548 "/dev/input/by-id/usb-Contour_Design_ShuttlePRO_v2-event-if00",
550 int ret = sizeof(shuttle_devs) / sizeof(shuttle_devs[0]);
551 while( --ret >= 0 && stat(shuttle_devs[ret] , &st) );
552 return ret >= 0 ? shuttle_devs[ret] : 0;
555 void Shuttle::start(const char *dev_name)
557 this->dev_name = dev_name;
565 if( running() && !done ) {
573 int Shuttle::get_focused_window_translation()
575 MWindowGUI *gui = mwindow->gui;
576 Display *dpy = gui->display;
578 int ret = 0, revert = 0;
579 char win_title[BCTEXTLEN];
580 gui->lock_window("Shuttle::get_focused_window_translation");
581 XGetInputFocus(dpy, &focus, &revert);
582 if( last_focused != focus ) {
583 last_focused = focus;
584 Atom prop = XInternAtom(dpy, "WM_NAME", False);
586 unsigned long remain, len;
588 if( XGetWindowProperty(dpy, focus, prop, 0, sizeof(win_title)-1, False,
589 AnyPropertyType, &type, &form, &len, &remain, &list) == Success ) {
590 len = len*(form/8) - remain;
591 memcpy(win_title, list, len);
595 printf("new focus: %08x\n", (unsigned)focus);
599 fprintf(stderr, "XGetWindowProperty failed for window 0x%x\n",
604 gui->unlock_window();
607 this->wdw = 0; this->win = 0;
608 this->wx = 0; this->wy = 0;
609 this->rx = 0; this->ry = 0;
611 BC_WindowBase *wdw = 0;
613 if( (wdw=mwindow->gui) && wdw->win == focus )
615 else if( (wdw=mwindow->awindow->gui) && wdw->win == focus )
617 else if( (wdw=mwindow->cwindow->gui) && wdw->win == focus )
619 else if( (wdw=mwindow->gui->mainmenu->load_file->thread->window) &&
623 int i = mwindow->vwindows.size();
625 VWindow *vwdw = mwindow->vwindows[i];
626 if( !vwdw->is_running() ) continue;
627 if( (wdw=vwdw->gui) && wdw->win == focus ) {
628 cin = FOCUS_VIEWER; break;
632 if( cin < 0 ) return -1;
633 Window root = 0, child = 0;
634 int root_x = 0, root_y = 0, win_x = 0, win_y = 0, x = 0, y = 0;
635 unsigned int mask = 0, width = 0, height = 0, border_width = 0, depth = 0;
636 wdw->lock_window("Shuttle::get_focused_window_translation 1");
637 if( XQueryPointer(wdw->display, focus, &root, &child,
638 &root_x, &root_y, &win_x, &win_y, &mask) ) {
640 if( wdw->active_menubar )
641 child = wdw->active_menubar->win;
642 else if( wdw->active_popup_menu )
643 child = wdw->active_popup_menu->win;
644 else if( wdw->active_subwindow )
645 child = wdw->active_subwindow->win;
648 XGetGeometry(wdw->display, child, &root, &x, &y,
649 &width, &height, &border_width, &depth);
651 wdw->unlock_window();
652 if( !child || !wdw->match_window(child) ) return -1;
659 this->wx = win_x - x;
660 this->wy = win_y - y;
661 for( tr=translations.first; tr; tr=tr->next ) {
662 if( tr->is_default ) return 1;
663 for( int i=0; i<tr->names.size(); ++i ) {
664 TransName *name = tr->names[i];
665 if( name->cin != cin ) continue;
666 if( regexec(&name->regex, win_title, 0, NULL, 0) )
670 tr = default_translation;
674 void Shuttle::handle_event()
676 if( read_config_file() > 0 ) {
680 if( get_focused_window_translation() < 0 )
682 if( last_translation != tr ) {
683 last_translation = tr;
685 printf("new translation: %s\n", tr->name);
687 //fprintf(stderr, "event: (%d, %d, 0x%x)\n", ev.type, ev.code, ev.value);
689 case EVENT_TYPE_DONE:
690 case EVENT_TYPE_ACTIVE_KEY:
693 key(ev.code, ev.value);
695 case EVENT_TYPE_JOGSHUTTLE:
696 jogshuttle(ev.code, ev.value);
699 fprintf(stderr, "handle_event() invalid type code\n");
706 for( enable_cancel(); !done; sleep(1) ) {
707 fd = open(dev_name, O_RDONLY);
710 if( first_time ) break;
713 if( !ioctl(fd, EVIOCGRAB, 1) ) { // exclusive access
716 int ret = read(fd, &ev, sizeof(ev));
718 if( ret != sizeof(ev) ) {
719 if( ret < 0 ) { perror("read event"); break; }
720 fprintf(stderr, "bad read: %d\n", ret);
727 perror( "evgrab ioctl" );
733 int Shuttle::read_config_file()
737 config_path = (env=getenv("SHUTTLE_CONFIG_FILE")) != 0 ? cstrdup(env) :
738 (env=getenv("HOME")) != 0 ? cstrcat(2, env, "/.shuttlerc") : 0;
739 if( !config_path ) { fprintf(stderr, "no config file\n"); return 1; }
742 if( stat(config_path, &st) ) {
744 char shuttlerc[BCTEXTLEN];
745 snprintf(shuttlerc, sizeof(shuttlerc), "%s/shuttlerc",
746 File::get_cindat_path());
747 if( stat(shuttlerc, &st) ) {
751 delete [] config_path;
752 config_path = cstrdup(shuttlerc);
754 if( config_mtime > 0 &&
755 config_mtime == st.st_mtime ) return 0;
756 FILE *fp = fopen(config_path, "r");
762 config_mtime = st.st_mtime;
763 translations.clear();
765 #define ws(ch) (ch==' ' || ch=='\t')
766 char line[BCTEXTLEN], *cp;
767 Translation *trans = 0;
769 int ret = fgets(cp=line,sizeof(line),fp) ? 0 : -1;
774 while( !ret && *cp == '[' ) {
776 while( *cp && *cp != ']' ) ++cp;
778 if( !name || !*name ) { ret = 1; break; }
780 if( !strcasecmp("default", name) )
782 else if( !strcasecmp("cinelerra", name) )
784 else if( !strcasecmp("resources", name) )
786 else if( !strcasecmp("composer", name) )
788 else if( !strcasecmp("viewer", name) )
790 else if( !strcasecmp("load", name) )
793 fprintf(stderr, "unknown focus target window: %s\n",
798 if( cin == FOCUS_DEFAULT ) {
799 trans = default_translation;
803 trans = new Translation(this, name);
806 while( ws(*cp) ) ++cp;
807 // regex in TransName constructor
808 trans->names.append(new TransName(cin, name, cp));
809 if( trans->names.last()->err ) { ret = 1; break; }
810 ret = fgets(cp=line,sizeof(line),fp) ? 0 : 1;
812 fprintf(stderr, "hit eof, no translation def for: %s\n",
813 trans->names.last()->name);
819 if( debug && trans ) {
820 printf("------------------------\n");
821 TransNames &names = trans->names;
822 for( int i=0; i<names.size(); ++i ) {
823 TransName *tp = names[i];
824 printf("[%s] # %d\n\n", tp->name, tp->cin);
827 // rules lines: "tok <stroke list>\n"
828 while( !ret && *cp != '[' ) {
829 const char *key = 0, *tok = 0;
830 while( ws(*cp) ) ++cp;
831 if( !*cp || *cp == '\n' || *cp == '#' ) goto skip;
833 while( *cp && !ws(*cp) && *cp != '\n' ) ++cp;
835 if( !strcmp(tok, "DEBUG") ) {
836 debug = 1; goto skip;
840 fprintf(stderr, "no translation section defining key: %s\n", key);
844 ret = trans->start_line(key);
845 while( !ret && *cp && *cp != '\n' ) {
846 while( ws(*cp) ) ++cp;
847 if( !*cp || *cp == '#' || *cp == '\n' ) break;
850 while( *cp && *cp != '"' && *cp != '\n' ) {
851 if( *cp != '\\' ) { ++cp; continue; }
852 for( char *bp=cp; *bp; ++bp ) bp[0] = bp[1];
855 trans->add_string(tok);
859 while( *cp && !ws(*cp) && *cp!='/' && *cp != '\n' ) ++cp;
860 int dhu = PRESS_RELEASE;
864 case 'D': dhu = PRESS; break;
865 case 'H': dhu = HOLD; break;
866 case 'U': dhu = RELEASE; break;
868 fprintf(stderr, "invalid up/down modifier [%s]%s: '%c'\n",
869 trans->name, tok, *cp);
876 trans->add_keystroke(tok, dhu);
879 trans->finish_line();
881 trans->print_line(key);
882 skip: ret = fgets(cp=line,sizeof(line),fp) ? 0 : -1;
886 if( trans != default_translation )
887 translations.append(trans);
892 fprintf(stderr, "shuttle config err file: %s, line:%d\n",