Exemple #1
0
    'the quick brown fox jumps over the lazy dog',  # demo string
    'Tip of the Day',  # wx built in translation
    'Warning',  # wx built in translation
]

[
    wxID_LANGUAGESELECTPANEL,
    wxID_LANGUAGESELECTPANELENGLISHBASECH,
    wxID_LANGUAGESELECTPANELLANGCTRLCONTAINER,
    wxID_LANGUAGESELECTPANELLANGFILTERRB,
    wxID_LANGUAGESELECTPANELSTATICLINE1,
    wxID_LANGUAGESELECTPANELSTATICTEXT1,
    wxID_LANGUAGESELECTPANELSTATICTEXT2,
    wxID_LANGUAGESELECTPANELSTATICTEXT3,
    wxID_LANGUAGESELECTPANELTRANSLATEDST,
] = wx.NewIdRef(9)


class LanguageSelectPanel(wx.Panel):
    def _init_coll_boxSizer3_Items(self, parent):
        # generated method, don't edit

        parent.Add(self.langCtrlContainer, 1, flag=wx.GROW, border=0)
        parent.Add(wx.Size(8, 8), flag=0, border=0)
        parent.Add(self.langFilterRB, 0, flag=0, border=0)

    def _init_coll_flexGridSizer1_Growables(self, parent):
        # generated method, don't edit

        parent.AddGrowableRow(1)
        parent.AddGrowableCol(0)
    def SelectProp(self, evt):
        """
		"""

        row, col = evt.GetRow(), evt.GetCol()

        table = self.GetTable()

        typ = table.dataTypes[row][1]
        prop = self.GetCellValue(row, 0)

        if prop == 'fill' or re.findall(
                "[.]*color[.]*", prop, flags=re.IGNORECASE):
            val = self.GetCellValue(row, 1)
            dlg = wx.ColourDialog(self.parent)
            dlg.GetColourData().SetChooseFull(True)
            if dlg.ShowModal() == wx.ID_OK:
                data = dlg.GetColourData()
                val = str([RGBToHEX(data.GetColour().Get())])
                self.SetCellValue(row, 1, val)
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'font':
            val = eval(self.GetCellValue(row, 1))
            default_font = wx.Font(val[0], val[1], val[2], val[3], False,
                                   val[4])
            data = wx.FontData()
            if sys.platform == 'win32':
                data.EnableEffects(True)
            data.SetAllowSymbols(False)
            data.SetInitialFont(default_font)
            data.SetRange(10, 30)
            dlg = wx.FontDialog(self.parent, data)
            if dlg.ShowModal() == wx.ID_OK:
                data = dlg.GetFontData()
                font = data.GetChosenFont()
                color = data.GetColour()
                val = [
                    font.GetPointSize(),
                    font.GetFamily(),
                    font.GetStyle(),
                    font.GetWeight(),
                    font.GetFaceName()
                ]
                self.SetCellValue(row, 1, str(val))
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'label':

            d = LabelGUI.LabelDialog(self.parent, self.parent.model)
            d.ShowModal()

            self.SetCellValue(row, 1, str(self.parent.model.label))
            self.AcceptProp(row, col)

        elif prop == 'image_path':

            dlg = ib.ImageDialog(self, os.path.join(HOME_PATH))
            dlg.Centre()

            if dlg.ShowModal() == wx.ID_OK:
                val = os.path.normpath(dlg.GetFile())
                if val != self.GetCellValue(row, 1):
                    self.SetCellValue(row, 1, val)
                    self.canvas.UpdateShapes([self.parent.model])
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif 'filename' in str(prop).lower():
            wcd = _('Data files All files (*)|*')
            val = self.GetCellValue(row, 1)
            default_dir = os.path.dirname(val) if os.path.exists(
                os.path.dirname(val)) else HOME_PATH
            dlg = wx.FileDialog(self,
                                message=_("Select file ..."),
                                defaultDir=default_dir,
                                defaultFile="",
                                wildcard=wcd,
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                val = os.path.normpath(dlg.GetPath())
                if val != self.GetCellValue(row, 1):
                    self.SetCellValue(row, 1, val)
                    self.canvas.UpdateShapes([self.parent.model])
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'python_path':

            model = self.parent.model

            ### for .amd or .cmd
            if model.model_path != '':
                wcd = _(
                    'Atomic DEVSimPy model (*.amd)|*.amd|Coupled DEVSimPy model (*.cmd)|*.cmd|All files (*)|*'
                )
            else:
                wcd = _('Python files (*.py)|*.py|All files (*)|*')

            default_dir = os.path.dirname(model.python_path) if os.path.exists(
                os.path.dirname(model.python_path)) else DOMAIN_PATH
            dlg = wx.FileDialog(self,
                                message=_("Select file ..."),
                                defaultDir=default_dir,
                                defaultFile="",
                                wildcard=wcd,
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                new_python_path = os.path.normpath(dlg.GetPath())

                ### if the user would like to load a compressed python file, he just give the name of compressed file that contain the python file
                if zipfile.is_zipfile(new_python_path):
                    zf = zipfile.ZipFile(new_python_path, 'r')
                    new_python_path = os.path.join(new_python_path, [
                        f for f in zf.namelist()
                        if f.endswith('.py') and f != 'plugins.py'
                    ][0])
                    ### update model path
                    model.model_path = os.path.dirname(new_python_path)

                self.SetCellValue(row, 1, new_python_path)

                # behavioral args update (because depends of the new class coming from new python file)
                new_cls = Components.GetClass(new_python_path)

                if inspect.isclass(new_cls):

                    ### update attributes (behavioral ang graphic)
                    old_args = model.args
                    model.args = Components.GetArgs(new_cls)
                    model.SetAttributes(Attributable.GRAPHICAL_ATTR)

                    ### copy of the same args value
                    for k, v in old_args.items():
                        if k in model.args:
                            model.args[k] = v

                    ### TODO: when ScopeGUI and DiskGUI will be amd models, delete this line)
                    ### delete xlabel and ylabel attributes if exist
                    model.RemoveAttribute('xlabel')
                    model.RemoveAttribute('ylabel')
                    ### Update of DEVSimPy model from new python behavioral file (ContainerBlock is not considered because he did not behavioral)
                    if new_cls.__name__ in ('To_Disk', 'MessagesCollector'):
                        model.__class__ = Container.DiskGUI
                    elif new_cls.__name__ == 'QuickScope':
                        model.__class__ = Container.ScopeGUI
                        model.AddAttribute("xlabel")
                        model.AddAttribute("ylabel")
                    elif True in [
                            'DomainStructure' in str(a)
                            for a in new_cls.__bases__
                    ]:
                        model.__class__ = Container.ContainerBlock
                    else:
                        model.__class__ = Container.CodeBlock

                    ### if we change the python file from zipfile we compresse the new python file and we update the python_path value
                    if zipfile.is_zipfile(model.model_path):
                        zf = ZipManager.Zip(model.model_path)
                        zf.Update([new_python_path])

                    ### update flag and color if bad filename
                    if model.bad_filename_path_flag:
                        model.bad_filename_path_flag = False
                else:
                    Container.MsgBoxError(evt, self, new_cls)
                    dlg.Destroy()
                    return False
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif typ == "list":
            frame = ListEditor(self,
                               wx.NewIdRef(),
                               _('List editor'),
                               values=self.GetCellValue(row, 1))
            if frame.ShowModal() == wx.ID_CANCEL:
                self.SetCellValue(row, 1, frame.GetValueAsString())
            else:
                frame.Destroy()

            self.AcceptProp(row, col)

        elif typ == 'dict':
            frame = DictionaryEditor(self,
                                     wx.NewIdRef(),
                                     _('List editor'),
                                     values=self.GetCellValue(row, 1))
            if frame.ShowModal() == wx.ID_CANCEL:
                self.SetCellValue(row, 1, frame.GetValueAsString())
            else:
                frame.Destroy()

            self.AcceptProp(row, col)
        elif 'choice' in typ:
            self.AcceptProp(row, col)
        else:
            pass

        ### all properties grid update (because the python classe has been changed)
        ### here, because OnAcceptProp should be executed before
        if prop == 'python_path':

            ### Update table from new model
            table.UpdateRowBehavioralData(model)
            self.SetTable(table, False)
            self.ForceRefresh()
            self.AutoSizeColumns()

            # code updating
            if isinstance(model, Achievable):
                new_code = CodeCB(self.parent, wx.NewIdRef(), model)
                #self.parent.boxH.Remove(0)
                if hasattr(self.parent, '_boxH'):
                    # DeleteWindows work better in vista
                    if wx.VERSION_STRING < '4.0':
                        self.parent._boxH.DeleteWindows()
                        self.parent._boxH.AddWindow(new_code,
                                                    1,
                                                    wx.EXPAND,
                                                    userData='code')
                    else:
                        self.parent._boxH.Clear()
                        self.parent._boxH.Add(new_code,
                                              1,
                                              wx.EXPAND,
                                              userData='code')

                    self.parent._boxH.Layout()
                else:
                    sys.stdout.write("_boxH is unknown!")
Exemple #3
0
# Author: Christian Brodbeck <*****@*****.**>
"""Eelbrain-specific wx IDs"""
import wx

APYDOC_NEW = wx.NewIdRef()
ATTACH = wx.NewIdRef()

BASELINE_CUSTOM = wx.NewIdRef()
BASELINE_GLOABL_MEAN = wx.NewIdRef()
BASELINE_NONE = wx.NewIdRef()

CANVAS_PANEL_ZOOM = wx.NewIdRef()
CANVAS_PANEL_OVERVIEW = wx.NewIdRef()
CLEAR_CACHE = wx.NewIdRef()
CLEAR_TERMINAL = wx.NewIdRef()
COLOUR_CHOOSER = wx.NewIdRef()
COMMENT = wx.NewIdRef()
COPY_AS_PNG = wx.NewIdRef()

DATASET_ATTACH = wx.NewIdRef()
DATASET_IMPORT = wx.NewIdRef()
DRAW_CROSSHAIRS = wx.NewIdRef()
DUPLICATE = wx.NewIdRef()
DUPLICATE_WITH_OUTPUT = wx.NewIdRef()

EXPERIMENT_LOAD = wx.NewIdRef()
EXPERIMENT_NEW = wx.NewIdRef()
ENABLE_STARTUP_SCRIPT = wx.NewIdRef()
EXEC_DOCUMENT = wx.NewIdRef()
EXEC_DOCUMENT_FROM_DISK = wx.NewIdRef()
EXEC_FILE = wx.NewIdRef()
Exemple #4
0
    def __init__(self):
        if DEBUG: print("FlexTilesFrame.__init__()")

        ### init
        wPos = (0, 20)
        wg = wx.Display(0).GetGeometry()
        wSz = (wg[2], int(wg[3] * 0.9))
        wx.Frame.__init__(
            self,
            None,
            -1,
            "FlexTiles-K v.%s" % (__version__),
            pos=tuple(wPos),
            size=tuple(wSz),
            style=wx.DEFAULT_FRAME_STYLE ^
            (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX),
        )
        self.SetBackgroundColour('#AAAABB')

        ### set app icon
        self.tbIcon = wx.adv.TaskBarIcon(iconType=wx.adv.TBI_DOCK)
        icon = wx.Icon("icon.ico")
        self.tbIcon.SetIcon(icon)

        ##### [begin] setting up attributes -----
        self.wSz = wSz  # window size
        self.fonts = getWXFonts()
        self.flagBlockUI = False  # flag to determine temporary UI block
        pi = self.setPanelInfo()  # set panel info
        self.pi = pi  # panel information
        self.gbs = {}  # for GridBagSizer
        self.panel = {}  # panels
        self.timer = {}  # timers
        self.csvFP = ""  # CSV file path
        self.outputPath = path.join(CWD, "output")  # output file path
        if not path.isdir(self.outputPath): mkdir(self.outputPath)
        self.ani = None  # to store animation info. to run
        self.kD = None  # to store drawing info. (used when in Kandinsky mode)
        self.colors = {}  # some preset colors
        self.colors[
            "ftBGCol"] = "#111111"  # background color of FlexTiles panel
        self.colors["highlightedTile"] = "#eeee33"  # for highlighting a tile
        self.nRows = 8  # number of rows in FlexTiles
        self.nCols = 8  # number of columns in FlexTiles
        self.tileSz = 75  # size in pixels
        ### resize tile-size if it bigger than window size
        if self.nCols * self.tileSz > wSz[0]:
            self.tileSz *= int(wSz[0] / (self.nCols * self.tileSz))
        if self.nRows * self.tileSz > wSz[1]:
            self.tileSz = int(self.tileSz * (wSz[1] /
                                             (self.nRows * self.tileSz)))
        ### load initial tile image
        initTileImg = "tile_init.png"
        self.initTileImg = load_img(initTileImg)
        # store initial (large) image for Kandinsky mode
        self.tileImgLarge = self.initTileImg.Copy()
        # store image for FlexTiles mode
        self.tileImg = self.initTileImg.Copy()
        ### if size doesn't match with desired size, rescale it.
        imgSz = self.tileImg.GetSize()
        if imgSz[0] != self.tileSz or imgSz[1] != self.tileSz:
            self.tileImg = self.tileImg.Rescale(self.tileSz, self.tileSz,
                                                wx.IMAGE_QUALITY_HIGH)
        lX = int(self.wSz[0] / 2 - (self.tileSz * self.nCols) / 2)
        tY = int(self.wSz[1] / 2 - (self.tileSz * self.nRows) / 2)
        # store rect of entire FlexTiles
        self.ftR = [
            lX,  # x1
            tY,  # y1 
            lX + self.tileSz * self.nCols,  # x2 
            tY + self.tileSz * self.nRows
        ]  # y2
        self.idxMouseOn = (None, None)  # row, column indices of tile, where
        # mouse pointer is currently on
        ### initialize angles and click-counters of all tiles
        d = []
        for ri in range(self.nRows):
            d.append([])
            for ci in range(self.nCols):
                #angle = randint(0,3) * 90
                angle = 0
                click = 0
                d[ri].append([angle, click])
        self.ftArr = np.asarray(d, dtype=np.uint16)  # store it as array
        self.ftSeq = []  # to store sequence of tile clicks
        self.progInitTime = time()  # starting time of the program
        self.currMP = None  # current mouse pointer position
        self.flagKandinsky = False  # whether it's in Kandinsky mode
        self.kDBtns = [
            "fill", "line", "rectangle", "circle", "curvyline", "polygon",
            "pencil"
        ]  # button names for Kandinsky mode
        self.selectedDBtn = ""  # selected drawing button name
        self.selectedFCol = "#cccccc"  # selected filling color
        self.selectedSCol = "#0000ff"  # selected stroke color
        self.selectedSThick = 1  # selected stroke thickness
        self.flagFreePencilDrawing = False  # free drawing is on
        self.freePencilDrawingPts = []  # points for free pencil drawing
        ##### [end] setting up attributes -----

        updateFrameSize(self, wSz)

        ### create panels
        for k in pi.keys():
            if k == "lp":
                self.panel[k] = SPanel.ScrolledPanel(self,
                                                     pos=pi[k]["pos"],
                                                     size=pi[k]["sz"],
                                                     style=pi[k]["style"])
            elif k == "mp":
                self.panel[k] = wx.Panel(self,
                                         pos=pi[k]["pos"],
                                         size=pi[k]["sz"],
                                         style=pi[k]["style"])
            self.panel[k].SetBackgroundColour(pi[k]["bgCol"])

        ### set up main-panel
        self.panel["mp"].Bind(wx.EVT_PAINT, self.onPaint)
        self.panel["mp"].Bind(wx.EVT_LEFT_DOWN, self.onLeftDown)
        self.panel["mp"].Bind(wx.EVT_LEFT_UP, self.onLeftUp)
        self.panel["mp"].Bind(wx.EVT_RIGHT_UP, self.onRightClick)
        self.panel["mp"].Bind(wx.EVT_MOTION, self.onMouseMove)

        ##### [begin] set up left panel interface -----
        nCol = 2
        hlSz = (pi["lp"]["sz"][0] - 10, -1
                )  # size of horizontal line separator
        self.gbs["lp"] = wx.GridBagSizer(0, 0)
        row = 0
        col = 0
        sTxt = setupStaticText(self.panel["lp"],
                               label="DrawingTools",
                               font=self.fonts[2],
                               fgColor="#cccccc")
        add2gbs(self.gbs["lp"], sTxt, (row, col), (1, 2))
        row += 1
        for i in range(len(self.kDBtns)):
            bn = self.kDBtns[i].capitalize()  # button name
            btn = wx.Button(self.panel["lp"],
                            -1,
                            size=(45, 45),
                            name="draw%s_btn" % (bn))
            # set image for button
            set_img_for_btn("img_draw%s_off.png" % (bn), btn)
            btn.Bind(wx.EVT_LEFT_DOWN, self.onButtonPressDown)
            add2gbs(self.gbs["lp"], btn, (row, col), (1, 1), bw=5)
            if i % 2 != 0:
                row += 1
                col = 0
            else:
                col += 1
        if len(self.kDBtns) % 2 != 0:
            row += 1
            col = 0
        sTxt = setupStaticText(self.panel["lp"],
                               label="Fill",
                               font=self.fonts[2],
                               fgColor="#cccccc")
        add2gbs(self.gbs["lp"], sTxt, (row, col), (1, 1))
        col += 1
        cpc = wx.ColourPickerCtrl(self.panel["lp"], -1, name="drawFCol_cpc")
        cpc.Bind(wx.EVT_COLOURPICKER_CHANGED, self.onColorPicked)
        cpc.SetColour(self.selectedFCol)
        add2gbs(self.gbs["lp"], cpc, (row, col), (1, 1), bw=0)
        row += 1
        col = 0
        sTxt = setupStaticText(self.panel["lp"],
                               label="Stroke",
                               font=self.fonts[2],
                               fgColor="#cccccc")
        add2gbs(self.gbs["lp"], sTxt, (row, col), (1, 1))
        col += 1
        cpc = wx.ColourPickerCtrl(self.panel["lp"], -1, name="drawSCol_cpc")
        cpc.Bind(wx.EVT_COLOURPICKER_CHANGED, self.onColorPicked)
        cpc.SetColour(self.selectedSCol)
        add2gbs(self.gbs["lp"], cpc, (row, col), (1, 1), bw=0)
        row += 1
        col = 0
        sTxt = setupStaticText(self.panel["lp"],
                               label="Stroke thickness",
                               font=self.fonts[0],
                               fgColor="#cccccc")
        add2gbs(self.gbs["lp"], sTxt, (row, col), (1, 1))
        col += 1
        spin = wx.SpinCtrl(self.panel["lp"],
                           -1,
                           size=(50, -1),
                           min=1,
                           max=50,
                           initial=self.selectedSThick,
                           name='strokeThick_spin',
                           style=wx.SP_ARROW_KEYS | wx.SP_WRAP)
        spin.Bind(wx.EVT_SPINCTRL, self.onSpinCtrl)
        add2gbs(self.gbs["lp"], spin, (row, col), (1, 1))
        row += 1
        col = 0
        add2gbs(self.gbs["lp"],
                wx.StaticLine(self.panel["lp"],
                              -1,
                              size=hlSz,
                              style=wx.LI_HORIZONTAL), (row, col),
                (1, nCol))  # horizontal line separator
        self.panel["lp"].SetSizer(self.gbs["lp"])
        self.gbs["lp"].Layout()
        self.panel["lp"].SetupScrolling()
        self.panel["lp"].Hide()
        ##### [end] set up top panel interface -----

        ### set up menu
        menuBar = wx.MenuBar()
        mainMenu = wx.Menu()
        kModeMenu = mainMenu.Append(wx.Window.NewControlId(),
                                    item="Kandinsky drawing mode\tCTRL+K")
        self.Bind(wx.EVT_MENU, self.onKandinskyMode, kModeMenu)
        saveMenu = mainMenu.Append(wx.Window.NewControlId(),
                                   item="Save\tCTRL+S")
        self.Bind(wx.EVT_MENU, self.onSave, saveMenu)
        quitMenu = mainMenu.Append(wx.Window.NewControlId(),
                                   item="Quit\tCTRL+Q")
        self.Bind(wx.EVT_MENU, self.onClose, quitMenu)
        menuBar.Append(mainMenu, "&FlexTiles")
        self.SetMenuBar(menuBar)

        ### keyboard binding
        kMode_btnId = wx.NewIdRef(count=1)
        save_btnId = wx.NewIdRef(count=1)
        exit_btnId = wx.NewIdRef(count=1)
        self.Bind(wx.EVT_MENU, self.onKandinskyMode, id=kMode_btnId)
        self.Bind(wx.EVT_MENU, self.onSave, id=save_btnId)
        self.Bind(wx.EVT_MENU, self.onClose, id=exit_btnId)
        accel_tbl = wx.AcceleratorTable([
            (wx.ACCEL_CMD, ord('K'), kMode_btnId),
            (wx.ACCEL_CMD, ord('S'), save_btnId),
            (wx.ACCEL_CMD, ord('Q'), exit_btnId),
        ])
        self.SetAcceleratorTable(accel_tbl)

        self.Bind(wx.EVT_CLOSE, self.onClose)
Exemple #5
0
 def _add_item(self, item):
     id_ = wx.NewIdRef()
     self.Append(id_, item.name)
     self.Bind(wx.EVT_MENU, item.callable, id=id_)
Exemple #6
0
    def __init__(self, parent):
        """
			Constructor.
		"""
        wx.Panel.__init__(self, parent)

        ### FileBrowse
        self.plugin_dir = filebrowse.DirBrowseButton(
            self,
            wx.NewIdRef(),
            startDirectory=PLUGINS_PATH,
            labelText=_("Plug-ins directory:"),
            toolTip=_("Change the plug-ins directory"),
            dialogTitle=_("Plug-ins directory..."))
        self.domain_dir = filebrowse.DirBrowseButton(
            self,
            wx.NewIdRef(),
            startDirectory=DOMAIN_PATH,
            labelText=_("Library directory:"),
            toolTip=_("Change the library directory"),
            dialogTitle=_("Libraries directory..."))
        self.out_dir = filebrowse.DirBrowseButton(
            self,
            wx.NewIdRef(),
            startDirectory=OUT_DIR,
            labelText=_("Output directory:"),
            toolTip=_("Change the output directory"),
            dialogTitle=_("Output directory..."))

        self.plugin_dir.SetValue(PLUGINS_PATH)
        self.domain_dir.SetValue(DOMAIN_PATH)
        self.out_dir.SetValue(OUT_DIR)

        ### StaticText
        self.st1 = wx.StaticText(self, wx.NewIdRef(),
                                 _("Number of recent file:"))
        self.st2 = wx.StaticText(self, wx.NewIdRef(), _("Font size:"))
        self.st3 = wx.StaticText(self, wx.NewIdRef(),
                                 _("Deep of history item:"))
        self.st4 = wx.StaticText(self, wx.NewIdRef(), _("wxPython version:"))

        if wx.VERSION_STRING >= '4.0':
            self.st1.SetToolTipString = self.st1.SetToolTip
            self.st2.SetToolTipString = self.st2.SetToolTip
            self.st3.SetToolTipString = self.st3.SetToolTip
            self.st4.SetToolTipString = self.st4.SetToolTip

        self.st1.SetToolTipString(
            _("Feel free to change the length of list defining the recent opened files."
              ))
        self.st2.SetToolTipString(
            _("Feel free to change the font size of DEVSimpy."))
        self.st3.SetToolTipString(
            _("Feel free to change the number of item for undo/redo command."))
        self.st4.SetToolTipString(
            _("Feel free to change the version of wxpython used loaded by DEVSimPy."
              ))

        ### number of opened file
        self.nb_opened_file = wx.SpinCtrl(self, wx.NewIdRef(), '')
        self.nb_opened_file.SetRange(2, 20)
        self.nb_opened_file.SetValue(NB_OPENED_FILE)

        ### Block font size
        self.font_size = wx.SpinCtrl(self, wx.NewIdRef(), '')
        self.font_size.SetRange(2, 20)
        self.font_size.SetValue(FONT_SIZE)

        ### number of undo/redo items
        self.nb_history_undo = wx.SpinCtrl(self, wx.NewIdRef(), '')
        self.nb_history_undo.SetRange(2, 100)
        self.nb_history_undo.SetValue(NB_HISTORY_UNDO)

        ### CheckBox for transparancy
        self.cb1 = wx.CheckBox(self, wx.NewIdRef(), _('Transparency'))
        if wx.VERSION_STRING >= '4.0':
            self.cb1.SetToolTipString = self.cb1.SetToolTip
        self.cb1.SetToolTipString(
            _("Transparency for the detached frame of diagrams"))
        self.cb1.SetValue(builtins.__dict__['TRANSPARENCY'])

        ### CheckBox for notification
        self.cb11 = wx.CheckBox(self, wx.NewIdRef(), _('Notififcations'))
        if wx.VERSION_STRING >= '4.0':
            self.cb11.SetToolTipString = self.cb11.SetToolTip
        self.cb1.SetToolTipString(_("Enable the notification messages"))
        self.cb11.SetValue(builtins.__dict__['NOTIFICATION'])

        ### wxPython version
        wxv = [wx.VERSION_STRING]

        self.cb2 = wx.ComboBox(self,
                               wx.NewIdRef(),
                               GetWXVersionFromIni(),
                               choices=wxv,
                               style=wx.CB_READONLY)
        if wx.VERSION_STRING >= '4.0':
            self.cb2.SetToolTipString = self.cb2.SetToolTip
        self.cb2.SetToolTipString(_("Default version of wxPython."))
        self.default_wxv = self.cb2.GetValue()

        ### Sizer
        box1 = wx.StaticBoxSizer(wx.StaticBox(self, wx.NewIdRef(),
                                              _('Properties')),
                                 orient=wx.VERTICAL)
        vsizer = wx.BoxSizer(wx.VERTICAL)
        hsizer = wx.GridSizer(4, 2, 20, 20)

        hsizer.AddMany([
            (self.st1, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.nb_opened_file, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.st3, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.nb_history_undo, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.st2, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.font_size, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.st4, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5),
            (self.cb2, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 5)
        ])

        vsizer.Add(self.plugin_dir, 1, wx.EXPAND)
        vsizer.Add(self.domain_dir, 1, wx.EXPAND)
        vsizer.Add(self.out_dir, 1, wx.EXPAND)
        vsizer.Add(hsizer, 0, wx.EXPAND)
        vsizer.Add(self.cb1, 1, wx.EXPAND)
        vsizer.Add(self.cb11, 1, wx.EXPAND)
        box1.Add(vsizer, 1, wx.EXPAND)

        ### Set sizer
        self.SetSizer(box1)
        self.SetAutoLayout(True)
 def __init__(self, parent):
     wx.Frame.__init__(self,
                       parent,
                       -1,
                       "File entry with browse",
                       size=(500, 260))
     self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
     panel = wx.Panel(self, -1)
     innerbox = wx.BoxSizer(wx.VERTICAL)
     control = FileBrowseButton(
         panel,
         initialValue="z:\\temp",
     )
     innerbox.Add(control, 0, wx.EXPAND)
     middlecontrol = FileBrowseButtonWithHistory(
         panel,
         labelText="With History",
         initialValue="d:\\temp",
         history=["c:\\temp", "c:\\tmp", "r:\\temp", "z:\\temp"],
         changeCallback=SimpleCallback("With History"),
     )
     innerbox.Add(middlecontrol, 0, wx.EXPAND)
     middlecontrol = FileBrowseButtonWithHistory(
         panel,
         labelText="History callback",
         initialValue="d:\\temp",
         history=self.historyCallBack,
         changeCallback=SimpleCallback("History callback"),
     )
     innerbox.Add(middlecontrol, 0, wx.EXPAND)
     self.bottomcontrol = control = FileBrowseButton(
         panel,
         labelText="With Callback",
         style=wx.SUNKEN_BORDER | wx.CLIP_CHILDREN,
         changeCallback=SimpleCallback("With Callback"),
     )
     innerbox.Add(control, 0, wx.EXPAND)
     self.bottommostcontrol = control = DirBrowseButton(
         panel,
         labelText="Simple dir browse button",
         style=wx.SUNKEN_BORDER | wx.CLIP_CHILDREN)
     innerbox.Add(control, 0, wx.EXPAND)
     ID = wx.NewIdRef()
     innerbox.Add(wx.Button(
         panel,
         ID,
         "Change Label",
     ), 1, wx.EXPAND)
     self.Bind(wx.EVT_BUTTON, self.OnChangeLabel, id=ID)
     ID = wx.NewIdRef()
     innerbox.Add(wx.Button(
         panel,
         ID,
         "Change Value",
     ), 1, wx.EXPAND)
     self.Bind(wx.EVT_BUTTON, self.OnChangeValue, id=ID)
     panel.SetAutoLayout(True)
     panel.SetSizer(innerbox)
     self.history = {
         "c:\\temp": 1,
         "c:\\tmp": 1,
         "r:\\temp": 1,
         "z:\\temp": 1
     }
    def CreateOptionsPage(self):
        """
        Creates the :class:`~wx.lib.agw.labelbook.LabelBook` option page which holds the
        :class:`~wx.lib.agw.flatmenu.FlatMenu` styles.
        """

        options = wx.Panel(self._book, wx.ID_ANY, wx.DefaultPosition,
                           wx.Size(300, 300))

        # Create some options here
        vsizer = wx.BoxSizer(wx.VERTICAL)
        options.SetSizer(vsizer)

        #-----------------------------------------------------------
        # options page layout
        # - Menu Style: Default or 2007 (radio group)
        #
        # - Default Style Settings:     (static box)
        #     + Draw vertical gradient  (check box)
        #     + Draw border             (check box)
        #     + Drop toolbar shadow     (check box)
        #
        # - Colour Scheme                   (static box)
        #     + Menu bar background colour  (combo button)
        #-----------------------------------------------------------

        self._menuStyleID = wx.NewIdRef()
        choices = [_("Default Style"), _("Metallic")]
        self._menuStyle = wx.RadioBox(options, self._menuStyleID,
                                      _("Menu bar style"), wx.DefaultPosition,
                                      wx.DefaultSize, choices)

        # update the selection
        theme = ArtManager.Get().GetMenuTheme()

        if theme == Style2007:
            self._menuStyle.SetSelection(1)
        else:
            self._menuStyle.SetSelection(0)

        # connect event to the control
        self._menuStyle.Bind(wx.EVT_RADIOBOX, self.OnChangeStyle)

        vsizer.Add(self._menuStyle, 0, wx.EXPAND | wx.ALL, 5)

        self._sbStyle = wx.StaticBoxSizer(
            wx.StaticBox(options, -1, _("Default style settings")),
            wx.VERTICAL)
        self._drawVertGradID = wx.NewIdRef()
        self._verticalGradient = wx.CheckBox(options, self._drawVertGradID,
                                             _("Draw vertical gradient"))
        self._verticalGradient.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle)
        self._sbStyle.Add(self._verticalGradient, 0, wx.EXPAND | wx.ALL, 3)
        self._verticalGradient.SetValue(
            ArtManager.Get().GetMBVerticalGradient())

        self._drawBorderID = wx.NewIdRef()
        self._drawBorder = wx.CheckBox(options, self._drawBorderID,
                                       _("Draw border around menu bar"))
        self._drawBorder.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle)
        self._sbStyle.Add(self._drawBorder, 0, wx.EXPAND | wx.ALL, 3)
        self._drawBorder.SetValue(ArtManager.Get().GetMenuBarBorder())

        self._shadowUnderTBID = wx.NewIdRef()
        self._shadowUnderTB = wx.CheckBox(options, self._shadowUnderTBID,
                                          _("Toolbar float over menu bar"))
        self._shadowUnderTB.Bind(wx.EVT_CHECKBOX, self.OnChangeStyle)
        self._sbStyle.Add(self._shadowUnderTB, 0, wx.EXPAND | wx.ALL, 3)
        self._shadowUnderTB.SetValue(ArtManager.Get().GetRaiseToolbar())

        vsizer.Add(self._sbStyle, 0, wx.EXPAND | wx.ALL, 5)

        # Misc
        sb = wx.StaticBoxSizer(wx.StaticBox(options, -1, _("Colour Scheme")),
                               wx.VERTICAL)
        self._colourID = wx.NewIdRef()

        colourChoices = ArtManager.Get().GetColourSchemes()
        colourChoices.sort()

        self._colour = wx.ComboBox(options,
                                   self._colourID,
                                   ArtManager.Get().GetMenuBarColourScheme(),
                                   choices=colourChoices,
                                   style=wx.CB_DROPDOWN | wx.CB_READONLY)
        sb.Add(self._colour, 0, wx.EXPAND)
        vsizer.Add(sb, 0, wx.EXPAND | wx.ALL, 5)
        self._colour.Bind(wx.EVT_COMBOBOX, self.OnChangeStyle)

        # update the dialog by sending all possible events to us
        event = wx.CommandEvent(wx.wxEVT_COMMAND_RADIOBOX_SELECTED,
                                self._menuStyleID)
        event.SetEventObject(self)
        event.SetInt(self._menuStyle.GetSelection())
        self._menuStyle.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED)
        event.SetId(self._drawVertGradID)
        event.SetInt(ArtManager.Get().GetMBVerticalGradient())
        self._verticalGradient.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED)
        event.SetId(self._shadowUnderTBID)
        event.SetInt(ArtManager.Get().GetRaiseToolbar())
        self._shadowUnderTB.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_CHECKBOX_CLICKED)
        event.SetId(self._drawBorderID)
        event.SetInt(ArtManager.Get().GetMenuBarBorder())
        self._drawBorder.ProcessEvent(event)

        event.SetEventType(wx.wxEVT_COMMAND_COMBOBOX_SELECTED)
        event.SetId(self._colourID)
        self._colour.ProcessEvent(event)

        return options
