This commit is contained in:
Andreas Preikschat 2011-02-03 18:59:47 +01:00
commit f596e1d8e0
68 changed files with 1319 additions and 1150 deletions

View File

@ -194,6 +194,9 @@ class OpenLP(QtGui.QApplication):
# now kill the splashscreen # now kill the splashscreen
self.splash.finish(self.mainWindow) self.splash.finish(self.mainWindow)
self.mainWindow.repaint() self.mainWindow.repaint()
update_check = QtCore.QSettings().value(
u'general/update check', QtCore.QVariant(True)).toBool()
if update_check:
VersionThread(self.mainWindow, app_version).start() VersionThread(self.mainWindow, app_version).start()
return self.exec_() return self.exec_()

View File

@ -315,7 +315,7 @@ def check_directory_exists(dir):
``dir`` ``dir``
Theme directory to make sure exists Theme directory to make sure exists
""" """
log.debug(u'check_directory_exists') log.debug(u'check_directory_exists %s' % dir)
if not os.path.exists(dir): if not os.path.exists(dir):
os.makedirs(dir) os.makedirs(dir)

View File

@ -314,7 +314,7 @@ body {
</html> </html>
""" """
def build_html(item, screen, alert, islive): def build_html(item, screen, alert, islive, background):
""" """
Build the full web paged structure for display Build the full web paged structure for display
@ -332,7 +332,9 @@ def build_html(item, screen, alert, islive):
theme = item.themedata theme = item.themedata
webkitvers = webkit_version() webkitvers = webkit_version()
# Image generated and poked in # Image generated and poked in
if item.bg_image_bytes: if background:
image = u'src="data:image/png;base64,%s"' % background
elif item.bg_image_bytes:
image = u'src="data:image/png;base64,%s"' % item.bg_image_bytes image = u'src="data:image/png;base64,%s"' % item.bg_image_bytes
else: else:
image = u'style="display:none;"' image = u'style="display:none;"'

View File

@ -98,16 +98,11 @@ class MediaManagerItem(QtGui.QWidget):
visible_title = self.plugin.getString(StringContent.VisibleName) visible_title = self.plugin.getString(StringContent.VisibleName)
self.title = unicode(visible_title[u'title']) self.title = unicode(visible_title[u'title'])
self.settingsSection = self.plugin.name.lower() self.settingsSection = self.plugin.name.lower()
if isinstance(icon, QtGui.QIcon):
self.icon = icon
elif isinstance(icon, basestring):
self.icon.addPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(icon)),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
else:
self.icon = None self.icon = None
if icon:
self.icon = build_icon(icon)
self.toolbar = None self.toolbar = None
self.remoteTriggered = None self.remoteTriggered = None
self.serviceItemIconName = None
self.singleServiceItem = True self.singleServiceItem = True
self.pageLayout = QtGui.QVBoxLayout(self) self.pageLayout = QtGui.QVBoxLayout(self)
self.pageLayout.setSpacing(0) self.pageLayout.setSpacing(0)
@ -512,7 +507,7 @@ class MediaManagerItem(QtGui.QWidget):
'No Service Item Selected'), 'No Service Item Selected'),
translate('OpenLP.MediaManagerItem', translate('OpenLP.MediaManagerItem',
'You must select an existing service item to add to.')) 'You must select an existing service item to add to.'))
elif self.title.lower() == serviceItem.name.lower(): elif self.plugin.name.lower() == serviceItem.name.lower():
self.generateSlideData(serviceItem) self.generateSlideData(serviceItem)
self.parent.serviceManager.addServiceItem(serviceItem, self.parent.serviceManager.addServiceItem(serviceItem,
replace=True) replace=True)
@ -529,9 +524,6 @@ class MediaManagerItem(QtGui.QWidget):
Common method for generating a service item Common method for generating a service item
""" """
serviceItem = ServiceItem(self.parent) serviceItem = ServiceItem(self.parent)
if self.serviceItemIconName:
serviceItem.add_icon(self.serviceItemIconName)
else:
serviceItem.add_icon(self.parent.icon_path) serviceItem.add_icon(self.parent.icon_path)
if self.generateSlideData(serviceItem, item, xmlVersion): if self.generateSlideData(serviceItem, item, xmlVersion):
return serviceItem return serviceItem
@ -544,3 +536,25 @@ class MediaManagerItem(QtGui.QWidget):
individual service items need to be processed by the plugins individual service items need to be processed by the plugins
""" """
pass pass
def _getIdOfItemToGenerate(self, item, remoteItem):
"""
Utility method to check items being submitted for slide generation.
``item``
The item to check.
``remoteItem``
The id to assign if the slide generation was remotely triggered.
"""
if item is None:
if self.remoteTriggered is None:
item = self.listView.currentItem()
if item is None:
return False
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
else:
item_id = remoteItem
else:
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
return item_id

View File

@ -42,6 +42,7 @@ class PluginStatus(object):
Inactive = 0 Inactive = 0
Disabled = -1 Disabled = -1
class StringContent(object): class StringContent(object):
Name = u'name' Name = u'name'
Import = u'import' Import = u'import'
@ -54,6 +55,7 @@ class StringContent(object):
Service = u'service' Service = u'service'
VisibleName = u'visible_name' VisibleName = u'visible_name'
class Plugin(QtCore.QObject): class Plugin(QtCore.QObject):
""" """
Base class for openlp plugins to inherit from. Base class for openlp plugins to inherit from.
@ -116,7 +118,7 @@ class Plugin(QtCore.QObject):
class MyPlugin(Plugin): class MyPlugin(Plugin):
def __init__(self): def __init__(self):
Plugin.__init(self, u'MyPlugin', u'0.1') Plugin.__init__(self, u'MyPlugin', u'0.1')
``name`` ``name``
Defaults to *None*. The name of the plugin. Defaults to *None*. The name of the plugin.

View File

@ -93,15 +93,15 @@ class SearchEdit(QtGui.QLineEdit):
``event`` ``event``
The event that happened. The event that happened.
""" """
sz = self.clearButton.size() size = self.clearButton.size()
frameWidth = self.style().pixelMetric( frameWidth = self.style().pixelMetric(
QtGui.QStyle.PM_DefaultFrameWidth) QtGui.QStyle.PM_DefaultFrameWidth)
self.clearButton.move(self.rect().right() - frameWidth - sz.width(), self.clearButton.move(self.rect().right() - frameWidth - size.width(),
(self.rect().bottom() + 1 - sz.height()) / 2) (self.rect().bottom() + 1 - size.height()) / 2)
if hasattr(self, u'menuButton'): if hasattr(self, u'menuButton'):
sz = self.menuButton.size() size = self.menuButton.size()
self.menuButton.move(self.rect().left() + frameWidth + 2, self.menuButton.move(self.rect().left() + frameWidth + 2,
(self.rect().bottom() + 1 - sz.height()) / 2) (self.rect().bottom() + 1 - size.height()) / 2)
def currentSearchType(self): def currentSearchType(self):
""" """

View File

@ -59,6 +59,7 @@ class ItemCapabilities(object):
OnLoadUpdate = 8 OnLoadUpdate = 8
AddIfNewItem = 9 AddIfNewItem = 9
ProvidesOwnDisplay = 10 ProvidesOwnDisplay = 10
AllowsDetailedTitleDisplay = 11
class ServiceItem(object): class ServiceItem(object):
@ -314,6 +315,20 @@ class ServiceItem(object):
path, text_image[u'title'], text_image[u'image'] ) path, text_image[u'title'], text_image[u'image'] )
self._new_item() self._new_item()
def get_display_title(self):
"""
Returns the title of the service item.
"""
if self.is_text():
return self.title
else:
if ItemCapabilities.AllowsDetailedTitleDisplay in self.capabilities:
return self._raw_frames[0][u'title']
elif len(self._raw_frames) > 1:
return self.title
else:
return self._raw_frames[0][u'title']
def merge(self, other): def merge(self, other):
""" """
Updates the _uuid with the value from the original one Updates the _uuid with the value from the original one

View File

@ -47,13 +47,16 @@ class SpellTextEdit(QtGui.QPlainTextEdit):
# Default dictionary based on the current locale. # Default dictionary based on the current locale.
if ENCHANT_AVAILABLE: if ENCHANT_AVAILABLE:
try: try:
self.dict = enchant.Dict() self.dictionary = enchant.Dict()
except DictNotFoundError: except DictNotFoundError:
self.dict = enchant.Dict(u'en_US') self.dictionary = enchant.Dict(u'en_US')
self.highlighter = Highlighter(self.document()) self.highlighter = Highlighter(self.document())
self.highlighter.setDict(self.dict) self.highlighter.spellingDictionary = self.dictionary
def mousePressEvent(self, event): def mousePressEvent(self, event):
"""
Handle mouse clicks within the text edit region.
"""
if event.button() == QtCore.Qt.RightButton: if event.button() == QtCore.Qt.RightButton:
# Rewrite the mouse event to a left button event so the cursor is # Rewrite the mouse event to a left button event so the cursor is
# moved to the location of the pointer. # moved to the location of the pointer.
@ -63,6 +66,9 @@ class SpellTextEdit(QtGui.QPlainTextEdit):
QtGui.QPlainTextEdit.mousePressEvent(self, event) QtGui.QPlainTextEdit.mousePressEvent(self, event)
def contextMenuEvent(self, event): def contextMenuEvent(self, event):
"""
Provide the context menu for the text edit region.
"""
popupMenu = self.createStandardContextMenu() popupMenu = self.createStandardContextMenu()
# Select the word under the cursor. # Select the word under the cursor.
cursor = self.textCursor() cursor = self.textCursor()
@ -74,10 +80,10 @@ class SpellTextEdit(QtGui.QPlainTextEdit):
# suggestions if it is. # suggestions if it is.
if ENCHANT_AVAILABLE and self.textCursor().hasSelection(): if ENCHANT_AVAILABLE and self.textCursor().hasSelection():
text = unicode(self.textCursor().selectedText()) text = unicode(self.textCursor().selectedText())
if not self.dict.check(text): if not self.dictionary.check(text):
spell_menu = QtGui.QMenu(translate('OpenLP.SpellTextEdit', spell_menu = QtGui.QMenu(translate('OpenLP.SpellTextEdit',
'Spelling Suggestions')) 'Spelling Suggestions'))
for word in self.dict.suggest(text): for word in self.dictionary.suggest(text):
action = SpellAction(word, spell_menu) action = SpellAction(word, spell_menu)
action.correct.connect(self.correctWord) action.correct.connect(self.correctWord)
spell_menu.addAction(action) spell_menu.addAction(action)
@ -126,28 +132,32 @@ class SpellTextEdit(QtGui.QPlainTextEdit):
cursor.insertText(html[u'start tag']) cursor.insertText(html[u'start tag'])
cursor.insertText(html[u'end tag']) cursor.insertText(html[u'end tag'])
class Highlighter(QtGui.QSyntaxHighlighter):
class Highlighter(QtGui.QSyntaxHighlighter):
"""
Provides a text highlighter for pointing out spelling errors in text.
"""
WORDS = u'(?iu)[\w\']+' WORDS = u'(?iu)[\w\']+'
def __init__(self, *args): def __init__(self, *args):
QtGui.QSyntaxHighlighter.__init__(self, *args) QtGui.QSyntaxHighlighter.__init__(self, *args)
self.dict = None self.spellingDictionary = None
def setDict(self, dict):
self.dict = dict
def highlightBlock(self, text): def highlightBlock(self, text):
if not self.dict: """
Highlight misspelt words in a block of text
"""
if not self.spellingDictionary:
return return
text = unicode(text) text = unicode(text)
format = QtGui.QTextCharFormat() charFormat = QtGui.QTextCharFormat()
format.setUnderlineColor(QtCore.Qt.red) charFormat.setUnderlineColor(QtCore.Qt.red)
format.setUnderlineStyle(QtGui.QTextCharFormat.SpellCheckUnderline) charFormat.setUnderlineStyle(QtGui.QTextCharFormat.SpellCheckUnderline)
for word_object in re.finditer(self.WORDS, text): for word_object in re.finditer(self.WORDS, text):
if not self.dict.check(word_object.group()): if not self.spellingDictionary.check(word_object.group()):
self.setFormat(word_object.start(), self.setFormat(word_object.start(),
word_object.end() - word_object.start(), format) word_object.end() - word_object.start(), charFormat)
class SpellAction(QtGui.QAction): class SpellAction(QtGui.QAction):
""" """

View File

@ -91,21 +91,30 @@ class ThemeLevel(object):
Song = 3 Song = 3
class BackgroundType(object): class BackgroundType(object):
"""
Type enumeration for backgrounds.
"""
Solid = 0 Solid = 0
Gradient = 1 Gradient = 1
Image = 2 Image = 2
@staticmethod @staticmethod
def to_string(type): def to_string(background_type):
if type == BackgroundType.Solid: """
Return a string representation of a background type.
"""
if background_type == BackgroundType.Solid:
return u'solid' return u'solid'
elif type == BackgroundType.Gradient: elif background_type == BackgroundType.Gradient:
return u'gradient' return u'gradient'
elif type == BackgroundType.Image: elif background_type == BackgroundType.Image:
return u'image' return u'image'
@staticmethod @staticmethod
def from_string(type_string): def from_string(type_string):
"""
Return a background type for the given string.
"""
if type_string == u'solid': if type_string == u'solid':
return BackgroundType.Solid return BackgroundType.Solid
elif type_string == u'gradient': elif type_string == u'gradient':
@ -114,6 +123,9 @@ class BackgroundType(object):
return BackgroundType.Image return BackgroundType.Image
class BackgroundGradientType(object): class BackgroundGradientType(object):
"""
Type enumeration for background gradients.
"""
Horizontal = 0 Horizontal = 0
Vertical = 1 Vertical = 1
Circular = 2 Circular = 2
@ -121,20 +133,26 @@ class BackgroundGradientType(object):
LeftBottom = 4 LeftBottom = 4
@staticmethod @staticmethod
def to_string(type): def to_string(gradient_type):
if type == BackgroundGradientType.Horizontal: """
Return a string representation of a background gradient type.
"""
if gradient_type == BackgroundGradientType.Horizontal:
return u'horizontal' return u'horizontal'
elif type == BackgroundGradientType.Vertical: elif gradient_type == BackgroundGradientType.Vertical:
return u'vertical' return u'vertical'
elif type == BackgroundGradientType.Circular: elif gradient_type == BackgroundGradientType.Circular:
return u'circular' return u'circular'
elif type == BackgroundGradientType.LeftTop: elif gradient_type == BackgroundGradientType.LeftTop:
return u'leftTop' return u'leftTop'
elif type == BackgroundGradientType.LeftBottom: elif gradient_type == BackgroundGradientType.LeftBottom:
return u'leftBottom' return u'leftBottom'
@staticmethod @staticmethod
def from_string(type_string): def from_string(type_string):
"""
Return a background gradient type for the given string.
"""
if type_string == u'horizontal': if type_string == u'horizontal':
return BackgroundGradientType.Horizontal return BackgroundGradientType.Horizontal
elif type_string == u'vertical': elif type_string == u'vertical':
@ -147,19 +165,25 @@ class BackgroundGradientType(object):
return BackgroundGradientType.LeftBottom return BackgroundGradientType.LeftBottom
class HorizontalType(object): class HorizontalType(object):
"""
Type enumeration for horizontal alignment.
"""
Left = 0 Left = 0
Center = 1 Center = 1
Right = 2 Right = 2
class VerticalType(object): class VerticalType(object):
"""
Type enumeration for vertical alignment.
"""
Top = 0 Top = 0
Middle = 1 Middle = 1
Bottom = 2 Bottom = 2
boolean_list = [u'italics', u'override', u'outline', u'shadow', BOOLEAN_LIST = [u'bold', u'italics', u'override', u'outline', u'shadow',
u'slide_transition'] u'slide_transition']
integer_list = [u'size', u'line_adjustment', u'x', u'height', u'y', INTEGER_LIST = [u'size', u'line_adjustment', u'x', u'height', u'y',
u'width', u'shadow_size', u'outline_size', u'horizontal_align', u'width', u'shadow_size', u'outline_size', u'horizontal_align',
u'vertical_align', u'wrap_style'] u'vertical_align', u'wrap_style']
@ -514,9 +538,9 @@ class ThemeXML(object):
return return
field = self._de_hump(element) field = self._de_hump(element)
tag = master + u'_' + field tag = master + u'_' + field
if field in boolean_list: if field in BOOLEAN_LIST:
setattr(self, tag, str_to_bool(value)) setattr(self, tag, str_to_bool(value))
elif field in integer_list: elif field in INTEGER_LIST:
setattr(self, tag, int(value)) setattr(self, tag, int(value))
else: else:
# make string value unicode # make string value unicode

110
openlp/core/lib/ui.py Normal file
View File

@ -0,0 +1,110 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
# Copyright (c) 2008-2011 Raoul Snyman #
# Portions copyright (c) 2008-2011 Tim Bentley, Jonathan Corwin, Michael #
# Gorven, Scott Guerrieri, Meinert Jordan, Andreas Preikschat, Christian #
# Richter, Philip Ridout, Maikel Stuivenberg, Martin Thompson, Jon Tibble, #
# Carsten Tinggaard, Frode Woldsund #
# --------------------------------------------------------------------------- #
# 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 #
###############################################################################
"""
The :mod:`ui` module provides standard UI components for OpenLP.
"""
import logging
from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate
log = logging.getLogger(__name__)
def add_welcome_page(parent, image):
"""
Generate an opening welcome page for a wizard using a provided image.
``image``
A splash image for the wizard.
"""
parent.welcomePage = QtGui.QWizardPage()
parent.welcomePage.setPixmap(QtGui.QWizard.WatermarkPixmap,
QtGui.QPixmap(image))
parent.welcomePage.setObjectName(u'WelcomePage')
parent.welcomeLayout = QtGui.QVBoxLayout(parent.welcomePage)
parent.welcomeLayout.setObjectName(u'WelcomeLayout')
parent.titleLabel = QtGui.QLabel(parent.welcomePage)
parent.titleLabel.setObjectName(u'TitleLabel')
parent.welcomeLayout.addWidget(parent.titleLabel)
parent.welcomeLayout.addSpacing(40)
parent.informationLabel = QtGui.QLabel(parent.welcomePage)
parent.informationLabel.setWordWrap(True)
parent.informationLabel.setObjectName(u'InformationLabel')
parent.welcomeLayout.addWidget(parent.informationLabel)
parent.welcomeLayout.addStretch()
parent.addPage(parent.welcomePage)
def save_cancel_button_box(parent):
"""
Return a standard dialog button box with save and cancel buttons.
"""
button_box = QtGui.QDialogButtonBox(parent)
button_box.setStandardButtons(
QtGui.QDialogButtonBox.Save | QtGui.QDialogButtonBox.Cancel)
button_box.setObjectName(u'%sButtonBox' % parent)
QtCore.QObject.connect(button_box, QtCore.SIGNAL(u'accepted()'),
parent.accept)
QtCore.QObject.connect(button_box, QtCore.SIGNAL(u'rejected()'),
parent.reject)
return button_box
def critical_error_message_box(title=None, message=None, parent=None,
question=False):
"""
Provides a standard critical message box for errors that OpenLP displays
to users.
``title``
The title for the message box.
``message``
The message to display to the user.
``parent``
The parent UI element to attach the dialog to.
``question``
Should this message box question the user.
"""
error = translate('OpenLP.Ui', 'Error')
if question:
return QtGui.QMessageBox.critical(parent, error, message,
QtGui.QMessageBox.StandardButtons(
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No))
data = {u'message': message}
data[u'title'] = title if title else error
return Receiver.send_message(u'openlp_error_message', data)
def media_item_combo_box(parent, name):
"""
Provide a standard combo box for media items.
"""
combo = QtGui.QComboBox(parent)
combo.setObjectName(name)
combo.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
combo.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
return combo

View File

@ -51,34 +51,6 @@ class HideMode(object):
Theme = 2 Theme = 2
Screen = 3 Screen = 3
def criticalErrorMessageBox(title=None, message=None, parent=None,
question=False):
"""
Provides a standard critical message box for errors that OpenLP displays
to users.
``title``
The title for the message box.
``message``
The message to display to the user.
``parent``
The parent UI element to attach the dialog to.
``question``
Should this message box question the user.
"""
error = translate('OpenLP.Ui', 'Error')
if question:
return QtGui.QMessageBox.critical(parent, error, message,
QtGui.QMessageBox.StandardButtons(
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No))
data = {u'message': message}
data[u'title'] = title if title else error
return Receiver.send_message(u'openlp_error_message', data)
from themeform import ThemeForm from themeform import ThemeForm
from filerenameform import FileRenameForm from filerenameform import FileRenameForm
from maindisplay import MainDisplay from maindisplay import MainDisplay
@ -99,6 +71,6 @@ from mediadockmanager import MediaDockManager
from servicemanager import ServiceManager from servicemanager import ServiceManager
from thememanager import ThemeManager from thememanager import ThemeManager
__all__ = ['criticalErrorMessageBox', 'SplashScreen', 'AboutForm', __all__ = ['SplashScreen', 'AboutForm', 'SettingsForm', 'MainDisplay',
'SettingsForm', 'MainDisplay', 'SlideController', 'ServiceManager', 'SlideController', 'ServiceManager', 'ThemeManager', 'MediaDockManager',
'ThemeManager', 'MediaDockManager', 'ServiceItemEditForm'] 'ServiceItemEditForm']

View File

@ -80,6 +80,16 @@ class AdvancedTab(SettingsTab):
self.hideMouseCheckBox.setObjectName(u'hideMouseCheckBox') self.hideMouseCheckBox.setObjectName(u'hideMouseCheckBox')
self.hideMouseLayout.addWidget(self.hideMouseCheckBox) self.hideMouseLayout.addWidget(self.hideMouseCheckBox)
self.leftLayout.addWidget(self.hideMouseGroupBox) self.leftLayout.addWidget(self.hideMouseGroupBox)
self.serviceOrderGroupBox = QtGui.QGroupBox(self.leftColumn)
self.serviceOrderGroupBox.setObjectName(u'serviceOrderGroupBox')
self.serviceOrderLayout = QtGui.QVBoxLayout(self.serviceOrderGroupBox)
self.serviceOrderLayout.setObjectName(u'serviceOrderLayout')
self.detailedServicePrintCheckBox = QtGui.QCheckBox(
self.serviceOrderGroupBox)
self.detailedServicePrintCheckBox.setObjectName(
u'detailedServicePrintCheckBox')
self.serviceOrderLayout.addWidget(self.detailedServicePrintCheckBox)
self.leftLayout.addWidget(self.serviceOrderGroupBox)
# self.sharedDirGroupBox = QtGui.QGroupBox(self.leftColumn) # self.sharedDirGroupBox = QtGui.QGroupBox(self.leftColumn)
# self.sharedDirGroupBox.setObjectName(u'sharedDirGroupBox') # self.sharedDirGroupBox.setObjectName(u'sharedDirGroupBox')
# self.sharedDirLayout = QtGui.QFormLayout(self.sharedDirGroupBox) # self.sharedDirLayout = QtGui.QFormLayout(self.sharedDirGroupBox)
@ -129,6 +139,11 @@ class AdvancedTab(SettingsTab):
'Mouse Cursor')) 'Mouse Cursor'))
self.hideMouseCheckBox.setText(translate('OpenLP.AdvancedTab', self.hideMouseCheckBox.setText(translate('OpenLP.AdvancedTab',
'Hide the mouse cursor when moved over the display window')) 'Hide the mouse cursor when moved over the display window'))
self.serviceOrderGroupBox.setTitle(translate('OpenLP.AdvancedTab',
'Service Order Print'))
self.detailedServicePrintCheckBox.setText(
translate('OpenLP.AdvancedTab',
'Print slide texts and service item notes as well'))
# self.sharedDirGroupBox.setTitle( # self.sharedDirGroupBox.setTitle(
# translate('AdvancedTab', 'Central Data Store')) # translate('AdvancedTab', 'Central Data Store'))
# self.sharedCheckBox.setText( # self.sharedCheckBox.setText(
@ -164,6 +179,8 @@ class AdvancedTab(SettingsTab):
QtCore.QVariant(True)).toBool()) QtCore.QVariant(True)).toBool())
self.hideMouseCheckBox.setChecked( self.hideMouseCheckBox.setChecked(
settings.value(u'hide mouse', QtCore.QVariant(False)).toBool()) settings.value(u'hide mouse', QtCore.QVariant(False)).toBool())
self.detailedServicePrintCheckBox.setChecked(settings.value(
u'detailed service print', QtCore.QVariant(False)).toBool())
settings.endGroup() settings.endGroup()
def save(self): def save(self):
@ -184,6 +201,8 @@ class AdvancedTab(SettingsTab):
QtCore.QVariant(self.enableAutoCloseCheckBox.isChecked())) QtCore.QVariant(self.enableAutoCloseCheckBox.isChecked()))
settings.setValue(u'hide mouse', settings.setValue(u'hide mouse',
QtCore.QVariant(self.hideMouseCheckBox.isChecked())) QtCore.QVariant(self.hideMouseCheckBox.isChecked()))
settings.setValue(u'detailed service print',
QtCore.QVariant(self.detailedServicePrintCheckBox.isChecked()))
settings.endGroup() settings.endGroup()
# def onSharedCheckBoxChanged(self, checked): # def onSharedCheckBoxChanged(self, checked):

View File

@ -34,7 +34,7 @@ import cPickle
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import SettingsTab, translate, DisplayTags from openlp.core.lib import SettingsTab, translate, DisplayTags
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
class DisplayTagTab(SettingsTab): class DisplayTagTab(SettingsTab):
''' '''
@ -276,7 +276,7 @@ class DisplayTagTab(SettingsTab):
""" """
for html in DisplayTags.get_html_tags(): for html in DisplayTags.get_html_tags():
if self._strip(html[u'start tag']) == u'n': if self._strip(html[u'start tag']) == u'n':
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.DisplayTagTab', 'Update Error'), translate('OpenLP.DisplayTagTab', 'Update Error'),
translate('OpenLP.DisplayTagTab', translate('OpenLP.DisplayTagTab',
'Tag "n" already defined.')) 'Tag "n" already defined.'))
@ -317,7 +317,7 @@ class DisplayTagTab(SettingsTab):
for linenumber, html1 in enumerate(html_expands): for linenumber, html1 in enumerate(html_expands):
if self._strip(html1[u'start tag']) == tag and \ if self._strip(html1[u'start tag']) == tag and \
linenumber != self.selected: linenumber != self.selected:
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.DisplayTagTab', 'Update Error'), translate('OpenLP.DisplayTagTab', 'Update Error'),
unicode(translate('OpenLP.DisplayTagTab', unicode(translate('OpenLP.DisplayTagTab',
'Tag %s already defined.')) % tag) 'Tag %s already defined.')) % tag)

View File

