Exemplo n.º 1
0
def saveWidgetObjects(widgetID):
    global _rObjects
    if widgetID not in _rObjects:
        return
    if _rObjects[widgetID]["state"]:
        _rObjects[widgetID]["timer"].stop()
        redRLog.log(redRLog.REDRCORE, redRLog.DEVEL, _("R objects from widgetID %s were collapsed (saved)") % widgetID)
        if RSession.mutex.tryLock():  # means the mutex is locked
            RSession.mutex.unlock()
            R(
                'save(%s, file = "%s")'
                % (
                    ",".join(_rObjects[widgetID]["vars"]),
                    os.path.join(redREnviron.directoryNames["tempDir"], widgetID).replace("\\", "/"),
                ),
                wantType="NoConversion",
                silent=True,
            )
            _rObjects[widgetID]["state"] = 0
            redRObjects.getWidgetInstanceByID(widgetID).setDataCollapsed(True)
            for v in _rObjects[widgetID]["vars"]:
                R('if(exists("%s")){rm("%s")}' % (v, v), wantType="NoConversion", silent=True)
            setTotalMemory()
        else:  # the session is locked so the data wasn't really saved.  We add time to the timer and try next time.
            # RSession.mutex.unlock()
            extendTimer(widgetID)
 def setOutputs(self, data, tmp = False):
     """Accepts a dict of key values and an optional arg tmp indicating if this is a template.
     The structure of the data dict is
     {
     version: version number
     id {
     
     name = outputSocket.name,
     signalClass = unicode(outputSocket.signalClass,
     value = None or outputSocket.signalCalss.saveSettings()
     }...
     }
     """
     
     if data.get('version', 1.85) > 1.85:
         #redRLog.log(redRLog.REDRCPRE, redRLog.DEBUG, "Adding Outputs using prior 1.85 settings.")
         for (key, value) in data.items():
             if key not in self.outputs.keys() or 'connections' not in value:
                 #print _('Signal does not exist')
                 continue
             ## find the signal from the widget and connect it
             for vValue in value['connections']:
                 ### find the widget
                 if not tmp:
                     widget = redRObjects.getWidgetInstanceByID(vValue['parentID'])
                 elif tmp:
                     widget = redRObjects.getWidgetInstanceByTempID(vValue['parentID'])
                 redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Input widget is %s' % widget)
                 if not widget:
                     redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Failed to find input widget %s' % vValue['parentID'])
                     return
                 inputSignal = widget.inputs.getSignal(vValue['wid'])
                 #redRLog.log(redRLog.REDRCPRE, redRLog.DEBUG, "Adding canvas line to using 1.85 settings.")
                 self.connectSignal(inputSignal, key, vValue['enabled'], process = False)  # connect the signal but don't send data through it.
                 if tmp:
                     self.propogateNone(ask = False)
     elif data.get('version', 1.85) <= 1.85: # 1.85 is the last supported version to not have version numbers in the output data containers.
         redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, "Adding Outputs using pre 1.85 settings.")
         for (key, value) in data.items():
             if key not in self.outputs.keys() or 'connections' not in value: continue
             for (vKey, vValue) in value['connections'].items():
                 if not tmp:
                     widget = redRObjects.getWidgetInstanceByID(vValue['parentID'])
                 elif tmp:
                     widget = redRObjects.getWidgetInstanceByTempID(vValue['parentID'])
                 redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Input widget is %s' % widget)
                 if not widget:
                     redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Failed to find input widget %s' % vValue['parentID'])
                     return
                 
                 if 'wid' in vValue.keys():
                     inputSignal = widget.inputs.getSignal(vValue['wid'])
                 elif 'id' in vValue.keys():
                     inputSignal = widget.inputs.getSignal(vValue['id'])
                     redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, "Adding canvas line to using < 1.85 settings.")
                 self.connectSignal(inputSignal, key, vValue['enabled'], process = False)  # connect the signal but don't send data through it.
                 if tmp:
                     self.propogateNone(ask = False)
