Exemple #1
0
def getJediProject(force=False):
    """Provides a jedi project"""
    global jediProject

    if force or jediProject is None:
        project = GlobalData().project
        if project.isLoaded():
            jPath = project.getProjectDir()

            addedPaths = []
            for path in project.getImportDirsAsAbsolutePaths():
                if path not in addedPaths:
                    addedPaths.append(path)
            projectDir = project.getProjectDir()
            if projectDir not in addedPaths:
                addedPaths.append(projectDir)

        else:
            jPath = os.path.realpath(QDir.homePath())
            addedPaths = ()

        jediProject = Project(jPath,
                              sys_path=GlobalData().originalSysPath[:],
                              added_sys_path=addedPaths)

    return jediProject
Exemple #2
0
def copySkin():
    """Copies the new system-wide skins to the user settings dir.

    Also tests if the configured skin is in place. Sets the default if not.
    """
    systemWideSkinsDir = srcDir + os.path.sep + "skins" + os.path.sep
    userSkinsDir = os.path.normpath(QDir.homePath()) + \
        os.path.sep + CONFIG_DIR + os.path.sep + "skins" + os.path.sep

    for item in os.listdir(systemWideSkinsDir):
        candidate = systemWideSkinsDir + item
        if os.path.isdir(candidate):
            userCandidate = userSkinsDir + item
            if not os.path.exists(userCandidate):
                try:
                    shutil.copytree(candidate, userCandidate)
                except Exception as exc:
                    logging.error("Could not copy system wide skin from " +
                                  candidate + " to the user skin to " +
                                  userCandidate +
                                  ". Continue without copying skin.")
                    logging.error(str(exc))

    # Check that the configured skin is in place
    userSkinDir = userSkinsDir + Settings()['skin']
    if os.path.exists(userSkinDir) and os.path.isdir(userSkinDir):
        # That's just fine
        return

    # Here: the configured skin is not found in the user dir.
    # Try to set the default.
    if os.path.exists(userSkinsDir + 'default'):
        if os.path.isdir(userSkinsDir + 'default'):
            logging.warning("The configured skin '" + Settings()['skin'] +
                            "' has not been found. "
                            "Fallback to the 'default' skin.")
            Settings()['skin'] = 'default'
            return

    # Default is not there. Try to pick any.
    anySkinName = None
    for item in os.listdir(userSkinsDir):
        if os.path.isdir(userSkinsDir + item):
            anySkinName = item
            break

    if anySkinName is None:
        # Really bad situation. No system wide skins, no local skins.
        logging.error("Cannot find the any Codimension skin. "
                      "Please check Codimension installation.")
        return

    # Here: last resort - fallback to the first found skin
    logging.warning("The configured skin '" + Settings()['skin'] +
                    "' has not been found. Fallback to the '" +
                    anySkinName + "' skin.")
    Settings()['skin'] = anySkinName
import json
import logging
from copy import deepcopy
from ui.qt import QObject, QDir, pyqtSignal
from .config import SETTINGS_ENCODING, CONFIG_DIR
from .runparamscache import RunParametersCache
from .debugenv import DebuggerEnvironment
from .searchenv import SearchEnvironment
from .fsenv import FileSystemEnvironment
from .filepositions import FilePositions
from .userencodings import FileEncodings
from .flowgroups import FlowUICollapsedGroups
from .webresourcecache import WebResourceCache
from .plantumlcache import PlantUMLCache

SETTINGS_DIR = os.path.join(os.path.realpath(QDir.homePath()),
                            CONFIG_DIR) + os.path.sep

CLEAR_AND_REUSE = 0
NO_CLEAR_AND_REUSE = 1
NO_REUSE = 2


class ProfilerSettings:
    """Holds IDE-wide profiler options"""
    def __init__(self):
        self.nodeLimit = 1.0
        self.edgeLimit = 1.0

    def profSettingsToJSON(self):
        """Converts the instance to a serializable structure"""
