diff --git a/openlp/core/app.py b/openlp/core/app.py index dfb413caa..ab738e1a2 100644 --- a/openlp/core/app.py +++ b/openlp/core/app.py @@ -287,12 +287,12 @@ class OpenLP(QtWidgets.QApplication): return QtWidgets.QApplication.event(self, event) -def parse_options(args=None): +def parse_options(): """ Parse the command line arguments - :param args: list of command line arguments - :return: a tuple of parsed options of type optparse.Value and a list of remaining argsZ + :return: An :object:`argparse.Namespace` insatnce containing the parsed args. + :rtype: argparse.Namespace """ # Set up command line options. parser = argparse.ArgumentParser(prog='openlp') @@ -307,9 +307,9 @@ def parse_options(args=None): dir_name=os.path.join('', '..', '..'))) parser.add_argument('-w', '--no-web-server', dest='no_web_server', action='store_true', help='Turn off the Web and Socket Server ') - parser.add_argument('rargs', nargs='?', default=[]) - # Parse command line options and deal with them. Use args supplied pragmatically if possible. - return parser.parse_args(args) if args else parser.parse_args() + parser.add_argument('rargs', nargs='*', default=[]) + # Parse command line options and deal with them. + return parser.parse_args() def set_up_logging(log_path): @@ -328,13 +328,11 @@ def set_up_logging(log_path): print('Logging to: {name}'.format(name=file_path)) -def main(args=None): +def main(): """ The main function which parses command line options and then runs - - :param args: Some args """ - args = parse_options(args) + args = parse_options() qt_args = ['--disable-web-security'] # qt_args = [] if args and args.loglevel.lower() in ['d', 'debug']: diff --git a/openlp/core/common/__init__.py b/openlp/core/common/__init__.py index dfed903c7..fd251be14 100644 --- a/openlp/core/common/__init__.py +++ b/openlp/core/common/__init__.py @@ -134,8 +134,8 @@ def extension_loader(glob_pattern, excluded_files=[]): importlib.import_module(module_name) except (ImportError, OSError): # On some platforms importing vlc.py might cause OSError exceptions. (e.g. Mac OS X) - log.warning('Failed to import {module_name} on path {extension_path}' - .format(module_name=module_name, extension_path=extension_path)) + log.exception('Failed to import {module_name} on path {extension_path}' + .format(module_name=module_name, extension_path=extension_path)) def path_to_module(path): diff --git a/openlp/core/display/window.py b/openlp/core/display/window.py index 6b2e9af1b..161b49981 100644 --- a/openlp/core/display/window.py +++ b/openlp/core/display/window.py @@ -180,7 +180,7 @@ class DisplayWindow(QtWidgets.QWidget): """ Set the URL of the webview - :param str url: The URL to set + :param QtCore.QUrl | str url: The URL to set """ if not isinstance(url, QtCore.QUrl): url = QtCore.QUrl(url) diff --git a/openlp/core/lib/theme.py b/openlp/core/lib/theme.py index 4bc145c72..f770b7487 100644 --- a/openlp/core/lib/theme.py +++ b/openlp/core/lib/theme.py @@ -333,7 +333,7 @@ class Theme(object): else: # make string value unicode if not isinstance(value, str): - value = str(str(value), 'utf-8') + value = str(value, 'utf-8') # None means an empty string so lets have one. if value == 'None': value = '' diff --git a/openlp/core/server.py b/openlp/core/server.py index 7c7842853..33c024254 100644 --- a/openlp/core/server.py +++ b/openlp/core/server.py @@ -22,6 +22,7 @@ from PyQt5 import QtCore, QtNetwork from openlp.core.common.mixins import LogMixin +from openlp.core.common.path import Path from openlp.core.common.registry import Registry @@ -97,7 +98,7 @@ class Server(QtCore.QObject, LogMixin): msg = self.in_stream.readLine() if msg: self.log_debug("socket msg = " + msg) - Registry().get('service_manager').on_load_service_clicked(msg) + Registry().get('service_manager').load_service(Path(msg)) def close_server(self): """ diff --git a/openlp/core/ui/firsttimewizard.py b/openlp/core/ui/firsttimewizard.py index 87b044ac0..8cb967a54 100644 --- a/openlp/core/ui/firsttimewizard.py +++ b/openlp/core/ui/firsttimewizard.py @@ -78,7 +78,7 @@ class ThemeListWidget(QtWidgets.QListWidget): """ nominal_width = 141 # Icon width of 133 + 4 each side max_items_per_row = self.viewport().width() // nominal_width or 1 # or 1 to avoid divide by 0 errors - col_size = (self.viewport().width() - 1) / max_items_per_row + col_size = (self.viewport().width() - 1) // max_items_per_row self.setGridSize(QtCore.QSize(col_size, 140)) diff --git a/openlp/core/ui/mainwindow.py b/openlp/core/ui/mainwindow.py index 3443185ae..703bdc943 100644 --- a/openlp/core/ui/mainwindow.py +++ b/openlp/core/ui/mainwindow.py @@ -22,7 +22,7 @@ """ This is the main window, where all the action happens. """ -import sys +import os from datetime import datetime from distutils import dir_util from distutils.errors import DistutilsFileError @@ -475,7 +475,6 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, LogMixin, RegistryPropert super(MainWindow, self).__init__() Registry().register('main_window', self) self.clipboard = self.application.clipboard() - self.arguments = ''.join(self.application.args) # Set up settings sections for the main application (not for use by plugins). self.ui_settings_section = 'user interface' self.general_settings_section = 'core' @@ -632,8 +631,8 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, LogMixin, RegistryPropert # if self.live_controller.display.isVisible(): # self.live_controller.display.setFocus() self.activateWindow() - if self.arguments: - self.open_cmd_line_files(self.arguments) + if self.application.args: + self.open_cmd_line_files(self.application.args) elif Settings().value(self.general_settings_section + '/auto open'): self.service_manager_contents.load_last_file() # This will store currently used layout preset so it remains enabled on next startup. @@ -1339,7 +1338,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, LogMixin, RegistryPropert self.application.set_normal_cursor() self.log_exception('Data copy failed {err}'.format(err=str(why))) err_text = translate('OpenLP.MainWindow', - 'OpenLP Data directory copy failed\n\n{err}').format(err=str(why)), + 'OpenLP Data directory copy failed\n\n{err}').format(err=str(why)) QtWidgets.QMessageBox.critical(self, translate('OpenLP.MainWindow', 'New Data Directory Error'), err_text, QtWidgets.QMessageBox.StandardButtons(QtWidgets.QMessageBox.Ok)) @@ -1354,11 +1353,11 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow, LogMixin, RegistryPropert settings.remove('advanced/data path') self.application.set_normal_cursor() - def open_cmd_line_files(self, filename): + def open_cmd_line_files(self, args): """ Open files passed in through command line arguments """ - if not isinstance(filename, str): - filename = str(filename, sys.getfilesystemencoding()) - if filename.endswith(('.osz', '.oszl')): - self.service_manager_contents.load_file(Path(filename)) + for arg in args: + file_name = os.path.expanduser(arg) + if os.path.isfile(file_name): + self.service_manager_contents.load_file(Path(file_name)) diff --git a/openlp/core/ui/servicemanager.py b/openlp/core/ui/servicemanager.py index 9303dae35..3858e1f48 100644 --- a/openlp/core/ui/servicemanager.py +++ b/openlp/core/ui/servicemanager.py @@ -430,11 +430,20 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi return False self.new_file() - def on_load_service_clicked(self, load_file=None): + def on_load_service_clicked(self, checked): + """ + Handle the `fileOpenItem` action + + :param bool checked: Not used. + :rtype: None + """ + self.load_service() + + def load_service(self, file_path=None): """ Loads the service file and saves the existing one it there is one unchanged. - :param load_file: The service file to the loaded. Will be None is from menu so selection will be required. + :param openlp.core.common.path.Path | None file_path: The service file to the loaded. """ if self.is_modified(): result = self.save_modified_service() @@ -442,7 +451,7 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi return False elif result == QtWidgets.QMessageBox.Save: self.decide_save_method() - if not load_file: + if not file_path: file_path, filter_used = FileDialog.getOpenFileName( self.main_window, translate('OpenLP.ServiceManager', 'Open File'), @@ -450,8 +459,6 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz *.oszl)')) if not file_path: return False - else: - file_path = str_to_path(load_file) Settings().setValue(self.main_window.service_manager_settings_section + '/last directory', file_path.parent) self.load_file(file_path) @@ -670,8 +677,9 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi def load_file(self, file_path): """ - Load an existing service file - :param file_path: + Load an existing service file. + + :param openlp.core.common.path.Path file_path: The service file to load. """ if not file_path.exists(): return False @@ -1520,12 +1528,12 @@ class ServiceManager(QtWidgets.QWidget, RegistryBase, Ui_ServiceManager, LogMixi event.setDropAction(QtCore.Qt.CopyAction) event.accept() for url in link.urls(): - file_name = url.toLocalFile() - if file_name.endswith('.osz'): - self.on_load_service_clicked(file_name) - elif file_name.endswith('.oszl'): + file_path = Path(url.toLocalFile()) + if file_path.suffix == '.osz': + self.load_service(file_path) + elif file_path.suffix == '.oszl': # todo correct - self.on_load_service_clicked(file_name) + self.load_service(file_path) elif link.hasText(): plugin = link.text() item = self.service_manager_list.itemAt(event.pos()) diff --git a/openlp/core/ui/slidecontroller.py b/openlp/core/ui/slidecontroller.py index b5855d3d3..437dbf88c 100644 --- a/openlp/core/ui/slidecontroller.py +++ b/openlp/core/ui/slidecontroller.py @@ -112,7 +112,7 @@ class MediaSlider(QtWidgets.QSlider): class InfoLabel(QtWidgets.QLabel): """ - InfoLabel is a subclassed QLabel. Created to provide the ablilty to add a ellipsis if the text is cut off. Original + InfoLabel is a subclassed QLabel. Created to provide the ability to add a ellipsis if the text is cut off. Original source: https://stackoverflow.com/questions/11446478/pyside-pyqt-truncate-text-in-qlabel-based-on-minimumsize """ diff --git a/openlp/core/widgets/dialogs.py b/openlp/core/widgets/dialogs.py index 7668dcab8..11083f393 100755 --- a/openlp/core/widgets/dialogs.py +++ b/openlp/core/widgets/dialogs.py @@ -35,7 +35,7 @@ class FileDialog(QtWidgets.QFileDialog): :type caption: str :type directory: openlp.core.common.path.Path :type options: QtWidgets.QFileDialog.Options - :rtype: tuple[openlp.core.common.path.Path, str] + :rtype: openlp.core.common.path.Path """ args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),)) diff --git a/openlp/core/widgets/layouts.py b/openlp/core/widgets/layouts.py index 65c61e266..0b46bf3f6 100644 --- a/openlp/core/widgets/layouts.py +++ b/openlp/core/widgets/layouts.py @@ -37,7 +37,7 @@ class AspectRatioLayout(QtWidgets.QLayout): """ Create a layout. - :param PyQt5.QtWidgets.QWidget parent: The parent widget, can be None. + :param QtWidgets.QWidget | None parent: The parent widget :param float aspect_ratio: The aspect ratio as a float (e.g. 16.0/9.0) """ super().__init__(parent) diff --git a/openlp/core/widgets/views.py b/openlp/core/widgets/views.py index 68422e1b4..dbe7c2be6 100644 --- a/openlp/core/widgets/views.py +++ b/openlp/core/widgets/views.py @@ -39,7 +39,7 @@ def handle_mime_data_urls(mime_data): """ Process the data from a drag and drop operation. - :param PyQt5.QtCore.QMimeData mime_data: The mime data from the drag and drop opperation. + :param QtCore.QMimeData mime_data: The mime data from the drag and drop opperation. :return: A list of file paths that were dropped :rtype: list[openlp.core.common.path.Path] """ @@ -297,7 +297,7 @@ class ListWidgetWithDnD(QtWidgets.QListWidget): """ self.setAcceptDrops(True) self.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) - Registry().register_function(('%s_dnd' % self.mime_data_text), self.parent().load_file) + Registry().register_function(('%s_dnd' % self.mime_data_text), self.parent().handle_mime_data) def clear(self, search_while_typing=False): """ @@ -412,7 +412,7 @@ class TreeWidgetWithDnD(QtWidgets.QTreeWidget): """ self.setAcceptDrops(True) self.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) - Registry().register_function(('%s_dnd' % self.mime_data_text), self.parent().load_file) + Registry().register_function(('%s_dnd' % self.mime_data_text), self.parent().handle_mime_data) Registry().register_function(('%s_dnd_internal' % self.mime_data_text), self.parent().dnd_move_internal) def mouseMoveEvent(self, event): diff --git a/openlp/plugins/bibles/lib/importers/csvbible.py b/openlp/plugins/bibles/lib/importers/csvbible.py index 694784f80..0f273de8b 100644 --- a/openlp/plugins/bibles/lib/importers/csvbible.py +++ b/openlp/plugins/bibles/lib/importers/csvbible.py @@ -102,7 +102,7 @@ class CSVBible(BibleImport): :rtype: list[namedtuple] """ try: - encoding = get_file_encoding(file_path)['encoding'] + encoding = get_file_encoding(file_path) with file_path.open('r', encoding=encoding, newline='') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"') return [results_tuple(*line) for line in csv_reader] diff --git a/openlp/plugins/images/lib/mediaitem.py b/openlp/plugins/images/lib/mediaitem.py index 14bef3f0e..9909198cf 100644 --- a/openlp/plugins/images/lib/mediaitem.py +++ b/openlp/plugins/images/lib/mediaitem.py @@ -401,10 +401,9 @@ class ImageMediaItem(MediaManagerItem): Process a list for files either from the File Dialog or from Drag and Drop. This method is overloaded from MediaManagerItem. - :param files: A List of strings containing the filenames of the files to be loaded + :param list[openlp.core.common.path.Path] file_paths: A List of paths to be loaded :param target_group: The QTreeWidgetItem of the group that will be the parent of the added files """ - file_paths = [Path(file) for file in file_paths] self.application.set_normal_cursor() self.load_list(file_paths, target_group) last_dir = file_paths[0].parent diff --git a/openlp/plugins/songs/lib/importers/presentationmanager.py b/openlp/plugins/songs/lib/importers/presentationmanager.py index ae673dcab..6647222cb 100644 --- a/openlp/plugins/songs/lib/importers/presentationmanager.py +++ b/openlp/plugins/songs/lib/importers/presentationmanager.py @@ -48,7 +48,7 @@ class PresentationManagerImport(SongImport): tree = etree.parse(str(file_path), parser=etree.XMLParser(recover=True)) except etree.XMLSyntaxError: # Try to detect encoding and use it - encoding = get_file_encoding(file_path)['encoding'] + encoding = get_file_encoding(file_path) # Open file with detected encoding and remove encoding declaration text = file_path.read_text(encoding=encoding) text = re.sub(r'.+\?>\n', '', text) diff --git a/openlp/plugins/songs/lib/importers/songbeamer.py b/openlp/plugins/songs/lib/importers/songbeamer.py index d5ba82bd0..0fe42c541 100644 --- a/openlp/plugins/songs/lib/importers/songbeamer.py +++ b/openlp/plugins/songs/lib/importers/songbeamer.py @@ -124,7 +124,7 @@ class SongBeamerImport(SongImport): self.chord_table = None if file_path.is_file(): # Detect the encoding - self.input_file_encoding = get_file_encoding(file_path)['encoding'] + self.input_file_encoding = get_file_encoding(file_path) # The encoding should only be ANSI (cp1252), UTF-8, Unicode, Big-Endian-Unicode. # So if it doesn't start with 'u' we default to cp1252. See: # https://forum.songbeamer.com/viewtopic.php?p=419&sid=ca4814924e37c11e4438b7272a98b6f2 diff --git a/openlp/plugins/songs/lib/importers/worshipassistant.py b/openlp/plugins/songs/lib/importers/worshipassistant.py index 15f14122f..4cc374f8f 100644 --- a/openlp/plugins/songs/lib/importers/worshipassistant.py +++ b/openlp/plugins/songs/lib/importers/worshipassistant.py @@ -82,7 +82,7 @@ class WorshipAssistantImport(SongImport): Receive a CSV file to import. """ # Get encoding - encoding = get_file_encoding(self.import_source)['encoding'] + encoding = get_file_encoding(self.import_source) with self.import_source.open('r', encoding=encoding) as songs_file: songs_reader = csv.DictReader(songs_file, escapechar='\\') try: diff --git a/tests/functional/openlp_core/common/test_init.py b/tests/functional/openlp_core/common/test_init.py index e968cce1f..d7320114e 100644 --- a/tests/functional/openlp_core/common/test_init.py +++ b/tests/functional/openlp_core/common/test_init.py @@ -322,7 +322,7 @@ class TestInit(TestCase, TestMixin): mocked_open.assert_called_once_with('rb') assert mocked_universal_detector_inst.feed.mock_calls == [call(b'data' * 256)] mocked_universal_detector_inst.close.assert_called_once_with() - assert result == encoding_result + assert result == 'UTF-8' def test_get_file_encoding_eof(self): """ @@ -344,7 +344,7 @@ class TestInit(TestCase, TestMixin): mocked_open.assert_called_once_with('rb') assert mocked_universal_detector_inst.feed.mock_calls == [call(b'data' * 256), call(b'data' * 4)] mocked_universal_detector_inst.close.assert_called_once_with() - assert result == encoding_result + assert result == 'UTF-8' def test_get_file_encoding_oserror(self): """ @@ -367,4 +367,4 @@ class TestInit(TestCase, TestMixin): mocked_log.exception.assert_called_once_with('Error detecting file encoding') mocked_universal_detector_inst.feed.assert_not_called() mocked_universal_detector_inst.close.assert_called_once_with() - assert result == encoding_result + assert result == 'UTF-8' diff --git a/tests/functional/openlp_core/ui/test_mainwindow.py b/tests/functional/openlp_core/ui/test_mainwindow.py index 6a7e02430..1d1929286 100644 --- a/tests/functional/openlp_core/ui/test_mainwindow.py +++ b/tests/functional/openlp_core/ui/test_mainwindow.py @@ -108,7 +108,6 @@ class TestMainWindow(TestCase, TestMixin): """ # GIVEN a non service file as an argument to openlp service = 'run_openlp.py' - self.main_window.arguments = service # WHEN the argument is processed self.main_window.open_cmd_line_files(service)