Exemplo n.º 3
0
def loadLines(lineList, loadingProgressBar, freeze, tmp):
    global sessionID
    failureText = ""
    loadedOk = 1
    for line in lineList:
        ## collect the indicies of the widgets to connect.
        inIndex = line.getAttribute("inWidgetIndex")
        outIndex = line.getAttribute("outWidgetIndex")
        print inIndex, outIndex

        if inIndex == None or outIndex == None or str(inIndex) == '' or str(
                outIndex) == '':  # drive down the except path
            print inIndex, outIndex

            raise Exception
        if freeze: enabled = 0
        else: enabled = line.getAttribute("enabled")
        #print str(line.getAttribute('signals'))
        ## collect the signals to be connected between these widgets.
        signals = eval(str(line.getAttribute("signals")))
        #print '((((((((((((((((\n\nSignals\n\n', signals, '\n\n'
        if tmp:  ## index up the index to match sessionID
            inIndex += '_' + str(sessionID)
            outIndex += '_' + str(sessionID)
            print inIndex, outIndex, _('Settings template ID to these values')
        inWidget = redRObjects.getWidgetInstanceByID(inIndex)
        outWidget = redRObjects.getWidgetInstanceByID(outIndex)

        #print inWidget, outWidget, '#########$$$$$#########$$$$$$#######'
        if inWidget == None or outWidget == None:
            print 'Expected ID\'s', inIndex, outIndex

            failureText += _(
                "<nobr>Failed to create a signal line between widgets <b>%s</b> and <b>%s</b></nobr><br>"
            ) % (outIndex, inIndex)
            loadedOk = 0
            continue

        ## add a link for each of the signals.
        for (outName, inName) in signals:
            ## try to add using the new settings
            sig = inWidget.inputs.getSignal(inName)
            outWidget.outputs.connectSignal(sig, outName, enabled, False)
            #if not schemaDoc.addLink(outWidget, inWidget, outName, inName, enabled, loading = True, process = False): ## connect the signal but don't process.
            ## try to add using the old settings
            #    schemaDoc.addLink175(outWidget, inWidget, outName, inName, enabled)
        #print '######## enabled ########\n\n', enabled, '\n\n'
        #self.addLine(outWidget, inWidget, enabled, process = False)
        #self.signalManager.setFreeze(0)
        qApp.processEvents()

    return (loadedOk, failureText)
Exemplo n.º 4
0
def loadLines(lineList, loadingProgressBar, freeze, tmp):
    global sessionID
    failureText = ""
    loadedOk = 1
    for line in lineList:
        ## collect the indicies of the widgets to connect.
        inIndex = line.getAttribute("inWidgetIndex")
        outIndex = line.getAttribute("outWidgetIndex")
        print inIndex, outIndex
        
        if inIndex == None or outIndex == None or str(inIndex) == '' or str(outIndex) == '': # drive down the except path
            print inIndex, outIndex 
            
            raise Exception
        if freeze: enabled = 0
        else:      enabled = line.getAttribute("enabled")
        #print str(line.getAttribute('signals'))
        ## collect the signals to be connected between these widgets.
        signals = eval(str(line.getAttribute("signals")))
        #print '((((((((((((((((\n\nSignals\n\n', signals, '\n\n'
        if tmp: ## index up the index to match sessionID
            inIndex += '_'+str(sessionID)
            outIndex += '_'+str(sessionID)
            print inIndex, outIndex, _('Settings template ID to these values')
        inWidget = redRObjects.getWidgetInstanceByID(inIndex)
        outWidget = redRObjects.getWidgetInstanceByID(outIndex)
        
        #print inWidget, outWidget, '#########$$$$$#########$$$$$$#######'
        if inWidget == None or outWidget == None:
            print 'Expected ID\'s', inIndex, outIndex

            failureText += _("<nobr>Failed to create a signal line between widgets <b>%s</b> and <b>%s</b></nobr><br>") % (outIndex, inIndex)
            loadedOk = 0
            continue
            
        ## add a link for each of the signals.
        for (outName, inName) in signals:
            ## try to add using the new settings
            sig = inWidget.inputs.getSignal(inName)
            outWidget.outputs.connectSignal(sig, outName, enabled, False)
        qApp.processEvents()
        
    return (loadedOk, failureText)
