#!/usr/bin/env python
#-------------------------------------------------
# this is a program that utilize the library of xdict.
# Made by Daniel Gau <r90057@im.ntu.edu.tw>
#-------------------------------------------------


# Client for the DICT protocol (RFC2229)
#
# Copyright (C) 2002 John Goerzen
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import socket, re

version = '1.0'

def dequote(str):
    """Will remove single or double quotes from the start and end of a string
    and return the result."""
    quotechars = "'\""
    while len(str) and str[0] in quotechars:
        str = str[1:]
    while len(str) and str[-1] in quotechars:
        str = str[0:-1]
    return str

def enquote(str):
    """This function will put a string in double quotes, properly
    escaping any existing double quotes with a backslash.  It will
    return the result."""
    return '"' + str.replace('"', "\\\"") + '"'

class Connection:
    """This class is used to establish a connection to a database server.
    You will usually use this as the first call into the dictclient library.
    Instantiating it takes two optional arguments: a hostname (a string)
    and a port (an int).  The hostname defaults to localhost
    and the port to 2628, the port specified in RFC."""
    def __init__(self, hostname = 'localhost', port = 2628):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((hostname, port))
        self.rfile = self.sock.makefile("rt")
        self.wfile = self.sock.makefile("wt", 0)
        self.saveconnectioninfo()

    def getresultcode(self):
        """Generic function to get a result code.  It will return a list
        consisting of two items: the integer result code and the text
        following.  You will not usually use this function directly."""
        line = self.rfile.readline().strip()
        code, text = line.split(' ', 1)
        return [int(code), text]

    def get200result(self):
        """Used when expecting a single line of text -- a 200-class
        result.  Returns [intcode, remaindertext]"""

        code, text = self.getresultcode()
        if code < 200 or code >= 300:
            raise Exception, "Got '%s' when 200-class response expected" % \
                  line
        return [code, text]

    def get100block(self):
        """Used when expecting multiple lines of text -- gets the block
        part only.  Does not get any codes or anything!  Returns a string."""
        data = []
        while 1:
            line = self.rfile.readline().strip()
            if line == '.':
                break
            data.append(line)
        return "\n".join(data)

    def get100result(self):
        """Used when expecting multiple lines of text, terminated by a period
        and a 200 code.  Returns: [initialcode, [bodytext_1lineperentry],
        finalcode]"""
        code, text = self.getresultcode()
        if code < 100 or code >= 200:
            raise Exception, "Got '%s' when 100-class response expected" % \
                  code

        bodylines = self.get100block().split("\n")

        code2 = self.get200result()[0]
        return [code, bodylines, code2]

    def get100dict(self):
        """Used when expecting a dictionary of results.  Will read from
        the initial 100 code, to a period and the 200 code."""
        dict = {}
        for line in self.get100result()[1]:
            key, val = line.split(' ', 1)
            dict[key] = dequote(val)
        return dict

    def saveconnectioninfo(self):
        """Called by __init__ to handle the initial connection.  Will
        save off the capabilities and messageid."""
        code, string = self.get200result()
        assert code == 220
        capstr, msgid = re.search('<(.*)> (<.*>)$', string).groups()
        self.capabilities = capstr.split('.')
        self.messageid = msgid
        
    def getcapabilities(self):
        """Returns a list of the capabilities advertised by the server."""
        return self.capabilities

    def getmessageid(self):
        """Returns the message id, including angle brackets."""
        return self.messageid

    def getdbdescs(self):
        """Gets a dict of available databases.  The key is the db name
        and the value is the db description.  This command may generate
        network traffic!"""
        if hasattr(self, 'dbdescs'):
            return self.dbdescs
        
        self.sendcommand("SHOW DB")
        self.dbdescs = self.get100dict()
        return self.dbdescs

    def getstratdescs(self):
        """Gets a dict of available strategies.  The key is the strat
        name and the value is the strat description.  This call may
        generate network traffic!"""
        if hasattr(self, 'stratdescs'):
            return self.stratdescs

        self.sendcommand("SHOW STRAT")
        self.stratdescs = self.get100dict()
        return self.stratdescs

    def getdbobj(self, dbname):
        """Gets a Database object corresponding to the database name passed
        in.  This function explicitly will *not* generate network traffic.
        If you have not yet run getdbdescs(), it will fail."""
        if not hasattr(self, 'dbobjs'):
            self.dbobjs = {}

        if self.dbobjs.has_key(dbname):
            return self.dbobjs[dbname]

        # We use self.dbdescs explicitly since we don't want to
        # generate net traffic with this request!

        if dbname != '*' and dbname != '!' and \
               not dbname in self.dbdescs.keys():
            raise Exception, "Invalid database name '%s'" % dbname

        self.dbobjs[dbname] = Database(self, dbname)
        return self.dbobjs[dbname]

    def sendcommand(self, command):
        """Takes a command, without a newline character, and sends it to
        the server."""
        self.wfile.write(command + "\n")

    def define(self, database, word):
        """Returns a list of Definition objects for each matching
        definition.  Parameters are the database name and the word
        to look up.  This is one of the main functions you will use
        to interact with the server.  Returns a list of Definition
        objects.  If there are no matches, an empty list is returned.

        Note: database may be '*' which means to search all databases,
        or '!' which means to return matches from the first database that
        has a match."""
        self.getdbdescs()               # Prime the cache

        #if database != '*' and database != '!' and database not in self.getdbdescs():
        #    raise Exception, "Invalid database '%s' specified" % database
        
        self.sendcommand("DEFINE " + enquote(database) + " " + enquote(word))
        code = self.getresultcode()[0]

        retval = []

        if code == 552:
            # No definitions.
            return []
        if code != 150:
            raise Exception, "Unknown code %d" % code

        while 1:
            code, text = self.getresultcode()
            if code != 151:
                break

            resultword, resultdb = re.search('^"(.+)" (\S+)', text).groups()
            defstr = self.get100block()
            retval.append(Definition(self, self.getdbobj(resultdb),
                                     resultword, defstr))
        return retval

    def match(self, database, strategy, word):
        """Gets matches for a query.  Arguments are database name,
        the strategy (see available ones in getstratdescs()), and the
        pattern/word to look for.  Returns a list of Definition objects.
        If there is no match, an empty list is returned.

        Note: database may be '*' which means to search all databases,
        or '!' which means to return matches from the first database that
        has a match."""
        self.getstratdescs()            # Prime the cache
        self.getdbdescs()               # Prime the cache
        if not strategy in self.getstratdescs().keys():
            raise Exception, "Invalid strategy '%s'" % strategy
        if database != '*' and database != '!' and \
               not database in self.getdbdescs().keys():
            raise Exception, "Invalid database name '%s'" % database

        self.sendcommand("MATCH %s %s %s" % (enquote(database),
                                             enquote(strategy),
                                             enquote(word)))
        code = self.getresultcode()[0]
        if code == 552:
            # No Matches
            return []
        if code != 152:
            raise Exception, "Unexpected code %d" % code

        retval = []

        for matchline in self.get100block().split("\n"):
            matchdict, matchword = matchline.split(" ", 1)
            retval.append(Definition(self, self.getdbobj(matchdict),
                                     dequote(matchword)))
        if self.getresultcode()[0] != 250:
            raise Exception, "Unexpected end-of-list code %d" % code
        return retval

