This commit is contained in:
Jonathan Corwin 2010-07-05 23:07:44 +01:00
commit 70dbd2c718
33 changed files with 340 additions and 334 deletions

View File

@ -60,18 +60,6 @@
.. autoclass:: openlp.core.lib.settingstab.SettingsTab .. autoclass:: openlp.core.lib.settingstab.SettingsTab
:members: :members:
:mod:`SongXMLBuilder`
---------------------
.. autoclass:: openlp.core.lib.songxmlhandler.SongXMLBuilder
:members:
:mod:`SongXMLParser`
--------------------
.. autoclass:: openlp.core.lib.songxmlhandler.SongXMLParser
:members:
:mod:`ThemeXML` :mod:`ThemeXML`
--------------- ---------------
@ -83,10 +71,3 @@
.. autoclass:: openlp.core.lib.toolbar.OpenLPToolbar .. autoclass:: openlp.core.lib.toolbar.OpenLPToolbar
:members: :members:
:mod:`XmlRootClass`
-------------------
.. autoclass:: openlp.core.lib.xmlrootclass.XmlRootClass
:members:

View File

@ -202,28 +202,17 @@ def check_item_selected(list_widget, message):
return False return False
return True return True
class ThemeLevel(object):
"""
Provides an enumeration for the level a theme applies to
"""
Global = 1
Service = 2
Song = 3
from eventreceiver import Receiver from eventreceiver import Receiver
from settingsmanager import SettingsManager from settingsmanager import SettingsManager
from plugin import PluginStatus, Plugin from plugin import PluginStatus, Plugin
from pluginmanager import PluginManager from pluginmanager import PluginManager
from settingstab import SettingsTab from settingstab import SettingsTab
from xmlrootclass import XmlRootClass
from serviceitem import ServiceItem from serviceitem import ServiceItem
from serviceitem import ServiceItemType from serviceitem import ServiceItemType
from serviceitem import ItemCapabilities from serviceitem import ItemCapabilities
from toolbar import OpenLPToolbar from toolbar import OpenLPToolbar
from dockwidget import OpenLPDockWidget from dockwidget import OpenLPDockWidget
from songxmlhandler import SongXMLBuilder, SongXMLParser from theme import ThemeLevel, ThemeXML
from themexmlhandler import ThemeXML
from renderer import Renderer from renderer import Renderer
from rendermanager import RenderManager from rendermanager import RenderManager
from mediamanageritem import MediaManagerItem from mediamanageritem import MediaManagerItem

View File

@ -189,7 +189,7 @@ class Manager(object):
Any parameters to order the returned objects by. Defaults to None. Any parameters to order the returned objects by. Defaults to None.
""" """
query = self.session.query(object_class) query = self.session.query(object_class)
if order_by_ref: if order_by_ref is not None:
return query.order_by(order_by_ref).all() return query.order_by(order_by_ref).all()
return query.all() return query.all()
@ -208,7 +208,7 @@ class Manager(object):
Any parameters to order the returned objects by. Defaults to None. Any parameters to order the returned objects by. Defaults to None.
""" """
query = self.session.query(object_class).filter(filter_clause) query = self.session.query(object_class).filter(filter_clause)
if order_by_ref: if order_by_ref is not None:
return query.order_by(order_by_ref).all() return query.order_by(order_by_ref).all()
return query.all() return query.all()

View File

@ -67,23 +67,23 @@ class Plugin(QtCore.QObject):
**Hook Functions** **Hook Functions**
``check_pre_conditions()`` ``checkPreConditions()``
Provides the Plugin with a handle to check if it can be loaded. Provides the Plugin with a handle to check if it can be loaded.
``get_media_manager_item()`` ``getMediaManagerItem()``
Returns an instance of MediaManagerItem to be used in the Media Manager. Returns an instance of MediaManagerItem to be used in the Media Manager.
``add_import_menu_item(import_menu)`` ``addImportMenuItem(import_menu)``
Add an item to the Import menu. Add an item to the Import menu.
``add_export_menu_item(export_menu)`` ``addExportMenuItem(export_menu)``
Add an item to the Export menu. Add an item to the Export menu.
``get_settings_tab()`` ``getSettingsTab()``
Returns an instance of SettingsTabItem to be used in the Settings Returns an instance of SettingsTabItem to be used in the Settings
dialog. dialog.
``add_to_menu(menubar)`` ``addToMenu(menubar)``
A method to add a menu item to anywhere in the menu, given the menu bar. A method to add a menu item to anywhere in the menu, given the menu bar.
``handle_event(event)`` ``handle_event(event)``
@ -134,9 +134,9 @@ class Plugin(QtCore.QObject):
self.pluginManager = plugin_helpers[u'pluginmanager'] self.pluginManager = plugin_helpers[u'pluginmanager']
QtCore.QObject.connect(Receiver.get_receiver(), QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'%s_add_service_item' % self.name), QtCore.SIGNAL(u'%s_add_service_item' % self.name),
self.process_add_service_event) self.processAddServiceEvent)
def check_pre_conditions(self): def checkPreConditions(self):
""" """
Provides the Plugin with a handle to check if it can be loaded. Provides the Plugin with a handle to check if it can be loaded.
Failing Preconditions does not stop a settings Tab being created Failing Preconditions does not stop a settings Tab being created
@ -145,7 +145,7 @@ class Plugin(QtCore.QObject):
""" """
return True return True
def set_status(self): def setStatus(self):
""" """
Sets the status of the plugin Sets the status of the plugin
""" """
@ -153,7 +153,7 @@ class Plugin(QtCore.QObject):
self.settingsSection + u'/status', self.settingsSection + u'/status',
QtCore.QVariant(PluginStatus.Inactive)).toInt()[0] QtCore.QVariant(PluginStatus.Inactive)).toInt()[0]
def toggle_status(self, new_status): def toggleStatus(self, new_status):
""" """
Changes the status of the plugin and remembers it Changes the status of the plugin and remembers it
""" """
@ -161,7 +161,7 @@ class Plugin(QtCore.QObject):
QtCore.QSettings().setValue( QtCore.QSettings().setValue(
self.settingsSection + u'/status', QtCore.QVariant(self.status)) self.settingsSection + u'/status', QtCore.QVariant(self.status))
def is_active(self): def isActive(self):
""" """
Indicates if the plugin is active Indicates if the plugin is active
@ -169,14 +169,14 @@ class Plugin(QtCore.QObject):
""" """
return self.status == PluginStatus.Active return self.status == PluginStatus.Active
def get_media_manager_item(self): def getMediaManagerItem(self):
""" """
Construct a MediaManagerItem object with all the buttons and things Construct a MediaManagerItem object with all the buttons and things
you need, and return it for integration into openlp.org. you need, and return it for integration into openlp.org.
""" """
pass pass
def add_import_menu_item(self, importMenu): def addImportMenuItem(self, importMenu):
""" """
Create a menu item and add it to the "Import" menu. Create a menu item and add it to the "Import" menu.
@ -185,7 +185,7 @@ class Plugin(QtCore.QObject):
""" """
pass pass
def add_export_menu_item(self, exportMenu): def addExportMenuItem(self, exportMenu):
""" """
Create a menu item and add it to the "Export" menu. Create a menu item and add it to the "Export" menu.
@ -194,7 +194,7 @@ class Plugin(QtCore.QObject):
""" """
pass pass
def add_tools_menu_item(self, toolsMenu): def addToolsMenuItem(self, toolsMenu):
""" """
Create a menu item and add it to the "Tools" menu. Create a menu item and add it to the "Tools" menu.
@ -203,13 +203,13 @@ class Plugin(QtCore.QObject):
""" """
pass pass
def get_settings_tab(self): def getSettingsTab(self):
""" """
Create a tab for the settings window. Create a tab for the settings window.
""" """
pass pass
def add_to_menu(self, menubar): def addToMenu(self, menubar):
""" """
Add menu items to the menu, given the menubar. Add menu items to the menu, given the menubar.
@ -218,11 +218,11 @@ class Plugin(QtCore.QObject):
""" """
pass pass
def process_add_service_event(self, replace=False): def processAddServiceEvent(self, replace=False):
""" """
Generic Drag and drop handler triggered from service_manager. Generic Drag and drop handler triggered from service_manager.
""" """
log.debug(u'process_add_service_event event called for plugin %s' % log.debug(u'processAddServiceEvent event called for plugin %s' %
self.name) self.name)
if replace: if replace:
self.mediaItem.onAddEditClick() self.mediaItem.onAddEditClick()
@ -243,15 +243,15 @@ class Plugin(QtCore.QObject):
""" """
if self.mediaItem: if self.mediaItem:
self.mediaItem.initialise() self.mediaItem.initialise()
self.insert_toolbox_item() self.insertToolboxItem()
def finalise(self): def finalise(self):
""" """
Called by the plugin Manager to cleanup things. Called by the plugin Manager to cleanup things.
""" """
self.remove_toolbox_item() self.removeToolboxItem()
def remove_toolbox_item(self): def removeToolboxItem(self):
""" """
Called by the plugin to remove toolbar Called by the plugin to remove toolbar
""" """
@ -260,7 +260,7 @@ class Plugin(QtCore.QObject):
if self.settings_tab: if self.settings_tab:
self.settingsForm.removeTab(self.name) self.settingsForm.removeTab(self.name)
def insert_toolbox_item(self): def insertToolboxItem(self):
""" """
Called by plugin to replace toolbar Called by plugin to replace toolbar
""" """
@ -269,7 +269,7 @@ class Plugin(QtCore.QObject):
if self.settings_tab: if self.settings_tab:
self.settingsForm.insertTab(self.settings_tab, self.weight) self.settingsForm.insertTab(self.settings_tab, self.weight)
def can_delete_theme(self, theme): def canDeleteTheme(self, theme):
""" """
Called to ask the plugin if a theme can be deleted Called to ask the plugin if a theme can be deleted
""" """

