Exemplo n.º 1
0
    def _deployResources(cls):
        """ On windows the resource folder data is stored within the application install directory.
            However, due to permissions issues, certain file types cannot be accessed from that
            directory without causing the program to crash. Therefore, the stored resources must
            be expanded into the user's AppData/Local folder. The method checks the currently
            deployed resources folder and deploys the stored resources if the existing resources
            either don't exist or don't match the currently installed version of the program. """

        if not OsUtils.isWindows() or not PyGlassEnvironment.isDeployed:
            return False

        storagePath       = PyGlassEnvironment.getInstallationPath('resource_storage', isDir=True)
        storageStampPath  = FileUtils.makeFilePath(storagePath, 'install.stamp')
        resourcePath      = PyGlassEnvironment.getRootResourcePath(isDir=True)
        resourceStampPath = FileUtils.makeFilePath(resourcePath, 'install.stamp')

        try:
            resousrceData = JSON.fromFile(resourceStampPath)
            storageData   = JSON.fromFile(storageStampPath)
            if resousrceData['CTS'] == storageData['CTS']:
                return False
        except Exception as err:
            pass

        SystemUtils.remove(resourcePath)
        FileUtils.mergeCopy(storagePath, resourcePath)
        return True
Exemplo n.º 2
0
    def __init__(self):
        """Creates a new instance of PyGlassApplication."""
        QtCore.QObject.__init__(self)
        self._qApplication = None
        self._window       = None
        self._splashScreen = None

        # Sets a temporary standard out and error for deployed applications in a write allowed
        # location to prevent failed write results.
        if PyGlassEnvironment.isDeployed:
            if appdirs:
                userDir = appdirs.user_data_dir(self.appID, self.appGroupID)
            else:
                userDir = FileUtils.createPath(
                    os.path.expanduser('~'), '.pyglass', self.appGroupID, self.appID, isDir=True)

            path = FileUtils.createPath(
                userDir,
                self.appID + '_out.log', isFile=True)
            folder = FileUtils.getDirectoryOf(path, createIfMissing=True)
            sys.stdout = open(path, 'w+')

            FileUtils.createPath(
                appdirs.user_data_dir(self.appID, self.appGroupID),
                self.appID + '_error.log',
                isFile=True)
            folder = FileUtils.getDirectoryOf(path, createIfMissing=True)
            sys.stderr = open(path, 'w+')

        PyGlassEnvironment.initializeAppSettings(self)
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        """Creates a new instance of PyGlassApplication."""
        QtCore.QObject.__init__(self)
        self._qApplication      = None
        self._window            = None
        self._splashScreen      = None

        self.redirectLogOutputs()
        PyGlassEnvironment.initializeAppSettings(self)
        self.redirectLogOutputs()
Exemplo n.º 4
0
    def upgradeDatabase(cls, databaseUrl):
        """upgradeDatabase doc..."""
        from pyglass.alembic.AlembicUtils import AlembicUtils

        if not AlembicUtils.hasAlembic:
            return False

        AlembicUtils.upgradeDatabase(
            databaseUrl=databaseUrl,
            resourcesPath=PyGlassEnvironment.getRootResourcePath(isDir=True),
            localResourcesPath=PyGlassEnvironment.getRootLocalResourcePath(isDir=True),
        )
        return True
Exemplo n.º 5
0
    def __init__(self, rootPath =None, recursive =True, **kwargs):
        """Creates a new instance of WidgetUiCompiler."""
        self._log        = Logger(self)
        self._verbose    = ArgsUtils.get('verbose', False, kwargs)
        self._recursive  = recursive
        self._pythonPath = os.path.normpath(sys.exec_prefix)

        if rootPath and os.path.isabs(rootPath):
            self._rootPath = FileUtils.cleanupPath(rootPath, isDir=True)
        elif rootPath:
            parts = rootPath.split(os.sep if rootPath.find(os.sep) != -1 else '/')
            self._rootPath = PyGlassEnvironment.getRootResourcePath(*parts, isDir=True)
        else:
            self._rootPath = PyGlassEnvironment.getRootResourcePath()