Exemplo n.º 5
0
def loadWidgets(widgets, loadingProgressBar, loadedSettingsDict, tmp):

    lpb = 0
    loadedOk = 1
    failureText = ''
    for widget in widgets.getElementsByTagName("widget"):
        try:
            name = widget.getAttribute("widgetName")
            #print name
            widgetID = widget.getAttribute('widgetID')
            caption = widget.getAttribute('captionTitle')
            #print widgetID
            settings = cPickle.loads(loadedSettingsDict[widgetID]['settings'])
            inputs = cPickle.loads(loadedSettingsDict[widgetID]['inputs'])
            outputs = cPickle.loads(loadedSettingsDict[widgetID]['outputs'])
            #print _('adding instance'), widgetID, inputs, outputs
            newwidget = addWidgetInstanceByFileName(name,
                                                    settings,
                                                    inputs,
                                                    outputs,
                                                    id=widgetID)
            if newwidget and tmp:
                import time
                nw = redRObjects.getWidgetInstanceByID(newwidget)
                ## if tmp we need to set the tempID
                nw.tempID = widgetID
                nw.widgetID = unicode(time.time())
                nw.variable_suffix = '_' + widgetID
                nw.resetRvariableNames()
                ## send None through all of the widget ouptuts if this is a template
                nw.outputs.propogateNone()
            nw = redRObjects.getWidgetInstanceByID(newwidget)
            nw.setWindowTitle(caption)
            #print _('Settings'), settings
            lpb += 1
            loadingProgressBar.setValue(lpb)
        except Exception as inst:
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                        redRLog.formatException())
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR, unicode(inst))
    ## now the widgets are loaded so we can move on to setting the connections

    return (loadedOk, failureText)
Exemplo n.º 6
0
def loadWidgetObjects(widgetID):
    global _rObjects
    if widgetID not in _rObjects:
        return
    if _rObjects[widgetID]["state"]:
        return
    redRLog.log(redRLog.REDRCORE, redRLog.DEVEL, _("R objects from widgetID %s were expanded (loaded)") % widgetID)
    if not RSession.mutex.tryLock():  # the session is locked
        while not RSession.mutex.tryLock():
            pass
    RSession.mutex.unlock()  # we need to unlock now that we have waited and acquired the lock (one day this will be changed to a more generic form if we can figure out a way of determining who has the lock.
    if (
        R(
            'load("%s")' % os.path.join(redREnviron.directoryNames["tempDir"], widgetID).replace("\\", "/"),
            wantType="NoConversion",
        )
        != "SessionLocked"
    ):
        _rObjects[widgetID]["state"] = 1
        redRObjects.getWidgetInstanceByID(widgetID).setDataCollapsed(False)
        extendTimer(widgetID)
        setTotalMemory()
