示例#1
0
    def __init__(self, parent =None, **kwargs):
        """Creates a new instance of PySideGui."""
        flags = ArgsUtils.extract('flags', None, kwargs)
        if flags is None:
            # By default the close button is hidden (only title shows)
            flags = QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint

        title          = ArgsUtils.extract('title', 'Dialog', kwargs)
        modal          = ArgsUtils.extract('modal', True, kwargs)
        widgetClass    = ArgsUtils.extract('widget', None, kwargs)
        self._callback = ArgsUtils.extract('callback', None, kwargs)
        self._canceled = True

        QtGui.QDialog.__init__(self, parent, flags)

        self.setStyleSheet(self.owner.styleSheetPath)
        if widgetClass is None:
            self._widget = None
        else:
            layout       = self._getLayout(self)
            self._widget = widgetClass(parent=self, **kwargs)
            layout.addWidget(self._widget)

        self.setModal(modal)
        self.setWindowTitle(title)
    def __init__(self, parent, path, session=None, **kwargs):
        """Creates a new instance of TrackImporterRemoteThread."""
        self._pretty = ArgsUtils.extract("pretty", False, kwargs)
        self._gzipped = ArgsUtils.extract("compressed", True, kwargs)
        self._difference = ArgsUtils.extract("difference", True, kwargs)

        RemoteExecutionThread.__init__(self, parent, **kwargs)

        self._path = path
        self._session = session
示例#3
0
    def __init__(self, source, **kwargs):

        self.footerDom  = u''
        self.page       = ArgsUtils.get('page', None, kwargs)
        self.site       = ArgsUtils.get('site', None, kwargs)

        self.filePath = ArgsUtils.get('path', None, kwargs)
        self.filename = ArgsUtils.get(
            'filename',
            os.path.basename(self.filePath) if self.filePath else None,
            kwargs)

        debugData = ArgsUtils.extract('debugData', None, kwargs)
        blocks    = {
            'root':[
                MarkupTextBlockUtils.createMarkupCommentDef(BlockDefinition.BLOCKED),
                MarkupTextBlockUtils.createMarkupOpenDef('quote'),
                MarkupTextBlockUtils.createMarkupCloseDef(BlockDefinition.BLOCKED) ],
            'quote':[
                BlockDefinition.createQuoteDef(BlockDefinition.BLOCKED),
                BlockDefinition.createLiteralDef(BlockDefinition.BLOCKED) ]}

        self._renderErrors = []
        self._tagIndex     = -1

        super(MarkupProcessor, self).__init__(
            source,
            ArgsUtils.extract('debug', False, kwargs),
            blocks,
            debugData,
            stripSource=False,
            **kwargs)

        self.logger.trace       = True
        self._result            = None
        self._anchors           = []
        self._tags              = []
        self._id                = StringUtils.getRandomString(8)
        self._css               = []
        self._js                = []
        self._radioArrays       = dict()
        self._patterns          = dict()
        self._groups            = dict()
        self._metadata          = ArgsUtils.getAsDict('metadata', kwargs)
        self._libraryIDs        = []
        self._autoTitle         = u''
        self._autoDescription   = u''
        self._allowModelCaching = False

        self.privateView = False
示例#4
0
    def __init__(self, parent, **kwargs):
        RemoteExecutionThread.__init__(self, parent, explicitComplete=True, **kwargs)
        self._pausePackageSteps     = ArgsUtils.extract('pausePackageSteps', False, kwargs)
        self._uploadAfterPackage    = ArgsUtils.extract('uploadAfterPackage', False, kwargs)
        self._flexData              = FlexProjectData(**kwargs)
        self._queue                 = []
        self._isProcessingQueue     = False
        self._isAbortingQueue       = False
        self._bucket                = None
        self._output                = dict()

        if self._uploadAfterPackage:
            self._output['urls'] = dict()
            self._bucket = self._flexData.createBucket()
示例#5
0
 def __init__(self, parent, url, args =None, **kwargs):
     """Creates a new instance of Request."""
     self._localData = ArgsUtils.extract('localData', None, kwargs)
     self._dead      = ArgsUtils.extract('dead', False, kwargs)
     QObject.__init__(self, parent, **kwargs)
     self._url       = url
     self._owner     = parent
     self._log       = parent.log if parent else Logger(self)
     self._callback  = None
     self._args      = args
     self._request   = None
     self._result    = None
     self._sent      = False
     self._async     = False