class Database:
    """An object corresponding to a particular database in a server."""
    def __init__(self, dictconn, dbname):
        """Initialize the object -- requires a Connection object and
        a database name."""
        self.conn = dictconn
        self.name = dbname
    
    def getname(self):
        """Returns the short name for this database."""
        return self.name
    
    def getdescription(self):
        if hasattr(self, 'description'):
            return self.description
        if self.getname() == '*':
            self.description = 'All Databases'
        elif self.getname() == '!':
            self.description = 'First matching database'
        else:
            self.description = self.conn.getdbdescs()[self.getname()]
        return self.description
    
    def getinfo(self):
        """Returns a string of info describing this database."""
        if hasattr(self, 'info'):
            return self.info

        if self.getname() == '*':
            self.info = "This special database will search all databases on the system."
        elif self.getname() == '!':
            self.info = "This special database will return matches from the first matching database."
        else:
            self.conn.sendcommand("SHOW INFO " + self.name)
            self.info = "\n".join(self.conn.get100result()[1])
        return self.info

    def define(self, word):
        """Get a definition from within this database.
        The argument, word, is the word to look up.  The return value is the
        same as from Connection.define()."""
        return self.conn.define(self.getname(), word)

    def match(self, strategy, word):
        """Get a match from within this database.
        The argument, word, is the word to look up.  The return value is
        the same as from Connection.define()."""
        return self.conn.match(self.getname(), strategy, word)

class Definition:
    """An object corresponding to a single definition."""
    def __init__(self, dictconn, db, word, defstr = None):
        """Instantiate the object.  Requires: a Connection object,
        a Database object (NOT corresponding to '*' or '!' databases),
        a word.  Optional: a definition string.  If not supplied,
        it will be fetched if/when it is requested."""
        self.conn = dictconn
        self.db = db
        self.word = word
        self.defstr = defstr

    def getdb(self):
        """Get the Database object corresponding to this definition."""
        return self.db

    def getdefstr(self):
        """Get the definition string (the actual content) of this
        definition."""
        if not self.defstr:
            self.defstr = self.conn.define(self.getdb().getname(), self.word)[0].getdefstr()
        return self.defstr

    def getword(self):
        """Get the word this object describes."""
        return self.word

from gtk import *
from GDK import *
from string import split,replace,strip,lstrip,find,lower
import GtkExtra
import sys,os,string


prop = [" "," "," ","<<形容詞>>","<<副詞>>","art. ","<<連接詞>>","int.  ","<<名詞>>"," "," ","num. ", 	"prep. "," ","pron.  ","<<動詞>>","<<助動詞>>","<<非及物動詞>>","<<及物動詞>>","vbl. "," ","st. ", "pr. ","<<過去分詞>>","<<複數>>","ing. "," ","<<形容詞>>","<<副詞>>","pla. ","pn. "," "]

