Exemple #1
0
 def __setitem__(self, action, key_list):
     assert action in self._actions
     if isinstance(key_list, str):
         key_list = (key_list, )
     # Delete previous bindings.
     if action in self._mappings:
         for old_key in self._mappings[action]:
             if old_key in self._bindings:
                 del self._bindings[old_key]
     errors = []
     valid_key_list = []
     for key in key_list:
         if key not in self._keys:
             errors.append('invalid key %s bound to action %s' %
                           (key, action))
             continue
         if key in self._bindings:
             errors.append('key %s is already bound to: %s' %
                           (key, self._bindings[key]))
             continue
         valid_key_list.append(key)
         self._bindings[key] = action
     self._mappings[action] = tuple(
         sorted(valid_key_list, key=self._keys.get))
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' +
                     '\n- '.join(errors))
Exemple #2
0
 def start_capture(self):
     """Begin listening for output from the stenotype machine."""
     if not self._connect():
         log.warning('Treal is not connected')
         self._error()
         return
     super(Treal, self).start_capture()
Exemple #3
0
    def find_stenograph(self):
        try:
            log.warning("Searching for Wi-Fi Stenographs...")
            udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                socket.IPPROTO_UDP)
            udp.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            udp.settimeout(10)

            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            while self._stenograph_address == None:
                udp.sendto(BATTLE_CRY, (BROADCAST_ADDRESS, BROADCAST_PORT))
                sleep(1.2)

                data, address = udp.recvfrom(65565)

                if "Mira in the neighborhood" in data.decode("utf-8"):
                    self._stenograph_address = address
                    udp.close()
                    break

        except client.timeout as e:
            log.warning('Client timed out: %s' % e)

        return self._stenograph_address
 def run(self):
     self._reset_state()
     while not self.finished.isSet():
         try:
             response = self._machine.read(self._file_offset)
         except IOError as e:
             log.warning(u'Stenograph machine disconnected, reconnecting…')
             log.debug('Stenograph exception: %s', str(e))
             self._reset_state()
             if self._reconnect():
                 log.warning('Stenograph reconnected.')
                 self._ready()
         except EOFError:
             # File ended -- will resume normal operation after new file
             self._reset_state()
         else:
             if response is None:
                 continue
             if not self._read_exactly_8 and len(response) == 8:
                 self._read_exactly_8 = True
             content = len(response) > 0
             self._file_offset += len(response)
             if not self._realtime and not content:
                 self._realtime = True
             elif self._realtime and content and self._read_exactly_8:
                 chords = Stenograph.process_steno_packet(response)
                 for keys in chords:
                     if keys:
                         self._on_stroke(keys)
     self._machine.disconnect()
Exemple #5
0
 def start_capture(self):
     """Begin listening for output from the stenotype machine."""
     if not self._connect():
         log.warning('Treal is not connected')
         self._error()
         return
     super(Treal, self).start_capture()
Exemple #6
0
 def start_capture(self):
     self.finished.clear()
     self._initializing()
     """Begin listening for output from the stenotype machine."""
     if not self._connect_machine():
         log.warning('Writer not found. Try clicking refresh.')
         self._error()
     else:
         self._ready()
         self.start()
Exemple #7
0
 def start_capture(self):
     self.finished.clear()
     self._initializing()
     """Begin listening for output from the stenotype machine."""
     if not self._connect_machine():
         log.warning('Stenograph machine is not connected')
         self._error()
     else:
         self._ready()
         self.start()
Exemple #8
0
 def start_capture(self):
     """Begin listening for output from the stenotype machine."""
     try:
         self._machine = hid.device(VENDOR_ID, 1)
         self._machine.set_nonblocking(1)
     except IOError as e:
         log.info('Treal device not found: %s', str(e))
         log.warning('Treal is not connected')
         self._error()
         return
     return ThreadedStenotypeBase.start_capture(self)
Exemple #9
0
 def start_capture(self):
     """Begin listening for output from the stenotype machine."""
     try:
         self._machine = hid.device(VENDOR_ID, 1)
         self._machine.set_nonblocking(1)
     except IOError as e:
         log.info('Treal device not found: %s', str(e))
         log.warning('Treal is not connected')
         self._error()
         return
     return ThreadedStenotypeBase.start_capture(self)
