Consolidate platform specific checks into the common module

This commit is contained in:
Jonathan Springer 2014-08-27 19:18:06 -04:00
parent 381da9c89d
commit f3207dac8e
20 changed files with 146 additions and 63 deletions

View File

@ -36,14 +36,14 @@ logging and a plugin framework are contained within the openlp.core module.
import os
import sys
import platform
import logging
from optparse import OptionParser
from traceback import format_exception
from PyQt4 import QtCore, QtGui
from openlp.core.common import Registry, OpenLPMixin, AppLocation, Settings, UiStrings, check_directory_exists
from openlp.core.common import Registry, OpenLPMixin, AppLocation, Settings, UiStrings, check_directory_exists, \
is_macosx, is_win
from openlp.core.lib import ScreenList
from openlp.core.resources import qInitResources
from openlp.core.ui.mainwindow import MainWindow
@ -126,7 +126,7 @@ class OpenLP(OpenLPMixin, QtGui.QApplication):
alternate_rows_repair_stylesheet = \
'QTableWidget, QListWidget, QTreeWidget {alternate-background-color: ' + base_color.name() + ';}\n'
application_stylesheet += alternate_rows_repair_stylesheet
if os.name == 'nt':
if is_win():
application_stylesheet += NT_REPAIR_STYLESHEET
if application_stylesheet:
self.setStyleSheet(application_stylesheet)
@ -275,7 +275,7 @@ def main(args=None):
# Throw the rest of the arguments at Qt, just in case.
qt_args.extend(args)
# Bug #1018855: Set the WM_CLASS property in X11
if platform.system() not in ['Windows', 'Darwin']:
if not is_win() and not is_macosx():
qt_args.append('OpenLP')
# Initialise the resources
qInitResources()

View File

@ -127,6 +127,33 @@ def de_hump(name):
sub_name = FIRST_CAMEL_REGEX.sub(r'\1_\2', name)
return SECOND_CAMEL_REGEX.sub(r'\1_\2', sub_name).lower()
def is_win():
"""
Returns true if running on a system with a nt kernel e.g. Windows, Wine
:return: True if system is running a nt kernel false otherwise
"""
return os.name.startswith('nt')
def is_macosx():
"""
Returns true if running on a system with a darwin kernel e.g. Mac OS X
:return: True if system is running a darwin kernel false otherwise
"""
return sys.platform.startswith('darwin')
def is_linux():
"""
Returns true if running on a system with a linux kernel e.g. Ubuntu, Debian, etc
:return: True if system is running a linux kernel false otherwise
"""
return sys.platform.startswith('linux')
from .openlpmixin import OpenLPMixin
from .registry import Registry
from .registrymixin import RegistryMixin

View File

@ -33,10 +33,10 @@ import logging
import os
import sys
from openlp.core.common import Settings
from openlp.core.common import Settings, is_win, is_macosx
if sys.platform != 'win32' and sys.platform != 'darwin':
if not is_win() and not is_macosx():
try:
from xdg import BaseDirectory
XDG_BASE_AVAILABLE = True
@ -145,13 +145,13 @@ def _get_os_dir_path(dir_type):
directory = os.path.abspath(os.path.join(os.path.dirname(openlp.__file__), '..', 'resources'))
if os.path.exists(directory):
return directory
if sys.platform == 'win32':
if is_win():
if dir_type == AppLocation.DataDir:
return os.path.join(str(os.getenv('APPDATA')), 'openlp', 'data')
elif dir_type == AppLocation.LanguageDir:
return os.path.dirname(openlp.__file__)
return os.path.join(str(os.getenv('APPDATA')), 'openlp')
elif sys.platform == 'darwin':
elif is_macosx():
if dir_type == AppLocation.DataDir:
return os.path.join(str(os.getenv('HOME')), 'Library', 'Application Support', 'openlp', 'Data')
elif dir_type == AppLocation.LanguageDir:

View File

