示例#1
0
    def locateMayaEnvFiles(cls):
        """ Finds the location of all Maya.env files located in the default location on the host
            and return them as a list. If no such env files exist, the method returns an empty
            list. """

        home = FileUtils.cleanupPath(OsUtils.getHomePath(), isDir=True)
        if not os.path.exists(home):
            return []

        if OsUtils.isWindows():
            root = FileUtils.createPath(OsUtils.getDocumentsPath(),
                                        'maya',
                                        isDir=True)
            if not os.path.exists(root):
                return []
        elif OsUtils.isMac():
            root = FileUtils.createPath(home,
                                        'Library',
                                        'Preferences',
                                        'Autodesk',
                                        'maya',
                                        isDir=True)
            if not os.path.exists(root):
                return []
        else:
            return []

        out = []
        FileUtils.walkPath(root, cls._handleFindEnvFiles, out)
        return out
    def run(self):
        """Doc..."""

        # Create the bin directory where the output will be stored if it does not already exist
        binPath = self.getBinPath(isDir=True)
        if not os.path.exists(binPath):
            os.makedirs(binPath)

        # Remove any folders created by previous build attempts
        for d in self._CLEANUP_FOLDERS:
            path = os.path.join(binPath, d)
            if os.path.exists(path):
                shutil.rmtree(path)

        os.chdir(binPath)

        ResourceCollector(self, verbose=True).run()

        cmd = [
            FileUtils.makeFilePath(sys.prefix, 'bin', 'python'),
            '"%s"' % self._createSetupFile(binPath),
            OsUtils.getPerOsValue('py2exe', 'py2app'), '>',
            '"%s"' % self.getBinPath('setup.log', isFile=True)]

        print('[COMPILING]: Executing %s' % OsUtils.getPerOsValue('py2exe', 'py2app'))
        print('[COMMAND]: %s' % ' '.join(cmd))
        result = SystemUtils.executeCommand(cmd, remote=False, wait=True)
        if result['code']:
            print('COMPILATION ERROR:')
            print(result['out'])
            print(result['error'])
            return False

        if self.appFilename and OsUtils.isWindows():
            name   = self.applicationClass.__name__
            source = FileUtils.createPath(binPath, 'dist', name + '.exe', isFile=True)
            dest   = FileUtils.createPath(binPath, 'dist', self.appFilename + '.exe', isFile=True)
            os.rename(source, dest)

        if OsUtils.isWindows() and not self._createWindowsInstaller(binPath):
            print('Installer Creation Failed')
            return False
        elif OsUtils.isMac() and not self._createMacDmg(binPath):
            print('DMG Creation Failed')
            return False

        # Remove the resources path once compilation is complete
        resourcePath = FileUtils.createPath(binPath, 'resources', isDir=True)
        SystemUtils.remove(resourcePath)

        buildPath = FileUtils.createPath(binPath, 'build', isDir=True)
        SystemUtils.remove(buildPath)

        FileUtils.openFolderInSystemDisplay(binPath)

        return True
示例#3
0
 def isDeployed(cls):
     try:
         if cls._isDeployed is None:
             if OsUtils.isWindows():
                 cls._isDeployed = cls._ENV_PATH.find(os.sep + 'library.zip' + os.sep) != -1
             elif OsUtils.isMac():
                 cls._isDeployed = cls._ENV_PATH.find(os.sep + 'site-packages.zip' + os.sep) != -1
         return cls._isDeployed
     except Exception, err:
         return True
