openlp/openlp/core/utils/__init__.py

263 lines
10 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
###############################################################################
# OpenLP - Open Source Lyrics Projection #
# --------------------------------------------------------------------------- #
2009-12-31 12:52:01 +00:00
# Copyright (c) 2008-2010 Raoul Snyman #
# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael #
2010-07-24 22:10:47 +00:00
# Gorven, Scott Guerrieri, Meinert Jordan, Andreas Preikschat, Christian #
# Richter, Philip Ridout, Maikel Stuivenberg, Martin Thompson, Jon Tibble, #
# Carsten Tinggaard, Frode Woldsund #
# --------------------------------------------------------------------------- #
# This program is free software; you can redistribute it and/or modify it #
# under the terms of the GNU General Public License as published by the Free #
# Software Foundation; version 2 of the License. #
# #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
# more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
2010-06-10 19:45:02 +00:00
"""
The :mod:`utils` module provides the utility libraries for OpenLP
"""
2010-07-30 22:48:09 +00:00
import logging
import os
2010-07-30 22:48:09 +00:00
import re
import sys
2010-07-30 22:48:09 +00:00
import time
2009-10-12 04:43:02 +00:00
import urllib2
2010-06-10 19:45:02 +00:00
from datetime import datetime
from PyQt4 import QtGui, QtCore
import openlp
2010-07-30 22:48:09 +00:00
from openlp.core.lib import Receiver, translate
2009-10-14 17:52:50 +00:00
log = logging.getLogger(__name__)
images_filter = None
2009-10-14 17:52:50 +00:00
2010-07-30 22:48:09 +00:00
class VersionThread(QtCore.QThread):
"""
A special Qt thread class to fetch the version of OpenLP from the website.
This is threaded so that it doesn't affect the loading time of OpenLP.
"""
def __init__(self, parent, app_version):
QtCore.QThread.__init__(self, parent)
self.app_version = app_version
self.version_splitter = re.compile(
r'([0-9]+).([0-9]+).([0-9]+)(?:-bzr([0-9]+))?')
def run(self):
"""
Run the thread.
"""
time.sleep(1)
Receiver.send_message(u'maindisplay_blank_check')
version = check_latest_version(self.app_version)
remote_version = {}
local_version = {}
match = self.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))
match = self.version_splitter.match(self.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))
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)
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 AppLocation(object):
"""
The :class:`AppLocation` class is a static class which retrieves a
directory based on the directory type.
"""
AppDir = 1
ConfigDir = 2
DataDir = 3
PluginsDir = 4
VersionDir = 5
2010-06-22 12:32:15 +00:00
CacheDir = 6
@staticmethod
def get_directory(dir_type=1):
"""
Return the appropriate directory according to the directory type.
``dir_type``
The directory type you want, for instance the data directory.
"""
if dir_type == AppLocation.AppDir:
2010-03-18 15:43:27 +00:00
return os.path.abspath(os.path.split(sys.argv[0])[0])
elif dir_type == AppLocation.ConfigDir:
if sys.platform == u'win32':
path = os.path.join(os.getenv(u'APPDATA'), u'openlp')
elif sys.platform == u'darwin':
path = os.path.join(os.getenv(u'HOME'), u'Library',
u'Application Support', u'openlp')
else:
try:
from xdg import BaseDirectory
2010-04-23 16:00:32 +00:00
path = os.path.join(
BaseDirectory.xdg_config_home, u'openlp')
except ImportError:
path = os.path.join(os.getenv(u'HOME'), u'.openlp')
return path
elif dir_type == AppLocation.DataDir:
if sys.platform == u'win32':
path = os.path.join(os.getenv(u'APPDATA'), u'openlp', u'data')
elif sys.platform == u'darwin':
path = os.path.join(os.getenv(u'HOME'), u'Library',
u'Application Support', u'openlp', u'Data')
else:
try:
from xdg import BaseDirectory
path = os.path.join(BaseDirectory.xdg_data_home, u'openlp')
except ImportError:
path = os.path.join(os.getenv(u'HOME'), u'.openlp', u'data')
return path
elif dir_type == AppLocation.PluginsDir:
2010-03-18 15:43:27 +00:00
plugin_path = None
app_path = os.path.abspath(os.path.split(sys.argv[0])[0])
if hasattr(sys, u'frozen') and sys.frozen == 1:
2010-03-18 15:43:27 +00:00
plugin_path = os.path.join(app_path, u'plugins')
else:
2010-03-18 15:52:37 +00:00
plugin_path = os.path.join(
os.path.split(openlp.__file__)[0], u'plugins')
2010-03-18 15:43:27 +00:00
return plugin_path
elif dir_type == AppLocation.VersionDir:
if hasattr(sys, u'frozen') and sys.frozen == 1:
plugin_path = os.path.abspath(os.path.split(sys.argv[0])[0])
else:
plugin_path = os.path.split(openlp.__file__)[0]
return plugin_path
2010-06-22 12:32:15 +00:00
elif dir_type == AppLocation.CacheDir:
if sys.platform == u'win32':
path = os.path.join(os.getenv(u'APPDATA'), u'openlp')
elif sys.platform == u'darwin':
path = os.path.join(os.getenv(u'HOME'), u'Library',
u'Application Support', u'openlp')
else:
try:
from xdg import BaseDirectory
path = os.path.join(
BaseDirectory.xdg_cache_home, u'openlp')
except ImportError:
path = os.path.join(os.getenv(u'HOME'), u'.openlp')
return path
2010-04-27 16:27:57 +00:00
@staticmethod
def get_data_path():
path = AppLocation.get_directory(AppLocation.DataDir)
if not os.path.exists(path):
os.makedirs(path)
return path
@staticmethod
def get_section_data_path(section):
data_path = AppLocation.get_data_path()
path = os.path.join(data_path, section)
if not os.path.exists(path):
os.makedirs(path)
return path
2010-04-27 16:27:57 +00:00
def check_latest_version(current_version):
"""
Check the latest version of OpenLP against the version file on the OpenLP
site.
``current_version``
The current version of OpenLP.
"""
version_string = current_version[u'full']
2010-04-23 19:42:51 +00:00
#set to prod in the distribution config file.
2010-04-28 14:17:42 +00:00
settings = QtCore.QSettings()
settings.beginGroup(u'general')
last_test = unicode(settings.value(u'last version test',
QtCore.QVariant(datetime.now().date())).toString())
2009-11-30 18:29:22 +00:00
this_test = unicode(datetime.now().date())
2010-04-28 14:17:42 +00:00
settings.setValue(u'last version test', QtCore.QVariant(this_test))
settings.endGroup()
2009-11-30 18:29:22 +00:00
if last_test != this_test:
if current_version[u'build']:
2010-04-23 16:00:32 +00:00
req = urllib2.Request(
u'http://www.openlp.org/files/dev_version.txt')
else:
req = urllib2.Request(u'http://www.openlp.org/files/version.txt')
req.add_header(u'User-Agent', u'OpenLP/%s' % current_version[u'full'])
2009-10-12 04:43:02 +00:00
try:
version_string = unicode(urllib2.urlopen(req, None).read()).strip()
2009-10-12 04:43:02 +00:00
except IOError, e:
if hasattr(e, u'reason'):
log.exception(u'Reason for failure: %s', e.reason)
return version_string
2010-04-23 16:00:32 +00:00
def add_actions(target, actions):
"""
Adds multiple actions to a menu or toolbar in one command.
``target``
The menu or toolbar to add actions to.
``actions``
2010-04-23 19:42:51 +00:00
The actions to be added. An action consisting of the keyword 'None'
will result in a separator being inserted into the target.
2010-04-23 16:00:32 +00:00
"""
for action in actions:
if action is None:
target.addSeparator()
else:
target.addAction(action)
def get_filesystem_encoding():
"""
Returns the name of the encoding used to convert Unicode filenames into
system file names.
"""
encoding = sys.getfilesystemencoding()
if encoding is None:
encoding = sys.getdefaultencoding()
return encoding
def get_images_filter():
"""
Returns a filter string for a file dialog containing all the supported
image formats.
"""
global images_filter
if not images_filter:
log.debug(u'Generating images filter.')
2010-06-19 18:42:49 +00:00
formats = [unicode(fmt)
for fmt in QtGui.QImageReader.supportedImageFormats()]
2010-06-19 18:42:49 +00:00
visible_formats = u'(*.%s)' % u'; *.'.join(formats)
actual_formats = u'(*.%s)' % u' *.'.join(formats)
images_filter = u'%s %s %s' % (translate('OpenLP', 'Image Files'),
visible_formats, actual_formats)
return images_filter
2010-04-16 22:06:28 +00:00
from languagemanager import LanguageManager
2010-05-25 23:07:50 +00:00
__all__ = [u'AppLocation', u'check_latest_version', u'add_actions',
2010-07-27 09:32:52 +00:00
u'get_filesystem_encoding', u'LanguageManager']