Пример #1
0
 def __init__(self, parent=None, id=-1, locals=None):
     wx.Panel.__init__(self, parent, id)
     self.shell = Shell(parent=self, locals=locals)
     #self.crust= Crust(parent=self,locals=locals)
     #self.shell = self.crust.shell
     #self.shell.SetSize(wxSize(800,100))
     EVT_SIZE(self, self.OnSize)
Пример #2
0
    def __init__(self, parent):
        self.__layout_frame = parent
        self.__context = parent.GetContext()

        # create GUI
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Python Console',
                          size=(500, 300),
                          style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.CAPTION
                          | wx.CLOSE_BOX | wx.SYSTEM_MENU)

        menu_bar = wx.MenuBar()
        menu = wx.Menu()
        menu_run_script = menu.Append(wx.NewId(), '&Run Script\tAlt-R',
                                      'Run a script in the console.')
        menu_bar.Append(menu, '&Shell')
        self.SetMenuBar(menu_bar)

        self.__shell = Shell(self)

        # set up what user is given to work with
        self.__shell.interp.locals = {'context': self.__context}

        self.Bind(wx.EVT_CLOSE,
                  lambda evt: self.Hide())  # Hide instead of closing
        self.Bind(wx.EVT_MENU, self.OnRunScript)
Пример #3
0
class PanelCompiler(
        wx.Panel, ):
    def __init__(self, parent):

        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour("3399FF")

        self.button = wx.Button(self,
                                label="Compilar",
                                pos=(35, 110),
                                size=(80, 50))
        self.Bind(wx.EVT_BUTTON, self.Compilar, self.button)

        self.button_2 = wx.Button(self,
                                  wx.ID_OK,
                                  label="Enviar",
                                  pos=(35, 170),
                                  size=(80, 50))
        self.Bind(wx.EVT_BUTTON, self.Enviar, self.button_2)

        self.grid_panel = wx.Panel(self, pos=(200, 20), size=(620, 300))

        self.shell = PyShell(self.grid_panel)
        self.shell.write("prueba")
        dimensionador = wx.BoxSizer(wx.VERTICAL)
        dimensionador.Add(self.shell, 1, wx.EXPAND | wx.ALL, border=10)
        self.grid_panel.SetSizer(dimensionador)

    def Compilar(self, event):
        print "Compilando"

    def Enviar(self, event):
        print "Enviado"
Пример #4
0
class PanelCompiler(wx.Panel,):
    def __init__(self, parent):
        
        wx.Panel.__init__(self, parent)
	self.SetBackgroundColour("3399FF")
                
        self.button = wx.Button(self, label="Compilar", pos=(35, 110), size=(80,50))
        self.Bind(wx.EVT_BUTTON, self.Compilar,self.button)

        self.button_2 = wx.Button(self, wx.ID_OK, label="Enviar", pos=(35, 170),size=(80,50))
        self.Bind(wx.EVT_BUTTON, self.Enviar,self.button_2)
        
        self.grid_panel = wx.Panel(self,pos=(200,20),size=(620,300))
         
        self.shell = PyShell(self.grid_panel)
        self.shell.write("prueba")
        dimensionador = wx.BoxSizer(wx.VERTICAL) 
        dimensionador.Add(self.shell,1 ,wx.EXPAND| wx.ALL,border=10)
        self.grid_panel.SetSizer(dimensionador)
     

    def Compilar(self,event):
        print "Compilando"

       

    def Enviar(self,event):
        print "Enviado"
Пример #5
0
class ShellPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.shell = Shell(self)
        self.shell.clear()

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.shell, 1, wx.GROW)
        # self.sizer.Add(wx.StaticText(self, -1, 'Linestyle: '), 0)

        self.SetSizer(self.sizer)
        self.Layout()
        self.Fit()
class MapFrame(wx.Frame):
    def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition,
                 size=(900, 500), style=wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX, name="Frame"):
        super(MapFrame, self).__init__(parent, id, title, pos, size, style, name)

        # Attributes
        self.panel = wx.Panel(self, id=wx.ID_ANY, pos=wx.DefaultPosition,
                              size=(900, 500), style=wx.EXPAND, name="")

        vsizer = wx.BoxSizer(wx.HORIZONTAL)
        mapsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer = wx.BoxSizer(wx.VERTICAL)

        img_path = os.path.abspath("./UnsuiGUI/apartmentdesign.jpg")
        bitmap = wx.Bitmap(img_path, type=wx.BITMAP_TYPE_JPEG)
        img = wx.StaticBitmap(self.panel, wx.ID_ANY, bitmap=bitmap)

        self.start_button = wx.Button(self.panel, label="Start")
        self.load_button = wx.Button(self.panel, label="Load")
        self.load_button.Disable()
        self.end_button = wx.Button(self.panel, label="Quit")
        self.start_button.Bind(wx.EVT_BUTTON, self.OnStart)
        self.load_button.Bind(wx.EVT_BUTTON, self.OnLoad)
        self.end_button.Bind(wx.EVT_BUTTON, self.QuitButton)

        self.shell = PyShell(self.panel, -1, size=(400, -1))
        self.shell.clear()
        self.shell.SetLexer(wx.stc.STC_LEX_NULL)
        self.shell.redirectStdin(True)
        self.shell.redirectStdout(True)
        self.shell.SetInsertionPointEnd()
        self.shell.Bind(wx.EVT_COMMAND_ENTER, self.OnEnter)

        textsizer.Add(self.shell, 5, wx.EXPAND | wx.TE_MULTILINE, 5)
        mapsizer.Add(img, 5, wx.EXPAND | wx.ALIGN_CENTER, 5)

        mapsizerbuttonsizer = wx.BoxSizer(wx.HORIZONTAL)
        mapsizerbuttonsizer.Add(self.start_button, 5, wx.ALIGN_LEFT, 5)
        mapsizerbuttonsizer.Add(self.load_button, 5, wx.ALIGN_LEFT, 5)
        mapsizerbuttonsizer.Add(self.end_button, 5, wx.ALIGN_LEFT, 5)

        mapsizer.Add(mapsizerbuttonsizer, 0, wx.EXPAND|wx.ALIGN_CENTER, 5)
        vsizer.Add(mapsizer, 0, wx.EXPAND | wx.ALIGN_LEFT, 5)
        vsizer.Add(textsizer, 0, wx.EXPAND | wx.ALIGN_RIGHT, 5)

        self.panel.SetSizer(vsizer)

    def OnStart(self, evt):
        self.load_button.Enable()
        self.shell.execStartupScript("Unsui.py")

    def OnLoad(self, evt):
        self.shell.Execute("load")

    def QuitButton(self, evt):
        sys.exit()

    def OnEnter(self, evt):
        self.shell.ScrollToEnd()
Пример #7
0
 def CreateShell(self):
     ctrl=Shell(parent=self)
     ctrl.redirectStdout(redirect=True)
     ctrl.redirectStdin(redirect=True)
     ctrl.redirectStderr(redirect=True)
     init_printing(use_unicode=False)
          
     return ctrl
Пример #8
0
    def __init__(self, parent, phbst, **kwargs):
        """
        Args:
            parent:
                parent window.
            phbst:
                `PhbstFile` instance.
        """
        super(PhbstFileTab, self).__init__(parent, -1, **kwargs)
        self.phbst = phbst
        self.phdos_file = None

        splitter = wx.SplitterWindow(self, id=-1, style=wx.SP_3D)
        splitter.SetSashGravity(0.95)

        self.qpoints_panel = KpointsPanel(splitter, phbst.structure, phbst.qpoints)

        # Add Python shell
        msg = "PHBST_File object is accessible via the phbst variable. Use phbst.<TAB> to access the list of methods."
        msg = marquee(msg, width=len(msg) + 8, mark="#")
        msg = "#"*len(msg) + "\n" + msg + "\n" + "#"*len(msg) + "\n"

        pyshell = Shell(splitter, introText=msg, locals={"phbst": self.phbst})
        splitter.SplitHorizontally(self.qpoints_panel, pyshell)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND, 5)
        self.SetSizerAndFit(sizer)