Exemplo n.º 6
0
    def _createSetupFile(self, binPath):
        path = FileUtils.createPath(binPath, 'setup.py', isFile=True)
        scriptPath = inspect.getabsfile(self.applicationClass)

        try:
            sourcePath = PyGlassEnvironment.getPyGlassResourcePath(
                '..', 'setupSource.txt', isFile=True)
            f      = open(sourcePath, 'r+')
            source = f.read()
            f.close()
        except Exception as err:
            print(err)
            return None

        try:
            f = open(path, 'w+')
            f.write(source.replace(
                '##SCRIPT_PATH##', StringUtils.escapeBackSlashes(scriptPath)
            ).replace(
                '##RESOURCES##', StringUtils.escapeBackSlashes(JSON.asString(self.resources))
            ).replace(
                '##INCLUDES##', StringUtils.escapeBackSlashes(JSON.asString(self.siteLibraries))
            ).replace(
                '##ICON_PATH##', StringUtils.escapeBackSlashes(self._createIcon(binPath))
            ).replace(
                '##APP_NAME##', self.appDisplayName
            ).replace(
                '##SAFE_APP_NAME##', self.appDisplayName.replace(' ', '_') ))
            f.close()
        except Exception as err:
            print(err)
            return None

        return path
Exemplo n.º 7
0
    def _createNsisInstallerScript(self, binPath):
        path = FileUtils.createPath(binPath, 'installer.nsi', isFile=True)

        try:
            sourcePath = PyGlassEnvironment.getPyGlassResourcePath(
                '..', 'installer.tmpl.nsi', isFile=True)
            f = open(sourcePath, 'r+')
            source = f.read()
            f.close()
        except Exception as err:
            print(err)
            return None

        try:
            f = open(path, 'w+')
            f.write(source.replace(
                '##APP_NAME##', self.appDisplayName
            ).replace(
                '##APP_ID##', self.application.appID
            ).replace(
                '##APP_GROUP_ID##', self.application.appGroupID
            ).replace(
                '##SAFE_APP_NAME##', self.appDisplayName.replace(' ', '_') ))
            f.close()
        except Exception as err:
            print(err)
            return None

        return path
Exemplo n.º 8
0
 def _changeDirToLocalAppPath(cls, localResourcesPath):
     """_changeDirToLocalAppPath doc..."""
     if not localResourcesPath:
         localResourcesPath = PyGlassEnvironment.getRootLocalResourcePath(isDir=True)
     lastDir = os.path.abspath(os.curdir)
     os.chdir(localResourcesPath)
     return lastDir
Exemplo n.º 9
0
 def _getIconSheet(self):
     key = str(self._sizeIndex) + '-' + str(self._isDark)
     if key not in self._ICON_SHEETS:
         self._ICON_SHEETS[key] = QtGui.QPixmap(PyGlassEnvironment.getPyGlassResourcePath(
             'icons-%s-%s.png' % (
                 'dark' if self._isDark else 'light', str(self._ICON_SIZES[self._sizeIndex])
         ), isFile=True))
     return self._ICON_SHEETS[key]
