Example #1
0
    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 isPickleable(self,d):  # check to see if the object can be included in the pickle file
     # try:
         # cPickle.dumps(d)
         # return True
     # except:
         # return False
         
     
     import re
     if re.search('PyQt4|OWGUIEx|OWToolbars',unicode(type(d))) or d.__class__.__name__ in redRGUI.qtWidgets:
         return False
     elif type(d) in [list, dict, tuple]:
         if type(d) in [list, tuple]:
             for i in d:
                 if self.isPickleable(i) == False:
                     return False
             return True
         elif type(d) in [dict]:
             for k in d.keys():
                 if self.isPickleable(d[k]) == False:
                     #ok = False
                     return False
             return True
     elif type(d) in [type(None), str,unicode, int, float, bool, numpy.float64]:  # list of allowed save types, may epand in the future considerably
         return True
     elif isinstance(d, signals.BaseRedRVariable):
         return True
     else:
         redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Type ' + unicode(d) + ' is not supported at the moment..')  # notify the developer that the class that they are using is not saveable
         return False
Example #3
0
def removeWidgetIcon(icon):
    global _widgetIcons
    for t in _widgetIcons.values():
        redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('widget icon values %s') % str(t))
        while icon in t:
            redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('removing widget icon instance %s') % icon)
            t.remove(icon)
 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
Example #5
0
def getWidgetInstanceByID(wid):
    global _widgetInstances
    #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Loading widget %s keys are %s' % (id, _widgetInstances.keys()))
    try:
        return _widgetInstances[wid]
    except Exception as inst:
        redRLog.log(redRLog.REDRCORE, redRLog.ERROR, _('Error in locating widget %s, available widget ID\'s are %s' % (wid, _widgetInstances.keys())))
Example #6
0
def instances(wantType = 'list'):
    global _widgetInstances
    if wantType == 'list':## return all of the instances in a list
        redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('Widget instances are %s') % unicode(_widgetInstances.values()))
        return _widgetInstances.values()
    else:
        return _widgetInstances
Example #7
0
    def execUpdate(self, file):
        installDir = os.path.split(
            os.path.abspath(redREnviron.directoryNames['redRDir']))[0]
        # print installDir
        cmd = "%s /D=%s" % (file, installDir)
        try:
            if sys.platform == 'win32':
                shell.ShellExecuteEx(
                    shellcon.SEE_MASK_NOCLOSEPROCESS, 0, 'open', file,
                    "/D=%s" % installDir,
                    redREnviron.directoryNames['downloadsDir'], 0)
                # win32process.CreateProcess('Red-R update',cmd,'','','','','','','')
            else:
                print 'This is a linus system updates should be done through the Red-R repository'
        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_()
            return
Example #8
0
    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()
Example #9
0
def readTemplates(directory):
    import sys, imp
    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

        dirname, fname = os.path.split(filename)
        # dirname, package = os.path.split(dirname)
        templateName = fname
        #widgetName = package + '_' + widget
        try:
            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()

            splashWindow.showMessage("Registering template %s" % templateName,
                                     Qt.AlignHCenter + Qt.AlignBottom)
            qApp.processEvents()
            templateInfo = TemplateDescription(name=templateName,
                                               file=filename)
            templates.append(templateInfo)
        except Exception, msg:
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                        redRLog.formatException())
Example #10
0
 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:
         # print att
         try:
             if att in self.dontSaveList or re.search('^_', att):
                 continue
             i += 1
             self.progressBarAdvance(i)
             # print 'frist att: ' + att
             var = getattr(self, att)
             settings[att] = self.returnSettings(var)
         except:
             redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException())
     settings['_customSettings'] = self.saveCustomSettings()
     tempSentItems = self.processSentItems()
     settings['sentItems'] = {'sentItemsList':tempSentItems}
     
     # import pprint
     # pp = pprint.PrettyPrinter(indent=4)
     # pp.pprint(settings)
    
     
     
     #settingsID = self.sqlite.saveObject(settings)
     self.progressBarFinished()
     return settings
