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" ))
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'))
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 restart(disableAddons=False, debugLogging=False): """Restarts NVDA by starting a new copy with -r.""" if globalVars.appArgs.launcher: import wx globalVars.exitCode=3 wx.GetApp().ExitMainLoop() return import subprocess import winUser import shellapi options=[] if "-r" not in sys.argv: options.append("-r") try: sys.argv.remove('--disable-addons') except ValueError: pass try: sys.argv.remove('--debug-logging') except ValueError: pass if disableAddons: options.append('--disable-addons') if debugLogging: options.append('--debug-logging') try: sys.argv.remove("--ease-of-access") except ValueError: pass shellapi.ShellExecute(None, None, sys.executable.decode("mbcs"), subprocess.list2cmdline(sys.argv + options).decode("mbcs"), None, # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL winUser.SW_SHOWNORMAL)
def doInstall(createDesktopShortcut,startOnLogon,copyPortableConfig,isUpdate,silent=False,startAfterInstall=True): progressDialog = gui.IndeterminateProgressDialog(gui.mainFrame, # Translators: The title of the dialog presented while NVDA is being updated. _("Updating NVDA") if isUpdate # Translators: The title of the dialog presented while NVDA is being installed. else _("Installing NVDA"), # Translators: The message displayed while NVDA is being updated. _("Please wait while your previous installation of NVDA is being updated.") if isUpdate # Translators: The message displayed while NVDA is being installed. else _("Please wait while NVDA is being installed")) try: res=config.execElevated(config.SLAVE_FILENAME,["install",str(int(createDesktopShortcut)),str(int(startOnLogon))],wait=True,handleAlreadyElevated=True) if res==2: raise installer.RetriableFailure if copyPortableConfig: installedUserConfigPath=config.getInstalledUserConfigPath() if installedUserConfigPath: gui.ExecAndPump(installer.copyUserConfig,installedUserConfigPath) except Exception as e: res=e log.error("Failed to execute installer",exc_info=True) progressDialog.done() del progressDialog if isinstance(res,installer.RetriableFailure): # Translators: a message dialog asking to retry or cancel when NVDA install fails message=_("The installation is unable to remove or overwrite a file. Another copy of NVDA may be running on another logged-on user account. Please make sure all installed copies of NVDA are shut down and try the installation again.") # Translators: the title of a retry cancel dialog when NVDA installation fails title=_("File in Use") if winUser.MessageBox(None,message,title,winUser.MB_RETRYCANCEL)==winUser.IDRETRY: return doInstall(createDesktopShortcut,startOnLogon,copyPortableConfig,isUpdate,silent,startAfterInstall) if res!=0: log.error("Installation failed: %s"%res) # Translators: The message displayed when an error occurs during installation of NVDA. gui.messageBox(_("The installation of NVDA failed. Please check the Log Viewer for more information."), # Translators: The title of a dialog presented when an error occurs. _("Error"), wx.OK | wx.ICON_ERROR) return if not silent: msg = ( # Translators: The message displayed when NVDA has been successfully installed. _("Successfully installed NVDA. ") if not isUpdate # Translators: The message displayed when NVDA has been successfully updated. else _("Successfully updated your installation of NVDA. ")) # Translators: The message displayed to the user after NVDA is installed # and the installed copy is about to be started. gui.messageBox(msg+_("Please press OK to start the installed copy."), # Translators: The title of a dialog presented to indicate a successful operation. _("Success")) if startAfterInstall: # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL shellapi.ShellExecute( None, None, os.path.join(installer.defaultInstallPath,'nvda.exe'), None, None, winUser.SW_SHOWNORMAL ) else: wx.GetApp().ExitMainLoop()
def restart(disableAddons=False, debugLogging=False): """Restarts NVDA by starting a new copy.""" if globalVars.appArgs.launcher: import gui globalVars.exitCode=3 gui.safeAppExit() return import subprocess import winUser import shellapi for paramToRemove in ("--disable-addons", "--debug-logging", "--ease-of-access"): try: sys.argv.remove(paramToRemove) except ValueError: pass options = [] if not hasattr(sys, "frozen"): options.append(os.path.basename(sys.argv[0])) if disableAddons: options.append('--disable-addons') if debugLogging: options.append('--debug-logging') shellapi.ShellExecute( hwnd=None, operation=None, file=sys.executable, parameters=subprocess.list2cmdline(options + sys.argv[1:]), directory=globalVars.appDir, # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL showCmd=winUser.SW_SHOWNORMAL )
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"))
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 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)
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 openDefaultConfigurationDirectory(): """Opens the directory which would be used to store configuration by default. Used as a fallback when trying to explore user config from the start menu, and NVDA is not running.""" import config path = config.getUserDefaultConfigPath() if not path: raise ValueError("no user default config path") config.initConfigPath(path) shellapi.ShellExecute(0, None, path, None, None, winUser.SW_SHOWNORMAL)
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 script_open(self, gesture): try: PlaySound("C:/Windows/Media/Windows Battery Low.wav", SND_FILENAME | SND_ASYNC) content = getAppId() id = content.split(" ") shellapi.ShellExecute(None, 'open', "explorer.exe", "shell:appsfolder\{}".format(id[-1]), None, 10) except: #Translators: Mensaje que anuncia que no se ha encontrado la aplicación ui.message(_('No se encuentra la aplicación'))
def _downloadSuccess(self): self._stopped() # Translators: The message presented when the update has been successfully downloaded # and is about to be installed. gui.messageBox( _("Update downloaded. It will now be installed."), # Translators: The title of the dialog displayed when the update is about to be installed. _("Install Update")) state["removeFile"] = self.destPath saveState() shellapi.ShellExecute(None, None, self.destPath.decode("mbcs"), u"--install -m", None, 0)
def restart(): """Restarts NVDA by starting a new copy with -r.""" if globalVars.appArgs.launcher: import wx globalVars.exitCode=2 wx.GetApp().ExitMainLoop() return import subprocess import shellapi shellapi.ShellExecute(None, None, sys.executable.decode("mbcs"), subprocess.list2cmdline(sys.argv + ["-r"]).decode("mbcs"), None, 0)
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 _downloadSuccess(self): self._stopped() # Translators: The message presented when the update has been successfully downloaded # and is about to be installed. gui.messageBox( _("Update downloaded. It will now be installed."), # Translators: The title of the dialog displayed when the update is about to be installed. _("Install Update")) state["removeFile"] = self.destPath saveState() # #4475: ensure that the new process shows its first window, by providing SW_SHOWNORMAL shellapi.ShellExecute(None, None, self.destPath.decode("mbcs"), u"--install -m", None, winUser.SW_SHOWNORMAL)
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 openUserConfigurationDirectory(): """Opens directory containing config files for the current user""" import globalVars try: # configPath is guaranteed to be correct for NVDA, however it will not exist for NVDA_slave. path = globalVars.appArgs.configPath except AttributeError: import config path = config.getUserDefaultConfigPath() if not path: raise ValueError("no user default config path") config.initConfigPath(path) shellapi.ShellExecute(0, None, path, None, None, winUser.SW_SHOWNORMAL)
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()
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'))
def doCreatePortable(portableDirectory, copyUserConfig=False, silent=False, startAfterCreate=False): d = gui.IndeterminateProgressDialog( gui.mainFrame, # Translators: The title of the dialog presented while a portable copy of NVDA is bieng created. _("Creating Portable Copy"), # Translators: The message displayed while a portable copy of NVDA is bieng created. _("Please wait while a portable copy of NVDA is created.")) try: gui.ExecAndPump(installer.createPortableCopy, portableDirectory, copyUserConfig) except Exception as e: log.error("Failed to create portable copy", exc_info=True) d.done() if isinstance(e, installer.RetriableFailure): # Translators: a message dialog asking to retry or cancel when NVDA portable copy creation fails message = _("NVDA is unable to remove or overwrite a file.") # Translators: the title of a retry cancel dialog when NVDA portable copy creation fails title = _("File in Use") if winUser.MessageBox(None, message, title, winUser.MB_RETRYCANCEL) == winUser.IDRETRY: return doCreatePortable(portableDirectory, copyUserConfig, silent, startAfterCreate) # Translators: The message displayed when an error occurs while creating a portable copy of NVDA. # %s will be replaced with the specific error message. gui.messageBox( _("Failed to create portable copy: %s") % e, _("Error"), wx.OK | wx.ICON_ERROR) return d.done() if silent: wx.GetApp().ExitMainLoop() else: # Translators: The message displayed when a portable copy of NVDA has been successfully created. # %s will be replaced with the destination directory. gui.messageBox( _("Successfully created a portable copy of NVDA at %s") % portableDirectory, _("Success")) if startAfterCreate: # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL shellapi.ShellExecute( None, None, os.path.join(os.path.abspath(portableDirectory), 'nvda.exe'), u"-r", None, winUser.SW_SHOWNORMAL)
def _startNewInstance(newNVDA: NewNVDAInstance): """ If something (eg the installer or exit dialog) has requested a new NVDA instance to start, start it. Should only be used by calling triggerNVDAExit and after handleNVDAModuleCleanupBeforeGUIExit and _closeAllWindows. """ import shellapi from winUser import SW_SHOWNORMAL log.debug(f"Starting new NVDA instance: {newNVDA}") shellapi.ShellExecute( hwnd=None, operation=None, file=newNVDA.filePath, parameters=newNVDA.parameters, directory=newNVDA.directory, # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL showCmd=SW_SHOWNORMAL)
def _executeUpdate(destPath): if not destPath: return _setStateToNone(state) saveState() if config.isInstalledCopy(): executeParams = u"--install -m" else: portablePath = globalVars.appDir if os.access(portablePath, os.W_OK): executeParams = u'--create-portable --portable-path "{portablePath}" --config-path "{configPath}" -m'.format( portablePath=portablePath, configPath=globalVars.appArgs.configPath) else: executeParams = u"--launcher" # #4475: ensure that the new process shows its first window, by providing SW_SHOWNORMAL shellapi.ShellExecute(None, None, destPath, executeParams, None, winUser.SW_SHOWNORMAL)
def _executeUpdate(destPath): if not destPath: return state["pendingUpdateFile"] = None state["pendingUpdateVersion"] = None saveState() if config.isInstalledCopy(): executeParams = u"--install -m" else: portablePath = os.getcwdu() if os.access(portablePath, os.W_OK): executeParams = u'--create-portable --portable-path "{portablePath}" --config-path "{configPath}" -m'.format( portablePath=portablePath, configPath=os.path.abspath(globalVars.appArgs.configPath)) else: executeParams = u"--launcher" # #4475: ensure that the new process shows its first window, by providing SW_SHOWNORMAL shellapi.ShellExecute(None, None, destPath.decode("mbcs"), executeParams, None, winUser.SW_SHOWNORMAL)
def restartWithOptions(options): """Restarts NVDA by starting a new copy, providing some options.""" if globalVars.appArgs.launcher: import gui globalVars.exitCode=3 gui.safeAppExit() return import subprocess import winUser import shellapi if not hasattr(sys, "frozen"): options.insert(0, os.path.basename(sys.argv[0])) shellapi.ShellExecute( hwnd=None, operation=None, file=sys.executable, parameters=subprocess.list2cmdline(options), directory=globalVars.appDir, # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL showCmd=winUser.SW_SHOWNORMAL )
def cache(): shellapi.ShellExecute(None, 'runas', 'cmd.exe', '/c' + 'ipconfig / flushDNS', None, 10) sleep(0.5) ui.message(_("Se limpió la Caché DNS "))
def openUserConfigurationDirectory(): """Opens directory containing config files for the current user""" import globalVars shellapi.ShellExecute(0, None, globalVars.appArgs.configPath, None, None, winUser.SW_SHOWNORMAL)
def sc_boot(): shellapi.ShellExecute( None, 'runas', 'cmd.exe', '/c' + r'"{}\MpCmdRun.exe" -scan -bootsectorscan'.format(w_pt), None, 10)
def scan_f(): shellapi.ShellExecute( None, 'runas', 'cmd.exe', '/c' + r'"{}\MpCmdRun.exe" -scan -scantype 2'.format(w_pt), None, 10)