Exemplo n.º 10
0
    def run(self):
        """Doc..."""
        resources = self._compiler.resources

        #-------------------------------------------------------------------------------------------
        # RESOURCES
        #       If no resource folders were specified copy the entire contents of the resources
        #       folder. Make sure to skip the local resources path in the process.
        if not resources:
            for item in os.listdir(PyGlassEnvironment.getRootResourcePath(isDir=True)):
                itemPath = PyGlassEnvironment.getRootResourcePath(item)
                if os.path.isdir(itemPath) and not item in ['local', 'apps']:
                    resources.append(item)

        for container in resources:
            parts = container.replace('\\', '/').split('/')
            self._copyResourceFolder(
                PyGlassEnvironment.getRootResourcePath(*parts, isDir=True), parts)

        #-------------------------------------------------------------------------------------------
        # APP RESOURCES
        appResources = self._compiler.resourceAppIds
        if not appResources:
            appResources = []
        for appResource in appResources:
            itemPath = PyGlassEnvironment.getRootResourcePath('apps', appResource, isDir=True)
            if not os.path.exists(itemPath):
                self._log.write('[WARNING]: No such app resource path found: %s' % appResource)
                continue
            self._copyResourceFolder(itemPath, ['apps', appResource])

        #-------------------------------------------------------------------------------------------
        # PYGLASS RESOURCES
        #       Copy the resources from the PyGlass
        resources = []
        for item in os.listdir(PyGlassEnvironment.getPyGlassResourcePath('..', isDir=True)):
            itemPath = PyGlassEnvironment.getPyGlassResourcePath('..', item)
            if os.path.isdir(itemPath):
                resources.append(item)

        for container in resources:
            self._copyResourceFolder(
                PyGlassEnvironment.getPyGlassResourcePath('..', container), [container])

        # Create a stamp file in resources for comparing on future installations
        creationStampFile = FileUtils.makeFilePath(self._targetPath, 'install.stamp')
        JSON.toFile(creationStampFile, {'CTS':TimeUtils.toZuluPreciseTimestamp()})

        #-------------------------------------------------------------------------------------------
        # CLEANUP
        if self._verbose:
            self._log.write('CLEANUP: Removing unwanted destination files.')
        self._cleanupFiles(self._targetPath)

        self._copyPythonStaticResources()

        if self._verbose:
            self._log.write('COMPLETE: Resource Collection')

        return True
Exemplo n.º 11
0
def getAnalysisSettings():
    """ Retrieves the analysis configuration settings file as a SettingsConfig
        instance that can be modified and saved as needed.
        @return: SettingsConfig """
    if not __LOCALS__.SETTINGS_CONFIG:
        __LOCALS__.SETTINGS_CONFIG = SettingsConfig(
            FileUtils.makeFilePath(
                PyGlassEnvironment.getRootLocalResourcePath(
                    'analysis', isDir=True),
                'analysis.json'), pretty=True)
    return __LOCALS__.SETTINGS_CONFIG
Exemplo n.º 12
0
    def getAppDatabaseItems(cls, appName):
        databaseRoot = PyGlassEnvironment.getRootResourcePath('apps', appName, 'data')
        if not os.path.exists(databaseRoot):
            return []

        results = []
        os.path.walk(databaseRoot, cls._findAppDatabases, {
            'root':databaseRoot,
            'results':results,
            'appName':appName
        })
        return results
Exemplo n.º 13
0
    def _createNsisInstallerScript(self, binPath):
        path = FileUtils.createPath(binPath, 'installer.nsi', isFile=True)

        try:
            sourcePath = PyGlassEnvironment.getPyGlassResourcePath(
                '..', 'installer.tmpl.nsi', isFile=True)
            f = open(sourcePath, 'r+')
            source = f.read()
            f.close()
        except Exception, err:
            print err
            return None
Exemplo n.º 14
0
    def _createSetupFile(self, binPath):
        path = FileUtils.createPath(binPath, 'setup.py', isFile=True)
        scriptPath = inspect.getabsfile(self.applicationClass)

        try:
            sourcePath = PyGlassEnvironment.getPyGlassResourcePath(
                '..', 'setupSource.txt', isFile=True)
            f      = open(sourcePath, 'r+')
            source = f.read()
            f.close()
        except Exception, err:
            print err
            return None
Exemplo n.º 15
0
    def _showSplashScreen(self):
        """_showSplashScreen doc..."""
        parts = str(self.splashScreenUrl).split(':', 1)
        if len(parts) == 1 or parts[0].lower == 'app':
            splashImagePath = PyGlassEnvironment.getRootResourcePath(
                'apps', self.appID, parts[-1], isFile=True)
        else:
            splashImagePath = None

        if splashImagePath and os.path.exists(splashImagePath):
            splash = QtGui.QSplashScreen(QtGui.QPixmap(splashImagePath))
            splash.show()
            self._splashScreen = splash
            self.updateSplashScreen('Initializing User Interface')
