class CustomScriptProfile(PybotProfile): '''A runner profile which uses script given by the user''' name = "custom script" default_settings = dict(PybotProfile.default_settings, runner_script="") def get_command(self): return self.runner_script def get_cwd(self): return os.path.dirname(self.runner_script) def get_toolbar_items(self): return [self.RunScriptPanel, self.ArgumentsPanel, self.TagsPanel] def _validate_arguments(self, args): # Can't say anything about custom script argument validity pass def _create_error_log_message(self, error, returncode): return None def RunScriptPanel(self, parent): panel = wx.Panel(parent, wx.ID_ANY) self._script = FileBrowseButton( panel, labelText="Script to run tests:", size=(-1, -1), fileMask="*", changeCallback=self.OnCustomScriptChanged) self._script.SetValue(self.runner_script) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self._script, 0, wx.ALL | wx.EXPAND) panel.SetSizerAndFit(sizer) return panel def OnCustomScriptChanged(self, evt): self.set_setting("runner_script", self._script.GetValue())
class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="wx.Sound", size=(500, 100)) p = wx.Panel(self) # create the controls self.fbb = FileBrowseButton(p, labelText="Select WAV file:", fileMask="*.wav") btn = wx.Button(p, -1, "Play") self.Bind(wx.EVT_BUTTON, self.OnPlaySound, btn) # setup the layout with sizers sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.fbb, 1, wx.ALIGN_CENTER_VERTICAL) sizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL) border = wx.BoxSizer(wx.VERTICAL) border.Add(sizer, 0, wx.EXPAND | wx.ALL, 15) p.SetSizer(border) def OnPlaySound(self, evt): filename = self.fbb.GetValue() self.sound = wx.Sound(filename) if self.sound.IsOk(): self.sound.Play(wx.SOUND_ASYNC) else: wx.MessageBox("Invalid sound file", "Error")
class SendFileFrame(sc.SizedFrame): """File sending options.""" def __init__(self, callback, filename = '', prefix = '', suffix = '', linesep = '\n', preline = '', postline = '', ignore = ''): super(SendFileFrame, self).__init__(None, title = 'Send File') self.callback = callback s = wx.TE_RICH|wx.TE_MULTILINE p = self.GetContentsPane() p.SetSizerType('form') wx.StaticText(p, label = '&File name') self.filename = FileBrowseButton(p) self.filename.SetValue(filename) wx.StaticText(p, label = 'Text to &prefix the file with') self.prefix = wx.TextCtrl(p, value = prefix, style = s) wx.StaticText(p, label = 'Text to p&refix each line with') self.preLine = wx.TextCtrl(p, value = preline, style = s) wx.StaticText(p, label = 'Text to s&uffix each line with') self.postLine = wx.TextCtrl(p, value = postline, style = s) wx.StaticText(p, label = 'Line &seperator') self.linesep = wx.TextCtrl(p, value = linesep, style = s) wx.StaticText(p, label = 'Text to &suffix the file with') self.suffix = wx.TextCtrl(p, value = suffix, style = s) wx.StaticText(p, label = 'Text to &ignore') self.ignore = wx.TextCtrl(p, value = ignore) self.cancel = wx.Button(p, label = '&Cancel') self.cancel.Bind(wx.EVT_BUTTON, lambda event: self.Close(True)) self.ok = wx.Button(p, label = '&OK') self.ok.Bind(wx.EVT_BUTTON, self.onOk) self.ok.SetDefault() self.Maximize(True) def onOk(self, event): """Sends the stuff using callback.""" f = self.filename.GetValue() if not os.path.isfile(f): return wx.MessageBox('No such file: %s.' % f, 'Error', style = wx.ICON_ERROR) c = self.prefix.GetValue() sep = self.linesep.GetValue() c += sep pre = self.preLine.GetValue() post = self.postLine.GetValue() if self.ignore.GetValue(): m = re.compile(self.ignore.GetValue()) else: m = None with open(f, 'r') as f: for line in f: line = line[:-1] if not m or not m.match(line): c+= '%s%s%s%s' % (pre, line, post, sep) self.callback(c + self.suffix.GetValue()) self.Close(True)
class LogParserFrame(SizedFrame): """ The frame to use with LogParser. LogParserFrame(world) * world is the world to send the entries too. """ def __init__(self, world): super(LogParserFrame, self).__init__(None, title='Send Log') self.world = world p = self.GetContentsPane() p.SetSizerType('form') self.log = FileBrowseButton(p) self.log.SetLabel('Log &file to send') self.process = wx.CheckBox(p, label='&Process resulting lines') self.process.SetValue(True) wx.StaticText(p, label='Send &before log') self.logPrefix = wx.TextCtrl(p, style=wx.TE_RICH, value=logPrefix) wx.StaticText(p, label='Send &after log') self.logSuffix = wx.TextCtrl(p, style=wx.TE_RICH, value=logSuffix) self.ok = wx.Button(p, label='&OK') self.ok.Bind(wx.EVT_BUTTON, self.onOk) self.cancel = wx.Button(p, label='&Cancel') self.cancel.Bind(wx.EVT_BUTTON, lambda event: self.Close(True)) self.Maximize() def onOk(self, event): """Handle the form.""" l = self.log.GetValue() if not os.path.isfile(l): return wx.MessageBox('You must supply a valid log file.', 'Error') with open(l, 'r') as f: s = f.read() try: p = LogParser(s) except LogParserError as e: return wx.MessageBox(str(e), 'Error in log file') prefix = self.logPrefix.GetValue() if prefix: lines = [(0.0, prefix)] else: lines = [] lines += [(x, z) for x, y, z in p.contents if y == 'output'] suffix = self.logSuffix.GetValue() if suffix: lines.append((lines[-1][0], suffix)) LogParserProgress(lines, self.world, self.process.GetValue()).Show(True) self.Close(True)
class CustomScriptProfile(PybotProfile): """A runner profile which uses script given by the user""" name = "custom script" default_settings = dict(PybotProfile.default_settings, runner_script="") def get_command(self): # strip the starting and ending spaces to ensure # /bin/sh finding the executable file return self.runner_script.strip() def get_cwd(self): return os.path.dirname(self.runner_script) @overrides(PybotProfile) def get_toolbar_items(self, parent): return [ self._get_run_script_panel(parent), self._get_arguments_panel(parent), self._get_tags_panel(parent), self._get_log_options_panel(parent) ] def _validate_arguments(self, args): # Can't say anything about custom script argument validity pass def _create_error_log_message(self, error, returncode): return None def _get_run_script_panel(self, parent): panel = wx.Panel(parent, wx.ID_ANY) self._script_ctrl = FileBrowseButton( panel, labelText="Script to run tests:", size=(-1, -1), fileMask="*", changeCallback=self.OnCustomScriptChanged) self._script_ctrl.SetValue(self.runner_script) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self._script_ctrl, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5) panel.SetSizerAndFit(sizer) return panel def OnCustomScriptChanged(self, evt): self.set_setting("runner_script", self._script_ctrl.GetValue())
class MyFrame(wx.Frame): def __init__(self, parent, app_title, app_size): wx.Frame.__init__(self, parent, wx.ID_ANY, app_title, size=app_size) panel = wx.Panel(self) # Mask file browser to look for .bin files. # Explain browse_button. self.browse_button = FileBrowseButton(panel, labelText="Select a BIN file:", fileMask="*.bin") # Explain flash_button. self.flash_button = wx.Button(panel, wx.ID_ANY, "Flash") self.flash_button.Bind(wx.EVT_BUTTON, self.on_flash) self.text_ctrl = wx.TextCtrl(panel, style=wx.TE_MULTILINE) output_txt = "st-flash says:\n" self.text_ctrl.AppendText(output_txt) # Setup the layout with sizers. # Create a horizontal_sizer space. horiz_sizer = wx.BoxSizer(wx.HORIZONTAL) horiz_sizer.Add(self.browse_button, 1, wx.ALIGN_CENTER_VERTICAL) horiz_sizer.Add(self.flash_button, 0, wx.ALIGN_CENTER_VERTICAL) # Create a vertical_sizer space. vertical_sizer = wx.BoxSizer(wx.VERTICAL) vertical_sizer.Add(horiz_sizer, 0, wx.EXPAND | wx.ALL, 10) vertical_sizer.Add(self.text_ctrl, 1, wx.EXPAND | wx.ALL, 10) # Vertical sizer space contains horizontal sizer space, so set them. panel.SetSizer(vertical_sizer) def on_flash(self, evt): filename = self.browse_button.GetValue() if filename: p = Popen(['st-flash', 'write', filename, '0x8000000'], stdin=PIPE, stdout=PIPE, stderr=PIPE) output = p.communicate( b"input data that is passed to subprocess' stdin") self.text_ctrl.AppendText(output[0]) self.text_ctrl.AppendText(output[1]) else: wx.MessageBox("Missing or invalid BIN file", "Error")
class SaveDialog(wx.Dialog): def __init__(self, parent, path, name): wx.Dialog.__init__(self, parent, -1, "Save a copy of flame", size=(400, 120)) path = os.path.abspath(path) self.fbb = FileBrowseButton(self, -1, fileMask=parent.wildcard, labelText='File: ', initialValue=path, fileMode=wx.SAVE) self.nametc = wx.TextCtrl(self, -1) self.nametc.SetValue(name) self.nametc.SetMinSize((200, 27)) ok = wx.Button(self, wx.ID_OK) cancel = wx.Button(self, wx.ID_CANCEL) ok.SetDefault() btnsizer = wx.StdDialogButtonSizer() btnsizer.AddButton(ok) btnsizer.AddButton(cancel) btnsizer.Realize() szr0 = wx.BoxSizer(wx.HORIZONTAL) szr0.Add(wx.StaticText(self, -1, "Name:")) szr0.Add(self.nametc) szr = wx.BoxSizer(wx.VERTICAL) szr.AddMany( ((self.fbb, 0, wx.EXPAND | wx.ALL, 2), (szr0, 0, wx.EXPAND | wx.ALL, 2), (btnsizer, 0, wx.ALL, 2))) self.SetSizerAndFit(szr) self.SetSize((400, self.Size[1])) def GetPath(self): return self.fbb.GetValue() def GetName(self): return self.nametc.GetValue()
def run_as_data_tool(self): from cellprofiler.gui.editobjectsdlg import EditObjectsDialog import wx from wx.lib.filebrowsebutton import FileBrowseButton from cellprofiler.modules.namesandtypes import ObjectsImageProvider from bioformats import load_image with wx.Dialog(None) as dlg: dlg.Title = "Choose files for editing" dlg.Sizer = wx.BoxSizer(wx.VERTICAL) sub_sizer = wx.BoxSizer(wx.HORIZONTAL) dlg.Sizer.Add(sub_sizer, 0, wx.EXPAND | wx.ALL, 5) new_or_existing_rb = wx.RadioBox(dlg, style=wx.RA_VERTICAL, choices=("New", "Existing")) sub_sizer.Add(new_or_existing_rb, 0, wx.EXPAND) objects_file_fbb = FileBrowseButton( dlg, size=(300, -1), fileMask= "Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg", dialogTitle="Select objects file", labelText="Objects file:", ) objects_file_fbb.Enable(False) sub_sizer.AddSpacer(5) sub_sizer.Add(objects_file_fbb, 0, wx.ALIGN_TOP | wx.ALIGN_RIGHT) def on_radiobox(event): objects_file_fbb.Enable(new_or_existing_rb.GetSelection() == 1) new_or_existing_rb.Bind(wx.EVT_RADIOBOX, on_radiobox) image_file_fbb = FileBrowseButton( dlg, size=(300, -1), fileMask= "Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg", dialogTitle="Select guide image file", labelText="Guide image:", ) dlg.Sizer.Add(image_file_fbb, 0, wx.EXPAND | wx.ALL, 5) allow_overlap_checkbox = wx.CheckBox(dlg, -1, "Allow objects to overlap") allow_overlap_checkbox.Value = True dlg.Sizer.Add(allow_overlap_checkbox, 0, wx.EXPAND | wx.ALL, 5) buttons = wx.StdDialogButtonSizer() dlg.Sizer.Add(buttons, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5) buttons.Add(wx.Button(dlg, wx.ID_OK)) buttons.Add(wx.Button(dlg, wx.ID_CANCEL)) buttons.Realize() dlg.Fit() result = dlg.ShowModal() if result != wx.ID_OK: return self.allow_overlap.value = allow_overlap_checkbox.Value fullname = objects_file_fbb.GetValue() guidename = image_file_fbb.GetValue() if new_or_existing_rb.GetSelection() == 1: provider = ObjectsImageProvider("InputObjects", pathname2url(fullname), None, None) image = provider.provide_image(None) pixel_data = image.pixel_data shape = pixel_data.shape[:2] labels = [pixel_data[:, :, i] for i in range(pixel_data.shape[2])] else: labels = None # # Load the guide image # guide_image = load_image(guidename) if np.min(guide_image) != np.max(guide_image): guide_image = (guide_image - np.min(guide_image)) / ( np.max(guide_image) - np.min(guide_image)) if labels is None: shape = guide_image.shape[:2] labels = [np.zeros(shape, int)] with EditObjectsDialog(guide_image, labels, self.allow_overlap, self.object_name.value) as dialog_box: result = dialog_box.ShowModal() if result != wx.OK: return labels = dialog_box.labels n_frames = len(labels) with wx.FileDialog(None, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg: dlg.Path = fullname dlg.Wildcard = ("Object image file (*.tif,*.tiff)|*.tif;*.tiff|" "Ilastik project file (*.ilp)|*.ilp") result = dlg.ShowModal() fullname = dlg.Path if result == wx.ID_OK: if fullname.endswith(".ilp"): self.save_into_ilp(fullname, labels, guidename) else: from bioformats.formatwriter import write_image from bioformats.omexml import PT_UINT16 if os.path.exists(fullname): os.unlink(fullname) for i, l in enumerate(labels): write_image(fullname, l, PT_UINT16, t=i, size_t=len(labels))
class pvg_AcquirePanel(wx.Panel): def __init__(self, parent): # debug wx.Panel.__init__(self, parent, wx.ID_ANY) self.parent = parent print('$$$$$$ changing to dir: ' + data_dir) # debug os.chdir(data_dir) # debug mainSizer = wx.BoxSizer(wx.VERTICAL) self.FBconfig = FileBrowseButton(self, -1, labelText='Pick file', size=(300, -1), changeCallback=self.configCallback) print('$$$$$$ file browse button created') colLabels = [ 'Monitor', 'Source', 'Mask', 'Output', 'Track type', 'Track' ] dataTypes = [ gridlib.GRID_VALUE_NUMBER, gridlib.GRID_VALUE_STRING, gridlib.GRID_VALUE_STRING, gridlib.GRID_VALUE_STRING, gridlib.GRID_VALUE_STRING, gridlib.GRID_VALUE_BOOL, ] self.grid = CustTableGrid(self, colLabels, dataTypes, enableEdit=True, useMenu=False) print('$$$$$$ grid created by custtablegrid') self.grid.Clear() btnSizer = wx.BoxSizer(wx.HORIZONTAL) self.startBtn = wx.Button(self, wx.ID_ANY, 'Start') self.stopBtn = wx.Button(self, wx.ID_ANY, 'Stop') self.stopBtn.Enable(False) self.Bind(wx.EVT_BUTTON, self.onStop, self.stopBtn) self.Bind(wx.EVT_BUTTON, self.onStart, self.startBtn) print('$$$$$$ start and stop buttons are bound') btnSizer.Add(self.startBtn, 0, wx.ALL, 5) btnSizer.Add(self.stopBtn, 0, wx.ALL, 5) mainSizer.Add(self.FBconfig, 0, wx.EXPAND | wx.ALL, 5) mainSizer.Add(self.grid, 1, wx.EXPAND, 0) mainSizer.Add(btnSizer, 0, wx.ALL, 5) self.SetSizer(mainSizer) print('$$$$$$ sizer completed') # def configCallback(self, event): # debug """ """ self.loadFile(self.FBconfig.GetValue()) # def loadFile(self, filename): # debug """ """ print('$$$$$$ filename = ', filename) self.options = pvg_config(filename) print("$$$$$$ options = ", self.options) self.updateTable() print("$$$$$$ table updated") self.parent.sb.SetStatusText('Loaded file %s' % filename) print("$$$$$$ status bar message changed") # return True def updateTable(self): # debug """ """ monitorsData = self.options.getMonitorsData() self.grid.Clear() self.monitors = {} for mn in monitorsData: m = monitorsData[mn] try: s = os.path.split(m['source'])[1] except: s = 'Camera %02d' % (m['source'] + 1) mf = os.path.split(m['mask_file'])[1] df = 'Monitor%02d.txt' % (mn + 1) row = [mn, s, mf, df, m['track_type'], m['track']] self.grid.AddRow(row) for mn in monitorsData: # collects specs for monitors from config m = monitorsData[mn] self.monitors[mn] = (acquireThread(mn, m['source'], m['resolution'], m['mask_file'], m['track'], m['track_type'], m['dataFolder'])) print('$$$$$$ mm = ', mn, '\n options = ', self.monitors[mn], '\n m = ', m) # debug # def isToTrack(self, monitor): # debug """ """ d = self.grid.GetData() print('$$$$$$ isToTrack monitor = ', monitor) # debug for row in d: print('$$$$$$ isToTrack row in d = ', row) # debug print('$$$$$$ istotrack row[0] = ', row[0]) if monitor == row[0]: print('$$$$$$ isToTrack row[-1] = ', row[-1]) # return row[-1] # def onStart(self, event=None): # debug """ """ print('$$$$$$ Start button clicked') self.acquiring = True self.stopBtn.Enable(self.acquiring) self.startBtn.Enable(not self.acquiring) c = 0 print('$$$$$$ onStart monitors: ', self.monitors) for mon in self.monitors: print('\n $$$$$$ c is ', c) print('\n $$$$$$ mon: ', mon) if self.isToTrack(mon): print('\n$$$$$$ mon istotrack is true') self.monitors[mon].doTrack() print('\n $$$$$$ tracking done') c += 1 self.parent.sb.SetStatusText('Tracking %s Monitors' % (str(int(c)))) # def onStop(self, event): # debug """ """ print('$$$$$$ stop clicked') self.acquiring = False self.stopBtn.Enable(self.acquiring) self.startBtn.Enable(not self.acquiring) for mon in self.monitors: self.monitors[mon].halt() self.parent.sb.SetStatusText('All tracking is now stopped')
class mainPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, wx.ID_ANY, size=(600, 300)) self.parent = parent self.gui() def gui(self): self.inputfile = FileBrowseButton( self, id=wx.ID_ANY, labelText='Input File', buttonText='Browse', startDirectory='C:\Users\labadmin\Desktop\OptoGenetics\Data_Folder', toolTip='Type filename or click browse to choose input file', dialogTitle='Choose an input file', size=(300, -1), fileMask='*.*', fileMode=wx.ALL, name='input browse button') # self.outputPrompt = wx.StaticText(self, wx.ID_ANY, "Output File Prefix: ") # self.outputfile = wx.TextCtrl(self, wx.ID_ANY, name='outputprefix') self.datePrompt = wx.StaticText(self, wx.ID_ANY, "Start Date: ") self.startDate = wx.DatePickerCtrl(self, wx.ID_ANY, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY) self.timePrompt = wx.StaticText(self, wx.ID_ANY, "Start Time: ") self.spinbtn = wx.SpinButton(self, wx.ID_ANY, wx.DefaultPosition, (-1, 20), wx.SP_VERTICAL) self.startTime = masked.TimeCtrl(self, wx.ID_ANY, name='time: \n24 hour control', fmt24hr=True, spinButton=self.spinbtn) # self.fpsPrompt = wx.StaticText(self, wx.ID_ANY, "Frame Rate (fps): ") # self.fps = wx.TextCtrl(self, wx.ID_ANY) self.startBtn = wx.Button(self, wx.ID_STOP, label="Start") self.statusbar = wx.wx.TextCtrl(self, wx.ID_ANY, size=(1000, 20), value="", style=wx.TE_READONLY) self.Bind(wx.EVT_BUTTON, self.onStart, self.startBtn) mainSizer = wx.BoxSizer(wx.VERTICAL) # spacerSizer = wx.BoxSizer(wx.HORIZONTAL) inSizer = wx.BoxSizer(wx.HORIZONTAL) outSizer = wx.BoxSizer(wx.HORIZONTAL) dateSizer = wx.BoxSizer(wx.HORIZONTAL) timeSizer = wx.BoxSizer(wx.HORIZONTAL) # fpsSizer = wx.BoxSizer(wx.HORIZONTAL) inSizer.Add(self.inputfile, 1, wx.LEFT | wx.EXPAND, 10) # outSizer.Add(self.outputPrompt, 0, wx.LEFT, 10) # outSizer.Add(self.outputfile, 0, wx.LEFT, 10) dateSizer.Add(self.datePrompt, 0, wx.LEFT | wx.EXPAND, 10) dateSizer.Add(self.startDate, 0, wx.LEFT | wx.EXPAND, 10) # timeSizer.AddSpacer(8) timeSizer.Add(self.timePrompt, 0, wx.LEFT | wx.EXPAND, 10) timeSizer.Add(self.startTime, 0, wx.LEFT | wx.EXPAND, 7) timeSizer.Add(self.spinbtn, 0, wx.LEFT | wx.EXPAND, 4) # self.addWidgets(timeSizer, [self.timePrompt, self.startTime, self.spinbtn]) # timeSizer.Add(self.startTime, 0, wx.LEFT, 10) # fpsSizer.Add(self.fpsPrompt, 0, wx.LEFT | wx.EXPAND, 10) # fpsSizer.Add(self.fps, 0, wx.LEFT | wx.EXPAND, 10) mainSizer.Add(inSizer, 0, wx.LEFT | wx.EXPAND, 10) mainSizer.Add(outSizer, 0, wx.LEFT | wx.EXPAND, 10) mainSizer.Add(dateSizer, 0, wx.LEFT | wx.EXPAND, 10) mainSizer.Add(timeSizer, 0, wx.LEFT | wx.EXPAND, 10) # mainSizer.Add(fpsSizer, 0, wx.LEFT | wx.EXPAND, 10) mainSizer.Add(self.startBtn, 0, wx.CENTER, 10) mainSizer.AddSpacer(20) mainSizer.Add(self.statusbar, 0, wx.CENTER | wx.EXPAND, 10) mainSizer.AddSpacer(20) self.SetSizer(mainSizer) """ def addWidgets(self, mainSizer ,widgets): sizer = wx.BoxSizer(wx.HORIZONTAL) for widget in widgets: if isinstance(widget, wx.StaticText): sizer.Add(widget, 0, wx.ALL | wx.EXPAND, 2), else: sizer.Add(widget, 0, wx.ALL | wx.EXPAND, 2) mainSizer.Add(sizer) """ def onStart(self, event): self.startBtn.Enable(False) self.colSplit32() def colSplit32(self): parts = [] inputfile = self.inputfile.GetValue() self.outputprefix = os.path.split(inputfile)[1][0:-4] if self.outputprefix != '': with open(inputfile, 'rb') as f_in: input_tsv = csv.reader(f_in, delimiter='\t') self.interval = wx.TimeSpan( 0, 1, 0) # one minute of data per row of output for rowdata in input_tsv: # determine how many files are needed rownum = int(rowdata[0]) if rownum == 1: self.numofParts = int( math.ceil((len(rowdata) - 10) / 32.0)) # number of separate files needed for num in range(0, self.numofParts): parts.append( [] ) # create a list of data for each file to be created # fix the date and time realdatetime = self.startDate.Value + self.startTime.GetValue( as_wxTimeSpan=True) self.outputprefix = self.noOverwrite() else: realdatetime = realdatetime + self.interval rowdata[1] = realdatetime.Format( '%d %b %y') # column 1 is the date rowdata[2] = realdatetime.Format( '%H:%M:%S') # column 2 is the time prefix = '\t'.join( rowdata[0:10] ) # first 10 columns are part of each file for batch in range( 0, self.numofParts): # add 32 columns to each part startcol = 10 + batch * 32 endcol = startcol + 32 parts[batch].append( prefix + '\t' + '\t'.join(rowdata[startcol:endcol]) + '\n' ) # append all of the rows to list "part[batch]" if len( rowdata ) != self.numofParts * 32 + 10: # need to fill empty columns with zeroes morecols = (self.numofParts * 32 + 10) - input_tsv.__sizeof__() for rownum in range(0, len(parts[self.numofParts - 1])): parts[self.numofParts - 1][rownum] = parts[self.numofParts - 1][rownum][0:-1] + \ '\t' + '\t'.join(list(repeat('0', morecols))) + '\n' for batch in range(0, self.numofParts): outputfile = self.outputprefix + str( batch + 1) + '.txt' # create a filename for saving f_out = open(outputfile, 'a') for rownum in range(0, len(parts[batch])): f_out.write( parts[batch][rownum] ) # save "part" to the file in tab delimited format f_in.close() f_out.close() filename = os.path.split(self.outputprefix)[1] if filename == '': self.statusbar.SetValue('Cancelled.') self.startBtn.Enable(True) else: self.statusbar.SetValue('Done. Output file names start with: ' + filename) self.startBtn.Enable(True) def noOverwrite(self): goodname = False # avoid possibility of file overwrite while not goodname: goodname = True # change to false if there's a problem for batch in range(0, self.numofParts): # check for each output file outputfile = self.outputprefix + str( batch + 1) + '.txt' # create a filename for saving if os.path.isfile(outputfile) and goodname == True: self.statusbar.SetValue('Avoid overwrite: File -> ' + outputfile + ' <- already exists.') winsound.Beep(600, 200) goodname = False # no more files will be tested and while loop continues wildcard = "Monitor File Prefix (*.txt)|*.txt|" \ "All files (*.*)|*.*" # adding space in here will mess it up! dlg = wx.FileDialog( self.parent, message="Choose a different output prefix ...", wildcard=wildcard, style=wx.SAVE, ) if dlg.ShowModal( ) == wx.ID_OK: # show the file browser window self.outputprefix = dlg.GetPath( )[0: -4] # get the filepath & name from the save dialog, don't use extension else: self.outputprefix = '' goodname = True # stop looking for an output prefix name break dlg.Destroy() return self.outputprefix
class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Face_Expression_AutoMai", size=(800,500)) menuFile = wx.Menu() menuFile.Append(1, "&About...") menuFile.AppendSeparator() menuFile.Append(2, "E&xit") menuBar = wx.MenuBar() menuBar.Append(menuFile, "&File") self.SetMenuBar(menuBar) self.CreateStatusBar() self.SetStatusText("Enjoy making face expression!") self.Bind(wx.EVT_MENU, self.OnAbout, id=1) self.Bind(wx.EVT_MENU, self.OnQuit, id=2) p = wx.Panel(self) # create the controls self.fbb1 = FileBrowseButton(p, labelText="选择风格图片:", fileMask="*.jpg") self.fbb2 = FileBrowseButton(p, labelText="选择五官源图片:", fileMask="*.jpg") btn = wx.Button(p, -1, "生成") self.Bind(wx.EVT_BUTTON, self.OnGenePic, btn) # setup the layout with sizers sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.fbb1, 1, wx.ALIGN_CENTER_VERTICAL) sizer.Add(self.fbb2, 1, wx.ALIGN_CENTER_VERTICAL) sizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL) border = wx.BoxSizer(wx.VERTICAL) border.Add(sizer, 0, wx.EXPAND|wx.ALL, 15) p.SetSizer(border) def OnQuit(self, event): self.Close() def OnAbout(self, event): wx.MessageBox("Author: XiangLuoyang", "About Face_Expreesion", wx.OK | wx.ICON_INFORMATION, self) def OnGenePic(self, evt): fileaddr1 = self.fbb1.GetValue() fileaddr2 = self.fbb2.GetValue() PREDICTOR_PATH = "C:\shape_predictor_68_face_landmarks.dat" SCALE_FACTOR = 1 FEATHER_AMOUNT = 11 FACE_POINTS = list(range(17, 68)) MOUTH_POINTS = list(range(48, 61)) RIGHT_BROW_POINTS = list(range(17, 22)) LEFT_BROW_POINTS = list(range(22, 27)) RIGHT_EYE_POINTS = list(range(36, 42)) LEFT_EYE_POINTS = list(range(42, 48)) NOSE_POINTS = list(range(27, 35)) JAW_POINTS = list(range(0, 17)) # Points used to line up the images. ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS + RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS) # Points from the second image to overlay on the first. The convex hull of each # element will be overlaid. OVERLAY_POINTS = [ LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS, NOSE_POINTS + MOUTH_POINTS, ] # Amount of blur to use during colour correction, as a fraction of the # pupillary distance. COLOUR_CORRECT_BLUR_FRAC = 0.6 detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(PREDICTOR_PATH) class TooManyFaces(Exception): pass class NoFaces(Exception): pass def get_landmarks(im): rects = detector(im, 1) if len(rects) > 1: raise TooManyFaces if len(rects) == 0: raise NoFaces return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()]) def annotate_landmarks(im, landmarks): im = im.copy() for idx, point in enumerate(landmarks): pos = (point[0, 0], point[0, 1]) cv2.putText(im, str(idx), pos, fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale=0.4, color=(0, 0, 255)) cv2.circle(im, pos, 3, color=(0, 255, 255)) return im def draw_convex_hull(im, points, color): points = cv2.convexHull(points) cv2.fillConvexPoly(im, points, color=color) def get_face_mask(im, landmarks): im = numpy.zeros(im.shape[:2], dtype=numpy.float64) for group in OVERLAY_POINTS: draw_convex_hull(im, landmarks[group], color=1) im = numpy.array([im, im, im]).transpose((1, 2, 0)) im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0 im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) return im def transformation_from_points(points1, points2): """ Return an affine transformation [s * R | T] such that: sum ||s*R*p1,i + T - p2,i||^2 is minimized. """ # Solve the procrustes problem by subtracting centroids, scaling by the # standard deviation, and then using the SVD to calculate the rotation. See # the following for more details: # https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem points1 = points1.astype(numpy.float64) points2 = points2.astype(numpy.float64) c1 = numpy.mean(points1, axis=0) c2 = numpy.mean(points2, axis=0) points1 -= c1 points2 -= c2 s1 = numpy.std(points1) s2 = numpy.std(points2) points1 /= s1 points2 /= s2 U, S, Vt = numpy.linalg.svd(points1.T * points2) # The R we seek is in fact the transpose of the one given by U * Vt. This # is because the above formulation assumes the matrix goes on the right # (with row vectors) where as our solution requires the matrix to be on the # left (with column vectors). R = (U * Vt).T return numpy.vstack([numpy.hstack(((s2 / s1) * R, c2.T - (s2 / s1) * R * c1.T)), numpy.matrix([0., 0., 1.])]) def read_im_and_landmarks(fname): im = cv2.imread(fname, cv2.IMREAD_COLOR) im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR, im.shape[0] * SCALE_FACTOR)) s = get_landmarks(im) return im, s def warp_im(im, M, dshape): output_im = numpy.zeros(dshape, dtype=im.dtype) cv2.warpAffine(im, M[:2], (dshape[1], dshape[0]), dst=output_im, borderMode=cv2.BORDER_TRANSPARENT, flags=cv2.WARP_INVERSE_MAP) return output_im def correct_colours(im1, im2, landmarks1): blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm( numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) - numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0)) blur_amount = int(blur_amount) if blur_amount % 2 == 0: blur_amount += 1 im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0) im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0) # Avoid divide-by-zero errors. im2_blur += (128 * (im2_blur <= 1.0)).astype(im2_blur.dtype) return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) / im2_blur.astype(numpy.float64)) im1, landmarks1 = read_im_and_landmarks(fileaddr1) im2, landmarks2 = read_im_and_landmarks(fileaddr2) M = transformation_from_points(landmarks1[ALIGN_POINTS], landmarks2[ALIGN_POINTS]) mask = get_face_mask(im2, landmarks2) warped_mask = warp_im(mask, M, im1.shape) combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask], axis=0) warped_im2 = warp_im(im2, M, im1.shape) warped_corrected_im2 = correct_colours(im1, warped_im2, landmarks1) output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask cv2.imwrite('output.jpg', output_im) # self.sound = wx.Sound(filename) # if self.sound.IsOk(): # self.sound.Play(wx.SOUND_ASYNC) # else: # wx.MessageBox("Invalid sound file", "Error") # Alerts after generating the pictures image = wx.Image("./output.jpg",wx.BITMAP_TYPE_JPEG) frame = Image(image) frame.Show() dlg = wx.MessageDialog(None, '图片生成完毕,开始风格迁移。未迁移前图片地址:"./output.jpg"', 'Succeed', wx.YES_NO | wx.ICON_QUESTION) result = dlg.ShowModal() dlg.Destroy() Style.main() image = wx.Image("./generated/res.jpg",wx.BITMAP_TYPE_JPEG) frame = Image(image) frame.Show()
class Settings(wx.Dialog): def __init__(self, parent, config): wx.Dialog.__init__(self, parent, -1, _('Settings'), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) # notebook self.notebook = wx.Notebook(self, -1) self.notebook_gammu = wx.Panel(self.notebook, -1) self.notebook_connection = wx.Panel(self.notebook, -1) self.notebook_messages = wx.Panel(self.notebook, -1) self.notebook_view = wx.Panel(self.notebook, -1) self.notebook_other = wx.Panel(self.notebook, -1) self.notebook_hacks = wx.Panel(self.notebook, -1) # main layout self.sizer = wx.lib.rcsizer.RowColSizer() self.sizer.AddGrowableCol(2) self.sizer.AddGrowableRow(1) self.sizer.AddSpacer(1, 1, pos=(0, 0)) self.sizer.AddSpacer(1, 1, pos=(0, 4)) self.sizer.Add(self.notebook, pos=(1, 1), colspan=3, flag=wx.EXPAND) self.sizer.Add(wx.StaticLine(self, -1), pos=(2, 1), colspan=3, flag=wx.EXPAND) self.button_sizer = wx.StdDialogButtonSizer() self.button_sizer.AddButton(wx.Button(self, wx.ID_OK)) self.button_sizer.AddButton(wx.Button(self, wx.ID_CANCEL)) self.button_sizer.Realize() self.sizer.Add(self.button_sizer, pos=(3, 1), colspan=3, flag=wx.ALIGN_RIGHT) self.sizer.AddSpacer(1, 1, pos=(4, 0), colspan=5) self.config = config self.gammu_config = config.gammu # gammu tab self.sizer_gammu = wx.lib.rcsizer.RowColSizer() self.sizer_gammu.AddGrowableCol(1) self.sizer_gammu.AddSpacer(1, 1, pos=(0, 0)) r = 1 self.editcfgpath = FileBrowseButton( self.notebook_gammu, size=(250, -1), labelText='', initialValue=config.Read('/Gammu/Gammurc', False), toolTip= _('Please enter here path to gammu configuration file you want to use.' ), changeCallback=self.OnConfigChange, fileMode=wx.OPEN) self.sizer_gammu.Add(wx.StaticText(self.notebook_gammu, -1, _('Gammurc path')), pos=(r, 1), flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_gammu.Add(self.editcfgpath, pos=(r, 2), flag=wx.EXPAND) r += 1 self.sizer_gammu.Add(wx.StaticText( self.notebook_gammu, -1, _('You can configure connection parameters on Connection tab.')), pos=(r, 1), colspan=2) r += 1 self.sizer_gammu.AddSpacer(1, 1, pos=(r, 3)) r += 1 self.editauto = wx.CheckBox( self.notebook_gammu, -1, _('Automatically connect to phone on startup')) self.editauto.SetToolTipString( _('Whether you want application automatically connect to phone when it is started.' )) self.editauto.SetValue(config.Read('/Wammu/AutoConnect') == 'yes') self.sizer_gammu.Add(self.editauto, pos=(r, 1), colspan=2) r += 1 self.editdebug = wx.CheckBox(self.notebook_gammu, -1, _('Show debug log')) self.editdebug.SetToolTipString( _('Show debug information on error output.')) self.editdebug.SetValue(config.Read('/Debug/Show') == 'yes') self.sizer_gammu.Add(self.editdebug, pos=(r, 1), colspan=2) r += 1 self.editsync = wx.CheckBox(self.notebook_gammu, -1, _('Synchronize time')) self.editsync.SetToolTipString( _('Synchronise time in phone with computer time while connecting.') ) self.editsync.SetValue(config.ReadBool('/Gammu/SyncTime')) self.sizer_gammu.Add(self.editsync, pos=(r, 1), colspan=2) r += 1 self.editinfo = wx.CheckBox(self.notebook_gammu, -1, _('Startup information')) self.editinfo.SetToolTipString( _('Display startup on phone (not supported by all models).')) self.editinfo.SetValue(config.ReadBool('/Gammu/StartInfo')) self.sizer_gammu.Add(self.editinfo, pos=(r, 1), colspan=2) r += 1 if sys.platform != 'win32': # locking not available on windoze self.editlock = wx.CheckBox(self.notebook_gammu, -1, _('Lock device')) self.editlock.SetToolTipString( _('Whether to lock device in /var/lock. On some systems you might lack privileges to do so.' )) self.editlock.SetValue(config.ReadBool('/Gammu/LockDevice')) self.sizer_gammu.Add(self.editlock, pos=(r, 1), colspan=2) r += 1 self.sizer_gammu.AddSpacer(1, 1, pos=(r, 3)) # size gammu tab self.notebook_gammu.SetAutoLayout(True) self.notebook_gammu.SetSizer(self.sizer_gammu) self.sizer_gammu.Fit(self.notebook_gammu) self.sizer_gammu.SetSizeHints(self.notebook_gammu) # connection tab self.sizer_connection = wx.lib.rcsizer.RowColSizer() self.sizer_connection.AddGrowableCol(1) self.sizer_connection.AddSpacer(1, 1, pos=(0, 0)) r = 1 lst, choices = config.gammu.GetConfigList() self.editsection = wx.Choice(self.notebook_connection, choices=choices, size=(250, -1)) section = config.ReadInt('/Gammu/Section') for i in range(len(lst)): if lst[i]['Id'] == section: self.editsection.SetSelection(i) break self.sizer_connection.Add(wx.StaticText(self.notebook_connection, -1, _('Phone connection')), pos=(r, 1), rowspan=2, flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_connection.Add(self.editsection, pos=(r, 2)) self.Bind(wx.EVT_CHOICE, self.OnConnectionChange, self.editsection) r += 1 self.addsection = wx.Button(self.notebook_connection, wx.ID_ADD) self.sizer_connection.Add(self.addsection, pos=(r, 2), flag=wx.EXPAND) r += 1 self.sizer_connection.AddSpacer(1, 1, pos=(r, 3)) r += 1 self.editname = wx.TextCtrl(self.notebook_connection, -1, '', size=(250, -1)) self.editname.SetToolTipString(_('Name for this configuration.')) self.sizer_connection.Add(wx.StaticText(self.notebook_connection, -1, _('Name')), pos=(r, 1), flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_connection.Add(self.editname, pos=(r, 2)) r += 1 self.editdev = wx.ComboBox(self.notebook_connection, -1, '', choices=Wammu.Data.Devices, size=(150, -1)) self.editdev.SetToolTipString( _('Device, where your phone is connected.')) self.sizer_connection.Add(wx.StaticText(self.notebook_connection, -1, _('Device')), pos=(r, 1), flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_connection.Add(self.editdev, pos=(r, 2), flag=wx.ALIGN_RIGHT | wx.EXPAND) r += 1 self.editconn = wx.ComboBox(self.notebook_connection, -1, '', choices=Wammu.Data.Connections, size=(150, -1)) self.editconn.SetToolTipString( _('Connection which your phone understands, check Gammu documentation for connection details.' )) self.sizer_connection.Add(wx.StaticText(self.notebook_connection, -1, _('Connection')), pos=(r, 1), flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_connection.Add(self.editconn, pos=(r, 2), flag=wx.ALIGN_RIGHT | wx.EXPAND) r += 1 self.editmodel = wx.ComboBox(self.notebook_connection, -1, '', choices=Wammu.Data.Models, size=(150, -1)) self.editmodel.SetToolTipString( _('Phone model, you can usually keep here auto unless you have any problems.' )) if self.editmodel.GetValue() == '': self.editmodel.SetValue('auto') self.sizer_connection.Add(wx.StaticText(self.notebook_connection, -1, _('Model')), pos=(r, 1), flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_connection.Add(self.editmodel, pos=(r, 2), flag=wx.ALIGN_RIGHT | wx.EXPAND) r += 1 # Initialise above fields self.OnConnectionChange() self.sizer_connection.AddSpacer(1, 1, pos=(r, 3)) # size connection tab self.notebook_connection.SetAutoLayout(True) self.notebook_connection.SetSizer(self.sizer_connection) self.sizer_connection.Fit(self.notebook_connection) self.sizer_connection.SetSizeHints(self.notebook_connection) # messages tab self.sizer_messages = wx.lib.rcsizer.RowColSizer() self.sizer_messages.AddGrowableCol(1) self.sizer_messages.AddSpacer(1, 1, pos=(0, 0)) r = 1 v = config.ReadInt('/Message/ScaleImage') self.editscale = wx.SpinCtrl(self.notebook_messages, -1, str(v), style=wx.SP_WRAP | wx.SP_ARROW_KEYS, min=1, max=20, initial=v, size=(150, -1)) self.editscale.SetToolTipString( _('Whether images in messages should be scaled when displayed. This is usually good idea as they are pretty small.' )) self.sizer_messages.Add(wx.StaticText(self.notebook_messages, -1, _('Scale images')), pos=(r, 1)) self.sizer_messages.Add(self.editscale, pos=(r, 2)) r += 1 self.editformat = wx.CheckBox(self.notebook_messages, -1, _('Attempt to reformat text')) self.editformat.SetToolTipString( _('If you get sometimes "compressed" messages likeTHIStext, you should be interested in this choice.' )) self.editformat.SetValue(config.Read('/Message/Format') == 'yes') self.sizer_messages.Add(self.editformat, pos=(r, 1), colspan=2) r += 1 # options for new message self.new_message_panel = wx.Panel(self.notebook_messages, -1) self.sizer_messages.Add(self.new_message_panel, pos=(r, 1), colspan=2, flag=wx.EXPAND) r += 1 self.sizer_message_new = wx.StaticBoxSizer( wx.StaticBox(self.new_message_panel, -1, _('Default options for new message')), wx.HORIZONTAL) self.new_message_panel_2 = wx.Panel(self.new_message_panel, -1) self.sizer_message_new.Add(self.new_message_panel_2, 1, wx.EXPAND, 0) self.sizer_message_new_2 = wx.lib.rcsizer.RowColSizer() self.sizer_message_new_2.AddGrowableCol(1) r2 = 0 self.editconcat = wx.CheckBox(self.new_message_panel_2, -1, _('Concatenated')) self.editconcat.SetToolTipString( _('Create concatenated message, what allows to send longer messages.' )) self.editconcat.SetValue(config.Read('/Message/Concatenated') == 'yes') self.sizer_message_new_2.Add(self.editconcat, pos=(r2, 0), colspan=2) r2 += 1 self.editunicode = wx.CheckBox(self.new_message_panel_2, -1, _('Create unicode message')) self.editunicode.SetToolTipString( _('Unicode messages can contain national and other special characters, check this if you use non latin-1 characters. Your messages will require more space, so you can write less characters into single message.' )) self.editunicode.SetValue(config.Read('/Message/Unicode') == 'yes') self.sizer_message_new_2.Add(self.editunicode, pos=(r2, 0), colspan=2) r2 += 1 self.editreport = wx.CheckBox(self.new_message_panel_2, -1, _('Request delivery report by default')) self.editreport.SetToolTipString( _('Check to request delivery report for message.')) self.editreport.SetValue( config.Read('/Message/DeliveryReport') == 'yes') self.sizer_message_new_2.Add(self.editreport, pos=(r2, 0), colspan=2) r2 += 1 self.edit16bit = wx.CheckBox(self.new_message_panel_2, -1, _('Use 16bit Id')) self.edit16bit.SetToolTipString( _('Use 16 bit Id inside message. This is safe for most cases.')) self.edit16bit.SetValue(config.Read('/Message/16bitId') == 'yes') self.sizer_message_new_2.Add(self.edit16bit, pos=(r2, 0), colspan=2) r2 += 1 self.new_message_panel_2.SetAutoLayout(True) self.new_message_panel_2.SetSizer(self.sizer_message_new_2) self.sizer_message_new_2.Fit(self.new_message_panel_2) self.sizer_message_new_2.SetSizeHints(self.new_message_panel_2) self.new_message_panel.SetAutoLayout(True) self.new_message_panel.SetSizer(self.sizer_message_new) self.sizer_message_new.Fit(self.new_message_panel) self.sizer_message_new.SetSizeHints(self.new_message_panel) self.sizer_messages.AddSpacer(1, 1, pos=(r, 3)) # size messages tab self.notebook_messages.SetAutoLayout(True) self.notebook_messages.SetSizer(self.sizer_messages) self.sizer_messages.Fit(self.notebook_messages) self.sizer_messages.SetSizeHints(self.notebook_messages) # view tab self.sizer_view = wx.lib.rcsizer.RowColSizer() self.sizer_view.AddGrowableCol(1) self.sizer_view.AddSpacer(1, 1, pos=(0, 0)) r = 1 v = config.Read('/Wammu/NameFormat') self.editnameformat = wx.Choice( self.notebook_view, choices=[ _('Automatic'), _('Automatic starting with first name'), _('Automatic starting with last name'), _('Custom, use format string below') ], size=(250, -1)) if v == 'auto': self.editnameformat.SetSelection(0) elif v == 'auto-first-last': self.editnameformat.SetSelection(1) elif v == 'auto-last-first': self.editnameformat.SetSelection(2) elif v == 'custom': self.editnameformat.SetSelection(3) self.sizer_view.Add(wx.StaticText(self.notebook_view, -1, _('Name display format')), pos=(r, 1)) self.sizer_view.Add(self.editnameformat, pos=(r, 2), flag=wx.EXPAND) self.Bind(wx.EVT_CHOICE, self.OnNameFormatChange, self.editnameformat) r += 1 v = config.Read('/Wammu/NameFormatString') self.editnamestring = wx.ComboBox( self.notebook_view, -1, v, choices=[ v, '%(FirstName)s %(LastName)s (%(Company)s)', '%(LastName)s, %(FirstName)s (%(Company)s)', '%(LastName)s, %(FirstName)s (%(NickName)s)', ]) # l10n: The %s will be replaced by list of currently supported tags, %%(value)s should be kept intact (you can translate word value). self.editnamestring.SetToolTipString( _('Format string for name displaying. You can use %%(value)s format marks. Currently available values are: %s.' ) % 'Name, FirstName, LastName, NickName, FormalName, Company') self.sizer_view.Add(wx.StaticText(self.notebook_view, -1, _('Name format string')), pos=(r, 1), flag=wx.ALIGN_CENTER_VERTICAL) self.sizer_view.Add(self.editnamestring, pos=(r, 2), flag=wx.ALIGN_RIGHT | wx.EXPAND) r += 1 self.sizer_view.AddSpacer(1, 1, pos=(r, 3)) # size view tab self.notebook_view.SetAutoLayout(True) self.notebook_view.SetSizer(self.sizer_view) self.sizer_view.Fit(self.notebook_view) self.sizer_view.SetSizeHints(self.notebook_view) # other tab self.sizer_other = wx.lib.rcsizer.RowColSizer() self.sizer_other.AddGrowableCol(1) self.sizer_other.AddSpacer(1, 1, pos=(0, 0)) r = 1 v = config.ReadInt('/Wammu/RefreshState') self.editrefresh = wx.SpinCtrl(self.notebook_other, -1, str(v), style=wx.SP_WRAP | wx.SP_ARROW_KEYS, min=0, max=10000000, initial=v, size=(150, -1)) self.editrefresh.SetToolTipString( _('How often refresh phone state in application status bar. Enter value in miliseconds, 0 to disable.' )) self.sizer_other.Add(wx.StaticText(self.notebook_other, -1, _('Refresh phone state')), pos=(r, 1)) self.sizer_other.Add(self.editrefresh, pos=(r, 2)) r += 1 self.editconfirm = wx.CheckBox(self.notebook_other, -1, _('Confirm deleting')) self.editconfirm.SetToolTipString( _('Whether to ask for confirmation when deleting entries.')) self.editconfirm.SetValue(config.Read('/Wammu/ConfirmDelete') == 'yes') self.sizer_other.Add(self.editconfirm, pos=(r, 1), colspan=2) r += 1 self.taskbaricon = wx.CheckBox(self.notebook_other, -1, _('Task bar icon')) self.taskbaricon.SetToolTipString(_('Show icon in task bar.')) self.taskbaricon.SetValue(config.Read('/Wammu/TaskBarIcon') == 'yes') self.sizer_other.Add(self.taskbaricon, pos=(r, 1), colspan=2) r += 1 dtime = config.Read('/Wammu/DefaultTime') try: times = dtime.split(':') th = int(times[0]) tm = int(times[1]) ts = int(times[2]) except: th = 9 tm = 0 ts = 0 self.edittime = TimeCtrl(self.notebook_other, -1, fmt24hr=True) Wammu.Utils.FixupMaskedEdit(self.edittime) self.edittime.SetValue(wx.DateTimeFromHMS(th, tm, ts)) self.edittime.SetToolTipString( _('Default time to be used for newly created time fields.')) self.sizer_other.Add(wx.StaticText(self.notebook_other, -1, _('Default time')), pos=(r, 1)) self.sizer_other.Add(self.edittime, pos=(r, 2)) r += 1 v = config.ReadInt('/Wammu/DefaultDateOffset') self.editdate = wx.SpinCtrl(self.notebook_other, -1, str(v), style=wx.SP_WRAP | wx.SP_ARROW_KEYS, min=-10000000, max=10000000, initial=v, size=(150, -1)) self.editdate.SetToolTipString( _('Default date to be used for newly created time fields. Enter amount of days from today (1=tomorrow).' )) self.sizer_other.Add(wx.StaticText(self.notebook_other, -1, _('Default date=now + x days')), pos=(r, 1)) self.sizer_other.Add(self.editdate, pos=(r, 2)) r += 1 v = config.ReadInt('/Wammu/DefaultEntries') self.editentries = wx.SpinCtrl(self.notebook_other, -1, str(v), style=wx.SP_WRAP | wx.SP_ARROW_KEYS, min=0, max=20, initial=v, size=(150, -1)) self.editentries.SetToolTipString( _('How many entries will be shown in newly created item.')) self.sizer_other.Add(wx.StaticText(self.notebook_other, -1, _('Entries for new item')), pos=(r, 1)) self.sizer_other.Add(self.editentries, pos=(r, 2)) r += 1 lst = ['Auto'] lst += Wammu.Data.InternationalPrefixes self.editprefix = wx.ComboBox(self.notebook_other, -1, config.Read('/Wammu/PhonePrefix'), choices=lst, size=(150, -1)) self.editprefix.SetToolTipString( _('Prefix for non international phone numbers.')) self.sizer_other.Add(wx.StaticText(self.notebook_other, -1, _('Number prefix')), pos=(r, 1)) self.sizer_other.Add(self.editprefix, pos=(r, 2)) r += 1 self.sizer_other.AddSpacer(1, 1, pos=(r, 3)) # size other tab self.notebook_other.SetAutoLayout(True) self.notebook_other.SetSizer(self.sizer_other) self.sizer_other.Fit(self.notebook_other) self.sizer_other.SetSizeHints(self.notebook_other) # hacks tab self.sizer_hacks = wx.lib.rcsizer.RowColSizer() self.sizer_hacks.AddGrowableCol(1) self.sizer_hacks.AddSpacer(1, 1, pos=(0, 0)) r = 1 v = config.ReadInt('/Hacks/MaxEmptyGuess') self.editmaxemptyguess = wx.SpinCtrl(self.notebook_hacks, -1, str(v), style=wx.SP_WRAP | wx.SP_ARROW_KEYS, min=0, max=10000000, initial=v, size=(150, -1)) self.editmaxemptyguess.SetToolTipString( _('Applies only when Wammu can not find proper count of entries to read. This number limits how many empty entries will be read before reading will be stopped.' )) self.sizer_hacks.Add(wx.StaticText( self.notebook_hacks, -1, _('Maximal empty entries if total is guessed')), pos=(r, 1)) self.sizer_hacks.Add(self.editmaxemptyguess, pos=(r, 2)) r += 1 v = config.ReadInt('/Hacks/MaxEmptyKnown') self.editmaxemptyknown = wx.SpinCtrl(self.notebook_hacks, -1, str(v), style=wx.SP_WRAP | wx.SP_ARROW_KEYS, min=0, max=10000000, initial=v, size=(150, -1)) self.editmaxemptyknown.SetToolTipString( _('In case phone reports wrongly number of entries, Wammu would try to read infinitely or till error. This number limits how many empty entries will be read before reading will be stopped.' )) self.sizer_hacks.Add(wx.StaticText( self.notebook_hacks, -1, _('Maximal empty entries if total is known')), pos=(r, 1)) self.sizer_hacks.Add(self.editmaxemptyknown, pos=(r, 2)) r += 1 self.sizer_hacks.AddSpacer(1, 1, pos=(r, 3)) # size hacks tab self.notebook_hacks.SetAutoLayout(True) self.notebook_hacks.SetSizer(self.sizer_hacks) self.sizer_hacks.Fit(self.notebook_hacks) self.sizer_hacks.SetSizeHints(self.notebook_hacks) # add pages to notebook self.notebook.AddPage(self.notebook_gammu, _('Gammu')) self.notebook.AddPage(self.notebook_connection, _('Connection')) self.notebook.AddPage(self.notebook_messages, _('Messages')) self.notebook.AddPage(self.notebook_view, _('View')) self.notebook.AddPage(self.notebook_other, _('Other')) self.notebook.AddPage(self.notebook_hacks, _('Hacks')) # size main layout self.SetAutoLayout(True) self.SetSizer(self.sizer) self.sizer.Fit(self) self.sizer.SetSizeHints(self) # workaround, when sizers don't set correct size sz = self.GetSize() if sz.y < 150: self.SetSize((400, 400)) # Intialise fields self.OnNameFormatChange() # event handlers self.Bind(wx.EVT_BUTTON, self.Okay, id=wx.ID_OK) self.Bind(wx.EVT_BUTTON, self.AddPhone, id=wx.ID_ADD) def OnNameFormatChange(self, evt=None): selection = self.editnameformat.GetSelection() if selection < 0: selection = 0 if selection == 3: self.editnamestring.Enable(True) else: self.editnamestring.Enable(False) def OnConnectionChange(self, evt=None): selection = self.editsection.GetSelection() if selection < 0: selection = 0 lst, choices = self.gammu_config.GetConfigList() if len(lst) == 0: self.editdev.Enable(False) self.editmodel.Enable(False) self.editname.Enable(False) self.editconn.Enable(False) return self.editdev.Enable(True) self.editmodel.Enable(True) self.editname.Enable(True) self.editconn.Enable(True) current = lst[selection] gammu = self.gammu_config.GetConfig(current['Id']) self.editdev.SetValue(gammu['Device']) self.editmodel.SetValue(gammu['Model']) self.editname.SetValue(gammu['Name']) self.editconn.SetValue(gammu['Connection']) def OnConfigChange(self, evt=None): # temporarily change gammu config data newpath = self.editcfgpath.GetValue() self.gammu_config = Wammu.GammuSettings.GammuSettings( self.config, os.path.expanduser(newpath.encode('utf-8'))) self.RereadConfig() def RereadConfig(self): lst, choices = self.gammu_config.GetConfigList() self.editsection.Clear() for x in choices: self.editsection.Append(x) if len(choices) > 0: self.editsection.SetSelection(0) self.OnConnectionChange() def AddPhone(self, evt=None): index = self.gammu_config.FirstFree() result = Wammu.PhoneWizard.RunConfigureWizard(self, index) if result is not None: self.gammu_config.SetConfig(result['Position'], result['Device'], result['Connection'], result['Name']) self.RereadConfig() lst, choices = self.gammu_config.GetConfigList() self.editsection.SetSelection(len(lst) - 1) self.OnConnectionChange() def Okay(self, evt): lst, choices = self.config.gammu.GetConfigList() # Check whether we have some configuration if len(lst) == 0: wx.MessageDialog( self, _('You don\'t have any phone connection configured. Wammu will not be able to conect to your phone!' ), _('No phone configured!'), wx.OK | wx.ICON_ERROR).ShowModal() else: current = lst[self.editsection.GetSelection()] self.config.gammu = self.gammu_config self.config.gammu.SetConfig(current['Id'], self.editdev.GetValue(), self.editconn.GetValue(), self.editname.GetValue(), self.editmodel.GetValue()) self.config.Write('/Gammu/Gammurc', self.editcfgpath.GetValue()) self.config.WriteInt('/Gammu/Section', current['Id']) self.config.WriteBool('/Gammu/SyncTime', self.editsync.GetValue()) if sys.platform != 'win32': self.config.WriteBool('/Gammu/LockDevice', self.editlock.GetValue()) self.config.WriteBool('/Gammu/StartInfo', self.editinfo.GetValue()) if self.editdebug.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Debug/Show', value) if self.editauto.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Wammu/AutoConnect', value) if self.editformat.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Message/Format', value) if self.editconcat.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Message/Concatenated', value) if self.editunicode.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Message/Unicode', value) if self.editreport.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Message/DeliveryReport', value) if self.edit16bit.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Message/16bitId', value) self.config.WriteInt('/Message/ScaleImage', self.editscale.GetValue()) self.config.WriteInt('/Wammu/RefreshState', self.editrefresh.GetValue()) if self.editconfirm.GetValue(): value = 'yes' else: value = 'no' self.config.Write('Wammu/ConfirmDelete', value) if self.taskbaricon.GetValue(): value = 'yes' else: value = 'no' self.config.Write('/Wammu/TaskBarIcon', value) self.config.Write('Wammu/DefaultTime', self.edittime.GetValue()) self.config.WriteInt('/Wammu/DefaultDateOffset', self.editdate.GetValue()) self.config.WriteInt('/Wammu/DefaultEntries', self.editentries.GetValue()) self.config.Write('/Wammu/PhonePrefix', self.editprefix.GetValue()) self.config.Write('/Wammu/NameFormat', self.editnamestring.GetValue()) ind = self.editnameformat.GetSelection() if ind == 0: val = 'auto' elif ind == 1: val = 'auto-first-last' elif ind == 2: val = 'auto-last-first' elif ind == 3: val = 'custom' else: raise Exception('Invalid NameFormatString id: %d' % ind) self.config.Write('/Wammu/NameFormat', val) self.config.WriteInt('/Hacks/MaxEmptyGuess', self.editmaxemptyguess.GetValue()) self.config.WriteInt('/Hacks/MaxEmptyKnown', self.editmaxemptyknown.GetValue()) self.EndModal(wx.ID_OK)
class panelConfigure(wx.Panel): """ """ def __init__(self, parent): """ """ wx.Panel.__init__(self, parent, wx.ID_ANY, size=(-1, 300), style=wx.SUNKEN_BORDER | wx.TAB_TRAVERSAL) self.parent = parent self.thumbnail = None self.mask_file = None self.source = None self.sourceType = None self.track = None self.trackType = None lowerSizer = wx.BoxSizer(wx.HORIZONTAL) #Static box1 (LEFT) sb_1 = wx.StaticBox(self, -1, "Select Monitor") #, size=(250,-1)) sbSizer_1 = wx.StaticBoxSizer(sb_1, wx.VERTICAL) n_monitors = options.GetOption("Monitors") self.MonitorList = [ 'Monitor %s' % (int(m) + 1) for m in range(n_monitors) ] self.thumbnailNumber = wx.ComboBox(self, -1, size=(-1, -1), choices=self.MonitorList, style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT) self.Bind(wx.EVT_COMBOBOX, self.onChangingMonitor, self.thumbnailNumber) self.currentSource = wx.TextCtrl(self, -1, "No Source Selected", style=wx.TE_READONLY) btnSizer_1 = wx.BoxSizer(wx.HORIZONTAL) self.btnPlay = wx.Button(self, wx.ID_FORWARD, label="Play") self.btnStop = wx.Button(self, wx.ID_STOP, label="Stop") self.Bind(wx.EVT_BUTTON, self.onPlay, self.btnPlay) self.Bind(wx.EVT_BUTTON, self.onStop, self.btnStop) self.btnPlay.Enable(False) self.btnStop.Enable(False) self.applyButton = wx.Button(self, wx.ID_APPLY) self.applyButton.SetToolTip(wx.ToolTip("Apply and Save to file")) self.Bind(wx.EVT_BUTTON, self.onApplySource, self.applyButton) btnSizer_1.Add(self.btnPlay, 0, wx.ALIGN_LEFT | wx.ALL, 5) btnSizer_1.Add(self.btnStop, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.DOWN, 5) btnSizer_1.Add(self.applyButton, 0, wx.ALIGN_RIGHT | wx.LEFT | wx.RIGHT | wx.TOP, 5) sbSizer_1.Add(self.thumbnailNumber, 0, wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT | wx.TOP, 5) sbSizer_1.Add( self.currentSource, 0, wx.EXPAND | wx.ALIGN_CENTRE | wx.LEFT | wx.RIGHT | wx.TOP, 5) sbSizer_1.Add(btnSizer_1, 0, wx.EXPAND | wx.ALIGN_BOTTOM | wx.TOP, 5) lowerSizer.Add(sbSizer_1, 0, wx.EXPAND | wx.ALL, 5) #Static box2 (CENTER) sb_2 = wx.StaticBox(self, -1, "Select Video input") sbSizer_2 = wx.StaticBoxSizer(sb_2, wx.VERTICAL) grid2 = wx.FlexGridSizer(0, 2, 0, 0) n_cams = options.GetOption("Webcams") self.WebcamsList = ['Webcam %s' % (int(w) + 1) for w in range(n_cams)] rb1 = wx.RadioButton(self, -1, 'Camera', style=wx.RB_GROUP) source1 = wx.ComboBox(self, -1, size=(285, -1), choices=self.WebcamsList, style=wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT) self.Bind(wx.EVT_COMBOBOX, self.sourceCallback, source1) rb2 = wx.RadioButton(self, -1, 'File') source2 = FileBrowseButton(self, -1, labelText='', size=(300, -1), changeCallback=self.sourceCallback) rb3 = wx.RadioButton(self, -1, 'Folder') source3 = DirBrowseButton(self, style=wx.DD_DIR_MUST_EXIST, labelText='', size=(300, -1), changeCallback=self.sourceCallback) self.controls = [] self.controls.append((rb1, source1)) self.controls.append((rb2, source2)) self.controls.append((rb3, source3)) for radio, source in self.controls: grid2.Add(radio, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2) grid2.Add(source, 0, wx.ALIGN_CENTRE | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 2) self.Bind(wx.EVT_RADIOBUTTON, self.onChangeSource, radio) source.Enable(False) self.controls[0][1].Enable(True) #grid2.Add(wx.StaticText(self, -1, "")) sbSizer_2.Add(grid2) lowerSizer.Add(sbSizer_2, 0, wx.EXPAND | wx.ALL, 5) #Static box3 (RIGHT) sb_3 = wx.StaticBox(self, -1, "Set Tracking Parameters") sbSizer_3 = wx.StaticBoxSizer(sb_3, wx.VERTICAL) sbSizer_31 = wx.BoxSizer(wx.HORIZONTAL) self.activateTracking = wx.CheckBox(self, -1, "Activate Tracking") self.activateTracking.SetValue(False) self.activateTracking.Bind(wx.EVT_CHECKBOX, self.onActivateTracking) self.isSDMonitor = wx.CheckBox(self, -1, "Sleep Deprivation Monitor") self.isSDMonitor.SetValue(False) self.isSDMonitor.Bind(wx.EVT_CHECKBOX, self.onSDMonitor) self.isSDMonitor.Enable(False) sbSizer_31.Add(self.activateTracking, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5) sbSizer_31.Add(self.isSDMonitor, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5) self.pickMaskBrowser = FileBrowseButton(self, -1, labelText='Mask File') #sbSizer_3.Add ( self.activateTracking , 0, wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 ) sbSizer_3.Add(sbSizer_31, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5) sbSizer_3.Add(self.pickMaskBrowser, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND, 5) #trackingTypeSizer = wx.Sizer(wx.HORIZONTAL) self.trackDistanceRadio = wx.RadioButton( self, -1, "Activity as distance traveled", style=wx.RB_GROUP) self.trackVirtualBM = wx.RadioButton( self, -1, "Activity as midline crossings count") self.trackPosition = wx.RadioButton(self, -1, "Only position of flies") sbSizer_3.Add(wx.StaticText(self, -1, "Calculate fly activity as..."), 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 5) sbSizer_3.Add(self.trackDistanceRadio, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 2) sbSizer_3.Add(self.trackVirtualBM, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 2) sbSizer_3.Add(self.trackPosition, 0, wx.ALIGN_LEFT | wx.LEFT | wx.RIGHT | wx.TOP, 2) lowerSizer.Add(sbSizer_3, -1, wx.EXPAND | wx.ALL, 5) self.SetSizer(lowerSizer) self.Bind(EVT_THUMBNAIL_CLICKED, self.onThumbnailClicked) def __getSource(self): """ check which source is ticked and what is the associated value """ for (r, s), st in zip(self.controls, range(3)): if r.GetValue(): source = s.GetValue() sourceType = st return source, sourceType def __getTrackingType(self): """ return which tracking we are chosing ['DISTANCE','VBS','XY_COORDS'] """ if self.trackDistanceRadio.GetValue(): trackType = "DISTANCE" elif self.trackVirtualBM.GetValue(): trackType = "VBS" elif self.trackPosition.GetValue(): trackType = "XY_COORDS" return trackType def onPlay(self, event=None): """ """ if self.thumbnail: self.thumbnail.Play() self.btnStop.Enable(True) def onStop(self, event=None): """ """ if self.thumbnail and self.thumbnail.isPlaying: self.thumbnail.Stop() self.btnStop.Enable(False) def onThumbnailClicked(self, evt): """ Picking thumbnail by clicking on it """ self.monitor_number = evt.number + 1 self.thumbnail = evt.thumbnail self.thumbnailNumber.SetValue(self.MonitorList[self.monitor_number - 1]) self.updateThumbnail() def onChangingMonitor(self, evt): """ Picking thumbnail by using the dropbox """ sel = evt.GetString() self.monitor_number = self.MonitorList.index(sel) + 1 self.thumbnail = self.parent.scrollThumbnails.previewPanels[ self.monitor_number] #this is not very elegant self.updateThumbnail() def updateThumbnail(self): """ Refreshing thumbnail data """ if options.HasMonitor(self.monitor_number): sourceType, source, track, mask_file, trackType, isSDMonitor = options.GetMonitor( self.monitor_number) else: sourceType, source, track, mask_file, trackType, isSDMonitor = [ 0, '', False, '', 1, False ] if sourceType == 0 and source != '': source = self.WebcamsList[source] self.source = self.thumbnail.source = source self.sourceType = self.thumbnail.sourceType = sourceType self.thumbnail.track = track if self.thumbnail.hasMonitor(): self.thumbnail.mon.isSDMonitor = isSDMonitor #update first static box active = self.thumbnail.hasMonitor() self.applyButton.Enable(active) self.btnPlay.Enable(active) self.btnStop.Enable(active and self.thumbnail.isPlaying) text = os.path.split(str(self.source))[1] or "No Source Selected" self.currentSource.SetValue(text) #update second static box for radio, src in self.controls: src.Enable(False) src.SetValue('') radio, src = self.controls[self.sourceType] radio.SetValue(True) src.Enable(True) src.SetValue(self.source) #update third static box self.activateTracking.SetValue(self.thumbnail.track) self.isSDMonitor.SetValue(isSDMonitor) self.pickMaskBrowser.SetValue(mask_file or '') [self.trackDistanceRadio, self.trackVirtualBM, self.trackPosition][trackType].SetValue(True) def sourceCallback(self, event): """ """ self.applyButton.Enable(True) def onChangeSource(self, event): """ """ radio_selected = event.GetEventObject() for radio, source in self.controls: if radio is radio_selected: source.Enable(True) else: source.Enable(False) self.applyButton.Enable(True) def onApplySource(self, event): """ """ source, sourceType = self.__getSource() track = self.activateTracking.GetValue() self.mask_file = self.pickMaskBrowser.GetValue() self.trackType = self.__getTrackingType() if self.thumbnail: if sourceType > 0: camera = source else: camera = self.WebcamsList.index(source) self.thumbnail.source = camera self.thumbnail.sourceType = sourceType #Change the source text self.currentSource.SetValue(os.path.split(source)[1]) #Set thumbnail's source self.thumbnail.setMonitor(camera) #Enable buttons self.btnPlay.Enable(True) self.activateTracking.Enable(True) self.pickMaskBrowser.Enable(True) self.saveMonitorConfiguration() def saveMonitorConfiguration(self): """ """ options.SetMonitor(self.monitor_number, self.thumbnail.sourceType, self.thumbnail.source + 1, self.thumbnail.track, self.mask_file, self.trackType, self.thumbnail.mon.isSDMonitor) options.Save() def onActivateTracking(self, event): """ """ if self.thumbnail: self.thumbnail.track = event.IsChecked() def onSDMonitor(self, event): """ """ if self.thumbnail: self.thumbnail.mon.isSDMonitor = event.IsChecked()
class Create_new_acc_pro_or_file(wx.Frame): def __init__(self, is_create_file, client_actions): """ create a new acc project """ self.client_actions = client_actions self.is_create_file = is_create_file self.name_file = "" if is_create_file: name = "Name new File" else: name = "Name new Pro" wx.Frame.__init__(self, None, -1,name,size=(400,400)) self.p = wx.Panel(self, -1) wx.Button(self.p,label = "ADD", pos = (75, 80), size=(50,20), id = 1) self.p.Bind(wx.EVT_BUTTON, self.new_name_pro_file, id=1) is_pressed_on_file = True if is_create_file: is_pressed_on_file = False self.p = FileBrowseButton(self.p, id = 2, toolTip="Type fulename or click browse to choose file", dialogTitle="Choose a file", labelText="Select file:")#fileMask="*.file") #self.name_pro_or_file = wx.TextCtrl(self.p, value="", pos=(50, 25), size=(100,25)) #self.name_pro_or_file.SetMaxLength(20) # self.p.Bind(wx.BROWSER_NEW_WINDOW, ) self.Centre() def new_name_pro_file(self, event): if self.is_create_file: content = self.new_file_helper() dct_to_dend = {"NEW FILE": self.name_file, "CONTENT":content, "HEADERS": headers_files} else: dct_to_dend = {"NEW PROJECT": str(self.name_pro_or_file.Value), "HEADERS": headers_pros} editor = editor_data(dct_to_dend, False) self.client_actions.send(editor.data) recv = self.client_actions.recv() #the server will return : #"Confirm-User!\n\n\n..Edited-Name:\n\n\n...info of the pro\file: Acc_projects_or_files(self.client_actions, recv, self.is_create_file) self.Close() def new_file_helper(self): """ orginize propertly the info and the content of the new file """ path = str(self.p.GetValue()) content = "" with open(path, "rb") as file_text: content = file_text.read() path = path[::-1] lst_help = path.split("\\") self.name_file = lst_help[0][::-1] print "name file:", self.name_file return content def order_new_pro_or_file(self, recv): #the server will return : #"Confirm-User!\n\n\n..Edited-Name:\n\n\n...info of the pro\file: tpl = tuple(recv.split(division_line)) tpl = tpl[:len(tpl)-1] return tpl