Exemple #10
0
 def _connect_machine(self):
     connected = False
     try:
         connected = self._machine.connect()
     except AssertionError as e:
         log.warning('Error connecting: %s', e)
         self._error()
     except IOError as e:
         log.warning('Lost connection with Stenograph machine: %s', e)
         self._error()
     finally:
         return connected
Exemple #11
0
 def _connect_machine(self):
     connected = False
     try:
         connected = self._machine.connect()
     except ValueError:
         log.warning('Libusb must be installed.')
         self._error()
     except AssertionError as e:
         log.warning('Error connecting: %s', e)
         self._error()
     finally:
         return connected
Exemple #12
0
 def add_dictionary(self, event):
     dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", self.mask, wx.MULTIPLE)
     if dlg.ShowModal() == wx.ID_OK:
         paths = dlg.GetPaths()
         all_dicts = [x.label.GetLabel() for x in self.dictionary_controls]
         for path in paths:
             if not os.path.isfile(path):
                 log.warning('"%s" is not a file.', path)
             elif path in all_dicts:
                 log.warning('Dictionary already added, "%s"', path)
             else:
                 self.add_row(path)
     dlg.Destroy()
Exemple #13
0
 def set_log_file_name(self, config):
     """Set the file name for log output."""
     filename = config.get_log_file_name()
     if not filename:
         return
     if os.path.realpath(filename) == os.path.realpath(log.LOG_FILENAME):
         log.warning('stroke logging must use a different file than %s, '
                     'renaming to %s', log.LOG_FILENAME, conf.DEFAULT_LOG_FILE)
         filename = conf.DEFAULT_LOG_FILE
         config.set_log_file_name(filename)
         with open(config.target_file, 'wb') as f:
             config.save(f)
     log.set_stroke_filename(filename)
Exemple #14
0
 def add_dictionary(self, event):
     dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", self.mask,
                         wx.MULTIPLE)
     if dlg.ShowModal() == wx.ID_OK:
         paths = dlg.GetPaths()
         all_dicts = [x.label.GetLabel() for x in self.dictionary_controls]
         for path in paths:
             if not os.path.isfile(path):
                 log.warning('"%s" is not a file.', path)
             elif path in all_dicts:
                 log.warning('Dictionary already added, "%s"', path)
             else:
                 self.add_row(path)
     dlg.Destroy()
 def _update_image_resource(self, url, data):
     if url not in self._images:
         # Ignore request from a previous document.
         return
     image = QImage.fromData(data)
     if image is None:
         log.warning('could not load image from %s', url)
         return
     doc = self.document()
     doc.addResource(QTextDocument.ImageResource, QUrl(url), image)
     for frag in self._iter_fragments():
         fmt = frag.charFormat()
         if fmt.isImageFormat() and fmt.toImageFormat().name() == url:
             doc.markContentsDirty(frag.position(), frag.length())
Exemple #16
0
 def run(self):
     handler = DataHandler(self._on_stroke)
     self._ready()
     while not self.finished.isSet():
         try:
             packet = self._machine.read(5, 100)
         except IOError:
             self._machine.close()
             log.warning(u'Treal disconnected, reconnecting…')
             if self._reconnect():
                 log.warning('Treal reconnected.')
         else:
             if len(packet) is 5:
                 handler.update(packet)
Exemple #17
0
 def run(self):
     handler = DataHandler(self._on_stroke)
     self._ready()
     while not self.finished.isSet():
         try:
             packet = self._machine.read(5, 100)
         except IOError:
             self._machine.close()
             log.warning(u'Treal disconnected, reconnecting…')
             if self._reconnect():
                 log.warning('Treal reconnected.')
         else:
             if len(packet) is 5:
                 handler.update(packet)
Exemple #18
0
 def set_log_file_name(self, config):
     """Set the file name for log output."""
     filename = config.get_log_file_name()
     if not filename:
         return
     if os.path.realpath(filename) == os.path.realpath(log.LOG_FILENAME):
         log.warning(
             'stroke logging must use a different file than %s, '
             'renaming to %s', log.LOG_FILENAME, conf.DEFAULT_LOG_FILE)
         filename = conf.DEFAULT_LOG_FILE
         config.set_log_file_name(filename)
         with open(config.target_file, 'wb') as f:
             config.save(f)
     log.set_stroke_filename(filename)
