def begin_transition(self, active): self._active = active if active: Timer.stop(self) self._keyboard.begin_transition(Transition.ACTIVATE) else: if not config.xid_mode: Timer.start(self, config.window.inactive_transparency_delay)
def __init__(self): WindowRectTracker.__init__(self) self._screen_orientation = None self._save_position_timer = Timer() # init detection of screen "rotation" screen = self.get_screen() screen.connect('size-changed', self.on_screen_size_changed)
def __init__(self): self._window_rect = None self._origin = None self._client_offset = (0, 0) self._screen_orientation = None self._save_position_timer = Timer() # init detection of screen "rotation" screen = self.get_screen() screen.connect('size-changed', self.on_screen_size_changed)
def __init__(self, keyboard, notify_done_callback): self._layout = None self._notify_done_callback = notify_done_callback self._drag_selected = False # grazed by the pointer? KeyboardPopup.__init__(self) LayoutView.__init__(self, keyboard) TouchInput.__init__(self) self.connect("draw", self._on_draw) self.connect("destroy", self._on_destroy_event) self._close_timer = Timer() self.start_close_timer()
def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None
def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Counter for key popup animation """ self._popup_display=0 #In """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None """ Time between key activation flashes (in sec) """ self.ACTIVATION_FLASH_INTERVAL = config.scanner.activation_flash_interval #0.1 #In """ Number of key activation flashes """ self.ACTIVATION_FLASH_COUNT = config.scanner.activation_flash_count #2 #In
def on_screen_size_changed(self, screen): """ detect screen rotation (tablets)""" # Give the screen time to settle, the window manager # may block the move to previously invalid positions and # when docked, the slide animation may be drowned out by all # the action in other processes. Timer(1.5, self.on_screen_size_changed_delayed, screen)
def __init__(self): self._window_rect = None self._origin = None self._screen_orientation = None self._save_position_timer = Timer() # init detection of screen "rotation" screen = self.get_screen() screen.connect('size-changed', self._on_screen_size_changed)
def __init__(self): InputEventSource.__init__(self) self._input_sequences = {} self._touch_events_enabled = self.is_touch_enabled() self._multi_touch_enabled = config.keyboard.touch_input == \ TouchInputEnum.MULTI self._gestures_enabled = self._touch_events_enabled self._last_event_was_touch = False self._last_sequence_time = 0 self._gesture = NO_GESTURE self._gesture_begin_point = (0, 0) self._gesture_begin_time = 0 self._gesture_detected = False self._gesture_cancelled = False self._num_tap_sequences = 0 self._gesture_timer = Timer()
def on_input_sequence_end(self, sequence): key = sequence.active_key if key: keyboard = self.keyboard keyboard.key_up(key, self, sequence) if key and \ not self._drag_selected: Timer(config.UNPRESS_DELAY, self.close_window) else: self.close_window()
def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Counter for key popup animation """ self._popup_display = 0 #In """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None """ Time between key activation flashes (in sec) """ self.ACTIVATION_FLASH_INTERVAL = config.scanner.activation_flash_interval #0.1 #In """ Number of key activation flashes """ self.ACTIVATION_FLASH_COUNT = config.scanner.activation_flash_count #2 #In
def __init__(self, keyboard_widget, icp): self._last_ignore_configure_time = None self._last_configures = [] self._was_visible = False Gtk.Window.__init__(self, urgency_hint=False, width_request=self.MINIMUM_SIZE, height_request=self.MINIMUM_SIZE) KbdWindowBase.__init__(self, keyboard_widget, icp) WindowRectTracker.__init__(self) GObject.signal_new("quit-onboard", KbdWindow, GObject.SIGNAL_RUN_LAST, GObject.TYPE_BOOLEAN, ()) self._auto_position_poll_timer = Timer() self.restore_window_rect(startup=True) self.connect("map", self._on_map_event) self.connect("unmap", self._on_unmap_event) self.connect("delete-event", self._on_delete_event) self.connect("configure-event", self._on_configure_event) # Connect_after seems broken in Quantal, the callback is never called. #self.connect_after("configure-event", self._on_configure_event_after) self._osk_util.connect_root_property_notify( ["_NET_WORKAREA", "_NET_CURRENT_DESKTOP"], self._on_root_property_notify) once = CallOnce(100).enqueue # call at most once per 100ms rect_changed = lambda x: once(self._on_config_rect_changed) config.window.position_notify_add(rect_changed) config.window.size_notify_add(rect_changed) dock_size_changed = lambda x: once(self._on_config_dock_size_changed) config.window.dock_size_notify_add(dock_size_changed)
def __init__(self, wp): self._wp = wp self._accessible = None self._can_insert_text = False self._text_domains = TextDomains() self._text_domain = self._text_domains.get_nop_domain() self._changes = TextChanges() self._entering_text = False self._text_changed = False self._context = "" self._line = "" self._line_cursor = 0 self._span_at_cursor = TextSpan() self._begin_of_text = False # context starts at begin of text? self._begin_of_text_offset = None # offset of text begin self._last_context = None self._last_line = None self._update_context_timer = Timer()
def __init__(self, keyboard_widget, icp): self._last_ignore_configure_time = None self._last_configures = [] self._was_visible = False Gtk.Window.__init__(self, urgency_hint = False, width_request=self.MINIMUM_SIZE, height_request=self.MINIMUM_SIZE) KbdWindowBase.__init__(self, keyboard_widget, icp) WindowRectTracker.__init__(self) GObject.signal_new("quit-onboard", KbdWindow, GObject.SIGNAL_RUN_LAST, GObject.TYPE_BOOLEAN, ()) self._auto_position_poll_timer = Timer() self.restore_window_rect(startup = True) self.connect("map", self._on_map_event) self.connect("unmap", self._on_unmap_event) self.connect("delete-event", self._on_delete_event) self.connect("configure-event", self._on_configure_event) # Connect_after seems broken in Quantal, the callback is never called. #self.connect_after("configure-event", self._on_configure_event_after) self._osk_util.connect_root_property_notify(["_NET_WORKAREA", "_NET_CURRENT_DESKTOP"], self._on_root_property_notify) once = CallOnce(100).enqueue # call at most once per 100ms rect_changed = lambda x: once(self._on_config_rect_changed) config.window.position_notify_add(rect_changed) config.window.size_notify_add(rect_changed) dock_size_changed = lambda x: once(self._on_config_dock_size_changed) config.window.dock_size_notify_add(dock_size_changed)
class AtspiTextContext(TextContext): """ Keep track of the current text context with AT-SPI """ _state_tracker = AtspiStateTracker() def __init__(self, wp): self._wp = wp self._accessible = None self._can_insert_text = False self._text_domains = TextDomains() self._text_domain = self._text_domains.get_nop_domain() self._changes = TextChanges() self._entering_text = False self._text_changed = False self._context = "" self._line = "" self._line_cursor = 0 self._span_at_cursor = TextSpan() self._begin_of_text = False # context starts at begin of text? self._begin_of_text_offset = None # offset of text begin self._last_context = None self._last_line = None self._update_context_timer = Timer() def cleanup(self): self._register_atspi_listeners(False) def enable(self, enable): self._register_atspi_listeners(enable) def get_text_domain(self): return self._text_domain def get_context(self): """ Returns the predictions context, i.e. some range of text before the cursor position. """ if self._accessible is None: return "" # Don't update suggestions in scrolling terminals if self._entering_text or \ not self._text_changed or \ self.can_suggest_before_typing(): return self._context return "" def get_bot_context(self): """ Returns the predictions context with begin of text marker (at text begin). """ context = "" if self._accessible: context = self.get_context() # prepend domain specific begin-of-text marker if self._begin_of_text: marker = self.get_text_begin_marker() if marker: context = marker + " " + context return context def get_line(self): return self._line \ if self._accessible else "" def get_line_cursor_pos(self): return self._line_cursor \ if self._accessible else 0 def get_line_past_cursor(self): return self._line[self._line_cursor:] \ if self._accessible else "" def get_span_at_cursor(self): return self._span_at_cursor \ if self._accessible else None def get_cursor(self): return self._span_at_cursor.begin() \ if self._accessible else 0 def get_text_begin_marker(self): domain = self.get_text_domain() if domain: return domain.get_text_begin_marker() return "" def can_record_insertion(self, accessible, pos, length): domain = self.get_text_domain() if domain: return domain.can_record_insertion(accessible, pos, length) return True def can_suggest_before_typing(self): domain = self.get_text_domain() if domain: return domain.can_suggest_before_typing() return True def get_begin_of_text_offset(self): return self._begin_of_text_offset \ if self._accessible else None def get_changes(self): return self._changes def has_changes(self): """ Are there any changes to learn? """ return not self._changes.is_empty() def clear_changes(self): self._changes.clear() def can_insert_text(self): """ Can delete or insert text into the accessible? """ #return False # support for inserting is spotty: not in firefox, terminal return bool(self._accessible) and self._can_insert_text def delete_text(self, offset, length=1): """ Delete directly, without going through faking key presses. """ self._accessible.delete_text(offset, offset + length) def delete_text_before_cursor(self, length=1): """ Delete directly, without going through faking key presses. """ offset = self._accessible.get_caret_offset() self.delete_text(offset - length, length) def insert_text(self, offset, text): """ Insert directly, without going through faking key presses. """ self._accessible.insert_text(offset, text, -1) def insert_text_at_cursor(self, text): """ Insert directly, without going through faking key presses. Fails for terminal and firefox, unfortunately. """ offset = self._accessible.get_caret_offset() self.insert_text(offset, text) def _register_atspi_listeners(self, register=True): st = self._state_tracker if register: st.connect("text-entry-activated", self._on_text_entry_activated) st.connect("text-changed", self._on_text_changed) st.connect("text-caret-moved", self._on_text_caret_moved) #st.connect("key-pressed", self._on_atspi_key_pressed) else: st.disconnect("text-entry-activated", self._on_text_entry_activated) st.disconnect("text-changed", self._on_text_changed) st.disconnect("text-caret-moved", self._on_text_caret_moved) #st.disconnect("key-pressed", self._on_atspi_key_pressed) def get_accessible_capabilities(accessible, **kwargs): can_insert_text = False attributes = kwargs.get("attributes", {}) interfaces = kwargs.get("interfaces", []) if accessible: # Can insert text via Atspi? # Advantages: - faster, no individual key presses # - full trouble-free insertion of all unicode characters if "EditableText" in interfaces: # Support for atspi text insertion is spotty. # Firefox, LibreOffice Writer, gnome-terminal don't support it, # even if they claim to implement the EditableText interface. # Allow direct text insertion by gtk widgets if "toolkit" in attributes and attributes["toolkit"] == "gtk": can_insert_text = True return can_insert_text def _on_text_entry_activated(self, accessible): # old text_domain still valid here self._wp.on_text_entry_deactivated() #print("_on_text_entry_activated", accessible) # keep track of the active accessible asynchronously self._accessible = accessible self._entering_text = False self._text_changed = False # select text domain matching this accessible state = self._state_tracker.get_state() \ if self._accessible else {} self._text_domain = self._text_domains.find_match(**state) self._text_domain.init_domain() # determine capabilities of this accessible self._can_insert_text = self.get_accessible_capabilities(**state) # log accessible info if _logger.isEnabledFor(logging.DEBUG): log = _logger.debug log("-" * 70) log("Accessible focused: ") if self._accessible: state = self._state_tracker.get_state() for key, value in sorted(state.items()): msg = str(key) + "=" if key == "state-set": msg += repr(AtspiStateType.to_strings(value)) else: msg += str(value) log(msg) log("text_domain: {}".format(self._text_domain)) log("can_insert_text: {}".format(self._can_insert_text)) log("") else: log("None") log("") self._update_context() self._wp.on_text_entry_activated() def _on_text_changed(self, event): insertion_span = self._record_text_change(event.pos, event.length, event.insert) # synchrounously notify of text insertion if insertion_span: try: cursor_offset = self._accessible.get_caret_offset() except: # gi._glib.GError pass else: self._wp.on_text_inserted(insertion_span, cursor_offset) self._update_context() def _on_text_caret_moved(self, event): self._update_context() def _on_atspi_key_pressed(self, event): """ disabled, Francesco didn't receive any AT-SPI key-strokes. """ keycode = event.hw_code # uh oh, only keycodes... # hopefully "c" doesn't move around a lot. modifiers = event.modifiers #self._handle_key_press(keycode, modifiers) def on_onboard_typing(self, key, mod_mask): if key.is_text_changing(): keycode = 0 if key.is_return(): keycode = KeyCode.KP_Enter else: label = key.get_label() if label == "C" or label == "c": keycode = KeyCode.C self._handle_key_press(keycode, mod_mask) def _handle_key_press(self, keycode, modifiers): if self._accessible: domain = self.get_text_domain() if domain: self._entering_text, end_of_editing = \ domain.handle_key_press(keycode, modifiers) if end_of_editing == True: self._wp.commit_changes() elif end_of_editing == False: self._wp.discard_changes() def _record_text_change(self, pos, length, insert): accessible = self._accessible insertion_span = None char_count = None if accessible: try: char_count = accessible.get_character_count() except: # gi._glib.GError: The application no longer exists # when closing a tab in gnome-terminal. char_count = None if not char_count is None: # record the change spans_to_update = [] if insert: #print("insert", pos, length) if self._entering_text and \ self.can_record_insertion(accessible, pos, length): if self._wp.is_typing() or length < 30: # Remember all of the insertion, might have been # a pressed snippet or wordlist button. include_length = -1 else: # Remember only the first few characters. # Large inserts can be paste, reload or scroll # operations. Only learn the first word of these. include_length = 2 # simple span for current insertion begin = max(pos - 100, 0) end = min(pos + length + 100, char_count) text = Atspi.Text.get_text(accessible, begin, end) insertion_span = TextSpan(pos, length, text, begin) else: # Remember nothing, just update existing spans. include_length = None spans_to_update = self._changes.insert(pos, length, include_length) else: #print("delete", pos, length) spans_to_update = self._changes.delete(pos, length, self._entering_text) # update text of the modified spans for span in spans_to_update: # Get some more text around the span to hopefully # include whole words at beginning and end. begin = max(span.begin() - 100, 0) end = min(span.end() + 100, char_count) span.text = Atspi.Text.get_text(accessible, begin, end) span.text_pos = begin #print(self._changes) self._text_changed = True return insertion_span def _update_context(self): self._update_context_timer.start(0.01, self.on_text_context_changed) def on_text_context_changed(self): result = self._text_domain.read_context(self._accessible) if not result is None: (self._context, self._line, self._line_cursor, self._span_at_cursor, self._begin_of_text, self._begin_of_text_offset) = result context = self.get_bot_context( ) # make sure to include bot-markers if self._last_context != context or \ self._last_line != self._line: self._last_context = context self._last_line = self._line self._wp.on_text_context_changed() return False
def start(self, key): self._key = key Timer.start(self, 0.08)
class WindowRectTracker: """ Keeps track of the window rectangle when moving/resizing. Gtk only updates the position and size asynchrounously on configure events and hidden windows return invalid values. Auto-show et al need valid values from get_position and get_size at all times. """ def __init__(self): self._window_rect = None self._origin = None self._screen_orientation = None self._save_position_timer = Timer() # init detection of screen "rotation" screen = self.get_screen() screen.connect('size-changed', self._on_screen_size_changed) def cleanup(self): self._save_position_timer.finish() def move(self, x, y): """ Overload Gtk.Window.move to reliably keep track of the window position. """ Gtk.Window.move(self, x, y) def resize(self, w, h): """ Overload Gtk.Window.size to reliably keep track of the window size. """ Gtk.Window.resize(self, w, h) def move_resize(self, x, y, w, h): win = self.get_window() if win: win.move_resize(x, y, w, h) def get_position(self): if self._window_rect is None: return Gtk.Window.get_position(self) else: return self._window_rect.get_position() def get_size(self): if self._window_rect is None: return Gtk.Window.get_size(self) else: return self._window_rect.get_size() def get_origin(self): if self._origin is None: return self.get_window().get_origin() else: return self._origin def get_rect(self): return self._window_rect def is_visible(self): """ This is overloaded in KbdWindow """ return Gtk.Window.get_visible(self) def _on_screen_size_changed(self, screen): """ detect screen rotation (tablets)""" # Give the screen time to settle, the window manager # may block the move to previously invalid positions. Timer(0.3, self.restore_window_rect) def get_screen_orientation(self): """ Current orientation of the screen (tablet rotation). Only the aspect ratio is taken into account at this time. This appears to cover more cases than loocking at monitor rotation, in particular with multi-monitor screens. """ screen = self.get_screen() if screen.get_width() >= screen.get_height(): return Orientation.LANDSCAPE else: return Orientation.PORTRAIT def update_window_rect(self): """ Call this on configure event, the only time when get_position, get_size, etc. can be trusted. """ visible = self.is_visible() if visible: self._window_rect = Rect.from_position_size(Gtk.Window.get_position(self), Gtk.Window.get_size(self)) self._origin = self.get_window().get_origin() self._screen_orientation = self.get_screen_orientation() def restore_window_rect(self, startup = False): """ Restore window size and position. """ # Run pending save operations now, so they don't # interfere with the window rect after it was restored. self._save_position_timer.finish() orientation = self.get_screen_orientation() rect = self.read_window_rect(orientation) self._screen_orientation = orientation self._window_rect = rect _logger.debug("restore_window_rect {rect}, {orientation}" \ .format(rect = rect, orientation = orientation)) # Give the derived class a chance to modify the rect, # for example to correct the position for auto-show. rect = self.on_restore_window_rect(rect) # move/resize the window if startup: # gnome-shell doesn't take kindly to an initial move_resize(). # The window ends up at (0, 0) on startup and goes back there # repeatedly when hiding and unhiding. self.set_default_size(rect.w, rect.h) self.move(rect.x, rect.y) else: self.move_resize(rect.x, rect.y, rect.w, rect.h) def on_restore_window_rect(self, rect): return rect def save_window_rect(self, orientation = None, rect = None): """ Save window size and position. """ if orientation is None: orientation = self._screen_orientation if rect is None: rect = self._window_rect # Give the derived class a chance to modify the rect, # for example to override it for auto-show. rect = self.on_save_window_rect(rect) self.write_window_rect(orientation, rect) _logger.debug("save_window_rect {rect}, {orientation}" \ .format(rect = rect, orientation = orientation)) def on_save_window_rect(self, rect): return rect def read_window_rect(self, orientation, rect): """ Read orientation dependent rect. Overload this in derived classes. """ raise NotImplementedError() def write_window_rect(self, orientation, rect): """ Write orientation dependent rect. Overload this in derived classes. """ raise NotImplementedError() def start_save_position_timer(self): """ Trigger saving position and size to gsettings Delay this a few seconds to avoid excessive disk writes. Remember the current rect and rotation as the screen may have been rotated when the saving happens. """ self._save_position_timer.start(5, self.save_window_rect, self.get_screen_orientation(), self.get_rect()) def stop_save_position_timer(self): self._save_position_timer.stop()
class IconPalette(Gtk.Window, WindowRectTracker, WindowManipulator): """ Class that creates a movable and resizable floating window without decorations. The window shows the icon of onboard scaled to fit to the window and a resize grip that honors the desktop theme in use. Onboard offers an option to the user to make the window appear whenever the user hides the onscreen keyboard. The user can then click on the window to hide it and make the onscreen keyboard reappear. """ __gsignals__ = {str("activated"): (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, ())} """ Minimum size of the IconPalette """ MINIMUM_SIZE = 20 _layout_view = None def __init__(self): self._visible = False self._force_to_top = False self._last_pos = None self._dwell_progress = DwellProgress() self._dwell_begin_timer = None self._dwell_timer = None self._no_more_dwelling = False Gtk.Window.__init__( self, type_hint=self._get_window_type_hint(), skip_taskbar_hint=True, skip_pager_hint=True, has_resize_grip=False, urgency_hint=False, decorated=False, accept_focus=False, opacity=0.75, width_request=self.MINIMUM_SIZE, height_request=self.MINIMUM_SIZE, ) WindowRectTracker.__init__(self) WindowManipulator.__init__(self) self.set_keep_above(True) # use transparency if available visual = Gdk.Screen.get_default().get_rgba_visual() if visual: self.set_visual(visual) # set up event handling self.add_events( Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.POINTER_MOTION_MASK ) self.connect("button-press-event", self._on_button_press_event) self.connect("motion-notify-event", self._on_motion_notify_event) self.connect("button-release-event", self._on_button_release_event) self.connect("draw", self._on_draw) self.connect("configure-event", self._on_configure_event) self.connect("realize", self._on_realize_event) self.connect("unrealize", self._on_unrealize_event) self.connect("enter-notify-event", self._on_mouse_enter) self.connect("leave-notify-event", self._on_mouse_leave) # default coordinates of the iconpalette on the screen self.set_min_window_size(self.MINIMUM_SIZE, self.MINIMUM_SIZE) # self.set_default_size(1, 1) # no flashing on left screen edge in unity self.restore_window_rect() # Realize the window. Test changes to this in all supported # environments. It's all too easy to have the icp not show up reliably. self.update_window_options() self.hide() once = CallOnce(100).enqueue # call at most once per 100ms rect_changed = lambda x: once(self._on_config_rect_changed) config.icp.position_notify_add(rect_changed) config.icp.size_notify_add(rect_changed) config.icp.resize_handles_notify_add(lambda x: self.update_resize_handles()) self.update_sticky_state() self.update_resize_handles() def cleanup(self): WindowRectTracker.cleanup(self) def set_layout_view(self, view): self._layout_view = view self.queue_draw() def get_color_scheme(self): if self._layout_view: return self._layout_view.get_color_scheme() return None def _on_configure_event(self, widget, event): self.update_window_rect() def on_drag_initiated(self): self.stop_save_position_timer() self._stop_dwelling() def on_drag_done(self): self.update_window_rect() self.start_save_position_timer() self._no_more_dwelling = True def _on_realize_event(self, user_data): """ Gdk window created """ set_unity_property(self) if config.is_force_to_top(): self.get_window().set_override_redirect(True) self.restore_window_rect(True) def _on_unrealize_event(self, user_data): """ Gdk window destroyed """ self.set_type_hint(self._get_window_type_hint()) def _get_window_type_hint(self): if config.is_force_to_top(): return Gdk.WindowTypeHint.NORMAL else: return Gdk.WindowTypeHint.UTILITY def update_window_options(self, startup=False): if not config.xid_mode: # not when embedding # (re-)create the gdk window? force_to_top = config.is_force_to_top() if self._force_to_top != force_to_top: self._force_to_top = force_to_top visible = self._visible # visible before? if self.get_realized(): # not starting up? self.hide() self.unrealize() self.realize() if visible: self.show() def update_sticky_state(self): if not config.xid_mode: if config.get_sticky_state(): self.stick() else: self.unstick() def update_resize_handles(self): """ Tell WindowManipulator about the active resize handles """ self.set_drag_handles(config.icp.resize_handles) def get_drag_threshold(self): """ Overload for WindowManipulator """ return config.get_drag_threshold() def _on_button_press_event(self, widget, event): """ Save the pointer position. """ if event.button == 1 and event.window == self.get_window(): self.enable_drag_protection(True) sequence = InputSequence() sequence.init_from_button_event(event) self.handle_press(sequence, move_on_background=True) if self.is_moving(): self.reset_drag_protection() # force threshold return False def _on_motion_notify_event(self, widget, event): """ Move the window if the pointer has moved more than the DND threshold. """ sequence = InputSequence() sequence.init_from_motion_event(event) self.handle_motion(sequence, fallback=True) self.set_drag_cursor_at((event.x, event.y)) # start dwelling if nothing else is going on point = (event.x, event.y) hit = self.hit_test_move_resize(point) if hit is None: if ( not self.is_drag_initiated() and not self._is_dwelling() and not self._no_more_dwelling and not config.is_hover_click_active() and not config.lockdown.disable_dwell_activation ): self._start_dwelling() else: self._stop_dwelling() # allow resizing in peace return False def _on_button_release_event(self, widget, event): """ Save the window geometry, hide the IconPalette and emit the "activated" signal. """ result = False if event.button == 1 and event.window == self.get_window() and not self.is_drag_active(): self.emit("activated") result = True self.stop_drag() self.set_drag_cursor_at((event.x, event.y)) return result def _on_mouse_enter(self, widget, event): pass def _on_mouse_leave(self, widget, event): self._stop_dwelling() self._no_more_dwelling = False def _on_draw(self, widget, cr): """ Draw the onboard icon. """ if not Gtk.cairo_should_draw_window(cr, self.get_window()): return False rect = Rect(0.0, 0.0, float(self.get_allocated_width()), float(self.get_allocated_height())) color_scheme = self.get_color_scheme() # clear background cr.save() cr.set_operator(cairo.OPERATOR_CLEAR) cr.paint() cr.restore() # draw background color background_rgba = list(color_scheme.get_icon_rgba("background")) if Gdk.Screen.get_default().is_composited(): background_rgba[3] *= 0.75 cr.set_source_rgba(*background_rgba) corner_radius = min(rect.w, rect.h) * 0.1 roundrect_arc(cr, rect, corner_radius) cr.fill() # decoration frame line_rect = rect.deflate(2) cr.set_line_width(2) roundrect_arc(cr, line_rect, corner_radius) cr.stroke() else: cr.set_source_rgba(*background_rgba) cr.paint() # draw themed icon self._draw_themed_icon(cr, rect, color_scheme) # draw dwell progress rgba = [0.8, 0.0, 0.0, 0.5] bg_rgba = [0.1, 0.1, 0.1, 0.5] if color_scheme: key = RectKey("icon0") # take dwell color from the first icon "key" rgba = color_scheme.get_key_rgba(key, "dwell-progress") rgba[3] = min(0.75, rgba[3]) # more transparency key = RectKey("icon1") bg_rgba = color_scheme.get_key_rgba(key, "fill") bg_rgba[3] = min(0.75, rgba[3]) # more transparency dwell_rect = rect.grow(0.5) self._dwell_progress.draw(cr, dwell_rect, rgba, bg_rgba) return True def _draw_themed_icon(self, cr, icon_rect, color_scheme): """ draw themed icon """ keys = [RectKey("icon" + str(i)) for i in range(4)] # Default colors for the case when none of the icon keys # are defined in the color scheme. background_rgba = [1.0, 1.0, 1.0, 1.0] fill_rgbas = [[0.9, 0.7, 0.0, 0.75], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.54, 1.0, 1.0]] stroke_rgba = [0.0, 0.0, 0.0, 1.0] label_rgba = [0.0, 0.0, 0.0, 1.0] themed = False if color_scheme: if any(color_scheme.is_key_in_scheme(key) for key in keys): themed = True # four rounded rectangles rects = Rect(0.0, 0.0, 100.0, 100.0).deflate(5).subdivide(2, 2, 6) cr.save() cr.scale(icon_rect.w / 100.0, icon_rect.h / 100.0) cr.translate(icon_rect.x, icon_rect.y) cr.select_font_face("sans-serif") cr.set_line_width(2) for i, key in enumerate(keys): rect = rects[i] if themed: fill_rgba = color_scheme.get_key_rgba(key, "fill") stroke_rgba = color_scheme.get_key_rgba(key, "stroke") label_rgba = color_scheme.get_key_rgba(key, "label") else: fill_rgba = fill_rgbas[i] roundrect_arc(cr, rect, 5) cr.set_source_rgba(*fill_rgba) cr.fill_preserve() cr.set_source_rgba(*stroke_rgba) cr.stroke() if i == 0 or i == 3: if i == 0: letter = "O" else: letter = "B" cr.set_font_size(25) x_bearing, y_bearing, _width, _height, x_advance, y_advance = cr.text_extents(letter) r = rect.align_rect(Rect(0, 0, _width, _height), 0.3, 0.33) cr.move_to(r.x - x_bearing, r.y - y_bearing) cr.set_source_rgba(*label_rgba) cr.show_text(letter) cr.new_path() cr.restore() def show(self): """ Override Gtk.Widget.hide() to save the window geometry. """ Gtk.Window.show(self) self.move_resize(*self.get_rect()) # sync with WindowRectTracker self._visible = True def hide(self): """ Override Gtk.Widget.hide() to save the window geometry. """ Gtk.Window.hide(self) self._visible = False def _on_config_rect_changed(self): """ Gsettings position or size changed """ orientation = self.get_screen_orientation() rect = self.read_window_rect(orientation) if self.get_rect() != rect: self.restore_window_rect() def read_window_rect(self, orientation): """ Read orientation dependent rect. Overload for WindowRectTracker. """ if orientation == Orientation.LANDSCAPE: co = config.icp.landscape else: co = config.icp.portrait rect = Rect(co.x, co.y, co.width, co.height) return rect def write_window_rect(self, orientation, rect): """ Write orientation dependent rect. Overload for WindowRectTracker. """ # There are separate rects for normal and rotated screen (tablets). if orientation == Orientation.LANDSCAPE: co = config.icp.landscape else: co = config.icp.portrait co.settings.delay() co.x, co.y, co.width, co.height = rect co.settings.apply() def _is_dwelling(self): return bool(self._dwell_begin_timer) and ( self._dwell_begin_timer.is_running() or self._dwell_progress.is_dwelling() ) def _start_dwelling(self): self._stop_dwelling() self._dwell_begin_timer = Timer(1.5, self._on_dwell_begin_timer) self._no_more_dwelling = True def _stop_dwelling(self): if self._dwell_begin_timer: self._dwell_begin_timer.stop() if self._dwell_timer: self._dwell_timer.stop() self._dwell_progress.stop_dwelling() self.queue_draw() def _on_dwell_begin_timer(self): self._dwell_progress.start_dwelling() self._dwell_timer = Timer(0.025, self._on_dwell_timer) return False def _on_dwell_timer(self): self._dwell_progress.opacity, done = Fade.sin_fade(self._dwell_progress.dwell_start_time, 0.3, 0, 1.0) self.queue_draw() if self._dwell_progress.is_done(): if not self.is_drag_active(): self.emit("activated") self.stop_drag() return False return True
class AtspiTextContext(TextContext): """ Keep track of the current text context with AT-SPI """ _state_tracker = AtspiStateTracker() def __init__(self, wp): self._wp = wp self._accessible = None self._can_insert_text = False self._text_domains = TextDomains() self._text_domain = self._text_domains.get_nop_domain() self._changes = TextChanges() self._entering_text = False self._text_changed = False self._context = "" self._line = "" self._line_cursor = 0 self._span_at_cursor = TextSpan() self._begin_of_text = False # context starts at begin of text? self._begin_of_text_offset = None # offset of text begin self._last_context = None self._last_line = None self._update_context_timer = Timer() def cleanup(self): self._register_atspi_listeners(False) def enable(self, enable): self._register_atspi_listeners(enable) def get_text_domain(self): return self._text_domain def get_context(self): """ Returns the predictions context, i.e. some range of text before the cursor position. """ if self._accessible is None: return "" # Don't update suggestions in scrolling terminals if self._entering_text or \ not self._text_changed or \ self.can_suggest_before_typing(): return self._context return "" def get_bot_context(self): """ Returns the predictions context with begin of text marker (at text begin). """ context = "" if self._accessible: context = self.get_context() # prepend domain specific begin-of-text marker if self._begin_of_text: marker = self.get_text_begin_marker() if marker: context = marker + " " + context return context def get_line(self): return self._line \ if self._accessible else "" def get_line_cursor_pos(self): return self._line_cursor \ if self._accessible else 0 def get_line_past_cursor(self): return self._line[self._line_cursor:] \ if self._accessible else "" def get_span_at_cursor(self): return self._span_at_cursor \ if self._accessible else None def get_cursor(self): return self._span_at_cursor.begin() \ if self._accessible else 0 def get_text_begin_marker(self): domain = self.get_text_domain() if domain: return domain.get_text_begin_marker() return "" def can_record_insertion(self, accessible, pos, length): domain = self.get_text_domain() if domain: return domain.can_record_insertion(accessible, pos, length) return True def can_suggest_before_typing(self): domain = self.get_text_domain() if domain: return domain.can_suggest_before_typing() return True def get_begin_of_text_offset(self): return self._begin_of_text_offset \ if self._accessible else None def get_changes(self): return self._changes def has_changes(self): """ Are there any changes to learn? """ return not self._changes.is_empty() def clear_changes(self): self._changes.clear() def can_insert_text(self): """ Can delete or insert text into the accessible? """ #return False # support for inserting is spotty: not in firefox, terminal return bool(self._accessible) and self._can_insert_text def delete_text(self, offset, length = 1): """ Delete directly, without going through faking key presses. """ self._accessible.delete_text(offset, offset + length) def delete_text_before_cursor(self, length = 1): """ Delete directly, without going through faking key presses. """ offset = self._accessible.get_caret_offset() self.delete_text(offset - length, length) def insert_text(self, offset, text): """ Insert directly, without going through faking key presses. """ self._accessible.insert_text(offset, text, -1) def insert_text_at_cursor(self, text): """ Insert directly, without going through faking key presses. Fails for terminal and firefox, unfortunately. """ offset = self._accessible.get_caret_offset() self.insert_text(offset, text) def _register_atspi_listeners(self, register = True): st = self._state_tracker if register: st.connect("text-entry-activated", self._on_text_entry_activated) st.connect("text-changed", self._on_text_changed) st.connect("text-caret-moved", self._on_text_caret_moved) #st.connect("key-pressed", self._on_atspi_key_pressed) else: st.disconnect("text-entry-activated", self._on_text_entry_activated) st.disconnect("text-changed", self._on_text_changed) st.disconnect("text-caret-moved", self._on_text_caret_moved) #st.disconnect("key-pressed", self._on_atspi_key_pressed) def get_accessible_capabilities(accessible, **kwargs): can_insert_text = False attributes = kwargs.get("attributes", {}) interfaces = kwargs.get("interfaces", []) if accessible: # Can insert text via Atspi? # Advantages: - faster, no individual key presses # - full trouble-free insertion of all unicode characters if "EditableText" in interfaces: # Support for atspi text insertion is spotty. # Firefox, LibreOffice Writer, gnome-terminal don't support it, # even if they claim to implement the EditableText interface. # Allow direct text insertion by gtk widgets if "toolkit" in attributes and attributes["toolkit"] == "gtk": can_insert_text = True return can_insert_text def _on_text_entry_activated(self, accessible): # old text_domain still valid here self._wp.on_text_entry_deactivated() #print("_on_text_entry_activated", accessible) # keep track of the active accessible asynchronously self._accessible = accessible self._entering_text = False self._text_changed = False # select text domain matching this accessible state = self._state_tracker.get_state() \ if self._accessible else {} self._text_domain = self._text_domains.find_match(**state) self._text_domain.init_domain() # determine capabilities of this accessible self._can_insert_text = self.get_accessible_capabilities(**state) # log accessible info if _logger.isEnabledFor(logging.DEBUG): log = _logger.debug log("-"*70) log("Accessible focused: ") if self._accessible: state = self._state_tracker.get_state() for key, value in sorted(state.items()): msg = str(key) + "=" if key == "state-set": msg += repr(AtspiStateType.to_strings(value)) else: msg += str(value) log(msg) log("text_domain: {}".format(self._text_domain)) log("can_insert_text: {}".format(self._can_insert_text)) log("") else: log("None") log("") self._update_context() self._wp.on_text_entry_activated() def _on_text_changed(self, event): insertion_span = self._record_text_change(event.pos, event.length, event.insert) # synchrounously notify of text insertion if insertion_span: try: cursor_offset = self._accessible.get_caret_offset() except: # gi._glib.GError pass else: self._wp.on_text_inserted(insertion_span, cursor_offset) self._update_context() def _on_text_caret_moved(self, event): self._update_context() def _on_atspi_key_pressed(self, event): """ disabled, Francesco didn't receive any AT-SPI key-strokes. """ keycode = event.hw_code # uh oh, only keycodes... # hopefully "c" doesn't move around a lot. modifiers = event.modifiers #self._handle_key_press(keycode, modifiers) def on_onboard_typing(self, key, mod_mask): if key.is_text_changing(): keycode = 0 if key.is_return(): keycode = KeyCode.KP_Enter else: label = key.get_label() if label == "C" or label == "c": keycode = KeyCode.C self._handle_key_press(keycode, mod_mask) def _handle_key_press(self, keycode, modifiers): if self._accessible: domain = self.get_text_domain() if domain: self._entering_text, end_of_editing = \ domain.handle_key_press(keycode, modifiers) if end_of_editing == True: self._wp.commit_changes() elif end_of_editing == False: self._wp.discard_changes() def _record_text_change(self, pos, length, insert): accessible = self._accessible insertion_span = None char_count = None if accessible: try: char_count = accessible.get_character_count() except: # gi._glib.GError: The application no longer exists # when closing a tab in gnome-terminal. char_count = None if not char_count is None: # record the change spans_to_update = [] if insert: #print("insert", pos, length) if self._entering_text and \ self.can_record_insertion(accessible, pos, length): if self._wp.is_typing() or length < 30: # Remember all of the insertion, might have been # a pressed snippet or wordlist button. include_length = -1 else: # Remember only the first few characters. # Large inserts can be paste, reload or scroll # operations. Only learn the first word of these. include_length = 2 # simple span for current insertion begin = max(pos - 100, 0) end = min(pos+length + 100, char_count) text = Atspi.Text.get_text(accessible, begin, end) insertion_span = TextSpan(pos, length, text, begin) else: # Remember nothing, just update existing spans. include_length = None spans_to_update = self._changes.insert(pos, length, include_length) else: #print("delete", pos, length) spans_to_update = self._changes.delete(pos, length, self._entering_text) # update text of the modified spans for span in spans_to_update: # Get some more text around the span to hopefully # include whole words at beginning and end. begin = max(span.begin() - 100, 0) end = min(span.end() + 100, char_count) span.text = Atspi.Text.get_text(accessible, begin, end) span.text_pos = begin #print(self._changes) self._text_changed = True return insertion_span def _update_context(self): self._update_context_timer.start(0.01, self.on_text_context_changed) def on_text_context_changed(self): result = self._text_domain.read_context(self._accessible) if not result is None: (self._context, self._line, self._line_cursor, self._span_at_cursor, self._begin_of_text, self._begin_of_text_offset) = result context = self.get_bot_context() # make sure to include bot-markers if self._last_context != context or \ self._last_line != self._line: self._last_context = context self._last_line = self._line self._wp.on_text_context_changed() return False
class LayoutPopup(KeyboardPopup, LayoutView, TouchInput): """ Popup showing a (sub-)layout tree. """ IDLE_CLOSE_DELAY = 0 # seconds of inactivity until window closes def __init__(self, keyboard, notify_done_callback): self._layout = None self._notify_done_callback = notify_done_callback self._drag_selected = False # grazed by the pointer? KeyboardPopup.__init__(self) LayoutView.__init__(self, keyboard) TouchInput.__init__(self) self.connect("draw", self._on_draw) self.connect("destroy", self._on_destroy_event) self._close_timer = Timer() self.start_close_timer() def cleanup(self): self.stop_close_timer() # fix label popup staying visible on double click self.keyboard.hide_touch_feedback() LayoutView.cleanup(self) # deregister from keyboard def get_toplevel(self): return self def set_layout(self, layout, frame_width): self._layout = layout self._frame_width = frame_width self.update_labels() # set window size layout_canvas_rect = layout.get_canvas_border_rect() canvas_rect = layout_canvas_rect.inflate(frame_width) w, h = canvas_rect.get_size() self.set_default_size(w + 1, h + 1) def get_layout(self): return self._layout def get_frame_width(self): return self._frame_width def got_motion(self): """ Has the pointer ever entered the popup? """ return self._drag_selected def handle_realize_event(self): self.get_window().set_override_redirect(True) super(LayoutPopup, self).handle_realize_event() def _on_destroy_event(self, user_data): self.cleanup() def on_enter_notify(self, widget, event): self.stop_close_timer() def on_leave_notify(self, widget, event): self.start_close_timer() def on_input_sequence_begin(self, sequence): self.stop_close_timer() key = self.get_key_at_location(sequence.point) if key: sequence.active_key = key self.keyboard.key_down(key, self, sequence) def on_input_sequence_update(self, sequence): if sequence.state & BUTTON123_MASK: key = self.get_key_at_location(sequence.point) # drag-select new active key active_key = sequence.active_key if not active_key is key and \ (active_key is None or not active_key.activated): sequence.active_key = key self.keyboard.key_up(active_key, self, sequence, False) self.keyboard.key_down(key, self, sequence, False) self._drag_selected = True def on_input_sequence_end(self, sequence): key = sequence.active_key if key: keyboard = self.keyboard keyboard.key_up(key, self, sequence) if key and \ not self._drag_selected: Timer(config.UNPRESS_DELAY, self.close_window) else: self.close_window() def _on_draw(self, widget, context): decorated = LayoutView.draw(self, widget, context) def draw_window_frame(self, context, lod): corner_radius = config.CORNER_RADIUS border_rgba = self.get_popup_window_rgba("border") alpha = border_rgba[3] colors = [ [[0.5, 0.5, 0.5, alpha], 0 , 1], [border_rgba, 1.5, 2.0], ] rect = Rect(0, 0, self.get_allocated_width(), self.get_allocated_height()) for rgba, pos, width in colors: r = rect.deflate(width) roundrect_arc(context, r, corner_radius) context.set_line_width(width) context.set_source_rgba(*rgba) context.stroke() def close_window(self): self._notify_done_callback() def start_close_timer(self): if self.IDLE_CLOSE_DELAY: self._close_timer.start(self.IDLE_CLOSE_DELAY, self.close_window) def stop_close_timer(self): self._close_timer.stop()
class ScanMode(Timer): """ Abstract base class for all scanning modes. Specifies how the scanner moves between chunks of keys and when to activate them. Scan mode subclasses define a set of actions they support and the base class translates input device events into scan actions. Hierarchy: ScanMode --> AutoScan --> UserScan --> OverScan --> StepScan --> DirectScan """ """ Scan actions """ ACTION_STEP = 0 ACTION_LEFT = 1 ACTION_RIGHT = 2 ACTION_UP = 3 ACTION_DOWN = 4 ACTION_ACTIVATE = 5 ACTION_STEP_START = 6 ACTION_STEP_STOP = 7 ACTION_UNHANDLED = 8 """ Time between key activation flashes (in sec) """ ACTIVATION_FLASH_INTERVAL = 0.1 """ Number of key activation flashes """ ACTIVATION_FLASH_COUNT = 4 def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None def __del__(self): logger.debug("ScanMode.__del__()") def map_actions(self, detail, pressed): """ Abstract: Convert input events into scan actions. """ raise NotImplementedError() def do_action(self, action): """ Abstract: Handle scan actions. """ raise NotImplementedError() def scan(self): """ Abstract: Move between chunks. """ raise NotImplementedError() def create_chunker(self): """ Abstract: Create a chunker instance. """ raise NotImplementedError() def init_position(self): """ Virtual: Called if a new layer was set or a key activated. """ pass def handle_event(self, event, detail): """ Translate device events into scan actions. """ # Ignore events during key activation if self._activation_timer.is_running(): return if event == "ButtonPress": button_map = config.scanner.device_button_map action = self.map_actions(button_map, detail, True) elif event == "ButtonRelease": button_map = config.scanner.device_button_map action = self.map_actions(button_map, detail, False) elif event == "KeyPress": key_map = config.scanner.device_key_map action = self.map_actions(key_map, detail, True) elif event == "KeyRelease": key_map = config.scanner.device_key_map action = self.map_actions(key_map, detail, False) else: action = self.ACTION_UNHANDLED if action != self.ACTION_UNHANDLED: self.do_action(action) def on_timer(self): """ Override: Timer() callback. """ return self.scan() def max_cycles_reached(self): """ Check if the maximum number of scan cycles is reached. """ return self.chunker.cycles >= config.scanner.cycles def set_layer(self, layout, layer): """ Set the layer that should be scanned. """ self.reset() self.chunker = self.create_chunker() self.chunker.chunk(layout, layer) self.init_position() def _on_activation_timer(self, key): """ Timer callback: Flashes the key and finally activates it. """ if self._flash > 0: key.scanned = not key.scanned self._flash -= 1 self.redraw([key]) return True else: self._activate_callback(key) self.init_position() return False def activate(self): """ Activates a key and triggers feedback. """ key = self.chunker.get_key() if not key: return if config.scanner.feedback_flash: self._flash = self.ACTIVATION_FLASH_COUNT self._activation_timer.start(self.ACTIVATION_FLASH_INTERVAL, self._on_activation_timer, key) else: self._activate_callback(key) self.init_position() def reset(self): """ Stop scanning and clear all highlights. """ if self.is_running(): self.stop() if self.chunker: self.redraw(self.chunker.highlight_all(False)) def redraw(self, keys=None): """ Update individual keys or the entire keyboard. """ self._redraw_callback(keys) def finalize(self): """ Clean up the ScanMode instance. """ self.reset() self._activation_timer = None
class ScanMode(Timer): """ Abstract base class for all scanning modes. Specifies how the scanner moves between chunks of keys and when to activate them. Scan mode subclasses define a set of actions they support and the base class translates input device events into scan actions. Hierarchy: ScanMode --> AutoScan --> UserScan --> OverScan --> StepScan --> DirectScan """ """ Scan actions """ ACTION_STEP = 0 ACTION_LEFT = 1 ACTION_RIGHT = 2 ACTION_UP = 3 ACTION_DOWN = 4 ACTION_ACTIVATE = 5 ACTION_STEP_START = 6 ACTION_STEP_STOP = 7 ACTION_UNHANDLED = 8 """ Handles Key Events (Multiple Press at a time) """#In MUL_KEY = 0#In SCAN_PREV_ACTION = ACTION_UNHANDLED#In SCAN_ACTION_DO = True#In """ Time between key activation flashes (in sec) """ ACTIVATION_FLASH_INTERVAL = 0.1 """ Number of key activation flashes """ ACTIVATION_FLASH_COUNT = 2 def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Counter for key popup animation """ self._popup_display=0 #In """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None """ Time between key activation flashes (in sec) """ self.ACTIVATION_FLASH_INTERVAL = config.scanner.activation_flash_interval #0.1 #In """ Number of key activation flashes """ self.ACTIVATION_FLASH_COUNT = config.scanner.activation_flash_count #2 #In def __del__(self): logger.debug("ScanMode.__del__()") def map_actions(self, detail, pressed): """ Abstract: Convert input events into scan actions. """ raise NotImplementedError() def do_action(self, action): """ Abstract: Handle scan actions. """ raise NotImplementedError() def scan(self): """ Abstract: Move between chunks. """ raise NotImplementedError() def create_chunker(self): """ Abstract: Create a chunker instance. """ raise NotImplementedError() def init_position(self): """ Virtual: Called if a new layer was set or a key activated. """ pass def handle_event(self, event): """ Translate device events into scan actions. """ # Ignore events during key activation if self._activation_timer.is_running(): return event_type = event.xi_type if event_type == XIEventType.ButtonPress: button_map = config.scanner.device_button_map action = self.map_actions(button_map, event.button, True) elif event_type == XIEventType.ButtonRelease: button_map = config.scanner.device_button_map action = self.map_actions(button_map, event.button, False) elif event_type == XIEventType.KeyPress: if self.MUL_KEY >= 0:#In key_map = config.scanner.device_key_map#In self.SCAN_PREV_ACTION = self.map_actions(key_map, event.keyval, True)#In self.MUL_KEY = self.MUL_KEY + 1#In return#In else: action = self.map_actions(key_map, event.keyval, False) elif event_type == XIEventType.KeyRelease: if self.MUL_KEY > 0:#In self.MUL_KEY = self.MUL_KEY - 1#In key_map = config.scanner.device_key_map action = self.map_actions(key_map, event.keyval, True)#In if action != self.SCAN_PREV_ACTION:#In self.SCAN_ACTION_DO = False#In if self.MUL_KEY > 0 or (self.MUL_KEY == 0 and self.SCAN_ACTION_DO != True):#In action = self.map_actions(key_map, event.keyval, False) if self.MUL_KEY == 0 and self.SCAN_ACTION_DO != True:#In """ print("E R R O R : PLEASE DONT PRESS BOTH FUNCTIONALITIES TOGETHER!!!")#In TODO : Show Error Message """ self.SCAN_ACTION_DO = True#In else: action = self.map_actions(key_map, event.keyval, False) else: action = self.ACTION_UNHANDLED if action != self.ACTION_UNHANDLED: self.do_action(action) def on_timer(self): """ Override: Timer() callback. """ return self.scan() def max_cycles_reached(self): """ Check if the maximum number of scan cycles is reached. """ return self.chunker.cycles >= config.scanner.cycles def set_layer(self, layout, layer): """ Set the layer that should be scanned. """ self.reset() self.chunker = self.create_chunker() self.chunker.chunk(layout, layer) self.init_position() def _on_activation_timer(self, key): """ Timer callback: Flashes the key and finally activates it. """ if self._flash > 0: key.scanned = not key.scanned self._flash -= 1 self.redraw([key]) return True else: self._activate_callback(key) self.init_position() return False def _on_activation_timer_popup(self, key):#In """ Timer callback: Reset Scanner. """ self.init_position() return False def activate(self): """ Activates a key and triggers feedback. """ key = self.chunker.get_key() if not key: return if config.scanner.feedback_flash: """ Scanner Blinking """ self._flash = self.ACTIVATION_FLASH_COUNT * 2 #In self._activation_timer.start(self.ACTIVATION_FLASH_INTERVAL, self._on_activation_timer, key) else:#In """ Scanner Popup """ delay = config.UNPRESS_DELAY #In config.UNPRESS_DELAY = config.scanner.scanner_popup_unpress_delay #In self._activate_callback(key) self._activation_timer.start(config.scanner.scanner_popup_unpress_delay, self._on_activation_timer_popup, key) #In config.UNPRESS_DELAY = delay #In #self.init_position() def reset(self): """ Stop scanning and clear all highlights. """ if self.is_running(): self.stop() if self.chunker: self.redraw(self.chunker.highlight_all(False)) def redraw(self, keys=None): """ Update individual keys or the entire keyboard. """ self._redraw_callback(keys) def finalize(self): """ Clean up the ScanMode instance. """ self.reset() self._activation_timer = None
class TouchInput(InputEventSource): """ Unified handling of multi-touch sequences and conventional pointer input. """ GESTURE_DETECTION_SPAN = 100 # [ms] until two finger tap&drag is detected GESTURE_DELAY_PAUSE = 3000 # [ms] Suspend delayed sequence begin for this # amount of time after the last key press. delay_sequence_begin = True # No delivery, i.e. no key-presses after # gesture detection, but delays press-down. def __init__(self): InputEventSource.__init__(self) self._input_sequences = {} self._touch_events_enabled = self.is_touch_enabled() self._multi_touch_enabled = config.keyboard.touch_input == \ TouchInputEnum.MULTI self._gestures_enabled = self._touch_events_enabled self._last_event_was_touch = False self._last_sequence_time = 0 self._gesture = NO_GESTURE self._gesture_begin_point = (0, 0) self._gesture_begin_time = 0 self._gesture_detected = False self._gesture_cancelled = False self._num_tap_sequences = 0 self._gesture_timer = Timer() def is_touch_enabled(self): return config.keyboard.touch_input != TouchInputEnum.NONE def has_input_sequences(self): """ Are any clicks/touches still ongoing? """ return bool(self._input_sequences) def last_event_was_touch(self): """ Was there just a touch event? """ return self._last_event_was_touch def has_touch_source(self, event): """ Was source device of event a touch screen? """ source_device = event.get_source_device() source = source_device.get_source() return source == Gdk.InputSource.TOUCHSCREEN def _on_button_press_event(self, widget, event): if self._touch_events_enabled and \ self.has_touch_source(event): return # - Ignore double clicks (GDK_2BUTTON_PRESS), # we're handling them ourselves. # - no mouse wheel buttons if event.type == Gdk.EventType.BUTTON_PRESS and \ 1 <= event.button <= 3: sequence = InputSequence() sequence.init_from_button_event(event) sequence.primary = True self._last_event_was_touch = False self._input_sequence_begin(sequence) def _on_button_release_event(self, widget, event): sequence = self._input_sequences.get(POINTER_SEQUENCE) if not sequence is None: sequence.point = (event.x, event.y) sequence.root_point = (event.x_root, event.y_root) sequence.time = event.get_time() self._input_sequence_end(sequence) def _on_motion_event(self, widget, event): if self._touch_events_enabled and \ self.has_touch_source(event): return sequence = self._input_sequences.get(POINTER_SEQUENCE) if sequence is None and \ not event.state & BUTTON123_MASK: sequence = InputSequence() sequence.primary = True if sequence: sequence.init_from_motion_event(event) self._last_event_was_touch = False self._input_sequence_update(sequence) def _on_enter_notify(self, widget, event): self.on_enter_notify(widget, event) def _on_leave_notify(self, widget, event): self.on_leave_notify(widget, event) def _on_touch_event(self, widget, event): if not self.has_touch_source(event): return touch = event.touch id = str(touch.sequence) self._last_event_was_touch = True event_type = event.type if event_type == Gdk.EventType.TOUCH_BEGIN: sequence = InputSequence() sequence.init_from_touch_event(touch, id) if len(self._input_sequences) == 0: sequence.primary = True self._input_sequence_begin(sequence) elif event_type == Gdk.EventType.TOUCH_UPDATE: sequence = self._input_sequences.get(id) if not sequence is None: sequence.point = (touch.x, touch.y) sequence.root_point = (touch.x_root, touch.y_root) sequence.time = event.get_time() sequence.update_time = time.time() self._input_sequence_update(sequence) else: if event_type == Gdk.EventType.TOUCH_END: pass elif event_type == Gdk.EventType.TOUCH_CANCEL: pass sequence = self._input_sequences.get(id) if not sequence is None: sequence.time = event.get_time() self._input_sequence_end(sequence) def _input_sequence_begin(self, sequence): """ Button press/touch begin """ self._gesture_sequence_begin(sequence) first_sequence = len(self._input_sequences) == 0 if first_sequence or \ self._multi_touch_enabled: self._input_sequences[sequence.id] = sequence if not self._gesture_detected: if first_sequence and \ self._multi_touch_enabled and \ self.delay_sequence_begin and \ sequence.time - self._last_sequence_time > \ self.GESTURE_DELAY_PAUSE: # Delay the first tap; we may have to stop it # from reaching the keyboard. self._gesture_timer.start(self.GESTURE_DETECTION_SPAN / 1000.0, self.on_delayed_sequence_begin, sequence, sequence.point) else: # Tell the keyboard right away. self.deliver_input_sequence_begin(sequence) self._last_sequence_time = sequence.time def on_delayed_sequence_begin(self, sequence, point): if not self._gesture_detected: # work around race condition sequence.point = point # return to the original begin point self.deliver_input_sequence_begin(sequence) self._gesture_cancelled = True return False def deliver_input_sequence_begin(self, sequence): self.on_input_sequence_begin(sequence) sequence.delivered = True def _input_sequence_update(self, sequence): """ Pointer motion/touch update """ self._gesture_sequence_update(sequence) if not sequence.state & BUTTON123_MASK or \ not self.in_gesture_detection_delay(sequence): self._gesture_timer.finish() # run delayed begin before update self.on_input_sequence_update(sequence) def _input_sequence_end(self, sequence): """ Button release/touch end """ self._gesture_sequence_end(sequence) self._gesture_timer.finish() # run delayed begin before end if sequence.id in self._input_sequences: del self._input_sequences[sequence.id] if sequence.delivered: self.on_input_sequence_end(sequence) if self._input_sequences: self._discard_stuck_input_sequences() self._last_sequence_time = sequence.time def _discard_stuck_input_sequences(self): """ Input sequence handling requires guaranteed balancing of begin, update and end events. There is no indication yet this isn't always the case, but still, at this time it seems like a good idea to prepare for the worst. -> Clear out aged input sequences, so Onboard can start from a fresh slate and not become terminally unresponsive. """ expired_time = time.time() - 30 for id, sequence in list(self._input_sequences.items()): if sequence.update_time < expired_time: _logger.warning("discarding expired input sequence " + str(id)) del self._input_sequences[id] def in_gesture_detection_delay(self, sequence): """ Are we still in the time span where sequence begins aren't delayed and can't be undone after gesture detection? """ span = sequence.time - self._gesture_begin_time return span < self.GESTURE_DETECTION_SPAN def _gesture_sequence_begin(self, sequence): # first tap? if self._num_tap_sequences == 0: self._gesture = NO_GESTURE self._gesture_detected = False self._gesture_cancelled = False self._gesture_begin_point = sequence.point self._gesture_begin_time = sequence.time # event time else: # subsequent taps if self.in_gesture_detection_delay(sequence) and \ not self._gesture_cancelled: self._gesture_timer.stop() # cancel delayed sequence begin self._gesture_detected = True self._num_tap_sequences += 1 def _gesture_sequence_update(self, sequence): if self._gesture_detected and \ sequence.state & BUTTON123_MASK and \ self._gesture == NO_GESTURE: point = sequence.point dx = self._gesture_begin_point[0] - point[0] dy = self._gesture_begin_point[1] - point[1] d2 = dx * dx + dy * dy # drag gesture? if d2 >= DRAG_GESTURE_THRESHOLD2: num_touches = len(self._input_sequences) self._gesture = DRAG_GESTURE self.on_drag_gesture_begin(num_touches) return True def _gesture_sequence_end(self, sequence): if len(self._input_sequences) == 1: # last sequence of the gesture? if self._gesture_detected: gesture = self._gesture if gesture == NO_GESTURE: # tap gesture? elapsed = sequence.time - self._gesture_begin_time if elapsed <= 300: self.on_tap_gesture(self._num_tap_sequences) elif gesture == DRAG_GESTURE: self.on_drag_gesture_end(0) self._num_tap_sequences = 0 def on_tap_gesture(self, num_touches): return False def on_drag_gesture_begin(self, num_touches): return False def on_drag_gesture_end(self, num_touches): return False def redirect_sequence_update(self, sequence, func): """ redirect input sequence update to self. """ sequence = self._get_redir_sequence(sequence) func(sequence) def redirect_sequence_end(self, sequence, func): """ Redirect input sequence end to self. """ sequence = self._get_redir_sequence(sequence) # Make sure has_input_sequences() returns False inside of func(). # The keyboard needs this to detect the end of input. if sequence.id in self._input_sequences: del self._input_sequences[sequence.id] func(sequence) def _get_redir_sequence(self, sequence): """ Return a copy of <sequence>, managed in the target window. """ redir_sequence = self._input_sequences.get(sequence.id) if redir_sequence is None: redir_sequence = sequence.copy() redir_sequence.initial_active_key = None redir_sequence.active_key = None redir_sequence.cancel_key_action = False # was canceled by long press self._input_sequences[redir_sequence.id] = redir_sequence # convert to the new window client coordinates pos = self.get_position() rp = sequence.root_point redir_sequence.point = (rp[0] - pos[0], rp[1] - pos[1]) return redir_sequence
class ScanMode(Timer): """ Abstract base class for all scanning modes. Specifies how the scanner moves between chunks of keys and when to activate them. Scan mode subclasses define a set of actions they support and the base class translates input device events into scan actions. Hierarchy: ScanMode --> AutoScan --> UserScan --> OverScan --> StepScan --> DirectScan """ """ Scan actions """ ACTION_STEP = 0 ACTION_LEFT = 1 ACTION_RIGHT = 2 ACTION_UP = 3 ACTION_DOWN = 4 ACTION_ACTIVATE = 5 ACTION_STEP_START = 6 ACTION_STEP_STOP = 7 ACTION_UNHANDLED = 8 """ Time between key activation flashes (in sec) """ ACTIVATION_FLASH_INTERVAL = 0.1 """ Number of key activation flashes """ ACTIVATION_FLASH_COUNT = 4 def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None def __del__(self): logger.debug("ScanMode.__del__()") def map_actions(self, detail, pressed): """ Abstract: Convert input events into scan actions. """ raise NotImplementedError() def do_action(self, action): """ Abstract: Handle scan actions. """ raise NotImplementedError() def scan(self): """ Abstract: Move between chunks. """ raise NotImplementedError() def create_chunker(self): """ Abstract: Create a chunker instance. """ raise NotImplementedError() def init_position(self): """ Virtual: Called if a new layer was set or a key activated. """ pass def handle_event(self, event): """ Translate device events into scan actions. """ # Ignore events during key activation if self._activation_timer.is_running(): return event_type = event.xi_type if event_type == XIEventType.ButtonPress: button_map = config.scanner.device_button_map action = self.map_actions(button_map, event.button, True) elif event_type == XIEventType.ButtonRelease: button_map = config.scanner.device_button_map action = self.map_actions(button_map, event.button, False) elif event_type == XIEventType.KeyPress: key_map = config.scanner.device_key_map action = self.map_actions(key_map, event.keyval, True) elif event_type == XIEventType.KeyRelease: key_map = config.scanner.device_key_map action = self.map_actions(key_map, event.keyval, False) else: action = self.ACTION_UNHANDLED if action != self.ACTION_UNHANDLED: self.do_action(action) def on_timer(self): """ Override: Timer() callback. """ return self.scan() def max_cycles_reached(self): """ Check if the maximum number of scan cycles is reached. """ return self.chunker.cycles >= config.scanner.cycles def set_layer(self, layout, layer): """ Set the layer that should be scanned. """ self.reset() self.chunker = self.create_chunker() self.chunker.chunk(layout, layer) self.init_position() def _on_activation_timer(self, key): """ Timer callback: Flashes the key and finally activates it. """ if self._flash > 0: key.scanned = not key.scanned self._flash -= 1 self.redraw([key]) return True else: self._activate_callback(key) self.init_position() return False def activate(self): """ Activates a key and triggers feedback. """ key = self.chunker.get_key() if not key: return if config.scanner.feedback_flash: self._flash = self.ACTIVATION_FLASH_COUNT self._activation_timer.start(self.ACTIVATION_FLASH_INTERVAL, self._on_activation_timer, key) else: self._activate_callback(key) self.init_position() def reset(self): """ Stop scanning and clear all highlights. """ if self.is_running(): self.stop() if self.chunker: self.redraw(self.chunker.highlight_all(False)) def redraw(self, keys=None): """ Update individual keys or the entire keyboard. """ self._redraw_callback(keys) def finalize(self): """ Clean up the ScanMode instance. """ self.reset() self._activation_timer = None
def _start_dwelling(self): self._stop_dwelling() self._dwell_begin_timer = Timer(1.5, self._on_dwell_begin_timer) self._no_more_dwelling = True
def _on_dwell_begin_timer(self): self._dwell_progress.start_dwelling() self._dwell_timer = Timer(0.025, self._on_dwell_timer) return False
class WindowRectPersist(WindowRectTracker): """ Save and restore window position and size. """ def __init__(self): WindowRectTracker.__init__(self) self._screen_orientation = None self._save_position_timer = Timer() # init detection of screen "rotation" screen = self.get_screen() screen.connect('size-changed', self.on_screen_size_changed) def cleanup(self): self._save_position_timer.finish() def is_visible(self): """ This is overloaded in KbdWindow """ return Gtk.Window.get_visible(self) def on_screen_size_changed(self, screen): """ detect screen rotation (tablets)""" # Give the screen time to settle, the window manager # may block the move to previously invalid positions and # when docked, the slide animation may be drowned out by all # the action in other processes. Timer(1.5, self.on_screen_size_changed_delayed, screen) def on_screen_size_changed_delayed(self, screen): self.restore_window_rect() def get_screen_orientation(self): """ Current orientation of the screen (tablet rotation). Only the aspect ratio is taken into account at this time. This appears to cover more cases than looking at monitor rotation, in particular with multi-monitor screens. """ screen = self.get_screen() if screen.get_width() >= screen.get_height(): return Orientation.LANDSCAPE else: return Orientation.PORTRAIT def restore_window_rect(self, startup = False): """ Restore window size and position. """ # Run pending save operations now, so they don't # interfere with the window rect after it was restored. self._save_position_timer.finish() orientation = self.get_screen_orientation() rect = self.read_window_rect(orientation) self._screen_orientation = orientation self._window_rect = rect _logger.debug("restore_window_rect {rect}, {orientation}" \ .format(rect = rect, orientation = orientation)) # Give the derived class a chance to modify the rect, # for example to correct the position for auto-show. rect = self.on_restore_window_rect(rect) self._window_rect = rect # move/resize the window if startup: # gnome-shell doesn't take kindly to an initial move_resize(). # The window ends up at (0, 0) on and goes back there # repeatedly when hiding and unhiding. self.set_default_size(rect.w, rect.h) self.move(rect.x, rect.y) else: self.move_resize(rect.x, rect.y, rect.w, rect.h) # Initialize shadow variables with valid values so they # don't get taken from the unreliable window. # Fixes bad positioning of the very first auto-show. if startup: self._window_rect = rect.copy() # Ignore frame dimensions; still better than asking the window. self._origin = rect.left_top() self._screen_orientation = self.get_screen_orientation() def on_restore_window_rect(self, rect): return rect def save_window_rect(self, orientation = None, rect = None): """ Save window size and position. """ if orientation is None: orientation = self._screen_orientation if rect is None: rect = self._window_rect # Give the derived class a chance to modify the rect, # for example to override it for auto-show. rect = self.on_save_window_rect(rect) self.write_window_rect(orientation, rect) _logger.debug("save_window_rect {rect}, {orientation}" \ .format(rect = rect, orientation = orientation)) def on_save_window_rect(self, rect): return rect def read_window_rect(self, orientation, rect): """ Read orientation dependent rect. Overload this in derived classes. """ raise NotImplementedError() def write_window_rect(self, orientation, rect): """ Write orientation dependent rect. Overload this in derived classes. """ raise NotImplementedError() def start_save_position_timer(self): """ Trigger saving position and size to gsettings Delay this a few seconds to avoid excessive disk writes. Remember the current rect and rotation as the screen may have been rotated when the saving happens. """ self._save_position_timer.start(5, self.save_window_rect, self.get_screen_orientation(), self.get_rect()) def stop_save_position_timer(self): self._save_position_timer.stop()
class IconPalette(WindowRectPersist, WindowManipulator, Gtk.Window): """ Class that creates a movable and resizable floating window without decorations. The window shows the icon of onboard scaled to fit to the window and a resize grip that honors the desktop theme in use. Onboard offers an option to the user to make the window appear whenever the user hides the onscreen keyboard. The user can then click on the window to hide it and make the onscreen keyboard reappear. """ __gsignals__ = { str('activated'): (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, ()) } """ Minimum size of the IconPalette """ MINIMUM_SIZE = 20 _layout_view = None def __init__(self): self._visible = False self._force_to_top = False self._last_pos = None self._dwell_progress = DwellProgress() self._dwell_begin_timer = None self._dwell_timer = None self._no_more_dwelling = False Gtk.Window.__init__(self, type_hint=self._get_window_type_hint(), skip_taskbar_hint=True, skip_pager_hint=True, has_resize_grip=False, urgency_hint=False, decorated=False, accept_focus=False, opacity=0.75, width_request=self.MINIMUM_SIZE, height_request=self.MINIMUM_SIZE) WindowRectPersist.__init__(self) WindowManipulator.__init__(self) self.set_keep_above(True) # use transparency if available visual = Gdk.Screen.get_default().get_rgba_visual() if visual: self.set_visual(visual) # set up event handling self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.POINTER_MOTION_MASK) self.connect("button-press-event", self._on_button_press_event) self.connect("motion-notify-event", self._on_motion_notify_event) self.connect("button-release-event", self._on_button_release_event) self.connect("draw", self._on_draw) self.connect("configure-event", self._on_configure_event) self.connect("realize", self._on_realize_event) self.connect("unrealize", self._on_unrealize_event) self.connect("enter-notify-event", self._on_mouse_enter) self.connect("leave-notify-event", self._on_mouse_leave) # default coordinates of the iconpalette on the screen self.set_min_window_size(self.MINIMUM_SIZE, self.MINIMUM_SIZE) #self.set_default_size(1, 1) # no flashing on left screen edge in unity self.restore_window_rect() # Realize the window. Test changes to this in all supported # environments. It's all too easy to have the icp not show up reliably. self.update_window_options() self.hide() once = CallOnce(100).enqueue # call at most once per 100ms rect_changed = lambda x: once(self._on_config_rect_changed) config.icp.position_notify_add(rect_changed) config.icp.size_notify_add(rect_changed) config.icp.resize_handles_notify_add( lambda x: self.update_resize_handles()) self.update_sticky_state() self.update_resize_handles() def cleanup(self): WindowRectPersist.cleanup(self) def set_layout_view(self, view): self._layout_view = view self.queue_draw() def get_color_scheme(self): if self._layout_view: return self._layout_view.get_color_scheme() return None def _on_configure_event(self, widget, event): self.update_window_rect() def on_drag_initiated(self): self.stop_save_position_timer() self._stop_dwelling() def on_drag_done(self): self.update_window_rect() self.start_save_position_timer() self._no_more_dwelling = True def _on_realize_event(self, user_data): """ Gdk window created """ set_unity_property(self) if config.is_force_to_top(): self.set_override_redirect(True) self.restore_window_rect(True) def _on_unrealize_event(self, user_data): """ Gdk window destroyed """ self.set_type_hint(self._get_window_type_hint()) def _get_window_type_hint(self): if config.is_force_to_top(): return Gdk.WindowTypeHint.NORMAL else: return Gdk.WindowTypeHint.UTILITY def update_window_options(self, startup=False): if not config.xid_mode: # not when embedding # (re-)create the gdk window? force_to_top = config.is_force_to_top() if self._force_to_top != force_to_top: self._force_to_top = force_to_top visible = self._visible # visible before? if self.get_realized(): # not starting up? self.hide() self.unrealize() self.realize() if visible: self.show() def update_sticky_state(self): if not config.xid_mode: if config.get_sticky_state(): self.stick() else: self.unstick() def update_resize_handles(self): """ Tell WindowManipulator about the active resize handles """ self.set_drag_handles(config.icp.resize_handles) def get_drag_threshold(self): """ Overload for WindowManipulator """ return config.get_drag_threshold() def _on_button_press_event(self, widget, event): """ Save the pointer position. """ if event.button == 1 and event.window == self.get_window(): self.enable_drag_protection(True) sequence = InputSequence() sequence.init_from_button_event(event) self.handle_press(sequence, move_on_background=True) if self.is_moving(): self.reset_drag_protection() # force threshold return False def _on_motion_notify_event(self, widget, event): """ Move the window if the pointer has moved more than the DND threshold. """ sequence = InputSequence() sequence.init_from_motion_event(event) self.handle_motion(sequence, fallback=True) self.set_drag_cursor_at((event.x, event.y)) # start dwelling if nothing else is going on point = (event.x, event.y) hit = self.hit_test_move_resize(point) if hit is None: if not self.is_drag_initiated() and \ not self._is_dwelling() and \ not self._no_more_dwelling and \ not config.is_hover_click_active() and \ not config.lockdown.disable_dwell_activation: self._start_dwelling() else: self._stop_dwelling() # allow resizing in peace return False def _on_button_release_event(self, widget, event): """ Save the window geometry, hide the IconPalette and emit the "activated" signal. """ result = False if event.button == 1 and \ event.window == self.get_window() and \ not self.is_drag_active(): self.emit("activated") result = True self.stop_drag() self.set_drag_cursor_at((event.x, event.y)) return result def _on_mouse_enter(self, widget, event): pass def _on_mouse_leave(self, widget, event): self._stop_dwelling() self._no_more_dwelling = False def _on_draw(self, widget, cr): """ Draw the onboard icon. """ if not Gtk.cairo_should_draw_window(cr, self.get_window()): return False rect = Rect(0.0, 0.0, float(self.get_allocated_width()), float(self.get_allocated_height())) color_scheme = self.get_color_scheme() # clear background cr.save() cr.set_operator(cairo.OPERATOR_CLEAR) cr.paint() cr.restore() # draw background color background_rgba = list(color_scheme.get_icon_rgba("background")) if Gdk.Screen.get_default().is_composited(): background_rgba[3] *= 0.75 cr.set_source_rgba(*background_rgba) corner_radius = min(rect.w, rect.h) * 0.1 roundrect_arc(cr, rect, corner_radius) cr.fill() # decoration frame line_rect = rect.deflate(2) cr.set_line_width(2) roundrect_arc(cr, line_rect, corner_radius) cr.stroke() else: cr.set_source_rgba(*background_rgba) cr.paint() # draw themed icon self._draw_themed_icon(cr, rect, color_scheme) # draw dwell progress rgba = [0.8, 0.0, 0.0, 0.5] bg_rgba = [0.1, 0.1, 0.1, 0.5] if color_scheme: key = RectKey( "icon0") # take dwell color from the first icon "key" rgba = color_scheme.get_key_rgba(key, "dwell-progress") rgba[3] = min(0.75, rgba[3]) # more transparency key = RectKey("icon1") bg_rgba = color_scheme.get_key_rgba(key, "fill") bg_rgba[3] = min(0.75, rgba[3]) # more transparency dwell_rect = rect.grow(0.5) self._dwell_progress.draw(cr, dwell_rect, rgba, bg_rgba) return True def _draw_themed_icon(self, cr, icon_rect, color_scheme): """ draw themed icon """ keys = [RectKey("icon" + str(i)) for i in range(4)] # Default colors for the case when none of the icon keys # are defined in the color scheme. background_rgba = [1.0, 1.0, 1.0, 1.0] fill_rgbas = [[0.9, 0.7, 0.0, 0.75], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.54, 1.0, 1.0]] stroke_rgba = [0.0, 0.0, 0.0, 1.0] label_rgba = [0.0, 0.0, 0.0, 1.0] themed = False if color_scheme: if any(color_scheme.is_key_in_scheme(key) for key in keys): themed = True # four rounded rectangles rects = Rect(0.0, 0.0, 100.0, 100.0).deflate(5) \ .subdivide(2, 2, 6) cr.save() cr.scale(icon_rect.w / 100., icon_rect.h / 100.0) cr.translate(icon_rect.x, icon_rect.y) cr.select_font_face("sans-serif") cr.set_line_width(2) for i, key in enumerate(keys): rect = rects[i] if themed: fill_rgba = color_scheme.get_key_rgba(key, "fill") stroke_rgba = color_scheme.get_key_rgba(key, "stroke") label_rgba = color_scheme.get_key_rgba(key, "label") else: fill_rgba = fill_rgbas[i] roundrect_arc(cr, rect, 5) cr.set_source_rgba(*fill_rgba) cr.fill_preserve() cr.set_source_rgba(*stroke_rgba) cr.stroke() if i == 0 or i == 3: if i == 0: letter = "O" else: letter = "B" cr.set_font_size(25) x_bearing, y_bearing, _width, _height, \ x_advance, y_advance = cr.text_extents(letter) r = rect.align_rect(Rect(0, 0, _width, _height), 0.3, 0.33) cr.move_to(r.x - x_bearing, r.y - y_bearing) cr.set_source_rgba(*label_rgba) cr.show_text(letter) cr.new_path() cr.restore() def show(self): """ Override Gtk.Widget.hide() to save the window geometry. """ Gtk.Window.show(self) self.move_resize(*self.get_rect()) # sync with WindowRectTracker self._visible = True def hide(self): """ Override Gtk.Widget.hide() to save the window geometry. """ Gtk.Window.hide(self) self._visible = False def _on_config_rect_changed(self): """ Gsettings position or size changed """ orientation = self.get_screen_orientation() rect = self.read_window_rect(orientation) if self.get_rect() != rect: self.restore_window_rect() def read_window_rect(self, orientation): """ Read orientation dependent rect. Overload for WindowRectPersist. """ if orientation == Orientation.LANDSCAPE: co = config.icp.landscape else: co = config.icp.portrait rect = Rect(co.x, co.y, co.width, co.height) return rect def write_window_rect(self, orientation, rect): """ Write orientation dependent rect. Overload for WindowRectPersist. """ # There are separate rects for normal and rotated screen (tablets). if orientation == Orientation.LANDSCAPE: co = config.icp.landscape else: co = config.icp.portrait co.delay() co.x, co.y, co.width, co.height = rect co.apply() def _is_dwelling(self): return bool(self._dwell_begin_timer) and \ (self._dwell_begin_timer.is_running() or \ self._dwell_progress.is_dwelling()) def _start_dwelling(self): self._stop_dwelling() self._dwell_begin_timer = Timer(1.5, self._on_dwell_begin_timer) self._no_more_dwelling = True def _stop_dwelling(self): if self._dwell_begin_timer: self._dwell_begin_timer.stop() if self._dwell_timer: self._dwell_timer.stop() self._dwell_progress.stop_dwelling() self.queue_draw() def _on_dwell_begin_timer(self): self._dwell_progress.start_dwelling() self._dwell_timer = Timer(0.025, self._on_dwell_timer) return False def _on_dwell_timer(self): self._dwell_progress.opacity, done = \ Fade.sin_fade(self._dwell_progress.dwell_start_time, 0.3, 0, 1.0) self.queue_draw() if self._dwell_progress.is_done(): if not self.is_drag_active(): self.emit("activated") self.stop_drag() return False return True
class KbdWindow(KbdWindowBase, WindowRectTracker, Gtk.Window): # Minimum window size (for resizing in system mode, see handle_motion()) MINIMUM_SIZE = 20 home_rect = None def __init__(self, keyboard_widget, icp): self._last_ignore_configure_time = None self._last_configures = [] self._was_visible = False Gtk.Window.__init__(self, urgency_hint=False, width_request=self.MINIMUM_SIZE, height_request=self.MINIMUM_SIZE) KbdWindowBase.__init__(self, keyboard_widget, icp) WindowRectTracker.__init__(self) GObject.signal_new("quit-onboard", KbdWindow, GObject.SIGNAL_RUN_LAST, GObject.TYPE_BOOLEAN, ()) self._auto_position_poll_timer = Timer() self.restore_window_rect(startup=True) self.connect("map", self._on_map_event) self.connect("unmap", self._on_unmap_event) self.connect("delete-event", self._on_delete_event) self.connect("configure-event", self._on_configure_event) # Connect_after seems broken in Quantal, the callback is never called. #self.connect_after("configure-event", self._on_configure_event_after) self._osk_util.connect_root_property_notify( ["_NET_WORKAREA", "_NET_CURRENT_DESKTOP"], self._on_root_property_notify) once = CallOnce(100).enqueue # call at most once per 100ms rect_changed = lambda x: once(self._on_config_rect_changed) config.window.position_notify_add(rect_changed) config.window.size_notify_add(rect_changed) dock_size_changed = lambda x: once(self._on_config_dock_size_changed) config.window.dock_size_notify_add(dock_size_changed) def cleanup(self): WindowRectTracker.cleanup(self) KbdWindowBase.cleanup(self) if self.icp: self.icp.cleanup() self.icp.destroy() self.icp = None def _on_root_property_notify(self, property): """ Fixme: Exceptions get lost in here.""" if property == "_NET_WORKAREA": if config.is_docking_enabled() and \ not config.xid_mode: mon = self.get_docking_monitor() new_area = self.get_monitor_workarea() area = self._monitor_workarea.get(0) if area: # Only check for x changes, y is too dangerous for now, # too easy to get the timing wrong and end up with double docks. if area.x != new_area.x or \ area.w != new_area.w: area.x = new_area.x area.w = new_area.w _logger.info("workarea changed to {}, " "using {} for docking." \ .format(str(new_area), str(area))) self.update_docking() elif property == "_NET_CURRENT_DESKTOP": # OpenBox: Make sure to move the keyboard to the new desktop # on the next occasion. # Unity: Never reached (Raring), _NET_CURRENT_DESKTOP isn't # set when switching desktops there. However we do get a # configure event, so the transitioning code moves the # window and it is brought to the current desktop anyway. self._desktop_switch_count += 1 def _on_map_event(self, user_data): pass def _on_unmap_event(self, user_data): # Turn off struts in case this unmap is in response to # changes in window options, force-to-top in particular. if config.is_docking_enabled(): self.clear_struts() # untity starts onboard before the desktops # workarea has settled, reset it here on hiding, # as we know our struts are gone from this point. self.reset_monitor_workarea() def on_visibility_changed(self, visible): if not self._visible and visible and \ not config.is_docking_enabled() and \ not config.xid_mode: rect = self.get_current_rect() if not rect is None: # shouldn't happen, fix this self.move_resize(*rect) # sync position KbdWindowBase.on_visibility_changed(self, visible) def _on_config_rect_changed(self): """ Gsettings position or size changed """ if not config.xid_mode and \ not config.is_docking_enabled(): orientation = self.get_screen_orientation() rect = self.read_window_rect(orientation) # Only apply the new rect if it isn't the one we just wrote to # gsettings. Someone has to have manually changed the values # in gsettings to allow moving the window. rects = list(self._written_window_rects.values()) if not any(rect == r for r in rects): self.restore_window_rect() def _on_config_dock_size_changed(self): """ Gsettings size changed """ if not config.xid_mode and \ config.is_docking_enabled(): size = self.get_dock_size() # Only apply the new rect if it isn't the one we just wrote to # gsettings. Someone has to have manually changed the values # in gsettings to allow moving the window. sizes = list(self._written_dock_sizes.values()) if not any(size == sz for sz in sizes): self.restore_window_rect() def on_user_positioning_begin(self): self.stop_save_position_timer() self.stop_auto_position() self.keyboard_widget.freeze_auto_show() def on_user_positioning_done(self): self.update_window_rect() #self.detect_docking() if config.is_docking_enabled(): self.write_docking_size(self.get_screen_orientation(), self.get_size()) self.update_docking() else: self.update_home_rect() # Thaw auto show after a short delay to stop the window # from hiding due to spurios focus events after a system resize. self.keyboard_widget.thaw_auto_show(1.0) def detect_docking(self): if self.keyboard_widget.was_moving(): config.window.docking_enabled = False def _on_configure_event(self, widget, event): self.update_window_rect() if not config.is_docking_enabled(): # Connect_after seems broken in Quantal, but we still need to # get in after the default configure handler is done. Try to run # _on_configure_event_after in an idle handler instead. GLib.idle_add(self._on_configure_event_after, widget, event.copy()) def _on_configure_event_after(self, widget, event): """ Run this after KeyboardWidget's configure handler. After resizing Keyboard.update_layout() has to be called before limit_position() or the window jumps when it was close to the opposite screen edge of the resize handle. """ # Configure event due to user positioning? result = self._filter_configure_event(self._window_rect) if result == 0: self.update_home_rect() def _filter_configure_event(self, rect): """ Returns 0 for detected user positioning/sizing. Multiple defenses against false positives, i.e. window movement by autoshow, screen rotation, whathaveyou. """ # There is no user positioning in xembed mode. if config.xid_mode: return -1 # There is no system provided way to move/resize in # force-to-top mode. Solely rely on on_user_positioning_done(). if config.is_force_to_top(): return -2 # There is no user positioning for invisible windows. if not self.is_visible(): return -3 # There is no user positioning for iconified windows. if self.is_iconified(): return -4 # There is no user positioning for maximized windows. if self.is_maximized(): return -5 # Remember past n configure events. now = time.time() max_events = 4 self._last_configures = self._last_configures[-(max_events - 1):] # Same rect as before? if len(self._last_configures) and \ self._last_configures[-1][0] == rect: return 1 self._last_configures.append([rect, now]) # Only just started? if len(self._last_configures) < max_events: return 2 # Did we just move the window by auto-show? if not self._last_ignore_configure_time is None and \ time.time() - self._last_ignore_configure_time < 0.5: return 3 # Is the new window rect one of our known ones? if self.is_known_rect(self._window_rect): return 4 # Dragging the decorated frame doesn't produce continous # configure-events anymore as in Oneriric (Precise). # Disable all affected checks based on this. # The home rect will probably get lost occasionally. if not config.has_window_decoration(): # Less than n configure events in the last x seconds? first = self._last_configures[0] intervall = now - first[1] if intervall > 1.0: return 5 # Is there a jump > threshold in past positions? r0 = self._last_configures[-1][0] r1 = self._last_configures[-2][0] dx = r1.x - r0.x dy = r1.y - r0.y d2 = dx * dx + dy * dy if d2 > 50**2: self._last_configures = [] # restart return 6 return 0 def ignore_configure_events(self): self._last_ignore_configure_time = time.time() def remember_rect(self, rect): """ Remember the last 3 rectangles of auto-show repositioning. Time and order of configure events is somewhat unpredictable, so don't rely only on a single remembered rect. """ self._known_window_rects = self._known_window_rects[-3:] self._known_window_rects.append(rect) # Remembering the rects doesn't help if respositioning outside # of the work area in compiz with force-to-top mode disabled. # WM corrects window positions to fit into the viewable area. # -> add timing based block self.ignore_configure_events() def get_known_rects(self): """ Return all rects that may have resulted from internal window moves, not from user controlled drag operations. """ rects = list(self._known_window_rects) co = config.window.landscape rects.append(Rect(co.x, co.y, co.width, co.height)) co = config.window.portrait rects.append(Rect(co.x, co.y, co.width, co.height)) rects.append(self.home_rect) return rects def is_known_rect(self, rect): """ The home rect should be updated in response to user positiong/resizing. However we are unable to detect the end of window movement/resizing when window decoration is enabled. Instead we check if the current window rect is different from the ones auto-show knows and assume the user has changed it in this case. """ return any(rect == r for r in self.get_known_rects()) def move_home_rect_into_view(self): """ Make sure the home rect is valid, move it if necessary. This function may be called even if the window is invisible. """ rect = self._window_rect.copy() x, y = rect.x, rect.y _x, _y = self.keyboard_widget.limit_position(x, y) if _x != x or _y != y: self.update_home_rect() def update_home_rect(self): if config.is_docking_enabled(): return # update home rect rect = self._window_rect.copy() # Make sure the move button stays visible if self.can_move_into_view(): rect.x, rect.y = self.keyboard_widget.limit_position( rect.x, rect.y) self.home_rect = rect.copy() self.start_save_position_timer() # Make transitions aware of the new position, # undoubtedly reached by user positioning. # Else, window snaps back to the last transition position. self.keyboard_widget.sync_transition_position(rect) def get_home_rect(self): """ Get the un-repositioned rect, the one auto-show falls back to when there is nowhere else to move. """ if config.is_docking_enabled(): rect = self.get_dock_rect() else: rect = self.home_rect return rect def get_visible_rect(self): """ Returns the rect of the visible window rect with auto-show repositioning taken into account. """ home_rect = self.get_home_rect() # aware of docking rect = home_rect if config.is_auto_show_enabled(): r = self.get_repositioned_window_rect(home_rect) if not r is None: rect = r return rect def auto_position(self): self.update_position() # With docking enabled, when focusing the search entry of a # maximized firefox window, it changes position when the work # area shrinks and ends up below Onboard. # -> periodically update the window position for a little while, # this way slow systems can catch up too eventually (Nexus 7). self._poll_auto_position_start_time = time.time() start_delay = 0.1 self._auto_position_poll_timer.start(start_delay, self._on_auto_position_poll, start_delay) def _on_auto_position_poll(self, delay): self.update_position() # start another timer for progressively longer intervals delay = min(delay * 2.0, 1.0) if time.time() + delay < self._poll_auto_position_start_time + 3.0: self._auto_position_poll_timer.start(delay, self._on_auto_position_poll, delay) return True else: return False def stop_auto_position(self): self._auto_position_poll_timer.stop() def update_position(self): home_rect = self.get_home_rect() rect = self.get_repositioned_window_rect(home_rect) if rect is None: # move back home rect = home_rect if self.get_position() != rect.get_position(): self.keyboard_widget.transition_position_to(rect.x, rect.y) self.keyboard_widget.commit_transition() def get_repositioned_window_rect(self, home_rect): clearance = config.auto_show.widget_clearance test_clearance = clearance move_clearance = clearance limit_rects = None # None: all monitors # No test clearance when docking. Make it harder to jump # out of the dock, for example for the bottom search box # in maximized firefox. if config.is_docking_enabled(): test_clearance = (clearance[0], 0, clearance[2], 0) # limit the horizontal freedom to the docking monitor area, geom = self.get_docking_monitor_rects() limit_rects = [area] horizontal, vertical = self.get_repositioning_constraints() return self.keyboard_widget.auto_show.get_repositioned_window_rect( \ home_rect, limit_rects, test_clearance, move_clearance, horizontal, vertical) def reposition(self, x, y): """ Move the window from a transition, not meant for user positioning. """ # remember rects to distimguish from user move/resize w, h = self.get_size() self.remember_rect(Rect(x, y, w, h)) self.move(x, y) def get_repositioning_constraints(self): """ Return allowed respositioning directions for auto-show. """ if config.is_docking_enabled() and \ self.get_dock_expand(): return False, True else: return True, True def get_hidden_rect(self): """ Returns the rect of the hidden window rect with auto-show repositioning taken into account. """ if config.is_docking_enabled(): return self.get_docking_hideout_rect() return self.get_visible_rect() def get_current_rect(self): """ Returns the window rect with auto-show repositioning taken into account. """ if self.is_visible(): rect = self.get_visible_rect() else: rect = self.get_hidden_rect() return rect def on_restore_window_rect(self, rect): """ Overload for WindowRectTracker. """ if not config.is_docking_enabled(): self.home_rect = rect.copy() # check for alternative auto-show position r = self.get_current_rect() if r != rect: # remember our rects to distinguish from user move/resize self.remember_rect(r) rect = r self.keyboard_widget.sync_transition_position(rect) return rect def on_save_window_rect(self, rect): """ Overload for WindowRectTracker. """ # Ignore <rect> (self._window_rect), it may just be a temporary one # set by auto-show. Save the user selected home_rect instead. return self.home_rect def read_window_rect(self, orientation): """ Read orientation dependent rect. Overload for WindowRectTracker. """ if orientation == Orientation.LANDSCAPE: co = config.window.landscape else: co = config.window.portrait rect = Rect(co.x, co.y, co.width, co.height) return rect def write_window_rect(self, orientation, rect): """ Write orientation dependent rect. Overload for WindowRectTracker. """ # There are separate rects for normal and rotated screen (tablets). if orientation == Orientation.LANDSCAPE: co = config.window.landscape else: co = config.window.portrait # remember that we wrote this rect to gsettings self._written_window_rects[orientation] = rect.copy() # write to gsettings and trigger notifications co.settings.delay() co.x, co.y, co.width, co.height = rect co.settings.apply() def write_docking_size(self, orientation, size): co = self.get_orientation_config_object() expand = self.get_dock_expand() # remember that we wrote this rect to gsettings self._written_dock_sizes[orientation] = tuple(size) # write to gsettings and trigger notifications co.settings.delay() if not expand: co.dock_width = size[0] co.dock_height = size[1] co.settings.apply() def get_orientation_config_object(self): orientation = self.get_screen_orientation() if orientation == Orientation.LANDSCAPE: co = config.window.landscape else: co = config.window.portrait return co def on_transition_done(self, visible_before, visible_now): if visible_now: self.assure_on_current_desktop() self.update_docking() def on_screen_size_changed(self, screen): """ Screen rotation, etc. """ if config.is_docking_enabled(): # Can't correctly position the window while struts are active # -> turn them off for a moment self.clear_struts() # Attempt to hide the keyboard now. This won't work that well # as the system doesn't refresh the screen anymore until # after the rotation. self._was_visible = self.is_visible() self._screen_resizing = True keyboard_widget = self.keyboard_widget if keyboard_widget: keyboard_widget.transition_visible_to(False, 0.0) keyboard_widget.commit_transition() WindowRectTracker.on_screen_size_changed(self, screen) def on_screen_size_changed_delayed(self, screen): if config.is_docking_enabled(): self._screen_resizing = False self.reset_monitor_workarea() # The keyboard size may have changed, draw with the new size now, # while it's still in the hideout, so we don't have to watch. self.restore_window_rect() self.keyboard_widget.process_updates() keyboard_widget = self.keyboard_widget if keyboard_widget and self._was_visible: keyboard_widget.transition_visible_to(True, 0.0, 0.4) keyboard_widget.commit_transition() else: self.restore_window_rect() def limit_size(self, rect): """ Limits the given window rect to fit on screen. """ if self.keyboard_widget: return self.keyboard_widget.limit_size(rect) return rect def _emit_quit_onboard(self, event, data=None): self.emit("quit-onboard") def _on_delete_event(self, event, data=None): if config.lockdown.disable_quit: if self.keyboard_widget: return True else: self._emit_quit_onboard(event) def on_docking_notify(self): self.update_docking() self.keyboard_widget.update_resize_handles() def update_docking(self, force_update=False): enable = config.is_docking_enabled() if enable: rect = self.get_dock_rect() else: rect = Rect() shrink = config.window.docking_shrink_workarea edge = config.window.docking_edge expand = self.get_dock_expand() if self._docking_enabled != enable or \ (self._docking_enabled and \ (self._docking_rect != rect or \ self._shrink_work_area != shrink or \ self._dock_expand != expand or \ bool(self._current_struts) != shrink) ): self.enable_docking(enable) self._shrink_work_area = shrink self._dock_expand = expand self._docking_edge = edge self._docking_enabled = enable self._docking_rect = rect def enable_docking(self, enable): if enable: self._set_docking_struts(config.window.docking_shrink_workarea, config.window.docking_edge, self.get_dock_expand()) self.restore_window_rect() # knows about docking else: self.restore_window_rect() self.clear_struts() def clear_struts(self): self._set_docking_struts(False) def _set_docking_struts(self, enable, edge=None, expand=True): if not self.get_realized(): # no window, no xid return win = self.get_window() xid = win.get_xid() # requires GdkX11 import if not enable: self._apply_struts(xid, None) return area, geom = self.get_docking_monitor_rects() root = self.get_rootwin_rect() rect = self.get_dock_rect() top_start_x = top_end_x = 0 bottom_start_x = bottom_end_x = 0 #print("geom", geom, "area", area, "rect", rect) if edge: # Bottom top = 0 bottom = geom.h - area.bottom() + rect.h #bottom = root.h - area.bottom() + rect.h bottom_start_x = rect.left() bottom_end_x = rect.right() else: # Top top = area.top() + rect.h bottom = 0 top_start_x = rect.left() top_end_x = rect.right() struts = [ 0, 0, top, bottom, 0, 0, 0, 0, top_start_x, top_end_x, bottom_start_x, bottom_end_x ] self._apply_struts(xid, struts) def _apply_struts(self, xid, struts=None): if self._current_struts != struts: if struts is None: self._osk_struts.clear(xid) else: self._osk_struts.set(xid, struts) self._current_struts = struts def get_dock_size(self): co = self.get_orientation_config_object() return co.dock_width, co.dock_height def get_dock_expand(self): co = self.get_orientation_config_object() return co.dock_expand def get_dock_rect(self): area, geom = self.get_docking_monitor_rects() edge = config.window.docking_edge width, height = self.get_dock_size() rect = Rect(area.x, 0, area.w, height) if edge: # Bottom rect.y = area.y + area.h - height else: # Top rect.y = area.y expand = self.get_dock_expand() if expand: rect.w = area.w rect.x = area.x else: rect.w = min(width, area.w) rect.x = rect.x + (area.w - rect.w) // 2 return rect def get_docking_hideout_rect(self, reference_rect=None): """ Where the keyboard goes to hide when it slides off-screen. """ area, geom = self.get_docking_monitor_rects() rect = self.get_dock_rect() hideout = rect mcx, mcy = geom.get_center() if reference_rect: cx, cy = reference_rect.get_center() else: cx, cy = rect.get_center() clearance = 10 if cy > mcy: hideout.y = geom.bottom() + clearance # below Bottom else: hideout.y = geom.top() - rect.h - clearance # above Top return hideout def get_docking_monitor_rects(self): screen = self.get_screen() mon = self.get_docking_monitor() area = self._monitor_workarea.get(mon) if area is None: area = self.update_monitor_workarea() geom = screen.get_monitor_geometry(mon) geom = Rect(geom.x, geom.y, geom.width, geom.height) return area, geom def get_docking_monitor(self): screen = self.get_screen() return screen.get_primary_monitor() def reset_monitor_workarea(self): self._monitor_workarea = {} def update_monitor_workarea(self): """ Save the workarea, so we don't have to check all the time if our strut is already installed. """ mon = self.get_docking_monitor() area = self.get_monitor_workarea() self._monitor_workarea[mon] = area return area def get_monitor_workarea(self): screen = self.get_screen() mon = self.get_docking_monitor() area = screen.get_monitor_workarea(mon) area = Rect(area.x, area.y, area.width, area.height) return area @staticmethod def get_rootwin_rect(): rootwin = Gdk.get_default_root_window() return Rect.from_position_size( rootwin.get_position(), (rootwin.get_width(), rootwin.get_height())) def is_override_redirect_mode(self): return config.is_force_to_top() and \ self._wm_quirks.can_set_override_redirect(self) def assure_on_current_desktop(self): """ Make sure the window is visible in the current desktop in OpenBox and perhaps other WMs, except Compiz/Unity. Dbus Show() then makes Onboard appear after switching desktop (LP: 1092166, Raring). """ if self._moved_desktop_switch_count != self._desktop_switch_count: win = self.get_window() if win: win.move_to_current_desktop() self._moved_desktop_switch_count = self._desktop_switch_count
class LayoutPopup(KeyboardPopup, LayoutView, TouchInput): """ Popup showing a (sub-)layout tree. """ IDLE_CLOSE_DELAY = 0 # seconds of inactivity until window closes def __init__(self, keyboard, notify_done_callback): self._layout = None self._notify_done_callback = notify_done_callback self._drag_selected = False # grazed by the pointer? KeyboardPopup.__init__(self) LayoutView.__init__(self, keyboard) TouchInput.__init__(self) self.connect("draw", self._on_draw) self.connect("destroy", self._on_destroy_event) self._close_timer = Timer() self.start_close_timer() def cleanup(self): self.stop_close_timer() # fix label popup staying visible on double click self.keyboard.hide_touch_feedback() LayoutView.cleanup(self) # deregister from keyboard def get_toplevel(self): return self def set_layout(self, layout, frame_width): self._layout = layout self._frame_width = frame_width self.update_labels() # set window size layout_canvas_rect = layout.get_canvas_border_rect() canvas_rect = layout_canvas_rect.inflate(frame_width) w, h = canvas_rect.get_size() self.set_default_size(w + 1, h + 1) def get_layout(self): return self._layout def get_frame_width(self): return self._frame_width def got_motion(self): """ Has the pointer ever entered the popup? """ return self._drag_selected def handle_realize_event(self): self.set_override_redirect(True) super(LayoutPopup, self).handle_realize_event() def _on_destroy_event(self, user_data): self.cleanup() def on_enter_notify(self, widget, event): self.stop_close_timer() def on_leave_notify(self, widget, event): self.start_close_timer() def on_input_sequence_begin(self, sequence): self.stop_close_timer() key = self.get_key_at_location(sequence.point) if key: sequence.active_key = key self.keyboard.key_down(key, self, sequence) def on_input_sequence_update(self, sequence): if sequence.state & BUTTON123_MASK: key = self.get_key_at_location(sequence.point) # drag-select new active key active_key = sequence.active_key if not active_key is key and \ (active_key is None or not active_key.activated): sequence.active_key = key self.keyboard.key_up(active_key, self, sequence, False) self.keyboard.key_down(key, self, sequence, False) self._drag_selected = True def on_input_sequence_end(self, sequence): key = sequence.active_key if key: keyboard = self.keyboard keyboard.key_up(key, self, sequence) if key and \ not self._drag_selected: Timer(config.UNPRESS_DELAY, self.close_window) else: self.close_window() def _on_draw(self, widget, context): decorated = LayoutView.draw(self, widget, context) def draw_window_frame(self, context, lod): corner_radius = config.CORNER_RADIUS border_rgba = self.get_popup_window_rgba("border") alpha = border_rgba[3] colors = [ [[0.5, 0.5, 0.5, alpha], 0, 1], [border_rgba, 1.5, 2.0], ] rect = Rect(0, 0, self.get_allocated_width(), self.get_allocated_height()) for rgba, pos, width in colors: r = rect.deflate(width) roundrect_arc(context, r, corner_radius) context.set_line_width(width) context.set_source_rgba(*rgba) context.stroke() def close_window(self): self._notify_done_callback() def start_close_timer(self): if self.IDLE_CLOSE_DELAY: self._close_timer.start(self.IDLE_CLOSE_DELAY, self.close_window) def stop_close_timer(self): self._close_timer.stop()
class KeyboardGTK(Gtk.DrawingArea, WindowManipulator): def __init__(self): Gtk.DrawingArea.__init__(self) WindowManipulator.__init__(self) self.active_key = None self._active_event_type = None self._last_click_time = 0 self._last_click_key = None self._outside_click_timer = Timer() self._outside_click_detected = False self._outside_click_start_time = None self._long_press_timer = Timer() self._auto_release_timer = AutoReleaseTimer(self) self.dwell_timer = None self.dwell_key = None self.last_dwelled_key = None self._window_fade = FadeTimer() self._last_transition = None self.inactivity_timer = InactivityTimer(self) self.auto_show = AtspiAutoShow(self) self.auto_show.enable(config.is_auto_show_enabled()) self.touch_handles = TouchHandles() self.touch_handles_hide_timer = Timer() self.touch_handles_fade = FadeTimer() self.touch_handles_auto_hide = True self._aspect_ratio = None self._first_draw = True # self.set_double_buffered(False) self.set_app_paintable(True) # no tooltips when embedding, gnome-screen-saver flickers (Oneiric) if not config.xid_mode: self.set_has_tooltip(True) # works only at window creation -> always on self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK | Gdk.EventMask.ENTER_NOTIFY_MASK ) self.connect("parent-set", self._on_parent_set) self.connect("draw", self._on_draw) self.connect("button-press-event", self._on_mouse_button_press) self.connect("button_release_event", self._on_mouse_button_release) self.connect("motion-notify-event", self._on_motion) self.connect("query-tooltip", self._on_query_tooltip) self.connect("enter-notify-event", self._on_mouse_enter) self.connect("leave-notify-event", self._on_mouse_leave) self.connect("configure-event", self._on_configure_event) self.update_resize_handles() self.show() def initial_update(self): pass def _on_parent_set(self, widget, old_parent): win = self.get_kbd_window() if win: self.touch_handles.set_window(win) def cleanup(self): # stop timer callbacks for unused, but not yet destructed keyboards self.touch_handles_fade.stop() self.touch_handles_hide_timer.stop() self._window_fade.stop() self.inactivity_timer.stop() self._long_press_timer.stop() self._auto_release_timer.stop() self.auto_show.cleanup() self.stop_click_polling() def set_startup_visibility(self): win = self.get_kbd_window() assert(win) # Show the keyboard when turning off auto-show. # Hide the keyboard when turning on auto-show. # (Fix this when we know how to get the active accessible) # Hide the keyboard on start when start-minimized is set. # Start with active transparency if the inactivity_timer is enabled. # # start_minimized False True False True # auto_show False False True True # -------------------------------------------------- # window visible on start True False False False # window visible later True True False False if config.xid_mode: win.set_visible(True) # simply show the window else: # determine the initial transition if config.is_auto_show_enabled(): transition = Transition.AUTO_HIDE else: if config.is_visible_on_start(): if self.inactivity_timer.is_enabled(): transition = Transition.ACTIVATE else: transition = Transition.SHOW else: transition = Transition.HIDE # transition to initial opacity if win.supports_alpha: win.set_opacity(0.0) # fade in from full transparency self.begin_transition(transition, 0.2) # kick off inactivity timer, i.e. DEACTIVATE on timeout if transition == Transition.ACTIVATE: self.inactivity_timer.begin_transition(False) # Be sure to show/hide window and icon palette if transition in [Transition.SHOW, Transition.AUTO_SHOW, Transition.ACTIVATE]: win.set_visible(True) else: win.set_visible(False) def update_resize_handles(self): """ Tell WindowManipulator about the active resize handles """ self.set_drag_handles(config.window.resize_handles) def update_auto_show(self): """ Turn on/off auto-show and show/hide the window accordingly. """ enable = config.is_auto_show_enabled() self.auto_show.enable(enable) self.auto_show.set_visible(not enable) def update_transparency(self): self.begin_transition(Transition.ACTIVATE) if self.inactivity_timer.is_enabled(): self.inactivity_timer.begin_transition(False) else: self.inactivity_timer.stop() self.redraw() # for background transparency def update_inactive_transparency(self): if self.inactivity_timer.is_enabled(): self.begin_transition(Transition.DEACTIVATE) def get_transition_target_opacity(self, transition): transparency = 0 if transition in [Transition.ACTIVATE]: transparency = config.window.transparency elif transition in [Transition.SHOW, Transition.AUTO_SHOW]: if not self.inactivity_timer.is_enabled() or \ self.inactivity_timer.is_active(): transparency = config.window.transparency else: transparency = config.window.inactive_transparency elif transition in [Transition.HIDE, Transition.AUTO_HIDE]: transparency = 100 elif transition == Transition.DEACTIVATE: transparency = config.window.inactive_transparency return 1.0 - transparency / 100.0 def begin_transition(self, transition, duration = None): """ Start the transition to a different opacity """ window = self.get_kbd_window() if window: _duration = 0.3 if transition in [Transition.SHOW, Transition.HIDE, Transition.AUTO_HIDE, Transition.AUTO_SHOW, Transition.ACTIVATE]: _duration = 0.15 if duration is None: duration = _duration if transition in [Transition.SHOW, Transition.AUTO_SHOW]: if not window.is_visible(): window.set_visible(True) start_opacity = window.get_opacity() target_opacity = self.get_transition_target_opacity(transition) _logger.debug("begin opacity transition: {} to {}" \ .format(start_opacity, target_opacity)) # no fade delay for screens that can't fade (unity-2d) # Don't fade again when the target opacity has already # been reached. screen = window.get_screen() if screen and not screen.is_composited() or \ self._last_transition == transition and \ start_opacity == target_opacity: if transition in [Transition.HIDE, Transition.AUTO_HIDE]: window.set_visible(False) else: self._last_transition = transition self._window_fade.fade_to(start_opacity, target_opacity, duration, self._on_opacity_step, transition) def _on_opacity_step(self, opacity, done, transition): window = self.get_kbd_window() if window: window.set_opacity(opacity) if done: if transition in [Transition.HIDE, Transition.AUTO_HIDE]: window.set_visible(False) def toggle_visible(self): """ main method to show/hide onboard manually""" window = self.get_kbd_window() visible = not window.is_visible() if window else False self.set_user_visible(visible) def set_user_visible(self, visible): """ main method to show/hide onboard manually""" self.lock_auto_show_visible(visible) self.set_visible(visible) def set_visible(self, visible): """ Start show/hide transition. """ window = self.get_kbd_window() if window: if visible: self.begin_transition(Transition.SHOW) else: self.begin_transition(Transition.HIDE) def lock_auto_show_visible(self, visible): """ If the user unhides onboard, don't auto-hide it until he manually hides it again. """ if config.is_auto_show_enabled(): self.auto_show.lock_visible(visible) def start_click_polling(self): if self.has_latched_sticky_keys(): self._outside_click_timer.start(0.01, self._on_click_timer) self._outside_click_detected = False self._outside_click_start_time = time.time() def stop_click_polling(self): self._outside_click_timer.stop() def _on_click_timer(self): """ poll for mouse click outside of onboards window """ rootwin = Gdk.get_default_root_window() dunno, x, y, mask = rootwin.get_pointer() if mask & (Gdk.ModifierType.BUTTON1_MASK | Gdk.ModifierType.BUTTON2_MASK | Gdk.ModifierType.BUTTON3_MASK): self._outside_click_detected = True elif self._outside_click_detected: # button released anywhere outside of onboards control self.stop_click_polling() self.on_outside_click() return False # stop after 30 seconds if time.time() - self._outside_click_start_time > 30.0: self.stop_click_polling() self.on_cancel_outside_click() return False return True def get_drag_window(self): """ Overload for WindowManipulator """ return self.get_kbd_window() def get_drag_threshold(self): """ Overload for WindowManipulator """ return config.get_drag_threshold() def on_drag_initiated(self): """ Overload for WindowManipulator """ window = self.get_drag_window() if window: window.on_user_positioning_begin() def on_drag_done(self): """ Overload for WindowManipulator """ window = self.get_drag_window() if window: window.on_user_positioning_done() def get_always_visible_rect(self): """ Returns the bounding rectangle of all move buttons in canvas coordinates. Overload for WindowManipulator """ keys = self.find_keys_from_ids(["move"]) bounds = None for key in keys: r = key.get_canvas_border_rect() if not bounds: bounds = r else: bounds = bounds.union(r) return bounds def _on_configure_event(self, widget, user_data): self.update_layout() self.update_font_sizes() self.touch_handles.update_positions(self.canvas_rect) def _on_mouse_enter(self, widget, event): # ignore event if a mouse button is held down # we get the event once the button is released if event.state & (Gdk.ModifierType.BUTTON1_MASK | Gdk.ModifierType.BUTTON2_MASK | Gdk.ModifierType.BUTTON3_MASK): return # stop inactivity timer if self.inactivity_timer.is_enabled(): self.inactivity_timer.begin_transition(True) # stop click polling self.stop_click_polling() # Force into view for WindowManipulator's system drag mode. #if not config.xid_mode and \ # not config.window.window_decoration and \ # not config.window.force_to_top: # GObject.idle_add(self.force_into_view) def _on_mouse_leave(self, widget, event): # ignore event if a mouse button is held down # we get the event once the button is released if event.state & (Gdk.ModifierType.BUTTON1_MASK | Gdk.ModifierType.BUTTON2_MASK | Gdk.ModifierType.BUTTON3_MASK): return # start a timer to detect clicks outside of onboard self.start_click_polling() # start inactivity timer if self.inactivity_timer.is_enabled(): self.inactivity_timer.begin_transition(False) self.stop_dwelling() self.reset_touch_handles() def _on_motion(self, widget, event): point = (event.x, event.y) hit_key = None # hit-test touch handles first hit_handle = None if self.touch_handles.active: hit_handle = self.touch_handles.hit_test(point) self.touch_handles.set_prelight(hit_handle) # hit-test keys if hit_handle is None: hit_key = self.get_key_at_location(point) if event.state & (Gdk.ModifierType.BUTTON1_MASK | Gdk.ModifierType.BUTTON2_MASK | Gdk.ModifierType.BUTTON3_MASK): # move/resize self.handle_motion(event, fallback = True) # stop long press when drag threshold has been overcome if self.is_drag_active(): self.stop_long_press() else: if not hit_handle is None: # handle hovered over -> extend its visible time self.start_touch_handles_auto_show() # start dwelling if we have entered a dwell-enabled key if hit_key and \ hit_key.sensitive and \ not self.is_dwelling() and \ not self.already_dwelled(hit_key) and \ not config.scanner.enabled: controller = self.button_controllers.get(hit_key) if controller and controller.can_dwell(): self.start_dwelling(hit_key) self.do_set_cursor_at(point, hit_key) # cancel dwelling when the hit key changes if self.dwell_key and self.dwell_key != hit_key or \ self.last_dwelled_key and self.last_dwelled_key != hit_key: self.cancel_dwelling() def do_set_cursor_at(self, point, hit_key = None): """ Set/reset the cursor for frame resize handles """ if not config.xid_mode: allow_drag_cursors = not config.has_window_decoration() and \ not hit_key self.set_drag_cursor_at(point, allow_drag_cursors) def _on_mouse_button_press(self, widget, event): self.stop_click_polling() self.stop_dwelling() key = None point = (event.x, event.y) if event.type == Gdk.EventType.BUTTON_PRESS: # hit-test touch handles first hit_handle = None if self.touch_handles.active: hit_handle = self.touch_handles.hit_test(point) self.touch_handles.set_pressed(hit_handle) if not hit_handle is None: # handle clicked -> stop auto-show until button release self.stop_touch_handles_auto_show() else: # no handle clicked -> hide them now self.show_touch_handles(False) # hit-test keys if hit_handle is None: key = self.get_key_at_location(point) # enable/disable the drag threshold if not hit_handle is None: self.enable_drag_protection(False) elif key and key.id == "move": # Move key needs to support long press; # always use the drag threshold. self.enable_drag_protection(True) self.reset_drag_protection() else: self.enable_drag_protection(config.drag_protection) # handle resizing if not key and \ not config.has_window_decoration() and \ not config.xid_mode: if self.handle_press(event): return True # bail if we are in scanning mode if config.scanner.enabled: return True # press the key self.active_key = key if key: double_click_time = Gtk.Settings.get_default() \ .get_property("gtk-double-click-time") # single click? if self._last_click_key != key or \ event.time - self._last_click_time > double_click_time: self.press_key(key, event.button) # start long press detection controller = self.button_controllers.get(key) if controller and controller.can_long_press(): self._long_press_timer.start(1.0, self._on_long_press, key, event.button) # double click? else: self.press_key(key, event.button, EventType.DOUBLE_CLICK) self._last_click_key = key self._last_click_time = event.time return True def _on_long_press(self, key, button): controller = self.button_controllers.get(key) controller.long_press(button) def stop_long_press(self): self._long_press_timer.stop() def _on_mouse_button_release(self, widget, event): if not config.scanner.enabled: self.release_active_key() self.stop_drag() self._long_press_timer.stop() # reset cursor when there was no cursor motion point = (event.x, event.y) hit_key = self.get_key_at_location(point) self.do_set_cursor_at(point, hit_key) # reset touch handles self.reset_touch_handles() self.start_touch_handles_auto_show() def press_key(self, key, button = 1, event_type = EventType.CLICK): Keyboard.press_key(self, key, button, event_type) self._auto_release_timer.start() self._active_event_type = event_type def release_key(self, key, button = 1, event_type = None): if event_type is None: event_type = self._active_event_type Keyboard.release_key(self, key, button, event_type) self._active_event_type = None def is_dwelling(self): return not self.dwell_key is None def already_dwelled(self, key): return self.last_dwelled_key is key def start_dwelling(self, key): self.cancel_dwelling() self.dwell_key = key self.last_dwelled_key = key key.start_dwelling() self.dwell_timer = GObject.timeout_add(50, self._on_dwell_timer) def cancel_dwelling(self): self.stop_dwelling() self.last_dwelled_key = None def stop_dwelling(self): if self.dwell_timer: GObject.source_remove(self.dwell_timer) self.dwell_timer = None self.redraw([self.dwell_key]) self.dwell_key.stop_dwelling() self.dwell_key = None def _on_dwell_timer(self): if self.dwell_key: self.redraw([self.dwell_key]) if self.dwell_key.is_done(): key = self.dwell_key self.stop_dwelling() self.press_key(key, 0, EventType.DWELL) self.release_key(key, 0, EventType.DWELL) return False return True def release_active_key(self): if self.active_key: self.release_key(self.active_key) self.active_key = None return True def _on_query_tooltip(self, widget, x, y, keyboard_mode, tooltip): if config.show_tooltips and \ not self.is_drag_initiated(): key = self.get_key_at_location((x, y)) if key: if key.tooltip: r = Gdk.Rectangle() r.x, r.y, r.width, r.height = key.get_canvas_rect() tooltip.set_tip_area(r) # no effect in oneiric? tooltip.set_text(_(key.tooltip)) return True return False def _on_draw(self, widget, context): #_logger.debug("Draw: clip_extents=" + str(context.clip_extents())) #self.get_window().set_debug_updates(True) if not Gtk.cairo_should_draw_window(context, self.get_window()): return clip_rect = Rect.from_extents(*context.clip_extents()) # draw background decorated = self.draw_background(context) # On first run quickly overwrite the background only. # This gives a slightly smoother startup with desktop remnants # flashing though for a shorter time. if self._first_draw: self._first_draw = False self.queue_draw() return if not self.layout: return # run through all visible layout items layer_ids = self.layout.get_layer_ids() for item in self.layout.iter_visible_items(): if item.layer_id: # draw layer background layer_index = layer_ids.index(item.layer_id) parent = item.parent if parent and \ layer_index != 0: rect = parent.get_canvas_rect() context.rectangle(*rect.inflate(1)) if self.color_scheme: rgba = self.color_scheme.get_layer_fill_rgba(layer_index) else: rgba = [0.5, 0.5, 0.5, 0.9] context.set_source_rgba(*rgba) context.fill() self.draw_dish_key_background(context, 1.0, item.layer_id) # draw key if item.is_key() and \ clip_rect.intersects(item.get_canvas_rect()): item.draw(context) item.draw_image(context) item.draw_label(context) # draw touch handles (enlarged move and resize handles) if self.touch_handles.active: corner_radius = config.CORNER_RADIUS if decorated else 0 self.touch_handles.set_corner_radius(corner_radius) self.touch_handles.draw(context) def show_touch_handles(self, show, auto_hide = True): """ Show/hide the enlarged resize/move handels. Initiates an opacity fade. """ if show and config.lockdown.disable_touch_handles: return if show: self.touch_handles.set_prelight(None) self.touch_handles.set_pressed(None) self.touch_handles.active = True self.touch_handles_auto_hide = auto_hide start, end = 0.0, 1.0 else: self.stop_touch_handles_auto_show() start, end = 1.0, 0.0 if self.touch_handles_fade.target_value != end: self.touch_handles_fade.time_step = 0.025 self.touch_handles_fade.fade_to(start, end, 0.2, self._on_touch_handles_opacity) def reset_touch_handles(self): if self.touch_handles.active: self.touch_handles.set_prelight(None) self.touch_handles.set_pressed(None) def start_touch_handles_auto_show(self): """ (re-) starts the timer to hide touch handles """ if self.touch_handles.active and self.touch_handles_auto_hide: self.touch_handles_hide_timer.start(3.5, self.show_touch_handles, False) def stop_touch_handles_auto_show(self): """ stops the timer to hide touch handles """ self.touch_handles_hide_timer.stop() def _on_touch_handles_opacity(self, opacity, done): if done and opacity < 0.1: self.touch_handles.active = False self.touch_handles.opacity = opacity # Convoluted workaround for a weird cairo glitch (Precise). # When queuing all handles for drawing, the background only # under the move handle is clipped and remains transparent. # -> Fade with double frequency and queue some handles # for drawing only every other time. if 0: self.touch_handles.redraw() else: for handle in self.touch_handles.handles: if bool(self.touch_handles_fade.iteration & 1) != \ (handle.id in [Handle.MOVE, Handle.NORTH, Handle.SOUTH]): handle.redraw() if done: GObject.idle_add(self._on_touch_handles_opacity, 1.0, False) def hit_test_move_resize(self, point): hit = self.touch_handles.hit_test(point) if hit is None: hit = WindowManipulator.hit_test_move_resize(self, point) return hit def draw_background(self, context): """ Draw keyboard background """ win = self.get_kbd_window() decorated = False if config.xid_mode: # xembed mode # Disable transparency in lightdm and g-s-s for now. # There are too many issues and there is no real # visual improvement. if False and \ win.supports_alpha: self.clear_background(context) decorated = True self.draw_transparent_background(context, decorated) else: self.draw_plain_background(context) elif config.has_window_decoration(): # decorated window if win.supports_alpha and \ config.window.transparent_background: self.clear_background(context) else: self.draw_plain_background(context) else: # undecorated window if win.supports_alpha: self.clear_background(context) if not config.window.transparent_background: decorated = True self.draw_transparent_background(context, decorated) else: self.draw_plain_background(context) return decorated def clear_background(self, context): """ Clear the whole gtk background. Makes the whole strut transparent in xembed mode. """ context.save() context.set_operator(cairo.OPERATOR_CLEAR) context.paint() context.restore() def get_layer_fill_rgba(self, layer_index): if self.color_scheme: return self.color_scheme.get_layer_fill_rgba(layer_index) else: return [0.5, 0.5, 0.5, 1.0] def get_background_rgba(self): """ layer 0 color * background_transparency """ layer0_rgba = self.get_layer_fill_rgba(0) background_alpha = 1.0 - config.window.background_transparency / 100.0 background_alpha *= layer0_rgba[3] return layer0_rgba[:3] + [background_alpha] def draw_transparent_background(self, context, decorated = True): """ fill with the transparent background color """ rgba = self.get_background_rgba() context.set_source_rgba(*rgba) # draw on the potentially aspect-corrected frame around the layout rect = self.layout.get_canvas_border_rect() rect = rect.inflate(config.get_frame_width()) corner_radius = config.CORNER_RADIUS if decorated: roundrect_arc(context, rect, corner_radius) else: context.rectangle(*rect) context.fill() if decorated: # inner decoration line line_rect = rect.deflate(1) roundrect_arc(context, line_rect, corner_radius) context.stroke() self.draw_dish_key_background(context, rgba[3]) def draw_plain_background(self, context, layer_index = 0): """ fill with plain layer 0 color; no alpha support required """ rgba = self.get_layer_fill_rgba(layer_index) context.set_source_rgba(*rgba) context.paint() self.draw_dish_key_background(context) def draw_dish_key_background(self, context, alpha = 1.0, layer_id = None): """ Black background following the contours of key clusters to simulate the opening in the keyboard plane. """ if config.theme_settings.key_style == "dish": context.push_group() context.set_source_rgba(0, 0, 0, 1) enlargement = self.layout.context.scale_log_to_canvas((0.8, 0.8)) corner_radius = self.layout.context.scale_log_to_canvas_x(2.4) if layer_id is None: generator = self.layout.iter_visible_items() else: generator = self.layout.iter_layer_items(layer_id) for item in generator: if item.is_key(): rect = item.get_canvas_fullsize_rect() rect = rect.inflate(*enlargement) roundrect_curve(context, rect, corner_radius) context.fill() context.pop_group_to_source() context.paint_with_alpha(alpha); def _on_mods_changed(self): _logger.info("Modifiers have been changed") self.update_font_sizes() def redraw(self, keys = None): """ Queue redrawing for individual keys or the whole keyboard. """ if keys: area = None for key in keys: rect = key.context.log_to_canvas_rect(key.get_border_rect()) area = area.union(rect) if area else rect area = area.inflate(2.0) # account for stroke width, anti-aliasing self.queue_draw_area(*area) else: self.queue_draw() def update_font_sizes(self): """ Cycles through each group of keys and set each key's label font size to the maximum possible for that group. """ context = self.create_pango_context() for keys in list(self.layout.get_key_groups().values()): max_size = 0 for key in keys: key.configure_label(self.mods) best_size = key.get_best_font_size(context) if best_size: if not max_size or best_size < max_size: max_size = best_size for key in keys: key.font_size = max_size def emit_quit_onboard(self, data=None): _logger.debug("Entered emit_quit_onboard") self.get_kbd_window().emit("quit-onboard") def get_kbd_window(self): return self.get_parent() def get_click_type_button_rects(self): """ Returns bounding rectangles of all click type buttons in root window coordinates. """ keys = self.find_keys_from_ids(["singleclick", "secondaryclick", "middleclick", "doubleclick", "dragclick"]) rects = [] for key in keys: r = key.get_canvas_border_rect() x0, y0 = self.get_window().get_root_coords(r.x, r.y) x1, y1 = self.get_window().get_root_coords(r.x + r.w, r.y + r.h) rects.append((x0, y0, x1 - x0, y1 -y0)) return rects def on_layout_updated(self): # experimental support for keeping window aspect ratio # Currently, in Oneiric, neither lightdm, nor gnome-screen-saver # appear to honor these hints. aspect_ratio = None if config.is_keep_aspect_ratio_enabled(): log_rect = self.layout.get_border_rect() aspect_ratio = log_rect.w / float(log_rect.h) aspect_ratio = self.layout.get_log_aspect_ratio() if self._aspect_ratio != aspect_ratio: window = self.get_kbd_window() if window: geom = Gdk.Geometry() if aspect_ratio is None: window.set_geometry_hints(self, geom, 0) else: geom.min_aspect = geom.max_aspect = aspect_ratio window.set_geometry_hints(self, geom, Gdk.WindowHints.ASPECT) self._aspect_ratio = aspect_ratio def refresh_pango_layouts(self): """ When the systems font dpi setting changes our pango layout object, it still caches the old setting, leading to wrong font scaling. Refresh the pango layout object. """ _logger.info(_("Refreshing pango layout, new font dpi setting is '{}'") \ .format(Gtk.Settings.get_default().get_property("gtk-xft-dpi"))) Key.reset_pango_layout()
def __init__(self, keyboard_widget): self._keyboard_widget = keyboard_widget self._auto_show_timer = Timer() self._thaw_timer = Timer() self._active_accessible = None
def __init__(self): Gtk.DrawingArea.__init__(self) WindowManipulator.__init__(self) self.active_key = None self._active_event_type = None self._last_click_time = 0 self._last_click_key = None self._outside_click_timer = Timer() self._outside_click_detected = False self._outside_click_start_time = None self._long_press_timer = Timer() self._auto_release_timer = AutoReleaseTimer(self) self.dwell_timer = None self.dwell_key = None self.last_dwelled_key = None self._window_fade = FadeTimer() self._last_transition = None self.inactivity_timer = InactivityTimer(self) self.auto_show = AtspiAutoShow(self) self.auto_show.enable(config.is_auto_show_enabled()) self.touch_handles = TouchHandles() self.touch_handles_hide_timer = Timer() self.touch_handles_fade = FadeTimer() self.touch_handles_auto_hide = True self._aspect_ratio = None self._first_draw = True # self.set_double_buffered(False) self.set_app_paintable(True) # no tooltips when embedding, gnome-screen-saver flickers (Oneiric) if not config.xid_mode: self.set_has_tooltip(True) # works only at window creation -> always on self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK | Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK | Gdk.EventMask.ENTER_NOTIFY_MASK ) self.connect("parent-set", self._on_parent_set) self.connect("draw", self._on_draw) self.connect("button-press-event", self._on_mouse_button_press) self.connect("button_release_event", self._on_mouse_button_release) self.connect("motion-notify-event", self._on_motion) self.connect("query-tooltip", self._on_query_tooltip) self.connect("enter-notify-event", self._on_mouse_enter) self.connect("leave-notify-event", self._on_mouse_leave) self.connect("configure-event", self._on_configure_event) self.update_resize_handles() self.show()
class AutoShow(object): """ Auto-show and hide Onboard. """ # Delay from the last focus event until the keyboard is shown/hidden. # Raise it to reduce unnecessary transitions (flickering). # Lower it for more immediate reactions. SHOW_REACTION_TIME = 0.0 HIDE_REACTION_TIME = 0.3 _lock_visible = False _frozen = False _keyboard_widget = None _state_tracker = AtspiStateTracker() def __init__(self, keyboard_widget): self._keyboard_widget = keyboard_widget self._auto_show_timer = Timer() self._thaw_timer = Timer() self._active_accessible = None def cleanup(self): self._auto_show_timer.stop() self._thaw_timer.stop() def enable(self, enable): if enable: self._state_tracker.connect("text-entry-activated", self._on_text_entry_activated) self._state_tracker.connect("text-caret-moved", self._on_text_caret_moved) else: self._state_tracker.disconnect("text-entry-activated", self._on_text_entry_activated) self._state_tracker.disconnect("text-caret-moved", self._on_text_caret_moved) if enable: self._lock_visible = False self._frozen = False def is_frozen(self): return self._frozen def freeze(self, thaw_time=None): """ Stop showing and hiding the keyboard window. thaw_time in seconds, None to freeze forever. """ self._frozen = True self._thaw_timer.stop() if not thaw_time is None: self._thaw_timer.start(thaw_time, self._on_thaw) # Discard pending hide/show actions. self._auto_show_timer.stop() def thaw(self, thaw_time=None): """ Allow hiding and showing the keyboard window again. thaw_time in seconds, None to thaw immediately. """ self._thaw_timer.stop() if thaw_time is None: self._thaw() else: self._thaw_timer.start(thaw_time, self._on_thaw) def _on_thaw(self): self._thaw_timer.stop() self._frozen = False return False def lock_visible(self, lock, thaw_time=1.0): """ Lock window permanetly visible in response to the user showing it. Optionally freeze hiding/showing for a limited time. """ # Permanently lock visible. self._lock_visible = lock # Temporarily stop showing/hiding. if thaw_time: self.freeze(thaw_time) # Leave the window in its current state, # discard pending hide/show actions. self._auto_show_timer.stop() # Stop pending auto-repositioning if lock: window = self._keyboard_widget.get_kbd_window() if window: window.stop_auto_position() def _on_text_caret_moved(self, event): """ Show the keyboard on click of an already focused text entry (LP: 1078602). Do this only for single line text entries to still allow clicking longer documents without having onboard show up. """ if config.auto_show.enabled and \ not self._keyboard_widget.is_visible(): accessible = self._active_accessible if accessible: if self._state_tracker.is_single_line(): self._on_text_entry_activated(accessible) def _on_text_entry_activated(self, accessible): window = self._keyboard_widget.get_kbd_window() self._active_accessible = accessible active = bool(accessible) # show/hide the keyboard window if not active is None: # Always allow to show the window even when locked. # Mitigates right click on unity-2d launcher hiding # onboard before _lock_visible is set (Precise). if self._lock_visible: active = True if not self.is_frozen(): self.show_keyboard(active) # The active accessible changed, stop trying to # track the position of the previous one. # -> less erratic movement during quick focus changes if window: window.stop_auto_position() # reposition the keyboard window if active and \ not accessible is None and \ not self._lock_visible and \ not self.is_frozen(): if window: window.auto_position() def show_keyboard(self, show): """ Begin AUTO_SHOW or AUTO_HIDE transition """ # Don't act on each and every focus message. Delay the start # of the transition slightly so that only the last of a bunch of # focus messages is acted on. delay = self.SHOW_REACTION_TIME if show else \ self.HIDE_REACTION_TIME self._auto_show_timer.start(delay, self._begin_transition, show) def _begin_transition(self, show): self._keyboard_widget.transition_visible_to(show) self._keyboard_widget.commit_transition() return False def get_repositioned_window_rect(self, home, limit_rects, test_clearance, move_clearance, horizontal=True, vertical=True): """ Get the alternative window rect suggested by auto-show or None if no repositioning is required. """ accessible = self._active_accessible if accessible: rect = self._state_tracker.get_accessible_extents(accessible) if not rect.is_empty() and \ not self._lock_visible: return self._get_window_rect_for_accessible_rect( \ home, rect, limit_rects, test_clearance, move_clearance, horizontal, vertical) return None def _get_window_rect_for_accessible_rect(self, home, rect, limit_rects, test_clearance, move_clearance, horizontal=True, vertical=True): """ Find new window position based on the screen rect of the accessible. """ mode = "nooverlap" x = y = None if mode == "closest": x, y = rect.left(), rect.bottom() if mode == "nooverlap": x, y = self._find_non_occluding_position(home, rect, limit_rects, test_clearance, move_clearance, horizontal, vertical) if not x is None: return Rect(x, y, home.w, home.h) else: return None def _find_non_occluding_position(self, home, acc_rect, limit_rects, test_clearance, move_clearance, horizontal=True, vertical=True): # The home_rect doesn't include window decoration, # make sure to add decoration for correct clearance. rh = home.copy() window = self._keyboard_widget.get_kbd_window() if window: offset = window.get_client_offset() rh.w += offset[0] rh.h += offset[1] # Leave some clearance around the accessible to account for # window frames and position errors of firefox entries. ra = acc_rect.apply_border(*test_clearance) if rh.intersects(ra): # Leave a different clearance for the new to be found positions. ra = acc_rect.apply_border(*move_clearance) x, y = rh.get_position() # candidate positions vp = [] if horizontal: vp.append([ra.left() - rh.w, y]) vp.append([ra.right(), y]) if vertical: vp.append([x, ra.top() - rh.h]) vp.append([x, ra.bottom()]) # limited, non-intersecting candidate rectangles vr = [] for p in vp: pl = self._keyboard_widget.limit_position( p[0], p[1], self._keyboard_widget.canvas_rect, limit_rects) r = Rect(pl[0], pl[1], rh.w, rh.h) if not r.intersects(ra): vr.append(r) # candidate with smallest center-to-center distance wins chx, chy = rh.get_center() dmin = None rmin = None for r in vr: cx, cy = r.get_center() dx, dy = cx - chx, cy - chy d2 = dx * dx + dy * dy if dmin is None or dmin > d2: dmin = d2 rmin = r if not rmin is None: return rmin.get_position() return None, None
def start(self): self.stop() delay = config.keyboard.sticky_key_release_delay if delay: Timer.start(self, delay)
def reset(self): Timer.stop(self) self.draw_unpressed()
class AtspiAutoShow(object): """ Auto-show and hide Onboard based on at-spi focus events. """ # Delay from the last focus event until the keyboard is shown/hidden. # Raise it to reduce unnecessary transitions (flickering). # Lower it for more immediate reactions. SHOW_REACTION_TIME = 0.0 HIDE_REACTION_TIME = 0.3 _atspi_listeners_registered = False _focused_accessible = None _lock_visible = False _keyboard = None def __init__(self, keyboard): self._keyboard = keyboard self._auto_show_timer = Timer() def cleanup(self): self._register_atspi_listeners(False) def enable(self, enable): self._register_atspi_listeners(enable) if enable: self._lock_visible = False def lock_visible(self, lock): self._lock_visible = lock def set_visible(self, visible): """ Begin AUTO_SHOW or AUTO_HIDE transition """ # Don't act on each and every focus message. Delay the start # of the transition slightly so that only the last of a bunch of # focus messages is acted on. delay = self.SHOW_REACTION_TIME if visible else \ self.HIDE_REACTION_TIME self._auto_show_timer.start(delay, self._begin_transition, visible) def _register_atspi_listeners(self, register = True): if not "Atspi" in globals(): return if register: if not self._atspi_listeners_registered: Atspi.EventListener.register_no_data(self._on_atspi_global_focus, "focus") Atspi.EventListener.register_no_data(self._on_atspi_object_focus, "object:state-changed:focused") self._atspi_listeners_registered = True else: if self._atspi_listeners_registered: Atspi.EventListener.deregister_no_data(self._on_atspi_global_focus, "focus") Atspi.EventListener.deregister_no_data(self._on_atspi_object_focus, "object:state-changed:focused") self._atspi_listeners_registered = False def _on_atspi_global_focus(self, event): self._on_atspi_focus(event, True) def _on_atspi_object_focus(self, event): self._on_atspi_focus(event) def _on_atspi_focus(self, event, focus_received = False): if config.auto_show.enabled: accessible = event.source self._log_accessible(accessible) if accessible: focused = focus_received or event.detail1 # received focus? editable = self._is_accessible_editable(accessible) visible = focused and editable show = visible if focused: self._focused_accessible = accessible elif not focused and self._focused_accessible == accessible: self._focused_accessible = None else: show = None # show/hide the window if not show is None: # Always allow to show the window even when locked. # Mitigates right clicking unity-2d launcher hiding # onboard before _lock_visible is set (Precise). if self._lock_visible and show == False: show = True self.set_visible(show) # reposition the keyboard window if show and self._focused_accessible: self.update_position() def _begin_transition(self, show): if show: self._keyboard.begin_transition(Transition.AUTO_SHOW) else: self._keyboard.begin_transition(Transition.AUTO_HIDE) return False def update_position(self): window = self._keyboard.get_kbd_window() if window: rect = self.get_repositioned_window_rect(window.home_rect) if rect is None: # move back home rect = window.home_rect # remember rects to distimguish from user move/resize window.remember_rect(rect) if window.get_position() != rect.get_position(): window.move(rect.x, rect.y) def get_repositioned_window_rect(self, home): """ Get the alternative window rect suggested by auto-show or None if no repositioning is required. """ accessible = self._focused_accessible if accessible: try: ext = accessible.get_extents(Atspi.CoordType.SCREEN) except: # private exception gi._glib.GError when # right clicking onboards unity2d launcher (Precise) _logger.info("AtspiAutoHide: Invalid accessible," " failed to get extents") return None rect = Rect(ext.x, ext.y, ext.width, ext.height) if not rect.is_empty() and \ not self._lock_visible: return self._get_window_rect_for_accessible_rect(home, rect) return None def _get_window_rect_for_accessible_rect(self, home, rect): """ Find new window position based on the screen rect of the accessible. """ mode = "nooverlap" x = y = None if mode == "closest": x, y = rect.left(), rect.bottom() # x, y = self._keyboard.limit_position(x, y, self._keyboard.canvas_rect) if mode == "vertical": x, y = home.left(), rect.bottom() x, y = self._find_non_occluding_position(home, rect, True) if mode == "nooverlap": x, y = self._find_non_occluding_position(home, rect) if not x is None: return Rect(x, y, home.w, home.h) else: return None def _find_non_occluding_position(self, home, acc_rect, vertical = True, horizontal = True): # Leave some clearance around the accessible to account for # window frames and position errors of firefox entries. ra = acc_rect.apply_border(*config.auto_show.widget_clearance) rh = home if rh.intersects(ra): x, y = rh.get_position() # candidate positions vp = [] if horizontal: vp.append([ra.left() - rh.w, y]) vp.append([ra.right(), y]) if vertical: vp.append([x, ra.top() - rh.h]) vp.append([x, ra.bottom()]) # limited, non-intersecting candidate rectangles vr = [] for p in vp: pl = self._keyboard.limit_position( p[0], p[1], self._keyboard.canvas_rect) r = Rect(pl[0], pl[1], rh.w, rh.h) chx, chy = rh.get_center() cx, cy = r.get_center() d2 = cx * chx + cy * chy if not r.intersects(ra): vr.append(r) # candidate with smallest center-to-center distance wins chx, chy = rh.get_center() dmin = None rmin = None for r in vr: cx, cy = r.get_center() dx, dy = cx - chx, cy - chy d2 = dx * dx + dy * dy if dmin is None or dmin > d2: dmin = d2 rmin = r if not rmin is None: return rmin.get_position() return None, None def _is_accessible_editable(self, accessible): """ Is this an accessible onboard should be shown for? """ try: role = accessible.get_role() state = accessible.get_state_set() except: # private exception gi._glib.GError when gedit became unresponsive _logger.info("AtspiAutoHide: Invalid accessible," " failed to get role and state set") return False if role in [Atspi.Role.TEXT, Atspi.Role.TERMINAL, Atspi.Role.DATE_EDITOR, Atspi.Role.PASSWORD_TEXT, Atspi.Role.EDITBAR, Atspi.Role.ENTRY, Atspi.Role.DOCUMENT_TEXT, Atspi.Role.DOCUMENT_FRAME, Atspi.Role.DOCUMENT_EMAIL, Atspi.Role.SPIN_BUTTON, Atspi.Role.PARAGRAPH, # LibreOffice Writer Atspi.Role.HEADER, Atspi.Role.FOOTER, ]: if role in [Atspi.Role.TERMINAL] or \ state.contains(Atspi.StateType.EDITABLE): return True return False def _log_accessible(self, accessible): if _logger.isEnabledFor(logging.DEBUG): msg = "At-spi focus event: " if not accessible: msg += "accessible={}".format(accessible) else: state_set = accessible.get_state_set() editable = state_set.contains(Atspi.StateType.EDITABLE) \ if state_set else None ext = accessible.get_extents(Atspi.CoordType.SCREEN) extents = Rect(ext.x, ext.y, ext.width, ext.height) msg += "name={name}, role={role}({role_name}), " \ "editable={editable}, states={states}, " \ "extents={extents}]" \ .format(name=accessible.get_name(), role = accessible.get_role(), role_name = accessible.get_role_name(), editable = editable, states = state_set.states, # ValueError: invalid enum value: 47244640264 #state_set = state_set.get_states() \ # if state_set else None, extents = extents \ ) _logger.debug(msg)
class ScanMode(Timer): """ Abstract base class for all scanning modes. Specifies how the scanner moves between chunks of keys and when to activate them. Scan mode subclasses define a set of actions they support and the base class translates input device events into scan actions. Hierarchy: ScanMode --> AutoScan --> UserScan --> OverScan --> StepScan --> DirectScan """ """ Scan actions """ ACTION_STEP = 0 ACTION_LEFT = 1 ACTION_RIGHT = 2 ACTION_UP = 3 ACTION_DOWN = 4 ACTION_ACTIVATE = 5 ACTION_STEP_START = 6 ACTION_STEP_STOP = 7 ACTION_UNHANDLED = 8 """ Handles Key Events (Multiple Press at a time) """ #In MUL_KEY = 0 #In SCAN_PREV_ACTION = ACTION_UNHANDLED #In SCAN_ACTION_DO = True #In """ Time between key activation flashes (in sec) """ ACTIVATION_FLASH_INTERVAL = 0.1 """ Number of key activation flashes """ ACTIVATION_FLASH_COUNT = 2 def __init__(self, redraw_callback, activate_callback): super(ScanMode, self).__init__() logger.debug("ScanMode.__init__()") """ Activation timer instance """ self._activation_timer = Timer() """ Counter for key flash animation """ self._flash = 0 """ Counter for key popup animation """ self._popup_display = 0 #In """ Callback for key redraws """ self._redraw_callback = redraw_callback """ Callback for key activation """ self._activate_callback = activate_callback """ A Chunker instance """ self.chunker = None """ Time between key activation flashes (in sec) """ self.ACTIVATION_FLASH_INTERVAL = config.scanner.activation_flash_interval #0.1 #In """ Number of key activation flashes """ self.ACTIVATION_FLASH_COUNT = config.scanner.activation_flash_count #2 #In def __del__(self): logger.debug("ScanMode.__del__()") def map_actions(self, detail, pressed): """ Abstract: Convert input events into scan actions. """ raise NotImplementedError() def do_action(self, action): """ Abstract: Handle scan actions. """ raise NotImplementedError() def scan(self): """ Abstract: Move between chunks. """ raise NotImplementedError() def create_chunker(self): """ Abstract: Create a chunker instance. """ raise NotImplementedError() def init_position(self): """ Virtual: Called if a new layer was set or a key activated. """ pass def handle_event(self, event): """ Translate device events into scan actions. """ # Ignore events during key activation if self._activation_timer.is_running(): return event_type = event.xi_type if event_type == XIEventType.ButtonPress: button_map = config.scanner.device_button_map action = self.map_actions(button_map, event.button, True) elif event_type == XIEventType.ButtonRelease: button_map = config.scanner.device_button_map action = self.map_actions(button_map, event.button, False) elif event_type == XIEventType.KeyPress: if self.MUL_KEY >= 0: #In key_map = config.scanner.device_key_map #In self.SCAN_PREV_ACTION = self.map_actions( key_map, event.keyval, True) #In self.MUL_KEY = self.MUL_KEY + 1 #In return #In else: action = self.map_actions(key_map, event.keyval, False) elif event_type == XIEventType.KeyRelease: if self.MUL_KEY > 0: #In self.MUL_KEY = self.MUL_KEY - 1 #In key_map = config.scanner.device_key_map action = self.map_actions(key_map, event.keyval, True) #In if action != self.SCAN_PREV_ACTION: #In self.SCAN_ACTION_DO = False #In if self.MUL_KEY > 0 or (self.MUL_KEY == 0 and self.SCAN_ACTION_DO != True): #In action = self.map_actions(key_map, event.keyval, False) if self.MUL_KEY == 0 and self.SCAN_ACTION_DO != True: #In """ print("E R R O R : PLEASE DONT PRESS BOTH FUNCTIONALITIES TOGETHER!!!")#In TODO : Show Error Message """ self.SCAN_ACTION_DO = True #In else: action = self.map_actions(key_map, event.keyval, False) else: action = self.ACTION_UNHANDLED if action != self.ACTION_UNHANDLED: self.do_action(action) def on_timer(self): """ Override: Timer() callback. """ return self.scan() def max_cycles_reached(self): """ Check if the maximum number of scan cycles is reached. """ return self.chunker.cycles >= config.scanner.cycles def set_layer(self, layout, layer): """ Set the layer that should be scanned. """ self.reset() self.chunker = self.create_chunker() self.chunker.chunk(layout, layer) self.init_position() def _on_activation_timer(self, key): """ Timer callback: Flashes the key and finally activates it. """ if self._flash > 0: key.scanned = not key.scanned self._flash -= 1 self.redraw([key]) return True else: self._activate_callback(key) self.init_position() return False def _on_activation_timer_popup(self, key): #In """ Timer callback: Reset Scanner. """ self.init_position() return False def activate(self): """ Activates a key and triggers feedback. """ key = self.chunker.get_key() if not key: return if config.scanner.feedback_flash: """ Scanner Blinking """ self._flash = self.ACTIVATION_FLASH_COUNT * 2 #In self._activation_timer.start(self.ACTIVATION_FLASH_INTERVAL, self._on_activation_timer, key) else: #In """ Scanner Popup """ delay = config.UNPRESS_DELAY #In config.UNPRESS_DELAY = config.scanner.scanner_popup_unpress_delay #In self._activate_callback(key) self._activation_timer.start( config.scanner.scanner_popup_unpress_delay, self._on_activation_timer_popup, key) #In config.UNPRESS_DELAY = delay #In #self.init_position() def reset(self): """ Stop scanning and clear all highlights. """ if self.is_running(): self.stop() if self.chunker: self.redraw(self.chunker.highlight_all(False)) def redraw(self, keys=None): """ Update individual keys or the entire keyboard. """ self._redraw_callback(keys) def finalize(self): """ Clean up the ScanMode instance. """ self.reset() self._activation_timer = None
def __init__(self, keyboard): self._keyboard = keyboard self._auto_show_timer = Timer()
class KbdWindow(KbdWindowBase, WindowRectTracker, Gtk.Window): # Minimum window size (for resizing in system mode, see handle_motion()) MINIMUM_SIZE = 20 home_rect = None def __init__(self, keyboard_widget, icp): self._last_ignore_configure_time = None self._last_configures = [] self._was_visible = False Gtk.Window.__init__(self, urgency_hint = False, width_request=self.MINIMUM_SIZE, height_request=self.MINIMUM_SIZE) KbdWindowBase.__init__(self, keyboard_widget, icp) WindowRectTracker.__init__(self) GObject.signal_new("quit-onboard", KbdWindow, GObject.SIGNAL_RUN_LAST, GObject.TYPE_BOOLEAN, ()) self._auto_position_poll_timer = Timer() self.restore_window_rect(startup = True) self.connect("map", self._on_map_event) self.connect("unmap", self._on_unmap_event) self.connect("delete-event", self._on_delete_event) self.connect("configure-event", self._on_configure_event) # Connect_after seems broken in Quantal, the callback is never called. #self.connect_after("configure-event", self._on_configure_event_after) self._osk_util.connect_root_property_notify(["_NET_WORKAREA", "_NET_CURRENT_DESKTOP"], self._on_root_property_notify) once = CallOnce(100).enqueue # call at most once per 100ms rect_changed = lambda x: once(self._on_config_rect_changed) config.window.position_notify_add(rect_changed) config.window.size_notify_add(rect_changed) dock_size_changed = lambda x: once(self._on_config_dock_size_changed) config.window.dock_size_notify_add(dock_size_changed) def cleanup(self): WindowRectTracker.cleanup(self) KbdWindowBase.cleanup(self) if self.icp: self.icp.cleanup() self.icp.destroy() self.icp = None def _on_root_property_notify(self, property): """ Fixme: Exceptions get lost in here.""" if property == "_NET_WORKAREA": if config.is_docking_enabled() and \ not config.xid_mode: mon = self.get_docking_monitor() new_area = self.get_monitor_workarea() area = self._monitor_workarea.get(0) if area: # Only check for x changes, y is too dangerous for now, # too easy to get the timing wrong and end up with double docks. if area.x != new_area.x or \ area.w != new_area.w: area.x = new_area.x area.w = new_area.w _logger.info("workarea changed to {}, " "using {} for docking." \ .format(str(new_area), str(area))) self.update_docking() elif property == "_NET_CURRENT_DESKTOP": # OpenBox: Make sure to move the keyboard to the new desktop # on the next occasion. # Unity: Never reached (Raring), _NET_CURRENT_DESKTOP isn't # set when switching desktops there. However we do get a # configure event, so the transitioning code moves the # window and it is brought to the current desktop anyway. self._desktop_switch_count += 1 def _on_map_event(self, user_data): pass def _on_unmap_event(self, user_data): # Turn off struts in case this unmap is in response to # changes in window options, force-to-top in particular. if config.is_docking_enabled(): self.clear_struts() # untity starts onboard before the desktops # workarea has settled, reset it here on hiding, # as we know our struts are gone from this point. self.reset_monitor_workarea() def on_visibility_changed(self, visible): if not self._visible and visible and \ not config.is_docking_enabled() and \ not config.xid_mode: rect = self.get_current_rect() if not rect is None: # shouldn't happen, fix this self.move_resize(*rect) # sync position KbdWindowBase.on_visibility_changed(self, visible) def _on_config_rect_changed(self): """ Gsettings position or size changed """ if not config.xid_mode and \ not config.is_docking_enabled(): orientation = self.get_screen_orientation() rect = self.read_window_rect(orientation) # Only apply the new rect if it isn't the one we just wrote to # gsettings. Someone has to have manually changed the values # in gsettings to allow moving the window. rects = list(self._written_window_rects.values()) if not any(rect == r for r in rects): self.restore_window_rect() def _on_config_dock_size_changed(self): """ Gsettings size changed """ if not config.xid_mode and \ config.is_docking_enabled(): size = self.get_dock_size() # Only apply the new rect if it isn't the one we just wrote to # gsettings. Someone has to have manually changed the values # in gsettings to allow moving the window. sizes = list(self._written_dock_sizes.values()) if not any(size == sz for sz in sizes): self.restore_window_rect() def on_user_positioning_begin(self): self.stop_save_position_timer() self.stop_auto_position() self.keyboard_widget.freeze_auto_show() def on_user_positioning_done(self): self.update_window_rect() #self.detect_docking() if config.is_docking_enabled(): self.write_docking_size(self.get_screen_orientation(), self.get_size()) self.update_docking() else: self.update_home_rect() # Thaw auto show after a short delay to stop the window # from hiding due to spurios focus events after a system resize. self.keyboard_widget.thaw_auto_show(1.0) def detect_docking(self): if self.keyboard_widget.was_moving(): config.window.docking_enabled = False def _on_configure_event(self, widget, event): self.update_window_rect() if not config.is_docking_enabled(): # Connect_after seems broken in Quantal, but we still need to # get in after the default configure handler is done. Try to run # _on_configure_event_after in an idle handler instead. GLib.idle_add(self._on_configure_event_after, widget, event.copy()) def _on_configure_event_after(self, widget, event): """ Run this after KeyboardWidget's configure handler. After resizing Keyboard.update_layout() has to be called before limit_position() or the window jumps when it was close to the opposite screen edge of the resize handle. """ # Configure event due to user positioning? result = self._filter_configure_event(self._window_rect) if result == 0: self.update_home_rect() def _filter_configure_event(self, rect): """ Returns 0 for detected user positioning/sizing. Multiple defenses against false positives, i.e. window movement by autoshow, screen rotation, whathaveyou. """ # There is no user positioning in xembed mode. if config.xid_mode: return -1 # There is no system provided way to move/resize in # force-to-top mode. Solely rely on on_user_positioning_done(). if config.is_force_to_top(): return -2 # There is no user positioning for invisible windows. if not self.is_visible(): return -3 # There is no user positioning for iconified windows. if self.is_iconified(): return -4 # There is no user positioning for maximized windows. if self.is_maximized(): return -5 # Remember past n configure events. now = time.time() max_events = 4 self._last_configures = self._last_configures[-(max_events - 1):] # Same rect as before? if len(self._last_configures) and \ self._last_configures[-1][0] == rect: return 1 self._last_configures.append([rect, now]) # Only just started? if len(self._last_configures) < max_events: return 2 # Did we just move the window by auto-show? if not self._last_ignore_configure_time is None and \ time.time() - self._last_ignore_configure_time < 0.5: return 3 # Is the new window rect one of our known ones? if self.is_known_rect(self._window_rect): return 4 # Dragging the decorated frame doesn't produce continous # configure-events anymore as in Oneriric (Precise). # Disable all affected checks based on this. # The home rect will probably get lost occasionally. if not config.has_window_decoration(): # Less than n configure events in the last x seconds? first = self._last_configures[0] intervall = now - first[1] if intervall > 1.0: return 5 # Is there a jump > threshold in past positions? r0 = self._last_configures[-1][0] r1 = self._last_configures[-2][0] dx = r1.x - r0.x dy = r1.y - r0.y d2 = dx * dx + dy * dy if d2 > 50**2: self._last_configures = [] # restart return 6 return 0 def ignore_configure_events(self): self._last_ignore_configure_time = time.time() def remember_rect(self, rect): """ Remember the last 3 rectangles of auto-show repositioning. Time and order of configure events is somewhat unpredictable, so don't rely only on a single remembered rect. """ self._known_window_rects = self._known_window_rects[-3:] self._known_window_rects.append(rect) # Remembering the rects doesn't help if respositioning outside # of the work area in compiz with force-to-top mode disabled. # WM corrects window positions to fit into the viewable area. # -> add timing based block self.ignore_configure_events() def get_known_rects(self): """ Return all rects that may have resulted from internal window moves, not from user controlled drag operations. """ rects = list(self._known_window_rects) co = config.window.landscape rects.append(Rect(co.x, co.y, co.width, co.height)) co = config.window.portrait rects.append(Rect(co.x, co.y, co.width, co.height)) rects.append(self.home_rect) return rects def is_known_rect(self, rect): """ The home rect should be updated in response to user positiong/resizing. However we are unable to detect the end of window movement/resizing when window decoration is enabled. Instead we check if the current window rect is different from the ones auto-show knows and assume the user has changed it in this case. """ return any(rect == r for r in self.get_known_rects()) def move_home_rect_into_view(self): """ Make sure the home rect is valid, move it if necessary. This function may be called even if the window is invisible. """ rect = self._window_rect.copy() x, y = rect.x, rect.y _x, _y = self.keyboard_widget.limit_position(x, y) if _x != x or _y != y: self.update_home_rect() def update_home_rect(self): if config.is_docking_enabled(): return # update home rect rect = self._window_rect.copy() # Make sure the move button stays visible if self.can_move_into_view(): rect.x, rect.y = self.keyboard_widget.limit_position(rect.x, rect.y) self.home_rect = rect.copy() self.start_save_position_timer() # Make transitions aware of the new position, # undoubtedly reached by user positioning. # Else, window snaps back to the last transition position. self.keyboard_widget.sync_transition_position(rect) def get_home_rect(self): """ Get the un-repositioned rect, the one auto-show falls back to when there is nowhere else to move. """ if config.is_docking_enabled(): rect = self.get_dock_rect() else: rect = self.home_rect return rect def get_visible_rect(self): """ Returns the rect of the visible window rect with auto-show repositioning taken into account. """ home_rect = self.get_home_rect() # aware of docking rect = home_rect if config.is_auto_show_enabled(): r = self.get_repositioned_window_rect(home_rect) if not r is None: rect = r return rect def auto_position(self): self.update_position() # With docking enabled, when focusing the search entry of a # maximized firefox window, it changes position when the work # area shrinks and ends up below Onboard. # -> periodically update the window position for a little while, # this way slow systems can catch up too eventually (Nexus 7). self._poll_auto_position_start_time = time.time() start_delay = 0.1 self._auto_position_poll_timer.start(start_delay, self._on_auto_position_poll, start_delay) def _on_auto_position_poll(self, delay): self.update_position() # start another timer for progressively longer intervals delay = min(delay * 2.0, 1.0) if time.time() + delay < self._poll_auto_position_start_time + 3.0: self._auto_position_poll_timer.start(delay, self._on_auto_position_poll, delay) return True else: return False def stop_auto_position(self): self._auto_position_poll_timer.stop() def update_position(self): home_rect = self.get_home_rect() rect = self.get_repositioned_window_rect(home_rect) if rect is None: # move back home rect = home_rect if self.get_position() != rect.get_position(): self.keyboard_widget.transition_position_to(rect.x, rect.y) self.keyboard_widget.commit_transition() def get_repositioned_window_rect(self, home_rect): clearance = config.auto_show.widget_clearance test_clearance = clearance move_clearance = clearance limit_rects = None # None: all monitors # No test clearance when docking. Make it harder to jump # out of the dock, for example for the bottom search box # in maximized firefox. if config.is_docking_enabled(): test_clearance = (clearance[0], 0, clearance[2], 0) # limit the horizontal freedom to the docking monitor area, geom = self.get_docking_monitor_rects() limit_rects = [area] horizontal, vertical = self.get_repositioning_constraints() return self.keyboard_widget.auto_show.get_repositioned_window_rect( \ home_rect, limit_rects, test_clearance, move_clearance, horizontal, vertical) def reposition(self, x, y): """ Move the window from a transition, not meant for user positioning. """ # remember rects to distimguish from user move/resize w, h = self.get_size() self.remember_rect(Rect(x, y, w, h)) self.move(x, y) def get_repositioning_constraints(self): """ Return allowed respositioning directions for auto-show. """ if config.is_docking_enabled() and \ self.get_dock_expand(): return False, True else: return True, True def get_hidden_rect(self): """ Returns the rect of the hidden window rect with auto-show repositioning taken into account. """ if config.is_docking_enabled(): return self.get_docking_hideout_rect() return self.get_visible_rect() def get_current_rect(self): """ Returns the window rect with auto-show repositioning taken into account. """ if self.is_visible(): rect = self.get_visible_rect() else: rect = self.get_hidden_rect() return rect def on_restore_window_rect(self, rect): """ Overload for WindowRectTracker. """ if not config.is_docking_enabled(): self.home_rect = rect.copy() # check for alternative auto-show position r = self.get_current_rect() if r != rect: # remember our rects to distinguish from user move/resize self.remember_rect(r) rect = r self.keyboard_widget.sync_transition_position(rect) return rect def on_save_window_rect(self, rect): """ Overload for WindowRectTracker. """ # Ignore <rect> (self._window_rect), it may just be a temporary one # set by auto-show. Save the user selected home_rect instead. return self.home_rect def read_window_rect(self, orientation): """ Read orientation dependent rect. Overload for WindowRectTracker. """ if orientation == Orientation.LANDSCAPE: co = config.window.landscape else: co = config.window.portrait rect = Rect(co.x, co.y, co.width, co.height) return rect def write_window_rect(self, orientation, rect): """ Write orientation dependent rect. Overload for WindowRectTracker. """ # There are separate rects for normal and rotated screen (tablets). if orientation == Orientation.LANDSCAPE: co = config.window.landscape else: co = config.window.portrait # remember that we wrote this rect to gsettings self._written_window_rects[orientation] = rect.copy() # write to gsettings and trigger notifications co.settings.delay() co.x, co.y, co.width, co.height = rect co.settings.apply() def write_docking_size(self, orientation, size): co = self.get_orientation_config_object() expand = self.get_dock_expand() # remember that we wrote this rect to gsettings self._written_dock_sizes[orientation] = tuple(size) # write to gsettings and trigger notifications co.settings.delay() if not expand: co.dock_width = size[0] co.dock_height = size[1] co.settings.apply() def get_orientation_config_object(self): orientation = self.get_screen_orientation() if orientation == Orientation.LANDSCAPE: co = config.window.landscape else: co = config.window.portrait return co def on_transition_done(self, visible_before, visible_now): if visible_now: self.assure_on_current_desktop() self.update_docking() def on_screen_size_changed(self, screen): """ Screen rotation, etc. """ if config.is_docking_enabled(): # Can't correctly position the window while struts are active # -> turn them off for a moment self.clear_struts() # Attempt to hide the keyboard now. This won't work that well # as the system doesn't refresh the screen anymore until # after the rotation. self._was_visible = self.is_visible() self._screen_resizing = True keyboard_widget = self.keyboard_widget if keyboard_widget: keyboard_widget.transition_visible_to(False, 0.0) keyboard_widget.commit_transition() WindowRectTracker.on_screen_size_changed(self, screen) def on_screen_size_changed_delayed(self, screen): if config.is_docking_enabled(): self._screen_resizing = False self.reset_monitor_workarea() # The keyboard size may have changed, draw with the new size now, # while it's still in the hideout, so we don't have to watch. self.restore_window_rect() self.keyboard_widget.process_updates() keyboard_widget = self.keyboard_widget if keyboard_widget and self._was_visible: keyboard_widget.transition_visible_to(True, 0.0, 0.4) keyboard_widget.commit_transition() else: self.restore_window_rect() def limit_size(self, rect): """ Limits the given window rect to fit on screen. """ if self.keyboard_widget: return self.keyboard_widget.limit_size(rect) return rect def _emit_quit_onboard(self, event, data=None): self.emit("quit-onboard") def _on_delete_event(self, event, data=None): if config.lockdown.disable_quit: if self.keyboard_widget: return True else: self._emit_quit_onboard(event) def on_docking_notify(self): self.update_docking() self.keyboard_widget.update_resize_handles() def update_docking(self, force_update = False): enable = config.is_docking_enabled() if enable: rect = self.get_dock_rect() else: rect = Rect() shrink = config.window.docking_shrink_workarea edge = config.window.docking_edge expand = self.get_dock_expand() if self._docking_enabled != enable or \ (self._docking_enabled and \ (self._docking_rect != rect or \ self._shrink_work_area != shrink or \ self._dock_expand != expand or \ bool(self._current_struts) != shrink) ): self.enable_docking(enable) self._shrink_work_area = shrink self._dock_expand = expand self._docking_edge = edge self._docking_enabled = enable self._docking_rect = rect def enable_docking(self, enable): if enable: self._set_docking_struts(config.window.docking_shrink_workarea, config.window.docking_edge, self.get_dock_expand()) self.restore_window_rect() # knows about docking else: self.restore_window_rect() self.clear_struts() def clear_struts(self): self._set_docking_struts(False) def _set_docking_struts(self, enable, edge = None, expand = True): if not self.get_realized(): # no window, no xid return win = self.get_window() xid = win.get_xid() # requires GdkX11 import if not enable: self._apply_struts(xid, None) return area, geom = self.get_docking_monitor_rects() root = self.get_rootwin_rect() rect = self.get_dock_rect() top_start_x = top_end_x = 0 bottom_start_x = bottom_end_x = 0 #print("geom", geom, "area", area, "rect", rect) if edge: # Bottom top = 0 bottom = geom.h - area.bottom() + rect.h #bottom = root.h - area.bottom() + rect.h bottom_start_x = rect.left() bottom_end_x = rect.right() else: # Top top = area.top() + rect.h bottom = 0 top_start_x = rect.left() top_end_x = rect.right() struts = [0, 0, top, bottom, 0, 0, 0, 0, top_start_x, top_end_x, bottom_start_x, bottom_end_x] self._apply_struts(xid, struts) def _apply_struts(self, xid, struts = None): if self._current_struts != struts: if struts is None: self._osk_struts.clear(xid) else: self._osk_struts.set(xid, struts) self._current_struts = struts def get_dock_size(self): co = self.get_orientation_config_object() return co.dock_width, co.dock_height def get_dock_expand(self): co = self.get_orientation_config_object() return co.dock_expand def get_dock_rect(self): area, geom = self.get_docking_monitor_rects() edge = config.window.docking_edge width, height = self.get_dock_size() rect = Rect(area.x, 0, area.w, height) if edge: # Bottom rect.y = area.y + area.h - height else: # Top rect.y = area.y expand = self.get_dock_expand() if expand: rect.w = area.w rect.x = area.x else: rect.w = min(width, area.w) rect.x = rect.x + (area.w - rect.w) // 2 return rect def get_docking_hideout_rect(self, reference_rect = None): """ Where the keyboard goes to hide when it slides off-screen. """ area, geom = self.get_docking_monitor_rects() rect = self.get_dock_rect() hideout = rect mcx, mcy = geom.get_center() if reference_rect: cx, cy = reference_rect.get_center() else: cx, cy = rect.get_center() clearance = 10 if cy > mcy: hideout.y = geom.bottom() + clearance # below Bottom else: hideout.y = geom.top() - rect.h - clearance # above Top return hideout def get_docking_monitor_rects(self): screen = self.get_screen() mon = self.get_docking_monitor() area = self._monitor_workarea.get(mon) if area is None: area = self.update_monitor_workarea() geom = screen.get_monitor_geometry(mon) geom = Rect(geom.x, geom.y, geom.width, geom.height) return area, geom def get_docking_monitor(self): screen = self.get_screen() return screen.get_primary_monitor() def reset_monitor_workarea(self): self._monitor_workarea = {} def update_monitor_workarea(self): """ Save the workarea, so we don't have to check all the time if our strut is already installed. """ mon = self.get_docking_monitor() area = self.get_monitor_workarea() self._monitor_workarea[mon] = area return area def get_monitor_workarea(self): screen = self.get_screen() mon = self.get_docking_monitor() area = screen.get_monitor_workarea(mon) area = Rect(area.x, area.y, area.width, area.height) return area @staticmethod def get_rootwin_rect(): rootwin = Gdk.get_default_root_window() return Rect.from_position_size(rootwin.get_position(), (rootwin.get_width(), rootwin.get_height())) def is_override_redirect_mode(self): return config.is_force_to_top() and \ self._wm_quirks.can_set_override_redirect(self) def assure_on_current_desktop(self): """ Make sure the window is visible in the current desktop in OpenBox and perhaps other WMs, except Compiz/Unity. Dbus Show() then makes Onboard appear after switching desktop (LP: 1092166, Raring). """ if self._moved_desktop_switch_count != self._desktop_switch_count: win = self.get_window() if win: win.move_to_current_desktop() self._moved_desktop_switch_count = self._desktop_switch_count