def do_pause(self): # should go to app pause mode. from kivy.app import App from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, exit.') stopTouchApp() return if not app.dispatch('on_pause'): Logger.info('WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return # XXX FIXME wait for sdl resume while True: event = self._win.poll() if event is False: continue if event is None: continue action, args = event[0], event[1:] if action == 'quit': EventLoop.quit = True self.close() break elif action == 'windowrestored': break app.dispatch('on_resume')
def _event_filter(self, action): from kivy.app import App if action == 'app_terminating': EventLoop.quit = True self.close() elif action == 'app_lowmemory': self.dispatch('on_memorywarning') elif action == 'app_willenterbackground': from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, exit.') stopTouchApp() return 0 if not app.dispatch('on_pause'): Logger.info('WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return 0 self._pause_loop = True elif action == 'app_didenterforeground': # on iOS, the did enter foreground is launched at the start # of the application. in our case, we want it only when the app # is resumed if self._pause_loop: self._pause_loop = False app = App.get_running_app() app.dispatch('on_resume') return 0
def stop(self, *largs): '''Stop the application. If you use this method, the whole application will stop by issuing a call to :func:`~kivy.base.stopTouchApp`. ''' stopTouchApp()
def do_pause(self): # should go to app pause mode (desktop style) from kivy.app import App from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info("WindowSDL: No running App found, exit.") stopTouchApp() return if not app.dispatch("on_pause"): Logger.info("WindowSDL: App doesn't support pause mode, stop.") stopTouchApp() return # XXX FIXME wait for sdl resume while True: event = self._win.poll() if event is False: continue if event is None: continue action, args = event[0], event[1:] if action == "quit": EventLoop.quit = True self.close() break elif action == "app_willenterforeground": break elif action == "windowrestored": break app.dispatch("on_resume")
def on_keyboard(self, key, scancode=None, str=None, modifier=None): # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w # TODO If just CMD+w is pressed, only the window should be closed. is_osx = sys.platform == 'darwin' if key == 27 or (is_osx and key in (113, 119) and modifier == 1024): stopTouchApp() self.close() # not sure what to do here return True super(WindowSDL, self).on_keyboard(key, scancode, str, modifier)
def on_keyboard_android(self, window, key, scancode, codepoint, modifier): if key in (8, 27) or key == Keyboard.keycodes['escape']: # Backspace or escape if self.screen_manager.current == 'main': stopTouchApp() else: self.go_main() if self.experiment_layout.experiment is not None: if key in (282, 319): self.experiment_layout.toggle_tabs() return True
def on_keyboard(self, key, scancode=None, codepoint=None, modifier=None, **kwargs): codepoint = codepoint or kwargs.get("unicode") # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w # TODO If just CMD+w is pressed, only the window should be closed. is_osx = platform() == "darwin" if key == 27 or (is_osx and key in (113, 119) and modifier == 1024): stopTouchApp() self.close() # not sure what to do here return True super(WindowPygame, self).on_keyboard(key, scancode, codepoint=codepoint, modifier=modifier)
def mainloop(self): while not EventLoop.quit and EventLoop.status == 'started': try: self._mainloop() except BaseException as inst: # use exception manager first r = ExceptionManager.handle_exception(inst) if r == ExceptionManager.RAISE: stopTouchApp() raise else: pass
def tearDown(self, fake=False): '''When the test is finished, stop the application, and unbind our current flip callback. ''' from kivy.base import stopTouchApp from kivy.core.window import Window Window.unbind(on_flip=self.on_window_flip) stopTouchApp() if not fake and self.test_failed: self.assertTrue(False) super(GraphicUnitTest, self).tearDown()
def stop(self, *largs): '''Stop the application. If you use this method, the whole application will stop by issuing a call to :func:`~kivy.base.stopTouchApp`. ''' self.dispatch('on_stop') stopTouchApp() # Clear the window children for child in self._app_window.children: self._app_window.remove_widget(child)
def on_keyboard_android(self, window, key, scancode, codepoint, modifier): if key in ( 8, 27 ) or key == Keyboard.keycodes['escape']: # Backspace or escape if self.screen_manager.current == 'main': stopTouchApp() else: self.go_main() if self.experiment_layout.experiment is not None: if key in (282, 319): self.experiment_layout.toggle_tabs() return True
def on_keyboard(self, key, scancode=None, codepoint=None, modifier=None, **kwargs): codepoint = codepoint or kwargs.get('unicode') # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w # TODO If just CMD+w is pressed, only the window should be closed. is_osx = platform() == 'darwin' if key == 27 or (is_osx and key in (113, 119) and modifier == 1024): stopTouchApp() self.close() # not sure what to do here return True super(WindowPygame, self).on_keyboard(key, scancode, codepoint=codepoint, modifier=modifier)
def mainloop(self): while not EventLoop.quit and EventLoop.status == 'started': try: self._mainloop() if not pygame.display.get_active(): pygame.time.wait(100) except BaseException as inst: # use exception manager first r = ExceptionManager.handle_exception(inst) if r == ExceptionManager.RAISE: stopTouchApp() raise else: pass
def mainloop(self): while not EventLoop.quit and EventLoop.status == 'started': try: self._mainloop() if not pygame.display.get_active(): pygame.time.wait(100) except BaseException, inst: # use exception manager first r = ExceptionManager.handle_exception(inst) if r == ExceptionManager.RAISE: stopTouchApp() raise else: pass
def on_key_down(self, win, key, scancode, string, modifiers): system = platform.system() if system == 'Darwin': if 'meta' in modifiers: if key == 113: # cmd+q stopTouchApp() return True if key == 104: # cmd+h pygame.display.iconify() return True elif platform == 'Windows': if 'alt' in modifiers and key == 285: # alt+f4 stopTouchApp() return True
def mainloop(self): while not self.quit and self.status == 'started': try: self.idle() if self.window: self.window.mainloop() except BaseException as inst: # use exception manager first r = ExceptionManager.handle_exception(inst) if r == ExceptionManager.RAISE: stopTouchApp() raise else: pass
async def __aexit__(self, exc_type, exc_val, exc_tb): from kivy.core.window import Window from kivy.animation import Animation from kivy.base import stopTouchApp from kivy.logger import LoggerHistory stopTouchApp() for anim in list(Animation._instances): anim._unregister() for child in Window.children[:]: Window.remove_widget(child) self._context.pop() self._context = None LoggerHistory.clear_history()
async def async_mainloop(self): from kivy.base import ExceptionManager, stopTouchApp while not self.quit and self.status == 'started': try: await self.async_idle() if self.window: self.window.mainloop() except BaseException as inst: # use exception manager first r = ExceptionManager.handle_exception(inst) if r == ExceptionManager.RAISE: stopTouchApp() raise else: pass
def exit_app(self): if platform == 'android': # go to home from jnius import autoclass Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') theActivity = PythonActivity.mActivity # Switch to home screen to force our App to pause homeIntent = Intent(Intent.ACTION_MAIN) homeIntent.addCategory(Intent.CATEGORY_HOME) homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) theActivity.startActivity(homeIntent) else: # Exit explicitly from kivy.base import stopTouchApp stopTouchApp()
async def wait_stop_app(self): if self.app is None: return from kivy.base import stopTouchApp, EventLoop stopTouchApp() await self.async_sleep(0) if EventLoop.status == 'idle': # it never started so don't wait to start return ts = time.perf_counter() while not self.app_has_stopped: await self.async_sleep(.1) if time.perf_counter() - ts >= 60: raise TimeoutError()
def mainloop(self): # don't known why, but pygame required a resize event # for opengl, before mainloop... window reinit ? #self.dispatch('on_resize', *self.size) while not EventLoop.quit and EventLoop.status == 'started': try: self._mainloop() except BaseException as inst: # use exception manager first r = ExceptionManager.handle_exception(inst) if r == ExceptionManager.RAISE: stopTouchApp() raise else: pass
async def async_runTouchApp(widget=None, slave=False): '''Identical to :func:`runTouchApp` but instead is a coroutine that can be run in an existing async event loop. .. versionadded:: 1.10.1 ''' from kivy.base import _runTouchApp_prepare, stopTouchApp, EventLoop _runTouchApp_prepare(widget=widget, slave=slave) # we are in a slave mode, don't do dispatching. if slave: return try: await EventLoop.async_mainloop() finally: stopTouchApp()
def on_keyboard(self, window, key, scancode, codepoint, modifier): if key in (8, 27) or key == Keyboard.keycodes['escape']: # Backspace or escape if self.screen_manager.current == 'main': stopTouchApp() else: self.go_main() if self.experiment_layout.experiment is not None: if key == Keyboard.keycodes['p']: # P if self.experiment_layout.play_button.state == 'down': self.experiment_layout.play_button.state = 'normal' else: self.experiment_layout.play_button.state = 'down' if key == 114: # R self.experiment_layout.reset() if key in (282, 319, 9): self.experiment_layout.toggle_tabs() return True
def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'escape': base.stopTouchApp() elif keycode[1] == 'd': self.set_mode('insert') elif keycode[1] == 's': self.set_mode('select') elif keycode[1] == 'w': self.set_item('atom') elif keycode[1] == 'e': self.set_item('ellipse') elif keycode[1] == 'r': self.set_item('rectangle') elif keycode[1] == 'p': self.active_graph.show_tree(0) elif keycode[1] == 'o': self.view_symbolic_formula() elif keycode[1] == 'n': self.show_gringo_query() elif keycode[1] == 'g': self.show_save() elif keycode[1] == 'l': self.show_load() elif keycode[1] == 'y': print self.name_manager.get_all() print asp.Line.get_all_lines() elif keycode[1] == 't': self.toggle_sidepanel() elif keycode[1] == 'tab': if not self.show_sidepanel: self.toggle_sidepanel() self.ids.atom_input.focus = True elif keycode[1] == '.': if DEBUG: rb = refbrowser.InteractiveBrowser(self) rb.main() # self.all_objects = muppy.get_objects() # sum1 = summary.summarize(self.all_objects) # summary.print_(sum1) # self.tracker.create_snapshot() # self.tracker.stats.print_summary() return True
def on_keyboard(self, window, key, scancode, codepoint, modifier): if key in ( 8, 27 ) or key == Keyboard.keycodes['escape']: # Backspace or escape if self.screen_manager.current == 'main': stopTouchApp() else: self.go_main() if self.experiment_layout.experiment is not None: if key == Keyboard.keycodes['p']: # P if self.experiment_layout.play_button.state == 'down': self.experiment_layout.play_button.state = 'normal' else: self.experiment_layout.play_button.state = 'down' if key == 114: # R self.experiment_layout.reset() if key in (282, 319, 9): self.experiment_layout.toggle_tabs() return True
def on_keyboard(self, key, scancode=None, codepoint=None, modifier=None, **kwargs): '''Event called when keyboard is used. .. warning:: Some providers may omit `scancode`, `codepoint` and/or `modifier`! ''' if 'unicode' in kwargs: Logger.warning("The use of the unicode parameter is deprecated, " "and will be removed in future versions. Use " "codepoint instead, which has identical " "semantics.") # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w # TODO If just CMD+w is pressed, only the window should be closed. is_osx = platform == 'darwin' if self.on_keyboard.exit_on_escape: if key == 27 or all([is_osx, key in [113, 119], modifier == 1024]): stopTouchApp() self.close() return True
async def async_runTouchApp(widget=None, slave=False, async_lib=None): '''Identical to :func:`runTouchApp` but instead it is a coroutine that can be run in an existing async event loop. ``async_lib`` is the async library to use. See :mod:`kivy.app` for details and example usage. .. versionadded:: 2.0.0 ''' if async_lib is not None: Clock.init_async_lib(async_lib) _runTouchApp_prepare(widget=widget, slave=slave) # we are in a slave mode, don't do dispatching. if slave: return try: await EventLoop.async_mainloop() finally: stopTouchApp()
def _event_filter(self, action, *largs): from kivy.app import App if action == 'app_terminating': EventLoop.quit = True elif action == 'app_lowmemory': self.dispatch('on_memorywarning') elif action == 'app_willenterbackground': from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, exit.') stopTouchApp() return 0 if not app.dispatch('on_pause'): Logger.info( 'WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return 0 self._pause_loop = True elif action == 'app_didenterforeground': # on iOS, the did enter foreground is launched at the start # of the application. in our case, we want it only when the app # is resumed if self._pause_loop: self._pause_loop = False app = App.get_running_app() app.dispatch('on_resume') elif action == 'windowresized': self._size = largs self._win.resize_window(*self._size) # Force kivy to render the frame now, so that the canvas is drawn. EventLoop.idle() return 0
def on_keyboard(self, key, scancode=None, codepoint=None, modifier=None, **kwargs): '''Event called when keyboard is used. .. warning:: Some providers may omit `scancode`, `codepoint` and/or `modifier`! ''' if 'unicode' in kwargs: Logger.warning("The use of the unicode parameter is deprecated, " "and will be removed in future versions. Use " "codepoint instead, which has identical " "semantics.") # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w # TODO If just CMD+w is pressed, only the window should be closed. is_osx = platform == 'darwin' if WindowBase.on_keyboard.exit_on_escape: if key == 27 or all([is_osx, key in [113, 119], modifier == 1024]): if not self.dispatch('on_request_close', source='keyboard'): stopTouchApp() self.close() return True
def runTouchApp(widget=None, slave=False): '''Static main function that starts the application loop. You can access some magic via the following arguments: See :mod:`kivy.app` for example usage. :Parameters: `<empty>` To make dispatching work, you need at least one input listener. If not, application will leave. (MTWindow act as an input listener) `widget` If you pass only a widget, a MTWindow will be created and your widget will be added to the window as the root widget. `slave` No event dispatching is done. This will be your job. `widget + slave` No event dispatching is done. This will be your job but we try to get the window (must be created by you beforehand) and add the widget to it. Very useful for embedding Kivy in another toolkit. (like Qt, check kivy-designed) ''' _runTouchApp_prepare(widget=widget, slave=slave) # we are in a slave mode, don't do dispatching. if slave: return try: EventLoop.mainloop() finally: stopTouchApp()
def do_pause(self): # should go to app pause mode. from kivy.app import App from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, exit.') stopTouchApp() return #print 'dispatch app on_pause' if not app.dispatch('on_pause'): Logger.info('WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return # XXX FIXME wait for sdl resume while True: event = sdl.poll() if event is False: continue if event is None: continue #print 'sdl received', event action, args = event[0], event[1:] if action == 'quit': EventLoop.quit = True self.close() break elif action == 'windowrestored': #print 'app goes live again!' break #print 'dispatch app on_resume' app.dispatch('on_resume')
def do_pause(self): # should go to app pause mode. from kivy.app import App from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info("WindowSDL: No running App found, exit.") stopTouchApp() return if not app.dispatch("on_pause"): Logger.info("WindowSDL: App doesn't support pause mode, stop.") stopTouchApp() return # XXX FIXME wait for sdl resume while True: event = sdl.poll() if event is False: continue if event is None: continue # print 'sdl received', event action, args = event[0], event[1:] if action == "quit": EventLoop.quit = True self.close() break elif action == "windowrestored": # print 'app goes live again!' break # print 'dispatch app on_resume' app.dispatch("on_resume")
def stopTouchApp(): '''Stop the current application by leaving the main loop. See :mod:`kivy.app` for example usage. ''' if EventLoop is None: return if EventLoop.status in ('stopped', 'closed'): return if EventLoop.status != 'started': if not EventLoop.stopping: EventLoop.stopping = True Clock.schedule_once(lambda dt: stopTouchApp(), 0) return Logger.info('Base: Leaving application in progress...') EventLoop.close()
def test_video_unload(self): # fix issue https://github.com/kivy/kivy/issues/2275 # AttributeError: 'NoneType' object has no attribute 'texture' from kivy.uix.video import Video from kivy.clock import Clock from kivy.base import runTouchApp, stopTouchApp from os.path import join, dirname here = dirname(__file__) source = join(here, "..", "..", "examples", "widgets", "softboy.avi") video = Video(source=source, play=True) Clock.schedule_once(lambda x: stopTouchApp(), 1) def unload_video(video, position): if position > 0.01: video.unload() Clock.schedule_once(lambda x: stopTouchApp(), 0.1) video.bind(position=unload_video) runTouchApp(video)
def android_check_pause(*largs): # do nothing until android asks for it. if not android.check_pause(): return from kivy.app import App from kivy.base import stopTouchApp from kivy.logger import Logger from kivy.core.window import Window global g_android_redraw_count, _redraw_event # try to get the current running application Logger.info('Android: Must go into sleep mode, check the app') app = App.get_running_app() # no running application, stop our loop. if app is None: Logger.info('Android: No app running, stop everything.') stopTouchApp() return # try to go to pause mode if app.dispatch('on_pause'): Logger.info('Android: App paused, now wait for resume.') # app goes in pause mode, wait. android.wait_for_resume() # is it a stop or resume ? if android.check_stop(): # app must stop Logger.info('Android: Android wants to close our app.') stopTouchApp() else: # app resuming now ! Logger.info('Android: Android has resumed, resume the app.') app.dispatch('on_resume') Window.canvas.ask_update() g_android_redraw_count = 25 # 5 frames/seconds for 5 seconds if _redraw_event is None: _redraw_event = Clock.schedule_interval( _android_ask_redraw, 1 / 5) else: _redraw_event.cancel() _redraw_event() Logger.info('Android: App resume completed.') # app doesn't support pause mode, just stop it. else: Logger.info('Android: App doesn\'t support pause mode, stop.') stopTouchApp()
def test_video_unload(self): # fix issue https://github.com/kivy/kivy/issues/2275 # AttributeError: 'NoneType' object has no attribute 'texture' from kivy.uix.video import Video from kivy.clock import Clock from kivy.base import runTouchApp, stopTouchApp from kivy import kivy_examples_dir from os.path import join, dirname, abspath source = abspath(join(kivy_examples_dir, "widgets", "cityCC0.mpg")) video = Video(source=source, play=True) Clock.schedule_once(lambda x: stopTouchApp(), 1) def unload_video(video, position): if position > 0.01: video.unload() Clock.schedule_once(lambda x: stopTouchApp(), 0.1) video.bind(position=unload_video) runTouchApp(video)
def main(): config = "DEBUG" if __debug__ else "RELEASE" debuggable_widget = DebuggableWidget() # We cannot use asserts here since we will run this with -O in tests. for attribute in ["debug_text", "color_rgba", "background_rgba"]: if hasattr(debuggable_widget, attribute) != __debug__: raise Exception("%s should %sbe present in %s mode." % ( attribute, "not " if __debug__ else "", config)) # Test that code that uses DebuggableWidgets does not crash in RELEASE mode. debuggable_widget.debug_text = "DebugText" debuggable_widget.color_rgba = 1, 0, 0, 1 debuggable_widget.background_rgba = 0, 0.3, 0, 1 Clock.schedule_once(lambda _: stopTouchApp(), 1) runTouchApp(debuggable_widget) print("SUCCESS")
def android_check_pause(*largs): # do nothing until android ask for it. if not android.check_pause(): return from kivy.app import App from kivy.base import stopTouchApp from kivy.logger import Logger from kivy.core.window import Window # try to get the current running application Logger.info('Android: Must to in sleep mode, check the app') app = App.get_running_app() # no running application, stop our loop. if app is None: Logger.info('Android: No app running, stop everything.') stopTouchApp() return # try to go to pause mode if app.dispatch('on_pause'): Logger.info('Android: App paused, now wait for resume.') # app goes in pause mode, wait. android.wait_for_resume() # is it a stop or resume ? if android.check_stop(): # app must stop Logger.info('Android: Android want to close our app.') stopTouchApp() else: # app resuming now ! Logger.info('Android: Android resumed, resume the app') app.dispatch('on_resume') Window.canvas.ask_update() Logger.info('Android: App resume completed.') # app don't support pause mode, just stop it. else: Logger.info('Android: App doesn\'t support pause mode, stop.') stopTouchApp()
def on_key_down(self, src, key, scancode, char, mods): from kivy.base import stopTouchApp if is_quit_key(char, mods): stopTouchApp() elif char == ',' and 'meta' in mods: self.show_settings()
def next(self): stopTouchApp()
def unload_video(video, position): if position > 0.01: video.unload() Clock.schedule_once(lambda x: stopTouchApp(), 0.1)
def exit(self): stopTouchApp()
def stop_peaky(exit_code=0): stopTouchApp() try: exit(exit_code) except: pass
async def kivy_app(request, nursery): gc.collect() if apps: last_app, last_request = apps.pop() assert last_app() is None, \ 'Memory leak: failed to release app for test ' + repr(last_request) from os import environ environ['KIVY_USE_DEFAULTCONFIG'] = '1' # force window size + remove all inputs from kivy.config import Config Config.set('graphics', 'width', '320') Config.set('graphics', 'height', '240') for items in Config.items('input'): Config.remove_option('input', items[0]) from kivy.core.window import Window from kivy.context import Context from kivy.clock import ClockBase from kivy.factory import FactoryBase, Factory from kivy.app import App from kivy.lang.builder import BuilderBase, Builder from kivy.base import stopTouchApp from kivy import kivy_data_dir from kivy.logger import LoggerHistory kivy_eventloop = environ.get('KIVY_EVENTLOOP', 'asyncio') if kivy_eventloop == 'asyncio': pytest.importorskip( 'pytest_asyncio', reason='KIVY_EVENTLOOP == "asyncio" but ' '"pytest_asyncio" is not installed') async_lib = 'asyncio' elif kivy_eventloop == 'trio': pytest.importorskip( 'pytest_trio', reason='KIVY_EVENTLOOP == "trio" but ' '"pytest_trio" is not installed') async_lib = 'trio' else: pytest.skip( 'KIVY_EVENTLOOP must be set to either of "asyncio" or ' '"trio" to run async tests') context = Context(init=False) context['Clock'] = ClockBase(async_lib=async_lib) # have to make sure all global kv files are loaded before this because # globally read kv files (e.g. on module import) will not be loaded again # in the new builder, except if manually loaded, which we don't do context['Factory'] = FactoryBase.create_from(Factory) context['Builder'] = BuilderBase.create_from(Builder) context.push() Window.create_window() Window.register() Window.initialized = True Window.canvas.clear() app = request.param[0]() app.set_async_lib(async_lib) if async_lib == 'asyncio': import asyncio loop = asyncio.get_event_loop() loop.create_task(app.async_run()) else: nursery.start_soon(app.async_run) from kivy.clock import Clock Clock._max_fps = 0 ts = time.perf_counter() while not app.app_has_started: await app.async_sleep(.1) if time.perf_counter() - ts >= 10: raise TimeoutError() await app.wait_clock_frames(5) yield app stopTouchApp() ts = time.perf_counter() while not app.app_has_stopped: await app.async_sleep(.1) if time.perf_counter() - ts >= 10: raise TimeoutError() for child in Window.children[:]: Window.remove_widget(child) context.pop() # release all the resources del context LoggerHistory.clear_history() apps.append((weakref.ref(app), request)) del app gc.collect()
def on_keyboard(self, key, scancode=None, unicode=None): if key == 27: stopTouchApp() self.close() #not sure what to do here return True super(WindowPygame, self).on_keyboard(key, scancode, unicode)
def _on_close(self, instance, *largs): stopTouchApp()
def android_check_pause(*largs): if not android.check_pause(): return from kivy.base import stopTouchApp stopTouchApp()