def inner(*args): #Here is hould loop on the template to apply them on values from kivy.base import EventLoop EventLoop.idle() pim = tmpl.toPILImage(for_print = True).rotate(90) pm.setImage(pim) self.stack.add_widget(pm)
def submitGUI(self): """ Submit the GUI Get all settings, confirm they are valid, save new settings file """ # Error check all GUI settings errorCheckPassed = self.check_GUI_settings() # write GUI settings to file if errorCheckPassed: # Convery the GUI_settings from kivy dictproperty to a regular ol' # python dict allSettings = {} for k in self.GUI_settings.keys(): allSettings[k] = self.GUI_settings[k] # write the settings as the new config yaml file with open(createMaskConfigFile, 'w') as outputFile: yaml.dump(allSettings, outputFile, default_flow_style=False) # Close the GUI global submitButtonPressed submitButtonPressed = True App.get_running_app().stop() EventLoop.exit()
def probe(self): inputs = get_inputs(self.input_path) inputs = [x for x in inputs if x.has_capability(ABS_MT_POSITION_X)] for device in inputs: Logger.info('ProbeSysfs: found device: %s at %s' % ( device.name, device.device)) # must ignore ? if self.match: if not match(self.match, device.name, IGNORECASE): Logger.warning('ProbeSysfs: device not match the' ' rule in config, ignoring.') continue d = device.device devicename = self.device % dict(name=d.split(sep)[-1]) provider = MotionEventFactory.get(self.provider) if provider is None: Logger.info('ProbeSysfs: unable to found provider %s' % self.provider) Logger.info('ProbeSysfs: fallback on hidinput') provider = MotionEventFactory.get('hidinput') if provider is None: Logger.critical('ProbeSysfs: no input provider found' ' to handle this device !') continue instance = provider(devicename, '%s,%s' % (device.device, ','.join(self.args))) if instance: from kivy.base import EventLoop EventLoop.add_input_provider(instance)
def __init__(self, cache_dir='cache', **kwargs): from kivy.base import EventLoop EventLoop.ensure_window() CACHE['directory'] = cache_dir self._invalid_scale = True self._tiles = [] self._tiles_bg = [] self._tilemap = {} self._layers = [] self._default_marker_layer = None self._need_redraw_all = False self._transform_lock = False self.trigger_update(True) self.canvas = Canvas() self._scatter = MapViewScatter() self.add_widget(self._scatter) with self._scatter.canvas: self.canvas_map = Canvas() self.canvas_layers = Canvas() with self.canvas: self.canvas_layers_out = Canvas() self._scale_target_anim = False self._scale_target = 1. self._touch_count = 0 Clock.schedule_interval(self._animate_color, 1 / 60.) self.lat = kwargs.get("lat", self.lat) self.lon = kwargs.get("lon", self.lon) super(MapView, self).__init__(**kwargs)
def __init__(self,parent,**kwargs): from kivy.base import EventLoop self.result=None dlg = MessageBox(parent,**kwargs) while (dlg) and (self.result is None): EventLoop.idle() return self.result
def on_play(self, instance, value): if not value: Logger.info('Recorder: Stop playing %r' % self.filename) EventLoop.remove_input_provider(self) return if not exists(self.filename): Logger.error('Recorder: Unable to found %r file, play aborted.' % ( self.filename)) return with open(self.filename, 'r') as fd: data = fd.read().splitlines() if len(data) < 2: Logger.error('Recorder: Unable to play %r, file truncated.' % ( self.filename)) return if data[0] != '#RECORDER1.0': Logger.error('Recorder: Unable to play %r, invalid header.' % ( self.filename)) return # decompile data self.play_data = [literal_eval(x) for x in data[1:]] self.play_time = time() self.play_me = {} Logger.info('Recorder: Start playing %d events from %r' % (len(self.play_data), self.filename)) EventLoop.add_input_provider(self)
def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # assign the default context of the widget creation if not hasattr(self, '_context'): self._context = get_current_context() super(Widget, self).__init__(**kwargs) # Create the default canvas if not exist if self.canvas is None: self.canvas = Canvas(opacity=self.opacity) # Apply all the styles if '__no_builder' not in kwargs: #current_root = Builder.idmap.get('root') #Builder.idmap['root'] = self Builder.apply(self) #if current_root is not None: # Builder.idmap['root'] = current_root #else: # Builder.idmap.pop('root') # Bind all the events for argument in kwargs: if argument[:3] == 'on_': self.bind(**{argument: kwargs[argument]})
def __init__(self, **kwargs): super(Widget, self).__init__() # Register touch events self.register_event_type('on_touch_down') self.register_event_type('on_touch_move') self.register_event_type('on_touch_up') # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # Auto bind on own handler if exist properties = self.__properties.keys() for func in dir(self): if not func.startswith('on_'): continue name = func[3:] if name in properties: self.bind(**{name: getattr(self, func)}) # Create the default canvas self.canvas = Canvas() # Apply the existing arguments to our widget for key, value in kwargs.iteritems(): if hasattr(self, key): setattr(self, key, value) # Apply all the styles if '__no_builder' not in kwargs: Builder.apply(self)
def build(self): EventLoop.ensure_window() self.window = EventLoop.window self.root = FloatLayout() self.screens = {} self.screens['menu'] = MenuScreen(self) self.open_screen('menu')
def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # Assign the default context of the widget creation. if not hasattr(self, '_context'): self._context = get_current_context() no_builder = '__no_builder' in kwargs if no_builder: del kwargs['__no_builder'] on_args = {k: v for k, v in kwargs.items() if k[:3] == 'on_'} for key in on_args: del kwargs[key] super(Widget, self).__init__(**kwargs) # Create the default canvas if it does not exist. if self.canvas is None: self.canvas = Canvas(opacity=self.opacity) # Apply all the styles. if not no_builder: #current_root = Builder.idmap.get('root') #Builder.idmap['root'] = self Builder.apply(self) #if current_root is not None: # Builder.idmap['root'] = current_root #else: # Builder.idmap.pop('root') # Bind all the events. if on_args: self.bind(**on_args)
def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # Assign the default context of the widget creation. if not hasattr(self, '_context'): self._context = get_current_context() no_builder = '__no_builder' in kwargs self._disabled_value = False if no_builder: del kwargs['__no_builder'] on_args = {k: v for k, v in kwargs.items() if k[:3] == 'on_'} for key in on_args: del kwargs[key] self._disabled_count = 0 super(Widget, self).__init__(**kwargs) # Create the default canvas if it does not exist. if self.canvas is None: self.canvas = Canvas(opacity=self.opacity) # Apply all the styles. if not no_builder: Builder.apply(self, ignored_consts=self._kwargs_applied_init) # Bind all the events. if on_args: self.bind(**on_args)
def __init__(self, **kwargs): # Make sure opengl context exists EventLoop.ensure_window() self.canvas = RenderContext(use_parent_projection=True, use_parent_modelview=True) with self.canvas: self.fbo = Fbo(size=self.size) with self.fbo.before: PushMatrix() with self.fbo: ClearColor(0, 0, 0, 0) ClearBuffers() self._background_color = Color(*self.background_color) self.fbo_rectangle = Rectangle(size=self.size) with self.fbo.after: PopMatrix() super(EffectWidget, self).__init__(**kwargs) Clock.schedule_interval(self._update_glsl, 0) self.bind(size=self.refresh_fbo_setup, effects=self.refresh_fbo_setup, background_color=self._refresh_background_color) self.refresh_fbo_setup() self._refresh_background_color() # In case thi was changed in kwargs
def build(self): from kivy.base import EventLoop EventLoop.ensure_window() self.window = EventLoop.window self.root = TestWidget()
def inner(*args): #Here is hould loop on the template to apply them on values from kivy.base import EventLoop EventLoop.idle() cim = tmpl.toImage() cim.texture.flip_vertical() self.ids['img'].texture = cim.texture
def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # Register touch events self.register_event_type('on_touch_down') self.register_event_type('on_touch_move') self.register_event_type('on_touch_up') super(Widget, self).__init__(**kwargs) # Create the default canvas if not exist if self.canvas is None: self.canvas = Canvas() # Apply all the styles if '__no_builder' not in kwargs: #current_root = Builder.idmap.get('root') #Builder.idmap['root'] = self Builder.apply(self) #if current_root is not None: # Builder.idmap['root'] = current_root #else: # Builder.idmap.pop('root') # Bind all the events for argument, value in kwargs.items(): if argument.startswith('on_'): self.bind(**{argument: value})
def _mainloop(self): EventLoop.idle() for event in pygame.event.get(): # kill application (SIG_TERM) if event.type == pygame.QUIT: EventLoop.quit = True self.close() # mouse move elif event.type == pygame.MOUSEMOTION: # don't dispatch motion if no button are pressed if event.buttons == (0, 0, 0): continue x, y = event.pos self.dispatch('on_mouse_move', x, y, self.modifiers) # mouse action elif event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP): self._pygame_update_modifiers() x, y = event.pos btn = 'left' if event.button == 3: btn = 'right' elif event.button == 2: btn = 'middle' eventname = 'on_mouse_down' if event.type == pygame.MOUSEBUTTONUP: eventname = 'on_mouse_up' self.dispatch(eventname, x, y, btn, self.modifiers) # keyboard action elif event.type in (pygame.KEYDOWN, pygame.KEYUP): self._pygame_update_modifiers(event.mod) # atm, don't handle keyup if event.type == pygame.KEYUP: self.dispatch('on_key_up', event.key, event.scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', event.key, event.scancode, event.unicode): continue self.dispatch('on_keyboard', event.key, event.scancode, event.unicode) # video resize elif event.type == pygame.VIDEORESIZE: pass # ignored event elif event.type in (pygame.ACTIVEEVENT, pygame.VIDEOEXPOSE): pass # unhandled event ! else: Logger.debug('WinPygame: Unhandled event %s' % str(event))
def submitGUI(self): """ Submit the GUI Get all settings, confirm they are valid, save new settings file """ ## Error Check All GUI SETTINGS errorCheckPassed = self.check_GUI_settings() # write GUI settings to file if errorCheckPassed: # Convery the GUI_settings from kivy dictproperty to a regular ol' # python dict (and do some reformatting along the way) allSettings = {} for k in self.GUI_settings.keys(): # convert text inputs to integers if k in ['pynealScannerPort', 'resultsServerPort', 'numTimepts']: allSettings[k] = int(self.GUI_settings[k]) else: allSettings[k] = self.GUI_settings[k] # write the settings as the new config yaml file with open(setupConfigFile, 'w') as outputFile: yaml.dump(allSettings, outputFile, default_flow_style=False) # Close the GUI global submitButtonPressed submitButtonPressed = True App.get_running_app().stop() EventLoop.exit()
def build(self): self.load_sounds() self.highscore_fn = join(self.user_data_dir, 'highscore.dat') from kivy.base import EventLoop EventLoop.ensure_window() # load textures for fn in ('gem', 'gem_selected', 't5', 't10', 'tarea', 'tline', 'star'): texture = CoreImage(join('data', '{}.png'.format(fn)), mipmap=True).texture self.textures[fn] = texture self.root = ScreenManager(transition=SlideTransition()) self.bind(score_combo=self.check_game_over, timer=self.check_game_over, timer_next=self.check_game_over) self.ui_jewel = JewelUI(name='jewel') self.root.add_widget(self.ui_jewel) self.start() Clock.schedule_interval(self.update_time, 1 / 20.) #Clock.schedule_interval(self._stats, 1 / 60.) #self._stats() # load highscores if not exists(self.highscore_fn): return try: with open(self.highscore_fn) as fd: version, highscores = json.load(fd) if version == HIGHSCORE_VERSION: self.highscores = highscores except: pass
def __init__(self, **kwargs): # Make sure opengl context exists EventLoop.ensure_window() self.canvas = RenderContext(use_parent_projection=True, use_parent_modelview=True) with self.canvas: self.fbo = Fbo(size=self.size) with self.fbo.before: PushMatrix() self.fbo_translation = Translate(-self.x, -self.y, 0) with self.fbo: Color(*self.background_color) self.fbo_rectangle = Rectangle(size=self.size) with self.fbo.after: PopMatrix() super(EffectWidget, self).__init__(**kwargs) Clock.schedule_interval(self._update_glsl, 0) self.bind(pos=self._update_translation, size=self.refresh_fbo_setup, effects=self.refresh_fbo_setup) self.refresh_fbo_setup()
def test_scrollbar_both_margin(self): EventLoop.ensure_window() win = EventLoop.window grid = TestGrid() scroll = TestScrollbarBothMargin() margin = scroll.bar_margin scroll.add_widget(grid) win.add_widget(scroll) # get widgets ready EventLoop.idle() left, right = scroll.to_window(scroll.x, scroll.right) bottom, top = scroll.to_window(scroll.y, scroll.top) # touch in the half of the bar m = margin + scroll.bar_width / 2.0 points = [ [left, bottom + m, right, bottom + m, 'bottom', 'right', False], [left, top - m, right, top - m, 'top', 'right', False], [right - m, top, right - m, bottom, 'bottom', 'right', False], [left + m, top, left + m, bottom, 'bottom', 'left', False], [left, bottom, right, bottom, 'bottom', 'right', True], [left, top, right, top, 'top', 'right', True], [right, top, right, bottom, 'bottom', 'right', True], [left, top, left, bottom, 'bottom', 'left', True] ] self.process_points(scroll, points) self.render(scroll)
def PopupOk(text, title='', btn_text='Continue', input=None, callback=None): btnclose = Button(text=btn_text, size_hint_y=None, height='50sp') content = BoxLayout(orientation='vertical') p = Popup(title=title, content=content, size=('300dp', '300dp'), size_hint=(None, None), pos_hint={'top':.95}) content.add_widget(Label(text=text)) if input is not None: assert callback is not None ti = TextInput(height='50sp', font_size='30sp', input_type=input, multiline=False, size_hint_y = None, focus=True) content.add_widget(ti) def _callback(*args): try: ti.hide_keyboard() except AttributeError: # On a real computer, not the phone pass if ti.text == '': callback(None) else: callback(ti.text) p.bind(on_dismiss=_callback) p.is_visable = True content.add_widget(btnclose) btnclose.bind(on_release=p.dismiss) p.open() if input is not None: while not p.is_visable: EventLoop.idle() return ti.text
def dpi(self): '''Return the DPI of the screen. Depending on the platform, the DPI can be taken from the Window provider (Desktop mainly) or from a platform-specific module (like android/ios). ''' custom_dpi = environ.get('KIVY_DPI') if custom_dpi: return float(custom_dpi) if platform == 'android': if USE_SDL2: import jnius Hardware = jnius.autoclass('org.renpy.android.Hardware') return Hardware.getDPI() else: import android return android.get_dpi() elif platform == 'ios': import ios return ios.get_dpi() # for all other platforms.. from kivy.base import EventLoop EventLoop.ensure_window() return EventLoop.window.dpi
def build(self): self.sound = {} self.title = 'DB Shooter' from kivy.base import EventLoop EventLoop.ensure_window() self.window = EventLoop.window # start the background music: self.music = SoundLoader.load('sound/background.mp3') self.music.volume = self.config.getint('General', 'Music') / 100.0 self.music.bind(on_stop=self.replaySound) self.music.play() # create the root widget and give it a reference of the view / application instance self.MyViewController = MyViewController(app=self) self.root = self.MyViewController.view # load all other sounds: self.sound['pop'] = SoundLoader.load('sound/pop.mp3') self.sound['popping'] = SoundLoader.load('sound/popping.mp3') self.sound['swoosh'] = SoundLoader.load('sound/swoosh.mp3') sound_volume = self.config.getint('General', 'Sound') / 100.0 for item in self.sound: self.sound[item].volume = sound_volume # if the user started the game the first time, display quick start guide if self.config.get('General', 'FirstStartup') == 'Yes': Clock.schedule_once(self.displayHelpScreen,0) self.config.set('General', 'FirstStartup', 'No') self.config.write()
def __init__(self, **kwargs): _init_berkelium() # Before doing anything, ensure the windows exist. EventLoop.ensure_window() EventLoop.window.bind(on_keyboard=self.on_window_keyboard) self._touches = [] self._bk = _WindowDelegate(self, self.width, self.height, self.transparency) self.register_event_type('on_start_loading') self.register_event_type('on_load') self.register_event_type('on_crashed_worker') self.register_event_type('on_crashed_plugin') self.register_event_type('on_provisional_load_error') self.register_event_type('on_console_message') self.register_event_type('on_script_alert') self.register_event_type('on_navigation_requested') self.register_event_type('on_created_window') self.register_event_type('on_widget_created') self.register_event_type('on_widget_destroyed') self.register_event_type('on_widget_resize') self.register_event_type('on_widget_move') self.register_event_type('on_widget_paint') self.register_event_type('on_paint') super(Webbrowser, self).__init__(**kwargs) if self.url is not None: self.open_url(self.url) with self.canvas: self._g_color = Color(1, 1, 1) self._g_rect = Rectangle(texture=self._bk.texture, size=self.size) self._g_rect.tex_coords = (0, 1, 1, 1, 1, 0, 0, 0) _install_berkelium_update(self)
def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() EventLoop.window.bind(on_keyboard=self.on_widget_keyboard) super(WebbrowserChildWidget, self).__init__(**kwargs) self._id = 0
def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # Register touch events self.register_event_type("on_touch_down") self.register_event_type("on_touch_move") self.register_event_type("on_touch_up") super(Widget, self).__init__(**kwargs) # Create the default canvas if not exist if self.canvas is None: self.canvas = Canvas(opacity=self.opacity) # Apply all the styles if "__no_builder" not in kwargs: # current_root = Builder.idmap.get('root') # Builder.idmap['root'] = self Builder.apply(self) # if current_root is not None: # Builder.idmap['root'] = current_root # else: # Builder.idmap.pop('root') # Bind all the events for argument in kwargs: if argument[:3] == "on_": self.bind(**{argument: kwargs[argument]})
def test_widget_button(self, *args): EventLoop.ensure_window() self._win = EventLoop.window self.clean_garbage() # build the widget tree & add Window as the main EL self.root = self.builder.Builder.load_string( KV, filename="InspectorTestCase.KV") self.render(self.root) self.assertLess(len(self._win.children), 2) # checked widget highlight = self.root.ids.highlight highlight_exp = self.root.ids.highlight.text # activate inspector with root as ctx inspector.start(self._win, self.root) self.advance_frames(2) # pull the Inspector drawer from bottom ins = self.root.inspector ins.activated = True ins.inspect_enabled = True self.assertTrue(ins.at_bottom) # touch button center touch = UnitTestTouch(*highlight.center) touch.touch_down() touch.touch_up() # open Inspector properties ins.show_widget_info() self.advance_frames(2) # check if the button is selected # stored instance self.assertEqual(ins.widget.text, highlight_exp) # data in properties for node in ins.treeview.iterate_all_nodes(): lkey = getattr(node.ids, 'lkey', None) if not lkey: continue if lkey.text == 'text': ltext = node.ids.ltext # slice because the string is displayed with quotes self.assertEqual(ltext.text[1:-1], highlight_exp) break # close Inspector ins.inspect_enabled = False ins.activated = False self.render(self.root) self.advance_frames(1) # stop Inspector completely inspector.stop(self._win, self.root) self.assertLess(len(self._win.children), 2) self.render(self.root)
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # setup ! w, h = self._size resizable = Config.getboolean('graphics', 'resizable') gl_size = self._win.setup_window(pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable) # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) else: w, h = self._size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() # auto add input provider Logger.info('Window: auto add sdl input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')
def on_event_loop_start(self, *args, **kwargs): EventLoop.unbind(on_start=self.on_event_loop_start) if self._init_complete: return if self.size == [1, 1]: return self._init_complete = True self.build_nodes()
def add_item(self, qt, verso): from os.path import relpath stack = App.get_running_app().root.ids['deck'].ids['stack'] ########################################################## qt = int(qt) if self.is_all_folder: #print self, self.source, self.name, self.is_all_folder #It is a folder, add all the imge from folder for name in [x for x in os.listdir(self.is_all_folder) if x.endswith(FILE_FILTER)]: ##for fiv in self.parent.children: ##if fiv.is_all_folder: continue if name.endswith(('.csv','.xlsx')): continue box = StackPart() #box.name = fiv.name box.name = name box.source = os.path.join(self.is_all_folder, name) box.qt = qt box.verso = verso if name.endswith('.kv'): if self.is_all_folder.startswith(gamepath): fold = relpath(self.is_all_folder, gamepath) else: fold = self.is_all_folder box.template = "@%s"%os.path.join(fold, name) box.realise() stack.add_widget(box) from kivy.base import EventLoop EventLoop.idle() elif self.name.endswith('.csv'): App.get_running_app().root.ids.deck.load_file_csv(self.name) elif self.name.endswith('.xlsx'): App.get_running_app().root.ids.deck.load_file(self.name) elif self.name.endswith('.bgp'): self.extract_package() elif self.name.endswith('.py'): print 'should be executing', self.name, self.source, self.is_all_folder from imp import load_source Logger.info('Executing PYScript file %s'%self.name) m = self.name load_source(m[:-3],m) else: box = StackPart() box.name = self.name box.source = self.source box.qt = qt box.verso = verso stack.add_widget(box) if self.name.endswith('.kv'): box.tmplWidget = self.tmplWidget if self.name.startswith(gamepath): fold = relpath(self.name, gamepath) else: fold = self.name box.template = "@%s"%fold box.realise()
import os import unittest import mock from kivy.base import EventLoop from kivy.core.image import Image from zbarcam import ZBarCam FIXTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures') # https://github.com/kivy/kivy/blob/1.10.1/doc/sources/faq.rst EventLoop.ensure_window() class TestZBarCam(unittest.TestCase): def setUp(self): with mock.patch('kivy.uix.anchorlayout.AnchorLayout.__init__'): self.zbarcam = ZBarCam() def test_detect_qrcode_frame_no_qrcode(self): """ Checks `_detect_qrcode_frame()` returns empty list on no qrcode. """ fixture_path = os.path.join(FIXTURE_DIR, 'no_qr_code.png') texture = Image(fixture_path).texture code_types = self.zbarcam.code_types symbols = self.zbarcam._detect_qrcode_frame(texture, code_types) self.assertEqual(symbols, []) def test_detect_qrcode_frame_one_qrcode(self):
def _mainloop(self): EventLoop.idle()
def on_window_flip(self, window): '''Internal method to be called when the window have just displayed an image. When an image is showed, we decrement our framecount. If framecount is come to 0, we are taking the screenshot. The screenshot is done in a temporary place, and is compared to the original one -> test ok/ko. If no screenshot is available in the results directory, a new one will be created. ''' from kivy.base import EventLoop from tempfile import mkstemp from os.path import join, exists from os import unlink, close from shutil import move, copy # don't save screenshot until we have enough frames. #log.debug('framecount %d' % self.framecount) self.framecount -= 1 if self.framecount > 0: return reffn = None match = False try: # just get a temporary name fd, tmpfn = mkstemp(suffix='.png', prefix='kivyunit-') close(fd) unlink(tmpfn) # get a filename for the current unit test self.test_counter += 1 test_uid = '%s-%d.png' % ('_'.join( self.id().split('.')[-2:]), self.test_counter) # capture the screen log.info('Capturing screenshot for %s' % test_uid) tmpfn = window.screenshot(tmpfn) log.info('Capture saved at %s' % tmpfn) # search the file to compare to reffn = join(self.results_dir, test_uid) log.info('Compare with %s' % reffn) # get sourcecode import inspect frame = inspect.getouterframes(inspect.currentframe())[6] sourcecodetab, line = inspect.getsourcelines(frame[0]) line = frame[2] - line currentline = sourcecodetab[line] sourcecodetab[line] = '<span style="color: red;">%s</span>' % ( currentline) sourcecode = ''.join(sourcecodetab) sourcecodetab[line] = '>>>>>>>>\n%s<<<<<<<<\n' % currentline sourcecodeask = ''.join(sourcecodetab) if not exists(reffn): log.info('No image reference, move %s as ref ?' % test_uid) if self.interactive_ask_ref(sourcecodeask, tmpfn, self.id()): move(tmpfn, reffn) tmpfn = reffn log.info('Image used as reference') match = True else: log.info('Image discarded') else: import pygame s1 = pygame.image.load(tmpfn) s2 = pygame.image.load(reffn) sd1 = pygame.image.tostring(s1, 'RGB') sd2 = pygame.image.tostring(s2, 'RGB') if sd1 != sd2: log.critical('%s at render() #%d, images are different.' % (self.id(), self.test_counter)) if self.interactive_ask_diff(sourcecodeask, tmpfn, reffn, self.id()): log.critical('user ask to use it as ref.') move(tmpfn, reffn) tmpfn = reffn match = True else: self.test_failed = True else: match = True # generate html from os.path import join, dirname, exists, basename from os import mkdir build_dir = join(dirname(__file__), 'build') if not exists(build_dir): mkdir(build_dir) copy(reffn, join(build_dir, 'ref_%s' % basename(reffn))) if tmpfn != reffn: copy(tmpfn, join(build_dir, 'test_%s' % basename(reffn))) with open(join(build_dir, 'index.html'), 'at') as fd: color = '#ffdddd' if not match else '#ffffff' fd.write('<div style="background-color: %s">' % color) fd.write('<h2>%s #%d</h2>' % (self.id(), self.test_counter)) fd.write('<table><tr><th>Reference</th>' '<th>Test</th>' '<th>Comment</th>') fd.write('<tr><td><img src="ref_%s"/></td>' % basename(reffn)) if tmpfn != reffn: fd.write('<td><img src="test_%s"/></td>' % basename(reffn)) else: fd.write('<td>First time, no comparaison.</td>') fd.write('<td><pre>%s</pre></td>' % sourcecode) fd.write('</table></div>') finally: try: if reffn != tmpfn: unlink(tmpfn) except: pass EventLoop.stop()
def test_smooth_scroll_end(self): EventLoop.ensure_window() win = EventLoop.window grid = TestGrid() scroll = ScrollView(smooth_scroll_end=10) assert scroll.smooth_scroll_end == 10 scroll.add_widget(grid) # XXX this shouldn't be needed, but previous tests apparently # don't cleanup while win.children: win.remove_widget(win.children[0]) win.add_widget(scroll) # get widgets ready EventLoop.idle() e = scroll.effect_y assert e.velocity == 0 touch = UTMotionEvent( "unittest", next(touch_id), { "x": scroll.center_x / float(win.width), "y": scroll.center_y / float(win.height), }) touch.profile.append('button') touch.button = 'scrollup' EventLoop.post_dispatch_input("begin", touch) # EventLoop.post_dispatch_input("update", touch) assert e.velocity == 10 * scroll.scroll_wheel_distance EventLoop.idle() assert 0 < e.velocity < 10 * scroll.scroll_wheel_distance EventLoop.post_dispatch_input("end", touch) EventLoop.idle() assert 0 < e.velocity < 10 * scroll.scroll_wheel_distance # wait for velocity to die off while e.velocity: EventLoop.idle() touch = UTMotionEvent( "unittest", next(touch_id), { "x": scroll.center_x / float(win.width), "y": scroll.center_y / float(win.height), }) touch.profile.append('button') touch.button = 'scrolldown' EventLoop.post_dispatch_input("begin", touch) # EventLoop.post_dispatch_input("update", touch) assert e.velocity == -10 * scroll.scroll_wheel_distance EventLoop.idle() assert 0 > e.velocity > -10 * scroll.scroll_wheel_distance EventLoop.post_dispatch_input("end", touch) EventLoop.idle() assert 0 > e.velocity > -10 * scroll.scroll_wheel_distance
def build(self): EventLoop.ensure_window() return Game()
def doexit(self): global capture if capture != None: capture.release() capture = None EventLoop.close()
def move_frames(self, t): for i in range(t): EventLoop.idle()
def __init__(self, **kwargs): kwargs.setdefault('force', False) # don't init window 2 times, # except if force is specified if WindowBase.__instance is not None and not kwargs.get('force'): return self.initialized = False # create a trigger for update/create the window when one of window # property changes self.trigger_create_window = Clock.create_trigger( self.create_window, -1) # Create a trigger for updating the keyboard height self.trigger_keyboard_height = Clock.create_trigger( self._upd_kbd_height, .5) # set the default window parameter according to the configuration if 'fullscreen' not in kwargs: fullscreen = Config.get('graphics', 'fullscreen') if fullscreen not in ('auto', 'fake'): fullscreen = fullscreen.lower() in ('true', '1', 'yes', 'yup') kwargs['fullscreen'] = fullscreen if 'width' not in kwargs: kwargs['width'] = Config.getint('graphics', 'width') if 'height' not in kwargs: kwargs['height'] = Config.getint('graphics', 'height') if 'rotation' not in kwargs: kwargs['rotation'] = Config.getint('graphics', 'rotation') if 'position' not in kwargs: kwargs['position'] = Config.getdefault('graphics', 'position', 'auto') if 'top' in kwargs: kwargs['position'] = 'custom' kwargs['top'] = kwargs['top'] else: kwargs['top'] = Config.getint('graphics', 'top') if 'left' in kwargs: kwargs['position'] = 'custom' kwargs['left'] = kwargs['left'] else: kwargs['left'] = Config.getint('graphics', 'left') kwargs['_size'] = (kwargs.pop('width'), kwargs.pop('height')) super(WindowBase, self).__init__(**kwargs) # bind all the properties that need to recreate the window for prop in ('fullscreen', 'position', 'top', 'left', '_size', 'system_size'): self.bind(**{prop: self.trigger_create_window}) self.bind(size=self.trigger_keyboard_height, rotation=self.trigger_keyboard_height) self.bind(softinput_mode=lambda *dt: self.update_viewport(), keyboard_height=lambda *dt: self.update_viewport()) # init privates self._system_keyboard = Keyboard(window=self) self._keyboards = {'system': self._system_keyboard} self._vkeyboard_cls = None self.children = [] self.parent = self # before creating the window import kivy.core.gl # NOQA # configure the window self.create_window() # attach modules + listener event EventLoop.set_window(self) Modules.register_window(self) EventLoop.add_event_listener(self) # manage keyboard(s) self.configure_keyboards() # assign the default context of the widget creation if not hasattr(self, '_context'): self._context = get_current_context() # mark as initialized self.initialized = True
def test_widget_popup(self, *args): EventLoop.ensure_window() self._win = EventLoop.window self.clean_garbage() # build the widget tree & add Window as the main EL self.root = Builder.load_string(KV) self.render(self.root) self.assertLess(len(self._win.children), 2) # checked widget popup = self.root.ids.popup popup_exp = self.root.ids.popup.text # activate inspector with root as ctx inspector.start(self._win, self.root) self.advance_frames(1) # pull the Inspector drawer from bottom, # but don't inspect yet! ins = self.root.inspector ins.inspect_enabled = False ins.activated = True self.assertTrue(ins.at_bottom) # touch button center to open the popup touch = UnitTestTouch(*popup.center) touch.touch_down() touch.touch_up() self.advance_frames(1) # start inspecting ins.inspect_enabled = True self.advance_frames(1) # inspect FirstModal's button touch.touch_down() touch.touch_up() self.advance_frames(1) # open Inspector properties ins.show_widget_info() self.advance_frames(2) # check if the popup is selected # stored instance self.assertIsInstance(ins.widget, Factory.Button) self.assertIsInstance(ins.widget.parent, Factory.FirstModal) # check with new Popup instance if the properties match temp_popup = Factory.FirstModal() temp_popup_exp = temp_popup.ids.firstmodal.text self.assertEqual(ins.widget.text, temp_popup_exp) # data in properties for node in ins.treeview.iterate_all_nodes(): lkey = getattr(node.ids, 'lkey', None) if not lkey: continue if lkey.text == 'text': ltext = node.ids.ltext # slice because the string is displayed with quotes self.assertEqual(ltext.text[1:-1], temp_popup_exp) break del temp_popup # close popup ins.inspect_enabled = False touch = UnitTestTouch(0, 0) touch.touch_down() touch.touch_up() self.advance_frames(10) # close Inspector ins.activated = False self.render(self.root) self.advance_frames(10) # stop Inspector completely inspector.stop(self._win, self.root) self.assertLess(len(self._win.children), 2) self.render(self.root)
def _mainloop(self): EventLoop.idle() for event in pygame.event.get(): # kill application (SIG_TERM) if event.type == pygame.QUIT: if self.dispatch('on_request_close'): continue EventLoop.quit = True self.close() # mouse move elif event.type == pygame.MOUSEMOTION: x, y = event.pos self.mouse_pos = x, self.system_size[1] - y # don't dispatch motion if no button are pressed if event.buttons == (0, 0, 0): continue self._mouse_x = x self._mouse_y = y self._mouse_meta = self.modifiers self.dispatch('on_mouse_move', x, y, self.modifiers) # mouse action elif event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP): self._pygame_update_modifiers() x, y = event.pos btn = 'left' if event.button == 3: btn = 'right' elif event.button == 2: btn = 'middle' elif event.button == 4: btn = 'scrolldown' elif event.button == 5: btn = 'scrollup' elif event.button == 6: btn = 'scrollright' elif event.button == 7: btn = 'scrollleft' eventname = 'on_mouse_down' if event.type == pygame.MOUSEBUTTONUP: eventname = 'on_mouse_up' self._mouse_x = x self._mouse_y = y self._mouse_meta = self.modifiers self._mouse_btn = btn self._mouse_down = eventname == 'on_mouse_down' self.dispatch(eventname, x, y, btn, self.modifiers) # keyboard action elif event.type in (pygame.KEYDOWN, pygame.KEYUP): self._pygame_update_modifiers(event.mod) # atm, don't handle keyup if event.type == pygame.KEYUP: self.dispatch('on_key_up', event.key, event.scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', event.key, event.scancode, event.unicode, self.modifiers): continue self.dispatch('on_keyboard', event.key, event.scancode, event.unicode, self.modifiers) # video resize elif event.type == pygame.VIDEORESIZE: self._size = event.size self.update_viewport() elif event.type == pygame.VIDEOEXPOSE: self.canvas.ask_update() # ignored event elif event.type == pygame.ACTIVEEVENT: pass # drop file (pygame patch needed) elif event.type == pygame.USEREVENT and \ hasattr(pygame, 'USEREVENT_DROPFILE') and \ event.code == pygame.USEREVENT_DROPFILE: self.dispatch('on_dropfile', event.filename) '''
def _mainloop(self): EventLoop.idle() while True: event = self._win.poll() if event is False: break if event is None: continue action, args = event[0], event[1:] if action == 'quit': EventLoop.quit = True self.close() break elif action in ('fingermotion', 'fingerdown', 'fingerup'): # for finger, pass the raw event to SDL motion event provider # XXX this is problematic. On OSX, it generates touches with 0, # 0 coordinates, at the same times as mouse. But it works. # We have a conflict of using either the mouse or the finger. # Right now, we have no mechanism that we could use to know # which is the preferred one for the application. if platform == "ios": SDL2MotionEventProvider.q.appendleft(event) pass elif action == 'mousemotion': x, y = args x, y = self._fix_mouse_pos(x, y) self._mouse_x = x self._mouse_y = y # don't dispatch motion if no button are pressed if len(self._mouse_buttons_down) == 0: continue self._mouse_meta = self.modifiers self.dispatch('on_mouse_move', x, y, self.modifiers) elif action in ('mousebuttondown', 'mousebuttonup'): x, y, button = args x, y = self._fix_mouse_pos(x, y) btn = 'left' if button == 3: btn = 'right' elif button == 2: btn = 'middle' eventname = 'on_mouse_down' self._mouse_buttons_down.add(button) if action == 'mousebuttonup': eventname = 'on_mouse_up' self._mouse_buttons_down.remove(button) self._mouse_x = x self._mouse_y = y self.dispatch(eventname, x, y, btn, self.modifiers) elif action.startswith('mousewheel'): self._update_modifiers() x, y, button = args btn = 'scrolldown' if action.endswith('up'): btn = 'scrollup' elif action.endswith('right'): btn = 'scrollright' elif action.endswith('left'): btn = 'scrollleft' self._mouse_meta = self.modifiers self._mouse_btn = btn #times = x if y == 0 else y #times = min(abs(times), 100) #for k in range(times): self._mouse_down = True self.dispatch('on_mouse_down', self._mouse_x, self._mouse_y, btn, self.modifiers) self._mouse_down = False self.dispatch('on_mouse_up', self._mouse_x, self._mouse_y, btn, self.modifiers) elif action == 'dropfile': dropfile = args self.dispatch('on_dropfile', dropfile[0]) # video resize elif action == 'windowresized': self._size = self._win.window_size # don't use trigger here, we want to delay the resize event cb = self._do_resize Clock.unschedule(cb) Clock.schedule_once(cb, .1) elif action == 'windowresized': self.canvas.ask_update() elif action == 'windowrestored': self.canvas.ask_update() elif action == 'windowexposed': self.canvas.ask_update() elif action == 'windowminimized': if Config.getboolean('kivy', 'pause_on_minimize'): self.do_pause() elif action == 'joyaxismotion': stickid, axisid, value = args self.dispatch('on_joy_axis', stickid, axisid, value) elif action == 'joyhatmotion': stickid, hatid, value = args self.dispatch('on_joy_hat', stickid, hatid, value) elif action == 'joyballmotion': stickid, ballid, xrel, yrel = args self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel) elif action == 'joybuttondown': stickid, buttonid = args self.dispatch('on_joy_button_down', stickid, buttonid) elif action == 'joybuttonup': stickid, buttonid = args self.dispatch('on_joy_button_up', stickid, buttonid) elif action in ('keydown', 'keyup'): mod, key, scancode, kstr = args key_swap = { SDLK_LEFT: 276, SDLK_RIGHT: 275, SDLK_UP: 273, SDLK_DOWN: 274, SDLK_HOME: 278, SDLK_END: 279, SDLK_PAGEDOWN: 281, SDLK_PAGEUP: 280, SDLK_SHIFTR: 303, SDLK_SHIFTL: 304, SDLK_SUPER: 309, SDLK_LCTRL: 305, SDLK_RCTRL: 306, SDLK_LALT: 308, SDLK_RALT: 307, SDLK_CAPS: 301, SDLK_INSERT: 277, SDLK_F1: 282, SDLK_F2: 283, SDLK_F3: 284, SDLK_F4: 285, SDLK_F5: 286, SDLK_F6: 287, SDLK_F7: 288, SDLK_F8: 289, SDLK_F9: 290, SDLK_F10: 291, SDLK_F11: 292, SDLK_F12: 293, SDLK_F13: 294, SDLK_F14: 295, SDLK_F15: 296, SDLK_KEYPADNUM: 300, SDLK_KP_DEVIDE: 267, SDLK_KP_MULTIPLY: 268, SDLK_KP_MINUS: 269, SDLK_KP_PLUS: 270, SDLK_KP_ENTER: 271, SDLK_KP_DOT: 266, SDLK_KP_0: 256, SDLK_KP_1: 257, SDLK_KP_2: 258, SDLK_KP_3: 259, SDLK_KP_4: 260, SDLK_KP_5: 261, SDLK_KP_6: 262, SDLK_KP_7: 263, SDLK_KP_8: 264, SDLK_KP_9: 265 } if platform == 'ios': # XXX ios keyboard suck, when backspace is hit, the delete # keycode is sent. fix it. key_swap[127] = 8 # back try: key = key_swap[key] except KeyError: pass if action == 'keydown': self._update_modifiers(mod, key) else: self._update_modifiers(mod) # ignore the key, it # has been released # if mod in self._meta_keys: if (key not in self._modifiers and key not in self.command_keys.keys()): try: kstr = unichr(key) except ValueError: pass #if 'shift' in self._modifiers and key\ # not in self.command_keys.keys(): # return if action == 'keyup': self.dispatch('on_key_up', key, scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', key, scancode, kstr, self.modifiers): continue self.dispatch('on_keyboard', key, scancode, kstr, self.modifiers) elif action == 'textinput': text = args[0] self.dispatch('on_textinput', text) # XXX on IOS, keydown/up don't send unicode anymore. # With latest sdl, the text is sent over textinput # Right now, redo keydown/up, but we need to seperate both call # too. (and adapt on_key_* API.) #self.dispatch() #self.dispatch('on_key_down', key, None, args[0], # self.modifiers) #self.dispatch('on_keyboard', None, None, args[0], # self.modifiers) #self.dispatch('on_key_up', key, None, args[0], # self.modifiers) # unhandled event ! else: Logger.trace('WindowSDL: Unhandled event %s' % str(event))
def test_relativelayout_coordinates(self): EventLoop.ensure_window() rl = RelativeLayout(pos=(100, 100)) EventLoop.window.add_widget(rl) # do_layout() called self.assertEqual(rl.to_parent(50, 50), (150, 150)) self.assertEqual(rl.to_local(50, 50), (-50, -50))
def test_widget_multipopup(self, *args): EventLoop.ensure_window() self._win = EventLoop.window self.clean_garbage() # build the widget tree & add Window as the main EL self.root = Builder.load_string(KV) self.render(self.root) self.assertLess(len(self._win.children), 2) # checked widget popup = self.root.ids.popup popup_exp = self.root.ids.popup.text # activate inspector with root as ctx inspector.start(self._win, self.root) self.advance_frames(1) # pull the Inspector drawer from bottom, # but don't inspect yet! ins = self.root.inspector ins.inspect_enabled = False ins.activated = True self.assertTrue(ins.at_bottom) # touch button center to open the popup touch = UnitTestTouch(*popup.center) touch.touch_down() touch.touch_up() self.advance_frames(1) # touch Window center to open # the second and the third popup touch = UnitTestTouch( self._win.width / 2.0, self._win.height / 2.0 ) for i in range(2): touch.touch_down() touch.touch_up() self.advance_frames(1) # fixed order, first opened - last closed modals = ( Factory.ThirdModal, Factory.SecondModal, Factory.FirstModal ) for mod in modals: # start inspecting ins.inspect_enabled = True self.advance_frames(1) # inspect button touch.touch_down() touch.touch_up() self.advance_frames(1) # check if the popup is selected # stored instance self.assertIsInstance(ins.widget, Factory.Button) self.assertIsInstance(ins.widget.parent, mod) # close popup ins.inspect_enabled = False orig = UnitTestTouch(0, 0) orig.touch_down() orig.touch_up() self.advance_frames(10) # close Inspector ins.activated = False self.render(self.root) self.advance_frames(10) # stop Inspector completely inspector.stop(self._win, self.root) self.assertLess(len(self._win.children), 2) self.render(self.root)
def test_slider_move(self): EventLoop.ensure_window() win = EventLoop.window layout = BoxLayout(orientation='vertical') s_handle = _TestSliderHandle() s_all = _TestSliderAll() layout.add_widget(s_handle) layout.add_widget(s_all) win.add_widget(layout) # get widgets ready EventLoop.idle() cur1 = s_handle.children[0] cur2 = s_all.children[0] h1 = cur1.to_window(*cur1.center)[1] h2 = h1 - s_handle.cursor_height h3 = cur2.to_window(*cur2.center)[1] h4 = h3 - s_all.cursor_height w1 = cur1.to_window(*cur1.center)[0] w2 = cur2.to_window(*cur2.center)[0] wh = win.width / 2.0 dt = 2 # default pos, new pos, slider ID points = [ [w1, h1, wh, h1, 'handle'], [w1, h2, wh, h2, 'handle'], [w2, h3, wh, h3, 'all'], [w2, h4, wh, h4, 'all'], ] for point in points: x, y, nx, ny, id = point # custom touch touch = UTMotionEvent("unittest", 1, { "x": x / float(win.width), "y": y / float(win.height), }) # touch down EventLoop.post_dispatch_input("begin", touch) if id == 'handle': # touch on handle if x == w1 and y == h1: self.assertAlmostEqual(s_handle.value, 0.0, delta=dt) # touch in widget area (ignored, previous value) elif x == w1 and y == h2: self.assertAlmostEqual(s_handle.value, 50.0, delta=dt) elif id == 'all': # touch on handle: if x == w1 and y == h3: self.assertAlmostEqual(s_all.value, 0.0, delta=dt) # touch in widget area elif x == w1 and y == h4: self.assertAlmostEqual(s_all.value, 0.0, delta=dt) # move from default to new pos touch.move({ "x": nx / float(win.width), "y": ny / float(win.height) }) EventLoop.post_dispatch_input("update", touch) if id == 'handle': # move from handle to center if nx == wh and ny == h1: self.assertAlmostEqual(s_handle.value, 50.0, delta=dt) # move to center (ignored, previous value) elif nx == wh and ny == h2: self.assertAlmostEqual(s_handle.value, 50.0, delta=dt) elif id == 'all': # touch on handle: if nx == wh and ny == h3: self.assertAlmostEqual(s_all.value, 50.0, delta=dt) # touch in widget area elif nx == wh and ny == h4: self.assertAlmostEqual(s_all.value, 50.0, delta=dt) # touch up EventLoop.post_dispatch_input("end", touch) self.render(layout)
def advance_time(self, secs=.1): start = self._current_time while self._current_time < start + secs: EventLoop.idle() self._current_time += 1 / self._fps
def on_close(self, *largs): '''Event called when the window is closed''' Modules.unregister_window(self) EventLoop.remove_event_listener(self)
def install_twisted_reactor(**kwargs): '''Installs a threaded twisted reactor, which will schedule one reactor iteration before the next frame only when twisted needs to do some work. any arguments or keyword arguments passed to this function will be passed on the the threadedselect reactors interleave function, these are the arguments one would usually pass to twisted's reactor.startRunning Unlike the default twisted reactor, the installed reactor will not handle any signals unnless you set the 'installSignalHandlers' keyword argument to 1 explicitly. This is done to allow kivy to handle teh signals as usual, unless you specifically want the twisted reactor to handle the signals (e.g. SIGINT).''' import twisted # prevent installing more than once if hasattr(twisted, '_kivy_twisted_reactor_installed'): return twisted._kivy_twisted_reactor_installed = True # dont let twisted handle signals, unless specifically requested kwargs.setdefault('installSignalHandlers', 0) # install threaded-select reactor, to use with own event loop from twisted.internet import _threadedselect _threadedselect.install() # now we can import twisted reactor as usual from twisted.internet import reactor from collections import deque from kivy.base import EventLoop from kivy.logger import Logger from kivy.clock import Clock # will hold callbacks to twisted callbacks q = deque() # twisted will call the wake function when it needsto do work def reactor_wake(twisted_loop_next): Logger.trace("Support: twisted wakeup call to schedule task") q.append(twisted_loop_next) # called every frame, to process the reactors work in main thread def reactor_work(*args): Logger.trace("Support: processing twisted task queue") while len(q): q.popleft()() # start the reactor, by telling twisted how to wake, and process def reactor_start(*args): Logger.info("Support: Starting twisted reactor") reactor.interleave(reactor_wake, **kwargs) Clock.schedule_interval(reactor_work, 0) # make sure twisted reactor is shutdown if eventloop exists def reactor_stop(*args): '''will shutdown the twisted reactor main loop ''' if reactor.threadpool: Logger.info("Support: Stooping twisted threads") reactor.threadpool.stop() Logger.info("Support: Shutting down twisted reactor") reactor._mainLoopShutdown() # start and stop teh reactor along with kivy EventLoop EventLoop.bind(on_start=reactor_start) EventLoop.bind(on_stop=reactor_stop)
def _mainloop(self): EventLoop.idle() for event in pygame.event.get(): # kill application (SIG_TERM) if event.type == pygame.QUIT: EventLoop.quit = True self.close() # mouse move elif event.type == pygame.MOUSEMOTION: # don't dispatch motion if no button are pressed if event.buttons == (0, 0, 0): continue x, y = event.pos self.dispatch('on_mouse_move', x, y, self.modifiers) # mouse action elif event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP): self._pygame_update_modifiers() x, y = event.pos btn = 'left' if event.button == 3: btn = 'right' elif event.button == 2: btn = 'middle' elif event.button == 4: btn = 'scrolldown' elif event.button == 5: btn = 'scrollup' eventname = 'on_mouse_down' if event.type == pygame.MOUSEBUTTONUP: eventname = 'on_mouse_up' self.dispatch(eventname, x, y, btn, self.modifiers) # keyboard action elif event.type in (pygame.KEYDOWN, pygame.KEYUP): self._pygame_update_modifiers(event.mod) # atm, don't handle keyup if event.type == pygame.KEYUP: self.dispatch('on_key_up', event.key, event.scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', event.key, event.scancode, event.unicode, self.modifiers): continue self.dispatch('on_keyboard', event.key, event.scancode, event.unicode, self.modifiers) # video resize elif event.type == pygame.VIDEORESIZE: self._size = event.size # don't use trigger here, we want to delay the resize event cb = self._do_resize Clock.unschedule(cb) Clock.schedule_once(cb, .1) elif event.type == pygame.VIDEOEXPOSE: self.canvas.ask_update() # ignored event elif event.type == pygame.ACTIVEEVENT: pass # unhandled event ! else: Logger.debug('WinPygame: Unhandled event %s' % str(event))
def setUp(self): self.app = TesterApp() EventLoop.ensure_window() self._win = EventLoop.window self.clean_garbage() super(ImageTestCase, self).setUp()
def update_gui(self): if EventLoop.window and hasattr(EventLoop.window, '_mainloop'): EventLoop.window._mainloop() else: EventLoop.idle()
def process_points(self, scroll, points): win = EventLoop.window dt = 0.02 for point in points: if DEBUG: print('point:', point, scroll.scroll_x, scroll.scroll_y) Clock.schedule_once(lambda *dt: sleep(0.5), 0) self.render(scroll) x, y, nx, ny, pos_x, pos_y, border_check = point scroll.bar_pos = (pos_x, pos_y) touch = UTMotionEvent("unittest", next(touch_id), { "x": x / float(win.width), "y": y / float(win.height), }) # we start with the default top-left corner self.assertAlmostEqual(scroll.scroll_x, 0.0, delta=dt) self.assertAlmostEqual(scroll.scroll_y, 1.0, delta=dt) # check the collision with the margin empty area if border_check: EventLoop.post_dispatch_input("begin", touch) touch.move({ "x": nx / float(win.width), "y": ny / float(win.height) }) EventLoop.post_dispatch_input("update", touch) EventLoop.post_dispatch_input("end", touch) self.assertAlmostEqual(scroll.scroll_x, 0.0, delta=dt) self.assertAlmostEqual(scroll.scroll_y, 1.0, delta=dt) return EventLoop.post_dispatch_input("begin", touch) touch.move({ "x": nx / float(win.width), "y": ny / float(win.height) }) EventLoop.post_dispatch_input("update", touch) EventLoop.post_dispatch_input("end", touch) if DEBUG: print(scroll.scroll_x, scroll.scroll_y) Clock.schedule_once(lambda *dt: sleep(0.5), 0) self.render(scroll) # check the scroll position self.assertAlmostEqual(scroll.scroll_x, 0.0 if x == nx else 1.0, delta=dt) self.assertAlmostEqual(scroll.scroll_y, 1.0 if y == ny else 0.0, delta=dt) # reset scroll to original state scroll.scroll_x = 0.0 scroll.scroll_y = 1.0
def _run_mc(self): EventLoop.idle()
def build(self): self.icon = 'icon.png' # print the application informations print '\nDeflectouch v%s Copyright (C) 2012 2015 Cyril Stoller' % VERSION print 'This program comes with ABSOLUTELY NO WARRANTY' print 'This is free software, and you are welcome to redistribute it' print 'under certain conditions; see the source code for details.\n' from kivy.base import EventLoop EventLoop.ensure_window() self.window = EventLoop.window # create the root widget and give it a reference of the application instance (so it can access the application settings) self.deflectouchwidget = DeflectouchWidget(app=self) self.root = self.deflectouchwidget # start the background music: self.music = SoundLoader.load('sound/deflectouch.ogg') self.music.volume = self.config.getint('General', 'Music') / 100.0 self.music.bind(on_stop=self.sound_replay) self.music.play() # load all other sounds: self.sound['switch'] = SoundLoader.load('sound/switch.ogg') self.sound['select'] = SoundLoader.load('sound/select.ogg') self.sound['reset'] = SoundLoader.load('sound/reset.ogg') self.sound['beep'] = SoundLoader.load('sound/beep.ogg') self.sound['bullet_start'] = SoundLoader.load('sound/bullet_start.ogg') self.sound['explosion'] = SoundLoader.load('sound/explosion.ogg') self.sound['accomplished'] = SoundLoader.load('sound/accomplished.ogg') self.sound['no_deflector'] = SoundLoader.load('sound/no_deflector.ogg') self.sound['deflector_new'] = SoundLoader.load( 'sound/deflector_new.ogg') self.sound['deflector_down'] = SoundLoader.load( 'sound/deflector_down.ogg') self.sound['deflector_up'] = SoundLoader.load('sound/deflector_up.ogg') self.sound['deflector_delete'] = SoundLoader.load( 'sound/deflector_delete.ogg') self.sound['deflection'] = SoundLoader.load('sound/deflection.ogg') sound_volume = self.config.getint('General', 'Sound') / 100.0 for item in self.sound: self.sound[item].volume = sound_volume # continue on the last level which wasn't finished level_opened = False for counter, char in enumerate(self.config.get('GamePlay', 'Levels')): # if I found a level not yet done, continue with that if char == '0': self.deflectouchwidget.load_level(counter + 1) level_opened = True break # if all levels were completed, just open the last one. if level_opened == False: self.deflectouchwidget.load_level(40) # if the user started the game the first time, display quick start guide if self.config.get('General', 'FirstStartup') == 'Yes': Clock.schedule_once(self.welcome_screen, 2) self.config.set('General', 'FirstStartup', 'No') self.config.write()
def _mainloop(self): EventLoop.idle() # for android/iOS, we don't want to have any event nor executing our # main loop while the pause is going on. This loop wait any event (not # handled by the event filter), and remove them from the queue. # Nothing happen during the pause on iOS, except gyroscope value sent # over joystick. So it's safe. while self._pause_loop: self._win.wait_event() if not self._pause_loop: break self._win.poll() while True: event = self._win.poll() if event is False: break if event is None: continue action, args = event[0], event[1:] if action == 'quit': if self.dispatch('on_request_close'): continue EventLoop.quit = True self.close() break elif action in ('fingermotion', 'fingerdown', 'fingerup'): # for finger, pass the raw event to SDL motion event provider # XXX this is problematic. On OSX, it generates touches with 0, # 0 coordinates, at the same times as mouse. But it works. # We have a conflict of using either the mouse or the finger. # Right now, we have no mechanism that we could use to know # which is the preferred one for the application. if platform in ('ios', 'android'): SDL2MotionEventProvider.q.appendleft(event) pass elif action == 'mousemotion': x, y = args x, y = self._fix_mouse_pos(x, y) self._mouse_x = x self._mouse_y = y # don't dispatch motion if no button are pressed if len(self._mouse_buttons_down) == 0: continue self._mouse_meta = self.modifiers self.dispatch('on_mouse_move', x, y, self.modifiers) elif action in ('mousebuttondown', 'mousebuttonup'): x, y, button = args x, y = self._fix_mouse_pos(x, y) btn = 'left' if button == 3: btn = 'right' elif button == 2: btn = 'middle' eventname = 'on_mouse_down' self._mouse_buttons_down.add(button) if action == 'mousebuttonup': eventname = 'on_mouse_up' self._mouse_buttons_down.remove(button) self._mouse_x = x self._mouse_y = y self.dispatch(eventname, x, y, btn, self.modifiers) elif action.startswith('mousewheel'): self._update_modifiers() x, y, button = args btn = 'scrolldown' if action.endswith('up'): btn = 'scrollup' elif action.endswith('right'): btn = 'scrollright' elif action.endswith('left'): btn = 'scrollleft' self._mouse_meta = self.modifiers self._mouse_btn = btn # times = x if y == 0 else y # times = min(abs(times), 100) # for k in range(times): self._mouse_down = True self.dispatch('on_mouse_down', self._mouse_x, self._mouse_y, btn, self.modifiers) self._mouse_down = False self.dispatch('on_mouse_up', self._mouse_x, self._mouse_y, btn, self.modifiers) elif action == 'dropfile': dropfile = args self.dispatch('on_dropfile', dropfile[0]) # video resize elif action == 'windowresized': self._size = self._win.window_size # don't use trigger here, we want to delay the resize event ev = self._do_resize_ev if ev is None: ev = Clock.schedule_once(self._do_resize, .1) self._do_resize_ev = ev else: ev() elif action == 'windowresized': self.canvas.ask_update() elif action == 'windowrestored': self.dispatch('on_restore') self.canvas.ask_update() elif action == 'windowexposed': self.canvas.ask_update() elif action == 'windowminimized': self.dispatch('on_minimize') if Config.getboolean('kivy', 'pause_on_minimize'): self.do_pause() elif action == 'windowmaximized': self.dispatch('on_maximize') elif action == 'windowhidden': self.dispatch('on_hide') elif action == 'windowshown': self.dispatch('on_show') elif action == 'windowfocusgained': self._focus = True elif action == 'windowfocuslost': self._focus = False elif action == 'windowenter': self.dispatch('on_cursor_enter') elif action == 'windowleave': self.dispatch('on_cursor_leave') elif action == 'joyaxismotion': stickid, axisid, value = args self.dispatch('on_joy_axis', stickid, axisid, value) elif action == 'joyhatmotion': stickid, hatid, value = args self.dispatch('on_joy_hat', stickid, hatid, value) elif action == 'joyballmotion': stickid, ballid, xrel, yrel = args self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel) elif action == 'joybuttondown': stickid, buttonid = args self.dispatch('on_joy_button_down', stickid, buttonid) elif action == 'joybuttonup': stickid, buttonid = args self.dispatch('on_joy_button_up', stickid, buttonid) elif action in ('keydown', 'keyup'): mod, key, scancode, kstr = args try: key = self.key_map[key] except KeyError: pass if action == 'keydown': self._update_modifiers(mod, key) else: # ignore the key, it has been released self._update_modifiers(mod) # if mod in self._meta_keys: if (key not in self._modifiers and key not in self.command_keys.keys()): try: kstr_chr = unichr(key) try: kstr_chr.encode(sys.stdout.encoding) kstr = kstr_chr except UnicodeError: pass except ValueError: pass # if 'shift' in self._modifiers and key\ # not in self.command_keys.keys(): # return if action == 'keyup': self.dispatch('on_key_up', key, scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', key, scancode, kstr, self.modifiers): continue self.dispatch('on_keyboard', key, scancode, kstr, self.modifiers) elif action == 'textinput': text = args[0] self.dispatch('on_textinput', text) # unhandled event ! else: Logger.trace('WindowSDL: Unhandled event %s' % str(event))
def build(self): EventLoop.ensure_window() return GlslDemo()
def _mainloop(self): EventLoop.idle() while True: event = sdl.poll() if event is False: break if event is None: continue action, args = event[0], event[1:] if action == 'quit': if not self.dispatch('on_request_close'): EventLoop.quit = True self.close() break elif action in ('fingermotion', 'fingerdown', 'fingerup'): # for finger, pass the raw event to SDL motion event provider SDLMotionEventProvider.q.appendleft(event) if action == 'mousemotion': x, y = args self.dispatch('on_mouse_move', x, y, self.modifiers) elif action in ('mousebuttondown', 'mousebuttonup'): x, y, button = args btn = 'left' if button == 3: btn = 'right' elif button == 2: btn = 'middle' eventname = 'on_mouse_down' if action == 'mousebuttonup': eventname = 'on_mouse_up' self.dispatch(eventname, x, y, btn, self.modifiers) # video resize elif action == 'windowresized': self._size = args # don't use trigger here, we want to delay the resize event cb = self._do_resize Clock.unschedule(cb) Clock.schedule_once(cb, .1) elif action == 'windowresized': self.canvas.ask_update() elif action == 'windowminimized': self.do_pause() elif action == 'windowrestored': pass elif action in ('keydown', 'keyup'): mod, key, scancode, str = args # XXX ios keyboard suck, when backspace is hit, the delete # keycode is sent. fix it. if key == 127: key = 8 self._pygame_update_modifiers(mod) if action == 'keyup': self.dispatch('on_key_up', key, scancode) continue # don't dispatch more key if down event is accepted if self.dispatch('on_key_down', key, scancode, str, self.modifiers): continue self.dispatch('on_keyboard', key, scancode, str, self.modifiers) elif action == 'textinput': key = args[0][0] # XXX on IOS, keydown/up don't send unicode anymore. # With latest sdl, the text is sent over textinput # Right now, redo keydown/up, but we need to seperate both call # too. (and adapt on_key_* API.) self.dispatch('on_key_down', key, None, args[0], self.modifiers) self.dispatch('on_keyboard', None, None, args[0], self.modifiers) self.dispatch('on_key_up', key, None, args[0], self.modifiers)
def value( self ): return self._value @value.setter def value( self, aValue ): aValue = min(max(0.0, aValue), 1.0) if self._value != aValue: self._value = aValue if self._value == 0.0: #todo: send button up event. elif self._value == 1.0: #todo: send button down event. if __name__ == '__main__': m = MyAnim(10.0) EventLoop.add_event_listener(m) EventLoop.start() a = Animation(value=20.0, duration=2.0) a += Animation(value=15.0, duration=1.0) a.bind(on_complete=m.done) a.start(m) while m.run: EventLoop.idle() print(m.value) sleep(0.1) #Part Name #value, time, transition #All values are absolute, but we want to use deltas, so we need to figure out how
def __init__(self, **kwargs): kwargs.setdefault('force', False) # don't init window 2 times, # except if force is specified if WindowBase.__instance is not None and not kwargs.get('force'): return self.initialized = False # event subsystem self.register_event_type('on_draw') self.register_event_type('on_flip') self.register_event_type('on_rotate') self.register_event_type('on_resize') self.register_event_type('on_close') self.register_event_type('on_motion') self.register_event_type('on_touch_down') self.register_event_type('on_touch_move') self.register_event_type('on_touch_up') self.register_event_type('on_mouse_down') self.register_event_type('on_mouse_move') self.register_event_type('on_mouse_up') self.register_event_type('on_keyboard') self.register_event_type('on_key_down') self.register_event_type('on_key_up') self.register_event_type('on_dropfile') # create a trigger for update/create the window when one of window # property changes self.trigger_create_window = Clock.create_trigger( self.create_window, -1) # set the default window parameter according to the configuration if 'fullscreen' not in kwargs: fullscreen = Config.get('graphics', 'fullscreen') if fullscreen not in ('auto', 'fake'): fullscreen = fullscreen.lower() in ('true', '1', 'yes', 'yup') kwargs['fullscreen'] = fullscreen if 'width' not in kwargs: kwargs['width'] = Config.getint('graphics', 'width') if 'height' not in kwargs: kwargs['height'] = Config.getint('graphics', 'height') if 'rotation' not in kwargs: kwargs['rotation'] = Config.getint('graphics', 'rotation') if 'position' not in kwargs: kwargs['position'] = Config.get('graphics', 'position', 'auto') if 'top' in kwargs: kwargs['position'] = 'custom' kwargs['top'] = kwargs['top'] else: kwargs['top'] = Config.getint('graphics', 'top') if 'left' in kwargs: kwargs['position'] = 'custom' kwargs['left'] = kwargs['left'] else: kwargs['left'] = Config.getint('graphics', 'left') kwargs['_size'] = (kwargs.pop('width'), kwargs.pop('height')) super(WindowBase, self).__init__(**kwargs) # bind all the properties that need to recreate the window for prop in ('fullscreen', 'position', 'top', 'left', '_size', 'system_size'): self.bind(**{prop: self.trigger_create_window}) # init privates self._system_keyboard = Keyboard(window=self) self._keyboards = {'system': self._system_keyboard} self._vkeyboard_cls = None self.children = [] self.parent = self # before creating the window __import__('kivy.core.gl') # configure the window self.create_window() # attach modules + listener event Modules.register_window(self) EventLoop.set_window(self) EventLoop.add_event_listener(self) # manage keyboard(s) self.configure_keyboards() # mark as initialized self.initialized = True
def install_twisted_reactor(**kwargs): '''Installs a threaded twisted reactor, which will schedule one reactor iteration before the next frame only when twisted needs to do some work. Any arguments or keyword arguments passed to this function will be passed on the the threadedselect reactors interleave function. These are the arguments one would usually pass to twisted's reactor.startRunning. Unlike the default twisted reactor, the installed reactor will not handle any signals unless you set the 'installSignalHandlers' keyword argument to 1 explicitly. This is done to allow kivy to handle the signals as usual unless you specifically want the twisted reactor to handle the signals (e.g. SIGINT). .. note:: Twisted is not included in iOS build by default. To use it on iOS, put the twisted distribution (and zope.interface dependency) in your application directory. ''' import twisted # prevent installing more than once if hasattr(twisted, '_kivy_twisted_reactor_installed'): return twisted._kivy_twisted_reactor_installed = True # don't let twisted handle signals, unless specifically requested kwargs.setdefault('installSignalHandlers', 0) # install threaded-select reactor, to use with own event loop from twisted.internet import _threadedselect _threadedselect.install() # now we can import twisted reactor as usual from twisted.internet import reactor from twisted.internet.error import ReactorNotRunning from collections import deque from kivy.base import EventLoop from kivy.logger import Logger from kivy.clock import Clock # will hold callbacks to twisted callbacks q = deque() # twisted will call the wake function when it needs to do work def reactor_wake(twisted_loop_next): '''Wakeup the twisted reactor to start processing the task queue ''' Logger.trace("Support: twisted wakeup call to schedule task") q.append(twisted_loop_next) # called every frame, to process the reactors work in main thread def reactor_work(*args): '''Process the twisted reactor task queue ''' Logger.trace("Support: processing twisted task queue") while len(q): q.popleft()() global _twisted_reactor_work _twisted_reactor_work = reactor_work # start the reactor, by telling twisted how to wake, and process def reactor_start(*args): '''Start the twisted reactor main loop ''' Logger.info("Support: Starting twisted reactor") reactor.interleave(reactor_wake, **kwargs) Clock.schedule_interval(reactor_work, 0) # make sure twisted reactor is shutdown if eventloop exists def reactor_stop(*args): '''Shutdown the twisted reactor main loop ''' if reactor.threadpool: Logger.info("Support: Stopping twisted threads") reactor.threadpool.stop() Logger.info("Support: Shutting down twisted reactor") reactor._mainLoopShutdown() try: reactor.stop() except ReactorNotRunning: pass import sys sys.modules.pop('twisted.internet.reactor', None) global _twisted_reactor_stopper _twisted_reactor_stopper = reactor_stop # start and stop the reactor along with kivy EventLoop Clock.schedule_once(reactor_start, 0) EventLoop.bind(on_stop=reactor_stop)
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # setup ! w, h = self.system_size resizable = Config.getboolean('graphics', 'resizable') state = (Config.get('graphics', 'window_state') if self._is_desktop else None) self.system_size = _size = self._win.setup_window( pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable, state) # calculate density sz = self._win._get_gl_size()[0] self._density = density = sz / _size[0] if self._is_desktop and self.size[0] != _size[0]: self.dpi = density * 96. # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) else: w, h = self.system_size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() if self.initialized: return # auto add input provider Logger.info('Window: auto add sdl2 input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')