From b948c4f78aed8578209643e2a3ff219211db535c Mon Sep 17 00:00:00 2001 From: Rafael Mardojai CM Date: Fri, 1 Nov 2024 11:12:05 -0500 Subject: [PATCH] window: `translate_selection`: Only get clipboard when window is active Fixes #407 --- dialect/window.blp | 2 ++ dialect/window.py | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/dialect/window.blp b/dialect/window.blp index 2e61b359..e21dadc5 100644 --- a/dialect/window.blp +++ b/dialect/window.blp @@ -44,6 +44,8 @@ template $DialectWindow : Adw.ApplicationWindow { height-request: 320; focus-widget: src_text; + notify::is-active => $_on_is_active_changed(); + Adw.Breakpoint { condition ("max-width: 680px") setters { diff --git a/dialect/window.py b/dialect/window.py index 90a14e4f..58e0acaf 100644 --- a/dialect/window.py +++ b/dialect/window.py @@ -105,6 +105,7 @@ class DialectWindow(Adw.ApplicationWindow): current_history = 0 # for history management # Translation-related variables + pending_trans_selection = False next_translation: TranslationRequest | None = None # for ongoing translation translation_loading = False # for ongoing translation @@ -509,10 +510,15 @@ def translate(self, text: str, src_lang: str | None, dest_lang: str | None): @background_task async def translate_selection(self, src_lang: str | None, dest_lang: str | None): """Runs `translate` with the selection clipboard text""" - if display := Gdk.Display.get_default(): - clipboard = display.get_primary_clipboard() - if text := await clipboard.read_text_async(): # type: ignore - self.translate(text, src_lang, dest_lang) + if self.props.is_active: + if display := Gdk.Display.get_default(): + clipboard = display.get_primary_clipboard() + if text := await clipboard.read_text_async(): # type: ignore + self.translate(text, src_lang, dest_lang) + self.pending_trans_selection = False + else: + self.translate(self.src_buffer.props.text, src_lang, dest_lang) # Just set the langs + self.pending_trans_selection = True def save_settings(self, *args, **kwargs): if not self.is_maximized(): @@ -932,6 +938,11 @@ def _on_user_action_ended(self, _buffer): if Settings.get().live_translation: self._on_translation() + @Gtk.Template.Callback() + def _on_is_active_changed(self, *_args): + if self.pending_trans_selection and self.props.is_active: + self.translate_selection(self.src_lang_selector.selected, self.dest_lang_selector.selected) + @Gtk.Template.Callback() def _on_retry_load_translator_clicked(self, *_args): self.reload_provider("translator")