예제 #1
0
 def getFromDefaults(self):
     self.w.clearOutPut.set(getDefault("DrawBotClearOutput", True))
     self.w.liveOutPut.set(getDefault("DrawButLiveUpdateStdoutStderr", False))
     self.w.useFutureDivision.set(getDefault("DrawBotUseFutureDivision", True))
     self.w.animateIcon.set(getDefault("DrawBotAnimateIcon", True))
     self.w.checkForUpdates.set(getDefault("DrawBotCheckForUpdatesAtStartup", True))
     self.w.syntaxColors.getFromDefaults()
예제 #2
0
 def getFromDefaults(self):
     self.w.clearOutPut.set(getDefault("DrawBotClearOutput", True))
     self.w.liveOutPut.set(
         getDefault("DrawButLiveUpdateStdoutStderr", False))
     self.w.animateIcon.set(getDefault("DrawBotAnimateIcon", True))
     self.w.checkForUpdates.set(
         getDefault("DrawBotCheckForUpdatesAtStartup", True))
     self.w.syntaxColors.getFromDefaults()
예제 #3
0
 def checkSyntax(self, sender=None):
     # get the code
     code = self.code()
     # get te path of the document (will be None for an untitled document)
     path = self.path()
     # when enabled clear the output text view
     if getDefault("DrawBotClearOutput", True):
         self.outPutView.set("")
     # create a new std output, catching all print statements and tracebacks
     self.output = []
     self.stdout = StdOutput(self.output)
     self.stderr = StdOutput(self.output, True)
     # run the code, but with the optional flag checkSyntaxOnly so it will just compile the code
     ScriptRunner(code,
                  path,
                  stdout=self.stdout,
                  stderr=self.stderr,
                  checkSyntaxOnly=True)
     # set the catched print statements and tracebacks in the the output text view
     for text, isError in self.output:
         self.outPutView.append(text, isError)
     # clean up
     self.output = None
     self.stdout = None
     self.stderr = None
예제 #4
0
    def runCode(self, liveCoding=False):
        # get the code
        code = self.code()
        # save the code in the defaults, if something goes wrong
        setDefault("DrawBotCodeBackup", code)
        # get te path of the document (will be None for an untitled document)
        path = self.path()
        # reset the internal warning system
        warnings.resetWarnings()
        # reset the drawing tool
        _drawBotDrawingTool._reset()
        # create a namespace
        namespace = DrawBotNamespace(_drawBotDrawingTool, _drawBotDrawingTool._magicVariables)
        # add the tool callbacks in the name space
        _drawBotDrawingTool._addToNamespace(namespace)
        # when enabled clear the output text view
        if getDefault("DrawBotClearOutput", True):
            self.outPutView.clear()
        # create a new std output, catching all print statements and tracebacks
        self.output = []
        self.stdout = StdOutput(self.output)
        self.stderr = StdOutput(self.output, True)
        # warnings should show the warnings
        warnings.shouldShowWarnings = True
        # run the code
        ScriptRunner(code, path, namespace=namespace, stdout=self.stdout, stderr=self.stderr)
        # warnings should stop posting them
        warnings.shouldShowWarnings = False
        # set context, only when the panes are visible
        if self.w.split.isPaneVisible("drawView") or self.w.split.isPaneVisible("thumbnails"):
            def createContext(context):
                # draw the tool in to the context
                _drawBotDrawingTool._drawInContext(context)
            # create a context to draw in
            context = DrawBotContext()
            # savely run the callback and track all traceback back the the output
            CallbackRunner(createContext, stdout=self.stdout, stderr=self.stderr, args=[context])
            # get the pdf document and set in the draw view
            pdfDocument = context.getNSPDFDocument()
            if not liveCoding or (pdfDocument and pdfDocument.pageCount()):
                self.drawView.setPDFDocument(pdfDocument)
            # scroll down
            self.drawView.scrollDown()
        else:
            # if the panes are not visible, clear the draw view
            self.drawView.setPDFDocument(None)

        # set the catched print statements and tracebacks in the the output text view
        for text, isError in self.output:
            if liveCoding and isError:
                continue
            self.outPutView.append(text, isError)

        # reset the code backup if the script runs with any crashes
        setDefault("DrawBotCodeBackup", None)
        # clean up
        
        self.output = None
        self.stdout = None
        self.stderr = None
 def checkNowCallback(self, sender):
     from drawBot.updater import Updater
     oldValue = getDefault("DrawBotCheckForUpdatesAtStartup", True)
     setDefault("DrawBotCheckForUpdatesAtStartup", True)
     updater = Updater(self.w)
     if not updater.needsUpdate:
         self.showMessage("You have the latest version!", "DrawBot %s is currently the newest version" % updater.__version__)
     setDefault("DrawBotCheckForUpdatesAtStartup", oldValue)