示例#6
0
文件: __init__.py 项目: sernst/Nimble
def runPythonExec(script, kwargs =None):
    from nimble.NimbleEnvironment import NimbleEnvironment
    from nimble.data.NimbleResponseData import NimbleResponseData
    from nimble.data.enum.DataKindEnum import DataKindEnum

    try:
        nimble.cmds.undoInfo(openChunk=True)
    except Exception as err:
        return False

    try:
        # Create a new, temporary module in which to run the script
        module = imp.new_module('runExecTempModule')

        # Initialize the script with script inputs
        setattr(module, NimbleEnvironment.REMOTE_KWARGS_KEY, kwargs if kwargs is not None else dict())
        setattr(module, NimbleEnvironment.REMOTE_RESULT_KEY, dict())

        # Executes the script in the new module
        exec_(script, module.__dict__)

        # Find a NimbleScriptBase derived class definition and if it exists, run it to populate the
        # results
        for name,value in Reflection.getReflectionDict(module).iteritems():
            if not inspect.isclass(value):
                continue

            if NimbleScriptBase in value.__bases__:
                getattr(module, name)().run()
                break

        # Retrieve the results object that contains all results set by the execution of the script
        result = getattr(module, NimbleEnvironment.REMOTE_RESULT_KEY)
    except Exception as err:
        logger = Logger('runPythonExec', printOut=True)
        logger.writeError('ERROR: Failed Remote Script Execution', err)
        result = NimbleResponseData(
            kind=DataKindEnum.PYTHON_SCRIPT,
            response=NimbleResponseData.FAILED_RESPONSE,
            error=str(err) )

    # If a result dictionary contains an error key format the response as a failure
    try:
        errorMessage = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
        if errorMessage:
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_SCRIPT,
                response=NimbleResponseData.FAILED_RESPONSE,
                error=errorMessage,
                payload=result)
    except Exception as err:
        pass

    try:
        nimble.cmds.undoInfo(closeChunk=True)
    except Exception as err:
        return False

    return result
示例#7
0
    def __init__(self, *args, **kwargs):
        """Creates a new instance of ListDataOrganizer."""
        root = ArgsUtils.extract('root', None, kwargs, args, 0)
        if isinstance(root, basestring):
            root = [root]

        super(ListDataOrganizer, self).__init__(list, root, **kwargs)
示例#8
0
    def __init__(self, **kwargs):
        """Creates a new instance of MarkupTagError."""

        self._errorAtEnd = ArgsUtils.extract("errorAtEnd", False, kwargs)

        ArgsUtils.addIfMissing("errorDef", self.READ_FAILURE, kwargs, True)
        MarkupError.__init__(self, **kwargs)
示例#9
0
    def __init__(self, parent=None, **kwargs):
        """Creates a new instance of PyGlassWebKitWidget."""
        self._communicator = ArgsUtils.extract("communicator", None, kwargs)
        self._debug = ArgsUtils.extract("debug", False, kwargs)
        url = ArgsUtils.extract("url", None, kwargs)
        localUrl = ArgsUtils.extract("localUrl", None, kwargs)
        PyGlassWidget.__init__(self, parent, widgetFile=False, **kwargs)

        layout = self._getLayout(self, QtGui.QVBoxLayout)
        layout.setContentsMargins(0, 0, 0, 0)

        self._webView = PyGlassWebView(self, communicator=self._communicator, debug=self._debug)
        layout.addWidget(self._webView)
        self.setLayout(layout)

        if url:
            self._webView.openUrl(url)
        elif localUrl:
            self._webView.openLocalWebUrl(url)
示例#10
0
文件: Request.py 项目: sernst/PyGlass
    def send(self, cls, *args, **kwargs):
        """ Sends an API request to the cloud servers and handles the response. This can be sent
            either synchronously or asynchronously depending on whether or not a callback argument
            is included in the request. Asynchronous requests must be handled within the context
            of a running PySide application loop, as the threading is managed by PySide. """

        callback = ArgsUtils.extract('callback', None, kwargs, args, 0)
        if self:
            return self._sendRequest(callback=callback, **kwargs)
        return cls._createAndSend(callback=callback, **kwargs)