View File

@ -109,9 +109,9 @@ class PluginManager(object):
log.exception(u'loaded plugin %s has no helpers', unicode(p)) log.exception(u'loaded plugin %s has no helpers', unicode(p))
plugins_list = sorted(plugin_objects, self.order_by_weight) plugins_list = sorted(plugin_objects, self.order_by_weight)
for plugin in plugins_list: for plugin in plugins_list:
if plugin.check_pre_conditions(): if plugin.checkPreConditions():
log.debug(u'Plugin %s active', unicode(plugin.name)) log.debug(u'Plugin %s active', unicode(plugin.name))
plugin.set_status() plugin.setStatus()
else: else:
plugin.status = PluginStatus.Disabled plugin.status = PluginStatus.Disabled
self.plugins.append(plugin) self.plugins.append(plugin)
@ -138,7 +138,7 @@ class PluginManager(object):
""" """
for plugin in self.plugins: for plugin in self.plugins:
if plugin.status is not PluginStatus.Disabled: if plugin.status is not PluginStatus.Disabled:
plugin.mediaItem = plugin.get_media_manager_item() plugin.mediaItem = plugin.getMediaManagerItem()
def hook_settings_tabs(self, settingsform=None): def hook_settings_tabs(self, settingsform=None):
""" """
@ -151,7 +151,7 @@ class PluginManager(object):
""" """
for plugin in self.plugins: for plugin in self.plugins:
if plugin.status is not PluginStatus.Disabled: if plugin.status is not PluginStatus.Disabled:
plugin.settings_tab = plugin.get_settings_tab() plugin.settings_tab = plugin.getSettingsTab()
if plugin.settings_tab: if plugin.settings_tab:
log.debug(u'Inserting settings tab item from %s' % log.debug(u'Inserting settings tab item from %s' %
plugin.name) plugin.name)
@ -169,7 +169,7 @@ class PluginManager(object):
""" """
for plugin in self.plugins: for plugin in self.plugins:
if plugin.status is not PluginStatus.Disabled: if plugin.status is not PluginStatus.Disabled:
plugin.add_import_menu_item(import_menu) plugin.addImportMenuItem(import_menu)
def hook_export_menu(self, export_menu): def hook_export_menu(self, export_menu):
""" """
@ -181,7 +181,7 @@ class PluginManager(object):
""" """
for plugin in self.plugins: for plugin in self.plugins:
if plugin.status is not PluginStatus.Disabled: if plugin.status is not PluginStatus.Disabled:
plugin.add_export_menu_item(export_menu) plugin.addExportMenuItem(export_menu)
def hook_tools_menu(self, tools_menu): def hook_tools_menu(self, tools_menu):
""" """
@ -193,7 +193,7 @@ class PluginManager(object):
""" """
for plugin in self.plugins: for plugin in self.plugins:
if plugin.status is not PluginStatus.Disabled: if plugin.status is not PluginStatus.Disabled:
plugin.add_tools_menu_item(tools_menu) plugin.addToolsMenuItem(tools_menu)
def initialise_plugins(self): def initialise_plugins(self):
""" """
@ -202,12 +202,12 @@ class PluginManager(object):
""" """
for plugin in self.plugins: for plugin in self.plugins:
log.info(u'initialising plugins %s in a %s state' log.info(u'initialising plugins %s in a %s state'
% (plugin.name, plugin.is_active())) % (plugin.name, plugin.isActive()))
if plugin.is_active(): if plugin.isActive():
plugin.initialise() plugin.initialise()
log.info(u'Initialisation Complete for %s ' % plugin.name) log.info(u'Initialisation Complete for %s ' % plugin.name)
if not plugin.is_active(): if not plugin.isActive():
plugin.remove_toolbox_item() plugin.removeToolboxItem()
def finalise_plugins(self): def finalise_plugins(self):
""" """
@ -216,7 +216,6 @@ class PluginManager(object):
""" """
log.info(u'finalising plugins') log.info(u'finalising plugins')
for plugin in self.plugins: for plugin in self.plugins:
if plugin.is_active(): if plugin.isActive():
plugin.finalise() plugin.finalise()
log.info(u'Finalisation Complete for %s ' % plugin.name) log.info(u'Finalisation Complete for %s ' % plugin.name)

