def __init__(self, setting_file_path: str): """Default constructor :param setting_file_path: Path to a file to read the settings :type setting_file_path: str """ super().__init__() self.__app = App() self.__id = NewIdRef() self.__io_mgr = IOManager(setting_file_path, self) self.__public_mgr_dict = DotNotationDict() self.__temp_setting = {} CommunicableObjectBase._core_mgr = self window_size = self.Get(WINDOW_SIZE) self.__main_window = MainWindow(self, parent=None, size=window_size) self.__public_mgr_dict = self.__CreatePublicManager() self.__temp_setting[MANAGER_LIST] = lambda: list(self.__public_mgr_dict .values()) SpectrumFunctionContainerBase.data_accessor = SpectrumFunctionContainerAccessor( self.Get(DATA_MANAGER), self.Get(PEAK_MANAGER)) self.__InitializePublicManagers() self.__RestoreStorableObjSetting() self.InitialTitle()
def __init__(self, name): self.path = self.basepath self.name = name self.logger = init_logger(self.logfile) wxApp.__init__(self, redirect=False, filename=self.logfile) self.AppName = name self.AppDisplayName = name self.icon = wx.Icon(self.get_resource('Icon.ico'))
def main(): """Main entry point.""" parser = ArgumentParser() parser.add_argument('url', nargs='?', help='The URL to load.') args = parser.parse_args() a = App() f = MainFrame() f.Show(True) f.Maximize() if args.url is not None: f.address.SetValue(args.url) f.on_enter(None) a.MainLoop()
def main(): server_address = (Communicator.LOCALHOST, Communicator().com_registry["hmc"]) # Enabled by default logging causes RPC to malfunction when the GUI runs on # pythonw. Explicitly disable logging for the XML server. server = SimpleXMLRPCServer(server_address, logRequests=False, allow_none=True) app = App(False) SettingsFrame( None, settings.SETTINGS_WINDOW_TITLE + settings.SOFTWARE_VERSION_NUMBER, server) app.MainLoop()
def main(): m = None app = App() try: m = Mqn("mqn") app.MainLoop() except Exception as e: #print("""Unhandled exception:\n{}""".format(str(e))) #raise wx.MessageDialog(parent=None, caption="Error!", message="""{}: {}""".format(type(e).__name__, e)).ShowModal() return finally: # gracefully disconnect, even if an exception is thrown if m != None and getattr(m, 'client', False) and m.mqtt_connected==True: # if there is an mqn object, if it has an mqtt client, and it indicates that it is still connected to a broker m.mqtt_disconnect()
def gui(self) -> None: logging.debug("BeerProgramming.gui(self)") app = App() frame = front.Frame(name="Beer Programming") panel = frame.new_panel(bgcolor=(50, 50, 50)) player_panel = panel.new_panel("(%0.49,%1)") chat_panel = panel.new_panel("(%0.49,%1)", "(%0.51,0)") self.text_list = { self.name: panel.add_text((0, 0), "(%1,%0.2)", self.name) } app.MainLoop()
def setUpClass(cls): TestBase.setUpLogging() TestCreateOglInterfaceCommand.clsLogger = getLogger(__name__) PyutPreferences.determinePreferencesLocation() TestCreateOglInterfaceCommand.clsApp = App()
def setUp(self): """ Initialize. @author C.Dutoit """ # Initialize mediator and error manager ctrl = Mediator.getMediator() ctrl.setScriptMode() fileHandling = MainUI(None, ctrl) ctrl.registerFileHandling(fileHandling) errorManager = ctrl.getErrorManager() errorManager.changeType(ErrorViewTypes.RAISE_ERROR_VIEW) whereWeAre: str = getcwd() PyutUtils.setBasePath(whereWeAre) # Create wx application # For python 3 and wx 4.x we need to save it so it does not get GC'ed self.app = App() # Create frame # baseFrame = wxFrame(None, -1, "", size=(10, 10)) baseFrame = Frame(None, -1, "", size=(10, 10)) umlFrame = UmlFrame(baseFrame, None) umlFrame.Show(True) self._umlFrame = umlFrame
def setUpClass(cls): TestBase.setUpLogging() TestDeleteOglLinkedObjectCommand.clsLogger = getLogger(__name__) PyutPreferences.determinePreferencesLocation() TestDeleteOglLinkedObjectCommand.clsApp = App()
def reverb_main() -> None: """Provide the main entry point.""" with initialized(): a: App = App() ctx: Context = Context() f: ReverbFrame = ReverbFrame(ctx) f.Show(show=True) f.Maximize(maximize=True) a.MainLoop()
def start(WD=None, inp_file=None, delay_time=1, vocal=False, data_model=3): global cit_magic if int(float(data_model)) == 3: cit_magic = cit_magic else: cit_magic = cit_magic2 app = App() # start the GUI # overriding vocal argument `not vocal` for testing purposes dg = Demag_GUIAU(WD, write_to_log_file=True, inp_file=inp_file, delay_time=delay_time, data_model=float(data_model)) app.frame = dg app.frame.Center() app.frame.Show() app.MainLoop()
def getFilePath(wildcard, title): app = App(None) style = FD_OPEN | FD_FILE_MUST_EXIST dialog = FileDialog(None, title, wildcard=wildcard, style=style) if dialog.ShowModal() == ID_OK: path = dialog.GetPath() else: path = None dialog.Destroy() return path
def OnExit(self): """ """ self.__do = None self._frame = None self.splash = None # Seemed to be removed in latest versions of wxPython ??? try: return wxApp.OnExit(self) except (ValueError, Exception) as e: self.logger.error(f'OnExit: {e}')
def get_path(): app = App(None) style = FD_SAVE dialog = DirDialog(None, "Save to...", "", DD_DEFAULT_STYLE | DD_DIR_MUST_EXIST) if dialog.ShowModal() == ID_OK: path = dialog.GetPath() else: path = "" print("No directory selected, saving to current directory.") dialog.Destroy() return path
def main(): app = App() with Settings() as s: mon = SaveMonitor( logging = s.logging, logFile = s.logFile, ) for i, save in enumerate(s.saves): mon.add_settings(*save, hidden = i in s.hidden, ) mon.Show(True) app.MainLoop() s.saves[:] = mon.saveData s.hidden = mon.hidden s.logging = mon.logging s.logFile = mon.logFile
def main(default=True): app = App() screen = ScreenDC() size = screen.GetSize() if default: size = (round(size[0] * 2.5), round(size[1] * 2.5)) bmp = Bitmap(size[0], size[1]) mem = MemoryDC(bmp) mem.Blit(0, 0, size[0], size[1], screen, 0, 0) del mem name = '{}.png'.format(str(randrange(1000))) fname = os.path.join(os.getcwd(), name) bmp.SaveFile(fname, BITMAP_TYPE_PNG) return fname
def __init__(self, app: App): super(Frame, self).__init__(None) self.editor = TextCtrl(self, 101, style=TE_MULTILINE) self.stat: StatusBar = self.CreateStatusBar() self.stat.SetFieldsCount(2) self.stat.SetStatusWidths([-1, -5]) self.SetTitle(f"{BASETITLE} - *Untitled*") self.SetSize(720, 540) self.File: str = None self.changed = False menubar: MenuBar = MenuBar() edit_menu: Menu = Menu() file_menu: Menu = Menu() edit_menu.Append(1, "&Preview\tCtrl+P") edit_menu.Append(2, "Post") edit_menu.AppendSeparator() edit_menu.Append(7, "&Ruby\tCtrl+R") edit_menu.Append(9, "&Dotmarks\tCtrl+Shift+D") edit_menu.Append(8, "&Paragraph\tCtrl+Space") file_menu.Append(3, "&New\tCtrl+N") file_menu.Append(4, "&Open\tCtrl+Shift+O") file_menu.AppendSeparator() file_menu.Append(5, "&Save as\tCtrl+Shift+S") file_menu.Append(6, "&Save\tCtrl+S") menubar.Append(file_menu, "&File") menubar.Append(edit_menu, "&Edit") self.SetMenuBar(menubar) self.Bind(EVT_MENU, self.Preview, id=1) self.Bind(EVT_MENU, self.Post, id=2) self.Bind(EVT_MENU, self.New, id=3) self.Bind(EVT_MENU, self.Open, id=4) self.Bind(EVT_MENU, self.SaveAs, id=5) self.Bind(EVT_MENU, self.Save, id=6) self.Bind(EVT_MENU, self.SetRuby, id=7) self.Bind(EVT_MENU, self.SetParagraphSpaces, id=8) self.Bind(EVT_MENU, self.Dotmarks, id=9) self.pvframe = HideFrame(None, -1, "プレビュー") self.pvctrl: WebView = WebView.New(self.pvframe) self.pvctrl.SetCanFocus(False) self.pvframe.SetCanFocus(False) self.Bind(EVT_TEXT, self.Reload, id=101) app.SetTopWindow(self) self.application = app self.Show()
def testGetScreenMetrics(self): from wx import App # noinspection PyUnusedLocal app = App() screenMetrics: ScreenMetrics = PyutUtils.getScreenMetrics() self.assertIsNotNone(screenMetrics, 'I must get something back') self.assertIsNot(0, screenMetrics.dpiX, 'I need a number') self.assertIsNot(0, screenMetrics.dpiY, 'I need a number') self.assertIsNot(0, screenMetrics.screenWidth, 'I need a screen width') self.assertIsNot(0, screenMetrics.screenHeight, 'I need a screen height') del app self.logger.info(f'{screenMetrics=}')
from wx import App, STAY_ON_TOP from app.OwlFrame import OwlFrame if __name__ == '__main__': app = App() frm = OwlFrame() frm.Show() app.MainLoop()
def __init__(self, filename = None): print "[+] Run hachoir-wx version %s" % VERSION self.filename = filename App.__init__(self, False)
class CoreManager(Singleton): """Core manager supervising managers. """ def __init__(self, setting_file_path: str): """Default constructor :param setting_file_path: Path to a file to read the settings :type setting_file_path: str """ super().__init__() self.__app = App() self.__id = NewIdRef() self.__io_mgr = IOManager(setting_file_path, self) self.__public_mgr_dict = DotNotationDict() self.__temp_setting = {} CommunicableObjectBase._core_mgr = self window_size = self.Get(WINDOW_SIZE) self.__main_window = MainWindow(self, parent=None, size=window_size) self.__public_mgr_dict = self.__CreatePublicManager() self.__temp_setting[MANAGER_LIST] = lambda: list(self.__public_mgr_dict .values()) SpectrumFunctionContainerBase.data_accessor = SpectrumFunctionContainerAccessor( self.Get(DATA_MANAGER), self.Get(PEAK_MANAGER)) self.__InitializePublicManagers() self.__RestoreStorableObjSetting() self.InitialTitle() def Launch(self, menubar_design: dict = None, setting_file_path: str = SETTING_FILE_PATH): """Launch iSATex. :param menubar_design: Menu bar design. Please refer to "MenubarManager.GetMenubarDesign"\'s documentation for details. Defaults to None :type menubar_design: dict, optional :param setting_file_path: Path to a file to read the settings, defaults to SETTING_FILE_PATH :type setting_file_path: str, optional """ logger.info('launch app.') menubar_design = self.Get(MENUBAR_MANAGER).GetMenubarDesign( ) if menubar_design is None else menubar_design menubar = self.Get(MENUBAR_MANAGER).CreateMenubar(menubar_design) self.__main_window.SetMenuBar(menubar) self.__main_window.Show() event = LaunchEvent(id=self.__id) self.SendEvent(event) try: self.__app.MainLoop() except Exception as e: LogError( 'The application did not terminate successfully.\nPlease check the log file.' ) logger.error(e) logger.info('end app.') def Get(self, key: str, default: Any = None, *args): """Get a reference to the manager. :type key: str :param default: Return value when the specified key is not found, defaults to None :type default: Any, optional :rtype: Any """ if key in self.__temp_setting: func = self.__temp_setting[key] return func() if len(args) == 0 else func(args) if key in self.__public_mgr_dict: return self.__public_mgr_dict[key] return self.__io_mgr.GetSetting(key, default) def SendEvent(self, event): """ This function sends an event to an instance of the "PanelBase" class and to the manager. Note that the event will not be sent until the project is started. :param event: Event object to be sent. :type event: Any type """ self.Get(EVENT_MANAGER).SendEvent(event) def InitialTitle(self): """Initializes the title of the main window. """ self.__main_window.SetTitle(APPLICATION_NAME) def GetTitle(self) -> str: """Get the title of the current main window. :rtype: str """ full_title = self.GetFullTitle() start = full_title.find('-') end = full_title.rfind('-') return full_title[start + 1:end] def GetFullTitle(self) -> str: """Get the title of the main window that is being displayed. :rtype: str """ return self.__main_window.GetTitle() def SetTitle(self, title: str): """Sets the title of the main window. :type title: str """ is_saved = self.Get(PROJECT_MANAGER).IsProjectSaved() title = f'{APPLICATION_NAME} -{title}- ' title += '' if is_saved else '(unsaved)' self.__main_window.SetTitle(title) def __CreatePublicManager(self): design = ( (MENUBAR_MANAGER, MenubarManager), (PANEL_MANAGER, PanelManager), (EVENT_MANAGER, EventManager), (FUNCTION_MANAGER, FunctionManager), (ENCODE_MANAGER, EncodeManager), (DECODE_MANAGER, DecodeManager), (MAPPING_MANAGER, MappingManager), (PROJECT_MANAGER, ProjectManager), (PEAK_MANAGER, PeakManager), (DATA_MANAGER, DataManager), (SPECTRUM_MANAGER, SpectrumManager), (COLOR_MANAGER, ColorManager), (PREFERENCE_MANAGER, PreferenceManager), ) public_mgr_dict = {} for key, mgr in design: public_mgr_dict[key] = mgr(core_manager=self, io_manager=self.__io_mgr) return public_mgr_dict def __InitializePublicManagers(self): """ Initialize the manager. The 'Get' function should not be used for anything other than getting the manager, because of the complexity of the reference. """ # Create the necessary instances for the setting event_list = self.__io_mgr.GetSetting(EVENT_LIST) spectrum_preset_list = self.__io_mgr.GetSetting( SPECTRUM_FUNCTION_PRESET_LIST) function_list = [ FuncClass() for FuncClass in self.__io_mgr.GetSetting(FUNCTION_CLASS_LIST) ] peak_function_list = list( sorted([ PeakFunc() for PeakFunc in self.__io_mgr.GetSetting( PEAK_FUNCTION_CLASS_LIST, []) ], key=lambda x: x.__class__.__name__)) peak_type_list = [PeakType(peak) for peak in peak_function_list] peak_type = self.__io_mgr.GetSetting(PEAK_TYPE) data_buffer_size = self.__io_mgr.GetSetting(DATA_BUFFER_SIZE) selected_encode_func = self.__io_mgr.GetSetting( SELECTED_ENCODE_FUNCTION) selected_decode_func = self.__io_mgr.GetSetting( SELECTED_DECODE_FUNCTION) selected_mapping_func = self.__io_mgr.GetSetting( SELECTED_MAPPING_FUNCTION) encode_encoding = self.__io_mgr.GetSetting(ENCODE_ENCODING) encode_delimiter = self.__io_mgr.GetSetting(ENCODE_DELIMITER) decode_encoding = self.__io_mgr.GetSetting(DECODE_ENCODING) table_size = self.__io_mgr.GetSetting(MAPPING_TABLE_SIZE) direction = self.__io_mgr.GetSetting(MAPPING_DIRECTION) cmap = self.__io_mgr.GetSetting(MAPPING_COLORMAP) layout_list = self.__io_mgr.GetSetting(LAYOUT_LIST) selected_layout = self.__io_mgr.GetSetting(SELECTED_LAYOUT) color_theme_list = self.__io_mgr.GetSetting(COLOR_THEME_LIST) selected_color_theme = self.__io_mgr.GetSetting(SELECTED_COLOR_THEME) event_receptor_list = [] menu_item_list = [] panel_list = [] for EventReceptor in self.__io_mgr.GetSetting( EVENT_RECEPTOR_CLASS_LIST): if issubclass(EventReceptor, CustomMenuItemBase): event_receptor = EventReceptor() menu_item_list.append(event_receptor) elif issubclass(PanelBase, PanelBase): event_receptor = EventReceptor(parent=self.__main_window) panel_list.append(event_receptor) elif issubclass(EventReceptor, PanelBase): continue else: event_receptor = EventReceptor() event_receptor_list.append(event_receptor) self.Get(MENUBAR_MANAGER).RegisterMenuItemList(menu_item_list) self.Get(EVENT_MANAGER).RegisterEventList(event_list) self.Get(PANEL_MANAGER).SetMainWindow(self.__main_window) # PanelClassList = self.__io_mgr.GetSetting(DotChain(PANEL, CLASS_LIST)) # panel_list = self.Get(PANEL_MANAGER).RegisterPanelList(PanelClassList, perspective_setting, self.__main_window) # event_receptor_list.extend(panel_list) self.Get(PANEL_MANAGER).RegisterLayout(layout_list) self.Get(PANEL_MANAGER).RegisterPanelList(panel_list, selected_layout) self.Get(EVENT_MANAGER).RegisterEventReceptorList(event_receptor_list) self.Get(FUNCTION_MANAGER).RegisterFunctionList(function_list) self.Get(FUNCTION_MANAGER).RegisterPreset(spectrum_preset_list) self.Get(FUNCTION_MANAGER).SelectEncodeFunction(selected_encode_func) self.Get(FUNCTION_MANAGER).SelectDecodeFunction(selected_decode_func) self.Get(FUNCTION_MANAGER).SelectMappingFunction(selected_mapping_func) self.Get(PEAK_MANAGER).RegisterPeakTypeList(peak_type_list) self.Get(PEAK_MANAGER).SelectPeakType(peak_type) self.Get(ENCODE_MANAGER).SelectEncoding(encode_encoding) self.Get(ENCODE_MANAGER).SelectDelimiter(encode_delimiter) self.Get(DECODE_MANAGER).SelectEncoding(decode_encoding) self.Get(MAPPING_MANAGER).SelectDirection(direction) self.Get(MAPPING_MANAGER).SetTableSize(table_size) self.Get(MAPPING_MANAGER).SelectColormap(cmap) self.Get(COLOR_MANAGER).RegisterColorThemeList(color_theme_list) self.Get(COLOR_MANAGER).SelectColorTheme(selected_color_theme) self.Get(PREFERENCE_MANAGER).SetDataBufferSize(data_buffer_size) def __RestoreStorableObjSetting(self): for editor in self.__GetEditorList(): if not isinstance(editor, SettingStorableObjectBase): continue setting = {} for key in editor.RequireSetting(): if self.__io_mgr.IsUnknownSetting( key) and key not in self.__temp_setting: register_key = self.__ConvertRegisterKey(key, editor) value = self.Get(register_key) else: value = self.Get(key) setting[key] = value editor.ReceiveSetting(setting) def __StoreStorableObjectSetting(self): for editor in self.__GetEditorList(): if not isinstance(editor, SettingStorableObjectBase): continue for key, value in editor.SendSetting().items(): if not (self.__io_mgr.IsUnknownSetting(key) or self.__io_mgr.IsCustomSetting(key)): continue key = self.__ConvertRegisterKey(key, editor) self.__io_mgr.SetSetting(key, value) def SaveSetting(self): """Save the state of the application. """ event = ExitEvent(self.__id) self.SendEvent(event) self.__StoreStorableObjectSetting() self.__io_mgr.SaveSetting() def __ConvertRegisterKey(self, key, editor: SettingStorableObjectBase): if not isinstance(editor, SettingStorableObjectBase): raise TypeError() return DotChain(editor.__class__.__name__, key) def __DeConvertRegisterKey(self, key, editor: SettingStorableObjectBase): if not isinstance(editor, SettingStorableObjectBase): raise TypeError() return key.lstrip(f'{editor.__class__.__name__}.') def __GetEditorList(self): return [ obj for obj in self.Get(PANEL_MANAGER).GetPanelList() + self.Get(MENUBAR_MANAGER).GetMenuItemList() if isinstance(obj, SettingStorableObjectBase) ] def OnEvent(self, event): event_type = event.GetEventType() if event_type == wxEVT_CLOSE_WINDOW: event.Skip() self.__main_window.Destroy()
def main(): app = App() MainWindow(parent=None, size=(WINDOW_WIDTH, WINDOW_HEIGHT)) app.MainLoop()
#!/usr/bin/env python import os import sys from wx import App # TODO: remove, fix for local import sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from easyselenium.ui.main_ui import MainFrame if __name__ == '__main__': app = App(False) main_ui = MainFrame(None) main_ui.Show() app.MainLoop() # TODO: use relative path in generator # TODO: better naming for generated fields # TODO: find and remove duplicate code # TODO: add wait_for_text_changed # TODO: add wait_for_value_changed # TODO: add wait_for_attribute_changed # TODO: add parent to Browser methods # TODO: changes are not applied when running test - if method is added to pagemodel and is used in test - NoMethod exception will be raised # TODO: if test case updated - doesn't updated in test runner # TODO: generator - when browser is closed - remove # TODO: add support for not uniq selectors # TODO: if selector is not uniq in 'Editor' use status text with notification: 'NOTE: this selector is not uniq' and show all possible object which could be found with this selector # TODO: add enable/disable for uniq selector in 'Selector finder'
import sys import argparse from wx import App from version import __VERSION__ from controlpanel import HondaECU_ControlPanel if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--noredirect', action='store_true', help="don't redirect stdout/stderr to gui") parser.add_argument('-V', '--version', action='store_true', help="show version information") args = parser.parse_args() if args.version: print(__VERSION__) sys.exit(0) app = App(redirect=not args.noredirect, useBestVisual=True) gui = HondaECU_ControlPanel(__VERSION__) app.MainLoop()
def setUpClass(cls): TestBase.setUpLogging() TestLineSplitter.clsLogger = getLogger(__name__) TestLineSplitter.clsApp = App()
def setUpClass(cls): TestBase.setUpLogging() TestIDFactory.clsLogger = getLogger(__name__) PyutPreferences.determinePreferencesLocation() TestIDFactory.clsApp = App()
def __init__(self): App.__init__(self, redirect=False)
def _quitRequest(self, event): exit() return if __name__ == "__main__": # allow exit() through the escape key _ESCAPE = True class App(App): def Start(self): # self.SetMenuBar() return App().MainLoop() # def SetMenuBar(self): # M1 = wx.Menu() # M1.Append( # wx.ID_NEW, # "&New File Name", # "select a new filename", # kind = wx.ITEM_NORMAL) # M1.Append( # wx.ID_SAVE, # "&Save Config File", # "save current configuration to file",
def init_gui(): app = App(False) frame = GUI() frame.Show() app.MainLoop()
def setUpClass(cls): TestBase.setUpLogging() TestAnchorPoint.clsLogger = getLogger(__name__) TestAnchorPoint.clsApp = App()
class MainWindow(MainFrame): app = App() size = DisplaySize() dpiX = 1 dpiY = 1 __currentSelectHost = None __currentEditHost = None def __init__(self): print(os.environ) self.app.locale = Locale(LANGUAGE_CHINESE_SIMPLIFIED) realSize = DisplaySize() self.dpiX = realSize[0] / self.size[0] self.dpiY = realSize[1] / self.size[1] MainFrame.__init__(self, None, dpi=(self.dpiY, self.dpiY)) self.trayIcon = TrayIcon(self) self.aboutDialog = AboutDialog(self, dpi=(self.dpiY, self.dpiY)) self.editDialog = EditDialog(self, dpi=(self.dpiY, self.dpiY)) self.InitMainWindow() self.InitHostsTree(ID_SYSTEM_HOSTS) def InitHostsTree(self, select=None): self.hostsTree.DeleteAllItems() root = self.hostsTree.AddRoot("全部Hosts", image=self.images["logo"]) selectId = self.hostsTree.AppendItem(root, "当前系统", image=self.images[sys.platform], data=systemHosts) for hosts in Settings.settings["hosts"]: itemId = self.hostsTree.AppendItem( root, hosts["name"], data=hosts, image=self.images[hosts["icon"] if hosts["icon"] else "logo"]) self.hostsTree.SetItemBold(itemId, hosts["active"]) if hosts["active"]: self.hostsTree.SetItemTextColour(itemId, Colour(0x12, 0x96, 0xdb)) if hosts["id"] == select: selectId = itemId self.hostsTree.ExpandAll() if selectId: self.hostsTree.SelectItem(selectId) def OnHostsTreeActivated(self, event): itemId = event.GetItem() hosts = self.hostsTree.GetItemData(itemId) if hosts["id"] == ID_SYSTEM_HOSTS or hosts['alwaysApply']: return self.ApplyHosts(hosts["id"]) def InitMainWindow(self): self.Show() self.codeEditor.SetValue(Hosts.GetSystemHosts()) self.codeEditor.SetReadOnly(True) self.Bind(EVT_CLOSE, self.OnWindowClose) self.statusBar.SetFieldsCount(3) self.SetStatusWidths([-1, -2, -1]) self.statusBar.SetStatusText( "当前共%d个Hosts规则" % len(Settings.settings["hosts"]), 0) self.statusBar.SetStatusText("编辑自动保存, 双击应用到系统", 1) self.hostsTree.Bind(EVT_TREE_SEL_CHANGED, self.OnHostsTreeItemSelect) self.hostsTree.Bind(EVT_TREE_ITEM_RIGHT_CLICK, self.ShowTreeItemMenu) self.hostsTree.Bind(EVT_TREE_ITEM_ACTIVATED, self.OnHostsTreeActivated) self.codeEditor.Bind(EVT_STC_CHANGE, self.OnKeyUp) updateTime = Settings.settings["lastCheckUpdateTime"] if updateTime and NowToTimestamp(updateTime) < 0: self.CheckUpdate() def OnKeyUp(self, event): # 如果是只读状态, 则忽略按键事件 if self.codeEditor.GetReadOnly() or not self.__currentEditHost: return self.__currentEditHost["content"] = self.codeEditor.GetValue() # 保存 def ShowTreeItemMenu(self, event): hosts = self.hostsTree.GetItemData(event.GetItem()) if not hosts: return self.__currentSelectHost = hosts menu = Menu() popMenuActive = menu.Append(TrayIcon.ID_TREE_MENU_SET_ACTIVE, "设置为当前Hosts") if hosts["id"] == ID_SYSTEM_HOSTS or hosts['alwaysApply']: popMenuActive.Enable(False) else: popMenuActive.Enable(not hosts["active"]) menu.AppendSeparator() popMenuEdit = menu.Append(TrayIcon.ID_TREE_MENU_EDIT, "编辑") popMenuEdit.Enable(hosts["id"] != ID_SYSTEM_HOSTS) popMenuDelete = menu.Append(TrayIcon.ID_TREE_MENU_DELETE, "删除") popMenuDelete.Enable(hosts["id"] != ID_SYSTEM_HOSTS) # menu.Append(TrayIcon.ID_TREE_MENU_REFRESH, "刷新") self.hostsTree.PopupMenu(menu, event.GetPoint()) self.hostsTree.Bind(EVT_MENU, self.OnMenuClicked) # self.hostsTree.Bind(EVT_MENU, self.OnMenuClicked, popMenuDelete.GetId()) # self.hostsTree.Bind(EVT_MENU, self.OnMenuClicked, popMenuActive.GetId()) # self.hostsTree.Bind(EVT_MENU, self.OnMenuClicked, popMenuEdit.GetId()) # self.hostsTree.Bind(EVT_MENU, self.OnMenuClicked, popMenuRefresh.GetId()) def OnHostsTreeItemSelect(self, event): hosts = self.hostsTree.GetItemData(event.GetItem()) if not hosts: return self.codeEditor.SetReadOnly(False) self.codeEditor.SetValue(Hosts.GetSystemHosts() if hosts["id"] == ID_SYSTEM_HOSTS else hosts["content"]) self.codeEditor.SetReadOnly(hosts["readOnly"]) self.codeEditor.SetHosts(hosts) def ToggleWindow(self): self.Iconize(not self.IsIconized()) self.Show(not self.IsShown()) if self.IsShown(): self.Raise() def OnWindowClose(self, event): self.Iconize(True) self.Hide() return False def ShowAboutDialog(self): self.aboutDialog.Show(True) def OnTaskBarHostsMenuClicked(self, event): self.ApplyHosts(event.GetId()) pass def ApplyHosts(self, hostsId: int): commonHostsLines = "# hosts file apply by mHosts v%s, %s\n " % ( Settings.version(), Now()) currentHostsLines = "" currentHosts = None for hosts in Settings.settings["hosts"]: if hosts["id"] == hostsId: currentHostsLines += "# ---------------- %(name)s ----------------%(br)s%(content)s%(br)s" % { "name": hosts['name'], "br": os.linesep, "content": hosts['content'] } currentHosts = hosts if hosts["alwaysApply"]: commonHostsLines += "# ---------------- %(name)s ----------------%(br)s%(content)s%(br)s" % { "name": hosts['name'], "br": os.linesep, "content": hosts['content'] } hostsToApply = commonHostsLines + os.linesep + currentHostsLines try: if Hosts.Save2System(ParseHosts(hostsToApply)): for hosts in Settings.settings["hosts"]: hosts["active"] = hosts["id"] == hostsId refreshDnsRes = Hosts.TryFlushDNSCache() MessagePanel.Send("Hosts已设置为" + currentHosts["name"] + "\nDNS缓存刷新" + ("成功" if refreshDnsRes else "失败"), "保存成功", dpi=(self.dpiX, self.dpiY)) else: MessageBox("保存失败", "提示", ICON_ERROR) self.InitHostsTree(ID_SYSTEM_HOSTS) Settings.Save() except Exception as e: message = str(e) if "Permission denied" in message: MessageBox("尝试写入hosts时权限不足, 保存失败, 请以管理员身份运行该软件", "权限不足", ICON_ERROR) else: MessageBox(message, "保存时出错", ICON_ERROR) def ShowEditDialog(self, hosts): self.editDialog.Show() self.editDialog.SetHosts(hosts) def OnMenuClicked(self, event: CommandEvent): handlers = { self.menuItemExit.GetId(): self.Exit, self.menuItemAbout.GetId(): self.ShowAboutDialog, self.menuItemHelpDoc.GetId(): lambda: LaunchDefaultBrowser("https://hefang.link/url/mhosts-doc"), self.menuItemNew.GetId(): lambda: self.ShowEditDialog(None), self.menuItemCheckUpdate.GetId(): self.CheckUpdate, TrayIcon.ID_EXIT: self.Exit, TrayIcon.ID_TOGGLE: self.ToggleWindow, TrayIcon.ID_REFRESH_DNS: MainWindow.DoRefreshDNS, TrayIcon.ID_NEW: lambda: self.ShowEditDialog(None), TrayIcon.ID_ABOUT: lambda: self.aboutDialog.Show(), TrayIcon.ID_IMPORT: None, TrayIcon.ID_LUNCH_CHROME: lambda: MainWindow.LunchChrome(), TrayIcon.ID_LUNCH_CHROME_CROS: lambda: MainWindow.LunchChrome( "--disable-web-security --user-data-dir=%(temp)s%(sep)smHostsChromeTempDir%(sep)s%(time)d" % { 'temp': os.environ['TEMP'], 'sep': os.sep, 'time': time.time() }), TrayIcon.ID_LUNCH_CHROME_NO_PLUGINS: lambda: MainWindow.LunchChrome( "--disable-plugins --disable-extensions"), TrayIcon.ID_TREE_MENU_EDIT: lambda: self.ShowEditDialog(self.__currentSelectHost), TrayIcon.ID_TREE_MENU_SET_ACTIVE: lambda: self.ApplyHosts(self.__currentSelectHost["id"]), TrayIcon.ID_TREE_MENU_DELETE: lambda: self.DeleteHosts(self.__currentSelectHost) } if event.GetId() in handlers: callback = handlers[event.GetId()] if callable(callback): callback() else: MessagePanel.Send("该菜单绑定的事件不可用", "菜单点击", dpi=(self.dpiX, self.dpiY)) else: MessagePanel.Send("该菜单没有绑定事件", "菜单点击", dpi=(self.dpiX, self.dpiY)) def CheckUpdate(self): CheckNewVersionThread(self).start() def DeleteHosts(self, hosts: dict): if hosts['active']: MessageBox("无法删除当前应用的hosts", "删除失败", ICON_ERROR) return for index, host in enumerate(Settings.settings["hosts"]): if host["id"] == hosts["id"]: del Settings.settings["hosts"][index] MessagePanel.Send("Hosts'%(name)s'已删除" % hosts, "删除成功", dpi=(self.dpiX, self.dpiY)) break self.InitHostsTree() @staticmethod def LunchChrome(args=""): chromePath = Settings.settings["chromePath"] if os.path.exists(chromePath): if ' ' in chromePath: chromePath = '"%s"' % chromePath cmd = u'%s %s' % (chromePath, args) print("正在启动Chrome, 命令:", cmd) Popen(cmd) else: Settings.settings["chromePath"] = "" MessageBox( "当前配置的Chrome路径'%s'不存在" % chromePath if chromePath else "当前未配置Chrome路径", "启动失败", ICON_ERROR) @staticmethod def DoRefreshDNS(): Hosts.TryFlushDNSCache() MessagePanel.Send(u"刷新DNS成功", u"提示") def Exit(self): BackgroundThread.stopAllBackThread() self.trayIcon.Destroy() self.aboutDialog.Close() self.aboutDialog.Destroy() self.Close() self.Destroy() self.app.ExitMainLoop() def MainLoop(self): self.app.MainLoop() Settings.Save() @staticmethod def PrintSysInfo(): print("版本:", Settings.version()) print("系统:", sys.platform) print("hosts:", Hosts.GetHostsPath())