示例#4
0
    def getSetupKwargs(self, **kwargs):
        """Doc..."""
        # Adds packages to python system path
        os.chdir(self.sourcePath)

        appName          = ArgsUtils.get('appDisplayName', None, kwargs)
        self._iconPath   = ArgsUtils.get('iconPath', '', kwargs)
        self._scriptPath = ArgsUtils.get('scriptPath', None, kwargs)
        self._paths      = ArgsUtils.getAsList('resources', kwargs)
        self._includes   = ArgsUtils.getAsList('includes', kwargs)
        for path in self._paths:
            sys.path.append(path)

        dataFiles = []
        if OsUtils.isWindows():
            dataFiles += self._addWindowsDataFiles()

        values = self._getSiteValues(dataFiles, [], [])
        window = {'script':self._scriptPath}

        #-------------------------------------------------------------------------------------------
        # [MAC] CLEANSE PACKAGES
        #       Py2app does not allow subpackages. Instead the entire package must be copied so
        #       any subpackage entries listed must be replaced by the top level package
        if not OsUtils.isWindows():
            packs = []
            for item in values['packages']:
                item = item.split('.')[0]
                if item not in packs:
                    packs.append(item)
            values['packages'] = packs

        compType = 'py2exe' if OsUtils.isWindows() else 'py2app'
        options = {
                'packages':values['packages'],
                'includes':values['includes']}
        out = dict(options={compType:options})

        if OsUtils.isWindows():
            if self._iconPath:
                window['icon_resources'] = [(1, self._iconPath)]
            out['windows']    = [window]
            out['data_files'] = values['dataFiles']
        else:
            if self._iconPath:
                options['iconfile'] = self._iconPath
            out['name']           = appName
            out['setup_requires'] = [compType]
            out['app']            = [window]
            options['resources'] = [
                FileUtils.createPath(self.sourcePath, 'resources', isDir=True) ]

        return out
    def run(self):
        """Doc..."""

        # Create the bin directory where the output will be stored if it does not alread exist
        binPath = self.getBinPath(isDir=True)
        if not os.path.exists(binPath):
            os.makedirs(binPath)

        # Remove any folders created by previous build attempts
        for d in self._CLEANUP_FOLDERS:
            path = os.path.join(binPath, d)
            if os.path.exists(path):
                shutil.rmtree(path)

        os.chdir(binPath)

        ResourceCollector(self, verbose=True).run()

        cmd = 'python %s %s > %s' % (
            self._createSetupFile(binPath),
            'py2exe' if OsUtils.isWindows() else 'py2app',
            self.getBinPath('setup.log', isFile=True) )

        result = SystemUtils.executeCommand(cmd, remote=False, wait=True)
        if result['code']:
            print 'COMPILATION ERROR:'
            print result['error']
            return False

        if self.appFilename and OsUtils.isWindows():
            name   = self.applicationClass.__name__
            source = FileUtils.createPath(binPath, 'dist', name + '.exe', isFile=True)
            dest   = FileUtils.createPath(binPath, 'dist', self.appFilename + '.exe', isFile=True)
            os.rename(source, dest)

        if OsUtils.isWindows() and not self._createWindowsInstaller(binPath):
            print 'Installer Creation Failed'
            return False
        elif OsUtils.isMac() and not self._createMacDmg(binPath):
            print 'DMG Creation Failed'
            return False

        # Remove the resources path once compilation is complete
        resourcePath = FileUtils.createPath(binPath, 'resources', isDir=True)
        SystemUtils.remove(resourcePath)

        buildPath = FileUtils.createPath(binPath, 'build', isDir=True)
        SystemUtils.remove(buildPath)

        return True
示例#6
0
    def checkEnvFile(cls, target, otherPaths=None):
        """Doc..."""
        pathSep = OsUtils.getPerOsValue(';', ':')
        additions = cls._getSourcePaths(otherPaths=otherPaths)

        with open(target, 'r') as f:
            contents = f.read()

        result = cls._PYTHON_PATH_PATTERN.search(contents)
        if not result:
            return False

        paths = result.groupdict()['paths'].split(pathSep)
        for addition in additions:
            found = False
            for p in paths:
                p = FileUtils.cleanupPath(p, noTail=True)
                if p == FileUtils.cleanupPath(addition.folderPath,
                                              noTail=True):
                    found = True
                    break
            if not found:
                return False

        return True
示例#7
0
    def _handleAddApp(self):
        defaultPath = self.appConfig.get('LAST_APP_PATH', OsUtils.getDocumentsPath())

        path = PyGlassBasicDialogManager.browseForDirectory(
            parent=self,
            caption=StringUtils.dedent("""
                Specify the root path to a PyGlass application, in which a resource folder
                resides"""),
            defaultPath=defaultPath)
        if not path:
            return

        label = PyGlassBasicDialogManager.openTextQuery(
            parent=self,
            header='Enter Application Name',
            message='Specify the name of this application for display within Alembic Migrator',
            defaultText=os.path.basename(path.rstrip(os.sep)) )

        apps = self.appConfig.get('APPLICATIONS', dict())
        appData = {
            'label':label,
            'path':path,
            'databases':dict(),
            'id':TimeUtils.getUidTimecode('App', StringUtils.slugify(label))}
        apps[appData['id']] = appData
        self.appConfig.set('APPLICATIONS', apps)

        self.refresh()
        resultItem = self.appsListWidget.findItems(appData['id'], QtCore.Qt.MatchExactly)
        if resultItem:
            resultItem[0].setSelected(True)
