2007-05-20 Don Allingham <don@gramps-project.org>

* src/Lru.py: pylint fixes
	* src/DisplayState.py: pylint fixes
	* src/Errors.py: pylint fixes
	* src/DbState.py: pylint fixes



svn: r8501
This commit is contained in:
Don Allingham 2007-05-21 03:44:18 +00:00
parent a598df4f6d
commit 263ab79ad9
5 changed files with 180 additions and 86 deletions

View File

@ -1,3 +1,9 @@
2007-05-20 Don Allingham <don@gramps-project.org>
* src/Lru.py: pylint fixes
* src/DisplayState.py: pylint fixes
* src/Errors.py: pylint fixes
* src/DbState.py: pylint fixes
2007-05-19 Don Allingham <don@gramps-project.org>
* src/Bookmarks.py: pylint fixes
* src/ColumnOrder.py: pylint fixes

View File

@ -26,10 +26,12 @@ __author__ = "Donald N. Allingham"
__revision__ = "$Revision: 8032 $"
from GrampsDb import GrampsDBCallback, GrampsDbBase
import Config
class DbState(GrampsDBCallback):
"""
Provides a class to encapsulate the state of the database..
"""
__signals__ = {
'database-changed' : (GrampsDbBase, ),
@ -38,12 +40,20 @@ class DbState(GrampsDBCallback):
}
def __init__(self):
"""
Initalize the state with an empty (and useless) GrampsDbBase. This is
just a place holder until a real DB is assigned.
"""
GrampsDBCallback.__init__(self)
self.db = GrampsDbBase()
self.open = False
self.active = None
def change_active_person(self, person):
"""
Changes the active person and emits a signal to notify those who
are interested.
"""
self.active = person
if person:
try:
@ -52,18 +62,31 @@ class DbState(GrampsDBCallback):
self.emit('active-changed', ("", ))
def change_active_handle(self, handle):
"""
Changes the active person based on the person's handle
"""
self.change_active_person(self.db.get_person_from_handle(handle))
def get_active_person(self):
if self.active: # Fetch a fresh version from DB to not return a stale one
"""
Gets the current active person. Creates a new instance to make sure that
the data is active.
"""
if self.active:
self.active = self.db.get_person_from_handle(self.active.handle)
return self.active
def change_database(self, database):
"""
Closes the existing db, and opens a new one.
"""
self.db.close()
self.change_database_noclose(database)
def change_database_noclose(self, database):
"""
Changes the current database. and resets the configuration prefixes.
"""
self.db = database
self.db.set_prefixes(
Config.get(Config.IPREFIX),
@ -79,9 +102,15 @@ class DbState(GrampsDBCallback):
self.open = True
def signal_change(self):
"""
Emits the database-changed signal with the new database
"""
self.emit('database-changed', (self.db, ))
def no_database(self):
"""
Closes the database without a new database
"""
self.db.close()
self.db = GrampsDbBase()
self.active = None

View File

@ -34,7 +34,7 @@ from gettext import gettext as _
#
#-------------------------------------------------------------------------
import logging
log = logging.getLogger(".DisplayState")
__LOG = logging.getLogger(".DisplayState")
#-------------------------------------------------------------------------
#
@ -65,8 +65,8 @@ DISABLED = -1
class History(GrampsDb.GrampsDBCallback):
__signals__ = {
'changed' : (list,),
'menu-changed' : (list,),
'changed' : (list, ),
'menu-changed' : (list, ),
}
def __init__(self):
@ -89,16 +89,16 @@ class History(GrampsDb.GrampsDBCallback):
else:
del_id = person_handle
hc = self.history.count(del_id)
for c in range(hc):
history_count = self.history.count(del_id)
for c in range(history_count):
self.history.remove(del_id)
self.index -= 1
mhc = self.mhistory.count(del_id)
for c in range(mhc):
self.mhistory.remove(del_id)
self.emit('changed',(self.history,))
self.emit('menu-changed',(self.mhistory,))
self.emit('changed', (self.history, ))
self.emit('menu-changed', (self.mhistory, ))
def push(self, person_handle):
self.prune()
@ -108,15 +108,15 @@ class History(GrampsDb.GrampsDBCallback):
self.mhistory.remove(person_handle)
self.mhistory.append(person_handle)
self.index += 1
self.emit('menu-changed',(self.mhistory,))
self.emit('changed',(self.history,))
self.emit('menu-changed', (self.mhistory, ))
self.emit('changed', (self.history, ))
def forward(self, step=1):
self.index += step
person_handle = self.history[self.index]
if person_handle not in self.mhistory:
self.mhistory.append(person_handle)
self.emit('menu-changed',(self.mhistory,))
self.emit('menu-changed', (self.mhistory, ))
return str(self.history[self.index])
def back(self, step=1):
@ -125,7 +125,7 @@ class History(GrampsDb.GrampsDBCallback):
person_handle = self.history[self.index]
if person_handle not in self.mhistory:
self.mhistory.append(person_handle)
self.emit('menu-changed',(self.mhistory,))
self.emit('menu-changed', (self.mhistory, ))
return str(self.history[self.index])
except IndexError:
return u""
@ -147,14 +147,14 @@ class History(GrampsDb.GrampsDBCallback):
#
#-------------------------------------------------------------------------
_rct_top = '<ui><menubar name="MenuBar"><menu action="FileMenu"><menu action="OpenRecent">'
_rct_btm = '</menu></menu></menubar></ui>'
__RCT_TOP = '<ui><menubar name="MenuBar"><menu action="FileMenu"><menu action="OpenRecent">'
__RCT_BTM = '</menu></menu></menubar></ui>'
import RecentFiles
import os
class RecentDocsMenu:
def __init__(self,uistate, state, fileopen):
def __init__(self, uistate, state, fileopen):
self.action_group = gtk.ActionGroup('RecentFiles')
self.active = DISABLED
self.uistate = uistate
@ -162,14 +162,14 @@ class RecentDocsMenu:
self.fileopen = fileopen
self.state = state
def load(self,item):
def load(self, item):
name = item.get_path()
dbtype = item.get_mime()
self.fileopen(name,dbtype)
self.fileopen(name, dbtype)
def build(self):
f = StringIO()
f.write(_rct_top)
buf = StringIO()
buf.write(__RCT_TOP)
gramps_rf = RecentFiles.GrampsRecentFiles()
count = 0
@ -187,11 +187,11 @@ class RecentDocsMenu:
for item in rfiles:
try:
filename = os.path.basename(item.get_path()).replace('_','__')
filename = os.path.basename(item.get_path()).replace('_', '__')
action_id = "RecentMenu%d" % count
f.write('<menuitem action="%s"/>' % action_id)
actions.append((action_id,None,filename,None,None,
make_callback(item,self.load)))
buf.write('<menuitem action="%s"/>' % action_id)
actions.append((action_id, None, filename, None, None,
make_callback(item, self.load)))
mitem = gtk.MenuItem(filename)
mitem.connect('activate', make_callback(item, self.load))
mitem.show()
@ -199,39 +199,40 @@ class RecentDocsMenu:
except RuntimeError:
pass # ignore no longer existing files
count +=1
f.write(_rct_btm)
count += 1
buf.write(__RCT_BTM)
self.action_group.add_actions(actions)
self.uimanager.insert_action_group(self.action_group,1)
self.active = self.uimanager.add_ui_from_string(f.getvalue())
self.uimanager.insert_action_group(self.action_group, 1)
self.active = self.uimanager.add_ui_from_string(buf.getvalue())
self.uimanager.ensure_update()
f.close()
buf.close()
new_menu.show()
self.uistate.set_open_recent_menu(new_menu)
def make_callback(n,f):
return lambda x: f(n)
def make_callback(val, func):
return lambda x: func(val)
def by_time(a,b):
return cmp(b.get_time(),a.get_time())
def by_time(first, second):
return cmp(second.get_time(), first.get_time())
from GrampsLogger import RotateHandler
class WarnHandler(RotateHandler):
def __init__(self,capacity,button):
RotateHandler.__init__(self,capacity)
def __init__(self, capacity, button):
RotateHandler.__init__(self, capacity)
self.setLevel(logging.WARN)
self.button = button
button.on_clicked(self.display)
self.timer = None
def emit(self,record):
def emit(self, record):
if self.timer:
gobject.source_remove(self.timer)
gobject.timeout_add(180*1000,self._clear)
RotateHandler.emit(self,record)
gobject.timeout_add(180*1000, self._clear)
RotateHandler.emit(self, record)
self.button.show()
def _clear(self):
@ -240,11 +241,11 @@ class WarnHandler(RotateHandler):
self.timer = None
return False
def display(self,obj):
def display(self, obj):
obj.hide()
g = gtk.glade.XML(const.gladeFile,'scrollmsg')
top = g.get_widget('scrollmsg')
msg = g.get_widget('msg')
xml = gtk.glade.XML(const.gladeFile, 'scrollmsg')
top = xml.get_widget('scrollmsg')
msg = xml.get_widget('msg')
buf = msg.get_buffer()
for i in self.get_formatted_log():
buf.insert_at_cursor(i + '\n')
@ -255,9 +256,9 @@ class WarnHandler(RotateHandler):
class DisplayState(GrampsDb.GrampsDBCallback):
__signals__ = {
'filters-changed' : (str,),
'filters-changed' : (str, ),
'nameformat-changed' : None,
'plugins-reloaded' : (list,list),
'plugins-reloaded' : (list, list),
}
def __init__(self, window, status, progress, warnbtn, uimanager,
@ -278,11 +279,11 @@ class DisplayState(GrampsDb.GrampsDBCallback):
self.last_bar = self.status.insert(min_width=15, ralign=True)
formatter = logging.Formatter('%(levelname)s %(name)s: %(message)s')
self.rh = WarnHandler(capacity=400,button=warnbtn)
self.rh.setFormatter(formatter)
self.rh.setLevel(logging.WARNING)
self.rhandler = WarnHandler(capacity=400, button=warnbtn)
self.rhandler.setFormatter(formatter)
self.rhandler.setLevel(logging.WARNING)
self.log = logging.getLogger()
self.log.addHandler(self.rh)
self.log.addHandler(self.rhandler)
# This call has been moved one level up,
# but this connection is still made!
# self.dbstate.connect('database-changed', self.db_changed)
@ -295,14 +296,14 @@ class DisplayState(GrampsDb.GrampsDBCallback):
self.relationship = _PluginMgr.relationship_class(db)
db.connect('long-op-start', self.progress_monitor.add_op)
def display_relationship(self,dbstate):
def display_relationship(self, dbstate):
default_person = dbstate.db.get_default_person()
active = dbstate.get_active_person()
if default_person == None or active == None:
return u''
pname = NameDisplay.displayer.display(default_person)
(name,plist) = self.relationship.get_relationship(
(name, plist) = self.relationship.get_relationship(
default_person,active)
if name:
@ -316,7 +317,7 @@ class DisplayState(GrampsDb.GrampsDBCallback):
def clear_history(self):
self.phistory.clear()
def set_busy_cursor(self,value):
def set_busy_cursor(self, value):
if value == self.busy:
return
else:
@ -328,15 +329,15 @@ class DisplayState(GrampsDb.GrampsDBCallback):
while gtk.events_pending():
gtk.main_iteration()
def set_open_widget(self,widget):
def set_open_widget(self, widget):
self.widget = widget
def set_open_recent_menu(self,menu):
def set_open_recent_menu(self, menu):
self.widget.set_menu(menu)
def push_message(self, dbstate, text):
self.status_text(text)
gobject.timeout_add(5000,self.modify_statusbar,dbstate)
gobject.timeout_add(5000, self.modify_statusbar, dbstate)
def show_filter_results(self, dbstate, matched, total):
text = "%d/%d" % (matched, total)
@ -347,36 +348,36 @@ class DisplayState(GrampsDb.GrampsDBCallback):
self.status.pop(1, self.last_bar)
self.status.push(1, '', self.last_bar)
def modify_statusbar(self,dbstate,active=None):
def modify_statusbar(self, dbstate, active=None):
self.status.pop(self.status_id)
if dbstate.active == None:
self.status.push(self.status_id,"")
self.status.push(self.status_id, "")
else:
person = dbstate.get_active_person()
if person:
pname = NameDisplay.displayer.display(person)
name = "[%s] %s" % (person.get_gramps_id(),pname)
name = "[%s] %s" % (person.get_gramps_id(), pname)
if Config.get(Config.STATUSBAR) > 1:
if person.handle != dbstate.db.get_default_handle():
msg = self.display_relationship(dbstate)
if msg:
name = "%s (%s)" % (name,msg.strip())
name = "%s (%s)" % (name, msg.strip())
else:
name = _("No active person")
self.status.push(self.status_id,name)
self.status.push(self.status_id, name)
while gtk.events_pending():
gtk.main_iteration()
def pulse_progressbar(self,value):
self.progress.set_fraction(min(value/100.0,1.0))
def pulse_progressbar(self, value):
self.progress.set_fraction(min(value/100.0, 1.0))
self.progress.set_text("%d%%" % value)
while gtk.events_pending():
gtk.main_iteration()
def status_text(self,text):
def status_text(self, text):
self.status.pop(self.status_id)
self.status.push(self.status_id,text)
self.status.push(self.status_id, text)
while gtk.events_pending():
gtk.main_iteration()
@ -385,7 +386,7 @@ if __name__ == "__main__":
import GrampsWidgets
rh = WarnHandler(capacity=400,button=GrampsWidgets.WarnButton())
log = logging.getLogger()
log.setLevel(logging.WARN)
log.addHandler(rh)
rhandler = WarnHandler(capacity=400, button=GrampsWidgets.WarnButton())
__LOG = logging.getLogger()
__LOG.setLevel(logging.WARN)
__LOG.addHandler(rhandler)

View File

@ -20,102 +20,117 @@
# $Id$
"""
Provide Error objects
"""
class FilterError(Exception):
"""Error used to report Filter errors"""
def __init__(self,value,value2=""):
def __init__(self, value, value2=""):
Exception.__init__(self)
self.value = value
self.value2 = value2
def __str__(self):
"Return string representation"
return self.value
def messages(self):
return (self.value,self.value2)
"Return the messages"
return (self.value, self.value2)
class DateError(Exception):
"""Error used to report Date errors"""
def __init__(self,value=""):
def __init__(self, value=""):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class DatabaseError(Exception):
"""Error used to report database errors"""
def __init__(self,value=""):
def __init__(self, value=""):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class ReportError(Exception):
"""Error used to report Report errors"""
def __init__(self,value,value2=""):
def __init__(self, value, value2=""):
Exception.__init__(self)
self.value = value
self.value2 = value2
def __str__(self):
"Return string representation"
return self.value
def messages(self):
return (self.value,self.value2)
"Return the messages"
return (self.value, self.value2)
class GedcomError(Exception):
"""Error used to report GEDCOM errors"""
def __init__(self,value):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class PluginError(Exception):
"""Error used to report plugin errors"""
def __init__(self,value):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class HandleError(Exception):
"""Error used to report wrong database handle errors"""
def __init__(self,value):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class GConfSchemaError(Exception):
"""Error used to report the absence of expected GConf schema."""
def __init__(self,value):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class WindowActiveError(Exception):
"""Error used to report that the request window is already displayed."""
def __init__(self,value):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class UnavailableError(Exception):
def __init__(self,value):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def __str__(self):
"Return string representation"
return self.value
class MaskError(Exception):

View File

@ -17,13 +17,23 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""
Least recently used algorithm
"""
class Node:
"""
Node to be stored in the LRU structure
"""
def __init__(self, prev, me):
self.prev = prev
self.me = me
self.next = None
class LRU: #Implementation of a length-limited O(1) LRU cache
class LRU:
"""
Implementation of a length-limited O(1) LRU cache
"""
def __init__(self, count):
self.count = max(count, 2)
self.d = {}
@ -31,12 +41,21 @@ class LRU: #Implementation of a length-limited O(1) LRU cache
self.last = None
def __contains__(self, obj):
"""
Returns True if the object is contained in the LRU
"""
return obj in self.d
def __getitem__(self, obj):
"""
Returns item assocated with Obj
"""
return self.d[obj].me[1]
def __setitem__(self, obj, val):
"""
Sets the item in the LRU, removing an old entry if needed
"""
if obj in self.d:
del self[obj]
nobj = Node(self.last, (obj, val))
@ -59,6 +78,9 @@ class LRU: #Implementation of a length-limited O(1) LRU cache
del a
def __delitem__(self, obj):
"""
Delete the object from the LRU
"""
nobj = self.d[obj]
if nobj.prev:
nobj.prev.next = nobj.next
@ -71,6 +93,9 @@ class LRU: #Implementation of a length-limited O(1) LRU cache
del self.d[obj]
def __iter__(self):
"""
Iterate over the LRU
"""
cur = self.first
while cur != None:
cur2 = cur.next
@ -79,6 +104,9 @@ class LRU: #Implementation of a length-limited O(1) LRU cache
raise StopIteration
def iteritems(self):
"""
Return items in the LRU using a generator
"""
cur = self.first
while cur != None:
cur2 = cur.next
@ -87,17 +115,32 @@ class LRU: #Implementation of a length-limited O(1) LRU cache
raise StopIteration
def iterkeys(self):
"""
Return keys in the LRU using a generator
"""
return iter(self.d)
def itervalues(self):
for i,j in self.iteritems():
yield j
"""
Return items and keys in the LRU using a generator
"""
for data in self.iteritems():
yield data[1]
def keys(self):
return [i for i,j in self.iteritems()]
"""
Return all keys
"""
return [data[0] for data in self.iteritems()]
def values(self):
return [j for i,j in self.iteritems()]
"""
Return all values
"""
return [data[1] for data in self.iteritems()]
def items(self):
return [i for i in self.iteritems()]
"""
Return all items
"""
return [data[0] for data in self.iteritems()]