Fix file handling

bzr-revno: 660
This commit is contained in:
meths@btinternet.com 2009-11-07 06:45:25 +00:00 committed by Tim Bentley
commit eba4115490
14 changed files with 349 additions and 247 deletions

View File

@ -74,6 +74,7 @@ class OpenLP(QtGui.QApplication):
#Load and store current Application Version
filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(filepath, u'version.txt'))
fversion = None
try:
fversion = open(filepath, 'r')
for line in fversion:
@ -83,6 +84,9 @@ class OpenLP(QtGui.QApplication):
except:
applicationVersion = {u'Full':u'1.9.0-000',
u'version':u'1.9.0', u'build':u'000'}
finally:
if fversion:
fversion.close()
#set the default string encoding
try:
sys.setappdefaultencoding(u'utf-8')

View File

@ -60,7 +60,7 @@ class SettingsManager(object):
u'user interface', u'display previewpanel', True))
def setUIItemVisibility(self, item=u'', isVisible=True):
if item != u'':
if item:
if item == u'ThemeManagerDock':
ConfigHelper.set_config(u'user interface',
u'display thememanager', isVisible)

View File

@ -194,7 +194,7 @@ class AmendThemeForm(QtGui.QDialog, Ui_AmendThemeDialog):
def onImageToolButtonClicked(self):
filename = QtGui.QFileDialog.getOpenFileName(
self, self.trUtf8('Open file'))
if filename != u'':
if filename:
self.ImageLineEdit.setText(filename)
self.theme.background_filename = filename
self.previewTheme(self.theme)

View File

@ -35,7 +35,7 @@ from openlp.core.lib import PluginConfig, OpenLPToolbar, ServiceItem, \
class ServiceManagerList(QtGui.QTreeWidget):
def __init__(self,parent=None,name=None):
def __init__(self, parent=None, name=None):
QtGui.QTreeWidget.__init__(self,parent)
self.parent = parent
@ -418,7 +418,7 @@ class ServiceManager(QtGui.QWidget):
u'Save Service', self.config.get_last_dir())
else:
filename = self.config.get_last_dir()
if filename != u'':
if filename:
splittedFile = filename.split(u'.')
if splittedFile[-1] != u'osz':
filename = filename + u'.osz'
@ -427,6 +427,9 @@ class ServiceManager(QtGui.QWidget):
self.config.set_last_dir(filename)
service = []
servicefile = filename + u'.osd'
zip = None
file = None
try:
zip = zipfile.ZipFile(unicode(filename), 'w')
for item in self.serviceItems:
service.append(
@ -441,6 +444,12 @@ class ServiceManager(QtGui.QWidget):
cPickle.dump(service, file)
file.close()
zip.write(servicefile)
except:
log.exception(u'Failed to save service to disk')
finally:
if file:
file.close()
if zip:
zip.close()
try:
os.remove(servicefile)
@ -467,8 +476,10 @@ class ServiceManager(QtGui.QWidget):
self.config.get_last_dir(), u'Services (*.osz)')
filename = unicode(filename)
name = filename.split(os.path.sep)
if filename != u'':
if filename:
self.config.set_last_dir(filename)
zip = None
f = None
try:
zip = zipfile.ZipFile(unicode(filename))
for file in zip.namelist():
@ -501,6 +512,11 @@ class ServiceManager(QtGui.QWidget):
log.exception(u'Failed to remove osd file')
except:
log.exception(u'Problem loading a service file')
finally:
if f:
f.close()
if zip:
zip.close()
self.isNew = False
self.serviceName = name[len(name) - 1]
self.parent.serviceChanged(True, self.serviceName)

View File

@ -426,7 +426,7 @@ class SlideController(QtGui.QWidget):
self.onSlideSelected()
self.PreviewListWidget.setFocus()
log.info(u'Display Rendering took %4s' % (time.time() - before))
if self.serviceitem.audit != u'' and self.isLive:
if self.serviceitem.audit and self.isLive:
Receiver().send_message(u'songusage_live', self.serviceitem.audit)
log.debug(u'displayServiceManagerItems End')

View File

