← Back to team overview

openlp-core team mailing list archive

[Merge] lp:~meths/openlp/trivialfixes into lp:openlp

 

Jon Tibble has proposed merging lp:~meths/openlp/trivialfixes into lp:openlp.

Requested reviews:
    openlp.org Core (openlp-core)

Fix file formatting in the tree with dos2unix.  Let me know if I missed any files you've noticed - want to confirm methodology.
-- 
https://code.launchpad.net/~meths/openlp/trivialfixes/+merge/11656
Your team openlp.org Core is subscribed to branch lp:openlp.
=== modified file 'demo_theme.xml'
--- demo_theme.xml	2008-10-07 19:12:32 +0000
+++ demo_theme.xml	2009-09-12 18:14:09 +0000
@@ -1,17 +1,17 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Theme>
-  <Name>openlp.org 2.0 Demo Theme</Name>
-  <BackgroundType>2</BackgroundType>
-  <BackgroundParameter1>./openlp/core/test/data_for_tests/treesbig.jpg</BackgroundParameter1>
-  <BackgroundParameter2>clBlack</BackgroundParameter2>
-  <BackgroundParameter3/>
-  <FontName>Tahoma</FontName>
-  <FontColor>clWhite</FontColor>
-  <FontProportion>16</FontProportion>
-  <Shadow>-1</Shadow>
-  <ShadowColor>$00000001</ShadowColor>
-  <Outline>-1</Outline>
-  <OutlineColor>clRed</OutlineColor>
-  <HorizontalAlign>2</HorizontalAlign>
-  <VerticalAlign>2</VerticalAlign>
-</Theme>
+<?xml version="1.0" encoding="iso-8859-1"?>
+<Theme>
+  <Name>openlp.org 2.0 Demo Theme</Name>
+  <BackgroundType>2</BackgroundType>
+  <BackgroundParameter1>./openlp/core/test/data_for_tests/treesbig.jpg</BackgroundParameter1>
+  <BackgroundParameter2>clBlack</BackgroundParameter2>
+  <BackgroundParameter3/>
+  <FontName>Tahoma</FontName>
+  <FontColor>clWhite</FontColor>
+  <FontProportion>16</FontProportion>
+  <Shadow>-1</Shadow>
+  <ShadowColor>$00000001</ShadowColor>
+  <Outline>-1</Outline>
+  <OutlineColor>clRed</OutlineColor>
+  <HorizontalAlign>2</HorizontalAlign>
+  <VerticalAlign>2</VerticalAlign>
+</Theme>

