Bridge

Common

Copyright (c) 2017-2022, CodeLV.

Distributed under the terms of the MIT License.

The full license is in the file LICENSE, distributed with this software.

Created on June 21, 2017

enamlnative.core.bridge.REGISTRY: dict[str, 'BridgeObject'] = {'': <class 'enamlnative.ios.app.ViewController'>, 'android.app.NotificationChannel': <class 'enamlnative.android.android_notification.NotificationChannel'>, 'android.app.NotificationChannelManager': <class 'enamlnative.android.android_notification.NotificationChannelManager'>, 'android.app.PendingIntent': <class 'enamlnative.android.android_content.PendingIntent'>, 'android.content.Context': <class 'enamlnative.android.android_content.Context'>, 'android.content.Intent': <class 'enamlnative.android.android_content.Intent'>, 'android.content.IntentFilter': <class 'enamlnative.android.android_content.IntentFilter'>, 'android.graphics.Bitmap': <class 'enamlnative.android.android_image_view.Bitmap'>, 'android.graphics.drawable.ColorDrawable': <class 'enamlnative.android.android_utils.ColorDrawable'>, 'android.graphics.drawable.Drawable': <class 'enamlnative.android.android_image_view.Drawable'>, 'android.graphics.drawable.Icon': <class 'enamlnative.android.android_image_view.Icon'>, 'android.hardware.Sensor': <class 'enamlnative.android.android_sensors.Sensor'>, 'android.hardware.SensorManager': <class 'enamlnative.android.android_sensors.SensorManager'>, 'android.hardware.usb.UsbAccessory': <class 'enamlnative.android.android_usb.UsbAccessory'>, 'android.hardware.usb.UsbConfiguration': <class 'enamlnative.android.android_usb.UsbConfiguration'>, 'android.hardware.usb.UsbDevice': <class 'enamlnative.android.android_usb.UsbDevice'>, 'android.hardware.usb.UsbDeviceConnection': <class 'enamlnative.android.android_usb.UsbDeviceConnection'>, 'android.hardware.usb.UsbEndpoint': <class 'enamlnative.android.android_usb.UsbEndpoint'>, 'android.hardware.usb.UsbInterface': <class 'enamlnative.android.android_usb.UsbInterface'>, 'android.hardware.usb.UsbManager': <class 'enamlnative.android.android_usb.UsbManager'>, 'android.hardware.usb.UsbRequest': <class 'enamlnative.android.android_usb.UsbRequest'>, 'android.location.LocationListener': <class 'enamlnative.android.android_location.LocationManager.LocationListener'>, 'android.location.LocationManager': <class 'enamlnative.android.android_location.LocationManager'>, 'android.net.Uri': <class 'enamlnative.android.android_utils.Uri'>, 'android.net.wifi.WifiConfiguration': <class 'enamlnative.android.android_wifi.WifiConfiguration'>, 'android.new.wifi.WifiManager': <class 'enamlnative.android.android_wifi.WifiManager'>, 'android.os.Handler': <class 'enamlnative.android.android_utils.Handler'>, 'android.os.HandlerThread': <class 'enamlnative.android.android_utils.HandlerThread'>, 'android.os.VibrationEffect': <class 'enamlnative.android.android_vibrator.VibrationEffect'>, 'android.os.Vibrator': <class 'enamlnative.android.android_vibrator.Vibrator'>, 'android.util.AttributeSet': <class 'enamlnative.android.android_utils.AttributeSet'>, 'android.view.View': <class 'enamlnative.android.android_view.View'>, 'android.view.ViewGroup$LayoutParams': <class 'enamlnative.android.android_view.LayoutParams'>, 'android.view.Window': <class 'enamlnative.android.android_window.Window'>, 'android.view.inputmethod.InputMethodManager': <class 'enamlnative.android.android_utils.InputMethodManager'>, 'android.widget.ImageView': <class 'enamlnative.android.android_image_view.ImageView'>, 'androidx.core.app.NotificationCompat': <class 'enamlnative.android.android_notification.Notification'>, 'androidx.core.app.NotificationCompat$Builder': <class 'enamlnative.android.android_notification.Notification.Builder'>, 'androidx.core.app.NotificationManagerCompat': <class 'enamlnative.android.android_notification.NotificationManager'>, 'com.bumptech.glide.Glide': <class 'enamlnative.android.android_image_view.Glide'>, 'com.bumptech.glide.RequestBuilder': <class 'enamlnative.android.android_image_view.RequestBuilder'>, 'com.bumptech.glide.RequestManager': <class 'enamlnative.android.android_image_view.RequestManager'>, 'com.codelv.enamlnative.EnamlActivity': <class 'enamlnative.android.android_activity.Activity'>, 'com.codelv.enamlnative.adapters.BridgeBroadcastReceiver': <class 'enamlnative.android.android_content.BroadcastReceiver'>, 'java.lang.Object': <class 'enamlnative.android.android_content.SystemService'>, 'java.util.ArrayList': <class 'enamlnative.android.android_utils.ArrayList'>, 'java.util.HashMap': <class 'enamlnative.android.android_utils.HashMap'>, 'java.util.concurrent.Executor': <class 'enamlnative.android.android_utils.Executor'>, 'java.util.concurrent.Executors': <class 'enamlnative.android.android_utils.Executors'>}

