コード例 #1
0
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())
コード例 #2
0
ファイル: sendfile.py プロジェクト: xuesong/mmc
 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)
コード例 #3
0
    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)
コード例 #4
0
ファイル: Graphics.py プロジェクト: adipeled158/ACC
        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()
コード例 #5
0
    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)
コード例 #6
0
 def __init__(self, parent, suggestion_source, label, controller, size=wx.DefaultSize):
     FileBrowseButton.__init__(self, parent, labelText=label,
         size=size, fileMask="*",
         changeCallback=self.OnFileChanged)
     self._parent = parent
     self._controller = controller
     self._browsed = False
     _ContentAssistTextCtrlBase.__init__(self, suggestion_source)
コード例 #7
0
ファイル: contentassist.py プロジェクト: MEDBEDb/RIDE
 def __init__(self, parent, suggestion_source, label, controller, size=wx.DefaultSize):
     FileBrowseButton.__init__(self, parent, labelText=label,
         size=size, fileMask="*",
         changeCallback=self.OnFileChanged)
     self._parent = parent
     self._controller = controller
     self._browsed = False
     _ContentAssistTextCtrlBase.__init__(self, suggestion_source)
コード例 #8
0
    def __init__(self, parent):
        debugprt(self, currentframe(), pgm, 'begin     ')  # 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')
        debugprt(self, currentframe(), pgm, 'end   ')  #
コード例 #9
0
 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
コード例 #10
0
ファイル: supplemental_prices.py プロジェクト: ontoral/candd
    def _init_ctrls(self, parent):
        self.DecYear = wx.Button(self, -1, '<<', size=(48, 36))
        self.DecYear.Bind(wx.EVT_BUTTON, self.OnDecYear)
        self.DecMonth = wx.Button(self, -1, ' < ', size=(48, 36))
        self.DecMonth.Bind(wx.EVT_BUTTON, self.OnDecMonth)
        self.Current = wx.Button(self, -1, 'Today')
        self.Current.Bind(wx.EVT_BUTTON, self.OnCurrent)
        self.IncMonth = wx.Button(self, -1, ' > ', size=(48, 36))
        self.IncMonth.Bind(wx.EVT_BUTTON, self.OnIncMonth)
        self.IncYear = wx.Button(self, -1, '>>', size=(48, 36))
        self.IncYear.Bind(wx.EVT_BUTTON, self.OnIncYear)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.Add(self.DecYear, 0, wx.ALL, 2)
        bsizer.Add(self.DecMonth, 0, wx.ALL, 2)
        bsizer.Add(self.Current, 1, wx.ALL | wx.EXPAND, 2)
        bsizer.Add(self.IncMonth, 0, wx.ALL, 2)
        bsizer.Add(self.IncYear, 0, wx.ALL, 2)

        self.Calendar = Calendar(self, -1, size=(200, 300))
        self.Calendar.Bind(wx.lib.calendar.EVT_CALENDAR, self.OnCalendarChange)
        self.Calendar.SetCurrentDay()
        self.Calendar.grid_color = 'BLUE'
        self.Calendar.SetBusType()

        self.FBB = FileBrowseButton(self,
                                    size=(450, -1),
                                    changeCallback=self.OnFBBChange)
        self.FBB.SetLabel('Symbols File:')

        self.DBB = DirBrowseButton(self,
                                   size=(450, -1),
                                   changeCallback=self.OnDBBChange)
        self.DBB.SetLabel('Prices Folder:')

        self.ListBox = gizmos.EditableListBox(
            self,
            -1,
            #              style=gizmos.EL_DEFAULT_STYLE | gizmos.EL_NO_REORDER
        )
        self.ListBox.GetUpButton().Show(False)
        self.ListBox.GetDownButton().Show(False)
        self.ListBox.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnSymbolListChange)
        self.ListBox.Bind(wx.EVT_LIST_INSERT_ITEM, self.OnSymbolListChange)

        self.Download = wx.Button(self, wx.OK, 'Download Prices')
        self.Download.Bind(wx.EVT_BUTTON, self.OnDownload)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.AddSizer(bsizer, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        sizer.AddWindow(self.Calendar, 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
        sizer.AddWindow(self.FBB, 0, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.DBB, 0, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.ListBox, 1, wx.ALL | wx.EXPAND, 5)
        sizer.AddWindow(self.Download, 0, wx.ALL | wx.ALIGN_RIGHT, 5)
        self.SetSizer(sizer)
コード例 #11
0
ファイル: runprofiles.py プロジェクト: charles20cent/RIDE
    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
コード例 #12
0
ファイル: GUIBuilder.py プロジェクト: scijava/bioimagexd
    def createFileSelection(self, n, items, currentFilter, save=0):
        """
		create a file selection GUI element that shows the filename and has a button to select a file
		"""
        itemName = items[n][0]

        box = wx.BoxSizer(wx.VERTICAL)
        text = currentFilter.getDesc(itemName)
        defValue = currentFilter.getDefaultValue(itemName)
        ftype = defValue.split(".")[-1]
        conf = Configuration.getConfiguration()
        remember = conf.getConfigItem("RememberPath", "Paths")
        lastPath = ""
        if remember:
            lastPath = conf.getConfigItem("LastPath_%s" % ftype, "Paths")
            if not lastPath:
                lastPath = "."

        updateFilenameFunc = lambda event, its = items[n], f = currentFilter, i = itemName, \
            s = self: s.onSetFileName(f, i, event)

        if save:
            filemode = wx.SAVE
        else:
            filemode = wx.OPEN

        browse = FileBrowseButton(self,
                                  -1,
                                  size=(400, -1),
                                  labelText=text,
                                  fileMask=items[n][2],
                                  dialogTitle=items[n][1],
                                  startDirectory=lastPath,
                                  changeCallback=updateFilenameFunc,
                                  fileMode=filemode)
        browse.SetValue(defValue)

        setFilenameFunc = lambda obj, event, arg, b = browse, i = itemName, s = self: \
               s.onSetFileNameFromFilter(b, i, arg)
        lib.messenger.connect(currentFilter, "set_%s" % itemName,
                              setFilenameFunc)

        longDesc = currentFilter.getLongDesc(itemName)
        if longDesc:
            browse.SetToolTip(wx.ToolTip(s))

        box.Add(browse, 1)
        self.itemSizer.Add(box, (self.currentRow, 0),
                           flag=wx.EXPAND | wx.HORIZONTAL)
        self.items[itemName] = box

        return 1
コード例 #13
0
ファイル: contentassist.py プロジェクト: charles20cent/RIDE
 def __init__(self, parent, suggestion_source, label, controller,
              size=wx.DefaultSize):
     FileBrowseButton.__init__(self, parent, labelText=label,
                               size=size, fileMask="*",
                               changeCallback=self.OnFileChanged)
     self._parent = parent
     self._controller = controller
     self._browsed = False
     _ContentAssistTextCtrlBase.__init__(self, suggestion_source)
     self.SetBackgroundColour(Colour(context.POPUP_BACKGROUND))
     self.SetOwnBackgroundColour(Colour(context.POPUP_BACKGROUND))
     self.SetForegroundColour(Colour(context.POPUP_FOREGROUND))
     self.SetOwnForegroundColour(Colour(context.POPUP_FOREGROUND))
コード例 #14
0
ファイル: sendfile.py プロジェクト: xuesong/mmc
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)
コード例 #15
0
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)
コード例 #16
0
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())
コード例 #17
0
ファイル: sound.py プロジェクト: Leonwenbin/wxPython
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")
コード例 #18
0
ファイル: sound.py プロジェクト: Leonwenbin/wxPython
    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)