=== modified file 'documentation/pyqt-sql-py2exe.txt'
--- documentation/pyqt-sql-py2exe.txt	2008-11-27 20:14:38 +0000
+++ documentation/pyqt-sql-py2exe.txt	2009-09-12 18:14:09 +0000
@@ -1,58 +1,58 @@
-This content can be found at this URL:
-http://netsuperbrain.com/Postmodern%20PostgreSQL%20Application%20Development.pdf
-
-Page 11-15: QtDesigner
-Page 18-20: SQLAlchemy
-Page 21-23: PyQt - widget
-Page 24   : main
-Page 28   : py2exe and release
-
-
-==============================
-This is the destilled content.
-==============================
-
-----------------
-** sqlalchemy **
-----------------
-from sqlalchemy import create_engine, MetaData, Table
-from sqlalchemy.orm import sessionmaker, mapper
-engine = create_engine( 'postgres://postgres@localhost/customers' )
-metadata = MetaData( bind=engine, reflect=True)
-Session = sessionmaker(bind=engine, autoflush=True,
-    transactional=True)
-
-class Customer(object): pass
-mapper( Customer, Table('customers', metadata ) )
-
-session = Session()
-customer = Customer( businessName=“Jamb Safety”,
-    website=“www.jamb.com” )
-session.save( customer )
-for customer in Session.query(Customer).filter(
-    Customer.businessName.like(“Jamb%”)):
-    print customer.businessName
-session.commit()
-
-------------------------
-** release and py2exe **
-------------------------
-
-from distutils.core import setup
-import py2exe
-import glob
-setup(
-    name="Customers",
-    author="Sankel Software",
-    author_email="david@xxxxxxxxxxxxxxxxxx",
-    url="http://sankelsoftware.com";,
-    license=“GPL",
-    version=“1.0.0",
-    windows=[ { "script":"main.py“,}],
-    options={"py2exe":{"includes":["sip”]}},
-    data_files=[
-       ("forms",glob.glob("forms/*.ui")),
-    ] )
-
-release:
-python setup.py py2exe --quiet --dist-dir=dist
+This content can be found at this URL:
+http://netsuperbrain.com/Postmodern%20PostgreSQL%20Application%20Development.pdf
+
+Page 11-15: QtDesigner
+Page 18-20: SQLAlchemy
+Page 21-23: PyQt - widget
+Page 24   : main
+Page 28   : py2exe and release
+
+
+==============================
+This is the destilled content.
+==============================
+
+----------------
+** sqlalchemy **
+----------------
+from sqlalchemy import create_engine, MetaData, Table
+from sqlalchemy.orm import sessionmaker, mapper
+engine = create_engine( 'postgres://postgres@localhost/customers' )
+metadata = MetaData( bind=engine, reflect=True)
+Session = sessionmaker(bind=engine, autoflush=True,
+    transactional=True)
+
+class Customer(object): pass
+mapper( Customer, Table('customers', metadata ) )
+
+session = Session()
+customer = Customer( businessName=“Jamb Safety”,
+    website=“www.jamb.com” )
+session.save( customer )
+for customer in Session.query(Customer).filter(
+    Customer.businessName.like(“Jamb%”)):
+    print customer.businessName
+session.commit()
+
+------------------------
+** release and py2exe **
+------------------------
+
+from distutils.core import setup
+import py2exe
+import glob
+setup(
+    name="Customers",
+    author="Sankel Software",
+    author_email="david@xxxxxxxxxxxxxxxxxx",
+    url="http://sankelsoftware.com";,
+    license=“GPL",
+    version=“1.0.0",
+    windows=[ { "script":"main.py“,}],
+    options={"py2exe":{"includes":["sip”]}},
+    data_files=[
+       ("forms",glob.glob("forms/*.ui")),
+    ] )
+
+release:
+python setup.py py2exe --quiet --dist-dir=dist

=== modified file 'openlp/core/test/data_for_tests/render_theme.xml'
--- openlp/core/test/data_for_tests/render_theme.xml	2009-03-12 20:19:24 +0000
+++ openlp/core/test/data_for_tests/render_theme.xml	2009-09-12 18:14:09 +0000
@@ -1,19 +1,19 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Theme>
-  <Name>openlp.org Packaged Theme</Name>
-  <BackgroundType>0</BackgroundType>
-  <BackgroundParameter1>clWhite</BackgroundParameter1>
-  <BackgroundParameter2/>
-  <BackgroundParameter3/>
-  <FontName>Tahoma</FontName>
-  <FontColor>$00007F</FontColor>
-  <FontProportion>53</FontProportion>
-  <FontUnits>pixels</FontUnits>
-  <Shadow>0</Shadow>
-  <ShadowColor>$000000</ShadowColor>
-  <Outline>0</Outline>
-  <OutlineColor>$000000</OutlineColor>
-  <HorizontalAlign>0</HorizontalAlign>
-  <VerticalAlign>0</VerticalAlign>
-  <WrapStyle>1</WrapStyle>
-</Theme>
+<?xml version="1.0" encoding="iso-8859-1"?>
+<Theme>
+  <Name>openlp.org Packaged Theme</Name>
+  <BackgroundType>0</BackgroundType>
+  <BackgroundParameter1>clWhite</BackgroundParameter1>
+  <BackgroundParameter2/>
+  <BackgroundParameter3/>
+  <FontName>Tahoma</FontName>
+  <FontColor>$00007F</FontColor>
+  <FontProportion>53</FontProportion>
+  <FontUnits>pixels</FontUnits>
+  <Shadow>0</Shadow>
+  <ShadowColor>$000000</ShadowColor>
+  <Outline>0</Outline>
+  <OutlineColor>$000000</OutlineColor>
+  <HorizontalAlign>0</HorizontalAlign>
+  <VerticalAlign>0</VerticalAlign>
+  <WrapStyle>1</WrapStyle>
+</Theme>

=== modified file 'openlp/core/theme/test/test_theme.xml'
--- openlp/core/theme/test/test_theme.xml	2009-03-12 20:19:24 +0000
+++ openlp/core/theme/test/test_theme.xml	2009-09-12 18:14:09 +0000
@@ -1,18 +1,18 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Theme>
-  <Name>openlp.org Packaged Theme</Name>
-  <BackgroundType>2</BackgroundType>
-  <BackgroundParameter1>sunset1.jpg</BackgroundParameter1>
-  <BackgroundParameter2/>
-  <BackgroundParameter3/>
-  <FontName>Tahoma</FontName>
-  <FontColor>clWhite</FontColor>
-  <FontProportion>16</FontProportion>
-  <FontUnits>pixels</FontUnits>
-  <Shadow>-1</Shadow>
-  <ShadowColor>$00000001</ShadowColor>
-  <Outline>-1</Outline>
-  <OutlineColor>clRed</OutlineColor>
-  <HorizontalAlign>2</HorizontalAlign>
-  <VerticalAlign>0</VerticalAlign>
-</Theme>
+<?xml version="1.0" encoding="iso-8859-1"?>
+<Theme>
+  <Name>openlp.org Packaged Theme</Name>
+  <BackgroundType>2</BackgroundType>
+  <BackgroundParameter1>sunset1.jpg</BackgroundParameter1>
+  <BackgroundParameter2/>
+  <BackgroundParameter3/>
+  <FontName>Tahoma</FontName>
+  <FontColor>clWhite</FontColor>
+  <FontProportion>16</FontProportion>
+  <FontUnits>pixels</FontUnits>
+  <Shadow>-1</Shadow>
+  <ShadowColor>$00000001</ShadowColor>
+  <Outline>-1</Outline>
+  <OutlineColor>clRed</OutlineColor>
+  <HorizontalAlign>2</HorizontalAlign>
+  <VerticalAlign>0</VerticalAlign>
+</Theme>

=== modified file 'openlp/core/ui/amendthemeform.py'
--- openlp/core/ui/amendthemeform.py	2009-09-12 17:24:16 +0000
+++ openlp/core/ui/amendthemeform.py	2009-09-12 18:14:09 +0000
@@ -1,715 +1,715 @@
-# -*- coding: utf-8 -*-
-# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
-
-###############################################################################
-# OpenLP - Open Source Lyrics Projection                                      #
-# --------------------------------------------------------------------------- #
-# Copyright (c) 2008-2009 Raoul Snyman                                        #
-# Portions copyright (c) 2008-2009 Martin Thompson, Tim Bentley, Carsten      #
-# Tinggaard, Jon Tibble, Jonathan Corwin, Maikel Stuivenberg, Scott Guerrieri #
-# --------------------------------------------------------------------------- #
-# 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 logging
-import os, os.path
-
-from PyQt4 import QtCore, QtGui
-from openlp.core.lib import ThemeXML, Renderer, file_to_xml, str_to_bool, \
-    translate
-
-from amendthemedialog import Ui_AmendThemeDialog
-
-log = logging.getLogger(u'AmendThemeForm')
-
-class AmendThemeForm(QtGui.QDialog,  Ui_AmendThemeDialog):
-
-    def __init__(self, thememanager, parent=None):
-        QtGui.QDialog.__init__(self, parent)
-        self.thememanager = thememanager
-        self.path = None
-        self.theme = ThemeXML()
-        self.setupUi(self)
-        #define signals
-        #Buttons
-        QtCore.QObject.connect(self.Color1PushButton ,
-            QtCore.SIGNAL(u'pressed()'), self.onColor1PushButtonClicked)
-        QtCore.QObject.connect(self.Color2PushButton ,
-            QtCore.SIGNAL(u'pressed()'), self.onColor2PushButtonClicked)
-        QtCore.QObject.connect(self.FontMainColorPushButton,
-            QtCore.SIGNAL(u'pressed()'), self.onFontMainColorPushButtonClicked)
-        QtCore.QObject.connect(self.FontFooterColorPushButton,
-            QtCore.SIGNAL(u'pressed()'),
-            self.onFontFooterColorPushButtonClicked)
-        QtCore.QObject.connect(self.OutlineColorPushButton,
-            QtCore.SIGNAL(u'pressed()'), self.onOutlineColorPushButtonClicked)
-        QtCore.QObject.connect(self.ShadowColorPushButton,
-            QtCore.SIGNAL(u'pressed()'), self.onShadowColorPushButtonClicked)
-        QtCore.QObject.connect(self.ImageToolButton,
-            QtCore.SIGNAL(u'pressed()'), self.onImageToolButtonClicked)
-        #Combo boxes
-        QtCore.QObject.connect(self.BackgroundComboBox,
-            QtCore.SIGNAL(u'activated(int)'), self.onBackgroundComboBoxSelected)
-        QtCore.QObject.connect(self.BackgroundTypeComboBox,
-            QtCore.SIGNAL(u'activated(int)'),
-            self.onBackgroundTypeComboBoxSelected)
-        QtCore.QObject.connect(self.GradientComboBox,
-            QtCore.SIGNAL(u'activated(int)'), self.onGradientComboBoxSelected)
-        QtCore.QObject.connect(self.FontMainComboBox,
-            QtCore.SIGNAL(u'activated(int)'), self.onFontMainComboBoxSelected)
-        QtCore.QObject.connect(self.FontMainWeightComboBox,
-            QtCore.SIGNAL(u'activated(int)'),
-            self.onFontMainWeightComboBoxSelected)
-        QtCore.QObject.connect(self.FontFooterComboBox,
-            QtCore.SIGNAL(u'activated(int)'), self.onFontFooterComboBoxSelected)
-        QtCore.QObject.connect(self.FontFooterWeightComboBox,
-            QtCore.SIGNAL(u'activated(int)'),
-            self.onFontFooterWeightComboBoxSelected)
-        QtCore.QObject.connect(self.HorizontalComboBox,
-            QtCore.SIGNAL(u'activated(int)'), self.onHorizontalComboBoxSelected)
-        QtCore.QObject.connect(self.VerticalComboBox,
-            QtCore.SIGNAL(u'activated(int)'), self.onVerticalComboBoxSelected)
-        #Spin boxes
-        QtCore.QObject.connect(self.FontMainSizeSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontMainSizeSpinBoxChanged)
-        QtCore.QObject.connect(self.FontFooterSizeSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontFooterSizeSpinBoxChanged)
-        QtCore.QObject.connect(self.FontMainDefaultCheckBox,
-            QtCore.SIGNAL(u'stateChanged(int)'),
-            self.onFontMainDefaultCheckBoxChanged)
-        QtCore.QObject.connect(self.FontMainXSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'), self.onFontMainXSpinBoxChanged)
-        QtCore.QObject.connect(self.FontMainYSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'), self.onFontMainYSpinBoxChanged)
-        QtCore.QObject.connect(self.FontMainWidthSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontMainWidthSpinBoxChanged)
-        QtCore.QObject.connect(self.FontMainHeightSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontMainHeightSpinBoxChanged)
-        QtCore.QObject.connect(self.FontFooterDefaultCheckBox,
-            QtCore.SIGNAL(u'stateChanged(int)'),
-            self.onFontFooterDefaultCheckBoxChanged)
-        QtCore.QObject.connect(self.FontFooterXSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontFooterXSpinBoxChanged)
-        QtCore.QObject.connect(self.FontFooterYSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontFooterYSpinBoxChanged)
-        QtCore.QObject.connect(self.FontFooterWidthSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontFooterWidthSpinBoxChanged)
-        QtCore.QObject.connect(self.FontFooterHeightSpinBox,
-            QtCore.SIGNAL(u'editingFinished()'),
-            self.onFontFooterHeightSpinBoxChanged)
-        QtCore.QObject.connect(self.OutlineCheckBox,
-            QtCore.SIGNAL(u'stateChanged(int)'), self.onOutlineCheckBoxChanged)
-        QtCore.QObject.connect(self.ShadowCheckBox,
-            QtCore.SIGNAL(u'stateChanged(int)'), self.onShadowCheckBoxChanged)
-
-    def accept(self):
-        new_theme = ThemeXML()
-        theme_name = unicode(self.ThemeNameEdit.displayText())
-        new_theme.new_document(theme_name)
-        save_from = None
-        save_to = None
-        if self.theme.background_mode == u'transparent':
-            new_theme.add_background_transparent()
-        else:
-            if self.theme.background_type == u'solid':
-                new_theme.add_background_solid( \
-                    unicode(self.theme.background_color))
-            elif self.theme.background_type == u'gradient':
-                new_theme.add_background_gradient( \
-                    unicode(self.theme.background_startColor),
-                    unicode(self.theme.background_endColor),
-                    self.theme.background_direction)
-            else:
-                (path, filename) = \
-                    os.path.split(unicode(self.theme.background_filename))
-                new_theme.add_background_image(filename)
-                save_to= os.path.join(self.path, theme_name, filename )
-                save_from = self.theme.background_filename
-
-        new_theme.add_font(unicode(self.theme.font_main_name),
-                unicode(self.theme.font_main_color),
-                unicode(self.theme.font_main_proportion),
-                unicode(self.theme.font_main_override), u'main',
-                unicode(self.theme.font_main_weight),
-                unicode(self.theme.font_main_italics),
-                unicode(self.theme.font_main_x),
-                unicode(self.theme.font_main_y),
-                unicode(self.theme.font_main_width),
-                unicode(self.theme.font_main_height))
-        new_theme.add_font(unicode(self.theme.font_footer_name),
-                unicode(self.theme.font_footer_color),
-                unicode(self.theme.font_footer_proportion),
-                unicode(self.theme.font_footer_override), u'footer',
-                unicode(self.theme.font_footer_weight),
-                unicode(self.theme.font_footer_italics),
-                unicode(self.theme.font_footer_x),
-                unicode(self.theme.font_footer_y),
-                unicode(self.theme.font_footer_width),
-                unicode(self.theme.font_footer_height) )
-        new_theme.add_display(unicode(self.theme.display_shadow),
-                unicode(self.theme.display_shadow_color),
-                unicode(self.theme.display_outline),
-                unicode(self.theme.display_outline_color),
-                unicode(self.theme.display_horizontalAlign),
-                unicode(self.theme.display_verticalAlign),
-                unicode(self.theme.display_wrapStyle))
-        theme = new_theme.extract_xml()
-        pretty_theme = new_theme.extract_formatted_xml()
-        if self.thememanager.saveTheme(theme_name, theme, pretty_theme,
-            save_from, save_to) is not False:
-            return QtGui.QDialog.accept(self)
-
-    def loadTheme(self, theme):
-        log.debug(u'LoadTheme %s', theme)
-        if theme == None:
-            self.theme.parse(self.baseTheme())
-        else:
-            xml_file = os.path.join(self.path, theme, theme + u'.xml')
-            xml = file_to_xml(xml_file)
-            self.theme.parse(xml)
-            self.theme.extend_image_filename(self.path)
-        self.cleanTheme(self.theme)
-        self.allowPreview = False
-        self.paintUi(self.theme)
-        self.allowPreview = True
-        self.previewTheme(self.theme)
-
-    def cleanTheme(self, theme):
-        self.theme.background_color = theme.background_color.strip()
-        self.theme.background_direction = theme.background_direction.strip()
-        self.theme.background_endColor = theme.background_endColor.strip()
-        if theme.background_filename:
-            self.theme.background_filename = theme.background_filename.strip()
-        #self.theme.background_mode
-        self.theme.background_startColor = theme.background_startColor.strip()
-        #self.theme.background_type
-        self.theme.display_display = theme.display_display.strip()
-        self.theme.display_horizontalAlign = \
-            theme.display_horizontalAlign.strip()
-        self.theme.display_outline = str_to_bool(theme.display_outline)
-        #self.theme.display_outline_color
-        self.theme.display_shadow = str_to_bool(theme.display_shadow)
-        #self.theme.display_shadow_color
-        self.theme.display_verticalAlign = \
-            theme.display_verticalAlign.strip()
-        self.theme.display_wrapStyle = theme.display_wrapStyle.strip()
-        self.theme.font_footer_color = theme.font_footer_color.strip()
-        self.theme.font_footer_height = theme.font_footer_height.strip()
-        self.theme.font_footer_italics = str_to_bool(theme.font_footer_italics)
-        self.theme.font_footer_name = theme.font_footer_name.strip()
-        #self.theme.font_footer_override
-        self.theme.font_footer_proportion = \
-            theme.font_footer_proportion.strip()
-        self.theme.font_footer_weight = theme.font_footer_weight.strip()
-        self.theme.font_footer_width = theme.font_footer_width.strip()
-        self.theme.font_footer_x = theme.font_footer_x.strip()
-        self.theme.font_footer_y = theme.font_footer_y.strip()
-        self.theme.font_main_color = theme.font_main_color.strip()
-        self.theme.font_main_height = theme.font_main_height.strip()
-        self.theme.font_main_italics = str_to_bool(theme.font_main_italics)
-        self.theme.font_main_name = theme.font_main_name.strip()
-        #self.theme.font_main_override
-        self.theme.font_main_proportion = theme.font_main_proportion.strip()
-        self.theme.font_main_weight = theme.font_main_weight.strip()
-        self.theme.font_main_x = theme.font_main_x.strip()
-        self.theme.font_main_y = theme.font_main_y.strip()
-        #self.theme.theme_mode
-        self.theme.theme_name = theme.theme_name.strip()
-        #self.theme.theme_version
-
-    def onImageToolButtonClicked(self):
-        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file')
-        if filename != "":
-            self.ImageLineEdit.setText(filename)
-            self.theme.background_filename = filename
-            self.previewTheme(self.theme)
-    #
-    #Main Font Tab
-    #
-    def onFontMainComboBoxSelected(self):
-        self.theme.font_main_name = self.FontMainComboBox.currentFont().family()
-        self.previewTheme(self.theme)
-
-    def onFontMainWeightComboBoxSelected(self, value):
-        if value  ==0:
-            self.theme.font_main_weight = u'Normal'
-            self.theme.font_main_italics = False
-        elif value  == 1:
-            self.theme.font_main_weight = u'Bold'
-            self.theme.font_main_italics = False
-        elif value  == 2:
-            self.theme.font_main_weight = u'Normal'
-            self.theme.font_main_italics = True
-        else:
-            self.theme.font_main_weight = u'Bold'
-            self.theme.font_main_italics = True
-        self.previewTheme(self.theme)
-
-    def onFontMainColorPushButtonClicked(self):
-        self.theme.font_main_color = QtGui.QColorDialog.getColor(
-            QtGui.QColor(self.theme.font_main_color), self).name()
-
-        self.FontMainColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(self.theme.font_main_color))
-        self.previewTheme(self.theme)
-
-    def onFontMainSizeSpinBoxChanged(self):
-        if self.theme.font_main_proportion != self.FontMainSizeSpinBox.value():
-            self.theme.font_main_proportion = self.FontMainSizeSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontMainDefaultCheckBoxChanged(self, value):
-        if value == 2:  # checked
-            self.theme.font_main_override = False
-        else:
-            self.theme.font_main_override = True
-
-        if int(self.theme.font_main_x) == 0 and \
-            int(self.theme.font_main_y) == 0 and \
-            int(self.theme.font_main_width) == 0 and \
-            int(self.theme.font_main_height) == 0:
-            self.theme.font_main_x = u'10'
-            self.theme.font_main_y = u'10'
-            self.theme.font_main_width = u'1024'
-            self.theme.font_main_height = u'730'
-            self.FontMainXSpinBox.setValue(int(self.theme.font_main_x))
-            self.FontMainYSpinBox.setValue(int(self.theme.font_main_y))
-            self.FontMainWidthSpinBox.setValue(int(self.theme.font_main_width))
-            self.FontMainHeightSpinBox.setValue(int( \
-                self.theme.font_main_height))
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onFontMainXSpinBoxChanged(self):
-        if self.theme.font_main_x != self.FontMainXSpinBox.value():
-            self.theme.font_main_x = self.FontMainXSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontMainYSpinBoxChanged(self):
-        if self.theme.font_main_y != self.FontMainYSpinBox.value():
-            self.theme.font_main_y = self.FontMainYSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontMainWidthSpinBoxChanged(self):
-        if self.theme.font_main_width != self.FontMainWidthSpinBox.value():
-            self.theme.font_main_width = self.FontMainWidthSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontMainHeightSpinBoxChanged(self):
-        if self.theme.font_main_height != self.FontMainHeightSpinBox.value():
-            self.theme.font_main_height = self.FontMainHeightSpinBox.value()
-            self.previewTheme(self.theme)
-    #
-    #Footer Font Tab
-    #
-    def onFontFooterComboBoxSelected(self):
-        self.theme.font_footer_name = \
-            self.FontFooterComboBox.currentFont().family()
-        self.previewTheme(self.theme)
-
-    def onFontFooterWeightComboBoxSelected(self, value):
-        if value  == 0:
-            self.theme.font_footer_weight = u'Normal'
-            self.theme.font_footer_italics = False
-        elif value  == 1:
-            self.theme.font_footer_weight = u'Bold'
-            self.theme.font_footer_italics = False
-        elif value  == 2:
-            self.theme.font_footer_weight = u'Normal'
-            self.theme.font_footer_italics = True
-        else:
-            self.theme.font_footer_weight = u'Bold'
-            self.theme.font_footer_italics = True
-        self.previewTheme(self.theme)
-
-    def onFontFooterColorPushButtonClicked(self):
-        self.theme.font_footer_color = QtGui.QColorDialog.getColor(
-            QtGui.QColor(self.theme.font_footer_color), self).name()
-
-        self.FontFooterColorPushButton.setStyleSheet(
-            'background-color: %s' % unicode(self.theme.font_footer_color))
-        self.previewTheme(self.theme)
-
-    def onFontFooterSizeSpinBoxChanged(self):
-        if self.theme.font_footer_proportion != \
-            self.FontFooterSizeSpinBox.value():
-            self.theme.font_footer_proportion = \
-                self.FontFooterSizeSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontFooterDefaultCheckBoxChanged(self, value):
-        if value == 2:  # checked
-            self.theme.font_footer_override = False
-        else:
-            self.theme.font_footer_override = True
-
-        if int(self.theme.font_footer_x) == 0 and \
-            int(self.theme.font_footer_y) == 0 and \
-            int(self.theme.font_footer_width) == 0 and \
-            int(self.theme.font_footer_height) == 0:
-            self.theme.font_footer_x = u'10'
-            self.theme.font_footer_y = u'730'
-            self.theme.font_footer_width = u'1024'
-            self.theme.font_footer_height = u'38'
-
-            self.FontFooterXSpinBox.setValue(int(self.theme.font_footer_x))
-            self.FontFooterYSpinBox.setValue(int(self.theme.font_footer_y))
-            self.FontFooterWidthSpinBox.setValue(int( \
-                self.theme.font_footer_width))
-            self.FontFooterHeightSpinBox.setValue(int( \
-                self.theme.font_footer_height))
-
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onFontFooterXSpinBoxChanged(self):
-        if self.theme.font_footer_x != self.FontFooterXSpinBox.value():
-            self.theme.font_footer_x = self.FontFooterXSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontFooterYSpinBoxChanged(self):
-        if self.theme.font_footer_y != self.FontFooterYSpinBox.value():
-            self.theme.font_footer_y = self.FontFooterYSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontFooterWidthSpinBoxChanged(self):
-        if self.theme.font_footer_width != self.FontFooterWidthSpinBox.value():
-            self.theme.font_footer_width = self.FontFooterWidthSpinBox.value()
-            self.previewTheme(self.theme)
-
-    def onFontFooterHeightSpinBoxChanged(self):
-        if self.theme.font_footer_height != \
-            self.FontFooterHeightSpinBox.value():
-            self.theme.font_footer_height = self.FontFooterHeightSpinBox.value()
-            self.previewTheme(self.theme)
-    #
-    #Background Tab
-    #
-    def onGradientComboBoxSelected(self, currentIndex):
-        self.setBackground(self.BackgroundTypeComboBox.currentIndex(),
-            currentIndex)
-
-    def onBackgroundComboBoxSelected(self, currentIndex):
-        if currentIndex == 0: # Opaque
-            self.theme.background_mode = u'opaque'
-        else:
-            self.theme.background_mode = u'transparent'
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onBackgroundTypeComboBoxSelected(self, currentIndex):
-        self.setBackground(currentIndex, self.GradientComboBox.currentIndex())
-
-    def setBackground(self, background, gradient):
-        if background == 0: # Solid
-            self.theme.background_type = u'solid'
-            if self.theme.background_color is None :
-                self.theme.background_color = u'#000000'
-        elif background == 1: # Gradient
-            self.theme.background_type = u'gradient'
-            if gradient == 0: # Horizontal
-                self.theme.background_direction = u'horizontal'
-            elif gradient == 1: # vertical
-                self.theme.background_direction = u'vertical'
-            else:
-                self.theme.background_direction = u'circular'
-            if self.theme.background_startColor is None :
-                self.theme.background_startColor = u'#000000'
-            if self.theme.background_endColor is None :
-                self.theme.background_endColor = u'#ff0000'
-        else:
-            self.theme.background_type = u'image'
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onColor1PushButtonClicked(self):
-        if self.theme.background_type == u'solid':
-            self.theme.background_color = QtGui.QColorDialog.getColor(
-                QtGui.QColor(self.theme.background_color), self).name()
-            self.Color1PushButton.setStyleSheet(
-                u'background-color: %s' % unicode(self.theme.background_color))
-        else:
-            self.theme.background_startColor = QtGui.QColorDialog.getColor(
-                QtGui.QColor(self.theme.background_startColor), self).name()
-            self.Color1PushButton.setStyleSheet(
-                u'background-color: %s' % \
-                    unicode(self.theme.background_startColor))
-
-        self.previewTheme(self.theme)
-
-    def onColor2PushButtonClicked(self):
-        self.theme.background_endColor = QtGui.QColorDialog.getColor(
-            QtGui.QColor(self.theme.background_endColor), self).name()
-        self.Color2PushButton.setStyleSheet(
-            u'background-color: %s' % unicode(self.theme.background_endColor))
-
-        self.previewTheme(self.theme)
-    #
-    #Other Tab
-    #
-    def onOutlineCheckBoxChanged(self, value):
-        if value == 2:  # checked
-            self.theme.display_outline = True
-        else:
-            self.theme.display_outline = False
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onOutlineColorPushButtonClicked(self):
-        self.theme.display_outline_color = QtGui.QColorDialog.getColor(
-            QtGui.QColor(self.theme.display_outline_color), self).name()
-        self.OutlineColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(self.theme.display_outline_color))
-        self.previewTheme(self.theme)
-
-    def onShadowCheckBoxChanged(self, value):
-        if value == 2:  # checked
-            self.theme.display_shadow = True
-        else:
-            self.theme.display_shadow = False
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onShadowColorPushButtonClicked(self):
-        self.theme.display_shadow_color = QtGui.QColorDialog.getColor(
-            QtGui.QColor(self.theme.display_shadow_color), self).name()
-        self.ShadowColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(self.theme.display_shadow_color))
-        self.previewTheme(self.theme)
-
-    def onHorizontalComboBoxSelected(self, currentIndex):
-        self.theme.display_horizontalAlign = currentIndex
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-
-    def onVerticalComboBoxSelected(self, currentIndex):
-        self.theme.display_verticalAlign = currentIndex
-        self.stateChanging(self.theme)
-        self.previewTheme(self.theme)
-    #
-    #Local Methods
-    #
-    def baseTheme(self):
-        log.debug(u'base theme created')
-        newtheme = ThemeXML()
-        newtheme.new_document(u'New Theme')
-        newtheme.add_background_solid(unicode(u'#000000'))
-        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
-            unicode(30), u'False')
-        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
-            unicode(12), u'False', u'footer')
-        newtheme.add_display(u'False', unicode(u'#FFFFFF'), u'False',
-            unicode(u'#FFFFFF'),
-            unicode(0), unicode(0), unicode(0))
-
-        return newtheme.extract_xml()
-
-    def paintUi(self, theme):
-        self.stateChanging(theme)
-        self.ThemeNameEdit.setText(self.theme.theme_name)
-        if self.theme.background_mode == u'opaque':
-            self.BackgroundComboBox.setCurrentIndex(0)
-        else:
-            self.BackgroundComboBox.setCurrentIndex(1)
-
-        if theme.background_type == u'solid':
-            self.BackgroundTypeComboBox.setCurrentIndex(0)
-        elif theme.background_type == u'gradient':
-            self.BackgroundTypeComboBox.setCurrentIndex(1)
-        else:
-            self.BackgroundTypeComboBox.setCurrentIndex(2)
-
-        if self.theme.background_direction == u'horizontal':
-            self.GradientComboBox.setCurrentIndex(0)
-        elif self.theme.background_direction == u'vertical':
-            self.GradientComboBox.setCurrentIndex(1)
-        else:
-            self.GradientComboBox.setCurrentIndex(2)
-
-        self.FontMainSizeSpinBox.setValue(int(self.theme.font_main_proportion))
-        if not self.theme.font_main_italics and \
-            self.theme.font_main_weight == u'Normal':
-            self.FontMainWeightComboBox.setCurrentIndex(0)
-        elif not self.theme.font_main_italics and \
-            self.theme.font_main_weight == u'Bold':
-            self.FontMainWeightComboBox.setCurrentIndex(1)
-        elif self.theme.font_main_italics and \
-            self.theme.font_main_weight == u'Normal':
-            self.FontMainWeightComboBox.setCurrentIndex(2)
-        else:
-            self.FontMainWeightComboBox.setCurrentIndex(3)
-
-        self.FontMainXSpinBox.setValue(int(self.theme.font_main_x))
-        self.FontMainYSpinBox.setValue(int(self.theme.font_main_y))
-        self.FontMainWidthSpinBox.setValue(int(self.theme.font_main_width))
-        self.FontMainHeightSpinBox.setValue(int(self.theme.font_main_height))
-        self.FontFooterSizeSpinBox.setValue(
-            int(self.theme.font_footer_proportion))
-        if not self.theme.font_footer_italics and \
-            self.theme.font_footer_weight == u'Normal':
-            self.FontFooterWeightComboBox.setCurrentIndex(0)
-        elif not self.theme.font_footer_italics and \
-            self.theme.font_footer_weight == u'Bold':
-            self.FontFooterWeightComboBox.setCurrentIndex(1)
-        elif self.theme.font_footer_italics and \
-            self.theme.font_footer_weight == u'Normal':
-            self.FontFooterWeightComboBox.setCurrentIndex(2)
-        else:
-            self.FontFooterWeightComboBox.setCurrentIndex(3)
-        self.FontFooterXSpinBox.setValue(int(self.theme.font_footer_x))
-        self.FontFooterYSpinBox.setValue(int(self.theme.font_footer_y))
-        self.FontFooterWidthSpinBox.setValue(int(self.theme.font_footer_width))
-        self.FontFooterHeightSpinBox.setValue(
-            int(self.theme.font_footer_height))
-        self.FontMainColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(theme.font_main_color))
-        self.FontFooterColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(theme.font_footer_color))
-
-        if self.theme.font_main_override == False:
-            self.FontMainDefaultCheckBox.setChecked(True)
-        else:
-            self.FontMainDefaultCheckBox.setChecked(False)
-
-        if self.theme.font_footer_override == False:
-            self.FontFooterDefaultCheckBox.setChecked(True)
-        else:
-            self.FontFooterDefaultCheckBox.setChecked(False)
-
-        self.OutlineColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(theme.display_outline_color))
-        self.ShadowColorPushButton.setStyleSheet(
-            u'background-color: %s' % unicode(theme.display_shadow_color))
-
-        if self.theme.display_outline:
-            self.OutlineCheckBox.setChecked(True)
-            self.OutlineColorPushButton.setEnabled(True)
-        else:
-            self.OutlineCheckBox.setChecked(False)
-            self.OutlineColorPushButton.setEnabled(False)
-
-        if self.theme.display_shadow:
-            self.ShadowCheckBox.setChecked(True)
-            self.ShadowColorPushButton.setEnabled(True)
-        else:
-            self.ShadowCheckBox.setChecked(False)
-            self.ShadowColorPushButton.setEnabled(False)
-
-        self.HorizontalComboBox.setCurrentIndex(
-            int(self.theme.display_horizontalAlign))
-        self.VerticalComboBox.setCurrentIndex(
-            int(self.theme.display_verticalAlign))
-
-    def stateChanging(self, theme):
-        if theme.background_mode == u'transparent':
-                self.Color1Label.setVisible(False)
-                self.Color1PushButton.setVisible(False)
-                self.Color2Label.setVisible(False)
-                self.Color2PushButton.setVisible(False)
-                self.ImageLabel.setVisible(False)
-                self.ImageLineEdit.setVisible(False)
-                self.ImageFilenameWidget.setVisible(False)
-                self.GradientLabel.setVisible(False)
-                self.GradientComboBox.setVisible(False)
-                self.BackgroundTypeComboBox.setVisible(False)
-                self.BackgroundTypeLabel.setVisible(False)
-        else:
-            self.BackgroundTypeComboBox.setVisible(True)
-            self.BackgroundTypeLabel.setVisible(True)
-            if theme.background_type == u'solid':
-                self.Color1PushButton.setStyleSheet(
-                    u'background-color: %s' % unicode(theme.background_color))
-                self.Color1Label.setText(translate(u'ThemeManager',
-                    u'Background Color:'))
-                self.Color1Label.setVisible(True)
-                self.Color1PushButton.setVisible(True)
-                self.Color2Label.setVisible(False)
-                self.Color2PushButton.setVisible(False)
-                self.ImageLabel.setVisible(False)
-                self.ImageLineEdit.setVisible(False)
-                self.ImageFilenameWidget.setVisible(False)
-                self.GradientLabel.setVisible(False)
-                self.GradientComboBox.setVisible(False)
-            elif theme.background_type == u'gradient':
-                self.Color1PushButton.setStyleSheet(u'background-color: %s' \
-                    % unicode(theme.background_startColor))
-                self.Color2PushButton.setStyleSheet(u'background-color: %s' \
-                    % unicode(theme.background_endColor))
-                self.Color1Label.setText(translate(u'ThemeManager',
-                    u'First  Color:'))
-                self.Color2Label.setText(translate(u'ThemeManager',
-                    u'Second Color:'))
-                self.Color1Label.setVisible(True)
-                self.Color1PushButton.setVisible(True)
-                self.Color2Label.setVisible(True)
-                self.Color2PushButton.setVisible(True)
-                self.ImageLabel.setVisible(False)
-                self.ImageLineEdit.setVisible(False)
-                self.ImageFilenameWidget.setVisible(False)
-                self.GradientLabel.setVisible(True)
-                self.GradientComboBox.setVisible(True)
-            else: # must be image
-                self.Color1Label.setVisible(False)
-                self.Color1PushButton.setVisible(False)
-                self.Color2Label.setVisible(False)
-                self.Color2PushButton.setVisible(False)
-                self.ImageLabel.setVisible(True)
-                self.ImageLineEdit.setVisible(True)
-                self.ImageFilenameWidget.setVisible(True)
-                self.GradientLabel.setVisible(False)
-                self.GradientComboBox.setVisible(False)
-
-        if theme.font_main_override == False:
-            self.FontMainXSpinBox.setEnabled(False)
-            self.FontMainYSpinBox.setEnabled(False)
-            self.FontMainWidthSpinBox.setEnabled(False)
-            self.FontMainHeightSpinBox.setEnabled(False)
-        else:
-            self.FontMainXSpinBox.setEnabled(True)
-            self.FontMainYSpinBox.setEnabled(True)
-            self.FontMainWidthSpinBox.setEnabled(True)
-            self.FontMainHeightSpinBox.setEnabled(True)
-
-        if theme.font_footer_override == False:
-            self.FontFooterXSpinBox.setEnabled(False)
-            self.FontFooterYSpinBox.setEnabled(False)
-            self.FontFooterWidthSpinBox.setEnabled(False)
-            self.FontFooterHeightSpinBox.setEnabled(False)
-        else:
-            self.FontFooterXSpinBox.setEnabled(True)
-            self.FontFooterYSpinBox.setEnabled(True)
-            self.FontFooterWidthSpinBox.setEnabled(True)
-            self.FontFooterHeightSpinBox.setEnabled(True)
-
-        if self.theme.display_outline:
-            self.OutlineColorPushButton.setEnabled(True)
-        else:
-            self.OutlineColorPushButton.setEnabled(False)
-
-        if self.theme.display_shadow:
-            self.ShadowColorPushButton.setEnabled(True)
-        else:
-            self.ShadowColorPushButton.setEnabled(False)
-
-    def previewTheme(self, theme):
-        if self.allowPreview:
-            frame = self.thememanager.generateImage(theme)
-            self.ThemePreview.setPixmap(QtGui.QPixmap.fromImage(frame))
+# -*- coding: utf-8 -*-
+# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
+
+###############################################################################
+# OpenLP - Open Source Lyrics Projection                                      #
+# --------------------------------------------------------------------------- #
+# Copyright (c) 2008-2009 Raoul Snyman                                        #
+# Portions copyright (c) 2008-2009 Martin Thompson, Tim Bentley, Carsten      #
+# Tinggaard, Jon Tibble, Jonathan Corwin, Maikel Stuivenberg, Scott Guerrieri #
+# --------------------------------------------------------------------------- #
+# 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 logging
+import os, os.path
+
+from PyQt4 import QtCore, QtGui
+from openlp.core.lib import ThemeXML, Renderer, file_to_xml, str_to_bool, \
+    translate
+
+from amendthemedialog import Ui_AmendThemeDialog
+
+log = logging.getLogger(u'AmendThemeForm')
+
+class AmendThemeForm(QtGui.QDialog,  Ui_AmendThemeDialog):
+
+    def __init__(self, thememanager, parent=None):
+        QtGui.QDialog.__init__(self, parent)
+        self.thememanager = thememanager
+        self.path = None
+        self.theme = ThemeXML()
+        self.setupUi(self)
+        #define signals
+        #Buttons
+        QtCore.QObject.connect(self.Color1PushButton ,
+            QtCore.SIGNAL(u'pressed()'), self.onColor1PushButtonClicked)
+        QtCore.QObject.connect(self.Color2PushButton ,
+            QtCore.SIGNAL(u'pressed()'), self.onColor2PushButtonClicked)
+        QtCore.QObject.connect(self.FontMainColorPushButton,
+            QtCore.SIGNAL(u'pressed()'), self.onFontMainColorPushButtonClicked)
+        QtCore.QObject.connect(self.FontFooterColorPushButton,
+            QtCore.SIGNAL(u'pressed()'),
+            self.onFontFooterColorPushButtonClicked)
+        QtCore.QObject.connect(self.OutlineColorPushButton,
+            QtCore.SIGNAL(u'pressed()'), self.onOutlineColorPushButtonClicked)
+        QtCore.QObject.connect(self.ShadowColorPushButton,
+            QtCore.SIGNAL(u'pressed()'), self.onShadowColorPushButtonClicked)
+        QtCore.QObject.connect(self.ImageToolButton,
+            QtCore.SIGNAL(u'pressed()'), self.onImageToolButtonClicked)
+        #Combo boxes
+        QtCore.QObject.connect(self.BackgroundComboBox,
+            QtCore.SIGNAL(u'activated(int)'), self.onBackgroundComboBoxSelected)
+        QtCore.QObject.connect(self.BackgroundTypeComboBox,
+            QtCore.SIGNAL(u'activated(int)'),
+            self.onBackgroundTypeComboBoxSelected)
+        QtCore.QObject.connect(self.GradientComboBox,
+            QtCore.SIGNAL(u'activated(int)'), self.onGradientComboBoxSelected)
+        QtCore.QObject.connect(self.FontMainComboBox,
+            QtCore.SIGNAL(u'activated(int)'), self.onFontMainComboBoxSelected)
+        QtCore.QObject.connect(self.FontMainWeightComboBox,
+            QtCore.SIGNAL(u'activated(int)'),
+            self.onFontMainWeightComboBoxSelected)
+        QtCore.QObject.connect(self.FontFooterComboBox,
+            QtCore.SIGNAL(u'activated(int)'), self.onFontFooterComboBoxSelected)
+        QtCore.QObject.connect(self.FontFooterWeightComboBox,
+            QtCore.SIGNAL(u'activated(int)'),
+            self.onFontFooterWeightComboBoxSelected)
+        QtCore.QObject.connect(self.HorizontalComboBox,
+            QtCore.SIGNAL(u'activated(int)'), self.onHorizontalComboBoxSelected)
+        QtCore.QObject.connect(self.VerticalComboBox,
+            QtCore.SIGNAL(u'activated(int)'), self.onVerticalComboBoxSelected)
+        #Spin boxes
+        QtCore.QObject.connect(self.FontMainSizeSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontMainSizeSpinBoxChanged)
+        QtCore.QObject.connect(self.FontFooterSizeSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontFooterSizeSpinBoxChanged)
+        QtCore.QObject.connect(self.FontMainDefaultCheckBox,
+            QtCore.SIGNAL(u'stateChanged(int)'),
+            self.onFontMainDefaultCheckBoxChanged)
+        QtCore.QObject.connect(self.FontMainXSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'), self.onFontMainXSpinBoxChanged)
+        QtCore.QObject.connect(self.FontMainYSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'), self.onFontMainYSpinBoxChanged)
+        QtCore.QObject.connect(self.FontMainWidthSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontMainWidthSpinBoxChanged)
+        QtCore.QObject.connect(self.FontMainHeightSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontMainHeightSpinBoxChanged)
+        QtCore.QObject.connect(self.FontFooterDefaultCheckBox,
+            QtCore.SIGNAL(u'stateChanged(int)'),
+            self.onFontFooterDefaultCheckBoxChanged)
+        QtCore.QObject.connect(self.FontFooterXSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontFooterXSpinBoxChanged)
+        QtCore.QObject.connect(self.FontFooterYSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontFooterYSpinBoxChanged)
+        QtCore.QObject.connect(self.FontFooterWidthSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontFooterWidthSpinBoxChanged)
+        QtCore.QObject.connect(self.FontFooterHeightSpinBox,
+            QtCore.SIGNAL(u'editingFinished()'),
+            self.onFontFooterHeightSpinBoxChanged)
+        QtCore.QObject.connect(self.OutlineCheckBox,
+            QtCore.SIGNAL(u'stateChanged(int)'), self.onOutlineCheckBoxChanged)
+        QtCore.QObject.connect(self.ShadowCheckBox,
+            QtCore.SIGNAL(u'stateChanged(int)'), self.onShadowCheckBoxChanged)
+
+    def accept(self):
+        new_theme = ThemeXML()
+        theme_name = unicode(self.ThemeNameEdit.displayText())
+        new_theme.new_document(theme_name)
+        save_from = None
+        save_to = None
+        if self.theme.background_mode == u'transparent':
+            new_theme.add_background_transparent()
+        else:
+            if self.theme.background_type == u'solid':
+                new_theme.add_background_solid( \
+                    unicode(self.theme.background_color))
+            elif self.theme.background_type == u'gradient':
+                new_theme.add_background_gradient( \
+                    unicode(self.theme.background_startColor),
+                    unicode(self.theme.background_endColor),
+                    self.theme.background_direction)
+            else:
+                (path, filename) = \
+                    os.path.split(unicode(self.theme.background_filename))
+                new_theme.add_background_image(filename)
+                save_to= os.path.join(self.path, theme_name, filename )
+                save_from = self.theme.background_filename
+
+        new_theme.add_font(unicode(self.theme.font_main_name),
+                unicode(self.theme.font_main_color),
+                unicode(self.theme.font_main_proportion),
+                unicode(self.theme.font_main_override), u'main',
+                unicode(self.theme.font_main_weight),
+                unicode(self.theme.font_main_italics),
+                unicode(self.theme.font_main_x),
+                unicode(self.theme.font_main_y),
+                unicode(self.theme.font_main_width),
+                unicode(self.theme.font_main_height))
+        new_theme.add_font(unicode(self.theme.font_footer_name),
+                unicode(self.theme.font_footer_color),
+                unicode(self.theme.font_footer_proportion),
+                unicode(self.theme.font_footer_override), u'footer',
+                unicode(self.theme.font_footer_weight),
+                unicode(self.theme.font_footer_italics),
+                unicode(self.theme.font_footer_x),
+                unicode(self.theme.font_footer_y),
+                unicode(self.theme.font_footer_width),
+                unicode(self.theme.font_footer_height) )
+        new_theme.add_display(unicode(self.theme.display_shadow),
+                unicode(self.theme.display_shadow_color),
+                unicode(self.theme.display_outline),
+                unicode(self.theme.display_outline_color),
+                unicode(self.theme.display_horizontalAlign),
+                unicode(self.theme.display_verticalAlign),
+                unicode(self.theme.display_wrapStyle))
+        theme = new_theme.extract_xml()
+        pretty_theme = new_theme.extract_formatted_xml()
+        if self.thememanager.saveTheme(theme_name, theme, pretty_theme,
+            save_from, save_to) is not False:
+            return QtGui.QDialog.accept(self)
+
+    def loadTheme(self, theme):
+        log.debug(u'LoadTheme %s', theme)
+        if theme == None:
+            self.theme.parse(self.baseTheme())
+        else:
+            xml_file = os.path.join(self.path, theme, theme + u'.xml')
+            xml = file_to_xml(xml_file)
+            self.theme.parse(xml)
+            self.theme.extend_image_filename(self.path)
+        self.cleanTheme(self.theme)
+        self.allowPreview = False
+        self.paintUi(self.theme)
+        self.allowPreview = True
+        self.previewTheme(self.theme)
+
+    def cleanTheme(self, theme):
+        self.theme.background_color = theme.background_color.strip()
+        self.theme.background_direction = theme.background_direction.strip()
+        self.theme.background_endColor = theme.background_endColor.strip()
+        if theme.background_filename:
+            self.theme.background_filename = theme.background_filename.strip()
+        #self.theme.background_mode
+        self.theme.background_startColor = theme.background_startColor.strip()
+        #self.theme.background_type
+        self.theme.display_display = theme.display_display.strip()
+        self.theme.display_horizontalAlign = \
+            theme.display_horizontalAlign.strip()
+        self.theme.display_outline = str_to_bool(theme.display_outline)
+        #self.theme.display_outline_color
+        self.theme.display_shadow = str_to_bool(theme.display_shadow)
+        #self.theme.display_shadow_color
+        self.theme.display_verticalAlign = \
+            theme.display_verticalAlign.strip()
+        self.theme.display_wrapStyle = theme.display_wrapStyle.strip()
+        self.theme.font_footer_color = theme.font_footer_color.strip()
+        self.theme.font_footer_height = theme.font_footer_height.strip()
+        self.theme.font_footer_italics = str_to_bool(theme.font_footer_italics)
+        self.theme.font_footer_name = theme.font_footer_name.strip()
+        #self.theme.font_footer_override
+        self.theme.font_footer_proportion = \
+            theme.font_footer_proportion.strip()
+        self.theme.font_footer_weight = theme.font_footer_weight.strip()
+        self.theme.font_footer_width = theme.font_footer_width.strip()
+        self.theme.font_footer_x = theme.font_footer_x.strip()
+        self.theme.font_footer_y = theme.font_footer_y.strip()
+        self.theme.font_main_color = theme.font_main_color.strip()
+        self.theme.font_main_height = theme.font_main_height.strip()
+        self.theme.font_main_italics = str_to_bool(theme.font_main_italics)
+        self.theme.font_main_name = theme.font_main_name.strip()
+        #self.theme.font_main_override
+        self.theme.font_main_proportion = theme.font_main_proportion.strip()
+        self.theme.font_main_weight = theme.font_main_weight.strip()
+        self.theme.font_main_x = theme.font_main_x.strip()
+        self.theme.font_main_y = theme.font_main_y.strip()
+        #self.theme.theme_mode
+        self.theme.theme_name = theme.theme_name.strip()
+        #self.theme.theme_version
+
+    def onImageToolButtonClicked(self):
+        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file')
+        if filename != "":
+            self.ImageLineEdit.setText(filename)
+            self.theme.background_filename = filename
+            self.previewTheme(self.theme)
+    #
+    #Main Font Tab
+    #
+    def onFontMainComboBoxSelected(self):
+        self.theme.font_main_name = self.FontMainComboBox.currentFont().family()
+        self.previewTheme(self.theme)
+
+    def onFontMainWeightComboBoxSelected(self, value):
+        if value  ==0:
+            self.theme.font_main_weight = u'Normal'
+            self.theme.font_main_italics = False
+        elif value  == 1:
+            self.theme.font_main_weight = u'Bold'
+            self.theme.font_main_italics = False
+        elif value  == 2:
+            self.theme.font_main_weight = u'Normal'
+            self.theme.font_main_italics = True
+        else:
+            self.theme.font_main_weight = u'Bold'
+            self.theme.font_main_italics = True
+        self.previewTheme(self.theme)
+
+    def onFontMainColorPushButtonClicked(self):
+        self.theme.font_main_color = QtGui.QColorDialog.getColor(
+            QtGui.QColor(self.theme.font_main_color), self).name()
+
+        self.FontMainColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(self.theme.font_main_color))
+        self.previewTheme(self.theme)
+
+    def onFontMainSizeSpinBoxChanged(self):
+        if self.theme.font_main_proportion != self.FontMainSizeSpinBox.value():
+            self.theme.font_main_proportion = self.FontMainSizeSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontMainDefaultCheckBoxChanged(self, value):
+        if value == 2:  # checked
+            self.theme.font_main_override = False
+        else:
+            self.theme.font_main_override = True
+
+        if int(self.theme.font_main_x) == 0 and \
+            int(self.theme.font_main_y) == 0 and \
+            int(self.theme.font_main_width) == 0 and \
+            int(self.theme.font_main_height) == 0:
+            self.theme.font_main_x = u'10'
+            self.theme.font_main_y = u'10'
+            self.theme.font_main_width = u'1024'
+            self.theme.font_main_height = u'730'
+            self.FontMainXSpinBox.setValue(int(self.theme.font_main_x))
+            self.FontMainYSpinBox.setValue(int(self.theme.font_main_y))
+            self.FontMainWidthSpinBox.setValue(int(self.theme.font_main_width))
+            self.FontMainHeightSpinBox.setValue(int( \
+                self.theme.font_main_height))
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onFontMainXSpinBoxChanged(self):
+        if self.theme.font_main_x != self.FontMainXSpinBox.value():
+            self.theme.font_main_x = self.FontMainXSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontMainYSpinBoxChanged(self):
+        if self.theme.font_main_y != self.FontMainYSpinBox.value():
+            self.theme.font_main_y = self.FontMainYSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontMainWidthSpinBoxChanged(self):
+        if self.theme.font_main_width != self.FontMainWidthSpinBox.value():
+            self.theme.font_main_width = self.FontMainWidthSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontMainHeightSpinBoxChanged(self):
+        if self.theme.font_main_height != self.FontMainHeightSpinBox.value():
+            self.theme.font_main_height = self.FontMainHeightSpinBox.value()
+            self.previewTheme(self.theme)
+    #
+    #Footer Font Tab
+    #
+    def onFontFooterComboBoxSelected(self):
+        self.theme.font_footer_name = \
+            self.FontFooterComboBox.currentFont().family()
+        self.previewTheme(self.theme)
+
+    def onFontFooterWeightComboBoxSelected(self, value):
+        if value  == 0:
+            self.theme.font_footer_weight = u'Normal'
+            self.theme.font_footer_italics = False
+        elif value  == 1:
+            self.theme.font_footer_weight = u'Bold'
+            self.theme.font_footer_italics = False
+        elif value  == 2:
+            self.theme.font_footer_weight = u'Normal'
+            self.theme.font_footer_italics = True
+        else:
+            self.theme.font_footer_weight = u'Bold'
+            self.theme.font_footer_italics = True
+        self.previewTheme(self.theme)
+
+    def onFontFooterColorPushButtonClicked(self):
+        self.theme.font_footer_color = QtGui.QColorDialog.getColor(
+            QtGui.QColor(self.theme.font_footer_color), self).name()
+
+        self.FontFooterColorPushButton.setStyleSheet(
+            'background-color: %s' % unicode(self.theme.font_footer_color))
+        self.previewTheme(self.theme)
+
+    def onFontFooterSizeSpinBoxChanged(self):
+        if self.theme.font_footer_proportion != \
+            self.FontFooterSizeSpinBox.value():
+            self.theme.font_footer_proportion = \
+                self.FontFooterSizeSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontFooterDefaultCheckBoxChanged(self, value):
+        if value == 2:  # checked
+            self.theme.font_footer_override = False
+        else:
+            self.theme.font_footer_override = True
+
+        if int(self.theme.font_footer_x) == 0 and \
+            int(self.theme.font_footer_y) == 0 and \
+            int(self.theme.font_footer_width) == 0 and \
+            int(self.theme.font_footer_height) == 0:
+            self.theme.font_footer_x = u'10'
+            self.theme.font_footer_y = u'730'
+            self.theme.font_footer_width = u'1024'
+            self.theme.font_footer_height = u'38'
+
+            self.FontFooterXSpinBox.setValue(int(self.theme.font_footer_x))
+            self.FontFooterYSpinBox.setValue(int(self.theme.font_footer_y))
+            self.FontFooterWidthSpinBox.setValue(int( \
+                self.theme.font_footer_width))
+            self.FontFooterHeightSpinBox.setValue(int( \
+                self.theme.font_footer_height))
+
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onFontFooterXSpinBoxChanged(self):
+        if self.theme.font_footer_x != self.FontFooterXSpinBox.value():
+            self.theme.font_footer_x = self.FontFooterXSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontFooterYSpinBoxChanged(self):
+        if self.theme.font_footer_y != self.FontFooterYSpinBox.value():
+            self.theme.font_footer_y = self.FontFooterYSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontFooterWidthSpinBoxChanged(self):
+        if self.theme.font_footer_width != self.FontFooterWidthSpinBox.value():
+            self.theme.font_footer_width = self.FontFooterWidthSpinBox.value()
+            self.previewTheme(self.theme)
+
+    def onFontFooterHeightSpinBoxChanged(self):
+        if self.theme.font_footer_height != \
+            self.FontFooterHeightSpinBox.value():
+            self.theme.font_footer_height = self.FontFooterHeightSpinBox.value()
+            self.previewTheme(self.theme)
+    #
+    #Background Tab
+    #
+    def onGradientComboBoxSelected(self, currentIndex):
+        self.setBackground(self.BackgroundTypeComboBox.currentIndex(),
+            currentIndex)
+
+    def onBackgroundComboBoxSelected(self, currentIndex):
+        if currentIndex == 0: # Opaque
+            self.theme.background_mode = u'opaque'
+        else:
+            self.theme.background_mode = u'transparent'
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onBackgroundTypeComboBoxSelected(self, currentIndex):
+        self.setBackground(currentIndex, self.GradientComboBox.currentIndex())
+
+    def setBackground(self, background, gradient):
+        if background == 0: # Solid
+            self.theme.background_type = u'solid'
+            if self.theme.background_color is None :
+                self.theme.background_color = u'#000000'
+        elif background == 1: # Gradient
+            self.theme.background_type = u'gradient'
+            if gradient == 0: # Horizontal
+                self.theme.background_direction = u'horizontal'
+            elif gradient == 1: # vertical
+                self.theme.background_direction = u'vertical'
+            else:
+                self.theme.background_direction = u'circular'
+            if self.theme.background_startColor is None :
+                self.theme.background_startColor = u'#000000'
+            if self.theme.background_endColor is None :
+                self.theme.background_endColor = u'#ff0000'
+        else:
+            self.theme.background_type = u'image'
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onColor1PushButtonClicked(self):
+        if self.theme.background_type == u'solid':
+            self.theme.background_color = QtGui.QColorDialog.getColor(
+                QtGui.QColor(self.theme.background_color), self).name()
+            self.Color1PushButton.setStyleSheet(
+                u'background-color: %s' % unicode(self.theme.background_color))
+        else:
+            self.theme.background_startColor = QtGui.QColorDialog.getColor(
+                QtGui.QColor(self.theme.background_startColor), self).name()
+            self.Color1PushButton.setStyleSheet(
+                u'background-color: %s' % \
+                    unicode(self.theme.background_startColor))
+
+        self.previewTheme(self.theme)
+
+    def onColor2PushButtonClicked(self):
+        self.theme.background_endColor = QtGui.QColorDialog.getColor(
+            QtGui.QColor(self.theme.background_endColor), self).name()
+        self.Color2PushButton.setStyleSheet(
+            u'background-color: %s' % unicode(self.theme.background_endColor))
+
+        self.previewTheme(self.theme)
+    #
+    #Other Tab
+    #
+    def onOutlineCheckBoxChanged(self, value):
+        if value == 2:  # checked
+            self.theme.display_outline = True
+        else:
+            self.theme.display_outline = False
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onOutlineColorPushButtonClicked(self):
+        self.theme.display_outline_color = QtGui.QColorDialog.getColor(
+            QtGui.QColor(self.theme.display_outline_color), self).name()
+        self.OutlineColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(self.theme.display_outline_color))
+        self.previewTheme(self.theme)
+
+    def onShadowCheckBoxChanged(self, value):
+        if value == 2:  # checked
+            self.theme.display_shadow = True
+        else:
+            self.theme.display_shadow = False
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onShadowColorPushButtonClicked(self):
+        self.theme.display_shadow_color = QtGui.QColorDialog.getColor(
+            QtGui.QColor(self.theme.display_shadow_color), self).name()
+        self.ShadowColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(self.theme.display_shadow_color))
+        self.previewTheme(self.theme)
+
+    def onHorizontalComboBoxSelected(self, currentIndex):
+        self.theme.display_horizontalAlign = currentIndex
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+
+    def onVerticalComboBoxSelected(self, currentIndex):
+        self.theme.display_verticalAlign = currentIndex
+        self.stateChanging(self.theme)
+        self.previewTheme(self.theme)
+    #
+    #Local Methods
+    #
+    def baseTheme(self):
+        log.debug(u'base theme created')
+        newtheme = ThemeXML()
+        newtheme.new_document(u'New Theme')
+        newtheme.add_background_solid(unicode(u'#000000'))
+        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
+            unicode(30), u'False')
+        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
+            unicode(12), u'False', u'footer')
+        newtheme.add_display(u'False', unicode(u'#FFFFFF'), u'False',
+            unicode(u'#FFFFFF'),
+            unicode(0), unicode(0), unicode(0))
+
+        return newtheme.extract_xml()
+
+    def paintUi(self, theme):
+        self.stateChanging(theme)
+        self.ThemeNameEdit.setText(self.theme.theme_name)
+        if self.theme.background_mode == u'opaque':
+            self.BackgroundComboBox.setCurrentIndex(0)
+        else:
+            self.BackgroundComboBox.setCurrentIndex(1)
+
+        if theme.background_type == u'solid':
+            self.BackgroundTypeComboBox.setCurrentIndex(0)
+        elif theme.background_type == u'gradient':
+            self.BackgroundTypeComboBox.setCurrentIndex(1)
+        else:
+            self.BackgroundTypeComboBox.setCurrentIndex(2)
+
+        if self.theme.background_direction == u'horizontal':
+            self.GradientComboBox.setCurrentIndex(0)
+        elif self.theme.background_direction == u'vertical':
+            self.GradientComboBox.setCurrentIndex(1)
+        else:
+            self.GradientComboBox.setCurrentIndex(2)
+
+        self.FontMainSizeSpinBox.setValue(int(self.theme.font_main_proportion))
+        if not self.theme.font_main_italics and \
+            self.theme.font_main_weight == u'Normal':
+            self.FontMainWeightComboBox.setCurrentIndex(0)
+        elif not self.theme.font_main_italics and \
+            self.theme.font_main_weight == u'Bold':
+            self.FontMainWeightComboBox.setCurrentIndex(1)
+        elif self.theme.font_main_italics and \
+            self.theme.font_main_weight == u'Normal':
+            self.FontMainWeightComboBox.setCurrentIndex(2)
+        else:
+            self.FontMainWeightComboBox.setCurrentIndex(3)
+
+        self.FontMainXSpinBox.setValue(int(self.theme.font_main_x))
+        self.FontMainYSpinBox.setValue(int(self.theme.font_main_y))
+        self.FontMainWidthSpinBox.setValue(int(self.theme.font_main_width))
+        self.FontMainHeightSpinBox.setValue(int(self.theme.font_main_height))
+        self.FontFooterSizeSpinBox.setValue(
+            int(self.theme.font_footer_proportion))
+        if not self.theme.font_footer_italics and \
+            self.theme.font_footer_weight == u'Normal':
+            self.FontFooterWeightComboBox.setCurrentIndex(0)
+        elif not self.theme.font_footer_italics and \
+            self.theme.font_footer_weight == u'Bold':
+            self.FontFooterWeightComboBox.setCurrentIndex(1)
+        elif self.theme.font_footer_italics and \
+            self.theme.font_footer_weight == u'Normal':
+            self.FontFooterWeightComboBox.setCurrentIndex(2)
+        else:
+            self.FontFooterWeightComboBox.setCurrentIndex(3)
+        self.FontFooterXSpinBox.setValue(int(self.theme.font_footer_x))
+        self.FontFooterYSpinBox.setValue(int(self.theme.font_footer_y))
+        self.FontFooterWidthSpinBox.setValue(int(self.theme.font_footer_width))
+        self.FontFooterHeightSpinBox.setValue(
+            int(self.theme.font_footer_height))
+        self.FontMainColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(theme.font_main_color))
+        self.FontFooterColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(theme.font_footer_color))
+
+        if self.theme.font_main_override == False:
+            self.FontMainDefaultCheckBox.setChecked(True)
+        else:
+            self.FontMainDefaultCheckBox.setChecked(False)
+
+        if self.theme.font_footer_override == False:
+            self.FontFooterDefaultCheckBox.setChecked(True)
+        else:
+            self.FontFooterDefaultCheckBox.setChecked(False)
+
+        self.OutlineColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(theme.display_outline_color))
+        self.ShadowColorPushButton.setStyleSheet(
+            u'background-color: %s' % unicode(theme.display_shadow_color))
+
+        if self.theme.display_outline:
+            self.OutlineCheckBox.setChecked(True)
+            self.OutlineColorPushButton.setEnabled(True)
+        else:
+            self.OutlineCheckBox.setChecked(False)
+            self.OutlineColorPushButton.setEnabled(False)
+
+        if self.theme.display_shadow:
+            self.ShadowCheckBox.setChecked(True)
+            self.ShadowColorPushButton.setEnabled(True)
+        else:
+            self.ShadowCheckBox.setChecked(False)
+            self.ShadowColorPushButton.setEnabled(False)
+
+        self.HorizontalComboBox.setCurrentIndex(
+            int(self.theme.display_horizontalAlign))
+        self.VerticalComboBox.setCurrentIndex(
+            int(self.theme.display_verticalAlign))
+
+    def stateChanging(self, theme):
+        if theme.background_mode == u'transparent':
+                self.Color1Label.setVisible(False)
+                self.Color1PushButton.setVisible(False)
+                self.Color2Label.setVisible(False)
+                self.Color2PushButton.setVisible(False)
+                self.ImageLabel.setVisible(False)
+                self.ImageLineEdit.setVisible(False)
+                self.ImageFilenameWidget.setVisible(False)
+                self.GradientLabel.setVisible(False)
+                self.GradientComboBox.setVisible(False)
+                self.BackgroundTypeComboBox.setVisible(False)
+                self.BackgroundTypeLabel.setVisible(False)
+        else:
+            self.BackgroundTypeComboBox.setVisible(True)
+            self.BackgroundTypeLabel.setVisible(True)
+            if theme.background_type == u'solid':
+                self.Color1PushButton.setStyleSheet(
+                    u'background-color: %s' % unicode(theme.background_color))
+                self.Color1Label.setText(translate(u'ThemeManager',
+                    u'Background Color:'))
+                self.Color1Label.setVisible(True)
+                self.Color1PushButton.setVisible(True)
+                self.Color2Label.setVisible(False)
+                self.Color2PushButton.setVisible(False)
+                self.ImageLabel.setVisible(False)
+                self.ImageLineEdit.setVisible(False)
+                self.ImageFilenameWidget.setVisible(False)
+                self.GradientLabel.setVisible(False)
+                self.GradientComboBox.setVisible(False)
+            elif theme.background_type == u'gradient':
+                self.Color1PushButton.setStyleSheet(u'background-color: %s' \
+                    % unicode(theme.background_startColor))
+                self.Color2PushButton.setStyleSheet(u'background-color: %s' \
+                    % unicode(theme.background_endColor))
+                self.Color1Label.setText(translate(u'ThemeManager',
+                    u'First  Color:'))
+                self.Color2Label.setText(translate(u'ThemeManager',
+                    u'Second Color:'))
+                self.Color1Label.setVisible(True)
+                self.Color1PushButton.setVisible(True)
+                self.Color2Label.setVisible(True)
+                self.Color2PushButton.setVisible(True)
+                self.ImageLabel.setVisible(False)
+                self.ImageLineEdit.setVisible(False)
+                self.ImageFilenameWidget.setVisible(False)
+                self.GradientLabel.setVisible(True)
+                self.GradientComboBox.setVisible(True)
+            else: # must be image
+                self.Color1Label.setVisible(False)
+                self.Color1PushButton.setVisible(False)
+                self.Color2Label.setVisible(False)
+                self.Color2PushButton.setVisible(False)
+                self.ImageLabel.setVisible(True)
+                self.ImageLineEdit.setVisible(True)
+                self.ImageFilenameWidget.setVisible(True)
+                self.GradientLabel.setVisible(False)
+                self.GradientComboBox.setVisible(False)
+
+        if theme.font_main_override == False:
+            self.FontMainXSpinBox.setEnabled(False)
+            self.FontMainYSpinBox.setEnabled(False)
+            self.FontMainWidthSpinBox.setEnabled(False)
+            self.FontMainHeightSpinBox.setEnabled(False)
+        else:
+            self.FontMainXSpinBox.setEnabled(True)
+            self.FontMainYSpinBox.setEnabled(True)
+            self.FontMainWidthSpinBox.setEnabled(True)
+            self.FontMainHeightSpinBox.setEnabled(True)
+
+        if theme.font_footer_override == False:
+            self.FontFooterXSpinBox.setEnabled(False)
+            self.FontFooterYSpinBox.setEnabled(False)
+            self.FontFooterWidthSpinBox.setEnabled(False)
+            self.FontFooterHeightSpinBox.setEnabled(False)
+        else:
+            self.FontFooterXSpinBox.setEnabled(True)
+            self.FontFooterYSpinBox.setEnabled(True)
+            self.FontFooterWidthSpinBox.setEnabled(True)
+            self.FontFooterHeightSpinBox.setEnabled(True)
+
+        if self.theme.display_outline:
+            self.OutlineColorPushButton.setEnabled(True)
+        else:
+            self.OutlineColorPushButton.setEnabled(False)
+
+        if self.theme.display_shadow:
+            self.ShadowColorPushButton.setEnabled(True)
+        else:
+            self.ShadowColorPushButton.setEnabled(False)
+
+    def previewTheme(self, theme):
+        if self.allowPreview:
+            frame = self.thememanager.generateImage(theme)
+            self.ThemePreview.setPixmap(QtGui.QPixmap.fromImage(frame))