Mapping of nativeclass str to subclasses

enamlnative.core.bridge.generate_id() int[source]

Generate an id for an object

enamlnative.core.bridge.convert_arg(arg: Any) Optional[str][source]

Convert an argument to a string

enamlnative.core.bridge.tag_object_with_id(obj)[source]

Generate and assign a id for the object

enamlnative.core.bridge.get_object_with_id(id)[source]

Get the object with the given id in the cache

enamlnative.core.bridge.get_app_class()[source]

Avoid circular import. Probably indicates a poor design…

enamlnative.core.bridge.encode(obj)[source]

Encode an object for proper decoding by Java or ObjC

enamlnative.core.bridge.msgpack_encoder(sig, obj)[source]

When passing a BridgeObject encode it in a special way so it can properly be interpreted as a reference.

TODO: This should use the object hooks for doing this automatically

enamlnative.core.bridge.dumps(data)[source]

Encodes events for sending over the bridge

enamlnative.core.bridge.loads(data)[source]

Decodes and processes events received from the bridge

exception enamlnative.core.bridge.BridgeReferenceError[source]

Bases: ReferenceError

This exception occurs when an event comes in from the bridge and python does not have any reference in the cache.

__weakref__

list of weak references to the object (if defined)

exception enamlnative.core.bridge.BridgeException[source]

Bases: Exception

This exception occurs when a remote method call fails.

__weakref__

list of weak references to the object (if defined)

enamlnative.core.bridge.get_handler(ptr: int, method: str) tuple[source]

Dereference the pointer and return the handler method.

class enamlnative.core.bridge.BridgeObject(*args, **kwargs)[source]

Bases: atom.atom.Atom

A proxy to a class in java. This sends the commands over the bridge for execution. The object is stored in a map with the given id and is valid until this object is deleted.

Parameters

__id__ (Int, Future, or None) –

If an __id__ keyword argument is passed during creation, then

If the __id__ is an int, this will assume the object was already created and only a reference to the object with the given id is needed.

If the __id__ is a Future (as specified by the app event loop), then the __id__ of he future will be used. When the future completes this object will then be put into the cache. This allows passing results directly instead of using the .then() method.

classmethod __init_subclass__(*args, **kwargs)[source]

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__init__(*args, **kwargs)[source]

Sends the event to create this object in Java.

__del__()[source]

Destroy this object and send a command to destroy the actual object reference the bridge implementation holds (allowing it to be released).

