File: device.py

package info (click to toggle)
mypaint 2.0.1-14
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 27,884 kB
  • sloc: python: 43,893; cpp: 6,931; xml: 2,475; sh: 473; makefile: 25
file content (669 lines) | stat: -rw-r--r-- 22,587 bytes parent folder | download | duplicates (4)
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
# This file is part of MyPaint.
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2019 by the MyPaint Development Team.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

"""Device specific settings and configuration"""


## Imports

from __future__ import division, print_function
import logging
import collections
import re

from lib.gettext import C_
from lib.gibindings import Gtk
from lib.gibindings import Gdk
from lib.gibindings import Pango

from lib.observable import event
import gui.application
import gui.mode

logger = logging.getLogger(__name__)

## Device prefs

# The per-device settings are stored in the prefs in a sub-dict whose
# string keys are formed from the device name and enough extra
# information to (hopefully) identify the device uniquely. Names are not
# unique, and IDs vary according to the order in which you plug devices
# in. So for now, our unique strings use a combination of the device's
# name, its source as presented by GDK, and the number of axes.

_PREFS_ROOT = "input.devices"
_PREFS_DEVICE_SUBKEY_FMT = "{name}:{source}:{num_axes}"


## Device type strings

_DEVICE_TYPE_STRING = {
    Gdk.InputSource.CURSOR: C_(
        "prefs: device's type label",
        "Cursor/puck",
    ),
    Gdk.InputSource.ERASER: C_(
        "prefs: device's type label",
        "Eraser",
    ),
    Gdk.InputSource.KEYBOARD: C_(
        "prefs: device's type label",
        "Keyboard",
    ),
    Gdk.InputSource.MOUSE: C_(
        "prefs: device's type label",
        "Mouse",
    ),
    Gdk.InputSource.PEN: C_(
        "prefs: device's type label",
        "Pen",
    ),
    Gdk.InputSource.TOUCHPAD: C_(
        "prefs: device's type label",
        "Touchpad",
    ),
    Gdk.InputSource.TOUCHSCREEN: C_(
        "prefs: device's type label",
        "Touchscreen",
    ),
}


## Settings consts and classes


class AllowedUsage:
    """Consts describing how a device may interact with the canvas"""

    ANY = "any"  #: Device can be used for any tasks.
    NOPAINT = "nopaint"  #: No direct painting, but can manipulate objects.
    NAVONLY = "navonly"  #: Device can only be used for navigation.
    IGNORED = "ignored"  #: Device cannot interact with the canvas at all.

    VALUES = (ANY, IGNORED, NOPAINT, NAVONLY)
    DISPLAY_STRING = {
        IGNORED: C_(
            "device settings: allowed usage",
            u"Ignore",
        ),
        ANY: C_(
            "device settings: allowed usage",
            u"Any Task",
        ),
        NOPAINT: C_(
            "device settings: allowed usage",
            u"Non-painting tasks",
        ),
        NAVONLY: C_(
            "device settings: allowed usage",
            u"Navigation only",
        ),
    }
    BEHAVIOR_MASK = {
        ANY: gui.mode.Behavior.ALL,
        IGNORED: gui.mode.Behavior.NONE,
        NOPAINT: gui.mode.Behavior.NON_PAINTING,
        NAVONLY: gui.mode.Behavior.CHANGE_VIEW,
    }


class ScrollAction:
    """Consts describing how a device's scroll events should be used.

    The user can assign one of these values to a device to configure
    whether they'd prefer panning or scrolling for unmodified scroll
    events. This setting can be queried via the device monitor.

    """

    ZOOM = "zoom"  #: Alter the canvas scaling
    PAN = "pan"   #: Pan across the canvas

    VALUES = (ZOOM, PAN)
    DISPLAY_STRING = {
        ZOOM: C_("device settings: unmodified scroll action", u"Zoom"),
        PAN: C_("device settings: unmodified scroll action", u"Pan"),
    }