예제 #6
0
 def checkNowCallback(self, sender):
     from drawBot.updater import Updater
     oldValue = getDefault("DrawBotCheckForUpdatesAtStartup", True)
     setDefault("DrawBotCheckForUpdatesAtStartup", True)
     updater = Updater(self.w)
     if not updater.needsUpdate:
         self.showMessage("You have the latest version!", "DrawBot %s is currently the newest version" % updater.__version__)
     setDefault("DrawBotCheckForUpdatesAtStartup", oldValue)
예제 #7
0
 def getFromDefaults(self):
     self.w.clearOutPut.set(getDefault("DrawBotClearOutput", True))
     self.w.liveOutPut.set(getDefault("DrawButLiveUpdateStdoutStderr", False))
     self.w.useFutureDivision.set(getDefault("DrawBotUseFutureDivision", True))
     self.w.animateIcon.set(getDefault("DrawBotAnimateIcon", True))
     self.w.checkForUpdates.set(getDefault("DrawBotCheckForUpdatesAtStartup", True))
     self.w.shouldOpenUntitledFile.set(getDefault("shouldOpenUntitledFile", True))
     self.w.showToolbar.set(getDefault("DrawBotAddToolbar", True))
     self.w.syntaxColors.getFromDefaults()
def styleFromDefault():
    styles = dict()
    tokens = getDefault("PyDETokenColors", fallbackStyleDict)
    for key, value in tokens.items():
        token = string_to_tokentype(key)
        if value and not value.startswith("#"):
            value = "#%s" % value
        styles[token] = value
    style = type('DrawBotStyle', (Style,), dict(styles=styles))
    style.background_color = _NSColorToHexString(getColorDefault("PyDEBackgroundColor", fallbackBackgroundColor))
    style.highlight_color = _NSColorToHexString(getColorDefault("PyDEHightLightColor", fallbackHightLightColor))
    return style
예제 #9
0
    def __init__(self):
        # make a window
        self.w = Window((400, 400), "DrawBot", minSize=(200, 200), textured=False, autosaveName=self.windowAutoSaveName)
        # setting previously stored frames, if any
        self.w.getNSWindow().setFrameUsingName_(self.windowAutoSaveName)
        try:
            # on 10.7+ full screen support
            self.w.getNSWindow().setCollectionBehavior_(128)  # NSWindowCollectionBehaviorFullScreenPrimary
        except:
            pass

        # the code editor
        self.codeView = CodeEditor((0, 0, -0, -0), callback=self.codeViewCallback)
        # the output view (will catch all stdout and stderr)
        self.outPutView = OutPutEditor((0, 0, -0, -0), readOnly=True)
        # the view to draw in
        self.drawView = DrawView((0, 0, -0, -0))
        # the view with all thumbnails
        self.thumbnails = ThumbnailView((0, 0, -0, -0))
        # connect the thumbnail view with the draw view
        self.thumbnails.setDrawView(self.drawView)

        # collect all code text view in a splitview
        paneDescriptors = [
            dict(view=self.codeView, identifier="codeView", minSize=50, canCollapse=False),
            dict(view=self.outPutView, identifier="outPutView", size=100, minSize=50, canCollapse=False),
        ]
        self.codeSplit = SplitView((0, 0, -0, -0), paneDescriptors, isVertical=False)

        # collect the draw scroll view and the code split view in a splitview
        paneDescriptors = [
            dict(view=self.thumbnails, identifier="thumbnails", minSize=100, size=100, maxSize=100),
            dict(view=self.drawView, identifier="drawView", minSize=50),
            dict(view=self.codeSplit, identifier="codeSplit", minSize=50, canCollapse=False),
        ]
        self.w.split = SplitView((0, 0, -0, -0), paneDescriptors)

        # setup BaseWindowController base behavoir
        self.setUpBaseWindowBehavior()

        # get the real size of the window
        windowX, windowY, windowWidth, windowHeight = self.w.getPosSize()
        # set the split view dividers at a specific position based on the window size
        self.w.split.setDividerPosition(0, 0)
        self.w.split.setDividerPosition(1, windowWidth * .6)
        self.codeSplit.setDividerPosition(0, windowHeight * .7)

        if getDefault("DrawBotAddToolbar", True):
            # add toolbar
            self.addToolbar()
