Update to trunk r1960

This commit is contained in:
Samuel Findlay 2012-05-02 00:00:53 +10:00
commit ecc943ae20
35 changed files with 256 additions and 276 deletions

View File

@ -1 +1 @@
1.9.5-bzr1421 1.9.9-bzr1956

View File

@ -49,7 +49,7 @@ from openlp.core.ui.firsttimeform import FirstTimeForm
from openlp.core.ui.exceptionform import ExceptionForm from openlp.core.ui.exceptionform import ExceptionForm
from openlp.core.ui import SplashScreen, ScreenList from openlp.core.ui import SplashScreen, ScreenList
from openlp.core.utils import AppLocation, LanguageManager, VersionThread, \ from openlp.core.utils import AppLocation, LanguageManager, VersionThread, \
get_application_version, DelayStartThread get_application_version
__all__ = [u'OpenLP', u'main'] __all__ = [u'OpenLP', u'main']
@ -145,7 +145,6 @@ class OpenLP(QtGui.QApplication):
VersionThread(self.mainWindow).start() VersionThread(self.mainWindow).start()
Receiver.send_message(u'live_display_blank_check') Receiver.send_message(u'live_display_blank_check')
self.mainWindow.appStartup() self.mainWindow.appStartup()
DelayStartThread(self.mainWindow).start()
# Skip exec_() for gui tests # Skip exec_() for gui tests
if not testing: if not testing:
return self.exec_() return self.exec_()

View File

@ -209,7 +209,7 @@ class Theme(object):
val = int(element_text[1:], 16) val = int(element_text[1:], 16)
except ValueError: # nope except ValueError: # nope
pass pass
elif DELPHI_COLORS.has_key(element_text): elif element_text in DELPHI_COLORS:
val = DELPHI_COLORS[element_text] val = DELPHI_COLORS[element_text]
delphi_color_change = True delphi_color_change = True
else: else:

View File

@ -730,7 +730,7 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
if self.liveController.display.isVisible(): if self.liveController.display.isVisible():
self.liveController.display.setFocus() self.liveController.display.setFocus()
self.activateWindow() self.activateWindow()
if len(self.arguments): if self.arguments:
args = [] args = []
for a in self.arguments: for a in self.arguments:
args.extend([a]) args.extend([a])

View File

@ -69,12 +69,13 @@ class MediaInfo(object):
def get_media_players(): def get_media_players():
""" """
This method extract the configured media players and overridden player from This method extract the configured media players and overridden player from
the settings the settings.
``players_list`` ``players_list``
this is a python list with all active media players A list with all active media players.
``overridden_player`` ``overridden_player``
here an special media player is choosen for all media actions Here an special media player is chosen for all media actions.
""" """
log.debug(u'get_media_players') log.debug(u'get_media_players')
players = unicode(QtCore.QSettings().value(u'media/players').toString()) players = unicode(QtCore.QSettings().value(u'media/players').toString())
@ -92,15 +93,17 @@ def get_media_players():
players_list = players.replace(u'[', u'').replace(u']', u'').split(u',') players_list = players.replace(u'[', u'').replace(u']', u'').split(u',')
return players_list, overridden_player return players_list, overridden_player
def set_media_players(players_list, overridden_player=u'auto'): def set_media_players(players_list, overridden_player=u'auto'):
""" """
This method saves the configured media players and overridden player to the This method saves the configured media players and overridden player to the
settings settings
``players_list`` ``players_list``
this is a python list with all active media players A list with all active media players.
``overridden_player`` ``overridden_player``
here an special media player is choosen for all media actions Here an special media player is chosen for all media actions.
""" """
log.debug(u'set_media_players') log.debug(u'set_media_players')
players = u','.join(players_list) players = u','.join(players_list)

View File

@ -84,10 +84,7 @@ class MediaController(object):
def set_active_players(self): def set_active_players(self):
savedPlayers = get_media_players()[0] savedPlayers = get_media_players()[0]
for player in self.mediaPlayers.keys(): for player in self.mediaPlayers.keys():
if player in savedPlayers: self.mediaPlayers[player].isActive = player in savedPlayers
self.mediaPlayers[player].isActive = True
else:
self.mediaPlayers[player].isActive = False
def register_controllers(self, controller): def register_controllers(self, controller):
""" """
@ -106,8 +103,8 @@ class MediaController(object):
AppLocation.get_directory(AppLocation.AppDir), AppLocation.get_directory(AppLocation.AppDir),
u'core', u'ui', u'media') u'core', u'ui', u'media')
for filename in os.listdir(controller_dir): for filename in os.listdir(controller_dir):
if filename.endswith(u'player.py') and \ if filename.endswith(u'player.py') and not \
not filename == 'media_player.py': filename == 'media_player.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):
modulename = u'openlp.core.ui.media.' + \ modulename = u'openlp.core.ui.media.' + \
@ -122,38 +119,36 @@ class MediaController(object):
for controller_class in controller_classes: for controller_class in controller_classes:
controller = controller_class(self) controller = controller_class(self)
self.register_controllers(controller) self.register_controllers(controller)
if self.mediaPlayers: if not self.mediaPlayers:
savedPlayers, overriddenPlayer = get_media_players()
invalidMediaPlayers = [mediaPlayer for mediaPlayer in savedPlayers \
if not mediaPlayer in self.mediaPlayers or \
not self.mediaPlayers[mediaPlayer].check_available()]
if len(invalidMediaPlayers) > 0:
for invalidPlayer in invalidMediaPlayers:
savedPlayers.remove(invalidPlayer)
set_media_players(savedPlayers, overriddenPlayer)
self.set_active_players()
return True
else:
return False return False
savedPlayers, overriddenPlayer = get_media_players()
invalidMediaPlayers = [mediaPlayer for mediaPlayer in savedPlayers
if not mediaPlayer in self.mediaPlayers or not
self.mediaPlayers[mediaPlayer].check_available()]
if invalidMediaPlayers:
for invalidPlayer in invalidMediaPlayers:
savedPlayers.remove(invalidPlayer)
set_media_players(savedPlayers, overriddenPlayer)
self.set_active_players()
return True
def video_state(self): def video_state(self):
""" """
Check if there is a running media Player and do updating stuff (e.g. Check if there is a running media Player and do updating stuff (e.g.
update the UI) update the UI)
""" """
if len(self.curDisplayMediaPlayer.keys()) == 0: if not self.curDisplayMediaPlayer.keys():
self.timer.stop() self.timer.stop()
else: else:
for display in self.curDisplayMediaPlayer.keys(): for display in self.curDisplayMediaPlayer.keys():
self.curDisplayMediaPlayer[display].resize(display) self.curDisplayMediaPlayer[display].resize(display)
self.curDisplayMediaPlayer[display].update_ui(display) self.curDisplayMediaPlayer[display].update_ui(display)
if self.curDisplayMediaPlayer[display] \ if self.curDisplayMediaPlayer[display].state == \
.state == MediaState.Playing: MediaState.Playing:
return return
# no players are active anymore # no players are active anymore
for display in self.curDisplayMediaPlayer.keys(): for display in self.curDisplayMediaPlayer.keys():
if self.curDisplayMediaPlayer[display] \ if self.curDisplayMediaPlayer[display].state != MediaState.Paused:
.state != MediaState.Paused:
display.controller.seekSlider.setSliderPosition(0) display.controller.seekSlider.setSliderPosition(0)
self.timer.stop() self.timer.stop()
@ -333,8 +328,7 @@ class MediaController(object):
'Unsupported File'))) 'Unsupported File')))
return False return False
# dont care about actual theme, set a black background # dont care about actual theme, set a black background
if controller.isLive and ( \ if controller.isLive and not controller.media_info.is_background:
controller.media_info.is_background == False):
display.frame.evaluateJavaScript(u'show_video( \ display.frame.evaluateJavaScript(u'show_video( \
"setBackBoard", null, null, null,"visible");') "setBackBoard", null, null, null,"visible");')
# now start playing # now start playing
@ -395,7 +389,7 @@ class MediaController(object):
""" """
Responds to the request to play a loaded video Responds to the request to play a loaded video
``msg`` ``msg``
First element is the controller which should be used First element is the controller which should be used
""" """
log.debug(u'video_play') log.debug(u'video_play')
@ -497,15 +491,15 @@ class MediaController(object):
First element is the boolean for Live indication First element is the boolean for Live indication
""" """
isLive = msg[1] isLive = msg[1]
if isLive: if not isLive:
controller = self.parent.liveController return
for display in self.curDisplayMediaPlayer.keys(): controller = self.parent.liveController
if display.controller == controller: for display in self.curDisplayMediaPlayer.keys():
if self.curDisplayMediaPlayer[display] \ if display.controller != controller or \
.state == MediaState.Playing: self.curDisplayMediaPlayer[display].state != MediaState.Playing:
self.curDisplayMediaPlayer[display].pause(display) continue
self.curDisplayMediaPlayer[display] \ self.curDisplayMediaPlayer[display].pause(display)
.set_visible(display, False) self.curDisplayMediaPlayer[display].set_visible(display, False)
def video_blank(self, msg): def video_blank(self, msg):
""" """
@ -517,16 +511,16 @@ class MediaController(object):
""" """
isLive = msg[1] isLive = msg[1]
hide_mode = msg[2] hide_mode = msg[2]
if isLive: if not isLive:
Receiver.send_message(u'live_display_hide', hide_mode) return
controller = self.parent.liveController Receiver.send_message(u'live_display_hide', hide_mode)
for display in self.curDisplayMediaPlayer.keys(): controller = self.parent.liveController
if display.controller == controller: for display in self.curDisplayMediaPlayer.keys():
if self.curDisplayMediaPlayer[display] \ if display.controller != controller or \
.state == MediaState.Playing: self.curDisplayMediaPlayer[display].state != MediaState.Playing:
self.curDisplayMediaPlayer[display].pause(display) continue
self.curDisplayMediaPlayer[display] \ self.curDisplayMediaPlayer[display].pause(display)
.set_visible(display, False) self.curDisplayMediaPlayer[display].set_visible(display, False)
def video_unblank(self, msg): def video_unblank(self, msg):
""" """
@ -538,19 +532,18 @@ class MediaController(object):
""" """
Receiver.send_message(u'live_display_show') Receiver.send_message(u'live_display_show')
isLive = msg[1] isLive = msg[1]
if isLive: if not isLive:
controller = self.parent.liveController return
for display in self.curDisplayMediaPlayer.keys(): controller = self.parent.liveController
if display.controller == controller: for display in self.curDisplayMediaPlayer.keys():
if self.curDisplayMediaPlayer[display] \ if display.controller != controller or \
.state == MediaState.Paused: self.curDisplayMediaPlayer[display].state != MediaState.Paused:
if self.curDisplayMediaPlayer[display].play(display): continue
self.curDisplayMediaPlayer[display] \ if self.curDisplayMediaPlayer[display].play(display):
.set_visible(display, True) self.curDisplayMediaPlayer[display].set_visible(display, True)
# Start Timer for ui updates # Start Timer for ui updates
if not self.timer.isActive(): if not self.timer.isActive():
self.timer.start() self.timer.start()
def get_audio_extensions_list(self): def get_audio_extensions_list(self):
audio_list = [] audio_list = []
@ -565,9 +558,8 @@ class MediaController(object):
video_list = [] video_list = []
for player in self.mediaPlayers.values(): for player in self.mediaPlayers.values():
if player.isActive: if player.isActive:
for item in player.video_extensions_list: video_list.extend([item for item in player.video_extensions_list
if not item in video_list: if item not in video_list])
video_list.append(item)
return video_list return video_list
def finalise(self): def finalise(self):

