Example #1
0
    def __init__(self):
        self.app = WxAsyncApp()
        self.main_frame = MainFrame(None)
        self.remote_mod_list = ObjectList(
            element=self.main_frame.mod_list_list,
            columns=("name", "owner", "description", "latest_version",
                     "downloads"),
        )
        self.installed_mod_list = ObjectList(
            element=self.main_frame.installed_mods_list,
            columns=("name", "namespace", "version"),
            column_labels=("Name", "Author", "Version"),
        )
        self.downloaded_mod_list = ObjectList(
            element=self.main_frame.downloaded_mods_list,
            columns=("name", "namespace", "version"),
            column_labels=("Name", "Author", "Version"),
        )
        self.job_queue_list = ObjectList(
            element=self.main_frame.job_queue_list,
            columns=("name", "parameters_str"),
            column_labels=("Task", "Parameters"),
        )

        risk_of_rain_path = get_install_path()

        if not risk_of_rain_path:
            wx.MessageBox(
                "Failed to detect Risk of Rain 2 path. Add it to config.toml",
                "Error",
                wx.OK | wx.ICON_ERROR,
            )
            risk_of_rain_path = Path("risk-of-rain-2")

        self.configuration = ModManagerConfiguration(
            thunderstore_url="https://thunderstore.io/",
            mod_cache_path="mod-cache/",
            mod_install_path=risk_of_rain_path / "BepInEx" / "plugins",
            risk_of_rain_path=risk_of_rain_path,
        )
        self.job_manager = JobManager(
            big_progress_bar=self.main_frame.progress_bar_big,
            small_progress_bar=self.main_frame.progress_bar_small,
        )
        self.job_manager.bind_on_job_added(self.refresh_job_list)
        self.job_manager.bind_on_job_finished(self.refresh_job_list)

        self.manager = ModManager(self.configuration, self.job_manager)
        self.manager.bind_on_install(self.refresh_installed_mod_list)
        self.manager.bind_on_uninstall(self.refresh_installed_mod_list)
        self.manager.bind_on_download(self.refresh_downloaded_mod_list)
        self.manager.bind_on_delete(self.refresh_downloaded_mod_list)

        self.current_selection = PackageMetadata.empty()
        self.main_frame.selection_description.SetLabel("")
        self.main_frame.selection_title.SetLabel("")
        self.main_frame.selection_version.SetLabel("")
        self.main_frame.selection_download_count.SetLabel("")
        self.main_frame.selection_thunderstore_button.Disable()
        self.bind_events()
Example #2
0
def main():
    # Ensure gamestate integration cfg is in csgo's cfg directory
    csgo_dir = get_csgo_path(os.path.join(get_steam_path(), "steamapps"))
    if csgo_dir is not None:
        copyfile(
            "gamestate_integration_ccs.cfg",
            os.path.join(csgo_dir, "csgo", "cfg", "gamestate_integration_ccs.cfg"),
        )

    oalInit()
    loop = asyncio.get_event_loop()
    app = WxAsyncApp()
    gui.MainFrame(
        None,
        title="CSGO Custom Sounds",
        size=wx.Size(320, 230),
        style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX),
    )
    loop.run_until_complete(app.MainLoop())

    # Freeing OpenAL buffers might fail if they are still in use
    # We don't really care since the OS will clean up anyway.
    try:
        oalQuit()
    except:  # noqa
        pass
Example #3
0
 def run():
     app = WxAsyncApp()
     frame = WxAsyncAppMessageThroughputTest()
     loop = get_event_loop()
     loop.run_until_complete(app.MainLoop())
     #app.__del__()
     return frame.results()
Example #4
0
def main():
    app = WxAsyncApp()
    frame = TitanFrame(None, title=f"{NAME} {VERSION}")
    frame.Show()
    app.SetTopWindow(frame)
    loop = get_event_loop()
    loop.run_until_complete(app.MainLoop())
Example #5
0
def main_async():
    # see https://github.com/sirk390/wxasync
    app = WxAsyncApp()
    frame = SelectableFrame()
    frame.Show(True)
    app.SetTopWindow(frame)
    loop = get_event_loop()
    loop.run_until_complete(app.MainLoop())