Пример #9
0
    def __init__(self, parent, giface, id=wx.ID_ANY, simpleEditorHandler=None, **kwargs):
        self.parent = parent
        self.giface = giface

        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        self.intro = _("Welcome to wxGUI Interactive Python Shell %s") % VERSION + "\n\n" + \
            _("Type %s for more GRASS scripting related information.") % "\"help(gs)\"" + "\n" + \
            _("Type %s to add raster or vector to the layer tree.") % "\"AddLayer()\"" + "\n\n"
        self.shell = PyShell(parent=self, id=wx.ID_ANY,
                             introText=self.intro,
                             locals={'gs': grass,
                                     'AddLayer': self.AddLayer})

        sys.displayhook = self._displayhook

        self.btnClear = Button(self, wx.ID_CLEAR)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnClear.SetToolTip(_("Delete all text from the shell"))

        self.simpleEditorHandler = simpleEditorHandler
        if simpleEditorHandler:
            self.btnSimpleEditor = Button(
                self, id=wx.ID_ANY, label=_("Simple &editor"))
            self.btnSimpleEditor.Bind(wx.EVT_BUTTON, simpleEditorHandler)
            self.btnSimpleEditor.SetToolTip(
                _("Open a simple Python code editor"))

        self._layout()
Пример #10
0
    def __init__(self, parent, sigres, **kwargs):
        """
        Args:
            parent:
                parent window.
            sigres:
                `SigresFile` object
        """
        super(SigresFileTab, self).__init__(parent, -1, **kwargs)
        self.sigres = sigres

        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetSashGravity(0.95)

        self.skb_panel = SpinKpointBandPanel(splitter, sigres.structure, sigres.nsppol, sigres.gwkpoints, sigres.max_gwbstop,
                                             bstart=sigres.min_gwbstart)

        # Set the callback for double click on k-point row..
        self.Bind(self.skb_panel.MYEVT_SKB_ACTIVATED, self.onShowQPTable)

        # Add Python shell
        msg = "SIGRES_File object is accessible via the sigres variable. Use sigres.<TAB> to access the list of methods."
        msg = marquee(msg, width=len(msg) + 8, mark="#")
        msg = "#"*len(msg) + "\n" + msg + "\n" + "#"*len(msg) + "\n"

        pyshell = Shell(splitter, introText=msg, locals={"sigres": sigres})
        splitter.SplitHorizontally(self.skb_panel, pyshell)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND, 5)
        self.SetSizerAndFit(sizer)
Пример #11
0
    def __init__(self, parent, mdf_file, **kwargs):
        """
        Args:
            parent:
                parent window.
            mdf_file:
        """
        super(MdfFileTab, self).__init__(parent, -1, **kwargs)
        self.mdf_file = mdf_file

        splitter = wx.SplitterWindow(self, id=-1, style=wx.SP_3D)
        splitter.SetSashGravity(0.95)

        self.qpoints_panel = MdfQpointsPanel(splitter, mdf_file)

        # Add Python shell
        msg = "MDF_object is accessible via the mdf_file variable. Use mdf_file.<TAB> to access the list of methods."
        msg = marquee(msg, width=len(msg) + 8, mark="#")
        msg = "#" * len(msg) + "\n" + msg + "\n" + "#" * len(msg) + "\n"

        # FIXME <Error>: CGContextRestoreGState: invalid context 0x0
        pyshell = Shell(splitter, introText=msg, locals={"mdf_file": mdf_file})
        splitter.SplitHorizontally(self.qpoints_panel, pyshell)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND, 5)
        self.SetSizerAndFit(sizer)
Пример #12
0
 def __init__(self, parent):
     wx.Panel.__init__(self, parent)
     self.intro = "Interactive Phase Retrieval Suite"
     self.shell = Shell(parent=self, id=wx.ID_ANY, introText=self.intro)
     self.shell.zoom(2)
     self.shell.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.shell)
     self.ih = 0
     sizer = wx.BoxSizer(wx.VERTICAL)
     sizer.Add(self.shell,
               1,
               flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
               border=2)
     sizer.Fit(self)
     self.SetSizer(sizer)
     self.SetAutoLayout(True)
     self.Layout()
Пример #13
0
    def __init__(self, parent, wfk, **kwargs):
        """
        Args:
            parent:
                parent window.
            wfk:
        """
        super(WfkFileTab, self).__init__(parent, -1, **kwargs)
        self.wfk = wfk

        splitter = wx.SplitterWindow(self, id=-1, style=wx.SP_3D)
        splitter.SetSashGravity(0.95)

        self.skb_panel = skb_panel = SpinKpointBandPanel(
            splitter, wfk.structure, wfk.nsppol, wfk.kpoints, wfk.mband)

        # Set the callback for double click on k-point row..
        self.Bind(skb_panel.MYEVT_SKB_ACTIVATED, self.onVisualizeSKB)

        # Add Python shell
        msg = "WFK_File object is accessible via the wfk variable. Use wfk.<TAB> to access the list of methods."
        msg = marquee(msg, width=len(msg) + 8, mark="#")
        msg = "#" * len(msg) + "\n" + msg + "\n" + "#" * len(msg) + "\n"

        # FIXME <Error>: CGContextRestoreGState: invalid context 0x0
        pyshell = Shell(splitter, introText=msg, locals={"wfk": self.wfk})
        splitter.SplitHorizontally(self.skb_panel, pyshell)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND, 5)
        self.SetSizerAndFit(sizer)
Пример #14
0
    def __init__(self, parent, gsr, **kwargs):
        """
        Args:
            parent:
                parent window.
            gsr:
                `GsrFile` instance.
        """
        super(GsrFileTab, self).__init__(parent, -1, **kwargs)
        self.gsr = gsr

        splitter = wx.SplitterWindow(self, id=-1, style=wx.SP_3D)
        splitter.SetSashGravity(0.95)

        self.kpoints_panel = KpointsPanel(splitter, gsr.structure, gsr.kpoints)

        # Add Python shell
        msg = "GSR_File object is accessible via the gsr variable. Use gsr.<TAB> to access the list of methods."
        msg = marquee(msg, width=len(msg) + 8, mark="#")
        msg = "#" * len(msg) + "\n" + msg + "\n" + "#" * len(msg) + "\n"

        pyshell = Shell(splitter, introText=msg, locals={"gsr": self.gsr})
        splitter.SplitHorizontally(self.kpoints_panel, pyshell)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND, 5)
        self.SetSizerAndFit(sizer)
Пример #15
0
    def __init__(self, parent, giface, id=wx.ID_ANY, simpleEditorHandler=None, **kwargs):
        self.parent = parent
        self.giface = giface

        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        self.intro = _("Welcome to wxGUI Interactive Python Shell %s") % VERSION + "\n\n" + \
            _("Type %s for more GRASS scripting related information.") % "\"help(grass)\"" + "\n" + \
            _("Type %s to add raster or vector to the layer tree.") % "\"AddLayer()\"" + "\n\n"
        self.shell = PyShell(parent=self, id=wx.ID_ANY,
                             introText=self.intro,
                             locals={'grass': grass,
                                     'AddLayer': self.AddLayer})

        sys.displayhook = self._displayhook

        self.btnClear = wx.Button(self, wx.ID_CLEAR)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnClear.SetToolTipString(_("Delete all text from the shell"))

        self.simpleEditorHandler = simpleEditorHandler
        if simpleEditorHandler:
            self.btnSimpleEditor = wx.Button(
                self, id=wx.ID_ANY, label=_("Simple &editor"))
            self.btnSimpleEditor.Bind(wx.EVT_BUTTON, simpleEditorHandler)
            self.btnSimpleEditor.SetToolTipString(
                _("Open a simple Python code editor"))

        self._layout()
Пример #16
0
class ConsoleDlg(wx.Frame):
    def __init__(self, parent):
        self.__layout_frame = parent
        self.__context = parent.GetContext()

        # create GUI
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Python Console',
                          size=(500, 300),
                          style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.CAPTION
                          | wx.CLOSE_BOX | wx.SYSTEM_MENU)

        menu_bar = wx.MenuBar()
        menu = wx.Menu()
        menu_run_script = menu.Append(wx.NewId(), '&Run Script\tAlt-R',
                                      'Run a script in the console.')
        menu_bar.Append(menu, '&Shell')
        self.SetMenuBar(menu_bar)

        self.__shell = Shell(self)

        # set up what user is given to work with
        self.__shell.interp.locals = {'context': self.__context}

        self.Bind(wx.EVT_CLOSE,
                  lambda evt: self.Hide())  # Hide instead of closing
        self.Bind(wx.EVT_MENU, self.OnRunScript)

    def OnRunScript(self, evt):
        # Loop until user saves or cancels
        dlg = wx.FileDialog(self,
                            'Run Python Script',
                            wildcard='Python Scripts (*.py)|*.py',
                            style=wx.FD_OPEN | wx.FD_CHANGE_DIR)
        dlg.ShowModal()
        ret = dlg.GetReturnCode()
        fp = dlg.GetPath()
        dlg.Destroy()

        if ret == wx.ID_CANCEL:
            return
        self.__shell.write('Running Script... ' + fp)
        self.__shell.run('execfile(\'%s\')' % fp)
