Пример #1
0
 def show_table(self, tab, title=None):
     wx.CallAfter(self._show_table, tab, title)
    def self_calbrate(self):
        self.port.apply_settings(calibrate=True)

        sleep(self.port.calibration_delay)
        wx.CallAfter(self.calibrate_button.Enable)
 def OnFilesLeftDown(self, event):
     event.Skip()
     wx.CallAfter(self.doStartDrag)
Пример #4
0
    def __init__(self,
                 parent,
                 id=-1,
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.SP_3D | wx.SP_LIVE_UPDATE,
                 name='Crust Window',
                 rootObject=None,
                 rootLabel=None,
                 rootIsNamespace=True,
                 intro='',
                 locals=None,
                 InterpClass=None,
                 startupScript=None,
                 execStartupScript=True,
                 *args,
                 **kwds):
        """Create Crust instance."""
        wx.SplitterWindow.__init__(self, parent, id, pos, size, style, name)

        # Turn off the tab-traversal style that is automatically
        # turned on by wx.SplitterWindow.  We do this because on
        # Windows the event for Ctrl-Enter is stolen and used as a
        # navigation key, but the Shell window uses it to insert lines.
        style = self.GetWindowStyle()
        self.SetWindowStyle(style & ~wx.TAB_TRAVERSAL)

        self.shell = Shell(parent=self,
                           introText=intro,
                           locals=locals,
                           InterpClass=InterpClass,
                           startupScript=startupScript,
                           execStartupScript=execStartupScript,
                           *args,
                           **kwds)

        self.editor = self.shell
        if rootObject is None:
            rootObject = self.shell.interp.locals
        self.notebook = wx.Notebook(parent=self, id=-1)
        self.shell.interp.locals['notebook'] = self.notebook
        self.filling = Filling(parent=self.notebook,
                               rootObject=rootObject,
                               rootLabel=rootLabel,
                               rootIsNamespace=rootIsNamespace)
        # Add 'filling' to the interpreter's locals.
        self.shell.interp.locals['filling'] = self.filling
        self.notebook.AddPage(page=self.filling, text='Namespace', select=True)

        self.display = Display(parent=self.notebook)
        self.notebook.AddPage(page=self.display, text='Display')
        # Add 'pp' (pretty print) to the interpreter's locals.
        self.shell.interp.locals['pp'] = self.display.setItem
        self.display.nbTab = self.notebook.GetPageCount() - 1

        self.calltip = Calltip(parent=self.notebook)
        self.notebook.AddPage(page=self.calltip, text='Calltip')

        self.sessionlisting = SessionListing(parent=self.notebook)
        self.notebook.AddPage(page=self.sessionlisting, text='History')

        self.dispatcherlisting = DispatcherListing(parent=self.notebook)
        self.notebook.AddPage(page=self.dispatcherlisting, text='Dispatcher')

        # Initialize in an unsplit mode, and check later after loading
        # settings if we should split or not.
        self.shell.Hide()
        self.notebook.Hide()
        self.Initialize(self.shell)
        self._shouldsplit = True
        wx.CallAfter(self._CheckShouldSplit)
        self.SetMinimumPaneSize(100)

        self.Bind(wx.EVT_SIZE, self.SplitterOnSize)
        self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.OnChanged)
        self.Bind(wx.EVT_SPLITTER_DCLICK, self.OnSashDClick)
Пример #5
0
 def run(self):
     #线程执行的代码
     for i in range(10):
         time.sleep(0.03)
         wx.CallAfter(pub.sendMessage, "update")
         time.sleep(0.5)
Пример #6
0
 def SetBitmapResource(self, control, rel):
     try:
         img = Image.open(pkg_resources.resource_stream('makechr', rel))
         wx.CallAfter(control.SetBitmap, self.PilImgToBitmap(img))
     except IOError:
         pass
Пример #7
0
 def OnModify(self, e):
     wx.CallAfter(self.reloadTimer.Start, 1000)
Пример #8
0
 def alert(self, info, title='ImagePy'):
     wx.CallAfter(self._alert, info, title)
Пример #9
0
 def onMbType(event):
     wx.CallAfter(fillOptSizer, bool(event.GetSelection()))
     event.Skip()
Пример #10
0
 def show_mesh(self, mesh=None, title=None):
     wx.CallAfter(self._show_mesh, mesh, title)
Пример #11
0
 def info(self, cont):
     wx.CallAfter(self.txt_info.SetLabel, cont)
