ExtensionCorba/ProjectInterfacesBrowser.py

Sat, 26 Oct 2024 16:45:57 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Sat, 26 Oct 2024 16:45:57 +0200
changeset 54
9e2b1adf8cd1
parent 53
d70c2a05a494
child 55
2f709d7a4a49
permissions
-rw-r--r--

Made proper parent relationship of modal dialogs clearer.

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

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

"""
Module implementing the a class used to display the interfaces (IDL) part
of the project.
"""

import contextlib
import glob
import os

from PyQt6.QtCore import QProcess, QThread, pyqtSignal
from PyQt6.QtWidgets import QApplication, QDialog, QMenu

from eric7 import Preferences
from eric7.EricGui import EricPixmapCache
from eric7.EricWidgets import EricMessageBox, EricPathPickerDialog
from eric7.EricWidgets.EricApplication import ericApp
from eric7.EricWidgets.EricPathPickerDialog import EricPathPickerModes
from eric7.EricWidgets.EricProgressDialog import EricProgressDialog
from eric7.Project.FileCategoryRepositoryItem import FileCategoryRepositoryItem
from eric7.Project.ProjectBaseBrowser import ProjectBaseBrowser
from eric7.Project.ProjectBrowserModel import (
    ProjectBrowserDirectoryItem,
    ProjectBrowserFileItem,
    ProjectBrowserSimpleDirectoryItem,
)
from eric7.Project.ProjectBrowserRepositoryItem import ProjectBrowserRepositoryItem
from eric7.SystemUtilities import FileSystemUtilities, OSUtilities
from eric7.UI.BrowserModel import (
    BrowserClassAttributeItem,
    BrowserClassItem,
    BrowserFileItem,
    BrowserMethodItem,
)
from eric7.UI.DeleteFilesConfirmationDialog import DeleteFilesConfirmationDialog
from eric7.UI.NotificationWidget import NotificationTypes