Example #6
0
 def loadGUI(self):
     """
     Load WxPython (async)
     """
     if self.useGUI and not self.wxApp:
         from wxasync import WxAsyncApp
         self.wxApp = WxAsyncApp()
         self.wxGUITask = asyncio.ensure_future(self.wxApp.MainLoop())
def createWindow(msg_queue, buffer, client_network_main, ip, port):
    print("Creating Window")
    loop = asyncio.get_event_loop()
    loop.create_task(client_network_main(msg_queue, buffer, ip, port))
    app = WxAsyncApp()
    player = Player("Stream Media Player", buffer, msg_queue)
    player.Show()
    app.SetTopWindow(player)
    print("Running")
    # loop.set_debug(True)
    loop.run_until_complete(app.MainLoop())
Example #8
0
async def async_gui(coroutine):
    loop = get_event_loop()
    app = WxAsyncApp()
    task = loop.create_task(app.MainLoop())
    try:
        await coroutine
    except Exception as e:
        dlg = wx.MessageDialog(None, str(e), "Error")
        dlg.ShowModal()
    finally:
        task.cancel()
Example #9
0
def start():
    logging.basicConfig(format='[%(name)s] %(levelname)s:%(message)s',
                        level=logging.DEBUG)
    app = WxAsyncApp()
    loop = asyncio.get_event_loop()
    w = MainWindow()
    try:
        loop.run_until_complete(app.MainLoop())
    finally:
        loop.stop()
        loop.close()
Example #10
0
    def loadGUI(self):
        """
        Load WxPython (async)
        """
        from wxasync import WxAsyncApp
        import wx.lib.agw.persist as PM

        self.wxApp = WxAsyncApp()
        self.wxGUITask = asyncio.ensure_future(self.wxApp.MainLoop())

        self.wxAppPersistMgr = PM.PersistenceManager.Get()
        _configFile = os.path.join(self.settingsDir, "persistGUI.cfg")
        self.wxAppPersistMgr.SetPersistenceFile(_configFile)
Example #11
0
def start():
    logging.basicConfig(format='[%(name)s] %(levelname)s:%(message)s',
                        level=logging.DEBUG)
    log.setLoggerLevel("base.persistentobject", logging.ERROR)
    log.setLoggerLevel("base.modelobject", logging.ERROR)
    log.setLoggerLevel("base.tilecontainer", logging.ERROR)
    #log.setLoggerLevel("gui.tilewidgetview", logging.ERROR)
    log.setLoggerLevel("gui.tilesetwidget", logging.ERROR)
    #log.setLoggerLevel("gui.gamepanels", logging.ERROR)
    app = WxAsyncApp()
    loop = asyncio.get_event_loop()
    w = MainWindow()
    try:
        loop.run_until_complete(app.MainLoop())
    finally:
        loop.stop()
        loop.close()
Example #12
0
def run():
    app = WxAsyncApp()

    app.path = os.path.dirname(sys.argv[0])

    from window.main import Main
    import prefs
    import worlds
    import theme

    prefs.Initialize()
    worlds.Initialize()
    theme.Initialize()

    frame = Main(None, "wxpymoo")
    frame.Show(True)

    app.loop.run_until_complete(app.MainLoop())
Example #13
0
def _real_main():
    utils.insure_filesystem()
    utils.setup_logging()
    logging.info(
        f"Starting UtopiaForReddit version {variables.version_human_friendly}")
    utils.setup_caching()
    logging.info("Loading config and saving defaults if needed.")
    variables.config = config.get_config().load().save_defaults()
    logging.info("Starting ui framework")
    loop = asyncio.get_event_loop()
    loop.set_exception_handler(global_exception_handler)
    app = WxAsyncApp(loop=loop)
    loop.set_debug(True)
    am = account_manager.AccountManager(True)
    # The account manager is either shown or passed through. In either case, the show call, are done in the create method of the account manager.
    # and then the main ui will be shown.
    # check for updates
    StartCoroutine(updater.check_for_updates(), am)
    # Show program tips
    tips.show_tips(None, False)
    loop.run_until_complete(app.MainLoop())