示例#11
0
    def __init__(self, parent, path, importType, session =None, analysisSession =None, **kwargs):
        """Creates a new instance of TrackImporterRemoteThread."""
        self._compressed = ArgsUtils.extract('compressed', False, kwargs)

        RemoteExecutionThread.__init__(self, parent, **kwargs)
        self._path       = path
        self._session    = session
        self._analysisSession = analysisSession
        self._importType = importType
        self._verbose    = ArgsUtils.get('verbose', True, kwargs)
示例#12
0
 def __init__(self, parent =None, *args, **kwargs):
     """Creates a new instance of StyledLabel."""
     self._fontFamily    = ArgsUtils.extract('fontFamily', None, kwargs)
     self._fontSize      = ArgsUtils.extract('fontSize', None, kwargs)
     self._color         = ArgsUtils.extract('color', None, kwargs)
     self._fontWeight    = ArgsUtils.extract('fontWeight', None, kwargs)
     self._isItalic      = ArgsUtils.extract('isItalic', None, kwargs)
     self._isBold        = ArgsUtils.extract('isBold', None, kwargs)
     self._isBorderless  = ArgsUtils.extract('isBorderless', True, kwargs)
     super(StyledLabel, self).__init__(parent, *args, **kwargs)
示例#13
0
    def __init__(self, parent, toggles =False, clickOn =False, **kwargs):
        """Creates a new instance of InteractiveElement."""
        self._clickCallback = ArgsUtils.extract('callback', None, kwargs)
        super(InteractiveElement, self).__init__(parent, **kwargs)

        self._toggles      = toggles
        self._clickOn      = clickOn
        self._checked      = False
        self._mode         = InteractionStatesEnum.NORMAL_MODE
        self._mouseEnabled = True

        c = QtGui.QCursor()
        c.setShape(QtCore.Qt.PointingHandCursor)
        self.setCursor(c)
示例#14
0
    def createReply(cls, kind, result, errorMessage=None):
        payload = result if isinstance(result, dict) else {"result": result}
        warnings = ArgsUtils.extract(NimbleEnvironment.REMOTE_RESULT_WARNING_KEY, None, payload)

        if errorMessage:
            return NimbleResponseData(
                kind=kind,
                response=NimbleResponseData.FAILED_RESPONSE,
                warnings=warnings,
                error=errorMessage,
                payload=payload,
            )

        return NimbleResponseData(
            kind=kind, warnings=warnings, response=NimbleResponseData.SUCCESS_RESPONSE, payload=payload
        )
示例#15
0
    def createReply(cls, kind, result, errorMessage=None):
        payload = result if isinstance(result, dict) else {'result': result}
        warnings = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_WARNING_KEY, None, payload)

        if errorMessage:
            return NimbleResponseData(
                kind=kind,
                response=NimbleResponseData.FAILED_RESPONSE,
                warnings=warnings,
                error=errorMessage,
                payload=payload)

        return NimbleResponseData(kind=kind,
                                  warnings=warnings,
                                  response=NimbleResponseData.SUCCESS_RESPONSE,
                                  payload=payload)
示例#16
0
    def _deployWalker(self, args, path, names):
        """Doc..."""

        # Skip CDN file uploads when not walking the CDN root path explicitly
        if not args['cdn'] and path.find(StaticFlowEnvironment.CDN_ROOT_PREFIX) != -1:
            return

        for name in names:
            namePath = FileUtils.createPath(path, name)
            if os.path.isdir(namePath) or StringUtils.ends(name, self._SKIP_EXTENSIONS):
                continue

            headersPath = namePath + '.headers'
            if os.path.exists(headersPath):
                headers = JSON.fromFile(headersPath)
            else:
                headers = dict()

            if self._forceAll:
                lastModified = None
            elif self._forceHtml and StringUtils.ends(name, self._FORCE_HTML_EXTENSIONS):
                lastModified = None
            else:
                lastModified = ArgsUtils.extract('_LAST_MODIFIED', None, headers)
                if lastModified:
                    lastModified = TimeUtils.webTimestampToDateTime(lastModified)

            kwargs = dict(
                key=u'/' + namePath[len(self._localRootPath):].replace(u'\\', u'/').strip(u'/'),
                maxAge=headers.get('max-age', -1),
                eTag=headers.get('eTag', None),
                expires=headers.get('Expires'),
                newerThanDate=lastModified,
                policy=S3Bucket.PUBLIC_READ)

            if StringUtils.ends(name, self._STRING_EXTENSIONS):
                result = self._bucket.put(
                    contents=FileUtils.getContents(namePath),
                    zipContents=True,
                    **kwargs)
            else:
                result = self._bucket.putFile(filename=namePath, **kwargs)

            if result:
                self._logger.write(u'DEPLOYED: ' + unicode(namePath) + u'->' + unicode(kwargs['key']))
