Moar pathlib refactors

This commit is contained in:
Phill Ridout 2017-11-18 22:37:24 +00:00
parent 9196db5af0
commit f07d6e736c
6 changed files with 53 additions and 76 deletions

View File

@ -172,15 +172,3 @@ def main_image(request):
'slide_image': 'data:image/png;base64,' + str(image_to_byte(live_controller.slide_image))
}
return {'results': result}
def get_content_type(file_name):
"""
Examines the extension of the file and determines what the content_type should be, defaults to text/plain
Returns the extension and the content_type
:param file_name: name of file
"""
ext = os.path.splitext(file_name)[1]
content_type = FILE_TYPES.get(ext, 'text/plain')
return ext, content_type

View File

@ -318,10 +318,10 @@ class MediaManagerItem(QtWidgets.QWidget, RegistryProperties):
self, self.on_new_prompt,
Settings().value(self.settings_section + '/last directory'),
self.on_new_file_masks)
log.info('New files(s) {file_paths}'.format(file_paths=file_paths))
log.info('New file(s) {file_paths}'.format(file_paths=file_paths))
if file_paths:
self.application.set_busy_cursor()
self.validate_and_load([path_to_str(path) for path in file_paths])
self.validate_and_load(file_paths)
self.application.set_normal_cursor()
def load_file(self, data):
@ -330,23 +330,24 @@ class MediaManagerItem(QtWidgets.QWidget, RegistryProperties):
:param data: A dictionary containing the list of files to be loaded and the target
"""
new_files = []
new_file_paths = []
error_shown = False
for file_name in data['files']:
file_type = file_name.split('.')[-1]
if file_type.lower() not in self.on_new_file_masks:
file_path = str_to_path(file_name) # TODO:
if file_path.suffix[1:].lower() not in self.on_new_file_masks:
if not error_shown:
critical_error_message_box(translate('OpenLP.MediaManagerItem', 'Invalid File Type'),
translate('OpenLP.MediaManagerItem',
'Invalid File {name}.\n'
'Suffix not supported').format(name=file_name))
critical_error_message_box(
translate('OpenLP.MediaManagerItem', 'Invalid File Type'),
translate('OpenLP.MediaManagerItem',
'Invalid File {file_path}.\nFile extension not supported').format(
file_path=file_path))
error_shown = True
else:
new_files.append(file_name)
if new_files:
new_file_paths.append(file_path)
if new_file_paths:
if 'target' in data:
self.validate_and_load(new_files, data['target'])
self.validate_and_load(new_files)
self.validate_and_load(new_file_paths, data['target'])
self.validate_and_load(new_file_paths)
def dnd_move_internal(self, target):
"""
@ -356,31 +357,30 @@ class MediaManagerItem(QtWidgets.QWidget, RegistryProperties):
"""
pass
def validate_and_load(self, files, target_group=None):
def validate_and_load(self, file_paths, target_group=None):
"""
Process a list for files either from the File Dialog or from Drag and
Drop
:param files: The files to be loaded.
:param list[openlp.core.common.path.Path] file_paths: The files to be loaded.
:param target_group: The QTreeWidgetItem of the group that will be the parent of the added files
"""
full_list = []
for count in range(self.list_view.count()):
full_list.append(self.list_view.item(count).data(QtCore.Qt.UserRole))
full_list.append(self.list_view.item(count).data(QtCore.Qt.UserRole)) # TODO: Path objects
duplicates_found = False
files_added = False
for file_path in files:
if file_path in full_list:
for file_path in file_paths:
if path_to_str(file_path) in full_list:
duplicates_found = True
else:
files_added = True
full_list.append(file_path)
full_list.append(path_to_str(file_path))
if full_list and files_added:
if target_group is None:
self.list_view.clear()
self.load_list(full_list, target_group)
last_dir = os.path.split(files[0])[0]
Settings().setValue(self.settings_section + '/last directory', Path(last_dir))
Settings().setValue(self.settings_section + '/last directory', file_paths[0].parent)
Settings().setValue('{section}/{section} files'.format(section=self.settings_section), self.get_file_list())
if duplicates_found:
critical_error_message_box(UiStrings().Duplicate,

View File

@ -43,8 +43,7 @@ class PluginManager(RegistryBase, LogMixin, RegistryProperties):
"""
super(PluginManager, self).__init__(parent)
self.log_info('Plugin manager Initialising')
self.base_path = os.path.abspath(str(AppLocation.get_directory(AppLocation.PluginsDir)))
self.log_debug('Base path {path}'.format(path=self.base_path))
self.log_debug('Base path {path}'.format(path=AppLocation.get_directory(AppLocation.PluginsDir)))
self.plugins = []
self.log_info('Plugin manager Initialised')

View File

