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() TestCreateOglInterfaceCommand.clsLogger = getLogger(__name__) PyutPreferences.determinePreferencesLocation() TestCreateOglInterfaceCommand.clsApp = App()
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 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 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 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(): """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(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 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 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 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 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=}')
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
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) gui = HondaECU_ControlPanel(__VERSION__) 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())
def openSettings(): from settingsFrame import SettingsFrame from wx import App app = App(False) frame = SettingsFrame(None, 'GMS Settings') app.MainLoop()
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Quantum Calculator Author: Hideto Manjo Licence: Apache License 2.0 ''' from wx import App from interface import Calculator if __name__ == '__main__': APPLICATION = App() FRAME = Calculator() FRAME.Show() APPLICATION.MainLoop()
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() TestIDFactory.clsLogger = getLogger(__name__) PyutPreferences.determinePreferencesLocation() TestIDFactory.clsApp = App()
def main(): app = App() MainWindow(parent=None, size=(WINDOW_WIDTH, WINDOW_HEIGHT)) app.MainLoop()
from wx import App from controlpanel import HondaECU_ControlPanel from version import __VERSION__ rid = {"MotoAmerica 2019: Junior Cup": "MAJC190"} restrictions = { "CBR500R": { "MotoAmerica 2019: Junior Cup": { "Ignition": [-4, 10] } } } if __name__ == '__main__': app = App(redirect=True) __VERSION__ = __VERSION__.split("-") __VERSION__[0] = __VERSION__[0] + "_MAspec" __VERSION__ = "-".join(__VERSION__) gui = HondaECU_ControlPanel(__VERSION__, nobins=True, restrictions=(rid, restrictions), force_restrictions=True) app.MainLoop()
def setUpClass(cls): TestBase.setUpLogging() TestLineSplitter.clsLogger = getLogger(__name__) TestLineSplitter.clsApp = App()
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",
#!/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'
def init_gui(): app = App(False) frame = GUI() frame.Show() app.MainLoop()
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(): global app app = App()