Пример #17
0
    def __init__(self, scrapefile, win, parent=None, *a, **kw):
        """
        @param scrapefile the config file to use
        @param win the window object (may be none)
        """
        super(ConfigBuilder, self).__init__(parent, *a, **kw)

        self.SetTitle("profile builder: %s" % scrapefile)

        self.win = win
        self.scrapefile = scrapefile
        self.use_simple = True

        self.bmp = wx.StaticBitmap(self, size=(win.size if win else (792, 546)))  # @TODO: parametrize

        vars = {'self': self}
        vars.update(self.__dict__)
        self.shell = Shell(self, locals = vars,
                           introText="SnakeEyes v0.0a\n")
        self.shell.AppendText("REF: ''.join(sorted(self.scraper['chat_box'].tool.font.data.values()))")

        self.refresh = wx.Button(self, wx.NewId(), "refresh")
        self.refresh.Bind(wx.EVT_BUTTON, self.on_refresh_button)

        self.make_scraper()
        self.live_data = ScrapeDataCtrl(self.scraper, self)
        self.live_data.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_item)

        if self.win is None:
            self.ticking = False
        else:
            self.timer = wx.Timer()
            self.timer.Bind(wx.EVT_TIMER, self.on_tick)
            self.ticking = True
            self.timer.Start(500, wx.TIMER_CONTINUOUS)

        # this is just so the mono image stands out
        self.SetBackgroundColour(wx.Colour(0x33, 0x33, 0x99))
        self.SetForegroundColour(wx.Colour(0xFF, 0xFF, 0xFF))

        self.values = {}

        self.layout()
        self.Show()
Пример #18
0
 def __init__(self, parent):
     wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, 
                             pos = wx.DefaultPosition, size = wx.Size( 500,300 ), 
                             style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
     shell = Shell(self, locals=cmds)
     bSizer = wx.BoxSizer( wx.VERTICAL )
     bSizer.Add( shell, 1, wx.EXPAND|wx.ALL, 5 )
     self.SetSizer(bSizer)
     cmds['plgs'] = Macros()
     shell.run('# numpy(np) and scipy.ndimage(ndimg) has been imported!\n')
     shell.run('# plgs.run_name() to call a ImagePy plugin.\n')
     shell.run('# IPy is avalible here, and curips() to get the current ImagePlus, update() to redraw.\n')
Пример #19
0
class ShellFrame(wx.Panel):
    def __init__(self, parent=None, id=-1, locals=None):
        wx.Panel.__init__(self, parent, id)
        self.shell = Shell(parent=self, locals=locals)
        #self.crust= Crust(parent=self,locals=locals)
        #self.shell = self.crust.shell
        #self.shell.SetSize(wxSize(800,100))
        EVT_SIZE(self, self.OnSize)

    def OnSize(self, event):
        self.shell.SetSize(self.GetClientSizeTuple())
Пример #20
0
    def __init__(self,
                 parent,
                 giface,
                 id=wx.ID_ANY,
                 simpleEditorHandler=None,
                 **kwargs):
        self.parent = parent
        self.giface = giface

        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        self.intro = (
            _("Welcome to wxGUI Interactive Python Shell %s") % VERSION +
            "\n\n" +
            _("Type %s for more GRASS scripting related information.") %
            '"help(gs)"' + "\n" +
            _("Type %s to add raster or vector to the layer tree.") %
            "\"AddLayer('map_name')\"" + "\n\n")

        shellargs = dict(
            parent=self,
            id=wx.ID_ANY,
            introText=self.intro,
            locals={
                "gs": grass,
                "AddLayer": self.AddLayer,
                "help": self.Help
            },
        )
        # useStockId (available since wxPython 4.0.2) should be False on macOS
        if sys.platform == "darwin" and CheckWxVersion([4, 0, 2]):
            shellargs["useStockId"] = False
        self.shell = PyShell(**shellargs)
        if IsDark():
            SetDarkMode(self.shell)

        sys.displayhook = self._displayhook

        self.btnClear = ClearButton(self)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnClear.SetToolTip(_("Delete all text from the shell"))

        self.simpleEditorHandler = simpleEditorHandler
        if simpleEditorHandler:
            self.btnSimpleEditor = Button(self,
                                          id=wx.ID_ANY,
                                          label=_("Simple &editor"))
            self.btnSimpleEditor.Bind(wx.EVT_BUTTON, simpleEditorHandler)
            self.btnSimpleEditor.SetToolTip(
                _("Open a simple Python code editor"))

        self._layout()
Пример #21
0
 def __init__(self, parent=None):
     """ConsoleWindow(parent=None) -> wx.MDIChildFrame"""
     super(ConsoleWindow, self).__init__(parent,
                                         title=self.title,
                                         style=wx.DEFAULT_FRAME_STYLE)
     self.parent = parent
     self.namespace = {
         '__name__':
         '__main__',
         'print':
         lambda *args, **kwargs: print(*args, **kwargs, file=self.console),
         'input':
         self.parent.InputFunc
     }
     self.console = Shell(self)
     self.Bind(wx.EVT_CLOSE, self.OnClose)
     self.Show(False)
