def removeSignal(self, signal, wid): """Remove the connection between the inSocket and outSocket (specified by id)""" redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('Removing signal %s, %s') % (unicode(signal), unicode(wid))) ## send None through the signal to the handler before we disconnect it. l = getLinkPairBySignal(self.outputs[wid], signal) if l: try: if signal.multiple: signal.handler( None, self.parent.widgetID ) else: signal.handler( #self.outputs[signalName]['value'] None ) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) finally: ## remove the signal from the outputs rm = [l for l in _linkPairs if l[0] == self.outputs[wid] and l[1] == signal] for s in rm: #print 'Links before remove', _linkPairs _linkPairs.remove(s) #print 'Links after remove', _linkPairs try: signal.parent.outputs.propogateNone() except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass
def insertWidgets(self, itab, tab, widgetRegistry): """Inserts widgt icons into the named tab""" try: addingWidgets = [] for widgetInfo in widgetRegistry['widgets'].values(): for t in widgetInfo.tags: if type(t) == tuple: if t[0] == unicode(itab): addingWidgets.append((widgetInfo, t[1])) else: # debugging print t if t == unicode(itab): addingWidgets.append((widgetInfo, 0)) # debugging print addingWidgets addingWidget = sorted(addingWidgets, key = lambda info: info[1]) ## now things are sorted on the widget values. for widgetInfo, val in addingWidget: try: button = WidgetTreeItem(tab, widgetInfo.name, widgetInfo, self, self.canvasDlg) if button not in tab.widgets: tab.widgets.append(button) self.allWidgets.append(button) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) # debugging print inst pass except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass
def execUpdate(self,file): installDir = os.path.split(os.path.abspath(redREnviron.directoryNames['redRDir']))[0] ######## WINDOWS ############## if sys.platform =='win32': cmd = "%s /D=%s" % (file,installDir) try: shell.ShellExecuteEx(shellcon.SEE_MASK_NOCLOSEPROCESS,0,'open',file,"/D=%s" % installDir, redREnviron.directoryNames['downloadsDir'],0) # win32process.CreateProcess('Red-R update',cmd,'','','','','','','') except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) mb = QMessageBox(_("Error"), _("There was an Error in updating Red-R."), QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton, self.schema) mb.exec_() ######## MAC ############## elif sys.platform =='darwin': cmd = '%s %s %s %s' % (os.path.join(redREnviron.directoryNames['redRDir'],'MacOS','python'), os.path.join(redREnviron.directoryNames['redRDir'],'redRMacUpdater.py'), file, installDir) print cmd r = QProcess.startDetached(cmd) ######## Linux ############ elif sys.platform == 'linux2': cmd = 'python %s %s %s' % (os.path.join(redREnviron.directoryNames['redRDir'], 'redRLinuxUpdater.py'), file, installDir) print cmd r = QProcess.startDetached(cmd) else: raise Exception('Update instructions are not present for the %s platform' % sys.platform) self.app.exit(1)
def createFavoriteWidgetTabs(self, widgetRegistry, widgetDir, picsDir, defaultPic): # populate the favorites widget, we will want to repopulate this when a widget is added try: ffile = os.path.abspath(redREnviron.directoryNames['redRDir'] + '/tagsSystem/favorites.xml') f = open(ffile, 'r') except: # there was an exception, the user might not have the favorites file, we need to make one and set a default settings redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) self.insertFavoriteWidgetTab(_('Favorites'), 1) # make a favorites tab return favTabs = xml.dom.minidom.parse(f) f.close() treeXML = favTabs.childNodes[0] # everything is contained within the Favorites #print _('Favorites') + unicode(treeXML.childNodes) #loop to make the catagories for node in treeXML.childNodes: # put the child nodes into the widgets if node.nodeName == 'group': tab = self.insertFavoriteWidgetTab(unicode(node.getAttribute('name')), 1) self.insertFavoriteChildTabs(node, tab, widgetRegistry) self.insertFavoriteWidgets(node, tab, widgetRegistry) if hasattr(tab, "adjustSize"): tab.adjustSize()
def getSettings(self): """collects settings for the save function, these will be included in the output file. Called in orngDoc during save.""" redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'moving to save'+unicode(self.captionTitle)) import re settings = {} if self.saveSettingsList: ## if there is a saveSettingsList then we just append the required elements to it. allAtts = self.saveSettingsList + self.requiredAtts else: allAtts = self.__dict__ self.progressBarInit() i = 0 for att in allAtts: try: if att in self.dontSaveList or re.search('^_', att): continue i += 1 self.progressBarAdvance(i) var = getattr(self, att) settings[att] = self.returnSettings(var) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) #print 'saving custom settings' settings['_customSettings'] = self.saveCustomSettings() #print 'processing sent items' tempSentItems = self.processSentItems() #print 'appending sent items' settings['sentItems'] = {'sentItemsList':tempSentItems} self.progressBarFinished() return settings
def parseUpdatesXML(self,fileName): try: f = open(fileName, 'r') updatesXML = xml.dom.minidom.parse(f) f.close() update = {} update['redRVersion'] = self.getXMLText(updatesXML.getElementsByTagName('redRVersion')[0].childNodes) if sys.platform=="win32": updatesNode = updatesXML.getElementsByTagName('win32')[0] elif sys.platform=="darwin": updatesNode = updatesXML.getElementsByTagName('mac')[0] elif sys.platform == 'linux2': updatesNode = updatesXML.getElementsByTagName('linux')[0] if updatesNode and updatesNode != None: if redREnviron.version['TYPE'] =='compiled': update['url'] = self.getXMLText(updatesNode.getElementsByTagName('compiled')[0].childNodes) elif redREnviron.version['TYPE'] =='src': update['url'] = self.getXMLText(updatesNode.getElementsByTagName('src')[0].childNodes) else: raise Exception('Unknown type') return False update['SVNVersion'] = self.getXMLText(updatesNode.getElementsByTagName('SVNVersion')[0].childNodes) update['date'] = self.getXMLText(updatesNode.getElementsByTagName('date')[0].childNodes) update['changeLog'] = self.getXMLText(updatesNode.getElementsByTagName('changeLog')[0].childNodes) return update except: redRLog.log(redRLog.REDRCORE,redRLog.ERROR,'Red-R update information cannot be downloaded.') redRLog.log(redRLog.REDRCORE,redRLog.DEBUG,redRLog.formatException())
def eventFilter(self, object, ev): try: # a wrapper that prevents problems for the listbox debigging should remove this if object != self.listWidget and object != self: return 0 if ev.type() == QEvent.MouseButtonPress: self.listWidget.hide() return 1 consumed = 0 if ev.type() == QEvent.KeyPress: consumed = 1 if ev.key() in [Qt.Key_Enter, Qt.Key_Return]: #print _('Return pressed') self.doneCompletion() elif ev.key() == Qt.Key_Escape: self.listWidget.hide() #self.setFocus() elif ev.key() in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Home, Qt.Key_End, Qt.Key_PageUp, Qt.Key_PageDown]: self.listWidget.setFocus() self.listWidget.event(ev) else: #self.setFocus() self.event(ev) return consumed except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) return 0
def restartRedR(self): print 'in restartRedR' #os specific function to start a new red-R instance try: if sys.platform =='win32': if redREnviron.version['TYPE']=='compiled': cmd = '"%s"' % os.path.join(redREnviron.directoryNames['redRDir'],'bin','red-RCanvas.exe') else: cmd = 'pythonw "%s"' % os.path.join(redREnviron.directoryNames['redRDir'],'canvas','red-RCanvas.pyw') elif sys.platform == 'linux2': cmd = 'python "%s"' % os.path.join(redREnviron.directoryNames['redRDir'],'canvas','red-RCanvas.pyw') elif sys.platform =='darwin': cmd = 'open -Wn /Applications/Red-R.app' else: raise Exception('Your os is not supported for restart') print cmd r = QProcess.startDetached(cmd) print 'on open', r if r: self.canvas.close() return else: raise Exception('Problem restarting Red-R.') except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,'Red-R could not be restarted. Please restart manually.') redRLog.log(redRLog.REDRCORE, redRLog.DEBUG,redRLog.formatException()) mb = QMessageBox(_("Error"), _("Please restart Red-R."), QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton, self.canvas) mb.exec_()
def eventFilter(self, object, ev): try: # a wrapper that prevents problems for the listbox debigging should remove this #print type(self) try: # apparently calls are sent to this widget without the listWidget existing. Still don't know why but this catches the error. if object != self.listWidget and object != self: return 0 if ev.type() == QEvent.MouseButtonPress: self.listWidget.hide() return 1 except: return 0 consumed = 0 if ev.type() == QEvent.KeyPress: consumed = 1 if ev.key() in [Qt.Key_Enter, Qt.Key_Return]: self.doneCompletion() elif ev.key() == Qt.Key_Escape: self.listWidget.hide() # self.setFocus() elif ev.key() in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Home, Qt.Key_End, Qt.Key_PageUp, Qt.Key_PageDown]: self.listWidget.setFocus() self.listWidget.event(ev) else: # self.setFocus() self.event(ev) return consumed except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) return 0
def boundingRect(self): # get the width of the widget's caption pixmap = QPixmap(200,40) painter = QPainter() painter.begin(pixmap) width = max(0, painter.boundingRect(QRectF(0,0,200,40), Qt.AlignLeft, self.caption).width() - 60) / 2 painter.end() #rect = QRectF(-10-width, -4, +10+width, +25) rect = QRectF(QPointF(0, 0), self.widgetSize).adjusted(-10-width, -4, +10+width, +25) if not self.ghost: try: if self.progressBarShown: rect.setTop(rect.top()-20) inst = self.instance() if inst != None: widgetState = inst.widgetState if widgetState.get("Info", {}).values() + widgetState.get("Warning", {}).values() + widgetState.get("Error", {}).values() != []: rect.setTop(rect.top()-21) else: ## remove self. self.remove() except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) return rect
def updateListBoxItems(self, callCallback = 1): if not self.listbox: return last = self.getText() tuples = self.listboxItems if not self.caseSensitive: tuples = [(text.lower(), item) for (text, item) in tuples] last = last.lower() if self.useRE: try: pattern = re.compile(last) tuples = [(text, QListWidgetItem(item)) for (text, item) in tuples if pattern.match(text)] except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) tuples = [(t, QListWidgetItem(i)) for (t,i) in self.listboxItems] # in case we make regular expressions crash we show all items else: if self.matchAnywhere: tuples = [(text, QListWidgetItem(item)) for (text, item) in tuples if last in text] else: tuples = [(text, QListWidgetItem(item)) for (text, item) in tuples if text.startswith(last)] self.listbox.clear() for (t, item) in tuples: self.listbox.addItem(item) if self.callback and callCallback: self.callback()
def constructCategoriesPopup(canvasDlg): global categoriesPopup categoriesPopup = CanvasPopup(canvasDlg) categoriesPopup.setStyleSheet(""" QMenu { background-color: #fffff0; selection-background-color: blue; } QMenu::item:disabled { color: #dddddd } QMenu::separator {height: 1px; background: #dddddd; margin-left: 3px; margin-right: 4px;}""") # tfile = os.path.abspath(redREnviron.directoryNames['redRDir'] + '/tagsSystem/tags.xml') # f = open(tfile, 'r') # mainTabs = xml.dom.minidom.parse(f) # f.close() mainTabs = redRObjects.widgetRegistry()['tags'] treeXML = mainTabs.childNodes[0] #print treeXML.childNodes for itab in treeXML.childNodes: if itab.nodeName == 'group': #picked a group element catmenu = categoriesPopup.addMenu(unicode(itab.getAttribute('name'))) categoriesPopup.catActions.append(catmenu) # put the catmenu in the categoriespopup insertChildActions(canvasDlg, catmenu, categoriesPopup, itab) insertWidgets(canvasDlg, catmenu, categoriesPopup, unicode(itab.getAttribute('name'))) # print redREnviron.settings["WidgetTabs"] try: for category, show in redREnviron.settings["WidgetTabs"]: if not show or not redRObjects.widgetRegistry().has_key(category): continue catmenu = categoriesPopup.addMenu(category) categoriesPopup.catActions.append(catmenu) #print canvasDlg.widgetRegistry[category] for widgetInfo in sorted(redRObjects.widgetRegistry()[category].values(), key=lambda x:x.priority): icon = QIcon(widgetInfo.icon) act = catmenu.addAction(icon, widgetInfo.name) act.widgetInfo = widgetInfo act.category = catmenu #categoriesPopup.allActions.append(act) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) ### Add the templates to the popup, these should be actions with a function that puts a templates icon and loads the template for template in redRObjects.widgetRegistry()['templates']: try: icon = QIcon(os.path.join(redREnviron.directoryNames['picsDir'], 'Default.png')) act = catmenu.addAction(icon, template.name) act.templateInfo = template categoriesPopup.templateActions.append(act) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException())
def callSignalDelete(self, name): if self.linksOut.has_key(name): for id in self.linksOut[name]: try: self.linksOut[name][id].deleteSignal() except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException())
def lineEditChanged(self,newValue,dataPointer,key): # print '@@@@@@@@@@@@@@@@@@@@@@@@@@', newValue try: if key in ['numChrLimit', 'numRowLimit']: dataPointer[key] = int(newValue) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass
def assign(name, object): try: rpy.r.assign(name, object) redRLog.log(redRLog.R, redRLog.DEBUG, _('Assigned object to %s') % name) return True except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) return False
def setSignalClass(self, d): try: # try to reload the output class from the signals import imp ## find the libraries directory fp, pathname, description = imp.find_module('libraries', [redREnviron.directoryNames['redRDir']]) #print 'loading module' varc = imp.load_module('libraries', fp, pathname, description) #print varc for mod in d['class'].split('.')[1:]: #print varc varc = getattr(varc, mod) var = varc(widget = self, checkVal = False, **d) var.loadSettings(d) except: # if it doesn't exist we need to set the class something so we look to the outputs. ## kick over to compatibility layer to add the settings. for 175 attributes redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) try: for (key, val) in d.items(): ## find the libraries directory fp, pathname, description = imp.find_module('libraries', [redREnviron.directoryNames['redRDir']]) #print 'loading module' varc = imp.load_module('libraries', fp, pathname, description) #print varc for mod in val['class'].split('.')[1:]: #print varc varc = getattr(varc, mod) var = varc(widget = self, data = val['data']) var.loadSettings(val) if fp: fp.close() except: #print 'something is really wrong we need to set some kind of data so let\'s set it to the signals.RVariable' redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) try: var = signals.BaseRedRVariable(widget = self, data = d['data']['data'], checkVal = False) except: ## fatal exception, there is no data in the data slot (the signal must not have data) we can't do anything so we except... redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) #print 'Fatal exception in loading. Can\'t assign the signal value' var = None finally: if fp: fp.close() return var
def insertWidgets(self, itab, tab, widgetRegistry): #print 'Widget Registry is \n\n' + unicode(widgetRegistry) + '\n\n' widgets = None try: for wName in widgetRegistry['widgets'].keys(): widgetInfo = widgetRegistry['widgets'][wName] try: if unicode(itab.replace(' ', '')) in widgetInfo.tags: # add the widget button = WidgetTreeItem(tab, widgetInfo.name, widgetInfo, self, self.canvasDlg) if button not in tab.widgets: tab.widgets.append(button) self.allWidgets.append(button) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException())
def addInstance(info, settings, insig, outsig, wid = None): """Called to add an instance of a widget to the canvas.""" global _widgetInstances global _widgetIcons global _widgetInfo m = __import__(info.fileName) instance = m.__dict__[info.widgetName].__new__(m.__dict__[info.widgetName], _owInfo = redREnviron.settings["owInfo"], _owWarning = redREnviron.settings["owWarning"], _owError = redREnviron.settings["owError"], _owShowStatus = redREnviron.settings["owShow"], _packageName = info.packageName) instance.__dict__['_widgetInfo'] = info if wid == None: OWRpy.uniqueWidgetNumber += 1 ctime = unicode(time.time()) wid = unicode(OWRpy.uniqueWidgetNumber) + '_' + ctime #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG,redRLog.formatException()) redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('adding instance number %s name %s') % (str(wid), info.name)) if info.name == 'Dummy': instance.__init__(forceInSignals = insig, forceOutSignals = outsig, wid = wid) else: instance.__init__(wid = wid) ## check if an id is present, if this is the case then we should set the id to the widget. instance.setProgressBarHandler(activeTab().progressBarHandler) # set progress bar event handler instance.setProcessingHandler(activeTab().processingHandler) instance.setWidgetWindowIcon(info.icon) #instance.canvasWidget = self instance.widgetInfo = info redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('instance ID is %s') % instance.widgetID) if wid in _widgetInstances.keys(): redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('id was found in the keys, placing as new ID')) ## this is interesting since we aren't supposed to have this, just in case, we throw a warning redRLog.log(redRLog.REDRCORE, redRLog.WARNING, _('Warning: widget id already in the keys, setting new widget instance')) wid = unicode(time.time()) instance.widgetID = wid instance.variable_suffix = '_' + instance.widgetID instance.resetRvariableNames() if not instance: raise Exception(_('Error in loading widget %s') % wid) _widgetInstances[wid] = instance # setting the settings should be the last thing that we do since this is a change of the widget data and may depend on access to the registry. instance.loadGlobalSettings() if settings: try: instance.setSettings(settings) instance.loadCustomSettings(settings) except Exception as inst: # print '##########################\n'*5 redRLog.log(redRLog.REDRCORE, redRLog.ERROR, _('redRObjects addInstance; error in setting settings or custom settings. <b>%s<b>') % inst) redRLog.log(redRLog.REDRCORE, redRLog.DEBUG,redRLog.formatException()) return wid
def uploadException(self,err): try: import httplib,urllib import sys,pickle,os, re #print redREnviron.settings['askToUploadError'], 'askToUploadError' #print redREnviron.settings['uploadError'], 'uploadError' if not redREnviron.settings['askToUploadError']: res = redREnviron.settings['uploadError'] else: self.msg = redRGUI.base.dialog(parent=qApp.canvasDlg,title='Red-R Error') error = redRGUI.base.widgetBox(self.msg,orientation='vertical') redRGUI.base.widgetLabel(error, label='Do you wish to report the Error Log?') buttons = redRGUI.base.widgetBox(error,orientation='horizontal') redRGUI.base.button(buttons, label = _('Yes'), callback = self.uploadYes) redRGUI.base.button(buttons, label = _('No'), callback = self.uploadNo) self.checked = False self.remember = redRGUI.base.checkBox(error,label='response', displayLabel=None, buttons=[_('Remember my Response')],callback=self.rememberResponse) res = self.msg.exec_() redREnviron.settings['uploadError'] = res # redRLog.log(redRLog.REDRCORE, redRLog.ERROR, 'aaa') if res == 1: # print 'in res' err['version'] = redREnviron.version['SVNVERSION'] err['type'] = redREnviron.version['TYPE'] err['redRversion'] = redREnviron.version['REDRVERSION'] #print err['traceback'] ##err['output'] = self.allOutput if os.name == 'nt': err['os'] = 'Windows' # else: # err['os'] = 'Not Specified' if redREnviron.settings['canContact']: err['email'] = redREnviron.settings['email'] # else: # err['email'] = 'None; no contact' #err['id'] = redREnviron.settings['id'] # print err.keys() params = urllib.urlencode(err) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("red-r.org",80) conn.request("POST", "/errorReport.php", params,headers) # r1 = conn.getresponse() # data1 = r1.read() # print type(data1),data1 # print r1.status, r1.reason else: return except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass
def updateScan(self): if self.rowNamesCombo.count() == 0: self.colNames = self.R('colnames(' + self.Rvariables['dataframe_org'] + ')',wantType='list') self.rowNamesCombo.clear() self.rowNamesCombo.addItem('NULL','NULL') for x in self.colNames: self.rowNamesCombo.addItem(x,x) self.scanarea.clear() data = self.R( #'rbind(colnames(' + self.Rvariables['dataframe_org'] #+ '), ' + self.Rvariables['dataframe_org'] + ')' ,wantType='dict') rownames = self.R('rownames(' + self.Rvariables['dataframe_org'] + ')',wantType='list') #self.colnames = self.R('colnames(rbind(colnames(' + self.Rvariables['dataframe_org'] + '), ' + self.Rvariables['dataframe_org'] + ')', wantType = 'list') txt = self.html_table(data,rownames) self.scanarea.setText(txt) try: print 'checking col classes %s' % self.useColClasses.checked() if self.useColClasses.checked() == 'TRUE': print 'col classes seen as TRUE' if len(self.colClasses) ==0: self.colClasses = self.R('as.vector(sapply(' + self.Rvariables['dataframe_org'] + ',class))',wantType='list') self.myColClasses = self.colClasses # print '@@@@@@@@@@@@@@@@@@@@@@@@@', self.myColClasses if len(self.dataTypes) ==0: types = ['factor','numeric','character','integer','logical'] self.dataTypes = [] if len(self.colNames) > 200: mb = QMessageBox(QMessageBox.Question, _('Col Classes Setting'), _('You are loading more than 200 columns of data.\n\nDo you really want to load this many classes?'), QMessageBox.Yes | QMessageBox.No) if mb.exec_() == QMessageBox.No: return for k,i,v in zip(range(len(self.colNames)),self.colNames,self.myColClasses): s = redRGUI.base.radioButtons(self.columnTypes,label=i,displayLabel=False, buttons=types,orientation='horizontal',callback=self.updateColClasses) # print k,i,unicode(v) if unicode(v) in types: s.setChecked(unicode(v)) else: s.addButton(unicode(v)) s.setChecked(unicode(v)) label = redRGUI.base.widgetLabel(None,label=i) self.columnTypes.layout().addWidget(label.controlArea,k,0) self.columnTypes.layout().addWidget(s.controlArea,k,1) self.dataTypes.append([i,s]) except: import redRLog redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) self.scanarea.clear() self.scanarea.setText(_('Problem reading or scanning the file. Please check the file integrity and try again.'))
def testCoreTestExamples(): packages = [ os.path.split(f)[1] for f in glob.glob(redREnviron.directoryNames["libraryDir"] + "/*") if ".svn" not in f ] for p in packages: try: redRLog.log(redRLog.REDRCORE, redRLog.INFO, "Loading test examples for package %s" % p) coreTestExamplesDir = os.path.join(redREnviron.directoryNames["libraryDir"], p, "CoreTestExamples") if not os.path.exists(coreTestExamplesDir): raise Exception("No CoreTestExamples Directory in package") for ef in glob.glob(coreTestExamplesDir + "/*.rrs"): try: redRLog.log(redRLog.REDRCORE, redRLog.INFO, "Loading test file %s" % ef) redRObjects.schemaDoc.clear() redRSaveLoad.loadDocument(unicode(ef), freeze=0, importing=False) except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.CRITICAL, redRLog.formatException()) except: redRLog.log(redRLog.REDRCORE, redRLog.CRITICAL, redRLog.formatException())
def loadGlobalSettings(self): file = self.getGlobalSettingsFile() if not os.path.exists(file): return try: file = open(file, "r") settings = cPickle.load(file) self.setSettings(settings, globalSettings = True) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) pass
def addWidget(widgetInfo, x= -1, y=-1, caption = "", widgetSettings = None, saveTempDoc = True, forceInSignals = None, forceOutSignals = None, wid = None): """A core function to expose widget addition to the rest of core. Taken over from :mod:`orngDoc`. .. note:: The function in :mod:`orngDoc` is still active but will soon be depricated for this function. """ #global sm global canvasDlg qApp.setOverrideCursor(Qt.WaitCursor) try: instanceID = addInstance(widgetInfo, widgetSettings, forceInSignals, forceOutSignals, wid = wid) caption = widgetInfo.name if getIconByIconCaption(caption): i = 2 while getIconByIconCaption('%s (%s)' % (caption, str(i))): i += 1 caption = '%s (%s)' % (caption, str(i)) newwidget = newIcon(activeCanvas(), activeTab(), widgetInfo, redRStyle.defaultWidgetIcon, canvasDlg, instanceID = instanceID, tabName = activeTabName()) newwidget.caption = caption newwidget.updateText(caption) redRLog.log(redRLog.REDRCORE, redRLog.INFO, _('Create new widget named %s.') % newwidget.caption) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) qApp.restoreOverrideCursor() return None resolveCollisions(newwidget, x, y) newwidget.instance().setWindowTitle(newwidget.caption) activeCanvas().update() try: #sm.addWidget(newwidget.instance()) newwidget.show() newwidget.updateTooltip() newwidget.setProcessing(1) # if redREnviron.settings["saveWidgetsPosition"]: # newwidget.instance().restoreWidgetPosition() newwidget.setProcessing(0) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) qApp.restoreOverrideCursor() return newwidget.instanceID
def get_(domain = 'messages', package = 'base', languages = None, fallback = False): """Return a function to convert strings into translated strings.""" #if locale: print locale try: if languages == None: try: languages = redREnviron.settings['language'].keys() except: print redREnviron.settings['language'] redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) languages = ['en_EN.ISO8859-1'] return superfallback if languages[0] == 'en_EN.ISO8859-1': return superfallback file = os.path.join(redREnviron.directoryNames['libraryDir'], package, 'languages') #print file t = gettext.translation(domain, localedir = os.path.join(redREnviron.directoryNames['libraryDir'], package, 'languages'), languages = languages, fallback = fallback) return t.gettext # returns the function except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) print 'Exception occured in setting the get_ function, %s' % unicode(inst) return superfallback
def onTabChange(self,index): # print 'onTabChange',index # get a data frame (dict) of r libraries if self.tabs.tabText(index) != _('R Settings'): return try: if not self.libListBox: return except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) self.libs = RSession.Rcommand('getCRANmirrors()') # place a listBox in the widget and fill it with a list of mirrors self.libListBox = redRlistBox(self.rlibrariesBox, label = _('Mirrors'), items = self.libs['Name'], callback = self.setMirror)
def _processSingle(self, outsig, insig, enabled = 1): """Process the data in the outsig socket through the handler specified by the insig socket.""" #print 'Processing signal %s, %s' % (outsig.name, insig.name) try: #print signal if not enabled: return 0 handler = insig.handler multiple = insig.multiple if outsig.getValue() == None: # if there is no data then it doesn't matter what the signal class is, becase none will be sent anyway self._handleSignal(outsig.getValue(), handler, multiple, insig.parent) elif (insig.signalClass == 'All') or ('All' in insig.signalClass) or (outsig.signalClass in insig.signalClass): #print '\n\n\nprocessing signal %s using handler: %s with multiple: %s\n\n\n\n' % (signal['value'], handler, multiple) self._handleSignal(outsig.getValue(), handler, multiple, insig.parent) else: sentSignal = False for sig in insig.signalClass: try: if sig in outsig.signalClass.convertToList: newVal = outsig.getValue().convertToClass(sig) self._handleSignal(newVal, handler, multiple, insig.parent) sentSignal = True break elif outsig.signalClass in sig.convertFromList: tempSignal = sig(self.parent, data = '', checkVal = False) ## make a temp holder to handle the processing. newVal = tempSignal.convertFromClass(outsig.getValue()) self._handleSignal(newVal, handler, multiple, insig.parent) sentSignal = True break except Exception as inst: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, unicode(inst)) redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) if sentSignal == False: ## we made it this far and the signal is still not sent. The user must have allowed this to get this far so we send the signal anyway. self._handleSignal(outsig.getValue(), handler, multiple, insig.parent) except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException())
def readTemplates(directory): """Reads the templates that are availabel in the package specified by directory.""" import sys, imp import zipfile global hasErrors, splashWindow, widgetsWithError # print '################readWidgets', directory, package templates = [] for filename in glob.iglob(os.path.join(directory, "*.rrts")): if os.path.isdir(filename) or os.path.islink(filename): continue # protects from a direcoty that has .rrs in it I guess print filename dirname, fname = os.path.split(filename) # dirname, package = os.path.split(dirname) templateName = fname #widgetName = package + '_' + widget try: # make a zipfile and then extract the template xml from it, then we can parse the template xml and set up the registry. try: tempZip = zipfile.ZipFile(filename) except zipfile.BadZipfile: continue if 'template.xml' not in tempZip.namelist(): print 'no template.xml in %s, atts are %s' % (filename, unicode(tempZip.namelist())) continue # these templates will not work with the current settings. tempXML = xml.dom.minidom.parseString(tempZip.read('template.xml')) description = tempXML.getElementsByTagName('saveDescription')[0].getAttribute('tempDescription') try: name = tempXML.getElementsByTagName('Name')[0].getAttribute('name') except: name = templateName #if not splashWindow: #import redREnviron #logo = QPixmap(os.path.join(redREnviron.directoryNames["canvasDir"], "icons", "splash.png")) #splashWindow = QSplashScreen(logo, Qt.WindowStaysOnTopHint) #splashWindow.setMask(logo.mask()) #splashWindow.show() qApp.processEvents() templateInfo = TemplateDescription(name = name, file = filename, description = description, icon = os.path.join(redREnviron.directoryNames['canvasIconsDir'],'dialog-information.png')) templates.append((filename, templateInfo)) if splashWindow: splashWindow.showMessage("Registering template %s" % templateName, Qt.AlignHCenter + Qt.AlignBottom) except Exception, msg: redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException())
def insertFavoriteChildTabs(self, node, tab, widgetRegistry): try: if node.hasChildNodes(): subTabs = node.childNodes else: return for child in subTabs: if child.nodeName == 'group': # we found another group childTab = WidgetTreeFolder(tab, unicode(child.getAttribute('name'))) childTab.widgets = [] childTab.setChildIndicatorPolicy(QTreeWidgetItem.DontShowIndicatorWhenChildless) self.insertFavoriteChildTabs(child, childTab, widgetRegistry) self.insertFavoriteWidgets(child, childTab, widgetRegistry) except: #subtabs don't exist redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) return
def connectSignal(self, signal, wid, enabled = 1, process = True): try: outSig = self.outputs[wid] #print '!@#$ adding signal %s %s' % (unicode(outSig), unicode(signal)) _linkPairs.append((outSig, signal, enabled, 1)) # now send data through redRObjects.addLine(self.parent, signal.parent) # add a line between the two widget on the canvas if process: #print _('processing signal') self._processSingle(outSig, signal) #print 'returning true' return True except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) redRLog.log(redRLog.REDRCORE, redRLog.ERROR, _('redRSignalManager connectSignal: error in connecting signal')) return False
def _handleSignal(self, value, handler, multiple, parentWidget): #print 'handling signal' try: if multiple: handler(value, self.parent.widgetID) else: handler(value) parentWidget.status.setText(_('New Data Received')) parentWidget.removeWarning(id = 'signalHandlerWarning') except: error = _("Error occured in processing signal in this widget.\nPlease check the widgets.\n") parentWidget.setWarning(id = 'signalHandlerWarning', text = unicode(error)) #print error redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException()) parentWidget.status.setText(_('Error in processing signal'))
def updateSuggestedItems(self): self.listWidget.setUpdatesEnabled(0) self.listWidget.clear() last = self.getLastTextItem() tuples = zip(self.itemsAsStrings, self.itemsAsItems) if not self.caseSensitive: tuples = [(text.lower(), item) for (text, item) in tuples] last = last.lower() if self.useRE: try: pattern = re.compile(last) tuples = [(text, item) for (text, item) in tuples if pattern.match(text)] except: redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) tuples = zip(self.itemsAsStrings, self.itemsAsItems) # in case we make regular expressions crash we show all items else: if self.matchAnywhere: tuples = [(text, item) for (text, item) in tuples if last in text] else: tuples = [(text, item) for (text, item) in tuples if text.startswith(last)] items = [tup[1] for tup in tuples] if items: if type(items[0]) == str: self.listWidget.addItems(items) else: for item in items: self.listWidget.addItem(QListWidgetItem(item)) self.listWidget.setCurrentRow(0) self.listWidget.setUpdatesEnabled(1) width = max(self.width(), self.autoSizeListWidget and self.listWidget.sizeHintForColumn(0)+10) if self.autoSizeListWidget: self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.listWidget.resize(width, self.listWidget.sizeHintForRow(0) * (min(self.nrOfSuggestions, len(items)))+5) self.listWidget.move(self.mapToGlobal(QPoint(0, self.height()))) self.listWidget.show() ## if not self.delimiters and items and not self.matchAnywhere: ## self.setText(last + unicode(items[0].text())[len(last):]) ## self.setSelection(len(unicode(self.text())), -(len(unicode(self.text()))-len(last))) ## self.setFocus() else: self.listWidget.hide() return if self.listUpdateCallback: self.listUpdateCallback()
def insertChildActions(canvasDlg, catmenu, categoriesPopup, itab): #### try: #subfile = os.path.abspath(tfile[:tfile.rindex('\\')+1]+itab+'Subtree.txt') #print _('checking file ')+subfile+_(' for more tabs') #f = open(subfile, 'r') if itab.hasChildNodes(): subTabs = itab.childNodes else: return for child in subTabs: if child.nodeName == 'group': # we found another group childTab = catmenu.addMenu(unicode(child.getAttribute('name'))) categoriesPopup.catActions.append(childTab) insertChildActions(canvasDlg, childTab, categoriesPopup, child) insertWidgets(canvasDlg, childTab, categoriesPopup, unicode(child.getAttribute('name'))) except: #subtabs don't exist redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException()) return