openlp/openlp/core/ui/thememanager.py

883 lines
39 KiB
Python
Raw Normal View History

2009-09-13 15:14:45 +00:00
# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
2011-12-27 10:33:55 +00:00
# Copyright (c) 2008-2012 Raoul Snyman #
# Portions copyright (c) 2008-2012 Tim Bentley, Gerald Britton, Jonathan #
2011-05-26 16:25:54 +00:00
# Corwin, Michael Gorven, Scott Guerrieri, Matthias Hub, Meinert Jordan, #
2011-05-26 17:11:22 +00:00
# Armin Köhler, Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias #
2011-06-12 16:02:52 +00:00
# Põldaru, Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
2011-06-12 15:41:01 +00:00
# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Frode Woldsund #
2009-09-13 15:14:45 +00:00
# --------------------------------------------------------------------------- #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as published by the Free #
# Software Foundation; version 2 of the License. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
import os
import zipfile
import shutil
import logging
2011-05-23 20:42:07 +00:00
import locale
import re
2009-09-13 15:14:45 +00:00
from xml.etree.ElementTree import ElementTree, XML
from PyQt4 import QtCore, QtGui
2011-02-18 03:15:09 +00:00
from openlp.core.lib import OpenLPToolbar, get_text_file_string, build_icon, \
Receiver, SettingsManager, translate, check_item_selected, \
2011-06-12 15:17:01 +00:00
check_directory_exists, create_thumb, validate_thumb
2011-02-18 03:15:09 +00:00
from openlp.core.lib.theme import ThemeXML, BackgroundType, VerticalType, \
BackgroundGradientType
from openlp.core.lib.settings import Settings
2011-06-29 09:23:42 +00:00
from openlp.core.lib.ui import UiStrings, critical_error_message_box, \
create_widget_action
from openlp.core.theme import Theme
from openlp.core.ui import FileRenameForm, ThemeForm
from openlp.core.utils import AppLocation, delete_file, get_filesystem_encoding
2009-09-13 15:14:45 +00:00
2010-02-27 15:31:23 +00:00
log = logging.getLogger(__name__)
2009-09-13 15:14:45 +00:00
class ThemeManager(QtGui.QWidget):
"""
Manages the orders of Theme.
"""
def __init__(self, mainwindow, parent=None):
2009-09-13 15:14:45 +00:00
QtGui.QWidget.__init__(self, parent)
self.mainwindow = mainwindow
self.settingsSection = u'themes'
self.themeForm = ThemeForm(self)
self.fileRenameForm = FileRenameForm(self)
# start with the layout
self.layout = QtGui.QVBoxLayout(self)
self.layout.setSpacing(0)
self.layout.setMargin(0)
self.layout.setObjectName(u'layout')
self.toolbar = OpenLPToolbar(self)
self.toolbar.setObjectName(u'toolbar')
self.toolbar.addToolbarAction(u'newTheme',
text=UiStrings().NewTheme, icon=u':/themes/theme_new.png',
tooltip=translate('OpenLP.ThemeManager', 'Create a new theme.'),
triggers=self.onAddTheme)
self.toolbar.addToolbarAction(u'editTheme',
text=translate('OpenLP.ThemeManager', 'Edit Theme'),
icon=u':/themes/theme_edit.png',
tooltip=translate('OpenLP.ThemeManager', 'Edit a theme.'),
triggers=self.onEditTheme)
self.deleteToolbarAction = self.toolbar.addToolbarAction(u'deleteTheme',
text=translate('OpenLP.ThemeManager', 'Delete Theme'),
icon=u':/general/general_delete.png',
tooltip=translate('OpenLP.ThemeManager', 'Delete a theme.'),
triggers=self.onDeleteTheme)
self.toolbar.addSeparator()
self.toolbar.addToolbarAction(u'importTheme',
text=translate('OpenLP.ThemeManager', 'Import Theme'),
icon=u':/general/general_import.png',
tooltip=translate('OpenLP.ThemeManager', 'Import a theme.'),
triggers=self.onImportTheme)
self.toolbar.addToolbarAction(u'exportTheme',
text=translate('OpenLP.ThemeManager', 'Export Theme'),
icon=u':/general/general_export.png',
tooltip=translate('OpenLP.ThemeManager', 'Export a theme.'),
triggers=self.onExportTheme)
self.layout.addWidget(self.toolbar)
self.themeWidget = QtGui.QWidgetAction(self.toolbar)
self.themeWidget.setObjectName(u'themeWidget')
# create theme manager list
self.themeListWidget = QtGui.QListWidget(self)
self.themeListWidget.setAlternatingRowColors(True)
self.themeListWidget.setIconSize(QtCore.QSize(88, 50))
self.themeListWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.themeListWidget.setObjectName(u'themeListWidget')
self.layout.addWidget(self.themeListWidget)
QtCore.QObject.connect(self.themeListWidget,
QtCore.SIGNAL('customContextMenuRequested(QPoint)'),
self.contextMenu)
# build the context menu
self.menu = QtGui.QMenu()
self.editAction = create_widget_action(self.menu,
text=translate('OpenLP.ThemeManager', '&Edit Theme'),
icon=u':/themes/theme_edit.png', triggers=self.onEditTheme)
self.copyAction = create_widget_action(self.menu,
text=translate('OpenLP.ThemeManager', '&Copy Theme'),
icon=u':/themes/theme_edit.png', triggers=self.onCopyTheme)
self.renameAction = create_widget_action(self.menu,
text=translate('OpenLP.ThemeManager', '&Rename Theme'),
icon=u':/themes/theme_edit.png', triggers=self.onRenameTheme)
self.deleteAction = create_widget_action(self.menu,
text=translate('OpenLP.ThemeManager', '&Delete Theme'),
icon=u':/general/general_delete.png', triggers=self.onDeleteTheme)
self.menu.addSeparator()
self.globalAction = create_widget_action(self.menu,
text=translate('OpenLP.ThemeManager', 'Set As &Global Default'),
icon=u':/general/general_export.png',
triggers=self.changeGlobalFromScreen)
self.exportAction = create_widget_action(self.menu,
text=translate('OpenLP.ThemeManager', '&Export Theme'),
icon=u':/general/general_export.png', triggers=self.onExportTheme)
2010-12-27 10:18:09 +00:00
# Signals
QtCore.QObject.connect(self.themeListWidget,
2009-09-13 15:14:45 +00:00
QtCore.SIGNAL(u'doubleClicked(QModelIndex)'),
self.changeGlobalFromScreen)
QtCore.QObject.connect(self.themeListWidget, QtCore.SIGNAL(
u'currentItemChanged(QListWidgetItem *, QListWidgetItem *)'),
self.checkListState)
2009-09-13 15:14:45 +00:00
QtCore.QObject.connect(Receiver.get_receiver(),
2010-04-16 07:31:01 +00:00
QtCore.SIGNAL(u'theme_update_global'), self.changeGlobalFromTab)
2010-12-27 10:18:09 +00:00
QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'config_updated'), self.configUpdated)
# Variables
#FIXME: convert to camelCase.
self.theme_list = []
self.path = AppLocation.get_section_data_path(self.settingsSection)
2011-01-09 08:17:17 +00:00
check_directory_exists(self.path)
#FIXME: convert to camelCase.
self.thumb_path = os.path.join(self.path, u'thumbnails')
check_directory_exists(self.thumb_path)
2010-10-17 18:58:42 +00:00
self.themeForm.path = self.path
#FIXME: convert to camelCase.
self.old_background_image = None
#FIXME: convert to camelCase.
self.bad_v1_name_chars = re.compile(r'[%+\[\]]')
2009-09-13 15:14:45 +00:00
# Last little bits of setting up
2010-12-27 10:18:09 +00:00
self.configUpdated()
2011-03-05 09:23:47 +00:00
def firstTime(self):
"""
Import new themes downloaded by the first time wizard
"""
Receiver.send_message(u'cursor_busy')
files = SettingsManager.get_files(self.settingsSection, u'.otz')
for file in files:
file = os.path.join(self.path, file)
2011-03-05 09:23:47 +00:00
self.unzipTheme(file, self.path)
delete_file(file)
Receiver.send_message(u'cursor_normal')
def configUpdated(self):
2010-12-27 10:18:09 +00:00
"""
Triggered when Config dialog is updated.
"""
self.global_theme = unicode(Settings().value(
self.settingsSection + u'/global theme',
2010-04-28 14:17:42 +00:00
QtCore.QVariant(u'')).toString())
2009-09-13 15:14:45 +00:00
def checkListState(self, item):
"""
If Default theme selected remove delete button.
"""
if item is None:
return
real_theme_name = unicode(item.data(QtCore.Qt.UserRole).toString())
2012-03-10 08:22:52 +00:00
theme_name = unicode(item.text())
2011-01-11 17:44:13 +00:00
# If default theme restrict actions
if real_theme_name == theme_name:
self.deleteToolbarAction.setVisible(True)
else:
self.deleteToolbarAction.setVisible(False)
def contextMenu(self, point):
2010-12-28 10:56:19 +00:00
"""
Build the Right Click Context menu and set state depending on
the type of theme.
"""
item = self.themeListWidget.itemAt(point)
if item is None:
return
real_theme_name = unicode(item.data(QtCore.Qt.UserRole).toString())
2012-03-10 08:22:52 +00:00
theme_name = unicode(item.text())
2012-06-23 17:21:27 +00:00
# FIXME: Shorten code.
# visible = real_theme_name == theme_name:
# self.deleteAction.setVisible(visible)
# self.renameAction.setVisible(visible)
# self.globalAction.setVisible(visible)
self.deleteAction.setVisible(False)
self.renameAction.setVisible(False)
2010-09-26 08:38:11 +00:00
self.globalAction.setVisible(False)
# If default theme restrict actions
if real_theme_name == theme_name:
self.deleteAction.setVisible(True)
self.renameAction.setVisible(True)
2010-09-26 08:38:11 +00:00
self.globalAction.setVisible(True)
2011-06-29 09:23:42 +00:00
self.menu.exec_(self.themeListWidget.mapToGlobal(point))
2012-03-10 08:22:52 +00:00
def changeGlobalFromTab(self, theme_name):
2010-06-10 01:57:59 +00:00
"""
Change the global theme when it is changed through the Themes settings
tab
"""
2012-03-10 08:22:52 +00:00
log.debug(u'changeGlobalFromTab %s', theme_name)
for count in range (0, self.themeListWidget.count()):
2010-08-28 15:49:51 +00:00
# reset the old name
item = self.themeListWidget.item(count)
old_name = item.text()
new_name = unicode(item.data(QtCore.Qt.UserRole).toString())
if old_name != new_name:
self.themeListWidget.item(count).setText(new_name)
2010-08-28 15:49:51 +00:00
# Set the new name
if theme_name == new_name:
name = unicode(translate('OpenLP.ThemeManager',
'%s (default)')) % new_name
self.themeListWidget.item(count).setText(name)
self.deleteToolbarAction.setVisible(
item not in self.themeListWidget.selectedItems())
2009-09-13 15:14:45 +00:00
def changeGlobalFromScreen(self, index=-1):
2010-06-10 01:57:59 +00:00
"""
Change the global theme when a theme is double clicked upon in the
Theme Manager list
"""
2009-09-13 15:14:45 +00:00
log.debug(u'changeGlobalFromScreen %s', index)
selected_row = self.themeListWidget.currentRow()
for count in range (0, self.themeListWidget.count()):
item = self.themeListWidget.item(count)
old_name = item.text()
2010-08-28 15:49:51 +00:00
# reset the old name
if old_name != unicode(item.data(QtCore.Qt.UserRole).toString()):
self.themeListWidget.item(count).setText(
2009-09-13 15:14:45 +00:00
unicode(item.data(QtCore.Qt.UserRole).toString()))
2010-08-28 15:49:51 +00:00
# Set the new name
2009-10-10 18:36:58 +00:00
if count == selected_row:
2009-09-13 15:14:45 +00:00
self.global_theme = unicode(
self.themeListWidget.item(count).text())
name = unicode(translate('OpenLP.ThemeManager',
'%s (default)')) % self.global_theme
self.themeListWidget.item(count).setText(name)
Settings().setValue(
self.settingsSection + u'/global theme',
2010-04-28 01:28:37 +00:00
QtCore.QVariant(self.global_theme))
2012-05-20 19:11:27 +00:00
Receiver.send_message(u'theme_update_global', self.global_theme)
self._pushThemes()
2009-09-13 15:14:45 +00:00
def onAddTheme(self):
2010-06-10 01:57:59 +00:00
"""
Loads a new theme with the default settings and then launches the theme
editing form for the user to make their customisations.
"""
2010-10-17 18:58:42 +00:00
theme = ThemeXML()
theme.set_default_header_footer()
2010-10-17 18:58:42 +00:00
self.themeForm.theme = theme
self.themeForm.exec_()
2009-09-13 15:14:45 +00:00
2010-09-26 06:20:24 +00:00
def onRenameTheme(self):
"""
Renames an existing theme to a new name
"""
if self._validate_theme_action(unicode(translate('OpenLP.ThemeManager',
'You must select a theme to rename.')),
unicode(translate('OpenLP.ThemeManager', 'Rename Confirmation')),
unicode(translate('OpenLP.ThemeManager', 'Rename %s theme?')),
2011-02-05 17:31:13 +00:00
False, False):
item = self.themeListWidget.currentItem()
old_theme_name = unicode(item.data(QtCore.Qt.UserRole).toString())
self.fileRenameForm.fileNameEdit.setText(old_theme_name)
if self.fileRenameForm.exec_():
new_theme_name = unicode(self.fileRenameForm.fileNameEdit.text())
if old_theme_name == new_theme_name:
return
if self.checkIfThemeExists(new_theme_name):
old_theme_data = self.getThemeData(old_theme_name)
self.cloneThemeData(old_theme_data, new_theme_name)
self.deleteTheme(old_theme_name)
2011-01-09 23:24:55 +00:00
for plugin in self.mainwindow.pluginManager.plugins:
if plugin.usesTheme(old_theme_name):
plugin.renameTheme(old_theme_name, new_theme_name)
self.loadThemes()
2012-05-23 16:14:03 +00:00
self.mainwindow.renderer.update_theme(
new_theme_name, old_theme_name)
2010-09-26 06:20:24 +00:00
def onCopyTheme(self):
"""
Copies an existing theme to a new name
"""
item = self.themeListWidget.currentItem()
old_theme_name = unicode(item.data(QtCore.Qt.UserRole).toString())
2011-06-29 09:08:53 +00:00
self.fileRenameForm.fileNameEdit.setText(
unicode(translate('OpenLP.ThemeManager',
2012-03-10 16:44:58 +00:00
'Copy of %s', 'Copy of <theme name>')) % old_theme_name)
2010-12-24 08:07:26 +00:00
if self.fileRenameForm.exec_(True):
new_theme_name = unicode(self.fileRenameForm.fileNameEdit.text())
if self.checkIfThemeExists(new_theme_name):
theme_data = self.getThemeData(old_theme_name)
self.cloneThemeData(theme_data, new_theme_name)
2010-09-26 07:39:50 +00:00
def cloneThemeData(self, theme_data, new_theme_name):
2010-09-26 07:39:50 +00:00
"""
2010-10-03 07:42:02 +00:00
Takes a theme and makes a new copy of it as well as saving it.
2010-09-26 07:39:50 +00:00
"""
log.debug(u'cloneThemeData')
save_to = None
save_from = None
if theme_data.background_type == u'image':
save_to = os.path.join(self.path, new_theme_name,
os.path.split(unicode(theme_data.background_filename))[1])
save_from = theme_data.background_filename
theme_data.theme_name = new_theme_name
theme_data.extend_image_filename(self.path)
self.saveTheme(theme_data, save_from, save_to)
2010-09-26 06:20:24 +00:00
2009-09-13 15:14:45 +00:00
def onEditTheme(self):
2010-06-10 01:57:59 +00:00
"""
Loads the settings for the theme that is to be edited and launches the
theme editing form so the user can make their changes.
"""
2012-05-23 16:14:03 +00:00
if check_item_selected(self.themeListWidget, translate(
'OpenLP.ThemeManager', 'You must select a theme to edit.')):
item = self.themeListWidget.currentItem()
theme = self.getThemeData(
2009-09-13 15:14:45 +00:00
unicode(item.data(QtCore.Qt.UserRole).toString()))
2010-07-12 22:32:46 +00:00
if theme.background_type == u'image':
self.old_background_image = theme.background_filename
2010-10-17 18:58:42 +00:00
self.themeForm.theme = theme
self.themeForm.exec_(True)
2012-06-23 17:21:27 +00:00
self.mainwindow.imageManager.deleteImage(theme.theme_name)
self.old_background_image = None
2012-05-23 16:14:03 +00:00
self.mainwindow.renderer.update_theme(theme.theme_name)
2009-09-13 15:14:45 +00:00
2010-09-26 08:38:11 +00:00
def onDeleteTheme(self):
2010-06-10 01:57:59 +00:00
"""
Delete a theme
"""
if self._validate_theme_action(unicode(translate('OpenLP.ThemeManager',
'You must select a theme to delete.')),
unicode(translate('OpenLP.ThemeManager', 'Delete Confirmation')),
unicode(translate('OpenLP.ThemeManager', 'Delete %s theme?'))):
item = self.themeListWidget.currentItem()
2009-09-13 15:14:45 +00:00
theme = unicode(item.text())
row = self.themeListWidget.row(item)
self.themeListWidget.takeItem(row)
self.deleteTheme(theme)
2011-02-05 20:10:08 +00:00
# As we do not reload the themes, push out the change. Reload the
# list as the internal lists and events need to be triggered.
self._pushThemes()
2012-05-23 21:02:34 +00:00
self.mainwindow.renderer.update_theme(theme, only_delete=True)
def deleteTheme(self, theme):
"""
Delete a theme.
``theme``
The theme to delete.
"""
self.theme_list.remove(theme)
2011-06-12 15:17:01 +00:00
thumb = u'%s.png' % theme
2011-01-14 18:58:47 +00:00
delete_file(os.path.join(self.path, thumb))
delete_file(os.path.join(self.thumb_path, thumb))
try:
encoding = get_filesystem_encoding()
shutil.rmtree(os.path.join(self.path, theme).encode(encoding))
except OSError:
2010-07-21 09:52:00 +00:00
log.exception(u'Error deleting theme %s', theme)
2009-09-13 15:14:45 +00:00
def onExportTheme(self):
"""
Export the theme in a zip file
"""
item = self.themeListWidget.currentItem()
if item is None:
critical_error_message_box(message=translate('OpenLP.ThemeManager',
'You have not selected a theme.'))
return
theme = unicode(item.data(QtCore.Qt.UserRole).toString())
path = QtGui.QFileDialog.getExistingDirectory(self,
unicode(translate('OpenLP.ThemeManager',
'Save Theme - (%s)')) % theme,
SettingsManager.get_last_dir(self.settingsSection, 1))
path = unicode(path)
2011-03-05 09:23:47 +00:00
Receiver.send_message(u'cursor_busy')
2009-11-07 00:00:36 +00:00
if path:
SettingsManager.set_last_dir(self.settingsSection, path, 1)
theme_path = os.path.join(path, theme + u'.otz')
2009-11-07 00:00:36 +00:00
zip = None
try:
zip = zipfile.ZipFile(theme_path, u'w')
2009-11-07 00:00:36 +00:00
source = os.path.join(self.path, theme)
for files in os.walk(source):
for name in files[2]:
2009-11-07 00:00:36 +00:00
zip.write(
os.path.join(source, name).encode(u'utf-8'),
os.path.join(theme, name).encode(u'utf-8'))
QtGui.QMessageBox.information(self,
translate('OpenLP.ThemeManager', 'Theme Exported'),
translate('OpenLP.ThemeManager',
2010-06-18 23:18:08 +00:00
'Your theme has been successfully exported.'))
2010-05-27 16:00:51 +00:00
except (IOError, OSError):
2009-11-07 00:00:36 +00:00
log.exception(u'Export Theme Failed')
critical_error_message_box(
translate('OpenLP.ThemeManager', 'Theme Export Failed'),
translate('OpenLP.ThemeManager',
2011-01-15 19:24:50 +00:00
'Your theme could not be exported due to an error.'))
2009-11-07 00:00:36 +00:00
finally:
if zip:
zip.close()
2011-03-05 09:23:47 +00:00
Receiver.send_message(u'cursor_normal')
2009-09-13 15:14:45 +00:00
def onImportTheme(self):
2010-06-10 01:57:59 +00:00
"""
Opens a file dialog to select the theme file(s) to import before
2011-02-25 17:05:01 +00:00
attempting to extract OpenLP themes from those files. This process
2010-06-10 01:57:59 +00:00
will load both OpenLP version 1 and version 2 themes.
"""
2010-06-18 23:18:08 +00:00
files = QtGui.QFileDialog.getOpenFileNames(self,
translate('OpenLP.ThemeManager', 'Select Theme Import File'),
2010-06-18 23:18:08 +00:00
SettingsManager.get_last_dir(self.settingsSection),
unicode(translate('OpenLP.ThemeManager',
2011-02-15 19:09:07 +00:00
'OpenLP Themes (*.theme *.otz)')))
2009-09-13 15:14:45 +00:00
log.info(u'New Themes %s', unicode(files))
if not files:
return
2011-03-05 09:23:47 +00:00
Receiver.send_message(u'cursor_busy')
for file in files:
SettingsManager.set_last_dir(self.settingsSection, unicode(file))
self.unzipTheme(file, self.path)
2009-09-13 15:14:45 +00:00
self.loadThemes()
2011-03-05 09:23:47 +00:00
Receiver.send_message(u'cursor_normal')
2009-09-13 15:14:45 +00:00
def loadThemes(self, firstTime=False):
2009-09-13 15:14:45 +00:00
"""
Loads the theme lists and triggers updates accross the whole system
using direct calls or core functions and events for the plugins.
2009-09-13 15:14:45 +00:00
The plugins will call back in to get the real list if they want it.
"""
log.debug(u'Load themes from dir')
self.theme_list = []
self.themeListWidget.clear()
2011-03-20 07:37:44 +00:00
files = SettingsManager.get_files(self.settingsSection, u'.png')
if firstTime:
2011-03-20 07:37:44 +00:00
self.firstTime()
files = SettingsManager.get_files(self.settingsSection, u'.png')
# No themes have been found so create one
if not files:
theme = ThemeXML()
theme.theme_name = UiStrings().Default
self._writeTheme(theme, None, None)
Settings().setValue(
self.settingsSection + u'/global theme',
QtCore.QVariant(theme.theme_name))
self.configUpdated()
2011-03-20 07:37:44 +00:00
files = SettingsManager.get_files(self.settingsSection, u'.png')
# Sort the themes by its name considering language specific characters.
# lower() is needed for windows!
2012-03-10 08:22:52 +00:00
files.sort(key=lambda file_name: unicode(file_name).lower(),
cmp=locale.strcoll)
2011-03-20 07:37:44 +00:00
# now process the file list of png files
for name in files:
# check to see file is in theme root directory
theme = os.path.join(self.path, name)
if os.path.exists(theme):
text_name = os.path.splitext(name)[0]
if text_name == self.global_theme:
2011-03-20 07:37:44 +00:00
name = unicode(translate('OpenLP.ThemeManager',
'%s (default)')) % text_name
2011-03-20 07:37:44 +00:00
else:
name = text_name
thumb = os.path.join(self.thumb_path, u'%s.png' % text_name)
2011-03-20 07:37:44 +00:00
item_name = QtGui.QListWidgetItem(name)
2011-06-12 15:17:01 +00:00
if validate_thumb(theme, thumb):
2011-03-20 07:37:44 +00:00
icon = build_icon(thumb)
else:
2011-06-12 15:17:01 +00:00
icon = create_thumb(theme, thumb)
2011-03-20 07:37:44 +00:00
item_name.setIcon(icon)
2012-06-23 17:21:27 +00:00
item_name.setData(
QtCore.Qt.UserRole, QtCore.QVariant(text_name))
2011-03-20 07:37:44 +00:00
self.themeListWidget.addItem(item_name)
self.theme_list.append(text_name)
self._pushThemes()
2009-09-13 15:14:45 +00:00
def _pushThemes(self):
2010-06-10 01:57:59 +00:00
"""
Notify listeners that the theme list has been updated
"""
2010-04-30 21:00:17 +00:00
Receiver.send_message(u'theme_update_list', self.getThemes())
2009-09-13 15:14:45 +00:00
def getThemes(self):
2010-06-10 01:57:59 +00:00
"""
Return the list of loaded themes
"""
return self.theme_list
2009-09-13 15:14:45 +00:00
2012-03-10 08:22:52 +00:00
def getThemeData(self, theme_name):
2010-06-10 01:57:59 +00:00
"""
Returns a theme object from an XML file
2012-03-10 08:22:52 +00:00
``theme_name``
2010-06-10 01:57:59 +00:00
Name of the theme to load from file
"""
2012-03-10 08:22:52 +00:00
log.debug(u'getthemedata for theme %s', theme_name)
xml_file = os.path.join(self.path, unicode(theme_name),
2012-03-10 08:22:52 +00:00
unicode(theme_name) + u'.xml')
xml = get_text_file_string(xml_file)
2009-11-06 02:12:56 +00:00
if not xml:
2012-06-23 17:21:27 +00:00
log.debug(u'No theme data - using default theme')
return ThemeXML()
2010-10-11 16:14:36 +00:00
else:
2010-12-28 10:56:19 +00:00
return self._createThemeFromXml(xml, self.path)
2009-09-13 15:14:45 +00:00
2012-03-10 08:22:52 +00:00
def overWriteMessageBox(self, theme_name):
ret = QtGui.QMessageBox.question(self,
translate('OpenLP.ThemeManager', 'Theme Already Exists'),
translate('OpenLP.ThemeManager',
'Theme %s already exists. Do you want to replace it?'
2012-03-10 08:22:52 +00:00
% theme_name),
QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No),
QtGui.QMessageBox.No)
2012-03-10 08:22:52 +00:00
return ret == QtGui.QMessageBox.Yes
2009-09-13 15:14:45 +00:00
2012-03-10 08:22:52 +00:00
def unzipTheme(self, file_name, dir):
2009-09-13 15:14:45 +00:00
"""
Unzip the theme, remove the preview file if stored
Generate a new preview file. Check the XML theme version and upgrade if
2009-09-13 15:14:45 +00:00
necessary.
"""
2012-03-10 08:22:52 +00:00
log.debug(u'Unzipping theme %s', file_name)
file_name = unicode(file_name)
2009-11-07 00:00:36 +00:00
zip = None
2012-03-10 08:22:52 +00:00
out_file = None
file_xml = None
2012-06-15 16:19:46 +00:00
abort_import = True
try:
2012-03-10 08:22:52 +00:00
zip = zipfile.ZipFile(file_name)
xml_file = filter(lambda name:
os.path.splitext(name)[1].lower() == u'.xml', zip.namelist())
if len(xml_file) != 1:
log.exception(u'Theme contains "%s" XML files' % len(xml_file))
raise Exception(u'validation')
xml_tree = ElementTree(element=XML(zip.read(xml_file[0]))).getroot()
v1_background = xml_tree.find(u'BackgroundType')
if v1_background is not None:
2012-06-23 17:21:27 +00:00
theme_name, file_xml, out_file, abort_import = \
self.unzipVersion122(
dir, zip, xml_file[0], xml_tree, v1_background, out_file)
else:
2012-03-10 08:22:52 +00:00
theme_name = xml_tree.find(u'name').text.strip()
theme_folder = os.path.join(dir, theme_name)
theme_exists = os.path.exists(theme_folder)
if theme_exists and not self.overWriteMessageBox(theme_name):
abort_import = True
return
else:
2012-03-10 08:22:52 +00:00
abort_import = False
for name in zip.namelist():
try:
uname = unicode(name, u'utf-8')
except UnicodeDecodeError:
log.exception(u'Theme file contains non utf-8 filename'
u' "%s"' % name.decode(u'utf-8', u'replace'))
raise Exception(u'validation')
2012-02-26 21:09:22 +00:00
uname = uname.replace(u'/', os.path.sep)
2012-03-10 16:44:58 +00:00
split_name = uname.split(os.path.sep)
if split_name[-1] == u'' or len(split_name) == 1:
# is directory or preview file
continue
full_name = os.path.join(dir, uname)
check_directory_exists(os.path.dirname(full_name))
if os.path.splitext(uname)[1].lower() == u'.xml':
2012-03-10 08:22:52 +00:00
file_xml = unicode(zip.read(name), u'utf-8')
out_file = open(full_name, u'w')
2012-03-10 08:22:52 +00:00
out_file.write(file_xml.encode(u'utf-8'))
else:
out_file = open(full_name, u'wb')
2012-03-10 08:22:52 +00:00
out_file.write(zip.read(name))
out_file.close()
except (IOError, zipfile.BadZipfile):
2012-03-10 08:22:52 +00:00
log.exception(u'Importing theme from zip failed %s' % file_name)
raise Exception(u'validation')
except Exception as info:
if unicode(info) == u'validation':
critical_error_message_box(translate('OpenLP.ThemeManager',
'Validation Error'), translate('OpenLP.ThemeManager',
'File is not a valid theme.'))
else:
raise
finally:
# Close the files, to be able to continue creating the theme.
if zip:
zip.close()
2012-03-10 08:22:52 +00:00
if out_file:
out_file.close()
if not abort_import:
# As all files are closed, we can create the Theme.
2012-03-10 08:22:52 +00:00
if file_xml:
theme = self._createThemeFromXml(file_xml, self.path)
self.generateAndSaveImage(dir, theme_name, theme)
2012-06-23 17:21:27 +00:00
# Only show the error message, when IOError was not raised (in
# this case the error message has already been shown).
elif zip is not None:
critical_error_message_box(
translate('OpenLP.ThemeManager', 'Validation Error'),
translate('OpenLP.ThemeManager',
'File is not a valid theme.'))
log.exception(u'Theme file does not contain XML data %s' %
2012-03-10 08:22:52 +00:00
file_name)
2009-09-13 15:14:45 +00:00
2012-06-23 17:21:27 +00:00
def unzipVersion122(self, dir, zip, xml_file, xml_tree, background,
out_file):
"""
Unzip openlp.org 1.2x theme file and upgrade the theme xml. When calling
this method, please keep in mind, that some parameters are redundant.
"""
2012-03-10 08:22:52 +00:00
theme_name = xml_tree.find(u'Name').text.strip()
theme_name = self.bad_v1_name_chars.sub(u'', theme_name)
2012-03-10 16:44:58 +00:00
theme_folder = os.path.join(dir, theme_name)
2012-03-10 08:22:52 +00:00
theme_exists = os.path.exists(theme_folder)
if theme_exists and not self.overWriteMessageBox(theme_name):
2012-03-10 16:14:07 +00:00
return '', '', '', True
2012-03-10 08:22:52 +00:00
themedir = os.path.join(dir, theme_name)
check_directory_exists(themedir)
file_xml = unicode(zip.read(xml_file), u'utf-8')
2012-03-10 08:22:52 +00:00
file_xml = self._migrateVersion122(file_xml)
out_file = open(os.path.join(themedir, theme_name + u'.xml'), u'w')
out_file.write(file_xml.encode(u'utf-8'))
out_file.close()
if background.text.strip() == u'2':
image_name = xml_tree.find(u'BackgroundParameter1').text.strip()
# image file has same extension and is in subfolder
imagefile = filter(lambda name: os.path.splitext(name)[1].lower()
== os.path.splitext(image_name)[1].lower() and name.find(r'/'),
zip.namelist())
if len(imagefile) >= 1:
out_file = open(os.path.join(themedir, image_name), u'wb')
2012-03-10 08:22:52 +00:00
out_file.write(zip.read(imagefile[0]))
out_file.close()
else:
log.exception(u'Theme file does not contain image file "%s"' %
image_name.decode(u'utf-8', u'replace'))
raise Exception(u'validation')
2012-03-10 08:22:52 +00:00
return theme_name, file_xml, out_file, False
2012-03-10 08:22:52 +00:00
def checkIfThemeExists(self, theme_name):
2009-09-13 15:14:45 +00:00
"""
2010-12-27 10:18:09 +00:00
Check if theme already exists and displays error message
2010-06-10 01:57:59 +00:00
2012-03-10 08:22:52 +00:00
``theme_name``
2010-12-28 10:56:19 +00:00
Name of the Theme to test
2010-12-27 10:18:09 +00:00
"""
2012-03-10 08:22:52 +00:00
theme_dir = os.path.join(self.path, theme_name)
2010-12-27 10:18:09 +00:00
if os.path.exists(theme_dir):
critical_error_message_box(
2011-01-15 19:24:50 +00:00
translate('OpenLP.ThemeManager', 'Validation Error'),
translate('OpenLP.ThemeManager',
'A theme with this name already exists.'))
2010-12-27 10:18:09 +00:00
return False
return True
2009-09-13 15:14:45 +00:00
def saveTheme(self, theme, image_from, image_to):
2009-09-13 15:14:45 +00:00
"""
Called by thememaintenance Dialog to save the theme
and to trigger the reload of the theme list
"""
self._writeTheme(theme, image_from, image_to)
2011-08-20 15:02:57 +00:00
if theme.background_type == \
BackgroundType.to_string(BackgroundType.Image):
self.mainwindow.imageManager.updateImage(theme.theme_name,
2011-08-21 05:33:07 +00:00
u'theme', QtGui.QColor(theme.background_border_color))
self.mainwindow.imageManager.processUpdates()
self.loadThemes()
def _writeTheme(self, theme, image_from, image_to):
"""
Writes the theme to the disk and handles the background image if
necessary
"""
2010-11-05 19:20:41 +00:00
name = theme.theme_name
theme_pretty_xml = theme.extract_formatted_xml()
2011-12-11 16:23:24 +00:00
log.debug(u'saveTheme %s %s', name, theme_pretty_xml.decode(u'utf-8'))
2009-09-13 15:14:45 +00:00
theme_dir = os.path.join(self.path, name)
2011-01-09 08:17:17 +00:00
check_directory_exists(theme_dir)
2009-09-13 15:14:45 +00:00
theme_file = os.path.join(theme_dir, name + u'.xml')
if self.old_background_image and \
image_to != self.old_background_image:
delete_file(self.old_background_image)
2012-03-10 08:22:52 +00:00
out_file = None
2010-12-27 10:18:09 +00:00
try:
2012-03-10 08:22:52 +00:00
out_file = open(theme_file, u'w')
out_file.write(theme_pretty_xml)
2010-12-27 10:18:09 +00:00
except IOError:
log.exception(u'Saving theme to file failed')
finally:
2012-03-10 08:22:52 +00:00
if out_file:
out_file.close()
if image_from and image_from != image_to:
2009-11-07 00:00:36 +00:00
try:
2010-12-27 10:18:09 +00:00
encoding = get_filesystem_encoding()
shutil.copyfile(
unicode(image_from).encode(encoding),
unicode(image_to).encode(encoding))
2010-05-27 16:00:51 +00:00
except IOError:
2010-12-27 10:18:09 +00:00
log.exception(u'Failed to save theme image')
self.generateAndSaveImage(self.path, name, theme)
2009-09-13 15:14:45 +00:00
2010-11-05 19:20:41 +00:00
def generateAndSaveImage(self, dir, name, theme):
log.debug(u'generateAndSaveImage %s %s', dir, name)
2009-09-13 15:14:45 +00:00
frame = self.generateImage(theme)
sample_path_name = os.path.join(self.path, name + u'.png')
if os.path.exists(sample_path_name):
os.unlink(sample_path_name)
frame.save(sample_path_name, u'png')
thumb = os.path.join(self.thumb_path, u'%s.png' % name)
create_thumb(sample_path_name, thumb, False)
log.debug(u'Theme image written to %s', sample_path_name)
2009-09-13 15:14:45 +00:00
def updatePreviewImages(self):
"""
Called to update the themes' preview images.
"""
2012-03-10 22:18:52 +00:00
self.mainwindow.displayProgressBar(len(self.theme_list))
for theme in self.theme_list:
self.mainwindow.incrementProgressBar()
self.generateAndSaveImage(
self.path, theme, self.getThemeData(theme))
self.mainwindow.finishedProgressBar()
self.loadThemes()
def generateImage(self, theme_data, forcePage=False):
2009-09-13 15:14:45 +00:00
"""
2011-03-28 18:56:39 +00:00
Call the renderer to build a Sample Image
``theme_data``
The theme to generated a preview for.
``forcePage``
Flag to tell message lines per page need to be generated.
2009-09-13 15:14:45 +00:00
"""
log.debug(u'generateImage \n%s ', theme_data)
2011-03-28 18:56:39 +00:00
return self.mainwindow.renderer.generate_preview(
theme_data, forcePage)
2009-09-13 15:14:45 +00:00
def getPreviewImage(self, theme):
2010-06-10 19:45:02 +00:00
"""
Return an image representing the look of the theme
``theme``
The theme to return the image for
"""
2009-09-13 15:14:45 +00:00
log.debug(u'getPreviewImage %s ', theme)
image = os.path.join(self.path, theme + u'.png')
return image
def _createThemeFromXml(self, theme_xml, path):
2010-06-10 19:45:02 +00:00
"""
Return a theme object using information parsed from XML
``theme_xml``
2010-06-10 19:45:02 +00:00
The XML data to load into the theme
"""
2009-11-06 02:12:56 +00:00
theme = ThemeXML()
theme.parse(theme_xml)
2009-11-06 02:12:56 +00:00
theme.extend_image_filename(path)
return theme
def _validate_theme_action(self, select_text, confirm_title, confirm_text,
2011-02-05 17:31:13 +00:00
testPlugin=True, confirm=True):
"""
Check to see if theme has been selected and the destructive action
is allowed.
"""
self.global_theme = unicode(Settings().value(
self.settingsSection + u'/global theme',
QtCore.QVariant(u'')).toString())
if check_item_selected(self.themeListWidget, select_text):
item = self.themeListWidget.currentItem()
theme = unicode(item.text())
# confirm deletion
2011-02-05 17:31:13 +00:00
if confirm:
answer = QtGui.QMessageBox.question(self, confirm_title,
confirm_text % theme, QtGui.QMessageBox.StandardButtons(
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No),
QtGui.QMessageBox.No)
if answer == QtGui.QMessageBox.No:
return False
# should be the same unless default
if theme != unicode(item.data(QtCore.Qt.UserRole).toString()):
critical_error_message_box(
2011-01-15 19:24:50 +00:00
message=translate('OpenLP.ThemeManager',
2011-01-15 00:53:12 +00:00
'You are unable to delete the default theme.'))
return False
2010-12-27 10:18:09 +00:00
# check for use in the system else where.
if testPlugin:
2011-01-09 23:24:55 +00:00
for plugin in self.mainwindow.pluginManager.plugins:
2010-12-27 10:18:09 +00:00
if plugin.usesTheme(theme):
critical_error_message_box(
translate('OpenLP.ThemeManager',
2011-01-01 17:23:24 +00:00
'Validation Error'),
2011-01-15 19:24:50 +00:00
unicode(translate('OpenLP.ThemeManager',
2011-01-01 17:23:24 +00:00
'Theme %s is used in the %s plugin.')) % \
2011-01-15 19:24:50 +00:00
(theme, plugin.name))
2010-12-27 10:18:09 +00:00
return False
return True
return False
2010-12-28 10:56:19 +00:00
def _migrateVersion122(self, xml_data):
"""
Convert the xml data from version 1 format to the current format.
New fields are loaded with defaults to provide a complete, working
theme containing all compatible customisations from the old theme.
``xml_data``
Version 1 theme to convert
"""
theme = Theme(xml_data)
new_theme = ThemeXML()
new_theme.theme_name = self.bad_v1_name_chars.sub(u'', theme.Name)
2010-12-28 10:56:19 +00:00
if theme.BackgroundType == 0:
new_theme.background_type = \
2010-12-28 10:56:19 +00:00
BackgroundType.to_string(BackgroundType.Solid)
new_theme.background_color = \
2010-12-28 10:56:19 +00:00
unicode(theme.BackgroundParameter1.name())
elif theme.BackgroundType == 1:
new_theme.background_type = \
2010-12-28 10:56:19 +00:00
BackgroundType.to_string(BackgroundType.Gradient)
new_theme.background_direction = \
2010-12-28 10:56:19 +00:00
BackgroundGradientType. \
to_string(BackgroundGradientType.Horizontal)
if theme.BackgroundParameter3.name() == 1:
new_theme.background_direction = \
2010-12-28 10:56:19 +00:00
BackgroundGradientType. \
to_string(BackgroundGradientType.Horizontal)
new_theme.background_start_color = \
2010-12-28 10:56:19 +00:00
unicode(theme.BackgroundParameter1.name())
new_theme.background_end_color = \
2010-12-28 10:56:19 +00:00
unicode(theme.BackgroundParameter2.name())
2012-01-04 17:19:49 +00:00
elif theme.BackgroundType == 2:
new_theme.background_type = \
2010-12-28 10:56:19 +00:00
BackgroundType.to_string(BackgroundType.Image)
new_theme.background_filename = unicode(theme.BackgroundParameter1)
2012-01-04 17:19:49 +00:00
elif theme.BackgroundType == 3:
new_theme.background_type = \
2012-01-04 17:19:49 +00:00
BackgroundType.to_string(BackgroundType.Transparent)
new_theme.font_main_name = theme.FontName
new_theme.font_main_color = unicode(theme.FontColor.name())
new_theme.font_main_size = theme.FontProportion * 3
new_theme.font_footer_name = theme.FontName
new_theme.font_footer_color = unicode(theme.FontColor.name())
new_theme.font_main_shadow = False
2010-12-28 10:56:19 +00:00
if theme.Shadow == 1:
new_theme.font_main_shadow = True
new_theme.font_main_shadow_color = unicode(theme.ShadowColor.name())
2010-12-28 10:56:19 +00:00
if theme.Outline == 1:
new_theme.font_main_outline = True
new_theme.font_main_outline_color = \
2010-12-28 10:56:19 +00:00
unicode(theme.OutlineColor.name())
vAlignCorrection = VerticalType.Top
2010-12-28 10:56:19 +00:00
if theme.VerticalAlign == 2:
vAlignCorrection = VerticalType.Middle
2010-12-28 10:56:19 +00:00
elif theme.VerticalAlign == 1:
vAlignCorrection = VerticalType.Bottom
new_theme.display_horizontal_align = theme.HorizontalAlign
new_theme.display_vertical_align = vAlignCorrection
return new_theme.extract_xml()