@ -51,6 +51,7 @@ class ValidEdit(QtGui.QLineEdit):
else: else:
return self.text() return self.text()
class GeneralTab(SettingsTab): class GeneralTab(SettingsTab):
""" """
GeneralTab is the general settings tab in the settings dialog. GeneralTab is the general settings tab in the settings dialog.
@ -113,6 +114,9 @@ class GeneralTab(SettingsTab):
self.showSplashCheckBox = QtGui.QCheckBox(self.startupGroupBox) self.showSplashCheckBox = QtGui.QCheckBox(self.startupGroupBox)
self.showSplashCheckBox.setObjectName(u'showSplashCheckBox') self.showSplashCheckBox.setObjectName(u'showSplashCheckBox')
self.startupLayout.addWidget(self.showSplashCheckBox) self.startupLayout.addWidget(self.showSplashCheckBox)
self.checkForUpdatesCheckBox = QtGui.QCheckBox(self.startupGroupBox)
self.checkForUpdatesCheckBox.setObjectName(u'checkForUpdatesCheckBox')
self.startupLayout.addWidget(self.checkForUpdatesCheckBox)
self.leftLayout.addWidget(self.startupGroupBox) self.leftLayout.addWidget(self.startupGroupBox)
self.settingsGroupBox = QtGui.QGroupBox(self.leftColumn) self.settingsGroupBox = QtGui.QGroupBox(self.leftColumn)
self.settingsGroupBox.setObjectName(u'settingsGroupBox') self.settingsGroupBox.setObjectName(u'settingsGroupBox')
@ -249,6 +253,8 @@ class GeneralTab(SettingsTab):
'Automatically open the last service')) 'Automatically open the last service'))
self.showSplashCheckBox.setText( self.showSplashCheckBox.setText(
translate('OpenLP.GeneralTab', 'Show the splash screen')) translate('OpenLP.GeneralTab', 'Show the splash screen'))
self.checkForUpdatesCheckBox.setText(
translate('OpenLP.GeneralTab', 'Check for updates to OpenLP'))
self.settingsGroupBox.setTitle( self.settingsGroupBox.setTitle(
translate('OpenLP.GeneralTab', 'Application Settings')) translate('OpenLP.GeneralTab', 'Application Settings'))
self.saveCheckServiceCheckBox.setText(translate('OpenLP.GeneralTab', self.saveCheckServiceCheckBox.setText(translate('OpenLP.GeneralTab',
@ -317,6 +323,8 @@ class GeneralTab(SettingsTab):
QtCore.QVariant(False)).toBool()) QtCore.QVariant(False)).toBool())
self.showSplashCheckBox.setChecked(settings.value(u'show splash', self.showSplashCheckBox.setChecked(settings.value(u'show splash',
QtCore.QVariant(True)).toBool()) QtCore.QVariant(True)).toBool())
self.checkForUpdatesCheckBox.setChecked(settings.value(u'update check',
QtCore.QVariant(True)).toBool())
self.autoPreviewCheckBox.setChecked(settings.value(u'auto preview', self.autoPreviewCheckBox.setChecked(settings.value(u'auto preview',
QtCore.QVariant(False)).toBool()) QtCore.QVariant(False)).toBool())
self.timeoutSpinBox.setValue(settings.value(u'loop delay', self.timeoutSpinBox.setValue(settings.value(u'loop delay',
@ -363,6 +371,8 @@ class GeneralTab(SettingsTab):
QtCore.QVariant(self.autoOpenCheckBox.isChecked())) QtCore.QVariant(self.autoOpenCheckBox.isChecked()))
settings.setValue(u'show splash', settings.setValue(u'show splash',
QtCore.QVariant(self.showSplashCheckBox.isChecked())) QtCore.QVariant(self.showSplashCheckBox.isChecked()))
settings.setValue(u'update check',
QtCore.QVariant(self.checkForUpdatesCheckBox.isChecked()))
settings.setValue(u'save prompt', settings.setValue(u'save prompt',
QtCore.QVariant(self.saveCheckServiceCheckBox.isChecked())) QtCore.QVariant(self.saveCheckServiceCheckBox.isChecked()))
settings.setValue(u'auto preview', settings.setValue(u'auto preview',

View File

@ -67,6 +67,7 @@ class MainDisplay(DisplayWidget):
self.isLive = live self.isLive = live
self.alertTab = None self.alertTab = None
self.hideMode = None self.hideMode = None
self.override = {}
mainIcon = build_icon(u':/icon/openlp-logo-16x16.png') mainIcon = build_icon(u':/icon/openlp-logo-16x16.png')
self.setWindowIcon(mainIcon) self.setWindowIcon(mainIcon)
self.retranslateUi() self.retranslateUi()
@ -111,7 +112,7 @@ class MainDisplay(DisplayWidget):
self.page = self.webView.page() self.page = self.webView.page()
self.frame = self.page.mainFrame() self.frame = self.page.mainFrame()
QtCore.QObject.connect(self.webView, QtCore.QObject.connect(self.webView,
QtCore.SIGNAL(u'loadFinished(bool)'), self.isLoaded) QtCore.SIGNAL(u'loadFinished(bool)'), self.isWebLoaded)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.frame.setScrollBarPolicy(QtCore.Qt.Vertical, self.frame.setScrollBarPolicy(QtCore.Qt.Vertical,
@ -144,7 +145,7 @@ class MainDisplay(DisplayWidget):
serviceItem = ServiceItem() serviceItem = ServiceItem()
serviceItem.bg_image_bytes = image_to_byte(initialFrame) serviceItem.bg_image_bytes = image_to_byte(initialFrame)
self.webView.setHtml(build_html(serviceItem, self.screen, self.webView.setHtml(build_html(serviceItem, self.screen,
self.parent.alertTab, self.isLive)) self.parent.alertTab, self.isLive, None))
self.initialFrame = True self.initialFrame = True
# To display or not to display? # To display or not to display?
if not self.screen[u'primary']: if not self.screen[u'primary']:
@ -162,7 +163,7 @@ class MainDisplay(DisplayWidget):
""" """
log.debug(u'text to display') log.debug(u'text to display')
# Wait for the webview to update before displaying text. # Wait for the webview to update before displaying text.
while not self.loaded: while not self.webLoaded:
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
self.frame.evaluateJavaScript(u'show_text("%s")' % \ self.frame.evaluateJavaScript(u'show_text("%s")' % \
slide.replace(u'\\', u'\\\\').replace(u'\"', u'\\\"')) slide.replace(u'\\', u'\\\\').replace(u'\"', u'\\\"'))
@ -204,14 +205,17 @@ class MainDisplay(DisplayWidget):
""" """
self.imageManager.add_image(name, path) self.imageManager.add_image(name, path)
self.image(name) self.image(name)
if hasattr(self, u'serviceItem'):
self.override[u'image'] = name
self.override[u'theme'] = self.serviceItem.themedata.theme_name
def image(self, name): def image(self, name):
""" """
Add an image as the background. The image is converted to a bytestream Add an image as the background. The image has already been added
on route. to the cache.
`Image` `Image`
The Image to be displayed can be QImage or QPixmap The name of the image to be displayed
""" """
log.debug(u'image to display') log.debug(u'image to display')
image = self.imageManager.get_image_bytes(name) image = self.imageManager.get_image_bytes(name)
@ -244,6 +248,7 @@ class MainDisplay(DisplayWidget):
self.displayImage(self.serviceItem.bg_image_bytes) self.displayImage(self.serviceItem.bg_image_bytes)
else: else:
self.displayImage(None) self.displayImage(None)
self.override = {}
# Update the preview frame. # Update the preview frame.
Receiver.send_message(u'maindisplay_active') Receiver.send_message(u'maindisplay_active')
@ -260,6 +265,7 @@ class MainDisplay(DisplayWidget):
self.phononActive = False self.phononActive = False
else: else:
self.frame.evaluateJavaScript(u'show_video("close");') self.frame.evaluateJavaScript(u'show_video("close");')
self.override = {}
# Update the preview frame. # Update the preview frame.
Receiver.send_message(u'maindisplay_active') Receiver.send_message(u'maindisplay_active')
@ -313,7 +319,10 @@ class MainDisplay(DisplayWidget):
Loads and starts a video to run with the option of sound Loads and starts a video to run with the option of sound
""" """
log.debug(u'video') log.debug(u'video')
self.loaded = True self.webLoaded = True
# We are running a background theme
self.override[u'theme'] = u''
self.override[u'video'] = True
vol = float(volume)/float(10) vol = float(volume)/float(10)
if isBackground or not self.usePhonon: if isBackground or not self.usePhonon:
js = u'show_video("init", "%s", %s, true); show_video("play");' % \ js = u'show_video("init", "%s", %s, true); show_video("play");' % \
@ -333,12 +342,12 @@ class MainDisplay(DisplayWidget):
Receiver.send_message(u'maindisplay_active') Receiver.send_message(u'maindisplay_active')
return self.preview() return self.preview()
def isLoaded(self): def isWebLoaded(self):
""" """
Called by webView event to show display is fully loaded Called by webView event to show display is fully loaded
""" """
log.debug(u'loaded') log.debug(u'Webloaded')
self.loaded = True self.webLoaded = True
def preview(self): def preview(self):
""" """
@ -357,7 +366,7 @@ class MainDisplay(DisplayWidget):
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
# Wait for the webview to update before geting the preview. # Wait for the webview to update before geting the preview.
# Important otherwise first preview will miss the background ! # Important otherwise first preview will miss the background !
while not self.loaded: while not self.webLoaded:
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
# if was hidden keep it hidden # if was hidden keep it hidden
if self.isLive: if self.isLive:
@ -379,18 +388,32 @@ class MainDisplay(DisplayWidget):
HTML to the display HTML to the display
""" """
log.debug(u'buildHtml') log.debug(u'buildHtml')
self.loaded = False self.webLoaded = False
self.initialFrame = False self.initialFrame = False
self.serviceItem = serviceItem self.serviceItem = serviceItem
background = None
# We have an image override so keep the image till the theme changes
if self.override:
# We have an video override so allow it to be stopped
if u'video' in self.override:
Receiver.send_message(u'video_background_replaced')
self.override = {}
elif self.override[u'theme'] != \
serviceItem.themedata.theme_name:
Receiver.send_message(u'live_theme_changed')
self.override = {}
else:
background = self.imageManager. \
get_image_bytes(self.override[u'image'])
if self.serviceItem.themedata.background_filename: if self.serviceItem.themedata.background_filename:
self.serviceItem.bg_image_bytes = self.imageManager. \ self.serviceItem.bg_image_bytes = self.imageManager. \
get_image_bytes(self.serviceItem.themedata.theme_name) get_image_bytes(self.serviceItem.themedata.theme_name)
html = build_html(self.serviceItem, self.screen, self.parent.alertTab, html = build_html(self.serviceItem, self.screen, self.parent.alertTab,
self.isLive) self.isLive, background)
log.debug(u'buildHtml - pre setHtml') log.debug(u'buildHtml - pre setHtml')
self.webView.setHtml(html) self.webView.setHtml(html)
log.debug(u'buildHtml - post setHtml') log.debug(u'buildHtml - post setHtml')
if serviceItem.foot_text and serviceItem.foot_text: if serviceItem.foot_text:
self.footer(serviceItem.foot_text) self.footer(serviceItem.foot_text)
# if was hidden keep it hidden # if was hidden keep it hidden
if self.hideMode and self.isLive: if self.hideMode and self.isLive:

View File

@ -87,10 +87,10 @@ class Ui_MainWindow(object):
self.screens, True) self.screens, True)
previewVisible = QtCore.QSettings().value( previewVisible = QtCore.QSettings().value(
u'user interface/preview panel', QtCore.QVariant(True)).toBool() u'user interface/preview panel', QtCore.QVariant(True)).toBool()
self.previewController.Panel.setVisible(previewVisible) self.previewController.panel.setVisible(previewVisible)
liveVisible = QtCore.QSettings().value(u'user interface/live panel', liveVisible = QtCore.QSettings().value(u'user interface/live panel',
QtCore.QVariant(True)).toBool() QtCore.QVariant(True)).toBool()
self.liveController.Panel.setVisible(liveVisible) self.liveController.panel.setVisible(liveVisible)
# Create menu # Create menu
self.MenuBar = QtGui.QMenuBar(mainWindow) self.MenuBar = QtGui.QMenuBar(mainWindow)
self.MenuBar.setObjectName(u'MenuBar') self.MenuBar.setObjectName(u'MenuBar')
@ -175,6 +175,10 @@ class Ui_MainWindow(object):
self.FileSaveAsItem = QtGui.QAction(mainWindow) self.FileSaveAsItem = QtGui.QAction(mainWindow)
self.FileSaveAsItem.setObjectName(u'FileSaveAsItem') self.FileSaveAsItem.setObjectName(u'FileSaveAsItem')
mainWindow.actionList.add_action(self.FileSaveAsItem, u'File') mainWindow.actionList.add_action(self.FileSaveAsItem, u'File')
self.printServiceOrderItem = QtGui.QAction(mainWindow)
self.printServiceOrderItem.setObjectName(u'printServiceItem')
mainWindow.actionList.add_action(
self.printServiceOrderItem, u'Print Service Order')
self.FileExitItem = QtGui.QAction(mainWindow) self.FileExitItem = QtGui.QAction(mainWindow)
self.FileExitItem.setIcon(build_icon(u':/system/system_exit.png')) self.FileExitItem.setIcon(build_icon(u':/system/system_exit.png'))
self.FileExitItem.setObjectName(u'FileExitItem') self.FileExitItem.setObjectName(u'FileExitItem')
@ -302,8 +306,8 @@ class Ui_MainWindow(object):
(self.ExportThemeItem, self.ExportLanguageItem)) (self.ExportThemeItem, self.ExportLanguageItem))
self.FileMenuActions = (self.FileNewItem, self.FileOpenItem, self.FileMenuActions = (self.FileNewItem, self.FileOpenItem,
self.FileSaveItem, self.FileSaveAsItem, None, self.FileSaveItem, self.FileSaveAsItem, None,
self.FileImportMenu.menuAction(), self.FileExportMenu.menuAction(), self.printServiceOrderItem, None, self.FileImportMenu.menuAction(),
self.FileExitItem) self.FileExportMenu.menuAction(), self.FileExitItem)
add_actions(self.ViewModeMenu, (self.ModeDefaultItem, add_actions(self.ViewModeMenu, (self.ModeDefaultItem,
self.ModeSetupItem, self.ModeLiveItem)) self.ModeSetupItem, self.ModeLiveItem))
add_actions(self.ViewMenu, (self.ViewModeMenu.menuAction(), add_actions(self.ViewMenu, (self.ViewModeMenu.menuAction(),
@ -381,6 +385,12 @@ class Ui_MainWindow(object):
'Save the current service under a new name.')) 'Save the current service under a new name.'))
self.FileSaveAsItem.setShortcut( self.FileSaveAsItem.setShortcut(
translate('OpenLP.MainWindow', 'Ctrl+Shift+S')) translate('OpenLP.MainWindow', 'Ctrl+Shift+S'))
self.printServiceOrderItem.setText(
translate('OpenLP.MainWindow', 'Print Service Order'))
self.printServiceOrderItem.setStatusTip(translate('OpenLP.MainWindow',
'Print the current Service Order.'))
self.printServiceOrderItem.setShortcut(
translate('OpenLP.MainWindow', 'Ctrl+P'))
self.FileExitItem.setText( self.FileExitItem.setText(
translate('OpenLP.MainWindow', 'E&xit')) translate('OpenLP.MainWindow', 'E&xit'))
self.FileExitItem.setStatusTip( self.FileExitItem.setStatusTip(
@ -563,10 +573,13 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
self.ServiceManagerContents.onLoadServiceClicked) self.ServiceManagerContents.onLoadServiceClicked)
QtCore.QObject.connect(self.FileSaveItem, QtCore.QObject.connect(self.FileSaveItem,
QtCore.SIGNAL(u'triggered()'), QtCore.SIGNAL(u'triggered()'),
self.ServiceManagerContents.onSaveServiceClicked) self.ServiceManagerContents.saveFile)
QtCore.QObject.connect(self.FileSaveAsItem, QtCore.QObject.connect(self.FileSaveAsItem,
QtCore.SIGNAL(u'triggered()'), QtCore.SIGNAL(u'triggered()'),
self.ServiceManagerContents.onSaveServiceAsClicked) self.ServiceManagerContents.saveFileAs)
QtCore.QObject.connect(self.printServiceOrderItem,
QtCore.SIGNAL(u'triggered()'),
self.ServiceManagerContents.printServiceOrder)
# i18n set signals for languages # i18n set signals for languages
QtCore.QObject.connect(self.AutoLanguageItem, QtCore.QObject.connect(self.AutoLanguageItem,
QtCore.SIGNAL(u'toggled(bool)'), self.setAutoLanguage) QtCore.SIGNAL(u'toggled(bool)'), self.setAutoLanguage)
@ -758,34 +771,29 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
""" """
Put OpenLP into "Default" view mode. Put OpenLP into "Default" view mode.
""" """
settings = QtCore.QSettings() self.setViewMode(True, True, True, True, True, u'default')
settings.setValue(u'%s/view mode' % self.generalSettingsSection,
u'default')
self.setViewMode(True, True, True, True, True)
def onModeSetupItemClicked(self): def onModeSetupItemClicked(self):
""" """
Put OpenLP into "Setup" view mode. Put OpenLP into "Setup" view mode.
""" """
settings = QtCore.QSettings() self.setViewMode(True, True, False, True, False, u'setup')
settings.setValue(u'%s/view mode' % self.generalSettingsSection,
u'setup')
self.setViewMode(True, True, False, True, False)
def onModeLiveItemClicked(self): def onModeLiveItemClicked(self):
""" """
Put OpenLP into "Live" view mode. Put OpenLP into "Live" view mode.
""" """
settings = QtCore.QSettings() self.setViewMode(False, True, False, False, True, u'live')
settings.setValue(u'%s/view mode' % self.generalSettingsSection,
u'live')
self.setViewMode(False, True, False, False, True)
def setViewMode(self, media=True, service=True, theme=True, preview=True, def setViewMode(self, media=True, service=True, theme=True, preview=True,
live=True): live=True, mode=u''):
""" """
Set OpenLP to a different view mode. Set OpenLP to a different view mode.
""" """
if mode:
settings = QtCore.QSettings()
settings.setValue(u'%s/view mode' % self.generalSettingsSection,
mode)
self.MediaManagerDock.setVisible(media) self.MediaManagerDock.setVisible(media)
self.ServiceManagerDock.setVisible(service) self.ServiceManagerDock.setVisible(service)
self.ThemeManagerDock.setVisible(theme) self.ThemeManagerDock.setVisible(theme)
@ -807,15 +815,7 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
Hook to close the main window and display windows on exit Hook to close the main window and display windows on exit
""" """
if self.ServiceManagerContents.isModified(): if self.ServiceManagerContents.isModified():
ret = QtGui.QMessageBox.question(self, ret = self.ServiceManagerContents.saveModifiedService()
translate('OpenLP.MainWindow', 'Save Changes to Service?'),
translate('OpenLP.MainWindow', 'Your service has changed. '
'Do you want to save those changes?'),
QtGui.QMessageBox.StandardButtons(
QtGui.QMessageBox.Cancel |
QtGui.QMessageBox.Discard |
QtGui.QMessageBox.Save),
QtGui.QMessageBox.Save)
if ret == QtGui.QMessageBox.Save: if ret == QtGui.QMessageBox.Save:
if self.ServiceManagerContents.saveFile(): if self.ServiceManagerContents.saveFile():
self.cleanUp() self.cleanUp()
@ -847,7 +847,6 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
self.cleanUp() self.cleanUp()
event.accept() event.accept()
def cleanUp(self): def cleanUp(self):
""" """
Runs all the cleanup code before OpenLP shuts down Runs all the cleanup code before OpenLP shuts down
@ -935,7 +934,7 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
True - Visible True - Visible
False - Hidden False - Hidden
""" """
self.previewController.Panel.setVisible(visible) self.previewController.panel.setVisible(visible)
QtCore.QSettings().setValue(u'user interface/preview panel', QtCore.QSettings().setValue(u'user interface/preview panel',
QtCore.QVariant(visible)) QtCore.QVariant(visible))
self.ViewPreviewPanel.setChecked(visible) self.ViewPreviewPanel.setChecked(visible)
@ -950,7 +949,7 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
True - Visible True - Visible
False - Hidden False - Hidden
""" """
self.liveController.Panel.setVisible(visible) self.liveController.panel.setVisible(visible)
QtCore.QSettings().setValue(u'user interface/live panel', QtCore.QSettings().setValue(u'user interface/live panel',
QtCore.QVariant(visible)) QtCore.QVariant(visible))
self.ViewLivePanel.setChecked(visible) self.ViewLivePanel.setChecked(visible)

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate, build_icon from openlp.core.lib import translate, build_icon
from openlp.core.lib.ui import save_cancel_button_box
class Ui_ServiceItemEditDialog(object): class Ui_ServiceItemEditDialog(object):
def setupUi(self, serviceItemEditDialog): def setupUi(self, serviceItemEditDialog):
@ -52,12 +53,8 @@ class Ui_ServiceItemEditDialog(object):
self.downButton.setObjectName(u'downButton') self.downButton.setObjectName(u'downButton')
self.buttonLayout.addWidget(self.downButton) self.buttonLayout.addWidget(self.downButton)
self.dialogLayout.addLayout(self.buttonLayout, 0, 1) self.dialogLayout.addLayout(self.buttonLayout, 0, 1)
self.buttonBox = QtGui.QDialogButtonBox(serviceItemEditDialog) self.dialogLayout.addWidget(
self.buttonBox.setStandardButtons( save_cancel_button_box(serviceItemEditDialog), 1, 0, 1, 2)
QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Save)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox, 1, 0, 1, 2)
self.retranslateUi(serviceItemEditDialog) self.retranslateUi(serviceItemEditDialog)
QtCore.QMetaObject.connectSlotsByName(serviceItemEditDialog) QtCore.QMetaObject.connectSlotsByName(serviceItemEditDialog)

View File

@ -46,10 +46,6 @@ class ServiceItemEditForm(QtGui.QDialog, Ui_ServiceItemEditDialog):
QtCore.SIGNAL(u'clicked()'), self.onItemDown) QtCore.SIGNAL(u'clicked()'), self.onItemDown)
QtCore.QObject.connect(self.deleteButton, QtCore.QObject.connect(self.deleteButton,
QtCore.SIGNAL(u'clicked()'), self.onItemDelete) QtCore.SIGNAL(u'clicked()'), self.onItemDelete)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'accepted()'), self.accept)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'rejected()'), self.reject)
QtCore.QObject.connect(self.listWidget, QtCore.QObject.connect(self.listWidget,
QtCore.SIGNAL(u'currentRowChanged(int)'), self.onCurrentRowChanged) QtCore.SIGNAL(u'currentRowChanged(int)'), self.onCurrentRowChanged)
@ -100,26 +96,29 @@ class ServiceItemEditForm(QtGui.QDialog, Ui_ServiceItemEditDialog):
""" """
Move the current row up in the list. Move the current row up in the list.
""" """
item = self.listWidget.currentItem() self.__moveItem(u'up')
if not item:
return
row = self.listWidget.row(item)
temp = self.itemList[row]
self.itemList.remove(self.itemList[row])
self.itemList.insert(row - 1, temp)
self.loadData()
self.listWidget.setCurrentRow(row - 1)
def onItemDown(self): def onItemDown(self):
""" """
Move the current row down in the list Move the current row down in the list
""" """
self.__moveItem(u'down')
def __moveItem(self, direction=u''):
"""
Move the current item.
"""
if not direction:
return
item = self.listWidget.currentItem() item = self.listWidget.currentItem()
if not item: if not item:
return return
row = self.listWidget.row(item) row = self.listWidget.row(item)
temp = self.itemList[row] temp = self.itemList[row]
self.itemList.remove(self.itemList[row]) self.itemList.remove(self.itemList[row])
if direction == u'up':
self.itemList.insert(row - 1, temp)
else:
self.itemList.insert(row + 1, temp) self.itemList.insert(row + 1, temp)
self.loadData() self.loadData()
self.listWidget.setCurrentRow(row + 1) self.listWidget.setCurrentRow(row + 1)

View File

