INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
width in pixels
def width(self): """width in pixels""" alloc_w = self.alloc_w if self.parent and isinstance(self.parent, graphics.Scene): alloc_w = self.parent.width def res(scene, event): if self.parent: self.queue_resize() else: ...
height in pixels
def height(self): """height in pixels""" alloc_h = self.alloc_h if self.parent and isinstance(self.parent, graphics.Scene): alloc_h = self.parent.height min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom h = alloc_h if alloc_h is not None and...
whether the user is allowed to interact with the widget. Item is enabled only if all it's parent elements are
def enabled(self): """whether the user is allowed to interact with the widget. Item is enabled only if all it's parent elements are""" enabled = self._enabled if not enabled: return False if self.parent and isinstance(self.parent, Widget): if self.parent....
default container alignment is to pile stuff just up, respecting only padding, margin and element's alignment properties
def resize_children(self): """default container alignment is to pile stuff just up, respecting only padding, margin and element's alignment properties""" width = self.width - self.horizontal_padding height = self.height - self.vertical_padding for sprite, props in (get_props(spr...
refresh hamster every x secs - load today, check last activity etc.
def check_hamster(self): """refresh hamster every x secs - load today, check last activity etc.""" try: # can't use the client because then we end up in a dbus loop # as this is initiated in storage todays_facts = self.storage._Storage__get_todays_facts() ...
check if we need to notify user perhaps
def check_user(self, todays_facts): """check if we need to notify user perhaps""" interval = self.conf_notify_interval if interval <= 0 or interval >= 121: return now = dt.datetime.now() message = None last_activity = todays_facts[-1] if todays_facts else No...
Stops tracking the current activity
def stop_tracking(self, end_time): """Stops tracking the current activity""" facts = self.__get_todays_facts() if facts and not facts[-1]['end_time']: self.__touch_fact(facts[-1], end_time) self.facts_changed()
Remove fact from storage by it's ID
def remove_fact(self, fact_id): """Remove fact from storage by it's ID""" self.start_transaction() fact = self.__get_fact(fact_id) if fact: self.__remove_fact(fact_id) self.facts_changed() self.end_transaction()
loads interface from the glade file; sorts out the path business
def load_ui_file(name): """loads interface from the glade file; sorts out the path business""" ui = gtk.Builder() ui.add_from_file(os.path.join(runtime.data_dir, name)) return ui
Appends the GCONF_PREFIX to the key if needed @param key: The key to check @type key: C{string} @returns: The fixed key @rtype: C{string}
def _fix_key(self, key): """ Appends the GCONF_PREFIX to the key if needed @param key: The key to check @type key: C{string} @returns: The fixed key @rtype: C{string} """ if not key.startswith(self.GCONF_DIR): return self.GCONF_DIR + key ...
Callback when a gconf key changes
def _key_changed(self, client, cnxn_id, entry, data=None): """ Callback when a gconf key changes """ key = self._fix_key(entry.key)[len(self.GCONF_DIR):] value = self._get_value(entry.value, self.DEFAULTS[key]) self.emit('conf-changed', key, value)
calls appropriate gconf function by the default value
def _get_value(self, value, default): """calls appropriate gconf function by the default value""" vtype = type(default) if vtype is bool: return value.get_bool() elif vtype is str: return value.get_string() elif vtype is int: return value.get_...
Returns the value of the key or the default value if the key is not yet in gconf
def get(self, key, default=None): """ Returns the value of the key or the default value if the key is not yet in gconf """ #function arguments override defaults if default is None: default = self.DEFAULTS.get(key, None) vtype = type(default) ...
Sets the key value in gconf and connects adds a signal which is fired if the key changes
def set(self, key, value): """ Sets the key value in gconf and connects adds a signal which is fired if the key changes """ logger.debug("Settings %s -> %s" % (key, value)) if key in self.DEFAULTS: vtype = type(self.DEFAULTS[key]) else: vty...
Start of the hamster day.
def day_start(self): """Start of the hamster day.""" day_start_minutes = self.get("day_start_minutes") hours, minutes = divmod(day_start_minutes, 60) return dt.time(hours, minutes)
Make sure fact has the correct start_time.
def localized_fact(self): """Make sure fact has the correct start_time.""" fact = Fact(self.activity.get_text()) if fact.start_time: fact.date = self.date else: fact.start_time = dt.datetime.now() return fact
creates a list of row positions for simpler manipulation
def set_row_positions(self): """creates a list of row positions for simpler manipulation""" self.row_positions = [i * self.row_height for i in range(len(self.rows))] self.set_size_request(0, self.row_positions[-1] + self.row_height if self.row_positions else 0)
* from previous activity | set time | minutes ago | start now * to ongoing | set time * activity * [@category] * #tags, #tags, #tags * we will leave description for later all our magic is space separated, strictly, start-end can be just dash ...
def update_suggestions(self, text=""): """ * from previous activity | set time | minutes ago | start now * to ongoing | set time * activity * [@category] * #tags, #tags, #tags * we will leave description for later all our mag...
unpack the struct into a proper dict
def from_dbus_fact(fact): """unpack the struct into a proper dict""" return Fact(fact[4], start_time = dt.datetime.utcfromtimestamp(fact[1]), end_time = dt.datetime.utcfromtimestamp(fact[2]) if fact[2] else None, description = fact[3], activity_id...
Add fact. activity name can use the `[-]start_time[-end_time] activity@category, description #tag1 #tag2` syntax, or params can be stated explicitly. Params will take precedence over the derived values. start_time defaults to current moment.
def add_fact(self, fact, temporary_activity = False): """Add fact. activity name can use the `[-]start_time[-end_time] activity@category, description #tag1 #tag2` syntax, or params can be stated explicitly. Params will take precedence over the derived values. start_time defaults ...
Returns facts for the time span matching the optional filter criteria. In search terms comma (",") translates to boolean OR and space (" ") to boolean AND. Filter is applied to tags, categories, activity names and description ongoing_days (int): look into the last `ongoing_da...
def get_facts(self, date, end_date=None, search_terms="", ongoing_days=0): """Returns facts for the time span matching the optional filter criteria. In search terms comma (",") translates to boolean OR and space (" ") to boolean AND. Filter is applied to tags, categories, activi...
returns list of all tags. by default only those that have been set for autocomplete
def get_tags(self, only_autocomplete = False): """returns list of all tags. by default only those that have been set for autocomplete""" return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTags(only_autocomplete))
Stop tracking current activity. end_time can be passed in if the activity should have other end time than the current moment
def stop_tracking(self, end_time = None): """Stop tracking current activity. end_time can be passed in if the activity should have other end time than the current moment""" end_time = timegm((end_time or dt.datetime.now()).timetuple()) return self.conn.StopTracking(end_time)
Update fact values. See add_fact for rules. Update is performed via remove/insert, so the fact_id after update should not be used anymore. Instead use the ID from the fact dict that is returned by this function
def update_fact(self, fact_id, fact, temporary_activity = False): """Update fact values. See add_fact for rules. Update is performed via remove/insert, so the fact_id after update should not be used anymore. Instead use the ID from the fact dict that is returned by this function""" ...
Return activities for category. If category is not specified, will return activities that have no category
def get_category_activities(self, category_id = None): """Return activities for category. If category is not specified, will return activities that have no category""" category_id = category_id or -1 return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryAct...
returns activity dict by name and optionally filtering by category. if activity is found but is marked as deleted, it will be resurrected unless told otherwise in the resurrect param
def get_activity_by_name(self, activity, category_id = None, resurrect = True): """returns activity dict by name and optionally filtering by category. if activity is found but is marked as deleted, it will be resurrected unless told otherwise in the resurrect param """ cate...
enables and disables action buttons depending on selected item
def category_changed_cb(self, selection, model): """ enables and disables action buttons depending on selected item """ (model, iter) = selection.get_selected() id = 0 if iter is None: self.activity_store.clear() else: self.prev_selected_activity = None ...
enables and disables action buttons depending on selected item
def activity_changed(self, selection, model): """ enables and disables action buttons depending on selected item """ (model, iter) = selection.get_selected() # treat any selected case unsorted_selected = self._get_selected_category() == -1 self.get_widget('activity_edit').set_se...
appends row, jumps to it and allows user to input name
def on_category_add_clicked(self, button): """ appends row, jumps to it and allows user to input name """ new_category = self.category_store.insert_before(self.category_store.unsorted_category, [-2, _("New category")]) model = self.categ...
appends row, jumps to it and allows user to input name
def on_activity_add_clicked(self, button): """ appends row, jumps to it and allows user to input name """ category_id = self._get_selected_category() new_activity = self.activity_store.append([-1, _("New activity"), category_id]) (model, iter) = self.selection.get_selected() s...
Inspect the bus for screensaver messages of interest
def bus_inspector(self, bus, message): """ Inspect the bus for screensaver messages of interest """ # We only care about stuff on this interface. We did filter # for it above, but even so we still hear from ourselves # (hamster messages). if message.get_interfac...
Provide qualified translatable strings via context. Taken from gnome-games.
def C_(ctx, s): """Provide qualified translatable strings via context. Taken from gnome-games. """ translated = gettext.gettext('%s\x04%s' % (ctx, s)) if '\x04' in translated: # no translation found, return input string return s return translated
set attributes for class. @param cls [any class]: the class to update the given attributes in. @param kw [dictionary]: dictionary of attributes names and values. if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class.
def def_attrs(cls,**kw): ''' set attributes for class. @param cls [any class]: the class to update the given attributes in. @param kw [dictionary]: dictionary of attributes names and values. if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class. ''' for k,v i...
load_tool: import a Python module, optionally using several directories. @param tool [string]: name of tool to import. @param tooldir [list]: directories to look for the tool. @return: the loaded module. Warning: this function is not thread-safe: plays with sys.path, so must run in sequence.
def load_tool(tool,tooldir=None): ''' load_tool: import a Python module, optionally using several directories. @param tool [string]: name of tool to import. @param tooldir [list]: directories to look for the tool. @return: the loaded module. Warning: this function is not thread-safe: plays with sys.path, s...
removes the build files
def clean(bld): '''removes the build files''' try: proj=Environment.Environment(Options.lockfile) except IOError: raise Utils.WafError('Nothing to clean (project not configured)') bld.load_dirs(proj[SRCDIR],proj[BLDDIR]) bld.load_envs() bld.is_install=0 bld.add_subdirs([os.path.split(Utils.g_module.root_path...
installs the build files
def install(bld): '''installs the build files''' bld=check_configured(bld) Options.commands['install']=True Options.commands['uninstall']=False Options.is_install=True bld.is_install=INSTALL build_impl(bld) bld.install()
removes the installed files
def uninstall(bld): '''removes the installed files''' Options.commands['install']=False Options.commands['uninstall']=True Options.is_install=True bld.is_install=UNINSTALL try: def runnable_status(self): return SKIP_ME setattr(Task.Task,'runnable_status_back',Task.Task.runnable_status) setattr(Task.Task,...
removes the build directory
def distclean(ctx=None): '''removes the build directory''' global commands lst=os.listdir('.') for f in lst: if f==Options.lockfile: try: proj=Environment.Environment(f) except: Logs.warn('could not read %r'%f) continue try: shutil.rmtree(proj[BLDDIR]) except IOError: pass excep...
makes a tarball for redistributing the sources
def dist(appname='',version=''): '''makes a tarball for redistributing the sources''' import tarfile if not appname:appname=Utils.g_module.APPNAME if not version:version=Utils.g_module.VERSION tmp_folder=appname+'-'+version if g_gz in['gz','bz2']: arch_name=tmp_folder+'.tar.'+g_gz else: arch_name=tmp_folder+...
checks if the sources compile (tarball from 'dist')
def distcheck(appname='',version='',subdir=''): '''checks if the sources compile (tarball from 'dist')''' import tempfile,tarfile if not appname:appname=Utils.g_module.APPNAME if not version:version=Utils.g_module.VERSION waf=os.path.abspath(sys.argv[0]) tarball=dist(appname,version) path=appname+'-'+version if...
setting suggested name to something readable, replace backslashes with dots so the name is valid in linux
def show(self, start_date, end_date): """setting suggested name to something readable, replace backslashes with dots so the name is valid in linux""" # title in the report file name vars = {"title": _("Time track"), "start": start_date.strftime("%x").replace("/", ".")...
Add tween for the object to go from current values to set ones. Example: add_tween(sprite, x = 500, y = 200, duration = 0.4) This will move the sprite to coordinates (500, 200) in 0.4 seconds. For parameter "easing" you can use one of the pytweener.Easing functions, or sp...
def add_tween(self, obj, duration = None, easing = None, on_complete = None, on_update = None, round = False, delay = None, **kwargs): """ Add tween for the object to go from current values to set ones. Example: add_tween(sprite, x = 500, y = 200, duration = 0.4) ...
Stop tweening an object, without completing the motion or firing the on_complete
def kill_tweens(self, obj = None): """Stop tweening an object, without completing the motion or firing the on_complete""" if obj is not None: try: del self.current_tweens[obj] except: pass else: self.current_tweens = col...
remove given tween without completing the motion or firing the on_complete
def remove_tween(self, tween): """"remove given tween without completing the motion or firing the on_complete""" if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]: self.current_tweens[tween.target].remove(tween) if not self.current_tweens[tween...
jump the the last frame of all tweens
def finish(self): """jump the the last frame of all tweens""" for obj in self.current_tweens: for tween in self.current_tweens[obj]: tween.finish() self.current_tweens = {}
update tweeners. delta_seconds is time in seconds since last frame
def update(self, delta_seconds): """update tweeners. delta_seconds is time in seconds since last frame""" for obj in tuple(self.current_tweens): for tween in tuple(self.current_tweens[obj]): done = tween.update(delta_seconds) if done: self...
Update tween with the time since the last frame
def update(self, ptime): """Update tween with the time since the last frame""" delta = self.delta + ptime total_duration = self.delay + self.duration if delta > total_duration: delta = total_duration if delta < self.delay: pass elif delta == tota...
expects a list of key, value to work with
def set_items(self, items): """expects a list of key, value to work with""" res = [] max_value = max(sum((rec[1] for rec in items)), 1) for key, val in items: res.append((key, val, val * 1.0 / max_value)) self._items = res
expects a list of 2-tuples
def set_values(self, values): """expects a list of 2-tuples""" self.values = values self.height = len(self.values) * 14 self._max = max(rec[1] for rec in values) if values else dt.timedelta(0)
Start now a new fact. clone_selected (bool): whether to start a clone of currently selected fact or to create a new fact from scratch. fallback (bool): if True, fall back to creating from scratch in case of no selected fact.
def start_new_fact(self, clone_selected=True, fallback=True): """Start now a new fact. clone_selected (bool): whether to start a clone of currently selected fact or to create a new fact from scratch. fallback (bool): if True, fall back to creating from scratch ...
Return the hamster day corresponding to a given civil datetime. The hamster day start is taken into account.
def datetime_to_hamsterday(civil_date_time): """Return the hamster day corresponding to a given civil datetime. The hamster day start is taken into account. """ # work around cyclic imports from hamster.lib.configuration import conf if civil_date_time.time() < conf.day_start: # early ...
Return the civil datetime corresponding to a given hamster day and time. The hamster day start is taken into account.
def hamsterday_time_to_datetime(hamsterday, time): """Return the civil datetime corresponding to a given hamster day and time. The hamster day start is taken into account. """ # work around cyclic imports from hamster.lib.configuration import conf if time < conf.day_start: # early mor...
formats duration in a human readable format. accepts either minutes or timedelta
def format_duration(minutes, human = True): """formats duration in a human readable format. accepts either minutes or timedelta""" if isinstance(minutes, dt.timedelta): minutes = duration_minutes(minutes) if not minutes: if human: return "" else: return ...
returns minutes from duration, otherwise we keep bashing in same math
def duration_minutes(duration): """returns minutes from duration, otherwise we keep bashing in same math""" if isinstance(duration, list): res = dt.timedelta() for entry in duration: res += entry return duration_minutes(res) elif isinstance(duration, dt.timedelta): ...
figure if week starts on monday or sunday
def locale_first_weekday(): """figure if week starts on monday or sunday""" first_weekday = 6 #by default settle on monday try: process = os.popen("locale first_weekday week-1stday") week_offset, week_start = process.read().split('\n')[:2] process.close() week_start = dt.dat...
groups items by field described in keyfunc and counts totals using value from sumfunc
def totals(iter, keyfunc, sumfunc): """groups items by field described in keyfunc and counts totals using value from sumfunc """ data = sorted(iter, key=keyfunc) res = {} for k, group in groupby(data, keyfunc): res[k] = sum([sumfunc(entry) for entry in group]) return res
converts date into dictionary, having prefix for all the keys
def dateDict(date, prefix = ""): """converts date into dictionary, having prefix for all the keys""" res = {} res[prefix+"a"] = date.strftime("%a") res[prefix+"A"] = date.strftime("%A") res[prefix+"b"] = date.strftime("%b") res[prefix+"B"] = date.strftime("%B") res[prefix+"c"] = date.strfti...
look up tags by their name. create if not found
def __get_tag_ids(self, tags): """look up tags by their name. create if not found""" db_tags = self.fetchall("select * from tags where name in (%s)" % ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables changes = Fal...
get most recent, preferably not deleted activity by it's name
def __get_activity_by_name(self, name, category_id = None, resurrect = True): """get most recent, preferably not deleted activity by it's name""" if category_id: query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM ...
returns category by it's name
def __get_category_id(self, name): """returns category by it's name""" query = """ SELECT id from categories WHERE lower(name) = lower(?) ORDER BY id desc LIMIT 1 """ res = self.fetchone(query, (name, )) ...
put the fact back together and move all the unique tags to an array
def __group_tags(self, facts): """put the fact back together and move all the unique tags to an array""" if not facts: return facts #be it None or whatever grouped_facts = [] for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]): fact_tags = list(fact_tags) ...
tries to put task in the given date if there are conflicts, we will only truncate the ongoing task and replace it's end part with our activity
def __squeeze_in(self, start_time): """ tries to put task in the given date if there are conflicts, we will only truncate the ongoing task and replace it's end part with our activity """ # we are checking if our start time is in the middle of anything # or maybe there is...
finds facts that happen in given interval and shifts them to make room for new fact
def __solve_overlaps(self, start_time, end_time): """finds facts that happen in given interval and shifts them to make room for new fact """ if end_time is None or start_time is None: return # possible combinations and the OR clauses that catch them # (the si...
returns list of activities for autocomplete, activity names converted to lowercase
def __get_activities(self, search): """returns list of activities for autocomplete, activity names converted to lowercase""" query = """ SELECT a.name AS name, b.name AS category FROM activities a LEFT JOIN categories b ON coalesce(b.id...
check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else, just remove it
def __remove_activity(self, id): """ check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else, just remove it""" query = "select count(*) as count from facts where activity_id = ?" bound_facts = self.f...
move all activities to unsorted and remove category
def __remove_category(self, id): """move all activities to unsorted and remove category""" affected_query = """ SELECT id FROM facts WHERE activity_id in (SELECT id FROM activities where category_id=?) """ affected_ids = [res[0] for res in self.fet...
remove affected ids from the index
def __remove_index(self, ids): """remove affected ids from the index""" if not ids: return ids = ",".join((str(id) for id in ids)) self.execute("DELETE FROM fact_index where id in (%s)" % ids)
check if maybe index needs rebuilding in the time span
def __check_index(self, start_date, end_date): """check if maybe index needs rebuilding in the time span""" index_query = """SELECT id FROM facts WHERE (end_time >= ? OR end_time IS NULL) AND start_time <= ? ...
execute sql statement. optionally you can give multiple statements to save on cursor creation and closure
def execute(self, statement, params = ()): """ execute sql statement. optionally you can give multiple statements to save on cursor creation and closure """ con = self.__con or self.connection cur = self.__cur or con.cursor() if isinstance(statement, list) == Fal...
upgrade DB to hamster version
def run_fixtures(self): self.start_transaction() """upgrade DB to hamster version""" version = self.fetchone("SELECT version FROM version")["version"] current_version = 9 if version < 8: # working around sqlite's utf-f case sensitivity (bug 624438) # mor...
Current fact index in the self.facts list.
def current_fact_index(self): """Current fact index in the self.facts list.""" facts_ids = [fact.id for fact in self.facts] return facts_ids.index(self.current_fact.id)
the row height is defined by following factors: * how many facts are there in the day * does the fact have description / tags This func creates a list of row start positions to be able to quickly determine what to display
def set_row_heights(self): """ the row height is defined by following factors: * how many facts are there in the day * does the fact have description / tags This func creates a list of row start positions to be able to quickly determine what t...
chains the given list of functions and object animations into a callback string. Expects an interlaced list of object and params, something like: object, {params}, callable, {params}, object, {}, object, {params} Assumes that all callees accept on_complete na...
def chain(*steps): """chains the given list of functions and object animations into a callback string. Expects an interlaced list of object and params, something like: object, {params}, callable, {params}, object, {}, object, {params} Assumes that all cal...
returns the given data distributed in the space ensuring it's full pixels and with the given gap. this will result in minor sub-pixel inaccuracies. XXX - figure out where to place these guys as they are quite useful
def full_pixels(space, data, gap_pixels=1): """returns the given data distributed in the space ensuring it's full pixels and with the given gap. this will result in minor sub-pixel inaccuracies. XXX - figure out where to place these guys as they are quite useful """ available = space - (len(data...
parse string or a color tuple into color usable for cairo (all values in the normalized (0..1) range
def parse(self, color): """parse string or a color tuple into color usable for cairo (all values in the normalized (0..1) range""" assert color is not None #parse color into rgb values if isinstance(color, str): match = self.hex_color_long.match(color) if...
returns gdk.Color object of the given color
def gdk(self, color): """returns gdk.Color object of the given color""" c = self.parse(color) return gdk.Color.from_floats(c)
returns color darker by step (where step is in range 0..255)
def darker(self, color, step): """returns color darker by step (where step is in range 0..255)""" hls = colorsys.rgb_to_hls(*self.rgb(color)) return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
if color is dark, will return a lighter one, otherwise darker
def contrast(self, color, step): """if color is dark, will return a lighter one, otherwise darker""" hls = colorsys.rgb_to_hls(*self.rgb(color)) if self.is_light(color): return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2]) else: return colorsys.hls_to_rgb(hls...
Mix colors. Args: ca (gdk.RGBA): first color cb (gdk.RGBA): second color xb (float): between 0.0 and 1.0 Return: gdk.RGBA: linear interpolation between ca and cb, 0 or 1 return the unaltered 1st or 2nd color respectively, ...
def mix(self, ca, cb, xb): """Mix colors. Args: ca (gdk.RGBA): first color cb (gdk.RGBA): second color xb (float): between 0.0 and 1.0 Return: gdk.RGBA: linear interpolation between ca and cb, 0 or 1 return the unaltered 1st...
draw a curve. (x2, y2) is the middle point of the curve
def curve_to(self, x, y, x2, y2, x3, y3): """draw a curve. (x2, y2) is the middle point of the curve""" self._add_instruction("curve_to", x, y, x2, y2, x3, y3)
change width and dash of a line
def set_line_style(self, width = None, dash = None, dash_offset = 0): """change width and dash of a line""" if width is not None: self._add_instruction("set_line_width", width) if dash is not None: self._add_instruction("set_dash", dash, dash_offset)
the alpha has to changed based on the parent, so that happens at the time of drawing
def _set_color(self, context, r, g, b, a): """the alpha has to changed based on the parent, so that happens at the time of drawing""" if a < 1: context.set_source_rgba(r, g, b, a) else: context.set_source_rgb(r, g, b)
set active color. You can use hex colors like "#aaa", or you can use normalized RGB tripplets (where every value is in range 0..1), or you can do the same thing in range 0..65535. also consider skipping this operation and specify the color on stroke and fill.
def set_color(self, color, alpha = 1): """set active color. You can use hex colors like "#aaa", or you can use normalized RGB tripplets (where every value is in range 0..1), or you can do the same thing in range 0..65535. also consider skipping this operation and specify the color on str...
draw arc going counter-clockwise from start_angle to end_angle
def arc(self, x, y, radius, start_angle, end_angle): """draw arc going counter-clockwise from start_angle to end_angle""" self._add_instruction("arc", x, y, radius, start_angle, end_angle)
draw circle
def circle(self, x, y, radius): """draw circle""" self._add_instruction("arc", x, y, radius, 0, math.pi * 2)
draw 'perfect' ellipse, opposed to squashed circle. works also for equilateral polygons
def ellipse(self, x, y, width, height, edges = None): """draw 'perfect' ellipse, opposed to squashed circle. works also for equilateral polygons""" # the automatic edge case is somewhat arbitrary steps = edges or max((32, width, height)) / 2 angle = 0 step = math.pi *...
draw arc going clockwise from start_angle to end_angle
def arc_negative(self, x, y, radius, start_angle, end_angle): """draw arc going clockwise from start_angle to end_angle""" self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle)
draw a rectangle. if corner_radius is specified, will draw rounded corners. corner_radius can be either a number or a tuple of four items to specify individually each corner, starting from top-left and going clockwise
def rectangle(self, x, y, width, height, corner_radius = 0): """draw a rectangle. if corner_radius is specified, will draw rounded corners. corner_radius can be either a number or a tuple of four items to specify individually each corner, starting from top-left and going clockwise""" ...
fill rectangular area with specified color
def fill_area(self, x, y, width, height, color, opacity = 1): """fill rectangular area with specified color""" self.save_context() self.rectangle(x, y, width, height) self._add_instruction("clip") self.rectangle(x, y, width, height) self.fill(color, opacity) self....
fill and stroke the drawn area in one go
def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None): """fill and stroke the drawn area in one go""" if line_width: self.set_line_style(line_width) if fill and stroke: self.fill_preserve(fill, opacity) elif fill: self.fill(fill, opaci...
utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout
def create_layout(self, size = None): """utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout""" if not self.context: # TODO - this is rather sloppy as far as exception goes ...
display text. unless font_desc is provided, will use system's default font
def show_label(self, text, size = None, color = None, font_desc = None): """display text. unless font_desc is provided, will use system's default font""" font_desc = pango.FontDescription(font_desc or _font_desc) if color: self.set_color(color) if size: font_desc.set_absolute_size(size *...
display text. font_desc is string of pango font description often handier than calling this function directly, is to create a class:Label object
def show_layout(self, text, font_desc, alignment = pango.Alignment.LEFT, width = -1, wrap = None, ellipsize = None, single_paragraph_mode = False): """display text. font_desc is string of pango font description often handier than calling this function directly,...
draw accumulated instructions in context
def _draw(self, context, opacity): """draw accumulated instructions in context""" # if we have been moved around, we should update bounds fresh_draw = len(self.__new_instructions or []) > 0 if fresh_draw: #new stuff! self.paths = [] self.__instruction_cache = sel...
instead of caching paths, this function caches the whole drawn thing use cache_as_bitmap on sprite to enable this mode
def _draw_as_bitmap(self, context, opacity): """ instead of caching paths, this function caches the whole drawn thing use cache_as_bitmap on sprite to enable this mode """ matrix = context.get_matrix() matrix_changed = matrix != self._last_matrix new_instr...
breadth-first sprite search by ID
def find(self, id): """breadth-first sprite search by ID""" for sprite in self.sprites: if sprite.id == id: return sprite for sprite in self.sprites: found = sprite.find(id) if found: return found
traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute
def traverse(self, attr_name = None, attr_value = None): """traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute """ for sprite in self.sprites: ...
will print out the lines in console if debug is enabled for the specific sprite
def log(self, *lines): """will print out the lines in console if debug is enabled for the specific sprite""" if getattr(self, "debug", False): print(dt.datetime.now().time(), end=' ') for line in lines: print(line, end=' ') print()
add one sprite at a time. used by add_child. split them up so that it would be possible specify the index externally
def _add(self, sprite, index = None): """add one sprite at a time. used by add_child. split them up so that it would be possible specify the index externally""" if sprite == self: raise Exception("trying to add sprite to itself") if sprite.parent: sprite.x, sprit...
sort sprites by z_order
def _sort(self): """sort sprites by z_order""" self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order)