@ -29,9 +29,7 @@
"""
Provide Registry values for adding to classes
"""
import os
from openlp.core.common import Registry
from openlp.core.common import Registry, is_win
class RegistryProperties(object):
@ -45,7 +43,7 @@ class RegistryProperties(object):
Adds the openlp to the class dynamically.
Windows needs to access the application in a dynamic manner.
"""
if os.name == 'nt':
if is_win():
return Registry().get('application')
else:
if not hasattr(self, '_application') or not self._application:

View File

@ -36,7 +36,7 @@ import sys
from PyQt4 import QtCore, QtGui
from openlp.core.common import ThemeLevel, SlideLimits, UiStrings
from openlp.core.common import ThemeLevel, SlideLimits, UiStrings, is_win, is_linux
log = logging.getLogger(__name__)
@ -44,7 +44,7 @@ log = logging.getLogger(__name__)
# Fix for bug #1014422.
X11_BYPASS_DEFAULT = True
if sys.platform.startswith('linux'):
if is_linux():
# Default to False on Gnome.
X11_BYPASS_DEFAULT = bool(not os.environ.get('GNOME_DESKTOP_SESSION_ID'))
# Default to False on Xfce.
@ -86,7 +86,7 @@ class Settings(QtCore.QSettings):
"""
__default_settings__ = {
'advanced/add page break': False,
'advanced/alternate rows': not sys.platform.startswith('win'),
'advanced/alternate rows': not is_win(),
'advanced/current media plugin': -1,
'advanced/data path': '',
'advanced/default color': '#ffffff',

View File

@ -38,7 +38,7 @@ import bs4
import sqlalchemy
from lxml import etree
from openlp.core.common import RegistryProperties
from openlp.core.common import RegistryProperties, is_linux
from PyQt4 import Qt, QtCore, QtGui, QtWebKit
@ -137,7 +137,7 @@ class ExceptionForm(QtGui.QDialog, Ui_ExceptionDialog, RegistryProperties):
'pyICU: %s\n' % ICU_VERSION + \
'pyUNO bridge: %s\n' % self._pyuno_import() + \
'VLC: %s\n' % VLC_VERSION
if platform.system() == 'Linux':
if is_linux():
if os.environ.get('KDE_FULL_SESSION') == 'true':
system += 'Desktop: KDE SC\n'
elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):

View File

@ -43,7 +43,7 @@ import sys
from PyQt4 import QtCore, QtGui, QtWebKit, QtOpenGL
from PyQt4.phonon import Phonon
from openlp.core.common import Registry, RegistryProperties, OpenLPMixin, Settings, translate
from openlp.core.common import Registry, RegistryProperties, OpenLPMixin, Settings, translate, is_macosx
from openlp.core.lib import ServiceItem, ImageSource, build_html, expand_tags, image_to_byte
from openlp.core.lib.theme import BackgroundType
@ -74,7 +74,7 @@ class Display(QtGui.QGraphicsView):
# OpenGL. Only white blank screen is shown on the 2nd monitor all the
# time. We need to investigate more how to use OpenGL properly on Mac OS
# X.
if sys.platform != 'darwin':
if not is_macosx():
self.setViewport(QtOpenGL.QGLWidget())
def setup(self):
@ -143,7 +143,7 @@ class MainDisplay(OpenLPMixin, Display, RegistryProperties):
# on Mac OS X. For next OpenLP version we should test it on other
# platforms. For OpenLP 2.0 keep it only for OS X to not cause any
# regressions on other platforms.
if sys.platform == 'darwin':
if is_macosx():
window_flags = QtCore.Qt.FramelessWindowHint | QtCore.Qt.Window
# For primary screen ensure it stays above the OS X dock
# and menu bar

View File

