Pathlib changes in presentation plugin

This commit is contained in:
Philip Ridout 2017-09-07 22:52:39 +01:00
parent 24358337e7
commit f0e7381f5c
10 changed files with 82 additions and 70 deletions

View File

@ -310,7 +310,7 @@ class OpenLPWizard(QtWidgets.QWizard, RegistryProperties):
""" """
folder_path = FileDialog.getExistingDirectory( folder_path = FileDialog.getExistingDirectory(
self, title, Settings().value(self.plugin.settings_section + '/' + setting_name), self, title, Settings().value(self.plugin.settings_section + '/' + setting_name),
QtWidgets.QFileDialog.ShowDirsOnly) FileDialog.ShowDirsOnly)
if folder_path: if folder_path:
editbox.setText(str(folder_path)) editbox.setText(str(folder_path))
Settings().setValue(self.plugin.settings_section + '/' + setting_name, folder_path) Settings().setValue(self.plugin.settings_section + '/' + setting_name, folder_path)

View File

@ -42,6 +42,7 @@ from openlp.core.common.actions import ActionList, CategoryOrder
from openlp.core.common.path import Path, path_to_str, str_to_path from openlp.core.common.path import Path, path_to_str, str_to_path
from openlp.core.common.versionchecker import get_application_version from openlp.core.common.versionchecker import get_application_version
from openlp.core.lib import Renderer, PluginManager, ImageManager, PluginStatus, ScreenList, build_icon from openlp.core.lib import Renderer, PluginManager, ImageManager, PluginStatus, ScreenList, build_icon
from openlp.core.lib.shutil import copyfile
from openlp.core.lib.ui import create_action from openlp.core.lib.ui import create_action
from openlp.core.ui import AboutForm, SettingsForm, ServiceManager, ThemeManager, LiveController, PluginForm, \ from openlp.core.ui import AboutForm, SettingsForm, ServiceManager, ThemeManager, LiveController, PluginForm, \
ShortcutListForm, FormattingTagForm, PreviewController ShortcutListForm, FormattingTagForm, PreviewController
@ -848,12 +849,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
QtWidgets.QMessageBox.No) QtWidgets.QMessageBox.No)
if answer == QtWidgets.QMessageBox.No: if answer == QtWidgets.QMessageBox.No:
return return
import_file_name, filter_used = QtWidgets.QFileDialog.getOpenFileName( import_file_path, filter_used = FileDialog.getOpenFileName(
self, self,
translate('OpenLP.MainWindow', 'Import settings'), translate('OpenLP.MainWindow', 'Import settings'),
'', None,
translate('OpenLP.MainWindow', 'OpenLP Settings (*.conf)')) translate('OpenLP.MainWindow', 'OpenLP Settings (*.conf)'))
if not import_file_name: if import_file_path is None:
return return
setting_sections = [] setting_sections = []
# Add main sections. # Add main sections.
@ -871,12 +872,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
# Add plugin sections. # Add plugin sections.
setting_sections.extend([plugin.name for plugin in self.plugin_manager.plugins]) setting_sections.extend([plugin.name for plugin in self.plugin_manager.plugins])
# Copy the settings file to the tmp dir, because we do not want to change the original one. # Copy the settings file to the tmp dir, because we do not want to change the original one.
temp_directory = os.path.join(str(gettempdir()), 'openlp') temp_dir_path = Path(gettempdir(), 'openlp')
check_directory_exists(Path(temp_directory)) check_directory_exists(temp_dir_path)
temp_config = os.path.join(temp_directory, os.path.basename(import_file_name)) temp_config_path = temp_dir_path / import_file_path.name
shutil.copyfile(import_file_name, temp_config) copyfile(import_file_path, temp_config_path)
settings = Settings() settings = Settings()
import_settings = Settings(temp_config, Settings.IniFormat) import_settings = Settings(str(temp_config_path), Settings.IniFormat)
log.info('hook upgrade_plugin_settings') log.info('hook upgrade_plugin_settings')
self.plugin_manager.hook_upgrade_plugin_settings(import_settings) self.plugin_manager.hook_upgrade_plugin_settings(import_settings)
@ -920,7 +921,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
settings.setValue('{key}'.format(key=section_key), value) settings.setValue('{key}'.format(key=section_key), value)
now = datetime.now() now = datetime.now()
settings.beginGroup(self.header_section) settings.beginGroup(self.header_section)
settings.setValue('file_imported', import_file_name) settings.setValue('file_imported', import_file_path)
settings.setValue('file_date_imported', now.strftime("%Y-%m-%d %H:%M")) settings.setValue('file_date_imported', now.strftime("%Y-%m-%d %H:%M"))
settings.endGroup() settings.endGroup()
settings.sync() settings.sync()