Example #11
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)
Example #12
0
 def isPickleable(self,d):  # check to see if the object can be included in the pickle file
     import re
     #if isinstance(d,QObject):
     # print unicode(type(d))
     if re.search('PyQt4|OWGUIEx|OWToolbars',unicode(type(d))) or d.__class__.__name__ in redRGUI.qtWidgets:
         #print 'QT object NOT Pickleable'
         return False
     elif type(d) in [list, dict, tuple]:
         #ok = True
         if type(d) in [list, tuple]:
             for i in d:
                 if self.isPickleable(i) == False:
                     #ok = False
                     return False
             return True
         elif type(d) in [dict]:
             for k in d.keys():
                 if self.isPickleable(d[k]) == False:
                     #ok = False
                     return False
             return True
     elif type(d) in [type(None), str,unicode, int, float, bool, numpy.float64]:  # list of allowed save types, may epand in the future considerably
         return True
     elif isinstance(d, signals.BaseRedRVariable):
         return True
     else: 
         
         redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Type ' + unicode(d) + ' is not supported at the moment..')  # notify the developer that the class that they are using is not saveable
         return False
Example #13
0
    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()
Example #14
0
def loadRequiredPackages(required, loadingProgressBar):
    try:  # protect the required functions in a try statement, we want to load these things and they should be there but we can't force it to exist in older schemas, so this is in a try.
        required = cPickle.loads(required)
        if len(required) > 0:
            if 'CRANrepos' in redREnviron.settings.keys():
                repo = redREnviron.settings['CRANrepos']
            else:
                repo = None
            loadingProgressBar.setLabelText(_('Loading required R Packages. If not found they will be downloaded.\n This may take a while...'))
            RSession.require_librarys(required['R'], repository=repo)
        
        installedPackages = redRPackageManager.getInstalledPackages()
        downloadList = {}
        print type(required['RedR'])
        #print required['RedR']
        
        for name,package in required['RedR'].items():
            #print package
            if (package['Name'] not in installedPackages.keys()) or (float(package['Version']['Number']) > float(installedPackages[package['Name']]['Version']['Number'])):
                print 'my package number %s' % str(float(installedPackages[package['Name']]['Version']['Number'])), 'their package number %s' % str(float(package['Version']['Number']))
                downloadList[package['Name']] = {'Version':unicode(package['Version']['Number']), 'installed':False}

        if len(downloadList.keys()) > 0:
            pm = redRPackageManager.packageManager(canvasDlg)
            pm.show()
            pm.askToInstall(downloadList, _('The following packages need to be installed before the session can be loaded.'))
    except Exception as inst: 
        redRLog.log(redRLog.REDRCORE, redRLog.ERROR, _('redRSaveLoad loadRequiredPackages; error loading package %s') % inst)  
 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
Example #16
0
 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
Example #17
0
 def log(self, comment, level = redRLog.DEVEL):
     """Class implemnetation of logging
     
     Passes parameters to the :mod:`redRLog` module.
     """
     #if not self.widgetID: self.widgetID = 1
     redRLog.log(redRLog.REDRWIDGET,level,comment)
    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_()
Example #19
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)
                widgetState = self.instance().widgetState
                if widgetState.get("Info", {}).values() + widgetState.get(
                        "Warning", {}).values() + widgetState.get(
                            "Error", {}).values() != []:
                    rect.setTop(rect.top() - 21)
            except:
                redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                            redRLog.formatException())
        return rect
Example #20
0
    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 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 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 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 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