View File

@ -29,6 +29,7 @@ format it for the output display.
import logging import logging
from PyQt4 import QtGui, QtCore from PyQt4 import QtGui, QtCore
from openlp.core.lib import resize_image from openlp.core.lib import resize_image
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View File

@ -27,8 +27,7 @@ import logging
from PyQt4 import QtCore from PyQt4 import QtCore
from renderer import Renderer from openlp.core.lib import Renderer, ThemeLevel
from openlp.core.lib import ThemeLevel
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View File

@ -79,6 +79,14 @@ BLANK_THEME_XML = \
</theme> </theme>
''' '''
class ThemeLevel(object):
"""
Provides an enumeration for the level a theme applies to
"""
Global = 1
Service = 2
Song = 3
class ThemeXML(object): class ThemeXML(object):
""" """
A class to encapsulate the Theme XML. A class to encapsulate the Theme XML.
@ -313,7 +321,6 @@ class ThemeXML(object):
element.appendChild(value) element.appendChild(value)
background.appendChild(element) background.appendChild(element)
def child_element(self, element, tag, value): def child_element(self, element, tag, value):
""" """
Generic child element creator. Generic child element creator.
@ -351,14 +358,8 @@ class ThemeXML(object):
``xml`` ``xml``
The XML string to parse. The XML string to parse.
""" """
self.base_parse_xml()
self.parse_xml(xml)
def base_parse_xml(self):
"""
Pull in the blank theme XML as a starting point.
"""
self.parse_xml(BLANK_THEME_XML) self.parse_xml(BLANK_THEME_XML)
self.parse_xml(xml)
def parse_xml(self, xml): def parse_xml(self, xml):
""" """
@ -414,4 +415,3 @@ class ThemeXML(object):
if key[0:1] != u'_': if key[0:1] != u'_':
theme_strings.append(u'%30s: %s' % (key, getattr(self, key))) theme_strings.append(u'%30s: %s' % (key, getattr(self, key)))
return u'\n'.join(theme_strings) return u'\n'.join(theme_strings)

View File

@ -1,104 +0,0 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
# Copyright (c) 2008-2010 Raoul Snyman #
# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael #
# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin #
# Thompson, Jon Tibble, Carsten Tinggaard #
# --------------------------------------------------------------------------- #
# 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; version 2 of the License. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
import os
import sys
from xml.etree.ElementTree import ElementTree, XML
sys.path.append(os.path.abspath(os.path.join(u'.', u'..', u'..')))
class XmlRootClass(object):
"""
Root class for themes, songs etc
This class provides interface for parsing xml files into object attributes.
If you overload this class and provide a function called `post_tag_hook`,
it will be called thusly for each `tag, value` pair::
(element.tag, val) = self.post_tag_hook(element.tag, val)
"""
def _set_from_xml(self, xml, root_tag):
"""
Set song properties from given xml content.
``xml``
Formatted xml tags and values.
``root_tag``
The root tag of the xml.
"""
root = ElementTree(element=XML(xml))
xml_iter = root.getiterator()
for element in xml_iter:
if element.tag != root_tag:
text = element.text
if text is None:
val = text
elif isinstance(text, basestring):
# Strings need special handling to sort the colours out
if text[0] == u'$':
# This might be a hex number, let's try to convert it.
try:
val = int(text[1:], 16)
except ValueError:
pass
else:
# Let's just see if it's a integer.
try:
val = int(text)
except ValueError:
# Ok, it seems to be a string.
val = text
if hasattr(self, u'post_tag_hook'):
(element.tag, val) = \
self.post_tag_hook(element.tag, val)
setattr(self, element.tag, val)
def __str__(self):
"""
Return string with all public attributes
The string is formatted with one attribute per line
If the string is split on newline then the length of the
list is equal to the number of attributes
"""
attributes = []
for attrib in dir(self):
if not attrib.startswith(u'_'):
attributes.append(
u'%30s : %s' % (attrib, getattr(self, attrib)))
return u'\n'.join(attributes)
def _get_as_string(self):
"""
Return one string with all public attributes
"""
result = u''
for attrib in dir(self):
if not attrib.startswith(u'_'):
result += u'_%s_' % getattr(self, attrib)
return result

View File

@ -222,4 +222,3 @@ class Theme(object):
if key[0:1] != u'_': if key[0:1] != u'_':
theme_strings.append(u'%30s : %s' % (key, getattr(self, key))) theme_strings.append(u'%30s : %s' % (key, getattr(self, key)))
return u'\n'.join(theme_strings) return u'\n'.join(theme_strings)

View File

