Exemplo n.º 1
0
    def __init__(self, parent, config):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        scrolled_panel = ScrolledPanel(self)
        scrolled_panel.SetAutoLayout(1)
        scrolled_panel.SetupScrolling()
        main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer = wx.FlexGridSizer(2, 10, 10)
        for index, entry in enumerate(config):
            if index > 0:
                for _ in range(0, 2):
                    rule = wx.StaticLine(
                        scrolled_panel,
                        style=wx.LI_HORIZONTAL,
                        size=(-1, 2)
                    )
                    grid_sizer.Add(rule, proportion=1, flag=wx.EXPAND |
                                   wx.TOP | wx.BOTTOM, border=10)
            if entry.help_value:
                grid_sizer.Add(1, 0, 1, wx.EXPAND)
                help_sizer = wx.BoxSizer(wx.HORIZONTAL)
                help_label = HidableAutoWrapStaticText(
                    parent=scrolled_panel,
                    label=u"%s" % entry.help_value.decode('utf8', 'ignore'),
                    kind='help_value',
                )
                help_sizer.Add(help_label, -1, wx.EXPAND)
                grid_sizer.Add(help_sizer, 1, wx.EXPAND)
            label_sizer = wx.BoxSizer(wx.VERTICAL)
            label_sizer.Add(0, 1, 1, wx.EXPAND)
            label = wx.StaticText(
                scrolled_panel,
                label=entry.key_name,
                style=wx.ALIGN_RIGHT
            )
            label_sizer.Add(label, flag=wx.ALIGN_RIGHT)
            label_sizer.Add(0, 1, 1, wx.EXPAND)
            grid_sizer.Add(label_sizer, 0, wx.EXPAND)
            current_value = wx.TextCtrl(
                scrolled_panel,
                value=str(entry.current),
                size=(-1, -1)
            )
            grid_sizer.Add(current_value, -1, wx.EXPAND)
            if entry.man:
                grid_sizer.Add(1, 0, 1, wx.EXPAND)
                man_sizer = wx.BoxSizer(wx.HORIZONTAL)
                man_label = HidableAutoWrapStaticText(
                    parent=scrolled_panel,
                    label=u"%s" % entry.man.decode('utf8', 'ignore'),
                    kind='man',
                )
                man_sizer.Add(man_label, -1, wx.EXPAND)
                grid_sizer.Add(man_sizer, 1, wx.EXPAND)
        grid_sizer.AddGrowableCol(1, 1)
        scroll_sizer = wx.BoxSizer(wx.HORIZONTAL)
        scroll_sizer.Add(grid_sizer, 1, wx.EXPAND | wx.ALL, 10)
        scrolled_panel.SetSizer(scroll_sizer)
        main_sizer.Add(scrolled_panel, 1, wx.EXPAND)
        self.SetSizer(main_sizer)
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        bg_color = 'green'

        # changes the background of the scrollbars
        self.SetBackgroundColour(bg_color)

        sizer = wx.BoxSizer(wx.VERTICAL)

        panel = ScrolledPanel(self)
        panel.SetBackgroundColour(bg_color)
        panel.SetupScrolling(scroll_y=True)

        panelsizer = wx.BoxSizer(wx.VERTICAL)

        for _ in range(4):
            p = wx.Panel(panel, size=(400, 300))
            p.SetBackgroundColour(bg_color)
            panelsizer.Add(p, 0, flag=wx.EXPAND)
            panelsizer.Add((-1, 10))

        panel.SetSizer(panelsizer)

        for child in panel.GetChildren():
            print(type(child))  # there is no scrollbar

        sizer.Add(panel, 1, flag=wx.EXPAND)
        self.SetSizer(sizer)
        self.Layout()
Exemplo n.º 3
0
class TextFileView(IOTABaseDialog):
    def __init__(self,
                 parent,
                 label_style='bold',
                 content_style='normal',
                 contents=None,
                 *args,
                 **kwargs):

        dlg_style = wx.CAPTION | wx.CLOSE_BOX | wx.RESIZE_BORDER | wx.STAY_ON_TOP

        IOTABaseDialog.__init__(self,
                                parent,
                                style=dlg_style,
                                label_style=label_style,
                                content_style=content_style,
                                size=(600, 500),
                                *args,
                                **kwargs)

        self.txt_panel = ScrolledPanel(self)
        self.txt_sizer = wx.BoxSizer(wx.VERTICAL)
        self.txt_panel.SetSizer(self.txt_sizer)

        self.txt = wx.StaticText(self.txt_panel, label=contents)
        self.txt_sizer.Add(self.txt)

        self.txt_panel.SetupScrolling()
        self.envelope.Add(self.txt_panel,
                          1,
                          flag=wx.EXPAND | wx.ALL,
                          border=10)
Exemplo n.º 4
0
    def initUI(self):
        """ Define dialog elements """
        num_sensors = self.settings.ReadInt("numSensors", 1)

        vbox0 = wx.BoxSizer(wx.VERTICAL)
        pnl = ScrolledPanel(self)
        vbox1 = wx.BoxSizer(wx.VERTICAL)

        st = wx.StaticText(
            pnl,
            label="If the sensor numbers don't match, "
            + "make first the adjustments in "
            + "Settings>Ports",
            size=(600, 60),
        )
        st.SetFont(wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.NORMAL))
        vbox1.Add(st, proportion=0, flag=wx.ALL)

        image = wx.Image("docs/diagram.png", wx.BITMAP_TYPE_ANY).Rescale(450, 300)
        imageBitmap = wx.StaticBitmap(pnl, bitmap=wx.Bitmap(image))
        vbox1.Add(imageBitmap, proportion=1, flag=wx.ALL | wx.CENTER)

        st = wx.StaticText(pnl, label="All distances in cm")
        vbox1.Add(st, proportion=0, flag=wx.ALL)

        self.setting_to_control = {}

        self.addLabelledCtrl(pnl, vbox1, "DB1")
        self.addLabelledCtrl(pnl, vbox1, "DB2")
        for i in range(num_sensors):
            self.addLabelledCtrl(pnl, vbox1, "DL" + str(i + 1))
        for i in range(num_sensors):
            self.addLabelledCtrl(pnl, vbox1, "DR" + str(i + 1))
        if self.settings.ReadBool("connectedgL", False):
            self.addLabelledCtrl(pnl, vbox1, "DGLX")
            self.addLabelledCtrl(pnl, vbox1, "DGLY")
        if self.settings.ReadBool("connectedgR", False):
            self.addLabelledCtrl(pnl, vbox1, "DGRX")
            self.addLabelledCtrl(pnl, vbox1, "DGRY")
        if self.settings.ReadBool("connectedeL", False):
            self.addLabelledCtrl(pnl, vbox1, "IEL")
            self.addLabelledCtrl(pnl, vbox1, "DEL")
        if self.settings.ReadBool("connectedeR", False):
            self.addLabelledCtrl(pnl, vbox1, "IER")
            self.addLabelledCtrl(pnl, vbox1, "DER")

        pnl.SetSizer(vbox1)
        pnl.SetupScrolling()

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        okButton = wx.Button(self, label="OK")
        cancelButton = wx.Button(self, label="Cancel")
        hbox.Add(okButton)
        hbox.Add(cancelButton, flag=wx.LEFT, border=5)
        okButton.Bind(wx.EVT_BUTTON, self.OnOK)
        cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)

        vbox0.Add(pnl, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        vbox0.Add(hbox, proportion=0, flag=wx.ALIGN_CENTER | wx.ALL, border=10)
        self.SetSizer(vbox0)
    def update(self, **kwargs):
        """ 
        Results
        -------
        wxPanel obj
        https://stackoverflow.com/questions/3104323/getting-a-wxpython-panel-item-to-expand  
        """
        p1 = ScrolledPanel(self,
                           -1,
                           style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER,
                           name="panel1")
        p1.SetBackgroundColour("White")
        vbox = wx.BoxSizer(wx.VERTICAL)

        txt_info = wx.StaticText(p1, -1, txt)
        txt_info.SetForegroundColour("Green")

        vbox.Add(txt_info, 0, wx.ALIGN_LEFT | wx.ALL, 5)
        vbox.Add(wx.StaticLine(p1, -1, size=(1024, -1)), 0, wx.ALL, 5)
        vbox.Add((20, 20))

        p1.SetSizer(vbox)
        p1.SetAutoLayout(1)
        p1.SetupScrolling()
        return p1
Exemplo n.º 6
0
    def __init__(self, parent, pos, size, model):
        super(Frame, self).__init__(parent, pos, size, model)

        # setup layout
        self.ax_size = 200
        figsize = (10, 10)
        self.SetMinSize((400, 400))

        # setup scrolled panel
        panel = ScrolledPanel(self)
        self.panel = panel

        # setup figure canvas
        self.canvas = FigureCanvasPanel(panel, figsize=figsize)
        self.canvas.figure.subplots_adjust(0, 0, 1, 1, 0, 0)
        panel.SetupScrolling(False, scrollToTop=False, scrollIntoView=False)

        # sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.canvas, 0)
        panel.SetSizer(sizer)
        self.canvas_sizer = sizer

        # Toolbar
        tb = self.InitToolbar(can_open=False)
        tb.AddSeparator()
        # buttons
        button = wx.Button(tb, ID.SHOW_SOURCES, "Sources")
        button.Bind(wx.EVT_BUTTON, self.OnShowSources)
        tb.AddControl(button)
        button = wx.Button(tb, ID.FIND_RARE_EVENTS, "Rare Events")
        button.Bind(wx.EVT_BUTTON, self.OnFindRareEvents)
        tb.AddControl(button)
        # tail
        tb.AddStretchableSpace()
        self.InitToolbarTail(tb)
        tb.Realize()

        self.CreateStatusBar()

        # Bind Events ---
        self.doc.callbacks.subscribe('case_change', self.CaseChanged)
        self.panel.Bind(wx.EVT_SIZE, self.OnPanelResize)
        self.canvas.mpl_connect('axes_enter_event', self.OnPointerEntersAxes)
        self.canvas.mpl_connect('axes_leave_event', self.OnPointerEntersAxes)
        self.canvas.mpl_connect('button_press_event', self.OnCanvasClick)
        self.canvas.mpl_connect('key_release_event', self.OnCanvasKey)
        # re-Bind right click
        self.canvas.Unbind(wx.EVT_RIGHT_DOWN)
        self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)

        # attributes
        self.last_model = ""
        self.source_frame = None
        self.butterfly_baseline = ID.BASELINE_NONE

        # Finalize
        self.plot()
        self.UpdateTitle()
Exemplo n.º 7
0
 def make_page(self, title):
     page = ScrolledPanel(parent=self.notebook, id=-1)
     vbox = BoxSizer(VERTICAL)
     field = Field(page, title)
     self.get_fields(page, vbox, field)
     self.fields.append(field)
     page.SetupScrolling()
     page.SetSizer(vbox)
     self.notebook.AddPage(page, title)
Exemplo n.º 8
0
    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        panel = ScrolledPanel(parent, -1, style=self.STYLE)
        sizer = wx.BoxSizer(wx.VERTICAL)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)
        panel.SetupScrolling()

        return panel
Exemplo n.º 9
0
class PanelContainer(wx.Panel):
    """This contains a preference panel.

    This container has the ability to hold several panels,
    and to be able to switch between them. For some modes, however,
    the container will only hold a single panel.

    Each page has a title area, and an area for a preferences panel
    """
    def __init__(self, *args, **kwargs):
        super(PanelContainer, self).__init__(*args, **kwargs)

        self._current_panel = None
        self.title = wx.StaticText(self, label="Your message here")
        # self.panels_container = wx.Panel(self)
        self.panels_container = ScrolledPanel(self,
                                              wx.ID_ANY,
                                              style=wx.TAB_TRAVERSAL)
        self.panels_container.SetupScrolling()
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, wx.TOP | wx.LEFT | wx.EXPAND, 4)
        sizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 4)
        sizer.Add(self.panels_container, 1, wx.EXPAND)
        # sizer.Add(self._create_body(), 1, flag=wx.EXPAND | wx.ALL, border=16)
        self.SetSizer(sizer)
        self.panels_container.SetSizer(wx.BoxSizer(wx.VERTICAL))

        font = self.title.GetFont()
        font.SetPointSize(font.GetPointSize() + 2)
        self.title.SetFont(font)
        self.title.SetForegroundColour("#000000")

    def AddPanel(self, panel_class, settings):
        """Add a panel to the dialog"""
        panel = panel_class(parent=self.panels_container, settings=settings)
        self.panels_container.GetSizer().Add(panel, 1, wx.EXPAND)
        return panel

    def ShowPanel(self, panel):
        """Arrange for the given panel to be shown"""
        if self._current_panel is not None:
            self._current_panel.Hide()
        self._current_panel = panel
        panel.Show()
        sizer = self.panels_container.GetSizer()
        item = sizer.GetItem(panel)
        title = getattr(panel, "title", panel.location[-1])
        self.title.SetLabel(title)
        if item is None:
            sizer.Add(panel, 1, wx.EXPAND)
        sizer.Layout()

    def SetTitle(self, title):
        """Set the title of the panel"""
        self.title.SetLabel(title)