Exemple #4
0
    def __selectFile(self, extension):
        """Picks a file of a certain extension"""
        dialog = QFileDialog(self, 'Save flowchart as')
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setLabelText(QFileDialog.Accept, "Save")
        dialog.setNameFilter(extension.upper() + " files (*." +
                             extension.lower() + ")")
        urls = []
        for dname in QDir.drives():
            urls.append(QUrl.fromLocalFile(dname.absoluteFilePath()))
        urls.append(QUrl.fromLocalFile(QDir.homePath()))
        project = GlobalData().project
        if project.isLoaded():
            urls.append(QUrl.fromLocalFile(project.getProjectDir()))
        dialog.setSidebarUrls(urls)

        suggestedFName = self.__parentWidget.getFileName()
        if '.' in suggestedFName:
            dotIndex = suggestedFName.rindex('.')
            suggestedFName = suggestedFName[:dotIndex]

        dialog.setDirectory(self.__getDefaultSaveDir())
        dialog.selectFile(suggestedFName + "." + extension.lower())
        dialog.setOption(QFileDialog.DontConfirmOverwrite, False)
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        if dialog.exec_() != QDialog.Accepted:
            return None

        fileNames = dialog.selectedFiles()
        fileName = os.path.abspath(str(fileNames[0]))
        if os.path.isdir(fileName):
            logging.error("A file must be selected")
            return None

        if "." not in fileName:
            fileName += "." + extension.lower()

        # Check permissions to write into the file or to a directory
        if os.path.exists(fileName):
            # Check write permissions for the file
            if not os.access(fileName, os.W_OK):
                logging.error("There is no write permissions for " + fileName)
                return None
        else:
            # Check write permissions to the directory
            dirName = os.path.dirname(fileName)
            if not os.access(dirName, os.W_OK):
                logging.error("There is no write permissions for the "
                              "directory " + dirName)
                return None

        if os.path.exists(fileName):
            res = QMessageBox.warning(
                self, "Save flowchart as",
                "<p>The file <b>" + fileName + "</b> already exists.</p>",
                QMessageBox.StandardButtons(QMessageBox.Abort |
                                            QMessageBox.Save),
                QMessageBox.Abort)
            if res == QMessageBox.Abort or res == QMessageBox.Cancel:
                return None

        # All prerequisites are checked, return a file name
        return fileName
Exemple #5
0
 def __getDefaultSaveDir():
     """Provides the default directory to save files to"""
     project = GlobalData().project
     if project.isLoaded():
         return project.getProjectDir()
     return QDir.currentPath()
Exemple #6
0
def getJediScript(code, srcPath):
    """Provides the jedi Script object considering the current project"""
    if not os.path.isabs(srcPath):
        # Pretend it is in the user home dir
        srcPath = os.path.realpath(QDir.homePath()) + os.path.sep + srcPath
    return jedi.Script(code=code, path=srcPath, project=getJediProject())