Пример #12
0
 def show_txt(self, cont, title='ImagePy'):
     wx.CallAfter(self._show_txt, cont, title)
Пример #13
0
 def show_workflow(self, cont, title='ImagePy'):
     wx.CallAfter(self._show_workflow, cont, title)
Пример #14
0
 def show_md(self, cont, title='ImagePy'):
     wx.CallAfter(self._show_md, cont, title)
Пример #15
0
 def onRun(self, event):
     print("Clicky!")
     wx.CallAfter(self.AfterRun, "I don't appear until after OnRun exits")
     s = input("Enter something:")
     print(s)
Пример #16
0
 def on_future_completed(self, completed_future):
     self.Dismiss()
     wx.CallAfter(self.done_callback, completed_future)
Пример #17
0
 def __run(self):
     wx.CallAfter(self.AfterRun, "I appear immediately (event handler\n"+ \
                     "exited when OnRun2 finished)")
     s = input("Enter something in this thread:")
     print(s)
Пример #18
0
 def Dismiss(self):
     if self.snak_dg:
         wx.CallAfter(self.snak_dg.Hide)
         wx.CallAfter(self.snak_dg.Destroy)
         wx.CallAfter(self.snak_dg.Parent.Enable)
Пример #19
0
 def load(self, bitmap):
     self.bitmap = bitmap
     wx.CallAfter(self.ctrl.SetBitmap, self.bitmap)
Пример #20
0
 def onHide(self, event):
     wx.CallAfter(self.progress_dlg.Hide)
     self.is_hidden = True
    def _applyEulerianVideoMagnification(self):

        timestamp = timeit.default_timer()

        if self._useGrayOverlay and \
               not self._isCaptureMonochrome:
            smallImage = cv2.cvtColor(self._image,
                                      cv2.COLOR_BGR2GRAY).astype(numpy.float32)
        else:
            smallImage = self._image.astype(numpy.float32)

        # Downsample the image using a pyramid technique.
        i = 0
        while i < self._numPyramidLevels:
            smallImage = cv2.pyrDown(smallImage)
            i += 1
        if self._useLaplacianPyramid:
            smallImage[:] -= \
                cv2.pyrUp(cv2.pyrDown(smallImage))

        historyLength = len(self._historyTimestamps)

        if historyLength < self._maxHistoryLength - 1:

            # Append the new image and timestamp to the
            # history.
            self._history[historyLength] = smallImage
            self._historyTimestamps.append(timestamp)

            # The history is still not full, so wait.
            return

        if historyLength == self._maxHistoryLength - 1:
            # Append the new image and timestamp to the
            # history.
            self._history[historyLength] = smallImage
            self._historyTimestamps.append(timestamp)
        else:
            # Drop the oldest image and timestamp from the
            # history and append the new ones.
            self._history[:-1] = self._history[1:]
            self._historyTimestamps.popleft()
            self._history[-1] = smallImage
            self._historyTimestamps.append(timestamp)

        # The history is full, so process it.

        # Find the average length of time per frame.
        startTime = self._historyTimestamps[0]
        endTime = self._historyTimestamps[-1]
        timeElapsed = endTime - startTime
        timePerFrame = \
                timeElapsed / self._maxHistoryLength
        fps = 1.0 / timePerFrame
        wx.CallAfter(self._fpsStaticText.SetLabel, 'FPS:  %.1f' % fps)

        # Apply the temporal bandpass filter.
        fftResult = fft(self._history, axis=0, threads=self._numFFTThreads)
        frequencies = fftfreq(self._maxHistoryLength, d=timePerFrame)
        lowBound = (numpy.abs(frequencies - self._minHz)).argmin()
        highBound = (numpy.abs(frequencies - self._maxHz)).argmin()
        fftResult[:lowBound] = 0j
        fftResult[highBound:-highBound] = 0j
        fftResult[-lowBound:] = 0j
        ifftResult = ifft(fftResult, axis=0, threads=self._numIFFTThreads)

        # Amplify the result and overlay it on the
        # original image.
        overlay = numpy.real(ifftResult[-1]) * \
                          self._amplification
        i = 0
        while i < self._numPyramidLevels:
            overlay = cv2.pyrUp(overlay)
            i += 1
        if self._useGrayOverlay and \
                not self._isCaptureMonochrome:
            overlay = cv2.cvtColor(overlay, cv2.COLOR_GRAY2BGR)
        cv2.add(self._image, overlay, self._image, dtype=cv2.CV_8U)