View File

@ -255,10 +255,10 @@ class ImpressDocument(PresentationDocument):
if self.check_thumbnails(): if self.check_thumbnails():
return return
if is_win(): if is_win():
thumb_dir_url = 'file:///' + self.get_temp_folder().replace('\\', '/') \ thumb_dir_url = 'file:///' + str(self.get_temp_folder()).replace('\\', '/') \
.replace(':', '|').replace(' ', '%20') .replace(':', '|').replace(' ', '%20')
else: else:
thumb_dir_url = uno.systemPathToFileUrl(self.get_temp_folder()) thumb_dir_url = uno.systemPathToFileUrl(str(self.get_temp_folder()))
properties = [] properties = []
properties.append(self.create_property('FilterName', 'impress_png_Export')) properties.append(self.create_property('FilterName', 'impress_png_Export'))
properties = tuple(properties) properties = tuple(properties)
@ -266,17 +266,18 @@ class ImpressDocument(PresentationDocument):
pages = doc.getDrawPages() pages = doc.getDrawPages()
if not pages: if not pages:
return return
if not os.path.isdir(self.get_temp_folder()): temp_folder_path = self.get_temp_folder()
os.makedirs(self.get_temp_folder()) if not temp_folder_path.isdir():
temp_folder_path.mkdir()
for index in range(pages.getCount()): for index in range(pages.getCount()):
page = pages.getByIndex(index) page = pages.getByIndex(index)
doc.getCurrentController().setCurrentPage(page) doc.getCurrentController().setCurrentPage(page)
url_path = '{path}/{name}.png'.format(path=thumb_dir_url, name=str(index + 1)) url_path = '{path}/{name}.png'.format(path=thumb_dir_url, name=str(index + 1))
path = os.path.join(self.get_temp_folder(), str(index + 1) + '.png') path = temp_folder_path / '{number).png'.format(number=index + 1)
try: try:
doc.storeToURL(url_path, properties) doc.storeToURL(url_path, properties)
self.convert_thumbnail(path, index + 1) self.convert_thumbnail(str(path), index + 1)
delete_file(Path(path)) delete_file(path)
except ErrorCodeIOException as exception: except ErrorCodeIOException as exception:
log.exception('ERROR! ErrorCodeIOException {error:d}'.format(error=exception.ErrCode)) log.exception('ERROR! ErrorCodeIOException {error:d}'.format(error=exception.ErrCode))
except: except:

View File