Example #25
0
def insertWidgets(canvasDlg, catmenu, categoriesPopup, catName):
    #print 'Widget Registry is \n\n' + unicode(widgetRegistry) + '\n\n'
    widgets = None
    #print unicode(canvasDlg.widgetRegistry['templates'])
    try:
        for wName in redRObjects.widgetRegistry()['widgets'].keys(
        ):  ## move across all of the widgets in the widgetRegistry.  This is different from the templates that are tagged as templates
            widgetInfo = redRObjects.widgetRegistry()['widgets'][wName]
            try:
                if unicode(
                        catName
                ) in widgetInfo.tags:  # add the widget, wtags is the list of tags in the widget, catName is the name of the category that we are adding
                    icon = QIcon(widgetInfo.icon)
                    act = catmenu.addAction(icon, widgetInfo.name)

                    act.widgetInfo = widgetInfo
                    act.category = catmenu
                    if not widgetInfo.name in categoriesPopup.widgetActionNameList:
                        categoriesPopup.allActions.append(act)
                        categoriesPopup.widgetActionNameList.append(
                            widgetInfo.name)
            except Exception as inst:
                redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                            redRLog.formatException())
                pass
    except Exception as inst:
        redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                    'Exception in Tabs with widgetRegistry %s' % inst)
Example #26
0
    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 closeEvent(self, ce, postCloseFun=None):
        # save the current width of the toolbox, if we are using it
        # if isinstance(self.widgetsToolBar, orngTabs.WidgetToolBox):
            # redREnviron.settings["toolboxWidth"] = self.widgetsToolBar.toolbox.width()
        # redREnviron.settings["showWidgetToolbar"] = self.widgetsToolBar.isVisible()
        # redREnviron.settings["showToolbar"] = self.toolbar.isVisible()
#         qtsettings = QSettings("Red-R", "Red-R")
#         qtsettings.setValue("geometry", saveGeometry())
#         qtsettings.setValue("windowState", saveState())
        
        try:
            #ce.accept()
            redREnviron.settings["geometry"] = self.saveGeometry()
            redREnviron.settings["windowState"] = self.saveState()
            redREnviron.settings['pos'] = self.pos()
            redREnviron.settings['size'] = self.size()

            
            
            redREnviron.saveSettings()
            # closed = self.schema.close()
            if redREnviron.settings['dontAskBeforeClose']:
                res = QMessageBox.No
            else:
                res = QMessageBox.question(self, _('Red-R Canvas'),_('Do you wish to save the schema?'), QMessageBox.Yes, QMessageBox.No, QMessageBox.Cancel)
            
            if res == QMessageBox.Yes:
                self.RVariableRemoveSupress = 1
                #saveComplete = 
                closed=redRSaveLoad.saveDocument()
            elif res == QMessageBox.No:
                closed=True
            else:
                closed=False
        
            if closed:
                if postCloseFun:
                    print 'asdfasdfasfd'
                    r = postCloseFun()
                    print 'a', r
                self.canvasIsClosing = 1        # output window (and possibly report window also) will check this variable before it will close the window
                redRObjects.closeAllWidgets() # close all the widget first so their global data is saved
                import shutil
                shutil.rmtree(redREnviron.directoryNames['tempDir'], True) # remove the tempdir, better hope we saved everything we wanted.
                # close the entire session dropping anything that was open in case it was left by something else, 
                # makes the closing much cleaner than just loosing the session.
                
                redRHistory.saveConnectionHistory()
                redRLog.fileLogger.closeLogFile()
                #redRLog.closeLogger()
                ce.accept()
                QMainWindow.closeEvent(self,ce)
                

            else:
                ce.ignore()
        except Exception as inst:
            redRLog.log(redRLog.REDRCORE, redRLog.CRITICAL, 'Error closing session: %s' % unicode(inst))
            ce.ignore()
Example #28
0
def removeWidgetInstanceByID(id):
    try:
        widget = getWidgetInstanceByID(id)
        removeWidgetInstance(widget)
        del _widgetInstances[id]
    except:
        redRLog.log(redRLog.REDRCORE, redRLog.DEBUG,
                    'Failed to remove the widget instance %s' % id)
 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())
Example #30
0
 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
Example #31
0
 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
Example #32
0
def copy():
    ## copy the selected files and reload them as templates in the schema
    
    activeIcons = collectIcons()
    if len(activeIcons) == 0: return
    redRLog.log(redRLog.REDRCORE, redRLog.INFO, _('Making a copy with widgets %s') % _tempWidgets)
    
    makeTemplate(filename = redREnviron.directoryNames['tempDir']+'/copy.rrts', copy=True)