Exemple #9
0
    p = Properties()
    if sys.argv[1] == '--incell':
        # GE Incell xml wrapper
        # LOOP
        p.LoadIncellFiles(sys.argv[2], sys.argv[3], sys.argv[4:])
    else:
        p.LoadFile(sys.argv[1])

from cpa.cpatool import CPATool
import inspect

import cpa.multiclasssql
# ---
import wx

ID_CLASSIFIER = wx.NewIdRef()
ID_IMAGE_GALLERY = wx.NewIdRef()
ID_PLATE_VIEWER = wx.NewIdRef()
ID_TABLE_VIEWER = wx.NewIdRef()
ID_IMAGE_VIEWER = wx.NewIdRef()
ID_SCATTER = wx.NewIdRef()
ID_HISTOGRAM = wx.NewIdRef()
ID_DENSITY = wx.NewIdRef()
ID_BOXPLOT = wx.NewIdRef()
ID_NORMALIZE = wx.NewIdRef()


def get_cpatool_subclasses():
    '''returns a list of CPATool subclasses.
    '''
    class_objs = inspect.getmembers(sys.modules[__name__], inspect.isclass)
Exemple #10
0
ID_NEW = wx.ID_NEW
ID_OPEN = wx.ID_OPEN
ID_REVERT = wx.ID_REVERT
ID_CLOSE = wx.ID_CLOSE
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_PRINT = wx.ID_PRINT
ID_EXIT = wx.ID_EXIT
ID_UNDO = wx.ID_UNDO
ID_REDO = wx.ID_REDO
ID_CUT = wx.ID_CUT
ID_COPY = wx.ID_COPY
ID_PASTE = wx.ID_PASTE
ID_CLEAR = wx.ID_CLEAR
ID_SELECTALL = wx.ID_SELECTALL
ID_EMPTYBUFFER = wx.NewIdRef()
ID_ABOUT = wx.ID_ABOUT
ID_HELP = wx.NewIdRef()
ID_AUTOCOMP_SHOW = wx.NewIdRef()
ID_AUTOCOMP_MAGIC = wx.NewIdRef()
ID_AUTOCOMP_SINGLE = wx.NewIdRef()
ID_AUTOCOMP_DOUBLE = wx.NewIdRef()
ID_CALLTIPS_SHOW = wx.NewIdRef()
ID_CALLTIPS_INSERT = wx.NewIdRef()
ID_COPY_PLUS = wx.NewIdRef()
ID_NAMESPACE = wx.NewIdRef()
ID_PASTE_PLUS = wx.NewIdRef()
ID_WRAP = wx.NewIdRef()
ID_TOGGLE_MAXIMIZE = wx.NewIdRef()
ID_SHOW_LINENUMBERS = wx.NewIdRef()
ID_ENABLESHELLMODE = wx.NewIdRef()
    def CreateMenusPage(self):
        """ Creates the :class:`~wx.lib.agw.labelbook.LabelBook` pages with :class:`~wx.lib.agw.flatmenu.FlatMenu` information. """

        menus = wx.Panel(self._book, wx.ID_ANY, wx.DefaultPosition,
                         wx.Size(300, 300))
        sz = wx.BoxSizer(wx.VERTICAL)
        menus.SetSizer(sz)

        choices = []

        mb = self.GetParent()

        if not self.created:
            self.order = []

        # Add all the menu items that are currently visible to the list
        for i in range(len(mb._items)):

            dummy, lableOnly = ArtManager.Get().GetAccelIndex(
                mb._items[i].GetTitle())
            choices.append(lableOnly)

            # Add the menu to the visible menus map
            self._visibleMenus.update({lableOnly: mb._items[i].GetMenu()})
            if not self.created:
                self.order.append(lableOnly)

        # Add all hidden menus to the menu bar

        for key in self._hiddenMenus:
            choices.append(key)

        if self.created:
            visible = OrderedDict()
            hidden = OrderedDict()
            for items in self.order:
                if items in self._visibleMenus:
                    visible[items] = self._visibleMenus[items]
                elif items in self._hiddenMenus:
                    hidden[items] = self._hiddenMenus[items]

            self._visibleMenus = visible
            self._hiddenMenus = hidden

        self._menuListId = wx.NewIdRef()
        self._checkListMenus = wx.CheckListBox(menus,
                                               self._menuListId,
                                               pos=wx.DefaultPosition,
                                               size=wx.Size(250, 250),
                                               choices=self.order,
                                               style=wx.BORDER_SIMPLE)
        self._checkListMenus.Bind(wx.EVT_CHECKLISTBOX, self.OnMenuChecked)

        # check all visible items
        for indx, item in enumerate(self.order):
            if item in self._visibleMenus:
                self._checkListMenus.Check(indx)

        # Add title panel
        title = FMTitlePanel(menus, _("Select Menu To Add/Remove:"))
        sz.Add(title, 0, wx.EXPAND | wx.ALL, 2)
        sz.Add(self._checkListMenus, 1,
               wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, 2)

        self.created = True

        return menus
