PluginProjectKivy.py

Wed, 12 Jun 2013 20:05:16 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Wed, 12 Jun 2013 20:05:16 +0200
changeset 3
b7e3e3b131ea
parent 1
371cfb479eb6
child 11
a3a738778142
permissions
-rw-r--r--

Finished the Kivy project suupport plug-in.

# -*- coding: utf-8 -*-

# Copyright (c) 2013 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the Kivy project plug-in.
"""

import os
import glob
import fnmatch

from PyQt4.QtCore import QObject, QTranslator

from E5Gui.E5Application import e5App

import Preferences

from pygments.lexers._mapping import LEXERS

# Start-of-Header
name = "Kivy Project Plugin"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "1.0.0"
className = "ProjectKivyPlugin"
packageName = "ProjectKivy"
shortDescription = "Project support for Kivy projects."
longDescription = """This plugin implements project support for Kivy projects."""
needsRestart = False
pyqtApi = 2
# End-of-Header

error = ""


def apiFiles(language):
    """
    Module function to return the API files made available by this plugin.
    
    @return list of API filenames (list of string)
    """
    if language in ["Python2"]:
        apisDir = \
            os.path.join(os.path.dirname(__file__), "ProjectKivy", "APIs")
        apis = glob.glob(os.path.join(apisDir, '*.api'))
    else:
        apis = []
    return apis


class ProjectKivyPlugin(QObject):
    """
    Class implementing the Kivy project plugin.
    """
    lexerAssociations = {
        "*.kv": "Pygments|Kivy",
        "*.kivy": "Pygments|Kivy",
    }
    
    KivyLexerKey = 'KivyLexer'
    KivyLexerEntry = (
        'ProjectKivy.KivyLexer',
        'Kivy',
        ('kivy', 'kv'),
        ('*.kv', '*.kivy'),
        ('application/x-kivy',)
    )
    
    def __init__(self, ui):
        """
        Constructor
        
        @param ui reference to the user interface object (UI.UserInterface)
        """
        QObject.__init__(self, ui)
        self.__ui = ui
        self.__initialize()
        
        self.__translator = None
        self.__loadTranslator()
    
    def __initialize(self):
        """
        Private slot to (re)initialize the plugin.
        """
        self.__e5project = e5App().getObject("Project")
    
    def activate(self):
        """
        Public method to activate this plugin.
        
        @return tuple of None and activation status (boolean)
        """
        try:
            self.__e5project.registerProjectType("Kivy", self.trUtf8("Kivy"),
                self.fileTypesCallback,
                lexerAssociationCallback=self.lexerAssociationCallback,
                progLanguages=["Python2"])
        except TypeError:
            # for backward compatibility
            self.__e5project.registerProjectType("Kivy", self.trUtf8("Kivy"),
                self.fileTypesCallback,
                lexerAssociationCallback=self.lexerAssociationCallback)
        
        from Project.ProjectBrowser import SourcesBrowserFlag, FormsBrowserFlag, \
            TranslationsBrowserFlag, OthersBrowserFlag
        Preferences.setProjectBrowserFlagsDefault("Kivy",
            SourcesBrowserFlag | \
            FormsBrowserFlag | \
            TranslationsBrowserFlag | \
            OthersBrowserFlag,
        )
        
        LEXERS[self.KivyLexerKey] = self.KivyLexerEntry
        import QScintilla.Lexers
        if self.__ui.versionIsNewer('5.3.5', '20130611'):
            QScintilla.Lexers.registerLexer(
                "Kivy", 
                self.trUtf8("Kivy"), 
                "dummy.kv", 
                self.getLexer, 
                [self.trUtf8('Kivy Files (*.kv *.kivy)')],
                [self.trUtf8('Kivy Files (*.kv)')], 
                ['*.kv', '*.kivy']
            )
        else:
            # work around a bug in older versions
            QScintilla.Lexers.registerLexer(
                "Kivy", 
                self.trUtf8("Kivy"), 
                "dummy.kv", 
                self.getLexer, 
                self.trUtf8('Kivy Files (*.kv *.kivy)'),
                self.trUtf8('Kivy Files (*.kv)'),
                ['*.kv', '*.kivy']
            )
        
        return None, True
    
    def deactivate(self):
        """
        Public method to deactivate this plugin.
        """
        self.__e5project.unregisterProjectType("Kivy")
        
        import QScintilla.Lexers
        QScintilla.Lexers.unregisterLexer("Kivy")
        if self.KivyLexerKey in LEXERS:
            del LEXERS[self.KivyLexerKey]
        
        self.__initialize()
    
    def __loadTranslator(self):
        """
        Private method to load the translation file.
        """
        if self.__ui is not None:
            loc = self.__ui.getLocale()
            if loc and loc != "C":
                locale_dir = \
                    os.path.join(os.path.dirname(__file__), "ProjectKivy", "i18n")
                translation = "django_%s" % loc
                translator = QTranslator(None)
                loaded = translator.load(translation, locale_dir)
                if loaded:
                    self.__translator = translator
                    e5App().installTranslator(self.__translator)
                else:
                    print("Warning: translation file '{0}' could not be loaded.".format(
                        translation))
                    print("Using default.")
    
    def fileTypesCallback(self):
        """
        Public method get the filetype associations of the Kivy project type.
        
        @return dictionary with file type associations
        """
        if self.__e5project.getProjectType() == "Kivy":
            fileTypes = {
                "*.kv": "SOURCES",
                "*.kivy": "SOURCES",
                "*.py": "SOURCES",
            }
        else:
            fileTypes = {}
        return fileTypes
    
    def lexerAssociationCallback(self, filename):
        """
        Public method to get the lexer association of the Kivy project type for
        a file.
        
        @param filename name of the file (string)
        @return name of the lexer (string) (Pygments lexers are prefixed with 'Pygments|')
        """
        for pattern, language in self.lexerAssociations.items():
            if fnmatch.fnmatch(filename, pattern):
                return language
        
        return ""
    
    def getLexer(self, parent=None):
        """
        Public method to instantiate a Pygments Kivy lexer object.
        
        @param parent reference to the parent object (QObject)
        @return reference to the instanciated lexer object (QsciLexer)
        """
        from QScintilla.Lexers.LexerPygments import LexerPygments
        lexer = LexerPygments(parent, name="Kivy")
        if lexer.canStyle():
            return lexer
        else:
            return None

eric ide

mercurial