Exemple #19
0
def update_engine(engine, config, reset_machine=False):
    """Modify a StenoEngine using a before and after config object.
    
    Using the before and after allows this function to not make unnecessary 
    changes.
    """
    if reset_machine:
        engine.set_machine(None)

    machine_type = config.get_machine_type()
    try:
        machine_class = machine_registry.get(machine_type)
    except NoSuchMachineException as e:
        raise InvalidConfigurationError(unicode(e))
    machine_options = config.get_machine_specific_options(machine_type)
    machine_mappings = config.get_system_keymap(machine_type)
    engine.set_machine(machine_class, machine_options, machine_mappings)

    dictionary_file_names = config.get_dictionary_file_names()
    engine.set_dictionaries(dictionary_file_names)

    log_file_name = config.get_log_file_name()
    if log_file_name:
        # Older versions would use "plover.log" for logging strokes.
        if os.path.realpath(log_file_name) == os.path.realpath(log.LOG_FILENAME):
            log.warning('stroke logging must use a different file than %s, '
                        'renaming to %s', log.LOG_FILENAME, conf.DEFAULT_LOG_FILE)
            log_file_name = conf.DEFAULT_LOG_FILE
            config.set_log_file_name(log_file_name)
            with open(config.target_file, 'wb') as f:
                config.save(f)
    engine.set_log_file_name(log_file_name)

    enable_stroke_logging = config.get_enable_stroke_logging()
    engine.enable_stroke_logging(enable_stroke_logging)

    enable_translation_logging = config.get_enable_translation_logging()
    engine.enable_translation_logging(enable_translation_logging)

    space_placement = config.get_space_placement()
    engine.set_space_placement(space_placement)

    undo_levels = config.get_undo_levels()
    engine.set_undo_levels(undo_levels)

    start_capitalized = config.get_start_capitalized()
    start_attached = config.get_start_attached()
    engine.set_starting_stroke_state(attach=start_attached,
                                     capitalize=start_capitalized)
Exemple #20
0
 def start_capture(self):
     """Begin listening for output from the stenotype machine."""
     try:
         if hasattr(hid.device, 'open'):
             self._machine = hid.device()
             self._machine.open(VENDOR_ID, 1)
         else:
             self._machine = hid.device(VENDOR_ID, 1)
         self._machine.set_nonblocking(0)
     except IOError as e:
         log.info('Treal device not found: %s', str(e))
         log.warning('Treal is not connected')
         self._error()
         return
     super(Stenotype, self).start_capture()
Exemple #21
0
 def set_mappings(self, mappings):
     # When setting from a string, assume a list of mappings:
     # [[action1, [key1, key2]], [action2, [key3]], ...]
     if isinstance(mappings, str):
         mappings = json.loads(mappings)
     mappings = dict(mappings)
     # Set from:
     # { action1: [key1, key2], ... actionn: [keyn] }
     self._mappings = OrderedDict()
     self._bindings = {}
     bound_keys = defaultdict(list)
     errors = []
     for action in self._actions:
         key_list = mappings.get(action)
         if not key_list:
             # Not an issue if 'no-op' is not mapped...
             if action != 'no-op':
                 errors.append('action %s is not bound' % action)
             # Add dummy mapping for each missing action
             # so it's shown in the configurator.
             self._mappings[action] = ()
             continue
         if isinstance(key_list, str):
             key_list = (key_list, )
         valid_key_list = []
         for key in key_list:
             if key not in self._keys:
                 errors.append('invalid key %s bound to action %s' %
                               (key, action))
                 continue
             valid_key_list.append(key)
             bound_keys[key].append(action)
             self._bindings[key] = action
         self._mappings[action] = tuple(
             sorted(valid_key_list, key=self._keys.get))
     for action in (set(mappings) - set(self._actions)):
         key_list = mappings.get(action)
         if isinstance(key_list, str):
             key_list = (key_list, )
         errors.append('invalid action %s mapped to key(s) %s' %
                       (action, ' '.join(key_list)))
     for key, action_list in bound_keys.items():
         if len(action_list) > 1:
             errors.append('key %s is bound multiple times: %s' %
                           (key, str(action_list)))
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' +
                     '\n- '.join(errors))