@ -182,10 +182,6 @@ class ThemeManager(QtGui.QWidget):
self.ThemeListWidget.takeItem(row)
try:
os.remove(os.path.join(self.path, th))
except:
#if not present do not worry
pass
try:
shutil.rmtree(os.path.join(self.path, theme))
except:
#if not present do not worry
@ -210,15 +206,21 @@ class ThemeManager(QtGui.QWidget):
unicode(self.trUtf8(u'Save Theme - (%s)')) % theme,
self.config.get_last_dir(1) )
path = unicode(path)
if path != u'':
if path:
self.config.set_last_dir(path, 1)
themePath = os.path.join(path, theme + u'.theme')
zip = None
try:
zip = zipfile.ZipFile(themePath, u'w')
source = os.path.join(self.path, theme)
for root, dirs, files in os.walk(source):
for name in files:
zip.write(
os.path.join(source, name), os.path.join(theme, name))
except:
log.exception(u'Export Theme Failed')
finally:
if zip:
zip.close()
def onImportTheme(self):
@ -291,14 +293,10 @@ class ThemeManager(QtGui.QWidget):
"""
log.debug(u'Unzipping theme %s', filename)
filename = unicode(filename)
zip = None
outfile = None
try:
zip = zipfile.ZipFile(filename)
except:
QtGui.QMessageBox.critical(
self, self.trUtf8(u'Error'),
self.trUtf8(u'File is not a valid theme!'),
QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok))
return
filexml = None
themename = None
for file in zip.namelist():
@ -323,12 +321,21 @@ class ThemeManager(QtGui.QWidget):
filexml = xml_data
outfile = open(fullpath, u'w')
outfile.write(filexml)
outfile.close()
else:
outfile = open(fullpath, u'w')
outfile.write(zip.read(file))
outfile.close()
self.generateAndSaveImage(dir, themename, filexml)
except:
QtGui.QMessageBox.critical(
self, self.trUtf8(u'Error'),
self.trUtf8(u'File is not a valid theme!'),
QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok))
log.exception(u'Importing theme from zip file failed')
finally:
if zip:
zip.close()
if outfile:
outfile.close()
def checkVersion1(self, xmlfile):
"""
@ -408,13 +415,22 @@ class ThemeManager(QtGui.QWidget):
result == QtGui.QMessageBox.Yes
if result == QtGui.QMessageBox.Yes:
# Save the theme, overwriting the existing theme if necessary.
outfile = None
try:
outfile = open(theme_file, u'w')
outfile.write(theme_pretty_xml)
except:
log.exception(u'Saving theme to file failed')
finally:
if outfile:
outfile.close()
if image_from and image_from != image_to:
print "if", image_from
print "it", image_to
try:
shutil.copyfile(image_from, image_to)
except:
log.exception(u'Failed to save theme image')
self.generateAndSaveImage(self.path, name, theme_xml)
self.loadThemes()
else:

View File

@ -101,23 +101,29 @@ class Registry(object):
return False
def _load(self):
file_handle = None
try:
if not os.path.isfile(self.file_name):
return False
file_handle = open(self.file_name, u'r')
self.config.readfp(file_handle)
file_handle.close()
return True
except:
return False
finally:
if file_handle:
file_handle.close()
def _save(self):
file_handle = None
try:
if not os.path.exists(os.path.dirname(self.file_name)):
os.makedirs(os.path.dirname(self.file_name))
file_handle = open(self.file_name, u'w')
self.config.write(file_handle)
file_handle.close()
return self._load()
except:
return False
finally:
if file_handle:
file_handle.close()

View File