Пример #22
0
 def Pulse(self, message):
     if self.progress_dlg is not None:
         wx.CallAfter(self.progress_dlg.Pulse, message)
Пример #23
0
    def run(self):
        def TCAShut():
            ui.message(_('Apagando el Pc.'))
            winsound.PlaySound('C:\Windows\Media\Windows Shutdown.wav',
                               winsound.SND_FILENAME)
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            subprocess.run('shutdown.exe -s -t 3', shell=True, startupinfo=si)

        def TCAShutR():
            ui.message(_('Reiniciando el PC.'))
            winsound.PlaySound('C:\Windows\Media\Windows Shutdown.wav',
                               winsound.SND_FILENAME)
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            subprocess.run('shutdown.exe -r -t 3', shell=True)

        def TCAShutA():
            ui.message(_('anulando el apagado o reinicio del pc.'))
            subprocess.run('shutdown.exe -a', shell=True)

        def TCAcopy_sys():
            subprocess.Popen('Systeminfo | clip', shell=True)

        def TCAList():
            t_obj(self)
            if self.v_obj is not False:
                os.chdir(self.v_obj)
                subprocess.Popen('dir /b|clip', shell=True)
                os.chdir(a_path)
                ui.message(_('Copiada la lista al portapapeles'))
            else:
                ui.message(_('No se pudo copiar la lista al portapapeles'))

        @rdt
        def TCAsfc():
            shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                  '/c' + 'sfc' + '/scannow' + '&pause', None,
                                  10)

        def TCAcopitar():
            lt = ['powershell', 'Get-WmiObject Win32_SoundDevice |clip']
            subprocess.run(lt, shell=True)
            ui.message(_('Copiada la info del sonido al portapapeles'))

        @rdt
        def ocu():
            t_obj(self)
            if self.v_obj is not False:
                d = os.path.dirname(self.v_obj)
                b = os.path.basename(self.v_obj)
                os.chdir(d)
                shellapi.ShellExecute(None, None, 'cmd.exe',
                                      '/c' + r'attrib +s +h "{}"'.format(b),
                                      None, 0)
                sleep(0.5)
                keyboardHandler.KeyboardInputGesture.fromName("alt+f4").send()
                os.startfile(d)
                tones.beep(900, 50)
                os.chdir(a_path)
            else:
                ui.message(_('No fue posible ocultar los elementos'))

        @rdt
        def mos():
            t_obj(self)
            if self.v_obj is not False:
                os.chdir(self.v_obj)
                shellapi.ShellExecute(None, None, 'cmd.exe',
                                      '/c' + r'attrib /d -s -h', None, 0)
                sleep(0.5)
                os.chdir(a_path)
            else:
                ui.message(_('no se pudieron mostrar los archivos'))

        def clean():
            if os.path.isfile(
                    os.path.join(globalVars.appArgs.configPath, "tsu.ini")):
                pass
            else:
                dlg = wx.RichMessageDialog(
                    None,
                    _("Si es la primera vez que ejecuta ésta acción.\n es necesario crear un perfil de limpieza, solo debe hacerlo una vez.\n puede pulsar en Crear perfil también si desea modificar uno existente, o puede marcar  la casilla para no volver a mostrar éste mensaje."
                      ),
                    style=wx.CANCEL)
                dlg.SetOKLabel(_("Crear perfil"))
                dlg.ShowCheckBox(_("No volver  a mostrar este mensaje"))
                rp = dlg.ShowModal()
                if dlg.IsCheckBoxChecked():
                    with open(
                            os.path.join(globalVars.appArgs.configPath,
                                         "tsu.ini"), "w") as tsu_i:
                        tsu_i.write("sageset: True")
                else:
                    pass

                if rp == wx.ID_OK:
                    try:
                        os.environ['PROGRAMFILES(X86)']
                        with disable_file_system_redirection():
                            shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                                  '/c' + 'CLEANMGR /sageset:1',
                                                  None, 0)

                    except:
                        shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                              '/c' + 'CLEANMGR /sageset:1',
                                              None, 0)
                else:
                    dlg.Destroy()

            try:
                os.environ['PROGRAMFILES(X86)']
                with disable_file_system_redirection():
                    shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                          '/c' + 'CLEANMGR /sagerun:1', None,
                                          0)

            except:
                shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                      '/c' + 'CLEANMGR /sagerun:1', None, 0)

        @rdt
        def r_explo():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + 'taskkill /f /im explorer.exe' + '& start explorer',
                None, 10)

        @rdt
        def optim():
            subprocess.Popen('dfrgui')

        def iver():
            shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                  '/c' + 'shutdown /h', None, 10)

        @rdt
        def a_dism():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + 'DISM /online /cleanup-image /RestoreHealth' + '&pause',
                None, 10)

        @rdt
        def sh_b():
            dlg = wx.MessageDialog(
                None,
                _("Está a punto de reiniciar el sistema, y activar el modo Seguro con funciones de red.\n En éste modo los sistemas Windows anteriores al 10, puede que no tengan sonidos, por ende, el lector de pantalla no tendrá soporte de voz.\n Deberá deshabilitar este modo desde las configuraciones del sistema msconfig, o haciendo uso de TCA SystemUtilities en el apartado: apagado del sistema.\n ¿Está seguro que desea continuar?"
                  ), _("Atención activación del Modo seguro!"),
                wx.YES_NO | wx.ICON_QUESTION)
            rp = dlg.ShowModal()
            if rp == wx.ID_YES:
                shellapi.ShellExecute(
                    None, 'runas', 'cmd.exe',
                    '/c' + r'bcdedit /set {default} safeboot network', None,
                    10)
                shellapi.ShellExecute(
                    None, 'runas', 'cmd.exe', '/c' +
                    r'bcdedit /set {default} safebootalternateshell yes', None,
                    10)

                ui.message(_("Modo seguro activado, se va a reiniciar el Pc"))
                winsound.PlaySound('C:\Windows\Media\Windows Shutdown.wav',
                                   winsound.SND_FILENAME)
                subprocess.run('shutdown.exe -r -t 3', shell=True)
            else:
                dlg.Destroy()

        @rdt
        def sh_nor():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + r'bcdedit /deletevalue {default} safeboot', None, 10)
            ui.message(_("Modo normal, reiniciando el Pc"))
            winsound.PlaySound('C:\Windows\Media\Windows Shutdown.wav',
                               winsound.SND_FILENAME)
            subprocess.run('shutdown.exe -r -t 3', shell=True)

        def susp():
            ui.message(_("Suspendiendo el sistema"))
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + 'Rundll32.exe powrprof.dll, SetSuspendState', None, 10)

        @rdt
        def resPC():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + 'powershell start ms-settings:recovery', None, 10)

        @rdt
        def qclip():

            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                r'"{}\MpCmdRun.exe" -Restore -ListAll'.format(w_pt) + '|clip',
                None, 10)

        @rdt
        def scan_r():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + r'"{}\MpCmdRun.exe" -scan -scantype 1'.format(w_pt),
                None, 10)

        @rdt
        def scan_f():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + r'"{}\MpCmdRun.exe" -scan -scantype 2'.format(w_pt),
                None, 10)

        @rdt
        def sc_boot():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe',
                '/c' + r'"{}\MpCmdRun.exe" -scan -bootsectorscan'.format(w_pt),
                None, 10)

        @rdt
        def sc_f():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                r'powershell Set-MpPreference -DisableArchiveScanning 0', None,
                10)
            sleep(1)
            ui.message(_('Se activó el escanéo de archivos comprimidos'))

        @rdt
        def sc_nf():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                r'powershell Set-MpPreference -DisableArchiveScanning 1', None,
                10)
            sleep(1)
            ui.message(_('Se desactivó el escanéo de archivos comprimidos'))

        def webcam_d():

            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                r'powershell Disable-PnpDevice -InstanceId (Get-PnpDevice -FriendlyName *webcam*  -Status OK).InstanceId',
                None, 10)
            sleep(0.1)
            keyboardHandler.KeyboardInputGesture.fromName("enter").send()
            sleep(2)
            ui.message(_('Se desactivó la Webcam'))

        def webcam_ac():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                r'powershell Enable-PnpDevice -InstanceId (Get-PnpDevice -FriendlyName *webcam* -Status Error).InstanceId',
                None, 10)
            sleep(0.1)
            keyboardHandler.KeyboardInputGesture.fromName("enter").send()
            sleep(2)
            ui.message(_('Se activó la Webcam'))

        def bios():
            dlg = wx.MessageDialog(
                None,
                _("Está a punto de activar entrar a la BIOS-UEFI\n El PC se va a reiniciar en unos segundos. \n Recuerda que en la BIOS-UEFI no podrás utilizar un lector de pantalla, tendrás que pedir ayuda visual.\n ¿está seguro que desea continuar?"
                  ),
                _("¿Atención Se intentará activar la entrada a la BIOS-UEFI!"),
                wx.YES_NO | wx.ICON_QUESTION)
            rp = dlg.ShowModal()
            if rp == wx.ID_YES:
                shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                      '/c' + 'shutdown /r /fw', None, 10)
            else:
                dlg.Destroy()

        def cache():
            shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                  '/c' + 'ipconfig / flushDNS', None, 10)
            sleep(0.5)
            ui.message(_("Se limpió la Caché DNS "))

        @rdt
        def des_space():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                'DISM.exe /Online /Set-ReservedStorageState /State:Disabled',
                None, 10)
            sleep(0.5)
            ui.message(_("Se desactivó el espacio reservado"))

        @rdt
        def ac_space():
            shellapi.ShellExecute(
                None, 'runas', 'cmd.exe', '/c' +
                'DISM.exe /Online /Set-ReservedStorageState /State:Enabled',
                None, 10)
            sleep(0.5)
            ui.message(_("Se activó el espacio reservado"))

        @rdt
        def cmd():
            t_obj(self)
            if self.v_obj is not False:
                try:
                    os.chdir(self.v_obj)
                except:
                    ui.message(_('No se pudo obtener la ruta para el CMD'))
                    return
                shellapi.ShellExecute(
                    None, None, 'cmd.exe',
                    '{}:'.format(os.path.abspath(self.v_obj)), None, 10)
            else:
                ui.message("no se pudo ejecutar el cmd")

        @rdt
        def cmd_ad():
            t_obj(self)
            if self.v_obj is not False:
                try:
                    os.chdir(self.v_obj)
                except:
                    ui.message(_('No se pudo obtener la ruta para el CMD'))
                    return
                shellapi.ShellExecute(
                    None, 'runas', 'cmd.exe',
                    '{}:'.format(os.path.abspath(self.v_obj)), self.v_obj, 10)
            else:
                ui.message("no se pudo ejecutar el cmd")

        def delete_config():
            os.chdir("C:/Program Files (x86)/NVDA/systemConfig")
            pt_ac = os.getcwd()
            paths_sc = (pt_ac, os.path.join(pt_ac, 'addons'),
                        os.path.join(pt_ac, 'profiles'))
            if len(os.listdir('addons')) > 0:
                dlg = wx.MessageDialog(
                    None,
                    _('Este proceso eliminará todos los complementos y configuraciones que están en pantallas seguras.\n Es necesario que se reinicie el explorador de Windows, se deben cerrar todas las ventanas del explorador.\n Si tiene activado el uac (Control de cuentas de usuario), es probable que deba darle varias veces permisos para continuar.\n ¿Está seguro que desea continuar?'
                      ),
                    _('Atención borrando addons y configuraciones de pantallas seguras'
                      ), wx.YES_NO | wx.ICON_QUESTION)
                rp = dlg.ShowModal()
                if rp == wx.ID_YES:
                    for path in paths_sc:
                        os.chdir(path)

                        for folder in os.listdir():
                            if os.path.isdir(folder):
                                if folder == 'addons':
                                    continue
                                elif folder == 'profiles':
                                    continue
                                elif folder == 'speechDicts':
                                    continue

                                shellapi.ShellExecute(
                                    None, 'runas', 'cmd.exe', '/c' +
                                    r'rd /s /q "{}\{}"'.format(path, folder),
                                    None, 0)

                            elif os.path.isfile(folder):
                                shellapi.ShellExecute(
                                    None, 'runas', 'cmd.exe',
                                    '/c' + r'del /f /a /q "{}\{}"'.format(
                                        path, folder), None, 0)

                    os.chdir(a_path)
                    tones.beep(950, 50)
                    sleep(1)
                    ui.message(
                        _("Se limpió la configuración en pantallas seguras  "))
                    r_explo()

                else:
                    dlg.Destroy()
            else:
                ui.message(
                    _("No existen configuraciones guardadas en pantallas seguras"
                      ))

        @rdt
        def clean_clip():
            try:
                shellapi.ShellExecute(
                    None, 'runas', 'cmd.exe', '/c' +
                    r'powershell Restart-Service -Name "cbdhsvc*" -force',
                    None, 0)
            except:
                ui.message(_('no hay nada en el historial del portapapeles'))
            try:
                shellapi.ShellExecute(None, 'runas', 'cmd.exe',
                                      '/c' + 'echo off | clip', None, 0)
            except:
                ui.message(_('No fue posible eliminar el portapapeles'))

            ui.message(_('Se limpió correctamente el portapapeles'))

        if self.op == 4:
            wx.CallAfter(TCAcopy_sys)
        elif self.op == 1:
            wx.CallAfter(TCAShut)
        elif self.op == 2:
            wx.CallAfter(TCAShutR)
        elif self.op == 3:
            wx.CallAfter(TCAShutA)
        elif self.op == 5:
            wx.CallAfter(TCAList)
        elif self.op == 6:
            wx.CallAfter(TCAsfc)
        elif self.op == 7:
            wx.CallAfter(TCAcopitar)
        elif self.op == 8:
            wx.CallAfter(ocu)
        elif self.op == 9:
            wx.CallAfter(mos)
        elif self.op == 10:
            wx.CallAfter(clean)
        elif self.op == 11:
            wx.CallAfter(r_explo)
        elif self.op == 12:
            wx.CallAfter(optim)
        elif self.op == 13:
            wx.CallAfter(iver)
        elif self.op == 14:
            wx.CallAfter(a_dism)
        elif self.op == 15:
            wx.CallAfter(sh_b)
        elif self.op == 16:
            wx.CallAfter(sh_nor)
        elif self.op == 17:
            wx.CallAfter(susp)
        elif self.op == 18:
            wx.CallAfter(resPC)
        elif self.op == 19:
            wx.CallAfter(qclip)
        elif self.op == 20:
            wx.CallAfter(scan_r)
        elif self.op == 21:
            wx.CallAfter(scan_f)
        elif self.op == 22:
            wx.CallAfter(sc_boot)
        elif self.op == 23:
            wx.CallAfter(sc_f)
        elif self.op == 24:
            wx.CallAfter(sc_nf)
        elif self.op == 25:
            wx.CallAfter(webcam_d)
        elif self.op == 26:
            wx.CallAfter(webcam_ac)
        elif self.op == 27:
            wx.CallAfter(bios)
        elif self.op == 28:
            wx.CallAfter(cache)
        elif self.op == 29:
            wx.CallAfter(des_space)
        elif self.op == 30:
            wx.CallAfter(ac_space)
        elif self.op == 31:
            wx.CallAfter(cmd)
        elif self.op == 32:
            wx.CallAfter(cmd_ad)
        elif self.op == 33:
            wx.CallAfter(delete_config)
        elif self.op == 34:
            wx.CallAfter(clean_clip)