Exemplo n.º 16
0
    def getPathFromDatabaseUrl(cls, databaseUrl):
        urlParts = databaseUrl.split(u'://')

        # Determine the sqlite database path
        if urlParts[0].lower() == u'shared':
            path = [u'shared', u'data']
        else:
            path = [u'apps', urlParts[0], u'data']

        path += urlParts[1].strip(u'/').split(u'/')
        if not path[-1].endswith(u'.vdb'):
            path[-1] += u'.vdb'

        return PyGlassEnvironment.getRootLocalResourcePath(*path)
Exemplo n.º 17
0
    def getAppDatabaseItems(cls, appName, localResourcesPath =None):
        if not localResourcesPath:
            localResourcesPath = PyGlassEnvironment.getRootLocalResourcePath(isDir=True)

        databaseRoot = FileUtils.makeFolderPath(localResourcesPath, 'apps', appName, 'data')
        if not os.path.exists(databaseRoot):
            return []

        results = []
        FileUtils.walkPath(databaseRoot, cls._findAppDatabases, {
            'root':databaseRoot,
            'results':results,
            'appName':appName })

        return results
Exemplo n.º 18
0
    def getMigrationPathFromDatabaseUrl(cls, databaseUrl, root =False):
        urlParts = databaseUrl.split(u'://')
        if urlParts[0].lower() == u'shared':
            path = [u'shared', u'migration']
        else:
            path = [u'apps', urlParts[0], u'migration']

        if not root:
            path += urlParts[-1].split(u'/')

            # Remove the extension
            if path[-1].endswith(u'.vdb'):
                path[-1] = path[-1][:-4]

        return PyGlassEnvironment.getResourcePath(*path)
Exemplo n.º 19
0
    def _getIconPath(self):
        path = self.iconPath
        if not path:
            return ''

        if isinstance(path, basestring):
            if os.path.isabs(path) and os.path.exists(path):
                return FileUtils.cleanupPath(path)
            else:
                path = path.replace('\\', '/').strip('/').split('/')

        path.append('icons' if OsUtils.isWindows() else 'icons.iconset')
        out = PyGlassEnvironment.getRootResourcePath(*path, isDir=True)
        if os.path.exists(out):
            return out
        return ''
Exemplo n.º 20
0
    def getPathFromDatabaseUrl(cls, databaseUrl, localResourcesPath=None):
        urlParts = databaseUrl.split("://")

        # Determine the sqlite database path
        if urlParts[0].lower() == "shared":
            path = ["shared", "data"]
        else:
            path = ["apps", urlParts[0], "data"]

        path += urlParts[1].strip("/").split("/")
        if not path[-1].endswith(".vdb"):
            path[-1] += ".vdb"

        if localResourcesPath:
            return FileUtils.makeFilePath(localResourcesPath, *path)

        return PyGlassEnvironment.getRootLocalResourcePath(*path, isFile=True)
Exemplo n.º 21
0
    def __init__(self, **kwargs):
        """
        Creates a new instance of AnalyzerBase.

        [cacheData] ~ Object | CacheData
            A caching object on which to store data during analysis at the
            analyzer level, instead of the stage level.

        [logger] ~ Logger
            A logger object to use for logging within this analyzer. If no such
            logger exists, a new logger is created.

        [logFolderPath] ~ String
            If no logger was specified for the analyzer, this is the absolute
            path to the folder where the log file should be written. This
            value is ignored if you specify a logger.
        """

        self._tracksSession     = None
        self._analysisSession   = None
        self._cache             = ConfigsDict(kwargs.get('cacheData'))
        self._logger            = kwargs.get('logger')
        self._tempPath          = kwargs.get('tempPath')
        self._stages            = []
        self._sitemaps          = []
        self._trackways         = dict()
        self._seriesBundles     = dict()
        self._plotFigures       = dict()
        self._currentStage      = None
        self._success           = False
        self._errorMessage      = None
        self._startTime         = None

        if not self._logger:
            self._logger = Logger(
                name=self,
                logFolder=kwargs.get('logFolderPath'),
                printOut=True,
                headerless=True,
                removeIfExists=True,
                timestampFileSuffix=False)

        self._defaultRootPath = PyGlassEnvironment.getRootLocalResourcePath(
            'analysis', isDir=True)
        self._settings = DataLoadUtils.getAnalysisSettings()
