code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
d = self.declaration style = d.style or '@style/Widget.DeviceDefault.PopupMenu' self.window = PopupWindow(self.get_context(), None, 0, style) self.showing = False
def create_widget(self)
Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent.
10.915205
10.237519
1.066196
w = self.window d = self.declaration self.set_background_color(d.background_color) self.set_touchable(d.touchable) self.set_outside_touchable(d.outside_touchable) # Listen for events w.setOnDismissListener(w.getId()) w.onDismiss.connect(self.on_dismiss) super(AndroidPopupWindow, self).init_widget()
def init_widget(self)
Set the listeners
5.315166
5.037367
1.055148
super(AndroidPopupWindow, self).init_layout() #: Set the content for view in self.child_widgets(): self.window.setContentView(view) break #: Show it if needed d = self.declaration if d.show: self.set_show(d.show)
def init_layout(self)
If a view is given show it
8.18404
7.211025
1.134934
view = child.widget if view is not None: self.window.setContentView(view)
def child_added(self, child)
Overwrite the content view
8.82735
6.425634
1.373771
super(AndroidPopupWindow, self).destroy() window = self.window if window: #: Clear the dismiss listener #: (or we get an error during the callback) window.setOnDismissListener(None) #window.dismiss() del self.window
def destroy(self)
A reimplemented destructor that cancels the dialog before destroying.
9.636992
8.364518
1.152128
if not self.showing: return d = self.declaration self.set_show(d.show)
def update(self)
Update the PopupWindow if it is currently showing. This avoids calling update during initialization.
12.059157
9.680439
1.245724
items = [] if self.condition: for nodes, key, f_locals in self.pattern_nodes: with new_scope(key, f_locals): for node in nodes: child = node(None) if isinstance(child, list): items.extend(child) else: items.append(child) for old in self.items: if not old.is_destroyed: old.destroy() #: Insert items into THIS node, NOT the PARENT #if len(items) > 0: # self.parent.insert_children(self, items) self.items = items
def refresh_items(self)
Refresh the items of the pattern. This method destroys the old items and creates and initializes the new items. It is overridden to NOT insert the children to the parent. The Fragment adapter handles this.
5.378587
5.051786
1.06469
super(AndroidSwipeRefreshLayout, self).init_widget() d = self.declaration w = self.widget if not d.enabled: self.set_enabled(d.enabled) if d.indicator_background_color: self.set_indicator_background_color(d.indicator_background_color) if d.indicator_color: self.set_indicator_color(d.indicator_color) if d.trigger_distance: self.set_trigger_distance(d.trigger_distance) w.onRefresh.connect(self.on_refresh) w.setOnRefreshListener(w.getId())
def init_widget(self)
Initialize the underlying widget.
2.60775
2.414944
1.079839
try: return sys.modules[mod] except KeyError: pass lib = ExtensionImporter.extension_modules[mod] m = imp.load_dynamic(mod, lib) sys.modules[mod] = m return m
def load_module(self, mod)
Load the extension using the load_dynamic method.
3.552901
3.365471
1.055692
d = self.declaration self.widget = TabLayout(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying widget.
13.200659
9.948987
1.326834
super(AndroidTabLayout, self).init_widget() w = self.widget w.addOnTabSelectedListener(w.getId()) w.onTabSelected.connect(self.on_tab_selected) w.onTabUnselected.connect(self.on_tab_unselected)
def init_widget(self)
Initialize the underlying widget.
3.6717
3.237583
1.134086
super(AndroidTabLayout, self).destroy() if self.tabs: del self.tabs
def destroy(self)
Destroy all tabs when destroyed
11.958867
7.508229
1.592768
old_keys = old.members().keys() new_keys = new.members().keys() for key in old_keys: old_obj = getattr(old, key) try: new_obj = getattr(new, key) if old_obj == new_obj: continue except AttributeError: # Remove any obsolete members try: delattr(old, key) except (AttributeError, TypeError): pass continue try: #: Update any changed members #: TODO: We have to somehow know if this was changed by the user or the code! #: and ONLY update if it's due to the code changing! Without this, the entire concept #: is broken and useless... setattr(old, key, getattr(new, key)) except (AttributeError, TypeError): pass # skip non-writable attributes #: Add any new members for key in set(new_keys)-set(old_keys): try: setattr(old, key, getattr(new, key)) except (AttributeError, TypeError): pass
def update_atom_members(old, new)
Update an atom member
3.891714
3.876159
1.004013
autoreload.update_class(old, new) if isinstance2(old, new, AtomMeta): update_atom_members(old, new)
def update_class_by_type(old, new)
Update declarative classes or fallback on default
15.770713
15.075352
1.046126
with enaml.imports(): super(EnamlReloader, self).check(check_all=check_all, do_reload=do_reload)
def check(self, check_all=True, do_reload=True)
Check whether some modules need to be reloaded.
4.963192
3.976846
1.248022
#: Create and initialize if not new: new = type(old)() if not new.is_initialized: new.initialize() if self.debug: print("Updating {} with {}".format(old, new)) #: Update attrs, funcs, and bindings of this node self.update_attrs(old, new) self.update_funcs(old, new) self.update_bindings(old, new) #: Update any child pattern nodes before the children self.update_pattern_nodes(old, new) #: Now update any children self.update_children(old, new)
def update(self, old, new=None)
Update given view declaration with new declaration Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative or None The new or reloaded view instance to that will be used to update the existing view. If none is given, one of the same type as old will be created and initialized with no attributes passed.
4.64704
4.381063
1.060711
name = new.__class__.__name__ #: TODO: We should pick the BEST one from this list #: based on some "matching" criteria (such as matching ref name or params) matches = [c for c in old_nodes if name == c.__class__.__name__] if self.debug: print("Found matches for {}: {} ".format(new, matches)) return matches[0] if matches else None
def find_best_matching_node(self, new, old_nodes)
Find the node that best matches the new node given the old nodes. If no good match exists return `None`.
7.7474
8.175257
0.947664
#: Copy in storage from new node if new._d_storage: old._d_storage = new._d_storage
def update_attrs(self, old, new)
Update any `attr` members. Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative The new view instance that should be used for updating
14.855167
23.983727
0.619385
#: Copy the Expression Engine if new._d_engine: old._d_engine = new._d_engine engine = old._d_engine #: Rerun any read expressions which should trigger #: any dependent writes for k in engine._handlers.keys(): try: engine.update(old, k) except: if self.debug: print(traceback.format_exc()) pass
def update_bindings(self, old, new)
Update any enaml operator bindings. Parameters ----------- old: Declarative The existing view instance that needs to be updated new: Declarative The new view instance that should be used for updating
9.059635
9.692779
0.934679
super(UiKitProgressView, self).init_widget() d = self.declaration if d.progress: self.set_progress(d.progress)
def init_widget(self)
Initialize the state of the toolkit widget. This method is called during the top-down pass, just after the 'create_widget()' method is called. This method should init the state of the widget. The child widgets will not yet be created.
8.55203
6.133841
1.394237
widget = self.widget if widget is not None: del self.widget super(UiKitToolkitObject, self).destroy()
def destroy(self)
A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None.
9.315898
5.728168
1.626331
d = self.declaration self.widget = View(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying label widget.
11.738718
8.819957
1.330927
super(AndroidView, self).init_widget() # Initialize the widget by updating only the members that # have read expressions declared. This saves a lot of time and # simplifies widget initialization code for k, v in self.get_declared_items(): handler = getattr(self, 'set_'+k, None) if handler: handler(v)
def init_widget(self)
Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the properties that need to be overridden from defaults thus greatly reducing the number of initialization checks, saving time and memory. If you don't want this to happen override `get_declared_keys` to return an empty list.
9.99195
7.208369
1.38616
d = self.declaration engine = d._d_engine if engine: layout = {} for k, h in engine._handlers.items(): # Handlers with read operations if not h.read_pair: continue v = getattr(d, k) if k in LAYOUT_KEYS: layout[k] = v continue yield (k, v) if layout: yield ('layout', layout)
def get_declared_items(self)
Get the members that were set in the enamldef block for this Declaration. Layout keys are grouped together until the end so as to avoid triggering multiple updates. Returns ------- result: List of (k,v) pairs that were defined for this widget in enaml List of keys and values
7.593751
6.462635
1.175024
d = self.declaration r = {'key': key, 'result': False} d.key_event(r) return r['result']
def on_key(self, view, key, event)
Trigger the key event Parameters ---------- view: int The ID of the view that sent this event key: int The code of the key that was pressed data: bytes The msgpack encoded key event
9.730884
13.9961
0.695257
d = self.declaration r = {'event': event, 'result': False} d.touch_event(r) return r['result']
def on_touch(self, view, event)
Trigger the touch event Parameters ---------- view: int The ID of the view that sent this event data: bytes The msgpack encoded key event
9.568671
16.80792
0.569295
v = View.VISIBILITY_VISIBLE if visible else View.VISIBILITY_GONE self.widget.setVisibility(v)
def set_visible(self, visible)
Set the visibility of the widget.
7.265985
6.391091
1.136893
# Update the layout with the widget defaults update = self.layout_params is not None params = self.default_layout.copy() params.update(layout) # Create the layout params parent = self.parent() if not isinstance(parent, AndroidView): # Root node parent = self update = True parent.apply_layout(self, params) if update: self.widget.setLayoutParams(self.layout_params)
def set_layout(self, layout)
Sets the LayoutParams of this widget. Since the available properties that may be set for the layout params depends on the parent, actual creation of the params is delegated to the parent Parameters ---------- layout: Dict A dict of layout parameters the parent should used to layout this child. The widget defaults are updated with user passed values.
6.840138
5.540843
1.234494
dp = self.dp w, h = (coerce_size(layout.get('width', 'wrap_content')), coerce_size(layout.get('height', 'wrap_content'))) w = w if w < 0 else int(w * dp) h = h if h < 0 else int(h * dp) layout_params = self.layout_param_type(w, h) if layout.get('margin'): l, t, r, b = layout['margin'] layout_params.setMargins(int(l*dp), int(t*dp), int(r*dp), int(b*dp)) return layout_params
def create_layout_params(self, child, layout)
Create the LayoutParams for a child with it's requested layout parameters. Subclasses should override this as needed to handle layout specific needs. Parameters ---------- child: AndroidView A view to create layout params for. layout: Dict A dict of layout parameters to use to create the layout. Returns ------- layout_params: LayoutParams A LayoutParams bridge object with the requested layout options.
2.580712
2.410326
1.07069
layout_params = child.layout_params if not layout_params: layout_params = self.create_layout_params(child, layout) w = child.widget if w: dp = self.dp # padding if 'padding' in layout: l, t, r, b = layout['padding'] w.setPadding(int(l*dp), int(t*dp), int(r*dp), int(b*dp)) # left, top, right, bottom if 'left' in layout: w.setLeft(int(layout['left']*dp)) if 'top' in layout: w.setTop(int(layout['top']*dp)) if 'right' in layout: w.setRight(int(layout['right']*dp)) if 'bottom' in layout: w.setBottom(int(layout['bottom']*dp)) # x, y, z if 'x' in layout: w.setX(layout['x']*dp) if 'y' in layout: w.setY(layout['y']*dp) if 'z' in layout: w.setZ(layout['z']*dp) # set min width and height # maximum is not supported by AndroidViews (without flexbox) if 'min_height' in layout: w.setMinimumHeight(int(layout['min_height']*dp)) if 'min_width' in layout: w.setMinimumWidth(int(layout['min_width']*dp)) child.layout_params = layout_params
def apply_layout(self, child, layout)
Apply a layout to a child. This sets the layout_params of the child which is later used during the `init_layout` pass. Subclasses should override this as needed to handle layout specific needs of the ViewGroup. Parameters ---------- child: AndroidView A view to create layout params for. layout: Dict A dict of layout parameters to use to create the layout.
1.958035
1.892007
1.034898
with enamlnative.imports(): for impl in [ TornadoEventLoop, TwistedEventLoop, BuiltinEventLoop, ]: if impl.available(): print("Using {} event loop!".format(impl)) return impl() raise RuntimeError("No event loop implementation is available. " "Install tornado or twisted.")
def default(cls)
Get the first available event loop implementation based on which packages are installed.
7.945793
6.047348
1.31393
print("Uncaught error during callback: {}".format(callback)) print("Error: {}".format(error))
def log_error(self, callback, error=None)
Log the error that occurred when running the given callback.
7.429736
7.591233
0.978726
loop = self.loop r = loop.callLater(0, callback, *args, **kwargs) loop.wakeUp() return r
def deferred_call(self, callback, *args, **kwargs)
We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor "wakes up"
4.359529
3.939355
1.106661
loop = self.loop r = loop.callLater(ms/1000.0, callback, *args, **kwargs) loop.wakeUp() return r
def timed_call(self, ms, callback, *args, **kwargs)
We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor "wakes up"
4.004994
3.436708
1.165358
super(UiKitView, self).init_widget() self.widget.yoga.isEnabled = True # Initialize the widget by updating only the members that # have read expressions declared. This saves a lot of time and # simplifies widget initialization code for k, v in self.get_declared_items(): handler = getattr(self, 'set_'+k, None) if handler: handler(v)
def init_widget(self)
Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the properties that need to be overridden from defaults thus greatly reducing the number of initialization checks, saving time and memory. If you don't want this to happen override `get_declared_keys` to return an empty list.
12.015041
9.54751
1.258448
widget = self.widget for child_widget in self.child_widgets(): widget.addSubview(child_widget)
def init_layout(self)
Initialize the layout of the toolkit widget. This method is called during the bottom-up pass. This method should initialize the layout of the widget. The child widgets will be fully initialized and layed out when this is called.
7.68505
7.123192
1.078877
d = self.declaration if d.x or d.y or d.width or d.height: self.frame = (d.x, d.y, d.width, d.height)
def update_frame(self)
Define the view frame for this widgets
3.630718
2.960053
1.226572
super(UiKitView, self).child_added(child) widget = self.widget #: TODO: Should index be cached? for i, child_widget in enumerate(self.child_widgets()): if child_widget == child.widget: widget.insertSubview(child_widget, atIndex=i)
def child_added(self, child)
Handle the child added event from the declaration. This handler will unparent the child toolkit widget. Subclasses which need more control should reimplement this method.
6.887902
6.421404
1.072647
super(UiKitView, self).child_moved(child) #: Remove and re-add in correct spot #: TODO: Should use exchangeSubviewAtIndex self.child_removed(child) self.child_added(child)
def child_moved(self, child)
Handle the child moved event from the declaration.
13.099027
12.120317
1.08075
super(UiKitView, self).child_removed(child) if child.widget is not None: child.widget.removeFromSuperview()
def child_removed(self, child)
Handle the child removed event from the declaration. This handler will unparent the child toolkit widget. Subclasses which need more control should reimplement this method.
6.007514
6.096416
0.985417
widget = self.widget if widget is not None: widget.removeFromSuperview() super(UiKitView, self).destroy()
def destroy(self)
A reimplemented destructor. This destructor will remove itself from the superview.
8.21091
5.21278
1.57515
super(AndroidSurfaceView, self).init_layout() # Force layout using the default params if not self.layout_params: self.set_layout({})
def init_layout(self)
Add all child widgets to the view
11.269083
9.799337
1.149984
#: If we set the TMP env variable the dev reloader will save file #: and load changes in this directory instead of overwriting the #: ones installed with the app. os.environ['TMP'] = os.path.join(sys.path[0], '../tmp') from enamlnative.android.app import AndroidApplication app = AndroidApplication( debug=True, #: Makes a lot of lag! dev='server', load_view=load_view, ) app.start()
def main()
Called by PyBridge.start()
13.253314
13.479749
0.983202
super(AndroidViewAnimator, self).init_widget() d = self.declaration if d.animate_first_view: self.set_animate_first_view(d.animate_first_view) if d.displayed_child: self.set_displayed_child(d.displayed_child)
def init_widget(self)
Initialize the underlying widget.
3.827514
3.389953
1.129076
self.widget = ViewPager(self.get_context()) self.adapter = BridgedFragmentStatePagerAdapter()
def create_widget(self)
Create the underlying widget.
18.879074
16.37009
1.153266
super(AndroidViewPager, self).child_added(child) self._notify_count += 1 self.get_context().timed_call( self._notify_delay, self._notify_change)
def child_added(self, child)
When a child is added, schedule a data changed notification
8.921594
7.80047
1.143725
d = self.declaration self._notify_count -= 1 if self._notify_count == 0: #: Tell the UI we made changes self.adapter.notifyDataSetChanged(now=True) self.get_context().timed_call( 500, self._queue_pending_calls)
def _notify_change(self)
After all changes have settled, tell Java it changed
10.975384
10.478334
1.047436
# d = self.declaration # #: We have to wait for the current_index to be ready before we can # #: change pages if self._notify_count > 0: self._pending_calls.append( lambda index=index: self.widget.setCurrentItem(index)) else: self.widget.setCurrentItem(index)
def set_current_index(self, index)
We can only set the index once the page has been created. otherwise we get `FragmentManager is already executing transactions` errors in Java. To avoid this, we only call this once has been loaded.
7.873771
6.789415
1.159713
from .android_fragment import AndroidFragment if isinstance(child, AndroidFragment): return super(AndroidViewPager, self).create_layout_params(child, layout) # Only apply to decor views dp = self.dp w, h = (coerce_size(layout.get('width', 'match_parent')), coerce_size(layout.get('height', 'wrap_content'))) w = w if w < 0 else int(w * dp) h = h if h < 0 else int(h * dp) # No (w,h) constructor params = ViewPagerLayoutParams() params.width = w params.height = h params.isDecor = True return params
def create_layout_params(self, child, layout)
Override as there is no (width, height) constructor.
3.8862
3.509492
1.10734
d = self.declaration self.widget = CardView(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying widget.
12.986099
9.726186
1.335169
d = self.declaration self.widget = TextClock(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying widget.
14.587271
10.875139
1.341341
super(AndroidTextClock, self).init_widget() d = self.declaration if d.format_12_hour: self.set_format_12_hour(d.format_12_hour) if d.format_24_hour: self.set_format_24_hour(d.format_24_hour) if d.time_zone: self.set_time_zone(d.time_zone)
def init_widget(self)
Initialize the underlying widget.
2.350748
2.129351
1.103974
d = self.declaration if self.indeterminate: #: Note: Style will only exist on activity indicators! style = ProgressBar.STYLES[d.size] else: style = ProgressBar.STYLE_HORIZONTAL self.widget = ProgressBar(self.get_context(), None, style)
def create_widget(self)
Create the underlying widget.
11.970305
10.966887
1.091495
super(AndroidProgressBar, self).init_widget() d = self.declaration self.set_indeterminate(self.indeterminate) if not self.indeterminate: if d.max: self.set_max(d.max) if d.min: self.set_min(d.min) self.set_progress(d.progress) if d.secondary_progress: self.set_secondary_progress(d.secondary_progress)
def init_widget(self)
Initialize the underlying widget.
2.742608
2.469782
1.110466
d = self.declaration self.widget = Flexbox(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying widget.
13.555831
9.910971
1.36776
params = self.create_layout_params(child, layout) w = child.widget if w: # padding if layout.get('padding'): dp = self.dp l, t, r, b = layout['padding'] w.setPadding(int(l*dp), int(t*dp), int(r*dp), int(b*dp)) child.layout_params = params
def apply_layout(self, child, layout)
Apply the flexbox specific layout.
3.953172
3.772984
1.047758
app = AndroidApplication.instance() f = app.create_future() def on_ready(ims): ims.toggleSoftInput(flag, 0) f.set_result(True) cls.get().then(on_ready) return f
def toggle_keyboard(cls, flag=HIDE_IMPLICIT_ONLY)
Toggle the keyboard on and off Parameters ---------- flag: int Flag to send to toggleSoftInput Returns -------- result: future Resolves when the toggle is complete
8.123526
6.194584
1.311392
app = AndroidApplication.instance() f = app.create_future() def on_ready(ims): view = app.view.proxy.widget def on_token(__id__): ims.hideSoftInputFromWindow( JavaBridgeObject(__id__=__id__), 0).then(f.set_result) view.getWindowToken().then(on_token) cls.get().then(on_ready) return f
def hide_keyboard(cls)
Hide keyboard if it's open Returns -------- result: future Resolves when the hide is complete
12.473845
12.61479
0.988827
app = AndroidApplication.instance() f = app.create_future() if cls._instance: f.set_result(cls._instance) return f def on_service(obj_id): #: Create the manager if not cls.instance(): m = cls(__id__=obj_id) else: m = cls.instance() f.set_result(m) cls.from_(app).then(on_service) return f
def get(cls)
Acquires the NotificationManager service async.
6.117416
5.119687
1.194881
app = AndroidApplication.instance() if app.api_level >= 26: channel = NotificationChannel(channel_id, name, importance) channel.setDescription(description) NotificationChannelManager.get().then( lambda mgr: mgr.createNotificationChannel(channel)) return channel
def create_channel(cls, channel_id, name, importance=IMPORTANCE_DEFAULT, description="")
Before you can deliver the notification on Android 8.0 and higher, you must register your app's notification channel with the system by passing an instance of NotificationChannel to createNotificationChannel(). Parameters ---------- channel_id: String- Channel ID name: String Channel name importance: Int One of the IMPORTANCE levels description: String Channel description Returns ------- channel: NotificationChannel or None The channel that was created.
5.391093
5.485903
0.982718
app = AndroidApplication.instance() builder = Notification.Builder(app, channel_id) builder.update(*args, **kwargs) return builder.show()
def show_notification(cls, channel_id, *args, **kwargs)
Create and show a Notification. See `Notification.Builder.update` for a list of accepted parameters.
5.482802
4.022593
1.363002
def on_ready(mgr): if isinstance(notification_or_id, JavaBridgeObject): nid = notification_or_id.__id__ else: nid = notification_or_id if tag is None: mgr.cancel_(nid) else: mgr.cancel(tag, nid) cls.get().then(on_ready)
def cancel_notification(cls, notification_or_id, tag=None)
Cancel the notification. Parameters ---------- notification_or_id: Notification.Builder or int The notification or id of a notification to clear tag: String The tag of the notification to clear
4.387816
5.084352
0.863004
d = self.declaration self.create_notification() if d.show: self.set_show(d.show)
def init_layout(self)
Create the notification in the top down pass if show = True
9.922987
5.526752
1.795446
builder = self.builder NotificationManager.cancel_notification(builder) del self.builder super(AndroidNotification, self).destroy()
def destroy(self)
A reimplemented destructor that cancels the notification before destroying.
11.490178
7.778168
1.477235
d = self.declaration builder = self.builder = Notification.Builder(self.get_context(), d.channel_id) d = self.declaration # Apply any custom settings if d.settings: builder.update(**d.settings) for k, v in self.get_declared_items(): handler = getattr(self, 'set_{}'.format(k)) handler(v) builder.setSmallIcon(d.icon or '@mipmap/ic_launcher') # app = self.get_context() # intent = Intent() # intent.setClass(app, ) # builder.setContentIntent(PendingIntent.getActivity(app, 0, intent, 0)) #: Set custom content if present for view in self.child_widgets(): builder.setCustomContentView(view) break
def create_notification(self)
Instead of the typical create_widget we use `create_notification` because after it's closed it needs created again.
5.494772
5.320385
1.032777
d = self.declaration button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect self.widget = UIButton(buttonWithType=button_type)
def create_widget(self)
Create the toolkit widget for the proxy object.
11.122688
10.475979
1.061733
super(Block, self).initialize() block = self.block if block: #: This block is setting the content of another block #: Remove the existing blocks children if self.mode == 'replace': #: Clear the blocks children for c in block.children: c.destroy() #: Add this blocks children to the other block block.insert_children(None, self.children) else: #: This block is inserting it's children into it's parent self.parent.insert_children(self, self.children)
def initialize(self)
A reimplemented initializer. This method will add the include objects to the parent of the include and ensure that they are initialized.
6.431068
6.465945
0.994606
if self.is_initialized: if change['type'] == 'update': old_block = change['oldvalue'] old_parent = old_block.parent for c in self.children: old_parent.child_removed(c) new_block = change['value'] new_block.parent.insert_children(new_block, self.children)
def _observe_block(self, change)
A change handler for the 'objects' list of the Include. If the object is initialized objects which are removed will be unparented and objects which are added will be reparented. Old objects will be destroyed if the 'destroy_old' flag is True.
4.170907
4.056226
1.028273
d = self.declaration if d.text: self.set_text(d.text) if d.text_color: self.set_text_color(d.text_color) if d.text_alignment: self.set_text_alignment(d.text_alignment) if d.font_family or d.text_size: self.refresh_font() if hasattr(d, 'max_lines') and d.max_lines: self.set_max_lines(d.max_lines)
def init_text(self)
Init text properties for this widget
2.248166
2.022406
1.11163
super(AndroidViewGroup, self).init_layout() widget = self.widget i = 0 for child in self.children(): child_widget = child.widget if child_widget: if child.layout_params: widget.addView_(child_widget, i, child.layout_params) else: widget.addView(child_widget, i) i += 1 # Force layout using the default params if not self.layout_params: self.set_layout({})
def init_layout(self)
Add all child widgets to the view
4.324839
3.933955
1.099361
super(AndroidViewGroup, self).child_added(child) widget = self.widget #: TODO: Should index be cached? for i, child_widget in enumerate(self.child_widgets()): if child_widget == child.widget: if child.layout_params: widget.addView_(child_widget, i, child.layout_params) else: widget.addView(child_widget, i)
def child_added(self, child)
Handle the child added event from the declaration. This handler will unparent the child toolkit widget. Subclasses which need more control should reimplement this method.
5.576199
5.587264
0.99802
super(AndroidViewGroup, self).child_moved(child) #: Remove and re-add in correct spot self.child_removed(child) self.child_added(child)
def child_moved(self, child)
Handle the child moved event from the declaration.
6.767392
6.214646
1.088942
super(AndroidViewGroup, self).child_removed(child) if child.widget is not None: self.widget.removeView(child.widget)
def child_removed(self, child)
Handle the child removed event from the declaration. This handler will unparent the child toolkit widget. Subclasses which need more control should reimplement this method.
4.361197
4.82829
0.903259
d = self.declaration self.widget = TimePicker(self.get_context(), None, d.style or '@attr/timePickerStyle')
def create_widget(self)
Create the underlying widget.
16.570568
12.565469
1.318739
super(AndroidTimePicker, self).init_widget() d = self.declaration w = self.widget self.set_hour(d.hour) self.set_minute(d.minute) self.set_hour_mode(d.hour_mode) w.setOnTimeChangedListener(w.getId()) w.onTimeChanged.connect(self.on_time_changed)
def init_widget(self)
Initialize the underlying widget.
3.421184
3.070095
1.114358
widget = self.widget if widget is not None: parent = self.parent_widget() if parent is not None: parent.removeView(widget) del self.widget super(AndroidToolkitObject, self).destroy()
def destroy(self)
A reimplemented destructor. This destructor will clear the reference to the toolkit widget and set its parent to None.
4.851056
4.172747
1.162557
d = self.declaration self.widget = ToggleButton(self.get_context(), None, d.style or "@attr/buttonStyleToggle")
def create_widget(self)
Create the underlying widget.
18.084028
13.378378
1.351735
super(UiKitSwitch, self).init_widget() d = self.declaration if d.checked: self.set_checked(d.checked) #: Watch the on property for change #: So apparently UISwitch is not KVO compliant... # self.widget.addObserver( # self.get_app().view_controller, # forKeyPath="on", # options=UISwitch.NSKeyValueObservingOptionNew|UISwitch.NSKeyValueObservingOptionOld, # context=self.widget #) #: A really ugly way to add the target #: would be nice if we could just pass the block pointer here :) self.get_app().bridge.addTarget( self.widget, forControlEvents=UISwitch.UIControlEventValueChanged, andCallback=self.widget.getId(), usingMethod="onValueChanged", withValues=["on"]#,"selected"] ) self.widget.onValueChanged.connect(self.on_checked_changed)
def init_widget(self)
Bind the on property to the checked state
11.156694
10.375057
1.075338
#: Since iOS decides to call this like 100 times for each defer it d = self.declaration with self.widget.setOn.suppressed(): d.checked = on
def on_checked_changed(self, on)
See https://stackoverflow.com/questions/19628310/
49.195999
49.52647
0.993327
d = self.declaration self.widget = Chronometer(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying widget.
12.313317
9.361592
1.315302
super(AndroidChronometer, self).init_widget() w = self.widget w.setOnChronometerTickListener(w.getId()) w.onChronometerTick.connect(self.on_chronometer_tick)
def init_widget(self)
Initialize the underlying widget.
4.492516
3.904248
1.150674
for name in func_attrs: try: setattr(old, name, getattr(new, name)) except (AttributeError, TypeError): pass
def update_function(old, new)
Upgrade the code object of a function
3.75262
3.905534
0.960847
update_generic(old.fdel, new.fdel) update_generic(old.fget, new.fget) update_generic(old.fset, new.fset)
def update_property(old, new)
Replace get/set/del functions of a property
2.849878
2.402336
1.186295
# collect old objects in the module for name, obj in list(module.__dict__.items()): if not hasattr(obj, '__module__') or obj.__module__ != module.__name__: continue key = (module.__name__, name) try: old_objects.setdefault(key, []).append(weakref.ref(obj)) except TypeError: pass # reload module try: # clear namespace first from old cruft old_dict = module.__dict__.copy() old_name = module.__name__ module.__dict__.clear() module.__dict__['__name__'] = old_name module.__dict__['__loader__'] = old_dict['__loader__'] except (TypeError, AttributeError, KeyError): pass try: module = reload(module) except: # restore module dictionary on failed reload module.__dict__.update(old_dict) raise # iterate over all objects and update functions & classes for name, new_obj in list(module.__dict__.items()): key = (module.__name__, name) if key not in old_objects: continue new_refs = [] for old_ref in old_objects[key]: old_obj = old_ref() if old_obj is None: continue new_refs.append(old_ref) update_generic(old_obj, new_obj) if new_refs: old_objects[key] = new_refs else: del old_objects[key] return module
def superreload(module, reload=reload, old_objects={})
Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading
2.528491
2.550108
0.991523
try: del self.modules[module_name] except KeyError: pass self.skip_modules[module_name] = True
def mark_module_skipped(self, module_name)
Skip reloading the named module in the future
3.15004
3.080238
1.022661
try: del self.skip_modules[module_name] except KeyError: pass self.modules[module_name] = True
def mark_module_reloadable(self, module_name)
Reload the named module in the future (if it is imported)
3.882735
3.804358
1.020602
self.mark_module_reloadable(module_name) import_module(module_name) top_name = module_name.split('.')[0] top_module = sys.modules[top_name] return top_module, top_name
def aimport_module(self, module_name)
Import a module, and mark it reloadable Returns ------- top_module : module The imported module if it is top-level, or the top-level top_name : module Name of top_module
3.753469
2.964585
1.266103
if not self.enabled and not check_all: return if check_all or self.check_all: modules = list(sys.modules.keys()) else: modules = list(self.modules.keys()) for modname in modules: m = sys.modules.get(modname, None) if modname in self.skip_modules: continue py_filename, pymtime = self.filename_and_mtime(m) if py_filename is None: continue try: if pymtime <= self.modules_mtimes[modname]: continue except KeyError: self.modules_mtimes[modname] = pymtime continue else: if self.failed.get(py_filename, None) == pymtime: continue self.modules_mtimes[modname] = pymtime # If we've reached this point, we should try to reload the module if do_reload: try: if self.debug: print("Reloading {}".format(m)) superreload(m, reload, self.old_objects) if py_filename in self.failed: del self.failed[py_filename] except: print("[autoreload of %s failed: %s]" % ( modname, traceback.format_exc(10))) self.failed[py_filename] = pymtime
def check(self, check_all=False, do_reload=True)
Check whether some modules need to be reloaded.
3.168945
3.089679
1.025655
r if parameter_s == '': self._reloader.check(True) elif parameter_s == '0': self._reloader.enabled = False elif parameter_s == '1': self._reloader.check_all = False self._reloader.enabled = True elif parameter_s == '2': self._reloader.check_all = True self._reloader.enabled = True
def autoreload(self, parameter_s='')
r"""%autoreload => Reload modules automatically %autoreload Reload all modules (except those excluded by %aimport) automatically now. %autoreload 0 Disable automatic reloading. %autoreload 1 Reload all modules imported with %aimport every time before executing the Python code typed. %autoreload 2 Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work: - Functions and classes imported via 'from xxx import foo' are upgraded to new versions when 'xxx' is reloaded. - Methods and properties of classes are upgraded on reload, so that calling 'c.foo()' on an object 'c' created before the reload causes the new code for 'foo' to be executed. Some of the known remaining caveats are: - Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only). - Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded. - C extension modules cannot be reloaded, and so cannot be autoreloaded.
2.773719
2.80805
0.987774
modname = parameter_s if not modname: to_reload = sorted(self._reloader.modules.keys()) to_skip = sorted(self._reloader.skip_modules.keys()) if stream is None: stream = sys.stdout if self._reloader.check_all: stream.write("Modules to reload:\nall-except-skipped\n") else: stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload)) stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip)) elif modname.startswith('-'): modname = modname[1:] self._reloader.mark_module_skipped(modname) else: for _module in ([_.strip() for _ in modname.split(',')]): top_module, top_name = self._reloader.aimport_module(_module) # Inject module to user namespace self.shell.push({top_name: top_module})
def aimport(self, parameter_s='', stream=None)
%aimport => Import modules for automatic reloading. %aimport List modules to automatically import and not to import. %aimport foo Import module 'foo' and mark it to be autoreloaded for %autoreload 1 %aimport foo, bar Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1 %aimport -foo Mark module 'foo' to not be autoreloaded for %autoreload 1
3.629401
3.785961
0.958647
newly_loaded_modules = set(sys.modules) - self.loaded_modules for modname in newly_loaded_modules: _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname]) if pymtime is not None: self._reloader.modules_mtimes[modname] = pymtime self.loaded_modules.update(newly_loaded_modules)
def post_execute(self)
Cache the modification times of any modules imported in this execution
4.072664
3.479306
1.170539
d = self.declaration self.widget = EditText(self.get_context(), None, d.style or "@attr/editTextStyle")
def create_widget(self)
Create the underlying widget.
13.977683
10.582788
1.320794
d = self.declaration style = d.style if d.style else ( '@attr/borderlessButtonStyle' if d.flat else '@attr/buttonStyle') self.widget = Button(self.get_context(), None, style)
def create_widget(self)
Create the underlying widget.
10.017635
8.348459
1.199938
d = self.declaration self.widget = FloatingActionButton(self.get_context(), None, d.style)
def create_widget(self)
Create the underlying widget.
14.130552
10.826186
1.30522
d = self.declaration self.widget = Picker(self.get_context(), None, d.style or '@attr/numberPickerStyle')
def create_widget(self)
Create the underlying widget.
20.104626
15.138289
1.328065
super(AndroidPicker, self).init_widget() d = self.declaration w = self.widget if d.items: self.set_items(d.items) else: if d.max_value: self.set_max_value(d.max_value) if d.min_value: self.set_min_value(d.min_value) self.set_value(d.value) if d.wraps: self.set_wraps(d.wraps) if d.long_press_update_interval: self.set_long_press_update_interval(d.long_press_update_interval) w.setOnValueChangedListener(w.getId()) w.onValueChange.connect(self.on_value_change)
def init_widget(self)
Set the checked state after all children have been populated.
2.600973
2.524582
1.030259
d = self.declaration with self.widget.setValue.suppressed(): d.value = new
def on_value_change(self, picker, old, new)
Set the checked property based on the checked state of all the children
14.17835
19.502012
0.72702
d = self.declaration mode = 1 if d.mode == 'dropdown' else 0 self.widget = Spinner(self.get_context(), mode) # Create the adapter simple_spinner_item = 0x01090008 self.adapter = ArrayAdapter(self.get_context(), '@layout/simple_spinner_dropdown_item')
def create_widget(self)
Create the underlying label widget.
9.279251
8.330948
1.113829
w = self.widget # Selection listener w.setAdapter(self.adapter) w.setOnItemSelectedListener(w.getId()) w.onItemSelected.connect(self.on_item_selected) w.onNothingSelected.connect(self.on_nothing_selected) super(AndroidSpinner, self).init_widget()
def init_widget(self)
Initialize the underlying widget.
4.614802
4.242312
1.087804
self.adapter.clear() self.adapter.addAll(items)
def set_items(self, items)
Generate the view cache
9.11823
7.861616
1.159842