@ -36,8 +36,8 @@ from PyQt4 import QtCore, QtGui
from openlp.core.lib import OpenLPToolbar, ServiceItem, context_menu_action, \ from openlp.core.lib import OpenLPToolbar, ServiceItem, context_menu_action, \
Receiver, build_icon, ItemCapabilities, SettingsManager, translate, \ Receiver, build_icon, ItemCapabilities, SettingsManager, translate, \
ThemeLevel ThemeLevel
from openlp.core.ui import criticalErrorMessageBox, ServiceNoteForm, \ from openlp.core.lib.ui import critical_error_message_box
ServiceItemEditForm from openlp.core.ui import ServiceNoteForm, ServiceItemEditForm
from openlp.core.utils import AppLocation, delete_file, file_is_unicode, \ from openlp.core.utils import AppLocation, delete_file, file_is_unicode, \
split_filename split_filename
@ -108,7 +108,7 @@ class ServiceManager(QtGui.QWidget):
translate('OpenLP.ServiceManager', 'Save Service'), translate('OpenLP.ServiceManager', 'Save Service'),
u':/general/general_save.png', u':/general/general_save.png',
translate('OpenLP.ServiceManager', 'Save this service'), translate('OpenLP.ServiceManager', 'Save this service'),
self.onSaveServiceClicked) self.saveFile)
self.toolbar.addSeparator() self.toolbar.addSeparator()
self.themeLabel = QtGui.QLabel(translate('OpenLP.ServiceManager', self.themeLabel = QtGui.QLabel(translate('OpenLP.ServiceManager',
'Theme:'), self) 'Theme:'), self)
@ -178,8 +178,8 @@ class ServiceManager(QtGui.QWidget):
translate('OpenLP.ServiceManager', 'Move &down'), translate('OpenLP.ServiceManager', 'Move &down'),
None, None,
translate('OpenLP.ServiceManager', translate('OpenLP.ServiceManager',
'Moves the selection up the window.'), 'Moves the selection down the window.'),
self.onMoveSelectionDown, shortcut=QtCore.Qt.Key_Up) self.onMoveSelectionDown, shortcut=QtCore.Qt.Key_Down)
self.serviceManagerList.down.setVisible(False) self.serviceManagerList.down.setVisible(False)
self.serviceManagerList.up = self.orderToolbar.addToolbarButton( self.serviceManagerList.up = self.orderToolbar.addToolbarButton(
translate('OpenLP.ServiceManager', 'Move up'), translate('OpenLP.ServiceManager', 'Move up'),
@ -361,12 +361,7 @@ class ServiceManager(QtGui.QWidget):
Create a new service. Create a new service.
""" """
if self.isModified(): if self.isModified():
result = QtGui.QMessageBox.question(self.mainwindow, result = self.saveModifiedService()
translate('OpenLP.ServiceManager', 'Save Changes'),
translate('OpenLP.ServiceManager', 'The current service has '
'been modified, would you like to save it?'),
QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Save)
if result == QtGui.QMessageBox.Cancel: if result == QtGui.QMessageBox.Cancel:
return False return False
elif result == QtGui.QMessageBox.Save: elif result == QtGui.QMessageBox.Save:
@ -376,12 +371,7 @@ class ServiceManager(QtGui.QWidget):
def onLoadServiceClicked(self): def onLoadServiceClicked(self):
if self.isModified(): if self.isModified():
result = QtGui.QMessageBox.question(self.mainwindow, result = self.saveModifiedService()
translate('OpenLP.ServiceManager', 'Save Changes'),
translate('OpenLP.ServiceManager', 'The current service has '
'been modified, would you like to save it?'),
QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Save)
if result == QtGui.QMessageBox.Cancel: if result == QtGui.QMessageBox.Cancel:
return False return False
elif result == QtGui.QMessageBox.Save: elif result == QtGui.QMessageBox.Save:
@ -397,11 +387,13 @@ class ServiceManager(QtGui.QWidget):
split_filename(fileName)[0]) split_filename(fileName)[0])
self.loadFile(fileName) self.loadFile(fileName)
def onSaveServiceClicked(self): def saveModifiedService(self):
self.saveFile() return QtGui.QMessageBox.question(self.mainwindow,
translate('OpenLP.ServiceManager', 'Modified Service'),
def onSaveServiceAsClicked(self): translate('OpenLP.ServiceManager', 'The current service has '
self.saveFileAs() 'been modified. Would you like to save this service?'),
QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Save)
def onRecentServiceClicked(self): def onRecentServiceClicked(self):
sender = self.sender() sender = self.sender()
@ -499,7 +491,7 @@ class ServiceManager(QtGui.QWidget):
for file in zip.namelist(): for file in zip.namelist():
ucsfile = file_is_unicode(file) ucsfile = file_is_unicode(file)
if not ucsfile: if not ucsfile:
criticalErrorMessageBox( critical_error_message_box(
message=translate('OpenLP.ServiceManager', message=translate('OpenLP.ServiceManager',
'File is not a valid service.\n' 'File is not a valid service.\n'
'The content encoding is not UTF-8.')) 'The content encoding is not UTF-8.'))
@ -514,6 +506,8 @@ class ServiceManager(QtGui.QWidget):
if filePath.endswith(u'osd'): if filePath.endswith(u'osd'):
p_file = filePath p_file = filePath
if 'p_file' in locals(): if 'p_file' in locals():
Receiver.send_message(u'cursor_busy')
Receiver.send_message(u'openlp_process_events')
fileTo = open(p_file, u'r') fileTo = open(p_file, u'r')
items = cPickle.load(fileTo) items = cPickle.load(fileTo)
fileTo.close() fileTo.close()
@ -528,13 +522,14 @@ class ServiceManager(QtGui.QWidget):
Receiver.send_message(u'%s_service_load' % Receiver.send_message(u'%s_service_load' %
serviceItem.name.lower(), serviceItem) serviceItem.name.lower(), serviceItem)
delete_file(p_file) delete_file(p_file)
Receiver.send_message(u'cursor_normal')
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('OpenLP.ServiceManager', message=translate('OpenLP.ServiceManager',
'File is not a valid service.')) 'File is not a valid service.'))
log.exception(u'File contains no service data') log.exception(u'File contains no service data')
except (IOError, NameError): except (IOError, NameError):
log.exception(u'Problem loading a service file') log.exception(u'Problem loading service file %s' % fileName)
finally: finally:
if fileTo: if fileTo:
fileTo.close() fileTo.close()
@ -544,9 +539,7 @@ class ServiceManager(QtGui.QWidget):
self.mainwindow.addRecentFile(fileName) self.mainwindow.addRecentFile(fileName)
self.setModified(False) self.setModified(False)
QtCore.QSettings(). \ QtCore.QSettings(). \
setValue(u'service/last file',QtCore.QVariant(fileName)) setValue(u'service/last file', QtCore.QVariant(fileName))
# Refresh Plugin lists
Receiver.send_message(u'plugin_list_refresh')
def loadLastFile(self): def loadLastFile(self):
""" """
@ -603,7 +596,7 @@ class ServiceManager(QtGui.QWidget):
if self.serviceNoteForm.exec_(): if self.serviceNoteForm.exec_():
self.serviceItems[item][u'service_item'].notes = \ self.serviceItems[item][u'service_item'].notes = \
self.serviceNoteForm.textEdit.toPlainText() self.serviceNoteForm.textEdit.toPlainText()
self.repaintServiceList(item, 0) self.repaintServiceList(item, -1)
def onServiceItemEditForm(self): def onServiceItemEditForm(self):
item = self.findServiceItem()[0] item = self.findServiceItem()[0]
@ -615,8 +608,7 @@ class ServiceManager(QtGui.QWidget):
def nextItem(self): def nextItem(self):
""" """
Called by the SlideController to select the Called by the SlideController to select the next service item.
next service item
""" """
if len(self.serviceManagerList.selectedItems()) == 0: if len(self.serviceManagerList.selectedItems()) == 0:
return return
@ -634,8 +626,7 @@ class ServiceManager(QtGui.QWidget):
def previousItem(self): def previousItem(self):
""" """
Called by the SlideController to select the Called by the SlideController to select the previous service item.
previous service item
""" """
if len(self.serviceManagerList.selectedItems()) == 0: if len(self.serviceManagerList.selectedItems()) == 0:
return return
@ -654,13 +645,13 @@ class ServiceManager(QtGui.QWidget):
def onSetItem(self, message): def onSetItem(self, message):
""" """
Called by a signal to select a specific item Called by a signal to select a specific item.
""" """
self.setItem(int(message[0])) self.setItem(int(message[0]))
def setItem(self, index): def setItem(self, index):
""" """
Makes a specific item in the service live Makes a specific item in the service live.
""" """
if index >= 0 and index < self.serviceManagerList.topLevelItemCount: if index >= 0 and index < self.serviceManagerList.topLevelItemCount:
item = self.serviceManagerList.topLevelItem(index) item = self.serviceManagerList.topLevelItem(index)
@ -669,8 +660,7 @@ class ServiceManager(QtGui.QWidget):
def onMoveSelectionUp(self): def onMoveSelectionUp(self):
""" """
Moves the selection up the window Moves the selection up the window. Called by the up arrow.
Called by the up arrow
""" """
serviceIterator = QtGui.QTreeWidgetItemIterator(self.serviceManagerList) serviceIterator = QtGui.QTreeWidgetItemIterator(self.serviceManagerList)
tempItem = None tempItem = None
@ -695,8 +685,7 @@ class ServiceManager(QtGui.QWidget):
def onMoveSelectionDown(self): def onMoveSelectionDown(self):
""" """
Moves the selection down the window Moves the selection down the window. Called by the down arrow.
Called by the down arrow
""" """
serviceIterator = QtGui.QTreeWidgetItemIterator(self.serviceManagerList) serviceIterator = QtGui.QTreeWidgetItemIterator(self.serviceManagerList)
firstItem = None firstItem = None
@ -718,7 +707,7 @@ class ServiceManager(QtGui.QWidget):
def onCollapseAll(self): def onCollapseAll(self):
""" """
Collapse all the service items Collapse all the service items.
""" """
for item in self.serviceItems: for item in self.serviceItems:
item[u'expanded'] = False item[u'expanded'] = False
@ -726,15 +715,15 @@ class ServiceManager(QtGui.QWidget):
def collapsed(self, item): def collapsed(self, item):
""" """
Record if an item is collapsed Record if an item is collapsed. Used when repainting the list to get the
Used when repainting the list to get the correct state correct state.
""" """
pos = item.data(0, QtCore.Qt.UserRole).toInt()[0] pos = item.data(0, QtCore.Qt.UserRole).toInt()[0]
self.serviceItems[pos -1 ][u'expanded'] = False self.serviceItems[pos -1 ][u'expanded'] = False
def onExpandAll(self): def onExpandAll(self):
""" """
Collapse all the service items Collapse all the service items.
""" """
for item in self.serviceItems: for item in self.serviceItems:
item[u'expanded'] = True item[u'expanded'] = True
@ -742,70 +731,68 @@ class ServiceManager(QtGui.QWidget):
def expanded(self, item): def expanded(self, item):
""" """
Record if an item is collapsed Record if an item is collapsed. Used when repainting the list to get the
Used when repainting the list to get the correct state correct state.
""" """
pos = item.data(0, QtCore.Qt.UserRole).toInt()[0] pos = item.data(0, QtCore.Qt.UserRole).toInt()[0]
self.serviceItems[pos -1 ][u'expanded'] = True self.serviceItems[pos -1 ][u'expanded'] = True
def onServiceTop(self): def onServiceTop(self):
""" """
Move the current ServiceItem to the top of the list Move the current ServiceItem to the top of the list.
""" """
item, count = self.findServiceItem() item, child = self.findServiceItem()
if item < len(self.serviceItems) and item is not -1: if item < len(self.serviceItems) and item is not -1:
temp = self.serviceItems[item] temp = self.serviceItems[item]
self.serviceItems.remove(self.serviceItems[item]) self.serviceItems.remove(self.serviceItems[item])
self.serviceItems.insert(0, temp) self.serviceItems.insert(0, temp)
self.repaintServiceList(0, count) self.repaintServiceList(0, child)
self.setModified(True) self.setModified(True)
def onServiceUp(self): def onServiceUp(self):
""" """
Move the current ServiceItem up in the list Move the current ServiceItem one position up in the list.
Note move up means move to top of area ie 0.
""" """
item, count = self.findServiceItem() item, child = self.findServiceItem()
if item > 0: if item > 0:
temp = self.serviceItems[item] temp = self.serviceItems[item]
self.serviceItems.remove(self.serviceItems[item]) self.serviceItems.remove(self.serviceItems[item])
self.serviceItems.insert(item - 1, temp) self.serviceItems.insert(item - 1, temp)
self.repaintServiceList(item - 1, count) self.repaintServiceList(item - 1, child)
self.setModified(True) self.setModified(True)
def onServiceDown(self): def onServiceDown(self):
""" """
Move the current ServiceItem down in the list Move the current ServiceItem one position down in the list.
Note move down means move to bottom of area i.e len().
""" """
item, count = self.findServiceItem() item, child = self.findServiceItem()
if item < len(self.serviceItems) and item is not -1: if item < len(self.serviceItems) and item is not -1:
temp = self.serviceItems[item] temp = self.serviceItems[item]
self.serviceItems.remove(self.serviceItems[item]) self.serviceItems.remove(self.serviceItems[item])
self.serviceItems.insert(item + 1, temp) self.serviceItems.insert(item + 1, temp)
self.repaintServiceList(item + 1, count) self.repaintServiceList(item + 1, child)
self.setModified(True) self.setModified(True)
def onServiceEnd(self): def onServiceEnd(self):
""" """
Move the current ServiceItem to the bottom of the list Move the current ServiceItem to the bottom of the list.
""" """
item, count = self.findServiceItem() item, child = self.findServiceItem()
if item < len(self.serviceItems) and item is not -1: if item < len(self.serviceItems) and item is not -1:
temp = self.serviceItems[item] temp = self.serviceItems[item]
self.serviceItems.remove(self.serviceItems[item]) self.serviceItems.remove(self.serviceItems[item])
self.serviceItems.insert(len(self.serviceItems), temp) self.serviceItems.insert(len(self.serviceItems), temp)
self.repaintServiceList(len(self.serviceItems) - 1, count) self.repaintServiceList(len(self.serviceItems) - 1, child)
self.setModified(True) self.setModified(True)
def onDeleteFromService(self): def onDeleteFromService(self):
""" """
Remove the current ServiceItem from the list Remove the current ServiceItem from the list.
""" """
item = self.findServiceItem()[0] item = self.findServiceItem()[0]
if item is not -1: if item != -1:
self.serviceItems.remove(self.serviceItems[item]) self.serviceItems.remove(self.serviceItems[item])
self.repaintServiceList(0, 0) self.repaintServiceList(item - 1, -1)
self.setModified(True) self.setModified(True)
def repaintServiceList(self, serviceItem, serviceItemChild): def repaintServiceList(self, serviceItem, serviceItemChild):
@ -847,7 +834,7 @@ class ServiceManager(QtGui.QWidget):
else: else:
treewidgetitem.setIcon(0, treewidgetitem.setIcon(0,
build_icon(u':/general/general_delete.png')) build_icon(u':/general/general_delete.png'))
treewidgetitem.setText(0, serviceitem.title) treewidgetitem.setText(0, serviceitem.get_display_title())
treewidgetitem.setToolTip(0, serviceitem.notes) treewidgetitem.setToolTip(0, serviceitem.notes)
treewidgetitem.setData(0, QtCore.Qt.UserRole, treewidgetitem.setData(0, QtCore.Qt.UserRole,
QtCore.QVariant(item[u'order'])) QtCore.QVariant(item[u'order']))
@ -867,16 +854,16 @@ class ServiceManager(QtGui.QWidget):
def validateItem(self, serviceItem): def validateItem(self, serviceItem):
""" """
Validates the service item and if the suffix matches an accepted Validates the service item and if the suffix matches an accepted
one it allows the item to be displayed one it allows the item to be displayed.
""" """
if serviceItem.is_command(): if serviceItem.is_command():
type = serviceItem._raw_frames[0][u'title'].split(u'.')[1] type = serviceItem._raw_frames[0][u'title'].split(u'.')[-1]
if type not in self.suffixes: if type not in self.suffixes:
serviceItem.is_valid = False serviceItem.is_valid = False
def cleanUp(self): def cleanUp(self):
""" """
Empties the servicePath of temporary files Empties the servicePath of temporary files.
""" """
for file in os.listdir(self.servicePath): for file in os.listdir(self.servicePath):
file_path = os.path.join(self.servicePath, file) file_path = os.path.join(self.servicePath, file)
@ -884,7 +871,7 @@ class ServiceManager(QtGui.QWidget):
def onThemeComboBoxSelected(self, currentIndex): def onThemeComboBoxSelected(self, currentIndex):
""" """
Set the theme for the current service Set the theme for the current service.
""" """
log.debug(u'onThemeComboBoxSelected') log.debug(u'onThemeComboBoxSelected')
self.service_theme = unicode(self.themeComboBox.currentText()) self.service_theme = unicode(self.themeComboBox.currentText())
@ -967,12 +954,12 @@ class ServiceManager(QtGui.QWidget):
# if not passed set to config value # if not passed set to config value
if expand is None: if expand is None:
expand = self.expandTabs expand = self.expandTabs
sitem = self.findServiceItem()[0]
item.render() item.render()
if replace: if replace:
sitem, child = self.findServiceItem()
item.merge(self.serviceItems[sitem][u'service_item']) item.merge(self.serviceItems[sitem][u'service_item'])
self.serviceItems[sitem][u'service_item'] = item self.serviceItems[sitem][u'service_item'] = item
self.repaintServiceList(sitem, 0) self.repaintServiceList(sitem, child)
self.mainwindow.liveController.replaceServiceManagerItem(item) self.mainwindow.liveController.replaceServiceManagerItem(item)
else: else:
# nothing selected for dnd # nothing selected for dnd
@ -981,17 +968,17 @@ class ServiceManager(QtGui.QWidget):
for inditem in item: for inditem in item:
self.serviceItems.append({u'service_item': inditem, self.serviceItems.append({u'service_item': inditem,
u'order': len(self.serviceItems) + 1, u'order': len(self.serviceItems) + 1,
u'expanded':expand}) u'expanded': expand})
else: else:
self.serviceItems.append({u'service_item': item, self.serviceItems.append({u'service_item': item,
u'order': len(self.serviceItems) + 1, u'order': len(self.serviceItems) + 1,
u'expanded':expand}) u'expanded': expand})
self.repaintServiceList(len(self.serviceItems) + 1, 0) self.repaintServiceList(len(self.serviceItems) - 1, -1)
else: else:
self.serviceItems.insert(self.dropPosition, self.serviceItems.insert(self.dropPosition,
{u'service_item': item, u'order': self.dropPosition, {u'service_item': item, u'order': self.dropPosition,
u'expanded':expand}) u'expanded': expand})
self.repaintServiceList(self.dropPosition, 0) self.repaintServiceList(self.dropPosition, -1)
# if rebuilding list make sure live is fixed. # if rebuilding list make sure live is fixed.
if rebuild: if rebuild:
self.mainwindow.liveController.replaceServiceManagerItem(item) self.mainwindow.liveController.replaceServiceManagerItem(item)
@ -1002,12 +989,12 @@ class ServiceManager(QtGui.QWidget):
""" """
Send the current item to the Preview slide controller Send the current item to the Preview slide controller
""" """
item, count = self.findServiceItem() item, child = self.findServiceItem()
if self.serviceItems[item][u'service_item'].is_valid: if self.serviceItems[item][u'service_item'].is_valid:
self.mainwindow.previewController.addServiceManagerItem( self.mainwindow.previewController.addServiceManagerItem(
self.serviceItems[item][u'service_item'], count) self.serviceItems[item][u'service_item'], child)
else: else:
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ServiceManager', 'Missing Display Handler'), translate('OpenLP.ServiceManager', 'Missing Display Handler'),
translate('OpenLP.ServiceManager', 'Your item cannot be ' translate('OpenLP.ServiceManager', 'Your item cannot be '
'displayed as there is no handler to display it')) 'displayed as there is no handler to display it'))
@ -1026,10 +1013,10 @@ class ServiceManager(QtGui.QWidget):
""" """
Send the current item to the Live slide controller Send the current item to the Live slide controller
""" """
item, count = self.findServiceItem() item, child = self.findServiceItem()
if self.serviceItems[item][u'service_item'].is_valid: if self.serviceItems[item][u'service_item'].is_valid:
self.mainwindow.liveController.addServiceManagerItem( self.mainwindow.liveController.addServiceManagerItem(
self.serviceItems[item][u'service_item'], count) self.serviceItems[item][u'service_item'], child)
if QtCore.QSettings().value( if QtCore.QSettings().value(
self.mainwindow.generalSettingsSection + u'/auto preview', self.mainwindow.generalSettingsSection + u'/auto preview',
QtCore.QVariant(False)).toBool(): QtCore.QVariant(False)).toBool():
@ -1041,7 +1028,7 @@ class ServiceManager(QtGui.QWidget):
self.serviceItems[item][u'service_item'], 0) self.serviceItems[item][u'service_item'], 0)
self.mainwindow.liveController.previewListWidget.setFocus() self.mainwindow.liveController.previewListWidget.setFocus()
else: else:
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ServiceManager', 'Missing Display Handler'), translate('OpenLP.ServiceManager', 'Missing Display Handler'),
translate('OpenLP.ServiceManager', 'Your item cannot be ' translate('OpenLP.ServiceManager', 'Your item cannot be '
'displayed as the plugin required to display it is missing ' 'displayed as the plugin required to display it is missing '
@ -1060,26 +1047,26 @@ class ServiceManager(QtGui.QWidget):
def findServiceItem(self): def findServiceItem(self):
""" """
Finds a ServiceItem in the list and returns the position of the Finds the selected ServiceItem in the list and returns the position of
serviceitem and its selected child item. For example, if the third child the serviceitem and its selected child item. For example, if the third
item (in the Slidecontroller known as slide) in the second service item child item (in the Slidecontroller known as slide) in the second service
is selected this will return:: item is selected this will return::
(1, 2) (1, 2)
""" """
items = self.serviceManagerList.selectedItems() items = self.serviceManagerList.selectedItems()
pos = 0 serviceItem = 0
count = -1 serviceItemChild = -1
for item in items: for item in items:
parentitem = item.parent() parentitem = item.parent()
if parentitem is None: if parentitem is None:
pos = item.data(0, QtCore.Qt.UserRole).toInt()[0] serviceItem = item.data(0, QtCore.Qt.UserRole).toInt()[0]
else: else:
pos = parentitem.data(0, QtCore.Qt.UserRole).toInt()[0] serviceItem = parentitem.data(0, QtCore.Qt.UserRole).toInt()[0]
count = item.data(0, QtCore.Qt.UserRole).toInt()[0] serviceItemChild = item.data(0, QtCore.Qt.UserRole).toInt()[0]
# adjust for zero based arrays # Adjust for zero based arrays.
pos = pos - 1 serviceItem -= 1
return pos, count return serviceItem, serviceItemChild
def dragEnterEvent(self, event): def dragEnterEvent(self, event):
""" """
@ -1105,7 +1092,7 @@ class ServiceManager(QtGui.QWidget):
item = self.serviceManagerList.itemAt(event.pos()) item = self.serviceManagerList.itemAt(event.pos())
# ServiceManager started the drag and drop # ServiceManager started the drag and drop
if plugin == u'ServiceManager': if plugin == u'ServiceManager':
startpos, startCount = self.findServiceItem() startpos, child = self.findServiceItem()
# If no items selected # If no items selected
if startpos == -1: if startpos == -1:
return return
@ -1116,7 +1103,7 @@ class ServiceManager(QtGui.QWidget):
serviceItem = self.serviceItems[startpos] serviceItem = self.serviceItems[startpos]
self.serviceItems.remove(serviceItem) self.serviceItems.remove(serviceItem)
self.serviceItems.insert(endpos, serviceItem) self.serviceItems.insert(endpos, serviceItem)
self.repaintServiceList(endpos, startCount) self.repaintServiceList(endpos, child)
else: else:
# we are not over anything so drop # we are not over anything so drop
replace = False replace = False
@ -1182,17 +1169,60 @@ class ServiceManager(QtGui.QWidget):
def listRequest(self, message=None): def listRequest(self, message=None):
data = [] data = []
curindex = self.findServiceItem()[0] item = self.findServiceItem()[0]
if curindex >= 0 and curindex < len(self.serviceItems): if item >= 0 and item < len(self.serviceItems):
curitem = self.serviceItems[curindex] curitem = self.serviceItems[item]
else: else:
curitem = None curitem = None
for item in self.serviceItems: for item in self.serviceItems:
service_item = item[u'service_item'] service_item = item[u'service_item']
data_item = {} data_item = {}
data_item[u'title'] = unicode(service_item.title) data_item[u'title'] = unicode(service_item.get_display_title())
data_item[u'plugin'] = unicode(service_item.name) data_item[u'plugin'] = unicode(service_item.name)
data_item[u'notes'] = unicode(service_item.notes) data_item[u'notes'] = unicode(service_item.notes)
data_item[u'selected'] = (item == curitem) data_item[u'selected'] = (item == curitem)
data.append(data_item) data.append(data_item)
Receiver.send_message(u'servicemanager_list_response', data) Receiver.send_message(u'servicemanager_list_response', data)
def printServiceOrder(self):
"""
Print a Service Order Sheet.
"""
if not self.serviceItems:
critical_error_message_box(
message=translate('OpenLP.ServiceManager',
'There is no service item in this service.'))
return
printDialog = QtGui.QPrintDialog()
if not printDialog.exec_():
return
text = u'<h2>%s</h2>' % translate('OpenLP.ServiceManager',
'Service Order Sheet')
for item in self.serviceItems:
item = item[u'service_item']
# add the title
text += u'<h4><img src="%s" /> %s</h4>' % (item.icon,
item.get_display_title())
if not QtCore.QSettings().value(u'advanced' +
u'/detailed service print', QtCore.QVariant(True)).toBool():
continue
if item.is_text():
# Add the text of the service item.
for slide in item.get_frames():
text += u'<p>' + slide[u'text'] + u'</p>'
elif item.is_image():
# Add the image names of the service item.
text += u'<ol>'
for slide in range(len(item.get_frames())):
text += u'<li><p>%s</p></li>' % item.get_frame_title(slide)
text += u'</ol>'
if item.foot_text:
# add footer
text += u'<p>%s</p>' % item.foot_text
if item.notes:
# add notes
text += u'<p><b>%s</b> %s</p>' % (translate(
'OpenLP.ServiceManager', 'Notes:'), item.notes)
serviceDocument = QtGui.QTextDocument()
serviceDocument.setHtml(text)
serviceDocument.print_(printDialog.printer())

View File

@ -1,48 +0,0 @@
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
# Copyright (c) 2008-2011 Raoul Snyman #
# Portions copyright (c) 2008-2011 Tim Bentley, Jonathan Corwin, Michael #
# Gorven, Scott Guerrieri, Meinert Jordan, Andreas Preikschat, Christian #
# Richter, Philip Ridout, Maikel Stuivenberg, Martin Thompson, Jon Tibble, #
# Carsten Tinggaard, Frode Woldsund #
# --------------------------------------------------------------------------- #
# 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 #
###############################################################################
from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate
class Ui_ServiceNoteEdit(object):
def setupUi(self, serviceNoteEdit):
serviceNoteEdit.setObjectName(u'serviceNoteEdit')
self.dialogLayout = QtGui.QVBoxLayout(serviceNoteEdit)
self.dialogLayout.setObjectName(u'verticalLayout')
self.textEdit = QtGui.QTextEdit(serviceNoteEdit)
self.textEdit.setObjectName(u'textEdit')
self.dialogLayout.addWidget(self.textEdit)
self.buttonBox = QtGui.QDialogButtonBox(serviceNoteEdit)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel |
QtGui.QDialogButtonBox.Save)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(serviceNoteEdit)
QtCore.QMetaObject.connectSlotsByName(serviceNoteEdit)
def retranslateUi(self, serviceNoteEdit):
serviceNoteEdit.setWindowTitle(
translate('OpenLP.ServiceNoteForm', 'Service Item Notes'))

View File

@ -26,9 +26,10 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from servicenotedialog import Ui_ServiceNoteEdit from openlp.core.lib import translate
from openlp.core.lib.ui import save_cancel_button_box
class ServiceNoteForm(QtGui.QDialog, Ui_ServiceNoteEdit): class ServiceNoteForm(QtGui.QDialog):
""" """
This is the form that is used to edit the verses of the song. This is the form that is used to edit the verses of the song.
""" """
@ -37,8 +38,19 @@ class ServiceNoteForm(QtGui.QDialog, Ui_ServiceNoteEdit):
Constructor Constructor
""" """
QtGui.QDialog.__init__(self, parent) QtGui.QDialog.__init__(self, parent)
self.setupUi(self) self.setupUi()
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'accepted()'), self.retranslateUi()
self.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'rejected()'), def setupUi(self):
self.reject) self.setObjectName(u'serviceNoteEdit')
self.dialogLayout = QtGui.QVBoxLayout(self)
self.dialogLayout.setObjectName(u'verticalLayout')
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.setObjectName(u'textEdit')
self.dialogLayout.addWidget(self.textEdit)
self.dialogLayout.addWidget(save_cancel_button_box(self))
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self):
self.setWindowTitle(
translate('OpenLP.ServiceNoteForm', 'Service Item Notes'))

View File

@ -77,14 +77,14 @@ class SlideController(QtGui.QWidget):
self.selectedRow = 0 self.selectedRow = 0
self.serviceItem = None self.serviceItem = None
self.alertTab = None self.alertTab = None
self.Panel = QtGui.QWidget(parent.ControlSplitter) self.panel = QtGui.QWidget(parent.ControlSplitter)
self.slideList = {} self.slideList = {}
# Layout for holding panel # Layout for holding panel
self.panelLayout = QtGui.QVBoxLayout(self.Panel) self.panelLayout = QtGui.QVBoxLayout(self.panel)
self.panelLayout.setSpacing(0) self.panelLayout.setSpacing(0)
self.panelLayout.setMargin(0) self.panelLayout.setMargin(0)
# Type label for the top of the slide controller # Type label for the top of the slide controller
self.typeLabel = QtGui.QLabel(self.Panel) self.typeLabel = QtGui.QLabel(self.panel)
if self.isLive: if self.isLive:
self.typeLabel.setText(translate('OpenLP.SlideController', 'Live')) self.typeLabel.setText(translate('OpenLP.SlideController', 'Live'))
self.split = 1 self.split = 1
@ -98,7 +98,7 @@ class SlideController(QtGui.QWidget):
self.typeLabel.setAlignment(QtCore.Qt.AlignCenter) self.typeLabel.setAlignment(QtCore.Qt.AlignCenter)
self.panelLayout.addWidget(self.typeLabel) self.panelLayout.addWidget(self.typeLabel)
# Splitter # Splitter
self.splitter = QtGui.QSplitter(self.Panel) self.splitter = QtGui.QSplitter(self.panel)
self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setOrientation(QtCore.Qt.Vertical)
self.panelLayout.addWidget(self.splitter) self.panelLayout.addWidget(self.splitter)
# Actual controller section # Actual controller section
@ -119,6 +119,8 @@ class SlideController(QtGui.QWidget):
self.previewListWidget.isLive = self.isLive self.previewListWidget.isLive = self.isLive
self.previewListWidget.setObjectName(u'PreviewListWidget') self.previewListWidget.setObjectName(u'PreviewListWidget')
self.previewListWidget.setSelectionBehavior(1) self.previewListWidget.setSelectionBehavior(1)
self.previewListWidget.setSelectionMode(
QtGui.QAbstractItemView.SingleSelection)
self.previewListWidget.setEditTriggers( self.previewListWidget.setEditTriggers(
QtGui.QAbstractItemView.NoEditTriggers) QtGui.QAbstractItemView.NoEditTriggers)
self.previewListWidget.setHorizontalScrollBarPolicy( self.previewListWidget.setHorizontalScrollBarPolicy(
@ -183,13 +185,13 @@ class SlideController(QtGui.QWidget):
u'Stop Loop', u':/media/media_stop.png', u'Stop Loop', u':/media/media_stop.png',
translate('OpenLP.SlideController', 'Stop continuous loop'), translate('OpenLP.SlideController', 'Stop continuous loop'),
self.onStopLoop) self.onStopLoop)
self.DelaySpinBox = QtGui.QSpinBox() self.delaySpinBox = QtGui.QSpinBox()
self.DelaySpinBox.setMinimum(1) self.delaySpinBox.setMinimum(1)
self.DelaySpinBox.setMaximum(180) self.delaySpinBox.setMaximum(180)
self.toolbar.addToolbarWidget(u'Image SpinBox', self.DelaySpinBox) self.toolbar.addToolbarWidget(u'Image SpinBox', self.delaySpinBox)
self.DelaySpinBox.setSuffix(translate('OpenLP.SlideController', self.delaySpinBox.setSuffix(translate('OpenLP.SlideController',
's')) 's'))
self.DelaySpinBox.setToolTip(translate('OpenLP.SlideController', self.delaySpinBox.setToolTip(translate('OpenLP.SlideController',
'Delay between slides in seconds')) 'Delay between slides in seconds'))
else: else:
self.toolbar.addToolbarSeparator(u'Close Separator') self.toolbar.addToolbarSeparator(u'Close Separator')
@ -480,18 +482,11 @@ class SlideController(QtGui.QWidget):
def onSongBarHandler(self): def onSongBarHandler(self):
request = unicode(self.sender().text()) request = unicode(self.sender().text())
slideno = self.slideList[request] slideno = self.slideList[request]
if slideno > self.previewListWidget.rowCount(): self.__updatePreviewSelection(slideno)
self.previewListWidget.selectRow(
self.previewListWidget.rowCount() - 1)
else:
if slideno + 1 < self.previewListWidget.rowCount():
self.previewListWidget.scrollToItem(
self.previewListWidget.item(slideno + 1, 0))
self.previewListWidget.selectRow(slideno)
self.onSlideSelected() self.onSlideSelected()
def receiveSpinDelay(self, value): def receiveSpinDelay(self, value):
self.DelaySpinBox.setValue(int(value)) self.delaySpinBox.setValue(int(value))
def enableToolBar(self, item): def enableToolBar(self, item):
""" """
@ -663,14 +658,7 @@ class SlideController(QtGui.QWidget):
self.previewListWidget.resizeRowsToContents() self.previewListWidget.resizeRowsToContents()
self.previewListWidget.setColumnWidth(0, self.previewListWidget.setColumnWidth(0,
self.previewListWidget.viewport().size().width()) self.previewListWidget.viewport().size().width())
if slideno > self.previewListWidget.rowCount(): self.__updatePreviewSelection(slideno)
self.previewListWidget.selectRow(
self.previewListWidget.rowCount() - 1)
else:
if slideno + 1 < self.previewListWidget.rowCount():
self.previewListWidget.scrollToItem(
self.previewListWidget.item(slideno + 1, 0))
self.previewListWidget.selectRow(slideno)
self.enableToolBar(serviceItem) self.enableToolBar(serviceItem)
# Pass to display for viewing # Pass to display for viewing
self.display.buildHtml(self.serviceItem) self.display.buildHtml(self.serviceItem)
@ -681,6 +669,19 @@ class SlideController(QtGui.QWidget):
Receiver.send_message(u'slidecontroller_%s_started' % self.typePrefix, Receiver.send_message(u'slidecontroller_%s_started' % self.typePrefix,
[serviceItem]) [serviceItem])
def __updatePreviewSelection(self, slideno):
"""
Utility method to update the selected slide in the list.
"""
if slideno > self.previewListWidget.rowCount():
self.previewListWidget.selectRow(
self.previewListWidget.rowCount() - 1)
else:
if slideno + 1 < self.previewListWidget.rowCount():
self.previewListWidget.scrollToItem(
self.previewListWidget.item(slideno + 1, 0))
self.previewListWidget.selectRow(slideno)
def onTextRequest(self): def onTextRequest(self):
""" """
Return the text for the current item in controller Return the text for the current item in controller
@ -997,7 +998,7 @@ class SlideController(QtGui.QWidget):
""" """
if self.previewListWidget.rowCount() > 1: if self.previewListWidget.rowCount() > 1:
self.timer_id = self.startTimer( self.timer_id = self.startTimer(
int(self.DelaySpinBox.value()) * 1000) int(self.delaySpinBox.value()) * 1000)
self.toolbar.actions[u'Stop Loop'].setVisible(True) self.toolbar.actions[u'Stop Loop'].setVisible(True)
self.toolbar.actions[u'Start Loop'].setVisible(False) self.toolbar.actions[u'Start Loop'].setVisible(False)

View File

@ -31,7 +31,7 @@ from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate, BackgroundType, BackgroundGradientType, \ from openlp.core.lib import translate, BackgroundType, BackgroundGradientType, \
Receiver Receiver
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.core.utils import get_images_filter from openlp.core.utils import get_images_filter
from themewizard import Ui_ThemeWizard from themewizard import Ui_ThemeWizard
@ -55,7 +55,6 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
self.thememanager = parent self.thememanager = parent
self.setupUi(self) self.setupUi(self)
self.registerFields() self.registerFields()
self.accepted = False
self.updateThemeAllowed = True self.updateThemeAllowed = True
QtCore.QObject.connect(self.backgroundComboBox, QtCore.QObject.connect(self.backgroundComboBox,
QtCore.SIGNAL(u'currentIndexChanged(int)'), QtCore.SIGNAL(u'currentIndexChanged(int)'),
@ -120,14 +119,12 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
QtCore.QObject.connect(self.mainFontComboBox, QtCore.QObject.connect(self.mainFontComboBox,
QtCore.SIGNAL(u'activated(int)'), QtCore.SIGNAL(u'activated(int)'),
self.calculateLines) self.calculateLines)
QtCore.QObject.connect(self, QtCore.SIGNAL(u'accepted()'), self.accept)
def setDefaults(self): def setDefaults(self):
""" """
Set up display at start of theme edit. Set up display at start of theme edit.
""" """
self.restart() self.restart()
self.accepted = False
self.setBackgroundPageValues() self.setBackgroundPageValues()
self.setMainAreaPageValues() self.setMainAreaPageValues()
self.setFooterAreaPageValues() self.setFooterAreaPageValues()
@ -250,6 +247,7 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
""" """
Change state as Outline check box changed Change state as Outline check box changed
""" """
if self.updateThemeAllowed:
if state == QtCore.Qt.Checked: if state == QtCore.Qt.Checked:
self.theme.font_main_outline = True self.theme.font_main_outline = True
else: else:
@ -262,6 +260,7 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
""" """
Change state as Shadow check box changed Change state as Shadow check box changed
""" """
if self.updateThemeAllowed:
if state == QtCore.Qt.Checked: if state == QtCore.Qt.Checked:
self.theme.font_main_shadow = True self.theme.font_main_shadow = True
else: else:
@ -273,14 +272,18 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
def onMainPositionCheckBoxStateChanged(self, value): def onMainPositionCheckBoxStateChanged(self, value):
""" """
Change state as Main Area Position check box changed Change state as Main Area Position check box changed
NOTE the font_main_override is the inverse of the check box value
""" """
self.theme.font_main_override = (value == QtCore.Qt.Checked) if self.updateThemeAllowed:
self.theme.font_main_override = not (value == QtCore.Qt.Checked)
def onFooterPositionCheckBoxStateChanged(self, value): def onFooterPositionCheckBoxStateChanged(self, value):
""" """
Change state as Footer Area Position check box changed Change state as Footer Area Position check box changed
NOTE the font_footer_override is the inverse of the check box value
""" """
self.theme.font_footer_override = (value == QtCore.Qt.Checked) if self.updateThemeAllowed:
self.theme.font_footer_override = not (value == QtCore.Qt.Checked)
def exec_(self, edit=False): def exec_(self, edit=False):
""" """
@ -446,6 +449,7 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
""" """
Background gradient Combo box has changed. Background gradient Combo box has changed.
""" """
if self.updateThemeAllowed:
self.theme.background_direction = \ self.theme.background_direction = \
BackgroundGradientType.to_string(index) BackgroundGradientType.to_string(index)
self.setBackgroundPageValues() self.setBackgroundPageValues()
@ -560,21 +564,16 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
""" """
Lets save the them as Finish has been pressed Lets save the them as Finish has been pressed
""" """
# Some reason getting double submission.
# Hack to stop it for now.
if self.accepted:
return
# Save the theme name # Save the theme name
self.theme.theme_name = \ self.theme.theme_name = unicode(self.field(u'name').toString())
unicode(self.field(u'name').toString())
if not self.theme.theme_name: if not self.theme.theme_name:
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ThemeForm', 'Theme Name Missing'), translate('OpenLP.ThemeForm', 'Theme Name Missing'),
translate('OpenLP.ThemeForm', translate('OpenLP.ThemeForm',
'There is no name for this theme. Please enter one.')) 'There is no name for this theme. Please enter one.'))
return return
if self.theme.theme_name == u'-1' or self.theme.theme_name == u'None': if self.theme.theme_name == u'-1' or self.theme.theme_name == u'None':
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ThemeForm', 'Theme Name Invalid'), translate('OpenLP.ThemeForm', 'Theme Name Invalid'),
translate('OpenLP.ThemeForm', translate('OpenLP.ThemeForm',
'Invalid theme name. Please enter one.')) 'Invalid theme name. Please enter one.'))
@ -590,7 +589,6 @@ class ThemeForm(QtGui.QWizard, Ui_ThemeWizard):
if not self.edit_mode and \ if not self.edit_mode and \
not self.thememanager.checkIfThemeExists(self.theme.theme_name): not self.thememanager.checkIfThemeExists(self.theme.theme_name):
return return
self.accepted = True
self.thememanager.saveTheme(self.theme, saveFrom, saveTo) self.thememanager.saveTheme(self.theme, saveFrom, saveTo)
return QtGui.QDialog.accept(self) return QtGui.QDialog.accept(self)