Exemplo n.º 22
0
    def getMigrationPathFromDatabaseUrl(cls, databaseUrl, root=False, resourcesPath=None):
        urlParts = databaseUrl.split("://")
        if urlParts[0].lower() == "shared":
            path = ["shared", "alembic"]
        else:
            path = ["apps", urlParts[0], "alembic"]

        if not root:
            path += urlParts[-1].split("/")

            # Remove the extension
            if path[-1].endswith(".vdb"):
                path[-1] = path[-1][:-4]

        if resourcesPath:
            return FileUtils.makeFolderPath(resourcesPath, *path, isDir=True)

        return PyGlassEnvironment.getRootResourcePath(*path, isDir=True)
Exemplo n.º 23
0
    def run(self, appArgs =None, **kwargs):
        """Doc..."""
        try:
            if PyGlassEnvironment.isDeployed:
                logPath = PyGlassEnvironment.getRootLocalResourcePath('logs', isDir=True)
                if not os.path.exists(logPath):
                    os.makedirs(logPath)

                try:
                    sys.stdout.close()
                except Exception, err:
                    pass
                sys.stdout = open(logPath + 'out.log', 'w')

                try:
                    sys.stderr.close()
                except Exception, err:
                    pass
                sys.stderr = open(logPath + 'error.log', 'w')
Exemplo n.º 24
0
    def hasMigrationEnvironment(cls, databaseUrl, resourcesPath =None):
        """ Determines whether or not the specified application database currently has a migration
            environment setup
            :param databaseUrl:
            :param resourcesPath:
            :return: True or false depending on the presence of a migration environment """

        if not resourcesPath:
            resourcesPath = PyGlassEnvironment.getRootResourcePath(isDir=True)

        migrationPath = PyGlassModelUtils.getMigrationPathFromDatabaseUrl(
            databaseUrl=databaseUrl, resourcesPath=resourcesPath)

        if not os.path.exists(migrationPath):
            return False
        if not os.path.exists(FileUtils.makeFilePath(migrationPath, 'alembic.ini')):
            return False
        if not os.path.exists(FileUtils.makeFolderPath(migrationPath, 'versions')):
            return False
        return True
Exemplo n.º 25
0
    def redirectLogOutputs(self, prefix =None, logFolderPath =None):
        """ Sets a temporary standard out and error for deployed applications in a write allowed
            location to prevent failed write results. """

        if not PyGlassEnvironment.isDeployed:
            return

        if not prefix:
            prefix = self.appID

        if not prefix.endswith('_'):
            prefix += '_'

        if logFolderPath:
            logPath = logFolderPath
        elif PyGlassEnvironment.isInitialized:
            logPath = PyGlassEnvironment.getRootLocalResourcePath('logs', isDir=True)
        else:
            prefix += 'init_'
            if appdirs:
                logPath = appdirs.user_data_dir(self.appID, self.appGroupID)
            else:
                logPath = FileUtils.createPath(
                    os.path.expanduser('~'), '.pyglass', self.appGroupID, self.appID, isDir=True)

        FileUtils.getDirectoryOf(logPath, createIfMissing=True)
        try:
            sys.stdout.flush()
            sys.stdout.close()
        except Exception as err:
            pass
        sys.stdout = open(FileUtils.makeFilePath(logPath, prefix + 'out.log'), 'w+')

        try:
            sys.stderr.flush()
            sys.stderr.close()
        except Exception as err:
            pass
        sys.stderr = open(FileUtils.makeFilePath(logPath, prefix + 'error.log'), 'w+')

        return True
