forked from bulletmark/libinput-gestures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libinput-gestures
executable file
·916 lines (761 loc) · 29.8 KB
/
libinput-gestures
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
#!/usr/bin/env python3
'Read gestures from libinput touchpad and action shell commands.'
# Mark Blakeney, Sep 2015.
import os
import sys
import argparse
import subprocess
import shlex
import re
import getpass
import fcntl
import platform
import math
import gi
import hashlib
import threading
from time import monotonic
from collections import OrderedDict
from pathlib import Path
dbus_imported = True
try:
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
gi.require_version('Wnck', '3.0')
gi.require_version('Gtk', '3.0')
gi.require_version('Bamf', '3')
from gi.repository import Bamf, Gio
except ImportError:
dbus_imported = False
session_locked = False
PROGPATH = Path(sys.argv[0])
PROGNAME = PROGPATH.stem
HOME = Path('~').expanduser()
# Conf file containing gesture commands.
# Search first for user file then system file.
CONFNAME = f'{PROGNAME}.conf'
USERDIR = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
CONFDIRS = (USERDIR, '/etc')
# Ratio of X/Y (or Y/X) at which we consider an oblique swipe gesture.
# The number is the trigger angle in degrees and set to 360/8/2.
OBLIQUE_RATIO = math.tan(math.radians(22.5))
# Default minimum significant distance to move for swipes, in dots.
# Can be changed using configuration command.
swipe_min_threshold = 0
args = None
abzsquare = None
# Timeout on gesture action from start to end. 0 = no timeout. In secs.
# Can be changed using configuration command.
DEFAULT_TIMEOUT = 1.5
timeoutv = DEFAULT_TIMEOUT
# Rotation threshold in degrees to discriminate pinch rotate from in/out
ROTATE_ANGLE = 15.0
# Appname for grouping actions in .conf via [CATCHALL_APPNAME]
CATCHALL_APPNAME='general'
def open_lock(*args):
'Create lock/pid files based on given list of arguments'
# We use exclusive assess to a file for this
fname = Path('/tmp', '-'.join(args))
flock = fname.with_suffix('.lock').open('w')
try:
fcntl.lockf(flock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
return None, None
fpid = fname.with_suffix('.pid').open('w')
return flock, fpid
def run(cmd, *, check=True, block=True):
'Run function and return standard output, Popen() handle, or None'
try:
if block:
result = subprocess.check_output(cmd, universal_newlines=True,
stderr=(None if check else subprocess.DEVNULL))
else:
result = bool(subprocess.Popen(cmd))
except Exception as e:
result = None
if check:
print(str(e), file=sys.stderr)
return result
def get_libinput_vers():
'Return the libinput installed version number string'
# Try to use newer libinput interface then fall back to old
# (depreciated) interface.
res = run(('libinput', '--version'), check=False)
if res:
return res.strip(), True
res = run(('libinput-list-devices', '--version'), check=False)
return res and res.strip(), False
def get_active_window_title():
root = subprocess.Popen(['xprop', '-root', '_NET_ACTIVE_WINDOW'], stdout=subprocess.PIPE)
stdout, stderr = root.communicate()
m = re.search(b'^_NET_ACTIVE_WINDOW.* ([\w]+)$', stdout)
if m != None:
window_id = m.group(1)
if window_id != '0x0':
if args.verbose:
print(f'window id: {window_id} from: {stdout}');
window = subprocess.Popen(['xprop', '-id', window_id, 'WM_NAME'], stdout=subprocess.PIPE)
stdout, stderr = window.communicate()
else:
window = 'Desktop'
else:
return None
match = re.match(b"WM_NAME\(\w+\) = (?P<name>.+)$", stdout)
if match != None:
return match.group("name").strip(b'"')
return None
def get_devices_list(cmd_list_devices, device_list):
'Get list of devices and their attributes (as a dict) from libinput'
if device_list:
with open(device_list) as fd:
stdout = fd.read()
else:
stdout = run(cmd_list_devices.split())
if stdout:
dev = {}
for line in stdout.splitlines():
line = line.strip()
if line and ':' in line:
key, value = line.split(':', maxsplit=1)
dev[key.strip().lower()] = value.strip()
elif dev:
yield dev
dev = {}
# Ensure we include last device
if dev:
yield dev
def get_device_info(name, cmd_list_devices, device_list):
'Determine libinput touchpad device and return device info'
devices = list(get_devices_list(cmd_list_devices, device_list))
if not devices:
print('Can not see any devices, did you add yourself to the '
'input group and reboot?', file=sys.stderr)
return None
# If a specific device name was asked for then return that device
# This is the "Device" name from libinput list-devices command.
if name:
kdev = str(Path(name).resolve()) if name[0] == '/' else None
for d in devices:
# If the device name starts with a '/' then it is instead
# considered as the explicit device path although since
# device paths can change through reboots this is best to be
# a symlink. E.g. users should use the corresponding full
# path link under /dev/input/by-path/ or /dev/input/by-id/.
if kdev:
if d.get('kernel') == kdev:
return d
elif d.get('device') == name:
return d
return None
# Otherwise look for 1st device with touchpad capabilities
for d in devices:
if 'size' in d and 'pointer' in d.get('capabilities'):
return d
# Otherwise look for 1st device with touchpad in it's name
# or, failing that, 1st device with trackpad in it's name
for txt in ('touch ?pad', 'track ?pad'):
for d in devices:
if re.search(txt, d.get('device', ''), re.I):
return d
# Give up
return None
def get_device(name, cmd_list_devices, device_list):
'Determine libinput touchpad device and add fixed path info'
dev = get_device_info(name, cmd_list_devices, device_list)
if dev:
devname = dev.get('kernel')
evname = ''
if devname:
devpath = Path(devname)
# Also determine and prefer a non-volatile path merely
# because it is more identifying for users.
for dirstr in ('/dev/input/by-path', '/dev/input/by-id'):
dirpath = Path(dirstr)
if dirpath.exists():
for path in dirpath.iterdir():
if path.resolve() == devpath:
devname = str(path)
evname = f'({devpath.name})'
break
if evname:
break
dev['_path'] = devname
dev['_diag'] = f"{devname}{evname}: {dev.get('device', '?')}"
return dev
class COMMAND:
'Generic command handler'
def __init__(self, args):
self.reprstr = ' '.join(args)
# Expand '~' and env vars in executable command name
args[0] = os.path.expandvars(os.path.expanduser(args[0]))
self.argslist = args
def run(self):
'Run this command + arguments'
run(self.argslist, block=False)
def __str__(self):
'Return string representation'
return self.reprstr
# Table of internal commands
internal_commands = OrderedDict()
def add_internal_command(cls):
'Add configuration command to command lookup table based on name'
internal_commands[re.sub('^COMMAND', '', cls.__name__)] = cls
class ArgumentParser(argparse.ArgumentParser):
'Custom ArgumentParser to return error text'
def error(self, msg):
raise Exception(msg)
@add_internal_command
class COMMAND_internal(COMMAND):
'Internal command handler.'
# Commands currently supported follow. Each is configured with the
# (X,Y) translation to be applied to the desktop grid.
commands = (
('ws_up', ( 0, 1)), # noqa: E241,E201
('ws_down', ( 0, -1)), # noqa: E241,E201
('ws_left', ( 1, 0)), # noqa: E241,E201
('ws_right', (-1, 0)), # noqa: E241,E201
('ws_left_up', ( 1, 1)), # noqa: E241,E201
('ws_left_down', ( 1, -1)), # noqa: E241,E201
('ws_right_up', (-1, 1)), # noqa: E241,E201
('ws_right_down', (-1, -1)), # noqa: E241,E201
)
commands_list = [c[0] for c in commands]
CMDTEST = 'wmctrl -m'.split()
CMDLIST = 'wmctrl -d'.split()
CMDSET = 'wmctrl -s'.split()
def __init__(self, args):
'Action internal swipe commands'
super().__init__(args)
# Set up command line arguments
opt = ArgumentParser(prog=self.argslist[0], description=self.__doc__)
opt.add_argument('-w', '--wrap', action='store_true',
help='wrap workspaces when switching to/from start/end')
opt.add_argument('-c', '--cols', type=int,
help='number of columns in virtual desktop grid, default=1')
opt.add_argument('--row', type=int, default=0, help=argparse.SUPPRESS)
opt.add_argument('--col', type=int, default=0, help=argparse.SUPPRESS)
opt.add_argument('action', choices=self.commands_list,
help='Internal command to action')
args = opt.parse_args(self.argslist[1:])
self.nowrap = not args.wrap
self.rows = 0
self.cols = 0
cmdi = self.commands_list.index(args.action)
if self.CMDTEST[0] and not run(self.CMDTEST, check=False):
print(f'Warning: must install {self.CMDTEST[0]} '
'to use _internal command.', file=sys.stderr)
# Only do above check once
self.CMDTEST[0] = ''
if cmdi >= 2:
if args.row or args.col:
opt.error('Legacy "--row" and "--col" not supported')
if args.cols is None:
if cmdi < 4:
self.cols = 1
cmdi -= 2
else:
opt.error('"--cols" must be specified')
elif args.cols < 1:
opt.error('"--cols" must be >= 1')
else:
self.cols = args.cols
else:
# Convert old legacy/depreciated arguments to new arguments
if args.cols is not None:
if args.cols < 1:
opt.error('"--cols" must be >= 1')
self.cols = args.cols
elif args.row:
cmdi += 2
self.cols = args.row
elif args.col:
self.rows = args.col
else:
self.cols = 1
# Save the translations appropriate to this command
self.xmove, self.ymove = self.commands[cmdi][1]
def run(self, block=False):
'Get list of current workspaces and select next one'
stdout = run(self.CMDLIST, check=False)
if not stdout:
# This command can fail on GNOME when you have only a single
# dynamic workspace (probably a GNOME bug) so let's just
# fudge that default case.
stdout = '0 *\n1 -'
# Parse the output of above command
lines = [ln.split(maxsplit=2)[1] for ln in stdout.strip().splitlines()]
start = index = lines.index('*')
num = len(lines)
cols = self.cols or num // self.rows
numv = ((num - 1) // cols + 1) * cols
# Calculate new workspace X direction index
count = self.xmove
if count < 0:
if index % cols == 0:
if self.nowrap:
return
index += cols - 1
if index >= num:
if self.ymove == 0:
if self.nowrap:
return
index = num - 1
else:
index += count
elif count > 0:
index += count
if index % cols == 0:
if self.nowrap:
return
index -= cols
elif index >= num:
if self.ymove == 0:
if self.nowrap:
return
index -= numv - index
# Calculate new workspace Y direction index
count = self.ymove * cols
if count < 0:
if index < cols and self.nowrap:
return
index = (index + count) % numv
if index >= num:
index += count
elif count > 0:
index += count
if index >= numv:
if self.nowrap:
return
index = index % numv
elif index >= num:
if self.nowrap:
return
index = (index + count) % numv
# Switch to desired workspace
return run(self.CMDSET + [str(index)], block=block) \
if index != start else None
# Table of gesture handlers
handlers = OrderedDict()
# cache for application id to name
appname_cache = {};
def add_gesture_handler(cls):
'Create gesture handler instance and add to lookup table based on name'
handlers[cls.__name__] = cls()
class GESTURE:
'Abstract base class for handling for gestures'
def __init__(self):
'Initialise this gesture at program start'
self.name = type(self).__name__
self.motions = OrderedDict()
self.has_extended = False
def add(self, motion, fingers, command, appname):
'Add a configured motion command for this gesture'
if motion not in self.SUPPORTED_MOTIONS:
opts = '" or "'.join(self.SUPPORTED_MOTIONS)
return f'Gesture {self.name.lower()} does not support '\
f'motion "{motion}".\nMust be "{opts}"'
if not command:
return 'No command configured'
# If any extended gestures configured then set flag to enable
# their discrimination
if self.extended_text and self.extended_text in motion:
self.has_extended = True
key = (appname, motion, fingers) if fingers else (appname, motion)
try:
cmds = shlex.split(command)
except Exception as e:
return str(e)
cls = internal_commands.get(cmds[0], COMMAND)
try:
self.motions[key] = cls(cmds)
except Exception as e:
return str(e)
return None
def begin(self, fingers):
'Initialise this gesture at the start of motion'
self.fingers = fingers
self.data = [0.0, 0.0]
self.starttime = monotonic()
def action(self, motion):
# determine application name of the current active window
appname = get_active_window_title();
appl = Bamf.Matcher.get_default().get_active_application()
if not appl in appname_cache:
if appl:
if appl.get_desktop_file():
appname = Gio.DesktopAppInfo.new_from_filename( appl.get_desktop_file() ).get_name()
if appname == '':
appname = appl.get_name()
appname = appname.lower()
appname_cache[appl] = appname;
else:
appname = appname_cache[appl];
if args.debug:
print(f'current active window [{appname}]')
'Action a motion command for this gesture'
command = self.motions.get((appname, motion, self.fingers)) or \
self.motions.get((appname, motion)) or \
self.motions.get((CATCHALL_APPNAME, motion, self.fingers)) or \
self.motions.get((CATCHALL_APPNAME, motion))
if args.verbose:
print(f'{PROGNAME}: [{appname}] {self.name} {motion} '
f'{self.fingers} {self.data}')
if command:
print(' ', command)
else:
print(' ', 'no command')
if timeoutv > 0 and (self.starttime + timeoutv) < monotonic():
if args.verbose:
print(' ', 'timeout - no action')
return
if timeoutv > 0 and (self.starttime + timeoutv) < monotonic():
if args.verbose:
print(' ', 'timeout - no action')
return
if command and not args.debug:
command.run()
@add_gesture_handler
class SWIPE(GESTURE):
'Class to handle this type of gesture'
SUPPORTED_MOTIONS = ('left', 'right', 'up', 'down',
'left_up', 'right_up', 'left_down', 'right_down')
extended_text = '_'
def update(self, coords):
'Update this gesture for a motion'
# Ignore this update if we can not parse the numbers we expect
try:
x = float(coords[2])
y = float(coords[3])
except (ValueError, IndexError):
return False
self.data[0] += x
self.data[1] += y
return True
def end(self):
'Action this gesture at the end of a motion sequence'
x, y = self.data
abx = abs(x)
aby = abs(y)
# Require absolute distance movement beyond a small thresh-hold.
if abx**2 + aby**2 < abzsquare:
return
# Discriminate left/right or up/down.
# If significant movement in both planes the consider it a
# oblique swipe (but only if any are configured)
if abx > aby:
motion = 'left' if x < 0 else 'right'
if self.has_extended and abx > 0 and aby / abx > OBLIQUE_RATIO:
motion += '_up' if y < 0 else '_down'
else:
motion = 'up' if y < 0 else 'down'
if self.has_extended and aby > 0 and abx / aby > OBLIQUE_RATIO:
motion = ('left_' if x < 0 else 'right_') + motion
self.action(motion)
@add_gesture_handler
class PINCH(GESTURE):
'Class to handle this type of gesture'
SUPPORTED_MOTIONS = ('in', 'out', 'clockwise', 'anticlockwise')
extended_text = 'clock'
def update(self, coords):
'Update this gesture for a motion'
# Ignore this update if we can not parse the numbers we expect
try:
x = float(coords[4])
y = float(coords[5])
except (ValueError, IndexError):
return False
self.data[0] += x - 1.0
self.data[1] += y
return True
def end(self):
'Action this gesture at the end of a motion sequence'
ratio, angle = self.data
if self.has_extended and abs(angle) > ROTATE_ANGLE:
self.action('clockwise' if angle >= 0.0 else 'anticlockwise')
elif ratio != 0.0:
self.action('in' if ratio <= 0.0 else 'out')
@add_gesture_handler
class HOLD(GESTURE):
'Class to handle this type of gesture'
SUPPORTED_MOTIONS = ('on',)
extended_text = None
def update(self, coords):
return True
def end(self):
'Action this gesture at the end of a motion sequence'
self.action('on')
# Table of configuration commands
conf_commands = OrderedDict()
def add_conf_command(func):
'Add configuration command to command lookup table based on name'
conf_commands[re.sub('^conf_', '', func.__name__)] = func
@add_conf_command
def conf_gesture(lineargs, appname):
'Process a single gesture line in conf file'
fields = lineargs.split(maxsplit=2)
# Look for configured gesture. Sanity check the line.
if len(fields) < 3:
return 'Invalid gesture line - not enough fields'
gesture, motion, command = fields
handler = handlers.get(gesture.upper())
if not handler:
opts = '" or "'.join([h.lower() for h in handlers])
return f'Gesture "{gesture}" is not supported.\nMust be "{opts}"'
# Gesture command can be configured with optional specific finger
# count so look for that
fingers, *fcommand = command.split(maxsplit=1)
if fingers.isdigit() and len(fingers) == 1:
command = fcommand[0] if fcommand else ''
else:
fingers = None
# Add the configured gesture
return handler.add(motion.lower(), fingers, command, appname)
@add_conf_command
def conf_device(lineargs):
'Process a single device line in conf file'
# Command line overrides configuration file
if not args.device:
args.device = lineargs
return None if args.device else 'No device specified'
@add_conf_command
def swipe_threshold(lineargs):
'Change swipe threshold'
global swipe_min_threshold
try:
swipe_min_threshold = int(lineargs)
except Exception:
return 'Must be integer value'
return None if swipe_min_threshold >= 0 else 'Must be >= 0'
@add_conf_command
def timeout(lineargs):
'Change gesture timeout'
global timeoutv
try:
timeoutv = float(lineargs)
except Exception:
return 'Must be float value'
return None if timeoutv >= 0 else 'Must be >= 0'
def get_conf_line(line, appname):
'Process a single line in conf file'
key, *argslist = line.split(maxsplit=1)
# Old format conf files may have a ":" appended to the key
key = key.rstrip(':')
conf_func = conf_commands.get(key)
if not conf_func:
opts = '" or "'.join(conf_commands)
return f'Configuration command "{key}" is not supported.\n' \
f'Must be "{opts}"'
return conf_func(argslist[0] if argslist else '', appname)
def get_conf(conffile, confname):
'Read given configuration file and store internal actions etc'
with conffile.open() as fp:
appname = CATCHALL_APPNAME
for num, line in enumerate(fp, 1):
line = line.strip()
if not line or line[0] == '#':
continue
if line[0] == '[':
appname = line[1:-1].strip().lower();
continue
errmsg = get_conf_line(line, appname)
if errmsg:
sys.exit(f'Error at line {num} in file {confname}:\n'
f'>> {line} <<\n{errmsg}.')
def unexpanduser(cfile):
'Return absolute path name, with $HOME replaced by ~'
cfile_abs = cfile.resolve()
if cfile_abs.parts[:len(HOME.parts)] != HOME.parts:
return str(cfile_abs)
return str(Path('~', *cfile_abs.parts[len(HOME.parts):]))
# Search for configuration file. Use file given as command line
# argument, else look for file in search dir order.
def read_conf(conffile, defname):
if conffile:
confpath = Path(conffile)
if not confpath.exists():
sys.exit(f'Conf file "{conffile}" does not exist.')
else:
for confdir in CONFDIRS:
confpath = Path(confdir, defname)
if confpath.exists():
break
else:
opts = ' or '.join([unexpanduser(Path(c)) for c in CONFDIRS])
sys.exit(f'No file {defname} in {opts}.')
# Hide any personal user dir/names from diag output
confname = unexpanduser(confpath)
# Read and process the conf file
get_conf(confpath, confname)
return confname
def lockcheck():
'Listen on DBus to set session_locked state'
def proc(busname, vals, _):
global session_locked
if busname == 'org.freedesktop.login1.Session':
val = vals.get('LockedHint')
if val is not None:
session_locked = bool(val)
DBusGMainLoop(set_as_default=True)
dbus.SystemBus().add_signal_receiver(
proc,
'PropertiesChanged',
'org.freedesktop.DBus.Properties',
'org.freedesktop.login1',
)
GLib.MainLoop().run()
def gethash():
'Return a crude hash identifier for this software version'
progs = (PROGPATH, PROGPATH.with_name(PROGNAME + '-setup'))
return hashlib.md5(b''.join(p.read_bytes() for p in progs if
p.exists())).hexdigest()
def main():
global args, abzsquare
# Set up command line arguments
opt = argparse.ArgumentParser(description=__doc__)
opt.add_argument('-c', '--conffile',
help='alternative configuration file')
opt.add_argument('-v', '--verbose', action='store_true',
help='output diagnostic messages')
opt.add_argument('-d', '--debug', action='store_true',
help='output diagnostic messages only, do not action gestures')
opt.add_argument('-r', '--raw', action='store_true',
help='output raw libinput debug-event messages only, '
'do not action gestures')
opt.add_argument('-l', '--list', action='store_true',
help='just list out environment and configuration')
opt.add_argument('--device',
help='explicit device name to use (or path if starts with /)')
# Test/diag hidden option to specify a file containing libinput list
# device output to parse
opt.add_argument('--device-list', help=argparse.SUPPRESS)
args = opt.parse_args()
if args.debug or args.raw or args.list:
args.verbose = True
# Libinput changed the way in which it's utilities are called
libvers, has_subcmd = get_libinput_vers()
if not libvers:
sys.exit('libinput helper tools do not seem to be installed?')
if has_subcmd:
cmd_debug_events = 'libinput debug-events'
cmd_list_devices = 'libinput list-devices'
else:
cmd_debug_events = 'libinput-debug-events'
cmd_list_devices = 'libinput-list-devices'
if args.verbose:
# Output various info/version info
xsession = os.getenv('XDG_SESSION_DESKTOP') or \
os.getenv('DESKTOP_SESSION') or 'unknown'
xtype = os.getenv('XDG_SESSION_TYPE') or 'unknown'
xstr = f'session {xsession}+{xtype}'
pf = platform.platform()
pfpy = f'python {platform.python_version()}'
lstr = f'libinput {libvers}'
print(f'{PROGNAME}: {xstr} on {pf}, {pfpy}, {lstr}')
# Output hash version/checksum of this program
print(f'Hash: {gethash()}')
# Read and process the conf file
confname = read_conf(args.conffile, CONFNAME)
# List out available gestures if that is asked for
if args.verbose:
if not args.raw:
print(f'Gestures configured in {confname}:')
for h in handlers.values():
for mpair, cmd in h.motions.items():
if len(mpair) == 2:
appname, motion = mpair
fingers = ''
else:
appname, motion, fingers = mpair
print(f'[{appname}] {h.name.lower()} {motion:10}{fingers:>2} {cmd}')
if swipe_min_threshold:
print(f'swipe_threshold {swipe_min_threshold}')
if timeoutv != DEFAULT_TIMEOUT:
print(f'timeout {timeoutv}')
if args.device:
print(f'device {args.device}')
# Get touchpad device
if not args.device or args.device.lower() != "all":
device = get_device(args.device, cmd_list_devices, args.device_list)
if not device:
sys.exit('Could not determine touchpad device.')
else:
device = None
if args.verbose:
if device:
print(f"{PROGNAME}: device {device.get('_diag')}")
else:
print(f'{PROGNAME}: monitoring all devices')
# If just called to list out above environment info then exit now
if args.list:
status = run((PROGNAME + '-setup', 'status'), check=False)
if status:
print(status.strip())
sys.exit()
# Make sure only one instance running for current user
user = getpass.getuser()
lockfile, pidfile = open_lock(PROGNAME, user)
if not lockfile:
sys.exit(f'{PROGNAME} is already running for {user}, terminating ..')
# Set up square of swipe threshold
abzsquare = swipe_min_threshold**2
# Note your must "sudo gpasswd -a $USER input" then reboot for
# permission to access the device.
devstr = f" --device {device.get('_path')}" if device else ''
command = f'stdbuf -oL -- {cmd_debug_events}{devstr}'
if dbus_imported:
t = threading.Thread(target=lockcheck)
t.daemon = True
t.start()
cmd = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
bufsize=1, universal_newlines=True)
# Store PIDs for potential kill
pidfile.write(f'{os.getpid()}\n{cmd.pid}\n')
pidfile.flush()
os.fsync(pidfile.fileno())
# Sit in a loop forever reading the libinput messages ..
handler = None
for line in cmd.stdout:
# Ignore gestures if this session is locked
if session_locked:
continue
# Just output raw messages if in that mode
if args.raw:
print(line.strip())
continue
# Only interested in gestures
if 'GESTURE_' not in line:
continue
# Split received message line into relevant fields
dev, gevent, time, other = line.strip().split(maxsplit=3)
try:
gesture, event = gevent[8:].split('_')
except Exception:
continue
fingers, *argslist = other.split(maxsplit=1)
params = argslist[0] if argslist else ''
# Action each type of event
if event == 'UPDATE':
if handler:
# Split parameters into list of clean numbers
if not handler.update(re.split(r'[^-.\d]+', params)):
print('Could not parse {gesture} {event}: {params}',
file=sys.stderr)
elif event == 'BEGIN':
handler = handlers.get(gesture)
if handler:
handler.begin(fingers)
else:
print(f'Unknown gesture received: {gesture}.',
file=sys.stderr)
elif event == 'END':
# Ignore gesture if final action is cancelled
if handler:
if params != 'cancelled':
handler.end()
handler = None
else:
print(f'Unknown gesture {gesture} + event {event} received.',
file=sys.stderr)
if __name__ == '__main__':
main()