Merge lp:~eduardo-mucelli/cairo-dock-plug-ins-extras/Translator into lp:~cairo-dock-team/cairo-dock-plug-ins-extras/third-party

Proposed by Eduardo Mucelli Rezende Oliveira
Status: Merged
Merged at revision: 94
Proposed branch: lp:~eduardo-mucelli/cairo-dock-plug-ins-extras/Translator
Merge into: lp:~cairo-dock-team/cairo-dock-plug-ins-extras/third-party
Diff against target: 360 lines (+110/-59)
5 files modified
Translator/Changelog.txt (+2/-1)
Translator/README (+1/-1)
Translator/Translator (+104/-54)
Translator/Translator.conf (+1/-1)
Translator/auto-load.conf (+2/-2)
To merge this branch: bzr merge lp:~eduardo-mucelli/cairo-dock-plug-ins-extras/Translator
Reviewer Review Type Date Requested Status
Matthieu Baerts Approve
Review via email: mp+39480@code.launchpad.net

Commit message

Added a string pre-processing to remove the possible line breaks in the text to be translated. Changed the shortcuts, both the X-server, and the Dock one were set to Ctrl+Alt[W|R]

Description of the change

Added a string pre-processing to remove the possible line breaks in the text to be translated. Changed the shortcuts, both the X-server, and the Dock one were set to Ctrl+Alt[W|R]

To post a comment you must log in.
Revision history for this message
Matthieu Baerts (matttbe) wrote :

@Eduardo: Thank you ;)

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'Translator/Changelog.txt'
2--- Translator/Changelog.txt 2010-08-25 00:37:35 +0000
3+++ Translator/Changelog.txt 2010-10-27 20:47:46 +0000
4@@ -1,5 +1,6 @@
5+0.1.5:(October/27/2010): Added a string pre-processing to remove the possible line breaks in the text to be translated. Changed the shortcuts, both the X-server, and the Dock one were set to Ctrl+Alt[W|R]
6 0.1.4:(August/24/2010): For Cairo-dock 2.2.0 or higher, the user can move from the translation result to a new translation, or edit the recently translated text.
7-0.1.3: (August/23/2010): Adding the dock-level shortcut Ctrl + F9, requires Cairo-Dock 2.2.0 or higher. Removing glib import since it was redundant and causing problems in Debian Lenny.
8+0.1.3:(August/23/2010): Adding the dock-level shortcut Ctrl + F9, requires Cairo-Dock 2.2.0 or higher. Removing glib import since it was redundant and causing problems in Debian Lenny.
9 0.1.2:(August/8/2010): Formally known as doCkranslator, the applet was renamed to Translator.
10 0.1.1:(July/18/2010): Switch languages menu added, thanks to Matttbe for this suggestion. util module added.
11 0.1.0:(July/18/2010): doCkranslator now has another fast-as-hell way to translate. Press Ctrl + F8 to open the input dialog, paste some text, and press Enter. The shortcut capability requires Python-Xlib, but even if the user has not it, the applet works without this capability.
12
13=== modified file 'Translator/README'
14--- Translator/README 2010-07-18 18:03:12 +0000
15+++ Translator/README 2010-10-27 20:47:46 +0000
16@@ -1,4 +1,4 @@
17-To use the Ctrl + F8 shortcut, in order to open the dialog box, it is necessary to install the Python-Xlib.
18+To use the Ctrl + Alt[W|R] shortcut, in order to open the dialog box, it is necessary to install the Python-Xlib, or at least Cairo-Dock 2.2.0.
19
20 # Contact me
21
22
23=== modified file 'Translator/Translator'
24--- Translator/Translator 2010-08-25 00:37:35 +0000
25+++ Translator/Translator 2010-10-27 20:47:46 +0000
26@@ -17,34 +17,37 @@
27
28 # This applet provides a translator tool using the Google Translator service
29 # Translator (formally doCkranslator) translates from lots of languages to lots of languages
30-# To choose the source and destination languages:
31-# (I) Right-click on the icon -> To/From -> Choose the destination language
32-# (II) Right-click on the icon -> Translator -> Configuration
33-# Anyway, the easier way to choose the destination language is scroll up/down over the icon
34-# To translate:
35-# (I) Press Ctrl + F8, type the text, and press Enter (requires Python-Xlib)
36-# (II) Press Ctrl + F9, type the text, and press Enter (requires Cairo-dock 2.2.0 or higher)
37-# (III) Left-click on the icon; type your text and press Enter
38-# (IV) Select any text in any place, and middle click on the icon
39+# First it is necessary to choose the languages using one of the following ways:
40+# (I) Scroll up/down over the icon to choose the destination language
41+# (II) Right-click on the icon -> "To", or "From"
42+# (III) Right-click on the icon -> Translator -> Configuration
43+# To translate you can do it using one of the following ways:
44+# (I) Left-click on the icon; type your text and press Enter
45+# (II) Select any text in any place, and middle click on the icon
46+# The plugin also provides useful keyboard shortcuts (requires Python-Xlib, or Cairo-dock 2.2.0)
47+# If you want to translate something you are reading in the foreign language you chose "From":
48+# * Press Ctrl + Alt + R, type the text, and press Enter
49+# If you are writing something in your native language you chose "To":
50+# * Press Ctrl + Alt + W, type the text, and press Enter
51 # Translated text will be shown as a dialog and be available in the clipboard, just press Ctrl+v to have it
52
53-import gobject, dbus, os.path, urllib, gtk, ConfigParser
54+import gobject, dbus, os, urllib, gtk, ConfigParser
55 from dbus.mainloop.glib import DBusGMainLoop
56 from dbus import glib
57 from sgmllib import SGMLParser
58 from urllib import FancyURLopener
59 from util import log
60
61-# Este applet tenta obter dois niveis de atalho, o nivel mais baixo diretamente
62-# do X Server atraves do Ctrl + F8, e o mais alto pelo Cairo-dock com Ctrl + F9.
63-# Ver os metodos low_level_keypress_binding() e dock_level_keypress_binding
64+# Este applet tenta obter o atalho Ctrl + Alt + [R|W] em dois niveis, o nivel mais
65+# baixo diretamente do X Server e o mais alto pelo Cairo-dock.
66+# Ver os metodos low_level_keypress_binding e dock_level_keypress_binding
67
68-# This applet tries to get two shortcut levels, the lower one from X Server
69-# through Ctrl + F8, and the higher one from Cairo-dock with Ctrl + F9.
70+# This applet tries to get the Ctrl + Alt + [R|W] shortcut in two levels, the lower
71+# one from X Server, and the highergher one from Cairo-dock.
72 # Check the low_level_keypress_binding and dock_level_keypress_binding methods out.
73
74 # Mesmo que o usuario nao tenha a Python-Xlib instalada, o applet ira funcionar,
75-# pois esta biblioteca eh usada apenas para fazer a linkagem entre Ctrl + F8 e
76+# pois esta biblioteca eh usada apenas para fazer a linkagem entre Ctrl + Alt + [R|W] e
77 # a abertura da caixa de dialogo para a insercao do texto a ser traduzido
78 # Obs.: As bibliotecas thread e timer tambem nao precisam ser carregadas
79 # uma vez que elas sao uteis apenas quando a Xlib esta presente
80@@ -55,10 +58,10 @@
81 import thread # abrir um fluxo alternativo com a classe KeyHandler
82 import time
83 except ImportError: # Nao tem a Python-Xlib instalada, msg nele
84- log ("Ctrl + F8 shortcut won't work, install Python-Xlib library")
85+ log ("Ctrl + Alt + [R|W] shortcut won't work, install Python-Xlib library")
86 low_level_shortcut_available = False
87 else:
88- log ("Ctrl + F8 shortcut gonna work, Python-Xlib library is up and running")
89+ log ("Ctrl + Alt + [R|W] shortcut gonna work, Python-Xlib library is up and running")
90 low_level_shortcut_available = True
91
92 DBusGMainLoop(set_as_default=True)
93@@ -79,7 +82,7 @@
94 applet = Applet(icon, configuration)
95 applet.start()
96
97- if low_level_shortcut_available: # Python-Xlib installed so lets make Ctrl+F8 shortcut available
98+ if low_level_shortcut_available: # Python-Xlib installed, grab the Ctrl+Alt+[R|W] shortcut!
99 thread.start_new_thread(KeyHandler(applet).start, ("handler", 1)) # (funcao callback, (nome da thread, tempo de dormencia))
100
101 loop = gobject.MainLoop()
102@@ -87,9 +90,9 @@
103 sys.exit(0)
104
105 class KeyHandler:
106- """Class que registra o evento de pressionamento do atalho Ctrl + F8 e abre a caixa de dialogo no applet"""
107+ """Class que registra o evento de pressionamento do atalho Ctrl + Alt + [R|W] e abre a caixa de dialogo no applet"""
108 """O registro do evento comeca ao fazer o grab_key da combinacao de teclas; se o X identificar o pressionamento
109- de alguma tecla com o Control (X.ControlMask), chama o handle_event que verifica se a tecla eh o F8; caso positivo,
110+ de alguma tecla com o Control + Alt (X.ControlMask | X.Mod1Mask), chama o handle_event que verifica se a tecla eh o [R|W]; caso positivo,
111 chama o metodo ask_text para abrir a caixa de dialogo no applet """
112
113 def __init__(self, applet):
114@@ -101,14 +104,18 @@
115 self.disp = Display()
116 self.root = self.disp.screen().root
117 self.root.change_attributes(event_mask = X.KeyPressMask)
118- self.f8_keycode = self.disp.keysym_to_keycode(XK.string_to_keysym('F8'))
119- self.root.grab_key(self.f8_keycode, X.ControlMask, True, X.GrabModeAsync, X.GrabModeAsync) # Pega do X quando pressionar Ctrl + F8
120- # self.root.grab_key(self.f8_keycode, X.AnyModifier, True, X.GrabModeAsync, X.GrabModeAsync) # Pega do X quando pressionar F8
121+ self.r_keycode = self.disp.keysym_to_keycode(XK.string_to_keysym('R'))
122+ self.w_keycode = self.disp.keysym_to_keycode(XK.string_to_keysym('W'))
123+ # Pega do X quando pressionar Ctrl + Alt + R
124+ self.root.grab_key(self.r_keycode, (X.ControlMask | X.Mod1Mask), True, X.GrabModeAsync, X.GrabModeAsync)
125+ # Pega do X quando pressionar Ctrl + Alt + W
126+ self.root.grab_key(self.w_keycode, (X.ControlMask | X.Mod1Mask), True, X.GrabModeAsync, X.GrabModeAsync)
127 self.disp.set_error_handler(self.disp_error_handler)
128
129 def disp_error_handler(self, error, request):
130- log ("Error %s" % error)
131- self.root.ungrab_key(self.f8_keycode, X.AnyModifier)
132+ log ("Key handler error %s" % error)
133+ self.root.ungrab_key(self.r_keycode, X.AnyModifier)
134+ self.root.ungrab_key(self.w_keycode, X.AnyModifier)
135 self.running = 0
136
137 def lookup_keysym(self, keysym):
138@@ -121,12 +128,17 @@
139 keycode = aEvent.detail
140 log ("Pressed key %s" % self.lookup_keysym(self.disp.keycode_to_keysym(keycode,0)))
141 if aEvent.type == X.KeyPress:
142- if keycode == self.f8_keycode:
143- log ("Ok, 'Ctrl + F8' pressed")
144+ if keycode == self.r_keycode:
145+ log ("Ok, 'Ctrl + Alt + R' pressed")
146+ self.applet.set_read_mode()
147+ self.applet.ask_text() # Abrir o caixa de dialogo para o texto a ser traduzido
148+ elif keycode == self.w_keycode:
149+ log ("Ok, 'Ctrl + Alt + W' pressed")
150+ self.applet.set_write_mode()
151 self.applet.ask_text() # Abrir o caixa de dialogo para o texto a ser traduzido
152
153 def start(self, name, sleeptime):
154- log ("KeyHandler start")
155+ log ("Low level key handler started")
156 while self.running: # Faz o polling ateh que o evento seja recebido
157 event = self.root.display.next_event() # busca o evento que tiver
158 self.handle_event(event) # lanca o metodo de tratamento do evento
159@@ -168,11 +180,22 @@
160 def translate_it(self, source, destiny):
161 parser = TranslatorParser() # create the parser
162 opener = AgentOpener() # opens the web connection with masked user-agent
163- url = "http://translate.google.com/?sl=%s&tl=%s&q=%s" % (source, destiny, self.text_to_be_translated.replace(' ', '%20').encode('utf-8'))
164- page = opener.open(url) # get the HTML
165- parser.parse(page.read()) # feed the parser to get the specific content: translated text
166- page.close() # lets close the page connection
167- self.text_to_be_translated = parser.translated_content # from the parser, we get the translated content
168+ url = "http://translate.google.com/?sl=%s&tl=%s&q=%s" % (source, destiny, self.adjust(self.text_to_be_translated))
169+ try:
170+ page = opener.open(url) # get the HTML
171+ except IOError:
172+ log ("Problem to open the remote translator, check the text to be translated")
173+ else:
174+ parser.parse(page.read()) # feed the parser to get the specific content: translated text
175+ page.close() # lets close the page connection
176+ self.text_to_be_translated = parser.translated_content # from the parser, we get the translated content
177+ return self.text_to_be_translated
178+
179+ def adjust(self, text):
180+ """Ajusta o texto removendo espacos, quebras de linha, codifica tudo em utf-8"""
181+ log ("Text to be translated before adjust: %s" % (self.text_to_be_translated))
182+ self.text_to_be_translated = self.text_to_be_translated.strip().replace(os.linesep, ' ').replace(' ', '%20').encode('utf-8')
183+ log ("Text to be translated later adjust: %s" % (self.text_to_be_translated))
184 return self.text_to_be_translated
185
186 class Language:
187@@ -191,15 +214,16 @@
188 self.sources = [] # list of possible source languages
189 self.destiny = None # get it from configuration file
190 self.destinies = [] # list of possible resulting languages
191+ # self.favorites = [] # TODO lista de linguas favoritas
192 self.scroll_destiny_language = 0
193 self.dialog_active_time = 10 # time in seconds that the dialog window will be active
194 self.new_translation_key = 1 # there are 3 buttons, cancel = 0, new = 1 ...
195 self.edit_translation_key = 2 # ... and edit
196
197 def start(self):
198- log ("Applet start")
199+ log ("Applet started")
200 self.read_languages_file()
201- self.set_configuration_parameters()
202+ self.read_configuration_parameters()
203 self.connect_to_callbacks()
204 self.dock_level_keypress_binding()
205
206@@ -214,15 +238,24 @@
207 self.icon.connect_to_signal("on_shortkey", self.action_on_dock_level_shortkey)
208 self.icon.connect_to_signal("on_answer_dialog", self.action_on_answer_dialog)
209
210- def set_configuration_parameters(self):
211- reader = ConfigParser.RawConfigParser()
212- reader.read(self.configuration)
213- slang = reader.getint('Configuration', 'source') # get the source language position in the list
214- dlang = reader.getint('Configuration', 'destiny') # get the destination language position in the list
215- self.source = self.sources[slang]
216- self.destiny = self.destinies[dlang] # first set the destination language ...
217+ def read_configuration_parameters(self):
218+ self.source = self.get_source_language_from_configuration()
219+ self.destiny = self.get_destiny_language_from_configuration() # first set the destination language ...
220+ log ("From %s to %s read from configuration file" % (self.source.name, self.destiny.name))
221 self.inform_current_destiny_language() # ... and show it
222
223+ def get_source_language_from_configuration(self):
224+ reader = ConfigParser.RawConfigParser()
225+ reader.read(self.configuration)
226+ slang = reader.getint('Configuration', 'source') # get the source language index
227+ return self.sources[slang] # retorna a instancia de Language referente ao indice
228+
229+ def get_destiny_language_from_configuration(self):
230+ reader = ConfigParser.RawConfigParser()
231+ reader.read(self.configuration)
232+ dlang = reader.getint('Configuration', 'destiny') # get the destination language index
233+ return self.destinies[dlang] # retorna a instancia de Language referente ao indice
234+
235 def read_languages_file(self):
236 """Read the languages file formated as Name<space>Abbreviation, e.g, Portuguese pt"""
237 f = open('.languages', "rb")
238@@ -231,17 +264,17 @@
239 name, abbrv = splited[0], splited[1]
240 self.sources.append(Language(name, abbrv)) # e.g, Language("English", "en")
241 self.destinies.append(Language(name, abbrv)) # e.g, Language("Portuguese", "pt")
242-
243+
244 def dock_level_keypress_binding(self):
245 try:
246- self.icon.BindShortkey(["<Control>F9"])
247+ self.icon.BindShortkey(["<Control><Alt>R"]) # for reading moments
248+ self.icon.BindShortkey(["<Control><Alt>W"]) # for writing moments
249 except dbus.DBusException:
250- log ("Ctrl + F9 shortcut won't work, update Cairo-dock to 2.2.0 or higher")
251+ log ("Ctrl + Alt + [R|W] shortcut won't work, update Cairo-dock to 2.2.0 or higher")
252 else:
253- log ("Ctrl + F9 shortcut gonna work, Cairo-dock 2.2.0 or higher is up and running")
254+ log ("Ctrl + Alt + [R|W] shortcut gonna work, Cairo-dock 2.2.0 or higher is up and running")
255
256 def translate(self, sentence, source, destiny):
257- log ("sentence: %s (from: %s to: %s)" % (sentence, source, destiny))
258 self.inform_start_of_waiting_process()
259
260 interface = Interface(sentence) # alimenta o tradutor com o sentence a ser traduzida
261@@ -257,15 +290,27 @@
262
263 self.inform_end_of_waiting_process()
264 self.inform_current_destiny_language()
265- log ("translated: %s" % translated)
266+ log ("Translated: %s" % translated)
267
268 def ask_text(self, default=""):
269 label = "Translate from %s to %s:" % (self.source.name, self.destiny.name)
270- self.icon.AskText(label, default) # heya user, tell me what do you wanna translate
271+ self.icon.AskText(label, default) # heya user, tell me what do you wanna and I will translate
272
273 def action_on_dock_level_shortkey(self, key):
274+ if (key == "<Control><Alt>R"): # Usuario esta lendo a lingua desconhecida (Ingles) e quer traduzir para a linguage destino (Portugues)
275+ self.set_read_mode()
276+ elif (key == "<Control><Alt>W"): # Usuario esta escrevendo em sua lingua (Portugues) e quer traduzir para a linguage destino (Ingles)
277+ self.set_write_mode()
278 self.ask_text()
279
280+ def set_read_mode(self):
281+ self.source = self.get_source_language_from_configuration()
282+ self.destiny = self.get_destiny_language_from_configuration()
283+
284+ def set_write_mode(self):
285+ self.source = self.get_destiny_language_from_configuration() # trocada em relacao ao de cima
286+ self.destiny = self.get_source_language_from_configuration()
287+
288 def action_on_answer(self, answer):
289 if answer:
290 self.text_to_be_translated = answer
291@@ -321,7 +366,7 @@
292
293 def switch_languages(self):
294 self.source, self.destiny = self.destiny, self.source
295- log ("Switched languages from self.source.namemenu: source [%s] destiny [%s]" % (self.source.name, self.destiny.name))
296+ log ("Switched languages, lets translate from %s to %s" % (self.source.name, self.destiny.name))
297 self.inform_current_destiny_language()
298
299 def switch_source_language(self, index):
300@@ -335,7 +380,7 @@
301 self.icon.AddMenuItems(self.build_menu_for_destiny_languages())
302 self.icon.AddMenuItems(self.build_menu_for_switch_languages())
303 except TypeError:
304- log ("AddMenuItems method is not available, update Cairo-dock to 2.1.4 or higher2.1.4-0beta0")
305+ log ("AddMenuItems method is not available, update Cairo-dock to 2.1.4 or higher")
306
307 def build_menu_for_destiny_languages(self):
308 destiny_sub_menu_icon = os.path.abspath("./data/to.png")
309@@ -353,9 +398,14 @@
310 return destiny_sub_menu
311
312 def build_menu_for_source_languages(self):
313+ """o sub-menu destinos (acima) tem, para cada uma de suas entradas, ids que variam de 0 ao len(self.destinies)-1
314+ consequentemente, o primeiro id do menu de origem (este aqui) eh len(self.destinies). Eh necessario apenas deslocar
315+ o id por este primeiro indice para ter um indice que varia de len(self.destinies)+1 ao len(self.sources).
316+ Ver switch_source_language()"""
317 """destinies sub-menu (above) has, for each one of its entries, ids that ranges from 0 to len(self.destinies)-1
318 consequently, the first id of the sources menu is the len(self.destinies). It is just necessary to shift the
319- id by this first index to get a index that ranges from 0 to len(self.sources). See switch_source_language()"""
320+ id by this first index to get a index that ranges from len(self.destinies)+1 to len(self.sources).
321+ See switch_source_language()"""
322 source_sub_menu_icon = os.path.abspath("./data/from.png")
323 source_sub_menu_index = len(self.destinies)
324 source_sub_menu = [{'type':1, 'label':'From', 'menu':0, 'id':source_sub_menu_index, 'icon':source_sub_menu_icon}]
325@@ -379,7 +429,7 @@
326
327 def action_on_reload(self, config_has_changed):
328 if config_has_changed:
329- self.set_configuration_parameters()
330+ self.read_configuration_parameters()
331
332 def set_to_clipboard(self, sentence):
333 clipboard = gtk.clipboard_get() # get the clipboard
334
335=== modified file 'Translator/Translator.conf'
336--- Translator/Translator.conf 2010-08-25 00:37:35 +0000
337+++ Translator/Translator.conf 2010-10-27 20:47:46 +0000
338@@ -1,4 +1,4 @@
339-#!en;0.1.4
340+#!en;0.1.5
341
342 #[gtk-about]
343 [Icon]
344
345=== modified file 'Translator/auto-load.conf'
346--- Translator/auto-load.conf 2010-08-25 00:37:35 +0000
347+++ Translator/auto-load.conf 2010-10-27 20:47:46 +0000
348@@ -4,10 +4,10 @@
349 author = Eduardo Mucelli Rezende Oliveira
350
351 # A short description of the applet and how to use it.
352-description = Translator (formally doCkranslator) translates from lots of languages to lots of languages\nTo choose the source and destination languages:\n (I) Right-click on the icon -> To/From -> Choose the destination language\n (II) Right-click on the icon -> Translator -> Configuration\nAnyway, the easier way to choose the destination language is scroll up/down over the icon\nTo translate:\n (I) Press Ctrl + F8, type the text, and press Enter (requires Python-Xlib)\n (II) Press Ctrl + F9, type the text, and press Enter (requires Cairo-dock 2.2.0 or higher)\n (III) Left-click on the icon; type your text and press Enter\n (IV) Select any text in any place, and middle click on the icon\nTranslated text will be shown as a dialog and be available in the clipboard, just press Ctrl+v to have it
353+description = This applet provides a translator tool using the Google Translator service\n Translator (formally doCkranslator) translates from lots of languages to lots of languages\n First it is necessary to choose the languages using one of the following ways:\n (I) Scroll up/down over the icon to choose the destination language\n (II) Right-click on the icon -> "To", or "From"\n (III) Right-click on the icon -> Translator -> Configuration\n To translate you can do it using one of the following ways:\n (I) Left-click on the icon; type your text and press Enter\n (II) Select any text in any place, and middle click on the icon\n The plugin also provides useful keyboard shortcuts (requires Python-Xlib, or Cairo-dock 2.2.0)\n If you want to translate something you are reading in the foreign language you chose "From":\n * Press Ctrl + Alt + R, type the text, and press Enter\n If you are writing something in your native language you chose "To":\n * Press Ctrl + Alt + W, type the text, and press Enter\n Translated text will be shown as a dialog and be available in the clipboard, just press Ctrl+v to have it
354
355 # Category of the applet : 2 = files, 3 = internet, 4 = Desktop, 5 = accessory, 6 = system, 7 = fun
356 category = 5
357
358 # Version of the applet; change it everytime you change something in the config file. Don't forget to update the version both in this file and in the config file.
359-version = 0.1.4
360+version = 0.1.5

Subscribers

People subscribed via source and target branches