Exemple #22
0
    def start_capture(self):
        self._close_port()

        try:
            self.serial_port = serial.Serial(**self.serial_params)
        except (serial.SerialException, OSError):
            log.warning('Can\'t open serial port', exc_info=True)
            self._error()
            return

        if not self.serial_port.isOpen():
            log.warning('Serial port is not open: %s', self.serial_params.get('port'))
            self._error()
            return

        return ThreadedStenotypeBase.start_capture(self)
Exemple #23
0
    def start_capture(self):
        self._close_port()

        try:
            self.serial_port = serial.Serial(**self.serial_params)
        except (serial.SerialException, OSError) as e:
            log.warning('Can\'t open Serial port: %s', str(e))
            self._error()
            return

        if not self.serial_port.isOpen():
            log.warning('Serial port is not open: %s', self.serial_params.get('port'))
            self._error()
            return

        return ThreadedStenotypeBase.start_capture(self)
Exemple #24
0
def update_engine(engine, config, reset_machine=False):
    """Modify a StenoEngine using a before and after config object.
    
    Using the before and after allows this function to not make unnecessary 
    changes.
    """
    machine_type = config.get_machine_type()
    try:
        machine_class = machine_registry.get(machine_type)
    except NoSuchMachineException as e:
        raise InvalidConfigurationError(str(e))
    machine_options = config.get_machine_specific_options(machine_type)
    machine_mappings = config.get_system_keymap(machine_type)
    engine.set_machine(machine_class, machine_options, machine_mappings,
                       reset_machine=reset_machine)

    dictionary_file_names = config.get_dictionary_file_names()
    engine.set_dictionaries(dictionary_file_names)

    log_file_name = config.get_log_file_name()
    if log_file_name:
        # Older versions would use "plover.log" for logging strokes.
        if os.path.realpath(log_file_name) == os.path.realpath(log.LOG_FILENAME):
            log.warning('stroke logging must use a different file than %s, '
                        'renaming to %s', log.LOG_FILENAME, conf.DEFAULT_LOG_FILE)
            log_file_name = conf.DEFAULT_LOG_FILE
            config.set_log_file_name(log_file_name)
            with open(config.target_file, 'wb') as f:
                config.save(f)
    engine.set_log_file_name(log_file_name)

    enable_stroke_logging = config.get_enable_stroke_logging()
    engine.enable_stroke_logging(enable_stroke_logging)

    enable_translation_logging = config.get_enable_translation_logging()
    engine.enable_translation_logging(enable_translation_logging)

    space_placement = config.get_space_placement()
    engine.set_space_placement(space_placement)

    undo_levels = config.get_undo_levels()
    engine.set_undo_levels(undo_levels)

    start_capitalized = config.get_start_capitalized()
    start_attached = config.get_start_attached()
    engine.set_starting_stroke_state(attach=start_attached,
                                     capitalize=start_capitalized)
Exemple #25
0
    def run(self):
        class ReadState(object):
            def __init__(self):
                self.realtime = False  # Not realtime until we get a 0-length response
                self.realtime_file_open = False  # We are reading from a file
                self.offset = 0  # File offset to read from

            def reset(self):
                self.__init__()

        state = ReadState()

        while not self.finished.isSet():
            try:
                if not state.realtime_file_open:
                    # Open realtime file
                    self._send_receive(StenoPacket.make_open_request())
                    state.realtime_file_open = True
                response = self._send_receive(
                    StenoPacket.make_read_request(file_offset=state.offset))
            except IOError as e:
                log.warning(u'Stenograph writer disconnected, reconnecting…')
                log.debug('Stenograph exception: %s', e)

                # User could start a new file while disconnected.
                state.reset()
                if self._reconnect():
                    log.warning('Stenograph writer reconnected.')
                    self._ready()
            except NoRealtimeFileException:
                # User hasn't started writing, just keep opening the realtime file
                state.reset()
            except FinishedReadingClosedFileException:
                # File closed! Open the realtime file.
                state.reset()
            else:
                if response.data_length:
                    state.offset += response.data_length
                elif not state.realtime:
                    state.realtime = True
                if response.data_length and state.realtime:
                    for stroke in response.strokes():
                        self._on_stroke(stroke)

        self._machine.disconnect()
