PageRenderTime 311ms CodeModel.GetById 100ms app.highlight 73ms RepoModel.GetById 133ms app.codeStats 0ms

/python/helper/PinYinSetup/SetupUI.py

http://scim-python.googlecode.com/
Python | 300 lines | 248 code | 26 blank | 26 comment | 28 complexity | bb8efdf571f3deae3ad607c9a78b47e3 MD5 | raw file
  1# -*- coding: utf-8 -*-
  2# vim: set noet ts=4:
  3#
  4# scim-python
  5#
  6# Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
  7#
  8#
  9# This library is free software; you can redistribute it and/or
 10# modify it under the terms of the GNU Lesser General Public
 11# License as published by the Free Software Foundation; either
 12# version 2 of the License, or (at your option) any later version.
 13#
 14# This library is distributed in the hope that it will be useful,
 15# but WITHOUT ANY WARRANTY; without even the implied warranty of
 16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 17# GNU Lesser General Public License for more details.
 18#
 19# You should have received a copy of the GNU Lesser General Public
 20# License along with this program; if not, write to the
 21# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 22# Boston, MA  02111-1307  USA
 23#
 24# $Id: $
 25#
 26import os.path as path
 27import scim
 28import gobject
 29import gtk
 30import gtk.gdk as gdk
 31import gtk.glade as glade
 32import sys
 33
 34from gettext import dgettext
 35_ = lambda a : dgettext ("scim-python", a)
 36
 37try:
 38    from PYDict import *
 39except:
 40    pathname = path.dirname (__file__)
 41    pathname = path.abspath(pathname)
 42    pathname = path.join (pathname, "../../engine/PinYin")
 43    pathname = path.abspath(pathname)
 44    sys.path.append(pathname)
 45    from PYDict import *
 46
 47RGB_COLOR = lambda c : ((c.red & 0xff00) << 8) + (c.green & 0xff00) + ((c.blue & 0xff00) >> 8)
 48GDK_COLOR = lambda c : gdk.Color (((c >> 16) & 0xff) * 256, ((c >> 8) & 0xff) * 256, (c & 0xff) * 256)
 49RGB = lambda r, g, b : ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff)
 50
 51
 52class SetupUI ():
 53	def __init__ (self, helper_info):
 54		self._helper_info = helper_info
 55		self._helper_agent = scim.HelperAgent ()
 56		self._need_reload_config = False
 57		
 58		self._options = {
 59			"SupportGBK" :		[True, self._checkbutton_op],
 60			"ShuangPin" :		[False, self._checkbutton_op],
 61			"AutoCorrect" :		[True, self._checkbutton_op],
 62			#FuzzyPinYin Hacking by YW
 63			"FuzzyPinYin" :		[False, self._checkbutton_op],#0
 64			"FuzzyS_Sh" :		[False, self._checkbutton_op],#1
 65            "FuzzyC_Ch" :		[False, self._checkbutton_op],#2
 66            "FuzzyZ_Zh" :		[False, self._checkbutton_op],#3
 67            "FuzzyL_N" :		[False, self._checkbutton_op],#4
 68            "FuzzyIn_Ing" :		[False, self._checkbutton_op],#5
 69			"FuzzyEn_Eng" :		[False, self._checkbutton_op],#6
 70			"FuzzyAn_Ang" :		[False, self._checkbutton_op],#7
 71			
 72            "SpellCheck" :		[True, self._checkbutton_op],
 73			"UVToTemp" :		[True, self._checkbutton_op],
 74			"ShiftSelectCandidates" :
 75								[True, self._checkbutton_op],
 76			
 77			"CommaPageDownUp" :	[True, self._checkbutton_op],
 78			"EqualPageDownUp" :	[True, self._checkbutton_op],
 79			"AutoCommit" :		[False, self._checkbutton_op],
 80			
 81			"PhraseColor" :		[RGB (0, 0, 0), self._colorbutton_op],
 82			"NewPhraseColor" : 	[RGB (0xef, 0, 0), self._colorbutton_op],
 83			"UserPhraseColor" : [RGB (0, 0, 0xbf), self._colorbutton_op],
 84			"SpecialPhraseColor" :
 85								[RGB (0, 0xbf, 0), self._colorbutton_op],
 86			"EnglishPhraseColor" : 	[RGB (0, 0xbf, 0), self._colorbutton_op],
 87			"ErrorEnglishPhraseColor" : 
 88								[RGB (0xef, 0, 0), self._colorbutton_op],
 89			"PageSize" : 		[5, self._combobox_op, range (1, 10)],
 90			"ShuangPinSchema" : ["MSPY", self._combobox_op, SHUANGPIN_SCHEMAS.keys ()],
 91		}
 92
 93	def run (self, uuid, config, display):
 94		self._config = config
 95		self._uuid = uuid
 96		self._display = display
 97
 98		self._init_agent ()
 99		self._init_ui ()