class Pref(GtkDialog):
    def __init__(self,modal=TRUE,app=None):
        GtkDialog.__init__(self)
	self.connect("destroy", self.quit)
	self.connect("delete_event", self.quit)
        self.set_title("設定")
	#variable
	self.app = app
	self.connect_status = 0
	self.database = None
	self.match_type = None
        #self.set_usize(400,400)

	#interface setup
	# ip input, port input
	hbox = GtkHBox(spacing=10)
	hbox.set_border_width(10)
	self.vbox.pack_start(hbox)
	hbox.show()
	label = GtkLabel("Dictd Server IP:")
	hbox.pack_start(label)
	label.show()
	self.ip_entry = GtkEntry()
	self.ip_entry.set_text(self.app.ip)
	hbox.pack_start(self.ip_entry)
	self.ip_entry.show()
	label = GtkLabel("Port:")
	hbox.pack_start(label)
	label.show()
	self.port_entry = GtkEntry()
	self.port_entry.set_usize(60,24)
	self.port_entry.set_max_length(5)
	self.port_entry.set_text(self.app.port)
	hbox.pack_start(self.port_entry)
	self.port_entry.show()
	##separator
	separator = GtkHSeparator()
	self.vbox.pack_start(separator, expand=FALSE)
	separator.show()
	##menu
	#dbmenu
	hbox = GtkHBox(spacing=10)
	hbox.set_border_width(10)
	self.vbox.pack_start(hbox)
	hbox.show()
        self.dbmenu = GtkOptionMenu()
        hbox.pack_start(self.dbmenu)
        self.dbmenu.show()	
	#matchmenu
        self.matchmenu = GtkOptionMenu()
        hbox.pack_start(self.matchmenu)
        self.matchmenu.show()	
	#button
        self.c_button = GtkButton("連結")
	self.c_button.grab_focus()
        self.c_button.connect("clicked", self.connect_dictd)
	self.action_area.pack_start(self.c_button)
        self.c_button.show()
        self.d_button = GtkButton("斷線")
        self.d_button.connect("clicked", self.disconnect_dictd)
        self.action_area.pack_start(self.d_button)
        button = GtkButton("確定")
        button.connect("clicked", self.okay)
        self.action_area.pack_start(button)
        button.show()
	button = GtkButton("取消")
	button.connect("clicked", self.quit)
	self.action_area.pack_start(button)
        #self.action_area.pack_start(button)
        button.show()
	self.ret = None

    #function for creating menus for db menu
    def create_dbmenu(self,dblist):
        if len(dblist) < 1: return None
        menu = GtkMenu()
	group = None
	##item for all database
	menuitem = GtkRadioMenuItem(group,"all")
	group = menuitem
	menuitem.connect("activate",self.menuitem_response,"*")
        menu.append(menuitem)
        menuitem.show()
	# other items
        for db in dblist:
                menuitem = GtkRadioMenuItem(group,db)
		menuitem.connect("activate",self.menuitem_response,'db',db)
		group = menuitem
                menu.append(menuitem)
                menuitem.show()
        return menu

    #function for creating menus for match menu
    def create_matchmenu(self,matchlist):
        if len(matchlist) < 1: return None
        menu = GtkMenu()
	group = None
	# other items
        for match in matchlist:
                menuitem = GtkRadioMenuItem(group,match)
		menuitem.connect("activate",self.menuitem_response,'match',match)
		group = menuitem
                menu.append(menuitem)
                menuitem.show()
        return menu

    # function when the menuitem is activated
    # args[0] is the menuitem object 
    # args[1] is the menuitem type
    # args[2] is the one at last of connect
    def menuitem_response(self,*args):
    	if len(args) == 3:
		if args[1] == 'db':
			self.database = args[2]
		else:
			self.match_type = args[2]

    #function for connect button
    def connect_dictd(self,*args):
    	self.app.ip = self.ip_entry.get_text()
    	self.app.port = self.port_entry.get_text()
	self.app.co = Connection(hostname=self.app.ip,port = int(self.app.port))
        self.dbmenu.set_menu(self.create_dbmenu(self.app.co.getdbdescs().keys()))
        self.matchmenu.set_menu(self.create_matchmenu(self.app.co.getstratdescs().keys()))
	self.database = '*'
	self.match_type = 'exact'
	self.c_button.hide()
	self.d_button.show()
	self.connect_staus = 1
		
    #disconnect the dictd server
    def disconnect_dictd(self,*args):
	self.d_button.hide()
	self.c_button.show()
	self.app.co = None
	self.connect_staus = 0
    	
    #function for okay button
    def okay(self,button):
    	self.app.ip = self.ip_entry.get_text()
    	self.app.port = self.port_entry.get_text()
	if self.app.co == None and self.connect_status == 1:
		self.app.co = Connection(hostname=self.app.ip,port = int(self.app.port))
	self.app.database = self.database
	self.app.match_type = self.match_type
	self.quit()

    #function for cancel button
    def quit(self,w=None,event=None):
    	self.hide()

