A bunch of fixes suggested by pylint.

This commit is contained in:
Tomas Groth 2016-07-01 23:17:20 +02:00
parent 1cf078be76
commit 8aa917c89c
40 changed files with 92 additions and 97 deletions

View File

@ -138,7 +138,7 @@ class CategoryList(object):
for category in self.categories: for category in self.categories:
if category.name == key: if category.name == key:
return category return category
raise KeyError('Category "{keY}" does not exist.'.format(key=key)) raise KeyError('Category "{key}" does not exist.'.format(key=key))
def __len__(self): def __len__(self):
""" """

View File

@ -22,11 +22,12 @@
""" """
The :mod:`db` module provides helper functions for database related methods. The :mod:`db` module provides helper functions for database related methods.
""" """
import sqlalchemy
import logging import logging
from copy import deepcopy from copy import deepcopy
import sqlalchemy
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View File

@ -168,7 +168,7 @@ def format_time(text, local_time):
""" """
return local_time.strftime(match.group()) return local_time.strftime(match.group())
return re.sub('\%[a-zA-Z]', match_formatting, text) return re.sub(r'\%[a-zA-Z]', match_formatting, text)
def get_locale_key(string): def get_locale_key(string):

View File

@ -26,7 +26,7 @@ import datetime
import logging import logging
import os import os
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui
from openlp.core.common import ThemeLevel, SlideLimits, UiStrings, is_win, is_linux from openlp.core.common import ThemeLevel, SlideLimits, UiStrings, is_win, is_linux

View File

@ -68,7 +68,7 @@ class UiStrings(object):
self.Default = translate('OpenLP.Ui', 'Default') self.Default = translate('OpenLP.Ui', 'Default')
self.DefaultColor = translate('OpenLP.Ui', 'Default Color:') self.DefaultColor = translate('OpenLP.Ui', 'Default Color:')
self.DefaultServiceName = translate('OpenLP.Ui', 'Service %Y-%m-%d %H-%M', self.DefaultServiceName = translate('OpenLP.Ui', 'Service %Y-%m-%d %H-%M',
'This may not contain any of the following characters: /\\?*|<>\[\]":+\n' 'This may not contain any of the following characters: /\\?*|<>[]":+\n'
'See http://docs.python.org/library/datetime' 'See http://docs.python.org/library/datetime'
'.html#strftime-strptime-behavior for more information.') '.html#strftime-strptime-behavior for more information.')
self.Delete = translate('OpenLP.Ui', '&Delete') self.Delete = translate('OpenLP.Ui', '&Delete')

View File

@ -10,10 +10,10 @@ from datetime import datetime
from distutils.version import LooseVersion from distutils.version import LooseVersion
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from openlp.core.common import AppLocation, Settings
from PyQt5 import QtCore from PyQt5 import QtCore
from openlp.core.common import AppLocation, Settings
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
APPLICATION_VERSION = {} APPLICATION_VERSION = {}

View File

@ -95,7 +95,7 @@ def get_text_file_string(text_file):
content = None content = None
try: try:
file_handle = open(text_file, 'r', encoding='utf-8') file_handle = open(text_file, 'r', encoding='utf-8')
if not file_handle.read(3) == '\xEF\xBB\xBF': if file_handle.read(3) != '\xEF\xBB\xBF':
# no BOM was found # no BOM was found
file_handle.seek(0) file_handle.seek(0)
content = file_handle.read() content = file_handle.read()

View File

@ -178,9 +178,9 @@ def upgrade_db(url, upgrade):
version_meta = Metadata.populate(key='version', value=int(upgrade.__version__)) version_meta = Metadata.populate(key='version', value=int(upgrade.__version__))
session.commit() session.commit()
upgrade_version = upgrade.__version__ upgrade_version = upgrade.__version__
version_meta = int(version_meta.value) version = int(version_meta.value)
session.close() session.close()
return version_meta, upgrade_version return version, upgrade_version
def delete_database(plugin_name, db_file_name=None): def delete_database(plugin_name, db_file_name=None):

View File

@ -389,8 +389,8 @@ is the function which has to be called from outside. The generated and returned
""" """
import logging import logging
from PyQt5 import QtWebKit
from string import Template from string import Template
from PyQt5 import QtWebKit
from openlp.core.common import Settings from openlp.core.common import Settings
from openlp.core.lib.theme import BackgroundType, BackgroundGradientType, VerticalType, HorizontalType from openlp.core.lib.theme import BackgroundType, BackgroundGradientType, VerticalType, HorizontalType
@ -647,7 +647,7 @@ def webkit_version():
webkit_ver = float(QtWebKit.qWebKitVersion()) webkit_ver = float(QtWebKit.qWebKitVersion())
log.debug('Webkit version = {version}'.format(version=webkit_ver)) log.debug('Webkit version = {version}'.format(version=webkit_ver))
except AttributeError: except AttributeError:
webkit_ver = 0 webkit_ver = 0.0
return webkit_ver return webkit_ver

View File

@ -272,7 +272,7 @@ class ImageManager(QtCore.QObject):
Add image to cache if it is not already there. Add image to cache if it is not already there.
""" """
log.debug('add_image {path}'.format(path=path)) log.debug('add_image {path}'.format(path=path))
if not (path, source, width, height) in self._cache: if (path, source, width, height) not in self._cache:
image = Image(path, source, background, width, height) image = Image(path, source, background, width, height)
self._cache[(path, source, width, height)] = image self._cache[(path, source, width, height)] = image
self._conversion_queue.put((image.priority, image.secondary_priority, image)) self._conversion_queue.put((image.priority, image.secondary_priority, image))

View File

