Набор замедления мыши - как к?

Введение: xinput команда позволяет мне устанавливать параметр замедления для своей мыши, что я должен сделать, потому что мне нравится маленькая чувствительность мыши, и самое маленькое значение в Ubuntu все еще немного слишком высоко для меня. Таким образом, я использую:

szczepan@szczepan-550P5C:~$ xinput list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ A4TECH USB Device                         id=10   [slave  pointer  (2)]
⎜   ↳ A4TECH USB Device                         id=11   [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=14   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ Power Button                              id=9    [slave  keyboard (3)]
    ↳ WebCam SC-13HDL11939N                     id=12   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=13   [slave  keyboard (3)]
szczepan@szczepan-550P5C:~$ xinput set-prop 11 "Device Accel Constant Deceleration" 5

... и все в порядке. Но я должен использовать эти команды каждый раз, когда я включаю свое устройство на, вхожу в систему после поворота прочь/сон.

Мой вопрос: действительно ли возможно вызвать Ubuntu, каждый раз, когда этот deivce обнаруживается, для установки параметра "Устройство Accel Постоянное Замедление" для устройства USB-устройство A4TECH как 5? И если да, как я могу сделать это? Спасибо за все усилие заранее.

2
задан 4 August 2016 в 14:21

1 ответ

Введение

Рев сценария ожидает пользовательского устройства, которое будет соединено, и устанавливает соответствующие значения, непрерывно повторяя процесс, таким образом позволяя пользователю подключить и отключить устройство несколько время во время сессии.

Это читает пользователя - определенные настройки в ~/.xinputmonrc файл, который должен быть создан прежде, чем запустить сценарий

Использование

Как показано -h опция:

usage: xinput_monitor.py [-h] [-q] -d DEVICE

Script that waits for presence of user device and sets preferences as defined in
~/.xinputmonrc file

optional arguments:
  -h, --help            show this help message and exit
  -q, --quiet           Blocks on-screen notifications
  -d DEVICE, --device DEVICE
                        device name

Примечание: Как указано в описании, чтениях файла ~/.xinputmonrc где ~ Ваш корневой каталог. Пример такого файла (отмечают использование массива свойствами, которые требуют нескольких значений):

{
 "Device Accel Constant Deceleration":5,
 "Evdev Scrolling Distance":[1,1,1]
}

Предположим, что мы имеем Logitech USB Receiver устройство, перечисленное в xinput вывод. Как сценарий можно назвать так:

python3 xinput_monitor.py -d "Logitech USB Receiver"

Сценарий выпустит уведомление, что контроль запустился:

enter image description here

После того как устройство подключено, оно выпустит уведомление, что устройство было обнаружено:

enter image description here

Если все в порядке, сценарий продолжается тихо и ожидает, пока устройство не является disconnected:

enter image description here

-q опция позволяет заставлять все пузыри уведомления замолчать.

Получение сценария

Исходный код доступен в этом сообщении и как Суть на GitHub

Можно скопировать исходный код отсюда, сохранить его как xinput_monitor.py , и сделайте исполняемый файл с chmod +x xinput_monitor.py терминальная команда в том, какой бы ни каталог Вы сохранили его.

Исходный код

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Sergiy Kolodyazhnyy
Date:  August 2nd, 2016
Written for: https://askubuntu.com/q/806212/295286
Tested on Ubuntu 16.04 LTS

usage: xinput_monitor.py [-h] [-q] -d DEVICE

Script that waits for presence of user device 
and sets preferences as defined
in ~/.xinputmonrc file

optional arguments:
  -h, --help            show this help message and exit
  -q, --quiet           Blocks on-screen notifications
  -d DEVICE, --device DEVICE
                        device name

"""
from __future__ import print_function
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
import subprocess
import argparse
import time
import json
import os

def send_notif(n,title, text):
    try:
        if Notify.init(__file__):
            # n = Notify.Notification.new("Notify")
            n.update(title, text)
            n.set_urgency(2)
            if not n.show():
                raise SyntaxError("sending notification failed!")
        else:
            raise SyntaxError("can't initialize notification!")
    except SyntaxError as error:
        print(error)
        if error == "sending notification failed!":
            Notify.uninit()
    else:
        Notify.uninit()

def run_cmd(cmdlist):
    """ Reusable function for running shell commands"""
    try:
        stdout = subprocess.check_output(cmdlist)
    except subprocess.CalledProcessError as pserror:
        return pserror.output.decode().strip()
        #sys.exit(1)
    else:
        if stdout:
            return stdout.decode().strip()

def list_ids(mouse_name):
    """ Returns list of ids for the same device"""
    #while True:
    mouse_ids = []
    for dev_id in run_cmd(['xinput','list','--id-only']).split('\n'):
        if mouse_name in run_cmd(['xinput','list','--name-only',dev_id]):
           mouse_ids.append(dev_id)
    return mouse_ids

def read_config_file(notif):

    """ reads ~/.xinputmonrc  file """
    rcfile = os.path.join( os.path.expanduser('~'),'.xinputmonrc')
    try:
        with open(rcfile) as config_file:
            config_data = json.load(config_file)
    except IOError as error:
        send_notif(notif, __file__ , error.__repr__()  )
    else:
        if config_data:
            return config_data

def set_props(notif,device):
    """Sets properties per each device is
       given by list_ids() function"""

    props = read_config_file(notif)
    # Thiscan also be set manually as in 
    # commented-out example below

    #props = { 'Device Accel Profile':'-1',
    #          'Device Accel Constant Deceleration':'3.5',
    #          'Device Accel Velocity Scaling':'1.0'   }

    if not props:
        send_notif(notif,'Reading ~/.xinputmonrc failed', 
                   'Please write proper rc file.') 
        return None
    """ set all property-value pair per each device id
        Uncomment the print function if you wish to know
        which ids have been altered for double-checking
        with xinput list-props"""
    for dev_id in list_ids(device):
        # print(dev_id)
        for prop,value in props.items():
            if type(value) is not list: 
                value = [value]
            run_cmd(['xinput','set-prop',dev_id,prop] + 
                    [str(item) for item in value ])  

def parse_args():
    """ Parse command line arguments"""
    arg_parser = argparse.ArgumentParser(
                 description="""Script that waits for """ + 
                             """presence of user device """+ 
                             """and sets preferences as """ + 
                             """defined in ~/.xinputmonrc file""")
    arg_parser.add_argument(
                '-q','--quiet', action='store_true',
                help='Blocks on-screen notifications',
                required=False)

    arg_parser.add_argument(
                '-d','--device', 
                help='device name',
                type=str,
                required=True)
    return arg_parser.parse_args()

def main():
    notif = Notify.Notification.new("Notify")
    args = parse_args()
    while True:
         if not args.quiet:
             send_notif(notif, __file__ , 
                        'Wating for ' + args.device )
         while args.device not in run_cmd(['xinput','list','--name-only']):
             time.sleep(0.25)
             pass
         time.sleep(0.25) # let xinput catch up
         if not args.quiet:
             send_notif(notif, __file__, 
                        args.device + ' connected. Setting values')
         # set props here
         set_props(notif,args.device)
         while args.device in run_cmd(['xinput','list','--name-only']):
             time.sleep(0.25)
             pass
         if not args.quiet:
             send_notif( notif , __file__ , args.device +  
                         ' disconnected. Resuming monitoring' )

if __name__ == '__main__':
    main()

Примечания

4
ответ дан 2 December 2019 в 02:18

Другие вопросы по тегам:

Похожие вопросы: