/
my_youdao.py
312 lines (279 loc) · 9.95 KB
/
my_youdao.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python
# coding=utf8
import os
import sys
import time
import subprocess
import queue
import peewee
import wx
from youdao import Fetcher
from models import Word, Item, init_close_db
from utils import init_list, save_list, Status, delta, get_url
from word_getter import WordGetter
from action import Search, Recite, Flash
HotKey = None
if sys.platform == 'darwin':
title = 'Press ctrl+cmd+z to search selected word'
#from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
elif sys.platform == 'linux2':
title = 'Press left ctrl and left shift to search selected word'
else:
title = 'Press win+z to search selected word'
from hotkey import HotKey
from quick_edit_mode import win32, handle, old_mode, quick_edit
size = (800, 500)
same_word_hint = 'same word ?'
class GUI(Search):
previous = ''
item = None
def __init__(self, material_queue, word_queue, product_queue):
super(GUI, self).__init__(None, title, size)
self.material_queue = material_queue
self.word_queue = word_queue
self.product_queue = product_queue
self.item_queue = queue.Queue()
self.Bind(wx.EVT_CLOSE, self.close_handler)
self.words = init_list()
self.bind()
wx.CallLater(delta, self.respond)
if HotKey:
HotKey(self)
def check_search_word(self, word):
word = Word(word)
if word.is_valid:
if self.previous != word.value:
self.previous = word.value
else:
print(same_word_hint)
self.search_word(word)
else:
self.clear(word, 'Invalid word.')
def respond(self):
if not self.material_queue.empty():
word = self.material_queue.get()
self.check_search_word(word)
if not self.item_queue.empty():
self.item = self.item_queue.get()
self.show_in_gui()
if not self.product_queue.empty():
word, item_dict_or_str = self.product_queue.get()
if isinstance(item_dict_or_str, dict):
# if no example, do not save to db, but if added to xml, save it to db.
if item_dict_or_str['example']:
item = self.save_item(item_dict_or_str)
else:
item = Item(**item_dict_or_str)
self.item_queue.put(item)
else:
self.clear(word, item_dict_or_str)
wx.CallLater(delta, self.respond)
def center(self):
w = self.winfo_screenwidth()
h = self.winfo_screenheight()
self.ize = tuple(
int(_) for _ in self.geometry().split('+')[0].split('x'))
x = w / 2 - self.ize[0] / 2
y = h / 2 - self.ize[1] / 2
self.geometry("%dx%d+%d+%d" % (self.ize + (x, y)))
def bind(self):
self.entry_name.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self.btn_save.Bind(wx.EVT_BUTTON, self.save_after_edit)
self.btn_lookup.Bind(wx.EVT_BUTTON, self.enter_handler)
self.btn_add.Bind(wx.EVT_BUTTON, self.add_to_xml)
self.btn_recite.Bind(wx.EVT_BUTTON, self.create_recite_window)
self.btn_flash.Bind(wx.EVT_BUTTON, self.create_flash_window)
if self.words:
self.btn_recite.Enable()
self.btn_flash.Enable()
self.btn_sort.Bind(wx.EVT_BUTTON, self.sort)
def sort(self, e=None):
self.words = init_list()
self.btn_sort.Disable()
self.words.sort(key=lambda x: x.score)
save_list(self.words)
time.sleep(1)
self.btn_sort.Enable()
@init_close_db
def save_after_edit(self, event=None):
if self.item:
self.item.meaning = self.area_meaning.GetValue()
self.item.example = self.area_example.GetValue()
try:
self.item.save(force_insert=True)
except peewee.IntegrityError as e:
print(type(e), e)
self.item.save()
def create_recite_window(self, e=None):
self.words = init_list()
self.recite = Recite(self)
self.btn_recite.Disable()
self.btn_flash.Disable()
def create_flash_window(self, e=None):
self.words = init_list()
self.flash = Flash(self)
self.btn_recite.Disable()
self.btn_flash.Disable()
def OnKeyUp(self, e=None):
code = e.GetKeyCode()
if code == wx.WXK_RETURN:
self.enter_handler(e)
def enter_handler(self, e=None):
word = self.entry_name.GetValue()
if word:
self.material_queue.put(word)
self.focus_in_entry()
def btn_recite_handler(self, e=None):
if self.words:
self.btn_recite.Enable()
self.btn_flash.Enable()
else:
self.btn_recite.Disable()
self.btn_flash.Disable()
def show_in_gui(self):
self.btn_save.Enable()
if not self.in_xml():
self.btn_add.Enable()
else:
self.btn_add.Disable()
self.entry_name.SetValue(self.item.name)
self.label_phonetic.SetLabel(self.item.phonetic)
self.area_meaning.SetValue(self.item.meaning)
self.area_example.SetValue(self.item.example)
#self.highlight(self.item.name)
#self.highlight(self.item.name.title())
self.popup_and_focus()
def popup_and_focus(self):
if sys.platform == 'darwin':
self.mac_raise(subproc=True)
elif sys.platform == 'linux2':
self.linux_raise()
else:
if self.IsIconized():
self.Iconize(False)
self.Raise()
self.focus_in_entry()
def linux_raise(self):
'''
print self.IsIconized() # always False
if self.IsIconized():
self.Iconize(False)
self.Show(True)
self.Refresh()
self.Raise()
'''
command = 'wmctrl -a "%s"' % title # or xdotool
os.system(command)
def mac_raise(self, subproc=False):
#nsapp = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
#nsapp.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
if self.IsIconized():
self.Iconize(False)
if subproc:
subprocess.Popen([
'osascript',
'-e',
'''
tell application "System Events"
set procName to name of first process whose unix id is %s
end tell
tell application procName to activate
''' % os.getpid(),
])
else:
long_cmd = (
"""/usr/bin/osascript -e 'tell app "Finder" """
"""to set frontmost of process "Python" to true'"""
)
os.system(long_cmd)
#self.Raise() # shake; tremble; vibrate, not needed
def focus_in_entry(self):
self.entry_name.SetFocus() # no need to set focus? need
#self.entry_name.SetSelection(0, -1) # not works
self.entry_name.SetSelection(-1, -1)
#self.entry_name.SetInsertionPointEnd()
def clear(self, word, meaning):
meaning = meaning or 'No such word or web failure.'
self.entry_name.SetValue(word.value)
self.label_phonetic.SetLabel('')
self.area_meaning.SetValue(meaning)
self.area_example.SetValue(get_url(word.value))
self.btn_add.Disable()
self.btn_save.Disable()
self.popup_and_focus()
def in_xml(self):
# return self.item.name in [one.name for one in self.words]
for one in self.words:
if self.item.name == one.name:
return True
return False
@init_close_db
def add_to_xml(self, event=None):
self.btn_add.Disable()
self.words = init_list()
if self.in_xml(): # strange duplicate items
return
# if add a word that is not in db now to xml, save it to db.
try:
temp = Item.get(name=self.item.name)
except Exception:
temp = None
if not temp:
self.item.save(force_insert=True) # only save() not save to db
try:
if self.words:
self.words.insert(1, self.item.convert())
else:
self.words.insert(0, self.item.convert())
save_list(self.words)
except Exception as e:
print(e)
@init_close_db
def query_db(self, word):
try:
return Item.get(name=word)
except Exception:
return None
@init_close_db
def save_item(self, item_dict):
try:
item = Item.create(**item_dict)
item = item.to_unicode()
except peewee.IntegrityError as e:
print(type(e), e)
item = self.query_db(item_dict['name'])
return item
def search_word(self, word):
if word.lang == 'cn':
self.word_queue.put(word)
else:
item = self.query_db(word.value)
if item:
self.item_queue.put(item)
else:
self.word_queue.put(word)
def close_handler(self, e=None):
if sys.platform == 'win32':
'''
# enable Windows console(cmd.exe) quick edit mode
new_mode = old_mode | quick_edit
win32.SetConsoleMode(handle, new_mode)
'''
# respect individual preference
win32.SetConsoleMode(handle, old_mode)
Status.running = False
self.Hide()
self.Destroy()
if __name__ == '__main__':
if sys.platform == 'win32':
# disable Windows console(cmd.exe) quick edit mode
new_mode = old_mode & (~quick_edit)
win32.SetConsoleMode(handle, new_mode)
material_queue = queue.Queue()
word_queue = queue.Queue()
product_queue = queue.Queue()
WordGetter(material_queue).start()
Fetcher(word_queue, product_queue).start()
app = wx.App()
GUI(material_queue, word_queue, product_queue)
app.MainLoop()