trac-macos / tracmacos / prefs.py

Olemis Lang 5fdb7ad 

















































































































































# Copyright (c) 2010 Olemis Lang. All rights reserved.
#
# 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; either version 2 of the License, or
# (at your option) any later version.
# 
# 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

from trac.core import *
from trac.config import Option, IntOption, ListOption
from trac.env import IEnvironmentSetupParticipant
from trac.util.translation import _
from trac.prefs.api import IPreferencePanelProvider
from trac.web.chrome import add_script, add_stylesheet, ITemplateProvider

from pkg_resources import resource_filename, resource_string
from os.path import dirname, exists, join

from themeengine.api import ThemeEngineSystem

NAME_THEME_PREFS = 'theme'
NAME_THEME_SYSTEM = '*'

class ThemePreferencesPanel(Component):
    """Per-user theme settings."""
    implements(IPreferencePanelProvider, IEnvironmentSetupParticipant,
            ITemplateProvider)

    def __init__(self):
        self.system = ThemeEngineSystem(self.env)

    # ITemplateProvider methods
    def get_htdocs_dirs(self):
        for theme in self.system.info.itervalues() :
            if 'htdocs' in theme:
                ns = 'theme_' + theme['name'] 
                path = resource_filename(theme['module'], theme['htdocs'])
                yield ns, path

    def get_templates_dirs(self):
        for theme in self.system.info.itervalues() :
            if 'template' in theme:
                yield resource_filename(theme['module'], 
                        dirname(theme['template']))

    # IPreferencePanelProvider methods
    def get_preference_panels(self, req):
        """Return a list of available preference panels.
        
        @return     `('theme', 'Theme settings for <username>')`.
        """
        username = req.authname or 'anonymous'
        yield 'theme', _('Theme settings for ') + username

    def render_preference_panel(self, req, panel):
        """Process a request for a preference panel.
        """
        if req.method == 'POST':
            req.args['action'] = 'save'
            theme_name = req.args['theme']
            if theme_name == NAME_THEME_SYSTEM :
                del req.session[NAME_THEME_PREFS]
            else :
                req.session[NAME_THEME_PREFS] = theme_name
            req.redirect(req.href.prefs(panel)) 

        theme_info = self.system.info.items()
        theme_name = req.session.get(NAME_THEME_PREFS) or \
                self.system.theme_name or 'Default'
        data = {
            'themeengine' : {
                'info' : theme_info,
                'current' : theme_name,
            }
        }
        index = 0
        curtheme = None
        for i, (k, v) in enumerate(data['themeengine']['info']):
            if k == theme_name:
                index = i
                curtheme = v
                break
        data['themeengine']['current_index'] = index
        data['themeengine']['current_theme'] = curtheme

        system_theme = curtheme.copy()
        system_theme['name'] = NAME_THEME_SYSTEM
        system_theme['description'] = "Use theme for this site"
        theme_info.append((NAME_THEME_SYSTEM, system_theme))

        add_stylesheet(req, 'themeengine/admin.css')
        add_script(req, 'themeengine/jcarousellite_1.0.1.js')

        return 'prefs_theme.html', data

    # IEnvironmentSetupParticipant methods
    def environment_created():
        """Create theme preferences template."""
        self._clone_template()

    def environment_needs_upgrade(self, db):
        """Environment never needs upgrade. Nonetheless ensure 
        preferences panel template is already created.
        """
        if not exists(join(self.env.path, 'templates', 'prefs_theme.html')):
            self._clone_template()
        return False

    def upgrade_environment(self, db):
        """Environment never needs upgrade.
        """

    # Internal methods
    def _clone_template(self):
        r"""Copy theme admin template to the environment's templates 
        directory and update it to display preferences.
        """
        template_contents = resource_string('themeengine', \
                'templates/admin_theme.html')
        template_path = join(self.env.path, 'templates', 'prefs_theme.html')
        self.log.info('Creating theme prefs template at ' + template_path)
        try:
            f = open(template_path, 'wb')
            try:
                f.write(template_contents.replace(
                            '<xi:include href="admin.html" />',
                            '<xi:include href="prefs.html" />')
                        .replace(
                            '<form method="post">',
                            '')
                        .replace(
                            '</form>',
                            '')
                    )
            finally:
                f.close()
        except IOError, exc :
            raise TracError(str(exc), 'Trac setup error')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.