예제 #10
0
    def __init__(self):
        # make a window
        self.w = Window((400, 400), "DrawBot", minSize=(200, 200), textured=False, autosaveName=self.windowAutoSaveName)
        # setting previously stored frames, if any
        self.w.getNSWindow().setFrameUsingName_(self.windowAutoSaveName)
        try:
            # on 10.7+ full screen support
            self.w.getNSWindow().setCollectionBehavior_(128)  # NSWindowCollectionBehaviorFullScreenPrimary
        except:
            pass

        # the code editor
        self.codeView = CodeEditor((0, 0, -0, -0), callback=self.codeViewCallback)
        # the output view (will catch all stdout and stderr)
        self.outPutView = OutPutEditor((0, 0, -0, -0), readOnly=True)
        # the view to draw in
        self.drawView = DrawView((0, 0, -0, -0))
        # the view with all thumbnails
        self.thumbnails = ThumbnailView((0, 0, -0, -0))
        # connect the thumbnail view with the draw view
        self.thumbnails.setDrawView(self.drawView)

        # collect all code text view in a splitview
        paneDescriptors = [
            dict(view=self.codeView, identifier="codeView", minSize=50, canCollapse=False),
            dict(view=self.outPutView, identifier="outPutView", size=100, minSize=50, canCollapse=False),
        ]
        self.codeSplit = SplitView((0, 0, -0, -0), paneDescriptors, isVertical=False)

        # collect the draw scroll view and the code split view in a splitview
        paneDescriptors = [
            dict(view=self.thumbnails, identifier="thumbnails", minSize=100, size=100, maxSize=100),
            dict(view=self.drawView, identifier="drawView", minSize=50),
            dict(view=self.codeSplit, identifier="codeSplit", minSize=50, canCollapse=False),
        ]
        self.w.split = SplitView((0, 0, -0, -0), paneDescriptors)

        # setup BaseWindowController base behavoir
        self.setUpBaseWindowBehavior()

        # get the real size of the window
        windowX, windowY, windowWidth, windowHeight = self.w.getPosSize()
        # set the split view dividers at a specific position based on the window size
        self.w.split.setDividerPosition(0, 0)
        self.w.split.setDividerPosition(1, windowWidth * .6)
        self.codeSplit.setDividerPosition(0, windowHeight * .7)

        if getDefault("DrawBotAddToolbar", True):
            # add toolbar
            self.addToolbar()
예제 #11
0
 def checkNowCallback(self, sender):
     from drawBot.updater import Updater
     oldValue = getDefault("DrawBotCheckForUpdatesAtStartup", True)
     setDefault("DrawBotCheckForUpdatesAtStartup", True)
     updater = Updater(self.w)
     if updater.currentVersionErrors:
         self.showMessage(
             "Cannot retrieve the version number from the DrawBot repository.",
             "\n".join(updater.currentVersionErrors))
     elif not updater.needsUpdate:
         self.showMessage(
             "You have the latest version!",
             "DrawBot %s is currently the newest version" %
             updater.__version__)
     setDefault("DrawBotCheckForUpdatesAtStartup", oldValue)
