def checkbox(element, instance: wx.CheckBox): props = element['props'] set_basic_props(instance, props) instance.Unbind(wx.EVT_CHECKBOX) if props.get('on_change'): instance.Bind(wx.EVT_CHECKBOX, props['on_change']) return instance
def __createSimpleGridOptions(self) -> BoxSizer: szrSimple: BoxSizer = BoxSizer(VERTICAL) cbEnableBackgroundGrid: CheckBox = CheckBox( self, self.enableBackgroundGridID, _('Enable Background Grid')) cbSnapToGrid: CheckBox = CheckBox(self, self.snapToGridID, _('Snap to Grid')) box: StaticBox = StaticBox(self, ID_ANY, _("Grid Interval")) szrGridInterval: StaticBoxSizer = StaticBoxSizer( box, HORIZONTAL | ALIGN_LEFT) scGridInterval: SpinCtrl = SpinCtrl(self, self.scGridIntervalID, "") szrGridInterval.Add(scGridInterval, 0, LEFT | RIGHT, BackgroundPreferences.HORIZONTAL_GAP) szrSimple.Add(cbEnableBackgroundGrid, 0, LEFT | RIGHT, BackgroundPreferences.VERTICAL_GAP) szrSimple.Add(cbSnapToGrid, 0, LEFT | BOTTOM, BackgroundPreferences.VERTICAL_GAP) szrSimple.AddSpacer(BackgroundPreferences.VERTICAL_GAP) szrSimple.Add(szrGridInterval, 0, LEFT | RIGHT | TOP, BackgroundPreferences.VERTICAL_GAP) self._cbEnableBackgroundGrid: CheckBox = cbEnableBackgroundGrid self._cbSnapToGrid: CheckBox = cbSnapToGrid self._scGridInterval: SpinCtrl = scGridInterval return szrSimple
def _createControls(self): """ Creates the panel's controls and stashes them as private instance variables """ self._textId = wxNewIdRef() self._cacheOptionControl = CheckBox(parent=self, label="Allow Todoist Cache Cleanup", id=ID_ANY) self._tasksInParentOption = CheckBox(parent=self, label="Single Todoist Project", id=ID_ANY) self._parentProjectNameContainer = TextContainer(parent=self, labelText='Todoist Project Name:', valueChangedCallback=self.__onParentProjectNameChange)
def toggle(control: wx.CheckBox) -> bool: """ Toggle value of the given control. Usually used for checkboxes. :param control: """ if control.IsEnabled(): control.SetValue(not control.GetValue()) return True return False
def construct(self): 'Construct GUI components.' self.header = StaticText(self, -1, _('Update Frequency:')) self.header.SetBold() self.desc = AutoHeightStaticText(self, -1, UPDATE_DESC_TEXT) self.desc.MinSize = wx.Size(40, -1) self.update_texts = {} # "Tweets every" self.choices = {} # "0 - 10 minutes" # Build StaticText, Choice for each update option. for i, (name, guistring) in enumerate(UPDATE_TYPES): self.update_texts[name] = StaticText(self, -1, guistring) self.choices[name] = Choice(self, choices=UPDATE_GUI_STRINGS) self.total = StaticText(self, style=ALIGN_CENTER) self.total.SetBold() self.auto_throttle = CheckBox( self, label=_('Auto-throttle when Twitter lowers the rate limit.'), name='auto_throttle') if self.show_server_options: self.server_text = StaticText(self, -1, _('Server')) self.server = wx.TextCtrl(self, -1)
def _createControls(self): """ Creates the main control and stashes them as private instance variables """ self.__cbCenterAppOnStartup: CheckBox = CheckBox( self, self.__centerAppOnStartupId, _('Center Pyut on Startup')) mainSizer: BoxSizer = BoxSizer(VERTICAL) mainSizer.Add(self.__cbCenterAppOnStartup, 0, ALL, PositioningPreferences.VERTICAL_GAP) mainSizer.Add(self.__createAppPositionControls(), 0, ALL, PositioningPreferences.VERTICAL_GAP) mainSizer.Add(self.__createAppSizeControls(), 0, ALL, PositioningPreferences.VERTICAL_GAP) self._setControlValues() self.Bind(EVT_CHECKBOX, self.__onCenterOnStartupChanged, id=self.__centerAppOnStartupId) self.SetAutoLayout(True) self.SetSizer(mainSizer)
def __createTextStyleContainer(self, parent: Window) -> BoxSizer: styleContainer: BoxSizer = BoxSizer(HORIZONTAL) self._cbBoldText = CheckBox(parent=parent, id=self._cbBoldTextId, label=_('Bold Text')) self._cbItalicizeText = CheckBox(parent=parent, id=self._cbItalicizeTextId, label=_('Italicize Text')) styleContainer.Add(self._cbBoldText, 0, ALL, TextAttributesContainer.HORIZONTAL_GAP) styleContainer.Add(self._cbItalicizeText, 0, ALL, TextAttributesContainer.HORIZONTAL_GAP) return styleContainer
def __createBooleanControls(self): """ Creates the main control and stashes them as private instance variables """ self.__cbMaximize: CheckBox = CheckBox(self, self.__maximizeID, _("&Full Screen on startup")) self.__cbAutoResize: CheckBox = CheckBox( self, self.__autoResizeID, _("&Auto resize classes to fit content")) self.__cbShowParams: CheckBox = CheckBox(self, self.__showParamsID, _("&Show params in classes")) self.__cbShowTips: CheckBox = CheckBox(self, self.__showTipsID, _("Show &Tips on startup")) self.__cbCenterDiagram: CheckBox = CheckBox(self, self.__centerDiagramID, _('Center Diagram')) self.__btnResetTips: Button = Button(self, self.__resetTipsID, _('Reset Tips'))
def _createControls(self): """ Creates the main control and stashes them as private instance variables """ self.__cbMaximize: CheckBox = CheckBox(self, self.__maximizeID, _('&Full Screen on startup')) self.__cbAutoResize: CheckBox = CheckBox(self, self.__autoResizeID, _('&Auto resize classes to fit content')) self.__cbShowParams: CheckBox = CheckBox(self, self.__showParamsID, _("&Show method parameters")) self.__cbShowTips: CheckBox = CheckBox(self, self.__showTipsID, _("Show &Tips on startup")) self.__cbCenterDiagram: CheckBox = CheckBox(self, self.__centerDiagramID, _('&Center Diagram View')) self.__cbToolBarIconSize: CheckBox = CheckBox(self, self.__toolBarIconSizeID, _('&Large Toolbar Icons')) self.__btnResetTips: Button = Button(self, self.__resetTipsID, _('Reset Tips')) mainSizer: BoxSizer = BoxSizer(VERTICAL) mainSizer.Add(self.__cbAutoResize, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) mainSizer.Add(self.__cbShowParams, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) mainSizer.Add(self.__cbMaximize, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) mainSizer.Add(self.__cbCenterDiagram, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) mainSizer.Add(self.__cbShowTips, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) mainSizer.Add(self.__cbToolBarIconSize, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) mainSizer.Add(self.__btnResetTips, 0, ALL, GeneralPreferencesPanel.VERTICAL_GAP) self.SetAutoLayout(True) self.SetSizer(mainSizer) self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__autoResizeID) self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__showParamsID) self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__maximizeID) self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__showTipsID) self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__toolBarIconSizeID) self.Bind(EVT_BUTTON, self.__OnBtnResetTips, id=self.__resetTipsID)
def _makeACheckBox(self, valueToSet: bool, rowNumber: int, columnName: str, columnIdx: int): nameInfo: str = self.__embedInformationInName(columnName=columnName, rowNumber=rowNumber, columnNumber=columnIdx) retCB: CheckBox = CheckBox(self, ID_ANY, "", DefaultPosition, DefaultSize, 0, name=nameInfo) retCB.SetValue(valueToSet) retCB.Bind(EVT_CHECKBOX, self._onListItemChecked) self.SetItemWindow(rowNumber, columnIdx, retCB, expand=True)
def field_from_value(self, window, value, field): item = None if isinstance(value, six.string_types): item = TextCtrl(window, value=value) field.text_type = STRING_SETTING elif isinstance(value, list): if isinstance(value[0], six.string_types): item = TextCtrl(window, value=", ".join(value)) field.text_type = STRING_LIST_SETTING elif isinstance(value[0], numbers.Real): item = TextCtrl(window, value=", ".join((str(x) for x in value))) field.text_type = NUMBER_LIST_SETTING elif isinstance(value, bool): item = CheckBox(window, -1, '', (120, 75)) item.SetValue(value) elif isinstance(value, numbers.Real): item = TextCtrl(window, value=str(value)) field.text_type = NUMBER_SETTING elif isinstance(value, dict): subpage = Panel(window) vbox = BoxSizer(VERTICAL) for lbl in sorted(value.keys()): hbox = BoxSizer(HORIZONTAL) value2 = value[lbl] label = StaticText(subpage, label=lbl) hbox.Add(label, flag=RIGHT, border=8) subfield = Field(None, lbl) item = self.field_from_value(subpage, value2, subfield) field.add_child(subfield) if item is not None: hbox.Add(item, proportion=1) vbox.Add(hbox, flag=EXPAND | LEFT | RIGHT | TOP, border=5) vbox.Add((-1, 5)) subpage.SetSizer(vbox) subpage.Show() item = subpage else: # This is left for bug reporting purposes. printer.out(("{} from the field {} was not assigned to " + "{} because type {} wasn't properly handled.").format( value, field, window, type(value))) field.widget = item return item
def field_from_value(self, window, value, field): item = None if isinstance(value, basestring): item = TextCtrl(window, value=value) field.text_type = STRING_SETTING elif isinstance(value, list): if isinstance(value[0], basestring): item = TextCtrl(window, value=", ".join(value)) field.text_type = STRINGLIST_SETTING elif isinstance(value[0], int): item = TextCtrl(window, value=", ".join((str(x) for x in value))) field.text_type = INTEGERLIST_SETTING elif isinstance(value, bool): item = CheckBox(window, -1, '', (120, 75)) item.SetValue(value) elif isinstance(value, int): item = TextCtrl(window, value=str(value)) field.text_type = INTEGER_SETTING elif isinstance(value, dict): subpage = Panel(window) vbox = BoxSizer(VERTICAL) alpha = value.keys() alpha.sort() for lbl in alpha: hbox = BoxSizer(HORIZONTAL) value2 = value[lbl] label = StaticText(subpage, label=lbl) hbox.Add(label, flag=RIGHT, border=8) subfield = Field(None, lbl) item = self.field_from_value(subpage, value2, subfield) field.add_child(subfield) if item is not None: hbox.Add(item, proportion=1) vbox.Add(hbox, flag=EXPAND | LEFT | RIGHT | TOP, border=5) vbox.Add((-1, 5)) subpage.SetSizer(vbox) subpage.Show() item = subpage field.wx_field = item return item
def _buildLowerDialog(self) -> BoxSizer: nextTipButton: Button = Button(self, ID_SET_NEXT_TIP, _("&Next tip")) previousTipButton: Button = Button(self, ID_SET_PREVIOUS_TIP, _("&Previous tip")) loSizer: BoxSizer = BoxSizer(HORIZONTAL) loSizer.Add(previousTipButton, WX_SIZER_NOT_CHANGEABLE, ALL | ALIGN_CENTER, 5) loSizer.Add(nextTipButton, WX_SIZER_NOT_CHANGEABLE, ALL | ALIGN_CENTER, 5) loSizer.Add(Button(self, ID_OK, "&Ok"), 0, ALL | ALIGN_CENTER, 5) self._chkShowTips: CheckBox = CheckBox(self, ID_CHK_SHOW_TIPS, _("&Show tips at startup")) showTips: bool = self._prefs.showTipsOnStartup self._chkShowTips.SetValue(showTips) return loSizer
def construct_entry_control(self, entry): """Creates the primary entry control""" if 'boolean' == entry.var_type: control = CheckBox( self.scrolled_panel, name=entry.key_name ) control.SetValue(entry.current) elif 'number' == entry.var_type: control = SpinCtrl( self.scrolled_panel, name=entry.key_name, ) control.SetValue(entry.current) else: control = TextCtrl( self.scrolled_panel, value=str(entry.current), name=entry.key_name, size=(-1, -1) ) self.grid_sizer.Add(control, -1, EXPAND)
class TodoistConfigurationPanel(AbstractConfigurationPanel): def __init__(self, parent: Notebook): self._cacheOptionControl: CheckBox = cast(CheckBox, None) self._tasksInParentOption: CheckBox = cast(CheckBox, None) self._parentProjectNameContainer: TextContainer = cast(TextContainer, None) super().__init__(parent) self.SetSizerType('vertical') self._textId: int = cast(int, None) self.Bind(EVT_CHECKBOX, self.__onCacheOption, self._cacheOptionControl) self.Bind(EVT_CHECKBOX, self.__onTasksInParentProject, self._tasksInParentOption) def _createControls(self): """ Creates the panel's controls and stashes them as private instance variables """ self._textId = wxNewIdRef() self._cacheOptionControl = CheckBox(parent=self, label="Allow Todoist Cache Cleanup", id=ID_ANY) self._tasksInParentOption = CheckBox(parent=self, label="Single Todoist Project", id=ID_ANY) self._parentProjectNameContainer = TextContainer(parent=self, labelText='Todoist Project Name:', valueChangedCallback=self.__onParentProjectNameChange) def _setControlValues(self): """ Set the current configuration values on the controls. """ chkBoxValue: bool = self._preferences.singleTodoistProject self._tasksInParentOption.SetValue(chkBoxValue) self._parentProjectNameContainer.textValue = self._preferences.todoistProjectName if chkBoxValue is False: self._parentProjectNameContainer.textControlEnabled(False) if self._preferences.cleanTodoistCache is True: self._cacheOptionControl.SetValue(True) else: self._cacheOptionControl.SetValue(False) def __onParentProjectNameChange(self, newValue: str): self._preferences.todoistProjectName = newValue def __onTasksInParentProject(self, event: CommandEvent): if event.IsChecked() is True: self._preferences.singleTodoistProject = True self._parentProjectNameContainer.textControlEnabled(True) else: self._preferences.singleTodoistProject = False self._parentProjectNameContainer.textControlEnabled(False) def __onCacheOption(self, event: CommandEvent): if event.IsChecked() is True: self._preferences.cleanTodoistCache = True else: self._preferences.cleanTodoistCache = False
def __init__(self, *args, **kwargs): Panel.__init__(self, *args, **kwargs) sizer = GridBagSizer(5, 5) row = 0 col = 0 self.cb_html_output = CheckBox(self, label=u'Report in HTML') self.cb_html_output.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_html_output, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_html_report = TextCtrl(self, style=TE_READONLY) self.txt_html_report.Disable() sizer.Add(self.txt_html_report, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_select_html = Button(self, label=u'Select HTML file') self.btn_select_html.Disable() self.btn_select_html.Bind(EVT_BUTTON, self.__on_select_file) sizer.Add(self.btn_select_html, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.cb_xml_output = CheckBox(self, label=u'Report in XML') self.cb_xml_output.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_xml_output, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_xml_report = TextCtrl(self, style=TE_READONLY) self.txt_xml_report.Disable() sizer.Add(self.txt_xml_report, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_select_xml = Button(self, label=u'Select XML file') self.btn_select_xml.Disable() self.btn_select_xml.Bind(EVT_BUTTON, self.__on_select_file) sizer.Add(self.btn_select_xml, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.cb_options = CheckBox(self, label=u'Additional options') self.cb_options.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_options, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_options = TextCtrl(self) self.txt_options.Disable() sizer.Add(self.txt_options, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_nose_help = Button(self, label=u'Show help') self.btn_nose_help.Bind(EVT_BUTTON, self.__on_show_help) sizer.Add(self.btn_nose_help, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.btn_load_tests_from_files = Button(self, label=u'Load tests from files') self.btn_load_tests_from_files.Bind(EVT_BUTTON, self.__load_tests_from_files) sizer.Add(self.btn_load_tests_from_files, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.btn_load_tests_from_dir = Button( self, label=u'Load tests from directory') self.btn_load_tests_from_dir.Bind(EVT_BUTTON, self.__load_tests_from_directory) sizer.Add(self.btn_load_tests_from_dir, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 dummy_label = StaticText(self) sizer.Add(dummy_label, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.cb_browser = Choice(self, choices=Browser.get_supported_browsers()) self.cb_browser.Select(0) sizer.Add(self.cb_browser, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.btn_run = Button(self, label=u'Run test cases') self.btn_run.Bind(EVT_BUTTON, self.__run_tests) sizer.Add(self.btn_run, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 window = SplitterWindow(self, style=SP_3D | SP_LIVE_UPDATE) self.tree_ctrl = CustomTreeCtrl( window, style=TR_SINGLE | TR_HAS_BUTTONS | TR_AUTO_CHECK_CHILD | TR_AUTO_CHECK_PARENT | TR_AUTO_TOGGLE_CHILD) self.tree_ctrl.SetBackgroundColour(self.GetBackgroundColour()) self.tree_ctrl.SetForegroundColour(self.GetForegroundColour()) self.tree_ctrl.Bind(EVT_TREE_ITEM_CHECKED, self.__on_tree_check) self.txt_ctrl = TextCtrl(window, style=TE_MULTILINE | TE_READONLY | HSCROLL | VSCROLL) font_size = self.txt_ctrl.GetFont().GetPointSize() self.txt_ctrl.SetFont( Font(font_size, FONTFAMILY_TELETYPE, NORMAL, NORMAL)) window.SplitVertically(self.tree_ctrl, self.txt_ctrl) sizer.Add(window, pos=(row, col), span=(1, 5), flag=FLAG_ALL_AND_EXPAND) sizer.AddGrowableCol(2, 1) sizer.AddGrowableRow(row, 1) self.SetSizerAndFit(sizer)
class TestRunnerTab(Panel): def __init__(self, *args, **kwargs): Panel.__init__(self, *args, **kwargs) sizer = GridBagSizer(5, 5) row = 0 col = 0 self.cb_html_output = CheckBox(self, label=u'Report in HTML') self.cb_html_output.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_html_output, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_html_report = TextCtrl(self, style=TE_READONLY) self.txt_html_report.Disable() sizer.Add(self.txt_html_report, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_select_html = Button(self, label=u'Select HTML file') self.btn_select_html.Disable() self.btn_select_html.Bind(EVT_BUTTON, self.__on_select_file) sizer.Add(self.btn_select_html, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.cb_xml_output = CheckBox(self, label=u'Report in XML') self.cb_xml_output.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_xml_output, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_xml_report = TextCtrl(self, style=TE_READONLY) self.txt_xml_report.Disable() sizer.Add(self.txt_xml_report, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_select_xml = Button(self, label=u'Select XML file') self.btn_select_xml.Disable() self.btn_select_xml.Bind(EVT_BUTTON, self.__on_select_file) sizer.Add(self.btn_select_xml, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.cb_options = CheckBox(self, label=u'Additional options') self.cb_options.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_options, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_options = TextCtrl(self) self.txt_options.Disable() sizer.Add(self.txt_options, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_nose_help = Button(self, label=u'Show help') self.btn_nose_help.Bind(EVT_BUTTON, self.__on_show_help) sizer.Add(self.btn_nose_help, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.btn_load_tests_from_files = Button(self, label=u'Load tests from files') self.btn_load_tests_from_files.Bind(EVT_BUTTON, self.__load_tests_from_files) sizer.Add(self.btn_load_tests_from_files, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.btn_load_tests_from_dir = Button( self, label=u'Load tests from directory') self.btn_load_tests_from_dir.Bind(EVT_BUTTON, self.__load_tests_from_directory) sizer.Add(self.btn_load_tests_from_dir, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 dummy_label = StaticText(self) sizer.Add(dummy_label, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.cb_browser = Choice(self, choices=Browser.get_supported_browsers()) self.cb_browser.Select(0) sizer.Add(self.cb_browser, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.btn_run = Button(self, label=u'Run test cases') self.btn_run.Bind(EVT_BUTTON, self.__run_tests) sizer.Add(self.btn_run, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 window = SplitterWindow(self, style=SP_3D | SP_LIVE_UPDATE) self.tree_ctrl = CustomTreeCtrl( window, style=TR_SINGLE | TR_HAS_BUTTONS | TR_AUTO_CHECK_CHILD | TR_AUTO_CHECK_PARENT | TR_AUTO_TOGGLE_CHILD) self.tree_ctrl.SetBackgroundColour(self.GetBackgroundColour()) self.tree_ctrl.SetForegroundColour(self.GetForegroundColour()) self.tree_ctrl.Bind(EVT_TREE_ITEM_CHECKED, self.__on_tree_check) self.txt_ctrl = TextCtrl(window, style=TE_MULTILINE | TE_READONLY | HSCROLL | VSCROLL) font_size = self.txt_ctrl.GetFont().GetPointSize() self.txt_ctrl.SetFont( Font(font_size, FONTFAMILY_TELETYPE, NORMAL, NORMAL)) window.SplitVertically(self.tree_ctrl, self.txt_ctrl) sizer.Add(window, pos=(row, col), span=(1, 5), flag=FLAG_ALL_AND_EXPAND) sizer.AddGrowableCol(2, 1) sizer.AddGrowableRow(row, 1) self.SetSizerAndFit(sizer) def __on_show_help(self, evt): text = check_output(['nosetests', '--help']) DialogWithText(self, u'Help for nosetests', text).ShowModal() def __on_select_file(self, evt): folder = self.__get_safe_path_from_root_folder(RootFolder.REPORTS) obj = evt.GetEventObject() txt_ctrl = None if obj == self.btn_select_html: wildcard = u'*.html' txt_ctrl = self.txt_html_report elif obj == self.btn_select_xml: wildcard = u'*.xml' txt_ctrl = self.txt_xml_report else: wildcard = u'*.*' dialog = FileDialog(self, defaultDir=folder, style=FD_SAVE | FD_OVERWRITE_PROMPT, wildcard=wildcard) if dialog.ShowModal() == ID_OK and txt_ctrl: txt_ctrl.SetValue(dialog.GetPath()) def __on_check(self, evt): cb_obj = evt.GetEventObject() checkboxes_and_txt_ctrls = { self.cb_html_output: self.txt_html_report, self.cb_options: self.txt_options, self.cb_xml_output: self.txt_xml_report } checkboxes_and_btns = { self.cb_html_output: self.btn_select_html, self.cb_xml_output: self.btn_select_xml } txt_ctrl = checkboxes_and_txt_ctrls[cb_obj] btn = checkboxes_and_btns.get(cb_obj) if txt_ctrl.IsEnabled(): txt_ctrl.Disable() if btn: btn.Disable() else: txt_ctrl.Enable() if btn: btn.Enable() def __on_tree_check(self, evt): # styles doesn't work: TR_AUTO_CHECK_CHILD | TR_AUTO_CHECK_PARENT | TR_AUTO_TOGGLE_CHILD # TODO: fix if all children are check then one child is uncheck - parent is checked item = evt.GetItem() checked = item.IsChecked() parent = item.GetParent() def all_children_are_checked(_parent): states = [child.IsChecked() for child in _parent.GetChildren()] uniq_states = list(set(states)) return len(uniq_states) == 1 and uniq_states[0] is True self.tree_ctrl.AutoCheckChild(item, checked) if parent: self.tree_ctrl.AutoCheckParent(item, all_children_are_checked(parent)) def __get_safe_path_from_root_folder(self, subfolder=None): folder = self.GetTopLevelParent().get_root_folder() if subfolder and folder: path_for_subfolder = os.path.join(folder, subfolder) if os.path.exists(path_for_subfolder): return path_for_subfolder return folder if folder else '.' def __load_tests_to_tree(self, file_paths=None, dir_path=None): if file_paths: python_files = file_paths elif dir_path: python_files = [f for f in get_list_of_files(dir_path, True)] else: python_files = [] python_files = [ f for f in python_files if 'test' in os.path.basename(f) and os.path.splitext(f)[-1] == '.py' ] if len(python_files) > 0: syspath = list(os.sys.path) try: root_folder = self.__get_safe_path_from_root_folder() if root_folder not in os.sys.path: os.sys.path.append(root_folder) checkbox_type = 1 self.tree_ctrl.DeleteAllItems() root = self.tree_ctrl.AddRoot('All test cases', checkbox_type) for python_file in python_files: top_item = self.tree_ctrl.AppendItem( root, os.path.abspath(python_file), checkbox_type) parsed_classes = ParsedClass.get_parsed_classes( python_file) for parsed_class in parsed_classes: item = self.tree_ctrl.AppendItem( top_item, parsed_class.name, checkbox_type) test_methods = [ k for k in parsed_class.methods.keys() if k.startswith('test_') ] for tc_name in test_methods: self.tree_ctrl.AppendItem(item, tc_name, checkbox_type) self.tree_ctrl.ExpandAll() except Exception: show_error_dialog(self, traceback.format_exc(), 'Cannot add test cases') finally: os.sys.path = syspath def __load_tests_from_directory(self, evt): folder = self.__get_safe_path_from_root_folder(RootFolder.TESTS_FOLDER) if folder: dialog = DirDialog(self, defaultPath=folder, style=DD_DIR_MUST_EXIST) if dialog.ShowModal() == ID_OK: self.__load_tests_to_tree(dir_path=dialog.GetPath()) else: show_dialog_path_doesnt_exist(self, folder) def __load_tests_from_files(self, evt): folder = self.__get_safe_path_from_root_folder(RootFolder.TESTS_FOLDER) if folder: dialog = FileDialog(self, defaultDir=folder, style=FD_OPEN | FD_FILE_MUST_EXIST | FD_MULTIPLE, wildcard=u'*.py') if dialog.ShowModal() == ID_OK: self.__load_tests_to_tree(file_paths=dialog.GetPaths()) else: show_dialog_path_doesnt_exist(self, folder) def __get_nose_command(self): root = self.tree_ctrl.GetRootItem() tests = [] for _file in root.GetChildren(): for _class in _file.GetChildren(): for test_case in _class.GetChildren(): if test_case.IsChecked(): # TODO: fix for files that contain spaces tests.append(u'%s:%s.%s' % (_file.GetText(), _class.GetText(), test_case.GetText())) args = [ '--with-path="%s"' % self.__get_safe_path_from_root_folder(), '--logging-level=INFO' ] use_html_report = (self.cb_html_output.IsChecked() and len(self.txt_html_report.GetValue()) > 0) if use_html_report: report_path = self.txt_html_report.GetValue() args.append('--with-html --html-file="%s"' % report_path) use_xml_report = (self.cb_xml_output.IsChecked() and len(self.txt_xml_report.GetValue()) > 0) if use_xml_report: report_path = self.txt_xml_report.GetValue() args.append('--with-xunit --xunit-file="%s"' % report_path) use_options = (self.cb_options.IsChecked() and len(self.txt_options.GetValue()) > 0) if use_options: report_path = self.txt_options.GetValue() args.append(report_path) nose_cmd = [u'nosetests'] + args + tests return nose_cmd def __run_tests(self, evt): # TODO: do not run if root folder is not selected self.txt_ctrl.Clear() dialog = InfiniteProgressBarDialog( self, u'Running test cases', u'Running selected test cases... Please wait...') def wrap_func(): stdout = os.sys.stdout stderr = os.sys.stderr redirected = RedirectText(self.txt_ctrl) os.sys.stdout = redirected os.sys.stderr = redirected try: nose_cmd = self.__get_nose_command() browser_name = self.cb_browser.GetStringSelection() Browser.DEFAULT_BROWSER = browser_name report_folder = self.__get_safe_path_from_root_folder( RootFolder.REPORTS) BaseTest.FAILED_SCREENSHOT_FOLDER = report_folder easy_selenium_cmd = u" ".join(nose_cmd).replace( "nosetests", "easy_selenium_cli.py -b " + browser_name) print(u"Executing command:\n%s" % easy_selenium_cmd) print(u"Nose output:") run(argv=nose_cmd[1:]) finally: dialog.close_event.set() os.sys.stdout = stdout os.sys.stderr = stderr run_in_separate_thread(wrap_func) dialog.ShowModal()
def __init__(self, master, saveDirVal = None, backupDirVal = None): self.master = master saveDirSizer = BoxSizer(HORIZONTAL) self.saveDir = TextCtrl(master, size = (600, -1) ) if saveDirVal: self.saveDir.SetValue(saveDirVal) saveDirSizer.Add(StaticText(master, label = "Save directory"), 0, EXPAND ) saveDirSizer.Add(self.saveDir, 1, EXPAND) selectSaveDir = Button(master, -1, "Select") saveDirSizer.Add(selectSaveDir, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_select_save_dir, selectSaveDir) openSave = Button(master, label = "Open") saveDirSizer.Add(openSave, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_open_save_dir, openSave) hide = Button(master, label = "Hide") saveDirSizer.Add(hide, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_hide, hide) backupDirSizer = BoxSizer(HORIZONTAL) self.backupDir = TextCtrl(master) if backupDirVal: self.backupDir.SetValue(backupDirVal) backupDirSizer.Add(StaticText(master, label = "Backup directory"), 0, EXPAND ) backupDirSizer.Add(self.backupDir, 1, EXPAND) switch = Button(master, label = "Switch") master.Bind(EVT_BUTTON, self._on_switch, switch) backupDirSizer.Add(switch, 0, EXPAND) override = Button(master, label = "Overwrite") master.Bind(EVT_BUTTON, self._on_overwrite, override) backupDirSizer.Add(override, 0, EXPAND) selectBackupDir = Button(master, -1, "Select") master.Bind(EVT_BUTTON, self._on_select_backup_dir, selectBackupDir) backupDirSizer.Add(selectBackupDir, 0, EXPAND) openBackup = Button(master, label = "Open") backupDirSizer.Add(openBackup, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_open_backup_dir, openBackup) filterOutSizer = BoxSizer(HORIZONTAL) filterOutSizer.Add(StaticText(master, label = "Filter Out"), 0, EXPAND) self.filterOut = TextCtrl(master) filterOutSizer.Add(self.filterOut, 1, EXPAND) self.cbMonitor = CheckBox(master, label = "Monitor") master.Bind(EVT_CHECKBOX, self._on_monitor, self.cbMonitor) self.sizer = sizer = BoxSizer(VERTICAL) sizer.Add(saveDirSizer, 0, EXPAND) sizer.Add(backupDirSizer, 0, EXPAND) sizer.Add(filterOutSizer, 0, EXPAND) sizer.Add(self.cbMonitor, 0, EXPAND) self.settingsWidgets = [ selectSaveDir, self.saveDir, self.backupDir, switch, selectBackupDir, self.filterOut ]
def __init__(self, parent, windowId, pyutClass: PyutClass): """ Args: parent: dialog parent windowId: dialog identity pyutClass: Class modified by dialog """ super().__init__(parent=parent, windowId=windowId, dlgTitle=_("Class Edit"), pyutModel=pyutClass) self.logger: Logger = getLogger(__name__) lblStereotype: StaticText = StaticText(self, -1, _("Stereotype")) self._txtStereotype: TextCtrl = TextCtrl(self, ID_TXT_STEREO_TYPE, "", size=(125, -1)) self._szrNameStereotype.Add(lblStereotype, 0, ALL, 5) self._szrNameStereotype.Add(self._txtStereotype, 1, ALIGN_CENTER) # Label Fields lblField = StaticText(self, -1, _("Fields :")) # ListBox List self._lstFieldList = ListBox(self, ID_LST_FIELD_LIST, choices=[], style=LB_SINGLE) self.Bind(EVT_LISTBOX, self._evtFieldList, id=ID_LST_FIELD_LIST) self.Bind(EVT_LISTBOX_DCLICK, self._evtFieldListDClick, id=ID_LST_FIELD_LIST) # Button Add self._btnFieldAdd = Button(self, ID_BTN_FIELD_ADD, _("&Add")) self.Bind(EVT_BUTTON, self._onFieldAdd, id=ID_BTN_FIELD_ADD) # Button Edit self._btnFieldEdit = Button(self, ID_BTN_FIELD_EDIT, _("&Edit")) self.Bind(EVT_BUTTON, self._onFieldEdit, id=ID_BTN_FIELD_EDIT) # Button Remove self._btnFieldRemove = Button(self, ID_BTN_FIELD_REMOVE, _("&Remove")) self.Bind(EVT_BUTTON, self._onFieldRemove, id=ID_BTN_FIELD_REMOVE) # Button Up self._btnFieldUp = Button(self, ID_BTN_FIELD_UP, _("&Up")) self.Bind(EVT_BUTTON, self._onFieldUp, id=ID_BTN_FIELD_UP) # Button Down self._btnFieldDown = Button(self, ID_BTN_FIELD_DOWN, _("&Down")) self.Bind(EVT_BUTTON, self._onFieldDown, id=ID_BTN_FIELD_DOWN) # Sizer for Fields buttons szrFieldButtons = BoxSizer(HORIZONTAL) szrFieldButtons.Add(self._btnFieldAdd, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldEdit, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldRemove, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldUp, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldDown, 0, ALL, 5) szrMethodButtons: BoxSizer = self._createMethodsUIArtifacts() # Show stereotype checkbox self._chkShowStereotype = CheckBox(self, -1, _("Show stereotype")) # Show fields checkbox self._chkShowFields = CheckBox(self, -1, _("Show fields")) # Show methods checkbox self._chkShowMethods = CheckBox(self, -1, _("Show methods")) # Sizer for display properties szrDisplayProperties = BoxSizer(VERTICAL) szrDisplayProperties.Add(self._chkShowStereotype, 0, ALL, 5) szrDisplayProperties.Add(self._chkShowFields, 0, ALL, 5) szrDisplayProperties.Add(self._chkShowMethods, 0, ALL, 5) self._szrMain.Add(lblField, 0, ALL, 5) self._szrMain.Add(self._lstFieldList, 1, ALL | EXPAND, 5) self._szrMain.Add(szrFieldButtons, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add(self._lblMethod, 0, ALL, 5) self._szrMain.Add(self._lstMethodList, 1, ALL | EXPAND, 5) self._szrMain.Add(szrMethodButtons, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add(szrDisplayProperties, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add( self._szrButtons, 0, ALL | ALIGN_RIGHT, 5 ) # wxPython 4.1.0 Vertical alignment flags are ignored in vertical sizers # Fill the txt control with class data self._fillAllControls() # Fix buttons (enable or not) self._fixBtnFields() self._fixBtnMethod() # Set the focus and selection self._txtName.SetFocus() self._txtName.SetSelection(0, len(self._txtName.GetValue())) # Help Pycharm self._dlgMethod = cast(Dialog, None) self._szrMain.Fit(self) # subclasses need to do this self.Centre() self.ShowModal()
def __init__(self, parent): """ """ # Check import sys if sys.platform == "win32": return # Initialize the dialog box super().__init__( parent, -1, _("Tips"), DefaultPosition, Size(DEFAULT_WIDTH, DEFAULT_HEIGHT), RESIZE_BORDER | SYSTEM_MENU | CAPTION | FRAME_FLOAT_ON_PARENT | STAY_ON_TOP) # Normalize tips from org.pyut.general.LineSplitter import LineSplitter ls = LineSplitter() dc = ClientDC(self) for i in range(len(Tips)): tip = ls.split(Tips[i], dc, int(DEFAULT_WIDTH * 0.8)) Tips[i] = "" for line in tip: Tips[i] += line + "\n" # tip = "" # for line in Tips[i].split("\n"): # newLine = "" # for word in line.split(" "): # if len(newLine) + len(word) > 59: # tip += newLine + "\n" # newLine = "" # newLine += word + " " # tip += newLine # Tips[i] = tip # Set current tips self._prefs = PyutPreferences() self._currentTip = self._prefs[PyutPreferences.CURRENT_TIP] if self._currentTip is None: self._currentTip = 0 else: self._currentTip = int(self._currentTip) # Add icon # fileName = resource_filename(IMG_PKG, 'TipsLogo.bmp') # icon = Icon(fileName, BITMAP_TYPE_BMP) # self.SetIcon(icon) # self.Center(BOTH) # Center on the screen self.Center(dir=VERTICAL) self.AcceptsFocus() # Create controls # bmp: Bitmap = org.pyut.resources.img.ImgTipsFrameTipsLogo.embeddedImage.GetBitmap() bmp: Bitmap = TipsLogo.GetBitmap() self._picture = StaticBitmap(self, -1, bmp) tip = Tips[self._currentTip] self._label = StaticText(self, -1, tip, size=Size(DEFAULT_WIDTH * 0.8, DEFAULT_HEIGHT * 0.8), style=ST_NO_AUTORESIZE) nextTipButton = Button(self, ID_SET_NEXT_TIP, _("&Next tip")) previousTipButton = Button(self, ID_SET_PREVIOUS_TIP, _("&Previous tip")) self._chkShowTips = CheckBox(self, ID_CHK_SHOW_TIPS, _("&Show tips at startup")) showTips: bool = self._prefs.showTipsOnStartup() self._chkShowTips.SetValue(showTips) # Upper sizer upSizer = BoxSizer(HORIZONTAL) upSizer.Add(self._picture, 0, ALL | ALIGN_CENTER, 5) upSizer.Add(self._label, 1, ALL | ALIGN_CENTER, 5) # Lower sizer loSizer = BoxSizer(HORIZONTAL) loSizer.Add(previousTipButton, 0, ALL | ALIGN_CENTER, 5) loSizer.Add(nextTipButton, 0, ALL | ALIGN_CENTER, 5) loSizer.Add(Button(self, ID_OK, "&Ok"), 0, ALL | ALIGN_CENTER, 5) # Main sizer self.SetAutoLayout(True) mainSizer = BoxSizer(VERTICAL) mainSizer.Add(upSizer, 0, ALL | ALIGN_CENTER, 5) mainSizer.Add(self._chkShowTips, 0, ALL | ALIGN_CENTER, 5) mainSizer.Add(loSizer, 0, ALL | ALIGN_CENTER, 5) self.SetSizer(mainSizer) mainSizer.Fit(self) # Events self.Bind(EVT_BUTTON, self._onOk, id=ID_OK) self.Bind(EVT_CLOSE, self._onClose) self.Bind(EVT_BUTTON, self._onNextTip, id=ID_SET_NEXT_TIP) self.Bind(EVT_BUTTON, self._onPreviousTip, id=ID_SET_PREVIOUS_TIP)
class SaveSettings(object): def __init__(self, master, saveDirVal = None, backupDirVal = None): self.master = master saveDirSizer = BoxSizer(HORIZONTAL) self.saveDir = TextCtrl(master, size = (600, -1) ) if saveDirVal: self.saveDir.SetValue(saveDirVal) saveDirSizer.Add(StaticText(master, label = "Save directory"), 0, EXPAND ) saveDirSizer.Add(self.saveDir, 1, EXPAND) selectSaveDir = Button(master, -1, "Select") saveDirSizer.Add(selectSaveDir, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_select_save_dir, selectSaveDir) openSave = Button(master, label = "Open") saveDirSizer.Add(openSave, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_open_save_dir, openSave) hide = Button(master, label = "Hide") saveDirSizer.Add(hide, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_hide, hide) backupDirSizer = BoxSizer(HORIZONTAL) self.backupDir = TextCtrl(master) if backupDirVal: self.backupDir.SetValue(backupDirVal) backupDirSizer.Add(StaticText(master, label = "Backup directory"), 0, EXPAND ) backupDirSizer.Add(self.backupDir, 1, EXPAND) switch = Button(master, label = "Switch") master.Bind(EVT_BUTTON, self._on_switch, switch) backupDirSizer.Add(switch, 0, EXPAND) override = Button(master, label = "Overwrite") master.Bind(EVT_BUTTON, self._on_overwrite, override) backupDirSizer.Add(override, 0, EXPAND) selectBackupDir = Button(master, -1, "Select") master.Bind(EVT_BUTTON, self._on_select_backup_dir, selectBackupDir) backupDirSizer.Add(selectBackupDir, 0, EXPAND) openBackup = Button(master, label = "Open") backupDirSizer.Add(openBackup, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_open_backup_dir, openBackup) filterOutSizer = BoxSizer(HORIZONTAL) filterOutSizer.Add(StaticText(master, label = "Filter Out"), 0, EXPAND) self.filterOut = TextCtrl(master) filterOutSizer.Add(self.filterOut, 1, EXPAND) self.cbMonitor = CheckBox(master, label = "Monitor") master.Bind(EVT_CHECKBOX, self._on_monitor, self.cbMonitor) self.sizer = sizer = BoxSizer(VERTICAL) sizer.Add(saveDirSizer, 0, EXPAND) sizer.Add(backupDirSizer, 0, EXPAND) sizer.Add(filterOutSizer, 0, EXPAND) sizer.Add(self.cbMonitor, 0, EXPAND) self.settingsWidgets = [ selectSaveDir, self.saveDir, self.backupDir, switch, selectBackupDir, self.filterOut ] def _on_overwrite(self, _): self.ask_and_overwrite() def ask_and_overwrite(self): backupDir = self.backupDir.GetValue() savePath = self.saveDir.GetValue() if not (isdir(backupDir) and bool(savePath)): with MessageDialog(self.master, "Set paths up!", "Error") as dlg: dlg.ShowModal() return False repo = Repo(backupDir) if repo.is_dirty(): with MessageDialog(self.master, "Backup repository '%s' is dirty" % backupDir, "Error") as dlg: dlg.ShowModal() return False active_branch = repo.active_branch try: c = active_branch.commit except Exception as e: hint = "" try: if active_branch.name == "master": hint = "Is backup empty?" except: pass with MessageDialog(self.master, str(e) + "\n" + hint, "Error") as dlg: dlg.ShowModal() return False label = commit_time_str(c) + " | " + c.message dlg = MessageDialog(self.master, "Do you want to overwrite save data with current version?\n\n" + "SHA1: %s\n\n%s\n\n" % (c.hexsha, label) + "Files in save directory will be overwritten!", "Confirmation is required", YES_NO ) switch = dlg.ShowModal() == ID_YES dlg.Destroy() if not switch: return False self._switch_to(c) return True def _on_switch(self, _): backupDir = self.backupDir.GetValue() if not isdir(backupDir): return with BackupSelector(self.master, backupDir) as dlg: res = dlg.ShowModal() if res != ID_OK: return target = dlg.target try: self._switch_to(target) except BaseException as e: with MessageDialog(self.master, str(e), "Error") as dlg: dlg.ShowModal() def _switch_to(self, target): repo = Repo(self.backupDir.GetValue()) if repo.is_dirty(): raise RuntimeError("Backup repository is dirty") active = repo.active_branch cur = active.commit if cur.hexsha != target.hexsha: # select name for backup branch backups = [] need_head = True for h in repo.heads: mi = backup_re.match(h.name) if mi: backups.append(int(mi.group(1), base = 10)) if h.commit.hexsha == cur.hexsha: need_head = False if backups: n = max(backups) + 1 else: n = 0 # TODO: do not set branch if commits are reachable (other # branch exists) # setup backup branch and checkout new version if need_head: back_head = repo.create_head("backup_%u" % n, cur) try: active.commit = target try: active.checkout(True) except: active.commit = cur raise except: if need_head: repo.delete_head(back_head) raise save_path = self.saveDir.GetValue() # remove files of current stack = [cur.tree] while stack: node = stack.pop() for b in node.blobs: b_path = join(save_path, b.path) if exists(b_path): remove(b_path) stack.extend(node.trees) # copy files from target stack = [target.tree] while stack: node = stack.pop() for b in node.blobs: b_path = join(save_path, b.path) makedirs(dirname(b_path), exist_ok = True) with open(b_path, "wb+") as f: b.stream_data(f) stack.extend(node.trees) def _open_dir(self, path): if exists(path): open_directory_in_explorer(path) def _on_open_save_dir(self, _): self._open_dir(self.saveDir.GetValue()) def _on_open_backup_dir(self, _): self._open_dir(self.backupDir.GetValue()) def _on_select_save_dir(self, _): if not hasattr(self, "dlgSaveDir"): self.dlgSaveDir = DirDialog(self.master, "Choose directory of save data", "", DD_DEFAULT_STYLE | DD_DIR_MUST_EXIST ) cur = self.saveDir.GetValue() if cur: self.dlgSaveDir.SetPath(cur) if self.dlgSaveDir.ShowModal() == ID_OK: self.saveDir.SetValue(self.dlgSaveDir.GetPath()) def _on_select_backup_dir(self, _): if not hasattr(self, "dlgBackupDir"): self.dlgBackupDir = DirDialog(self.master, "Choose directory for backup", "", DD_DEFAULT_STYLE | DD_DIR_MUST_EXIST ) cur = self.backupDir.GetValue() if cur: self.dlgBackupDir.SetPath(cur) if self.dlgBackupDir.ShowModal() == ID_OK: self.backupDir.SetValue(self.dlgBackupDir.GetPath()) def _enable_settings(self): for w in self.settingsWidgets: w.Enable(True) def _disable_settings(self): for w in self.settingsWidgets: w.Enable(False) def _on_monitor(self, _): root = self.saveDir.GetValue() backup = self.backupDir.GetValue() root2threads = self.master.root2threads # See: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html if self.cbMonitor.IsChecked(): self._disable_settings() if not root: dlg = MessageDialog(self.master, "Pleas select save directory", "Error" ) dlg.ShowModal() dlg.Destroy() self.cbMonitor.SetValue(False) self._enable_settings() return if not exists(root): dlg = MessageDialog(self.master, "No such directory '%s'" % root, "Error" ) dlg.ShowModal() dlg.Destroy() self.cbMonitor.SetValue(False) self._enable_settings() return if not backup: dlg = MessageDialog(self.master, "Pleas select backup directory", "Error" ) dlg.ShowModal() dlg.Destroy() self.cbMonitor.SetValue(False) self._enable_settings() return if root in root2threads: return # already monitored if not exists(backup): dlg = MessageDialog(self.master, "Directory '%s' does not exist. Create?" % backup, "Create backup directory", YES_NO ) res = dlg.ShowModal() dlg.Destroy() if not res: self.cbMonitor.SetValue(False) self._enable_settings() return makedirs(backup) filterOutRe = None filterOut = self.filterOut.GetValue() if filterOut: try: filterOutRe = compile(filterOut) except: if filterOut: dlg = MessageDialog(self.master, "Incorrect filter expression" " (use Python's re syntax)\n" + format_exc() + "\nContinue without filter?", "Filter Out Error", YES_NO ) res = dlg.ShowModal() dlg.Destroy() if res == ID_NO: self.cbMonitor.SetValue(False) self._enable_settings() return mt = MonitorThread(root, lambda : root2threads.pop(root)) bt = BackUpThread(root, backup, mt.changes, filterOutRe) root2threads[root] = (mt, bt) mt.start() bt.start() else: self._enable_settings() if root in root2threads: for t in root2threads[root]: t.exit_request = True def _on_hide(self, __): self.master._hide_save_settings(self) @property def saveData(self): return ( self.saveDir.GetValue(), self.backupDir.GetValue(), self.filterOut.GetValue(), )
class DlgEditClass(DlgEditClassCommon): """ Dialog for the class edits. Creating a DlgEditClass object will automatically open a dialog for class editing. The PyutClass given in the constructor parameters will be used to fill the fields of the dialog, and will be updated when the OK button is clicked. Dialogs for methods and fields editing are implemented in different classes and created when invoking the _callDlgEditMethod and _callDlgEditField methods. Because dialog works on a copy of the PyutClass object, if you cancel the dialog any modifications are lost. Examples of `DlgEditClass` use are in `Mediator.py` """ def __init__(self, parent, windowId, pyutClass: PyutClass): """ Args: parent: dialog parent windowId: dialog identity pyutClass: Class modified by dialog """ super().__init__(parent=parent, windowId=windowId, dlgTitle=_("Class Edit"), pyutModel=pyutClass) self.logger: Logger = getLogger(__name__) lblStereotype: StaticText = StaticText(self, -1, _("Stereotype")) self._txtStereotype: TextCtrl = TextCtrl(self, ID_TXT_STEREO_TYPE, "", size=(125, -1)) self._szrNameStereotype.Add(lblStereotype, 0, ALL, 5) self._szrNameStereotype.Add(self._txtStereotype, 1, ALIGN_CENTER) # Label Fields lblField = StaticText(self, -1, _("Fields :")) # ListBox List self._lstFieldList = ListBox(self, ID_LST_FIELD_LIST, choices=[], style=LB_SINGLE) self.Bind(EVT_LISTBOX, self._evtFieldList, id=ID_LST_FIELD_LIST) self.Bind(EVT_LISTBOX_DCLICK, self._evtFieldListDClick, id=ID_LST_FIELD_LIST) # Button Add self._btnFieldAdd = Button(self, ID_BTN_FIELD_ADD, _("&Add")) self.Bind(EVT_BUTTON, self._onFieldAdd, id=ID_BTN_FIELD_ADD) # Button Edit self._btnFieldEdit = Button(self, ID_BTN_FIELD_EDIT, _("&Edit")) self.Bind(EVT_BUTTON, self._onFieldEdit, id=ID_BTN_FIELD_EDIT) # Button Remove self._btnFieldRemove = Button(self, ID_BTN_FIELD_REMOVE, _("&Remove")) self.Bind(EVT_BUTTON, self._onFieldRemove, id=ID_BTN_FIELD_REMOVE) # Button Up self._btnFieldUp = Button(self, ID_BTN_FIELD_UP, _("&Up")) self.Bind(EVT_BUTTON, self._onFieldUp, id=ID_BTN_FIELD_UP) # Button Down self._btnFieldDown = Button(self, ID_BTN_FIELD_DOWN, _("&Down")) self.Bind(EVT_BUTTON, self._onFieldDown, id=ID_BTN_FIELD_DOWN) # Sizer for Fields buttons szrFieldButtons = BoxSizer(HORIZONTAL) szrFieldButtons.Add(self._btnFieldAdd, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldEdit, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldRemove, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldUp, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldDown, 0, ALL, 5) szrMethodButtons: BoxSizer = self._createMethodsUIArtifacts() # Show stereotype checkbox self._chkShowStereotype = CheckBox(self, -1, _("Show stereotype")) # Show fields checkbox self._chkShowFields = CheckBox(self, -1, _("Show fields")) # Show methods checkbox self._chkShowMethods = CheckBox(self, -1, _("Show methods")) # Sizer for display properties szrDisplayProperties = BoxSizer(VERTICAL) szrDisplayProperties.Add(self._chkShowStereotype, 0, ALL, 5) szrDisplayProperties.Add(self._chkShowFields, 0, ALL, 5) szrDisplayProperties.Add(self._chkShowMethods, 0, ALL, 5) self._szrMain.Add(lblField, 0, ALL, 5) self._szrMain.Add(self._lstFieldList, 1, ALL | EXPAND, 5) self._szrMain.Add(szrFieldButtons, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add(self._lblMethod, 0, ALL, 5) self._szrMain.Add(self._lstMethodList, 1, ALL | EXPAND, 5) self._szrMain.Add(szrMethodButtons, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add(szrDisplayProperties, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add( self._szrButtons, 0, ALL | ALIGN_RIGHT, 5 ) # wxPython 4.1.0 Vertical alignment flags are ignored in vertical sizers # Fill the txt control with class data self._fillAllControls() # Fix buttons (enable or not) self._fixBtnFields() self._fixBtnMethod() # Set the focus and selection self._txtName.SetFocus() self._txtName.SetSelection(0, len(self._txtName.GetValue())) # Help Pycharm self._dlgMethod = cast(Dialog, None) self._szrMain.Fit(self) # subclasses need to do this self.Centre() self.ShowModal() def _callDlgEditField(self, field: PyutField) -> int: """ Dialog for Field editing Args: field: Field to be edited Returns: return code from dialog """ self._dlgField = DlgEditField(theParent=self, theWindowId=ID_ANY, fieldToEdit=field, theMediator=self._mediator) return self._dlgField.ShowModal() def _dupParams(self, params): """ Duplicate a list of params, all params are duplicated too. @since 1.9 @author N. Dubois <*****@*****.**> """ dupParams = [] for i in params: param: PyutParam = PyutParam(name=i.getName(), theParameterType=i.getType(), defaultValue=i.getDefaultValue()) dupParams.append(param) return dupParams def _fillAllControls(self): """ Fill all controls with _pyutModelCopy data. """ # Fill Class name self._txtName.SetValue(self._pyutModelCopy.getName()) # Fill Stereotype stereotype = self._pyutModelCopy.getStereotype() if stereotype is None: strStereotype = "" else: strStereotype = stereotype.getName() self._txtStereotype.SetValue(strStereotype) # Fill the list controls try: for el in self._pyutModelCopy.fields: self.logger.debug(f'field: {el}') self._lstFieldList.Append(str(el)) self._fillMethodList() except (ValueError, Exception) as e: eMsg: str = _(f"Error: {e}") dlg = MessageDialog(self, eMsg, OK | ICON_ERROR) dlg.ShowModal() dlg.Destroy() # Fill display properties self._chkShowFields.SetValue(self._pyutModelCopy.showFields) self._chkShowMethods.SetValue(self._pyutModelCopy.showMethods) self._chkShowStereotype.SetValue( self._pyutModelCopy.getShowStereotype()) def _fixBtnFields(self): """ Fix buttons of fields list (enable or not). """ selection = self._lstFieldList.GetSelection() # Button Edit and Remove ans = selection != -1 self._btnFieldEdit.Enable(ans) self._btnFieldRemove.Enable(ans) self._btnFieldUp.Enable(selection > 0) self._btnFieldDown.Enable( ans and selection < self._lstFieldList.GetCount() - 1) # noinspection PyUnusedLocal def _onFieldAdd(self, event: CommandEvent): """ Add a new field in the list. Args: event: """ field = PyutField() ret = self._callDlgEditField(field) if ret == OK: self._pyutModelCopy.fields.append(field) # Add fields in dialog list self._lstFieldList.Append(str(field)) # Tell window that its data has been modified fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() # noinspection PyUnusedLocal def _onFieldEdit(self, event: CommandEvent): """ Edit a field. """ selection = self._lstFieldList.GetSelection() field = self._pyutModelCopy.fields[selection] ret = self._callDlgEditField(field) if ret == OK: # Modify field in dialog list self._lstFieldList.SetString(selection, str(field)) # Tell window that its data has been modified fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() # noinspection PyUnusedLocal def _onFieldRemove(self, event: CommandEvent): """ Remove a field from the list. """ # Remove from list control selection = self._lstFieldList.GetSelection() self._lstFieldList.Delete(selection) # Select next if self._lstFieldList.GetCount() > 0: index = min(selection, self._lstFieldList.GetCount() - 1) self._lstFieldList.SetSelection(index) # Remove from _pyutModelCopy fields = self._pyutModelCopy.fields fields.pop(selection) # Fix buttons of fields list (enable or not) self._fixBtnFields() # Tell window that its data has been modified fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() # noinspection PyUnusedLocal def _onFieldUp(self, event: CommandEvent): """ Move up a field in the list. """ # Move up the field in _pyutModelCopy selection = self._lstFieldList.GetSelection() fields = self._pyutModelCopy.fields field = fields[selection] fields.pop(selection) fields.insert(selection - 1, field) # Move up the field in dialog list self._lstFieldList.SetString(selection, str(fields[selection])) self._lstFieldList.SetString(selection - 1, str(fields[selection - 1])) self._lstFieldList.SetSelection(selection - 1) # Fix buttons (enable or not) self._fixBtnFields() # Tell window that its data has been modified fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() # noinspection PyUnusedLocal def _onFieldDown(self, event: CommandEvent): """ Move down a field in the list. """ selection = self._lstFieldList.GetSelection() fields = self._pyutModelCopy.fields field = fields[selection] fields.pop(selection) fields.insert(selection + 1, field) # Move down the field in dialog list self._lstFieldList.SetString(selection, str(fields[selection])) self._lstFieldList.SetString(selection + 1, str(fields[selection + 1])) self._lstFieldList.SetSelection(selection + 1) # Fix buttons (enable or not) self._fixBtnFields() # Tell window that its data has been modified fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() # noinspection PyUnusedLocal def _evtFieldList(self, event): """ Called when click on Fields list. """ self._fixBtnFields() def _evtFieldListDClick(self, event: CommandEvent): """ Called when there is a double-click on Fields list. """ self._onFieldEdit(event) def _convertNone(self, theString): """ Return the same string, if string = None, return an empty string. Args: theString: The string Returns: The input string or 'None' if it was empty """ if theString is None: theString = "" return theString # noinspection PyUnusedLocal def _onOk(self, event: CommandEvent): """ Activated when button OK is clicked. """ strStereotype = self._txtStereotype.GetValue() if strStereotype == "": self._pyutModel.setStereotype(None) else: self._pyutModel.setStereotype(getPyutStereotype(strStereotype)) # Adds all fields in a list self._pyutModel.fields = self._pyutModelCopy.fields # Update display properties self._pyutModel.showFields = self._chkShowFields.GetValue() self._pyutModel.showMethods = self._chkShowMethods.GetValue() self._pyutModel.setShowStereotype(self._chkShowStereotype.GetValue()) from org.pyut.PyutPreferences import PyutPreferences prefs = PyutPreferences() try: if prefs["AUTO_RESIZE"]: oglClass = self._mediator.getOglClass(self._pyutModel) oglClass.autoResize() except (ValueError, Exception) as e: self.logger.warning(f'{e}') fileHandling = self._mediator.getFileHandling() project = fileHandling.getCurrentProject() if project is not None: project.setModified() super()._onOk(event)