100		self._load_config ()
101		gtk.main ()
102		if self._need_reload_config:
103			self._config.flush ()
104			self._helper_agent.reload_config ()
105		self._helper_agent.close_connection ()
106
107	def _combobox_op (self, name, opt, info):
108		widget = self._xml.get_widget (name)
109		if widget == None:
110			print >> sys.stderr, "Can not find widget %s" % name
111			return False
112		if opt == "read":
113			info[0] = self._read (name, info[0])
114			widget.set_active (info[2].index (info[0]))
115			return True
116		if opt == "write":
117			info[0] = info[2][widget.get_active ()]
118			self._write (name, info[0])
119			return True
120		if opt == "check":
121			return info[0] != info[2][widget.get_active ()]
122
123		if opt == "init":
124			model = gtk.ListStore (str)
125			for v in info[2]:
126				model.append ([_(str (v))])
127			widget.set_model (model)
128		return False
129	
130	def _colorbutton_op (self, name, opt, info):
131		widget = self._xml.get_widget (name)
132		if widget == None:
133			print >> sys.stderr, "Can not find widget %s" % name
134			return False
135		if opt == "read":
136			info[0] = self._read (name, info[0])
137			widget.set_color (GDK_COLOR (info[0]))
138			return True
139		if opt == "write":
140			info[0] = RGB_COLOR (widget.get_color ())
141			self._write (name, info[0])
142			return True
143		if opt == "check":
144			return info[0] != RGB_COLOR (widget.get_color ())
145		return False
146
147	def _checkbutton_op (self, name, opt, info):
148		widget = self._xml.get_widget (name)
149		if widget == None:
150			print >> sys.stderr, "Can not find widget %s" % name
151			return False
152
153		if opt == "read":
154			info[0] = self._read (name, info[0])
155			widget.set_active (info[0])
156			return True
157		if opt == "write":
158			info[0] = widget.get_active ()
159			self._write (name, info[0])
160			return True
161		if opt == "check":
162			return info[0] != widget.get_active ()
163		return False
164
165	def _read (self, name, v):
166		return self._config.read ("/IMEngine/Python/PinYin/" + name, v)
167	
168	def _write (self, name, v):
169		return self._config.write ("/IMEngine/Python/PinYin/" + name, v)
170	
171	def _init_ui (self):
172		glade.textdomain("scim-python")
173		glade_file = path.join (path.dirname (__file__), "SetupUI.glade")
174		self._xml = glade.XML (glade_file)
175		self._window = self._xml.get_widget ("window_main")
176		for name, info in self._options.items ():
177			info[1] (name, "init", info)
178			info[1] (name, "read", info)
179		self._xml.signal_autoconnect (self)
180		self._window.show_all ()
181
182	def _init_agent (self):
183		fd = self._helper_agent.open_connection (self._helper_info, self._display)
184		if fd >= 0:
185			condition = gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP
186			gobject.io_add_watch (fd, condition, self.on_agent_event)
187
188	def _load_config (self):
189		for name, info in self._options.items ():
190			info[1] (name, "read", info)
191
192	def _save_config (self):
193		self._need_reload_config = True
194		for name, info in self._options.items ():
195			info[1] (name, "write", info)
196	
197	def _query_changed (self):
198		for name, info in self._options.items ():
199			if info[1] (name, "check", info):
200				return True
201		return False
202	
203	def _quit (self, need_confirm ):
204		if need_confirm == False:
205			gtk.main_quit ()
206			return True
207		else:
208			dlg = gtk.MessageDialog (self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
209						gtk.BUTTONS_YES_NO, _("Are you sure to close Python PinYin Setup without save configure?"))
210			id = dlg.run ()
211			dlg.destroy ()
212			if id == gtk.RESPONSE_YES:
213				gtk.main_quit ()
214				return True
215		return False
216
217	def _optimize_user_db (self):
218		import sqlite3
219		dlg = gtk.MessageDialog (self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, 
220						gtk.BUTTONS_OK, _("The user phrases database will be reorganized! Please don't use python PinYin now."))
221		dlg.run ()
222		dlg.destroy ()
223		
224		try:
225			db = sqlite3.connect (path.expanduser ("~/.scim/scim-python/pinyin/user.db"))
226			sqlstring = """
227				BEGIN TRANSACTION;
228				CREATE TABLE tmp AS SELECT * FROM py_phrase;
229				DELETE FROM py_phrase;
230				INSERT INTO py_phrase SELECT * FROM tmp ORDER BY ylen, y0, y1, y2, y3, yx, phrase;
231				DROP TABLE tmp;
232				COMMIT;
233			"""
234			db.executescript (sqlstring)
235			db.executescript ("VACUUM;")
236		except:
237			import traceback
238			traceback.print_exc ()
239
240		dlg.destroy ()
241		dlg = gtk.MessageDialog (self._window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
242		                        gtk.BUTTONS_OK, _("Reorganizing is over!"))
243		dlg.run ()
244		dlg.destroy ()
245
246	# events handlers
247	def on_window_main_delete_event (self, widget, event):
248		result = self._quit (True)
249		return True
250	
251	def on_button_ok_clicked (self, button):
252		changed = self._query_changed ()
253		if changed:
254			self._save_config ()
255		self._quit (False)
256	
257	def on_button_apply_clicked (self, button):
258		self._save_config ()
259	
260	def on_button_cancel_clicked (self, button):
261		changed = self._query_changed ()
262		self._quit (changed)
263	
264	def on_button_optimize_db_clicked (self, button):
265		self._optimize_user_db ()
266
267	def on_value_changed (self, widget, data = None):
268		if self._query_changed ():
269			self._xml.get_widget ("button_apply").set_sensitive (True)
270		else:
271			self._xml.get_widget ("button_apply").set_sensitive (False)
272			
273	def on_agent_event (self, fd, condition):
274		
275		if condition == gobject.IO_IN:
276			while self._helper_agent.has_pending_event ():
277				self._helper_agent.filter_event ()
278			return True
279		
280		elif condition == gobject.IO_ERR or condition == gobject.IO_HUP:
281			gtk.main_quit ()
282			return False
283		
284		return False
285
286if __name__ == "__main__":
287	class CC:
288		def __init__ (self):
289			pass
290
291		def read (self, name, v):
292			return v
293		def write (self, name, v):
294			pass
295		def flush (self):
296			pass
297
298	helper_info = ("eebeecd7-cb22-48f4-8ced-70e42dad1a79", "", "", "", 1)
299	SetupUI (helper_info). run ("eebeecd7-cb22-48f4-8ced-70e42dad1a79", CC (), ":0.0")
300