=== modified file 'openlp/core/ui/thememanager.py'
--- openlp/core/ui/thememanager.py	2009-09-12 17:24:16 +0000
+++ openlp/core/ui/thememanager.py	2009-09-12 18:14:09 +0000
@@ -1,460 +1,460 @@
-# -*- coding: utf-8 -*-
-# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
-
-###############################################################################
-# OpenLP - Open Source Lyrics Projection                                      #
-# --------------------------------------------------------------------------- #
-# Copyright (c) 2008-2009 Raoul Snyman                                        #
-# Portions copyright (c) 2008-2009 Martin Thompson, Tim Bentley, Carsten      #
-# Tinggaard, Jon Tibble, Jonathan Corwin, Maikel Stuivenberg, Scott Guerrieri #
-# --------------------------------------------------------------------------- #
-# This program is free software; you can redistribute it and/or modify it     #
-# under the terms of the GNU General Public License as published by the Free  #
-# Software Foundation; version 2 of the License.                              #
-#                                                                             #
-# This program is distributed in the hope that it will be useful, but WITHOUT #
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       #
-# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    #
-# more details.                                                               #
-#                                                                             #
-# You should have received a copy of the GNU General Public License along     #
-# with this program; if not, write to the Free Software Foundation, Inc., 59  #
-# Temple Place, Suite 330, Boston, MA 02111-1307 USA                          #
-###############################################################################
-
-import os
-import sys
-import zipfile
-import shutil
-import logging
-
-from xml.etree.ElementTree import ElementTree, XML
-from PyQt4 import QtCore, QtGui
-
-from openlp.core.ui import AmendThemeForm, ServiceManager
-from openlp.core.theme import Theme
-from openlp.core.lib import PluginConfig,  \
-    OpenLPToolbar, ThemeXML, Renderer, translate, \
-    file_to_xml, buildIcon,  Receiver
-from openlp.core.utils import ConfigHelper
-
-class ThemeManager(QtGui.QWidget):
-    """
-    Manages the orders of Theme.
-    """
-    global log
-    log = logging.getLogger(u'ThemeManager')
-
-    def __init__(self, parent):
-        QtGui.QWidget.__init__(self, parent)
-        self.parent = parent
-        self.Layout = QtGui.QVBoxLayout(self)
-        self.Layout.setSpacing(0)
-        self.Layout.setMargin(0)
-        self.amendThemeForm = AmendThemeForm(self)
-        self.Toolbar = OpenLPToolbar(self)
-        self.Toolbar.addToolbarButton(
-            translate(u'ThemeManager', u'New Theme'), u':/themes/theme_new.png',
-            translate(u'ThemeManager', u'Create a new theme'), self.onAddTheme)
-        self.Toolbar.addToolbarButton(
-            translate(u'ThemeManager', u'Edit Theme'),
-            u':/themes/theme_edit.png',
-            translate(u'ThemeManager', u'Edit a theme'), self.onEditTheme)
-        self.Toolbar.addToolbarButton(
-            translate(u'ThemeManager', u'Delete Theme'),
-            u':/themes/theme_delete.png',
-            translate(u'ThemeManager', u'Delete a theme'), self.onDeleteTheme)
-        self.Toolbar.addSeparator()
-        self.Toolbar.addToolbarButton(
-            translate(u'ThemeManager', u'Import Theme'),
-            u':/themes/theme_import.png',
-            translate(u'ThemeManager', u'Import a theme'), self.onImportTheme)
-        self.Toolbar.addToolbarButton(
-            translate(u'ThemeManager', u'Export Theme'),
-            u':/themes/theme_export.png',
-            translate(u'ThemeManager', u'Export a theme'), self.onExportTheme)
-        self.ThemeWidget = QtGui.QWidgetAction(self.Toolbar)
-        self.Layout.addWidget(self.Toolbar)
-        self.ThemeListWidget = QtGui.QListWidget(self)
-        self.ThemeListWidget.setAlternatingRowColors(True)
-        self.ThemeListWidget.setIconSize(QtCore.QSize(88,50))
-        self.Layout.addWidget(self.ThemeListWidget)
-        #Signals
-        QtCore.QObject.connect(self.ThemeListWidget,
-            QtCore.SIGNAL(u'doubleClicked(QModelIndex)'),
-            self.changeGlobalFromScreen)
-        QtCore.QObject.connect(Receiver.get_receiver(),
-            QtCore.SIGNAL(u'update_global_theme'), self.changeGlobalFromTab)
-        #Variables
-        self.themelist = []
-        self.path = os.path.join(ConfigHelper.get_data_path(), u'themes')
-        self.checkThemesExists(self.path)
-        self.amendThemeForm.path = self.path
-        # Last little bits of setting up
-        self.config = PluginConfig(u'themes')
-        self.servicePath = self.config.get_data_path()
-        self.global_theme = unicode(
-            self.config.get_config(u'theme global theme', u''))
-
-    def changeGlobalFromTab(self, themeName):
-        log.debug(u'changeGlobalFromTab %s', themeName)
-        for count in range (0,  self.ThemeListWidget.count()):
-            #reset the old name
-            item = self.ThemeListWidget.item(count)
-            oldName =  item.text()
-            newName = unicode(item.data(QtCore.Qt.UserRole).toString())
-            if oldName != newName:
-                self.ThemeListWidget.item(count).setText(newName)
-            #Set the new name
-            if themeName  == newName:
-                name = u'%s (%s)' % (newName, translate(u'ThemeManager',
-                    u'default'))
-                self.ThemeListWidget.item(count).setText(name)
-
-    def changeGlobalFromScreen(self, index):
-        log.debug(u'changeGlobalFromScreen %s', index)
-        for count in range (0,  self.ThemeListWidget.count()):
-            item = self.ThemeListWidget.item(count)
-            oldName =  item.text()
-            #reset the old name
-            if oldName != unicode(item.data(QtCore.Qt.UserRole).toString()):
-                self.ThemeListWidget.item(count).setText(
-                    unicode(item.data(QtCore.Qt.UserRole).toString()))
-            #Set the new name
-            if count  == index.row():
-                self.global_theme = unicode(
-                    self.ThemeListWidget.item(count).text())
-                name = u'%s (%s)' % (self.global_theme,
-                    translate(u'ThemeManager', u'default'))
-                self.ThemeListWidget.item(count).setText(name)
-                self.config.set_config(u'theme global theme', self.global_theme)
-                Receiver().send_message(u'update_global_theme',
-                    self.global_theme)
-                self.pushThemes()
-
-    def onAddTheme(self):
-        self.amendThemeForm.theme.parse(self.baseTheme())
-        self.amendThemeForm.loadTheme(None)
-        self.amendThemeForm.exec_()
-
-    def onEditTheme(self):
-        item = self.ThemeListWidget.currentItem()
-        if item is not None:
-            self.amendThemeForm.setTheme(self.getThemeData(
-                item.data(QtCore.Qt.UserRole).toString()))
-            self.amendThemeForm.loadTheme()
-            self.amendThemeForm.exec_()
-
-    def onDeleteTheme(self):
-        self.global_theme = unicode(
-            self.config.get_config(u'theme global theme', u''))
-        item = self.ThemeListWidget.currentItem()
-        if item is not None:
-            theme = unicode(item.text())
-            # should be the same unless default
-            if theme != unicode(item.data(QtCore.Qt.UserRole).toString()):
-                QtGui.QMessageBox.critical(self,
-                    translate(u'ThemeManager', u'Error'),
-                    translate(u'ThemeManager',
-                        u'You are unable to delete the default theme!'),
-                    QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok))
-            else:
-                self.themelist.remove(theme)
-                th = theme +  u'.png'
-                row = self.ThemeListWidget.row(item)
-                self.ThemeListWidget.takeItem(row)
-                try:
-                    os.remove(os.path.join(self.path, th))
-                except:
-                    #if not present do not worry
-                    pass
-                try:
-                    shutil.rmtree(os.path.join(self.path, theme))
-                except:
-                    #if not present do not worry
-                    pass
-                # As we do not reload the themes push out the change
-                # Reaload the list as the internal lists and events need
-                # to be triggered
-                self.pushThemes()
-
-    def onExportTheme(self):
-        pass
-
-    def onImportTheme(self):
-        files = QtGui.QFileDialog.getOpenFileNames(None,
-            translate(u'ThemeManager', u'Select Theme Import File'),
-            self.path, u'Theme (*.*)')
-        log.info(u'New Themes %s', unicode(files))
-        if len(files) > 0:
-            for file in files:
-                self.unzipTheme(file, self.path)
-        self.loadThemes()
-
-    def loadThemes(self):
-        """
-        Loads the theme lists and triggers updates accross
-        the whole system using direct calls or core functions
-        and events for the plugins.
-        The plugins will call back in to get the real list if they want it.
-        """
-        log.debug(u'Load themes from dir')
-        self.themelist = []
-        self.ThemeListWidget.clear()
-        for root, dirs, files in os.walk(self.path):
-            for name in files:
-                if name.endswith(u'.png'):
-                    #check to see file is in theme root directory
-                    theme =  os.path.join(self.path, name)
-                    if os.path.exists(theme):
-                        (path, filename) = os.path.split(unicode(file))
-                        textName = os.path.splitext(name)[0]
-                        if textName == self.global_theme:
-                            name = u'%s (%s)' % (textName,
-                                translate(u'ThemeManager', u'default'))
-                        else:
-                            name = textName
-                        item_name = QtGui.QListWidgetItem(name)
-                        item_name.setIcon(buildIcon(theme))
-                        item_name.setData(QtCore.Qt.UserRole,
-                            QtCore.QVariant(textName))
-                        self.ThemeListWidget.addItem(item_name)
-                        self.themelist.append(textName)
-        self.pushThemes()
-
-    def pushThemes(self):
-        Receiver().send_message(u'update_themes',  self.getThemes() )
-
-    def getThemes(self):
-        return self.themelist
-
-    def getThemeData(self, themename):
-        log.debug(u'getthemedata for theme %s', themename)
-        xml_file = os.path.join(self.path, unicode(themename), unicode(themename) + u'.xml')
-        try:
-            xml = file_to_xml(xml_file)
-        except:
-            newtheme = ThemeXML()
-            newtheme.new_document(u'New Theme')
-            newtheme.add_background_solid(unicode(u'#000000'))
-            newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'), unicode(30), u'False')
-            newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'), unicode(12), u'False', u'footer')
-            newtheme.add_display(u'False', unicode(u'#FFFFFF'), u'False', unicode(u'#FFFFFF'),
-                unicode(0), unicode(0), unicode(0))
-            xml = newtheme.extract_xml()
-        theme = ThemeXML()
-        theme.parse(xml)
-        theme.extend_image_filename(self.path)
-        return theme
-
-    def checkThemesExists(self, dir):
-        log.debug(u'check themes')
-        if os.path.exists(dir) == False:
-            os.mkdir(dir)
-
-    def unzipTheme(self, filename, dir):
-        """
-        Unzip the theme, remove the preview file if stored
-        Generate a new preview fileCheck the XML theme version and upgrade if
-        necessary.
-        """
-        log.debug(u'Unzipping theme %s', filename)
-        zip = zipfile.ZipFile(unicode(filename))
-        filexml = None
-        themename = None
-        for file in zip.namelist():
-            if file.endswith(os.path.sep):
-                theme_dir = os.path.join(dir, file)
-                if os.path.exists(theme_dir) == False:
-                    os.mkdir(os.path.join(dir, file))
-            else:
-                fullpath = os.path.join(dir, file)
-                names = file.split(os.path.sep)
-                if len(names) > 1:
-                    # not preview file
-                    if themename is None:
-                        themename = names[0]
-                    xml_data = zip.read(file)
-                    if os.path.splitext(file)[1].lower() in [u'.xml']:
-                        if self.checkVersion1(xml_data):
-                            # upgrade theme xml
-                            filexml = self.migrateVersion122(filename,
-                                fullpath, xml_data)
-                        else:
-                            filexml = xml_data
-                        outfile = open(fullpath, u'w')
-                        outfile.write(filexml)
-                        outfile.close()
-                    else:
-                        outfile = open(fullpath, u'w')
-                        outfile.write(zip.read(file))
-                        outfile.close()
-        self.generateAndSaveImage(dir, themename, filexml)
-
-    def checkVersion1(self, xmlfile):
-        """
-        Am I a version 1 theme
-        """
-        log.debug(u'checkVersion1 ')
-        theme = xmlfile
-        tree = ElementTree(element=XML(theme)).getroot()
-        if tree.find(u'BackgroundType') is None:
-            return False
-        else:
-            return True
-
-    def migrateVersion122(self, filename, fullpath, xml_data):
-        """
-        Called by convert the xml data from version 1 format
-        to the current format.
-        New fields are defaulted but the new theme is useable
-        """
-        log.debug(u'migrateVersion122 %s %s', filename, fullpath)
-        theme = Theme(xml_data)
-        newtheme = ThemeXML()
-        newtheme.new_document(theme.Name)
-        if theme.BackgroundType == 0:
-            newtheme.add_background_solid(unicode(
-                theme.BackgroundParameter1.name()))
-        elif theme.BackgroundType == 1:
-            direction = u'vertical'
-            if theme.BackgroundParameter3.name() == 1:
-                direction = u'horizontal'
-            newtheme.add_background_gradient(
-                unicode(theme.BackgroundParameter1.name()),
-                unicode(theme.BackgroundParameter2.name()), direction)
-        else:
-            newtheme.add_background_image(unicode(theme.BackgroundParameter1))
-
-        newtheme.add_font(unicode(theme.FontName),
-            unicode(theme.FontColor.name()),
-            unicode(theme.FontProportion * 2), u'False')
-        newtheme.add_font(unicode(theme.FontName),
-            unicode(theme.FontColor.name()),
-            unicode(12), u'False', u'footer')
-        outline = False
-        shadow = False
-        if theme.Shadow == 1:
-            shadow = True
-        if theme.Outline == 1:
-            outline = True
-        newtheme.add_display(unicode(shadow), unicode(theme.ShadowColor.name()),
-            unicode(outline), unicode(theme.OutlineColor.name()),
-            unicode(theme.HorizontalAlign), unicode(theme.VerticalAlign),
-            unicode(theme.WrapStyle))
-        return newtheme.extract_xml()
-
-    def saveTheme(self, name, theme_xml, theme_pretty_xml, image_from,
-        image_to) :
-        """
-        Called by thememaintenance Dialog to save the theme
-        and to trigger the reload of the theme list
-        """
-        log.debug(u'saveTheme %s %s', name, theme_xml)
-        theme_dir = os.path.join(self.path, name)
-        if os.path.exists(theme_dir) == False:
-            os.mkdir(os.path.join(self.path, name))
-        theme_file = os.path.join(theme_dir, name + u'.xml')
-        log.debug(theme_file)
-
-        result = QtGui.QMessageBox.Yes
-        if os.path.exists(theme_file):
-            result = QtGui.QMessageBox.question(
-                self,
-                translate(u'ThemeManager', u'Theme Exists'),
-                translate(u'ThemeManager', u'A theme with this name already exists, would you like to overwrite it?'),
-                (QtGui.QMessageBox.Yes | QtGui.QMessageBox.No),
-                QtGui.QMessageBox.No)
-        if result == QtGui.QMessageBox.Yes:
-            # Save the theme, overwriting the existing theme if necessary.
-            outfile = open(theme_file, u'w')
-            outfile.write(theme_pretty_xml)
-            outfile.close()
-            if image_from is not None and image_from != image_to:
-                shutil.copyfile(image_from, image_to)
-
-            self.generateAndSaveImage(self.path, name, theme_xml)
-            self.loadThemes()
-        else:
-            # Don't close the dialog - allow the user to change the name of
-            # the theme or to cancel the theme dialog completely.
-            return False
-
-    def generateAndSaveImage(self, dir, name, theme_xml):
-        log.debug(u'generateAndSaveImage %s %s %s', dir, name, theme_xml)
-        theme = ThemeXML()
-        theme.parse(theme_xml)
-        theme.extend_image_filename(dir)
-        frame = self.generateImage(theme)
-        samplepathname = os.path.join(self.path, name + u'.png')
-        if os.path.exists(samplepathname):
-            os.unlink(samplepathname)
-        frame.save(samplepathname, u'png')
-        log.debug(u'Theme image written to %s', samplepathname)
-
-    def generateImage(self, themedata):
-        """
-        Call the RenderManager to build a Sample Image
-        """
-        log.debug(u'generateImage %s ', themedata)
-        frame = self.parent.RenderManager.generate_preview(themedata)
-        return frame
-
-    def getPreviewImage(self, theme):
-        log.debug(u'getPreviewImage %s ', theme)
-        image = os.path.join(self.path, theme + u'.png')
-        return image
-
-    def baseTheme(self):
-        log.debug(u'base theme created')
-        newtheme = ThemeXML()
-        newtheme.new_document(u'New Theme')
-        newtheme.add_background_solid(unicode(u'#000000'))
-        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
-            unicode(30), u'False')
-        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
-            unicode(12), u'False', u'footer')
-        newtheme.add_display(u'False', unicode(u'#FFFFFF'), u'False',
-            unicode(u'#FFFFFF'), unicode(0), unicode(0), unicode(0))
-        return newtheme.extract_xml()
-
-    def cleanTheme(self, theme):
-        theme.background_color = theme.background_color.strip()
-        theme.background_direction = theme.background_direction.strip()
-        theme.background_endColor = theme.background_endColor.strip()
-        if theme.background_filename:
-            theme.background_filename = theme.background_filename.strip()
-        #theme.background_mode
-        theme.background_startColor = theme.background_startColor.strip()
-        #theme.background_type
-        if theme.display_display:
-            theme.display_display = theme.display_display.strip()
-        theme.display_horizontalAlign = theme.display_horizontalAlign.strip()
-        theme.display_outline = str_to_bool(theme.display_outline)
-        #theme.display_outline_color
-        theme.display_shadow = str_to_bool(theme.display_shadow)
-        #theme.display_shadow_color
-        theme.display_verticalAlign = theme.display_verticalAlign.strip()
-        theme.display_wrapStyle = theme.display_wrapStyle.strip()
-        theme.font_footer_color = theme.font_footer_color.strip()
-        theme.font_footer_height = theme.font_footer_height.strip()
-        theme.font_footer_italics = str_to_bool(theme.font_footer_italics)
-        theme.font_footer_name = theme.font_footer_name.strip()
-        #theme.font_footer_override
-        theme.font_footer_proportion = theme.font_footer_proportion.strip()
-        theme.font_footer_weight = theme.font_footer_weight.strip()
-        theme.font_footer_width = theme.font_footer_width.strip()
-        theme.font_footer_x = theme.font_footer_x.strip()
-        theme.font_footer_y = theme.font_footer_y.strip()
-        theme.font_main_color = theme.font_main_color.strip()
-        theme.font_main_height = theme.font_main_height.strip()
-        theme.font_main_italics = str_to_bool(theme.font_main_italics)
-        theme.font_main_name = theme.font_main_name.strip()
-        #theme.font_main_override
-        theme.font_main_proportion = theme.font_main_proportion.strip()
-        theme.font_main_weight = theme.font_main_weight.strip()
-        theme.font_main_x = theme.font_main_x.strip()
-        theme.font_main_y = theme.font_main_y.strip()
-        #theme.theme_mode
-        theme.theme_name = theme.theme_name.strip()
-        #theme.theme_version
+# -*- coding: utf-8 -*-
+# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
+
+###############################################################################
+# OpenLP - Open Source Lyrics Projection                                      #
+# --------------------------------------------------------------------------- #
+# Copyright (c) 2008-2009 Raoul Snyman                                        #
+# Portions copyright (c) 2008-2009 Martin Thompson, Tim Bentley, Carsten      #
+# Tinggaard, Jon Tibble, Jonathan Corwin, Maikel Stuivenberg, Scott Guerrieri #
+# --------------------------------------------------------------------------- #
+# This program is free software; you can redistribute it and/or modify it     #
+# under the terms of the GNU General Public License as published by the Free  #
+# Software Foundation; version 2 of the License.                              #
+#                                                                             #
+# This program is distributed in the hope that it will be useful, but WITHOUT #
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       #
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    #
+# more details.                                                               #
+#                                                                             #
+# You should have received a copy of the GNU General Public License along     #
+# with this program; if not, write to the Free Software Foundation, Inc., 59  #
+# Temple Place, Suite 330, Boston, MA 02111-1307 USA                          #
+###############################################################################
+
+import os
+import sys
+import zipfile
+import shutil
+import logging
+
+from xml.etree.ElementTree import ElementTree, XML
+from PyQt4 import QtCore, QtGui
+
+from openlp.core.ui import AmendThemeForm, ServiceManager
+from openlp.core.theme import Theme
+from openlp.core.lib import PluginConfig,  \
+    OpenLPToolbar, ThemeXML, Renderer, translate, \
+    file_to_xml, buildIcon,  Receiver
+from openlp.core.utils import ConfigHelper
+
+class ThemeManager(QtGui.QWidget):
+    """
+    Manages the orders of Theme.
+    """
+    global log
+    log = logging.getLogger(u'ThemeManager')
+
+    def __init__(self, parent):
+        QtGui.QWidget.__init__(self, parent)
+        self.parent = parent
+        self.Layout = QtGui.QVBoxLayout(self)
+        self.Layout.setSpacing(0)
+        self.Layout.setMargin(0)
+        self.amendThemeForm = AmendThemeForm(self)
+        self.Toolbar = OpenLPToolbar(self)
+        self.Toolbar.addToolbarButton(
+            translate(u'ThemeManager', u'New Theme'), u':/themes/theme_new.png',
+            translate(u'ThemeManager', u'Create a new theme'), self.onAddTheme)
+        self.Toolbar.addToolbarButton(
+            translate(u'ThemeManager', u'Edit Theme'),
+            u':/themes/theme_edit.png',
+            translate(u'ThemeManager', u'Edit a theme'), self.onEditTheme)
+        self.Toolbar.addToolbarButton(
+            translate(u'ThemeManager', u'Delete Theme'),
+            u':/themes/theme_delete.png',
+            translate(u'ThemeManager', u'Delete a theme'), self.onDeleteTheme)
+        self.Toolbar.addSeparator()
+        self.Toolbar.addToolbarButton(
+            translate(u'ThemeManager', u'Import Theme'),
+            u':/themes/theme_import.png',
+            translate(u'ThemeManager', u'Import a theme'), self.onImportTheme)
+        self.Toolbar.addToolbarButton(
+            translate(u'ThemeManager', u'Export Theme'),
+            u':/themes/theme_export.png',
+            translate(u'ThemeManager', u'Export a theme'), self.onExportTheme)
+        self.ThemeWidget = QtGui.QWidgetAction(self.Toolbar)
+        self.Layout.addWidget(self.Toolbar)
+        self.ThemeListWidget = QtGui.QListWidget(self)
+        self.ThemeListWidget.setAlternatingRowColors(True)
+        self.ThemeListWidget.setIconSize(QtCore.QSize(88,50))
+        self.Layout.addWidget(self.ThemeListWidget)
+        #Signals
+        QtCore.QObject.connect(self.ThemeListWidget,
+            QtCore.SIGNAL(u'doubleClicked(QModelIndex)'),
+            self.changeGlobalFromScreen)
+        QtCore.QObject.connect(Receiver.get_receiver(),
+            QtCore.SIGNAL(u'update_global_theme'), self.changeGlobalFromTab)
+        #Variables
+        self.themelist = []
+        self.path = os.path.join(ConfigHelper.get_data_path(), u'themes')
+        self.checkThemesExists(self.path)
+        self.amendThemeForm.path = self.path
+        # Last little bits of setting up
+        self.config = PluginConfig(u'themes')
+        self.servicePath = self.config.get_data_path()
+        self.global_theme = unicode(
+            self.config.get_config(u'theme global theme', u''))
+
+    def changeGlobalFromTab(self, themeName):
+        log.debug(u'changeGlobalFromTab %s', themeName)
+        for count in range (0,  self.ThemeListWidget.count()):
+            #reset the old name
+            item = self.ThemeListWidget.item(count)
+            oldName =  item.text()
+            newName = unicode(item.data(QtCore.Qt.UserRole).toString())
+            if oldName != newName:
+                self.ThemeListWidget.item(count).setText(newName)
+            #Set the new name
+            if themeName  == newName:
+                name = u'%s (%s)' % (newName, translate(u'ThemeManager',
+                    u'default'))
+                self.ThemeListWidget.item(count).setText(name)
+
+    def changeGlobalFromScreen(self, index):
+        log.debug(u'changeGlobalFromScreen %s', index)
+        for count in range (0,  self.ThemeListWidget.count()):
+            item = self.ThemeListWidget.item(count)
+            oldName =  item.text()
+            #reset the old name
+            if oldName != unicode(item.data(QtCore.Qt.UserRole).toString()):
+                self.ThemeListWidget.item(count).setText(
+                    unicode(item.data(QtCore.Qt.UserRole).toString()))
+            #Set the new name
+            if count  == index.row():
+                self.global_theme = unicode(
+                    self.ThemeListWidget.item(count).text())
+                name = u'%s (%s)' % (self.global_theme,
+                    translate(u'ThemeManager', u'default'))
+                self.ThemeListWidget.item(count).setText(name)
+                self.config.set_config(u'theme global theme', self.global_theme)
+                Receiver().send_message(u'update_global_theme',
+                    self.global_theme)
+                self.pushThemes()
+
+    def onAddTheme(self):
+        self.amendThemeForm.theme.parse(self.baseTheme())
+        self.amendThemeForm.loadTheme(None)
+        self.amendThemeForm.exec_()
+
+    def onEditTheme(self):
+        item = self.ThemeListWidget.currentItem()
+        if item is not None:
+            self.amendThemeForm.setTheme(self.getThemeData(
+                item.data(QtCore.Qt.UserRole).toString()))
+            self.amendThemeForm.loadTheme()
+            self.amendThemeForm.exec_()
+
+    def onDeleteTheme(self):
+        self.global_theme = unicode(
+            self.config.get_config(u'theme global theme', u''))
+        item = self.ThemeListWidget.currentItem()
+        if item is not None:
+            theme = unicode(item.text())
+            # should be the same unless default
+            if theme != unicode(item.data(QtCore.Qt.UserRole).toString()):
+                QtGui.QMessageBox.critical(self,
+                    translate(u'ThemeManager', u'Error'),
+                    translate(u'ThemeManager',
+                        u'You are unable to delete the default theme!'),
+                    QtGui.QMessageBox.StandardButtons(QtGui.QMessageBox.Ok))
+            else:
+                self.themelist.remove(theme)
+                th = theme +  u'.png'
+                row = self.ThemeListWidget.row(item)
+                self.ThemeListWidget.takeItem(row)
+                try:
+                    os.remove(os.path.join(self.path, th))
+                except:
+                    #if not present do not worry
+                    pass
+                try:
+                    shutil.rmtree(os.path.join(self.path, theme))
+                except:
+                    #if not present do not worry
+                    pass
+                # As we do not reload the themes push out the change
+                # Reaload the list as the internal lists and events need
+                # to be triggered
+                self.pushThemes()
+
+    def onExportTheme(self):
+        pass
+
+    def onImportTheme(self):
+        files = QtGui.QFileDialog.getOpenFileNames(None,
+            translate(u'ThemeManager', u'Select Theme Import File'),
+            self.path, u'Theme (*.*)')
+        log.info(u'New Themes %s', unicode(files))
+        if len(files) > 0:
+            for file in files:
+                self.unzipTheme(file, self.path)
+        self.loadThemes()
+
+    def loadThemes(self):
+        """
+        Loads the theme lists and triggers updates accross
+        the whole system using direct calls or core functions
+        and events for the plugins.
+        The plugins will call back in to get the real list if they want it.
+        """
+        log.debug(u'Load themes from dir')
+        self.themelist = []
+        self.ThemeListWidget.clear()
+        for root, dirs, files in os.walk(self.path):
+            for name in files:
+                if name.endswith(u'.png'):
+                    #check to see file is in theme root directory
+                    theme =  os.path.join(self.path, name)
+                    if os.path.exists(theme):
+                        (path, filename) = os.path.split(unicode(file))
+                        textName = os.path.splitext(name)[0]
+                        if textName == self.global_theme:
+                            name = u'%s (%s)' % (textName,
+                                translate(u'ThemeManager', u'default'))
+                        else:
+                            name = textName
+                        item_name = QtGui.QListWidgetItem(name)
+                        item_name.setIcon(buildIcon(theme))
+                        item_name.setData(QtCore.Qt.UserRole,
+                            QtCore.QVariant(textName))
+                        self.ThemeListWidget.addItem(item_name)
+                        self.themelist.append(textName)
+        self.pushThemes()
+
+    def pushThemes(self):
+        Receiver().send_message(u'update_themes',  self.getThemes() )
+
+    def getThemes(self):
+        return self.themelist
+
+    def getThemeData(self, themename):
+        log.debug(u'getthemedata for theme %s', themename)
+        xml_file = os.path.join(self.path, unicode(themename), unicode(themename) + u'.xml')
+        try:
+            xml = file_to_xml(xml_file)
+        except:
+            newtheme = ThemeXML()
+            newtheme.new_document(u'New Theme')
+            newtheme.add_background_solid(unicode(u'#000000'))
+            newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'), unicode(30), u'False')
+            newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'), unicode(12), u'False', u'footer')
+            newtheme.add_display(u'False', unicode(u'#FFFFFF'), u'False', unicode(u'#FFFFFF'),
+                unicode(0), unicode(0), unicode(0))
+            xml = newtheme.extract_xml()
+        theme = ThemeXML()
+        theme.parse(xml)
+        theme.extend_image_filename(self.path)
+        return theme
+
+    def checkThemesExists(self, dir):
+        log.debug(u'check themes')
+        if os.path.exists(dir) == False:
+            os.mkdir(dir)
+
+    def unzipTheme(self, filename, dir):
+        """
+        Unzip the theme, remove the preview file if stored
+        Generate a new preview fileCheck the XML theme version and upgrade if
+        necessary.
+        """
+        log.debug(u'Unzipping theme %s', filename)
+        zip = zipfile.ZipFile(unicode(filename))
+        filexml = None
+        themename = None
+        for file in zip.namelist():
+            if file.endswith(os.path.sep):
+                theme_dir = os.path.join(dir, file)
+                if os.path.exists(theme_dir) == False:
+                    os.mkdir(os.path.join(dir, file))
+            else:
+                fullpath = os.path.join(dir, file)
+                names = file.split(os.path.sep)
+                if len(names) > 1:
+                    # not preview file
+                    if themename is None:
+                        themename = names[0]
+                    xml_data = zip.read(file)
+                    if os.path.splitext(file)[1].lower() in [u'.xml']:
+                        if self.checkVersion1(xml_data):
+                            # upgrade theme xml
+                            filexml = self.migrateVersion122(filename,
+                                fullpath, xml_data)
+                        else:
+                            filexml = xml_data
+                        outfile = open(fullpath, u'w')
+                        outfile.write(filexml)
+                        outfile.close()
+                    else:
+                        outfile = open(fullpath, u'w')
+                        outfile.write(zip.read(file))
+                        outfile.close()
+        self.generateAndSaveImage(dir, themename, filexml)
+
+    def checkVersion1(self, xmlfile):
+        """
+        Am I a version 1 theme
+        """
+        log.debug(u'checkVersion1 ')
+        theme = xmlfile
+        tree = ElementTree(element=XML(theme)).getroot()
+        if tree.find(u'BackgroundType') is None:
+            return False
+        else:
+            return True
+
+    def migrateVersion122(self, filename, fullpath, xml_data):
+        """
+        Called by convert the xml data from version 1 format
+        to the current format.
+        New fields are defaulted but the new theme is useable
+        """
+        log.debug(u'migrateVersion122 %s %s', filename, fullpath)
+        theme = Theme(xml_data)
+        newtheme = ThemeXML()
+        newtheme.new_document(theme.Name)
+        if theme.BackgroundType == 0:
+            newtheme.add_background_solid(unicode(
+                theme.BackgroundParameter1.name()))
+        elif theme.BackgroundType == 1:
+            direction = u'vertical'
+            if theme.BackgroundParameter3.name() == 1:
+                direction = u'horizontal'
+            newtheme.add_background_gradient(
+                unicode(theme.BackgroundParameter1.name()),
+                unicode(theme.BackgroundParameter2.name()), direction)
+        else:
+            newtheme.add_background_image(unicode(theme.BackgroundParameter1))
+
+        newtheme.add_font(unicode(theme.FontName),
+            unicode(theme.FontColor.name()),
+            unicode(theme.FontProportion * 2), u'False')
+        newtheme.add_font(unicode(theme.FontName),
+            unicode(theme.FontColor.name()),
+            unicode(12), u'False', u'footer')
+        outline = False
+        shadow = False
+        if theme.Shadow == 1:
+            shadow = True
+        if theme.Outline == 1:
+            outline = True
+        newtheme.add_display(unicode(shadow), unicode(theme.ShadowColor.name()),
+            unicode(outline), unicode(theme.OutlineColor.name()),
+            unicode(theme.HorizontalAlign), unicode(theme.VerticalAlign),
+            unicode(theme.WrapStyle))
+        return newtheme.extract_xml()
+
+    def saveTheme(self, name, theme_xml, theme_pretty_xml, image_from,
+        image_to) :
+        """
+        Called by thememaintenance Dialog to save the theme
+        and to trigger the reload of the theme list
+        """
+        log.debug(u'saveTheme %s %s', name, theme_xml)
+        theme_dir = os.path.join(self.path, name)
+        if os.path.exists(theme_dir) == False:
+            os.mkdir(os.path.join(self.path, name))
+        theme_file = os.path.join(theme_dir, name + u'.xml')
+        log.debug(theme_file)
+
+        result = QtGui.QMessageBox.Yes
+        if os.path.exists(theme_file):
+            result = QtGui.QMessageBox.question(
+                self,
+                translate(u'ThemeManager', u'Theme Exists'),
+                translate(u'ThemeManager', u'A theme with this name already exists, would you like to overwrite it?'),
+                (QtGui.QMessageBox.Yes | QtGui.QMessageBox.No),
+                QtGui.QMessageBox.No)
+        if result == QtGui.QMessageBox.Yes:
+            # Save the theme, overwriting the existing theme if necessary.
+            outfile = open(theme_file, u'w')
+            outfile.write(theme_pretty_xml)
+            outfile.close()
+            if image_from is not None and image_from != image_to:
+                shutil.copyfile(image_from, image_to)
+
+            self.generateAndSaveImage(self.path, name, theme_xml)
+            self.loadThemes()
+        else:
+            # Don't close the dialog - allow the user to change the name of
+            # the theme or to cancel the theme dialog completely.
+            return False
+
+    def generateAndSaveImage(self, dir, name, theme_xml):
+        log.debug(u'generateAndSaveImage %s %s %s', dir, name, theme_xml)
+        theme = ThemeXML()
+        theme.parse(theme_xml)
+        theme.extend_image_filename(dir)
+        frame = self.generateImage(theme)
+        samplepathname = os.path.join(self.path, name + u'.png')
+        if os.path.exists(samplepathname):
+            os.unlink(samplepathname)
+        frame.save(samplepathname, u'png')
+        log.debug(u'Theme image written to %s', samplepathname)
+
+    def generateImage(self, themedata):
+        """
+        Call the RenderManager to build a Sample Image
+        """
+        log.debug(u'generateImage %s ', themedata)
+        frame = self.parent.RenderManager.generate_preview(themedata)
+        return frame
+
+    def getPreviewImage(self, theme):
+        log.debug(u'getPreviewImage %s ', theme)
+        image = os.path.join(self.path, theme + u'.png')
+        return image
+
+    def baseTheme(self):
+        log.debug(u'base theme created')
+        newtheme = ThemeXML()
+        newtheme.new_document(u'New Theme')
+        newtheme.add_background_solid(unicode(u'#000000'))
+        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
+            unicode(30), u'False')
+        newtheme.add_font(unicode(QtGui.QFont().family()), unicode(u'#FFFFFF'),
+            unicode(12), u'False', u'footer')
+        newtheme.add_display(u'False', unicode(u'#FFFFFF'), u'False',
+            unicode(u'#FFFFFF'), unicode(0), unicode(0), unicode(0))
+        return newtheme.extract_xml()
+
+    def cleanTheme(self, theme):
+        theme.background_color = theme.background_color.strip()
+        theme.background_direction = theme.background_direction.strip()
+        theme.background_endColor = theme.background_endColor.strip()
+        if theme.background_filename:
+            theme.background_filename = theme.background_filename.strip()
+        #theme.background_mode
+        theme.background_startColor = theme.background_startColor.strip()
+        #theme.background_type
+        if theme.display_display:
+            theme.display_display = theme.display_display.strip()
+        theme.display_horizontalAlign = theme.display_horizontalAlign.strip()
+        theme.display_outline = str_to_bool(theme.display_outline)
+        #theme.display_outline_color
+        theme.display_shadow = str_to_bool(theme.display_shadow)
+        #theme.display_shadow_color
+        theme.display_verticalAlign = theme.display_verticalAlign.strip()
+        theme.display_wrapStyle = theme.display_wrapStyle.strip()
+        theme.font_footer_color = theme.font_footer_color.strip()
+        theme.font_footer_height = theme.font_footer_height.strip()
+        theme.font_footer_italics = str_to_bool(theme.font_footer_italics)
+        theme.font_footer_name = theme.font_footer_name.strip()
+        #theme.font_footer_override
+        theme.font_footer_proportion = theme.font_footer_proportion.strip()
+        theme.font_footer_weight = theme.font_footer_weight.strip()
+        theme.font_footer_width = theme.font_footer_width.strip()
+        theme.font_footer_x = theme.font_footer_x.strip()
+        theme.font_footer_y = theme.font_footer_y.strip()
+        theme.font_main_color = theme.font_main_color.strip()
+        theme.font_main_height = theme.font_main_height.strip()
+        theme.font_main_italics = str_to_bool(theme.font_main_italics)
+        theme.font_main_name = theme.font_main_name.strip()
+        #theme.font_main_override
+        theme.font_main_proportion = theme.font_main_proportion.strip()
+        theme.font_main_weight = theme.font_main_weight.strip()
+        theme.font_main_x = theme.font_main_x.strip()
+        theme.font_main_y = theme.font_main_y.strip()
+        #theme.theme_mode
+        theme.theme_name = theme.theme_name.strip()
+        #theme.theme_version