Exemplo n.º 26
0
    def run(self):
        """Doc..."""
        resources = self._compiler.resources

        #-------------------------------------------------------------------------------------------
        # APP RESOURCES
        #       If no resource folders were specified copy the entire contents of the resources
        #       folder. Make sure to skip the local resources path in the process.
        if not resources:
            for item in os.listdir(PyGlassEnvironment.getRootResourcePath(isDir=True)):
                itemPath = PyGlassEnvironment.getRootResourcePath(item)
                if os.path.isdir(itemPath) and not item == 'local':
                    resources.append(item)

        for container in resources:
            parts = container.replace('\\', '/').split('/')
            self._copyResourceFolder(
                PyGlassEnvironment.getRootResourcePath(*parts, isDir=True), parts
            )

        #-------------------------------------------------------------------------------------------
        # PYGLASS RESOURCES
        #       Copy the resources from the PyGlass
        resources = []
        for item in os.listdir(PyGlassEnvironment.getPyGlassResourcePath('..', isDir=True)):
            itemPath = PyGlassEnvironment.getPyGlassResourcePath('..', item)
            if os.path.isdir(itemPath):
                resources.append(item)

        for container in resources:
            self._copyResourceFolder(
                PyGlassEnvironment.getPyGlassResourcePath('..', container), [container]
            )

        #-------------------------------------------------------------------------------------------
        # CLEANUP
        if self._verbose:
            self._log.write('CLEANUP: Removing unwanted destination files.')
        self._cleanupFiles(self._targetPath)

        self._copyPythonStaticResources()

        if self._verbose:
            self._log.write('COMPLETE: Resource Collection')

        return True
Exemplo n.º 27
0
 def _runPreMainWindowImpl(self):
     # Overrides the resource path for running StaticFlow applications within the PyGlass app
     StaticFlowEnvironment.setResourceRootPath(PyGlassEnvironment.getRootResourcePath())
Exemplo n.º 28
0
from __future__ import print_function, absolute_import, unicode_literals, division

import sqlalchemy as sqla
from pyaid.dict.DictUtils import DictUtils
from pyglass.app.PyGlassEnvironment import PyGlassEnvironment
PyGlassEnvironment.initializeFromInternalPath(__file__)

from cadence.models.tracks.Tracks_Track import Tracks_Track

models = {'Track':Tracks_Track.MASTER}
session = Tracks_Track.MASTER.createSession()
verbose = True

for label,model in models.iteritems():
    query = session.query(model).filter(model.uid.in_((
        'track1l2ic-1s7-rZ3g4I0Yzvzd',
        'track1l2id-1sZ-UvtVfQoOAOPo')) )
    items = query.all()
    print('\n\n\n%s' % (60*'-'))
    print('MODEL:', label)
    print('COUNT:', len(items))

    if not items:
        print('No matching items found')
    else:
        for item in items:
            if verbose:
                print('[TRACK]: %s [%s]:\n  * hidden: %s\n  * complete: %s\n  * next: %s\n%s' % (
                    item.fingerprint, item.uid,
                    'Y' if item.hidden else 'N', 'Y' if item.isComplete else 'N', item.next,
Exemplo n.º 29
0
#       When running outside of a PyGlass application, the PyGlass environment must be initialized
#       explicitly, including specifying the relationship between the run script (this file) and
#       the resource directory. This must be done before importing database classes so that the
#       database import correctly locates the database file and initializes the model classes to
#       that file.

from pyaid.system.SystemUtils import SystemUtils

from pyaid.file.FileUtils import FileUtils

from pyglass.app.PyGlassEnvironment import PyGlassEnvironment

location = FileUtils.getDirectoryOf(__file__)

PyGlassEnvironment.initializeExplicitAppSettings(
    FileUtils.createPath(location, '..', 'resources', isDir=True),
    FileUtils.createPath(location, '..', 'resources', 'local', isDir=True) )

#---------------------------------------------------------------------------------------------------
# RUN TEST SCRIPT

from cadence.models.tracks.Tracks_SiteMap import Tracks_SiteMap
from cadence.svg.CadenceDrawing import CadenceDrawing

model   = Tracks_SiteMap.MASTER
session = model.createSession()
siteMap = session.query(model).filter(model.index == 13).first()
fileName = 'test_new.svg'
drawing = CadenceDrawing(fileName, siteMap)

xFed   = siteMap.xFederal
Exemplo n.º 30
0
 def getRootLocalResourcePath(self, *args, **kwargs):
     return PyGlassEnvironment.getRootLocalResourcePath(*args, **kwargs)