def checkWidgetDuplication(widgets): for widget in widgets.getElementsByTagName("widget"): #widgetIDisNew = self.checkID(widget.getAttribute('widgetID')) if widget.getAttribute('widgetID') in redRObjects.instances(wantType = 'dict').keys(): qApp.restoreOverrideCursor() QMessageBox.critical(canvasDlg, _('Red-R Canvas'), _('Widget ID is a duplicate, I can\'t load this!!!'), QMessageBox.Ok) return False return True
def checkWidgetDuplication(widgets): for widget in widgets.getElementsByTagName("widget"): #widgetIDisNew = self.checkID(widget.getAttribute('widgetID')) if widget.getAttribute('widgetID') in redRObjects.instances( wantType='dict').keys(): qApp.restoreOverrideCursor() QMessageBox.critical( canvasDlg, _('Red-R Canvas'), _('Widget ID is a duplicate, I can\'t load this!!!'), QMessageBox.Ok) return False return True
def createReportsMenu(self,schemaImage=True): qname = QFileDialog.getSaveFileName(self, _("Write Report to File"), redREnviron.directoryNames['documentsDir'] + "/Report-"+unicode(datetime.date.today())+".odt", "Open Office Text (*.odt);; HTML (*.html);; LaTeX (*.tex)") if qname.isEmpty(): return qname = unicode(qname) name = unicode(qname) # this is the file name of the Report # name = os.path.join(redREnviron.directoryNames['redRDir'],'restr.odt') if os.path.splitext(name)[1].lower() not in [".odt", ".html", ".tex"]: name = name + '.odt' fileDir = os.path.split(name)[0] try: fileDir2 = os.path.join(fileDir, os.path.splitext("Data-"+os.path.split(name)[1])[0]) fileDir2 = fileDir2.replace('\\', '/') fd3 = [] for p in fileDir2.split('/'): if len(p) > 8 and ' ' in p: fd3.append(p.replace(' ', '')[:6]+'~1') else: fd3.append(p) fileDir2 = '/'.join(fd3) if os.path.isdir(fileDir2): shutil.rmtree(fileDir2) # makes a file to place the temp data into. #This will be deleted once the odt file is made. os.mkdir(fileDir2) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) # show the report list and allow the user to select widgets to include in the report. ## get the report info for the included widgets. # reportData = self.getReportData(fileDir2,name) import redRObjects done = self.createReport(fileDir2,name,redRObjects.instances(),schemaImage) if not done: return if os.name =='nt': #os.startfile doneDialog = redRdialog(self.schema,title=_("Report Generated")) redRwidgetLabel(doneDialog,label=_('Your report is ready to view.')) buttonBox = redRWidgetBox(doneDialog,orientation='horizontal') acceptButton = redRbutton(buttonBox,_('View Report')) QObject.connect(acceptButton, SIGNAL("clicked()"), doneDialog.accept) acceptButton = redRbutton(buttonBox,_('Done')) QObject.connect(acceptButton, SIGNAL("clicked()"), doneDialog.reject) if doneDialog.exec_() == QDialog.Accepted: try: os.startfile(name,'open') except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) mb = QMessageBox(_("Cannot Open File"), _("Red-R cannot open the reports file. Please open the file manually.\nThis is not a problem with Red-R, it is a problem with your document viewer."), QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton,self) mb.exec_() else: QMessageBox.information(self, _("Red-R Canvas"), _("Your report is ready to view."), QMessageBox.Ok + QMessageBox.Default )
def createReportsMenu(self, widgets = None, schemaImage=True): qname = QFileDialog.getSaveFileName(self, _("Write Report to File"), redREnviron.directoryNames['documentsDir'] + "/Report-"+unicode(datetime.date.today())+".odt", "Open Office Text (*.odt);; HTML (*.html);; LaTeX (*.tex)") if qname.isEmpty(): return qname = unicode(qname) name = unicode(qname) # this is the file name of the Report # name = os.path.join(redREnviron.directoryNames['redRDir'],'restr.odt') if os.path.splitext(name)[1].lower() not in [".odt", ".html", ".tex"]: name = name + '.odt' fileDir = os.path.split(name)[0] try: fileDir2 = os.path.join(fileDir, os.path.splitext("Data-"+os.path.split(name)[1])[0]) fileDir2 = fileDir2.replace('\\', '/') fd3 = [] for p in fileDir2.split('/'): if len(p) > 8 and ' ' in p: fd3.append(p.replace(' ', '')[:6]+'~1') else: fd3.append(p) fileDir2 = '/'.join(fd3) if os.path.isdir(fileDir2): shutil.rmtree(fileDir2) # makes a file to place the temp data into. #This will be deleted once the odt file is made. os.mkdir(fileDir2) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) # show the report list and allow the user to select widgets to include in the report. ## get the report info for the included widgets. # reportData = self.getReportData(fileDir2,name) if not widgets: import redRObjects import redRSignalManager widgets = redRObjects.instances() """The widgets may be stored in a seemingly random manner in the instances section. We would like to show the report in a way that makes sense. There is no real easy way to do this but the general plan that seems to work most often is to ensure that we don't make a report on a widget that has signaling widgets that aren't reported on yet. That is we report widgets as they send data. Note that this might not be the chronological order in which the analysis was carried out but it will be close to the order in which processing occurs from the data's point of view.""" widgetscopy = widgets widgetsnew = [] def copywidget(w, widgetscopy, widgetsnew): """Copies the widget to the right place.""" widgetscopy.remove(w) widgetsnew.append(w) def parentsIndexed(olist, widgetsnew): """Checks if the parent widgets have been indexed or not""" for o in olist: if o not in widgetsnew: return False return True while len(widgetscopy) > 0: for w in widgetscopy: if len(w.inputs.inputs.keys()) == 0 or len(redRSignalManager.getInputInstances(w)) == 0: copywidget(w, widgetscopy, widgetsnew) print 'Copy widget %s' % unicode(w) elif parentsIndexed(redRSignalManager.getInputInstances(w), widgetsnew): copywidget(w, widgetscopy, widgetsnew) print 'Copy widget %s' % unicode(w) print unicode(widgetsnew) print unicode(widgets) widgets = widgetsnew done = self.createReport(fileDir2,name,widgets,schemaImage) if not done: return if os.name =='nt': #os.startfile doneDialog = redRQTCore.dialog(self.schema,title=_("Report Generated")) redRQTCore.widgetLabel(doneDialog,label=_('Your report is ready to view.')) buttonBox = redRQTCore.widgetBox(doneDialog,orientation='horizontal') acceptButton = redRQTCore.button(buttonBox,_('View Report')) QObject.connect(acceptButton, SIGNAL("clicked()"), doneDialog.accept) acceptButton = redRQTCore.button(buttonBox,_('Done')) QObject.connect(acceptButton, SIGNAL("clicked()"), doneDialog.reject) if doneDialog.exec_() == QDialog.Accepted: try: os.startfile(name,'open') except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) mb = QMessageBox(_("Cannot Open File"), _("Red-R cannot open the reports file. Please open the file manually.\nThis is not a problem with Red-R, it is a problem with your document viewer."), QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton,self) mb.exec_() else: QMessageBox.information(self, _("Red-R Canvas"), _("Your report is ready to view."), QMessageBox.Ok + QMessageBox.Default )
def loadDocument180(filename, caption = None, freeze = 0, importing = 0): global sessionID import redREnviron if filename.split('.')[-1] in ['rrts']: tmp=True elif filename.split('.')[-1] in ['rrs']: tmp=False else: QMessageBox.information(self, _('Red-R Error'), _('Cannot load file with extension %s') % unicode(filename.split('.')[-1]), QMessageBox.Ok + QMessageBox.Default) return loadingProgressBar = startProgressBar(_('Loading %s') % unicode(os.path.basename(filename)), _('Loading ')+unicode(filename), 2) ## What is the purpose of this??? if not os.path.exists(filename): if os.path.splitext(filename)[1].lower() != ".tmp": QMessageBox.critical(self, _('Red-R Canvas'), _('Unable to locate file "%s"') % filename, QMessageBox.Ok) return loadingProgressBar.hide() loadingProgressBar.close() ### # set cursor qApp.setOverrideCursor(Qt.WaitCursor) if os.path.splitext(filename)[1].lower() == ".rrs": schemaPath, _schemaName = os.path.split(filename) canvasDlg.setCaption(caption or _schemaName) if importing: # a normal load of the session _schemaName = "" loadingProgressBar.setLabelText(_('Loading Schema Data, please wait')) ### unzip the file ### zfile = zipfile.ZipFile( unicode(filename), "r" ) for name in zfile.namelist(): file(os.path.join(redREnviron.directoryNames['tempDir'],os.path.basename(name)), 'wb').write(zfile.read(name)) ## put the data into the tempdir for this session for each file that was in the temp dir for the last schema when saved. doc = parse(os.path.join(redREnviron.directoryNames['tempDir'],'tempSchema.tmp')) # load the doc data for the data in the temp dir. ## get info from the schema schema = doc.firstChild widgets = schema.getElementsByTagName("widgets")[0] lines = schema.getElementsByTagName('channels')[0] f = open(os.path.join(redREnviron.directoryNames['tempDir'],'settings.pickle')) settingsDict = eval(unicode(f.read())) f.close() #settingsDict = eval(unicode(settings[0].getAttribute("settingsDictionary"))) loadedSettingsDict = settingsDict loadRequiredPackages(settingsDict['_requiredPackages'], loadingProgressBar = loadingProgressBar) ## make sure that there are no duplicate widgets. if not tmp: ## need to load the r session before we can load the widgets because the signals will beed to check the classes on init. if not checkWidgetDuplication(widgets = widgets): QMessageBox.information(self, _('Schema Loading Failed'), _('Duplicated widgets were detected between this schema and the active one. Loading is not possible.'), QMessageBox.Ok + QMessageBox.Default) return RSession.Rcommand('load("' + os.path.join(redREnviron.directoryNames['tempDir'], "tmp.RData").replace('\\','/') +'")') loadingProgressBar.setLabelText(_('Loading Widgets')) loadingProgressBar.setMaximum(len(widgets.getElementsByTagName("widget"))+1) loadingProgressBar.setValue(0) globalData.globalData = cPickle.loads(loadedSettingsDict['_globalData']) (loadedOkW, tempFailureTextW) = loadWidgets180(widgets = widgets, loadingProgressBar = loadingProgressBar, loadedSettingsDict = loadedSettingsDict, tmp = tmp) lineList = lines.getElementsByTagName("channel") loadingProgressBar.setLabelText(_('Loading Lines')) (loadedOkL, tempFailureTextL) = loadLines(lineList, loadingProgressBar = loadingProgressBar, freeze = freeze, tmp = tmp) #for widget in redRObjects.instances(): widget.updateTooltip() #activeCanvas().update() #saveTempDoc() if not loadedOkW and loadedOkL: failureText = tempFailureTextW + tempFailureTextL QMessageBox.information(canvasDlg, _('Schema Loading Failed'), _('The following errors occured while loading the schema: <br><br>') + failureText, QMessageBox.Ok + QMessageBox.Default) for widget in redRObjects.instances(): widget.setLoadingSavedSession(False) qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() loadingProgressBar.hide() loadingProgressBar.close() if tmp: sessionID += 1
def loadDocument(filename, caption = None, freeze = 0, importing = 0): if not os.path.exists(filename): mb = QMessageBox(QMessageBox.Information, _("File Location Error"), _("""The file that you attempted to load can't be found. This can happen if you moved the location of the file. If you were loading a template please use the refresh registry button (green and red arrows forming a circle) to resolve this. If you were loading a file from the quick bar, please try loading using "Open"."""), buttons = QMessageBox.Ok | QMessageBox.Default) mb.exec_() return # declare globals global _schemaName global schemaPath global globalNotes global canvasDlg # inform user of document load redRLog.log(redRLog.REDRCORE, redRLog.INFO, _('Loading Document %s') % filename) import redREnviron ## set settings for pipeline, template, or schema if filename.split('.')[-1] in ['rrts']: tmp=True pipe = False elif filename.split('.')[-1] in ['rrs']: tmp=False pipe = False elif filename.split('.')[-1] in ['rrpipe']: ## pipeline, no data but everything else there. pipe = True tmp = False else: QMessageBox.information(None, 'Red-R Error', _('Cannot load file with extension %s') % unicode(filename.split('.')[-1]), QMessageBox.Ok + QMessageBox.Default) return ## set the progress bar loadingProgressBar = startProgressBar(_('Loading %s') % unicode(os.path.basename(filename)), _('Loading %s') % unicode(filename), 2) # set cursor qApp.setOverrideCursor(Qt.WaitCursor) ## set the caption if os.path.splitext(filename)[1].lower() == ".rrs": schemaPath, _schemaName = os.path.split(filename) canvasDlg.setCaption(caption or _schemaName) if importing: # a normal load of the session _schemaName = "" loadingProgressBar.setLabelText(_('Loading Schema Data, please wait')) ### unzip the file ### zfile = zipfile.ZipFile( unicode(filename), "r" ) for name in zfile.namelist(): file(os.path.join(redREnviron.directoryNames['tempDir'],os.path.basename(name)), 'wb').write(zfile.read(name)) ## put the data into the tempdir for this session for each file that was in the temp dir for the last schema when saved. doc = parse(os.path.join(redREnviron.directoryNames['tempDir'],'tempSchema.tmp')) # load the doc data for the data in the temp dir. ## get info from the schema schema = doc.firstChild try: version = doc.getElementsByTagName("header")[0].getAttribute('version') if not version: redRLog.log(redRLog.REDRCORE, redRLog.WARNING, _('Version Tag Missing, using Red-R 1.80 loading specifications')) ## we should move everything to the earlier versions of orngDoc for loading. loadDocument180(filename, caption = None, freeze = 0, importing = 0) loadingProgressBar.hide() loadingProgressBar.close() LOADINGINPROGRESS = False return else: print _('The version is:%s') % version except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) redRLog.log(redRLog.REDRCORE, redRLog.WARNING, _('Error in loading the schema %s, reverting to load with 1.80 settings') % inst) loadDocument180(filename, caption = None, freeze = 0, importing = 0) loadingProgressBar.hide() loadingProgressBar.close() LOADINGINPROGRESS = False return ## extract the widgets and the tab settings widgets = schema.getElementsByTagName("widgets")[0] tabs = schema.getElementsByTagName("tabs")[0] #settings = schema.getElementsByTagName("settings") f = open(os.path.join(redREnviron.directoryNames['tempDir'],'settings.pickle')) settingsDict = eval(unicode(f.read())) f.close() ## load the required packages loadRequiredPackages(settingsDict['_requiredPackages'], loadingProgressBar = loadingProgressBar) ## make sure that there are no duplicate widgets. if not tmp and not pipe: ## need to load the r session before we can load the widgets because the signals will beed to check the classes on init. if not checkWidgetDuplication(widgets = widgets): QMessageBox.information(canvasDlg, _('Schema Loading Failed'), _('Duplicated widgets were detected between this schema and the active one. Loading is not possible.'), QMessageBox.Ok + QMessageBox.Default) LOADINGINPROGRESS = False return ## load the R session print 'Loading R session' RSession.Rcommand('load("' + os.path.join(redREnviron.directoryNames['tempDir'], "tmp.RData").replace('\\','/') +'")') loadingProgressBar.setLabelText(_('Loading Widgets')) loadingProgressBar.setMaximum(len(widgets.getElementsByTagName("widget"))+1) loadingProgressBar.setValue(0) """Load the widget instances. We load widget instances for schemas and then load the tab data. This is different for templates where the widget data is stored in the tab structure. Because the settings are consolidated with the widgets on that level (or rather are accessible there too) we do the loading of widgets in templates with the tabs.""" if not tmp: ## load the global data. globalData.globalData = cPickle.loads(settingsDict['_globalData']) if notesTextWidget and ('none' in globalData.globalData.keys()) and ('globalNotes' in globalData.globalData['none'].keys()): notesTextWidget.setHtml(globalData.globalData['none']['globalNotes']['data']) (loadedOkW, tempFailureTextW, settingsList) = loadWidgets(widgets = widgets, loadingProgressBar = loadingProgressBar, loadedSettingsDict = settingsDict, tmp = tmp) ## LOAD tabs ##### move through all of the tabs and load them. (loadedOkT, tempFailureTextT) = loadTabs(tabs = tabs, loadingProgressBar = loadingProgressBar, tmp = tmp, loadedSettingsDict = settingsDict) if not tmp: redRLog.log(10, 9,3,_('Setting Signals')) for widget in redRObjects.instances(): redRLog.log(10, 9, 9, _('Setting Signals for %s') % widget) try: if widget.widgetID not in settingsDict.keys(): redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, "widget id not in settings dict.keys(), keys are: %s" % str(settingsDict.keys())) continue redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, "setting widget outputs") widget.outputs.setOutputs(cPickle.loads(settingsDict[widget.widgetID]['outputs']), tmp) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) redRLog.log(1, 9, 1, _('Error setting signals %s, Settings are %s') % (inst, settingsDict[widget.widgetID].keys())) else: for widget in redRObjects.instances(): if widget.tempID and widget.tempID in settingsDict.keys(): redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, "widget id not in settings dict.keys(), keys are: %s" % str(settingsDict.keys())) widget.outputs.setOutputs(cPickle.loads(settingsDict[widget.tempID]['outputs']), tmp) if pipe: ## send none through all of the data. for w in redRObjects.instances(): w.outputs.propogateNone(ask = False) for widget in redRObjects.instances(): widget.tempID = None ## we set the temp ID to none so that there won't be a conflict with other temp loading. ## some saved sessions may have widget instances that are available but that do not match to icons. This shouldn't happen normally but if it does then we have instances that can persist without us knowing about it. We clear those here. for i in redRObjects.instances(): try: redRObjects.getWidgetByInstance(i) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) try: redRObjects.removeWidgetInstance(i) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass """Clean Up""" qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() loadingProgressBar.hide() loadingProgressBar.close() print redRObjects._lines redRObjects.updateLines()
def save(filename = None, template = False, copy = False, pipe = False): global _schemaName global schemaPath global notesTextWidget #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, '%s' % filename) if filename == None and not copy: filename = os.path.join(schemaPath, _schemaName) elif copy: filename = os.path.join(redREnviron.directoryNames['tempDir'], 'copy.rrts') #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, 'Saveing file as name %s' % filename) progressBar = startProgressBar( _('Saving ')+unicode(os.path.basename(filename)), _('Saving ')+unicode(os.path.basename(filename)), len(redRObjects.instances())+len(redRObjects.lines())+3) progress = 0 # create xml document (doc, schema, header, widgets, lines, settings, required, tabs, saveTagsList, saveDescription) = makeXMLDoc() """!@#$ Is this still required? If packages request R libraries then we don't really need to install them again, we just need to resolve the packages.""" requiredRLibraries = {} #save widgets tempWidgets = redRObjects.instances(wantType = 'dict') ## all of the widget instances, these are not the widget icons """This is where we save the instances to the file.""" print 'Saving widget instances ', tempWidgets (widgets, settingsDict, requireRedRLibraries) = saveInstances(tempWidgets, widgets, doc, progressBar) # save tabs and the icons and the channels if not copy or template: #tabs.setAttribute('tabNames', unicode(self.canvasTabs.keys())) for t in redRObjects.tabNames(): temp = doc.createElement('tab') temp.setAttribute('name', t) ## set all of the widget icons on the tab widgetIcons = doc.createElement('widgetIcons') for wi in redRObjects.getIconsByTab(t)[t]: ## extract only the list for this tab thus the [t] syntax saveIcon(widgetIcons, wi, doc) temp.appendChild(widgetIcons) ## append the widgetIcons XML to the global XML tabs.appendChild(temp) ## save the global settings ## if notesTextWidget: globalData.setGlobalData('Notes', 'globalNotes', unicode(notesTextWidget.toHtml())) settingsDict['_globalData'] = cPickle.dumps(globalData.globalData,2) settingsDict['_requiredPackages'] = cPickle.dumps({'R': requiredRLibraries.keys(),'RedR': requireRedRLibraries},2) #print requireRedRLibraries file = open(os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), "wt") file.write(unicode(settingsDict)) file.close() if template: taglist = unicode(tempDialog.tagsList.text()) tempDescription = unicode(tempDialog.descriptionEdit.toPlainText()) saveTagsList.setAttribute("tagsList", taglist) saveDescription.setAttribute("tempDescription", tempDescription) xmlText = doc.toprettyxml() progress += 1 progressBar.setValue(progress) if not template and not copy and not pipe: tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") tempR = os.path.join(redREnviron.directoryNames['tempDir'], "tmp.RData").replace('\\','/') file = open(tempschema, "wt") file.write(xmlText.encode('utf-8', 'replace')) file.close() doc.unlink() progressBar.setLabelText('Saving Data...') progress += 1 progressBar.setValue(progress) RSession.Rcommand('save.image("' + tempR + '")') # save the R data createZipFile(filename,[],[redREnviron.directoryNames['tempDir']])# collect the files that are in the tempDir and save them into the zip file. elif template: tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") file = open(tempschema, "wt") file.write(xmlText) file.close() zout = zipfile.ZipFile(filename, "w") zout.write(tempschema,"tempSchema.tmp") zout.write(os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'),'settings.pickle') zout.close() doc.unlink() elif copy: tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") file = open(tempschema, "wt") file.write(xmlText) file.close() zout = zipfile.ZipFile(filename, "w") zout.write(tempschema,"tempSchema.tmp") zout.write(os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'),'settings.pickle') zout.close() doc.unlink() loadTemplate(filename) progress += 1 progressBar.setValue(progress) progressBar.close() if os.path.splitext(filename)[1].lower() == ".rrs": (schemaPath, schemaName) = os.path.split(filename) redREnviron.settings["saveSchemaDir"] = schemaPath canvasDlg.toolbarFunctions.addToRecentMenu(filename) canvasDlg.setCaption(schemaName) redRLog.log(redRLog.REDRCORE, redRLog.INFO, 'Document Saved Successfully to %s' % filename) return True
def makeTemplate(filename, copy = False): ## this is different from saving. We want to make a special file that only has the selected widgets, their connections, and settings. No R data or tabs are saved. if not copy: tempDialog = TemplateDialog() tempDialog.exec_() tempdoc = Document() ## generates the main document type. tempXML = tempdoc.createElement("TemplateXML") saveTagsList = tempdoc.createElement("TagsList") saveDescription = tempdoc.createElement("saveDescription") templateName = tempdoc.createElement('Name') tempXML.appendChild(saveTagsList) tempXML.appendChild(saveDescription) tempXML.appendChild(templateName) taglist = unicode(tempDialog.tagsList.text()) tempDescription = unicode(tempDialog.descriptionEdit.toPlainText()) tempName = unicode(tempDialog.nameEdit.text()) saveTagsList.setAttribute("tagsList", taglist) saveDescription.setAttribute("tempDescription", tempDescription) templateName.setAttribute("name", tempName) tempdoc.appendChild(tempXML) print tempdoc.toprettyxml() activeIcons = collectIcons() progressBar = startProgressBar( _('Saving ')+unicode(os.path.basename(filename)), _('Saving ')+unicode(os.path.basename(filename)), len(redRObjects.instances(wantType = 'list'))+len(redRObjects.lines().values())+3) progress = 0 # create xml document (doc, schema, header, widgets, lines, settings, required, tabs, saveTagsList, saveDescription) = makeXMLDoc() requiredRLibraries = {} # save the widgets tempWidgets = {} for w in activeIcons: tempWidgets[w.instanceID] = w.instance() (widgets, settingsDict, requireRedRLibraries) = saveInstances(tempWidgets, widgets, doc, progressBar) #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, 'orngDoc makeTemplate; selected widgets: %s' % sw) temp = doc.createElement('tab') temp.setAttribute('name', 'template') ## set all of the widget icons on the tab widgetIcons = doc.createElement('widgetIcons') for wi in activeIcons: saveIcon(widgetIcons, wi, doc) temp.appendChild(widgetIcons) ## append the widgetIcons XML to the global XML tabs.appendChild(temp) ## save the global settings ## settingsDict['_globalData'] = cPickle.dumps(globalData.globalData,2) settingsDict['_requiredPackages'] = cPickle.dumps({'R': requiredRLibraries.keys(),'RedR': requireRedRLibraries},2) file = open(os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), "wt") file.write(unicode(settingsDict)) file.close() xmlText = doc.toprettyxml() progress += 1 progressBar.setValue(progress) tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") file = open(tempschema, "wt") file.write(xmlText) file.close() zout = zipfile.ZipFile(filename, "w") zout.write(tempschema,"tempSchema.tmp") zout.write(os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'),'settings.pickle') if not copy: with open(os.path.join(redREnviron.directoryNames['tempDir'], 'template.xml'), 'w') as f: f.write(tempdoc.toprettyxml()) zout.write(os.path.join(redREnviron.directoryNames['tempDir'], 'template.xml'), 'template.xml') zout.close() doc.unlink() if copy: loadTemplate(filename) progress += 1 progressBar.setValue(progress) progressBar.close() return True
def loadDocument180(filename, caption=None, freeze=0, importing=0): global sessionID import redREnviron if filename.split('.')[-1] in ['rrts']: tmp = True elif filename.split('.')[-1] in ['rrs']: tmp = False else: QMessageBox.information( self, _('Red-R Error'), _('Cannot load file with extension %s') % unicode(filename.split('.')[-1]), QMessageBox.Ok + QMessageBox.Default) return loadingProgressBar = startProgressBar( _('Loading %s') % unicode(os.path.basename(filename)), _('Loading ') + unicode(filename), 2) ## What is the purpose of this??? if not os.path.exists(filename): if os.path.splitext(filename)[1].lower() != ".tmp": QMessageBox.critical(self, _('Red-R Canvas'), _('Unable to locate file "%s"') % filename, QMessageBox.Ok) return loadingProgressBar.hide() loadingProgressBar.close() ### # set cursor qApp.setOverrideCursor(Qt.WaitCursor) if os.path.splitext(filename)[1].lower() == ".rrs": schemaPath, _schemaName = os.path.split(filename) canvasDlg.setCaption(caption or _schemaName) if importing: # a normal load of the session _schemaName = "" loadingProgressBar.setLabelText(_('Loading Schema Data, please wait')) ### unzip the file ### zfile = zipfile.ZipFile(unicode(filename), "r") for name in zfile.namelist(): file( os.path.join(redREnviron.directoryNames['tempDir'], os.path.basename(name)), 'wb' ).write( zfile.read(name) ) ## put the data into the tempdir for this session for each file that was in the temp dir for the last schema when saved. doc = parse( os.path.join(redREnviron.directoryNames['tempDir'], 'tempSchema.tmp') ) # load the doc data for the data in the temp dir. ## get info from the schema schema = doc.firstChild widgets = schema.getElementsByTagName("widgets")[0] lines = schema.getElementsByTagName('channels')[0] f = open( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle')) settingsDict = eval(unicode(f.read())) f.close() #settingsDict = eval(unicode(settings[0].getAttribute("settingsDictionary"))) loadedSettingsDict = settingsDict loadRequiredPackages(settingsDict['_requiredPackages'], loadingProgressBar=loadingProgressBar) ## make sure that there are no duplicate widgets. if not tmp: ## need to load the r session before we can load the widgets because the signals will beed to check the classes on init. if not checkWidgetDuplication(widgets=widgets): QMessageBox.information( self, _('Schema Loading Failed'), _('Duplicated widgets were detected between this schema and the active one. Loading is not possible.' ), QMessageBox.Ok + QMessageBox.Default) return RSession.Rcommand('load("' + os.path.join(redREnviron.directoryNames['tempDir'], "tmp.RData").replace('\\', '/') + '")') loadingProgressBar.setLabelText(_('Loading Widgets')) loadingProgressBar.setMaximum( len(widgets.getElementsByTagName("widget")) + 1) loadingProgressBar.setValue(0) globalData.globalData = cPickle.loads(loadedSettingsDict['_globalData']) (loadedOkW, tempFailureTextW) = loadWidgets180(widgets=widgets, loadingProgressBar=loadingProgressBar, loadedSettingsDict=loadedSettingsDict, tmp=tmp) lineList = lines.getElementsByTagName("channel") loadingProgressBar.setLabelText(_('Loading Lines')) (loadedOkL, tempFailureTextL) = loadLines(lineList, loadingProgressBar=loadingProgressBar, freeze=freeze, tmp=tmp) #for widget in redRObjects.instances(): widget.updateTooltip() #activeCanvas().update() #saveTempDoc() if not loadedOkW and loadedOkL: failureText = tempFailureTextW + tempFailureTextL QMessageBox.information( canvasDlg, _('Schema Loading Failed'), _('The following errors occured while loading the schema: <br><br>' ) + failureText, QMessageBox.Ok + QMessageBox.Default) for widget in redRObjects.instances(): widget.setLoadingSavedSession(False) qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() loadingProgressBar.hide() loadingProgressBar.close() if tmp: sessionID += 1
def loadDocument(filename, caption=None, freeze=0, importing=0): global _schemaName global schemaPath global globalNotes redRLog.log(redRLog.REDRCORE, redRLog.INFO, _('Loading Document %s') % filename) import redREnviron if filename.split('.')[-1] in ['rrts']: tmp = True pipe = False elif filename.split('.')[-1] in ['rrs']: tmp = False pipe = False elif filename.split('.')[-1] in [ 'rrpipe' ]: ## pipeline, no data but everything else there. pipe = True tmp = False else: QMessageBox.information( None, 'Red-R Error', _('Cannot load file with extension %s') % unicode(filename.split('.')[-1]), QMessageBox.Ok + QMessageBox.Default) return loadingProgressBar = startProgressBar( _('Loading %s') % unicode(os.path.basename(filename)), _('Loading %s') % unicode(filename), 2) # set cursor qApp.setOverrideCursor(Qt.WaitCursor) if os.path.splitext(filename)[1].lower() == ".rrs": schemaPath, _schemaName = os.path.split(filename) canvasDlg.setCaption(caption or _schemaName) if importing: # a normal load of the session _schemaName = "" loadingProgressBar.setLabelText(_('Loading Schema Data, please wait')) ### unzip the file ### zfile = zipfile.ZipFile(unicode(filename), "r") for name in zfile.namelist(): file( os.path.join(redREnviron.directoryNames['tempDir'], os.path.basename(name)), 'wb' ).write( zfile.read(name) ) ## put the data into the tempdir for this session for each file that was in the temp dir for the last schema when saved. doc = parse( os.path.join(redREnviron.directoryNames['tempDir'], 'tempSchema.tmp') ) # load the doc data for the data in the temp dir. ## get info from the schema schema = doc.firstChild try: version = schema.getElementsByTagName("header")[0].getAttribute( 'version') if not version: redRLog.log( redRLog.REDRCORE, redRLog.WARNING, _('Version Tag Missing, using Red-R 1.80 loading specifications' ) ) ## we should move everything to the earlier versions of orngDoc for loading. loadDocument180(filename, caption=None, freeze=0, importing=0) loadingProgressBar.hide() loadingProgressBar.close() return else: print _('The version is:%s') % version except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) redRLog.log( redRLog.REDRCORE, redRLog.WARNING, _('Error in loading the schema %s, reverting to load with 1.80 settings' ) % inst) loadDocument180(filename, caption=None, freeze=0, importing=0) loadingProgressBar.hide() loadingProgressBar.close() return widgets = schema.getElementsByTagName("widgets")[0] tabs = schema.getElementsByTagName("tabs")[0] #settings = schema.getElementsByTagName("settings") f = open( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle')) settingsDict = eval(unicode(f.read())) f.close() ## load the required packages loadRequiredPackages(settingsDict['_requiredPackages'], loadingProgressBar=loadingProgressBar) ## make sure that there are no duplicate widgets. if not tmp and not pipe: ## need to load the r session before we can load the widgets because the signals will beed to check the classes on init. if not checkWidgetDuplication(widgets=widgets): QMessageBox.information( canvasDlg, _('Schema Loading Failed'), _('Duplicated widgets were detected between this schema and the active one. Loading is not possible.' ), QMessageBox.Ok + QMessageBox.Default) return RSession.Rcommand('load("' + os.path.join(redREnviron.directoryNames['tempDir'], "tmp.RData").replace('\\', '/') + '")') loadingProgressBar.setLabelText(_('Loading Widgets')) loadingProgressBar.setMaximum( len(widgets.getElementsByTagName("widget")) + 1) loadingProgressBar.setValue(0) if not tmp: globalData.globalData = cPickle.loads(settingsDict['_globalData']) if notesTextWidget and ('none' in globalData.globalData.keys()) and ( 'globalNotes' in globalData.globalData['none'].keys()): notesTextWidget.setHtml( globalData.globalData['none']['globalNotes']['data']) (loadedOkW, tempFailureTextW) = loadWidgets(widgets=widgets, loadingProgressBar=loadingProgressBar, loadedSettingsDict=settingsDict, tmp=tmp) ## LOAD tabs ##### move through all of the tabs and load them. (loadedOkT, tempFailureTextT) = loadTabs(tabs=tabs, loadingProgressBar=loadingProgressBar, tmp=tmp, loadedSettingsDict=settingsDict) if not tmp: redRLog.log(10, 9, 3, _('Setting Signals')) for widget in redRObjects.instances(): redRLog.log(10, 9, 9, _('Setting Signals for %s') % widget) try: if widget.widgetID not in settingsDict.keys(): continue widget.outputs.setOutputs( cPickle.loads( settingsDict[widget.widgetID]['connections']), tmp) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) redRLog.log( 1, 9, 1, _('Error setting signals %s, Settings are %s') % (inst, settingsDict[widget.widgetID].keys())) else: for widget in redRObjects.instances(): if widget.tempID and widget.tempID in settingsDict.keys(): widget.outputs.setOutputs( cPickle.loads(settingsDict[widget.tempID]['connections']), tmp) if pipe: ## send none through all of the data. for w in redRObjects.instances(): w.outputs.propogateNone(ask=False) for widget in redRObjects.instances(): widget.tempID = None ## we set the temp ID to none so that there won't be a conflict with other temp loading. ## some saved sessions may have widget instances that are available but that do not match to icons. This shouldn't happen normally but if it does then we have instances that can persist without us knowing about it. We clear those here. for i in redRObjects.instances(): try: redRObjects.getWidgetByInstance(i) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) try: redRObjects.removeWidgetInstance(i) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() qApp.restoreOverrideCursor() loadingProgressBar.hide() loadingProgressBar.close() redRObjects.updateLines()
def save(filename=None, template=False, copy=False, pipe=False): global _schemaName global schemaPath global notesTextWidget #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, '%s' % filename) if filename == None and not copy: filename = os.path.join(schemaPath, _schemaName) elif copy: filename = os.path.join(redREnviron.directoryNames['tempDir'], 'copy.rrts') #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, 'Saveing file as name %s' % filename) progressBar = startProgressBar( _('Saving ') + unicode(os.path.basename(filename)), _('Saving ') + unicode(os.path.basename(filename)), len(redRObjects.instances()) + len(redRObjects.lines()) + 3) progress = 0 # create xml document (doc, schema, header, widgets, lines, settings, required, tabs, saveTagsList, saveDescription) = makeXMLDoc() requiredRLibraries = {} #save widgets tempWidgets = redRObjects.instances( wantType='dict' ) ## all of the widget instances, these are not the widget icons (widgets, settingsDict, requireRedRLibraries) = saveInstances(tempWidgets, widgets, doc, progressBar) # save tabs and the icons and the channels if not copy or template: #tabs.setAttribute('tabNames', unicode(self.canvasTabs.keys())) for t in redRObjects.tabNames(): temp = doc.createElement('tab') temp.setAttribute('name', t) ## set all of the widget icons on the tab widgetIcons = doc.createElement('widgetIcons') for wi in redRObjects.getIconsByTab( t )[t]: ## extract only the list for this tab thus the [t] syntax saveIcon(widgetIcons, wi, doc) # tabLines = doc.createElement('tabLines') # for line in self.widgetLines(t)[t]: # saveLine(tabLines, line) temp.appendChild( widgetIcons) ## append the widgetIcons XML to the global XML #temp.appendChild(tabLines) ## append the tabLines XML to the global XML tabs.appendChild(temp) ## save the global settings ## if notesTextWidget: globalData.setGlobalData('Notes', 'globalNotes', unicode(notesTextWidget.toHtml())) settingsDict['_globalData'] = cPickle.dumps(globalData.globalData, 2) settingsDict['_requiredPackages'] = cPickle.dumps( { 'R': requiredRLibraries.keys(), 'RedR': requireRedRLibraries }, 2) #print requireRedRLibraries file = open( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), "wt") file.write(unicode(settingsDict)) file.close() if template: taglist = unicode(tempDialog.tagsList.text()) tempDescription = unicode(tempDialog.descriptionEdit.toPlainText()) saveTagsList.setAttribute("tagsList", taglist) saveDescription.setAttribute("tempDescription", tempDescription) xmlText = doc.toprettyxml() progress += 1 progressBar.setValue(progress) if not template and not copy and not pipe: tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") tempR = os.path.join(redREnviron.directoryNames['tempDir'], "tmp.RData").replace('\\', '/') file = open(tempschema, "wt") file.write(xmlText) file.close() doc.unlink() progressBar.setLabelText('Saving Data...') progress += 1 progressBar.setValue(progress) RSession.Rcommand('save.image("' + tempR + '")') # save the R data createZipFile( filename, [], [redREnviron.directoryNames['tempDir']] ) # collect the files that are in the tempDir and save them into the zip file. elif template: tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") file = open(tempschema, "wt") file.write(xmlText) file.close() zout = zipfile.ZipFile(filename, "w") zout.write(tempschema, "tempSchema.tmp") zout.write( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), 'settings.pickle') zout.close() doc.unlink() elif copy: tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") file = open(tempschema, "wt") file.write(xmlText) file.close() zout = zipfile.ZipFile(filename, "w") zout.write(tempschema, "tempSchema.tmp") zout.write( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), 'settings.pickle') zout.close() doc.unlink() loadTemplate(filename) progress += 1 progressBar.setValue(progress) progressBar.close() if os.path.splitext(filename)[1].lower() == ".rrs": (schemaPath, schemaName) = os.path.split(filename) redREnviron.settings["saveSchemaDir"] = schemaPath canvasDlg.toolbarFunctions.addToRecentMenu(filename) canvasDlg.setCaption(schemaName) redRLog.log(redRLog.REDRCORE, redRLog.INFO, 'Document Saved Successfully to %s' % filename) return True
def makeTemplate(filename=None, copy=False): ## this is different from saving. We want to make a special file that only has the selected widgets, their connections, and settings. No R data or tabs are saved. if copy and len(_tempWidgets) == 0: return elif len(_tempWidgets) == 0: mb = QMessageBox( _("Save Template"), _("No widgets are selected.\nTemplates require widgets to be selected before saving as template." ), QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.No | QMessageBox.Escape, QMessageBox.NoButton) mb.exec_() return if not copy: if not filename: redRLog.log( redRLog.REDRCORE, redRLog.ERROR, _('orngDoc in makeTemplate; no filename specified, this is highly irregular!! Exiting from template save.' )) return tempDialog = TemplateDialog() if tempDialog.exec_() == QDialog.Rejected: return else: filename = redREnviron.directoryNames['tempDir'] + '/copy.rrts' progressBar = startProgressBar( _('Saving ') + unicode(os.path.basename(filename)), _('Saving ') + unicode(os.path.basename(filename)), len(redRObjects.instances(wantType='list')) + len(redRObjects.lines().values()) + 3) progress = 0 # create xml document (doc, schema, header, widgets, lines, settings, required, tabs, saveTagsList, saveDescription) = makeXMLDoc() requiredRLibraries = {} # save the widgets tempWidgets = {} if copy: for w in _tempWidgets: tempWidgets[w.instanceID] = w.instance() else: for w in redRObjects.activeTab().getSelectedWidgets(): tempWidgets[w.instanceID] = w.instance() (widgets, settingsDict, requireRedRLibraries) = saveInstances(tempWidgets, widgets, doc, progressBar) # save the icons and the lines sw = redRObjects.activeTab().getSelectedWidgets() #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, 'orngDoc makeTemplate; selected widgets: %s' % sw) temp = doc.createElement('tab') temp.setAttribute('name', 'template') ## set all of the widget icons on the tab widgetIcons = doc.createElement('widgetIcons') for wi in sw: saveIcon(widgetIcons, wi, doc) # tabLines = doc.createElement('tabLines') # for line in redRObjects.getLinesByTab()[redRObjects.activeTabName()]: # redRLog.log(redRLog.REDRCORE, redRLog.INFO, 'orngDoc makeTemplate; checking line %s, inWidget %s, outWidget %s' % (line, line.inWidget, line.outWidget)) # if (line.inWidget not in sw) or (line.outWidget not in sw): # continue # saveLine(tabLines, line) temp.appendChild( widgetIcons) ## append the widgetIcons XML to the global XML #temp.appendChild(tabLines) ## append the tabLines XML to the global XML tabs.appendChild(temp) ## save the global settings ## settingsDict['_globalData'] = cPickle.dumps(globalData.globalData, 2) settingsDict['_requiredPackages'] = cPickle.dumps( { 'R': requiredRLibraries.keys(), 'RedR': requireRedRLibraries }, 2) #print requireRedRLibraries file = open( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), "wt") file.write(unicode(settingsDict)) file.close() if not copy: taglist = unicode(tempDialog.tagsList.text()) tempDescription = unicode(tempDialog.descriptionEdit.toPlainText()) saveTagsList.setAttribute("tagsList", taglist) saveDescription.setAttribute("tempDescription", tempDescription) xmlText = doc.toprettyxml() progress += 1 progressBar.setValue(progress) tempschema = os.path.join(redREnviron.directoryNames['tempDir'], "tempSchema.tmp") file = open(tempschema, "wt") file.write(xmlText) file.close() zout = zipfile.ZipFile(filename, "w") zout.write(tempschema, "tempSchema.tmp") zout.write( os.path.join(redREnviron.directoryNames['tempDir'], 'settings.pickle'), 'settings.pickle') zout.close() doc.unlink() if copy: loadTemplate(filename) progress += 1 progressBar.setValue(progress) progressBar.close() #redRLog.log(redRLog.REDRCORE, redRLog.ERROR, _('Template saved successfully')) return True