Exemplo n.º 7
0
def loadTabs(tabs, loadingProgressBar, tmp, loadedSettingsDict = None):
    # load the tabs
    
    loadedOK = True
    for t in tabs.getElementsByTagName('tab'):
        if not tmp:
            redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Loading tab %s' % t)
            schemaDoc.makeSchemaTab(t.getAttribute('name'))
            schemaDoc.setTabActive(t.getAttribute('name'))
        addY = minimumY()
        for witemp in t.getElementsByTagName('widgetIcons')[0].getElementsByTagName('widgetIcon'):
            name = witemp.getAttribute('name')             # save icon name
            instance = witemp.getAttribute('instance')        # save instance ID
            
            xPos = int(witemp.getAttribute("xPos"))      # save the xPos
            yPos = int(witemp.getAttribute("yPos"))      # same the yPos
            if not tmp:
                try:
                    caption = witemp.getAttribute("caption")          # save the caption
                    redRLog.log(1, 5, 3, _('loading widgeticon %(NAME)s, %(INSTANCE)s, %(CAPTION)s') % {'NAME':name, 'INSTANCE':instance, 'CAPTION':caption})
                    schemaDoc.addWidgetIconByFileName(name, x = xPos, y = yPos + addY, caption = caption, instance = instance) ##  add the widget icon 
                except Exception as inst:
                    redRLog.log(1, 9, 1, _('Loading exception occured for %s, %s') % (name, inst))
            else:
                print 'loading widget as tmp widget'
                #print 'loadedSettingsDict %s' % loadedSettingsDict.keys()
                caption = ""
                settings = cPickle.loads(loadedSettingsDict[instance]['settings'])
            
                import time
                loadingInstanceID = unicode(time.time())
                newwidget = schemaDoc.addWidgetByFileName(name, x = xPos, y = yPos + addY, widgetSettings = settings, wid = loadingInstanceID)
                nw = redRObjects.getWidgetInstanceByID(newwidget)
                ## if tmp we need to set the tempID
                nw.tempID = instance
                nw.widgetID = loadingInstanceID
                nw.variable_suffix = '_' + loadingInstanceID
                nw.resetRvariableNames()
                ## send None through all of the widget ouptuts if this is a template
                nw.outputs.propogateNone()
        
    return (True, '')
Exemplo n.º 8
0
 def setOutputs(self, data, tmp = False):
     for (key, value) in data.items():
         if key not in self.outputSignals.keys():
             #print _('Signal does not exist')
             continue
         ## find the signal from the widget and connect it
         for (vKey, vValue) in value['connections'].items():
             ### find the widget
             if not tmp:
                 widget = redRObjects.getWidgetInstanceByID(vValue['parentID'])
             elif tmp:
                 widget = redRObjects.getWidgetInstanceByTempID(vValue['parentID'])
             redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Widget is %s' % widget)
             if not widget:
                 redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Failed to find widget %s' % vValue['parentID'])
                 return
             inputSignal = widget.inputs.getSignal(vValue['id'])
             self.connectSignal(inputSignal, key, vValue['enabled'], process = False)  # connect the signal but don't send data through it.
             if tmp:
                 self.propogateNone(ask = False)
Exemplo n.º 9
0
 def instance(self):
     return redRObjects.getWidgetInstanceByID(self.instanceID)
Exemplo n.º 10
0
def loadWidgets(widgets, loadingProgressBar, loadedSettingsDict, tmp):
        
    lpb = 0
    loadedOk = 1
    failureText = ''
    redRLog.log(redRLog.REDRCORE, redRLog.INFO, 'Loading widgets %s' % str(widgets.getElementsByTagName("widget")))
    widgetSettingsList = []
    for widget in widgets.getElementsByTagName("widget"):
        try:
            name = widget.getAttribute("widgetName")
            
            widgetID = widget.getAttribute('widgetID')
            caption = widget.getAttribute('captionTitle')
            #print 'Loading widget', name, caption, widgetID
            
            # compatibility for redr185
            if 'settings' in loadedSettingsDict[widgetID]:
                settings = cPickle.loads(loadedSettingsDict[widgetID]['settings'])
            else: 
                """ reload the settings from save time """
                print "Loading settings for widget %s" % str(widgetID)+'.pickle'
                with open(os.path.join(redREnviron.directoryNames['tempDir'], str(widgetID)+'.pickle'), 'rb') as f:
                    try:
                        settings = cPickle.load(f)
                    except Exception as inst:
                        print "Error occurred in getting widget settings: ", str(inst)
                        settings = {}
                    f.close()
            
            
            widgetSettingsList.append((widgetID, settings))  # we need to load the settings after we load all of the widgets, this will prevent errors when we load settings.
            inputs = cPickle.loads(loadedSettingsDict[widgetID]['inputs'])
            outputs = cPickle.loads(loadedSettingsDict[widgetID]['outputs'])
            #print _('adding instance'), widgetID, inputs, outputs
            newwidget = addWidgetInstanceByFileName(name, settings, inputs, outputs, wid = widgetID)
            if newwidget and tmp:
                import time
                nw = redRObjects.getWidgetInstanceByID(newwidget)
                ## if tmp we need to set the tempID
                nw.tempID = widgetID
                nw.widgetID = unicode(time.time())
                nw.variable_suffix = '_' + widgetID
                nw.resetRvariableNames()
                ## send None through all of the widget ouptuts if this is a template
                nw.outputs.propogateNone()
            nw = redRObjects.getWidgetInstanceByID(newwidget)
            nw.setWindowTitle(caption)
            #nw.setDataCollapsed(True)  # the data must come in colapsed, this will help to prevent loading needless R data.
            #print str(widget.getAttribute('collapsed'))
            if str(widget.getAttribute('collapsed')):
                nw.setDataCollapsed(eval(widget.getAttribute('collapsed')))  # we set the default to be not collapsed.
            
            lpb += 1
            loadingProgressBar.setValue(lpb)
        except Exception as inst:
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException())
            #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, unicode(inst))
            #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, 'Loaded Settings Dict Is: %s' % unicode(loadedSettingsDict))
    ## now the widgets are loaded so we can move on to setting the connections
    
    return (loadedOk, failureText, widgetSettingsList)