=== modified file 'openlp/plugins/bibles/test/biblebooks_msg_short.csv'
--- openlp/plugins/bibles/test/biblebooks_msg_short.csv	2008-12-10 19:11:00 +0000
+++ openlp/plugins/bibles/test/biblebooks_msg_short.csv	2009-09-12 18:14:09 +0000
@@ -1,8 +1,8 @@
-1,1,"Genesis","GEN"
-2,1,"Exodus","EXOD"
-3,1,"Leviticus","LEV"
-4,1,"Numbers","NUM"
-47,2,"Matthew","MATT"
-48,2,"Mark","MARK"
-49,2,"Luke","LUKE"
-50,2,"John","JOHN"
+1,1,"Genesis","GEN"
+2,1,"Exodus","EXOD"
+3,1,"Leviticus","LEV"
+4,1,"Numbers","NUM"
+47,2,"Matthew","MATT"
+48,2,"Mark","MARK"
+49,2,"Luke","LUKE"
+50,2,"John","JOHN"

=== modified file 'openlp/plugins/bibles/test/biblebooks_niv_short.csv'
--- openlp/plugins/bibles/test/biblebooks_niv_short.csv	2008-12-10 19:11:00 +0000
+++ openlp/plugins/bibles/test/biblebooks_niv_short.csv	2009-09-12 18:14:09 +0000
@@ -1,9 +1,9 @@
-1,1,"Genesis","GEN"
-2,1,"Exodus","EXOD"
-3,1,"Leviticus","LEV"
-4,1,"Numbers","NUM"
-46,1,"Malachi","MAL"
-47,2,"Matthew","MATT"
-48,2,"Mark","MARK"
-49,2,"Luke","LUKE"
-50,2,"John","JOHN"
+1,1,"Genesis","GEN"
+2,1,"Exodus","EXOD"
+3,1,"Leviticus","LEV"
+4,1,"Numbers","NUM"
+46,1,"Malachi","MAL"
+47,2,"Matthew","MATT"
+48,2,"Mark","MARK"
+49,2,"Luke","LUKE"
+50,2,"John","JOHN"