Пример #22
0
 def __init__(self, parent):
     wx.Panel.__init__(self,
                       parent,
                       id=wx.ID_ANY,
                       pos=wx.DefaultPosition,
                       size=wx.Size(500, 300),
                       style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
     cmds['app'] = parent
     cmds['get_img'] = lambda name=None, app=self: self.app.get_img()
     cmds['update'] = lambda app=self: self.app.get_img().update()
     shell = Shell(self, locals=cmds)
     bSizer = wx.BoxSizer(wx.VERTICAL)
     bSizer.Add(shell, 1, wx.EXPAND | wx.ALL, 5)
     self.SetSizer(bSizer)
     cmds['plgs'] = Macros()
     shell.run('# plgs.run_name() to call a ImagePy plugin.\n')
     shell.run(
         '# app is avalible here, and get_img() to get the current ImagePlus, update() to redraw.\n'
     )
Пример #23
0
class PyShellWindow(wx.Panel):
    """Python Shell Window"""

    def __init__(self, parent, giface, id=wx.ID_ANY, simpleEditorHandler=None, **kwargs):
        self.parent = parent
        self.giface = giface

        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        self.intro = _("Welcome to wxGUI Interactive Python Shell %s") % VERSION + "\n\n" + \
            _("Type %s for more GRASS scripting related information.") % "\"help(gs)\"" + "\n" + \
            _("Type %s to add raster or vector to the layer tree.") % "\"AddLayer()\"" + "\n\n"
        self.shell = PyShell(parent=self, id=wx.ID_ANY,
                             introText=self.intro,
                             locals={'gs': grass,
                                     'AddLayer': self.AddLayer})

        sys.displayhook = self._displayhook

        self.btnClear = Button(self, wx.ID_CLEAR)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnClear.SetToolTip(_("Delete all text from the shell"))

        self.simpleEditorHandler = simpleEditorHandler
        if simpleEditorHandler:
            self.btnSimpleEditor = Button(
                self, id=wx.ID_ANY, label=_("Simple &editor"))
            self.btnSimpleEditor.Bind(wx.EVT_BUTTON, simpleEditorHandler)
            self.btnSimpleEditor.SetToolTip(
                _("Open a simple Python code editor"))

        self._layout()

    def _displayhook(self, value):
        print(value)  # do not modify __builtin__._

    def _layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        sizer.Add(self.shell, proportion=1,
                  flag=wx.EXPAND)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        if self.simpleEditorHandler:
            btnSizer.Add(self.btnSimpleEditor, proportion=0,
                         flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
        btnSizer.AddStretchSpacer()
        btnSizer.Add(self.btnClear, proportion=0,
                     flag=wx.EXPAND, border=5)
        sizer.Add(btnSizer, proportion=0,
                  flag=wx.ALL | wx.EXPAND, border=5)

        sizer.Fit(self)
        sizer.SetSizeHints(self)

        self.SetSizer(sizer)

        self.Fit()
        self.SetAutoLayout(True)
        self.Layout()

    def AddLayer(self, name, ltype='auto'):
        """Add selected map to the layer tree

        :param name: name of raster/vector map to be added
        :param type: map type ('raster', 'vector', 'auto' for autodetection)
        """
        fname = None
        if ltype == 'raster' or ltype != 'vector':
            # check for raster
            fname = grass.find_file(name, element='cell')['fullname']
            if fname:
                ltype = 'raster'
                lcmd = 'd.rast'

        if not fname and (ltype == 'vector' or ltype != 'raster'):
            # if not found check for vector
            fname = grass.find_file(name, element='vector')['fullname']
            if fname:
                ltype = 'vector'
                lcmd = 'd.vect'

        if not fname:
            return _("Raster or vector map <%s> not found") % (name)

        self.giface.GetLayerTree().AddLayer(ltype=ltype,
                                            lname=fname,
                                            lchecked=True,
                                            lcmd=[lcmd, 'map=%s' % fname])
        if ltype == 'raster':
            return _('Raster map <%s> added') % fname

        return _('Vector map <%s> added') % fname

    def OnClear(self, event):
        """Delete all text from the shell
        """
        self.shell.clear()
        self.shell.showIntro(self.intro)
        self.shell.prompt()
Пример #24
0
class FenetrePrincipale(wx.Frame):
    def __init__(self, config):
        wx.Frame.__init__(self,
                          None,
                          id=wx.ID_ANY,
                          title=tourbillon.__nom__,
                          size=(640, 400),
                          style=wx.DEFAULT_FRAME_STYLE)
        self.SetBackgroundColour(images.couleur('grille'))
        self.config = config

        # Création d'un gestionnaire de fenetres pour la gestion des fenêtres flottantes
        self._mgr = aui.AuiManager(
            self, aui.AUI_MGR_ALLOW_FLOATING | aui.AUI_MGR_TRANSPARENT_HINT
            | aui.AUI_MGR_TRANSPARENT_DRAG | aui.AUI_MGR_ALLOW_ACTIVE_PANE)

        # Fenêtre informations montrée
        self.fenetre_affichage = dlginfo.DialogueInformations(
            self, self.config)
        self.affichage_visible = False
        self.fenetre_affichage.Bind(wx.EVT_CLOSE, self.masquer_info)

        # Icon
        self.SetIcon(images.TourBillon_icon())

        # Créer la barre de menu
        self.barre_menu = barres.BarreMenu(self)
        self.SetMenuBar(self.barre_menu)

        # Créer la barre de statut
        self.barre_etat = barres.BarreEtat(self)
        self.SetStatusBar(self.barre_etat)

        # Créer la barre des boutons (pas la guerre)
        self.barre_bouton = barres.BarreBouton(self)
        self._mgr.AddPane(
            self.barre_bouton,
            aui.AuiPaneInfo().Name("controles").Top().CaptionVisible(
                False).MinSize(wx.Size(-1, 60)).DockFixed().Floatable(False))

        # Créer la grille
        if self.config.get_typed('INTERFACE', 'image'):
            chemin_image = glob(configdir('fond_perso*'))[0]
        else:
            chemin_image = ""
        self.grille = grl.GrillePanel(self, images.bitmap(chemin_image))
        self.barre_menu.FindItemById(barres.ID_STATISTIQUES).Check(
            self.config.get_typed('INTERFACE', 'afficher_statistiques'))
        self.afficher_statistiques(None)
        self._mgr.AddPane(self.grille,
                          aui.AuiPaneInfo().Name("grille").CenterPane())

        # Creation d'un shell Python (utile pour le debug)
        self.shell = Shell(self,
                           introText='',
                           locals={
                               'intf': self,
                               'trb': tournoi.tournoi(),
                               'cfg': self.config,
                               'cst': cst
                           },
                           InterpClass=None,
                           startupScript=None,
                           execStartupScript=True)
        self.shell.SetSize((600, 200))
        self._mgr.AddPane(
            self.shell,
            aui.AuiPaneInfo().Name('shell').Caption("Python Shell").Bottom().
            CloseButton(True).MaximizeButton(True).Hide())
        self.barre_menu.FindItemById(barres.ID_SHELL).Check(
            self.config.get_typed('INTERFACE', 'afficher_shell'))
        self.afficher_shell(None)

        # Effectuer les connections sur les evenements

        # ... de la barre de menu
        self.Bind(wx.EVT_MENU, self.nouveau, id=wx.ID_NEW)
        self.Bind(wx.EVT_MENU, self.ouvrir_demande, id=wx.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.enregistrer, id=wx.ID_SAVE)
        self.Bind(wx.EVT_MENU, self.enregistrer_sous, id=wx.ID_SAVEAS)
        self.Bind(wx.EVT_MENU,
                  self.apercu_avant_impression,
                  id=wx.ID_PREVIEW_PRINT)
        self.Bind(wx.EVT_MENU, self.imprimer, id=wx.ID_PRINT)
        self.Bind(wx.EVT_MENU, self.quitter, id=wx.ID_EXIT)

        self.Bind(wx.EVT_MENU,
                  self.afficher_statistiques,
                  id=barres.ID_STATISTIQUES)
        self.Bind(wx.EVT_MENU, self.afficher_info, id=barres.ID_INFO)
        self.Bind(wx.EVT_MENU, self.afficher_tirage, id=barres.ID_TIRAGE)
        self.Bind(wx.EVT_MENU, self.afficher_shell, id=barres.ID_SHELL)

        self.Bind(wx.EVT_MENU, self.nouvelle_equipe, id=barres.ID_NOUVELLE_E)
        self.Bind(wx.EVT_MENU, self.modifier_equipe, id=barres.ID_MODIFIER_E)
        self.Bind(wx.EVT_MENU, self.supprimer_equipe, id=barres.ID_SUPPRIMER_E)
        self.Bind(wx.EVT_MENU, self.nouvelle_partie, id=barres.ID_NOUVELLE_P)
        self.Bind(wx.EVT_MENU, self.supprimer_partie, id=barres.ID_SUPPRIMER_P)
        self.Bind(wx.EVT_MENU, self.entrer_resultats, id=barres.ID_RESULTATS)
        self.Bind(wx.EVT_MENU, self.classement, id=barres.ID_CLASSEMENT)
        self.Bind(wx.EVT_MENU, self.preferences, id=wx.ID_PREFERENCES)

        self.Bind(wx.EVT_MENU, self.info_systeme, id=wx.ID_PROPERTIES)
        self.Bind(wx.EVT_MENU, self.a_propos_de, id=wx.ID_ABOUT)

        # ... de la barre de contrôle
        self.Bind(wx.EVT_BUTTON, self.afficher_partie_prec,
                  self.barre_bouton.btn_precedente)
        self.Bind(wx.EVT_BUTTON, self.afficher_partie_suiv,
                  self.barre_bouton.btn_suivante)

        self.Bind(wx.EVT_BUTTON, self.enregistrer, id=wx.ID_SAVE)
        self.Bind(wx.EVT_BUTTON, self.afficher_info, id=barres.ID_INFO)
        self.Bind(wx.EVT_BUTTON, self.afficher_tirage, id=barres.ID_TIRAGE)
        self.Bind(wx.EVT_BUTTON, self.nouvelle_equipe, id=barres.ID_NOUVELLE_E)
        self.Bind(wx.EVT_BUTTON, self.nouvelle_partie, id=barres.ID_NOUVELLE_P)
        self.Bind(wx.EVT_BUTTON, self.entrer_resultats, id=barres.ID_RESULTATS)
        self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN,
                  self.grille.rechercher_suivant,
                  id=wx.ID_FIND)
        self.Bind(wx.EVT_TEXT_ENTER,
                  self.grille.rechercher_suivant,
                  id=wx.ID_FIND)
        self.Bind(wx.EVT_TEXT, self.grille.rechercher, id=wx.ID_FIND)
        self.Bind(evt.EVT_MENU_RECHERCHE, self.grille.chg_recherche_colonne,
                  self.barre_bouton)

        # ... des autres événements
        self.Bind(wx.EVT_CLOSE, self.quitter)
        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.masquer_shell)
        self.Bind(evt.EVT_RAFRAICHIR, self.rafraichir)
        self.grille.Bind(grl.grid.EVT_GRID_CELL_LEFT_DCLICK,
                         self.grille_double_click)
        self.grille.Bind(grl.grid.EVT_GRID_CELL_RIGHT_CLICK,
                         self.grille_contexte)
        self.grille.Bind(wx.EVT_KEY_DOWN, self.grille_enter)

        # Rafraichir
        self._mgr.Update()
        self.Layout()
        wx.PostEvent(self, evt.RafraichirEvent(self.GetId()))

    def grille_enter(self, event):
        """
        Ouvre le fenêtre correspondant à l'activitée en cours
        pour l'équipe selectionnée si la touche [ENTER] et
        pressée (voir la fonction 'grille_double_click' pour
        plus de details).
        """
        if event.GetKeyCode() == wx.WXK_RETURN:
            self.grille_double_click(event)
        else:
            event.Skip()

    def grille_double_click(self, event):
        """
        Ouvre le fenêtre correspondant à l'activitée en cours
        pour l'équipe selectionnée:
            - "Ajout de Joueur" si le tournoi n'est pas commencé
            - "Entrer les Résultats" si le tournoi est commencé
        """
        if tournoi.tournoi() is not None:
            if self.grille.selection() is not None:
                statut = tournoi.tournoi().statut
                if statut == cst.T_INSCRIPTION or (
                        statut == cst.T_ATTEND_TIRAGE
                        and tournoi.tournoi().nb_parties() == 0):
                    self.modifier_equipe(event)
                else:
                    self.entrer_resultats(event)

    def grille_contexte(self, event):
        """
        Ouvre le menu contextuel
        """
        if tournoi.tournoi() is not None:
            if self.grille.selection() is not None:
                menu = barres.cree_contexte_menu()
                self.PopupMenu(
                    menu,
                    wx.GetMousePosition() -
                    self.GetPosition() - (self.grille.GetPosition().x / 2,
                                          self.grille.GetPosition().y / 2))
                menu.Destroy()

    def rafraichir(self, event):
        """
        Appelle la methode 'rafraichir' de chaque widget qui a besoin de l'être.
        """
        t = tournoi.tournoi()

        # Titre
        if tournoi.FICHIER_TOURNOI is not None:
            self.SetTitle("%s - %s" %
                          (tourbillon.__nom__, tournoi.FICHIER_TOURNOI))
        else:
            self.SetTitle(tourbillon.__nom__)

        # Barre de menu
        if event.quoi == 'menu' or event.quoi == 'tout':
            if t is None:
                nom = ''
            else:
                nom = 'Tournoi  du %s' % t.debut.strftime('%d/%m/%Y')

            self.barre_menu._rafraichir()
            self.barre_bouton._rafraichir(nom)

        # Barre d'état
        if event.quoi == 'etat' or event.quoi == 'tout':
            if t is None:
                self.barre_etat._rafraichir('', 0, 0, 0, False)
            else:
                # Indication équipe incomplète
                nb_incompletes = 0
                num_partie = self.barre_bouton.numero()
                if self.barre_bouton.numero() > 0:
                    for equipe in tournoi.tournoi().partie(
                            num_partie).equipes():
                        if equipe.resultat(num_partie).etat is None:
                            nb_incompletes += 1
                self.barre_etat._rafraichir(
                    t.debut.strftime('%Hh%M'), t.nb_parties(), t.nb_equipes(),
                    nb_incompletes / tournoi.tournoi().equipes_par_manche,
                    t.modifie)

        p = self.barre_bouton.numero()

        # Limite de raffraichissement
        limite = None
        if self.config.get_typed('INTERFACE', 'CUMULE_STATISTIQUES') == 1:
            limite = p

        # Equipes
        if event.quoi == 'tout':
            if tournoi.tournoi() is None:
                self.grille._rafraichir()
            else:
                for equipe in tournoi.tournoi().equipes():
                    self.grille._rafraichir(equipe=equipe,
                                            partie=p,
                                            partie_limite=limite)

        elif event.quoi.startswith('equipe'):
            num = int(event.quoi.split('_')[1])
            self.grille._rafraichir(equipe=tournoi.tournoi().equipe(num),
                                    partie=p,
                                    partie_limite=limite)

        # Classement
        if event.quoi == 'classement' or event.quoi == 'tout':
            if tournoi.tournoi() is not None:
                avec_victoires = self.config.get_typed('TOURNOI',
                                                       'CLASSEMENT_VICTOIRES')
                avec_joker = self.config.get_typed('TOURNOI',
                                                   'CLASSEMENT_JOKER')
                avec_duree = self.config.get_typed('TOURNOI',
                                                   'CLASSEMENT_DUREE')
                self.grille._rafraichir(
                    classement=tournoi.tournoi().classement(
                        avec_victoires, avec_joker, avec_duree, limite))
            else:
                self.grille._rafraichir(classement={})

        # Informations
        if t is not None:
            try:
                self.fenetre_affichage._rafraichir(t.statut)
            except wx._core.PyAssertionError:
                # HACK wxpython 3.0 sur Windows 8.1: wxTextMeasure::BeginMeasuring()
                # must not be used with non-native wxDCs
                # A resoudre, mais comment?????
                logger.info(
                    "Je ne peux pas rafraichir la fenêtre d'information aux joueurs (wxpython + Windows bug)"
                )
        # fond
        if event.quoi == 'fond':
            if self.config.get_typed('INTERFACE', 'image'):
                chemin_image = glob(configdir('fond_perso*'))[0]
            else:
                chemin_image = ""
            self.grille.chg_fond(images.bitmap(chemin_image))

    def nouveau(self, event):
        ret = self.enregister_demande()

        if ret != wx.ID_CANCEL:
            if self.config.get_typed("INTERFACE",
                                     'NOUVEAU_AFFICHE_PREFERENCES'):
                ret = self.preferences(evt.PreferencesEvent(self.GetId(), 1))
            else:
                ret = wx.ID_OK

            if ret == wx.ID_OK:
                self.shell.interp.locals['trb'] = tournoi.nouveau_tournoi(
                    self.config.get_typed("TOURNOI", "EQUIPES_PAR_MANCHE"),
                    self.config.get_typed("TOURNOI", "POINTS_PAR_MANCHE"),
                    self.config.get_typed("TOURNOI", "JOUEURS_PAR_EQUIPE"))

                # Rafraichir
                self.grille.effacer()
                self.barre_bouton.chg_partie()
                wx.PostEvent(self, evt.RafraichirEvent(self.GetId()))

                logger.info(u"Il est %s, un nouveau tournoi commence..." %
                            tournoi.tournoi().debut.strftime('%Hh%M'))

    def ouvrir_demande(self, event):
        """
        Demander à l'utilisateur quel fichier il souhaite ouvrir.
        """
        ret = self.enregister_demande()

        if ret != wx.ID_CANCEL:
            if tournoi.FICHIER_TOURNOI is not None:
                l = os.path.split(tournoi.FICHIER_TOURNOI)
                d = l[0]
                f = l[1]
            else:
                d = self.config.get('INTERFACE', 'ENREGISTREMENT')
                f = ''

            dlg = wx.FileDialog(self,
                                message="Ouvrir",
                                defaultDir=d,
                                defaultFile=f,
                                wildcard=FILTRE_FICHIER,
                                style=wx.OPEN)
            ret = dlg.ShowModal()

            if ret == wx.ID_OK:
                fichier = dlg.GetPath()
                self.ouvrir(fichier)
            dlg.Destroy()

    def ouvrir(self, fichier):
        self.shell.interp.locals['trb'] = tournoi.charger_tournoi(fichier)

        # Rafraichir
        self.barre_bouton.chg_partie(tournoi.tournoi().nb_parties())
        self.grille.effacer()
        self.grille.ajout_equipe(*tournoi.tournoi().equipes())
        wx.PostEvent(self, evt.RafraichirEvent(self.GetId()))

        self.SetTitle("%s - %s" % (tourbillon.__nom__, fichier))
        logger.info(u"Chargé, prêt à jouer mon commandant!")

    def enregister_demande(self):
        """
        Demander à l'utilisateur s'il veux enregristrer le
        tournoi courrant.
        """
        continuer = wx.ID_OK
        if tournoi.tournoi() is not None:
            if tournoi.tournoi().modifie:
                dlg = wx.MessageDialog(
                    self,
                    u"Le tournoi en cours n'est pas enregistré, si vous cliquez sur NON, les données seront perdues.",
                    caption=u"Voulez-vous enregistrer le tournoi en cours?",
                    style=wx.CANCEL | wx.YES | wx.NO | wx.ICON_QUESTION)
                ret = dlg.ShowModal()
                dlg.Destroy()
                if ret == wx.ID_YES:
                    continuer = self.enregistrer_sous(None)
                elif ret == wx.ID_CANCEL:
                    continuer = wx.ID_CANCEL

        return continuer

    def enregistrer(self, event):
        if tournoi.FICHIER_TOURNOI is None:
            self.enregistrer_sous(event)
        else:
            tournoi.enregistrer_tournoi()

        # Rafraichir
        wx.PostEvent(self, evt.RafraichirEvent(self.GetId(), 'etat'))

    def enregistrer_auto(self):
        if self.config.get_typed(
                'INTERFACE',
                'ENREGISTREMENT_AUTO') and tournoi.FICHIER_TOURNOI is not None:
            self.enregistrer(None)

    def enregistrer_sous(self, event):
        if tournoi.FICHIER_TOURNOI is not None:
            l = os.path.split(tournoi.FICHIER_TOURNOI)
            d = l[0]
            f = l[1]
        else:
            d = self.config.get('INTERFACE', 'ENREGISTREMENT')
            f = u"tournoi_billon_%s.yml" % datetime.now().strftime('%d/%m/%Y')
        dlg = wx.FileDialog(self,
                            message="Enregistrer",
                            defaultDir=d,
                            defaultFile=f,
                            wildcard=FILTRE_FICHIER,
                            style=wx.SAVE)
        ret = dlg.ShowModal()

        if ret == wx.ID_OK:
            fichier = dlg.GetPath()
            _p, ext = os.path.splitext(fichier)
            if ext not in ['.trb', '.yml']:
                fichier += '.yml'
            tournoi.enregistrer_tournoi(fichier)

            # Rafraichir
            wx.PostEvent(self, evt.RafraichirEvent(self.GetId(), 'etat'))
            logger.info(u"C'est dans la boîte.")

        dlg.Destroy()
        return ret

    def apercu_avant_impression(self, event):
        avec_victoires = self.config.get_typed('TOURNOI',
                                               'CLASSEMENT_VICTOIRES')
        avec_joker = self.config.get_typed('TOURNOI', 'CLASSEMENT_JOKER')
        avec_duree = self.config.get_typed('TOURNOI', 'CLASSEMENT_DUREE')
        dlg = dlgim.DialogueImprimer(
            self,
            tournoi.tournoi().classement(avec_victoires, avec_joker,
                                         avec_duree))
        dlg.Preview()

    def imprimer(self, event):
        avec_victoires = self.config.get_typed('TOURNOI',
                                               'CLASSEMENT_VICTOIRES')
        avec_joker = self.config.get_typed('TOURNOI', 'CLASSEMENT_JOKER')
        avec_duree = self.config.get_typed('TOURNOI', 'CLASSEMENT_DUREE')
        dlg = dlgim.DialogueImprimer(
            self,
            tournoi.tournoi().classement(avec_victoires, avec_joker,
                                         avec_duree))
        dlg.Print()

    def quitter(self, event):
        ret = self.enregister_demande()

        if ret != wx.ID_CANCEL:
            # Enregistrer la géométrie de l'interface
            if self.IsMaximized():
                self.config.set('INTERFACE', 'MAXIMISER', 'True')
            else:
                self.config.set('INTERFACE', 'MAXIMISER', 'False')
                self.config.set(
                    'INTERFACE', 'GEOMETRIE',
                    str(self.GetPositionTuple() + self.GetSizeTuple()))
            self.config.set(
                'INTERFACE', 'afficher_statistiques',
                str(
                    self.barre_menu.FindItemById(
                        barres.ID_STATISTIQUES).IsChecked()))
            self.config.set(
                'INTERFACE', 'afficher_shell',
                str(self.barre_menu.FindItemById(barres.ID_SHELL).IsChecked()))

            self.Destroy()

    def afficher_statistiques(self, event):
        """
        Affiche la grille des statistiques du
        tournoi en cours.
        """
        valeur = self.barre_menu.FindItemById(
            barres.ID_STATISTIQUES).IsChecked()
        self.grille.afficher_statistiques(valeur)

    def afficher_shell(self, event):
        """
        Affiche un shell Python qui donne accées à l'ensemble des variables
        du programme.
        """
        valeur = self.barre_menu.FindItemById(barres.ID_SHELL).IsChecked()
        self._mgr.GetPane('shell').Show(valeur)
        self._mgr.Update()

    def masquer_shell(self, event):
        """Masquer le shell (appelé lorsque l'utilisateur click sur le croix
        rouge de la fenêtre)
        """
        self.barre_menu.FindItemById(barres.ID_SHELL).Check(False)
        event.Skip()

    def afficher_info(self, event):
        """Afficher la fenêtre d'information joueurs.
        """
        self.affichage_visible = not self.affichage_visible

        if self.affichage_visible:
            self.barre_bouton.FindItemById(barres.ID_INFO).Check(
                self.affichage_visible)
            self.barre_menu.FindItemById(barres.ID_INFO).Check(
                self.affichage_visible)
            self.fenetre_affichage.Show()
            self.SetFocus()
        else:
            self.fenetre_affichage.Close()

    def masquer_info(self, event):
        """Masquer la fenêtre d'information joueurs (appelé lorsque l'utilisateur
        click sur le croix rouge de la fenêtre)
        """
        self.affichage_visible = False
        self.barre_bouton.FindItemById(barres.ID_INFO).Check(False)
        self.barre_menu.FindItemById(barres.ID_INFO).Check(False)
        event.Skip()

    def afficher_tirage(self, event):
        num = self.barre_bouton.numero()

        dlg = dlgpa.DialogueAfficherTirage(self, num)
        dlg.Show()

    def afficher_partie_prec(self, event):
        if tournoi.tournoi() is None:
            self.barre_bouton.chg_partie()
        else:
            try:
                tournoi.tournoi().partie(self.barre_bouton.numero() - 1)
                self.barre_bouton.chg_partie(self.barre_bouton.numero() - 1)
            except ValueError, e:
                self.barre_etat.SetStatusText(unicode(e))

            # Rafraichir
            wx.PostEvent(self, evt.RafraichirEvent(self.GetId()))