View File

@ -2,25 +2,26 @@
# Python ctypes bindings for VLC # Python ctypes bindings for VLC
# #
# Copyright (C) 2009-2010 the VideoLAN team # Copyright (C) 2009-2012 the VideoLAN team
# $Id: $ # $Id: $
# #
# Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr> # Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr>
# Jean Brouwers <MrJean1 at gmail.com> # Jean Brouwers <MrJean1 at gmail.com>
# Geoff Salmon <geoff.salmon at gmail.com>
# #
# This program is free software; you can redistribute it and/or modify # This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser General Public License as
# the Free Software Foundation; either version 2 of the License, or # published by the Free Software Foundation; either version 2.1 of the
# (at your option) any later version. # License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This library is distributed in the hope that it will be useful, but
# but WITHOUT ANY WARRANTY; without even the implied warranty of # WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# GNU General Public License for more details. # Lesser General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser General Public
# along with this program; if not, write to the Free Software # License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA
"""This module provides bindings for the LibVLC public API, see """This module provides bindings for the LibVLC public API, see
U{http://wiki.videolan.org/LibVLC}. U{http://wiki.videolan.org/LibVLC}.
@ -47,7 +48,7 @@ import sys
from inspect import getargspec from inspect import getargspec
__version__ = "N/A" __version__ = "N/A"
build_date = "Tue Jan 17 12:20:48 2012" build_date = "Fri Apr 27 16:47:21 2012"
# Internal guard to prevent internal classes to be directly # Internal guard to prevent internal classes to be directly
# instanciated. # instanciated.
@ -126,7 +127,7 @@ class VLCException(Exception):
try: try:
_Ints = (int, long) _Ints = (int, long)
except NameError: # no long in Python 3+ except NameError: # no long in Python 3+
_Ints = int _Ints = int
_Seqs = (list, tuple) _Seqs = (list, tuple)
# Default instance. It is used to instanciate classes directly in the # Default instance. It is used to instanciate classes directly in the
@ -904,6 +905,11 @@ class Instance(_Ctype):
def media_new(self, mrl, *options): def media_new(self, mrl, *options):
"""Create a new Media instance. """Create a new Media instance.
If mrl contains a colon (:), it will be treated as a
URL. Else, it will be considered as a local path. If you need
more control, directly use media_new_location/media_new_path
methods.
Options can be specified as supplementary string parameters, e.g. Options can be specified as supplementary string parameters, e.g.
C{m = i.media_new('foo.avi', 'sub-filter=marq{marquee=Hello}', 'vout-filter=invert')} C{m = i.media_new('foo.avi', 'sub-filter=marq{marquee=Hello}', 'vout-filter=invert')}
@ -914,7 +920,12 @@ class Instance(_Ctype):
@param options: optional media option=value strings @param options: optional media option=value strings
""" """
m = libvlc_media_new_location(self, mrl) if ':' in mrl:
# Assume it is a URL
m = libvlc_media_new_location(self, mrl)
else:
# Else it should be a local path.
m = libvlc_media_new_path(self, mrl)
for o in options: for o in options:
libvlc_media_add_option(m, o) libvlc_media_add_option(m, o)
m._instance = self m._instance = self
@ -1511,7 +1522,7 @@ class Media(_Ctype):
def save_meta(self): def save_meta(self):
'''Save the meta previously set. '''Save the meta previously set.
@return: true if the write operation was successfull. @return: true if the write operation was successful.
''' '''
return libvlc_media_save_meta(self) return libvlc_media_save_meta(self)
@ -2230,7 +2241,7 @@ class MediaPlayer(_Ctype):
@param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32").
@param rate: sample rate (expressed in Hz). @param rate: sample rate (expressed in Hz).
@param channels: channels count. @param channels: channels count.
@version: LibVLC 1.2.0 or later. @version: LibVLC 2.0.0 or later.
''' '''
return libvlc_audio_set_format(self, format, rate, channels) return libvlc_audio_set_format(self, format, rate, channels)
@ -2378,7 +2389,7 @@ class MediaPlayer(_Ctype):
def navigate(self, navigate): def navigate(self, navigate):
'''Navigate through DVD Menu. '''Navigate through DVD Menu.
@param navigate: the Navigation mode. @param navigate: the Navigation mode.
@version: libVLC 1.2.0 or later. @version: libVLC 2.0.0 or later.
''' '''
return libvlc_media_player_navigate(self, navigate) return libvlc_media_player_navigate(self, navigate)
@ -2489,7 +2500,7 @@ class MediaPlayer(_Ctype):
'''Get the current subtitle delay. Positive values means subtitles are being '''Get the current subtitle delay. Positive values means subtitles are being
displayed later, negative values earlier. displayed later, negative values earlier.
@return: time (in microseconds) the display of subtitles is being delayed. @return: time (in microseconds) the display of subtitles is being delayed.
@version: LibVLC 1.2.0 or later. @version: LibVLC 2.0.0 or later.
''' '''
return libvlc_video_get_spu_delay(self) return libvlc_video_get_spu_delay(self)
@ -2500,7 +2511,7 @@ class MediaPlayer(_Ctype):
The subtitle delay will be reset to zero each time the media changes. The subtitle delay will be reset to zero each time the media changes.
@param i_delay: time (in microseconds) the display of subtitles should be delayed. @param i_delay: time (in microseconds) the display of subtitles should be delayed.
@return: 0 on success, -1 on error. @return: 0 on success, -1 on error.
@version: LibVLC 1.2.0 or later. @version: LibVLC 2.0.0 or later.
''' '''
return libvlc_video_set_spu_delay(self, i_delay) return libvlc_video_set_spu_delay(self, i_delay)
@ -3247,7 +3258,7 @@ def libvlc_media_set_meta(p_md, e_meta, psz_value):
def libvlc_media_save_meta(p_md): def libvlc_media_save_meta(p_md):
'''Save the meta previously set. '''Save the meta previously set.
@param p_md: the media desriptor. @param p_md: the media desriptor.
@return: true if the write operation was successfull. @return: true if the write operation was successful.
''' '''
f = _Cfunctions.get('libvlc_media_save_meta', None) or \ f = _Cfunctions.get('libvlc_media_save_meta', None) or \
_Cfunction('libvlc_media_save_meta', ((1,),), None, _Cfunction('libvlc_media_save_meta', ((1,),), None,
@ -4084,7 +4095,7 @@ def libvlc_audio_set_format(mp, format, rate, channels):
@param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32").
@param rate: sample rate (expressed in Hz). @param rate: sample rate (expressed in Hz).
@param channels: channels count. @param channels: channels count.
@version: LibVLC 1.2.0 or later. @version: LibVLC 2.0.0 or later.
''' '''
f = _Cfunctions.get('libvlc_audio_set_format', None) or \ f = _Cfunctions.get('libvlc_audio_set_format', None) or \
_Cfunction('libvlc_audio_set_format', ((1,), (1,), (1,), (1,),), None, _Cfunction('libvlc_audio_set_format', ((1,), (1,), (1,), (1,),), None,
@ -4328,7 +4339,7 @@ def libvlc_media_player_navigate(p_mi, navigate):
'''Navigate through DVD Menu. '''Navigate through DVD Menu.
@param p_mi: the Media Player. @param p_mi: the Media Player.
@param navigate: the Navigation mode. @param navigate: the Navigation mode.
@version: libVLC 1.2.0 or later. @version: libVLC 2.0.0 or later.
''' '''
f = _Cfunctions.get('libvlc_media_player_navigate', None) or \ f = _Cfunctions.get('libvlc_media_player_navigate', None) or \
_Cfunction('libvlc_media_player_navigate', ((1,), (1,),), None, _Cfunction('libvlc_media_player_navigate', ((1,), (1,),), None,
@ -4554,7 +4565,7 @@ def libvlc_video_get_spu_delay(p_mi):
displayed later, negative values earlier. displayed later, negative values earlier.
@param p_mi: media player. @param p_mi: media player.
@return: time (in microseconds) the display of subtitles is being delayed. @return: time (in microseconds) the display of subtitles is being delayed.
@version: LibVLC 1.2.0 or later. @version: LibVLC 2.0.0 or later.
''' '''
f = _Cfunctions.get('libvlc_video_get_spu_delay', None) or \ f = _Cfunctions.get('libvlc_video_get_spu_delay', None) or \
_Cfunction('libvlc_video_get_spu_delay', ((1,),), None, _Cfunction('libvlc_video_get_spu_delay', ((1,),), None,
@ -4569,7 +4580,7 @@ def libvlc_video_set_spu_delay(p_mi, i_delay):
@param p_mi: media player. @param p_mi: media player.
@param i_delay: time (in microseconds) the display of subtitles should be delayed. @param i_delay: time (in microseconds) the display of subtitles should be delayed.
@return: 0 on success, -1 on error. @return: 0 on success, -1 on error.
@version: LibVLC 1.2.0 or later. @version: LibVLC 2.0.0 or later.
''' '''
f = _Cfunctions.get('libvlc_video_set_spu_delay', None) or \ f = _Cfunctions.get('libvlc_video_set_spu_delay', None) or \
_Cfunction('libvlc_video_set_spu_delay', ((1,), (1,),), None, _Cfunction('libvlc_video_set_spu_delay', ((1,), (1,),), None,

View File

@ -25,30 +25,42 @@
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
import logging
import sys, os
from datetime import datetime from datetime import datetime
try: from distutils.version import LooseVersion
import vlc import logging
vlc_available = bool(vlc.get_default_instance()) import os
except (ImportError, NameError): import sys
vlc_available = False
except OSError, e:
if sys.platform.startswith('win'):
if isinstance(e, WindowsError) and e.winerror == 126:
vlc_available = False
else:
raise
else:
raise
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from openlp.core.lib import Receiver from openlp.core.lib import Receiver
from openlp.core.lib.mediaplayer import MediaPlayer from openlp.core.lib.mediaplayer import MediaPlayer
from openlp.core.ui.media import MediaState from openlp.core.ui.media import MediaState
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
VLC_AVAILABLE = False
try:
import vlc
VLC_AVAILABLE = bool(vlc.get_default_instance())
except (ImportError, NameError):
pass
except OSError, e:
if sys.platform.startswith('win'):
if not isinstance(e, WindowsError) and e.winerror != 126:
raise
else:
raise
if VLC_AVAILABLE:
try:
version = vlc.libvlc_get_version()
except:
version = u'0.0.0'
if LooseVersion(version) < LooseVersion('1.1.0'):
VLC_AVAILABLE = False
log.debug(u'VLC could not be loaded: %s' % version)
AUDIO_EXT = [ AUDIO_EXT = [
u'*.mp3' u'*.mp3'
, u'*.wav' , u'*.wav'
@ -128,7 +140,7 @@ class VlcPlayer(MediaPlayer):
self.hasOwnWidget = True self.hasOwnWidget = True
def check_available(self): def check_available(self):
return vlc_available return VLC_AVAILABLE
def load(self, display): def load(self, display):
log.debug(u'load vid in Vlc Controller') log.debug(u'load vid in Vlc Controller')

View File

@ -483,7 +483,7 @@ class ServiceManager(QtGui.QWidget):
service_item = item[u'service_item'].get_service_repr() service_item = item[u'service_item'].get_service_repr()
# Get all the audio files, and ready them for embedding in the # Get all the audio files, and ready them for embedding in the
# service file. # service file.
if len(service_item[u'header'][u'background_audio']) > 0: if service_item[u'header'][u'background_audio']:
for i, filename in \ for i, filename in \
enumerate(service_item[u'header'][u'background_audio']): enumerate(service_item[u'header'][u'background_audio']):
new_file = os.path.join(u'audio', new_file = os.path.join(u'audio',
@ -822,7 +822,7 @@ class ServiceManager(QtGui.QWidget):
""" """
Called by the SlideController to select the next service item. Called by the SlideController to select the next service item.
""" """
if len(self.serviceManagerList.selectedItems()) == 0: if not self.serviceManagerList.selectedItems():
return return
selected = self.serviceManagerList.selectedItems()[0] selected = self.serviceManagerList.selectedItems()[0]
lookFor = 0 lookFor = 0
@ -840,7 +840,7 @@ class ServiceManager(QtGui.QWidget):
""" """
Called by the SlideController to select the previous service item. Called by the SlideController to select the previous service item.
""" """
if len(self.serviceManagerList.selectedItems()) == 0: if not self.serviceManagerList.selectedItems():
return return
selected = self.serviceManagerList.selectedItems()[0] selected = self.serviceManagerList.selectedItems()[0]
prevItem = None prevItem = None

View File

@ -151,7 +151,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
if action is None: if action is None:
continue continue
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
if len(shortcuts) == 0: if not shortcuts:
item.setText(1, u'') item.setText(1, u'')
item.setText(2, u'') item.setText(2, u'')
elif len(shortcuts) == 1: elif len(shortcuts) == 1:
@ -195,7 +195,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
return return
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
new_shortcuts = [] new_shortcuts = []
if len(shortcuts) != 0: if shortcuts:
new_shortcuts.append(shortcuts[0]) new_shortcuts.append(shortcuts[0])
new_shortcuts.append( new_shortcuts.append(
QtGui.QKeySequence(self.alternatePushButton.text())) QtGui.QKeySequence(self.alternatePushButton.text()))
@ -241,7 +241,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
self.primaryPushButton.setChecked(False) self.primaryPushButton.setChecked(False)
self.alternatePushButton.setChecked(False) self.alternatePushButton.setChecked(False)
else: else:
if len(action.defaultShortcuts) != 0: if action.defaultShortcuts:
primary_label_text = action.defaultShortcuts[0].toString() primary_label_text = action.defaultShortcuts[0].toString()
if len(action.defaultShortcuts) == 2: if len(action.defaultShortcuts) == 2:
alternate_label_text = action.defaultShortcuts[1].toString() alternate_label_text = action.defaultShortcuts[1].toString()
@ -313,7 +313,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
self.refreshShortcutList() self.refreshShortcutList()
primary_button_text = u'' primary_button_text = u''
alternate_button_text = u'' alternate_button_text = u''
if len(temp_shortcuts) != 0: if temp_shortcuts:
primary_button_text = temp_shortcuts[0].toString() primary_button_text = temp_shortcuts[0].toString()
if len(temp_shortcuts) == 2: if len(temp_shortcuts) == 2:
alternate_button_text = temp_shortcuts[1].toString() alternate_button_text = temp_shortcuts[1].toString()
@ -363,7 +363,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
return return
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
new_shortcuts = [] new_shortcuts = []
if len(action.defaultShortcuts) != 0: if action.defaultShortcuts:
new_shortcuts.append(action.defaultShortcuts[0]) new_shortcuts.append(action.defaultShortcuts[0])
# We have to check if the primary default shortcut is available. But # We have to check if the primary default shortcut is available. But
# we only have to check, if the action has a default primary # we only have to check, if the action has a default primary
@ -391,7 +391,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
return return
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
new_shortcuts = [] new_shortcuts = []
if len(shortcuts) != 0: if shortcuts:
new_shortcuts.append(shortcuts[0]) new_shortcuts.append(shortcuts[0])
if len(action.defaultShortcuts) == 2: if len(action.defaultShortcuts) == 2:
new_shortcuts.append(action.defaultShortcuts[1]) new_shortcuts.append(action.defaultShortcuts[1])

View File

@ -555,7 +555,7 @@ class SlideController(Controller):
Process the service item request queue. The key presses can arrive Process the service item request queue. The key presses can arrive
faster than the processing so implement a FIFO queue. faster than the processing so implement a FIFO queue.
""" """
if len(self.keypress_queue): if self.keypress_queue:
while len(self.keypress_queue) and not self.keypress_loop: while len(self.keypress_queue) and not self.keypress_loop:
self.keypress_loop = True self.keypress_loop = True
keypressCommand = self.keypress_queue.popleft() keypressCommand = self.keypress_queue.popleft()
@ -694,7 +694,7 @@ class SlideController(Controller):
if item.is_text(): if item.is_text():
if QtCore.QSettings().value( if QtCore.QSettings().value(
self.parent().songsSettingsSection + u'/display songbar', self.parent().songsSettingsSection + u'/display songbar',
QtCore.QVariant(True)).toBool() and len(self.slideList) > 0: QtCore.QVariant(True)).toBool() and self.slideList:
self.songMenu.show() self.songMenu.show()
if item.is_capable(ItemCapabilities.CanLoop) and \ if item.is_capable(ItemCapabilities.CanLoop) and \
len(item.get_frames()) > 1: len(item.get_frames()) > 1:

View File

@ -444,7 +444,7 @@ class ThemeManager(QtGui.QWidget):
self.firstTime() self.firstTime()
files = SettingsManager.get_files(self.settingsSection, u'.png') files = SettingsManager.get_files(self.settingsSection, u'.png')
# No themes have been found so create one # No themes have been found so create one
if len(files) == 0: if not files:
theme = ThemeXML() theme = ThemeXML()
theme.theme_name = UiStrings().Default theme.theme_name = UiStrings().Default
self._writeTheme(theme, None, None) self._writeTheme(theme, None, None)

View File

@ -27,14 +27,15 @@
""" """
The :mod:`openlp.core.utils` module provides the utility libraries for OpenLP. The :mod:`openlp.core.utils` module provides the utility libraries for OpenLP.
""" """
from datetime import datetime
from distutils.version import LooseVersion
import logging import logging
import os import os
import re import re
from subprocess import Popen, PIPE
import sys import sys
import time import time
import urllib2 import urllib2
from datetime import datetime
from subprocess import Popen, PIPE
from PyQt4 import QtGui, QtCore from PyQt4 import QtGui, QtCore
@ -55,7 +56,6 @@ UNO_CONNECTION_TYPE = u'pipe'
#UNO_CONNECTION_TYPE = u'socket' #UNO_CONNECTION_TYPE = u'socket'
CONTROL_CHARS = re.compile(r'[\x00-\x1F\x7F-\x9F]', re.UNICODE) CONTROL_CHARS = re.compile(r'[\x00-\x1F\x7F-\x9F]', re.UNICODE)
INVALID_FILE_CHARS = re.compile(r'[\\/:\*\?"<>\|\+\[\]%]', re.UNICODE) INVALID_FILE_CHARS = re.compile(r'[\\/:\*\?"<>\|\+\[\]%]', re.UNICODE)
VERSION_SPLITTER = re.compile(r'([0-9]+).([0-9]+).([0-9]+)(?:-bzr([0-9]+))?')
class VersionThread(QtCore.QThread): class VersionThread(QtCore.QThread):
""" """
@ -72,48 +72,8 @@ class VersionThread(QtCore.QThread):
time.sleep(1) time.sleep(1)
app_version = get_application_version() app_version = get_application_version()
version = check_latest_version(app_version) version = check_latest_version(app_version)
remote_version = {} if LooseVersion(str(version)) > LooseVersion(str(app_version[u'full'])):
local_version = {}
match = VERSION_SPLITTER.match(version)
if match:
remote_version[u'major'] = int(match.group(1))
remote_version[u'minor'] = int(match.group(2))
remote_version[u'release'] = int(match.group(3))
if len(match.groups()) > 3 and match.group(4):
remote_version[u'revision'] = int(match.group(4))
else:
return
match = VERSION_SPLITTER.match(app_version[u'full'])
if match:
local_version[u'major'] = int(match.group(1))
local_version[u'minor'] = int(match.group(2))
local_version[u'release'] = int(match.group(3))
if len(match.groups()) > 3 and match.group(4):
local_version[u'revision'] = int(match.group(4))
else:
return
if remote_version[u'major'] > local_version[u'major'] or \
remote_version[u'minor'] > local_version[u'minor'] or \
remote_version[u'release'] > local_version[u'release']:
Receiver.send_message(u'openlp_version_check', u'%s' % version) Receiver.send_message(u'openlp_version_check', u'%s' % version)
elif remote_version.get(u'revision') and \
local_version.get(u'revision') and \
remote_version[u'revision'] > local_version[u'revision']:
Receiver.send_message(u'openlp_version_check', u'%s' % version)
class DelayStartThread(QtCore.QThread):
"""
A special Qt thread class to build things after OpenLP has started
"""
def __init__(self, parent):
QtCore.QThread.__init__(self, parent)
def run(self):
"""
Run the thread.
"""
Receiver.send_message(u'openlp_phonon_creation')
class AppLocation(object): class AppLocation(object):
@ -181,6 +141,7 @@ class AppLocation(object):
check_directory_exists(path) check_directory_exists(path)
return path return path
def _get_os_dir_path(dir_type): def _get_os_dir_path(dir_type):
""" """
Return a path based on which OS and environment we are running in. Return a path based on which OS and environment we are running in.
@ -220,6 +181,7 @@ def _get_os_dir_path(dir_type):
u'.openlp', u'data') u'.openlp', u'data')
return os.path.join(unicode(os.getenv(u'HOME'), encoding), u'.openlp') return os.path.join(unicode(os.getenv(u'HOME'), encoding), u'.openlp')
def _get_frozen_path(frozen_option, non_frozen_option): def _get_frozen_path(frozen_option, non_frozen_option):
""" """
Return a path based on the system status. Return a path based on the system status.
@ -228,6 +190,7 @@ def _get_frozen_path(frozen_option, non_frozen_option):
return frozen_option return frozen_option
return non_frozen_option return non_frozen_option
def get_application_version(): def get_application_version():
""" """
Returns the application version of the running instance of OpenLP:: Returns the application version of the running instance of OpenLP::
@ -267,7 +230,7 @@ def get_application_version():
if code != 0: if code != 0:
raise Exception(u'Error running bzr tags') raise Exception(u'Error running bzr tags')
lines = output.splitlines() lines = output.splitlines()
if len(lines) == 0: if not lines:
tag = u'0.0.0' tag = u'0.0.0'
revision = u'0' revision = u'0'
else: else:
@ -307,6 +270,7 @@ def get_application_version():
log.info(u'Openlp version %s' % APPLICATION_VERSION[u'version']) log.info(u'Openlp version %s' % APPLICATION_VERSION[u'version'])
return APPLICATION_VERSION return APPLICATION_VERSION
def check_latest_version(current_version): def check_latest_version(current_version):
""" """
Check the latest version of OpenLP against the version file on the OpenLP Check the latest version of OpenLP against the version file on the OpenLP
@ -340,6 +304,7 @@ def check_latest_version(current_version):
version_string = remote_version version_string = remote_version
return version_string return version_string
def add_actions(target, actions): def add_actions(target, actions):
""" """
Adds multiple actions to a menu or toolbar in one command. Adds multiple actions to a menu or toolbar in one command.
@ -357,6 +322,7 @@ def add_actions(target, actions):
else: else:
target.addAction(action) target.addAction(action)
def get_filesystem_encoding(): def get_filesystem_encoding():
""" """
Returns the name of the encoding used to convert Unicode filenames into Returns the name of the encoding used to convert Unicode filenames into
@ -367,6 +333,7 @@ def get_filesystem_encoding():
encoding = sys.getdefaultencoding() encoding = sys.getdefaultencoding()
return encoding return encoding
def get_images_filter(): def get_images_filter():
""" """
Returns a filter string for a file dialog containing all the supported Returns a filter string for a file dialog containing all the supported
@ -383,6 +350,7 @@ def get_images_filter():
visible_formats, actual_formats) visible_formats, actual_formats)
return IMAGES_FILTER return IMAGES_FILTER
def split_filename(path): def split_filename(path):
""" """
Return a list of the parts in a given path. Return a list of the parts in a given path.
@ -393,6 +361,7 @@ def split_filename(path):
else: else:
return os.path.split(path) return os.path.split(path)
def clean_filename(filename): def clean_filename(filename):
""" """
Removes invalid characters from the given ``filename``. Removes invalid characters from the given ``filename``.
@ -404,6 +373,7 @@ def clean_filename(filename):
filename = unicode(filename, u'utf-8') filename = unicode(filename, u'utf-8')
return INVALID_FILE_CHARS.sub(u'_', CONTROL_CHARS.sub(u'', filename)) return INVALID_FILE_CHARS.sub(u'_', CONTROL_CHARS.sub(u'', filename))
def delete_file(file_path_name): def delete_file(file_path_name):
""" """
Deletes a file from the system. Deletes a file from the system.
@ -421,6 +391,7 @@ def delete_file(file_path_name):
log.exception("Unable to delete file %s" % file_path_name) log.exception("Unable to delete file %s" % file_path_name)
return False return False
def get_web_page(url, header=None, update_openlp=False): def get_web_page(url, header=None, update_openlp=False):
""" """
Attempts to download the webpage at url and returns that page or None. Attempts to download the webpage at url and returns that page or None.
@ -457,6 +428,7 @@ def get_web_page(url, header=None, update_openlp=False):
log.debug(page) log.debug(page)
return page return page
def get_uno_command(): def get_uno_command():
""" """
Returns the UNO command to launch an openoffice.org instance. Returns the UNO command to launch an openoffice.org instance.
@ -469,6 +441,7 @@ def get_uno_command():
CONNECTION = u'"-accept=socket,host=localhost,port=2002;urp;"' CONNECTION = u'"-accept=socket,host=localhost,port=2002;urp;"'
return u'%s %s %s' % (COMMAND, OPTIONS, CONNECTION) return u'%s %s %s' % (COMMAND, OPTIONS, CONNECTION)
def get_uno_instance(resolver): def get_uno_instance(resolver):
""" """
Returns a running openoffice.org instance. Returns a running openoffice.org instance.

View File

@ -90,7 +90,7 @@ class CategoryActionList(object):
def append(self, name): def append(self, name):
weight = 0 weight = 0
if len(self.actions) > 0: if self.actions:
weight = self.actions[-1][0] + 1 weight = self.actions[-1][0] + 1
self.add(name, weight) self.add(name, weight)
@ -156,7 +156,7 @@ class CategoryList(object):
def append(self, name, actions=None): def append(self, name, actions=None):
weight = 0 weight = 0
if len(self.categories) > 0: if self.categories:
weight = self.categories[-1].weight + 1 weight = self.categories[-1].weight + 1
if actions: if actions:
self.add(name, weight, actions) self.add(name, weight, actions)

View File

@ -101,7 +101,7 @@ class AlertForm(QtGui.QDialog, Ui_AlertDialog):
self.alertTextEdit.setText(u'') self.alertTextEdit.setText(u'')
def onNewClick(self): def onNewClick(self):
if len(self.alertTextEdit.text()) == 0: if not self.alertTextEdit.text():
QtGui.QMessageBox.information(self, QtGui.QMessageBox.information(self,
translate('AlertsPlugin.AlertForm', 'New Alert'), translate('AlertsPlugin.AlertForm', 'New Alert'),
translate('AlertsPlugin.AlertForm', 'You haven\'t specified ' translate('AlertsPlugin.AlertForm', 'You haven\'t specified '

View File

@ -62,7 +62,7 @@ class BiblePlugin(Plugin):
# unicode(UiStrings().Export)) # unicode(UiStrings().Export))
# Set to invisible until we can export bibles # Set to invisible until we can export bibles
self.exportBibleItem.setVisible(False) self.exportBibleItem.setVisible(False)
if len(self.manager.old_bible_databases): if self.manager.old_bible_databases:
self.toolsUpgradeItem.setVisible(True) self.toolsUpgradeItem.setVisible(True)
def finalise(self): def finalise(self):
@ -83,7 +83,7 @@ class BiblePlugin(Plugin):
""" """
Perform tasks on application startup Perform tasks on application startup
""" """
if len(self.manager.old_bible_databases): if self.manager.old_bible_databases:
if QtGui.QMessageBox.information(self.formParent, if QtGui.QMessageBox.information(self.formParent,
translate('OpenLP', 'Information'), translate('OpenLP', translate('OpenLP', 'Information'), translate('OpenLP',
'Bible format has changed.\nYou have to upgrade your ' 'Bible format has changed.\nYou have to upgrade your '

View File

@ -426,8 +426,7 @@ class BibleUpgradeForm(OpenLPWizard):
if meta[u'key'] == u'download_source': if meta[u'key'] == u'download_source':
web_bible = True web_bible = True
self.includeWebBible = True self.includeWebBible = True
if meta.has_key(u'proxy_server'): proxy_server = meta.get(u'proxy_server')
proxy_server = meta[u'proxy_server']
if web_bible: if web_bible:
if meta_data[u'download_source'].lower() == u'crosswalk': if meta_data[u'download_source'].lower() == u'crosswalk':
handler = CWExtract(proxy_server) handler = CWExtract(proxy_server)
@ -572,7 +571,7 @@ class BibleUpgradeForm(OpenLPWizard):
int(verse[u'verse']), unicode(verse[u'text'])) int(verse[u'verse']), unicode(verse[u'text']))
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
self.newbibles[number].session.commit() self.newbibles[number].session.commit()
if self.success.has_key(number) and not self.success[number]: if not self.success.get(number, True):
self.incrementProgressBar(unicode(translate( self.incrementProgressBar(unicode(translate(
'BiblesPlugin.UpgradeWizardForm', 'BiblesPlugin.UpgradeWizardForm',
'Upgrading Bible %s of %s: "%s"\nFailed')) % 'Upgrading Bible %s of %s: "%s"\nFailed')) %
@ -586,7 +585,7 @@ class BibleUpgradeForm(OpenLPWizard):
'Upgrading Bible %s of %s: "%s"\n' 'Upgrading Bible %s of %s: "%s"\n'
'Complete')) % 'Complete')) %
(number + 1, max_bibles, name)) (number + 1, max_bibles, name))
if self.newbibles.has_key(number): if number in self.newbibles:
self.newbibles[number].session.close() self.newbibles[number].session.close()
# Close the last bible's connection if possible. # Close the last bible's connection if possible.
if old_bible is not None: if old_bible is not None:
@ -599,7 +598,7 @@ class BibleUpgradeForm(OpenLPWizard):
successful_import = 0 successful_import = 0
failed_import = 0 failed_import = 0
for number, filename in enumerate(self.files): for number, filename in enumerate(self.files):
if self.success.has_key(number) and self.success[number]: if self.success.get(number):
successful_import += 1 successful_import += 1
elif self.checkBox[number].checkState() == QtCore.Qt.Checked: elif self.checkBox[number].checkState() == QtCore.Qt.Checked:
failed_import += 1 failed_import += 1

View File

@ -236,7 +236,7 @@ def get_reference_separator(separator_type):
``separator_type`` ``separator_type``
The role and format of the separator. The role and format of the separator.
""" """
if len(REFERENCE_SEPARATORS) == 0: if not REFERENCE_SEPARATORS:
update_reference_separators() update_reference_separators()
return REFERENCE_SEPARATORS[separator_type] return REFERENCE_SEPARATORS[separator_type]
@ -247,7 +247,7 @@ def get_reference_match(match_type):
``match_type`` ``match_type``
The type of match is ``range_separator``, ``range`` or ``full``. The type of match is ``range_separator``, ``range`` or ``full``.
""" """
if len(REFERENCE_MATCHES) == 0: if not REFERENCE_MATCHES:
update_reference_separators() update_reference_separators()
return REFERENCE_MATCHES[match_type] return REFERENCE_MATCHES[match_type]

View File

@ -106,7 +106,7 @@ class BGExtract(object):
verse_list = {} verse_list = {}
# Cater for inconsistent mark up in the first verse of a chapter. # Cater for inconsistent mark up in the first verse of a chapter.
first_verse = verses.find(u'versenum') first_verse = verses.find(u'versenum')
if first_verse and len(first_verse.contents): if first_verse and first_verse.contents:
verse_list[1] = unicode(first_verse.contents[0]) verse_list[1] = unicode(first_verse.contents[0])
for verse in verses(u'sup', u'versenum'): for verse in verses(u'sup', u'versenum'):
raw_verse_num = verse.next raw_verse_num = verse.next

View File

@ -392,7 +392,7 @@ class BibleMediaItem(MediaManagerItem):
if bible in bibles: if bible in bibles:
find_and_set_in_combo_box(self.advancedVersionComboBox, bible) find_and_set_in_combo_box(self.advancedVersionComboBox, bible)
self.initialiseAdvancedBible(unicode(bible)) self.initialiseAdvancedBible(unicode(bible))
elif len(bibles): elif bibles:
self.initialiseAdvancedBible(bibles[0]) self.initialiseAdvancedBible(bibles[0])
bible = QtCore.QSettings().value( bible = QtCore.QSettings().value(
self.settingsSection + u'/quick bible', QtCore.QVariant( self.settingsSection + u'/quick bible', QtCore.QVariant(
@ -408,7 +408,7 @@ class BibleMediaItem(MediaManagerItem):
self.plugin.appStartup() self.plugin.appStartup()
self.updateAutoCompleter() self.updateAutoCompleter()
def initialiseAdvancedBible(self, bible): def initialiseAdvancedBible(self, bible, last_book_id=None):
""" """
This initialises the given bible, which means that its book names and This initialises the given bible, which means that its book names and
their chapter numbers is added to the combo boxes on the their chapter numbers is added to the combo boxes on the
@ -417,8 +417,12 @@ class BibleMediaItem(MediaManagerItem):
``bible`` ``bible``
The bible to initialise (unicode). The bible to initialise (unicode).
``last_book_id``
The "book reference id" of the book which is choosen at the moment.
(int)
""" """
log.debug(u'initialiseAdvancedBible %s', bible) log.debug(u'initialiseAdvancedBible %s, %s', bible, last_book_id)
book_data = self.plugin.manager.get_books(bible) book_data = self.plugin.manager.get_books(bible)
secondbible = unicode(self.advancedSecondComboBox.currentText()) secondbible = unicode(self.advancedSecondComboBox.currentText())
if secondbible != u'': if secondbible != u'':
@ -432,6 +436,7 @@ class BibleMediaItem(MediaManagerItem):
book_data = book_data_temp book_data = book_data_temp
self.advancedBookComboBox.clear() self.advancedBookComboBox.clear()
first = True first = True
initialise_chapter_verse = False
language_selection = self.plugin.manager.get_language_selection(bible) language_selection = self.plugin.manager.get_language_selection(bible)
book_names = BibleStrings().BookNames book_names = BibleStrings().BookNames
for book in book_data: for book in book_data:
@ -451,8 +456,19 @@ class BibleMediaItem(MediaManagerItem):
row, QtCore.QVariant(book[u'book_reference_id'])) row, QtCore.QVariant(book[u'book_reference_id']))
if first: if first:
first = False first = False
self.initialiseChapterVerse(bible, book[u'name'], first_book = book
book[u'book_reference_id']) initialise_chapter_verse = True
if last_book_id and last_book_id == int(book[u'book_reference_id']):
index = self.advancedBookComboBox.findData(
QtCore.QVariant(book[u'book_reference_id']))
if index == -1:
# Not Found.
index = 0
self.advancedBookComboBox.setCurrentIndex(index)
initialise_chapter_verse = False
if initialise_chapter_verse:
self.initialiseChapterVerse(bible, first_book[u'name'],
first_book[u'book_reference_id'])
def initialiseChapterVerse(self, bible, book, book_ref_id): def initialiseChapterVerse(self, bible, book, book_ref_id):
log.debug(u'initialiseChapterVerse %s, %s, %s', bible, book, log.debug(u'initialiseChapterVerse %s, %s, %s', bible, book,
@ -597,11 +613,15 @@ class BibleMediaItem(MediaManagerItem):
QtCore.QSettings().setValue(self.settingsSection + u'/advanced bible', QtCore.QSettings().setValue(self.settingsSection + u'/advanced bible',
QtCore.QVariant(self.advancedVersionComboBox.currentText())) QtCore.QVariant(self.advancedVersionComboBox.currentText()))
self.initialiseAdvancedBible( self.initialiseAdvancedBible(
unicode(self.advancedVersionComboBox.currentText())) unicode(self.advancedVersionComboBox.currentText()),
self.advancedBookComboBox.itemData(
int(self.advancedBookComboBox.currentIndex())))
def onAdvancedSecondComboBox(self): def onAdvancedSecondComboBox(self):
self.initialiseAdvancedBible( self.initialiseAdvancedBible(
unicode(self.advancedVersionComboBox.currentText())) unicode(self.advancedVersionComboBox.currentText()),
self.advancedBookComboBox.itemData(
int(self.advancedBookComboBox.currentIndex())))
def onAdvancedBookComboBox(self): def onAdvancedBookComboBox(self):
item = int(self.advancedBookComboBox.currentIndex()) item = int(self.advancedBookComboBox.currentIndex())
@ -878,7 +898,7 @@ class BibleMediaItem(MediaManagerItem):
items = item items = item
else: else:
items = self.listView.selectedItems() items = self.listView.selectedItems()
if len(items) == 0: if not items:
return False return False
bible_text = u'' bible_text = u''
old_item = None old_item = None
@ -949,7 +969,7 @@ class BibleMediaItem(MediaManagerItem):
# Service Item: Title # Service Item: Title
service_item.title = create_separated_list(raw_title) service_item.title = create_separated_list(raw_title)
# Service Item: Theme # Service Item: Theme
if len(self.settings.bible_theme) == 0: if not self.settings.bible_theme:
service_item.theme = None service_item.theme = None
else: else:
service_item.theme = self.settings.bible_theme service_item.theme = self.settings.bible_theme

View File

@ -254,7 +254,7 @@ class EditCustomForm(QtGui.QDialog, Ui_CustomEditDialog):
Checks whether a custom is valid or not. Checks whether a custom is valid or not.
""" """
# We must have a title. # We must have a title.
if len(self.titleEdit.displayText()) == 0: if not self.titleEdit.displayText():
self.titleEdit.setFocus() self.titleEdit.setFocus()
critical_error_message_box( critical_error_message_box(
message=translate('CustomPlugin.EditCustomForm', message=translate('CustomPlugin.EditCustomForm',

View File

@ -258,7 +258,7 @@ class CustomMediaItem(MediaManagerItem):
search_length = 2 search_length = 2
if len(text) > search_length: if len(text) > search_length:
self.onSearchTextButtonClicked() self.onSearchTextButtonClicked()
elif len(text) == 0: elif not text:
self.onClearTextButtonClick() self.onClearTextButtonClick()
def onClearTextButtonClick(self): def onClearTextButtonClick(self):

View File

@ -191,13 +191,13 @@ class EditVerseForm(QtGui.QDialog, Ui_EditVerseDialog):
else: else:
log.debug(unicode(self.getVerse()[0]).split(u'\n')) log.debug(unicode(self.getVerse()[0]).split(u'\n'))
value = unicode(self.getVerse()[0]).split(u'\n')[1] value = unicode(self.getVerse()[0]).split(u'\n')[1]
if len(value) == 0: if not value:
lines = unicode(self.getVerse()[0]).split(u'\n') lines = unicode(self.getVerse()[0]).split(u'\n')
index = 2 index = 2
while index < len(lines) and len(value) == 0: while index < len(lines) and not value:
value = lines[index] value = lines[index]
index += 1 index += 1
if len(value) == 0: if not value:
critical_error_message_box( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'You need to type some text in to the verse.')) 'You need to type some text in to the verse.'))

View File

@ -108,7 +108,7 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
item_id = self._getCurrentItemId(list_widget) item_id = self._getCurrentItemId(list_widget)
if item_id != -1: if item_id != -1:
item = self.manager.get_object(item_class, item_id) item = self.manager.get_object(item_class, item_id)
if item and len(item.songs) == 0: if item and not item.songs:
if critical_error_message_box(dlg_title, del_text, self, if critical_error_message_box(dlg_title, del_text, self,
True) == QtGui.QMessageBox.Yes: True) == QtGui.QMessageBox.Yes:
self.manager.delete_object(item_class, item.id) self.manager.delete_object(item_class, item.id)
@ -191,7 +191,7 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
``edit`` ``edit``
If we edit an item, this should be *True*. If we edit an item, this should be *True*.
""" """
if len(objects) > 0: if objects:
# If we edit an existing object, we need to make sure that we do # If we edit an existing object, we need to make sure that we do
# not return False when nothing has changed. # not return False when nothing has changed.
if edit: if edit:

View File

@ -316,7 +316,7 @@ def clean_song(manager, song):
verse_type, verse_type,
verse[0][u'label'], verse[0][u'label'],
verse[1], verse[1],
verse[0][u'lang'] if verse[0].has_key(u'lang') else None verse[0].get(u'lang')
) )
compare_order.append((u'%s%s' % (verse_type, verse[0][u'label']) compare_order.append((u'%s%s' % (verse_type, verse[0][u'label'])
).upper()) ).upper())

View File

@ -211,7 +211,7 @@ class CCLIFileImport(SongImport):
elif verse_lines[0].startswith(u'('): elif verse_lines[0].startswith(u'('):
verse_type = VerseType.Tags[VerseType.Other] verse_type = VerseType.Tags[VerseType.Other]
verse_text = verse_lines[1] verse_text = verse_lines[1]
if len(verse_text) > 0: if verse_text:
self.addVerse(verse_text, verse_type) self.addVerse(verse_text, verse_type)
check_first_verse_line = False check_first_verse_line = False
# Handle multiple authors # Handle multiple authors

View File

@ -162,15 +162,12 @@ class EasySlidesImport(SongImport):
separatorlines = 0 separatorlines = 0
for line in lines: for line in lines:
line = line.strip() line = line.strip()
if len(line) == 0: if not line:
continue continue
elif line[1:7] == u'region': elif line[1:7] == u'region':
# this is region separator, probably [region 2] # this is region separator, probably [region 2]
region = self._extractRegion(line) region = self._extractRegion(line)
if regionlines.has_key(region): regionlines[region] = 1 + regionlines.get(region, 0)
regionlines[region] = regionlines[region] + 1
else:
regionlines[region] = 1
elif line[0] == u'[': elif line[0] == u'[':
separatorlines = separatorlines + 1 separatorlines = separatorlines + 1
# if the song has separators # if the song has separators
@ -206,7 +203,7 @@ class EasySlidesImport(SongImport):
for line in lines: for line in lines:
line = line.strip() line = line.strip()
if len(line) == 0: if not line:
if separators: if separators:
# separators are used, so empty line means slide break # separators are used, so empty line means slide break
# inside verse # inside verse
@ -215,15 +212,11 @@ class EasySlidesImport(SongImport):
else: else:
# separators are not used, so empty line starts a new verse # separators are not used, so empty line starts a new verse
vt = u'V' vt = u'V'
if verses[reg].has_key(vt): vn = len(verses[reg].get(vt, {})) + 1
vn = len(verses[reg][vt].keys())+1
else:
vn = u'1'
inst = 1 inst = 1
elif line[0:7] == u'[region': elif line[0:7] == u'[region':
reg = self._extractRegion(line) reg = self._extractRegion(line)
if not verses.has_key(reg): verses.setdefault(reg, {})
verses[reg] = {}
if not regionsInVerses: if not regionsInVerses:
vt = u'V' vt = u'V'
vn = u'1' vn = u'1'
@ -238,28 +231,19 @@ class EasySlidesImport(SongImport):
if match: if match:
marker = match.group(1).strip() marker = match.group(1).strip()
vn = match.group(2) vn = match.group(2)
if len(marker) == 0: vt = MarkTypes.get(marker, u'O') if marker else u'V'
vt = u'V'
elif MarkTypes.has_key(marker):
vt = MarkTypes[marker]
else:
vt = u'O'
if regionsInVerses: if regionsInVerses:
region = defaultregion region = defaultregion
inst = 1 inst = 1
if self._listHas(verses, [reg, vt, vn, inst]): if self._listHas(verses, [reg, vt, vn, inst]):
inst = len(verses[reg][vt][vn])+1 inst = len(verses[reg][vt][vn]) + 1
else: else:
if not [reg, vt, vn, inst] in our_verse_order: if not [reg, vt, vn, inst] in our_verse_order:
our_verse_order.append([reg, vt, vn, inst]) our_verse_order.append([reg, vt, vn, inst])
if not verses[reg].has_key(vt): verses[reg].setdefault(vt, {})
verses[reg][vt] = {} verses[reg][vt].setdefault(vn, {})
if not verses[reg][vt].has_key(vn): verses[reg][vt][vn].setdefault(inst, [])
verses[reg][vt][vn] = {} verses[reg][vt][vn][inst].append(self.tidyText(line))
if not verses[reg][vt][vn].has_key(inst):
verses[reg][vt][vn][inst] = []
words = self.tidyText(line)
verses[reg][vt][vn][inst].append(words)
# done parsing # done parsing
versetags = [] versetags = []
@ -286,11 +270,11 @@ class EasySlidesImport(SongImport):
try: try:
order = unicode(song.Sequence).strip().split(u',') order = unicode(song.Sequence).strip().split(u',')
for tag in order: for tag in order:
if len(tag) == 0: if not tag:
continue continue
elif tag[0].isdigit(): elif tag[0].isdigit():
tag = u'V' + tag tag = u'V' + tag
elif SeqTypes.has_key(tag.lower()): elif tag.lower() in SeqTypes:
tag = SeqTypes[tag.lower()] tag = SeqTypes[tag.lower()]
else: else:
continue continue
@ -307,9 +291,7 @@ class EasySlidesImport(SongImport):
def _listHas(self, lst, subitems): def _listHas(self, lst, subitems):
for subitem in subitems: for subitem in subitems:
if isinstance(lst, dict) and lst.has_key(subitem): if subitem in lst:
lst = lst[subitem]
elif isinstance(lst, list) and subitem in lst:
lst = lst[subitem] lst = lst[subitem]
else: else:
return False return False

View File

@ -62,15 +62,15 @@ def strip_rtf(blob, encoding):
if control: if control:
# for delimiters, set control to False # for delimiters, set control to False
if c == '{': if c == '{':
if len(control_word) > 0: if control_word:
depth += 1 depth += 1
control = False control = False
elif c == '}': elif c == '}':
if len(control_word) > 0: if control_word:
depth -= 1 depth -= 1
control = False control = False
elif c == '\\': elif c == '\\':
new_control = (len(control_word) > 0) new_control = bool(control_word)
control = False control = False
elif c.isspace(): elif c.isspace():
control = False control = False
@ -79,7 +79,7 @@ def strip_rtf(blob, encoding):
if len(control_word) == 3 and control_word[0] == '\'': if len(control_word) == 3 and control_word[0] == '\'':
control = False control = False
if not control: if not control:
if len(control_word) == 0: if not control_word:
if c == '{' or c == '}' or c == '\\': if c == '{' or c == '}' or c == '\\':
clear_text.append(c) clear_text.append(c)
else: else:
@ -360,7 +360,7 @@ class EasyWorshipSongImport(SongImport):
field_desc = self.fieldDescs[field_desc_index] field_desc = self.fieldDescs[field_desc_index]
# Return None in case of 'blank' entries # Return None in case of 'blank' entries
if isinstance(field, str): if isinstance(field, str):
if len(field.rstrip('\0')) == 0: if not field.rstrip('\0'):
return None return None
elif field == 0: elif field == 0:
return None return None

View File

@ -295,9 +295,8 @@ class SongMediaItem(MediaManagerItem):
log.debug(u'display results Book') log.debug(u'display results Book')
self.listView.clear() self.listView.clear()
for book in searchresults: for book in searchresults:
songs = sorted(book.songs, key=lambda song: int( songs = sorted(book.songs, key=lambda song:
re.sub(r'[^0-9]', u' ', song.song_number).partition(' ')[0]) int(re.match(r'[0-9]+', u'0' + song.song_number).group()))
if len(re.sub(r'[^\w]', ' ', song.song_number)) else 0)
for song in songs: for song in songs:
# Do not display temporary songs # Do not display temporary songs
if song.temporary: if song.temporary:
@ -331,7 +330,7 @@ class SongMediaItem(MediaManagerItem):
search_length = 3 search_length = 3
if len(text) > search_length: if len(text) > search_length:
self.onSearchTextButtonClicked() self.onSearchTextButtonClicked()
elif len(text) == 0: elif not text:
self.onClearTextButtonClick() self.onClearTextButtonClick()
def onImportClick(self): def onImportClick(self):
@ -491,7 +490,7 @@ class SongMediaItem(MediaManagerItem):
else: else:
# Loop through the verse list and expand the song accordingly. # Loop through the verse list and expand the song accordingly.
for order in song.verse_order.lower().split(): for order in song.verse_order.lower().split():
if len(order) == 0: if not order:
break break
for verse in verseList: for verse in verseList:
if verse[0][u'type'][0].lower() == order[0] and \ if verse[0][u'type'][0].lower() == order[0] and \
@ -530,7 +529,7 @@ class SongMediaItem(MediaManagerItem):
u'authors': u', '.join(author_list)} u'authors': u', '.join(author_list)}
service_item.xml_version = self.openLyrics.song_to_xml(song) service_item.xml_version = self.openLyrics.song_to_xml(song)
# Add the audio file to the service item. # Add the audio file to the service item.
if len(song.media_files) > 0: if song.media_files:
service_item.add_capability(ItemCapabilities.HasBackgroundAudio) service_item.add_capability(ItemCapabilities.HasBackgroundAudio)
service_item.background_audio = \ service_item.background_audio = \
[m.file_name for m in song.media_files] [m.file_name for m in song.media_files]
@ -575,12 +574,12 @@ class SongMediaItem(MediaManagerItem):
editId = song.id editId = song.id
break break
# If there's any backing tracks, copy them over. # If there's any backing tracks, copy them over.
if len(item.background_audio) > 0: if item.background_audio:
self._updateBackgroundAudio(song, item) self._updateBackgroundAudio(song, item)
if add_song and self.addSongFromService: if add_song and self.addSongFromService:
song = self.openLyrics.xml_to_song(item.xml_version) song = self.openLyrics.xml_to_song(item.xml_version)
# If there's any backing tracks, copy them over. # If there's any backing tracks, copy them over.
if len(item.background_audio) > 0: if item.background_audio:
self._updateBackgroundAudio(song, item) self._updateBackgroundAudio(song, item)
editId = song.id editId = song.id
self.onSearchTextButtonClicked() self.onSearchTextButtonClicked()
@ -588,7 +587,7 @@ class SongMediaItem(MediaManagerItem):
# Make sure we temporary import formatting tags. # Make sure we temporary import formatting tags.
song = self.openLyrics.xml_to_song(item.xml_version, True) song = self.openLyrics.xml_to_song(item.xml_version, True)
# If there's any backing tracks, copy them over. # If there's any backing tracks, copy them over.
if len(item.background_audio) > 0: if item.background_audio:
self._updateBackgroundAudio(song, item) self._updateBackgroundAudio(song, item)
editId = song.id editId = song.id
temporary = True temporary = True

View File

@ -122,8 +122,7 @@ class OpenLP1SongImport(SongImport):
cursor.execute( cursor.execute(
u'SELECT settingsid FROM songs WHERE songid = %s' % song_id) u'SELECT settingsid FROM songs WHERE songid = %s' % song_id)
theme_id = cursor.fetchone()[0] theme_id = cursor.fetchone()[0]
if themes.has_key(theme_id): self.themeName = themes.get(theme_id, u'')
self.themeName = themes[theme_id]
verses = lyrics.split(u'\n\n') verses = lyrics.split(u'\n\n')
for verse in verses: for verse in verses:
if verse.strip(): if verse.strip():
@ -191,7 +190,7 @@ class OpenLP1SongImport(SongImport):
# Detect charset by songs. # Detect charset by songs.
cursor.execute(u'SELECT name FROM sqlite_master ' cursor.execute(u'SELECT name FROM sqlite_master '
u'WHERE type = \'table\' AND name = \'tracks\'') u'WHERE type = \'table\' AND name = \'tracks\'')
if len(cursor.fetchall()) > 0: if cursor.fetchall():
cursor.execute(u'SELECT fulltrackname FROM tracks') cursor.execute(u'SELECT fulltrackname FROM tracks')
tracks = cursor.fetchall() tracks = cursor.fetchall()
for track in tracks: for track in tracks:

View File

@ -174,7 +174,7 @@ class OpenSongImport(SongImport):
if semicolon >= 0: if semicolon >= 0:
this_line = this_line[:semicolon] this_line = this_line[:semicolon]
this_line = this_line.strip() this_line = this_line.strip()
if not len(this_line): if not this_line:
continue continue
# skip guitar chords and page and column breaks # skip guitar chords and page and column breaks
if this_line.startswith(u'.') or this_line.startswith(u'---') \ if this_line.startswith(u'.') or this_line.startswith(u'---') \
@ -197,15 +197,12 @@ class OpenSongImport(SongImport):
# the verse tag # the verse tag
verse_tag = content verse_tag = content
verse_num = u'1' verse_num = u'1'
if len(verse_tag) == 0: verse_index = VerseType.from_loose_input(verse_tag) \
verse_index = 0 if verse_tag else 0
else:
verse_index = VerseType.from_loose_input(verse_tag)
verse_tag = VerseType.Tags[verse_index] verse_tag = VerseType.Tags[verse_index]
inst = 1 inst = 1
if [verse_tag, verse_num, inst] in our_verse_order \ if [verse_tag, verse_num, inst] in our_verse_order \
and verses.has_key(verse_tag) \ and verse_num in verses.get(verse_tag, {}):
and verses[verse_tag].has_key(verse_num):
inst = len(verses[verse_tag][verse_num]) + 1 inst = len(verses[verse_tag][verse_num]) + 1
continue continue
# number at start of line.. it's verse number # number at start of line.. it's verse number
@ -213,11 +210,9 @@ class OpenSongImport(SongImport):
verse_num = this_line[0] verse_num = this_line[0]
this_line = this_line[1:].strip() this_line = this_line[1:].strip()
our_verse_order.append([verse_tag, verse_num, inst]) our_verse_order.append([verse_tag, verse_num, inst])
if not verses.has_key(verse_tag): verses.setdefault(verse_tag, {})
verses[verse_tag] = {} verses[verse_tag].setdefault(verse_num, {})
if not verses[verse_tag].has_key(verse_num): if inst not in verses[verse_tag][verse_num]:
verses[verse_tag][verse_num] = {}
if not verses[verse_tag][verse_num].has_key(inst):
verses[verse_tag][verse_num][inst] = [] verses[verse_tag][verse_num][inst] = []
our_verse_order.append([verse_tag, verse_num, inst]) our_verse_order.append([verse_tag, verse_num, inst])
# Tidy text and remove the ____s from extended words # Tidy text and remove the ____s from extended words
@ -252,15 +247,14 @@ class OpenSongImport(SongImport):
if match is not None: if match is not None:
verse_tag = match.group(1) verse_tag = match.group(1)
verse_num = match.group(2) verse_num = match.group(2)
if not len(verse_tag): if not verse_tag:
verse_tag = VerseType.Tags[VerseType.Verse] verse_tag = VerseType.Tags[VerseType.Verse]
else: else:
# Assume it's no.1 if there are no digits # Assume it's no.1 if there are no digits
verse_tag = verse_def verse_tag = verse_def
verse_num = u'1' verse_num = u'1'
verse_def = u'%s%s' % (verse_tag, verse_num) verse_def = u'%s%s' % (verse_tag, verse_num)
if verses.has_key(verse_tag) and \ if verse_num in verses.get(verse_tag, {}):
verses[verse_tag].has_key(verse_num):
self.verseOrderList.append(verse_def) self.verseOrderList.append(verse_def)
else: else:
log.info(u'Got order %s but not in verse tags, dropping' log.info(u'Got order %s but not in verse tags, dropping'

View File

@ -61,9 +61,9 @@ class SongImport(QtCore.QObject):
""" """
self.manager = manager self.manager = manager
QtCore.QObject.__init__(self) QtCore.QObject.__init__(self)
if kwargs.has_key(u'filename'): if u'filename' in kwargs:
self.importSource = kwargs[u'filename'] self.importSource = kwargs[u'filename']
elif kwargs.has_key(u'filenames'): elif u'filenames' in kwargs:
self.importSource = kwargs[u'filenames'] self.importSource = kwargs[u'filenames']
else: else:
raise KeyError(u'Keyword arguments "filename[s]" not supplied.') raise KeyError(u'Keyword arguments "filename[s]" not supplied.')
@ -273,7 +273,7 @@ class SongImport(QtCore.QObject):
Author not checked here, if no author then "Author unknown" is Author not checked here, if no author then "Author unknown" is
automatically added automatically added
""" """
if not self.title or not len(self.verses): if not self.title or not self.verses:
return False return False
else: else:
return True return True
@ -314,13 +314,10 @@ class SongImport(QtCore.QObject):
verse_def = new_verse_def verse_def = new_verse_def
sxml.add_verse_to_lyrics(verse_tag, verse_def[1:], verse_text, lang) sxml.add_verse_to_lyrics(verse_tag, verse_def[1:], verse_text, lang)
song.lyrics = unicode(sxml.extract_xml(), u'utf-8') song.lyrics = unicode(sxml.extract_xml(), u'utf-8')
if not len(self.verseOrderList) and \ if not self.verseOrderList and self.verseOrderListGeneratedUseful:
self.verseOrderListGeneratedUseful:
self.verseOrderList = self.verseOrderListGenerated self.verseOrderList = self.verseOrderListGenerated
for i, current_verse_def in enumerate(self.verseOrderList): self.verseOrderList = map(lambda v: verses_changed_to_other.get(v, v),
if verses_changed_to_other.has_key(current_verse_def): self.verseOrderList)
self.verseOrderList[i] = \
verses_changed_to_other[current_verse_def]
song.verse_order = u' '.join(self.verseOrderList) song.verse_order = u' '.join(self.verseOrderList)
song.copyright = self.copyright song.copyright = self.copyright
song.comments = self.comments song.comments = self.comments

View File

@ -204,7 +204,7 @@ class SongShowPlusImport(SongImport):
elif verse_type == "pre-chorus": elif verse_type == "pre-chorus":
verse_tag = VerseType.Tags[VerseType.PreChorus] verse_tag = VerseType.Tags[VerseType.PreChorus]
else: else:
if not self.otherList.has_key(verse_name): if verse_name not in self.otherList:
if ignore_unique: if ignore_unique:
return None return None
self.otherCount = self.otherCount + 1 self.otherCount = self.otherCount + 1

View File

@ -611,7 +611,7 @@ class OpenLyrics(object):
text += u'{%s}' % element.get(u'name') text += u'{%s}' % element.get(u'name')
# Some formattings may have only start tag. # Some formattings may have only start tag.
# Handle this case if element has no children and contains no text. # Handle this case if element has no children and contains no text.
if len(element) == 0 and not element.text: if not element and not element.text:
use_endtag = False use_endtag = False
# Append text from element. # Append text from element.
if element.text: if element.text:

View File

@ -239,7 +239,7 @@ class SongsPlugin(Plugin):
for sfile in os.listdir(db_dir): for sfile in os.listdir(db_dir):
if sfile.startswith(u'songs_') and sfile.endswith(u'.sqlite'): if sfile.startswith(u'songs_') and sfile.endswith(u'.sqlite'):
song_dbs.append(os.path.join(db_dir, sfile)) song_dbs.append(os.path.join(db_dir, sfile))
if len(song_dbs) == 0: if not song_dbs:
return return
progress = QtGui.QProgressDialog(self.formParent) progress = QtGui.QProgressDialog(self.formParent)
progress.setWindowModality(QtCore.Qt.WindowModal) progress.setWindowModality(QtCore.Qt.WindowModal)