예제 #1
0
    def FetchData(self):
        self.checkList.Clear()
        self.checkListItems = []

        unselectedQualities = [self.listBoxItems[i] for i in range(
            len(self.listBoxItems)) if i not in self.listBox.GetSelections()]

        startWorker(self.OnDataFetched, self.FetchDataWorker, wargs=(
            self.listUrlTextInput.GetLineText(0),
            unselectedQualities,
            int(self.comboBox.GetSelection()) + 1,
            self.userConfig["aliases"]))

        # Progress Dialog
        self.progress = 0
        self.keepGoing = True
        progressDialog = wx.ProgressDialog("Fetching data",
                                           "This may take a while...",
                                           parent=self,
                                           style=wx.PD_APP_MODAL | wx.PD_CAN_ABORT | wx.PD_AUTO_HIDE)

        while self.keepGoing and self.progress < 100:
            wx.MilliSleep(250)
            wx.Yield()
            (self.keepGoing, skip) = progressDialog.Update(self.progress)
        progressDialog.Destroy()
예제 #2
0
	def OnNavigated(self, event):
		url = event.GetURL()
		if url == 'https://www.dropbox.com/1/oauth2/authorize_submit':
			result = self.browser.RunScript("""
				if (!document.getElementsByClassName) {
    				document.getElementsByClassName=function(cn) {
        			var allT=document.getElementsByTagName('*'), allCN=[], i=0, a;
        			while(a=allT[i++]) {
            			a.className==cn ? allCN[allCN.length]=a : null;
        			}
        			return allCN
   					}
				}
				document.title = document.getElementsByClassName('auth-code')[0].innerText;
				""")
			auth_code = self.browser.GetCurrentTitle()
			self.parent.Hide()
			self.Destroy()
			
			track_event('Dropbox auth finished')

			startWorker(did_login, self.shotBufApp.did_finish_auth(auth_code))
			

		else:
			print 'Fail'
예제 #3
0
    def OnCreateFile(self, e=None):
        linetime = self.WXLine.GetValue()
        taudiff = self.WXDecay.GetValue()
        N = self.WXNumber.GetValue()
        inttype = self.WXDropInt.GetValue()
        
        if inttype == "uint16":
            dtype = np.uint16
        else:
            dtype = np.uint32

        # file dialog
        filename = "test_tau{}ms_line{}ms_N{}_{}.dat".format(
                        taudiff, linetime, N, inttype)

        dlg = wx.FileDialog(self, "Save as .dat file", "./", filename, 
              "DAT files (*.dat)|*.dat;*.daT;*.dAt;*.dAT;*.Dat;*.DaT;*.DAt;*.DAT",
           wx.SAVE|wx.FD_OVERWRITE_PROMPT)
        # user cannot do anything until he clicks "OK"
        if dlg.ShowModal() == wx.ID_OK:
            # Workaround for Ubuntu 12.10 since 0.2.0
            path = dlg.GetPath()
        else:
            return

        wx.BeginBusyCursor()

        # start new thread
        args = N, taudiff, linetime, dtype, path
        delayedresult.startWorker(_CreateConsumer, _CreateWorker,
                                  wargs=(args,),)
