Minor misc + pathlib refactors

This commit is contained in:
Philip Ridout 2017-09-24 09:39:54 +01:00
parent d61ed7e9b1
commit dfe2ae347e
9 changed files with 40 additions and 60 deletions

View File

@ -24,7 +24,6 @@ The :mod:`openlp.core.utils` module provides the utility libraries for OpenLP.
""" """
import hashlib import hashlib
import logging import logging
import os
import platform import platform
import socket import socket
import sys import sys

View File

@ -22,9 +22,8 @@
""" """
The :mod:`advancedtab` provides an advanced settings facility. The :mod:`advancedtab` provides an advanced settings facility.
""" """
from datetime import datetime, timedelta
import logging import logging
import os from datetime import datetime, timedelta
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
@ -492,22 +491,25 @@ class AdvancedTab(SettingsTab):
self.service_name_edit.setText(UiStrings().DefaultServiceName) self.service_name_edit.setText(UiStrings().DefaultServiceName)
self.service_name_edit.setFocus() self.service_name_edit.setFocus()
def on_data_directory_path_edit_path_changed(self, new_data_path): def on_data_directory_path_edit_path_changed(self, new_path):
""" """
Browse for a new data directory location. Handle the `editPathChanged` signal of the data_directory_path_edit
:param openlp.core.common.path.Path new_path: The new path
:rtype: None
""" """
# Make sure they want to change the data. # Make sure they want to change the data.
answer = QtWidgets.QMessageBox.question(self, translate('OpenLP.AdvancedTab', 'Confirm Data Directory Change'), answer = QtWidgets.QMessageBox.question(self, translate('OpenLP.AdvancedTab', 'Confirm Data Directory Change'),
translate('OpenLP.AdvancedTab', 'Are you sure you want to change the ' translate('OpenLP.AdvancedTab', 'Are you sure you want to change the '
'location of the OpenLP data directory to:\n\n{path}' 'location of the OpenLP data directory to:\n\n{path}'
'\n\nThe data directory will be changed when OpenLP is ' '\n\nThe data directory will be changed when OpenLP is '
'closed.').format(path=new_data_path), 'closed.').format(path=new_path),
defaultButton=QtWidgets.QMessageBox.No) defaultButton=QtWidgets.QMessageBox.No)
if answer != QtWidgets.QMessageBox.Yes: if answer != QtWidgets.QMessageBox.Yes:
self.data_directory_path_edit.path = AppLocation.get_data_path() self.data_directory_path_edit.path = AppLocation.get_data_path()
return return
# Check if data already exists here. # Check if data already exists here.
self.check_data_overwrite(path_to_str(new_data_path)) self.check_data_overwrite(new_path)
# Save the new location. # Save the new location.
self.main_window.set_new_data_path(path_to_str(new_data_path)) self.main_window.set_new_data_path(path_to_str(new_data_path))
self.data_directory_cancel_button.show() self.data_directory_cancel_button.show()
@ -526,9 +528,10 @@ class AdvancedTab(SettingsTab):
def check_data_overwrite(self, data_path): def check_data_overwrite(self, data_path):
""" """
Check if there's already data in the target directory. Check if there's already data in the target directory.
:param openlp.core.common.path.Path data_path: The target directory to check
""" """
test_path = os.path.join(data_path, 'songs') if (data_path / 'songs').exists():
if os.path.exists(test_path):
self.data_exists = True self.data_exists = True
# Check is they want to replace existing data. # Check is they want to replace existing data.
answer = QtWidgets.QMessageBox.warning(self, answer = QtWidgets.QMessageBox.warning(self,
@ -537,7 +540,7 @@ class AdvancedTab(SettingsTab):
'WARNING: \n\nThe location you have selected \n\n{path}' 'WARNING: \n\nThe location you have selected \n\n{path}'
'\n\nappears to contain OpenLP data files. Do you wish to ' '\n\nappears to contain OpenLP data files. Do you wish to '
'replace these files with the current data ' 'replace these files with the current data '
'files?').format(path=os.path.abspath(data_path,)), 'files?'.format(path=data_path)),
QtWidgets.QMessageBox.StandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.StandardButtons(QtWidgets.QMessageBox.Yes |
QtWidgets.QMessageBox.No), QtWidgets.QMessageBox.No),
QtWidgets.QMessageBox.No) QtWidgets.QMessageBox.No)