class HelpDialog(GtkDialog):
    def __init__(self,modal=TRUE,file=None):
        GtkDialog.__init__(self)
	self.set_title("pyDict Help")
        self.connect("destroy", self.quit)
        self.connect("delete_event", self.quit)
        if modal:
            grab_add(self)
        box = GtkVBox(spacing=10)
        box.set_border_width(10)
        self.vbox.pack_start(box)
        box.show()
        self.swin = GtkScrolledWindow()
	self.swin.set_usize(500,300)
        box.pack_start(self.swin)
        self.swin.show()

	self.text = GtkText()
	self.swin.add(self.text)
	self.text.show()
	
	self.text.freeze()
	# get red color
	cmap = self.text.get_colormap()
	fg = cmap.alloc(65535,0,0)
	# read file in
	f = open(file,'r').readlines()
	for x in range(len(f)):
		# not pronunciation guide lines
		if f[x][0:3] != '   ':
			self.text.insert_defaults(f[x])
		# pronunciation guide lines
		else:
			for y in range(len(f[x])):
				if f[x][y] == '_' and y < len(f[x]) -3:
					if f[x][y+2] == '_':
						self.text.insert_defaults(f[x][0:y])
						self.text.insert(None,fg,None,f[x][y+1])
						self.text.insert_defaults(f[x][y+3:])
					elif f[x][y+3] == '_':
						self.text.insert_defaults(f[x][0:y])
						self.text.insert(None,fg,None,f[x][y+1:y+2])
						self.text.insert_defaults(f[x][y+4:])
	self.text.thaw()
	self.text.grab_focus()

        button = GtkButton("OK")
        button.connect("clicked", self.click)
        button.set_flags(CAN_DEFAULT)
        self.action_area.pack_start(button)
        button.show()
	self.ret = None

    def quit(self, w=None, event=None):
        self.hide()
        self.destroy()
    def click(self, button):
        self.quit()