class Settings (object):
    """A device's settings"""

    DEFAULT_USAGE = AllowedUsage.VALUES[0]
    DEFAULT_SCROLL = ScrollAction.VALUES[0]

    def __init__(self, prefs, usage=DEFAULT_USAGE, scroll=DEFAULT_SCROLL):
        super(Settings, self).__init__()
        self._usage = self.DEFAULT_USAGE
        self._update_usage_mask()
        self._scroll = self.DEFAULT_SCROLL
        self._prefs = prefs
        self._load_from_prefs()

    @property
    def usage(self):
        return self._usage

    @usage.setter
    def usage(self, value):
        if value not in AllowedUsage.VALUES:
            raise ValueError("Unrecognized usage value")
        self._usage = value
        self._update_usage_mask()
        self._save_to_prefs()

    @property
    def usage_mask(self):
        return self._usage_mask

    @property
    def scroll(self):
        return self._scroll

    @scroll.setter
    def scroll(self, value):
        if value not in ScrollAction.VALUES:
            raise ValueError("Unrecognized scroll value")
        self._scroll = value
        self._save_to_prefs()

    def _load_from_prefs(self):
        usage = self._prefs.get("usage", self.DEFAULT_USAGE)
        if usage not in AllowedUsage.VALUES:
            usage = self.DEFAULT_USAGE
        self._usage = usage
        scroll = self._prefs.get("scroll", self.DEFAULT_SCROLL)
        if scroll not in ScrollAction.VALUES:
            scroll = self.DEFAULT_SCROLL
        self._scroll = scroll
        self._update_usage_mask()

    def _save_to_prefs(self):
        self._prefs.update({
            "usage": self._usage,
            "scroll": self._scroll,
        })

    def _update_usage_mask(self):
        self._usage_mask = AllowedUsage.BEHAVIOR_MASK[self._usage]


## Main class defs