@ -187,7 +187,7 @@ class PresentationMediaItem(MediaManagerItem):
if controller_name: if controller_name:
controller = self.controllers[controller_name] controller = self.controllers[controller_name]
doc = controller.add_document(file) doc = controller.add_document(file)
thumb = os.path.join(doc.get_thumbnail_folder(), 'icon.png') thumb = str(doc.get_thumbnail_folder() / 'icon.png')
preview = doc.get_thumbnail_path(1, True) preview = doc.get_thumbnail_path(1, True)
if not preview and not initial_load: if not preview and not initial_load:
doc.load_presentation() doc.load_presentation()
@ -304,17 +304,17 @@ class PresentationMediaItem(MediaManagerItem):
controller = self.controllers[processor] controller = self.controllers[processor]
service_item.processor = None service_item.processor = None
doc = controller.add_document(filename) doc = controller.add_document(filename)
if doc.get_thumbnail_path(1, True) is None or not os.path.isfile( if doc.get_thumbnail_path(1, True) is None or \
os.path.join(doc.get_temp_folder(), 'mainslide001.png')): not (doc.get_temp_folder() / 'mainslide001.png').is_file():
doc.load_presentation() doc.load_presentation()
i = 1 i = 1
image = os.path.join(doc.get_temp_folder(), 'mainslide{number:0>3d}.png'.format(number=i)) image = str(doc.get_temp_folder() / 'mainslide{number:0>3d}.png'.format(number=i))
thumbnail = os.path.join(doc.get_thumbnail_folder(), 'slide%d.png' % i) thumbnail = str(doc.get_thumbnail_folder() / 'slide{number:d}.png'.format(number=i))
while os.path.isfile(image): while os.path.isfile(image):
service_item.add_from_image(image, name, thumbnail=thumbnail) service_item.add_from_image(image, name, thumbnail=thumbnail)
i += 1 i += 1
image = os.path.join(doc.get_temp_folder(), 'mainslide{number:0>3d}.png'.format(number=i)) image = str(doc.get_temp_folder() / 'mainslide{number:0>3d}.png'.format(number=i))
thumbnail = os.path.join(doc.get_thumbnail_folder(), 'slide{number:d}.png'.format(number=i)) thumbnail = str(doc.get_thumbnail_folder() / 'slide{number:d}.png'.format(number=i))
service_item.add_capability(ItemCapabilities.HasThumbnails) service_item.add_capability(ItemCapabilities.HasThumbnails)
doc.close_presentation() doc.close_presentation()
return True return True

View File

@ -240,46 +240,46 @@ class PdfDocument(PresentationDocument):
:return: True is loading succeeded, otherwise False. :return: True is loading succeeded, otherwise False.
""" """
log.debug('load_presentation pdf') log.debug('load_presentation pdf')
temp_dir_path = self.get_temp_folder()
# Check if the images has already been created, and if yes load them # Check if the images has already been created, and if yes load them
if os.path.isfile(os.path.join(self.get_temp_folder(), 'mainslide001.png')): if (temp_dir_path / 'mainslide001.png').is_file():
created_files = sorted(os.listdir(self.get_temp_folder())) created_files = sorted(temp_dir_path.glob('*'))
for fn in created_files: for image_path in created_files:
if os.path.isfile(os.path.join(self.get_temp_folder(), fn)): if image_path.is_file():
self.image_files.append(os.path.join(self.get_temp_folder(), fn)) self.image_files.append(str(image_path))
self.num_pages = len(self.image_files) self.num_pages = len(self.image_files)
return True return True
size = ScreenList().current['size'] size = ScreenList().current['size']
# Generate images from PDF that will fit the frame. # Generate images from PDF that will fit the frame.
runlog = '' runlog = ''
try: try:
if not os.path.isdir(self.get_temp_folder()): if not temp_dir_path.is_dir():
os.makedirs(self.get_temp_folder()) temp_dir_path.mkdir(parents=True)
# The %03d in the file name is handled by each binary # The %03d in the file name is handled by each binary
if self.controller.mudrawbin: if self.controller.mudrawbin:
log.debug('loading presentation using mudraw') log.debug('loading presentation using mudraw')
runlog = check_output([self.controller.mudrawbin, '-w', str(size.width()), '-h', str(size.height()), runlog = check_output([self.controller.mudrawbin, '-w', str(size.width()), '-h', str(size.height()),
'-o', os.path.join(self.get_temp_folder(), 'mainslide%03d.png'), self.file_path], '-o', str(temp_dir_path / 'mainslide%03d.png'), self.file_path],
startupinfo=self.startupinfo) startupinfo=self.startupinfo)
elif self.controller.mutoolbin: elif self.controller.mutoolbin:
log.debug('loading presentation using mutool') log.debug('loading presentation using mutool')
runlog = check_output([self.controller.mutoolbin, 'draw', '-w', str(size.width()), '-h', runlog = check_output([self.controller.mutoolbin, 'draw', '-w', str(size.width()), '-h',
str(size.height()), str(size.height()),
'-o', os.path.join(self.get_temp_folder(), 'mainslide%03d.png'), self.file_path], '-o', str(temp_dir_path / 'mainslide%03d.png'), self.file_path],
startupinfo=self.startupinfo) startupinfo=self.startupinfo)
elif self.controller.gsbin: elif self.controller.gsbin:
log.debug('loading presentation using gs') log.debug('loading presentation using gs')
resolution = self.gs_get_resolution(size) resolution = self.gs_get_resolution(size)
runlog = check_output([self.controller.gsbin, '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=png16m', runlog = check_output([self.controller.gsbin, '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=png16m',
'-r' + str(resolution), '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-r' + str(resolution), '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4',
'-sOutputFile=' + os.path.join(self.get_temp_folder(), 'mainslide%03d.png'), '-sOutputFile=' + str(temp_dir_path / 'mainslide%03d.png'),
self.file_path], startupinfo=self.startupinfo) self.file_path], startupinfo=self.startupinfo)
created_files = sorted(os.listdir(self.get_temp_folder())) created_files = sorted(temp_dir_path.glob('*'))
for fn in created_files: for image_path in created_files:
if os.path.isfile(os.path.join(self.get_temp_folder(), fn)): if image_path.is_file():
self.image_files.append(os.path.join(self.get_temp_folder(), fn)) self.image_files.append(str(image_path))
except Exception as e: except Exception:
log.debug(e) log.exception(runlog)
log.debug(runlog)
return False return False
self.num_pages = len(self.image_files) self.num_pages = len(self.image_files)
# Create thumbnails # Create thumbnails