示例#8
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
示例#9
0
    def __init__(self, compiler, **kwargs):
        """Creates a new instance of ResourceCollector."""
        self._log        = Logger(self)
        self._verbose    = ArgsUtils.get('verbose', False, kwargs)
        self._compiler   = compiler

        if OsUtils.isWindows():
            self._targetPath = self._compiler.getBinPath('resources', isDir=True)
        elif OsUtils.isMac():
            self._targetPath = self._compiler.getBinPath('resources', 'resources', isDir=True)

        if os.path.exists(self._targetPath):
            shutil.rmtree(self._targetPath)

        if not os.path.exists(self._targetPath):
            os.makedirs(self._targetPath)
示例#10
0
    def _runAirDebug(self):
        pd = self._projectData

        if OsUtils.isWindows() and pd.hasPlatform(FlexProjectData.WINDOWS_PLATFORM):
            pd.setPlatform(FlexProjectData.WINDOWS_PLATFORM)
        elif OsUtils.isMac() and pd.hasPlatform(FlexProjectData.MAC_PLATFORM):
            pd.setPlatform(FlexProjectData.MAC_PLATFORM)
        elif pd.hasPlatform(FlexProjectData.AIR_PLATFORM):
            pd.setPlatform(FlexProjectData.AIR_PLATFORM)

        if not pd.updateApplicationConfigFile():
            self._log.write([
                'ERROR: Unable to update the application descriptor file',
                'PATH: ' + pd.appDescriptorPath,
                'VERSION: ' + pd.airVersion,
                'ID: ' + pd.appId ])
            return 1


        adlCommand    = 'adl.exe' if PyGlassEnvironment.isWindows else 'adl'
        appDescriptor = FileUtils.createPath(pd.projectPath, 'application.xml', isFile=True)

        cmd = [
            self.parent().mainWindow.getRootAIRPath(pd.airVersion, 'bin', adlCommand),
            '-profile', 'extendedDesktop']

        aneDebugPath = AirUtils.deployDebugNativeExtensions(cmd, pd)

        cmd += [appDescriptor, pd.platformBinPath]

        deployment = AirUtils.deployExternalIncludes(self._projectData)
        code       = 0
        try:
            os.chdir(FileUtils.createPath(pd.projectPath, isDir=True))
            print 'PLATFORM:', pd.currentPlatformID
            print 'LOCATION:', os.path.abspath(os.curdir)
            print 'COMMAND:', cmd

            result = SystemUtils.executeCommand(cmd)
            if result['code']:
                self._log.write('RESULT ERROR CODE: ' + str(result['code']) + '\n' + result['out'])
                code = 1
        except Exception, err:
            self._log.writeError('DEBUG ATTEMPT FAILED', err)
            code = 1
    def _createIcon(self, binPath):
        iconPath = self._getIconPath()
        if not iconPath:
            return iconPath

        if os.path.isfile(iconPath):
            return iconPath

        #-------------------------------------------------------------------------------------------
        # MAC ICON CREATION
        #       On OSX use Apple's iconutil (XCode developer tools must be installed) to create an
        #       icns file from the icons.iconset folder at the specified location.
        if OsUtils.isMac():
            targetPath = FileUtils.createPath(binPath, self.appDisplayName + '.icns', isFile=True)
            result = SystemUtils.executeCommand([
                'iconutil', '-c', 'icns', '-o', '"' + targetPath + '"', '"' + iconPath + '"'])
            if result['code']:
                return ''
            return targetPath

        #-------------------------------------------------------------------------------------------
        # WINDOWS ICON CREATION
        #       On Windows use convert (ImageMagick must be installed and on the PATH) to create an
        #       ico file from the icons folder of png files.
        result = SystemUtils.executeCommand('where convert')
        if result['code']:
            return ''
        items = result['out'].replace('\r', '').strip().split('\n')
        convertCommand = None
        for item in items:
            if item.find('System32') == -1:
                convertCommand = item
                break
        if not convertCommand:
            return ''

        images = os.listdir(iconPath)
        cmd = ['"' + convertCommand + '"']
        for image in images:
            if not StringUtils.ends(image, ('.png', '.jpg')):
                continue
            imagePath = FileUtils.createPath(iconPath, image, isFile=True)
            cmd.append('"' + imagePath + '"')
        if len(cmd) < 2:
            return ''

        targetPath = FileUtils.createPath(binPath, self.appDisplayName + '.ico', isFile=True)
        cmd.append('"' + targetPath + '"')

        result = SystemUtils.executeCommand(cmd)
        if result['code'] or not os.path.exists(targetPath):
            print 'FAILED:'
            print result['command']
            print result['error']
            return ''

        return targetPath