@ -41,7 +41,8 @@ from datetime import datetime
from PyQt4 import QtCore, QtGui
from openlp.core.common import Registry, RegistryProperties, AppLocation, Settings, check_directory_exists, translate
from openlp.core.common import Registry, RegistryProperties, AppLocation, Settings, check_directory_exists, translate, \
is_win, is_macosx
from openlp.core.lib import Renderer, OpenLPDockWidget, PluginManager, ImageManager, PluginStatus, ScreenList, \
build_icon
from openlp.core.lib.ui import UiStrings, create_action
@ -289,7 +290,7 @@ class Ui_MainWindow(object):
triggers=self.on_about_item_clicked)
# Give QT Extra Hint that this is an About Menu Item
self.about_item.setMenuRole(QtGui.QAction.AboutRole)
if os.name == 'nt':
if is_win():
self.local_help_file = os.path.join(AppLocation.get_directory(AppLocation.AppDir), 'OpenLP.chm')
self.offline_help_item = create_action(main_window, 'offlineHelpItem',
icon=':/system/system_help_contents.png',
@ -323,7 +324,7 @@ class Ui_MainWindow(object):
# Qt on OS X looks for keywords in the menu items title to determine which menu items get added to the main
# menu. If we are running on Mac OS X the menu items whose title contains those keywords but don't belong in the
# main menu need to be marked as such with QAction.NoRole.
if sys.platform == 'darwin':
if is_macosx():
self.settings_shortcuts_item.setMenuRole(QtGui.QAction.NoRole)
self.formatting_tag_item.setMenuRole(QtGui.QAction.NoRole)
add_actions(self.settings_menu, (self.settings_plugin_list_item, self.settings_language_menu.menuAction(),
@ -332,7 +333,7 @@ class Ui_MainWindow(object):
add_actions(self.tools_menu, (self.tools_open_data_folder, None))
add_actions(self.tools_menu, (self.tools_first_time_wizard, None))
add_actions(self.tools_menu, [self.update_theme_images])
if os.name == 'nt':
if is_win():
add_actions(self.help_menu, (self.offline_help_item, self.on_line_help_item, None, self.web_site_item,
self.about_item))
else:
@ -426,7 +427,7 @@ class Ui_MainWindow(object):
self.settings_plugin_list_item.setStatusTip(translate('OpenLP.MainWindow', 'List the Plugins'))
self.about_item.setText(translate('OpenLP.MainWindow', '&About'))
self.about_item.setStatusTip(translate('OpenLP.MainWindow', 'More information about OpenLP'))
if os.name == 'nt':
if is_win():
self.offline_help_item.setText(translate('OpenLP.MainWindow', '&User Guide'))
self.on_line_help_item.setText(translate('OpenLP.MainWindow', '&Online Help'))
self.search_shortcut_action.setText(UiStrings().Search)
@ -1073,7 +1074,7 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow, RegistryProperties):
if self.live_controller.display:
self.live_controller.display.close()
self.live_controller.display = None
if os.name == 'nt':
if is_win():
# Needed for Windows to stop crashes on exit
Registry().remove('application')

View File

@ -38,7 +38,7 @@ import threading
from PyQt4 import QtGui
from openlp.core.common import Settings
from openlp.core.common import Settings, is_win, is_macosx
from openlp.core.lib import translate
from openlp.core.ui.media import MediaState
from openlp.core.ui.media.mediaplayer import MediaPlayer
@ -52,7 +52,7 @@ try:
except (ImportError, NameError, NotImplementedError):
pass
except OSError as e:
if sys.platform.startswith('win'):
if is_win():
if not isinstance(e, WindowsError) and e.winerror != 126:
raise
else:
@ -139,9 +139,9 @@ class VlcPlayer(MediaPlayer):
# You have to give the id of the QFrame (or similar object)
# to vlc, different platforms have different functions for this.
win_id = int(display.vlc_widget.winId())
if sys.platform == "win32":
if is_win():
display.vlc_media_player.set_hwnd(win_id)
elif sys.platform == "darwin":
elif is_macosx():
# We have to use 'set_nsobject' since Qt4 on OSX uses Cocoa
# framework and not the old Carbon.
display.vlc_media_player.set_nsobject(win_id)

View File

@ -44,10 +44,10 @@ from random import randint
from PyQt4 import QtGui, QtCore
from openlp.core.common import Registry, AppLocation, Settings
from openlp.core.common import Registry, AppLocation, Settings, is_win, is_macosx
if sys.platform != 'win32' and sys.platform != 'darwin':
if not is_win() and not is_macosx():
try:
from xdg import BaseDirectory
XDG_BASE_AVAILABLE = True

View File

@ -35,7 +35,7 @@ import sys
from PyQt4 import QtCore, QtGui
from openlp.core.common import AppLocation, Settings, translate
from openlp.core.common import AppLocation, Settings, translate, is_win, is_macosx
log = logging.getLogger(__name__)
@ -60,7 +60,7 @@ class LanguageManager(object):
app_translator = QtCore.QTranslator()
app_translator.load(language, lang_path)
# A translator for buttons and other default strings provided by Qt.
if sys.platform != 'win32' and sys.platform != 'darwin':
if not is_win() and not is_macosx():
lang_path = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)
default_translator = QtCore.QTranslator()
default_translator.load('qt_%s' % language, lang_path)

View File

@ -42,7 +42,9 @@ import logging
import os
import time
if os.name == 'nt':
from openlp.core.common import is_win
if is_win():
from win32com.client import Dispatch
import pywintypes
# Declare an empty exception to match the exception imported from UNO
@ -93,7 +95,7 @@ class ImpressController(PresentationController):
Impress is able to run on this machine.
"""
log.debug('check_available')
if os.name == 'nt':
if is_win():
return self.get_com_servicemanager() is not None
else:
return uno_available
@ -104,7 +106,7 @@ class ImpressController(PresentationController):
UNO interface when required.
"""
log.debug('start process Openoffice')
if os.name == 'nt':
if is_win():
self.manager = self.get_com_servicemanager()
self.manager._FlagAsMethod('Bridge_GetStruct')
self.manager._FlagAsMethod('Bridge_GetValueObject')
@ -175,7 +177,7 @@ class ImpressController(PresentationController):
self.docs[0].close_presentation()
desktop = None
try:
if os.name != 'nt':
if not is_win():
desktop = self.get_uno_desktop()
else:
desktop = self.get_com_desktop()
@ -223,7 +225,7 @@ class ImpressDocument(PresentationDocument):
is available the presentation is loaded and started.
"""
log.debug('Load Presentation OpenOffice')
if os.name == 'nt':
if is_win():
desktop = self.controller.get_com_desktop()
if desktop is None:
self.controller.start_process()
@ -236,7 +238,7 @@ class ImpressDocument(PresentationDocument):
return False
self.desktop = desktop
properties = []
if os.name != 'nt':
if not is_win():
# Recent versions of Impress on Windows won't start the presentation if it starts as minimized. It seems OK
# on Linux though.
properties.append(self.create_property('Minimized', True))
@ -246,7 +248,7 @@ class ImpressDocument(PresentationDocument):
except:
log.warning('Failed to load presentation %s' % url)
return False
if os.name == 'nt':
if is_win():
# As we can't start minimized the Impress window gets in the way.
# Either window.setPosSize(0, 0, 200, 400, 12) or .setVisible(False)
window = self.document.getCurrentController().getFrame().getContainerWindow()
@ -264,7 +266,7 @@ class ImpressDocument(PresentationDocument):
log.debug('create thumbnails OpenOffice')
if self.check_thumbnails():
return
if os.name == 'nt':
if is_win():
thumb_dir_url = 'file:///' + self.get_temp_folder().replace('\\', '/') \
.replace(':', '|').replace(' ', '%20')
else:
@ -297,7 +299,7 @@ class ImpressDocument(PresentationDocument):
Create an OOo style property object which are passed into some Uno methods.
"""
log.debug('create property OpenOffice')
if os.name == 'nt':
if is_win():
property_object = self.controller.manager.Bridge_GetStruct('com.sun.star.beans.PropertyValue')
else:
property_object = PropertyValue()

View File

@ -34,7 +34,7 @@ import re
from subprocess import check_output, CalledProcessError, STDOUT
from openlp.core.utils import AppLocation
from openlp.core.common import Settings
from openlp.core.common import Settings, is_win
from openlp.core.lib import ScreenList
from .presentationcontroller import PresentationController, PresentationDocument
@ -123,7 +123,7 @@ class PdfController(PresentationController):
else:
# Fallback to autodetection
application_path = AppLocation.get_directory(AppLocation.AppDir)
if os.name == 'nt':
if is_win():
# for windows we only accept mudraw.exe in the base folder
application_path = AppLocation.get_directory(AppLocation.AppDir)
if os.path.isfile(os.path.join(application_path, 'mudraw.exe')):

View File

@ -33,7 +33,9 @@ This modul is for controlling powerpiont. PPT API documentation:
import os
import logging
if os.name == 'nt':
from openlp.core.common import is_win
if is_win():
from win32com.client import Dispatch
import winreg
import win32ui
@ -69,7 +71,7 @@ class PowerpointController(PresentationController):
PowerPoint is able to run on this machine.
"""
log.debug('check_available')
if os.name == 'nt':
if is_win():
try:
winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, 'PowerPoint.Application').Close()
return True
@ -77,7 +79,7 @@ class PowerpointController(PresentationController):
pass
return False
if os.name == 'nt':
if is_win():
def start_process(self):
"""
Loads PowerPoint process.
@ -271,7 +273,7 @@ class PowerpointDocument(PresentationDocument):
trace_error_handler(log)
self.show_error_msg()
if os.name == 'nt':
if is_win():
def start_presentation(self):
"""
Starts a presentation from the beginning.

View File

@ -30,7 +30,9 @@
import logging
import os
if os.name == 'nt':
from openlp.core.common import is_win
if is_win():
from ctypes import cdll
from ctypes.wintypes import RECT
@ -63,11 +65,11 @@ class PptviewController(PresentationController):
PPT Viewer is able to run on this machine.
"""
log.debug('check_available')
if os.name != 'nt':
if not is_win():
return False
return self.check_installed()
if os.name == 'nt':
if is_win():
def check_installed(self):
"""
Check the viewer is installed.

View File

@ -37,7 +37,7 @@ from time import sleep
from PyQt4 import QtCore, QtGui
from openlp.core import Settings
from openlp.core.common import Registry
from openlp.core.common import Registry, is_win
from openlp.core.lib import translate
from openlp.plugins.songs.forms.songselectdialog import Ui_SongSelectDialog
from openlp.plugins.songs.lib.songselect import SongSelectImport
@ -377,7 +377,7 @@ class SongSelectForm(QtGui.QDialog, Ui_SongSelectDialog):
Adds the openlp to the class dynamically.
Windows needs to access the application in a dynamic manner.
"""
if os.name == 'nt':
if is_win():
return Registry().get('application')
else:
if not hasattr(self, '_application'):

View File

@ -32,7 +32,7 @@ The :mod:`importer` modules provides the general song import functionality.
import os
import logging
from openlp.core.common import translate, UiStrings
from openlp.core.common import translate, UiStrings, is_win
from openlp.core.ui.wizard import WizardStrings
from .importers.opensong import OpenSongImport
from .importers.easyslides import EasySlidesImport
@ -70,14 +70,14 @@ except ImportError:
log.exception('Error importing %s', 'OooImport')
HAS_OOO = False
HAS_MEDIASHOUT = False
if os.name == 'nt':
if is_win():
try:
from .importers.mediashout import MediaShoutImport
HAS_MEDIASHOUT = True
except ImportError:
log.exception('Error importing %s', 'MediaShoutImport')
HAS_WORSHIPCENTERPRO = False
if os.name == 'nt':
if is_win():
try:
from .importers.worshipcenterpro import WorshipCenterProImport
HAS_WORSHIPCENTERPRO = True

View File

@ -32,13 +32,14 @@ import time
from PyQt4 import QtCore
from openlp.core.common import is_win
from openlp.core.utils import get_uno_command, get_uno_instance
from openlp.core.lib import translate
from .songimport import SongImport
log = logging.getLogger(__name__)
if os.name == 'nt':
if is_win():
from win32com.client import Dispatch
NoConnectException = Exception
else:
@ -106,7 +107,7 @@ class OpenOfficeImport(SongImport):
Start OpenOffice.org process
TODO: The presentation/Impress plugin may already have it running
"""
if os.name == 'nt':
if is_win():
self.start_ooo_process()
self.desktop = self.ooo_manager.createInstance('com.sun.star.frame.Desktop')
else:
@ -133,7 +134,7 @@ class OpenOfficeImport(SongImport):
Start the OO Process
"""
try:
if os.name == 'nt':
if is_win():
self.ooo_manager = Dispatch('com.sun.star.ServiceManager')
self.ooo_manager._FlagAsMethod('Bridge_GetStruct')
self.ooo_manager._FlagAsMethod('Bridge_GetValueObject')
@ -150,7 +151,7 @@ class OpenOfficeImport(SongImport):
Open the passed file in OpenOffice.org Impress
"""
self.file_path = file_path
if os.name == 'nt':
if is_win():
url = file_path.replace('\\', '/')
url = url.replace(':', '|').replace(' ', '%20')
url = 'file:///' + url

View File

@ -37,12 +37,13 @@ import logging
import os
import re
from openlp.core.common import is_win
from .openoffice import OpenOfficeImport
log = logging.getLogger(__name__)
if os.name == 'nt':
if is_win():
from .openoffice import PAGE_BEFORE, PAGE_AFTER, PAGE_BOTH
RuntimeException = Exception
else:

View File

@ -32,7 +32,8 @@ Functional tests to test the AppLocation class and related methods.
from unittest import TestCase
from openlp.core.common import check_directory_exists, de_hump, trace_error_handler, translate
from openlp.core.common import check_directory_exists, de_hump, trace_error_handler, translate, is_win, is_macosx, \
is_linux
from tests.functional import MagicMock, patch
@ -139,3 +140,51 @@ class TestCommonFunctions(TestCase):
# THEN: the translated string should be returned, and the mocked function should have been called
mocked_translate.assert_called_with(context, text, comment, encoding, n)
self.assertEqual('Translated string', result, 'The translated string should have been returned')
def is_win_test(self):
"""
Test the is_win() function
"""
# GIVEN: Mocked out objects
with patch('openlp.core.common.os') as mocked_os, patch('openlp.core.common.sys') as mocked_sys:
# WHEN: The mocked os.name and sys.platform are set to 'nt' and 'win32' repectivly
mocked_os.name = 'nt'
mocked_sys.platform = 'win32'
# THEN: The three platform functions should perform properly
self.assertTrue(is_win(), 'is_win() should return True')
self.assertFalse(is_macosx(), 'is_macosx() should return False')
self.assertFalse(is_linux(), 'is_linux() should return False')
def is_macosx_test(self):
"""
Test the is_macosx() function
"""
# GIVEN: Mocked out objects
with patch('openlp.core.common.os') as mocked_os, patch('openlp.core.common.sys') as mocked_sys:
# WHEN: The mocked os.name and sys.platform are set to 'posix' and 'darwin' repectivly
mocked_os.name = 'posix'
mocked_sys.platform = 'darwin'
# THEN: The three platform functions should perform properly
self.assertTrue(is_macosx(), 'is_macosx() should return True')
self.assertFalse(is_win(), 'is_win() should return False')
self.assertFalse(is_linux(), 'is_linux() should return False')
def is_linux_test(self):
"""
Test the is_linux() function
"""
# GIVEN: Mocked out objects
with patch('openlp.core.common.os') as mocked_os, patch('openlp.core.common.sys') as mocked_sys:
# WHEN: The mocked os.name and sys.platform are set to 'posix' and 'linux3' repectivly
mocked_os.name = 'posix'
mocked_sys.platform = 'linux3'
# THEN: The three platform functions should perform properly
self.assertTrue(is_linux(), 'is_linux() should return True')
self.assertFalse(is_win(), 'is_win() should return False')
self.assertFalse(is_macosx(), 'is_macosx() should return False')