=== modified file 'openlp/plugins/bibles/test/bibleverses_msg_short.csv'
--- openlp/plugins/bibles/test/bibleverses_msg_short.csv	2008-12-10 19:11:00 +0000
+++ openlp/plugins/bibles/test/bibleverses_msg_short.csv	2009-09-12 18:14:09 +0000
@@ -1,35 +1,35 @@
-"Genesis",1,1,"First this: God created the Heavens and Earth - all you see, all you don't see."
-"Genesis",1,2,"Earth was a soup of nothingness, a bottomless emptiness, an inky blackness. God's Spirit brooded like a bird above the watery abyss."
-"Exodus",1,1,"These are the names of the Israelites who went to Egypt with Jacob, each bringing his family members:"
-"Exodus",1,2,"Reuben, Simeon, Levi, and Judah,"
-"Exodus",2,1,"A man from the family of Levi married a Levite woman."
-"Exodus",2,2,"The woman became pregnant and had a son. She saw there was something special about him and hid him. She hid him for three months."
-"Leviticus",1,1,"God called Moses and spoke to him from the Tent of Meeting:"
-"Leviticus",1,2,"""Speak to the People of Israel. Tell them, When anyone presents an offering to God, present an animal from either the herd or the flock."
-"Leviticus",1,3,"""If the offering is a Whole-Burnt-Offering from the herd, present a male without a defect at the entrance to the Tent of Meeting that it may be accepted by God."
-"Numbers",1,1,"God spoke to Moses in the Wilderness of Sinai at the Tent of Meeting on the first day of the second month in the second year after they had left Egypt. He said,"
-"Numbers",1,2,"""Number the congregation of the People of Israel by clans and families, writing down the names of every male."
-"Matthew",1,1,"The family tree of Jesus Christ, David's son, Abraham's son:"
-"Matthew",1,2,"Abraham had Isaac, Isaac had Jacob, Jacob had Judah and his brothers,"
-"Matthew",1,3,"Judah had Perez and Zerah (the mother was Tamar), Perez had Hezron, Hezron had Aram,"
-"Matthew",1,4,"Aram had Amminadab, Amminadab had Nahshon, Nahshon had Salmon,"
-"Matthew",1,5,"Salmon had Boaz (his mother was Rahab), Boaz had Obed (Ruth was the mother), Obed had Jesse,"
-"Matthew",1,6,"Jesse had David, and David became king. David had Solomon (Uriah's wife was the mother),"
-"Matthew",1,7,"Solomon had Rehoboam, Rehoboam had Abijah, Abijah had Asa,"
-"Matthew",1,8,"Asa had Jehoshaphat, Jehoshaphat had Joram, Joram had Uzziah,"
-"Matthew",2,1,"After Jesus was born in Bethlehem village, Judah territory - this was during Herod's kingship - a band of scholars arrived in Jerusalem from the East."
-"Matthew",2,2,"They asked around, ""Where can we find and pay homage to the newborn King of the Jews? We observed a star in the eastern sky that "Matthew",3,1,"While Jesus was living in the Galilean hills, John, called ""the Baptizer,"" was preaching in the desert country of Judea."
-"Matthew",3,2,"His message was simple and austere, like his desert surroundings: ""Change your life. God's kingdom is here."""
-"Matthew",3,3,"John and his message were authorized by Isaiah's prophecy: Thunder in the desert! Prepare for God's arrival! Make the road smooth and straight!"
-"Mark",1,1,"The good news of Jesus Christ - the Message! - begins here,"
-"Mark",1,2,"following to the letter the scroll of the prophet Isaiah. Watch closely: I'm sending my preacher ahead of you; He'll make the road smooth for you."
-"Mark",1,3,"Thunder in the desert! Prepare for God's arrival! Make the road smooth and straight!"
-"Luke",1,1,"So many others have tried their hand at putting together a story of the wonderful harvest of Scripture and history that took place among us,"
-"Luke",1,2,"using reports handed down by the original eyewitnesses who served this Word with their very lives."
-"Luke",1,3,"Since I have investigated all the reports in close detail, starting from the story's beginning, I decided to write it all out for you, most honorable Theophilus,"
-"John",1,1,"The Word was first, the Word present to God, God present to the Word. The Word was God,"
-"John",1,2,"in readiness for God from day one."
-"John",1,3,"Everything was created through him; nothing - not one thing! - came into being without him."
-"John",2,1,"Three days later there was a wedding in the village of Cana in Galilee. Jesus' mother was there."
-"John",2,2,"Jesus and his disciples were guests also."
-"John",2,3,"When they started running low on wine at the wedding banquet, Jesus' mother told him, ""They're just about out of wine."""
+"Genesis",1,1,"First this: God created the Heavens and Earth - all you see, all you don't see."
+"Genesis",1,2,"Earth was a soup of nothingness, a bottomless emptiness, an inky blackness. God's Spirit brooded like a bird above the watery abyss."
+"Exodus",1,1,"These are the names of the Israelites who went to Egypt with Jacob, each bringing his family members:"
+"Exodus",1,2,"Reuben, Simeon, Levi, and Judah,"
+"Exodus",2,1,"A man from the family of Levi married a Levite woman."
+"Exodus",2,2,"The woman became pregnant and had a son. She saw there was something special about him and hid him. She hid him for three months."
+"Leviticus",1,1,"God called Moses and spoke to him from the Tent of Meeting:"
+"Leviticus",1,2,"""Speak to the People of Israel. Tell them, When anyone presents an offering to God, present an animal from either the herd or the flock."
+"Leviticus",1,3,"""If the offering is a Whole-Burnt-Offering from the herd, present a male without a defect at the entrance to the Tent of Meeting that it may be accepted by God."
+"Numbers",1,1,"God spoke to Moses in the Wilderness of Sinai at the Tent of Meeting on the first day of the second month in the second year after they had left Egypt. He said,"
+"Numbers",1,2,"""Number the congregation of the People of Israel by clans and families, writing down the names of every male."
+"Matthew",1,1,"The family tree of Jesus Christ, David's son, Abraham's son:"
+"Matthew",1,2,"Abraham had Isaac, Isaac had Jacob, Jacob had Judah and his brothers,"
+"Matthew",1,3,"Judah had Perez and Zerah (the mother was Tamar), Perez had Hezron, Hezron had Aram,"
+"Matthew",1,4,"Aram had Amminadab, Amminadab had Nahshon, Nahshon had Salmon,"
+"Matthew",1,5,"Salmon had Boaz (his mother was Rahab), Boaz had Obed (Ruth was the mother), Obed had Jesse,"
+"Matthew",1,6,"Jesse had David, and David became king. David had Solomon (Uriah's wife was the mother),"
+"Matthew",1,7,"Solomon had Rehoboam, Rehoboam had Abijah, Abijah had Asa,"
+"Matthew",1,8,"Asa had Jehoshaphat, Jehoshaphat had Joram, Joram had Uzziah,"
+"Matthew",2,1,"After Jesus was born in Bethlehem village, Judah territory - this was during Herod's kingship - a band of scholars arrived in Jerusalem from the East."
+"Matthew",2,2,"They asked around, ""Where can we find and pay homage to the newborn King of the Jews? We observed a star in the eastern sky that "Matthew",3,1,"While Jesus was living in the Galilean hills, John, called ""the Baptizer,"" was preaching in the desert country of Judea."
+"Matthew",3,2,"His message was simple and austere, like his desert surroundings: ""Change your life. God's kingdom is here."""
+"Matthew",3,3,"John and his message were authorized by Isaiah's prophecy: Thunder in the desert! Prepare for God's arrival! Make the road smooth and straight!"
+"Mark",1,1,"The good news of Jesus Christ - the Message! - begins here,"
+"Mark",1,2,"following to the letter the scroll of the prophet Isaiah. Watch closely: I'm sending my preacher ahead of you; He'll make the road smooth for you."
+"Mark",1,3,"Thunder in the desert! Prepare for God's arrival! Make the road smooth and straight!"
+"Luke",1,1,"So many others have tried their hand at putting together a story of the wonderful harvest of Scripture and history that took place among us,"
+"Luke",1,2,"using reports handed down by the original eyewitnesses who served this Word with their very lives."
+"Luke",1,3,"Since I have investigated all the reports in close detail, starting from the story's beginning, I decided to write it all out for you, most honorable Theophilus,"
+"John",1,1,"The Word was first, the Word present to God, God present to the Word. The Word was God,"
+"John",1,2,"in readiness for God from day one."
+"John",1,3,"Everything was created through him; nothing - not one thing! - came into being without him."
+"John",2,1,"Three days later there was a wedding in the village of Cana in Galilee. Jesus' mother was there."
+"John",2,2,"Jesus and his disciples were guests also."
+"John",2,3,"When they started running low on wine at the wedding banquet, Jesus' mother told him, ""They're just about out of wine."""