Example #33
0
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
Example #34
0
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 removeLine(self, line):
        if line in self.inLines:
            self.inLines.remove(line)
        elif line in self.outLines:
            self.outLines.remove(line)
        else:
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR, "Red-R Canvas: Erorr. Unable to remove line")

        self.updateTooltip()
Example #36
0
def removeWidgetInstanceByID(wid):
    try:
        widget = getWidgetInstanceByID(wid)
        removeWidgetInstance(widget)
        del _widgetInstances[wid]
        
        
    except Exception as inst: 
        redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Failed to remove the widget instance %s, %s' % (wid, unicode(inst)))
Example #37
0
 def setTable(self, table, colNames, database = None, force = False):
     if not database:
         database = self.dataBase
     if force:
         self.execute('DROP TABLE IF EXISTS '+table, database = database)
     try:
         self.execute("CREATE TABLE "+table+" "+colNames, database = database)
     except Exception as inst:
         redRLog.log(redRLog.REDRCORE, redRLog.ERROR, inst)
Example #38
0
def removeWidgetIcon(icon):
    global _widgetIcons
    for t in _widgetIcons.values():
        redRLog.log(redRLog.REDRCORE, redRLog.DEBUG,
                    _('widget icon values %s') % str(t))
        while icon in t:
            redRLog.log(redRLog.REDRCORE, redRLog.DEBUG,
                        _('removing widget icon instance %s') % icon)
            t.remove(icon)
Example #39
0
def instances(wantType='list'):
    global _widgetInstances
    if wantType == 'list':  ## return all of the instances in a list
        redRLog.log(
            redRLog.REDRCORE, redRLog.DEBUG,
            _('Widget instances are %s') % unicode(_widgetInstances.values()))
        return _widgetInstances.values()
    else:
        return _widgetInstances
Example #40
0
    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())
Example #41
0
 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.'))
Example #42
0
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 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
Example #44
0
 def loadGlobalSettings(self):
     file = self.getGlobalSettingsFile()
     if not 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
Example #45
0
def getWidgetInstanceByID(id):
    global _widgetInstances
    #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Loading widget %s keys are %s' % (id, _widgetInstances.keys()))
    try:
        return _widgetInstances[id]
    except Exception as inst:
        redRLog.log(
            redRLog.REDRCORE, redRLog.ERROR,
            _('Error in locating widget %s, available widget ID\'s are %s, %s')
            % (id, _widgetInstances.keys(), unicode(inst)))
Example #46
0
    def removeLine(self, line):
        if line in self.inLines:
            self.inLines.remove(line)
        elif line in self.outLines:
            self.outLines.remove(line)
        else:
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                        "Red-R Canvas: Erorr. Unable to remove line")

        self.updateTooltip()
Example #47
0
def getWidgetByInstance(instance): 
    """This function returns an icon matching the instance of the sent instance.  This can indicate if a widget is matched with an icon or not to prevent lost widgets from cluttering the session.""" 
    global _widgetIcons
    for t in _widgetIcons.values():
        for widget in t:
            if widget.instance() == instance:
                return widget
    else:
        redRLog.log(redRLog.REDRCORE, redRLog.WARNING, 'Unable to find a matching widget instance %s' % str(instance))
        raise Exception(_('Widget %s not found in %s') % (instance, _widgetIcons))
 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
Example #49
0
 def updatePackagesFromRepository(self):
     #print '|#| updatePackagesFromRepository'
     redRLog.log(redRLog.REDRCORE, redRLog.INFO,
                 _('Updating packages from repository'))
     url = self.repository + '/packages.xml'
     file = os.path.join(redREnviron.directoryNames['canvasSettingsDir'],
                         'red-RPackages.xml')
     from datetime import date
     redREnviron.settings['red-RPackagesUpdated'] = today = date.today()
     #print url, file
     self.urlOpener.retrieve(url, file)
 def addSpinBox(self, key, name, items):
     """Adds a new spinBox to the DynamicSpinBox"""
     print 'Adding spinbox %s' % key
     if key in self.spinBoxes.keys():
         redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'key exists, loading applying settings')
         self.spinBoxes[key].setMaximum(items[0])
         self.spinBoxes[key].setMinimum(items[1])
         self.spinBoxes[key].setValue(items[2])
         self.spinBoxes[key].setDecimals(items[3])
     else:
         self.spinBoxes[key] = spinBox(self, label = name, max = items[0], min = items[1], value = items[2], decimals = items[3], orientation = self.orientation, callback = self.callback, toolTip = self.toolTip)