コード例 #19
0
 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()
コード例 #20
0
    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]))
コード例 #21
0
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")
コード例 #22
0
    def __init__(self, dialogTitle, defaultFile, fileMask, fileMode,
                 optionsList):

        wx.Dialog.__init__(self,
                           id=-1,
                           name=u'FileChooserWithOptions',
                           parent=None,
                           style=wx.DIALOG_MODAL | wx.DEFAULT_DIALOG_STYLE,
                           title=dialogTitle)

        sizer = wx.BoxSizer(wx.VERTICAL)

        buttonText = _(u'&Browse')
        labelText = _(u'&File location: ')
        initialPath = os.path.join(os.path.realpath(os.path.curdir),
                                   defaultFile)
        self.filechooser = FileBrowseButton(self,
                                            -1,
                                            size=(400, -1),
                                            labelText=labelText,
                                            buttonText=buttonText,
                                            dialogTitle=dialogTitle,
                                            fileMask=fileMask,
                                            startDirectory=os.path.curdir,
                                            initialValue=initialPath,
                                            fileMode=fileMode)

        sizer.Add(self.filechooser, 0, wx.ALL, 5)

        self.options = {}
        for opt in optionsList:
            cb = self.options[opt['name']] = wx.CheckBox(
                self, -1, opt['label'])
            cb.SetValue(opt['checked'])
            sizer.Add(cb, 0, wx.ALL, 3)

        buttonSizer = self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL)

        self.box = box = wx.BoxSizer(wx.VERTICAL)
        box.Add(sizer)
        box.Add(buttonSizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
        self.SetSizer(box)
        box.Fit(self)

        self.Layout()
        self.CenterOnScreen()
コード例 #23
0
 def AddWidget(self, name, ty, default=None):
     if ty == bool:
         widget = wx.CheckBox(self, -1)
         if default:
             widget.SetValue(True)
     elif ty == file:
         widget = FileBrowseButton(self,
                                   -1,
                                   labelText='',
                                   initialValue=default or "")
         widget.SetMinSize((300, widget.GetSize()[1]))
     elif type(ty) in (list, tuple):
         widget = ValidChoice(self, choices=ty, default=default or 0)
     else:
         widget = ValidTextCtrl(self, ty, default)
     return wx.StaticText(self, -1, name), widget
コード例 #24
0
ファイル: gradientbrowser.py プロジェクト: gijzelaerr/fr0st
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent

        mask = ("Gradient Files (*.ugr)|*.ugr|"
                "Map Files (*.map)|*.map|"
                "Flame Files (*.flame)|*.flame|"
                "Flam3 XML Palette (*.xml)|*.xml|"
                "All files (*.*)|*.*")

        path = os.path.abspath(config["flamepath"])
        self.fbb = FileBrowseButton(self, -1, fileMask=mask, labelText='File:',
                                    changeCallback=self.fbb_callback,
                                    initialValue=path)
             
        self.bcb = wx.combo.BitmapComboBox(self, style=wx.CB_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.OnCombo, self.bcb)

        self.load(path)

        szr = Box(self, "Gradient Browser", (self.fbb, 0, wx.EXPAND|wx.ALL, 5),
                                            (self.bcb, 0, wx.EXPAND|wx.ALL, 5))
        self.SetSizerAndFit(szr)
コード例 #25
0
ファイル: contentassist.py プロジェクト: charles20cent/RIDE
 def OnBrowse(self, evt=None):
     self._browsed = True
     FileBrowseButton.OnBrowse(self, evt)
     self._browsed = False
コード例 #26
0
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()
コード例 #27
0
    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))
コード例 #28
0
    def __init__(self, *args, **kwds):

        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        
        self.pickMaskBrowser = FileBrowseButton(self, -1, labelText='Mask File')
コード例 #29
0
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
コード例 #30
0
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')
コード例 #31
0
    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)