=== modified file 'openlp/plugins/presentations/lib/pptviewlib/README.TXT'
--- openlp/plugins/presentations/lib/pptviewlib/README.TXT	2008-12-10 20:40:18 +0000
+++ openlp/plugins/presentations/lib/pptviewlib/README.TXT	2009-09-12 18:14:09 +0000
@@ -1,116 +1,116 @@
-
-PPTVIEWLIB - Control PowerPoint Viewer 2003/2007 (for openlp.org)
-Copyright (C) 2008 Jonathan Corwin (j@xxxxxxxxxxxx)
-            
-This library wrappers the free Microsoft PowerPoint Viewer (2003/2007) program, 
-allowing it to be more easily controlled from another program. 
-
-The PowerPoint Viewer must already be installed on the destination machine, and is 
-freely available at microsoft.com.
-
-The full Microsoft Office PowerPoint and PowerPoint Viewer 97 have a COM interface allowing
-automation. This ability was removed from the 2003+ viewer offerings.
-
-To developers: I am not a C/C++ or Win32 API programmer as you can probably tell. 
-The code and API of this DLL could certainly do with some tidying up, and the
-error trapping, where it exists, is very basic. I'll happily accept patches!
-
-This library is covered by the GPL (http://www.gnu.org/licenses/)
-It is NOT covered by the LGPL, so can only be used in GPL compatable programs.
-(http://www.gnu.org/licenses/why-not-lgpl.html)
-
-This README.TXT must be distributed with the pptviewlib.dll
-
-This library has a limit of 50 PowerPoints which can be opened simultaneously.
-
-USAGE
------
-int OpenPPT(char *filename, HWND hParentWnd, RECT rect, char *previewpath);
-
-	Opens the PowerPoint file, counts the number of slides, sizes and positions accordingly
-	and creates preview images of each slide. Note PowerPoint Viewer only allows the 
-	slideshow to be resized whilst it is being loaded. It can be moved at any time however.
-
-	The only way to count the number of slides is to step through the entire show. Therefore
-	there will be a delay whilst opening large presentations for the first time.
-	For pre XP/2003 systems, the slideshow will flicker as the screen snapshots are taken.
-
-	filename:    The PowerPoint file to be opened. Full path
-	hParentWnd:  The window which will become the parent of the slideshow window. 
-   			     Can be NULL.
-	rect:        The location/dimensions of the slideshow window. 
-			     If all properties of this structure are zero, the dimensions of the hParentWnd
-			     are used. 
-	previewpath  If specified, the prefix to use for snapshot images of each slide, in the 
-			     form: previewpath + n + ".bmp", where n is the slide number.
-			     A file called previewpath + "info.txt" will also be created containing information
-			     about the PPT file, to speed up future openings of the unmodified file.
-			     Note it is up the calling program to directly access these images if they 
-			     are required.
-
-	RETURNS:     An unique identifier to pass to other methods in this library.
-			     If < 0, then the PPT failed to open.
-			     If >=0, ClosePPT must be called when the PPT is no longer being used
-			     or when the calling program is closed to release resources/hooks.
-               
-void ClosePPT(int id);
-	 Closes the presentation, releasing any resources and hooks.
-
-	 id: The value returned from OpenPPT.
-	
-int GetCurrentSlide(int id);
-	Returns the current slide number (from 1)
-
-	id: The value returned from OpenPPT.
-
-int GetSlideCount(int id);
-	Returns the total number of slides.
-
-	id: The value returned from OpenPPT.
-
-void NextStep(int id);
-	Advances one step (animation) through the slideshow.
-
-	id: The value returned from OpenPPT.
-
-void PrevStep(int id);
-	Goes backwards one step (animation) through the slideshow.
-
-	id: The value returned from OpenPPT.
-
-void GotoSlide(int id, int slideno);
-	Goes directly to a specific slide in the slideshow
-
-	id: The value returned from OpenPPT.
-	slideno: The number of the slide (from 1) to go directly to.
-	
-	If the slide has already been displayed, then the completed slide with animations performed
-	will be shown. This is how the PowerPoint Viewer works so have no control over this.
-
-void RestartShow(int id);
-	Restarts the show from the beginning. To reset animations, behind the scenes it 
-	has to travel to the end and step backwards though the entire show. Therefore
-	for large presentations there might be a delay.
-
-	id: The value returned from OpenPPT.
-
-void Blank(int id);
-	Blanks the screen, colour black.
-
-	id: The value returned from OpenPPT.
-
-void Unblank(int id)
-	Unblanks the screen, restoring it to it's pre-blank state.
-	
-	id: The value returned from OpenPPT.
-
-void Stop(int id)
-	Moves the slideshow off the screen. (There is no concept of stop show in the PowerPoint Viewer)
-
-	id: The value returned from OpenPPT.
-
-void Resume(int id)
-	Moves the slideshow display back onto the screen following a Stop()
-
-	id: The value returned from OpenPPT.
-
+
+PPTVIEWLIB - Control PowerPoint Viewer 2003/2007 (for openlp.org)
+Copyright (C) 2008 Jonathan Corwin (j@xxxxxxxxxxxx)
+            
+This library wrappers the free Microsoft PowerPoint Viewer (2003/2007) program, 
+allowing it to be more easily controlled from another program. 
+
+The PowerPoint Viewer must already be installed on the destination machine, and is 
+freely available at microsoft.com.
+
+The full Microsoft Office PowerPoint and PowerPoint Viewer 97 have a COM interface allowing
+automation. This ability was removed from the 2003+ viewer offerings.
+
+To developers: I am not a C/C++ or Win32 API programmer as you can probably tell. 
+The code and API of this DLL could certainly do with some tidying up, and the
+error trapping, where it exists, is very basic. I'll happily accept patches!
+
+This library is covered by the GPL (http://www.gnu.org/licenses/)
+It is NOT covered by the LGPL, so can only be used in GPL compatable programs.
+(http://www.gnu.org/licenses/why-not-lgpl.html)
+
+This README.TXT must be distributed with the pptviewlib.dll
+
+This library has a limit of 50 PowerPoints which can be opened simultaneously.
+
+USAGE
+-----
+int OpenPPT(char *filename, HWND hParentWnd, RECT rect, char *previewpath);
+
+	Opens the PowerPoint file, counts the number of slides, sizes and positions accordingly
+	and creates preview images of each slide. Note PowerPoint Viewer only allows the 
+	slideshow to be resized whilst it is being loaded. It can be moved at any time however.
+
+	The only way to count the number of slides is to step through the entire show. Therefore
+	there will be a delay whilst opening large presentations for the first time.
+	For pre XP/2003 systems, the slideshow will flicker as the screen snapshots are taken.
+
+	filename:    The PowerPoint file to be opened. Full path
+	hParentWnd:  The window which will become the parent of the slideshow window. 
+   			     Can be NULL.
+	rect:        The location/dimensions of the slideshow window. 
+			     If all properties of this structure are zero, the dimensions of the hParentWnd
+			     are used. 
+	previewpath  If specified, the prefix to use for snapshot images of each slide, in the 
+			     form: previewpath + n + ".bmp", where n is the slide number.
+			     A file called previewpath + "info.txt" will also be created containing information
+			     about the PPT file, to speed up future openings of the unmodified file.
+			     Note it is up the calling program to directly access these images if they 
+			     are required.
+
+	RETURNS:     An unique identifier to pass to other methods in this library.
+			     If < 0, then the PPT failed to open.
+			     If >=0, ClosePPT must be called when the PPT is no longer being used
+			     or when the calling program is closed to release resources/hooks.
+               
+void ClosePPT(int id);
+	 Closes the presentation, releasing any resources and hooks.
+
+	 id: The value returned from OpenPPT.
+	
+int GetCurrentSlide(int id);
+	Returns the current slide number (from 1)
+
+	id: The value returned from OpenPPT.
+
+int GetSlideCount(int id);
+	Returns the total number of slides.
+
+	id: The value returned from OpenPPT.
+
+void NextStep(int id);
+	Advances one step (animation) through the slideshow.
+
+	id: The value returned from OpenPPT.
+
+void PrevStep(int id);
+	Goes backwards one step (animation) through the slideshow.
+
+	id: The value returned from OpenPPT.
+
+void GotoSlide(int id, int slideno);
+	Goes directly to a specific slide in the slideshow
+
+	id: The value returned from OpenPPT.
+	slideno: The number of the slide (from 1) to go directly to.
+	
+	If the slide has already been displayed, then the completed slide with animations performed
+	will be shown. This is how the PowerPoint Viewer works so have no control over this.
+
+void RestartShow(int id);
+	Restarts the show from the beginning. To reset animations, behind the scenes it 
+	has to travel to the end and step backwards though the entire show. Therefore
+	for large presentations there might be a delay.
+
+	id: The value returned from OpenPPT.
+
+void Blank(int id);
+	Blanks the screen, colour black.
+
+	id: The value returned from OpenPPT.
+
+void Unblank(int id)
+	Unblanks the screen, restoring it to it's pre-blank state.
+	
+	id: The value returned from OpenPPT.
+
+void Stop(int id)
+	Moves the slideshow off the screen. (There is no concept of stop show in the PowerPoint Viewer)
+
+	id: The value returned from OpenPPT.
+
+void Resume(int id)
+	Moves the slideshow display back onto the screen following a Stop()
+
+	id: The value returned from OpenPPT.
+

=== modified file 'openlp/plugins/presentations/lib/pptviewlib/pptviewlib.cpp'
--- openlp/plugins/presentations/lib/pptviewlib/pptviewlib.cpp	2008-12-10 20:40:18 +0000
+++ openlp/plugins/presentations/lib/pptviewlib/pptviewlib.cpp	2009-09-12 18:14:09 +0000
@@ -1,753 +1,753 @@
-/*
- *   PPTVIEWLIB - Control PowerPoint Viewer 2003/2007 (for openlp.org)
- *   Copyright (C) 2008 Jonathan Corwin
- *
- *  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, either version 2 of the License, or
- *  (at your option) any later version.
- *
- *  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, see <http://www.gnu.org/licenses/>.
- */
-
-
-#define WIN32_LEAN_AND_MEAN  
-#include <windows.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <time.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include "pptviewlib.h"
-
-// Because of the callbacks used by SetWindowsHookEx, the memory used needs to be
-// sharable across processes (the callbacks are done from a different process)
-// Therefore use data_seg with RWS memory.
-//
-// See http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx for alternative
-// method of holding memory, removing fixed limits which would allow dynamic number
-// of items, rather than a fixed number. Use a Local\ mapping, since global has UAC 
-// issues in Vista.
-#pragma data_seg(".PPTVIEWLIB")
-PPTVIEWOBJ pptviewobj[MAX_PPTOBJS] = {NULL};
-HHOOK globalhook = NULL;
-BOOL debug = FALSE;
-#pragma data_seg()
-#pragma comment(linker, "/SECTION:.PPTVIEWLIB,RWS")
-
-#define DEBUG(...)  if(debug) printf(__VA_ARGS__)
-
-
-HINSTANCE hInstance = NULL;
-
-BOOL APIENTRY DllMain( HMODULE hModule,
-                       DWORD  ul_reason_for_call,
-                       LPVOID lpReserved
-					 )
-{
-    hInstance = (HINSTANCE)hModule;
-	switch (ul_reason_for_call)
-	{
-	case DLL_PROCESS_ATTACH:
-		DEBUG("PROCESS_ATTACH\n");
-		break;
-	case DLL_THREAD_ATTACH:
-		DEBUG("THREAD_ATTACH\n");
-		break;
-	case DLL_THREAD_DETACH:
-		DEBUG("THREAD_DETACH\n");
-		break;
-	case DLL_PROCESS_DETACH:
-		// Clean up... hopefully there is only the one process attached? 
-		// We'll find out soon enough during tests!
-		DEBUG("PROCESS_DETACH\n");
-		for(int i = 0; i<MAX_PPTOBJS; i++)
-			ClosePPT(i);
-		break;
-	}
-	return TRUE;
-}
-DllExport void SetDebug(BOOL onoff)
-{
-	printf("SetDebug\n");
-	debug = onoff;
-	DEBUG("enabled\n");
-}
-
-// Open the PointPoint, count the slides and take a snapshot of each slide
-// for use in previews
-// previewpath is a prefix for the location to put preview images of each slide.
-// "<n>.bmp" will be appended to complete the path. E.g. "c:\temp\slide" would 
-// create "c:\temp\slide1.bmp" slide2.bmp, slide3.bmp etc.
-// It will also create a *info.txt containing information about the ppt
-DllExport int OpenPPT(char *filename, HWND hParentWnd, RECT rect, char *previewpath)
-{
-	STARTUPINFO si;
-	PROCESS_INFORMATION pi;
-	char cmdline[MAX_PATH * 2];
-	int id;
-
-	DEBUG("OpenPPT start: %s; %s\n", filename, previewpath);
-	DEBUG("OpenPPT start: %u; %i, %i, %i, %i\n", hParentWnd, rect.top, rect.left, rect.bottom, rect.right);
-	if(GetPPTViewerPath(cmdline, sizeof(cmdline))==FALSE)
-	{
-		DEBUG("OpenPPT: GetPPTViewerPath failed\n");
-		return -1;
-	}
-	id = -1;
-	for(int i = 0; i<MAX_PPTOBJS; i++)
-	{
-		if(pptviewobj[i].state==PPT_CLOSED)
-		{
-			id=i;
-			break;
-		}
-	}
-	if(id<0)
-	{
-		DEBUG("OpenPPT: Too many PPTs\n");
-		return -1;
-	}
-	memset(&pptviewobj[id], 0, sizeof(PPTVIEWOBJ));
-	strcpy_s(pptviewobj[id].filename, MAX_PATH, filename);
-	strcpy_s(pptviewobj[id].previewpath, MAX_PATH, previewpath);
-	pptviewobj[id].state = PPT_CLOSED;
-	pptviewobj[id].slideCount = 0;
-	pptviewobj[id].currentSlide = 0;
-	pptviewobj[id].firstSlideSteps = 0;
-	pptviewobj[id].hParentWnd = hParentWnd;
-	pptviewobj[id].hWnd = NULL;
-	pptviewobj[id].hWnd2 = NULL;
-	if(hParentWnd!=NULL&&rect.top==0&&rect.bottom==0&&rect.left==0&&rect.right==0)
-	{
-		LPRECT wndrect = NULL;
-		GetWindowRect(hParentWnd, wndrect);
-		pptviewobj[id].rect.top = 0;
-		pptviewobj[id].rect.left = 0;
-		pptviewobj[id].rect.bottom = wndrect->bottom-wndrect->top;
-		pptviewobj[id].rect.right = wndrect->right-wndrect->left;
-	}
-	else
-	{
-		pptviewobj[id].rect.top = rect.top;
-		pptviewobj[id].rect.left = rect.left;
-		pptviewobj[id].rect.bottom = rect.bottom;
-		pptviewobj[id].rect.right = rect.right;
-	}
-	strcat_s(cmdline, MAX_PATH * 2, "/S \"");
-	strcat_s(cmdline, MAX_PATH * 2, filename);
-	strcat_s(cmdline, MAX_PATH * 2, "\"");
-	memset(&si, 0, sizeof(si));
-	memset(&pi, 0, sizeof(pi));
-	BOOL gotinfo = GetPPTInfo(id);
-	/* 
-	 * I'd really like to just hook on the new threadid. However this always gives
-	 * error 87. Perhaps I'm hooking to soon? No idea... however can't wait
-	 * since I need to ensure I pick up the WM_CREATE as this is the only
-	 * time the window can be resized in such away the content scales correctly
-	 *
-	 * hook = SetWindowsHookEx(WH_CBT,CbtProc,hInstance,pi.dwThreadId);
-	 */
-	if(globalhook!=NULL)
-		UnhookWindowsHookEx(globalhook);
-	globalhook = SetWindowsHookEx(WH_CBT,CbtProc,hInstance,NULL);
-	if(globalhook==0)
-	{
-		DEBUG("OpenPPT: SetWindowsHookEx failed\n");
-		ClosePPT(id);
-		return -1;
-	}
-	pptviewobj[id].state = PPT_STARTED;
-    Sleep(10); 
-	if(!CreateProcess(NULL, cmdline, NULL, NULL, FALSE, 0, 0, NULL, &si, &pi))
-	{
-		DEBUG("OpenPPT: CreateProcess failed\n");
-		ClosePPT(id);
-		return -1;
-	}
-	pptviewobj[id].dwProcessId = pi.dwProcessId;
-	pptviewobj[id].dwThreadId = pi.dwThreadId;
-	pptviewobj[id].hThread = pi.hThread;
-	pptviewobj[id].hProcess = pi.hProcess;
-	while(pptviewobj[id].state==PPT_STARTED)
-		Sleep(10);
-	if(gotinfo)
-	{
-		DEBUG("OpenPPT: Info loaded, no refresh\n");
-		pptviewobj[id].state = PPT_LOADED;
-		Resume(id);
-	}
-	else
-	{
-		DEBUG("OpenPPT: Get info\n");
-		pptviewobj[id].steps = 0;
-		int steps = 0;
-		while(pptviewobj[id].state==PPT_OPENED)
-		{
-			if(steps<=pptviewobj[id].steps)
-			{
-				Sleep(20);
-				DEBUG("OpenPPT: Step %d/%d\n",steps,pptviewobj[id].steps);
-				steps++;
-				NextStep(id);
-			} 
-			Sleep(10);
-		}
-		DEBUG("OpenPPT: Steps %d, first slide steps %d\n",pptviewobj[id].steps,pptviewobj[id].firstSlideSteps);
-		SavePPTInfo(id);
-	    if(pptviewobj[id].state==PPT_CLOSING){
-	        ClosePPT(id);
-	        id=-1;
-	    }
-		else
-       		RestartShow(id);
-	}
-	if(id>=0)
-	{
-	    if(pptviewobj[id].mhook!=NULL)	
-		    UnhookWindowsHookEx(pptviewobj[id].mhook);
-	    pptviewobj[id].mhook = NULL;
-	}
-	DEBUG("OpenPPT: Exit: id=%i\n", id);
-	return id;
-}
-// Load information about the ppt from an info.txt file.
-// Format:
-// version
-// filedate
-// filesize
-// slidecount
-// first slide steps
-BOOL GetPPTInfo(int id)
-{
-	struct _stat filestats;
-	char info[MAX_PATH];
-	FILE* pFile;
-	char buf[100];
-
-	DEBUG("GetPPTInfo: start\n");
-	if(_stat(pptviewobj[id].filename, &filestats)!=0)
-		return FALSE;
-	sprintf_s(info, MAX_PATH, "%sinfo.txt", pptviewobj[id].previewpath);
-	int err = fopen_s(&pFile, info, "r");
-	if(err!=0)
-	{
-		DEBUG("GetPPTInfo: file open failed - %d\n", err);
-		return FALSE;
-	}
-	fgets(buf, 100, pFile); // version == 1
-	fgets(buf, 100, pFile); 
-	if(filestats.st_mtime!=atoi(buf))
-	{
-		fclose (pFile);
-		return FALSE;
-	}
-	fgets(buf, 100, pFile);	
-	if(filestats.st_size!=atoi(buf))
-	{
-		fclose (pFile);
-		return FALSE;
-	}
-	fgets(buf, 100, pFile); // slidecount
-	int slidecount = atoi(buf);
-	fgets(buf, 100, pFile); // first slide steps
-	int firstslidesteps = atoi(buf);
-	// check all the preview images still exist
-	for(int i = 1; i<=slidecount; i++)
-	{
-		sprintf_s(info, MAX_PATH, "%s%i.bmp", pptviewobj[id].previewpath, i);
-		if(GetFileAttributes(info)==INVALID_FILE_ATTRIBUTES)
-			return FALSE;
-	}
-	fclose(pFile);
-	pptviewobj[id].slideCount = slidecount;
-	pptviewobj[id].firstSlideSteps = firstslidesteps;
-	DEBUG("GetPPTInfo: exit ok\n");
-	return TRUE;
-}
-
-BOOL SavePPTInfo(int id)
-{
-	struct _stat filestats;
-	char info[MAX_PATH];
-	FILE* pFile;
-
-	DEBUG("SavePPTInfo: start\n");
-	if(_stat(pptviewobj[id].filename, &filestats)!=0)
-	{
-		DEBUG("SavePPTInfo: stat of %s failed\n", pptviewobj[id].filename);
-		return FALSE;
-	}
-	sprintf_s(info, MAX_PATH, "%sinfo.txt", pptviewobj[id].previewpath);
-	int err = fopen_s(&pFile, info, "w");
-	if(err!=0)
-	{
-		DEBUG("SavePPTInfo: fopen of %s failed%i\n", info, err);
-		return FALSE;
-	}
-	fprintf(pFile, "1\n");
-	fprintf(pFile, "%u\n", filestats.st_mtime);
-	fprintf(pFile, "%u\n", filestats.st_size);
-	fprintf(pFile, "%u\n", pptviewobj[id].slideCount);
-	fprintf(pFile, "%u\n", pptviewobj[id].firstSlideSteps);
-	fclose (pFile);
-	DEBUG("SavePPTInfo: exit ok\n");
-	return TRUE;
-}
-
-// Get the path of the PowerPoint viewer from the registry
-BOOL GetPPTViewerPath(char *pptviewerpath, int strsize)
-{
-	HKEY hkey;
-	DWORD dwtype, dwsize;
-	LRESULT lresult;
-
-	DEBUG("GetPPTViewerPath: start\n");
-	if(RegOpenKeyEx(HKEY_CLASSES_ROOT, "Applications\\PPTVIEW.EXE\\shell\\open\\command", 0, KEY_READ, &hkey)!=ERROR_SUCCESS)
-    	if(RegOpenKeyEx(HKEY_CLASSES_ROOT, "Applications\\PPTVIEW.EXE\\shell\\Show\\command", 0, KEY_READ, &hkey)!=ERROR_SUCCESS)
-		return FALSE;	
-	dwtype = REG_SZ;
-	dwsize = (DWORD)strsize;
-	lresult = RegQueryValueEx(hkey, NULL, NULL, &dwtype, (LPBYTE)pptviewerpath, &dwsize );
-	RegCloseKey(hkey);
-	if(lresult!=ERROR_SUCCESS)
-		return FALSE;
-	pptviewerpath[strlen(pptviewerpath)-4] = '\0';	// remove "%1" from end of key value
-	DEBUG("GetPPTViewerPath: exit ok\n");
-	return TRUE;
-}
-
-// Unhook the Windows hook 
-void Unhook(int id)
-{
-	DEBUG("Unhook: start %d\n", id);
-	if(pptviewobj[id].hook!=NULL)	
-		UnhookWindowsHookEx(pptviewobj[id].hook);
-	if(pptviewobj[id].mhook!=NULL)	
-		UnhookWindowsHookEx(pptviewobj[id].mhook);
-	pptviewobj[id].hook = NULL;
-	pptviewobj[id].mhook = NULL;
-	DEBUG("Unhook: exit ok\n");
-}
-
-// Close the PowerPoint viewer, release resources
-DllExport void ClosePPT(int id)
-{
-	DEBUG("ClosePPT: start%d\n", id);
-	pptviewobj[id].state = PPT_CLOSED;
-	Unhook(id);
-	if(pptviewobj[id].hWnd==0)
-		TerminateThread(pptviewobj[id].hThread, 0);
-	else
-		PostMessage(pptviewobj[id].hWnd, WM_CLOSE, 0, 0);
-	CloseHandle(pptviewobj[id].hThread);
-	CloseHandle(pptviewobj[id].hProcess);
-	memset(&pptviewobj[id], 0, sizeof(PPTVIEWOBJ));
-	DEBUG("ClosePPT: exit ok\n");
-	return;
-}
-// Moves the show back onto the display
-DllExport void Resume(int id)
-{
-	DEBUG("Resume: %d\n", id);
-	MoveWindow(pptviewobj[id].hWnd, pptviewobj[id].rect.left, pptviewobj[id].rect.top, 
-			pptviewobj[id].rect.right - pptviewobj[id].rect.left, 
-			pptviewobj[id].rect.bottom - pptviewobj[id].rect.top, TRUE);
-	Unblank(id);								
-}
-// Moves the show off the screen so it can't be seen
-DllExport void Stop(int id)
-{
-	DEBUG("Stop:%d\n", id);
-	MoveWindow(pptviewobj[id].hWnd, -32000, -32000, 
-			pptviewobj[id].rect.right - pptviewobj[id].rect.left, 
-			pptviewobj[id].rect.bottom - pptviewobj[id].rect.top, TRUE);
-}
-
-// Return the total number of slides
-DllExport int GetSlideCount(int id)
-{
-	DEBUG("GetSlideCount:%d\n", id);
-	if(pptviewobj[id].state==0)
-		return -1;
-	else
-		return pptviewobj[id].slideCount;
-}
-
-// Return the number of the slide currently viewing
-DllExport int GetCurrentSlide(int id)
-{
-	DEBUG("GetCurrentSlide:%d\n", id);
-	if(pptviewobj[id].state==0)
-		return -1;
-	else
-		return pptviewobj[id].currentSlide;
-}
-
-// Take a step forwards through the show 
-DllExport void NextStep(int id)
-{
-	DEBUG("NextStep:%d\n", id);
-	if(pptviewobj[id].currentSlide>pptviewobj[id].slideCount)
-		return;
-	PostMessage(pptviewobj[id].hWnd2, WM_MOUSEWHEEL, MAKEWPARAM(0, -WHEEL_DELTA), 0);
-}
-
-// Take a step backwards through the show 
-DllExport void PrevStep(int id)
-{
-	DEBUG("PrevStep:%d\n", id);
-	PostMessage(pptviewobj[id].hWnd2, WM_MOUSEWHEEL, MAKEWPARAM(0, WHEEL_DELTA), 0);
-}
-
-// Blank the show (black screen)
-DllExport void Blank(int id)
-{	
-	// B just toggles blank on/off. However pressing any key unblanks.
-	// So send random unmapped letter first (say 'A'), then we can 
-	// better guarantee B will blank instead of trying to guess 
-	// whether it was already blank or not.
-	DEBUG("Blank:%d\n", id);
-	HWND h1 = GetForegroundWindow();
-	HWND h2 = GetFocus();
-	SetForegroundWindow(pptviewobj[id].hWnd);
-	SetFocus(pptviewobj[id].hWnd);
-	Sleep(50);	// slight pause, otherwise event triggering this call may grab focus back!
-	keybd_event((int)'A', 0, 0, 0);
-	keybd_event((int)'A', 0, KEYEVENTF_KEYUP, 0);
-	keybd_event((int)'B', 0, 0, 0);
-	keybd_event((int)'B', 0, KEYEVENTF_KEYUP, 0);
-	SetForegroundWindow(h1);
-	SetFocus(h2);
-	//PostMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, 'B', 0x00300001);
-	//PostMessage(pptviewobj[id].hWnd2, WM_CHAR, 'b', 0x00300001);
-	//PostMessage(pptviewobj[id].hWnd2, WM_KEYUP, 'B', 0xC0300001);
-}
-// Unblank the show 
-DllExport void Unblank(int id)
-{	
-	DEBUG("Unblank:%d\n", id);
-	// Pressing any key resumes. 
-	// For some reason SendMessage works for unblanking, but not blanking.
-//	SendMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, 'A', 0);
-	SendMessage(pptviewobj[id].hWnd2, WM_CHAR, 'A', 0);
-//	SendMessage(pptviewobj[id].hWnd2, WM_KEYUP, 'A', 0);
-//	HWND h1 = GetForegroundWindow();
-//	HWND h2 = GetFocus();
-//	Sleep(50);	// slight pause, otherwise event triggering this call may grab focus back!
-//	SetForegroundWindow(pptviewobj[id].hWnd);
-//	SetFocus(pptviewobj[id].hWnd);
-//	keybd_event((int)'A', 0, 0, 0);
-//	SetForegroundWindow(h1);
-//	SetFocus(h2);
-}
-
-// Go directly to a slide
-DllExport void GotoSlide(int id, int slideno)
-{	
-	DEBUG("GotoSlide %i %i:\n", id, slideno);
-	// Did try WM_KEYDOWN/WM_CHAR/WM_KEYUP with SendMessage but didn't work
-	// perhaps I was sending to the wrong window? No idea. 
-	// Anyway fall back to keybd_event, which is OK as long we makesure
-	// the slideshow has focus first
-	char ch[10];
-
-	if(slideno<0) return;
-	_itoa_s(slideno, ch, 10, 10);
-	HWND h1 = GetForegroundWindow();
-	HWND h2 = GetFocus();
-	SetForegroundWindow(pptviewobj[id].hWnd);
-	SetFocus(pptviewobj[id].hWnd);
-	Sleep(50);	// slight pause, otherwise event triggering this call may grab focus back!
-	for(int i=0;i<10;i++)
-	{
-		if(ch[i]=='\0') break;
-		keybd_event((BYTE)ch[i], 0, 0, 0);
-		keybd_event((BYTE)ch[i], 0, KEYEVENTF_KEYUP, 0);
-	}
-	keybd_event(VK_RETURN, 0, 0, 0);
-	keybd_event(VK_RETURN, 0, KEYEVENTF_KEYUP, 0);
-	SetForegroundWindow(h1);
-	SetFocus(h2);
-
-	//for(int i=0;i<10;i++)
-	//{
-	//	if(ch[i]=='\0') break;
-	//	SendMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, ch[i], 0);
-	//	SendMessage(pptviewobj[id].hWnd2, WM_CHAR, ch[i], 0);
-	//	SendMessage(pptviewobj[id].hWnd2, WM_KEYUP, ch[i], 0);
-	//}
-	//SendMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, VK_RETURN, 0);
-	//SendMessage(pptviewobj[id].hWnd2, WM_CHAR, VK_RETURN, 0);
-	//SendMessage(pptviewobj[id].hWnd2, WM_KEYUP, VK_RETURN, 0);
-	//keybd_event(VK_RETURN, 0, 0, 0);
-}
-
-// Restart the show from the beginning
-DllExport void RestartShow(int id)
-{
-	// If we just go direct to slide one, then it remembers that all other slides have
-	// been animated, so ends up just showing the completed slides of those slides that
-	// have been animated next time we advance. 
-	// Only way I've found to get around this is to step backwards all the way through. 
-	// Lets move the window out of the way first so the audience doesn't see this.
-	DEBUG("RestartShow:%d\n", id);
-	Stop(id);
-	GotoSlide(id, pptviewobj[id].slideCount);
-	while(pptviewobj[id].currentSlide>1)
-	{
-		PrevStep(id);
-		Sleep(10);
-	}
-	for(int i=0;i<=pptviewobj[id].firstSlideSteps;i++)
-	{
-		PrevStep(id);
-		Sleep(10);
-	}
-	Resume(id);
-}
-
-// This hook is started with the PPTVIEW.EXE process and waits for the
-// WM_CREATEWND message. At this point (and only this point) can the
-// window be resized to the correct size.
-// Release the hook as soon as we're complete to free up resources
-LRESULT CALLBACK CbtProc(int nCode, WPARAM wParam, LPARAM lParam)
-{
-	HHOOK hook = globalhook;
-    if(nCode==HCBT_CREATEWND)
-    {
-	    char csClassName[16];
-        HWND hCurrWnd = (HWND)wParam;
-		DWORD retProcId = NULL;
-		GetClassName(hCurrWnd, csClassName, sizeof(csClassName));
-		if((strcmp(csClassName, "paneClassDC")==0)
-		  ||(strcmp(csClassName, "screenClass")==0))
-		{
-			int id=-1;
-			DWORD windowthread = GetWindowThreadProcessId(hCurrWnd,NULL);
-			for(int i=0; i<MAX_PPTOBJS; i++)
-			{
-				if(pptviewobj[i].dwThreadId==windowthread)
-				{
-					id=i;
-					break;
-				}
-			}
-			if(id>=0)
-			{
-				if(strcmp(csClassName, "paneClassDC")==0)
-					pptviewobj[id].hWnd2=hCurrWnd;
-				else		
-				{
-					pptviewobj[id].hWnd=hCurrWnd;
-					CBT_CREATEWND* cw = (CBT_CREATEWND*)lParam;
-					if(pptviewobj[id].hParentWnd!=NULL) 
-						cw->lpcs->hwndParent = pptviewobj[id].hParentWnd;
-					cw->lpcs->cy=(pptviewobj[id].rect.bottom-pptviewobj[id].rect.top);
-					cw->lpcs->cx=(pptviewobj[id].rect.right-pptviewobj[id].rect.left);
-					cw->lpcs->y=-32000; 
-					cw->lpcs->x=-32000; 
-				}
-				if((pptviewobj[id].hWnd!=NULL)&&(pptviewobj[id].hWnd2!=NULL))
-				{
-					UnhookWindowsHookEx(globalhook);
-					globalhook=NULL;
-					pptviewobj[id].hook = SetWindowsHookEx(WH_CALLWNDPROC,CwpProc,hInstance,pptviewobj[id].dwThreadId);
-					pptviewobj[id].mhook = SetWindowsHookEx(WH_GETMESSAGE,GetMsgProc,hInstance,pptviewobj[id].dwThreadId);
-					Sleep(10);
-					pptviewobj[id].state = PPT_OPENED;
-				}
-			}
-		}
-    }
-	return CallNextHookEx(hook,nCode,wParam,lParam); 
-}
-
-// This hook exists whilst the slideshow is loading but only listens on the
-// slideshows thread. It listens out for mousewheel events
-LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam) 
-{
-	HHOOK hook = NULL;
-	MSG *pMSG = (MSG *)lParam;
-	DWORD windowthread = GetWindowThreadProcessId(pMSG->hwnd,NULL);
-	int id=-1;
-	for(int i=0; i<MAX_PPTOBJS; i++)
-	{
-		if(pptviewobj[i].dwThreadId==windowthread)
-		{
-			id=i;
-			hook = pptviewobj[id].mhook;
-			break;
-		}
-	}
-	if(id>=0&&nCode==HC_ACTION&&wParam==PM_REMOVE&&pMSG->message==WM_MOUSEWHEEL)
-    {
-		if(pptviewobj[id].state!=PPT_LOADED)
-		{
-			if(pptviewobj[id].currentSlide==1)
-				pptviewobj[id].firstSlideSteps++;
-			pptviewobj[id].steps++;
-		}
-    }
-    return CallNextHookEx(hook, nCode, wParam, lParam);
-}
-// This hook exists whilst the slideshow is running but only listens on the
-// slideshows thread. It listens out for slide changes, message WM_USER+22.
-LRESULT CALLBACK CwpProc(int nCode, WPARAM wParam, LPARAM lParam){
-	CWPSTRUCT *cwp;
-	cwp = (CWPSTRUCT *)lParam;
-	HHOOK hook = NULL;
-	char filename[MAX_PATH];
-
-	DWORD windowthread = GetWindowThreadProcessId(cwp->hwnd,NULL);
-	int id=-1;
-	for(int i=0; i<MAX_PPTOBJS; i++)
-	{
-		if(pptviewobj[i].dwThreadId==windowthread)
-		{
-			id=i;
-			hook = pptviewobj[id].hook;
-			break;
-		}
-	}
-	if((id>=0)&&(nCode==HC_ACTION))
-	{
-		if(cwp->message==WM_USER+22)
-		{
-			if(pptviewobj[id].state != PPT_LOADED)
-			{
-				if((pptviewobj[id].currentSlide>0)
-				&& (pptviewobj[id].previewpath!=NULL&&strlen(pptviewobj[id].previewpath)>0))
-				{
-					sprintf_s(filename, MAX_PATH, "%s%i.bmp", pptviewobj[id].previewpath, pptviewobj[id].currentSlide);
-					CaptureAndSaveWindow(cwp->hwnd, filename);
-				}
-			}
-			if(cwp->wParam==0)
-			{
-				if(pptviewobj[id].currentSlide>0) 
-				{
-					pptviewobj[id].state = PPT_LOADED;
-					pptviewobj[id].currentSlide = pptviewobj[id].slideCount+1;
-				}
-			} 
-			else
-			{
-				pptviewobj[id].currentSlide = cwp->wParam - 255;
-				if(pptviewobj[id].currentSlide>pptviewobj[id].slideCount)
-					pptviewobj[id].slideCount = pptviewobj[id].currentSlide;
-			}
-		}
-		if((pptviewobj[id].state != PPT_CLOSED)&&(cwp->message==WM_CLOSE||cwp->message==WM_QUIT))
-			pptviewobj[id].state = PPT_CLOSING;
-	}
-	return CallNextHookEx(hook,nCode,wParam,lParam); 
-}
-
-VOID CaptureAndSaveWindow(HWND hWnd, CHAR* filename)
-{
-	HBITMAP hBmp;
-	if ((hBmp = CaptureWindow(hWnd)) == NULL) 
-		return;
-
-	RECT client;
-	GetClientRect (hWnd, &client);
-	UINT uiBytesPerRow = 3 * client.right; // RGB takes 24 bits
-	UINT uiRemainderForPadding;
-
-	if ((uiRemainderForPadding = uiBytesPerRow % sizeof (DWORD)) > 0) 
-		uiBytesPerRow += (sizeof (DWORD) - uiRemainderForPadding);
-
-	UINT uiBytesPerAllRows = uiBytesPerRow * client.bottom;
-	PBYTE pDataBits;
-
-	if ((pDataBits = new BYTE [uiBytesPerAllRows]) != NULL) 
-	{
-		BITMAPINFOHEADER bmi = {0};
-		BITMAPFILEHEADER bmf = {0};
-
-		// Prepare to get the data out of HBITMAP:
-		bmi.biSize = sizeof (bmi);
-		bmi.biPlanes = 1;
-		bmi.biBitCount = 24;
-		bmi.biHeight = client.bottom;
-		bmi.biWidth = client.right;
-
-		// Get it:
-		HDC hDC = GetDC (hWnd);
-		GetDIBits (hDC, hBmp, 0, client.bottom, pDataBits, 
-					(BITMAPINFO*) &bmi, DIB_RGB_COLORS);
-		ReleaseDC (hWnd, hDC);
-
-		// Fill the file header:
-		bmf.bfOffBits = sizeof (bmf) + sizeof (bmi);
-		bmf.bfSize = bmf.bfOffBits + uiBytesPerAllRows;
-		bmf.bfType = 0x4D42;
-
-		// Writing:
-		FILE* pFile;
-		int err = fopen_s(&pFile, filename, "wb");
-		if (err == 0) 
-		{
-			fwrite (&bmf, sizeof (bmf), 1, pFile);
-			fwrite (&bmi, sizeof (bmi), 1, pFile);
-			fwrite (pDataBits, sizeof (BYTE), uiBytesPerAllRows, pFile);
-			fclose (pFile);
-		} 
-		delete [] pDataBits;
-	}
-	DeleteObject (hBmp);
-}
-HBITMAP CaptureWindow (HWND hWnd) {
-	HDC hDC;
-	BOOL bOk = FALSE;
-	HBITMAP hImage = NULL;
-
-	hDC = GetDC (hWnd);
-	RECT rcClient;
-	GetClientRect (hWnd, &rcClient);
-	if ((hImage = CreateCompatibleBitmap (hDC, rcClient.right, rcClient.bottom)) != NULL) 
-	{
-		HDC hMemDC;
-		HBITMAP hDCBmp;
-
-		if ((hMemDC = CreateCompatibleDC (hDC)) != NULL) 
-		{
-			hDCBmp = (HBITMAP) SelectObject (hMemDC, hImage);
-			HMODULE hLib = LoadLibrary("User32");
-			// PrintWindow works for windows outside displayable area
-			// but was only introduced in WinXP. BitBlt requires the window to be topmost 
-			// and within the viewable area of the display
-			if(GetProcAddress(hLib, "PrintWindow")==NULL)
-			{
-				SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE); 
-				BitBlt (hMemDC, 0, 0, rcClient.right, rcClient.bottom, hDC, 0, 0, SRCCOPY);
-				SetWindowPos(hWnd, HWND_NOTOPMOST, -32000, -32000, 0, 0, SWP_NOSIZE); 
-			}
-			else
-			{
-				PrintWindow(hWnd, hMemDC, 0);
-			}
-			SelectObject (hMemDC, hDCBmp);
-			DeleteDC (hMemDC);
-			bOk = TRUE;
-		}
-	}
-	ReleaseDC (hWnd, hDC);
-	if (! bOk) 
-	{
-		if (hImage) 
-		{
-			DeleteObject (hImage);
-			hImage = NULL;
-		}
-	}
-	return hImage;
-}
+/*
+ *   PPTVIEWLIB - Control PowerPoint Viewer 2003/2007 (for openlp.org)
+ *   Copyright (C) 2008 Jonathan Corwin
+ *
+ *  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, either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  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, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#define WIN32_LEAN_AND_MEAN  
+#include <windows.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "pptviewlib.h"
+
+// Because of the callbacks used by SetWindowsHookEx, the memory used needs to be
+// sharable across processes (the callbacks are done from a different process)
+// Therefore use data_seg with RWS memory.
+//
+// See http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx for alternative
+// method of holding memory, removing fixed limits which would allow dynamic number
+// of items, rather than a fixed number. Use a Local\ mapping, since global has UAC 
+// issues in Vista.
+#pragma data_seg(".PPTVIEWLIB")
+PPTVIEWOBJ pptviewobj[MAX_PPTOBJS] = {NULL};
+HHOOK globalhook = NULL;
+BOOL debug = FALSE;
+#pragma data_seg()
+#pragma comment(linker, "/SECTION:.PPTVIEWLIB,RWS")
+
+#define DEBUG(...)  if(debug) printf(__VA_ARGS__)
+
+
+HINSTANCE hInstance = NULL;
+
+BOOL APIENTRY DllMain( HMODULE hModule,
+                       DWORD  ul_reason_for_call,
+                       LPVOID lpReserved
+					 )
+{
+    hInstance = (HINSTANCE)hModule;
+	switch (ul_reason_for_call)
+	{
+	case DLL_PROCESS_ATTACH:
+		DEBUG("PROCESS_ATTACH\n");
+		break;
+	case DLL_THREAD_ATTACH:
+		DEBUG("THREAD_ATTACH\n");
+		break;
+	case DLL_THREAD_DETACH:
+		DEBUG("THREAD_DETACH\n");
+		break;
+	case DLL_PROCESS_DETACH:
+		// Clean up... hopefully there is only the one process attached? 
+		// We'll find out soon enough during tests!
+		DEBUG("PROCESS_DETACH\n");
+		for(int i = 0; i<MAX_PPTOBJS; i++)
+			ClosePPT(i);
+		break;
+	}
+	return TRUE;
+}
+DllExport void SetDebug(BOOL onoff)
+{
+	printf("SetDebug\n");
+	debug = onoff;
+	DEBUG("enabled\n");
+}
+
+// Open the PointPoint, count the slides and take a snapshot of each slide
+// for use in previews
+// previewpath is a prefix for the location to put preview images of each slide.
+// "<n>.bmp" will be appended to complete the path. E.g. "c:\temp\slide" would 
+// create "c:\temp\slide1.bmp" slide2.bmp, slide3.bmp etc.
+// It will also create a *info.txt containing information about the ppt
+DllExport int OpenPPT(char *filename, HWND hParentWnd, RECT rect, char *previewpath)
+{
+	STARTUPINFO si;
+	PROCESS_INFORMATION pi;
+	char cmdline[MAX_PATH * 2];
+	int id;
+
+	DEBUG("OpenPPT start: %s; %s\n", filename, previewpath);
+	DEBUG("OpenPPT start: %u; %i, %i, %i, %i\n", hParentWnd, rect.top, rect.left, rect.bottom, rect.right);
+	if(GetPPTViewerPath(cmdline, sizeof(cmdline))==FALSE)
+	{
+		DEBUG("OpenPPT: GetPPTViewerPath failed\n");
+		return -1;
+	}
+	id = -1;
+	for(int i = 0; i<MAX_PPTOBJS; i++)
+	{
+		if(pptviewobj[i].state==PPT_CLOSED)
+		{
+			id=i;
+			break;
+		}
+	}
+	if(id<0)
+	{
+		DEBUG("OpenPPT: Too many PPTs\n");
+		return -1;
+	}
+	memset(&pptviewobj[id], 0, sizeof(PPTVIEWOBJ));
+	strcpy_s(pptviewobj[id].filename, MAX_PATH, filename);
+	strcpy_s(pptviewobj[id].previewpath, MAX_PATH, previewpath);
+	pptviewobj[id].state = PPT_CLOSED;
+	pptviewobj[id].slideCount = 0;
+	pptviewobj[id].currentSlide = 0;
+	pptviewobj[id].firstSlideSteps = 0;
+	pptviewobj[id].hParentWnd = hParentWnd;
+	pptviewobj[id].hWnd = NULL;
+	pptviewobj[id].hWnd2 = NULL;
+	if(hParentWnd!=NULL&&rect.top==0&&rect.bottom==0&&rect.left==0&&rect.right==0)
+	{
+		LPRECT wndrect = NULL;
+		GetWindowRect(hParentWnd, wndrect);
+		pptviewobj[id].rect.top = 0;
+		pptviewobj[id].rect.left = 0;
+		pptviewobj[id].rect.bottom = wndrect->bottom-wndrect->top;
+		pptviewobj[id].rect.right = wndrect->right-wndrect->left;
+	}
+	else
+	{
+		pptviewobj[id].rect.top = rect.top;
+		pptviewobj[id].rect.left = rect.left;
+		pptviewobj[id].rect.bottom = rect.bottom;
+		pptviewobj[id].rect.right = rect.right;
+	}
+	strcat_s(cmdline, MAX_PATH * 2, "/S \"");
+	strcat_s(cmdline, MAX_PATH * 2, filename);
+	strcat_s(cmdline, MAX_PATH * 2, "\"");
+	memset(&si, 0, sizeof(si));
+	memset(&pi, 0, sizeof(pi));
+	BOOL gotinfo = GetPPTInfo(id);
+	/* 
+	 * I'd really like to just hook on the new threadid. However this always gives
+	 * error 87. Perhaps I'm hooking to soon? No idea... however can't wait
+	 * since I need to ensure I pick up the WM_CREATE as this is the only
+	 * time the window can be resized in such away the content scales correctly
+	 *
+	 * hook = SetWindowsHookEx(WH_CBT,CbtProc,hInstance,pi.dwThreadId);
+	 */
+	if(globalhook!=NULL)
+		UnhookWindowsHookEx(globalhook);
+	globalhook = SetWindowsHookEx(WH_CBT,CbtProc,hInstance,NULL);
+	if(globalhook==0)
+	{
+		DEBUG("OpenPPT: SetWindowsHookEx failed\n");
+		ClosePPT(id);
+		return -1;
+	}
+	pptviewobj[id].state = PPT_STARTED;
+    Sleep(10); 
+	if(!CreateProcess(NULL, cmdline, NULL, NULL, FALSE, 0, 0, NULL, &si, &pi))
+	{
+		DEBUG("OpenPPT: CreateProcess failed\n");
+		ClosePPT(id);
+		return -1;
+	}
+	pptviewobj[id].dwProcessId = pi.dwProcessId;
+	pptviewobj[id].dwThreadId = pi.dwThreadId;
+	pptviewobj[id].hThread = pi.hThread;
+	pptviewobj[id].hProcess = pi.hProcess;
+	while(pptviewobj[id].state==PPT_STARTED)
+		Sleep(10);
+	if(gotinfo)
+	{
+		DEBUG("OpenPPT: Info loaded, no refresh\n");
+		pptviewobj[id].state = PPT_LOADED;
+		Resume(id);
+	}
+	else
+	{
+		DEBUG("OpenPPT: Get info\n");
+		pptviewobj[id].steps = 0;
+		int steps = 0;
+		while(pptviewobj[id].state==PPT_OPENED)
+		{
+			if(steps<=pptviewobj[id].steps)
+			{
+				Sleep(20);
+				DEBUG("OpenPPT: Step %d/%d\n",steps,pptviewobj[id].steps);
+				steps++;
+				NextStep(id);
+			} 
+			Sleep(10);
+		}
+		DEBUG("OpenPPT: Steps %d, first slide steps %d\n",pptviewobj[id].steps,pptviewobj[id].firstSlideSteps);
+		SavePPTInfo(id);
+	    if(pptviewobj[id].state==PPT_CLOSING){
+	        ClosePPT(id);
+	        id=-1;
+	    }
+		else
+       		RestartShow(id);
+	}
+	if(id>=0)
+	{
+	    if(pptviewobj[id].mhook!=NULL)	
+		    UnhookWindowsHookEx(pptviewobj[id].mhook);
+	    pptviewobj[id].mhook = NULL;
+	}
+	DEBUG("OpenPPT: Exit: id=%i\n", id);
+	return id;
+}
+// Load information about the ppt from an info.txt file.
+// Format:
+// version
+// filedate
+// filesize
+// slidecount
+// first slide steps
+BOOL GetPPTInfo(int id)
+{
+	struct _stat filestats;
+	char info[MAX_PATH];
+	FILE* pFile;
+	char buf[100];
+
+	DEBUG("GetPPTInfo: start\n");
+	if(_stat(pptviewobj[id].filename, &filestats)!=0)
+		return FALSE;
+	sprintf_s(info, MAX_PATH, "%sinfo.txt", pptviewobj[id].previewpath);
+	int err = fopen_s(&pFile, info, "r");
+	if(err!=0)
+	{
+		DEBUG("GetPPTInfo: file open failed - %d\n", err);
+		return FALSE;
+	}
+	fgets(buf, 100, pFile); // version == 1
+	fgets(buf, 100, pFile); 
+	if(filestats.st_mtime!=atoi(buf))
+	{
+		fclose (pFile);
+		return FALSE;
+	}
+	fgets(buf, 100, pFile);	
+	if(filestats.st_size!=atoi(buf))
+	{
+		fclose (pFile);
+		return FALSE;
+	}
+	fgets(buf, 100, pFile); // slidecount
+	int slidecount = atoi(buf);
+	fgets(buf, 100, pFile); // first slide steps
+	int firstslidesteps = atoi(buf);
+	// check all the preview images still exist
+	for(int i = 1; i<=slidecount; i++)
+	{
+		sprintf_s(info, MAX_PATH, "%s%i.bmp", pptviewobj[id].previewpath, i);
+		if(GetFileAttributes(info)==INVALID_FILE_ATTRIBUTES)
+			return FALSE;
+	}
+	fclose(pFile);
+	pptviewobj[id].slideCount = slidecount;
+	pptviewobj[id].firstSlideSteps = firstslidesteps;
+	DEBUG("GetPPTInfo: exit ok\n");
+	return TRUE;
+}
+
+BOOL SavePPTInfo(int id)
+{
+	struct _stat filestats;
+	char info[MAX_PATH];
+	FILE* pFile;
+
+	DEBUG("SavePPTInfo: start\n");
+	if(_stat(pptviewobj[id].filename, &filestats)!=0)
+	{
+		DEBUG("SavePPTInfo: stat of %s failed\n", pptviewobj[id].filename);
+		return FALSE;
+	}
+	sprintf_s(info, MAX_PATH, "%sinfo.txt", pptviewobj[id].previewpath);
+	int err = fopen_s(&pFile, info, "w");
+	if(err!=0)
+	{
+		DEBUG("SavePPTInfo: fopen of %s failed%i\n", info, err);
+		return FALSE;
+	}
+	fprintf(pFile, "1\n");
+	fprintf(pFile, "%u\n", filestats.st_mtime);
+	fprintf(pFile, "%u\n", filestats.st_size);
+	fprintf(pFile, "%u\n", pptviewobj[id].slideCount);
+	fprintf(pFile, "%u\n", pptviewobj[id].firstSlideSteps);
+	fclose (pFile);
+	DEBUG("SavePPTInfo: exit ok\n");
+	return TRUE;
+}
+
+// Get the path of the PowerPoint viewer from the registry
+BOOL GetPPTViewerPath(char *pptviewerpath, int strsize)
+{
+	HKEY hkey;
+	DWORD dwtype, dwsize;
+	LRESULT lresult;
+
+	DEBUG("GetPPTViewerPath: start\n");
+	if(RegOpenKeyEx(HKEY_CLASSES_ROOT, "Applications\\PPTVIEW.EXE\\shell\\open\\command", 0, KEY_READ, &hkey)!=ERROR_SUCCESS)
+    	if(RegOpenKeyEx(HKEY_CLASSES_ROOT, "Applications\\PPTVIEW.EXE\\shell\\Show\\command", 0, KEY_READ, &hkey)!=ERROR_SUCCESS)
+		return FALSE;	
+	dwtype = REG_SZ;
+	dwsize = (DWORD)strsize;
+	lresult = RegQueryValueEx(hkey, NULL, NULL, &dwtype, (LPBYTE)pptviewerpath, &dwsize );
+	RegCloseKey(hkey);
+	if(lresult!=ERROR_SUCCESS)
+		return FALSE;
+	pptviewerpath[strlen(pptviewerpath)-4] = '\0';	// remove "%1" from end of key value
+	DEBUG("GetPPTViewerPath: exit ok\n");
+	return TRUE;
+}
+
+// Unhook the Windows hook 
+void Unhook(int id)
+{
+	DEBUG("Unhook: start %d\n", id);
+	if(pptviewobj[id].hook!=NULL)	
+		UnhookWindowsHookEx(pptviewobj[id].hook);
+	if(pptviewobj[id].mhook!=NULL)	
+		UnhookWindowsHookEx(pptviewobj[id].mhook);
+	pptviewobj[id].hook = NULL;
+	pptviewobj[id].mhook = NULL;
+	DEBUG("Unhook: exit ok\n");
+}
+
+// Close the PowerPoint viewer, release resources
+DllExport void ClosePPT(int id)
+{
+	DEBUG("ClosePPT: start%d\n", id);
+	pptviewobj[id].state = PPT_CLOSED;
+	Unhook(id);
+	if(pptviewobj[id].hWnd==0)
+		TerminateThread(pptviewobj[id].hThread, 0);
+	else
+		PostMessage(pptviewobj[id].hWnd, WM_CLOSE, 0, 0);
+	CloseHandle(pptviewobj[id].hThread);
+	CloseHandle(pptviewobj[id].hProcess);
+	memset(&pptviewobj[id], 0, sizeof(PPTVIEWOBJ));
+	DEBUG("ClosePPT: exit ok\n");
+	return;
+}
+// Moves the show back onto the display
+DllExport void Resume(int id)
+{
+	DEBUG("Resume: %d\n", id);
+	MoveWindow(pptviewobj[id].hWnd, pptviewobj[id].rect.left, pptviewobj[id].rect.top, 
+			pptviewobj[id].rect.right - pptviewobj[id].rect.left, 
+			pptviewobj[id].rect.bottom - pptviewobj[id].rect.top, TRUE);
+	Unblank(id);								
+}
+// Moves the show off the screen so it can't be seen
+DllExport void Stop(int id)
+{
+	DEBUG("Stop:%d\n", id);
+	MoveWindow(pptviewobj[id].hWnd, -32000, -32000, 
+			pptviewobj[id].rect.right - pptviewobj[id].rect.left, 
+			pptviewobj[id].rect.bottom - pptviewobj[id].rect.top, TRUE);
+}
+
+// Return the total number of slides
+DllExport int GetSlideCount(int id)
+{
+	DEBUG("GetSlideCount:%d\n", id);
+	if(pptviewobj[id].state==0)
+		return -1;
+	else
+		return pptviewobj[id].slideCount;
+}
+
+// Return the number of the slide currently viewing
+DllExport int GetCurrentSlide(int id)
+{
+	DEBUG("GetCurrentSlide:%d\n", id);
+	if(pptviewobj[id].state==0)
+		return -1;
+	else
+		return pptviewobj[id].currentSlide;
+}
+
+// Take a step forwards through the show 
+DllExport void NextStep(int id)
+{
+	DEBUG("NextStep:%d\n", id);
+	if(pptviewobj[id].currentSlide>pptviewobj[id].slideCount)
+		return;
+	PostMessage(pptviewobj[id].hWnd2, WM_MOUSEWHEEL, MAKEWPARAM(0, -WHEEL_DELTA), 0);
+}
+
+// Take a step backwards through the show 
+DllExport void PrevStep(int id)
+{
+	DEBUG("PrevStep:%d\n", id);
+	PostMessage(pptviewobj[id].hWnd2, WM_MOUSEWHEEL, MAKEWPARAM(0, WHEEL_DELTA), 0);
+}
+
+// Blank the show (black screen)
+DllExport void Blank(int id)
+{	
+	// B just toggles blank on/off. However pressing any key unblanks.
+	// So send random unmapped letter first (say 'A'), then we can 
+	// better guarantee B will blank instead of trying to guess 
+	// whether it was already blank or not.
+	DEBUG("Blank:%d\n", id);
+	HWND h1 = GetForegroundWindow();
+	HWND h2 = GetFocus();
+	SetForegroundWindow(pptviewobj[id].hWnd);
+	SetFocus(pptviewobj[id].hWnd);
+	Sleep(50);	// slight pause, otherwise event triggering this call may grab focus back!
+	keybd_event((int)'A', 0, 0, 0);
+	keybd_event((int)'A', 0, KEYEVENTF_KEYUP, 0);
+	keybd_event((int)'B', 0, 0, 0);
+	keybd_event((int)'B', 0, KEYEVENTF_KEYUP, 0);
+	SetForegroundWindow(h1);
+	SetFocus(h2);
+	//PostMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, 'B', 0x00300001);
+	//PostMessage(pptviewobj[id].hWnd2, WM_CHAR, 'b', 0x00300001);
+	//PostMessage(pptviewobj[id].hWnd2, WM_KEYUP, 'B', 0xC0300001);
+}
+// Unblank the show 
+DllExport void Unblank(int id)
+{	
+	DEBUG("Unblank:%d\n", id);
+	// Pressing any key resumes. 
+	// For some reason SendMessage works for unblanking, but not blanking.
+//	SendMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, 'A', 0);
+	SendMessage(pptviewobj[id].hWnd2, WM_CHAR, 'A', 0);
+//	SendMessage(pptviewobj[id].hWnd2, WM_KEYUP, 'A', 0);
+//	HWND h1 = GetForegroundWindow();
+//	HWND h2 = GetFocus();
+//	Sleep(50);	// slight pause, otherwise event triggering this call may grab focus back!
+//	SetForegroundWindow(pptviewobj[id].hWnd);
+//	SetFocus(pptviewobj[id].hWnd);
+//	keybd_event((int)'A', 0, 0, 0);
+//	SetForegroundWindow(h1);
+//	SetFocus(h2);
+}
+
+// Go directly to a slide
+DllExport void GotoSlide(int id, int slideno)
+{	
+	DEBUG("GotoSlide %i %i:\n", id, slideno);
+	// Did try WM_KEYDOWN/WM_CHAR/WM_KEYUP with SendMessage but didn't work
+	// perhaps I was sending to the wrong window? No idea. 
+	// Anyway fall back to keybd_event, which is OK as long we makesure
+	// the slideshow has focus first
+	char ch[10];
+
+	if(slideno<0) return;
+	_itoa_s(slideno, ch, 10, 10);
+	HWND h1 = GetForegroundWindow();
+	HWND h2 = GetFocus();
+	SetForegroundWindow(pptviewobj[id].hWnd);
+	SetFocus(pptviewobj[id].hWnd);
+	Sleep(50);	// slight pause, otherwise event triggering this call may grab focus back!
+	for(int i=0;i<10;i++)
+	{
+		if(ch[i]=='\0') break;
+		keybd_event((BYTE)ch[i], 0, 0, 0);
+		keybd_event((BYTE)ch[i], 0, KEYEVENTF_KEYUP, 0);
+	}
+	keybd_event(VK_RETURN, 0, 0, 0);
+	keybd_event(VK_RETURN, 0, KEYEVENTF_KEYUP, 0);
+	SetForegroundWindow(h1);
+	SetFocus(h2);
+
+	//for(int i=0;i<10;i++)
+	//{
+	//	if(ch[i]=='\0') break;
+	//	SendMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, ch[i], 0);
+	//	SendMessage(pptviewobj[id].hWnd2, WM_CHAR, ch[i], 0);
+	//	SendMessage(pptviewobj[id].hWnd2, WM_KEYUP, ch[i], 0);
+	//}
+	//SendMessage(pptviewobj[id].hWnd2, WM_KEYDOWN, VK_RETURN, 0);
+	//SendMessage(pptviewobj[id].hWnd2, WM_CHAR, VK_RETURN, 0);
+	//SendMessage(pptviewobj[id].hWnd2, WM_KEYUP, VK_RETURN, 0);
+	//keybd_event(VK_RETURN, 0, 0, 0);
+}
+
+// Restart the show from the beginning
+DllExport void RestartShow(int id)
+{
+	// If we just go direct to slide one, then it remembers that all other slides have
+	// been animated, so ends up just showing the completed slides of those slides that
+	// have been animated next time we advance. 
+	// Only way I've found to get around this is to step backwards all the way through. 
+	// Lets move the window out of the way first so the audience doesn't see this.
+	DEBUG("RestartShow:%d\n", id);
+	Stop(id);
+	GotoSlide(id, pptviewobj[id].slideCount);
+	while(pptviewobj[id].currentSlide>1)
+	{
+		PrevStep(id);
+		Sleep(10);
+	}
+	for(int i=0;i<=pptviewobj[id].firstSlideSteps;i++)
+	{
+		PrevStep(id);
+		Sleep(10);
+	}
+	Resume(id);
+}
+
+// This hook is started with the PPTVIEW.EXE process and waits for the
+// WM_CREATEWND message. At this point (and only this point) can the
+// window be resized to the correct size.
+// Release the hook as soon as we're complete to free up resources
+LRESULT CALLBACK CbtProc(int nCode, WPARAM wParam, LPARAM lParam)
+{
+	HHOOK hook = globalhook;
+    if(nCode==HCBT_CREATEWND)
+    {
+	    char csClassName[16];
+        HWND hCurrWnd = (HWND)wParam;
+		DWORD retProcId = NULL;
+		GetClassName(hCurrWnd, csClassName, sizeof(csClassName));
+		if((strcmp(csClassName, "paneClassDC")==0)
+		  ||(strcmp(csClassName, "screenClass")==0))
+		{
+			int id=-1;
+			DWORD windowthread = GetWindowThreadProcessId(hCurrWnd,NULL);
+			for(int i=0; i<MAX_PPTOBJS; i++)
+			{
+				if(pptviewobj[i].dwThreadId==windowthread)
+				{
+					id=i;
+					break;
+				}
+			}
+			if(id>=0)
+			{
+				if(strcmp(csClassName, "paneClassDC")==0)
+					pptviewobj[id].hWnd2=hCurrWnd;
+				else		
+				{
+					pptviewobj[id].hWnd=hCurrWnd;
+					CBT_CREATEWND* cw = (CBT_CREATEWND*)lParam;
+					if(pptviewobj[id].hParentWnd!=NULL) 
+						cw->lpcs->hwndParent = pptviewobj[id].hParentWnd;
+					cw->lpcs->cy=(pptviewobj[id].rect.bottom-pptviewobj[id].rect.top);
+					cw->lpcs->cx=(pptviewobj[id].rect.right-pptviewobj[id].rect.left);
+					cw->lpcs->y=-32000; 
+					cw->lpcs->x=-32000; 
+				}
+				if((pptviewobj[id].hWnd!=NULL)&&(pptviewobj[id].hWnd2!=NULL))
+				{
+					UnhookWindowsHookEx(globalhook);
+					globalhook=NULL;
+					pptviewobj[id].hook = SetWindowsHookEx(WH_CALLWNDPROC,CwpProc,hInstance,pptviewobj[id].dwThreadId);
+					pptviewobj[id].mhook = SetWindowsHookEx(WH_GETMESSAGE,GetMsgProc,hInstance,pptviewobj[id].dwThreadId);
+					Sleep(10);
+					pptviewobj[id].state = PPT_OPENED;
+				}
+			}
+		}
+    }
+	return CallNextHookEx(hook,nCode,wParam,lParam); 
+}
+
+// This hook exists whilst the slideshow is loading but only listens on the
+// slideshows thread. It listens out for mousewheel events
+LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam) 
+{
+	HHOOK hook = NULL;
+	MSG *pMSG = (MSG *)lParam;
+	DWORD windowthread = GetWindowThreadProcessId(pMSG->hwnd,NULL);
+	int id=-1;
+	for(int i=0; i<MAX_PPTOBJS; i++)
+	{
+		if(pptviewobj[i].dwThreadId==windowthread)
+		{
+			id=i;
+			hook = pptviewobj[id].mhook;
+			break;
+		}
+	}
+	if(id>=0&&nCode==HC_ACTION&&wParam==PM_REMOVE&&pMSG->message==WM_MOUSEWHEEL)
+    {
+		if(pptviewobj[id].state!=PPT_LOADED)
+		{
+			if(pptviewobj[id].currentSlide==1)
+				pptviewobj[id].firstSlideSteps++;
+			pptviewobj[id].steps++;
+		}
+    }
+    return CallNextHookEx(hook, nCode, wParam, lParam);
+}
+// This hook exists whilst the slideshow is running but only listens on the
+// slideshows thread. It listens out for slide changes, message WM_USER+22.
+LRESULT CALLBACK CwpProc(int nCode, WPARAM wParam, LPARAM lParam){
+	CWPSTRUCT *cwp;
+	cwp = (CWPSTRUCT *)lParam;
+	HHOOK hook = NULL;
+	char filename[MAX_PATH];
+
+	DWORD windowthread = GetWindowThreadProcessId(cwp->hwnd,NULL);
+	int id=-1;
+	for(int i=0; i<MAX_PPTOBJS; i++)
+	{
+		if(pptviewobj[i].dwThreadId==windowthread)
+		{
+			id=i;
+			hook = pptviewobj[id].hook;
+			break;
+		}
+	}
+	if((id>=0)&&(nCode==HC_ACTION))
+	{
+		if(cwp->message==WM_USER+22)
+		{
+			if(pptviewobj[id].state != PPT_LOADED)
+			{
+				if((pptviewobj[id].currentSlide>0)
+				&& (pptviewobj[id].previewpath!=NULL&&strlen(pptviewobj[id].previewpath)>0))
+				{
+					sprintf_s(filename, MAX_PATH, "%s%i.bmp", pptviewobj[id].previewpath, pptviewobj[id].currentSlide);
+					CaptureAndSaveWindow(cwp->hwnd, filename);
+				}
+			}
+			if(cwp->wParam==0)
+			{
+				if(pptviewobj[id].currentSlide>0) 
+				{
+					pptviewobj[id].state = PPT_LOADED;
+					pptviewobj[id].currentSlide = pptviewobj[id].slideCount+1;
+				}
+			} 
+			else
+			{
+				pptviewobj[id].currentSlide = cwp->wParam - 255;
+				if(pptviewobj[id].currentSlide>pptviewobj[id].slideCount)
+					pptviewobj[id].slideCount = pptviewobj[id].currentSlide;
+			}
+		}
+		if((pptviewobj[id].state != PPT_CLOSED)&&(cwp->message==WM_CLOSE||cwp->message==WM_QUIT))
+			pptviewobj[id].state = PPT_CLOSING;
+	}
+	return CallNextHookEx(hook,nCode,wParam,lParam); 
+}
+
+VOID CaptureAndSaveWindow(HWND hWnd, CHAR* filename)
+{
+	HBITMAP hBmp;
+	if ((hBmp = CaptureWindow(hWnd)) == NULL) 
+		return;
+
+	RECT client;
+	GetClientRect (hWnd, &client);
+	UINT uiBytesPerRow = 3 * client.right; // RGB takes 24 bits
+	UINT uiRemainderForPadding;
+
+	if ((uiRemainderForPadding = uiBytesPerRow % sizeof (DWORD)) > 0) 
+		uiBytesPerRow += (sizeof (DWORD) - uiRemainderForPadding);
+
+	UINT uiBytesPerAllRows = uiBytesPerRow * client.bottom;
+	PBYTE pDataBits;
+
+	if ((pDataBits = new BYTE [uiBytesPerAllRows]) != NULL) 
+	{
+		BITMAPINFOHEADER bmi = {0};
+		BITMAPFILEHEADER bmf = {0};
+
+		// Prepare to get the data out of HBITMAP:
+		bmi.biSize = sizeof (bmi);
+		bmi.biPlanes = 1;
+		bmi.biBitCount = 24;
+		bmi.biHeight = client.bottom;
+		bmi.biWidth = client.right;
+
+		// Get it:
+		HDC hDC = GetDC (hWnd);
+		GetDIBits (hDC, hBmp, 0, client.bottom, pDataBits, 
+					(BITMAPINFO*) &bmi, DIB_RGB_COLORS);
+		ReleaseDC (hWnd, hDC);
+
+		// Fill the file header:
+		bmf.bfOffBits = sizeof (bmf) + sizeof (bmi);
+		bmf.bfSize = bmf.bfOffBits + uiBytesPerAllRows;
+		bmf.bfType = 0x4D42;
+
+		// Writing:
+		FILE* pFile;
+		int err = fopen_s(&pFile, filename, "wb");
+		if (err == 0) 
+		{
+			fwrite (&bmf, sizeof (bmf), 1, pFile);
+			fwrite (&bmi, sizeof (bmi), 1, pFile);
+			fwrite (pDataBits, sizeof (BYTE), uiBytesPerAllRows, pFile);
+			fclose (pFile);
+		} 
+		delete [] pDataBits;
+	}
+	DeleteObject (hBmp);
+}
+HBITMAP CaptureWindow (HWND hWnd) {
+	HDC hDC;
+	BOOL bOk = FALSE;
+	HBITMAP hImage = NULL;
+
+	hDC = GetDC (hWnd);
+	RECT rcClient;
+	GetClientRect (hWnd, &rcClient);
+	if ((hImage = CreateCompatibleBitmap (hDC, rcClient.right, rcClient.bottom)) != NULL) 
+	{
+		HDC hMemDC;
+		HBITMAP hDCBmp;
+
+		if ((hMemDC = CreateCompatibleDC (hDC)) != NULL) 
+		{
+			hDCBmp = (HBITMAP) SelectObject (hMemDC, hImage);
+			HMODULE hLib = LoadLibrary("User32");
+			// PrintWindow works for windows outside displayable area
+			// but was only introduced in WinXP. BitBlt requires the window to be topmost 
+			// and within the viewable area of the display
+			if(GetProcAddress(hLib, "PrintWindow")==NULL)
+			{
+				SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE); 
+				BitBlt (hMemDC, 0, 0, rcClient.right, rcClient.bottom, hDC, 0, 0, SRCCOPY);
+				SetWindowPos(hWnd, HWND_NOTOPMOST, -32000, -32000, 0, 0, SWP_NOSIZE); 
+			}
+			else
+			{
+				PrintWindow(hWnd, hMemDC, 0);
+			}
+			SelectObject (hMemDC, hDCBmp);
+			DeleteDC (hMemDC);
+			bOk = TRUE;
+		}
+	}
+	ReleaseDC (hWnd, hDC);
+	if (! bOk) 
+	{
+		if (hImage) 
+		{
+			DeleteObject (hImage);
+			hImage = NULL;
+		}
+	}
+	return hImage;
+}

