Exemple #1
0
    def test_utilsWindowDisabler(self):
        wd = wx.WindowDisabler()
        self.assertTrue(not self.frame.IsEnabled())
        del wd

        wd = wx.WindowDisabler(self.frame)
        self.assertTrue(self.frame.IsEnabled())
Exemple #2
0
    def __init__(self, mainFrame, adb, optionsHandler):
        wx.Frame.__init__(self,
                          mainFrame,
                          title='Installing builds',
                          style=wx.DEFAULT_FRAME_STYLE
                          & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.mainFrame = mainFrame
        self.adb = adb
        self.optionsHandler = optionsHandler
        self.checkboxesState = True
        self.buildChosen = ''
        self.disabler = wx.WindowDisabler(self)
        self.panel = wx.Panel(self)

        self.selectBuildButton, self.chooseLatestBuildButton, self.chosenBuildTextCtrl, self.devicesSizer, self.installBuildButton, self.checkAllButton, self.closeButton, self.optionsCombobox = self.createControls(
        )

        self.Bind(wx.EVT_BUTTON, self.selectBuild, self.selectBuildButton)
        self.Bind(wx.EVT_BUTTON, self.getLatestBuildFromOptionsFolder,
                  self.chooseLatestBuildButton)
        self.Bind(wx.EVT_BUTTON, self.installBuild, self.installBuildButton)
        self.Bind(wx.EVT_BUTTON, self.switchAllCheckboxes, self.checkAllButton)
        self.Bind(wx.EVT_BUTTON, self.onClose, self.closeButton)

        self.Bind(wx.EVT_CLOSE, self.onClose)

        self.Fit()
        self.Show()
Exemple #3
0
    def on_save_as(self):
        if self.get_project_filename():
            dir_name, file_name = os.path.split(self.get_project_filename())
        style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
        wildcard = "Arquivo de projeto do GRIPy (*.pgg)|*.pgg"

        fdlg = wx.FileDialog(
            self.GetTopWindow(),
            'Escolha o arquivo PGG',
            #dir_name, file_name,
            wildcard=wildcard,
            style=style)

        if fdlg.ShowModal() == wx.ID_OK:

            file_name = fdlg.GetFilename()
            dir_name = fdlg.GetDirectory()
            if not file_name.endswith('.pgg'):
                file_name += '.pgg'
            disableAll = wx.WindowDisabler()
            wait = wx.BusyInfo("Saving GriPy project. Wait...")
            self.save_project_data(os.path.join(dir_name, file_name))
            del wait
            del disableAll

        fdlg.Destroy()
Exemple #4
0
 def ShowWindow(self):
     self._disabler = wx.WindowDisabler(self)
     self.CenterOnParent()
     self.Show()
     self.Restore()
     self.UpdatePulse()
     self.Raise()
    def __init__(self, parentFrame, deviceId, adb, listOfPackages):
        wx.Frame.__init__(self,
                          parentFrame,
                          title='Installed packages',
                          style=wx.DEFAULT_FRAME_STYLE
                          & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.parentFrame = parentFrame
        self.deviceId = deviceId
        self.adb = adb
        self.listOfPackages = listOfPackages
        self.versionInfoDict = {
            'Version Name': self.adb.getBuildVersionNameFromDevice,
            'Version Code': self.adb.getBuildVersionCodeFromDevice,
            'Debug?': self.adb.isInstalledPackageDebuggable
        }

        self.disabler = wx.WindowDisabler(self)
        self.panel = wx.Panel(self)

        self.infoCtrlsUpdateList, self.closeBtn = self.createControls()
        self.runUpdateThreads()

        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.Bind(wx.EVT_BUTTON, self.onClose, self.closeBtn)
        self.Fit()
        self.Show(True)
Exemple #6
0
def kde_file_selector(message, default_path="", default_filename="",
                      default_extension="", wildcard="*.*", flags=0,
                      *args, **kwds):
    """\
    Pops up the standard KDE file selector box, calling kdialog. The API is
    identical to that of wx.FileSelector. If kdialog can't be invoked,
    reverts to the standard wx.FileSelector. Note that at the moment not all
    the arguments are meaningful (for example, parent and initial position are
    ignored), and multiple selections are not supported.
    """
    if not _kdialog_ok:
        return wx.FileSelector(message, default_path, default_filename,
                               default_extension, wildcard, flags,
                               *args, **kwds)
    
    r, w = os.pipe()
    handler = _SigChldHandler()
    oldhandler = signal.signal(signal.SIGCHLD, handler)

    pid = os.fork()

    if pid == 0:
        os.close(r)
        os.dup2(w, sys.stdout.fileno())
        os.close(w)
        startdir = default_path
        if default_filename:
            if not os.path.isdir(startdir):
                startdir = os.path.dirname(startdir)
            startdir = os.path.join(startdir, default_filename)
        if flags & wx.SAVE:
            kind = '--getsavefilename'
        else:
            kind = '--getopenfilename'
        os.execlp('kdialog', 'kdialog', kind, startdir,
                  _wx_to_kde_wildcard(wildcard), '--title', message)
    elif pid > 0:
        disabler = wx.WindowDisabler()
        app = wx.GetApp()
        os.close(w)
        while not handler.done:
            app.Dispatch()
        if handler.status != 0:
            os.close(r)
            return ""

        filename = os.fdopen(r).readline().strip()
        signal.signal(signal.SIGCHLD, oldhandler or signal.SIG_DFL)
        if (flags & wx.SAVE) and (flags & wx.OVERWRITE_PROMPT) and \
               os.path.exists(filename):
            if wx.MessageBox(_("File '%s' already exists: do you really want "
                               "to overwrite it?") % misc.wxstr(filename),
                             _("Confirm"),
                             style=wx.YES_NO|wx.ICON_QUESTION) == wx.NO:
                return kde_file_selector(message, default_path,
                                         default_filename, default_extension,
                                         wildcard, flags)
        return filename
    else:
        raise OSError, _("Fork Error")
Exemple #7
0
    def optimizeFitPrice(self, event):
        fitID = self.getActiveFit()
        sFit = Fit.getInstance()
        fit = sFit.getFit(fitID)

        if fit:

            def updateFitCb(replacementsCheaper):
                del self.waitDialog
                del self.disablerAll
                rebaseMap = {
                    k.ID: v.ID
                    for k, v in replacementsCheaper.items()
                }
                self.command.Submit(
                    cmd.GuiRebaseItemsCommand(fitID=fitID,
                                              rebaseMap=rebaseMap))

            fitItems = {
                i
                for i in Fit.fitItemIter(fit, forceFitImplants=True)
                if i is not fit.ship.item
            }
            self.disablerAll = wx.WindowDisabler()
            self.waitDialog = wx.BusyInfo("Please Wait...", parent=self)
            Price.getInstance().findCheaperReplacements(fitItems,
                                                        updateFitCb,
                                                        fetchTimeout=10)
Exemple #8
0
 def open_dialog(cls):
     d = cls.get_dialog()
     # Forcibly disable all windows (other than the progress dialog) to
     # prevent user event processing in the wx.Yield calls.
     cls.disabler = wx.WindowDisabler(d)
     wx.BeginBusyCursor()
     return d
 def ShowModal(self):
     """
     This function is the one giving the wx.FileDialog behavior
     """
     self._disabler = wx.WindowDisabler(self)
     self.Show()
     self.eventLoop = wx.GUIEventLoop()
     self.eventLoop.Run()
Exemple #10
0
 def on_save(self):
     if self.get_project_filename():
         disableAll = wx.WindowDisabler()
         wait = wx.BusyInfo("Saving GriPy project. Wait...")
         self.save_project_data()
         del wait
         del disableAll
     else:
         self.on_save_as()
Exemple #11
0
    def fill(self, names, sels):
        wx.WindowDisabler()

        wx.BeginBusyCursor()
        self.load(names)
        self.Populate()

        items = self.fixstardata.iteritems()
        for k, v in items:
            for i in range(len(sels)):
                if sels[i]:
                    self.CheckItem(i)

        wx.EndBusyCursor()
Exemple #12
0
 def busy(self, value):
     if value:
         self._busy = True
         self._disableAll = wx.WindowDisabler()
         if not isinstance(value, str):
             v = _("Busy...")
         else:
             v = value
         self._wait = BusyInfo("Please wait. \n%s" % v, parent=self)
         wx.GetApp().Yield()
     else:
         self._busy = False
         self._wait = None
         self._disableAll = None
         wx.GetApp().Yield()
Exemple #13
0
 def __init__(self, mainFrame, optionsHandler):
     wx.Frame.__init__(self,
                       mainFrame,
                       title='Options',
                       style=wx.DEFAULT_FRAME_STYLE
                       & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
     self.disabler = wx.WindowDisabler(self)
     self.mainFrame = mainFrame
     self.optionsHandler = optionsHandler
     self.changedOptions = {}
     self.panel = wx.Panel(self)
     self.saveBtn, self.jenkinsCredentialControls = self.createControls()
     self.Bind(wx.EVT_BUTTON, self.saveChanges, self.saveBtn)
     self.Bind(wx.EVT_CLOSE, self.onClose)
     self.Fit()
     self.Show(True)
    def call_sct_command(self, command):
        disable_window = wx.WindowDisabler()
        binfo = ProgressDialog(frame)
        binfo.Show()

        thr = SCTCallThread(command)
        thr.start()

        # No access to app.pending() from here
        while True:
            thr.join(0.1)
            wx.Yield()
            if not thr.isAlive():
                break
        thr.join()

        binfo.Destroy()
Exemple #15
0
    def show(self, value=True, modal=None):
        "Display or hide the window, optionally disabling all other windows"
        self.wx_obj.Show(value)
        if modal:
            # disable all top level windows of this application (MakeModal)
            disabler = wx.WindowDisabler(self.wx_obj)
            # create an event loop to stop execution
            eventloop = wx.EventLoop()

            def on_close_modal(evt):
                evt.Skip()
                eventloop.Exit()

            self.wx_obj.Bind(wx.EVT_CLOSE, on_close_modal)
            # start the event loop to wait user interaction
            eventloop.Run()
            # reenable the windows disabled and return control to the caller
            del disabler
    def __init__(self, parentFrame, optionsHandler, jenkinsCredentialControls):
        wx.Frame.__init__(self,
                          parentFrame,
                          title='Edit credentials',
                          style=wx.DEFAULT_FRAME_STYLE
                          & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.parentFrame = parentFrame
        self.optionsHandler = optionsHandler
        self.jenkinsCredentialControls = jenkinsCredentialControls
        self.disabler = wx.WindowDisabler(self)
        self.panel = wx.Panel(self)
        self.saveBtn, self.userInputField, self.passwordInputField = self.createControls(
        )

        self.Bind(wx.EVT_BUTTON, self.updateJenkinsCreds, self.saveBtn)
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.Fit()
        self.Show(True)
 def Recreate(self, config, message):
     app = ceGUI.GetApp()
     disabler = wx.WindowDisabler()
     app.busyInfo = wx.BusyInfo(message)
     try:
         app.topWindow.closing = True
         ceGUI.UnsubscribeAll()
         self.Hide()
         app.Yield()
         self.Destroy()
         app.config = config
         config.OnRecreate()
         newFrame = app.topWindow = app.GetTopWindow()
         app.SetTopWindow(newFrame)
         newFrame.Show()
     finally:
         del disabler
         app.busyInfo = None
Exemple #18
0
    def __init__(self, parentFrame, deviceId, adb):
        wx.Frame.__init__(self,
                          parentFrame,
                          title='Device Info',
                          style=wx.DEFAULT_FRAME_STYLE
                          & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.parentFrame = parentFrame
        self.deviceId = deviceId
        self.adb = adb
        self.disabler = wx.WindowDisabler(self)
        self.deviceInfoTable = (
            ('Brand', self.adb.getProperty, 'field',
             'ro.product.brand'), ('Model', self.adb.getProperty, 'field',
                                   'ro.product.model'),
            ('Screen size', self.adb.getDeviceScreenSize,
             'field'), ('IP Address', self.adb.getDeviceIpAddress,
                        'field'), ('ADB tcpip port', self.adb.getProperty,
                                   'field', 'service.adb.tcp.port'),
            ('Battery', self.adb.getBatteryStatus,
             'field'), ('Plugged in?', self.adb.getPluggedInStatus, 'field'),
            ('OS version', self.adb.getProperty, 'field',
             'ro.build.version.release'), ('API version', self.adb.getProperty,
                                           'field', 'ro.build.version.sdk'),
            ('Device timezone', self.adb.getProperty, 'field',
             'persist.sys.timezone'), ('Device language', self.adb.getProperty,
                                       'field', 'persist.sys.locale'),
            ('Marketing name', self.adb.getProperty, 'field',
             'ro.config.marketing_name'), ('Wifi name', self.adb.getWifiName,
                                           'field'),
            ('Serial No', self.adb.getProperty, 'field',
             'ro.boot.serialno'), ('Installed packages',
                                   self.adb.getListOfInstalledPackages,
                                   'button'))
        self.installedPackagesList = None
        self.panel = wx.Panel(self)
        self.deviceInfoControls, self.showPackagesButton, self.closeBtn, = self.createControls(
        )
        self.updateFields()

        self.Bind(wx.EVT_BUTTON, self.showPackages, self.showPackagesButton)
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.Bind(wx.EVT_BUTTON, self.onClose, self.closeBtn)
        self.Fit()
        self.Show(True)
Exemple #19
0
    def __init__(self, mainFrame, adb, optionsHandler):
        wx.Frame.__init__(self, mainFrame, title = 'Capturing screenshots!', style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
        self.mainFrame = mainFrame
        self.adb = adb
        self.optionsHandler = optionsHandler
        self.checkboxesState = True
        self.directory = self.optionsHandler.getOption('Screenshots folder', str)
        self.disabler = wx.WindowDisabler(self)
        self.panel = wx.Panel(self)

        self.openButton, self.closeButton, self.captureButton, self.checkAllButton, self.devicesSizer = self.createControls()

        self.Bind(wx.EVT_BUTTON, self.switchAllCheckboxes, self.checkAllButton)
        self.Bind(wx.EVT_BUTTON, self.captureScreenshots, self.captureButton)
        self.Bind(wx.EVT_BUTTON, self.openScreenshotsFolder, self.openButton)
        self.Bind(wx.EVT_BUTTON, self.onClose, self.closeButton)
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.Fit()
        self.Show(True)
    def pick_inp(self, parent, WD):
        dlg = wx.FileDialog(parent,
                            message="Choose .inp file",
                            defaultDir=WD,
                            defaultFile="magic.inp",
                            wildcard="*.inp",
                            style=wx.FD_OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            inp_file_name = dlg.GetPath()
        else:
            # notify user that most recent file will be used
            disableAll = wx.WindowDisabler()
            wait = wx.BusyInfo('No inp file selected. Reading from'
                               ' most recently opened files...')
            wx.SafeYield()
            sleep(1.5)
            del wait
            inp_file_name = None
        dlg.Destroy()
        return inp_file_name
Exemple #21
0
	def fill(self, names):
		wx.WindowDisabler()

		self.initchecking = True
		wx.BeginBusyCursor()
		self.load()
		self.Populate()

		nset = set()
		items = self.fixstardata.iteritems()
		for k, v in items:
			for nomname in names.iterkeys():
				if v[1] == nomname and nomname not in nset:
					if len(nset) >= FixStarListCtrl.MAX_SEL_NUM:
						break

					self.CheckItem(k-1)
					nset.add(nomname)

		wx.EndBusyCursor()
		self.initchecking = False
Exemple #22
0
def kde_dir_selector(message="", default_path="", *args, **kwds):
    """\
    Pops up the standard KDE directory selector box, calling kdialog.
    The API is identical to that of wx.DirSelector. If kdialog can't be
    invoked, reverts to the standard wx.DirSelector. Note that at the moment
    not all the arguments are meaningful (for example, parent and initial
    position are ignored).
    """
    if not _kdialog_ok:
        return wx.DirSelector(message, default_path, *args, **kwds)

    r, w = os.pipe()
    handler = _SigChldHandler()
    oldhandler = signal.signal(signal.SIGCHLD, handler)
    pid = os.fork()

    if pid == 0:
        os.close(r)
        os.dup2(w, sys.stdout.fileno())
        os.close(w)
        if not default_path:
            default_path = os.getcwd()
        os.execlp('kdialog', 'kdialog', '--getexistingdirectory', default_path,
                  '--title', message)
    elif pid > 0:
        disabler = wx.WindowDisabler()
        app = wx.GetApp()
        os.close(w)
        while not handler.done:
            app.Dispatch()
        if handler.status != 0:
            os.close(r)
            return ""

        dirname = os.fdopen(r).readline().strip()
        signal.signal(signal.SIGCHLD, oldhandler or signal.SIG_DFL)
        return dirname
    else:
        raise OSError, "Fork Error"
Exemple #23
0
def on_create_1_layer_image(*args, **kwargs):
    OM = ObjectManager()
    UIM = UIManager()
    #
    dlg = UIM.create('dialog_controller', title='Create 1 layer image')
    ctn_model = dlg.view.AddCreateContainer('StaticBox', label='Image', orient=wx.VERTICAL, 
                                              proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    #
    box_name = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                        orient=wx.HORIZONTAL, proportion=1, 
                                        flag=wx.EXPAND|wx.ALL, border=5)
    dlg.view.AddStaticText(box_name, label='Name:', proportion=1)
    dlg.view.AddTextCtrl(box_name, proportion=1, flag=wx.ALIGN_LEFT, border=5, 
                         widget_name='image_name', initial="My image") 
           
   
    #
    box_color = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                        orient=wx.HORIZONTAL, proportion=1,
                                        flag=wx.EXPAND|wx.ALL, border=5)
    dlg.view.AddStaticText(box_color, label='Color:', proportion=1)
    dlg.view.AddChoice(box_color, proportion=1, flag=wx.ALIGN_LEFT, 
                       widget_name='color', options=COLOR_TYPES, initial=0)
    #  
    

    #
    box_width_pixels = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                        orient=wx.HORIZONTAL, proportion=1,
                                        flag=wx.EXPAND|wx.ALL, border=5)
    dlg.view.AddStaticText(box_width_pixels, label='Width pixels:', proportion=1)    
    dlg.view.AddTextCtrl(box_width_pixels, proportion=1, flag=wx.ALIGN_LEFT, 
                         border=5, widget_name='width_pixels', initial=100)  
    
    #  

    #
    box_height_pixels = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                        orient=wx.HORIZONTAL, proportion=1,
                                        flag=wx.EXPAND|wx.ALL, border=5)
    dlg.view.AddStaticText(box_height_pixels, label='Height pixels:', proportion=1)    
    dlg.view.AddTextCtrl(box_height_pixels, proportion=1, flag=wx.ALIGN_LEFT, 
                         border=5, widget_name='height_pixels', initial=100)  
    
    #  
  
    
    #    
    dlg.view.SetSize((400, 250))
    result = dlg.view.ShowModal()

    try:
        disableAll = wx.WindowDisabler()
        wait = wx.BusyInfo("Creating model. Wait...")
        if result == wx.ID_OK:
            results = dlg.get_results()  
            print(results)
            
            
            width = int(results.get('width_pixels'))
            height = int(results.get('height_pixels')) 
            
            if results.get('color') == "white":
                data = np.ones((height, width), dtype=np.ubyte) 
                data *= 255
            else:
                data = np.zeros((height, width), dtype=np.ubyte)
            

            img = OM.new('image', data, name=results.get('image_name'))
            result = OM.add(img)

            
            
    except Exception as e:
        print ('ERROR [on_create_model]:', str(e))
        raise
    finally:
        del wait
        del disableAll
        UIM.remove(dlg.uid)
    def on_ok(self, event):

        parDict = OrderedDict()
        parDict['Qvalue'] = 0
        if self.modChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a type of Seismogram to be modeled!")
            raise Exception(
                "Please choose a type of Seismogram to be modeled!")
        parDict['modFlag'] = self.modtype[
            self.modChoiceBox.GetStringSelection()]
        if self.respChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a type of Response!")
            raise Exception("Please choose a type of Response!")
        parDict['respFlag'] = self.modtype[
            self.modChoiceBox.GetStringSelection()]
        if self.wellChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Well!")
            raise Exception("Please choose a Well!")
        parDict['wellID'] = self.wellOptions[
            self.wellChoiceBox.GetStringSelection()]
        if self.vpChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Vp log!")
            raise Exception("Please choose a Vp log!")
        parDict['vpLogID'] = self.logOptions[
            self.vpChoiceBox.GetStringSelection()]
        if self.vsChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Vs log!")
            raise Exception("Please choose a Vs log!")
        parDict['vsLogID'] = self.logOptions[
            self.vsChoiceBox.GetStringSelection()]
        if self.rhoChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a Density log!")
            raise Exception("Please choose a Density log!")
        parDict['rhoLogID'] = self.logOptions[
            self.rhoChoiceBox.GetStringSelection()]
        if not self.yesQvalueRB.GetValue() and not self.noQvalueRB.GetValue():
            wx.MessageBox("Please choose the Q-value option!")
            raise Exception("Please choose the Q-value option!")
            parDict['Qvalue'] = self.yesQvalueRB.GetValue()
        if self.flagRB == 0:
            parDict['Qvalue'] = 1
            if self.qpChoiceBox.GetStringSelection() == "":
                wx.MessageBox("Please choose a Q-value log for P-Wave!")
                raise Exception("Please choose a Q-value log for P-Wave!")
            parDict['Pwav_QvalueID'] = self.logOptions[
                self.qpChoiceBox.GetStringSelection()]
            if self.qsChoiceBox.GetStringSelection() == "":
                wx.MessageBox("Please choose a Q-value log for S-Wave!")
                raise Exception("Please choose a Q-value log for S-Wave!")
            parDict['Swav_QvalueID'] = self.logOptions[
                self.qsChoiceBox.GetStringSelection()]
        if self.nsampTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Number of Samples!")
            raise Exception("Please choose the Number of Samples!")
        parDict['numsamps'] = int(float(self.nsampTxtCtrl.GetValue()))
        if self.dtTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Sample Rate Interval!")
            raise Exception("Please choose the Sample Rate Interval!")
        parDict['dt'] = float(self.dtTxtCtrl.GetValue())
        if self.fwavTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose Peak Frequency of the Wavelet to be Used!")
            raise Exception(
                "Please choose Peak Frequency of the Wavelet to be Used!")
        parDict['fWav'] = float(self.fwavTxtCtrl.GetValue())
        if self.ntrcsTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Number of Traces of the Output!")
            raise Exception(
                "Please choose the Number of Traces of the Output!")
        parDict['ntraces'] = int(float(self.ntrcsTxtCtrl.GetValue()))
        if self.trc1TxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the 1st trace cordinate!")
            raise Exception("Please choose the 1st trace cordinate!")
        parDict['trc1'] = float(self.trc1TxtCtrl.GetValue())
        if self.latdtTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Lateral Sample Rate!")
            raise Exception("Please choose the Lateral Sample Rate!")
        parDict['dlat'] = float(self.latdtTxtCtrl.GetValue())
        if self.cam1velTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Velocity of the 1st Layer!")
            raise Exception("Please choose the Velocity of the 1st Layer!")
        parDict['vel1'] = float(self.cam1velTxtCtrl.GetValue())
        if self.cam1thickTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Thickness of 1st Layer!")
            raise Exception("Please choose the Thickness of 1st Layer!")
        parDict['z1'] = float(self.cam1thickTxtCtrl.GetValue())
        if self.nsupTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Number of Superior Layers!")
            raise Exception("Please choose the Number of Superior Layers!")
        parDict['nsup'] = int(float(self.nsupTxtCtrl.GetValue()))
        if self.zsupTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Thickness of Each Superior Layers!")
            raise Exception(
                "Please choose the Thickness of Each Superior Layers!")
        parDict['zsup'] = float(self.zsupTxtCtrl.GetValue())
        if self.firstLayerTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Depth of the 1st Layer to be Modeled!")
            raise Exception(
                "Please choose the Depth of the 1st Layer to be Modeled!")
        parDict['firstLayer'] = float(self.firstLayerTxtCtrl.GetValue())
        if self.lastLayerTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Depth of the Last Layer to be Modeled!")
            raise Exception(
                "Please choose the Depth of the Last Layer to be Modeled!")
        parDict['lastLayer'] = float(self.lastLayerTxtCtrl.GetValue())
        if self.pnumTxtCtrl.GetValue() == "":
            wx.MessageBox(
                "Please choose the Number Ray Parameters to Integration!")
            raise Exception(
                "Please choose the Number Ray Parameters to Integration!")
        parDict['pNum'] = int(float(self.pnumTxtCtrl.GetValue()))
        if self.angmaxTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Maximum Angle of Incidence!")
            raise Exception("Please choose the Maximum Angle of Incidence!")
        parDict['angMax'] = float(self.angmaxTxtCtrl.GetValue())
        if self.vpSupTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the P velocity of Superior Layers!")
            raise Exception("Please choose the P velocity of Superior Layers!")
        parDict['vpSup'] = float(self.vpSupTxtCtrl.GetValue())
        if self.vsSupTxtCtrl.GetValue() == "":
            wx.MessageBox("Please choose the Maximum Angle of Incidence!")
            raise Exception("Please choose the Maximum Angle of Incidence!")
        parDict['vsSup'] = float(self.vsSupTxtCtrl.GetValue())
        if self.outChoiceBox.GetStringSelection() == "":
            wx.MessageBox("Please choose a type of Output!")
            raise Exception("Please choose a type of Output!")
        parDict['outFlag'] = self.outtype[
            self.outChoiceBox.GetStringSelection()]
        if self.objTxtCtrl.GetValue() == "":
            wx.MessageBox("Please Choose an Output Name!")
            raise Exception("Please Choose an Output Name!")
        parDict['outName'] = self.objTxtCtrl.GetValue()

        return_flag = -1

        try:
            disableAll = wx.WindowDisabler()
            wait = wx.BusyInfo("Running the Modeling...")
            return_flag = Reflectivity(self.OM, parDict)
        except Exception as e:
            print('ERROR:', e)
            pass
        finally:
            del wait
            del disableAll
            self.dlg.Destroy()

        if return_flag == 1:
            wx.MessageBox('Vp and Vs logs have different sizes!')
        elif return_flag == 2:
            wx.MessageBox('Vp and Density logs have different sizes!')
        elif return_flag == 3:
            wx.MessageBox('Vp and Depth indexes have different sizes!')
        elif return_flag == 4:
            wx.MessageBox('Insuficient Number of Layer!')
        elif return_flag == 5:
            wx.MessageBox(
                'The Q-values Logs have different sizes than Vp and VS!')
        elif return_flag == 6:
            wx.MessageBox('Done!')
        else:
            wx.MessageBox('Other problems has occurred.')
Exemple #25
0
 def MakeModal(self, modal=True):
     if modal and not hasattr(self, '_disabler'):
         self._disabler = wx.WindowDisabler(self)
     if not modal and hasattr(self, '_disabler'):
         del self._disabler
Exemple #26
0
def on_load_model(*args, **kwargs):
    wildcard = "Load segmentated file (*.png, *.tif)|*.png;*.tif"



    fdlg = wx.FileDialog(wx.App.Get().GetTopWindow(), 
                         "Choose file", 
                         wildcard=wildcard, 
                         style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST
    )
    if fdlg.ShowModal() == wx.ID_OK:
        file_name = fdlg.GetFilename()
        dir_name = fdlg.GetDirectory()
        fdlg.Destroy()
    else:
        fdlg.Destroy()
        return
    fullfilename = os.path.join(dir_name, file_name)    
    
    print("\n\n")
    print (fullfilename)
    
    input_vec = plt.imread(fullfilename)
    
    
    print(input_vec.shape)
    print(input_vec.dtype)
    
    if (len(input_vec.shape) == 2):
        print(input_vec[100,100])
        
    elif (len(input_vec.shape) == 3):    
        
        ny, nx, ncolor = input_vec.shape
        
        new_vec = np.zeros((ny, nx), dtype=np.int8)
        
        if (input_vec.shape[2] == 4):
            # RGBA
            for y in range(ny):
                for x in range(nx):
                    new_vec[y, x] = (input_vec[y, x, 0] + input_vec[y, x, 1] + 
                                     input_vec[y, x, 2] + input_vec[y, x, 3])/4  
            
            
            #new_vec = np.array(Image.open(fullfilename).convert('L'))
            
            print(new_vec)
            print(new_vec[100,100])
            values = np.unique(new_vec)
    
            print(values.size)
            
            input_vec = new_vec
        #print(input_vec[100,100])
        
        
    
    
    values = np.unique(input_vec)
    
    print(values.size)
    
    if values.size > 2:
        msg = "File {} is not a binary segmentated file!".format(file_name)
        logging.error(msg)
        raise Exception(msg)
        
    OM = ObjectManager()
    UIM = UIManager()
    #
    dlg = UIM.create('dialog_controller', title='Create 2 layers model')
    #
    ctn_name = dlg.view.AddCreateContainer('StaticBox', 
                                           label='New model name', 
                                           orient=wx.VERTICAL, 
                                           proportion=0, 
                                           flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_name, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='model_name', 
                         initial=file_name.split(".")[0])     
    #    
    #
    ctn_xaxis = dlg.view.AddCreateContainer('StaticBox', 
                                        label="X Axis spacing",
                                        orient=wx.VERTICAL, 
                                        proportion=0, 
                                        flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_xaxis, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='dx', initial=0.000296)
    #
    ctn_yaxis = dlg.view.AddCreateContainer('StaticBox', 
                                            label="Y Axis spacing", 
                                            orient=wx.VERTICAL, 
                                            proportion=0, 
                                            flag=wx.EXPAND|wx.TOP, border=5) 
    dlg.view.AddTextCtrl(ctn_yaxis, proportion=0, flag=wx.EXPAND|wx.TOP,
                         border=5, widget_name='dy', initial=0.000296)
    #        
    #
    ctn_layer_1 = dlg.view.AddCreateContainer('StaticBox', 
                                label='Layer 1 - Value: ' + str(values[0]), 
                                orient=wx.VERTICAL, 
                                proportion=0, 
                                flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_vp1 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_1, label='Vp(m/s)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_vp1, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='vp1', initial=2500.0)
    #
    ctn_rho1 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_1, label='Rho(g/cm3)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_rho1, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='rho1', initial=2.2)
    #    

    #
    if values.size == 2:
        ctn_layer_2 = dlg.view.AddCreateContainer('StaticBox', 
                                    label='Layer 2 - Value: ' + str(values[1]), 
                                    orient=wx.VERTICAL, 
                                    proportion=0, 
                                    flag=wx.EXPAND|wx.TOP, border=5)
        #
        ctn_vp2 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_2, label='Vp(m/s)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
        dlg.view.AddTextCtrl(ctn_vp2, proportion=0, flag=wx.EXPAND|wx.TOP,
                             border=5, widget_name='vp2', initial=4000.0)
        #
        ctn_rho2 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_2, label='Rho(g/cm3)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
        dlg.view.AddTextCtrl(ctn_rho2, proportion=0, flag=wx.EXPAND|wx.TOP, 
                             border=5, widget_name='rho2', initial=3.0)         
        #
    #    
    # ctn_layer_3 = dlg.view.AddCreateContainer('StaticBox', label='Layer 3', orient=wx.HORIZONTAL)
    # #
    # ctn_start3 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_3, label='Start', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_start3, proportion=0, flag=wx.EXPAND|wx.TOP, border=5, widget_name='start3', initial=200.0)       
    # #
    # ctn_vp3 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_3, label='Vp(m/s)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_vp3, proportion=0, flag=wx.EXPAND|wx.TOP, border=5, widget_name='vp3', initial=2645.0)
    # #
    # ctn_vs3 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_3, label='Vs(m/s)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_vs3, proportion=0, flag=wx.EXPAND|wx.TOP, border=5, widget_name='vs3', initial=1170.0)        
    # #
    # ctn_rho3 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_3, label='Rho(g/cm3)', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_rho3, proportion=0, flag=wx.EXPAND|wx.TOP, border=5, widget_name='rho3', initial=2.29)          
    # #    
    # ctn_q3 = dlg.view.AddCreateContainer('StaticBox', ctn_layer_3, label='Q', orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    # dlg.view.AddTextCtrl(ctn_q3, proportion=0, flag=wx.EXPAND|wx.TOP, border=5, widget_name='q3', initial=2000.0)   
    # #    
    dlg.view.SetSize((300, 550))
    result = dlg.view.ShowModal()

    try:
        disableAll = wx.WindowDisabler()
        wait = wx.BusyInfo("Creating model. Wait...")
        if result == wx.ID_OK:
            results = dlg.get_results()  

            am = OM.new('acoustic_2d_model', input_vec, 
                        dx=results.get('dx'), 
                        dy=results.get('dy'), 
                        name=results.get('model_name'))
            result = OM.add(am)
            
            print ('result acoustic_2d_model:', result, args, kwargs)
    
    
            layer1 = OM.new('geolayer', value=values[0], vp=results.get('vp1'),
                            rho=results.get('rho1'), name="Layer 1")
            result = OM.add(layer1, am.uid)
            print ('result layer 1:', result)
            
            if values.size == 2:
                layer2 = OM.new('geolayer', value=values[1],
                                vp=results.get('vp2'), rho=results.get('rho2'),
                                name="Layer 2")
                result = OM.add(layer2, am.uid)
                print ('result layer 2:', result)    
    
    
            print(input_vec.shape)
    

        
        
        
        # UIM = UIManager()      
        # mwc = wx.GetApp().get_main_window_controller()
        # cc = UIM.create('crossplot_controller', mwc.uid)        
        
        # xlim_max, ylim_max = input_vec.shape
        # # (left, right, bottom, top)
        # extent = (0, 0, xlim_max, ylim_max)

        # image = cc._main_panel.append_artist("AxesImage", 
        #                                      cmap="Greys") #,
        #                                      #extent=extent)
        # #cc._main_panel.add_image(image)
        # cc._main_panel.set_plot_lim('x', (0, xlim_max))
        # cc._main_panel.set_plot_lim('y', (ylim_max, 0))
        
        # print(xlim_max, ylim_max)
        
        # image.set_data(input_vec)
        # image.set_label('crossplot_controller')    
        
        
        # if image.get_clip_path() is None:
        #     # image does not already have clipping set, 
        #     # clip to axes patch
        #     image.set_clip_path(image.axes.patch)        
        
        #gripy_app = wx.App.Get()
        #gripy_app.load_project_data(fullfilename)
    except Exception as e:
        print ('ERROR [on_create_model]:', str(e))
        raise
    finally:
        del wait
        del disableAll
        UIM.remove(dlg.uid)
Exemple #27
0
def on_create_wavelet(*args, **kwargs):
    OM = ObjectManager()
    UIM = UIManager()
    #
    dlg = UIM.create('dialog_controller', title='Create Wavelet')
    #
    ctn_wavelet = dlg.view.AddCreateContainer('StaticBox', label='Wavelet', 
                                              orient=wx.VERTICAL, proportion=0, 
                                              flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddChoice(ctn_wavelet, proportion=0, flag=wx.EXPAND|wx.TOP, 
                       border=5, widget_name='wavelet', options=WAVELET_TYPES,
                       initial=0)
    #
    ctn_f0 = dlg.view.AddCreateContainer('StaticBox', 
                                        label='Base frequency (f0)', 
                                        orient=wx.VERTICAL, 
                                        proportion=0, 
                                        flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_f0, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='f0', initial='10.0') 
    #
    ctn_amp = dlg.view.AddCreateContainer('StaticBox', 
                                        label='Amplitude', 
                                        orient=wx.VERTICAL, 
                                        proportion=0, 
                                        flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_amp, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='amp', initial='1.0') 
    #    
    ctn_name = dlg.view.AddCreateContainer('StaticBox', 
                                           label='New wavelet name', 
                                           orient=wx.VERTICAL, 
                                           proportion=0, 
                                           flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_name, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='wavelet_name', 
                         initial='My Ricker Wavelet')     
    #    
    
    
    dlg.view.SetSize((300, 400))
    result = dlg.view.ShowModal()
    #
    try:
        disableAll = wx.WindowDisabler()
        wait = wx.BusyInfo("Creating wavelet. Wait...")
        if result == wx.ID_OK:
            results = dlg.get_results()          
            print (results)
            
            wavelet = OM.new('wavelet', _type="Ricker", 
                             f0=results.get('f0'), 
                             amp=results.get('amp'), 
                             name=results.get('wavelet_name'))
                             
            result = OM.add(wavelet)
            
            print ('result wavelet:', result, args, kwargs)            
            
            
    except Exception as e:
        print ('ERROR [on_create_model]:', str(e))
        raise
        
    finally:
        del wait
        del disableAll
        UIM.remove(dlg.uid)        
Exemple #28
0
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          title=u"pyfa: Character Editor",
                          pos=wx.DefaultPosition,
                          size=wx.Size(641, 600),
                          style=wx.DEFAULT_FRAME_STYLE
                          | wx.FRAME_FLOAT_ON_PARENT | wx.TAB_TRAVERSAL)

        i = wx.IconFromBitmap(
            bitmapLoader.getBitmap("character_small", "icons"))
        self.SetIcon(i)

        self.disableWin = wx.WindowDisabler(self)
        self.SetSizeHintsSz(wx.Size(640, 600), wx.DefaultSize)
        self.SetBackgroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE))

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        self.navSizer = wx.BoxSizer(wx.HORIZONTAL)

        cChar = service.Character.getInstance()
        charList = cChar.getCharacterList()
        charList.sort(key=lambda t: t[1])

        self.btnSave = wx.Button(self, wx.ID_SAVE)
        self.btnSave.Hide()
        self.btnSave.Bind(wx.EVT_BUTTON, self.processRename)

        self.characterRename = wx.TextCtrl(self,
                                           wx.ID_ANY,
                                           style=wx.TE_PROCESS_ENTER)
        self.characterRename.Hide()
        self.characterRename.Bind(wx.EVT_TEXT_ENTER, self.processRename)

        self.skillTreeChoice = wx.Choice(self, wx.ID_ANY, style=0)

        for id, name, active in charList:
            i = self.skillTreeChoice.Append(name, id)
            if active:
                self.skillTreeChoice.SetSelection(i)

        self.navSizer.Add(self.skillTreeChoice, 1, wx.ALL | wx.EXPAND, 5)

        buttons = (("new", wx.ART_NEW),
                   ("rename", bitmapLoader.getBitmap("rename", "icons")),
                   ("copy", wx.ART_COPY), ("delete", wx.ART_DELETE))

        size = None
        for name, art in buttons:
            bitmap = wx.ArtProvider.GetBitmap(
                art, wx.ART_BUTTON) if name != "rename" else art
            btn = wx.BitmapButton(self, wx.ID_ANY, bitmap)
            if size is None:
                size = btn.GetSize()

            btn.SetMinSize(size)
            btn.SetMaxSize(size)

            btn.SetToolTipString("%s character" % name.capitalize())
            btn.Bind(wx.EVT_BUTTON, getattr(self, name))
            setattr(self, "btn%s" % name.capitalize(), btn)
            self.navSizer.Add(btn, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 2)

        mainSizer.Add(self.navSizer, 0, wx.ALL | wx.EXPAND, 5)

        self.viewsNBContainer = wx.Notebook(self, wx.ID_ANY,
                                            wx.DefaultPosition, wx.DefaultSize,
                                            0)

        self.sview = SkillTreeView(self.viewsNBContainer)
        self.iview = ImplantsTreeView(self.viewsNBContainer)
        #=======================================================================
        # RC2
        self.iview.Show(False)
        #=======================================================================
        self.aview = APIView(self.viewsNBContainer)

        self.viewsNBContainer.AddPage(self.sview, "Skills")

        #=======================================================================
        # Disabled for RC2
        # self.viewsNBContainer.AddPage(self.iview, "Implants")
        #=======================================================================
        self.viewsNBContainer.AddPage(self.aview, "API")

        mainSizer.Add(self.viewsNBContainer, 1, wx.EXPAND | wx.ALL, 5)

        bSizerButtons = wx.BoxSizer(wx.HORIZONTAL)

        self.btnOK = wx.Button(self, wx.ID_OK)
        bSizerButtons.Add(self.btnOK, 0, wx.ALL, 5)
        self.btnOK.Bind(wx.EVT_BUTTON, self.editingFinished)

        mainSizer.Add(bSizerButtons, 0, wx.ALIGN_RIGHT, 5)

        self.SetSizer(mainSizer)
        self.Layout()

        self.Centre(wx.BOTH)

        charID = self.getActiveCharacter()
        if cChar.getCharName(charID) in ("All 0", "All 5"):
            self.restrict()

        self.registerEvents()

        self.mainFrame = gui.mainFrame.MainFrame.getInstance()
Exemple #29
0
    def __init__(self,
                 parent=None,
                 id=-1,
                 title="",
                 message="",
                 agwStyle=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE):
        """
        Default class constructor.

        :param `parent`: parent window;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `title`: dialog title to show in titlebar;
        :param `message`: message displayed above the progress bar;
        :param `style`: the dialog style. This can be a combination of the following bits:

         =================== =========== ==================================================
         Window Styles       Hex Value   Description
         =================== =========== ==================================================
         ``PD_CAN_ABORT``            0x1 This flag tells the dialog that it should have a ``Cancel`` button which the user may press. If this happens, the next call to `UpdatePulse` will return ``False``.
         ``PD_APP_MODAL``            0x2 Make the progress dialog modal. If this flag is not given, it is only 'locally' modal - that is the input to the parent window is disabled, but not to the other ones.
         ``PD_AUTO_HIDE``            0x4 Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached.
         ``PD_ELAPSED_TIME``         0x8 This flag tells the dialog that it should show elapsed time (since creating the dialog).
         =================== =========== ==================================================
         
        """

        wx.Dialog.__init__(self, parent, id, title)

        self._delay = 3
        self._hasAbortButton = False

        # we may disappear at any moment, let the others know about it
        self.SetExtraStyle(self.GetExtraStyle() | wx.WS_EX_TRANSIENT)

        self._hasAbortButton = (agwStyle & wx.PD_CAN_ABORT)

        if wx.Platform == "__WXMSW__":
            # we have to remove the "Close" button from the title bar then as it is
            # confusing to have it - it doesn't work anyhow
            # FIXME: should probably have a (extended?) window style for this
            if not self._hasAbortButton:
                self.EnableClose(False)

        self._state = (self._hasAbortButton and [Continue]
                       or [Uncancelable])[0]
        self._parentTop = wx.GetTopLevelParent(parent)

        dc = wx.ClientDC(self)
        dc.SetFont(wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT))
        widthText, dummy = dc.GetTextExtent(message)

        sizer = wx.BoxSizer(wx.VERTICAL)

        self._msg = wx.StaticText(self, wx.ID_ANY, message)
        sizer.Add(self._msg, 0, wx.LEFT | wx.TOP, 2 * LAYOUT_MARGIN)

        sizeDlg = wx.Size()
        sizeLabel = self._msg.GetSize()
        sizeDlg.y = 2 * LAYOUT_MARGIN + sizeLabel.y

        self._gauge = ProgressGauge(self, -1)

        sizer.Add(self._gauge, 0, wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
                  2 * LAYOUT_MARGIN)

        sizeGauge = self._gauge.GetSize()
        sizeDlg.y += 2 * LAYOUT_MARGIN + sizeGauge.y

        # create the estimated/remaining/total time zones if requested
        self._elapsed = None
        self._display_estimated = self._last_timeupdate = self._break = 0
        self._ctdelay = 0

        label = None

        nTimeLabels = 0

        if agwStyle & wx.PD_ELAPSED_TIME:

            nTimeLabels += 1
            self._elapsed = self.CreateLabel("Elapsed time : ", sizer)

        if nTimeLabels > 0:

            label = wx.StaticText(self, -1, "")
            # set it to the current time
            self._timeStart = wx.GetCurrentTime()
            sizeDlg.y += nTimeLabels * (label.GetSize().y + LAYOUT_MARGIN)
            label.Destroy()

        sizeDlgModified = False

        if wx.Platform == "__WXMSW__":
            sizerFlags = wx.ALIGN_RIGHT | wx.ALL
        else:
            sizerFlags = wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM | wx.TOP

        if self._hasAbortButton:
            buttonSizer = wx.BoxSizer(wx.HORIZONTAL)

            self._btnAbort = wx.Button(self, -1, "Cancel")
            self._btnAbort.Bind(wx.EVT_BUTTON, self.OnCancel)

            # Windows dialogs usually have buttons in the lower right corner
            buttonSizer.Add(self._btnAbort, 0, sizerFlags, LAYOUT_MARGIN)

            if not sizeDlgModified:
                sizeDlg.y += 2 * LAYOUT_MARGIN + wx.Button.GetDefaultSize().y

        if self._hasAbortButton:
            sizer.Add(buttonSizer, 0, sizerFlags, LAYOUT_MARGIN)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

        self._agwStyle = agwStyle

        self.SetSizerAndFit(sizer)

        sizeDlg.y += 2 * LAYOUT_MARGIN

        # try to make the dialog not square but rectangular of reasonable width
        sizeDlg.x = max(widthText, 4 * sizeDlg.y / 3)
        sizeDlg.x *= 3
        sizeDlg.x /= 2
        self.SetClientSize(sizeDlg)

        self.Centre(wx.CENTER_FRAME | wx.BOTH)

        if agwStyle & wx.PD_APP_MODAL:
            self._winDisabler = wx.WindowDisabler(self)
        else:
            if self._parentTop:
                self._parentTop.Disable()
            self._winDisabler = None

        self.ShowDialog()
        self.Enable()

        # this one can be initialized even if the others are unknown for now
        # NB: do it after calling Layout() to keep the labels correctly aligned
        if self._elapsed:
            self.SetTimeLabel(0, self._elapsed)

        if not wx.EventLoop().GetActive():
            self.evtloop = wx.EventLoop()
            wx.EventLoop.SetActive(self.evtloop)

        self.Update()
Exemple #30
0
def on_create_model(*args, **kwargs):
    
    OM = ObjectManager()
    UIM = UIManager()
    
    

    #
    images_od = OrderedDict()
    images = OM.list('image')
    for image in images:
        images_od[image.name] = image.uid    

    #
    dlg = UIM.create('dialog_controller', title='Chose image for model input')
    ctn_image = dlg.view.AddCreateContainer('StaticBox', label='Select Image', 
                                            orient=wx.VERTICAL, proportion=0, 
                                            flag=wx.EXPAND|wx.TOP, border=5)


    dlg.view.AddChoice(ctn_image, proportion=0, flag=wx.EXPAND|wx.TOP, 
                       border=5, widget_name='images_choice', options=images_od,
                       initial=0) 
    #
    
    dlg.view.SetSize((300, 180))
    result = dlg.view.ShowModal()

  
    
    if result == wx.ID_OK:
        results = dlg.get_results()  
            
        print(results)    
    
        image_uid = results.get("images_choice")    
        
        if not image_uid:
            return
        
        image = OM.get(image_uid)    
    
    
        values = np.unique(image.data)
        print(values)
        print(values.size)
    
        if values.size > 2:
            raise Exception("ERRO!")
    
    
        #
        dlg = UIM.create('dialog_controller', title='Create model')


        ctn_model = dlg.view.AddCreateContainer('StaticBox', label='Model', orient=wx.VERTICAL, 
                                                  proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
        #
        box_img_input = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                               orient=wx.HORIZONTAL, proportion=1, 
                                               flag=wx.EXPAND|wx.ALL, border=5)
        dlg.view.AddStaticText(box_img_input, label='Image input:', proportion=1)        
        dlg.view.AddTextCtrl(box_img_input, proportion=1, flag=wx.ALIGN_LEFT, border=5, 
                             widget_name='image_name', initial=image.name)         
        textctrl_image_name = dlg.view.get_object('image_name')
        textctrl_image_name.disable()        
        #
        box_name = dlg.view.AddCreateContainer('BoxSizer', ctn_model, 
                                               orient=wx.HORIZONTAL, proportion=1, 
                                               flag=wx.EXPAND|wx.ALL, border=5)
        dlg.view.AddStaticText(box_name, label='Name:', proportion=1)
        dlg.view.AddTextCtrl(box_name, proportion=1, flag=wx.ALIGN_LEFT, border=5, 
                             widget_name='model_name', initial="My model") 
        #
    
    
    # X Axis
    #
    def on_change_x_size(name, old_value, new_value, **kwargs):
        try:
            x_samples = float(dlg.view.get_object('x_samples').get_value())
            x_spacing = float(dlg.view.get_object('x_spacing').get_value())
            res = str(x_samples * x_spacing) 
        except:
            res = ""
        textctrl_x_size = dlg.view.get_object('x_size')
        textctrl_x_size.set_value(res)      
    #
    #
    ctn_x_axis = dlg.view.AddCreateContainer('StaticBox', label='X axis', 
        orient=wx.HORIZONTAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_x_samples = dlg.view.AddCreateContainer('StaticBox', ctn_x_axis, 
            label='Samples(pixels)', orient=wx.VERTICAL, proportion=1, 
            flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_x_samples, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='x_samples', initial=image.width)
    textctrl_x_pixels = dlg.view.get_object('x_samples')
    textctrl_x_pixels.disable()
    #textctrl_x_samples.set_trigger(on_change_x_size)
    #
    ctn_x_spacing = dlg.view.AddCreateContainer('StaticBox', ctn_x_axis, 
                label='Spacing(m)', orient=wx.VERTICAL, proportion=1, 
                flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_x_spacing, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='x_spacing', initial=1)
    
    
    textctrl_x_spacing = dlg.view.get_object('x_spacing')
    textctrl_x_spacing.set_trigger(on_change_x_size)
    #
    ctn_x_size = dlg.view.AddCreateContainer('StaticBox', ctn_x_axis, 
                label='Size(m)', orient=wx.VERTICAL, proportion=1, 
                flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_x_size, proportion=1, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='x_size')
    textctrl_x_size = dlg.view.get_object('x_size')
    textctrl_x_size.disable()
    #
    on_change_x_size(None, None, None)
    #    
          
    
    # Y Axis
    #   
    def on_change_y_size(name, old_value, new_value, **kwargs):
        try:
            y_samples = float(dlg.view.get_object('y_samples').get_value())
            y_spacing = float(dlg.view.get_object('y_spacing').get_value())
            res = str(y_samples * y_spacing) 
        except:
            res = ""
        textctrl_y_size = dlg.view.get_object('y_size')
        textctrl_y_size.set_value(res)      
    #
    #
    ctn_y_axis = dlg.view.AddCreateContainer('StaticBox', label='Y axis', 
                                             orient=wx.HORIZONTAL, 
                                             proportion=0, 
                                             flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_y_samples = dlg.view.AddCreateContainer('StaticBox', ctn_y_axis, 
                                                label='Samples(pixels)', 
                                                orient=wx.VERTICAL, 
                                                proportion=1, 
                                                flag=wx.EXPAND|wx.TOP, 
                                                border=5)
    dlg.view.AddTextCtrl(ctn_y_samples, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='y_samples', initial=image.height)
    textctrl_y_pixels = dlg.view.get_object('y_samples')
    textctrl_y_pixels.disable()
    #textctrl_y_samples.set_trigger(on_change_y_size)
    #
    ctn_y_spacing = dlg.view.AddCreateContainer('StaticBox', ctn_y_axis, 
                                                label='Spacing(m)', 
                                                orient=wx.VERTICAL, 
                                                proportion=1, 
                                                flag=wx.EXPAND|wx.TOP, 
                                                border=5)
    dlg.view.AddTextCtrl(ctn_y_spacing, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='y_spacing', initial=1)
    textctrl_y_spacing = dlg.view.get_object('y_spacing')
    textctrl_y_spacing.set_trigger(on_change_y_size)
    #
    ctn_y_size = dlg.view.AddCreateContainer('StaticBox', ctn_y_axis, 
                                                label='Size(m)', 
                                                orient=wx.VERTICAL, 
                                                proportion=1, 
                                                flag=wx.EXPAND|wx.TOP, 
                                                border=5)
    dlg.view.AddTextCtrl(ctn_y_size, proportion=1, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='y_size')
    textctrl_y_size = dlg.view.get_object('y_size')
    textctrl_y_size.disable()
    #
    on_change_y_size(None, None, None)
    #    
    
    if values[0] == 0:
        value_layer_1_text = "color: Black"
    elif values[0] == 255:    
        value_layer_1_text = "color: White"
    else:    
        value_layer_1_text = "value: " + str(values[0])
    
    ctn_prop_matrix = dlg.view.AddCreateContainer('StaticBox', 
            label="Layer 1 properties (" + value_layer_1_text + ")", 
            orient=wx.HORIZONTAL, proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
    #
    ctn_matrix_vp = dlg.view.AddCreateContainer('StaticBox', ctn_prop_matrix, 
                                                label='Vp(m/s)', orient=wx.VERTICAL, proportion=1, flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_matrix_vp, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='matrix_vp', initial=4000.0)  
    #
    ctn_matrix_rho = dlg.view.AddCreateContainer('StaticBox', ctn_prop_matrix, 
                                                label='Rho(m/s)', orient=wx.VERTICAL, proportion=1, flag=wx.EXPAND|wx.TOP, border=5)
    dlg.view.AddTextCtrl(ctn_matrix_rho, proportion=0, flag=wx.EXPAND|wx.TOP, 
                         border=5, widget_name='matrix_rho', initial=3.0)  
    #
    
    if values.size == 2:
        if values[1] == 0:
            value_layer_2_text = "color: Black"
        elif values[1] == 255:    
            value_layer_2_text = "color: White"
        else:    
            value_layer_2_text = "value: " + str(values[1])
            
        ctn_prop_pores = dlg.view.AddCreateContainer('StaticBox',
                label="Layer 2 properties (" + value_layer_2_text + ")", 
                orient=wx.HORIZONTAL, 
                proportion=0, flag=wx.EXPAND|wx.TOP, border=5)
        #          
        ctn_pores_vp = dlg.view.AddCreateContainer('StaticBox', ctn_prop_pores, 
                label='Vp(m/s)', orient=wx.VERTICAL, 
                proportion=1, flag=wx.EXPAND|wx.TOP, border=5)
        dlg.view.AddTextCtrl(ctn_pores_vp, proportion=0, flag=wx.EXPAND|wx.TOP, 
                             border=5, widget_name='pores_vp', initial=2500.0)  
        #
        ctn_pores_rho = dlg.view.AddCreateContainer('StaticBox', ctn_prop_pores, 
                label='Rho(m/s)', orient=wx.VERTICAL, proportion=1, 
                flag=wx.EXPAND|wx.TOP, border=5)
        dlg.view.AddTextCtrl(ctn_pores_rho, proportion=0, flag=wx.EXPAND|wx.TOP, 
                             border=5, widget_name='pores_rho', initial=2.2)  
        #    
    
    dlg.view.SetSize((400, 580))
    result = dlg.view.ShowModal()

    try:
        disableAll = wx.WindowDisabler()
        wait = wx.BusyInfo("Creating model. Wait...")
        if result == wx.ID_OK:
            results = dlg.get_results()  
            
            print(results)


            am = OM.new('acoustic_2d_model', 
                        image_uid=image.uid,
                        dx=results.get('x_spacing'), 
                        dy=results.get('y_spacing'), 
                        name=results.get('model_name'))
            result = OM.add(am)
            
            print ('result acoustic_2d_model:', result, args, kwargs)
    

    
            layer1 = OM.new('geolayer', value=values[0], 
                    vp=results.get('matrix_vp'), rho=results.get('matrix_rho'),
                    name="Layer 1")
            result = OM.add(layer1, am.uid)
            print ('result layer 1:', result)
            
            
            if values.size == 2:
                layer2 = OM.new('geolayer', value=values[1], 
                    vp=results.get('pores_vp'), rho=results.get('pores_rho'), 
                    name="Layer 2")
                result = OM.add(layer2, am.uid)
                print ('result layer 2:', result)    
    
    

            
            
    except Exception as e:
        print ('ERROR [on_create_model]:', str(e))
        raise
    finally:
        del wait
        del disableAll
        UIM.remove(dlg.uid)