Exemple #12
0
    def __init__(self):
        """ Creates pose editor window. """
        wx.Frame.__init__(self,
                          None,
                          -1,
                          VERSION,
                          style=wx.DEFAULT_FRAME_STYLE)

        # key data for our program
        self.project = Project()  # holds data for our project
        self.panelIndex = dict()  # existant tools
        self.saveReq = False
        self.panel = None
        self.port = None
        self.filename = ""
        self.dirname = ""
        self.columns = 2  # column count for pose editor

        # for clearing red color on status bar
        self.timer = wx.Timer(self, self.ID_TIMER)
        self.timeout = 0

        # build our menu bar
        menubar = wx.MenuBar()
        prjmenu = wx.Menu()
        # dialog with name, # of servos
        prjmenu.Append(self.ID_NEW, "&New\tCtrl+N", "", wx.ITEM_NORMAL)
        prjmenu.Append(self.ID_OPEN, "&Open\tCtrl+O", "",
                       wx.ITEM_NORMAL)  # open file dialog
        prjmenu.AppendSeparator()
        # if name unknown, ask, otherwise save
        prjmenu.Append(self.ID_SAVE, "&Save\tCtrl+S", "", wx.ITEM_NORMAL)
        prjmenu.Append(self.ID_SAVE_AS, "Save As")  # ask for name, save
        prjmenu.AppendSeparator()
        prjmenu.Append(self.ID_EXIT, "&Quit\tCtrl+Q", "", wx.ITEM_NORMAL)
        menubar.Append(prjmenu, "Project")

        # Create tool panel
        toolsmenu = wx.Menu()
        for panel in panels:
            name = panel.NAME
            id = wx.NewIdRef()
            self.panelIndex[id] = panel
            toolsmenu.Append(id, name)
        toolsmenu.Append(self.ID_EXPORT, "Export to AVR")  # save as dialog
        menubar.Append(toolsmenu, "Tools")

        configmenu = wx.Menu()
        # dialog box: arbotix/thru, speed, port
        configmenu.Append(self.ID_PORT, "Port")
        columnmenu = wx.Menu()
        columnmenu.Append(self.ID_2COL, "2 columns")
        columnmenu.Append(self.ID_3COL, "3 columns")
        columnmenu.Append(self.ID_4COL, "4 columns")
        configmenu.AppendSubMenu(columnmenu, "Pose editor")
        # live update
        self.live = configmenu.Append(self.ID_LIVE_UPDATE,
                                      "Live pose update",
                                      kind=wx.ITEM_CHECK)
        # configmenu.Append(self.ID_TEST,"test") # for in-house testing of boards
        menubar.Append(configmenu, "Configuration")

        helpmenu = wx.Menu()
        helpmenu.Append(self.ID_ABOUT, "About")
        menubar.Append(helpmenu, "Help")

        self.SetMenuBar(menubar)

        # configure events
        self.Bind(wx.EVT_MENU, self.newFile, self.ID_NEW)
        self.Bind(wx.EVT_MENU, self.openFile, self.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.saveFile, self.ID_SAVE)
        self.Bind(wx.EVT_MENU, self.saveFileAs, self.ID_SAVE_AS)
        self.Bind(wx.EVT_MENU, sys.exit, self.ID_EXIT)

        for t in self.panelIndex.keys():
            self.Bind(wx.EVT_MENU, self.loadTool, t)
        self.Bind(wx.EVT_MENU, self.export, self.ID_EXPORT)

        self.Bind(wx.EVT_MENU, self.doRelax, self.ID_RELAX)
        self.Bind(wx.EVT_MENU, self.doPort, self.ID_PORT)
        self.Bind(wx.EVT_MENU, self.doTest, self.ID_TEST)
        self.Bind(wx.EVT_MENU, self.doAbout, self.ID_ABOUT)
        self.Bind(wx.EVT_CLOSE, self.doClose)
        self.Bind(wx.EVT_TIMER, self.OnTimer, id=self.ID_TIMER)

        self.Bind(wx.EVT_MENU, self.setLiveUpdate, self.ID_LIVE_UPDATE)
        self.Bind(wx.EVT_MENU, self.do2Col, self.ID_2COL)
        self.Bind(wx.EVT_MENU, self.do3Col, self.ID_3COL)
        self.Bind(wx.EVT_MENU, self.do4Col, self.ID_4COL)

        # editor area
        self.sb = self.CreateStatusBar(2)
        self.sb.SetStatusWidths([-1, 250])
        self.sb.SetStatusText('not connected', 1)

        self.loadTool()
        self.sb.SetStatusText('please create or open a project...', 0)
        self.Centre()

        self.Show(True)