예제 #12
0
def styleFromDefault():
    styles = dict()
    tokens = getDefault("PyDETokenColors", fallbackStyleDict)
    for key, value in tokens.items():
        token = string_to_tokentype(key)
        if value and not value.startswith("#"):
            value = "#%s" % value
        styles[token] = value

    style = type('DrawBotStyle', (Style, ), dict(styles=styles))
    style.background_color = _NSColorToHexString(
        getColorDefault("PyDEBackgroundColor", fallbackBackgroundColor))
    style.highlight_color = _NSColorToHexString(
        getColorDefault("PyDEHightLightColor", fallbackHightLightColor))

    return style
예제 #13
0
 def checkSyntax(self, sender=None):
     # get the code
     code = self.code()
     # get te path of the document (will be None for an untitled document)
     path = self.path()
     # when enabled clear the output text view
     if getDefault("DrawBotClearOutput", True):
         self.outPutView.set("")
     # create a new std output, catching all print statements and tracebacks
     self.output = []
     self.stdout = StdOutput(self.output)
     self.stderr = StdOutput(self.output, True)
     # run the code, but with the optional flag checkSyntaxOnly so it will just compile the code
     ScriptRunner(code, path, stdout=self.stdout, stderr=self.stderr, checkSyntaxOnly=True)
     # set the catched print statements and tracebacks in the the output text view
     for text, isError in self.output:
         self.outPutView.append(text, isError)
     # clean up
     self.output = None
     self.stdout = None
     self.stderr = None
예제 #14
0
 def getFromDefaults(self):
     self.w.clearOutPut.set(getDefault("DrawBotClearOutput", True))
     self.w.animateIcon.set(getDefault("DrawBotAnimateIcon", True))
     self.w.syntaxColors.getFromDefaults()
예제 #15
0
파일: DrawBot.py 프로젝트: bitforks/drawbot
 def sheduleIconTimer(self):
     if getDefault("DrawBotAnimateIcon", True):
         self._iconTimer = AppKit.NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(0.1, self, "animateApplicationIcon:", None, False)
예제 #16
0
 def sheduleIconTimer(self):
     if getDefault("DrawBotAnimateIcon", True):
         self._iconTimer = AppKit.NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
             0.1, self, "animateApplicationIcon:", None, False)
예제 #17
0
 def applicationShouldOpenUntitledFile_(self, sender):
     return getDefault("shouldOpenUntitledFile", True)
def ScriptRunner(text=None, path=None, stdout=None, stderr=None, namespace=None, checkSyntaxOnly=False):

    def userCancelledMonitor():
        # This will be called from a thread
        while not scriptDone:  # scriptDone is in the surrounding scope
            if CheckEventQueueForUserCancel():
                # Send a SIGINT signal to ourselves.
                # This gets delivered to the main thread as a KeyboardInterrupt
                # exception, cancelling the running script.
                with cancelLock:
                    os.kill(os.getpid(), SIGINT)
                break
            time.sleep(0.25)  # check at most 4 times per second

    if path:
        if PY2 and isinstance(path, unicode):
            path = path.encode("utf-8")
        curDir, fileName = os.path.split(path)
    else:
        curDir = os.getenv("HOME")
        fileName = '<untitled>'
    # save up the important bits
    saveStdout = sys.stdout
    saveStderr = sys.stderr
    saveArgv = sys.argv
    try:
        saveDir = os.getcwd()
    except:
        saveDir = None
    # set up the name space
    if namespace is None:
        namespace = dict()
    namespace["__file__"] = path
    namespace["__name__"] = "__main__"
    namespace["help"] = _Helper()

    if stdout is not None:
        sys.stdout = stdout
    if stderr is not None:
        sys.stderr = stderr
    sys.argv = [fileName]
    if curDir:
        os.chdir(curDir)
        sys.path.insert(0, curDir)
    # here we go
    if text is None:
        with open(path, 'rb') as f:
            text = f.read().decode("utf-8")
    source = text.replace('\r\n', '\n').replace('\r', '\n')
    if PY2 and hasEncodingDeclaration(source) and isinstance(source, unicode):
        # Python 2 compile() complains when an encoding declaration is found in a unicode string.
        # As a workaround, we'll just encode it back as a utf-8 string and all is good.
        source = source.encode("utf-8")
    compileFlags = 0
    if getDefault("DrawBotUseFutureDivision", True):
        compileFlags |= __future__.CO_FUTURE_DIVISION

    try:
        try:
            code = compile(source + '\n\n', fileName, "exec", compileFlags, dont_inherit=True)
        except:
            traceback.print_exc(0)
        else:
            if not checkSyntaxOnly:
                scriptDone = False
                if CheckEventQueueForUserCancel is not None:
                    t = threading.Thread(target=userCancelledMonitor, name="UserCancelledMonitor")
                    t.start()
                try:
                    exec(code, namespace)
                except KeyboardInterrupt:
                    sys.stderr.write("Cancelled.\n")
                except:
                    etype, value, tb = sys.exc_info()
                    if tb.tb_next is not None:
                        tb = tb.tb_next
                    traceback.print_exception(etype, value, tb)
                    etype = value = tb = None
    finally:
        # reset the important bits
        scriptDone = True
        sys.stdout = saveStdout
        sys.stderr = saveStderr
        sys.argv = saveArgv
        if saveDir:
            os.chdir(saveDir)
        if curDir:
            sys.path.remove(curDir)