Exemplo n.º 10
0
def scrolledpanel(element, instance: ScrolledPanel):
    props = element['props']
    set_basic_props(instance, props)
    instance.SetupScrolling(
        scroll_x=props.get('scroll_x', False),
        scroll_y=props.get('scroll_y', False)
    )
    instance.Unbind(wx.EVT_LEFT_DOWN)
    if 'on_click' in props:
        instance.Bind(wx.EVT_LEFT_DOWN, props['on_click'])
    return instance
 def _create_body(self, plugins, activation_callback):
     panel = ScrolledPanel(self, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
     panel.SetupScrolling()
     sizer = wx.FlexGridSizer(1, 2, hgap=8, vgap=8)
     sizer.AddGrowableCol(1, 1)
     sizer.Add(self._create_label(panel, 'Enabled'), 0, wx.BOTTOM, border=8)
     sizer.Add(self._create_label(panel, 'Plugin'), 0,
               wx.BOTTOM|wx.EXPAND, border=8)
     for plugin in sorted(plugins, key=lambda p: p.name):
         sizer.Add(_PluginEnablationCheckBox(panel, plugin, activation_callback),
                   flag=wx.ALIGN_CENTER_HORIZONTAL)
         sizer.Add(_PluginRow(panel, plugin), 0, wx.EXPAND)
     panel.SetSizer(sizer)
     return panel
Exemplo n.º 12
0
class SimplePanel(PanelMixin, SizerMixin, Generic[C]):
    """A simple panel.

    Consider this the main canvas to which widgets can be attached.
    """
    @property
    def ui_item(self):
        """Return UI item."""
        return self._ui_item

    @property
    def _sizer(self):
        return self._sizer_

    def __init__(self, parent, controller: C, scrollable=False, **kwargs):
        """Init."""
        self._controller = controller
        if scrollable:
            self._ui_item = ScrolledPanel(parent)
            self._ui_item.SetupScrolling()
        else:
            self._ui_item = wx.Panel(parent)
        super().__init__()

        self._sizer_ = wx.BoxSizer(wx.VERTICAL)
        self.ui_item.SetSizer(self._sizer)
        self._ui_item.Parent.Bind(wx.EVT_SIZE, self._on_size)

    @property
    def controller(self) -> C:
        """Return the controller."""
        return self._controller

    def _on_size(self, evt):
        evt.Skip()

        # Ugly as hell. Makes wrapping text better though.
        # to check, open the "text wrapping window" in the demo. Maximize the screen
        # and normalize it again. Observer the difference between textbox sizes when
        # enabling or disabling this code below.
        wx.CallLater(1, self._refresh)
        wx.CallLater(2, self._refresh)
        wx.CallLater(3, self._refresh)

        self._refresh()

    def _refresh(self):
        _LOGGER.debug("posting size event")
        if self._ui_item:
            self._ui_item.PostSizeEvent()
Exemplo n.º 13
0
    def __init__(self, parent):
        wx.Dialog.__init__(self,
                           parent,
                           id=wx.ID_ANY,
                           title=u"车辆保险到期提醒",
                           pos=wx.DefaultPosition,
                           size=(800, 530),
                           style=wx.CAPTION | wx.STAY_ON_TOP
                           | wx.RESIZE_BORDER)

        self.alarm_time = None

        border = wx.BoxSizer(wx.VERTICAL)

        # 操作条
        opt_sizer = wx.BoxSizer(wx.HORIZONTAL)

        if not auth.Auth.logon_user[2] == 2:
            export_btn = wx.Button(self, wx.ID_ANY, u"导出")
            self.Bind(wx.EVT_BUTTON, self.on_export, export_btn)
            opt_sizer.Add(export_btn, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        border.Add(opt_sizer, 0, wx.ALIGN_RIGHT, 5)

        # 网格条
        grid_boxer = wx.BoxSizer(wx.HORIZONTAL)
        panel = ScrolledPanel(self, size=(780, 400))
        alarm_grid = vehiclepanel.VehicleGrid(panel)
        # 加载预警数据
        self.data = service.search_vehicle(30, None)
        alarm_grid.set_data(self.data)
        grid_boxer.Add(alarm_grid, 0, wx.ALIGN_TOP, 5)
        panel.SetSizer(grid_boxer)
        panel.Fit()
        panel.SetAutoLayout(1)
        panel.SetupScrolling()
        border.Add(panel, 0, wx.FIXED_MINSIZE, 5)

        # 按钮条
        buttons = wx.BoxSizer()
        self.close_btn = wx.Button(self, wx.ID_OK, u"关闭")
        self.close_btn.SetDefault()
        self.close_btn.Enable(False)
        buttons.Add(self.close_btn)
        border.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALL, 5)

        self.SetSizer(border)
Exemplo n.º 14
0
    def createInterface(self):
        panel = wx.Panel(self, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(wx.StaticText(panel, label='Current Vis Group : '))
        currVisGroupCombo = wx.Choice(panel, -1, choices=self.visGroupNames)
        currVisGroupCombo.Bind(wx.EVT_CHOICE, self.selectVisGroup)
        hbox.Add(currVisGroupCombo)
        panel.SetSizer(hbox)

        scrolledPanel = ScrolledPanel(self)
        vbox2 = wx.BoxSizer(wx.VERTICAL)

        self.checkBoxes = []
        for groupInfo in self.visGroups:
            nodePath = groupInfo[0]
            group = groupInfo[1]
            name = group.getName()
            checkBox = wx.CheckBox(scrolledPanel, -1, name)
            checkBox.Bind(wx.EVT_CHECKBOX,
                          lambda p0=None, p1=name: self.toggleVisGroup(p0, p1))
            self.checkBoxes.append(checkBox)
            vbox2.Add(checkBox)
            # Assemble list of groups visible from this group
            visible = []
            for i in range(group.getNumVisibles()):
                visible.append(group.getVisibleName(i))
            visible.sort()
            self.visDict[name] = [nodePath, group, visible]

        scrolledPanel.SetSizer(vbox2)
        scrolledPanel.SetupScrolling(scroll_y=True, rate_y=20)

        buttonPanel = wx.Panel(self, -1)
        self.showOptionBox = wx.RadioBox(buttonPanel,
                                         -1,
                                         "",
                                         choices=['Show All', 'Show Target'],
                                         majorDimension=1,
                                         style=wx.RA_SPECIFY_ROWS)
        self.showOptionBox.Bind(wx.EVT_RADIOBOX, self.refreshVisibility)
        vbox.Add(panel)
        vbox.Add(scrolledPanel, 1, wx.EXPAND, 0)
        vbox.Add(buttonPanel)
        self.SetSizer(vbox)
Exemplo n.º 15
0
def main():
    from wx.lib.scrolledpanel import ScrolledPanel
    app = wx.PySimpleApp()
    frame = wx.Frame(None, wx.ID_ANY, __doc__)
    #~ sizer = wx.GridSizer(1, 1)
    #~ canvas = irrlicht_canvas(frame)
    panel = ScrolledPanel(frame, wx.ID_ANY)
    sizer = wx.GridSizer(1, 1)
    canvas = irrlicht_canvas(panel)
    sizer.Add(canvas, 0, wx.EXPAND | wx.ALL)
    panel.SetSizer(sizer)
    panel.SetAutoLayout(1)
    panel.SetupScrolling()
    #~ frame.SetSizer(sizer)
    #~ frame.SetAutoLayout(1)
    app.SetTopWindow(frame)
    #~ frame.SetIcon(wx.IconFromBitmap(svg_to_bitmap(logo, (32, 32), use_cairo = False)))
    #~ frame.SetSize(canvas.GetVirtualSize())
    frame.Show()
    app.MainLoop()
Exemplo n.º 16
0
class ScrolledWindow(Frame):
    def __init__(self, contents, *args, **kw):
        super().__init__(*args, **kw)
        icon_bundle = self.GetParent().GetIcons()
        if not icon_bundle.IsEmpty():
            self.SetIcon(icon_bundle.GetIconByIndex(0))

        self.scrolled_panel = ScrolledPanel(self)
        self.contents = HelpText(self.scrolled_panel, style=TE_MULTILINE)
        self.layout()
        self.contents.SetLabel(contents)
        self.SetupScrolling()

    def layout(self):
        self.vbox = BoxSizer(VERTICAL)
        self.vbox.Add(self.contents, 0, ALL, 25)
        self.scrolled_panel.SetSizer(self.vbox)

    def Fit(self):
        self.scrolled_panel.Fit()
        return super().Fit()

    def SetupScrolling(self):
        self.Fit()
        width, height = self.GetSize()
        height = min(height, WINDOW_HEIGHT)
        self.SetSize(0, 0, width, height)

        self.scrolled_panel.SetupScrolling()

    def Show(self, show=True):
        if self.IsShown() and show:
            self.Raise()
        self.Center()
        return super().Show(show=show)

    def Destroy(self, is_destroy=False):
        self.Hide()
        return is_destroy
Exemplo n.º 17
0
class MyFrame(wx.Frame):
    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition,
                          wx.Size(600, 400))
        # Controls
        self.tin = wx.TextCtrl(self,
                               size=wx.Size(600, 400),
                               style=wx.TE_MULTILINE)
        self.test_panel = ScrolledPanel(self, size=wx.Size(600, 400))
        self.test_panel.SetupScrolling()
        self.tin2 = wx.StaticText(self.test_panel)

        # Layout
        # -- Scrolled Window
        self.panel_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.panel_sizer.Add(self.tin2, 0, wx.EXPAND)
        self.test_panel.SetSizer(self.panel_sizer)
        self.panel_sizer.Fit(self.test_panel)
        # -- Main Frame
        self.inner_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.inner_sizer.Add(self.tin, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 50)
        self.inner_sizer.Add(self.test_panel, 1,
                             wx.LEFT | wx.RIGHT | wx.EXPAND, 50)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.inner_sizer, 1, wx.ALL | wx.EXPAND, 20)
        self.SetSizer(self.sizer)
        self.sizer.Fit(self)
        self.sizer.Layout()

        self.test_panel.SetAutoLayout(1)

        # Bind Events
        self.tin.Bind(wx.EVT_TEXT, self.TextChange)

    def TextChange(self, event):
        self.tin2.SetLabel(self.tin.GetValue())
        self.test_panel.FitInside()