示例#12
0
 def requestsCABundle(cls):
     if cls.isDeployed:
         return  cls.getRootResourcePath(
             'pythonRoot',
             'Lib',
             'site-packages',
             'requests',
             'cacert.pem' if OsUtils.isWindows() else '.pem',
             isFile=True)
     return requests.utils.DEFAULT_CA_BUNDLE_PATH
示例#13
0
    def platformDistributionPath(self):
        ptype = self.buildTypeFolderName

        if self.isNative:
            platform = 'win' if OsUtils.isWindows() else 'mac'
            return FileUtils.createPath(
                self.platformProjectPath,
                'dist', 'native', platform, ptype, isDir=True)

        return FileUtils.createPath(self.platformProjectPath, 'dist', ptype, isDir=True)
示例#14
0
    def __init__(self, compiler, **kwargs):
        """Creates a new instance of ResourceCollector."""
        self._log        = Logger(self, printOut=True)
        self._verbose    = ArgsUtils.get('verbose', False, kwargs)
        self._compiler   = compiler

        if OsUtils.isWindows():
            self._targetPath = self._compiler.getBinPath('resources', isDir=True)
        elif OsUtils.isMac():
            # Resource folder resides inside another resource folder so that the copying retains
            # the original directory structure
            self._targetPath = self._compiler.getBinPath('resources', 'resources', isDir=True)
            #self._targetPath = self._compiler.getBinPath('resources', isDir=True)

        if os.path.exists(self._targetPath):
            shutil.rmtree(self._targetPath)

        if not os.path.exists(self._targetPath):
            os.makedirs(self._targetPath)
示例#15
0
    def _createPlatformsSnapshot(self, overrides =None):
        out = dict()
        platforms = {
            FlexProjectData.NATIVE_PLATFORM:self.nativePlatformCheck,
            FlexProjectData.WINDOWS_PLATFORM:self.nativePlatformCheck,
            FlexProjectData.MAC_PLATFORM:self.nativePlatformCheck,
            FlexProjectData.AIR_PLATFORM:self.airPlatformCheck,
            FlexProjectData.FLASH_PLATFORM:self.webPlatformCheck,
            FlexProjectData.ANDROID_PLATFORM:self.androidPlatformCheck,
            FlexProjectData.IOS_PLATFORM:self.iosPlatformCheck }
        for pid, check in platforms.iteritems():
            out[pid] = check.isChecked() or ArgsUtils.get(pid, False, overrides)

        out[FlexProjectData.WINDOWS_PLATFORM] \
            = out[FlexProjectData.WINDOWS_PLATFORM] and OsUtils.isWindows()
        out[FlexProjectData.MAC_PLATFORM] \
            = out[FlexProjectData.MAC_PLATFORM] and OsUtils.isMac()

        return out