class Monitor (object):
    """Monitors device use & plugging, and manages their configuration

    An instance resides in the main application. It is responsible for
    monitoring known devices, determining their characteristics, and
    storing their settings. Per-device settings are stored in the main
    application preferences.

    """

    def __init__(self, app):
        """Initializes, assigning initial input device uses

        :param app: the owning Application instance.
        :type app: gui.application.Application
        """
        super(Monitor, self).__init__()
        self._app = app
        if app is not None:
            self._prefs = app.preferences
        else:
            self._prefs = {}
        if _PREFS_ROOT not in self._prefs:
            self._prefs[_PREFS_ROOT] = {}

        # Transient device information
        self._device_settings = collections.OrderedDict()  # {dev: settings}
        self._last_event_device = None
        self._last_pen_device = None

        disp = Gdk.Display.get_default()
        mgr = disp.get_device_manager()
        mgr.connect("device-added", self._device_added_cb)
        mgr.connect("device-removed", self._device_removed_cb)
        self._device_manager = mgr

        for physical_device in mgr.list_devices(Gdk.DeviceType.SLAVE):
            self._init_device_settings(physical_device)

    ## Devices list

    def get_device_settings(self, device):
        """Gets the settings for a device

        :param Gdk.Device device: a physical ("slave") device
        :returns: A settings object which can be manipulated, or None
        :rtype: Settings

        Changes to the returned object made via its API are saved to the
        user preferences immediately.

        If the device is a keyboard, or is otherwise unsuitable as a
        pointing device, None is returned instead. The caller needs to
        check this case.

        """
        self._init_device_settings(device)
        return self._device_settings.get(device)

    def _init_device_settings(self, device):
        """Ensures that the device settings are loaded for a device"""
        source = device.get_source()
        if source == Gdk.InputSource.KEYBOARD:
            return
        num_axes = device.get_n_axes()
        if num_axes < 2:
            return
        settings = self._device_settings.get(device)
        if not settings:
            try:
                vendor_id = device.get_vendor_id()
                product_id = device.get_product_id()
            except AttributeError:
                # New in GDK 3.16
                vendor_id = "?"
                product_id = "?"
            logger.info(
                "New device %r"
                " (%s, axes:%d, class=%s, vendor=%r, product=%r)",
                device.get_name(),
                source.value_name,
                num_axes,
                device.__class__.__name__,
                vendor_id,
                product_id,
            )
            dev_prefs_key = _device_prefs_key(device)
            dev_prefs = self._prefs[_PREFS_ROOT].setdefault(dev_prefs_key, {})
            settings = Settings(dev_prefs)
            self._device_settings[device] = settings
            self.devices_updated()
        assert settings is not None

    def _device_added_cb(self, mgr, device):
        """Informs that a device has been plugged in"""
        logger.debug("device-added %r", device.get_name())
        self._init_device_settings(device)

    def _device_removed_cb(self, mgr, device):
        """Informs that a device has been unplugged"""
        logger.debug("device-removed %r", device.get_name())
        self._device_settings.pop(device, None)
        self.devices_updated()

    @event
    def devices_updated(self):
        """Event: the devices list was changed"""

    def get_devices(self):
        """Yields devices and their settings, for UI stuff

        :rtype: iterator
        :returns: ultimately a sequence of (Gdk.Device, Settings) pairs

        """
        for device, settings in self._device_settings.items():
            yield (device, settings)

    ## Current device

    @event
    def current_device_changed(self, old_device, new_device):
        """Event: the current device has changed

        :param Gdk.Device old_device: Previous device used
        :param Gdk.Device new_device: New device used
        """

    def device_used(self, device):
        """Informs about a device being used, for use by controllers

        :param Gdk.Device device: the device being used
        :returns: whether the device changed

        If the device has changed, this method then notifies interested
        parties via the device_changed observable @event.

        This method returns True if the device was the same as the previous
        device, and False if it has changed.
        """
        if not self.get_device_settings(device):
            return False
        if device == self._last_event_device:
            return True
        self.current_device_changed(self._last_event_device, device)
        old_device = self._last_event_device
        new_device = device
        self._last_event_device = device

        # small problem with this code: it doesn't work well with brushes that
        # have (eraser not in [1.0, 0.0])

        new_device.name = new_device.props.name
        new_device.source = new_device.props.input_source

        logger.debug(
            "Device change: name=%r source=%s",
            new_device.name, new_device.source.value_name,
        )

        # When editing brush settings, it is often more convenient to use the
        # mouse. Because of this, we don't restore brushsettings when switching
        # to/from the mouse. We act as if the mouse was identical to the last
        # active pen device.

        if (new_device.source == Gdk.InputSource.MOUSE and
                self._last_pen_device):
            new_device = self._last_pen_device
        if new_device.source == Gdk.InputSource.PEN:
            self._last_pen_device = new_device
        if (old_device and old_device.source == Gdk.InputSource.MOUSE and
                self._last_pen_device):
            old_device = self._last_pen_device

        bm = self._app.brushmanager
        if old_device:
            # Clone for saving
            old_brush = bm.clone_selected_brush(name=None)
            bm.store_brush_for_device(old_device.name, old_brush)

        if new_device.source == Gdk.InputSource.MOUSE:
            # Avoid fouling up unrelated devbrushes at stroke end
            self._prefs.pop('devbrush.last_used', None)
        else:
            # Select the brush and update the UI.
            # Use a sane default if there's nothing associated
            # with the device yet.
            brush = bm.fetch_brush_for_device(new_device.name)
            if brush is None:
                if device_is_eraser(new_device):
                    brush = bm.get_default_eraser()
                else:
                    brush = bm.get_default_brush()
            self._prefs['devbrush.last_used'] = new_device.name
            bm.select_brush(brush)


