← Back to team overview

openlp-core team mailing list archive

[Merge] lp:~gerald-britton/openlp/constants into lp:openlp

 

jerryb has proposed merging lp:~gerald-britton/openlp/constants into lp:openlp.

Requested reviews:
  OpenLP Core (openlp-core)

For more details, see:
https://code.launchpad.net/~gerald-britton/openlp/constants/+merge/59990

NOT READY FOR MERGING!

This patch shows how we might simplify OpenLP code by using constant definitions and the partial function from the functools module.  It adds a class to the __init__.py module in core/lib and uses that class in core/ui/servicemanager.py.  The class definition contains constants corresponding to the translation contexts used in the calls to the translate function.  

Note:  I put these constants in a class to provide logical separation, though they could just as well have been inserted at the module level in core/lib/__init__.py.

In servicemanager.py, I make use of this new class in conjunction with the partial function.  Then, wherever translate() is called inside this module, I can drop the first parameter, which is -- well -- a constant!

Note: I reused the function name "translate" in this case, since only one constant is in use in servicemanager.py.  This is not required but just a convenient choice for the proof-of-concept. We can use new names for the partial functions if desired. (We would need to do so if multiple translation context constants were in use in one module).

The advantages of this approach are:

1. Constants are grouped together for easy management and visibility.
2. functools.partial provides a means to curry the constants in function calls.
3. Code using the partial function becomes simpler and shorter.
4. Python-generated byte-code becomes shorter since it does not need to build a reference to the constant for each function call.

Note 2: This proposal is just for review.  If there is consensus to proceed in this direction, other modules in core/ui should be similarly modified.

NOT READY FOR MERGING!





-- 
https://code.launchpad.net/~gerald-britton/openlp/constants/+merge/59990
Your team OpenLP Core is requested to review the proposed merge of lp:~gerald-britton/openlp/constants into lp:openlp.
=== modified file 'openlp/core/lib/__init__.py'
--- openlp/core/lib/__init__.py	2011-05-03 17:36:20 +0000
+++ openlp/core/lib/__init__.py	2011-05-04 20:23:23 +0000
@@ -292,3 +292,41 @@
 from renderer import Renderer
 from mediamanageritem import MediaManagerItem
 from openlp.core.utils.actions import ActionList
+
+###############################################################################
+#
+#  Define constants for translation contexts.
+#
+###############################################################################
+
+
+class TranslateContext:
+    prefix = 'OpenLP.'
+    ABOUTFORM = prefix + 'AboutForm' 
+    ADVANCEDTAB = prefix + 'AdvancedTab' 
+    DISPLAYTAGDIALOG = prefix + 'DisplayTagDialog' 
+    DISPLAYTAGTAB = prefix + 'DisplayTagTab' 
+    EXCEPTIONDIALOG = prefix + 'ExceptionDialog' 
+    EXCEPTIONFORM = prefix + 'ExceptionForm' 
+    FILERENAMEFORM = prefix + 'FileRenameForm' 
+    FIRSTTIMELANGUAGEFORM = prefix + 'FirstTimeLanguageForm' 
+    FIRSTTIMEWIZARD = prefix + 'FirstTimeWizard' 
+    GENERALTAB = prefix + 'GeneralTab' 
+    MAINDISPLAY = prefix + 'MainDisplay' 
+    MAINWINDOW = prefix + 'MainWindow' 
+    PLUGINFORM = prefix + 'PluginForm' 
+    PRINTSERVICEDIALOG = prefix + 'PrintServiceDialog' 
+    PRINTSERVICEFORM = prefix + 'PrintServiceForm' 
+    SCREENLIST = prefix + 'ScreenList' 
+    SERVICEITEMEDITFORM = prefix + 'ServiceItemEditForm' 
+    SERVICEMANAGER = prefix + 'ServiceManager' 
+    SERVICENOTEFORM = prefix + 'ServiceNoteForm' 
+    SETTINGSFORM = prefix + 'SettingsForm' 
+    SHORTCUTLISTDIALOG = prefix + 'ShortcutListDialog' 
+    SLIDECONTROLLER = prefix + 'SlideController' 
+    STARTTIMEFORM = prefix + 'StartTimeForm' 
+    THEMEFORM = prefix + 'ThemeForm' 
+    THEMEMANAGER = prefix + 'ThemeManager' 
+    THEMESTAB = prefix + 'ThemesTab' 
+    THEMEWIZARD = prefix + 'ThemeWizard' 
+    UI = prefix + 'Ui' 