Example #14
0
class moduleManager():
    """
    Manage a set of modules
    """
    def __init__(self, loop, settingsDir, useGUI):
        # dict of modules. Key is module name
        self.multiModules = {}

        # are we using a GUI?
        self.useGUI = useGUI

        # asyncio event loop
        self.loop = loop

        # PaGS settings dir
        self.settingsDir = settingsDir

        # dict of tx send functions for vehicles
        # self.vehTxCallbacks = {}

        # Callback to sending packets
        self.pktTxCallback = None

        # Callback to vehicles
        self.vehListCallback = None
        self.getVehCallback = None

        # Dict of current terminal commands?
        self.commands = {}

        # add in module managment commands
        self.commands['module'] = {'load': self.load, 'list': self.list}

        # Dict of modules that print text
        self.printers = {}

        # WxAsync (if we're using a GUI)
        self.wxApp = None
        self.wxGUITask = None
        self.wxAppPersistMgr = None

        if self.useGUI:
            self.loadGUI()

    def printVeh(self, vehname: str, text: str):
        """
        Print to any loaded outputs
        """
        for prname in self.printers:
            self.printers[prname](text, vehname)

    def onPktTxAttach(self, func):
        """
        Attach a callback to a packet recieved
        """
        self.pktTxCallback = func

    def onVehListAttach(self, func):
        """
        Attach a callback to a packet recieved
        """
        self.vehListCallback = func

    def onVehGetAttach(self, func):
        """
        Attach a callback to a packet recieved
        """
        self.getVehCallback = func

    def load(self, vehname: str, module: str):
        """
        Command handler for "module load xxx" command
        """
        if module in self.multiModules or "PaGS." + module in self.multiModules:
            self.printVeh(vehname, "Module already loaded")
        else:
            try:
                self.addModule(module)
                if module in self.multiModules or "PaGS." + module in self.multiModules:
                    self.printVeh(vehname, "Loaded module " + module)
                else:
                    self.printVeh(vehname, "Cannot load module " + module)
            except ValueError:
                self.printVeh(vehname, "Cannot find module")

    def list(self, vehname: str):
        """
        Command handler for "module list" command
        """
        self.printVeh(vehname, "Loaded Modules: ")
        for key in self.multiModules:
            self.printVeh(vehname, key)

    def onModuleCommandCallback(self, vehname, cmd):
        """
        Process a user command from vehicle
        """
        self.printVeh(vehname, cmd)
        # First decode the command
        if cmd == "":
            return
        try:
            args = shlex.split(cmd)
        except ValueError:
            self.printVeh(vehname, "Malformed command: " + str(cmd))
            return
        # ensure the command is not malformed
        if len(args) < 2 or args[0] not in self.commands.keys(
        ) or args[1] not in self.commands[args[0]].keys():
            self.printVeh(vehname, "Command not found: " + str(cmd))
            return
        # ensure the vehicle has a connection
        if not self.getVehCallback(vehname).hasInitial:
            self.printVeh(
                vehname,
                "Cannot send command to vehicle - no packets received on link")
            return
        try:
            # then send it onwards, with handled exceptions
            # also await if it's an async function
            if len(args) > 2:
                self.commands[args[0]][args[1]](vehname, *args[2:])
            else:
                self.commands[args[0]][args[1]](vehname)
        except Exception:
            self.printVeh(vehname, traceback.format_exc())

    def loadGUI(self):
        """
        Load WxPython (async)
        """
        from wxasync import WxAsyncApp
        import wx.lib.agw.persist as PM

        self.wxApp = WxAsyncApp()
        self.wxGUITask = asyncio.ensure_future(self.wxApp.MainLoop())

        self.wxAppPersistMgr = PM.PersistenceManager.Get()
        _configFile = os.path.join(self.settingsDir, "persistGUI.cfg")
        self.wxAppPersistMgr.SetPersistenceFile(_configFile)

    def addModule(self, name: str):
        """
        Initialise a module
        """
        mod = None
        try:
            mod = import_module(name)
        except ImportError:
            try:
                mod = import_module("PaGS." + name)
                name = "PaGS." + name
            except ImportError:
                raise ValueError('No module with that name')

        self.multiModules[name] = mod.Module(self.loop, self.outgoingPacket,
                                             self.vehListCallback,
                                             self.getVehCallback,
                                             self.onModuleCommandCallback,
                                             self.printVeh, self.settingsDir,
                                             self.useGUI, self.wxAppPersistMgr)
        # and add any vehicles from beforehand
        for vehname in self.vehListCallback():
            self.multiModules[name].addVehicle(vehname)

        # add any command callbacks
        self.commands[self.multiModules[name].shortName] = {}
        for key, val in self.multiModules[name].commandDict.items():
            self.commands[self.multiModules[name].shortName].update({key: val})

        # add any output printers, if defined
        try:
            printer = self.multiModules[name].printVeh
            self.printers[name] = printer
        except AttributeError:
            pass

    async def removeModule(self, name: str):
        """
        Remove a module
        """
        if name not in self.multiModules:
            raise ValueError('No module with that name')
            return
        else:
            if name in self.printers.keys():
                del self.printers[name]
            del self.commands[self.multiModules[name].shortName]

            await self.multiModules[name].closeModule()

            del self.multiModules[name]
            return

    async def closeAllModules(self):
        """
        Close all modules cleanly
        """
        for modulename in self.multiModules:
            await self.multiModules[modulename].closeModule()

        # Close the wxAsync GUI if required
        if self.wxGUITask:
            self.wxGUITask.cancel()
            with suppress(asyncio.CancelledError):
                await self.wxGUITask  # await for task cancellation

    def addVehicle(self, vehName):
        """
        Event for add new vehicle
        """
        for modulename in self.multiModules:
            self.multiModules[modulename].addVehicle(vehName)

    def removeVehicle(self, vehName):
        """
        Event for remove vehicle
        """
        for modulename in self.multiModules:
            self.multiModules[modulename].removeVehicle(vehName)

    def incomingPacket(self, vehname: str, pkt, strconnection: str):
        """
        Pass incoming packets onto modules
        """
        for modulename in self.multiModules:
            logging.debug("Packet from " + vehname + " going to module " +
                          modulename)
            try:
                # then send it onwards, with handled exceptions
                self.multiModules[modulename].incomingPacket(vehname, pkt)
            except Exception:
                self.printVeh(vehname, traceback.format_exc())

    def outgoingPacket(self, vehname: str, pktType, **kwargs):
        """
        Send the packet out via the vehicle manager
        """
        if self.pktTxCallback:
            logging.debug("Module sending packet to " + vehname)
            self.pktTxCallback(vehname, pktType, **dict(kwargs))