View File

@ -149,21 +149,11 @@ class ExceptionForm(QtWidgets.QDialog, Ui_ExceptionDialog, RegistryProperties):
opts = self._create_report() opts = self._create_report()
report_text = self.report_text.format(version=opts['version'], description=opts['description'], report_text = self.report_text.format(version=opts['version'], description=opts['description'],
traceback=opts['traceback'], libs=opts['libs'], system=opts['system']) traceback=opts['traceback'], libs=opts['libs'], system=opts['system'])
filename = str(file_path)
try: try:
report_file = open(filename, 'w') with file_path.open('w') as report_file:
try:
report_file.write(report_text) report_file.write(report_text)
except UnicodeError:
report_file.close()
report_file = open(filename, 'wb')
report_file.write(report_text.encode('utf-8'))
finally:
report_file.close()
except IOError: except IOError:
log.exception('Failed to write crash report') log.exception('Failed to write crash report')
finally:
report_file.close()
def on_send_report_button_clicked(self): def on_send_report_button_clicked(self):
""" """
@ -219,7 +209,7 @@ class ExceptionForm(QtWidgets.QDialog, Ui_ExceptionDialog, RegistryProperties):
translate('ImagePlugin.ExceptionDialog', 'Select Attachment'), translate('ImagePlugin.ExceptionDialog', 'Select Attachment'),
Settings().value(self.settings_section + '/last directory'), Settings().value(self.settings_section + '/last directory'),
'{text} (*)'.format(text=UiStrings().AllFiles)) '{text} (*)'.format(text=UiStrings().AllFiles))
log.info('New file {file}'.format(file=file_path)) log.info('New files {file_path}'.format(file_path=file_path))
if file_path: if file_path:
self.file_attachment = str(file_path) self.file_attachment = str(file_path)

View File

@ -31,11 +31,11 @@ class FileDialog(QtWidgets.QFileDialog):
""" """
Wraps `getExistingDirectory` so that it can be called with, and return Path objects Wraps `getExistingDirectory` so that it can be called with, and return Path objects
:type parent: QtWidgets.QWidget or None :type parent: QtWidgets.QWidget | None
:type caption: str :type caption: str
:type directory: openlp.core.common.path.Path :type directory: openlp.core.common.path.Path
:type options: QtWidgets.QFileDialog.Options :type options: QtWidgets.QFileDialog.Options
:rtype: tuple[Path, str] :rtype: tuple[openlp.core.common.path.Path, str]
""" """
args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),)) args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),))
@ -50,13 +50,13 @@ class FileDialog(QtWidgets.QFileDialog):
""" """
Wraps `getOpenFileName` so that it can be called with, and return Path objects Wraps `getOpenFileName` so that it can be called with, and return Path objects
:type parent: QtWidgets.QWidget or None :type parent: QtWidgets.QWidget | None
:type caption: str :type caption: str
:type directory: openlp.core.common.path.Path :type directory: openlp.core.common.path.Path
:type filter: str :type filter: str
:type initialFilter: str :type initialFilter: str
:type options: QtWidgets.QFileDialog.Options :type options: QtWidgets.QFileDialog.Options
:rtype: tuple[Path, str] :rtype: tuple[openlp.core.common.path.Path, str]
""" """
args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),)) args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),))
@ -71,13 +71,13 @@ class FileDialog(QtWidgets.QFileDialog):
""" """
Wraps `getOpenFileNames` so that it can be called with, and return Path objects Wraps `getOpenFileNames` so that it can be called with, and return Path objects
:type parent: QtWidgets.QWidget or None :type parent: QtWidgets.QWidget | None
:type caption: str :type caption: str
:type directory: openlp.core.common.path.Path :type directory: openlp.core.common.path.Path
:type filter: str :type filter: str
:type initialFilter: str :type initialFilter: str
:type options: QtWidgets.QFileDialog.Options :type options: QtWidgets.QFileDialog.Options
:rtype: tuple[list[Path], str] :rtype: tuple[list[openlp.core.common.path.Path], str]
""" """
args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),)) args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),))
@ -93,13 +93,13 @@ class FileDialog(QtWidgets.QFileDialog):
""" """
Wraps `getSaveFileName` so that it can be called with, and return Path objects Wraps `getSaveFileName` so that it can be called with, and return Path objects
:type parent: QtWidgets.QWidget or None :type parent: QtWidgets.QWidget | None
:type caption: str :type caption: str
:type directory: openlp.core.common.path.Path :type directory: openlp.core.common.path.Path
:type filter: str :type filter: str
:type initialFilter: str :type initialFilter: str
:type options: QtWidgets.QFileDialog.Options :type options: QtWidgets.QFileDialog.Options
:rtype: tuple[Path or None, str] :rtype: tuple[openlp.core.common.path.Path | None, str]
""" """
args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),)) args, kwargs = replace_params(args, kwargs, ((2, 'directory', path_to_str),))

