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(
self, title, Settings().value(self.plugin.settings_section + '/' + setting_name),
QtWidgets.QFileDialog.ShowDirsOnly)
FileDialog.ShowDirsOnly)
if folder_path:
editbox.setText(str(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.versionchecker import get_application_version
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.ui import AboutForm, SettingsForm, ServiceManager, ThemeManager, LiveController, PluginForm, \
ShortcutListForm, FormattingTagForm, PreviewController
@ -848,12 +849,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
QtWidgets.QMessageBox.No)
if answer == QtWidgets.QMessageBox.No:
return
import_file_name, filter_used = QtWidgets.QFileDialog.getOpenFileName(
import_file_path, filter_used = FileDialog.getOpenFileName(
self,
translate('OpenLP.MainWindow', 'Import settings'),
'',
None,
translate('OpenLP.MainWindow', 'OpenLP Settings (*.conf)'))
if not import_file_name:
if import_file_path is None:
return
setting_sections = []
# Add main sections.
@ -871,12 +872,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
# Add plugin sections.
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.
temp_directory = os.path.join(str(gettempdir()), 'openlp')
check_directory_exists(Path(temp_directory))
temp_config = os.path.join(temp_directory, os.path.basename(import_file_name))
shutil.copyfile(import_file_name, temp_config)
temp_dir_path = Path(gettempdir(), 'openlp')
check_directory_exists(temp_dir_path)
temp_config_path = temp_dir_path / import_file_path.name
copyfile(import_file_path, temp_config_path)
settings = Settings()
import_settings = Settings(temp_config, Settings.IniFormat)
import_settings = Settings(str(temp_config_path), Settings.IniFormat)
log.info('hook upgrade_plugin_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)
now = datetime.now()
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.endGroup()
settings.sync()

View File

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

View File

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

View File

@ -240,46 +240,46 @@ class PdfDocument(PresentationDocument):
:return: True is loading succeeded, otherwise False.
"""
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
if os.path.isfile(os.path.join(self.get_temp_folder(), 'mainslide001.png')):
created_files = sorted(os.listdir(self.get_temp_folder()))
for fn in created_files:
if os.path.isfile(os.path.join(self.get_temp_folder(), fn)):
self.image_files.append(os.path.join(self.get_temp_folder(), fn))
if (temp_dir_path / 'mainslide001.png').is_file():
created_files = sorted(temp_dir_path.glob('*'))
for image_path in created_files:
if image_path.is_file():
self.image_files.append(str(image_path))
self.num_pages = len(self.image_files)
return True
size = ScreenList().current['size']
# Generate images from PDF that will fit the frame.
runlog = ''
try:
if not os.path.isdir(self.get_temp_folder()):
os.makedirs(self.get_temp_folder())
if not temp_dir_path.is_dir():
temp_dir_path.mkdir(parents=True)
# The %03d in the file name is handled by each binary
if self.controller.mudrawbin:
log.debug('loading presentation using mudraw')
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)
elif self.controller.mutoolbin:
log.debug('loading presentation using mutool')
runlog = check_output([self.controller.mutoolbin, 'draw', '-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)
elif self.controller.gsbin:
log.debug('loading presentation using gs')
resolution = self.gs_get_resolution(size)
runlog = check_output([self.controller.gsbin, '-dSAFER', '-dNOPAUSE', '-dBATCH', '-sDEVICE=png16m',
'-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)
created_files = sorted(os.listdir(self.get_temp_folder()))
for fn in created_files:
if os.path.isfile(os.path.join(self.get_temp_folder(), fn)):
self.image_files.append(os.path.join(self.get_temp_folder(), fn))
except Exception as e:
log.debug(e)
log.debug(runlog)
created_files = sorted(temp_dir_path.glob('*'))
for image_path in created_files:
if image_path.is_file():
self.image_files.append(str(image_path))
except Exception:
log.exception(runlog)
return False
self.num_pages = len(self.image_files)
# Create thumbnails

View File

@ -177,7 +177,7 @@ class PowerpointDocument(PresentationDocument):
if not self.presentation.Slides(num + 1).SlideShowTransition.Hidden:
self.index_map[key] = num + 1
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
self.slide_count = key - 1

View File

@ -121,17 +121,17 @@ class PptviewDocument(PresentationDocument):
the background PptView task started earlier.
"""
log.debug('LoadPresentation')
temp_folder = self.get_temp_folder()
temp_dir_path = self.get_temp_folder()
size = ScreenList().current['size']
rect = RECT(size.x(), size.y(), size.right(), size.bottom())
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
byte_file_path = self.file_path.encode('utf-16-le') + b'\0'
preview_path = preview_path.encode('utf-16-le') + b'\0'
if not os.path.isdir(temp_folder):
os.makedirs(temp_folder)
self.ppt_id = self.controller.process.OpenPPT(byte_file_path, None, rect, preview_path)
preview_file_name = str(preview_path).encode('utf-16-le') + b'\0'
if not temp_dir_path:
temp_dir_path.mkdir(parents=True)
self.ppt_id = self.controller.process.OpenPPT(byte_file_path, None, rect, preview_file_name)
if self.ppt_id >= 0:
self.create_thumbnails()
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.path import Path
from openlp.core.lib import create_thumb, validate_thumb
from openlp.core.lib.shutil import rmtree
log = logging.getLogger(__name__)
@ -99,7 +100,7 @@ class PresentationDocument(object):
"""
self.slide_number = 0
self.file_path = name
check_directory_exists(Path(self.get_thumbnail_folder()))
check_directory_exists(self.get_thumbnail_folder())
def load_presentation(self):
"""
@ -116,10 +117,12 @@ class PresentationDocument(object):
a file, e.g. thumbnails
"""
try:
if os.path.exists(self.get_thumbnail_folder()):
shutil.rmtree(self.get_thumbnail_folder())
if os.path.exists(self.get_temp_folder()):
shutil.rmtree(self.get_temp_folder())
thumbnail_folder_path = self.get_thumbnail_folder()
temp_folder_path = self.get_temp_folder()
if thumbnail_folder_path.exists():
rmtree(thumbnail_folder_path)
if temp_folder_path.exists():
rmtree(temp_folder_path)
except OSError:
log.exception('Failed to delete presentation controller files')
@ -132,24 +135,30 @@ class PresentationDocument(object):
def get_thumbnail_folder(self):
"""
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
if Settings().value('presentations/thumbnail_scheme') == 'md5':
folder = md5_hash(self.file_path.encode('utf-8'))
else:
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):
"""
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
if Settings().value('presentations/thumbnail_scheme') == 'md5':
folder = md5_hash(self.file_path.encode('utf-8'))
else:
folder = folder = self.get_file_name()
return os.path.join(self.controller.temp_folder, folder)
folder = self.get_file_name()
return Path(self.controller.temp_folder, folder)
def check_thumbnails(self):
"""
@ -251,15 +260,17 @@ class PresentationDocument(object):
thumb_path = self.get_thumbnail_path(idx, False)
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
:param slide_no: The slide an image is required for, starting at 1
:param check_exists:
:param int slide_no: The slide an image is required for, starting at 1
: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')
if os.path.isfile(path) or not check_exists:
path = self.get_thumbnail_folder() / (self.controller.thumbnail_prefix + str(slide_no) + '.png')
if path.is_file() or not check_exists:
return path
else:
return None
@ -304,7 +315,7 @@ class PresentationDocument(object):
"""
titles = []
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):
try:
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')
titles = []
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 = ''
if os.path.exists(notes_file):
try:
@ -331,14 +342,13 @@ class PresentationDocument(object):
and notes to the slideNote%.txt
"""
if titles:
titles_file = os.path.join(self.get_thumbnail_folder(), 'titles.txt')
with open(titles_file, mode='wt', encoding='utf-8') as fo:
titles_path = self.get_thumbnail_folder() / 'titles.txt'
with titles_path.open(mode='wt', encoding='utf-8') as fo:
fo.writelines(titles)
if notes:
for slide_no, note in enumerate(notes, 1):
notes_file = os.path.join(self.get_thumbnail_folder(),
'slideNotes{number:d}.txt'.format(number=slide_no))
with open(notes_file, mode='wt', encoding='utf-8') as fn:
notes_path = self.get_thumbnail_folder() / 'slideNotes{number:d}.txt'.format(number=slide_no)
with notes_path.open(mode='wt', encoding='utf-8') as fn:
fn.write(note)

View File

@ -48,7 +48,7 @@ def report_song_list():
Path(translate('SongPlugin.ReportSongList', 'song_extract.csv')),
translate('SongPlugin.ReportSongList', 'CSV format (*.csv)'))
if not report_file_path:
if report_file_path is None:
main_window.error_message(
translate('SongPlugin.ReportSongList', 'Output Path Not Selected'),
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)
@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.QUrlQuery.addQueryItem")
@patch("openlp.core.ui.exceptionform.Qt")