id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
18,700
utils.py
openstenoproject_plover/plover/gui_qt/utils.py
from PyQt5.QtCore import QSettings from PyQt5.QtGui import QGuiApplication, QKeySequence from PyQt5.QtWidgets import ( QAction, QMainWindow, QToolBar, QToolButton, QWidget, ) from plover import _ def ActionCopyViewSelectionToClipboard(view): def copy_selection_to_clipboard(): indexes = view.selectedIndexes() data = view.model().mimeData(indexes) QGuiApplication.clipboard().setMimeData(data) action = QAction(_('Copy selection to clipboard')) action.setShortcut(QKeySequence(QKeySequence.Copy)) action.triggered.connect(copy_selection_to_clipboard) return action def ToolButton(action): button = QToolButton() button.setDefaultAction(action) return button def ToolBar(*action_list): toolbar = QToolBar() for action in action_list: if action is None: toolbar.addSeparator() else: toolbar.addWidget(ToolButton(action)) return toolbar class WindowState(QWidget): ROLE = None def _save_state(self, settings): pass def save_state(self): assert self.ROLE settings = QSettings() settings.beginGroup(self.ROLE) settings.setValue('geometry', self.saveGeometry()) if isinstance(self, QMainWindow): settings.setValue('state', self.saveState()) self._save_state(settings) settings.endGroup() def _restore_state(self, settings): pass def restore_state(self): assert self.ROLE settings = QSettings() settings.beginGroup(self.ROLE) geometry = settings.value('geometry') if geometry is not None: self.restoreGeometry(geometry) if isinstance(self, QMainWindow): state = settings.value('state') if state is not None: self.restoreState(state) self._restore_state(settings) settings.endGroup() def find_menu_actions(menu): '''Recursively find and return a menu actions.''' actions_dict = {} for action in menu.actions(): name = action.objectName() if not name: sub_menu = action.menu() if sub_menu is None: continue actions_dict.update(find_menu_actions(sub_menu)) name = sub_menu.objectName() assert name assert name not in actions_dict actions_dict[name] = action return actions_dict
2,452
Python
.py
74
25.594595
60
0.6558
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,701
tool.py
openstenoproject_plover/plover/gui_qt/tool.py
from PyQt5.QtWidgets import QDialog from plover.gui_qt.utils import WindowState class Tool(QDialog, WindowState): # Used for dialog window title, menu entry text. TITLE = None # Optional path to icon image. ICON = None # Optional shortcut (as a string). SHORTCUT = None # Note: the class documentation is automatically used as tooltip. def __init__(self, engine): super().__init__() self._update_title() self._engine = engine def _update_title(self): self.setWindowTitle('Plover: ' + self.TITLE) def setupUi(self, widget): super().setupUi(widget) self._update_title()
664
Python
.py
19
28.894737
69
0.66405
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,702
machine_options.py
openstenoproject_plover/plover/gui_qt/machine_options.py
from copy import copy from pathlib import Path from PyQt5.QtCore import Qt, QVariant, pyqtSignal from PyQt5.QtGui import ( QTextCharFormat, QTextFrameFormat, QTextListFormat, QTextCursor, QTextDocument, ) from PyQt5.QtWidgets import ( QGroupBox, QStyledItemDelegate, QStyle, QToolTip, ) from serial import Serial from serial.tools.list_ports import comports from plover import _ from plover.oslayer.serial import patch_ports_info from plover.gui_qt.config_keyboard_widget_ui import Ui_KeyboardWidget from plover.gui_qt.config_serial_widget_ui import Ui_SerialWidget def serial_port_details(port_info): parts = [] global_ignore = {None, 'n/a', Path(port_info.device).name} local_ignore = set(global_ignore) for attr, fmt in ( ('product', _('product: {value}')), ('manufacturer', _('manufacturer: {value}')), ('serial_number', _('serial number: {value}')), ): value = getattr(port_info, attr) if value not in global_ignore: parts.append(fmt.format(value=value)) local_ignore.add(value) description = getattr(port_info, 'description') if description not in local_ignore: parts.insert(0, _('description: {value}').format(value=description)) if not parts: return None return parts class SerialOption(QGroupBox, Ui_SerialWidget): class PortDelegate(QStyledItemDelegate): def __init__(self): super().__init__() self._doc = QTextDocument() doc_margin = self._doc.documentMargin() self._doc.setIndentWidth(doc_margin * 3) background = QToolTip.palette().toolTipBase() foreground = QToolTip.palette().toolTipText() self._device_format = QTextCharFormat() self._details_char_format = QTextCharFormat() self._details_char_format.setFont(QToolTip.font()) self._details_char_format.setBackground(background) self._details_char_format.setForeground(foreground) self._details_frame_format = QTextFrameFormat() self._details_frame_format.setBackground(background) self._details_frame_format.setForeground(foreground) self._details_frame_format.setTopMargin(doc_margin) self._details_frame_format.setBottomMargin(-3 * doc_margin) self._details_frame_format.setBorderStyle(QTextFrameFormat.BorderStyle_Solid) self._details_frame_format.setBorder(doc_margin / 2) self._details_frame_format.setPadding(doc_margin) self._details_list_format = QTextListFormat() self._details_list_format.setStyle(QTextListFormat.ListSquare) def _format_port(self, index): self._doc.clear() cursor = QTextCursor(self._doc) cursor.setCharFormat(self._device_format) port_info = index.data(Qt.UserRole) if port_info is None: cursor.insertText(index.data(Qt.DisplayRole)) return cursor.insertText(port_info.device) details = serial_port_details(port_info) if not details: return cursor.insertFrame(self._details_frame_format) details_list = cursor.createList(self._details_list_format) for n, part in enumerate(details): if n: cursor.insertBlock() cursor.insertText(part, self._details_char_format) def paint(self, painter, option, index): painter.save() if option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.highlight()) text_color = option.palette.highlightedText() else: text_color = option.palette.text() self._device_format.setForeground(text_color) doc_margin = self._doc.documentMargin() self._details_frame_format.setWidth(option.rect.width() - doc_margin * 2) self._format_port(index) painter.translate(option.rect.topLeft()) self._doc.drawContents(painter) painter.restore() def sizeHint(self, option, index): self._format_port(index) return self._doc.size().toSize() valueChanged = pyqtSignal(QVariant) def __init__(self): super().__init__() self.setupUi(self) self.port.setItemDelegate(self.PortDelegate()) self._value = {} def setValue(self, value): self._value = copy(value) self.on_scan() port = value['port'] if port is not None and port != 'None': port_index = self.port.findText(port) if port_index != -1: self.port.setCurrentIndex(port_index) else: self.port.setCurrentText(port) self.baudrate.addItems(map(str, Serial.BAUDRATES)) self.baudrate.setCurrentText(str(value['baudrate'])) self.bytesize.addItems(map(str, Serial.BYTESIZES)) self.bytesize.setCurrentText(str(value['bytesize'])) self.parity.addItems(Serial.PARITIES) self.parity.setCurrentText(value['parity']) self.stopbits.addItems(map(str, Serial.STOPBITS)) self.stopbits.setCurrentText(str(value['stopbits'])) timeout = value['timeout'] if timeout is None: self.use_timeout.setChecked(False) self.timeout.setValue(0.0) self.timeout.setEnabled(False) else: self.use_timeout.setChecked(True) self.timeout.setValue(timeout) self.timeout.setEnabled(True) for setting in ('xonxoff', 'rtscts'): widget = getattr(self, setting) if setting in value: widget.setChecked(value[setting]) else: widget.setEnabled(False) def _update(self, field, value): self._value[field] = value self.valueChanged.emit(self._value) def on_scan(self): self.port.clear() for port_info in sorted(patch_ports_info(comports())): self.port.addItem(port_info.device, port_info) def on_port_changed(self, value): self._update('port', value) def on_baudrate_changed(self, value): self._update('baudrate', int(value)) def on_bytesize_changed(self, value): self._update('baudrate', int(value)) def on_parity_changed(self, value): self._update('parity', value) def on_stopbits_changed(self, value): self._update('stopbits', float(value)) def on_timeout_changed(self, value): self._update('timeout', value) def on_use_timeout_changed(self, value): if value: timeout = self.timeout.value() else: timeout = None self.timeout.setEnabled(value) self._update('timeout', timeout) def on_xonxoff_changed(self, value): self._update('xonxoff', value) def on_rtscts_changed(self, value): self._update('rtscts', value) class KeyboardOption(QGroupBox, Ui_KeyboardWidget): valueChanged = pyqtSignal(QVariant) def __init__(self): super().__init__() self.setupUi(self) self.arpeggiate.setToolTip(_( 'Arpeggiate allows using non-NKRO keyboards.\n' '\n' 'Each key can be pressed separately and the\n' 'space bar is pressed to send the stroke.' )) self._value = {} def setValue(self, value): self._value = copy(value) self.arpeggiate.setChecked(value['arpeggiate']) self.first_up_chord_send.setChecked(value['first_up_chord_send']) def on_arpeggiate_changed(self, value): self._value['arpeggiate'] = value self.valueChanged.emit(self._value) def on_first_up_chord_send_changed(self, value): self._value['first_up_chord_send'] = value self.valueChanged.emit(self._value)
8,031
Python
.py
191
32.408377
89
0.62785
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,703
trayicon.py
openstenoproject_plover/plover/gui_qt/trayicon.py
from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMessageBox, QSystemTrayIcon from plover import _, __name__ as __software_name__ from plover import log from plover.oslayer.config import PLATFORM from plover.machine.base import ( STATE_STOPPED, STATE_INITIALIZING, STATE_RUNNING, STATE_ERROR, ) class TrayIcon(QObject): def __init__(self): super().__init__() self._supported = QSystemTrayIcon.isSystemTrayAvailable() self._context_menu = None self._enabled = False self._trayicon = None self._state_icons = {} for state in ( 'disconnected', 'disabled', 'enabled', ): icon = QIcon(':/state-%s.svg' % state) if hasattr(icon, 'setIsMask'): icon.setIsMask(True) self._state_icons[state] = icon self._machine = None self._machine_state = 'disconnected' self._is_running = False self._update_state() def set_menu(self, menu): self._context_menu = menu if self._enabled: self._trayicon.setContextMenu(menu) def show_message(self, message, icon=QSystemTrayIcon.Information, timeout=10000): self._trayicon.showMessage(__software_name__.capitalize(), message, icon, timeout) def log(self, level, message): if self._enabled: if level <= log.INFO: icon = QSystemTrayIcon.Information timeout = 10 elif level <= log.WARNING: icon = QSystemTrayIcon.Warning timeout = 15 else: icon = QSystemTrayIcon.Critical timeout = 25 self.show_message(message, icon, timeout * 1000) else: if level <= log.INFO: icon = QMessageBox.Information elif level <= log.WARNING: icon = QMessageBox.Warning else: icon = QMessageBox.Critical msgbox = QMessageBox() msgbox.setText(message) msgbox.setIcon(icon) msgbox.exec_() def is_supported(self): return self._supported def enable(self): if not self._supported: return self._trayicon = QSystemTrayIcon() # On OS X, the context menu is activated with either mouse buttons, # and activation messages are still sent, so ignore those... if PLATFORM != 'mac': self._trayicon.activated.connect(self._on_activated) if self._context_menu is not None: self._trayicon.setContextMenu(self._context_menu) self._enabled = True self._update_state() self._trayicon.show() def disable(self): if not self._enabled: return self._trayicon.hide() self._trayicon = None self._enabled = False def is_enabled(self): return self._enabled def update_machine_state(self, machine, state): self._machine = machine self._machine_state = state self._update_state() def update_output(self, enabled): self._is_running = enabled self._update_state() clicked = pyqtSignal() def _update_state(self): if self._machine_state not in (STATE_INITIALIZING, STATE_RUNNING): state = 'disconnected' else: state = 'enabled' if self._is_running else 'disabled' icon = self._state_icons[state] if not self._enabled: return machine_state = _('{machine} is {state}').format( machine=_(self._machine), state=_(self._machine_state), ) if self._is_running: # i18n: Tray icon tooltip. output_state = _('output is enabled') else: # i18n: Tray icon tooltip. output_state = _('output is disabled') self._trayicon.setIcon(icon) self._trayicon.setToolTip( # i18n: Tray icon tooltip. 'Plover:\n- %s\n- %s' % (output_state, machine_state) ) def _on_activated(self, reason): if reason == QSystemTrayIcon.Trigger: self.clicked.emit()
4,359
Python
.py
122
25.540984
75
0.571902
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,704
engine.py
openstenoproject_plover/plover/gui_qt/engine.py
from PyQt5.QtCore import ( QThread, QVariant, pyqtSignal, ) from plover.engine import StenoEngine from plover.oslayer.config import PLATFORM class Engine(StenoEngine, QThread): # Signals. signal_stroked = pyqtSignal(QVariant) signal_translated = pyqtSignal(QVariant, QVariant) signal_machine_state_changed = pyqtSignal(str, str) signal_output_changed = pyqtSignal(bool) signal_config_changed = pyqtSignal(QVariant) signal_dictionaries_loaded = pyqtSignal(QVariant) signal_send_string = pyqtSignal(str) signal_send_backspaces = pyqtSignal(int) signal_send_key_combination = pyqtSignal(str) signal_add_translation = pyqtSignal() signal_focus = pyqtSignal() signal_configure = pyqtSignal() signal_lookup = pyqtSignal() signal_suggestions = pyqtSignal() signal_quit = pyqtSignal() def __init__(self, config, controller, keyboard_emulation): StenoEngine.__init__(self, config, controller, keyboard_emulation) QThread.__init__(self) self._signals = {} for hook in self.HOOKS: signal = getattr(self, 'signal_' + hook) self.hook_connect(hook, signal.emit) self._signals[hook] = signal def _in_engine_thread(self): return self.currentThread() == self def start(self): QThread.start(self) StenoEngine.start(self) def join(self): QThread.wait(self) return self.code def run(self): if PLATFORM == 'mac': import appnope appnope.nope() super().run() def signal_connect(self, name, callback): self._signals[name].connect(callback)
1,682
Python
.py
47
29.12766
74
0.672
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,705
suggestions_widget.py
openstenoproject_plover/plover/gui_qt/suggestions_widget.py
from PyQt5.QtCore import ( QAbstractListModel, QMimeData, QModelIndex, Qt, ) from PyQt5.QtGui import ( QFont, QFontMetrics, QTextCharFormat, QTextCursor, QTextDocument, ) from PyQt5.QtWidgets import ( QListView, QStyle, QStyledItemDelegate, ) from plover import _ from plover.translation import escape_translation from .utils import ActionCopyViewSelectionToClipboard # i18n: Widget: “SuggestionsWidget”. NO_SUGGESTIONS_STRING = _('no suggestions') MAX_SUGGESTIONS_COUNT = 10 class SuggestionsDelegate(QStyledItemDelegate): def __init__(self, parent=None): super().__init__(parent=parent) self._doc = QTextDocument() self._translation_char_format = QTextCharFormat() self._strokes_char_format = QTextCharFormat() self._strokes_char_format.font().setStyleHint(QFont.Monospace) self._size_hint_cache = {} def clear_size_hint_cache(self): self._size_hint_cache.clear() @property def text_font(self): return self._translation_char_format.font() @text_font.setter def text_font(self, font): self._translation_char_format.setFont(font) self.clear_size_hint_cache() @property def strokes_font(self): return self._strokes_char_format.font() @strokes_font.setter def strokes_font(self, font): self._strokes_char_format.setFont(font) self.clear_size_hint_cache() def _format_suggestion(self, index): suggestion = index.data(Qt.DisplayRole) translation = escape_translation(suggestion.text) + ':' if not suggestion.steno_list: translation += ' ' + NO_SUGGESTIONS_STRING return translation, None strokes = '' for strokes_list in suggestion.steno_list[:MAX_SUGGESTIONS_COUNT]: strokes += '\n ' + '/'.join(strokes_list) return translation, strokes def _suggestion_size_hint(self, index): translation, strokes = self._format_suggestion(index) size = QFontMetrics(self.text_font).size(0, translation) if strokes is not None: size += QFontMetrics(self.strokes_font).size(0, strokes) return size def paint(self, painter, option, index): painter.save() if option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.highlight()) text_color = option.palette.highlightedText() else: text_color = option.palette.text() self._translation_char_format.setForeground(text_color) self._strokes_char_format.setForeground(text_color) painter.translate(option.rect.topLeft()) self._doc.clear() cursor = QTextCursor(self._doc) translation, strokes = self._format_suggestion(index) cursor.insertText(translation, self._translation_char_format) if strokes is not None: cursor.insertText(strokes, self._strokes_char_format) self._doc.drawContents(painter) painter.restore() def sizeHint(self, option, index): size = self._size_hint_cache.get(index.row()) if size is not None: return size size = self._suggestion_size_hint(index) self._size_hint_cache[index.row()] = size return size class SuggestionsModel(QAbstractListModel): def __init__(self): super().__init__() self._suggestion_list = [] def rowCount(self, parent): return 0 if parent.isValid() else len(self._suggestion_list) def data(self, index, role): if not index.isValid(): return None suggestion = self._suggestion_list[index.row()] if role == Qt.DisplayRole: return suggestion if role == Qt.AccessibleTextRole: translation = escape_translation(suggestion.text) if suggestion.steno_list: steno = ', '.join('/'.join(strokes_list) for strokes_list in suggestion.steno_list[:MAX_SUGGESTIONS_COUNT]) else: steno = NO_SUGGESTIONS_STRING return translation + ': ' + steno return None def clear(self): self.modelAboutToBeReset.emit() self._suggestion_list.clear() self.modelReset.emit() def extend(self, suggestion_list): row = len(self._suggestion_list) self.beginInsertRows(QModelIndex(), row, row + len(suggestion_list)) self._suggestion_list.extend(suggestion_list) self.endInsertRows() def mimeTypes(self): return ['text/plain'] def mimeData(self, indexes): data = QMimeData() data.setText('\n'.join(filter(None, ( self.data(index, Qt.AccessibleTextRole) for index in indexes )))) return data class SuggestionsWidget(QListView): def __init__(self, parent=None): super().__init__(parent=parent) self.setResizeMode(self.Adjust) self.setSelectionMode(self.ExtendedSelection) self._copy_action = ActionCopyViewSelectionToClipboard(self) self.addAction(self._copy_action) self._model = SuggestionsModel() self._delegate = SuggestionsDelegate(self) self.setModel(self._model) self.setItemDelegate(self._delegate) def append(self, suggestion_list): scrollbar = self.verticalScrollBar() scroll_at_end = scrollbar.value() == scrollbar.maximum() self._model.extend(suggestion_list) if scroll_at_end: self.scrollToBottom() def clear(self): self._model.clear() self._delegate.clear_size_hint_cache() def _reformat(self): self._model.layoutAboutToBeChanged.emit() self._model.layoutChanged.emit() @property def text_font(self): return self._delegate.text_font @text_font.setter def text_font(self, font): self._delegate.text_font = font self._reformat() @property def strokes_font(self): return self._delegate.strokes_font @strokes_font.setter def strokes_font(self, font): self._delegate.strokes_font = font self._reformat()
6,238
Python
.py
165
29.69697
80
0.646669
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,706
dictionary_editor.py
openstenoproject_plover/plover/gui_qt/dictionary_editor.py
from operator import attrgetter, itemgetter from collections import namedtuple from itertools import chain from PyQt5.QtCore import ( QAbstractTableModel, QModelIndex, Qt, ) from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import ( QComboBox, QDialog, QStyledItemDelegate, ) from plover import _ from plover.translation import escape_translation, unescape_translation from plover.misc import expand_path, shorten_path from plover.steno import normalize_steno, steno_to_sort_key from plover.gui_qt.dictionary_editor_ui import Ui_DictionaryEditor from plover.gui_qt.steno_validator import StenoValidator from plover.gui_qt.utils import ToolBar, WindowState _COL_STENO, _COL_TRANS, _COL_DICT, _COL_COUNT = range(3 + 1) class DictionaryItem(namedtuple('DictionaryItem', 'steno translation dictionary')): @property def strokes(self): return normalize_steno(self.steno, strict=False) @property def dictionary_path(self): return self.dictionary.path class DictionaryItemDelegate(QStyledItemDelegate): def __init__(self, dictionary_list): super().__init__() self._dictionary_list = dictionary_list def createEditor(self, parent, option, index): if index.column() == _COL_DICT: dictionary_paths = [ shorten_path(dictionary.path) for dictionary in self._dictionary_list if not dictionary.readonly ] combo = QComboBox(parent) combo.addItems(dictionary_paths) return combo widget = super().createEditor(parent, option, index) if index.column() == _COL_STENO: widget.setValidator(StenoValidator()) return widget class DictionaryItemModel(QAbstractTableModel): def __init__(self, dictionary_list, sort_column, sort_order): super().__init__() self._error_icon = QIcon(':/dictionary_error.svg') self._dictionary_list = dictionary_list self._operations = [] self._entries = [] self._sort_column = sort_column self._sort_order = sort_order self._update_entries() def _update_entries(self, strokes_filter=None, translation_filter=None): self._entries = [] for dictionary in self._dictionary_list: for strokes, translation in dictionary.items(): steno = '/'.join(strokes) if strokes_filter is not None and \ not steno.startswith(strokes_filter): continue if translation_filter is not None and \ not translation.startswith(translation_filter): continue item = DictionaryItem(steno, translation, dictionary) self._entries.append(item) self.sort(self._sort_column, self._sort_order) @property def has_undo(self): return bool(self._operations) @property def modified(self): paths = set() dictionary_list = [] for op_list in self._operations: if not isinstance(op_list, list): op_list = (op_list,) for item in chain(*op_list): if item is None: continue dictionary = item.dictionary if dictionary.path in paths: continue paths.add(dictionary.path) dictionary_list.append(dictionary) return dictionary_list # Note: # - since switching from a dictionary to a table does not enforce the # unicity of keys, a deletion can fail when one of the duplicate has # already been deleted. # - when undoing an operation at the table level, the item may have # been filtered-out and not present def _undo(self, old_item, new_item): if old_item is None: # Undo addition. try: del new_item.dictionary[new_item.strokes] except KeyError: pass try: row = self._entries.index(new_item) except ValueError: # Happen if the item is filtered-out. pass else: self.remove_rows([row], record=False) return if new_item is None: # Undo deletion. self.new_row(0, item=old_item, record=False) return # Undo update. try: del new_item.dictionary[new_item.strokes] except KeyError: pass try: row = self._entries.index(new_item) except ValueError: # Happen if the item is filtered-out, # "create" a new row so the user see # the result of the undo. self.new_row(0, item=old_item, record=False) else: old_item.dictionary[old_item.strokes] = old_item.translation self._entries[row] = old_item self.dataChanged.emit(self.index(row, _COL_STENO), self.index(row, _COL_TRANS)) def undo(self, op=None): op = self._operations.pop() if isinstance(op, list): for old_item, new_item in op: self._undo(old_item, new_item) else: self._undo(*op) def rowCount(self, parent): return 0 if parent.isValid() else len(self._entries) def columnCount(self, parent): return _COL_COUNT def headerData(self, section, orientation, role): if orientation != Qt.Horizontal or role != Qt.DisplayRole: return None if section == _COL_STENO: # i18n: Widget: “DictionaryEditor”. return _('Strokes') if section == _COL_TRANS: # i18n: Widget: “DictionaryEditor”. return _('Translation') if section == _COL_DICT: # i18n: Widget: “DictionaryEditor”. return _('Dictionary') def data(self, index, role): if not index.isValid() or role not in (Qt.EditRole, Qt.DisplayRole, Qt.DecorationRole): return None item = self._entries[index.row()] column = index.column() if role == Qt.DecorationRole: if column == _COL_STENO: try: normalize_steno(item.steno) except ValueError: return self._error_icon return None if column == _COL_STENO: return item.steno if column == _COL_TRANS: return escape_translation(item.translation) if column == _COL_DICT: return shorten_path(item.dictionary.path) def flags(self, index): if not index.isValid(): return Qt.NoItemFlags f = Qt.ItemIsEnabled | Qt.ItemIsSelectable item = self._entries[index.row()] if not item.dictionary.readonly: f |= Qt.ItemIsEditable return f def filter(self, strokes_filter=None, translation_filter=None): self.modelAboutToBeReset.emit() self._update_entries(strokes_filter, translation_filter) self.modelReset.emit() @staticmethod def _item_steno_sort_key(item): return steno_to_sort_key(item[_COL_STENO], strict=False) def sort(self, column, order): self.layoutAboutToBeChanged.emit() if column == _COL_DICT: key = attrgetter('dictionary_path') elif column == _COL_STENO: key = self._item_steno_sort_key else: key = itemgetter(column) self._entries.sort(key=key, reverse=(order == Qt.DescendingOrder)) self._sort_column = column self._sort_order = order self.layoutChanged.emit() def setData(self, index, value, role=Qt.EditRole, record=True): assert role == Qt.EditRole row = index.row() column = index.column() old_item = self._entries[row] strokes = old_item.strokes steno, translation, dictionary = old_item if column == _COL_STENO: strokes = normalize_steno(value.strip(), strict=False) steno = '/'.join(strokes) if not steno or steno == old_item.steno: return False elif column == _COL_TRANS: translation = unescape_translation(value.strip()) if translation == old_item.translation: return False elif column == _COL_DICT: path = expand_path(value) for dictionary in self._dictionary_list: if dictionary.path == path: break if dictionary == old_item.dictionary: return False try: del old_item.dictionary[old_item.strokes] except KeyError: pass if not old_item.strokes and not old_item.translation: # Merge operations when editing a newly added row. if self._operations and self._operations[-1] == [(None, old_item)]: self._operations.pop() old_item = None new_item = DictionaryItem(steno, translation, dictionary) self._entries[row] = new_item dictionary[strokes] = translation if record: self._operations.append((old_item, new_item)) self.dataChanged.emit(index, index) return True def new_row(self, row, item=None, record=True): if item is None: if row == 0 and not self._entries: dictionary = self._dictionary_list[0] else: dictionary = self._entries[row].dictionary item = DictionaryItem('', '', dictionary) self.beginInsertRows(QModelIndex(), row, row) self._entries.insert(row, item) if record: self._operations.append((None, item)) self.endInsertRows() def remove_rows(self, row_list, record=True): assert row_list operations = [] for row in sorted(row_list, reverse=True): self.beginRemoveRows(QModelIndex(), row, row) item = self._entries.pop(row) self.endRemoveRows() try: del item.dictionary[item.strokes] except KeyError: pass else: operations.append((item, None)) if record: self._operations.append(operations) class DictionaryEditor(QDialog, Ui_DictionaryEditor, WindowState): ROLE = 'dictionary_editor' def __init__(self, engine, dictionary_paths): super().__init__() self.setupUi(self) self._engine = engine with engine: dictionary_list = [ dictionary for dictionary in engine.dictionaries.dicts if dictionary.path in dictionary_paths ] sort_column, sort_order = _COL_STENO, Qt.AscendingOrder self._model = DictionaryItemModel(dictionary_list, sort_column, sort_order) self._model.dataChanged.connect(self.on_data_changed) self.table.sortByColumn(sort_column, sort_order) self.table.setSortingEnabled(True) self.table.setModel(self._model) self.table.resizeColumnsToContents() self.table.setItemDelegate(DictionaryItemDelegate(dictionary_list)) self.table.selectionModel().selectionChanged.connect(self.on_selection_changed) background = self.table.palette().highlightedText().color().name() text_color = self.table.palette().highlight().color().name() self.table.setStyleSheet(''' QTableView::item:focus { background-color: %s; color: %s; }''' % (background, text_color)) self.table.setFocus() for action in ( self.action_Undo, self.action_Delete, ): action.setEnabled(False) # Toolbar. self.layout().addWidget(ToolBar( self.action_Undo, self.action_Delete, self.action_New, )) self.strokes_filter.setValidator(StenoValidator()) self.restore_state() self.finished.connect(self.save_state) @property def _selection(self): return list(sorted( index.row() for index in self.table.selectionModel().selectedRows(0) )) def _select(self, row, edit=False): row = min(row, self._model.rowCount(QModelIndex()) - 1) index = self._model.index(row, 0) self.table.setCurrentIndex(index) if edit: self.table.edit(index) def on_data_changed(self, top_left, bottom_right): self.table.setCurrentIndex(top_left) self.action_Undo.setEnabled(self._model.has_undo) def on_selection_changed(self): enabled = bool(self._selection) for action in ( self.action_Delete, ): action.setEnabled(enabled) def on_undo(self): assert self._model.has_undo self._model.undo() self.action_Undo.setEnabled(self._model.has_undo) def on_delete(self): selection = self._selection assert selection self._model.remove_rows(selection) self._select(selection[0]) self.action_Undo.setEnabled(self._model.has_undo) def on_new(self): selection = self._selection if selection: row = self._selection[0] else: row = 0 self.table.reset() self._model.new_row(row) self._select(row, edit=True) self.action_Undo.setEnabled(self._model.has_undo) def on_apply_filter(self): self.table.selectionModel().clear() strokes_filter = '/'.join(normalize_steno(self.strokes_filter.text().strip())) translation_filter = unescape_translation(self.translation_filter.text().strip()) self._model.filter(strokes_filter=strokes_filter, translation_filter=translation_filter) def on_clear_filter(self): self.strokes_filter.setText('') self.translation_filter.setText('') self._model.filter(strokes_filter=None, translation_filter=None) def on_finished(self, result): with self._engine: self._engine.dictionaries.save(dictionary.path for dictionary in self._model.modified)
14,690
Python
.py
368
28.845109
95
0.587295
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,707
steno_validator.py
openstenoproject_plover/plover/gui_qt/steno_validator.py
from PyQt5.QtGui import QValidator from plover.steno import normalize_steno class StenoValidator(QValidator): def validate(self, text, pos): if not text.strip('-/'): state = QValidator.Intermediate else: prefix = text.rstrip('-/') if text == prefix: state = QValidator.Acceptable steno = text else: state = QValidator.Intermediate steno = prefix try: normalize_steno(steno) except ValueError: state = QValidator.Invalid return state, text, pos
644
Python
.py
19
22.368421
47
0.552335
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,708
main_window.py
openstenoproject_plover/plover/gui_qt/main_window.py
from functools import partial import json import os import subprocess from PyQt5.QtCore import QCoreApplication, Qt from PyQt5.QtGui import QCursor, QIcon, QKeySequence from PyQt5.QtWidgets import ( QMainWindow, QMenu, ) from plover import _, log from plover.oslayer import wmctrl from plover.oslayer.config import CONFIG_DIR, PLATFORM from plover.registry import registry from plover.resource import resource_filename from plover.gui_qt.log_qt import NotificationHandler from plover.gui_qt.main_window_ui import Ui_MainWindow from plover.gui_qt.config_window import ConfigWindow from plover.gui_qt.about_dialog import AboutDialog from plover.gui_qt.trayicon import TrayIcon from plover.gui_qt.utils import WindowState, find_menu_actions class MainWindow(QMainWindow, Ui_MainWindow, WindowState): ROLE = 'main' def __init__(self, engine, use_qt_notifications): super().__init__() self.setupUi(self) if hasattr(self, 'setUnifiedTitleAndToolBarOnMac'): self.setUnifiedTitleAndToolBarOnMac(True) self._engine = engine self._active_dialogs = {} self._dialog_class = { 'about' : AboutDialog, 'configuration' : ConfigWindow, } all_actions = find_menu_actions(self.menubar) # Dictionaries. self.dictionaries.add_translation.connect(self._add_translation) self.dictionaries.setup(engine) # Populate edit menu from dictionaries' own. edit_menu = all_actions['menu_Edit'].menu() for action in self.dictionaries.edit_menu.actions(): edit_menu.addAction(action) # Tray icon. self._trayicon = TrayIcon() self._trayicon.enable() self._trayicon.clicked.connect(self._engine.toggle_output) if use_qt_notifications: handler = NotificationHandler() handler.emitSignal.connect(self._trayicon.log) log.add_handler(handler) popup_menu = QMenu() for action_name in ( 'action_ToggleOutput', 'action_Reconnect', '', 'menu_Tools', '', 'action_Configure', 'action_OpenConfigFolder', '', 'menu_Help', '', 'action_Show', 'action_Quit', ): if action_name: popup_menu.addAction(all_actions[action_name]) else: popup_menu.addSeparator() self._trayicon.set_menu(popup_menu) engine.signal_connect('machine_state_changed', self._trayicon.update_machine_state) engine.signal_connect('quit', self.on_quit) self.action_Quit.triggered.connect(engine.quit) # Toolbar popup menu for selecting which tools are shown. self.toolbar_menu = QMenu() self.toolbar.setContextMenuPolicy(Qt.CustomContextMenu) self.toolbar.customContextMenuRequested.connect( lambda: self.toolbar_menu.popup(QCursor.pos()) ) # Populate tools bar/menu. tools_menu = all_actions['menu_Tools'].menu() for tool_plugin in registry.list_plugins('gui.qt.tool'): tool = tool_plugin.obj menu_action = tools_menu.addAction(tool.TITLE) if tool.SHORTCUT is not None: menu_action.setShortcut(QKeySequence.fromString(tool.SHORTCUT)) if tool.ICON is not None: icon = tool.ICON # Internal QT resources start with a `:`. if not icon.startswith(':'): icon = resource_filename(icon) menu_action.setIcon(QIcon(icon)) menu_action.triggered.connect(partial(self._activate_dialog, tool_plugin.name, args=())) toolbar_action = self.toolbar.addAction(menu_action.icon(), menu_action.text()) if tool.__doc__ is not None: toolbar_action.setToolTip(tool.__doc__) toolbar_action.triggered.connect(menu_action.trigger) toggle_action = self.toolbar_menu.addAction(menu_action.icon(), menu_action.text()) toggle_action.setObjectName(tool_plugin.name) toggle_action.setCheckable(True) toggle_action.setChecked(True) toggle_action.toggled.connect(toolbar_action.setVisible) self._dialog_class[tool_plugin.name] = tool engine.signal_connect('output_changed', self.on_output_changed) # Machine. for plugin in registry.list_plugins('machine'): self.machine_type.addItem(_(plugin.name), plugin.name) engine.signal_connect('config_changed', self.on_config_changed) engine.signal_connect('machine_state_changed', lambda machine, state: self.machine_state.setText(state.capitalize()) ) self.restore_state() # Commands. engine.signal_connect('add_translation', partial(self._add_translation, manage_windows=True)) engine.signal_connect('focus', self._focus) engine.signal_connect('configure', partial(self._configure, manage_windows=True)) engine.signal_connect('lookup', partial(self._activate_dialog, 'lookup', manage_windows=True)) engine.signal_connect('suggestions', partial(self._activate_dialog, 'suggestions', manage_windows=True)) # Load the configuration (but do not start the engine yet). if not engine.load_config(): self.on_configure() # Apply configuration settings. config = self._engine.config self._warn_on_hide_to_tray = not config['start_minimized'] self._update_machine(config['machine_type']) self._configured = False self.set_visible(not config['start_minimized']) # Process events before starting the engine # (to avoid display lag at window creation). QCoreApplication.processEvents() # Start the engine. engine.start() def set_visible(self, visible): if visible: self.show() else: if self._trayicon.is_enabled(): self.hide() else: self.showMinimized() def _activate_dialog(self, name, args=(), manage_windows=False): if manage_windows: previous_window = wmctrl.GetForegroundWindow() dialog = self._active_dialogs.get(name) if dialog is None: dialog_class = self._dialog_class[name] dialog = self._active_dialogs[name] = dialog_class(self._engine, *args) dialog.setWindowIcon(self.windowIcon()) def on_finished(): del self._active_dialogs[name] dialog.deleteLater() if manage_windows and previous_window is not None: wmctrl.SetForegroundWindow(previous_window) dialog.finished.connect(on_finished) dialog.showNormal() dialog.activateWindow() dialog.raise_() def _add_translation(self, dictionary=None, manage_windows=False): if not dictionary: dictionary = None self._activate_dialog('add_translation', args=(dictionary,), manage_windows=manage_windows) def _focus(self): self.showNormal() self.activateWindow() self.raise_() def _configure(self, manage_windows=False): self._activate_dialog('configuration', manage_windows=manage_windows) def _lookup(self, manage_windows=False): self._activate_dialog('lookup', manage_windows=manage_windows) def _restore_state(self, settings): if settings.contains('hidden_toolbar_tools'): hidden_toolbar_tools = json.loads(settings.value('hidden_toolbar_tools')) for action in self.toolbar_menu.actions(): action.setChecked(action.objectName() not in hidden_toolbar_tools) def _save_state(self, settings): hidden_toolbar_tools = { action.objectName() for action in self.toolbar_menu.actions() if not action.isChecked() } settings.setValue('hidden_toolbar_tools', json.dumps(list(sorted(hidden_toolbar_tools)))) def _update_machine(self, machine_type): self.machine_type.setCurrentIndex(self.machine_type.findData(machine_type)) def on_config_changed(self, config_update): if 'machine_type' in config_update: self._update_machine(config_update['machine_type']) if not self._configured: self._configured = True if config_update.get('show_suggestions_display', False): self._activate_dialog('suggestions') if config_update.get('show_stroke_display', False): self._activate_dialog('paper_tape') def on_machine_changed(self, machine_index): self._engine.config = { 'machine_type': self.machine_type.itemData(machine_index) } def on_output_changed(self, enabled): self._trayicon.update_output(enabled) self.output_enable.setChecked(enabled) self.output_disable.setChecked(not enabled) self.action_ToggleOutput.setChecked(enabled) def on_toggle_output(self, enabled): self._engine.output = enabled def on_enable_output(self): self.on_toggle_output(True) def on_disable_output(self): self.on_toggle_output(False) def on_configure(self): self._configure() def on_open_config_folder(self): if PLATFORM == 'win': os.startfile(CONFIG_DIR) elif PLATFORM == 'linux': subprocess.call(['xdg-open', CONFIG_DIR]) elif PLATFORM == 'mac': subprocess.call(['open', CONFIG_DIR]) def on_reconnect(self): self._engine.reset_machine() def on_manage_dictionaries(self): self._activate_dialog('dictionary_manager') def on_about(self): self._activate_dialog('about') def on_quit(self): for dialog in list(self._active_dialogs.values()): dialog.close() self.save_state() self._trayicon.disable() self.hide() QCoreApplication.quit() def on_show(self): self._focus() def closeEvent(self, event): event.ignore() self.hide() if not self._trayicon.is_enabled(): self._engine.quit() return if not self._warn_on_hide_to_tray: return self._trayicon.show_message(_('Application is still running.')) self._warn_on_hide_to_tray = False
10,694
Python
.py
243
33.831276
101
0.628023
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,709
dictionaries_widget.py
openstenoproject_plover/plover/gui_qt/dictionaries_widget.py
from contextlib import contextmanager import os from PyQt5.QtCore import ( QAbstractListModel, QModelIndex, Qt, pyqtSignal, ) from PyQt5.QtGui import QCursor, QIcon from PyQt5.QtWidgets import ( QFileDialog, QGroupBox, QMenu, ) from plover import _ from plover.config import DictionaryConfig from plover.dictionary.base import create_dictionary from plover.engine import ErroredDictionary from plover.misc import normalize_path from plover.oslayer.config import CONFIG_DIR from plover.registry import registry from plover.gui_qt.dictionaries_widget_ui import Ui_DictionariesWidget from plover.gui_qt.dictionary_editor import DictionaryEditor from plover.gui_qt.utils import ToolBar def _dictionary_formats(include_readonly=True): return {plugin.name for plugin in registry.list_plugins('dictionary') if include_readonly or not plugin.obj.readonly} def _dictionary_filters(include_readonly=True): formats = sorted(_dictionary_formats(include_readonly=include_readonly)) filters = ['*.' + ext for ext in formats] # i18n: Widget: “DictionariesWidget”, file picker. filters = [_('Dictionaries ({extensions})').format(extensions=' '.join(filters))] filters.extend( # i18n: Widget: “DictionariesWidget”, file picker. _('{format} dictionaries ({extensions})').format( format=ext.strip('.').upper(), extensions='*.' + ext, ) for ext in formats ) return ';; '.join(filters) @contextmanager def _new_dictionary(filename): try: d = create_dictionary(filename, threaded_save=False) yield d d.save() except Exception as e: raise Exception('creating dictionary %s failed. %s' % (filename, e)) from e class DictionariesModel(QAbstractListModel): class DictionaryItem: __slots__ = 'row path enabled short_path _loaded state'.split() def __init__(self, row, config, loaded=None): self.row = row self.path = config.path self.enabled = config.enabled self.short_path = config.short_path self.loaded = loaded @property def loaded(self): return self._loaded @loaded.setter def loaded(self, loaded): if loaded is None: state = 'loading' elif isinstance(loaded, ErroredDictionary): state = 'error' elif loaded.readonly: state = 'readonly' else: state = 'normal' self.state = state self._loaded = loaded @property def config(self): return DictionaryConfig(self.path, self.enabled) @property def is_loaded(self): return self.state not in {'loading', 'error'} SUPPORTED_ROLES = { Qt.AccessibleTextRole, Qt.CheckStateRole, Qt.DecorationRole, Qt.DisplayRole, Qt.ToolTipRole } FLAGS = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled has_undo_changed = pyqtSignal(bool) def __init__(self, engine, icons, max_undo=20): super().__init__() self._engine = engine self._favorite = None self._from_path = {} self._from_row = [] self._reverse_order = False self._undo_stack = [] self._max_undo = max_undo self._icons = icons with engine: config = engine.config engine.signal_connect('config_changed', self._on_config_changed) engine.signal_connect('dictionaries_loaded', self._on_dictionaries_loaded) self._reset_items(config['dictionaries'], config['classic_dictionaries_display_order'], backup=False, publish=False) @property def _config(self): item_list = self._from_row if self._reverse_order: item_list = reversed(item_list) return [item.config for item in item_list] def _updated_rows(self, row_list): for row in row_list: index = self.index(row) self.dataChanged.emit(index, index, self.SUPPORTED_ROLES) def _backup_config(self): config = self._config assert not self._undo_stack or config != self._undo_stack[-1] self._undo_stack.append(config) if len(self._undo_stack) == 1: self.has_undo_changed.emit(True) elif len(self._undo_stack) > self._max_undo: self._undo_stack.pop(0) def _publish_config(self, config): self._engine.config = {'dictionaries': config} def _update_favorite(self): item_list = self._from_row if self._reverse_order: item_list = reversed(item_list) old, new = self._favorite, None for item in item_list: if item.enabled and item.state == 'normal': new = item break if new is old: return set() self._favorite = new return { favorite.row for favorite in filter(None, (old, new)) } def _reset_items(self, config, reverse_order=None, backup=True, publish=True): if backup: self._backup_config() if reverse_order is None: reverse_order = self._reverse_order self.layoutAboutToBeChanged.emit() old_persistent_indexes = self.persistentIndexList() assert all(index.isValid() for index in old_persistent_indexes) old_persistent_items = [ self._from_row[index.row()] for index in old_persistent_indexes ] from_row = [] from_path = {} for row, d in enumerate(reversed(config) if reverse_order else config): item = self._from_path.get(d.path) if item is None: item = self.DictionaryItem(row, d) else: item.row = row item.enabled = d.enabled assert d.path not in from_path from_path[d.path] = item from_row.append(item) self._reverse_order = reverse_order self._from_path = from_path self._from_row = from_row self._update_favorite() new_persistent_indexes = [] for old_item in old_persistent_items: new_item = self._from_path.get(old_item.path) if new_item is None: new_index = QModelIndex() else: new_index = self.index(new_item.row) new_persistent_indexes.append(new_index) self.changePersistentIndexList(old_persistent_indexes, new_persistent_indexes) self.layoutChanged.emit() if publish: self._publish_config(config) def _on_config_changed(self, config_update): config = config_update.get('dictionaries') reverse_order = config_update.get('classic_dictionaries_display_order') noop = True if reverse_order is not None: noop = reverse_order == self._reverse_order if config is not None: noop = noop and config == self._config if noop: return if config is None: config = self._config else: if self._undo_stack: self.has_undo_changed.emit(False) self._undo_stack.clear() self._reset_items(config, reverse_order, backup=False, publish=False) def _on_dictionaries_loaded(self, loaded_dictionaries): updated_rows = set() for item in self._from_row: loaded = loaded_dictionaries.get(item.path) if loaded == item.loaded: continue item.loaded = loaded updated_rows.add(item.row) if not updated_rows: return updated_rows.update(self._update_favorite()) self._updated_rows(updated_rows) def _move(self, index_list, step): row_list = sorted(self._normalized_row_list(index_list)) if not row_list: return old_path_list = [item.path for item in self._from_row] new_path_list = old_path_list[:] if step > 0: row_list = reversed(row_list) row_limit = len(self._from_row) - 1 update_row = min else: row_limit = 0 update_row = max for old_row in row_list: new_row = update_row(old_row + step, row_limit) new_path_list.insert(new_row, new_path_list.pop(old_row)) row_limit = new_row - step if old_path_list == new_path_list: return if self._reverse_order: new_path_list = reversed(new_path_list) config = [ self._from_path[path].config for path in new_path_list ] self._reset_items(config) @staticmethod def _normalized_path_list(path_list): return list(dict.fromkeys(map(normalize_path, path_list))) @staticmethod def _normalized_row_list(index_list): return list(dict.fromkeys(index.row() for index in index_list if index.isValid())) def _insert(self, dest_row, path_list): old_path_list = [item.path for item in self._from_row] new_path_list = ( [p for p in old_path_list[:dest_row] if p not in path_list] + path_list + [p for p in old_path_list[dest_row:] if p not in path_list] ) if new_path_list == old_path_list: return if self._reverse_order: new_path_list = reversed(new_path_list) config = [ self._from_path[path].config if path in self._from_path else DictionaryConfig(path) for path in new_path_list ] self._reset_items(config) def add(self, path_list): new_path_list = self._normalized_path_list( path for path in path_list if path not in self._from_path ) if new_path_list: # Add with highest priority. if self._reverse_order: dest_row = len(self._from_path) new_path_list = reversed(new_path_list) else: dest_row = 0 self._insert(dest_row, new_path_list) elif path_list: # Trigger a reload, just in case. self._engine.config = {} def iter_loaded(self, index_list): row_list = sorted(self._normalized_row_list(index_list)) if self._reverse_order: row_list = reversed(row_list) for row in row_list: item = self._from_row[row] if item.is_loaded: yield item.loaded def insert(self, index, path_list): # Insert at the end if `index` is not valid. row = index.row() if index.isValid() else len(self._from_row) self._insert(row, self._normalized_path_list(path_list)) def move(self, dst_index, src_index_list): self.insert(dst_index, [self._from_row[row].path for row in self._normalized_row_list(src_index_list)]) def move_down(self, index_list): self._move(index_list, +1) def move_up(self, index_list): self._move(index_list, -1) def remove(self, index_list): row_set = self._normalized_row_list(index_list) if not row_set: return config = [item.config for item in self._from_row if item.row not in row_set] self._reset_items(config) def undo(self): config = self._undo_stack.pop() if not self._undo_stack: self.has_undo_changed.emit(False) self._reset_items(config, backup=False) # Model API. def rowCount(self, parent=QModelIndex()): return 0 if parent.isValid() else len(self._from_row) @classmethod def flags(cls, index): return cls.FLAGS if index.isValid() else Qt.NoItemFlags def data(self, index, role): if not index.isValid() or role not in self.SUPPORTED_ROLES: return None d = self._from_row[index.row()] if role == Qt.DisplayRole: return d.short_path if role == Qt.CheckStateRole: return Qt.Checked if d.enabled else Qt.Unchecked if role == Qt.AccessibleTextRole: accessible_text = [d.short_path] if not d.enabled: # i18n: Widget: “DictionariesWidget”, accessible text. accessible_text.append(_('disabled')) if d is self._favorite: # i18n: Widget: “DictionariesWidget”, accessible text. accessible_text.append(_('favorite')) elif d.state == 'error': # i18n: Widget: “DictionariesWidget”, accessible text. accessible_text.append(_('errored: {exception}.').format( exception=str(d.loaded.exception))) elif d.state == 'loading': # i18n: Widget: “DictionariesWidget”, accessible text. accessible_text.append(_('loading')) elif d.state == 'readonly': # i18n: Widget: “DictionariesWidget”, accessible text. accessible_text.append(_('read-only')) return ', '.join(accessible_text) if role == Qt.DecorationRole: return self._icons.get('favorite' if d is self._favorite else d.state) if role == Qt.ToolTipRole: # i18n: Widget: “DictionariesWidget”, tooltip. tooltip = [_('Full path: {path}.').format(path=d.config.path)] if d is self._favorite: # i18n: Widget: “DictionariesWidget”, tool tip. tooltip.append(_('This dictionary is marked as the favorite.')) elif d.state == 'loading': # i18n: Widget: “DictionariesWidget”, tool tip. tooltip.append(_('This dictionary is being loaded.')) elif d.state == 'error': # i18n: Widget: “DictionariesWidget”, tool tip. tooltip.append(_('Loading this dictionary failed: {exception}.') .format(exception=str(d.loaded.exception))) elif d.state == 'readonly': # i18n: Widget: “DictionariesWidget”, tool tip. tooltip.append(_('This dictionary is read-only.')) return '\n\n'.join(tooltip) return None def setData(self, index, value, role): if not index.isValid() or role != Qt.CheckStateRole: return False if value == Qt.Checked: enabled = True elif value == Qt.Unchecked: enabled = False else: return False d = self._from_row[index.row()] if d.enabled == enabled: return False self._backup_config() d.enabled = enabled self._updated_rows({d.row} | self._update_favorite()) self._publish_config(self._config) return True class DictionariesWidget(QGroupBox, Ui_DictionariesWidget): add_translation = pyqtSignal(str) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self._setup = False self._engine = None self._model = None # The save/open/new dialogs will open on that directory. self._file_dialogs_directory = CONFIG_DIR # Start with all actions disabled (until `setup` is called). for action in ( self.action_AddDictionaries, self.action_AddTranslation, self.action_EditDictionaries, self.action_MoveDictionariesDown, self.action_MoveDictionariesUp, self.action_RemoveDictionaries, self.action_SaveDictionaries, self.action_Undo, ): action.setEnabled(False) # Toolbar. self.layout().addWidget(ToolBar( self.action_Undo, None, self.action_EditDictionaries, self.action_RemoveDictionaries, self.action_AddDictionaries, self.action_AddTranslation, None, self.action_MoveDictionariesUp, self.action_MoveDictionariesDown, )) # Add menu. self.menu_AddDictionaries = QMenu(self.action_AddDictionaries.text()) self.menu_AddDictionaries.setIcon(self.action_AddDictionaries.icon()) self.menu_AddDictionaries.addAction(self.action_OpenDictionaries) self.menu_AddDictionaries.addAction(self.action_CreateDictionary) self.action_AddDictionaries.setMenu(self.menu_AddDictionaries) # Save menu. self.menu_SaveDictionaries = QMenu(self.action_SaveDictionaries.text()) self.menu_SaveDictionaries.setIcon(self.action_SaveDictionaries.icon()) self.menu_SaveDictionaries.addAction(self.action_CopyDictionaries) self.menu_SaveDictionaries.addAction(self.action_MergeDictionaries) self.view.dragEnterEvent = self._drag_enter_event self.view.dragMoveEvent = self._drag_move_event self.view.dropEvent = self._drag_drop_event self.setFocusProxy(self.view) # Edit context menu. edit_menu = QMenu() edit_menu.addAction(self.action_Undo) edit_menu.addSeparator() edit_menu.addMenu(self.menu_AddDictionaries) edit_menu.addAction(self.action_EditDictionaries) edit_menu.addMenu(self.menu_SaveDictionaries) edit_menu.addAction(self.action_RemoveDictionaries) edit_menu.addSeparator() edit_menu.addAction(self.action_MoveDictionariesUp) edit_menu.addAction(self.action_MoveDictionariesDown) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect( lambda p: edit_menu.exec_(self.view.mapToGlobal(p))) self.edit_menu = edit_menu def setup(self, engine): assert not self._setup self._engine = engine self._model = DictionariesModel(engine, { name: QIcon(':/dictionary_%s.svg' % name) for name in 'favorite loading error readonly normal'.split() }) self._model.has_undo_changed.connect(self.on_has_undo) self.view.setModel(self._model) self.view.selectionModel().selectionChanged.connect(self.on_selection_changed) for action in ( self.action_AddDictionaries, self.action_AddTranslation, ): action.setEnabled(True) self._setup = True @property def _selected(self): return sorted(self.view.selectedIndexes(), key=lambda index: index.row()) def _drag_accept(self, event): accepted = False if event.source() is self.view: accepted = True elif event.mimeData().hasUrls(): # Only allow a list of supported local files. for url in event.mimeData().urls(): if not url.isLocalFile(): break filename = url.toLocalFile() extension = os.path.splitext(filename)[1].lower()[1:] if extension not in _dictionary_formats(): break else: accepted = True if accepted: event.accept() return accepted def _drag_enter_event(self, event): self._drag_accept(event) def _drag_move_event(self, event): self._drag_accept(event) def _drag_drop_event(self, event): if not self._drag_accept(event): return index = self.view.indexAt(event.pos()) if event.source() == self.view: self._model.move(index, self._selected) else: path_list = [url.toLocalFile() for url in event.mimeData().urls()] self._model.insert(index, path_list) def _get_dictionary_save_name(self, title, default_name=None, default_extensions=(), initial_filename=None): if default_name is not None: # Default to a writable dictionary format. writable_extensions = set(_dictionary_formats(include_readonly=False)) default_name += '.' + next((e for e in default_extensions if e in writable_extensions), 'json') default_name = os.path.join(self._file_dialogs_directory, default_name) else: default_name = self._file_dialogs_directory default_name = normalize_path(default_name) new_filename = QFileDialog.getSaveFileName( parent=self, caption=title, directory=default_name, filter=_dictionary_filters(include_readonly=False), )[0] if not new_filename: return None new_filename = normalize_path(new_filename) self._file_dialogs_directory = os.path.dirname(new_filename) if new_filename == initial_filename: return None return new_filename def _edit_dictionaries(self, index_list): path_list = [d.path for d in self._model.iter_loaded(index_list)] if not path_list: return editor = DictionaryEditor(self._engine, path_list) editor.exec_() def _copy_dictionaries(self, dictionaries): need_reload = False # i18n: Widget: “DictionariesWidget”, “save as copy” file picker. title_template = _('Save a copy of {name} as...') # i18n: Widget: “DictionariesWidget”, “save as copy” file picker. default_name_template = _('{name} - Copy') for original in dictionaries: title = title_template.format(name=os.path.basename(original.path)) name, ext = os.path.splitext(os.path.basename(original.path)) default_name = default_name_template.format(name=name) new_filename = self._get_dictionary_save_name(title, default_name, [ext[1:]], initial_filename=original.path) if new_filename is None: continue with _new_dictionary(new_filename) as copy: copy.update(original) need_reload = True return need_reload def _merge_dictionaries(self, dictionaries): names, exts = zip(*( os.path.splitext(os.path.basename(d.path)) for d in dictionaries)) default_name = ' + '.join(names) default_exts = list(dict.fromkeys(e[1:] for e in exts)) # i18n: Widget: “DictionariesWidget”, “save as merge” file picker. title = _('Merge {names} as...').format(names=default_name) new_filename = self._get_dictionary_save_name(title, default_name, default_exts) if new_filename is None: return False with _new_dictionary(new_filename) as merge: # Merge in reverse priority order, so higher # priority entries overwrite lower ones. for source in reversed(dictionaries): merge.update(source) return True def _save_dictionaries(self, merge=False): # Ignore dictionaries that are not loaded. dictionaries = list(self._model.iter_loaded(self._selected)) if not dictionaries: return if merge: save_fn = self._merge_dictionaries else: save_fn = self._copy_dictionaries if save_fn(dictionaries): # This will trigger a reload of any modified dictionary. self._engine.config = {} def on_open_dictionaries(self): new_filenames = QFileDialog.getOpenFileNames( # i18n: Widget: “DictionariesWidget”, “add” file picker. parent=self, caption=_('Load dictionaries'), directory=self._file_dialogs_directory, filter=_dictionary_filters(), )[0] if not new_filenames: return self._file_dialogs_directory = os.path.dirname(new_filenames[-1]) self._model.add(new_filenames) def on_create_dictionary(self): # i18n: Widget: “DictionariesWidget”, “new” file picker. new_filename = self._get_dictionary_save_name(_('Create dictionary')) if new_filename is None: return with _new_dictionary(new_filename): pass self._model.add([new_filename]) def on_copy_dictionaries(self): self._save_dictionaries() def on_merge_dictionaries(self): self._save_dictionaries(merge=True) def on_activate_dictionary(self, index): self._edit_dictionaries([index]) def on_add_dictionaries(self): self.menu_AddDictionaries.exec_(QCursor.pos()) def on_add_translation(self): dictionary = next(self._model.iter_loaded([self.view.currentIndex()]), None) self.add_translation.emit(None if dictionary is None else dictionary.path) def on_edit_dictionaries(self): self._edit_dictionaries(self._selected) def on_has_undo(self, available): self.action_Undo.setEnabled(available) def on_move_dictionaries_down(self): self._model.move_down(self._selected) def on_move_dictionaries_up(self): self._model.move_up(self._selected) def on_remove_dictionaries(self): self._model.remove(self._selected) def on_selection_changed(self): selection = self._selected has_selection = bool(selection) for widget in ( self.action_RemoveDictionaries, self.action_MoveDictionariesUp, self.action_MoveDictionariesDown, ): widget.setEnabled(has_selection) has_live_selection = next(self._model.iter_loaded(selection), None) is not None for widget in ( self.action_EditDictionaries, self.action_SaveDictionaries, self.menu_SaveDictionaries, ): widget.setEnabled(has_live_selection) def on_undo(self): self._model.undo()
26,436
Python
.py
629
31.166932
98
0.598206
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,710
main.py
openstenoproject_plover/plover/gui_qt/main.py
from pathlib import Path import signal import sys from PyQt5.QtCore import ( QCoreApplication, QLibraryInfo, QTimer, QTranslator, Qt, QtDebugMsg, QtInfoMsg, QtWarningMsg, pyqtRemoveInputHook, qInstallMessageHandler, ) from PyQt5.QtWidgets import QApplication, QMessageBox from plover import _, __name__ as __software_name__, __version__, log from plover.oslayer.config import CONFIG_DIR from plover.oslayer.keyboardcontrol import KeyboardEmulation from plover.gui_qt.engine import Engine # Disable pyqtRemoveInputHook to avoid getting # spammed when using the debugger. pyqtRemoveInputHook() class Application: def __init__(self, config, controller, use_qt_notifications): # This is done dynamically so localization # support can be configure beforehand. from plover.gui_qt.main_window import MainWindow self._app = None self._win = None self._engine = None self._translator = None QCoreApplication.setApplicationName(__software_name__.capitalize()) QCoreApplication.setApplicationVersion(__version__) QCoreApplication.setOrganizationName('Open Steno Project') QCoreApplication.setOrganizationDomain('openstenoproject.org') self._app = QApplication([sys.argv[0], '-name', 'plover']) self._app.setAttribute(Qt.AA_UseHighDpiPixmaps) # Apply custom stylesheet if present. stylesheet_path = Path(CONFIG_DIR) / 'plover.qss' if stylesheet_path.exists(): log.info('using stylesheet at: %s', stylesheet_path) self._app.setStyleSheet(stylesheet_path.read_text()) # Enable localization of standard Qt controls. log.info('setting language to: %s', _.lang) self._translator = QTranslator() translations_dir = QLibraryInfo.location(QLibraryInfo.TranslationsPath) self._translator.load('qtbase_' + _.lang, translations_dir) self._app.installTranslator(self._translator) QApplication.setQuitOnLastWindowClosed(False) self._app.engine = self._engine = Engine(config, controller, KeyboardEmulation()) # On macOS, quitting through the dock will result # in a direct call to `QCoreApplication.quit`. self._app.aboutToQuit.connect(self._app.engine.quit) signal.signal(signal.SIGINT, lambda signum, stack: self._engine.quit()) # Make sure the Python interpreter runs at least every second, # so signals have a chance to be processed. self._timer = QTimer() self._timer.timeout.connect(lambda: None) self._timer.start(1000) self._win = MainWindow(self._engine, use_qt_notifications) def __del__(self): del self._win del self._app del self._engine del self._translator def run(self): self._app.exec_() return self._engine.join() def show_error(title, message): print('%s: %s' % (title, message)) app = QApplication([]) QMessageBox.critical(None, title, message) del app def default_excepthook(*exc_info): log.error('Qt GUI error', exc_info=exc_info) def default_message_handler(msg_type, msg_log_context, msg_string): log_fn = { QtDebugMsg: log.debug, QtInfoMsg: log.info, QtWarningMsg: log.warning, }.get(msg_type, log.error) details = [] if msg_log_context.file is not None: details.append('%s:%u' % (msg_log_context.file, msg_log_context.line)) if msg_log_context.function is not None: details.append(msg_log_context.function) if details: details = ' [%s]' % ', '.join(details) else: details = '' log_fn('Qt: %s%s', msg_string, details) def main(config, controller): # Setup internationalization support. use_qt_notifications = not log.has_platform_handler() # Log GUI exceptions that make it back to the event loop. if sys.excepthook is sys.__excepthook__: sys.excepthook = default_excepthook # Capture and log Qt messages. qInstallMessageHandler(default_message_handler) app = Application(config, controller, use_qt_notifications) code = app.run() del app return code
4,230
Python
.py
104
34.096154
89
0.685944
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,711
config_window.py
openstenoproject_plover/plover/gui_qt/config_window.py
from collections import ChainMap from copy import copy from functools import partial from PyQt5.QtCore import ( Qt, QVariant, pyqtSignal, ) from PyQt5.QtWidgets import ( QCheckBox, QComboBox, QDialog, QDialogButtonBox, QFileDialog, QFormLayout, QFrame, QGroupBox, QLabel, QScrollArea, QSpinBox, QStyledItemDelegate, QTableWidget, QTableWidgetItem, ) from plover import _ from plover.config import MINIMUM_UNDO_LEVELS, MINIMUM_TIME_BETWEEN_KEY_PRESSES from plover.misc import expand_path, shorten_path from plover.registry import registry from plover.gui_qt.config_window_ui import Ui_ConfigWindow from plover.gui_qt.config_file_widget_ui import Ui_FileWidget from plover.gui_qt.utils import WindowState class NopeOption(QLabel): valueChanged = pyqtSignal(bool) def __init__(self): super().__init__() # i18n: Widget: “NopeOption” (empty config option message, # e.g. the machine option when selecting the Treal machine). self.setText(_('Nothing to see here!')) def setValue(self, value): pass class BooleanOption(QCheckBox): valueChanged = pyqtSignal(bool) def __init__(self): super().__init__() self.stateChanged.connect(lambda: self.valueChanged.emit(self.isChecked())) def setValue(self, value): self.setChecked(value) class IntOption(QSpinBox): def __init__(self, maximum=None, minimum=None): super().__init__() if maximum is not None: self.setMaximum(maximum) if minimum is not None: self.setMinimum(minimum) class ChoiceOption(QComboBox): valueChanged = pyqtSignal(str) def __init__(self, choices=None): super().__init__() choices = {} if choices is None else choices for value, label in sorted(choices.items()): self.addItem(label, value) self.activated.connect(self.on_activated) def setValue(self, value): self.setCurrentIndex(self.findData(value)) def on_activated(self, index): self.valueChanged.emit(self.itemData(index)) class FileOption(QGroupBox, Ui_FileWidget): valueChanged = pyqtSignal(str) def __init__(self, dialog_title, dialog_filter): super().__init__() self._dialog_title = dialog_title self._dialog_filter = dialog_filter self.setupUi(self) def setValue(self, value): self.path.setText(shorten_path(value)) def on_browse(self): filename_suggestion = self.path.text() filename = QFileDialog.getSaveFileName( self, self._dialog_title, filename_suggestion, self._dialog_filter, )[0] if not filename: return self.path.setText(shorten_path(filename)) self.valueChanged.emit(filename) def on_path_edited(self): self.valueChanged.emit(expand_path(self.path.text())) class TableOption(QTableWidget): def __init__(self): super().__init__() self.horizontalHeader().setStretchLastSection(True) self.setSelectionMode(self.SingleSelection) self.setTabKeyNavigation(False) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.verticalHeader().hide() self.currentItemChanged.connect(self._on_current_item_changed) def _on_current_item_changed(self, current, previous): # Ensure current item is visible. parent = self.parent() while parent is not None: if isinstance(parent, QScrollArea): row = current.row() pos = self.pos() x = pos.x() y = ( + pos.y() + self.rowViewportPosition(row) + self.rowHeight(row) ) parent.ensureVisible(x, y) return parent = parent.parent() class KeymapOption(TableOption): valueChanged = pyqtSignal(QVariant) class ItemDelegate(QStyledItemDelegate): def __init__(self, action_list): super().__init__() self._action_list = action_list def createEditor(self, parent, option, index): if index.column() == 1: combo = QComboBox(parent) combo.addItem('') combo.addItems(self._action_list) return combo return super().createEditor(parent, option, index) def __init__(self): super().__init__() self._value = [] self._updating = False self.setColumnCount(2) self.setHorizontalHeaderLabels(( # i18n: Widget: “KeymapOption”. _('Key'), # i18n: Widget: “KeymapOption”. _('Action'), )) self.cellChanged.connect(self._on_cell_changed) def setValue(self, value): self._updating = True self._value = copy(value) self.setRowCount(0) if value is not None: row = -1 for key in value.get_keys(): action = value.get_action(key) if action is None: action = '' row += 1 self.insertRow(row) item = QTableWidgetItem(key) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.setItem(row, 0, item) item = QTableWidgetItem(action) self.setItem(row, 1, item) self.resizeColumnsToContents() self.setMinimumSize(self.viewportSizeHint()) self.setItemDelegate(KeymapOption.ItemDelegate(value.get_actions())) self._updating = False def _on_cell_changed(self, row, column): if self._updating: return key = self.item(row, 0).data(Qt.DisplayRole) action = self.item(row, 1).data(Qt.DisplayRole) bindings = self._value.get_bindings() if action: bindings[key] = action else: bindings.pop(key, None) self._value.set_bindings(bindings) self.valueChanged.emit(self._value) class MultipleChoicesOption(TableOption): valueChanged = pyqtSignal(QVariant) LABELS = ( # i18n: Widget: “MultipleChoicesOption”. _('Choice'), # i18n: Widget: “MultipleChoicesOption”. _('Selected'), ) # i18n: Widget: “MultipleChoicesOption”. def __init__(self, choices=None, labels=None): super().__init__() if labels is None: labels = self.LABELS self._value = {} self._updating = False self._choices = {} if choices is None else choices self._reversed_choices = { translation: choice for choice, translation in choices.items() } self.setColumnCount(2) self.setHorizontalHeaderLabels(labels) self.cellChanged.connect(self._on_cell_changed) def setValue(self, value): self._updating = True self.resizeColumnsToContents() self.setMinimumSize(self.viewportSizeHint()) self.setRowCount(0) if value is None: value = set() else: # Don't mutate the original value. value = set(value) self._value = value row = -1 for choice in sorted(self._reversed_choices): row += 1 self.insertRow(row) item = QTableWidgetItem(self._choices[choice]) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.setItem(row, 0, item) item = QTableWidgetItem() item.setFlags((item.flags() & ~Qt.ItemIsEditable) | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Checked if choice in value else Qt.Unchecked) self.setItem(row, 1, item) self.resizeColumnsToContents() self.setMinimumSize(self.viewportSizeHint()) self._updating = False def _on_cell_changed(self, row, column): if self._updating: return assert column == 1 choice = self._reversed_choices[self.item(row, 0).data(Qt.DisplayRole)] if self.item(row, 1).checkState(): self._value.add(choice) else: self._value.discard(choice) self.valueChanged.emit(self._value) class BooleanAsDualChoiceOption(ChoiceOption): valueChanged = pyqtSignal(bool) def __init__(self, choice_false, choice_true): choices = { False: choice_false, True: choice_true } super().__init__(choices) class ConfigOption: def __init__(self, display_name, option_name, widget_class, help_text='', dependents=()): self.display_name = display_name self.option_name = option_name self.help_text = help_text self.widget_class = widget_class self.dependents = dependents self.layout = None self.widget = None self.label = None class ConfigWindow(QDialog, Ui_ConfigWindow, WindowState): ROLE = 'configuration' def __init__(self, engine): super().__init__() self.setupUi(self) self._engine = engine machines = { plugin.name: _(plugin.name) for plugin in registry.list_plugins('machine') } mappings = ( # i18n: Widget: “ConfigWindow”. (_('Interface'), ( ConfigOption(_('Start minimized:'), 'start_minimized', BooleanOption, _('Minimize the main window to systray on startup.')), ConfigOption(_('Show paper tape:'), 'show_stroke_display', BooleanOption, _('Open the paper tape on startup.')), ConfigOption(_('Show suggestions:'), 'show_suggestions_display', BooleanOption, _('Open the suggestions dialog on startup.')), ConfigOption(_('Add translation dialog opacity:'), 'translation_frame_opacity', partial(IntOption, maximum=100, minimum=0), _('Set the translation dialog opacity:\n' '- 0 makes the dialog invisible\n' '- 100 is fully opaque')), ConfigOption(_('Dictionaries display order:'), 'classic_dictionaries_display_order', partial(BooleanAsDualChoiceOption, _('top-down'), _('bottom-up')), _('Set the display order for dictionaries:\n' '- top-down: match the search order; highest priority first\n' '- bottom-up: reverse search order; lowest priority first\n')), )), # i18n: Widget: “ConfigWindow”. (_('Logging'), ( ConfigOption(_('Log file:'), 'log_file_name', partial(FileOption, _('Select a log file'), _('Log files (*.log)')), _('File to use for logging strokes/translations.')), ConfigOption(_('Log strokes:'), 'enable_stroke_logging', BooleanOption, _('Save strokes to the logfile.')), ConfigOption(_('Log translations:'), 'enable_translation_logging', BooleanOption, _('Save translations to the logfile.')), )), # i18n: Widget: “ConfigWindow”. (_('Machine'), ( ConfigOption(_('Machine:'), 'machine_type', partial(ChoiceOption, choices=machines), dependents=( ('machine_specific_options', self._update_machine_options), ('system_keymap', lambda v: self._update_keymap(machine_type=v)), )), ConfigOption(_('Options:'), 'machine_specific_options', self._machine_option), ConfigOption(_('Keymap:'), 'system_keymap', KeymapOption), )), # i18n: Widget: “ConfigWindow”. (_('Output'), ( ConfigOption(_('Enable at start:'), 'auto_start', BooleanOption, _('Enable output on startup.')), ConfigOption(_('Start attached:'), 'start_attached', BooleanOption, _('Disable preceding space on first output.\n' '\n' 'This option is only applicable when spaces are placed before.')), ConfigOption(_('Start capitalized:'), 'start_capitalized', BooleanOption, _('Capitalize the first word.')), ConfigOption(_('Space placement:'), 'space_placement', partial(ChoiceOption, choices={ 'Before Output': _('Before Output'), 'After Output': _('After Output'), }), _('Set automatic space placement: before or after each word.')), ConfigOption(_('Undo levels:'), 'undo_levels', partial(IntOption, maximum=10000, minimum=MINIMUM_UNDO_LEVELS), _('Set how many preceding strokes can be undone.\n' '\n' 'Note: the effective value will take into account the\n' 'dictionaries entry with the maximum number of strokes.')), ConfigOption(_('Key press delay (ms):'), 'time_between_key_presses', partial(IntOption, maximum=100000, minimum=MINIMUM_TIME_BETWEEN_KEY_PRESSES), _('Set the delay between emulated key presses (in milliseconds).\n' '\n' 'Some programs may drop key presses if too many are sent\n' 'within a short period of time. Increasing the delay gives\n' 'programs time to process each key press.\n' 'Setting the delay too high will negatively impact the\n' 'performance of key stroke output.')), )), # i18n: Widget: “ConfigWindow”. (_('Plugins'), ( ConfigOption(_('Extension:'), 'enabled_extensions', partial(MultipleChoicesOption, choices={ plugin.name: plugin.name for plugin in registry.list_plugins('extension') }, labels=(_('Name'), _('Enabled'))), _('Configure enabled plugin extensions.')), )), # i18n: Widget: “ConfigWindow”. (_('System'), ( ConfigOption(_('System:'), 'system_name', partial(ChoiceOption, choices={ plugin.name: plugin.name for plugin in registry.list_plugins('system') }), dependents=( ('system_keymap', lambda v: self._update_keymap(system_name=v)), )), )), ) # Only keep supported options, to avoid messing with things like # dictionaries, that are handled by another (possibly concurrent) # dialog. self._supported_options = set() for section, option_list in mappings: self._supported_options.update(option.option_name for option in option_list) self._update_config() # Create and fill tabs. option_by_name = {} for section, option_list in mappings: layout = QFormLayout() for option in option_list: option_by_name[option.option_name] = option option.layout = layout option.widget = self._create_option_widget(option) option.label = QLabel(option.display_name) option.label.setToolTip(option.help_text) option.label.setBuddy(option.widget) layout.addRow(option.label, option.widget) frame = QFrame() frame.setLayout(layout) frame.setAccessibleName(section) frame.setFocusProxy(option_list[0].widget) scroll_area = QScrollArea() scroll_area.setWidgetResizable(True) scroll_area.setWidget(frame) scroll_area.setFocusProxy(frame) self.tabs.addTab(scroll_area, section) # Update dependents. for option in option_by_name.values(): option.dependents = [ (option_by_name[option_name], update_fn) for option_name, update_fn in option.dependents ] self.buttons.button(QDialogButtonBox.Ok).clicked.connect(self.on_apply) self.buttons.button(QDialogButtonBox.Apply).clicked.connect(self.on_apply) self.tabs.currentWidget().setFocus() self.restore_state() self.finished.connect(self.save_state) def _update_config(self, save=False): with self._engine: if save: self._engine.config = self._config.maps[0] self._config = ChainMap({}, { name: value for name, value in self._engine.config.items() if name in self._supported_options }) def _machine_option(self, *args): machine_options = { plugin.name: plugin.obj for plugin in registry.list_plugins('gui.qt.machine_option') } machine_type = self._config['machine_type'] machine_class = registry.get_plugin('machine', machine_type).obj for klass in machine_class.mro(): # Look for `module_name:class_name` before `class_name`. for name in ( '%s:%s' % (klass.__module__, klass.__name__), klass.__name__, ): opt_class = machine_options.get(name) if opt_class is not None: return opt_class(*args) return NopeOption(*args) def _update_machine_options(self, machine_type=None): return self._engine[('machine_specific_options', machine_type or self._config['machine_type'])] def _update_keymap(self, system_name=None, machine_type=None): return self._engine[('system_keymap', system_name or self._config['system_name'], machine_type or self._config['machine_type'])] def _create_option_widget(self, option): widget = option.widget_class() widget.setToolTip(option.help_text) widget.setAccessibleName(option.display_name) widget.setAccessibleDescription(option.help_text) widget.valueChanged.connect(partial(self.on_option_changed, option)) widget.setValue(self._config[option.option_name]) return widget def keyPressEvent(self, event): # Disable Enter/Return key to trigger "OK". if event.key() in (Qt.Key_Enter, Qt.Key_Return): return super().keyPressEvent(event) def on_option_changed(self, option, value): self._config[option.option_name] = value for dependent, update_fn in option.dependents: # Ensure unsaved changes are discarded. if dependent.option_name in self._config.maps[0]: del self._config.maps[0][dependent.option_name] self._config.maps[1][dependent.option_name] = update_fn(value) widget = self._create_option_widget(dependent) dependent.layout.replaceWidget(dependent.widget, widget) dependent.label.setBuddy(widget) dependent.widget.deleteLater() dependent.widget = widget def on_apply(self): self._update_config(save=True)
20,409
Python
.py
454
31.477974
100
0.557062
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,712
lookup_dialog.py
openstenoproject_plover/plover/gui_qt/lookup_dialog.py
from PyQt5.QtCore import QEvent, Qt from plover import _ from plover.translation import unescape_translation from plover.gui_qt.lookup_dialog_ui import Ui_LookupDialog from plover.gui_qt.tool import Tool class LookupDialog(Tool, Ui_LookupDialog): # i18n: Widget: “LookupDialog”, tooltip. __doc__ = _('Search the dictionary for translations.') TITLE = _('Lookup') ICON = ':/lookup.svg' ROLE = 'lookup' SHORTCUT = 'Ctrl+L' def __init__(self, engine): super().__init__(engine) self.setupUi(self) self.pattern.installEventFilter(self) self.suggestions.installEventFilter(self) self.pattern.setFocus() self.restore_state() self.finished.connect(self.save_state) def eventFilter(self, watched, event): if event.type() == QEvent.KeyPress and \ event.key() in (Qt.Key_Enter, Qt.Key_Return): return True return False def _update_suggestions(self, suggestion_list): self.suggestions.clear() self.suggestions.append(suggestion_list) def on_lookup(self, pattern): translation = unescape_translation(pattern.strip()) suggestion_list = self._engine.get_suggestions(translation) self._update_suggestions(suggestion_list) def changeEvent(self, event): super().changeEvent(event) if event.type() == QEvent.ActivationChange and self.isActiveWindow(): self.pattern.setFocus() self.pattern.selectAll()
1,517
Python
.py
37
33.648649
77
0.675546
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,713
english_stenotype.py
openstenoproject_plover/plover/system/english_stenotype.py
KEYS = ( '#', 'S-', 'T-', 'K-', 'P-', 'W-', 'H-', 'R-', 'A-', 'O-', '*', '-E', '-U', '-F', '-R', '-P', '-B', '-L', '-G', '-T', '-S', '-D', '-Z', ) IMPLICIT_HYPHEN_KEYS = ('A-', 'O-', '-E', '-U', '*') SUFFIX_KEYS = ('-Z', '-D', '-S', '-G') NUMBER_KEY = '#' NUMBERS = { 'S-': '1-', 'T-': '2-', 'P-': '3-', 'H-': '4-', 'A-': '5-', 'O-': '0-', '-F': '-6', '-P': '-7', '-L': '-8', '-T': '-9', } # For RTF/CRE support: # # IV.C.1.iii Number Bar # If the number bar was used in a stroke, the stroke contains a number sign # to indicate that. T͟h͟e͟ ͟n͟u͟m͟b͟e͟r͟ ͟s͟i͟g͟n͟ ͟m͟a͟y͟ ͟b͟e͟ ͟a͟n͟y͟w͟h͟e͟r͟e͟ ͟w͟i͟t͟h͟i͟n͟ ͟t͟h͟e͟ ͟s͟t͟r͟o͟k͟e͟, […] # FERAL_NUMBER_KEY = True UNDO_STROKE_STENO = '*' ORTHOGRAPHY_RULES = [ # == +ly == # artistic + ly = artistically (r'^(.*[aeiou]c) \^ ly$', r'\1ally'), # humble + ly = humbly (*humblely) # questionable +ly = questionably # triple +ly = triply (r'^(.+[aeioubmnp])le \^ ly$', r'\1ly'), # == +ry == # statute + ry = statutory (r'^(.*t)e \^ (ry|ary)$', r'\1ory'), # confirm +tory = confirmatory (*confirmtory) (r'^(.+)m \^ tor(y|ily)$', r'\1mator\2'), # supervise +ary = supervisory (*supervisary) (r'^(.+)se \^ ar(y|ies)$', r'\1sor\2'), # == t +cy == # frequent + cy = frequency (tcy/tecy removal) (r'^(.*[naeiou])te? \^ cy$', r'\1cy'), # == +s == # establish + s = establishes (sibilant pluralization) (r'^(.*(?:s|sh|x|z|zh)) \^ s$', r'\1es'), # speech + s = speeches (soft ch pluralization) (r'^(.*(?:oa|ea|i|ee|oo|au|ou|l|n|(?<![gin]a)r|t)ch) \^ s$', r'\1es'), # cherry + s = cherries (consonant + y pluralization) (r'^(.+[bcdfghjklmnpqrstvwxz])y \^ s$', r'\1ies'), # == y == # die+ing = dying (r'^(.+)ie \^ ing$', r'\1ying'), # metallurgy + ist = metallurgist (r'^(.+[cdfghlmnpr])y \^ ist$', r'\1ist'), # beauty + ful = beautiful (y -> i) (r'^(.+[bcdfghjklmnpqrstvwxz])y \^ ([a-hj-xz].*)$', r'\1i\2'), # == +en == # write + en = written (r'^(.+)te \^ en$', r'\1tten'), # Minessota +en = Minessotan (*Minessotaen) (r'^(.+[ae]) \^ e(n|ns)$', r'\1\2'), # == +ial == # ceremony +ial = ceremonial (*ceremonyial) (r'^(.+)y \^ (ial|ially)$', r'\1\2'), # == +if == # spaghetti +ification = spaghettification (*spaghettiification) (r'^(.+)i \^ if(y|ying|ied|ies|ication|ications)$', r'\1if\2'), # == +ical == # fantastic +ical = fantastical (*fantasticcal) (r'^(.+)ic \^ (ical|ically)$', r'\1\2'), # epistomology +ical = epistomological (r'^(.+)ology \^ ic(al|ally)$', r'\1ologic\2'), # oratory +ical = oratorical (*oratoryical) (r'^(.*)ry \^ ica(l|lly|lity)$', r'\1rica\2'), # == +ist == # radical +ist = radicalist (*radicallist) (r'^(.*[l]) \^ is(t|ts)$', r'\1is\2'), # == +ity == # complementary +ity = complementarity (*complementaryity) (r'^(.*)ry \^ ity$', r'\1rity'), # disproportional +ity = disproportionality (*disproportionallity) (r'^(.*)l \^ ity$', r'\1lity'), # == +ive, +tive == # perform +tive = performative (*performtive) (r'^(.+)rm \^ tiv(e|ity|ities)$', r'\1rmativ\2'), # restore +tive = restorative (r'^(.+)e \^ tiv(e|ity|ities)$', r'\1ativ\2'), # == +ize == # token +ize = tokenize (*tokennize) # token +ise = tokenise (*tokennise) (r'^(.+)y \^ iz(e|es|ing|ed|er|ers|ation|ations|able|ability)$', r'\1iz\2'), (r'^(.+)y \^ is(e|es|ing|ed|er|ers|ation|ations|able|ability)$', r'\1is\2'), # conditional +ize = conditionalize (*conditionallize) (r'^(.+)al \^ iz(e|ed|es|ing|er|ers|ation|ations|m|ms|able|ability|abilities)$', r'\1aliz\2'), (r'^(.+)al \^ is(e|ed|es|ing|er|ers|ation|ations|m|ms|able|ability|abilities)$', r'\1alis\2'), # spectacular +ization = spectacularization (*spectacularrization) (r'^(.+)ar \^ iz(e|ed|es|ing|er|ers|ation|ations|m|ms)$', r'\1ariz\2'), (r'^(.+)ar \^ is(e|ed|es|ing|er|ers|ation|ations|m|ms)$', r'\1aris\2'), # category +ize/+ise = categorize/categorise (*categoryize/*categoryise) # custom +izable/+isable = customizable/customisable (*custommizable/*custommisable) # fantasy +ize = fantasize (*fantasyize) (r'^(.*[lmnty]) \^ iz(e|es|ing|ed|er|ers|ation|ations|m|ms|able|ability|abilities)$', r'\1iz\2'), (r'^(.*[lmnty]) \^ is(e|es|ing|ed|er|ers|ation|ations|m|ms|able|ability|abilities)$', r'\1is\2'), # == +olog == # criminal + ology = criminology # criminal + ologist = criminalogist (*criminallologist) (r'^(.+)al \^ olog(y|ist|ists|ical|ically)$', r'\1olog\2'), # == +ish == # similar +ish = similarish (*similarrish) (r'^(.+)(ar|er|or) \^ ish$', r'\1\2ish'), # free + ed = freed (r'^(.+e)e \^ (e.+)$', r'\1\2'), # narrate + ing = narrating (silent e) (r'^(.+[bcdfghjklmnpqrstuvwxz])e \^ ([aeiouy].*)$', r'\1\2'), # == misc == # defer + ed = deferred (consonant doubling) XXX monitor(stress not on last syllable) (r'^(.*(?:[bcdfghjklmnprstvwxyz]|qu)[aeiou])([bcdfgklmnprtvz]) \^ ([aeiouy].*)$', r'\1\2\2\3'), ] ORTHOGRAPHY_RULES_ALIASES = { 'able': 'ible', 'ability': 'ibility', } ORTHOGRAPHY_WORDLIST = 'american_english_words.txt' KEYMAPS = { 'Gemini PR': { '#' : ('#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8', '#9', '#A', '#B', '#C'), 'S-' : ('S1-', 'S2-'), 'T-' : 'T-', 'K-' : 'K-', 'P-' : 'P-', 'W-' : 'W-', 'H-' : 'H-', 'R-' : 'R-', 'A-' : 'A-', 'O-' : 'O-', '*' : ('*1', '*2', '*3', '*4'), '-E' : '-E', '-U' : '-U', '-F' : '-F', '-R' : '-R', '-P' : '-P', '-B' : '-B', '-L' : '-L', '-G' : '-G', '-T' : '-T', '-S' : '-S', '-D' : '-D', '-Z' : '-Z', 'no-op' : ('Fn', 'pwr', 'res1', 'res2'), }, 'Keyboard': { '#' : ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '='), 'S-' : ('a', 'q'), 'T-' : 'w', 'K-' : 's', 'P-' : 'e', 'W-' : 'd', 'H-' : 'r', 'R-' : 'f', 'A-' : 'c', 'O-' : 'v', '*' : ('t', 'g', 'y', 'h'), '-E' : 'n', '-U' : 'm', '-F' : 'u', '-R' : 'j', '-P' : 'i', '-B' : 'k', '-L' : 'o', '-G' : 'l', '-T' : 'p', '-S' : ';', '-D' : '[', '-Z' : '\'', 'arpeggiate': 'space', # Suppress adjacent keys to prevent miss-strokes. 'no-op' : ('z', 'x', 'b', ',', '.', '/', ']', '\\'), }, 'Passport': { '#' : '#', 'S-' : ('S', 'C'), 'T-' : 'T', 'K-' : 'K', 'P-' : 'P', 'W-' : 'W', 'H-' : 'H', 'R-' : 'R', 'A-' : 'A', 'O-' : 'O', '*' : ('~', '*'), '-E' : 'E', '-U' : 'U', '-F' : 'F', '-R' : 'Q', '-P' : 'N', '-B' : 'B', '-L' : 'L', '-G' : 'G', '-T' : 'Y', '-S' : 'X', '-D' : 'D', '-Z' : 'Z', 'no-op': ('!', '^', '+'), }, 'Stentura': { '#' : '#', 'S-' : 'S-', 'T-' : 'T-', 'K-' : 'K-', 'P-' : 'P-', 'W-' : 'W-', 'H-' : 'H-', 'R-' : 'R-', 'A-' : 'A-', 'O-' : 'O-', '*' : '*', '-E' : '-E', '-U' : '-U', '-F' : '-F', '-R' : '-R', '-P' : '-P', '-B' : '-B', '-L' : '-L', '-G' : '-G', '-T' : '-T', '-S' : '-S', '-D' : '-D', '-Z' : '-Z', 'no-op': '^', }, 'TX Bolt': { '#' : '#', 'S-' : 'S-', 'T-' : 'T-', 'K-' : 'K-', 'P-' : 'P-', 'W-' : 'W-', 'H-' : 'H-', 'R-' : 'R-', 'A-' : 'A-', 'O-' : 'O-', '*' : '*', '-E' : '-E', '-U' : '-U', '-F' : '-F', '-R' : '-R', '-P' : '-P', '-B' : '-B', '-L' : '-L', '-G' : '-G', '-T' : '-T', '-S' : '-S', '-D' : '-D', '-Z' : '-Z', }, 'Treal': { '#' : ('#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8', '#9', '#A', '#B'), 'S-' : ('S1-', 'S2-'), 'T-' : 'T-', 'K-' : 'K-', 'P-' : 'P-', 'W-' : 'W-', 'H-' : 'H-', 'R-' : 'R-', 'A-' : 'A-', 'O-' : 'O-', '*' : ('*1', '*2'), '-E' : '-E', '-U' : '-U', '-F' : '-F', '-R' : '-R', '-P' : '-P', '-B' : '-B', '-L' : '-L', '-G' : '-G', '-T' : '-T', '-S' : '-S', '-D' : '-D', '-Z' : '-Z', 'no-op': ('X1-', 'X2-', 'X3'), }, } DICTIONARIES_ROOT = 'asset:plover:assets' DEFAULT_DICTIONARIES = ('user.json', 'commands.json', 'main.json')
9,557
Python
.py
291
25.907216
126
0.35104
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,714
__init__.py
openstenoproject_plover/plover/system/__init__.py
from collections.abc import Sequence import os import re from plover.oslayer.config import CONFIG_DIR from plover.resource import resource_filename from plover.registry import registry from plover.steno import Stroke def _load_wordlist(filename, assets_dir): if filename is None: return {} path = None for directory in (CONFIG_DIR, assets_dir): if directory is None: continue path = os.path.join(resource_filename(directory), filename) if os.path.exists(path): break else: return {} with open(path, encoding='utf-8') as f: text = f.read() fields = text.split() it = iter(fields) words = dict(zip(it, map(int, it))) assert len(fields) == 2 * len(words), path + ' contains duplicate words.' return words def _key_order(keys, numbers): key_order = {} for order, key in enumerate(keys): key_order[key] = order number_key = numbers.get(key) if number_key is not None: key_order[number_key] = order return key_order def _suffix_keys(keys): assert isinstance(keys, Sequence) return keys _EXPORTS = { 'KEYS' : lambda mod: mod.KEYS, 'KEY_ORDER' : lambda mod: _key_order(mod.KEYS, mod.NUMBERS), 'NUMBER_KEY' : lambda mod: mod.NUMBER_KEY, 'NUMBERS' : lambda mod: dict(mod.NUMBERS), 'FERAL_NUMBER_KEY' : lambda mod: getattr(mod, 'FERAL_NUMBER_KEY', False), 'SUFFIX_KEYS' : lambda mod: _suffix_keys(mod.SUFFIX_KEYS), 'UNDO_STROKE_STENO' : lambda mod: mod.UNDO_STROKE_STENO, 'IMPLICIT_HYPHEN_KEYS' : lambda mod: set(mod.IMPLICIT_HYPHEN_KEYS), 'IMPLICIT_HYPHENS' : lambda mod: {l.replace('-', '') for l in mod.IMPLICIT_HYPHEN_KEYS}, 'ORTHOGRAPHY_WORDS' : lambda mod: _load_wordlist(mod.ORTHOGRAPHY_WORDLIST, mod.DICTIONARIES_ROOT), 'ORTHOGRAPHY_RULES' : lambda mod: [(re.compile(pattern, re.I), replacement) for pattern, replacement in mod.ORTHOGRAPHY_RULES], 'ORTHOGRAPHY_RULES_ALIASES': lambda mod: dict(mod.ORTHOGRAPHY_RULES_ALIASES), 'KEYMAPS' : lambda mod: mod.KEYMAPS, 'DICTIONARIES_ROOT' : lambda mod: mod.DICTIONARIES_ROOT, 'DEFAULT_DICTIONARIES' : lambda mod: mod.DEFAULT_DICTIONARIES, } def setup(system_name): system_symbols = {} system_mod = registry.get_plugin('system', system_name).obj for symbol, init in _EXPORTS.items(): system_symbols[symbol] = init(system_mod) system_symbols['NAME'] = system_name globals().update(system_symbols) Stroke.setup(KEYS, IMPLICIT_HYPHEN_KEYS, NUMBER_KEY, NUMBERS, FERAL_NUMBER_KEY, UNDO_STROKE_STENO) NAME = None
2,872
Python
.py
66
36.80303
109
0.62223
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,715
keyboard.py
openstenoproject_plover/plover/output/keyboard.py
from time import sleep from plover.output import Output class GenericKeyboardEmulation(Output): def __init__(self): super().__init__() self._key_press_delay_ms = 0 def set_key_press_delay(self, delay_ms): self._key_press_delay_ms = delay_ms def delay(self): if self._key_press_delay_ms > 0: sleep(self._key_press_delay_ms / 1000) def half_delay(self): if self._key_press_delay_ms > 0: sleep(self._key_press_delay_ms / 2000) def with_delay(self, iterable): for item in iterable: yield item self.delay()
567
Python
.py
18
26.888889
44
0.673432
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,716
__init__.py
openstenoproject_plover/plover/output/__init__.py
class Output: """Output interface.""" def send_backspaces(self, count): """Output the given number of backspaces.""" raise NotImplementedError() def send_string(self, string): """Output the given string.""" raise NotImplementedError() def send_key_combination(self, combo): """Output a sequence of key combinations. See `plover.key_combo` for the format of the `combo` string. """ raise NotImplementedError() def set_key_press_delay(self, delay_ms): """Sets the delay between outputting key press events.""" raise NotImplementedError()
646
Python
.py
16
32.5
68
0.65
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,717
config.py
openstenoproject_plover/plover/oslayer/config.py
# Copyright (c) 2012 Hesky Fisher # See LICENSE.txt for details. """Platform dependent configuration.""" import os import sys import appdirs if sys.platform.startswith('darwin'): PLATFORM = 'mac' elif sys.platform.startswith('linux'): PLATFORM = 'linux' elif sys.platform.startswith('win'): PLATFORM = 'win' elif sys.platform.startswith(('freebsd', 'openbsd')): PLATFORM = 'bsd' else: PLATFORM = None # If the program's working directory has a plover.cfg file then run in # "portable mode", i.e. store all data in the same directory. This allows # keeping all Plover files in a portable drive. # # Note: the special case when run from an app bundle on macOS. if PLATFORM == 'mac' and '.app/' in os.path.realpath(__file__): PROGRAM_DIR = os.path.abspath(os.path.join(os.path.dirname(sys.executable), *[os.path.pardir] * 3)) else: PROGRAM_DIR = os.getcwd() # Setup configuration directory. CONFIG_BASENAME = 'plover.cfg' if os.path.isfile(os.path.join(PROGRAM_DIR, CONFIG_BASENAME)): CONFIG_DIR = PROGRAM_DIR else: config_directories = [ getattr(appdirs, directory_type)('plover') for directory_type in ('user_config_dir', 'user_data_dir') ] for CONFIG_DIR in config_directories: if os.path.isfile(os.path.join(CONFIG_DIR, CONFIG_BASENAME)): break else: CONFIG_DIR = config_directories[0] CONFIG_FILE = os.path.join(CONFIG_DIR, CONFIG_BASENAME) # Setup plugins directory. PLUGINS_PLATFORM = PLATFORM ASSETS_DIR = os.path.realpath(os.path.join(__file__, '../../assets'))
1,616
Python
.py
44
32.363636
79
0.690339
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,718
controller.py
openstenoproject_plover/plover/oslayer/controller.py
from multiprocessing import connection from threading import Thread import errno import os import tempfile from plover import log from plover.oslayer.config import PLATFORM class Controller: def __init__(self, instance='plover', authkey=b'plover'): if PLATFORM == 'win': self._address = r'\\.\pipe' + '\\' + instance self._family = 'AF_PIPE' else: self._address = os.path.join(tempfile.gettempdir(), instance + '_socket') self._family = 'AF_UNIX' self._authkey = authkey self._listen = None self._thread = None self._message_cb = None @property def is_owner(self): return self._listen is not None def force_cleanup(self): assert not self.is_owner if PLATFORM != 'win' and os.path.exists(self._address): os.unlink(self._address) return True return False def __enter__(self): assert self._listen is None try: self._listen = connection.Listener(self._address, self._family, authkey=self._authkey) except Exception as e: if PLATFORM == 'win': if not isinstance(e, PermissionError): raise else: if not isinstance(e, OSError) or e.errno != errno.EADDRINUSE: raise return self def __exit__(self, exc_type, exc_value, traceback): if self.is_owner: self._listen.close() def _accept(self): conn = self._listen.accept() try: msg = conn.recv() if msg is None: return True self._message_cb(msg) finally: conn.close() return False def _run(self): while True: try: if self._accept(): break except Exception as e: log.error('handling client failed', exc_info=True) def _send_message(self, msg): conn = connection.Client(self._address, self._family, authkey=self._authkey) try: conn.send(msg) finally: conn.close() def send_command(self, command): self._send_message(('command', command)) def start(self, message_cb): assert self.is_owner if self._thread is not None: return self._message_cb = message_cb self._thread = Thread(target=self._run) self._thread.start() def stop(self): assert self.is_owner if self._thread is None: return self._send_message(None) self._thread.join() self._thread = None
2,744
Python
.py
83
22.891566
85
0.550434
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,719
__init__.py
openstenoproject_plover/plover/oslayer/__init__.py
# Copyright (c) 2011 Hesky Fisher. # See LICENSE.txt for details. """This package abstracts os details for plover.""" import os from plover import log from .config import PLATFORM PLATFORM_PACKAGE = { 'bsd' : 'linux', 'linux': 'linux', 'mac' : 'osx', 'win' : 'windows', } def _add_platform_package_to_path(): platform_package = PLATFORM_PACKAGE.get(PLATFORM) if platform_package is None: log.warning('No platform-specific oslayer package for: %s' % PLATFORM) return __path__.insert(0, os.path.join(__path__[0], platform_package)) _add_platform_package_to_path()
617
Python
.py
19
28.736842
78
0.681356
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,720
keyboardlayout.py
openstenoproject_plover/plover/oslayer/osx/keyboardlayout.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: @abarnert, @willwade, and @morinted # Code taken and modified from # <https://github.com/willwade/PyUserInput/blob/master/pykeyboard/mac_keycode.py> # <https://stackoverflow.com/questions/1918841/how-to-convert-ascii-character-to-cgkeycode> from threading import Thread import ctypes import ctypes.util import re import struct import unicodedata from PyObjCTools import AppHelper import AppKit import Foundation from plover import log from plover.key_combo import CHAR_TO_KEYNAME from plover.misc import popcount_8 carbon_path = ctypes.util.find_library('Carbon') carbon = ctypes.cdll.LoadLibrary(carbon_path) CFIndex = ctypes.c_int64 class CFRange(ctypes.Structure): _fields_ = [('loc', CFIndex), ('len', CFIndex)] carbon.TISCopyCurrentKeyboardInputSource.argtypes = [] carbon.TISCopyCurrentKeyboardInputSource.restype = ctypes.c_void_p carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource.argtypes = [] carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource.restype = ctypes.c_void_p carbon.TISGetInputSourceProperty.argtypes = [ctypes.c_void_p, ctypes.c_void_p] carbon.TISGetInputSourceProperty.restype = ctypes.c_void_p carbon.LMGetKbdType.argtypes = [] carbon.LMGetKbdType.restype = ctypes.c_uint32 carbon.CFDataGetLength.argtypes = [ctypes.c_void_p] carbon.CFDataGetLength.restype = ctypes.c_uint64 carbon.CFDataGetBytes.argtypes = [ctypes.c_void_p, CFRange, ctypes.c_void_p] carbon.CFDataGetBytes.restype = None carbon.CFRelease.argtypes = [ctypes.c_void_p] carbon.CFRelease.restype = None kTISPropertyUnicodeKeyLayoutData = ctypes.c_void_p.in_dll( carbon, 'kTISPropertyUnicodeKeyLayoutData') kTISPropertyInputSourceID = ctypes.c_void_p.in_dll( carbon, 'kTISPropertyInputSourceID') kTISPropertyInputSourceIsASCIICapable = ctypes.c_void_p.in_dll( carbon, 'kTISPropertyInputSourceIsASCIICapable') COMMAND = '⌘' SHIFT = '⇧' OPTION = '⌥' CONTROL = '⌃' CAPS = '⇪' UNKNOWN = '?' UNKNOWN_L = '?_L' KEY_CODE_VISUALIZATION = """ ┌───────────────────Layout of Apple Extended Keyboard II───────────────────────┐ │ 53 122 120 99 118 96 97 98 100 101 109 103 111 105 107 113 │ │ │ │ 50─── 18 19 20 21 23 22 26 28 25 29 27 24 ─────51 114 115 116 71 81 75 67 │ │ 48──── 12 13 14 15 17 16 32 34 31 35 33 30 ────42 117 119 121 89 91 92 78 │ │ 57───── 0 1 2 3 5 4 38 40 37 41 39 ──────36 86 87 88 69 │ │ 56────── 6 7 8 9 11 45 46 43 47 44 ───────56 126 83 84 85 76 │ │ 59── 58─ 55─ ──────────49───────── ─55 ──58 ───59 123 125 124 82─── 65 76 │ └──────────────────────────────────────────────────────────────────────────────┘ Valid keycodes not visible on layout: 10, 52, 54, 60-64, 66, 68, 70, 72-74, 77, 79, 80, 90, 93-95, 102, 104, 106, 108, 110, 112, 127 """ SPECIAL_KEY_NAMES = { '\x1b': 'Esc', # Will map both Esc and Clear (key codes 53 and 71) '\xa0': 'nbsp', '\x08': 'Bksp', '\x05': 'Help', '\x01': 'Home', '\x7f': 'Del', '\x04': 'End', '\x0c': 'PgDn', '\x0b': 'PgUp', # \x0b is also the clear character signal } DEFAULT_SEQUENCE = (None, 0), def is_printable(string): for character in string: category = unicodedata.category(character) if category[0] in 'C': # Exception: the "Apple" character that most Mac layouts have return False if string != "" else True elif category == 'Zs' and character != ' ': return False elif category in 'Zl, Zp': return False return True def get_printable_string(s): if s is None: return 'None' return s if is_printable(s) else SPECIAL_KEY_NAMES.setdefault( s, s.encode('unicode_escape').decode("utf-8") ) class KeyboardLayout: def __init__(self, watch_layout=True): self._char_to_key_sequence = None self._key_sequence_to_char = None self._modifier_masks = None self._deadkey_symbol_to_key_sequence = None # Spawn a thread that responds to system keyboard layout changes. if watch_layout: self._watcher = Thread( target=self._layout_watcher, name="LayoutWatcher") self._watcher.start() self._update_layout() def _layout_watcher(self): layout = self class LayoutWatchingCallback(AppKit.NSObject): def layoutChanged_(self, event): log.info('Mac keyboard layout changed, updating') layout._update_layout() center = Foundation.NSDistributedNotificationCenter.defaultCenter() watcher_callback = LayoutWatchingCallback.new() center.addObserver_selector_name_object_suspensionBehavior_( watcher_callback, 'layoutChanged:', 'com.apple.Carbon.TISNotifySelectedKeyboardInputSourceChanged', None, Foundation.NSNotificationSuspensionBehaviorDeliverImmediately ) AppHelper.runConsoleEventLoop(installInterrupt=True) def _update_layout(self): char_to_key_sequence, key_sequence_to_char, modifier_masks = KeyboardLayout._get_layout() self._char_to_key_sequence = char_to_key_sequence self._key_sequence_to_char = key_sequence_to_char self._modifier_masks = modifier_masks self._deadkey_symbol_to_key_sequence = self._deadkeys_by_symbols() def deadkey_symbol_to_key_sequence(self, symbol): return self._deadkey_symbol_to_key_sequence.get(symbol, DEFAULT_SEQUENCE) def key_code_to_char(self, key_code, modifier=0): """Provide a key code and a modifier and it provides the character""" return get_printable_string( self._key_sequence_to_char[key_code, modifier] ) def char_to_key_sequence(self, char): """Finds the key code and modifier sequence for the character""" key_sequence = self._char_to_key_sequence.get(char, DEFAULT_SEQUENCE) if not isinstance(key_sequence[0], tuple): key_sequence = key_sequence, return key_sequence def _deadkeys_by_symbols(self): # We store deadkeys as "characters"; dkX, where X is the symbol. symbols = { '`': '`', '´': '´', '^': ('^', 'ˆ'), '~': ('~', '˜'), '¨': '¨', } deadkeys_by_symbol = {} for symbol, equivalent_symbols in symbols.items(): for equivalent_symbol in equivalent_symbols: sequence = self.char_to_key_sequence('dk%s' % equivalent_symbol) if sequence[0][0] is not None: deadkeys_by_symbol[symbol] = sequence return deadkeys_by_symbol def format_modifier_header(self): modifiers = ( '| {}\t'.format(KeyboardLayout._modifier_string(mod)).expandtabs(8) for mod in sorted(self._modifier_masks.values()) ) header = 'Keycode\t{}'.format(''.join(modifiers)) return '%s\n%s' % (header, re.sub(r'[^|]', '-', header)) def format_keycode_keys(self, keycode): """Returns all the variations of the keycode with modifiers""" keys = ('| {}\t'.format(get_printable_string( self._key_sequence_to_char[keycode, mod])).expandtabs(8) for mod in sorted(self._modifier_masks.values())) return '{}\t{}'.format(keycode, ''.join(keys)).expandtabs(8) @staticmethod def _modifier_dictionary(modifier_mask): """Provide a dictionary of active modifier keys from mod mask""" modifiers = { SHIFT: False, COMMAND: False, CONTROL: False, OPTION: False, CAPS: False, UNKNOWN: False, UNKNOWN_L: False } if modifier_mask & 16: modifiers[CONTROL] = True if modifier_mask & 8: modifiers[OPTION] = True if modifier_mask & 4: modifiers[CAPS] = True if modifier_mask & 2: modifiers[SHIFT] = True if modifier_mask & 1: modifiers[COMMAND] = True return modifiers @staticmethod def _modifier_string(modifier_mask): """Turn modifier mask into string representing modifiers""" s = '' modifiers = KeyboardLayout._modifier_dictionary(modifier_mask) for key in modifiers: s += key if modifiers[key] else '' return s @staticmethod def _get_layout(): keyboard_input_source = carbon.TISCopyCurrentKeyboardInputSource() layout_source = carbon.TISGetInputSourceProperty( keyboard_input_source, kTISPropertyUnicodeKeyLayoutData ) # Some keyboard layouts don't return UnicodeKeyLayoutData so we turn to a different source. if layout_source is None: carbon.CFRelease(keyboard_input_source) keyboard_input_source = carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource() layout_source = carbon.TISGetInputSourceProperty( keyboard_input_source, kTISPropertyUnicodeKeyLayoutData ) layout_size = carbon.CFDataGetLength(layout_source) layout_buffer = ctypes.create_string_buffer(b'\000' * layout_size) carbon.CFDataGetBytes( layout_source, CFRange(0, layout_size), ctypes.byref(layout_buffer) ) keyboard_type = carbon.LMGetKbdType() parsed_layout = KeyboardLayout._parse_layout( layout_buffer, keyboard_type ) carbon.CFRelease(keyboard_input_source) return parsed_layout @staticmethod def _parse_layout(buf, ktype): hf, dv, featureinfo, ktcount = struct.unpack_from('HHII', buf) offset = struct.calcsize('HHII') ktsize = struct.calcsize('IIIIIII') kts = [struct.unpack_from('IIIIIII', buf, offset + ktsize * i) for i in range(ktcount)] for i, kt in enumerate(kts): if kt[0] <= ktype <= kt[1]: kentry = i break else: kentry = 0 ktf, ktl, modoff, charoff, sroff, stoff, seqoff = kts[kentry] # Modifiers mf, deftable, mcount = struct.unpack_from('HHI', buf, modoff) modtableoff = modoff + struct.calcsize('HHI') modtables = struct.unpack_from('B' * mcount, buf, modtableoff) modifier_masks = {} for i, table in enumerate(modtables): modifier_masks.setdefault(table, i) # Sequences sequences = [] if seqoff: sf, scount = struct.unpack_from('HH', buf, seqoff) seqtableoff = seqoff + struct.calcsize('HH') lastoff = -1 for soff in struct.unpack_from('H' * scount, buf, seqtableoff): if lastoff >= 0: sequences.append( buf[seqoff + lastoff:seqoff + soff].decode('utf-16')) lastoff = soff def lookupseq(key): if key >= 0xFFFE: return None if key & 0xC000: seq = key & ~0xC000 if seq < len(sequences): return sequences[seq] return chr(key) # Dead keys deadkeys = [] if sroff: srf, srcount = struct.unpack_from('HH', buf, sroff) srtableoff = sroff + struct.calcsize('HH') for recoff in struct.unpack_from('I' * srcount, buf, srtableoff): cdata, nextstate, ecount, eformat = struct.unpack_from('HHHH', buf, recoff) recdataoff = recoff + struct.calcsize('HHHH') edata = buf[recdataoff:recdataoff + 4 * ecount] deadkeys.append((cdata, nextstate, ecount, eformat, edata)) if stoff: stf, stcount = struct.unpack_from('HH', buf, stoff) sttableoff = stoff + struct.calcsize('HH') dkterms = struct.unpack_from('H' * stcount, buf, sttableoff) else: dkterms = [] # Get char tables char_to_key_sequence = {} key_sequence_to_char = {} deadkey_state_to_key_sequence = {} key_sequence_to_deadkey_state = {} def favored_modifiers(modifier_a, modifier_b): """0 if they are equal, 1 if a is better, -1 if b is better""" a_favored_over_b = 0 modifiers_a = KeyboardLayout._modifier_dictionary(modifier_a) modifiers_b = KeyboardLayout._modifier_dictionary(modifier_b) count_a = popcount_8(modifier_a) count_b = popcount_8(modifier_b) # Favor no CAPS modifier if modifiers_a[CAPS] and not modifiers_b[CAPS]: a_favored_over_b = -1 elif modifiers_b[CAPS] and not modifiers_a[CAPS]: a_favored_over_b = 1 # Favor no command modifier elif modifiers_a[COMMAND] and not modifiers_b[COMMAND]: a_favored_over_b = -1 elif modifiers_b[COMMAND] and not modifiers_a[COMMAND]: a_favored_over_b = 1 # Favor no control modifier elif modifiers_a[CONTROL] and not modifiers_b[CONTROL]: a_favored_over_b = -1 elif modifiers_b[CONTROL] and not modifiers_a[CONTROL]: a_favored_over_b = 1 # Finally, favor fewer modifiers elif count_a > count_b: a_favored_over_b = -1 elif count_b > count_a: a_favored_over_b = 1 return a_favored_over_b def save_shortest_key_sequence(character, new_sequence): current_sequence = char_to_key_sequence.setdefault(character, new_sequence) if current_sequence != new_sequence: # Convert responses to tuples... if not isinstance(current_sequence[0], tuple): current_sequence = current_sequence, if not isinstance(new_sequence[0], tuple): new_sequence = new_sequence, first_current_better = favored_modifiers( current_sequence[-1][1], new_sequence[-1][1] ) last_current_better = favored_modifiers( current_sequence[0][1], new_sequence[0][1] ) # Favor key sequence with best modifiers (avoids a short sequence with awful modifiers) # e.g. ABC Extended wants ¯ from (⌘⌥a,) instead of the saner (⌥a, space) if first_current_better == last_current_better != 0: if first_current_better < 0: char_to_key_sequence[character] = new_sequence # Favor shortest sequence (fewer separate key presses) elif len(current_sequence) < len(new_sequence): pass elif len(new_sequence) < len(current_sequence): char_to_key_sequence[character] = new_sequence[0] # Favor fewer modifiers on last item elif last_current_better < 0: char_to_key_sequence[character] = new_sequence # Favor lower modifiers on first item if last item is the same elif last_current_better == 0 and first_current_better < 0: char_to_key_sequence[character] = new_sequence def lookup_and_add(key, j, mod): ch = lookupseq(key) save_shortest_key_sequence(ch, (j, mod)) key_sequence_to_char[j, mod] = ch cf, csize, ccount = struct.unpack_from('HHI', buf, charoff) chartableoff = charoff + struct.calcsize('HHI') for i, table_offset in enumerate( struct.unpack_from('I' * ccount, buf, chartableoff)): mod = modifier_masks[i] for j, key in enumerate( struct.unpack_from('H' * csize, buf, table_offset)): if key == 65535: key_sequence_to_char[j, mod] = 'mod' elif key >= 0xFFFE: key_sequence_to_char[j, mod] = '<{}>'.format(key) elif key & 0x0C000 == 0x4000: dead = key & ~0xC000 if dead < len(deadkeys): cdata, nextstate, ecount, eformat, edata = deadkeys[dead] if eformat == 0 and nextstate: # Initial: symbols, e.g. `, ~, ^ new_deadkey = (j, mod) current_deadkey = deadkey_state_to_key_sequence.setdefault( nextstate, new_deadkey ) if new_deadkey != current_deadkey: if favored_modifiers(current_deadkey[1], new_deadkey[1]) < 0: deadkey_state_to_key_sequence[nextstate] = new_deadkey if nextstate - 1 < len(dkterms): base_key = lookupseq(dkterms[nextstate - 1]) dead_key_name = 'dk{}'.format(base_key) else: dead_key_name = 'dk#{}'.format(nextstate) key_sequence_to_char[j, mod] = dead_key_name save_shortest_key_sequence(dead_key_name, (j, mod)) elif eformat == 1 or (eformat == 0 and not nextstate): # Terminal: letters, e.g. a, e, o, A, E, O key_sequence_to_deadkey_state[j, mod] = deadkeys[dead] lookup_and_add(cdata, j, mod) elif eformat == 2: # range # TODO! pass else: lookup_and_add(key, j, mod) for key, dead in key_sequence_to_deadkey_state.items(): j, mod = key cdata, nextstate, ecount, eformat, edata = dead entries = [struct.unpack_from('HH', edata, i * 4) for i in range(ecount)] for state, key in entries: # Ignore if unknown state... if state in deadkey_state_to_key_sequence: dj, dmod = deadkey_state_to_key_sequence[state] ch = lookupseq(key) save_shortest_key_sequence(ch, ((dj, dmod), (j, mod))) key_sequence_to_char[(dj, dmod), (j, mod)] = ch char_to_key_sequence['\n'] = (36, 0) char_to_key_sequence['\r'] = (36, 0) char_to_key_sequence['\t'] = (48, 0) return char_to_key_sequence, key_sequence_to_char, modifier_masks if __name__ == '__main__': layout = KeyboardLayout(False) print(KEY_CODE_VISUALIZATION) print() print(layout.format_modifier_header()) for keycode in range(127): print(layout.format_keycode_keys(keycode)) print() unmapped_characters = [] for char, keyname in sorted(CHAR_TO_KEYNAME.items()): sequence = [] for code, mod in layout.char_to_key_sequence(char): if code is not None: sequence.append( (code, '{}{}'.format( layout._modifier_string(mod), layout.key_code_to_char(code, 0) )) ) else: unmapped_characters.append(char) if sequence: print('Name:\t\t{}\nCharacter:\t{}\nSequence:\t‘{}’\nBase codes:\t‘{}’\n'.format( keyname, char, '’, ‘'.join(combo[1] for combo in sequence), '’, ‘'.join(str(combo[0]) for combo in sequence) )) print('No mapping on this layout for characters: ‘{}’'.format( '’, ‘'.join(unmapped_characters) ))
20,759
Python
.py
438
34.420091
103
0.563561
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,721
wmctrl.py
openstenoproject_plover/plover/oslayer/osx/wmctrl.py
from Cocoa import NSWorkspace, NSRunningApplication, NSApplicationActivateIgnoringOtherApps def GetForegroundWindow(): return NSWorkspace.sharedWorkspace().frontmostApplication().processIdentifier() def SetForegroundWindow(pid): target_window = NSRunningApplication.runningApplicationWithProcessIdentifier_(pid) target_window.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
402
Python
.py
6
63.5
91
0.872774
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,722
i18n.py
openstenoproject_plover/plover/oslayer/osx/i18n.py
from AppKit import NSLocale def get_system_language(): lang_list = NSLocale.preferredLanguages() return lang_list[0] if lang_list else None
150
Python
.py
4
34
46
0.770833
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,723
log.py
openstenoproject_plover/plover/oslayer/osx/log.py
import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') NSObject = objc.lookUpClass('NSObject') from plover import log, __name__ as __software_name__ import logging class NotificationHandler(logging.Handler): """ Handler using OS X Notification Center to show messages. """ def __init__(self): super().__init__() self.setLevel(log.WARNING) self.setFormatter(log.NoExceptionTracebackFormatter('%(message)s')) def emit(self, record): # Notification Center has no levels or timeouts. notification = NSUserNotification.alloc().init() notification.setTitle_(record.levelname.title()) notification.setInformativeText_(self.format(record)) ns = NSUserNotificationCenter.defaultUserNotificationCenter() ns.setDelegate_(always_present_delegator) ns.deliverNotification_(notification) class AlwaysPresentNSDelegator(NSObject): """ Custom delegator to force presenting even if Plover is in the foreground. """ def userNotificationCenter_didActivateNotification_(self, ns, note): # Do nothing return def userNotificationCenter_shouldPresentNotification_(self, ns, note): # Force notification, even if frontmost application. return True always_present_delegator = AlwaysPresentNSDelegator.alloc().init()
1,434
Python
.py
31
40.258065
77
0.740661
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,724
keyboardcontrol.py
openstenoproject_plover/plover/oslayer/osx/keyboardcontrol.py
# coding: utf-8 import threading from time import sleep from queue import Queue from Quartz import ( CFMachPortCreateRunLoopSource, CFMachPortInvalidate, CFRunLoopAddSource, CFRunLoopSourceInvalidate, CFRunLoopGetCurrent, CFRunLoopRun, CFRunLoopStop, CFRelease, CGEventCreateKeyboardEvent, CGEventGetFlags, CGEventGetIntegerValueField, CGEventKeyboardSetUnicodeString, CGEventMaskBit, CGEventPost, CGEventSetFlags, CGEventSourceCreate, CGEventTapCreate, CGEventTapEnable, kCFRunLoopCommonModes, kCGEventFlagMaskAlternate, kCGEventFlagMaskCommand, kCGEventFlagMaskControl, kCGEventFlagMaskNonCoalesced, kCGEventFlagMaskNumericPad, kCGEventFlagMaskSecondaryFn, kCGEventFlagMaskShift, kCGEventKeyDown, kCGEventKeyUp, kCGEventTapDisabledByTimeout, kCGEventTapOptionDefault, kCGHeadInsertEventTap, kCGKeyboardEventKeycode, kCGSessionEventTap, kCGEventSourceStateHIDSystemState, NSEvent, NSSystemDefined, ) from plover import log from plover.key_combo import add_modifiers_aliases, parse_key_combo, KEYNAME_TO_CHAR from plover.machine.keyboard_capture import Capture from plover.output.keyboard import GenericKeyboardEmulation from .keyboardlayout import KeyboardLayout BACK_SPACE = 51 NX_KEY_OFFSET = 65536 NX_KEYS = { "AudioRaiseVolume": 0, "AudioLowerVolume": 1, "MonBrightnessUp": 2, "MonBrightnessDown": 3, "AudioMute": 7, "Num_Lock": 10, "Eject": 14, "AudioPause": 16, "AudioPlay": 16, "AudioNext": 17, "AudioPrev": 18, "AudioRewind": 20, "KbdBrightnessUp": 21, "KbdBrightnessDown": 22 } KEYNAME_TO_KEYCODE = { 'fn': 63, 'alt_l': 58, 'alt_r': 61, 'control_l': 59, 'control_r': 62, 'shift_l': 56, 'shift_r': 60, 'super_l': 55, 'super_r': 55, 'caps_lock': 57, 'return': 36, 'tab': 48, 'backspace': BACK_SPACE, 'delete': 117, 'escape': 53, 'clear': 71, 'up': 126, 'down': 125, 'left': 123, 'right': 124, 'page_up': 116, 'page_down': 121, 'home': 115, 'end': 119, 'f1': 122, 'f2': 120, 'f3': 99, 'f4': 118, 'f5': 96, 'f6': 97, 'f7': 98, 'f8': 100, 'f9': 101, 'f10': 109, 'f11': 103, 'f12': 111, 'f13': 105, 'f14': 107, 'f15': 113, 'f16': 106, 'f17': 64, 'f18': 79, 'f19': 80, 'f20': 90, 'kp_0': 82, 'kp_1': 83, 'kp_2': 84, 'kp_3': 85, 'kp_4': 86, 'kp_5': 87, 'kp_6': 88, 'kp_7': 89, 'kp_8': 91, 'kp_9': 92, 'kp_add': 69, 'kp_decimal': 65, 'kp_delete': 71, 'kp_divide': 75, 'kp_enter': 76, 'kp_equal': 81, 'kp_multiply': 67, 'kp_subtract': 78, } for name, code in NX_KEYS.items(): KEYNAME_TO_KEYCODE[name.lower()] = code + NX_KEY_OFFSET add_modifiers_aliases(KEYNAME_TO_KEYCODE) DEADKEY_SYMBOLS = { 'dead_acute': '´', 'dead_circumflex': '^', 'dead_diaeresis': '¨', 'dead_grave': '`', 'dead_tilde': '~', } def down(seq): return [(x, True) for x in seq] def up(seq): return [(x, False) for x in reversed(seq)] def down_up(seq): return down(seq) + up(seq) # Maps from keycodes to corresponding event masks. MODIFIER_KEYS_TO_MASKS = { 58: kCGEventFlagMaskAlternate, 61: kCGEventFlagMaskAlternate, # As of Sierra we *require* secondary fn to get control to work properly. 59: kCGEventFlagMaskControl, 62: kCGEventFlagMaskControl, 56: kCGEventFlagMaskShift, 60: kCGEventFlagMaskShift, 55: kCGEventFlagMaskCommand, 63: kCGEventFlagMaskSecondaryFn, } OUTPUT_SOURCE = CGEventSourceCreate(kCGEventSourceStateHIDSystemState) # For the purposes of this class, we're only watching these keys. # We could calculate the keys, but our default layout would be misleading: # # KEYCODE_TO_KEY = {keycode: mac_keycode.CharForKeycode(keycode) \ # for keycode in range(127)} KEYCODE_TO_KEY = { 122: 'F1', 120: 'F2', 99: 'F3', 118: 'F4', 96: 'F5', 97: 'F6', 98: 'F7', 100: 'F8', 101: 'F9', 109: 'F10', 103: 'F11', 111: 'F12', 50: '`', 29: '0', 18: '1', 19: '2', 20: '3', 21: '4', 23: '5', 22: '6', 26: '7', 28: '8', 25: '9', 27: '-', 24: '=', 12: 'q', 13: 'w', 14: 'e', 15: 'r', 17: 't', 16: 'y', 32: 'u', 34: 'i', 31: 'o', 35: 'p', 33: '[', 30: ']', 42: '\\', 0: 'a', 1: 's', 2: 'd', 3: 'f', 5: 'g', 4: 'h', 38: 'j', 40: 'k', 37: 'l', 41: ';', 39: '\'', 6: 'z', 7: 'x', 8: 'c', 9: 'v', 11: 'b', 45: 'n', 46: 'm', 43: ',', 47: '.', 44: '/', 49: 'space', BACK_SPACE: "BackSpace", 117: "Delete", 125: "Down", 119: "End", 53: "Escape", 115: "Home", 123: "Left", 121: "Page_Down", 116: "Page_Up", 36: "Return", 124: "Right", 48: "Tab", 126: "Up", } def keycode_needs_fn_mask(keycode): return ( keycode >= KEYNAME_TO_KEYCODE['escape'] and keycode not in MODIFIER_KEYS_TO_MASKS ) class KeyboardCaptureLoop: def __init__(self, callback): self._callback = callback self._loop = None self._source = None self._tap = None self._thread = None def _run(self, loop_is_set): self._loop = CFRunLoopGetCurrent() loop_is_set.set() del loop_is_set CFRunLoopAddSource(self._loop, self._source, kCFRunLoopCommonModes) CFRunLoopRun() def start(self): self._tap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp), self._callback, None) if self._tap is None: # TODO: See if there is a nice way to show # the user what's needed (or do it for them). raise Exception("Enable access for assistive devices.") self._source = CFMachPortCreateRunLoopSource(None, self._tap, 0) loop_is_set = threading.Event() self._thread = threading.Thread(target=self._run, args=(loop_is_set,), name="KeyboardCaptureLoop") self._thread.start() loop_is_set.wait() self.toggle_tap(True) def toggle_tap(self, enabled): CGEventTapEnable(self._tap, enabled) def cancel(self): if self._loop is not None: CFRunLoopStop(self._loop) if self._thread is not None: self._thread.join() if self._tap is not None: CFMachPortInvalidate(self._tap) CFRelease(self._tap) if self._source is not None: CFRunLoopSourceInvalidate(self._source) class KeyboardCapture(Capture): _KEYBOARD_EVENTS = {kCGEventKeyDown, kCGEventKeyUp} # Don't ignore Fn and Numeric flags so we can handle # the arrow and extended (home, end, etc...) keys. _PASSTHROUGH_MODIFIERS = ~(kCGEventFlagMaskNumericPad | kCGEventFlagMaskSecondaryFn | kCGEventFlagMaskNonCoalesced) def __init__(self): super().__init__() self.key_down = lambda key: None self.key_up = lambda key: None self._suppressed_keys = set() self._event_queue = Queue() self._event_thread = None self._capture_loop = None def _callback(self, proxy, event_type, event, reference): ''' Returning the event means that it is passed on for further processing by others. Returning None means that the event is intercepted. Delaying too long in returning appears to cause the system to ignore the tap forever after (https://github.com/openstenoproject/plover/issues/484#issuecomment-214743466). This motivates pushing callbacks to the other side of a queue of received events, so that we can return from this callback as soon as possible. ''' if event_type not in self._KEYBOARD_EVENTS: # Don't pass on meta events meant for this event tap. if event_type == kCGEventTapDisabledByTimeout: # Re-enable the tap and hope we act faster next time. self._capture_loop.toggle_tap(True) log.warning("Keystrokes may have been missed, the" "keyboard event tap has been re-enabled.") return None if CGEventGetFlags(event) & self._PASSTHROUGH_MODIFIERS: # Don't intercept or suppress the event if it has # modifiers and the whole keyboard is not suppressed. return event keycode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode) key = KEYCODE_TO_KEY.get(keycode) if key is None: # Not a supported key, don't intercept or suppress. return event # Notify supported key event. self._event_queue.put_nowait((key, event_type)) # And suppressed it if asked too. return None if key in self._suppressed_keys else event def start(self): self._capture_loop = KeyboardCaptureLoop(self._callback) self._capture_loop.start() self._event_thread = threading.Thread(name="KeyboardCapture", target=self._run) self._event_thread.start() def cancel(self): if self._event_thread is not None: self._event_queue.put(None) self._event_thread.join() if self._capture_loop is not None: self._capture_loop.cancel() def suppress(self, suppressed_keys=()): self._suppressed_keys = set(suppressed_keys) def _run(self): while True: event = self._event_queue.get() if event is None: return key, event_type = event if event_type == kCGEventKeyUp: self.key_up(key) else: self.key_down(key) class KeyboardEmulation(GenericKeyboardEmulation): RAW_PRESS, STRING_PRESS = range(2) def __init__(self): super().__init__() self._layout = KeyboardLayout() def send_backspaces(self, count): for _ in self.with_delay(range(count)): backspace_down = CGEventCreateKeyboardEvent( OUTPUT_SOURCE, BACK_SPACE, True) backspace_up = CGEventCreateKeyboardEvent( OUTPUT_SOURCE, BACK_SPACE, False) CGEventPost(kCGSessionEventTap, backspace_down) CGEventPost(kCGSessionEventTap, backspace_up) def send_string(self, string): # Key plan will store the type of output # (raw keycodes versus setting string) # and the list of keycodes or the goal character. key_plan = [] # apply_raw's properties are used to store # the current keycode sequence, # and add the sequence to the key plan when called as a function. def apply_raw(): if hasattr(apply_raw, 'sequence') \ and len(apply_raw.sequence) != 0: apply_raw.sequence.extend(apply_raw.release_modifiers) key_plan.append((self.RAW_PRESS, apply_raw.sequence)) apply_raw.sequence = [] apply_raw.release_modifiers = [] apply_raw() last_modifier = None for c in string: for keycode, modifier in self._layout.char_to_key_sequence(c): if keycode is not None: if modifier is not last_modifier: # Flush on modifier change. apply_raw() last_modifier = modifier modifier_keycodes = self._modifier_to_keycodes( modifier) apply_raw.sequence.extend(down(modifier_keycodes)) apply_raw.release_modifiers.extend( up(modifier_keycodes)) apply_raw.sequence.extend(down_up([keycode])) else: # Flush on type change. last_modifier = None apply_raw() key_plan.append((self.STRING_PRESS, c)) # Flush after string is complete. apply_raw() # We have a key plan for the whole string, grouping modifiers. for press_type, sequence in self.with_delay(key_plan): if press_type is self.STRING_PRESS: self._send_string_press(sequence) elif press_type is self.RAW_PRESS: self._send_sequence(sequence) @staticmethod def _send_string_press(c): event = CGEventCreateKeyboardEvent(OUTPUT_SOURCE, 0, True) KeyboardEmulation._set_event_string(event, c) CGEventPost(kCGSessionEventTap, event) event = CGEventCreateKeyboardEvent(OUTPUT_SOURCE, 0, False) KeyboardEmulation._set_event_string(event, c) CGEventPost(kCGSessionEventTap, event) def send_key_combination(self, combo): def name_to_code(name): # Static key codes code = KEYNAME_TO_KEYCODE.get(name) if code is not None: pass # Dead keys elif name.startswith('dead_'): code, mod = self._layout.deadkey_symbol_to_key_sequence( DEADKEY_SYMBOLS.get(name) )[0] # Normal keys else: char = KEYNAME_TO_CHAR.get(name, name) code, mods = self._layout.char_to_key_sequence(char)[0] return code # Parse and validate combo. key_events = parse_key_combo(combo, name_to_code) # Send events... self._send_sequence(key_events) @staticmethod def _modifier_to_keycodes(modifier): keycodes = [] if modifier & 16: keycodes.append(KEYNAME_TO_KEYCODE['control_r']) if modifier & 8: keycodes.append(KEYNAME_TO_KEYCODE['alt_r']) if modifier & 2: keycodes.append(KEYNAME_TO_KEYCODE['shift_r']) if modifier & 1: keycodes.append(KEYNAME_TO_KEYCODE['super_r']) return keycodes @staticmethod def _set_event_string(event, s): nb_utf16_codepoints = len(s.encode('utf-16-le')) // 2 CGEventKeyboardSetUnicodeString(event, nb_utf16_codepoints, s) MODS_MASK = ( kCGEventFlagMaskAlternate | kCGEventFlagMaskControl | kCGEventFlagMaskShift | kCGEventFlagMaskCommand | kCGEventFlagMaskSecondaryFn ) @staticmethod def _get_media_event(key_id, key_down): # Credit: https://gist.github.com/fredrikw/4078034 flags = 0xa00 if key_down else 0xb00 return NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( # nopep8: We can't make this line shorter! NSSystemDefined, (0, 0), flags, 0, 0, 0, 8, (key_id << 16) | flags, -1 ).CGEvent() def _send_sequence(self, sequence): # There is a bug in the event system that seems to cause inconsistent # modifiers on key events: # http://stackoverflow.com/questions/2008126/cgeventpost-possible-bug-when-simulating-keyboard-events # My solution is to manage the state myself. # I'm not sure how to deal with caps lock. # If mods_flags is not zero at the end then bad things might happen. mods_flags = 0 for keycode, key_down in self.with_delay(sequence): if keycode >= NX_KEY_OFFSET: # Handle media (NX) key. event = KeyboardEmulation._get_media_event( keycode - NX_KEY_OFFSET, key_down) else: # Handle regular keycode. if not key_down and keycode in MODIFIER_KEYS_TO_MASKS: mods_flags &= ~MODIFIER_KEYS_TO_MASKS[keycode] if key_down and keycode_needs_fn_mask(keycode): mods_flags |= kCGEventFlagMaskSecondaryFn event = CGEventCreateKeyboardEvent( OUTPUT_SOURCE, keycode, key_down) if key_down and keycode not in MODIFIER_KEYS_TO_MASKS: event_flags = CGEventGetFlags(event) # Add wanted flags, remove unwanted flags. goal_flags = ((event_flags & ~KeyboardEmulation.MODS_MASK) | mods_flags) if event_flags != goal_flags: CGEventSetFlags(event, goal_flags) # Half millisecond pause after key down. sleep(0.0005) if key_down and keycode in MODIFIER_KEYS_TO_MASKS: mods_flags |= MODIFIER_KEYS_TO_MASKS[keycode] if not key_down and keycode_needs_fn_mask(keycode): mods_flags &= ~kCGEventFlagMaskSecondaryFn CGEventPost(kCGSessionEventTap, event)
17,069
Python
.py
406
32.110837
161
0.595913
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,725
keyboardlayout.py
openstenoproject_plover/plover/oslayer/windows/keyboardlayout.py
# -*- coding: utf-8 -*- from collections import defaultdict, namedtuple from ctypes import windll, wintypes import codecs import ctypes import sys from plover.key_combo import CHAR_TO_KEYNAME, add_modifiers_aliases from plover.misc import popcount_8 from .wmctrl import GetForegroundWindow GetKeyboardLayout = windll.user32.GetKeyboardLayout GetKeyboardLayout.argtypes = [ wintypes.DWORD, # idThread ] GetKeyboardLayout.restype = wintypes.HKL GetWindowThreadProcessId = windll.user32.GetWindowThreadProcessId GetWindowThreadProcessId.argtypes = [ wintypes.HWND, # hWnd wintypes.LPDWORD, # lpdwProcessId ] GetWindowThreadProcessId.restype = wintypes.DWORD MapVirtualKeyEx = windll.user32.MapVirtualKeyExW MapVirtualKeyEx.argtypes = [ wintypes.UINT, # uCode, wintypes.UINT, # uMapType, wintypes.HKL, # dwhkl ] MapVirtualKeyEx.restype = wintypes.UINT ToUnicodeEx = windll.user32.ToUnicodeEx ToUnicodeEx.argtypes = [ wintypes.UINT, # wVirtKey, wintypes.UINT, # wScanCode, wintypes.LPBYTE, # lpKeyState, wintypes.LPWSTR, # pwszBuff, ctypes.c_int, # cchBuff, wintypes.UINT, # wFlags, wintypes.HKL, # dwhkl ] ToUnicodeEx.restype = ctypes.c_int def enum(name, items): ''' Helper to simulate an Enum. ''' keys, values = zip(*items) t = namedtuple(name, keys) return t._make(values) # Shift state enum. {{{ SHIFT_STATE = enum('SHIFT_STATE', ((mod, n) for n, mod in enumerate( 'BASE SHIFT CTRL SHIFT_CTRL MENU SHIFT_MENU MENU_CTRL SHIFT_MENU_CTRL'.split() ))) def shift_state_str(ss): s = '' for mod_state, mod_str in ( (SHIFT_STATE.SHIFT, 'SHIFT'), (SHIFT_STATE.CTRL, 'CTRL'), (SHIFT_STATE.MENU, 'MENU'), ): if (ss & mod_state) != 0: s += mod_str + '+' return s # }}} # Virtual keys enum. {{{ vk_dict = { 'LBUTTON' : 0x01, 'RBUTTON' : 0x02, 'CANCEL' : 0x03, 'MBUTTON' : 0x04, 'XBUTTON1' : 0x05, 'XBUTTON2' : 0x06, 'BACK' : 0x08, 'TAB' : 0x09, 'CLEAR' : 0x0C, 'RETURN' : 0x0D, 'SHIFT' : 0x10, 'CONTROL' : 0x11, 'MENU' : 0x12, 'PAUSE' : 0x13, 'CAPITAL' : 0x14, 'KANA' : 0x15, 'JUNJA' : 0x17, 'FINAL' : 0x18, 'HANJA' : 0x19, 'ESCAPE' : 0x1B, 'CONVERT' : 0x1C, 'NONCONVERT' : 0x1D, 'ACCEPT' : 0x1E, 'MODECHANGE' : 0x1F, 'SPACE' : 0x20, 'PRIOR' : 0x21, 'NEXT' : 0x22, 'END' : 0x23, 'HOME' : 0x24, 'LEFT' : 0x25, 'UP' : 0x26, 'RIGHT' : 0x27, 'DOWN' : 0x28, 'SELECT' : 0x29, 'PRINT' : 0x2A, 'EXECUTE' : 0x2B, 'SNAPSHOT' : 0x2C, 'INSERT' : 0x2D, 'DELETE' : 0x2E, 'HELP' : 0x2F, 'LWIN' : 0x5B, 'RWIN' : 0x5C, 'APPS' : 0x5D, 'SLEEP' : 0x5F, 'NUMPAD0' : 0x60, 'NUMPAD1' : 0x61, 'NUMPAD2' : 0x62, 'NUMPAD3' : 0x63, 'NUMPAD4' : 0x64, 'NUMPAD5' : 0x65, 'NUMPAD6' : 0x66, 'NUMPAD7' : 0x67, 'NUMPAD8' : 0x68, 'NUMPAD9' : 0x69, 'MULTIPLY' : 0x6A, 'ADD' : 0x6B, 'SEPARATOR' : 0x6C, 'SUBTRACT' : 0x6D, 'DECIMAL' : 0x6E, 'DIVIDE' : 0x6F, 'F1' : 0x70, 'F2' : 0x71, 'F3' : 0x72, 'F4' : 0x73, 'F5' : 0x74, 'F6' : 0x75, 'F7' : 0x76, 'F8' : 0x77, 'F9' : 0x78, 'F10' : 0x79, 'F11' : 0x7A, 'F12' : 0x7B, 'F13' : 0x7C, 'F14' : 0x7D, 'F15' : 0x7E, 'F16' : 0x7F, 'F17' : 0x80, 'F18' : 0x81, 'F19' : 0x82, 'F20' : 0x83, 'F21' : 0x84, 'F22' : 0x85, 'F23' : 0x86, 'F24' : 0x87, 'NUMLOCK' : 0x90, 'SCROLL' : 0x91, 'OEM_NEC_EQUAL' : 0x92, 'OEM_FJ_JISHO' : 0x92, 'OEM_FJ_MASSHOU' : 0x93, 'OEM_FJ_TOUROKU' : 0x94, 'OEM_FJ_LOYA' : 0x95, 'OEM_FJ_ROYA' : 0x96, 'LSHIFT' : 0xA0, 'RSHIFT' : 0xA1, 'LCONTROL' : 0xA2, 'RCONTROL' : 0xA3, 'LMENU' : 0xA4, 'RMENU' : 0xA5, 'BROWSER_BACK' : 0xA6, 'BROWSER_FORWARD' : 0xA7, 'BROWSER_REFRESH' : 0xA8, 'BROWSER_STOP' : 0xA9, 'BROWSER_SEARCH' : 0xAA, 'BROWSER_FAVORITES' : 0xAB, 'BROWSER_HOME' : 0xAC, 'VOLUME_MUTE' : 0xAD, 'VOLUME_DOWN' : 0xAE, 'VOLUME_UP' : 0xAF, 'MEDIA_NEXT_TRACK' : 0xB0, 'MEDIA_PREV_TRACK' : 0xB1, 'MEDIA_STOP' : 0xB2, 'MEDIA_PLAY_PAUSE' : 0xB3, 'LAUNCH_MAIL' : 0xB4, 'LAUNCH_MEDIA_SELECT': 0xB5, 'LAUNCH_APP1' : 0xB6, 'LAUNCH_APP2' : 0xB7, 'OEM_1' : 0xBA, 'OEM_PLUS' : 0xBB, 'OEM_COMMA' : 0xBC, 'OEM_MINUS' : 0xBD, 'OEM_PERIOD' : 0xBE, 'OEM_2' : 0xBF, 'OEM_3' : 0xC0, 'OEM_4' : 0xDB, 'OEM_5' : 0xDC, 'OEM_6' : 0xDD, 'OEM_7' : 0xDE, 'OEM_8' : 0xDF, 'OEM_AX' : 0xE1, 'OEM_102' : 0xE2, 'ICO_HELP' : 0xE3, 'ICO_00' : 0xE4, 'PROCESSKEY' : 0xE5, 'ICO_CLEAR' : 0xE6, 'PACKET' : 0xE7, 'OEM_RESET' : 0xE9, 'OEM_JUMP' : 0xEA, 'OEM_PA1' : 0xEB, 'OEM_PA2' : 0xEC, 'OEM_PA3' : 0xED, 'OEM_WSCTRL' : 0xEE, 'OEM_CUSEL' : 0xEF, 'OEM_ATTN' : 0xF0, 'OEM_FINISH' : 0xF1, 'OEM_COPY' : 0xF2, 'OEM_AUTO' : 0xF3, 'OEM_ENLW' : 0xF4, 'OEM_BACKTAB' : 0xF5, 'ATTN' : 0xF6, 'CRSEL' : 0xF7, 'EXSEL' : 0xF8, 'EREOF' : 0xF9, 'PLAY' : 0xFA, 'ZOOM' : 0xFB, 'NONAME' : 0xFC, 'PA1' : 0xFD, 'OEM_CLEAR' : 0xFE, } vk_dict['HANGEUL'] = vk_dict['KANA'] vk_dict['HANGUL'] = vk_dict['KANA'] vk_dict['KANJI'] = vk_dict['HANJA'] for digit in range(10): vk_dict['DIGIT%u' % digit] = 0x30 + digit for anum in range(26): vk_dict[chr(ord('A')+anum)] = 0x41 + anum VK = enum('VK', vk_dict.items()) VK_TO_NAME = { vk: name for name, vk in vk_dict.items() } VK_TO_KEYNAME = { VK.ADD : 'kp_add', VK.APPS : 'menu', VK.BACK : 'backspace', VK.BROWSER_BACK : 'back', VK.BROWSER_FAVORITES : 'favorites', VK.BROWSER_FORWARD : 'forward', VK.BROWSER_HOME : 'homepage', VK.BROWSER_HOME : 'www', VK.BROWSER_REFRESH : 'refresh', VK.BROWSER_SEARCH : 'search', VK.BROWSER_STOP : 'stop', VK.CANCEL : 'cancel', VK.CAPITAL : 'caps_lock', VK.CLEAR : 'clear', VK.DECIMAL : 'kp_decimal', VK.DELETE : 'delete', VK.DIVIDE : 'kp_divide', VK.DOWN : 'down', VK.END : 'end', VK.ESCAPE : 'escape', VK.EXECUTE : 'execute', VK.F1 : 'f1', VK.F2 : 'f2', VK.F3 : 'f3', VK.F4 : 'f4', VK.F5 : 'f5', VK.F6 : 'f6', VK.F7 : 'f7', VK.F8 : 'f8', VK.F9 : 'f9', VK.F10 : 'f10', VK.F11 : 'f11', VK.F12 : 'f12', VK.F13 : 'f13', VK.F14 : 'f14', VK.F15 : 'f15', VK.F16 : 'f16', VK.F17 : 'f17', VK.F18 : 'f18', VK.F19 : 'f19', VK.F20 : 'f20', VK.F21 : 'f21', VK.F22 : 'f22', VK.F23 : 'f23', VK.F24 : 'f24', VK.HELP : 'help', VK.HOME : 'home', VK.INSERT : 'insert', VK.LAUNCH_APP1 : 'mycomputer', VK.LAUNCH_APP2 : 'calculator', VK.LAUNCH_MAIL : 'mail', VK.LAUNCH_MEDIA_SELECT: 'audiomedia', VK.LCONTROL : 'control_l', VK.LEFT : 'left', VK.LMENU : 'alt_l', VK.LSHIFT : 'shift_l', VK.LWIN : 'super_l', VK.MEDIA_NEXT_TRACK : 'audionext', VK.MEDIA_PLAY_PAUSE : 'audiopause', VK.MEDIA_PLAY_PAUSE : 'audioplay', VK.MEDIA_PREV_TRACK : 'audioprev', VK.MEDIA_STOP : 'audiostop', VK.MODECHANGE : 'mode_switch', VK.MULTIPLY : 'kp_multiply', VK.NEXT : 'page_down', VK.NUMLOCK : 'num_lock', VK.NUMPAD0 : 'kp_0', VK.NUMPAD1 : 'kp_1', VK.NUMPAD2 : 'kp_2', VK.NUMPAD3 : 'kp_3', VK.NUMPAD4 : 'kp_4', VK.NUMPAD5 : 'kp_5', VK.NUMPAD6 : 'kp_6', VK.NUMPAD7 : 'kp_7', VK.NUMPAD8 : 'kp_8', VK.NUMPAD9 : 'kp_9', VK.OEM_PLUS : 'kp_equal', VK.PAUSE : 'pause', VK.PRIOR : 'page_up', VK.RCONTROL : 'control_r', VK.RETURN : 'return', VK.RIGHT : 'right', VK.RMENU : 'alt_r', VK.RSHIFT : 'shift_r', VK.RWIN : 'super_r', VK.SCROLL : 'scroll_lock', VK.SELECT : 'select', VK.SLEEP : 'standby', VK.SNAPSHOT : 'print', VK.SUBTRACT : 'kp_subtract', VK.TAB : 'tab', VK.UP : 'up', VK.VOLUME_DOWN : 'audiolowervolume', VK.VOLUME_MUTE : 'audiomute', VK.VOLUME_UP : 'audioraisevolume', } def vk_to_str(vk): s = VK_TO_NAME.get(vk) return '%x' % vk if s is None else s # }}} DEAD_KEYNAME = { 'asciicircum': 'dead_circumflex', 'asciitilde' : 'dead_tilde', } class KeyboardLayout: # {{{ def __init__(self, layout_id=None, debug=False): if layout_id is None: layout_id = KeyboardLayout.current_layout_id() self.layout_id = layout_id # Find virtual key code for each scan code (if any). sc_to_vk = {} vk_to_sc = {} for sc in range(0x01, 0x7f + 1): vk = MapVirtualKeyEx(sc, 3, layout_id) if vk != 0: sc_to_vk[sc] = vk vk_to_sc[vk] = sc state = (wintypes.BYTE * 256)() strbuf = ctypes.create_unicode_buffer(8) def fill_state(ss): for mod_state, mod_vk in ( (SHIFT_STATE.SHIFT, VK.SHIFT), (SHIFT_STATE.CTRL, VK.CONTROL), (SHIFT_STATE.MENU, VK.MENU), ): state[mod_vk] = 0x80 if (ss & mod_state) != 0 else 0 def to_unichr(vk, sc, ss): fill_state(ss) rc = ToUnicodeEx(vk, sc, state, strbuf, len(strbuf), 0, layout_id) if rc > 0: dead_key = False char = ctypes.wstring_at(strbuf.value, rc) elif rc < 0: # Dead key, flush state. dead_key = True fill_state(0) rc = ToUnicodeEx(VK.SPACE, vk_to_sc[VK.SPACE], state, strbuf, len(strbuf), 0, layout_id) char = ctypes.wstring_at(strbuf.value, rc) if rc > 0 else '' else: dead_key = False char = '' return char, dead_key def sort_vk_ss_list(vk_ss_list): # Prefer lower modifiers combo. return sorted(vk_ss_list, key=lambda vk_ss: popcount_8(vk_ss[1])) char_to_vk_ss = defaultdict(list) keyname_to_vk = defaultdict(list) for sc, vk in sorted(sc_to_vk.items()): for ss in SHIFT_STATE: if ss in (SHIFT_STATE.MENU, SHIFT_STATE.SHIFT_MENU): # Alt and Shift+Alt don't work, so skip them. continue char, dead_key = to_unichr(vk, sc, ss) if debug and char: print('%s%s -> %s [%r] %s' % ( shift_state_str(ss), vk_to_str(vk), char, char, '[dead key]' if dead_key else '', )) kn = None if char: kn = CHAR_TO_KEYNAME.get(char) if dead_key: kn = kn and DEAD_KEYNAME.get(kn, 'dead_' + kn) else: char_to_vk_ss[char].append((vk, ss)) if kn: keyname_to_vk[kn].append((vk, ss)) self.char_to_vk_ss = { char: sort_vk_ss_list(vk_ss_list)[0] for char, vk_ss_list in char_to_vk_ss.items() } self.char_to_vk_ss['\n'] = self.char_to_vk_ss['\r'] self.keyname_to_vk = { kn: vk for vk, kn in VK_TO_KEYNAME.items() } self.keyname_to_vk.update({ 'next' : VK.NEXT, 'prior' : VK.PRIOR, 'kp_delete' : VK.DELETE, 'kp_enter' : VK.RETURN, 'break' : VK.CANCEL, }) self.keyname_to_vk.update({ kn: sort_vk_ss_list(vk_ss_list)[0][0] for kn, vk_ss_list in keyname_to_vk.items() }) add_modifiers_aliases(self.keyname_to_vk) self.ss_to_vks = {} for ss in SHIFT_STATE: vk_list = [] for mod_state, mod_vk in ( (SHIFT_STATE.SHIFT, VK.SHIFT), (SHIFT_STATE.CTRL, VK.CONTROL), (SHIFT_STATE.MENU, VK.MENU), ): if (ss & mod_state) != 0: vk_list.append(mod_vk) self.ss_to_vks[ss] = tuple(vk_list) @staticmethod def current_layout_id(): pid = GetWindowThreadProcessId(GetForegroundWindow(), None) return GetKeyboardLayout(pid) # }}} if __name__ == '__main__': sys.stdout = codecs.getwriter('utf8')(sys.stdout) layout = KeyboardLayout(debug=True) print('character to virtual key + shift state [%u]' % len(layout.char_to_vk_ss)) for char, combo in sorted(layout.char_to_vk_ss.items()): vk, ss = combo print('%s [%r:%s] -> %s%s' % (char, char, CHAR_TO_KEYNAME.get(char, '?'), shift_state_str(ss), vk_to_str(vk))) print() print('keyname to virtual key [%u]' % len(layout.keyname_to_vk)) for kn, vk in sorted(layout.keyname_to_vk.items()): print('%s -> %s' % (kn, vk_to_str(vk))) print() print('modifiers combo [%u]' % len(layout.ss_to_vks)) for ss, vk_list in sorted(layout.ss_to_vks.items()): print('%s -> %s' % (shift_state_str(ss), '+'.join(vk_to_str(vk) for vk in vk_list))) # vim: foldmethod=marker
16,270
Python
.py
457
28.612691
92
0.435463
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,726
serial.py
openstenoproject_plover/plover/oslayer/windows/serial.py
# “Microsoft Corp”. MICROSOFT_VID = 0x045e def patch_ports_info(port_list): '''Patch serial ports info to remove erroneous manufacturer. Because on Windows 10 most USB serial devices will use the generic CDC/ACM driver, their manufacturer is reported as Microsoft. Strip that information if the vendor ID does not match. ''' for port_info in port_list: if port_info.manufacturer == 'Microsoft' \ and port_info.vid != MICROSOFT_VID: port_info.manufacturer = None return port_list
545
Python
.py
13
35.846154
70
0.706667
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,727
wmctrl.py
openstenoproject_plover/plover/oslayer/windows/wmctrl.py
from ctypes import windll, wintypes GetForegroundWindow = windll.user32.GetForegroundWindow GetForegroundWindow.argtypes = [] GetForegroundWindow.restype = wintypes.HWND SetForegroundWindow = windll.user32.SetForegroundWindow SetForegroundWindow.argtypes = [ wintypes.HWND, # hWnd ] SetForegroundWindow.restype = wintypes.BOOL
334
Python
.py
9
35.333333
55
0.857143
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,728
i18n.py
openstenoproject_plover/plover/oslayer/windows/i18n.py
import locale from ctypes import windll def get_system_language(): return locale.windows_locale[windll.kernel32.GetUserDefaultUILanguage()]
147
Python
.py
4
34
76
0.835714
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,729
keyboardcontrol.py
openstenoproject_plover/plover/oslayer/windows/keyboardcontrol.py
# Copyright (c) 2011 Hesky Fisher. # See LICENSE.txt for details. # # winkeyboardcontrol.py - capturing and injecting keyboard events in windows. """Keyboard capture and control in windows. This module provides an interface for basic keyboard event capture and emulation. Set the key_up and key_down functions of the KeyboardCapture class to capture keyboard input. Call the send_string and send_backspaces functions of the KeyboardEmulation class to emulate keyboard input. """ from ctypes import windll, wintypes import atexit import ctypes import multiprocessing import os import signal import threading import winreg from plover import log from plover.key_combo import parse_key_combo from plover.machine.keyboard_capture import Capture from plover.misc import to_surrogate_pair from plover.output.keyboard import GenericKeyboardEmulation from .keyboardlayout import KeyboardLayout # For the purposes of this class, we'll only report key presses that # result in these outputs in order to exclude special key combos. SCANCODE_TO_KEY = { 59: 'F1', 60: 'F2', 61: 'F3', 62: 'F4', 63: 'F5', 64: 'F6', 65: 'F7', 66: 'F8', 67: 'F9', 68: 'F10', 87: 'F11', 88: 'F12', 41: '`', 2: '1', 3: '2', 4: '3', 5: '4', 6: '5', 7: '6', 8: '7', 9: '8', 10: '9', 11: '0', 12: '-', 13: '=', 16: 'q', 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', 22: 'u', 23: 'i', 24: 'o', 25: 'p', 26: '[', 27: ']', 43: '\\', 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', 36: 'j', 37: 'k', 38: 'l', 39: ';', 40: '\'', 44: 'z', 45: 'x', 46: 'c', 47: 'v', 48: 'b', 49: 'n', 50: 'm', 51: ',', 52: '.', 53: '/', 57: 'space', 58: "BackSpace", 83: "Delete", 80: "Down", 79: "End", 1: "Escape", 71: "Home", 82: "Insert", 75: "Left", 73: "Page_Down", 81: "Page_Up", 28 : "Return", 77: "Right", 15: "Tab", 72: "Up", } KEY_TO_SCANCODE = dict(zip(SCANCODE_TO_KEY.values(), SCANCODE_TO_KEY.keys())) PASSTHROUGH_KEYS = { 0XA2, 0XA3, # Control 0XA0, 0XA1, # Shift 0XA4, 0XA5, # Alt 0X5B, 0X5C, # Win } """ SendInput code and classes based off: http://stackoverflow.com/questions/11906925/python-simulate-keydown """ class MOUSEINPUT(ctypes.Structure): _fields_ = (('dx', wintypes.LONG), ('dy', wintypes.LONG), ('mouseData', wintypes.DWORD), ('dwFlags', wintypes.DWORD), ('time', wintypes.DWORD), ('dwExtraInfo', wintypes.PULONG)) class KEYBDINPUT(ctypes.Structure): _fields_ = (('wVk', wintypes.WORD), ('wScan', wintypes.WORD), ('dwFlags', wintypes.DWORD), ('time', wintypes.DWORD), ('dwExtraInfo', wintypes.PULONG)) class _INPUTunion(ctypes.Union): _fields_ = (('mi', MOUSEINPUT), ('ki', KEYBDINPUT)) class INPUT(ctypes.Structure): _fields_ = (('type', wintypes.DWORD), ('union', _INPUTunion)) SendInput = windll.user32.SendInput SendInput.argtypes = [ wintypes.UINT, # cInputs ctypes.POINTER(INPUT), # pInputs, ctypes.c_int, # cbSize ] SendInput.restype = wintypes.UINT KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 KEYEVENTF_SCANCODE = 0x0008 KEYEVENTF_UNICODE = 0x0004 INPUT_MOUSE = 0 INPUT_KEYBOARD = 1 # Process utils code code based on psutil implementation. OpenProcess = windll.kernel32.OpenProcess OpenProcess.argtypes = [ wintypes.DWORD, # dwDesiredAccess wintypes.BOOL, # bInheritHandle wintypes.DWORD, # dwProcessId ] OpenProcess.restype = wintypes.HANDLE GetExitCodeProcess = windll.kernel32.GetExitCodeProcess GetExitCodeProcess.argtypes = [ wintypes.HANDLE, # hProcess wintypes.LPDWORD, # lpExitCode ] GetExitCodeProcess.restype = wintypes.BOOL CloseHandle = windll.kernel32.CloseHandle CloseHandle.argtypes = [ wintypes.HANDLE, # hObject ] CloseHandle.restype = wintypes.BOOL PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_VM_READ = 0x0010 ERROR_INVALID_PARAMETER = 87 ERROR_ACCESS_DENIED = 5 STILL_ACTIVE = 0x00000103 def pid_exists(pid): """Check whether pid exists in the current process table.""" process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid) if not process: err = ctypes.GetLastError() if err == ERROR_INVALID_PARAMETER: # Invalid parameter is no such process. return False if err == ERROR_ACCESS_DENIED: # Access denied obviously means there's a process to deny access to... return True raise ctypes.WinError(err) try: exitcode = wintypes.DWORD() out = GetExitCodeProcess(process, ctypes.byref(exitcode)) if not out: err = ctypes.GetLastError() if err == ERROR_ACCESS_DENIED: # Access denied means there's a process # there so we'll assume it's running. return True raise ctypes.WinError(err) return exitcode.value == STILL_ACTIVE finally: CloseHandle(process) class HeartBeat(threading.Thread): def __init__(self, ppid, exitcb): super().__init__() self._ppid = ppid self._exitcb = exitcb self._finished = threading.Event() def run(self): while pid_exists(self._ppid): if self._finished.wait(1): break self._exitcb() def stop(self): self._finished.set() self.join() class KBDLLHOOKSTRUCT(ctypes.Structure): _fields_ = (("vkCode", wintypes.DWORD), ("scanCode", wintypes.DWORD), ("flags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", ctypes.c_void_p)) PKBDLLHOOKSTRUCT = ctypes.POINTER(KBDLLHOOKSTRUCT) LRESULT = ctypes.c_long HOOKPROC = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM) SetWindowsHookExA = windll.user32.SetWindowsHookExA SetWindowsHookExA.argtypes = ( ctypes.c_int, # idHook, HOOKPROC, # lpfn, wintypes.HINSTANCE, # hmod, wintypes.DWORD, # dwThreadId ) SetWindowsHookExA.restype = wintypes.HHOOK CallNextHookEx = windll.user32.CallNextHookEx CallNextHookEx.argtypes = ( wintypes.HHOOK, # hhk ctypes.c_int, # nCode wintypes.WPARAM, # wParam wintypes.LPARAM, # lParam ) CallNextHookEx.restype = LRESULT UnhookWindowsHookEx = windll.user32.UnhookWindowsHookEx UnhookWindowsHookEx.argtypes = (wintypes.HHOOK,) UnhookWindowsHookEx.restype = wintypes.BOOL GetMessageW = windll.user32.GetMessageW GetMessageW.argtypes = ( wintypes.LPMSG, # lpMsg, wintypes.HWND, # hWnd, wintypes.UINT, # wMsgFilterMin, wintypes.UINT, # wMsgFilterMax ) GetMessageW.restype = wintypes.BOOL TranslateMessage = windll.user32.TranslateMessage TranslateMessage.argtypes = (wintypes.MSG,) TranslateMessage.restype = wintypes.BOOL DispatchMessageW = windll.user32.DispatchMessageW DispatchMessageW.argtypes = (wintypes.MSG,) DispatchMessageW.restype = LRESULT PostThreadMessageW = windll.user32.PostThreadMessageW PostThreadMessageW.argtypes = ( wintypes.DWORD, # idThread wintypes.UINT, # Msg wintypes.WPARAM, # wParam wintypes.LPARAM, # lParam ) PostThreadMessageW.restype = wintypes.BOOL WM_QUIT = 0x12 # Registry setting for low level hook timeout. 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 class KeyboardCaptureProcess(multiprocessing.Process): def __init__(self): super().__init__() self.daemon = True self._ppid = os.getpid() self._update_registry() self._tid = None self._queue = multiprocessing.Queue() self._suppressed_keys_bitmask = multiprocessing.Array(ctypes.c_uint64, (max(SCANCODE_TO_KEY.keys()) + 63) // 64) self._suppressed_keys_bitmask[:] = (0xffffffffffffffff,) * len(self._suppressed_keys_bitmask) @staticmethod 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) read_key = _open_key(winreg.KEY_READ) try: value, value_type = winreg.QueryValueEx(read_key, REG_LLHOOK_KEY_VALUE_NAME) except OSError: 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 OSError: 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) def run(self): heartbeat = HeartBeat(self._ppid, self._send_quit) heartbeat.start() try: self._run() finally: heartbeat.stop() def _run(self): # Ignore KeyboardInterrupt when attached to a console... signal.signal(signal.SIGINT, signal.SIG_IGN) self._tid = windll.kernel32.GetCurrentThreadId() self._queue.put(self._tid) passthrough_down_keys = set() def on_key(pressed, event): if event.flags & 0x10: # Ignore simulated events (e.g. from KeyboardEmulation). return False if event.vkCode in PASSTHROUGH_KEYS: if pressed: passthrough_down_keys.add(event.vkCode) else: passthrough_down_keys.discard(event.vkCode) key = SCANCODE_TO_KEY.get(event.scanCode) if key is None: # Unhandled, ignore and don't suppress. return False suppressed = bool(self._suppressed_keys_bitmask[event.scanCode // 64] & (1 << (event.scanCode % 64))) if pressed and passthrough_down_keys: # Modifier(s) pressed, ignore. return False self._queue.put((None, key, pressed)) return suppressed hook_id = None def low_level_handler(code, wparam, lparam): if code >= 0: event = ctypes.cast(lparam, PKBDLLHOOKSTRUCT)[0] pressed = wparam in (0x100, 0x104) if on_key(pressed, event): # Suppressed... return 1 return CallNextHookEx(hook_id, code, wparam, lparam) hook_proc = HOOKPROC(low_level_handler) hook_id = SetWindowsHookExA(0xd, hook_proc, None, 0) if not hook_id: self._queue.put((('failed to install keyboard hook: %s', ctypes.FormatError()), None, None)) return atexit.register(UnhookWindowsHookEx, hook_id) msg = wintypes.MSG() msg_p = ctypes.byref(msg) while GetMessageW(msg_p, None, 0, 0): TranslateMessage(msg_p) DispatchMessageW(msg_p) def _send_quit(self): PostThreadMessageW(self._tid, WM_QUIT, 0, 0) def start(self): self.daemon = True super().start() self._tid = self._queue.get() def stop(self): if self.is_alive(): self._send_quit() self.join() # Wake up capture thread, so it gets a chance to check if it must stop. self._queue.put((None, None, None)) def suppress(self, suppressed_keys): bitmask = [0] * len(self._suppressed_keys_bitmask) for key in suppressed_keys: code = KEY_TO_SCANCODE[key] bitmask[code // 64] |= (1 << (code % 64)) self._suppressed_keys_bitmask[:] = bitmask def get(self): return self._queue.get() class KeyboardCapture(Capture): def __init__(self): super().__init__() self._suppressed_keys = set() self._finished = None self._thread = None self._proc = None def start(self): self._finished = threading.Event() self._proc = KeyboardCaptureProcess() self._proc.start() self._thread = threading.Thread(target=self._run) self._thread.start() def _run(self): while True: error, key, pressed = self._proc.get() if error is not None: log.error(*error) if self._finished.is_set(): break (self.key_down if pressed else self.key_up)(key) def cancel(self): if self._finished is not None: self._finished.set() if self._proc is not None: self._proc.stop() if self._thread is not None: self._thread.join() def suppress(self, suppressed_keys=()): self._suppressed_keys = set(suppressed_keys) self._proc.suppress(self._suppressed_keys) class KeyboardEmulation(GenericKeyboardEmulation): def __init__(self): super().__init__() self.keyboard_layout = KeyboardLayout() # Sends input types to buffer @staticmethod def _send_input(*inputs): len_inputs = len(inputs) len_pinput = INPUT * len_inputs pinputs = len_pinput(*inputs) c_size = ctypes.c_int(ctypes.sizeof(INPUT)) return SendInput(len_inputs, pinputs, c_size) # Input type (can be mouse, keyboard) @staticmethod def _input(structure): if isinstance(structure, MOUSEINPUT): return INPUT(INPUT_MOUSE, _INPUTunion(mi=structure)) if isinstance(structure, KEYBDINPUT): return INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure)) raise TypeError('Cannot create INPUT structure!') # Container to send mouse input # Not used, but maybe one day it will be useful @staticmethod def _mouse_input(flags, x, y, data): return MOUSEINPUT(x, y, data, flags, 0, None) # Keyboard input type to send key input @staticmethod def _keyboard_input(code, flags): if flags & KEYEVENTF_UNICODE: # special handling of Unicode characters return KEYBDINPUT(0, code, flags, 0, None) return KEYBDINPUT(code, 0, flags, 0, None) # Abstraction to set flags to 0 and create an input type def _keyboard(self, code, flags=0): return self._input(self._keyboard_input(code, flags)) def _key_event(self, keycode, pressed): flags = 0 if pressed else KEYEVENTF_KEYUP self._send_input(self._keyboard(keycode, flags)) # Press and release a key def _key_press(self, char): vk, ss = self.keyboard_layout.char_to_vk_ss[char] keycode_list = [] keycode_list.extend(self.keyboard_layout.ss_to_vks[ss]) keycode_list.append(vk) # Press all keys. for keycode in keycode_list: self._key_event(keycode, True) # Release all keys for keycode in keycode_list: self._key_event(keycode, False) def _refresh_keyboard_layout(self): layout_id = KeyboardLayout.current_layout_id() if layout_id != self.keyboard_layout.layout_id: self.keyboard_layout = KeyboardLayout(layout_id) def _key_unicode(self, char): pairs = to_surrogate_pair(char) # Send press events for all codes, then release events for all codes. inputs = [self._keyboard(code, KEYEVENTF_UNICODE | direction) for direction in (0, KEYEVENTF_KEYUP) for code in pairs] self._send_input(*inputs) def send_backspaces(self, count): for _ in self.with_delay(range(count)): self._key_press('\x08') def send_string(self, string): self._refresh_keyboard_layout() for char in self.with_delay(string): if char in self.keyboard_layout.char_to_vk_ss: # We know how to simulate the character. self._key_press(char) else: # Otherwise, we send it as a Unicode string. self._key_unicode(char) def send_key_combination(self, combo): # Make sure keyboard layout is up-to-date. self._refresh_keyboard_layout() # Parse and validate combo. key_events = parse_key_combo(combo, self.keyboard_layout.keyname_to_vk.get) # Send events... for keycode, pressed in self.with_delay(key_events): self._key_event(keycode, pressed)
17,406
Python
.py
433
32.233256
120
0.628368
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,730
wmctrl_x11.py
openstenoproject_plover/plover/oslayer/linux/wmctrl_x11.py
from Xlib import X, display from Xlib.error import BadWindow from Xlib.protocol.event import ClientMessage class WmCtrl: def __init__(self): self._display = display.Display() self._root = self._display.screen().root self._atoms = { name: self._display.intern_atom(name) for name in ''' _NET_ACTIVE_WINDOW _NET_CURRENT_DESKTOP _NET_WM_DESKTOP _WIN_WORKSPACE '''.split() } def _get_wm_property(self, window, atom_name): prop = window.get_full_property(self._atoms[atom_name], X.AnyPropertyType) return None if prop is None else prop.value[0] def _client_msg(self, window, atom_name, data): ev_data = (data,) + (0,) * 4 ev = ClientMessage(window=window, client_type=self._atoms[atom_name], data = (32, ev_data)) ev_mask = X.SubstructureRedirectMask | X.SubstructureNotifyMask self._root.send_event(ev, event_mask=ev_mask) self._display.sync() def _map_raised(self, window): window.map() window.raise_window() self._display.sync() def get_foreground_window(self): return self._get_wm_property(self._root, '_NET_ACTIVE_WINDOW') def set_foreground_window(self, w): try: window = self._display.create_resource_object('window', w) for atom in ('_NET_WM_DESKTOP', '_WIN_WORKSPACE'): desktop = self._get_wm_property(window, atom) if desktop is not None: self._client_msg(self._root, '_NET_CURRENT_DESKTOP', desktop) break self._client_msg(window, '_NET_ACTIVE_WINDOW', 0) self._map_raised(window) except BadWindow: pass
1,962
Python
.py
48
28.375
71
0.542497
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,731
log_dbus.py
openstenoproject_plover/plover/oslayer/linux/log_dbus.py
from contextlib import contextmanager import ctypes.util import os import logging from plover import log, __name__ as __software_name__ from plover.oslayer.config import ASSETS_DIR APPNAME = ctypes.c_char_p(__software_name__.capitalize().encode()) APPICON = ctypes.c_char_p(os.path.join(ASSETS_DIR, 'plover.png').encode()) SERVICE = ctypes.c_char_p(b'org.freedesktop.Notifications') INTERFACE = ctypes.c_char_p(b'/org/freedesktop/Notifications') NOTIFY_URGENCY_LOW = ctypes.c_uint8(0) NOTIFY_URGENCY_NORMAL = ctypes.c_uint8(1) NOTIFY_URGENCY_CRITICAL = ctypes.c_uint8(2) DBUS_BUS_SESSION = ctypes.c_uint(0) DBUS_TYPE_ARRAY = ctypes.c_int(ord('a')) DBUS_TYPE_BYTE = ctypes.c_int(ord('y')) DBUS_TYPE_DICT_ENTRY = ctypes.c_int(ord('e')) DBUS_TYPE_INT32 = ctypes.c_int(ord('i')) DBUS_TYPE_STRING = ctypes.c_int(ord('s')) DBUS_TYPE_UINT32 = ctypes.c_int(ord('u')) DBUS_TYPE_VARIANT = ctypes.c_int(ord('v')) class DBusConnection(ctypes.c_void_p): pass class DBusError(ctypes.Structure): _fields_ = ( ('name' , ctypes.c_char_p), ('message' , ctypes.c_char_p), ('dummy1' , ctypes.c_uint), ('dummy2' , ctypes.c_uint), ('dummy3' , ctypes.c_uint), ('dummy4' , ctypes.c_uint), ('dummy5' , ctypes.c_uint), ('padding1', ctypes.c_void_p), ) class DBusMessage(ctypes.c_void_p): pass class DBusMessageIter(ctypes.Structure): _fields_ = ( ('dummy1' , ctypes.c_void_p), ('dummy2' , ctypes.c_void_p), ('dummy3' , ctypes.c_uint32), ('dummy4' , ctypes.c_int), ('dummy5' , ctypes.c_int), ('dummy6' , ctypes.c_int), ('dummy7' , ctypes.c_int), ('dummy8' , ctypes.c_int), ('dummy9' , ctypes.c_int), ('dummy10', ctypes.c_int), ('dummy11', ctypes.c_int), ('pad1' , ctypes.c_int), ('pad2' , ctypes.c_void_p), ('pad3' , ctypes.c_void_p), ) def ctypes_type(signature): if signature == 'void': return None ct = { 'connection_p' : DBusConnection, 'error_p' : DBusError, 'message_p' : DBusMessage, 'message_iter_p': DBusMessageIter, }.get(signature) if ct is not None: return ctypes.POINTER(ct) ct = getattr(ctypes, 'c_' + signature, None) if ct is not None: return ct if not signature.endswith('_p'): raise ValueError(signature) ct = getattr(ctypes, 'c_' + signature[:-2]) if ct is None: raise ValueError(signature) return ctypes.POINTER(ct) def ctypes_func(library, signature): restype, func_name, *argtypes = signature.split() func = getattr(library, func_name) func.argtypes = tuple(map(ctypes_type, argtypes)) func.restype = ctypes_type(restype) return func class DBusNotificationHandler(logging.Handler): """ Handler using DBus notifications to show messages. """ def __init__(self): super().__init__() self.setLevel(log.WARNING) self.setFormatter(log.NoExceptionTracebackFormatter('<b>%(levelname)s:</b> %(message)s')) libname = ctypes.util.find_library('dbus-1') if libname is None: raise FileNotFoundError('dbus-1 library') library = ctypes.cdll.LoadLibrary(libname) error_free = ctypes_func(library, 'void dbus_error_free error_p') error_init = ctypes_func(library, 'void dbus_error_init error_p') error_is_set = ctypes_func(library, 'bool dbus_error_is_set error_p') bus_get = ctypes_func(library, 'connection_p dbus_bus_get uint error_p') message_new = ctypes_func(library, 'message_p dbus_message_new_method_call char_p char_p char_p char_p') message_unref = ctypes_func(library, 'void dbus_message_unref message_p') iter_init_append = ctypes_func(library, 'void dbus_message_iter_init_append message_p message_iter_p') iter_append_basic = ctypes_func(library, 'bool dbus_message_iter_append_basic message_iter_p int void_p') iter_open_container = ctypes_func(library, 'bool dbus_message_iter_open_container message_iter_p int char_p message_iter_p') iter_close_container = ctypes_func(library, 'bool dbus_message_iter_close_container message_iter_p message_iter_p') connection_send = ctypes_func(library, 'bool dbus_connection_send connection_p message_p uint32_p') # Need message + container + dict_entry + variant = 4 iterators. self._iter_stack = [DBusMessageIter() for __ in range(4)] self._iter_stack_index = 0 @contextmanager def open_container(kind, signature): parent_iter = self._iter_stack[self._iter_stack_index] sub_iter = self._iter_stack[self._iter_stack_index + 1] if not iter_open_container(parent_iter, kind, signature, sub_iter): raise MemoryError self._iter_stack_index += 1 try: yield finally: if not iter_close_container(parent_iter, sub_iter): raise MemoryError self._iter_stack_index -= 1 def append_basic(kind, value): if not iter_append_basic(self._iter_stack[self._iter_stack_index], kind, ctypes.byref(value)): raise MemoryError error = DBusError() error_init(error) bus = bus_get(DBUS_BUS_SESSION, ctypes.byref(error)) if error_is_set(error): e = ConnectionError('%s: %s' % (error.name.decode(), error.message.decode())) error_free(error) raise e assert bus is not None actions_signature = ctypes.c_char_p(b's') hints_signature = ctypes.c_char_p(b'{sv}') notify_str = ctypes.c_char_p(b'Notify') urgency_signature = ctypes.c_char_p(b'y') urgency_str = ctypes.c_char_p(b'urgency') zero = ctypes.c_uint(0) def notify(body, urgency, timeout): message = message_new(SERVICE, INTERFACE, SERVICE, notify_str) try: iter_init_append(message, self._iter_stack[self._iter_stack_index]) # app_name append_basic(DBUS_TYPE_STRING, APPNAME) # replaces_id append_basic(DBUS_TYPE_UINT32, zero) # app_icon append_basic(DBUS_TYPE_STRING, APPICON) # summary append_basic(DBUS_TYPE_STRING, APPNAME) # body append_basic(DBUS_TYPE_STRING, body) # actions with open_container(DBUS_TYPE_ARRAY, actions_signature): pass # hints with open_container(DBUS_TYPE_ARRAY, hints_signature), open_container(DBUS_TYPE_DICT_ENTRY, None): append_basic(DBUS_TYPE_STRING, urgency_str) with open_container(DBUS_TYPE_VARIANT, urgency_signature): append_basic(DBUS_TYPE_BYTE, urgency) # expire_timeout append_basic(DBUS_TYPE_INT32, timeout) connection_send(bus, message, None) finally: message_unref(message) self._notify = notify def emit(self, record): level = record.levelno message = self.format(record) if message.endswith('\n'): message = message[:-1] if level <= log.INFO: timeout = 10 urgency = NOTIFY_URGENCY_LOW elif level <= log.WARNING: timeout = 15 urgency = NOTIFY_URGENCY_NORMAL else: timeout = 0 urgency = NOTIFY_URGENCY_CRITICAL self._notify(ctypes.c_char_p(message.encode()), urgency, ctypes.c_int(timeout * 1000))
7,803
Python
.py
176
35.079545
132
0.606814
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,732
serial.py
openstenoproject_plover/plover/oslayer/linux/serial.py
from pathlib import Path def patch_ports_info(port_list): '''Patch serial ports info to use device-by-id links.''' try: device_by_id = { str(device.resolve()): str(device) for device in Path('/dev/serial/by-id').iterdir() } except FileNotFoundError: device_by_id = {} for port_info in port_list: port_info.device = device_by_id.get(port_info.device, port_info.device) return port_list
463
Python
.py
13
28.615385
79
0.629464
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,733
keyboardcontrol_x11.py
openstenoproject_plover/plover/oslayer/linux/keyboardcontrol_x11.py
# -*- coding: utf-8 -*- # # Copyright (c) 2010 Joshua Harlan Lifton. # See LICENSE.txt for details. # # keyboardcontrol.py - capturing and injecting X keyboard events # # This code requires the X Window System with the 'XInput2' and 'XTest' # extensions and python-xlib with support for said extensions. """Keyboard capture and control using Xlib. This module provides an interface for basic keyboard event capture and emulation. Set the key_up and key_down functions of the KeyboardCapture class to capture keyboard input. Call the send_string and send_backspaces functions of the KeyboardEmulation class to emulate keyboard input. For an explanation of keycodes, keysyms, and modifiers, see: http://tronche.com/gui/x/xlib/input/keyboard-encoding.html """ import os import select import threading from time import sleep from Xlib import X, XK from Xlib.display import Display from Xlib.ext import xinput, xtest from Xlib.ext.ge import GenericEventCode from plover import log from plover.key_combo import add_modifiers_aliases, parse_key_combo from plover.machine.keyboard_capture import Capture from plover.output.keyboard import GenericKeyboardEmulation # Enable support for media keys. XK.load_keysym_group('xf86') # Load non-us keyboard related keysyms. XK.load_keysym_group('xkb') # Create case insensitive mapping of keyname to keysym. KEY_TO_KEYSYM = {} for symbol in sorted(dir(XK)): # Sorted so XK_a is preferred over XK_A. if not symbol.startswith('XK_'): continue name = symbol[3:].lower() keysym = getattr(XK, symbol) KEY_TO_KEYSYM[name] = keysym # Add aliases for `XF86_` keys. if name.startswith('xf86_'): alias = name[5:] if alias not in KEY_TO_KEYSYM: KEY_TO_KEYSYM[alias] = keysym add_modifiers_aliases(KEY_TO_KEYSYM) XINPUT_DEVICE_ID = xinput.AllDevices XINPUT_EVENT_MASK = xinput.KeyPressMask | xinput.KeyReleaseMask KEYCODE_TO_KEY = { # Function row. 67: "F1", 68: "F2", 69: "F3", 70: "F4", 71: "F5", 72: "F6", 73: "F7", 74: "F8", 75: "F9", 76: "F10", 95: "F11", 96: "F12", # Number row. 49: "`", 10: "1", 11: "2", 12: "3", 13: "4", 14: "5", 15: "6", 16: "7", 17: "8", 18: "9", 19: "0", 20: "-", 21: "=", 51: "\\", # Upper row. 24: "q", 25: "w", 26: "e", 27: "r", 28: "t", 29: "y", 30: "u", 31: "i", 32: "o", 33: "p", 34: "[", 35: "]", # Home row. 38: "a", 39: "s", 40: "d", 41: "f", 42: "g", 43: "h", 44: "j", 45: "k", 46: "l", 47: ";", 48: "'", # Bottom row. 52: "z", 53: "x", 54: "c", 55: "v", 56: "b", 57: "n", 58: "m", 59: ",", 60: ".", 61: "/", # Other keys. 22 : "BackSpace", 119: "Delete", 116: "Down", 115: "End", 9 : "Escape", 110: "Home", 118: "Insert", 113: "Left", 117: "Page_Down", 112: "Page_Up", 36 : "Return", 114: "Right", 23 : "Tab", 111: "Up", 65 : "space", } KEY_TO_KEYCODE = dict(zip(KEYCODE_TO_KEY.values(), KEYCODE_TO_KEY.keys())) class XEventLoop: def __init__(self, on_event, name='XEventLoop'): self._on_event = on_event self._lock = threading.Lock() self._display = Display() self._thread = threading.Thread(name=name, target=self._run) self._pipe = os.pipe() self._readfds = (self._pipe[0], self._display.fileno()) def __enter__(self): self._lock.__enter__() return self._display def __exit__(self, exc_type, exc_value, traceback): if exc_type is None and self._display is not None: self._display.sync() self._lock.__exit__(exc_type, exc_value, traceback) def _process_pending_events(self): for __ in range(self._display.pending_events()): self._on_event(self._display.next_event()) def _run(self): while True: with self._lock: self._process_pending_events() # No more events: sleep until we get new data on the # display connection, or on the pipe used to signal # the end of the loop. rlist, wlist, xlist = select.select(self._readfds, (), ()) assert not wlist assert not xlist if self._pipe[0] in rlist: break # If we're here, rlist should contains the display fd, # and the next iteration will find some pending events. def start(self): self._thread.start() def cancel(self): if self._thread.is_alive(): # Wake up the capture thread... os.write(self._pipe[1], b'quit') # ...and wait for it to terminate. self._thread.join() for fd in self._pipe: os.close(fd) self._display.close() self._display = None class KeyboardCapture(Capture): def __init__(self): super().__init__() self._event_loop = None self._window = None self._suppressed_keys = set() self._devices = [] def _update_devices(self, display): # Find all keyboard devices. # This function is never called while the event loop thread is running, # so it is unnecessary to lock self._display_lock. keyboard_devices = [] for devinfo in display.xinput_query_device(xinput.AllDevices).devices: # Only keep slave devices. # Note: we look at pointer devices too, as some keyboards (like the # VicTop mechanical gaming keyboard) register 2 devices, including # a pointer device with a key class (to fully support NKRO). if devinfo.use not in (xinput.SlaveKeyboard, xinput.SlavePointer): continue # Ignore XTest keyboard device. if 'Virtual core XTEST keyboard' == devinfo.name: continue # Ignore disabled devices. if not devinfo.enabled: continue # Check for the presence of a key class. for c in devinfo.classes: if c.type == xinput.KeyClass: keyboard_devices.append(devinfo.deviceid) break if XINPUT_DEVICE_ID == xinput.AllDevices: self._devices = keyboard_devices else: self._devices = [XINPUT_DEVICE_ID] log.info('XInput devices: %s', ', '.join(map(str, self._devices))) def _on_event(self, event): if event.type != GenericEventCode: return if event.evtype not in (xinput.KeyPress, xinput.KeyRelease): return assert event.data.sourceid in self._devices keycode = event.data.detail modifiers = event.data.mods.effective_mods & ~0b10000 & 0xFF key = KEYCODE_TO_KEY.get(keycode) if key is None: # Not a supported key, ignore... return # ...or pass it on to a callback method. if event.evtype == xinput.KeyPress: # Ignore event if a modifier is set. if modifiers == 0: self.key_down(key) elif event.evtype == xinput.KeyRelease: self.key_up(key) def start(self): self._event_loop = XEventLoop(self._on_event, name='KeyboardCapture') with self._event_loop as display: if not display.has_extension('XInputExtension'): raise Exception('X11\'s XInput extension is required, but could not be found.') self._update_devices(display) self._window = display.screen().root self._window.xinput_select_events([ (deviceid, XINPUT_EVENT_MASK) for deviceid in self._devices ]) self._event_loop.start() def cancel(self): if self._event_loop is None: return with self._event_loop: self._suppress_keys(()) self._event_loop.cancel() def suppress(self, suppressed_keys=()): with self._event_loop: self._suppress_keys(suppressed_keys) def _grab_key(self, keycode): for deviceid in self._devices: self._window.xinput_grab_keycode(deviceid, X.CurrentTime, keycode, xinput.GrabModeAsync, xinput.GrabModeAsync, True, XINPUT_EVENT_MASK, (0, X.Mod2Mask)) def _ungrab_key(self, keycode): for deviceid in self._devices: self._window.xinput_ungrab_keycode(deviceid, keycode, (0, X.Mod2Mask)) def _suppress_keys(self, suppressed_keys): suppressed_keys = set(suppressed_keys) if self._suppressed_keys == suppressed_keys: return for key in self._suppressed_keys - suppressed_keys: self._ungrab_key(KEY_TO_KEYCODE[key]) self._suppressed_keys.remove(key) for key in suppressed_keys - self._suppressed_keys: self._grab_key(KEY_TO_KEYCODE[key]) self._suppressed_keys.add(key) assert self._suppressed_keys == suppressed_keys # Keysym to Unicode conversion table. # Taken from xterm/keysym2ucs.c KEYSYM_TO_UCS = { 0x01a1: 0x0104, # Aogonek Ą LATIN CAPITAL LETTER A WITH OGONEK 0x01a2: 0x02d8, # breve ˘ BREVE 0x01a3: 0x0141, # Lstroke Ł LATIN CAPITAL LETTER L WITH STROKE 0x01a5: 0x013d, # Lcaron Ľ LATIN CAPITAL LETTER L WITH CARON 0x01a6: 0x015a, # Sacute Ś LATIN CAPITAL LETTER S WITH ACUTE 0x01a9: 0x0160, # Scaron Š LATIN CAPITAL LETTER S WITH CARON 0x01aa: 0x015e, # Scedilla Ş LATIN CAPITAL LETTER S WITH CEDILLA 0x01ab: 0x0164, # Tcaron Ť LATIN CAPITAL LETTER T WITH CARON 0x01ac: 0x0179, # Zacute Ź LATIN CAPITAL LETTER Z WITH ACUTE 0x01ae: 0x017d, # Zcaron Ž LATIN CAPITAL LETTER Z WITH CARON 0x01af: 0x017b, # Zabovedot Ż LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x01b1: 0x0105, # aogonek ą LATIN SMALL LETTER A WITH OGONEK 0x01b2: 0x02db, # ogonek ˛ OGONEK 0x01b3: 0x0142, # lstroke ł LATIN SMALL LETTER L WITH STROKE 0x01b5: 0x013e, # lcaron ľ LATIN SMALL LETTER L WITH CARON 0x01b6: 0x015b, # sacute ś LATIN SMALL LETTER S WITH ACUTE 0x01b7: 0x02c7, # caron ˇ CARON 0x01b9: 0x0161, # scaron š LATIN SMALL LETTER S WITH CARON 0x01ba: 0x015f, # scedilla ş LATIN SMALL LETTER S WITH CEDILLA 0x01bb: 0x0165, # tcaron ť LATIN SMALL LETTER T WITH CARON 0x01bc: 0x017a, # zacute ź LATIN SMALL LETTER Z WITH ACUTE 0x01bd: 0x02dd, # doubleacute ˝ DOUBLE ACUTE ACCENT 0x01be: 0x017e, # zcaron ž LATIN SMALL LETTER Z WITH CARON 0x01bf: 0x017c, # zabovedot ż LATIN SMALL LETTER Z WITH DOT ABOVE 0x01c0: 0x0154, # Racute Ŕ LATIN CAPITAL LETTER R WITH ACUTE 0x01c3: 0x0102, # Abreve Ă LATIN CAPITAL LETTER A WITH BREVE 0x01c5: 0x0139, # Lacute Ĺ LATIN CAPITAL LETTER L WITH ACUTE 0x01c6: 0x0106, # Cacute Ć LATIN CAPITAL LETTER C WITH ACUTE 0x01c8: 0x010c, # Ccaron Č LATIN CAPITAL LETTER C WITH CARON 0x01ca: 0x0118, # Eogonek Ę LATIN CAPITAL LETTER E WITH OGONEK 0x01cc: 0x011a, # Ecaron Ě LATIN CAPITAL LETTER E WITH CARON 0x01cf: 0x010e, # Dcaron Ď LATIN CAPITAL LETTER D WITH CARON 0x01d0: 0x0110, # Dstroke Đ LATIN CAPITAL LETTER D WITH STROKE 0x01d1: 0x0143, # Nacute Ń LATIN CAPITAL LETTER N WITH ACUTE 0x01d2: 0x0147, # Ncaron Ň LATIN CAPITAL LETTER N WITH CARON 0x01d5: 0x0150, # Odoubleacute Ő LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x01d8: 0x0158, # Rcaron Ř LATIN CAPITAL LETTER R WITH CARON 0x01d9: 0x016e, # Uring Ů LATIN CAPITAL LETTER U WITH RING ABOVE 0x01db: 0x0170, # Udoubleacute Ű LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x01de: 0x0162, # Tcedilla Ţ LATIN CAPITAL LETTER T WITH CEDILLA 0x01e0: 0x0155, # racute ŕ LATIN SMALL LETTER R WITH ACUTE 0x01e3: 0x0103, # abreve ă LATIN SMALL LETTER A WITH BREVE 0x01e5: 0x013a, # lacute ĺ LATIN SMALL LETTER L WITH ACUTE 0x01e6: 0x0107, # cacute ć LATIN SMALL LETTER C WITH ACUTE 0x01e8: 0x010d, # ccaron č LATIN SMALL LETTER C WITH CARON 0x01ea: 0x0119, # eogonek ę LATIN SMALL LETTER E WITH OGONEK 0x01ec: 0x011b, # ecaron ě LATIN SMALL LETTER E WITH CARON 0x01ef: 0x010f, # dcaron ď LATIN SMALL LETTER D WITH CARON 0x01f0: 0x0111, # dstroke đ LATIN SMALL LETTER D WITH STROKE 0x01f1: 0x0144, # nacute ń LATIN SMALL LETTER N WITH ACUTE 0x01f2: 0x0148, # ncaron ň LATIN SMALL LETTER N WITH CARON 0x01f5: 0x0151, # odoubleacute ő LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x01f8: 0x0159, # rcaron ř LATIN SMALL LETTER R WITH CARON 0x01f9: 0x016f, # uring ů LATIN SMALL LETTER U WITH RING ABOVE 0x01fb: 0x0171, # udoubleacute ű LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x01fe: 0x0163, # tcedilla ţ LATIN SMALL LETTER T WITH CEDILLA 0x01ff: 0x02d9, # abovedot ˙ DOT ABOVE 0x02a1: 0x0126, # Hstroke Ħ LATIN CAPITAL LETTER H WITH STROKE 0x02a6: 0x0124, # Hcircumflex Ĥ LATIN CAPITAL LETTER H WITH CIRCUMFLEX 0x02a9: 0x0130, # Iabovedot İ LATIN CAPITAL LETTER I WITH DOT ABOVE 0x02ab: 0x011e, # Gbreve Ğ LATIN CAPITAL LETTER G WITH BREVE 0x02ac: 0x0134, # Jcircumflex Ĵ LATIN CAPITAL LETTER J WITH CIRCUMFLEX 0x02b1: 0x0127, # hstroke ħ LATIN SMALL LETTER H WITH STROKE 0x02b6: 0x0125, # hcircumflex ĥ LATIN SMALL LETTER H WITH CIRCUMFLEX 0x02b9: 0x0131, # idotless ı LATIN SMALL LETTER DOTLESS I 0x02bb: 0x011f, # gbreve ğ LATIN SMALL LETTER G WITH BREVE 0x02bc: 0x0135, # jcircumflex ĵ LATIN SMALL LETTER J WITH CIRCUMFLEX 0x02c5: 0x010a, # Cabovedot Ċ LATIN CAPITAL LETTER C WITH DOT ABOVE 0x02c6: 0x0108, # Ccircumflex Ĉ LATIN CAPITAL LETTER C WITH CIRCUMFLEX 0x02d5: 0x0120, # Gabovedot Ġ LATIN CAPITAL LETTER G WITH DOT ABOVE 0x02d8: 0x011c, # Gcircumflex Ĝ LATIN CAPITAL LETTER G WITH CIRCUMFLEX 0x02dd: 0x016c, # Ubreve Ŭ LATIN CAPITAL LETTER U WITH BREVE 0x02de: 0x015c, # Scircumflex Ŝ LATIN CAPITAL LETTER S WITH CIRCUMFLEX 0x02e5: 0x010b, # cabovedot ċ LATIN SMALL LETTER C WITH DOT ABOVE 0x02e6: 0x0109, # ccircumflex ĉ LATIN SMALL LETTER C WITH CIRCUMFLEX 0x02f5: 0x0121, # gabovedot ġ LATIN SMALL LETTER G WITH DOT ABOVE 0x02f8: 0x011d, # gcircumflex ĝ LATIN SMALL LETTER G WITH CIRCUMFLEX 0x02fd: 0x016d, # ubreve ŭ LATIN SMALL LETTER U WITH BREVE 0x02fe: 0x015d, # scircumflex ŝ LATIN SMALL LETTER S WITH CIRCUMFLEX 0x03a2: 0x0138, # kra ĸ LATIN SMALL LETTER KRA 0x03a3: 0x0156, # Rcedilla Ŗ LATIN CAPITAL LETTER R WITH CEDILLA 0x03a5: 0x0128, # Itilde Ĩ LATIN CAPITAL LETTER I WITH TILDE 0x03a6: 0x013b, # Lcedilla Ļ LATIN CAPITAL LETTER L WITH CEDILLA 0x03aa: 0x0112, # Emacron Ē LATIN CAPITAL LETTER E WITH MACRON 0x03ab: 0x0122, # Gcedilla Ģ LATIN CAPITAL LETTER G WITH CEDILLA 0x03ac: 0x0166, # Tslash Ŧ LATIN CAPITAL LETTER T WITH STROKE 0x03b3: 0x0157, # rcedilla ŗ LATIN SMALL LETTER R WITH CEDILLA 0x03b5: 0x0129, # itilde ĩ LATIN SMALL LETTER I WITH TILDE 0x03b6: 0x013c, # lcedilla ļ LATIN SMALL LETTER L WITH CEDILLA 0x03ba: 0x0113, # emacron ē LATIN SMALL LETTER E WITH MACRON 0x03bb: 0x0123, # gcedilla ģ LATIN SMALL LETTER G WITH CEDILLA 0x03bc: 0x0167, # tslash ŧ LATIN SMALL LETTER T WITH STROKE 0x03bd: 0x014a, # ENG Ŋ LATIN CAPITAL LETTER ENG 0x03bf: 0x014b, # eng ŋ LATIN SMALL LETTER ENG 0x03c0: 0x0100, # Amacron Ā LATIN CAPITAL LETTER A WITH MACRON 0x03c7: 0x012e, # Iogonek Į LATIN CAPITAL LETTER I WITH OGONEK 0x03cc: 0x0116, # Eabovedot Ė LATIN CAPITAL LETTER E WITH DOT ABOVE 0x03cf: 0x012a, # Imacron Ī LATIN CAPITAL LETTER I WITH MACRON 0x03d1: 0x0145, # Ncedilla Ņ LATIN CAPITAL LETTER N WITH CEDILLA 0x03d2: 0x014c, # Omacron Ō LATIN CAPITAL LETTER O WITH MACRON 0x03d3: 0x0136, # Kcedilla Ķ LATIN CAPITAL LETTER K WITH CEDILLA 0x03d9: 0x0172, # Uogonek Ų LATIN CAPITAL LETTER U WITH OGONEK 0x03dd: 0x0168, # Utilde Ũ LATIN CAPITAL LETTER U WITH TILDE 0x03de: 0x016a, # Umacron Ū LATIN CAPITAL LETTER U WITH MACRON 0x03e0: 0x0101, # amacron ā LATIN SMALL LETTER A WITH MACRON 0x03e7: 0x012f, # iogonek į LATIN SMALL LETTER I WITH OGONEK 0x03ec: 0x0117, # eabovedot ė LATIN SMALL LETTER E WITH DOT ABOVE 0x03ef: 0x012b, # imacron ī LATIN SMALL LETTER I WITH MACRON 0x03f1: 0x0146, # ncedilla ņ LATIN SMALL LETTER N WITH CEDILLA 0x03f2: 0x014d, # omacron ō LATIN SMALL LETTER O WITH MACRON 0x03f3: 0x0137, # kcedilla ķ LATIN SMALL LETTER K WITH CEDILLA 0x03f9: 0x0173, # uogonek ų LATIN SMALL LETTER U WITH OGONEK 0x03fd: 0x0169, # utilde ũ LATIN SMALL LETTER U WITH TILDE 0x03fe: 0x016b, # umacron ū LATIN SMALL LETTER U WITH MACRON 0x047e: 0x203e, # overline ‾ OVERLINE 0x04a1: 0x3002, # kana_fullstop 。 IDEOGRAPHIC FULL STOP 0x04a2: 0x300c, # kana_openingbracket 「 LEFT CORNER BRACKET 0x04a3: 0x300d, # kana_closingbracket 」 RIGHT CORNER BRACKET 0x04a4: 0x3001, # kana_comma 、 IDEOGRAPHIC COMMA 0x04a5: 0x30fb, # kana_conjunctive ・ KATAKANA MIDDLE DOT 0x04a6: 0x30f2, # kana_WO ヲ KATAKANA LETTER WO 0x04a7: 0x30a1, # kana_a ァ KATAKANA LETTER SMALL A 0x04a8: 0x30a3, # kana_i ィ KATAKANA LETTER SMALL I 0x04a9: 0x30a5, # kana_u ゥ KATAKANA LETTER SMALL U 0x04aa: 0x30a7, # kana_e ェ KATAKANA LETTER SMALL E 0x04ab: 0x30a9, # kana_o ォ KATAKANA LETTER SMALL O 0x04ac: 0x30e3, # kana_ya ャ KATAKANA LETTER SMALL YA 0x04ad: 0x30e5, # kana_yu ュ KATAKANA LETTER SMALL YU 0x04ae: 0x30e7, # kana_yo ョ KATAKANA LETTER SMALL YO 0x04af: 0x30c3, # kana_tsu ッ KATAKANA LETTER SMALL TU 0x04b0: 0x30fc, # prolongedsound ー KATAKANA-HIRAGANA PROLONGED SOUND MARK 0x04b1: 0x30a2, # kana_A ア KATAKANA LETTER A 0x04b2: 0x30a4, # kana_I イ KATAKANA LETTER I 0x04b3: 0x30a6, # kana_U ウ KATAKANA LETTER U 0x04b4: 0x30a8, # kana_E エ KATAKANA LETTER E 0x04b5: 0x30aa, # kana_O オ KATAKANA LETTER O 0x04b6: 0x30ab, # kana_KA カ KATAKANA LETTER KA 0x04b7: 0x30ad, # kana_KI キ KATAKANA LETTER KI 0x04b8: 0x30af, # kana_KU ク KATAKANA LETTER KU 0x04b9: 0x30b1, # kana_KE ケ KATAKANA LETTER KE 0x04ba: 0x30b3, # kana_KO コ KATAKANA LETTER KO 0x04bb: 0x30b5, # kana_SA サ KATAKANA LETTER SA 0x04bc: 0x30b7, # kana_SHI シ KATAKANA LETTER SI 0x04bd: 0x30b9, # kana_SU ス KATAKANA LETTER SU 0x04be: 0x30bb, # kana_SE セ KATAKANA LETTER SE 0x04bf: 0x30bd, # kana_SO ソ KATAKANA LETTER SO 0x04c0: 0x30bf, # kana_TA タ KATAKANA LETTER TA 0x04c1: 0x30c1, # kana_CHI チ KATAKANA LETTER TI 0x04c2: 0x30c4, # kana_TSU ツ KATAKANA LETTER TU 0x04c3: 0x30c6, # kana_TE テ KATAKANA LETTER TE 0x04c4: 0x30c8, # kana_TO ト KATAKANA LETTER TO 0x04c5: 0x30ca, # kana_NA ナ KATAKANA LETTER NA 0x04c6: 0x30cb, # kana_NI ニ KATAKANA LETTER NI 0x04c7: 0x30cc, # kana_NU ヌ KATAKANA LETTER NU 0x04c8: 0x30cd, # kana_NE ネ KATAKANA LETTER NE 0x04c9: 0x30ce, # kana_NO ノ KATAKANA LETTER NO 0x04ca: 0x30cf, # kana_HA ハ KATAKANA LETTER HA 0x04cb: 0x30d2, # kana_HI ヒ KATAKANA LETTER HI 0x04cc: 0x30d5, # kana_FU フ KATAKANA LETTER HU 0x04cd: 0x30d8, # kana_HE ヘ KATAKANA LETTER HE 0x04ce: 0x30db, # kana_HO ホ KATAKANA LETTER HO 0x04cf: 0x30de, # kana_MA マ KATAKANA LETTER MA 0x04d0: 0x30df, # kana_MI ミ KATAKANA LETTER MI 0x04d1: 0x30e0, # kana_MU ム KATAKANA LETTER MU 0x04d2: 0x30e1, # kana_ME メ KATAKANA LETTER ME 0x04d3: 0x30e2, # kana_MO モ KATAKANA LETTER MO 0x04d4: 0x30e4, # kana_YA ヤ KATAKANA LETTER YA 0x04d5: 0x30e6, # kana_YU ユ KATAKANA LETTER YU 0x04d6: 0x30e8, # kana_YO ヨ KATAKANA LETTER YO 0x04d7: 0x30e9, # kana_RA ラ KATAKANA LETTER RA 0x04d8: 0x30ea, # kana_RI リ KATAKANA LETTER RI 0x04d9: 0x30eb, # kana_RU ル KATAKANA LETTER RU 0x04da: 0x30ec, # kana_RE レ KATAKANA LETTER RE 0x04db: 0x30ed, # kana_RO ロ KATAKANA LETTER RO 0x04dc: 0x30ef, # kana_WA ワ KATAKANA LETTER WA 0x04dd: 0x30f3, # kana_N ン KATAKANA LETTER N 0x04de: 0x309b, # voicedsound ゛ KATAKANA-HIRAGANA VOICED SOUND MARK 0x04df: 0x309c, # semivoicedsound ゜ KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK 0x05ac: 0x060c, # Arabic_comma ، ARABIC COMMA 0x05bb: 0x061b, # Arabic_semicolon ؛ ARABIC SEMICOLON 0x05bf: 0x061f, # Arabic_question_mark ؟ ARABIC QUESTION MARK 0x05c1: 0x0621, # Arabic_hamza ء ARABIC LETTER HAMZA 0x05c2: 0x0622, # Arabic_maddaonalef آ ARABIC LETTER ALEF WITH MADDA ABOVE 0x05c3: 0x0623, # Arabic_hamzaonalef أ ARABIC LETTER ALEF WITH HAMZA ABOVE 0x05c4: 0x0624, # Arabic_hamzaonwaw ؤ ARABIC LETTER WAW WITH HAMZA ABOVE 0x05c5: 0x0625, # Arabic_hamzaunderalef إ ARABIC LETTER ALEF WITH HAMZA BELOW 0x05c6: 0x0626, # Arabic_hamzaonyeh ئ ARABIC LETTER YEH WITH HAMZA ABOVE 0x05c7: 0x0627, # Arabic_alef ا ARABIC LETTER ALEF 0x05c8: 0x0628, # Arabic_beh ب ARABIC LETTER BEH 0x05c9: 0x0629, # Arabic_tehmarbuta ة ARABIC LETTER TEH MARBUTA 0x05ca: 0x062a, # Arabic_teh ت ARABIC LETTER TEH 0x05cb: 0x062b, # Arabic_theh ث ARABIC LETTER THEH 0x05cc: 0x062c, # Arabic_jeem ج ARABIC LETTER JEEM 0x05cd: 0x062d, # Arabic_hah ح ARABIC LETTER HAH 0x05ce: 0x062e, # Arabic_khah خ ARABIC LETTER KHAH 0x05cf: 0x062f, # Arabic_dal د ARABIC LETTER DAL 0x05d0: 0x0630, # Arabic_thal ذ ARABIC LETTER THAL 0x05d1: 0x0631, # Arabic_ra ر ARABIC LETTER REH 0x05d2: 0x0632, # Arabic_zain ز ARABIC LETTER ZAIN 0x05d3: 0x0633, # Arabic_seen س ARABIC LETTER SEEN 0x05d4: 0x0634, # Arabic_sheen ش ARABIC LETTER SHEEN 0x05d5: 0x0635, # Arabic_sad ص ARABIC LETTER SAD 0x05d6: 0x0636, # Arabic_dad ض ARABIC LETTER DAD 0x05d7: 0x0637, # Arabic_tah ط ARABIC LETTER TAH 0x05d8: 0x0638, # Arabic_zah ظ ARABIC LETTER ZAH 0x05d9: 0x0639, # Arabic_ain ع ARABIC LETTER AIN 0x05da: 0x063a, # Arabic_ghain غ ARABIC LETTER GHAIN 0x05e0: 0x0640, # Arabic_tatweel ـ ARABIC TATWEEL 0x05e1: 0x0641, # Arabic_feh ف ARABIC LETTER FEH 0x05e2: 0x0642, # Arabic_qaf ق ARABIC LETTER QAF 0x05e3: 0x0643, # Arabic_kaf ك ARABIC LETTER KAF 0x05e4: 0x0644, # Arabic_lam ل ARABIC LETTER LAM 0x05e5: 0x0645, # Arabic_meem م ARABIC LETTER MEEM 0x05e6: 0x0646, # Arabic_noon ن ARABIC LETTER NOON 0x05e7: 0x0647, # Arabic_ha ه ARABIC LETTER HEH 0x05e8: 0x0648, # Arabic_waw و ARABIC LETTER WAW 0x05e9: 0x0649, # Arabic_alefmaksura ى ARABIC LETTER ALEF MAKSURA 0x05ea: 0x064a, # Arabic_yeh ي ARABIC LETTER YEH 0x05eb: 0x064b, # Arabic_fathatan ً ARABIC FATHATAN 0x05ec: 0x064c, # Arabic_dammatan ٌ ARABIC DAMMATAN 0x05ed: 0x064d, # Arabic_kasratan ٍ ARABIC KASRATAN 0x05ee: 0x064e, # Arabic_fatha َ ARABIC FATHA 0x05ef: 0x064f, # Arabic_damma ُ ARABIC DAMMA 0x05f0: 0x0650, # Arabic_kasra ِ ARABIC KASRA 0x05f1: 0x0651, # Arabic_shadda ّ ARABIC SHADDA 0x05f2: 0x0652, # Arabic_sukun ْ ARABIC SUKUN 0x06a1: 0x0452, # Serbian_dje ђ CYRILLIC SMALL LETTER DJE 0x06a2: 0x0453, # Macedonia_gje ѓ CYRILLIC SMALL LETTER GJE 0x06a3: 0x0451, # Cyrillic_io ё CYRILLIC SMALL LETTER IO 0x06a4: 0x0454, # Ukrainian_ie є CYRILLIC SMALL LETTER UKRAINIAN IE 0x06a5: 0x0455, # Macedonia_dse ѕ CYRILLIC SMALL LETTER DZE 0x06a6: 0x0456, # Ukrainian_i і CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x06a7: 0x0457, # Ukrainian_yi ї CYRILLIC SMALL LETTER YI 0x06a8: 0x0458, # Cyrillic_je ј CYRILLIC SMALL LETTER JE 0x06a9: 0x0459, # Cyrillic_lje љ CYRILLIC SMALL LETTER LJE 0x06aa: 0x045a, # Cyrillic_nje њ CYRILLIC SMALL LETTER NJE 0x06ab: 0x045b, # Serbian_tshe ћ CYRILLIC SMALL LETTER TSHE 0x06ac: 0x045c, # Macedonia_kje ќ CYRILLIC SMALL LETTER KJE 0x06ad: 0x0491, # Ukrainian_ghe_with_upturn ґ CYRILLIC SMALL LETTER GHE WITH UPTURN 0x06ae: 0x045e, # Byelorussian_shortu ў CYRILLIC SMALL LETTER SHORT U 0x06af: 0x045f, # Cyrillic_dzhe џ CYRILLIC SMALL LETTER DZHE 0x06b0: 0x2116, # numerosign № NUMERO SIGN 0x06b1: 0x0402, # Serbian_DJE Ђ CYRILLIC CAPITAL LETTER DJE 0x06b2: 0x0403, # Macedonia_GJE Ѓ CYRILLIC CAPITAL LETTER GJE 0x06b3: 0x0401, # Cyrillic_IO Ё CYRILLIC CAPITAL LETTER IO 0x06b4: 0x0404, # Ukrainian_IE Є CYRILLIC CAPITAL LETTER UKRAINIAN IE 0x06b5: 0x0405, # Macedonia_DSE Ѕ CYRILLIC CAPITAL LETTER DZE 0x06b6: 0x0406, # Ukrainian_I І CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x06b7: 0x0407, # Ukrainian_YI Ї CYRILLIC CAPITAL LETTER YI 0x06b8: 0x0408, # Cyrillic_JE Ј CYRILLIC CAPITAL LETTER JE 0x06b9: 0x0409, # Cyrillic_LJE Љ CYRILLIC CAPITAL LETTER LJE 0x06ba: 0x040a, # Cyrillic_NJE Њ CYRILLIC CAPITAL LETTER NJE 0x06bb: 0x040b, # Serbian_TSHE Ћ CYRILLIC CAPITAL LETTER TSHE 0x06bc: 0x040c, # Macedonia_KJE Ќ CYRILLIC CAPITAL LETTER KJE 0x06bd: 0x0490, # Ukrainian_GHE_WITH_UPTURN Ґ CYRILLIC CAPITAL LETTER GHE WITH UPTURN 0x06be: 0x040e, # Byelorussian_SHORTU Ў CYRILLIC CAPITAL LETTER SHORT U 0x06bf: 0x040f, # Cyrillic_DZHE Џ CYRILLIC CAPITAL LETTER DZHE 0x06c0: 0x044e, # Cyrillic_yu ю CYRILLIC SMALL LETTER YU 0x06c1: 0x0430, # Cyrillic_a а CYRILLIC SMALL LETTER A 0x06c2: 0x0431, # Cyrillic_be б CYRILLIC SMALL LETTER BE 0x06c3: 0x0446, # Cyrillic_tse ц CYRILLIC SMALL LETTER TSE 0x06c4: 0x0434, # Cyrillic_de д CYRILLIC SMALL LETTER DE 0x06c5: 0x0435, # Cyrillic_ie е CYRILLIC SMALL LETTER IE 0x06c6: 0x0444, # Cyrillic_ef ф CYRILLIC SMALL LETTER EF 0x06c7: 0x0433, # Cyrillic_ghe г CYRILLIC SMALL LETTER GHE 0x06c8: 0x0445, # Cyrillic_ha х CYRILLIC SMALL LETTER HA 0x06c9: 0x0438, # Cyrillic_i и CYRILLIC SMALL LETTER I 0x06ca: 0x0439, # Cyrillic_shorti й CYRILLIC SMALL LETTER SHORT I 0x06cb: 0x043a, # Cyrillic_ka к CYRILLIC SMALL LETTER KA 0x06cc: 0x043b, # Cyrillic_el л CYRILLIC SMALL LETTER EL 0x06cd: 0x043c, # Cyrillic_em м CYRILLIC SMALL LETTER EM 0x06ce: 0x043d, # Cyrillic_en н CYRILLIC SMALL LETTER EN 0x06cf: 0x043e, # Cyrillic_o о CYRILLIC SMALL LETTER O 0x06d0: 0x043f, # Cyrillic_pe п CYRILLIC SMALL LETTER PE 0x06d1: 0x044f, # Cyrillic_ya я CYRILLIC SMALL LETTER YA 0x06d2: 0x0440, # Cyrillic_er р CYRILLIC SMALL LETTER ER 0x06d3: 0x0441, # Cyrillic_es с CYRILLIC SMALL LETTER ES 0x06d4: 0x0442, # Cyrillic_te т CYRILLIC SMALL LETTER TE 0x06d5: 0x0443, # Cyrillic_u у CYRILLIC SMALL LETTER U 0x06d6: 0x0436, # Cyrillic_zhe ж CYRILLIC SMALL LETTER ZHE 0x06d7: 0x0432, # Cyrillic_ve в CYRILLIC SMALL LETTER VE 0x06d8: 0x044c, # Cyrillic_softsign ь CYRILLIC SMALL LETTER SOFT SIGN 0x06d9: 0x044b, # Cyrillic_yeru ы CYRILLIC SMALL LETTER YERU 0x06da: 0x0437, # Cyrillic_ze з CYRILLIC SMALL LETTER ZE 0x06db: 0x0448, # Cyrillic_sha ш CYRILLIC SMALL LETTER SHA 0x06dc: 0x044d, # Cyrillic_e э CYRILLIC SMALL LETTER E 0x06dd: 0x0449, # Cyrillic_shcha щ CYRILLIC SMALL LETTER SHCHA 0x06de: 0x0447, # Cyrillic_che ч CYRILLIC SMALL LETTER CHE 0x06df: 0x044a, # Cyrillic_hardsign ъ CYRILLIC SMALL LETTER HARD SIGN 0x06e0: 0x042e, # Cyrillic_YU Ю CYRILLIC CAPITAL LETTER YU 0x06e1: 0x0410, # Cyrillic_A А CYRILLIC CAPITAL LETTER A 0x06e2: 0x0411, # Cyrillic_BE Б CYRILLIC CAPITAL LETTER BE 0x06e3: 0x0426, # Cyrillic_TSE Ц CYRILLIC CAPITAL LETTER TSE 0x06e4: 0x0414, # Cyrillic_DE Д CYRILLIC CAPITAL LETTER DE 0x06e5: 0x0415, # Cyrillic_IE Е CYRILLIC CAPITAL LETTER IE 0x06e6: 0x0424, # Cyrillic_EF Ф CYRILLIC CAPITAL LETTER EF 0x06e7: 0x0413, # Cyrillic_GHE Г CYRILLIC CAPITAL LETTER GHE 0x06e8: 0x0425, # Cyrillic_HA Х CYRILLIC CAPITAL LETTER HA 0x06e9: 0x0418, # Cyrillic_I И CYRILLIC CAPITAL LETTER I 0x06ea: 0x0419, # Cyrillic_SHORTI Й CYRILLIC CAPITAL LETTER SHORT I 0x06eb: 0x041a, # Cyrillic_KA К CYRILLIC CAPITAL LETTER KA 0x06ec: 0x041b, # Cyrillic_EL Л CYRILLIC CAPITAL LETTER EL 0x06ed: 0x041c, # Cyrillic_EM М CYRILLIC CAPITAL LETTER EM 0x06ee: 0x041d, # Cyrillic_EN Н CYRILLIC CAPITAL LETTER EN 0x06ef: 0x041e, # Cyrillic_O О CYRILLIC CAPITAL LETTER O 0x06f0: 0x041f, # Cyrillic_PE П CYRILLIC CAPITAL LETTER PE 0x06f1: 0x042f, # Cyrillic_YA Я CYRILLIC CAPITAL LETTER YA 0x06f2: 0x0420, # Cyrillic_ER Р CYRILLIC CAPITAL LETTER ER 0x06f3: 0x0421, # Cyrillic_ES С CYRILLIC CAPITAL LETTER ES 0x06f4: 0x0422, # Cyrillic_TE Т CYRILLIC CAPITAL LETTER TE 0x06f5: 0x0423, # Cyrillic_U У CYRILLIC CAPITAL LETTER U 0x06f6: 0x0416, # Cyrillic_ZHE Ж CYRILLIC CAPITAL LETTER ZHE 0x06f7: 0x0412, # Cyrillic_VE В CYRILLIC CAPITAL LETTER VE 0x06f8: 0x042c, # Cyrillic_SOFTSIGN Ь CYRILLIC CAPITAL LETTER SOFT SIGN 0x06f9: 0x042b, # Cyrillic_YERU Ы CYRILLIC CAPITAL LETTER YERU 0x06fa: 0x0417, # Cyrillic_ZE З CYRILLIC CAPITAL LETTER ZE 0x06fb: 0x0428, # Cyrillic_SHA Ш CYRILLIC CAPITAL LETTER SHA 0x06fc: 0x042d, # Cyrillic_E Э CYRILLIC CAPITAL LETTER E 0x06fd: 0x0429, # Cyrillic_SHCHA Щ CYRILLIC CAPITAL LETTER SHCHA 0x06fe: 0x0427, # Cyrillic_CHE Ч CYRILLIC CAPITAL LETTER CHE 0x06ff: 0x042a, # Cyrillic_HARDSIGN Ъ CYRILLIC CAPITAL LETTER HARD SIGN 0x07a1: 0x0386, # Greek_ALPHAaccent Ά GREEK CAPITAL LETTER ALPHA WITH TONOS 0x07a2: 0x0388, # Greek_EPSILONaccent Έ GREEK CAPITAL LETTER EPSILON WITH TONOS 0x07a3: 0x0389, # Greek_ETAaccent Ή GREEK CAPITAL LETTER ETA WITH TONOS 0x07a4: 0x038a, # Greek_IOTAaccent Ί GREEK CAPITAL LETTER IOTA WITH TONOS 0x07a5: 0x03aa, # Greek_IOTAdiaeresis Ϊ GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x07a7: 0x038c, # Greek_OMICRONaccent Ό GREEK CAPITAL LETTER OMICRON WITH TONOS 0x07a8: 0x038e, # Greek_UPSILONaccent Ύ GREEK CAPITAL LETTER UPSILON WITH TONOS 0x07a9: 0x03ab, # Greek_UPSILONdieresis Ϋ GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x07ab: 0x038f, # Greek_OMEGAaccent Ώ GREEK CAPITAL LETTER OMEGA WITH TONOS 0x07ae: 0x0385, # Greek_accentdieresis ΅ GREEK DIALYTIKA TONOS 0x07af: 0x2015, # Greek_horizbar ― HORIZONTAL BAR 0x07b1: 0x03ac, # Greek_alphaaccent ά GREEK SMALL LETTER ALPHA WITH TONOS 0x07b2: 0x03ad, # Greek_epsilonaccent έ GREEK SMALL LETTER EPSILON WITH TONOS 0x07b3: 0x03ae, # Greek_etaaccent ή GREEK SMALL LETTER ETA WITH TONOS 0x07b4: 0x03af, # Greek_iotaaccent ί GREEK SMALL LETTER IOTA WITH TONOS 0x07b5: 0x03ca, # Greek_iotadieresis ϊ GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x07b6: 0x0390, # Greek_iotaaccentdieresis ΐ GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS 0x07b7: 0x03cc, # Greek_omicronaccent ό GREEK SMALL LETTER OMICRON WITH TONOS 0x07b8: 0x03cd, # Greek_upsilonaccent ύ GREEK SMALL LETTER UPSILON WITH TONOS 0x07b9: 0x03cb, # Greek_upsilondieresis ϋ GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x07ba: 0x03b0, # Greek_upsilonaccentdieresis ΰ GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS 0x07bb: 0x03ce, # Greek_omegaaccent ώ GREEK SMALL LETTER OMEGA WITH TONOS 0x07c1: 0x0391, # Greek_ALPHA Α GREEK CAPITAL LETTER ALPHA 0x07c2: 0x0392, # Greek_BETA Β GREEK CAPITAL LETTER BETA 0x07c3: 0x0393, # Greek_GAMMA Γ GREEK CAPITAL LETTER GAMMA 0x07c4: 0x0394, # Greek_DELTA Δ GREEK CAPITAL LETTER DELTA 0x07c5: 0x0395, # Greek_EPSILON Ε GREEK CAPITAL LETTER EPSILON 0x07c6: 0x0396, # Greek_ZETA Ζ GREEK CAPITAL LETTER ZETA 0x07c7: 0x0397, # Greek_ETA Η GREEK CAPITAL LETTER ETA 0x07c8: 0x0398, # Greek_THETA Θ GREEK CAPITAL LETTER THETA 0x07c9: 0x0399, # Greek_IOTA Ι GREEK CAPITAL LETTER IOTA 0x07ca: 0x039a, # Greek_KAPPA Κ GREEK CAPITAL LETTER KAPPA 0x07cb: 0x039b, # Greek_LAMBDA Λ GREEK CAPITAL LETTER LAMDA 0x07cc: 0x039c, # Greek_MU Μ GREEK CAPITAL LETTER MU 0x07cd: 0x039d, # Greek_NU Ν GREEK CAPITAL LETTER NU 0x07ce: 0x039e, # Greek_XI Ξ GREEK CAPITAL LETTER XI 0x07cf: 0x039f, # Greek_OMICRON Ο GREEK CAPITAL LETTER OMICRON 0x07d0: 0x03a0, # Greek_PI Π GREEK CAPITAL LETTER PI 0x07d1: 0x03a1, # Greek_RHO Ρ GREEK CAPITAL LETTER RHO 0x07d2: 0x03a3, # Greek_SIGMA Σ GREEK CAPITAL LETTER SIGMA 0x07d4: 0x03a4, # Greek_TAU Τ GREEK CAPITAL LETTER TAU 0x07d5: 0x03a5, # Greek_UPSILON Υ GREEK CAPITAL LETTER UPSILON 0x07d6: 0x03a6, # Greek_PHI Φ GREEK CAPITAL LETTER PHI 0x07d7: 0x03a7, # Greek_CHI Χ GREEK CAPITAL LETTER CHI 0x07d8: 0x03a8, # Greek_PSI Ψ GREEK CAPITAL LETTER PSI 0x07d9: 0x03a9, # Greek_OMEGA Ω GREEK CAPITAL LETTER OMEGA 0x07e1: 0x03b1, # Greek_alpha α GREEK SMALL LETTER ALPHA 0x07e2: 0x03b2, # Greek_beta β GREEK SMALL LETTER BETA 0x07e3: 0x03b3, # Greek_gamma γ GREEK SMALL LETTER GAMMA 0x07e4: 0x03b4, # Greek_delta δ GREEK SMALL LETTER DELTA 0x07e5: 0x03b5, # Greek_epsilon ε GREEK SMALL LETTER EPSILON 0x07e6: 0x03b6, # Greek_zeta ζ GREEK SMALL LETTER ZETA 0x07e7: 0x03b7, # Greek_eta η GREEK SMALL LETTER ETA 0x07e8: 0x03b8, # Greek_theta θ GREEK SMALL LETTER THETA 0x07e9: 0x03b9, # Greek_iota ι GREEK SMALL LETTER IOTA 0x07ea: 0x03ba, # Greek_kappa κ GREEK SMALL LETTER KAPPA 0x07eb: 0x03bb, # Greek_lambda λ GREEK SMALL LETTER LAMDA 0x07ec: 0x03bc, # Greek_mu μ GREEK SMALL LETTER MU 0x07ed: 0x03bd, # Greek_nu ν GREEK SMALL LETTER NU 0x07ee: 0x03be, # Greek_xi ξ GREEK SMALL LETTER XI 0x07ef: 0x03bf, # Greek_omicron ο GREEK SMALL LETTER OMICRON 0x07f0: 0x03c0, # Greek_pi π GREEK SMALL LETTER PI 0x07f1: 0x03c1, # Greek_rho ρ GREEK SMALL LETTER RHO 0x07f2: 0x03c3, # Greek_sigma σ GREEK SMALL LETTER SIGMA 0x07f3: 0x03c2, # Greek_finalsmallsigma ς GREEK SMALL LETTER FINAL SIGMA 0x07f4: 0x03c4, # Greek_tau τ GREEK SMALL LETTER TAU 0x07f5: 0x03c5, # Greek_upsilon υ GREEK SMALL LETTER UPSILON 0x07f6: 0x03c6, # Greek_phi φ GREEK SMALL LETTER PHI 0x07f7: 0x03c7, # Greek_chi χ GREEK SMALL LETTER CHI 0x07f8: 0x03c8, # Greek_psi ψ GREEK SMALL LETTER PSI 0x07f9: 0x03c9, # Greek_omega ω GREEK SMALL LETTER OMEGA 0x08a1: 0x23b7, # leftradical ⎷ RADICAL SYMBOL BOTTOM 0x08a2: 0x250c, # topleftradical ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT 0x08a3: 0x2500, # horizconnector ─ BOX DRAWINGS LIGHT HORIZONTAL 0x08a4: 0x2320, # topintegral ⌠ TOP HALF INTEGRAL 0x08a5: 0x2321, # botintegral ⌡ BOTTOM HALF INTEGRAL 0x08a6: 0x2502, # vertconnector │ BOX DRAWINGS LIGHT VERTICAL 0x08a7: 0x23a1, # topleftsqbracket ⎡ LEFT SQUARE BRACKET UPPER CORNER 0x08a8: 0x23a3, # botleftsqbracket ⎣ LEFT SQUARE BRACKET LOWER CORNER 0x08a9: 0x23a4, # toprightsqbracket ⎤ RIGHT SQUARE BRACKET UPPER CORNER 0x08aa: 0x23a6, # botrightsqbracket ⎦ RIGHT SQUARE BRACKET LOWER CORNER 0x08ab: 0x239b, # topleftparens ⎛ LEFT PARENTHESIS UPPER HOOK 0x08ac: 0x239d, # botleftparens ⎝ LEFT PARENTHESIS LOWER HOOK 0x08ad: 0x239e, # toprightparens ⎞ RIGHT PARENTHESIS UPPER HOOK 0x08ae: 0x23a0, # botrightparens ⎠ RIGHT PARENTHESIS LOWER HOOK 0x08af: 0x23a8, # leftmiddlecurlybrace ⎨ LEFT CURLY BRACKET MIDDLE PIECE 0x08b0: 0x23ac, # rightmiddlecurlybrace ⎬ RIGHT CURLY BRACKET MIDDLE PIECE 0x08bc: 0x2264, # lessthanequal ≤ LESS-THAN OR EQUAL TO 0x08bd: 0x2260, # notequal ≠ NOT EQUAL TO 0x08be: 0x2265, # greaterthanequal ≥ GREATER-THAN OR EQUAL TO 0x08bf: 0x222b, # integral ∫ INTEGRAL 0x08c0: 0x2234, # therefore ∴ THEREFORE 0x08c1: 0x221d, # variation ∝ PROPORTIONAL TO 0x08c2: 0x221e, # infinity ∞ INFINITY 0x08c5: 0x2207, # nabla ∇ NABLA 0x08c8: 0x223c, # approximate ∼ TILDE OPERATOR 0x08c9: 0x2243, # similarequal ≃ ASYMPTOTICALLY EQUAL TO 0x08cd: 0x21d4, # ifonlyif ⇔ LEFT RIGHT DOUBLE ARROW 0x08ce: 0x21d2, # implies ⇒ RIGHTWARDS DOUBLE ARROW 0x08cf: 0x2261, # identical ≡ IDENTICAL TO 0x08d6: 0x221a, # radical √ SQUARE ROOT 0x08da: 0x2282, # includedin ⊂ SUBSET OF 0x08db: 0x2283, # includes ⊃ SUPERSET OF 0x08dc: 0x2229, # intersection ∩ INTERSECTION 0x08dd: 0x222a, # union ∪ UNION 0x08de: 0x2227, # logicaland ∧ LOGICAL AND 0x08df: 0x2228, # logicalor ∨ LOGICAL OR 0x08ef: 0x2202, # partialderivative ∂ PARTIAL DIFFERENTIAL 0x08f6: 0x0192, # function ƒ LATIN SMALL LETTER F WITH HOOK 0x08fb: 0x2190, # leftarrow ← LEFTWARDS ARROW 0x08fc: 0x2191, # uparrow ↑ UPWARDS ARROW 0x08fd: 0x2192, # rightarrow → RIGHTWARDS ARROW 0x08fe: 0x2193, # downarrow ↓ DOWNWARDS ARROW 0x09df: 0x2422, # blank ␢ BLANK SYMBOL 0x09e0: 0x25c6, # soliddiamond ◆ BLACK DIAMOND 0x09e1: 0x2592, # checkerboard ▒ MEDIUM SHADE 0x09e2: 0x2409, # ht ␉ SYMBOL FOR HORIZONTAL TABULATION 0x09e3: 0x240c, # ff ␌ SYMBOL FOR FORM FEED 0x09e4: 0x240d, # cr ␍ SYMBOL FOR CARRIAGE RETURN 0x09e5: 0x240a, # lf ␊ SYMBOL FOR LINE FEED 0x09e8: 0x2424, # nl ␤ SYMBOL FOR NEWLINE 0x09e9: 0x240b, # vt ␋ SYMBOL FOR VERTICAL TABULATION 0x09ea: 0x2518, # lowrightcorner ┘ BOX DRAWINGS LIGHT UP AND LEFT 0x09eb: 0x2510, # uprightcorner ┐ BOX DRAWINGS LIGHT DOWN AND LEFT 0x09ec: 0x250c, # upleftcorner ┌ BOX DRAWINGS LIGHT DOWN AND RIGHT 0x09ed: 0x2514, # lowleftcorner └ BOX DRAWINGS LIGHT UP AND RIGHT 0x09ee: 0x253c, # crossinglines ┼ BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x09ef: 0x23ba, # horizlinescan1 ⎺ HORIZONTAL SCAN LINE-1 0x09f0: 0x23bb, # horizlinescan3 ⎻ HORIZONTAL SCAN LINE-3 0x09f1: 0x2500, # horizlinescan5 ─ BOX DRAWINGS LIGHT HORIZONTAL 0x09f2: 0x23bc, # horizlinescan7 ⎼ HORIZONTAL SCAN LINE-7 0x09f3: 0x23bd, # horizlinescan9 ⎽ HORIZONTAL SCAN LINE-9 0x09f4: 0x251c, # leftt ├ BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x09f5: 0x2524, # rightt ┤ BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x09f6: 0x2534, # bott ┴ BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x09f7: 0x252c, # topt ┬ BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x09f8: 0x2502, # vertbar │ BOX DRAWINGS LIGHT VERTICAL 0x0aa1: 0x2003, # emspace   EM SPACE 0x0aa2: 0x2002, # enspace   EN SPACE 0x0aa3: 0x2004, # em3space   THREE-PER-EM SPACE 0x0aa4: 0x2005, # em4space   FOUR-PER-EM SPACE 0x0aa5: 0x2007, # digitspace   FIGURE SPACE 0x0aa6: 0x2008, # punctspace   PUNCTUATION SPACE 0x0aa7: 0x2009, # thinspace   THIN SPACE 0x0aa8: 0x200a, # hairspace   HAIR SPACE 0x0aa9: 0x2014, # emdash — EM DASH 0x0aaa: 0x2013, # endash – EN DASH 0x0aac: 0x2423, # signifblank ␣ OPEN BOX 0x0aae: 0x2026, # ellipsis … HORIZONTAL ELLIPSIS 0x0aaf: 0x2025, # doubbaselinedot ‥ TWO DOT LEADER 0x0ab0: 0x2153, # onethird ⅓ VULGAR FRACTION ONE THIRD 0x0ab1: 0x2154, # twothirds ⅔ VULGAR FRACTION TWO THIRDS 0x0ab2: 0x2155, # onefifth ⅕ VULGAR FRACTION ONE FIFTH 0x0ab3: 0x2156, # twofifths ⅖ VULGAR FRACTION TWO FIFTHS 0x0ab4: 0x2157, # threefifths ⅗ VULGAR FRACTION THREE FIFTHS 0x0ab5: 0x2158, # fourfifths ⅘ VULGAR FRACTION FOUR FIFTHS 0x0ab6: 0x2159, # onesixth ⅙ VULGAR FRACTION ONE SIXTH 0x0ab7: 0x215a, # fivesixths ⅚ VULGAR FRACTION FIVE SIXTHS 0x0ab8: 0x2105, # careof ℅ CARE OF 0x0abb: 0x2012, # figdash ‒ FIGURE DASH 0x0abc: 0x2329, # leftanglebracket 〈 LEFT-POINTING ANGLE BRACKET 0x0abd: 0x002e, # decimalpoint . FULL STOP 0x0abe: 0x232a, # rightanglebracket 〉 RIGHT-POINTING ANGLE BRACKET 0x0ac3: 0x215b, # oneeighth ⅛ VULGAR FRACTION ONE EIGHTH 0x0ac4: 0x215c, # threeeighths ⅜ VULGAR FRACTION THREE EIGHTHS 0x0ac5: 0x215d, # fiveeighths ⅝ VULGAR FRACTION FIVE EIGHTHS 0x0ac6: 0x215e, # seveneighths ⅞ VULGAR FRACTION SEVEN EIGHTHS 0x0ac9: 0x2122, # trademark ™ TRADE MARK SIGN 0x0aca: 0x2613, # signaturemark ☓ SALTIRE 0x0acc: 0x25c1, # leftopentriangle ◁ WHITE LEFT-POINTING TRIANGLE 0x0acd: 0x25b7, # rightopentriangle ▷ WHITE RIGHT-POINTING TRIANGLE 0x0ace: 0x25cb, # emopencircle ○ WHITE CIRCLE 0x0acf: 0x25af, # emopenrectangle ▯ WHITE VERTICAL RECTANGLE 0x0ad0: 0x2018, # leftsinglequotemark ‘ LEFT SINGLE QUOTATION MARK 0x0ad1: 0x2019, # rightsinglequotemark ’ RIGHT SINGLE QUOTATION MARK 0x0ad2: 0x201c, # leftdoublequotemark “ LEFT DOUBLE QUOTATION MARK 0x0ad3: 0x201d, # rightdoublequotemark ” RIGHT DOUBLE QUOTATION MARK 0x0ad4: 0x211e, # prescription ℞ PRESCRIPTION TAKE 0x0ad6: 0x2032, # minutes ′ PRIME 0x0ad7: 0x2033, # seconds ″ DOUBLE PRIME 0x0ad9: 0x271d, # latincross ✝ LATIN CROSS 0x0adb: 0x25ac, # filledrectbullet ▬ BLACK RECTANGLE 0x0adc: 0x25c0, # filledlefttribullet ◀ BLACK LEFT-POINTING TRIANGLE 0x0add: 0x25b6, # filledrighttribullet ▶ BLACK RIGHT-POINTING TRIANGLE 0x0ade: 0x25cf, # emfilledcircle ● BLACK CIRCLE 0x0adf: 0x25ae, # emfilledrect ▮ BLACK VERTICAL RECTANGLE 0x0ae0: 0x25e6, # enopencircbullet ◦ WHITE BULLET 0x0ae1: 0x25ab, # enopensquarebullet ▫ WHITE SMALL SQUARE 0x0ae2: 0x25ad, # openrectbullet ▭ WHITE RECTANGLE 0x0ae3: 0x25b3, # opentribulletup △ WHITE UP-POINTING TRIANGLE 0x0ae4: 0x25bd, # opentribulletdown ▽ WHITE DOWN-POINTING TRIANGLE 0x0ae5: 0x2606, # openstar ☆ WHITE STAR 0x0ae6: 0x2022, # enfilledcircbullet • BULLET 0x0ae7: 0x25aa, # enfilledsqbullet ▪ BLACK SMALL SQUARE 0x0ae8: 0x25b2, # filledtribulletup ▲ BLACK UP-POINTING TRIANGLE 0x0ae9: 0x25bc, # filledtribulletdown ▼ BLACK DOWN-POINTING TRIANGLE 0x0aea: 0x261c, # leftpointer ☜ WHITE LEFT POINTING INDEX 0x0aeb: 0x261e, # rightpointer ☞ WHITE RIGHT POINTING INDEX 0x0aec: 0x2663, # club ♣ BLACK CLUB SUIT 0x0aed: 0x2666, # diamond ♦ BLACK DIAMOND SUIT 0x0aee: 0x2665, # heart ♥ BLACK HEART SUIT 0x0af0: 0x2720, # maltesecross ✠ MALTESE CROSS 0x0af1: 0x2020, # dagger † DAGGER 0x0af2: 0x2021, # doubledagger ‡ DOUBLE DAGGER 0x0af3: 0x2713, # checkmark ✓ CHECK MARK 0x0af4: 0x2717, # ballotcross ✗ BALLOT X 0x0af5: 0x266f, # musicalsharp ♯ MUSIC SHARP SIGN 0x0af6: 0x266d, # musicalflat ♭ MUSIC FLAT SIGN 0x0af7: 0x2642, # malesymbol ♂ MALE SIGN 0x0af8: 0x2640, # femalesymbol ♀ FEMALE SIGN 0x0af9: 0x260e, # telephone ☎ BLACK TELEPHONE 0x0afa: 0x2315, # telephonerecorder ⌕ TELEPHONE RECORDER 0x0afb: 0x2117, # phonographcopyright ℗ SOUND RECORDING COPYRIGHT 0x0afc: 0x2038, # caret ‸ CARET 0x0afd: 0x201a, # singlelowquotemark ‚ SINGLE LOW-9 QUOTATION MARK 0x0afe: 0x201e, # doublelowquotemark „ DOUBLE LOW-9 QUOTATION MARK 0x0ba3: 0x003c, # leftcaret < LESS-THAN SIGN 0x0ba6: 0x003e, # rightcaret > GREATER-THAN SIGN 0x0ba8: 0x2228, # downcaret ∨ LOGICAL OR 0x0ba9: 0x2227, # upcaret ∧ LOGICAL AND 0x0bc0: 0x00af, # overbar ¯ MACRON 0x0bc2: 0x22a5, # downtack ⊥ UP TACK 0x0bc3: 0x2229, # upshoe ∩ INTERSECTION 0x0bc4: 0x230a, # downstile ⌊ LEFT FLOOR 0x0bc6: 0x005f, # underbar _ LOW LINE 0x0bca: 0x2218, # jot ∘ RING OPERATOR 0x0bcc: 0x2395, # quad ⎕ APL FUNCTIONAL SYMBOL QUAD 0x0bce: 0x22a4, # uptack ⊤ DOWN TACK 0x0bcf: 0x25cb, # circle ○ WHITE CIRCLE 0x0bd3: 0x2308, # upstile ⌈ LEFT CEILING 0x0bd6: 0x222a, # downshoe ∪ UNION 0x0bd8: 0x2283, # rightshoe ⊃ SUPERSET OF 0x0bda: 0x2282, # leftshoe ⊂ SUBSET OF 0x0bdc: 0x22a2, # lefttack ⊢ RIGHT TACK 0x0bfc: 0x22a3, # righttack ⊣ LEFT TACK 0x0cdf: 0x2017, # hebrew_doublelowline ‗ DOUBLE LOW LINE 0x0ce0: 0x05d0, # hebrew_aleph א HEBREW LETTER ALEF 0x0ce1: 0x05d1, # hebrew_bet ב HEBREW LETTER BET 0x0ce2: 0x05d2, # hebrew_gimel ג HEBREW LETTER GIMEL 0x0ce3: 0x05d3, # hebrew_dalet ד HEBREW LETTER DALET 0x0ce4: 0x05d4, # hebrew_he ה HEBREW LETTER HE 0x0ce5: 0x05d5, # hebrew_waw ו HEBREW LETTER VAV 0x0ce6: 0x05d6, # hebrew_zain ז HEBREW LETTER ZAYIN 0x0ce7: 0x05d7, # hebrew_chet ח HEBREW LETTER HET 0x0ce8: 0x05d8, # hebrew_tet ט HEBREW LETTER TET 0x0ce9: 0x05d9, # hebrew_yod י HEBREW LETTER YOD 0x0cea: 0x05da, # hebrew_finalkaph ך HEBREW LETTER FINAL KAF 0x0ceb: 0x05db, # hebrew_kaph כ HEBREW LETTER KAF 0x0cec: 0x05dc, # hebrew_lamed ל HEBREW LETTER LAMED 0x0ced: 0x05dd, # hebrew_finalmem ם HEBREW LETTER FINAL MEM 0x0cee: 0x05de, # hebrew_mem מ HEBREW LETTER MEM 0x0cef: 0x05df, # hebrew_finalnun ן HEBREW LETTER FINAL NUN 0x0cf0: 0x05e0, # hebrew_nun נ HEBREW LETTER NUN 0x0cf1: 0x05e1, # hebrew_samech ס HEBREW LETTER SAMEKH 0x0cf2: 0x05e2, # hebrew_ayin ע HEBREW LETTER AYIN 0x0cf3: 0x05e3, # hebrew_finalpe ף HEBREW LETTER FINAL PE 0x0cf4: 0x05e4, # hebrew_pe פ HEBREW LETTER PE 0x0cf5: 0x05e5, # hebrew_finalzade ץ HEBREW LETTER FINAL TSADI 0x0cf6: 0x05e6, # hebrew_zade צ HEBREW LETTER TSADI 0x0cf7: 0x05e7, # hebrew_qoph ק HEBREW LETTER QOF 0x0cf8: 0x05e8, # hebrew_resh ר HEBREW LETTER RESH 0x0cf9: 0x05e9, # hebrew_shin ש HEBREW LETTER SHIN 0x0cfa: 0x05ea, # hebrew_taw ת HEBREW LETTER TAV 0x0da1: 0x0e01, # Thai_kokai ก THAI CHARACTER KO KAI 0x0da2: 0x0e02, # Thai_khokhai ข THAI CHARACTER KHO KHAI 0x0da3: 0x0e03, # Thai_khokhuat ฃ THAI CHARACTER KHO KHUAT 0x0da4: 0x0e04, # Thai_khokhwai ค THAI CHARACTER KHO KHWAI 0x0da5: 0x0e05, # Thai_khokhon ฅ THAI CHARACTER KHO KHON 0x0da6: 0x0e06, # Thai_khorakhang ฆ THAI CHARACTER KHO RAKHANG 0x0da7: 0x0e07, # Thai_ngongu ง THAI CHARACTER NGO NGU 0x0da8: 0x0e08, # Thai_chochan จ THAI CHARACTER CHO CHAN 0x0da9: 0x0e09, # Thai_choching ฉ THAI CHARACTER CHO CHING 0x0daa: 0x0e0a, # Thai_chochang ช THAI CHARACTER CHO CHANG 0x0dab: 0x0e0b, # Thai_soso ซ THAI CHARACTER SO SO 0x0dac: 0x0e0c, # Thai_chochoe ฌ THAI CHARACTER CHO CHOE 0x0dad: 0x0e0d, # Thai_yoying ญ THAI CHARACTER YO YING 0x0dae: 0x0e0e, # Thai_dochada ฎ THAI CHARACTER DO CHADA 0x0daf: 0x0e0f, # Thai_topatak ฏ THAI CHARACTER TO PATAK 0x0db0: 0x0e10, # Thai_thothan ฐ THAI CHARACTER THO THAN 0x0db1: 0x0e11, # Thai_thonangmontho ฑ THAI CHARACTER THO NANGMONTHO 0x0db2: 0x0e12, # Thai_thophuthao ฒ THAI CHARACTER THO PHUTHAO 0x0db3: 0x0e13, # Thai_nonen ณ THAI CHARACTER NO NEN 0x0db4: 0x0e14, # Thai_dodek ด THAI CHARACTER DO DEK 0x0db5: 0x0e15, # Thai_totao ต THAI CHARACTER TO TAO 0x0db6: 0x0e16, # Thai_thothung ถ THAI CHARACTER THO THUNG 0x0db7: 0x0e17, # Thai_thothahan ท THAI CHARACTER THO THAHAN 0x0db8: 0x0e18, # Thai_thothong ธ THAI CHARACTER THO THONG 0x0db9: 0x0e19, # Thai_nonu น THAI CHARACTER NO NU 0x0dba: 0x0e1a, # Thai_bobaimai บ THAI CHARACTER BO BAIMAI 0x0dbb: 0x0e1b, # Thai_popla ป THAI CHARACTER PO PLA 0x0dbc: 0x0e1c, # Thai_phophung ผ THAI CHARACTER PHO PHUNG 0x0dbd: 0x0e1d, # Thai_fofa ฝ THAI CHARACTER FO FA 0x0dbe: 0x0e1e, # Thai_phophan พ THAI CHARACTER PHO PHAN 0x0dbf: 0x0e1f, # Thai_fofan ฟ THAI CHARACTER FO FAN 0x0dc0: 0x0e20, # Thai_phosamphao ภ THAI CHARACTER PHO SAMPHAO 0x0dc1: 0x0e21, # Thai_moma ม THAI CHARACTER MO MA 0x0dc2: 0x0e22, # Thai_yoyak ย THAI CHARACTER YO YAK 0x0dc3: 0x0e23, # Thai_rorua ร THAI CHARACTER RO RUA 0x0dc4: 0x0e24, # Thai_ru ฤ THAI CHARACTER RU 0x0dc5: 0x0e25, # Thai_loling ล THAI CHARACTER LO LING 0x0dc6: 0x0e26, # Thai_lu ฦ THAI CHARACTER LU 0x0dc7: 0x0e27, # Thai_wowaen ว THAI CHARACTER WO WAEN 0x0dc8: 0x0e28, # Thai_sosala ศ THAI CHARACTER SO SALA 0x0dc9: 0x0e29, # Thai_sorusi ษ THAI CHARACTER SO RUSI 0x0dca: 0x0e2a, # Thai_sosua ส THAI CHARACTER SO SUA 0x0dcb: 0x0e2b, # Thai_hohip ห THAI CHARACTER HO HIP 0x0dcc: 0x0e2c, # Thai_lochula ฬ THAI CHARACTER LO CHULA 0x0dcd: 0x0e2d, # Thai_oang อ THAI CHARACTER O ANG 0x0dce: 0x0e2e, # Thai_honokhuk ฮ THAI CHARACTER HO NOKHUK 0x0dcf: 0x0e2f, # Thai_paiyannoi ฯ THAI CHARACTER PAIYANNOI 0x0dd0: 0x0e30, # Thai_saraa ะ THAI CHARACTER SARA A 0x0dd1: 0x0e31, # Thai_maihanakat ั THAI CHARACTER MAI HAN-AKAT 0x0dd2: 0x0e32, # Thai_saraaa า THAI CHARACTER SARA AA 0x0dd3: 0x0e33, # Thai_saraam ำ THAI CHARACTER SARA AM 0x0dd4: 0x0e34, # Thai_sarai ิ THAI CHARACTER SARA I 0x0dd5: 0x0e35, # Thai_saraii ี THAI CHARACTER SARA II 0x0dd6: 0x0e36, # Thai_saraue ึ THAI CHARACTER SARA UE 0x0dd7: 0x0e37, # Thai_sarauee ื THAI CHARACTER SARA UEE 0x0dd8: 0x0e38, # Thai_sarau ุ THAI CHARACTER SARA U 0x0dd9: 0x0e39, # Thai_sarauu ู THAI CHARACTER SARA UU 0x0dda: 0x0e3a, # Thai_phinthu ฺ THAI CHARACTER PHINTHU 0x0dde: 0x0e3e, # Thai_maihanakat_maitho ฾ ??? 0x0ddf: 0x0e3f, # Thai_baht ฿ THAI CURRENCY SYMBOL BAHT 0x0de0: 0x0e40, # Thai_sarae เ THAI CHARACTER SARA E 0x0de1: 0x0e41, # Thai_saraae แ THAI CHARACTER SARA AE 0x0de2: 0x0e42, # Thai_sarao โ THAI CHARACTER SARA O 0x0de3: 0x0e43, # Thai_saraaimaimuan ใ THAI CHARACTER SARA AI MAIMUAN 0x0de4: 0x0e44, # Thai_saraaimaimalai ไ THAI CHARACTER SARA AI MAIMALAI 0x0de5: 0x0e45, # Thai_lakkhangyao ๅ THAI CHARACTER LAKKHANGYAO 0x0de6: 0x0e46, # Thai_maiyamok ๆ THAI CHARACTER MAIYAMOK 0x0de7: 0x0e47, # Thai_maitaikhu ็ THAI CHARACTER MAITAIKHU 0x0de8: 0x0e48, # Thai_maiek ่ THAI CHARACTER MAI EK 0x0de9: 0x0e49, # Thai_maitho ้ THAI CHARACTER MAI THO 0x0dea: 0x0e4a, # Thai_maitri ๊ THAI CHARACTER MAI TRI 0x0deb: 0x0e4b, # Thai_maichattawa ๋ THAI CHARACTER MAI CHATTAWA 0x0dec: 0x0e4c, # Thai_thanthakhat ์ THAI CHARACTER THANTHAKHAT 0x0ded: 0x0e4d, # Thai_nikhahit ํ THAI CHARACTER NIKHAHIT 0x0df0: 0x0e50, # Thai_leksun ๐ THAI DIGIT ZERO 0x0df1: 0x0e51, # Thai_leknung ๑ THAI DIGIT ONE 0x0df2: 0x0e52, # Thai_leksong ๒ THAI DIGIT TWO 0x0df3: 0x0e53, # Thai_leksam ๓ THAI DIGIT THREE 0x0df4: 0x0e54, # Thai_leksi ๔ THAI DIGIT FOUR 0x0df5: 0x0e55, # Thai_lekha ๕ THAI DIGIT FIVE 0x0df6: 0x0e56, # Thai_lekhok ๖ THAI DIGIT SIX 0x0df7: 0x0e57, # Thai_lekchet ๗ THAI DIGIT SEVEN 0x0df8: 0x0e58, # Thai_lekpaet ๘ THAI DIGIT EIGHT 0x0df9: 0x0e59, # Thai_lekkao ๙ THAI DIGIT NINE 0x0ea1: 0x3131, # Hangul_Kiyeog ㄱ HANGUL LETTER KIYEOK 0x0ea2: 0x3132, # Hangul_SsangKiyeog ㄲ HANGUL LETTER SSANGKIYEOK 0x0ea3: 0x3133, # Hangul_KiyeogSios ㄳ HANGUL LETTER KIYEOK-SIOS 0x0ea4: 0x3134, # Hangul_Nieun ㄴ HANGUL LETTER NIEUN 0x0ea5: 0x3135, # Hangul_NieunJieuj ㄵ HANGUL LETTER NIEUN-CIEUC 0x0ea6: 0x3136, # Hangul_NieunHieuh ㄶ HANGUL LETTER NIEUN-HIEUH 0x0ea7: 0x3137, # Hangul_Dikeud ㄷ HANGUL LETTER TIKEUT 0x0ea8: 0x3138, # Hangul_SsangDikeud ㄸ HANGUL LETTER SSANGTIKEUT 0x0ea9: 0x3139, # Hangul_Rieul ㄹ HANGUL LETTER RIEUL 0x0eaa: 0x313a, # Hangul_RieulKiyeog ㄺ HANGUL LETTER RIEUL-KIYEOK 0x0eab: 0x313b, # Hangul_RieulMieum ㄻ HANGUL LETTER RIEUL-MIEUM 0x0eac: 0x313c, # Hangul_RieulPieub ㄼ HANGUL LETTER RIEUL-PIEUP 0x0ead: 0x313d, # Hangul_RieulSios ㄽ HANGUL LETTER RIEUL-SIOS 0x0eae: 0x313e, # Hangul_RieulTieut ㄾ HANGUL LETTER RIEUL-THIEUTH 0x0eaf: 0x313f, # Hangul_RieulPhieuf ㄿ HANGUL LETTER RIEUL-PHIEUPH 0x0eb0: 0x3140, # Hangul_RieulHieuh ㅀ HANGUL LETTER RIEUL-HIEUH 0x0eb1: 0x3141, # Hangul_Mieum ㅁ HANGUL LETTER MIEUM 0x0eb2: 0x3142, # Hangul_Pieub ㅂ HANGUL LETTER PIEUP 0x0eb3: 0x3143, # Hangul_SsangPieub ㅃ HANGUL LETTER SSANGPIEUP 0x0eb4: 0x3144, # Hangul_PieubSios ㅄ HANGUL LETTER PIEUP-SIOS 0x0eb5: 0x3145, # Hangul_Sios ㅅ HANGUL LETTER SIOS 0x0eb6: 0x3146, # Hangul_SsangSios ㅆ HANGUL LETTER SSANGSIOS 0x0eb7: 0x3147, # Hangul_Ieung ㅇ HANGUL LETTER IEUNG 0x0eb8: 0x3148, # Hangul_Jieuj ㅈ HANGUL LETTER CIEUC 0x0eb9: 0x3149, # Hangul_SsangJieuj ㅉ HANGUL LETTER SSANGCIEUC 0x0eba: 0x314a, # Hangul_Cieuc ㅊ HANGUL LETTER CHIEUCH 0x0ebb: 0x314b, # Hangul_Khieuq ㅋ HANGUL LETTER KHIEUKH 0x0ebc: 0x314c, # Hangul_Tieut ㅌ HANGUL LETTER THIEUTH 0x0ebd: 0x314d, # Hangul_Phieuf ㅍ HANGUL LETTER PHIEUPH 0x0ebe: 0x314e, # Hangul_Hieuh ㅎ HANGUL LETTER HIEUH 0x0ebf: 0x314f, # Hangul_A ㅏ HANGUL LETTER A 0x0ec0: 0x3150, # Hangul_AE ㅐ HANGUL LETTER AE 0x0ec1: 0x3151, # Hangul_YA ㅑ HANGUL LETTER YA 0x0ec2: 0x3152, # Hangul_YAE ㅒ HANGUL LETTER YAE 0x0ec3: 0x3153, # Hangul_EO ㅓ HANGUL LETTER EO 0x0ec4: 0x3154, # Hangul_E ㅔ HANGUL LETTER E 0x0ec5: 0x3155, # Hangul_YEO ㅕ HANGUL LETTER YEO 0x0ec6: 0x3156, # Hangul_YE ㅖ HANGUL LETTER YE 0x0ec7: 0x3157, # Hangul_O ㅗ HANGUL LETTER O 0x0ec8: 0x3158, # Hangul_WA ㅘ HANGUL LETTER WA 0x0ec9: 0x3159, # Hangul_WAE ㅙ HANGUL LETTER WAE 0x0eca: 0x315a, # Hangul_OE ㅚ HANGUL LETTER OE 0x0ecb: 0x315b, # Hangul_YO ㅛ HANGUL LETTER YO 0x0ecc: 0x315c, # Hangul_U ㅜ HANGUL LETTER U 0x0ecd: 0x315d, # Hangul_WEO ㅝ HANGUL LETTER WEO 0x0ece: 0x315e, # Hangul_WE ㅞ HANGUL LETTER WE 0x0ecf: 0x315f, # Hangul_WI ㅟ HANGUL LETTER WI 0x0ed0: 0x3160, # Hangul_YU ㅠ HANGUL LETTER YU 0x0ed1: 0x3161, # Hangul_EU ㅡ HANGUL LETTER EU 0x0ed2: 0x3162, # Hangul_YI ㅢ HANGUL LETTER YI 0x0ed3: 0x3163, # Hangul_I ㅣ HANGUL LETTER I 0x0ed4: 0x11a8, # Hangul_J_Kiyeog ᆨ HANGUL JONGSEONG KIYEOK 0x0ed5: 0x11a9, # Hangul_J_SsangKiyeog ᆩ HANGUL JONGSEONG SSANGKIYEOK 0x0ed6: 0x11aa, # Hangul_J_KiyeogSios ᆪ HANGUL JONGSEONG KIYEOK-SIOS 0x0ed7: 0x11ab, # Hangul_J_Nieun ᆫ HANGUL JONGSEONG NIEUN 0x0ed8: 0x11ac, # Hangul_J_NieunJieuj ᆬ HANGUL JONGSEONG NIEUN-CIEUC 0x0ed9: 0x11ad, # Hangul_J_NieunHieuh ᆭ HANGUL JONGSEONG NIEUN-HIEUH 0x0eda: 0x11ae, # Hangul_J_Dikeud ᆮ HANGUL JONGSEONG TIKEUT 0x0edb: 0x11af, # Hangul_J_Rieul ᆯ HANGUL JONGSEONG RIEUL 0x0edc: 0x11b0, # Hangul_J_RieulKiyeog ᆰ HANGUL JONGSEONG RIEUL-KIYEOK 0x0edd: 0x11b1, # Hangul_J_RieulMieum ᆱ HANGUL JONGSEONG RIEUL-MIEUM 0x0ede: 0x11b2, # Hangul_J_RieulPieub ᆲ HANGUL JONGSEONG RIEUL-PIEUP 0x0edf: 0x11b3, # Hangul_J_RieulSios ᆳ HANGUL JONGSEONG RIEUL-SIOS 0x0ee0: 0x11b4, # Hangul_J_RieulTieut ᆴ HANGUL JONGSEONG RIEUL-THIEUTH 0x0ee1: 0x11b5, # Hangul_J_RieulPhieuf ᆵ HANGUL JONGSEONG RIEUL-PHIEUPH 0x0ee2: 0x11b6, # Hangul_J_RieulHieuh ᆶ HANGUL JONGSEONG RIEUL-HIEUH 0x0ee3: 0x11b7, # Hangul_J_Mieum ᆷ HANGUL JONGSEONG MIEUM 0x0ee4: 0x11b8, # Hangul_J_Pieub ᆸ HANGUL JONGSEONG PIEUP 0x0ee5: 0x11b9, # Hangul_J_PieubSios ᆹ HANGUL JONGSEONG PIEUP-SIOS 0x0ee6: 0x11ba, # Hangul_J_Sios ᆺ HANGUL JONGSEONG SIOS 0x0ee7: 0x11bb, # Hangul_J_SsangSios ᆻ HANGUL JONGSEONG SSANGSIOS 0x0ee8: 0x11bc, # Hangul_J_Ieung ᆼ HANGUL JONGSEONG IEUNG 0x0ee9: 0x11bd, # Hangul_J_Jieuj ᆽ HANGUL JONGSEONG CIEUC 0x0eea: 0x11be, # Hangul_J_Cieuc ᆾ HANGUL JONGSEONG CHIEUCH 0x0eeb: 0x11bf, # Hangul_J_Khieuq ᆿ HANGUL JONGSEONG KHIEUKH 0x0eec: 0x11c0, # Hangul_J_Tieut ᇀ HANGUL JONGSEONG THIEUTH 0x0eed: 0x11c1, # Hangul_J_Phieuf ᇁ HANGUL JONGSEONG PHIEUPH 0x0eee: 0x11c2, # Hangul_J_Hieuh ᇂ HANGUL JONGSEONG HIEUH 0x0eef: 0x316d, # Hangul_RieulYeorinHieuh ㅭ HANGUL LETTER RIEUL-YEORINHIEUH 0x0ef0: 0x3171, # Hangul_SunkyeongeumMieum ㅱ HANGUL LETTER KAPYEOUNMIEUM 0x0ef1: 0x3178, # Hangul_SunkyeongeumPieub ㅸ HANGUL LETTER KAPYEOUNPIEUP 0x0ef2: 0x317f, # Hangul_PanSios ㅿ HANGUL LETTER PANSIOS 0x0ef3: 0x3181, # Hangul_KkogjiDalrinIeung ㆁ HANGUL LETTER YESIEUNG 0x0ef4: 0x3184, # Hangul_SunkyeongeumPhieuf ㆄ HANGUL LETTER KAPYEOUNPHIEUPH 0x0ef5: 0x3186, # Hangul_YeorinHieuh ㆆ HANGUL LETTER YEORINHIEUH 0x0ef6: 0x318d, # Hangul_AraeA ㆍ HANGUL LETTER ARAEA 0x0ef7: 0x318e, # Hangul_AraeAE ㆎ HANGUL LETTER ARAEAE 0x0ef8: 0x11eb, # Hangul_J_PanSios ᇫ HANGUL JONGSEONG PANSIOS 0x0ef9: 0x11f0, # Hangul_J_KkogjiDalrinIeung ᇰ HANGUL JONGSEONG YESIEUNG 0x0efa: 0x11f9, # Hangul_J_YeorinHieuh ᇹ HANGUL JONGSEONG YEORINHIEUH 0x0eff: 0x20a9, # Korean_Won ₩ WON SIGN 0x13a4: 0x20ac, # Euro € EURO SIGN 0x13bc: 0x0152, # OE Œ LATIN CAPITAL LIGATURE OE 0x13bd: 0x0153, # oe œ LATIN SMALL LIGATURE OE 0x13be: 0x0178, # Ydiaeresis Ÿ LATIN CAPITAL LETTER Y WITH DIAERESIS 0x20a0: 0x20a0, # EcuSign ₠ EURO-CURRENCY SIGN 0x20a1: 0x20a1, # ColonSign ₡ COLON SIGN 0x20a2: 0x20a2, # CruzeiroSign ₢ CRUZEIRO SIGN 0x20a3: 0x20a3, # FFrancSign ₣ FRENCH FRANC SIGN 0x20a4: 0x20a4, # LiraSign ₤ LIRA SIGN 0x20a5: 0x20a5, # MillSign ₥ MILL SIGN 0x20a6: 0x20a6, # NairaSign ₦ NAIRA SIGN 0x20a7: 0x20a7, # PesetaSign ₧ PESETA SIGN 0x20a8: 0x20a8, # RupeeSign ₨ RUPEE SIGN 0x20a9: 0x20a9, # WonSign ₩ WON SIGN 0x20aa: 0x20aa, # NewSheqelSign ₪ NEW SHEQEL SIGN 0x20ab: 0x20ab, # DongSign ₫ DONG SIGN 0x20ac: 0x20ac, # EuroSign € EURO SIGN } UCS_TO_KEYSYM = {ucs: keysym for keysym, ucs in KEYSYM_TO_UCS.items()} def is_latin1(code): return 0x20 <= code <= 0x7e or 0xa0 <= code <= 0xff def uchr_to_keysym(char): code = ord(char) # Latin-1 characters: direct, 1:1 mapping. if is_latin1(code): return code if code == 0x09: return XK.XK_Tab if code in (0x0a, 0x0d): return XK.XK_Return return UCS_TO_KEYSYM.get(code, code | 0x01000000) def keysym_to_string(keysym): # Latin-1 characters: direct, 1:1 mapping. if is_latin1(keysym): code = keysym elif (keysym & 0xff000000) == 0x01000000: code = keysym & 0x00ffffff else: code = KEYSYM_TO_UCS.get(keysym) if code is None: keysym_str = XK.keysym_to_string(keysym) if keysym_str is None: keysym_str = '' for c in keysym_str: if not c.isprintable(): keysym_str = '' break return keysym_str return chr(code) class KeyboardEmulation(GenericKeyboardEmulation): class Mapping: def __init__(self, keycode, modifiers, keysym, custom_mapping=None): self.keycode = keycode self.modifiers = modifiers self.keysym = keysym self.custom_mapping = custom_mapping def __str__(self): return '%u:%x=%x[%s]%s' % ( self.keycode, self.modifiers, self.keysym, keysym_to_string(self.keysym), '' if self.custom_mapping is None else '*', ) # We can use the first 2 entry of a X11 mapping: # keycode and keycode+shift. The 3rd entry is a # special keysym to mark the mapping. CUSTOM_MAPPING_LENGTH = 3 # Special keysym to mark custom keyboard mappings. PLOVER_MAPPING_KEYSYM = 0x01ffffff # Free unused keysym. UNUSED_KEYSYM = 0xffffff # XK_VoidSymbol def __init__(self): super().__init__() self._display = Display() self._update_keymap() def _update_keymap(self): '''Analyse keymap, build a mapping of keysym to (keycode + modifiers), and find unused keycodes that can be used for unmapped keysyms. ''' self._keymap = {} self._custom_mappings_queue = [] # Analyse X11 keymap. keycode = self._display.display.info.min_keycode keycode_count = self._display.display.info.max_keycode - keycode + 1 for mapping in self._display.get_keyboard_mapping(keycode, keycode_count): mapping = tuple(mapping) while mapping and X.NoSymbol == mapping[-1]: mapping = mapping[:-1] if not mapping: # Free never used before keycode. custom_mapping = [self.UNUSED_KEYSYM] * self.CUSTOM_MAPPING_LENGTH custom_mapping[-1] = self.PLOVER_MAPPING_KEYSYM mapping = custom_mapping elif self.CUSTOM_MAPPING_LENGTH == len(mapping) and \ self.PLOVER_MAPPING_KEYSYM == mapping[-1]: # Keycode was previously used by Plover. custom_mapping = list(mapping) else: # Used keycode. custom_mapping = None for keysym_index, keysym in enumerate(mapping): if keysym == self.PLOVER_MAPPING_KEYSYM: continue if keysym_index not in (0, 1, 4, 5): continue modifiers = 0 if 1 == (keysym_index % 2): # The keycode needs the Shift modifier. modifiers |= X.ShiftMask if 4 <= keysym_index <= 5: # 3rd (AltGr) level. modifiers |= X.Mod5Mask mapping = self.Mapping(keycode, modifiers, keysym, custom_mapping) if keysym != X.NoSymbol and keysym != self.UNUSED_KEYSYM: # Some keysym are mapped multiple times, prefer lower modifiers combos. previous_mapping = self._keymap.get(keysym) if previous_mapping is None or mapping.modifiers < previous_mapping.modifiers: self._keymap[keysym] = mapping if custom_mapping is not None: self._custom_mappings_queue.append(mapping) keycode += 1 log.debug('keymap:') for mapping in sorted(self._keymap.values(), key=lambda m: (m.keycode, m.modifiers)): log.debug('%s', mapping) log.info('%u custom mappings(s)', len(self._custom_mappings_queue)) # Determine the backspace mapping. backspace_keysym = XK.string_to_keysym('BackSpace') self._backspace_mapping = self._get_mapping(backspace_keysym) assert self._backspace_mapping is not None assert self._backspace_mapping.custom_mapping is None # Get modifier mapping. self.modifier_mapping = self._display.get_modifier_mapping() def send_backspaces(self, count): for x in self.with_delay(range(count)): self._send_keycode(self._backspace_mapping.keycode, self._backspace_mapping.modifiers) self._display.sync() def send_string(self, string): for char in string: keysym = uchr_to_keysym(char) # TODO: can we find mappings for multiple keys at a time? mapping = self._get_mapping(keysym, automatically_map=False) mapping_changed = False if mapping is None: mapping = self._get_mapping(keysym, automatically_map=True) if mapping is None: continue self._display.sync() self.half_delay() mapping_changed = True self._send_keycode(mapping.keycode, mapping.modifiers) self._display.sync() if mapping_changed: self.half_delay() else: self.delay() def send_key_combination(self, combo): # Parse and validate combo. key_events = [ (keycode, X.KeyPress if pressed else X.KeyRelease) for keycode, pressed in parse_key_combo(combo, self._get_keycode_from_keystring) ] # Emulate the key combination by sending key events. for keycode, event_type in self.with_delay(key_events): xtest.fake_input(self._display, event_type, keycode) self._display.sync() def _send_keycode(self, keycode, modifiers=0): """Emulate a key press and release. Arguments: keycode -- An integer in the inclusive range [8-255]. modifiers -- An 8-bit bit mask indicating if the key pressed is modified by other keys, such as Shift, Capslock, Control, and Alt. """ modifiers_list = [ self.modifier_mapping[n][0] for n in range(8) if (modifiers & (1 << n)) ] # Press modifiers. for mod_keycode in modifiers_list: xtest.fake_input(self._display, X.KeyPress, mod_keycode) # Press and release the base key. xtest.fake_input(self._display, X.KeyPress, keycode) xtest.fake_input(self._display, X.KeyRelease, keycode) # Release modifiers. for mod_keycode in reversed(modifiers_list): xtest.fake_input(self._display, X.KeyRelease, mod_keycode) def _get_keycode_from_keystring(self, keystring): '''Find the physical key <keystring> is mapped to. Return None of if keystring is not mapped. ''' keysym = KEY_TO_KEYSYM.get(keystring) if keysym is None: return None mapping = self._get_mapping(keysym, automatically_map=False) if mapping is None: return None return mapping.keycode def _get_mapping(self, keysym, automatically_map=True): """Return a keycode and modifier mask pair that result in the keysym. There is a one-to-many mapping from keysyms to keycode and modifiers pairs; this function returns one of the possibly many valid mappings, or None if no mapping exists, and a new one cannot be added. Arguments: keysym -- A key symbol. """ mapping = self._keymap.get(keysym) if mapping is None: # Automatically map? if not automatically_map: # No. return None # Can we map it? if 0 == len(self._custom_mappings_queue): # Nope... return None mapping = self._custom_mappings_queue.pop(0) previous_keysym = mapping.keysym keysym_index = mapping.custom_mapping.index(previous_keysym) # Update X11 keymap. mapping.custom_mapping[keysym_index] = keysym self._display.change_keyboard_mapping(mapping.keycode, [mapping.custom_mapping]) # Update our keymap. if previous_keysym in self._keymap: del self._keymap[previous_keysym] mapping.keysym = keysym self._keymap[keysym] = mapping log.debug('new mapping: %s', mapping) # Move custom mapping back at the end of # the queue so we don't use it too soon. self._custom_mappings_queue.append(mapping) elif mapping.custom_mapping is not None: # Same as above; prevent mapping # from being reused to soon. self._custom_mappings_queue.remove(mapping) self._custom_mappings_queue.append(mapping) return mapping
78,256
Python
.py
1,281
54.383294
101
0.589335
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,734
wmctrl.py
openstenoproject_plover/plover/oslayer/linux/wmctrl.py
from .wmctrl_x11 import WmCtrl _wmctrl = WmCtrl() GetForegroundWindow = _wmctrl.get_foreground_window SetForegroundWindow = _wmctrl.set_foreground_window
157
Python
.py
4
37.5
51
0.833333
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,735
i18n.py
openstenoproject_plover/plover/oslayer/linux/i18n.py
import locale import os # Note: highest priority first. LANG_ENV_VARS = ('LC_ALL', 'LC_MESSAGES', 'LANG') def get_system_language(): try: return next(filter(None, map(os.environ.get, LANG_ENV_VARS))) except StopIteration: return locale.getdefaultlocale()[0]
285
Python
.py
9
27.666667
69
0.699634
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,736
geminipr.py
openstenoproject_plover/plover/machine/geminipr.py
# Copyright (c) 2010-2011 Joshua Harlan Lifton. # See LICENSE.txt for details. """Thread-based monitoring of a Gemini PR stenotype machine.""" import binascii from plover import log from plover.machine.base import SerialStenotypeBase # In the Gemini PR protocol, each packet consists of exactly six bytes # and the most significant bit (MSB) of every byte is used exclusively # to indicate whether that byte is the first byte of the packet # (MSB=1) or one of the remaining five bytes of the packet (MSB=0). As # such, there are really only seven bits of steno data in each packet # byte. This is why the STENO_KEY_CHART below is visually presented as # six rows of seven elements instead of six rows of eight elements. STENO_KEY_CHART = ("Fn", "#1", "#2", "#3", "#4", "#5", "#6", "S1-", "S2-", "T-", "K-", "P-", "W-", "H-", "R-", "A-", "O-", "*1", "*2", "res1", "res2", "pwr", "*3", "*4", "-E", "-U", "-F", "-R", "-P", "-B", "-L", "-G", "-T", "-S", "-D", "#7", "#8", "#9", "#A", "#B", "#C", "-Z") BYTES_PER_STROKE = 6 class GeminiPr(SerialStenotypeBase): """Standard stenotype interface for a Gemini PR machine. """ KEYS_LAYOUT = ''' #1 #2 #3 #4 #5 #6 #7 #8 #9 #A #B #C Fn S1- T- P- H- *1 *3 -F -P -L -T -D S2- K- W- R- *2 *4 -R -B -G -S -Z A- O- -E -U pwr res1 res2 ''' def run(self): """Overrides base class run method. Do not call directly.""" self._ready() for packet in self._iter_packets(BYTES_PER_STROKE): if not (packet[0] & 0x80) or sum(b & 0x80 for b in packet[1:]): log.error('discarding invalid packet: %s', binascii.hexlify(packet)) continue steno_keys = [] for i, b in enumerate(packet): for j in range(1, 8): if (b & (0x80 >> j)): steno_keys.append(STENO_KEY_CHART[i * 7 + j - 1]) self._notify_keys(steno_keys)
2,118
Python
.py
46
36.695652
75
0.528128
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,737
keyboard.py
openstenoproject_plover/plover/machine/keyboard.py
# -*- coding: utf-8 -*- # Copyright (c) 2010 Joshua Harlan Lifton. # See LICENSE.txt for details. "For use with a computer keyboard (preferably NKRO) as a steno machine." from plover import _ from plover.machine.base import StenotypeBase from plover.misc import boolean from plover.oslayer.keyboardcontrol import KeyboardCapture # i18n: Machine name. _._('Keyboard') class Keyboard(StenotypeBase): """Standard stenotype interface for a computer keyboard. This class implements the three methods necessary for a standard stenotype interface: start_capture, stop_capture, and add_callback. """ KEYS_LAYOUT = ''' Escape F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 ` 1 2 3 4 5 6 7 8 9 0 - = \\ BackSpace Insert Home Page_Up Tab q w e r t y u i o p [ ] Delete End Page_Down a s d f g h j k l ; ' Return z x c v b n m , . / Up space Left Down Right ''' ACTIONS = ('arpeggiate',) def __init__(self, params): """Monitor the keyboard's events.""" super().__init__() self._arpeggiate = params['arpeggiate'] self._first_up_chord_send = params['first_up_chord_send'] if self._arpeggiate and self._first_up_chord_send: self._error() raise RuntimeError("Arpeggiate and first-up chord send cannot both be enabled!") self._is_suppressed = False # Currently held keys. self._down_keys = set() if self._first_up_chord_send: # If this is True, the first key in a stroke has already been released # and subsequent key-up events should not send more strokes self._chord_already_sent = False else: # Collect the keys in the stroke, in case first_up_chord_send is False self._stroke_keys = set() self._keyboard_capture = None self._last_stroke_key_down_count = 0 self._stroke_key_down_count = 0 self._update_bindings() def _update_suppression(self): if self._keyboard_capture is None: return suppressed_keys = self._bindings.keys() if self._is_suppressed else () self._keyboard_capture.suppress(suppressed_keys) def _update_bindings(self): self._arpeggiate_key = None self._bindings = dict(self.keymap.get_bindings()) for key, mapping in list(self._bindings.items()): if 'no-op' == mapping: self._bindings[key] = None elif 'arpeggiate' == mapping: if self._arpeggiate: self._bindings[key] = None self._arpeggiate_key = key else: # Don't suppress arpeggiate key if it's not used. del self._bindings[key] self._update_suppression() def set_keymap(self, keymap): super().set_keymap(keymap) self._update_bindings() def start_capture(self): """Begin listening for output from the stenotype machine.""" self._initializing() try: self._keyboard_capture = KeyboardCapture() self._keyboard_capture.key_down = self._key_down self._keyboard_capture.key_up = self._key_up self._keyboard_capture.start() self._update_suppression() except: self._error() raise self._ready() def stop_capture(self): """Stop listening for output from the stenotype machine.""" if self._keyboard_capture is not None: self._is_suppressed = False self._update_suppression() self._keyboard_capture.cancel() self._keyboard_capture = None self._stopped() def set_suppression(self, enabled): self._is_suppressed = enabled self._update_suppression() def suppress_last_stroke(self, send_backspaces): send_backspaces(self._last_stroke_key_down_count) self._last_stroke_key_down_count = 0 def _key_down(self, key): """Called when a key is pressed.""" assert key is not None self._stroke_key_down_count += 1 self._down_keys.add(key) if self._first_up_chord_send: self._chord_already_sent = False else: self._stroke_keys.add(key) def _key_up(self, key): """Called when a key is released.""" assert key is not None self._down_keys.discard(key) if self._first_up_chord_send: if self._chord_already_sent: return else: # A stroke is complete if all pressed keys have been released, # and — when arpeggiate mode is enabled — the arpeggiate key # is part of it. if ( self._down_keys or not self._stroke_keys or (self._arpeggiate and self._arpeggiate_key not in self._stroke_keys) ): return self._last_stroke_key_down_count = self._stroke_key_down_count if self._first_up_chord_send: steno_keys = {self._bindings.get(k) for k in self._down_keys | {key}} self._chord_already_sent = True else: steno_keys = {self._bindings.get(k) for k in self._stroke_keys} self._stroke_keys.clear() steno_keys -= {None} if steno_keys: self._notify(steno_keys) self._stroke_key_down_count = 0 @classmethod def get_option_info(cls): return { 'arpeggiate': (False, boolean), 'first_up_chord_send': (False, boolean), }
5,783
Python
.py
139
31.690647
92
0.577279
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,738
txbolt.py
openstenoproject_plover/plover/machine/txbolt.py
# Copyright (c) 2011 Hesky Fisher # See LICENSE.txt for details. "Thread-based monitoring of a stenotype machine using the TX Bolt protocol." import plover.machine.base # In the TX Bolt protocol, there are four sets of keys grouped in # order from left to right. Each byte represents all the keys that # were pressed in that set. The first two bits indicate which set this # byte represents. The next bits are set if the corresponding key was # pressed for the stroke. # 00XXXXXX 01XXXXXX 10XXXXXX 110XXXXX # HWPKTS UE*OAR GLBPRF #ZDST # The protocol uses variable length packets of one, two, three or four # bytes. Only those bytes for which keys were pressed will be # transmitted. The bytes arrive in order of the sets so it is clear # when a new stroke starts. Also, if a key is pressed in an earlier # set in one stroke and then a key is pressed only in a later set then # there will be a zero byte to indicate that this is a new stroke. So, # it is reliable to assume that a stroke ended when a lower set is # seen. Additionally, if there is no activity then the machine will # send a zero byte every few seconds. STENO_KEY_CHART = ("S-", "T-", "K-", "P-", "W-", "H-", # 00 "R-", "A-", "O-", "*", "-E", "-U", # 01 "-F", "-R", "-P", "-B", "-L", "-G", # 10 "-T", "-S", "-D", "-Z", "#") # 11 class TxBolt(plover.machine.base.SerialStenotypeBase): """TX Bolt interface. This class implements the three methods necessary for a standard stenotype interface: start_capture, stop_capture, and add_callback. """ KEYS_LAYOUT = ''' # # # # # # # # # # S- T- P- H- * -F -P -L -T -D S- K- W- R- * -R -B -G -S -Z A- O- -E -U ''' def __init__(self, params): super().__init__(params) self._reset_stroke_state() def _reset_stroke_state(self): self._pressed_keys = [] self._last_key_set = 0 def _finish_stroke(self): steno_keys = self.keymap.keys_to_actions(self._pressed_keys) if steno_keys: self._notify(steno_keys) self._reset_stroke_state() def run(self): """Overrides base class run method. Do not call directly.""" settings = self.serial_port.getSettingsDict() settings['timeout'] = 0.1 # seconds self.serial_port.applySettingsDict(settings) self._ready() while not self.finished.is_set(): # Grab data from the serial port, or wait for timeout if none available. raw = self.serial_port.read(max(1, self.serial_port.inWaiting())) if not raw: # Timeout, finish the current stroke. self._finish_stroke() continue for byte in raw: key_set = byte >> 6 if key_set <= self._last_key_set: # Starting a new stroke, finish previous one. self._finish_stroke() self._last_key_set = key_set for i in range(5 if key_set == 3 else 6): if (byte >> i) & 1: key = STENO_KEY_CHART[(key_set * 6) + i] self._pressed_keys.append(key) if key_set == 3: # Last possible set, the stroke is finished. self._finish_stroke()
3,418
Python
.py
73
37.657534
84
0.581731
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,739
stentura.py
openstenoproject_plover/plover/machine/stentura.py
# Copyright (c) 2011 Hesky Fisher # See LICENSE.txt for details. # Many thanks to a steno geek for help with the protocol. # TODO: Come up with a mechanism to communicate back to the engine when there # is a connection error. # TODO: Address any generic exceptions still left. """Thread-based monitoring of a stenotype machine using the stentura protocol. """ """ The stentura protocol uses packets to communicate with the machine. A request packet is sent to the machine and a response packet is received. If no response is received after a one second timeout then the same packet should be sent again. The machine may hold off on responding to a READC packet for up to 500ms if there are no new strokes. Each request packet should have a sequence number that is one higher than the previously sent packet modulo 256. The response packet will have the same sequence number. Each packet consists of a header followed by an optional data section. All multibyte fields are little endian. The request packet header is structured as follows: - SOH: 1 byte. Always set to ASCII SOH (0x1). - seq: 1 byte. The sequence number of this packet. - length: 2 bytes. The total length of the packet, including the data section, in bytes. - action: 2 bytes. The action requested. See actions below. - p1: 2 bytes. Parameter 1. The values for the parameters depend on the action. - p2: 2 bytes. Parameter 2. - p3: 2 bytes. Parameter 3. - p4: 2 bytes. Parameter 4. - p5: 2 bytes. Parameter 5. - checksum: 2 bytes. The CRC is computed over the packet from seq through p5. The specific CRC algorithm used is described above in the Crc class. The request header can be followed by a data section. The meaning of the data section depends on the action: - data: variable length. - crc: 2 bytes. A CRC over just the data section. The response packet header is structured as follows: - SOH: 1 byte. Always set to ASCII SOH (0x1). - seq: 1 byte. The sequence number of the request packet. - length: 2 bytes. The total length of the packet, including the data section, in bytes. - action: 2 bytes. The action of the request packet. - error: 2 bytes. The error code. Zero if no error. - p1: 2 bytes. Parameter 1. The values of the parameters depend on the action. - p2: 2 bytes. Parameter 2. - checksum: 2 bytes. The CRC is computed over the packet from seq through p2. The response header can be follows by a data section, whose meaning is dependent on the action. The structure is the same as in request packets. The stentura machine has a concept of drives and files. The first (and possibly only) drive is called A. Each file consists of a set of one or more blocks. Each block is 512 bytes long. In addition to regular files, there is a realtime file whose name is 'REALTIME.000'. All strokes typed are appended to this file. Subsequent reads from the realtime file ignore positional arguments and only return all the strokes since the last read action. However, opening the file again and reading from the beginning will result in all the same strokes being read again. The only reliable way to jump to the end is to do a full, sequential, read to the end before processing any strokes. I'm told that on some machines sending a READC without an OPEN will just read from the realtime file. The contents of the files are a sequence of strokes. Each stroke consists of four bytes. Each byte has the two most significant bytes set to one. The rest of the byte is a bitmask indicating which keys were pressed during the stroke. The format is as follows: 11^#STKP 11WHRAO* 11EUFRPB 11LGTSDZ ^ is something called a stenomark. I'm not sure what that is. # is the number bar. Note: Only OPEN and READC are needed to get strokes as they are typed from the realtime file. Actions and their packets: All unmentioned parameters should be zero and unless explicitly mentioned the packet should have no data section. RESET (0x14): Unknown. DISKSTATUS (0x7): Unknown. p1 is set to the ASCII value corresponding to the drive letter, e.g. 'A'. GETDOS (0x18): Returns the DOS filenames for the files in the requested drive. p1 is set to the ASCII value corresponding to the drive letter, e.g. 'A'. p2 is set to one to return the name of the realtime file (which is always 'REALTIME.000'). p3 controls which page to return, with 20 filenames per page. The return packet contains a data section that is 512 bytes long. The first bytes seems to be one. The filename for the first file starts at offset 32. My guess would be that the other filenames would exist at a fixed offset of 24 bytes apart. So first filename is at 32, second is at 56, third at 80, etc. There seems to be some meta data stored after the filename but I don't know what it means. DELETE (0x3): Deletes the specified files. NOP on realtime file. p1 is set to the ASCII value corresponding to the drive letter, e.g. 'A'. The filename is specified in the data section. OPEN (0xA): Opens a file for reading. This action is sticky and causes this file to be the current file for all following READC packets. p1 is set to the ASCII value corresponding to the drive letter, e.g. 'A'. The filename is specified in the data section. I'm told that if there is an error opening the realtime file then no strokes have been written yet. TODO: Check that and implement workaround. READC (0xB): Reads characters from the currently opened file. p1 is set to 1, I'm not sure why. p3 is set to the maximum number of bytes to read but should probably be 512. p4 is set to the block number. p5 is set to the starting byte offset within the block. It's possible that the machine will ignore the positional arguments to READC when reading from the realtime file and just return successive values for each call. The response will have the number of bytes read in p1 (but the same is deducible from the length). The data section will have the contents read from the file. CLOSE (0x2): Closes the current file. p1 is set to one, I don't know why. TERM (0x15): Unknown. DIAG (0x19): Unknown. """ import struct from plover import log import plover.machine.base # Python 3 replacement for Python 2 buffer. def buffer(object, offset=None, size=None): if offset is None: offset = 0 if size is None: size = len(object)-offset return memoryview(object)[offset:offset+size] def _allocate_buffer(): return bytearray(1024) class _ProtocolViolationException(Exception): """Something has happened that is doesn't follow the protocol.""" pass class _StopException(Exception): """The thread was asked to stop.""" pass class _TimeoutException(Exception): """An operation has timed out.""" pass class _ConnectionLostException(Exception): """Cannot communicate with the machine.""" pass _CRC_TABLE = [ 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040 ] def _crc(data, offset=None, size=None): """Compute the Crc algorithm used by the stentura protocol. This algorithm is described by the Rocksoft^TM Model CRC Algorithm as follows: Name : "CRC-16" Width : 16 Poly : 8005 Init : 0000 RefIn : True RefOut : True XorOut : 0000 Check : BB3D Args: - data: The data to checksum. The data should be an iterable that returns bytes Returns: The computed crc for the data. """ if offset is None: offset = 0 if size is None: size = len(data) - offset checksum = 0 for n in range(offset, offset + size): b = data[n] checksum = (_CRC_TABLE[(checksum ^ b) & 0xff] ^ ((checksum >> 8) & 0xff)) return checksum def _write_to_buffer(buf, offset, data): """Write data to buf at offset. Note: buf must be big enough, and will not be extended as needed. Args: - buf: The buffer. Should be of type bytearray() - offset. The offset at which to start writing. - data: An iterable containing the data to write. """ buf[offset:offset+len(data)] = data # Helper table for parsing strokes of the form: # 11^#STKP 11WHRAO* 11EUFRPB 11LGTSDZ _STENO_KEY_CHART = ('^', '#', 'S-', 'T-', 'K-', 'P-', # Byte #1 'W-', 'H-', 'R-', 'A-', 'O-', '*', # Byte #2 '-E', '-U', '-F', '-R', '-P', '-B', # Byte #3 '-L', '-G', '-T', '-S', '-D', '-Z') # Byte #4 def _parse_stroke(a, b, c, d): """Parse a stroke and return a list of keys pressed. Args: - a: The first byte. - b: The second byte. - c: The third byte. - d: The fourth byte. Returns: A sequence with all the keys pressed in the stroke. e.g. ['S-', 'A-', '-T'] """ fullstroke = (((a & 0x3f) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | d & 0x3f) return [_STENO_KEY_CHART[i] for i in range(24) if (fullstroke & (1 << (23 - i)))] def _parse_strokes(data): """Parse strokes from a buffer and return a sequence of strokes. Args: - data: A byte buffer. Returns: A sequence of strokes. Each stroke is a sequence of pressed keys. Throws: - _ProtocolViolationException if the data doesn't follow the protocol. """ strokes = [] if (len(data) % 4) != 0: raise _ProtocolViolationException( "Data size is not divisible by 4: %d" % (len(data))) for b in data: if (b & 0b11000000) != 0b11000000: raise _ProtocolViolationException("Data is not stroke: 0x%X" % (b)) for a, b, c, d in zip(*([iter(data)] * 4)): strokes.append(_parse_stroke(a, b, c, d)) return strokes # Actions _CLOSE = 0x2 _DELETE = 0x3 _DIAG = 0x19 _DISKSTATUS = 0x7 _GETDOS = 0x18 _OPEN = 0xA _READC = 0xB _RESET = 0x14 _TERM = 0x15 # Compiled struct for writing request headers. _REQUEST_STRUCT = struct.Struct('<2B7H') _SHORT_STRUCT = struct.Struct('<H') def _make_request(buf, action, seq, p1=0, p2=0, p3=0, p4=0, p5=0, data=None): """Create a request packet. Args: - buf: The buffer used for the packet. Should be bytearray() and big enough, as it will not be extended as needed. - action: The action for the packet. - seq: The sequence numbe for the packet. - p1 - p5: Parameter N for the packet (default: 0). - data: The data to add to the packet as a sequence of bytes, if any (default: None). Returns: A buffer as a slice of the passed in buf that holds the packet. """ length = 18 if data: length += len(data) + 2 # +2 for the data CRC. _REQUEST_STRUCT.pack_into(buf, 0, 1, seq, length, action, p1, p2, p3, p4, p5) crc = _crc(buf, 1, 15) _SHORT_STRUCT.pack_into(buf, 16, crc) if data: _write_to_buffer(buf, 18, data) crc = _crc(data) _SHORT_STRUCT.pack_into(buf, length - 2, crc) return buffer(buf, 0, length) def _make_open(buf, seq, drive, filename): """Make a packet with the OPEN command. Args: - buf: The buffer to use of type bytearray(). Will be extended if needed. - seq: The sequence number of the packet. - drive: The letter of the drive (probably 'A'). - filename: The name of the file (probably 'REALTIME.000'). Returns: A buffer as a slice of the passed in buf that holds the packet. """ return _make_request(buf, _OPEN, seq, p1=ord(drive), data=filename) def _make_read(buf, seq, block, byte, length=512): """Make a packet with the READC command. Args: - buf: The buffer to use of type bytearray(). Will be extended if needed. - seq: The sequence number of the packet. - block: The index of the file block to read. - byte: The byte offset within the block at which to start reading. - length: The number of bytes to read, max 512 (default: 512). Returns: A buffer as a slice of the passed in buf that holds the packet. """ return _make_request(buf, _READC, seq, p1=1, p3=length, p4=block, p5=byte) def _make_reset(buf, seq): """Make a packet with the RESET command. Args: - buf: The buffer to use of type bytearray(). Will be extended if needed. - seq: The sequence number of the packet. Returns: A buffer as a slice of the passed in buf that holds the packet. """ return _make_request(buf, _RESET, seq) def _validate_response(packet): """Validate a response packet. Args: - packet: The packet to validate. Returns: True if the packet is valid, False otherwise. """ if len(packet) < 14: return False length = _SHORT_STRUCT.unpack(packet[2:4])[0] if length != len(packet): return False if _crc(packet, 1, 13) != 0: return False if length > 14: if length < 17: return False if _crc(packet, 14) != 0: return False return True def _read_data(port, stop, buf, offset, num_bytes): """Read data off the serial port and into port at offset. Args: - port: The serial port to read. - stop: An event which, when set, causes this function to stop. - buf: The buffer to write. - offset: The offset into the buffer to write. - num_bytes: The number of bytes expected Returns: The number of bytes read. Raises: _StopException: If stop is set. _TimeoutException: If the timeout is reached with no data read. """ assert num_bytes > 0 read_bytes = port.read(num_bytes) if stop.is_set(): raise _StopException() if num_bytes > len(read_bytes): raise _TimeoutException() _write_to_buffer(buf, offset, read_bytes) return len(read_bytes) MINIMUM_PACKET_LENGTH = 14 def _read_packet(port, stop, buf): """Read a full packet from the port. Reads from the port until a full packet is received or the stop or timeout conditions are met. Args: - port: The port to read. - stop: Event object used to request stopping. - buf: The buffer to write. Returns: A buffer as a slice of buf holding the packet. Raises: _ProtocolViolationException: If the packet doesn't conform to the protocol. _TimeoutException: If the packet is not read within the timeout. _StopException: If a stop was requested. """ bytes_read = 0 bytes_read += _read_data(port, stop, buf, bytes_read, 4) assert 4 == bytes_read packet_length = _SHORT_STRUCT.unpack_from(buf, 2)[0] # Packet length should always be at least 14 bytes long if packet_length < MINIMUM_PACKET_LENGTH: raise _ProtocolViolationException() bytes_read += _read_data(port, stop, buf, bytes_read, packet_length - bytes_read) packet = buffer(buf, 0, bytes_read) if not _validate_response(packet): raise _ProtocolViolationException() return buffer(buf, 0, bytes_read) def _write_to_port(port, data): """Write data to a port. Args: - port: The port to write. - data: The data to write """ while data: data = buffer(data, port.write(data)) def _send_receive(port, stop, packet, buf, max_tries=3): """Send a packet and return the response. Send a packet and make sure there is a response and it is for the correct request and return it, otherwise retry max_retries times. Args: - port: The port to read. - stop: Event used to signal tp stop. - packet: The packet to send. May be used after buf is written so should be distinct. - buf: Buffer used to store response. - max_tries: The maximum number of times to retry sending the packet and reading the response before giving up (default: 3). Returns: A buffer as a slice of buf holding the response packet. Raises: _ConnectionLostException: If we can't seem to talk to the machine. _StopException: If a stop was requested. _ProtocolViolationException: If the responses packet violates the protocol. """ request_action = _SHORT_STRUCT.unpack(packet[4:6])[0] for attempt in range(max_tries): _write_to_port(port, packet) try: response = _read_packet(port, stop, buf) if response[1] != packet[1]: continue # Wrong sequence number. response_action = _SHORT_STRUCT.unpack(response[4:6])[0] if request_action != response_action: raise _ProtocolViolationException() return response except _TimeoutException: continue raise _ConnectionLostException() class _SequenceCounter: """A mod 256 counter.""" def __init__(self, seq=0): """Init a new counter starting at seq.""" self.seq = seq def __call__(self): """Return the next value.""" cur, self.seq = self.seq, (self.seq + 1) % 256 return cur def _read(port, stop, seq, request_buf, response_buf, stroke_buf, block, byte): """Read the full contents of the current file from beginning to end. The file should be opened first. Args: - port: The port to use. - stop: The event used to request stopping. - seq: A _SequenceCounter instance to use to track packets. - request_buf: Buffer to use for request packet. - response_buf: Buffer to use for response packet. - stroke_buf: Buffer to use for strokes read from the file. Raises: _ProtocolViolationException: If the protocol is violated. _StopException: If a stop is requested. _ConnectionLostException: If we can't seem to talk to the machine. """ bytes_read = 0 while True: packet = _make_read(request_buf, seq(), block, byte, length=512) response = _send_receive(port, stop, packet, response_buf) p1 = _SHORT_STRUCT.unpack(response[8:10])[0] if not ((p1 == 0 and len(response) == 14) or # No data. (p1 == len(response) - 16)): # Data. raise _ProtocolViolationException() if p1 == 0: return block, byte, buffer(stroke_buf, 0, bytes_read) data = buffer(response, 14, p1) _write_to_buffer(stroke_buf, bytes_read, data) bytes_read += len(data) byte += p1 if byte >= 512: block += 1 byte -= 512 def _loop(port, stop, callback, ready_callback, timeout=1): """Enter into a loop talking to the machine and returning strokes. Args: - port: The port to use. - stop: The event used to signal that it's time to stop. - callback: A function that takes a list of pressed keys, called for each stroke. - ready_callback: A function that is called when the machine is ready. - timeout: Timeout to use when waiting for a response in seconds. Should be 1 when talking to a real machine. (default: 1) Raises: _ProtocolViolationException: If the protocol is violated. _StopException: If a stop is requested. _ConnectionLostException: If we can't seem to talk to the machine. """ # We want to give the machine a standard timeout to finish whatever it's # doing but we also want to stop if asked to so this is the safe way to # wait. if stop.wait(timeout): raise _StopException() port.flushInput() port.flushOutput() # Set serial port timeout to the timeout value port.timeout = timeout # With Python 3, our replacement for buffer(), using memoryview, does not # allow resizing the original bytearray(), so make sure our buffers are big # enough to begin with. request_buf, response_buf = _allocate_buffer(), _allocate_buffer() stroke_buf = _allocate_buffer() seq = _SequenceCounter() request = _make_open(request_buf, seq(), b'A', b'REALTIME.000') # Any checking needed on the response packet? _send_receive(port, stop, request, response_buf) # Do a full read to get to the current position in the realtime file. block, byte = 0, 0 block, byte, _ = _read(port, stop, seq, request_buf, response_buf, stroke_buf, block, byte) ready_callback() while True: block, byte, data = _read(port, stop, seq, request_buf, response_buf, stroke_buf, block, byte) strokes = _parse_strokes(data) for stroke in strokes: callback(stroke) class Stentura(plover.machine.base.SerialStenotypeBase): """Stentura interface. This class implements the three methods necessary for a standard stenotype interface: start_capture, stop_capture, and add_callback. """ KEYS_LAYOUT = ''' # # # # # # # # # # S- T- P- H- * -F -P -L -T -D S- K- W- R- * -R -B -G -S -Z A- O- -E -U ^ ''' def run(self): """Overrides base class run method. Do not call directly.""" try: _loop(self.serial_port, self.finished, self._notify_keys, self._ready) except _StopException: pass except Exception: log.info("Failure starting Stentura", exc_info=True) self._error()
23,132
Python
.py
537
38.01676
102
0.683569
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,740
__init__.py
openstenoproject_plover/plover/machine/__init__.py
# Copyright (c) 2010 Joshua Harlan Lifton. # See LICENSE.txt for details. """Stenotype machines."""
101
Python
.py
3
32.333333
42
0.742268
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,741
base.py
openstenoproject_plover/plover/machine/base.py
# Copyright (c) 2010-2011 Joshua Harlan Lifton. # See LICENSE.txt for details. # TODO: add tests for all machines # TODO: add tests for new status callbacks """Base classes for machine types. Do not use directly.""" import binascii import threading import serial from plover import _, log from plover.machine.keymap import Keymap from plover.misc import boolean # i18n: Machine state. STATE_STOPPED = _('stopped') # i18n: Machine state. STATE_INITIALIZING = _('initializing') # i18n: Machine state. STATE_RUNNING = _('connected') # i18n: Machine state. STATE_ERROR = _('disconnected') class StenotypeBase: """The base class for all Stenotype classes.""" # Layout of physical keys. KEYS_LAYOUT = '' # And special actions to map to. ACTIONS = () # Fallback to use as machine type for finding a compatible keymap # if one is not already available for this machine type. KEYMAP_MACHINE_TYPE = None def __init__(self): # Setup default keymap with no translation of keys. keys = self.get_keys() self.keymap = Keymap(keys, keys) self.keymap.set_mappings(zip(keys, keys)) self.stroke_subscribers = [] self.state_subscribers = [] self.state = STATE_STOPPED def set_keymap(self, keymap): """Setup machine keymap.""" self.keymap = keymap def start_capture(self): """Begin listening for output from the stenotype machine.""" pass def stop_capture(self): """Stop listening for output from the stenotype machine.""" pass def add_stroke_callback(self, callback): """Subscribe to output from the stenotype machine. Argument: callback -- The function to call whenever there is output from the stenotype machine and output is being captured. """ self.stroke_subscribers.append(callback) def remove_stroke_callback(self, callback): """Unsubscribe from output from the stenotype machine. Argument: callback -- A function that was previously subscribed. """ self.stroke_subscribers.remove(callback) def add_state_callback(self, callback): self.state_subscribers.append(callback) def remove_state_callback(self, callback): self.state_subscribers.remove(callback) def _notify(self, steno_keys): """Invoke the callback of each subscriber with the given argument.""" for callback in self.stroke_subscribers: callback(steno_keys) def _notify_keys(self, steno_keys): steno_keys = self.keymap.keys_to_actions(steno_keys) if steno_keys: self._notify(steno_keys) def set_suppression(self, enabled): '''Enable keyboard suppression. This is only of use for the keyboard machine, to suppress the keyboard when then engine is running. ''' pass def suppress_last_stroke(self, send_backspaces): '''Suppress the last stroke key events after the fact. This is only of use for the keyboard machine, and the engine is resumed with a command stroke. Argument: send_backspaces -- The function to use to send backspaces. ''' pass def _set_state(self, state): self.state = state for callback in self.state_subscribers: callback(state) def _stopped(self): self._set_state(STATE_STOPPED) def _initializing(self): self._set_state(STATE_INITIALIZING) def _ready(self): self._set_state(STATE_RUNNING) def _error(self): self._set_state(STATE_ERROR) @classmethod def get_actions(cls): """List of supported actions to map to.""" return cls.ACTIONS @classmethod def get_keys(cls): return tuple(cls.KEYS_LAYOUT.split()) @classmethod def get_option_info(cls): """Get the default options for this machine.""" return {} class ThreadedStenotypeBase(StenotypeBase, threading.Thread): """Base class for thread based machines. Subclasses should override run. """ def __init__(self): threading.Thread.__init__(self) self._on_unhandled_exception(self._error) self.name += '-machine' StenotypeBase.__init__(self) self.finished = threading.Event() def _on_unhandled_exception(self, action): super_invoke_excepthook = self._invoke_excepthook def invoke_excepthook(self): action() super_invoke_excepthook(self) self._invoke_excepthook = invoke_excepthook def run(self): """This method should be overridden by a subclass.""" pass def start_capture(self): """Begin listening for output from the stenotype machine.""" self.finished.clear() self._initializing() self.start() def stop_capture(self): """Stop listening for output from the stenotype machine.""" self.finished.set() try: self.join() except RuntimeError: pass self._stopped() class SerialStenotypeBase(ThreadedStenotypeBase): """For use with stenotype machines that connect via serial port. This class implements the three methods necessary for a standard stenotype interface: start_capture, stop_capture, and add_callback. """ # Default serial parameters. SERIAL_PARAMS = { 'port': None, 'baudrate': 9600, 'bytesize': 8, 'parity': 'N', 'stopbits': 1, 'timeout': 2.0, } def __init__(self, serial_params): """Monitor the stenotype over a serial port. The key-value pairs in the <serial_params> dict are the same as the keyword arguments for a serial.Serial object. """ ThreadedStenotypeBase.__init__(self) self._on_unhandled_exception(self._handle_disconnect) self.serial_port = None self.serial_params = serial_params def _close_port(self): if self.serial_port is None: return self.serial_port.close() self.serial_port = None def _handle_disconnect(self): self._close_port() self._error() 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) def stop_capture(self): """Stop listening for output from the stenotype machine.""" ThreadedStenotypeBase.stop_capture(self) self._close_port() @classmethod def get_option_info(cls): """Get the default options for this machine.""" sb = lambda s: int(float(s)) if float(s).is_integer() else float(s) converters = { 'port': str, 'baudrate': int, 'bytesize': int, 'parity': str, 'stopbits': sb, 'timeout': float, 'xonxoff': boolean, 'rtscts': boolean, } return { setting: (default, converters[setting]) for setting, default in cls.SERIAL_PARAMS.items() } def _iter_packets(self, packet_size): """Yield packets of <packets_size> bytes until the machine is stopped. N.B.: to workaround the fact that the Toshiba Bluetooth stack on Windows does not correctly handle the read timeout setting (returning immediately if some data is already available): - the effective timeout is re-configured to <timeout/packet_size> - multiple reads are done (until a packet is complete) - an incomplete packet will only be discarded if one of those reads return no data (but not on short read) """ self.serial_port.timeout = max( self.serial_params.get('timeout', 1.0) / packet_size, 0.01, ) packet = b'' while not self.finished.is_set(): raw = self.serial_port.read(packet_size - len(packet)) if not raw: if packet: log.error('discarding incomplete packet: %s', binascii.hexlify(packet)) packet = b'' continue packet += raw if len(packet) != packet_size: continue yield packet packet = b''
8,814
Python
.py
234
29.128205
86
0.625765
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,742
passport.py
openstenoproject_plover/plover/machine/passport.py
# Copyright (c) 2013 Hesky Fisher # See LICENSE.txt for details. "Thread-based monitoring of a stenotype machine using the passport protocol." from itertools import zip_longest from plover.machine.base import SerialStenotypeBase # Passport protocol is documented here: # http://www.eclipsecat.com/?q=system/files/Passport%20protocol_0.pdf class Passport(SerialStenotypeBase): """Passport interface.""" KEYS_LAYOUT = ''' # # # # # # # # # # S T P H ~ F N L Y D C K W R * Q B G X Z A O E U ! ^ + ''' SERIAL_PARAMS = dict(SerialStenotypeBase.SERIAL_PARAMS) SERIAL_PARAMS.update(baudrate=38400) def __init__(self, params): super().__init__(params) self.packet = [] def _read(self, b): b = chr(b) self.packet.append(b) if b == '>': self._handle_packet(''.join(self.packet)) del self.packet[:] def _handle_packet(self, packet): encoded = packet.split('/')[1] steno_keys = [] for key, shadow in grouper(encoded, 2, 0): shadow = int(shadow, base=16) if shadow >= 8: steno_keys.append(key) self._notify_keys(steno_keys) def run(self): """Overrides base class run method. Do not call directly.""" self._ready() while not self.finished.is_set(): # Grab data from the serial port. raw = self.serial_port.read(max(1, self.serial_port.inWaiting())) for b in raw: self._read(b) def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args)
1,800
Python
.py
48
29.770833
77
0.598158
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,743
keymap.py
openstenoproject_plover/plover/machine/keymap.py
import json from collections import defaultdict, OrderedDict from plover import log class Keymap: def __init__(self, keys, actions): # List of supported actions. self._actions = OrderedDict((action, n) for n, action in enumerate(actions)) self._actions['no-op'] = len(self._actions) # List of supported keys. self._keys = OrderedDict((key, n) for n, key in enumerate(keys)) # action -> keys self._mappings = {} # key -> action self._bindings = {} def get_keys(self): return self._keys.keys() def get_actions(self): return self._actions.keys() def set_bindings(self, bindings): # Set from: # { key1: action1, key2: action1, ... keyn: actionn } mappings = defaultdict(list) for key, action in dict(bindings).items(): mappings[action].append(key) self.set_mappings(mappings) 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)) def get_bindings(self): return self._bindings def get_mappings(self): return self._mappings def get_action(self, key, default=None): return self._bindings.get(key, default) def keys_to_actions(self, key_list): action_list = [] for key in key_list: assert key in self._keys, "'%s' not in %s" % (key, self._keys) action = self._bindings[key] if 'no-op' != action: action_list.append(action) return action_list def keys(self): return self._mappings.keys() def values(self): return self._mappings.values() def __len__(self): return len(self._mappings) def __getitem__(self, key): return self._mappings[key] 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)) def __iter__(self): return iter(self._mappings) def __eq__(self, other): return self.get_mappings() == other.get_mappings() def __str__(self): # Use the more compact list of mappings format: # [[action1, [key1, key2]], [action2, [key3]], ...] return json.dumps(list(self._mappings.items()))
5,290
Python
.py
125
30.768
97
0.542185
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,744
procat.py
openstenoproject_plover/plover/machine/procat.py
# Copyright (c) 2016 Ted Morin # See LICENSE.txt for details. """Thread-based monitoring of a ProCAT stenotype machine.""" import binascii from plover import log from plover.machine.base import SerialStenotypeBase # ProCAT machines send 4 bytes per stroke, with the last byte only consisting of # FF. So we need only look at the first 3 bytes to see our steno. The leading # bit is 0. STENO_KEY_CHART = (None, '#', 'S-', 'T-', 'K-', 'P-', 'W-', 'H-', 'R-', 'A-', 'O-', '*', '-E', '-U', '-F', '-R', '-P', '-B', '-L', '-G', '-T', '-S', '-D', '-Z', ) BYTES_PER_STROKE = 4 class ProCAT(SerialStenotypeBase): """Interface for ProCAT machines. """ KEYS_LAYOUT = ''' # # # # # # # # # # S- T- P- H- * -F -P -L -T -D S- K- W- R- * -R -B -G -S -Z A- O- -E -U ''' KEYMAP_MACHINE_TYPE = 'TX Bolt' def run(self): """Overrides base class run method. Do not call directly.""" self._ready() for packet in self._iter_packets(BYTES_PER_STROKE): if (packet[0] & 0x80) or packet[3] != 0xff: log.error('discarding invalid packet: %s', binascii.hexlify(packet)) continue self._notify_keys( self.process_steno_packet(packet) ) @staticmethod def process_steno_packet(raw): # Raw packet has 4 bytes, we only care about the first 3 steno_keys = [] for i, b in enumerate(raw[:3]): for j in range(0, 8): if b & 0x80 >> j: key = STENO_KEY_CHART[i * 8 + j] steno_keys.append(key) return steno_keys
1,753
Python
.py
45
29.622222
80
0.515044
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,745
__init__.py
openstenoproject_plover/plover/machine/keyboard_capture/__init__.py
class Capture: """Keyboard capture interface.""" # Callbacks for keyboard press/release events. key_down = lambda key: None key_up = lambda key: None def start(self): """Start capturing key events.""" raise NotImplementedError() def cancel(self): """Stop capturing key events.""" raise NotImplementedError() def suppress(self, suppressed_keys=()): """Setup suppression.""" raise NotImplementedError()
482
Python
.py
14
27.642857
50
0.645788
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,746
add_translation.py
openstenoproject_plover/plover/gui_none/add_translation.py
from plover.engine import StartingStrokeState class AddTranslation: def __init__(self, engine): self._status = None self._engine = engine self._translator_states = [] self._strokes, self._translation = (None, None) engine.hook_connect('add_translation', self.trigger) def _get_state(self): return ( self._engine.translator_state, self._engine.starting_stroke_state, ) def _set_state(self, translator_state, starting_stroke_state): self._engine.translator_state = translator_state self._engine.starting_stroke_state = starting_stroke_state def _clear_state(self, undo=False): self._engine.clear_translator_state(undo) self._engine.starting_stroke_state = StartingStrokeState() def _push_state(self): self._translator_states.insert(0, self._get_state()) def _pop_state(self): self._engine.clear_translator_state(True) self._set_state(*self._translator_states.pop(0)) @staticmethod def _stroke_filter(key, value): return value != '{PLOVER:ADD_TRANSLATION}' def send_string(self, s): self._translation += s def send_backspaces(self, b): self._translation = self._translation[:-b] def trigger(self): if self._status is None: self._push_state() self._clear_state() self._engine.add_dictionary_filter(self._stroke_filter) self._status = 'strokes' elif self._status == 'strokes': self._engine.remove_dictionary_filter(self._stroke_filter) state = self._get_state()[0] assert state.translations if len(state.translations) == 1: # Abort add translation. self._pop_state() self._status = None return self._strokes = tuple(s.rtfcre # Ignore add translation strokes. for t in state.translations[:-1] for s in t.strokes) self._clear_state(undo=True) self._translation = '' self._engine.hook_connect('send_string', self.send_string) self._engine.hook_connect('send_backspaces', self.send_backspaces) self._status = 'translations' elif self._status == 'translations': state = self._get_state()[0] self._engine.hook_disconnect('send_string', self.send_string) self._engine.hook_disconnect('send_backspaces', self.send_backspaces) self._engine.add_translation(self._strokes, self._translation.strip()) self._pop_state() self._status = None
2,768
Python
.py
62
33.225806
82
0.592056
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,747
engine.py
openstenoproject_plover/plover/gui_none/engine.py
from threading import Thread, current_thread from plover.engine import StenoEngine from plover.gui_none.add_translation import AddTranslation class Engine(StenoEngine, Thread): def __init__(self, config, controller, keyboard_emulation): StenoEngine.__init__(self, config, controller, keyboard_emulation) Thread.__init__(self) self.name += '-engine' self._add_translation = AddTranslation(self) # self.hook_connect('quit', self.quit) def _in_engine_thread(self): return current_thread() == self def start(self): Thread.start(self) StenoEngine.start(self) def join(self): Thread.join(self) return self.code
710
Python
.py
18
32.611111
74
0.683748
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,748
main.py
openstenoproject_plover/plover/gui_none/main.py
from threading import Event from plover.oslayer.keyboardcontrol import KeyboardEmulation from plover.gui_none.engine import Engine def show_error(title, message): print('%s: %s' % (title, message)) def main(config, controller): engine = Engine(config, controller, KeyboardEmulation()) if not engine.load_config(): return 3 quitting = Event() engine.hook_connect('quit', quitting.set) engine.start() try: quitting.wait() except KeyboardInterrupt: engine.quit() return engine.join()
547
Python
.py
17
27.294118
60
0.711832
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,749
send_command.py
openstenoproject_plover/plover/scripts/send_command.py
import argparse import sys from plover import log from plover.oslayer.controller import Controller def main(): description = 'Send a command to a running Plover instance.' parser = argparse.ArgumentParser(description=description) parser.add_argument('-l', '--log-level', choices=['debug', 'info', 'warning', 'error'], default=None, help='set log level') parser.add_argument('command', metavar='COMMAND{:ARGS}', type=str, help='the command to send') args = parser.parse_args(args=sys.argv[1:]) if args.log_level is not None: log.set_level(args.log_level.upper()) log.setup_platform_handler() with Controller() as controller: if controller.is_owner: log.error('sending command failed: no running instance found') sys.exit(1) controller.send_command(args.command) if __name__ == '__main__': main()
932
Python
.py
22
35.136364
91
0.654144
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,750
dist_main.py
openstenoproject_plover/plover/scripts/dist_main.py
import os import sys import subprocess from plover.oslayer.config import CONFIG_DIR, PLATFORM, PLUGINS_PLATFORM def main(): args = sys.argv[:] args[0:1] = [sys.executable, '-m', 'plover.scripts.main', '--gui', 'qt'] if '--no-user-plugins' in args[3:]: args.remove('--no-user-plugins') args.insert(1, '-s') os.environ['PYTHONUSERBASE'] = os.path.join(CONFIG_DIR, 'plugins', PLUGINS_PLATFORM) if PLATFORM == 'win': # Workaround https://bugs.python.org/issue19066 subprocess.Popen(args, cwd=os.getcwd()) sys.exit(0) os.execv(args[0], args) if __name__ == '__main__': main()
644
Python
.py
18
30.722222
88
0.634461
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,751
main.py
openstenoproject_plover/plover/scripts/main.py
# -*- coding: utf-8 -*- # Copyright (c) 2013 Hesky Fisher # See LICENSE.txt for details. "Launch the plover application." import argparse import atexit import os import sys import subprocess import traceback import pkg_resources from plover.config import Config from plover.oslayer.controller import Controller from plover.oslayer.config import CONFIG_DIR, CONFIG_FILE, PLATFORM from plover.registry import registry from plover import log from plover import __name__ as __software_name__ from plover import __version__ def init_config_dir(): """Creates plover's config dir. This usually only does anything the first time plover is launched. """ # Create the configuration directory if needed. if not os.path.exists(CONFIG_DIR): os.makedirs(CONFIG_DIR) # Create a default configuration file if one doesn't already exist. if not os.path.exists(CONFIG_FILE): open(CONFIG_FILE, 'wb').close() def main(): """Launch plover.""" description = "Run the plover stenotype engine. This is a graphical application." parser = argparse.ArgumentParser(description=description) parser.add_argument('--version', action='version', version='%s %s' % (__software_name__.capitalize(), __version__)) parser.add_argument('-s', '--script', default=None, nargs=argparse.REMAINDER, help='use another plugin console script as main entrypoint, ' 'passing in the rest of the command line arguments, ' 'print list of available scripts when no argument is given') parser.add_argument('-l', '--log-level', choices=['debug', 'info', 'warning', 'error'], default=None, help='set log level') parser.add_argument('-g', '--gui', default=None, help='set gui') args = parser.parse_args(args=sys.argv[1:]) if args.log_level is not None: log.set_level(args.log_level.upper()) log.setup_platform_handler() log.info('Plover %s', __version__) log.info('configuration directory: %s', CONFIG_DIR) if PLATFORM == 'mac': # Fixes PyQt issue on macOS Big Sur. os.environ['QT_MAC_WANTS_LAYER'] = '1' registry.update() if args.gui is None: gui_priority = { 'qt': 1, 'none': -1, } gui_list = sorted(registry.list_plugins('gui'), reverse=True, key=lambda gui: gui_priority.get(gui.name, 0)) gui = gui_list[0].obj else: gui = registry.get_plugin('gui', args.gui).obj try: if args.script is not None: if args.script: # Create a mapping of available console script, # with the following priorities (highest first): # - {project_name}-{version}:{script_name} # - {project_name}:{script_name} # - {script_name} console_scripts = {} for e in sorted(pkg_resources.iter_entry_points('console_scripts'), key=lambda e: (e.dist, e.name)): for key in ( '%s-%s:%s' % (e.dist.project_name, e.dist.version, e.name), '%s:%s' % (e.dist.project_name, e.name), e.name, ): console_scripts[key] = e entrypoint = console_scripts.get(args.script[0]) if entrypoint is None: log.error('no such script: %s', args.script[0]) code = 1 else: sys.argv = args.script try: code = entrypoint.load()() except SystemExit as e: code = e.code if code is None: code = 0 else: print('available script(s):') dist = None for e in sorted(pkg_resources.iter_entry_points('console_scripts'), key=lambda e: (str(e.dist), e.name)): if dist != e.dist: dist = e.dist print('%s:' % dist) print('- %s' % e.name) code = 0 os._exit(code) # Ensure only one instance of Plover is running at a time. with Controller() as controller: if controller.is_owner: # Not other instance, regular startup. if PLATFORM == 'mac': import appnope appnope.nope() init_config_dir() # This must be done after calling init_config_dir, so # Plover's configuration directory actually exists. log.setup_logfile() config = Config(CONFIG_FILE) code = gui.main(config, controller) else: log.info('another instance is running, sending `focus` command') # Other instance? Try focusing the main window. try: controller.send_command('focus') except ConnectionRefusedError: log.error('connection to existing instance failed, ' 'force cleaning before restart') # Assume the previous instance died, leaving # a stray socket, try cleaning it... if not controller.force_cleanup(): raise # ...and restart. code = -1 else: code = 0 except: gui.show_error('Unexpected error', traceback.format_exc()) code = 2 # Execute atexit handlers. atexit._run_exitfuncs() if code == -1: # Restart. args = sys.argv[:] if args[0].endswith('.py') or args[0].endswith('.pyc'): # We're running from source. spec = sys.modules['__main__'].__spec__ assert sys.argv[0] == spec.origin args[0:1] = [sys.executable, '-m', spec.name] if PLATFORM == 'win': # Workaround https://bugs.python.org/issue19066 subprocess.Popen(args, cwd=os.getcwd()) code = 0 else: os.execv(args[0], args) os._exit(code) if __name__ == '__main__': main()
6,444
Python
.py
152
29.671053
91
0.53395
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,752
key_combo.py
openstenoproject_plover/plover/meta/key_combo.py
def meta_key_combo(ctx, combo): action = ctx.copy_last_action() action.combo = combo return action
111
Python
.py
4
23.75
35
0.691589
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,753
currency.py
openstenoproject_plover/plover/meta/currency.py
def meta_retro_currency(ctx, dict_format): action = ctx.copy_last_action() last_words = ctx.last_words(count=1) if not last_words: return action currency = last_words[0].replace(',', '') for cast, fmt in ( (int, '{:,}' ), (float, '{:,.2f}'), ): try: cast_input = cast(currency) except ValueError: continue currency_format = dict_format.replace('c', fmt) action.prev_attach = True action.prev_replace = last_words[0] action.text = currency_format.format(cast_input) action.word = None break return action
648
Python
.py
21
23.190476
56
0.567783
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,754
conditional.py
openstenoproject_plover/plover/meta/conditional.py
import re from plover.formatting import _LookAheadAction IF_NEXT_META_RX = re.compile(r'((?:[^\\/]|\\\\|\\/)*)/?') IF_NEXT_ESCAPE_RX = re.compile(r'\\([\\/])') def meta_if_next_matches(ctx, meta): pattern, result1, result2 = [ IF_NEXT_ESCAPE_RX.sub(r'\1', s) for s in filter(None, IF_NEXT_META_RX.split(meta, 2)) ] action_list = [] for alternative in result1, result2: action = ctx.new_action() action.text = alternative action_list.append(action) return _LookAheadAction(pattern, *action_list)
560
Python
.py
15
32
61
0.62963
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,755
command.py
openstenoproject_plover/plover/meta/command.py
def meta_command(ctx, command): action = ctx.copy_last_action() action.command = command return action
115
Python
.py
4
24.75
35
0.711712
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,756
word_end.py
openstenoproject_plover/plover/meta/word_end.py
def meta_word_end(ctx, meta): action = ctx.copy_last_action() action.word_is_finished = True return action
119
Python
.py
4
25.75
35
0.695652
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,757
case.py
openstenoproject_plover/plover/meta/case.py
from plover.formatting import Case, apply_case def meta_case(ctx, case): case = Case(case.lower()) action = ctx.copy_last_action() action.next_case = case return action def meta_retro_case(ctx, case): case = Case(case.lower()) action = ctx.copy_last_action() action.prev_attach = True last_words = ctx.last_words(count=1) if last_words: action.prev_replace = last_words[0] action.text = apply_case(last_words[0], case) else: action.text = '' return action
527
Python
.py
17
25.823529
53
0.658777
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,758
attach.py
openstenoproject_plover/plover/meta/attach.py
from os.path import commonprefix from plover.formatting import ( Case, META_ATTACH_FLAG, META_CARRY_CAPITALIZATION, has_word_boundary, rightmost_word, ) from plover.orthography import add_suffix def meta_attach(ctx, meta): action = ctx.new_action() begin = meta.startswith(META_ATTACH_FLAG) end = meta.endswith(META_ATTACH_FLAG) if not (begin or end): # If not specified, attach at both ends. meta = META_ATTACH_FLAG + meta + META_ATTACH_FLAG begin = end = True if begin: meta = meta[len(META_ATTACH_FLAG):] action.prev_attach = True if end: meta = meta[:-len(META_ATTACH_FLAG)] action.next_attach = True action.word_is_finished = False last_word = ctx.last_action.word or '' if not meta: # We use an empty connection to indicate a "break" in the # application of orthography rules. This allows the # stenographer to tell Plover not to auto-correct a word. action.orthography = False elif ( last_word and not meta.isspace() and ctx.last_action.orthography and begin and (not end or has_word_boundary(meta)) ): new_word = add_suffix(last_word, meta) common_len = len(commonprefix([last_word, new_word])) replaced = last_word[common_len:] action.prev_replace = ctx.last_text(len(replaced)) assert replaced.lower() == action.prev_replace.lower() last_word = last_word[:common_len] meta = new_word[common_len:] action.text = meta if action.prev_attach: action.word = rightmost_word(last_word + meta) return action def meta_carry_capitalize(ctx, meta): # Meta format: ^~|content^ (attach flags are optional) action = ctx.new_action() if ctx.last_action.next_case == Case.CAP_FIRST_WORD: action.next_case = Case.CAP_FIRST_WORD begin = meta.startswith(META_ATTACH_FLAG) if begin: meta = meta[len(META_ATTACH_FLAG):] action.prev_attach = True meta = meta[len(META_CARRY_CAPITALIZATION):] end = meta.endswith(META_ATTACH_FLAG) if end: meta = meta[:-len(META_ATTACH_FLAG)] action.next_attach = True action.word_is_finished = False if meta or begin or end: action.text = meta return action
2,343
Python
.py
65
29.446154
65
0.650396
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,759
glue.py
openstenoproject_plover/plover/meta/glue.py
def meta_glue(ctx, text): action = ctx.new_action() action.glue = True action.text = text if ctx.last_action.glue: action.prev_attach = True return action
183
Python
.py
7
21.142857
33
0.653409
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,760
mode.py
openstenoproject_plover/plover/meta/mode.py
from plover.formatting import Case, SPACE def meta_mode(ctx, cmdline): """ cmdline should be: caps: UPPERCASE lower: lowercase title: Title Case camel: titlecase, no space, initial lowercase snake: underscore_space reset_space: Space resets to ' ' reset_case: Reset to normal case set_space:xy: Set space to xy reset: Reset to normal case, space resets to ' ' """ args = cmdline.split(':', 1) mode = args.pop(0).lower() action = ctx.copy_last_action() if mode == 'set_space': action.space_char = args[0] if args else '' return action # No argument allowed for other mode directives. if args: raise ValueError('%r is not a valid mode' % cmdline) if mode == 'caps': action.case = Case.UPPER elif mode == 'title': action.case = Case.TITLE elif mode == 'lower': action.case = Case.LOWER elif mode == 'snake': action.space_char = '_' elif mode == 'camel': action.case = Case.TITLE action.space_char = '' action.next_case = Case.LOWER_FIRST_CHAR elif mode == 'reset': action.space_char = SPACE action.case = None elif mode == 'reset_space': action.space_char = SPACE elif mode == 'reset_case': action.case = None else: raise ValueError('%r is not a valid mode' % cmdline) return action
1,451
Python
.py
45
25.222222
60
0.59943
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,761
punctuation.py
openstenoproject_plover/plover/meta/punctuation.py
from plover.formatting import Case def meta_comma(ctx, text): action = ctx.new_action() action.text = text action.prev_attach = True return action def meta_stop(ctx, text): action = ctx.new_action() action.prev_attach = True action.text = text action.next_case = Case.CAP_FIRST_WORD return action
336
Python
.py
12
23.75
42
0.700935
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,762
workflow_generate.py
openstenoproject_plover/.github/workflows/ci/workflow_generate.py
#!/usr/bin/env python import shlex import textwrap import jinja2 import yaml class GithubActionsYamlLoader(yaml.SafeLoader): @staticmethod def _unsupported(kind, token): return SyntaxError('Github Actions does not support %s:\n%s' % (kind, token.start_mark)) def fetch_alias(self): super().fetch_alias() raise self._unsupported('aliases', self.tokens[0]) def fetch_anchor(self): super().fetch_anchor() raise self._unsupported('anchors', self.tokens[0]) environment = jinja2.Environment( block_start_string='<%', block_end_string='%>', variable_start_string='<@', variable_end_string='@>', comment_start_string='<#', comment_end_string='#>', lstrip_blocks=True, trim_blocks=True, ) with open('.github/workflows/ci/workflow_context.yml') as fp: context = yaml.load(fp, Loader=yaml.SafeLoader) with open('.github/workflows/ci/workflow_template.yml') as fp: template = environment.from_string(fp.read()) for j in context['jobs']: base_type = j['type'].split('_')[0] j['id'] = '%s_%s' % (base_type, j['variant'].lower().replace(' ', '_').replace('.', '')) j['name'] = '%s (%s)' % (base_type.capitalize(), j['variant']) j['needs'] = j.get('needs', []) j['reqs'] = ['reqs/%s.txt' % r for r in j['reqs']] j['cache_extra_deps'] = j.get('cache_extra_deps', []) if context['skippy_enabled']: # Path to the "skip_cache" file. j['skip_cache_path'] = '.skip_cache_{id}'.format(**j) # Name of the "skip_cache" (name + tree SHA1 = key). j['skip_cache_name'] = 'skip_{id}_py-{python}_{platform}'.format(cache_epoch=context['cache_epoch'], **j) shell_definition = [] for k, v in sorted(j.items()): if isinstance(v, list): v = '(' + ' '.join(map(shlex.quote, v)) + ')' else: v = shlex.quote(v) shell_definition.append('job_%s=%s' % (k, v)) j['shell_definition'] = '; '.join(shell_definition) # Render template. workflow = template.render(context) # Save result. with open('.github/workflows/ci.yml', 'w') as fp: fp.write(textwrap.dedent( ''' # # DO NOT MODIFY! AUTO-GENERATED FROM: # .github/workflows/ci/workflow_template.yml # ''').lstrip()) fp.write(workflow) # And try parsing it to check it's valid YAML, # and ensure anchors/aliases are not used. GithubActionsYamlLoader(workflow).get_single_data()
2,473
Python
.py
64
33.15625
113
0.619883
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,763
download.py
openstenoproject_plover/plover_build_utils/download.py
#!/usr/bin/env python3 from urllib.request import urlopen from urllib.parse import urlsplit import hashlib import os import sys DOWNLOADS_DIR = os.path.join('.cache', 'downloads') def download(url, sha1=None, filename=None, downloads_dir=DOWNLOADS_DIR): if filename is None: filename = os.path.basename(urlsplit(url).path) dst = os.path.join(downloads_dir, filename) dst_dir = os.path.dirname(dst) if not os.path.exists(dst_dir): os.makedirs(dst_dir) retries = 0 while retries < 2: if sha1 is None or not os.path.exists(dst): retries += 1 try: with urlopen(url) as req, open(dst, 'wb') as fp: fp.write(req.read()) except Exception as e: print('error', e, file=sys.stderr) continue if sha1 is None: break h = hashlib.sha1() with open(dst, 'rb') as fp: while True: d = fp.read(4 * 1024 * 1024) if not d: break h.update(d) if h.hexdigest() == sha1: break print('sha1 does not match: %s instead of %s' % (h.hexdigest(), sha1), file=sys.stderr) os.unlink(dst) assert os.path.exists(dst), 'could not successfully retrieve %s' % url return dst if __name__ == '__main__': args = sys.argv[1:] url = args.pop(0) sha1 = None filename = None if args: sha1 = args.pop(0) or None if args: filename = args.pop(0) print(download(url, sha1, filename))
1,612
Python
.py
50
23.7
74
0.563344
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,764
tree.py
openstenoproject_plover/plover_build_utils/tree.py
#!/usr/bin/env python3 from pathlib import Path import functools import operator import os.path import stat import sys BLOCK_SIZES = ( (1024*1024*1024*1024, 'T'), (1024*1024*1024, 'G'), (1024*1024, 'M'), (1024, 'K'), ) def format_size(size): for bs, unit in BLOCK_SIZES: if size >= bs: return '%.1f%s' % (size / bs, unit) return str(size) def tree(path, dirs_only=False, max_depth=0, _depth=0): path = Path(path) lst = path.lstat() is_symlink = stat.S_ISLNK(lst.st_mode) st = lst if is_symlink else path.stat() is_dir = stat.S_ISDIR(st.st_mode) if is_symlink: size = 0 elif is_dir: size = functools.reduce(operator.add, [ tree(p, dirs_only=dirs_only, max_depth=max_depth, _depth=_depth+1) for p in sorted(path.iterdir()) ], 0) else: size = lst.st_size if (is_dir or not dirs_only) and \ (not max_depth or _depth <= max_depth): p = str(path) if is_dir: p += os.path.sep if is_symlink: p += ' -> ' + os.readlink(str(path)) print('%10s %s' % (format_size(size), p)) return size def main(): args = [] max_depth = 0 dirs_only = False argv = iter(sys.argv[1:]) for a in argv: if a == '-d': dirs_only = True continue if a == '-L': max_depth = int(next(argv)) continue if a.startswith('-'): raise ValueError(a) args.append(a) for a in args: tree(a, dirs_only=dirs_only, max_depth=max_depth) if __name__ == '__main__': main()
1,723
Python
.py
63
20.396825
57
0.525455
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,765
setup.py
openstenoproject_plover/plover_build_utils/setup.py
import contextlib import importlib import os import subprocess import sys from setuptools.command.build_py import build_py from setuptools.command.develop import develop import pkg_resources import setuptools class Command(setuptools.Command): def build_in_place(self): self.run_command('build_py') self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') @contextlib.contextmanager def project_on_sys_path(self, build=True): ei_cmd = self.get_finalized_command("egg_info") if build: self.build_in_place() else: ei_cmd.run() old_path = sys.path[:] old_modules = sys.modules.copy() try: sys.path.insert(0, pkg_resources.normalize_path(ei_cmd.egg_base)) pkg_resources.working_set.__init__() pkg_resources.add_activation_listener(lambda dist: dist.activate()) pkg_resources.require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version)) yield finally: sys.path[:] = old_path sys.modules.clear() sys.modules.update(old_modules) pkg_resources.working_set.__init__() def bdist_wheel(self): '''Run bdist_wheel and return resulting wheel file path.''' whl_cmd = self.get_finalized_command('bdist_wheel') whl_cmd.run() for cmd, py_version, dist_path in whl_cmd.distribution.dist_files: if cmd == 'bdist_wheel': return dist_path raise Exception('could not find wheel path') # i18n support. {{{ def babel_options(package, resource_dir=None): if resource_dir is None: localedir = '%s/messages' % package else: localedir = '%s/%s' % (package, resource_dir) template = '%s/%s.pot' % (localedir, package) return { 'compile_catalog': { 'domain': package, 'directory': localedir, }, 'extract_messages': { 'add_comments': ['i18n:'], 'output_file': template, 'strip_comments': True, }, 'init_catalog': { 'domain': package, 'input_file': template, 'output_dir': localedir, }, 'update_catalog': { 'domain': package, 'output_dir': localedir, } } # }}} # UI generation. {{{ class BuildUi(Command): description = 'build UI files' user_options = [ ('force', 'f', 'force re-generation of all UI files'), ] hooks = ''' plover_build_utils.pyqt:fix_icons plover_build_utils.pyqt:no_autoconnection '''.split() def initialize_options(self): self.force = False def finalize_options(self): pass def _build_ui(self, src): dst = os.path.splitext(src)[0] + '_ui.py' if not self.force and os.path.exists(dst) and \ os.path.getmtime(dst) >= os.path.getmtime(src): return cmd = ( sys.executable, '-m', 'PyQt5.uic.pyuic', '--from-import', src, ) if self.verbose: print('generating', dst) contents = subprocess.check_output(cmd).decode('utf-8') for hook in self.hooks: mod_name, attr_name = hook.split(':') mod = importlib.import_module(mod_name) hook_fn = getattr(mod, attr_name) contents = hook_fn(contents) with open(dst, 'w') as fp: fp.write(contents) def _build_resources(self, src): dst = os.path.join( os.path.dirname(os.path.dirname(src)), os.path.splitext(os.path.basename(src))[0] ) + '_rc.py' cmd = ( sys.executable, '-m', 'PyQt5.pyrcc_main', src, '-o', dst, ) if self.verbose: print('generating', dst) subprocess.check_call(cmd) def run(self): self.run_command('egg_info') std_hook_prefix = __package__ + '.pyqt:' hooks_info = [ h[len(std_hook_prefix):] if h.startswith(std_hook_prefix) else h for h in self.hooks ] if self.verbose: print('generating UI using hooks:', ', '.join(hooks_info)) ei_cmd = self.get_finalized_command('egg_info') for src in ei_cmd.filelist.files: if src.endswith('.qrc'): self._build_resources(src) if src.endswith('.ui'): self._build_ui(src) # }}} # Patched `build_py` command. {{{ class BuildPy(build_py): build_dependencies = [] def run(self): for command in self.build_dependencies: self.run_command(command) build_py.run(self) # }}} # Patched `develop` command. {{{ class Develop(develop): build_dependencies = [] def run(self): for command in self.build_dependencies: self.run_command(command) develop.run(self) # }}}
4,977
Python
.py
148
24.945946
83
0.570625
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,766
trim.py
openstenoproject_plover/plover_build_utils/trim.py
#!/usr/bin/env python3 import glob import shutil import sys import os def trim(directory, patterns_file, verbose=True, dry_run=False): if dry_run: verbose = True # Build list of patterns. pattern_list = [] exclude_list = [] subdir = directory with open(patterns_file) as fp: for line in fp: line = line.strip() # Empty line, ignore. if not line: continue # Comment, ignore. if line.startswith('#'): continue # Sub-directory change. if line.startswith(':'): subdir = os.path.join(directory, line[1:]) continue # Pattern (relative to current sub-directory). if line.startswith('!'): exclude_list.append(os.path.join(subdir, line[1:])) else: pattern_list.append(os.path.join(subdir, line)) # Create list of files to keep based on exclusion list. to_keep = set() for pattern in exclude_list: to_keep.update(glob.glob(pattern, recursive=True)) # Trim directory tree. for pattern in pattern_list: for path in reversed(glob.glob(pattern, recursive=True)): if path in to_keep: continue if verbose: print('removing', path) if dry_run: continue if os.path.isdir(path): shutil.rmtree(path) else: os.unlink(path) if __name__ == '__main__': directory, patterns_file = sys.argv[1:] trim(directory, patterns_file)
1,644
Python
.py
50
22.98
67
0.551919
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,767
get_pip.py
openstenoproject_plover/plover_build_utils/get_pip.py
#!/usr/bin/env python3 import os import shutil import sys import zipfile from .download import download from .install_wheels import WHEELS_CACHE, install_wheels PIP_VERSION = '21.3.1' PIP_WHEEL_URL = 'https://files.pythonhosted.org/packages/a4/6d/6463d49a933f547439d6b5b98b46af8742cc03ae83543e4d7688c2420f8b/pip-21.3.1-py3-none-any.whl' PIP_INSTALL = os.path.join('.cache', 'pip', PIP_VERSION) def get_pip(args=None): # Download the wheel. pip_wheel = download(PIP_WHEEL_URL, downloads_dir=WHEELS_CACHE) # "Install" it (can't run directly from it because of the PEP 517 code). if not os.path.exists(PIP_INSTALL): os.makedirs(PIP_INSTALL) # Extract it. with zipfile.ZipFile(pip_wheel) as z: z.extractall(PIP_INSTALL) # Get rid of the info metadata. shutil.rmtree(os.path.join(PIP_INSTALL, 'pip-%s.dist-info' % PIP_VERSION)) # If no arguments where passed, or only options arguments, # automatically install pip / setuptools / wheel, # otherwise, let the caller be in charge. if args is None or not next((a for a in args if not a.startswith('-')), None): args = (args or []) + [pip_wheel, 'setuptools', 'wheel'] # Run pip from the wheel we just got. install_wheels(args, pip_install=os.path.join(PIP_INSTALL, 'pip')) if __name__ == '__main__': get_pip(sys.argv[1:])
1,376
Python
.py
30
41.133333
152
0.695067
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,768
zipdir.py
openstenoproject_plover/plover_build_utils/zipdir.py
#!/usr/bin/env python3 import os import sys import zipfile def zipdir(directory, compression=zipfile.ZIP_DEFLATED): zipname = '%s.zip' % directory prefix = os.path.dirname(directory) with zipfile.ZipFile(zipname, 'w', compression) as zf: for dirpath, dirnames, filenames in os.walk(directory): for name in filenames: src = os.path.join(dirpath, name) dst = os.path.relpath(src, prefix) zf.write(src, dst) if __name__ == '__main__': directory = sys.argv[1] zipdir(directory)
567
Python
.py
16
28.625
63
0.637363
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,769
pyqt.py
openstenoproject_plover/plover_build_utils/pyqt.py
import re def fix_icons(contents): # replace ``addPixmap(QtGui.QPixmap(":/settings.svg"),`` # by ``addFile(":/settings.svg", QtCore.QSize(),`` contents = re.sub( r'\baddPixmap\(QtGui\.QPixmap\(("[^"]*")\),', r'addFile(\1, QtCore.QSize(),', contents ) return contents def gettext(contents): # replace ``_translate("context", `` by ``_(`` contents = re.sub(r'\n', ( '\n' '_ = __import__(__package__.split(".", 1)[0])._\n' ), contents, 1) contents = re.sub( r'\n\s+_translate = QtCore\.QCoreApplication\.translate\n', '\n', contents ) def repl(m): gd = m.groupdict() comment = '{ws}# i18n: Widget: “{widget}”'.format(**gd) field = gd['field'] if field: field = ' '.join( word.lower() for word in re.split(r'([A-Z][a-z_0-9]+)', field) if word ) comment += ", {field}".format(field=field) comment += '.' gd['pre2'] = gd['pre2'] or '' return '{comment}\n{ws}{pre1}{pre2}_('.format(comment=comment, **gd) contents = re.sub((r'(?P<ws> *)(?P<pre1>.*?)(?P<pre2>\.set(?P<field>\w+)\()?' r'\b_translate\("(?P<widget>.*)",\s'), repl, contents) assert re.search(r'\b_translate\(', contents) is None return contents def no_autoconnection(contents): # remove calls to ``QtCore.QMetaObject.connectSlotsByName`` contents = re.sub( r'\n\s+QtCore\.QMetaObject\.connectSlotsByName\(\w+\)\n', '\n', contents ) return contents
1,635
Python
.py
47
26.744681
81
0.51962
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,770
source_less.py
openstenoproject_plover/plover_build_utils/source_less.py
#!/usr/bin/env python3 import fnmatch import os import py_compile import shutil import sys def source_less(directory, excludes=()): for dirpath, dirnames, filenames in os.walk(directory): if '__pycache__' in dirnames: dirnames.remove('__pycache__') cache = os.path.join(dirpath, '__pycache__') shutil.rmtree(cache) for name in filenames: if not name.endswith('.py'): continue py = os.path.join(dirpath, name) for pattern in excludes: if fnmatch.fnmatch(py, pattern): break else: pyc = py + 'c' py_compile.compile(py, cfile=pyc) os.unlink(py) if __name__ == '__main__': directory = sys.argv[1] excludes = sys.argv[2:] source_less(directory, excludes)
871
Python
.py
27
23.074074
59
0.556615
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,771
install_wheels.py
openstenoproject_plover/plover_build_utils/install_wheels.py
#!/usr/bin/env python3 import os import subprocess import sys # Default directory for caching wheels. WHEELS_CACHE = os.path.join('.cache', 'wheels') def _split_opts(text): args = text.split() assert (len(args) % 2) == 0 return {name: int(nb_args) for name, nb_args in zip(*([iter(args)] * 2))} # Allowed `pip install/wheel` options. _PIP_OPTS = _split_opts( # General. ''' --isolated 0 -v 0 --verbose 0 -q 0 --quiet 0 --log 1 --proxy 1 --retries 1 --timeout 1 --exists-action 1 --trusted-host 1 --cert 1 --client-cert 1 --cache-dir 1 --no-cache-dir 0 --disable-pip-version-check 0 --progress-bar 1 ''' # Install/Wheel. ''' -c 1 --constraint 1 -r 1 --requirement 1 --no-deps 0 --use-pep517 0 ''' # Package Index. ''' -i 1 --index-url 1 --extra-index-url 1 --no-index 0 -f 1 --find-links 1 --process-dependency-links 0 ''' ) # Allowed `pip install` only options. _PIP_INSTALL_OPTS = _split_opts( ''' -t 1 --target 1 -U 0 --upgrade 0 --upgrade-strategy 1 --force-reinstall 0 -I 0 --ignore-installed 0 --user 0 --root 1 --prefix 1 --require-hashes 0 --no-warn-script-location 0 ''' ) def _pip(args, pip_install=None, verbose=True, no_progress=True): if no_progress: args.append('--progress-bar=off') cmd = [sys.executable] if sys.flags.no_site: cmd.append('-S') if sys.flags.no_user_site: cmd.append('-s') if sys.flags.ignore_environment: cmd.append('-E') if pip_install is not None: cmd.append(pip_install) else: cmd.extend(('-m', 'pip')) cmd.extend(args) if verbose: print('running', ' '.join(cmd), flush=True) return subprocess.call(cmd) def install_wheels(args, pip_install=None, verbose=True, no_install=False, no_progress=True): wheels_cache = WHEELS_CACHE wheel_args = [] install_args = [] while len(args) > 0: a = args.pop(0) if not a.startswith('-'): wheel_args.append(a) install_args.append(a) continue if '=' in a: a = a.split('=', 1) args.insert(0, a[1]) a = a[0] opt = a if opt == '-w': wheels_cache = args.pop(0) continue if opt == '--no-install': no_install = True continue if opt == '--progress-bar': if args[0] == 'off': no_progress = True del args[0] continue no_progress = False if opt in _PIP_OPTS: nb_args = _PIP_OPTS[opt] install_only = False elif opt in _PIP_INSTALL_OPTS: nb_args = _PIP_INSTALL_OPTS[opt] install_only = True else: raise ValueError('unsupported option: %s' % opt) a = [opt] + args[:nb_args] del args[:nb_args] if not install_only: wheel_args.extend(a) install_args.extend(a) wheel_args[0:0] = ['wheel', '-f', wheels_cache, '-w', wheels_cache] install_args[0:0] = ['install', '--no-index', '--no-cache-dir', '-f', wheels_cache] pip_kwargs = dict(pip_install=pip_install, no_progress=no_progress) code = _pip(wheel_args, **pip_kwargs) if code == 0 and not no_install: code = _pip(install_args, **pip_kwargs) if code != 0: raise Exception('wheels installation failed: pip execution returned %u' % code) if __name__ == '__main__': install_wheels(sys.argv[1:])
3,653
Python
.py
131
21.083969
93
0.553561
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,772
check_requirements.py
openstenoproject_plover/plover_build_utils/check_requirements.py
#!/usr/bin/env python3 from collections import OrderedDict import pkg_resources from plover.registry import Registry def sorted_requirements(requirements): return sorted(requirements, key=lambda r: str(r).lower()) # Find all available distributions. all_requirements = [ dist.as_requirement() for dist in pkg_resources.working_set ] # Find Plover requirements. plover_deps = set() for dist in pkg_resources.require('plover'): plover_deps.add(dist.as_requirement()) # Load plugins. registry = Registry(suppress_errors=False) registry.update() # Find plugins requirements. plugins = OrderedDict() plugins_deps = set() for plugin_dist in registry.list_distributions(): if plugin_dist.dist.project_name != 'plover': plugins[plugin_dist.dist.as_requirement()] = set() for requirement, deps in plugins.items(): for dist in pkg_resources.require(str(requirement)): if dist.as_requirement() not in plover_deps: deps.add(dist.as_requirement()) plugins_deps.update(deps) # List requirements. print('# plover') for requirement in sorted_requirements(plover_deps): print(requirement) for requirement, deps in plugins.items(): print('#', requirement.project_name) for requirement in sorted_requirements(deps): print(requirement) print('# other') for requirement in sorted_requirements(all_requirements): if requirement not in plover_deps and \ requirement not in plugins_deps: print(requirement) print('# ''vim: ft=cfg commentstring=#\\ %s list')
1,540
Python
.py
43
32.348837
61
0.744953
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,773
blackbox.py
openstenoproject_plover/plover_build_utils/testing/blackbox.py
import ast import functools import inspect import operator import re import shlex import textwrap from plover import system from plover.formatting import Formatter from plover.steno import normalize_steno from plover.steno_dictionary import StenoDictionary from plover.translation import Translator from .output import CaptureOutput from .steno import steno_to_stroke BLACKBOX_OUTPUT_RX = re.compile("r?['\"]") def blackbox_setup(blackbox): blackbox.output = CaptureOutput() blackbox.formatter = Formatter() blackbox.formatter.set_output(blackbox.output) blackbox.translator = Translator() blackbox.translator.set_min_undo_length(100) blackbox.translator.add_listener(blackbox.formatter.format) blackbox.dictionary = blackbox.translator.get_dictionary() blackbox.dictionary.set_dicts([StenoDictionary()]) def blackbox_replay(blackbox, name, test): # Hide from traceback on assertions (reduce output size for failed tests). __tracebackhide__ = operator.methodcaller('errisinstance', AssertionError) definitions, instructions = test.strip().rsplit('\n\n', 1) for entry in definitions.split('\n'): if entry.startswith(':'): _blackbox_replay_action(blackbox, entry[1:]) continue for steno, translation in ast.literal_eval( '{' + entry + '}' ).items(): blackbox.dictionary.set(normalize_steno(steno), translation) # Track line number for a more user-friendly assertion message. lines = test.split('\n') lnum = len(lines)-3 - test.rstrip().rsplit('\n\n', 1)[1].count('\n') for step in re.split('(?<=[^\\\\])\n', instructions): # Mark current instruction's line. lnum += 1 step = step.strip() # Support for changing some settings on the fly. if step.startswith(':'): _blackbox_replay_action(blackbox, step[1:]) continue steno, output = step.split(None, 1) steno = list(map(steno_to_stroke, normalize_steno(steno.strip()))) output = output.strip() assert_msg = ( name + '\n' + '\n'.join(('> ' if n == lnum else ' ') + l for n, l in enumerate(lines)) + '\n' ) if BLACKBOX_OUTPUT_RX.match(output): # Replay strokes. list(map(blackbox.translator.translate, steno)) # Check output. expected_output = ast.literal_eval(output) assert_msg += ( ' ' + repr(blackbox.output.text) + '\n' '!= ' + repr(expected_output) ) assert blackbox.output.text == expected_output, assert_msg elif output.startswith('raise '): expected_exception = output[6:].strip() try: list(map(blackbox.translator.translate, steno)) except Exception as e: exception_class = e.__class__.__name__ else: exception_class = 'None' assert_msg += ( ' ' + exception_class + '\n' '!= ' + expected_exception ) assert exception_class == expected_exception, assert_msg else: raise ValueError('invalid output:\n%s' % output) def _blackbox_replay_action(blackbox, action_spec): action, *args = shlex.split(action_spec) if action == 'start_attached': assert not args blackbox.formatter.start_attached = True elif action == 'spaces_after': assert not args blackbox.formatter.set_space_placement('After Output') elif action == 'spaces_before': assert not args blackbox.formatter.set_space_placement('Before Output') elif action == 'system': assert len(args) == 1 system.setup(args[0]) else: raise ValueError('invalid action:\n%r' % action_spec) def blackbox_test(cls_or_fn): if inspect.isclass(cls_or_fn): class wrapper(cls_or_fn): pass for name in dir(wrapper): if name.startswith('test_'): fn = getattr(wrapper, name) new_fn = blackbox_test(fn) setattr(wrapper, name, new_fn) else: name = cls_or_fn.__name__ test = textwrap.dedent(cls_or_fn.__doc__) # Use a lamdbda to reduce output size for failed tests. wrapper = lambda bb, *args, **kwargs: (blackbox_setup(bb), cls_or_fn(bb, *args, **kwargs), blackbox_replay(bb, name, test)) wrapper = functools.wraps(cls_or_fn)(wrapper) return wrapper
4,589
Python
.py
112
32.348214
131
0.616005
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,774
dict.py
openstenoproject_plover/plover_build_utils/testing/dict.py
from contextlib import contextmanager from pathlib import Path import os import tempfile @contextmanager def make_dict(tmp_path, contents, extension=None, name=None): kwargs = {'dir': str(tmp_path)} if name is not None: kwargs['prefix'] = name + '_' if extension is not None: kwargs['suffix'] = '.' + extension fd, path = tempfile.mkstemp(**kwargs) try: os.write(fd, contents) os.close(fd) yield Path(path) finally: os.unlink(path)
506
Python
.py
18
23
61
0.652263
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,775
output.py
openstenoproject_plover/plover_build_utils/testing/output.py
class CaptureOutput: def __init__(self): self.instructions = [] self.text = '' def send_backspaces(self, n): assert n <= len(self.text) self.text = self.text[:-n] self.instructions.append(('b', n)) def send_string(self, s): self.text += s self.instructions.append(('s', s)) def send_key_combination(self, c): self.instructions.append(('c', c)) def send_engine_command(self, c): self.instructions.append(('e', c))
510
Python
.py
15
26.533333
42
0.579592
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,776
__init__.py
openstenoproject_plover/plover_build_utils/testing/__init__.py
from .blackbox import blackbox_test from .dict import make_dict from .output import CaptureOutput from .parametrize import parametrize from .steno import steno_to_stroke from .steno_dictionary import dictionary_test
216
Python
.py
6
35
45
0.857143
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,777
parametrize.py
openstenoproject_plover/plover_build_utils/testing/parametrize.py
import inspect import pytest def parametrize(tests, arity=None): '''Helper for parametrizing pytest tests. Expects a list of lambdas, one per test. Each lambda must return the parameters for its respective test. Test identifiers will be automatically generated, from the test number and its lambda definition line (1.10, 2.12, 3.20, ...). If arity is None, the arguments being parametrized will be automatically set from the function's last arguments, according to the numbers of parameters for each test. ''' ids = [] argvalues = [] for n, t in enumerate(tests): line = inspect.getsourcelines(t)[1] ids.append('%u:%u' % (n+1, line)) argvalues.append(t()) if arity is None: arity = len(argvalues[0]) assert arity > 0 def decorator(fn): argnames = list( parameter.name for parameter in inspect.signature(fn).parameters.values() if parameter.default is inspect.Parameter.empty )[-arity:] if arity == 1: argnames = argnames[0] return pytest.mark.parametrize(argnames, argvalues, ids=ids)(fn) return decorator
1,189
Python
.py
31
31.451613
76
0.662902
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,778
steno_dictionary.py
openstenoproject_plover/plover_build_utils/testing/steno_dictionary.py
from collections import defaultdict from contextlib import contextmanager import ast import functools import inspect import os import pytest from plover.registry import registry from plover.resource import ASSET_SCHEME from plover.steno import normalize_steno from plover.steno_dictionary import StenoDictionary from .dict import make_dict from .parametrize import parametrize class _DictionaryTests: @staticmethod def make_dict(contents): return contents @contextmanager def tmp_dict(self, tmp_path, contents): contents = self.make_dict(contents) with make_dict(tmp_path, contents, extension=self.DICT_EXTENSION) as dict_path: yield dict_path @contextmanager def sample_dict(self, tmp_path): with self.tmp_dict(tmp_path, self.DICT_SAMPLE) as dict_path: yield dict_path @staticmethod def parse_entries(entries): return { normalize_steno(k): v for k, v in ast.literal_eval('{' + entries + '}').items() } def test_readonly_writable_file(self, tmp_path): ''' Writable file: match class read-only attribute. ''' with self.sample_dict(tmp_path) as dict_path: d = self.DICT_CLASS.load(str(dict_path)) assert d.readonly == self.DICT_CLASS.readonly def test_readonly_readonly_file(self, tmp_path): ''' Read-only file: read-only dictionary. ''' with self.sample_dict(tmp_path) as dict_path: dict_path.chmod(0o440) try: d = self.DICT_CLASS.load(str(dict_path)) assert d.readonly finally: # Deleting the file will fail on Windows # if we don't restore write permission. dict_path.chmod(0o660) def test_readonly_asset(self, tmp_path, monkeypatch): ''' Assets are always read-only. ''' with self.sample_dict(tmp_path) as dict_path: fake_asset = ASSET_SCHEME + 'fake:' + dict_path.name def fake_asset_only(r, v=None): assert r.startswith(ASSET_SCHEME + 'fake:') return v monkeypatch.setattr('plover.resource._asset_filename', functools.partial(fake_asset_only, v=str(dict_path))) d = self.DICT_CLASS.load(fake_asset) assert d.readonly VALID_KEY = ('TEFT', '-G') @pytest.mark.parametrize('method_name, args', ( ('__delitem__', (VALID_KEY,)), ('__setitem__', (VALID_KEY, 'pouet!')), ('clear' , ()), ('save' , ()), ('update' , ()), )) def test_readonly_no_change_allowed(self, tmp_path, method_name, args): ''' Don't allow changing a read-only dictionary. ''' with self.sample_dict(tmp_path) as dict_path: d = self.DICT_CLASS.load(str(dict_path)) d.readonly = True method = getattr(d, method_name) with pytest.raises(AssertionError): method(*args) def _test_entrypoint(self): ''' Check a corresponding `plover.dictionary` entrypoint exists. ''' plugin = registry.get_plugin('dictionary', self.DICT_EXTENSION) assert plugin.obj == self.DICT_CLASS DUMMY = object() MISSING_KEY = "ceci n'est pas une clef" MISSING_TRANSLATION = "ceci n'est pas une translation" def _test_load(self, tmp_path, contents, expected): ''' Test `load` implementation. ''' with self.tmp_dict(tmp_path, contents) as dict_path: expected_timestamp = dict_path.stat().st_mtime if inspect.isclass(expected): # Expect an exception. with pytest.raises(expected): self.DICT_CLASS.load(str(dict_path)) return # Except a successful load. d = self.DICT_CLASS.load(str(dict_path)) # Parse entries: entries = self.parse_entries(expected) # - expected: must be present expected_entries = {k: v for k, v in entries.items() if v is not None} # - unexpected: must not be present unexpected_entries = {k for k, v in entries.items() if v is None} # Basic checks. assert d.readonly == self.DICT_CLASS.readonly assert d.timestamp == expected_timestamp if self.DICT_SUPPORT_SEQUENCE_METHODS: assert sorted(d.items()) == sorted(expected_entries.items()) assert sorted(d) == sorted(expected_entries) assert len(d) == len(expected_entries) else: assert tuple(d.items()) == () assert tuple(d) == () assert len(d) == 0 for k, v in expected_entries.items(): assert k in d assert d[k] == v assert d.get(k) == v assert d.get(k, self.DUMMY) == v for k in unexpected_entries: assert k not in d with pytest.raises(KeyError): d[k] assert d.get(k) == None assert d.get(k, self.DUMMY) == self.DUMMY assert self.MISSING_KEY not in d assert d.get(self.MISSING_KEY, self.DUMMY) is self.DUMMY assert d.get(self.MISSING_KEY) == None with pytest.raises(KeyError): d[self.MISSING_KEY] # Longest key check. expected_longest_key = functools.reduce(max, (len(k) for k in expected_entries), 0) assert d.longest_key == expected_longest_key # Reverse lookup checks. expected_reverse = defaultdict(set) if self.DICT_SUPPORT_REVERSE_LOOKUP: for k, v in expected_entries.items(): expected_reverse[v].add(k) for v, key_set in expected_reverse.items(): assert d.reverse_lookup(v) == key_set assert d.reverse_lookup(self.MISSING_TRANSLATION) == set() # Case reverse lookup checks. expected_casereverse = defaultdict(set) if self.DICT_SUPPORT_CASEREVERSE_LOOKUP: for v in expected_entries.values(): expected_casereverse[v.lower()].add(v) for v, value_set in expected_casereverse.items(): assert d.casereverse_lookup(v) == value_set assert d.casereverse_lookup(self.MISSING_TRANSLATION) == set() class _ReadOnlyDictionaryTests: def test_readonly_no_create_allowed(self, tmp_path): ''' Don't allow creating a read-only dictionary. ''' with self.sample_dict(tmp_path) as dict_path: with pytest.raises(ValueError): self.DICT_CLASS.create(str(dict_path)) _TEST_DICTIONARY_UPDATE_DICT = { ('S-G',): 'something', ('SPH-G',): 'something', ('SPH*G',): 'Something', ('SPH', 'THEUPBG'): 'something', } _TEST_DICTIONARY_UPDATE_STENODICT = StenoDictionary() _TEST_DICTIONARY_UPDATE_STENODICT.update(_TEST_DICTIONARY_UPDATE_DICT) class _WritableDictionaryTests: def test_longest_key(self): ''' Check `longest_key` support. ''' assert self.DICT_SUPPORT_SEQUENCE_METHODS d = self.DICT_CLASS() assert d.longest_key == 0 d[('S',)] = 'a' assert d.longest_key == 1 d[('S', 'S', 'S', 'S')] = 'b' assert d.longest_key == 4 d[('S', 'S')] = 'c' assert d.longest_key == 4 assert d[('S', 'S')] == 'c' del d[('S', 'S', 'S', 'S')] assert d.longest_key == 2 del d[('S',)] assert d.longest_key == 2 if self.DICT_SUPPORT_REVERSE_LOOKUP: assert d.reverse_lookup('c') == {('S', 'S')} else: assert d.reverse_lookup('c') == set() if self.DICT_SUPPORT_CASEREVERSE_LOOKUP: assert d.casereverse_lookup('c') == {'c'} else: assert d.casereverse_lookup('c') == set() d.clear() assert d.longest_key == 0 assert d.reverse_lookup('c') == set() assert d.casereverse_lookup('c') == set() d[('S', 'S')] = 'c' assert d.longest_key == 2 def test_casereverse_del(self): ''' Check deletion correctly updates `casereverse_lookup` data. ''' d = self.DICT_CLASS() d[('S-G',)] = 'something' d[('SPH-G',)] = 'something' if self.DICT_SUPPORT_CASEREVERSE_LOOKUP: assert d.casereverse_lookup('something') == {'something'} else: assert d.casereverse_lookup('something') == set() del d[('S-G',)] if self.DICT_SUPPORT_CASEREVERSE_LOOKUP: assert d.casereverse_lookup('something') == {'something'} else: assert d.casereverse_lookup('something') == set() del d[('SPH-G',)] assert d.casereverse_lookup('something') == set() @parametrize(( lambda: (dict(_TEST_DICTIONARY_UPDATE_DICT), False, True), lambda: (dict(_TEST_DICTIONARY_UPDATE_DICT), False, False), lambda: (list(_TEST_DICTIONARY_UPDATE_DICT.items()), False, True), lambda: (list(_TEST_DICTIONARY_UPDATE_DICT.items()), False, False), lambda: (list(_TEST_DICTIONARY_UPDATE_DICT.items()), True, True), lambda: (list(_TEST_DICTIONARY_UPDATE_DICT.items()), True, False), lambda: (_TEST_DICTIONARY_UPDATE_STENODICT, False, True), lambda: (_TEST_DICTIONARY_UPDATE_STENODICT, False, False), )) def test_update(self, update_from, use_iter, start_empty): ''' Check `update` does the right thing, including consuming iterators once. ''' d = self.DICT_CLASS() if not start_empty: d.update({ ('SPH*G',): 'not something', ('STHEUPBG',): 'something', ('EF', 'REU', 'TH*EUPBG'): 'everything', }) assert d[('STHEUPBG',)] == 'something' assert d[('EF', 'REU', 'TH*EUPBG')] == 'everything' if self.DICT_SUPPORT_REVERSE_LOOKUP: assert d.reverse_lookup('not something') == {('SPH*G',)} else: assert d.reverse_lookup('not something') == set() if self.DICT_SUPPORT_REVERSE_LOOKUP: assert d.casereverse_lookup('not something') == {'not something'} else: assert d.casereverse_lookup('not something') == set() assert d.longest_key == 3 if use_iter: update_from = iter(update_from) d.update(update_from) assert d[('S-G',)] == 'something' assert d[('SPH-G',)] == 'something' assert d[('SPH*G',)] == 'Something' assert d[('SPH', 'THEUPBG')] == 'something' if not start_empty: assert d[('STHEUPBG',)] == 'something' assert d[('EF', 'REU', 'TH*EUPBG')] == 'everything' assert d.reverse_lookup('not something') == set() if self.DICT_SUPPORT_REVERSE_LOOKUP: assert d.reverse_lookup('something') == {('STHEUPBG',), ('S-G',), ('SPH-G',), ('SPH', 'THEUPBG')} else: assert d.reverse_lookup('something') == set() if self.DICT_SUPPORT_CASEREVERSE_LOOKUP: assert d.casereverse_lookup('something') == {'something', 'Something'} else: assert d.casereverse_lookup('something') == set() assert d.longest_key == 3 else: if self.DICT_SUPPORT_REVERSE_LOOKUP: assert d.reverse_lookup('something') == {('S-G',), ('SPH-G',), ('SPH', 'THEUPBG')} else: assert d.reverse_lookup('something') == set() if self.DICT_SUPPORT_CASEREVERSE_LOOKUP: assert d.casereverse_lookup('something') == {'something', 'Something'} else: assert d.casereverse_lookup('something') == set() assert d.longest_key == 2 INVALID_CONTENTS = b"ceci n'est pas un dictionaire" def _test_save(self, tmp_path, entries, expected): ''' Test `save` implementation. ''' dict_entries = self.parse_entries(entries) with self.tmp_dict(tmp_path, self.INVALID_CONTENTS) as dict_path: st = dict_path.stat() old_timestamp = st.st_mtime - 1 os.utime(str(dict_path), (st.st_atime, old_timestamp)) # Create... d = self.DICT_CLASS.create(str(dict_path)) # ...must not change the target file... assert d.timestamp == 0 assert dict_path.read_bytes() == self.INVALID_CONTENTS # ...even on update... d.update(dict_entries) assert d.timestamp == 0 assert dict_path.read_bytes() == self.INVALID_CONTENTS # ...until save is called. d.save() assert d.timestamp > old_timestamp if expected is None: assert dict_path.read_bytes() != self.INVALID_CONTENTS else: assert dict_path.read_bytes() == expected d = self.DICT_CLASS.load(str(dict_path)) assert sorted(d.items()) == sorted(dict_entries.items()) def _wrap_method(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) wrapper.__signature__ = inspect.signature(method) return wrapper def dictionary_test(cls): """ Torture tests for dictionary implementations. Usage: ```python @dictionary_test class TestMyDictionaryClass: # Mandatory: implementation class. DICT_CLASS = MyDictionaryClass # Mandatory: extension. DICT_EXTENSION = 'json' # Mandatory: valid sample dictionary contents. DICT_SAMPLE = b'{}' # Optional: if `True`, will check the implementation class # is registered as a valid `plover.dictionary` entrypoint. DICT_REGISTERED = True # Optional: if `False`, `len`, `__iter__`, and `items` # are not supported, and must respectively return: # 0 and empty sequences. # Note: only supported for read-only implementations, # writable implementations must support all sequence # methods. DICT_SUPPORT_SEQUENCE_METHODS = False # Optional: if `False`, then `reverse_lookup` is not # supported, and must return an empty set. DICT_SUPPORT_REVERSE_LOOKUP = False # Optional: if `False`, then `casereverse_lookup` is not # supported, and must return an empty set. # Note: if supported, then `DICT_SUPPORT_REVERSE_LOOKUP` # must be too. DICT_SUPPORT_CASEREVERSE_LOOKUP = False # Optional: load tests. DICT_LOAD_TESTS = ( lambda: ( # Dictionary file contents. b''' ''', # Expected entries, in Python-dictionary like format. ''' "TEFT": 'test', 'TEFT/-G': "testing", ''' ), ) # Optional: save tests. # Note: only for writable implementations. DICT_SAVE_TESTS = ( lambda: ( # Initial entries, in Python-dictionary like format. ''' "TEFT": 'test', 'TEFT/-G': "testing", ''' # Expected saved dictionary contents, or `None` # to skip the byte-for-byte test of the resulting # file contents. b''' ''', ), ) # Optional: if implemented, will be called to format # the contents before saving to a dictionary file, # including for load and save tests. @staticmethod def make_dict(self, contents): return contents """ DICT_SUPPORT_SEQUENCE_METHODS = getattr(cls, 'DICT_SUPPORT_SEQUENCE_METHODS', True) DICT_SUPPORT_REVERSE_LOOKUP = getattr(cls, 'DICT_SUPPORT_REVERSE_LOOKUP', True) DICT_SUPPORT_CASEREVERSE_LOOKUP = getattr(cls, 'DICT_SUPPORT_CASEREVERSE_LOOKUP', DICT_SUPPORT_REVERSE_LOOKUP) assert DICT_SUPPORT_REVERSE_LOOKUP or not DICT_SUPPORT_CASEREVERSE_LOOKUP base_classes = [cls, _DictionaryTests] if cls.DICT_CLASS.readonly: base_classes.append(_ReadOnlyDictionaryTests) else: base_classes.append(_WritableDictionaryTests) class_dict = { 'DICT_SUPPORT_SEQUENCE_METHODS': DICT_SUPPORT_SEQUENCE_METHODS, 'DICT_SUPPORT_REVERSE_LOOKUP': DICT_SUPPORT_REVERSE_LOOKUP, 'DICT_SUPPORT_CASEREVERSE_LOOKUP': DICT_SUPPORT_CASEREVERSE_LOOKUP, } if getattr(cls, 'DICT_REGISTERED', False): class_dict['test_entrypoint'] = _wrap_method(_DictionaryTests._test_entrypoint) if hasattr(cls, 'DICT_LOAD_TESTS'): class_dict['test_load'] = parametrize(cls.DICT_LOAD_TESTS, arity=2)( _wrap_method(_DictionaryTests._test_load)) if hasattr(cls, 'DICT_SAVE_TESTS'): assert not cls.DICT_CLASS.readonly class_dict['test_save'] = parametrize(cls.DICT_SAVE_TESTS, arity=2)( _wrap_method(_WritableDictionaryTests._test_save)) return type(cls.__name__, tuple(base_classes), class_dict)
17,403
Python
.py
414
31.707729
114
0.575849
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,779
conf.py
openstenoproject_plover/doc/conf.py
# Configuration file for the Sphinx documentation builder. # -- Project information ----------------------------------------------------- project = "Plover" copyright = "Open Steno Project" author = copyright release = "4.0.0-rc2" version = release # -- General configuration --------------------------------------------------- extensions = [ "sphinx_plover", "myst_parser", "sphinx.ext.todo", ] myst_enable_extensions = ["colon_fence"] templates_path = ["_templates"] exclude_patterns = [] pygments_style = "manni" pygments_dark_style = "monokai" source_suffix = [".rst", ".md"] todo_include_todos = True # -- Options for HTML output ------------------------------------------------- html_theme = "furo" html_static_path = ["_static"] html_title = f"{project} {version}" html_favicon = "_static/favicon.ico" html_css_files = [ "custom.css", ] html_theme_options = { "navigation_with_keys": True, "light_css_variables": { "color-brand-primary": "#3d6961", "color-brand-content": "#3d6961", "color-sidebar-background": "#3d6961", "color-sidebar-brand-text": "white", "color-sidebar-brand-text--hover": "white", "color-sidebar-caption-text": "white", "color-sidebar-link-text": "white", "color-sidebar-link-text--top-level": "white", "color-sidebar-item-background--hover": "#71a89f", "color-sidebar-item-expander-background--hover": "#71a89f", "color-inline-code-background": "transparent", "font-stack--header": "'Patua One', -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji'", "font-stack--monospace": "'JetBrains Mono', SFMono-Regular, Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace", }, "dark_css_variables": { "color-link": "#68a69b", "color-link--hover": "#68a69b", }, "light_logo": "dolores.svg", "dark_logo": "dolores.svg", } from pygments.lexer import RegexLexer, bygroups from pygments import token as t from sphinx.highlighting import lexers class RTFLexer(RegexLexer): name = "rtf" tokens = { "root": [ (r"(\\[a-z*\\_~\{\}]+)(-?\d+)?", bygroups(t.Keyword, t.Number.Integer)), (r"{\\\*\\cxcomment\s+", t.Comment.Multiline, "comment"), ( r"({)(\\\*\\cxs)(\s+)([A-Z#0-9\-/#!,]+)(})", bygroups(t.Operator, t.Keyword, t.Text, t.String, t.Operator), ), (r"{", t.Operator), (r"}", t.Operator), (r".+?", t.Text), ], "comment": [ (r"{", t.Comment.Multiline, "#push"), (r"}", t.Comment.Multiline, "#pop"), (r".+", t.Comment.Multiline), ], } lexers["rtf"] = RTFLexer(startinline=True)
2,675
Python
.py
76
31.513158
156
0.605825
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,780
settings.py
openstenoproject_plover/osx/dmg_resources/settings.py
# -*- coding: utf-8 -*- import plistlib import os.path application = defines.get('app', './dist/Plover.app') appname = os.path.basename(application) def icon_from_app(app_path): plist_path = os.path.join(app_path, 'Contents', 'Info.plist') with open(plist_path, 'rb') as plist_file: plist = plistlib.load(plist_file) icon_name = plist['CFBundleIconFile'] icon_root, icon_ext = os.path.splitext(icon_name) if not icon_ext: icon_ext = '.icns' icon_name = icon_root + icon_ext return os.path.join(app_path, 'Contents', 'Resources', icon_name) format = defines.get('format', 'UDBZ') # Files to include files = [application] # Symlinks to create symlinks = {'Applications': '/Applications'} # Volume icon badge_icon = icon_from_app(application) # Where to put the icons icon_locations = { appname: (114, 244), 'Applications': (527, 236) } background = 'osx/dmg_resources/background.png' show_status_bar = False show_tab_view = False show_toolbar = False show_pathbar = False show_sidebar = False # Window position in ((x, y), (w, h)) format window_rect = ((100, 100), (640, 380)) default_view = 'icon-view' show_icon_preview = False include_icon_view_settings = 'auto' include_list_view_settings = 'auto' arrange_by = None grid_offset = (0, 0) grid_spacing = 50 scroll_position = (0, 0) label_pos = 'bottom' text_size = 16 icon_size = 86
1,406
Python
.py
46
28.130435
69
0.699108
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,781
pyinfo.py
openstenoproject_plover/linux/appimage/pyinfo.py
from distutils import sysconfig import sys print("; ".join("py%s=%r" % (k, v) for k, v in sorted({ 'exe' : sys.executable, 'prefix' : getattr(sys, "base_prefix", sys.prefix), 'version': sysconfig.get_python_version(), 'include': sysconfig.get_python_inc(prefix=''), 'ldlib' : sysconfig.get_config_var('LDLIBRARY'), 'py3lib' : sysconfig.get_config_var('PY3LIBRARY'), 'stdlib' : sysconfig.get_python_lib(standard_lib=1, prefix=''), 'purelib': sysconfig.get_python_lib(plat_specific=0, prefix=''), 'platlib': sysconfig.get_python_lib(plat_specific=1, prefix=''), }.items())))
614
Python
.py
13
43.384615
68
0.663333
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,782
attach.py
openstenoproject_plover/plover/meta/attach.py
from os.path import commonprefix from plover.formatting import ( Case, META_ATTACH_FLAG, META_CARRY_CAPITALIZATION, has_word_boundary, rightmost_word, ) from plover.orthography import add_suffix def meta_attach(ctx, meta): action = ctx.new_action() begin = meta.startswith(META_ATTACH_FLAG) end = meta.endswith(META_ATTACH_FLAG) if not (begin or end): # If not specified, attach at both ends. meta = META_ATTACH_FLAG + meta + META_ATTACH_FLAG begin = end = True if begin: meta = meta[len(META_ATTACH_FLAG):] action.prev_attach = True if end: meta = meta[:-len(META_ATTACH_FLAG)] action.next_attach = True action.word_is_finished = False last_word = ctx.last_action.word or '' if not meta: # We use an empty connection to indicate a "break" in the # application of orthography rules. This allows the # stenographer to tell Plover not to auto-correct a word. action.orthography = False elif ( last_word and not meta.isspace() and ctx.last_action.orthography and begin and (not end or has_word_boundary(meta)) ): new_word = add_suffix(last_word, meta) common_len = len(commonprefix([last_word, new_word])) replaced = last_word[common_len:] action.prev_replace = ctx.last_text(len(replaced)) assert replaced.lower() == action.prev_replace.lower() last_word = last_word[:common_len] meta = new_word[common_len:] action.text = meta if action.prev_attach: action.word = rightmost_word(last_word + meta) return action def meta_carry_capitalize(ctx, meta): # Meta format: ^~|content^ (attach flags are optional) action = ctx.new_action() if ctx.last_action.next_case == Case.CAP_FIRST_WORD: action.next_case = Case.CAP_FIRST_WORD begin = meta.startswith(META_ATTACH_FLAG) if begin: meta = meta[len(META_ATTACH_FLAG):] action.prev_attach = True meta = meta[len(META_CARRY_CAPITALIZATION):] end = meta.endswith(META_ATTACH_FLAG) if end: meta = meta[:-len(META_ATTACH_FLAG)] action.next_attach = True action.word_is_finished = False if meta or begin or end: action.text = meta return action
2,343
Python
.tac
65
29.446154
65
0.650396
openstenoproject/plover
2,318
281
179
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,783
meson_shebang_normalisation.py
GNOME_meld/meson_shebang_normalisation.py
#!/usr/bin/env python3 import pathlib import sys def main(): in_path = pathlib.Path(sys.argv[1]) out_path = pathlib.Path(sys.argv[2]) if not in_path.exists(): print(f"Couldn't find {in_path}") sys.exit(1) lines = in_path.read_text().splitlines(keepends=True) lines[0] = "".join(lines[0].split("env ")) out_path.write_text("".join(lines)) stat = in_path.stat() out_path.chmod(stat.st_mode) if __name__ == "__main__": main()
482
Python
.py
16
25.4375
57
0.618736
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,784
setup.py
GNOME_meld/setup.py
#!/usr/bin/env python3 import glob import pathlib from distutils.core import setup # Copy conf.py in place if necessary base_path = pathlib.Path(__file__).parent conf_path = base_path / 'meld' / 'conf.py' if not conf_path.exists(): import shutil shutil.copyfile(conf_path.with_suffix('.py.in'), conf_path) import meld.build_helpers # noqa:E402 isort:skip import meld.conf # noqa:E402 isort:skip setup( name=meld.conf.__package__, version=meld.conf.__version__, description='Visual diff and merge tool', author='Kai Willadsen', author_email='kai.willadsen@gmail.com', url='https://meld.app', license='GPLv2+', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: X11 Applications :: GTK', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Desktop Environment :: Gnome', 'Topic :: Software Development', 'Topic :: Software Development :: Version Control', ], keywords=['diff', 'merge'], packages=[ 'meld', 'meld.matchers', 'meld.ui', 'meld.vc', ], package_data={ 'meld': ['README', 'COPYING', 'NEWS'], 'meld.vc': ['README', 'COPYING'], }, scripts=['bin/meld'], data_files=[ ('share/man/man1', ['data/meld.1'] ), ('share/doc/meld-' + meld.conf.__version__, ['COPYING', 'NEWS'] ), ('share/meld/icons', glob.glob("data/icons/*.png") + glob.glob("data/icons/COPYING*") ), ('share/meld/styles', glob.glob("data/styles/*.xml") ), ('share/meld/ui', glob.glob("data/ui/*.ui") + glob.glob("data/ui/*.xml") ), ], cmdclass={ "build_i18n": meld.build_helpers.build_i18n, "build_help": meld.build_helpers.build_help, "build_icons": meld.build_helpers.build_icons, "build_data": meld.build_helpers.build_data, "build_py": meld.build_helpers.build_py, "install": meld.build_helpers.install, "install_data": meld.build_helpers.install_data, }, distclass=meld.build_helpers.MeldDistribution, )
2,417
Python
.py
73
26.410959
85
0.596409
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,785
setup_win32.py
GNOME_meld/setup_win32.py
#!/usr/bin/env python3 import glob import os.path import pathlib import platform import sys import sysconfig from cx_Freeze import Executable, setup def get_non_python_libs(): """Returns list of tuples containing extra dependencies required to run meld on current platform. Every pair corresponds to a single library file. First tuple item is path in local filesystem during build. Second tuple item correspond to path expected in meld installation relative to meld prefix. Note that for returned dynamic libraries and executables dependencies are expected to be resolved by caller, for example by cx_freeze. """ local_bin = os.path.join(sys.prefix, "bin") inst_root = [] # local paths of files "to put at freezed root" inst_lib = [] # local paths of files "to put at freezed 'lib' subdir" if 'mingw' in sysconfig.get_platform(): # dll imported by dll dependencies expected to be auto-resolved later inst_root = [os.path.join(local_bin, 'libgtksourceview-4-0.dll')] # required for communicating multiple instances inst_lib.append(os.path.join(local_bin, 'gdbus.exe')) # gspawn-helper is needed for Gtk.show_uri function if platform.architecture()[0] == '32bit': inst_lib.append(os.path.join(local_bin, 'gspawn-win32-helper.exe')) else: inst_lib.append(os.path.join(local_bin, 'gspawn-win64-helper.exe')) return [ (f, os.path.basename(f)) for f in inst_root ] + [ (f, os.path.join('lib', os.path.basename(f))) for f in inst_lib ] gtk_data_dirs = [ 'etc/fonts', 'etc/gtk-3.0', 'lib/gdk-pixbuf-2.0', 'lib/girepository-1.0', 'share/fontconfig', 'share/glib-2.0', 'share/gtksourceview-4', 'share/icons', ] gtk_data_files = [] for data_dir in gtk_data_dirs: local_data_dir = os.path.join(sys.prefix, data_dir) for local_data_subdir, dirs, files in os.walk(local_data_dir): data_subdir = os.path.relpath(local_data_subdir, local_data_dir) gtk_data_files.append(( os.path.join(data_dir, data_subdir), [os.path.join(local_data_subdir, file) for file in files], )) manually_added_libs = { # add libgdk_pixbuf-2.0-0.dll manually to forbid auto-pulling of gdiplus.dll "libgdk_pixbuf-2.0-0.dll": os.path.join(sys.prefix, 'bin'), # librsvg is needed for SVG loading in gdkpixbuf "librsvg-2-2.dll": os.path.join(sys.prefix, 'bin'), } for lib, possible_path in manually_added_libs.items(): local_lib = os.path.join(possible_path, lib) if os.path.isfile(local_lib): gtk_data_files.append((os.path.dirname(lib), [local_lib])) build_exe_options = { "includes": ["gi"], "excludes": ["tkinter"], "packages": ["gi", "weakref"], "include_files": get_non_python_libs(), "bin_excludes": list(manually_added_libs.keys()), "zip_exclude_packages": [], "zip_include_packages": ["*"], } # Create our registry key, and fill with install directory and exe registry_table = [ ('MeldKLM', 2, r'SOFTWARE\Meld', '*', None, 'TARGETDIR'), ('MeldInstallDir', 2, r'SOFTWARE\Meld', 'InstallDir', '[TARGETDIR]', 'TARGETDIR'), ('MeldExecutable', 2, r'SOFTWARE\Meld', 'Executable', '[TARGETDIR]Meld.exe', 'TARGETDIR'), ] # Provide the locator and app search to give MSI the existing install directory # for future upgrades reg_locator_table = [ ('MeldInstallDirLocate', 2, r'SOFTWARE\Meld', 'InstallDir', 0), ] app_search_table = [('TARGETDIR', 'MeldInstallDirLocate')] msi_data = { 'Registry': registry_table, 'RegLocator': reg_locator_table, 'AppSearch': app_search_table, } bdist_msi_options = { "upgrade_code": "{1d303789-b4e2-4d6e-9515-c301e155cd50}", "data": msi_data, "all_users": True, "add_to_path": True, "install_icon": "data/icons/org.gnome.meld.ico", } executable_options = { "script": "bin/meld", "icon": "data/icons/org.gnome.meld.ico", } console_executable_options = dict(executable_options) if 'mingw' in sysconfig.get_platform(): executable_options.update({ "base": "Win32GUI", # comment to build console version to see stderr "target_name": "Meld.exe", "shortcut_name": "Meld", "shortcut_dir": "ProgramMenuFolder", }) console_executable_options.update({ "target_name": "MeldConsole.exe", }) # Copy conf.py in place if necessary base_path = pathlib.Path(__file__).parent conf_path = base_path / 'meld' / 'conf.py' if not conf_path.exists(): import shutil shutil.copyfile(conf_path.with_suffix('.py.in'), conf_path) import meld.build_helpers # noqa: E402 import meld.conf # noqa: E402 setup( name="Meld", version=meld.conf.__version__, description='Visual diff and merge tool', maintainer='Kai Willadsen', url='https://meld.app', license='GPLv2+', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: X11 Applications :: GTK', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Programming Language :: Python', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Desktop Environment :: Gnome', 'Topic :: Software Development', 'Topic :: Software Development :: Version Control', ], keywords=['diff', 'merge'], options={ "build_exe": build_exe_options, "bdist_msi": bdist_msi_options, # cx_freeze + bdist_dumb fails on non-empty prefix "install": {"prefix": "."}, # freezed binary doesn't use source files, they are only for humans "install_lib": {"compile": False}, }, executables=[ Executable(**executable_options), Executable(**console_executable_options), ], packages=[ 'meld', 'meld.matchers', 'meld.ui', 'meld.vc', ], package_data={ 'meld': ['README', 'COPYING', 'NEWS'], 'meld.vc': ['README', 'COPYING'], }, scripts=['bin/meld'], data_files=[ ('share/man/man1', ['data/meld.1'] ), ('share/doc/meld-' + meld.conf.__version__, ['COPYING', 'NEWS'] ), ('share/meld/icons', glob.glob("data/icons/*.png") + glob.glob("data/icons/COPYING*") ), ('share/meld/styles', glob.glob("data/styles/*.xml") ), ('share/meld/ui', glob.glob("data/ui/*.ui") + glob.glob("data/ui/*.xml") ), ] + gtk_data_files, cmdclass={ "build_i18n": meld.build_helpers.build_i18n, "build_help": meld.build_helpers.build_help, "build_icons": meld.build_helpers.build_icons, "build_data": meld.build_helpers.build_data, } )
6,916
Python
.py
189
30.798942
94
0.636866
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,786
conftest.py
GNOME_meld/test/conftest.py
import importlib.machinery import importlib.util import sys from unittest import mock import pytest @pytest.fixture(autouse=True) def default_icon_theme(): # Our tests need to run on a system with no default display, so all # our display-specific get_default() stuff will break. from gi.repository import Gtk with mock.patch( 'gi.repository.Gtk.IconTheme.get_default', mock.Mock(spec=Gtk.IconTheme.get_default)): yield @pytest.fixture(autouse=True) def template_resources(): import gi # noqa: F401 with mock.patch( 'gi._gtktemplate.validate_resource_path', mock.Mock(return_value=True)): yield def import_meld_conf(): loader = importlib.machinery.SourceFileLoader( 'meld.conf', './meld/conf.py.in') spec = importlib.util.spec_from_loader(loader.name, loader) mod = importlib.util.module_from_spec(spec) loader.exec_module(mod) import meld meld.conf = mod sys.modules['meld.conf'] = mod import_meld_conf()
1,042
Python
.py
31
28.225806
71
0.700701
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,787
test_iohelpers.py
GNOME_meld/test/test_iohelpers.py
from unittest import mock import pytest from gi.repository import Gio from meld.iohelpers import ( find_shared_parent_path, format_home_relative_path, format_parent_relative_path, ) @pytest.mark.parametrize( 'paths, expected_parent', [ # No paths, None return ([], None), # One path always returns its own parent (['/foo/a/b/c'], '/foo/a/b'), # Two paths (['/foo/a', '/foo/b'], '/foo'), # Three paths (['/foo/a', '/foo/b', '/foo/c'], '/foo'), # First path is deeper (['/foo/a/asd/asd', '/foo/b'], '/foo'), # Second path is deeper (['/foo/a/', '/foo/b/asd/asd'], '/foo'), # Common parent is the root (['/foo/a/', '/bar/b/'], '/'), # One path, one missing path (['/foo/a', None], None), # Two paths, one missing path (['/foo/a', None, '/foo/c'], None), ], ) def test_find_shared_parent_path(paths, expected_parent): files = [Gio.File.new_for_path(p) if p else None for p in paths] print([f.get_path() if f else repr(f) for f in files]) parent = find_shared_parent_path(files) if parent is None: assert expected_parent is None else: print(f'Parent: {parent.get_path()}; expected {expected_parent}') if expected_parent is None: assert parent is None else: assert parent.equal(Gio.File.new_for_path(expected_parent)) @pytest.mark.parametrize( "path, expected_format", [ ("/home/hey/foo", "~/foo"), ("/home/hmph/foo", "/home/hmph/foo"), ] ) def test_format_home_relative_path(path, expected_format): with mock.patch( "meld.iohelpers.GLib.get_home_dir", return_value="/home/hey/", ): gfile = Gio.File.new_for_path(path) assert format_home_relative_path(gfile) == expected_format @pytest.mark.parametrize( 'parent, child, expected_label', [ # Child is a direct child of parent ( '/home/hey/', '/home/hey/foo.txt', '…/hey/foo.txt', ), # Child is a direct child of parent and parent is the root ( '/', '/foo.txt', '/foo.txt', ), # Child is a 2-depth child of parent ( '/home/hey/', '/home/hey/project/foo.txt', '…/project/foo.txt', ), # Child is a 3-depth child of parent ( '/home/hey/', '/home/hey/project/package/foo.txt', '…/project/package/foo.txt', ), # Child is a more-than-3-depth child of parent, with long # immediate parent ( '/home/hey/', '/home/hey/project/package/subpackage/foo.txt', '…/project/…/subpackage/foo.txt', ), # Child is a more-than-3-depth child of parent, with short # immediate parent ( '/home/hey/', '/home/hey/project/package/src/foo.txt', '…/project/package/src/foo.txt', ), ], ) def test_format_parent_relative_path( parent: str, child: str, expected_label: str, ): parent_gfile = Gio.File.new_for_path(parent) child_gfile = Gio.File.new_for_path(child) label = format_parent_relative_path(parent_gfile, child_gfile) assert label == expected_label def test_format_parent_relative_path_no_parent(): parent_gfile = Gio.File.new_for_path('/') child_gfile = Gio.File.new_for_path('/') with pytest.raises(ValueError, match='has no parent'): format_parent_relative_path(parent_gfile, child_gfile)
3,688
Python
.py
114
24.552632
73
0.561883
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,788
test_filters.py
GNOME_meld/test/test_filters.py
import pytest @pytest.mark.parametrize("patterns,filename,expected_match", [ ([r'*.csv'], 'foo.csv', True), ([r'*.cvs'], 'foo.csv', False), ([r'*.csv *.xml'], 'foo.csv', True), ([r'*.csv *.xml'], 'foo.xml', True), ([r'*.csv', r'*.xml'], 'foo.csv', True), ([r'*.csv', r'*.xml'], 'foo.xml', True), ([r'*.csv', r'*.xml'], 'dumbtest', False), ([r'thing*csv'], 'thingcsv', True), ([r'thing*csv'], 'thingwhatevercsv', True), ([r'thing*csv'], 'csvthing', False), ]) def test_file_filters(patterns, filename, expected_match): from meld.filters import FilterEntry filters = [ FilterEntry.new_from_gsetting(("name", True, p), FilterEntry.SHELL) for p in patterns ] # All of the dirdiff logic is "does this match any filter", so # that's what we test here, even if it looks a bit weird. match = any(f.filter.match(filename) for f in filters) assert match == expected_match @pytest.mark.parametrize("pattern", [ r'*.foo*', # Trailing wildcard r'\xfoo', # Invalid escape ]) def test_bad_regex_compilation(pattern): from meld.filters import FilterEntry f = FilterEntry.new_from_gsetting( ("name", True, pattern), FilterEntry.REGEX) assert f.filter is None
1,264
Python
.py
32
34.75
75
0.625
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,789
test_accelerators.py
GNOME_meld/test/test_accelerators.py
from gi.repository import Gtk from meld.accelerators import VIEW_ACCELERATORS def test_accelerator_parse(): for accel_strings in VIEW_ACCELERATORS.values(): if isinstance(accel_strings, str): accel_strings = [accel_strings] for accel_string in accel_strings: key, mods = Gtk.accelerator_parse(accel_string) assert key def test_accelerator_duplication(): accels = set() allowed_duplicates = { # Allowed because they're different copy actions across views Gtk.accelerator_parse("<Alt>Left"), Gtk.accelerator_parse("<Alt>Right"), # Allowed because they activate different popovers across views Gtk.accelerator_parse("F8"), # Allowed because they're different panel show/hide across views Gtk.accelerator_parse("F9"), } for accel_strings in VIEW_ACCELERATORS.values(): if isinstance(accel_strings, str): accel_strings = [accel_strings] for accel_string in accel_strings: accel = Gtk.accelerator_parse(accel_string) if accel not in allowed_duplicates: assert ( accel not in accels ), f"Duplicate accelerator {accel_string}" accels.add(accel)
1,291
Python
.py
30
33.566667
72
0.649081
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,790
test_misc.py
GNOME_meld/test/test_misc.py
from unittest import mock import pytest from meld.misc import all_same, calc_syncpoint, merge_intervals @pytest.mark.parametrize("intervals, expected", [ # Dominated by a single range ([(1, 5), (5, 9), (10, 11), (0, 20)], [(0, 20)]), # No overlap ([(1, 5), (6, 9), (10, 11)], [(1, 5), (6, 9), (10, 11)]), # Two overlap points between ranges ([(1, 5), (5, 9), (10, 12), (11, 20)], [(1, 9), (10, 20)]), # Two overlap points between ranges, out of order ([(5, 9), (1, 5), (11, 20), (10, 12)], [(1, 9), (10, 20)]), # Two equal ranges ([(1, 5), (7, 8), (1, 5)], [(1, 5), (7, 8)]), # Three ranges overlap ([(1, 5), (4, 10), (9, 15)], [(1, 15)]) ]) def test_merge_intervals(intervals, expected): merged = merge_intervals(intervals) assert merged == expected @pytest.mark.parametrize("value, page_size, lower, upper, expected", [ # Boring top (0, 100, 0, 1000, 0.0), # Above the top! (0, 100, 100, 1000, 0.0), # Normal top scaling (25, 100, 0, 1000, 0.25), (50, 100, 0, 1000, 0.5), # Scaling with a lower offset (25, 100, 25, 1000, 0.0), (50, 100, 25, 1000, 0.25), # Somewhere in the middle (500, 100, 0, 1000, 0.5), # Normal bottom scaling (850, 100, 0, 1000, 0.5), (875, 100, 0, 1000, 0.75), # Boring bottom (900, 100, 0, 1000, 1.0), # Below the bottom! (1100, 100, 0, 1000, 1.0), ]) def test_calc_syncpoint(value, page_size, lower, upper, expected): import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk adjustment = Gtk.Adjustment() adjustment.configure(value, lower, upper, 1, 1, page_size) syncpoint = calc_syncpoint(adjustment) assert syncpoint == expected @pytest.mark.parametrize("lst, expected", [ (None, True), ([], True), ([0], True), ([1], True), ([0, 0], True), ([0, 1], False), ([1, 0], False), ([1, 1], True), ([0, 0, 0], True), ([0, 0, 1], False), ([0, 1, 0], False), ([0, 1, 1], False), ([1, 0, 0], False), ([1, 0, 1], False), ([1, 1, 0], False), ([1, 1, 1], True) ]) def test_all_same(lst, expected): assert all_same(lst) == expected @pytest.mark.parametrize("os_name, paths, expected", [ ('posix', ['/tmp/foo1', '/tmp/foo2'], ['foo1', 'foo2']), ('posix', ['/tmp/foo1', '/tmp/foo2', '/tmp/foo3'], ['foo1', 'foo2', 'foo3']), ('posix', ['/tmp/bar/foo1', '/tmp/woo/foo2'], ['foo1', 'foo2']), ('posix', ['/tmp/bar/foo1', '/tmp/woo/foo1'], ['[bar] foo1', '[woo] foo1']), ('posix', ['/tmp/bar/foo1', '/tmp/woo/foo1', '/tmp/ree/foo1'], ['[bar] foo1', '[woo] foo1', '[ree] foo1']), ('posix', ['/tmp/bar/deep/deep', '/tmp/bar/shallow'], ['deep', 'shallow']), ('posix', ['/tmp/bar/deep/deep/foo1', '/tmp/bar/shallow/foo1'], ['[deep] foo1', '[shallow] foo1']), # This case doesn't actually make much sense, so it's not that bad # that our output is... somewhat unclear. ('posix', ['/tmp/bar/subdir/subsub', '/tmp/bar/'], ['subsub', 'bar']), ('nt', ['C:\\Users\\hmm\\bar', 'C:\\Users\\hmm\\foo'], ['bar', 'foo']), ('nt', ['C:\\Users\\bar\\hmm', 'C:\\Users\\foo\\hmm'], ['[bar] hmm', '[foo] hmm']), # Check that paths with no commonality are handled ('posix', ['nothing in', 'common'], ['nothing in', 'common']), ('posix', ['<unnamed>', '/tmp/real/path'], ['<unnamed>', '/tmp/real/path']), ]) def test_shorten_names(os_name, paths, expected): from meld.misc import shorten_names with mock.patch('os.name', os_name): assert shorten_names(*paths) == expected
3,590
Python
.py
90
35.377778
111
0.553612
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,791
test_filediff.py
GNOME_meld/test/test_filediff.py
from unittest import mock import pytest from gi.repository import Gtk @pytest.mark.parametrize("text, ignored_ranges, expected_text", [ # 0123456789012345678901234567890123456789012345678901234567890123456789 # Matching without groups ( "# asdasdasdasdsad", [(0, 17)], "", ), # Matching with single group ( "asdasdasdasdsab", [(1, 14)], "ab", ), # Matching with multiple groups ( "xasdyasdz", [(1, 4), (5, 8)], "xyz", ), # Matching with multiple partially overlapping filters ( "qaqxqbyqzq", [(2, 6), (7, 8)], "qayzq", ), # Matching with multiple fully overlapping filters ( "qaqxqybqzq", [(2, 8)], "qazq", ), # Matching with and without groups, with single dominated match ( "# asdasdasdasdsab", [(0, 17)], "", ), # Matching with and without groups, with partially overlapping filters ( "/*a*/ub", [(0, 6)], "b", ), # Non-matching with groups ( "xasdyasdx", [], "xasdyasdx", ), # Multiple lines with non-overlapping filters ( "#ab\na2b", [(0, 3), (5, 6)], "\nab", ), # CVS keyword ( "$Author: John Doe $", [(8, 18)], "$Author:$", ), ]) def test_filter_text(text, ignored_ranges, expected_text): from meld.filediff import FileDiff from meld.filters import FilterEntry filter_patterns = [ '#.*', r'/\*.*\*/', 'a(.*)b', 'x(.*)y(.*)z', r'\$\w+:([^\n$]+)\$' ] filters = [ FilterEntry.new_from_gsetting(("name", True, f), FilterEntry.REGEX) for f in filter_patterns ] filediff = mock.MagicMock() filediff.text_filters = filters filter_text = FileDiff._filter_text buf = Gtk.TextBuffer() buf.create_tag("inline") buf.create_tag("dimmed") buf.set_text(text) start, end = buf.get_bounds() text = filter_text( filediff, buf.get_text(start, end, False), buf, start, end) # Find ignored ranges tag = buf.get_tag_table().lookup("dimmed") toggles = [] it = start.copy() if it.toggles_tag(tag): toggles.append(it.get_offset()) while it.forward_to_tag_toggle(tag): toggles.append(it.get_offset()) toggles = list(zip(toggles[::2], toggles[1::2])) print("Text:", text) print("Toggles:", toggles) assert toggles == ignored_ranges assert text == expected_text
2,604
Python
.py
103
18.84466
79
0.554038
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,792
test_chunk_actions.py
GNOME_meld/test/test_chunk_actions.py
from unittest import mock import pytest from gi.repository import GtkSource @pytest.mark.parametrize("text, newline, expected_text", [ # For the following tests, newlines and text match # Basic CRLF tests ("ree\r\neee", GtkSource.NewlineType.CR_LF, 'ree'), ("ree\r\neee\r\n", GtkSource.NewlineType.CR_LF, 'ree\r\neee'), # Basic CR tests ("ree\neee", GtkSource.NewlineType.CR, 'ree'), ("ree\neee\n", GtkSource.NewlineType.CR, 'ree\neee'), # Basic LF tests ("ree\reee", GtkSource.NewlineType.LF, 'ree'), ("ree\reee\r", GtkSource.NewlineType.LF, 'ree\reee'), # Mismatched newline and text ("ree\r\neee", GtkSource.NewlineType.CR, 'ree'), # Mismatched newline types within text ("ree\r\neee\n", GtkSource.NewlineType.CR_LF, 'ree\r\neee'), ("ree\r\neee\nqqq", GtkSource.NewlineType.CR_LF, 'ree\r\neee'), ("ree\r\neee\nqqq\r\n", GtkSource.NewlineType.CR_LF, 'ree\r\neee\nqqq'), ]) def test_delete_last_line_crlf(text, newline, expected_text): import meld.meldbuffer from meld.filediff import FileDiff from meld.matchers.myers import DiffChunk filediff = mock.Mock(FileDiff) with mock.patch('meld.meldbuffer.bind_settings', mock.DEFAULT): meldbuffer = meld.meldbuffer.MeldBuffer() meldbuffer.set_text(text) def make_last_line_chunk(buf): end = buf.get_line_count() last = end - 1 return DiffChunk('delete', last, end, last, end) start, end = meldbuffer.get_bounds() buf_text = meldbuffer.get_text(start, end, False) print(repr(buf_text)) with mock.patch.object( meldbuffer.data.sourcefile, 'get_newline_type', return_value=newline): filediff.textbuffer = [meldbuffer] filediff.textview = [mock.Mock()] FileDiff.delete_chunk(filediff, 0, make_last_line_chunk(meldbuffer)) start, end = meldbuffer.get_bounds() buf_text = meldbuffer.get_text(start, end, False) print(repr(buf_text)) assert buf_text == expected_text
2,026
Python
.py
46
38.26087
76
0.680894
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,793
test_gutterrendererchunk.py
GNOME_meld/test/test_gutterrendererchunk.py
from unittest import mock import pytest from meld.const import ActionMode from meld.matchers.myers import DiffChunk def make_chunk(chunk_type): return DiffChunk(chunk_type, 0, 1, 0, 1) @pytest.mark.parametrize("mode, editable, chunk, expected_action", [ # Replace mode with replace chunks (ActionMode.Replace, (True, True), make_chunk('replace'), ActionMode.Replace), (ActionMode.Replace, (True, False), make_chunk('replace'), ActionMode.Delete), (ActionMode.Replace, (False, True), make_chunk('replace'), ActionMode.Replace), (ActionMode.Replace, (False, False), make_chunk('replace'), None), # Replace mode with delete chunks (ActionMode.Replace, (True, True), make_chunk('delete'), ActionMode.Replace), (ActionMode.Replace, (True, False), make_chunk('delete'), ActionMode.Delete), (ActionMode.Replace, (False, True), make_chunk('delete'), ActionMode.Replace), (ActionMode.Replace, (False, False), make_chunk('delete'), None), # Delete mode makes a slightly weird choice to remove non-delete # actions while in delete mode; insert mode makes the opposite # choice # # Delete mode with replace chunks (ActionMode.Delete, (True, True), make_chunk('replace'), ActionMode.Delete), (ActionMode.Delete, (True, False), make_chunk('replace'), ActionMode.Delete), (ActionMode.Delete, (False, True), make_chunk('replace'), None), (ActionMode.Delete, (False, False), make_chunk('replace'), None), # Delete mode with delete chunks (ActionMode.Delete, (True, True), make_chunk('delete'), ActionMode.Delete), (ActionMode.Delete, (True, False), make_chunk('delete'), ActionMode.Delete), (ActionMode.Delete, (False, True), make_chunk('delete'), None), (ActionMode.Delete, (False, False), make_chunk('delete'), None), # Insert mode with replace chunks (ActionMode.Insert, (True, True), make_chunk('replace'), ActionMode.Insert), (ActionMode.Insert, (True, False), make_chunk('replace'), ActionMode.Delete), (ActionMode.Insert, (False, True), make_chunk('replace'), ActionMode.Insert), (ActionMode.Insert, (False, False), make_chunk('replace'), None), # Insert mode with delete chunks (ActionMode.Insert, (True, True), make_chunk('delete'), ActionMode.Replace), (ActionMode.Insert, (True, False), make_chunk('delete'), ActionMode.Delete), (ActionMode.Insert, (False, True), make_chunk('delete'), ActionMode.Replace), (ActionMode.Insert, (False, False), make_chunk('delete'), None), # We should never have insert chunks here (ActionMode.Replace, (True, True), make_chunk('insert'), None), (ActionMode.Replace, (True, False), make_chunk('insert'), None), (ActionMode.Replace, (False, True), make_chunk('insert'), None), (ActionMode.Replace, (False, False), make_chunk('insert'), None), # TODO: Add tests for conflict chunks ]) def test_classify_change_actions(mode, editable, chunk, expected_action): # These tests are disabled due to a segfault on the CI machines. return from meld.actiongutter import ActionGutter source_editable, target_editable = editable with mock.patch.object(ActionGutter, 'icon_direction'): renderer = ActionGutter() renderer._source_view = mock.Mock() renderer._source_view.get_editable.return_value = source_editable renderer._target_view = mock.Mock() renderer._target_view.get_editable.return_value = target_editable renderer.action_mode = mode action = renderer._classify_change_actions(chunk) assert action == expected_action
3,600
Python
.py
62
52.854839
83
0.705248
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,794
__init__.py
GNOME_meld/test/__init__.py
TEST_REQUIRES = { "GLib": "2.0", "Gtk": "3.0", "GtkSource": "4", } def enforce_requires(): import gi for namespace, version in TEST_REQUIRES.items(): gi.require_version(namespace, version) enforce_requires()
242
Python
.py
10
19.8
52
0.637168
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,795
test_buffer_lines.py
GNOME_meld/test/test_buffer_lines.py
from unittest import mock import pytest from meld.meldbuffer import BufferLines, MeldBuffer text = ("""0 1 2 3 4 5 6 7 8 9 10""") @pytest.fixture(scope='module', autouse=True) def mock_bind_settings(): with mock.patch('meld.meldbuffer.bind_settings', mock.DEFAULT): yield @pytest.fixture def buffer_setup(): buf = MeldBuffer() buf.set_text(text) buffer_lines = BufferLines(buf) yield buf, buffer_lines @pytest.mark.parametrize("line_start, line_end, expected_text", [ (0, 1, ["0"],), (0, 2, ["0", "1"],), # zero-sized slice (9, 9, [],), (9, 10, ["9"],), (9, 11, ["9", "10"],), # Past the end of the buffer (9, 12, ["9", "10"],), # Waaaay past the end of the buffer (9, 9999, ["9", "10"],), # And sidling towards past-the-end start indices (10, 12, ["10"],), (11, 12, [],), ]) def test_meld_buffer_slicing( line_start, line_end, expected_text, buffer_setup): buffer, buffer_lines = buffer_setup assert buffer_lines[line_start:line_end] == expected_text def test_meld_buffer_index_out_of_range(buffer_setup): buffer, buffer_lines = buffer_setup with pytest.raises(IndexError): buffer_lines[11] def test_meld_buffer_cached_contents(buffer_setup): buffer, buffer_lines = buffer_setup text_lines = text.splitlines() assert len(buffer_lines.lines) == len(buffer_lines) == len(text_lines) # Check that without access, we have no cached contents assert buffer_lines.lines == [None] * len(text_lines) # Access the lines so that they're cached buffer_lines[:] # Note that this only happens to be true for our simple text; if # it were true in general, we wouldn't need the complexities of the # BufferLines class. assert buffer_lines.lines == text_lines def test_meld_buffer_insert_text(buffer_setup): buffer, buffer_lines = buffer_setup # Access the lines so that they're cached buffer_lines[:] assert buffer_lines.lines[4:8] == ["4", "5", "6", "7"] # Delete from the start of line 5 to the start of line 7, # invalidating line 7 but leaving its contents intact. buffer.insert( buffer.get_iter_at_line(5), "hey\nthings", ) assert buffer_lines.lines[4:8] == ["4", None, None, "6"] assert buffer_lines[5:7] == ["hey", "things5"] assert buffer_lines.lines[4:8] == ["4", "hey", "things5", "6"] def test_meld_buffer_delete_range(buffer_setup): buffer, buffer_lines = buffer_setup # Access the lines so that they're cached buffer_lines[:] assert buffer_lines.lines[4:8] == ["4", "5", "6", "7"] # Delete from the start of line 5 to the start of line 7, # invalidating line 7 but leaving its contents intact. buffer.delete( buffer.get_iter_at_line(5), buffer.get_iter_at_line(7), ) assert buffer_lines.lines[4:7] == ["4", None, "8"] assert buffer_lines[5] == "7" assert buffer_lines.lines[4:7] == ["4", "7", "8"] def test_meld_buffer_cache_debug(caplog, buffer_setup): buffer, buffer_lines = buffer_setup buffer_lines = BufferLines(buffer, cache_debug=True) # Invalidate our line cache... buffer_lines.lines.append("invalid") # ...and check that insertion/deletion logs an error buffer.insert( buffer.get_iter_at_line(5), "hey", ) assert len(caplog.records) == 1 assert caplog.records[0].msg.startswith("Cache line count does not match") caplog.clear() buffer.delete( buffer.get_iter_at_line(5), buffer.get_iter_at_line(7), ) assert len(caplog.records) == 1 assert caplog.records[0].msg.startswith("Cache line count does not match")
3,720
Python
.py
106
30.283019
78
0.655008
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,796
test_matchers.py
GNOME_meld/test/test_matchers.py
import unittest from meld.matchers import myers class MatchersTests(unittest.TestCase): def test_basic_matcher(self): a = list('abcbdefgabcdefg') b = list('gfabcdefcd') r = [(0, 2, 3), (4, 5, 3), (10, 8, 2), (15, 10, 0)] matcher = myers.MyersSequenceMatcher(None, a, b) blocks = matcher.get_matching_blocks() self.assertEqual(blocks, r) def test_postprocessing_cleanup(self): a = list('abcfabgcd') b = list('afabcgabgcabcd') r = [(0, 2, 3), (4, 6, 3), (7, 12, 2), (9, 14, 0)] matcher = myers.MyersSequenceMatcher(None, a, b) blocks = matcher.get_matching_blocks() self.assertEqual(blocks, r) def test_inline_matcher(self): a = 'red, blue, yellow, white' b = 'black green, hue, white' r = [(17, 16, 7), (24, 23, 0)] matcher = myers.InlineMyersSequenceMatcher(None, a, b) blocks = matcher.get_matching_blocks() self.assertEqual(blocks, r) def test_sync_point_matcher0(self): a = list('012a3456c789') b = list('0a3412b5678') r = [(0, 0, 1), (3, 1, 3), (6, 7, 2), (9, 9, 2), (12, 11, 0)] matcher = myers.SyncPointMyersSequenceMatcher(None, a, b) blocks = matcher.get_matching_blocks() self.assertEqual(blocks, r) def test_sync_point_matcher2(self): a = list('012a3456c789') b = list('0a3412b5678') r = [(0, 0, 1), (1, 4, 2), (6, 7, 2), (9, 9, 2), (12, 11, 0)] matcher = myers.SyncPointMyersSequenceMatcher(None, a, b, [(3, 6)]) blocks = matcher.get_matching_blocks() self.assertEqual(blocks, r) def test_sync_point_matcher3(self): a = list('012a3456c789') b = list('02a341b5678') r = [(0, 0, 1), (2, 1, 1), (3, 2, 3), (9, 9, 2), (12, 11, 0)] matcher = myers.SyncPointMyersSequenceMatcher( None, a, b, [(3, 2), (8, 6)]) blocks = matcher.get_matching_blocks() self.assertEqual(blocks, r)
2,016
Python
.py
46
35.565217
75
0.570408
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,797
conftest.py
GNOME_meld/test/dirdiff/conftest.py
import pytest CHUNK_SIZE = 4096 * 10 diff_definition = { "a": { "a.txt": lambda: b"", "c": {"c.txt": lambda: b""}, "d": {"d.txt": lambda: (b"d" * CHUNK_SIZE) + b"d"}, "e": { "f": {}, "g": {"g.txt": lambda: b"g"}, "h": {"h.txt": lambda: b"h"}, "e.txt": lambda: b"", }, "crlf.txt": lambda: b"foo\r\nbar\r\n", "crlftrailing.txt": lambda: b"foo\r\nbar\r\n\r\n", }, "b": { "b.txt": lambda: b"", "c": {"c.txt": lambda: b""}, "d": { "d.txt": lambda: (b"d" * CHUNK_SIZE) + b"d", "d.1.txt": lambda: (b"D" * CHUNK_SIZE) + b"D", "d.2.txt": lambda: (b"d" * CHUNK_SIZE) + b"D", }, "e": { "f": {"f.txt": lambda: b""}, "g": {"g.txt": lambda: b""}, "h": {"h.txt": lambda: b"h"}, "e.txt": lambda: b"", }, "lf.txt": lambda: b"foo\nbar\n", "lftrailing.txt": lambda: b"foo\nbar\n\n", }, } def populate(definition, path): for k, v in definition.items(): file_path = path / k if isinstance(v, dict): file_path.mkdir() populate(v, file_path) else: file_path.write_bytes(v()) @pytest.fixture def create_sample_dir(tmp_path): populate(diff_definition, tmp_path) yield tmp_path
1,398
Python
.py
46
21.869565
59
0.437593
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,798
test_remove_blank_lines.py
GNOME_meld/test/dirdiff/test_remove_blank_lines.py
import pytest @pytest.mark.parametrize('txt, expected', [ # blank to be equal blank (b'', b''), # one line with spaces (b' ', b' '), # two lines empty (b'\n', b''), (b'\n ', b' '), (b' \n', b' '), (b' \n ', b' \n '), # tree lines empty (b'\n\n', b''), (b'\n\n ', b' '), (b'\n \n', b' '), (b'\n \n ', b' \n '), (b' \n \n ', b' \n \n '), # one line with space and content (b' content', b' content'), # empty line between content (b'content\n\ncontent', b'content\ncontent'), # multiple leading and trailing newlines (b'\n\n\ncontent\n\n\ncontent\n\n\n', b'content\ncontent'), ]) def test_remove_blank_lines(txt, expected): from meld.dirdiff import remove_blank_lines result = remove_blank_lines(txt) assert result == expected
823
Python
.py
28
24.857143
63
0.549242
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
18,799
test_files_same.py
GNOME_meld/test/dirdiff/test_files_same.py
from enum import Enum from os import path import pytest DiffResult = Enum( "DiffResult", "Same SameFiltered DodgySame DodgyDifferent Different FileError" ) def abspath(*args): d = path.dirname(__file__) return list(path.join(d, arg) for arg in args) cmp_args = { "shallow-comparison": False, "time-resolution": 10000000000, "ignore_blank_lines": True, "apply-text-filters": True, } no_ignore_args = dict(cmp_args) no_ignore_args["ignore_blank_lines"] = False no_ignore_args["apply-text-filters"] = False dodgy_args = dict(cmp_args) dodgy_args["shallow-comparison"] = True @pytest.mark.parametrize( "files, regexes, comparison_args, expected", [ # empty file list ((), [], cmp_args, DiffResult.Same), # dirs are same (("a", "b"), [], cmp_args, DiffResult.Same), # dir and file are different (("a", "b/b.txt"), [], cmp_args, DiffResult.Different), # shallow equal (time + size) (("a/d/d.txt", "b/d/d.1.txt"), [], dodgy_args, DiffResult.DodgySame), # empty files (fastest equal, won't read files) (("a/c/c.txt", "b/c/c.txt"), [], cmp_args, DiffResult.Same), # 4.1kb vs 4.1kb file (slow equal, read both until end) (("a/d/d.txt", "b/d/d.txt"), [], cmp_args, DiffResult.Same), # 4.1kb vs 4.1kb file (fast different, first chunk diff) (("a/d/d.txt", "b/d/d.1.txt"), [], cmp_args, DiffResult.Different), # 4.1kb vs 4.1kb file (slow different, read both until end) (("a/d/d.txt", "b/d/d.2.txt"), [], cmp_args, DiffResult.Different), # empty vs 1b file (fast different, first chunk diff) (("a/e/g/g.txt", "b/e/g/g.txt"), [], cmp_args, DiffResult.Different), # CRLF vs CRLF with trailing, ignoring blank lines (("a/crlf.txt", "a/crlftrailing.txt"), [], cmp_args, DiffResult.SameFiltered), # CRLF vs CRLF with trailing, not ignoring blank lines ( ("a/crlf.txt", "a/crlftrailing.txt"), [], no_ignore_args, DiffResult.Different, ), # LF vs LF with trailing, ignoring blank lines (("b/lf.txt", "b/lftrailing.txt"), [], cmp_args, DiffResult.SameFiltered), # LF vs LF with trailing, not ignoring blank lines (("b/lf.txt", "b/lftrailing.txt"), [], no_ignore_args, DiffResult.Different), # CRLF vs LF, ignoring blank lines (("a/crlf.txt", "b/lf.txt"), [], cmp_args, DiffResult.SameFiltered), # CRLF vs LF, not ignoring blank lines (("a/crlf.txt", "b/lf.txt"), [], no_ignore_args, DiffResult.Different), # CRLF with trailing vs LF with trailing, ignoring blank lines ( ("a/crlftrailing.txt", "b/lftrailing.txt"), [], cmp_args, DiffResult.SameFiltered, ), # CRLF with trailing vs LF with trailing, not ignoring blank lines ( ("a/crlftrailing.txt", "b/lftrailing.txt"), [], no_ignore_args, DiffResult.Different, ), ], ) def test_files_same(create_sample_dir, files, regexes, comparison_args, expected): from meld.dirdiff import _files_same files_path = [create_sample_dir / f for f in files] result = _files_same(files_path, regexes, comparison_args) actual = DiffResult(result + 1) assert actual == expected
3,399
Python
.py
80
35.1
86
0.603083
GNOME/meld
1,057
264
0
GPL-2.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)