def initTwisted(self): from twisted.internet import wxreactor wxreactor.install() # Monkey-patching older versions because of https://twistedmatrix.com/trac/ticket/3948 import twisted if map(int, twisted.__version__.split('.')) < (11,): from twisted.internet import reactor if wxreactor.WxReactor.callFromThread is not None: oldStop = wxreactor.WxReactor.stop def stopFromThread(self): self.callFromThread(oldStop, self) wxreactor.WxReactor.stop = stopFromThread
def run_main_view_wx(config): """ Runs main UI view based on wx framework. """ # imports import wx import socket # might be some cross platform (windows) issues reported with wxReactor from twisted.internet import wxreactor # add twisted / wx interaction support wxreactor.install() # add logging observer from twisted.python.log import PythonLoggingObserver observer = PythonLoggingObserver() observer.start() # then can do normal reactor imports from twisted.internet import reactor # and wx specific implementations from ui.view_model_wx import MainViewController from ui.view_model_wx import MainViewModel from ui.main_view_wx import MainWindow # ip address *much* faster than by device name ipaddr = socket.gethostbyname(config.server_name) logging.debug("RPC:\tServer name %s resolved to IP address %s" % (config.server_name, ipaddr)) # create rpc client from web.webclient import RPCClient, RPCClientFactory rpc_client = RPCClient() # create view model view_model = MainViewModel() # create view controller controller = MainViewController(rpc_client, view_model, config) # create wxApp and main window wxApp = wx.App(False) frame = MainWindow(None, "fishpi - Proof Of Concept Vehicle control", controller, ipaddr, config.rpc_port, config.camera_port) frame.Show() # run reactor rather than usual 'wxApp.MainLoop()' reactor.registerWxApp(wxApp) logging.debug("RPC:\tconnecting to %s (%s) on port %s" % (config.server_name, ipaddr, config.rpc_port)) reactor.connectTCP(ipaddr, config.rpc_port, RPCClientFactory(controller)) #reactor.callLater(5, update_callback) reactor.run()
def initTwisted(self): from twisted.internet import wxreactor wxreactor.install() # Monkey-patching older versions because of https://twistedmatrix.com/trac/ticket/3948 import twisted if map(int, twisted.__version__.split('.')) < (11, ): from twisted.internet import reactor if wxreactor.WxReactor.callFromThread is not None: oldStop = wxreactor.WxReactor.stop def stopFromThread(self): self.callFromThread(oldStop, self) wxreactor.WxReactor.stop = stopFromThread
def use_wx_twisted(app): """Run `app` with a wx+Twisted event loop""" import wx, sys # ugh, Twisted is kinda borken for wx; it uses old-style names exclusively sys.modules['wxPython'] = sys.modules['wxPython.wx'] = wx wx.wxApp = wx.App wx.wxCallAfter = wx.CallAfter wx.wxEventLoop = wx.EventLoop wx.NULL = None wx.wxFrame = wx.Frame from twisted.internet import wxreactor wxreactor.install().registerWxApp(wx.GetApp() or wx.PySimpleApp()) use_twisted(app) WXUI_START.notify(app)
def run_main_view_wx(server, rpc_port, camera_port): """ Runs main UI view based on wx framework. """ # imports import wx import socket # might be some cross platform (windows) issues reported with wxReactor from twisted.internet import wxreactor # add twisted / wx interaction support wxreactor.install() # add logging observer from twisted.python.log import PythonLoggingObserver observer = PythonLoggingObserver() observer.start() # add some extra logging (temp - merge later) #from sys import stdout #from twisted.python.log import startLogging, err #startLogging(stdout) # then can do normal reactor imports from twisted.internet import reactor from ui.main_view_wx import MainWindow # ip address *much* faster than by device name ipaddr = socket.gethostbyname(server) # create rpc client from web.webclient import RPCClient, RPCClientFactory rpc_client = RPCClient() # create wxApp and main window wxApp = wx.App(False) frame = MainWindow(None, "fishpi - Proof Of Concept Vehicle control", ipaddr, rpc_port, camera_port) frame.Show() # run reactor rather than usual 'wxApp.MainLoop()' reactor.registerWxApp(wxApp) logging.debug("RPC:\tconnecting to %s (%s) on port %s" % (server, ipaddr, rpc_port)) reactor.connectTCP(ipaddr, rpc_port, RPCClientFactory(frame)) #reactor.callLater(5, update_callback) reactor.run()
import argparse, logging, application, sys if __name__ == '__main__': from twisted.internet import wxreactor reactor = wxreactor.install() import log application.log_object = log.LogObject(application.name) parser = argparse.ArgumentParser(prog = application.name, description = 'A (very) basic command line MUD client.') if not hasattr(parser, 'version'): parser.add_argument('-v', '--version', action = 'version', version = application.version, help = 'Show version information') else: parser.version = application.version parser.add_argument('-l', '--log-file', metavar = 'file', type = argparse.FileType('w'), default = sys.stdout, help = 'The log file.') parser.add_argument('-L', '--log-level', metavar = 'level', choices = ['debug', 'info', 'warning', 'warning', 'error', 'critical'], default = 'info', help = 'Log level') parser.add_argument('file', nargs = '?', help = 'File to load commands from') args = parser.parse_args() logging.basicConfig(stream = args.log_file, level = args.log_level.upper()) logger = logging.getLogger() import connection, command_parser, functions, wx, gui reactor.addSystemEventTrigger('after', 'shutdown', logger.debug, 'Reactor shutdown.') application.factory = connection.MyClientFactory() application.app = wx.App() reactor.registerWxApp(application.app) gui.MainFrame() reactor.addSystemEventTrigger('after', 'shutdown', application.frame.Close, True) application.frame.Show(True) application.frame.Maximize() if args.file: functions.load(args.file) reactor.run() try:
def init(UI='', options=None, args=None, overDict=None, executablePath=None): """ In the method ``main()`` program firstly checks the command line arguments and then calls this method to start the whole process. This initialize some low level modules and finally create an instance of ``initializer()`` state machine and send it an event "run". """ global AppDataDir from logs import lg lg.out(4, 'bpmain.run UI="%s"' % UI) from system import bpio #---settings--- from main import settings if overDict: settings.override_dict(overDict) settings.init(AppDataDir) if not options or options.debug is None: lg.set_debug_level(settings.getDebugLevel()) from main import config config.conf().addCallback('logs/debug-level', lambda p, value, o, r: lg.set_debug_level(value)) #---USE_TRAY_ICON--- if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()): try: from system.tray_icon import USE_TRAY_ICON if bpio.Mac() or not bpio.isGUIpossible(): lg.out(4, ' GUI is not possible') USE_TRAY_ICON = False if USE_TRAY_ICON: from twisted.internet import wxreactor wxreactor.install() lg.out(4, ' wxreactor installed') except: USE_TRAY_ICON = False lg.exc() else: lg.out(4, ' local identity or key file is not ready') USE_TRAY_ICON = False lg.out(4, ' USE_TRAY_ICON=' + str(USE_TRAY_ICON)) if USE_TRAY_ICON: from system import tray_icon icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons')) lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path) tray_icon.init(icons_path) def _tray_control_func(cmd): if cmd == 'exit': from . import shutdowner shutdowner.A('stop', 'exit') tray_icon.SetControlFunc(_tray_control_func) #---OS Windows init--- if bpio.Windows(): try: from win32event import CreateMutex # @UnresolvedImport mutex = CreateMutex(None, False, "BitDust") lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex)) except: lg.exc() #---twisted reactor--- lg.out(4, 'bpmain.run want to import twisted.internet.reactor') try: from twisted.internet import reactor # @UnresolvedImport except: lg.exc() sys.exit('Error initializing reactor in bpmain.py\n') #---logfile---- if lg.logs_enabled() and lg.log_file(): lg.out(2, 'bpmain.run want to switch log files') if bpio.Windows() and bpio.isFrozen(): lg.stdout_stop_redirecting() lg.close_log_file() lg.open_log_file(settings.MainLogFilename()) # lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log') if bpio.Windows() and bpio.isFrozen(): lg.stdout_start_redirecting() #---memdebug--- # if settings.uconfig('logs.memdebug-enable') == 'True': # try: # from logs import memdebug # memdebug_port = int(settings.uconfig('logs.memdebug-port')) # memdebug.start(memdebug_port) # reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop) # lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port) # except: # lg.exc() #---process ID--- try: pid = os.getpid() pid_file_path = os.path.join(settings.MetaDataDir(), 'processid') bpio.WriteTextFile(pid_file_path, str(pid)) lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path)) except: lg.exc() # #---reactor.callLater patch--- # if lg.is_debug(12): # patchReactorCallLater(reactor) # monitorDelayedCalls(reactor) # #---plugins--- # from plugins import plug # plug.init() # reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown) lg.out(2, " python executable is: %s" % sys.executable) lg.out(2, " python version is:\n%s" % sys.version) lg.out(2, " python sys.path is:\n %s" % ('\n '.join(sys.path))) lg.out(2, "bpmain.run UI=[%s]" % UI) if lg.is_debug(20): lg.out(0, '\n' + bpio.osinfofull()) lg.out(4, 'import automats') #---START!--- from automats import automat automat.LifeBegins(lg.when_life_begins()) automat.OpenLogFile(settings.AutomatsLog()) from main import events events.init() from main import initializer IA = initializer.A() lg.out(4, 'sending event "run" to initializer()') reactor.callWhenRunning(IA.automat, 'run', UI) # @UndefinedVariable return IA
def install_wx(app): # not tested #del sys.modules['twisted.internet.reactor'] from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor reactor.registerWxApp(app)
def init(UI='', options=None, args=None, overDict=None, executablePath=None): """ In the method ``main()`` program firstly checks the command line arguments and then calls this method to start the whole process. This initialize some low level modules and finally create an instance of ``initializer()`` state machine and send it an event "run". """ global AppDataDir from logs import lg lg.out(4, 'bpmain.run UI="%s"' % UI) from system import bpio #---settings--- from main import settings if overDict: settings.override_dict(overDict) settings.init(AppDataDir) if not options or options.debug is None: lg.set_debug_level(settings.getDebugLevel()) from main import config config.conf().addCallback('logs/debug-level', lambda p, value, o, r: lg.set_debug_level(value)) #---USE_TRAY_ICON--- if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()): try: from system.tray_icon import USE_TRAY_ICON if bpio.Mac() or not bpio.isGUIpossible(): lg.out(4, ' GUI is not possible') USE_TRAY_ICON = False if USE_TRAY_ICON: from twisted.internet import wxreactor wxreactor.install() lg.out(4, ' wxreactor installed') except: USE_TRAY_ICON = False lg.exc() else: lg.out(4, ' local identity or key file is not ready') USE_TRAY_ICON = False lg.out(4, ' USE_TRAY_ICON=' + str(USE_TRAY_ICON)) if USE_TRAY_ICON: from system import tray_icon icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons')) lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path) tray_icon.init(icons_path) def _tray_control_func(cmd): if cmd == 'exit': import shutdowner shutdowner.A('stop', 'exit') tray_icon.SetControlFunc(_tray_control_func) #---OS Windows init--- if bpio.Windows(): try: from win32event import CreateMutex mutex = CreateMutex(None, False, "BitDust") lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex)) except: lg.exc() #---twisted reactor--- lg.out(4, 'bpmain.run want to import twisted.internet.reactor') try: from twisted.internet import reactor except: lg.exc() sys.exit('Error initializing reactor in bpmain.py\n') #---logfile---- if lg.logs_enabled() and lg.log_file(): lg.out(2, 'bpmain.run want to switch log files') if bpio.Windows() and bpio.isFrozen(): lg.stdout_stop_redirecting() lg.close_log_file() lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log') if bpio.Windows() and bpio.isFrozen(): lg.stdout_start_redirecting() #---memdebug--- # if settings.uconfig('logs.memdebug-enable') == 'True': # try: # from logs import memdebug # memdebug_port = int(settings.uconfig('logs.memdebug-port')) # memdebug.start(memdebug_port) # reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop) # lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port) # except: # lg.exc() #---process ID--- try: pid = os.getpid() pid_file_path = os.path.join(settings.MetaDataDir(), 'processid') bpio.WriteFile(pid_file_path, str(pid)) lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path)) except: lg.exc() # #---reactor.callLater patch--- # if lg.is_debug(12): # patchReactorCallLater(reactor) # monitorDelayedCalls(reactor) # #---plugins--- # from plugins import plug # plug.init() # reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown) lg.out(2, "bpmain.run UI=[%s]" % UI) if lg.is_debug(20): lg.out(0, '\n' + bpio.osinfofull()) lg.out(4, 'bpmain.run import automats') #---START!--- from automats import automat automat.LifeBegins(lg.when_life_begins()) automat.OpenLogFile(settings.AutomatsLog()) import initializer I = initializer.A() lg.out(4, 'bpmain.run send event "run" to initializer()') reactor.callWhenRunning(I.automat, 'run', UI) return I
#!/usr/bin/python import wx import os, sys from twisted.internet import wxreactor wxreactor.install() # must be before 'import reactor' from twisted.internet import reactor def run(): app = wx.App(False) app.path = os.path.dirname(sys.argv[0]) from window.main import Main import prefs import worlds prefs.Initialize() worlds.Initialize() frame = Main(None, "wxpymoo") frame.Show(True) reactor.registerWxApp(app) reactor.run() app.MainLoop()
#!/usr/bin/env python import wx import sys import time from twisted.internet import wxreactor; wxreactor.install() from twisted.internet import reactor from twisted.internet import defer import hashlib import cPickle from functools import partial """ Entangled depends on Twisted (py25-twisted) for network programming Entangled depends on sqlite3 (py25-sqlite3) for the SqliteDataStore class. Could just use the DictDataStore class instead. Twisted depends on ZopeInterface (py25-zopeinterface) """ class MyMenu(wx.Frame): panels = None def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(600, 500)) # setup some uninitialized instance variables self.txt_search = None self.txt_tag = None self.lc = None self.displayed_files = []
def run(UI='', options=None, args=None, overDict=None): """ In the method `main()` program firstly checks the command line arguments and then calls this method to start the whole process. This initialize some low level modules and finally create an instance of `initializer()` state machine and send it an event "run". """ import lib.dhnio as dhnio dhnio.Dprint(6, 'dhnmain.run sys.path=%s' % str(sys.path)) #---USE_TRAY_ICON--- try: from dhnicon import USE_TRAY_ICON dhnio.Dprint(4, 'dhnmain.run USE_TRAY_ICON='+str(USE_TRAY_ICON)) if dhnio.Linux() and not dhnio.X11_is_running(): USE_TRAY_ICON = False if USE_TRAY_ICON: from twisted.internet import wxreactor wxreactor.install() except: USE_TRAY_ICON = False dhnio.DprintException() if USE_TRAY_ICON: if dhnio.Linux(): icons_dict = { 'red': 'icon-red-24x24.png', 'green': 'icon-green-24x24.png', 'gray': 'icon-gray-24x24.png', } else: icons_dict = { 'red': 'icon-red.png', 'green': 'icon-green.png', 'gray': 'icon-gray.png', } import dhnicon icons_path = str(os.path.abspath(os.path.join(dhnio.getExecutableDir(), 'icons'))) dhnio.Dprint(4, 'dhnmain.run call dhnicon.init(%s)' % icons_path) dhnicon.init(icons_path, icons_dict) def _tray_control_func(cmd): if cmd == 'exit': #import dhninit #dhninit.shutdown_exit() import shutdowner shutdowner.A('stop', 'exit') dhnicon.SetControlFunc(_tray_control_func) dhnio.Dprint(4, 'dhnmain.run want to import twisted.internet.reactor') try: from twisted.internet import reactor except: dhnio.DprintException() sys.exit('Error initializing reactor in dhnmain.py\n') #---settings--- import lib.settings as settings if overDict: settings.override_dict(overDict) settings.init() if not options or options.debug is None: dhnio.SetDebug(settings.getDebugLevel()) #---logfile---- if dhnio.EnableLog and dhnio.LogFile is not None: dhnio.Dprint(2, 'dhnmain.run want to switch log files') if dhnio.Windows() and dhnio.isFrozen(): dhnio.StdOutRedirectingStop() dhnio.CloseLogFile() dhnio.OpenLogFile(settings.MainLogFilename()+'-'+time.strftime('%y%m%d%H%M%S')+'.log') if dhnio.Windows() and dhnio.isFrozen(): dhnio.StdOutRedirectingStart() #---memdebug--- if settings.uconfig('logs.memdebug-enable') == 'True': try: import lib.memdebug as memdebug memdebug_port = int(settings.uconfig('logs.memdebug-port')) memdebug.start(memdebug_port) reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop) dhnio.Dprint(2, 'dhnmain.run memdebug web server started on port %d' % memdebug_port) except: dhnio.DprintException() #---process ID--- try: pid = os.getpid() pid_file_path = os.path.join(settings.MetaDataDir(), 'processid') dhnio.WriteFile(pid_file_path, str(pid)) dhnio.Dprint(2, 'dhnmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path)) except: dhnio.DprintException() # #---reactor.callLater patch--- # if dhnio.Debug(12): # patchReactorCallLater(reactor) # monitorDelayedCalls(reactor) dhnio.Dprint(2,"dhnmain.run UI=[%s]" % UI) if dhnio.Debug(10): dhnio.Dprint(0, '\n' + dhnio.osinfofull()) dhnio.Dprint(4, 'dhnmain.run import automats') #---START!--- import lib.automat as automat automat.LifeBegins(dhnio.LifeBeginsTime) automat.OpenLogFile(settings.AutomatsLog()) import initializer import shutdowner dhnio.Dprint(4, 'dhnmain.run send event "run" to initializer()') #reactor.callLater(0, initializer.A, 'run', UI) initializer.A('run', UI) #reactor.addSystemEventTrigger('before', 'shutdown', lambda : initializer.A('reactor-stopped')) dhnio.Dprint(2, 'dhnmain.run calling reactor.run()') reactor.run() dhnio.Dprint(2, 'dhnmain.run reactor stopped') # this will call initializer() without reactor.callLater(0, ... ) # we do not have any timers initializer() so do not worry #initializer.A('reactor-stopped', use_reactor = False) shutdowner.A('reactor-stopped') dhnio.Dprint(2, 'dhnmain.run finished, EXIT') automat.objects().clear() automat.CloseLogFile() ## import threading ## dhnio.Dprint(0, 'threads:') ## for t in threading.enumerate(): ## dhnio.Dprint(0, ' '+str(t)) dhnio.CloseLogFile() if dhnio.Windows() and dhnio.isFrozen(): dhnio.StdOutRedirectingStop() return 0
import wx from twisted.internet import wxreactor from main_window import MainWindow def main(): app = wx.App(False) frame = MainWindow(None, 'UDP Demo') from twisted.internet import reactor reactor.registerWxApp(app) reactor.run() if __name__ == "__main__": wxreactor.install() main()
def start_surface_station(): log.startLogging(sys.stdout) wxreactor.install() print(""" ######## ## ## ######## ### ######## ######## ## ### ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ###### ## ## ## ######## ## ## ######## ######## ## ## #### ## ## ######### ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ######## ## ## ######## ## ## ## ## ## ## ###### ## ## #### ## ## ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ###### ####### #### """) try: os.environ[ "GOOGLE_APPLICATION_CREDENTIALS"] = config.google_application_credentials_path except OSError as e: print("Error setting GOOGLE_APPLICATION_CREDENTIALS\n{}".format(e)) app = wx.App(False) app._camera_factory = None app._joystick_factory = None app._frame = RootFrame(app, log) from twisted.internet import reactor reactor.registerWxApp(app) if config.sim_mode: print("Note: Simulation mode is true, we're running locally!") app._camera_factory = ClientFactory(config.dev_camera_ws_url, app, protocol=CameraStreamProtocol) app._joystick_factory = ClientFactory( config.dev_joystick_ws_url, app, protocol=JoystickExecutorProtocol) # Connect to host reactor.connectTCP(config.dev_robot_url, config.dev_camera_ws_port, app._camera_factory) reactor.connectTCP(config.dev_robot_url, config.dev_joystick_ws_port, app._joystick_factory) else: print( "Note: Simulation mode is false, we're looking for the actual robot!" ) app._camera_factory = ClientFactory(config.live_camera_ws_url, app, protocol=CameraStreamProtocol) app._joystick_factory = ClientFactory( config.live_joystick_ws_url, app, protocol=JoystickExecutorProtocol) # Connect to host reactor.connectTCP(config.live_robot_url, config.live_camera_ws_port, app._camera_factory) reactor.connectTCP(config.live_robot_url, config.live_joystick_ws_port, app._joystick_factory) # Start twisted event loop reactor.run()
from control.txt.txtUserControl import * from control.xml.xmlUserControl import * #from control.mysql.sqlUserControl import * from ui.serverManager.serverManagerUi import * from config import * from debug import * import gettext import os,sys import locale import string import re from wx.lib.wordwrap import wordwrap from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor, defer from protocol.server import server_twisted _ = wx.GetTranslation def opj(path): """Convert paths to the platform-specific separator""" st = apply(os.path.join, tuple(path.split('/'))) # HACK: on Linux, a leading / gets lost... if path.startswith('/'): st = '/' + st return st class serverManager(serverManagerUi):
def ImportWx(): global wxreactor from twisted.internet import wxreactor wxreactor.install()