Finished fixing variable names.

This commit is contained in:
Raoul Snyman 2011-09-06 07:47:33 +02:00
parent 14ffb6d3c1
commit 9659834430
7 changed files with 206 additions and 205 deletions

View File

@ -165,7 +165,7 @@ class CCLIFileImport(SongImport):
elif line.startswith(u'Themes='): elif line.startswith(u'Themes='):
song_topics = line[7:].strip() song_topics = line[7:].strip()
elif line.startswith(u'[S A'): elif line.startswith(u'[S A'):
self.ccli_number = line[4:-3].strip() self.ccliNumber = line[4:-3].strip()
elif line.startswith(u'Fields='): elif line.startswith(u'Fields='):
# Fields contain single line indicating verse, chorus, etc, # Fields contain single line indicating verse, chorus, etc,
# /t delimited, same as with words field. store seperately # /t delimited, same as with words field. store seperately
@ -204,7 +204,7 @@ class CCLIFileImport(SongImport):
verse_type = VerseType.Tags[VerseType.Other] verse_type = VerseType.Tags[VerseType.Other]
verse_text = verse_lines[1] verse_text = verse_lines[1]
if len(verse_text) > 0: if len(verse_text) > 0:
self.add_verse(verse_text, verse_type) self.addVerse(verse_text, verse_type)
check_first_verse_line = False check_first_verse_line = False
# Handle multiple authors # Handle multiple authors
author_list = song_author.split(u'/') author_list = song_author.split(u'/')
@ -213,9 +213,9 @@ class CCLIFileImport(SongImport):
for author in author_list: for author in author_list:
separated = author.split(u',') separated = author.split(u',')
if len(separated) > 1: if len(separated) > 1:
self.add_author(u' '.join(reversed(separated))) self.addAuthor(u' '.join(reversed(separated)))
else: else:
self.add_author(author) self.addAuthor(author)
self.topics = [topic.strip() for topic in song_topics.split(u'/t')] self.topics = [topic.strip() for topic in song_topics.split(u'/t')]
return self.finish() return self.finish()
@ -264,7 +264,7 @@ class CCLIFileImport(SongImport):
continue continue
elif verse_start: elif verse_start:
if verse_text: if verse_text:
self.add_verse(verse_text, verse_type) self.addVerse(verse_text, verse_type)
verse_text = u'' verse_text = u''
verse_start = False verse_start = False
else: else:
@ -278,7 +278,7 @@ class CCLIFileImport(SongImport):
if clean_line.startswith(u'CCLI'): if clean_line.startswith(u'CCLI'):
line_number += 1 line_number += 1
ccli_parts = clean_line.split(' ') ccli_parts = clean_line.split(' ')
self.ccli_number = ccli_parts[len(ccli_parts) - 1] self.ccliNumber = ccli_parts[len(ccli_parts) - 1]
elif not verse_start: elif not verse_start:
# We have the verse descriptor # We have the verse descriptor
verse_desc_parts = clean_line.split(u' ') verse_desc_parts = clean_line.split(u' ')
@ -333,5 +333,5 @@ class CCLIFileImport(SongImport):
if len(author_list) < 2: if len(author_list) < 2:
author_list = song_author.split(u'|') author_list = song_author.split(u'|')
# Clean spaces before and after author names. # Clean spaces before and after author names.
[self.add_author(author_name.strip()) for author_name in author_list] [self.addAuthor(author_name.strip()) for author_name in author_list]
return self.finish() return self.finish()

View File

@ -65,34 +65,34 @@ class EasiSlidesImport(SongImport):
for song in song_xml.Item: for song in song_xml.Item:
if self.stopImportFlag: if self.stopImportFlag:
return return
self._parse_song(song) self._parseSong(song)
def _parse_song(self, song): def _parseSong(self, song):
self._success = True self._success = True
self._add_unicode_attribute(u'title', song.Title1, True) self._addUnicodeAttribute(u'title', song.Title1, True)
if hasattr(song, u'Title2'): if hasattr(song, u'Title2'):
self._add_unicode_attribute(u'alternate_title', song.Title2) self._addUnicodeAttribute(u'alternateTitle', song.Title2)
if hasattr(song, u'SongNumber'): if hasattr(song, u'SongNumber'):
self._add_unicode_attribute(u'song_number', song.SongNumber) self._addUnicodeAttribute(u'songNumber', song.SongNumber)
if self.song_number == u'0': if self.songNumber == u'0':
self.song_number = u'' self.songNumber = u''
self._add_authors(song) self._addAuthors(song)
if hasattr(song, u'Copyright'): if hasattr(song, u'Copyright'):
self._add_copyright(song.Copyright) self._addCopyright(song.Copyright)
if hasattr(song, u'LicenceAdmin1'): if hasattr(song, u'LicenceAdmin1'):
self._add_copyright(song.LicenceAdmin1) self._addCopyright(song.LicenceAdmin1)
if hasattr(song, u'LicenceAdmin2'): if hasattr(song, u'LicenceAdmin2'):
self._add_copyright(song.LicenceAdmin2) self._addCopyright(song.LicenceAdmin2)
if hasattr(song, u'BookReference'): if hasattr(song, u'BookReference'):
self._add_unicode_attribute(u'song_book_name', song.BookReference) self._addUnicodeAttribute(u'songBookName', song.BookReference)
self._parse_and_add_lyrics(song) self._parseAndAddLyrics(song)
if self._success: if self._success:
if not self.finish(): if not self.finish():
self.logError(song.Title1 if song.Title1 else u'') self.logError(song.Title1 if song.Title1 else u'')
else: else:
self.setDefaults() self.setDefaults()
def _add_unicode_attribute(self, self_attribute, import_attribute, def _addUnicodeAttribute(self, self_attribute, import_attribute,
mandatory=False): mandatory=False):
""" """
Add imported values to the song model converting them to unicode at the Add imported values to the song model converting them to unicode at the
@ -119,7 +119,7 @@ class EasiSlidesImport(SongImport):
if mandatory: if mandatory:
self._success = False self._success = False
def _add_authors(self, song): def _addAuthors(self, song):
try: try:
authors = unicode(song.Writer).split(u',') authors = unicode(song.Writer).split(u',')
self.authors = \ self.authors = \
@ -130,7 +130,7 @@ class EasiSlidesImport(SongImport):
except AttributeError: except AttributeError:
pass pass
def _add_copyright(self, element): def _addCopyright(self, element):
""" """
Add a piece of copyright to the total copyright information for the Add a piece of copyright to the total copyright information for the
song. song.
@ -139,14 +139,14 @@ class EasiSlidesImport(SongImport):
The imported variable to get the data from. The imported variable to get the data from.
""" """
try: try:
self.add_copyright(unicode(element).strip()) self.addCopyright(unicode(element).strip())
except UnicodeDecodeError: except UnicodeDecodeError:
log.exception(u'Unicode error on decoding copyright: %s' % element) log.exception(u'Unicode error on decoding copyright: %s' % element)
self._success = False self._success = False
except AttributeError: except AttributeError:
pass pass
def _parse_and_add_lyrics(self, song): def _parseAndAddLyrics(self, song):
try: try:
lyrics = unicode(song.Contents).strip() lyrics = unicode(song.Contents).strip()
except UnicodeDecodeError: except UnicodeDecodeError:
@ -295,7 +295,7 @@ class EasiSlidesImport(SongImport):
else: else:
continue continue
if tag in versetags: if tag in versetags:
self.verse_order_list.append(tag) self.verseOrderList.append(tag)
else: else:
log.info(u'Got order item %s, which is not in versetags,' log.info(u'Got order item %s, which is not in versetags,'
u'dropping item from presentation order', tag) u'dropping item from presentation order', tag)

