Skip to content

Commit

Permalink
feat: Apply Black formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelmardojai authored and mufeedali committed Apr 25, 2024
1 parent 96e223c commit 0a56a92
Show file tree
Hide file tree
Showing 15 changed files with 186 additions and 289 deletions.
2 changes: 1 addition & 1 deletion dialect/languages.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,4 @@ def set_langs(self, langs, auto=False):

def set_selected(self, code):
for item in self.langs:
item.props.selected = (item.code == code)
item.props.selected = item.code == code
54 changes: 22 additions & 32 deletions dialect/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@

class Dialect(Adw.Application):
def __init__(self):
Adw.Application.__init__(
self,
application_id=APP_ID,
flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE
)
Adw.Application.__init__(self, application_id=APP_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
self.set_resource_base_path(RES_PATH)

# App window
Expand All @@ -43,14 +39,17 @@ def __init__(self):
self._signal_handler = None

# Add command line options
self.add_main_option('selection', b'n', GLib.OptionFlags.NONE,
GLib.OptionArg.NONE, 'Translate text from the primary clipboard', None)
self.add_main_option('text', b't', GLib.OptionFlags.NONE,
GLib.OptionArg.STRING, 'Text to translate', None)
self.add_main_option('src', b's', GLib.OptionFlags.NONE,
GLib.OptionArg.STRING, 'Source lang code', None)
self.add_main_option('dest', b'd', GLib.OptionFlags.NONE,
GLib.OptionArg.STRING, 'Destination lang code', None)
self.add_main_option(
'selection',
b'n',
GLib.OptionFlags.NONE,
GLib.OptionArg.NONE,
'Translate text from the primary clipboard',
None,
)
self.add_main_option('text', b't', GLib.OptionFlags.NONE, GLib.OptionArg.STRING, 'Text to translate', None)
self.add_main_option('src', b's', GLib.OptionFlags.NONE, GLib.OptionArg.STRING, 'Source lang code', None)
self.add_main_option('dest', b'd', GLib.OptionFlags.NONE, GLib.OptionArg.STRING, 'Destination lang code', None)

self.setup_actions()

Expand All @@ -62,7 +61,7 @@ def on_translator_loading(_win, _pspec):
self.window.disconnect(self._signal_handler)
# Process CLI args
self.process_command_line()

self.window = self.props.active_window

if not self.window:
Expand All @@ -72,7 +71,7 @@ def on_translator_loading(_win, _pspec):
# Translators: Do not translate the app name!
title=_('Dialect'),
default_height=height,
default_width=width
default_width=width,
)

# Decide when to process command line args
Expand Down Expand Up @@ -104,12 +103,9 @@ def process_command_line(self):
return

text = ''
langs = {
'src': None,
'dest': None
}
langs = {'src': None, 'dest': None}
selection = 'selection' in self.argv

if 'text' in self.argv:
text = self.argv['text']
if 'src' in self.argv:
Expand All @@ -127,11 +123,9 @@ def process_command_line(self):
self.argv = {}

def setup_actions(self):
""" Setup menu actions """
"""Setup menu actions"""

pronunciation = Gio.SimpleAction.new_stateful(
'pronunciation', None, Settings.get().show_pronunciation_value
)
pronunciation = Gio.SimpleAction.new_stateful('pronunciation', None, Settings.get().show_pronunciation_value)
pronunciation.connect('change-state', self._on_pronunciation)
self.add_action(pronunciation)

Expand Down Expand Up @@ -166,7 +160,7 @@ def setup_actions(self):
self.set_accels_for_action('win.show-help-overlay', ['<Primary>question'])

def _on_pronunciation(self, action, value):
""" Update show pronunciation setting """
"""Update show pronunciation setting"""
action.props.state = value
Settings.get().show_pronunciation = value

Expand All @@ -177,22 +171,18 @@ def _on_pronunciation(self, action, value):
self.window.dest_pron_revealer.props.reveal_child = value

def _on_preferences(self, _action, _param):
""" Show preferences window """
"""Show preferences window"""
window = DialectPreferencesDialog(self.window)
window.present(self.window)