View File

@ -177,7 +177,7 @@ class PowerpointDocument(PresentationDocument):
if not self.presentation.Slides(num + 1).SlideShowTransition.Hidden: if not self.presentation.Slides(num + 1).SlideShowTransition.Hidden:
self.index_map[key] = num + 1 self.index_map[key] = num + 1
self.presentation.Slides(num + 1).Export( self.presentation.Slides(num + 1).Export(
os.path.join(self.get_thumbnail_folder(), 'slide{key:d}.png'.format(key=key)), 'png', 320, 240) str(self.get_thumbnail_folder() / 'slide{key:d}.png'.format(key=key)), 'png', 320, 240)
key += 1 key += 1
self.slide_count = key - 1 self.slide_count = key - 1

View File

@ -121,17 +121,17 @@ class PptviewDocument(PresentationDocument):
the background PptView task started earlier. the background PptView task started earlier.
""" """
log.debug('LoadPresentation') log.debug('LoadPresentation')
temp_folder = self.get_temp_folder() temp_dir_path = self.get_temp_folder()
size = ScreenList().current['size'] size = ScreenList().current['size']
rect = RECT(size.x(), size.y(), size.right(), size.bottom()) rect = RECT(size.x(), size.y(), size.right(), size.bottom())
self.file_path = os.path.normpath(self.file_path) self.file_path = os.path.normpath(self.file_path)
preview_path = os.path.join(temp_folder, 'slide') preview_path = temp_dir_path / 'slide'
# Ensure that the paths are null terminated # Ensure that the paths are null terminated
byte_file_path = self.file_path.encode('utf-16-le') + b'\0' byte_file_path = self.file_path.encode('utf-16-le') + b'\0'
preview_path = preview_path.encode('utf-16-le') + b'\0' preview_file_name = str(preview_path).encode('utf-16-le') + b'\0'
if not os.path.isdir(temp_folder): if not temp_dir_path:
os.makedirs(temp_folder) temp_dir_path.mkdir(parents=True)
self.ppt_id = self.controller.process.OpenPPT(byte_file_path, None, rect, preview_path) self.ppt_id = self.controller.process.OpenPPT(byte_file_path, None, rect, preview_file_name)
if self.ppt_id >= 0: if self.ppt_id >= 0:
self.create_thumbnails() self.create_thumbnails()
self.stop_presentation() self.stop_presentation()

View File

