def idle(self): '''This function is called every frames. By default : * it "tick" the clock to the next frame * read all input and dispatch event * dispatch on_update + on_draw + on_flip on window ''' # update dt Clock.tick() # read and dispatch input from providers self.dispatch_input() window = self.window if window and window.canvas.needs_redraw: Clock.tick_draw() window.dispatch('on_draw') window.dispatch('on_flip') # don't loop if we don't have listeners ! if len(self.event_listeners) == 0: Logger.error('Base: No event listeners have been created') Logger.error('Base: Application will leave') self.exit() return False return self.quit
def test_schedule_once_draw_before(self): from kivy.clock import Clock Clock.schedule_once(callback, -1) Clock.tick_draw() self.assertEqual(counter, 1) Clock.tick() self.assertEqual(counter, 1)
def validate_card(self, rfid_tag): Logger.info('User Manager: validate_card with rfid_tag: {}'.format(rfid_tag)) self.app = App.get_running_app() headers = { 'Accept': 'application/json', 'Content-type': 'application/json', 'Cache-Control': 'no-cache', 'Authorization': 'Token ' + self.app.config.get('Software', 'license key') } req = UrlRequest('http://{}/api/1.0/employees/?format=json&rfid_tag={}'.format( self.app.config.get('Network', 'server fqdn'), rfid_tag), on_success=self.url_request_on_success, on_error=self.url_request_on_error, on_failure=self.url_request_on_failure, req_headers=headers) # don't use wait, but maximum 10s timeout for i in range(50): Clock.tick() sleep(.5) if req.is_finished: break # A valid tag will have an 'id' key in its data. if 'id' in self.employee: return True # valid API response from server else: self.employee = [] return False # invalid API response sent by server
def test_unschedule_after_tick(self): from kivy.clock import Clock Clock.schedule_once(callback, 5.) Clock.tick() Clock.unschedule(callback) Clock.tick() self.assertEqual(counter, 0)
def test_trigger_cancel(self): from kivy.clock import Clock trigger = Clock.create_trigger(callback, 5.) trigger() trigger.cancel() Clock.tick() self.assertEqual(counter, 0)
def test_scheduling_limits(self): global best_score from kivy.clock import Clock gdb = Recognizer(db=[self.Ninvar]) tpls = len(self.Ninvar.templates) best_score = 0 gdb.db.append(self.Ninvar) r = gdb.recognize([Ncandidate], max_gpf=1) r.bind(on_complete=best_score_cb) self.assertEqual(r.progress, 0) Clock.tick() self.assertEqual(r.progress, 0.5) self.assertEqual(best_score, 0) Clock.tick() self.assertEqual(r.progress, 1) self.assertTrue(best_score > 0.94 and best_score < 0.95) best_score = 0 gdb.db.append(self.Ninvar) r = gdb.recognize([Ncandidate], max_gpf=1) r.bind(on_complete=best_score_cb) self.assertEqual(r.progress, 0) Clock.tick() self.assertEqual(r.progress, 1 / 3.) Clock.tick() self.assertEqual(r.progress, 2 / 3.) self.assertEqual(best_score, 0) Clock.tick() self.assertEqual(r.progress, 1) self.assertTrue(best_score > 0.94 and best_score < 0.95)
def make_labels(): o = [] for text in labels: o.append(cls(text=text)) if tick == 'tick': Clock.tick()
def callback(self, skel, class_name): if self._parent.initialized and not self._parent.write_mode: try: skel = self.bridge.imgmsg_to_cv2(skel, desired_encoding= 'passthrough') action = class_name.source if action == 'Index': self.ran = False self.add_stroke_vector(skel[-1, -1, 1], skel[-1, -1, 0]) self.time = time.time() elif action == 'Palm': self.add_stroke() if not self.ran and time.time() - self.time > self.time_thres: self.ran = True if len(self.strokes[0])>0: self.progress = self.gdb.recognize(self.strokes[:-1]) #removing last empty sublist ^ clock.tick() self._data.add(gesture=self.gesture, found_gesture=self.found_gesture, strokes=self.strokes) self.strokes = [[]] evt = CreateEvent(EVT_STRK_TYPE, -1) wx.PostEvent(self._parent, evt) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print e else: self.strokes = [[]]
def test_init_geojson(self): """Providing the geojson directly, polygons should get added.""" options = {} mapview = MapView(**options) geojson = {} kwargs = {"geojson": geojson} maplayer = GeoJsonMapLayer(**kwargs) mapview.add_layer(maplayer) Clock.tick() assert maplayer.source == "" assert maplayer.geojson == geojson assert len(maplayer.canvas_line.children) == 0 assert len(maplayer.canvas_polygon.children) == 3 assert len(maplayer.g_canvas_polygon.children) == 0 geojson = load_json("maps-devrel-google.json") kwargs = {"geojson": geojson} maplayer = GeoJsonMapLayer(**kwargs) mapview = MapView(**options) mapview.add_layer(maplayer) Clock.tick() assert maplayer.source == "" assert maplayer.geojson == geojson assert len(maplayer.canvas_line.children) == 0 assert len(maplayer.canvas_polygon.children) == 3 assert len(maplayer.g_canvas_polygon.children) == 132
def test_callbacks(self): self.queue = [] req = UrlRequest('http://google.com', on_success=self._on_success, on_progress=self._on_progress, on_error=self._on_error) # don't use wait, but maximum 10s timeout for i in xrange(50): Clock.tick() sleep(.5) if req.is_finished: break self.assertTrue(req.is_finished) # we should have 2 progress minimum and one success self.assertGreaterEqual(len(self.queue), 3) print self.queue # ensure the callback is called from this thread (main). tid = thread.get_ident() self.assertEqual(self.queue[0][0], tid) self.assertEqual(self.queue[-2][0], tid) self.assertEqual(self.queue[-1][0], tid) self.assertEqual(self.queue[0][1], 'progress') self.assertEqual(self.queue[-2][1], 'progress') self.assertEqual(self.queue[-1][1], 'success') self.assertEqual(self.queue[0][2][0], 0) self.assertEqual(self.queue[-2][2][0], self.queue[-2][2][1])
def test_the_touch_that_might_already_ended(actually_ended): import time from kivy.clock import Clock from kivy.uix.widget import Widget from kivy.tests.common import UnitTestTouch import asynckivy as ak from asynckivy.exceptions import MotionEventAlreadyEndedError Clock.tick() async def job(w, t): if actually_ended: with pytest.raises(MotionEventAlreadyEndedError): async for __ in ak.rest_of_touch_moves(w, t): pass else: async for __ in ak.rest_of_touch_moves(w, t): pass w = Widget() t = UnitTestTouch(0, 0) t.time_end = 1 # something other than -1 task = ak.start(job(w, t)) if actually_ended: time.sleep(2.) Clock.tick() else: t.grab_current = None w.dispatch('on_touch_up', t) t.grab_current = w w.dispatch('on_touch_up', t) assert task.done
def test_schedule_another_one_during_a_scheduled_one(): from kivy.clock import Clock import asynckivy as ak from asynckivy import _start_soon task2 = None async def job1(): nonlocal task2 task2 = ak.start_soon(job2()) async def job2(): pass task1 = ak.start_soon(job1()) assert _start_soon._waiting == [ task1, ] assert not task1.done assert task2 is None Clock.tick() assert _start_soon._waiting == [ task2, ] assert task1.done assert not task2.done Clock.tick() assert _start_soon._waiting == [] assert task1.done assert task2.done
def test_to_local_and_to_parent__not_relative(widget_cls_name): from kivy.clock import Clock from kivy.factory import Factory widget = Factory.get(widget_cls_name)(pos=(100, 100)) Clock.tick() assert widget.to_local(0, 0) == (0, 0) assert widget.to_parent(0, 0) == (0, 0)
def test_to_window_and_to_widget(root_widget_cls_name, target_widget_cls_name): from kivy.clock import Clock from textwrap import dedent from kivy.lang import Builder root = Builder.load_string( dedent(''' {}: pos: 100, 0 # In case the root widget is ScrollView, this cushion is needed, # because ScrollView's direct child is always at pos(0, 0) Widget: pos: 0, 0 {}: id: target pos: 0, 100 ''').format(root_widget_cls_name, target_widget_cls_name)) Clock.tick() target = root.ids.target if is_relative_type(root): assert target.to_window(*target.pos) == (100, 100) assert target.to_widget(0, 0) == \ ((-100, -100) if is_relative_type(target) else (-100, 0)) else: assert target.to_window(*target.pos) == (0, 100) assert target.to_widget(0, 0) == \ ((0, -100) if is_relative_type(target) else (0, 0))
def test_callbacks(self): if os.environ.get('NONETWORK'): return self.queue = [] req = UrlRequest('http://google.com', on_success=self._on_success, on_progress=self._on_progress, on_error=self._on_error, on_redirect=self._on_redirect, debug=True) # don't use wait, but maximum 10s timeout for i in range(50): Clock.tick() sleep(.5) if req.is_finished: break self.assertTrue(req.is_finished) # we should have 2 progress minimum and one success self.assertTrue(len(self.queue) >= 3) # ensure the callback is called from this thread (main). tid = _thread.get_ident() self.assertEqual(self.queue[0][0], tid) self.assertEqual(self.queue[-2][0], tid) self.assertEqual(self.queue[-1][0], tid) self.assertEqual(self.queue[0][1], 'progress') self.assertEqual(self.queue[-2][1], 'progress') self.assertIn(self.queue[-1][1], ('success', 'redirect')) self.assertEqual(self.queue[0][2][0], 0) self.assertEqual(self.queue[-2][2][0], self.queue[-2][2][1])
def test_trigger_interval(self): from kivy.clock import Clock trigger = Clock.create_trigger(callback, 0, interval=True) trigger() Clock.tick() self.assertEqual(counter, 1) Clock.tick() self.assertEqual(counter, 2)
def proceed_search(self, db, query=None): if query is not None: db.search_tag(query) else: db.search_tag() sleep(0.1) for i in range(2): Clock.tick()
def pega_codigo(self): url = 'https://www.google.com' codigo = UrlRequest(url, self.on_sucess, self.on_error) while not codigo.is_finished: Clock.tick() result = codigo.result self.ids.boxCod.add_widget(nLabel(text=str(result)))
def refresh_tagesthemen(self): self.is_refreshing = True Clock.tick() info = get_tagesthemen_download_link_date() UrlRequest(url=info['link'], on_success=self.after_download, on_progress=self.on_download_progress, file_path='./videos/' + info['date'] + 'tagesthemen.mp4')
def cut_first(qty): self.proceed_search(db) self.assertEqual('/0001.jpg', cursor.filename) for i in range(qty): b.mark_current() b.select_next(0) b.select_first() b.cut_marked() Clock.tick()
def test_trigger_decorator_cancel(self): from kivy.clock import Clock, triggered @triggered() def triggered_callback(): callback(dt=0) triggered_callback() triggered_callback.cancel() Clock.tick() self.assertEqual(counter, 0)
def cut(cut_method, position=None): cut_method() if position is not None: b.select_custom(position) Clock.tick() sleep(0.1) Clock.tick() Clock.tick() b.cut_marked() sleep(0.1) Clock.tick() Clock.tick()
def test_auth_header(): if os.environ.get('NONETWORK'): return from kivy.network.urlrequest import UrlRequest from kivy.clock import Clock obj = UrlRequestQueue([]) queue = obj.queue head = { "Authorization": "Basic {}".format(b64encode( "{}:{}".format('user', 'passwd').encode('utf-8') ).decode('utf-8')) } req = UrlRequest( 'http://httpbin.org/basic-auth/user/passwd', on_success=obj._on_success, on_progress=obj._on_progress, on_error=obj._on_error, on_redirect=obj._on_redirect, req_headers=head, debug=True ) # don't use wait, but maximum 10s timeout for i in range(50): Clock.tick() sleep(.5) if req.is_finished: break assert req.is_finished if req.error and req.error.errno == 11001: pytest.skip('Cannot connect to get address') # we should have 2 progress minimum and one success assert len(queue) >= 3 # ensure the callback is called from this thread (main). tid = threading.get_ident() assert queue[0][0] == tid assert queue[-2][0] == tid assert queue[-1][0] == tid assert queue[0][1] == 'progress' assert queue[-2][1] == 'progress' assert queue[-1][1] in ('success', 'redirect') assert queue[-1][2] == ({'authenticated': True, 'user': '******'}, ) assert queue[0][2][0] == 0 assert queue[-2][2][0] == queue[-2][2][1]
def test_download(self): """Checks download() callback.""" callback = mock.Mock() url = "https://ifconfig.me/" downloader = Downloader.instance() assert len(downloader._futures) == 0 with patch_requests_get() as m_get: downloader.download(url, callback) assert m_get.call_args_list == [mock.call(url)] assert callback.call_args_list == [] assert len(downloader._futures) == 1 Clock.tick() assert callback.call_args_list == [mock.call(url, mock.ANY)] assert len(downloader._futures) == 0
def test_create_sleep(): import time from kivy.clock import Clock import asynckivy as ak async def _task(): nonlocal task_state sleep = await ak.create_sleep(.5) task_state = 'A' await sleep() task_state = 'B' await sleep() task_state = 'C' task_state = None Clock.tick() ak.start(_task()) time.sleep(.2) Clock.tick() assert task_state == 'A' time.sleep(.5) Clock.tick() assert task_state == 'B' time.sleep(.5) Clock.tick() assert task_state == 'C'
def test_timeout_case_1(self): global best_score from kivy.clock import Clock from time import sleep best_score = 0 gdb = Recognizer(db=[self.Tbound, self.Ninvar]) r = gdb.recognize([Ncandidate], max_gpf=1, timeout=0.4) Clock.tick() # matches Tbound in this tick self.assertEqual(best_score, 0) sleep(0.4) Clock.tick() # should match Ninv, but times out (got T) self.assertEqual(r.status, 'timeout') self.assertEqual(r.progress, .5) self.assertTrue(r.best['name'] == 'T') self.assertTrue(r.best['score'] < 0.5)
def test_scheduling(self): global best_score from kivy.clock import Clock gdb = Recognizer(db=[self.Tinvar, self.Ninvar]) r = gdb.recognize([Ncandidate], max_gpf=1) r.bind(on_complete=best_score_cb) # _recognize_tick is scheduled here; compares to Tinvar Clock.tick() self.assertEqual(r.progress, .5) self.assertEqual(best_score, .0) # Now complete the search operation Clock.tick() self.assertEqual(r.progress, 1) self.assertTrue(best_score > 0.94 and best_score < 0.95)
def prepare_browser(self, app): app.session = Session() db = SqliteDb() db.init_test_db(app.session) b = Browser() app.root.set_browser(b) b.ready() b.on_switch(loader_thread=False) sleep(0.1) Clock.tick() return b, db
def test_auth_header(self): if os.environ.get('NONETWORK'): return self.queue = [] head = { "Authorization": "Basic {}".format( b64encode("{}:{}".format( 'user', 'passwd').encode('utf-8')).decode('utf-8')) } req = UrlRequest('http://httpbin.org/basic-auth/user/passwd', on_success=self._on_success, on_progress=self._on_progress, on_error=self._on_error, on_redirect=self._on_redirect, req_headers=head, debug=True) # don't use wait, but maximum 10s timeout for i in range(50): Clock.tick() sleep(.5) if req.is_finished: break self.assertTrue(req.is_finished) # we should have 2 progress minimum and one success self.assertTrue(len(self.queue) >= 3) # ensure the callback is called from this thread (main). tid = _thread.get_ident() self.assertEqual(self.queue[0][0], tid) self.assertEqual(self.queue[-2][0], tid) self.assertEqual(self.queue[-1][0], tid) self.assertEqual(self.queue[0][1], 'progress') self.assertEqual(self.queue[-2][1], 'progress') self.assertIn(self.queue[-1][1], ('success', 'redirect')) self.assertEqual(self.queue[-1][2], ({ 'authenticated': True, 'user': '******' }, )) self.assertEqual(self.queue[0][2][0], 0) self.assertEqual(self.queue[-2][2][0], self.queue[-2][2][1])
def test_filechooserlistview_unicode(self): if self.skip_test: return from kivy.uix.filechooser import FileChooserListView from kivy.clock import Clock from os.path import join wid = FileChooserListView(path=self.basepathu) for i in range(1): Clock.tick() files = [join(self.basepathu, f) for f in wid.files] for f in self.ufiles: self.assertIn(f, files) # we cannot test the bfiles because we'd have to know the system # unicode encoding to be able to compare to returned unicode for f in self.exitsfiles: self.assertIn(f, files)
def test_filechooserlistview_unicode(self): from kivy.uix.filechooser import FileChooserListView from kivy.clock import Clock from os.path import join wid = FileChooserListView(path=self.basepathu) for i in range(1): Clock.tick() files = [join(self.basepathu, f) for f in wid.files] for f in self.ufiles: self.assertIn(f, files) # we cannot test the bfiles because we'd have to know the system # unicode encoding to be able to compare to returned unicode for f in self.exitsfiles: self.assertIn(f, files) wid = FileChooserListView(path=self.basepathb) Clock.tick() files = [join(self.basepathb, f) for f in wid.files] for f in self.bfiles: self.assertIn(f, files)
def idle(self): '''This function is called after every frame. By default: * it "ticks" the clock to the next frame. * it reads all input and dispatches events. * it dispatches `on_update`, `on_draw` and `on_flip` events to the window. ''' # update dt Clock.tick() # read and dispatch input from providers self.dispatch_input() # flush all the canvas operation Builder.sync() # tick before draw Clock.tick_draw() # flush all the canvas operation Builder.sync() window = self.window if window and window.canvas.needs_redraw: window.dispatch('on_draw') window.dispatch('on_flip') # don't loop if we don't have listeners ! if len(self.event_listeners) == 0: Logger.error('Base: No event listeners have been created') Logger.error('Base: Application will leave') self.exit() return False return self.quit
def test_timeout_case_2(self): global best_score from kivy.clock import Clock from time import sleep best_score = 0 gdb = Recognizer(db=[self.Tbound, self.Ninvar, self.Tinvar]) r = gdb.recognize([Ncandidate], max_gpf=1, timeout=0.8) Clock.tick() # matches Tbound in this tick self.assertEqual(best_score, 0) sleep(0.4) Clock.tick() # matches Ninvar in this tick sleep(0.4) Clock.tick() # should match Tinvar, but times out self.assertEqual(r.status, 'timeout') self.assertEqual(r.progress, 2 / 3.) self.assertTrue(r.best['score'] >= .94 and r.best['score'] <= .95)
def sleep(self, t): start = time() while time() < start + t: sleep(.01) Clock.tick()
def test_parallel_recognize(self): global counter from kivy.clock import Clock counter = 0 gdb = Recognizer() for i in range(9): gdb.add_gesture('T', [TGesture], priority=50) gdb.add_gesture('N', [NGesture]) r1 = gdb.recognize([Ncandidate], max_gpf=1) r1.bind(on_complete=counter_cb) Clock.tick() # first run scheduled here; 9 left r2 = gdb.recognize([Ncandidate], max_gpf=1) r2.bind(on_complete=counter_cb) Clock.tick() # 8 left r3 = gdb.recognize([Ncandidate], max_gpf=1) r3.bind(on_complete=counter_cb) Clock.tick() # 7 left # run some immediate searches, should not interfere. for i in range(5): n = gdb.recognize([TGesture], max_gpf=0) self.assertEqual(n.best['name'], 'T') self.assertTrue(round(n.best['score'], 1) == 1.0) for i in range(6): Clock.tick() self.assertEqual(counter, 0) Clock.tick() self.assertEqual(counter, 1) Clock.tick() self.assertEqual(counter, 2) Clock.tick() self.assertEqual(counter, 3)
def _clock_sandbox(self, dt): #import pdb; pdb.set_trace() Clock.tick() Builder.sync()
callback will be dispatched from the same thread from which you're calling. .. versionadded:: 1.1.0 ''' while self.resp_status is None: self._dispatch_result(delay) sleep(delay) if __name__ == '__main__': from pprint import pprint def on_success(req, result): pprint('Got the result:') pprint(result) def on_error(req, error): pprint('Got an error:') pprint(error) req = UrlRequest('http://api.twitter.com/1/trends.json', on_success, on_error) while not req.is_finished: sleep(1) Clock.tick() print('result =', req.result) print('error =', req.error)
def test_schedule_once_twice(self): from kivy.clock import Clock Clock.schedule_once(callback) Clock.schedule_once(callback) Clock.tick() self.assertEqual(counter, 2)
def test_unschedule_event(self): from kivy.clock import Clock ev = Clock.schedule_once(callback) Clock.unschedule(ev) Clock.tick() self.assertEqual(counter, 0)
def test_property_rebind(self): from kivy.uix.label import Label from kivy.uix.togglebutton import ToggleButton from kivy.lang import Builder from kivy.properties import ObjectProperty, DictProperty, AliasProperty from kivy.clock import Clock class ObjWidget(Label): button = ObjectProperty(None, rebind=True, allownone=True) class ObjWidgetRebindFalse(Label): button = ObjectProperty(None, rebind=False, allownone=True) class DictWidget(Label): button = DictProperty({'button': None}, rebind=True, allownone=True) class DictWidgetFalse(Label): button = DictProperty({'button': None}, rebind=False) class AliasWidget(Label): _button = None def setter(self, value): self._button = value return True def getter(self): return self._button button = AliasProperty(getter, setter, rebind=True) Builder.load_string(''' <ObjWidget>: text: self.button.state if self.button is not None else 'Unset' <ObjWidgetRebindFalse>: text: self.button.state if self.button is not None else 'Unset' <AliasWidget>: text: self.button.state if self.button is not None else 'Unset' <DictWidget>: text: self.button.button.state if self.button.button is not None\ else 'Unset' <DictWidgetFalse>: text: self.button.button.state if self.button.button is not None\ else 'Unset' ''') obj = ObjWidget() obj_false = ObjWidgetRebindFalse() dict_rebind = DictWidget() dict_false = DictWidgetFalse() alias_rebind = AliasWidget() button = ToggleButton() Clock.tick() self.assertEqual(obj.text, 'Unset') self.assertEqual(obj_false.text, 'Unset') self.assertEqual(dict_rebind.text, 'Unset') self.assertEqual(dict_false.text, 'Unset') self.assertEqual(alias_rebind.text, 'Unset') obj.button = button obj_false.button = button dict_rebind.button.button = button dict_false.button.button = button alias_rebind.button = button Clock.tick() self.assertEqual(obj.text, 'normal') self.assertEqual(obj_false.text, 'normal') self.assertEqual(dict_rebind.text, 'normal') self.assertEqual(dict_false.text, 'Unset') self.assertEqual(alias_rebind.text, 'normal') button.state = 'down' Clock.tick() self.assertEqual(obj.text, 'down') self.assertEqual(obj_false.text, 'normal') self.assertEqual(dict_rebind.text, 'down') self.assertEqual(dict_false.text, 'Unset') self.assertEqual(alias_rebind.text, 'down') button.state = 'normal' Clock.tick() self.assertEqual(obj.text, 'normal') self.assertEqual(obj_false.text, 'normal') self.assertEqual(dict_rebind.text, 'normal') self.assertEqual(dict_false.text, 'Unset') self.assertEqual(alias_rebind.text, 'normal') obj.button = None obj_false.button = None dict_rebind.button.button = None dict_false.button.button = None alias_rebind.button = None Clock.tick() self.assertEqual(obj.text, 'Unset') self.assertEqual(obj_false.text, 'Unset') self.assertEqual(dict_rebind.text, 'Unset') self.assertEqual(dict_false.text, 'Unset') self.assertEqual(alias_rebind.text, 'Unset')
def run(self): o = [] for x in self.labels: o.append(Button(text=x)) # tick for texture creation Clock.tick()
def run(self): o = [] for x in self.labels: o.append(Label(label=x)) # tick for texture creation Clock.tick()