Пример #25
0
class PanelScript(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.intro = "Interactive Phase Retrieval Suite"
        self.shell = Shell(parent=self, id=wx.ID_ANY, introText=self.intro)
        self.shell.zoom(2)
        self.shell.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.shell)
        self.ih = 0
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.shell,
                  1,
                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
                  border=2)
        sizer.Fit(self)
        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        self.Layout()

    def OnKeyDown(self, event):
        if self.shell.AutoCompActive():
            event.Skip()
            return
        key = event.GetKeyCode()
        if key == wx.WXK_RETURN:
            self.ih = 0
            self.shell.processLine()
            self.shell.clearCommand()
        elif key == wx.WXK_UP:
            if self.ih < len(self.shell.history):
                self.ih += 1
                self.shell.clearCommand()
                self.shell.write(self.shell.history[(self.ih - 1)])
        elif key == wx.WXK_DOWN:
            self.shell.clearCommand()
            self.ih -= 1
            if self.ih > 0:
                self.shell.write(self.shell.history[self.ih - 1])
            else:
                self.ih = 0
        else:
            event.Skip()
Пример #26
0
class PyShellWindow(wx.Panel):
    """Python Shell Window"""
    def __init__(self, parent, id = wx.ID_ANY, **kwargs):
        self.parent = parent # GMFrame
        
        wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
        
        self.intro = _("Welcome to wxGUI Interactive Python Shell %s") % VERSION + "\n\n" + \
            _("Type %s for more GRASS scripting related information.") % "\"help(grass)\"" + "\n" + \
            _("Type %s to add raster or vector to the layer tree.") % "\"AddLayer()\"" + "\n\n"
        self.shell = PyShell(parent = self, id = wx.ID_ANY,
                             introText = self.intro,
                             locals={'grass': grass,
                                     'AddLayer': self.AddLayer})
        
        sys.displayhook = self._displayhook
        
        self.btnClear = wx.Button(self, wx.ID_CLEAR)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnClear.SetToolTipString(_("Delete all text from the shell"))
                
        self._layout()
        
    def _displayhook(self, value):
        print value # do not modify __builtin__._
        
    def _layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)
        
        sizer.Add(item = self.shell, proportion = 1,
                  flag = wx.EXPAND)
        
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(item = self.btnClear, proportion = 0,
                     flag = wx.EXPAND | wx.RIGHT, border = 5)
        sizer.Add(item = btnSizer, proportion = 0,
                  flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
        
        sizer.Fit(self)
        sizer.SetSizeHints(self)
        
        self.SetSizer(sizer)
        
        self.Fit()
        self.SetAutoLayout(True)        
        self.Layout()

    def AddLayer(self, name, ltype = 'auto'):
        """Add selected map to the layer tree

        :param name: name of raster/vector map to be added
        :param type: map type ('raster', 'vector', 'auto' for autodetection)
        """
        fname = None
        if ltype == 'raster' or ltype != 'vector':
            # check for raster
            fname = grass.find_file(name, element = 'cell')['fullname']
            if fname:
                ltype = 'raster'
                lcmd = 'd.rast'
        
        if not fname and (ltype == 'vector' or ltype != 'raster'):
            # if not found check for vector
            fname = grass.find_file(name, element = 'vector')['fullname']
            if fname:
                ltype = 'vector'
                lcmd = 'd.vect'
        
        if not fname:
            return _("Raster or vector map <%s> not found") % (name)
        
        self.parent.GetLayerTree().AddLayer(ltype = ltype,
                                            lname = fname,
                                            lchecked = True,
                                            lcmd = [lcmd, 'map=%s' % fname])
        if ltype == 'raster':
            return _('Raster map <%s> added') % fname
        
        return _('Vector map <%s> added') % fname
    
    def OnClear(self, event):
        """Delete all text from the shell
        """
        self.shell.clear()
        self.shell.showIntro(self.intro)
        self.shell.prompt()
Пример #27
0
class PyShellWindow(wx.Panel):
    """Python Shell Window"""
    def __init__(self,
                 parent,
                 giface,
                 id=wx.ID_ANY,
                 simpleEditorHandler=None,
                 **kwargs):
        self.parent = parent
        self.giface = giface

        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        self.intro = (
            _("Welcome to wxGUI Interactive Python Shell %s") % VERSION +
            "\n\n" +
            _("Type %s for more GRASS scripting related information.") %
            '"help(gs)"' + "\n" +
            _("Type %s to add raster or vector to the layer tree.") %
            "\"AddLayer('map_name')\"" + "\n\n")

        shellargs = dict(
            parent=self,
            id=wx.ID_ANY,
            introText=self.intro,
            locals={
                "gs": grass,
                "AddLayer": self.AddLayer,
                "help": self.Help
            },
        )
        # useStockId (available since wxPython 4.0.2) should be False on macOS
        if sys.platform == "darwin" and CheckWxVersion([4, 0, 2]):
            shellargs["useStockId"] = False
        self.shell = PyShell(**shellargs)
        if IsDark():
            SetDarkMode(self.shell)

        sys.displayhook = self._displayhook

        self.btnClear = ClearButton(self)
        self.btnClear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btnClear.SetToolTip(_("Delete all text from the shell"))

        self.simpleEditorHandler = simpleEditorHandler
        if simpleEditorHandler:
            self.btnSimpleEditor = Button(self,
                                          id=wx.ID_ANY,
                                          label=_("Simple &editor"))
            self.btnSimpleEditor.Bind(wx.EVT_BUTTON, simpleEditorHandler)
            self.btnSimpleEditor.SetToolTip(
                _("Open a simple Python code editor"))

        self._layout()

    def _displayhook(self, value):
        print(value)  # do not modify __builtin__._

    def _layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        sizer.Add(self.shell, proportion=1, flag=wx.EXPAND)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        if self.simpleEditorHandler:
            btnSizer.Add(
                self.btnSimpleEditor,
                proportion=0,
                flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
                border=5,
            )
        btnSizer.AddStretchSpacer()
        btnSizer.Add(self.btnClear, proportion=0, flag=wx.EXPAND, border=5)
        sizer.Add(btnSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)

        sizer.Fit(self)
        sizer.SetSizeHints(self)

        self.SetSizer(sizer)

        self.Fit()
        self.SetAutoLayout(True)
        self.Layout()

    def AddLayer(self, name, ltype="auto"):
        """Add selected map to the layer tree

        :param name: name of raster/vector map to be added
        :param type: map type ('raster', 'vector', 'auto' for autodetection)
        """
        fname = None
        if ltype == "raster" or ltype != "vector":
            # check for raster
            fname = grass.find_file(name, element="cell")["fullname"]
            if fname:
                ltype = "raster"
                lcmd = "d.rast"

        if not fname and (ltype == "vector" or ltype != "raster"):
            # if not found check for vector
            fname = grass.find_file(name, element="vector")["fullname"]
            if fname:
                ltype = "vector"
                lcmd = "d.vect"

        if not fname:
            return _("Raster or vector map <%s> not found") % (name)

        self.giface.GetLayerTree().AddLayer(ltype=ltype,
                                            lname=fname,
                                            lchecked=True,
                                            lcmd=[lcmd, "map=%s" % fname])
        if ltype == "raster":
            return _("Raster map <%s> added") % fname

        return _("Vector map <%s> added") % fname

    def Help(self, obj):
        """Override help() function

        :param obj object/str: generate the help of the given object

        return str: help str of the given object
        """
        with redirect_stdout(io.StringIO()) as f:
            help(obj)
        return f.getvalue()

    def OnClear(self, event):
        """Delete all text from the shell"""
        self.shell.clear()
        self.shell.showIntro(self.intro)
        self.shell.prompt()
Пример #28
0
    def __init__(self, config):
        wx.Frame.__init__(self,
                          None,
                          id=wx.ID_ANY,
                          title=tourbillon.__nom__,
                          size=(640, 400),
                          style=wx.DEFAULT_FRAME_STYLE)
        self.SetBackgroundColour(images.couleur('grille'))
        self.config = config

        # Création d'un gestionnaire de fenetres pour la gestion des fenêtres flottantes
        self._mgr = aui.AuiManager(
            self, aui.AUI_MGR_ALLOW_FLOATING | aui.AUI_MGR_TRANSPARENT_HINT
            | aui.AUI_MGR_TRANSPARENT_DRAG | aui.AUI_MGR_ALLOW_ACTIVE_PANE)

        # Fenêtre informations montrée
        self.fenetre_affichage = dlginfo.DialogueInformations(
            self, self.config)
        self.affichage_visible = False
        self.fenetre_affichage.Bind(wx.EVT_CLOSE, self.masquer_info)

        # Icon
        self.SetIcon(images.TourBillon_icon())

        # Créer la barre de menu
        self.barre_menu = barres.BarreMenu(self)
        self.SetMenuBar(self.barre_menu)

        # Créer la barre de statut
        self.barre_etat = barres.BarreEtat(self)
        self.SetStatusBar(self.barre_etat)

        # Créer la barre des boutons (pas la guerre)
        self.barre_bouton = barres.BarreBouton(self)
        self._mgr.AddPane(
            self.barre_bouton,
            aui.AuiPaneInfo().Name("controles").Top().CaptionVisible(
                False).MinSize(wx.Size(-1, 60)).DockFixed().Floatable(False))

        # Créer la grille
        if self.config.get_typed('INTERFACE', 'image'):
            chemin_image = glob(configdir('fond_perso*'))[0]
        else:
            chemin_image = ""
        self.grille = grl.GrillePanel(self, images.bitmap(chemin_image))
        self.barre_menu.FindItemById(barres.ID_STATISTIQUES).Check(
            self.config.get_typed('INTERFACE', 'afficher_statistiques'))
        self.afficher_statistiques(None)
        self._mgr.AddPane(self.grille,
                          aui.AuiPaneInfo().Name("grille").CenterPane())

        # Creation d'un shell Python (utile pour le debug)
        self.shell = Shell(self,
                           introText='',
                           locals={
                               'intf': self,
                               'trb': tournoi.tournoi(),
                               'cfg': self.config,
                               'cst': cst
                           },
                           InterpClass=None,
                           startupScript=None,
                           execStartupScript=True)
        self.shell.SetSize((600, 200))
        self._mgr.AddPane(
            self.shell,
            aui.AuiPaneInfo().Name('shell').Caption("Python Shell").Bottom().
            CloseButton(True).MaximizeButton(True).Hide())
        self.barre_menu.FindItemById(barres.ID_SHELL).Check(
            self.config.get_typed('INTERFACE', 'afficher_shell'))
        self.afficher_shell(None)

        # Effectuer les connections sur les evenements

        # ... de la barre de menu
        self.Bind(wx.EVT_MENU, self.nouveau, id=wx.ID_NEW)
        self.Bind(wx.EVT_MENU, self.ouvrir_demande, id=wx.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.enregistrer, id=wx.ID_SAVE)
        self.Bind(wx.EVT_MENU, self.enregistrer_sous, id=wx.ID_SAVEAS)
        self.Bind(wx.EVT_MENU,
                  self.apercu_avant_impression,
                  id=wx.ID_PREVIEW_PRINT)
        self.Bind(wx.EVT_MENU, self.imprimer, id=wx.ID_PRINT)
        self.Bind(wx.EVT_MENU, self.quitter, id=wx.ID_EXIT)

        self.Bind(wx.EVT_MENU,
                  self.afficher_statistiques,
                  id=barres.ID_STATISTIQUES)
        self.Bind(wx.EVT_MENU, self.afficher_info, id=barres.ID_INFO)
        self.Bind(wx.EVT_MENU, self.afficher_tirage, id=barres.ID_TIRAGE)
        self.Bind(wx.EVT_MENU, self.afficher_shell, id=barres.ID_SHELL)

        self.Bind(wx.EVT_MENU, self.nouvelle_equipe, id=barres.ID_NOUVELLE_E)
        self.Bind(wx.EVT_MENU, self.modifier_equipe, id=barres.ID_MODIFIER_E)
        self.Bind(wx.EVT_MENU, self.supprimer_equipe, id=barres.ID_SUPPRIMER_E)
        self.Bind(wx.EVT_MENU, self.nouvelle_partie, id=barres.ID_NOUVELLE_P)
        self.Bind(wx.EVT_MENU, self.supprimer_partie, id=barres.ID_SUPPRIMER_P)
        self.Bind(wx.EVT_MENU, self.entrer_resultats, id=barres.ID_RESULTATS)
        self.Bind(wx.EVT_MENU, self.classement, id=barres.ID_CLASSEMENT)
        self.Bind(wx.EVT_MENU, self.preferences, id=wx.ID_PREFERENCES)

        self.Bind(wx.EVT_MENU, self.info_systeme, id=wx.ID_PROPERTIES)
        self.Bind(wx.EVT_MENU, self.a_propos_de, id=wx.ID_ABOUT)

        # ... de la barre de contrôle
        self.Bind(wx.EVT_BUTTON, self.afficher_partie_prec,
                  self.barre_bouton.btn_precedente)
        self.Bind(wx.EVT_BUTTON, self.afficher_partie_suiv,
                  self.barre_bouton.btn_suivante)

        self.Bind(wx.EVT_BUTTON, self.enregistrer, id=wx.ID_SAVE)
        self.Bind(wx.EVT_BUTTON, self.afficher_info, id=barres.ID_INFO)
        self.Bind(wx.EVT_BUTTON, self.afficher_tirage, id=barres.ID_TIRAGE)
        self.Bind(wx.EVT_BUTTON, self.nouvelle_equipe, id=barres.ID_NOUVELLE_E)
        self.Bind(wx.EVT_BUTTON, self.nouvelle_partie, id=barres.ID_NOUVELLE_P)
        self.Bind(wx.EVT_BUTTON, self.entrer_resultats, id=barres.ID_RESULTATS)
        self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN,
                  self.grille.rechercher_suivant,
                  id=wx.ID_FIND)
        self.Bind(wx.EVT_TEXT_ENTER,
                  self.grille.rechercher_suivant,
                  id=wx.ID_FIND)
        self.Bind(wx.EVT_TEXT, self.grille.rechercher, id=wx.ID_FIND)
        self.Bind(evt.EVT_MENU_RECHERCHE, self.grille.chg_recherche_colonne,
                  self.barre_bouton)

        # ... des autres événements
        self.Bind(wx.EVT_CLOSE, self.quitter)
        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.masquer_shell)
        self.Bind(evt.EVT_RAFRAICHIR, self.rafraichir)
        self.grille.Bind(grl.grid.EVT_GRID_CELL_LEFT_DCLICK,
                         self.grille_double_click)
        self.grille.Bind(grl.grid.EVT_GRID_CELL_RIGHT_CLICK,
                         self.grille_contexte)
        self.grille.Bind(wx.EVT_KEY_DOWN, self.grille_enter)

        # Rafraichir
        self._mgr.Update()
        self.Layout()
        wx.PostEvent(self, evt.RafraichirEvent(self.GetId()))