Example #51
0
 def widgetListStateChange(self,item,col):
     try:
         if item.checkState(0) == Qt.Checked:
             item.pointer['includeInReports'] = True
         else:
             item.pointer['includeInReports'] = False
         # print item.pointer
     except:
         redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException())
         #print 'do nothing'
         pass
Example #52
0
    def R(self,
          query,
          callType='getRData',
          processingNotice=False,
          silent=False,
          showException=True,
          wantType='convert',
          listOfLists=True):

        self.setRIndicator(True)
        #try:
        if processingNotice:
            self.status.setStatus(4)

        qApp.setOverrideCursor(Qt.WaitCursor)
        try:
            commandOutput = RSession.Rcommand(query=query,
                                              silent=silent,
                                              wantType=wantType,
                                              listOfLists=listOfLists)
        except RuntimeError as inst:
            #print _('asdfasdfasdf'), inst
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR,
                        redRLog.formatException())
            qApp.restoreOverrideCursor()
            self.setRIndicator(False)
            if showException:
                QMessageBox.information(self, _('Red-R Canvas'),
                                        _('R Error: ') + unicode(inst),
                                        QMessageBox.Ok + QMessageBox.Default)

            raise RuntimeError(unicode(inst))
            return None  # now processes can catch potential errors

        #except:
        #    print _('R exception occurred')
        self.processing = False
        if processingNotice:
            self.status.setStatus(5)

            #self.progressBarFinished()
        if not silent:
            OWRpy.globalRHistory.append(query)
            self.widgetRHistory.append(query)

            self.ROutput.setCursorToEnd()
            self.ROutput.append(
                '> ' + query
            )  #Keep track automatically of what R functions were performed.

        qApp.restoreOverrideCursor()
        self.setRIndicator(False)
        return commandOutput
Example #53
0
    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 = redRdialog(parent=self,title='Red-R Error')
                
                error = redRwidgetBox(self.msg,orientation='vertical')
                redRwidgetLabel(error, label='Do you wish to report the Error Log?')
                buttons = redRwidgetBox(error,orientation='horizontal')

                redRbutton(buttons, label = _('Yes'), callback = self.uploadYes)
                redRbutton(buttons, label = _('No'), callback = self.uploadNo)
                self.checked = False
                self.remember = redRcheckBox(error,buttons=[_('Remember my Response')],callback=self.rememberResponse)
                res = self.msg.exec_()
                redREnviron.settings['uploadError'] = res
            #print res
            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, 'Error'
                params = urllib.urlencode(err)
                headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
                conn = httplib.HTTPConnection("localhost",80)
                conn.request("POST", "/errorReport.php", params,headers)
                
            else:
                return
        except: 
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException())
            pass