Пример #24
0
 def Update(self, value, message):
     if self.should_update():
         self._last_update = time.perf_counter()
         wx.CallAfter(self.progress_dlg.Update, value, message)
Пример #25
0
    def __init__(self):
        cfg = wx.GetApp().get_config("PSP")

        # shelves (persistent dictionaries)
        psp_defects = cfg.get("psp_defects", "psp_defects.dat")
        psp_times = cfg.get("psp_times", "psp_times.dat")
        psp_summary = cfg.get("psp_summary", "psp_summary.dat")

        # metadata directory (convert to full path)
        self.psp_metadata_dir = cfg.get("metadata", "medatada")
        self.psp_metadata_dir = os.path.abspath(self.psp_metadata_dir)
        self.psp_metadata_cache = {}  # filename: (filestamp, metadata)
        if not os.path.exists(self.psp_metadata_dir):
            os.makedirs(self.psp_metadata_dir)

        # text recording logs
        psp_event_log_filename = cfg.get("psp_event_log", "psp_event_log.txt")
        self.psp_event_log_file = open(psp_event_log_filename, "a")

        self._current_psp_phase = None

        tb4 = self.CreatePSPToolbar()
        self._mgr.AddPane(
            tb4,
            aui.AuiPaneInfo().Name("psp_toolbar").Caption("PSP Toolbar").
            ToolbarPane().Top().Position(3).CloseButton(True))

        grid = self.CreatePSPPlanSummaryGrid(filename=psp_times)
        self._mgr.AddPane(
            grid,
            aui.AuiPaneInfo().Caption("PSP Plan Summary Times").Name(
                "psp_plan").Bottom().Position(1).Row(2).FloatingSize(
                    wx.Size(200, 200)).CloseButton(True).MaximizeButton(True))
        self.psp_defect_list = self.CreatePSPDefectRecordingLog(
            filename=psp_defects)
        self._mgr.AddPane(
            self.psp_defect_list,
            aui.AuiPaneInfo().Caption("PSP Defect Recording Log").Name(
                "psp_defects").Bottom().Row(2).FloatingSize(wx.Size(
                    300, 200)).CloseButton(True).MaximizeButton(True))
        self._mgr.Update()
        # flag for time not spent on psp task
        self.psp_interruption = None

        self.AppendWindowMenuItem('PSP', (
            'psp_plan',
            'psp_defects',
            'psp_toolbar',
        ), self.OnWindowMenu)

        # web2py json rpc client
        self.psp_rpc_client = simplejsonrpc.ServiceProxy(cfg.get("server_url"))
        self.psp_wiki_url = cfg.get("wiki_url")
        self.psp_project_name = cfg.get("project_name")
        if self.psp_project_name:
            self.psp_set_project(self.psp_project_name)

        self.Bind(wx.EVT_CHOICE, self.OnPSPPhaseChoice, self.psp_phase_choice)
        self.SetPSPPhase(cfg.get("current_phase"))

        self.CreatePSPMenu()

        # start up a browser on psp2py app
        url = cfg.get("psp2py_url")
        if False and url:
            import webbrowser
            wx.CallAfter(webbrowser.open, url)