class SettingsEditor (Gtk.Grid):
    """Per-device settings editor"""

    ## Class consts

    _USAGE_CONFIG_COL = 0
    _USAGE_STRING_COL = 1
    _SCROLL_CONFIG_COL = 0
    _SCROLL_STRING_COL = 1

    __gtype_name__ = "MyPaintDeviceSettingsEditor"

    ## Initialization

    def __init__(self, monitor=None):
        """Initialize

        :param Monitor monitor: monitor instance (for testing)

        By default, the central app's `device_monitor` is used to permit
        parameterless construction.
        """
        super(SettingsEditor, self).__init__()
        if monitor is None:
            app = gui.application.get_app()
            monitor = app.device_monitor
        self._monitor = monitor

        self._devices_store = Gtk.ListStore(object)
        self._devices_view = Gtk.TreeView(model=self._devices_store)

        col = Gtk.TreeViewColumn(C_(
            "prefs: devices table: column header",
            # TRANSLATORS: Column's data is the device's name
            "Device",
        ))
        col.set_min_width(200)
        col.set_expand(True)
        col.set_sizing(Gtk.TreeViewColumnSizing.AUTOSIZE)
        self._devices_view.append_column(col)
        cell = Gtk.CellRendererText()
        cell.set_property("ellipsize", Pango.EllipsizeMode.MIDDLE)
        col.pack_start(cell, True)
        col.set_cell_data_func(cell, self._device_name_datafunc)

        col = Gtk.TreeViewColumn(C_(
            "prefs: devices table: column header",
            # TRANSLATORS: Column's data is the number of axes (an integer)
            "Axes",
        ))
        col.set_min_width(30)
        col.set_resizable(True)
        col.set_expand(False)
        col.set_sizing(Gtk.TreeViewColumnSizing.AUTOSIZE)
        self._devices_view.append_column(col)
        cell = Gtk.CellRendererText()
        col.pack_start(cell, True)
        col.set_cell_data_func(cell, self._device_axes_datafunc)

        col = Gtk.TreeViewColumn(C_(
            "prefs: devices table: column header",
            # TRANSLATORS: Column shows type labels ("Touchscreen", "Pen" etc.)
            "Type",
        ))
        col.set_min_width(120)
        col.set_resizable(True)
        col.set_expand(False)
        col.set_sizing(Gtk.TreeViewColumnSizing.AUTOSIZE)
        self._devices_view.append_column(col)
        cell = Gtk.CellRendererText()
        cell.set_property("ellipsize", Pango.EllipsizeMode.END)
        col.pack_start(cell, True)
        col.set_cell_data_func(cell, self._device_type_datafunc)

        # Usage config value => string store (dropdowns)
        store = Gtk.ListStore(str, str)
        for conf_val in AllowedUsage.VALUES:
            string = AllowedUsage.DISPLAY_STRING[conf_val]
            store.append([conf_val, string])
        self._usage_store = store

        col = Gtk.TreeViewColumn(C_(
            "prefs: devices table: column header",
            # TRANSLATORS: Column's data is a dropdown allowing the allowed
            # TRANSLATORS: tasks for the row's device to be configured.
            u"Use for…",
        ))
        col.set_min_width(100)
        col.set_resizable(True)
        col.set_expand(False)
        self._devices_view.append_column(col)

        cell = Gtk.CellRendererCombo()
        cell.set_property("model", self._usage_store)
        cell.set_property("text-column", self._USAGE_STRING_COL)
        cell.set_property("mode", Gtk.CellRendererMode.EDITABLE)
        cell.set_property("editable", True)
        cell.set_property("has-entry", False)
        cell.set_property("ellipsize", Pango.EllipsizeMode.END)
        cell.connect("changed", self._usage_cell_changed_cb)
        col.pack_start(cell, True)
        col.set_cell_data_func(cell, self._device_usage_datafunc)

        # Scroll action config value => string store (dropdowns)
        store = Gtk.ListStore(str, str)
        for conf_val in ScrollAction.VALUES:
            string = ScrollAction.DISPLAY_STRING[conf_val]
            store.append([conf_val, string])
        self._scroll_store = store

        col = Gtk.TreeViewColumn(C_(
            "prefs: devices table: column header",
            # TRANSLATORS: Column's data is a dropdown for how the device's
            # TRANSLATORS: scroll wheel or scroll-gesture events are to be
            # TRANSLATORS: interpreted normally.
            u"Scroll…",
        ))
        col.set_min_width(100)
        col.set_resizable(True)
        col.set_expand(False)
        self._devices_view.append_column(col)

        cell = Gtk.CellRendererCombo()
        cell.set_property("model", self._scroll_store)
        cell.set_property("text-column", self._USAGE_STRING_COL)
        cell.set_property("mode", Gtk.CellRendererMode.EDITABLE)
        cell.set_property("editable", True)
        cell.set_property("has-entry", False)
        cell.set_property("ellipsize", Pango.EllipsizeMode.END)
        cell.connect("changed", self._scroll_cell_changed_cb)
        col.pack_start(cell, True)
        col.set_cell_data_func(cell, self._device_scroll_datafunc)

        # Pretty borders
        view_scroll = Gtk.ScrolledWindow()
        view_scroll.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        pol = Gtk.PolicyType.AUTOMATIC
        view_scroll.set_policy(pol, pol)
        view_scroll.add(self._devices_view)
        view_scroll.set_hexpand(True)
        view_scroll.set_vexpand(True)
        self.attach(view_scroll, 0, 0, 1, 1)

        self._update_devices_store()
        self._monitor.devices_updated += self._update_devices_store

    ## Display and sort funcs

    def _device_name_datafunc(self, column, cell, model, iter_, *data):
        device = model.get_value(iter_, 0)
        cell.set_property("text", device.get_name())

    def _device_axes_datafunc(self, column, cell, model, iter_, *data):
        device = model.get_value(iter_, 0)
        n_axes = device.get_n_axes()
        cell.set_property("text", "%d" % (n_axes,))

    def _device_type_datafunc(self, column, cell, model, iter_, *data):
        device = model.get_value(iter_, 0)
        source = device.get_source()
        text = _DEVICE_TYPE_STRING.get(source, source.value_nick)
        cell.set_property("text", text)

    def _device_usage_datafunc(self, column, cell, model, iter_, *data):
        device = model.get_value(iter_, 0)
        settings = self._monitor.get_device_settings(device)
        if not settings:
            return
        text = AllowedUsage.DISPLAY_STRING[settings.usage]
        cell.set_property("text", text)

    def _device_scroll_datafunc(self, column, cell, model, iter_, *data):
        device = model.get_value(iter_, 0)
        settings = self._monitor.get_device_settings(device)
        if not settings:
            return
        text = ScrollAction.DISPLAY_STRING[settings.scroll]
        cell.set_property("text", text)

    ## Updates

    def _usage_cell_changed_cb(self, combo, device_path_str,
                               usage_iter, *etc):
        config = self._usage_store.get_value(
            usage_iter,
            self._USAGE_CONFIG_COL,
        )
        device_iter = self._devices_store.get_iter(device_path_str)
        device = self._devices_store.get_value(device_iter, 0)
        settings = self._monitor.get_device_settings(device)
        if not settings:
            return
        settings.usage = config
        self._devices_view.columns_autosize()

    def _scroll_cell_changed_cb(self, conf_combo, device_path_str,
                                conf_iter, *etc):
        conf_store = self._scroll_store
        conf_col = self._SCROLL_CONFIG_COL
        conf_value = conf_store.get_value(conf_iter, conf_col)
        device_store = self._devices_store
        device_iter = device_store.get_iter(device_path_str)
        device = device_store.get_value(device_iter, 0)
        settings = self._monitor.get_device_settings(device)
        if not settings:
            return
        settings.scroll = conf_value
        self._devices_view.columns_autosize()

    def _update_devices_store(self, *_ignored):
        """Repopulates the displayed list"""
        updated_list = list(self._monitor.get_devices())
        updated_list_map = dict(updated_list)
        paths_for_removal = []
        devices_retained = set()
        for row in self._devices_store:
            device, = row
            if device not in updated_list_map:
                paths_for_removal.append(row.path)
                continue
            devices_retained.add(device)
        for device, config in updated_list:
            if device in devices_retained:
                continue
            self._devices_store.append([device])
        for unwanted_row_path in reversed(paths_for_removal):
            unwanted_row_iter = self._devices_store.get_iter(unwanted_row_path)
            self._devices_store.remove(unwanted_row_iter)
        self._devices_view.queue_draw()


## Helper funcs


def _device_prefs_key(device):
    """Returns the subkey to use in the app prefs for a device"""
    source = device.get_source()
    name = device.get_name()
    n_axes = device.get_n_axes()
    return u"%s:%s:%d" % (name, source.value_nick, n_axes)


def device_is_eraser(device):
    """Tests whether a device appears to be an eraser"""
    if device is None:
        return False
    if device.get_source() == Gdk.InputSource.ERASER:
        return True
    if re.search(r'\<eraser\>', device.get_name(), re.I):
        return True
    return False


## Testing


def _test():
    """Interactive UI testing for SettingsEditor and Monitor"""
    logging.basicConfig(level=logging.DEBUG)
    win = Gtk.Window()
    win.set_title("gui.device.SettingsEditor")
    win.set_default_size(500, 400)
    win.connect("destroy", Gtk.main_quit)
    monitor = Monitor(app=None)
    editor = SettingsEditor(monitor)
    win.add(editor)
    win.show_all()
    Gtk.main()
    print(monitor._prefs)


if __name__ == '__main__':
    _test()