class App(GtkWindow):
    def __init__(self):
        GtkWindow.__init__(self,WINDOW_TOPLEVEL)
        self.create_vars()
        self.create_boxes()
        self.create_widgets()

        self.connect("destroy",self.quit)
        self.connect("delete_event",self.quit)
        self.connect("key_press_event",self.rlookup)    

        self.entry.grab_focus()
        self.set_title("pyDict-0.2.6.1")
        self.set_usize(650,400)
        
    def create_vars(self):
        self.lookup_mode=0		# 0:English->Chinese  1:Chinese->English
        self.size_mode=1		# 1:large 0:small
        self.words = []
	self.index = 0			# initialize clistbox index        
	# dictd server related
	self.ip = "140.138.2.235"		# default dictd server ip
	self.port = "2628"		# default dictd server port
	#self.co = Connection(self.ip,self.port) # connection to dictd server
	self.pref = None		# Pref Dialog
	self.co = None			# Connection object
	self.match_type= 'exact'	# string matching type
	self.database = 'wn'		# database choose... could be *

    def create_boxes(self):
        self.b_large = GtkVBox()
        self.b_small = GtkVBox()
        self.add(self.b_large)
        self.small_win = GtkWindow(WINDOW_TOPLEVEL)
        self.small_win.add(self.b_small)
        self.b_small.show()
        self.b_large.show()	
        
    def create_widgets(self):
        #
	# create menubar
	#
        hdlbox = GtkHandleBox()
        self.b_large.pack_start(hdlbox,expand=FALSE)
        hdlbox.show()
        mf = GtkExtra.MenuFactory()
        mf.add_entries([
                ('檔案/離開', '<control>Q', self.quit),
                ('編輯/改變大小','<control>S',self.change_size),
                ('編輯/設定...', '<control>P',self.pref_setup),
                ('說明/說明...','<control>H',self.help_help),
                ('說明/關於...','<control>A',self.help_about),
        ])
        self.add_accel_group(mf.accelerator)
        hdlbox.add(mf)
        mf.show()
	#
	# create entrybox
	#
        hdlbox = GtkHandleBox()
        self.b_large.pack_start(hdlbox, expand=FALSE)
        hdlbox.show()
	hbox = GtkHBox()
	hdlbox.add(hbox)
	hbox.show()
	# create combobox for word entry and history
	self.combo = GtkCombo()
	hbox.pack_start(self.combo,expand=FALSE)
	self.combo.list.connect("button_press_event",self.word_his)
	self.combo.disable_activate()
	self.combo.show()
	# create entry
	self.entry = self.combo.entry
	self.entry.connect("key_press_event",self.lookup)
	#hbox.pack_start(self.entry,expand=FALSE)
	self.entry.show()
	# create commit button
	self.b_commit = GtkButton("Search")	
	self.b_commit.connect("clicked",self.lookup)
	hbox.pack_start(self.b_commit,expand=FALSE)
	self.b_commit.show()
	# create radiobutton
	self.rb_etoc = GtkRadioButton(None,"英翻中")
	hbox.pack_start(self.rb_etoc,expand=FALSE)
	self.rb_etoc.show()
        self.rb_ctoe = GtkRadioButton(self.rb_etoc,"中翻英")
	hbox.pack_start(self.rb_ctoe,expand=FALSE)
	self.rb_ctoe.show()
	# create smart toggle button
	self.tb_smart = GtkToggleButton("智慧模式")
	hbox.pack_start(self.tb_smart)
	self.tb_smart.show()
	# create scale button
	button = GtkButton("縮小")
	button.connect("clicked",self.change_size)
	hbox.pack_start(button)
	button.show()
	#
	# create listbox and explanation text
	#
	hbox = GtkHBox()
	self.b_large.pack_start(hbox)
	hbox.show()
	# create scrolledwindow for listbox
	swin = GtkScrolledWindow()
	swin.set_policy(POLICY_AUTOMATIC,POLICY_AUTOMATIC)
	swin.set_usize(200,400)
	hbox.pack_start(swin,expand=FALSE)
	swin.show()
	# create listbox
	self.clist= GtkCList(1)
	self.clist.set_column_width(0,180)
	self.clist.connect('select_row',self.select_list_word)
	self.clist.connect('key_press_event',self.move_list)
	swin.add(self.clist)
	self.clist.show()

	#create explanation text
	stwin = GtkScrolledWindow()
	stwin.set_policy(POLICY_AUTOMATIC,POLICY_AUTOMATIC)
	#stwin.set_usize(200,400)
	hbox.pack_start(stwin)
	stwin.show()

	self.text = GtkText()
        self.text.connect("button_press_event", self.text_click)
	self.text.set_events(GDK.KEY_PRESS_MASK)
	stwin.add(self.text)
	self.text.show()
	#
	# create a button for small hbox
	#
	button = GtkButton("pyDict-0.2.5.1")
	button.connect("clicked",self.change_size)
	self.b_small.pack_start(button,expand=FALSE)
	button.show()
	        
    def change_size(self, *args):
	if self.size_mode ==1:
		self.hide()
		self.small_win.show()
		self.size_mode = 0
	else:
		self.small_win.hide()
		self.show()
		self.size_mode = 1
		self.entry.grab_focus()

    def show_word(self,word):
	# initialize font
	style = self.text.get_style()
	try:
		#font = load_font("-urw-bookman-light-r-normal-*-*-140-*-*-p-*-iso8859-1")
		font = load_font('-schumacher-clean-medium-r-normal-*-*-140-*-*-c-*-iso646.1991-irv')
		newfont = TRUE
	except RuntimeError:
		newfont = FALSE
	# initialize red color
	cmap = self.text.get_colormap()
	fg = cmap.alloc(65535,0,0)
	#
	# freeze the text area
	#
	self.text.freeze()
        # clear the old one
	self.text.backward_delete(self.text.get_length())
       	# insert word
	self.text.insert_defaults(word['word']+'\n')
	# add mark if it exists
	if word.has_key('mark'):
		mark_string = '[' + word['mark'] + ']\n\n'
		if newfont:
			self.text.insert(font,None,None,mark_string)
		else:
			self.text.insert_defaults(mark_string)
	else:
		self.text.insert_defaults('\n')
	# show it in self.text
	for x in range(len(word['mean'])):
		index = find(word['mean'][x],'>>')
		if index != -1:
			# display red font
			self.text.insert(None,fg,None,word['mean'][x][:index+2])
			self.text.insert_defaults(word['mean'][x][index+2:]+'\n')
		else:
			self.text.insert_defaults(word['mean'][x]+ '\n')	
	# thaw the text area
	self.show_dictd_word(word['word'])
	self.text.thaw()
		
    def update_list(self):
	# show words in self.listbox
	self.clist.freeze()
	self.clist.clear()
	for i in range(len(self.words)):				
		self.clist.append((self.words[i]['word'],))
	self.clist.columns_autosize()
	self.clist.thaw()

    def execute(self,word,used=0):	# English to Chinese
		if(used == 0):
			# add the word to the history list
			item = GtkListItem(word)
			self.combo.list.prepend_items([item,])
			item.show()
		# move self.index to top
		self.index = 0
		command = g_command + ' -A 20 "^' + word + '.*=.*$" ' + dict_path + lower(word[0]) + '.lib' + '|awk "NR < 19 "'
		result_lines = os.popen(command,'r').readlines()
		#if result_lines:
		if result_lines:
			# initiate the word list
			self.words=[]
			for x in range(len(result_lines)):
				self.words.append(process_line(result_lines[x]))
			# show the first word in self.text
			self.show_word(self.words[0])
			self.update_list()
		else:
		        # clear the old one
			self.text.backward_delete(self.text.get_length())
			self.text.insert_defaults(word + ' not found in pydict!!\n')
			# add entries found in dict server
			self.show_dictd_word(word)


    def c_execute(self,word):		# chinese to English
		# move self.index to top
		self.index = 0
		pro_inp = ''
		inp = word
		num = len(inp)
		#esc_list = []
		#for x in range(33,128):
		#	esc_list.append(chr(x))
		for x in range(num):
			#if inp[x] in esc_list:
			if inp[x] == '\\':
				pro_inp = pro_inp + '\\\\\\' + inp[x]
			else:
				pro_inp = pro_inp + inp[x]

		command = g_command + ' -h ".*=.*' + pro_inp + '.*$" ' + dict_path + '*.lib'
		result_lines = os.popen(command,'r').readlines()
		#if result_lines:
		if result_lines:
			# initiate the word list
			self.words=[]
			for x in range(len(result_lines)):
				self.words.append(process_line(result_lines[x]))
			# show the first word in self.text
			self.show_word(self.words[0])
			# show words in self.listbox
			self.update_list()
		else:
		        # clear the old one
			self.text.backward_delete(self.text.get_length())
			self.text.insert_defaults(word + ' not found in pydict!!\n')

    def row_execute(self,word,up_down):		
	# roll_up or roll_down in clist 
	# up_down == 0 : up
	# up_down == 1 : down 
	command = g_command + ' -1 "^' + word + '.*=.*$" ' + dict_path + lower(word[0]) + '.lib' + '|awk "NR < 2 "'
	result_lines = os.popen(command,'r').readlines()
	# insert new word
	if up_down == 0:	# up
		command = g_command + ' -1 "^' + word + '.*=.*$" ' + dict_path + lower(word[0]) + '.lib' + '|awk "NR < 2 "'
		result_lines = os.popen(command,'r').readlines()
		self.words.insert(0,process_line(result_lines[0]))
		self.words.pop()
		self.show_word(self.words[0])
		self.clist.remove(len(self.words)-1)
		self.clist.insert(0,(self.words[0]['word'],))
	elif up_down == 1:
		command = g_command + ' -1 "^' + word + '.*=.*$" ' + dict_path + lower(word[0]) + '.lib' + '|tail -n 1'
		result_lines = os.popen(command,'r').readlines()
		self.words.append(process_line(result_lines[0]))
		temp = self.words.pop(0)
		self.show_word(self.words[len(self.words)-1])
		self.clist.remove(0)
		self.clist.append((self.words[len(self.words)-1]['word'],))
	#self.update_list()

	
    def lookup(self,*args):
        # args[0]: widget  args[1]: event
	# if self.lookup_mode == 0:			# English to Chinese
	# and if self.tb_smart.get_active() == 1:	# smart mode
	if self.rb_etoc.get_active() and self.tb_smart.get_active():
		if args[1].keyval <= 256:
			word = args[0].get_text() + chr(args[1].keyval)
			self.execute(lstrip(word))
		elif args[1].keyval == BackSpace:	#25688
			word = args[0].get_text()[:-1] 
			if word != '':
				self.execute(lstrip(word))
			else:
				self.clist.clear()
				# clear the old one
				self.text.backward_delete(self.text.get_length())
	# English to Chinese but no smart mode
	elif args[0] == self.b_commit or (self.rb_etoc.get_active() and args[1].keyval in (KP_Enter,Return)):
		word = strip(self.entry.get_text())	# trim white spaces
		self.execute(word)		
		self.entry.set_text(word)
		self.entry.select_region(0,-1)		# 0-->beginning 1-->end			
	# Chinese to English mode
	elif self.rb_ctoe.get_active():			# Chinese to English
		if args[0] == self.b_commit or args[1].keyval in (KP_Enter,Return):
			word = self.entry.get_text()
			self.c_execute(strip(word))
			self.entry.select_region(0,-1)		# 0-->beginning 1-->end 
	
    # begin input words when key press event is received.
    def rlookup(self,*args):
	if args[1].keyval == F1:
		self.help_help()
	elif args[1].keyval <= 256 or args[1].keyval == BackSpace:
		self.entry.grab_focus()

    def select_list_word(self,*args):
        # args[0]: widget   args[1]: row   args[2]: column  args[3]: event
        word = self.clist.get_text(args[1],args[2])
	# fine index of the word in self.words
	for x in self.words:
		if x['word'] == word:
			self.index = index = self.words.index(x)
			break
	# show the word
	self.show_word(self.words[index])
        
    def move_list(self,*args):
        # args[0]: widget   args[1]: event
        if args[1].keyval == 65362 and self.index != 0:		#KP_Up
        	self.clist.unselect_row(self.index,0)
        	self.index = self.index - 1
        	self.clist.select_row(self.index,0)
        	self.select_list_word(None,self.index,0,None)
	elif args[1].keyval == 65362 and self.index == 0 and self.rb_etoc.get_active(): #go up
		self.row_execute(self.words[0]['word'],0)
		self.clist.unselect_row(self.index,0)
		self.clist.select_row(0,0)
        elif args[1].keyval == 65364 and self.index < len(self.words)-1:		#KP_Down         
		self.clist.unselect_row(self.index,0)
         	self.index = self.index + 1
        	self.clist.select_row(self.index,0)
        	self.select_list_word(None,self.index,0,None)
	elif args[1].keyval == 65364 and self.index == len(self.words) -1 and self.rb_etoc.get_active(): # go down
		self.row_execute(self.words[len(self.words)-1]['word'],1)
		self.clist.unselect_row(self.index,0)
		self.clist.select_row(len(self.words)-1,0)
        elif args[1].keyval == 65365 and self.index -5 >= 0:		#KP_Page_Up
        	self.clist.unselect_row(self.index,0)
        	self.index = self.index -5
        	self.clist.select_row(self.index,0)
        	self.select_list_word(None,self.index,0,None)
        elif args[1].keyval == 65366 and self.index + 5 < len(self.words)-1:		#KP_Page_Down 	
        	self.clist.unselect_row(self.index,0)
        	self.index = self.index + 5
        	self.clist.select_row(self.index,0)
        	self.select_list_word(None,self.index,0,None)

    def show_dictd_word(self,word):
    	if self.co != None:
		result = self.co.match(self.database,self.match_type,word)
		# initialize red color
		cmap = self.text.get_colormap()
		yellow = cmap.alloc(40000,40000,0)
		blue = cmap.alloc(0,0,65535)
		# freeze texxt area
		self.text.freeze()
		# begin insert
		self.text.insert(None,yellow,None,'\nfound %s results:\n' % (len(result)))
		for r in result:
			focus = 0
			sync = 0
			lines = r.getdefstr()
			# show text without enhanced display
			if r.getdb().getname() not in ['wn','webster']:
				self.text.insert_defaults(lines + '\n\n')
			else:
				## check for special characters
				for l in range(len(lines)):
					ch = lines[l]
					if ch not in ['[','{','}',']'] and sync == 0 and focus == 0: 
						self.text.insert_defaults(ch)
					elif ch == '}':
						focus = 0
						#self.text.insert_defaults(' ')
					elif ch == '[' and lines[l+1:l+4] == 'syn':
						sync = 1
						self.text.insert_defaults('\n' + 'synonym: ')
					elif ch == ']':
						sync = 0
						self.text.insert_defaults('\n')
					elif ch == '{':
						focus = 1
					elif focus == 1:
						self.text.insert(None,blue,None,ch)
					elif ch == ',':
						self.text.insert_defaults(ch)
							
				self.text.insert_defaults('\n\n')
		# end insert
		self.text.thaw()

    def text_click(self,win, event):
	letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
	pos = win.get_position()
	if pos == 0:
		return
	word = ''
	# find the back part of the word
	i = 1
	while  self.text.get_chars(pos+i-1,pos+i) in letters and i < self.text.get_length():
		word = word + self.text.get_chars(pos+i-1,pos+i) 
		i = i + 1
	# find the front part of the word
	i = 1
	while  self.text.get_chars(pos-i,pos-i+1) in letters and i < self.text.get_length():
		word = self.text.get_chars(pos-i,pos-i+1) + word
		i = i + 1
	# check if a word is selected
	if word == '':
		return
	self.execute(word)
	self.entry.set_text(word)
	self.entry.select_region(0,-1)		# 0-->beginning 1-->end			

    def quit(self,*args):
        mainquit()

    def word_his(self,*args):
	self.execute(self.entry.get_text(),used=1)

    def help_about(self,mi=None):
	GtkExtra.message_box("pyDict v0.2.6.1",
	"""pyDict v0.2.6.1
	Made by Daniel Gau
	<r90057@im.ntu.edu.tw>
	for my lovely wife, Cecile Ho.
	""",("OK",),pixmap='/usr/local/lib/X11/pyDict/yaba.xpm')
	
    def help_help(self,mi=None):
	hd = HelpDialog(file = "/usr/local/lib/X11/pyDict/HELP")
	hd.show()

    def pref_setup(self,mi=None):
    	if self.pref == None:
    		self.pref = Pref(app=self)
	self.pref.show()
	