View File

@ -32,11 +32,12 @@ import logging
from xml.etree.ElementTree import ElementTree, XML from xml.etree.ElementTree import ElementTree, XML
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.ui import criticalErrorMessageBox, FileRenameForm, ThemeForm
from openlp.core.theme import Theme
from openlp.core.lib import OpenLPToolbar, ThemeXML, get_text_file_string, \ from openlp.core.lib import OpenLPToolbar, ThemeXML, get_text_file_string, \
build_icon, Receiver, SettingsManager, translate, check_item_selected, \ build_icon, Receiver, SettingsManager, translate, check_item_selected, \
BackgroundType, BackgroundGradientType, check_directory_exists BackgroundType, BackgroundGradientType, check_directory_exists
from openlp.core.lib.ui import critical_error_message_box
from openlp.core.theme import Theme
from openlp.core.ui import FileRenameForm, ThemeForm
from openlp.core.utils import AppLocation, delete_file, file_is_unicode, \ from openlp.core.utils import AppLocation, delete_file, file_is_unicode, \
get_filesystem_encoding get_filesystem_encoding
@ -359,7 +360,7 @@ class ThemeManager(QtGui.QWidget):
""" """
item = self.themeListWidget.currentItem() item = self.themeListWidget.currentItem()
if item is None: if item is None:
criticalErrorMessageBox(message=translate('OpenLP.ThemeManager', critical_error_message_box(message=translate('OpenLP.ThemeManager',
'You have not selected a theme.')) 'You have not selected a theme.'))
return return
theme = unicode(item.data(QtCore.Qt.UserRole).toString()) theme = unicode(item.data(QtCore.Qt.UserRole).toString())
@ -386,7 +387,7 @@ class ThemeManager(QtGui.QWidget):
'Your theme has been successfully exported.')) 'Your theme has been successfully exported.'))
except (IOError, OSError): except (IOError, OSError):
log.exception(u'Export Theme Failed') log.exception(u'Export Theme Failed')
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ThemeManager', 'Theme Export Failed'), translate('OpenLP.ThemeManager', 'Theme Export Failed'),
translate('OpenLP.ThemeManager', translate('OpenLP.ThemeManager',
'Your theme could not be exported due to an error.')) 'Your theme could not be exported due to an error.'))
@ -496,7 +497,7 @@ class ThemeManager(QtGui.QWidget):
for file in zip.namelist(): for file in zip.namelist():
ucsfile = file_is_unicode(file) ucsfile = file_is_unicode(file)
if not ucsfile: if not ucsfile:
criticalErrorMessageBox( critical_error_message_box(
message=translate('OpenLP.ThemeManager', message=translate('OpenLP.ThemeManager',
'File is not a valid theme.\n' 'File is not a valid theme.\n'
'The content encoding is not UTF-8.')) 'The content encoding is not UTF-8.'))
@ -531,14 +532,14 @@ class ThemeManager(QtGui.QWidget):
theme = self._createThemeFromXml(filexml, self.path) theme = self._createThemeFromXml(filexml, self.path)
self.generateAndSaveImage(dir, themename, theme) self.generateAndSaveImage(dir, themename, theme)
else: else:
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ThemeManager', 'Validation Error'), translate('OpenLP.ThemeManager', 'Validation Error'),
translate('OpenLP.ThemeManager', translate('OpenLP.ThemeManager',
'File is not a valid theme.')) 'File is not a valid theme.'))
log.exception(u'Theme file does not contain XML data %s' % log.exception(u'Theme file does not contain XML data %s' %
filename) filename)
except (IOError, NameError): except (IOError, NameError):
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ThemeManager', 'Validation Error'), translate('OpenLP.ThemeManager', 'Validation Error'),
translate('OpenLP.ThemeManager', translate('OpenLP.ThemeManager',
'File is not a valid theme.')) 'File is not a valid theme.'))
@ -558,7 +559,7 @@ class ThemeManager(QtGui.QWidget):
""" """
theme_dir = os.path.join(self.path, themeName) theme_dir = os.path.join(self.path, themeName)
if os.path.exists(theme_dir): if os.path.exists(theme_dir):
criticalErrorMessageBox( critical_error_message_box(
translate('OpenLP.ThemeManager', 'Validation Error'), translate('OpenLP.ThemeManager', 'Validation Error'),
translate('OpenLP.ThemeManager', translate('OpenLP.ThemeManager',
'A theme with this name already exists.')) 'A theme with this name already exists.'))
@ -688,7 +689,7 @@ class ThemeManager(QtGui.QWidget):
return False return False
# should be the same unless default # should be the same unless default
if theme != unicode(item.data(QtCore.Qt.UserRole).toString()): if theme != unicode(item.data(QtCore.Qt.UserRole).toString()):
criticalErrorMessageBox( critical_error_message_box(
message=translate('OpenLP.ThemeManager', message=translate('OpenLP.ThemeManager',
'You are unable to delete the default theme.')) 'You are unable to delete the default theme.'))
return False return False
@ -696,7 +697,8 @@ class ThemeManager(QtGui.QWidget):
if testPlugin: if testPlugin:
for plugin in self.mainwindow.pluginManager.plugins: for plugin in self.mainwindow.pluginManager.plugins:
if plugin.usesTheme(theme): if plugin.usesTheme(theme):
criticalErrorMessageBox(translate('OpenLP.ThemeManager', critical_error_message_box(
translate('OpenLP.ThemeManager',
'Validation Error'), 'Validation Error'),
unicode(translate('OpenLP.ThemeManager', unicode(translate('OpenLP.ThemeManager',
'Theme %s is used in the %s plugin.')) % \ 'Theme %s is used in the %s plugin.')) % \

View File

@ -165,13 +165,7 @@ class ThemesTab(SettingsTab):
self.global_theme = unicode(self.DefaultComboBox.currentText()) self.global_theme = unicode(self.DefaultComboBox.currentText())
self.parent.renderManager.set_global_theme( self.parent.renderManager.set_global_theme(
self.global_theme, self.theme_level) self.global_theme, self.theme_level)
image = self.parent.ThemeManagerContents.getPreviewImage( self.__previewGlobalTheme()
self.global_theme)
preview = QtGui.QPixmap(unicode(image))
if not preview.isNull():
preview = preview.scaled(300, 255, QtCore.Qt.KeepAspectRatio,
QtCore.Qt.SmoothTransformation)
self.DefaultListView.setPixmap(preview)
def updateThemeList(self, theme_list): def updateThemeList(self, theme_list):
""" """
@ -198,6 +192,12 @@ class ThemesTab(SettingsTab):
self.parent.renderManager.set_global_theme( self.parent.renderManager.set_global_theme(
self.global_theme, self.theme_level) self.global_theme, self.theme_level)
if self.global_theme is not u'': if self.global_theme is not u'':
self.__previewGlobalTheme()
def __previewGlobalTheme(self):
"""
Utility method to update the global theme preview image.
"""
image = self.parent.ThemeManagerContents.getPreviewImage( image = self.parent.ThemeManagerContents.getPreviewImage(
self.global_theme) self.global_theme)
preview = QtGui.QPixmap(unicode(image)) preview = QtGui.QPixmap(unicode(image))

View File

@ -27,32 +27,17 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate, build_icon from openlp.core.lib import translate, build_icon
from openlp.core.lib.ui import add_welcome_page
class Ui_ThemeWizard(object): class Ui_ThemeWizard(object):
def setupUi(self, ThemeWizard): def setupUi(self, themeWizard):
ThemeWizard.setObjectName(u'OpenLP.ThemeWizard') themeWizard.setObjectName(u'OpenLP.ThemeWizard')
ThemeWizard.setModal(True) themeWizard.setModal(True)
ThemeWizard.setWizardStyle(QtGui.QWizard.ModernStyle) themeWizard.setWizardStyle(QtGui.QWizard.ModernStyle)
ThemeWizard.setOptions( themeWizard.setOptions(QtGui.QWizard.IndependentPages |
QtGui.QWizard.IndependentPages |
QtGui.QWizard.NoBackButtonOnStartPage) QtGui.QWizard.NoBackButtonOnStartPage)
# Welcome Page # Welcome Page
self.welcomePage = QtGui.QWizardPage() add_welcome_page(themeWizard, u':/wizards/wizard_createtheme.bmp')
self.welcomePage.setPixmap(QtGui.QWizard.WatermarkPixmap,
QtGui.QPixmap(u':/wizards/wizard_createtheme.bmp'))
self.welcomePage.setObjectName(u'WelcomePage')
self.welcomeLayout = QtGui.QVBoxLayout(self.welcomePage)
self.welcomeLayout.setObjectName(u'WelcomeLayout')
self.titleLabel = QtGui.QLabel(self.welcomePage)
self.titleLabel.setObjectName(u'TitleLabel')
self.welcomeLayout.addWidget(self.titleLabel)
self.welcomeLayout.addSpacing(40)
self.informationLabel = QtGui.QLabel(self.welcomePage)
self.informationLabel.setWordWrap(True)
self.informationLabel.setObjectName(u'InformationLabel')
self.welcomeLayout.addWidget(self.informationLabel)
self.welcomeLayout.addStretch()
ThemeWizard.addPage(self.welcomePage)
# Background Page # Background Page
self.backgroundPage = QtGui.QWizardPage() self.backgroundPage = QtGui.QWizardPage()
self.backgroundPage.setObjectName(u'BackgroundPage') self.backgroundPage.setObjectName(u'BackgroundPage')
@ -142,7 +127,7 @@ class Ui_ThemeWizard(object):
self.imageSpacer) self.imageSpacer)
self.backgroundStack.addWidget(self.imageWidget) self.backgroundStack.addWidget(self.imageWidget)
self.backgroundLayout.addLayout(self.backgroundStack) self.backgroundLayout.addLayout(self.backgroundStack)
ThemeWizard.addPage(self.backgroundPage) themeWizard.addPage(self.backgroundPage)
# Main Area Page # Main Area Page
self.mainAreaPage = QtGui.QWizardPage() self.mainAreaPage = QtGui.QWizardPage()
self.mainAreaPage.setObjectName(u'MainAreaPage') self.mainAreaPage.setObjectName(u'MainAreaPage')
@ -225,7 +210,7 @@ class Ui_ThemeWizard(object):
self.shadowSizeSpinBox.setObjectName(u'ShadowSizeSpinBox') self.shadowSizeSpinBox.setObjectName(u'ShadowSizeSpinBox')
self.shadowLayout.addWidget(self.shadowSizeSpinBox) self.shadowLayout.addWidget(self.shadowSizeSpinBox)
self.mainAreaLayout.addRow(self.shadowCheckBox, self.shadowLayout) self.mainAreaLayout.addRow(self.shadowCheckBox, self.shadowLayout)
ThemeWizard.addPage(self.mainAreaPage) themeWizard.addPage(self.mainAreaPage)
# Footer Area Page # Footer Area Page
self.footerAreaPage = QtGui.QWizardPage() self.footerAreaPage = QtGui.QWizardPage()
self.footerAreaPage.setObjectName(u'FooterAreaPage') self.footerAreaPage.setObjectName(u'FooterAreaPage')
@ -251,7 +236,7 @@ class Ui_ThemeWizard(object):
self.footerSizeSpinBox.setObjectName(u'FooterSizeSpinBox') self.footerSizeSpinBox.setObjectName(u'FooterSizeSpinBox')
self.footerAreaLayout.addRow(self.footerSizeLabel, self.footerAreaLayout.addRow(self.footerSizeLabel,
self.footerSizeSpinBox) self.footerSizeSpinBox)
ThemeWizard.addPage(self.footerAreaPage) themeWizard.addPage(self.footerAreaPage)
# Alignment Page # Alignment Page
self.alignmentPage = QtGui.QWizardPage() self.alignmentPage = QtGui.QWizardPage()
self.alignmentPage.setObjectName(u'AlignmentPage') self.alignmentPage.setObjectName(u'AlignmentPage')
@ -276,7 +261,7 @@ class Ui_ThemeWizard(object):
self.transitionsCheckBox.setObjectName(u'TransitionsCheckBox') self.transitionsCheckBox.setObjectName(u'TransitionsCheckBox')
self.alignmentLayout.addRow(self.transitionsLabel, self.alignmentLayout.addRow(self.transitionsLabel,
self.transitionsCheckBox) self.transitionsCheckBox)
ThemeWizard.addPage(self.alignmentPage) themeWizard.addPage(self.alignmentPage)
# Area Position Page # Area Position Page
self.areaPositionPage = QtGui.QWizardPage() self.areaPositionPage = QtGui.QWizardPage()
self.areaPositionPage.setObjectName(u'AreaPositionPage') self.areaPositionPage.setObjectName(u'AreaPositionPage')
@ -352,7 +337,7 @@ class Ui_ThemeWizard(object):
self.footerPositionLayout.addRow(self.footerHeightLabel, self.footerPositionLayout.addRow(self.footerHeightLabel,
self.footerHeightSpinBox) self.footerHeightSpinBox)
self.areaPositionLayout.addWidget(self.footerPositionGroupBox) self.areaPositionLayout.addWidget(self.footerPositionGroupBox)
ThemeWizard.addPage(self.areaPositionPage) themeWizard.addPage(self.areaPositionPage)
# Preview Page # Preview Page
self.previewPage = QtGui.QWizardPage() self.previewPage = QtGui.QWizardPage()
self.previewPage.setObjectName(u'PreviewPage') self.previewPage.setObjectName(u'PreviewPage')
@ -381,9 +366,8 @@ class Ui_ThemeWizard(object):
self.previewBoxLabel.setObjectName(u'PreviewBoxLabel') self.previewBoxLabel.setObjectName(u'PreviewBoxLabel')
self.previewAreaLayout.addWidget(self.previewBoxLabel) self.previewAreaLayout.addWidget(self.previewBoxLabel)
self.previewLayout.addWidget(self.previewArea) self.previewLayout.addWidget(self.previewArea)
ThemeWizard.addPage(self.previewPage) themeWizard.addPage(self.previewPage)
self.retranslateUi(themeWizard)
self.retranslateUi(ThemeWizard)
QtCore.QObject.connect(self.backgroundComboBox, QtCore.QObject.connect(self.backgroundComboBox,
QtCore.SIGNAL(u'currentIndexChanged(int)'), self.backgroundStack, QtCore.SIGNAL(u'currentIndexChanged(int)'), self.backgroundStack,
QtCore.SLOT(u'setCurrentIndex(int)')) QtCore.SLOT(u'setCurrentIndex(int)'))
@ -423,10 +407,10 @@ class Ui_ThemeWizard(object):
QtCore.QObject.connect(self.footerPositionCheckBox, QtCore.QObject.connect(self.footerPositionCheckBox,
QtCore.SIGNAL(u'toggled(bool)'), self.footerHeightSpinBox, QtCore.SIGNAL(u'toggled(bool)'), self.footerHeightSpinBox,
QtCore.SLOT(u'setDisabled(bool)')) QtCore.SLOT(u'setDisabled(bool)'))
QtCore.QMetaObject.connectSlotsByName(ThemeWizard) QtCore.QMetaObject.connectSlotsByName(themeWizard)
def retranslateUi(self, ThemeWizard): def retranslateUi(self, themeWizard):
ThemeWizard.setWindowTitle( themeWizard.setWindowTitle(
translate('OpenLP.ThemeWizard', 'Theme Wizard')) translate('OpenLP.ThemeWizard', 'Theme Wizard'))
self.titleLabel.setText( self.titleLabel.setText(
u'<span style="font-size:14pt; font-weight:600;">%s</span>' % \ u'<span style="font-size:14pt; font-weight:600;">%s</span>' % \

View File

@ -31,6 +31,7 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import build_icon, Receiver from openlp.core.lib import build_icon, Receiver
from openlp.core.lib.ui import add_welcome_page
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -63,36 +64,12 @@ class OpenLPWizard(QtGui.QWizard):
self.setOptions(QtGui.QWizard.IndependentPages | self.setOptions(QtGui.QWizard.IndependentPages |
QtGui.QWizard.NoBackButtonOnStartPage | QtGui.QWizard.NoBackButtonOnStartPage |
QtGui.QWizard.NoBackButtonOnLastPage) QtGui.QWizard.NoBackButtonOnLastPage)
self.addWelcomePage(image) add_welcome_page(self, image)
self.addCustomPages() self.addCustomPages()
self.addProgressPage() self.addProgressPage()
self.retranslateUi() self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self) QtCore.QMetaObject.connectSlotsByName(self)
def addWelcomePage(self, image):
"""
Add the opening welcome page to the wizard.
``image``
A splash image for the wizard
"""
self.welcomePage = QtGui.QWizardPage()
self.welcomePage.setPixmap(QtGui.QWizard.WatermarkPixmap,
QtGui.QPixmap(image))
self.welcomePage.setObjectName(u'WelcomePage')
self.welcomeLayout = QtGui.QVBoxLayout(self.welcomePage)
self.welcomeLayout.setObjectName(u'WelcomeLayout')
self.titleLabel = QtGui.QLabel(self.welcomePage)
self.titleLabel.setObjectName(u'TitleLabel')
self.welcomeLayout.addWidget(self.titleLabel)
self.welcomeLayout.addSpacing(40)
self.informationLabel = QtGui.QLabel(self.welcomePage)
self.informationLabel.setWordWrap(True)
self.informationLabel.setObjectName(u'InformationLabel')
self.welcomeLayout.addWidget(self.informationLabel)
self.welcomeLayout.addStretch()
self.addPage(self.welcomePage)
def addProgressPage(self): def addProgressPage(self):
""" """
Add the progress page for the wizard. This page informs the user how Add the progress page for the wizard. This page informs the user how

View File

@ -137,10 +137,7 @@ class AppLocation(object):
os.path.split(openlp.__file__)[0]) os.path.split(openlp.__file__)[0])
return os.path.join(app_path, u'i18n') return os.path.join(app_path, u'i18n')
else: else:
return _get_os_dir_path(u'openlp', return _get_os_dir_path(dir_type)
os.path.join(os.getenv(u'HOME'), u'Library',
u'Application Support', u'openlp'),
None, os.path.join(os.getenv(u'HOME'), u'.openlp'), dir_type)
@staticmethod @staticmethod
def get_data_path(): def get_data_path():
@ -163,17 +160,18 @@ class AppLocation(object):
os.makedirs(path) os.makedirs(path)
return path return path
def _get_os_dir_path(win_option, darwin_option, base_dir_option, def _get_os_dir_path(dir_type):
non_base_dir_option, dir_type=1):
""" """
Return a path based on which OS and environment we are running in. Return a path based on which OS and environment we are running in.
""" """
if sys.platform == u'win32': if sys.platform == u'win32':
return os.path.join(os.getenv(u'APPDATA'), win_option) return os.path.join(os.getenv(u'APPDATA'), u'openlp')
elif sys.platform == u'darwin': elif sys.platform == u'darwin':
if dir_type == AppLocation.DataDir: if dir_type == AppLocation.DataDir:
return os.path.join(darwin_option, u'Data') return os.path.join(os.getenv(u'HOME'), u'Library',
return darwin_option u'Application Support', u'openlp', u'Data')
return os.path.join(os.getenv(u'HOME'), u'Library',
u'Application Support', u'openlp')
else: else:
if XDG_BASE_AVAILABLE: if XDG_BASE_AVAILABLE:
if dir_type == AppLocation.ConfigDir: if dir_type == AppLocation.ConfigDir:
@ -183,7 +181,7 @@ def _get_os_dir_path(win_option, darwin_option, base_dir_option,
elif dir_type == AppLocation.CacheDir: elif dir_type == AppLocation.CacheDir:
return os.path.join(BaseDirectory.xdg_cache_home, u'openlp') return os.path.join(BaseDirectory.xdg_cache_home, u'openlp')
else: else:
return non_base_dir_option return os.path.join(os.getenv(u'HOME'), u'.openlp')
def _get_frozen_path(frozen_option, non_frozen_option): def _get_frozen_path(frozen_option, non_frozen_option):
""" """

View File

@ -45,15 +45,14 @@ class AlertsPlugin(Plugin):
self.icon = build_icon(u':/plugins/plugin_alerts.png') self.icon = build_icon(u':/plugins/plugin_alerts.png')
self.alertsmanager = AlertsManager(self) self.alertsmanager = AlertsManager(self)
self.manager = Manager(u'alerts', init_schema) self.manager = Manager(u'alerts', init_schema)
visible_name = self.getString(StringContent.VisibleName) self.visible_name = self.getString(StringContent.VisibleName)
self.alertForm = AlertForm(self, visible_name[u'title']) self.alertForm = AlertForm(self)
def getSettingsTab(self): def getSettingsTab(self):
""" """
Return the settings tab for the Alerts plugin Return the settings tab for the Alerts plugin
""" """
visible_name = self.getString(StringContent.VisibleName) self.alertsTab = AlertsTab(self, self.visible_name[u'title'])
self.alertsTab = AlertsTab(self, visible_name[u'title'])
return self.alertsTab return self.alertsTab
def addToolsMenuItem(self, tools_menu): def addToolsMenuItem(self, tools_menu):

View File

@ -35,7 +35,7 @@ class AlertForm(QtGui.QDialog, Ui_AlertDialog):
""" """
Provide UI for the alert system Provide UI for the alert system
""" """
def __init__(self, plugin, visible_title): def __init__(self, plugin):
""" """
Initialise the alert form Initialise the alert form
""" """

View File

@ -35,7 +35,7 @@ from PyQt4 import QtCore, QtGui
from openlp.core.lib import Receiver, SettingsManager, translate from openlp.core.lib import Receiver, SettingsManager, translate
from openlp.core.lib.db import delete_database from openlp.core.lib.db import delete_database
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.core.ui.wizard import OpenLPWizard from openlp.core.ui.wizard import OpenLPWizard
from openlp.core.utils import AppLocation, string_is_unicode from openlp.core.utils import AppLocation, string_is_unicode
from openlp.plugins.bibles.lib.manager import BibleFormat from openlp.plugins.bibles.lib.manager import BibleFormat
@ -124,9 +124,12 @@ class BibleImportForm(OpenLPWizard):
QtCore.QObject.connect(self.osisBrowseButton, QtCore.QObject.connect(self.osisBrowseButton,
QtCore.SIGNAL(u'clicked()'), QtCore.SIGNAL(u'clicked()'),
self.onOsisBrowseButtonClicked) self.onOsisBrowseButtonClicked)
QtCore.QObject.connect(self.csvTestamentsButton,
QtCore.SIGNAL(u'clicked()'),
self.onCsvTestamentsBrowseButtonClicked)
QtCore.QObject.connect(self.csvBooksButton, QtCore.QObject.connect(self.csvBooksButton,
QtCore.SIGNAL(u'clicked()'), QtCore.SIGNAL(u'clicked()'),
self.onBooksBrowseButtonClicked) self.onCsvBooksBrowseButtonClicked)
QtCore.QObject.connect(self.csvVersesButton, QtCore.QObject.connect(self.csvVersesButton,
QtCore.SIGNAL(u'clicked()'), QtCore.SIGNAL(u'clicked()'),
self.onCsvVersesBrowseButtonClicked) self.onCsvVersesBrowseButtonClicked)
@ -187,6 +190,18 @@ class BibleImportForm(OpenLPWizard):
self.csvLayout = QtGui.QFormLayout(self.csvWidget) self.csvLayout = QtGui.QFormLayout(self.csvWidget)
self.csvLayout.setMargin(0) self.csvLayout.setMargin(0)
self.csvLayout.setObjectName(u'CsvLayout') self.csvLayout.setObjectName(u'CsvLayout')
self.csvTestamentsLabel = QtGui.QLabel(self.csvWidget)
self.csvTestamentsLabel.setObjectName(u'CsvTestamentsLabel')
self.csvTestamentsLayout = QtGui.QHBoxLayout()
self.csvTestamentsLayout.setObjectName(u'CsvTestamentsLayout')
self.csvTestamentsEdit = QtGui.QLineEdit(self.csvWidget)
self.csvTestamentsEdit.setObjectName(u'CsvTestamentsEdit')
self.csvTestamentsLayout.addWidget(self.csvTestamentsEdit)
self.csvTestamentsButton = QtGui.QToolButton(self.csvWidget)
self.csvTestamentsButton.setIcon(self.openIcon)
self.csvTestamentsButton.setObjectName(u'CsvTestamentsButton')
self.csvTestamentsLayout.addWidget(self.csvTestamentsButton)
self.csvLayout.addRow(self.csvTestamentsLabel, self.csvTestamentsLayout)
self.csvBooksLabel = QtGui.QLabel(self.csvWidget) self.csvBooksLabel = QtGui.QLabel(self.csvWidget)
self.csvBooksLabel.setObjectName(u'CsvBooksLabel') self.csvBooksLabel.setObjectName(u'CsvBooksLabel')
self.csvBooksLayout = QtGui.QHBoxLayout() self.csvBooksLayout = QtGui.QHBoxLayout()
@ -213,7 +228,7 @@ class BibleImportForm(OpenLPWizard):
self.csvLayout.addRow(self.csvVersesLabel, self.csvVersesLayout) self.csvLayout.addRow(self.csvVersesLabel, self.csvVersesLayout)
self.csvSpacer = QtGui.QSpacerItem(10, 0, QtGui.QSizePolicy.Fixed, self.csvSpacer = QtGui.QSpacerItem(10, 0, QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Minimum) QtGui.QSizePolicy.Minimum)
self.csvLayout.setItem(2, QtGui.QFormLayout.LabelRole, self.csvSpacer) self.csvLayout.setItem(3, QtGui.QFormLayout.LabelRole, self.csvSpacer)
self.selectStack.addWidget(self.csvWidget) self.selectStack.addWidget(self.csvWidget)
self.openSongWidget = QtGui.QWidget(self.selectPage) self.openSongWidget = QtGui.QWidget(self.selectPage)
self.openSongWidget.setObjectName(u'OpenSongWidget') self.openSongWidget.setObjectName(u'OpenSongWidget')
@ -389,6 +404,8 @@ class BibleImportForm(OpenLPWizard):
translate('BiblesPlugin.ImportWizardForm', 'File location:')) translate('BiblesPlugin.ImportWizardForm', 'File location:'))
self.osisFileLabel.setText( self.osisFileLabel.setText(
translate('BiblesPlugin.ImportWizardForm', 'File location:')) translate('BiblesPlugin.ImportWizardForm', 'File location:'))
self.csvTestamentsLabel.setText(
translate('BiblesPlugin.ImportWizardForm', 'Testaments location:'))
self.csvBooksLabel.setText( self.csvBooksLabel.setText(
translate('BiblesPlugin.ImportWizardForm', 'Books location:')) translate('BiblesPlugin.ImportWizardForm', 'Books location:'))
self.csvVersesLabel.setText( self.csvVersesLabel.setText(
@ -469,7 +486,7 @@ class BibleImportForm(OpenLPWizard):
elif self.currentPage() == self.selectPage: elif self.currentPage() == self.selectPage:
if self.field(u'source_format').toInt()[0] == BibleFormat.OSIS: if self.field(u'source_format').toInt()[0] == BibleFormat.OSIS:
if not self.field(u'osis_location').toString(): if not self.field(u'osis_location').toString():
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Invalid Bible Location'), 'Invalid Bible Location'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -478,8 +495,17 @@ class BibleImportForm(OpenLPWizard):
self.osisFileEdit.setFocus() self.osisFileEdit.setFocus()
return False return False
elif self.field(u'source_format').toInt()[0] == BibleFormat.CSV: elif self.field(u'source_format').toInt()[0] == BibleFormat.CSV:
if not self.field(u'csv_booksfile').toString(): if not self.field(u'csv_testamentsfile').toString():
criticalErrorMessageBox( answer = critical_error_message_box(translate(
'BiblesPlugin.ImportWizardForm', 'No Testaments File'),
translate('BiblesPlugin.ImportWizardForm',
'You have not specified a testaments file. Do you '
'want to proceed with the import?'), question=True)
if answer == QtGui.QMessageBox.No:
self.csvTestamentsEdit.setFocus()
return False
elif not self.field(u'csv_booksfile').toString():
critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Invalid Books File'), 'Invalid Books File'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -488,7 +514,7 @@ class BibleImportForm(OpenLPWizard):
self.csvBooksEdit.setFocus() self.csvBooksEdit.setFocus()
return False return False
elif not self.field(u'csv_versefile').toString(): elif not self.field(u'csv_versefile').toString():
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Invalid Verse File'), 'Invalid Verse File'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -499,7 +525,7 @@ class BibleImportForm(OpenLPWizard):
elif self.field(u'source_format').toInt()[0] == \ elif self.field(u'source_format').toInt()[0] == \
BibleFormat.OpenSong: BibleFormat.OpenSong:
if not self.field(u'opensong_file').toString(): if not self.field(u'opensong_file').toString():
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Invalid OpenSong Bible'), 'Invalid OpenSong Bible'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -509,7 +535,7 @@ class BibleImportForm(OpenLPWizard):
return False return False
elif self.field(u'source_format').toInt()[0] == BibleFormat.OpenLP1: elif self.field(u'source_format').toInt()[0] == BibleFormat.OpenLP1:
if not self.field(u'openlp1_location').toString(): if not self.field(u'openlp1_location').toString():
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Invalid Bible Location'), 'Invalid Bible Location'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -523,7 +549,7 @@ class BibleImportForm(OpenLPWizard):
license_copyright = \ license_copyright = \
unicode(self.field(u'license_copyright').toString()) unicode(self.field(u'license_copyright').toString())
if not license_version: if not license_version:
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Empty Version Name'), 'Empty Version Name'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -531,7 +557,7 @@ class BibleImportForm(OpenLPWizard):
self.versionNameEdit.setFocus() self.versionNameEdit.setFocus()
return False return False
elif not license_copyright: elif not license_copyright:
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'Empty Copyright'), 'Empty Copyright'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
@ -540,7 +566,7 @@ class BibleImportForm(OpenLPWizard):
self.copyrightEdit.setFocus() self.copyrightEdit.setFocus()
return False return False
elif self.manager.exists(license_version): elif self.manager.exists(license_version):
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin.ImportWizardForm', 'Bible Exists'), translate('BiblesPlugin.ImportWizardForm', 'Bible Exists'),
translate('BiblesPlugin.ImportWizardForm', translate('BiblesPlugin.ImportWizardForm',
'This Bible already exists. Please import ' 'This Bible already exists. Please import '
@ -572,7 +598,15 @@ class BibleImportForm(OpenLPWizard):
translate('BiblesPlugin.ImportWizardForm', 'Open OSIS File'), translate('BiblesPlugin.ImportWizardForm', 'Open OSIS File'),
self.osisFileEdit) self.osisFileEdit)
def onBooksBrowseButtonClicked(self): def onCsvTestamentsBrowseButtonClicked(self):
"""
Show the file open dialog for the testaments CSV file.
"""
self.getFileName(translate('BiblesPlugin.ImportWizardForm',
'Open Testaments CSV File'), self.csvTestamentsEdit, u'%s (*.csv)'
% translate('BiblesPlugin.ImportWizardForm', 'CSV File'))
def onCsvBooksBrowseButtonClicked(self):
""" """
Show the file open dialog for the books CSV file. Show the file open dialog for the books CSV file.
""" """
@ -613,12 +647,14 @@ class BibleImportForm(OpenLPWizard):
""" """
self.selectPage.registerField(u'source_format', self.formatComboBox) self.selectPage.registerField(u'source_format', self.formatComboBox)
self.selectPage.registerField(u'osis_location', self.osisFileEdit) self.selectPage.registerField(u'osis_location', self.osisFileEdit)
self.selectPage.registerField(
u'csv_testamentsfile', self.csvTestamentsEdit)
self.selectPage.registerField(u'csv_booksfile', self.csvBooksEdit) self.selectPage.registerField(u'csv_booksfile', self.csvBooksEdit)
self.selectPage.registerField(u'csv_versefile', self.csvVersesEdit) self.selectPage.registerField(u'csv_versefile', self.csvVersesEdit)
self.selectPage.registerField(u'opensong_file', self.openSongFileEdit) self.selectPage.registerField(u'opensong_file', self.openSongFileEdit)
self.selectPage.registerField(u'web_location', self.webSourceComboBox) self.selectPage.registerField(u'web_location', self.webSourceComboBox)
self.selectPage.registerField(u'web_biblename', self.selectPage.registerField(
self.webTranslationComboBox) u'web_biblename', self.webTranslationComboBox)
self.selectPage.registerField(u'proxy_server', self.webServerEdit) self.selectPage.registerField(u'proxy_server', self.webServerEdit)
self.selectPage.registerField(u'proxy_username', self.webUserEdit) self.selectPage.registerField(u'proxy_username', self.webUserEdit)
self.selectPage.registerField(u'proxy_password', self.webPasswordEdit) self.selectPage.registerField(u'proxy_password', self.webPasswordEdit)
@ -641,6 +677,7 @@ class BibleImportForm(OpenLPWizard):
self.cancelButton.setVisible(True) self.cancelButton.setVisible(True)
self.setField(u'source_format', QtCore.QVariant(0)) self.setField(u'source_format', QtCore.QVariant(0))
self.setField(u'osis_location', QtCore.QVariant('')) self.setField(u'osis_location', QtCore.QVariant(''))
self.setField(u'csv_testamentsfile', QtCore.QVariant(''))
self.setField(u'csv_booksfile', QtCore.QVariant('')) self.setField(u'csv_booksfile', QtCore.QVariant(''))
self.setField(u'csv_versefile', QtCore.QVariant('')) self.setField(u'csv_versefile', QtCore.QVariant(''))
self.setField(u'opensong_file', QtCore.QVariant('')) self.setField(u'opensong_file', QtCore.QVariant(''))
@ -770,7 +807,8 @@ class BibleImportForm(OpenLPWizard):
elif bible_type == BibleFormat.CSV: elif bible_type == BibleFormat.CSV:
# Import a CSV bible. # Import a CSV bible.
importer = self.manager.import_bible(BibleFormat.CSV, importer = self.manager.import_bible(BibleFormat.CSV,
name=license_version, name=license_version, testamentsfile=unicode(
self.field(u'csv_testamentsfile').toString()),
booksfile=unicode(self.field(u'csv_booksfile').toString()), booksfile=unicode(self.field(u'csv_booksfile').toString()),
versefile=unicode(self.field(u'csv_versefile').toString()) versefile=unicode(self.field(u'csv_versefile').toString())
) )
@ -795,8 +833,7 @@ class BibleImportForm(OpenLPWizard):
bible = \ bible = \
self.web_bible_list[WebDownload.Bibleserver][bible_version] self.web_bible_list[WebDownload.Bibleserver][bible_version]
importer = self.manager.import_bible( importer = self.manager.import_bible(
BibleFormat.WebDownload, BibleFormat.WebDownload, name=license_version,
name=license_version,
download_source=WebDownload.get_name(download_location), download_source=WebDownload.get_name(download_location),
download_name=bible, download_name=bible,
proxy_server=unicode(self.field(u'proxy_server').toString()), proxy_server=unicode(self.field(u'proxy_server').toString()),

View File

@ -23,7 +23,48 @@
# 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 #
############################################################################### ###############################################################################
"""
The :mod:`cvsbible` modules provides a facility to import bibles from a set of
CSV files.
The module expects two mandatory files containing the books and the verses and
will accept an optional third file containing the testaments.
The format of the testament file is:
<testament_id>,<testament_name>
For example:
1,Old Testament
2,New Testament
The format of the books file is:
<book_id>,<testament_id>,<book_name>,<book_abbreviation>
For example
1,1,Genesis,Gen
2,1,Exodus,Exod
...
40,2,Matthew,Matt
There are two acceptable formats of the verses file. They are:
<book_id>,<chapter_number>,<verse_number>,<verse_text>
or
<book_name>,<chapter_number>,<verse_number>,<verse_text>
For example:
1,1,1,"In the beginning God created the heaven and the earth."
or
"Genesis",1,2,"And the earth was without form, and void; and...."
All CSV files are expected to use a comma (',') as the delimeter and double
quotes ('"') as the quote symbol.
"""
import logging import logging
import chardet import chardet
import csv import csv
@ -31,7 +72,7 @@ import csv
from PyQt4 import QtCore from PyQt4 import QtCore
from openlp.core.lib import Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.plugins.bibles.lib.db import BibleDB from openlp.plugins.bibles.lib.db import BibleDB, Testament
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -39,38 +80,81 @@ class CSVBible(BibleDB):
""" """
This class provides a specialisation for importing of CSV Bibles. This class provides a specialisation for importing of CSV Bibles.
""" """
def __init__(self, parent, **kwargs): def __init__(self, parent, **kwargs):
""" """
Loads a Bible from a pair of CVS files passed in Loads a Bible from a set of CVS files.
This class assumes the files contain all the information and This class assumes the files contain all the information and
a clean bible is being loaded. a clean bible is being loaded.
""" """
log.info(self.__class__.__name__) log.info(self.__class__.__name__)
BibleDB.__init__(self, parent, **kwargs) BibleDB.__init__(self, parent, **kwargs)
try:
self.testamentsfile = kwargs[u'testamentsfile']
except KeyError:
self.testamentsfile = None
self.booksfile = kwargs[u'booksfile'] self.booksfile = kwargs[u'booksfile']
self.versesfile = kwargs[u'versefile'] self.versesfile = kwargs[u'versefile']
QtCore.QObject.connect(Receiver.get_receiver(), QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'openlp_stop_wizard'), self.stop_import) QtCore.SIGNAL(u'openlp_stop_wizard'), self.stop_import)
def do_import(self): def setup_testaments(self):
success = True """
books_file = None Overrides parent method so we can handle importing a testament file.
book_ptr = None """
verse_file = None if self.testamentsfile:
# Populate the Tables self.wizard.progressBar.setMinimum(0)
self.wizard.progressBar.setMaximum(2)
self.wizard.progressBar.setValue(0)
testaments_file = None
try: try:
books_file = open(self.booksfile, 'r') details = get_file_encoding(self.testamentsfile)
dialect = csv.Sniffer().sniff(books_file.read(1024)) testaments_file = open(self.testamentsfile, 'rb')
books_file.seek(0) testaments_reader = csv.reader(testaments_file, delimiter=',',
books_reader = csv.reader(books_file, dialect) quotechar='"')
for line in books_reader: for line in testaments_reader:
# cancel pressed
if self.stop_import_flag: if self.stop_import_flag:
break break
details = chardet.detect(line[1]) self.wizard.incrementProgressBar(unicode(
self.create_book(unicode(line[1], details['encoding']), translate('BibleDB.Wizard',
line[2], int(line[0])) 'Importing testaments... %s')) %
unicode(line[1], details['encoding']), 0)
self.save_object(Testament.populate(
name=unicode(line[1], details['encoding'])))
Receiver.send_message(u'openlp_process_events')
except (IOError, IndexError):
log.exception(u'Loading testaments from file failed')
finally:
if testaments_file:
testaments_file.close()
self.wizard.incrementProgressBar(unicode(translate(
'BibleDB.Wizard', 'Importing testaments... done.')), 2)
else:
BibleDB.setup_testaments(self)
def do_import(self):
"""
Import the bible books and verses.
"""
self.wizard.progressBar.setValue(0)
self.wizard.progressBar.setMinimum(0)
self.wizard.progressBar.setMaximum(66)
success = True
books_file = None
book_list = {}
# Populate the Tables
try:
details = get_file_encoding(self.booksfile)
books_file = open(self.booksfile, 'r')
books_reader = csv.reader(books_file, delimiter=',', quotechar='"')
for line in books_reader:
if self.stop_import_flag:
break
self.wizard.incrementProgressBar(unicode(
translate('BibleDB.Wizard', 'Importing books... %s')) %
unicode(line[2], details['encoding']))
self.create_book(unicode(line[2], details['encoding']),
unicode(line[3], details['encoding']), int(line[1]))
book_list[int(line[0])] = unicode(line[2], details['encoding'])
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
except (IOError, IndexError): except (IOError, IndexError):
log.exception(u'Loading books from file failed') log.exception(u'Loading books from file failed')
@ -78,28 +162,37 @@ class CSVBible(BibleDB):
finally: finally:
if books_file: if books_file:
books_file.close() books_file.close()
if not success: if self.stop_import_flag or not success:
return False return False
self.wizard.progressBar.setValue(0)
self.wizard.progressBar.setMaximum(67)
verse_file = None
try: try:
verse_file = open(self.versesfile, 'r') book_ptr = None
dialect = csv.Sniffer().sniff(verse_file.read(1024)) details = get_file_encoding(self.versesfile)
verse_file.seek(0) verse_file = open(self.versesfile, 'rb')
verse_reader = csv.reader(verse_file, dialect) verse_reader = csv.reader(verse_file, delimiter=',', quotechar='"')
for line in verse_reader: for line in verse_reader:
if self.stop_import_flag: if self.stop_import_flag:
# cancel pressed
break break
details = chardet.detect(line[3]) try:
if book_ptr != line[0]: line_book = book_list[int(line[0])]
book = self.get_book(line[0]) except ValueError:
line_book = unicode(line[0], details['encoding'])
if book_ptr != line_book:
book = self.get_book(line_book)
book_ptr = book.name book_ptr = book.name
self.wizard.incrementProgressBar(unicode(translate( self.wizard.incrementProgressBar(unicode(translate(
'BiblesPlugin.CSVImport', 'Importing %s %s...', 'BibleDB.Wizard', 'Importing verses from %s...',
'Importing <book name> <chapter>...')) % 'Importing verses from <book name>...')) % book.name)
(book.name, int(line[1])))
self.session.commit() self.session.commit()
self.create_verse(book.id, line[1], line[2], try:
unicode(line[3], details['encoding'])) verse_text = unicode(line[3], details['encoding'])
except UnicodeError:
verse_text = unicode(line[3], u'cp1252')
self.create_verse(book.id, line[1], line[2], verse_text)
self.wizard.incrementProgressBar(translate('BibleDB.Wizard',
'Importing verses... done.'))
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
self.session.commit() self.session.commit()
except IOError: except IOError:
@ -112,3 +205,18 @@ class CSVBible(BibleDB):
return False return False
else: else:
return success return success
def get_file_encoding(filename):
"""
Utility function to get the file encoding.
"""
detect_file = None
try:
detect_file = open(filename, 'r')
details = chardet.detect(detect_file.read(1024))
except IOError:
log.exception(u'Error detecting file encoding')
finally:
if detect_file:
detect_file.close()
return details

View File

@ -35,7 +35,7 @@ from sqlalchemy.orm.exc import UnmappedClassError
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.lib.db import BaseModel, init_db, Manager from openlp.core.lib.db import BaseModel, init_db, Manager
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -206,10 +206,16 @@ class BibleDB(QtCore.QObject, Manager):
""" """
self.wizard = wizard self.wizard = wizard
self.create_meta(u'dbversion', u'2') self.create_meta(u'dbversion', u'2')
self.setup_testaments()
return self.name
def setup_testaments(self):
"""
Initialise the testaments section of a bible with suitable defaults.
"""
self.save_object(Testament.populate(name=u'Old Testament')) self.save_object(Testament.populate(name=u'Old Testament'))
self.save_object(Testament.populate(name=u'New Testament')) self.save_object(Testament.populate(name=u'New Testament'))
self.save_object(Testament.populate(name=u'Apocrypha')) self.save_object(Testament.populate(name=u'Apocrypha'))
return self.name
def create_book(self, name, abbrev, testament=1): def create_book(self, name, abbrev, testament=1):
""" """
@ -355,7 +361,7 @@ class BibleDB(QtCore.QObject, Manager):
verse_list.extend(verses) verse_list.extend(verses)
else: else:
log.debug(u'OpenLP failed to find book %s', book) log.debug(u'OpenLP failed to find book %s', book)
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin', 'No Book Found'), translate('BiblesPlugin', 'No Book Found'),
translate('BiblesPlugin', 'No matching book ' translate('BiblesPlugin', 'No matching book '
'could be found in this Bible. Check that you have ' 'could be found in this Bible. Check that you have '

View File

@ -38,7 +38,7 @@ from HTMLParser import HTMLParseError
from BeautifulSoup import BeautifulSoup, NavigableString from BeautifulSoup import BeautifulSoup, NavigableString
from openlp.core.lib import Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.core.utils import AppLocation, get_web_page from openlp.core.utils import AppLocation, get_web_page
from openlp.plugins.bibles.lib import SearchResults from openlp.plugins.bibles.lib import SearchResults
from openlp.plugins.bibles.lib.db import BibleDB, Book from openlp.plugins.bibles.lib.db import BibleDB, Book
@ -210,6 +210,7 @@ class BGExtract(object):
cleaner = [(re.compile('&nbsp;|<br />|\'\+\''), lambda match: '')] cleaner = [(re.compile('&nbsp;|<br />|\'\+\''), lambda match: '')]
soup = get_soup_for_bible_ref( soup = get_soup_for_bible_ref(
u'http://www.biblegateway.com/passage/?%s' % url_params, u'http://www.biblegateway.com/passage/?%s' % url_params,
pre_parse_regex=r'<meta name.*?/>', pre_parse_substitute='',
cleaner=cleaner) cleaner=cleaner)
if not soup: if not soup:
return None return None
@ -430,7 +431,7 @@ class HTTPBible(BibleDB):
if not db_book: if not db_book:
book_details = HTTPBooks.get_book(book) book_details = HTTPBooks.get_book(book)
if not book_details: if not book_details:
criticalErrorMessageBox( critical_error_message_box(
translate('BiblesPlugin', 'No Book Found'), translate('BiblesPlugin', 'No Book Found'),
translate('BiblesPlugin', 'No matching ' translate('BiblesPlugin', 'No matching '
'book could be found in this Bible. Check that you ' 'book could be found in this Bible. Check that you '
@ -499,7 +500,8 @@ class HTTPBible(BibleDB):
""" """
return HTTPBooks.get_verse_count(book, chapter) return HTTPBooks.get_verse_count(book, chapter)
def get_soup_for_bible_ref(reference_url, header=None, cleaner=None): def get_soup_for_bible_ref(reference_url, header=None, pre_parse_regex=None,
pre_parse_substitute=None, cleaner=None):
""" """
Gets a webpage and returns a parsed and optionally cleaned soup or None. Gets a webpage and returns a parsed and optionally cleaned soup or None.
@ -509,6 +511,13 @@ def get_soup_for_bible_ref(reference_url, header=None, cleaner=None):
``header`` ``header``
An optional HTTP header to pass to the bible web server. An optional HTTP header to pass to the bible web server.
``pre_parse_regex``
A regular expression to run on the webpage. Allows manipulation of the
webpage before passing to BeautifulSoup for parsing.
``pre_parse_substitute``
The text to replace any matches to the regular expression with.
``cleaner`` ``cleaner``
An optional regex to use during webpage parsing. An optional regex to use during webpage parsing.
""" """
@ -518,12 +527,15 @@ def get_soup_for_bible_ref(reference_url, header=None, cleaner=None):
if not page: if not page:
send_error_message(u'download') send_error_message(u'download')
return None return None
page_source = page.read()
if pre_parse_regex and pre_parse_substitute is not None:
page_source = re.sub(pre_parse_regex, pre_parse_substitute, page_source)
soup = None soup = None
try: try:
if cleaner: if cleaner:
soup = BeautifulSoup(page, markupMassage=cleaner) soup = BeautifulSoup(page_source, markupMassage=cleaner)
else: else:
soup = BeautifulSoup(page) soup = BeautifulSoup(page_source)
except HTMLParseError: except HTMLParseError:
log.exception(u'BeautifulSoup could not parse the bible page.') log.exception(u'BeautifulSoup could not parse the bible page.')
if not soup: if not soup:
@ -540,14 +552,14 @@ def send_error_message(error_type):
The type of error that occured for the issue. The type of error that occured for the issue.
""" """
if error_type == u'download': if error_type == u'download':
criticalErrorMessageBox( critical_error_message_box(
translate('BiblePlugin.HTTPBible', 'Download Error'), translate('BiblePlugin.HTTPBible', 'Download Error'),
translate('BiblePlugin.HTTPBible', 'There was a ' translate('BiblePlugin.HTTPBible', 'There was a '
'problem downloading your verse selection. Please check your ' 'problem downloading your verse selection. Please check your '
'Internet connection, and if this error continues to occur ' 'Internet connection, and if this error continues to occur '
'please consider reporting a bug.')) 'please consider reporting a bug.'))
elif error_type == u'parse': elif error_type == u'parse':
criticalErrorMessageBox( critical_error_message_box(
translate('BiblePlugin.HTTPBible', 'Parse Error'), translate('BiblePlugin.HTTPBible', 'Parse Error'),
translate('BiblePlugin.HTTPBible', 'There was a ' translate('BiblePlugin.HTTPBible', 'There was a '
'problem extracting your verse selection. If this error continues ' 'problem extracting your verse selection. If this error continues '

View File

@ -92,7 +92,7 @@ class BibleFormat(object):
return None return None
@staticmethod @staticmethod
def list(): def get_formats_list():
""" """
Return a list of the supported Bible formats. Return a list of the supported Bible formats.
""" """

View File

@ -30,7 +30,7 @@ from PyQt4 import QtCore, QtGui
from openlp.core.lib import MediaManagerItem, Receiver, BaseListWithDnD, \ from openlp.core.lib import MediaManagerItem, Receiver, BaseListWithDnD, \
ItemCapabilities, translate ItemCapabilities, translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box, media_item_combo_box
from openlp.plugins.bibles.forms import BibleImportForm from openlp.plugins.bibles.forms import BibleImportForm
from openlp.plugins.bibles.lib import get_reference_match from openlp.plugins.bibles.lib import get_reference_match
@ -81,33 +81,21 @@ class BibleMediaItem(MediaManagerItem):
self.quickLayout.setObjectName(u'quickLayout') self.quickLayout.setObjectName(u'quickLayout')
self.quickVersionLabel = QtGui.QLabel(self.quickTab) self.quickVersionLabel = QtGui.QLabel(self.quickTab)
self.quickVersionLabel.setObjectName(u'quickVersionLabel') self.quickVersionLabel.setObjectName(u'quickVersionLabel')
self.quickVersionComboBox = QtGui.QComboBox(self.quickTab) self.quickVersionComboBox = media_item_combo_box(self.quickTab,
self.quickVersionComboBox.setSizeAdjustPolicy( u'quickVersionComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.quickVersionComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.quickVersionComboBox.setObjectName(u'quickVersionComboBox')
self.quickVersionLabel.setBuddy(self.quickVersionComboBox) self.quickVersionLabel.setBuddy(self.quickVersionComboBox)
self.quickLayout.addRow(self.quickVersionLabel, self.quickLayout.addRow(self.quickVersionLabel,
self.quickVersionComboBox) self.quickVersionComboBox)
self.quickSecondLabel = QtGui.QLabel(self.quickTab) self.quickSecondLabel = QtGui.QLabel(self.quickTab)
self.quickSecondLabel.setObjectName(u'quickSecondLabel') self.quickSecondLabel.setObjectName(u'quickSecondLabel')
self.quickSecondComboBox = QtGui.QComboBox(self.quickTab) self.quickSecondComboBox = media_item_combo_box(self.quickTab,
self.quickSecondComboBox.setSizeAdjustPolicy( u'quickSecondComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.quickSecondComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.quickSecondComboBox.setObjectName(u'quickSecondComboBox')
self.quickSecondLabel.setBuddy(self.quickSecondComboBox) self.quickSecondLabel.setBuddy(self.quickSecondComboBox)
self.quickLayout.addRow(self.quickSecondLabel, self.quickSecondComboBox) self.quickLayout.addRow(self.quickSecondLabel, self.quickSecondComboBox)
self.quickSearchTypeLabel = QtGui.QLabel(self.quickTab) self.quickSearchTypeLabel = QtGui.QLabel(self.quickTab)
self.quickSearchTypeLabel.setObjectName(u'quickSearchTypeLabel') self.quickSearchTypeLabel.setObjectName(u'quickSearchTypeLabel')
self.quickSearchComboBox = QtGui.QComboBox(self.quickTab) self.quickSearchComboBox = media_item_combo_box(self.quickTab,
self.quickSearchComboBox.setSizeAdjustPolicy( u'quickSearchComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.quickSearchComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.quickSearchComboBox.setObjectName(u'quickSearchComboBox')
self.quickSearchTypeLabel.setBuddy(self.quickSearchComboBox) self.quickSearchTypeLabel.setBuddy(self.quickSearchComboBox)
self.quickLayout.addRow(self.quickSearchTypeLabel, self.quickLayout.addRow(self.quickSearchTypeLabel,
self.quickSearchComboBox) self.quickSearchComboBox)
@ -119,12 +107,8 @@ class BibleMediaItem(MediaManagerItem):
self.quickLayout.addRow(self.quickSearchLabel, self.quickSearchEdit) self.quickLayout.addRow(self.quickSearchLabel, self.quickSearchEdit)
self.quickClearLabel = QtGui.QLabel(self.quickTab) self.quickClearLabel = QtGui.QLabel(self.quickTab)
self.quickClearLabel.setObjectName(u'quickClearLabel') self.quickClearLabel.setObjectName(u'quickClearLabel')
self.quickClearComboBox = QtGui.QComboBox(self.quickTab) self.quickClearComboBox = media_item_combo_box(self.quickTab,
self.quickClearComboBox.setSizeAdjustPolicy( u'quickClearComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.quickClearComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.quickClearComboBox.setObjectName(u'quickClearComboBox')
self.quickLayout.addRow(self.quickClearLabel, self.quickClearComboBox) self.quickLayout.addRow(self.quickClearLabel, self.quickClearComboBox)
self.quickSearchButtonLayout = QtGui.QHBoxLayout() self.quickSearchButtonLayout = QtGui.QHBoxLayout()
self.quickSearchButtonLayout.setObjectName(u'quickSearchButtonLayout') self.quickSearchButtonLayout.setObjectName(u'quickSearchButtonLayout')
@ -144,36 +128,24 @@ class BibleMediaItem(MediaManagerItem):
self.advancedVersionLabel.setObjectName(u'advancedVersionLabel') self.advancedVersionLabel.setObjectName(u'advancedVersionLabel')
self.advancedLayout.addWidget(self.advancedVersionLabel, 0, 0, self.advancedLayout.addWidget(self.advancedVersionLabel, 0, 0,
QtCore.Qt.AlignRight) QtCore.Qt.AlignRight)
self.advancedVersionComboBox = QtGui.QComboBox(self.advancedTab) self.advancedVersionComboBox = media_item_combo_box(self.advancedTab,
self.advancedVersionComboBox.setSizeAdjustPolicy( u'advancedVersionComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.advancedVersionComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.advancedVersionComboBox.setObjectName(u'advancedVersionComboBox')
self.advancedVersionLabel.setBuddy(self.advancedVersionComboBox) self.advancedVersionLabel.setBuddy(self.advancedVersionComboBox)
self.advancedLayout.addWidget(self.advancedVersionComboBox, 0, 1, 1, 2) self.advancedLayout.addWidget(self.advancedVersionComboBox, 0, 1, 1, 2)
self.advancedSecondLabel = QtGui.QLabel(self.advancedTab) self.advancedSecondLabel = QtGui.QLabel(self.advancedTab)
self.advancedSecondLabel.setObjectName(u'advancedSecondLabel') self.advancedSecondLabel.setObjectName(u'advancedSecondLabel')
self.advancedLayout.addWidget(self.advancedSecondLabel, 1, 0, self.advancedLayout.addWidget(self.advancedSecondLabel, 1, 0,
QtCore.Qt.AlignRight) QtCore.Qt.AlignRight)
self.advancedSecondComboBox = QtGui.QComboBox(self.advancedTab) self.advancedSecondComboBox = media_item_combo_box(self.advancedTab,
self.advancedSecondComboBox.setSizeAdjustPolicy( u'advancedSecondComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.advancedSecondComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.advancedSecondComboBox.setObjectName(u'advancedSecondComboBox')
self.advancedSecondLabel.setBuddy(self.advancedSecondComboBox) self.advancedSecondLabel.setBuddy(self.advancedSecondComboBox)
self.advancedLayout.addWidget(self.advancedSecondComboBox, 1, 1, 1, 2) self.advancedLayout.addWidget(self.advancedSecondComboBox, 1, 1, 1, 2)
self.advancedBookLabel = QtGui.QLabel(self.advancedTab) self.advancedBookLabel = QtGui.QLabel(self.advancedTab)
self.advancedBookLabel.setObjectName(u'advancedBookLabel') self.advancedBookLabel.setObjectName(u'advancedBookLabel')
self.advancedLayout.addWidget(self.advancedBookLabel, 2, 0, self.advancedLayout.addWidget(self.advancedBookLabel, 2, 0,
QtCore.Qt.AlignRight) QtCore.Qt.AlignRight)
self.advancedBookComboBox = QtGui.QComboBox(self.advancedTab) self.advancedBookComboBox = media_item_combo_box(self.advancedTab,
self.advancedBookComboBox.setSizeAdjustPolicy( u'advancedBookComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.advancedBookComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.advancedBookComboBox.setObjectName(u'advancedBookComboBox')
self.advancedBookLabel.setBuddy(self.advancedBookComboBox) self.advancedBookLabel.setBuddy(self.advancedBookComboBox)
self.advancedLayout.addWidget(self.advancedBookComboBox, 2, 1, 1, 2) self.advancedLayout.addWidget(self.advancedBookComboBox, 2, 1, 1, 2)
self.advancedChapterLabel = QtGui.QLabel(self.advancedTab) self.advancedChapterLabel = QtGui.QLabel(self.advancedTab)
@ -202,17 +174,12 @@ class BibleMediaItem(MediaManagerItem):
self.advancedToVerse = QtGui.QComboBox(self.advancedTab) self.advancedToVerse = QtGui.QComboBox(self.advancedTab)
self.advancedToVerse.setObjectName(u'advancedToVerse') self.advancedToVerse.setObjectName(u'advancedToVerse')
self.advancedLayout.addWidget(self.advancedToVerse, 5, 2) self.advancedLayout.addWidget(self.advancedToVerse, 5, 2)
self.advancedClearLabel = QtGui.QLabel(self.quickTab) self.advancedClearLabel = QtGui.QLabel(self.quickTab)
self.advancedClearLabel.setObjectName(u'advancedClearLabel') self.advancedClearLabel.setObjectName(u'advancedClearLabel')
self.advancedLayout.addWidget(self.advancedClearLabel, 6, 0, self.advancedLayout.addWidget(self.advancedClearLabel, 6, 0,
QtCore.Qt.AlignRight) QtCore.Qt.AlignRight)
self.advancedClearComboBox = QtGui.QComboBox(self.quickTab) self.advancedClearComboBox = media_item_combo_box(self.quickTab,
self.advancedClearComboBox.setSizeAdjustPolicy( u'advancedClearComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.advancedClearComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.advancedClearComboBox.setObjectName(u'advancedClearComboBox')
self.advancedClearLabel.setBuddy(self.advancedClearComboBox) self.advancedClearLabel.setBuddy(self.advancedClearComboBox)
self.advancedLayout.addWidget(self.advancedClearComboBox, 6, 1, 1, 2) self.advancedLayout.addWidget(self.advancedClearComboBox, 6, 1, 1, 2)
self.advancedSearchButtonLayout = QtGui.QHBoxLayout() self.advancedSearchButtonLayout = QtGui.QHBoxLayout()
@ -254,9 +221,6 @@ class BibleMediaItem(MediaManagerItem):
QtCore.QObject.connect(self.quickSearchEdit, QtCore.QObject.connect(self.quickSearchEdit,
QtCore.SIGNAL(u'returnPressed()'), self.onQuickSearchButton) QtCore.SIGNAL(u'returnPressed()'), self.onQuickSearchButton)
def addListViewToToolBar(self):
MediaManagerItem.addListViewToToolBar(self)
def configUpdated(self): def configUpdated(self):
log.debug(u'configUpdated') log.debug(u'configUpdated')
if QtCore.QSettings().value(self.settingsSection + u'/second bibles', if QtCore.QSettings().value(self.settingsSection + u'/second bibles',
@ -390,7 +354,8 @@ class BibleMediaItem(MediaManagerItem):
verse_count = self.parent.manager.get_verse_count(bible, book, 1) verse_count = self.parent.manager.get_verse_count(bible, book, 1)
if verse_count == 0: if verse_count == 0:
self.advancedSearchButton.setEnabled(False) self.advancedSearchButton.setEnabled(False)
criticalErrorMessageBox(message=translate('BiblePlugin.MediaItem', critical_error_message_box(
message=translate('BiblePlugin.MediaItem',
'Bible not fully loaded')) 'Bible not fully loaded'))
else: else:
self.advancedSearchButton.setEnabled(True) self.advancedSearchButton.setEnabled(True)
@ -528,19 +493,7 @@ class BibleMediaItem(MediaManagerItem):
if self.advancedClearComboBox.currentIndex() == 0: if self.advancedClearComboBox.currentIndex() == 0:
self.listView.clear() self.listView.clear()
if self.listView.count() != 0: if self.listView.count() != 0:
# Check if the first item is a second bible item or not. self.__checkSecondBible(bible, second_bible)
bitem = self.listView.item(0)
item_second_bible = self._decodeQtObject(bitem, 'second_bible')
if item_second_bible and second_bible or not item_second_bible and \
not second_bible:
self.displayResults(bible, second_bible)
elif criticalErrorMessageBox(
message=translate('BiblePlugin.MediaItem',
'You cannot combine single and second bible verses. Do you '
'want to delete your search results and start a new search?'),
parent=self, question=True) == QtGui.QMessageBox.Yes:
self.listView.clear()
self.displayResults(bible, second_bible)
else: else:
self.displayResults(bible, second_bible) self.displayResults(bible, second_bible)
Receiver.send_message(u'cursor_normal') Receiver.send_message(u'cursor_normal')
@ -580,23 +533,29 @@ class BibleMediaItem(MediaManagerItem):
if self.quickClearComboBox.currentIndex() == 0: if self.quickClearComboBox.currentIndex() == 0:
self.listView.clear() self.listView.clear()
if self.listView.count() != 0 and self.search_results: if self.listView.count() != 0 and self.search_results:
self.__checkSecondBible(bible, second_bible)
elif self.search_results:
self.displayResults(bible, second_bible)
self.quickSearchButton.setEnabled(True)
Receiver.send_message(u'cursor_normal')
Receiver.send_message(u'openlp_process_events')
def __checkSecondBible(self, bible, second_bible):
"""
Check if the first item is a second bible item or not.
"""
bitem = self.listView.item(0) bitem = self.listView.item(0)
item_second_bible = self._decodeQtObject(bitem, 'second_bible') item_second_bible = self._decodeQtObject(bitem, 'second_bible')
if item_second_bible and second_bible or not item_second_bible and \ if item_second_bible and second_bible or not item_second_bible and \
not second_bible: not second_bible:
self.displayResults(bible, second_bible) self.displayResults(bible, second_bible)
elif criticalErrorMessageBox( elif critical_error_message_box(
message=translate('BiblePlugin.MediaItem', message=translate('BiblePlugin.MediaItem',
'You cannot combine single and second bible verses. Do you ' 'You cannot combine single and second bible verses. Do you '
'want to delete your search results and start a new search?'), 'want to delete your search results and start a new search?'),
parent=self, question=True) == QtGui.QMessageBox.Yes: parent=self, question=True) == QtGui.QMessageBox.Yes:
self.listView.clear() self.listView.clear()
self.displayResults(bible, second_bible) self.displayResults(bible, second_bible)
elif self.search_results:
self.displayResults(bible, second_bible)
self.quickSearchButton.setEnabled(True)
Receiver.send_message(u'cursor_normal')
Receiver.send_message(u'openlp_process_events')
def displayResults(self, bible, second_bible=u''): def displayResults(self, bible, second_bible=u''):
""" """

View File

@ -19,7 +19,7 @@ IBS-fordítás (Új Károli), KAR
King James Version, KJV King James Version, KJV
Luther 1984, LUT Luther 1984, LUT
Septuaginta, LXX Septuaginta, LXX
Neue Genfer Übersetzung, NGÜ Neue Genfer Übersetzung, NGU
New International Readers Version, NIRV New International Readers Version, NIRV
New International Version, NIV New International Version, NIV
Neues Leben, NL Neues Leben, NL

1 عربي ARA
19 King James Version KJV
20 Luther 1984 LUT
21 Septuaginta LXX
22 Neue Genfer Übersetzung NGÜ NGU
23 New International Readers Version NIRV
24 New International Version NIV
25 Neues Leben NL

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import build_icon, translate from openlp.core.lib import build_icon, translate
from openlp.core.lib.ui import save_cancel_button_box
class Ui_CustomEditDialog(object): class Ui_CustomEditDialog(object):
def setupUi(self, customEditDialog): def setupUi(self, customEditDialog):
@ -93,16 +94,9 @@ class Ui_CustomEditDialog(object):
self.creditLabel.setBuddy(self.creditEdit) self.creditLabel.setBuddy(self.creditEdit)
self.bottomFormLayout.addRow(self.creditLabel, self.creditEdit) self.bottomFormLayout.addRow(self.creditLabel, self.creditEdit)
self.dialogLayout.addLayout(self.bottomFormLayout) self.dialogLayout.addLayout(self.bottomFormLayout)
self.buttonBox = QtGui.QDialogButtonBox(customEditDialog) self.buttonBox = save_cancel_button_box(customEditDialog)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel |
QtGui.QDialogButtonBox.Save)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox) self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(customEditDialog) self.retranslateUi(customEditDialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'accepted()'),
customEditDialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'rejected()'),
customEditDialog.closePressed)
QtCore.QMetaObject.connectSlotsByName(customEditDialog) QtCore.QMetaObject.connectSlotsByName(customEditDialog)
def retranslateUi(self, customEditDialog): def retranslateUi(self, customEditDialog):

View File

@ -29,7 +29,7 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.custom.lib import CustomXMLBuilder, CustomXMLParser from openlp.plugins.custom.lib import CustomXMLBuilder, CustomXMLParser
from openlp.plugins.custom.lib.db import CustomSlide from openlp.plugins.custom.lib.db import CustomSlide
from editcustomdialog import Ui_CustomEditDialog from editcustomdialog import Ui_CustomEditDialog
@ -136,15 +136,15 @@ class EditCustomForm(QtGui.QDialog, Ui_CustomEditDialog):
if preview: if preview:
self.previewButton.setVisible(True) self.previewButton.setVisible(True)
def closePressed(self): def reject(self):
Receiver.send_message(u'custom_edit_clear') Receiver.send_message(u'custom_edit_clear')
self.close() QtGui.QDialog.reject(self)
def accept(self): def accept(self):
log.debug(u'accept') log.debug(u'accept')
if self.saveCustom(): if self.saveCustom():
Receiver.send_message(u'custom_load_list') Receiver.send_message(u'custom_load_list')
self.close() QtGui.QDialog.accept(self)
def saveCustom(self): def saveCustom(self):
""" """
@ -152,7 +152,7 @@ class EditCustomForm(QtGui.QDialog, Ui_CustomEditDialog):
""" """
valid, message = self._validate() valid, message = self._validate()
if not valid: if not valid:
criticalErrorMessageBox(message=message) critical_error_message_box(message=message)
return False return False
sxml = CustomXMLBuilder() sxml = CustomXMLBuilder()
sxml.new_document() sxml.new_document()

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate, SpellTextEdit from openlp.core.lib import translate, SpellTextEdit
from openlp.core.lib.ui import save_cancel_button_box
class Ui_CustomSlideEditDialog(object): class Ui_CustomSlideEditDialog(object):
def setupUi(self, customSlideEditDialog): def setupUi(self, customSlideEditDialog):
@ -36,20 +37,13 @@ class Ui_CustomSlideEditDialog(object):
self.slideTextEdit = SpellTextEdit(self) self.slideTextEdit = SpellTextEdit(self)
self.slideTextEdit.setObjectName(u'slideTextEdit') self.slideTextEdit.setObjectName(u'slideTextEdit')
self.dialogLayout.addWidget(self.slideTextEdit) self.dialogLayout.addWidget(self.slideTextEdit)
self.buttonBox = QtGui.QDialogButtonBox(customSlideEditDialog) self.buttonBox = save_cancel_button_box(customSlideEditDialog)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel |
QtGui.QDialogButtonBox.Save)
self.buttonBox.setObjectName(u'buttonBox')
self.splitButton = QtGui.QPushButton(customSlideEditDialog) self.splitButton = QtGui.QPushButton(customSlideEditDialog)
self.splitButton.setObjectName(u'splitButton') self.splitButton.setObjectName(u'splitButton')
self.buttonBox.addButton(self.splitButton, self.buttonBox.addButton(self.splitButton,
QtGui.QDialogButtonBox.ActionRole) QtGui.QDialogButtonBox.ActionRole)
self.dialogLayout.addWidget(self.buttonBox) self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(customSlideEditDialog) self.retranslateUi(customSlideEditDialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'accepted()'),
customSlideEditDialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'rejected()'),
customSlideEditDialog.reject)
QtCore.QMetaObject.connectSlotsByName(customSlideEditDialog) QtCore.QMetaObject.connectSlotsByName(customSlideEditDialog)
def retranslateUi(self, customSlideEditDialog): def retranslateUi(self, customSlideEditDialog):

View File

@ -68,9 +68,6 @@ class CustomMediaItem(MediaManagerItem):
QtCore.QObject.connect(Receiver.get_receiver(), QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'custom_preview'), self.onPreviewClick) QtCore.SIGNAL(u'custom_preview'), self.onPreviewClick)
def requiredIcons(self):
MediaManagerItem.requiredIcons(self)
def initialise(self): def initialise(self):
self.loadCustomListView(self.manager.get_all_objects( self.loadCustomListView(self.manager.get_all_objects(
CustomSlide, order_by_ref=CustomSlide.title)) CustomSlide, order_by_ref=CustomSlide.title))
@ -149,16 +146,7 @@ class CustomMediaItem(MediaManagerItem):
raw_footer = [] raw_footer = []
slide = None slide = None
theme = None theme = None
if item is None: item_id = self._getIdOfItemToGenerate(item, self.remoteCustom)
if self.remoteTriggered is None:
item = self.listView.currentItem()
if item is None:
return False
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
else:
item_id = self.remoteCustom
else:
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
service_item.add_capability(ItemCapabilities.AllowsEdit) service_item.add_capability(ItemCapabilities.AllowsEdit)
service_item.add_capability(ItemCapabilities.AllowsPreview) service_item.add_capability(ItemCapabilities.AllowsPreview)
service_item.add_capability(ItemCapabilities.AllowsLoop) service_item.add_capability(ItemCapabilities.AllowsLoop)

View File

@ -31,8 +31,8 @@ from PyQt4 import QtCore, QtGui
from openlp.core.lib import MediaManagerItem, BaseListWithDnD, build_icon, \ from openlp.core.lib import MediaManagerItem, BaseListWithDnD, build_icon, \
ItemCapabilities, SettingsManager, translate, check_item_selected, \ ItemCapabilities, SettingsManager, translate, check_item_selected, \
check_directory_exists check_directory_exists, Receiver
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.core.utils import AppLocation, delete_file, get_images_filter from openlp.core.utils import AppLocation, delete_file, get_images_filter
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -44,7 +44,6 @@ class ImageListView(BaseListWithDnD):
self.PluginName = u'Images' self.PluginName = u'Images'
BaseListWithDnD.__init__(self, parent) BaseListWithDnD.__init__(self, parent)
class ImageMediaItem(MediaManagerItem): class ImageMediaItem(MediaManagerItem):
""" """
This is the custom media manager item for images. This is the custom media manager item for images.
@ -57,6 +56,8 @@ class ImageMediaItem(MediaManagerItem):
# be instanced by the base MediaManagerItem. # be instanced by the base MediaManagerItem.
self.ListViewWithDnD_class = ImageListView self.ListViewWithDnD_class = ImageListView
MediaManagerItem.__init__(self, parent, self, icon) MediaManagerItem.__init__(self, parent, self, icon)
QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'live_theme_changed'), self.liveThemeChanged)
def retranslateUi(self): def retranslateUi(self):
self.OnNewPrompt = translate('ImagePlugin.MediaItem', self.OnNewPrompt = translate('ImagePlugin.MediaItem',
@ -95,7 +96,6 @@ class ImageMediaItem(MediaManagerItem):
def addListViewToToolBar(self): def addListViewToToolBar(self):
MediaManagerItem.addListViewToToolBar(self) MediaManagerItem.addListViewToToolBar(self)
self.listView.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
self.listView.addAction(self.replaceAction) self.listView.addAction(self.replaceAction)
def addEndHeaderBar(self): def addEndHeaderBar(self):
@ -142,7 +142,7 @@ class ImageMediaItem(MediaManagerItem):
items = self.listView.selectedIndexes() items = self.listView.selectedIndexes()
if items: if items:
service_item.title = unicode( service_item.title = unicode(
translate('ImagePlugin.MediaItem', 'Image(s)')) translate('ImagePlugin.MediaItem', 'Images'))
service_item.add_capability(ItemCapabilities.AllowsMaintain) service_item.add_capability(ItemCapabilities.AllowsMaintain)
service_item.add_capability(ItemCapabilities.AllowsPreview) service_item.add_capability(ItemCapabilities.AllowsPreview)
service_item.add_capability(ItemCapabilities.AllowsLoop) service_item.add_capability(ItemCapabilities.AllowsLoop)
@ -161,7 +161,7 @@ class ImageMediaItem(MediaManagerItem):
items.remove(item) items.remove(item)
# We cannot continue, as all images do not exist. # We cannot continue, as all images do not exist.
if not items: if not items:
criticalErrorMessageBox( critical_error_message_box(
translate('ImagePlugin.MediaItem', 'Missing Image(s)'), translate('ImagePlugin.MediaItem', 'Missing Image(s)'),
unicode(translate('ImagePlugin.MediaItem', unicode(translate('ImagePlugin.MediaItem',
'The following image(s) no longer exist: %s')) % 'The following image(s) no longer exist: %s')) %
@ -193,6 +193,12 @@ class ImageMediaItem(MediaManagerItem):
self.resetAction.setVisible(False) self.resetAction.setVisible(False)
self.parent.liveController.display.resetImage() self.parent.liveController.display.resetImage()
def liveThemeChanged(self):
"""
Triggered by the change of theme in the slide controller
"""
self.resetAction.setVisible(False)
def onReplaceClick(self): def onReplaceClick(self):
""" """
Called to replace Live backgound with the image selected. Called to replace Live backgound with the image selected.
@ -208,11 +214,8 @@ class ImageMediaItem(MediaManagerItem):
self.parent.liveController.display.directImage(name, filename) self.parent.liveController.display.directImage(name, filename)
self.resetAction.setVisible(True) self.resetAction.setVisible(True)
else: else:
criticalErrorMessageBox( critical_error_message_box(
translate('ImagePlugin.MediaItem', 'Live Background Error'), translate('ImagePlugin.MediaItem', 'Live Background Error'),
unicode(translate('ImagePlugin.MediaItem', unicode(translate('ImagePlugin.MediaItem',
'There was a problem replacing your background, ' 'There was a problem replacing your background, '
'the image file "%s" no longer exists.')) % filename) 'the image file "%s" no longer exists.')) % filename)
def onPreviewClick(self):
MediaManagerItem.onPreviewClick(self)

View File

@ -30,8 +30,8 @@ import os
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import MediaManagerItem, BaseListWithDnD, build_icon, \ from openlp.core.lib import MediaManagerItem, BaseListWithDnD, build_icon, \
ItemCapabilities, SettingsManager, translate, check_item_selected ItemCapabilities, SettingsManager, translate, check_item_selected, Receiver
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -57,7 +57,9 @@ class MediaMediaItem(MediaManagerItem):
u':/media/media_video.png').toImage() u':/media/media_video.png').toImage()
MediaManagerItem.__init__(self, parent, self, icon) MediaManagerItem.__init__(self, parent, self, icon)
self.singleServiceItem = False self.singleServiceItem = False
self.serviceItemIconName = u':/media/image_clapperboard.png' QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'video_background_replaced'),
self.videobackgroundReplaced)
def retranslateUi(self): def retranslateUi(self):
self.OnNewPrompt = translate('MediaPlugin.MediaItem', 'Select Media') self.OnNewPrompt = translate('MediaPlugin.MediaItem', 'Select Media')
@ -81,7 +83,6 @@ class MediaMediaItem(MediaManagerItem):
def addListViewToToolBar(self): def addListViewToToolBar(self):
MediaManagerItem.addListViewToToolBar(self) MediaManagerItem.addListViewToToolBar(self)
self.listView.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
self.listView.addAction(self.replaceAction) self.listView.addAction(self.replaceAction)
def addEndHeaderBar(self): def addEndHeaderBar(self):
@ -99,6 +100,12 @@ class MediaMediaItem(MediaManagerItem):
self.resetAction.setVisible(False) self.resetAction.setVisible(False)
self.parent.liveController.display.resetVideo() self.parent.liveController.display.resetVideo()
def videobackgroundReplaced(self):
"""
Triggered by main display on change of serviceitem
"""
self.resetAction.setVisible(False)
def onReplaceClick(self): def onReplaceClick(self):
""" """
Called to replace Live backgound with the media selected. Called to replace Live backgound with the media selected.
@ -113,7 +120,7 @@ class MediaMediaItem(MediaManagerItem):
self.parent.liveController.display.video(filename, 0, True) self.parent.liveController.display.video(filename, 0, True)
self.resetAction.setVisible(True) self.resetAction.setVisible(True)
else: else:
criticalErrorMessageBox(translate('MediaPlugin.MediaItem', critical_error_message_box(translate('MediaPlugin.MediaItem',
'Live Background Error'), 'Live Background Error'),
unicode(translate('MediaPlugin.MediaItem', unicode(translate('MediaPlugin.MediaItem',
'There was a problem replacing your background, ' 'There was a problem replacing your background, '
@ -137,7 +144,7 @@ class MediaMediaItem(MediaManagerItem):
return True return True
else: else:
# File is no longer present # File is no longer present
criticalErrorMessageBox( critical_error_message_box(
translate('MediaPlugin.MediaItem', 'Missing Media File'), translate('MediaPlugin.MediaItem', 'Missing Media File'),
unicode(translate('MediaPlugin.MediaItem', unicode(translate('MediaPlugin.MediaItem',
'The file %s no longer exists.')) % filename) 'The file %s no longer exists.')) % filename)

View File

@ -171,11 +171,11 @@ class ImpressController(PresentationController):
desktop = self.get_com_desktop() desktop = self.get_com_desktop()
#Sometimes we get a failure and desktop is None #Sometimes we get a failure and desktop is None
if not desktop: if not desktop:
log.exception(u'Failed to terminate OpenOffice') log.exception(u'Failed to find an OpenOffice desktop to terminate')
return return
docs = desktop.getComponents() docs = desktop.getComponents()
if docs.hasElements(): if docs.hasElements():
log.debug(u'OpenOffice not terminated') log.debug(u'OpenOffice not terminated as docs are still open')
else: else:
try: try:
desktop.terminate() desktop.terminate()

View File

@ -31,7 +31,7 @@ from PyQt4 import QtCore, QtGui
from openlp.core.lib import MediaManagerItem, BaseListWithDnD, build_icon, \ from openlp.core.lib import MediaManagerItem, BaseListWithDnD, build_icon, \
SettingsManager, translate, check_item_selected, Receiver, ItemCapabilities SettingsManager, translate, check_item_selected, Receiver, ItemCapabilities
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box, media_item_combo_box
from openlp.plugins.presentations.lib import MessageListener from openlp.plugins.presentations.lib import MessageListener
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -116,12 +116,8 @@ class PresentationMediaItem(MediaManagerItem):
self.displayLayout.setObjectName(u'displayLayout') self.displayLayout.setObjectName(u'displayLayout')
self.displayTypeLabel = QtGui.QLabel(self.presentationWidget) self.displayTypeLabel = QtGui.QLabel(self.presentationWidget)
self.displayTypeLabel.setObjectName(u'displayTypeLabel') self.displayTypeLabel.setObjectName(u'displayTypeLabel')
self.displayTypeComboBox = QtGui.QComboBox(self.presentationWidget) self.displayTypeComboBox = media_item_combo_box(
self.displayTypeComboBox.setSizeAdjustPolicy( self.presentationWidget, u'displayTypeComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.displayTypeComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.displayTypeComboBox.setObjectName(u'displayTypeComboBox')
self.displayTypeLabel.setBuddy(self.displayTypeComboBox) self.displayTypeLabel.setBuddy(self.displayTypeComboBox)
self.displayLayout.addRow(self.displayTypeLabel, self.displayLayout.addRow(self.displayTypeLabel,
self.displayTypeComboBox) self.displayTypeComboBox)
@ -181,7 +177,7 @@ class PresentationMediaItem(MediaManagerItem):
filename = os.path.split(unicode(file))[1] filename = os.path.split(unicode(file))[1]
if titles.count(filename) > 0: if titles.count(filename) > 0:
if not initialLoad: if not initialLoad:
criticalErrorMessageBox( critical_error_message_box(
translate('PresentationPlugin.MediaItem', translate('PresentationPlugin.MediaItem',
'File Exists'), 'File Exists'),
translate('PresentationPlugin.MediaItem', translate('PresentationPlugin.MediaItem',
@ -205,7 +201,7 @@ class PresentationMediaItem(MediaManagerItem):
if initialLoad: if initialLoad:
icon = build_icon(u':/general/general_delete.png') icon = build_icon(u':/general/general_delete.png')
else: else:
criticalErrorMessageBox( critical_error_message_box(
self, translate('PresentationPlugin.MediaItem', self, translate('PresentationPlugin.MediaItem',
'Unsupported File'), 'Unsupported File'),
translate('PresentationPlugin.MediaItem', translate('PresentationPlugin.MediaItem',
@ -250,6 +246,7 @@ class PresentationMediaItem(MediaManagerItem):
service_item.title = unicode(self.displayTypeComboBox.currentText()) service_item.title = unicode(self.displayTypeComboBox.currentText())
service_item.shortname = unicode(self.displayTypeComboBox.currentText()) service_item.shortname = unicode(self.displayTypeComboBox.currentText())
service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay) service_item.add_capability(ItemCapabilities.ProvidesOwnDisplay)
service_item.add_capability(ItemCapabilities.AllowsDetailedTitleDisplay)
shortname = service_item.shortname shortname = service_item.shortname
if shortname: if shortname:
for item in items: for item in items:
@ -277,7 +274,7 @@ class PresentationMediaItem(MediaManagerItem):
return True return True
else: else:
# File is no longer present # File is no longer present
criticalErrorMessageBox( critical_error_message_box(
translate('PresentationPlugin.MediaItem', translate('PresentationPlugin.MediaItem',
'Missing Presentation'), 'Missing Presentation'),
unicode(translate('PresentationPlugin.MediaItem', unicode(translate('PresentationPlugin.MediaItem',
@ -286,7 +283,7 @@ class PresentationMediaItem(MediaManagerItem):
return False return False
else: else:
# File is no longer present # File is no longer present
criticalErrorMessageBox( critical_error_message_box(
translate('PresentationPlugin.MediaItem', translate('PresentationPlugin.MediaItem',
'Missing Presentation'), 'Missing Presentation'),
unicode(translate('PresentationPlugin.MediaItem', unicode(translate('PresentationPlugin.MediaItem',

View File

@ -116,7 +116,7 @@ class Controller(object):
def last(self): def last(self):
""" """
Based on the handler passed at startup triggers the first slide Based on the handler passed at startup triggers the last slide
""" """
log.debug(u'Live = %s, last' % self.is_live) log.debug(u'Live = %s, last' % self.is_live)
if not self.is_live: if not self.is_live:

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.lib.ui import save_cancel_button_box
class Ui_AuthorsDialog(object): class Ui_AuthorsDialog(object):
def setupUi(self, authorsDialog): def setupUi(self, authorsDialog):
@ -55,17 +56,9 @@ class Ui_AuthorsDialog(object):
self.displayLabel.setBuddy(self.displayEdit) self.displayLabel.setBuddy(self.displayEdit)
self.authorLayout.addRow(self.displayLabel, self.displayEdit) self.authorLayout.addRow(self.displayLabel, self.displayEdit)
self.dialogLayout.addLayout(self.authorLayout) self.dialogLayout.addLayout(self.authorLayout)
self.buttonBox = QtGui.QDialogButtonBox(authorsDialog) self.dialogLayout.addWidget(save_cancel_button_box(authorsDialog))
self.buttonBox.setStandardButtons(
QtGui.QDialogButtonBox.Save | QtGui.QDialogButtonBox.Cancel)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(authorsDialog) self.retranslateUi(authorsDialog)
authorsDialog.setMaximumHeight(authorsDialog.sizeHint().height()) authorsDialog.setMaximumHeight(authorsDialog.sizeHint().height())
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'accepted()'), authorsDialog.accept)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'rejected()'), authorsDialog.reject)
QtCore.QMetaObject.connectSlotsByName(authorsDialog) QtCore.QMetaObject.connectSlotsByName(authorsDialog)
def retranslateUi(self, authorsDialog): def retranslateUi(self, authorsDialog):

View File

@ -27,7 +27,7 @@
from PyQt4 import QtGui, QtCore from PyQt4 import QtGui, QtCore
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.songs.forms.authorsdialog import Ui_AuthorsDialog from openlp.plugins.songs.forms.authorsdialog import Ui_AuthorsDialog
class AuthorsForm(QtGui.QDialog, Ui_AuthorsDialog): class AuthorsForm(QtGui.QDialog, Ui_AuthorsDialog):
@ -80,17 +80,19 @@ class AuthorsForm(QtGui.QDialog, Ui_AuthorsDialog):
def accept(self): def accept(self):
if not self.firstNameEdit.text(): if not self.firstNameEdit.text():
criticalErrorMessageBox(message=translate('SongsPlugin.AuthorsForm', critical_error_message_box(
message=translate('SongsPlugin.AuthorsForm',
'You need to type in the first name of the author.')) 'You need to type in the first name of the author.'))
self.firstNameEdit.setFocus() self.firstNameEdit.setFocus()
return False return False
elif not self.lastNameEdit.text(): elif not self.lastNameEdit.text():
criticalErrorMessageBox(message=translate('SongsPlugin.AuthorsForm', critical_error_message_box(
message=translate('SongsPlugin.AuthorsForm',
'You need to type in the last name of the author.')) 'You need to type in the last name of the author.'))
self.lastNameEdit.setFocus() self.lastNameEdit.setFocus()
return False return False
elif not self.displayEdit.text(): elif not self.displayEdit.text():
if criticalErrorMessageBox( if critical_error_message_box(
message=translate('SongsPlugin.AuthorsForm', message=translate('SongsPlugin.AuthorsForm',
'You have not set a display name for the ' 'You have not set a display name for the '
'author, combine the first and last names?'), 'author, combine the first and last names?'),

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import build_icon, translate from openlp.core.lib import build_icon, translate
from openlp.core.lib.ui import save_cancel_button_box
class Ui_EditSongDialog(object): class Ui_EditSongDialog(object):
def setupUi(self, editSongDialog): def setupUi(self, editSongDialog):
@ -111,14 +112,8 @@ class Ui_EditSongDialog(object):
self.authorsLayout.setObjectName(u'authorsLayout') self.authorsLayout.setObjectName(u'authorsLayout')
self.authorAddLayout = QtGui.QHBoxLayout() self.authorAddLayout = QtGui.QHBoxLayout()
self.authorAddLayout.setObjectName(u'authorAddLayout') self.authorAddLayout.setObjectName(u'authorAddLayout')
self.authorsComboBox = QtGui.QComboBox(self.authorsGroupBox) self.authorsComboBox = editSongDialogComboBox(
self.authorsComboBox.setSizeAdjustPolicy( self.authorsGroupBox, u'authorsComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.authorsComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.authorsComboBox.setEditable(True)
self.authorsComboBox.setInsertPolicy(QtGui.QComboBox.NoInsert)
self.authorsComboBox.setObjectName(u'authorsComboBox')
self.authorAddLayout.addWidget(self.authorsComboBox) self.authorAddLayout.addWidget(self.authorsComboBox)
self.authorAddButton = QtGui.QPushButton(self.authorsGroupBox) self.authorAddButton = QtGui.QPushButton(self.authorsGroupBox)
self.authorAddButton.setObjectName(u'authorAddButton') self.authorAddButton.setObjectName(u'authorAddButton')
@ -152,14 +147,8 @@ class Ui_EditSongDialog(object):
self.topicsLayout.setObjectName(u'topicsLayout') self.topicsLayout.setObjectName(u'topicsLayout')
self.topicAddLayout = QtGui.QHBoxLayout() self.topicAddLayout = QtGui.QHBoxLayout()
self.topicAddLayout.setObjectName(u'topicAddLayout') self.topicAddLayout.setObjectName(u'topicAddLayout')
self.topicsComboBox = QtGui.QComboBox(self.topicsGroupBox) self.topicsComboBox = editSongDialogComboBox(
self.topicsComboBox.setSizeAdjustPolicy( self.topicsGroupBox, u'topicsComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.topicsComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.topicsComboBox.setEditable(True)
self.topicsComboBox.setInsertPolicy(QtGui.QComboBox.NoInsert)
self.topicsComboBox.setObjectName(u'topicsComboBox')
self.topicAddLayout.addWidget(self.topicsComboBox) self.topicAddLayout.addWidget(self.topicsComboBox)
self.topicAddButton = QtGui.QPushButton(self.topicsGroupBox) self.topicAddButton = QtGui.QPushButton(self.topicsGroupBox)
self.topicAddButton.setObjectName(u'topicAddButton') self.topicAddButton.setObjectName(u'topicAddButton')
@ -183,14 +172,8 @@ class Ui_EditSongDialog(object):
self.songBookLayout.setObjectName(u'songBookLayout') self.songBookLayout.setObjectName(u'songBookLayout')
self.songBookNameLabel = QtGui.QLabel(self.songBookGroupBox) self.songBookNameLabel = QtGui.QLabel(self.songBookGroupBox)
self.songBookNameLabel.setObjectName(u'songBookNameLabel') self.songBookNameLabel.setObjectName(u'songBookNameLabel')
self.songBookComboBox = QtGui.QComboBox(self.songBookGroupBox) self.songBookComboBox = editSongDialogComboBox(
self.songBookComboBox.setSizeAdjustPolicy( self.songBookGroupBox, u'songBookComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.songBookComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.songBookComboBox.setEditable(True)
self.songBookComboBox.setInsertPolicy(QtGui.QComboBox.NoInsert)
self.songBookComboBox.setObjectName(u'songBookComboBox')
self.songBookNameLabel.setBuddy(self.songBookComboBox) self.songBookNameLabel.setBuddy(self.songBookComboBox)
self.songBookLayout.addRow(self.songBookNameLabel, self.songBookLayout.addRow(self.songBookNameLabel,
self.songBookComboBox) self.songBookComboBox)
@ -215,14 +198,8 @@ class Ui_EditSongDialog(object):
self.themeGroupBox.setObjectName(u'themeGroupBox') self.themeGroupBox.setObjectName(u'themeGroupBox')
self.themeLayout = QtGui.QHBoxLayout(self.themeGroupBox) self.themeLayout = QtGui.QHBoxLayout(self.themeGroupBox)
self.themeLayout.setObjectName(u'themeLayout') self.themeLayout.setObjectName(u'themeLayout')
self.themeComboBox = QtGui.QComboBox(self.themeGroupBox) self.themeComboBox = editSongDialogComboBox(
self.themeComboBox.setSizeAdjustPolicy( self.themeGroupBox, u'themeComboBox')
QtGui.QComboBox.AdjustToMinimumContentsLength)
self.themeComboBox.setSizePolicy(
QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
self.themeComboBox.setEditable(True)
self.themeComboBox.setInsertPolicy(QtGui.QComboBox.NoInsert)
self.themeComboBox.setObjectName(u'themeComboBox')
self.themeLayout.addWidget(self.themeComboBox) self.themeLayout.addWidget(self.themeComboBox)
self.themeAddButton = QtGui.QPushButton(self.themeGroupBox) self.themeAddButton = QtGui.QPushButton(self.themeGroupBox)
self.themeAddButton.setObjectName(u'themeAddButton') self.themeAddButton.setObjectName(u'themeAddButton')
@ -264,16 +241,9 @@ class Ui_EditSongDialog(object):
self.themeTabLayout.addWidget(self.commentsGroupBox) self.themeTabLayout.addWidget(self.commentsGroupBox)
self.songTabWidget.addTab(self.themeTab, u'') self.songTabWidget.addTab(self.themeTab, u'')
self.dialogLayout.addWidget(self.songTabWidget) self.dialogLayout.addWidget(self.songTabWidget)
self.buttonBox = QtGui.QDialogButtonBox(editSongDialog) self.buttonBox = save_cancel_button_box(editSongDialog)
self.buttonBox.setStandardButtons(
QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Save)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox) self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(editSongDialog) self.retranslateUi(editSongDialog)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'rejected()'), editSongDialog.closePressed)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'accepted()'), editSongDialog.accept)
QtCore.QMetaObject.connectSlotsByName(editSongDialog) QtCore.QMetaObject.connectSlotsByName(editSongDialog)
def retranslateUi(self, editSongDialog): def retranslateUi(self, editSongDialog):
@ -338,3 +308,15 @@ class Ui_EditSongDialog(object):
self.songTabWidget.indexOf(self.themeTab), self.songTabWidget.indexOf(self.themeTab),
translate('SongsPlugin.EditSongForm', translate('SongsPlugin.EditSongForm',
'Theme, Copyright Info && Comments')) 'Theme, Copyright Info && Comments'))
def editSongDialogComboBox(parent, name):
"""
Utility method to generate a standard combo box for this dialog.
"""
comboBox = QtGui.QComboBox(parent)
comboBox.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToMinimumContentsLength)
comboBox.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
comboBox.setEditable(True)
comboBox.setInsertPolicy(QtGui.QComboBox.NoInsert)
comboBox.setObjectName(name)
return comboBox

View File

@ -30,7 +30,7 @@ import re
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.songs.forms import EditVerseForm from openlp.plugins.songs.forms import EditVerseForm
from openlp.plugins.songs.lib import SongXML, VerseType from openlp.plugins.songs.lib import SongXML, VerseType
from openlp.plugins.songs.lib.db import Book, Song, Author, Topic from openlp.plugins.songs.lib.db import Book, Song, Author, Topic
@ -255,7 +255,6 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
self.songBookNumberEdit.setText(self.song.song_number) self.songBookNumberEdit.setText(self.song.song_number)
else: else:
self.songBookNumberEdit.setText(u'') self.songBookNumberEdit.setText(u'')
# lazy xml migration for now # lazy xml migration for now
self.verseListWidget.clear() self.verseListWidget.clear()
self.verseListWidget.setRowCount(0) self.verseListWidget.setRowCount(0)
@ -333,11 +332,7 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
author = Author.populate(first_name=text.rsplit(u' ', 1)[0], author = Author.populate(first_name=text.rsplit(u' ', 1)[0],
last_name=text.rsplit(u' ', 1)[1], display_name=text) last_name=text.rsplit(u' ', 1)[1], display_name=text)
self.manager.save_object(author) self.manager.save_object(author)
author_item = QtGui.QListWidgetItem( self.__addAuthorToList(author)
unicode(author.display_name))
author_item.setData(QtCore.Qt.UserRole,
QtCore.QVariant(author.id))
self.authorsListView.addItem(author_item)
self.loadAuthors() self.loadAuthors()
self.authorsComboBox.setCurrentIndex(0) self.authorsComboBox.setCurrentIndex(0)
else: else:
@ -347,15 +342,11 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
author = self.manager.get_object(Author, item_id) author = self.manager.get_object(Author, item_id)
if self.authorsListView.findItems(unicode(author.display_name), if self.authorsListView.findItems(unicode(author.display_name),
QtCore.Qt.MatchExactly): QtCore.Qt.MatchExactly):
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'This author is already in the list.')) 'This author is already in the list.'))
else: else:
author_item = QtGui.QListWidgetItem(unicode( self.__addAuthorToList(author)
author.display_name))
author_item.setData(QtCore.Qt.UserRole,
QtCore.QVariant(author.id))
self.authorsListView.addItem(author_item)
self.authorsComboBox.setCurrentIndex(0) self.authorsComboBox.setCurrentIndex(0)
else: else:
QtGui.QMessageBox.warning(self, QtGui.QMessageBox.warning(self,
@ -365,6 +356,14 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
'or type in a new author and click the "Add Author to ' 'or type in a new author and click the "Add Author to '
'Song" button to add the new author.')) 'Song" button to add the new author.'))
def __addAuthorToList(self, author):
"""
Add an author to the author list.
"""
author_item = QtGui.QListWidgetItem(unicode(author.display_name))
author_item.setData(QtCore.Qt.UserRole, QtCore.QVariant(author.id))
self.authorsListView.addItem(author_item)
def onAuthorsListViewPressed(self): def onAuthorsListViewPressed(self):
if self.authorsListView.count() > 1: if self.authorsListView.count() > 1:
self.authorRemoveButton.setEnabled(True) self.authorRemoveButton.setEnabled(True)
@ -400,7 +399,7 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
topic = self.manager.get_object(Topic, item_id) topic = self.manager.get_object(Topic, item_id)
if self.topicsListView.findItems(unicode(topic.name), if self.topicsListView.findItems(unicode(topic.name),
QtCore.Qt.MatchExactly): QtCore.Qt.MatchExactly):
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'This topic is already in the list.')) 'This topic is already in the list.'))
else: else:
@ -533,21 +532,21 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
if not self.titleEdit.text(): if not self.titleEdit.text():
self.songTabWidget.setCurrentIndex(0) self.songTabWidget.setCurrentIndex(0)
self.titleEdit.setFocus() self.titleEdit.setFocus()
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'You need to type in a song title.')) 'You need to type in a song title.'))
return False return False
if self.verseListWidget.rowCount() == 0: if self.verseListWidget.rowCount() == 0:
self.songTabWidget.setCurrentIndex(0) self.songTabWidget.setCurrentIndex(0)
self.verseListWidget.setFocus() self.verseListWidget.setFocus()
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'You need to type in at least one verse.')) 'You need to type in at least one verse.'))
return False return False
if self.authorsListView.count() == 0: if self.authorsListView.count() == 0:
self.songTabWidget.setCurrentIndex(1) self.songTabWidget.setCurrentIndex(1)
self.authorsListView.setFocus() self.authorsListView.setFocus()
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'You need to have an author for this song.')) 'You need to have an author for this song.'))
return False return False
@ -575,7 +574,7 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
valid = verses.pop(0) valid = verses.pop(0)
for verse in verses: for verse in verses:
valid = valid + u', ' + verse valid = valid + u', ' + verse
criticalErrorMessageBox( critical_error_message_box(
message=unicode(translate('SongsPlugin.EditSongForm', message=unicode(translate('SongsPlugin.EditSongForm',
'The verse order is invalid. There is no verse ' 'The verse order is invalid. There is no verse '
'corresponding to %s. Valid entries are %s.')) % \ 'corresponding to %s. Valid entries are %s.')) % \
@ -648,29 +647,31 @@ class EditSongForm(QtGui.QDialog, Ui_EditSongDialog):
""" """
Free up autocompletion memory on dialog exit Free up autocompletion memory on dialog exit
""" """
log.debug (u'SongEditForm.clearCaches')
self.authors = [] self.authors = []
self.themes = [] self.themes = []
self.books = [] self.books = []
self.topics = [] self.topics = []
def closePressed(self): def reject(self):
""" """
Exit Dialog and do not save Exit Dialog and do not save
""" """
log.debug (u'SongEditForm.reject')
Receiver.send_message(u'songs_edit_clear') Receiver.send_message(u'songs_edit_clear')
self.clearCaches() self.clearCaches()
self.close() QtGui.QDialog.reject(self)
def accept(self): def accept(self):
""" """
Exit Dialog and save song if valid Exit Dialog and save song if valid
""" """
log.debug(u'accept') log.debug(u'SongEditForm.accept')
self.clearCaches() self.clearCaches()
if self._validate_song(): if self._validate_song():
self.saveSong() self.saveSong()
Receiver.send_message(u'songs_load_list') Receiver.send_message(u'songs_load_list')
self.close() QtGui.QDialog.accept(self)
def saveSong(self, preview=False): def saveSong(self, preview=False):
""" """

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import build_icon, translate, SpellTextEdit from openlp.core.lib import build_icon, translate, SpellTextEdit
from openlp.core.lib.ui import save_cancel_button_box
from openlp.plugins.songs.lib import VerseType from openlp.plugins.songs.lib import VerseType
class Ui_EditVerseDialog(object): class Ui_EditVerseDialog(object):
@ -59,17 +60,8 @@ class Ui_EditVerseDialog(object):
self.verseTypeLayout.addWidget(self.insertButton) self.verseTypeLayout.addWidget(self.insertButton)
self.verseTypeLayout.addStretch() self.verseTypeLayout.addStretch()
self.dialogLayout.addLayout(self.verseTypeLayout) self.dialogLayout.addLayout(self.verseTypeLayout)
self.buttonBox = QtGui.QDialogButtonBox(editVerseDialog) self.dialogLayout.addWidget(save_cancel_button_box(editVerseDialog))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel |
QtGui.QDialogButtonBox.Save)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(editVerseDialog) self.retranslateUi(editVerseDialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'accepted()'),
editVerseDialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(u'rejected()'),
editVerseDialog.reject)
QtCore.QMetaObject.connectSlotsByName(editVerseDialog) QtCore.QMetaObject.connectSlotsByName(editVerseDialog)
def retranslateUi(self, editVerseDialog): def retranslateUi(self, editVerseDialog):

View File

@ -29,7 +29,7 @@ import logging
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.songs.lib import VerseType, translate from openlp.plugins.songs.lib import VerseType, translate
from editversedialog import Ui_EditVerseDialog from editversedialog import Ui_EditVerseDialog
@ -168,7 +168,7 @@ class EditVerseForm(QtGui.QDialog, Ui_EditVerseDialog):
else: else:
value = self.getVerse()[0].split(u'\n')[1] value = self.getVerse()[0].split(u'\n')[1]
if len(value) == 0: if len(value) == 0:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'You need to type some text in to the verse.')) 'You need to type some text in to the verse.'))
return False return False

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.lib.ui import save_cancel_button_box
class Ui_SongBookDialog(object): class Ui_SongBookDialog(object):
def setupUi(self, songBookDialog): def setupUi(self, songBookDialog):
@ -49,17 +50,9 @@ class Ui_SongBookDialog(object):
self.publisherLabel.setBuddy(self.publisherEdit) self.publisherLabel.setBuddy(self.publisherEdit)
self.bookLayout.addRow(self.publisherLabel, self.publisherEdit) self.bookLayout.addRow(self.publisherLabel, self.publisherEdit)
self.dialogLayout.addLayout(self.bookLayout) self.dialogLayout.addLayout(self.bookLayout)
self.buttonBox = QtGui.QDialogButtonBox(songBookDialog) self.dialogLayout.addWidget(save_cancel_button_box(songBookDialog))
self.buttonBox.setStandardButtons(
QtGui.QDialogButtonBox.Save | QtGui.QDialogButtonBox.Cancel)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(songBookDialog) self.retranslateUi(songBookDialog)
songBookDialog.setMaximumHeight(songBookDialog.sizeHint().height()) songBookDialog.setMaximumHeight(songBookDialog.sizeHint().height())
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'accepted()'), songBookDialog.accept)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'rejected()'), songBookDialog.reject)
QtCore.QMetaObject.connectSlotsByName(songBookDialog) QtCore.QMetaObject.connectSlotsByName(songBookDialog)
def retranslateUi(self, songBookDialog): def retranslateUi(self, songBookDialog):

View File

@ -27,7 +27,7 @@
from PyQt4 import QtGui from PyQt4 import QtGui
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.songs.forms.songbookdialog import Ui_SongBookDialog from openlp.plugins.songs.forms.songbookdialog import Ui_SongBookDialog
class SongBookForm(QtGui.QDialog, Ui_SongBookDialog): class SongBookForm(QtGui.QDialog, Ui_SongBookDialog):
@ -50,7 +50,7 @@ class SongBookForm(QtGui.QDialog, Ui_SongBookDialog):
def accept(self): def accept(self):
if not self.nameEdit.text(): if not self.nameEdit.text():
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongBookForm', message=translate('SongsPlugin.SongBookForm',
'You need to type in a name for the book.')) 'You need to type in a name for the book.'))
self.nameEdit.setFocus() self.nameEdit.setFocus()

View File

@ -32,7 +32,7 @@ import os
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import Receiver, SettingsManager, translate from openlp.core.lib import Receiver, SettingsManager, translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.core.ui.wizard import OpenLPWizard from openlp.core.ui.wizard import OpenLPWizard
from openlp.plugins.songs.lib.importer import SongFormat from openlp.plugins.songs.lib.importer import SongFormat
@ -165,29 +165,29 @@ class SongImportForm(OpenLPWizard):
self.formatStack = QtGui.QStackedLayout() self.formatStack = QtGui.QStackedLayout()
self.formatStack.setObjectName(u'FormatStack') self.formatStack.setObjectName(u'FormatStack')
# OpenLP 2.0 # OpenLP 2.0
self.addSingleFileSelectItem(u'openLP2') self.addFileSelectItem(u'openLP2', single_select=True)
# openlp.org 1.x # openlp.org 1.x
self.addSingleFileSelectItem(u'openLP1', None, True) self.addFileSelectItem(u'openLP1', None, True, True)
# OpenLyrics # OpenLyrics
self.addMultiFileSelectItem(u'openLyrics', u'OpenLyrics', True) self.addFileSelectItem(u'openLyrics', u'OpenLyrics', True)
# Open Song # Open Song
self.addMultiFileSelectItem(u'openSong', u'OpenSong') self.addFileSelectItem(u'openSong', u'OpenSong')
# Words of Worship # Words of Worship
self.addMultiFileSelectItem(u'wordsOfWorship') self.addFileSelectItem(u'wordsOfWorship')
# CCLI File import # CCLI File import
self.addMultiFileSelectItem(u'ccli') self.addFileSelectItem(u'ccli')
# Songs of Fellowship # Songs of Fellowship
self.addMultiFileSelectItem(u'songsOfFellowship', None, True) self.addFileSelectItem(u'songsOfFellowship', None, True)
# Generic Document/Presentation import # Generic Document/Presentation import
self.addMultiFileSelectItem(u'generic', None, True) self.addFileSelectItem(u'generic', None, True)
# EasySlides # EasySlides
self.addSingleFileSelectItem(u'easiSlides') self.addFileSelectItem(u'easiSlides', single_select=True)
# EasyWorship # EasyWorship
self.addSingleFileSelectItem(u'ew') self.addFileSelectItem(u'ew', single_select=True)
# Words of Worship # Words of Worship
self.addMultiFileSelectItem(u'songBeamer') self.addFileSelectItem(u'songBeamer')
# Commented out for future use. # Commented out for future use.
# self.addSingleFileSelectItem(u'csv', u'CSV') # self.addFileSelectItem(u'csv', u'CSV', single_select=True)
self.sourceLayout.addLayout(self.formatStack) self.sourceLayout.addLayout(self.formatStack)
self.addPage(self.sourcePage) self.addPage(self.sourcePage)
@ -318,16 +318,6 @@ class SongImportForm(OpenLPWizard):
self.openLP2FilenameLabel.minimumSizeHint().width()) self.openLP2FilenameLabel.minimumSizeHint().width())
self.formatSpacer.changeSize(width, 0, QtGui.QSizePolicy.Fixed, self.formatSpacer.changeSize(width, 0, QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Fixed) QtGui.QSizePolicy.Fixed)
self.openLP2FormLabelSpacer.changeSize(width, 0,
QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
self.openLP1FormLabelSpacer.changeSize(width, 0,
QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
self.easiSlidesFormLabelSpacer.changeSize(width, 0,
QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
self.ewFormLabelSpacer.changeSize(width, 0, QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Fixed)
# self.csvFormLabelSpacer.changeSize(width, 0, QtGui.QSizePolicy.Fixed,
# QtGui.QSizePolicy.Fixed)
def validateCurrentPage(self): def validateCurrentPage(self):
""" """
@ -339,7 +329,7 @@ class SongImportForm(OpenLPWizard):
source_format = self.formatComboBox.currentIndex() source_format = self.formatComboBox.currentIndex()
if source_format == SongFormat.OpenLP2: if source_format == SongFormat.OpenLP2:
if self.openLP2FilenameEdit.text().isEmpty(): if self.openLP2FilenameEdit.text().isEmpty():
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No OpenLP 2.0 Song Database Selected'), 'No OpenLP 2.0 Song Database Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -349,7 +339,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.OpenLP1: elif source_format == SongFormat.OpenLP1:
if self.openLP1FilenameEdit.text().isEmpty(): if self.openLP1FilenameEdit.text().isEmpty():
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No openlp.org 1.x Song Database Selected'), 'No openlp.org 1.x Song Database Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -359,7 +349,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.OpenLyrics: elif source_format == SongFormat.OpenLyrics:
if self.openLyricsFileListWidget.count() == 0: if self.openLyricsFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No OpenLyrics Files Selected'), 'No OpenLyrics Files Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -369,7 +359,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.OpenSong: elif source_format == SongFormat.OpenSong:
if self.openSongFileListWidget.count() == 0: if self.openSongFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No OpenSong Files Selected'), 'No OpenSong Files Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -379,7 +369,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.WordsOfWorship: elif source_format == SongFormat.WordsOfWorship:
if self.wordsOfWorshipFileListWidget.count() == 0: if self.wordsOfWorshipFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No Words of Worship Files Selected'), 'No Words of Worship Files Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -389,7 +379,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.CCLI: elif source_format == SongFormat.CCLI:
if self.ccliFileListWidget.count() == 0: if self.ccliFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No CCLI Files Selected'), 'No CCLI Files Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -399,7 +389,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.SongsOfFellowship: elif source_format == SongFormat.SongsOfFellowship:
if self.songsOfFellowshipFileListWidget.count() == 0: if self.songsOfFellowshipFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No Songs of Fellowship File Selected'), 'No Songs of Fellowship File Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -409,7 +399,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.Generic: elif source_format == SongFormat.Generic:
if self.genericFileListWidget.count() == 0: if self.genericFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No Document/Presentation Selected'), 'No Document/Presentation Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -419,7 +409,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.EasiSlides: elif source_format == SongFormat.EasiSlides:
if self.easiSlidesFilenameEdit.text().isEmpty(): if self.easiSlidesFilenameEdit.text().isEmpty():
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No Easislides Songs file selected'), 'No Easislides Songs file selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -429,7 +419,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.EasyWorship: elif source_format == SongFormat.EasyWorship:
if self.ewFilenameEdit.text().isEmpty(): if self.ewFilenameEdit.text().isEmpty():
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No EasyWorship Song Database Selected'), 'No EasyWorship Song Database Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -439,7 +429,7 @@ class SongImportForm(OpenLPWizard):
return False return False
elif source_format == SongFormat.SongBeamer: elif source_format == SongFormat.SongBeamer:
if self.songBeamerFileListWidget.count() == 0: if self.songBeamerFileListWidget.count() == 0:
criticalErrorMessageBox( critical_error_message_box(
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
'No SongBeamer File Selected'), 'No SongBeamer File Selected'),
translate('SongsPlugin.ImportWizardForm', translate('SongsPlugin.ImportWizardForm',
@ -791,52 +781,8 @@ class SongImportForm(OpenLPWizard):
translate('SongsPlugin.SongImportForm', translate('SongsPlugin.SongImportForm',
'Your song import failed.')) 'Your song import failed.'))
def addSingleFileSelectItem(self, prefix, obj_prefix=None, def addFileSelectItem(self, prefix, obj_prefix=None, can_disable=False,
can_disable=False): single_select=False):
if not obj_prefix:
obj_prefix = prefix
page = QtGui.QWidget()
page.setObjectName(obj_prefix + u'Page')
if can_disable:
importWidget = self.disablableWidget(page, prefix, obj_prefix)
else:
importWidget = page
importLayout = QtGui.QFormLayout(importWidget)
importLayout.setMargin(0)
if can_disable:
importLayout.setObjectName(obj_prefix + u'ImportLayout')
else:
importLayout.setObjectName(obj_prefix + u'Layout')
filenameLabel = QtGui.QLabel(importWidget)
filenameLabel.setObjectName(obj_prefix + u'FilenameLabel')
fileLayout = QtGui.QHBoxLayout()
fileLayout.setObjectName(obj_prefix + u'FileLayout')
filenameEdit = QtGui.QLineEdit(importWidget)
filenameEdit.setObjectName(obj_prefix + u'FilenameEdit')
fileLayout.addWidget(filenameEdit)
browseButton = QtGui.QToolButton(importWidget)
browseButton.setIcon(self.openIcon)
browseButton.setObjectName(obj_prefix + u'BrowseButton')
fileLayout.addWidget(browseButton)
importLayout.addRow(filenameLabel, fileLayout)
formSpacer = QtGui.QSpacerItem(10, 0, QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Minimum)
importLayout.setItem(1, QtGui.QFormLayout.LabelRole, formSpacer)
self.formatStack.addWidget(page)
setattr(self, prefix + u'Page', page)
setattr(self, prefix + u'FilenameLabel', filenameLabel)
setattr(self, prefix + u'FormLabelSpacer', formSpacer)
setattr(self, prefix + u'FileLayout', fileLayout)
setattr(self, prefix + u'FilenameEdit', filenameEdit)
setattr(self, prefix + u'BrowseButton', browseButton)
if can_disable:
setattr(self, prefix + u'ImportLayout', importLayout)
else:
setattr(self, prefix + u'Layout', importLayout)
self.formatComboBox.addItem(u'')
def addMultiFileSelectItem(self, prefix, obj_prefix=None,
can_disable=False):
if not obj_prefix: if not obj_prefix:
obj_prefix = prefix obj_prefix = prefix
page = QtGui.QWidget() page = QtGui.QWidget()
@ -847,10 +793,25 @@ class SongImportForm(OpenLPWizard):
importWidget = page importWidget = page
importLayout = QtGui.QVBoxLayout(importWidget) importLayout = QtGui.QVBoxLayout(importWidget)
importLayout.setMargin(0) importLayout.setMargin(0)
if can_disable:
importLayout.setObjectName(obj_prefix + u'ImportLayout') importLayout.setObjectName(obj_prefix + u'ImportLayout')
if single_select:
fileLayout = QtGui.QHBoxLayout()
fileLayout.setObjectName(obj_prefix + u'FileLayout')
filenameLabel = QtGui.QLabel(importWidget)
filenameLabel.setObjectName(obj_prefix + u'FilenameLabel')
fileLayout.addWidget(filenameLabel)
filenameEdit = QtGui.QLineEdit(importWidget)
filenameEdit.setObjectName(obj_prefix + u'FilenameEdit')
fileLayout.addWidget(filenameEdit)
browseButton = QtGui.QToolButton(importWidget)
browseButton.setIcon(self.openIcon)
browseButton.setObjectName(obj_prefix + u'BrowseButton')
fileLayout.addWidget(browseButton)
formSpacer = QtGui.QSpacerItem(10, 0, QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Expanding)
importLayout.addLayout(fileLayout)
importLayout.addSpacerItem(formSpacer)
else: else:
importLayout.setObjectName(obj_prefix + u'Layout')
fileListWidget = QtGui.QListWidget(importWidget) fileListWidget = QtGui.QListWidget(importWidget)
fileListWidget.setSelectionMode( fileListWidget.setSelectionMode(
QtGui.QAbstractItemView.ExtendedSelection) QtGui.QAbstractItemView.ExtendedSelection)
@ -870,14 +831,17 @@ class SongImportForm(OpenLPWizard):
importLayout.addLayout(buttonLayout) importLayout.addLayout(buttonLayout)
self.formatStack.addWidget(page) self.formatStack.addWidget(page)
setattr(self, prefix + u'Page', page) setattr(self, prefix + u'Page', page)
if single_select:
setattr(self, prefix + u'FilenameLabel', filenameLabel)
setattr(self, prefix + u'FileLayout', fileLayout)
setattr(self, prefix + u'FilenameEdit', filenameEdit)
setattr(self, prefix + u'BrowseButton', browseButton)
else:
setattr(self, prefix + u'FileListWidget', fileListWidget) setattr(self, prefix + u'FileListWidget', fileListWidget)
setattr(self, prefix + u'ButtonLayout', buttonLayout) setattr(self, prefix + u'ButtonLayout', buttonLayout)
setattr(self, prefix + u'AddButton', addButton) setattr(self, prefix + u'AddButton', addButton)
setattr(self, prefix + u'RemoveButton', removeButton) setattr(self, prefix + u'RemoveButton', removeButton)
if can_disable:
setattr(self, prefix + u'ImportLayout', importLayout) setattr(self, prefix + u'ImportLayout', importLayout)
else:
setattr(self, prefix + u'Layout', importLayout)
self.formatComboBox.addItem(u'') self.formatComboBox.addItem(u'')
def disablableWidget(self, page, prefix, obj_prefix): def disablableWidget(self, page, prefix, obj_prefix):

View File

@ -29,7 +29,7 @@ from PyQt4 import QtGui, QtCore
from sqlalchemy.sql import and_ from sqlalchemy.sql import and_
from openlp.core.lib import Receiver, translate from openlp.core.lib import Receiver, translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.songs.forms import AuthorsForm, TopicsForm, SongBookForm from openlp.plugins.songs.forms import AuthorsForm, TopicsForm, SongBookForm
from openlp.plugins.songs.lib.db import Author, Book, Topic, Song from openlp.plugins.songs.lib.db import Author, Book, Topic, Song
from songmaintenancedialog import Ui_SongMaintenanceDialog from songmaintenancedialog import Ui_SongMaintenanceDialog
@ -94,8 +94,8 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
self.typeListWidget.setFocus() self.typeListWidget.setFocus()
return QtGui.QDialog.exec_(self) return QtGui.QDialog.exec_(self)
def _getCurrentItemId(self, ListWidget): def _getCurrentItemId(self, listWidget):
item = ListWidget.currentItem() item = listWidget.currentItem()
if item: if item:
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0] item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
return item_id return item_id
@ -108,14 +108,14 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
if item_id != -1: if item_id != -1:
item = self.manager.get_object(item_class, item_id) item = self.manager.get_object(item_class, item_id)
if item and len(item.songs) == 0: if item and len(item.songs) == 0:
if criticalErrorMessageBox(title=dlg_title, message=del_text, if critical_error_message_box(title=dlg_title, message=del_text,
parent=self, question=True) == QtGui.QMessageBox.Yes: parent=self, question=True) == QtGui.QMessageBox.Yes:
self.manager.delete_object(item_class, item.id) self.manager.delete_object(item_class, item.id)
reset_func() reset_func()
else: else:
criticalErrorMessageBox(dlg_title, err_text) critical_error_message_box(dlg_title, err_text)
else: else:
criticalErrorMessageBox(dlg_title, sel_text) critical_error_message_box(dlg_title, sel_text)
def resetAuthors(self): def resetAuthors(self):
""" """
@ -159,66 +159,43 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
def checkAuthor(self, new_author, edit=False): def checkAuthor(self, new_author, edit=False):
""" """
Returns *False* if the given Author already exists, otherwise *True*. Returns *False* if the given Author already exists, otherwise *True*.
``edit``
If we edit an item, this should be *True*.
""" """
authors = self.manager.get_all_objects(Author, authors = self.manager.get_all_objects(Author,
and_(Author.first_name == new_author.first_name, and_(Author.first_name == new_author.first_name,
Author.last_name == new_author.last_name, Author.last_name == new_author.last_name,
Author.display_name == new_author.display_name)) Author.display_name == new_author.display_name))
# Check if this author already exists. return self.__checkObject(authors, new_author, edit)
if len(authors) > 0:
# If we edit an existing Author, we need to make sure that we do
# not return False when nothing has changed.
if edit:
for author in authors:
if author.id != new_author.id:
return False
return True
else:
return False
else:
return True
def checkTopic(self, new_topic, edit=False): def checkTopic(self, new_topic, edit=False):
""" """
Returns *False* if the given Topic already exists, otherwise *True*. Returns *False* if the given Topic already exists, otherwise *True*.
``edit``
If we edit an item, this should be *True*.
""" """
topics = self.manager.get_all_objects(Topic, topics = self.manager.get_all_objects(Topic,
Topic.name == new_topic.name) Topic.name == new_topic.name)
if len(topics) > 0: return self.__checkObject(topics, new_topic, edit)
# If we edit an existing Topic, we need to make sure that we do
# not return False when nothing has changed.
if edit:
for topic in topics:
if topic.id != new_topic.id:
return False
return True
else:
return False
else:
return True
def checkBook(self, new_book, edit=False): def checkBook(self, new_book, edit=False):
""" """
Returns *False* if the given Topic already exists, otherwise *True*. Returns *False* if the given Topic already exists, otherwise *True*.
``edit``
If we edit an item, this should be *True*.
""" """
books = self.manager.get_all_objects(Book, books = self.manager.get_all_objects(Book,
and_(Book.name == new_book.name, and_(Book.name == new_book.name,
Book.publisher == new_book.publisher)) Book.publisher == new_book.publisher))
if len(books) > 0: return self.__checkObject(books, new_book, edit)
# If we edit an existing Book, we need to make sure that we do
def __checkObject(self, objects, new_object, edit):
"""
Utility method to check for an existing object.
``edit``
If we edit an item, this should be *True*.
"""
if len(objects) > 0:
# If we edit an existing object, we need to make sure that we do
# not return False when nothing has changed. # not return False when nothing has changed.
if edit: if edit:
for book in books: for object in objects:
if book.id != new_book.id: if object.id != new_object.id:
return False return False
return True return True
else: else:
@ -237,11 +214,11 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
if self.manager.save_object(author): if self.manager.save_object(author):
self.resetAuthors() self.resetAuthors()
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not add your author.')) 'Could not add your author.'))
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'This author already exists.')) 'This author already exists.'))
@ -252,11 +229,11 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
if self.manager.save_object(topic): if self.manager.save_object(topic):
self.resetTopics() self.resetTopics()
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not add your topic.')) 'Could not add your topic.'))
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'This topic already exists.')) 'This topic already exists.'))
@ -268,17 +245,18 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
if self.manager.save_object(book): if self.manager.save_object(book):
self.resetBooks() self.resetBooks()
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not add your book.')) 'Could not add your book.'))
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'This book already exists.')) 'This book already exists.'))
def onAuthorEditButtonClick(self): def onAuthorEditButtonClick(self):
author_id = self._getCurrentItemId(self.authorsListWidget) author_id = self._getCurrentItemId(self.authorsListWidget)
if author_id != -1: if author_id == -1:
return
author = self.manager.get_object(Author, author_id) author = self.manager.get_object(Author, author_id)
self.authorform.setAutoDisplayName(False) self.authorform.setAutoDisplayName(False)
self.authorform.firstNameEdit.setText(author.first_name) self.authorform.firstNameEdit.setText(author.first_name)
@ -300,32 +278,32 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
self.resetAuthors() self.resetAuthors()
Receiver.send_message(u'songs_load_list') Receiver.send_message(u'songs_load_list')
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not save your changes.')) 'Could not save your changes.'))
elif criticalErrorMessageBox(message=unicode(translate( elif critical_error_message_box(message=unicode(translate(
'SongsPlugin.SongMaintenanceForm', 'The author %s already ' 'SongsPlugin.SongMaintenanceForm', 'The author %s already '
'exists. Would you like to make songs with author %s use ' 'exists. Would you like to make songs with author %s use '
'the existing author %s?')) % (author.display_name, 'the existing author %s?')) % (author.display_name,
temp_display_name, author.display_name), temp_display_name, author.display_name),
parent=self, question=True) == QtGui.QMessageBox.Yes: parent=self, question=True) == QtGui.QMessageBox.Yes:
self.mergeAuthors(author) self.__mergeObjects(author, self.mergeAuthors,
self.resetAuthors() self.resetAuthors)
Receiver.send_message(u'songs_load_list')
else: else:
# We restore the author's old first and last name as well as # We restore the author's old first and last name as well as
# his display name. # his display name.
author.first_name = temp_first_name author.first_name = temp_first_name
author.last_name = temp_last_name author.last_name = temp_last_name
author.display_name = temp_display_name author.display_name = temp_display_name
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not save your modified author, because the ' 'Could not save your modified author, because the '
'author already exists.')) 'author already exists.'))
def onTopicEditButtonClick(self): def onTopicEditButtonClick(self):
topic_id = self._getCurrentItemId(self.topicsListWidget) topic_id = self._getCurrentItemId(self.topicsListWidget)
if topic_id != -1: if topic_id == -1:
return
topic = self.manager.get_object(Topic, topic_id) topic = self.manager.get_object(Topic, topic_id)
self.topicform.nameEdit.setText(topic.name) self.topicform.nameEdit.setText(topic.name)
# Save the topic's name for the case that he has to be restored. # Save the topic's name for the case that he has to be restored.
@ -336,28 +314,28 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
if self.manager.save_object(topic): if self.manager.save_object(topic):
self.resetTopics() self.resetTopics()
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not save your changes.')) 'Could not save your changes.'))
elif criticalErrorMessageBox( elif critical_error_message_box(
message=unicode(translate('SongsPlugin.SongMaintenanceForm', message=unicode(translate('SongsPlugin.SongMaintenanceForm',
'The topic %s already exists. Would you like to make songs ' 'The topic %s already exists. Would you like to make songs '
'with topic %s use the existing topic %s?')) % (topic.name, 'with topic %s use the existing topic %s?')) % (topic.name,
temp_name, topic.name), temp_name, topic.name),
parent=self, question=True) == QtGui.QMessageBox.Yes: parent=self, question=True) == QtGui.QMessageBox.Yes:
self.mergeTopics(topic) self.__mergeObjects(topic, self.mergeTopics, self.resetTopics)
self.resetTopics()
else: else:
# We restore the topics's old name. # We restore the topics's old name.
topic.name = temp_name topic.name = temp_name
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not save your modified topic, because it ' 'Could not save your modified topic, because it '
'already exists.')) 'already exists.'))
def onBookEditButtonClick(self): def onBookEditButtonClick(self):
book_id = self._getCurrentItemId(self.booksListWidget) book_id = self._getCurrentItemId(self.booksListWidget)
if book_id != -1: if book_id == -1:
return
book = self.manager.get_object(Book, book_id) book = self.manager.get_object(Book, book_id)
if book.publisher is None: if book.publisher is None:
book.publisher = u'' book.publisher = u''
@ -374,22 +352,32 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
if self.manager.save_object(book): if self.manager.save_object(book):
self.resetBooks() self.resetBooks()
else: else:
criticalErrorMessageBox( critical_error_message_box(
message=translate('SongsPlugin.SongMaintenanceForm', message=translate('SongsPlugin.SongMaintenanceForm',
'Could not save your changes.')) 'Could not save your changes.'))
elif criticalErrorMessageBox( elif critical_error_message_box(
message=unicode(translate('SongsPlugin.SongMaintenanceForm', message=unicode(translate('SongsPlugin.SongMaintenanceForm',
'The book %s already exists. Would you like to make songs ' 'The book %s already exists. Would you like to make songs '
'with book %s use the existing book %s?')) % (book.name, 'with book %s use the existing book %s?')) % (book.name,
temp_name, book.name), temp_name, book.name),
parent=self, question=True) == QtGui.QMessageBox.Yes: parent=self, question=True) == QtGui.QMessageBox.Yes:
self.mergeBooks(book) self.__mergeObjects(book, self.mergeBooks, self.resetBooks)
self.resetBooks()
else: else:
# We restore the book's old name and publisher. # We restore the book's old name and publisher.
book.name = temp_name book.name = temp_name
book.publisher = temp_publisher book.publisher = temp_publisher
def __mergeObjects(self, dbObject, merge, reset):
"""
Utility method to merge two objects to leave one in the database.
"""
Receiver.send_message(u'cursor_busy')
Receiver.send_message(u'openlp_process_events')
merge(dbObject)
reset()
Receiver.send_message(u'songs_load_list')
Receiver.send_message(u'cursor_normal')
def mergeAuthors(self, old_author): def mergeAuthors(self, old_author):
""" """
Merges two authors into one author. Merges two authors into one author.
@ -496,42 +484,32 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
def onAuthorsListRowChanged(self, row): def onAuthorsListRowChanged(self, row):
""" """
Called when the *authorsListWidget* current's row has changed. Called when the *authorsListWidget*s current row has changed.
``row``
The current row. If there is no current row, the value is -1
""" """
if row == -1: self.__rowChange(row, self.authorsEditButton, self.authorsDeleteButton)
self.authorsDeleteButton.setEnabled(False)
self.authorsEditButton.setEnabled(False)
else:
self.authorsDeleteButton.setEnabled(True)
self.authorsEditButton.setEnabled(True)
def onTopicsListRowChanged(self, row): def onTopicsListRowChanged(self, row):
""" """
Called when the *booksListWidget* current's row has changed. Called when the *topicsListWidget*s current row has changed.
``row``
The current row. If there is no current row, the value is -1.
""" """
if row == -1: self.__rowChange(row, self.topicsEditButton, self.topicsDeleteButton)
self.topicsDeleteButton.setEnabled(False)
self.topicsEditButton.setEnabled(False)
else:
self.topicsDeleteButton.setEnabled(True)
self.topicsEditButton.setEnabled(True)
def onBooksListRowChanged(self, row): def onBooksListRowChanged(self, row):
""" """
Called when the *booksListWidget* current's row has changed. Called when the *booksListWidget*s current row has changed.
"""
self.__rowChange(row, self.booksEditButton, self.booksDeleteButton)
def __rowChange(self, row, editButton, deleteButton):
"""
Utility method to toggle if buttons are enabled.
``row`` ``row``
The current row. If there is no current row, the value is -1. The current row. If there is no current row, the value is -1.
""" """
if row == -1: if row == -1:
self.booksDeleteButton.setEnabled(False) deleteButton.setEnabled(False)
self.booksEditButton.setEnabled(False) editButton.setEnabled(False)
else: else:
self.booksDeleteButton.setEnabled(True) deleteButton.setEnabled(True)
self.booksEditButton.setEnabled(True) editButton.setEnabled(True)

