not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.8 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Sugar interface for Enyo JavaScript framework
  4. import logging
  5. import json
  6. import inspect
  7. class Enyo:
  8. """Class to handle communication with Enyo"""
  9. def __init__(self, webview):
  10. """Constructor: link to the WebKit widget"""
  11. self.webview = webview
  12. self.handlers = {}
  13. self.webview.connect("console-message", self._message_emitted)
  14. def connect(self, name, callback):
  15. """Add a new handler for an event"""
  16. self.handlers[name] = callback
  17. def send_message(self, name, args=None):
  18. """Send a message to Enyo"""
  19. script = "enyo.Sugar.sendMessage('"+name+"', "
  20. if not args is None:
  21. value = "'"+self.json_encode(args)+"'"
  22. else:
  23. value = "null"
  24. script = script+value+")"
  25. logging.warning("sugar://"+name+"/"+value)
  26. return self.webview.execute_script(script)
  27. def _message_emitted(self, widget, value, line, source):
  28. """Raised when a message from Enyo has been received"""
  29. # Only consider prefixed message
  30. prefix = "enyo://"
  31. if not value.startswith(prefix):
  32. return False
  33. # Get name
  34. prefixlen = len(prefix)
  35. size = value[prefixlen:prefixlen+value[prefixlen:].index("/")]
  36. start = prefixlen+1+len(size)
  37. name = value[start:start+int(size)]
  38. # Get param
  39. start = start + len(name)+1
  40. size = value[start:start+value[start:].index("/")]
  41. if int(size) == 0:
  42. args = None
  43. else:
  44. start = start+1+len(size)
  45. args = value[start:]
  46. # Call handler if exist
  47. logging.warning(value);
  48. if name in self.handlers:
  49. callback = self.handlers[name]
  50. if args:
  51. callback(json.loads(args))
  52. else:
  53. callback(None)
  54. return True
  55. def json_encode(self, obj):
  56. """Encode object as a JSON string"""
  57. try:
  58. result = json.dumps(obj)
  59. except TypeError:
  60. result = "{"
  61. first = True
  62. for name in dir(obj):
  63. value = getattr(obj, name)
  64. if not name.startswith('__') and not inspect.ismethod(value) and not inspect.isroutine(value) and not inspect.isbuiltin(value) and not isinstance(value, obj.__class__):
  65. if not first:
  66. result = result + ', '
  67. else:
  68. first = False
  69. result = result + '"'+name+'": '
  70. result = result + self.json_encode(value)
  71. result = result + "}"
  72. return result
  73. def json_decode(self, str):
  74. """Decode JSON string as object"""
  75. return json.loads(str)