@ -29,6 +29,7 @@ from PyQt5 import QtCore
from openlp.core.common import Registry, AppLocation, Settings, check_directory_exists, md5_hash from openlp.core.common import Registry, AppLocation, Settings, check_directory_exists, md5_hash
from openlp.core.common.path import Path from openlp.core.common.path import Path
from openlp.core.lib import create_thumb, validate_thumb from openlp.core.lib import create_thumb, validate_thumb
from openlp.core.lib.shutil import rmtree
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -99,7 +100,7 @@ class PresentationDocument(object):
""" """
self.slide_number = 0 self.slide_number = 0
self.file_path = name self.file_path = name
check_directory_exists(Path(self.get_thumbnail_folder())) check_directory_exists(self.get_thumbnail_folder())
def load_presentation(self): def load_presentation(self):
""" """
@ -116,10 +117,12 @@ class PresentationDocument(object):
a file, e.g. thumbnails a file, e.g. thumbnails
""" """
try: try:
if os.path.exists(self.get_thumbnail_folder()): thumbnail_folder_path = self.get_thumbnail_folder()
shutil.rmtree(self.get_thumbnail_folder()) temp_folder_path = self.get_temp_folder()
if os.path.exists(self.get_temp_folder()): if thumbnail_folder_path.exists():
shutil.rmtree(self.get_temp_folder()) rmtree(thumbnail_folder_path)
if temp_folder_path.exists():
rmtree(temp_folder_path)
except OSError: except OSError:
log.exception('Failed to delete presentation controller files') log.exception('Failed to delete presentation controller files')
@ -132,24 +135,30 @@ class PresentationDocument(object):
def get_thumbnail_folder(self): def get_thumbnail_folder(self):
""" """
The location where thumbnail images will be stored The location where thumbnail images will be stored
:return: The path to the thumbnail
:rtype: openlp.core.common.path.Path
""" """
# TODO: If statement can be removed when the upgrade path from 2.0.x to 2.2.x is no longer needed # TODO: If statement can be removed when the upgrade path from 2.0.x to 2.2.x is no longer needed
if Settings().value('presentations/thumbnail_scheme') == 'md5': if Settings().value('presentations/thumbnail_scheme') == 'md5':
folder = md5_hash(self.file_path.encode('utf-8')) folder = md5_hash(self.file_path.encode('utf-8'))
else: else:
folder = self.get_file_name() folder = self.get_file_name()
return os.path.join(self.controller.thumbnail_folder, folder) return Path(self.controller.thumbnail_folder, folder)
def get_temp_folder(self): def get_temp_folder(self):
""" """
The location where thumbnail images will be stored The location where thumbnail images will be stored
:return: The path to the temporary file folder
:rtype: openlp.core.common.path.Path
""" """
# TODO: If statement can be removed when the upgrade path from 2.0.x to 2.2.x is no longer needed # TODO: If statement can be removed when the upgrade path from 2.0.x to 2.2.x is no longer needed
if Settings().value('presentations/thumbnail_scheme') == 'md5': if Settings().value('presentations/thumbnail_scheme') == 'md5':
folder = md5_hash(self.file_path.encode('utf-8')) folder = md5_hash(self.file_path.encode('utf-8'))
else: else:
folder = folder = self.get_file_name() folder = self.get_file_name()
return os.path.join(self.controller.temp_folder, folder) return Path(self.controller.temp_folder, folder)
def check_thumbnails(self): def check_thumbnails(self):
""" """
@ -251,15 +260,17 @@ class PresentationDocument(object):
thumb_path = self.get_thumbnail_path(idx, False) thumb_path = self.get_thumbnail_path(idx, False)
create_thumb(file, thumb_path, False, QtCore.QSize(-1, 360)) create_thumb(file, thumb_path, False, QtCore.QSize(-1, 360))
def get_thumbnail_path(self, slide_no, check_exists): def get_thumbnail_path(self, slide_no, check_exists=True):
""" """
Returns an image path containing a preview for the requested slide Returns an image path containing a preview for the requested slide
:param slide_no: The slide an image is required for, starting at 1 :param int slide_no: The slide an image is required for, starting at 1
:param check_exists: :param bool check_exists: Check if the generated path exists
:return: The path, or None if the :param:`check_exists` is True and the file does not exist
:rtype: openlp.core.common.path.Path, None
""" """
path = os.path.join(self.get_thumbnail_folder(), self.controller.thumbnail_prefix + str(slide_no) + '.png') path = self.get_thumbnail_folder() / (self.controller.thumbnail_prefix + str(slide_no) + '.png')
if os.path.isfile(path) or not check_exists: if path.is_file() or not check_exists:
return path return path
else: else:
return None return None
@ -304,7 +315,7 @@ class PresentationDocument(object):
""" """
titles = [] titles = []
notes = [] notes = []
titles_file = os.path.join(self.get_thumbnail_folder(), 'titles.txt') titles_file = str(self.get_thumbnail_folder() / 'titles.txt')
if os.path.exists(titles_file): if os.path.exists(titles_file):
try: try:
with open(titles_file, encoding='utf-8') as fi: with open(titles_file, encoding='utf-8') as fi:
@ -313,7 +324,7 @@ class PresentationDocument(object):
log.exception('Failed to open/read existing titles file') log.exception('Failed to open/read existing titles file')
titles = [] titles = []
for slide_no, title in enumerate(titles, 1): for slide_no, title in enumerate(titles, 1):
notes_file = os.path.join(self.get_thumbnail_folder(), 'slideNotes{number:d}.txt'.format(number=slide_no)) notes_file = str(self.get_thumbnail_folder() / 'slideNotes{number:d}.txt'.format(number=slide_no))
note = '' note = ''
if os.path.exists(notes_file): if os.path.exists(notes_file):
try: try:
@ -331,14 +342,13 @@ class PresentationDocument(object):
and notes to the slideNote%.txt and notes to the slideNote%.txt
""" """
if titles: if titles:
titles_file = os.path.join(self.get_thumbnail_folder(), 'titles.txt') titles_path = self.get_thumbnail_folder() / 'titles.txt'
with open(titles_file, mode='wt', encoding='utf-8') as fo: with titles_path.open(mode='wt', encoding='utf-8') as fo:
fo.writelines(titles) fo.writelines(titles)
if notes: if notes:
for slide_no, note in enumerate(notes, 1): for slide_no, note in enumerate(notes, 1):
notes_file = os.path.join(self.get_thumbnail_folder(), notes_path = self.get_thumbnail_folder() / 'slideNotes{number:d}.txt'.format(number=slide_no)
'slideNotes{number:d}.txt'.format(number=slide_no)) with notes_path.open(mode='wt', encoding='utf-8') as fn:
with open(notes_file, mode='wt', encoding='utf-8') as fn:
fn.write(note) fn.write(note)