Exemple #7
0
def copySkin():
    """Copies the new system-wide skins to the user settings dir.

    Also tests if the configured skin is in place. Sets the default if not.
    """
    # I cannot import it at the top because the fileutils want
    # to use the pixmap cache which needs the application to be
    # created, so the import is deferred
    from utils.fileutils import saveToFile

    systemWideSkinsDir = srcDir + os.path.sep + "skins" + os.path.sep
    userSkinsDir = os.path.normpath(QDir.homePath()) + \
        os.path.sep + CONFIG_DIR + os.path.sep + "skins" + os.path.sep

    skinFiles = ['app.css', 'skin.json', 'cflow.json']
    platformSuffix = '.' + sys.platform.lower()

    if os.path.exists(systemWideSkinsDir):
        for item in os.listdir(systemWideSkinsDir):
            candidate = systemWideSkinsDir + item
            if os.path.isdir(candidate):
                userCandidate = userSkinsDir + item
                if not os.path.exists(userCandidate):
                    try:
                        os.makedirs(userCandidate, exist_ok=True)
                        filesToCopy = []
                        for fName in skinFiles:
                            generalFile = candidate + os.path.sep + fName
                            platformSpecificFile = generalFile + platformSuffix
                            userFile = userCandidate + os.path.sep + fName
                            if os.path.exists(platformSpecificFile):
                                filesToCopy.append(
                                    [platformSpecificFile, userFile])
                            elif os.path.exists(generalFile):
                                filesToCopy.append([generalFile, userFile])
                            else:
                                raise Exception('The skin file ' + fName +
                                                ' is not found in the '
                                                'installation package')
                        for srcDst in filesToCopy:
                            shutil.copyfile(srcDst[0], srcDst[1])
                    except Exception as exc:
                        logging.error(
                            "Could not copy system wide skin from "
                            "%s to  the user skin to %s. "
                            "Continue without copying skin.", candidate,
                            userCandidate)
                        logging.error(str(exc))

    # Deal with the default settings
    defaultSkinDir = userSkinsDir + 'default'
    defaultSkinDirOK = True
    if not os.path.exists(defaultSkinDir):
        # Create the default skin dir
        try:
            os.makedirs(defaultSkinDir, exist_ok=True)
        except Exception as exc:
            defaultSkinDirOK = False
            logging.error('Error creating a default skin directory: %s',
                          defaultSkinDir)
            logging.error(str(exc))

    if defaultSkinDirOK:
        defaultCSS = defaultSkinDir + os.path.sep + 'app.css'
        if not os.path.exists(defaultCSS):
            try:
                saveToFile(defaultCSS, _DEFAULT_APP_CSS)
            except Exception as exc:
                logging.error('Error creating default skin app.css file at %s',
                              defaultCSS)
                logging.error(str(exc))
        defaultCommonSkin = defaultSkinDir + os.path.sep + 'skin.json'
        if not os.path.exists(defaultCommonSkin):
            try:
                with open(defaultCommonSkin, 'w',
                          encoding=DEFAULT_ENCODING) as diskfile:
                    json.dump(_DEFAULT_SKIN_SETTINGS,
                              diskfile,
                              indent=4,
                              default=toJSON)
            except Exception as exc:
                logging.error(
                    'Error creating default skin skin.json '
                    'file at %s', defaultCommonSkin)
                logging.error(str(exc))
        defaultCFlowSkin = defaultSkinDir + os.path.sep + 'cflow.json'
        if not os.path.exists(defaultCFlowSkin):
            try:
                with open(defaultCFlowSkin, 'w',
                          encoding=DEFAULT_ENCODING) as diskfile:
                    json.dump(_DEFAULT_CFLOW_SETTINGS,
                              diskfile,
                              indent=4,
                              default=toJSON)
            except Exception as exc:
                logging.error(
                    'Error creating default skin cflow.json '
                    'file at %s', defaultCFlowSkin)
                logging.error(str(exc))

    # Check that the configured skin is in place
    userSkinDir = userSkinsDir + Settings()['skin']
    if os.path.exists(userSkinDir) and os.path.isdir(userSkinDir):
        # That's just fine
        return

    # Here: the configured skin is not found in the user dir.
    # Try to set the default.
    if os.path.exists(defaultSkinDir):
        if os.path.isdir(defaultSkinDir):
            logging.warning(
                "The configured skin '%s' has not been found. "
                "Fallback to the 'default' skin.",
                Settings()['skin'])
            Settings()['skin'] = 'default'
            return

    # Default is not there. Try to pick any.
    anySkinName = None
    for item in os.listdir(userSkinsDir):
        if os.path.isdir(userSkinsDir + item):
            anySkinName = item
            break

    if anySkinName is None:
        # Really bad situation. No system wide skins, no local skins.
        logging.error("Cannot find the any Codimension skin. "
                      "Please check Codimension installation.")
        return

    # Here: last resort - fallback to the first found skin
    logging.warning(
        "The configured skin '%s' has not been found. "
        "Fallback to the '%s' skin.",
        Settings()['skin'], anySkinName)
    Settings()['skin'] = anySkinName