Example #15
0
                if d.name.lower().startswith("lego mario"):
                    self.gui.status_field.SetLabel("Found Mario!")
                    try:
                        async with BleakClient(d.address) as client:
                            await client.is_connected()
                            self.gui.status_field.SetLabel("Mario is connected")
                            self.is_connected = True
                            await client.start_notify(LEGO_CHARACTERISTIC_UUID, self.notification_handler)
                            await asyncio.sleep(0.1)
                            await client.write_gatt_char(LEGO_CHARACTERISTIC_UUID, SUBSCRIBE_IMU_COMMAND)
                            await asyncio.sleep(0.1)
                            await client.write_gatt_char(LEGO_CHARACTERISTIC_UUID, SUBSCRIBE_RGB_COMMAND)
                            while await client.is_connected():
                                await self.process_keys()
                    except:
                        pass


# Run it
if __name__ == "__main__":
    # The application object.
    app = WxAsyncApp()
    # The app frame
    frm = MarioFrame()
    # Drawing it
    frm.Show()

    # Start the main loop
    loop = asyncio.get_event_loop()
    loop.run_until_complete(app.MainLoop())
Example #16
0
def main():
    app = WxAsyncApp()
    loop = get_event_loop()
    toolbar_frame = ToolbarFrame(loop, None)
    toolbar_frame.Show()
    loop.run_until_complete(app.MainLoop())