Exemple #13
0
class Editor(wx.Frame):
    """Implements the main editor window. """
    ID_NEW = wx.NewIdRef()
    ID_OPEN = wx.NewIdRef()
    ID_SAVE = wx.NewIdRef()
    ID_SAVE_AS = wx.NewIdRef()
    ID_EXIT = wx.NewIdRef()
    ID_EXPORT = wx.NewIdRef()
    ID_RELAX = wx.NewIdRef()
    ID_PORT = wx.NewIdRef()
    ID_ABOUT = wx.NewIdRef()
    ID_TEST = wx.NewIdRef()
    ID_TIMER = wx.NewIdRef()
    ID_COL_MENU = wx.NewIdRef()
    ID_LIVE_UPDATE = wx.NewIdRef()
    ID_2COL = wx.NewIdRef()
    ID_3COL = wx.NewIdRef()
    ID_4COL = wx.NewIdRef()

    def __init__(self):
        """ Creates pose editor window. """
        wx.Frame.__init__(self,
                          None,
                          -1,
                          VERSION,
                          style=wx.DEFAULT_FRAME_STYLE)

        # key data for our program
        self.project = Project()  # holds data for our project
        self.panelIndex = dict()  # existant tools
        self.saveReq = False
        self.panel = None
        self.port = None
        self.filename = ""
        self.dirname = ""
        self.columns = 2  # column count for pose editor

        # for clearing red color on status bar
        self.timer = wx.Timer(self, self.ID_TIMER)
        self.timeout = 0

        # build our menu bar
        menubar = wx.MenuBar()
        prjmenu = wx.Menu()
        # dialog with name, # of servos
        prjmenu.Append(self.ID_NEW, "&New\tCtrl+N", "", wx.ITEM_NORMAL)
        prjmenu.Append(self.ID_OPEN, "&Open\tCtrl+O", "",
                       wx.ITEM_NORMAL)  # open file dialog
        prjmenu.AppendSeparator()
        # if name unknown, ask, otherwise save
        prjmenu.Append(self.ID_SAVE, "&Save\tCtrl+S", "", wx.ITEM_NORMAL)
        prjmenu.Append(self.ID_SAVE_AS, "Save As")  # ask for name, save
        prjmenu.AppendSeparator()
        prjmenu.Append(self.ID_EXIT, "&Quit\tCtrl+Q", "", wx.ITEM_NORMAL)
        menubar.Append(prjmenu, "Project")

        # Create tool panel
        toolsmenu = wx.Menu()
        for panel in panels:
            name = panel.NAME
            id = wx.NewIdRef()
            self.panelIndex[id] = panel
            toolsmenu.Append(id, name)
        toolsmenu.Append(self.ID_EXPORT, "Export to AVR")  # save as dialog
        menubar.Append(toolsmenu, "Tools")

        configmenu = wx.Menu()
        # dialog box: arbotix/thru, speed, port
        configmenu.Append(self.ID_PORT, "Port")
        columnmenu = wx.Menu()
        columnmenu.Append(self.ID_2COL, "2 columns")
        columnmenu.Append(self.ID_3COL, "3 columns")
        columnmenu.Append(self.ID_4COL, "4 columns")
        configmenu.AppendSubMenu(columnmenu, "Pose editor")
        # live update
        self.live = configmenu.Append(self.ID_LIVE_UPDATE,
                                      "Live pose update",
                                      kind=wx.ITEM_CHECK)
        # configmenu.Append(self.ID_TEST,"test") # for in-house testing of boards
        menubar.Append(configmenu, "Configuration")

        helpmenu = wx.Menu()
        helpmenu.Append(self.ID_ABOUT, "About")
        menubar.Append(helpmenu, "Help")

        self.SetMenuBar(menubar)

        # configure events
        self.Bind(wx.EVT_MENU, self.newFile, self.ID_NEW)
        self.Bind(wx.EVT_MENU, self.openFile, self.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.saveFile, self.ID_SAVE)
        self.Bind(wx.EVT_MENU, self.saveFileAs, self.ID_SAVE_AS)
        self.Bind(wx.EVT_MENU, sys.exit, self.ID_EXIT)

        for t in self.panelIndex.keys():
            self.Bind(wx.EVT_MENU, self.loadTool, t)
        self.Bind(wx.EVT_MENU, self.export, self.ID_EXPORT)

        self.Bind(wx.EVT_MENU, self.doRelax, self.ID_RELAX)
        self.Bind(wx.EVT_MENU, self.doPort, self.ID_PORT)
        self.Bind(wx.EVT_MENU, self.doTest, self.ID_TEST)
        self.Bind(wx.EVT_MENU, self.doAbout, self.ID_ABOUT)
        self.Bind(wx.EVT_CLOSE, self.doClose)
        self.Bind(wx.EVT_TIMER, self.OnTimer, id=self.ID_TIMER)

        self.Bind(wx.EVT_MENU, self.setLiveUpdate, self.ID_LIVE_UPDATE)
        self.Bind(wx.EVT_MENU, self.do2Col, self.ID_2COL)
        self.Bind(wx.EVT_MENU, self.do3Col, self.ID_3COL)
        self.Bind(wx.EVT_MENU, self.do4Col, self.ID_4COL)

        # editor area
        self.sb = self.CreateStatusBar(2)
        self.sb.SetStatusWidths([-1, 250])
        self.sb.SetStatusText('not connected', 1)

        self.loadTool()
        self.sb.SetStatusText('please create or open a project...', 0)
        self.Centre()

        self.Show(True)

    def loadTool(self, e=None):
        """Load toolpane."""
        if self.panel is not None:
            self.panel.save()
            # self.sizer.Remove(self.panel)
            self.panel.Destroy()
        self.ClearBackground()
        # instantiate
        if e is None:
            # PoseEditor
            self.panel = panels[0](self, self.port)
        else:
            self.panel = self.panelIndex[e.GetId()](self, self.port)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.panel, 1, wx.EXPAND | wx.ALL, 10)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)
        self.sizer.Fit(self)
        self.sb.SetStatusText(self.panel.STATUS)
        self.panel.SetFocus()

    def newFile(self, e):
        """Open a dialog that asks for robot name and servo count."""
        dlg = NewProjectDialog(self, -1, "Create New Project")
        if dlg.ShowModal() == wx.ID_OK:
            self.project.new(dlg.name.GetValue(), dlg.count.GetValue(),
                             int(dlg.resolution.GetValue()))
            self.loadTool()
            self.sb.SetStatusText('created new project ' + self.project.name +
                                  ', please create a pose...')
            self.SetTitle(VERSION + " - " + self.project.name)
            self.panel.saveReq = True
            self.filename = ""
        dlg.Destroy()

    def openFile(self, e):
        """Loads a robot file into the GUI."""
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.ppr",
                            wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetPath()
            self.dirname = dlg.GetDirectory()
            print("Opening: " + self.filename)
            self.project.load(self.filename)
            self.SetTitle(VERSION + " - " + self.project.name)
            dlg.Destroy()
            self.loadTool()
            self.sb.SetStatusText('opened ' + self.filename)

    def saveFile(self, e=None):
        """Save a robot file from the GUI."""
        if self.filename == "":
            dlg = wx.FileDialog(self, "Choose a file", self.dirname, "",
                                "*.ppr", wx.FD_SAVE)
            if dlg.ShowModal() == wx.ID_OK:
                self.filename = dlg.GetPath()
                self.dirname = dlg.GetDirectory()
                dlg.Destroy()
            else:
                return
        if self.filename[-4:] != ".ppr":
            self.filename = self.filename + ".ppr"
        self.project.saveFile(self.filename)
        self.sb.SetStatusText('saved ' + self.filename)

    def saveFileAs(self, e):
        self.filename = ""
        self.saveFile()

    def export(self, e):
        """Export a pose file for use with Sanguino Library."""
        if self.project.name == "":
            self.sb.SetBackgroundColour('RED')
            self.sb.SetStatusText('please create a project')
            self.timer.Start(20)
            return
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.h",
                            wx.FD_SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            self.project.export(dlg.GetPath())
            self.sb.SetStatusText("exported " + dlg.GetPath(), 0)
            dlg.Destroy()

    def findPorts(self):
        """Return a list of serial ports """
        self.ports = []
        for p in list_ports.comports():
            try:
                s = serial.Serial(p.device)
                s.close()
                self.ports.append(p.device)
            except OSError:
                pass

    def doPort(self, e=None):
        """ open a serial port """
        if self.port is None:
            self.findPorts()
        dlg = wx.SingleChoiceDialog(self, 'Port (Ex. COM4 or /dev/ttyUSB0)',
                                    'Select Communications Port', self.ports)
        # dlg = PortDialog(self,'Select Communications Port',self.ports)
        if dlg.ShowModal() == wx.ID_OK:
            if self.port is not None:
                self.port.ser.close()
            print("Opening port: " + self.ports[dlg.GetSelection()])
            self.openPort(self.ports[dlg.GetSelection()])
            dlg.Destroy()

    def openPort(self, port, baud=115200, interpolate=True):
        try:
            # TODO: add ability to select type of driver
            self.port = Driver(port, baud, interpolate)
            self.panel.port = self.port
            self.panel.portUpdated()
            self.sb.SetStatusText(port + '@' + str(baud), 1)
        except BaseException:
            self.port = None
            self.sb.SetBackgroundColour('RED')
            self.sb.SetStatusText('Could Not Open Port ' + port, 0)
            self.sb.SetStatusText('not connected', 1)
            self.timer.Start(20)
        return self.port

    def doTest(self, e=None):
        if self.port is not None:
            self.port.execute(253, 25, list())

    def doRelax(self, e=None):
        """ Relax servos so you can pose them. """
        if self.port is not None:
            print("PyPose: relaxing servos...")
            for servo in range(self.project.count):
                self.port.setReg(servo + 1, ax12.P_TORQUE_ENABLE, [
                    0,
                ])
        else:
            self.sb.SetBackgroundColour('RED')
            self.sb.SetStatusText("No Port Open", 0)
            self.timer.Start(20)

    def doAbout(self, e=None):
        license = """
        This program is free software; you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation; either version 2 of the License, or
        (at your option) any later version.

        This library is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
        Lesser General Public License for more details.

        You should have received a copy of the GNU Lesser General Public
        License along with this library; if not, write to the Free Software
        Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA)
        """
        info = wx.adv.AboutDialogInfo()
        info.SetName(VERSION)
        info.SetDescription(
            "A lightweight pose and capture software for the ArbotiX robocontroller"
        )
        info.SetCopyright("""
            Copyright (c) 2020 Funtech-Makers.  All right reserved.
            Copyright (c) 2008-2010 Michael E. Ferguson.  All right reserved.
            """)
        info.SetLicense(license)
        info.SetWebSite("http://www.vanadiumlabs.com")
        wx.adv.AboutBox(info)

    def doClose(self, e=None):
        # TODO: edit this to check if we NEED to save...
        if self.project.save:
            dlg = wx.MessageDialog(None, 'Save changes before closing?', '',
                                   wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
            r = dlg.ShowModal()
            if r == wx.ID_CANCEL:
                e.Veto()
                return
            elif r == wx.ID_YES:
                self.saveFile()
                pass
        self.Destroy()

    def OnTimer(self, e=None):
        self.timeout = self.timeout + 1
        if self.timeout > 50:
            self.sb.SetBackgroundColour(wx.NullColour)
            self.sb.SetStatusText("", 0)
            self.sb.Refresh()
            self.timeout = 0
            self.timer.Stop()

    def do2Col(self, e=None):
        self.columns = 2
        if self.panelIndex == 0:
            self.loadTool()

    def do3Col(self, e=None):
        self.columns = 3
        if isinstance(self.panel, panels[0]):
            self.loadTool()

    def do4Col(self, e=None):
        self.columns = 4
        if isinstance(self.panel, panels[0]):
            self.loadTool()

    def setLiveUpdate(self, e=None):
        if isinstance(self.panel, panels[0]):
            self.panel.live = self.live.IsChecked()
Exemple #14
0
    def mousePositionsList(self, appName):
        self.appName = appName
        self.positions = ConfigObj(os.path.join(GCMousePositions,
                                                f"{appName}.gc"),
                                   encoding="UTF-8")
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        sHelper = gui.guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
        # Translators: The label for the list view of the mouse positions in the current application.
        mousePositionsText = _("&Saved mouse positions")
        self.mousePositionsList = sHelper.addLabeledControl(mousePositionsText,
                                                            wx.ListCtrl,
                                                            style=wx.LC_REPORT
                                                            | wx.LC_SINGLE_SEL,
                                                            size=(550, 350))
        # Translators: the column in mouse positions list to identify the position name.
        self.mousePositionsList.InsertColumn(0, _("Name"), width=150)
        # Translators: the column in mouse positions list to identify the X coordinate.
        self.mousePositionsList.InsertColumn(1, _("Position X"), width=50)
        # Translators: the column in mouse positions list to identify the Y coordinate.
        self.mousePositionsList.InsertColumn(2, _("Position Y"), width=50)
        self.mousePositionsList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onJump)

        for entry in sorted(self.positions.keys()):
            x, y = self.positions[entry].split(",")
            self.mousePositionsList.Append((entry, x, y))
        self.mousePositionsList.Select(0, on=1)
        self.mousePositionsList.SetItemState(0, wx.LIST_STATE_FOCUSED,
                                             wx.LIST_STATE_FOCUSED)

        bHelper = gui.guiHelper.ButtonHelper(orientation=wx.HORIZONTAL)

        jumpButtonID = wx.NewIdRef()
        # Translators: the button to jump to the selected position.
        bHelper.addButton(self, jumpButtonID, _("&Jump"), wx.DefaultPosition)

        renameButtonID = wx.NewIdRef()
        # Translators: the button to rename a mouse position.
        bHelper.addButton(self, renameButtonID, _("&Rename"),
                          wx.DefaultPosition)

        deleteButtonID = wx.NewIdRef()
        # Translators: the button to delete the selected mouse position.
        bHelper.addButton(self, deleteButtonID, _("&Delete"),
                          wx.DefaultPosition)

        clearButtonID = wx.NewIdRef()
        # Translators: the button to clear all mouse positions for the focused app.
        bHelper.addButton(self, clearButtonID, _("C&lear positions"),
                          wx.DefaultPosition)

        # Translators: The label of a button to close the mouse positions dialog.
        bHelper.addButton(self, wx.ID_CLOSE, _("&Close"), wx.DefaultPosition)

        sHelper.addItem(bHelper)

        self.Bind(wx.EVT_BUTTON, self.onJump, id=jumpButtonID)
        self.Bind(wx.EVT_BUTTON, self.onRename, id=renameButtonID)
        self.Bind(wx.EVT_BUTTON, self.onDelete, id=deleteButtonID)
        self.Bind(wx.EVT_BUTTON, self.onClear, id=clearButtonID)
        self.Bind(wx.EVT_BUTTON, lambda evt: self.Close(), id=wx.ID_CLOSE)

        # Borrowed from NVDA Core (add-ons manager).
        # To allow the dialog to be closed with the escape key.
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.EscapeId = wx.ID_CLOSE

        mainSizer.Add(sHelper.sizer,
                      border=gui.guiHelper.BORDER_FOR_DIALOGS,
                      flag=wx.ALL)
        self.Sizer = mainSizer
        mainSizer.Fit(self)
        self.mousePositionsList.SetFocus()
        self.CenterOnScreen()