Exemple #26
0
        def start_capture(self):
            """Begin listening for output from the stenotype machine."""
            devices = hid.HidDeviceFilter(vendor_id=VENDOR_ID).get_devices()
            if len(devices) == 0:
                log.info('Treal: no devices with vendor id %s', str(VENDOR_ID))
                log.warning('Treal not connected')
                self._error()
                return
            self._machine = devices[0]
            self._machine.open()
            handler = DataHandler(self._notify)

            def callback(p):
                if len(p) != 6: return
                handler.update(p[1:])

            self._machine.set_raw_data_handler(callback)
            self._ready()
Exemple #27
0
        def start_capture(self):
            """Begin listening for output from the stenotype machine."""
            devices = hid.HidDeviceFilter(vendor_id=VENDOR_ID).get_devices()
            if len(devices) == 0:
                log.info('Treal: no devices with vendor id %s', str(VENDOR_ID))
                log.warning('Treal not connected')
                self._error()
                return
            self._machine = devices[0]
            self._machine.open()
            handler = DataHandler(self._notify)

            def callback(p):
                if len(p) != 6: return
                handler.update(p[1:])

            self._machine.set_raw_data_handler(callback)
            self._ready()
Exemple #28
0
    def _update_registry():
        # From MSDN documentation:
        #
        # The hook procedure should process a message in less time than the
        # data entry specified in the LowLevelHooksTimeout value in the
        # following registry key:
        #
        # HKEY_CURRENT_USER\Control Panel\Desktop
        #
        # The value is in milliseconds. If the hook procedure times out, the
        # system passes the message to the next hook. However, on Windows 7 and
        # later, the hook is silently removed without being called. There is no
        # way for the application to know whether the hook is removed.

        def _open_key(rights):
            return winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                  r'Control Panel\Desktop', 0, rights)

        REG_LLHOOK_KEY_FULL_NAME = r'HKEY_CURRENT_USER\Control Panel\Desktop\LowLevelHooksTimeout'
        REG_LLHOOK_KEY_VALUE_NAME = 'LowLevelHooksTimeout'
        REG_LLHOOK_KEY_VALUE_TYPE = winreg.REG_DWORD
        REG_LLHOOK_KEY_VALUE = 5000

        read_key = _open_key(winreg.KEY_READ)
        try:
            value, value_type = winreg.QueryValueEx(read_key,
                                                    REG_LLHOOK_KEY_VALUE_NAME)
        except WindowsError:
            value, value_type = (None, None)

        if value_type != REG_LLHOOK_KEY_VALUE_TYPE or value != REG_LLHOOK_KEY_VALUE:
            try:
                write_key = _open_key(winreg.KEY_WRITE)
                winreg.SetValueEx(write_key, REG_LLHOOK_KEY_VALUE_NAME, 0,
                                  REG_LLHOOK_KEY_VALUE_TYPE,
                                  REG_LLHOOK_KEY_VALUE)
            except WindowsError:
                log.warning(
                    'could not update registry key: %s, see documentation',
                    REG_LLHOOK_KEY_FULL_NAME)
            else:
                log.warning(
                    'the following registry key has been updated, '
                    'you should reboot: %s', REG_LLHOOK_KEY_FULL_NAME)
