class FlatRRDProtoBarChart(tw2.protovis.conventional.BarChart, RRDFlatMixin): series_sorter = twc.Param("function to compare to data points for sorting", default=None) prune_zeroes = twc.Param("hide zero-valued series?", default=False) p_data = twc.Variable("Internally produced") p_labels = twc.Variable("Internally produced") method = twc.Param( "Method for consolidating values. Either 'sum' or 'average'", default='average') def prepare(self): data = self.flat_fetch() if self.series_sorter: data.sort(self.series_sorter) if not self.method in ['sum', 'average']: raise ValueError, "Illegal value '%s' for method" % self.method self.p_labels = [series['label'] for series in data] if self.method == 'sum': self.p_data = [ sum([d[1] for d in series['data']]) for series in data ] elif self.method == 'average': self.p_data = [ sum([d[1] for d in series['data']]) / len(series['data']) for series in data ] super(FlatRRDProtoBarChart, self).prepare()
class ChosenMixin(twc.Widget): '''Mixin for Chosen SelectFields''' resources = [chosen_js, chosen_css] selector = twc.Variable("Escaped id. jQuery selector.") opts = twc.Variable( 'Arguments for the javascript init function. ' 'See http://harvesthq.github.io/chosen/options.html', default=dict()) placeholder = twc.Param('Placeholder text, prompting user for selection', default='') no_results_text = twc.Param( 'Text shown when the search term returned no results', default='') search_contains = twc.Param( 'Allow matches starting from anywhere within a word.', default=False) def prepare(self): super(ChosenMixin, self).prepare() # put code here to run just before the widget is displayed if 'id' in self.attrs: self.selector = "#" + self.attrs['id'].replace(':', '\\:') if self.placeholder: self.attrs['data-placeholder'] = self.placeholder if self.no_results_text: self.opts['no_results_text'] = self.no_results_text if self.search_contains: self.opts['search_contains'] = True self.add_call(twj.jQuery(self.selector).chosen(self.opts))
class SelectionTable(SelectionField): selected_verb = "checked" template = "tw2.forms.templates.selection_table" cols = twc.Param('Number of columns', default=1) options_rows = twc.Variable() grouped_options_rows = twc.Variable() name = None def _group_rows(self, seq, size): if not hasattr(seq, 'next'): seq = iter(seq) while True: chunk = [] try: for i in range(size): chunk.append(six.advance_iterator(seq)) yield chunk except StopIteration: if chunk: yield chunk break def prepare(self): super(SelectionTable, self).prepare() self.options_rows = self._group_rows(self.options, self.cols) self.grouped_options_rows = [(g, self._group_rows(o, self.cols)) for g, o in self.grouped_options]
class JQueryUIWidget(twc.Widget): """ Base JQueryUIWidget """ _hide_docs = False resources = [jquery_ui_js, jquery_ui_css] jqmethod = twc.Variable("(str) Name of this widget's jQuery init method") selector = twc.Variable("(str) Escaped id. jQuery selector.") options = twc.Param('(dict) A dict of options to pass to the widget', default={}) # TODO -- add all the events http://api.jquery.com/category/events/ # TODO -- try to automatically generate IDs if not specified # TODO -- TBD, figure out if this actually makes sense for all ui things. events = twc.Param('(dict) (BETA) javascript callbacks for events', default={}) def prepare(self): if self.events is not None and not isinstance(self.events, dict): raise ValueError, 'Events parameter must be a dict' self.resources.append(jquery_ui_css(name=get_ui_theme_name())) if self.options is not None and not isinstance(self.options, dict): raise ValueError, 'Options parameter must be a dict' self.options = encoder.encode(self.options) super(JQueryUIWidget, self).prepare() if not hasattr(self, 'id') or 'id' not in self.attrs: raise ValueError, 'JQueryWidget must be supplied an id' self.selector = self.attrs['id'].replace(':', '\\\\:')
class VerticalSelectionTable(SelectionField): field_type = twc.Variable(default=True) selected_verb = "checked" template = "tw2.forms.templates.vertical_selection_table" cols = twc.Param( 'Number of columns. If the options are grouped, this is overidden.', default=1) options_rows = twc.Variable() def _gen_row_single(self, single, cols): row_count = int(math.ceil(float(len(single)) / float(cols))) # This shouldn't really need spacers. It's hackish. # (Problem: 4 items in a 3 column table) spacer_count = (row_count * cols) - len(single) single.extend([(None, None)] * spacer_count) col_iters = [] for i in range(cols): start = i * row_count col_iters.append(iter(single[start:start + row_count])) while True: row = [] try: for col_iter in col_iters: row.append(six.advance_iterator(col_iter)) yield row except StopIteration: if row: yield row break def _gen_row_grouped(self, grouped_options): row_count = max([len(o) for g, o in grouped_options]) col_iters = [] for g, o in grouped_options: spacer_count = row_count - len(o) o.extend([(None, None)] * spacer_count) col_iters.append(hasattr(o, 'next') and o or iter(o)) while True: row = [] try: for col_iter in col_iters: row.append(six.advance_iterator(col_iter)) yield row except StopIteration: if row: yield row break def prepare(self): super(VerticalSelectionTable, self).prepare() if self.grouped_options[0][0]: self.options_rows = self._gen_row_grouped(self.grouped_options) else: self.options_rows = self._gen_row_single(self.options, self.cols)
class TabWidget(twc.Widget): template = "mako:fedoracommunity.widgets.package.templates.tabs" base_url = twc.Param(default='/') args = twc.Param(default=None) kwds = twc.Param(default=None) tabs = twc.Variable(default=None) _uuid = twc.Param(default=None) widget = twc.Variable(default=None) active_tab = twc.Variable(default=None) tabs = twc.Variable(default=None) default_tab = None def __init__(self, *args, **kw): super(TabWidget, self).__init__(*args, **kw) self._uuid = str(uuid.uuid4()) self._expanded_tabs = OrderedDict() for key, widget_key in self.tabs.items(): display_name = key key = key.lower().replace(' ', '_') self._expanded_tabs[key] = { 'display_name': display_name, 'widget_key': widget_key } def prepare(self): super(TabWidget, self).prepare() if not self.args: self.args = [] if not self.kwds: self.kwds = {} if isinstance(self.args, mako.runtime.Undefined): self.args = [] if isinstance(self.kwds, mako.runtime.Undefined): self.kwds = {} if len(self.args) > 0: active_tab = self.args.pop(0).lower() else: active_tab = self.default_tab.lower() try: self.widget = moksha.common.utils.get_widget( self._expanded_tabs[active_tab]['widget_key']) except KeyError: self.widget = None self.tabs = self._expanded_tabs self.active_tab = active_tab if isinstance(self.base_url, Template): self.base_url = tg.url(self.base_url.render(**self.__dict__))
class PackageWidget(twc.Widget): template = "mako:fedoracommunity.widgets.package.templates.package_chrome" package_name = twc.Param() args = twc.Param(default=None) kwds = twc.Param(default=None) latest_build = twc.Variable(default='Koji unavailable') summary = twc.Variable(default='No summary provided') description = twc.Variable(default='No description provided') navigation_widget = PackageNavWidget def prepare(self): name = self.args.pop(0) self.kwds['package_name'] = name self.kwds['subpackage_of'] = "" self.package_name = name xapian_conn = get_connector('xapian') result = xapian_conn.get_package_info(name) self.package_info = result super(PackageWidget, self).prepare() if not result: tg.redirect('/s/' + name) if result['name'] == name: self.summary = result['summary'] self.description = result['description'] else: self.kwds['subpackage_of'] = result['name'] for subpkg in result['sub_pkgs']: if subpkg['name'] == name: self.summary = subpkg['summary'] self.description = subpkg['description'] break else: tg.redirect('/s/' + name) koji = get_connector('koji') try: builds = koji._koji_client.getLatestBuilds('rawhide', package=result['name']) if builds: self.latest_build = builds[0]['version'] + '-' + \ builds[0]['release'] else: self.latest_build = 'Not built in rawhide' except Exception, e: log.error('Unable to query koji: %s' % str(e))
class FlatRRDProtoLineChart(tw2.protovis.conventional.LineChart, RRDFlatMixin): p_data = twc.Variable("Internally produced") p_labels = twc.Variable("Internally produced") p_time_series = True p_time_series_format = "%b %Y" def prepare(self): data = self.flat_fetch() self.p_labels = [d['label'] for d in data] self.p_data = [[{ 'x': int(d[0]), 'y': d[1], } for d in series['data']] for series in data] super(FlatRRDProtoLineChart, self).prepare()
class Wysihtml5(twf.TextArea): template = "mako:tw2.wysihtml5.templates.wysihtml5" resources = [wysihtml5_js] parser = twc.Param( 'The set of parser rules to use. ' 'The simple parser contains only basic html5 tags, while the ' 'advanced parser contains more html5 tags and preserves some ' 'css classes. If you use the simple parser, the editor css is ' 'not strictly needed.', default='advanced') toolbar_id = twc.Variable(default='wysihtml5-toolbar') def prepare(self): super(Wysihtml5, self).prepare() if not hasattr(self, 'id') or 'id' not in self.attrs: raise ValueError('WYSIHTML5 must be supplied an id') self.resources.append(parsers[self.parser]) self.toolbar_id = self.compound_id + '-toolbar' self.resources.append( twc.JSSource(src=""" var editor = new wysihtml5.Editor("%s", { toolbar: "%s", parserRules: wysihtml5ParserRules, stylesheets: ["/resources/%s/%s"] }); """ % (self.compound_id, self.toolbar_id, wysihtml5_editor_css.guess_modname(), wysihtml5_editor_css.filename)))
class InputField(FormField): """A generic <input> field. Generally you won't use this one, but will rely on one of its specialised subclasses like :class:`.TextField` or :class:`Checkbox`. """ type = twc.Variable('Type of input field', default=twc.Required, attribute=True) #: Input type value = twc.Param(attribute=True) #: Current value of the input required = twc.Param( 'Input field is required', attribute=True, default=None) #: Add required attributed to the input. autofocus = twc.Param( 'Autofocus form field (HTML5 only)', attribute=True, default=None) #: Add autofocus attributed to the input. template = "tw2.forms.templates.input_field" def prepare(self): super(InputField, self).prepare() self.safe_modify('attrs') self.attrs['required'] = 'required' if self.required in [ True, 'required' ] else None self.required = None # Needed because self.required would otherwise overwrite self.attrs['required'] again
def prepare(self): package_name = self.kwds['package_name'] xapian_conn = get_connector('xapian') result = xapian_conn.get_package_info(package_name) self.package_name = package_name self.package_info = result latest_build = twc.Variable(default='Koji unavailable') super(Details, self).prepare() if result['name'] == package_name: self.summary = result['summary'] self.description = result['description'] else: for subpkg in result['sub_pkgs']: if subpkg['name'] == package_name: self.summary = subpkg['summary'] self.description = subpkg['description'] break self.package_info = result koji = get_connector('koji') try: builds = koji._koji_client.getLatestBuilds('rawhide', package=result['name']) if builds: self.latest_build = builds[0]['version'] + '-' + \ builds[0]['release'] else: self.latest_build = 'Not built in rawhide' except Exception, e: log.error('Unable to query koji: %s' % str(e))
class TabView(twf.widgets.BaseLayout): resources = YuiWidget.resources + [ twc.CSSLink(modname=__name__, filename="static/" + yui_version + "/tabview/assets/skins/sam/tabview.css"), twc.JSLink( modname=__name__, filename="static/" + yui_version + "/element/element-min.js"), twc.JSLink( modname=__name__, filename="static/" + yui_version + "/tabview/tabview-min.js"), ] template = "genshi:tw2.yui.templates.tabview" # These don't apply; hide from widget browser hover_help = twc.Variable() help_text = twc.Variable() container_attrs = twc.Variable()
class GrowingGridLayout(twf.GridLayout): """A GridLayout that can dynamically grow on the client, with delete and undo functionality. This is useful for allowing users to enter a list of items that can vary in length. To function correctly, the widget must appear inside a CustomisedForm.""" resources = [ twc.Link(id='undo', modname=__name__, filename="static/undo.png"), twc.JSLink(modname=__name__, filename="static/dynforms.js"), ] template = 'genshi:tw2.dynforms.templates.growing_grid_layout' # TBD: support these properly & min/max repetitions = twc.Variable() extra_reps = twc.Variable(default=1) mix_reps = twc.Variable() max_reps = twc.Variable() @classmethod def post_define(cls): if hasattr(cls.child, 'children'): if not hasattr(cls.child.children, 'del'): # TBD: 'del' in ... cls.child = cls.child(children=list(cls.child.children) + [DeleteButton(id='del', label='')]) def prepare(self): if not hasattr(self, '_validated'): self.value = [None] + (self.value or []) super(GrowingGridLayout, self).prepare() # First and last rows have delete hidden (and hidingbutton) and get onchange for r in (self.children[0], self.children[self.repetitions - 1]): for c in r.children: c.safe_modify('attrs') if c.id == 'del': c.attrs['style'] = 'display:none;' + c.attrs.get( 'style', '') else: c.attrs['onchange'] = 'twd_grow_add(this);' + c.attrs.get( 'onchange', '') # First row is hidden hidden_row = self.children[0] hidden_row.safe_modify('attrs') hidden_row.attrs['style'] = 'display:none;' + hidden_row.attrs.get( 'style', '') def _validate(self, value, state=None): value = [v for v in value if not ('del.x' in v and 'del.y' in v)] return twc.RepeatingWidget._validate( self, [None] + twf.StripBlanks().to_python(value), state)[1:]
class Selectable(twc.Widget): template = 'mako:moksha.api.widgets.selectable.templates.selectable' resources = [jquery_js, jquery_ui_js, moksha_ui_selectable_js] content_id = twc.Variable() def prepare(self): super(Selectable, self).prepare() self.content_id = d.id + '-uuid' + str(uuid4()) self.add_call(jQuery("#%s" % d.content_id).moksha_selectable())
class ContextAwareWidget(twc.Widget): '''Inherit from this widget class if you want your widget to automatically get the pylons.tmpl_context in its dictionary ''' tmpl_context = twc.Variable() def prepare(self): super(ContextAwareWidget, self).prepare() self.tmpl_context = tmpl_context
class FormField(twc.Widget): name = twc.Variable('dom name', request_local=False, attribute=True, default=property(lambda s: hasattr(s, 'compound_key') and s.compound_key or s.compound_id)) @property def required(self): return self.validator and (getattr(self.validator, 'required', None))
class BugStatsWidget(twc.Widget): template = "mako:fedoracommunity.widgets.package.templates.bugs_stats_widget" id = twc.Param(default='bugs_widget') kwds = twc.Param(default=None) product = twc.Param(default='Fedora') version = twc.Param(default='rawhide') epel_version = twc.Param(default='el6') package = twc.Param(default=None) num_open = twc.Param(default='-') num_new_this_week = twc.Param(default='') num_closed_this_week = twc.Param(default='') bz_prefix = "https://bugzilla.redhat.com/buglist.cgi" status_open_string = "bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED" status_closed_string = "bug_status=CLOSED" base_query_string = twc.Variable(default='') open_query_string = twc.Variable(default='') closed_query_string = twc.Variable(default='') def prepare(self): super(BugStatsWidget, self).prepare() def to_query_string(query): return "&".join([ "{key}={value}".format(key=key, value=value) for key, value in query.items() ]) self.base_query_string = to_query_string({ "query_format": "advanced", "product": self.product, "component": self.package, }) self.open_query_string = to_query_string({ "chfieldto": "Now", "chfield": "[Bug creation]", "chfieldfrom": datetime.datetime.now().isoformat().split('T')[0], }) self.closed_query_string = to_query_string({ "chfieldto": "Now", "chfield": "bug_status", "chfieldvalue": "CLOSED", "chfieldfrom": datetime.datetime.now().isoformat().split('T')[0], })
class Patches(twc.Widget): kwds = twc.Param(default=None) patches = twc.Param(default={}) package = twc.Variable() diffstat = twc.Variable(default='') releases = ReleaseFilter template = 'mako:fedoracommunity.widgets.package.templates.patches' def prepare(self): super(Patches, self).prepare() self.package = self.kwds['package_name'] self.subpackage_of = self.kwds.get('subpackage_of') if self.subpackage_of: main_package = self.subpackage_of else: main_package = self.package self.branch = self.kwds.get('branch', 'master') repo = FedoraGitRepo(main_package, branch=self.branch) self.patches = repo.get_patches() self.diffstat = repo.get_diffstat()
class jQueryUIThemeCSSLink(jQueryUIMixin, twc.CSSLink): name = twc.Variable() # Generated from get_ui_theme_name() @property def subdir(self): return 'css/%(name)s' % dict(name=self.name) extension = 'css' def prepare(self): self.name = get_ui_theme_name() super(jQueryUIThemeCSSLink, self).prepare()
class FlatRRDFlotWidget(tw2.jqplugins.flot.FlotWidget, RRDFlatMixin): data = twc.Variable("Internally produced.") options = { 'xaxis': { 'mode': 'time', } } def prepare(self): # TODO -- can this be moved to post_define? self.data = self.flat_fetch() super(FlatRRDFlotWidget, self).prepare()
class FlatRRDStreamGraph(tw2.protovis.custom.StreamGraph, RRDFlatMixin): """ TODO -- this guy needs a lot of work until he looks cool. """ p_data = twc.Variable("Internally produced") logarithmic = twc.Param("Logscale? Boolean!", default=False) def prepare(self): data = self.flat_fetch() self.p_data = [[item[1] for item in series['data']] for series in data] if self.logarithmic: self.p_data = [[math.log(value + 1) for value in series] for series in self.p_data] super(FlatRRDStreamGraph, self).prepare()
class BrowseWidget(twc.Widget): id = None template = 'genshi:tw2.devtools.templates.wb_widget' name = twc.Variable() widget = twc.Variable() params = twc.Variable() child_params = twc.Variable() demo = twc.Variable() source = twc.Variable() def prepare(self): super(BrowseWidget, self).prepare() tw2.jqplugins.ui.set_ui_theme_name('pepper-grinder') if self.value: self.name, self.widget, self.demo = self.value if self.source: self.resources.extend([ tw2.jquery.jquery_js, tw2.jqplugins.ui.jquery_ui_js, tw2.jqplugins.ui.jquery_ui_css, twc.JSLink(modname=__name__, filename='static/js/source.js') ]) if getattr(self.widget, '_hide_docs', False) and self.demo: self.demo.resources.extend([ tw2.jquery.jquery_js, twc.JSLink(modname=__name__, filename='static/js/browser.js') ]) self.params = sorted(self.widget._params.values(), key=lambda p: p._seq) self.child_params = [ p for p in self.widget._all_params.values() if p.child_param and not p.internal ] self.child_params.sort(key=lambda p: p._seq) req_prm = [ p.name for p in self.params if p.default is twc.Required ] if self.demo: try: self.demo = self.demo(id='demo', parent=self.__class__).req() self.demo.prepare() except Exception as e: warnings.warn(six.text_type(e)) self.demo = None elif not req_prm or req_prm == ['id']: # auto demo try: self.demo = self.widget(id='demo', parent=self.__class__).req() self.demo.prepare() except Exception as e: warnings.warn(six.text_type(e)) self.demo = None else: self.demo = None
class PackageWidget(twc.Widget): template = "mako:fedoracommunity.widgets.package.templates.package_chrome" package_name = twc.Param() args = twc.Param(default=None) kwds = twc.Param(default=None) summary = twc.Variable(default='No summary provided') description = twc.Variable(default='No description provided') navigation_widget = PackageNavWidget def prepare(self): name = self.args.pop(0) self.kwds['package_name'] = name self.kwds['subpackage_of'] = "" self.package_name = name xapian_conn = get_connector('xapian') result = xapian_conn.get_package_info(name) self.package_info = result super(PackageWidget, self).prepare() if not result: tg.redirect('/s/' + name) if result['name'] == name: self.summary = result['summary'] self.description = result['description'] else: self.kwds['subpackage_of'] = result['name'] for subpkg in result['sub_pkgs']: if subpkg['name'] == name: self.summary = subpkg['summary'] self.description = subpkg['description'] break else: tg.redirect('/s/' + name) def __repr__(self): return u"<PackageWidget %s>" % self.package_name
class FormField(twc.Widget): """Basic Form Widget from which each other field will inherit""" name = twc.Variable( 'dom name', request_local=False, attribute=True, default=property(lambda s: hasattr(s, 'compound_key') and s. compound_key or s.compound_id)) #: Name of the field @property def required(self): """If the field is required according to its validator (read-only)""" return self.validator and (getattr(self.validator, 'required', None))
class SourceCodeWidget(twc.Widget): widget = twc.Param('The name of the widget') module = twc.Param('Whether to display the entire module', default=False) source = twc.Param('Optional source code', default=None) title = twc.Variable(' An optional title for the document') code = twc.Variable('The actual rendered source code') template = "mako:moksha.widgets.templates.sourcecode" container_options = { 'width': 625, 'height': 675, 'title': 'View Source', 'icon': 'comment.png', 'top': 50, 'left': 300 } hidden = twc.Param(default=True) module = twc.Param(default=False) title = twc.Param(default=None) def prepare(self): super(SourceCodeWidget, self).prepare() title = self.widget.__class__.__name__ if not self.source: try: self.widget = moksha.utils.get_widget(self.widget) except Exception, e: self.widget = namedAny(self.widget) if self.module: obj = namedAny(self.widget.__module__) else: obj = self.widget.__class__ self.source = inspect.getsource(obj) html_args = {'full': True} if self.title: html_args['title'] = self.title self.code = highlight(self.source, PythonLexer(), HtmlFormatter(**html_args))
class CalendarDatePicker(twf.widgets.InputField): """ A JavaScript calendar system for picking dates. The date format can be configured on the validator. """ resources = [ twc.CSSLink(modname='tw2.dynforms', filename='static/calendar/calendar-system.css'), twc.JSLink(modname='tw2.dynforms', filename='static/calendar/calendar.js'), twc.JSLink(modname='tw2.dynforms', filename='static/calendar/calendar-setup.js'), twc.Link(id='cal', modname='tw2.dynforms', filename='static/office-calendar.png'), ] language = twc.Param('Short country code for language to use, e.g. fr, de', default='en') show_time = twc.Variable('Whether to display the time', default=False) value = twc.Param('The default value is the current date/time', default=None) validator = twc.DateValidator template = "genshi:tw2.dynforms.templates.calendar" type = 'text' def prepare(self): if not self.value: # XXX -- Doing this instead of twc.Deferred consciously. # twc.Deferred is/was nice, but the execution in post_define(...) of # cls._deferred = [k for k, v in cls.__dict__.iteritems() # if isinstance(v, pm.Deferred)] # with dir(..) instead of vars(..) is too costly. This is the only # place I'm aware of that actually uses deferred params. - threebean self.value = dt.datetime.now() super(CalendarDatePicker, self).prepare() self.safe_modify('resources') self.resources.extend([ twc.JSLink(parent=self.__class__, modname='tw2.dynforms', filename='static/calendar/lang/calendar-%s.js' % self.language), ]) self.add_call( twc.js_function('Calendar.setup')(dict( inputField=self.compound_id, ifFormat=self.validator.format, button=self.compound_id + ':trigger', showsTime=self.show_time)))
class ImageButton(twc.Link, InputField): type = "image" width = twc.Param('Width of image in pixels', attribute=True, default=None) height = twc.Param('Height of image in pixels', attribute=True, default=None) alt = twc.Param('Alternate text', attribute=True, default='') src = twc.Variable(attribute=True) def prepare(self): super(ImageButton, self).prepare() self.src = self.link self.safe_modify('attrs') self.attrs['src'] = self.src # TBD: hack!
class Patch(twc.Widget): kwds = twc.Param() diffstat = twc.Param('The diffstat for this patch', default=True) text = twc.Variable('The text of the patch') changelog = twc.Variable('The changelog of this patch') template = 'mako:fedoracommunity.widgets.package.templates.patch' def prepare(self): super(Patch, self).prepare() self.package = self.kwds['package'] self.subpackage_of = self.kwds.get('subpackage_of') self.patch = self.kwds['patch'] self.branch = self.kwds['branch'] if self.subpackage_of: main_package = self.subpackage_of else: main_package = self.package repo = FedoraGitRepo(main_package, branch=self.branch) diff = repo.get_patch(self.patch) if self.diffstat: self.diffstat = repo.get_diffstat(self.patch) self.text = highlight(diff, DiffLexer(), HtmlFormatter(full=True, nobackground=True)) self.changelog = repo.get_patch_changelog(self.patch)
class jqGridWidget(tw2_jq_ui.JQueryUIWidget): resources = [ tw2.jquery.jquery_js, tw2_jq_ui.jquery_ui_js, tw2_jq_ui.jquery_ui_css, base.jqgrid_locale, base.jqgrid_js, base.jqgrid_css, ] template = "tw2.jqplugins.jqgrid.templates.jqgrid" options = twc.Param("Configuration options to pass to jqgrid", default={}) pager_options = twc.Param("Configuration options for pager", default={}) pager_id = twc.Variable("options['pager'] placeholder", default=None) prmFilter = twc.Param("params to pass to filter toolbar", default={}) prmEdit = twc.Param("params to pass to pager [Edit]", default={}) prmAdd = twc.Param("params to pass to pager [Add]", default={}) prmDel = twc.Param("params to pass to pager [Del]", default={}) prmSearch = twc.Param("params to pass to pager [Search]", default={}) prmView = twc.Param("params to pass to pager [View]", default={}) # so this would be a list of dicts - and encoded as [below] # self.custom_pager_buttons = map(encoder.encode, # self.custom_pager_buttons) custom_pager_buttons = twc.Param("custom buttons to add to jqgrid pager", default=[]) def prepare(self): if not self.options: raise ValueError('jqGridWidget must be given a dict of options') if (not 'url' in self.options and not 'data' in self.options and not 'datastr' in self.options): raise ValueError("jqGridWidget must be supplied a " + "'url', 'data', or 'datastr' in options") self.pager_id = self.options.get('pager', None) super(jqGridWidget, self).prepare() self._pager_options = encoder.encode(self.pager_options) self._prmFilter = encoder.encode(self.prmFilter) self._prmEdit = encoder.encode(self.prmEdit) self._prmAdd = encoder.encode(self.prmAdd) self._prmDel = encoder.encode(self.prmDel) self._prmSearch = encoder.encode(self.prmSearch) self._prmView = encoder.encode(self.prmView) self._custom_pager_buttons = map(encoder.encode, self.custom_pager_buttons)
class ColorPicker(YuiWidget): resources = YuiWidget.resources + [ twc.CSSLink(modname=__name__, filename="static/" + yui_version + "/colorpicker/assets/skins/sam/colorpicker.css"), twc.JSLink( modname=__name__, filename="static/" + yui_version + "/dragdrop/dragdrop-min.js"), twc.JSLink( modname=__name__, filename="static/" + yui_version + "/animation/animation-min.js"), twc.JSLink(modname=__name__, filename="static/" + yui_version + "/slider/slider-min.js"), twc.JSLink( modname=__name__, filename="static/" + yui_version + "/element/element-min.js"), twc.JSLink(modname=__name__, filename="static/" + yui_version + "/colorpicker/colorpicker-min.js"), twc.Link(id='picker_thumb', modname=__name__, filename="static/" + yui_version + "/colorpicker/assets/picker_thumb.png"), twc.Link(id='hue_thumb', modname=__name__, filename="static/" + yui_version + "/colorpicker/assets/hue_thumb.png"), ] template = "genshi:tw2.yui.templates.colorpicker" rgb = twc.Variable(default='[0xFF,0xFF,0xFF]') def prepare(self): self.safe_modify('options') if self.value and re.match('^#[0-9a-fA-F]{6}$', self.value): self.rgb = twc.encoder.encode( [int(self.value[i:i + 2], 16) for i in (1, 3, 5)]) self.options['images'] = { 'PICKER_THUMB': '/resources/tw2.yui.widgets/static/' + yui_version + '/colorpicker/assets/picker_thumb.png', 'HUE_THUMB': '/resources/tw2.yui.widgets/static/' + yui_version + '/colorpicker/assets/hue_thumb.png', } super(ColorPicker, self).prepare()