示例#16
0
    def __init__(
        self,
        fileName,
        siteMap,
        labelTracks=True,
        labelColor="black",
        session=None,
        showUncertainty=True,
        showCenters=True,
        **kwargs
    ):
        """ Creates a new instance of CadenceDrawing.  Calls to the public functions line(), rect(),
            and others result in objects being added to the SVG canvas, with the file written by the
            save() method to specified fileName.  The second argument, the siteMap is provided as an
            argument to establish the correspondence between the Maya scene and the site siteMap
            coordinates. """

        self._logger = kwargs.get("logger")
        if not self._logger:
            self._logger = Logger(self, printOut=True)

        self.siteMapReady = siteMap.isReady
        if not self.siteMapReady:
            self._logger.write('[ERROR|CadenceDrawing]: Sitemap "%s-%s" not ready' % (siteMap.name, siteMap.level))
            return

        self.fileName = fileName
        self.siteMap = siteMap
        self.siteName = siteMap.name
        self.siteLevel = siteMap.level

        # Generally units can be specified in millimeters.  In a few cases, however, (e.g.,
        # PolyLine) the coordinates must be unqualified integers (as px).  The site maps, however
        # are in 'scaled mm'.  Hence the need for a cnversion factor pxPerMm. Unfortunately, the
        # conversion between px and mm is OS-dependent. The conversion from px to inches is 72 for
        # Apple but 90 more generally).

        ppi = 72 if OsUtils.isMac() else 90
        self.pxPerMm = ppi / 25.4

        # specify the width and height explicitly in mm, and likewise for the background rect
        left = siteMap.left * mm
        top = siteMap.top * mm
        width = siteMap.width * mm
        height = siteMap.height * mm

        self._drawing = svgwrite.Drawing(fileName, profile="tiny", size=(width, height), stroke=svgwrite.rgb(0, 0, 0))
        self._drawing.add(self._drawing.rect((left, top), (width, height), opacity="0"))

        self.groups = dict()

        if labelTracks:
            self.labelTracks(
                color=labelColor, session=session, showUncertainty=showUncertainty, showCenters=showCenters
            )
示例#17
0
    def _runClear(self):
        self._log.write(
            '<div style="font-size:24px">Clearing Android Logcat...</div>\n'
        )

        command = 'adb.exe' if OsUtils.isWindows() else 'adb'
        cmd = [
            '"%s"' % self.parent().mainWindow.getAndroidSDKPath('platform-tools', command),
            'logcat',
            '-c'
        ]

        return SystemUtils.executeCommand(cmd)
示例#18
0
    def airExtension(self):
        if self.currentPlatformID == FlexProjectData.IOS_PLATFORM:
            return 'ipa'
        elif self.currentPlatformID == FlexProjectData.ANDROID_PLATFORM:
            return 'apk'
        elif self.currentPlatformID == FlexProjectData.NATIVE_PLATFORM:
            return 'exe' if OsUtils.isWindows() else 'dmg'
        elif self._currentPlatformID == FlexProjectData.WINDOWS_PLATFORM:
            return 'exe'
        elif self._currentPlatformID == FlexProjectData.MAC_PLATFORM:
            return 'dmg'

        return 'air'
示例#19
0
    def _runDump(self):
        self._log.write(u'<div style="font-size:24px">Retrieving Android Logcat...</div>\n')

        command = 'adb.exe' if OsUtils.isWindows() else 'adb'
        cmd = [
            '"%s"' % self.parent().mainWindow.getAndroidSDKPath('platform-tools', command),
            'logcat',
            '-d',
            '-v', 'long']

        result = SystemUtils.executeCommand(cmd)
        if 'out' in result:
            out = result['out']

            res = AndroidLogcatThread._LOGCAT_HEADER_RE.finditer(out)
            if res:
                entries = []
                for r in res:
                    if entries:
                        entries[-1]['value'] = out[entries[-1]['res'].end():r.start()].strip()
                    entries.append({
                        'res':r,
                        'level':r.groupdict()['level'],
                        'pid':r.groupdict()['pid'],
                        'time':r.groupdict()['time'],
                        'id':r.groupdict()['id'] })
                if entries:
                    entries[-1]['value'] = out[entries[-1]['res'].end():].strip()

                res = ''
                for item in entries:
                    if 'value' not in item:
                        continue

                    item = self._parseLogEntry(item)

                    if item.ignore:
                        res += u'<div style="color:#999999;font-size:10px;">' + item.value + u'</div>'
                        continue

                    res += u'<div style="font-size:5px;">.</div><div style="color:' + item.color \
                        + u';font-size:14px;">' \
                        + u'<span style="background-color:' + item.backColor \
                        + u';font-size:10px;">[' + item.id \
                        + u']</span> ' + item.value + u'</div><div style="font-size:5px;">.</div>'

                if res:
                    result['out'] = res

        return result