Exemple #29
0
 def __init__(self, assignments):
     assignments = dict(assignments)
     self.keymap = OrderedDict()
     bound_keys = {}
     # Keep only valid entries, and add missing entries.
     for action, _ in Keymap.DEFAULT:
         keylist = assignments.get(action, ())
         for key in keylist:
             if key in bound_keys:
                 bound_keys[key].append(action)
             else:
                 bound_keys[key] = [action]
         self.keymap[action] = keylist
     errors = []
     for key, action_list in bound_keys.items():
         if len(action_list) > 1:
             errors.append('key %s is bound multiple times: %s' % (key, str(action_list)))
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' + '\n- '.join(errors))
Exemple #30
0
 def set_mappings(self, mappings):
     # When setting from a string, assume a list of mappings:
     # [[action1, [key1, key2]], [action2, [key3]], ...]
     if isinstance(mappings, str):
         mappings = json.loads(mappings)
     mappings = dict(mappings)
     # Set from:
     # { action1: [key1, key2], ... actionn: [keyn] }
     self._mappings = OrderedDict()
     self._bindings = {}
     bound_keys = defaultdict(list)
     errors = []
     for action in self._actions:
         key_list = mappings.get(action)
         if not key_list:
             # Not an issue if 'no-op' is not mapped...
             if action != 'no-op':
                 errors.append('action %s is not bound' % action)
             # Add dummy mapping for each missing action
             # so it's shown in the configurator.
             self._mappings[action] = ()
             continue
         if isinstance(key_list, str):
             key_list = (key_list,)
         valid_key_list = []
         for key in key_list:
             if key not in self._keys:
                 errors.append('invalid key %s bound to action %s' % (key, action))
                 continue
             valid_key_list.append(key)
             bound_keys[key].append(action)
             self._bindings[key] = action
         self._mappings[action] = tuple(sorted(valid_key_list, key=self._keys.get))
     for action in (set(mappings) - set(self._actions)):
         key_list = mappings.get(action)
         if isinstance(key_list, str):
             key_list = (key_list,)
         errors.append('invalid action %s mapped to key(s) %s' % (action, ' '.join(key_list)))
     for key, action_list in bound_keys.items():
         if len(action_list) > 1:
             errors.append('key %s is bound multiple times: %s' % (key, str(action_list)))
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' + '\n- '.join(errors))
Exemple #31
0
    def _update_registry():
        # From MSDN documentation:
        #
        # The hook procedure should process a message in less time than the
        # data entry specified in the LowLevelHooksTimeout value in the
        # following registry key:
        #
        # HKEY_CURRENT_USER\Control Panel\Desktop
        #
        # The value is in milliseconds. If the hook procedure times out, the
        # system passes the message to the next hook. However, on Windows 7 and
        # later, the hook is silently removed without being called. There is no
        # way for the application to know whether the hook is removed.


        def _open_key(rights):
            return winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                  r'Control Panel\Desktop',
                                  0, rights)

        REG_LLHOOK_KEY_FULL_NAME = r'HKEY_CURRENT_USER\Control Panel\Desktop\LowLevelHooksTimeout'
        REG_LLHOOK_KEY_VALUE_NAME = 'LowLevelHooksTimeout'
        REG_LLHOOK_KEY_VALUE_TYPE = winreg.REG_DWORD
        REG_LLHOOK_KEY_VALUE = 5000

        read_key = _open_key(winreg.KEY_READ)
        try:
            value, value_type = winreg.QueryValueEx(read_key, REG_LLHOOK_KEY_VALUE_NAME)
        except WindowsError:
            value, value_type = (None, None)

        if value_type != REG_LLHOOK_KEY_VALUE_TYPE or value != REG_LLHOOK_KEY_VALUE:
            try:
                write_key = _open_key(winreg.KEY_WRITE)
                winreg.SetValueEx(write_key, REG_LLHOOK_KEY_VALUE_NAME, 0,
                                  REG_LLHOOK_KEY_VALUE_TYPE, REG_LLHOOK_KEY_VALUE)
            except WindowsError as e:
                log.warning('could not update registry key: %s, see documentation',
                            REG_LLHOOK_KEY_FULL_NAME)
            else:
                log.warning('the following registry key has been updated, '
                            'you should reboot: %s', REG_LLHOOK_KEY_FULL_NAME)
Exemple #32
0
 def __setitem__(self, action, key_list):
     assert action in self._actions
     if isinstance(key_list, string_types):
         key_list = (key_list,)
     # Delete previous bindings.
     if action in self._mappings:
         for old_key in self._mappings[action]:
             if old_key in self._bindings:
                 del self._bindings[old_key]
     errors = []
     for key in key_list:
         if key not in self._keys:
             errors.append('invalid key %s bound to action %s' % (key, action))
         if key in self._bindings:
             action_list = (action, self._bindings[key])
             errors.append('key %s is bound multiple times: %s' % (key, str(action_list)))
             del self._bindings[key]
         self._bindings[key] = action
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' + '\n- '.join(errors))
Exemple #33
0
    def connect(self):
        """Attempt to connect and return connection"""

        # Disconnect device if it's already connected.
        if self._connected:
            self.disconnect()

        # Find IP of Stenograph machine.
        self._stenograph_address = self.find_stenograph()

        # No IP address = no device found.
        if not self._stenograph_address:
            return self._connected

        # Now create a TCP connection to the found machine's IP address.
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(10)
            sock.connect((self._stenograph_address[0], 80))
            self._sock = sock
            log.warning('Stenograph writer found at IP address: %s!' %
                        self._stenograph_address[0])
        except socket.timeout as e:
            log.warning('Stenograph writer timed out: %s' % e)
        except socket.error as exc:
            log.warning('Stenograph writer binding error: %s' % exc)

        self._connected = True

        return self._connected
