class MokshaLiveFeedTree(DynaTreeWidget): options = dict(title='Moksha Live Feed Tree', rootVisible=True, persist=True, fx={ 'height': 'toggle', 'duration': 200 }, initAjax={ 'url': '/apps/feeds/init_tree', 'data': { 'key': 'root' } }, onActivate=twc.JSSymbol(src=""" function(dtnode) { moksha.send_message( 'moksha.feeds', { action: 'get_feed', 'key': dtnode.data.key, topic: moksha_feed_topic}); }""")) def prepare(self): self.topic = str(uuid4()) super(MokshaLiveFeedTree, self).prepare()
class DemoFlatRRDJitAreaChart(tw2.rrd.FlatRRDJitAreaChart): start = datetime.datetime.fromtimestamp(1280000000) end = datetime.datetime.fromtimestamp(1304000000) rrd_filenames = [ data_directory + '/flat/cpu_user.rrd', data_directory + '/flat/cpu_wio.rrd', data_directory + '/flat/cpu_system.rrd', ] steps = 25 timedelta = datetime.timedelta(days=90) width = "400px" height = "250px" offset = 0 showAggregates = False showLabels = False Label = {'size': 15, 'family': 'Arial', 'color': 'white'} Tips = { 'enable': True, 'onShow': twc.JSSymbol(src=""" (function(tip, elem) { tip.innerHTML = "<b>" + elem.name + "</b>: " + elem.value + " % cpu usage across 8 cores."; })""") }
def prepare(self): super(MokshaContainer, self).prepare() if isinstance(self.content, twc.widgets.WidgetMeta): self.content = self.content.req() if isinstance(self.content, twc.Widget): self.widget_name = self.content.__class__.__name__ content_args = getattr(self, 'content_args', {}) if isinstance(self.content, LiveWidget): topics = self.content.get_topics() # FIXME: also unregister the moksha callback functions. Handle # cases where multiple widgets are listening to the same topics self.onClose = twc.JSSymbol( src="function(o){%s $(o).remove();}" % unsubscribe_topics(topics)) self.onIconize = self.onCollapse = twc.JSSymbol( src="function(o){%s}" % unsubscribe_topics(topics)) self.onRestore = twc.JSSymbol(src="function(o){%s}" % subscribe_topics(topics)) self.content = self.content.display(**content_args) for option in self.options: # TODO -- inspect this. It might have become wonky in tw1->tw2 setattr(self, option, getattr(self, option, True) and option or '') self.buttons = '' for button in self.button_options: if getattr(self, button, True): self.buttons += '%s,' % button[:1] self.buttons = self.buttons[:-1] self.id = str(uuid.uuid4()) self._container_options = encoder.encode({ 'elementsPath': '/resources/moksha.widgets.container.container/static/css/elements/', 'onClose': self.onClose, 'onResize': self.onResize, 'onCollapse': self.onCollapse, 'onIconize': self.onIconize, 'onDrag': self.onDrag, 'onRestore': self.onRestore, })
class ToDateWidget(CustomizedDatePicker): id = 'to_date' options = { 'showAnim': 'slideDown', 'autoSize': True, 'yearRange': '1989:2011', 'changeYear': True, 'onSelect': twc.JSSymbol(onselect_tmpl % 'to_date'), }
class OrbitedWidget(twc.Widget): onopen = twc.Param("A javascript callback for when the connection opens", default=twc.JSSymbol(src="function(){}")) onread = twc.Param("A javascript callback for when new data is read", default=twc.JSSymbol(src="function(){}")) onclose = twc.Param("A javascript callback for when the connection closes", default=twc.JSSymbol(src="function(){}")) orbited_port = twc.Param("Orbited port", default=orbited_port) orbited_host = twc.Param("Orbited host", default=orbited_host) orbited_scheme = twc.Param("Orbited scheme", default=orbited_scheme) template = "mako:moksha.wsgi.widgets.api.orbited.templates.orbited" def prepare(self): orbited_url = '%s://%s:%s' % ( self.orbited_scheme, self.orbited_host, self.orbited_port, ) orbited_js = twc.JSLink(link=orbited_url + '/static/Orbited.js', resources=[tw2.jquery.jquery_js]) self.resources.append(orbited_js)
class MokshaAjaxFeedEntriesTree(DynaTreeWidget): options = { 'rootVisible': False, 'persist': True, 'onActivate': twc.JSSymbol(src=""" function(dtnode) { $('#BottomPane').load( '/apps/feeds/get_entry?key=' + dtnode.data.key); }"""), }
class MokshaLiveFeedEntriesTree(DynaTreeWidget): options = dict(rootVisible=False, persist=True, onActivate=twc.JSSymbol(src=""" function(dtnode) { moksha.send_message('moksha.feeds', { 'action': 'get_entry', 'key': dtnode.data.key, topic: moksha_feed_topic }); /* Unsubscribe from current feed, subscribe to new one */ } """.replace('\n', '')))
def prepare(self): super(MokshaContextualMenu, self).prepare() if not self.id: raise Exception("MokshaMenu must have an id!") if not self.callback: raise Exception("Must provide a callback URL!") menus = [] for menu in self.menus: menus.append((menu.lower().replace(' ', ''), menu)) self.menus = menus self.add_call( jQuery(twc.JSSymbol(src='document')).buildContextualMenu({ 'template': self.callback, 'menuWidth': self.menuWidth, 'rootMenuSelector': ".%s" % self.rootMenuSelector, 'menuSelector': ".%s" % self.menuSelector, 'iconPath': self.iconPath, 'hasImages': self.hasImages, 'fadeTime': self.fadeTime, 'fadeInTime': self.fadeInTime, 'fadeOutTime': self.fadeOutTime, 'adjustLeft': self.adjustLeft, 'adjustTop': self.adjustTop, 'opacity': self.opacity, 'shadow': self.shadow, 'effect': self.effect, 'minZindex': self.minZindex }))
class DemoDynaTree(DynaTreeWidget): options = { 'onActivate': twc.JSSymbol( src="""function(node) { alert("You activated " + node.data.title); }"""), 'children': [ {'title': "Item 1"}, {'title': "Folder 2", 'isFolder': True, 'key': "folder2", 'children': [ {'title': "Sub-item 2.1"}, {'title': "Sub-item 2.2"} ] }, {'title': "Item 3"} ] }
class MokshaAjaxFeedTree(DynaTreeWidget): options = { 'title': 'Moksha Ajax Feed Tree', 'rootVisible': True, 'persist': True, 'initAjax': { 'url': '/apps/feeds/init_tree', 'data': { 'key': 'root' } }, 'onActivate': twc.JSSymbol(src=""" function(dtnode) { $('#TopPane').load( '/apps/feeds/get_entries?key=' + dtnode.data.key.replace(/ /, '')); } """.replace('\n', '')) }
class MokshaContainer(twc.Widget): template = 'mako:moksha.widgets.container.templates.container' resources = [ jquery_js, jquery_ui_js, container_js, container_css, container_resources, ] options = ['draggable', 'resizable'] button_options = ['iconize', 'minimize', 'close'] draggable = twc.Param(default=True) droppable = twc.Param(default=True) resizable = twc.Param(default=False) iconize = twc.Param(default=True) minimize = twc.Param(default=True) close = twc.Param(default=True) hide = twc.Param(default=True) # TODO -- there is a better tw2 idiom for this content = twc.Param("TODO == replace this with 'child'", default='') widget_name = twc.Param(default=None) title = twc.Param(default='Moksha Container') skin = twc.Param(default='default') # default, black, white, stiky, alert view_source = twc.Param(default=True) dock = twc.Param(default='moksha_dock') icon = twc.Param(default='gears.png') # Pixel tweaking width = twc.Param(default=450) height = twc.Param(default=500) left = twc.Param(default=170) top = twc.Param(default=125) # Javascript callbacks onResize = twc.Param(default=twc.JSSymbol(src="function(o){}")) onClose = twc.Param(default=twc.JSSymbol(src="function(o){}")) onCollapse = twc.Param(default=twc.JSSymbol(src="function(o){}")) onIconize = twc.Param(default=twc.JSSymbol(src="function(o){}")) onDrag = twc.Param(default=twc.JSSymbol(src="function(o){}")) onRestore = twc.Param(default=twc.JSSymbol(src="function(o){}")) _container_options = twc.Variable() def prepare(self): super(MokshaContainer, self).prepare() if isinstance(self.content, twc.widgets.WidgetMeta): self.content = self.content.req() if isinstance(self.content, twc.Widget): self.widget_name = self.content.__class__.__name__ content_args = getattr(self, 'content_args', {}) if isinstance(self.content, LiveWidget): topics = self.content.get_topics() # FIXME: also unregister the moksha callback functions. Handle # cases where multiple widgets are listening to the same topics self.onClose = twc.JSSymbol( src="function(o){%s $(o).remove();}" % unsubscribe_topics(topics)) self.onIconize = self.onCollapse = twc.JSSymbol( src="function(o){%s}" % unsubscribe_topics(topics)) self.onRestore = twc.JSSymbol(src="function(o){%s}" % subscribe_topics(topics)) self.content = self.content.display(**content_args) for option in self.options: # TODO -- inspect this. It might have become wonky in tw1->tw2 setattr(self, option, getattr(self, option, True) and option or '') self.buttons = '' for button in self.button_options: if getattr(self, button, True): self.buttons += '%s,' % button[:1] self.buttons = self.buttons[:-1] self.id = str(uuid.uuid4()) self._container_options = encoder.encode({ 'elementsPath': '/resources/moksha.widgets.container.container/static/css/elements/', 'onClose': self.onClose, 'onResize': self.onResize, 'onCollapse': self.onCollapse, 'onIconize': self.onIconize, 'onDrag': self.onDrag, 'onRestore': self.onRestore, })
class DemoNestedRRDJitTreeMap(tw2.rrd.NestedRRDJitTreeMap): start = datetime.datetime.fromtimestamp(1306557540) end = datetime.datetime.fromtimestamp(1306558380) root_title = "Country versus Filename" rrd_directories = [ data_directory + 'nested/filename/' + country for country in [ 'Brazil/', 'Canada/', 'China/', 'France/', 'Germany/', 'Greece/', 'India/', 'Italy/', 'Malaysia/', 'Mexico/', 'Peru/', 'Puerto_Rico/', 'Russian_Federation/', 'Singapore/', 'Spain/', 'Sweden/', 'Turkey/', 'Ukraine/', 'United_Kingdom/', 'United_States/', ] ] Tips = { 'enable': True, 'offsetX': 20, 'offsetY': 20, 'onShow': twc.JSSymbol(src=""" (function(tip, node, isLeaf, domElement) { var html = '<div class="tip-title">' + node.name + '</div><div class="tip-text">'; var data = node.data; if(data['$area']) { html += ' hits per second: ' + data['$area'].toFixed(2); } tip.innerHTML = html; }) """) } onCreateLabel = twc.JSSymbol(src=""" (function(domElement, node){ domElement.innerHTML = node.name; var style = domElement.style; style.display = ''; style.border = '1px solid transparent'; style.color = '#000000'; domElement.onmouseover = function() { style.border = '1px solid #9FD4FF'; }; domElement.onmouseout = function() { style.border = '1px solid transparent'; }; } ) """)
class NestedRRDJitTreeMap(tw2.jit.TreeMap, RRDNestedMixin): data = twc.Variable("Internally produced.") method = twc.Param( "Method for consolidating values. Either 'sum' or 'average'", default='average') root_title = twc.Param("Root title", default=None) postInitJSCallback = twc.JSSymbol( src="(function (jitwidget) { jitwidget.refresh(); })") def make_from_nested(self, data): res = [] for i in range(len(data)): key1 = data[i]['label'] children = [] for j in range(len(data[i]['data'])): key2 = data[i]['data'][j]['label'] value = sum([item[1] for item in data[i]['data'][j]['data']]) if self.method == 'average': value = float(value) / len(data[i]['data'][j]['data']) if value == 0: continue children.append( self.make_node( primary=key2, secondary=key1, value=value, children=[], )) if not children: continue res.append( self.make_node( primary=key1, secondary=None, children=children, value=sum([c['data']['$area'] for c in children]), )) return res def make_color(self, value, _max, _min): lower, upper = 0x025167, 0x39AECF x = float(value - _min) / (_max - _min) color = (x * (upper - lower)) + lower return "#%0.6x" % color def add_colors(self, _max, _min): for i in range(len(self.data['children'])): for j in range(len(self.data['children'][i]['children'])): self.data['children'][i]['children'][j]['data']['$color'] = \ self.make_color( self.data['children'][i]['children'][j]['data']['$area'], _max, _min ) def find_bounds(self): _min, _max = 10000000000, 0 for i in range(len(self.data['children'])): for j in range(len(self.data['children'][i]['children'])): v = self.data['children'][i]['children'][j]['data']['$area'] if v < _min: _min = v if v > _max: _max = v return _min, _max def make_node(self, primary, secondary, value, children): return { 'id': str(primary) + "-" + str(secondary), 'name': primary, 'children': children, 'data': { '$area': value, }, } def prepare(self): if not self.root_title: raise ValueError, "Root title is required." raw_data = self.nested_fetch() self.data = { 'id': 'root', 'name': self.root_title, 'children': self.make_from_nested(raw_data), } _min, _max = self.find_bounds() self.add_colors(_max, _min) super(NestedRRDJitTreeMap, self).prepare()
def prepare(self): super(ButtonColumn, self).prepare() self.options['formatter'] = twc.JSSymbol(self.formatter_tmpl % (self.id, self.label)) self.options['label'] = ''