Example #17
0
class Application:
    def __init__(self):
        self.app = WxAsyncApp()
        self.main_frame = MainFrame(None)
        self.remote_mod_list = ObjectList(
            element=self.main_frame.mod_list_list,
            columns=("name", "owner", "description", "latest_version",
                     "downloads"),
        )
        self.installed_mod_list = ObjectList(
            element=self.main_frame.installed_mods_list,
            columns=("name", "namespace", "version"),
            column_labels=("Name", "Author", "Version"),
        )
        self.downloaded_mod_list = ObjectList(
            element=self.main_frame.downloaded_mods_list,
            columns=("name", "namespace", "version"),
            column_labels=("Name", "Author", "Version"),
        )
        self.job_queue_list = ObjectList(
            element=self.main_frame.job_queue_list,
            columns=("name", "parameters_str"),
            column_labels=("Task", "Parameters"),
        )

        risk_of_rain_path = get_install_path()

        if not risk_of_rain_path:
            wx.MessageBox(
                "Failed to detect Risk of Rain 2 path. Add it to config.toml",
                "Error",
                wx.OK | wx.ICON_ERROR,
            )
            risk_of_rain_path = Path("risk-of-rain-2")

        self.configuration = ModManagerConfiguration(
            thunderstore_url="https://thunderstore.io/",
            mod_cache_path="mod-cache/",
            mod_install_path=risk_of_rain_path / "BepInEx" / "plugins",
            risk_of_rain_path=risk_of_rain_path,
        )
        self.job_manager = JobManager(
            big_progress_bar=self.main_frame.progress_bar_big,
            small_progress_bar=self.main_frame.progress_bar_small,
        )
        self.job_manager.bind_on_job_added(self.refresh_job_list)
        self.job_manager.bind_on_job_finished(self.refresh_job_list)

        self.manager = ModManager(self.configuration, self.job_manager)
        self.manager.bind_on_install(self.refresh_installed_mod_list)
        self.manager.bind_on_uninstall(self.refresh_installed_mod_list)
        self.manager.bind_on_download(self.refresh_downloaded_mod_list)
        self.manager.bind_on_delete(self.refresh_downloaded_mod_list)

        self.current_selection = PackageMetadata.empty()
        self.main_frame.selection_description.SetLabel("")
        self.main_frame.selection_title.SetLabel("")
        self.main_frame.selection_version.SetLabel("")
        self.main_frame.selection_download_count.SetLabel("")
        self.main_frame.selection_thunderstore_button.Disable()
        self.bind_events()

    def refresh_job_list(self):
        self.job_queue_list.update(self.job_manager.job_queue)

    async def handle_remote_mod_list_select(self, event=None):
        await self.handle_selection_update(
            self.remote_mod_list.get_first_selection())

    async def handle_installed_mod_list_select(self, event=None):
        await self.handle_selection_update(
            self.installed_mod_list.get_first_selection())

    async def handle_downloaded_mod_list_select(self, event=None):
        await self.handle_selection_update(
            self.downloaded_mod_list.get_first_selection())

    async def handle_selection_update(self, selection):
        if not selection:
            return
        selection_meta = self.manager.resolve_package_metadata(selection)
        self.current_selection = selection_meta
        self.main_frame.selection_title.SetLabel(selection_meta.name)
        self.main_frame.selection_title.Wrap(160)

        self.main_frame.selection_description.SetLabel(
            selection_meta.description)
        self.main_frame.selection_description.Wrap(240)

        version_text = f"Selected Version: v{selection_meta.version}"
        self.main_frame.selection_version.SetLabel(version_text)
        self.main_frame.selection_version.Wrap(240)

        downloads_text = f"Downloads: {selection_meta.downloads}"
        self.main_frame.selection_download_count.SetLabel(downloads_text)
        self.main_frame.selection_download_count.Wrap(240)

        if selection_meta.thunderstore_url:
            self.main_frame.selection_thunderstore_button.Enable()
        else:
            self.main_frame.selection_thunderstore_button.Disable()

        bitmap = None

        icon_data = await selection_meta.get_icon_bytes()
        if icon_data:
            bitmap = wx.Image(icon_data).ConvertToBitmap()

        if bitmap is None:
            bitmap = wx.Bitmap("resources\\icon-unknown.png")

        if self.current_selection == selection_meta:
            self.main_frame.selection_icon_bitmap.SetBitmap(bitmap)

    async def handle_installed_mod_list_uninstall(self, event=None):
        selections = self.installed_mod_list.get_selected_objects()
        for selection in selections:
            meta = self.manager.resolve_package_metadata(selection)
            await self.add_job(UninstallPackage, meta.package_reference)

    async def handle_downloaded_mod_list_install(self, event=None):
        selections = self.downloaded_mod_list.get_selected_objects()
        for selection in selections:
            meta = self.manager.resolve_package_metadata(selection)
            reference = meta.package_reference
            if reference.version:
                await self.add_job(InstallPackage, reference)
            else:
                newest = self.manager.get_newest_cached(reference)
                if newest:
                    self.manager.installed_packages(newest)

    async def handle_downloaded_mod_list_delete(self, event=None):
        selections = self.downloaded_mod_list.get_selected_objects()
        for selection in selections:
            meta = self.manager.resolve_package_metadata(selection)
            reference = meta.package_reference
            if self.main_frame.downloaded_mods_group_version_checkbox.GetValue(
            ):
                reference = reference.without_version
            await self.add_job(DeletePackage, reference)

    async def handle_installed_mod_list_update_button(self, event=None):
        self.main_frame.installed_mods_update_button.Disable()
        await self.handle_mod_list_refresh()
        installed_packages = self.manager.installed_packages
        for package in self.manager.installed_packages:
            package = package.without_version
            if package not in self.manager.api.packages:
                continue
            package = self.manager.api.packages[package]
            latest = package.versions.latest.package_reference
            if latest not in installed_packages:
                await self.add_job(DownloadAndInstallPackage, latest)
        self.main_frame.installed_mods_update_button.Enable()

    def handle_selection_thunderstore_button(self, event=None):
        meta = self.manager.resolve_package_metadata(self.current_selection)
        if meta.thunderstore_url:
            webbrowser.open(meta.thunderstore_url)

    def bind_events(self):
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_mod_list_refresh,
            self.main_frame.mod_list_refresh_button,
        )
        self.main_frame.downloaded_mods_group_version_checkbox.Bind(
            wx.EVT_CHECKBOX, self.refresh_downloaded_mod_list)
        self.main_frame.selection_thunderstore_button.Bind(
            wx.EVT_BUTTON, self.handle_selection_thunderstore_button)
        AsyncBind(
            wx.EVT_LIST_ITEM_SELECTED,
            self.handle_installed_mod_list_select,
            self.main_frame.installed_mods_list,
        )
        AsyncBind(
            wx.EVT_LIST_ITEM_SELECTED,
            self.handle_downloaded_mod_list_select,
            self.main_frame.downloaded_mods_list,
        )
        AsyncBind(
            wx.EVT_LIST_ITEM_SELECTED,
            self.handle_remote_mod_list_select,
            self.main_frame.mod_list_list,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_installed_mod_list_uninstall,
            self.main_frame.installed_mods_uninstall_button,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_downloaded_mod_list_install,
            self.main_frame.downloaded_mods_install_button,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_downloaded_mod_list_delete,
            self.main_frame.downloaded_mods_delete_button,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_mod_list_install,
            self.main_frame.mod_list_install_button,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_installed_mod_list_export,
            self.main_frame.installed_mods_export_button,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_installed_mod_list_import,
            self.main_frame.installed_mods_import_button,
        )
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_installed_mod_list_update_button,
            self.main_frame.installed_mods_update_button,
        )
        AsyncBind(wx.EVT_TEXT, self.handle_mod_list_search,
                  self.main_frame.mod_list_search)
        AsyncBind(
            wx.EVT_BUTTON,
            self.handle_launch_game_button,
            self.main_frame.launch_game_button,
        )

    async def handle_launch_game_button(self, event=None):
        webbrowser.open_new("steam://run/632360")

    async def handle_installed_mod_list_export(self, event=None):
        CopyableDialog(
            self.main_frame,
            "Installed mods export",
            json.dumps([str(x) for x in self.manager.installed_packages]),
        )

    async def attempt_import(self, raw_data):
        try:
            references = json.loads(raw_data)
        except Exception:
            wx.MessageBox(
                "Failed to import mod configuration. Is it proper JSON?",
                "Error",
                wx.OK | wx.ICON_ERROR,
            )
            return

        try:
            references = [PackageReference.parse(x) for x in references]
        except Exception:
            wx.MessageBox(
                "Failed to parse some of the mod names and could not import.",
                "Error",
                wx.OK | wx.ICON_ERROR,
            )
            return

        for reference in references:
            await self.add_job(DownloadAndInstallPackage, reference)

    async def add_job(self, cls, *args):
        await self.job_manager.put(cls(self.manager, *args))

    async def handle_installed_mod_list_import(self, event=None):
        dialog = wx.TextEntryDialog(self.main_frame, "Enter mod configuration",
                                    "Installed mods import")
        if dialog.ShowModal() == wx.ID_OK:
            await self.attempt_import(dialog.GetValue())
        dialog.Destroy()

    async def handle_mod_list_search(self, event=None):
        query = event.GetString()
        if query is None:
            return
        await self.update_mod_list_content(query)

    async def handle_mod_list_install(self, event=None):
        selections = self.remote_mod_list.get_selected_objects()
        for selection in selections:
            meta = self.manager.resolve_package_metadata(selection)
            await self.add_job(DownloadAndInstallPackage,
                               meta.package_reference)

    async def handle_mod_list_refresh(self, event=None):
        if event:
            event.GetEventObject().Disable()
        try:
            await self.manager.api.async_update_packages()
            await self.update_mod_list_content()
        except Exception as e:
            log_exception(e)
            wx.MessageBox(
                "Failed to pull remote package data. Server could be offline.",
                "Error",
                wx.OK | wx.ICON_ERROR,
            )
        if event:
            event.GetEventObject().Enable()

    async def update_mod_list_content(self, query=None):
        if query is None:
            query = self.main_frame.mod_list_search.GetValue()

        def matches_query(package):
            matches_name = query.lower() in str(package.full_name).lower()
            matches_desc = query.lower() in package.description.lower()
            return matches_name or matches_desc

        packages = self.manager.api.packages.values()
        packages = filter(matches_query, packages)
        packages = sorted(packages, key=lambda entry: entry.name)
        self.remote_mod_list.update(packages)

    def refresh_installed_mod_list(self, event=None):
        packages = sorted(self.manager.installed_packages,
                          key=lambda entry: entry.name)
        self.installed_mod_list.update(packages)

    def refresh_downloaded_mod_list(self, event=None):
        packages = self.manager.cached_packages
        if self.main_frame.downloaded_mods_group_version_checkbox.GetValue():
            packages = set([package.without_version for package in packages])
        packages = sorted(packages, key=lambda entry: entry.name)
        self.downloaded_mod_list.update(packages)

    def launch(self):
        self.main_frame.Show()
        self.refresh_installed_mod_list()
        self.refresh_downloaded_mod_list()
        wx.Log.SetActiveTarget(wx.LogStderr())
        StartCoroutine(self.job_manager.worker, self.main_frame)
        StartCoroutine(self.manager.validate_cache, self.main_frame)
        StartCoroutine(self.manager.migrate_mmm_prefixes, self.main_frame)
        loop = get_event_loop()
        loop.run_until_complete(self.app.MainLoop())