def ScriptRunner(text=None,
                 path=None,
                 stdout=None,
                 stderr=None,
                 namespace=None,
                 checkSyntaxOnly=False):
    def userCancelledMonitor():
        # This will be called from a thread
        while not scriptDone:  # scriptDone is in the surrounding scope
            if CheckEventQueueForUserCancel():
                # Send a SIGINT signal to ourselves.
                # This gets delivered to the main thread as a KeyboardInterrupt
                # exception, cancelling the running script.
                with cancelLock:
                    os.kill(os.getpid(), SIGINT)
                break
            time.sleep(0.25)  # check at most 4 times per second

    if path:
        if PY2 and isinstance(path, unicode):
            path = path.encode("utf-8")
        curDir, fileName = os.path.split(path)
    else:
        curDir = os.getenv("HOME")
        fileName = '<untitled>'
    # save up the important bits
    saveStdout = sys.stdout
    saveStderr = sys.stderr
    saveArgv = sys.argv
    try:
        saveDir = os.getcwd()
    except:
        saveDir = None
    # set up the name space
    if namespace is None:
        namespace = dict()
    namespace["__file__"] = path
    namespace["__name__"] = "__main__"
    namespace["help"] = _Helper()

    if stdout is not None:
        sys.stdout = stdout
    if stderr is not None:
        sys.stderr = stderr
    sys.argv = [fileName]
    if curDir:
        os.chdir(curDir)
        sys.path.insert(0, curDir)
    # here we go
    if text is None:
        with open(path, 'rb') as f:
            text = f.read().decode("utf-8")
    source = text.replace('\r\n', '\n').replace('\r', '\n')
    if PY2 and hasEncodingDeclaration(source) and isinstance(source, unicode):
        # Python 2 compile() complains when an encoding declaration is found in a unicode string.
        # As a workaround, we'll just encode it back as a utf-8 string and all is good.
        source = source.encode("utf-8")
    compileFlags = 0
    if getDefault("DrawBotUseFutureDivision", True):
        compileFlags |= __future__.CO_FUTURE_DIVISION

    try:
        try:
            code = compile(source + '\n\n',
                           fileName,
                           "exec",
                           compileFlags,
                           dont_inherit=True)
        except:
            traceback.print_exc(0)
        else:
            if not checkSyntaxOnly:
                scriptDone = False
                if CheckEventQueueForUserCancel is not None:
                    t = threading.Thread(target=userCancelledMonitor,
                                         name="UserCancelledMonitor")
                    t.start()
                try:
                    exec(code, namespace)
                except KeyboardInterrupt:
                    sys.stderr.write("Cancelled.\n")
                except:
                    etype, value, tb = sys.exc_info()
                    if tb.tb_next is not None:
                        tb = tb.tb_next
                    traceback.print_exception(etype, value, tb)
                    etype = value = tb = None
    finally:
        # reset the important bits
        scriptDone = True
        sys.stdout = saveStdout
        sys.stderr = saveStderr
        sys.argv = saveArgv
        if saveDir:
            os.chdir(saveDir)
        if curDir:
            sys.path.remove(curDir)