Example #54
0
 def _processSingle(self, signal, connection):
     try:
         #print signal
         if not connection['enabled']: return 0
         handler = connection['signal']['handler']
         multiple = connection['signal']['multiple']
         #print '\n\n\n', connection['signal']['signalClass'], '\n\n\n'
         #print '\n\n\n', 'Signal Value is\n', signal['value'], '\n\n\n'
         if signal['value'] == None: # if there is no data then it doesn't matter what the signal class is, becase none will be sent anyway
             self._handleSignal(signal['value'], handler, multiple, connection['signal']['parent']) 
             self._handleNone(connection['signal']['parent'], connection['signal']['sid'], True)
             self._handleDirty(connection['signal']['parent'], connection['signal']['sid'], False)  ## undo the dirty signal
         elif signal['signalClass'] == 'All' or 'All' in connection['signal']['signalClass']:
             #print '\n\n\nprocessing signal %s using handler: %s with multiple: %s\n\n\n\n' % (signal['value'], handler, multiple)
             self._handleSignal(signal['value'], handler, multiple, connection['signal']['parent']) 
             self._handleDirty(connection['signal']['parent'], connection['signal']['sid'], False)  ## undo the dirty signal
             self._handleNone(connection['signal']['parent'], connection['signal']['sid'], False)   ## indicate that the signal doesn't have a None
         elif signal['signalClass'] in connection['signal']['signalClass']:
             self._handleSignal(signal['value'], handler, multiple, connection['signal']['parent'])
             self._handleDirty(connection['signal']['parent'], connection['signal']['sid'], False)  ## undo the dirty signal
             self._handleNone(connection['signal']['parent'], connection['signal']['sid'], False)   ## indicate that the signal doesn't have a None
         else:
             sentSignal = False
             for sig in connection['signal']['signalClass']:
                 try:
                     if sig in signal['signalClass'].convertToList:
                         newVal = signal['value'].convertToClass(sig)
                         self._handleSignal(newVal, handler, multiple, connection['signal']['parent'])
                         self._handleDirty(connection['signal']['parent'], connection['signal']['sid'], False)  ## undo the dirty signal
                         self._handleNone(connection['signal']['parent'], connection['signal']['sid'], False)   ## indicate that the signal doesn't have a None
                         connection['signal']['value'] = newVal
                         sentSignal = True
                         break
                     elif signal['signalClass'] in sig.convertFromList:
                         tempSignal = sig(data = '', checkVal = False)                       ## make a temp holder to handle the processing.
                         newVal = tempSignal.convertFromClass(signal['value'])
                         self._handleSignal(newVal, handler, multiple, connection['signal']['parent'])
                         self._handleDirty(connection['signal']['parent'], connection['signal']['sid'], False)  ## undo the dirty signal
                         self._handleNone(connection['signal']['parent'], connection['signal']['sid'], False)   ## indicate that the signal doesn't have a None
                         connection['signal']['value'] = newVal
                         sentSignal = True
                         break
                 except:
                     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(signal['value'], handler, multiple, connection['signal']['parent'])
                 self._handleDirty(connection['signal']['parent'], connection['signal']['sid'], False)  ## undo the dirty signal
                 self._handleNone(connection['signal']['parent'], connection['signal']['sid'], False)   ## indicate that the signal doesn't have a None
     except:
         redRLog.log(redRLog.REDRCORE, redRLog.ERROR,redRLog.formatException())
Example #55
0
 def propogateNone(self, ask = True):    
     ## send None through all of my output channels
     redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, _('Propagating None through signal'))
     for id in self.outputIDs():
         #print 'None sent in widget %s through id %s' % (self.parent.widgetID, id)
         self.parent.send(id, None)
     
     ## identify all of the downstream widgets and send none through them, then propogateNone in their inputs
     
     dWidgets = self.linkingWidgets()
     #print dWidgets
     ## send None through all of the channels
     for w in dWidgets:
         w.outputs.propogateNone(ask = False)
Example #56
0
 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)
Example #57
0
 def _handleSignal(self, value, handler, multiple, parentWidget):
     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'))
Example #58
0
 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
Example #59
0
 def refreshToolTip(self):
     #  first we need to get the signals that are sent through the line, there might be more than one so we do it here.
     outinstance = self.outWidget.instance()
     outSignalIDs = [
         i[0]
         for i in outinstance.outputs.getLinkPairs(self.inWidget.instance())
     ]
     tip = 'Signal Data Summary:\n'
     for id in outSignalIDs:
         s = outinstance.outputs.getSignal(id)
         if s and s['value'] != None:
             tip += s['value'].summary() + '\n'
     redRLog.log(
         redRLog.REDRCORE, redRLog.DEBUG,
         'orngCanvasItems in refreshToolTip; setting tooltip to %s' % tip)
     self.setToolTip(tip)