Exemple #15
0
 def test_WindowIDRef02(self):
     d = {wx.NewIdRef(): 'one', wx.NewIdRef(): 'two'}
     keys = sorted(d.keys())
     for k in keys:
         val = d[k]
Exemple #16
0
    def __makeObjects(self):
        """Add interactors"""

        self.tbarSizer = makeTitleBar(self, 'Options for Standard Rebin',
                                      color=WP.BG_COLOR_TITLEBAR_PANEL1)
        #
        #  Labels
        #
        self.min_lab = wx.StaticText(self, wx.NewIdRef(), 'min', style=wx.ALIGN_CENTER)
        self.max_lab = wx.StaticText(self, wx.NewIdRef(), 'max', style=wx.ALIGN_CENTER)
        self.num_lab = wx.StaticText(self, wx.NewIdRef(), 'num', style=wx.ALIGN_CENTER)
        self.rho_lab = wx.StaticText(self, wx.NewIdRef(), 'rho', style=wx.ALIGN_CENTER)
        self.eta_lab = wx.StaticText(self, wx.NewIdRef(), 'eta', style=wx.ALIGN_CENTER)
        #
        #  Rho
        #
        self.rmin_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1, max=10000, value=str(100))
        self.rmax_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1, max=10000, value=str(1000))
        self.rnum_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1, max=10000, value=str(500))
        #
        #  Eta
        #
        self.emin_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=-360, max=360, value=str(0))
        self.emax_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=-360, max=360, value=str(360))
        self.enum_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1,    max=360, value=str(36))
        #
        #  Other options
        #
        self.corr_cbox = wx.CheckBox(self, wx.NewIdRef(), 'corrected')
        self.npdv_lab  = wx.StaticText(self, wx.NewIdRef(), 'pixel divisions',
                                      style=wx.ALIGN_CENTER)
        self.npdv_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1, max=10, initial=1)
        self.frame_lab = wx.StaticText(self, wx.NewIdRef(), 'frame',
                                       style=wx.ALIGN_CENTER)
        self.frame_cho = wx.Choice(self, wx.NewIdRef(), choices=['frame 1'])

        return
Exemple #17
0
    def __init__(self, parent):
        """ Constructor
		"""
        wx.Panel.__init__(self, parent)

        ### Sizer
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        hbox4 = wx.BoxSizer(wx.HORIZONTAL)
        hbox5 = wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)

        self.sim_success_sound_path = builtins.__dict__[
            'SIMULATION_SUCCESS_SOUND_PATH']
        self.sim_error_sound_path = builtins.__dict__[
            'SIMULATION_ERROR_SOUND_PATH']

        ### Buttons
        self.sim_success_sound_btn = wx.Button(
            self,
            wx.NewIdRef(),
            os.path.basename(self.sim_success_sound_path), (25, 105),
            name='success')
        self.sim_success_sound_btn.Enable(
            self.sim_success_sound_path is not os.devnull)
        if wx.VERSION_STRING >= '4.0':
            self.sim_success_sound_btn.SetToolTipString = self.sim_success_sound_btn.SetToolTip
        self.sim_success_sound_btn.SetToolTipString(
            _("Press this button in order to change the song arriving at the end of the simulation."
              ))

        self.sim_error_sound_btn = wx.Button(
            self,
            wx.NewIdRef(),
            os.path.basename(self.sim_error_sound_path), (25, 105),
            name='error')
        self.sim_error_sound_btn.Enable(
            self.sim_error_sound_path is not os.devnull)
        if wx.VERSION_STRING >= '4.0':
            self.sim_error_sound_btn.SetToolTipString = self.sim_error_sound_btn.SetToolTip
        self.sim_error_sound_btn.SetToolTipString(
            _("Press this button in order to change the song arriving when an error occur in a model during the simulation."
              ))

        self.devs_doc_btn = wx.Button(self, wx.ID_ABOUT, name='doc')
        if wx.VERSION_STRING >= '4.0':
            self.devs_doc_btn.SetToolTipString = self.devs_doc_btn.SetToolTip
        self.devs_doc_btn.SetToolTipString(
            _("Press this button to read the documentation of the selected DEVS package"
              ))

        ### CheckBox
        self.cb1 = wx.CheckBox(self, wx.NewIdRef(), _('Notification'))
        if wx.VERSION_STRING >= '4.0':
            self.cb1.SetToolTipString = self.cb1.SetToolTip
        self.cb1.SetToolTipString(
            _("Notification song is generate when the simulation is over."))
        self.cb1.SetValue(self.sim_success_sound_path is not os.devnull)

        self.cb2 = wx.CheckBox(self, wx.NewIdRef(), _('No Time Limit'))
        if wx.VERSION_STRING >= '4.0':
            self.cb2.SetToolTipString = self.cb2.SetToolTip
        self.cb2.SetValue(builtins.__dict__['NTL'])
        self.cb2.SetToolTipString(
            _("No Time Limit allow the stop of simulation when all of models are idle."
              ))

        ### StaticText for DEVS Kernel directory
        self.txt3 = wx.StaticText(self, wx.NewIdRef(), _("DEVS packages:"))
        self.cb3 = wx.ComboBox(self,
                               wx.NewIdRef(),
                               DEFAULT_DEVS_DIRNAME,
                               choices=list(DEVS_DIR_PATH_DICT.keys()),
                               style=wx.CB_READONLY)
        if wx.VERSION_STRING >= '4.0':
            self.cb3.SetToolTipString = self.cb3.SetToolTip
        self.cb3.SetToolTipString(
            _("Default DEVS Kernel package (PyDEVS, PyPDEVS, ect.)."))
        self.default_devs_dir = DEFAULT_DEVS_DIRNAME

        ### StaticText for strategy
        self.txt = wx.StaticText(self, wx.NewIdRef(), _("Default strategy:"))
        ### choice of combo-box depends on the default DEVS package directory
        c = list(PYDEVS_SIM_STRATEGY_DICT.keys()
                 ) if DEFAULT_DEVS_DIRNAME == 'PyDEVS' else list(
                     PYPDEVS_SIM_STRATEGY_DICT.keys())

        self.cb4 = wx.ComboBox(self,
                               wx.NewIdRef(),
                               DEFAULT_SIM_STRATEGY,
                               choices=c,
                               style=wx.CB_READONLY)
        if wx.VERSION_STRING >= '4.0':
            self.cb4.SetToolTipString = self.cb4.SetToolTip
        self.cb4.SetToolTipString(
            _("Default strategy for the simulation algorithm. Please see the DEVSimPy doc for more information of possible strategy."
              ))
        self.sim_defaut_strategy = DEFAULT_SIM_STRATEGY

        ### StaticText
        self.sim_defaut_plot_dyn_freq = builtins.__dict__[
            'DEFAULT_PLOT_DYN_FREQ']
        self.txt2 = wx.StaticText(self, wx.NewIdRef(),
                                  _("Frequency of plotting refresh:"))
        self.sc = wx.SpinCtrl(self,
                              wx.NewIdRef(),
                              str(self.sim_defaut_plot_dyn_freq), (55, 90),
                              (60, -1),
                              min=10,
                              max=10000)
        if wx.VERSION_STRING >= '4.0':
            self.sc.SetToolTipString = self.sc.SetToolTip
        self.sc.SetToolTipString(_("Default frequency for dynamic plotting."))

        ### Adding sizer
        hbox1.Add(self.cb1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 15)
        hbox1.Add(self.sim_success_sound_btn, 1, wx.EXPAND | wx.ALL, 15)
        hbox1.Add(self.sim_error_sound_btn, 1, wx.EXPAND | wx.ALL, 15)

        hbox5.Add(self.txt3, 0, wx.EXPAND | wx.ALL, 15)
        hbox5.Add(self.cb3, 1, wx.EXPAND | wx.ALL, 15)
        hbox5.Add(self.devs_doc_btn, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL)

        hbox2.Add(self.txt, 0, wx.ALL | wx.EXPAND, 15)
        hbox2.Add(self.cb4, 1, wx.ALL | wx.EXPAND, 15)

        hbox3.Add(self.cb2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 15)

        hbox4.Add(self.txt2, 0, wx.ALL, 15)
        hbox4.Add(self.sc, 1, wx.ALL, 15)

        #hbox4.Add(information, 1, wx.ALIGN_CENTER_VERTICAL, 15)
        ##hbox4.Add(self.strategy_info, 1, wx.ALIGN_CENTER_VERTICAL, 15)

        vbox.Add(hbox1, 0, wx.EXPAND | wx.ALL, 10)
        vbox.Add(hbox5, 0, wx.EXPAND | wx.ALL, 10)
        vbox.Add(hbox2, 0, wx.EXPAND | wx.ALL, 10)
        vbox.Add(hbox3, 0, wx.EXPAND | wx.ALL, 10)
        vbox.Add(hbox4, 0, wx.EXPAND | wx.ALL, 10)

        ### Set sizer
        self.SetSizer(vbox)
        self.SetAutoLayout(True)

        ### Binding
        self.sim_success_sound_btn.Bind(wx.EVT_BUTTON, self.OnSelectSound)
        self.sim_error_sound_btn.Bind(wx.EVT_BUTTON, self.OnSelectSound)
        self.devs_doc_btn.Bind(wx.EVT_BUTTON, self.OnAbout)
        self.cb1.Bind(wx.EVT_CHECKBOX, self.onCb1Check)
        self.cb4.Bind(wx.EVT_COMBOBOX, self.onCb4)
        self.cb3.Bind(wx.EVT_COMBOBOX, self.onCb3)
        self.sc.Bind(wx.EVT_SPINCTRL, self.onSc)