# change proposition
def change_prop(str):
	start=0
	end=0
	mean_list = []
	tmp = str
	for x in range(len(prop)):
		tmp = replace(tmp,chr(x),'@@'+prop[x])
	return tmp

# display soundmarks
def change_pron(str):
	tmp = ''
	for x in range(len(str)):
		if str[x] == chr(0x01):
			tmp = tmp + 'I'
		elif str[x] == chr(0x02):
			tmp = tmp + 'E'
		elif str[x] == chr(0x03):
			tmp = tmp + 'ae'
		elif str[x] == chr(0x04):
			tmp = tmp + 'a'
		elif str[x] == chr(0x06):
			tmp = tmp + 'c'
		elif str[x] == chr(0x0b):
			tmp = tmp + '8'
		elif str[x] == chr(0x0e):
			tmp = tmp + 'U'
		elif str[x] == chr(0x0f):
			tmp = tmp + '^'
		elif str[x] == chr(0x10):
			tmp = tmp + '2'
		elif str[x] == chr(0x11):
			tmp = tmp + '2*'
		elif str[x] == chr(0x13):
			tmp = tmp + '2~'
		elif str[x] == chr(0x17):
			tmp = tmp + 'l.'
		elif str[x] == chr(0x19):
			tmp = tmp + 'n_'
		elif str[x] == chr(0x1c):
			tmp = tmp + '&'
		elif str[x] == chr(0x1d):
			tmp = tmp + 'S'
		elif str[x] == chr(0x1e):
			tmp = tmp + '3'
		elif str[x] == chr(0x65) and x == 0:
			pass
		else:
			tmp = tmp + str[x]
	return tmp