class enamlnative.core.bridge.NestedBridgeObject(root, attr, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeObject

A nested object allows you to invoke methods and set properties of an object that is a property of another object using the dot notation.

Useful for setting nested properties without needing to first create a reference bridge object (thus saving the time waiting for the bridge to reply) for example:

UIView view = [UIView new];

view.yoga.width = YES;

Would require to create a reference to the “yoga” object first but instead we just add our nested object’s prefix and let the bridge resolve the actual property. It works like a regular BridgeObject but appends the “name’.

This object is NOT in the cache on either side of the bridge.

__init__(root, attr, **kwargs)[source]

Sends the event to create this object in Java.

__del__()[source]

Destroy this object and send a command to destroy the actual object reference the bridge implementation holds (allowing it to be released).

class enamlnative.core.bridge.BridgeMethod(*args, **kwargs)[source]

Bases: atom.property.Property

A method that is callable via the bridge. When called, this serializes the call, packs the arguments, and delegates handling to a bridge in native code.

#: Define it class View(BridgeObject):

addView = BridgeMethod(‘android.view.View’)

#: Create instance view = View() view2 = View()

#: Use it view.addView(view2)

__init__(*args, **kwargs)[source]

Initialize a Property member.

Parameters
  • fget (callable or None, optional) – The callable invoked to get the property value. It must accept a single argument which is the owner object. If not provided, the property cannot be read. The default is None.

  • fset (callable or None, optional) – The callable invoked to set the property value. It must accept two arguments: the owner object and property value. If not provided, the property cannot be set. The default is None.

  • fdel (callable or None, optional) – The callable invoked to delete the property value. It must accept a single argument which is the owner object. If not provided, the property cannot be deleted. The default is None.

  • cached (bool, optional) – Whether or not the property caches the computed value. A cached property will only evaluate ‘fget’ once until the ‘reset’ method of the property is invoked. The default is False.

suppressed(obj: enamlnative.core.bridge.BridgeObject)[source]

Suppress calls within this context to avoid feedback loops

__call__(obj, *args, **kwargs)[source]

The Swift like syntax is used

pack_args(obj, *args, **kwargs)[source]

Subclasses should implement this to pack args as needed for the native bridge implementation. Must return a tuple containing (“methodName”, [list, of, encoded, args])

class enamlnative.core.bridge.BridgeStaticMethod(*args, **kwargs)[source]

Bases: atom.property.Property

A method that is callable via the bridge. When called, this serializes the call, packs the arguments, and delegates handling to a bridge in native code.

#: Define it class Toast(BridgeObject):

makeToast = BridgeStaticMethod(*args)

#: Use result = Toast.makeToast(*args)

__init__(*args, **kwargs)[source]

Initialize a Property member.

Parameters
  • fget (callable or None, optional) – The callable invoked to get the property value. It must accept a single argument which is the owner object. If not provided, the property cannot be read. The default is None.

  • fset (callable or None, optional) – The callable invoked to set the property value. It must accept two arguments: the owner object and property value. If not provided, the property cannot be set. The default is None.

  • fdel (callable or None, optional) – The callable invoked to delete the property value. It must accept a single argument which is the owner object. If not provided, the property cannot be deleted. The default is None.

  • cached (bool, optional) – Whether or not the property caches the computed value. A cached property will only evaluate ‘fget’ once until the ‘reset’ method of the property is invoked. The default is False.

__get__(instance, owner)[source]

Return an attribute of instance, which is of type owner.

__call__(*args, **kwargs)[source]

Call self as a function.

pack_args(obj, *args, **kwargs)[source]

Subclasses should implement this to pack args as needed for the native bridge implementation. Must return a tuple containing (“methodName”, [list, of, encoded, args])

class enamlnative.core.bridge.BridgeField(arg)[source]

Bases: atom.property.Property

Allows you to set fields or properties over the bridge using normal python syntax.

#: Define it class View(BridgeObject):

width = BridgeField(‘int’)

#: Create instance view = View()

#: Set field view.width = 200

__init__(arg)[source]

Initialize a Property member.

Parameters
  • fget (callable or None, optional) – The callable invoked to get the property value. It must accept a single argument which is the owner object. If not provided, the property cannot be read. The default is None.

  • fset (callable or None, optional) – The callable invoked to set the property value. It must accept two arguments: the owner object and property value. If not provided, the property cannot be set. The default is None.

  • fdel (callable or None, optional) – The callable invoked to delete the property value. It must accept a single argument which is the owner object. If not provided, the property cannot be deleted. The default is None.

  • cached (bool, optional) – Whether or not the property caches the computed value. A cached property will only evaluate ‘fget’ once until the ‘reset’ method of the property is invoked. The default is False.

suppressed(obj)[source]

Suppress calls within this context to avoid feedback loops

__fget__(obj)[source]

Return an object that can be used to retrieve the value.

class enamlnative.core.bridge.BridgeCallback(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeMethod

Description of a callback method of a View (or subclass) in Objc or Java. When called,it fires the connected callback. If no callback is connected it will try to lookup a default callback implementation matching the name _impl_<name>. If that does not exist, it will simply do nothing.

This is triggered when it receives an event from the bridge indicating the call has occurred.

#: Define it class View(BridgeObject):

onClick = BridgeCallback()

#: Create instance view = View()

def on_click():

print(“Clicked!”)

#: Connect to callback view.onClick.connect(on_click)

You can define a “default” callback implementation by implementing the method with name of _impl_<name>. Connecting a callback will override this behavior.

#: Define it class LocationManager(BridgeObject):

hashCode = BridgeCallback()

def _impl_hashCode(self):

return self.__id__

__weakref__

list of weak references to the object (if defined)

__call__(obj, *args)[source]

Fire the callback if one is connected

connect(obj, callback)[source]

Set the callback to be fired when the event occurs.

disconnect(obj, callback=None)[source]

Remove the callback to be fired when the event occurs.

class enamlnative.core.bridge.BridgeFuture(return_type: Optional[type] = None)[source]

Bases: _asyncio.Future

A future which automatically resolves to the return type

__init__(return_type: Optional[type] = None)[source]
set_result(result)[source]

Mark the future done and set its result.

If the future is already done when this method is called, raises InvalidStateError.

Java Bridge

Copyright (c) 2017-2022, CodeLV.

Distributed under the terms of the MIT License.

The full license is in the file LICENSE, distributed with this software.

Created on June 21, 2017

enamlnative.android.bridge.encode_args(method: enamlnative.core.bridge.BridgeMethod, args: tuple, encoder=<function msgpack_encoder>)[source]

Common function for packing method arguments.

class enamlnative.android.bridge.JavaMethod(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeMethod

Description of a method of a View (or subclass) in Java. When called, this serializes call, packs the arguments, and delegates handling to a bridge in Java.

pack_args(obj: enamlnative.core.bridge.BridgeObject, *args, **kwargs)[source]

Subclasses should implement this to pack args as needed for the native bridge implementation. Must return a tuple containing (“methodName”, [list, of, encoded, args])

__weakref__

list of weak references to the object (if defined)

class enamlnative.android.bridge.JavaStaticMethod(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeStaticMethod

pack_args(*args, **kwargs)[source]

Subclasses should implement this to pack args as needed for the native bridge implementation. Must return a tuple containing (“methodName”, [list, of, encoded, args])

__weakref__

list of weak references to the object (if defined)

class enamlnative.android.bridge.JavaField(arg)[source]

Bases: enamlnative.core.bridge.BridgeField

The superclass implementation is sufficient but extend for possible future modification.

__weakref__

list of weak references to the object (if defined)

class enamlnative.android.bridge.JavaCallback(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeCallback, enamlnative.android.bridge.JavaMethod

Description of a callback method of a View (or subclass) in Java. When called, it fires the connected callback. This is triggered when it receives an event from the bridge indicating the call has occured.

pack_args(obj: enamlnative.core.bridge.BridgeObject, *args, **kwargs)[source]

Subclasses should implement this to pack args as needed for the native bridge implementation. Must return a tuple containing (“methodName”, [list, of, encoded, args])

class enamlnative.android.bridge.JavaBridgeObject(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeObject

A proxy to a class in java. This sends the commands over the bridge for execution. The object is stored in a map with the given id and is valid until this object is deleted.

Parameters

__id__ (Int) – If an __id__ keyward argument is passed during creation, this will assume the object was already created and only a reference to the object with the given id is needed.

hashCode

A callback with an implementation built in

class enamlnative.android.bridge.JavaProxy(ref: Optional[enamlnative.core.bridge.BridgeObject] = None, **kwargs)[source]

Bases: enamlnative.android.bridge.JavaBridgeObject

A bridge object that creates a Proxy for the given ref. This should NOT be given any JavaMethods or JavaFields, however JavaCallbacks are fine.

These are generally throw away usages. Only save them if you need to use them as a reference later (such as when removing a listener).

Parameters

ref (JavaBridgeObject) – The bridge object that should receive all of the callbacks invocations. If none is given it will send them to the proxy itself.

__init__(ref: Optional[enamlnative.core.bridge.BridgeObject] = None, **kwargs)[source]

Sends the event to create this View in Java

Objective-C Bridge

Copyright (c) 2017-2022, CodeLV.

Distributed under the terms of the MIT License.

The full license is in the file LICENSE, distributed with this software.

Created on June 21, 2017

class enamlnative.ios.bridge.ObjcMethod(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeMethod

Description of a method of a View (or subclass) in Objc. When called, this serializes the call, packs the arguments, and delegates handling to a bridge in Objc.

To keep method calling similar to Swift instead of defining a method matching the signature with underscores like pyobjc and pyobjus the signature should be defined as follows:

  1. The first argument, if any, should be a string.

  2. Subsequent arguments should each be a dictionary of the available subnames and their types.

For instance:

UIView insertSubview has the following signatures:

  • (void)insertSubview:(UIView *)view

    atIndex:(NSInteger)index;

  • (void)insertSubview:(UIView *)view

    aboveSubview:(UIView *)siblingSubview;

  • (void)insertSubview:(UIView *)view

    belowSubview:(UIView *)siblingSubview;

This is defined in python like:

insertSubview = ObjcMethod(‘UIView’,
dict(atIndex=’NSInteger’,

aboveSubview=’UIView’, belowSubview=’UIView’))

Doing it this way it can be called like Swift, using kwargs

view.insertSubview(subview, atIndex=3) view.insertSubview(subview, aboveSubview=above_view)

pack_args(obj, *args, **kwargs)[source]

Arguments must be packed according to the kwargs passed and the signature defined.

__weakref__

list of weak references to the object (if defined)

class enamlnative.ios.bridge.ObjcProperty(arg)[source]

Bases: enamlnative.core.bridge.BridgeField

The superclass implementation is sufficient

__weakref__

list of weak references to the object (if defined)

class enamlnative.ios.bridge.ObjcCallback(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeCallback, enamlnative.ios.bridge.ObjcMethod

Description of a callback method of a View (or subclass) in Objc. When called, it fires the connected callback. This is triggered when it receives an event from the bridge indicating the call has occured.

pack_args(obj, *args, **kwargs)[source]

Subclasses should implement this to pack args as needed for the native bridge implementation. Must return a tuple containing (“methodName”, [list, of, encoded, args])

class enamlnative.ios.bridge.ObjcBridgeObject(*args, **kwargs)[source]

Bases: enamlnative.core.bridge.BridgeObject

A proxy to a class in java. This sends the commands over the bridge for execution. The object is stored in a map with the given id and is valid until this object is deleted.

Parameters

__id__ (Int) – If an __id__ keyward argument is passed during creation, this will assume the object was already created and only a reference to the object with the given id is needed.

classmethod __init_subclass__(*args, **kwargs)[source]

Use the class name by default as everything should be unique.

__init__(*args, **kwargs)[source]

Sends the event to create this View in Java