def onDecrypt(self, event): errFound = self._checkFilesPasswd(self.KeyFilePath.GetValue(),self.toEncryptPath.GetValue(),self.encryptPassword.GetValue()) if (errFound): event.Skip() else: # open save dialog to pick location to save the decrypted file. with wx.DirDialog(self, _("Select Directory to Save Decrypted File in:"),"", style= wx.DD_DEFAULT_STYLE) as dirDialog: if dirDialog.ShowModal() == wx.ID_CANCEL: event.Skip() # the user changed their mind return() savePath=dirDialog.GetPath() # decrypt and save the file. wait = wx.GenericProgressDialog("Processing",message="",maximum=8) wait.Update(1,"Processing...(Please Wait)") # 1) Randomize the key file using the password. wait.Update(2, "Randomizing key file...") rawkey=open(self.keypath,'rb') rndkey=randomizefile(rawkey, self.passwd) rawkey.close() # 2) Decrypt the file using the temporary randomized key file. wait.Update(5, "Decrypting file...") todecryptfile=open(self.toencryptpath,'rb') decryptresult = decryptfile(savePath,todecryptfile,rndkey) todecryptfile.close() wait.Update(7,"Securely erasing randomized key file...") eraseresult=secureerasefile(rndkey) wait.Update(8, "Done") print("Decryption completed.") del wait event.Skip()
def __init__(self, *args, **kwargs): super(TitanPatcherFrame, self).__init__( style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX, *args, **kwargs) self.progress_bar = wx.GenericProgressDialog( message=f"Applying patch...", title="Titan Patcher") self.progress_msg = [] self.patch_is_finished = False self.width = 350 self.height = 80 self.progress = 0 self.working_dir = "./" self.patch_parent_dir = os.path.join(self.working_dir, "patch") self.patch_dir = os.path.join(self.patch_parent_dir, "titan") self.patch_zip = os.path.join(self.working_dir, "patch.zip") self.config_file = os.path.join(self.working_dir, "titan_games.toml") if len(sys.argv) < 3 or sys.argv[1] != "to_titan": self.progress_bar.Pulse("Paused...") self._error_dialog( title="Incorrect Usage!", msg=f"Titan's patcher is not supposed to be opened manually!") return self.new_version = sys.argv[2] self.pre_check() self.start_patching()
def download_and_unpack(url: str): # pylint: disable=no-member asset_data = get(url).json() zip_url = None for asset in asset_data: if asset['content_type'] == 'application/x-zip-compressed': zip_url = asset['browser_download_url'] break if zip_url: zip_data = get(zip_url, stream=True) size = int(zip_data.headers.get('content-length', 0)) pd = wx.GenericProgressDialog( title="Downloading Update", message="Downloading update, please wait...", maximum=size, style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME) with io.BytesIO() as bio: downloaded = 0 cancelled = False for data in zip_data.iter_content(chunk_size=int(size / 100)): bio.write(data) downloaded += len(data) pd.Update(downloaded) if pd.WasCancelled(): cancelled = True break pd.Destroy() if cancelled: return None with zipfile.ZipFile(bio) as zip_file: exe_name = zip_file.namelist()[0] zip_file.extractall() return exe_name return None
def Run(self, file_path, frame_delay=aob.DEFAULT_frameDelay, show_selections=aob.DEFAULT_showSelections): """Must be called from the UI event thread. Creates a worker thread with the _RunBegin() and _Runend() methods. Args: file_path (str): path to GIF file to create frame_delay (float): delay in seconds b/w frames show_selections (bool): toggle """ if Config.IsWindows(): dialog = wx.GenericProgressDialog( 'Save Animated Image', 'Initializing...', style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT) else: dialog = wx.ProgressDialog('Save Animated Image', 'Initializing...', style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT) dialog.Show() wxlibdr.startWorker( self._RunEnd, self._RunBackground, wargs=[dialog, file_path, frame_delay, show_selections])
def progressbar(parent, message, title, count, can_abort=True): style = wx.PD_AUTO_HIDE | wx.PD_APP_MODAL style = style | wx.PD_CAN_ABORT dlg = wx.GenericProgressDialog(title, message, count, parent, style=style) def close_dlg(evt, dlg=dlg): dlg.Destroy() dlg.Bind(wx.EVT_CLOSE, close_dlg) return dlg
def __init__(self): wx.App.__init__(self, redirect=not __debug__) self.folder = None self.dummy = wx.Frame(None) self.SetTopWindow(self.dummy) if platform=='win32': # wx 3 ProgressDialog on windows cannot be hidden and has annoying disabled Close button self.progress = wx.GenericProgressDialog(appname, "Initializing", parent=self.dummy, style=wx.PD_APP_MODAL|wx.PD_SMOOTH) else: self.progress = wx.ProgressDialog(appname, "Initializing", parent=self.dummy, style=wx.PD_APP_MODAL|wx.PD_SMOOTH) if not platform.startswith('linux'): self.progress.Hide() # can't be unhidden on wxGTK self.progress.SetDimensions(-1, -1, 320, -1, wx.SIZE_USE_EXISTING) self.Bind(wx.EVT_IDLE, self.activate)
def __init__(self, title, msg, maxItems, icon=None): self._app = wx.App() self._meter = wx.GenericProgressDialog(title, msg, maxItems, style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE | wx.PD_REMAINING_TIME | wx.PD_ESTIMATED_TIME) self.maxitems = maxItems self.lastitem = 0 set_icon(self._meter, icon)
def download_to_tempdir(self, run, tmpdir): ''' Actually download the files from the cluster into tmpdir, showing a progress dialog ''' run.downloads = [[d[0], tmpdir] for d in run.downloads] CPRynner.CPRynner().start_download(run) dialog = wx.GenericProgressDialog("Downloading", "Downloading files") maximum = dialog.GetRange() while run['download_status'] < 1: value = min(maximum, int(maximum * run['download_status'])) dialog.Update(value) time.sleep(0.04) dialog.Destroy()
def _create_progress_dlg(self): self.progress_dlg = wx.GenericProgressDialog( parent=self.parent, title=self.title, message=self.message, maximum=self.maxvalue, style=self.prog_dlg_style, ) self.progress_dlg.Bind(wx.EVT_BUTTON, self.onHide, id=ID_SKIP) self.progress_dlg.Bind(wx.EVT_BUTTON, self.onAbort, id=wx.ID_CANCEL) mainFrame = wx.GetApp().mainFrame mainFrame.Bind( wx.EVT_KILL_FOCUS, lambda e: e.IsShown() and mainFrame.contentTextCtrl.SetFocus(), id=self.progress_dlg.Id, )
def test_progdlg1(self): max = 50 dlg = wx.GenericProgressDialog("Progress dialog example", "An informative message", parent=self.frame, maximum=max) keepGoing = True count = 0 while keepGoing and count < max: count += 1 #wx.MilliSleep(250) self.myYield() (keepGoing, skip) = dlg.Update(count) dlg.Destroy()
def upload(self, run, dialog=None): rynner = CPRynner() if dialog == None: dialog = wx.GenericProgressDialog("Uploading", "Uploading files") destroy_dialog = True else: destroy_dialog = False if rynner is not None: rynner.start_upload(run) maximum = dialog.GetRange() while run['upload_status'] < 1: value = min(maximum, int(maximum * run['upload_status'])) dialog.Update(value) dialog.Update(maximum - 1) if destroy_dialog: dialog.Destroy()
def onEncrypt(self, event): errFound = self._checkFilesPasswd(self.KeyFilePath.GetValue(),self.toEncryptPath.GetValue(),self.encryptPassword.GetValue()) if (errFound): event.Skip() else: # open save dialog to pick location to save the encrypted file. with wx.FileDialog(self, _("Save Encrypted File As..."), wildcard="", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT | wx.FD_CHANGE_DIR) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: event.Skip() # the user changed their mind return() savePath=fileDialog.GetPath() rawName=os.path.basename(self.toencryptpath) #print('savePath='+savePath+' \nrawName='+rawName) # encrypt and save the file. wait = wx.GenericProgressDialog("Processing",message="",maximum=8) wait.Update(1,"Processing...(Please Wait)") # 1) Randomize the key file using the password. wait.Update(2, "Randomizing key file...") rawkey=open(self.keypath,'rb') rndkey=randomizefile(rawkey, self.passwd) rawkey.close() # 2) Encrypt the file using the temporary randomized key file. wait.Update(4, "Encrypting file...") toencryptfile=open(self.toencryptpath,'rb') encrypted=encryptfile(toencryptfile,rawName,rndkey) toencryptfile.close() tempPath=os.path.realpath(encrypted.name) encrypted.close() # 3) Save the encrypted file to the requested name. wait.Update(6, "Saving encrypted file...") os.rename(tempPath,savePath) # 4) Securely delete the randomized key file. wait.Update(7, "Securely erasing randomized key file...") erasestatus=secureerasefile(rndkey) wait.Update(8, "Done.") print ("Encryption Completed.") del wait event.Skip()
def ShowSimResult(self, event=None): """ Display simulation results in the grid control """ id = self.cc_id_sim.GetValue() # Retrieve simulation ID from combo box if id == '': return id = int(id) # Find simulation results object related to current project cur_result = None for result in DB.SimulationResults.values(): if result.ID == id and result.ProjectID == self.idPrj: cur_result = result break no_col = len(cur_result.DataColumns) no_row = len(cur_result.Data) no_grid_col = self.grid.GetNumberCols() no_grid_row = self.grid.GetNumberRows() # If there are too many records, allow the user to decide how many # to load to the system to reduce the load. It is impractical to show # very large simulation results. if no_col * no_row > 50000: dlg = wx.NumberEntryDialog( self, 'Define number or records to show', 'The result grid is very large (' + str(no_row) + ' rows x ' + str(no_col) + ' columns) \nand it is probably not practical to show it on the screen. \nPlease decide how many rows you wish to view. \nNote that you can later export the results to view them in full in another application. \nPressing Cancel will show all rows and in some cases may overwhelm the system.', 'Rows to show', 1000, 0, 100000) dlg.CenterOnScreen() if dlg.ShowModal() == wx.ID_OK: no_row = min(dlg.GetValue(), no_row) # adjust the number of rows and columns of the grid congtrol if no_col > no_grid_col: self.grid.AppendCols(no_col - no_grid_col) elif no_col < no_grid_col: self.grid.DeleteCols(no_col, no_grid_col - no_col) if no_row > no_grid_row: self.grid.AppendRows(no_row - no_grid_row) elif no_row < no_grid_row: self.grid.DeleteRows(no_row, no_grid_row - no_row) self.grid.ClearGrid() # Clear current values in grid control dlg = wx.GenericProgressDialog( "Load Data", "Loading Data. Please wait......", maximum=no_col + no_row, parent=self, style=wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME) dlg.CenterOnScreen() for i, column in enumerate( cur_result.DataColumns): # write column header on grid control self.grid.SetColLabelValue(i, column) dlg.Update(i) # update length of gauge in progress dialog for i, row in enumerate(cur_result.Data[0:no_row] ): # write data in each cell in the range for j, col in enumerate(row): value = cdml.iif(row[j] == None, '', str(row[j])) self.grid.SetCellValue(i, j, value) dlg.Update(i + no_col) dlg.Destroy()
def OnReplayLog(self, e: wx.MenuEvent): LOG.info("Attempting to replay an eqlog...") openFileDialog = wx.FileDialog(self.GetParent(), "Open EQ Logfile", "D:\\EverQuest\\Logs\\", "", "EQ Logfile (eqlog_*.txt)|eqlog_*.txt", wx.FD_OPEN) result = openFileDialog.ShowModal() filename = openFileDialog.GetPath() openFileDialog.Destroy() if result != wx.ID_OK: return config.PLAYER_NAME = utils.get_character_name_from_logfile(filename) # Load the lines from the logfile with open(filename, 'r') as logfile: loglines = logfile.readlines() # Get the timestamp bounds try: first_time = utils.get_first_timestamp(loglines) last_time = utils.get_first_timestamp(reversed(loglines)) LOG.info("%s -> %s", first_time, last_time) if not first_time and last_time: raise ValueError() except (TypeError, ValueError): LOG.exception("Failed to find a first/last timestamp") self.DialogParseFail() return time_select_dialog = wx.Dialog(self.GetParent(), title="Select Time Bounds") time_select_main_box = wx.BoxSizer(wx.VERTICAL) # Time Bounds time_select_bounds_box = wx.GridBagSizer(3, 2) bold_font = wx.Font(10, wx.DEFAULT, wx.DEFAULT, wx.BOLD) from_label = wx.StaticText(time_select_dialog, label="From") from_label.SetFont(bold_font) date_chooser_from = wx.adv.DatePickerCtrl(time_select_dialog) date_chooser_from.SetValue(first_time) date_chooser_from.SetRange(first_time, last_time) time_chooser_from = wx.adv.TimePickerCtrl(time_select_dialog) time_chooser_from.SetValue(first_time) to_label = wx.StaticText(time_select_dialog, label="To") to_label.SetFont(bold_font) date_chooser_to = wx.adv.DatePickerCtrl(time_select_dialog) date_chooser_to.SetValue(last_time) date_chooser_to.SetRange(first_time, last_time) time_chooser_to = wx.adv.TimePickerCtrl(time_select_dialog) time_chooser_to.SetValue(last_time) time_select_bounds_box.Add(from_label, pos=(0, 0), border=2, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL) time_select_bounds_box.Add(date_chooser_from, pos=(0, 1), border=2, flag=wx.ALIGN_RIGHT | wx.ALL) time_select_bounds_box.Add(time_chooser_from, pos=(0, 2), border=2, flag=wx.ALIGN_RIGHT | wx.ALL) time_select_bounds_box.Add(to_label, pos=(1, 0), border=2, flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL) time_select_bounds_box.Add(date_chooser_to, pos=(1, 1), border=2, flag=wx.ALIGN_RIGHT | wx.ALL) time_select_bounds_box.Add(time_chooser_to, pos=(1, 2), border=2, flag=wx.ALIGN_RIGHT | wx.ALL) # Buttons time_select_buttons_box = time_select_dialog.CreateButtonSizer( wx.OK | wx.CANCEL) time_select_main_box.Add(time_select_bounds_box, border=10, flag=wx.ALL | wx.EXPAND) time_select_main_box.Add(time_select_buttons_box, border=10, flag=wx.BOTTOM | wx.RIGHT | wx.EXPAND) time_select_dialog.SetSizer(time_select_main_box) time_select_dialog.Fit() # Show the modal if time_select_dialog.ShowModal() != wx.ID_OK: time_select_dialog.Destroy() return time_select_dialog.Destroy() fd, ft = date_chooser_from.GetValue(), time_chooser_from.GetValue() fdt = datetime.datetime(*map(int, fd.FormatISODate().split('-')), *map(int, ft.FormatISOTime().split(':'))) td, tt = date_chooser_to.GetValue(), time_chooser_to.GetValue() tdt = datetime.datetime(*map(int, td.FormatISODate().split('-')), *map(int, tt.FormatISOTime().split(':'))) first_index = utils.find_timestamp(loglines, fdt) last_index = utils.find_timestamp(loglines, tdt) if first_index is None or last_index is None: # can't parse those times LOG.error( "Couldn't find the first (%s) or last (%s) log line index.", first_index, last_index) self.DialogParseFail() return LOG.debug("Times: %s -> %s", fdt, tdt) LOG.debug("First line: %s", loglines[first_index]) LOG.debug("Last line: %s", loglines[max(last_index - 1, 0)]) picked_lines = loglines[first_index:last_index] total_picked_lines = len(picked_lines) parse_progress_dialog = wx.GenericProgressDialog( title="Parsing Logs...", message="Please wait while your logfile is parsed.", maximum=total_picked_lines, parent=self.GetParent(), style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME) logreplay.replay_logs(picked_lines, parse_progress_dialog) self.GetParent().bidding_frame.OnHideRot(None) parse_progress_dialog.Destroy()
def start_progress_dialog(start): if start: preset.gui_progress_dialog = wx.GenericProgressDialog( "", "", style=wx.PD_AUTO_HIDE | wx.PD_APP_MODAL | wx.PD_CAN_ABORT) else: preset.gui_progress_dialog = None
def progress_dialog(message, caption="", maximum=100): return wx.GenericProgressDialog(caption,message,maximum=maximum)
def prepare_run(self, workspace): '''Invoke the image_set_list pickling mechanism and save the pipeline''' pipeline = workspace.pipeline if pipeline.test_mode: return True if self.batch_mode.value: return True else: rynner = CPRynner() if rynner is not None: # Get parameters max_tasks = int(cluster_tasks_per_node()) setup_script = cluster_setup_script() # Set walltime rynner.provider.walltime = str( self.max_walltime.value) + ":00:00" # save the pipeline path = self.save_pipeline(workspace) # Create the run data structure file_list = pipeline.file_list file_list = [ name.replace('file:///', '') for name in file_list ] file_list = [name.replace('file:', '') for name in file_list] file_list = [name.replace('%20', ' ') for name in file_list] if len(file_list) == 0: wx.MessageBox( "No images found. Did you remember to add them to the Images module?", caption="No images", style=wx.OK | wx.ICON_INFORMATION) return False # Divide measurements to runs according to the number of cores on a node n_images = len(file_list) if not self.is_archive.value: n_measurements = int(n_images / self.n_images_per_measurement.value) measurements_per_run = int(n_measurements / max_tasks) + 1 grouped_images = self.group_images(file_list, n_measurements, measurements_per_run, self.type_first.value) n_image_groups = max(zip(*grouped_images)[0]) + 1 # Add image files to uploads uploads = [[name, 'run{}/images'.format(g)] for g, name in grouped_images] else: if n_images > 1: wx.MessageBox( "Include only one image archive per run.", caption="Image error", style=wx.OK | wx.ICON_INFORMATION) return False uploads = [[file_list[0], 'images']] n_measurements = self.measurements_in_archive.value n_image_groups = max_tasks # Also add the pipeline uploads += [[path, '.']] # The runs are downloaded in their separate folders. They can be processed later output_dir = cpprefs.get_default_output_directory() downloads = [['run{}'.format(g), output_dir] for g in range(n_image_groups)] # Create run scripts and add to uploads for g in range(n_image_groups): runscript_name = 'cellprofiler_run{}'.format(g) local_script_path = os.path.join( rynner.provider.script_dir, runscript_name) if not self.is_archive.value: n_measurements = len([ i for i in grouped_images if i[0] == g ]) / self.n_images_per_measurement.value script = "cellprofiler -c -p ../Batch_data.h5 -o results -i images -f 1 -l {} 2>>../cellprofiler_output; rm -r images".format( n_measurements) else: n_images_per_group = int(n_measurements / max_tasks) n_additional_images = int(n_measurements % max_tasks) if g < n_additional_images: first = (n_images_per_group + 1) * g last = (n_images_per_group + 1) * (g + 1) else: first = n_images_per_group * g + n_additional_images last = n_images_per_group * ( g + 1) + n_additional_images script = "mkdir images; cp ../images/* images; cellprofiler -c -p ../Batch_data.h5 -o results -i images -f {} -l {} 2>>../cellprofiler_output; rm -r images".format( first, last) with open(local_script_path, "w") as file: file.write(script) uploads += [[local_script_path, "run{}".format(g)]] # Define the job to run script = '{}; printf %s\\\\n {{0..{}}} | xargs -P 40 -n 1 -IX bash -c "cd runX ; ./cellprofiler_runX; ";'.format( setup_script, n_image_groups - 1) script = script.replace('\r\n', '\n') script = script.replace(';;', ';') print(script) run = rynner.create_run( jobname=self.runname.value.replace(' ', '_'), script=script, uploads=uploads, downloads=downloads, ) run['account'] = self.account.value # Copy the pipeline and images accross dialog = wx.GenericProgressDialog("Uploading", "Uploading files", style=wx.PD_APP_MODAL) try: self.upload(run, dialog) # Submit the run dialog.Update(dialog.GetRange() - 1, "Submitting") success = CPRynner().submit(run) dialog.Destroy() if success: wx.MessageBox( "RunOnCluster submitted the run to the cluster", caption="RunOnCluster: Batch job submitted", style=wx.OK | wx.ICON_INFORMATION) else: wx.MessageBox("RunOnCluster failed to submit the run", caption="RunOnCluster: Failure", style=wx.OK | wx.ICON_INFORMATION) except Exception as e: dialog.Destroy() raise e return False