Exemplo n.º 18
0
    def initUI(self, num_sensors):
        """ Define dialog elements """
        ports = [""] + self.getSerialPorts()
        cameras = [""] + self.getCameraPorts()

        vbox0 = wx.BoxSizer(wx.VERTICAL)
        pnl = ScrolledPanel(self)
        vbox1 = wx.BoxSizer(wx.VERTICAL)

        hbox0 = wx.BoxSizer(wx.HORIZONTAL)
        st0 = wx.StaticText(pnl,
                            label="Number of sensor units per side",
                            size=(300, 30))
        hbox0.Add(st0, proportion=0, flag=wx.ALL)
        self.spinCtrl = wx.SpinCtrl(pnl, min=1, initial=num_sensors)
        self.spinCtrl.Bind(wx.EVT_TEXT, self.OnNumberChange)
        hbox0.Add(self.spinCtrl, proportion=0, flag=wx.ALL)

        vbox1.Add(hbox0, proportion=0, border=10, flag=wx.TOP | wx.BOTTOM)

        device_tuples = list(devices.values())
        self.checkbox_to_combobox = {}
        self.setting_to_checkbox = {}
        for device_tuple in device_tuples:
            name = device_tuple[0]
            scaling = device_tuple[1]
            vbox_aux = wx.BoxSizer(wx.VERTICAL)
            st_aux = wx.StaticText(pnl, label=name, size=(120, 30))
            vbox_aux.Add(st_aux, proportion=0, flag=wx.ALL)
            if scaling:
                for i in range(num_sensors):
                    self.addCheckComboBoxes(vbox_aux,
                                            pnl,
                                            ports,
                                            name,
                                            "L",
                                            number=i + 1)
                for i in range(num_sensors):
                    self.addCheckComboBoxes(vbox_aux,
                                            pnl,
                                            ports,
                                            name,
                                            "R",
                                            number=i + 1)
            else:
                self.addCheckComboBoxes(vbox_aux, pnl, ports, name, "L")
                self.addCheckComboBoxes(vbox_aux, pnl, ports, name, "R")
            vbox1.Add(vbox_aux,
                      proportion=0,
                      border=10,
                      flag=wx.TOP | wx.BOTTOM | wx.EXPAND)
        vbox_aux = wx.BoxSizer(wx.VERTICAL)
        st_aux = wx.StaticText(pnl, label="Camera", size=(120, 30))
        vbox_aux.Add(st_aux, proportion=0, flag=wx.ALL)
        vbox1.Add(vbox_aux,
                  proportion=1,
                  border=10,
                  flag=wx.TOP | wx.BOTTOM | wx.EXPAND)
        self.addCheckComboBoxes(vbox_aux, pnl, cameras, "Camera", "L")
        self.addCheckComboBoxes(vbox_aux, pnl, cameras, "Camera", "R")
        pnl.SetSizer(vbox1)
        pnl.SetupScrolling()

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        okButton = wx.Button(self, label="OK")
        cancelButton = wx.Button(self, label="Cancel")
        hbox1.Add(okButton)
        hbox1.Add(cancelButton, flag=wx.LEFT, border=5)
        okButton.Bind(wx.EVT_BUTTON, self.OnOK)
        cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)

        vbox0.Add(pnl, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        vbox0.Add(hbox1,
                  proportion=0,
                  flag=wx.ALIGN_CENTER | wx.ALL,
                  border=10)
        self.SetSizer(vbox0)
Exemplo n.º 19
0
    def __init__(self, parent, *args, devices=[], **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        self._Devices = devices
        self._Settings = self._Benchmarks = None
        self._Miners = [miner(main.CONFIG_DIR) for miner in all_miners]
        # dict of (device, algorithm) -> Item
        self._Items = {}
        self._Thread = None

        pub.subscribe(self._OnSettings, 'data.settings')
        pub.subscribe(self._OnBenchmarks, 'data.benchmarks')

        pub.subscribe(self._OnStartMining, 'mining.start')
        pub.subscribe(self._OnStopMining, 'mining.stop')

        pub.subscribe(self._OnClose, 'app.close')

        pub.subscribe(self._OnBenchmarkStatus, 'benchmarking.status')
        pub.subscribe(self._OnBenchmarkSet, 'benchmarking.set')
        pub.subscribe(self._OnBenchmarkClear, 'benchmarking.clear')
        pub.subscribe(self._OnBenchmarkStop, 'benchmarking.stop')

        self.Bind(EVT_SPEEDS, self.OnInputSpeeds)

        sizer = wx.BoxSizer(orient=wx.VERTICAL)
        self.SetSizer(sizer)

        # Create inner scrolled area.
        innerWindow = ScrolledPanel(self)
        innerWindow.SetupScrolling()
        sizer.Add(
            innerWindow,
            wx.SizerFlags().Border(wx.LEFT | wx.RIGHT | wx.TOP,
                                   main.PADDING_PX).Proportion(1.0).Expand())
        innerSizer = wx.BoxSizer(orient=wx.VERTICAL)
        innerWindow.SetSizer(innerSizer)

        # Populate it with a collapsible panel for each device.
        self._DeviceCp = {}
        for device in self._Devices:
            deviceCp = wx.CollapsiblePane(
                innerWindow,
                label=f'{device.name}\n{device.uuid}',
                style=wx.CP_NO_TLW_RESIZE)
            self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged,
                      deviceCp)
            innerSizer.Add(deviceCp, wx.SizerFlags().Expand())
            self._DeviceCp[device] = deviceCp

        bottomSizer = wx.BoxSizer(orient=wx.HORIZONTAL)
        sizer.Add(bottomSizer,
                  wx.SizerFlags().Border(wx.ALL, main.PADDING_PX).Expand())

        # Create bottom controls.
        self._SelectTodo = wx.Button(self, label='Unmeasured')
        self.Bind(wx.EVT_BUTTON, self.OnSelectUnmeasured, self._SelectTodo)
        bottomSizer.Add(self._SelectTodo)

        bottomSizer.AddSpacer(main.PADDING_PX)

        self._SelectNone = wx.Button(self, label='None')
        self.Bind(wx.EVT_BUTTON, self.OnSelectNone, self._SelectNone)
        bottomSizer.Add(self._SelectNone)

        bottomSizer.AddStretchSpacer()

        self._Benchmark = wx.Button(self, label='Benchmark')
        self.Bind(wx.EVT_BUTTON, self.OnBenchmark, self._Benchmark)
        bottomSizer.Add(self._Benchmark)
Exemplo n.º 20
0
class ExportAnalysisEvents(wx.Frame):
    def __init__(self, parent, analysis, ext="ext", non_scalars=[]):
        self.parent = parent
        self.analysis = analysis
        self.ext = ext
        self.toggled_event_features = True
        # Get the window positioning correctly
        pos = self.parent.GetPosition()
        pos = (pos[0] + 100, pos[1] + 100)
        wx.Frame.__init__(self,
                          parent=self.parent,
                          title="Export all event data",
                          pos=pos,
                          style=wx.DEFAULT_FRAME_STYLE
                          | wx.FRAME_FLOAT_ON_PARENT)
        ## panel
        self.panel = ScrolledPanel(self)
        self.panel.SetupScrolling()
        self.topSizer = wx.BoxSizer(wx.VERTICAL)
        # init
        textinit = wx.StaticText(
            self.panel,
            label="Export all event data as *.{} files.".format(ext))
        self.topSizer.Add(textinit)
        # Chechbox asking for Mono-Model
        horsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.WXCheckFilter = wx.CheckBox(self.panel,
                                         label="export filtered data only")
        self.WXCheckFilter.SetValue(True)
        horsizer.Add(self.WXCheckFilter, 0,
                     wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        horsizer.AddStretchSpacer()
        # Button to (de)select all variables
        btnselect = wx.Button(self.panel, wx.ID_ANY, "(De-)select all")
        self.Bind(wx.EVT_BUTTON, self.OnToggleAllEventFeatures, btnselect)
        horsizer.Add(btnselect, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        self.topSizer.Add(horsizer, 0, wx.EXPAND)
        ## Add checkboxes
        checks = []
        # find out which are actually used in the analysis
        for cc in dclab.dfn.scalar_feature_names:
            for mm in self.analysis.measurements:
                if cc in mm:
                    checks.append(cc)
        checks = non_scalars + sorted(list(set(checks)))
        self.box = wx.StaticBox(self.panel, label="Axes")
        self.sizerin = wx.StaticBoxSizer(self.box, wx.VERTICAL)
        # get longest text of checks
        dc = wx.ScreenDC()
        tl = np.max([dc.GetTextExtent(c)[0] for c in checks])
        sp = dc.GetTextExtent(" ")[0]

        for c in checks:
            # label id (b/c of sorting)
            lid = c + ":" + " " * ((tl - dc.GetTextExtent(c)[0]) // sp) + "\t"
            label = dclab.dfn.feature_name2label[c]
            cb = wx.CheckBox(self.panel, label=lid + label, name=c)
            self.sizerin.Add(cb)
            if c in self.analysis.GetPlotAxes():
                cb.SetValue(True)
        self.topSizer.Add(self.sizerin)
        btnbrws = wx.Button(self.panel, wx.ID_ANY, "Save to directory")
        # Binds the button to the function - close the tool
        self.Bind(wx.EVT_BUTTON, self.OnBrowse, btnbrws)
        self.topSizer.Add(btnbrws, 0, wx.EXPAND)
        self.panel.SetSizer(self.topSizer)
        self.topSizer.Fit(self)
        self.SetMinSize((self.topSizer.GetMinSizeTuple()[0], 500))
        #Icon
        if parent.MainIcon is not None:
            wx.Frame.SetIcon(self, parent.MainIcon)
        self.Show(True)

    def OnBrowse(self, e=None):
        """ Let the user select a directory and save
        everything in that directory.
        """
        # warn the user, if there are measurements that
        # have the same name.
        names = [m.title for m in self.analysis.measurements]
        dupl = list(set([n for n in names if names.count(n) > 1]))
        if len(dupl) != 0:
            dlg1 = wx.MessageDialog(self,
                message="Cannot export plots with duplicate titles: {}".format(
                            ", ".join(dupl))\
                        +"\nPlot titles can be edited in the 'Contour Plot' tab.",
                style=wx.OK|wx.ICON_ERROR)
            if dlg1.ShowModal() == wx.ID_OK:
                return

        # make directory dialog
        dlg2 = wx.DirDialog(
            self,
            message="Select directory for data export",
            defaultPath=self.parent.config.get_path("ExportData"),
            style=wx.DD_DEFAULT_STYLE)

        if dlg2.ShowModal() == wx.ID_OK:
            outdir = dlg2.GetPath().encode("utf-8")
            self.parent.config.set_path(outdir, "ExportData")

            # determine if user wants filtered data
            filtered = self.WXCheckFilter.IsChecked()

            # search all children for checkboxes that have
            # the names in dclab.dfn.feature_names
            names = dclab.dfn.feature_names
            features = []
            for ch in self.panel.GetChildren():
                if (isinstance(ch, wx._controls.CheckBox) and ch.IsChecked()):
                    name = ch.GetName()
                    if name in names:
                        features.append(name)

            # Call the export function of dclab.rtdc_dataset
            # Check if the files already exist
            for m in self.analysis.measurements:
                if os.path.exists(
                        os.path.join(outdir, m.title + "." + self.ext)):
                    msg = "Override existing .{} files in '{}'?".format(
                        self.ext, outdir)
                    dlg3 = wx.MessageDialog(self,
                                            message=msg,
                                            style=wx.YES_NO | wx.YES_DEFAULT
                                            | wx.ICON_QUESTION)
                    if dlg3.ShowModal() == wx.ID_YES:
                        # ok, leave loop
                        break
                    else:
                        # do not continue
                        return
            wx.BeginBusyCursor()
            self.export(out_dir=outdir, features=features, filtered=filtered)
            wx.EndBusyCursor()

    def OnToggleAllEventFeatures(self, e=None):
        """Set all values of the event features to 
        `self.toggled_event_features` and invert
        `self.toggled_event_features`.
        """
        panel = self.panel
        names = dclab.dfn.feature_names
        for ch in panel.GetChildren():
            if (isinstance(ch, wx._controls.CheckBox)
                    and ch.GetName() in names):
                ch.SetValue(self.toggled_event_features)

        # Invert for next execution
        self.toggled_event_features = not self.toggled_event_features

    @staticmethod
    def get_dataset_features(data_set, features):
        out_feat = []
        for feat in features:
            if feat in data_set:
                out_feat.append(feat)
        return out_feat

    def export(self, out_dir, features, filtered):
        raise NotImplementedError("Please subclass and rewrite this function.")
Exemplo n.º 21
0
class ImportTextDialog(wx.Dialog):
    requiredVariables = {'x':'x position [nm]',
                        'y':'y position [nm]'}
    recommendedVariables = {'A':'amplitude of Gaussian',
                            't':'time [frames]',
                            'sig':'std. deviation of Gaussian [nm]',
                            'error_x':'fit error in x direction [nm]'}
    niceVariables = {'error_y':'fit error in y direction [nm]'}

    def __init__(self, parent, textFileName):
        wx.Dialog.__init__(self, parent, title='Import data from text file')

        self.colNames, self.dataLines = self.TextFileHeaderParse(textFileName)

        sizer1 = wx.BoxSizer(wx.VERTICAL)
        #sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer1.Add(wx.StaticText(self, -1, 'Please assign variable names to each column. Some variable names must be present for the program to function correctly'), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)

        self.GenerateDataGrid(sizer1)

        sizer2 = wx.BoxSizer(wx.HORIZONTAL)

        self.stRequiredNotPresent = wx.StaticText(self, -1, 'Required variables not yet defined:\n')
        sizer2.Add(self.stRequiredNotPresent, 1,  wx.ALL, 5)

        self.stRecommendedNotPresent = wx.StaticText(self, -1, 'Recommended variables not yet defined:\n')
        sizer2.Add(self.stRecommendedNotPresent, 1, wx.ALL, 5)
        sizer1.Add(sizer2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL|wx.EXPAND, 5)
        
        sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer2.Add(wx.StaticText(self, -1, 'Pixel size [nm]:'), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        self.tPixelSize = wx.TextCtrl(self, -1, '1.0')
        sizer2.Add(self.tPixelSize, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        sizer1.Add(sizer2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL|wx.EXPAND, 5)
        
        btSizer = wx.StdDialogButtonSizer()

        self.btnOK = wx.Button(self, wx.ID_OK)
        self.btnOK.SetDefault()
        self.btnOK.Enable(False)

        btSizer.AddButton(self.btnOK)

        btn = wx.Button(self, wx.ID_CANCEL)

        btSizer.AddButton(btn)

        btSizer.Realize()

        sizer1.Add(btSizer, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)

        self.CheckColNames()

        self.SetSizer(sizer1)
        sizer1.Fit(self)

    def TextFileHeaderParse(self, filename):
        n = 0
        commentLines = []
        dataLines = []

        fid = open(filename, 'r')
        
        if filename.endswith('.csv'):
            delim = ','
        else:
            delim = None #whitespace

        while n < 10:
            line = fid.readline()
            if line.startswith('#'): #check for comments
                commentLines.append(line[1:])
            elif not isnumber(line.split(delim)[0]): #or textual header that is not a comment
                commentLines.append(line)
            else:
                dataLines.append(line.split(delim))
                n += 1
                
        self.numCommentLines = len(commentLines)

        numCols = len(dataLines[0])
        
        #print commentLines
        
        #print commentLines[-1].split(delim), len(commentLines[-1].split(delim)), numCols

        if len(commentLines) > 0 and len(commentLines[-1].split(delim)) == numCols:
            colNames = commentLines[-1].split(delim)
        else:
            colNames = ['column_%d' % i for i in range(numCols)]

        return colNames, dataLines

    def CheckColNames(self):
        reqNotDef = [var for var in self.requiredVariables.keys() if not var in self.colNames]

        if len(reqNotDef) > 0:
            self.btnOK.Enable(False)
            sreq = 'Required variables not yet defined:\n'
            for k in reqNotDef:
                sreq += '\n\t%s\t-\t%s' % (k, self.requiredVariables[k])
            self.stRequiredNotPresent.SetForegroundColour(wx.RED)
        else:
            self.btnOK.Enable(True)
            sreq = 'All required variables are defined\n'
            self.stRequiredNotPresent.SetForegroundColour(wx.GREEN)

        self.stRequiredNotPresent.SetLabel(sreq)

        recNotDef = [var for var in self.recommendedVariables.keys() if not var in self.colNames]

        if len(recNotDef) > 0:
            sreq = 'Recomended variables not yet defined:\n'
            for k in recNotDef:
                sreq += '\n\t%s\t-\t%s' % (k, self.recommendedVariables[k])
            self.stRecommendedNotPresent.SetForegroundColour(wx.Colour(200, 150, 0))
        else:
            sreq = 'All recommended variables are defined\n'
            self.stRecommendedNotPresent.SetForegroundColour(wx.GREEN)

        self.stRecommendedNotPresent.SetLabel(sreq)

        

    def GenerateDataGrid(self, sizer):
        vsizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Column names and preview:'))
        self.scrollW = ScrolledPanel(self, -1, size=(800, 150))
        self.comboIDs = []
        self.combos = []

        fgSizer = wx.FlexGridSizer(1+len(self.dataLines), len(self.colNames), 4, 4)

        for cn in self.colNames:
            id = wx.NewId()
            self.comboIDs.append(id)

            cb = wx.ComboBox(self.scrollW, id, size=(120, -1), choices=[cn]+ list(self.requiredVariables.keys()) +list(self.recommendedVariables.keys()) + list(self.niceVariables.keys()))
            self.combos.append(cb)
            cb.SetSelection(0)

            cb.Bind(wx.EVT_COMBOBOX, self.OnColNameChange)
            cb.Bind(wx.EVT_TEXT, self.OnColNameChange)

            fgSizer.Add(cb)

        for dl in self.dataLines:
            for de in dl:
                fgSizer.Add(wx.StaticText(self.scrollW, -1, de))

        self.scrollW.SetSizer(fgSizer)
        self.scrollW.SetAutoLayout(True)
        self.scrollW.SetupScrolling()

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

    def OnColNameChange(self, event):
        colNum = self.comboIDs.index(event.GetId())
        self.colNames[colNum] = self.combos[colNum].GetValue()

        self.CheckColNames()


    def GetFieldNames(self):
        return self.colNames
        
    def GetNumberComments(self):
        return self.numCommentLines
        
    def GetPixelSize(self):
        return float(self.tPixelSize.GetValue())
Exemplo n.º 22
0
class OnlineOfflineScreen(wx.Frame):
    """This class creates the graphical layout of the chatroom"""
    def __init__(self,user,passw):
        """This function sets the dimensions of the frame and
        the layout of the buttons"""
        self.user = user
        self.passw=passw
        wx.Frame.__init__(self, None, -1, 'Friends', 
                size=(500, 350))
        self.panel = ScrolledPanel(self, size = wx.Size( 500, 350 ))
        self.panel.SetupScrolling()
        self.Bind(wx.EVT_CLOSE, self.OnCloseMe)
        self.sizer = wx.FlexGridSizer(5,2,5,5)
        self.buttons=[]
        Publisher().subscribe(self.createButton, "update")
        Publisher().subscribe(self.updateButton, "updatebuttons")
        

    def OnCloseMe(self, event):
        """destroys the window"""
        self.Destroy()

    def updateButton(self, msg):
        """This method refreshes the chatroom window with button updates"""
        onoffdict = online_users(chat_login.UserText,chat_login.PasswordText)
        unreadmessages = unread_messages(chat_login.UserText,chat_login.PasswordText)
        a=onoffdict
        u=unreadmessages
        for key in a:
            KeyFound = False
            for button in self.buttons:
                if (button.parameterVal==key):
                    KeyFound = True
                    if(a[key]==1):
                        button.SetBackgroundColour('#89E398')
                    elif a[key]==0:
                        button.SetBackgroundColour('#E6E6E6')
                    if(u[key]==0):
                        button.SetLabel(key) 
                    else:
                        button.SetLabel(key+' ('+str(u[key])+')')

            if (KeyFound==False):
                if(self.user==key):
                    pass
                else:
                    if(a[key]==1):
                        if(u[key]==0):
                            b = wx.Button(self.panel, -1, key) 
                        else:
                            b = wx.Button(self.panel, -1, key+' ('+str(u[key])+')')
                        self.buttons.append(b)
                        b.Enable(True)
                        b.SetBackgroundColour('#89E398') 
                        self.sizer.Add(b,0,wx.EXPAND)
                        b.parameterVal=key
                        b.Bind(wx.EVT_BUTTON,self.OnB)
                        self.panel.SetSizer(self.sizer)
                        w, h = self.GetClientSize()
                        self.SetSize((w, h))
                        self.Show()
                        
                    elif(a[key]==0):
                        if(u[key]==0):
                            b = wx.Button(self.panel, -1, key) 
                        else:
                            b = wx.Button(self.panel, -1, key+' ('+str(u[key])+')')
                        self.buttons.append(b)
                        b.Enable(True)
                        button.SetBackgroundColour('#E6E6E6')
                        self.sizer.Add(b,0,wx.EXPAND)
                        b.parameterVal=key
                        b.Bind(wx.EVT_BUTTON,self.OnB)
                        self.panel.SetSizer(self.sizer)
                        w, h = self.GetClientSize()
                        self.SetSize((w, h))
                        self.Show()
                
            
    def createButton(self, msg):
        """This method gets a dictionary of online/offline users. After iterating
            through the dictionary, it creates a green button to indicate an
            online user and normal button to indicate offline user"""
        onoffdict = online_users(chat_login.UserText,chat_login.PasswordText)
        unreadmessages = unread_messages(chat_login.UserText,chat_login.PasswordText)
        a=onoffdict
        u=unreadmessages
        for key in a:
            if(self.user==key):
                pass
            else:
                if(a[key]==1):
                    if(u[key]==0):
                        b = wx.Button(self.panel, -1, key) 
                    else:
                        b = wx.Button(self.panel, -1, key+' ('+str(u[key])+')')
                    self.buttons.append(b)
                    b.Enable(True)
                    b.SetBackgroundColour('#89E398') 
                    self.sizer.Add(b,0,wx.EXPAND)
                    b.parameterVal=key
                    b.Bind(wx.EVT_BUTTON,self.OnB)
                    self.panel.SetSizer(self.sizer)
                    
                elif(a[key]==0):
                    if(u[key]==0):
                        b = wx.Button(self.panel, -1, key) 
                    else:
                        b = wx.Button(self.panel, -1, key+' ('+str(u[key])+')')
                    self.buttons.append(b)
                    b.Enable(True)
                    b.SetBackgroundColour('#E6E6E6')
                    self.sizer.Add(b,0,wx.EXPAND)
                    b.parameterVal=key
                    b.Bind(wx.EVT_BUTTON,self.OnB)
                    self.panel.SetSizer(self.sizer)
        self.Centre()
        self.Show()
        
    def OnB(self, event):
        """This method contains an event handler which opens a specific chat
            window of the person whose button is pressed"""
        bp = event.GetEventObject()
        friend = bp.parameterVal
        app1 = wx.PySimpleApp(0)
        wx.InitAllImageHandlers()
        frame_1 = ChatScreen(self.user, self.passw,friend, None, -1, "")
        TextThread()
        app1.SetTopWindow(frame_1)
        frame_1.Show()
        app1.MainLoop()
Exemplo n.º 23
0
class BatchFilterFolder(wx.Frame):
    def __init__(self, parent, analysis):
        self.parent = parent
        self.analysis = analysis
        self.out_tsv_file = None
        self.data_files = None
        self.axes_panel_sizer = None
        # Features checks
        self.toggled_event_features = True
        # Statistical parameters checks
        self.toggled_stat_parms = False

        # Get the window positioning correctly
        wx.Frame.__init__(self,
                          parent=self.parent,
                          title="Batch filtering",
                          style=wx.DEFAULT_FRAME_STYLE
                          | wx.FRAME_FLOAT_ON_PARENT)
        ## panel
        panel = self.panel = wx.Panel(self)
        self.topSizer = wx.BoxSizer(wx.VERTICAL)
        # init
        self.topSizer.Add(
            wx.StaticText(panel,
            label="Apply the filter setting of one measurement\n"+\
                  "to all measurements within a folder and\n"+\
                  "save selected statistical parameters.")
            )
        self.topSizer.AddSpacer(10)
        ## Filter source selection
        boxleft = wx.StaticBox(panel, label="Filter settings")
        self.rbtnhere = wx.RadioButton(panel,
                                       -1,
                                       'Current session',
                                       style=wx.RB_GROUP)
        self.rbtnhere.SetValue(True)
        self.rbtnthere = wx.RadioButton(panel, -1, 'Other source')
        self.rbtnthere.Disable()
        self.dropdown = wx.ComboBox(panel, -1, "", (15, 30), wx.DefaultSize,
                                    [], wx.CB_DROPDOWN | wx.CB_READONLY)
        # Create the dropdownlist
        self.Bind(wx.EVT_RADIOBUTTON, self.OnRadioHere, self.rbtnhere)
        self.Bind(wx.EVT_RADIOBUTTON, self.OnRadioThere, self.rbtnthere)
        self.Bind(wx.EVT_COMBOBOX, self.OnSelectMeasurement, self.dropdown)
        leftSizer = wx.StaticBoxSizer(boxleft, wx.VERTICAL)
        leftSizer.Add(self.rbtnhere)
        leftSizer.Add(self.rbtnthere)
        leftSizer.AddSpacer(5)
        leftSizer.Add(self.dropdown)
        leftSizer.AddSpacer(5)
        self.topSizer.Add(leftSizer, 0, wx.EXPAND)
        self.topSizer.AddSpacer(10)

        ## Folder selection
        boxfold = wx.StaticBox(panel, label="Input folder")
        foldSizer = wx.StaticBoxSizer(boxfold, wx.VERTICAL)
        btnbrws = wx.Button(panel, wx.ID_ANY, "Browse")
        # Binds the button to the function - close the tool
        self.Bind(wx.EVT_BUTTON, self.OnBrowse, btnbrws)
        self.WXfold_text1 = wx.StaticText(
            panel, label="Folder containing RT-DC measurements")
        self.WXdropdown_flowrate = wx.ComboBox(panel, -1, "All measurements",
                                               (15, 30), wx.DefaultSize,
                                               ["All measurements"],
                                               wx.CB_DROPDOWN | wx.CB_READONLY)
        self.WXdropdown_flowrate.Disable()
        self.WXdropdown_region = wx.ComboBox(
            panel, -1, "Channel and Reservoir", (15, 30), wx.DefaultSize,
            ["Channel and Reservoir", "Channel only", "Reservoir only"],
            wx.CB_DROPDOWN | wx.CB_READONLY)
        fold2sizer = wx.BoxSizer(wx.HORIZONTAL)
        fold2sizer.Add(btnbrws)
        fold2sizer.Add(self.WXfold_text1, 0,
                       wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        foldSizer.AddSpacer(5)
        foldSizer.Add(fold2sizer, 0,
                      wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        foldSizer.Add(self.WXdropdown_flowrate, 0, wx.EXPAND | wx.ALL)
        foldSizer.Add(self.WXdropdown_region, 0, wx.EXPAND | wx.ALL)
        foldSizer.AddSpacer(5)
        self.topSizer.Add(foldSizer, 0, wx.EXPAND)
        self.topSizer.AddSpacer(10)

        ## Axes checkboxes
        self.axes_panel = ScrolledPanel(panel, -1, size=(-1, 200))
        self.axes_panel.SetupScrolling()
        self.topSizer.Add(self.axes_panel, 1, wx.EXPAND)
        self.topSizer.AddSpacer(10)

        ## Statistical parameters
        self.stat_panel = ScrolledPanel(panel, -1, size=(-1, 200))
        self.stat_panel.SetupScrolling()
        self.topSizer.Add(self.stat_panel, 1, wx.EXPAND)
        self.topSizer.AddSpacer(10)
        self.SetupStatisticalParameters()

        ## Output selection
        boxtsv = wx.StaticBox(panel, label="Output file")
        tsvSizer = wx.StaticBoxSizer(boxtsv, wx.VERTICAL)
        btnbrwstsv = wx.Button(panel, wx.ID_ANY, "Browse")
        # Binds the button to the function - close the tool
        self.Bind(wx.EVT_BUTTON, self.OnBrowseTSV, btnbrwstsv)
        self.WXtsv_text1 = wx.StaticText(
            panel, label="Results of statistical analysis")
        tsv2sizer = wx.BoxSizer(wx.HORIZONTAL)
        tsv2sizer.Add(btnbrwstsv)
        tsv2sizer.Add(self.WXtsv_text1, 0,
                      wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        tsvSizer.AddSpacer(5)
        tsvSizer.Add(tsv2sizer, 0,
                     wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
        self.topSizer.Add(tsvSizer, 0, wx.EXPAND)

        ## Batch button
        btnbatch = wx.Button(self.panel, wx.ID_ANY, "Perform batch filtering")
        # Binds the button to the function - close the tool
        self.Bind(wx.EVT_BUTTON, self.OnBatch, btnbatch)
        self.topSizer.Add(btnbatch, 0, wx.EXPAND)
        btnbatch.Disable()
        self.btnbatch = btnbatch

        panel.SetSizer(self.topSizer)
        self.topSizer.Fit(self.panel)
        self.SetMinSize(self.topSizer.GetMinSizeTuple())

        self.OnRadioHere()
        #Icon
        if parent.MainIcon is not None:
            wx.Frame.SetIcon(self, parent.MainIcon)
        self.Show(True)

    def OnBatch(self, e=None):
        wx.BeginBusyCursor()
        # Get selected axes
        features = []
        for ch in self.axes_panel.GetChildren():
            if (isinstance(ch, wx._controls.CheckBox) and ch.IsChecked()):
                name = ch.GetName()
                if name in dclab.dfn.scalar_feature_names:
                    features.append(name)
        # Get selected features
        col_dict = dclab.statistics.Statistics.available_methods
        methods = []
        for ch in self.stat_panel.GetChildren():
            if (isinstance(ch, wx._controls.CheckBox) and ch.IsChecked()):
                name = ch.GetName()
                if name in col_dict:
                    methods.append(name)
        # Get filter configuration of selected measurement
        if self.rbtnhere.GetValue():
            mhere = self.analysis.measurements[self.dropdown.GetSelection()]
            f_config = mhere.config
        # Compute statistics
        head = None
        rows = []
        # Determine which flow rates to use
        idflow = self.WXdropdown_flowrate.GetSelection() - 1
        if idflow < 0:
            files = self.data_files
        else:
            files = self.flow_dict[self.flow_rates[idflow]]
        # Filter regions
        regid = self.WXdropdown_region.GetSelection()
        if regid > 0:
            if regid == 1:
                reg = "channel"
            elif regid == 2:
                reg = "reservoir"
            newfiles = []
            for tt in files:
                if meta_tool.get_chip_region(tt) == reg:
                    newfiles.append(tt)
            files = newfiles
        if not files:
            raise ValueError("No valid measurements with current selection!")

        # Process each data file separately to reduce memory usage
        for data in files:
            # Make analysis from data file
            anal = analysis.Analysis([data], config=f_config)
            mm = anal.measurements[0]
            # Apply filters
            mm.apply_filter()
            # Get statistics
            h, v = dclab.statistics.get_statistics(rtdc_ds=mm,
                                                   methods=methods,
                                                   features=features)
            if head is None:
                head = h
            else:
                assert h == head, "Problem with available methods/features!"

            rows.append([mm.path, mm.title] + v)

        head = ["data file", "Title"] + head

        with io.open(self.out_tsv_file, "w") as fd:
            header = u"\t".join([h for h in head])
            fd.write("# " + header + "\n")

        with open(self.out_tsv_file, "ab") as fd:
            for row in rows:
                fmt = ["{:s}"] * 2 + ["{:.10e}"] * len(v)
                line = "\t".join(fmt).format(*row)
                fd.write(line + "\n")
        wx.EndBusyCursor()

    def OnBrowse(self, e=None):
        """ Let the user select a directory and search that directory
        for RT-DC data sets.
        """
        # make directory dialog
        dlg2 = wx.DirDialog(
            self,
            message="Please select directory containing measurements",
            defaultPath=self.parent.config.get_path("BatchFD"),
            style=wx.DD_DEFAULT_STYLE)

        if dlg2.ShowModal() == wx.ID_OK:
            thepath = dlg2.GetPath().encode("utf-8")
        else:
            thepath = None
        dlg2.Destroy()
        wx.Yield()
        if thepath is not None:
            wx.BeginBusyCursor()
            self.WXfold_text1.SetLabel(thepath)
            self.parent.config.set_path(thepath, "BatchFD")
            # Search directory
            tree, _cols = meta_tool.collect_data_tree(thepath)
            self.data_files = [t[1][1] for t in tree]

            if self.out_tsv_file is not None:
                self.btnbatch.Enable()
            wx.EndBusyCursor()

        # Update WXdropdown_flowrate and self.flow_rates
        # Determine flow rates
        flow_dict = {}
        for tt in self.data_files:
            fr = meta_tool.get_flow_rate(tt)
            if fr not in flow_dict:
                flow_dict[fr] = []
            flow_dict[fr].append(tt)
        selections = ["All measurements ({})".format(len(self.data_files))]
        self.flow_rates = list(flow_dict.keys())
        self.flow_rates.sort()
        for fr in self.flow_rates:
            num = len(flow_dict[fr])
            selections += ["Flow rate {} µl/s ({})".format(fr, num)]
        self.WXdropdown_flowrate.SetItems(selections)
        self.WXdropdown_flowrate.SetSelection(0)
        self.WXdropdown_flowrate.Enable()
        self.flow_dict = flow_dict

    def OnBrowseTSV(self, e=None):
        dlg2 = wx.FileDialog(
            self,
            message="Please select an output file.",
            defaultDir=self.parent.config.get_path("BatchOut"),
            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
            wildcard="TSV files" + " (*.tsv)|*.tsv")

        if dlg2.ShowModal() == wx.ID_OK:
            thepath = dlg2.GetPath().encode("utf-8")
            if not thepath.endswith(".tsv"):
                thepath += ".tsv"
            self.WXtsv_text1.SetLabel(thepath)
            thedir = os.path.dirname(thepath)
            self.parent.config.set_path(thedir, "BatchOut")
            self.out_tsv_file = thepath

        if self.data_files is not None:
            self.btnbatch.Enable()

    def OnRadioHere(self, e=None):
        meas = [mm.title for mm in self.analysis.measurements]
        self.dropdown.SetItems(meas)
        self.dropdown.SetSelection(0)
        self.OnSelectMeasurement()

    def OnRadioThere(self, e=None):
        self.OnUpdateAxes()
        self.filter_config = None

    def OnSelectMeasurement(self, e=None):
        ## Remove initial stuff
        sizer = self.axes_panel_sizer
        panel = self.axes_panel
        if sizer is not None:
            for child in sizer.GetChildren():
                window = child.GetWindow()
                panel.RemoveChild(window)
                sizer.RemoveWindow(window)
                window.Destroy()
            sizerin = sizer
        else:
            box = wx.StaticBox(self.axes_panel, label="Event features")
            sizerbox = wx.StaticBoxSizer(box, wx.HORIZONTAL)
            sizerin = wx.BoxSizer(orient=wx.VERTICAL)
            sizerbox.Add(sizerin)
            sizersel = wx.BoxSizer(orient=wx.VERTICAL)
            btnselect = wx.Button(self.axes_panel, wx.ID_ANY,
                                  "(De-)select all")
            sizersel.Add(btnselect, 0, wx.ALIGN_RIGHT)
            sizerbox.Add(sizersel, 1, wx.EXPAND | wx.ALIGN_RIGHT)
            self.Bind(wx.EVT_BUTTON, self.OnToggleAllEventFeatures, btnselect)
            sizerbox.AddSpacer(5)

        self.axes_panel_sizer = sizerin

        checks = []
        if self.rbtnhere.Value:
            sel = self.dropdown.GetSelection()
            mm = self.analysis.measurements[sel]
            for c in dclab.dfn.scalar_feature_names:
                if c in mm:
                    checks.append(c)
        else:
            for c in dclab.dfn.scalar_feature_names:
                checks.append(c)

        checks = list(set(checks))
        labels = [dclab.dfn.feature_name2label[c] for c in checks]

        # Sort checks according to labels
        checks = [x for (_y, x) in sorted(zip(labels, checks))]
        labels.sort()

        for c, l in zip(checks, labels):
            # label id (b/c of sorting)
            label = l
            cb = wx.CheckBox(self.axes_panel, label=label, name=c)
            sizerin.Add(cb)
            if c in self.analysis.GetPlotAxes():
                cb.SetValue(True)

        self.axes_panel.SetupScrolling()
        self.axes_panel.SetSizer(sizerbox)
        sizerbox.Fit(self.axes_panel)
        self.topSizer.Fit(self.panel)
        size = self.topSizer.GetMinSizeTuple()
        self.SetSize((size[0] + 1, -1))
        self.SetSize((size[0] - 1, -1))

    def OnToggleAllEventFeatures(self, e=None):
        """Set all values of the event features to 
        `self.toggled_event_features` and invert
        `self.toggled_event_features`.
        """
        panel = self.axes_panel
        for ch in panel.GetChildren():
            if isinstance(ch, wx._controls.CheckBox):
                ch.SetValue(self.toggled_event_features)

        # Invert for next execution
        self.toggled_event_features = not self.toggled_event_features

    def OnToggleAllStatParms(self, e=None):
        """Set all values of the statistical parameters to 
        `self.toggled_stat_parms` and invert
        `self.toggled_stat_parms`.
        """
        panel = self.stat_panel
        for ch in panel.GetChildren():
            if isinstance(ch, wx._controls.CheckBox):
                ch.SetValue(self.toggled_stat_parms)

        # Invert for next execution
        self.toggled_stat_parms = not self.toggled_stat_parms

    def SetupStatisticalParameters(self, e=None):
        ## Remove initial stuff
        box = wx.StaticBox(self.stat_panel, label="Statistical parameters")
        sizerbox = wx.StaticBoxSizer(box, wx.HORIZONTAL)
        sizerin = wx.BoxSizer(orient=wx.VERTICAL)
        sizerbox.Add(sizerin)
        sizersel = wx.BoxSizer(orient=wx.VERTICAL)
        btnselect = wx.Button(self.stat_panel, wx.ID_ANY, "(De-)select all")
        sizersel.Add(btnselect, 0, wx.ALIGN_RIGHT)
        sizerbox.Add(sizersel, 1, wx.EXPAND | wx.ALIGN_RIGHT)
        self.Bind(wx.EVT_BUTTON, self.OnToggleAllStatParms, btnselect)
        sizerbox.AddSpacer(5)

        checks = list(dclab.statistics.Statistics.available_methods.keys())
        checks.sort()

        for c in checks:
            # label id (b/c of sorting)
            cb = wx.CheckBox(self.stat_panel, label=c, name=c)
            sizerin.Add(cb)
            cb.SetValue(True)

        self.stat_panel.SetupScrolling()
        self.stat_panel.SetSizer(sizerbox)
        sizerbox.Fit(self.stat_panel)
class ProjectPropertiesPanel(wx.Notebook):
    def AddSizerParams(self, parent, sizer, params):
        for idx, (name, label) in enumerate(params):
            border = 0
            if idx == 0:
                border |= wx.TOP
            elif idx == len(params) - 1:
                border |= wx.BOTTOM

            st = wx.StaticText(parent, label=label)
            sizer.AddWindow(st,
                            border=10,
                            flag=wx.ALIGN_CENTER_VERTICAL | border | wx.LEFT)

            tc = wx.TextCtrl(parent, style=wx.TE_PROCESS_ENTER)
            setattr(self, name, tc)
            callback = self.GetTextCtrlChangedFunction(tc, name)
            self.Bind(wx.EVT_TEXT_ENTER, callback, tc)
            tc.Bind(wx.EVT_KILL_FOCUS, callback)
            sizer.AddWindow(tc, border=10, flag=wx.GROW | border | wx.RIGHT)

    def __init__(self,
                 parent,
                 controller=None,
                 window=None,
                 enable_required=True,
                 scrolling=True):
        wx.Notebook.__init__(self, parent)

        self.Controller = controller
        self.ParentWindow = window
        self.Values = None

        # Project Panel elements

        self.ProjectPanel = ScrolledPanel(self, style=wx.TAB_TRAVERSAL)
        self.ProjectPanel.SetAutoLayout(1)
        if scrolling:
            self.ProjectPanel.SetupScrolling()
        projectpanel_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=5, vgap=15)
        projectpanel_sizer.AddGrowableCol(1)
        self.ProjectPanel.SetSizer(projectpanel_sizer)

        self.AddSizerParams(
            self.ProjectPanel, projectpanel_sizer,
            [("projectName", _('Project Name (required):')),
             ("projectVersion", _('Project Version (optional):')),
             ("productName", _('Product Name (required):')),
             ("productVersion", _('Product Version (required):')),
             ("productRelease", _('Product Release (optional):'))])

        self.AddPage(self.ProjectPanel, _("Project"))

        # Author Panel elements

        self.AuthorPanel = ScrolledPanel(self, style=wx.TAB_TRAVERSAL)
        self.AuthorPanel.SetAutoLayout(1)
        if scrolling:
            self.AuthorPanel.SetupScrolling()
        authorpanel_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=4, vgap=15)
        authorpanel_sizer.AddGrowableCol(1)
        self.AuthorPanel.SetSizer(authorpanel_sizer)

        self.AddSizerParams(self.AuthorPanel, authorpanel_sizer,
                            [("companyName", _('Company Name (required):')),
                             ("companyURL", _('Company URL (optional):')),
                             ("authorName", _('Author Name (optional):')),
                             ("organization", _('Organization (optional):'))])

        self.AddPage(self.AuthorPanel, _("Author"))

        # Graphics Panel elements

        self.GraphicsPanel = ScrolledPanel(self, style=wx.TAB_TRAVERSAL)
        self.GraphicsPanel.SetAutoLayout(1)
        if scrolling:
            self.GraphicsPanel.SetupScrolling()
        graphicpanel_sizer = wx.FlexGridSizer(cols=1, hgap=5, rows=4, vgap=5)
        graphicpanel_sizer.AddGrowableCol(0)
        graphicpanel_sizer.AddGrowableRow(3)
        self.GraphicsPanel.SetSizer(graphicpanel_sizer)

        pageSize_st = wx.StaticText(self.GraphicsPanel,
                                    label=_('Page Size (optional):'))
        graphicpanel_sizer.AddWindow(pageSize_st,
                                     border=10,
                                     flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP
                                     | wx.LEFT | wx.RIGHT)

        pageSize_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5)
        pageSize_sizer.AddGrowableCol(1)
        graphicpanel_sizer.AddSizer(pageSize_sizer,
                                    border=10,
                                    flag=wx.GROW | wx.LEFT | wx.RIGHT)

        for name, label in [('PageWidth', _('Width:')),
                            ('PageHeight', _('Height:'))]:
            st = wx.StaticText(self.GraphicsPanel, label=label)
            pageSize_sizer.AddWindow(st,
                                     border=12,
                                     flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT)

            sp = wx.SpinCtrl(self.GraphicsPanel,
                             min=0,
                             max=2**16,
                             style=wx.TE_PROCESS_ENTER)
            setattr(self, name, sp)
            callback = self.GetPageSizeChangedFunction(sp, name)
            self.Bind(wx.EVT_TEXT_ENTER, callback, sp)
            sp.Bind(wx.EVT_KILL_FOCUS, callback)
            pageSize_sizer.AddWindow(sp, flag=wx.GROW)

        scaling_st = wx.StaticText(self.GraphicsPanel,
                                   label=_('Grid Resolution:'))
        graphicpanel_sizer.AddWindow(scaling_st,
                                     border=10,
                                     flag=wx.GROW | wx.LEFT | wx.RIGHT)

        scaling_nb = wx.Notebook(self.GraphicsPanel)
        graphicpanel_sizer.AddWindow(scaling_nb,
                                     border=10,
                                     flag=wx.GROW | wx.BOTTOM | wx.LEFT
                                     | wx.RIGHT)

        self.Scalings = {}
        for language, translation in [("FBD", _("FBD")), ("LD", _("LD")),
                                      ("SFC", _("SFC"))]:
            scaling_panel = wx.Panel(scaling_nb, style=wx.TAB_TRAVERSAL)
            scalingpanel_sizer = wx.FlexGridSizer(cols=2,
                                                  hgap=5,
                                                  rows=2,
                                                  vgap=5)
            scalingpanel_sizer.AddGrowableCol(1)
            scaling_panel.SetSizer(scalingpanel_sizer)

            scaling_controls = []
            for idx, (name, label) in enumerate([('XScale', _('Horizontal:')),
                                                 ('YScale', _('Vertical:'))]):
                if idx == 0:
                    border = wx.TOP
                else:
                    border = wx.BOTTOM

                st = wx.StaticText(scaling_panel, label=label)
                scalingpanel_sizer.AddWindow(st,
                                             border=10,
                                             flag=wx.ALIGN_CENTER_VERTICAL
                                             | border | wx.LEFT)

                sp = wx.SpinCtrl(scaling_panel,
                                 min=0,
                                 max=2**16,
                                 style=wx.TE_PROCESS_ENTER)
                scaling_controls.append(sp)
                callback = self.GetScalingChangedFunction(sp, language, name)
                self.Bind(wx.EVT_TEXT_ENTER, callback, sp)
                sp.Bind(wx.EVT_KILL_FOCUS, callback)
                scalingpanel_sizer.AddWindow(sp,
                                             border=10,
                                             flag=wx.GROW | border | wx.RIGHT)

            self.Scalings[language] = scaling_controls
            scaling_nb.AddPage(scaling_panel, translation)

        self.AddPage(self.GraphicsPanel, _("Graphics"))

        # Miscellaneous Panel elements

        self.DescriptionPanel = ScrolledPanel(parent=self,
                                              name='DescriptionPanel',
                                              style=wx.TAB_TRAVERSAL)
        self.DescriptionPanel.SetAutoLayout(1)
        if scrolling:
            self.DescriptionPanel.SetupScrolling()
        DescriptionPanel_sizer = wx.FlexGridSizer(cols=1,
                                                  hgap=5,
                                                  rows=5,
                                                  vgap=5)
        DescriptionPanel_sizer.AddGrowableCol(0)
        DescriptionPanel_sizer.AddGrowableRow(4)
        self.DescriptionPanel.SetSizer(DescriptionPanel_sizer)

        description_label = wx.StaticText(
            self.DescriptionPanel, label=_('Content Description (optional):'))
        DescriptionPanel_sizer.AddWindow(description_label,
                                         border=10,
                                         flag=wx.TOP | wx.LEFT)

        self.ContentDescription = wx.TextCtrl(self.DescriptionPanel,
                                              size=wx.Size(400, 200),
                                              style=wx.TE_MULTILINE
                                              | wx.TE_PROCESS_ENTER)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnContentDescriptionChanged,
                  self.ContentDescription)
        self.ContentDescription.Bind(wx.EVT_KILL_FOCUS,
                                     self.OnContentDescriptionChanged)
        DescriptionPanel_sizer.AddWindow(self.ContentDescription,
                                         border=10,
                                         flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP
                                         | wx.LEFT | wx.RIGHT)

        self.AddPage(self.DescriptionPanel, _("Description"))

        for param in REQUIRED_PARAMS:
            getattr(self, param).Enable(enable_required)

    def RefreshView(self):
        if self.Controller is not None:
            self.SetValues(self.Controller.GetProjectProperties())

    def SetValues(self, values):
        self.Values = values
        for item, value in values.items():
            if item == "contentDescription":
                self.ContentDescription.SetValue(value)
            elif item == "pageSize":
                self.PageWidth.SetValue(value[0])
                self.PageHeight.SetValue(value[1])
            elif item == "scaling":
                for language, (x, y) in value.items():
                    if language in self.Scalings:
                        self.Scalings[language][0].SetValue(x)
                        self.Scalings[language][1].SetValue(y)
            else:
                tc = getattr(self, item, None)
                if tc is not None:
                    tc.SetValue(value)

    def GetValues(self):
        values = {}
        for param in [
                "projectName", "projectVersion", "productName",
                "productVersion", "productRelease", "companyName",
                "companyURL", "authorName", "organization"
        ]:
            value = getattr(self, param).GetValue()
            if param in REQUIRED_PARAMS or value != "":
                values[param] = value
            else:
                values[param] = None
        values["language"] = None
        content_description = self.ContentDescription.GetValue()
        if content_description != "":
            values["contentDescription"] = content_description
        else:
            values["contentDescription"] = None
        values["pageSize"] = (self.PageWidth.GetValue(),
                              self.PageHeight.GetValue())
        values["scaling"] = {}
        for language in ["FBD", "LD", "SFC"]:
            values["scaling"][language] = (
                self.Scalings[language][0].GetValue(),
                self.Scalings[language][1].GetValue())
        return values

    def GetTextCtrlChangedFunction(self, textctrl, name):
        def TextCtrlChangedFunction(event):
            if self.Controller is not None and self.Values is not None:
                old_value = self.Values.get(name)
                new_value = textctrl.GetValue()
                if name in REQUIRED_PARAMS and new_value == "":
                    new_value = None
                if name == 'companyURL':
                    if not URI_model.match(new_value):
                        new_value = None
                        dialog = wx.MessageDialog(
                            self,
                            _('Invalid URL!\n'
                              'Please enter correct URL address.'), _("Error"),
                            wx.OK | wx.ICON_ERROR)
                        dialog.ShowModal()
                        dialog.Destroy()
                if old_value != new_value:
                    self.Controller.SetProjectProperties(
                        properties={name: new_value})
                    self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU,
                                               PROJECTTREE, PAGETITLES)
                    wx.CallAfter(self.RefreshView)
            event.Skip()

        return TextCtrlChangedFunction

    def GetPageSizeChangedFunction(self, spinctrl, name):
        def PageSizeChangedFunction(event):
            if self.Controller is not None:
                if self.Values is not None:
                    old_value = self.Values.get("pageSize")
                else:
                    old_value = (0, 0)
                if name == 'PageWidth':
                    new_value = (spinctrl.GetValue(), old_value[1])
                else:
                    new_value = (old_value[0], spinctrl.GetValue())
                if old_value != new_value:
                    self.Controller.SetProjectProperties(
                        properties={"pageSize": new_value})
                    self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU,
                                               PAGETITLES, SCALING)
                    wx.CallAfter(self.RefreshView)
            event.Skip()

        return PageSizeChangedFunction

    def GetScalingChangedFunction(self, spinctrl, language, name):
        def ScalingChangedFunction(event):
            if self.Controller is not None:
                old_value = (0, 0)
                if self.Values is not None:
                    scaling = self.Values.get("scaling")
                    if scaling is not None:
                        old_value = scaling.get(language)
                if name == 'XScale':
                    new_value = (spinctrl.GetValue(), old_value[1])
                else:
                    new_value = (old_value[0], spinctrl.GetValue())
                if old_value != new_value:
                    self.Controller.SetProjectProperties(
                        properties={"scaling": {
                            language: new_value
                        }})
                    self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU,
                                               PAGETITLES, SCALING)
                    wx.CallAfter(self.RefreshView)
            event.Skip()

        return ScalingChangedFunction

    def OnContentDescriptionChanged(self, event):
        if self.Controller is not None:
            if self.Values is not None:
                old_value = self.Values.get("contentDescription")
            else:
                old_value = None
            new_value = self.ContentDescription.GetValue()
            if new_value == "":
                new_value = None
            if old_value != new_value:
                self.Controller.SetProjectProperties(
                    properties={"contentDescription": new_value})
                self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU,
                                           PAGETITLES)
                wx.CallAfter(self.RefreshView)
        event.Skip()
Exemplo n.º 25
0
class DubList(wx.Frame):
    class Node(wx.TextCtrl):
        def __init__(self, parent, id, value, pos, size, style, validator,
                     name, listPtr):
            super(DubList.Node, self).__init__(parent, id, value, pos, size,
                                               style, validator, name)
            print "Node"

            self.nodesizer = wx.FlexGridSizer(cols=2, vgap=1, hgap=1)
            self.popButton = wx.Button(self, wx.ID_ANY, "K",
                                       wx.DefaultPosition, (11, 11))
            self.pushButton = wx.Button(self, wx.ID_ANY, "P",
                                        wx.DefaultPosition + (0, 13), (11, 11))
            self.listManager = listPtr
            self.next = None
            self.prev = None
            self.val = None
            self.point = self.GetPosition()

            self.Bind(wx.EVT_BUTTON, listPtr.onRemove, self.popButton)
            self.Bind(wx.EVT_BUTTON, listPtr.onPush, self.pushButton)

    def __init__(self, parent, id, title, pos, size, style, name):
        super(DubList, self).__init__(parent, id, title, pos, size, style,
                                      name)

        masterSizer = wx.BoxSizer(wx.VERTICAL)
        #self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
        self.nodeNumbers = 0
        #self.listWindow = scrolledpanel(self, wx.ID_ANY, self.Position, self.Size, wx.VSCROLL, "list window")
        self.listWindow = ScrolledPanel(self, wx.ID_ANY, self.GetPosition(),
                                        self.GetSize(),
                                        wx.TAB_TRAVERSAL | wx.VSCROLL,
                                        "list window")
        self.listWindow.SetupScrolling(0, 1, 0, 20, 1, 1)

        #self.listWindow.SetScrollRate(5,5) not needced
        self.listOfNodes = []
        self.mysizer = wx.GridBagSizer(5, 5)
        #self.mysizer = wx.BoxSizer(wx.VERTICAL)

        button = wx.Button(self.listWindow, wx.ID_ANY, "push new node",
                           wx.DefaultPosition + (150, 0), wx.DefaultSize, 0,
                           wx.DefaultValidator, "make")
        button.Bind(wx.EVT_BUTTON, self.buttonDown, button)

        button0 = wx.Button(self.listWindow, wx.ID_ANY, "pop last node",
                            wx.DefaultPosition + (260, 0), wx.DefaultSize,
                            wx.BU_EXACTFIT, wx.DefaultValidator, "take")
        button0.Bind(wx.EVT_BUTTON, self.button0Down, button0)

        #layout
        #self.mysizer.SetSizeHints(self.listWindow) not needed
        #self.mysizer.Add(button, 0,0,1,None)
        #self.mysizer.Add(button0, 0,0,1,None)

        self.mysizer.Add(button, (0, 1), (0, 0), 0, 1, "addButton")
        self.mysizer.Add(button0, (1, 1), (0, 0), 0, 1, "removeButton")

        self.listWindow.SetSizer(self.mysizer)
        self.mysizer.Fit(self.listWindow)

        self.listWindow.SetAutoLayout(1)

    def onRemove(self, event):
        button = event.GetEventObject()
        button = button.GetParent()
        print "middle pop", button.val

        #patch pointers of adjacent Nodes
        if button.prev is not None:
            button.prev.next = button.next

        if button.next is not None:
            button.next.prev = button.prev

        #iter = button.next

        position = self.mysizer.FindItem(button)  #find GBSizerItem

        gap = position.GetPos()

        iter = button
        self.mysizer.Detach(button)

        #push all the itesm below the target node up one unit
        while (iter):
            if (iter.next is not None):
                newgap = self.mysizer.GetItemPosition(iter.next)
                self.mysizer.SetItemPosition(iter.next, gap)
                gap = newgap
                iter = iter.next
            else:
                break

        self.listOfNodes.remove(button)
        self.mysizer.FitInside(self.listWindow)

        self.mysizer.Layout()
        button.Destroy()

    def onPush(self, event):

        #get infor for shifter
        button = event.GetEventObject()
        button = button.GetParent()
        print "middle push", button.val
        namestring = "button" + str(self.nodeNumbers)
        #get index of node being clicked
        print "index", 2 + self.listOfNodes.index(button)
        targetIndex = self.listOfNodes.index(button)
        targetposition = self.mysizer.GetItemPosition(button)
        targetposition.Row += 1
        #push new node at btome of clicked node, and shift whole list bewlow it, down one Unit
        firstNode = self.listOfNodes[targetIndex]  # head of list

        #shifter
        #walk is how many nodes we need to push down, or "walk" to
        walk = 0
        while firstNode.next is not None:  #iter until eol
            firstNode = firstNode.next
            walk += 1

        while walk:
            lastPos = self.mysizer.GetItemPosition(firstNode)
            lastPos.row += 1
            self.mysizer.SetItemPosition(firstNode, lastPos)
            firstNode = firstNode.prev
            walk -= 1

        #malloc and push
        create = self.Node(self.listWindow, wx.ID_ANY, namestring,
                           wx.DefaultPosition, wx.DefaultSize, 0,
                           wx.DefaultValidator, namestring, self)
        if firstNode.next:
            firstNode.next.prev = create
            create.next = firstNode.next

        firstNode.next = create
        create.prev = firstNode

        self.listOfNodes.insert(targetIndex + 1, create)
        self.nodeNumbers += 1
        self.mysizer.Add(create, targetposition, (0, 0), 0, 1, namestring)
        self.mysizer.FitInside(self.listWindow)
        self.listWindow.ScrollChildIntoView(create)
        print self.nodeNumbers

    def buttonDown(self, event):
        print "LIST: push pressed"
        namestring = "button"
        # a list
        if len(self.listOfNodes) is not 0:
            firstNode = self.listOfNodes[0]  # head of list

            while firstNode.next is not None:  #iter until eol
                firstNode = firstNode.next

            namestring += str(self.nodeNumbers)
            #create = Node(self.listWindow, wx.ID_ANY,namestring,firstNode.point + (0,25), wx.DefaultSize, 0, wx.DefaultValidator, namestring)
            create = self.Node(self.listWindow, wx.ID_ANY, namestring,
                               firstNode.point, wx.DefaultSize, 0,
                               wx.DefaultValidator, namestring, self)
            create.val = len(self.listOfNodes)

            firstNode.next = create
            create.prev = firstNode
            # no list
        else:
            namestring += str(len(self.listOfNodes))
            create = self.Node(self.listWindow, wx.ID_ANY, namestring,
                               wx.DefaultPosition, wx.DefaultSize, 0,
                               wx.DefaultValidator, namestring, self)
            create.val = len(self.listOfNodes)
            create.parent = self
        self.nodeNumbers += 1
        #self.mysizer.Add(create,0,0,1,namestring) #boxsizer add
        self.mysizer.Add(create, (1 + len(self.listOfNodes), 2), (0, 0), 0, 1,
                         namestring)
        self.listOfNodes.append(create)
        self.mysizer.FitInside(self.listWindow)
        #self.listWindow.SetFocus()not needed
        self.listWindow.ScrollChildIntoView(create)
        #self.listWindow.Refresh() not needed
        #self.listWindow.Update()  not needed
        #self.mysizer.Layout()     not needed
        print self.nodeNumbers

    def button0Down(self, event):
        print "LIST: pop pressed"
        if len(self.listOfNodes) is not 0:
            lastNode = self.listOfNodes[len(self.listOfNodes) -
                                        1]  #grab last node
            try:
                prev = lastNode.prev
                prev.next = None
            except:
                print "last node"

            self.mysizer.Detach(lastNode)
            self.listOfNodes.remove(lastNode)
            lastNode.Destroy()
            self.mysizer.FitInside(self.listWindow)
            self.mysizer.Layout()
        else:
            print "no list"
Exemplo n.º 26
0
    def __init__(self, parent=None, *args, **kw):
        super().__init__(parent,
                         title='Azur Lane Combat Counter',
                         style=wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX
                         | wx.SYSTEM_MENU | wx.TAB_TRAVERSAL | wx.RESIZE_BORDER
                         | wx.CLIP_CHILDREN,
                         *args,
                         **kw)

        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
        self.SetBackgroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))

        frame_sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(frame_sizer)

        header_sizer = wx.BoxSizer(wx.HORIZONTAL)
        frame_sizer.Add(header_sizer, 0, wx.EXPAND | wx.ALL, border=5)

        self.spin = wx.SpinCtrl(self,
                                min=0,
                                max=99999,
                                style=wx.ALIGN_CENTER_HORIZONTAL
                                | wx.SP_ARROW_KEYS | wx.SP_WRAP
                                | wx.TE_PROCESS_ENTER)
        self.spin.SetFont(
            wx.Font(30, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL, False, "Segoe UI"))
        self.spin.Bind(wx.EVT_SPINCTRL,
                       lambda e: self.on_number_change(e.GetPosition()))
        self.spin.Bind(wx.EVT_TEXT,
                       lambda e: self.on_number_change(e.GetInt()))

        header_sizer.Add(self.spin, 1, flag=wx.ALL)

        display_checkbox = wx.CheckBox(self, label='Display')
        display_checkbox.Bind(wx.EVT_CHECKBOX,
                              lambda e: self.on_display_check(e.IsChecked()))

        header_sizer.Add(display_checkbox,
                         flag=wx.CENTER | wx.LEFT | wx.RIGHT,
                         border=40)

        info_panel = ScrolledPanel(self,
                                   style=wx.BORDER_THEME | wx.TAB_TRAVERSAL)
        info_panel.SetBackgroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENU))

        panel_sizer = wx.BoxSizer(wx.VERTICAL)
        info_panel.SetSizer(panel_sizer)

        self.info_text = wx.StaticText(info_panel)
        self.info_text.Wrap(-1)
        self.info_text.SetFocus()  # this removes focus from the SpinCtrl

        panel_sizer.Add(self.info_text, 0, wx.ALL, border=5)

        info_panel.Layout()
        info_panel.SetupScrolling()
        panel_sizer.FitInside(info_panel)
        frame_sizer.Add(info_panel, 1, wx.EXPAND | wx.ALL, border=5)

        self.Layout()
        self.Centre(wx.BOTH)