Пример #26
0
    def run(self):
        import pdb
        #pdb.set_trace()
        try:
            count = 0
            win = self.window

            wx.CallAfter(win.Update, 1, u'更新桌面云状态...')
            if self.cancel:
                return

            if self.Type == 'JSP' or self.Type == 'UNKNOWN':
                #import pdb
                #pdb.set_trace()
                vminfo = havclient.server_port(AdminShadow['admins'],
                                               self.p_id,
                                               self.vm,
                                               search_opts=None,
                                               all_tenants=None)
                passwd = havclient.get_cipher(FirstUser['firstuser'],
                                              self.p_id, self.vm)
                #vmcipher = havclient.get_cipher(FirstUser['firstuser'], self.p_id, self.vm)
                #passwd = vmcipher.cipher
                vmconsole = consoleInfo.ConsoleInfo(vminfo['console'])
                host = vmconsole.host
                port = vmconsole.port
                dsport = vmconsole.tlsport

                public_ip = Setting.getPublic().lower()
                Logger.info("The public_ip status is %s", public_ip)
                dport = port
                if public_ip == "false":
                    dhost = Wfile.Parsing_hosts(host)
                    try:
                        os.environ["SPICE_PROXY"] = ""
                    except:
                        Logger.error(
                            "Configure the environment variables failed!")
                        pass
                elif public_ip == "true":
                    dhost = host
                    proxy_status, proxy_port = SpicePorxyRequests()
                    if proxy_status:
                        try:
                            os.environ["SPICE_PROXY"] = "http://%s:%s" % (
                                Setting.getServer(), proxy_port)
                        except:
                            Logger.error(
                                "Configure the environment variables failed!")
                    else:
                        Util.MessageBox(self, '连接失败!\n\n系统管理员未设置公网代理!', u'错误',
                                        wx.OK | wx.ICON_ERROR)
                        return

                wx.CallAfter(win.WorkFinished, u'获取桌面云信息... 成功')

                wx.CallAfter(win.Update, 1, u'打开桌面云...')

                argument = self.get_argument()
                #cmdline = 'scdaemon spice://%s/?port=%s\&tls-port=%s\&password=%s --hotkeys=exit-app=shift+f12,release-cursor=shift+f11 -f --title="%s"' % (dhost,dport,dsport,passwd,self.vm.name) + argument
                cmdline = 'scdaemon spice://%s/?port=%s\&password=%s --hotkeys=exit-app=shift+f12,release-cursor=shift+f11 -f --title="%s"' % (
                    dhost, dport, passwd, self.vm.name) + argument
                Logger.info("Spice Cmd:%s", cmdline)
            elif self.Type == 'RDP':
                user = Setting.getUser()
                Logger.info("The user of VM is %s", user)
                password = Setting.getCipher()
                Logger.info("The password of user is %s", password)

                ip = havclient.get_vm_ip(self.vm)

                public_ip = Setting.getPublic().lower()
                Logger.info("The public_ip status is %s", public_ip)

                argu = self.get_rdpsetting()
                if public_ip == 'false':
                    ipaddress = ip
                    Logger.info("The ipaddress of user is %s", ipaddress)
                    cmdline = 'xfreerdp /u:%s /p:%s /v:%s /cert-ignore -sec-tls /bpp:32 /gdi:hw /multimedia:decoder:gstreamer +auto-reconnect /sound:sys:pulse /microphone:sys:pulse -f ' % (
                        user, password, ipaddress) + argu
                elif public_ip == 'true':
                    ip, port = Wfile.getmapping_prot(ip, '3389')
                    ipaddress = ip + ':' + port
                    Logger.info("The ipaddress of user is %s", ipaddress)
                    cmdline = 'xfreerdp /u:%s /p:%s /v:%s /cert-ignore -sec-tls /bpp:32 /gdi:hw /multimedia:decoder:gstreamer +auto-reconnect /sound:sys:pulse /microphone:sys:pulse -f ' % (
                        user, password, ipaddress) + argu

                Logger.info("Rdp Cmd:%s", cmdline)

            body = {}
            vmlogintime = Setting.getVMLoginTime()
            clientip = Setting.getClientIP()
            body['client_time'] = vmlogintime
            body['client_ip'] = clientip

            # try:
            #     havclient.connect_client_info(AdminShadow['admins'], self.p_id, self.vm.id, body)
            # except:
            #     Logger.error("Send vmlogininfo failed!")

            Logger.debug(cmdline)

            ret = Util.RunConnectGuestWithLog(cmdline)

            if self.cancel:
                return
            wx.CallAfter(win.WorkFinished, u'打开桌面云... 成功')
            wx.CallAfter(win.Finish)

            name = self.vm.name
            desktop = name.encode('utf-8')
            Setting.setDesktop(desktop)
            Setting.save()

            RestartDeviceRequests()

            SaveVmLoginInfo()

            self.stop()

            self.ret = ret
        except Exception, e:
            self.ret = 1
            self.msg = "%s : %s" % (SPICE_ERR_TABLE[1], e)