Example #18
0
 def run():
     loop = get_event_loop()
     app = WxAsyncApp()
     frame = WxAsyncAsyncIOLatencyTest(loop=loop)
     loop.run_until_complete(app.MainLoop())
     return frame.results()
Example #19
0
async def main():            
    app = WxAsyncApp()
    frame = TestFrame()
    frame.Show()
    app.SetTopWindow(frame)
    await app.MainLoop()
Example #20
0
async def run_app():
    app = WxAsyncApp()
    main_window = MainWindow()
    main_window.Show()
    app.SetTopWindow(main_window)
    await app.MainLoop()
Example #21
0
import asyncio
import logging
import os

from demo.windows.main_window import MainWindow
from wxasync import WxAsyncApp

_LOGGER = logging.getLogger(__name__)

if __name__ == "__main__":
    os.environ["DEBUGGING"] = "1"
    logging.basicConfig(level=logging.DEBUG)
    loop = asyncio.get_event_loop()
    app = WxAsyncApp()
    main_window = MainWindow()
    main_window.Show()
    app.SetTopWindow(main_window)
    loop.run_until_complete(app.MainLoop())
Example #22
0
def main():
    app = WxAsyncApp()
    frame = TitanPatcherFrame(None, title=f"Titan Patcher")
    app.SetTopWindow(frame)
    loop = get_event_loop()
    loop.run_until_complete(app.MainLoop())
