def append(category, key, obj, timeout=None): '''Add a new object to the cache. :Parameters: `category`: str Identifier of the category. `key`: str Unique identifier of the object to store. `obj`: object Object to store in cache. `timeout`: double (optional) Time after which to delete the object if it has not been used. If None, no timeout is applied. ''' #check whether obj should not be cached first if getattr(obj, '_no_cache', False): return try: cat = Cache._categories[category] except KeyError: Logger.warning('Cache: category <%s> not exist' % category) return timeout = timeout or cat['timeout'] # FIXME: activate purge when limit is hit #limit = cat['limit'] #if limit is not None and len(Cache._objects[category]) >= limit: # Cache._purge_oldest(category) Cache._objects[category][key] = { 'object': obj, 'timeout': timeout, 'lastaccess': Clock.get_time(), 'timestamp': Clock.get_time()}
def append(category, key, obj, timeout=None): '''Add a new object in the cache. :Parameters: `category` : str Identifier of the category `key` : str Uniq identifier of the object to store `obj` : object Object to store in cache `timeout` : double (optionnal) Custom time to delete the object if it's not used. ''' try: cat = Cache._categories[category] except KeyError: Logger.warning('Cache: category <%s> not exist' % category) return timeout = timeout or cat['timeout'] # FIXME: activate purge when limit is hit #limit = cat['limit'] #if limit is not None and len(Cache._objects[category]) >= limit: # Cache._purge_oldest(category) Cache._objects[category][key] = { 'object': obj, 'timeout': timeout, 'lastaccess': Clock.get_time(), 'timestamp': Clock.get_time()}
def append(category, key, obj, timeout=None): '''Add a new object to the cache. :Parameters: `category`: str Identifier of the category. `key`: str Unique identifier of the object to store. `obj`: object Object to store in cache. `timeout`: double (optional) Time after which to delete the object if it has not been used. If None, no timeout is applied. ''' # check whether obj should not be cached first if getattr(obj, '_nocache', False): return try: cat = Cache._categories[category] except KeyError: Logger.warning('Cache: category <%s> does not exist' % category) return timeout = timeout or cat['timeout'] limit = cat['limit'] if limit is not None and len(Cache._objects[category]) >= limit: Cache._purge_oldest(category) Cache._objects[category][key] = { 'object': obj, 'timeout': timeout, 'lastaccess': Clock.get_time(), 'timestamp': Clock.get_time()}
def append(category, key, obj, timeout=None): '''Add a new object in the cache. :Parameters: `category` : str Identifier of the category `key` : str Uniq identifier of the object to store `obj` : object Object to store in cache `timeout` : double (optionnal) Custom time to delete the object if it's not used. ''' #check whether obj should not be cached first if getattr(obj, '_no_cache', False): return try: cat = Cache._categories[category] except KeyError: Logger.warning('Cache: category <%s> not exist' % category) return timeout = timeout or cat['timeout'] # FIXME: activate purge when limit is hit #limit = cat['limit'] #if limit is not None and len(Cache._objects[category]) >= limit: # Cache._purge_oldest(category) Cache._objects[category][key] = { 'object': obj, 'timeout': timeout, 'lastaccess': Clock.get_time(), 'timestamp': Clock.get_time() }
def on_touch_up(self, touch): if touch.grab_current is not self: return self._num_touches -= 1 if self._pinch_flag: if self._num_touches == 0: # user was pinching, and now both fingers are up. Return to normal if self.SVidx > touch.ud['orig_SVidx']: Clock.schedule_once( self.inertial_incr_SVidx, (Clock.get_time() - touch.ud['orig_time']) / (self.SVidx - touch.ud['orig_SVidx'])) if self.SVidx < touch.ud['orig_SVidx']: Clock.schedule_once( self.inertial_decr_SVidx, (Clock.get_time() - touch.ud['orig_time']) / (self.SVidx - touch.ud['orig_SVidx'])) self._pinch_flag = False return else: # user was pinching, and at least one finger remains. We don't want to treat the remaining fingers as touches return else: r, theta = rect_to_polar(self.origin, *touch.pos) # if touch up is outside the wheel, ignore if r >= self.radius: return # compute which ColorArc is being touched (they aren't widgets so we don't get collide_point) and set bg_color based on the selected ColorArc piece = int((theta / (2 * pi)) * self.pieces_of_pie) division = int((r / self.radius) * self.piece_divisions) self.bg_color_hsv = self.arcs[self.pieces_of_pie * division + piece].color
def _set_sample_time(self): if self.last_sample == 0.0: self.last_sample = Clock.get_time() else: new_sample = Clock.get_time() new_sample_time = new_sample - self.last_sample self._insert_new_sample(new_sample_time) self.last_sample = new_sample self.avg_sample_time = self._get_avg_from_samples() Clock.unschedule(self._reset_timer) Clock.schedule_once(self._reset_timer, 3)
def append(category, key, obj, timeout=None): '''Add a new object to the cache. :Parameters: `category`: str Identifier of the category. `key`: str Unique identifier of the object to store. `obj`: object Object to store in cache. `timeout`: double (optional) Time after which to delete the object if it has not been used. If None, no timeout is applied. :raises: `ValueError`: If `None` is used as `key`. .. versionchanged:: 2.0.0 Raises `ValueError` if `None` is used as `key`. ''' # check whether obj should not be cached first if getattr(obj, '_nocache', False): return if key is None: # This check is added because of the case when key is None and # one of purge methods gets called. Then loop in purge method will # call Cache.remove with key None which then clears entire # category from Cache making next iteration of loop to raise a # KeyError because next key will not exist. # See: https://github.com/kivy/kivy/pull/6950 raise ValueError('"None" cannot be used as key in Cache') try: cat = Cache._categories[category] except KeyError: Logger.warning('Cache: category <%s> does not exist' % category) return timeout = timeout or cat['timeout'] limit = cat['limit'] if limit is not None and len(Cache._objects[category]) >= limit: Cache._purge_oldest(category) Cache._objects[category][key] = { 'object': obj, 'timeout': timeout, 'lastaccess': Clock.get_time(), 'timestamp': Clock.get_time() }
def game_loop(self, dt): #print 'looping', dt if self.is_shooting and (self.last_bullet is None or Clock.get_time() - self.last_bullet > 0.25): self.add_bullet() self.last_bullet = Clock.get_time() for b in self.bullets: cur_angle = math.atan2((b.y - self.center_y), (b.x - self.center_x)) magnitude = math.sqrt( math.pow(b.y - self.center_y, 2) + math.pow(b.x - self.center_x, 2) ) - 2 b.bullet_size = (magnitude / 200.) * 5. if magnitude < 2: self.bullets.remove(b) self.remove_widget(b) else: b.pos = (self.center_x + math.cos(cur_angle) * magnitude, self.center_y + math.sin(cur_angle) * magnitude)
def on_touch_up(self, touch): if self.collide_point(*touch.pos): if Clock.get_time() - touch.time_start > TOUCH_HOLD_THRESHOLD: self.toggle_guess_bomb() else: self.reveal_square() return True
def update(self, dt): if self.animation: self.animation.apply(skeleton=self.skeleton, time=Clock.get_time() / 2., loop=True) self.skeleton.updateWorldTransform() self.skeleton.draw(self.canvas)
def _purge_by_timeout(dt): curtime = Clock.get_time() for category in Cache._objects: if category not in Cache._categories: continue timeout = Cache._categories[category]['timeout'] if timeout is not None and dt > timeout: # XXX got a lag ! that may be because the frame take lot of # time to draw. and the timeout is not adapted to the current # framerate. So, increase the timeout by two. # ie: if the timeout is 1 sec, and framerate go to 0.7, newly # object added will be automaticly trashed. timeout *= 2 Cache._categories[category]['timeout'] = timeout continue for key in list(Cache._objects[category].keys())[:]: lastaccess = Cache._objects[category][key]['lastaccess'] objtimeout = Cache._objects[category][key]['timeout'] # take the object timeout if available if objtimeout is not None: timeout = objtimeout # no timeout, cancel if timeout is None: continue if curtime - lastaccess > timeout: del Cache._objects[category][key]
def reset_game(self, instance=None, value=None): Logger.info("reset: game") if self.board: self.playing_area.remove_widget(self.board) self.board = GameBoard() self.playing_area.add_widget(self.board) self.start_time = Clock.get_time()
def start(self): print "Discovering start() called" Clock.schedule_once(self.checkIfModeIsCompleted, 1) self.last_touch = Clock.get_time() Clock.schedule_interval(self.checkTimeout, 5) self.pulse()
def process(self, events): if self.triple_tap_distance == 0 or self.triple_tap_time == 0: return events # first, check if a touch down have a triple tap for etype, touch in events: if not touch.is_touch: continue if etype == 'begin': triple_tap = self.find_triple_tap(touch) if triple_tap: touch.is_double_tap = False touch.is_triple_tap = True time = touch.time_start - triple_tap.time_start touch.triple_tap_time = time distance = triple_tap.triple_tap_distance touch.triple_tap_distance = distance # add the touch internaly self.touches[touch.uid] = (etype, touch) # second, check if up-touch is timeout for triple tap time_current = Clock.get_time() for touchid in self.touches.keys()[:]: etype, touch = self.touches[touchid] if etype != 'end': continue if time_current - touch.time_start < self.triple_tap_time: continue del self.touches[touchid] return events
def __init__(self, touch, **kwargs): super(GestureContainer, self).__init__(**kwargs) # This is the touch.uid of the oldest touch represented self.id = str(touch.uid) # Store various timestamps for decision making self._create_time = Clock.get_time() self._update_time = None self._cleanup_time = None self._cache_time = 0 # We can cache the candidate here to save zip()/Vector instantiation self._vectors = None # The color is applied to all canvas items of this gesture col = kwargs.get('color', None) if col is not None: self.color = col else: self.color = [1.0, 1.0, 1.0] # Key is touch.uid; value is a kivy.graphics.Line(); it's used even # if line_width is 0 (ie not actually drawn anywhere) self._strokes = {} # Make sure the bbox is up to date with the first touch position self.update_bbox(touch)
def add_stroke(self, touch, line): '''Associate a list of points with a touch.uid; the line itself is created by the caller, but subsequent move/up events look it up via us. This is done to avoid problems during merge.''' self._update_time = Clock.get_time() self._strokes[str(touch.uid)] = line self.active_strokes += 1
def process(self, events): if self.double_tap_distance == 0 or self.double_tap_time == 0: return events # first, check if a touch down have a double tap for etype, touch in events: if not touch.is_touch: continue if etype == 'begin': double_tap = self.find_double_tap(touch) if double_tap: touch.is_double_tap = True time = touch.time_start - double_tap.time_start touch.double_tap_time = time distance = double_tap.double_tap_distance touch.double_tap_distance = distance # add the touch internaly self.touches[touch.uid] = (etype, touch) # second, check if up-touch is timeout for double tap time_current = Clock.get_time() for touchid in self.touches.keys()[:]: etype, touch = self.touches[touchid] if etype != 'end': continue if time_current - touch.time_start < self.double_tap_time: continue del self.touches[touchid] return events
def start_beat_event(self, dt): now = Clock.get_time() if not self.start_time: self.start_time = now self._start_time = now beat = now - self.start_time if beat > self.time_between_first_beats: self.start_time = now try: self.start_time -= (now - self._start_time) % self.time_between_first_beats # print "now", now # print "self._start_time", self._start_time # print "self.start_time", self.start_time # print "self.time_between_first_beats", self.time_between_first_beats self.on_beat() except ZeroDivisionError: print " " print " " print " " print "saved from ZeroDivisionError in start_beat_event()" print "now", now print "self._start_time", self._start_time print "self.start_time", self.start_time print "self.time_between_first_beats", self.time_between_first_beats print " " print " " print " "
def _purge_by_timeout(dt): curtime = Clock.get_time() for category in Cache._objects: if category not in Cache._categories: continue timeout = Cache._categories[category]['timeout'] if timeout is not None and dt > timeout: # XXX got a lag ! that may be because the frame take lot of # time to draw. and the timeout is not adapted to the current # framerate. So, increase the timeout by two. # ie: if the timeout is 1 sec, and framerate go to 0.7, newly # object added will be automatically trashed. timeout *= 2 Cache._categories[category]['timeout'] = timeout continue for key in list(Cache._objects[category].keys())[:]: lastaccess = Cache._objects[category][key]['lastaccess'] objtimeout = Cache._objects[category][key]['timeout'] # take the object timeout if available if objtimeout is not None: timeout = objtimeout # no timeout, cancel if timeout is None: continue if curtime - lastaccess > timeout: del Cache._objects[category][key]
def updateSlideShow(self, dtime): # do not continue with updates, if stop requested if self.state == EState.STOPSHOW: return False # if enough time passed, since the last change of the image # then add a new image into the list of currently visible images currentTime = Clock.get_time() if currentTime > self.slideShowLastTimestamp: # select randomly a file from all available files # the selected files get it's probability reduced idx = np.random.choice(len(self.slideShowAvailableFiles), 1, self.slideShowAvailableFileProbabilities) self.slideShowAvailableFileProbabilities[idx] *= 0.75 # create a new image from the selected file, this will be shown def _addImageStartScrolling(pic): width = randint(float(self.root.width)/2.5, float(self.root.width)/1.5) pic.keep_aspect = True pic.size = (width, width) pic.x = uniform(-width/3., self.root.width - width + width/3.) pic.y = -pic.size[1] pic.rotation = uniform(-25,25) self.slideShowCurrentPictures.append( (pic, uniform(100,200)) ) self.root.add_widget(pic,1) pic = Picture(self.slideShowAvailableFiles[idx], _addImageStartScrolling, pictureMaxTexSize) # repeat the process in X seconds self.slideShowLastTimestamp = currentTime + 2.0 pass # all images which are currently available, are scrolled through the screen validPictures = [] for (pic,speed) in self.slideShowCurrentPictures: pic.y += dtime * speed if pic.y < self.root.height: validPictures.append( (pic,speed) ) else: def _removeImage(w): Cache.remove('kv.image') Cache.remove('kv.texture') Cache.remove('kv.loader') self.root.remove_widget(w) anim = Animation(alpha=0, duration=0.5) anim.bind(on_complete = lambda a,w: _removeImage(w)) anim.start(pic) self.slideShowCurrentPictures = validPictures # continue updates return True pass
def trigger_back(self): isdoubleback = True actually_prev_timestamp = self.prev_back_timestamp self.prev_back_timestamp = Clock.get_time() if self.prev_back_timestamp - actually_prev_timestamp > 1: isdoubleback = False self.dispatch('on_back', isdoubleback)
def trigger_back(self): isdoubleback = True actually_prev_timestamp = self.prev_back_timestamp self.prev_back_timestamp = Clock.get_time() if self.prev_back_timestamp - actually_prev_timestamp > 1 : isdoubleback = False self.dispatch('on_back', isdoubleback)
def update(self, dt): # print("update") if not self.pause: if self.animation: self.animation.apply(skeleton=self.skeleton, time=Clock.get_time() / 2., loop=True) self.skeleton.setPosisiton(skeletonX, skeletonY) self.skeleton.updateWorldTransform() self.skeleton.draw(self.canvas)
def update_contour(self, *args): _, _, self.contourplot.data[:] = self.make_contour_data(Clock.get_time()) # this does not trigger an update, because we replace the # values of the arry and do not change the object. # However, we cannot do "...data = make_contour_data()" as # kivy will try to check for the identity of the new and # old values. In numpy, 'nd1 == nd2' leads to an error # (you have to use np.all). Ideally, property should be patched # for this. self.contourplot.ask_draw()
def my_turn(self, time_left, word): self.bottom_buttons.clear_widgets() self.bottom_buttons.add_widget(self.word_guessed_button) self.start_time = Clock.get_time() self.turn_time = time_left self.word_label.text = word def count_downer(interval): self.time_label.text = str(round(self.time_remaining())) self.count_downer = count_downer Clock.schedule_interval(self.count_downer, 1.0)
def test_timestamp_and_lastaccess(test_file): Cache.remove(RESOURCE_CACHE) start = Clock.get_time() resource_find(test_file) ts = Cache.get_timestamp(RESOURCE_CACHE, test_file) last_access = Cache.get_lastaccess(RESOURCE_CACHE, test_file) assert ts >= start, 'Last timestamp not accurate.' assert last_access >= start, 'Last access time is not accurate.'
def game_loop(self, dt): #print 'looping', dt if self.is_shooting and (self.last_bullet is None or Clock.get_time() - self.last_bullet > 0.25): self.add_bullet() self.last_bullet = Clock.get_time() for b in self.bullets: cur_angle = math.atan2((b.y - self.center_y), (b.x - self.center_x)) magnitude = math.sqrt( math.pow(b.y - self.center_y, 2) + math.pow(b.x - self.center_x, 2)) - 2 b.bullet_size = (magnitude / 200.) * 5. if magnitude < 2: self.bullets.remove(b) self.remove_widget(b) else: b.pos = (self.center_x + math.cos(cur_angle) * magnitude, self.center_y + math.sin(cur_angle) * magnitude)
def on_enter(self, *args): """Call the setter and blank myself out so that my hint text shows up. It will be the same you just entered if everything's working. """ if self.text == '': return self.set_value(Clock.get_time(), int(self.text)) self.text = '' self.focus = False
def __init__(self, **kwargs): self._win = None self._cursor_blink_time = Clock.get_time() self._cursor = [0, 0] self._selection = False self._selection_finished = True self._selection_touch = None self.selection_text = "" self.selection_from = None self.selection_to = None self._bubble = None self._lines_flags = [] self._lines_labels = [] self._lines_rects = [] self._line_spacing = 0 self._label_cached = None self._line_options = None self._keyboard = None self.interesting_keys = { 8: "backspace", 13: "enter", 127: "del", 271: "enter", 273: "cursor_up", 274: "cursor_down", 275: "cursor_right", 276: "cursor_left", 278: "cursor_home", 279: "cursor_end", 280: "cursor_pgup", 281: "cursor_pgdown", 303: "shift_L", 304: "shift_R", } self.register_event_type("on_text_validate") super(TextInput, self).__init__(**kwargs) self.bind(font_size=self._trigger_refresh_line_options, font_name=self._trigger_refresh_line_options) self.bind( padding_x=self._trigger_refresh_text, padding_y=self._trigger_refresh_text, tab_width=self._trigger_refresh_text, font_size=self._trigger_refresh_text, font_name=self._trigger_refresh_text, size=self._trigger_refresh_text, ) self.bind(pos=self._trigger_update_graphics) self._trigger_refresh_line_options() self._trigger_refresh_text()
def _purge_oldest(category, maxpurge=1): print('PURGE', category) import heapq time = Clock.get_time() heap_list = [] for key in Cache._objects[category]: obj = Cache._objects[category][key] if obj['lastaccess'] == obj['timestamp'] == time: continue heapq.heappush(heap_list, (obj['lastaccess'], key)) print('<<<', obj['lastaccess']) n = 0 while n <= maxpurge: try: n += 1 lastaccess, key = heapq.heappop(heap_list) print(n, '=>', key, lastaccess, Clock.get_time()) except Exception: return Cache.remove(category, key)
def _update_color(self, dt): places = [player['place'] for player in self.players.itervalues()] delta = abs(cos(Clock.get_time() * 3)) * 0.4 if 1 in places: self.view.c1.a = 0.55 + delta if 2 in places: self.view.c2.a = 0.55 + delta if 3 in places: self.view.c3.a = 0.55 + delta if 4 in places: self.view.c4.a = 0.55 + delta
def load_contacts(self, interval): if not self.dialog_load_contact: self.dialog_load_contact = dialog( title=data.string_lang_wait[:-3], text=data.string_lang_contacts_load, dismiss=False) while _default_time() < (Clock.get_time() + MAX_TIME): self.show_contacts(self.info_contacts) self.dialog_load_contact.dismiss() Clock.unschedule(self.load_contacts)
def start_activation_timer(self): """Reset the activation timer to its initial state. This method resets the timer that determines when the enemy is activated. It should only be called when a new game or level is started. """ Clock.unschedule(self.__activate) self.activation_timer_start = Clock.get_time() Clock.schedule_once(self.__activate, self.activation_timer)
def update_contour(self, *args): _, _, self.contourplot.data[:] = self.make_contour_data( Clock.get_time()) # this does not trigger an update, because we replace the # values of the arry and do not change the object. # However, we cannot do "...data = make_contour_data()" as # kivy will try to check for the identity of the new and # old values. In numpy, 'nd1 == nd2' leads to an error # (you have to use np.all). Ideally, property should be patched # for this. self.contourplot.ask_draw()
def __init__(self, **kwargs): super(MinesweeperGame, self).__init__(**kwargs) self._keyboard = Window.request_keyboard(self.close, self) self._keyboard.bind(on_key_down=self.press) self.num_bombs_left = NUMBER_OF_BOMBS self.timer = 999 self.start_time = Clock.get_time() self.best_time = 9999 self.board = GameBoard() self.playing_area.add_widget(self.board) Clock.schedule_interval(self.timer_callback, 1.0)
def _purge_oldest(category, maxpurge=1): Logger.trace('Cache: Remove oldest in %s' % category) import heapq time = Clock.get_time() heap_list = [] for key in Cache._objects[category]: obj = Cache._objects[category][key] if obj['lastaccess'] == obj['timestamp'] == time: continue heapq.heappush(heap_list, (obj['lastaccess'], key)) Logger.trace('Cache: <<< %f' % obj['lastaccess']) n = 0 while n <= maxpurge: try: n += 1 lastaccess, key = heapq.heappop(heap_list) Logger.trace('Cache: %d => %s %f %f' % (n, key, lastaccess, Clock.get_time())) except Exception: return Cache.remove(category, key)
def __init__(self, **kwargs): self._win = None self._cursor_blink_time = Clock.get_time() self._cursor = [0, 0] self._selection = False self._selection_finished = True self._selection_touch = None self.selection_text = '' self.selection_from = None self.selection_to = None self._bubble = None self._lines_flags = [] self._lines_labels = [] self._lines_rects = [] self._line_spacing = 0 self._label_cached = None self._line_options = None self._keyboard = None self.interesting_keys = { 8: 'backspace', 13: 'enter', 127: 'del', 271: 'enter', 273: 'cursor_up', 274: 'cursor_down', 275: 'cursor_right', 276: 'cursor_left', 278: 'cursor_home', 279: 'cursor_end', 280: 'cursor_pgup', 281: 'cursor_pgdown', 303: 'shift_L', 304: 'shift_R' } self.register_event_type('on_text_validate') super(TextInput, self).__init__(**kwargs) self.bind(font_size=self._trigger_refresh_line_options, font_name=self._trigger_refresh_line_options) self.bind(padding_x=self._trigger_refresh_text, padding_y=self._trigger_refresh_text, tab_width=self._trigger_refresh_text, font_size=self._trigger_refresh_text, font_name=self._trigger_refresh_text, size=self._trigger_refresh_text) self.bind(pos=self._trigger_update_graphics) self._trigger_refresh_line_options() self._trigger_refresh_text()
def on_touch_up(self, touch): if touch.grab_current is not self: return touch.ungrab(self) self._num_touches -= 1 if self._pinch_flag: if self._num_touches == 0: # user was pinching, and now both fingers are up. Return # to normal if self.sv_idx > touch.ud['orig_sv_idx']: Clock.schedule_once( self.inertial_incr_sv_idx, (Clock.get_time() - touch.ud['orig_time']) / (self.sv_idx - touch.ud['orig_sv_idx'])) if self.sv_idx < touch.ud['orig_sv_idx']: Clock.schedule_once( self.inertial_decr_sv_idx, (Clock.get_time() - touch.ud['orig_time']) / (self.sv_idx - touch.ud['orig_sv_idx'])) self._pinch_flag = False return else: # user was pinching, and at least one finger remains. We # don't want to treat the remaining fingers as touches return else: r, theta = rect_to_polar(self._origin, *touch.pos) # if touch up is outside the wheel, ignore if r >= self._radius: return # compute which ColorArc is being touched (they aren't # widgets so we don't get collide_point) and set # _hsv based on the selected ColorArc piece = int((theta / (2 * pi)) * self._pieces_of_pie) division = int((r / self._radius) * self._piece_divisions) hsva = list( self.arcs[self._pieces_of_pie * division + piece].color) self.color = list(hsv_to_rgb(*hsva[:3])) + hsva[-1:]
def __init__(self, **kwargs): self._win = None self._cursor_blink_time = Clock.get_time() self._cursor = [0, 0] self._selection = False self._selection_finished = True self._selection_touch = None self.selection_text = '' self.selection_from = None self.selection_to = None self._bubble = None self._lines_flags = [] self._lines_labels = [] self._lines_rects = [] self._line_spacing = 0 self._label_cached = None self._line_options = None self._keyboard = None self.interesting_keys = { 8: 'backspace', 13: 'enter', 127: 'del', 271: 'enter', 273: 'cursor_up', 274: 'cursor_down', 275: 'cursor_right', 276: 'cursor_left', 278: 'cursor_home', 279: 'cursor_end', 280: 'cursor_pgup', 281: 'cursor_pgdown', 303: 'shift_L', 304: 'shift_R'} self.register_event_type('on_text_validate') super(TextInput, self).__init__(**kwargs) self.bind(font_size=self._trigger_refresh_line_options, font_name=self._trigger_refresh_line_options) self.bind(padding_x=self._trigger_refresh_text, padding_y=self._trigger_refresh_text, tab_width=self._trigger_refresh_text, font_size=self._trigger_refresh_text, font_name=self._trigger_refresh_text, size=self._trigger_refresh_text) self.bind(pos=self._trigger_update_graphics) self._trigger_refresh_line_options() self._trigger_refresh_text()
def _cleanup(self, dt): '''This method is scheduled from _complete_dispatcher to clean up the canvas and internal gesture list after a gesture is completed.''' m = UNDERSHOOT_MARGIN rg = self.canvas.remove_group gestures = self._gestures for idx, g in enumerate(gestures): if g._cleanup_time is None: continue if g._cleanup_time <= Clock.get_time() + m: rg(g.id) del gestures[idx] self.dispatch('on_gesture_cleanup', g)
def one_cmd(self, cmd_line): "Run cmd exec" # Parse cmd (cmd, args) = self.parse_line(cmd_line) # Search for command try: func = getattr(self, 'cmd_' + cmd) except AttributeError: self.default_cmd(cmd) else: func(args) Logger.debug("CORE: @{} {}".format(Clock.get_time(), cmd_line))
def on_touch_down(self, touch): r = self._get_touch_r(touch.pos) if r > self.radius: return False # code is still set up to allow pinch to zoom, but this is disabled for now since it was fiddly with # small wheels. Comment out these lines and adjust on_touch_move to reenable this. if self._num_touches != 0: return False touch.grab(self) self._num_touches += 1 touch.ud['anchor_r'] = r touch.ud['orig_SVidx'] = self.SVidx touch.ud['orig_time'] = Clock.get_time()
def update_bbox(self, touch): '''Update gesture bbox from a touch coordinate''' x, y = touch.x, touch.y bb = self.bbox if x < bb['minx']: bb['minx'] = x if y < bb['miny']: bb['miny'] = y if x > bb['maxx']: bb['maxx'] = x if y > bb['maxy']: bb['maxy'] = y self.width = bb['maxx'] - bb['minx'] self.height = bb['maxy'] - bb['miny'] self._update_time = Clock.get_time()
def get(category, key, default=None): '''Get a object from the cache. :Parameters: `category`: str Identifier of the category. `key`: str Unique identifier of the object in the store. `default`: anything, defaults to None Default value to be returned if the key is not found. ''' try: Cache._objects[category][key]['lastaccess'] = Clock.get_time() return Cache._objects[category][key]['object'] except Exception: return default
def __pause_mode_change(self): """Pause the mode change timers. This method pauses the chase/scatter mode change timers. It should be called when the enemies become frightened. """ Clock.unschedule(self.__change_mode) pause_time = Clock.get_time() time_into_mode = pause_time - self.mode_change_start if self.chasing: self.mode_time_remaining = self.chase_length - time_into_mode elif not self.chasing: self.mode_time_remaining = self.scatter_length - time_into_mode
def get(category, key, default=None): '''Get a object in cache. :Parameters: `category` : str Identifier of the category `key` : str Uniq identifier of the object to store `default` : anything, default to None Default value to be returned if key is not found ''' try: Cache._objects[category][key]['lastaccess'] = Clock.get_time() return Cache._objects[category][key]['object'] except Exception: return default
def merge_gestures(self, g, other): '''Merges two gestures together, the oldest one is retained and the newer one gets the `GestureContainer.was_merged` flag raised.''' # Swap order depending on gesture age (the merged gesture gets # the color from the oldest one of the two). swap = other._create_time < g._create_time a = swap and other or g b = swap and g or other # Apply the outer limits of bbox to the merged gesture abbox = a.bbox bbbox = b.bbox if bbbox['minx'] < abbox['minx']: abbox['minx'] = bbbox['minx'] if bbbox['miny'] < abbox['miny']: abbox['miny'] = bbbox['miny'] if bbbox['maxx'] > abbox['maxx']: abbox['maxx'] = bbbox['maxx'] if bbbox['maxy'] > abbox['maxy']: abbox['maxy'] = bbbox['maxy'] # Now transfer the coordinates from old to new gesture; # FIXME: This can probably be copied more efficiently? astrokes = a._strokes lw = self.line_width a_id = a.id col = a.color self.canvas.remove_group(b.id) canv_add = self.canvas.add for uid, old in b._strokes.items(): # FIXME: Can't figure out how to change group= for existing Line() new_line = Line( points=old.points, width=old.width, group=a_id) astrokes[uid] = new_line if lw: canv_add(Color(col[0], col[1], col[2], mode='rgb', group=a_id)) canv_add(new_line) b.active = False b.was_merged = True a.active_strokes += b.active_strokes a._update_time = Clock.get_time() return a
def on_touch_up(self, touch): # check if mode is complete before so I can read the text. # Next touch will throw a message to the server self.last_touch = Clock.get_time() self.checkIfModeIsCompleted() # Clock.schedule_once(self.checkIfModeIsCompleted(), 5.0) for shape in self.shapes: # add interaction if shape.collide_point(*touch.pos): if self.children.count(self.descFor(shape)) < 1: # displays text box print self.descFor(shape) self.add_widget(self.descFor(shape)) shape.viewed = True
def _purge_oldest(category, maxpurge=1): print 'PURGE', category import heapq heap_list = [] for key in Cache._objects[category]: obj = Cache._objects[category][key] if obj['lastaccess'] == obj['timestamp']: continue heapq.heappush(heap_list, (obj['lastaccess'], key)) print '<<<', obj['lastaccess'] n = 0 while n < maxpurge: try: lastaccess, key = heapq.heappop(heap_list) print '=>', key, lastaccess, Clock.get_time() except Exception: return del Cache._objects[category][key]
def update_points(self, *args): if False: if self.all_points2_idx < len(self.all_points2): self.all_points2_idx += 1 self.graph.add_points( {'cos': self.all_points2[:self.all_points2_idx]}, isUpdate=False) elif True: if self.all_points2_idx < len(self.all_points2): self.graph.add_points( { 'cos': self.all_points2[self.all_points2_idx:self. all_points2_idx + 2] }, isUpdate=True) self.all_points2_idx += 2 else: all_points = [(x / 10., cos(Clock.get_time() + x / 50.)) for x in range(-500, 501)] self.graph.add_points({'cos': all_points}, isUpdate=False) pass