示例#20
0
    def openFolderInSystemDisplay(cls, path):
        """ Opens the specified folder (or the folder containing the specified
            file) in Explorer, Finder, or File Viewer depending on the platform.
        """
        if not os.path.exists(path):
            return False
        if not os.path.isdir(path):
            path = cls.getDirectoryOf(path)
        path = path.rstrip(os.sep)

        if OsUtils.isWindows():
            os.startfile(path)
            return True

        if OsUtils.isMac():
            os.system('open "%s"' % path)
            return True

        try:
            os.system('xdg-open "%s"' % path)
            return True
        except Exception as err:
            return False
示例#21
0
文件: FileUtils.py 项目: sernst/PyAid
    def openFolderInSystemDisplay(cls, path):
        """ Opens the specified folder (or the folder containing the specified
            file) in Explorer, Finder, or File Viewer depending on the platform.
        """
        if not os.path.exists(path):
            return False
        if not os.path.isdir(path):
            path = cls.getDirectoryOf(path)
        path = path.rstrip(os.sep)

        if OsUtils.isWindows():
            os.startfile(path)
            return True

        if OsUtils.isMac():
            os.system('open "%s"' % path)
            return True

        try:
            os.system('xdg-open "%s"' % path)
            return True
        except Exception as err:
            return False
示例#22
0
    def locateMayaEnvFiles(cls):
        """ Finds the location of all Maya.env files located in the default location on the host
            and return them as a list. If no such env files exist, the method returns an empty
            list. """

        home = FileUtils.cleanupPath(OsUtils.getHomePath(), isDir=True)
        if not os.path.exists(home):
            return []

        if OsUtils.isWindows():
            root = FileUtils.createPath(OsUtils.getDocumentsPath(), 'maya', isDir=True)
            if not os.path.exists(root):
                return []
        elif OsUtils.isMac():
            root = FileUtils.createPath(
                home, 'Library', 'Preferences', 'Autodesk', 'maya', isDir=True)
            if not os.path.exists(root):
                return []
        else:
            return []

        out = []
        FileUtils.walkPath(root, cls._handleFindEnvFiles, out)
        return out
    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 ''
示例#24
0
    def _addWindowsDataFiles(self):
        """ Finds the MS Visual Studio runtime dlls that must be bundled with the application in
            order for the Python environment to run properly."""

        if not OsUtils.isWindows():
            return []

        dllPath = None
        for rootPath in self._PROGRAM_FILES_PATHS:
            path = rootPath + "Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC90.CRT"
            if os.path.exists(path):
                dllPath = path
                break
        if dllPath is None:
            raise Exception("Unable to find Microsoft Visual Studio 9.0 installation.")

        sys.path.append(dllPath)
        return [("Microsoft.VC90.CRT", glob(dllPath + r'\*.*'))]
示例#25
0
    def _runImpl(self):
        sets = self._settings

        if not self._settings.hasPlatform(FlexProjectData.ANDROID_PLATFORM):
            self._log.write('ERROR: No Android platform information found. Install aborted.')
            return 1

        self._settings.setPlatform(FlexProjectData.ANDROID_PLATFORM)

        self._log.write(
            '<div style="font-size:24px">Installing APK...</div>\n'
            + '(This can take a few minutes. Please stand by)'
        )

        command = 'adb.exe' if OsUtils.isWindows() else 'adb'
        cmd = [
            '"%s"' % self.parent().mainWindow.getAndroidSDKPath('platform-tools', command),
            'install',
            '-r',
            FileUtils.createPath(
                sets.platformDistributionPath, sets.contentTargetFilename + '.' + sets.airExtension)
        ]

        result = SystemUtils.executeCommand(cmd)

        if result['out']:
            self._log.write(
                '<div style="color:#999999">'
                + '<div style="font-size:18px">Result:'
                + '</div>' + result['out']
                + ('' if result['code'] else ('<br/>' + result['error']))
                + '</div>'
            )

        if result['code'] and result['error']:
            self._log.write(
                '<div style="color:#993333">'
                + '<div style="font-size:18px">Error:'
                + '</div>' + result['error'] + '</div>'
            )

        return result['code']