Example #23
0
        self.dwbtn = wx.Button(panel, label='下载', size=(-1, 27))
        grid_sizer.AddMany([(self.tag_ctrl, 1, wx.EXPAND), (self.begin),
                            (self.end), (self.dwbtn)])

        AsyncBind(wx.EVT_BUTTON, self.download, self.dwbtn)

        box_sizer.Add(grid_sizer, 1, wx.ALL | wx.CENTER, 20)

        self.img_list = wx.ListCtrl(panel, -1, style=wx.LC_REPORT)
        self.img_list.InsertColumn(0, '图片名')

        box_sizer.Add(self.img_list, 1, wx.EXPAND | wx.ALL ^ wx.TOP, 20)

        panel.SetSizer(box_sizer)

        self.Centre()

    async def download(self, evt):
        pass


if __name__ == '__main__':
    app = WxAsyncApp()
    frame = MainFrame()
    app.SetTopWindow(frame)
    frame.Show()

    evt = asyncio.get_event_loop()
    evt.run_until_complete(app.MainLoop())
if __name__ == '__main__':
    import _overlapped

    orig = _overlapped.GetQueuedCompletionStatus 
    def GetQueuedCompletionStatus(iocp, ms):
        handles = ctypes.c_int(iocp)
        result = ctypes.windll.user32.MsgWaitForMultipleObjectsEx(1, ctypes.byref(handles), 1, QS_ALLINPUT|QS_ALLPOSTMESSAGE, MWMO_ALERTABLE)
        if result == WAIT_IO_COMPLETION:
            return orig (iocp, ms)
        elif result == WAIT_TIMEOUT:
            return
        app = wx.App.Get()
        if type(app) is not WxAsyncApp:
            raise Exception("Create a 'WxAsyncApp' first")
        app.DispatchMessages()
        
    _overlapped.GetQueuedCompletionStatus = GetQueuedCompletionStatus
    loop = asyncio.ProactorEventLoop()
    
    asyncio.set_event_loop(loop)
    
      
    app = WxAsyncApp()

    '''frame = TestFrame()
    frame.Show()
    app.SetTopWindow(frame)
    loop = get_event_loop()
    loop.run_until_complete(app.MainLoop())
    '''
    print (WxMessageThroughputTest.run())
 def run():  
     loop = get_event_loop()
     app = WxAsyncApp()
     frame = WxAsyncAppCombinedThroughputTest(loop=loop)
     loop.run_until_complete(app.MainLoop())
     return frame.results()
Example #26
0
def start_gui():
    """start the GUI"""
    return WxAsyncApp()
Example #27
0
 async def main():            
     app = WxAsyncApp()
     asyncio.create_task(opendialog())
     await app.MainLoop()
Example #28
0
def wx_app():
    app = WxAsyncApp()
    return app