def list_plugins():
    working_set = WorkingSet()
    # Make sure user site packages are added
    # to the set so user plugins are listed.
    user_site_packages = site.USER_SITE
    if not running_under_virtualenv() and \
       user_site_packages not in working_set.entries:
        working_set.entry_keys.setdefault(user_site_packages, [])
        working_set.entries.append(user_site_packages)
        for dist in find_distributions(user_site_packages, only=True):
            working_set.add(dist, user_site_packages, replace=True)
    plugins = defaultdict(list)
    for dist in working_set.by_key.values():
        if dist.key == 'plover':
            continue
        for entrypoint_type in dist.get_entry_map().keys():
            if entrypoint_type.startswith('plover.'):
                break
        else:
            continue
        if isinstance(dist, DistInfoDistribution):
            metadata_entry = 'METADATA'
        else:
            # Assume it's an egg distribution...
            metadata_entry = 'PKG-INFO'
        if not dist.has_metadata(metadata_entry):
            log.warning('ignoring distribution (missing metadata): %s', dist)
            continue
        metadata = Metadata()
        metadata.parse(dist.get_metadata(metadata_entry))
        plugin_metadata = PluginMetadata.from_dict({
            attr: getattr(metadata, attr)
            for attr in PluginMetadata._fields
        })
        plugins[dist.key].append(plugin_metadata)
    return {
        name: list(sorted(versions))
        for name, versions in plugins.items()
    }
Exemple #35
0
        def connect(self):
            """Attempt to and return connection"""
            # Disconnect device if it's already connected.
            if self._connected:
                self.disconnect()

            # Find the device by the vendor ID.
            usb_device = core.find(idVendor=VENDOR_ID)
            if not usb_device:  # Device not found
                return self._connected

            # Copy the default configuration.
            try:
                usb_device.set_configuration()
            except core.USBError as e:
                log.warning('Error connecting: %s', e)
                self._error()
            config = usb_device.get_active_configuration()
            interface = config[(0, 0)]

            # Get the write endpoint.
            endpoint_out = util.find_descriptor(
                interface,
                custom_match=lambda e: util.endpoint_direction(
                    e.bEndpointAddress) == util.ENDPOINT_OUT)
            assert endpoint_out is not None, 'cannot find write endpoint'

            # Get the read endpoint.
            endpoint_in = util.find_descriptor(
                interface,
                custom_match=lambda e: util.endpoint_direction(
                    e.bEndpointAddress) == util.ENDPOINT_IN)
            assert endpoint_in is not None, 'cannot find read endpoint'

            self._usb_device = usb_device
            self._endpoint_in = endpoint_in
            self._endpoint_out = endpoint_out
            self._connected = True
            return self._connected
  def _connect(self):
    connected = False

    # Set plover mode to initializing
    self._initializing()

    try:
      # Init the raw pins
      io.setup(self._modeSelectPin, io.IN, pull_up_down = io.PUD_UP)
      io.setup(16, io.IN, pull_up_down = io.PUD_UP)
      io.setup(20, io.IN, pull_up_down = io.PUD_UP)
      io.setup(21, io.IN, pull_up_down = io.PUD_UP)
      io.setup(1, io.IN, pull_up_down = io.PUD_UP)
      io.setup(26, io.IN, pull_up_down = io.PUD_UP)
      io.setup(19, io.IN, pull_up_down = io.PUD_UP)
      io.setup(13, io.IN, pull_up_down = io.PUD_UP)
      io.setup(6, io.IN, pull_up_down = io.PUD_UP)
      io.setup(0, io.IN, pull_up_down = io.PUD_UP)

      # Init the port expander pins
      self._bus = smbus.SMBus(1)
      self._bus.write_byte_data(0x20, 0x0c, 0xff)
      self._bus.write_byte_data(0x20, 0x0d, 0xff)

      # Check if switch on board is set to NKRO
      if io.input(self._modeSelectPin):
        log.warning("NKRO not selected on board. TinyMod4 plugin Disabled.")
        self._error()
        return connected

      self._ready()
      connected = True
      return connected
    except:
      log.warning("Error setting up TinyMod4")
      self._error()

    return connected