示例#26
0
    def flush(self, **kwargs):
        if not self._buffer:
            return

        items = []
        for logItem in self._buffer:
            item = self.logMessageToString(logMessage=logItem) + '\n'
            item = StringUtils.toStr2(item)
            items.append(item)

        for cb in self._writeCallbacks:
            try:
                cb(self, items)
            except Exception:
                pass

        if not self._logPath:
            self.clear()
            return

        elif self._logFile:
            try:
                out = StringUtils.toStr2('\n').join(items)
                exists = os.path.exists(self._logFile)
                with FileLock(self._logFile, 'a') as lock:
                    lock.file.write(out)
                    lock.release()

                try:
                    if not exists and not OsUtils.isWindows():
                        os.system('chmod 775 %s' % self._logFile)
                except Exception:
                    pass

            except Exception as err:
                print("LOGGER ERROR: Unable to write log file.")
                print(err)

        self.clear()
示例#27
0
文件: Logger.py 项目: sernst/PyAid
    def flush(self, **kwargs):
        if not self._buffer:
            return

        items = []
        for logItem in self._buffer:
            item = self.logMessageToString(logMessage=logItem) + '\n'
            item = StringUtils.toStr2(item)
            items.append(item)

        for cb in self._writeCallbacks:
            try:
                cb(self, items)
            except Exception:
                pass

        if not self._logPath:
            self.clear()
            return

        elif self._logFile:
            try:
                out = StringUtils.toStr2('\n').join(items)
                exists = os.path.exists(self._logFile)
                with FileLock(self._logFile, 'a') as lock:
                    lock.file.write(out)
                    lock.release()

                try:
                    if not exists and not OsUtils.isWindows():
                        os.system('chmod 775 %s' % self._logFile)
                except Exception:
                    pass

            except Exception as err:
                print("LOGGER ERROR: Unable to write log file.")
                print(err)

        self.clear()
示例#28
0
    def _handleKeyboardCallback(self, event):
        mod  = event.modifiers()
        mods = QtCore.Qt.ShiftModifier | QtCore.Qt.ControlModifier
        if mod != mods:
            if OsUtils.isMac():
                mods = QtCore.Qt.ShiftModifier | QtCore.Qt.MetaModifier
                if mod != mods:
                    return False
            else:
                return False

        op = self.windowOpacity()

        if event.key() in [QtCore.Qt.Key_Plus, QtCore.Qt.Key_Equal]:
            op = min(1.0, op + 0.2)
        elif event.key() in [QtCore.Qt.Key_Minus, QtCore.Qt.Key_Underscore]:
            op = max(0.2, op - 0.2)
        else:
            return False

        self.setWindowOpacity(op)
        return True
示例#29
0
    def _getRootResourcePath(cls, application):
        if cls.isDeployed:
            if OsUtils.isWindows():
                out = FileUtils.createPath(
                    appdirs.user_data_dir(application.appID, application.appGroupID),
                    'resources', isDir=True)
            else:
                out = FileUtils.createPath(
                    cls._ENV_PATH.split('/Resources/lib/')[0],
                    'Resources', 'resources', isDir=True)
        else:
            rootPath = application.debugRootResourcePath
            if not rootPath:
                return None
            elif isinstance(rootPath, basestring):
                rootPath = rootPath.replace('\\', '/').strip('/').split('/')

            out = FileUtils.createPath(
                application.applicationCodePath, *rootPath, isDir=True)

        if out and not os.path.exists(out):
            os.makedirs(out)
        return out
示例#30
0
    def checkEnvFile(cls, target, otherPaths =None):
        """Doc..."""
        pathSep   = OsUtils.getPerOsValue(';', ':')
        additions = cls._getSourcePaths(otherPaths=otherPaths)

        with open(target, 'r') as f:
            contents = f.read()

        result = cls._PYTHON_PATH_PATTERN.search(contents)
        if not result:
            return False

        paths = result.groupdict()['paths'].split(pathSep)
        for addition in additions:
            found = False
            for p in paths:
                p = FileUtils.cleanupPath(p, noTail=True)
                if p == FileUtils.cleanupPath(addition.folderPath, noTail=True):
                    found = True
                    break
            if not found:
                return False

        return True
示例#31
0
 def _joinPathEntries(cls, entries):
     out = []
     for entry in entries:
         out.append(entry.folderPath)
     return OsUtils.getPerOsValue(';', ':').join(out)
示例#32
0
 def modifyNodeCommand(cls, cmd):
     if OsUtils.isMac():
         return [
             'export',
             'PATH=%s:$PATH;' % StaticFlowEnvironment.nodePackageManagerPath] + cmd
     return cmd
示例#33
0
 def isWindows(cls):
     return OsUtils.isWindows()