예제 #20
0
파일: DrawBot.py 프로젝트: thomgb/drawbot
 def applicationShouldOpenUntitledFile_(self, sender):
     return getDefault("shouldOpenUntitledFile", True)
예제 #21
0
    def __init__(self, text=None, path=None, stdout=None, stderr=None, namespace=None, checkSyntaxOnly=False):
        from threading import Thread
        if path:
            if isinstance(path, unicode):
                path = path.encode("utf-8")
            curDir, fileName = os.path.split(path)
        else:
            curDir = os.getenv("HOME")
            fileName = '<untitled>'
        # save up the important bits
        saveStdout = sys.stdout
        saveStderr = sys.stderr
        saveArgv = sys.argv
        try:
            saveDir = os.getcwd()
        except:
            saveDir = None
        # set up the name space
        if namespace is None:
            namespace = dict()
        namespace["__file__"] = path
        namespace["__name__"] = "__main__"
        namespace["help"] = _Helper()

        if stdout:
            sys.stdout = stdout
        if stderr:
            sys.stderr = stderr
        sys.argv = [fileName]
        os.chdir(curDir)
        sys.path.insert(0, curDir)
        if localSitePackagesPath and localSitePackagesPath not in sys.path:
            site.addsitedir(localSitePackagesPath)
        # here we go
        if text is None:
            f = open(path, 'rb')
            text = f.read()
            f.close()
        source = text.replace('\r\n', '\n').replace('\r', '\n')

        compileFlags = 0
        if getDefault("DrawBotUseFutureDivision", True):
            compileFlags |= __future__.CO_FUTURE_DIVISION

        try:
            try:
                code = compile(source + '\n\n', fileName, "exec", compileFlags)
            except:
                traceback.print_exc(0)
            else:
                if not checkSyntaxOnly:
                    self._scriptDone = False
                    try:
                        exec code in namespace
                    except KeyboardInterrupt:
                        pass
                    except:
                        etype, value, tb = sys.exc_info()
                        if tb.tb_next is not None:
                            tb = tb.tb_next
                        traceback.print_exception(etype, value, tb)
                        etype = value = tb = None
        finally:
            # reset the important bits
            self._scriptDone = True
            sys.stdout = saveStdout
            sys.stderr = saveStderr
            sys.argv = saveArgv
            if saveDir:
                os.chdir(saveDir)
            sys.path.remove(curDir)
예제 #22
0
    def __init__(self,
                 text=None,
                 path=None,
                 stdout=None,
                 stderr=None,
                 namespace=None,
                 checkSyntaxOnly=False):
        from threading import Thread
        if path:
            if isinstance(path, unicode):
                path = path.encode("utf-8")
            curDir, fileName = os.path.split(path)
        else:
            curDir = os.getenv("HOME")
            fileName = '<untitled>'
        # save up the important bits
        saveStdout = sys.stdout
        saveStderr = sys.stderr
        saveArgv = sys.argv
        try:
            saveDir = os.getcwd()
        except:
            saveDir = None
        # set up the name space
        if namespace is None:
            namespace = dict()
        namespace["__file__"] = path
        namespace["__name__"] = "__main__"
        namespace["help"] = _Helper()

        if stdout:
            sys.stdout = stdout
        if stderr:
            sys.stderr = stderr
        sys.argv = [fileName]
        os.chdir(curDir)
        sys.path.insert(0, curDir)
        if localSitePackagesPath and localSitePackagesPath not in sys.path:
            site.addsitedir(localSitePackagesPath)
        # here we go
        if text is None:
            f = open(path, 'rb')
            text = f.read()
            f.close()
        source = text.replace('\r\n', '\n').replace('\r', '\n')

        compileFlags = 0
        if getDefault("DrawBotUseFutureDivision", True):
            compileFlags |= __future__.CO_FUTURE_DIVISION

        try:
            try:
                code = compile(source + '\n\n', fileName, "exec", compileFlags)
            except:
                traceback.print_exc(0)
            else:
                if not checkSyntaxOnly:
                    self._scriptDone = False
                    try:
                        exec code in namespace
                    except KeyboardInterrupt:
                        pass
                    except:
                        etype, value, tb = sys.exc_info()
                        if tb.tb_next is not None:
                            tb = tb.tb_next
                        traceback.print_exception(etype, value, tb)
                        etype = value = tb = None
        finally:
            # reset the important bits
            self._scriptDone = True
            sys.stdout = saveStdout
            sys.stderr = saveStderr
            sys.argv = saveArgv
            if saveDir:
                os.chdir(saveDir)
            sys.path.remove(curDir)