View File

@ -70,7 +70,7 @@ class AlertForm(QtWidgets.QDialog, Ui_AlertDialog):
item_name = QtWidgets.QListWidgetItem(alert.text) item_name = QtWidgets.QListWidgetItem(alert.text)
item_name.setData(QtCore.Qt.UserRole, alert.id) item_name.setData(QtCore.Qt.UserRole, alert.id)
self.alert_list_widget.addItem(item_name) self.alert_list_widget.addItem(item_name)
if alert.text == str(self.alert_text_edit.text()): if alert.text == self.alert_text_edit.text():
self.item_id = alert.id self.item_id = alert.id
self.alert_list_widget.setCurrentRow(self.alert_list_widget.row(item_name)) self.alert_list_widget.setCurrentRow(self.alert_list_widget.row(item_name))

View File

@ -32,9 +32,6 @@ class AlertsTab(SettingsTab):
""" """
AlertsTab is the alerts settings tab in the settings dialog. AlertsTab is the alerts settings tab in the settings dialog.
""" """
def __init__(self, parent, name, visible_title, icon_path):
super(AlertsTab, self).__init__(parent, name, visible_title, icon_path)
def setupUi(self): def setupUi(self):
self.setObjectName('AlertsTab') self.setObjectName('AlertsTab')
super(AlertsTab, self).setupUi() super(AlertsTab, self).setupUi()

View File

@ -34,9 +34,6 @@ class CustomTab(SettingsTab):
""" """
CustomTab is the Custom settings tab in the settings dialog. CustomTab is the Custom settings tab in the settings dialog.
""" """
def __init__(self, parent, title, visible_title, icon_path):
super(CustomTab, self).__init__(parent, title, visible_title, icon_path)
def setupUi(self): def setupUi(self):
self.setObjectName('CustomTab') self.setObjectName('CustomTab')
super(CustomTab, self).setupUi() super(CustomTab, self).setupUi()

View File

@ -19,7 +19,6 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 # # with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
from PyQt5 import QtCore, QtWidgets from PyQt5 import QtCore, QtWidgets
from openlp.core.common import translate from openlp.core.common import translate

View File