@ -59,6 +59,7 @@ class BibleImportForm(QtGui.QDialog, Ui_BibleImportDialog):
filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(filepath, u'..',
u'resources', u'crosswalkbooks.csv'))
fbibles = None
try:
fbibles = open(filepath, 'r')
for line in fbibles:
@ -66,6 +67,9 @@ class BibleImportForm(QtGui.QDialog, Ui_BibleImportDialog):
self.cwBibleVersions[p[0]] = p[1].replace(u'\n', u'')
except:
log.exception(u'Crosswalk resources missing')
finally:
if fbibles:
fbibles.close()
#Load and store BibleGateway Bibles
filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(filepath, u'..',
@ -77,6 +81,9 @@ class BibleImportForm(QtGui.QDialog, Ui_BibleImportDialog):
self.bgBibleVersions[p[0]] = p[1].replace(u'\n', u'')
except:
log.exception(u'Biblegateway resources missing')
finally:
if fbibles:
fbibles.close()
self.loadBibleCombo(self.cwBibleVersions)
self.cwActive = True
@ -125,7 +132,7 @@ class BibleImportForm(QtGui.QDialog, Ui_BibleImportDialog):
filename = QtGui.QFileDialog.getOpenFileName(
self, self.trUtf8(u'Open Bible Verses file'),
self.config.get_last_dir(1))
if filename != u'':
if filename:
self.VerseLocationEdit.setText(filename)
self.config.set_last_dir(filename, 1)
self.setCsv()
@ -134,7 +141,7 @@ class BibleImportForm(QtGui.QDialog, Ui_BibleImportDialog):
filename = QtGui.QFileDialog.getOpenFileName(
self, self.trUtf8(u'Open Bible Books file'),
self.config.get_last_dir(2))
if filename != u'':
if filename:
self.BooksLocationEdit.setText(filename)
self.config.set_last_dir(filename, 2)
self.setCsv()
@ -143,7 +150,7 @@ class BibleImportForm(QtGui.QDialog, Ui_BibleImportDialog):
filename = QtGui.QFileDialog.getOpenFileName(
self, self.trUtf8(u'Open OSIS import file'),
self.config.get_last_dir(3))
if filename != u'':
if filename:
self.OSISLocationEdit.setText(filename)
self.config.set_last_dir(filename, 3)
self.setOsis()

View File

@ -48,9 +48,9 @@ class BibleCSVImpl(BibleCommon):
def load_data(self, booksfile, versesfile, dialogobject):
#Populate the Tables
fbooks = None
try:
fbooks = open(booksfile, 'r')
fverse = open(versesfile, 'r')
count = 0
for line in fbooks:
# cancel pressed
@ -68,7 +68,15 @@ class BibleCSVImpl(BibleCommon):
if count % 3 == 0:
Receiver().send_message(u'process_events')
count = 0
except:
log.exception(u'Loading books from file failed')
finally:
if fbooks:
fbooks.close()
fverse = None
try:
fverse = open(versesfile, 'r')
count = 0
book_ptr = None
for line in fverse:
@ -91,3 +99,8 @@ class BibleCSVImpl(BibleCommon):
if count % 3 == 0:
Receiver().send_message(u'process_events')
count = 0
except:
log.exception(u'Loading verses from file failed')
finally:
if fverse:
fverse.close()

View File

@ -60,12 +60,20 @@ class BibleOSISImpl():
filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(
filepath, u'..', u'resources',u'osisbooks.csv'))
fbibles = None
try:
fbibles = open(filepath, u'r')
for line in fbibles:
p = line.split(u',')
self.booksOfBible[p[0]] = p[1].replace(u'\n', u'')
self.abbrevOfBible[p[0]] = p[2].replace(u'\n', u'')
self.loadbible = True
except:
log.exception(u'OSIS bible import failed')
finally:
self.loadbible = False
if fbibles:
fbibles.close()
QtCore.QObject.connect(Receiver().get_receiver(),
QtCore.SIGNAL(u'openlpstopimport'), self.stop_import)
@ -86,9 +94,18 @@ class BibleOSISImpl():
The Import dialog, so that we can increase the counter on
the progress bar.
"""
detect_file = None
try:
detect_file = open(osisfile_record, u'r')
details = chardet.detect(detect_file.read(2048))
except:
log.exception(u'Failed to detect OSIS file encoding')
return
finally:
if detect_file:
detect_file.close()
osis = None
try:
osis = codecs.open(osisfile_record, u'r', details['encoding'])
book_ptr = None
count = 0
@ -113,7 +130,8 @@ class BibleOSISImpl():
#remove tags of extra information
text = self.remove_block(u'<title', u'</title>', text)
text = self.remove_block(u'<note', u'</note>', text)
text = self.remove_block(u'<divineName', u'</divineName>', text)
text = self.remove_block(
u'<divineName', u'</divineName>', text)
text = self.remove_tag(u'<lb', text)
text = self.remove_tag(u'<q', text)
text = self.remove_tag(u'<l', text)
@ -139,7 +157,8 @@ class BibleOSISImpl():
if book_ptr != p[0]:
# first time through
if book_ptr is None:
# set the max book size depending on the first book read
# set the max book size depending
# on the first book read
if p[0] == u'Gen':
dialogobject.setMax(65)
else:
@ -162,6 +181,11 @@ class BibleOSISImpl():
if count % 3 == 0:
Receiver().send_message(u'process_events')
count = 0
except:
log.exception(u'Loading bible from OSIS file failed')
finally:
if osis:
osis.close()
def remove_block(self, start_tag, end_tag, text):
"""

View File

@ -105,7 +105,8 @@ class BibleCommon(object):
xml_string = u''
req = urllib2.Request(urlstring)
#Make us look like an IE Browser on XP to stop blocking by web site
req.add_header(u'User-Agent', u'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')
req.add_header(u'User-Agent',
u'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')
try:
handle = urllib2.urlopen(req)
html = handle.read()
@ -164,4 +165,3 @@ class BibleCommon(object):
start_tag = text.find(u'<')
text = text.replace(u'>', u'')
return text.rstrip().lstrip()

View File