예제 #4
0
    def OnConvert(self, evt):
        """Convert button event handler."""

        if self.converter and len(self.file_list):
            # Prompt the user to select a destination for the converted file
            saveDialog = wx.FileDialog(self, defaultDir=os.getcwd(),
                                        defaultFile="output.pdf",
                                        style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

            if saveDialog.ShowModal() == wx.ID_OK:
                # Start the conversion process in a different thread
                outputPath = saveDialog.GetPath().replace(".pdf", "")
                startWorker(self.OnConversionCompleted, self.convertWorker,
                            wargs=([file.path for file in self.file_list], outputPath))

                # Show an indeterminate progress bar while the conversion is happening in the background.
                self.progressComplete = False
                self.keepGoing = True
                progressDialog = wx.ProgressDialog("Converting to sheet music",
                                                   "This may take a while...",
                                                   parent=self,
                                                   style=wx.PD_APP_MODAL | wx.PD_CAN_ABORT)

                while self.keepGoing and not self.progressComplete:
                    self.keepGoing = progressDialog.Pulse()[0]
                    wx.MilliSleep(30)
                progressDialog.Destroy()

                if os.path.exists(outputPath):
                    os.remove(outputPath)
 def runMeasurement(self, devices,autoMeasure):
     """ Runs the automatic measurement."""
     self.numDevices = len(devices)
     self.gauge.SetRange(self.numDevices)
     self.text.SetLabel('0 out of %d devices measured'%self.numDevices)
     # Run the automatic measurement in a separate thread so it doesnt block the GUI.
     startWorker(self.measurementDoneCb, self.doMeasurement, wargs=(autoMeasure,devices,self.checkAborted,self.slowThreadUpdateGauge))
     self.ShowModal()
예제 #6
0
def Update(parent):
    """ This is a thread for _Update """
    ghrepo="ZELLMECHANIK-DRESDEN/ShapeOut"
    parent.StatusBar.SetStatusText("Checking for updates...")
    version = so_version.version
        
    delayedresult.startWorker(_UpdateConsumer, _UpdateWorker,
                              wargs=(ghrepo, version),
                              cargs=(parent,))
예제 #7
0
 def handleGet(self, event): 
     """Compute result in separate thread, doesn't affect GUI response."""
     self.buttonGet.Enable(False)
     self.buttonAbort.Enable(True)
     self.abortEvent.clear()
     self.jobID += 1
     
     DR.startWorker(self._resultConsumer, self._resultProducer, 
                               wargs=(self.jobID,self.abortEvent), jobID=self.jobID)
예제 #8
0
    def OnGetUK(self, event):

        self.button_GetUK.Enable(False)
        print u'Тянем Урядовый курьер за %s'%self.text_UK_Date.GetValue()
        self.abortEvent.clear()
        self.jobID += 1
        delayedresult.startWorker(self._resultConsumerUK,
                                  self._resultProducerUK,
                                  wargs=(self.jobID,self.abortEvent),
                                  jobID=self.jobID)
예제 #9
0
    def OnGetRG(self, event):

        self.button_GetRG.Enable(False)
        print u'Тянем рабочку за %s'%self.text_UK_Date.GetValue()
        self.abortEvent.clear()
        self.jobID += 1
        delayedresult.startWorker(self._resultConsumerRG,
                                  self._resultProducerRG,
                                  wargs=(self.jobID,self.abortEvent),
                                  jobID=self.jobID)
예제 #10
0
    def OnGetDAY(self, event):

        self.button_GetDAY.Enable(False)
        print u'Тянем ДЕНЬ'
        self.abortEvent.clear()
        self.jobID += 1
        delayedresult.startWorker(self._resultConsumerDAY,
                                  self._resultProducerDAY,
                                  wargs=(self.jobID,self.abortEvent),
                                  jobID=self.jobID)
예제 #11
0
 def OnGetZN(self, event):
     print 'OK'
     self.button_GetZN.Enable(False)
     print u'Тянем Зеркало Недели'
     self.abortEvent.clear()
     self.jobID += 1
     delayedresult.startWorker(self._resultConsumerZN,
                               self._resultProducerZN,
                               wargs=(self.jobID,self.abortEvent),
                               jobID=self.jobID)
예제 #12
0
 def OnGetCV(self, event):
     print 'OK'
     self.button_GetCV.Enable(False)
     print u'Тянем CV'
     self.abortEvent.clear()
     self.jobID += 1
     delayedresult.startWorker(self._resultConsumerCV,
                               self._resultProducerCV,
                               wargs=(self.jobID,self.abortEvent),
                               jobID=self.jobID)
예제 #13
0
 def OnGetKOM(self, event):
     print 'OK'
     self.button_GetKOM.Enable(False)
     print u'Тянем KOMMENTARI'
     self.abortEvent.clear()
     self.jobID += 1
     delayedresult.startWorker(self._resultConsumerKOM,
                               self._resultProducerKOM,
                               wargs=(self.jobID,self.abortEvent),
                               jobID=self.jobID)
예제 #14
0
    def onAnuncios(self, event):

        # global lista_anuncios
        # message = "Analizando el archivo %s " %str(self.currentFile)
        # busy = PBI.PyBusyInfo(message, parent=None, title="Procesando")
        # #lista_anuncios=delayedresult.startWorker(self.tonteriamaxima,self.reconocer_huellas())
        # lista_anuncios=self.reconocer_huellas()
        # wx.Yield()
        # del busy

        delayedresult.startWorker(self.resultConsumer, self.resultProducer, wargs=(self.currentFile,))
예제 #15
0
    def __call__(self):
        """ Make the call! """

        # Display the progress dialog (we do it here and NOT in the result
        # producer because the producer is NOT in the GUI thread!).
        self._open_progress_dialog()

        import wx.lib.delayedresult as delayedresult
        delayedresult.startWorker(self._result_consumer, self._result_producer)

        return
예제 #16
0
 def handleGet(self, event): 
     """Compute result in separate thread, doesn't affect GUI response."""
     self.buttonGet.Enable(False)
     self.buttonAbort.Enable(True)
     self.abortEvent.clear()
     self.jobID += 1
     
     self.log( "Starting job %s in producer thread: GUI remains responsive"
               % self.jobID )
     delayedresult.startWorker(self._resultConsumer, self._resultProducer, 
                               wargs=(self.jobID,self.abortEvent), jobID=self.jobID)
예제 #17
0
파일: update.py 프로젝트: DerDeef/ShapeOut
def Update(parent):
    """ This is a thread for _Update """
    ghrepo="ZellMechanik-Dresden/ShapeOut"
    parent.StatusBar.SetStatusText("Checking for updates...")
    if hasattr(so_version, "repo_tag"):
        version = so_version.repo_tag  # @UndefinedVariable
    else:
        version = so_version.version
        
    delayedresult.startWorker(_UpdateConsumer, _UpdateWorker,
                              wargs=(ghrepo, version),
                              cargs=(parent,))
예제 #18
0
파일: main.py 프로젝트: wucaicheng/peanuts
    def TestCaseRunDialog(self, testcase):

        self.abortEvent = delayedresult.AbortEvent()
        self.abortEvent.clear()
        self.jobID = 1
        self.runFlag = True  # testcases were completed, destory dlg
        testKeepGoing = True

        self.dlg = wx.ProgressDialog('Executing test suite progress',
                                     'Running......please wait.',
                                     maximum=50,
                                     parent=self,
                                     style=0
                                           | wx.PD_APP_MODAL
                                           | wx.PD_CAN_ABORT
                                           ##                        | wx.PD_CAN_SKIP
                                           | wx.PD_ELAPSED_TIME
                                           | wx.PD_REMAINING_TIME
                                     ##                        | wx.PD_AUTO_HIDE
                                     )

        delayedresult.startWorker(self.DestoryTestCaseRunDialog, self.TextTestRunnerFailCheck,
                                  wargs=(self.jobID, self.abortEvent, testcase, v.FAIL_RETRY),
                                  jobID=self.jobID)

        # start memory monitor
        self.memMon = mm.HttpMemCPUMonitor(v.MEM_MONITOR_INTERVAL)
        self.memMon.start()

        if v.CONNECTION_TYPE is not 3:
            self.memMonXlsx = mm.MemMonitorXlsx(v.MEM_MONITOR_INTERVAL, file=v.MAIL_XLSX)
            # self.memMonXlsx.setDaemon(True)
            self.memMonXlsx.start()

        while testKeepGoing and self.runFlag:
            wx.Yield()  # refresh progress
            (testKeepGoing, skip) = self.dlg.Pulse()
            t.sleep(0.1)
            # set testKeepGoing to False when click cancel

        if os.path.exists(v.TEST_SUITE_LOG_PATH):
            if not os.path.exists(v.REPORT_NAME):
                os.rename(v.TEST_SUITE_LOG_PATH, v.REPORT_NAME)
            else:
                os.rename(v.TEST_SUITE_LOG_PATH, v.REPORT_NAME + "_" + str(random.randint(1, 9999)))

        if testKeepGoing is False: # click cancel
            os.system("taskkill /F /IM python.exe | taskkill /F /T /IM adb.exe")
        else: # reboot android device
            co.setAdbReboot(v.ANDROID_SERIAL_NUM, v.DEVICE_STATUS_LOG)
        self.abortEvent.set()
        self.dlg.Destroy()
예제 #19
0
 def _renderstart(self):
     self.abortEvent.clear()
     self.rendering = True
     self.html.UpdateRenderText(_("Started..."))
     self.jobID += 1
     
     params = self.createParams()
     print "-"*20
     for p in params:
         print type(p), p
     
     delayedresult.startWorker(self._resultConsumer, self._resultProducer,
             wargs=(self.jobID,self.abortEvent, params), jobID=self.jobID)
예제 #20
0
    def UpdateList(self, url=PLUGIN_REPO):
        """Update the list of available downloads
        @param url: url to fetch update list from
        @postcondition: Worker thread is started that will update list when it
                        finishes.

        """
        if self._list.GetItemCount():
            self._list.DeleteAllItems()
        frame = self.GetGrandParent()
        frame.SetStatusText(_("Retrieving Plugin List") + "...", 0)
        frame.Busy(True)
        delayedresult.startWorker(self._UpdateCatcher, _GetPluginListData, wkwargs={"url": url}, jobID="update")
예제 #21
0
 def DelayedWorkerLoadData(self):
     if hasattr(self.gauge, "Pulse"):
         self.gauge.Pulse()
     else:
         self.gauge.SetRange(2)
         self.gauge.SetValue(1)
         
     self.tc.SetValue("Loading...")
     self.job_id += 1
     self.url.Insert(self.url.GetValue(),0)
     self.SaveState()
     delayedresult.startWorker(self.LoadComplete, self.LoadData, 
                                       jobID=self.job_id)
예제 #22
0
    def on_generate_q_vectors(self, event):

        generator = self._generatorsChoice.GetStringSelection()
        generator = REGISTRY["qvectors"][generator](self._trajectory.universe)
        parameters = self._configurationPanel.get_value()
        generator.configure(parameters)
        
        qPanel = QVectorsPanel(generator,parameters,self._mainPanel,wx.ID_ANY)
        self._notebook.AddPage(qPanel, "Q Vectors")
        
        qPanel.udName.Disable()
        qPanel.saveButton.Disable()
        
        startWorker(self.generate_q_vectors_done, self.generate_q_vectors, cargs=(qPanel,),wargs=(generator,qPanel.progress.status))                                          
예제 #23
0
    def __init__(self, store):
        ORMKeyValueObject.__init__(self, store)
        self.Store = store
        self.Accounts = AccountList(store)
        self._Tags = {}

        # Handle Mint integration, but send the message in the main thread, otherwise, dead.
        if self.MintEnabled:
            delayedresult.startWorker(lambda result: Publisher.sendMessage("mint.updated"), Mint.LoginFromKeyring, wkwargs={"notify": False})

        Publisher.subscribe(self.onCurrencyChanged, "user.currency_changed")
        Publisher.subscribe(self.onMintToggled, "user.mint.toggled")
        Publisher.subscribe(self.onAccountChanged, "view.account changed")
        Publisher.subscribe(self.onTransactionTagged, "transaction.tagged")
        Publisher.subscribe(self.onTransactionUntagged, "transaction.untagged")
예제 #24
0
  def Run( self, title = 'Save Image Montage' ):
    """
Must be called from the UI event thread.
Creates a separate thread with the _Run() method as target.
@param  file_path	path to gif file to create
@return			thread that was started
"""
    dialog = wx.ProgressDialog( title, 'Loading images...', self.totalSteps )
    dialog.Show()

    wxlibdr.startWorker(
	self._RunEnd,
	self._RunBegin,
	wargs = [ dialog, title ]
        )
예제 #25
0
    def _renderstart(self):
        self.abortEvent.clear()
        self.rendering = True
        self.html.UpdateRenderText(_("Started..."))
        self.jobID += 1

        params = self.createParams()
        print "-" * 20
        for p in params:
            print type(p), p

        delayedresult.startWorker(self._resultConsumer,
                                  self._resultProducer,
                                  wargs=(self.jobID, self.abortEvent, params),
                                  jobID=self.jobID)
예제 #26
0
 def connect_handler(self, ip_port):
     ip, port = ip_port.split(":", 1)
     try:
         port = int(port)
     except ValueError:
         self.add_error_text(lang.getstr("port.invalid", port) + "\n")
         self.add_text("> ")
         return
     if self.conn:
         self.disconnect()
     self.add_text(lang.getstr("connecting.to", (ip, port)) + "\n")
     self.busy = True
     delayedresult.startWorker(self.check_result,
                               self.connect,
                               cargs=(self.get_app_info, None, False),
                               wargs=(ip, port))
예제 #27
0
    def modbusAutoPollingOver(self, something):

        print('Something:', something)
        print('Checking for Queued Items')
        if self.manQ:
            print('Sending queued item...')
            temp = self.manQ.pop()
            ret = self.sendModbus(temp)
            # print('Queue process returned data' , ret)
            wx.CallAfter(self.updateScreen, temp, ret)
            print('Starting worker in poll over queued item...')
            startWorker(self.modbusAutoPollingOver, self.modbusAutoPolling)
        else:
            print('No queued items...')
            print('Starting worker in poll over no queued item...')
            startWorker(self.modbusAutoPollingOver, self.modbusAutoPolling)
예제 #28
0
  def Run( self, callback = None ):
    """Launches load.
Must be called in the UI thread.
@param  callback	optional callback function invoked upon completion
			with prototype
			callback( boolean env_loaded, float load_time_secs )
"""
    dialog = wx.ProgressDialog(
        'Loading 3D Environment', 'Initializing...', 10
	)
    dialog.Show();

    wxlibdr.startWorker(
	self._RunEnd, self._RunBegin,
	wargs = [ dialog, callback ]
        )
예제 #29
0
    def UpdateList(self, url=PLUGIN_REPO):
        """Update the list of available downloads
        @param url: url to fetch update list from
        @postcondition: Worker thread is started that will update list when it
                        finishes.

        """
        if self._list.GetItemCount():
            self._list.DeleteAllItems()
        frame = self.GetGrandParent()
        frame.SetStatusText(_("Retrieving Plugin List") + "...", 0)
        frame.Busy(True)
        delayedresult.startWorker(self._UpdateCatcher,
                                  _GetPluginListData,
                                  wkwargs={'url': url},
                                  jobID='update')
예제 #30
0
 def async_send(self, msg_id, msg_data=(), datatype='l'):
   """Create a thread to do the sync without stalling the gui"""
   if not self.sending_command:
     self.sending_command = True
     self.m.parent.pause_stop.enable_stop(True)
     if len(datatype) == 1:
       data_str = msg_id + ' ' + ' '.join([hexlify(pack(datatype, x))
                                           for x in msg_data])
     else:
       data_str = msg_id
       for i in range(len(datatype)):
         data_str += ' ' + hexlify(pack(datatype[i], msg_data[i]))
     delayedresult.startWorker(self._send_response, self.send,
                               wargs=(data_str,), jobID=msg_id)
   else:
     self.m.update_status("Command in progress", 0)
    def OnSearchText(self, event):
        if not self.string_text.GetValue():
            return
        self.results.DeleteAllItems()
        del self.result_indices[:]
        pattern = re.compile(self.string_text.GetValue())

        if self.root is None and self.indices:
            self.root = self.tree.model.GetItem(self.indices)[2]
        if isinstance(self.root, (List, Structure)):
            self.progress = wx.ProgressDialog(
                "Searching...",
                'Searching for "%s"' % pattern.pattern,
                parent=self,
                style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_SMOOTH)
            from random import random

            def check(s):
                if random() < 0.05:
                    cont, skip = self.progress.UpdatePulse()
                    if not cont:
                        raise StopIteration, 'search cancelled'
                m = pattern.search(s)
                return bool(m)

            def store(s, indices):
                #if m.start() > self.truncate:
                #    self.results.Append(('...'+(s[m.start()-self.truncate-3:]),))
                #else:
                self.results.Append((s, ))
                self.result_indices.append(indices)

            self.search_button.Enabled = False

            #search = SearchString(check, store, self.indices)
            #self.root.accept(search)
            #self.search_button.Enabled = True

            search = SearchString(check, partial(wx.CallAfter, store),
                                  self.indices)
            delayedresult.startWorker(self.OnSearchDone,
                                      self.root.accept,
                                      wargs=[search])
        elif isinstance(self.root, unicode):
            if pattern.search(self.root):
                self.results.Append((self.root, ))
                self.result_indices.append(self.indices)
예제 #32
0
    def DownloadUpdates(self, dl_loc=wx.EmptyString):
        """Downloads available updates and configures the bar.
        Returns True if the update was successfull or False if
        it was not. The updates will be downloaded to the
        specified location or to the Users Desktop or Home
        Folder if no location is specified.
        @keyword dl_loc: location to download file to

        """
        self.LOG("[updater][info] UpdateProgress: Download Starting...")
        if dl_loc == wx.EmptyString:
            dl_loc = self.GetDownloadLocation()
        self._mode = self.ID_DOWNLOADING
        self.SetValue(0)
        self.Start(50)  # XXX Try this for starters
        self._downloading = True  # Mark the work status as busy
        delayedresult.startWorker(self._ResultNotifier, self._DownloadThread, wargs=dl_loc, jobID=self.ID_DOWNLOADING)
예제 #33
0
    def CheckForUpdates(self):
        """Checks for updates and activates the bar. In order to keep the
        UI from freezing while checking for updates the actual work is carried
        out on another thread. When the thread exits it will set the _checking
        attribute to false and set the _status attribute (See GetStatus) to the
        return value of the check function which is either a version string or
        an appropriate error message.

        @see: L{_UpdatesCheckThread}

        """
        # Set bar to Checking mode so it knows to simulate update progress
        self._mode = self.ID_CHECKING
        self.SetValue(0)
        self.Start(10)
        self._checking = True
        delayedresult.startWorker(self._ResultNotifier, self._UpdatesCheckThread, jobID=self.ID_CHECKING)
	def __open(self, url):
		if self.__openBusyFile:
			self.__openBusyFile()
		self.__workerThread = delayedresult.startWorker(
			self.__resultConsumer,
			self.__resultProducer,
			wargs = (url, self.__abortEvent),
		)
예제 #35
0
    def DownloadUpdates(self, dl_loc=wx.EmptyString):
        """Downloads available updates and configures the bar.
        Returns True if the update was successfull or False if
        it was not. The updates will be downloaded to the
        specified location or to the Users Desktop or Home
        Folder if no location is specified.
        @keyword dl_loc: location to download file to

        """
        self.LOG("[updater][info] UpdateProgress: Download Starting...")
        if dl_loc == wx.EmptyString:
            dl_loc = self.GetDownloadLocation()
        self._mode = self.ID_DOWNLOADING
        self.SetValue(0)
        self.Start(50)   #XXX Try this for starters
        self._downloading = True # Mark the work status as busy
        delayedresult.startWorker(self._ResultNotifier, self._DownloadThread,
                                  wargs=dl_loc, jobID=self.ID_DOWNLOADING)
예제 #36
0
    def start_indexing(self, event):
        ''' This function is called when the "Start Indexing" button is pressed.
        '''
        self.indbtn.Enable(False)
        self.abortEvent.clear()
        self.jobID += 1

        self.log.SetValue("Starting indexing process:")
        if self.bulkrb.GetValue():
            delayedresult.startWorker(self._resultConsumer,
                                      self.create_bulk_index,
                                      wargs=(self.jobID,self.abortEvent),
                                      jobID=self.jobID)
        elif self.splitrb.GetValue():
            delayedresult.startWorker(self._resultConsumer,
                                      self.create_split_index,
                                      wargs=(self.jobID,self.abortEvent),
                                      jobID=self.jobID)
예제 #37
0
def startWorker(consumer=None, workerFn=None, wargs=None, wkwargs=None):
    def catch(*args, **kwargs):
        try:
            workerFn(*args, **kwargs)
        except:
            print traceback.format_exc()
            raise
    return delayedresult.startWorker(consumer=consumer, workerFn=catch,
                                     wargs=wargs, wkwargs=wkwargs)
예제 #38
0
def runInParallel( listOfSnippets, numberOfThreads, caption=""):
  runInParallel.res = None
  for i in listOfSnippets:
    if isinstance(i,file):
      i.seek(0)
  progress = wx.ProgressDialog("Tasks completion progress",
                               caption,
                               maximum = len(listOfSnippets),
                               parent=None,
                               style = wx.PD_CAN_ABORT
                                | wx.PD_APP_MODAL
                                | wx.PD_ELAPSED_TIME
                                | wx.PD_REMAINING_TIME
                                | wx.PD_SMOOTH
                                )

  def doRun():
    for i in xrange( min(numberOfThreads, len(listOfSnippets)) ):
      t = ThreadRunner()
      t.start()
    ThreadRunner.queue.join()
    return ThreadRunner.getResults()

  def consumer(delayedResult):
    resQueue = delayedResult.get()
    runInParallel.res = [None]*resQueue.qsize()
    while not resQueue.empty():
      elem = resQueue.get()
      runInParallel.res[elem[0]] = elem[1]

  for taskN, snippet in enumerate(listOfSnippets):
    ThreadRunner.queue.put((taskN, snippet))

  delayedresult.startWorker(consumer, doRun)
  while (threading.activeCount() > 1) or (not ThreadRunner.queue.empty()):
    wx.MilliSleep(500)
    i = (len(listOfSnippets) - ThreadRunner.queue.qsize())-(threading.activeCount()-1)
    keepgoing = progress.Update( i )[0]
    if not keepgoing: 
      ThreadRunner.stop()
      break
  progress.Destroy()

  return runInParallel.res
예제 #39
0
    def CheckForUpdates(self):
        """Checks for updates and activates the bar. In order to keep the
        UI from freezing while checking for updates the actual work is carried
        out on another thread. When the thread exits it will set the _checking
        attribute to false and set the _status attribute (See GetStatus) to the
        return value of the check function which is either a version string or
        an appropriate error message.

        @see: L{_UpdatesCheckThread}

        """
        # Set bar to Checking mode so it knows to simulate update progress
        self._mode = self.ID_CHECKING
        self.SetValue(0)
        self.Start(10)
        self._checking = True
        delayedresult.startWorker(self._ResultNotifier,
                                  self._UpdatesCheckThread,
                                  jobID=self.ID_CHECKING)
예제 #40
0
    def onRunButton(self, evt):

        global optionParser
        inputFiles = re.split(r'\s+', self.t1.GetValue().strip())

        optionParser.options.project = self.t2.GetValue()

        optionParser.options.email = self.t3.GetValue()

        if not inputFiles or not optionParser.options.project:
            dlg = wx.MessageDialog(
                self,
                'You need to specify an input sequence file and a project folder before you can start the analysis',
                'Missing input information.', wx.OK | wx.ICON_ERROR
                #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                #wx.OK | wx.ICON_INFORMATION
            )
            dlg.ShowModal()
            dlg.Destroy()
            return

        optionParser.postProcess(guiParent=self)

        self.logframe.Show(True)

        self.runB.Enable(False)
        self.optionsB.Enable(False)
        self.b1.Enable(False)
        self.b2.Enable(False)
        self.t1.Enable(False)
        self.t2.Enable(False)
        self.abortB.Enable(True)
        self.abortB.SetDefault()
        self.abortEvent.clear()
        self.jobID += 1
        delayedresult.startWorker(self._resultConsumer,
                                  self._resultProducer,
                                  wargs=(self.jobID, self.abortEvent,
                                         inputFiles),
                                  jobID=self.jobID)
예제 #41
0
 def Render(self):
     """ Callable render method. This is intended to be the 'master' render
     method, called when the Node Graph image is to be rendered. After this is
     complete, the result event will be called.
     """
     if meta.ENABLE_THREADING is True:
         self._abortEvent.clear()
         self._jobID += 1
         delayedresult.startWorker(self._PostRender,
                                   self._Render,
                                   wargs=(self._jobID, self._abortEvent),
                                   jobID=self._jobID)
     else:
         self._imageViewport.UpdateInfoText(True)
         self._renderer.Render(self._nodeGraph.GetNodes())
         render_image = self._renderer.GetRender()
         if render_image is not None:
             self._imageViewport.UpdateViewerImage(
                 utils.ConvertImageToWx(render_image),
                 self._renderer.GetTime())
         self._imageViewport.UpdateInfoText(False)
         self._nodeGraph.UpdateAllNodes()
예제 #42
0
 def check_result(self,
                  delayedResult,
                  get_response=False,
                  additional_commands=None,
                  colorize=True):
     try:
         result = delayedResult.get()
     except Exception as exception:
         if hasattr(exception, "originalTraceback"):
             self.add_text(exception.originalTraceback)
         result = exception
     if result:
         if isinstance(result, socket.socket):
             self.conn = result
             result = lang.getstr("connection.established")
         text = "%s\n" % safe_unicode(result)
         self.add_text(text)
         if colorize or isinstance(result, Exception):
             end = self.console.GetLastPosition()
             start = end - len(text)
             if isinstance(result, Exception):
                 color = ERRORCOLOR
             else:
                 color = RESPONSECOLOR
             self.mark_text(start, end, color)
     if get_response and not isinstance(result, Exception):
         delayedresult.startWorker(self.check_result,
                                   get_response,
                                   cargs=(False, additional_commands))
     else:
         self.add_text("> ")
         if additional_commands:
             self.add_text(additional_commands[0].rstrip("\n"))
             if additional_commands[0].endswith("\n"):
                 self.send_command_handler(additional_commands[0],
                                           additional_commands[1:])
                 return
         self.console.SetFocus()
         self.busy = False
예제 #43
0
 def DownloadUpdates(self, dl_loc=wx.EmptyString):
     """Downloads available updates and configures the bar.
     Returns True if the update was successfull or False if
     it was not. The updates will be downloaded to the 
     specified location or to the Users Desktop or Home
     Folder if no location is specified.
     @keyword dl_loc: location to download file to
     
     """
     self.LOG("[updateprog][evt] Attempting to download updates...")
     if dl_loc == wx.EmptyString:
         dl_loc = wx.GetHomeDir() + util.GetPathChar()
         if os.path.exists(dl_loc + u"Desktop"):
             dl_loc = dl_loc + u"Desktop" + util.GetPathChar()
     self._mode = self.ID_DOWNLOADING
     self.SetValue(0)
     self.Start(50)  #XXX Try this for starters
     self._downloading = True  # Mark the work status as busy
     delayedresult.startWorker(self._ResultNotifier,
                               self._DownloadThread,
                               wargs=dl_loc,
                               jobID=self.ID_DOWNLOADING)
예제 #44
0
def startWorker(consumer=None, workerFn=None, wargs=None, wkwargs=None):
    def catch(*args, **kwargs):
        import traceback
        try:
            workerFn(*args, **kwargs)
        except Exception:
            print(traceback.format_exc())
            raise

    return delayedresult.startWorker(consumer=consumer,
                                     workerFn=catch,
                                     wargs=wargs,
                                     wkwargs=wkwargs)
예제 #45
0
    def OnButton(self, evt):
        """Handles the Button Events.
        @param evt: Event that called this handler
        @type evt: wx.EVT_BUTTON

        """
        e_id = evt.GetId()
        if e_id == self.ID_DOWNLOAD:
            urls = list()
            for item in self._dl_list:
                if self._dl_list[item] and item in self._p_list:
                    urls.append(self._p_list[item].GetUrl())
            self._eggcount = len(urls)

            # Start a separate thread to download each selection
            for egg in range(len(urls)):
                self.GetGrandParent().SetStatusText(_("Downloading") + "...", 0)
                self.GetGrandParent().Busy(True)
                delayedresult.startWorker(self._ResultCatcher, _DownloadPlugin,
                                          wargs=(urls[egg]), jobID=egg)
        else:
            evt.Skip()
예제 #46
0
  def _OnCreate( self, ev ):
    """
Called on the UI thread.
"""
    ev.Skip()

    mpact_path = self.fMpactField.GetValue()
    shift_path = self.fShiftField.GetValue()
    output_path = self.fOutputField.GetValue()

#		-- Check inputs
#		--
    msg = ''
    if len( mpact_path ) == 0:
      msg = 'Please select an MPACT file'
    elif not os.path.exists( mpact_path ):
      msg = 'MPACT file "{0:s}" not found'.format( mpact_path )

    elif len( shift_path ) == 0:
      msg = 'Please select a Shift file'
    elif not os.path.exists( shift_path ):
      msg = 'Shift file "{0:s}" not found'.format( shift_path )

    elif len( output_path ) == 0:
      msg = 'Please specify an output file'

    if msg:
      wx.MessageDialog( self, msg, 'Create Excore Output' ).\
          ShowWindowModal()
    else:
      self.fCreateButton.Disable()
      self.fProgressField.SetLabel(
	  'Creating {0:s} from {1:s} and {2:s}'.\
	  format( output_path, mpact_path, shift_path )
          )
      #self.fProgressGauge.SetValue( 0 )
      self.fProgressGauge.Pulse()
      self.fProgressGauge.Show()

      wargs = [ mpact_path, shift_path, output_path ]
      th = wxlibdr.startWorker(
          self._CreateTaskEnd, self._CreateTaskBegin,
	  wargs = wargs
	  )
예제 #47
0
 def runcpabe(runtype, jid, onresult, *args):
     """
         Environment variables exposed to all other modules,
         including the home path, shared folder path and name,
         key path, ABEsafe configuration path, and the database file
     """
     if runtype == CPABE.ENC:
         fcreate = args[0]
         f_seg2 = fcreate.rpartition('.')
         f_seg = f_seg2[0].rpartition('.')
         fcheck = fcreate
         replica = 1
         while os.path.exists(fcheck) and replica <= sys.maxint:
             fcheck = f_seg[0] + "(" + str(replica) + ")" + f_seg[
                 1] + f_seg[2] + f_seg2[1] + f_seg2[2]
             replica += 1
         import tempfile
         ftmp = tempfile.NamedTemporaryFile()
         result = CPABE.libc.abe_encrypt(
             str(ftmp.name), str(os.path.join(CPABE.CONFIG_PATH,
                                              ".pub_key")), str(args[1]),
             str(args[2].replace(';', '')))
         DR.startWorker(onresult,
                        CPABE.execbg,
                        cargs=(ftmp, fcheck),
                        wargs=(result, ),
                        jobID=jid)
     elif runtype == CPABE.DEC:
         result = CPABE.libc.abe_decrypt(
             str(args[0]), str(os.path.join(CPABE.CONFIG_PATH, ".pub_key")),
             str(os.path.join(CPABE.KEYS_PATH, args[1])),
             str(args[2].replace(';', '')))
         DR.startWorker(onresult, CPABE.execbg, wargs=(result, ), jobID=jid)
     elif runtype == CPABE.OPEN:
         status = CPABE.libc.abe_checkopen(
             str(os.path.join(CPABE.CONFIG_PATH, ".pub_key")),
             str(os.path.join(CPABE.KEYS_PATH, args[0])),
             str(args[1].replace(';', '')))
         return status
     elif runtype == CPABE.MKEY:
         result = CPABE.libc.abe_checkmetapriv(
             str(os.path.join(CPABE.CONFIG_PATH, ".pub_key")), str(args[0]),
             str(os.path.join(CPABE.KEYS_PATH, args[1]).replace(';', '')))
         DR.startWorker(onresult, CPABE.execbg, wargs=(result, ), jobID=jid)
     elif runtype == CPABE.POK:
         if re.sub(r"\s+", '', args[0]) == "":
             return 1
         status = CPABE.libc.abe_checkmeta(
             str(os.path.join(CPABE.CONFIG_PATH, ".pub_key")),
             str(args[0].replace(';', '')))
         return status
예제 #48
0
    def __init__(self, *args, **kwargs):

        self.n = 100
        self.xqueue = deque('')
        self.runningMean = 0
        self.current_time = 0
        self.elapsed_time = 0
        self.saved_time = 0
        self.millis = 0
        self.frame = wx.Frame(
            *args,
            **kwargs,
            size=(1280, 1024),
        )
        self.frame.Center()
        self.panel = wx.Panel(self.frame)
        self.jobID = 0
        self.packetIterator = 0
        self.test1 = 0

        # fonts
        largeFont = wx.Font(34, wx.ROMAN, wx.NORMAL, wx.NORMAL)

        # this is a new comment
        # # labels
        # self.miscLbl = wx.StaticText(self.panel, -1, pos=(10,30),size = (120,20))
        self.tmpLbl_1 = wx.StaticText(self.panel,
                                      -1,
                                      pos=(10, 10),
                                      size=(120, 20))
        self.tmpLbl_1.SetLabel('Temperature')
        self.temperatureLbl = wx.StaticText(self.panel,
                                            -1,
                                            pos=(30, 20),
                                            size=(120, 20))
        self.temperatureLbl.SetFont(largeFont)

        self.tmpLbl_2 = wx.StaticText(self.panel,
                                      -1,
                                      pos=(20, 60),
                                      size=(120, 20))
        self.tmpLbl_2.SetLabel('Humdity')
        self.humidityLbl = wx.StaticText(self.panel,
                                         -1,
                                         pos=(30, 70),
                                         size=(120, 20))
        self.humidityLbl.SetFont(largeFont)

        self.tmpLbl_2 = wx.StaticText(self.panel,
                                      -1,
                                      pos=(10, 110),
                                      size=(120, 20))
        self.tmpLbl_2.SetLabel('Light Sensor')
        self.lightLbl = wx.StaticText(self.panel,
                                      -1,
                                      pos=(30, 130),
                                      size=(120, 20))
        self.lightLbl.SetFont(largeFont)

        self.tmpLbl_3 = wx.StaticText(self.panel,
                                      -1,
                                      pos=(10, 250),
                                      size=(120, 20))
        self.tmpLbl_3.SetLabel('Packet Time')
        self.packetTime = wx.StaticText(self.panel,
                                        -1,
                                        pos=(100, 250),
                                        size=(120, 20))

        self.tmpLbl_4 = wx.StaticText(self.panel,
                                      -1,
                                      pos=(10, 280),
                                      size=(120, 20))
        self.tmpLbl_4.SetLabel('Poll Count')
        self.pollCount = wx.StaticText(self.panel,
                                       -1,
                                       pos=(100, 280),
                                       size=(120, 20))

        self.tmpLbl_5 = wx.StaticText(self.panel,
                                      -1,
                                      pos=(10, 310),
                                      size=(120, 20))
        self.tmpLbl_5.SetLabel('ESP ID')
        self.lbl_espID = wx.StaticText(self.panel,
                                       -1,
                                       pos=(100, 310),
                                       size=(120, 20))

        #comment

        # bitmaps
        self.PilotLightGreenOn = wx.Image("PilotLightGreenOn.bmp")
        self.PilotLightGreenOn = self.PilotLightGreenOn.Scale(
            20, 20, wx.IMAGE_QUALITY_HIGH)

        self.PilotLightRedOn = wx.Image("PilotLightRedOn.bmp")
        self.PilotLightRedOn = self.PilotLightRedOn.Scale(
            20, 20, wx.IMAGE_QUALITY_HIGH)

        self.ctrlsHreg = []
        self.ctrlsHreg.append('')
        for i in range(1, 42):
            setattr(
                self, "labelCtrlHreg%s" % (i),
                wx.StaticText(self.panel,
                              -1,
                              label='hReg' + str(i),
                              pos=(300, 20 * (i - 1)),
                              name='lblHreg' + str(i)))
            self.ctrlsHreg.append(
                wx.StaticText(self.panel,
                              -1,
                              label='',
                              pos=(400, 20 * (i - 1)),
                              name=''))

        for i in range(42, 85):
            setattr(
                self, "labelCtrlHreg%s" % (i),
                wx.StaticText(self.panel,
                              -1,
                              label='hReg' + str(i),
                              pos=(500, 20 * (i - 43)),
                              name='lblHreg' + str(i)))
            self.ctrlsHreg.append(
                wx.StaticText(self.panel,
                              -1,
                              label='',
                              pos=(600, 20 * (i - 43)),
                              name=''))

        for i in range(85, 129):
            setattr(
                self, "labelCtrlHreg%s" % (i),
                wx.StaticText(self.panel,
                              -1,
                              label='hReg' + str(i),
                              pos=(700, 20 * (i - 86)),
                              name='lblHreg' + str(i)))
            self.ctrlsHreg.append(
                wx.StaticText(self.panel,
                              -1,
                              label='',
                              pos=(800, 20 * (i - 86)),
                              name=''))
        self.labelCtrlHreg1.SetLabel("Light sensor")
        self.labelCtrlHreg2.SetLabel("Temperature")
        self.labelCtrlHreg3.SetLabel("Humidity")
        self.labelCtrlHreg4.SetLabel("Heat pulse")
        self.labelCtrlHreg5.SetLabel("Cool pulse")
        self.labelCtrlHreg6.SetLabel("Fan pulse")
        self.labelCtrlHreg100.SetLabel("DHT TimeOut")
        self.labelCtrlHreg101.SetLabel("DHT Checksum")
        self.labelCtrlHreg102.SetLabel("DHT Status")
        self.labelCtrlHreg103.SetLabel("Error BLINK")
        self.labelCtrlHreg104.SetLabel("Wifi Status")
        self.labelCtrlHreg105.SetLabel("Therm Status")
        self.labelCtrlHreg106.SetLabel("Reset Rsn")
        self.labelCtrlHreg107.SetLabel("Chip ID")
        #self.labelCtrlHreg108.SetLabel("Chip ID low")

        self.ctrlsCoil = []
        for i in range(1, 33):
            setattr(self, "labelCtrlCoil%s" % i,
                    (wx.StaticText(self.panel,
                                   -1,
                                   label='Coil' + str(i),
                                   pos=(850, 20 * i),
                                   name='lblCoil' + str(i))))
            self.ctrlsCoil.append(
                wx.StaticText(self.panel,
                              -1,
                              label='',
                              pos=(950, 20 * i),
                              name=''))

        self.labelCtrlCoil1.SetLabel("Heat overrider")
        self.labelCtrlCoil2.SetLabel("Heat control")
        self.labelCtrlCoil3.SetLabel("Cool override")
        self.labelCtrlCoil4.SetLabel("Cool control")
        self.labelCtrlCoil5.SetLabel("Fan overrride")
        self.labelCtrlCoil6.SetLabel("Fan control")
        self.labelCtrlCoil7.SetLabel("Heat call")
        self.labelCtrlCoil8.SetLabel("Cool call")
        self.labelCtrlCoil9.SetLabel("Fan call")
        self.labelCtrlCoil10.SetLabel("Heat call")

        self.ctrlsBitmaps = []
        for i in range(1, 33):
            self.ctrlsBitmaps.append(
                wx.StaticBitmap(self.panel,
                                wx.ID_ANY,
                                wx.Bitmap(self.PilotLightRedOn),
                                pos=(265, i * 25),
                                size=(20, 20)))

        # buttons
        self.btn_heatoverrride = buttons.GenButton(self.panel,
                                                   name="Heat Override",
                                                   pos=(140, 25),
                                                   size=(120, 20))
        self.btn_heatcontrol = buttons.GenButton(self.panel,
                                                 name='Heat Control',
                                                 pos=(140, 50),
                                                 size=(120, 20))
        self.btn_cooloverrride = buttons.GenButton(self.panel,
                                                   name="Cool Override",
                                                   pos=(140, 75),
                                                   size=(120, 20))
        self.btn_coolcontrol = buttons.GenButton(self.panel,
                                                 name='Cool Control',
                                                 pos=(140, 100),
                                                 size=(120, 20))
        self.btn_fanoverrride = buttons.GenButton(self.panel,
                                                  name="Fan Override",
                                                  pos=(140, 125),
                                                  size=(120, 20))
        self.btn_fancontrol = buttons.GenButton(self.panel,
                                                name='Fan Control',
                                                pos=(140, 150),
                                                size=(120, 20))

        #self.btn_restartESP = buttons.GenButton(self.panel, name='Restart ESP', pos=(500, 30), size=(120, 20))
        #self.btn_restartESP.SetLabel("Restart ESP")

        self.btn_heatoverrride.SetLabel("Heat Override")
        self.btn_heatcontrol.SetLabel("Heat Control")
        self.btn_cooloverrride.SetLabel("Cool Override")
        self.btn_coolcontrol.SetLabel("Cool Control")
        self.btn_fanoverrride.SetLabel("Fan Override")
        self.btn_fancontrol.SetLabel("Fan Control")
        #self.btn_restartESP.SetLabel("Restart ESP")

        self.lightGauge = wx.Gauge(self.panel,
                                   range=1024,
                                   pos=(10, 115),
                                   size=(100, 25),
                                   style=wx.GA_HORIZONTAL)

        # events
        self.btn_heatoverrride.Bind(wx.EVT_BUTTON, self.OnClicked)
        self.btn_heatcontrol.Bind(wx.EVT_BUTTON, self.OnClicked)
        self.btn_cooloverrride.Bind(wx.EVT_BUTTON, self.OnClicked)
        self.btn_coolcontrol.Bind(wx.EVT_BUTTON, self.OnClicked)
        self.btn_fanoverrride.Bind(wx.EVT_BUTTON, self.OnClicked)
        self.btn_fancontrol.Bind(wx.EVT_BUTTON, self.OnClicked)
        #self.btn_restartESP.Bind(wx.EVT_BUTTON, self.OnPress)

        # start thread
        startWorker(self.modbusAutoPollingOver, self.modbusAutoPolling)
예제 #49
0
    def OnClose(self):
        self.Destroy()
        self.Close(True)


if __name__ == "__main__":
    _opts, _args = helpers.parse_args()
    app = MainWindow(redirect=True, filename=os.devnull)

    # update status bar
    tw = app.GetTopWindow()
    tw.PushStatusText('Starting...')

    # start the threads
    startWorker(app._ResultNotifier, app.updateLogWindow)
    startWorker(app._ResultNotifier, app.updateControllersStatus)
    startWorker(app._ResultNotifier, app.mainThread)
    startWorker(app._ResultNotifier, app.updateOperatorWindow)

    # start main loop
    app.MainLoop()

    # kill all remaining threads
    import threading

    for thread in threading.enumerate():
        if thread.isAlive():
            try:
                thread._Thread__stop()
                if thread.getName() != 'MainThread':
예제 #50
0
 def onOk(self, e):
     if self.panel.Validate():
         self.startSession()
         delayedresult.startWorker(consumer=self._consumer,
                                   workerFn=self._worker)
    def CheckForUpdate(self,
                       silentUnlessUpdate=False,
                       parentWindow=None,
                       cfg=None):
        """
        This method will check for the availability of a new update, and will
        prompt the user with details if there is one there. By default it will
        also tell the user if there is not a new update, but you can pass
        silentUnlessUpdate=True to not bother the user if there isn't a new
        update available.

        This method should be called from an event handler for a "Check for
        updates" menu item, or something similar. The actual update check
        will be run in a background thread and this function will return
        immediately after starting the thread so the application is not
        blocked if there is network communication problems. A callback to the
        GUI thread will be made to do the update or report problems as
        needed.
        """
        if not isFrozenApp or self._checkInProgress:
            return
        self._checkInProgress = True

        def doFindUpdate():
            try:
                newest = self._esky.find_update()
                chLogTxt = ''
                if newest is not None and self._changelogURL:
                    req = urlopen(self._changelogURL, timeout=4)
                    chLogTxt = req.read()
                    req.close()
                return (newest, chLogTxt)

            except URLError:
                return 'URLError'

        def processResults(result):
            result = result.get()
            self._checkInProgress = False
            if result == 'URLError':
                if not silentUnlessUpdate:
                    MultiMessageBox(self._networkFailureMsg % self._updatesURL,
                                    self._caption,
                                    parent=parentWindow,
                                    icon=self._icon,
                                    style=wx.OK | SOT)
                return

            active = self._esky.active_version
            if cfg:
                oldPath = cfg.GetPath()
                cfg.SetPath('/autoUpdate')
                today = int(wx.DateTime.Today().GetJulianDayNumber())
                cfg.WriteInt('lastCheck', today)
                cfg.Write('lastCheckVersion', active)
                cfg.Flush()
                cfg.SetPath(oldPath)

            newest, chLogTxt = result
            if newest is None:
                if not silentUnlessUpdate:
                    MultiMessageBox(
                        "You are already running the newest verison of %s." %
                        self.GetAppDisplayName(),
                        self._caption,
                        parent=parentWindow,
                        icon=self._icon,
                        style=wx.OK | SOT)
                return
            self._parentWindow = parentWindow

            resp = MultiMessageBox(
                "A new version of %s is available.\n\n"
                "You are currently running verison %s; version %s is now "
                "available for download.  Do you wish to install it now?" %
                (self.GetAppDisplayName(), active, newest),
                self._caption,
                msg2=chLogTxt,
                style=wx.YES_NO | SOT,
                parent=parentWindow,
                icon=self._icon,
                btnLabels={
                    wx.ID_YES: "Yes, install now",
                    wx.ID_NO: "No, maybe later"
                })
            if resp != wx.YES:
                return

            # Ok, there is a little trickery going on here. We don't know yet if
            # the user wants to restart the application after the update is
            # complete, but since atexit functions are executed in a LIFO order we
            # need to registar our function before we call auto_update and Esky
            # possibly registers its own atexit function, because we want ours to
            # be run *after* theirs. So we'll create an instance of an info object
            # and register its method now, and then fill in the details below
            # once we decide what we want to do.
            class RestartInfo(object):
                def __init__(self):
                    self.exe = None

                def restart(self):
                    if self.exe is not None:
                        # Execute the program, replacing this process
                        os.execv(self.exe, [self.exe] + sys.argv[1:])

            info = RestartInfo()
            atexit.register(info.restart)

            try:
                # Let Esky handle all the rest of the update process so we can
                # take advantage of the error checking and priviledge elevation
                # (if neccessary) that they have done so we don't have to worry
                # about that ourselves like we would if we broke down the proccess
                # into component steps.
                self._esky.auto_update(self._updateProgress)

            except UpdateAbortedError:
                MultiMessageBox("Update canceled.",
                                self._caption,
                                parent=parentWindow,
                                icon=self._icon,
                                style=wx.OK | SOT)
                if self._pd:
                    self._pd.Destroy()

                self.InitUpdates(self._updatesURL, self._changelogURL,
                                 self._icon)
                return

            # Ask the user if they want the application to be restarted.
            resp = MultiMessageBox(
                "The upgrade to %s %s is ready to use; the application will "
                "need to be restarted to begin using the new release.\n\n"
                "Restart %s now?" %
                (self.GetAppDisplayName(), newest, self.GetAppDisplayName()),
                self._caption,
                style=wx.YES_NO | SOT,
                parent=parentWindow,
                icon=self._icon,
                btnLabels={
                    wx.ID_YES: "Yes, restart now",
                    wx.ID_NO: "No, I'll restart later"
                })

            if resp == wx.YES:
                # Close all windows in this application...
                for w in wx.GetTopLevelWindows():
                    if isinstance(w, wx.Dialog):
                        w.Destroy()
                    elif isinstance(w, wx.Frame):
                        w.Close(True)  # force close (can't be cancelled)
                wx.Yield()

                # ...find the path of the esky bootstrap/wrapper program...
                exe = esky.util.appexe_from_executable(sys.executable)

                # ...and tell our RestartInfo object about it.
                info.exe = exe

                # Make sure the CWD not in the current version's appdir, so it can
                # hopefully be cleaned up either as we exit or as the next verison
                # is starting.
                os.chdir(os.path.dirname(exe))

                # With all the top level windows closed the MainLoop should exit
                # automatically, but just in case tell it to exit so we can have a
                # normal-as-possible shutdown of this process. Hopefully there
                # isn't anything happening after we return from this function that
                # matters.
                self.ExitMainLoop()

            return

        # Start the worker thread that will check for an update, it will call
        # processResults when it is finished.
        import wx.lib.delayedresult as dr
        dr.startWorker(processResults, doFindUpdate)
예제 #52
0
 def OnTimer(self, event):
     # Start another thread which will update the bitmap
     # But only if another is not still running!
     if self.t is None:
         self.timer.Stop()
         self.t = startWorker(self.ComputationDone, self.Compute)
예제 #53
0
 def start_delay_work(self, c_func, w_func, **kwargs):
     delayedresult.startWorker(c_func, w_func, **kwargs)
예제 #54
0
 def do(self, action):
     startWorker(self.OnFinish, self.onDo, wargs=[action])
예제 #55
0
def check_and_update(parent, preferences, force=False):
    """
	Check for updates, and interact with user.
	
	Update mode is automatic if force=False, else manual.
	
	parent: parent window of any created modal dialogs
	"""
    def check_for_updates():
        """
		Check and return available updates.
		
		Honour the frequency of update checking unless force is True.
		
		Return list of pair (version, description),
		where description is an html-formatted text.
		Raise an exception if anything goes wrong.
		"""
        if (force or preferences.updateLastCheck is None
                or datetime.datetime.now() > preferences.updateLastCheck +
                datetime.timedelta(days=preferences.updateFrequency)):
            tr = RequestsTransport()
            s = Server(preferences.updateUrl, transport=tr)
            # method returns a dictionary with those keys:
            # 'new_url': if defined, new url of the webservice
            # 'updates': list of 3-tuples (version, description, downloadUrl)
            u = s.checkForUpdates(
                glb.VERSION,
                preferences.updateFrequency,
                platform.system(),
                platform.architecture(),
                platform.platform(),
                platform.python_version(),
                wx.version(),
                i18n.getLang(),
            )
            u2 = [
                x for x in u['updates']
                if x[0] not in preferences.ignoredUpdates
            ]
            preferences.updateLastCheck = datetime.datetime.now()
            if 'new_url' in u:
                preferences.updateUrl = u['new_url']
            return u2
        return []

    def consume_updates(dr):
        try:
            u = dr.get()
            if len(u) > 0:
                d = MyUpdateDialog(parent, preferences, u)
                d.ShowModal()
            elif force:
                d = wx.MessageDialog(
                    parent, _("Your version of Songpress is up to date."),
                    _("Songpress"), wx.OK | wx.ICON_INFORMATION)
                d.ShowModal()
        except Exception as e:
            logging.error(traceback.format_exc())
            if force:
                d = wx.MessageDialog(
                    parent,
                    _("There was an error while checking for updates.\nPlease try again later."
                      ), _("Update error"), wx.OK | wx.ICON_ERROR)
                d.ShowModal()

    delayedresult.startWorker(consume_updates, check_for_updates)
예제 #56
0
 def runFineAlign(self, fineAlign):
     self.fineAlign = fineAlign
     self.exception = None
     startWorker(self.fineAlignDoneCb, self.doFineAlign, wargs=[fineAlign])
     self.ShowModal()
예제 #57
0
 def on_clicked(self, event):
     if self.msg != '':
         self.btn1.Enable(False)
         self.tc2.SetValue('查询中请稍后。。。。。。_(:з」∠)_')
         startWorker(self._resultConsumer, self._resultProducer, jobID=self.job_id)
예제 #58
0
 def on_timer(self, evt):
     if update_method == 'wpkg-gp':
         if wpkg_running():
             return
     startWorker(self.update_check_done, self.update_check)
예제 #59
0
 def onIdle(self, event):
     # TODO: Use plain threading like other parts of LTLMoP?
     if not self.waitingForInput:
         delayedresult.startWorker(self.updateFromInput, self.checkForInput)
         self.waitingForInput = True
     event.Skip()
예제 #60
0
 def start(self):
     """
     Compute result in separate thread, doesn't affect GUI response.
     """
     self.abortEvent.clear()
     delayedresult.startWorker(self.result, self.process)