Exemplo n.º 27
0
class EditDialog(wx.Dialog):
    def __init__(self, edit_url):
        super().__init__(parent=None,
                         title=preset.message["edit_title"] + "[" +
                         edit_url.URL_Name + "]",
                         size=(700, 590),
                         style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.url = edit_url

        self.scrolled_panel = ScrolledPanel(self)
        self.scrolled_panel.SetupScrolling()

        self.left_box_sizer = wx.BoxSizer(wx.VERTICAL)
        self.right_box_sizer = wx.BoxSizer(wx.VERTICAL)

        max_length = 0
        for item in preset.label_dictionary:
            label_length = len(preset.label_dictionary[item])
            if label_length > max_length:
                max_length = label_length

        self.attribute_list = []
        for index, item in enumerate(edit_url.to_list()):
            element_value = edit_url.get_position(index)
            if isinstance(element_value, datetime.datetime):
                item_value = utils.date_to_string(element_value)
            else:
                item_value = str(element_value)
            self.attribute_list.append(
                wx.TextCtrl(self.scrolled_panel, value=item_value))
            dialog_place = "left"
            if index > 21:
                dialog_place = "right"
            self.add_widgets(edit_url.get_label(str(index)),
                             self.attribute_list[index], dialog_place,
                             max_length)

        cancel_button = wx.Button(self,
                                  id=wx.ID_CANCEL,
                                  label=preset.message["cancel_button"])

        save_button = wx.Button(self,
                                id=wx.ID_OK,
                                label=preset.message["edit_save"])
        save_button.Bind(wx.EVT_BUTTON, self.on_save)

        horizontal_box_sizer = wx.BoxSizer(wx.HORIZONTAL)
        horizontal_box_sizer.Add(self.left_box_sizer, 1, wx.EXPAND, 1)
        horizontal_box_sizer.Add(self.right_box_sizer, 1, wx.EXPAND, 1)

        self.scrolled_panel.SetSizer(horizontal_box_sizer)
        self.scrolled_panel.SetAutoLayout(1)

        button_box_sizer = wx.BoxSizer(wx.HORIZONTAL)
        button_box_sizer.Add(save_button, 1)
        button_box_sizer.Add(cancel_button, 1)

        main_box_sizer = wx.BoxSizer(wx.VERTICAL)
        main_box_sizer.Add(self.scrolled_panel, 1, wx.EXPAND, 1)
        main_box_sizer.Add(button_box_sizer, 0, wx.ALL | wx.EXPAND, 0)

        self.SetSizer(main_box_sizer)

    def add_widgets(self, text_label, text_ctrl, dialog_place, max_length):
        spaces_gap = max_length - len(text_label)
        text_label = text_label + " " * spaces_gap + ":"
        static_text = wx.StaticText(self.scrolled_panel,
                                    label=text_label,
                                    size=(max_length * 8, -1))
        static_text.SetFont(
            wx.Font(8, wx.TELETYPE, wx.NORMAL, wx.BOLD, underline=True))

        static_bullet = wx.StaticText(self.scrolled_panel,
                                      label=" °",
                                      size=(14, -1))
        static_bullet.SetFont(wx.Font(8, wx.TELETYPE, wx.NORMAL, wx.BOLD))

        box_sizer_horizontal = wx.BoxSizer(wx.HORIZONTAL)
        box_sizer_horizontal.Add(static_bullet, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        box_sizer_horizontal.Add(static_text, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        box_sizer_horizontal.Add(text_ctrl, 1, wx.ALL, 0)

        if dialog_place == "left":
            self.left_box_sizer.Add(box_sizer_horizontal, 1, wx.EXPAND, 1)
        else:
            self.right_box_sizer.Add(box_sizer_horizontal, 1, wx.EXPAND, 1)

    def on_save(self, event):
        save_list = []
        for element in self.attribute_list:
            save_list.append(element.GetValue())
        self.url.set_data(save_list)
        self.EndModal(event.EventObject.Id)
Exemplo n.º 28
0
class PRIMEAdvancedOptions(BaseDialog):
    ''' Advanced Options Dialog'''
    def __init__(self,
                 parent,
                 phil=None,
                 label_style='bold',
                 content_style='normal',
                 *args,
                 **kwargs):

        BaseDialog.__init__(self,
                            parent,
                            label_style=label_style,
                            content_style=content_style,
                            size=(600, 300),
                            *args,
                            **kwargs)

        # Create options panel (all objects should be called as self.options.object)
        self.options = ScrolledPanel(self, size=(-1, 300))
        options_sizer = wx.BoxSizer(wx.VERTICAL)
        self.options.SetSizer(options_sizer)

        phil_box = wx.StaticBox(self, label='PRIME Input')
        phil_box_sizer = wx.StaticBoxSizer(phil_box, wx.VERTICAL)

        # Target file input
        self.phil = ct.PHILBox(self,
                               btn_import=False,
                               btn_export=False,
                               btn_default=False,
                               ctr_size=(500, 200),
                               ctr_value='')
        phil_box_sizer.Add(self.phil, 1, flag=wx.EXPAND | wx.ALL, border=10)

        # PRIME Options (there is some redundancy with the PHIL textbox)
        opt_box = wx.StaticBox(self.options, label='Advanced Options')
        opt_box_sizer = wx.StaticBoxSizer(opt_box, wx.VERTICAL)

        # Resolution
        self.res_override = wx.CheckBox(self.options,
                                        label='Resolution override')
        self.res = ct.OptionCtrl(self.options,
                                 label='Resolution: ',
                                 label_size=(120, -1),
                                 label_style='normal',
                                 ctrl_size=wx.DefaultSize,
                                 items=[('high', 50), ('low', 1.5)])
        opt_box_sizer.Add(self.res_override, flag=f.stack, border=10)
        opt_box_sizer.Add(self.res, flag=f.stack, border=10)

        # Target space group
        self.sg = ct.OptionCtrl(self.options,
                                label='Space Group: ',
                                label_size=(120, -1),
                                label_style='normal',
                                ctrl_size=(100, -1),
                                items=[('spacegroup', 'P212121')])
        opt_box_sizer.Add(self.sg, flag=f.stack, border=10)

        # Target unit cell
        self.uc = ct.OptionCtrl(self.options,
                                label='Unit Cell: ',
                                label_size=(120, -1),
                                label_style='normal',
                                ctrl_size=(300, -1),
                                items=[('unit_cell', '72 120 134 90 90 90')])
        self.anom = wx.CheckBox(self.options, label='Anomalous')
        self.anom.SetValue(False)
        opt_box_sizer.Add(self.uc, flag=f.stack, border=10)
        opt_box_sizer.Add(self.anom, flag=f.stack, border=10)

        # CC cutoff
        self.cc = ct.OptionCtrl(self.options,
                                label='CC cutoff: ',
                                label_size=(120, -1),
                                label_style='normal',
                                ctrl_size=(100, -1),
                                items=[('cc_cutoff', 0.25)])
        opt_box_sizer.Add(self.cc, flag=f.stack, border=10)

        # Pixel size
        self.pix = ct.OptionCtrl(self.options,
                                 label='Pixel size: ',
                                 label_size=(120, -1),
                                 label_style='normal',
                                 ctrl_size=(100, -1),
                                 items=[('pixel_size', 0.172)])
        opt_box_sizer.Add(self.pix,
                          flag=wx.RIGHT | wx.LEFT | wx.TOP,
                          border=10)

        self.cycles = ct.SpinCtrl(self.options,
                                  label='No. of Cycles:',
                                  label_size=(120, -1),
                                  label_style='normal',
                                  ctrl_size=(60, -1))
        opt_box_sizer.Add(self.cycles, flag=wx.ALL, border=10)

        # Dialog controls
        dialog_box = self.CreateSeparatedButtonSizer(wx.OK | wx.CANCEL)

        options_sizer.Add(opt_box_sizer, 1, flag=f.expand, border=10)
        self.main_sizer.Add(phil_box_sizer,
                            1,
                            flag=wx.EXPAND | wx.ALL,
                            border=10)
        self.main_sizer.Add(self.options,
                            1,
                            flag=wx.EXPAND | wx.ALL,
                            border=10)
        self.main_sizer.Add(dialog_box,
                            flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.ALL,
                            border=10)

        self.options.SetupScrolling()
Exemplo n.º 29
0
class InjectionInputsPanel(pdsim_panels.PDPanel):
    """
    The container panel for all the injection ports and injection data 
    """
    def __init__(self, parent, **kwargs):
        pdsim_panels.PDPanel.__init__(self, parent, **kwargs)

        #Now we are going to put everything into a scrolled window
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        self.scrolled_panel = ScrolledPanel(self,
                                            size=(-1, -1),
                                            style=wx.TAB_TRAVERSAL,
                                            name="panel1")
        self.scrolled_panel.SetScrollbars(1, 1, 1, 1)
        self.scrolled_panel.SetupScrolling()

        #Add the header row of buttons
        self.View = wx.Button(self.scrolled_panel, label='View')
        self.View.Bind(wx.EVT_BUTTON, self.OnView)
        self.AddInjection = wx.Button(self.scrolled_panel,
                                      label='Add Injection Line')
        self.AddInjection.Bind(wx.EVT_BUTTON, self.OnAddInjection)
        self.PlotExistence = wx.Button(self.scrolled_panel,
                                       label='Plot Existence')
        self.PlotExistence.Bind(wx.EVT_BUTTON, self.OnPlotExistence)
        buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
        buttons_sizer.Add(self.AddInjection)
        buttons_sizer.Add(self.View)
        buttons_sizer.Add(self.PlotExistence)

        sizer = wx.FlexGridSizer(cols=1)
        sizer.Add(buttons_sizer)
        sizer.AddSpacer(10)
        sizer.Layout()

        self.scrolled_panel.SetAutoLayout(1)

        #Do the layout of all the panels
        self.scrolled_panel.SetSizer(sizer)
        main_sizer.Add(self.scrolled_panel, 1, wx.EXPAND)
        self.SetSizer(main_sizer)
        main_sizer.Layout()

        #Set some local variables
        self.Nterms = 0
        self.Lines = []

    def OnAddInjection(self, event=None):
        """
        Add an injection line to the injection panel
        """
        IE = InjectionElementPanel(self.scrolled_panel, self.Nterms + 1)
        #Put the panel within the scrolled panel and refresh
        self.scrolled_panel.GetSizer().Add(IE, 0)
        self.scrolled_panel.FitInside()
        self.GetSizer().Layout()

        #Update the local variables
        self.Lines.append(IE)
        self.Nterms += 1

        self.Refresh()

    def remove_all(self):
        while self.Lines:
            self.RemoveInjection(self.Lines[0])

    def RemoveInjection(self, injection):
        """
        Remove the given injection term
        """
        self.Lines.remove(injection)
        injection.Destroy()
        self.Nterms -= 1
        #Renumber the injection panels that are contained in scrolled_panel
        I = 1
        for child in self.scrolled_panel.Children:
            if isinstance(child, InjectionElementPanel):
                child.SizerBox.SetLabel("Injection line #" + str(I))
                I += 1
        self.GetSizer().Layout()
        self.scrolled_panel.FitInside()
        self.Refresh()

    def OnView(self, event):

        geo = self.GetTopLevelParent().MTB.InputsTB.panels[0].Scroll.geo
        SAF = ScrollAnimForm(geo, start=False)

        #IEPs are children that are instances of InjectionElementPanel class
        IEPs = [
            child for child in self.scrolled_panel.Children
            if isinstance(child, InjectionElementPanel)
        ]
        for IEP in IEPs:
            for child in IEP.Children:
                if isinstance(child, InjectionPortPanel):
                    # Get the values from the panel
                    vals = child.get_values()
                    # Overlay the port on the scroll wrap plot
                    scroll_geo.overlay_injection_port(0,
                                                      geo,
                                                      vals['phi'],
                                                      SAF.ax,
                                                      vals['involute'],
                                                      rport=vals['D'] / 2,
                                                      offset=vals['offset'])
        SAF.start()
        SAF.Show()

    def OnPlotExistence(self, event=None):
        """
        Plot a 2D line plot showing which control volume is connected to 
        each injection port as a function of the crank angle
        """
        import pylab
        import numpy as np

        _Scroll = self.GetTopLevelParent().MTB.InputsTB.panels[0].Scroll

        Iport = 1
        #IEPs are children that are instances of InjectionElementPanel class
        IEPs = [
            child for child in self.scrolled_panel.Children
            if isinstance(child, InjectionElementPanel)
        ]
        for IEP in IEPs:
            for child in IEP.Children:
                if isinstance(child, InjectionPortPanel):
                    #Get the values from the port panel
                    v = child.get_values()

                    partner_list = []

                    theta = np.linspace(0, 2 * pi, 1000)
                    for th in theta:
                        partner_list.append(
                            _Scroll._get_injection_CVkey(
                                v['phi'], th, v['involute']))

                    #Find the break points in each segment
                    dividers = [
                        i for i in range(len(theta) - 1)
                        if not partner_list[i] == partner_list[i + 1]
                    ]
                    #Add end and beginning indices
                    dividers = [0] + dividers + [len(theta) - 1]

                    for i in range(len(dividers) - 1):
                        L = dividers[i]
                        R = dividers[i + 1]
                        M = int((L + R) / 2)
                        pylab.plot(np.r_[theta[L], theta[R]], np.r_[Iport,
                                                                    Iport])
                        pylab.plot(np.r_[theta[L], theta[L]],
                                   np.r_[Iport - 0.02, Iport + 0.02], 'k')
                        pylab.plot(np.r_[theta[R], theta[R]],
                                   np.r_[Iport - 0.02, Iport + 0.02], 'k')
                        pylab.text(theta[M],
                                   Iport + .02,
                                   partner_list[M],
                                   ha='center',
                                   va='bottom')

                    #Increase the counter
                    Iport += 1

        pylab.xticks([0, pi / 2, pi, 3 * pi / 2, 2 * pi],
                     [0, r'$\pi/2$', r'$\pi$', r'$3\pi/2$', r'$2\pi$'])
        pylab.xlim(0, 2 * pi)
        pylab.ylim(0.5, Iport - 1 + 0.5)
        pylab.yticks(range(1, Iport + 1))
        pylab.show()

    def build_from_configfile(self, config):
        """
        Get parameters from the configfile section for this plugin
        
        Parameters
        ----------
        config : yaml configuration section for the plugin
        
        """

        if config:
            self.remove_all()
            for line in config:
                # Add an injection line panel
                self.OnAddInjection()
                #Get a pointer to the last IEP (the one just added)
                IEP = self.Lines[-1]
                #Set the line length in the GUI [m]
                IEP.Lval.SetValue(str(line['Length']))
                #Set the line ID in the GUI
                IEP.IDval.SetValue(str(line['ID']))
                #Set the State in the GUI
                State = line['inletState']
                IEP.state.set_state(State['Fluid'],
                                    T=State['T'],
                                    D=State['rho'])
                if 'ports' in line and line['ports']:
                    for i, port in enumerate(line['ports']):
                        if i > 0: IEP.OnAddPort()
                        # Get a pointer to the port panel
                        portpanel = IEP.ports_list[-1]
                        # Set the values in the panel
                        portpanel.set_values(port)

    def get_additional_parametric_terms(self):

        #: the list of terms
        _T = []

        #IEPs are children of injection_panel that are instances of InjectionElementPanel class
        IEPs = [
            child for child in self.scrolled_panel.Children
            if isinstance(child, InjectionElementPanel)
        ]
        for i, IEP in enumerate(IEPs):
            I = str(i + 1)

            _T += [
                dict(attr='injection_state_pressure_' + I,
                     text='Injection pressure #' + I + ' [kPa]',
                     parent=self),
                dict(attr='injection_state_sat_temp_' + I,
                     text='Injection saturated temperature (dew) #' + I +
                     ' [K]',
                     parent=self),
                dict(attr='injection_state_temp_' + I,
                     text='Injection temperature #' + I + ' [K]',
                     parent=self),
                dict(attr='injection_state_superheat_' + I,
                     text='Injection superheat #' + I + ' [K]',
                     parent=self),
            ]

            Ports = [
                c for c in IEP.Children if isinstance(c, InjectionPortPanel)
            ]
            for j, child in enumerate(Ports):
                J = str(j + 1)
                _T += [
                    dict(attr='injection_phi_' + I + '_' + J,
                         text='Injection port angle #' + I + ':' + J +
                         ' [rad]',
                         parent=self)
                ]

        return _T

    def apply_additional_parametric_terms(self, attrs, vals, panel_items):
        """
        Set the terms in the injection panel based on the additional parametric
        terms provided by the get_additional_parametric_terms() function
        """
        def apply_line_terms(attrs, vals):
            def is_int(i):
                """ Returns True if it is an integer """
                try:
                    i = int(i)
                    return True
                except ValueError:
                    return False

            def is_line_term(attr):
                """
                Check if it is a line type term of the form injection_xxxxx_1'
                and is not a port term of the form injection_xxxxx_1_1
                """
                if not attr.startswith('injection'):
                    return False

                #If there are no underscores, return false
                if len(attr.rsplit('_', 1)) == 1:
                    return False

                #Try to split twice
                attr, i, j = attr.rsplit('_', 2)

                # If the far right one is an integer and the left part isn't you are
                # ok, its an injection line
                if not is_int(i) and is_int(j):
                    return True
                else:
                    return False

            # First check about the injection state; if two state related terms are
            # provided, use them to fix the injection state
            inj_state_params = [(par, val) for par, val in zip(attrs, vals)
                                if is_line_term(par)]
            num_inj_state_params = len(inj_state_params)

            for i in range(len(self.Lines)):

                #Find the injection state terms that apply for this line
                state_params = [
                    (par, val) for par, val in zip(attrs, vals)
                    if par.find('state') > -1 and par.endswith(str(i + 1))
                ]
                num_state_params = len(state_params)

                #Get a copy of the state from the StatePanel
                inletState = self.Lines[i].state.GetState()

                if num_state_params > 0:
                    #Unzip the parameters (List of tuples -> tuple of lists)
                    state_attrs, state_vals = zip(*state_params)

                if num_state_params == 2:
                    # Remove all the entries that correspond to the injection state -
                    # we need them and don't want to set them in the conventional way
                    for a in state_attrs:
                        vals.pop(attrs.index(a))
                        attrs.pop(attrs.index(a))

                    #: The string representation of the index (1-based)
                    I = str(i + 1)

                    #Temperature and pressure provided
                    if 'injection_state_temp_' + I in state_attrs and 'injection_state_pressure_' + I in state_attrs:
                        injection_temp = state_vals[state_attrs.index(
                            'injection_state_temp_' + I)]
                        injection_pressure = state_vals[state_attrs.index(
                            'injection_state_pressure_' + I)]
                        self.Lines[i].state.set_state(inletState.Fluid,
                                                      T=injection_temp,
                                                      P=injection_pressure)

                    #Dew temperature and superheat provided
                    elif 'injection_state_sat_temp_' + I in state_attrs and 'injection_state_superheat_' + I in state_attrs:
                        injection_sat_temp = state_vals[state_attrs.index(
                            'injection_state_sat_temp_' + I)]
                        injection_superheat = state_vals[state_attrs.index(
                            'injection_state_superheat_' + I)]
                        injection_temp = injection_sat_temp + injection_superheat
                        import CoolProp.CoolProp as CP
                        injection_pressure = CP.PropsSI(
                            'P', 'T', injection_sat_temp, 'Q', 1.0,
                            inletState.Fluid) / 1000.0
                        self.Lines[i].state.set_state(inletState.Fluid,
                                                      T=injection_temp,
                                                      P=injection_pressure)

                    else:
                        raise ValueError(
                            'Invalid combination of injection states: ' +
                            str(state_attrs))

                elif num_inj_state_params == 1:
                    import textwrap
                    string = textwrap.dedent("""
                             Sorry but you need to provide two variables for the injection
                             state in parametric table to fix the state.  
                             
                             If you want to just modify the saturated temperature, add the superheat as a
                             variable and give it one element in the parametric table
                             """)
                    dlg = wx.MessageDialog(None, string)
                    dlg.ShowModal()
                    dlg.Destroy()
                    raise ValueError(
                        'Must provide two state variables in the parametric table for injection line'
                    )

                elif num_inj_state_params > 2:
                    raise ValueError(
                        'Only two inlet state parameters can be provided in parametric table'
                    )

            return attrs, vals

        def apply_port_terms(attrs, vals):
            phi_params = [(par, val) for par, val in zip(attrs, vals)
                          if par.startswith('injection_phi')]
            num_phi_params = len(phi_params)

            if num_phi_params > 0:
                #Unzip the parameters (List of tuples -> tuple of lists)
                phi_attrs, phi_vals = zip(*phi_params)

                # Remove all the entries that correspond to the angles
                # we need them and don't want to set them in the conventional way
                for a in phi_attrs:
                    i = attrs.index(a)
                    vals.pop(i)
                    attrs.pop(i)

                for attr, val in zip(phi_attrs, phi_vals):

                    # Term might look like something like 'injection_phi_1_2'
                    # i would be 0, j would be 1
                    #indices are zero-based
                    j = int(attr.rsplit('_', 1)[1]) - 1
                    i = int(attr.rsplit('_', 2)[1]) - 1

                    self.Lines[i].ports_list[j].phi_inj_port.SetValue(str(val))

            return attrs, vals

        #Apply all the line terms and get back the lists
        attrs, vals = apply_line_terms(attrs, vals)
        #Apply all the line terms and get back the lists
        attrs, vals = apply_port_terms(attrs, vals)

        return attrs, vals
Exemplo n.º 30
0
    def __init__(self, parent, exc_type, exc_value, exc_info, exc_msg):
        wx.Dialog.__init__(self, parent, 
                title="fr0st has encountered an error")

        self.exc_msg = exc_msg

        self.show_label = "Show Error Report >>"
        self.hide_label = "Hide Error Report <<"

        self.collapsible = wx.CollapsiblePane(self, label=self.show_label)

        pane = self.collapsible.GetPane()
        scrolled = ScrolledPanel(pane, size=(500, 250),
                style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)

        text = wx.StaticText(scrolled, label=exc_msg)
        copy_clipboard = wx.Button(pane, label='Copy to clipboard')
        self.Bind(wx.EVT_BUTTON, self.OnCopyClipboard, copy_clipboard)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(text, 1, wx.EXPAND)
        scrolled.SetSizer(sizer)

        scrolled.SetAutoLayout(True)
        scrolled.SetupScrolling()

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(copy_clipboard, 0, wx.ALIGN_RIGHT|wx.RIGHT, 15)
        sizer.Add(scrolled, 1, wx.EXPAND|wx.ALL, 15)
        pane.SetSizer(sizer)

        sizer = wx.BoxSizer(wx.VERTICAL)

        static = wx.StaticText(self, 
                label="fr0st has encountered an error and must exit.")
        static.Wrap(500)
        sizer.Add(static, 0, wx.EXPAND|wx.ALL, 5)

        static = wx.StaticText(self, label="%s: %s" % (
                    exc_type.__name__, str(exc_value)), style=wx.BORDER_SUNKEN)

        static.Wrap(500)
        sizer.Add(static, 0, wx.EXPAND|wx.ALL, 5)
        static = wx.StaticText(self, 
                label="If this problem persists, please consider posting "
                      "the error report to the mailing list.")
        static.Wrap(500)
        sizer.Add(static, 0, wx.EXPAND|wx.ALL, 5)

        sizer.Add(self.collapsible, 0, wx.EXPAND|wx.ALL, 5)

        quit_button = wx.Button(self, label='Exit fr0st', id=wx.ID_EXIT)
        self.Bind(wx.EVT_BUTTON, self.OnExitFr0st, quit_button)

        ok_button = wx.Button(self, label='OK', id=wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, self.OnOK, ok_button)

        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        button_sizer.Add(ok_button, 0, wx.ALL, 5)
        button_sizer.Add(quit_button, 0, wx.ALL, 5)

        #buttons = self.CreateButtonSizer(wx.OK)
        #buttons = self.CreateSeparatedButtonSizer(wx.OK)
        sizer.Add(button_sizer, 0, wx.ALIGN_RIGHT)

        self.SetSizerAndFit(sizer)