示例#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 _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
    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
示例#4
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
示例#5
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
            )
    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
示例#7
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)
示例#8
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
示例#9
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)
示例#10
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
示例#11
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
示例#12
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
示例#13
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
示例#14
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
示例#15
0
 def modifyNodeCommand(cls, cmd):
     if OsUtils.isMac():
         return [
             'export',
             'PATH=%s:$PATH;' % StaticFlowEnvironment.nodePackageManagerPath] + cmd
     return cmd
示例#16
0
    def _runImpl(self):
        pd          = self._flexData
        useFlash    = pd.isPlatformActive(FlexProjectData.FLASH_PLATFORM)
        useAir      = pd.isPlatformActive(FlexProjectData.AIR_PLATFORM)
        useWindows  = pd.isPlatformActive(FlexProjectData.WINDOWS_PLATFORM) and OsUtils.isWindows()
        useMac      = pd.isPlatformActive(FlexProjectData.MAC_PLATFORM) and OsUtils.isMac()
        useAndroid  = pd.isPlatformActive(FlexProjectData.ANDROID_PLATFORM)
        useIOS      = pd.isPlatformActive(FlexProjectData.IOS_PLATFORM)

        # In cases where nothing was set (usual because debugging will be run on the default
        # platform) pick the platform to compile if such a platform exists
        useAny = useFlash or useAir or useWindows or useMac or useAndroid or useIOS
        if not useAny:
            if pd.hasPlatform(FlexProjectData.AIR_PLATFORM):
                useAir = True
            elif pd.hasPlatform(FlexProjectData.WINDOWS_PLATFORM) and OsUtils.isWindows():
                useWindows = True
            elif pd.hasPlatform(FlexProjectData.MAC_PLATFORM) and OsUtils.isMac():
                useMac = True
            elif pd.hasPlatform(FlexProjectData.FLASH_PLATFORM):
                useFlash = True
            elif pd.hasPlatform(FlexProjectData.ANDROID_PLATFORM):
                useAndroid = True
            elif pd.hasPlatform(FlexProjectData.IOS_PLATFORM):
                useIOS = True
            else:
                self._runComplete(1)
                return

        q = self._queue

        if useFlash:
            pid = FlexProjectData.FLASH_PLATFORM
            q.append([self._doCompile, pid, 'Flash SWF Compiled'])
            if self._uploadAfterPackage:
                q.append([self._doUpload, pid, 'Flash'])

        if useAir:
            pid = FlexProjectData.AIR_PLATFORM
            q.append([self._doCompile, pid, 'Air SWF Compiled'])
            q.append([self._doPackage, pid, 'Air Packaged'])
            if self._uploadAfterPackage:
                q.append([self._doUpload, pid, 'Air'])

        if useWindows:
            pid = FlexProjectData.WINDOWS_PLATFORM
            q.append([self._doCompile, pid, 'Windows SWF Compiled'])
            q.append([self._doPackage, pid, 'Windows Packaged'])
            if self._uploadAfterPackage:
                q.append([self._doUpload, pid, 'Windows'])

        if useMac:
            pid = FlexProjectData.MAC_PLATFORM
            q.append([self._doCompile, pid, 'Mac SWF Compiled'])
            q.append([self._doPackage, pid, 'Mac Packaged'])
            if self._uploadAfterPackage:
                q.append([self._doUpload, pid, 'Mac'])

        if useAndroid:
            pid = FlexProjectData.ANDROID_PLATFORM
            q.append([self._doCompile, pid, 'Android SWF Compiled'])
            q.append([self._doPackage, pid, 'Android Packaged'])
            if self._uploadAfterPackage:
                q.append([self._doUpload, pid, 'Android'])

        if useIOS:
            pid = FlexProjectData.IOS_PLATFORM
            q.append([self._doCompile, pid, 'iOS SWF Compiled'])
            q.append([self._doPackage, pid, 'iOS Packaged'])
            if self._uploadAfterPackage:
                q.append([self._doUpload, pid, 'iOS'])

        self._isProcessingQueue = True
        while self._queue:
            if self._isAbortingQueue:
                self._runComplete(1)
                return

            if not self._isProcessingQueue:
                time.sleep(1)
                continue

            # Get the first item in the list and execute it
            try:
                item = self._queue.pop(0)
                item[0](item[1], item[2])
            except Exception, err:
                self._log.writeError('Failed Compilation/Package Step', err)
                self._runComplete(1)
                return