View File

@ -27,6 +27,7 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.lib.ui import save_cancel_button_box
class Ui_TopicsDialog(object): class Ui_TopicsDialog(object):
def setupUi(self, topicsDialog): def setupUi(self, topicsDialog):
@ -43,17 +44,9 @@ class Ui_TopicsDialog(object):
self.nameLabel.setBuddy(self.nameEdit) self.nameLabel.setBuddy(self.nameEdit)
self.nameLayout.addRow(self.nameLabel, self.nameEdit) self.nameLayout.addRow(self.nameLabel, self.nameEdit)
self.dialogLayout.addLayout(self.nameLayout) self.dialogLayout.addLayout(self.nameLayout)
self.buttonBox = QtGui.QDialogButtonBox(topicsDialog) self.dialogLayout.addWidget(save_cancel_button_box(topicsDialog))
self.buttonBox.setStandardButtons(
QtGui.QDialogButtonBox.Save | QtGui.QDialogButtonBox.Cancel)
self.buttonBox.setObjectName(u'buttonBox')
self.dialogLayout.addWidget(self.buttonBox)
self.retranslateUi(topicsDialog) self.retranslateUi(topicsDialog)
topicsDialog.setMaximumHeight(topicsDialog.sizeHint().height()) topicsDialog.setMaximumHeight(topicsDialog.sizeHint().height())
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'accepted()'), topicsDialog.accept)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(u'rejected()'), topicsDialog.reject)
QtCore.QMetaObject.connectSlotsByName(topicsDialog) QtCore.QMetaObject.connectSlotsByName(topicsDialog)
def retranslateUi(self, topicsDialog): def retranslateUi(self, topicsDialog):