Exemple #18
0
    def __makeObjects(self):
        """Add interactors"""

        self.tbarSizer = makeTitleBar(self, 'Options for Spherical Rebin',
                                      color=WP.BG_COLOR_TITLEBAR_PANEL1)
        #
        #  Integer inputs
        #
        self.lump_lab = wx.StaticText(self, wx.NewIdRef(), '# lumped frames (omega)', style=wx.ALIGN_CENTER)
        self.lump_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1, max=1000, initial=1)

        self.bins_lab = wx.StaticText(self, wx.NewIdRef(), 'azimuthal bins (eta)', style=wx.ALIGN_CENTER)
        self.bins_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=1, max=10000, initial=600)

        self.thresh_lab = wx.StaticText(self, wx.NewIdRef(), 'threshold',
                                        style=wx.ALIGN_CENTER)
        self.thresh_spn  = wx.SpinCtrl(self, wx.NewIdRef(), min=0, max=10000, initial=20)
        #
        #  Material and HKLs selector
        #
        exp = wx.GetApp().ws
        self.matl_cho = wx.Choice(self, wx.NewIdRef(), choices=exp.matNames)
        self.matl_cho.SetSelection(0)
        self.read_cho = wx.Choice(self, wx.NewIdRef(), choices=exp.readerNames)
        self.read_cho.SetSelection(0)
        self.hkls_but = wx.Button(self, wx.NewIdRef(), 'Select HKL')
        #
        #  Angle/axis
        #
        name = 'angle'
        self.angle_lab = wx.StaticText(self, wx.NewIdRef(), name, style=wx.ALIGN_CENTER)
        self.angle_flt = FloatControl(self, wx.NewIdRef())
        self.angle_flt.SetValue(1.0)

        name = 'axis x'
        self.axis1_lab = wx.StaticText(self, wx.NewIdRef(), name, style=wx.ALIGN_CENTER)
        self.axis1_flt = FloatControl(self, wx.NewIdRef())
        self.axis1_flt.SetValue(1.0)

        name = 'axis y'
        self.axis2_lab = wx.StaticText(self, wx.NewIdRef(), name, style=wx.ALIGN_CENTER)
        self.axis2_flt = FloatControl(self, wx.NewIdRef())
        self.axis2_flt.SetValue(1.0)

        name = 'axis z'
        self.axis3_lab = wx.StaticText(self, wx.NewIdRef(), name, style=wx.ALIGN_CENTER)
        self.axis3_flt = FloatControl(self, wx.NewIdRef())
        self.axis3_flt.SetValue(1.0)


        return
Exemple #19
0
    def __init__(self, parent):
        """
			Constructor.
		"""

        wx.Toolbook.__init__(self, parent, wx.NewIdRef(), style=wx.BK_DEFAULT)

        ### don't try to translate this labels with _() because there are used to find png
        L = [('General', "(self)"), ('Simulation', "(self)"),
             ('Editor', "(self)"), ('Plugins', "(self)")]

        # make an image list using the LBXX images
        il = wx.ImageList(25, 25)
        for img in [
                wx.Bitmap(os.path.join(ICON_PATH, "%s_pref.png" % a[0]))
                for a in L
        ]:
            il.Add(img)
        self.AssignImageList(il)

        imageIdGenerator = iter(range(il.GetImageCount()))

        for p, label in [("%sPanel%s" % (s, str(args)), _(s))
                         for s, args in L]:
            page = eval(p)
            self.AddPage(page, label, imageId=next(imageIdGenerator))

        ### Plug-in page setting (populate is done when page is changed)
        self.pluginPanel = self.GetPage(self.GetPageCount() - 1)

        self.CheckList = GeneralPluginsList(
            self.pluginPanel.GetRightPanel(),
            style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SORT_ASCENDING)
        self.pluginPanel.SetPluginsList(self.CheckList)

        lpanel = self.pluginPanel.GetLeftPanel()

        ### Buttons for insert or delete plug-ins
        self.addBtn = wx.Button(lpanel, wx.ID_ADD, size=(140, -1))
        self.delBtn = wx.Button(lpanel, wx.ID_DELETE, size=(140, -1))
        self.refBtn = wx.Button(lpanel, wx.ID_REFRESH, size=(140, -1))
        if wx.VERSION_STRING >= '4.0':
            self.addBtn.SetToolTipString = self.addBtn.SetToolTip
            self.delBtn.SetToolTipString = self.delBtn.SetToolTip
            self.refBtn.SetToolTipString = self.refBtn.SetToolTip

        self.addBtn.SetToolTipString(_("Add new plug-ins"))
        self.delBtn.SetToolTipString(_("Delete all existing plug-ins"))
        self.refBtn.SetToolTipString(_("Refresh plug-ins list"))

        ### add widget to plug-in panel
        self.pluginPanel.AddWidget(3, self.addBtn)
        self.pluginPanel.AddWidget(4, self.delBtn)
        self.pluginPanel.AddWidget(5, self.refBtn)

        ### Binding
        self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGED, self.OnPageChanged)
        self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGING, self.OnPageChanging)
        self.Bind(wx.EVT_BUTTON, self.OnAdd, id=self.addBtn.GetId())
        self.Bind(wx.EVT_BUTTON, self.OnDelete, id=self.delBtn.GetId())
        self.Bind(wx.EVT_BUTTON, self.OnRefresh, id=self.refBtn.GetId())