@ -19,7 +19,6 @@
# with this program; if not, write to the Free Software Foundation, Inc., 59 # # with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
import logging import logging
import os import os
@ -60,7 +59,7 @@ class SongUsageDetailForm(QtWidgets.QDialog, Ui_SongUsageDetailDialog, RegistryP
def on_report_path_edit_path_changed(self, file_path): def on_report_path_edit_path_changed(self, file_path):
""" """
Called when the path in the `PathEdit` has changed Handle the `pathEditChanged` signal from report_path_edit
:param openlp.core.common.path.Path file_path: The new path. :param openlp.core.common.path.Path file_path: The new path.
:rtype: None :rtype: None
@ -72,7 +71,7 @@ class SongUsageDetailForm(QtWidgets.QDialog, Ui_SongUsageDetailDialog, RegistryP
Ok was triggered so lets save the data and run the report Ok was triggered so lets save the data and run the report
""" """
log.debug('accept') log.debug('accept')
path = path_to_str(self.report_path_edit.path) path = self.report_path_edit.path
if not path: if not path:
self.main_window.error_message( self.main_window.error_message(
translate('SongUsagePlugin.SongUsageDetailForm', 'Output Path Not Selected'), translate('SongUsagePlugin.SongUsageDetailForm', 'Output Path Not Selected'),
@ -80,7 +79,7 @@ class SongUsageDetailForm(QtWidgets.QDialog, Ui_SongUsageDetailDialog, RegistryP
' song usage report. \nPlease select an existing path on your computer.') ' song usage report. \nPlease select an existing path on your computer.')
) )
return return
check_directory_exists(Path(path)) check_directory_exists(path)
file_name = translate('SongUsagePlugin.SongUsageDetailForm', file_name = translate('SongUsagePlugin.SongUsageDetailForm',
'usage_detail_{old}_{new}.txt' 'usage_detail_{old}_{new}.txt'
).format(old=self.from_date_calendar.selectedDate().toString('ddMMyyyy'), ).format(old=self.from_date_calendar.selectedDate().toString('ddMMyyyy'),
@ -91,29 +90,25 @@ class SongUsageDetailForm(QtWidgets.QDialog, Ui_SongUsageDetailDialog, RegistryP
SongUsageItem, and_(SongUsageItem.usagedate >= self.from_date_calendar.selectedDate().toPyDate(), SongUsageItem, and_(SongUsageItem.usagedate >= self.from_date_calendar.selectedDate().toPyDate(),
SongUsageItem.usagedate < self.to_date_calendar.selectedDate().toPyDate()), SongUsageItem.usagedate < self.to_date_calendar.selectedDate().toPyDate()),
[SongUsageItem.usagedate, SongUsageItem.usagetime]) [SongUsageItem.usagedate, SongUsageItem.usagetime])
report_file_name = os.path.join(path, file_name) report_file_name = path / file_name
file_handle = None
try: try:
file_handle = open(report_file_name, 'wb') with report_file_name.open('wb') as file_handle:
for instance in usage: for instance in usage:
record = ('\"{date}\",\"{time}\",\"{title}\",\"{copyright}\",\"{ccli}\",\"{authors}\",' record = ('\"{date}\",\"{time}\",\"{title}\",\"{copyright}\",\"{ccli}\",\"{authors}\",'
'\"{name}\",\"{source}\"\n').format(date=instance.usagedate, time=instance.usagetime, '\"{name}\",\"{source}\"\n').format(date=instance.usagedate, time=instance.usagetime,
title=instance.title, copyright=instance.copyright, title=instance.title, copyright=instance.copyright,
ccli=instance.ccl_number, authors=instance.authors, ccli=instance.ccl_number, authors=instance.authors,
name=instance.plugin_name, source=instance.source) name=instance.plugin_name, source=instance.source)
file_handle.write(record.encode('utf-8')) file_handle.write(record.encode('utf-8'))
self.main_window.information_message( self.main_window.information_message(
translate('SongUsagePlugin.SongUsageDetailForm', 'Report Creation'), translate('SongUsagePlugin.SongUsageDetailForm', 'Report Creation'),
translate('SongUsagePlugin.SongUsageDetailForm', translate('SongUsagePlugin.SongUsageDetailForm',
'Report \n{name} \nhas been successfully created. ').format(name=report_file_name) 'Report \n{name} \nhas been successfully created. ').format(name=report_file_name)
) )
except OSError as ose: except OSError as ose:
log.exception('Failed to write out song usage records') log.exception('Failed to write out song usage records')
critical_error_message_box(translate('SongUsagePlugin.SongUsageDetailForm', 'Report Creation Failed'), critical_error_message_box(translate('SongUsagePlugin.SongUsageDetailForm', 'Report Creation Failed'),
translate('SongUsagePlugin.SongUsageDetailForm', translate('SongUsagePlugin.SongUsageDetailForm',
'An error occurred while creating the report: {error}' 'An error occurred while creating the report: {error}'
).format(error=ose.strerror)) ).format(error=ose.strerror))
finally:
if file_handle:
file_handle.close()
self.close() self.close()