View File

@ -27,7 +27,7 @@
from PyQt4 import QtGui from PyQt4 import QtGui
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.ui import criticalErrorMessageBox from openlp.core.lib.ui import critical_error_message_box
from openlp.plugins.songs.forms.topicsdialog import Ui_TopicsDialog from openlp.plugins.songs.forms.topicsdialog import Ui_TopicsDialog
class TopicsForm(QtGui.QDialog, Ui_TopicsDialog): class TopicsForm(QtGui.QDialog, Ui_TopicsDialog):
@ -49,7 +49,8 @@ class TopicsForm(QtGui.QDialog, Ui_TopicsDialog):
def accept(self): def accept(self):
if not self.nameEdit.text(): if not self.nameEdit.text():
criticalErrorMessageBox(message=translate('SongsPlugin.TopicsForm', critical_error_message_box(
message=translate('SongsPlugin.TopicsForm',
'You need to type in a topic name.')) 'You need to type in a topic name.'))
self.nameEdit.setFocus() self.nameEdit.setFocus()
return False return False

View File

@ -133,29 +133,37 @@ class EasiSlidesImport(SongImport):
pass pass
def _add_copyright(self, song): def _add_copyright(self, song):
copyright = [] """
Assign the copyright information from the import to the song being
created.
``song``
The current song being imported.
"""
copyright_list = []
self.__add_copyright_element(copyright_list, song.Copyright)
self.__add_copyright_element(copyright_list, song.LicenceAdmin1)
self.__add_copyright_element(copyright_list, song.LicenceAdmin2)
self.add_copyright(u' '.join(copyright_list))
def __add_copyright_element(self, copyright_list, element):
"""
Add a piece of copyright to the total copyright information for the
song.
``copyright_list``
The array to add the information to.
``element``
The imported variable to get the data from.
"""
try: try:
copyright.append(unicode(song.Copyright).strip()) copyright_list.append(unicode(element).strip())
except UnicodeDecodeError: except UnicodeDecodeError:
log.exception(u'Unicode decode error while decoding Copyright') log.exception(u'Unicode error decoding %s' % element)
self._success = False self._success = False
except AttributeError: except AttributeError:
pass pass
try:
copyright.append(unicode(song.LicenceAdmin1).strip())
except UnicodeDecodeError:
log.exception(u'Unicode decode error while decoding LicenceAdmin1')
self._success = False
except AttributeError:
pass
try:
copyright.append(unicode(song.LicenceAdmin2).strip())
except UnicodeDecodeError:
log.exception(u'Unicode decode error while decoding LicenceAdmin2')
self._success = False
except AttributeError:
pass
self.add_copyright(u' '.join(copyright))
def _parse_and_add_lyrics(self, song): def _parse_and_add_lyrics(self, song):
try: try:
@ -314,11 +322,11 @@ class EasiSlidesImport(SongImport):
pass pass
def _listHas(self, lst, subitems): def _listHas(self, lst, subitems):
for i in subitems: for subitem in subitems:
if type(lst) == type({}) and lst.has_key(i): if isinstance(lst, dict) and lst.has_key(subitem):
lst = lst[i] lst = lst[subitem]
elif type(lst) == type([]) and i in lst: elif isinstance(lst, list) and subitem in lst:
lst = lst[i] lst = lst[subitem]
else: else:
return False return False
return True return True