示例#34
0
 def _joinPathEntries(cls, entries):
     out = []
     for entry in entries:
         out.append(entry.folderPath)
     return OsUtils.getPerOsValue(';', ':').join(out)
示例#35
0
    def modifyEnvFile(cls, target, install =True, test =False, otherPaths =None):
        """Doc..."""
        pathSep   = OsUtils.getPerOsValue(';', ':')
        removals  = []
        entries   = cls._getSourcePaths(otherPaths=otherPaths)
        additions = entries + []

        with open(target, 'r') as f:
            contents = f.read().strip()

        result = cls._PYTHON_PATH_PATTERN.search(contents)
        if not result:
            if install and not test:
                with open(target, 'w') as f:
                    f.write(
                        (contents + '\n' if contents else '') + 'PYTHONPATH='
                        + cls._joinPathEntries(additions) )
            return cls.MAYA_ENV_MODIFIED_RESULT_NT(additions if install else [], removals)

        paths = result.groupdict()['paths'].strip()
        paths = paths.split(pathSep) if paths else []
        if not paths and not install:
            return cls.MAYA_ENV_MODIFIED_RESULT_NT([], [])

        index = 0
        while index < len(paths):
            # Stop if no more additions remain
            if not additions:
                break

            p = FileUtils.cleanupPath(paths[index], noTail=True)

            # If path already exists don't add it again
            pathMatch = cls._hasPath(p, additions)
            if pathMatch:
                additions.remove(pathMatch)

                # If uninstalling add to removals
                if not install:
                    removals.append(pathMatch)
                    paths.remove(p)
                else:
                    index += 1
                continue
            elif not install:
                index += 1
                continue

            for entry in entries:
                testPath = FileUtils.createPath(p, entry.rootName, noTail=True)
                if os.path.exists(testPath):
                    paths.remove(p)

            index += 1

        for entry in additions:
            paths.append(entry.folderPath)

        insertion = ('PYTHONPATH=' + pathSep.join(paths) + '\n') if paths else ''
        contents  = contents[:result.start()] + insertion + contents[result.end():]

        result = cls.MAYA_ENV_MODIFIED_RESULT_NT(additions if install else [], removals)
        if test:
            return result

        with open(target, 'w') as f:
            f.write(contents)

        return result
示例#36
0
    def modifyEnvFile(cls, target, install=True, test=False, otherPaths=None):
        """Doc..."""
        pathSep = OsUtils.getPerOsValue(';', ':')
        removals = []
        entries = cls._getSourcePaths(otherPaths=otherPaths)
        additions = entries + []

        with open(target, 'r') as f:
            contents = f.read().strip()

        result = cls._PYTHON_PATH_PATTERN.search(contents)
        if not result:
            if install and not test:
                with open(target, 'w') as f:
                    f.write((contents + '\n' if contents else '') +
                            'PYTHONPATH=' + cls._joinPathEntries(additions))
            return cls.MAYA_ENV_MODIFIED_RESULT_NT(
                additions if install else [], removals)

        paths = result.groupdict()['paths'].strip()
        paths = paths.split(pathSep) if paths else []
        if not paths and not install:
            return cls.MAYA_ENV_MODIFIED_RESULT_NT([], [])

        index = 0
        while index < len(paths):
            # Stop if no more additions remain
            if not additions:
                break

            p = FileUtils.cleanupPath(paths[index], noTail=True)

            # If path already exists don't add it again
            pathMatch = cls._hasPath(p, additions)
            if pathMatch:
                additions.remove(pathMatch)

                # If uninstalling add to removals
                if not install:
                    removals.append(pathMatch)
                    paths.remove(p)
                else:
                    index += 1
                continue
            elif not install:
                index += 1
                continue

            for entry in entries:
                testPath = FileUtils.createPath(p, entry.rootName, noTail=True)
                if os.path.exists(testPath):
                    paths.remove(p)

            index += 1

        for entry in additions:
            paths.append(entry.folderPath)

        insertion = ('PYTHONPATH=' + pathSep.join(paths) +
                     '\n') if paths else ''
        contents = contents[:result.start()] + insertion + contents[result.end(
        ):]

        result = cls.MAYA_ENV_MODIFIED_RESULT_NT(additions if install else [],
                                                 removals)
        if test:
            return result

        with open(target, 'w') as f:
            f.write(contents)

        return result