@ -35,14 +35,15 @@ from openlp.core.ui import HideMode
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
HTMLIMAGE = """<html>
<body>
<img src=\"file://%s\" alt\"Hello\">
</body></html>
"""
#http://www.steveheffernan.com/html5-video-player/demo-video-player.html #http://www.steveheffernan.com/html5-video-player/demo-video-player.html
HTMLVIDEO = u"""<html> HTMLVIDEO = u"""<html>
<head>
<style>
*{
margin: 0;
padding:0
}
</style>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
var video; var video;
var bodyLoaded = function(){ var bodyLoaded = function(){
@ -50,11 +51,10 @@ HTMLVIDEO = u"""<html>
video.volume = 0; video.volume = 0;
} }
</script> </script>
<body id=\"body\" onload=\"bodyLoaded();>\" </head>
<video id=\"video\" src=\"%s\" <body id="body" onload="bodyLoaded();">
autoplay loop width=%s height=%s autobuffer=\"autobuffer\" preload > <video id="video" src="%s" autoplay="autoplay" loop="loop"
your browser does not support the video tag width="%s" height="%s" autobuffer="autobuffer" preload="preload" />
</video>
</body></html> </body></html>
""" """

View File

@ -115,10 +115,10 @@ class PluginForm(QtGui.QDialog, Ui_PluginViewDialog):
if self.programaticChange: if self.programaticChange:
return return
if status == 0: if status == 0:
self.activePlugin.toggle_status(PluginStatus.Active) self.activePlugin.toggleStatus(PluginStatus.Active)
self.activePlugin.initialise() self.activePlugin.initialise()
else: else:
self.activePlugin.toggle_status(PluginStatus.Inactive) self.activePlugin.toggleStatus(PluginStatus.Inactive)
self.activePlugin.finalise() self.activePlugin.finalise()
status_text = 'Inactive' status_text = 'Inactive'
if self.activePlugin.status == PluginStatus.Active: if self.activePlugin.status == PluginStatus.Active:

View File

@ -212,7 +212,7 @@ class ThemeManager(QtGui.QWidget):
QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok)) QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok))
else: else:
for plugin in self.parent.plugin_manager.plugins: for plugin in self.parent.plugin_manager.plugins:
if not plugin.can_delete_theme(theme): if not plugin.canDeleteTheme(theme):
QtGui.QMessageBox.critical(self, QtGui.QMessageBox.critical(self,
translate('ThemeManager', 'Error'), translate('ThemeManager', 'Error'),
unicode(translate('ThemeManager', unicode(translate('ThemeManager',
@ -682,4 +682,3 @@ class ThemeManager(QtGui.QWidget):
#theme.theme_mode #theme.theme_mode
theme.theme_name = theme.theme_name.strip() theme.theme_name = theme.theme_name.strip()
#theme.theme_version #theme.theme_version

View File

@ -47,14 +47,14 @@ class alertsPlugin(Plugin):
self.alertForm = AlertForm(self.manager, self) self.alertForm = AlertForm(self.manager, self)
self.status = PluginStatus.Active self.status = PluginStatus.Active
def get_settings_tab(self): def getSettingsTab(self):
""" """
Return the settings tab for the Alerts plugin Return the settings tab for the Alerts plugin
""" """
self.alertsTab = AlertsTab(self) self.alertsTab = AlertsTab(self)
return self.alertsTab return self.alertsTab
def add_tools_menu_item(self, tools_menu): def addToolsMenuItem(self, tools_menu):
""" """
Give the alerts plugin the opportunity to add items to the Give the alerts plugin the opportunity to add items to the
**Tools** menu. **Tools** menu.

View File

@ -57,14 +57,14 @@ class BiblePlugin(Plugin):
self.ImportBibleItem.setVisible(False) self.ImportBibleItem.setVisible(False)
self.ExportBibleItem.setVisible(False) self.ExportBibleItem.setVisible(False)
def get_settings_tab(self): def getSettingsTab(self):
return BiblesTab(self.name) return BiblesTab(self.name)
def get_media_manager_item(self): def getMediaManagerItem(self):
# Create the BibleManagerItem object # Create the BibleManagerItem object
return BibleMediaItem(self, self.icon, self.name) return BibleMediaItem(self, self.icon, self.name)
def add_import_menu_item(self, import_menu): def addImportMenuItem(self, import_menu):
self.ImportBibleItem = QtGui.QAction(import_menu) self.ImportBibleItem = QtGui.QAction(import_menu)
self.ImportBibleItem.setObjectName(u'ImportBibleItem') self.ImportBibleItem.setObjectName(u'ImportBibleItem')
import_menu.addAction(self.ImportBibleItem) import_menu.addAction(self.ImportBibleItem)
@ -75,7 +75,7 @@ class BiblePlugin(Plugin):
QtCore.SIGNAL(u'triggered()'), self.onBibleImportClick) QtCore.SIGNAL(u'triggered()'), self.onBibleImportClick)
self.ImportBibleItem.setVisible(False) self.ImportBibleItem.setVisible(False)
def add_export_menu_item(self, export_menu): def addExportMenuItem(self, export_menu):
self.ExportBibleItem = QtGui.QAction(export_menu) self.ExportBibleItem = QtGui.QAction(export_menu)
self.ExportBibleItem.setObjectName(u'ExportBibleItem') self.ExportBibleItem.setObjectName(u'ExportBibleItem')
export_menu.addAction(self.ExportBibleItem) export_menu.addAction(self.ExportBibleItem)
@ -94,7 +94,7 @@ class BiblePlugin(Plugin):
'displayed on the screen during the service.') 'displayed on the screen during the service.')
return about_text return about_text
def can_delete_theme(self, theme): def canDeleteTheme(self, theme):
if self.settings_tab.bible_theme == theme: if self.settings_tab.bible_theme == theme:
return False return False
return True return True

View File

@ -53,10 +53,10 @@ class CustomPlugin(Plugin):
self.icon = build_icon(u':/plugins/plugin_custom.png') self.icon = build_icon(u':/plugins/plugin_custom.png')
self.status = PluginStatus.Active self.status = PluginStatus.Active
def get_settings_tab(self): def getSettingsTab(self):
return CustomTab(self.name) return CustomTab(self.name)
def get_media_manager_item(self): def getMediaManagerItem(self):
# Create the CustomManagerItem object # Create the CustomManagerItem object
return CustomMediaItem(self, self.icon, self.name) return CustomMediaItem(self, self.icon, self.name)
@ -68,7 +68,7 @@ class CustomPlugin(Plugin):
'songs plugin.<br>') 'songs plugin.<br>')
return about_text return about_text
def can_delete_theme(self, theme): def canDeleteTheme(self, theme):
if not self.custommanager.get_all_objects_filtered(CustomSlide, if not self.custommanager.get_all_objects_filtered(CustomSlide,
CustomSlide.theme_name == theme): CustomSlide.theme_name == theme):
return True return True

View File

@ -28,7 +28,8 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from editcustomdialog import Ui_customEditDialog from editcustomdialog import Ui_customEditDialog
from openlp.core.lib import SongXMLBuilder, SongXMLParser, Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.plugins.custom.lib import CustomXMLBuilder, CustomXMLParser
from openlp.plugins.custom.lib.db import CustomSlide from openlp.plugins.custom.lib.db import CustomSlide
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -119,8 +120,8 @@ class EditCustomForm(QtGui.QDialog, Ui_customEditDialog):
self.customSlide = self.custommanager.get_object(CustomSlide, id) self.customSlide = self.custommanager.get_object(CustomSlide, id)
self.TitleEdit.setText(self.customSlide.title) self.TitleEdit.setText(self.customSlide.title)
self.CreditEdit.setText(self.customSlide.credits) self.CreditEdit.setText(self.customSlide.credits)
songXML = SongXMLParser(self.customSlide.text) customXML = CustomXMLParser(self.customSlide.text)
verseList = songXML.get_verses() verseList = customXML.get_verses()
for verse in verseList: for verse in verseList:
self.VerseListView.addItem(verse[1]) self.VerseListView.addItem(verse[1])
theme = self.customSlide.theme_name theme = self.customSlide.theme_name
@ -152,7 +153,7 @@ class EditCustomForm(QtGui.QDialog, Ui_customEditDialog):
translate('CustomPlugin.EditCustomForm', 'Error'), message, translate('CustomPlugin.EditCustomForm', 'Error'), message,
QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok)) QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok))
return False return False
sxml = SongXMLBuilder() sxml = CustomXMLBuilder()
sxml.new_document() sxml.new_document()
sxml.add_lyrics_to_song() sxml.add_lyrics_to_song()
count = 1 count = 1

View File

@ -23,5 +23,6 @@
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
from customxmlhandler import CustomXMLBuilder, CustomXMLParser
from mediaitem import CustomMediaItem from mediaitem import CustomMediaItem
from customtab import CustomTab from customtab import CustomTab

View File

@ -23,7 +23,8 @@
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
""" """
The :mod:`songxmlhandler` module provides the XML functionality for songs The :mod:`customxmlhandler` module provides the XML functionality for custom
slides
The basic XML is of the format:: The basic XML is of the format::
@ -45,26 +46,26 @@ from xml.parsers.expat import ExpatError
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class SongXMLBuilder(object): class CustomXMLBuilder(object):
""" """
This class builds the XML used to describe songs. This class builds the XML used to describe songs.
""" """
log.info(u'SongXMLBuilder Loaded') log.info(u'CustomXMLBuilder Loaded')
def __init__(self): def __init__(self):
""" """
Set up the song builder. Set up the song builder.
""" """
# Create the minidom document # Create the minidom document
self.song_xml = Document() self.custom_xml = Document()
def new_document(self): def new_document(self):
""" """
Create a new song XML document. Create a new song XML document.
""" """
# Create the <song> base element # Create the <song> base element
self.song = self.song_xml.createElement(u'song') self.song = self.custom_xml.createElement(u'song')
self.song_xml.appendChild(self.song) self.custom_xml.appendChild(self.song)
self.song.setAttribute(u'version', u'1.0') self.song.setAttribute(u'version', u'1.0')
def add_lyrics_to_song(self): def add_lyrics_to_song(self):
@ -73,7 +74,7 @@ class SongXMLBuilder(object):
song. song.
""" """
# Create the main <lyrics> element # Create the main <lyrics> element
self.lyrics = self.song_xml.createElement(u'lyrics') self.lyrics = self.custom_xml.createElement(u'lyrics')
self.lyrics.setAttribute(u'language', u'en') self.lyrics.setAttribute(u'language', u'en')
self.song.appendChild(self.lyrics) self.song.appendChild(self.lyrics)
@ -92,32 +93,32 @@ class SongXMLBuilder(object):
The actual text of the verse to be stored. The actual text of the verse to be stored.
""" """
#log.debug(u'add_verse_to_lyrics %s, %s\n%s' % (type, number, content)) #log.debug(u'add_verse_to_lyrics %s, %s\n%s' % (type, number, content))
verse = self.song_xml.createElement(u'verse') verse = self.custom_xml.createElement(u'verse')
verse.setAttribute(u'type', type) verse.setAttribute(u'type', type)
verse.setAttribute(u'label', number) verse.setAttribute(u'label', number)
self.lyrics.appendChild(verse) self.lyrics.appendChild(verse)
# add data as a CDATA section to protect the XML from special chars # add data as a CDATA section to protect the XML from special chars
cds = self.song_xml.createCDATASection(content) cds = self.custom_xml.createCDATASection(content)
verse.appendChild(cds) verse.appendChild(cds)
def dump_xml(self): def dump_xml(self):
""" """
Debugging aid to dump XML so that we can see what we have. Debugging aid to dump XML so that we can see what we have.
""" """
return self.song_xml.toprettyxml(indent=u' ') return self.custom_xml.toprettyxml(indent=u' ')
def extract_xml(self): def extract_xml(self):
""" """
Extract our newly created XML song. Extract our newly created XML song.
""" """
return self.song_xml.toxml(u'utf-8') return self.custom_xml.toxml(u'utf-8')
class SongXMLParser(object): class CustomXMLParser(object):
""" """
A class to read in and parse a song's XML. A class to read in and parse a song's XML.
""" """
log.info(u'SongXMLParser Loaded') log.info(u'CustomXMLParser Loaded')
def __init__(self, xml): def __init__(self, xml):
""" """
@ -126,9 +127,9 @@ class SongXMLParser(object):
``xml`` ``xml``
The XML of the song to be parsed. The XML of the song to be parsed.
""" """
self.song_xml = None self.custom_xml = None
try: try:
self.song_xml = ElementTree( self.custom_xml = ElementTree(
element=XML(unicode(xml).encode('unicode-escape'))) element=XML(unicode(xml).encode('unicode-escape')))
except ExpatError: except ExpatError:
log.exception(u'Invalid xml %s', xml) log.exception(u'Invalid xml %s', xml)
@ -138,7 +139,7 @@ class SongXMLParser(object):
Iterates through the verses in the XML and returns a list of verses Iterates through the verses in the XML and returns a list of verses
and their attributes. and their attributes.
""" """
xml_iter = self.song_xml.getiterator() xml_iter = self.custom_xml.getiterator()
verse_list = [] verse_list = []
for element in xml_iter: for element in xml_iter:
if element.tag == u'verse': if element.tag == u'verse':
@ -152,4 +153,4 @@ class SongXMLParser(object):
""" """
Debugging aid to dump XML so that we can see what we have. Debugging aid to dump XML so that we can see what we have.
""" """
return dump(self.song_xml) return dump(self.custom_xml)

View File

@ -27,8 +27,9 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import MediaManagerItem, SongXMLParser, BaseListWithDnD, \ from openlp.core.lib import MediaManagerItem, BaseListWithDnD, \
Receiver, ItemCapabilities, translate, check_item_selected Receiver, ItemCapabilities, translate, check_item_selected
from openlp.plugins.custom.lib import CustomXMLParser
from openlp.plugins.custom.lib.db import CustomSlide from openlp.plugins.custom.lib.db import CustomSlide
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -170,8 +171,8 @@ class CustomMediaItem(MediaManagerItem):
theme = customSlide.theme_name theme = customSlide.theme_name
if theme: if theme:
service_item.theme = theme service_item.theme = theme
songXML = SongXMLParser(customSlide.text) customXML = CustomXMLParser(customSlide.text)
verseList = songXML.get_verses() verseList = customXML.get_verses()
for verse in verseList: for verse in verseList:
raw_slides.append(verse[1]) raw_slides.append(verse[1])
service_item.title = title service_item.title = title

View File

@ -39,10 +39,10 @@ class ImagePlugin(Plugin):
self.icon = build_icon(u':/plugins/plugin_images.png') self.icon = build_icon(u':/plugins/plugin_images.png')
self.status = PluginStatus.Active self.status = PluginStatus.Active
def get_settings_tab(self): def getSettingsTab(self):
return ImageTab(self.name) return ImageTab(self.name)
def get_media_manager_item(self): def getMediaManagerItem(self):
# Create the MediaManagerItem object # Create the MediaManagerItem object
return ImageMediaItem(self, self.icon, self.name) return ImageMediaItem(self, self.icon, self.name)

View File

@ -47,19 +47,19 @@ class MediaPlugin(Plugin):
for mimetype in Phonon.BackendCapabilities.availableMimeTypes(): for mimetype in Phonon.BackendCapabilities.availableMimeTypes():
mimetype = unicode(mimetype) mimetype = unicode(mimetype)
type = mimetype.split(u'audio/x-') type = mimetype.split(u'audio/x-')
self.audio_list, mimetype = self._add_to_list(self.audio_list, self.audio_list, mimetype = self._addToList(self.audio_list,
type, mimetype) type, mimetype)
type = mimetype.split(u'audio/') type = mimetype.split(u'audio/')
self.audio_list, mimetype = self._add_to_list(self.audio_list, self.audio_list, mimetype = self._addToList(self.audio_list,
type, mimetype) type, mimetype)
type = mimetype.split(u'video/x-') type = mimetype.split(u'video/x-')
self.video_list, mimetype = self._add_to_list(self.video_list, self.video_list, mimetype = self._addToList(self.video_list,
type, mimetype) type, mimetype)
type = mimetype.split(u'video/') type = mimetype.split(u'video/')
self.video_list, mimetype = self._add_to_list(self.video_list, self.video_list, mimetype = self._addToList(self.video_list,
type, mimetype) type, mimetype)
def _add_to_list(self, list, value, type): def _addToList(self, list, value, type):
if len(value) == 2: if len(value) == 2:
if list.find(value[1]) == -1: if list.find(value[1]) == -1:
list += u'*.%s ' % value[1] list += u'*.%s ' % value[1]
@ -67,7 +67,7 @@ class MediaPlugin(Plugin):
type = u'' type = u''
return list, type return list, type
def get_media_manager_item(self): def getMediaManagerItem(self):
# Create the MediaManagerItem object # Create the MediaManagerItem object
return MediaMediaItem(self, self.icon, self.name) return MediaMediaItem(self, self.icon, self.name)

View File

@ -173,7 +173,7 @@ class PowerpointDocument(PresentationDocument):
return True return True
def is_active(self): def isActive(self):
""" """
Returns true if a presentation is currently active Returns true if a presentation is currently active
""" """
@ -206,7 +206,7 @@ class PowerpointDocument(PresentationDocument):
""" """
Returns true if screen is blank Returns true if screen is blank
""" """
if self.is_active(): if self.isActive():
return self.presentation.SlideShowWindow.View.State == 3 return self.presentation.SlideShowWindow.View.State == 3
else: else:
return False return False

View File

@ -43,7 +43,7 @@ class PresentationPlugin(Plugin):
self.icon = build_icon(u':/plugins/plugin_presentations.png') self.icon = build_icon(u':/plugins/plugin_presentations.png')
self.status = PluginStatus.Active self.status = PluginStatus.Active
def get_settings_tab(self): def getSettingsTab(self):
""" """
Create the settings Tab Create the settings Tab
""" """
@ -52,7 +52,7 @@ class PresentationPlugin(Plugin):
def initialise(self): def initialise(self):
log.info(u'Presentations Initialising') log.info(u'Presentations Initialising')
Plugin.initialise(self) Plugin.initialise(self)
self.insert_toolbox_item() self.insertToolboxItem()
for controller in self.controllers: for controller in self.controllers:
if self.controllers[controller].enabled: if self.controllers[controller].enabled:
self.controllers[controller].start_process() self.controllers[controller].start_process()
@ -66,7 +66,7 @@ class PresentationPlugin(Plugin):
controller.kill() controller.kill()
Plugin.finalise(self) Plugin.finalise(self)
def get_media_manager_item(self): def getMediaManagerItem(self):
""" """
Create the Media Manager List Create the Media Manager List
""" """
@ -76,12 +76,12 @@ class PresentationPlugin(Plugin):
def registerControllers(self, controller): def registerControllers(self, controller):
self.controllers[controller.name] = controller self.controllers[controller.name] = controller
def check_pre_conditions(self): def checkPreConditions(self):
""" """
Check to see if we have any presentation software available Check to see if we have any presentation software available
If Not do not install the plugin. If Not do not install the plugin.
""" """
log.debug(u'check_pre_conditions') log.debug(u'checkPreConditions')
controller_dir = os.path.join( controller_dir = os.path.join(
AppLocation.get_directory(AppLocation.PluginsDir), AppLocation.get_directory(AppLocation.PluginsDir),
u'presentations', u'lib') u'presentations', u'lib')

View File

@ -48,7 +48,7 @@ class RemotesPlugin(Plugin):
""" """
log.debug(u'initialise') log.debug(u'initialise')
Plugin.initialise(self) Plugin.initialise(self)
self.insert_toolbox_item() self.insertToolboxItem()
self.server = HttpServer(self) self.server = HttpServer(self)
def finalise(self): def finalise(self):
@ -60,7 +60,7 @@ class RemotesPlugin(Plugin):
if self.server: if self.server:
self.server.close() self.server.close()
def get_settings_tab(self): def getSettingsTab(self):
""" """
Create the settings Tab Create the settings Tab
""" """

View File

@ -28,9 +28,9 @@ import re
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import SongXMLBuilder, SongXMLParser, Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.plugins.songs.forms import EditVerseForm from openlp.plugins.songs.forms import EditVerseForm
from openlp.plugins.songs.lib import VerseType from openlp.plugins.songs.lib import SongXMLBuilder, SongXMLParser, VerseType
from openlp.plugins.songs.lib.db import Book, Song, Author, Topic from openlp.plugins.songs.lib.db import Book, Song, Author, Topic
from editsongdialog import Ui_EditSongDialog from editsongdialog import Ui_EditSongDialog
@ -639,8 +639,6 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
log.debug(u'processLyrics') log.debug(u'processLyrics')
try: try:
sxml = SongXMLBuilder() sxml = SongXMLBuilder()
sxml.new_document()
sxml.add_lyrics_to_song()
text = u'' text = u''
multiple = [] multiple = []
for i in range (0, self.VerseListWidget.rowCount()): for i in range (0, self.VerseListWidget.rowCount()):
@ -666,4 +664,3 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
log.debug(u'processTitle') log.debug(u'processTitle')
self.song.search_title = \ self.song.search_title = \
re.sub(r'[\'"`,;:(){}?]+', u'', unicode(self.song.search_title)) re.sub(r'[\'"`,;:(){}?]+', u'', unicode(self.song.search_title))

View File

@ -137,6 +137,7 @@ class VerseType(object):
unicode(VerseType.to_string(VerseType.Other)).lower(): unicode(VerseType.to_string(VerseType.Other)).lower():
return VerseType.Other return VerseType.Other
from xml import LyricsXML, SongXMLBuilder, SongXMLParser
from songstab import SongsTab from songstab import SongsTab
from mediaitem import SongMediaItem from mediaitem import SongMediaItem
from songimport import SongImport from songimport import SongImport
@ -145,4 +146,3 @@ try:
from oooimport import OooImport from oooimport import OooImport
except ImportError: except ImportError:
pass pass

View File

@ -27,11 +27,12 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import MediaManagerItem, SongXMLParser, \ from openlp.core.lib import MediaManagerItem, BaseListWithDnD, Receiver, \
BaseListWithDnD, Receiver, ItemCapabilities, translate, check_item_selected ItemCapabilities, translate, check_item_selected
from openlp.plugins.songs.forms import EditSongForm, SongMaintenanceForm, \ from openlp.plugins.songs.forms import EditSongForm, SongMaintenanceForm, \
ImportWizardForm ImportWizardForm
from openlp.plugins.songs.lib.db import Song from openlp.plugins.songs.lib import SongXMLParser
from openlp.plugins.songs.lib.db import Author, Song
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View File

@ -25,8 +25,8 @@
import re import re
from openlp.core.lib import SongXMLBuilder, translate from openlp.core.lib import translate
from openlp.plugins.songs.lib import VerseType from openlp.plugins.songs.lib import SongXMLBuilder, VerseType
from openlp.plugins.songs.lib.db import Song, Author, Topic, Book from openlp.plugins.songs.lib.db import Song, Author, Topic, Book
class SongImport(object): class SongImport(object):
@ -276,8 +276,6 @@ class SongImport(object):
song.song_number = self.song_number song.song_number = self.song_number
song.search_lyrics = u'' song.search_lyrics = u''
sxml = SongXMLBuilder() sxml = SongXMLBuilder()
sxml.new_document()
sxml.add_lyrics_to_song()
for (versetag, versetext) in self.verses: for (versetag, versetext) in self.verses:
if versetag[0] == u'C': if versetag[0] == u'C':
versetype = VerseType.to_string(VerseType.Chorus) versetype = VerseType.to_string(VerseType.Chorus)

View File

@ -24,18 +24,18 @@
############################################################################### ###############################################################################
import logging import logging
import sys #import sys
import os #import os
from types import ListType from types import ListType
from xml.etree.ElementTree import ElementTree, XML
sys.path.append(os.path.abspath(u'./../../../..')) # Do we need these two lines?
#sys.path.append(os.path.abspath(u'./../../../..'))
from openlp.core.lib import XmlRootClass #sys.path.append(os.path.abspath(os.path.join(u'.', u'..', u'..')))
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class SongException(Exception): class SongException(Exception):
pass pass
@ -74,23 +74,78 @@ _BLANK_OPENSONG_XML = \
</song> </song>
''' '''
class _OpenSong(XmlRootClass): class _OpenSong(object):
"""Class for import of OpenSong""" """
Class for import of OpenSong
"""
def __init__(self, xmlContent = None): def __init__(self, xmlContent = None):
"""Initialize from given xml content""" """
super(_OpenSong, self).__init__() Initialize from given xml content
self.from_buffer(xmlContent) """
self._set_from_xml(_BLANK_OPENSONG_XML, 'song')
def _reset(self):
"""Reset all song attributes"""
self._setFromXml(_BLANK_OPENSONG_XML, 'song')
def from_buffer(self, xmlContent):
"""Initialize from buffer(string) with xml content"""
self._reset()
if xmlContent: if xmlContent:
self._setFromXml(xmlContent, 'song') self._set_from_xml(xmlContent, 'song')
def _set_from_xml(self, xml, root_tag):
"""
Set song properties from given xml content.
``xml``
Formatted xml tags and values.
``root_tag``
The root tag of the xml.
"""
root = ElementTree(element=XML(xml))
xml_iter = root.getiterator()
for element in xml_iter:
if element.tag != root_tag:
text = element.text
if text is None:
val = text
elif isinstance(text, basestring):
# Strings need special handling to sort the colours out
if text[0] == u'$':
# This might be a hex number, let's try to convert it.
try:
val = int(text[1:], 16)
except ValueError:
pass
else:
# Let's just see if it's a integer.
try:
val = int(text)
except ValueError:
# Ok, it seems to be a string.
val = text
if hasattr(self, u'post_tag_hook'):
(element.tag, val) = \
self.post_tag_hook(element.tag, val)
setattr(self, element.tag, val)
def __str__(self):
"""
Return string with all public attributes
The string is formatted with one attribute per line
If the string is split on newline then the length of the
list is equal to the number of attributes
"""
attributes = []
for attrib in dir(self):
if not attrib.startswith(u'_'):
attributes.append(
u'%30s : %s' % (attrib, getattr(self, attrib)))
return u'\n'.join(attributes)
def _get_as_string(self):
"""
Return one string with all public attributes
"""
result = u''
for attrib in dir(self):
if not attrib.startswith(u'_'):
result += u'_%s_' % getattr(self, attrib)
return result
def get_author_list(self): def get_author_list(self):
"""Convert author field to an authorlist """Convert author field to an authorlist
@ -252,14 +307,6 @@ class Song(object):
self.set_lyrics(u'') self.set_lyrics(u'')
return return
def set_songid(self, songid):
"""Set the songid for the database"""
self.songid = songid
def get_songid(self):
"""Return the songid for the database"""
return self.songid
def from_opensong_buffer(self, xmlcontent): def from_opensong_buffer(self, xmlcontent):
"""Initialize from buffer(string) of xml lines in opensong format""" """Initialize from buffer(string) of xml lines in opensong format"""
self._reset() self._reset()
@ -323,10 +370,6 @@ class Song(object):
"""Return title value""" """Return title value"""
return self.title return self.title
def get_search_title(self):
"""Return search_title"""
return self.search_title
def from_ccli_text_buffer(self, textList): def from_ccli_text_buffer(self, textList):
""" """
Create song from a list of texts (strings) - CCLI text format expected Create song from a list of texts (strings) - CCLI text format expected

View File

@ -22,15 +22,10 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 # # with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
from lxml import objectify
from lxml.etree import XMLSyntaxError
class LyricsXML(object):
""" """
This class represents the XML in the ``lyrics`` field of a song. The :mod:`xml` module provides the XML functionality for songs
The basic XML looks like this:: The basic XML is of the format::
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<song version="1.0"> <song version="1.0">
@ -41,6 +36,112 @@ class LyricsXML(object):
</lyrics> </lyrics>
</song> </song>
""" """
import logging
from lxml import etree, objectify
log = logging.getLogger(__name__)
class SongXMLBuilder(object):
"""
This class builds the XML used to describe songs.
"""
log.info(u'SongXMLBuilder Loaded')
def __init__(self, song_language=None):
"""
Set up the song builder.
``song_language``
The language used in this song
"""
lang = u'en'
if song_language:
lang = song_language
self.song_xml = objectify.fromstring(u'<song version="1.0" />')
self.lyrics = etree.SubElement(self.song_xml, u'lyrics', language=lang)
def add_verse_to_lyrics(self, type, number, content):
"""
Add a verse to the ``<lyrics>`` tag.
``type``
A string denoting the type of verse. Possible values are "Chorus",
"Verse", "Bridge", and "Custom".
``number``
An integer denoting the number of the item, for example: verse 1.
``content``
The actual text of the verse to be stored.
"""
#log.debug(u'add_verse_to_lyrics %s, %s\n%s' % (type, number, content))
verse = etree.Element(u'verse', type=type, label=number)
verse.text = etree.CDATA(content)
self.lyrics.append(verse)
def dump_xml(self):
"""
Debugging aid to dump XML so that we can see what we have.
"""
return etree.tostring(self.song_xml, encoding=u'UTF-8',
xml_declaration=True, pretty_print=True)
def extract_xml(self):
"""
Extract our newly created XML song.
"""
return etree.tostring(self.song_xml, encoding=u'UTF-8',
xml_declaration=True)
class SongXMLParser(object):
"""
A class to read in and parse a song's XML.
"""
log.info(u'SongXMLParser Loaded')
def __init__(self, xml):
"""
Set up our song XML parser.
``xml``
The XML of the song to be parsed.
"""
self.song_xml = None
if xml[:5] == u'<?xml':
xml = xml[38:]
try:
self.song_xml = objectify.fromstring(xml)
except etree.XMLSyntaxError:
log.exception(u'Invalid xml %s', xml)
def get_verses(self):
"""
Iterates through the verses in the XML and returns a list of verses
and their attributes.
"""
xml_iter = self.song_xml.getiterator()
verse_list = []
for element in xml_iter:
if element.tag == u'verse':
if element.text is None:
element.text = u''
verse_list.append([element.attrib, unicode(element.text)])
return verse_list
def dump_xml(self):
"""
Debugging aid to dump XML so that we can see what we have.
"""
return etree.dump(self.song_xml)
class LyricsXML(object):
"""
This class represents the XML in the ``lyrics`` field of a song.
"""
def __init__(self, song=None): def __init__(self, song=None):
if song: if song:
if song.lyrics.startswith(u'<?xml'): if song.lyrics.startswith(u'<?xml'):
@ -74,7 +175,7 @@ class LyricsXML(object):
}) })
self.lyrics.append(language) self.lyrics.append(language)
return True return True
except XMLSyntaxError: except etree.XMLSyntaxError:
return False return False
def extract(self, text): def extract(self, text):
@ -136,4 +237,3 @@ class LyricsXML(object):
song_output = u'<?xml version="1.0" encoding="UTF-8"?>' + \ song_output = u'<?xml version="1.0" encoding="UTF-8"?>' + \
u'<song version="1.0">%s</song>' % lyrics_output u'<song version="1.0">%s</song>' % lyrics_output
return song_output return song_output

View File

@ -61,7 +61,7 @@ class SongsPlugin(Plugin):
self.icon = build_icon(u':/plugins/plugin_songs.png') self.icon = build_icon(u':/plugins/plugin_songs.png')
self.status = PluginStatus.Active self.status = PluginStatus.Active
def get_settings_tab(self): def getSettingsTab(self):
return SongsTab(self.name) return SongsTab(self.name)
def initialise(self): def initialise(self):
@ -70,14 +70,14 @@ class SongsPlugin(Plugin):
self.mediaItem.displayResultsSong( self.mediaItem.displayResultsSong(
self.manager.get_all_objects(Song, Song.title)) self.manager.get_all_objects(Song, Song.title))
def get_media_manager_item(self): def getMediaManagerItem(self):
""" """
Create the MediaManagerItem object, which is displaed in the Create the MediaManagerItem object, which is displaed in the
Media Manager. Media Manager.
""" """
return SongMediaItem(self, self.icon, self.name) return SongMediaItem(self, self.icon, self.name)
def add_import_menu_item(self, import_menu): def addImportMenuItem(self, import_menu):
""" """
Give the Songs plugin the opportunity to add items to the Give the Songs plugin the opportunity to add items to the
**Import** menu. **Import** menu.
@ -137,7 +137,7 @@ class SongsPlugin(Plugin):
QtCore.QObject.connect(self.ImportOooItem, QtCore.QObject.connect(self.ImportOooItem,
QtCore.SIGNAL(u'triggered()'), self.onImportOooItemClick) QtCore.SIGNAL(u'triggered()'), self.onImportOooItemClick)
def add_export_menu_item(self, export_menu): def addExportMenuItem(self, export_menu):
""" """
Give the Songs plugin the opportunity to add items to the Give the Songs plugin the opportunity to add items to the
**Export** menu. **Export** menu.
@ -191,7 +191,7 @@ class SongsPlugin(Plugin):
'This plugin allows songs to be managed and displayed.') 'This plugin allows songs to be managed and displayed.')
return about_text return about_text
def can_delete_theme(self, theme): def canDeleteTheme(self, theme):
if not self.manager.get_all_objects_filtered(Song, if not self.manager.get_all_objects_filtered(Song,
Song.theme_name == theme): Song.theme_name == theme):
return True return True

View File

@ -46,7 +46,7 @@ class SongUsagePlugin(Plugin):
self.songusagemanager = None self.songusagemanager = None
self.songusageActive = False self.songusageActive = False
def add_tools_menu_item(self, tools_menu): def addToolsMenuItem(self, tools_menu):
""" """
Give the SongUsage plugin the opportunity to add items to the Give the SongUsage plugin the opportunity to add items to the
**Tools** menu. **Tools** menu.