Exemplo n.º 11
0
 def instance(self):
     return redRObjects.getWidgetInstanceByID(self.instanceID)
Exemplo n.º 12
0
def loadTabs(tabs, loadingProgressBar, tmp, loadedSettingsDict=None):
    # load the tabs

    loadedOK = True
    for t in tabs.getElementsByTagName('tab'):
        if not tmp:
            redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Loading tab %s' % t)
            schemaDoc.makeSchemaTab(t.getAttribute('name'))
            schemaDoc.setTabActive(t.getAttribute('name'))
        addY = minimumY()
        for witemp in t.getElementsByTagName(
                'widgetIcons')[0].getElementsByTagName('widgetIcon'):
            name = witemp.getAttribute('name')  # save icon name
            instance = witemp.getAttribute('instance')  # save instance ID

            xPos = int(witemp.getAttribute("xPos"))  # save the xPos
            yPos = int(witemp.getAttribute("yPos"))  # same the yPos
            if not tmp:
                try:
                    caption = witemp.getAttribute(
                        "caption")  # save the caption
                    redRLog.log(
                        1, 5, 3,
                        _('loading widgeticon %(NAME)s, %(INSTANCE)s, %(CAPTION)s'
                          ) % {
                              'NAME': name,
                              'INSTANCE': instance,
                              'CAPTION': caption
                          })
                    schemaDoc.addWidgetIconByFileName(
                        name,
                        x=xPos,
                        y=yPos + addY,
                        caption=caption,
                        instance=instance)  ##  add the widget icon
                except Exception as inst:
                    redRLog.log(
                        1, 9, 1,
                        _('Loading exception occured for %s, %s') %
                        (name, inst))
            else:
                #print 'loadedSettingsDict %s' % loadedSettingsDict.keys()
                caption = ""
                settings = cPickle.loads(
                    loadedSettingsDict[instance]['settings'])

                import time
                loadingInstanceID = unicode(time.time())
                newwidget = schemaDoc.addWidgetByFileName(
                    name,
                    x=xPos,
                    y=yPos + addY,
                    widgetSettings=settings,
                    id=loadingInstanceID)
                nw = redRObjects.getWidgetInstanceByID(newwidget)
                ## if tmp we need to set the tempID
                nw.tempID = instance
                nw.widgetID = loadingInstanceID
                nw.variable_suffix = '_' + loadingInstanceID
                nw.resetRvariableNames()
                ## send None through all of the widget ouptuts if this is a template
                nw.outputs.propogateNone()

    return (True, '')
Exemplo n.º 13
0
 def createReport(self, printer = None):
     import redRObjects
     qApp.canvasDlg.reports.createReportsMenu(
     [redRObjects.getWidgetInstanceByID(self.widgetID)],schemaImage=False)