class ProjectInterfacesBrowser(ProjectBaseBrowser):
    """
    A class used to display the interfaces (IDL) part of the project.

    @signal appendStdout(str) emitted after something was received from
        a QProcess on stdout
    @signal appendStderr(str) emitted after something was received from
        a QProcess on stderr
    @signal showMenu(str, QMenu) emitted when a menu is about to be shown.
        The name of the menu and a reference to the menu are given.
    """

    appendStdout = pyqtSignal(str)
    appendStderr = pyqtSignal(str)
    showMenu = pyqtSignal(str, QMenu)

    FileFilter = "idl"

    def __init__(self, plugin, parent=None):
        """
        Constructor

        @param plugin reference to the plugin object
        @type CorbaExtensionPlugin
        @param parent parent widget of this browser
        @type QWidget
        """
        project = ericApp().getObject("Project")
        projectBrowser = ericApp().getObject("ProjectBrowser")

        self.omniidl = plugin.getPreferences("omniidl")
        if self.omniidl == "":
            self.omniidl = (
                "omniidl.exe" if OSUtilities.isWindowsPlatform() else "omniidl"
            )
        if not FileSystemUtilities.isinpath(self.omniidl):
            self.omniidl = None

        ProjectBaseBrowser.__init__(self, project, self.FileFilter, parent)

        self.selectedItemsFilter = [
            ProjectBrowserFileItem,
            ProjectBrowserSimpleDirectoryItem,
        ]

        self.setWindowTitle(self.tr("CORBA IDL"))

        self.setWhatsThis(
            self.tr(
                """<b>Project IDL Browser</b>"""
                """<p>This allows to easily see all CORBA IDL files contained in the"""
                """ current project. Several actions can be executed via the context"""
                """ menu.</p>"""
            )
        )

        # Add the file category handled by the browser.
        project.addFileCategory(
            "INTERFACES",
            FileCategoryRepositoryItem(
                fileCategoryFilterTemplate=self.tr("CORBA IDL Files ({0})"),
                fileCategoryUserString=self.tr("CORBA  IDL Files"),
                fileCategoryTyeString=self.tr("IDL Files"),
                fileCategoryExtensions=["*.idl"],
            ),
        )

        # Add the project browser type to the browser type repository.
        projectBrowser.addTypedProjectBrowser(
            "interfaces",
            ProjectBrowserRepositoryItem(
                projectBrowser=self,
                projectBrowserUserString=self.tr("CORBA IDL Browser"),
                priority=50,
                fileCategory="INTERFACES",
                fileFilter=self.FileFilter,
                getIcon=self.getIcon,
            ),
        )

        # Connect signals of Project.
        project.prepareRepopulateItem.connect(self._prepareRepopulateItem)
        project.completeRepopulateItem.connect(self._completeRepopulateItem)
        project.projectClosed.connect(self._projectClosed)
        project.projectOpened.connect(self._projectOpened)
        project.newProject.connect(self._newProject)
        project.reinitVCS.connect(self._initMenusAndVcs)
        project.projectPropertiesChanged.connect(self._initMenusAndVcs)

        # Connect signals of ProjectBrowser.
        projectBrowser.preferencesChanged.connect(self.handlePreferencesChanged)

        # Connect some of our own signals.
        self.appendStderr.connect(projectBrowser.appendStderr)
        self.appendStdout.connect(projectBrowser.appendStdout)
        self.closeSourceWindow.connect(projectBrowser.closeSourceWindow)
        self.sourceFile[str].connect(projectBrowser.sourceFile[str])
        self.sourceFile[str, int].connect(projectBrowser.sourceFile[str, int])

    def deactivate(self):
        """
        Public method to deactivate the browser.
        """
        project = ericApp().getObject("Project")
        projectBrowser = ericApp().getObject("ProjectBrowser")

        # Disconnect some of our own signals.
        self.appendStderr.disconnect(projectBrowser.appendStderr)
        self.appendStdout.disconnect(projectBrowser.appendStdout)
        self.closeSourceWindow.disconnect(projectBrowser.closeSourceWindow)
        self.sourceFile[str].disconnect(projectBrowser.sourceFile[str])
        self.sourceFile[str, int].disconnect(projectBrowser.sourceFile[str, int])

        # Disconnect signals of ProjectBrowser.
        projectBrowser.preferencesChanged.disconnect(self.handlePreferencesChanged)

        # Disconnect signals of Project.
        project.prepareRepopulateItem.disconnect(self._prepareRepopulateItem)
        project.completeRepopulateItem.disconnect(self._completeRepopulateItem)
        project.projectClosed.disconnect(self._projectClosed)
        project.projectOpened.disconnect(self._projectOpened)
        project.newProject.disconnect(self._newProject)
        project.reinitVCS.disconnect(self._initMenusAndVcs)
        project.projectPropertiesChanged.disconnect(self._initMenusAndVcs)

        # Remove the project browser type from the browser type repository.
        projectBrowser.removeTypedProjectBrowser("interfaces")

        # Remove the file category handled by the browser.
        project.removeFileCategory("INTERFACES")

    def getIcon(self):
        """
        Public method to get an icon for the project browser.

        @return icon for the browser
        @rtype QIcon
        """
        iconSuffix = "dark" if ericApp().usesDarkPalette() else "light"

        return EricPixmapCache.getIcon(
            os.path.join(
                os.path.dirname(__file__), "icons", "corba-{0}".format(iconSuffix)
            )
        )

    def _createPopupMenus(self):
        """
        Protected overloaded method to generate the popup menu.
        """
        self.menuActions = []
        self.multiMenuActions = []
        self.dirMenuActions = []
        self.dirMultiMenuActions = []

        self.sourceMenu = QMenu(self)
        if self.omniidl is not None:
            self.sourceMenu.addAction(
                self.tr("Compile interface"), self.__compileInterface
            )
            self.sourceMenu.addAction(
                self.tr("Compile all interfaces"), self.__compileAllInterfaces
            )
            self.sourceMenu.addSeparator()
            self.sourceMenu.addAction(
                self.tr("Configure IDL compiler"), self.__configureIdlCompiler
            )
            self.sourceMenu.addSeparator()
        self.sourceMenu.addAction(self.tr("Open"), self._openItem)
        self.sourceMenu.addSeparator()
        act = self.sourceMenu.addAction(self.tr("Rename file"), self._renameFile)
        self.menuActions.append(act)
        act = self.sourceMenu.addAction(
            self.tr("Remove from project"), self._removeFile
        )
        self.menuActions.append(act)
        act = self.sourceMenu.addAction(self.tr("Delete"), self.__deleteFile)
        self.menuActions.append(act)
        self.sourceMenu.addSeparator()
        self.sourceMenu.addAction(
            self.tr("New interface file..."), self.__addNewInterfaceFile
        )
        self.sourceMenu.addSeparator()
        self.sourceMenu.addAction(
            self.tr("Add interfaces..."), self.__addInterfaceFiles
        )
        self.sourceMenu.addAction(
            self.tr("Add interfaces directory..."), self.__addInterfacesDirectory
        )
        self.sourceMenu.addSeparator()
        with contextlib.suppress(AttributeError):
            # eric7 > 23.12
            self.sourceMenu.addAction(
                self.tr("Show in File Manager"), self._showInFileManager
            )
        self.sourceMenu.addAction(
            self.tr("Copy Path to Clipboard"), self._copyToClipboard
        )
        self.sourceMenu.addSeparator()
        self.sourceMenu.addAction(
            self.tr("Expand all directories"), self._expandAllDirs
        )
        self.sourceMenu.addAction(
            self.tr("Collapse all directories"), self._collapseAllDirs
        )
        self.sourceMenu.addAction(self.tr("Collapse all files"), self._collapseAllFiles)
        self.sourceMenu.addSeparator()
        self.sourceMenu.addAction(self.tr("Configure..."), self._configure)
        self.sourceMenu.addAction(self.tr("Configure CORBA..."), self.__configureCorba)

        self.menu = QMenu(self)
        if self.omniidl is not None:
            self.menu.addAction(self.tr("Compile interface"), self.__compileInterface)
            self.menu.addAction(
                self.tr("Compile all interfaces"), self.__compileAllInterfaces
            )
            self.menu.addSeparator()
            self.menu.addAction(
                self.tr("Configure IDL compiler"), self.__configureIdlCompiler
            )
            self.menu.addSeparator()
        self.menu.addAction(self.tr("Open"), self._openItem)
        self.menu.addSeparator()
        self.menu.addAction(
            self.tr("New interface file..."), self.__addNewInterfaceFile
        )
        self.menu.addSeparator()
        self.menu.addAction(self.tr("Add interfaces..."), self.__addInterfaceFiles)
        self.menu.addAction(
            self.tr("Add interfaces directory..."), self.__addInterfacesDirectory
        )
        self.menu.addSeparator()
        with contextlib.suppress(AttributeError):
            # eric7 > 23.12
            self.menu.addAction(
                self.tr("Show in File Manager"), self._showInFileManager
            )
            self.menu.addSeparator()
        self.menu.addAction(self.tr("Expand all directories"), self._expandAllDirs)
        self.menu.addAction(self.tr("Collapse all directories"), self._collapseAllDirs)
        self.menu.addAction(self.tr("Collapse all files"), self._collapseAllFiles)
        self.menu.addSeparator()
        self.menu.addAction(self.tr("Configure..."), self._configure)
        self.menu.addAction(self.tr("Configure CORBA..."), self.__configureCorba)

        self.backMenu = QMenu(self)
        if self.omniidl is not None:
            self.backMenu.addAction(
                self.tr("Compile all interfaces"), self.__compileAllInterfaces
            )
            self.backMenu.addSeparator()
            self.backMenu.addAction(
                self.tr("Configure IDL compiler"), self.__configureIdlCompiler
            )
            self.backMenu.addSeparator()
        self.backMenu.addAction(
            self.tr("New interface file..."), self.__addNewInterfaceFile
        )
        self.backMenu.addSeparator()
        self.backMenu.addAction(
            self.tr("Add interfaces..."), lambda: self.project.addFiles("INTERFACES")
        )
        self.backMenu.addAction(
            self.tr("Add interfaces directory..."),
            lambda: self.project.addDirectory("INTERFACES"),
        )
        self.backMenu.addSeparator()
        with contextlib.suppress(AttributeError):
            # eric7 > 23.12
            self.backMenu.addAction(
                self.tr("Show in File Manager"), self._showProjectInFileManager
            )
            self.backMenu.addSeparator()
        self.backMenu.addAction(self.tr("Expand all directories"), self._expandAllDirs)
        self.backMenu.addAction(
            self.tr("Collapse all directories"), self._collapseAllDirs
        )
        self.backMenu.addAction(self.tr("Collapse all files"), self._collapseAllFiles)
        self.backMenu.addSeparator()
        self.backMenu.addAction(self.tr("Configure..."), self._configure)
        self.backMenu.addAction(self.tr("Configure CORBA..."), self.__configureCorba)
        self.backMenu.setEnabled(False)

        # create the menu for multiple selected files
        self.multiMenu = QMenu(self)
        if self.omniidl is not None:
            self.multiMenu.addAction(
                self.tr("Compile interfaces"), self.__compileSelectedInterfaces
            )
            self.multiMenu.addSeparator()
            self.multiMenu.addAction(
                self.tr("Configure IDL compiler"), self.__configureIdlCompiler
            )
            self.multiMenu.addSeparator()
        self.multiMenu.addAction(self.tr("Open"), self._openItem)
        self.multiMenu.addSeparator()
        act = self.multiMenu.addAction(self.tr("Remove from project"), self._removeFile)
        self.multiMenuActions.append(act)
        act = self.multiMenu.addAction(self.tr("Delete"), self.__deleteFile)
        self.multiMenuActions.append(act)
        self.multiMenu.addSeparator()
        self.multiMenu.addAction(self.tr("Expand all directories"), self._expandAllDirs)
        self.multiMenu.addAction(
            self.tr("Collapse all directories"), self._collapseAllDirs
        )
        self.multiMenu.addAction(self.tr("Collapse all files"), self._collapseAllFiles)
        self.multiMenu.addSeparator()
        self.multiMenu.addAction(self.tr("Configure..."), self._configure)
        self.multiMenu.addAction(self.tr("Configure CORBA..."), self.__configureCorba)

        self.dirMenu = QMenu(self)
        if self.omniidl is not None:
            self.dirMenu.addAction(
                self.tr("Compile all interfaces"), self.__compileAllInterfaces
            )
            self.dirMenu.addSeparator()
            self.dirMenu.addAction(
                self.tr("Configure IDL compiler"), self.__configureIdlCompiler
            )
            self.dirMenu.addSeparator()
        act = self.dirMenu.addAction(self.tr("Remove from project"), self._removeFile)
        self.dirMenuActions.append(act)
        act = self.dirMenu.addAction(self.tr("Delete"), self._deleteDirectory)
        self.dirMenuActions.append(act)
        self.dirMenu.addSeparator()
        self.dirMenu.addAction(
            self.tr("New interface file..."), self.__addNewInterfaceFile
        )
        self.dirMenu.addSeparator()
        self.dirMenu.addAction(self.tr("Add interfaces..."), self.__addInterfaceFiles)
        self.dirMenu.addAction(
            self.tr("Add interfaces directory..."), self.__addInterfacesDirectory
        )
        self.dirMenu.addSeparator()
        with contextlib.suppress(AttributeError):
            # eric7 > 23.12
            self.dirMenu.addAction(
                self.tr("Show in File Manager"), self._showInFileManager
            )
        self.dirMenu.addAction(self.tr("Copy Path to Clipboard"), self._copyToClipboard)
        self.dirMenu.addSeparator()
        self.dirMenu.addAction(self.tr("Expand all directories"), self._expandAllDirs)
        self.dirMenu.addAction(
            self.tr("Collapse all directories"), self._collapseAllDirs
        )
        self.dirMenu.addAction(self.tr("Collapse all files"), self._collapseAllFiles)
        self.dirMenu.addSeparator()
        self.dirMenu.addAction(self.tr("Configure..."), self._configure)
        self.dirMenu.addAction(self.tr("Configure CORBA..."), self.__configureCorba)

        self.dirMultiMenu = QMenu(self)
        if self.omniidl is not None:
            self.dirMultiMenu.addAction(
                self.tr("Compile all interfaces"), self.__compileAllInterfaces
            )
            self.dirMultiMenu.addSeparator()
            self.dirMultiMenu.addAction(
                self.tr("Configure IDL compiler"), self.__configureIdlCompiler
            )
            self.dirMultiMenu.addSeparator()
        self.dirMultiMenu.addAction(
            self.tr("Add interfaces..."), lambda: self.project.addFiles("INTERFACES")
        )
        self.dirMultiMenu.addAction(
            self.tr("Add interfaces directory..."),
            lambda: self.project.addDirectory("INTERFACES"),
        )
        self.dirMultiMenu.addSeparator()
        self.dirMultiMenu.addAction(
            self.tr("Expand all directories"), self._expandAllDirs
        )
        self.dirMultiMenu.addAction(
            self.tr("Collapse all directories"), self._collapseAllDirs
        )
        self.dirMultiMenu.addAction(
            self.tr("Collapse all files"), self._collapseAllFiles
        )
        self.dirMultiMenu.addSeparator()
        self.dirMultiMenu.addAction(self.tr("Configure..."), self._configure)
        self.dirMultiMenu.addAction(
            self.tr("Configure CORBA..."), self.__configureCorba
        )

        self.sourceMenu.aboutToShow.connect(self.__showContextMenu)
        self.multiMenu.aboutToShow.connect(self.__showContextMenuMulti)
        self.dirMenu.aboutToShow.connect(self.__showContextMenuDir)
        self.dirMultiMenu.aboutToShow.connect(self.__showContextMenuDirMulti)
        self.backMenu.aboutToShow.connect(self.__showContextMenuBack)
        self.mainMenu = self.sourceMenu

    def _contextMenuRequested(self, coord):
        """
        Protected slot to show the context menu.

        @param coord the position of the mouse pointer
        @type QPoint
        """
        if not self.project.isOpen():
            return

        with contextlib.suppress(Exception):  # secok
            categories = self.getSelectedItemsCountCategorized(
                [
                    ProjectBrowserFileItem,
                    BrowserClassItem,
                    BrowserMethodItem,
                    ProjectBrowserSimpleDirectoryItem,
                ]
            )
            cnt = categories["sum"]
            if cnt <= 1:
                index = self.indexAt(coord)
                if index.isValid():
                    self._selectSingleItem(index)
                    categories = self.getSelectedItemsCountCategorized(
                        [
                            ProjectBrowserFileItem,
                            BrowserClassItem,
                            BrowserMethodItem,
                            ProjectBrowserSimpleDirectoryItem,
                        ]
                    )
                    cnt = categories["sum"]

            bfcnt = categories[str(ProjectBrowserFileItem)]
            cmcnt = (
                categories[str(BrowserClassItem)] + categories[str(BrowserMethodItem)]
            )
            sdcnt = categories[str(ProjectBrowserSimpleDirectoryItem)]
            if cnt > 1 and cnt == bfcnt:
                self.multiMenu.popup(self.mapToGlobal(coord))
            elif cnt > 1 and cnt == sdcnt:
                self.dirMultiMenu.popup(self.mapToGlobal(coord))
            else:
                index = self.indexAt(coord)
                if cnt == 1 and index.isValid():
                    if bfcnt == 1 or cmcnt == 1:
                        itm = self.model().item(index)
                        if isinstance(itm, ProjectBrowserFileItem):
                            self.sourceMenu.popup(self.mapToGlobal(coord))
                        elif isinstance(itm, (BrowserClassItem, BrowserMethodItem)):
                            self.menu.popup(self.mapToGlobal(coord))
                        else:
                            self.backMenu.popup(self.mapToGlobal(coord))
                    elif sdcnt == 1:
                        self.dirMenu.popup(self.mapToGlobal(coord))
                    else:
                        self.backMenu.popup(self.mapToGlobal(coord))
                else:
                    self.backMenu.popup(self.mapToGlobal(coord))

    def __showContextMenu(self):
        """
        Private slot called by the menu aboutToShow signal.
        """
        ProjectBaseBrowser._showContextMenu(self, self.menu)

        self.showMenu.emit("Main", self.menu)

    def __showContextMenuMulti(self):
        """
        Private slot called by the multiMenu aboutToShow signal.
        """
        ProjectBaseBrowser._showContextMenuMulti(self, self.multiMenu)

        self.showMenu.emit("MainMulti", self.multiMenu)

    def __showContextMenuDir(self):
        """
        Private slot called by the dirMenu aboutToShow signal.
        """
        ProjectBaseBrowser._showContextMenuDir(self, self.dirMenu)

        self.showMenu.emit("MainDir", self.dirMenu)

    def __showContextMenuDirMulti(self):
        """
        Private slot called by the dirMultiMenu aboutToShow signal.
        """
        ProjectBaseBrowser._showContextMenuDirMulti(self, self.dirMultiMenu)

        self.showMenu.emit("MainDirMulti", self.dirMultiMenu)

    def __showContextMenuBack(self):
        """
        Private slot called by the backMenu aboutToShow signal.
        """
        ProjectBaseBrowser._showContextMenuBack(self, self.backMenu)

        self.showMenu.emit("MainBack", self.backMenu)

    def _openItem(self):
        """
        Protected slot to handle the open popup menu entry.
        """
        itmList = self.getSelectedItems(
            [
                BrowserFileItem,
                BrowserClassItem,
                BrowserMethodItem,
                BrowserClassAttributeItem,
            ]
        )

        for itm in itmList:
            if isinstance(itm, BrowserFileItem):
                self.sourceFile[str].emit(itm.fileName())
            elif isinstance(itm, BrowserClassItem):
                self.sourceFile[str, int].emit(itm.fileName(), itm.classObject().lineno)
            elif isinstance(itm, BrowserMethodItem):
                self.sourceFile[str, int].emit(
                    itm.fileName(), itm.functionObject().lineno
                )
            elif isinstance(itm, BrowserClassAttributeItem):
                self.sourceFile[str, int].emit(
                    itm.fileName(), itm.attributeObject().lineno
                )

    def __addNewInterfaceFile(self):
        """
        Private method to add a new interface file to the project.
        """
        itm = self.model().item(self.currentIndex())
        if isinstance(
            itm, (ProjectBrowserFileItem, BrowserClassItem, BrowserMethodItem)
        ):
            dn = os.path.dirname(itm.fileName())
        elif isinstance(
            itm, (ProjectBrowserSimpleDirectoryItem, ProjectBrowserDirectoryItem)
        ):
            dn = itm.dirName()
        else:
            dn = ""

        filename, ok = EricPathPickerDialog.getStrPath(
            self,
            self.tr("New interface file"),
            self.tr("Enter the path of the new interface file:"),
            mode=EricPathPickerModes.SAVE_FILE_ENSURE_EXTENSION_MODE,
            strPath=dn,
            defaultDirectory=dn,
            filters=self.project.getFileCategoryFilters(
                categories=["INTERFACES"], withAll=False
            ),
        )
        if ok:
            if not os.path.splitext(filename)[1]:
                filename += ".idl"

            if os.path.exists(filename):
                EricMessageBox.critical(
                    self,
                    self.tr("New interface file"),
                    self.tr(
                        "<p>The file <b>{0}</b> already exists. The action will be"
                        " aborted.</p>"
                    ).format(filename),
                )
                return

            try:
                with open(filename, "w") as f:
                    f.write("// {0}\n".format(self.project.getRelativePath(filename)))
            except OSError as err:
                EricMessageBox.critical(
                    self,
                    self.tr("New interface file"),
                    self.tr(
                        "<p>The file <b>{0}</b> could not be created. Aborting...</p>"
                        "<p>Reason: {1}</p>"
                    ).format(filename, str(err)),
                )
                return

            self.project.appendFile(filename)
            self.sourceFile[str].emit(filename)

    def __addInterfaceFiles(self):
        """
        Private method to add interface files to the project.
        """
        itm = self.model().item(self.currentIndex())
        if isinstance(
            itm, (ProjectBrowserFileItem, BrowserClassItem, BrowserMethodItem)
        ):
            dn = os.path.dirname(itm.fileName())
        elif isinstance(
            itm, (ProjectBrowserSimpleDirectoryItem, ProjectBrowserDirectoryItem)
        ):
            dn = itm.dirName()
        else:
            dn = None
        self.project.addFiles("INTERFACES", dn)

    def __addInterfacesDirectory(self):
        """
        Private method to add interface files of a directory to the project.
        """
        itm = self.model().item(self.currentIndex())
        if isinstance(
            itm, (ProjectBrowserFileItem, BrowserClassItem, BrowserMethodItem)
        ):
            dn = os.path.dirname(itm.fileName())
        elif isinstance(
            itm, (ProjectBrowserSimpleDirectoryItem, ProjectBrowserDirectoryItem)
        ):
            dn = itm.dirName()
        else:
            dn = None
        self.project.addDirectory("INTERFACES", dn)

    def __deleteFile(self):
        """
        Private method to delete files from the project.
        """
        itmList = self.getSelectedItems()

        files = []
        fullNames = []
        for itm in itmList:
            fn2 = itm.fileName()
            fullNames.append(fn2)
            fn = self.project.getRelativePath(fn2)
            files.append(fn)

        dlg = DeleteFilesConfirmationDialog(
            self.parent(),
            self.tr("Delete interfaces"),
            self.tr(
                "Do you really want to delete these interfaces from the project?"
            ),
            files,
        )

        if dlg.exec() == QDialog.DialogCode.Accepted:
            for fn2, fn in zip(fullNames, files):
                self.closeSourceWindow.emit(fn2)
                self.project.deleteFile(fn)

    ###########################################################################
    ##  Methods to handle the various compile commands
    ###########################################################################

    def __readStdout(self):
        """
        Private slot to handle the readyReadStandardOutput signal of the
        omniidl process.
        """
        if self.compileProc is None:
            return

        ioEncoding = Preferences.getSystem("IOEncoding")

        self.compileProc.setReadChannel(QProcess.ProcessChannel.StandardOutput)
        while self.compileProc and self.compileProc.canReadLine():
            s = "omniidl: "
            output = str(self.compileProc.readLine(), ioEncoding, "replace")
            s += output
            self.appendStdout.emit(s)

    def __readStderr(self):
        """
        Private slot to handle the readyReadStandardError signal of the
        omniidl process.
        """
        if self.compileProc is None:
            return

        ioEncoding = Preferences.getSystem("IOEncoding")

        self.compileProc.setReadChannel(QProcess.ProcessChannel.StandardError)
        while self.compileProc and self.compileProc.canReadLine():
            s = "omniidl: "
            error = str(self.compileProc.readLine(), ioEncoding, "replace")
            s += error
            self.appendStderr.emit(s)

    def __compileIDLDone(self, exitCode, exitStatus):
        """
        Private slot to handle the finished signal of the omniidl process.

        @param exitCode exit code of the process
        @type int
        @param exitStatus exit status of the process
        @type QProcess.ExitStatus
        """
        pixmapSuffix = "dark" if ericApp().usesDarkPalette() else "light"
        pixmap = EricPixmapCache.getPixmap(
            os.path.join(
                os.path.dirname(__file__),
                "icons",
                "corba48-{0}".format(pixmapSuffix),
            )
        )

        self.compileRunning = False
        ui = ericApp().getObject("UserInterface")
        if exitStatus == QProcess.ExitStatus.NormalExit and exitCode == 0:
            path = os.path.dirname(self.idlFile)
            poaList = glob.glob(os.path.join(path, "*__POA"))
            npoaList = [f.replace("__POA", "") for f in poaList]
            fileList = glob.glob(os.path.join(path, "*_idl.py"))
            for directory in poaList + npoaList:
                fileList += FileSystemUtilities.direntries(directory, True, "*.py")
            for file in fileList:
                self.project.appendFile(file)
            ui.showNotification(
                pixmap,
                self.tr("Interface Compilation"),
                self.tr("The compilation of the interface file was successful."),
            )
        else:
            ui.showNotification(
                pixmap,
                self.tr("Interface Compilation"),
                self.tr("The compilation of the interface file failed."),
                kind=NotificationTypes.CRITICAL,
                timeout=0,
            )
        self.compileProc = None

    def __compileIDL(self, fn, noDialog=False, progress=None):
        """
        Private method to compile a .idl file to python.

        @param fn filename of the .idl file to be compiled
        @type str
        @param noDialog flag indicating silent operations
        @type bool
        @param progress reference to the progress dialog
        @type EricProgressDialog
        @return reference to the compile process
        @rtype QProcess
        """
        params = self.project.getProjectData(dataKey="IDLPARAMS")

        self.compileProc = QProcess()
        args = []

        args.append("-bpython")
        args.append("-I.")
        for directory in params["IncludeDirs"]:
            args.append(
                "-I{0}".format(self.project.getAbsoluteUniversalPath(directory))
            )
        for name in params["DefinedNames"]:
            args.append("-D{0}".format(name))
        for name in params["UndefinedNames"]:
            args.append("-U{0}".format(name))

        fn = self.project.getAbsoluteUniversalPath(fn)
        self.idlFile = fn
        args.append("-C{0}".format(os.path.dirname(fn)))
        args.append(fn)

        self.compileProc.finished.connect(self.__compileIDLDone)
        self.compileProc.readyReadStandardOutput.connect(self.__readStdout)
        self.compileProc.readyReadStandardError.connect(self.__readStderr)

        self.noDialog = noDialog
        self.compileProc.start(self.omniidl, args)
        procStarted = self.compileProc.waitForStarted(5000)
        if procStarted:
            self.compileRunning = True
            return self.compileProc
        else:
            self.compileRunning = False
            if progress is not None:
                progress.cancel()
            EricMessageBox.critical(
                self,
                self.tr("Process Generation Error"),
                self.tr(
                    "<p>Could not start {0}.<br>"
                    "Ensure that it is in the search path.</p>"
                ).format(self.omniidl),
            )
            return None

    def __compileInterface(self):
        """
        Private method to compile an interface to python.
        """
        if self.omniidl is not None:
            itm = self.model().item(self.currentIndex())
            fn2 = itm.fileName()
            fn = self.project.getRelativePath(fn2)
            self.__compileIDL(fn)

    def __compileAllInterfaces(self):
        """
        Private method to compile all interfaces to python.
        """
        if self.omniidl is not None:
            numIDLs = len(self.project.getProjectData(dataKey="INTERFACES"))
            progress = EricProgressDialog(
                self.tr("Compiling interfaces..."),
                self.tr("Abort"),
                0,
                numIDLs,
                self.tr("%v/%m Interfaces"),
                self,
            )
            progress.setModal(True)
            progress.setMinimumDuration(0)
            progress.setWindowTitle(self.tr("Interfaces"))

            for prog, fn in enumerate(
                self.project.getProjectData(dataKey="INTERFACES")
            ):
                progress.setValue(prog)
                if progress.wasCanceled():
                    break
                proc = self.__compileIDL(fn, True, progress)
                if proc is not None:
                    while proc.state() == QProcess.ProcessState.Running:
                        QThread.msleep(100)
                        QApplication.processEvents()
                else:
                    break
            progress.setValue(numIDLs)

    def __compileSelectedInterfaces(self):
        """
        Private method to compile selected interfaces to python.
        """
        if self.omniidl is not None:
            items = self.getSelectedItems()

            files = [self.project.getRelativePath(itm.fileName()) for itm in items]
            numIDLs = len(files)
            progress = EricProgressDialog(
                self.tr("Compiling interfaces..."),
                self.tr("Abort"),
                0,
                numIDLs,
                self.tr("%v/%m Interfaces"),
                self,
            )
            progress.setModal(True)
            progress.setMinimumDuration(0)
            progress.setWindowTitle(self.tr("Interfaces"))

            for prog, fn in enumerate(files):
                progress.setValue(prog)
                if progress.wasCanceled():
                    break
                proc = self.__compileIDL(fn, True, progress)
                if proc is not None:
                    while proc.state() == QProcess.ProcessState.Running:
                        QThread.msleep(100)
                        QApplication.processEvents()
                else:
                    break
            progress.setValue(numIDLs)

    def __configureIdlCompiler(self):
        """
        Private method to show a dialog to configure some options for the
        IDL compiler.
        """
        from .IdlCompilerOptionsDialog import IdlCompilerOptionsDialog

        params = self.project.getProjectData(dataKey="IDLPARAMS")

        dlg = IdlCompilerOptionsDialog(
            params["IncludeDirs"][:],
            params["DefinedNames"][:],
            params["UndefinedNames"][:],
            project=self.project,
            parent=self,
        )
        if dlg.exec() == QDialog.DialogCode.Accepted:
            include, defined, undefined = dlg.getData()
            if include != params["IncludeDirs"]:
                params["IncludeDirs"] = include[:]
                self.project.setDirty(True)
            if defined != params["DefinedNames"]:
                params["DefinedNames"] = defined[:]
                self.project.setDirty(True)
            if undefined != params["UndefinedNames"]:
                params["UndefinedNames"] = undefined[:]
                self.project.setDirty(True)

    def __configureCorba(self):
        """
        Private method to open the configuration dialog.
        """
        ericApp().getObject("UserInterface").showPreferences("corbaPage")

eric ide

mercurial