#!/usr/bin/python # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. """This module provides shared functionality for the system to generate Dart:html APIs from the IDL database.""" import emitter import monitored import os from generator import * from htmldartgenerator import * _js_custom_members = monitored.Set('systemhtml._js_custom_members', [ 'ArrayBuffer.slice', 'AudioBufferSourceNode.start', 'AudioBufferSourceNode.stop', 'AudioContext.createGain', 'AudioContext.createScriptProcessor', 'CanvasRenderingContext2D.lineDashOffset', 'Console.memory', 'Console.profiles', 'Console.assertCondition', 'Console.count', 'Console.debug', 'Console.dir', 'Console.dirxml', 'Console.error', 'Console.group', 'Console.groupCollapsed', 'Console.groupEnd', 'Console.info', 'Console.log', 'Console.markTimeline', 'Console.profile', 'Console.profileEnd', 'Console.time', 'Console.timeEnd', 'Console.timeStamp', 'Console.trace', 'Console.warn', 'CSSStyleDeclaration.setProperty', 'Element.insertAdjacentElement', 'Element.insertAdjacentHTML', 'Element.insertAdjacentText', 'Element.webkitMatchesSelector', 'Element.remove', 'ElementEvents.mouseWheel', 'ElementEvents.transitionEnd', 'DOMException.name', 'HTMLTableElement.createTBody', 'IDBDatabase.transaction', 'KeyboardEvent.initKeyboardEvent', 'MouseEvent.offsetX', 'MouseEvent.offsetY', 'Navigator.language', 'Navigator.webkitGetUserMedia', 'URL.createObjectURL', 'URL.revokeObjectURL', 'WheelEvent.wheelDeltaX', 'WheelEvent.wheelDeltaY', 'Window.cancelAnimationFrame', 'Window.console', 'Window.document', 'Window.indexedDB', 'Window.location', 'Window.open', 'Window.requestAnimationFrame', 'WorkerContext.indexedDB', ]) _js_custom_constructors = monitored.Set('systemhtml._js_custom_constructors', [ 'AudioContext', 'Blob', 'MutationObserver', 'Notification', 'RTCIceCandidate', 'RTCPeerConnection', 'RTCSessionDescription', 'SpeechRecognition', ]) # Classes that offer only static methods, and therefore we should suppress # constructor creation. _static_classes = set(['Url']) # Information for generating element constructors. # # TODO(sra): maybe remove all the argument complexity and use cascades. # # var c = new CanvasElement(width: 100, height: 70); # var c = new CanvasElement()..width = 100..height = 70; # class ElementConstructorInfo(object): def __init__(self, name=None, tag=None, params=[], opt_params=[], factory_provider_name='document'): self.name = name # The constructor name 'h1' in 'HeadingElement.h1' self.tag = tag or name # The HTML or SVG tag self.params = params self.opt_params = opt_params self.factory_provider_name = factory_provider_name def ConstructorInfo(self, interface_name): info = OperationInfo() info.overloads = None info.declared_name = interface_name info.name = interface_name info.constructor_name = self.name info.js_name = None info.type_name = interface_name info.param_infos = map(lambda tXn: ParamInfo(tXn[1], tXn[0], True), self.opt_params) info.requires_named_arguments = True info.factory_parameters = ['"%s"' % self.tag] info.pure_dart_constructor = True return info _html_element_constructors = monitored.Dict( 'systemhtml._html_element_constructors', { 'HTMLAnchorElement' : ElementConstructorInfo(tag='a', opt_params=[('DOMString', 'href')]), 'HTMLAreaElement': 'area', 'HTMLButtonElement': 'button', 'HTMLBRElement': 'br', 'HTMLBaseElement': 'base', 'HTMLBodyElement': 'body', 'HTMLButtonElement': 'button', 'HTMLCanvasElement': ElementConstructorInfo(tag='canvas', opt_params=[('int', 'width'), ('int', 'height')]), 'HTMLContentElement': 'content', 'HTMLDataListElement': 'datalist', 'HTMLDListElement': 'dl', 'HTMLDetailsElement': 'details', 'HTMLDivElement': 'div', 'HTMLEmbedElement': 'embed', 'HTMLFieldSetElement': 'fieldset', 'HTMLFormElement': 'form', 'HTMLHRElement': 'hr', 'HTMLHeadElement': 'head', 'HTMLHeadingElement': [ElementConstructorInfo('h1'), ElementConstructorInfo('h2'), ElementConstructorInfo('h3'), ElementConstructorInfo('h4'), ElementConstructorInfo('h5'), ElementConstructorInfo('h6')], 'HTMLHtmlElement': 'html', 'HTMLIFrameElement': 'iframe', 'HTMLImageElement': ElementConstructorInfo(tag='img', opt_params=[('DOMString', 'src'), ('int', 'width'), ('int', 'height')]), 'HTMLKeygenElement': 'keygen', 'HTMLLIElement': 'li', 'HTMLLabelElement': 'label', 'HTMLLegendElement': 'legend', 'HTMLLinkElement': 'link', 'HTMLMapElement': 'map', 'HTMLMenuElement': 'menu', 'HTMLMeterElement': 'meter', 'HTMLOListElement': 'ol', 'HTMLObjectElement': 'object', 'HTMLOptGroupElement': 'optgroup', 'HTMLOutputElement': 'output', 'HTMLParagraphElement': 'p', 'HTMLParamElement': 'param', 'HTMLPreElement': 'pre', 'HTMLProgressElement': 'progress', 'HTMLScriptElement': 'script', 'HTMLSelectElement': 'select', 'HTMLSourceElement': 'source', 'HTMLSpanElement': 'span', 'HTMLStyleElement': 'style', 'HTMLTableCaptionElement': 'caption', 'HTMLTableCellElement': 'td', 'HTMLTableColElement': 'col', 'HTMLTableElement': 'table', 'HTMLTableRowElement': 'tr', #'HTMLTableSectionElement'
'HTMLTextAreaElement': 'textarea', 'HTMLTitleElement': 'title', 'HTMLTrackElement': 'track', 'HTMLUListElement': 'ul', 'HTMLVideoElement': 'video' }) _svg_element_constructors = monitored.Dict( 'systemhtml._svg_element_constructors', { 'SVGAElement': 'a', 'SVGAltGlyphElement': 'altGlyph', 'SVGAnimateElement': 'animate', 'SVGAnimateMotionElement': 'animateMotion', 'SVGAnimateTransformElement': 'animateTransform', 'SVGAnimationElement': 'animation', 'SVGCircleElement': 'circle', 'SVGClipPathElement': 'clipPath', 'SVGCursorElement': 'cursor', 'SVGDefsElement': 'defs', 'SVGDescElement': 'desc', 'SVGEllipseElement': 'ellipse', 'SVGFEBlendElement': 'feBlend', 'SVGFEColorMatrixElement': 'feColorMatrix', 'SVGFEComponentTransferElement': 'feComponentTransfer', 'SVGFEConvolveMatrixElement': 'feConvolveMatrix', 'SVGFEDiffuseLightingElement': 'feDiffuseLighting', 'SVGFEDisplacementMapElement': 'feDisplacementMap', 'SVGFEDistantLightElement': 'feDistantLight', 'SVGFEFloodElement': 'feFlood', 'SVGFEFuncAElement': 'feFuncA', 'SVGFEFuncBElement': 'feFuncB', 'SVGFEFuncGElement': 'feFuncG', 'SVGFEFuncRElement': 'feFuncR', 'SVGFEGaussianBlurElement': 'feGaussianBlur', 'SVGFEImageElement': 'feImage', 'SVGFEMergeElement': 'feMerge', 'SVGFEMergeNodeElement': 'feMergeNode', 'SVGFEMorphology': 'feMorphology', 'SVGFEOffsetElement': 'feOffset', 'SVGFEPointLightElement': 'fePointLight', 'SVGFESpecularLightingElement': 'feSpecularLighting', 'SVGFESpotLightElement': 'feSpotLight', 'SVGFETileElement': 'feTile', 'SVGFETurbulenceElement': 'feTurbulence', 'SVGFilterElement': 'filter', 'SVGForeignObjectElement': 'foreignObject', 'SVGGlyphElement': 'glyph', 'SVGGElement': 'g', 'SVGHKernElement': 'hkern', 'SVGImageElement': 'image', 'SVGLinearGradientElement': 'linearGradient', 'SVGLineElement': 'line', 'SVGMarkerElement': 'marker', 'SVGMaskElement': 'mask', 'SVGMPathElement': 'mpath', 'SVGPathElement': 'path', 'SVGPatternElement': 'pattern', 'SVGPolygonElement': 'polygon', 'SVGPolylineElement': 'polyline', 'SVGRadialGradientElement': 'radialGradient', 'SVGRectElement': 'rect', 'SVGScriptElement': 'script', 'SVGSetElement': 'set', 'SVGStopElement': 'stop', 'SVGStyleElement': 'style', 'SVGSwitchElement': 'switch', 'SVGSymbolElement': 'symbol', 'SVGTextElement': 'text', 'SVGTitleElement': 'title', 'SVGTRefElement': 'tref', 'SVGTSpanElement': 'tspan', 'SVGUseElement': 'use', 'SVGViewElement': 'view', 'SVGVKernElement': 'vkern', }) _element_constructors = { 'html': _html_element_constructors, 'indexed_db': {}, 'svg': _svg_element_constructors, 'web_audio': {}, } _factory_ctr_strings = { 'html': { 'provider_name': 'document', 'constructor_name': '$dom_createElement' }, 'indexed_db': { 'provider_name': 'document', 'constructor_name': '$dom_createElement' }, 'svg': { 'provider_name': '_SvgElementFactoryProvider', 'constructor_name': 'createSvgElement_tag', }, 'web_audio': { 'provider_name': 'document', 'constructor_name': '$dom_createElement' }, } def ElementConstructorInfos(typename, element_constructors, factory_provider_name='_Elements'): """Returns list of ElementConstructorInfos about the convenience constructors for an Element or SvgElement.""" # TODO(sra): Handle multiple and named constructors. if typename not in element_constructors: return [] infos = element_constructors[typename] if isinstance(infos, str): infos = ElementConstructorInfo(tag=infos, factory_provider_name=factory_provider_name) if not isinstance(infos, list): infos = [infos] return infos # ------------------------------------------------------------------------------ def SvgSupportStr(tagName): return 'Svg%s' % ElemSupportStr(tagName) def ElemSupportStr(tagName): return "Element.isTagSupported('%s')" % tagName _js_support_checks_basic_element_with_constructors = [ 'HTMLContentElement', 'HTMLDataListElement', 'HTMLDetailsElement', 'HTMLEmbedElement', 'HTMLMeterElement', 'HTMLObjectElement', 'HTMLOutputElement', 'HTMLProgressElement', 'HTMLTrackElement', ] _js_support_checks_additional_element = [ # IE creates keygen as Block elements 'HTMLKeygenElement', 'SVGAltGlyphElement', 'SVGAnimateElement', 'SVGAnimateMotionElement', 'SVGAnimateTransformElement', 'SVGCursorElement', 'SVGFEBlendElement', 'SVGFEColorMatrixElement', 'SVGFEComponentTransferElement', 'SVGFEConvolveMatrixElement', 'SVGFEDiffuseLightingElement', 'SVGFEDisplacementMapElement', 'SVGFEDistantLightElement', 'SVGFEFloodElement', 'SVGFEFuncAElement', 'SVGFEFuncBElement', 'SVGFEFuncGElement', 'SVGFEFuncRElement', 'SVGFEGaussianBlurElement', 'SVGFEImageElement', 'SVGFEMergeElement', 'SVGFEMergeNodeElement', 'SVGFEMorphology', 'SVGFEOffsetElement', 'SVGFEPointLightElement', 'SVGFESpecularLightingElement', 'SVGFESpotLightElement', 'SVGFETileElement', 'SVGFETurbulenceElement', 'SVGFilterElement', 'SVGForeignObjectElement', 'SVGSetElement', ] js_support_checks = dict({ 'ArrayBuffer': "JS('bool', 'typeof window.ArrayBuffer != \"undefined\"')", 'Database': "JS('bool', '!!(window.openDatabase)')", 'DOMApplicationCache': "JS('bool', '!!(window.applicationCache)')", 'DOMFileSystem': "JS('bool', '!!(window.webkitRequestFileSystem)')", 'FormData': "JS('bool', '!!(window.FormData)')", 'HashChangeEvent': "Event._isTypeSupported('HashChangeEvent')", 'HTMLShadowElement': ElemSupportStr('shadow'), 'MediaStreamEvent': "Event._isTypeSupported('MediaStreamEvent')", 'MediaStreamTrackEvent': "Event._isTypeSupported('MediaStreamTrackEvent')", 'NotificationCenter': "JS('bool', '!!(window.webkitNotifications)')", 'Performance': "JS('bool', '!!(window.performance)')", 'SpeechRecognition': "JS('bool', '!!(window.SpeechRecognition || " "window.webkitSpeechRecognition)')", 'SVGExternalResourcesRequired': ('supported(SvgElement element)', "JS('bool', '#.externalResourcesRequired !== undefined && " "#.externalResourcesRequired.animVal !== undefined', " "element, element)"), 'SVGLangSpace': ('supported(SvgElement element)', "JS('bool', '#.xmlspace !== undefined && #.xmllang !== undefined', " "element, element)"), 'TouchList': "JS('bool', '!!document.createTouchList')", 'XMLHttpRequestProgressEvent': "Event._isTypeSupported('XMLHttpRequestProgressEvent')", 'WebGLRenderingContext': "JS('bool', '!!(window.WebGLRenderingContext)')", 'WebKitCSSMatrix': "JS('bool', '!!(window.WebKitCSSMatrix)')", 'WebKitPoint': "JS('bool', '!!(window.WebKitPoint)')", 'WebSocket': "JS('bool', 'typeof window.WebSocket != \"undefined\"')", 'XSLTProcessor': "JS('bool', '!!(window.XSLTProcessor)')", }.items() + dict((key, SvgSupportStr(_svg_element_constructors[key]) if key.startswith('SVG') else ElemSupportStr(_html_element_constructors[key])) for key in _js_support_checks_basic_element_with_constructors + _js_support_checks_additional_element).items()) # ------------------------------------------------------------------------------ class HtmlDartInterfaceGenerator(object): """Generates dart interface and implementation for the DOM IDL interface.""" def __init__(self, options, library_emitter, event_generator, interface, backend): self._renamer = options.renamer self._database = options.database self._template_loader = options.templates self._type_registry = options.type_registry self._options = options self._library_emitter = library_emitter self._event_generator = event_generator self._interface = interface self._backend = backend self._interface_type_info = self._type_registry.TypeInfo(self._interface.id) self._library_name = self._renamer.GetLibraryName(self._interface) def Generate(self): if 'Callback' in self._interface.ext_attrs: self.GenerateCallback() else: self.GenerateInterface() def GenerateCallback(self): """Generates a typedef for the callback interface.""" handlers = [operation for operation in self._interface.operations if operation.id == 'handleEvent'] info = AnalyzeOperation(self._interface, handlers) code = self._library_emitter.FileEmitter(self._interface.id, self._library_name) code.Emit(self._template_loader.Load('callback.darttemplate')) typedef_name = self._renamer.RenameInterface(self._interface) code.Emit('typedef void $NAME($PARAMS);\n', LIBRARYNAME='dart.dom.%s' % self._library_name, NAME=typedef_name, PARAMS=info.ParametersDeclaration(self._DartType)) self._backend.GenerateCallback(info) def GenerateInterface(self): interface_name = self._interface_type_info.interface_name() factory_provider = None if interface_name in interface_factories: factory_provider = interface_factories[interface_name] factory_constructor_name = None constructors = [] if interface_name in _static_classes: constructor_info = None else: constructor_info = AnalyzeConstructor(self._interface) if constructor_info: constructors.append(constructor_info) # TODO(antonm): consider removing it later. factory_provider = interface_name # HTML Elements and SVG Elements have convenience constructors. infos = ElementConstructorInfos(self._interface.id, _element_constructors[self._library_name], factory_provider_name= _factory_ctr_strings[self._library_name]['provider_name']) if infos: factory_constructor_name = _factory_ctr_strings[ self._library_name]['constructor_name'] for info in infos: constructors.append(info.ConstructorInfo(self._interface.id)) if factory_provider: assert factory_provider == info.factory_provider_name else: factory_provider = info.factory_provider_name implementation_emitter = self._ImplementationEmitter() base_type_info = None if self._interface.parents: supertype = self._interface.parents[0].type.id if not IsDartCollectionType(supertype) and not IsPureInterface(supertype): base_type_info = self._type_registry.TypeInfo(supertype) if base_type_info.merged_into() \ and self._backend.ImplementsMergedMembers(): base_type_info = self._type_registry.TypeInfo( base_type_info.merged_into()) if base_type_info: base_class = base_type_info.implementation_name() else: base_class = self._backend.RootClassName() implements = self._backend.AdditionalImplementedInterfaces() for parent in self._interface.parents: parent_type_info = self._type_registry.TypeInfo(parent.type.id) if parent_type_info.interface_name() != base_class and \ parent_type_info != base_type_info: implements.append(parent_type_info.interface_name()) secure_base_name = self._backend.SecureBaseName(interface_name) if secure_base_name: implements.append(secure_base_name) implements_str = '' if implements: implements_str = ' implements ' + ', '.join(set(implements)) annotations = FormatAnnotationsAndComments( GetAnnotationsAndComments(self._library_name, self._interface.doc_js_name), '') self._implementation_members_emitter = implementation_emitter.Emit( self._backend.ImplementationTemplate(), LIBRARYNAME='dart.dom.%s' % self._library_name, ANNOTATIONS=annotations, CLASSNAME=self._interface_type_info.implementation_name(), EXTENDS=' extends %s' % base_class if base_class else '', IMPLEMENTS=implements_str, DOMNAME=self._interface.doc_js_name, NATIVESPEC=self._backend.NativeSpec()) self._backend.StartInterface(self._implementation_members_emitter) self._backend.EmitHelpers(base_class) self._event_generator.EmitStreamProviders( self._interface, self._backend.CustomJSMembers(), self._implementation_members_emitter, self._library_name) self._backend.AddConstructors( constructors, factory_provider, factory_constructor_name) self._backend.EmitSupportCheck() merged_interface = self._interface_type_info.merged_interface() if merged_interface: self._backend.AddMembers(self._database.GetInterface(merged_interface), not self._backend.ImplementsMergedMembers()) self._backend.AddMembers(self._interface) self._backend.AddSecondaryMembers(self._interface) self._event_generator.EmitStreamGetters( self._interface, [], self._implementation_members_emitter, self._library_name) self._backend.FinishInterface() def _ImplementationEmitter(self): basename = self._interface_type_info.implementation_name() if (self._interface_type_info.merged_into() and self._backend.ImplementsMergedMembers()): # Merged members are implemented in target interface implementation. return emitter.Emitter() return self._library_emitter.FileEmitter(basename, self._library_name) def _DartType(self, type_name): return self._type_registry.DartType(type_name) # ------------------------------------------------------------------------------ class Dart2JSBackend(HtmlDartGenerator): """Generates a dart2js class for the dart:html library from a DOM IDL interface. """ def __init__(self, interface, options): super(Dart2JSBackend, self).__init__(interface, options) self._database = options.database self._template_loader = options.templates self._type_registry = options.type_registry self._renamer = options.renamer self._interface_type_info = self._type_registry.TypeInfo(self._interface.id) self._current_secondary_parent = None self._library_name = self._renamer.GetLibraryName(self._interface) def ImplementsMergedMembers(self): return True def GenerateCallback(self, info): pass def RootClassName(self): return None def AdditionalImplementedInterfaces(self): implements = super(Dart2JSBackend, self).AdditionalImplementedInterfaces() if self._interface_type_info.list_item_type(): implements.append('JavaScriptIndexingBehavior') return implements def NativeSpec(self): native_spec = MakeNativeSpec(self._interface.javascript_binding_name) return ' native "%s"' % native_spec def ImplementationTemplate(self): if IsPureInterface(self._interface.id): return self._template_loader.Load('pure_interface.darttemplate') template_file = ('impl_%s.darttemplate' % self._interface.doc_js_name) return (self._template_loader.TryLoad(template_file) or self._template_loader.Load('dart2js_impl.darttemplate')) def StartInterface(self, members_emitter): self._members_emitter = members_emitter def FinishInterface(self): pass def HasSupportCheck(self): return self._interface.doc_js_name in js_support_checks def GetSupportCheck(self): """Return a tuple of the support check function signature and the support test itself. If no parameters are supplied, we assume the default.""" if self._interface.doc_js_name in _js_support_checks_additional_element: if self._interface.doc_js_name in _svg_element_constructors: lib_prefix = 'Svg' constructors = _svg_element_constructors else: lib_prefix = '' constructors = _html_element_constructors return (js_support_checks.get(self._interface.doc_js_name) + " && (new %sElement.tag('%s') is %s)" % (lib_prefix, constructors[self._interface.doc_js_name], self._renamer.RenameInterface(self._interface))) return js_support_checks.get(self._interface.doc_js_name) def GenerateCustomFactory(self, constructor_info): # Custom factory will be taken from the template. return self._interface.doc_js_name in _js_custom_constructors def IsConstructorArgumentOptional(self, argument): return 'Optional' in argument.ext_attrs def EmitStaticFactoryOverload(self, constructor_info, name, arguments): index = len(arguments) arguments = constructor_info.ParametersAsArgumentList(index) if arguments: arguments = ', ' + arguments self._members_emitter.Emit( " static $INTERFACE_NAME $NAME($PARAMETERS) => " "JS('$INTERFACE_NAME', 'new $CTOR_NAME($PLACEHOLDERS)'$ARGUMENTS);\n", INTERFACE_NAME=self._interface_type_info.interface_name(), NAME=name, # TODO(antonm): add types to parameters. PARAMETERS=constructor_info.ParametersAsArgumentList(index), CTOR_NAME=constructor_info.name or self._interface.doc_js_name, PLACEHOLDERS=','.join(['#'] * index), ARGUMENTS=arguments) def SecondaryContext(self, interface): if interface is not self._current_secondary_parent: self._current_secondary_parent = interface self._members_emitter.Emit('\n // From $WHERE\n', WHERE=interface.id) def AddIndexer(self, element_type): """Adds all the methods required to complete implementation of List.""" # We would like to simply inherit the implementation of everything except # length, [], and maybe []=. It is possible to extend from a base # array implementation class only when there is no other implementation # inheritance. There might be no implementation inheritance other than # DOMBaseWrapper for many classes, but there might be some where the # array-ness is introduced by a non-root interface: # # interface Y extends X, List