PluginPySide2PyQt.py

Fri, 01 Jan 2016 12:19:08 +0100

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Fri, 01 Jan 2016 12:19:08 +0100
changeset 38
a93172e31adb
parent 36
fa0e373b6c3c
child 39
7c28362ead81
permissions
-rw-r--r--

Updated copyright for 2016.

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

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

"""
Module implementing the PySide to PyQt (and vice versa) plug-in.
"""

from __future__ import unicode_literals

import os

from PyQt5.QtCore import QObject, QTranslator
from PyQt5.QtWidgets import QMenu

from E5Gui.E5Application import e5App

# Start-Of-Header
name = "PySide to PyQt (and vice versa) Plug-in"
author = "Detlev Offenbach <detlev@die-offenbachs.de>"
autoactivate = True
deactivateable = True
version = "2.1.0"
className = "PySide2PyQtPlugin"
packageName = "PySide2PyQt"
shortDescription = "Convert PySide file to PyQt and vice versa"
longDescription = \
    """This plug-in implements a tool to convert a PySide file""" \
    """ to PyQt4 or PyQt5 and vice versa. It works with the text of the""" \
    """ current editor."""
needsRestart = False
pyqtApi = 2
python2Compatible = True
# End-Of-Header

error = ""


class PySide2PyQtPlugin(QObject):
    """
    Class implementing the PySide to PyQt (and vice versa) plugin.
    """
    def __init__(self, ui):
        """
        Constructor
        
        @param ui reference to the user interface object (UI.UserInterface)
        """
        QObject.__init__(self, ui)
        self.__ui = ui
        
        self.__translator = None
        self.__loadTranslator()
        
        self.__initMenu()
        
        self.__editors = {}
        self.__mainActions = []
    
    def activate(self):
        """
        Public method to activate this plugin.
        
        @return tuple of None and activation status (boolean)
        """
        global error
        error = ""     # clear previous error
        
        self.__ui.showMenu.connect(self.__populateMenu)
        
        menu = self.__ui.getMenu("plugin_tools")
        if menu is not None:
            if not menu.isEmpty():
                act = menu.addSeparator()
                self.__mainActions.append(act)
            act = menu.addMenu(self.__menu)
            self.__mainActions.append(act)
        
        e5App().getObject("ViewManager").editorOpenedEd.connect(
            self.__editorOpened)
        e5App().getObject("ViewManager").editorClosedEd.connect(
            self.__editorClosed)
        
        for editor in e5App().getObject("ViewManager").getOpenEditors():
            self.__editorOpened(editor)
        
        return None, True
    
    def deactivate(self):
        """
        Public method to deactivate this plugin.
        """
        self.__ui.showMenu.disconnect(self.__populateMenu)
        
        menu = self.__ui.getMenu("plugin_tools")
        if menu is not None:
            for act in self.__mainActions:
                menu.removeAction(act)
        self.__mainActions = []

        e5App().getObject("ViewManager").editorOpenedEd.disconnect(
            self.__editorOpened)
        e5App().getObject("ViewManager").editorClosedEd.disconnect(
            self.__editorClosed)
        
        for editor, acts in self.__editors.items():
            editor.showMenu.disconnect(self.__editorShowMenu)
            menu = editor.getMenu("Tools")
            if menu is not None:
                for act in acts:
                    menu.removeAction(act)
        self.__editors = {}
    
    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__), "PySide2PyQt", "i18n")
                translation = "pyside2pyqt_{0}".format(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 __initMenu(self):
        """
        Private method to initialize the menu.
        """
        self.__menu = QMenu(self.tr("PySide to/from PyQt"))
        self.__menu.addAction(self.tr("PySide to PyQt4"), self.__pyside2Pyqt)\
            .setData("pyqt4")
        self.__menu.addAction(self.tr("PySide to PyQt5"), self.__pyside2Pyqt)\
            .setData("pyqt5")
        self.__menu.addAction(self.tr("PyQt4 to PySide"), self.__pyqt2Pyside)\
            .setData("pyqt4")
        self.__menu.addAction(self.tr("PyQt5 to PySide"), self.__pyqt2Pyside)\
            .setData("pyqt5")
        self.__menu.setEnabled(False)
    
    def __populateMenu(self, name, menu):
        """
        Private slot to populate the tools menu with our entries.
        
        @param name name of the menu (string)
        @param menu reference to the menu to be populated (QMenu)
        """
        if name not in ["Tools", "PluginTools"]:
            return
        
        editor = e5App().getObject("ViewManager").activeWindow()
        
        if name == "Tools":
            if not menu.isEmpty():
                menu.addSeparator()
            act = menu.addMenu(self.__menu)
            act.setEnabled(editor is not None)
        elif name == "PluginTools" and self.__mainActions:
            self.__mainActions[-1].setEnabled(editor is not None)
    
    def __editorOpened(self, editor):
        """
        Private slot called, when a new editor was opened.
        
        @param editor reference to the new editor (QScintilla.Editor)
        """
        menu = editor.getMenu("Tools")
        if menu is not None:
            self.__editors[editor] = []
            if not menu.isEmpty():
                act = menu.addSeparator()
                self.__editors[editor].append(act)
            act = menu.addMenu(self.__menu)
            self.__editors[editor].append(act)
            self.__menu.setEnabled(True)
            editor.showMenu.connect(self.__editorShowMenu)
    
    def __editorClosed(self, editor):
        """
        Private slot called, when an editor was closed.
        
        @param editor reference to the editor (QScintilla.Editor)
        """
        try:
            del self.__editors[editor]
            if not self.__editors:
                self.__menu.setEnabled(False)
        except KeyError:
            pass
    
    def __editorShowMenu(self, menuName, menu, editor):
        """
        Private slot called, when the the editor context menu or a submenu is
        about to be shown.
        
        @param menuName name of the menu to be shown (string)
        @param menu reference to the menu (QMenu)
        @param editor reference to the editor
        """
        if menuName == "Tools":
            if self.__menu.menuAction() not in menu.actions():
                # Re-add our menu
                self.__editors[editor] = []
                if not menu.isEmpty():
                    act = menu.addSeparator()
                    self.__editors[editor].append(act)
                act = menu.addMenu(self.__menu)
                self.__editors[editor].append(act)
    
    def __pyside2Pyqt(self):
        """
        Private slot to convert the code of the current editor from PySide
        to PyQt.
        """
        editor = e5App().getObject("ViewManager").activeWindow()
        if editor is None:
            return
        
        act = self.sender()
        if act is None:
            return
        
        text = editor.text()
        pyqt = act.data()
        if pyqt == "pyqt4":
            newText = (text
                       .replace("PySide", "PyQt4")
                       .replace("Signal", "pyqtSignal")
                       .replace("Slot", "pyqtSlot")
                       .replace("Property", "pyqtProperty")
                       .replace("pyside-uic", "pyuic4")
                       .replace("pyside-rcc", "pyrcc4")
                       .replace("pyside-lupdate", "pylupdate4")
                       )
        elif pyqt == "pyqt5":
            # Note: this code does no Qt4 to Qt5 conversion
            newText = (text
                       .replace("PySide", "PyQt5")
                       .replace("Signal", "pyqtSignal")
                       .replace("Slot", "pyqtSlot")
                       .replace("Property", "pyqtProperty")
                       .replace("pyside-uic", "pyuic5")
                       .replace("pyside-rcc", "pyrcc5")
                       .replace("pyside-lupdate", "pylupdate5")
                       )
        else:
            return
        
        if newText != text:
            editor.beginUndoAction()
            editor.selectAll()
            editor.replaceSelectedText(newText)
            editor.endUndoAction()
    
    def __pyqt2Pyside(self):
        """
        Private slot to convert the code of the current editor from PyQt
        to PySide.
        """
        editor = e5App().getObject("ViewManager").activeWindow()
        if editor is None:
            return
        
        act = self.sender()
        if act is None:
            return
        
        text = editor.text()
        pyqt = act.data()
        if pyqt == "pyqt4":
            newText = (text
                       .replace("PyQt4", "PySide")
                       .replace("pyqtSignal", "Signal")
                       .replace("pyqtSlot", "Slot")
                       .replace("pyqtProperty", "Property")
                       .replace("pyuic4", "pyside-uic")
                       .replace("pyrcc4", "pyside-rcc")
                       .replace("pylupdate4", "pyside-lupdate")
                       )
        elif pyqt == "pyqt5":
            # Note: this code does no Qt4 to Qt5 conversion
            newText = (text
                       .replace("PyQt5", "PySide")
                       .replace("pyqtSignal", "Signal")
                       .replace("pyqtSlot", "Slot")
                       .replace("pyqtProperty", "Property")
                       .replace("pyuic5", "pyside-uic")
                       .replace("pyrcc5", "pyside-rcc")
                       .replace("pylupdate5", "pyside-lupdate")
                       )
        else:
            return
        
        if newText != text:
            editor.beginUndoAction()
            editor.selectAll()
            editor.replaceSelectedText(newText)
            editor.endUndoAction()

eric ide

mercurial