def _on_about(self, _action, _param):
""" Show about dialog """
"""Show about dialog"""
builder = Gtk.Builder.new_from_resource(f'{RES_PATH}/about.ui')
about = builder.get_object('about')

about.props.application_icon = APP_ID
about.props.version = VERSION
about.props.developers = [
"Mufeed Ali",
"Rafael Mardojai CM http://rafaelmardojai.com",
"Libretto"
]
about.props.developers = ["Mufeed Ali", "Rafael Mardojai CM http://rafaelmardojai.com", "Libretto"]

about.add_link(_('Donate'), 'https://opencollective.com/dialect')

Expand Down
28 changes: 13 additions & 15 deletions dialect/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,16 @@ def __init__(self, window, **kwargs):
self.window = window

# Bind preferences with GSettings
Settings.get().bind('live-translation', self.live_translation, 'enable-expansion',
Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('sp-translation', self.search_provider, 'active',
Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('translate-accel', self.translate_accel,
'selected', Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('src-auto', self.src_auto, 'active',
Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('custom-default-font-size', self.custom_default_font_size, 'enable-expansion',
Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('default-font-size', self.default_font_size, 'value',
Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind(
'live-translation', self.live_translation, 'enable-expansion', Gio.SettingsBindFlags.DEFAULT
)
Settings.get().bind('sp-translation', self.search_provider, 'active', Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('translate-accel', self.translate_accel, 'selected', Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind('src-auto', self.src_auto, 'active', Gio.SettingsBindFlags.DEFAULT)
Settings.get().bind(
'custom-default-font-size', self.custom_default_font_size, 'enable-expansion', Gio.SettingsBindFlags.DEFAULT
)
Settings.get().bind('default-font-size', self.default_font_size, 'value', Gio.SettingsBindFlags.DEFAULT)

self.translator_config.props.sensitive = False
self.tts_config.props.sensitive = False
Expand All @@ -61,7 +59,7 @@ def __init__(self, window, **kwargs):
self.translator_config.props.sensitive = self._provider_has_settings(Settings.get().active_translator)

# Setup TTS chooser
if (len(TTS) >= 1):
if len(TTS) >= 1:
tts_model = ProvidersListModel('tts', True)
with self.tts.freeze_notify():
self.tts.set_model(tts_model)
Expand All @@ -87,8 +85,8 @@ def __init__(self, window, **kwargs):

@Gtk.Template.Callback()
def is_not_true(self, _widget, boolean):
""" Check if boolean is not true
template binding closure function
"""Check if boolean is not true
template binding closure function
"""
return not boolean

Expand Down
7 changes: 2 additions & 5 deletions dialect/providers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,8 @@ class ProvidersListModel(GObject.GObject, Gio.ListModel):
def __init__(self, p_type='', show_disabled=False):
super().__init__()

if (p_type): # If we want to get an specific provider type
types = {
'translators': TRANSLATORS,
'tts': TTS
}
if p_type: # If we want to get an specific provider type
types = {'translators': TRANSLATORS, 'tts': TTS}
providers = types.get(p_type)
else: # Get all providers
providers = MODULES
Expand Down
2 changes: 1 addition & 1 deletion dialect/providers/modules/bing.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def on_response(data):
data['translations'][0]['text'],
(text, src, dest),
detected=detected,
pronunciation=(None, pronunciation)
pronunciation=(None, pronunciation),
)
on_done(translation)

Expand Down
4 changes: 1 addition & 3 deletions dialect/providers/modules/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,9 +450,7 @@ def on_response(data):
)
)
except TypeError:
translated_parts = [
TranslatedPart(parsed[1][0][1][0], [parsed[1][0][0][0], parsed[1][0][1][0]])
]
translated_parts = [TranslatedPart(parsed[1][0][1][0], [parsed[1][0][0][0], parsed[1][0][1][0]])]

first_iter = True
translated = ""
Expand Down
101 changes: 55 additions & 46 deletions dialect/search_provider/search_provider.in
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ dbus_interface_description = '''
</node>
'''


class TranslateService:
def __init__(self):
self.loaded = False
Expand Down Expand Up @@ -100,7 +101,7 @@ class TranslateService:
case ProviderErrorCode.API_KEY_REQUIRED:
self.translations[error_id] = _('API key is required to use the service')
case _:
self.translations[error_id] = _('Translation failed')
self.translations[error_id] = _('Translation failed')
callback([error_id])

text = ' '.join(terms)
Expand All @@ -114,13 +115,7 @@ class TranslateService:
error_id = ERROR_PREFIX + text

src, dest = self.translator.denormalize_lang(self.src_language, self.dest_language)
self.translator.translate(
text,
src,
dest,
on_done,
on_fail
)
self.translator.translate(text, src, dest, on_done, on_fail)

else:
provider = Settings.get().active_translator
Expand Down Expand Up @@ -239,46 +234,60 @@ class TranslateService:
else:
self._load_translator()


class TranslateServiceApplication(Gio.Application):
def __init__(self):
Gio.Application.__init__(
self,
application_id='@[email protected]',
flags=Gio.ApplicationFlags.IS_SERVICE,
inactivity_timeout=10000,
)
self.service_object = TranslateService()
self.search_interface = Gio.DBusNodeInfo.new_for_xml(dbus_interface_description).interfaces[0]

def do_dbus_register(self, connection, object_path):
try:
connection.register_object(
object_path=object_path,
interface_info=self.search_interface,
method_call_closure=self.on_dbus_method_call,
)
except:
self.quit()
return False
finally:
return True

def on_dbus_method_call(self, connection, sender, object_path, interface_name, method_name, parameters, invocation):
def return_value(results):
results = (results,)
if results == (None,):
results = ()
results_type = (
"("
+ "".join(
map(
lambda argument_info: argument_info.signature,
self.search_interface.lookup_method(method_name).out_args,
)
)
+ ")"
)
wrapped_results = GLib.Variant(results_type, results)

invocation.return_value(wrapped_results)

self.release()

self.hold()

method = getattr(self.service_object, method_name)
arguments = list(parameters.unpack())
arguments.append(return_value)

method(*arguments)

def __init__(self):
Gio.Application.__init__(self,
application_id='@[email protected]',
flags=Gio.ApplicationFlags.IS_SERVICE,
inactivity_timeout=10000)
self.service_object = TranslateService()
self.search_interface = Gio.DBusNodeInfo.new_for_xml(dbus_interface_description).interfaces[0]

def do_dbus_register(self, connection, object_path):
try:
connection.register_object(object_path=object_path,
interface_info=self.search_interface,
method_call_closure=self.on_dbus_method_call)
except:
self.quit()
return False
finally:
return True

def on_dbus_method_call(self, connection, sender, object_path, interface_name, method_name, parameters, invocation):
def return_value(results):
results = results,
if results == (None,):
results = ()
results_type = "(" + "".join(map(lambda argument_info: argument_info.signature, self.search_interface.lookup_method(method_name).out_args)) + ")"
wrapped_results = GLib.Variant(results_type, results)

invocation.return_value(wrapped_results)

self.release()

self.hold()

method = getattr(self.service_object, method_name)
arguments = list(parameters.unpack())
arguments.append(return_value)

method(*arguments)

if __name__ == "__main__":
app = TranslateServiceApplication()
Expand Down
2 changes: 1 addition & 1 deletion dialect/shortcuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ def __init__(self, **kwargs):

@Gtk.Template.Callback()
def _on_show(self, _data):
""" Called on self::show signal """
"""Called on self::show signal"""
self.translate_shortcut.props.visible = not Settings.get().live_translation
self.translate_shortcut.props.accelerator = Settings.get().translate_accel
2 changes: 1 addition & 1 deletion dialect/widgets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Copyright 2020-2022 Rafael Mardojai CM
# SPDX-License-Identifier: GPL-3.0-or-later

from dialect.widgets.lang_selector import LangSelector # noqa
from dialect.widgets.lang_selector import LangSelector # noqa
from dialect.widgets.provider_preferences import ProviderPreferences # noqa
from dialect.widgets.textview import TextView # noqa
from dialect.widgets.theme_switcher import ThemeSwitcher # noqa
Loading

0 comments on commit 0a56a92

Please sign in to comment.