=== modified file 'openlp/plugins/presentations/lib/pptviewlib/pptviewlib.h'
--- openlp/plugins/presentations/lib/pptviewlib/pptviewlib.h	2008-12-10 20:40:18 +0000
+++ openlp/plugins/presentations/lib/pptviewlib/pptviewlib.h	2009-09-12 18:14:09 +0000
@@ -1,54 +1,54 @@
-
-#define DllExport extern "C"  __declspec( dllexport ) 
-
-enum PPTVIEWSTATE { PPT_CLOSED, PPT_STARTED, PPT_OPENED, PPT_LOADED, PPT_CLOSING};
-
-DllExport int OpenPPT(char *filename, HWND hParentWnd, RECT rect, char *previewpath);
-DllExport void ClosePPT(int id);
-DllExport int GetCurrentSlide(int id);
-DllExport int GetSlideCount(int id);
-DllExport void NextStep(int id);
-DllExport void PrevStep(int id);
-DllExport void GotoSlide(int id, int slideno);
-DllExport void RestartShow(int id);
-DllExport void Blank(int id);
-DllExport void Unblank(int id);
-DllExport void Stop(int id);
-DllExport void Resume(int id);
-DllExport void SetDebug(BOOL onoff);
-
-LRESULT CALLBACK CbtProc(int nCode, WPARAM wParam, LPARAM lParam);
-LRESULT CALLBACK CwpProc(int nCode, WPARAM wParam, LPARAM lParam);
-LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam);
-BOOL GetPPTViewerPath(char *pptviewerpath, int strsize);
-HBITMAP CaptureWindow (HWND hWnd);
-VOID SaveBitmap (CHAR* filename, HBITMAP hBmp) ;
-VOID CaptureAndSaveWindow(HWND hWnd, CHAR* filename);
-BOOL GetPPTInfo(int id);
-BOOL SavePPTInfo(int id);
-
-
-void Unhook(int id);
-
-#define MAX_PPTOBJS 50
-
-struct PPTVIEWOBJ 
-{
-	HHOOK hook;
-	HHOOK mhook;
-	HWND hWnd;
-	HWND hWnd2;
-	HWND hParentWnd;
-	HANDLE hProcess;
-	HANDLE hThread;
-	DWORD dwProcessId;
-	DWORD dwThreadId;
-	RECT rect;
-	int slideCount;
-	int currentSlide;
-	int firstSlideSteps;
-	int steps;
-	char filename[MAX_PATH];
-	char previewpath[MAX_PATH];
-	PPTVIEWSTATE state;
+
+#define DllExport extern "C"  __declspec( dllexport ) 
+
+enum PPTVIEWSTATE { PPT_CLOSED, PPT_STARTED, PPT_OPENED, PPT_LOADED, PPT_CLOSING};
+
+DllExport int OpenPPT(char *filename, HWND hParentWnd, RECT rect, char *previewpath);
+DllExport void ClosePPT(int id);
+DllExport int GetCurrentSlide(int id);
+DllExport int GetSlideCount(int id);
+DllExport void NextStep(int id);
+DllExport void PrevStep(int id);
+DllExport void GotoSlide(int id, int slideno);
+DllExport void RestartShow(int id);
+DllExport void Blank(int id);
+DllExport void Unblank(int id);
+DllExport void Stop(int id);
+DllExport void Resume(int id);
+DllExport void SetDebug(BOOL onoff);
+
+LRESULT CALLBACK CbtProc(int nCode, WPARAM wParam, LPARAM lParam);
+LRESULT CALLBACK CwpProc(int nCode, WPARAM wParam, LPARAM lParam);
+LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam);
+BOOL GetPPTViewerPath(char *pptviewerpath, int strsize);
+HBITMAP CaptureWindow (HWND hWnd);
+VOID SaveBitmap (CHAR* filename, HBITMAP hBmp) ;
+VOID CaptureAndSaveWindow(HWND hWnd, CHAR* filename);
+BOOL GetPPTInfo(int id);
+BOOL SavePPTInfo(int id);
+
+
+void Unhook(int id);
+
+#define MAX_PPTOBJS 50
+
+struct PPTVIEWOBJ 
+{
+	HHOOK hook;
+	HHOOK mhook;
+	HWND hWnd;
+	HWND hWnd2;
+	HWND hParentWnd;
+	HANDLE hProcess;
+	HANDLE hThread;
+	DWORD dwProcessId;
+	DWORD dwThreadId;
+	RECT rect;
+	int slideCount;
+	int currentSlide;
+	int firstSlideSteps;
+	int steps;
+	char filename[MAX_PATH];
+	char previewpath[MAX_PATH];
+	PPTVIEWSTATE state;
 };