@ -29,7 +29,6 @@ Some of the code for this form is based on the examples at:
"""
import html
import logging
import os
from PyQt5 import QtCore, QtWidgets, QtWebKit, QtWebKitWidgets, QtGui, QtMultimedia
@ -490,8 +489,7 @@ class MainDisplay(Display, LogMixin, RegistryProperties):
service_item = ServiceItem()
service_item.title = 'webkit'
service_item.processor = 'webkit'
path = os.path.join(str(AppLocation.get_section_data_path('themes')),
self.service_item.theme_data.theme_name)
path = str(AppLocation.get_section_data_path('themes') / self.service_item.theme_data.theme_name)
service_item.add_from_command(path,
path_to_str(self.service_item.theme_data.background_filename),
':/media/slidecontroller_multimedia.png')

View File

@ -649,8 +649,8 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
self.application.process_events()
plugin.first_time()
self.application.process_events()
temp_dir = os.path.join(str(gettempdir()), 'openlp')
shutil.rmtree(temp_dir, True)
temp_path = Path(gettempdir(), 'openlp')
temp_path.rmtree(True)
def on_first_time_wizard_clicked(self):
"""
@ -1219,7 +1219,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
settings.remove('custom slide')
settings.remove('service')
settings.beginGroup(self.general_settings_section)
self.recent_files = [path_to_str(file_path) for file_path in settings.value('recent files')]
self.recent_files = settings.value('recent files')
settings.endGroup()
settings.beginGroup(self.ui_settings_section)
self.move(settings.value('main window position'))
@ -1243,7 +1243,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
log.debug('Saving QSettings')
settings = Settings()
settings.beginGroup(self.general_settings_section)
settings.setValue('recent files', [str_to_path(file) for file in self.recent_files])
settings.setValue('recent files', self.recent_files)
settings.endGroup()
settings.beginGroup(self.ui_settings_section)
settings.setValue('main window position', self.pos())
@ -1259,26 +1259,24 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
Updates the recent file menu with the latest list of service files accessed.
"""
recent_file_count = Settings().value('advanced/recent file count')
existing_recent_files = [recentFile for recentFile in self.recent_files if os.path.isfile(str(recentFile))]
recent_files_to_display = existing_recent_files[0:recent_file_count]
self.recent_files_menu.clear()
for file_id, filename in enumerate(recent_files_to_display):
log.debug('Recent file name: {name}'.format(name=filename))
count = 0
for recent_path in self.recent_files:
if not recent_path.is_file():
continue
count += 1
log.debug('Recent file name: {name}'.format(name=recent_path))
action = create_action(self, '',
text='&{n} {name}'.format(n=file_id + 1,
name=os.path.splitext(os.path.basename(str(filename)))[0]),
data=filename,
triggers=self.service_manager_contents.on_recent_service_clicked)
text='&{n} {name}'.format(n=count, name=recent_path.name),
data=recent_path, triggers=self.service_manager_contents.on_recent_service_clicked)
self.recent_files_menu.addAction(action)
clear_recent_files_action = create_action(self, '',
text=translate('OpenLP.MainWindow', 'Clear List', 'Clear List of '
'recent files'),
statustip=translate('OpenLP.MainWindow', 'Clear the list of recent '
'files.'),
enabled=bool(self.recent_files),
triggers=self.clear_recent_file_menu)
if count == recent_file_count:
break
clear_recent_files_action = \
create_action(self, '', text=translate('OpenLP.MainWindow', 'Clear List', 'Clear List of recent files'),
statustip=translate('OpenLP.MainWindow', 'Clear the list of recent files.'),
enabled=bool(self.recent_files), triggers=self.clear_recent_file_menu)
add_actions(self.recent_files_menu, (None, clear_recent_files_action))
clear_recent_files_action.setEnabled(bool(self.recent_files))
def add_recent_file(self, filename):
"""
@ -1290,20 +1288,13 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, RegistryProperties):
# actually stored in the settings therefore the default value of 20 will
# always be used.
max_recent_files = Settings().value('advanced/max recent files')
if filename:
# Add some cleanup to reduce duplication in the recent file list
filename = os.path.abspath(filename)
# abspath() only capitalises the drive letter if it wasn't provided
# in the given filename which then causes duplication.
if filename[1:3] == ':\\':
filename = filename[0].upper() + filename[1:]
if filename in self.recent_files:
self.recent_files.remove(filename)
if not isinstance(self.recent_files, list):
self.recent_files = [self.recent_files]
self.recent_files.insert(0, filename)
while len(self.recent_files) > max_recent_files:
self.recent_files.pop()
file_path = Path(filename)
# Some cleanup to reduce duplication in the recent file list
file_path = file_path.resolve()
if file_path in self.recent_files:
self.recent_files.remove(file_path)
self.recent_files.insert(0, file_path)
self.recent_files = self.recent_files[:max_recent_files]
def clear_recent_file_menu(self):
"""

View File

@ -31,6 +31,7 @@ from PyQt5 import QtCore
from openlp.core.api.http import register_endpoint
from openlp.core.common import extension_loader
from openlp.core.common.i18n import translate
from openlp.core.common.path import path_to_str
from openlp.core.common.settings import Settings
from openlp.core.lib import Plugin, StringContent, build_icon
from openlp.plugins.presentations.endpoint import api_presentations_endpoint, presentations_endpoint
@ -144,12 +145,12 @@ class PresentationPlugin(Plugin):
# TODO: Can be removed when the upgrade path to OpenLP 3.0 is no longer needed, also ensure code in
# PresentationDocument.get_thumbnail_folder and PresentationDocument.get_temp_folder is removed
super().app_startup()
files_from_config = Settings().value('presentations/presentations files')
for file in files_from_config:
self.media_item.clean_up_thumbnails(file, clean_for_update=True)
presentation_paths = Settings().value('presentations/presentations files')
for path in presentation_paths:
self.media_item.clean_up_thumbnails(path, clean_for_update=True)
self.media_item.list_view.clear()
Settings().setValue('presentations/thumbnail_scheme', 'md5')
self.media_item.validate_and_load(files_from_config)
self.media_item.validate_and_load(presentation_paths)
@staticmethod
def about():