View File

@ -49,15 +49,15 @@ def strip_rtf(blob, encoding):
control = False control = False
clear_text = [] clear_text = []
control_word = [] control_word = []
# workaround for \tx bug: remove one pair of curly braces # workaround for \tx bug: remove one pair of curly braces
# if \tx is encountered # if \tx is encountered
match = RTF_STRIPPING_REGEX.search(blob) match = RTF_STRIPPING_REGEX.search(blob)
if match: if match:
# start and end indices of match are curly braces - filter them out # start and end indices of match are curly braces - filter them out
blob = ''.join([blob[i] for i in xrange(len(blob)) blob = ''.join([blob[i] for i in xrange(len(blob))
if i != match.start() and i !=match.end()]) if i != match.start() and i !=match.end()])
for c in blob: for c in blob:
if control: if control:
# for delimiters, set control to False # for delimiters, set control to False
@ -166,13 +166,13 @@ class EasyWorshipSongImport(SongImport):
if db_size < 0x800: if db_size < 0x800:
return return
db_file = open(self.importSource, 'rb') db_file = open(self.importSource, 'rb')
self.memo_file = open(import_source_mb, 'rb') self.memoFile = open(import_source_mb, 'rb')
# Don't accept files that are clearly not paradox files # Don't accept files that are clearly not paradox files
record_size, header_size, block_size, first_block, num_fields \ record_size, header_size, block_size, first_block, num_fields \
= struct.unpack('<hhxb8xh17xh', db_file.read(35)) = struct.unpack('<hhxb8xh17xh', db_file.read(35))
if header_size != 0x800 or block_size < 1 or block_size > 4: if header_size != 0x800 or block_size < 1 or block_size > 4:
db_file.close() db_file.close()
self.memo_file.close() self.memoFile.close()
return return
# Take a stab at how text is encoded # Take a stab at how text is encoded
self.encoding = u'cp1252' self.encoding = u'cp1252'
@ -218,16 +218,16 @@ class EasyWorshipSongImport(SongImport):
field_info, i * 2) field_info, i * 2)
field_descs.append(FieldDescEntry(field_name, field_type, field_descs.append(FieldDescEntry(field_name, field_type,
field_size)) field_size))
self.set_record_struct(field_descs) self.setRecordStruct(field_descs)
# Pick out the field description indexes we will need # Pick out the field description indexes we will need
try: try:
success = True success = True
fi_title = self.find_field(u'Title') fi_title = self.findField(u'Title')
fi_author = self.find_field(u'Author') fi_author = self.findField(u'Author')
fi_copy = self.find_field(u'Copyright') fi_copy = self.findField(u'Copyright')
fi_admin = self.find_field(u'Administrator') fi_admin = self.findField(u'Administrator')
fi_words = self.find_field(u'Words') fi_words = self.findField(u'Words')
fi_ccli = self.find_field(u'Song Number') fi_ccli = self.findField(u'Song Number')
except IndexError: except IndexError:
# This is the wrong table # This is the wrong table
success = False success = False
@ -244,13 +244,13 @@ class EasyWorshipSongImport(SongImport):
raw_record = db_file.read(record_size) raw_record = db_file.read(record_size)
self.fields = self.record_struct.unpack(raw_record) self.fields = self.record_struct.unpack(raw_record)
self.setDefaults() self.setDefaults()
self.title = self.get_field(fi_title) self.title = self.getField(fi_title)
# Get remaining fields. # Get remaining fields.
copy = self.get_field(fi_copy) copy = self.getField(fi_copy)
admin = self.get_field(fi_admin) admin = self.getField(fi_admin)
ccli = self.get_field(fi_ccli) ccli = self.getField(fi_ccli)
authors = self.get_field(fi_author) authors = self.getField(fi_author)
words = self.get_field(fi_words) words = self.getField(fi_words)
# Set the SongImport object members. # Set the SongImport object members.
if copy: if copy:
self.copyright = copy self.copyright = copy
@ -261,7 +261,7 @@ class EasyWorshipSongImport(SongImport):
unicode(translate('SongsPlugin.EasyWorshipSongImport', unicode(translate('SongsPlugin.EasyWorshipSongImport',
'Administered by %s')) % admin 'Administered by %s')) % admin
if ccli: if ccli:
self.ccli_number = ccli self.ccliNumber = ccli
if authors: if authors:
# Split up the authors # Split up the authors
author_list = authors.split(u'/') author_list = authors.split(u'/')
@ -270,7 +270,7 @@ class EasyWorshipSongImport(SongImport):
if len(author_list) < 2: if len(author_list) < 2:
author_list = authors.split(u',') author_list = authors.split(u',')
for author_name in author_list: for author_name in author_list:
self.add_author(author_name.strip()) self.addAuthor(author_name.strip())
if words: if words:
# Format the lyrics # Format the lyrics
words = strip_rtf(words, self.encoding) words = strip_rtf(words, self.encoding)
@ -281,9 +281,9 @@ class EasyWorshipSongImport(SongImport):
continue continue
verse_split = verse.split(u'\n', 1) verse_split = verse.split(u'\n', 1)
first_line_is_tag = False first_line_is_tag = False
# EW tags: verse, chorus, pre-chorus, bridge, tag, # EW tags: verse, chorus, pre-chorus, bridge, tag,
# intro, ending, slide # intro, ending, slide
for type in VerseType.Names+[u'tag', u'slide']: for type in VerseType.Names+[u'tag', u'slide']:
type = type.lower() type = type.lower()
ew_tag = verse_split[0].strip().lower() ew_tag = verse_split[0].strip().lower()
if ew_tag.startswith(type): if ew_tag.startswith(type):
@ -293,7 +293,7 @@ class EasyWorshipSongImport(SongImport):
first_line_is_tag = True first_line_is_tag = True
number_found = False number_found = False
# check if tag is followed by number and/or note # check if tag is followed by number and/or note
if len(ew_tag) > len(type): if len(ew_tag) > len(type):
match = NUMBER_REGEX.search(ew_tag) match = NUMBER_REGEX.search(ew_tag)
if match: if match:
number = match.group() number = match.group()
@ -305,8 +305,9 @@ class EasyWorshipSongImport(SongImport):
if not number_found: if not number_found:
verse_type += u'1' verse_type += u'1'
break break
self.add_verse( self.addVerse(
verse_split[-1].strip() if first_line_is_tag else verse, verse_split[-1].strip() \
if first_line_is_tag else verse,
verse_type) verse_type)
if len(self.comments) > 5: if len(self.comments) > 5:
self.comments += unicode( self.comments += unicode(
@ -318,10 +319,10 @@ class EasyWorshipSongImport(SongImport):
if not self.finish(): if not self.finish():
self.logError(self.importSource) self.logError(self.importSource)
db_file.close() db_file.close()
self.memo_file.close() self.memoFile.close()
def find_field(self, field_name): def find_field(self, field_name):
return [i for i, x in enumerate(self.field_descs) return [i for i, x in enumerate(self.fieldDescs)
if x.name == field_name][0] if x.name == field_name][0]
def set_record_struct(self, field_descs): def set_record_struct(self, field_descs):
@ -351,12 +352,12 @@ class EasyWorshipSongImport(SongImport):
fsl.append('Q') fsl.append('Q')
else: else:
fsl.append('%ds' % field_desc.size) fsl.append('%ds' % field_desc.size)
self.record_struct = struct.Struct(''.join(fsl)) self.recordStruct = struct.Struct(''.join(fsl))
self.field_descs = field_descs self.fieldDescs = field_descs
def get_field(self, field_desc_index): def get_field(self, field_desc_index):
field = self.fields[field_desc_index] field = self.fields[field_desc_index]
field_desc = self.field_descs[field_desc_index] field_desc = self.fieldDescs[field_desc_index]
# Return None in case of 'blank' entries # Return None in case of 'blank' entries
if isinstance(field, str): if isinstance(field, str):
if len(field.rstrip('\0')) == 0: if len(field.rstrip('\0')) == 0:
@ -382,18 +383,18 @@ class EasyWorshipSongImport(SongImport):
struct.unpack_from('<II', field, len(field)-10) struct.unpack_from('<II', field, len(field)-10)
sub_block = block_start & 0xff sub_block = block_start & 0xff
block_start &= ~0xff block_start &= ~0xff
self.memo_file.seek(block_start) self.memoFile.seek(block_start)
memo_block_type, = struct.unpack('b', self.memo_file.read(1)) memo_block_type, = struct.unpack('b', self.memoFile.read(1))
if memo_block_type == 2: if memo_block_type == 2:
self.memo_file.seek(8, os.SEEK_CUR) self.memoFile.seek(8, os.SEEK_CUR)
elif memo_block_type == 3: elif memo_block_type == 3:
if sub_block > 63: if sub_block > 63:
return u'' return u''
self.memo_file.seek(11 + (5 * sub_block), os.SEEK_CUR) self.memoFile.seek(11 + (5 * sub_block), os.SEEK_CUR)
sub_block_start, = struct.unpack('B', self.memo_file.read(1)) sub_block_start, = struct.unpack('B', self.memoFile.read(1))
self.memo_file.seek(block_start + (sub_block_start * 16)) self.memoFile.seek(block_start + (sub_block_start * 16))
else: else:
return u'' return u''
return self.memo_file.read(blob_size) return self.memoFile.read(blob_size)
else: else:
return 0 return 0

View File

@ -59,7 +59,7 @@ class OooImport(SongImport):
""" """
SongImport.__init__(self, manager, **kwargs) SongImport.__init__(self, manager, **kwargs)
self.document = None self.document = None
self.process_started = False self.processStarted = False
def doImport(self): def doImport(self):
if not isinstance(self.importSource, list): if not isinstance(self.importSource, list):
@ -79,10 +79,10 @@ class OooImport(SongImport):
break break
filename = unicode(filename) filename = unicode(filename)
if os.path.isfile(filename): if os.path.isfile(filename):
self.open_ooo_file(filename) self.openOooFile(filename)
if self.document: if self.document:
self.process_ooo_document() self.processOooDocument()
self.close_ooo_file() self.closeOooFile()
else: else:
self.logError(self.filepath, self.logError(self.filepath,
translate('SongsPlugin.SongImport', translate('SongsPlugin.SongImport',
@ -90,27 +90,27 @@ class OooImport(SongImport):
else: else:
self.logError(self.filepath, self.logError(self.filepath,
translate('SongsPlugin.SongImport', 'File not found')) translate('SongsPlugin.SongImport', 'File not found'))
self.close_ooo() self.closeOoo()
def process_ooo_document(self): def processOooDocument(self):
""" """
Handle the import process for OpenOffice files. This method facilitates Handle the import process for OpenOffice files. This method facilitates
allowing subclasses to handle specific types of OpenOffice files. allowing subclasses to handle specific types of OpenOffice files.
""" """
if self.document.supportsService( if self.document.supportsService(
"com.sun.star.presentation.PresentationDocument"): "com.sun.star.presentation.PresentationDocument"):
self.process_pres() self.processPres()
if self.document.supportsService("com.sun.star.text.TextDocument"): if self.document.supportsService("com.sun.star.text.TextDocument"):
self.process_doc() self.processDoc()
def start_ooo(self): def startOoo(self):
""" """
Start OpenOffice.org process Start OpenOffice.org process
TODO: The presentation/Impress plugin may already have it running TODO: The presentation/Impress plugin may already have it running
""" """
if os.name == u'nt': if os.name == u'nt':
self.start_ooo_process() self.startOooProcess()
self.desktop = self.ooo_manager.createInstance( self.desktop = self.oooManager.createInstance(
u'com.sun.star.frame.Desktop') u'com.sun.star.frame.Desktop')
else: else:
context = uno.getComponentContext() context = uno.getComponentContext()
@ -123,7 +123,7 @@ class OooImport(SongImport):
uno_instance = get_uno_instance(resolver) uno_instance = get_uno_instance(resolver)
except NoConnectException: except NoConnectException:
log.exception("Failed to resolve uno connection") log.exception("Failed to resolve uno connection")
self.start_ooo_process() self.startOooProcess()
loop += 1 loop += 1
else: else:
manager = uno_instance.ServiceManager manager = uno_instance.ServiceManager
@ -132,22 +132,22 @@ class OooImport(SongImport):
return return
raise raise
def start_ooo_process(self): def startOooProcess(self):
try: try:
if os.name == u'nt': if os.name == u'nt':
self.ooo_manager = Dispatch(u'com.sun.star.ServiceManager') self.oooManager = Dispatch(u'com.sun.star.ServiceManager')
self.ooo_manager._FlagAsMethod(u'Bridge_GetStruct') self.oooManager._FlagAsMethod(u'Bridge_GetStruct')
self.ooo_manager._FlagAsMethod(u'Bridge_GetValueObject') self.oooManager._FlagAsMethod(u'Bridge_GetValueObject')
else: else:
cmd = get_uno_command() cmd = get_uno_command()
process = QtCore.QProcess() process = QtCore.QProcess()
process.startDetached(cmd) process.startDetached(cmd)
process.waitForStarted() process.waitForStarted()
self.process_started = True self.processStarted = True
except: except:
log.exception("start_ooo_process failed") log.exception("start_ooo_process failed")
def open_ooo_file(self, filepath): def openOooFile(self, filepath):
""" """
Open the passed file in OpenOffice.org Impress Open the passed file in OpenOffice.org Impress
""" """
@ -166,7 +166,7 @@ class OooImport(SongImport):
if not self.document.supportsService( if not self.document.supportsService(
"com.sun.star.presentation.PresentationDocument") and not \ "com.sun.star.presentation.PresentationDocument") and not \
self.document.supportsService("com.sun.star.text.TextDocument"): self.document.supportsService("com.sun.star.text.TextDocument"):
self.close_ooo_file() self.closeOooFile()
else: else:
self.importWizard.incrementProgressBar( self.importWizard.incrementProgressBar(
u'Processing file ' + filepath, 0) u'Processing file ' + filepath, 0)
@ -174,21 +174,21 @@ class OooImport(SongImport):
log.exception("open_ooo_file failed: %s", url) log.exception("open_ooo_file failed: %s", url)
return return
def close_ooo_file(self): def closeOooFile(self):
""" """
Close file. Close file.
""" """
self.document.close(True) self.document.close(True)
self.document = None self.document = None
def close_ooo(self): def closeOoo(self):
""" """
Close OOo. But only if we started it and not on windows Close OOo. But only if we started it and not on windows
""" """
if self.process_started: if self.processStarted:
self.desktop.terminate() self.desktop.terminate()
def process_pres(self): def processPres(self):
""" """
Process the file Process the file
""" """
@ -209,10 +209,10 @@ class OooImport(SongImport):
if slidetext.strip() == u'': if slidetext.strip() == u'':
slidetext = u'\f' slidetext = u'\f'
text += slidetext text += slidetext
self.process_songs_text(text) self.processSongsText(text)
return return
def process_doc(self): def processDoc(self):
""" """
Process the doc file, a paragraph at a time Process the doc file, a paragraph at a time
""" """
@ -231,16 +231,16 @@ class OooImport(SongImport):
if textportion.BreakType in (PAGE_AFTER, PAGE_BOTH): if textportion.BreakType in (PAGE_AFTER, PAGE_BOTH):
paratext += u'\f' paratext += u'\f'
text += paratext + u'\n' text += paratext + u'\n'
self.process_songs_text(text) self.processSongsText(text)
def process_songs_text(self, text): def processSongsText(self, text):
songtexts = self.tidy_text(text).split(u'\f') songtexts = self.tidyText(text).split(u'\f')
self.setDefaults() self.setDefaults()
for songtext in songtexts: for songtext in songtexts:
if songtext.strip(): if songtext.strip():
self.process_song_text(songtext.strip()) self.processSongText(songtext.strip())
if self.check_complete(): if self.checkComplete():
self.finish() self.finish()
self.setDefaults() self.setDefaults()
if self.check_complete(): if self.checkComplete():
self.finish() self.finish()

View File

@ -130,9 +130,9 @@ class OpenSongImport(SongImport):
root = tree.getroot() root = tree.getroot()
fields = dir(root) fields = dir(root)
decode = { decode = {
u'copyright': self.add_copyright, u'copyright': self.addCopyright,
u'ccli': u'ccli_number', u'ccli': u'ccli_number',
u'author': self.parse_author, u'author': self.parseAuthor,
u'title': u'title', u'title': u'title',
u'aka': u'alternate_title', u'aka': u'alternate_title',
u'hymn_number': u'song_number' u'hymn_number': u'song_number'
@ -214,7 +214,7 @@ class OpenSongImport(SongImport):
verses[verse_tag][verse_num][inst] = [] verses[verse_tag][verse_num][inst] = []
our_verse_order.append([verse_tag, verse_num, inst]) our_verse_order.append([verse_tag, verse_num, inst])
# Tidy text and remove the ____s from extended words # Tidy text and remove the ____s from extended words
this_line = self.tidy_text(this_line) this_line = self.tidyText(this_line)
this_line = this_line.replace(u'_', u'') this_line = this_line.replace(u'_', u'')
this_line = this_line.replace(u'|', u'\n') this_line = this_line.replace(u'|', u'\n')
verses[verse_tag][verse_num][inst].append(this_line) verses[verse_tag][verse_num][inst].append(this_line)
@ -223,9 +223,9 @@ class OpenSongImport(SongImport):
for (verse_tag, verse_num, inst) in our_verse_order: for (verse_tag, verse_num, inst) in our_verse_order:
verse_def = u'%s%s' % (verse_tag, verse_num) verse_def = u'%s%s' % (verse_tag, verse_num)
lines = u'\n'.join(verses[verse_tag][verse_num][inst]) lines = u'\n'.join(verses[verse_tag][verse_num][inst])
self.add_verse(lines, verse_def) self.addVerse(lines, verse_def)
if not self.verses: if not self.verses:
self.add_verse('') self.addVerse('')
# figure out the presentation order, if present # figure out the presentation order, if present
if u'presentation' in fields and root.presentation: if u'presentation' in fields and root.presentation:
order = unicode(root.presentation) order = unicode(root.presentation)
@ -246,7 +246,7 @@ class OpenSongImport(SongImport):
verse_def = u'%s%s' % (verse_tag, verse_num) verse_def = u'%s%s' % (verse_tag, verse_num)
if verses.has_key(verse_tag) and \ if verses.has_key(verse_tag) and \
verses[verse_tag].has_key(verse_num): verses[verse_tag].has_key(verse_num):
self.verse_order_list.append(verse_def) self.verseOrderList.append(verse_def)
else: else:
log.info(u'Got order %s but not in verse tags, dropping' log.info(u'Got order %s but not in verse tags, dropping'
u'this item from presentation order', verse_def) u'this item from presentation order', verse_def)

View File

@ -83,18 +83,18 @@ class SofImport(OooImport):
OooImport.__init__(self, manager, **kwargs) OooImport.__init__(self, manager, **kwargs)
self.song = False self.song = False
def process_ooo_document(self): def processOooDocument(self):
""" """
Handle the import process for SoF files. Handle the import process for SoF files.
""" """
self.process_sof_file() self.processSofFile()
def process_sof_file(self): def processSofFile(self):
""" """
Process the RTF file, a paragraph at a time Process the RTF file, a paragraph at a time
""" """
self.blanklines = 0 self.blankLines = 0
self.new_song() self.newSong()
try: try:
paragraphs = self.document.getText().createEnumeration() paragraphs = self.document.getText().createEnumeration()
while paragraphs.hasMoreElements(): while paragraphs.hasMoreElements():
@ -102,13 +102,13 @@ class SofImport(OooImport):
return return
paragraph = paragraphs.nextElement() paragraph = paragraphs.nextElement()
if paragraph.supportsService("com.sun.star.text.Paragraph"): if paragraph.supportsService("com.sun.star.text.Paragraph"):
self.process_paragraph(paragraph) self.processParagraph(paragraph)
except RuntimeException as exc: except RuntimeException as exc:
log.exception(u'Error processing file: %s', exc) log.exception(u'Error processing file: %s', exc)
if not self.finish(): if not self.finish():
self.logError(self.filepath) self.logError(self.filepath)
def process_paragraph(self, paragraph): def processParagraph(self, paragraph):
""" """
Process a paragraph. Process a paragraph.
In the first book, a paragraph is a single line. In the latter ones In the first book, a paragraph is a single line. In the latter ones
@ -124,26 +124,26 @@ class SofImport(OooImport):
while textportions.hasMoreElements(): while textportions.hasMoreElements():
textportion = textportions.nextElement() textportion = textportions.nextElement()
if textportion.BreakType in (PAGE_BEFORE, PAGE_BOTH): if textportion.BreakType in (PAGE_BEFORE, PAGE_BOTH):
self.process_paragraph_text(text) self.processParagraphText(text)
self.new_song() self.newSong()
text = u'' text = u''
text += self.process_textportion(textportion) text += self.process_textportion(textportion)
if textportion.BreakType in (PAGE_AFTER, PAGE_BOTH): if textportion.BreakType in (PAGE_AFTER, PAGE_BOTH):
self.process_paragraph_text(text) self.processParagraphText(text)
self.new_song() self.newSong()
text = u'' text = u''
self.process_paragraph_text(text) self.processParagraphText(text)
def process_paragraph_text(self, text): def processParagraphText(self, text):
""" """
Split the paragraph text into multiple lines and process Split the paragraph text into multiple lines and process
""" """
for line in text.split(u'\n'): for line in text.split(u'\n'):
self.process_paragraph_line(line) self.processParagraphLine(line)
if self.blanklines > 2: if self.blankLines > 2:
self.new_song() self.newSong()
def process_paragraph_line(self, text): def processParagraphLine(self, text):
""" """
Process a single line. Throw away that text which isn't relevant, i.e. Process a single line. Throw away that text which isn't relevant, i.e.
stuff that appears at the end of the song. stuff that appears at the end of the song.
@ -151,16 +151,16 @@ class SofImport(OooImport):
""" """
text = text.strip() text = text.strip()
if text == u'': if text == u'':
self.blanklines += 1 self.blankLines += 1
if self.blanklines > 1: if self.blankLines > 1:
return return
if self.title != u'': if self.title != u'':
self.finish_verse() self.finishVerse()
return return
self.blanklines = 0 self.blankLines = 0
if self.skip_to_close_bracket: if self.skipToCloseBracket:
if text.endswith(u')'): if text.endswith(u')'):
self.skip_to_close_bracket = False self.skipToCloseBracket = False
return return
if text.startswith(u'CCL Licence'): if text.startswith(u'CCL Licence'):
self.italics = False self.italics = False
@ -169,24 +169,24 @@ class SofImport(OooImport):
return return
if text.startswith(u'(NB.') or text.startswith(u'(Regrettably') \ if text.startswith(u'(NB.') or text.startswith(u'(Regrettably') \
or text.startswith(u'(From'): or text.startswith(u'(From'):
self.skip_to_close_bracket = True self.skipToCloseBracket = True
return return
if text.startswith(u'Copyright'): if text.startswith(u'Copyright'):
self.add_copyright(text) self.addCopyright(text)
return return
if text == u'(Repeat)': if text == u'(Repeat)':
self.finish_verse() self.finishVerse()
self.repeat_verse() self.repeatVerse()
return return
if self.title == u'': if self.title == u'':
if self.copyright == u'': if self.copyright == u'':
self.add_sof_author(text) self.addSofAuthor(text)
else: else:
self.add_copyright(text) self.addCopyright(text)
return return
self.add_verse_line(text) self.addVerseLine(text)
def process_textportion(self, textportion): def processTextPortion(self, textportion):
""" """
Process a text portion. Here we just get the text and detect if Process a text portion. Here we just get the text and detect if
it's bold or italics. If it's bold then its a song number or song title. it's bold or italics. If it's bold then its a song number or song title.
@ -199,53 +199,53 @@ class SofImport(OooImport):
return text return text
if textportion.CharWeight == BOLD: if textportion.CharWeight == BOLD:
boldtext = text.strip() boldtext = text.strip()
if boldtext.isdigit() and self.song_number == '': if boldtext.isdigit() and self.songNumber == '':
self.add_songnumber(boldtext) self.addSongNumber(boldtext)
return u'' return u''
if self.title == u'': if self.title == u'':
text = self.uncap_text(text) text = self.uncap_text(text)
self.add_title(text) self.addTitle(text)
return text return text
if text.strip().startswith(u'('): if text.strip().startswith(u'('):
return text return text
self.italics = (textportion.CharPosture == ITALIC) self.italics = (textportion.CharPosture == ITALIC)
return text return text
def new_song(self): def newSong(self):
""" """
A change of song. Store the old, create a new A change of song. Store the old, create a new
... but only if the last song was complete. If not, stick with it ... but only if the last song was complete. If not, stick with it
""" """
if self.song: if self.song:
self.finish_verse() self.finishVerse()
if not self.check_complete(): if not self.checkComplete():
return return
self.finish() self.finish()
self.song = True self.song = True
self.setDefaults() self.setDefaults()
self.skip_to_close_bracket = False self.skipToCloseBracket = False
self.is_chorus = False self.isChorus = False
self.italics = False self.italics = False
self.currentverse = u'' self.currentVerse = u''
def add_songnumber(self, song_no): def addSongNumber(self, song_no):
""" """
Add a song number, store as alternate title. Also use the song Add a song number, store as alternate title. Also use the song
number to work out which songbook we're in number to work out which songbook we're in
""" """
self.song_number = song_no self.songNumber = song_no
self.alternate_title = song_no + u'.' self.alternateTitle = song_no + u'.'
self.song_book_pub = u'Kingsway Publications' self.songBook_pub = u'Kingsway Publications'
if int(song_no) <= 640: if int(song_no) <= 640:
self.song_book = u'Songs of Fellowship 1' self.songBook = u'Songs of Fellowship 1'
elif int(song_no) <= 1150: elif int(song_no) <= 1150:
self.song_book = u'Songs of Fellowship 2' self.songBook = u'Songs of Fellowship 2'
elif int(song_no) <= 1690: elif int(song_no) <= 1690:
self.song_book = u'Songs of Fellowship 3' self.songBook = u'Songs of Fellowship 3'
else: else:
self.song_book = u'Songs of Fellowship 4' self.songBook = u'Songs of Fellowship 4'
def add_title(self, text): def addTitle(self, text):
""" """
Add the title to the song. Strip some leading/trailing punctuation that Add the title to the song. Strip some leading/trailing punctuation that
we don't want in a title we don't want in a title
@ -258,7 +258,7 @@ class SofImport(OooImport):
self.title = title self.title = title
self.importWizard.incrementProgressBar(u'Processing song ' + title, 0) self.importWizard.incrementProgressBar(u'Processing song ' + title, 0)
def add_sof_author(self, text): def addSofAuthor(self, text):
""" """
Add the author. OpenLP stores them individually so split by 'and', '&' Add the author. OpenLP stores them individually so split by 'and', '&'
and comma. and comma.
@ -266,42 +266,42 @@ class SofImport(OooImport):
"Mr Smith" and "Mrs Smith". "Mr Smith" and "Mrs Smith".
""" """
text = text.replace(u' and ', u' & ') text = text.replace(u' and ', u' & ')
self.parse_author(text) self.parseAuthor(text)
def add_verse_line(self, text): def addVerseLine(self, text):
""" """
Add a line to the current verse. If the formatting has changed and Add a line to the current verse. If the formatting has changed and
we're beyond the second line of first verse, then this indicates we're beyond the second line of first verse, then this indicates
a change of verse. Italics are a chorus a change of verse. Italics are a chorus
""" """
if self.italics != self.is_chorus and ((len(self.verses) > 0) or if self.italics != self.isChorus and ((len(self.verses) > 0) or
(self.currentverse.count(u'\n') > 1)): (self.currentVerse.count(u'\n') > 1)):
self.finish_verse() self.finishVerse()
if self.italics: if self.italics:
self.is_chorus = True self.isChorus = True
self.currentverse += text + u'\n' self.currentVerse += text + u'\n'
def finish_verse(self): def finishVerse(self):
""" """
Verse is finished, store it. Note in book 1+2, some songs are formatted Verse is finished, store it. Note in book 1+2, some songs are formatted
incorrectly. Here we try and split songs with missing line breaks into incorrectly. Here we try and split songs with missing line breaks into
the correct number of verses. the correct number of verses.
""" """
if self.currentverse.strip() == u'': if self.currentVerse.strip() == u'':
return return
if self.is_chorus: if self.isChorus:
versetag = u'C' versetag = u'C'
splitat = None splitat = None
else: else:
versetag = u'V' versetag = u'V'
splitat = self.verse_splits(self.song_number) splitat = self.verseSplits(self.songNumber)
if splitat: if splitat:
ln = 0 ln = 0
verse = u'' verse = u''
for line in self.currentverse.split(u'\n'): for line in self.currentVerse.split(u'\n'):
ln += 1 ln += 1
if line == u'' or ln > splitat: if line == u'' or ln > splitat:
self.add_sof_verse(verse, versetag) self.addSofVerse(verse, versetag)
ln = 0 ln = 0
if line: if line:
verse = line + u'\n' verse = line + u'\n'
@ -310,19 +310,19 @@ class SofImport(OooImport):
else: else:
verse += line + u'\n' verse += line + u'\n'
if verse: if verse:
self.add_sof_verse(verse, versetag) self.addSofVerse(verse, versetag)
else: else:
self.add_sof_verse(self.currentverse, versetag) self.addSofVerse(self.currentVerse, versetag)
self.currentverse = u'' self.currentVerse = u''
self.is_chorus = False self.isChorus = False
def add_sof_verse(self, lyrics, tag): def addSofVerse(self, lyrics, tag):
self.add_verse(lyrics, tag) self.addVerse(lyrics, tag)
if not self.is_chorus and u'C1' in self.verse_order_list_generated: if not self.isChorus and u'C1' in self.verseOrderListGenerated:
self.verse_order_list_generated.append(u'C1') self.verseOrderListGenerated.append(u'C1')
self.verse_order_list_generated_useful = True self.verseOrderListGenerated_useful = True
def uncap_text(self, text): def uncapText(self, text):
""" """
Words in the title are in all capitals, so we lowercase them. Words in the title are in all capitals, so we lowercase them.
However some of these words, e.g. referring to God need a leading However some of these words, e.g. referring to God need a leading
@ -348,7 +348,7 @@ class SofImport(OooImport):
text = u''.join(textarr) text = u''.join(textarr)
return text return text
def verse_splits(self, song_number): def verseSplits(self, song_number):
""" """
Because someone at Kingsway forgot to check the 1+2 RTF file, Because someone at Kingsway forgot to check the 1+2 RTF file,
some verses were not formatted correctly. some verses were not formatted correctly.

View File

@ -91,7 +91,7 @@ class SongBeamerImport(SongImport):
(re.compile(u'<align.*?>'), u''), (re.compile(u'<align.*?>'), u''),
(re.compile(u'<valign.*?>'), u'') (re.compile(u'<valign.*?>'), u'')
] ]
def __init__(self, manager, **kwargs): def __init__(self, manager, **kwargs):
""" """
Initialise the Song Beamer importer. Initialise the Song Beamer importer.
@ -110,8 +110,8 @@ class SongBeamerImport(SongImport):
if self.stopImportFlag: if self.stopImportFlag:
return return
self.setDefaults() self.setDefaults()
self.current_verse = u'' self.currentVerse = u''
self.current_verse_type = VerseType.Tags[VerseType.Verse] self.currentVerseType = VerseType.Tags[VerseType.Verse]
read_verses = False read_verses = False
file_name = os.path.split(file)[1] file_name = os.path.split(file)[1]
if os.path.isfile(file): if os.path.isfile(file):
@ -119,48 +119,48 @@ class SongBeamerImport(SongImport):
details = chardet.detect(detect_file.read()) details = chardet.detect(detect_file.read())
detect_file.close() detect_file.close()
infile = codecs.open(file, u'r', details['encoding']) infile = codecs.open(file, u'r', details['encoding'])
songData = infile.readlines() song_data = infile.readlines()
infile.close() infile.close()
else: else:
continue continue
self.title = file_name.split('.sng')[0] self.title = file_name.split('.sng')[0]
read_verses = False read_verses = False
for line in songData: for line in song_data:
# Just make sure that the line is of the type 'Unicode'. # Just make sure that the line is of the type 'Unicode'.
line = unicode(line).strip() line = unicode(line).strip()
if line.startswith(u'#') and not read_verses: if line.startswith(u'#') and not read_verses:
self.parse_tags(line) self.parseTags(line)
elif line.startswith(u'---'): elif line.startswith(u'---'):
if self.current_verse: if self.currentVerse:
self.replace_html_tags() self.replaceHtmlTags()
self.add_verse(self.current_verse, self.addVerse(self.currentVerse,
self.current_verse_type) self.currentVerseType)
self.current_verse = u'' self.currentVerse = u''
self.current_verse_type = VerseType.Tags[VerseType.Verse] self.currentVerseType = VerseType.Tags[VerseType.Verse]
read_verses = True read_verses = True
verse_start = True verse_start = True
elif read_verses: elif read_verses:
if verse_start: if verse_start:
verse_start = False verse_start = False
if not self.check_verse_marks(line): if not self.checkVerseMarks(line):
self.current_verse = line + u'\n' self.currentVerse = line + u'\n'
else: else:
self.current_verse += line + u'\n' self.currentVerse += line + u'\n'
if self.current_verse: if self.currentVerse:
self.replace_html_tags() self.replaceHtmlTags()
self.add_verse(self.current_verse, self.current_verse_type) self.addVerse(self.currentVerse, self.currentVerseType)
if not self.finish(): if not self.finish():
self.logError(file) self.logError(file)
def replace_html_tags(self): def replaceHtmlTags(self):
""" """
This can be called to replace SongBeamer's specific (html) tags with This can be called to replace SongBeamer's specific (html) tags with
OpenLP's specific (html) tags. OpenLP's specific (html) tags.
""" """
for pair in SongBeamerImport.HTML_TAG_PAIRS: for pair in SongBeamerImport.HTML_TAG_PAIRS:
self.current_verse = pair[0].sub(pair[1], self.current_verse) self.currentVerse = pair[0].sub(pair[1], self.currentVerse)
def parse_tags(self, line): def parseTags(self, line):
""" """
Parses a meta data line. Parses a meta data line.
@ -176,11 +176,11 @@ class SongBeamerImport(SongImport):
if not tag_val[0] or not tag_val[1]: if not tag_val[0] or not tag_val[1]:
return return
if tag_val[0] == u'#(c)': if tag_val[0] == u'#(c)':
self.add_copyright(tag_val[1]) self.addCopyright(tag_val[1])
elif tag_val[0] == u'#AddCopyrightInfo': elif tag_val[0] == u'#AddCopyrightInfo':
pass pass
elif tag_val[0] == u'#Author': elif tag_val[0] == u'#Author':
self.parse_author(tag_val[1]) self.parseAuthor(tag_val[1])
elif tag_val[0] == u'#BackgroundImage': elif tag_val[0] == u'#BackgroundImage':
pass pass
elif tag_val[0] == u'#Bible': elif tag_val[0] == u'#Bible':
@ -188,7 +188,7 @@ class SongBeamerImport(SongImport):
elif tag_val[0] == u'#Categories': elif tag_val[0] == u'#Categories':
self.topics = tag_val[1].split(',') self.topics = tag_val[1].split(',')
elif tag_val[0] == u'#CCLI': elif tag_val[0] == u'#CCLI':
self.ccli_number = tag_val[1] self.ccliNumber = tag_val[1]
elif tag_val[0] == u'#Chords': elif tag_val[0] == u'#Chords':
pass pass
elif tag_val[0] == u'#ChurchSongID': elif tag_val[0] == u'#ChurchSongID':
@ -220,7 +220,7 @@ class SongBeamerImport(SongImport):
elif tag_val[0] == u'#LangCount': elif tag_val[0] == u'#LangCount':
pass pass
elif tag_val[0] == u'#Melody': elif tag_val[0] == u'#Melody':
self.parse_author(tag_val[1]) self.parseAuthor(tag_val[1])
elif tag_val[0] == u'#NatCopyright': elif tag_val[0] == u'#NatCopyright':
pass pass
elif tag_val[0] == u'#OTitle': elif tag_val[0] == u'#OTitle':
@ -235,10 +235,10 @@ class SongBeamerImport(SongImport):
song_book_pub = tag_val[1] song_book_pub = tag_val[1]
elif tag_val[0] == u'#Songbook' or tag_val[0] == u'#SongBook': elif tag_val[0] == u'#Songbook' or tag_val[0] == u'#SongBook':
book_data = tag_val[1].split(u'/') book_data = tag_val[1].split(u'/')
self.song_book_name = book_data[0].strip() self.songBookName = book_data[0].strip()
if len(book_data) == 2: if len(book_data) == 2:
number = book_data[1].strip() number = book_data[1].strip()
self.song_number = number if number.isdigit() else u'' self.songNumber = number if number.isdigit() else u''
elif tag_val[0] == u'#Speed': elif tag_val[0] == u'#Speed':
pass pass
elif tag_val[0] == u'Tempo': elif tag_val[0] == u'Tempo':
@ -269,7 +269,7 @@ class SongBeamerImport(SongImport):
# TODO: add the verse order. # TODO: add the verse order.
pass pass
def check_verse_marks(self, line): def checkVerseMarks(self, line):
""" """
Check and add the verse's MarkType. Returns ``True`` if the given line Check and add the verse's MarkType. Returns ``True`` if the given line
contains a correct verse mark otherwise ``False``. contains a correct verse mark otherwise ``False``.
@ -279,10 +279,10 @@ class SongBeamerImport(SongImport):
""" """
marks = line.split(u' ') marks = line.split(u' ')
if len(marks) <= 2 and marks[0] in SongBeamerTypes.MarkTypes: if len(marks) <= 2 and marks[0] in SongBeamerTypes.MarkTypes:
self.current_verse_type = SongBeamerTypes.MarkTypes[marks[0]] self.currentVerseType = SongBeamerTypes.MarkTypes[marks[0]]
if len(marks) == 2: if len(marks) == 2:
# If we have a digit, we append it to current_verse_type. # If we have a digit, we append it to current_verse_type.
if marks[1].isdigit(): if marks[1].isdigit():
self.current_verse_type += marks[1] self.currentVerseType += marks[1]
return True return True
return False return False