Exemple #20
0
    def __init__(self, *args, **kwargs):
        """ Constructor
		"""

        if 'specific_domain_path' in kwargs:
            domain_path = kwargs['specific_domain_path']
            del kwargs['specific_domain_path']
        else:
            domain_path = DOMAIN_PATH

        Wizard.__init__(self, *args, **kwargs)

        # properties of model
        self.type = "Atomic"
        self.label = ""
        self.inputs = 1
        self.outputs = 1
        self.python_path = ""
        self.model_path = ""
        self.specific_behavior = ""

        # special properties for Port
        self.id = None

        # canvas parent
        parent = self.GetParent()

        # Create a page 1
        page1 = wizard_page(self, _('Type of Model'))
        bt1 = wx.RadioButton(page1,
                             wx.NewIdRef(),
                             _('Atomic model'),
                             style=wx.RB_GROUP)
        bt2 = wx.RadioButton(page1, wx.NewIdRef(), _('Coupled model'))
        if wx.VERSION_STRING >= '4.0':
            bt1.SetToolTipString = bt1.SetToolTip
            bt2.SetToolTipString = bt2.SetToolTip

        bt1.SetToolTipString(
            _("DEVS classic atomic model. It is used to define the behavior (or a part of behavior) of the system"
              ))
        bt2.SetToolTipString(
            _("DEVS classic coupled model. It is used to define the structure (or a part of structure) of the system"
              ))
        page1.add_stuff(
            wx.StaticText(page1, wx.NewIdRef(),
                          _('Choose the type of model:')))
        page1.add_stuff(bt1)
        page1.add_stuff(bt2)

        ### if left click on the DetachedFrame, port instance can be created
        if isinstance(parent.GetTopLevelParent(), Container.DetachedFrame):
            bt3 = wx.RadioButton(page1, wx.NewIdRef(), _('Input Port'))
            bt4 = wx.RadioButton(page1, wx.NewIdRef(), _('Output Port'))
            if wx.VERSION_STRING >= '4.0':
                bt3.SetToolTipString = bt3.SetToolTip
                bt4.SetToolTipString = bt4.SetToolTip

            bt3.SetToolTipString(
                _("DEVS classic input model. It is used to link models"))
            bt4.SetToolTipString(
                _("DEVS classic output model. It is used to link models"))
            page1.add_stuff(bt3)
            page1.add_stuff(bt4)

            def onBt3Click(evt):
                """ input port radio button has been pressed. We redefine its action
				"""

                self.type = "IPort"
                page1.SetNext(page6)
                page6.SetNext(page5)
                page5.SetNext(None)
                page5.SetPrev(page1)
                page6.SetPrev(page1)

            def onBt4Click(evt):
                """ input port radio button has been pressed. We redefine its action
				"""

                self.type = "OPort"
                page1.SetNext(page7)
                page7.SetNext(page5)
                page5.SetNext(None)
                page5.SetPrev(page1)
                page7.SetPrev(page1)

            bt3.Bind(wx.EVT_RADIOBUTTON, onBt3Click)
            bt4.Bind(wx.EVT_RADIOBUTTON, onBt4Click)

        def python_path_call_back(evt):
            fn = evt.GetEventObject().GetValue()
            cls = Components.GetClass(fn)
            if inspect.isclass(cls):

                ### import are here because the simulator (PyDEVS or PyPDEVS) require it
                from DomainInterface.DomainBehavior import DomainBehavior
                from DomainInterface.DomainStructure import DomainStructure
                if not (issubclass(cls, DomainBehavior)
                        or issubclass(cls, DomainStructure)):
                    dlg = wx.MessageDialog(
                        parent,
                        _('The python file must contain a class that inherit of DomainBehavior or DomainStructure master class.\n Please choose a correct python file.'
                          ), _('Wizard Manager'), wx.ID_OK | wx.ICON_ERROR)
                    dlg.ShowModal()
            else:
                dlg = wx.MessageDialog(
                    parent,
                    _('The python file not includes a class definition.\n Please choose a correct python file.'
                      ), _('Wizard Manager'), wx.ID_OK | wx.ICON_ERROR)
                dlg.ShowModal()

        def plugin_path_call_back(evt):
            fn = evt.GetEventObject().GetValue()
            if os.path.basename(fn) != 'plugins.py':
                dlg = wx.MessageDialog(
                    parent,
                    _('The name of plugin python file must be plugins.py.\n Please choose a correct plugin python file.'
                      ), _('Wizard Manager'), wx.ID_OK | wx.ICON_ERROR)
                dlg.ShowModal()

        # Create a page 2
        page2 = wizard_page(self, _('Atomic Model (AMD)'))
        sb1 = wx.StaticBoxSizer(wx.StaticBox(page2, wx.NewIdRef(),
                                             _('Properties')),
                                orient=wx.VERTICAL)
        vb1 = wx.BoxSizer(wx.VERTICAL)
        vbox2 = wx.GridSizer(6, 2, 3, 3)
        bt5 = wx.CheckBox(page2, wx.NewIdRef(), _('Default python file'))
        bt5.SetValue(True)
        if wx.VERSION_STRING >= '4.0': bt5.SetToolTipString = bt5.SetToolTip
        bt5.SetToolTipString(_("Choose python file from specific directory"))
        bt51 = wx.CheckBox(page2, wx.NewIdRef(), _('No plugin file'))
        if wx.VERSION_STRING >= '4.0': bt51.SetToolTipString = bt51.SetToolTip
        bt51.SetToolTipString(_("Choose plugin file from specific directory"))
        bt51.SetValue(True)
        cb0 = wx.ComboBox(page2,
                          wx.NewIdRef(),
                          _('Default'),
                          choices=[
                              _('Default'),
                              _('Generator'),
                              _('Viewer'),
                              _('Collector')
                          ],
                          style=wx.CB_READONLY)
        # filebrowse properties
        fb1 = filebrowse.FileBrowseButton(
            page2,
            wx.NewIdRef(),
            startDirectory=DOMAIN_PATH,
            labelText="",
            fileMask=
            'Python File (*.py)|*.py|Compliled Python File (*.pyc)|*.pyc',
            toolTip=bt5.GetToolTip().GetTip(),
            changeCallback=python_path_call_back)
        fb12 = filebrowse.FileBrowseButton(
            page2,
            wx.NewIdRef(),
            startDirectory=DOMAIN_PATH,
            labelText="",
            fileMask='plugins.py',
            toolTip=bt51.GetToolTip().GetTip(),
            changeCallback=plugin_path_call_back)
        fb1.Enable(False)
        fb12.Enable(False)
        vbox2.AddMany([
            (wx.StaticText(page2, wx.NewIdRef(), _('Label')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.TextCtrl(page2,
                         wx.NewIdRef(),
                         value=_("Atomic_Name"),
                         validator=TextObjectValidator()), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.StaticText(page2, wx.NewIdRef(), _('Specific Behavior')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (cb0, 0, wx.EXPAND),
            (wx.StaticText(page2, wx.NewIdRef(), _('Inputs')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.SpinCtrl(page2,
                         wx.NewIdRef(),
                         '1',
                         min=MIN_NB_PORT,
                         max=MAX_NB_PORT), 0, wx.EXPAND),
            (wx.StaticText(page2, wx.NewIdRef(), _('Outputs')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.SpinCtrl(page2,
                         wx.NewIdRef(),
                         '1',
                         min=MIN_NB_PORT,
                         max=MAX_NB_PORT), 0, wx.EXPAND), (bt5, 0),
            (fb1, 0, wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (bt51, 0),
            (fb12, 0, wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        ])
        vb1.Add(vbox2, 0, wx.EXPAND)
        sb1.Add(vb1, 0, wx.EXPAND)

        page2.add_stuff(sb1)

        # Create a page 3
        page3 = wizard_page(self, _('Coupled Model (CMD)'))
        sb2 = wx.StaticBoxSizer(wx.StaticBox(page3, wx.NewIdRef(),
                                             _('Properties')),
                                orient=wx.VERTICAL)
        vb2 = wx.BoxSizer(wx.VERTICAL)
        vbox3 = wx.GridSizer(6, 2, 3, 3)
        bt6 = wx.CheckBox(page3, wx.NewIdRef(), _('Default python file'))
        if wx.VERSION_STRING >= '4.0': bt6.SetToolTipString = bt6.SetToolTip
        bt6.SetToolTipString(bt5.GetToolTip().GetTip())
        bt6.SetValue(True)
        bt61 = wx.CheckBox(page3, wx.NewIdRef(), _('No plugin file'))
        if wx.VERSION_STRING >= '4.0': bt61.SetToolTipString = bt61.SetToolTip
        bt61.SetToolTipString(bt51.GetToolTip().GetTip())
        bt61.SetValue(True)
        # filebrowse properties
        fb4 = filebrowse.FileBrowseButton(
            page3,
            wx.NewIdRef(),
            startDirectory=DOMAIN_PATH,
            labelText="",
            fileMask=
            'Python File (*.py)|*.py|Compliled Python File (*.pyc)|*.pyc',
            toolTip=bt6.GetToolTip().GetTip(),
            changeCallback=plugin_path_call_back)
        fb41 = filebrowse.FileBrowseButton(
            page3,
            wx.NewIdRef(),
            startDirectory=DOMAIN_PATH,
            labelText="",
            fileMask='plugins.py',
            toolTip=bt61.GetToolTip().GetTip(),
            changeCallback=plugin_path_call_back)
        fb4.Enable(False)
        fb41.Enable(False)
        vbox3.AddMany([
            (wx.StaticText(page3, wx.NewIdRef(), _('Label')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.TextCtrl(page3,
                         wx.NewIdRef(),
                         value=_("Coupled_Name"),
                         validator=TextObjectValidator()), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.StaticText(page3, wx.NewIdRef(), _('Inputs')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.SpinCtrl(page3,
                         wx.NewIdRef(),
                         '1',
                         min=MIN_NB_PORT,
                         max=MAX_NB_PORT), 0, wx.EXPAND),
            (wx.StaticText(page3, wx.NewIdRef(), _('Outputs')), 0,
             wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (wx.SpinCtrl(page3,
                         wx.NewIdRef(),
                         '1',
                         min=MIN_NB_PORT,
                         max=MAX_NB_PORT), 0, wx.EXPAND), (bt6, 0),
            (fb4, 0, wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
            (bt61, 0),
            (fb41, 0, wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        ])
        #page3.add_stuff(vbox3)
        vb2.Add(vbox3, 0, wx.EXPAND)
        sb2.Add(vb2, 0, wx.EXPAND)
        page3.add_stuff(sb2)

        # Create a page 4_1
        page4_1 = wizard_page(self, _('Finish'))
        # save filebrowse
        init = os.path.join(domain_path,
                            "%s.amd" % vbox2.GetItem(1).GetWindow().GetValue())
        fb2 = filebrowse.FileBrowseButton(
            page4_1,
            wx.NewIdRef(),
            initialValue=init,
            fileMode=wx.SAVE,
            #startDirectory = DOMAIN_PATH,
            labelText=_("Save as"),
            fileMask='*.amd')

        page4_1.add_stuff(fb2)

        # Create a page 4_2
        page4_2 = wizard_page(self, _('Finish'))
        init = os.path.join(domain_path,
                            "%s.cmd" % vbox3.GetItem(1).GetWindow().GetValue())
        # save filebrowse
        fb3 = filebrowse.FileBrowseButton(
            page4_2,
            wx.NewIdRef(),
            initialValue=init,
            fileMode=wx.SAVE,
            #startDirectory = DOMAIN_PATH,
            labelText=_("Save as"),
            fileMask='*.cmd')
        page4_2.add_stuff(fb3)

        # Create a page 5
        page5 = wizard_page(self, _('Finish'))
        page5.add_stuff(
            wx.StaticText(page5, wx.NewIdRef(),
                          _('Port model has been created.')))

        ### if left click on the DetachedFrame, port instance can be created
        if isinstance(parent.GetTopLevelParent(), Container.DetachedFrame):
            # Create a page 6
            page6 = wizard_page(self, _('Input Port'))
            sb3 = wx.StaticBoxSizer(wx.StaticBox(page6, wx.NewIdRef(),
                                                 _('Properties')),
                                    orient=wx.VERTICAL)
            vb3 = wx.BoxSizer(wx.VERTICAL)
            #page6.add_stuff(wx.StaticBox(page6, -1, _('Properties')))
            cb_id1 = wx.CheckBox(page6, wx.NewIdRef(), _('Automatic Id'))
            spin_id1 = wx.SpinCtrl(page6,
                                   wx.NewIdRef(),
                                   str(parent.diagram.GetiPortCount()),
                                   min=MIN_NB_PORT,
                                   max=MAX_NB_PORT)
            cb_id1.SetValue(True)
            spin_id1.Enable(False)
            vbox6 = wx.GridSizer(2, 2, 3, 3)
            vbox6.AddMany([
                (wx.StaticText(page6, wx.NewIdRef(), _('Label')), 0,
                 wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
                (wx.TextCtrl(page6, wx.NewIdRef(), value=_("IPort ")), 0,
                 wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
                (cb_id1, 0), (spin_id1, 0, wx.EXPAND)
            ])
            vb3.Add(vbox6, 0, wx.EXPAND)
            sb3.Add(vb3, 0, wx.EXPAND)

            page6.add_stuff(sb3)
            #page6.add_stuff(vbox6)

            # Create a page 7
            page7 = wizard_page(self, _('Output Port'))
            #page7.add_stuff(wx.StaticBox(page7, -1, _('Properties')))
            sb4 = wx.StaticBoxSizer(wx.StaticBox(page7, wx.NewIdRef(),
                                                 _('Properties')),
                                    orient=wx.VERTICAL)
            vb4 = wx.BoxSizer(wx.VERTICAL)
            cb_id2 = wx.CheckBox(page7, wx.NewIdRef(), _('Automatic Id'))
            spin_id2 = wx.SpinCtrl(page7,
                                   wx.NewIdRef(),
                                   str(parent.diagram.GetoPortCount()),
                                   min=MIN_NB_PORT,
                                   max=MAX_NB_PORT)
            cb_id2.SetValue(True)
            spin_id2.Enable(False)
            vbox7 = wx.GridSizer(2, 2, 3, 3)
            vbox7.AddMany([
                (wx.StaticText(page7, wx.NewIdRef(), _('Label')), 0,
                 wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
                (wx.TextCtrl(page7, wx.NewIdRef(), value=_("OPort ")), 0,
                 wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL),
                (cb_id2, 0), (spin_id2, 0, wx.EXPAND)
            ])
            vb4.Add(vbox7, 0, wx.EXPAND)
            sb4.Add(vb4, 0, wx.EXPAND)

            page7.add_stuff(sb4)

        def onBt1Click(evt):
            """ Atomic radio button has been pressed. We redefine its action
			"""

            self.type = "Atomic"
            page1.SetNext(page2)
            page2.SetPrev(page1)
            page2.SetNext(page4_1)
            page4_1.SetPrev(page2)

        def onBt2Click(evt):
            """ Coupled radio button has been pressed. We redefine its action
			"""

            self.type = "Coupled"
            page1.SetNext(page3)
            page3.SetPrev(page1)
            page3.SetNext(page4_2)
            page4_2.SetPrev(page3)

        # event handler for check button
        def onBt5Check(evt):
            """ Python file selector is checked.
			"""

            if evt.GetEventObject().GetValue():
                fb1.Enable(False)
            else:
                fb1.Enable(True)

        # event handler for check button
        def onBt51Check(evt):
            """ Python file selector is checked.
			"""
            if evt.GetEventObject().GetValue():
                fb12.Enable(False)
            else:
                fb12.Enable(True)

        def onBt6Check(evt):
            """ Python file selector is checked.
			"""

            if evt.GetEventObject().GetValue():
                fb4.Enable(False)
            else:
                fb4.Enable(True)

        # event handler for check button
        def onBt61Check(evt):
            """ Python file selector is checked.
			"""
            if evt.GetEventObject().GetValue():
                fb41.Enable(False)
            else:
                fb41.Enable(True)

        def onCbId1(evt):
            if evt.GetEventObject().GetValue():
                spin_id1.Enable(False)
            else:
                spin_id1.Enable(True)

        def onCbId2(evt):
            if evt.GetEventObject().GetValue():
                spin_id2.Enable(False)
            else:
                spin_id2.Enable(True)

        def OnSpecificBehavior(evt):
            """ Give the control on the number of input and output form specific behavior choice
			"""

            ### specific behavior choice
            val = evt.GetEventObject().GetValue()

            ### if generator, 0 input and x output (1 is the default)
            if val == _('Generator'):

                ### no input and
                vbox2.GetItem(5).GetWindow().SetValue(0)
                ### update output
                if vbox2.GetItem(7).GetWindow().GetValue() == 0:
                    vbox2.GetItem(7).GetWindow().SetValue(1)

                ### Disable the choice
                vbox2.GetItem(4).GetWindow().Enable(False)
                vbox2.GetItem(5).GetWindow().Enable(False)
                ### Enable the output choice
                vbox2.GetItem(6).GetWindow().Enable(True)
                vbox2.GetItem(7).GetWindow().Enable(True)

            ### if collector, 0 output and x input (1 is the default)
            elif val in (_('Collector'), _('Viewer')):
                ### no output
                vbox2.GetItem(7).GetWindow().SetValue(0)

                ### update input
                if vbox2.GetItem(5).GetWindow().GetValue() == 0:
                    vbox2.GetItem(5).GetWindow().SetValue(1)

                ### Disable the choice
                vbox2.GetItem(7).GetWindow().Enable(False)
                vbox2.GetItem(6).GetWindow().Enable(False)
                ### Enable the output choice
                vbox2.GetItem(5).GetWindow().Enable(True)
                vbox2.GetItem(4).GetWindow().Enable(True)

            ### if Default, 1 output and input
            else:
                vbox2.GetItem(5).GetWindow().Enable(True)
                vbox2.GetItem(4).GetWindow().Enable(True)
                vbox2.GetItem(6).GetWindow().Enable(True)
                vbox2.GetItem(7).GetWindow().Enable(True)
                vbox2.GetItem(5).GetWindow().SetValue(1)
                vbox2.GetItem(7).GetWindow().SetValue(1)

        def OnInputAMDLabel(evt):
            fb2.SetValue(os.path.join(domain_path, "%s.amd" % evt.GetString()))

        def OnInputCMDLabel(evt):
            fb3.SetValue(os.path.join(domain_path, "%s.cmd" % evt.GetString()))

        # Binding
        bt1.Bind(wx.EVT_RADIOBUTTON, onBt1Click)
        bt2.Bind(wx.EVT_RADIOBUTTON, onBt2Click)
        bt5.Bind(wx.EVT_CHECKBOX, onBt5Check)
        bt51.Bind(wx.EVT_CHECKBOX, onBt51Check)
        bt6.Bind(wx.EVT_CHECKBOX, onBt6Check)
        bt61.Bind(wx.EVT_CHECKBOX, onBt61Check)
        ### if left click on the DetachedFrame, port instance can be created
        if isinstance(parent.GetTopLevelParent(), Container.DetachedFrame):
            cb_id1.Bind(wx.EVT_CHECKBOX, onCbId1)
            cb_id2.Bind(wx.EVT_CHECKBOX, onCbId2)
        cb0.Bind(wx.EVT_COMBOBOX, OnSpecificBehavior)
        amd_input_label = vbox2.GetItem(1).GetWindow()
        amd_input_label.Bind(wx.EVT_TEXT, OnInputAMDLabel)
        cmd_input_label = vbox3.GetItem(1).GetWindow()
        cmd_input_label.Bind(wx.EVT_TEXT, OnInputCMDLabel)

        # Add some more pages
        self.add_page(page1)
        self.add_page(page2)
        self.add_page(page3)
        self.add_page(page4_1)
        self.add_page(page4_2)
        self.add_page(page5)

        ### if left click on the DetachedFrame, port instance can be created
        if isinstance(parent.GetTopLevelParent(), Container.DetachedFrame):
            self.add_page(page6)
            self.add_page(page7)

        # define next and prev
        page1.SetNext(page2)
        page2.SetNext(page4_1)
        page2.SetPrev(page1)
        page3.SetPrev(page1)
        page3.SetNext(page4_2)
        page4_1.SetPrev(page2)
        page4_2.SetPrev(page3)
        page4_1.SetNext(None)
        page4_2.SetNext(None)
Exemple #21
0
# -*- coding: utf-8 -*-

import sys
import wx

from wxPyMail import SendMailWx
from Utilities import FormatTrace, EnvironmentInfo, GetActiveWindow

_ = wx.GetTranslation

ID_SEND = wx.NewIdRef()


class BaseDialog(wx.Dialog):
    """ A wx.Dialog base class.
    """
    def __init__(self, parent):
        """ Constructor.
        """

        wx.Dialog.__init__(self,
                           parent,
                           size=(500, 600),
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.MainFrame = parent

    def CreateButtons(self):
        """ Creates the Ok and cancel bitmap buttons. """

        # Build a couple of fancy and useless buttons
        self.cancelButton = wx.Button(self.panel, wx.ID_CANCEL, "")
Exemple #22
0
 def DoDrawing(self, dc):
     random.seed()
     self.objids = []
     self.boundsdict = {}
     for i in range(SHAPE_COUNT):
         id = wx.NewIdRef()
         dc.SetId(id)
         choice = random.randint(0,8)
         if choice in (0,1):
             x = random.randint(0, W)
             y = random.randint(0, H)
             pen = self.RandomPen()
             dc.SetPen(pen)
             dc.DrawPoint(x,y)
             r = wx.Rect(x,y,1,1)
             r.Inflate(pen.GetWidth(),pen.GetWidth())
             dc.SetIdBounds(id,r)
         elif choice in (2,3):
             x1 = random.randint(0, W-SW)
             y1 = random.randint(0, H-SH)
             x2 = random.randint(x1, x1+SW)
             y2 = random.randint(y1, y1+SH)
             pen = self.RandomPen()
             dc.SetPen(pen)
             dc.DrawLine(x1,y1,x2,y2)
             r = wx.Rect(x1,y1,x2-x1,y2-y1)
             r.Inflate(pen.GetWidth(),pen.GetWidth())
             dc.SetIdBounds(id,r)
         elif choice in (4,5):
             w = random.randint(10, SW)
             h = random.randint(10, SH)
             x = random.randint(0, W - w)
             y = random.randint(0, H - h)
             pen = self.RandomPen()
             dc.SetPen(pen)
             dc.SetBrush(self.RandomBrush())
             dc.DrawRectangle(x,y,w,h)
             r = wx.Rect(x,y,w,h)
             r.Inflate(pen.GetWidth(),pen.GetWidth())
             dc.SetIdBounds(id,r)
             self.objids.append(id)
         elif choice == 6:
             Np = 8 # number of characters in text
             word = []
             for i in range(Np):
                 c = chr( random.randint(48, 122) )
                 word.append( c )
             word = "".join(word)
             w,h = self.GetFullTextExtent(word)[0:2]
             x = random.randint(0, W-w)
             y = random.randint(0, H-h)
             dc.SetFont(self.GetFont())
             dc.SetTextForeground(self.RandomColor())
             dc.SetTextBackground(self.RandomColor())
             dc.DrawText(word, x, y)
             r = wx.Rect(x,y,w,h)
             r.Inflate(2,2)
             dc.SetIdBounds(id, r)
             self.objids.append(id)
         elif choice == 7:
             Np = 8 # number of points per polygon
             poly = []
             minx = SW
             miny = SH
             maxx = 0
             maxy = 0
             for i in range(Np):
                 x = random.randint(0, SW)
                 y = random.randint(0, SH)
                 if x < minx: minx = x
                 if x > maxx: maxx = x
                 if y < miny: miny = y
                 if y > maxy: maxy = y
                 poly.append(wx.Point(x,y))
             x = random.randint(0, W-SW)
             y = random.randint(0, H-SH)
             pen = self.RandomPen()
             dc.SetPen(pen)
             dc.SetBrush(self.RandomBrush())
             dc.DrawPolygon(poly, x,y)
             r = wx.Rect(minx+x,miny+y,maxx-minx,maxy-miny)
             r.Inflate(pen.GetWidth(),pen.GetWidth())
             dc.SetIdBounds(id,r)
             self.objids.append(id)
         elif choice == 8:
             w,h = self.bmp.GetSize()
             x = random.randint(0, W-w)
             y = random.randint(0, H-h)
             dc.DrawBitmap(self.bmp,x,y,True)
             dc.SetIdBounds(id,wx.Rect(x,y,w,h))
             self.objids.append(id)
Exemple #23
0
import math
import wx
import wx.adv
import wx.lib.agw.flatmenu as flatmenu
from PIL import Image

from GimelStudio.utils import DrawGrid, ConvertImageToWx
from GimelStudio.registry import CreateNode
from GimelStudio.node import Wire
from .add_node_menu import AddNodeMenu
from .menu_button import MenuButton
from GimelStudio.datafiles import *

# Create IDs
ID_SELECTION_BBOX = wx.NewIdRef()
ID_MENU_BUTTON = wx.NewIdRef()
ID_RENDER_AS_BACKGROUND = wx.NewIdRef()

# Max number of nodes that can be added to the menu is 200, currently
CONTEXTMENU_ADDNODE_IDS = wx.NewIdRef(200)

ID_CONTEXTMENU_DELETENODE = wx.NewIdRef()
ID_CONTEXTMENU_DELETENODES = wx.NewIdRef()
ID_CONTEXTMENU_DUPLICATENODE = wx.NewIdRef()
ID_CONTEXTMENU_DESELECTALLNODES = wx.NewIdRef()
ID_CONTEXTMENU_SELECTALLNODES = wx.NewIdRef()

ID_ADDNODEMENU = wx.NewIdRef()

Exemple #24
0
        alive_count += 1
    else:
        dead_count += 1
    neighbour_info = [alive_count, dead_count]

    if (gridInfos[x][y] == CellStatus.dead.value):
        if (neighbour_info[0] == 3):
            return CellStatus.alive.value
    else:
        if (neighbour_info[0] < 2 or neighbour_info[0] > 3):
            return CellStatus.dead.value
    return gridInfos[x][y]


# Define notification event for thread completion
EVT_RESULT_ID = wx.NewIdRef()


class ResultEvent(wx.PyEvent):
    def __init__(self, data):
        wx.PyEvent.__init__(self)
        self.SetEventType(EVT_RESULT_ID)
        self.data = data


# Thread class that executes processing
class WorkerThread(Thread):
    def __init__(self, notify_window):
        Thread.__init__(self)
        self._notify_window = notify_window
        self._want_abort = False
#!/usr/bin/env python

import wx
import wx.grid
import wx.html
import wx.aui as aui

from six import BytesIO

ID_CreateTree = wx.NewIdRef()
ID_CreateGrid = wx.NewIdRef()
ID_CreateText = wx.NewIdRef()
ID_CreateHTML = wx.NewIdRef()
ID_CreateSizeReport = wx.NewIdRef()
ID_GridContent = wx.NewIdRef()
ID_TextContent = wx.NewIdRef()
ID_TreeContent = wx.NewIdRef()
ID_HTMLContent = wx.NewIdRef()
ID_SizeReportContent = wx.NewIdRef()
ID_CreatePerspective = wx.NewIdRef()
ID_CopyPerspective = wx.NewIdRef()

ID_TransparentHint = wx.NewIdRef()
ID_VenetianBlindsHint = wx.NewIdRef()
ID_RectangleHint = wx.NewIdRef()
ID_NoHint = wx.NewIdRef()
ID_HintFade = wx.NewIdRef()
ID_AllowFloating = wx.NewIdRef()
ID_NoVenetianFade = wx.NewIdRef()
ID_TransparentDrag = wx.NewIdRef()
ID_AllowActivePane = wx.NewIdRef()
Exemple #26
0
 def test_newIdRef01(self):
     id = wx.NewIdRef()
     assert isinstance(id, wx.WindowIDRef)
     id.GetValue()
     id.GetId()
     id.__int__()
    def __init__(self, parent, id, model=None):
        wx.Choicebook.__init__(self, parent, id)

        self.parent = parent

        cls = Components.GetClass(model.python_path)

        if inspect.isclass(cls):

            info = _("Unable to load sources")

            try:
                a = inspect.getdoc(cls)
            except:
                a = info

            try:
                b = inspect.getsource(cls)
            except:
                b = info

            try:
                c = inspect.getsource(cls.__init__)
            except:
                c = info

            try:
                d = inspect.getsource(cls.intTransition)
            except:
                d = info

            try:
                e = inspect.getsource(cls.extTransition)
            except:
                e = info

            try:
                f = inspect.getsource(cls.outputFnc)
            except:
                f = info

            try:
                g = inspect.getsource(cls.timeAdvance)
            except:
                g = info

            try:
                h = inspect.getsource(cls.finish) if hasattr(
                    cls, 'finish') else "\tpass"
            except:
                h = info

            pageTexts = {
                _('Doc'): a,
                _('Class'): b,
                _('Constructor'): c,
                _('Internal Transition'): d,
                _('External Transition'): e,
                _('Output Function'): f,
                _('Time Advance Function'): g,
                _('Finish Function'): h
            }
        else:
            pageTexts = {
                _("Importing Error"):
                _("Error trying to import the module: %s.\nChange the python path by clicking in the above 'python_path' cell.\n %s"
                  % (model.python_path, str(cls)))
            }

        # Now make a bunch of panels for the choice book
        for nameFunc in pageTexts:
            win = wx.Panel(self)
            box = wx.BoxSizer(wx.HORIZONTAL)
            st = wx.TextCtrl(win, wx.NewIdRef(), '', style=wx.TE_MULTILINE)
            try:
                txt = str(pageTexts[nameFunc], errors='replace')
            except TypeError:
                txt = pageTexts[nameFunc]
            finally:
                if txt:
                    st.AppendText(txt)
                    st.ShowPosition(wx.TOP)
                    st.SetEditable(False)
                    box.Add(st, 1, wx.EXPAND)
                    win.SetSizer(box)
                else:
                    sys.stdout.write(
                        _("Method %s of class %s unknown!\n" %
                          (nameFunc, cls.__name__)))

            self.AddPage(win, nameFunc)
Exemple #28
0
 def test_newIdRef02(self):
     refs = wx.NewIdRef(5)
     assert len(refs) == 5
     for ref in refs:
         assert isinstance(ref, wx.WindowIDRef)
Exemple #29
0
# -*- coding: utf-8 -*-

import wx
import wx.xrc
from formRunproc import FormRunproc
from formInsprogs import FormInsprogs
from formWebrequest import FormWebrequest

###########################################################################
## Class MainForm
###########################################################################

#----------------------------------------------------------------------
[ID_EXIT, ID_FORM1, ID_FORM2, ID_FORM3, ID_ABOUT] = wx.NewIdRef(5)
#----------------------------------------------------------------------


class FormMain(wx.MDIParentFrame):
    def __init__(self):
        wx.MDIParentFrame.__init__(self,
                                   None,
                                   -1,
                                   "My first program on Pyton",
                                   size=(800, 600))

        self.winCount = 0
        #self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)

        m__file = wx.Menu()
        #m__file.AppendSeparator()
        m__file.Append(ID_EXIT, "E&xit")
Exemple #30
0
    def CreatePopups(self):

        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewIdRef()
            self.popupID2 = wx.NewIdRef()
            self.popupID3 = wx.NewIdRef()
            self.popupID4 = wx.NewIdRef()
            self.popupID5 = wx.NewIdRef()
            self.popupID6 = wx.NewIdRef()
            self.popupID7 = wx.NewIdRef()
            self.popupID8 = wx.NewIdRef()
            self.popupID9 = wx.NewIdRef()
            self.popupID10 = wx.NewIdRef()
            self.popupID11 = wx.NewIdRef()
            self.popupID12 = wx.NewIdRef()

            self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
            self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
            self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4)
            self.Bind(wx.EVT_MENU, self.OnPopupFive, id=self.popupID5)
            self.Bind(wx.EVT_MENU, self.OnPopupSix, id=self.popupID6)
            self.Bind(wx.EVT_MENU, self.OnPopupSeven, id=self.popupID7)
            self.Bind(wx.EVT_MENU, self.OnPopupEight, id=self.popupID8)
            self.Bind(wx.EVT_MENU, self.OnPopupNine, id=self.popupID9)

        menu = wx.Menu()
        item = wx.MenuItem(menu, self.popupID1, "One")
        img = images.Mondrian.GetImage()
        img.Rescale(16, 16)
        bmp = img.ConvertToBitmap()
        item.SetBitmap(bmp)
        menu.Append(item)

        # add some other items
        menu.Append(self.popupID2, "Two")
        menu.Append(self.popupID3, "Three")
        menu.Append(self.popupID4, "Four")
        menu.Append(self.popupID5, "Five")
        menu.Append(self.popupID6, "Six")
        # make a submenu
        sm = wx.Menu()
        sm.Append(self.popupID8, "Sub Item 1")
        sm.Append(self.popupID9, "Sub Item 1")
        menu.Append(self.popupID7, "Test Submenu", sm)

        return menu