예제 #23
0
    def runCode(self, liveCoding=False):
        # get the code
        code = self.code()
        # code = code.encode("utf-8")
        # save the code in the defaults, if something goes wrong
        setDefault("DrawBotCodeBackup", code)
        # get te path of the document (will be None for an untitled document)
        path = self.path()
        # reset the internal warning system
        warnings.resetWarnings()
        # reset the drawing tool
        _drawBotDrawingTool.newDrawing()
        # create a namespace
        namespace = DrawBotNamespace(_drawBotDrawingTool,
                                     _drawBotDrawingTool._magicVariables)
        # add the tool callbacks in the name space
        _drawBotDrawingTool._addToNamespace(namespace)
        # when enabled clear the output text view
        if getDefault("DrawBotClearOutput", True):
            self.outPutView.clear()
        # create a new std output, catching all print statements and tracebacks
        self.output = []

        liveOutput = None
        if getDefault("DrawButLiveUpdateStdoutStderr", False):
            liveOutput = self.outPutView

        self.stdout = StdOutput(self.output, outputView=liveOutput)
        self.stderr = StdOutput(self.output,
                                isError=True,
                                outputView=liveOutput)
        # warnings should show the warnings
        warnings.shouldShowWarnings = True
        # run the code
        ScriptRunner(code,
                     path,
                     namespace=namespace,
                     stdout=self.stdout,
                     stderr=self.stderr)
        # warnings should stop posting them
        warnings.shouldShowWarnings = False
        # set context, only when the panes are visible
        if self.w.split.isPaneVisible(
                "drawView") or self.w.split.isPaneVisible("thumbnails"):

            def createContext(context):
                # draw the tool in to the context
                _drawBotDrawingTool._drawInContext(context)

            # create a context to draw in
            context = DrawBotContext()
            # savely run the callback and track all traceback back the output
            CallbackRunner(createContext,
                           stdout=self.stdout,
                           stderr=self.stderr,
                           args=[context])
            # get the pdf document and set in the draw view
            pdfDocument = context.getNSPDFDocument()
            selectionIndex = self.thumbnails.getSelection()
            if not liveCoding or (pdfDocument and pdfDocument.pageCount()):
                self.drawView.setPDFDocument(pdfDocument)
            # scroll to the original position
            self.drawView.scrollToPageIndex(selectionIndex)
        else:
            # if the panes are not visible, clear the draw view
            self.drawView.setPDFDocument(None)
        # drawing is done
        _drawBotDrawingTool.endDrawing()
        # set the catched print statements and tracebacks in the the output text view
        for text, isError in self.output:
            if liveCoding and isError:
                continue
            self.outPutView.append(text, isError)

        # reset the code backup if the script runs with any crashes
        setDefault("DrawBotCodeBackup", None)
        # clean up

        self.output = None
        self.stdout = None
        self.stderr = None
예제 #24
0
 def getFromDefaults(self):
     self.w.clearOutPut.set(getDefault("DrawBotClearOutput", True))
     self.w.animateIcon.set(getDefault("DrawBotAnimateIcon", True))
     self.w.checkForUpdates.set(getDefault("DrawBotCheckForUpdatesAtStartup", True))
     self.w.syntaxColors.getFromDefaults()