View File

@ -48,7 +48,7 @@ def report_song_list():
Path(translate('SongPlugin.ReportSongList', 'song_extract.csv')), Path(translate('SongPlugin.ReportSongList', 'song_extract.csv')),
translate('SongPlugin.ReportSongList', 'CSV format (*.csv)')) translate('SongPlugin.ReportSongList', 'CSV format (*.csv)'))
if not report_file_path: if report_file_path is None:
main_window.error_message( main_window.error_message(
translate('SongPlugin.ReportSongList', 'Output Path Not Selected'), translate('SongPlugin.ReportSongList', 'Output Path Not Selected'),
translate('SongPlugin.ReportSongList', 'You have not set a valid output location for your report. \n' translate('SongPlugin.ReportSongList', 'You have not set a valid output location for your report. \n'

View File

@ -103,7 +103,7 @@ class TestExceptionForm(TestMixin, TestCase):
os.remove(self.tempfile) os.remove(self.tempfile)
@patch("openlp.core.ui.exceptionform.Ui_ExceptionDialog") @patch("openlp.core.ui.exceptionform.Ui_ExceptionDialog")
@patch("openlp.core.ui.exceptionform.QtWidgets.QFileDialog") @patch("openlp.core.ui.exceptionform.FileDialog")
@patch("openlp.core.ui.exceptionform.QtCore.QUrl") @patch("openlp.core.ui.exceptionform.QtCore.QUrl")
@patch("openlp.core.ui.exceptionform.QtCore.QUrlQuery.addQueryItem") @patch("openlp.core.ui.exceptionform.QtCore.QUrlQuery.addQueryItem")
@patch("openlp.core.ui.exceptionform.Qt") @patch("openlp.core.ui.exceptionform.Qt")