Пример #27
0
    def OnClose(self, event):

        wx.CallAfter(self.Destroy)
Пример #28
0
 def cr(self):
     time.sleep(0.01)
     wx.CallAfter(self.rotateafter)
     self.triggered = 0
Пример #29
0
    def display(self,
                img,
                title=None,
                colormap=None,
                style='image',
                subtitles=None,
                auto_contrast=False,
                contrast_level=None,
                **kws):
        """display image"""
        if title is not None:
            self.SetTitle(title)
        if subtitles is not None:
            self.subtitles = subtitles
        cmode = self.config_mode.lower()[:3]
        img = np.array(img)

        if len(img.shape) == 3:
            ishape = img.shape
            # make sure 3d image is shaped (NY, NX, 3)
            if ishape[2] != 3:
                if ishape[0] == 3:
                    img = img.swapaxes(0, 1).swapaxes(1, 2)
                elif ishape[1] == 3:
                    img = img.swapaxes(1, 2)

            if cmode != 'rgb':
                for comp in self.config_panel.Children:
                    comp.Destroy()
                self.config_mode = 'rgb'
                self.panel.conf.tricolor_mode = 'rgb'
                self.Build_ConfigPanel()
        else:
            if cmode != 'int':
                for comp in self.config_panel.Children:
                    comp.Destroy()
                self.config_mode = 'int'
                self.Build_ConfigPanel()

        if contrast_level is None:
            if auto_contrast:
                cl_str = '1.0'
            else:
                cl_str = self.contrast_panel.choice.GetStringSelection()
        else:
            cl_int = max(np.where(Contrast_NDArray <= contrast_level)[0])
            cl_str = Contrast_List[cl_int]

        if cl_str == 'None':
            contrast_level = 0
        else:
            contrast_level = float(cl_str)

        self.contrast_panel.choice.SetStringSelection(cl_str)
        self.panel.conf.contrast_level = contrast_level

        self.panel.display(img,
                           style=style,
                           contrast_level=contrast_level,
                           colormap=colormap,
                           **kws)

        self.set_contrast_levels(contrast_level=contrast_level)

        self.panel.conf.title = title
        if colormap is not None and self.config_mode == 'int':
            self.cmap_panels[0].cmap_choice.SetStringSelection(colormap)
            self.cmap_panels[0].set_colormap(name=colormap)

        if subtitles is not None:
            if isinstance(subtitles, dict):
                self.set_subtitles(**subtitles)
            elif self.config_mode == 'int':
                self.set_subtitles(red=subtitles)

        self.panel.conf.style = 'image'
        self.contrast_panel.Enable()

        if style == 'contour':
            self.panel.conf.style = 'contour'
            self.contrast_panel.Disable()
            # self.interp_panel.Disable()

        self.config_panel.Refresh()
        self.SendSizeEvent()
        wx.CallAfter(self.EnableMenus)
Пример #30
0
 def show_img(self, img, title=None):
     wx.CallAfter(self._show_img, img, title)