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 __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 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 build(self): from kivy.base import EventLoop EventLoop.ensure_window() self.window = EventLoop.window self.root = TestWidget()
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): EventLoop.ensure_window() self.window = EventLoop.window self.root = FloatLayout() self.screens = {} self.screens['menu'] = MenuScreen(self) self.open_screen('menu')
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 __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, **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 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 __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() # 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): # 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 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): # 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 __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 __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 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 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() self.canvas_widget = CanvasWidget() # Crea el ROOT widget self.canvas_widget.set_color( # Pone color inicial al trazo get_color_from_hex('#190707')) return self.canvas_widget
def bind_keyboards(self): from kivy.base import EventLoop EventLoop.ensure_window() def on_key_down(window, keycode, *args): if keycode == 27: if self.sm.current != 'home': self.sm.current = 'home' return True EventLoop.window.bind(on_key_down=on_key_down)
def test_relativelayout_on_touch_move(self): EventLoop.ensure_window() rl = RelativeLayout() EventLoop.window.add_widget(rl) touch = UTMotionEvent("unittest", 1, {"x": .5, "y": .5}) EventLoop.post_dispatch_input("begin", touch) touch.move({"x": .6, "y": .4}) EventLoop.post_dispatch_input("update", touch) EventLoop.post_dispatch_input("end", touch)
def build(self): EventLoop.ensure_window() layout = FloatLayout() if self.figure: self.figure.size_hint_y = 0.9 layout.add_widget(self.figure) if self.toolbar: self.toolbar.size_hint_y = 0.1 layout.add_widget(self.toolbar) return layout
def populate_fbo(self, fbo): if not self.has_gui: return EventLoop.ensure_window() if self._update_fbo < 2: for obj in self.objs: self.fbo_widget.size = canvas3d.PICKING_BUFFER_SIZE self.fbo_widget.fbo.size = canvas3d.PICKING_BUFFER_SIZE obj.texture = self.fbo_widget.fbo.texture with self.fbo_widget.fbo: ClearColor(1, 1, 1, 1) self.flip_coords = False
def build(self): EventLoop.ensure_window() if EventLoop.window.__class__.__name__.endswith('Pygame'): try: from pygame import mouse # pygame_compile_cursor is a fixed version of # pygame.cursors.compile a, b = pygame_compile_cursor() mouse.set_cursor((24, 24), (9, 9), a, b) except: pass return CanvasWidget()
def build(self): """build application""" from kivy.base import EventLoop EventLoop.ensure_window() self.window = EventLoop.window self.gravity = GravityRing(name='gravity') self.sm.add_widget(Menu(name='menu')) self.sm.add_widget(self.gravity) self.sm.add_widget(ConfigScreen(name='configscreen', sm=self.sm)) # gravity.update(1) # Clock.schedule_interval(self.gravity.update, 1. / 60) Window.bind(on_keyboard=self.hook_keyboard) return self.sm
def build(self): EventLoop.ensure_window() if EventLoop.window.__class__.__name__.endswith('Pygame'): try: from pygame import mouse from pygame import cursors a, b = cursors.compile(CURSOR, black='@', white='-') mouse.set_cursor((24, 24), (9, 9), a, b) except ImportError: pass self.canvas_widget = CanvasWidget() self.canvas_widget.set_color(get_color_from_hex('#2980B9')) return self.canvas_widget
def build(self): EventLoop.ensure_window() EventLoop.window.title = self.title = 'Rockivy | Kivy App Contest 2014' if EventLoop.window.__class__.__name__.endswith('Pygame'): try: # because pygame hates nice cursors pygame_set_cursor() except: pass game = Game() self.on_start = game.on_start return init_ui(game)
def build(self): EventLoop.ensure_window() if EventLoop.window.__class__.__name__.endswith("Pygame"): try: from pygame import mouse a, b = pygame_compile_cursor() mouse.set_cursor((24, 24), (9, 9), a, b) except: pass self.canvas_widget = CanvasWidget() self.canvas_widget.set_color(get_color_from_hex("#2980b9")) return self.canvas_widget
def build(self): """Configure l'affichage selon le systeme d'exploitation courrant et initialise le widget de base""" self.Config = ConfigParser.ConfigParser() self.Config.read(config_path) Manager.SERVEUR_LOGIN = (self.Config.get("Server", "ip"), int(self.Config.get("Server", "port"))) from kivy.base import EventLoop EventLoop.ensure_window() self.window = EventLoop.window self.root = InterfaceManager(app=self) self.configurer()
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 = self.builder.Builder.load_string( KV, filename="InspectorTestCase.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(5) # stop Inspector completely inspector.stop(self._win, self.root) self.assertLess(len(self._win.children), 2) self.render(self.root)
def _get_root_widget(): EventLoop.ensure_window() return EventLoop.window.children[0]
def __init__(self): super(LoginScreen, self).__init__() EventLoop.ensure_window() Window.clearcolor = (1, 1, 1, 1) Window.size = (1280, 700) EventLoop.window.title = self.title = 'ball_detection' lbl1 = Label(text="Input Path : ", italic=True, bold=True, size_hint=(.08, .05), pos=(70, 650), color=(0, 0, 0, 0)) lbl2 = Label(text="visualization :", bold=True, size_hint=(.08, .05), pos=(720, 650), font_size='20sp', color=(0, 0, 0, 0)) txt1 = TextInput(multiline=False, font_size=20, size_hint=(.2, .05), pos=(180, 650)) ok = Button(text="OK", italic=True, size_hint=(.08, .05), pos=(450, 650)) stop = Button(text="Stop", italic=True, size_hint=(.08, .05), pos=(560, 650)) temp = cv2.imread('gui_images/img_original.jpg') temp = cv2.resize(temp, (450, 450)) cv2.imwrite('gui_images/temp.jpg', temp) img_graph = 'gui_images/temp.jpg' self.im_graph = Image(source=img_graph, pos_hint={ 'center_x': 0.70, 'center_y': 0.58 }) in_px = Label( text= "Results in CM/Pixels\n Toss Height : \n Toss Distance : \n Toss Speed : \n Ball Speed : ", bold=True, font_size=20, size_hint=(.2, .2), pos=(645, 40), color=(0, 0, 0, 0)) in_cm = Label(text="\n|\n|\n|\n|", bold=True, font_size=20, size_hint=(.2, .2), pos=(850, 40), color=(0, 0, 0, 0)) str1 = str('\n') + str(0.0) + " px\n" + str( 0.0) + " px\n" + str(0.0) + " px/sec\n" + str( 0.0) + ' px/sec' self.in_px_ans = Label(text=str1, italic=True, bold=True, font_size=20, size_hint=(.2, .2), pos=(780, 40), color=(0, 0, 0, 0)) str2 = str('\n') + str(0.0) + " cm\n" + str( 0.0) + " cm\n" + str(0.0) + " cm/sec\n" + str( 0.0) + ' cm/sec' self.in_cm_ans = Label(text=str2, italic=True, bold=True, font_size=20, size_hint=(.2, .2), pos=(930, 40), color=(0, 0, 0, 0)) img_src = 'gui_images/bg.png' self.im = Image(source=img_src, pos_hint={ 'center_x': 0.28, 'center_y': 0.475 }) dropdown = DropDown() for index in range(1, 15): btn = Button(text='Plot %d' % index, size_hint_y=None, height=42) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) mainbutton = Button(text='Show Plots', size_hint=(.1, .05), pos=(1140, 605)) mainbutton.bind(on_release=dropdown.open) dropdown.bind(on_select=lambda instance, x: save_plot(x)) self.add_widget(mainbutton) self.add_widget(self.im) self.add_widget(lbl1) self.add_widget(lbl2) self.add_widget(txt1) self.add_widget(ok) self.add_widget(stop) self.add_widget(in_px) self.add_widget(in_cm) self.add_widget(self.in_cm_ans) self.add_widget(self.in_px_ans) self.add_widget(self.im_graph) ok.bind(on_press=lambda *a: storage_for_file_name(txt1.text)) stop.bind(on_press=lambda *a: storage_for_file_name('stop')) Clock.schedule_interval(self.update, 1.0 / 1000.0)
def test_touch_draw(self): # get Window instance for creating visible # widget tree and for calculating coordinates EventLoop.ensure_window() win = EventLoop.window # add widget for testing child = WidgetCanvasDraw() win.add_widget(child) # get widgets ready EventLoop.idle() # default "cursor" position in the middle pos = [win.width / 2.0, win.height / 2.0] # default pos, new pos points = [ [pos[0] - 5, pos[1], pos[0] + 5, pos[1]], [pos[0], pos[1] - 5, pos[0], pos[1] + 5] ] # general behavior for touch+move+release for i, point in enumerate(points): x, y, nx, ny = point # create custom MotionEvent (touch) instance touch = UTMotionEvent("unittest", 1, { "sx": x / float(win.width), "sy": y / float(win.height), }) # dispatch the MotionEvent in EventLoop as # touch/press/click, see Profiles for more info: # https://kivy.org/docs/api-kivy.input.motionevent.html#profiles EventLoop.post_dispatch_input("begin", touch) # the touch is dispatched and has ud['lines'] # available from on_touch_down self.assertIn('lines', touch.ud) self.assertTrue(isinstance(touch.ud['lines'], Point)) # move touch from current to the new position touch.move({ "sx": nx / float(win.width), "sy": ny / float(win.height) }) # update the MotionEvent in EventLoop EventLoop.post_dispatch_input("update", touch) # release the MotionEvent in EventLoop EventLoop.post_dispatch_input("end", touch) # still available, but released self.assertIn('lines', touch.ud) self.assertTrue(isinstance(touch.ud['lines'], Point)) expected_points = [[ x + 0, y, x + 1, y, x + 2, y, x + 3, y, x + 4, y, x + 5, y, x + 6, y, x + 7, y, x + 8, y, x + 9, y ], [ x, y + 0, x, y + 1, x, y + 2, x, y + 3, x, y + 4, x, y + 5, x, y + 6, x, y + 7, x, y + 8, x, y + 9 ]] # check if the instruction points == expected ones self.assertEqual( touch.ud['lines'].points, expected_points[i] ) # render the graphics self.render(child)
def build(self): EventLoop.ensure_window() return FontRender()
def setUp(self): self.app = TesterApp() EventLoop.ensure_window() self._win = EventLoop.window self.clean_garbage() super(ImageTestCase, self).setUp()
def build(self): EventLoop.ensure_window() return Game()
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 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 = self.builder.Builder.load_string( KV, filename="InspectorTestCase.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(5) # stop Inspector completely inspector.stop(self._win, self.root) self.assertLess(len(self._win.children), 2) self.render(self.root)
def build(self): # print the application informations print '\nDeflectouch v%s Copyright (C) 2012 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 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 build(self): EventLoop.ensure_window() return GlslDemo()
def build(self): EventLoop.ensure_window() return Starfield()
from kivy.uix.textinput import TextInput from kivy.core.window import Window from kivy.lang import Builder from kivy.utils import get_color_from_hex from kivy.clock import Clock from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.base import EventLoop from kivy.properties import (NumericProperty, ListProperty, BooleanProperty, StringProperty, ObjectProperty) from config import HOVER, NORMAL, RED, COLOR_PALETTE, DB, DEF_USER from mine import Mine EventLoop.ensure_window() class CustomPopup(Popup): score_board = [] editable_text = ObjectProperty() def __init__(self, horizontal='', vertical='', spend='', level='', **kwargs): super(CustomPopup, self).__init__(**kwargs) self.board_h = horizontal self.board_v = vertical self.level = level self.spend = spend self.separator_height = 0 self.background = "" grid = self.children[0]