@ -23,7 +23,6 @@
Provide plugin management Provide plugin management
""" """
import os import os
import sys
import imp import imp
from openlp.core.lib import Plugin, PluginStatus from openlp.core.lib import Plugin, PluginStatus

View File

@ -40,13 +40,12 @@ log.debug('projector.lib.db module loaded')
from sqlalchemy import Column, ForeignKey, Integer, MetaData, String, and_ from sqlalchemy import Column, ForeignKey, Integer, MetaData, String, and_
from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import backref, relationship from sqlalchemy.orm import relationship
from openlp.core.lib.db import Manager, init_db, init_url from openlp.core.lib.db import Manager, init_db, init_url
from openlp.core.lib.projector.constants import PJLINK_DEFAULT_CODES from openlp.core.lib.projector.constants import PJLINK_DEFAULT_CODES
metadata = MetaData() Base = declarative_base(MetaData())
Base = declarative_base(metadata)
class CommonBase(object): class CommonBase(object):
@ -54,8 +53,8 @@ class CommonBase(object):
Base class to automate table name and ID column. Base class to automate table name and ID column.
""" """
@declared_attr @declared_attr
def __tablename__(cls): def __tablename__(self):
return cls.__name__.lower() return self.__name__.lower()
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
@ -257,7 +256,7 @@ class ProjectorDB(Manager):
projector = self.get_object_filtered(Projector, Projector.id == dbid) projector = self.get_object_filtered(Projector, Projector.id == dbid)
if projector is None: if projector is None:
# Not found # Not found
log.warn('get_projector_by_id() did not find {data}'.format(data=id)) log.warning('get_projector_by_id() did not find {data}'.format(data=id))
return None return None
log.debug('get_projectorby_id() returning 1 entry for "{entry}" id="{data}"'.format(entry=dbid, log.debug('get_projectorby_id() returning 1 entry for "{entry}" id="{data}"'.format(entry=dbid,
data=projector.id)) data=projector.id))
@ -290,7 +289,7 @@ class ProjectorDB(Manager):
projector = self.get_object_filtered(Projector, Projector.ip == ip) projector = self.get_object_filtered(Projector, Projector.ip == ip)
if projector is None: if projector is None:
# Not found # Not found
log.warn('get_projector_by_ip() did not find {ip}'.format(ip=ip)) log.warning('get_projector_by_ip() did not find {ip}'.format(ip=ip))
return None return None
log.debug('get_projectorby_ip() returning 1 entry for "{ip}" id="{data}"'.format(ip=ip, log.debug('get_projectorby_ip() returning 1 entry for "{ip}" id="{data}"'.format(ip=ip,
data=projector.id)) data=projector.id))
@ -307,7 +306,7 @@ class ProjectorDB(Manager):
projector = self.get_object_filtered(Projector, Projector.name == name) projector = self.get_object_filtered(Projector, Projector.name == name)
if projector is None: if projector is None:
# Not found # Not found
log.warn('get_projector_by_name() did not find "{name}"'.format(name=name)) log.warning('get_projector_by_name() did not find "{name}"'.format(name=name))
return None return None
log.debug('get_projector_by_name() returning one entry for "{name}" id="{data}"'.format(name=name, log.debug('get_projector_by_name() returning one entry for "{name}" id="{data}"'.format(name=name,
data=projector.id)) data=projector.id))
@ -324,7 +323,7 @@ class ProjectorDB(Manager):
""" """
old_projector = self.get_object_filtered(Projector, Projector.ip == projector.ip) old_projector = self.get_object_filtered(Projector, Projector.ip == projector.ip)
if old_projector is not None: if old_projector is not None:
log.warn('add_new() skipping entry ip="{ip}" (Already saved)'.format(ip=old_projector.ip)) log.warning('add_new() skipping entry ip="{ip}" (Already saved)'.format(ip=old_projector.ip))
return False return False
log.debug('add_new() saving new entry') log.debug('add_new() saving new entry')
log.debug('ip="{ip}", name="{name}", location="{location}"'.format(ip=projector.ip, log.debug('ip="{ip}", name="{name}", location="{location}"'.format(ip=projector.ip,
@ -408,10 +407,10 @@ class ProjectorDB(Manager):
:param source: ProjectorSource id :param source: ProjectorSource id
:returns: ProjetorSource instance or None :returns: ProjetorSource instance or None
""" """
source_entry = self.get_object_filtered(ProjetorSource, ProjectorSource.id == source) source_entry = self.get_object_filtered(ProjectorSource, ProjectorSource.id == source)
if source_entry is None: if source_entry is None:
# Not found # Not found
log.warn('get_source_by_id() did not find "{source}"'.format(source=source)) log.warning('get_source_by_id() did not find "{source}"'.format(source=source))
return None return None
log.debug('get_source_by_id() returning one entry for "{source}""'.format(source=source)) log.debug('get_source_by_id() returning one entry for "{source}""'.format(source=source))
return source_entry return source_entry
@ -430,8 +429,8 @@ class ProjectorDB(Manager):
if source_entry is None: if source_entry is None:
# Not found # Not found
log.warn('get_source_by_id() not found') log.warning('get_source_by_id() not found')
log.warn('code="{code}" projector_id="{data}"'.format(code=code, data=projector_id)) log.warning('code="{code}" projector_id="{data}"'.format(code=code, data=projector_id))
return None return None
log.debug('get_source_by_id() returning one entry') log.debug('get_source_by_id() returning one entry')
log.debug('code="{code}" projector_id="{data}"'.format(code=code, data=projector_id)) log.debug('code="{code}" projector_id="{data}"'.format(code=code, data=projector_id))

View File

@ -310,10 +310,10 @@ class PJLink1(QTcpSocket):
read = self.readLine(self.maxSize) read = self.readLine(self.maxSize)
dontcare = self.readLine(self.maxSize) # Clean out the trailing \r\n dontcare = self.readLine(self.maxSize) # Clean out the trailing \r\n
if read is None: if read is None:
log.warn('({ip}) read is None - socket error?'.format(ip=self.ip)) log.warning('({ip}) read is None - socket error?'.format(ip=self.ip))
return return
elif len(read) < 8: elif len(read) < 8:
log.warn('({ip}) Not enough data read)'.format(ip=self.ip)) log.warning('({ip}) Not enough data read)'.format(ip=self.ip))
return return
data = decode(read, 'ascii') data = decode(read, 'ascii')
# Possibility of extraneous data on input when reading. # Possibility of extraneous data on input when reading.
@ -402,7 +402,7 @@ class PJLink1(QTcpSocket):
self.projectorReceivedData.emit() self.projectorReceivedData.emit()
return return
elif '=' not in data: elif '=' not in data:
log.warn('({ip}) get_data(): Invalid packet received'.format(ip=self.ip)) log.warning('({ip}) get_data(): Invalid packet received'.format(ip=self.ip))
self.send_busy = False self.send_busy = False
self.projectorReceivedData.emit() self.projectorReceivedData.emit()
return return
@ -410,15 +410,15 @@ class PJLink1(QTcpSocket):
try: try:
(prefix, class_, cmd, data) = (data_split[0][0], data_split[0][1], data_split[0][2:], data_split[1]) (prefix, class_, cmd, data) = (data_split[0][0], data_split[0][1], data_split[0][2:], data_split[1])
except ValueError as e: except ValueError as e:
log.warn('({ip}) get_data(): Invalid packet - expected header + command + data'.format(ip=self.ip)) log.warning('({ip}) get_data(): Invalid packet - expected header + command + data'.format(ip=self.ip))
log.warn('({ip}) get_data(): Received data: "{data}"'.format(ip=self.ip, data=data_in.strip())) log.warning('({ip}) get_data(): Received data: "{data}"'.format(ip=self.ip, data=data_in.strip()))
self.change_status(E_INVALID_DATA) self.change_status(E_INVALID_DATA)
self.send_busy = False self.send_busy = False
self.projectorReceivedData.emit() self.projectorReceivedData.emit()
return return
if not (self.pjlink_class in PJLINK_VALID_CMD and cmd in PJLINK_VALID_CMD[self.pjlink_class]): if not (self.pjlink_class in PJLINK_VALID_CMD and cmd in PJLINK_VALID_CMD[self.pjlink_class]):
log.warn('({ip}) get_data(): Invalid packet - unknown command "{data}"'.format(ip=self.ip, data=cmd)) log.warning('({ip}) get_data(): Invalid packet - unknown command "{data}"'.format(ip=self.ip, data=cmd))
self.send_busy = False self.send_busy = False
self.projectorReceivedData.emit() self.projectorReceivedData.emit()
return return
@ -461,7 +461,7 @@ class PJLink1(QTcpSocket):
:param queue: Option to force add to queue rather than sending directly :param queue: Option to force add to queue rather than sending directly
""" """
if self.state() != self.ConnectedState: if self.state() != self.ConnectedState:
log.warn('({ip}) send_command(): Not connected - returning'.format(ip=self.ip)) log.warning('({ip}) send_command(): Not connected - returning'.format(ip=self.ip))
self.send_queue = [] self.send_queue = []
return return
self.projectorNetwork.emit(S_NETWORK_SENDING) self.projectorNetwork.emit(S_NETWORK_SENDING)
@ -577,7 +577,7 @@ class PJLink1(QTcpSocket):
if cmd in self.PJLINK1_FUNC: if cmd in self.PJLINK1_FUNC:
self.PJLINK1_FUNC[cmd](data) self.PJLINK1_FUNC[cmd](data)
else: else:
log.warn('({ip}) Invalid command {data}'.format(ip=self.ip, data=cmd)) log.warning('({ip}) Invalid command {data}'.format(ip=self.ip, data=cmd))
self.send_busy = False self.send_busy = False
self.projectorReceivedData.emit() self.projectorReceivedData.emit()
@ -596,7 +596,7 @@ class PJLink1(QTcpSocket):
fill = {'Hours': int(data_dict[0]), 'On': False if data_dict[1] == '0' else True} fill = {'Hours': int(data_dict[0]), 'On': False if data_dict[1] == '0' else True}
except ValueError: except ValueError:
# In case of invalid entry # In case of invalid entry
log.warn('({ip}) process_lamp(): Invalid data "{data}"'.format(ip=self.ip, data=data)) log.warning('({ip}) process_lamp(): Invalid data "{data}"'.format(ip=self.ip, data=data))
return return
lamps.append(fill) lamps.append(fill)
data_dict.pop(0) # Remove lamp hours data_dict.pop(0) # Remove lamp hours
@ -623,7 +623,7 @@ class PJLink1(QTcpSocket):
self.send_command('INST') self.send_command('INST')
else: else:
# Log unknown status response # Log unknown status response
log.warn('({ip}) Unknown power response: {data}'.format(ip=self.ip, data=data)) log.warning('({ip}) Unknown power response: {data}'.format(ip=self.ip, data=data))
return return
def process_avmt(self, data): def process_avmt(self, data):
@ -648,7 +648,7 @@ class PJLink1(QTcpSocket):
shutter = True shutter = True
mute = True mute = True
else: else:
log.warn('({ip}) Unknown shutter response: {data}'.format(ip=self.ip, data=data)) log.warning('({ip}) Unknown shutter response: {data}'.format(ip=self.ip, data=data))
update_icons = shutter != self.shutter update_icons = shutter != self.shutter
update_icons = update_icons or mute != self.mute update_icons = update_icons or mute != self.mute
self.shutter = shutter self.shutter = shutter
@ -797,7 +797,7 @@ class PJLink1(QTcpSocket):
Initiate connection to projector. Initiate connection to projector.
""" """
if self.state() == self.ConnectedState: if self.state() == self.ConnectedState:
log.warn('({ip}) connect_to_host(): Already connected - returning'.format(ip=self.ip)) log.warning('({ip}) connect_to_host(): Already connected - returning'.format(ip=self.ip))
return return
self.change_status(S_CONNECTING) self.change_status(S_CONNECTING)
self.connectToHost(self.ip, self.port if type(self.port) is int else int(self.port)) self.connectToHost(self.ip, self.port if type(self.port) is int else int(self.port))
@ -809,9 +809,9 @@ class PJLink1(QTcpSocket):
""" """
if abort or self.state() != self.ConnectedState: if abort or self.state() != self.ConnectedState:
if abort: if abort:
log.warn('({ip}) disconnect_from_host(): Aborting connection'.format(ip=self.ip)) log.warning('({ip}) disconnect_from_host(): Aborting connection'.format(ip=self.ip))
else: else:
log.warn('({ip}) disconnect_from_host(): Not connected - returning'.format(ip=self.ip)) log.warning('({ip}) disconnect_from_host(): Not connected - returning'.format(ip=self.ip))
self.reset_information() self.reset_information()
self.disconnectFromHost() self.disconnectFromHost()
try: try:

View File

@ -531,7 +531,7 @@ def words_split(line):
:param line: Line to be split :param line: Line to be split
""" """
# this parse we are to be wordy # this parse we are to be wordy
return re.split('\s+', line) return re.split(r'\s+', line)
def get_start_tags(raw_text): def get_start_tags(raw_text):

View File

@ -34,7 +34,7 @@ import ntpath
from PyQt5 import QtGui from PyQt5 import QtGui
from openlp.core.common import RegistryProperties, Settings, translate, AppLocation, md5_hash from openlp.core.common import RegistryProperties, Settings, translate, AppLocation, md5_hash
from openlp.core.lib import ImageSource, build_icon, clean_tags, expand_tags, create_thumb from openlp.core.lib import ImageSource, build_icon, clean_tags, expand_tags
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View File

@ -23,7 +23,6 @@
Provide the theme XML and handling functions for OpenLP v2 themes. Provide the theme XML and handling functions for OpenLP v2 themes.
""" """
import os import os
import re
import logging import logging
import json import json
@ -477,12 +476,12 @@ class ThemeXML(object):
if element == 'weight': if element == 'weight':
element = 'bold' element = 'bold'
if value == 'Normal': if value == 'Normal':
value = False ret_value = False
else: else:
value = True ret_value = True
if element == 'proportion': if element == 'proportion':
element = 'size' element = 'size'
return False, master, element, value return False, master, element, ret_value
def _create_attr(self, master, element, value): def _create_attr(self, master, element, value):
""" """

View File

@ -179,5 +179,4 @@ def get_web_page(url, header=None, update_openlp=False):
return page return page
__all__ = ['get_application_version', 'check_latest_version', __all__ = ['get_web_page']
'get_web_page']

View File

@ -32,8 +32,6 @@ import sqlalchemy
from PyQt5 import Qt, QtCore, QtGui, QtWebKit, QtWidgets from PyQt5 import Qt, QtCore, QtGui, QtWebKit, QtWidgets
from lxml import etree from lxml import etree
from openlp.core.common import RegistryProperties, is_linux
try: try:
import migrate import migrate
MIGRATE_VERSION = getattr(migrate, '__version__', '< 0.7') MIGRATE_VERSION = getattr(migrate, '__version__', '< 0.7')
@ -74,6 +72,7 @@ except ImportError:
from openlp.core.common import Settings, UiStrings, translate from openlp.core.common import Settings, UiStrings, translate
from openlp.core.common.versionchecker import get_application_version from openlp.core.common.versionchecker import get_application_version
from openlp.core.common import RegistryProperties, is_linux
from .exceptiondialog import Ui_ExceptionDialog from .exceptiondialog import Ui_ExceptionDialog

View File

@ -666,14 +666,14 @@ class FirstTimeForm(QtWidgets.QWizard, UiFirstTimeWizard, RegistryProperties):
if missed_files: if missed_files:
file_list = '' file_list = ''
for entry in missed_files: for entry in missed_files:
file_list += '{text}<br \>'.format(text=entry) file_list += '{text}<br \\>'.format(text=entry)
msg = QtWidgets.QMessageBox() msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setIcon(QtWidgets.QMessageBox.Warning)
msg.setWindowTitle(translate('OpenLP.FirstTimeWizard', 'Network Error')) msg.setWindowTitle(translate('OpenLP.FirstTimeWizard', 'Network Error'))
msg.setText(translate('OpenLP.FirstTimeWizard', 'Unable to download some files')) msg.setText(translate('OpenLP.FirstTimeWizard', 'Unable to download some files'))
msg.setInformativeText(translate('OpenLP.FirstTimeWizard', msg.setInformativeText(translate('OpenLP.FirstTimeWizard',
'The following files were not able to be ' 'The following files were not able to be '
'downloaded:<br \>{text}'.format(text=file_list))) 'downloaded:<br \\>{text}'.format(text=file_list)))
msg.setStandardButtons(msg.Ok) msg.setStandardButtons(msg.Ok)
ans = msg.exec() ans = msg.exec()
return True return True

View File

@ -84,7 +84,7 @@ class FormattingTagController(object):
'desc': desc, 'desc': desc,
'start tag': '{{{tag}}}'.format(tag=tag), 'start tag': '{{{tag}}}'.format(tag=tag),
'start html': start_html, 'start html': start_html,
'end tag': '{/{tag}}}'.format(tag=tag), 'end tag': '{{{tag}}}'.format(tag=tag),
'end html': end_html, 'end html': end_html,
'protected': False, 'protected': False,
'temporary': False 'temporary': False

View File

@ -164,7 +164,7 @@ class Highlighter(QtGui.QSyntaxHighlighter):
""" """
Provides a text highlighter for pointing out spelling errors in text. Provides a text highlighter for pointing out spelling errors in text.
""" """
WORDS = '(?iu)[\w\']+' WORDS = r'(?iu)[\w\']+'
def __init__(self, *args): def __init__(self, *args):
""" """

View File

@ -33,7 +33,7 @@ import html
import logging import logging
import os import os
from PyQt5 import QtCore, QtWidgets, QtWebKit, QtWebKitWidgets, QtOpenGL, QtGui, QtMultimedia from PyQt5 import QtCore, QtWidgets, QtWebKit, QtWebKitWidgets, QtGui, QtMultimedia
from openlp.core.common import AppLocation, Registry, RegistryProperties, OpenLPMixin, Settings, translate,\ from openlp.core.common import AppLocation, Registry, RegistryProperties, OpenLPMixin, Settings, translate,\
is_macosx, is_win is_macosx, is_win
@ -468,9 +468,9 @@ class MainDisplay(OpenLPMixin, Display, RegistryProperties):
self.service_item.theme_data.background_filename, ImageSource.Theme) self.service_item.theme_data.background_filename, ImageSource.Theme)
if image_path: if image_path:
image_bytes = self.image_manager.get_image_bytes(image_path, ImageSource.ImagePlugin) image_bytes = self.image_manager.get_image_bytes(image_path, ImageSource.ImagePlugin)
html = build_html(self.service_item, self.screen, self.is_live, background, image_bytes, created_html = build_html(self.service_item, self.screen, self.is_live, background, image_bytes,
plugins=self.plugin_manager.plugins) plugins=self.plugin_manager.plugins)
self.web_view.setHtml(html) self.web_view.setHtml(created_html)
if service_item.foot_text: if service_item.foot_text:
self.footer(service_item.foot_text) self.footer(service_item.foot_text)
# if was hidden keep it hidden # if was hidden keep it hidden

View File

@ -46,7 +46,6 @@ from openlp.core.ui.firsttimeform import FirstTimeForm
from openlp.core.ui.media import MediaController from openlp.core.ui.media import MediaController
from openlp.core.ui.printserviceform import PrintServiceForm from openlp.core.ui.printserviceform import PrintServiceForm
from openlp.core.ui.projector.manager import ProjectorManager from openlp.core.ui.projector.manager import ProjectorManager
from openlp.core.ui.lib.toolbar import OpenLPToolbar
from openlp.core.ui.lib.dockwidget import OpenLPDockWidget from openlp.core.ui.lib.dockwidget import OpenLPDockWidget
from openlp.core.ui.lib.mediadockmanager import MediaDockManager from openlp.core.ui.lib.mediadockmanager import MediaDockManager

View File

@ -24,10 +24,10 @@ The :mod:`~openlp.core.ui.media` module contains classes and objects for media p
""" """
import logging import logging
from openlp.core.common import Settings
from PyQt5 import QtCore from PyQt5 import QtCore
from openlp.core.common import Settings
log = logging.getLogger(__name__ + '.__init__') log = logging.getLogger(__name__ + '.__init__')

View File

@ -38,7 +38,6 @@ from openlp.core.ui.media.mediaplayer import MediaPlayer
from openlp.core.ui.media import MediaState, MediaInfo, MediaType, get_media_players, set_media_players,\ from openlp.core.ui.media import MediaState, MediaInfo, MediaType, get_media_players, set_media_players,\
parse_optical_path parse_optical_path
from openlp.core.ui.lib.toolbar import OpenLPToolbar from openlp.core.ui.lib.toolbar import OpenLPToolbar
from openlp.core.ui.lib.dockwidget import OpenLPDockWidget
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -175,7 +174,7 @@ class MediaController(RegistryMixin, OpenLPMixin, RegistryProperties):
log.debug('_check_available_media_players') log.debug('_check_available_media_players')
controller_dir = os.path.join(AppLocation.get_directory(AppLocation.AppDir), 'core', 'ui', 'media') controller_dir = os.path.join(AppLocation.get_directory(AppLocation.AppDir), 'core', 'ui', 'media')
for filename in os.listdir(controller_dir): for filename in os.listdir(controller_dir):
if filename.endswith('player.py') and not filename == 'mediaplayer.py': if filename.endswith('player.py') and filename != 'mediaplayer.py':
path = os.path.join(controller_dir, filename) path = os.path.join(controller_dir, filename)
if os.path.isfile(path): if os.path.isfile(path):
module_name = 'openlp.core.ui.media.' + os.path.splitext(filename)[0] module_name = 'openlp.core.ui.media.' + os.path.splitext(filename)[0]
@ -554,7 +553,7 @@ class MediaController(RegistryMixin, OpenLPMixin, RegistryProperties):
default_player = [used_players[0]] default_player = [used_players[0]]
if service_item.processor and service_item.processor != UiStrings().Automatic: if service_item.processor and service_item.processor != UiStrings().Automatic:
# check to see if the player is usable else use the default one. # check to see if the player is usable else use the default one.
if not service_item.processor.lower() in used_players: if service_item.processor.lower() not in used_players:
used_players = default_player used_players = default_player
else: else:
used_players = [service_item.processor.lower()] used_players = [service_item.processor.lower()]

View File

@ -224,9 +224,11 @@ class PlayerTab(SettingsTab):
self.settings_form.register_post_process('mediaitem_media_rebuild') self.settings_form.register_post_process('mediaitem_media_rebuild')
self.settings_form.register_post_process('config_screen_changed') self.settings_form.register_post_process('config_screen_changed')
def post_set_up(self): def post_set_up(self, post_update=False):
""" """
Late setup for players as the MediaController has to be initialised first. Late setup for players as the MediaController has to be initialised first.
:param post_update: Indicates if called before or after updates.
""" """
for key, player in self.media_players.items(): for key, player in self.media_players.items():
player = self.media_players[key] player = self.media_players[key]

View File

@ -112,7 +112,6 @@ def get_vlc():
# This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups # This needs to happen on module load and not in get_vlc(), otherwise it can cause crashes on some DE on some setups
# (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs... # (reported on Gnome3, Unity, Cinnamon, all GTK+ based) when using native filedialogs...
if is_linux() and 'nose' not in sys.argv[0] and get_vlc(): if is_linux() and 'nose' not in sys.argv[0] and get_vlc():
import ctypes
try: try:
try: try:
x11 = ctypes.cdll.LoadLibrary('libX11.so.6') x11 = ctypes.cdll.LoadLibrary('libX11.so.6')
@ -233,7 +232,7 @@ class VlcPlayer(MediaPlayer):
""" """
vlc = get_vlc() vlc = get_vlc()
start = datetime.now() start = datetime.now()
while not media_state == display.vlc_media.get_state(): while media_state != display.vlc_media.get_state():
if display.vlc_media.get_state() == vlc.State.Error: if display.vlc_media.get_state() == vlc.State.Error:
return False return False
self.application.process_events() self.application.process_events()

View File

@ -22,10 +22,10 @@
""" """
The :mod:`~openlp.core.ui.media.webkit` module contains our WebKit video player The :mod:`~openlp.core.ui.media.webkit` module contains our WebKit video player
""" """
from PyQt5 import QtGui, QtWebKitWidgets
import logging import logging
from PyQt5 import QtGui, QtWebKitWidgets
from openlp.core.common import Settings from openlp.core.common import Settings
from openlp.core.lib import translate from openlp.core.lib import translate
from openlp.core.ui.media import MediaState from openlp.core.ui.media import MediaState

View File

@ -141,23 +141,23 @@ def Build_Tab(group, source_key, default, projector, projectordb, edit=False):
return widget, button_count, buttonchecked return widget, button_count, buttonchecked
def set_button_tooltip(bar): def set_button_tooltip(button_bar):
""" """
Set the toolip for the standard buttons used Set the toolip for the standard buttons used
:param bar: QDialogButtonBar instance to update :param button_bar: QDialogButtonBar instance to update
""" """
for button in bar.buttons(): for button in button_bar.buttons():
if bar.standardButton(button) == QDialogButtonBox.Cancel: if button_bar.standardButton(button) == QDialogButtonBox.Cancel:
button.setToolTip(translate('OpenLP.SourceSelectForm', button.setToolTip(translate('OpenLP.SourceSelectForm',
'Ignoring current changes and return to OpenLP')) 'Ignoring current changes and return to OpenLP'))
elif bar.standardButton(button) == QDialogButtonBox.Reset: elif button_bar.standardButton(button) == QDialogButtonBox.Reset:
button.setToolTip(translate('OpenLP.SourceSelectForm', button.setToolTip(translate('OpenLP.SourceSelectForm',
'Delete all user-defined text and revert to PJLink default text')) 'Delete all user-defined text and revert to PJLink default text'))
elif bar.standardButton(button) == QDialogButtonBox.Discard: elif button_bar.standardButton(button) == QDialogButtonBox.Discard:
button.setToolTip(translate('OpenLP.SourceSelectForm', button.setToolTip(translate('OpenLP.SourceSelectForm',
'Discard changes and reset to previous user-defined text')) 'Discard changes and reset to previous user-defined text'))
elif bar.standardButton(button) == QDialogButtonBox.Ok: elif button_bar.standardButton(button) == QDialogButtonBox.Ok:
button.setToolTip(translate('OpenLP.SourceSelectForm', button.setToolTip(translate('OpenLP.SourceSelectForm',
'Save changes and return to OpenLP')) 'Save changes and return to OpenLP'))
else: else:

View File

@ -133,7 +133,7 @@ class ProjectorTab(SettingsTab):
settings.setValue('socket timeout', self.socket_timeout_spin_box.value()) settings.setValue('socket timeout', self.socket_timeout_spin_box.value())
settings.setValue('poll time', self.socket_poll_spin_box.value()) settings.setValue('poll time', self.socket_poll_spin_box.value())
settings.setValue('source dialog type', self.dialog_type_combo_box.currentIndex()) settings.setValue('source dialog type', self.dialog_type_combo_box.currentIndex())
settings.endGroup settings.endGroup()
def on_dialog_type_combo_box_changed(self): def on_dialog_type_combo_box_changed(self):
self.dialog_type = self.dialog_type_combo_box.currentIndex() self.dialog_type = self.dialog_type_combo_box.currentIndex()

View File

@ -774,7 +774,7 @@ class ServiceManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ServiceMa
else: else:
critical_error_message_box(message=translate('OpenLP.ServiceManager', 'File is not a valid service.')) critical_error_message_box(message=translate('OpenLP.ServiceManager', 'File is not a valid service.'))
self.log_error('File contains no service data') self.log_error('File contains no service data')
except (IOError, NameError, zipfile.BadZipfile): except (IOError, NameError):
self.log_exception('Problem loading service file {name}'.format(name=file_name)) self.log_exception('Problem loading service file {name}'.format(name=file_name))
critical_error_message_box(message=translate('OpenLP.ServiceManager', critical_error_message_box(message=translate('OpenLP.ServiceManager',
'File could not be opened because it is corrupt.')) 'File could not be opened because it is corrupt.'))
@ -1327,7 +1327,7 @@ class ServiceManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ServiceMa
""" """
The theme may have changed in the settings dialog so make sure the theme combo box is in the correct state. The theme may have changed in the settings dialog so make sure the theme combo box is in the correct state.
""" """
visible = not self.renderer.theme_level == ThemeLevel.Global visible = self.renderer.theme_level != ThemeLevel.Global
self.toolbar.actions['theme_combo_box'].setVisible(visible) self.toolbar.actions['theme_combo_box'].setVisible(visible)
self.toolbar.actions['theme_label'].setVisible(visible) self.toolbar.actions['theme_label'].setVisible(visible)
self.regenerate_service_items() self.regenerate_service_items()

View File

@ -37,7 +37,6 @@ from openlp.core.lib import ItemCapabilities, ServiceItem, ImageSource, ServiceI
build_html build_html
from openlp.core.lib.ui import create_action from openlp.core.lib.ui import create_action
from openlp.core.ui.lib.toolbar import OpenLPToolbar from openlp.core.ui.lib.toolbar import OpenLPToolbar
from openlp.core.ui.lib.dockwidget import OpenLPDockWidget
from openlp.core.ui.lib.listpreviewwidget import ListPreviewWidget from openlp.core.ui.lib.listpreviewwidget import ListPreviewWidget
from openlp.core.ui import HideMode, MainDisplay, Display, DisplayControllerType from openlp.core.ui import HideMode, MainDisplay, Display, DisplayControllerType

View File

@ -249,7 +249,7 @@ class ThemeForm(QtWidgets.QWizard, Ui_ThemeWizard, RegistryProperties):
NOTE the font_main_override is the inverse of the check box value NOTE the font_main_override is the inverse of the check box value
""" """
if self.update_theme_allowed: if self.update_theme_allowed:
self.theme.font_main_override = not (value == QtCore.Qt.Checked) self.theme.font_main_override = (value != QtCore.Qt.Checked)
def on_footer_position_check_box_state_changed(self, value): def on_footer_position_check_box_state_changed(self, value):
""" """
@ -257,7 +257,7 @@ class ThemeForm(QtWidgets.QWizard, Ui_ThemeWizard, RegistryProperties):
NOTE the font_footer_override is the inverse of the check box value NOTE the font_footer_override is the inverse of the check box value
""" """
if self.update_theme_allowed: if self.update_theme_allowed:
self.theme.font_footer_override = not (value == QtCore.Qt.Checked) self.theme.font_footer_override = (value != QtCore.Qt.Checked)
def exec(self, edit=False): def exec(self, edit=False):
""" """

View File

@ -583,7 +583,7 @@ class ThemeManager(OpenLPMixin, RegistryMixin, QtWidgets.QWidget, Ui_ThemeManage
out_file.write(theme_zip.read(name)) out_file.write(theme_zip.read(name))
out_file.close() out_file.close()
except (IOError, zipfile.BadZipfile): except (IOError, zipfile.BadZipfile):
self.log_exception('Importing theme from zip failed {name|'.format(name=file_name)) self.log_exception('Importing theme from zip failed {name}'.format(name=file_name))
raise ValidationError raise ValidationError
except ValidationError: except ValidationError:
critical_error_message_box(translate('OpenLP.ThemeManager', 'Validation Error'), critical_error_message_box(translate('OpenLP.ThemeManager', 'Validation Error'),

View File

@ -28,7 +28,7 @@ from PyQt5 import QtCore
from openlp.core.common import Registry from openlp.core.common import Registry
from openlp.core.ui import HideMode from openlp.core.ui import HideMode
from openlp.core.lib import ServiceItemContext, ServiceItem from openlp.core.lib import ServiceItemContext
from openlp.plugins.presentations.lib.pdfcontroller import PDF_CONTROLLER_FILETYPES from openlp.plugins.presentations.lib.pdfcontroller import PDF_CONTROLLER_FILETYPES
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View File

@ -80,7 +80,7 @@ class PdfController(PresentationController):
found_mutool = re.search('usage: mutool.*', decoded_line, re.IGNORECASE) found_mutool = re.search('usage: mutool.*', decoded_line, re.IGNORECASE)
if found_mutool: if found_mutool:
# Test that mutool contains mudraw # Test that mutool contains mudraw
if re.search('draw\s+--\s+convert document.*', runlog.decode(), re.IGNORECASE | re.MULTILINE): if re.search(r'draw\s+--\s+convert document.*', runlog.decode(), re.IGNORECASE | re.MULTILINE):
program_type = 'mutool' program_type = 'mutool'
break break
found_gs = re.search('GPL Ghostscript.*', decoded_line, re.IGNORECASE) found_gs = re.search('GPL Ghostscript.*', decoded_line, re.IGNORECASE)
@ -215,8 +215,8 @@ class PdfDocument(PresentationDocument):
height = 0.0 height = 0.0
for line in runlog.splitlines(): for line in runlog.splitlines():
try: try:
width = float(re.search('.*Size: x: (\d+\.?\d*), y: \d+.*', line.decode()).group(1)) width = float(re.search(r'.*Size: x: (\d+\.?\d*), y: \d+.*', line.decode()).group(1))
height = float(re.search('.*Size: x: \d+\.?\d*, y: (\d+\.?\d*).*', line.decode()).group(1)) height = float(re.search(r'.*Size: x: \d+\.?\d*, y: (\d+\.?\d*).*', line.decode()).group(1))
break break
except AttributeError: except AttributeError:
continue continue

View File

@ -181,13 +181,13 @@ class PptviewDocument(PresentationDocument):
index = -1 index = -1
list_to_add = None list_to_add = None
# check if it is a slide # check if it is a slide
match = re.search("slides/slide(.+)\.xml", zip_info.filename) match = re.search(r'slides/slide(.+)\.xml', zip_info.filename)
if match: if match:
index = int(match.group(1)) - 1 index = int(match.group(1)) - 1
node_type = 'ctrTitle' node_type = 'ctrTitle'
list_to_add = titles list_to_add = titles
# or a note # or a note
match = re.search("notesSlides/notesSlide(.+)\.xml", zip_info.filename) match = re.search(r'notesSlides/notesSlide(.+)\.xml', zip_info.filename)
if match: if match:
index = int(match.group(1)) - 1 index = int(match.group(1)) - 1
node_type = 'body' node_type = 'body'

View File

@ -124,7 +124,7 @@ class PresentationPlugin(Plugin):
log.debug('check_pre_conditions') log.debug('check_pre_conditions')
controller_dir = os.path.join(AppLocation.get_directory(AppLocation.PluginsDir), 'presentations', 'lib') controller_dir = os.path.join(AppLocation.get_directory(AppLocation.PluginsDir), 'presentations', 'lib')
for filename in os.listdir(controller_dir): for filename in os.listdir(controller_dir):
if filename.endswith('controller.py') and not filename == 'presentationcontroller.py': if filename.endswith('controller.py') and filename != 'presentationcontroller.py':
path = os.path.join(controller_dir, filename) path = os.path.join(controller_dir, filename)
if os.path.isfile(path): if os.path.isfile(path):
module_name = 'openlp.plugins.presentations.lib.' + os.path.splitext(filename)[0] module_name = 'openlp.plugins.presentations.lib.' + os.path.splitext(filename)[0]

View File

@ -112,7 +112,6 @@ class TestServiceItem(TestCase):
# WHEN: adding an image from a saved Service and mocked exists # WHEN: adding an image from a saved Service and mocked exists
line = convert_file_service_item(TEST_PATH, 'serviceitem_image_1.osj') line = convert_file_service_item(TEST_PATH, 'serviceitem_image_1.osj')
with patch('openlp.core.ui.servicemanager.os.path.exists') as mocked_exists,\ with patch('openlp.core.ui.servicemanager.os.path.exists') as mocked_exists,\
patch('openlp.core.lib.serviceitem.create_thumb') as mocked_create_thumb,\
patch('openlp.core.lib.serviceitem.AppLocation.get_section_data_path') as \ patch('openlp.core.lib.serviceitem.AppLocation.get_section_data_path') as \
mocked_get_section_data_path: mocked_get_section_data_path:
mocked_exists.return_value = True mocked_exists.return_value = True
@ -164,7 +163,6 @@ class TestServiceItem(TestCase):
line2 = convert_file_service_item(TEST_PATH, 'serviceitem_image_2.osj', 1) line2 = convert_file_service_item(TEST_PATH, 'serviceitem_image_2.osj', 1)
with patch('openlp.core.ui.servicemanager.os.path.exists') as mocked_exists, \ with patch('openlp.core.ui.servicemanager.os.path.exists') as mocked_exists, \
patch('openlp.core.lib.serviceitem.create_thumb') as mocked_create_thumb, \
patch('openlp.core.lib.serviceitem.AppLocation.get_section_data_path') as \ patch('openlp.core.lib.serviceitem.AppLocation.get_section_data_path') as \
mocked_get_section_data_path: mocked_get_section_data_path:
mocked_exists.return_value = True mocked_exists.return_value = True

View File

@ -27,6 +27,7 @@ import logging
from unittest import TestCase from unittest import TestCase
from pylint import epylint as lint from pylint import epylint as lint
from pylint.__pkginfo__ import pylint_version
class TestPylint(TestCase): class TestPylint(TestCase):
@ -37,17 +38,19 @@ class TestPylint(TestCase):
""" """
# GIVEN: The openlp base folder # GIVEN: The openlp base folder
enabled_checks = 'missing-format-argument-key,unused-format-string-argument' enabled_checks = 'missing-format-argument-key,unused-format-string-argument'
disabled_checks = 'all' #disabled_checks = 'all'
disabled_checks = ''
# WHEN: Running pylint # WHEN: Running pylint
(pylint_stdout, pylint_stderr) = \ (pylint_stdout, pylint_stderr) = \
lint.py_run('{path} --disable={disabled} --enable={enabled} --reports=no'.format(path='openlp', lint.py_run('{path} --disable={disabled} --enable={enabled} --reports=no'.format(path='openlp',
disabled=disabled_checks, disabled=disabled_checks,
enabled=enabled_checks), enabled=enabled_checks),
return_std=True) return_std=True, script='pylint3')
stdout = pylint_stdout.read() stdout = pylint_stdout.read()
stderr = pylint_stderr.read() stderr = pylint_stderr.read()
print(stdout) print(stdout)
print(stderr)
# THEN: The output should be empty # THEN: The output should be empty
self.assertTrue(stdout == '', 'PyLint should find no errors') self.assertTrue(stdout == 's', 'PyLint should find no errors')