\ No newline at end of file

=== modified file 'openlp/plugins/presentations/lib/pptviewlib/pptviewlib.vcproj'
--- openlp/plugins/presentations/lib/pptviewlib/pptviewlib.vcproj	2008-12-10 20:40:18 +0000
+++ openlp/plugins/presentations/lib/pptviewlib/pptviewlib.vcproj	2009-09-12 18:14:09 +0000
@@ -1,203 +1,203 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="9.00"
-	Name="pptviewlib"
-	ProjectGUID="{04CC20D1-DC5A-4189-8181-4011E3C21DCF}"
-	RootNamespace="pptviewlib"
-	Keyword="Win32Proj"
-	TargetFrameworkVersion="196613"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
-			IntermediateDirectory="$(ConfigurationName)"
-			ConfigurationType="2"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PPTVIEWLIB_EXPORTS"
-				MinimalRebuild="true"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				DebugInformationFormat="4"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				LinkIncremental="2"
-				ModuleDefinitionFile=""
-				GenerateDebugInformation="true"
-				SubSystem="2"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
-			IntermediateDirectory="$(ConfigurationName)"
-			ConfigurationType="2"
-			CharacterSet="1"
-			WholeProgramOptimization="1"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="2"
-				EnableIntrinsicFunctions="true"
-				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PPTVIEWLIB_EXPORTS"
-				RuntimeLibrary="2"
-				EnableFunctionLevelLinking="true"
-				UsePrecompiledHeader="2"
-				WarningLevel="3"
-				DebugInformationFormat="3"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				LinkIncremental="1"
-				ModuleDefinitionFile="pptviewlib.def"
-				GenerateDebugInformation="true"
-				SubSystem="2"
-				OptimizeReferences="2"
-				EnableCOMDATFolding="2"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<Filter
-			Name="Source Files"
-			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
-			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
-			>
-			<File
-				RelativePath=".\pptviewlib.cpp"
-				>
-			</File>
-			<File
-				RelativePath=".\README.TXT"
-				>
-			</File>
-		</Filter>
-		<Filter
-			Name="Header Files"
-			Filter="h;hpp;hxx;hm;inl;inc;xsd"
-			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
-			>
-			<File
-				RelativePath=".\pptviewlib.h"
-				>
-			</File>
-		</Filter>
-		<Filter
-			Name="Resource Files"
-			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
-			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
-			>
-		</Filter>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="pptviewlib"
+	ProjectGUID="{04CC20D1-DC5A-4189-8181-4011E3C21DCF}"
+	RootNamespace="pptviewlib"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PPTVIEWLIB_EXPORTS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				UsePrecompiledHeader="0"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				ModuleDefinitionFile=""
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="2"
+			CharacterSet="1"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				EnableIntrinsicFunctions="true"
+				PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PPTVIEWLIB_EXPORTS"
+				RuntimeLibrary="2"
+				EnableFunctionLevelLinking="true"
+				UsePrecompiledHeader="2"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				ModuleDefinitionFile="pptviewlib.def"
+				GenerateDebugInformation="true"
+				SubSystem="2"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath=".\pptviewlib.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\README.TXT"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath=".\pptviewlib.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>


Follow ups