Пример #29
0
class ConfigBuilder(wx.Frame):
    """
    Interactively build a scraping profile.
    """
    def __init__(self, scrapefile, win, parent=None, *a, **kw):
        """
        @param scrapefile the config file to use
        @param win the window object (may be none)
        """
        super(ConfigBuilder, self).__init__(parent, *a, **kw)

        self.SetTitle("profile builder: %s" % scrapefile)

        self.win = win
        self.scrapefile = scrapefile
        self.use_simple = True

        self.bmp = wx.StaticBitmap(self, size=(win.size if win else (792, 546)))  # @TODO: parametrize

        vars = {'self': self}
        vars.update(self.__dict__)
        self.shell = Shell(self, locals = vars,
                           introText="SnakeEyes v0.0a\n")
        self.shell.AppendText("REF: ''.join(sorted(self.scraper['chat_box'].tool.font.data.values()))")

        self.refresh = wx.Button(self, wx.NewId(), "refresh")
        self.refresh.Bind(wx.EVT_BUTTON, self.on_refresh_button)

        self.make_scraper()
        self.live_data = ScrapeDataCtrl(self.scraper, self)
        self.live_data.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_item)

        if self.win is None:
            self.ticking = False
        else:
            self.timer = wx.Timer()
            self.timer.Bind(wx.EVT_TIMER, self.on_tick)
            self.ticking = True
            self.timer.Start(500, wx.TIMER_CONTINUOUS)

        # this is just so the mono image stands out
        self.SetBackgroundColour(wx.Colour(0x33, 0x33, 0x99))
        self.SetForegroundColour(wx.Colour(0xFF, 0xFF, 0xFF))

        self.values = {}

        self.layout()
        self.Show()

    def layout(self):
        """Arranges the controls inside the window."""
        box = wx.BoxSizer(wx.VERTICAL)

        # top row
        row = wx.BoxSizer(wx.HORIZONTAL)
        row.Add(wx.StaticText(self, -1, self.scrapefile))
        row.Add(self.refresh)
        row.AddSpacer(20)
        row.Add(wx.StaticText(self, -1, "hwnd:"))
        if self.win is not None:
            row.Add(wx.TextCtrl(self, -1, str(self.win.hwnd)))
        box.Add(row)

        # image itself
        row = wx.BoxSizer(wx.HORIZONTAL)
        row.Add(self.bmp, 0, wx.EXPAND)
        self.live_data.SetSizeHints(200, -1)
        row.Add(self.live_data, 1, wx.EXPAND)
        box.Add(row, 0, wx.EXPAND)

        # bottom row (shell)
        self.shell.SetSizeHints(500,-1)
        box.Add(self.shell, 1, wx.EXPAND)
        self.SetSizerAndFit(box)

    def on_item(self, e):
        item = self.live_data.GetItem(e.m_itemIndex, 0).GetText() # item, column

        reload(glyph_gui)
        reload(font_gui)

        wx_bmp = convert.img_to_wxbmp(self.scraper[item].last_snapshot)
        dlg = glyph_gui.GlyphDialog(wx_bmp, self, -1,
                               title="current glyph in region '%s'" % item)
        dlg.ShowModal()

    def on_refresh_button(self, e):
        self.live_coding_hook()
        self.reload_modules()
        self.make_scraper()
        self.set_image(self.screen)

    @staticmethod
    def reload_modules():
        reload(snakeeyes.config)
        reload(snakeeyes.Region)
        reload(snakeeyes)
        reload(glyph_gui)
        reload(font_gui)


    def live_coding_hook(self):
        # this is a little livecoding thing:
        pass #exec open("c:/temp/textregion.py").read() in locals()

    def make_scraper(self):
        self.scraper = snakeeyes.load_config(self.scrapefile)

    def collect_values(self, img):
        try:
            self.scraper.collect_values(img)
        except snakeeyes.fontdata.NeedTraining as e:
            self.request_training(e.font, e.glyph)

    def paste_snaps(self, onto):
        for region in self.scraper.values():
            onto.paste(region.last_snapshot, region.rect.pos)

    def update_image(self):
        """
        this captures the new image from the window.
        """
        meth = self.win.as_image_simple if self.use_simple else self.win.as_image
        self.set_image(meth())

    def set_image(self, image):
        """
        this takes any image as a parameter
        """
        self.screen = image
        img = ImageOps.grayscale(self.screen).convert("RGB")

        try:
            self.values = self.scraper.collect_values(self.screen)
        except NeedTraining as e:
            self.request_training(e.font, e.glyph)
        else:
            self.paste_snaps(onto=img)

        self.live_data.repopulate()
        self.scraper.draw_boxes(img)
        self.bmp.SetBitmap(convert.img_to_wxbmp(img))

        self.Refresh()

    def on_tick(self, e):
        if self.ticking:
            self.update_image()

    def request_training(self, font, glyph):
        if not self.ticking: return
        self.ticking = False
        reload(glyph_gui)
        wx_bmp = convert.img_to_wxbmp(glyph)

        dlg = glyph_gui.GlyphDialog(wx_bmp, self, -1,
                                    "train me!")
        dlg.when_done = self.training_done
        dlg.font = font
        dlg.glyph = glyph
        dlg.Show()

    def training_done(self, dlg, which_button):
        if which_button == wx.ID_OK:
            self.dlg = dlg # only for the shell
            print("OK! learning new value!", dlg.txt.GetValue())
            dlg.font.learn(dlg.glyph, dlg.txt.GetValue())
        self.ticking = True
Пример #30
0
 def __init__(self,parent):
     #introText="""We could use ipython ?"""
     Shell.__init__(self,parent,introText="")
Пример #31
0
 def __init__(self, parent):
     wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
     sh = wx.BoxSizer(wx.VERTICAL)
     sh.Add(Shell(self, -1), -1, wx.ALL|wx.EXPAND, border = 0)
     self.SetSizer(sh)
Пример #32
0
 def __init__(self, parent):
     #introText="""We could use ipython ?"""
     Shell.__init__(self, parent, introText="")