View File

@ -105,7 +105,7 @@ class SongFormat(object):
return None return None
@staticmethod @staticmethod
def list(): def get_formats_list():
""" """
Return a list of the supported song formats. Return a list of the supported song formats.
""" """

View File

@ -68,9 +68,6 @@ class SongMediaItem(MediaManagerItem):
self.editItem = None self.editItem = None
self.whitespace = re.compile(r'\W+', re.UNICODE) self.whitespace = re.compile(r'\W+', re.UNICODE)
def requiredIcons(self):
MediaManagerItem.requiredIcons(self)
def addEndHeaderBar(self): def addEndHeaderBar(self):
self.addToolbarSeparator() self.addToolbarSeparator()
## Song Maintenance Button ## ## Song Maintenance Button ##
@ -98,8 +95,6 @@ class SongMediaItem(MediaManagerItem):
self.searchLayout.addLayout(self.searchButtonLayout) self.searchLayout.addLayout(self.searchButtonLayout)
self.pageLayout.addWidget(self.searchWidget) self.pageLayout.addWidget(self.searchWidget)
# Signals and slots # Signals and slots
QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'plugin_list_refresh'), self.onSearchTextButtonClick)
QtCore.QObject.connect(self.searchTextEdit, QtCore.QObject.connect(self.searchTextEdit,
QtCore.SIGNAL(u'returnPressed()'), self.onSearchTextButtonClick) QtCore.SIGNAL(u'returnPressed()'), self.onSearchTextButtonClick)
QtCore.QObject.connect(self.searchTextButton, QtCore.QObject.connect(self.searchTextButton,
@ -340,16 +335,7 @@ class SongMediaItem(MediaManagerItem):
author_list = u'' author_list = u''
author_audit = [] author_audit = []
ccli = u'' ccli = u''
if item is None: item_id = self._getIdOfItemToGenerate(item, self.remoteSong)
if self.remoteTriggered is None:
item = self.listView.currentItem()
if item is None:
return False
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
else:
item_id = self.remoteSong
else:
item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0]
service_item.add_capability(ItemCapabilities.AllowsEdit) service_item.add_capability(ItemCapabilities.AllowsEdit)
service_item.add_capability(ItemCapabilities.AllowsPreview) service_item.add_capability(ItemCapabilities.AllowsPreview)
service_item.add_capability(ItemCapabilities.AllowsLoop) service_item.add_capability(ItemCapabilities.AllowsLoop)
@ -445,6 +431,7 @@ class SongMediaItem(MediaManagerItem):
if add_song: if add_song:
if self.addSongFromService: if self.addSongFromService:
editId = self.openLyrics.xml_to_song(item.xml_version) editId = self.openLyrics.xml_to_song(item.xml_version)
self.onSearchTextButtonClick()
# Update service with correct song id. # Update service with correct song id.
if editId: if editId:
Receiver.send_message(u'service_item_update', Receiver.send_message(u'service_item_update',

View File

@ -66,31 +66,34 @@ class OooImport(SongImport):
QtCore.SIGNAL(u'openlp_stop_wizard'), self.stop_import) QtCore.SIGNAL(u'openlp_stop_wizard'), self.stop_import)
def do_import(self): def do_import(self):
self.abort = False self.stop_import_flag = False
self.import_wizard.progressBar.setMaximum(0) self.import_wizard.progressBar.setMaximum(0)
self.start_ooo() self.start_ooo()
for filename in self.filenames: for filename in self.filenames:
if self.abort: if self.stop_import_flag:
self.import_wizard.incrementProgressBar(u'Import cancelled', 0) self.import_wizard.incrementProgressBar(u'Import cancelled', 0)
return return
filename = unicode(filename) filename = unicode(filename)
if os.path.isfile(filename): if os.path.isfile(filename):
self.open_ooo_file(filename) self.open_ooo_file(filename)
if self.document: if self.document:
if self.document.supportsService( self.process_ooo_document()
"com.sun.star.presentation.PresentationDocument"):
self.process_pres()
if self.document.supportsService(
"com.sun.star.text.TextDocument"):
self.process_doc()
self.close_ooo_file() self.close_ooo_file()
self.close_ooo() self.close_ooo()
self.import_wizard.progressBar.setMaximum(1) self.import_wizard.progressBar.setMaximum(1)
self.import_wizard.incrementProgressBar(u'', 1) self.import_wizard.incrementProgressBar(u'', 1)
return True return True
def stop_import(self): def process_ooo_document(self):
self.abort = True """
Handle the import process for OpenOffice files. This method facilitates
allowing subclasses to handle specific types of OpenOffice files.
"""
if self.document.supportsService(
"com.sun.star.presentation.PresentationDocument"):
self.process_pres()
if self.document.supportsService("com.sun.star.text.TextDocument"):
self.process_doc()
def start_ooo(self): def start_ooo(self):
""" """
@ -180,7 +183,7 @@ class OooImport(SongImport):
slides = doc.getDrawPages() slides = doc.getDrawPages()
text = u'' text = u''
for slide_no in range(slides.getCount()): for slide_no in range(slides.getCount()):
if self.abort: if self.stop_import_flag:
self.import_wizard.incrementProgressBar(u'Import cancelled', 0) self.import_wizard.incrementProgressBar(u'Import cancelled', 0)
return return
slide = slides.getByIndex(slide_no) slide = slides.getByIndex(slide_no)

View File

@ -39,9 +39,7 @@ from oooimport import OooImport
if os.name == u'nt': if os.name == u'nt':
BOLD = 150.0 BOLD = 150.0
ITALIC = 2 ITALIC = 2
PAGE_BEFORE = 4 from oooimport import PAGE_BEFORE, PAGE_AFTER, PAGE_BOTH
PAGE_AFTER = 5
PAGE_BOTH = 6
else: else:
try: try:
from com.sun.star.awt.FontWeight import BOLD from com.sun.star.awt.FontWeight import BOLD
@ -75,23 +73,11 @@ class SofImport(OooImport):
""" """
OooImport.__init__(self, master_manager, **kwargs) OooImport.__init__(self, master_manager, **kwargs)
def do_import(self): def process_ooo_document(self):
self.abort = False """
self.start_ooo() Handle the import process for SoF files.
for filename in self.filenames: """
if self.abort:
self.import_wizard.incrementProgressBar(u'Import cancelled', 0)
return
filename = unicode(filename)
if os.path.isfile(filename):
self.open_ooo_file(filename)
if self.document:
self.process_sof_file() self.process_sof_file()
self.close_ooo_file()
self.close_ooo()
self.import_wizard.progressBar.setMaximum(1)
self.import_wizard.incrementProgressBar(u'', 1)
return True
def process_sof_file(self): def process_sof_file(self):
""" """
@ -101,7 +87,7 @@ class SofImport(OooImport):
self.new_song() self.new_song()
paragraphs = self.document.getText().createEnumeration() paragraphs = self.document.getText().createEnumeration()
while paragraphs.hasMoreElements(): while paragraphs.hasMoreElements():
if self.abort: if self.stop_import_flag:
self.import_wizard.incrementProgressBar(u'Import cancelled', 0) self.import_wizard.incrementProgressBar(u'Import cancelled', 0)
return return
paragraph = paragraphs.nextElement() paragraph = paragraphs.nextElement()
@ -318,7 +304,6 @@ class SofImport(OooImport):
self.currentverse = u'' self.currentverse = u''
self.is_chorus = False self.is_chorus = False
def uncap_text(self, text): def uncap_text(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.

View File

@ -227,7 +227,7 @@ class SongImport(QtCore.QObject):
self.versecounts[versetag[0]] = int(versetag[1:]) self.versecounts[versetag[0]] = int(versetag[1:])
self.verses.append([versetag, versetext.rstrip(), lang]) self.verses.append([versetag, versetext.rstrip(), lang])
self.verse_order_list.append(versetag) self.verse_order_list.append(versetag)
if versetag.startswith(u'V') and self.contains_verse(u'C1'): if versetag.startswith(u'V') and u'C1' in self.verse_order_list:
self.verse_order_list.append(u'C1') self.verse_order_list.append(u'C1')
def repeat_verse(self): def repeat_verse(self):
@ -236,9 +236,6 @@ class SongImport(QtCore.QObject):
""" """
self.verse_order_list.append(self.verse_order_list[-1]) self.verse_order_list.append(self.verse_order_list[-1])
def contains_verse(self, versetag):
return versetag in self.verse_order_list
def check_complete(self): def check_complete(self):
""" """
Check the mandatory fields are entered (i.e. title and a verse) Check the mandatory fields are entered (i.e. title and a verse)

View File

@ -26,7 +26,7 @@
from PyQt4 import QtGui from PyQt4 import QtGui
from openlp.core.lib import translate from openlp.core.lib import translate, Receiver
from openlp.plugins.songusage.lib.db import SongUsageItem from openlp.plugins.songusage.lib.db import SongUsageItem
from songusagedeletedialog import Ui_SongUsageDeleteDialog from songusagedeletedialog import Ui_SongUsageDeleteDialog
@ -55,4 +55,9 @@ class SongUsageDeleteForm(QtGui.QDialog, Ui_SongUsageDeleteDialog):
deleteDate = self.deleteCalendar.selectedDate().toPyDate() deleteDate = self.deleteCalendar.selectedDate().toPyDate()
self.manager.delete_all_objects(SongUsageItem, self.manager.delete_all_objects(SongUsageItem,
SongUsageItem.usagedate <= deleteDate) SongUsageItem.usagedate <= deleteDate)
Receiver.send_message(u'openlp_information_message', {
u'title': translate('SongUsagePlugin.SongUsageDeleteForm',
'Deletion Successful'),
u'message': translate('SongUsagePlugin.SongUsageDeleteForm',
'All requested data has been deleted successfully. ')})
self.close() self.close()

View File

@ -60,10 +60,12 @@ class Ui_SongUsageDetailDialog(object):
self.horizontalLayout.setObjectName(u'horizontalLayout') self.horizontalLayout.setObjectName(u'horizontalLayout')
self.fileLineEdit = QtGui.QLineEdit(self.fileGroupBox) self.fileLineEdit = QtGui.QLineEdit(self.fileGroupBox)
self.fileLineEdit.setObjectName(u'fileLineEdit') self.fileLineEdit.setObjectName(u'fileLineEdit')
self.fileLineEdit.setReadOnly(True)
self.fileLineEdit.setEnabled(False)
self.horizontalLayout.addWidget(self.fileLineEdit) self.horizontalLayout.addWidget(self.fileLineEdit)
self.saveFilePushButton = QtGui.QPushButton(self.fileGroupBox) self.saveFilePushButton = QtGui.QPushButton(self.fileGroupBox)
self.saveFilePushButton.setIcon( self.saveFilePushButton.setIcon(
build_icon(u':/general/general_load.png')) build_icon(u':/general/general_open.png'))
self.saveFilePushButton.setObjectName(u'saveFilePushButton') self.saveFilePushButton.setObjectName(u'saveFilePushButton')
self.horizontalLayout.addWidget(self.saveFilePushButton) self.horizontalLayout.addWidget(self.saveFilePushButton)
self.verticalLayout4.addLayout(self.horizontalLayout) self.verticalLayout4.addLayout(self.horizontalLayout)

View File

@ -30,7 +30,8 @@ import os
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from sqlalchemy.sql import and_ from sqlalchemy.sql import and_
from openlp.core.lib import SettingsManager, translate from openlp.core.lib import SettingsManager, translate, Receiver, \
check_directory_exists
from openlp.plugins.songusage.lib.db import SongUsageItem from openlp.plugins.songusage.lib.db import SongUsageItem
from songusagedetaildialog import Ui_SongUsageDetailDialog from songusagedetaildialog import Ui_SongUsageDetailDialog
@ -51,49 +52,74 @@ class SongUsageDetailForm(QtGui.QDialog, Ui_SongUsageDetailDialog):
self.setupUi(self) self.setupUi(self)
def initialise(self): def initialise(self):
"""
We need to set up the screen
"""
year = QtCore.QDate().currentDate().year() year = QtCore.QDate().currentDate().year()
if QtCore.QDate().currentDate().month() < 9: if QtCore.QDate().currentDate().month() < 9:
year -= 1 year -= 1
toDate = QtCore.QDate(year, 8, 31) toDate = QtCore.QSettings().value(
fromDate = QtCore.QDate(year - 1, 9, 1) u'songusage/to date',
QtCore.QVariant(QtCore.QDate(year, 8, 31))).toDate()
fromDate = QtCore.QSettings().value(
u'songusage/from date',
QtCore.QVariant(QtCore.QDate(year - 1, 9, 1))).toDate()
self.fromDate.setSelectedDate(fromDate) self.fromDate.setSelectedDate(fromDate)
self.toDate.setSelectedDate(toDate) self.toDate.setSelectedDate(toDate)
self.fileLineEdit.setText( self.fileLineEdit.setText(
SettingsManager.get_last_dir(self.plugin.settingsSection, 1)) SettingsManager.get_last_dir(self.plugin.settingsSection, 1))
def defineOutputLocation(self): def defineOutputLocation(self):
"""
Triggered when the Directory selection button is pressed
"""
path = QtGui.QFileDialog.getExistingDirectory(self, path = QtGui.QFileDialog.getExistingDirectory(self,
translate('SongUsagePlugin.SongUsageDetailForm', translate('SongUsagePlugin.SongUsageDetailForm',
'Output File Location'), 'Output File Location'),
SettingsManager.get_last_dir(self.plugin.settingsSection, 1)) SettingsManager.get_last_dir(self.plugin.settingsSection, 1))
path = unicode(path) path = unicode(path)
if path != u'': if path:
SettingsManager.set_last_dir(self.plugin.settingsSection, path, 1) SettingsManager.set_last_dir(self.plugin.settingsSection, path, 1)
self.fileLineEdit.setText(path) self.fileLineEdit.setText(path)
def accept(self): def accept(self):
log.debug(u'Detailed report generated') """
Ok was pressed so lets save the data and run the report
"""
log.debug(u'accept')
path = unicode(self.fileLineEdit.text())
check_directory_exists(path)
filename = unicode(translate('SongUsagePlugin.SongUsageDetailForm', filename = unicode(translate('SongUsagePlugin.SongUsageDetailForm',
'usage_detail_%s_%s.txt')) % ( 'usage_detail_%s_%s.txt')) % (
self.fromDate.selectedDate().toString(u'ddMMyyyy'), self.fromDate.selectedDate().toString(u'ddMMyyyy'),
self.toDate.selectedDate().toString(u'ddMMyyyy')) self.toDate.selectedDate().toString(u'ddMMyyyy'))
QtCore.QSettings().setValue(u'songusage/from date',
QtCore.QVariant(self.fromDate.selectedDate()))
QtCore.QSettings().setValue(u'songusage/to date',
QtCore.QVariant(self.toDate.selectedDate()))
usage = self.plugin.manager.get_all_objects( usage = self.plugin.manager.get_all_objects(
SongUsageItem, and_( SongUsageItem, and_(
SongUsageItem.usagedate >= self.fromDate.selectedDate().toPyDate(), SongUsageItem.usagedate >= self.fromDate.selectedDate().toPyDate(),
SongUsageItem.usagedate < self.toDate.selectedDate().toPyDate()), SongUsageItem.usagedate < self.toDate.selectedDate().toPyDate()),
[SongUsageItem.usagedate, SongUsageItem.usagetime]) [SongUsageItem.usagedate, SongUsageItem.usagetime])
outname = os.path.join(unicode(self.fileLineEdit.text()), filename) outname = os.path.join(path, filename)
file = None fileHandle = None
try: try:
file = open(outname, u'w') fileHandle = open(outname, u'w')
for instance in usage: for instance in usage:
record = u'\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n' % ( record = u'\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n' % (
instance.usagedate, instance.usagetime, instance.title, instance.usagedate, instance.usagetime, instance.title,
instance.copyright, instance.ccl_number, instance.authors) instance.copyright, instance.ccl_number, instance.authors)
file.write(record) fileHandle.write(record.encode(u'utf-8'))
Receiver.send_message(u'openlp_information_message', {
u'title': translate('SongUsagePlugin.SongUsageDetailForm',
'Report Creation'),
u'message': unicode(translate(
'SongUsagePlugin.SongUsageDetailForm', 'Report \n%s \n'
'has been successfully created. ')) % outname})
except IOError: except IOError:
log.exception(u'Failed to write out song usage records') log.exception(u'Failed to write out song usage records')
finally: finally:
if file: if fileHandle:
file.close() fileHandle.close()
self.close() self.close()