Debian Codegraph @

setup/main.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2009 Leo Zheng <[email protected]>, Kov Chai <[email protected]>
4 # *
5 # The contents of this file are subject to the terms of either the GNU Lesser
6 # General Public License Version 2.1 only ("LGPL") or the Common Development and
7 # Distribution License ("CDDL")(collectively, the "License"). You may not use this
8 # file except in compliance with the License. You can obtain a copy of the CDDL at
9 # http://www.opensource.org/licenses/cddl1.php and a copy of the LGPLv2.1 at
10 # http://www.opensource.org/licenses/lgpl-license.php. See the License for the
11 # specific language governing permissions and limitations under the License. When
12 # distributing the software, include this License Header Notice in each file and
13 # include the full text of the License in the License file as well as the
14 # following notice:
15 #
16 # NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
17 # (CDDL)
18 # For Covered Software in this distribution, this License shall be governed by the
19 # laws of the State of California (excluding conflict-of-law provisions).
20 # Any litigation relating to this License shall be subject to the jurisdiction of
21 # the Federal Courts of the Northern District of California and the state courts
22 # of the State of California, with venue lying in Santa Clara County, California.
23 #
24 # Contributor(s):
25 #
26 # If you wish your version of this file to be governed by only the CDDL or only
27 # the LGPL Version 2.1, indicate your decision by adding "[Contributor]" elects to
28 # include this software in this distribution under the [CDDL or LGPL Version 2.1]
29 # license." If you don't indicate a single choice of license, a recipient has the
30 # option to distribute your version of this file under either the CDDL or the LGPL
31 # Version 2.1, or to extend the choice of license to its licensees as provided
32 # above. However, if you add LGPL Version 2.1 code and therefore, elected the LGPL
33 # Version 2 license, then the option applies only if the new code is made subject
34 # to such option by the copyright holder.
35 #
36
37 import sys
38 import os
39 from os import path
40 try:
41 import gtk
42 import glib
43 except ImportError:
44 from gi import require_version as gi_require_version
45 gi_require_version('Gtk', '3.0')
46 from gi.repository import Gtk as gtk
47 from gi.repository import GLib as glib
48 try:
49 import ibus
50 except ImportError:
51 from gi import require_version as gi_require_version
52 gi_require_version('IBus', '1.0')
53 from gi.repository import IBus as ibus
54 import gettext
55 import locale
56
57 GETTEXT_PACKAGE="ibus-sunpinyin"
58 _ = lambda msg: gettext.gettext(msg)
59
60 XML_FILE = path.join(path.dirname(__file__), "setup.xml")
61 SEPARATOR = "/"
62
63 class Logger:
64 @staticmethod
65 def pr(message):
66 print(message, file=sys.stderr)
67
68
69 class Option(object):
70 """Option serves as an interface of ibus.config
71
72 it is used to synchronize the configuration with setting on user interface
73 """
74 config = ibus.Bus().get_config()
75 __wrappers = {
76 bool: glib.Variant.new_boolean,
77 int: glib.Variant.new_int32,
78 str: glib.Variant.new_string,
79 list: glib.Variant.new_strv,
80 }
81
82 def __init__(self, name, default):
83 self.name = name
84 self.default = default
85 self.__wrap = self.__wrappers[type(self.default)]
86
87 def read(self):
88 section, key = self.__get_config_name()
89 wrapped = self.config.get_value(section, key)
90 return self.default if wrapped is None else wrapped.unpack()
91
92 def write(self, v):
93 section, key = self.__get_config_name()
94 return self.config.set_value(section, key, self.__wrap(v))
95
96 def __get_config_name(self):
97 keys = self.name.rsplit(SEPARATOR ,1)
98 if len(keys) == 2:
99 return SEPARATOR.join(("engine/SunPinyin", keys[0])), keys[1]
100 else:
101 assert len(keys) == 1
102 return "engine/SunPinyin", keys[0]
103
104 class TrivalOption(Option):
105 """option represented using a simple gtk widget
106 """
107 def __init__(self, name, default, owner):
108 super(TrivalOption, self).__init__(name, default)
109 self.xml = owner
110 self.widget = owner.get_object(name)
111 assert self.widget is not None, "%s not found in gtkbuilder" % name
112
113 def init_ui(self):
114 self.init()
115 self.read_config()
116
117 def init(self):
118 pass
119
120 def read_config(self):
121 """update user inferface with ibus.config
122 """
123 self.v = self.read()
124 self.__set_value(self.v)
125
126 def write_config(self):
127 v = self.save_ui_setting()
128 self.write(v)
129
130 def save_ui_setting(self):
131 """save user interface settings into self.v
132 """
133 self.v = self.__get_value()
134 return self.v
135
136 def is_changed(self):
137 return self.v != self.__get_value()
138
139 def __get_value(self):
140 try:
141 return self.widget.get_value()
142 except:
143 return self.widget.get_active()
144
145 def __set_value(self, v):
146 try:
147 self.widget.set_value(v)
148 except:
149 self.widget.set_active(v)
150
151 class CheckBoxOption(TrivalOption):
152 def __init__(self, name, default, owner):
153 super(CheckBoxOption, self).__init__(name, default, owner)
154
155 class ComboBoxOption(TrivalOption):
156 def __init__(self, name, default, options, owner):
157 try:
158 default = int(default)
159 except ValueError:
160 default = options.index(default)
161 super(ComboBoxOption, self).__init__(name, default, owner)
162 self.options = options
163
164 def init(self):
165 model = gtk.ListStore(str)
166 for v in self.options:
167 model.append([str(v)])
168 self.widget.set_model(model)
169
170 def __get_value(self):
171 active = self.widget.get_active()
172 try:
173 # if the options are numbers, save the liternal of active option as
174 # a number
175 return int(self.options[active])
176 except ValueError:
177 # otherwise save its index
178 return active
179
180 def __set_value(self, v):
181 try:
182 # if the options are just numbers, we treat 'self.v' as the literal
183 # of option
184 dummy = int(self.options[0])
185 active = self.options.index(v)
186 except ValueError:
187 active = v
188 self.widget.set_active(active)
189
190 class RadioOption(Option):
191 """option represented using multiple Raidio buttons
192 """
193 def __init__(self, name, default, options, owner):
194 super(RadioOption, self).__init__(name, default)
195 self.options = options
196 self.xml = owner
197
198 def init_ui(self):
199 self.read_config()
200
201 def read_config(self):
202 self.v = self.read()
203 name = SEPARATOR.join([self.name, self.v])
204 button = self.xml.get_object(name)
205 assert button is not None, "button: %r not found" % name
206 button.set_active(True)
207
208 def write_config(self):
209 active_opt = None
210 for opt in self.options:
211 radio_name = SEPARATOR.join([self.name, opt])
212 radio = self.xml.get_object(radio_name)
213 if radio.get_active():
214 active_opt = opt
215 break
216 assert active_opt is not None
217 self.write(active_opt)
218
219 class MappingInfo:
220 def __init__(self, name, mapping):
221 self.name = name
222 self.mapping = mapping
223
224 class MappingOption(object):
225 """an option which presents some sort of mapping, e.g. fuzzy pinyin mapping
226
227 it is not directly related to a config option like TrivalOption does, but
228 we always have a checkbox in UI for each of it so user can change it easily.
229 """
230 def __init__(self, name, mappings, owner):
231 self.name = name
232 self.widget = owner.get_object(name)
233 self.mappings = mappings
234
235 def get_mappings(self):
236 if self.widget.get_active():
237 return [':'.join(self.mappings)]
238 else:
239 return []
240
241 def set_active(self, enabled):
242 self.widget.set_active(enabled)
243
244 def get_active(self):
245 return self.widget.get_active()
246
247 is_enabled = property(get_active, set_active)
248
249 def key(self):
250 return self.mappings[0]
251
252 class MultiMappingOption(Option):
253 def __init__(self, name, options, default=[]):
254 Option.__init__(self, name, default)
255 self.options = options
256 self.saved_pairs = default
257
258 def read_config(self):
259 if not self.saved_pairs:
260 self.saved_pairs = self.read()
261 keys = {pair.split(':')[0] for pair in self.saved_pairs}
262 for opt in self.options:
263 opt.is_enabled = (opt.key() in keys)
264 # throw away unknown pair
265
266 def write_config(self):
267 # ignore empty settings
268 if self.saved_pairs:
269 self.write(self.saved_pairs)
270
271 def save_ui_setting(self):
272 self.saved_pairs = sum([opt.get_mappings() for opt in self.options
273 if opt.is_enabled], [])
274 return self.saved_pairs
275
276 def set_active_all(self, enabled):
277 for opt in self.options:
278 opt.is_enabled = enabled
279
280 class MultiCheckDialog (object):
281 """ a modal dialog box with 'choose all' and 'choose none' button
282
283 TODO: another option is to use radio button
284 """
285 def __init__ (self, ui_name, config_name, mappings, option_klass=MappingOption):
286 self.ui_name = ui_name
287 self.config_name = config_name
288 self.mappings = mappings
289 self.option_klass = option_klass
290 self.saved_settings = []
291 self.mapping_options = None
292
293 def get_setup_name(self):
294 """assuming the name of dialog looks like 'dlg_fuzzy_setup'
295 """
296 return '_'.join(['dlg', self.ui_name, 'setup'])
297
298 def __init_ui(self, parent_window):
299 dlg_name = self.get_setup_name()
300 self.__xml = gtk.Builder()
301 self.__xml.add_objects_from_file(XML_FILE, [dlg_name])
302 self.__dlg = self.__xml.get_object(dlg_name)
303 assert self.__dlg is not None, "dialog %s not found in %s" % (dlg_name, XML_FILE)
304 self.__dlg.set_transient_for(parent_window)
305 handlers = {'_'.join(["on", self.ui_name, "select_all_clicked"]) : self.on_button_check_all_clicked,
306 '_'.join(["on", self.ui_name, "unselect_all_clicked"]) : self.on_button_uncheck_all_clicked,
307 '_'.join(["on", self.ui_name, "ok_clicked"]) : self.on_button_ok_clicked,
308 '_'.join(["on", self.ui_name, "cancel_clicked"]) : self.on_button_cancel_clicked}
309 self.__xml.connect_signals(handlers)
310
311 options = [self.option_klass(m.name, m.mapping, self.__xml)
312 for m in self.mappings]
313 self.mapping_options = MultiMappingOption(self.config_name, options, self.saved_settings)
314
315 def dummy(self):
316 """a dummy func, i don't initialize myself upon other's request.
317 instead, i will do it by myself.
318 """
319 pass
320
321 init_ui = read_config = dummy
322
323 def run(self, parent_window):
324 self.__init_ui(parent_window)
325 self.__read_config()
326 self.__dlg.run()
327
328 def __read_config(self):
329 self.mapping_options.read_config()
330
331 def __save_ui_settings(self):
332 """save to in-memory storage, will flush to config if not canceled in main_window
333 """
334 self.saved_settings = self.mapping_options.save_ui_setting()
335
336 def write_config(self):
337 if self.mapping_options is not None:
338 self.mapping_options.write_config()
339
340 def on_button_check_all_clicked(self, button):
341 self.mapping_options.set_active_all(True)
342
343 def on_button_uncheck_all_clicked(self, button):
344 self.mapping_options.set_active_all(False)
345
346 def on_button_ok_clicked(self, button):
347 """update given options with settings in UI, these settings will be
348 written to config if user push 'OK' or 'Apply' in the main window
349 """
350 self.__save_ui_settings()
351 self.__dlg.destroy()
352
353 def on_button_cancel_clicked(self, button):
354 self.__dlg.destroy()
355
356 class FuzzySetupDialog (MultiCheckDialog):
357 def __init__(self):
358 mappings = [MappingInfo('QuanPin/Fuzzy/ShiSi', ('sh','s')),
359 MappingInfo('QuanPin/Fuzzy/ZhiZi', ('zh','z')),
360 MappingInfo('QuanPin/Fuzzy/ChiCi', ('ch','c')),
361 MappingInfo('QuanPin/Fuzzy/ShiSi', ('sh','s')),
362 MappingInfo('QuanPin/Fuzzy/AnAng', ('an','ang')),
363 MappingInfo('QuanPin/Fuzzy/OnOng', ('on','ong')),
364 MappingInfo('QuanPin/Fuzzy/EnEng', ('en','eng')),
365 MappingInfo('QuanPin/Fuzzy/InIng', ('in','ing')),
366 MappingInfo('QuanPin/Fuzzy/EngOng', ('eng','ong')),
367 MappingInfo('QuanPin/Fuzzy/IanIang', ('ian','iang')),
368 MappingInfo('QuanPin/Fuzzy/UanUang', ('uan','uang')),
369 MappingInfo('QuanPin/Fuzzy/NeLe', ('n','l')),
370 MappingInfo('QuanPin/Fuzzy/FoHe', ('f','h')),
371 MappingInfo('QuanPin/Fuzzy/LeRi', ('l','r')),
372 MappingInfo('QuanPin/Fuzzy/KeGe', ('k','g'))]
373 MultiCheckDialog.__init__(self,
374 ui_name = 'fuzzy',
375 config_name = 'QuanPin/Fuzzy/Pinyins',
376 mappings = mappings)
377
378 class CorrectionSetupDialog (MultiCheckDialog):
379 def __init__(self):
380 mappings = [MappingInfo('QuanPin/AutoCorrection/GnNg', ('gn','ng')),
381 MappingInfo('QuanPin/AutoCorrection/UenUn', ('uen','un')),
382 MappingInfo('QuanPin/AutoCorrection/ImgIng', ('img','ing')),
383 MappingInfo('QuanPin/AutoCorrection/IouIu', ('iou','iu')),
384 MappingInfo('QuanPin/AutoCorrection/UeiUi', ('uei','ui'))]
385 MultiCheckDialog.__init__(self,
386 ui_name = 'correction',
387 config_name = 'QuanPin/AutoCorrection/Pinyins',
388 mappings = mappings)
389
390 class PunctMapping(MappingOption):
391 def __init__(self, name, mappings, owner):
392 MappingOption.__init__(self, name, mappings, owner)
393 if mappings:
394 self.widget.set_sensitive(True)
395 self.init_keys_values(mappings)
396 else:
397 self.widget.set_sensitive(False)
398
399 def init_keys_values(self, mappings):
400 self.keys = [m[0] for m in mappings]
401 values_with_closing = [v or k for k, v in mappings]
402 self.values = []
403 for v in values_with_closing:
404 try:
405 self.values.append(v[0])
406 except:
407 self.values.append(v)
408 self.keys.reverse()
409 self.values.reverse()
410
411 def get_mappings(self):
412 if self.widget.get_active():
413 pairs = []
414 for k,vs in self.mappings:
415 try:
416 for v in vs:
417 pairs.append(':'.join([k,v]))
418 except:
419 v = vs
420 if v is None:
421 continue
422 pairs.append(':'.join([k,v]))
423 return pairs
424 else:
425 return []
426
427 def set_active(self, enabled):
428 if not self.mappings: return
429 if enabled:
430 self.widget.set_label('\n'.join(self.values))
431 else:
432 self.widget.set_label('\n'.join(self.keys))
433 self.widget.set_active(enabled)
434
435 is_enabled = property(MappingOption.get_active, set_active)
436
437 def key(self):
438 for k, v in self.mappings:
439 if v is not None:
440 return k
441 else:
442 return None
443
444 class PunctMappingSetupDialog (MultiCheckDialog):
445 # TODO: the UI should looks like a virtual keyboard,
446 # user are allowed to choose the mappings to all punctuation keys.
447 def __init__(self):
448 mappings = [MappingInfo('togglebutton1', [('`', None), ('~', '~')]),
449 MappingInfo('togglebutton2', []),
450 MappingInfo('togglebutton3', [('2', None), ('@', '@')]),
451 MappingInfo('togglebutton4', [('3', None), ('#', '#')]),
452 MappingInfo('togglebutton5', [('4', None), ('$', '¥' )]),
453 MappingInfo('togglebutton6', [('5', None), ('%', '%')]),
454 MappingInfo('togglebutton7', [('6', None), ('^', '…')]),
455 MappingInfo('togglebutton8', [('7', None), ('&', '&')]),
456 MappingInfo('togglebutton9', [('8', None), ('*', '*')]),
457 MappingInfo('togglebutton10', [('9', None), ('*', '(')]),
458 MappingInfo('togglebutton11', [('0', None), ('*', ')')]),
459 MappingInfo('togglebutton12', [('-', '-'), ('_', '——')]),
460 MappingInfo('togglebutton13', [('=', '='), ('+', '+')]),
461 MappingInfo('togglebutton14', [('\\', None), ('|', '‖')]),
462 MappingInfo('togglebutton27', [('[', '〔'), ('{', '{')]),
463 MappingInfo('togglebutton28', [(']', '〕'), ('}', '}')]),
464 MappingInfo('togglebutton39', []),
465 MappingInfo('togglebutton40', []),
466 MappingInfo('togglebutton50', [(',', None), ('<', '〈')]),
467 MappingInfo('togglebutton51', [('.', '·'), ('>', '〉')]),
468 MappingInfo('togglebutton52', [('/', '/'), ('?', None)])]
469 #'\'', ('‘', '’'),
470 MultiCheckDialog.__init__(self, ui_name="punctmapping",
471 config_name="General/PunctMapping/Mappings",
472 mappings=mappings,
473 option_klass=PunctMapping)
474
475 class MainWindow():
476 SPECIAL_OBJECTS = [
477 'pymodel', 'memory_adjustment', 'candidate_adjustment',
478 'max_best_adjustment', 'max_tail_candidate_adjustment',
479 ]
480
481 def __init__ (self):
482 self.__bus = ibus.Bus()
483 self.__config = self.__bus.get_config()
484
485
486 def run(self):
487 self.__init_ui("main_window")
488 self.__read_config()
489 gtk.main()
490
491 def __init_ui(self, name):
492 self.__init_gettext()
493 xml_file = path.join(path.dirname(__file__), XML_FILE)
494 self.__xml = gtk.Builder()
495 self.__xml.add_objects_from_file(xml_file, self.SPECIAL_OBJECTS)
496 self.__xml.add_objects_from_file(xml_file, [name])
497 self.__xml.connect_signals(self)
498 self.__init_options()
499 self.window = self.__xml.get_object(name)
500 self.window.show_all()
501
502 def __init_gettext(self):
503 locale.setlocale(locale.LC_ALL, "")
504 localedir = os.getenv("IBUS_LOCALEDIR")
505 gettext.bindtextdomain(GETTEXT_PACKAGE, localedir)
506 gettext.bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8")
507
508 def __init_options(self):
509 self.__fuzzy_setup = FuzzySetupDialog()
510 self.__correction_setup = CorrectionSetupDialog()
511 self.__punctmapping_setup = PunctMappingSetupDialog()
512
513 self.__options = [
514 TrivalOption("General/MemoryPower", 3, self.__xml),
515 TrivalOption("General/PageSize", 10, self.__xml),
516 TrivalOption("General/MaxBest", 1, self.__xml),
517 TrivalOption("General/MaxTailCandidate", 0, self.__xml),
518
519 RadioOption("General/InitialStatus/Mode", 'Chinese', ['Chinese', 'English'], self.__xml),
520 RadioOption("General/InitialStatus/Punct", 'Full', ['Full', 'Half'], self.__xml),
521 RadioOption("General/InitialStatus/Letter", 'Half', ['Full', 'Half'], self.__xml),
522 RadioOption("General/Charset", 'GBK', ['GB2312', 'GBK', 'GB18030'], self.__xml),
523 CheckBoxOption("General/PunctMapping/Enabled", False, self.__xml),
524
525 RadioOption("Keyboard/ModeSwitch", 'Shift', ['Shift', 'Control'], self.__xml),
526 RadioOption("Keyboard/PunctSwitch", 'None', ['ControlComma',
527 'ControlPeriod',
528 'None'], self.__xml),
529 CheckBoxOption("Keyboard/Page/MinusEquals", False, self.__xml),
530 CheckBoxOption("Keyboard/Page/Brackets", False, self.__xml),
531 CheckBoxOption("Keyboard/Page/CommaPeriod", False, self.__xml),
532 CheckBoxOption("Keyboard/CancelBackspace", True, self.__xml),
533 CheckBoxOption("Keyboard/SmartPunct", True, self.__xml),
534
535 RadioOption("Pinyin/Scheme", 'QuanPin', ['QuanPin', 'ShuangPin'], self.__xml),
536 ComboBoxOption("Pinyin/ShuangPinType", 'MS2003', ['MS2003',
537 'ABC',
538 'ZiRanMa',
539 'Pinyin++',
540 'ZiGuang',
541 'XiaoHe'], self.__xml),
542 CheckBoxOption("QuanPin/Fuzzy/Enabled", False, self.__xml),
543 CheckBoxOption("QuanPin/AutoCorrection/Enabled", False, self.__xml),
544 CheckBoxOption("QuanPin/FuzzySegs/Enabled", False, self.__xml),
545 CheckBoxOption("QuanPin/InnerFuzzy/Enabled", False, self.__xml),
546
547 self.__fuzzy_setup,
548 self.__correction_setup,
549 self.__punctmapping_setup,
550 ]
551
552 def __get_option(self, name):
553 for opt in self.__options:
554 if opt.name == name:
555 return opt
556 else:
557 return None
558
559 def __read_config(self):
560 for opt in self.__options:
561 opt.init_ui()
562 opt.read_config()
563 self.on_chk_fuzzy_enabled_toggled(None)
564 self.on_chk_correction_enabled_toggled(None)
565 self.on_chk_punctmapping_enabled_toggled(None)
566 self.on_radio_shuangpin_toggled(None)
567
568 def __write_config(self):
569 for opt in self.__options:
570 opt.write_config()
571
572 def __update_enabling_button(self, checkbox_name, button_name):
573 """enable a setup button when checked, disable it otherwise
574 """
575 checkbox = self.__xml.get_object(checkbox_name)
576 assert checkbox is not None, "checkbox: %s not found" % checkbox_name
577 button = self.__xml.get_object(button_name)
578 assert button is not None, "button: %s not found" % button_name
579 button_enabled = checkbox.get_active()
580 button.set_sensitive(button_enabled)
581
582 def on_radio_shuangpin_toggled(self, button):
583 radio = self.__xml.get_object("Pinyin/Scheme/ShuangPin")
584 enabled = radio.get_active()
585 combo = self.__xml.get_object("Pinyin/ShuangPinType")
586 combo.set_sensitive(enabled)
587
588 def on_chk_fuzzy_enabled_toggled(self, button):
589 self.__update_enabling_button("QuanPin/Fuzzy/Enabled",
590 "button_fuzzy_setup")
591
592 def on_button_fuzzy_setup_clicked(self, button):
593 self.__fuzzy_setup.run(self.window)
594
595 def on_chk_correction_enabled_toggled(self, button):
596 self.__update_enabling_button("QuanPin/AutoCorrection/Enabled",
597 "button_correction_setup")
598
599 def on_chk_smartseg_enabled_toggled(self, button):
600 self.__update_enabling_button("QuanPin/FuzzySegs/Enabled",
601 "QuanPin/InnerFuzzy/Enabled")
602
603 def on_button_correction_setup_clicked(self, button):
604 self.__correction_setup.run(self.window)
605
606 def on_chk_punctmapping_enabled_toggled(self, button):
607 self.__update_enabling_button("General/PunctMapping/Enabled",
608 "button_punctmapping_setup")
609
610 def on_button_punctmapping_setup_clicked(self, button):
611 self.__punctmapping_setup.run(self.window)
612
613 def on_main_ok_clicked(self, button):
614 self.__write_config()
615 self.__quit()
616
617 def on_main_apply_clicked(self, button):
618 self.__write_config()
619
620 def on_main_cancel_clicked(self, button):
621 self.__quit()
622
623 def __quit(self):
624 gtk.main_quit()
625
626 if __name__ == "__main__":
627 MainWindow().run()
628
629 # -*- indent-tabs-mode: nil -*- vim:et:ts=4