Exemple #37
0
 def __setitem__(self, action, key_list):
     assert action in self._actions
     if isinstance(key_list, str):
         key_list = (key_list,)
     # Delete previous bindings.
     if action in self._mappings:
         for old_key in self._mappings[action]:
             if old_key in self._bindings:
                 del self._bindings[old_key]
     errors = []
     valid_key_list = []
     for key in key_list:
         if key not in self._keys:
             errors.append('invalid key %s bound to action %s' % (key, action))
             continue
         if key in self._bindings:
             errors.append('key %s is already bound to: %s' % (key, self._bindings[key]))
             continue
         valid_key_list.append(key)
         self._bindings[key] = action
     self._mappings[action] = tuple(sorted(valid_key_list, key=self._keys.get))
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' + '\n- '.join(errors))
Exemple #38
0
 def __setitem__(self, action, key_list):
     assert action in self._actions
     if isinstance(key_list, string_types):
         key_list = (key_list, )
     # Delete previous bindings.
     if action in self._mappings:
         for old_key in self._mappings[action]:
             if old_key in self._bindings:
                 del self._bindings[old_key]
     errors = []
     for key in key_list:
         if key not in self._keys:
             errors.append('invalid key %s bound to action %s' %
                           (key, action))
         if key in self._bindings:
             action_list = (action, self._bindings[key])
             errors.append('key %s is bound multiple times: %s' %
                           (key, str(action_list)))
             del self._bindings[key]
         self._bindings[key] = action
     if len(errors) > 0:
         log.warning('Keymap is invalid, behavior undefined:\n\n- ' +
                     '\n- '.join(errors))
Exemple #39
0
    def start_capture(self):
        if self.serial_port:
            self.serial_port.close()

        try:
            self.serial_port = serial.Serial(**self.serial_params)
        except (serial.SerialException, OSError) as e:
            log.warning('Stentura not connected')
            log.info('Can\'t open Serial port: %s', str(e))
            self._error()
            return
        if self.serial_port is None:
            log.warning('Serial port not found: %s', str(e))
            self._error()
            return
        if not self.serial_port.isOpen():
            log.warning('Serial port is not open: %s', str(e))
            self._error()
            return

        return ThreadedStenotypeBase.start_capture(self)
Exemple #40
0
    def start_capture(self):
        if self.serial_port:
            self.serial_port.close()

        try:
            self.serial_port = serial.Serial(**self.serial_params)
        except (serial.SerialException, OSError) as e:
            log.warning('Machine not connected')
            log.info('Can\'t open Serial port: %s', str(e))
            self._error()
            return
        if self.serial_port is None:
            log.warning('Serial port not found: %s', str(e))
            self._error()
            return
        if not self.serial_port.isOpen():
            log.warning('Serial port is not open: %s', str(e))
            self._error()
            return

        return ThreadedStenotypeBase.start_capture(self)
Exemple #41
0
import sys
from plover import log


handler = None

try:
    if sys.platform.startswith('linux'):
        from plover.oslayer.log_dbus import DbusNotificationHandler
        handler_class = DbusNotificationHandler
    elif sys.platform.startswith('darwin'):
        from plover.oslayer.log_osx import OSXNotificationHandler
        handler_class = OSXNotificationHandler
except Exception:
    log.warning('could not import platform gui log', exc_info=True)
else:
    try:
        handler = handler_class()
    except Exception:
        log.error('could not initialize platform gui log', exc_info=True)

if handler is None:
    from plover.gui.log_wx import WxNotificationHandler
    handler = WxNotificationHandler()

log.add_handler(handler)
Exemple #42
0
import sys
from plover import log

handler = None

try:
    if sys.platform.startswith('linux'):
        from plover.oslayer.log_dbus import DbusNotificationHandler
        handler_class = DbusNotificationHandler
    elif sys.platform.startswith('darwin'):
        from plover.oslayer.log_osx import OSXNotificationHandler
        handler_class = OSXNotificationHandler
except Exception:
    log.warning('could not import platform gui log', exc_info=True)
else:
    try:
        handler = handler_class()
    except Exception:
        log.error('could not initialize platform gui log', exc_info=True)

if handler is None:
    from plover.gui.log_wx import WxNotificationHandler
    handler = WxNotificationHandler()

log.add_handler(handler)