]*>", "\t", data)
data = re.sub (" *\n", "\n", data)
lines = string.split (data, "\n")
output = []
for line in lines:
if line == "":
indent = indent + 1
elif line == " ":
indent = indent - 1
if indent < 0: indent = 0
elif line == "":
center = center + 1
elif line == "":
center = center - 1
if center < 0: center = 0
else:
if center:
line = " "*indent + string.strip(line)
nline = re.sub("\[.*?m", "", line)
nline = re.sub ("<[^>]*>", "", nline)
c = WIDTH/2 - (len (nline) / 2)
output.append (" "*c + line)
else:
output.append (" "*indent + line)
data = string.join (output, "\n")
data = re.sub (" *\n", "\n", data)
data = re.sub ("\n\n\n*", "\n\n", data)
data = re.sub ("<[^>]*>", "", data)
return (data, center, indent)
def html2text (data, use_ansi = 0, is_latin1 = 0):
pre = re.split("(?s)([^<]* )", data)
out = []
indent = 0
center = 0
for part in pre:
if part[:5] != "":
(res, center, indent) = tag_replace (part,center,indent, use_ansi)
out.append (res)
else:
part = re.sub("(?i)*pre>", "", part)
out.append (part)
data = string.join (out)
data = re.sub (">", ">", data)
data = re.sub ("<", "<", data)
data = re.sub (" ", " ", data)
return data
def usage(progname):
print "usage: %s --help " % progname
print __doc__
def main(argc, argv):
progname = argv[0]
alist, args = getopt.getopt(argv[1:], "", ["help"])
for (field, val) in alist:
if field == "--help":
usage(progname)
return
if len(args):
file = args[0]
else:
return
progname = argv[0]
fp = open (file)
data = fp.read()
fp.close()
if data:
print (html2text(data))
else:
print "Document contained no data"
if __name__ == "__main__":
main(len(sys.argv), sys.argv)
opendict-0.6.8/lib/gui/ 0000775 0000764 0000764 00000000000 13204646653 014627 5 ustar nerijus nerijus opendict-0.6.8/lib/gui/__init__.py 0000664 0000764 0000764 00000000000 13204646653 016726 0 ustar nerijus nerijus opendict-0.6.8/lib/gui/dictaddwin.py 0000664 0000764 0000764 00000006375 13204646653 017326 0 ustar nerijus nerijus # -*- coding: utf-8 -*-
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# Module: gui.dictaddwin
import wx
from lib import misc
_ = wx.GetTranslation
# IDs range: 6300-6310
class DictAddWindow(wx.Dialog):
def __init__(self, parent, fname, filePath):
wx.Dialog.__init__(self, parent, -1,
_("Add new dictionary"), wx.DefaultPosition,
wx.DefaultSize, wx.DEFAULT_DIALOG_STYLE)
self.filePath = filePath
vboxMain = wx.BoxSizer(wx.VERTICAL)
msg1 = _("The file format of \"%s\" could not be \nrecognized by its" \
" extention. Please select one\nfrom the list:") % fname
label1 = wx.StaticText(self, -1, msg1)
vboxMain.Add(label1, 0, wx.ALL | wx.EXPAND, 5)
choices = [misc.dictFormats["zip"], # OpenDict plugin
_("\"%s\" dictionary format") % misc.dictFormats["dwa"],
_("\"%s\" dictionary format") % misc.dictFormats["mova"],
_("\"%s\" dictionary format") % misc.dictFormats["tmx"],
_("\"%s\" dictionary format") % misc.dictFormats["dz"]]
self.box = wx.ListBox(self, -1, wx.Point(-1, -1),
wx.Size(-1, -1), choices, wx.LB_SINGLE)
vboxMain.Add(self.box, 1, wx.ALL | wx.EXPAND, 3)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
buttonOK = wx.Button(self, wx.ID_OK, _("OK"))
hboxButtons.Add(buttonOK, 0, wx.ALL, 1)
buttonCancel = wx.Button(self, 6302, _("Cancel"))
hboxButtons.Add(buttonCancel, 0, wx.ALL, 1)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.CENTER, 2)
self.SetSizer(vboxMain)
self.Fit()
wx.EVT_BUTTON(self, wx.ID_OK, self.onOK)
wx.EVT_BUTTON(self, 6302, self.onCancel)
def onOK(self, event):
parent = self.GetParent()
i = self.box.GetSelection()
ext = ""
if i == 0:
ext = "zip"
elif i == 1:
ext = "dwa"
elif i == 2:
ext = "mova"
elif i == 3:
ext = "tmx"
elif i == 4:
ext == "dz"
from installer import Installer
installer = Installer(parent, parent.app.config)
installer.install(self.filePath, ext)
self.Destroy()
def onCancel(self, event):
self.GetParent().dictType = None
self.Destroy()
opendict-0.6.8/lib/gui/dictconnwin.py 0000664 0000764 0000764 00000025066 13204646653 017531 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
import wx
from wx.lib.rcsizer import RowColSizer
import traceback
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
from lib.parser import DictConnection
from lib.extra import dictclient
from lib.threads import Process
from lib.gui import errorwin
from lib import misc
_ = wx.GetTranslation
CONNECTION_CHECK_INTERVAL = 400
class DictConnWindow(wx.Frame):
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.parent = parent
self.app = wx.GetApp()
vboxMain = wx.BoxSizer(wx.VERTICAL)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
hboxServer = RowColSizer()
#
# Server address row
#
hboxServer.Add(wx.StaticText(self, -1, _("Server: ")),
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
row=0, col=0, border=1)
servers = ['dict.org', 'localhost']
self.entryServer = wx.ComboBox(self, -1,
self.app.config.get('dictServer'), wx.Point(-1, -1),
wx.Size(-1, -1), servers, wx.CB_DROPDOWN)
hboxServer.Add(self.entryServer, flag=wx.EXPAND, row=0, col=1, border=1)
hboxServer.Add(wx.Button(self, 1000, _("Default Server")),
flag=wx.EXPAND, row=0, col=2, border=5)
#
# Port entry row
#
hboxServer.Add(wx.StaticText(self, -1, _("Port: ")),
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
row=1, col=0, border=1)
hboxServer.Add(wx.Button(self, 1001, _("Default Port")),
flag=wx.EXPAND, row=1, col=2, border=5)
self.entryPort = wx.TextCtrl(self, -1,
self.app.config.get('dictServerPort'))
hboxServer.Add(self.entryPort, flag=wx.EXPAND, row=1, col=1, border=1)
#
# Database selection row
#
hboxServer.Add(wx.StaticText(self, -1, _("Database: ")),
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
row=2, col=0, border=1)
self.msgSearchInAll = _("Search in all databases")
self.choiceDB = wx.ComboBox(self, 1002, self.msgSearchInAll,
choices=[self.msgSearchInAll],
style=wx.TE_READONLY)
self.choiceDB.SetInsertionPoint(0)
hboxServer.Add(self.choiceDB, flag=wx.EXPAND, row=2, col=1, border=1)
hboxServer.Add(wx.Button(self, 1003, _("Fetch List")), #size=(-1, 18)),
flag=wx.EXPAND, row=2, col=2, border=1)
#
# Encoding selection row
#
hboxServer.Add(wx.StaticText(self, -1, _("Character encoding: ")),
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
row=3, col=0, border=1)
self.entryEncoding = wx.ComboBox(self, 1006,
misc.encodings.keys()[
misc.encodings.values().index(
self.app.config.get('dict-server-encoding'))],
wx.Point(-1, -1),
wx.Size(-1, -1), misc.encodings.keys(),
wx.CB_DROPDOWN | wx.CB_READONLY)
hboxServer.Add(self.entryEncoding, flag=wx.EXPAND, row=3, col=1, border=1)
#hboxServer.Add(wx.StaticText(self, -1, _("Strategy: ")),
# flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
# row=3, col=0, rowspan=1, border=1)
#
#self.choiceStrat = wx.ComboBox(self, 1006, #size=(-1, 20),
# choices=[])
#hboxServer.Add(self.choiceStrat, flag=wx.EXPAND, row=3, col=1,
# rowspan=1, border=1)
#
#hboxServer.Add(wx.Button(self, 1007, _("Update")), #size=(-1, 18)),
# flag=wx.EXPAND, row=3, col=2, border=5)
hboxServer.AddGrowableCol(1)
vboxMain.Add(hboxServer, 1, wx.ALL | wx.EXPAND, 4)
self.buttonOK = wx.Button(self, 1004, _("Connect"))
hboxButtons.Add(self.buttonOK, 0, wx.ALL, 1)
self.buttonCancel = wx.Button(self, 1005, _("Cancel"))
hboxButtons.Add(self.buttonCancel, 0, wx.ALL, 1)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_CENTER, 2)
self.CreateStatusBar()
self.SetSizer(vboxMain)
self.Fit()
self.SetSize((500, -1))
self.timerUpdateDB = wx.Timer(self, 1006)
self.timerConnect = wx.Timer(self, 1007)
self.update = None
self.connection = None
wx.EVT_BUTTON(self, 1000, self.onDefaultServer)
wx.EVT_BUTTON(self, 1001, self.onDefaultPort)
wx.EVT_BUTTON(self, 1003, self.onUpdateDB)
wx.EVT_BUTTON(self, 1007, self.onUpdateStrats)
wx.EVT_BUTTON(self, 1004, self.onOK)
wx.EVT_BUTTON(self, 1005, self.onCancel)
wx.EVT_TIMER(self, 1006, self.onTimerUpdateDB)
wx.EVT_TIMER(self, 1007, self.onTimerConnect)
def onTimerUpdateDB(self, event):
systemLog(DEBUG, "DictConnection: [IDLE] Receiving DB list...")
if self.update != None:
if self.update.isDone():
systemLog(DEBUG, "DictConnection: DB list received")
obj = self.update()
if type(obj) == type({}):
self.timerUpdateDB.Stop()
self.update = None
self.choiceDB.Clear()
self.choiceDB.Append(self.msgSearchInAll)
for name in obj.values():
self.choiceDB.Append(name)
self.SetStatusText(_("Done"))
self.choiceDB.SetValue(self.msgSearchInAll)
self.choiceDB.SetInsertionPoint(0)
elif obj != None:
self.SetStatusText(_("Receiving database list..."))
self.update = Process(obj.getdbdescs)
else:
self.timerUpdateDB.Stop()
self.SetStatusText('')
title = _("Connection Error")
msg = _("Unable to connect to server")
errorwin.showErrorMessage(title, msg)
def onTimerConnect(self, event):
if self.connection != None:
if self.connection.isDone():
systemLog(INFO, "Connection timer stopped")
self.timerConnect.Stop()
self.conn = self.connection()
if self.conn == None:
self.SetStatusText('')
title = _("Connection Error")
msg = _("Unable to connect to server")
errorwin.showErrorMessage(title, msg)
else:
self.prepareForUsing()
def onDefaultServer(self, event):
self.entryServer.SetValue("dict.org")
def onDefaultPort(self, event):
self.entryPort.SetValue("2628")
def onUpdateDB(self, event):
self.SetStatusText(_("Connecting..."))
self.timerUpdateDB.Start(CONNECTION_CHECK_INTERVAL)
self.update = Process(dictclient.Connection,
self.entryServer.GetValue(),
int(self.entryPort.GetValue()))
# not used, remove
def onUpdateStrats(self, event):
conn = dictclient.Connection()
strats = conn.getstratdescs()
for name in strats.values():
self.choiceStrat.Append(name)
# Thread is not used there, because program don't hang if can't
# connect. Otherwise, it may hang for a second depending on the
# connection speed. TODO: better solution?
def onOK(self, event):
self.server = self.entryServer.GetValue()
self.app.config.set('dictServer', self.server)
self.port = self.entryPort.GetValue()
encName = self.entryEncoding.GetValue()
try:
enc = misc.encodings[encName]
except KeyError:
print 'Error: invalid encoding name "%s", defaulting to UTF-8' % \
encName
enc = 'UTF-8'
self.encoding = (enc, encName)
self.timerConnect.Stop()
self.timerUpdateDB.Stop()
self.SetStatusText(_("Connecting to %s...") % self.server)
self.timerConnect.Start(CONNECTION_CHECK_INTERVAL)
self.connection = Process(dictclient.Connection,
self.server, int(self.port))
def prepareForUsing(self):
"""Prepare MainWindow for displaying data"""
systemLog(INFO, "DictConnection: Connected, preparing main window...")
db = self.choiceDB.GetValue()
if self.choiceDB.FindString(db) == 0:
db = "*"
db_name = ""
else:
try:
dbs = self.conn.getdbdescs()
for d in dbs.keys():
if dbs[d] == db:
db = d
db_name = dbs[db]
except:
traceback.print_exc()
self.app.window.SetStatusText(misc.errors[4])
return
self.app.window.onCloseDict(None)
self.app.window.activeDictionary = DictConnection(self.server,
int(self.port),
db, "")
self.app.config.set('dict-server-encoding', self.encoding[0])
self.parent.changeEncoding(self.encoding[1])
if db_name != "":
title = "OpenDict - %s (%s)" % (self.server, db_name)
else:
title = "OpenDict - %s" % self.server
self.app.window.SetTitle(title)
self.app.window.checkEncMenuItem(self.encoding[0])
if not self.app.window.activeDictionary.getUsesWordList():
self.app.window.hideWordList()
self.app.window.SetStatusText("")
self.timerUpdateDB.Stop()
self.Destroy()
def onCancel(self, event):
self.timerUpdateDB.Stop()
self.timerConnect.Stop()
self.Destroy()
opendict-0.6.8/lib/gui/dicteditorwin.py 0000664 0000764 0000764 00000051132 13204646653 020053 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# TODO: not usable yet, needs some work with encodings, gui, etc.
from wx.lib.rcsizer import RowColSizer
import wx
import os
import codecs
import traceback
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
from lib.misc import encodings, printError
from lib.parser import TMXParser
from lib.gui import errorwin
from lib import info
from lib import dicteditor
from lib import enc
_ = wx.GetTranslation
class EditWordWindow(wx.Frame):
"""Word editor window"""
def __init__(self, word, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
vboxMain = wx.BoxSizer(wx.VERTICAL)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
self.boxInfo = RowColSizer()
self.boxInfo.Add(wx.StaticText(self, -1, _("Word: "), pos=(-1, -1)),
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
row=0, col=0, border=1)
self.entryWord = wx.TextCtrl(self, -1, word)
self.entryWord.Disable()
self.boxInfo.Add(self.entryWord, flag=wx.EXPAND,
row=0, col=1, border=1)
self.transLabels = {}
self.textEntries = {}
unit = parent.editor.getUnit(word)
if unit:
translations = unit.getTranslations()
for trans in translations:
comment = translations[trans]
if comment:
transcomm = u"%s // %s" % (trans, comment)
else:
transcomm = trans
transcomm = enc.toWX(transcomm)
self.onAddEmptyField(None)
entry = self.textEntries.get(max(self.textEntries.keys()))
if entry:
entry.SetValue(transcomm)
self.boxInfo.AddGrowableCol(1)
vboxMain.Add(self.boxInfo, 1, wx.ALL | wx.EXPAND, 2)
idAdd = wx.NewId()
self.buttonAdd = wx.Button(self, idAdd, _("Add translation field"))
vboxMain.Add(self.buttonAdd, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
self.buttonOK = wx.Button(self, 6050, _("OK"))
hboxButtons.Add(self.buttonOK, 0, wx.ALL, 1)
self.buttonCancel = wx.Button(self, 6051, _("Cancel"))
hboxButtons.Add(self.buttonCancel, 0, wx.ALL, 1)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
self.SetSizer(vboxMain)
self.Fit()
self.SetSize((500, -1))
self.Bind(wx.EVT_BUTTON, self.onAddEmptyField, self.buttonAdd)
self.Bind(wx.EVT_BUTTON, self.onSave, self.buttonOK)
self.Bind(wx.EVT_BUTTON, self.onClose, self.buttonCancel)
def onAddEmptyField(self, event):
"""Add empty translation field"""
transLabel = wx.StaticText(self, -1, _("Translation #%d: ") \
% (len(self.textEntries)+1))
self.transLabels[len(self.transLabels)] = transLabel
self.boxInfo.Add(transLabel,
flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTRE_VERTICAL,
row=len(self.transLabels), col=0, border=1)
text = wx.TextCtrl(self, -1,
"",
size=(100, -1))
self.textEntries[len(self.textEntries)] = text
self.boxInfo.Add(text, flag=wx.EXPAND,
row=len(self.textEntries),
col=1, border=1)
self.Fit()
self.SetSize((500, -1))
def onSave(self, event):
"""Apply changes"""
parent = self.GetParent()
word = enc.fromWX(self.entryWord.GetValue())
translations = []
for label in self.textEntries.values():
translations.append(enc.fromWX(label.GetValue()))
transcomm = {}
for translation in translations:
if not len(translation.strip()):
continue
chunks = translation.split('//', 1)
if len(chunks) == 2:
t = chunks[0]
c = chunks[1]
else:
t = chunks[0]
c = None
transcomm[t] = c
parent.editor.getUnit(word).setTranslations(transcomm)
parent.setChanged(True)
parent.checkAllButtons()
self.Destroy()
def onClose(self, event):
"""Close window withous saveing changes"""
self.Destroy()
# IDs range: 6000-6200
class DictEditorWindow(wx.Frame):
"""Built-in dictionary editor. This tool lets user create and
manage his own dictionaries in TMX format."""
class AddWordWindow(EditWordWindow):
"""Window for adding new word"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
EditWordWindow.__init__(self, '', parent, id, title, pos,
size, style)
self.entryWord.Enable(1)
self.onAddEmptyField(None)
def onSave(self, event):
"""Apply changes"""
parent = self.GetParent()
word = enc.fromWX(self.entryWord.GetValue())
translations = []
for label in self.textEntries.values():
translations.append(enc.fromWX(label.GetValue()))
transcomm = {}
for translation in translations:
if not len(translation.strip()):
continue
chunks = translation.split('//', 1)
if len(chunks) == 2:
t = chunks[0]
c = chunks[1]
else:
t = chunks[0]
c = None
transcomm[t] = c
unit = dicteditor.Translation()
unit.setWord(word)
unit.setTranslations(transcomm)
parent.editor.addUnit(unit)
parent.list.Append(enc.toWX(word))
parent.setChanged(True)
parent.checkAllButtons()
self.Destroy()
# IDs range: 6000-6003
class ConfirmExitWindow(wx.Dialog):
"""Save confirmation dialog"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
wx.Dialog.__init__(self, parent, id, title, pos, size, style)
self.parent = self.GetParent()
vboxMain = wx.BoxSizer(wx.VERTICAL)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
labelMsg = wx.StaticText(self, -1,
_("Dictionary \"%s\" has been changed") \
% parent.name)
vboxMain.Add(labelMsg, 1, wx.ALL | wx.EXPAND, 15)
buttonSave = wx.Button(self, 6000, _("Save"))
hboxButtons.Add(buttonSave, 0, wx.ALL | wx.EXPAND, 3)
buttonExit = wx.Button(self, 6001, _("Do not save"))
hboxButtons.Add(buttonExit, 0, wx.ALL | wx.EXPAND, 3)
buttonCancel = wx.Button(self, 6002, _("Cancel"))
hboxButtons.Add(buttonCancel, 0, wx.ALL | wx.EXPAND, 3)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.EXPAND, 2)
self.SetSizer(vboxMain)
self.Fit()
wx.EVT_BUTTON(self, 6000, self.onSave)
wx.EVT_BUTTON(self, 6001, self.onExitParent)
wx.EVT_BUTTON(self, 6002, self.onClose)
def onSave(self, event):
if self.parent.cAction == "save":
self.parent.onSave(None)
self.parent.Destroy()
elif self.parent.cAction == "open":
self.parent.onSave(None)
self.Hide()
self.parent.open()
elif self.parent.cAction == "close":
self.parent.onSave(None)
self.parent.Destroy()
def onExitParent(self, event):
if self.parent.cAction == "save" or self.parent.cAction == "close":
self.parent.Destroy()
elif self.parent.cAction == "open":
self.Hide()
self.parent.open()
self.Destroy()
def onClose(self, event):
self.Destroy()
# -------------------------------------------------------------
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.app = wx.GetApp()
self.CreateStatusBar()
self.priTitle = _("Dictionary editor")
self.savedOnce = False
self.changed = False
self.editor = dicteditor.Editor()
self.cAction = None
vboxMain = wx.BoxSizer(wx.VERTICAL)
vboxDict = wx.BoxSizer(wx.VERTICAL)
vboxList = wx.BoxSizer(wx.VERTICAL)
hboxDict = wx.BoxSizer(wx.HORIZONTAL)
vboxEditButtons = wx.BoxSizer(wx.VERTICAL)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
# Control buttons
self.controlButtons = []
self.buttonAdd = wx.Button(self, 6000, _("Add"))
self.buttonAdd.SetToolTipString(_("Add word"))
self.controlButtons.append(self.buttonAdd)
self.buttonEdit = wx.Button(self, 6001, _("Edit"))
self.buttonEdit.SetToolTipString(_("Change translation"))
self.controlButtons.append(self.buttonEdit)
self.buttonRemove = wx.Button(self, 6002, _("Remove"))
self.buttonRemove.SetToolTipString(_("Remove selected word"))
self.controlButtons.append(self.buttonRemove)
self.buttonSort = wx.Button(self, 6004, _("Sort"))
self.buttonSort.SetToolTipString(_("Sort word list"))
self.controlButtons.append(self.buttonSort)
self.buttonSave = wx.Button(self, 6005, _("Save"))
self.buttonSave.SetToolTipString(_("Save words to file"))
self.controlButtons.append(self.buttonSave)
self.buttonSaveAs = wx.Button(self, 6006, _("Save As..."))
self.buttonSaveAs.SetToolTipString(_("Save with a different file name"))
self.controlButtons.append(self.buttonSaveAs)
for button in self.controlButtons:
button.Disable()
vboxEditButtons.Add(button, 0, wx.ALL | wx.EXPAND, 1)
panelList = wx.Panel(self, -1)
sbSizerList = wx.StaticBoxSizer(wx.StaticBox(panelList, -1,
_("Word List")),
wx.VERTICAL)
self.list = wx.ListBox(panelList, 6020,
wx.Point(-1, -1),
wx.Size(-1, -1),
[],
wx.LB_SINGLE | wx.SUNKEN_BORDER)
sbSizerList.Add(self.list, 1, wx.ALL | wx.EXPAND, 0)
panelList.SetSizer(sbSizerList)
panelList.SetAutoLayout(True)
sbSizerList.Fit(panelList)
hboxDict.Add(panelList, 1, wx.ALL | wx.EXPAND, 0)
hboxDict.Add(vboxEditButtons, 0, wx.ALL | wx.EXPAND, 5)
vboxDict.Add(hboxDict, 1, wx.ALL | wx.EXPAND, 0)
vboxMain.Add(vboxDict, 1, wx.ALL | wx.EXPAND, 10)
self.buttonNew = wx.Button(self, 6030, _("New..."))
self.buttonNew.SetToolTipString(_("Start new dictionary"))
hboxButtons.Add(self.buttonNew, 0, wx.ALL | wx.EXPAND, 1)
self.buttonOpen = wx.Button(self, 6031, _("Open..."))
self.buttonOpen.SetToolTipString(_("Open dictionary file"))
hboxButtons.Add(self.buttonOpen, 0, wx.ALL | wx.EXPAND, 1)
self.buttonClose = wx.Button(self, 6032, _("Close"))
self.buttonClose.SetToolTipString(_("Close editor window"))
hboxButtons.Add(self.buttonClose, 0, wx.ALL | wx.EXPAND, 1)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
self.SetIcon(wx.Icon(os.path.join(info.GLOBAL_HOME,
"pixmaps",
"icon-24x24.png"),
wx.BITMAP_TYPE_PNG))
self.SetSizer(vboxMain)
self.Bind(wx.EVT_LISTBOX, self.onWordSelected, self.list)
self.Bind(wx.EVT_BUTTON, self.onCreate, self.buttonNew)
wx.EVT_BUTTON(self, 6000, self.onAddWord)
wx.EVT_BUTTON(self, 6001, self.onEdit)
wx.EVT_BUTTON(self, 6002, self.onRemove)
wx.EVT_BUTTON(self, 6003, self.onSearch)
wx.EVT_BUTTON(self, 6004, self.onSort)
wx.EVT_BUTTON(self, 6005, self.onSave)
wx.EVT_BUTTON(self, 6006, self.onSaveAs)
wx.EVT_BUTTON(self, 6031, self.onOpen)
wx.EVT_BUTTON(self, 6032, self.onClose)
wx.EVT_CLOSE(self, self.onClose)
def onAddWord(self, event):
self.SetStatusText("")
window = self.AddWordWindow(self, -1, _("New Word"),
size=(-1, -1), pos=(-1, -1),
style=wx.DEFAULT_FRAME_STYLE)
window.CentreOnScreen()
window.Show(True)
def onEdit(self, event):
self.SetStatusText("")
word = self.list.GetStringSelection()
if word == "":
return
window = EditWordWindow(word, self, -1, _("Edit Word"),
size=(-1, -1),
style=wx.DEFAULT_FRAME_STYLE)
window.CentreOnScreen()
window.Show(True)
self.checkAllButtons()
def onRemove(self, event):
self.SetStatusText("")
word = self.list.GetStringSelection()
if word != "":
self.list.Delete(self.list.FindString(word))
self.editor.removeUnit(self.editor.getUnit(word))
self.setChanged(True)
self.checkAllButtons()
def onSearch(self, event):
self.SetStatusText("")
def onSort(self, event):
words = []
for unit in self.editor.getUnits():
words.append(unit.getWord())
if len(words) == 0:
self.SetStatusText(_("List is empty"))
return
words.sort()
self.list.Clear()
self.list.InsertItems(words, 0)
self.SetStatusText(_("List sorted"))
self.setChanged(True)
self.checkAllButtons()
def onSaveAs(self, event):
self.onSave(None)
def onSave(self, event):
self.SetStatusText("")
self.cAction = "save"
wildCard = "Slowo dictionaries (*.dwa)|*.dwa"
default = 'Untitled-dictionary.dwa'
if not self.savedOnce or not event:
dialog = wx.FileDialog(self,
wildcard=wildCard,
defaultFile=default,
message=_("Save file"),
style=wx.FD_SAVE | wx.FD_CHANGE_DIR)
if dialog.ShowModal() == wx.ID_OK:
self.filePath = dialog.GetPaths()[0]
else:
return
if os.path.isdir(self.filePath):
if self.filePath.endswith('..'):
self.filePath = self.filePath[:-2]
self.filePath += default
if not self.filePath.endswith('.dwa'):
self.filePath += '.dwa'
self.editor.save(self.filePath)
self.setChanged(False)
self.name = os.path.basename(self.filePath)
self.savedOnce = True
self.checkAllButtons()
self.SetStatusText(_("Dictionary saved"))
self.SetTitle("%s - %s" % (self.priTitle, self.name))
def onCreate(self, event):
self.editor = dicteditor.Editor()
self.list.Clear()
self.checkAllButtons()
self.savedOnce = False
self.name = _("Untitled")
self.SetStatusText("")
self.SetTitle("%s - %s" % (self.priTitle, self.name))
def checkAddButton(self):
"""Check for add button visibility"""
if not hasattr(self, 'editor'):
self.buttonAdd.Disable()
else:
self.buttonAdd.Enable(1)
def checkEditButton(self):
"""Check for edit button visibility"""
if self.list.GetSelection() == -1:
self.buttonEdit.Disable()
else:
self.buttonEdit.Enable(1)
def checkRemoveButton(self):
"""Check for remove button visibility"""
if self.list.GetSelection() == -1:
self.buttonRemove.Disable()
else:
self.buttonRemove.Enable(1)
def checkSortButton(self):
"""Check for sort button visibility"""
if not hasattr(self, 'editor'):
self.buttonSort.Disable()
elif len(self.editor.getUnits()) < 2:
self.buttonSort.Disable()
else:
self.buttonSort.Enable(1)
def checkSaveButton(self):
"""Check for save button visibility"""
if not hasattr(self, 'editor'):
self.buttonSave.Disable()
elif not self.changed:
self.buttonSave.Disable()
else:
self.buttonSave.Enable(1)
def checkAllButtons(self):
"""Check all buttons for visibility changes"""
self.checkAddButton()
self.checkEditButton()
self.checkRemoveButton()
self.checkSortButton()
self.checkSaveButton()
self.buttonSaveAs.Enable(True)
def onOpen(self, event):
if self.editor and self.changed:
window = self.ConfirmExitWindow(self,
-1,
_("Exit confirmation"))
self.cAction = "open"
window.CentreOnScreen()
window.Show(True)
else:
self.open()
self.savedOnce = True # no need to specify file name
def open(self):
wildCard = "Slowo dictionaries (*.dwa)|*.dwa"
dialog = wx.FileDialog(self, message=_("Choose dictionary file"),
wildcard=wildCard, style=wx.FD_OPEN|wx.FD_MULTIPLE)
if dialog.ShowModal() == wx.ID_OK:
name = os.path.split(dialog.GetPaths()[0])[1]
self.filePath = dialog.GetPaths()[0]
self.name = os.path.split(self.filePath)[1]
wx.BeginBusyCursor()
try:
self.editor.load(self.filePath)
except Exception, e:
wx.EndBusyCursor()
traceback.print_exc()
title = _("Open Failed")
msg = _("Unable to open dictionary (got message: %s)") % e
errorwin.showErrorMessage(title, msg)
return
self.SetTitle("%s - %s" % (self.priTitle, self.name))
self.list.Clear()
words = []
for unit in self.editor.getUnits():
words.append(enc.toWX(unit.getWord()))
words.sort()
self.list.InsertItems(words, 0)
self.checkAllButtons()
self.SetStatusText(_("Dictionary loaded"))
wx.EndBusyCursor()
def onWordSelected(self, event):
"""This method is invoked when list item is selected"""
self.checkAllButtons()
def onClose(self, event):
if self.changed:
self.cAction = "close"
window = self.ConfirmExitWindow(self, -1, _("Exit confirmation"))
window.CentreOnScreen()
window.Show(True)
else:
self.Destroy()
def setChanged(self, value):
"""Set changed=value"""
self.changed = value
def getChanged(self):
"""Get if changed"""
return self.changed
opendict-0.6.8/lib/gui/errorwin.py 0000664 0000764 0000764 00000005073 13204646653 017055 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# Module: gui.errorwin
import wx
import sys
import os
import traceback
_ = wx.GetTranslation
from lib import info
def showErrorMessage(title, msg):
"""Show error message dialog"""
window = wx.MessageDialog(None,
msg,
title,
wx.OK | wx.ICON_ERROR)
window.CenterOnScreen()
window.ShowModal()
window.Destroy()
def showInfoMessage(title, msg):
"""Show info message dialog"""
window = wx.MessageDialog(None,
msg,
title,
wx.OK | wx.ICON_INFORMATION)
window.CenterOnScreen()
window.ShowModal()
window.Destroy()
class ErrorWindow(wx.Frame):
"""This window is shown when OpenDict can't start because
of some error."""
def __init__(self, parent, id, title, error, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CENTRE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
raise DeprecationWarning
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(wx.StaticText(self, -1, _("An error occured:")), 0,
wx.ALL | wx.EXPAND, 5)
errMsg = wx.TextCtrl(self, -1, size=(-1, 200),
style=wx.TE_MULTILINE | wx.TE_READONLY)
errMsg.WriteText(error)
vbox.Add(errMsg, 1,
wx.ALL | wx.EXPAND, 10)
vbox.Add(wx.StaticText(self, -1, msg), 0,
wx.ALL | wx.EXPAND, 5)
self.buttonClose = wx.Button(self, 200, _("Close"))
vbox.Add(self.buttonClose, 0, wx.ALL | wx.CENTRE, 2)
self.SetSizer(vbox)
self.Fit()
wx.EVT_CLOSE(self, self.onCloseWindow)
wx.EVT_BUTTON(self, 200, self.onExit)
opendict-0.6.8/lib/gui/helpwin.py 0000664 0000764 0000764 00000020326 13204646653 016652 0 ustar nerijus nerijus # -*- coding: UTF-8 -*-
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# Module: gui.helpwin
#from wx import *
#from wx.html import *
import wx
import os
import sys
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
from lib import enc
from lib import info
_ = wx.GetTranslation
class LicenseWindow(wx.Frame):
"""Licence window class"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CENTRE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
vbox = wx.BoxSizer(wx.VERTICAL)
#
# Read licence file
#
try:
fd = open(os.path.join(info.GLOBAL_HOME, 'copying.html'))
data = fd.read()
fd.close()
except Exception, e:
systemLog(ERROR, "Unable to read licence file: %s" % e)
data = "Error: licence file not found"
scWinAbout = wx.ScrolledWindow(self, -1, wx.DefaultPosition,
wx.Size(-1, -1))
htmlWin = wx.html.HtmlWindow(scWinAbout, -1, style=wx.SUNKEN_BORDER)
htmlWin.SetFonts('Helvetica', 'Fixed', [10]*5)
htmlWin.SetPage(data)
scBox = wx.BoxSizer(wx.VERTICAL)
scBox.Add(htmlWin, 1, wx.ALL | wx.EXPAND, 1)
scWinAbout.SetSizer(scBox)
vbox.Add(scWinAbout, 1, wx.ALL | wx.EXPAND, 5)
self.buttonClose = wx.Button(self, 2002, _("&Close"))
vbox.Add(self.buttonClose, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
self.SetSizer(vbox)
wx.EVT_BUTTON(self, 2002, self.onClose)
def onClose(self, event):
"""This method is invoked when Close button is clicked"""
self.Destroy()
class CreditsWindow(wx.Dialog):
"""Credits window class"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize):
wx.Dialog.__init__(self, parent, id, title, pos, size)
vbox = wx.BoxSizer(wx.VERTICAL)
nb = wx.Notebook(self, -1)
# "Written by" panel
writePanel = wx.Panel(nb, -1)
vboxWrite = wx.BoxSizer(wx.VERTICAL)
writtenString = unicode("Martynas Jocius \n"
"Nerijus Baliūnas \n"
"Mantas Kriaučiūnas ",
"UTF-8")
written = enc.toWX(writtenString)
labelWrite = wx.StaticText(writePanel, -1, written)
vboxWrite.Add(labelWrite, 0, wx.ALL, 10)
writePanel.SetSizer(vboxWrite)
writePanel.SetFocus()
nb.AddPage(writePanel, _("Written By"))
# "Translations" panel
tPanel = wx.Panel(nb, -1)
vboxTP = wx.BoxSizer(wx.VERTICAL)
transString = unicode("Martynas Jocius ",
"UTF-8")
trans = enc.toWX(transString)
labelTP = wx.StaticText(tPanel, -1, trans)
vboxTP.Add(labelTP, 0, wx.ALL, 10)
tPanel.SetSizer(vboxTP)
nb.AddPage(tPanel, _("Translated By"))
# "Thanks" panel
thPanel = wx.Panel(nb, -1)
vboxThP = wx.BoxSizer(wx.VERTICAL)
thanksString = _("Ports:\n\n") + u"Debian/Ubuntu:\n Kęstutis Biliūnas \n\nMacOS X:\n Linas Valiukas "
thanks = enc.toWX(thanksString)
labelThP = wx.StaticText(thPanel, -1, thanks)
vboxThP.Add(labelThP, 0, wx.ALL, 10)
thPanel.SetSizer(vboxThP)
nb.AddPage(thPanel, _("Thanks To"))
# "Sponsor" panel
sponsorPanel = wx.Panel(nb, -1)
vboxSP = wx.BoxSizer(wx.VERTICAL)
sponsorString = _("OpenDict project was sponsored by IDILES.\n"
"Visit company's website at http://www.idiles.com.")
sponsor = enc.toWX(sponsorString)
labelSP = wx.StaticText(sponsorPanel, -1, sponsor)
vboxSP.Add(labelSP, 0, wx.ALL, 10)
sponsorPanel.SetSizer(vboxSP)
nb.AddPage(sponsorPanel, _("Sponsors"))
vbox.Add(nb, 1, wx.ALL | wx.EXPAND, 3)
buttonClose = wx.Button(self, 2005, _("&Close"))
vbox.Add(buttonClose, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
self.SetSizer(vbox)
wx.EVT_BUTTON(self, 2005, self.onClose)
def onClose(self, event):
"""This method is invoked when Close button is clicked"""
self.Destroy()
class AboutWindow(wx.Dialog):
"""Information window about OpenDict"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
wx.Dialog.__init__(self, parent, id, title, pos, size, style)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
vbox = wx.BoxSizer(wx.VERTICAL)
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME,
"pixmaps", "icon-96x96.png"),
wx.BITMAP_TYPE_PNG)
vbox.Add(wx.StaticBitmap(self, -1, bmp, wx.Point(-1, -1)), 0, wx.ALL |
wx.CENTRE, 5)
title = "OpenDict %s" % info.VERSION
copy = "Copyright %(c)s 2003-2006 Martynas Jocius \n" \
"Copyright %(c)s 2007-2008 Idiles Systems Ltd " \
% {'c': unicode("\302\251", "UTF-8")}
desc = _("OpenDict is a multiplatform dictionary.")
page = "http://opendict.sf.net\nhttps://github.com/nerijus/opendict"
titleLabel = wx.StaticText(self, -1, title,
style=wx.ALIGN_CENTER)
titleLabel.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
vbox.Add(titleLabel, 1, wx.ALL | wx.ALIGN_CENTER, 5)
copyLabel = wx.StaticText(self, -1, copy, style=wx.ALIGN_CENTER)
copyLabel.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD))
vbox.Add(copyLabel, 1, wx.ALL | wx.ALIGN_CENTER, 5)
descLabel = wx.StaticText(self, -1,
_("OpenDict is a multiplatform dictionary."), style=wx.ALIGN_CENTER)
descLabel.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
vbox.Add(descLabel, 1, wx.ALL | wx.ALIGN_CENTER, 5)
pageLabel = wx.StaticText(self, -1, page, style=wx.ALIGN_CENTER)
pageLabel.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL))
vbox.Add(pageLabel, 1, wx.ALL | wx.ALIGN_CENTER, 5)
vbox.Add(wx.StaticLine(self, -1), 0, wx.ALL | wx.EXPAND, 5)
self.buttonCredits = wx.Button(self, 2004, _("C&redits"))
hboxButtons.Add(self.buttonCredits, 0, wx.ALL | wx.ALIGN_LEFT, 3)
self.buttonLicence = wx.Button(self, 2006, _("&Licence"))
hboxButtons.Add(self.buttonLicence, 0, wx.ALL | wx.ALIGN_LEFT, 3)
self.buttonOK = wx.Button(self, 2003, _("&Close"))
hboxButtons.Add(self.buttonOK, 0, wx.ALL | wx.ALIGN_RIGHT, 3)
vbox.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_CENTER, 5)
self.SetSizer(vbox)
vbox.Fit(self)
wx.EVT_BUTTON(self, 2003, self.onClose)
wx.EVT_BUTTON(self, 2004, self.onCredits)
wx.EVT_BUTTON(self, 2006, self.onLicence)
def onClose(self, event):
self.Destroy()
def onCredits(self, event):
creditsWindow = CreditsWindow(self, -1, "Credits",
size=(500, 240))
creditsWindow.CentreOnScreen()
creditsWindow.Show()
def onLicence(self, event):
licenseWindow = LicenseWindow(self, -1,
_("Licence"),
size=(500, 400),
style=wx.DEFAULT_FRAME_STYLE)
licenseWindow.CenterOnScreen()
licenseWindow.Show(True)
opendict-0.6.8/lib/gui/mainwin.py 0000664 0000764 0000764 00000134610 13204646653 016650 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
"""
Main window GUI module
"""
import wx
import wx.html
import os
import cStringIO
import traceback
from lib import info
from lib.gui.dictconnwin import DictConnWindow
from lib.gui.pluginwin import PluginManagerWindow
from lib.gui.dicteditorwin import DictEditorWindow
from lib.gui.dictaddwin import DictAddWindow
from lib.gui.prefswin import PrefsWindow
from lib.gui import prefswin
from lib.gui.helpwin import LicenseWindow, AboutWindow
from lib.gui import errorwin
from lib.gui import miscwin
from lib.parser import SlowoParser
from lib.parser import MovaParser
from lib.parser import TMXParser
from lib.parser import DictParser
from lib.threads import Process
from lib.history import History
from lib.installer import Installer
from lib.extra.html2text import html2text
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
from lib import misc
from lib import info
from lib import util
from lib import meta
from lib import enc
from lib import errortype
from lib import dicttype
from lib import plaindict
_ = wx.GetTranslation
# Constants
titleTemplate = "OpenDict - %s"
NORMAL_FONT_SIZE = '10'
# Used to remember word when searching by entering text to the entry,
# selecting one from the list or clicking a link.
lastLookupWord = None
class HtmlWindow(wx.html.HtmlWindow):
"""Html control for showing transaltion and catching
link-clicking"""
def OnLinkClicked(self, linkInfo):
global lastLookupWord
lastLookupWord = linkInfo.GetHref()
wx.BeginBusyCursor()
parent = self.GetParent().GetParent().GetParent()
word = enc.fromWX(lastLookupWord)
try:
word = word.encode(parent.activeDictionary.getEncoding())
except Exception, e:
# FIXME: Code duplicates
traceback.print_exc()
parent.buttonStop.Disable()
parent.entry.Enable(True)
parent.timerSearch.Stop()
parent.SetStatusText(_('Stopped'))
wx.EndBusyCursor()
systemLog(ERROR, "Unable to decode '%s': %s" % (word.encode('UTF-8'),
e))
title = _("Encode Failed")
msg = _("Unable to encode text \"%s\" in %s for \"%s\".") \
% (enc.toWX(word), parent.activeDictionary.getEncoding(),
parent.activeDictionary.getName())
errorwin.showErrorMessage(title, msg)
return
parent.SetStatusText(_("Searching..."))
parent.entry.SetValue(word)
parent.timerSearch.Start(parent.delay)
parent.search = Process(parent.activeDictionary.search,
word)
class MainWindow(wx.Frame):
"""Main OpenDict window with basic controls"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.app = wx.GetApp()
self.printer = wx.html.HtmlEasyPrinting()
self.history = History()
self.htmlCode = ""
self.dictName = ""
self.activeDictionary = None
self.words = []
self.delay = 10 # miliseconds
self.lastInstalledDictName = None
# This var is used by onTimerSearch to recognize search method.
# If search was done by selecting a word in a list, then word list
# is not updated, otherwise is.
self.__searchedBySelecting = 0
# Box sizers
vboxMain = wx.BoxSizer(wx.VERTICAL)
self.hboxToolbar = wx.BoxSizer(wx.HORIZONTAL)
#
# Menu Bar
#
self.menuBar = wx.MenuBar()
#
# File menu
#
menuFile = wx.Menu()
idPrint = wx.NewId()
#menuFile.Append(idPrint, _("Print Translation"), "")
idPreview = wx.NewId()
#menuFile.Append(idPreview, _("Print Preview"), "")
idFind = wx.NewId()
menuFile.Append(idFind, _("Look Up\tCtrl-U"),
_("Lookup up word in the dictionary"))
menuFile.AppendSeparator()
idCloseDict = wx.NewId()
menuFile.Append(idCloseDict, _("&Close Dictionary\tCtrl-W"),
_("Close opened dicitonary"))
idExit = wx.NewId()
menuFile.Append(idExit, _("E&xit\tCtrl-Q"),
_("Exit program"))
self.menuBar.Append(menuFile, _("&File"))
menuEdit = wx.Menu()
#
# Clear functions
#
idClearEntry = wx.NewId()
menuEdit.Append(idClearEntry, _("&Clear Search Entry\tCtrl-L"))
idClearHistory = wx.NewId()
menuEdit.Append(idClearHistory, _("Clear History"))
menuEdit.AppendSeparator()
#
# Clipboard functions
#
idCopy = wx.NewId()
menuEdit.Append(idCopy, _("Copy\tCtrl-C"),
_("Copy selected translation text"))
idPaste = wx.NewId()
menuEdit.Append(idPaste, _("Paste\tCtrl-V"),
_("Paste clipboard text into the search entry"))
menuEdit.AppendSeparator()
idPrefs = wx.NewId()
menuEdit.Append(idPrefs, _("Preferences...\tCtrl-P"), _("Edit preferences"))
self.menuBar.Append(menuEdit, _("&Edit"))
#
# View menu
#
menuView = wx.Menu()
# Font size
self.menuFontSize = wx.Menu()
self.menuFontSize.Append(2007, _("Increase\tCtrl-="),
_("Increase text size"))
self.menuFontSize.Append(2008, _("Decrease\tCtrl--"),
_("Decrease text size"))
self.menuFontSize.AppendSeparator()
self.menuFontSize.Append(2009, _("Normal\tCtrl-0"),
_("Set normal text size"))
menuView.AppendMenu(2002, _("Font Size"), self.menuFontSize)
# Font face
self.menuFontFace = wx.Menu()
i = 0
keys = misc.fontFaces.keys()
keys.sort()
for face in keys:
self.menuFontFace.AppendRadioItem(2500+i, face, "")
wx.EVT_MENU(self, 2500+i, self.onDefault)
if self.app.config.get('fontFace') == misc.fontFaces[face]:
self.menuFontFace.FindItemById(2500+i).Check(1)
i+=1
menuView.AppendMenu(2001, _("Font Face"), self.menuFontFace)
# Font encoding
self.menuEncodings = wx.Menu()
i = 0
keys = misc.encodings.keys()
keys.sort()
for encoding in keys:
self.menuEncodings.AppendRadioItem(2100+i , encoding, "")
wx.EVT_MENU(self, 2100+i, self.onDefault)
if self.app.config.get('encoding') == misc.encodings[encoding]:
self.menuEncodings.FindItemById(2100+i).Check(1)
i+=1
menuView.AppendMenu(2000, _("Character Encoding"), self.menuEncodings)
menuView.AppendSeparator()
idShowHide = wx.NewId()
menuView.Append(idShowHide, _("Show/Hide Word List...\tCtrl-H"),
_("Show or hide word list"))
self.menuBar.Append(menuView, _("&View"))
#
# Dictionaries menu
#
self.menuDict = wx.Menu()
dicts = []
for dictionary in self.app.dictionaries.values():
dicts.append([dictionary.getName(), dictionary.getActive()])
dicts.sort()
for name, active in dicts:
#if not self.app.config.activedict.enabled(name):
# continue
if not active:
continue
encoded = enc.toWX(name)
itemID = self.app.config.ids.keys()[\
self.app.config.ids.values().index(name)]
try:
# item = wx.MenuItem(self.menuDict,
# itemID,
# encoded)
# self.menuDict.AppendItem(item)
self.menuDict.AppendRadioItem(itemID, encoded, "")
wx.EVT_MENU(self, itemID, self.onDefault)
if self.app.config.get('defaultDict') == name:
self.menuDict.FindItemById(itemID).Check(1)
except Exception, e:
systemLog(ERROR, "Unable to create menu item for '%s' (%s)" \
% (name, e))
self.menuDict.AppendSeparator()
idAddDict = wx.NewId()
self.menuDict.Append(idAddDict, _("&Install Dictionary From File..."))
self.menuBar.Append(self.menuDict, _("&Dictionaries"))
#
# Tools menu
#
menuTools = wx.Menu()
idManageDict = wx.NewId()
menuTools.Append(idManageDict, _("Manage Dictionaries...\tCtrl-M"),
_("Install or remove dictionaries"))
menuTools.Append(5002, _("Create Dictionaries..."),
_("Create and edit dictionaries"))
menuTools.AppendSeparator()
idUseScan = wx.NewId()
item = wx.MenuItem(menuTools,
idUseScan,
_("Take Words From Clipboard"),
_("Scan the clipboard for text to translate"),
wx.ITEM_CHECK)
menuTools.AppendItem(item)
menuTools.Check(idUseScan, self.app.config.get('useClipboard') == 'True')
menuTools.AppendSeparator()
idDictServer = wx.NewId()
menuTools.Append(idDictServer, _("Connect to DICT Server..."),
_("Open connection to DICT server"))
menuTools.AppendSeparator()
idPron = wx.NewId()
menuTools.Append(idPron, _("Pronounce\tCtrl-E"),
_("Pronounce word"))
self.menuBar.Append(menuTools, _("Tools"))
#
# Help menu
#
menuHelp = wx.Menu()
idAbout = wx.NewId()
menuHelp.Append(idAbout, _("&About\tCtrl-A"))
self.menuBar.Append(menuHelp, _("&Help"))
self.SetMenuBar(self.menuBar)
# Search Bar
labelWord = wx.StaticText(self, -1, _("Word:"))
self.hboxToolbar.Add(labelWord, 0, wx.ALL | wx.CENTER | wx.ALIGN_RIGHT, 5)
self.entry = wx.ComboBox(self, 153, "", wx.Point(-1, -1),
wx.Size(-1, -1), [], wx.CB_DROPDOWN)
self.entry.SetToolTipString(_("Enter some text and press " \
"\"Look Up\" button or "
"[ENTER] key on your keyboard"))
self.hboxToolbar.Add(self.entry, 1, wx.ALL | wx.CENTER, 1)
#self.buttonSearch = wx.Button(self, wx.ID_FIND)
self.buttonSearch = wx.Button(self, idFind, _("Look Up"))
self.buttonSearch.SetToolTipString(_("Click this button to look " \
"up word in " \
"the dictionary"))
self.hboxToolbar.Add(self.buttonSearch, 0, wx.ALL | wx.CENTER, 1)
# Back button
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "left.png"),
wx.BITMAP_TYPE_PNG)
self.buttonBack = wx.BitmapButton(self, 2010, bmp, (24, 24),
style=wx.NO_BORDER)
self.buttonBack.SetToolTipString(_("History Back"))
self.buttonBack.Disable()
self.hboxToolbar.Add(self.buttonBack, 0, wx.ALL | wx.CENTER, 1)
# Forward button
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "right.png"),
wx.BITMAP_TYPE_PNG)
self.buttonForward = wx.BitmapButton(self, 2011, bmp, (24, 24),
style=wx.NO_BORDER)
self.buttonForward.SetToolTipString(_("History Forward"))
self.buttonForward.Disable()
self.hboxToolbar.Add(self.buttonForward, 0, wx.ALL | wx.CENTER, 1)
# Stop threads
# TODO: how thread can be killed?
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "stop.png"),
wx.BITMAP_TYPE_PNG)
self.buttonStop = wx.BitmapButton(self, 155, bmp, (16, 16),
style=wx.NO_BORDER)
self.buttonStop.SetToolTipString(_("Stop searching"))
self.buttonStop.Disable()
self.hboxToolbar.Add(self.buttonStop, 0, wx.ALL | wx.CENTER, 1)
# Word list is hidden by default
self.wlHidden = True
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "hide.png"),
wx.BITMAP_TYPE_PNG)
self.buttonHide = wx.BitmapButton(self, 152, bmp, (24, 24),
style=wx.NO_BORDER)
self.hboxToolbar.Add(self.buttonHide, 0, wx.ALL | wx.CENTER, 1)
vboxMain.Add(self.hboxToolbar, 0, wx.ALL | wx.EXPAND | wx.GROW, 0)
# Splitter Window
self.splitter = wx.SplitterWindow(self, -1)
# List panel
self.createListPanel()
# Html window panel
self.panelHtml = wx.Panel(self.splitter, -1)
sbSizerHtml = wx.StaticBoxSizer(wx.StaticBox(self.panelHtml, -1,
_("Translation")),
wx.VERTICAL)
self.htmlWin = HtmlWindow(self.panelHtml, -1, style=wx.SUNKEN_BORDER)
sbSizerHtml.Add(self.htmlWin, 1, wx.ALL | wx.EXPAND, 0)
self.panelHtml.SetSizer(sbSizerHtml)
self.panelHtml.SetAutoLayout(True)
sbSizerHtml.Fit(self.panelHtml)
self.splitter.SplitVertically(self.panelList, self.panelHtml,
int(self.app.config.get('sashPos')))
self.splitter.SetMinimumPaneSize(90)
self.splitter.SetSashSize(5)
if not self.activeDictionary:
self.hideWordList()
vboxMain.Add(self.splitter, 1, wx.ALL | wx.GROW | wx.EXPAND, 0)
# Status bar
self.CreateStatusBar()
# Main sizer
self.SetSizer(vboxMain)
self.timerSearch = wx.Timer(self, 5000)
self.timerLoad = wx.Timer(self, 5001)
idClipboard = wx.NewId()
self.timerClipboard = wx.Timer(self, idClipboard)
self.scanTimeout = 2000
self.search = None
self.load = None
self.SetIcon(wx.Icon(os.path.join(info.GLOBAL_HOME,
"pixmaps",
"icon-32x32.png"),
wx.BITMAP_TYPE_PNG))
#
# Loading default dictionary
#
if self.app.config.get('defaultDict'):
self.loadDictionary(self.app.dictionaries.get(\
self.app.config.get('defaultDict')))
self.SetMinSize((320, 160))
#
# Events
#
# TODO: New-style event definition
# File menu events
wx.EVT_MENU(self, idPrint, self.onPrint)
wx.EVT_MENU(self, idPreview, self.onPreview)
wx.EVT_MENU(self, idCloseDict, self.onCloseDict)
wx.EVT_MENU(self, idExit, self.onExit)
# Edit menu events
wx.EVT_MENU(self, idClearHistory, self.onClearHistory)
wx.EVT_MENU(self, idCopy, self.onCopy)
wx.EVT_MENU(self, idPaste, self.onPaste)
wx.EVT_MENU(self, idClearEntry, self.onClean)
# View menu events
wx.EVT_MENU(self, 2007, self.onIncreaseFontSize)
wx.EVT_MENU(self, 2008, self.onDecreaseFontSize)
wx.EVT_MENU(self, 2009, self.onNormalFontSize)
wx.EVT_MENU(self, idShowHide, self.onHideUnhide)
# Dictionaries menu events
wx.EVT_MENU(self, idAddDict, self.onAddDict)
# Tools menu events
wx.EVT_MENU(self, idDictServer, self.onOpenDictConn)
wx.EVT_MENU(self, idUseScan, self.onUseScanClipboard)
wx.EVT_MENU(self, idManageDict, self.onShowPluginManager)
wx.EVT_MENU(self, 5002, self.onShowDictEditor)
wx.EVT_MENU(self, idPrefs, self.onShowPrefsWindow)
wx.EVT_MENU(self, idPron, self.onPronounce)
# Help menu events
wx.EVT_MENU(self, idAbout, self.onAbout)
# Other events
self.Bind(wx.EVT_BUTTON, self.onSearch, self.buttonSearch)
wx.EVT_MENU(self, idFind, self.onSearch)
wx.EVT_BUTTON(self, 2010, self.onBack)
wx.EVT_BUTTON(self, 2011, self.onForward)
wx.EVT_BUTTON(self, 155, self.onStop)
wx.EVT_BUTTON(self, 151, self.onClean)
wx.EVT_BUTTON(self, 152, self.onHideUnhide)
wx.EVT_TEXT_ENTER(self, 153, self.onSearch)
wx.EVT_LISTBOX(self, 154, self.onWordSelected)
wx.EVT_TIMER(self, 5000, self.onTimerSearch)
wx.EVT_TIMER(self, idClipboard, self.onTimerClipboard)
wx.EVT_CLOSE(self, self.onCloseWindow)
self.entry.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)
# Prepare help message
self.htmlCode = _("""
Welcome to OpenDict
Short usage information:
- To start using dictionary, select one from Dictionaries
menu.
- To install new dictionary from the Internet, select
Manage Dictionaries
from Tools menu and choose Available tab.
- To install new dictionary from file, select Install Dictionary From File...
from Dictionaries menu.
""")
if self.activeDictionary:
self.htmlCode = ""
self.updateHtmlScreen()
if self.app.invalidDictionaries:
miscwin.showInvalidDicts(self, self.app.invalidDictionaries)
if self.app.config.get('useClipboard') == 'True':
self.timerClipboard.Start(self.scanTimeout)
def onExit(self, event):
self.onCloseWindow(None)
def onCloseWindow(self, event):
self.onCloseDict(None)
self.savePreferences()
self.Destroy()
# TODO: Move aftersearch actions into separate method
def onTimerSearch(self, event):
"""Search timer. When finished, sets search results"""
if self.search != None and self.search.isDone():
self.timerSearch.Stop()
self.search.stop()
#
# Turn back active interface elements state
wx.EndBusyCursor()
self.SetStatusText("")
self.entry.Enable(1)
self.buttonStop.Disable()
global lastLookupWord
word = lastLookupWord
if self.entry.FindString(word) == -1:
self.entry.Append(word)
result = self.search()
# Check if search result is SerachResult object.
# SearchResult class is used by new-type plugins.
try:
assert result.__class__ == meta.SearchResult
except:
self.SetStatusText(errortype.INTERNAL_ERROR.getMessage())
if self.activeDictionary.getType() == dicttype.PLUGIN:
title = errortype.INTERNAL_ERROR.getMessage()
message = errortype.INTERNAL_ERROR.getLongMessage()
else:
title = errortype.OPENDICT_BUG.getMessage()
message = errortype.OPENDICT_BUG.getLongMessage()
systemLog(ERROR, "%s: %s" % (message, misc.getTraceback()))
errorwin.showErrorMessage(title, message)
return
# Check status code
if result.getError() != errortype.OK:
systemLog(ERROR, result.getError())
self.htmlWin.SetPage("")
self.wordList.Clear()
if result.getError() in \
[errortype.INTERNAL_ERROR, errortype.INVALID_ENCODING]:
errorwin.showErrorMessage(result.getError().getMessage(),
result.getError().getLongMessage())
else:
self.SetStatusText(result.getError().getMessage())
return
#
# If dictionary (plugin) does not use NOT_FOUND notification,
# check for translation and show it manually
#
if not result.getTranslation():
self.SetStatusText(errortype.NOT_FOUND.getMessage())
try:
transUnicode = unicode(result.translation,
self.activeDictionary.getEncoding())
except Exception, e:
systemLog(ERROR, "Unable to decode translation in %s (%s)" \
% (self.activeDictionary.getEncoding(),
e))
title = errortype.INVALID_ENCODING.getMessage()
msg = _("Translation cannot be displayed using selected " \
"encoding %s. Please try another encoding from " \
"View > Character Encoding menu.") \
% self.activeDictionary.getEncoding()
self.SetStatusText(title)
errorwin.showErrorMessage(title, msg)
return
transPreparedForWX = enc.toWX(transUnicode)
self.htmlWin.SetPage(transPreparedForWX)
self.history.add(transPreparedForWX)
# FIXME: Nasty names
# Where it is used? htmlWin.GetPage
self.htmlCode = transPreparedForWX
if not self.wordListHidden():
if not self.__searchedBySelecting:
self.wordList.Clear()
toUnicode = lambda s: unicode(s,
self.activeDictionary.getEncoding())
wordsInUnicode = map(toUnicode, result.words)
wordsPreparedForWX = map(enc.toWX, wordsInUnicode)
self.wordList.InsertItems(wordsPreparedForWX, 0)
self.words = wordsPreparedForWX
if not self.__searchedBySelecting:
matches = self.wordList.GetCount()
if matches == 1:
self.SetStatusText(_("1 word matches"))
elif matches > 1:
self.SetStatusText(_("%d words match") % matches)
else:
self.SetStatusText(_("Done"))
if self.history.canBack():
self.buttonBack.Enable(1)
self.search = None
def onTimerClipboard(self, event):
"""Clipboard timer, used to watch new text in a clipboard"""
def getText():
do = wx.TextDataObject()
text = None
wx.TheClipboard.Open()
if wx.TheClipboard.GetData(do):
try:
text = do.GetText().strip()
except Exception, e:
print e
wx.TheClipboard.Close()
return enc.toWX(text)
text = getText()
old_text = ''
if hasattr(self, 'old_clipboard_text'):
old_text = self.old_clipboard_text
if text and text != old_text:
self.entry.SetValue(text)
self.onSearch(None)
self.old_clipboard_text = text
def onUseScanClipboard(self, event):
"""Scan Clipboard menu item selected"""
if event and event.GetInt():
self.timerClipboard.Start(self.scanTimeout)
else:
self.timerClipboard.Stop()
def onSearch(self, event):
if self.activeDictionary == None:
if len(self.app.dictionaries):
title = _("No dictionary activated")
msg = _("No dictionary activated. Please select one from "\
"\"Dictionaries\" menu and try again.")
else:
title = _("No dictionaries installed")
msg = _("There is no dictionaries installed. You can " \
"install one by selecting Tools > Manage " \
"Dictionaries > Available")
errorwin.showErrorMessage(title, msg)
return
if self.search and not self.search.isDone():
self.onStop(None)
word = self.entry.GetValue().strip()
if word == "":
self.SetStatusText(_("Please enter some text and try again"))
self.entry.SetFocus()
return
global lastLookupWord
lastLookupWord = word
wx.BeginBusyCursor()
self.__searchedBySelecting = 0
self.SetStatusText(_("Searching..."))
self.timerSearch.Stop()
self.search = None
self.buttonStop.Enable(1)
self.entry.Disable()
self.timerSearch.Start(self.delay)
word = enc.fromWX(word)
try:
word = word.encode(self.activeDictionary.getEncoding())
except Exception, e:
# FIXME: Code duplicates
self.buttonStop.Disable()
self.entry.Enable(True)
self.timerSearch.Stop()
self.SetStatusText(_('Stopped'))
wx.EndBusyCursor()
systemLog(ERROR, "Unable to decode '%s': %s" % (word.encode('UTF-8'),
e))
title = _("Encode Failed")
msg = _("Unable to encode text \"%s\" in %s for \"%s\". "
"That logically means the word "
"definition does not exist in the dictionary.") \
% (enc.toWX(word), self.activeDictionary.getEncoding(),
self.activeDictionary.getName())
errorwin.showErrorMessage(title, msg)
return
self.search = Process(self.activeDictionary.search, word)
def onBack(self, event):
self.buttonForward.Enable(1)
self.htmlWin.SetPage(self.history.back())
if not self.history.canBack():
self.buttonBack.Disable()
def onForward(self, event):
self.buttonBack.Enable(1)
self.htmlWin.SetPage(self.history.forward())
if not self.history.canForward():
self.buttonForward.Disable()
def onStop(self, event):
self.entry.Enable(1)
self.SetStatusText(_("Stopped"))
self.timerSearch.Stop()
self.timerLoad.Stop()
if self.search:
self.search.stop()
self.search = None
if self.load:
self.load.stop()
self.load = None
wx.EndBusyCursor()
self.buttonStop.Disable()
def onClean(self, event):
self.entry.SetValue("")
self.entry.SetFocus()
def onKeyDown(self, event):
"""Key down event handler."""
if event.GetKeyCode() == wx.WXK_ESCAPE:
self.onClean(None)
event.Skip()
def onClearHistory(self, event):
self.entry.Clear()
self.history.clear()
self.buttonBack.Disable()
self.buttonForward.Disable()
def wordListHidden(self):
"""Returns True if word list marked to be hidden, False
otherwise"""
if self.wlHidden:
return True
return False
def onHideUnhide(self, event):
if self.wordListHidden():
self.unhideWordList()
else:
self.hideWordList()
def onOpenDictConn(self, event):
window = DictConnWindow(self, -1,
_("Connect to DICT server"),
style=wx.DEFAULT_FRAME_STYLE)
window.CentreOnScreen()
window.Show(True)
def onCloseDict(self, event):
"""Clear widgets and set messages"""
# If there was a registered dict, set it's default encoding
# FIXME: new way
try:
if self.dict.name in self.app.config.registers.keys():
self.app.config.registers[self.dict.name][2] = self.app.config.encoding
except:
pass
self.wordList.Clear()
self.htmlWin.SetPage("")
self.SetTitle("OpenDict")
self.words = []
if self.activeDictionary:
self.activeDictionary.stop()
self.activeDictionary = None
self.SetStatusText(_("Choose a dictionary from \"Dictionaries\" menu"))
def onCopy(self, event):
self.do = wx.TextDataObject()
self.do.SetText(self.htmlWin.SelectionToText())
wx.TheClipboard.Open()
wx.TheClipboard.SetData(self.do)
wx.TheClipboard.Close()
def onPaste(self, event):
"""This method is invoked when Paste menu item is selected"""
do = wx.TextDataObject()
wx.TheClipboard.Open()
if wx.TheClipboard.GetData(do):
try:
self.entry.SetValue(do.GetText())
except:
self.SetStatusText(_("Failed to copy text from the clipboard"))
else:
self.SetStatusText(_("Clipboard contains no text data"))
wx.TheClipboard.Close()
def onPronounce(self, event):
"""Pronouce word using external software."""
word = self.entry.GetValue().strip()
if word:
cmd = self.app.config.get('pronunciationCommand') or prefswin.PRON_COMMAND
if self.app.config.get('pronounceTrans') == 'True':
word = html2text(self.htmlCode)
import locale
localeCharset = locale.getpreferredencoding()
try:
word = word.replace('(', '').replace(')', '').replace('\n',
'').replace('\r', '').replace('"', '\\"')
cmd = (cmd % word).encode(localeCharset)
Process(os.system, cmd)
except Exception, e:
traceback.print_exc()
title = _("Error")
msg = _("Unable to decode text using your locale charset %s" \
% localeCharset)
errorwin.showErrorMessage(title, msg)
def onShowGroupsWindow(self, event):
"""This method is invoked when Groups menu item is selected"""
self.groupsWindow = GroupsWindow(self, -1,
_("Groups"),
size=(330, 150),
style=wx.DEFAULT_FRAME_STYLE)
self.groupsWindow.CentreOnScreen()
self.groupsWindow.Show(True)
def onShowPluginManager(self, event):
"""This method is invoked when Dictionaries Manager
menu item is selected"""
try:
self.pmWindow = PluginManagerWindow(self, -1,
_("Manage Dictionaries"),
size=(500, 500),
style=wx.DEFAULT_FRAME_STYLE)
self.pmWindow.CentreOnScreen()
self.pmWindow.Show(True)
except Exception, e:
traceback.print_exc()
systemLog(ERROR, "Unable to show prefs window: %s" % e)
self.SetStatusText("Error occured, please contact developers (%s)" \
% e)
def onShowFileRegistry(self, event):
self.regWindow = FileRegistryWindow(self, -1,
_("File Register"),
size=(340, 200),
style=wx.DEFAULT_FRAME_STYLE)
self.regWindow.CentreOnScreen()
self.regWindow.Show(True)
def onShowDictEditor(self, event):
editor = DictEditorWindow(self, -1, _("Create Dictionaries"),
size=(400, 500),
style=wx.DEFAULT_FRAME_STYLE)
editor.CentreOnScreen()
editor.Show(True)
def onShowPrefsWindow(self, event):
try:
self.prefsWindow = PrefsWindow(self, -1, _("Preferences"),
size=(-1, -1),
style=wx.DEFAULT_FRAME_STYLE)
self.prefsWindow.CentreOnScreen()
self.prefsWindow.Show(True)
except Exception, e:
traceback.print_exc()
systemLog(ERROR, "Unable to show preferences window: %s" % e)
title = errortype.OPENDICT_BUG.getMessage()
msg = errortype.OPENDICT_BUG.getLongMessage()
errorwin.showErrorMessage(title, msg)
def onDefault(self, event):
# FIXME: Bad way. Try setting a few constants for each type
# of dictionary and then check this type instead of IDs.
eventID = event.GetId()
if eventID in self.app.config.ids.keys():
dictionary = self.app.dictionaries.get(self.app.config.ids.get(eventID))
self.loadDictionary(dictionary)
label = self.menuDict.FindItemById(eventID).GetLabel()
self.app.config.set('defaultDict', label)
elif 2100 <= eventID < 2500:
label = self.menuEncodings.FindItemById(eventID).GetLabel()
self.changeEncoding(label)
elif 2500 <= eventID < 2600:
label = self.menuFontFace.FindItemById(eventID).GetLabel()
self.changeFontFace(label)
elif 2600 <= eventID < 2700:
label = self.menuFontSize.FindItemById(eventID).GetLabel()
self.changeFontSize(label)
def checkIfNeedsList(self):
"""Unhides word list if current dictionary uses it"""
if self.activeDictionary.getUsesWordList():
if self.wordListHidden():
self.unhideWordList()
else:
if not self.wordListHidden():
self.hideWordList()
def addDictionary(self, dictInstance):
"""Add dictionary to menu and updates ids"""
app = wx.GetApp()
app.dictionaries[dictInstance.getName()] = dictInstance
unid = util.generateUniqueID()
# Insert new menu item only if no same named dictionary exists
#if not dictInstance.getName() in app.config.ids.values():
app.config.ids[unid] = dictInstance.getName()
item = wx.MenuItem(self.menuDict,
unid,
dictInstance.getName())
wx.EVT_MENU(self, unid, self.onDefault)
#self.menuDict.InsertItem(self.menuDict.GetMenuItemCount()-2, item)
self.menuDict.InsertItem(0, item)
def removeDictionary(self, name):
"""Remove dictionary from the menu"""
item = self.menuDict.FindItem(name)
if item:
self.menuDict.Delete(item)
def loadDictionary(self, dictInstance):
"""Prepares main window for using dictionary"""
if not dictInstance:
systemLog(ERROR, "loadDictionary: dictInstance is False")
return
#
# Check licence agreement
#
licence = dictInstance.getLicence()
if licence \
and not self.app.agreements.getAccepted(dictInstance.getPath()):
if not miscwin.showLicenceAgreement(None, licence):
from lib.gui import errorwin
title = _("Licence Agreement Rejected")
msg = _("You cannot use dictionary \"%s\" without accepting "\
"licence agreement") % dictInstance.getName()
errorwin.showErrorMessage(title, msg)
return
else:
self.app.agreements.addAgreement(dictInstance.getPath())
self.onCloseDict(None)
self.activeDictionary = dictInstance
if dictInstance.getType() in dicttype.indexableTypes:
if plaindict.indexShouldBeMade(dictInstance):
# Notify about indexing
from lib.gui import errorwin
title = _("Dictionary Index")
msg = _("This is the first time you use this dictionary or it " \
"has been changed on disk since last indexing. " \
"Indexing is used to make search more efficient. " \
"The dictionary will be indexed now. It can take a few " \
"or more seconds.\n\n" \
"Press OK to continue...")
errorwin.showInfoMessage(title, msg)
# Make index
try:
wx.BeginBusyCursor()
plaindict.makeIndex(dictInstance,
self.app.config.get('encoding'))
wx.EndBusyCursor()
except Exception, e:
wx.EndBusyCursor()
traceback.print_exc()
title = _("Index Creation Error")
msg = _("Error occured while indexing file. " \
"This may be because of currently selected " \
"character encoding %s is not correct for this " \
"dictionary. Try selecting " \
"another encoding from View > Character Encoding " \
"menu") % self.app.config.get('encoding')
from lib.gui import errorwin
errorwin.showErrorMessage(title, msg)
return
# Load index
try:
wx.BeginBusyCursor()
index = plaindict.loadIndex(dictInstance)
self.activeDictionary.setIndex(index)
wx.EndBusyCursor()
except Exception, e:
wx.EndBusyCursor()
traceback.print_exc()
title = _("Error")
msg = _("Unable to load dictionary index table. "
"Got error: %s") % e
from lib.gui import errorwin
errorwin.showErrorMessage(title, msg)
return
wx.BeginBusyCursor()
self.activeDictionary.start()
self.checkIfNeedsList()
self.SetTitle(titleTemplate % dictInstance.getName())
self.SetStatusText(enc.toWX(_("Dictionary \"%s\" loaded") \
% dictInstance.getName()))
self.entry.SetFocus()
try:
self.checkEncMenuItem(self.activeDictionary.getEncoding())
except Exception, e:
systemLog(ERROR, "Unable to select encoding menu item: %s" % e)
wx.EndBusyCursor()
def loadPlugin(self, name):
"""Sets plugin as currently used dictionary"""
systemLog(INFO, "Loading plugin '%s'..." % name)
self.entry.Disable()
self.dictName = name
self.activeDictionary = self.app.dictionaries.get(name)
self.checkIfNeedsList()
self.SetTitle(titleTemplate % name)
self.entry.Enable(1)
self.SetStatusText("Done") # TODO: Set something more useful
self.htmlWin.SetPage("")
# FIXME: deprecated, update!
def loadRegister(self, name):
self.SetTitle(titleTemplate % name) # TODO: should be set after loading
item = self.app.config.registers[name]
self.dictName = name
self.entry.Disable()
if item[1] == "dwa":
self.timerLoad.Start(self.delay)
self.load = Process(SlowoParser, item[0], self)
elif item[1] == "mova":
self.timerLoad.Start(self.delay)
self.load = Process(MovaParser, item[0],
self)
elif item[1] == "tmx":
self.timerLoad.Start(self.delay)
self.load = Process(TMXParser, item[0],
self)
elif item[1] == "dz":
self.timerLoad.Start(self.delay)
self.load = Process(DictParser, item[0],
self)
else:
self.SetStatusText(_("Error: not supported dictionary type"))
return
self.app.config.encoding = item[2]
self.checkEncMenuItem(self.app.config.encoding)
def changeEncoding(self, name):
self.app.config.set('encoding', misc.encodings[name])
if self.activeDictionary:
print "Setting encoding %s for dictionary %s" % \
(self.app.config.get('encoding'), self.activeDictionary.name)
self.activeDictionary.setEncoding(self.app.config.get('encoding'))
systemLog(INFO, "Dictionary encoding set to %s" \
% self.activeDictionary.getEncoding())
plaindict.savePlainConfiguration(self.activeDictionary)
def changeFontFace(self, name):
"""Save font face changes"""
self.app.config.set('fontFace', misc.fontFaces[name])
self.updateHtmlScreen()
def changeFontSize(self, name):
fontSize = int(name) * 10
systemLog(INFO, "Setting font size %d" % fontSize)
self.app.config.set('fontSize', fontSize)
self.updateHtmlScreen()
def updateHtmlScreen(self):
"""Update HtmlWindow screen"""
self.htmlWin.SetFonts(self.app.config.get('fontFace'), "Fixed",
[int(self.app.config.get('fontSize'))]*5)
self.htmlWin.SetPage(self.htmlCode)
def onIncreaseFontSize(self, event):
"""Increase font size"""
self.app.config.set('fontSize', int(self.app.config.get('fontSize'))+2)
self.updateHtmlScreen()
def onDecreaseFontSize(self, event):
"""Decrease font size"""
self.app.config.set('fontSize', int(self.app.config.get('fontSize'))-2)
self.updateHtmlScreen()
def onNormalFontSize(self, event):
"""Set normal font size"""
self.app.config.set('fontSize', NORMAL_FONT_SIZE)
self.updateHtmlScreen()
def checkEncMenuItem(self, name):
"""Select menu item defined by name"""
ename = ""
for key in misc.encodings:
if name == misc.encodings[key]:
ename = key
break
if len(ename) == 0:
systemLog(ERROR, "Something wrong with encodings (name == None)")
return
self.menuEncodings.FindItemById(self.menuEncodings.FindItem(ename)).Check(1)
def getCurrentEncoding(self):
"""Return currently set encoding"""
# Is this the best way for keeping it?
return self.app.config.encoding
def onAddDict(self, event):
installer = Installer(self, self.app.config)
installer.showGUI()
def onAddFromFile(self, event):
"""Starts dictionary registration process"""
fileDialog = wx.FileDialog(self, _("Choose dictionary file"), "", "",
"", wx.FD_OPEN|wx.FD_MULTIPLE)
if fileDialog.ShowModal() == wx.ID_OK:
file = fileDialog.GetPaths()[0]
else:
fileDialog.Destroy()
return
flist = ["Slowo", "Mova", "TMX", "Dict"]
msg = _("Select dictionary format. If you can't find\n" \
"the format of your dictionary, the register\n" \
"system does not support it yet.")
formatDialog = wx.SingleChoiceDialog(self,
msg,
_("Dictionary format"),
flist, wx.OK|wx.CANCEL)
if formatDialog.ShowModal() == wx.ID_OK:
format = formatDialog.GetStringSelection()
else:
formatDialog.Destroy()
return
fileDialog.Destroy()
formatDialog.Destroy()
return self.app.reg.registerDictionary(file, format,
self.app.config.defaultEnc)
def onAddFromPlugin(self, event):
"""Starts plugin installation process"""
dialog = wx.FileDialog(self, _("Choose plugin file"), "", "",
"", wx.FD_OPEN|wx.FD_MULTIPLE)
if dialog.ShowModal() == wx.ID_OK:
plugin.installPlugin(self.app.config, dialog.GetPaths()[0])
dialog.Destroy()
def onManual(self, event):
"""Shows Manual window"""
systemLog(WARNING, "Manual function is not impelemented yet")
def onAbout(self, event):
"""Shows 'About' window"""
aboutWindow = AboutWindow(self, -1,
_("About"),
style=wx.DEFAULT_DIALOG_STYLE)
aboutWindow.CentreOnScreen()
aboutWindow.Show(True)
def onWordSelected(self, event):
"""Is called when word list item is selected"""
if self.search and not self.search.isDone():
return
self.__searchedBySelecting = 1
self.SetStatusText(_("Searching..."))
self.buttonStop.Enable(1)
self.timerSearch.Start(self.delay)
word = event.GetString()
global lastLookupWord
lastLookupWord = word
self.entry.SetValue(word)
word = enc.fromWX(word)
word = word.encode(self.activeDictionary.getEncoding())
self.search = Process(self.activeDictionary.search, word)
wx.BeginBusyCursor()
def createListPanel(self):
self.panelList = wx.Panel(self.splitter, -1)
sbSizerList = wx.StaticBoxSizer(wx.StaticBox(self.panelList, -1,
_("Word List")),
wx.VERTICAL)
self.wordList = wx.ListBox(self.panelList, 154, wx.Point(-1, -1),
wx.Size(-1, -1), self.words, wx.LB_SINGLE)
sbSizerList.Add(self.wordList, 1, wx.ALL | wx.EXPAND, 0)
self.panelList.SetSizer(sbSizerList)
self.panelList.SetAutoLayout(True)
sbSizerList.Fit(self.panelList)
def hideWordList(self):
"""Hides word list"""
systemLog(DEBUG, "Hiding word list...")
self.splitter.SetSashPosition(0)
self.splitter.Unsplit(self.panelList)
self.wlHidden = True
# And change the button pixmap
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "unhide.png"),
wx.BITMAP_TYPE_PNG)
self.buttonHide.SetBitmapLabel(bmp)
self.buttonHide.SetToolTipString(_("Show word list"))
self.buttonHide.Show(False)
def unhideWordList(self):
"""Shows word list"""
systemLog(DEBUG, "Showing word list...")
self.createListPanel()
self.splitter.SplitVertically(self.panelList, self.panelHtml)
self.splitter.SetSashPosition(int(self.app.config.get('sashPos')))
self.wlHidden = False
# And change the pixmap
bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "hide.png"),
wx.BITMAP_TYPE_PNG)
self.buttonHide.SetBitmapLabel(bmp)
self.buttonHide.SetToolTipString(_("Hide word list"))
def onPrint(self, event):
"""This method is invoked when print menu item is selected"""
try:
self.printer.PrintText(self.htmlCode)
except Exception, e:
self.SetStatusText(_("Failed to print"))
systemLog(ERROR, "Unable to print translation (%s)" % e)
traceback.print_exc()
def onPreview(self, event):
"""This method is invoked when preview menu item is selected"""
try:
self.printer.PreviewText(self.htmlCode)
except Exception, e:
systemLog(ERROR, "Unable to preview translation (%s)" % e)
self.SetStatusText(_("Page preview failed"))
traceback.print_exc()
def savePreferences(self):
"""Saves window preferences when exiting"""
if self.app.config.get('saveWindowSize'):
self.app.config.set('windowWidth', self.GetSize()[0])
self.app.config.set('windowHeight', self.GetSize()[1])
if self.app.config.get('saveWindowPos'):
self.app.config.set('windowPosX', self.GetPosition()[0])
self.app.config.set('windowPosY', self.GetPosition()[1])
if self.app.config.get('saveSashPos'):
if not self.wordListHidden():
self.app.config.set('sashPos', self.splitter.GetSashPosition())
try:
self.app.config.save()
except Exception, e:
systemLog(ERROR, "Unable to save configuration: %s" % e)
opendict-0.6.8/lib/gui/miscwin.py 0000664 0000764 0000764 00000011317 13204646653 016655 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
import wx
import wx.html
import shutil
import traceback
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
from lib import enc
from lib.gui import errorwin
_ = wx.GetTranslation
class PluginLicenceWindow(wx.Dialog):
def __init__(self, parent, id, title, msg, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
wx.Dialog.__init__(self, parent, id, title, pos, size, style)
vbox = wx.BoxSizer(wx.VERTICAL)
vboxButtons = wx.BoxSizer(wx.HORIZONTAL)
htmlWin = wx.html.HtmlWindow(self, -1, style=wx.SUNKEN_BORDER)
htmlWin.SetFonts('Helvetica', 'Fixed', [10]*5)
error = False
try:
encodedText = enc.toWX(unicode(msg, 'UTF-8'))
htmlWin.SetPage(encodedText)
except Exception, e:
systemLog(ERROR, "Unable to encode/show licence text: %s" % e)
htmlWin.SetPage(_("Error: unable to show licence text"))
error = True
vbox.Add(htmlWin, 1, wx.ALL | wx.EXPAND, 5)
if not error:
self.buttonNo = wx.Button(self, wx.ID_CANCEL, _("Do not accept"))
vboxButtons.Add(self.buttonNo, 0, wx.ALL, 2)
self.buttonYes = wx.Button(self, wx.ID_OK, _("Accept"))
vboxButtons.Add(self.buttonYes, 0, wx.ALL, 2)
else:
self.buttonNo = wx.Button(self, wx.ID_CANCEL, _("Close"))
vboxButtons.Add(self.buttonNo, 0, wx.ALL, 2)
vbox.Add(vboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
self.SetSizer(vbox)
def showLicenceAgreement(parentWindow, licenceText):
"""Show licence agreement window"""
dialog = PluginLicenceWindow(parentWindow, -1, _("Licence Agreement"),
licenceText, size=(600, 400))
result = dialog.ShowModal()
dialog.Destroy()
if result == wx.ID_OK:
return True
return False
class InvalidDictWindow(wx.Dialog):
def __init__(self, parent, id, title, dicts, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
wx.Dialog.__init__(self, parent, id, title, pos, size, style)
self.dicts = {}
self.buttons = {}
vbox = wx.BoxSizer(wx.VERTICAL)
vboxButtons = wx.BoxSizer(wx.HORIZONTAL)
vboxDicts = wx.BoxSizer(wx.VERTICAL)
grid = wx.FlexGridSizer(2, 2, 5, 5)
msg = _("You have directories that containt invalid dictionaries " \
"and cannot be loaded. \nYou can try to remove these " \
"directories right now.")
vbox.Add(wx.StaticText(self, -1, msg),
0, wx.ALL, 5)
row = 0
for d in dicts:
grid.Add(wx.StaticText(self, -1, d),
0, wx.ALIGN_CENTER_VERTICAL)
rid = wx.NewId()
self.dicts[rid] = d
b = wx.Button(self, rid, _("Remove"))
self.buttons[rid] = b
grid.Add(b, 1, wx.ALIGN_CENTER_VERTICAL)
wx.EVT_BUTTON(self, rid, self.onRemove)
vbox.Add(grid, 0, wx.ALL, 10)
vbox.Add(wx.StaticLine(self, -1), 1, wx.ALL | wx.EXPAND, 1)
self.buttonClose = wx.Button(self, wx.ID_CANCEL, _("Close"))
vboxButtons.Add(self.buttonClose, 0, wx.ALL, 5)
vbox.Add(vboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
self.SetSizer(vbox)
self.Fit()
def onRemove(self, event):
path = self.dicts[event.GetId()]
try:
shutil.rmtree(path)
self.buttons[event.GetId()].Disable()
except Exception, e:
traceback.print_exc()
title = _("Unable to remove")
msg = _("Unable to remove directory \"%s\": %s") % (path, e)
errorwin.showErrorMessage(title, msg)
def showInvalidDicts(parentWin, invalidDicts):
"""Show licence agreement window"""
dialog = InvalidDictWindow(None, -1, _("Invalid Dictionaries"),
invalidDicts)
result = dialog.ShowModal()
dialog.Destroy()
opendict-0.6.8/lib/gui/pluginwin.py 0000664 0000764 0000764 00000061235 13204646653 017224 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
#from wx import *
#import wx.lib.mixins.listctrl as listmix
import wx
from shutil import rmtree
import os
import traceback
import time
from lib.gui import errorwin
from lib import installer
from lib import dicttype
from lib import enc
from lib import info
from lib import misc
from lib import xmltools
from lib import util
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
_ = wx.GetTranslation
class DictListCtrl(wx.ListCtrl):
def __init__(self, parent, ID, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
class PluginManagerWindow(wx.Frame):
"""Plugin Manager lets install, remove and view info
about installed plugins"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.app = wx.GetApp()
self.mainWin = parent
self.currentInstalledItemSelection = -1
self.currentAvailItemSelection = -1
vboxMain = wx.BoxSizer(wx.VERTICAL)
self.installedDictionaries = {}
self.availDictionaries = self.app.cache.get('addons') or {}
installed = True
for dictName in self.app.dictionaries.keys():
self.installedDictionaries[dictName] = installed
tabbedPanel = wx.Notebook(self, -1)
# Add 'installed' panel
panelInstalled = self._makeInstalledPanel(tabbedPanel)
tabbedPanel.AddPage(panelInstalled, _("Installed"))
# Add 'available' panel
panelAvailable = self._makeAvailablePanel(tabbedPanel)
tabbedPanel.AddPage(panelAvailable, _("Available"))
vboxMain.Add(tabbedPanel, 1, wx.ALL | wx.EXPAND, 2)
# Add info panel
panelInfo = self._makeInfoPanel()
vboxMain.Add(panelInfo, 0, wx.ALL | wx.EXPAND, 2)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
self.buttonClose = wx.Button(self, 163, _("Close"))
hboxButtons.Add(self.buttonClose, 0, wx.ALL | wx.ALIGN_RIGHT, 3)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 1)
self.SetIcon(wx.Icon(os.path.join(info.GLOBAL_HOME,
"pixmaps",
"icon-24x24.png"),
wx.BITMAP_TYPE_PNG))
self.SetSizer(vboxMain)
self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onPageChanged)
wx.EVT_BUTTON(self, 161, self.onInstall)
wx.EVT_BUTTON(self, 162, self.onRemove)
wx.EVT_BUTTON(self, 163, self.onClose)
self.addons = self.app.cache.get("addons", {})
def _makeInstalledPanel(self, tabbedPanel):
"""Creates panel with for controlling installed dictionaries"""
#
# Boxes
#
panelInstalled = wx.Panel(tabbedPanel, -1)
vboxInstalled = wx.BoxSizer(wx.VERTICAL)
# Help message
labelHelp = wx.StaticText(panelInstalled, -1,
_("Checked dictionaries are available from the " \
"menu, unchecked dictionaries \nare not available from the menu."));
vboxInstalled.Add(labelHelp, 0, wx.ALL, 3)
#
# Installed list
#
idDictList = wx.NewId()
self.installedList = wx.CheckListBox(panelInstalled, idDictList,
style=wx.LC_REPORT
| wx.LC_SINGLE_SEL
| wx.SUNKEN_BORDER)
self.Bind(wx.EVT_CHECKLISTBOX, self.onDictionaryChecked,
self.installedList)
self.Bind(wx.EVT_LISTBOX, self.onInstalledSelected,
self.installedList)
vboxInstalled.Add(self.installedList, 1, wx.ALL | wx.EXPAND, 1)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
#
# "Install from file" button
#
idInstallFile = wx.NewId()
self.buttonInstallFile = wx.Button(panelInstalled, idInstallFile,
_("Install From File"))
hboxButtons.Add(self.buttonInstallFile, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
#
# "Remove" button
#
idRemove = wx.NewId()
self.buttonRemove = wx.Button(panelInstalled, idRemove, _("Remove"))
self.buttonRemove.Disable()
hboxButtons.Add(self.buttonRemove, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
vboxInstalled.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
panelInstalled.SetSizer(vboxInstalled)
vboxInstalled.Fit(panelInstalled)
#
# Make columns
#
dictNames = self.installedDictionaries.keys()
dictNames.sort()
self.setInstalledDicts(dictNames)
self.Bind(wx.EVT_BUTTON, self.onRemove, self.buttonRemove)
self.Bind(wx.EVT_BUTTON, self.onInstallFile, self.buttonInstallFile)
return panelInstalled
def _makeAvailablePanel(self, tabbedPanel):
"""Creates panel with for controlling installed dictionaries"""
#
# Boxes
#
panelAvailable = wx.Panel(tabbedPanel, -1)
vboxAvailable = wx.BoxSizer(wx.VERTICAL)
#
# List of available dictionaries
#
idAvailList = wx.NewId()
self.availableList = DictListCtrl(panelAvailable, idAvailList,
style=wx.LC_REPORT
| wx.LC_SINGLE_SEL
#| wx.LC_NO_HEADER
| wx.SUNKEN_BORDER)
vboxAvailable.Add(self.availableList, 1, wx.ALL | wx.EXPAND, 1)
# Horizontal box for buttons
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
#
# "Update" button
#
idUpdate = wx.NewId()
self.buttonUpdate = wx.Button(panelAvailable, idUpdate,
_("Update List"))
hboxButtons.Add(self.buttonUpdate, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
#
# "Install" button
#
idInstall = wx.NewId()
self.buttonInstall = wx.Button(panelAvailable, idInstall, _("Install"))
self.buttonInstall.Disable()
hboxButtons.Add(self.buttonInstall, 0, wx.ALL | wx.ALIGN_RIGHT, 2)
vboxAvailable.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 1)
panelAvailable.SetSizer(vboxAvailable)
vboxAvailable.Fit(panelAvailable)
#
# Make columns
#
self.availableList.InsertColumn(0, _("Name"))
self.availableList.InsertColumn(1, _("Size"))
addons = self.app.cache.get('addons')
if not addons:
addons = {}
dictNames = addons.keys()
dictNames.sort()
for dictionary in dictNames:
index = self.availableList.InsertStringItem(0, dictionary)
sizeString = "%d KB" % addons.get(dictionary).getSize()
self.availableList.SetStringItem(index, 1,
sizeString)
self.availableList.SetItemData(index, index+1)
# Keep wide if list is empty yet
if addons:
self.availableList.SetColumnWidth(0, wx.LIST_AUTOSIZE)
self.availableList.SetColumnWidth(1, wx.LIST_AUTOSIZE)
else:
self.availableList.SetColumnWidth(0, 200)
self.availableList.SetColumnWidth(1, 120)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onAvailableSelected,
self.availableList)
self.Bind(wx.EVT_BUTTON, self.onInstall, self.buttonInstall)
self.Bind(wx.EVT_BUTTON, self.onUpdate, self.buttonUpdate)
return panelAvailable
def _makeInfoPanel(self):
"""Create information panel"""
#
# Boxes
#
panelInfo = wx.Panel(self, -1)
vboxInfo = wx.BoxSizer(wx.VERTICAL)
vboxInfoBox = wx.BoxSizer(wx.VERTICAL)
sbSizerInfo = wx.StaticBoxSizer(\
wx.StaticBox(panelInfo, -1,
_("Information About Dictionary")),
wx.VERTICAL)
grid = wx.FlexGridSizer(3, 2, 1, 1)
self.labelName = wx.StaticText(panelInfo, -1, "")
self.labelVersion = wx.StaticText(panelInfo, -1, "")
self.labelFormat = wx.StaticText(panelInfo, -1, "")
self.labelAuthor = wx.StaticText(panelInfo, -1, "")
self.labelSize = wx.StaticText(panelInfo, -1, "")
self.textAbout = wx.TextCtrl(panelInfo, -1, size=(-1, 100),
style=wx.TE_MULTILINE | wx.TE_READONLY)
self.stName = wx.StaticText(panelInfo, -1, _("Name: "))
self.stName.Disable()
grid.Add(self.stName, 0, wx.ALL | wx.ALIGN_RIGHT)
grid.Add(self.labelName, 0, wx.ALL)
self.stVersion = wx.StaticText(panelInfo, -1, _("Version: "))
self.stVersion.Disable()
grid.Add(self.stVersion, 0, wx.ALL | wx.ALIGN_RIGHT)
grid.Add(self.labelVersion, 0, wx.ALL)
self.stAuthor = wx.StaticText(panelInfo, -1, _("Maintainer: "))
self.stAuthor.Disable()
grid.Add(self.stAuthor, 0, wx.ALL | wx.ALIGN_RIGHT)
grid.Add(self.labelAuthor, 0, wx.ALL)
vboxInfoBox.Add(grid, 1, wx.ALL | wx.EXPAND, 1)
vboxInfoBox.Add(self.textAbout, 0, wx.ALL | wx.EXPAND, 1)
sbSizerInfo.Add(vboxInfoBox, 1, wx.ALL | wx.EXPAND, 5)
vboxInfo.Add(sbSizerInfo, 1, wx.ALL | wx.EXPAND, 5)
panelInfo.SetSizer(vboxInfo)
vboxInfo.Fit(panelInfo)
return panelInfo
def onDictionaryChecked(self, event, *args):
index = event.GetSelection()
label = self.installedList.GetString(index)
if self.installedList.IsChecked(index):
self._addDictToMenu(label)
d = self.app.dictionaries.get(label)
d.setActive()
else:
self._removeDictFromMenu(label)
d = self.app.dictionaries.get(label)
d.setActive(active=False)
self.installedList.SetSelection(index)
def _removeDictFromMenu(self, name):
self.app.config.activedict.remove(name)
self.app.config.activedict.save()
self.app.window.removeDictionary(name)
def _addDictToMenu(self, name):
dict = None
for k, v in self.app.dictionaries.items():
if k == name:
dict = v
if dict:
self.app.config.activedict.add(name)
self.app.config.activedict.save()
self.app.window.addDictionary(dict)
def onPageChanged(self, event):
_pageInstalled = 0
_pageAvail = 1
sel = event.GetSelection()
if sel == _pageInstalled:
if self.currentInstalledItemSelection == -1:
self.clearInfo()
self.disableInfo()
else:
self.enableInfo()
self.showInstalledInfo()
elif sel == _pageAvail:
if self.currentAvailItemSelection == -1:
self.clearInfo()
self.disableInfo()
else:
self.enableInfo()
self.showAvailableInfo()
def onInstalledSelected(self, event):
"""Called when list item is selected"""
self.currentInstalledItemSelection = event.GetSelection()
self.buttonRemove.Enable(1)
self.showInstalledInfo()
def showInstalledInfo(self):
"""Show information about selected dictionary"""
dictName = self.installedList.GetString(\
self.currentInstalledItemSelection)
dictInstance = self.app.dictionaries.get(dictName)
self.showInfo(dictInstance)
def showAvailableInfo(self):
"""Show information about selected dictionary"""
dictName = self.availableList.GetItemText(\
self.currentAvailItemSelection)
dictInstance = self.addons.get(dictName)
if not dictInstance:
systemLog(ERROR, "BUG: add-on '%s' not found by name" % dictName)
return
self.showInfo(dictInstance)
def showInfo(self, dictInstance):
"""Show information about dictionary"""
self.stName.Enable(1)
self.stVersion.Enable(1)
self.stAuthor.Enable(1)
if dictInstance.getName():
dictName = enc.toWX(dictInstance.getName())
else:
dictName = '--'
self.labelName.SetLabel(dictName)
if dictInstance.getVersion():
dictVersion = enc.toWX(dictInstance.getVersion())
else:
dictVersion = '--'
self.labelVersion.SetLabel(dictVersion)
if dictInstance.getAuthors():
authors = []
for author in dictInstance.getAuthors():
if author:
authors.append("%s <%s>" % (author.get('name'),
author.get('email')))
dictAuthors = enc.toWX(', '.join(authors))
else:
dictAuthors = '--'
self.labelAuthor.SetLabel(dictAuthors)
if dictInstance.getDescription():
description = enc.toWX(dictInstance.getDescription().strip())
else:
description = ''
self.textAbout.Clear()
self.textAbout.WriteText(description)
def onAvailableSelected(self, event):
self.currentAvailItemSelection = event.m_itemIndex
self.buttonInstall.Enable(1)
self.showAvailableInfo()
def clearInfo(self):
"""Clear info fields"""
self.labelName.SetLabel('')
self.labelVersion.SetLabel('')
self.labelAuthor.SetLabel('')
self.textAbout.Clear()
def disableInfo(self):
"""Make info widgets inactive"""
self.stName.Disable()
self.stVersion.Disable()
self.stAuthor.Disable()
self.textAbout.Disable()
def enableInfo(self):
"""Make info widgets active"""
self.stName.Enable(1)
self.stVersion.Enable(1)
self.stAuthor.Enable(1)
self.textAbout.Enable(1)
def setInstalledDicts(self, dictNames):
"""Clear the list of installed dictionaries and set new items"""
for i in range(self.installedList.GetCount()):
self.installedList.Delete(i)
dictNames.sort()
i = 0
for dictionary in dictNames:
index = self.installedList.Insert(dictionary, i)
if self.app.dictionaries[dictionary].getActive():
self.installedList.Check(i)
i += 1
def setAvailDicts(self, addons):
"""Clear the list of available dictionaries and set
new items"""
self.availableList.DeleteAllItems()
names = addons.keys()
names.sort()
names.reverse()
for name in names:
addon = addons.get(name)
index = self.availableList.InsertStringItem(0, addon.getName())
self.availableList.SetStringItem(index, 1,
str(addon.getSize())+" KB")
self.availableList.SetItemData(index, index+1)
if names:
self.availableList.SetColumnWidth(0, wx.LIST_AUTOSIZE)
else:
title = _("List updated")
msg = _("All your dictionaries are up to date.")
errorwin.showInfoMessage(title, msg)
def onUpdate(self, event):
"""Update dictionaries list"""
title = _("Downloading List")
downloader = util.DownloadThread(self.app.config.get('repository-list'))
progressDialog = wx.ProgressDialog(title,
'',
maximum=100,
parent=self,
style=wx.PD_CAN_ABORT
| wx.PD_APP_MODAL)
keepGoing = True
error = None
try:
systemLog(INFO, "Opening %s..." % \
self.app.config.get('repository-list'))
downloader.start()
xmlData = ''
while keepGoing and not downloader.finished():
keepGoing = progressDialog.Update(downloader.getPercentage(),
downloader.getMessage())
if not keepGoing:
downloader.stop()
break
xmlData += downloader.getBytes()
time.sleep(0.1)
progressDialog.Destroy()
xmlData += downloader.getBytes()
systemLog(INFO, "Finished downloading list")
except Exception, e:
traceback.print_exc()
progressDialog.Destroy()
error = _("Unable to download list from %s: %s") \
% (self.app.config.get('repository-list'), e)
if not error:
error = downloader.getErrorMessage()
if error:
systemLog(ERROR, error)
title = _("Unable to download list")
errorwin.showErrorMessage(title, error)
return
if len(xmlData) == 0:
return
if hasattr(self, "addons"):
del self.addons
allAddons = xmltools.parseAddOns(xmlData)
self.addons = {}
for name, obj in allAddons.items():
if name in self.app.dictionaries.keys() \
and obj.getVersion() <= (\
self.app.dictionaries.get(name).getVersion() or ""):
continue
self.addons[name] = obj
app = wx.GetApp()
if app.cache.has_key("addons"):
del app.cache["addons"]
app.cache["addons"] = self.addons
self.setAvailDicts(self.addons)
def onInstall(self, event):
"""Install button pressed"""
name = self.availableList.GetItemText(\
self.currentAvailItemSelection)
dictInfo = self.addons.get(name)
if not dictInfo:
systemLog(ERROR, "Interal Error, add-on %s not found in list" \
% name)
return
self._fetchAddon(dictInfo)
def onInstallFile(self, event):
"""Install dictionary from file"""
inst = installer.Installer(self.mainWin, self.app.config)
inst.showGUI()
dictNames = []
for name in self.app.dictionaries.keys():
dictNames.append(enc.toWX(name))
self.setInstalledDicts(dictNames)
def onRemove(self, event):
"""Remove button pressed"""
systemLog(INFO, "Removing %s" % self.installedList.GetString(
self.currentInstalledItemSelection))
dictName = self.installedList.GetString(
self.currentInstalledItemSelection)
dictInstance = self.app.dictionaries.get(dictName)
try:
if dictInstance.getType() == dicttype.PLUGIN:
removeDictionary = installer.removePluginDictionary
else:
removeDictionary = installer.removePlainDictionary
removeDictionary(dictInstance)
except Exception, e:
traceback.print_exc()
title = _("Unable to remove")
msg = _("Unable to remove dictionary \"%s\"") % dictName
errorwin.showErrorMessage(title, msg)
return
self.installedList.Delete(self.currentInstalledItemSelection)
idDictMenuItem = None
for iid, dictionary in self.app.config.ids.items():
if dictionary == dictName:
idDictMenuItem = iid
if idDictMenuItem is not None:
self.mainWin.menuDict.Delete(idDictMenuItem)
parent = self.GetParent()
if parent.activeDictionary \
and dictName == parent.activeDictionary.getName():
parent.onCloseDict(None)
self.buttonRemove.Disable()
del self.app.dictionaries[dictName]
self.clearInfo()
self.disableInfo()
def onClose(self, event):
"""Close event occured"""
self.Destroy()
def _fetchAddon(self, dictInfo):
"""Fetch add-on using progress bar"""
downloadsDir = os.path.join(info.LOCAL_HOME, 'downloads')
if not os.path.exists(downloadsDir):
os.mkdir(downloadsDir)
localPath = os.path.join(downloadsDir,
os.path.basename(dictInfo.getLocation()))
title = _("Downloading %s...") % dictInfo.getName()
progressDialog = wx.ProgressDialog(title,
'',
maximum=100,
parent=self,
style=wx.PD_CAN_ABORT
| wx.PD_APP_MODAL)
keepGoing = True
error = None
downloader = util.DownloadThread(dictInfo.getLocation())
stopped = False
try:
fd = open(localPath, 'wb')
downloader.start()
while keepGoing and not downloader.finished():
keepGoing = progressDialog.Update(downloader.getPercentage(),
downloader.getMessage())
if not keepGoing:
stopped = True
break
chunk = downloader.getBytes()
fd.write(chunk)
time.sleep(0.1)
bytes = downloader.getBytes()
if len(bytes):
fd.write(bytes)
progressDialog.Destroy()
downloader.stop()
except Exception, e:
traceback.print_exc()
progressDialog.Destroy()
error = "Unable to fetch \"%s\" from %s: %s" \
% (dictInfo.getName(), dictInfo.getLocation(), e)
systemLog(ERROR, error)
fd.close()
if stopped:
return
if not error:
error = downloader.getErrorMessage()
if error:
systemLog(ERROR, error)
title = _("Unable to download")
errorwin.showErrorMessage(title, error)
return
md5sum = util.getMD5Sum(localPath)
#
# Check checksum
#
if md5sum != dictInfo.getChecksum():
title = _("File is damaged")
msg = _("Downloaded file is damaged and cannot be installed. " \
"Please try again.")
errorwin.showErrorMessage(title, msg)
return
#
# Remove old version if exists
#
if dictInfo.getName() in self.app.dictionaries.keys():
try:
dictInstance = self.app.dictionaries.get(dictInfo.getName())
if dictInstance.getType() == dicttype.PLUGIN:
installer.removePluginDictionary(dictInstance)
else:
installer.removePlainDictionary(dictInstance)
except Exception, e:
traceback.print_exc()
title = _("Error")
msg = _("Unable to remove old version of \"%s\". "
"Error occured: \"%s\". New version "
"cannot be installed without removing old one.") \
% (dictInstance.getName(), e)
errorwin.showErrorMessage(title, msg)
return
#
# Install
#
try:
inst = installer.Installer(self.mainWin, self.app.config)
inst.install(localPath)
if self.installedList.FindString(dictInfo.getName()) == wx.NOT_FOUND:
index = self.installedList.Insert(dictInfo.getName(), 0)
self.installedList.Check(0)
self.app.config.activedict.add(dictInfo.getName())
self.app.config.activedict.save()
# FIXME: Code-wasting. Separated duplicated code into
# functions.
except Exception, e:
traceback.print_exc()
title = _("Unable to install")
msg = _("Unable to install dictionary \"%s\".") \
% dictInfo.getName()
errorwin.showErrorMessage(title, msg)
return
self.availableList.DeleteItem(self.currentAvailItemSelection)
del self.addons[dictInfo.getName()]
self.buttonInstall.Disable()
self.clearInfo()
self.disableInfo()
opendict-0.6.8/lib/gui/prefswin.py 0000664 0000764 0000764 00000022427 13204646653 017045 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
import wx
from lib.logger import systemLog, debugLog, DEBUG, INFO, WARNING, ERROR
from lib.misc import encodings
from lib import enc
_ = wx.GetTranslation
PRON_COMMAND = "echo \"(SayText \\\"%s\\\")\" | festival"
class PrefsWindow(wx.Dialog):
"""Preferences dialog class"""
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
"""Initialize preferences dialog window"""
wx.Dialog.__init__(self, parent, id, title, pos, size, style)
self.app = wx.GetApp()
vboxMain = wx.BoxSizer(wx.VERTICAL)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
grid = wx.FlexGridSizer(4, 2, 1, 1)
grid.Add(wx.StaticText(self, -1, _("Default dictionary: ")),
0, wx.ALIGN_CENTER_VERTICAL)
dictNames = []
for name, d in self.app.dictionaries.items():
if d.getActive():
dictNames.append(name)
dictNames.sort()
dictNames.insert(0, "")
try:
map(enc.toWX, dictNames)
except Exception, e:
systemLog(ERROR, "Unable to decode titles to UTF-8 (%s)" % e)
self.dictChooser = wx.ComboBox(self, 1100,
enc.toWX(self.app.config.get('defaultDict')),
wx.Point(-1, -1),
wx.Size(-1, -1), dictNames, wx.TE_READONLY)
grid.Add(self.dictChooser, 0, wx.EXPAND)
grid.Add(wx.StaticText(self, -1, _("Default encoding: ")),
0, wx.ALIGN_CENTER_VERTICAL)
self.encChooser = wx.ComboBox(self, 1108,
encodings.keys()[encodings.values().index(self.app.config.get('encoding'))],
wx.Point(-1, -1),
wx.Size(-1, -1), encodings.keys(),
wx.TE_READONLY)
grid.Add(self.encChooser, 0, wx.EXPAND | wx.ALIGN_RIGHT)
grid.AddGrowableCol(1)
grid.Add(wx.StaticText(self, -1, _("Default DICT server: ")),
0, wx.ALIGN_CENTER_VERTICAL)
self.serverEntry = wx.TextCtrl(self, -1,
self.app.config.get('dictServer'))
grid.Add(self.serverEntry, 0, wx.EXPAND)
grid.Add(wx.StaticText(self, -1, _("Default DICT server port: ")),
0, wx.ALIGN_CENTER_VERTICAL)
self.portEntry = wx.TextCtrl(self, -1,
self.app.config.get('dictServerPort'))
grid.Add(self.portEntry, 0, wx.EXPAND)
vboxMain.Add(grid, 0, wx.ALL | wx.EXPAND, 4)
#
# Pronunciation
#
panelPron = wx.Panel(self, -1)
sbSizerPron = wx.StaticBoxSizer(wx.StaticBox(panelPron, -1,
_("Pronunciation")),
wx.VERTICAL)
panelPron.SetSizer(sbSizerPron)
panelPron.SetAutoLayout(True)
sbSizerPron.Fit(panelPron)
vboxMain.Add(panelPron, 0, wx.ALL | wx.EXPAND, 5)
hboxPronCmd = wx.BoxSizer(wx.HORIZONTAL)
hboxPronCmd.Add(wx.StaticText(panelPron, -1, _("System Command: ")), 0,
wx.ALIGN_CENTER_VERTICAL)
self.entryPron = wx.TextCtrl(panelPron, -1,
self.app.config.get('pronunciationCommand') or \
PRON_COMMAND)
hboxPronCmd.Add(self.entryPron, 1, wx.EXPAND, 0)
self.buttonDefaultPron = wx.Button(panelPron, 1106, _("Default"))
hboxPronCmd.Add(self.buttonDefaultPron, 0, wx.ALL | wx.EXPAND)
sbSizerPron.Add(hboxPronCmd, 0, wx.ALL | wx.EXPAND, 4)
hboxPronWhat = wx.BoxSizer(wx.HORIZONTAL)
self.rbPronOrig = wx.RadioButton(panelPron, -1, _("Pronounce original word"))
hboxPronWhat.Add(self.rbPronOrig, 0, wx.ALL | wx.EXPAND, 3)
self.rbPronTrans = wx.RadioButton(panelPron, -1, _("Pronounce translation"))
if self.app.config.get('pronounceTrans') == 'True':
self.rbPronTrans.SetValue(True)
hboxPronWhat.Add(self.rbPronTrans, 0, wx.ALL | wx.EXPAND, 3)
sbSizerPron.Add(hboxPronWhat, 0, wx.ALL | wx.EXPAND, 0)
self.winSize = wx.CheckBox(self, 1101, _("Save window size on exit"))
self.winSize.SetValue(self.app.config.get('saveWindowSize') == 'True')
vboxMain.Add(self.winSize, 0, wx.ALL, 3)
self.winPos = wx.CheckBox(self, 1102, _("Save window position on exit"))
self.winPos.SetValue(self.app.config.get('saveWindowPos') == 'True')
vboxMain.Add(self.winPos, 0, wx.ALL, 3)
self.sashPos = wx.CheckBox(self, 1103, _("Save sash position on exit"))
self.sashPos.SetValue(self.app.config.get('saveSashPos') == 'True')
vboxMain.Add(self.sashPos, 0, wx.ALL, 3)
self.clipboard = wx.CheckBox(self, 1103,
_("Take words from the clipboard by default"))
self.clipboard.SetValue(self.app.config.get('useClipboard') == 'True')
vboxMain.Add(self.clipboard, 0, wx.ALL, 3)
vboxMain.Add(wx.StaticLine(self, -1), 0, wx.ALL | wx.EXPAND, 5)
self.buttonOK = wx.Button(self, 1104, _("OK"))
hboxButtons.Add(self.buttonOK, 0, wx.ALL | wx.EXPAND, 1)
self.buttonCancel = wx.Button(self, 1105, _("Cancel"))
hboxButtons.Add(self.buttonCancel, 0, wx.ALL | wx.EXPAND, 1)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 4)
self.SetSizer(vboxMain)
self.Fit()
self.SetSize((400, -1))
wx.EVT_CHECKBOX(self, 1101, self.onSaveWinSizeClicked)
wx.EVT_CHECKBOX(self, 1102, self.onSaveWinPosClicked)
wx.EVT_CHECKBOX(self, 1103, self.onSaveSashPosClicked)
wx.EVT_BUTTON(self, 1106, self.onDefaultPron)
wx.EVT_BUTTON(self, 1104, self.onOK)
wx.EVT_BUTTON(self, 1105, self.onCancel)
def onSaveWinSizeClicked(self, event):
"""This method is invoked when checkbox for window size
is clicked"""
if event.Checked() == 1:
self.app.config.winSize = self.GetParent().GetSize()
self.app.config.saveWinSize = 1
else:
self.app.config.saveWinSize = 0
def onSaveWinPosClicked(self, event):
"""This method is invoked when checkbox for window position
is clicked"""
if event.Checked() == 1:
self.app.config.winPos = self.GetParent().GetPosition()
self.app.config.saveWinPos = 1
else:
self.app.config.saveWinPos = 0
def onSaveSashPosClicked(self, event):
"""This method is invoked when checkbox for sash position
is clicked"""
if event.Checked() == 1:
self.app.config.sashPos = self.GetParent().splitter.GetSashPosition()
self.app.config.saveSashPos = 1
else:
self.app.config.saveSashPos = 0
def onDefaultPron(self, event):
"""Set pronunciation command to default value"""
self.entryPron.SetValue(PRON_COMMAND)
def onOK(self, event):
"""Save configuration in the configuration object"""
self.app.config.set('defaultDict',
enc.fromWX(self.dictChooser.GetValue()))
self.app.config.set('encoding', encodings[self.encChooser.GetValue()])
if self.app.window.activeDictionary == None:
self.app.window.checkEncMenuItem(self.app.config.get('encoding'))
self.app.config.set('dictServer', self.serverEntry.GetValue())
self.app.config.set('dictServerPort', self.portEntry.GetValue())
self.app.config.set('pronunciationCommand', self.entryPron.GetValue())
self.app.config.set('pronounceTrans', str(self.rbPronTrans.GetValue()))
self.app.config.set('saveWindowSize', str(self.winSize.GetValue()))
self.app.config.set('saveWindowPos', str(self.winPos.GetValue()))
self.app.config.set('saveSashPos', str(self.sashPos.GetValue()))
self.app.config.set('useClipboard', str(self.clipboard.GetValue()))
frame = self.GetParent()
if self.app.config.get('saveWinSize'):
self.app.config.set('windowWidth', frame.GetSize()[0])
self.app.config.set('windowHeight', frame.GetSize()[1])
if self.app.config.get('saveWindowPos'):
self.app.config.set('windowPosX', frame.GetPosition()[0])
self.app.config.set('windowPosY', frame.GetPosition()[1])
if self.app.config.get('saveSashPos'):
if not frame.wordListHidden():
self.app.config.set('sashPos', frame.splitter.GetSashPosition())
self.app.config.save()
self.Destroy()
def onCancel(self, event):
"""Close dialog window discarding changes"""
self.Destroy()
opendict-0.6.8/lib/gui/registerwin.py 0000664 0000764 0000764 00000012454 13204646653 017551 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# Module: gui.registerwin
import wx
import os
from info import home, uhome
_ = wx.GetTranslation
class FileRegistryWindow(wx.Frame):
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self.app = wx.GetApp()
vboxMain = wx.BoxSizer(wx.VERTICAL)
self.types = {}
self.types['dwa'] = "Slowo"
self.types['mova'] = "Mova"
self.types['tmx'] = "TMX"
self.types['dz'] = "DICT"
self.fileList = wx.ListBox(self, 190,
wx.Point(-1, -1),
wx.Size(-1, -1),
self.app.config.registers.keys(),
wx.LB_SINGLE | wx.SUNKEN_BORDER)
vboxMain.Add(self.fileList, 1, wx.ALL | wx.EXPAND, 1)
vboxInfo = wx.BoxSizer(wx.VERTICAL)
if len(self.app.config.registers.keys()) > 0:
self.fileList.SetSelection(0)
name = self.fileList.GetStringSelection()
item = self.app.config.registers[name]
else:
# There's no registered dictionaries
name = ""
item = []
item.extend(["", "", ""])
self.labelName = wx.StaticText(self, -1, _("Name: %s") % name)
vboxInfo.Add(self.labelName, 0, wx.ALL, 0)
self.labelPath = wx.StaticText(self, -1, _("Path: %s") % item[0])
vboxInfo.Add(self.labelPath, 0, wx.ALL, 0)
self.labelFormat = wx.StaticText(self, -1, _("Format: %s") % item[1])
vboxInfo.Add(self.labelFormat, 0, wx.ALL, 0)
self.labelEnc = wx.StaticText(self, -1, _("Encoding: %s") % item[2])
vboxInfo.Add(self.labelEnc, 0, wx.ALL, 0)
vboxMain.Add(vboxInfo, 0, wx.ALL | wx.EXPAND, 10)
hboxButtons = wx.BoxSizer(wx.HORIZONTAL)
self.buttonInstall = wx.Button(self, 191, _("Add new..."))
# FIXME: Needs to be rewritten
#hboxButtons.Add(self.buttonInstall, 1, wx.ALL | wx.EXPAND, 1)
self.buttonRemove = wx.Button(self, 192, _("Remove selected"))
hboxButtons.Add(self.buttonRemove, 1, wx.ALL | wx.EXPAND, 1)
self.buttonClose = wx.Button(self, 193, _("Close"))
hboxButtons.Add(self.buttonClose, 1, wx.ALL | wx.EXPAND, 1)
vboxMain.Add(hboxButtons, 0, wx.ALL | wx.EXPAND, 2)
self.SetSizer(vboxMain)
self.Fit()
wx.EVT_LISTBOX(self, 190, self.onFileSelected)
wx.EVT_BUTTON(self, 191, self.onInstall)
wx.EVT_BUTTON(self, 192, self.onRemove)
wx.EVT_BUTTON(self, 193, self.onClose)
def onFileSelected(self, event):
info = self.app.config.registers[event.GetString()]
self.labelName.SetLabel(_("Name: %s") % event.GetString())
self.labelPath.SetLabel(_("Path: %s") % info[0])
self.labelFormat.SetLabel(_("Format: %s") % self.types[info[1]])
self.labelEnc.SetLabel(_("Encoding: %s") % info[2])
def onInstall(self, event):
self.fileList.Append(self.app.window.onAddFromFile(None))
def onRemove(self, event):
self.app.window.onCloseDict(None)
pos = self.fileList.GetSelection()
item = self.fileList.GetStringSelection()
if item == "":
return
self.fileList.Delete(pos)
parent = self.GetParent()
parent.menuDict.Delete(parent.menuDict.FindItem(item))
if self.app.config.registers[item][1] != "Dict":
if os.path.exists(os.path.join(uhome, "register", item+".hash")):
try:
os.remove(os.path.join(uhome, "register", item+".hash"))
except:
self.app.window.SetStatusText(_("Error while deleting \"%s\"") \
% (item+".hash"))
return
elif os.path.exists(os.path.join(home, "register", item+".hash")):
try:
os.remove(os.path.join(home, "register", item+".hash"))
except:
self.app.window.SetStatusText(_("Error while deleting \"%s\"") \
% (item+".hash"))
return
del self.app.config.ids[item]
del self.app.config.registers[item]
for list in self.app.config.groups.values():
if item in list:
list.remove(item)
self.labelName.SetLabel(_("Name: %s") % "")
self.labelPath.SetLabel(_("Path: %s") % "")
self.labelFormat.SetLabel(_("Format: %s") % "")
self.labelEnc.SetLabel(_("Encoding: %s") % "")
def onClose(self, event):
self.Destroy()
opendict-0.6.8/lib/tests/ 0000775 0000764 0000764 00000000000 13204646653 015205 5 ustar nerijus nerijus opendict-0.6.8/lib/tests/test_editor.py 0000664 0000764 0000764 00000006702 13204646653 020111 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# Unit Test for editor.py
#
"""
Unit tests for editor.py
"""
import unittest
import os
import sys
sys.path.append('..')
import dicteditor
class TestTranslation(unittest.TestCase):
"""Translation test"""
translations = dicteditor.Translation()
def test_word(self):
"""Set/Get word should return correct value"""
self.translations.setWord('test')
self.assertEquals(self.translations.getWord(), 'test')
def test_translation(self):
"""Should return correct translations"""
self.translations.addTranslation('trans1')
self.translations.addTranslation('trans2', 'comment2')
self.translations.addTranslation('trans3')
self.translations.addTranslation('trans3', 'comment3')
trans = self.translations.getTranslations()
self.assertEquals(trans.has_key('trans1'), True)
self.assertEquals(len(trans.keys()), 3)
self.assertEquals(trans['trans3'], 'comment3')
trans = {'key1': 'value1', 'key2': 'value2'}
self.translations.setTranslations(trans)
self.assertEquals(len(self.translations.getTranslations()), 2)
class TestEditor(unittest.TestCase):
"""Editor test"""
def test_load(self):
"""Editor should load dictionary from file"""
editor = dicteditor.Editor()
self.assertEquals(len(editor.getUnits()), 0)
editor.load("data/sampledict.dwa")
self.assertEquals(len(editor.getUnits()), 7)
def test_save(self):
"""Editor should correctly write dictionary to disk"""
editor = dicteditor.Editor()
editor.load("data/sampledict.dwa")
units = editor.getUnits()
editor.save("data/__output.dwa")
editor.load("data/__output.dwa")
self.assertEquals(len(units), len(editor.getUnits()))
os.unlink("data/__output.dwa")
def test_getUnit(self):
"""getUnit() should return desired Translation object"""
editor = dicteditor.Editor()
editor.load("data/sampledict.dwa")
oldCount = len(editor.getUnits())
self.assert_(editor.getUnit('du') != None)
def test_addUnit(self):
"""addUnit() should add new translation unit or update old one"""
editor = dicteditor.Editor()
editor.load("data/sampledict.dwa")
oldCount = len(editor.getUnits())
newUnit = dicteditor.Translation()
newUnit.setWord("test")
newUnit.addTranslation("utiutiu")
editor.addUnit(newUnit)
self.assertEquals(len(editor.getUnits()), oldCount + 1)
def test_removeUnit(self):
"""removeUnit() should add new translation unit or update old one"""
editor = dicteditor.Editor()
editor.load("data/sampledict.dwa")
oldCount = len(editor.getUnits())
unit = editor.getUnit('vienas')
editor.removeUnit(unit)
self.assertEquals(len(editor.getUnits()), oldCount - 1)
def test_unicode(self):
"""All the strings must be unicode objects"""
editor = dicteditor.Editor()
editor.load("data/sampledict.dwa")
for unit in editor.getUnits()[:10]:
for trans in unit.getTranslations().keys():
self.assertEquals(type(trans), type(u''))
if __name__ == "__main__":
unittest.main()
opendict-0.6.8/lib/tests/test_plugin.py 0000664 0000764 0000764 00000004547 13204646653 020126 0 ustar nerijus nerijus # -*- coding: UTF-8 -*-
#
# OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# Unit Test for editor.py
#
"""
Unit tests for plugin.py
"""
import unittest
import os
import sys
sys.path.append('../..')
from lib import newplugin
class TestPluginInfo(unittest.TestCase):
"""PluginInfo test"""
def test_getInfo(self):
"""PluginInfo should have correct attributes"""
fd = open("data/plugin.xml")
xmlData = fd.read()
fd.close()
info = newplugin.PluginInfo(xmlData)
self.assertEquals(info.name, u"Sample plugin name ąčę")
self.assertEquals(info.version, u"1.2.3")
self.assertEquals(info.authors, [{"name": u"Sample author name ąčę",
"email": u"sample@example.com"}])
self.assertEquals(info.module, {"name": u"mymodule.py",
"lang": u"Python"})
self.assertEquals(info.encoding, u"UTF-8")
self.assertEquals(info.usesWordList, True)
self.assertEquals(info.opendictVersion, u"0.5.8")
self.assertEquals(info.pythonVersion, u"2.3")
platforms = [{"name": u"Linux"},
{"name": u"Windows"},
{"name": u"BSD"}]
platforms.sort()
self.assertEquals(info.platforms, platforms)
self.assertEquals(info.description,
u"This is short or long description ąčę.")
self.assertEquals(info.xmlData, xmlData)
class TestDictionaryPlugin(unittest.TestCase):
"""Test PluginHandler class"""
def test_class(self):
"""__init__ should load plugin info and module"""
p = newplugin.DictionaryPlugin(os.path.realpath('data/sampleplugin'))
self.assertEquals(p.__class__, newplugin.DictionaryPlugin)
self.assert_(p.info != None)
self.assert_(p.dictionary != None)
self.assert_(p.isValid() == True)
self.assertEquals(p.info.__class__, newplugin.PluginInfo)
self.assertEquals(len(p.dictionary.search('x').words), 20)
self.assertRaises(newplugin.InvalidPluginException,
newplugin.DictionaryPlugin, 'blabla')
if __name__ == "__main__":
unittest.main()
opendict-0.6.8/lib/tests/data/ 0000775 0000764 0000764 00000000000 13204646653 016116 5 ustar nerijus nerijus opendict-0.6.8/lib/tests/data/plugin.xml 0000664 0000764 0000764 00000001214 13204646653 020134 0 ustar nerijus nerijus
Sample plugin name ąčę
1.2.3
mymodule.py
UTF-8
True
0.5.8
2.3
This is short or long description ąčę.
opendict-0.6.8/lib/tests/data/sampledict.dwa 0000664 0000764 0000764 00000000270 13204646653 020737 0 ustar nerijus nerijus vienas = one ;
du = two // two pieces ;
trys = three // not 'tree' ;
keturi = four // not 'for' ;
žirafa = giraphe // from africa ;
miškas= forest ; wood;
ąžuolas=oak // oak wood;
opendict-0.6.8/lib/tests/data/sampleplugin/ 0000775 0000764 0000764 00000000000 13204646653 020616 5 ustar nerijus nerijus opendict-0.6.8/lib/tests/data/sampleplugin/plugin.xml 0000664 0000764 0000764 00000001340 13204646653 022634 0 ustar nerijus nerijus
Unicode plugin (ąčęėįšųū„“\ž)
0.1
sample.py
UTF-8
True
0.5.8
2.3
This plugin only demonstrates new type OpenDict plugin facilities. And
Unicode support too: ąčęėįšųū„“\ž.
opendict-0.6.8/lib/tests/data/sampleplugin/sample.py 0000664 0000764 0000764 00000003612 13204646653 022453 0 ustar nerijus nerijus #
# OpenDict
# Copyright (c) 2005 Martynas Jocius
#
# 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 opinion) any later version.
#
# This program is distributed in the hope that will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detals.
#
# You shoud have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
"""
Sample OpenDict plugin (new type)
"""
import string
import sys
def init(libraryPath):
"""This is required method for all plugins. The one and only
parameter gives OpenDict library path for requred imports. This
method returns plugin instance."""
sys.path.insert(0, libraryPath)
return SampleDictionary()
class SampleDictionary:
"""Sample dictionary"""
def __init__(self):
"""Import and save needed modules"""
from lib import errortype, meta
self.errorModule = errortype
self.metaModule = meta
def search(self, word):
"""Look up word"""
trans = []
words = []
trans.append("")
for i in range(10):
trans.append("Do you want to know what %s is žžčėčęė? So do I!" \
% word)
for i in range(20):
words.append("ž"+str(i)*5)
trans.append("")
result = self.metaModule.SearchResult()
result.status = self.errorModule.OK
result.translation = "".join(trans)
result.words = words
return result
opendict-0.6.8/misc/ 0000775 0000764 0000764 00000000000 13204646653 014230 5 ustar nerijus nerijus opendict-0.6.8/misc/opendict.desktop 0000664 0000764 0000764 00000012711 13204646653 017432 0 ustar nerijus nerijus [Desktop Entry]
Name=Dictionary OpenDict
Name[lt]=Žodynas „OpenDict“
Name[de]=OpenDict Wörterbuch
Name[ru]=Словарь OpenDict
Name[af]=OpenDict woordeboek
Name[sq]=Fjalori OpenDict
Name[ast]=Diccionariu OpenDict
Name[bn]=OpenDict অভিধান
Name[bs]=Rječnik OpenDict
Name[pt_BR]=Dicionário OpenDict
Name[bg]=Речник OpenDict
Name[ca]=Diccionari OpenDict
Name[ca@valencia]=Diccionari OpenDict
Name[zh_CN]=OpenDict 词典
Name[crh]=Szölük OpenDict
Name[cs]=Slovník OpenDict
Name[nl]=OpenDict woordenboek
Name[da]=Ordbogen OpenDict
Name[fr]=Dictionnaire OpenDict
Name[gl]=Dicionario OpenDict
Name[el]=Λεξικό OpenDict
Name[hu]=OpenDict szótár
Name[it]=Dizionario OpenDict
Name[ja]=OpenDict 辞書
Name[ky]=OpenDict сөздүгү
Name[ms]=Kamus OpenDict
Name[nb]=OpenDict ordbok
Name[oc]=Diccionari OpenDict
Name[pt]=Dicionário OpenDict
Name[pl]=Słownik OpenDict
Name[ro]=Dicționar OpenDict
Name[sk]=Slovník OpenDict
Name[sl]=Slovar OpenDict
Name[sv]=OpenDict ordbok
Name[tg]=Луғати OpenDict
Name[es]=Diccionario OpenDict
Name[tr]=Szölük OpenDict
Name[uk]=Словник OpenDict
Name[vi]=Từ điển OpenDict
GenericName=Dictionary OpenDict
GenericName[lt]=Žodynas „OpenDict“
GenericName[de]=OpenDict Wörterbuch
GenericName[ru]=Словарь OpenDict
GenericName[af]=OpenDict woordeboek
GenericName[sq]=Fjalori OpenDict
GenericName[ast]=Diccionariu OpenDict
GenericName[bn]=OpenDict অভিধান
GenericName[bs]=Rječnik OpenDict
GenericName[pt_BR]=Dicionário OpenDict
GenericName[bg]=Речник OpenDict
GenericName[ca]=Diccionari OpenDict
GenericName[ca@valencia]=Diccionari OpenDict
GenericName[zh_CN]=OpenDict 词典
GenericName[crh]=Szölük OpenDict
GenericName[cs]=Slovník OpenDict
GenericName[nl]=OpenDict woordenboek
GenericName[da]=Ordbogen OpenDict
GenericName[fr]=Dictionnaire OpenDict
GenericName[gl]=Dicionario OpenDict
GenericName[el]=Λεξικό OpenDict
GenericName[hu]=OpenDict szótár
GenericName[it]=Dizionario OpenDict
GenericName[ja]=OpenDict 辞書
GenericName[ky]=OpenDict сөздүгү
GenericName[ms]=Kamus OpenDict
GenericName[nb]=OpenDict ordbok
GenericName[oc]=Diccionari OpenDict
GenericName[pt]=Dicionário OpenDict
GenericName[pl]=Słownik OpenDict
GenericName[ro]=Dicționar OpenDict
GenericName[sk]=Slovník OpenDict
GenericName[sl]=Slovar OpenDict
GenericName[sv]=OpenDict ordbok
GenericName[tg]=Луғати OpenDict
GenericName[es]=Diccionario OpenDict
GenericName[tr]=Szölük OpenDict
GenericName[uk]=Словник OpenDict
GenericName[vi]=Từ điển OpenDict
Comment=Lookup words in a local or Internet dictionary
Comment[lt]=Ieškoti žodžių kompiuterio arba Interneto žodyne
Comment[de]=Wörter in einem lokalen Wörterbuch oder im Internet nachschlagen
Comment[ru]=Поиск слов в интернет-словаре или в локальном словаре
Comment[af]=Slaan woorde na in 'n plaaslike of internasionale woordeboek
Comment[sq]=Kontrollo fjalët në një fjalor lokal ose në internet
Comment[ast]=Gueta pallabres nun diccionariu llocal o d'Internet
Comment[bn]=স্থানীয় অথবা ইন্টারনেট অভিধানে শব্দ দেখুন
Comment[bs]=Tražite riječ u u lokalnom ili mrežnom rječniku
Comment[pt_BR]=Pesquisa palavras em um dicionário local ou da internet
Comment[bg]=Търсене на думи в локален или Интернет речник
Comment[ca]=Cerqueu paraules en un diccionari local o d'Internet
Comment[ca@valencia]=Cerqueu paraules en un diccionari local o d'Internet
Comment[zh_CN]=在本地或互联网词典中查找词语
Comment[crh]=Bir yerel ya da internet sözlüğünde kelimeleri ara
Comment[cs]=Vyhledávání slov v místním nebo online slovníku
Comment[da]=Slå ord op i en lokal ordbog eller på nettet
Comment[nl]=Woorden in een lokaal woordenboek of over het internet
Comment[fi]=Etsi sanoja paikallisesta tai verkossa sijaitsevasta sanakirjasta
Comment[fr]=Chercher des mots sur un dictionnaire local ou en ligne
Comment[gl]=Busque palabras nun dicionario local ou da Internet
Comment[el]=Αναζητήστε λέξεις σε τοπικά ή διαδικτυακά λεξικά
Comment[hu]=Szavak keresése helyi vagy internetes szótárban
Comment[it]=Cerca parole in un dizionario locale o su Internet
Comment[ja]=ローカルまたはインターネット上の辞書を使って単語を検索します
Comment[ky]=Сөздөрдү сөздүктөн же интернетен издөө
Comment[ms]=Cari perkataan didalam kamus setempat atau Internet
Comment[nb]=Slå opp ord i en lokal eller nettbasert ordbok
Comment[oc]=Cercar de mots sus un diccionari local o en linha
Comment[pl]=Wyszukuje tłumaczeń w słowniku lokalnym oraz internetowym
Comment[pt]=Procurar palavras num dicionário local ou online
Comment[ro]=Căutați cuvinte într-un dicționar local sau de pe Internet
Comment[sk]=Vyhľadávanie slov v lokálnom alebo internetovom slovníku
Comment[sl]=Poiščite besede v krajevnem ali medmrežnem slovarju
Comment[es]=Busca palabras en un diccionario local o de Internet
Comment[sv]=Slå upp ord i en ordbok lokalt eller på internet
Comment[tr]=Bir yerel ya da internet sözlüğünde kelimeleri ara
Comment[uk]=Пошук слів у локальному або інтернет-словниках
Comment[vi]=Tra cứu từ với từ điển ở máy hoặc trên Internet
Exec=opendict
Icon=opendict
StartupNotify=true
Terminal=false
Type=Application
Categories=GTK;Utility;Dictionary;
Keywords=Dictonary;Words;
opendict-0.6.8/misc/repository/ 0000775 0000764 0000764 00000000000 13204646653 016447 5 ustar nerijus nerijus opendict-0.6.8/misc/repository/Makefile 0000664 0000764 0000764 00000000134 13204646653 020105 0 ustar nerijus nerijus all:
python make-addons-list.py Dictionaries http://db.opendict.idiles.com
mv *.xml Data/
opendict-0.6.8/misc/repository/README.txt 0000664 0000764 0000764 00000000202 13204646653 020137 0 ustar nerijus nerijus Files here are used on the repository server to generate dictionary
lists to be installed. OpenDict end-users should ignore them. opendict-0.6.8/misc/repository/make-addons-list.py 0000775 0000764 0000764 00000020070 13204646653 022157 0 ustar nerijus nerijus #!/usr/bin/env python
import sys
import os
import zipfile
import md5
import xml.dom.minidom
#
# Add-ons description file generator for OpenDict
# Copyright (c) 2003-2006 Martynas Jocius
# Copyright (c) 2007 IDILES SYSTEMS, UAB
#
# Fast & dirty code
#
def parsePluginConfig(xmlData):
"""Parse plugin configuration"""
doc = xml.dom.minidom.parseString(xmlData)
name = None
version = None
authors = []
description = None
pluginElement = doc.getElementsByTagName('plugin')[0]
pluginType = pluginElement.getAttribute('type')
if pluginType != 'dictionary':
raise Exception, "Plugin is not dictionary plugin"
# Get name
for nameElement in doc.getElementsByTagName('name'):
for node in nameElement.childNodes:
if node.nodeType == node.TEXT_NODE:
name = node.data
# Get version
for versionElement in doc.getElementsByTagName('version'):
for node in versionElement.childNodes:
if node.nodeType == node.TEXT_NODE:
version = node.data
# Get authors
for authorElement in doc.getElementsByTagName('author'):
authorName = authorElement.getAttribute('name')
authorEMail = authorElement.getAttribute('email')
authors.append({'name': authorName, 'email': authorEMail})
# Get description
for descElement in doc.getElementsByTagName('description'):
for node in descElement.childNodes:
if node.nodeType == node.TEXT_NODE:
description = node.data
result = {}
result['name'] = name
result['version'] = version
result['authors'] = authors
result['description'] = description
return result
def parsePlainConfig(xmlData):
"""Parse plain dict configuration"""
doc = xml.dom.minidom.parseString(xmlData)
name = None
version = None
authors = []
description = None
registers = doc.getElementsByTagName('plain-dictionary')
if len(registers) == 0:
raise "Invalid configuration"
registerElement = registers[0]
for nameElement in registerElement.getElementsByTagName('name'):
for node in nameElement.childNodes:
name = node.data
for versionElement in registerElement.getElementsByTagName('version'):
for node in versionElement.childNodes:
version = node.data.strip()
for authorElement in registerElement.getElementsByTagName('author'):
authors.append({'name': authorElement.getAttribute('name'),
'email': authorElement.getAttribute('email')})
for descElement in \
registerElement.getElementsByTagName('description'):
for node in descElement.childNodes:
description = (description or '') + node.data.strip()
result = {}
result['name'] = name
result['version'] = version
result['authors'] = authors
result['description'] = description
return result
def generateElement(**args):
"""Generate add-on XML DOM elemente"""
doc = xml.dom.minidom.Document()
addonElement = doc.createElement('add-on')
addonElement.setAttribute('type', args.get('type'))
# Name element
nameElement = doc.createElement('name')
addonElement.appendChild(nameElement)
nameElement.appendChild(doc.createTextNode(args.get('name')))
# Version element
versionElement = doc.createElement('version')
addonElement.appendChild(versionElement)
versionElement.appendChild(doc.createTextNode(args.get('version')))
# Authors element
authorsElement = doc.createElement('authors')
addonElement.appendChild(authorsElement)
for author in (args.get('authors') or []):
authorElement = doc.createElement('author')
authorsElement.appendChild(authorElement)
authorElement.setAttribute('name', author.get('name'))
authorElement.setAttribute('email', author.get('email'))
# Description element
descElement = doc.createElement('description')
addonElement.appendChild(descElement)
descElement.appendChild(doc.createTextNode(args.get('description') \
or None))
# MD5 element
md5Element = doc.createElement('md5')
addonElement.appendChild(md5Element)
md5Element.appendChild(doc.createTextNode(args.get('md5sum')))
# URL element
urlElement = doc.createElement('url')
addonElement.appendChild(urlElement)
urlElement.appendChild(doc.createTextNode(args.get('url')))
# Size element
sizeElement = doc.createElement('size')
addonElement.appendChild(sizeElement)
sizeElement.appendChild(doc.createTextNode(str(args.get('size'))))
return addonElement
def listFiles(start, followLinks, myDepth, maxDepth):
"""Return file list"""
files = []
try:
dirList = os.listdir(start)
except:
if os.path.isdir(start):
print 'ERROR: Cannot list directory %s' % start
return files
for item in dirList:
path = os.path.join(start, item)
if os.path.isdir(path) and (followLinks or \
(not followLinks and not islink(path))):
files.extend(listFiles(path, followLinks,
myDepth + 1,
maxDepth))
else:
files.append(path)
return files
def makeDocument(addons):
"""Connect add-on elements to one XML document"""
doc = xml.dom.minidom.Document()
addonsElement = doc.createElement('opendict-add-ons')
doc.appendChild(addonsElement)
for addon in addons:
addonsElement.appendChild(addon)
return doc
def main():
"""Main procedure"""
if len(sys.argv) < 3:
print "Usage: %s " % sys.argv[0]
print "(Example: '%s . http://xxx.yyy.net/dicts')" % sys.argv[0]
sys.exit(1)
d = sys.argv[1]
baseURL = sys.argv[2]
xmlElements = []
for filePath in listFiles(d, True, 0, None):
try:
zipFile = zipfile.ZipFile(filePath, 'r')
except Exception, e:
print "ERROR: %s: %s" % (filePath, e)
continue
# Test CRC
if zipFile.testzip():
raise Exception, _("Dictionary plugin file is corrupted")
# Check if empty
try:
topDirectory = zipFile.namelist()[0]
except Exception, e:
raise Exception, _("Plugin file is empty (%s)" % e)
# Check for validity
for fileInZip in zipFile.namelist():
dirName = os.path.dirname(fileInZip)
fileName = os.path.basename(fileInZip)
topDir = zipFile.namelist()[0]
plainConfigPath = os.path.join(topDir, 'conf', 'config.xml')
pluginConfigPath = os.path.join(topDir, 'plugin.xml')
info = {}
if plainConfigPath in zipFile.namelist():
info.update(parsePlainConfig(zipFile.read(plainConfigPath)))
info['type'] = 'plain-dictionary'
elif pluginConfigPath in zipFile.namelist():
info.update(parsePluginConfig(zipFile.read(pluginConfigPath)))
info['type'] = 'plugin-dictionary'
sz = os.stat(filePath)[6] / 1000
fd = open(filePath)
m = md5.new(fd.read())
fd.close()
checksum = m.hexdigest()
location = baseURL + '/' + filePath
xmlElements.append(generateElement(type=info.get('type'),
name=info.get('name'),
version=info.get('version'),
authors=info.get('authors'),
description=info.get('description'),
url=location,
md5sum=checksum,
size=sz))
print "* %s" % filePath
doc = makeDocument(xmlElements)
fd = open('opendict-add-ons.xml', 'w')
fd.write(doc.toxml())
fd.close()
if __name__ == "__main__":
main()
opendict-0.6.8/pixmaps/ 0000775 0000764 0000764 00000000000 13204646653 014756 5 ustar nerijus nerijus opendict-0.6.8/pixmaps/hide.png 0000664 0000764 0000764 00000001074 13204646653 016377 0 ustar nerijus nerijus PNG
IHDR w= gAMA a bKGD C pHYs ~ tIME;¯l IDATx핱nPcF:VRROE KZZfD yb`PD1Ƈ!AŎc&=wc3r70ԀY1㏪jvݳY]yo kcMd(9(*OvÐZN_p;+S\jι\Ǐen/Xg3wwxfs`>(}E=`@b
&&ׁ/~^PJ74 \d9HsppH9zJD
Y ApjSՍ4c9k7WՍm{j79`<ߛnY$4`X~fyIiTS"JU۲+nmGg>
dM+PuUy{?&a) IENDB` opendict-0.6.8/pixmaps/icon-24x24.png 0000664 0000764 0000764 00000002264 13204646653 017201 0 ustar nerijus nerijus PNG
IHDR w= bKGD pHYs tIME).DmS AIDATHǭmlSUڮ0P$JD#,Ejcb"!!~ BL!@
DdemҮmv$U.몫F2ֲH qĐuII}̙Ӗ̘`YyyH$pD]0OKyh wCP\Gjٸ.uheSBFD
\ `ݲ8cg%~P7{]p:K!Gd$d$h/`.ze
!P vs:u_Y_kǩS&4ǩ(VO)f_@+]M;{?L2^b
=vˉ[J N"f)L xbvXRix}oEyzݳIUN_7H94og,%5E:^Jwx"AMXd$l[-M-&
744J^|ɒGJyw@m'qqT9ә@Y2%fh̨u0Aˆeފx_
H K(%ԘTi<9`s`e4rJjC`
6AyX_il㕙,QH}&[BY1)X^^AP#8Pb%7R(=}
e
9(Q!]m8Q
ʊ@8mhlԍihjVORT`S>)Ŗс[RL
e\H}ekWӉ+eŚ7+GgkT8TvҐfwwkSҪr;j55"IL1 3H`XPO\K^':rJ S/rLӹ@{L!!9s+xC,'u;E"ߕd4&OϽ }Tc8}x?5XS(.s94W}^ϥO۸c5yT<*3+\vfK>],9G IENDB` opendict-0.6.8/pixmaps/icon-32x32.png 0000664 0000764 0000764 00000003316 13204646653 017176 0 ustar nerijus nerijus PNG
IHDR szz bKGD pHYs tIME)< |