# transform line to word, meanning_list, mark	
def process_line(str):
    temp = {}
    split_word = split(str,'=')
    temp['word'] = split_word[0]
    lines = split(change_prop(split_word[1]),'@@')
    temp['mean'] = lines
    if len(split_word) == 3 and split_word[2] != '\n':
        temp['mark'] = change_pron(split_word[2][:-1])
    return temp
        
    	
# run English-Chinese under console

def console_e_dict(input=None):
	#set up g_command
	g_command = '/usr/bin/grep -s --ignore-case'
	if input == None:
		inp = raw_input('word:')
	else:
		inp = input
		
	while 1:
		if inp == '-q' or inp == '':
			return
		elif inp == '-e':
			pass
		elif inp == '-c':
			console_c_dict()
			return
		else:	
			command = g_command + " '^" + inp + "=.*$' " + dict_path + lower(inp[0]) + '.lib'
			result_line = os.popen(command,'r').readline()
			#if result_lines:
			if result_line:
				line = result_line
				word = process_line(line)
				# insert word
				print word['word'] 
				# add mark if it exists
				if word.has_key('mark'):
					mark_string = '[' + word['mark'] + ']'
					print mark_string + '\n' 
				else:
					print '\n'
				# show it in self.text
				for x in range(len(word['mean'])):
					print word['mean'][x] 	
				print 		
			else:
				print 'Not found'
			# only execute once
			if input != None:
				return
			inp = raw_input('word:')
        