示例#17
0
    def runPythonImport(cls, payload):
        try:
            kwargs       = payload.get('kwargs', {})
            targetModule = StringUtils.toStr2(payload.get('module'))
            targetMethod = StringUtils.toStr2(payload.get('method'))
            targetClass  = StringUtils.toStr2(payload.get('class'))
            target       = targetClass if targetClass is not None else targetMethod
            if target is None:
                parts        = targetModule.rsplit('.', 1)
                targetModule = parts[0]
                target       = parts[1]
        except Exception as err:
            NimbleEnvironment.logError([
                'ERROR: Failed to parse python import payload',
                'PAYLOAD: ' + DictUtils.prettyPrint(payload)], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError('\n'.join([
                    'ERROR: Failed to parse python import payload',
                    'PAYLOAD: ' + DictUtils.prettyPrint(payload)]), err),
                response=NimbleResponseData.FAILED_RESPONSE)

        # Dynamically import the specified module and reload it to make sure any changes have
        # been updated
        try:
            module = __import__(
                StringUtils.toStr2(targetModule),
                globals(), locals(),
                [StringUtils.toStr2(target)] if target else [])
            reload(module)
            target = getattr(module, target)
        except Exception as err:
            NimbleEnvironment.logError([
                'ERROR: Failed to import python target',
                'MODULE: %s' % targetModule,
                'TARGET: %s' % target,
                'PAYLOAD: ' + DictUtils.prettyPrint(payload)], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError(
                    'Failed to import python module', err),
                response=NimbleResponseData.FAILED_RESPONSE)

        try:
            result = dict()
            if targetClass is not None:
                tc = target()
                result = getattr(tc, targetMethod)(**kwargs) \
                    if targetMethod else \
                    tc(**kwargs)
            elif targetMethod is not None:
                result = target(**kwargs)
            else:
                # Find a NimbleScriptBase derived class definition and if it exists, run it to
                # populate the results
                for name,value in DictUtils.iter(Reflection.getReflectionDict(target)):
                    if not inspect.isclass(value):
                        continue

                    if NimbleScriptBase in value.__bases__:
                        result = getattr(target, name)()(**kwargs)
                        found  = True

            # If a result dictionary contains an error key format the response as a failure
            errorMessage = None
            try:
                errorMessage = ArgsUtils.extract(
                    NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
            except Exception as err:
                pass

            return cls.createReply(DataKindEnum.PYTHON_IMPORT, result, errorMessage=errorMessage)
        except Exception as err:
            msg = 'ERROR: Failed to execute remote script'
            NimbleEnvironment.logError([
                msg,
                'PAYLOAD: ' + DictUtils.prettyPrint(payload),
                'TARGET: ' + str(target)], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError(msg, err),
                response=NimbleResponseData.FAILED_RESPONSE)
 def __init__(self, *args, **kwargs):
     """Creates a new instance of SingleAttributeDataOrganizer."""
     self._name = ArgsUtils.extract('name', None, kwargs, args, 0)
     root       = ArgsUtils.extract('root', None, kwargs, args, 1)
     super(SingleAttributeDataOrganizer, self).__init__(root=root, **kwargs)
示例#19
0
 def __init__(self, parent, **kwargs):
     """Creates a new instance of AirDebugThread."""
     RemoteExecutionThread.__init__(self, parent, **kwargs)
     self._log.trace = True
     projectPath     = ArgsUtils.extract('projectPath', None, kwargs)
     self._projectData  = FlexProjectData(projectPath, **kwargs)
 def __init__(self, *args, **kwargs):
     """Creates a new instance of SingleValuedAttributeDataOrganizer."""
     self._name = ArgsUtils.extract('name', '', kwargs, args, 0)
     root       = ArgsUtils.extract('root', None, kwargs, args, 1)
     SingleValuedDataOrganizer.__init__(self, root, **kwargs)
示例#21
0
 def __init__(self, *args, **kwargs):
     """Creates a new instance of KeyDataOrganizer."""
     root = ArgsUtils.extract('root', None, kwargs, args, 0)
     super(KeyDataOrganizer, self).__init__(dict, root, **kwargs)
示例#22
0
 def __init__(self, *args, **kwargs):
     """Creates a new instance of AttributeDataOrganizer."""
     root         = ArgsUtils.extract('root', None, kwargs, args, 0)
     self._prefix = ArgsUtils.extract('prefix', '', kwargs, args, 1)
     KeyDataOrganizer.__init__(self, root, **kwargs)
示例#23
0
    def runPythonImport(cls, payload):
        try:
            kwargs = payload.get('kwargs', {})
            targetModule = StringUtils.toStr2(payload.get('module'))
            targetMethod = StringUtils.toStr2(payload.get('method'))
            targetClass = StringUtils.toStr2(payload.get('class'))
            target = targetClass if targetClass is not None else targetMethod
            if target is None:
                parts = targetModule.rsplit('.', 1)
                targetModule = parts[0]
                target = parts[1]
        except Exception as err:
            NimbleEnvironment.logError([
                'ERROR: Failed to parse python import payload',
                'PAYLOAD: ' + DictUtils.prettyPrint(payload)
            ], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError(
                    '\n'.join([
                        'ERROR: Failed to parse python import payload',
                        'PAYLOAD: ' + DictUtils.prettyPrint(payload)
                    ]), err),
                response=NimbleResponseData.FAILED_RESPONSE)

        # Dynamically import the specified module and reload it to make sure any changes have
        # been updated
        try:
            module = __import__(StringUtils.toStr2(targetModule), globals(),
                                locals(),
                                [StringUtils.toStr2(target)] if target else [])
            reload(module)
            target = getattr(module, target)
        except Exception as err:
            NimbleEnvironment.logError([
                'ERROR: Failed to import python target',
                'MODULE: %s' % targetModule,
                'TARGET: %s' % target,
                'PAYLOAD: ' + DictUtils.prettyPrint(payload)
            ], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError('Failed to import python module',
                                            err),
                response=NimbleResponseData.FAILED_RESPONSE)

        try:
            result = dict()
            if targetClass is not None:
                tc = target()
                result = getattr(tc, targetMethod)(**kwargs) \
                    if targetMethod else \
                    tc(**kwargs)
            elif targetMethod is not None:
                result = target(**kwargs)
            else:
                # Find a NimbleScriptBase derived class definition and if it exists, run it to
                # populate the results
                for name, value in DictUtils.iter(
                        Reflection.getReflectionDict(target)):
                    if not inspect.isclass(value):
                        continue

                    if NimbleScriptBase in value.__bases__:
                        result = getattr(target, name)()(**kwargs)
                        found = True

            # If a result dictionary contains an error key format the response as a failure
            errorMessage = None
            try:
                errorMessage = ArgsUtils.extract(
                    NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
            except Exception as err:
                pass

            return cls.createReply(DataKindEnum.PYTHON_IMPORT,
                                   result,
                                   errorMessage=errorMessage)
        except Exception as err:
            msg = 'ERROR: Failed to execute remote script'
            NimbleEnvironment.logError([
                msg, 'PAYLOAD: ' + DictUtils.prettyPrint(payload),
                'TARGET: ' + str(target)
            ], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError(msg, err),
                response=NimbleResponseData.FAILED_RESPONSE)
示例#24
0
 def __init__(self, *args, **kwargs):
     """Creates a new instance of DataListWidgetItem."""
     self._itemData = ArgsUtils.extract('data', None, kwargs)
     self._itemId   = ArgsUtils.extract('ident', None, kwargs)
     super(DataListWidgetItem, self).__init__(*args, **kwargs)
示例#25
0
    def __init__(self, **kwargs):
        """Creates a new instance of PyGlassWindow."""
        parent                  = ArgsUtils.extract('parent', None, kwargs)
        self._application       = ArgsUtils.extract('pyGlassApp', None, kwargs)
        self._qApplication      = ArgsUtils.extract('qApp', None, kwargs)
        self._isMainWindow      = ArgsUtils.extract('isMainWindow', bool(parent is None), kwargs)
        self._mainWindow        = ArgsUtils.extract('mainWindow', None, kwargs)
        self._appWrappingWidget = None
        self._centerWidget      = None
        self._hasShown          = False
        self._isHighDpi         = OsUtils.isHighDpiScaledScreen()
        self._settings          = ConfigsDict()

        self._appLevelWidgets              = dict()
        self._appLevelWidgetDisplayHistory = []

        self._keyboardCallback = ArgsUtils.extract('keyboardCallback', None, kwargs)

        if not self._mainWindow:
            if self._isMainWindow:
                self._mainWindow = self
            elif self._application:
                self._mainWindow = self._application.mainWindow

        self._dependentWindows = []
        self._currentWidget    = None

        QtGui.QMainWindow.__init__(self, parent, ArgsUtils.extract('flags', 0, kwargs))

        self._instanceUid = TimeUtils.getUidTimecode(
            prefix=self.__class__.__name__,
            suffix=StringUtils.getRandomString(8))

        self._styleSheet = kwargs.get('styleSheet', None)
        if self._styleSheet:
            self.setStyleSheet(self.styleSheetPath)

        if self._keyboardCallback is not None:
            self.setFocusPolicy(QtCore.Qt.StrongFocus)

        if self._isMainWindow:
            self._log                 = Logger(self, printOut=True)
            self._config              = ApplicationConfig(self)
            self._commonConfig        = ApplicationConfig(self, common=True)
            self._resourceFolderParts = PyGlassGuiUtils.getResourceFolderParts(self)

            icon = PyGlassGuiUtils.createIcon(
                kwargs.get('iconsPath', self.getAppResourcePath('icons', isDir=True)) )
            if icon:
                self.setWindowIcon(icon)

        elif self._mainWindow:
            icon = self._mainWindow.windowIcon()
            if icon:
                self.setWindowIcon(icon)

        self._appWrappingWidget = VisibilityElement(self)
        layout = QtGui.QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self._appWrappingWidget.setLayout(layout)

        self._contentWrappingWidget = self.addApplicationLevelWidget('main')
        layout = QtGui.QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self._contentWrappingWidget.setLayout(layout)

        # Loads the ui file if it exists
        externalCentralParent = None
        hasWindowFile = kwargs.get('mainWindowFile', False)
        if hasWindowFile == self:
            UiFileLoader.loadWidgetFile(self)
            externalCentralParent = getattr(self, 'windowContainer')
            if externalCentralParent:
                externalLayout = externalCentralParent.layout()
                if not externalLayout:
                    externalLayout = QtGui.QVBoxLayout()
                    externalLayout.setContentsMargins(0, 0, 0, 0)
                    externalLayout.setSpacing(0)
                    externalCentralParent.setLayout(externalLayout)

        if externalCentralParent:
            self._appWrappingWidget.setParent(externalCentralParent)
            externalLayout.addWidget(self._appWrappingWidget)
        else:
            self.setCentralWidget(self._appWrappingWidget)

        # Sets a non-standard central widget
        centralWidgetName = kwargs.get('centralWidgetName')
        if centralWidgetName and hasattr(self, centralWidgetName):
            self._centerWidget = getattr(self, centralWidgetName)
        elif hasWindowFile and not hasWindowFile == self:
            if not self._centerWidget:
                self._createCentralWidget()
            UiFileLoader.loadWidgetFile(self, target=self._centerWidget)
        elif not hasWindowFile:
            self._centerWidget = None

        if not self._centerWidget and kwargs.get('defaultCenterWidget', True):
            self._createCentralWidget()

        self._lastChildWidgetID  = None
        self._widgetParent  = None
        self._widgets       = None
        self._widgetFlags   = None

        self._widgetClasses = kwargs.get('widgets', dict())
        if self._widgetClasses:
            self._initializeWidgetChildren()

        self.setWindowTitle(kwargs.get('title', self._createTitleFromClass()))
        self.updateStatusBar()
示例#26
0
文件: FileUtils.py 项目: sernst/PyAid
    def _listPath(cls, rootPath, recursive, **kwargs):
        allowDots       = kwargs.get('allowDots', True)
        rootPath        = cls.cleanupPath(rootPath, isDir=True)
        listFiles       = kwargs.get('listFiles', True)
        listDirs        = kwargs.get('listDirs', False)
        skipSVN         = kwargs.get('skipSVN', True)
        skips           = kwargs.get('skips', None)

        absolute        = kwargs.get('absolute', True)
        pieces          = kwargs.get('pieces', False)

        topPath         = ArgsUtils.extract('topPath', rootPath, kwargs)
        allowExtensions = ArgsUtils.getAsList('allowExtensions', kwargs)
        skipExtensions  = ArgsUtils.getAsList('skipExtensions', kwargs)

        out = []
        for item in os.listdir(rootPath):
            if not allowDots and item.startswith('.'):
                continue

            if (skipSVN and item == '.svn') or (skips and item in skips):
                continue

            absItem = os.path.join(rootPath, item)
            if os.path.isdir(absItem):
                path = absItem + os.sep
                if listDirs:
                    out.append(path if absolute else item)
                absItem = None

                if recursive:
                    out += cls._listPath(
                        rootPath=path,
                        recursive=recursive,
                        topPath=topPath, **kwargs)

            elif os.path.isfile(absItem):
                skip = skipExtensions and StringUtils.ends(item, skipExtensions)
                if not listFiles or skip:
                    continue

                if allowExtensions and not StringUtils.ends(item, allowExtensions):
                    continue

            if not absItem:
                continue

            if not pieces and not absolute:
                out.append(item)
                continue

            relativeItem = absItem[len(topPath):].strip(os.sep).split(os.sep)
            if absolute:
                relativeItem.insert(0, topPath)

            if pieces:
                out.append(relativeItem)
            else:
                out.append(os.path.join(*relativeItem))

        return out
示例#27
0
    def __init__(self, **kwargs):
        """Creates a new instance of PyGlassWindow."""
        parent = ArgsUtils.extract('parent', None, kwargs)
        self._application  = ArgsUtils.extract('pyGlassApp', None, kwargs)
        self._qApplication = ArgsUtils.extract('qApp', None, kwargs)
        self._isMainWindow = ArgsUtils.extract('isMainWindow', bool(parent is None), kwargs)
        self._mainWindow   = ArgsUtils.extract('mainWindow', None, kwargs)
        self._centerWidget = None

        self._keyboardCallback = ArgsUtils.extract('keyboardCallback', None, kwargs)

        if not self._mainWindow:
            if self._isMainWindow:
                self._mainWindow = self
            elif self._application:
                self._mainWindow = self._application.mainWindow

        self._dependentWindows = []
        self._currentWidget    = None

        QtGui.QMainWindow.__init__(self, parent, ArgsUtils.extract('flags', 0, kwargs))

        if self._keyboardCallback is not None:
            self.setFocusPolicy(QtCore.Qt.StrongFocus)

        if self._isMainWindow:
            self._log                 = Logger(self, printOut=True)
            self._config              = ApplicationConfig(self)
            self._commonConfig        = ApplicationConfig(self, common=True)
            self._resourceFolderParts = PyGlassGuiUtils.getResourceFolderParts(self)

            icon = PyGlassGuiUtils.createIcon(
                ArgsUtils.get('iconsPath', self.getAppResourcePath('icons', isDir=True), kwargs) )
            if icon:
                self.setWindowIcon(icon)

        elif self._mainWindow:
            icon = self._mainWindow.windowIcon()
            if icon:
                self.setWindowIcon(icon)

        # Loads the ui file if it exists
        hasWindowFile = ArgsUtils.get('mainWindowFile', False, kwargs)
        if hasWindowFile:
            if not self._centerWidget:
                self._createCentralWidget()
            UiFileLoader.loadWidgetFile(self, target=self._centerWidget)

        self._styleSheet = ArgsUtils.get('styleSheet', None, kwargs)
        if self._styleSheet:
            self.setStyleSheet(self.styleSheetPath)

        # Sets a non-standard central widget
        centralWidgetName = ArgsUtils.get('centralWidgetName', None, kwargs)
        if centralWidgetName and hasattr(self, centralWidgetName):
            self._centerWidget = getattr(self, centralWidgetName)
        elif not hasWindowFile:
            self._centerWidget = None
            if ArgsUtils.get('defaultCenterWidget', False, kwargs):
                self._createCentralWidget()

        self._lastWidgetID  = None
        self._widgetParent  = None
        self._widgets       = None
        self._widgetFlags   = None

        self._widgetClasses = ArgsUtils.get('widgets', None, kwargs)
        if self._widgetClasses:
            self._initializeWidgetChildren()
        else:
            self._widgetClasses = dict()

        self.setWindowTitle(ArgsUtils.get('title', self._createTitleFromClass(), kwargs))
        self.updateStatusBar()
 def __init__(self, *args, **kwargs):
     """Creates a new instance of SingleValuedDataOrganizer."""
     root     = ArgsUtils.extract('root', None, kwargs, args, 0)
     DomDataOrganizer.__init__(self, unicode, root, **kwargs)
示例#29
0
 def _createAndSend(cls, parent, url, callback =None, args =None, **kwargs):
     dead = ArgsUtils.extract('dead', False, kwargs)
     req  = Request(parent=parent, url=url, args=args, dead=dead, **kwargs)
     if dead:
         return req.dead
     return req.send(callback)
示例#30
0
 def __init__(self, id, url, **kwargs):
     """Creates a new instance of ViewRedirect."""
     self.url          = url
     self.windowTarget = ArgsUtils.extract('windowTarget', '_blank', kwargs)
     super(ViewRedirect, self).__init__(id=id, **kwargs)
示例#31
0
    def _listPath(cls, rootPath, recursive, **kwargs):
        allowDots = kwargs.get('allowDots', True)
        rootPath = cls.cleanupPath(rootPath, isDir=True)
        listFiles = kwargs.get('listFiles', True)
        listDirs = kwargs.get('listDirs', False)
        skipSVN = kwargs.get('skipSVN', True)
        skips = kwargs.get('skips', None)

        absolute = kwargs.get('absolute', True)
        pieces = kwargs.get('pieces', False)

        topPath = ArgsUtils.extract('topPath', rootPath, kwargs)
        allowExtensions = ArgsUtils.getAsList('allowExtensions', kwargs)
        skipExtensions = ArgsUtils.getAsList('skipExtensions', kwargs)

        out = []
        for item in os.listdir(rootPath):
            if not allowDots and item.startswith('.'):
                continue

            if (skipSVN and item == '.svn') or (skips and item in skips):
                continue

            absItem = os.path.join(rootPath, item)
            if os.path.isdir(absItem):
                path = absItem + os.sep
                if listDirs:
                    out.append(path if absolute else item)
                absItem = None

                if recursive:
                    out += cls._listPath(rootPath=path,
                                         recursive=recursive,
                                         topPath=topPath,
                                         **kwargs)

            elif os.path.isfile(absItem):
                skip = skipExtensions and StringUtils.ends(
                    item, skipExtensions)
                if not listFiles or skip:
                    continue

                if allowExtensions and not StringUtils.ends(
                        item, allowExtensions):
                    continue

            if not absItem:
                continue

            if not pieces and not absolute:
                out.append(item)
                continue

            relativeItem = absItem[len(topPath):].strip(os.sep).split(os.sep)
            if absolute:
                relativeItem.insert(0, topPath)

            if pieces:
                out.append(relativeItem)
            else:
                out.append(os.path.join(*relativeItem))

        return out
示例#32
0
def runPythonExec(script, kwargs=None):
    from nimble.NimbleEnvironment import NimbleEnvironment
    from nimble.data.NimbleResponseData import NimbleResponseData
    from nimble.data.enum.DataKindEnum import DataKindEnum

    try:
        nimble.cmds.undoInfo(openChunk=True)
    except Exception as err:
        return False

    try:
        # Create a new, temporary module in which to run the script
        module = imp.new_module('runExecTempModule')

        # Initialize the script with script inputs
        setattr(module, NimbleEnvironment.REMOTE_KWARGS_KEY,
                kwargs if kwargs is not None else dict())
        setattr(module, NimbleEnvironment.REMOTE_RESULT_KEY, dict())

        # Executes the script in the new module
        exec_(script, module.__dict__)

        # Find a NimbleScriptBase derived class definition and if it exists, run it to populate the
        # results
        for name, value in Reflection.getReflectionDict(module).iteritems():
            if not inspect.isclass(value):
                continue

            if NimbleScriptBase in value.__bases__:
                getattr(module, name)().run()
                break

        # Retrieve the results object that contains all results set by the execution of the script
        result = getattr(module, NimbleEnvironment.REMOTE_RESULT_KEY)
    except Exception as err:
        logger = Logger('runPythonExec', printOut=True)
        logger.writeError('ERROR: Failed Remote Script Execution', err)
        result = NimbleResponseData(
            kind=DataKindEnum.PYTHON_SCRIPT,
            response=NimbleResponseData.FAILED_RESPONSE,
            error=str(err))

    # If a result dictionary contains an error key format the response as a failure
    try:
        errorMessage = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
        if errorMessage:
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_SCRIPT,
                response=NimbleResponseData.FAILED_RESPONSE,
                error=errorMessage,
                payload=result)
    except Exception as err:
        pass

    try:
        nimble.cmds.undoInfo(closeChunk=True)
    except Exception as err:
        return False

    return result