@ -71,7 +71,7 @@ class BibleManager(object):
def reload_bibles(self):
log.debug(u'Reload bibles')
files = self.config.get_files(self.bibleSuffix)
log.debug(u'Bible Files %s', files )
log.debug(u'Bible Files %s', files)
self.bible_db_cache = {}
self.bible_http_cache = {}
# books of the bible with testaments
@ -116,12 +116,19 @@ class BibleManager(object):
filepath = os.path.split(os.path.abspath(__file__))[0]
filepath = os.path.abspath(os.path.join(
filepath, u'..', u'resources',u'httpbooks.csv'))
fbibles = None
try:
fbibles = open(filepath, u'r')
for line in fbibles:
p = line.split(u',')
self.book_abbreviations[p[0]] = p[1].replace(u'\n', '')
self.book_testaments[p[0]] = p[2].replace(u'\n', '')
self.book_chapters.append({u'book':p[0], u'total':p[3].replace(u'\n', '')})
except:
log.exception(u'Failed to load bible')
finally:
if fbibles:
fbibles.close()
log.debug(u'Bible Initialised')
def process_dialog(self, dialogobject):

View File

@ -94,13 +94,10 @@ class _OpenSong(XmlRootClass):
in OpenSong an author list may be separated by '/'
return as a string
"""
res = []
if self.author:
lst = self.author.split(u' and ')
for l in lst:
res.append(l.strip())
s = u', '.join(res)
return s
list = self.author.split(u' and ')
res = [item.strip() for item in list]
return u', '.join(res)
def get_category_array(self):
"""Convert theme and alttheme into category_array
@ -116,8 +113,8 @@ class _OpenSong(XmlRootClass):
return s
def _reorder_verse(self, tag, tmpVerse):
"""Reorder the verse in case of first char is a number
"""
Reorder the verse in case of first char is a number
tag -- the tag of this verse / verse group
tmpVerse -- list of strings
"""
@ -147,8 +144,8 @@ class _OpenSong(XmlRootClass):
return res
def get_lyrics(self):
"""Convert the lyrics to openlp lyrics format
"""
Convert the lyrics to openlp lyrics format
return as list of strings
"""
lyrics = self.lyrics.split(u'\n')
@ -277,17 +274,22 @@ class Song(object):
self.set_lyrics(opensong.get_lyrics())
def from_opensong_file(self, xmlfilename):
"""Initialize from file containing xml
"""
Initialize from file containing xml
xmlfilename -- path to xml file
"""
lst = []
f = open(xmlfilename, 'r')
for line in f:
lst.append(line)
f.close()
xml = "".join(lst)
osfile = None
try:
osfile = open(xmlfilename, 'r')
list = [line for line in osfile]
osfile.close()
xml = "".join(list)
self.from_opensong_buffer(xml)
except:
log.exception(u'Failed to load opensong xml file')
finally:
if osfile:
osfile.close()
def _remove_punctuation(self, title):
"""Remove the puntuation chars from title
@ -380,16 +382,20 @@ class Song(object):
self.set_lyrics(lyrics)
def from_ccli_text_file(self, textFileName):
"""Create song from a list of texts read from given file
"""
Create song from a list of texts read from given file
textFileName -- path to text file
"""
lines = []
f = open(textFileName, 'r')
for orgline in f:
lines.append(orgline.rstrip())
f.close()
ccli_file = None
try:
ccli_file = open(textFileName, 'r')
lines = [orgline.rstrip() for orgline in ccli_file]
self.from_ccli_text_buffer(lines)
except:
log.exception(u'Failed to load CCLI text file')
finally:
if ccli_file:
ccli_file.close()
def _assure_string(self, string_in):
"""Force a string is returned"""
@ -401,12 +407,9 @@ class Song(object):
def _split_to_list(self, aString):
"""Split a string into a list - comma separated"""
res = []
if aString:
lst = aString.split(u',')
for l in lst:
# remove whitespace
res.append(l.strip())
list = aString.split(u',')
res = [item.strip() for item in list]
return res
def _list_to_string(self, strOrList):
@ -419,8 +422,8 @@ class Song(object):
lst = []
else:
raise SongTypeError(u'Variable not String or List')
s = u', '.join(lst)
return s
string = u', '.join(lst)
return string
def get_copyright(self):
"""Return copyright info string"""

View File

@ -111,12 +111,18 @@ class SongUsageDetailForm(QtGui.QDialog, Ui_SongUsageDetailDialog):
self.ToDateEdit.date().toString(u'ddMMyyyy'))
audits = self.parent.auditmanager.get_all_audits()
outname = os.path.join(unicode(self.FileLineEdit.text()), filename)
file = None
try:
file = open(outname, u'w')
for audit in audits:
record = u'\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n' % \
(audit.auditdate,audit.audittime, audit.title,
audit.copyright, audit.ccl_number , audit.authors)
file.write(record)
except:
log.exception(u'Failed to write out audit records')
finally:
if file:
file.close()
def summaryReport(self):