=== modified file 'openlp/core/ui/servicemanager.py'
--- openlp/core/ui/servicemanager.py	2011-04-29 08:45:36 +0000
+++ openlp/core/ui/servicemanager.py	2011-05-04 20:23:23 +0000
@@ -33,7 +33,7 @@
 from PyQt4 import QtCore, QtGui
 
 from openlp.core.lib import OpenLPToolbar, ServiceItem, Receiver, build_icon, \
-    ItemCapabilities, SettingsManager, translate
+    ItemCapabilities, SettingsManager, translate, TranslateContext
 from openlp.core.lib.theme import ThemeLevel
 from openlp.core.lib.ui import UiStrings, critical_error_message_box, \
     context_menu_action, find_and_set_in_combo_box
@@ -42,6 +42,8 @@
 from openlp.core.utils import AppLocation, delete_file, file_is_unicode, \
     split_filename
 from openlp.core.utils.actions import ActionList, CategoryOrder
+from functools import partial
+translate = partial(translate, TranslateContext.SERVICEMANAGER)
 
 class ServiceManagerList(QtGui.QTreeWidget):
     """
@@ -115,11 +117,11 @@
             UiStrings().CreateService, self.onNewServiceClicked)
         self.toolbar.addToolbarButton(
             UiStrings().OpenService, u':/general/general_open.png',
-            translate('OpenLP.ServiceManager', 'Load an existing service'),
+            translate('Load an existing service'),
             self.onLoadServiceClicked)
         self.toolbar.addToolbarButton(
             UiStrings().SaveService, u':/general/general_save.png',
-            translate('OpenLP.ServiceManager', 'Save this service'),
+            translate('Save this service'),
             self.saveFile)
         self.toolbar.addSeparator()
         self.themeLabel = QtGui.QLabel(u'%s:' % UiStrings().Theme, self)
@@ -127,8 +129,8 @@
         self.themeLabel.setObjectName(u'themeLabel')
         self.toolbar.addToolbarWidget(u'ThemeLabel', self.themeLabel)
         self.themeComboBox = QtGui.QComboBox(self.toolbar)
-        self.themeComboBox.setToolTip(translate('OpenLP.ServiceManager',
-            'Select a theme for the service'))
+        self.themeComboBox.setToolTip(
+            translate('Select a theme for the service'))
         self.themeComboBox.setSizeAdjustPolicy(
             QtGui.QComboBox.AdjustToMinimumContentsLength)
         self.themeComboBox.setSizePolicy(
@@ -162,10 +164,9 @@
         # Add the bottom toolbar
         self.orderToolbar = OpenLPToolbar(self)
         self.serviceManagerList.moveTop = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Move to &top'),
+            translate('Move to &top'),
             u':/services/service_top.png',
-            translate('OpenLP.ServiceManager',
-            'Move item to the top of the service.'),
+            translate('Move item to the top of the service.'),
             self.onServiceTop, shortcuts=[QtCore.Qt.Key_Home])
         self.serviceManagerList.moveTop.setObjectName(u'moveTop')
         action_list = ActionList.get_instance()
@@ -174,82 +175,73 @@
         action_list.add_action(
             self.serviceManagerList.moveTop, UiStrings().Service)
         self.serviceManagerList.moveUp = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Move &up'),
+            translate('Move &up'),
             u':/services/service_up.png',
-            translate('OpenLP.ServiceManager',
-            'Move item up one position in the service.'),
+            translate('Move item up one position in the service.'),
             self.onServiceUp, shortcuts=[QtCore.Qt.Key_PageUp])
         self.serviceManagerList.moveUp.setObjectName(u'moveUp')
         action_list.add_action(
             self.serviceManagerList.moveUp, UiStrings().Service)
         self.serviceManagerList.moveDown = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Move &down'),
+            translate('Move &down'),
             u':/services/service_down.png',
-            translate('OpenLP.ServiceManager',
-            'Move item down one position in the service.'),
+            translate('Move item down one position in the service.'),
             self.onServiceDown, shortcuts=[QtCore.Qt.Key_PageDown])
         self.serviceManagerList.moveDown.setObjectName(u'moveDown')
         action_list.add_action(
             self.serviceManagerList.moveDown, UiStrings().Service)
         self.serviceManagerList.moveBottom = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Move to &bottom'),
+            translate('Move to &bottom'),
             u':/services/service_bottom.png',
-            translate('OpenLP.ServiceManager',
-            'Move item to the end of the service.'),
+            translate('Move item to the end of the service.'),
             self.onServiceEnd, shortcuts=[QtCore.Qt.Key_End])
         self.serviceManagerList.moveBottom.setObjectName(u'moveBottom')
         action_list.add_action(
             self.serviceManagerList.moveBottom, UiStrings().Service)
         self.serviceManagerList.down = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Move &down'),
+            translate('Move &down'),
             None,
-            translate('OpenLP.ServiceManager',
-            'Moves the selection down the window.'),
+            translate('Moves the selection down the window.'),
             self.onMoveSelectionDown, shortcuts=[QtCore.Qt.Key_Down])
         self.serviceManagerList.down.setObjectName(u'down')
         action_list.add_action(self.serviceManagerList.down)
         self.serviceManagerList.down.setVisible(False)
         self.serviceManagerList.up = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Move up'),
+            translate('Move up'),
             None,
-            translate('OpenLP.ServiceManager',
-            'Moves the selection up the window.'),
+            translate('Moves the selection up the window.'),
             self.onMoveSelectionUp, shortcuts=[QtCore.Qt.Key_Up])
         self.serviceManagerList.up.setObjectName(u'up')
         action_list.add_action(self.serviceManagerList.up)
         self.serviceManagerList.up.setVisible(False)
         self.orderToolbar.addSeparator()
         self.serviceManagerList.delete = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', '&Delete From Service'),
+            translate('&Delete From Service'),
             u':/general/general_delete.png',
-            translate('OpenLP.ServiceManager',
-            'Delete the selected item from the service.'),
+            translate('Delete the selected item from the service.'),
             self.onDeleteFromService)
         self.orderToolbar.addSeparator()
         self.serviceManagerList.expand = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', '&Expand all'),
+            translate('&Expand all'),
             u':/services/service_expand_all.png',
-            translate('OpenLP.ServiceManager',
-            'Expand all the service items.'),
+            translate('Expand all the service items.'),
             self.onExpandAll, shortcuts=[QtCore.Qt.Key_Plus])
         self.serviceManagerList.expand.setObjectName(u'expand')
         action_list.add_action(
             self.serviceManagerList.expand, UiStrings().Service)
         self.serviceManagerList.collapse = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', '&Collapse all'),
+            translate('&Collapse all'),
             u':/services/service_collapse_all.png',
-            translate('OpenLP.ServiceManager',
-            'Collapse all the service items.'),
+            translate('Collapse all the service items.'),
             self.onCollapseAll, shortcuts=[QtCore.Qt.Key_Minus])
         self.serviceManagerList.collapse.setObjectName(u'collapse')
         action_list.add_action(
             self.serviceManagerList.collapse, UiStrings().Service)
         self.orderToolbar.addSeparator()
         self.serviceManagerList.makeLive = self.orderToolbar.addToolbarButton(
-            translate('OpenLP.ServiceManager', 'Go Live'),
+            translate('Go Live'),
             u':/general/general_live.png',
-            translate('OpenLP.ServiceManager',
-            'Send the selected item to Live.'), self.makeLive,
+            translate('Send the selected item to Live.'), self.makeLive,
             shortcuts=[QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return])
         self.serviceManagerList.makeLive.setObjectName(u'orderToolbar')
         action_list.add_action(
@@ -293,40 +285,40 @@
         # build the drag and drop context menu
         self.dndMenu = QtGui.QMenu()
         self.newAction = self.dndMenu.addAction(
-            translate('OpenLP.ServiceManager', '&Add New Item'))
+            translate('&Add New Item'))
         self.newAction.setIcon(build_icon(u':/general/general_edit.png'))
         self.addToAction = self.dndMenu.addAction(
-            translate('OpenLP.ServiceManager', '&Add to Selected Item'))
+            translate('&Add to Selected Item'))
         self.addToAction.setIcon(build_icon(u':/general/general_edit.png'))
         # build the context menu
         self.menu = QtGui.QMenu()
         self.editAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', '&Edit Item'))
+            translate('&Edit Item'))
         self.editAction.setIcon(build_icon(u':/general/general_edit.png'))
         self.maintainAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', '&Reorder Item'))
+            translate('&Reorder Item'))
         self.maintainAction.setIcon(build_icon(u':/general/general_edit.png'))
         self.notesAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', '&Notes'))
+            translate('&Notes'))
         self.notesAction.setIcon(build_icon(u':/services/service_notes.png'))
         self.timeAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', '&Start Time'))
+            translate('&Start Time'))
         self.timeAction.setIcon(build_icon(u':/media/media_time.png'))
         self.deleteAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', '&Delete >From Service'))
+            translate('&Delete From Service'))
         self.deleteAction.setIcon(build_icon(u':/general/general_delete.png'))
         self.sep1 = self.menu.addAction(u'')
         self.sep1.setSeparator(True)
         self.previewAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', 'Show &Preview'))
+            translate('Show &Preview'))
         self.previewAction.setIcon(build_icon(u':/general/general_preview.png'))
         self.liveAction = self.menu.addAction(
-            translate('OpenLP.ServiceManager', 'Show &Live'))
+            translate('Show &Live'))
         self.liveAction.setIcon(build_icon(u':/general/general_live.png'))
         self.sep2 = self.menu.addAction(u'')
         self.sep2.setSeparator(True)
         self.themeMenu = QtGui.QMenu(
-            translate('OpenLP.ServiceManager', '&Change Item Theme'))
+            translate('&Change Item Theme'))
         self.menu.addMenu(self.themeMenu)
         self.serviceManagerList.addActions(
             [self.serviceManagerList.moveDown,
@@ -411,10 +403,10 @@
             elif result == QtGui.QMessageBox.Save:
                 self.saveFile()
         fileName = unicode(QtGui.QFileDialog.getOpenFileName(self.mainwindow,
-            translate('OpenLP.ServiceManager', 'Open File'),
+            translate('Open File'),
             SettingsManager.get_last_dir(
             self.mainwindow.serviceSettingsSection),
-            translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz)')))
+            translate('OpenLP Service Files (*.osz)')))
         if not fileName:
             return False
         SettingsManager.set_last_dir(self.mainwindow.serviceSettingsSection,
@@ -423,8 +415,8 @@
 
     def saveModifiedService(self):
         return QtGui.QMessageBox.question(self.mainwindow,
-            translate('OpenLP.ServiceManager', 'Modified Service'),
-            translate('OpenLP.ServiceManager', 'The current service has '
+            translate('Modified Service'),
+            translate('The current service has '
             'been modified. Would you like to save this service?'),
             QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
             QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Save)
@@ -481,14 +473,14 @@
                 size_limit = 52428800 # 50MiB
                 #if file_size > size_limit:
                 #    # File exeeds size_limit bytes, ask user
-                #    message = unicode(translate('OpenLP.ServiceManager',
+                #    message = unicode(translate(
                 #        'Do you want to include \n%.1f MB file "%s"\n'
                 #        'into the service file?\nThis may take some time.\n\n'
                 #        'Please note that you need to\ntake care of that file'
                 #        ' yourself,\nif you leave it out.')) % \
                 #        (file_size/1048576, os.path.split(path_from)[1])
                 #    ans = QtGui.QMessageBox.question(self.mainwindow,
-                #        translate('OpenLP.ServiceManager', 'Including Large '
+                #        translate('Including Large '
                 #        'File'), message, QtGui.QMessageBox.StandardButtons(
                 #        QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel),
                 #        QtGui.QMessageBox.Ok)
@@ -539,7 +531,7 @@
             UiStrings().SaveService,
             SettingsManager.get_last_dir(
             self.mainwindow.serviceSettingsSection),
-            translate('OpenLP.ServiceManager', 'OpenLP Service Files (*.osz)')))
+            translate('OpenLP Service Files (*.osz)')))
         if not fileName:
             return False
         if os.path.splitext(fileName)[1] == u'':
@@ -564,9 +556,8 @@
                 ucsfile = file_is_unicode(file)
                 if not ucsfile:
                     critical_error_message_box(
-                        message=translate('OpenLP.ServiceManager',
-                        'File is not a valid service.\n'
-                        'The content encoding is not UTF-8.'))
+                        message=translate('File is not a valid service.\n'
+                            'The content encoding is not UTF-8.'))
                     continue
                 osfile = unicode(QtCore.QDir.toNativeSeparators(ucsfile))
                 filePath = os.path.join(self.servicePath,
@@ -603,27 +594,25 @@
                     'service/last file', QtCore.QVariant(fileName))
             else:
                 critical_error_message_box(
-                    message=translate('OpenLP.ServiceManager',
-                    'File is not a valid service.'))
+                    message=translate('File is not a valid service.'))
                 log.exception(u'File contains no service data')
         except (IOError, NameError, zipfile.BadZipfile):
             critical_error_message_box(
-                message=translate('OpenLP.ServiceManager',
-                'File could not be opened because it is corrupt.'))
+                message=translate('File could not be opened because it is corrupt.'))
             log.exception(u'Problem loading service file %s' % fileName)
         except zipfile.BadZipfile:
             if os.path.getsize(fileName) == 0:
                 log.exception(u'Service file is zero sized: %s' % fileName)
                 QtGui.QMessageBox.information(self,
-                    translate('OpenLP.ServiceManager', 'Empty File'),
-                    translate('OpenLP.ServiceManager', 'This service file '
+                    translate('Empty File'),
+                    translate('This service file '
                     'does not contain any data.'))
             else:
                 log.exception(u'Service file is cannot be extracted as zip: '
                     u'%s' % fileName)
                 QtGui.QMessageBox.information(self,
-                    translate('OpenLP.ServiceManager', 'Corrupt File'),
-                    translate('OpenLP.ServiceManager', 'This file is either '
+                    translate('Corrupt File'),
+                    translate('This file is either '
                     'corrupt or not an OpenLP 2.0 service file.'))
             return
         finally:
@@ -1124,8 +1113,8 @@
                 self.serviceItems[item][u'service_item'], child)
         else:
             critical_error_message_box(
-                translate('OpenLP.ServiceManager', 'Missing Display Handler'),
-                translate('OpenLP.ServiceManager', 'Your item cannot be '
+                translate('Missing Display Handler'),
+                translate('Your item cannot be '
                 'displayed as there is no handler to display it'))
 
     def getServiceItem(self):
@@ -1174,8 +1163,8 @@
                     self.mainwindow.liveController.previewListWidget.setFocus()
         else:
             critical_error_message_box(
-                translate('OpenLP.ServiceManager', 'Missing Display Handler'),
-                translate('OpenLP.ServiceManager', 'Your item cannot be '
+                translate('Missing Display Handler'),
+                translate('Your item cannot be '
                 'displayed as the plugin required to display it is missing '
                 'or inactive'))
 


Follow ups