# run Chinese-English under console

def console_c_dict(input=None):
	#set up g_command
	g_command = '/usr/bin/grep -s'
	if input == None:
		inp = raw_input('word:')
	else:
	    inp = input

	while 1:
		pro_inp = ''
		if inp == '-q' or inp == '':
			return	
		elif inp == '-c':
			pass
		elif inp == '-e':
			console_e_dict()
			return
		else:
			# fixing Chinese Escape character
			num = len(inp)
			for x in range(num):
				if inp[x] == '\\':
					pro_inp = pro_inp + '\\\\\\' + inp[x]
				else:
					pro_inp = pro_inp + inp[x]

			command = g_command + ' -h ".*=.*' + pro_inp + '.*$" ' + dict_path + '*.lib'
			result_lines = os.popen(command,'r').readlines()
			#if result_lines:
			if result_lines != None:
				for line in result_lines:
					word = process_line(line)
					# insert word
					print word['word'] 
					# add mark if it exists
					if word.has_key('mark'):
						mark_string = '[' + word['mark'] + ']'
						print mark_string + '\n'
					else:
						print '\n'
					# show it in self.text
					for x in range(len(word['mean'])):
						print word['mean'][x] 	
					print 		
			else:
				print 'Not found'
			if input != None:
				return
			inp = raw_input('word:')
if __name__ == '__main__':
    Usage ="""
pydict [options] [word]

options:
  -h		print out this help
  -i		console interactive mode
  -e [word]	English-Chinese mode(Default value)
  -c [word]	Chinese-English mode
  -q		Exit
    """

    def Header():
	# print title
	print '#----------------------------------------------------#'
	print '#  pyDict-0.2.6.1  Made by Daniel Gau(plateau)       #'
	print '#----------------------------------------------------#'
	print

	print 'type -q to leave'
	print 'type -c to Chinese-English mode'
	print 'type -e to English-Chinese mode'

    # set up grep command
    g_command = '/usr/bin/grep -s --ignore-case'
    dict_path = '/usr/local/lib/X11/pyDict/'

    # check if there is an DISPLAY environment variable
    if os.environ.has_key('DISPLAY') and len(sys.argv) == 1:
	app = App()
	app.show()
	mainloop()
    # if there isn't, then check the variable
    # the default is console English-Chinese mode.
    elif len(sys.argv) == 1:
	Header()
        console_e_dict(None)
    # two parameter. 
    elif len(sys.argv) == 2:
	if sys.argv[1] == '-i' or sys.argv[1] == '-e':
		Header()
        	console_e_dict(None)
	elif sys.argv[1] == '-c':
		Header()
        	console_c_dict(None)
	elif sys.argv[1] == '-h':
		print Usage
	else:
		console_e_dict(sys.argv[1])
    elif len(sys.argv) == 3:
	if sys.argv[1] == '-e':
        	console_e_dict(sys.argv[2])
	elif sys.argv[1] == '-c':
        	console_c_dict(sys.argv[2])
    else:
	print Usage
		
        
    
