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 installAllPackages():
    # get a list of all packages on the repository
    pm = redRPackageManager.packageManager(redRObjects.canvasDlg)
    pm.installAllPakcages()
    def __init__(self, app, parent = None, flags =  0):
        QMainWindow.__init__(self, parent)
        
        print "starting canvas dlg"
        
        self.setWindowTitle(_("Red-R Canvas %s") % redREnviron.version['REDRVERSION'])
        if os.path.exists(redRStyle.canvasIcon):
            self.setWindowIcon(QIcon(redRStyle.canvasIcon))
        
        ###############################
        #####Start splashWindow####
        ###############################
        logo = QPixmap(redRStyle.redRLogo)
        splashWindow = QSplashScreen(logo, Qt.WindowStaysOnTopHint)
        splashWindow.setMask(logo.mask())
        splashWindow.show()
        
        
        ###############################
        #####Notes and output Docks####
        ###############################
        
        self.notesDock = QDockWidget(_('Notes'))
        self.notesDock.setObjectName(_('CanvasNotes'))
        self.notes = redRTextEdit(None, label = _('Notes'))
        self.notes.setMinimumWidth(200)
        redRSaveLoad.setNotesWidget(self.notes)
        self.notesDock.setWidget(self.notes)
        self.addDockWidget(Qt.RightDockWidgetArea, self.notesDock)
        self.connect(self.notesDock,SIGNAL('visibilityChanged(bool)'),self.updateDock)
        
        print "connected notes dock"
        
        self.outputDock = QDockWidget(_('Output'))
        self.outputDock.setObjectName(_('CanvasOutput'))
        outbox = redRwidgetBox(None)
        self.printOutput = redRTextEdit(outbox, label = _('Output'),displayLabel=False, editable=False)
        hbox = redRwidgetBox(outbox,orientation='horizontal',alignment=Qt.AlignLeft)
        
        redRbutton(hbox, label = _('Save Output'), callback = self.saveOutputToFile)
        redRbutton(hbox, label = _('Clear Output'), callback = lambda: self.printOutput.clear())
        if redREnviron.settings["writeLogFile"]:
            redRbutton(hbox, label = _('Show in Browser'), callback = lambda: redRLog.fileLogger.showLogFile())
        
        self.outputDock.setWidget(outbox)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.outputDock)
        self.connect(self.outputDock,SIGNAL('visibilityChanged(bool)'),self.updateDock)
        #redRLog.setOutputWindow(self.printOutput)
        redRLog.setOutputManager('dock', self.dockOutputManger)
        
        #######################
        #####Output Manager####
        #######################

        # self.output = redROutput.OutputWindow(self)
        # redRLog.setOutputManager('window', self.output.outputManager)
        

        ###################
        #Register Widgets##
        ###################
  
        self.widgetRegistry = redRObjects.widgetRegistry() # the widget registry has been created
        
        print 'Register widgets'
        
        import redRGUI
        redRGUI.registerQTWidgets()
        # signals.registerRedRSignals()
        
        ###################
        #Main Cavas########
        ###################
        splashWindow.showMessage(_("Main Cavas"), Qt.AlignHCenter + Qt.AlignBottom)

        self.schema = orngDoc.SchemaDoc(self)
        self.setCentralWidget(self.schema)
        self.schema.setFocus()

        ###################
        #Toolbar and Menu##
        ###################
        
        splashWindow.showMessage(_("Creating Menu and Toolbar"), Qt.AlignHCenter + Qt.AlignBottom)
        self.toolbar = self.addToolBar(_("Toolbar"))
        self.toolbarFunctions = redRCanvasToolbar.redRCanvasToolbarandMenu(self,self.toolbar)
        self.toolbarFunctions.updateStyle()
        ######################
        #Create Widgets Dock##
        ######################
        
        self.widgetDock = QDockWidget(_('Widgets'))
        self.widgetDock.setObjectName('widgetDock')
        self.widgetDockBox = redRwidgetBox(None)
        self.widgetDockBox.setMinimumWidth(200)
        
        self.widgetDock.setWidget(self.widgetDockBox)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.widgetDock)
        self.connect(self.widgetDock,SIGNAL('visibilityChanged(bool)'),self.updateDock)
        
        self.widgetsToolBar = redRWidgetsTree.WidgetTree(self.widgetDockBox, self, self.widgetRegistry)
        self.suggestButtonsList = redRWidgetsTree.widgetSuggestions(self.widgetDockBox,self)
        
        # self.createWidgetsToolbar() # also creates the categories popup
        # self.toolbar.addWidget(self.widgetsToolBar.widgetSuggestEdit) ## kind of a hack but there you are.        

        ###################
        #####Status Bar####
        ###################
        splashWindow.showMessage(_("Creating Status Bar"), Qt.AlignHCenter + Qt.AlignBottom)
        
        self.statusBar = QStatusBar()
        self.statusBar.setSizeGripEnabled(False)
        self.setStatusBar(self.statusBar)
        
        docBox = redRwidgetBox(None,orientation='horizontal',spacing=4)
        
        self.showWidgetToolbar = redRbutton(docBox, '',toggleButton=True, 
        icon=redRStyle.defaultWidgetIcon, toolTip=_('Widget Tree'), callback = self.updateDockState)   
        
        self.showROutputButton = redRbutton(docBox, '',toggleButton=True, 
        icon=redRStyle.canvasIcon, toolTip=_('Log'), callback = self.updateDockState)   

        self.showNotesButton = redRbutton(docBox, '',toggleButton=True, 
        icon=redRStyle.notesIcon, toolTip=_('Notes'), callback = self.updateDockState)
        
        
        self.statusBar.addPermanentWidget(docBox)
        if 'dockState' in redREnviron.settings.keys() and 'widgetBox' in redREnviron.settings['dockState'].keys():
            self.showNotesButton.setChecked(redREnviron.settings['dockState']['notesBox'])
            self.showROutputButton.setChecked(redREnviron.settings['dockState']['outputBox'])
            self.showWidgetToolbar.setChecked(redREnviron.settings['dockState']['widgetBox'])
        

        

        ###################
        ##Reports##########
        ###################
        splashWindow.showMessage(_("Creating Reports"), Qt.AlignHCenter + Qt.AlignBottom)
        
        self.reports = redRReports.reports(self,self.schema)

        ###################
        ##Update Manager###
        ###################
        # splashWindow.showMessage(_("Creating Update Manager"), Qt.AlignHCenter + Qt.AlignBottom)
        # self.updateManager = redRUpdateManager.updateManager(self)
        
        
        
        
        ########################
        #Load Windows Settings##
        ########################

        splashWindow.showMessage(_("Setting States"), Qt.AlignHCenter + Qt.AlignBottom)

        if 'windowState' in redREnviron.settings.keys():
            self.restoreState(redREnviron.settings['windowState'])

        if 'geometry' in redREnviron.settings.keys():
            self.restoreGeometry(redREnviron.settings['geometry'])

        if 'size' in redREnviron.settings.keys():
            self.resize(redREnviron.settings['size'])
        else:
            # center window in the desktop
            # in newer versions of Qt we can also find the center of a primary screen
            # on multiheaded desktops
            
            width, height = redREnviron.settings.get("canvasWidth", 700), redREnviron.settings.get("canvasHeight", 600)
            desktop = app.desktop()
            deskH = desktop.screenGeometry(desktop.primaryScreen()).height()
            deskW = desktop.screenGeometry(desktop.primaryScreen()).width()
            h = max(0, deskH/2 - height/2)  # if the window is too small, resize the window to desktop size
            w = max(0, deskW/2 - width/2)
            self.move(w,h+2)
            self.resize(width,height)
        if 'pos' in redREnviron.settings.keys():
            self.move(redREnviron.settings['pos'])

        #########################
        #Show Main Red-R window##
        #########################
        
        self.show()
        redRSaveLoad.setCanvasDlg(self)
        redRObjects.setCanvasDlg(self)
        if splashWindow:
            splashWindow.hide()

        
        #########################
        #First Load##
        #########################
        
        try:
            if 'firstLoad' not in redREnviron.settings.keys():
                redREnviron.settings['firstLoad'] = True
            if redREnviron.settings['firstLoad']:
                redRInitWizard.startSetupWizard()
        except:
            redRLog.log(redRLog.REDRCORE, redRLog.ERROR, redRLog.formatException())
            pass
        
        #######################
        #####packageManager####
        #######################
        
        self.packageManager = redRPackageManager.packageManager(self)
        
        if redREnviron.settings['checkForPackageUpdates'] and self.packageManager.updatesAvailable(auto=True):
            self.packageManager.exec_()
            
        print "Processing events"
        #qApp.processEvents()
        print "events processed"