text:
WebInspector.ElementsTreeOutline = function() {
    this.element = document.createElement("ol");
    this.element.addEventListener("mousedown", this._onmousedown.bind(this), false);
    this.element.addEventListener("mousemove", this._onmousemove.bind(this), false);
    this.element.addEventListener("mouseout", this._onmouseout.bind(this), false);

    TreeOutline.call(this, this.element);

    this.includeRootDOMNode = true;
    this.selectEnabled = false;
    this.showInElementsPanelEnabled = false;
    this.rootDOMNode = null;
    this.focusedDOMNode = null;

    this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true);
    this.element.addEventListener("keydown", this._keyDown.bind(this), true);
}

WebInspector.ElementsTreeOutline.prototype = {
    get rootDOMNode()
    {
        return this._rootDOMNode;
    },

    set rootDOMNode(x)
    {
        if (this._rootDOMNode === x)
            return;

        this._rootDOMNode = x;

        this._isXMLMimeType = !!(WebInspector.mainResource && WebInspector.mainResource.mimeType && WebInspector.mainResource.mimeType.match(/x(?:ht)?ml/i));

        this.update();
    },

    get isXMLMimeType()
    {
        return this._isXMLMimeType;
    },

    nodeNameToCorrectCase: function(nodeName)
    {
        return this.isXMLMimeType ? nodeName : nodeName.toLowerCase();
    },

    get focusedDOMNode()
    {
        return this._focusedDOMNode;
    },

    set focusedDOMNode(x)
    {
        if (this._focusedDOMNode === x) {
            this.revealAndSelectNode(x);
            return;
        }

        this._focusedDOMNode = x;

        this.revealAndSelectNode(x);

        // The revealAndSelectNode() method might find a different element if there is inlined text,
        // and the select() call would change the focusedDOMNode and reenter this setter. So to
        // avoid calling focusedNodeChanged() twice, first check if _focusedDOMNode is the same
        // node as the one passed in.
        if (this._focusedDOMNode === x) {
            this.focusedNodeChanged();

            if (x && !this.suppressSelectHighlight) {
                InspectorBackend.highlightDOMNode(x.id);

                if ("_restorePreviousHighlightNodeTimeout" in this)
                    clearTimeout(this._restorePreviousHighlightNodeTimeout);

                function restoreHighlightToHoveredNode()
                {
                    var hoveredNode = WebInspector.hoveredDOMNode;
                    if (hoveredNode)
                        InspectorBackend.highlightDOMNode(hoveredNode.id);
                    else
                        InspectorBackend.hideDOMNodeHighlight();
                }

                this._restorePreviousHighlightNodeTimeout = setTimeout(restoreHighlightToHoveredNode, 2000);
            }
        }
    },

    update: function()
    {
        var selectedNode = this.selectedTreeElement ? this.selectedTreeElement.representedObject : null;

        this.removeChildren();

        if (!this.rootDOMNode)
            return;

        var treeElement;
        if (this.includeRootDOMNode) {
            treeElement = new WebInspector.ElementsTreeElement(this.rootDOMNode);
            treeElement.selectable = this.selectEnabled;
            this.appendChild(treeElement);
        } else {
            // FIXME: this could use findTreeElement to reuse a tree element if it already exists
            var node = this.rootDOMNode.firstChild;
            while (node) {
                treeElement = new WebInspector.ElementsTreeElement(node);
                treeElement.selectable = this.selectEnabled;
                this.appendChild(treeElement);
                node = node.nextSibling;
            }
        }

        if (selectedNode)
            this.revealAndSelectNode(selectedNode);
    },

    updateSelection: function()
    {
        if (!this.selectedTreeElement)
            return;
        var element = this.treeOutline.selectedTreeElement;
        element.updateSelection();
    },

    focusedNodeChanged: function(forceUpdate) {},

    findTreeElement: function(node)
    {
        var treeElement = TreeOutline.prototype.findTreeElement.call(this, node, isAncestorNode, parentNode);
        if (!treeElement && node.nodeType === Node.TEXT_NODE) {
            // The text node might have been inlined if it was short, so try to find the parent element.
            treeElement = TreeOutline.prototype.findTreeElement.call(this, node.parentNode, isAncestorNode, parentNode);
        }

        return treeElement;
    },

    createTreeElementFor: function(node)
    {
        var treeElement = this.findTreeElement(node);
        if (treeElement)
            return treeElement;
        if (!node.parentNode)
            return null;

        var treeElement = this.createTreeElementFor(node.parentNode);
        if (treeElement && treeElement.showChild(node.index))
            return treeElement.children[node.index];

        return null;
    },

    set suppressRevealAndSelect(x)
    {
        if (this._suppressRevealAndSelect === x)
            return;
        this._suppressRevealAndSelect = x;
    },

    revealAndSelectNode: function(node)
    {
        if (!node || this._suppressRevealAndSelect)
            return;

        var treeElement = this.createTreeElementFor(node);
        if (!treeElement)
            return;

        treeElement.reveal();
        treeElement.select();
    },

    _treeElementFromEvent: function(event)
    {
        var root = this.element;

        // We choose this X coordinate based on the knowledge that our list
        // items extend nearly to the right edge of the outer <ol>.
        var x = root.totalOffsetLeft + root.offsetWidth - 20;

        var y = event.pageY;

        // Our list items have 1-pixel cracks between them vertically. We avoid
        // the cracks by checking slightly above and slightly below the mouse
        // and seeing if we hit the same element each time.
        var elementUnderMouse = this.treeElementFromPoint(x, y);
        var elementAboveMouse = this.treeElementFromPoint(x, y - 2);
        var element;
        if (elementUnderMouse === elementAboveMouse)
            element = elementUnderMouse;
        else
            element = this.treeElementFromPoint(x, y + 2);

        return element;
    },

    _keyDown: function(event)
    {
        if (event.target !== this.treeOutline.element)
            return;

        var selectedElement = this.selectedTreeElement;
        if (!selectedElement)
            return;

        if (event.keyCode === WebInspector.KeyboardShortcut.KeyCodes.Backspace ||
                event.keyCode === WebInspector.KeyboardShortcut.KeyCodes.Delete) {
            var startTagTreeElement = this.findTreeElement(selectedElement.representedObject);
            if (selectedElement !== startTagTreeElement)
                selectedElement = startTagTreeElement;
            selectedElement.remove();
            event.preventDefault();
            event.stopPropagation();
            return;
        }

        // On Enter or Return start editing the first attribute
        // or create a new attribute on the selected element.
        if (isEnterKey(event)) {
            if (this._editing)
                return;

            selectedElement._startEditing();

            // prevent a newline from being immediately inserted
            event.preventDefault();
            event.stopPropagation();
            return;
        }
    },

    _onmousedown: function(event)
    {
        var element = this._treeElementFromEvent(event);

        if (!element || element.isEventWithinDisclosureTriangle(event))
            return;

        element.select();
    },

    _onmousemove: function(event)
    {
        var element = this._treeElementFromEvent(event);
        if (element && this._previousHoveredElement === element)
            return;

        if (this._previousHoveredElement) {
            this._previousHoveredElement.hovered = false;
            delete this._previousHoveredElement;
        }

        if (element) {
            element.hovered = true;
            this._previousHoveredElement = element;
        }

        WebInspector.hoveredDOMNode = (element ? element.representedObject : null);
    },

    _onmouseout: function(event)
    {
        var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
        if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.element))
            return;

        if (this._previousHoveredElement) {
            this._previousHoveredElement.hovered = false;
            delete this._previousHoveredElement;
        }

        WebInspector.hoveredDOMNode = null;
    },

    _contextMenuEventFired: function(event)
    {
        var listItem = event.target.enclosingNodeOrSelfWithNodeName("LI");
        if (!listItem || !listItem.treeElement)
            return;

        var contextMenu = new WebInspector.ContextMenu();

        var tag = event.target.enclosingNodeOrSelfWithClass("webkit-html-tag");
        var textNode = event.target.enclosingNodeOrSelfWithClass("webkit-html-text-node");
        if (tag && listItem.treeElement._populateTagContextMenu)
            listItem.treeElement._populateTagContextMenu(contextMenu, event);
        else if (textNode && listItem.treeElement._populateTextContextMenu)
            listItem.treeElement._populateTextContextMenu(contextMenu, textNode);
        contextMenu.show(event);
    }
}

WebInspector.ElementsTreeOutline.prototype.__proto__ = TreeOutline.prototype;

WebInspector.ElementsTreeElement = function(node, elementCloseTag)
{
    this._elementCloseTag = elementCloseTag;
    var hasChildrenOverride = !elementCloseTag && node.hasChildNodes() && !this._showInlineText(node);

    // The title will be updated in onattach.
    TreeElement.call(this, "", node, hasChildrenOverride);

    if (this.representedObject.nodeType == Node.ELEMENT_NODE && !elementCloseTag)
        this._canAddAttributes = true;
    this._searchQuery = null;
    this._expandedChildrenLimit = WebInspector.ElementsTreeElement.InitialChildrenLimit;
}

WebInspector.ElementsTreeElement.InitialChildrenLimit = 500;

// A union of HTML4 and HTML5-Draft elements that explicitly
// or implicitly (for HTML5) forbid the closing tag.
// FIXME: Revise once HTML5 Final is published.
WebInspector.ElementsTreeElement.ForbiddenClosingTagElements = [
    "area", "base", "basefont", "br", "canvas", "col", "command", "embed", "frame",
    "hr", "img", "input", "isindex", "keygen", "link", "meta", "param", "source"
].keySet();

// These tags we do not allow editing their tag name.
WebInspector.ElementsTreeElement.EditTagBlacklist = [
    "html", "head", "body"
].keySet();

WebInspector.ElementsTreeElement.prototype = {
    highlightSearchResults: function(searchQuery)
    {
        if (this._searchQuery === searchQuery)
            return;

        this._searchQuery = searchQuery;
        this.updateTitle();
    },

    get hovered()
    {
        return this._hovered;
    },

    set hovered(x)
    {
        if (this._hovered === x)
            return;

        this._hovered = x;

        if (this.listItemElement) {
            if (x) {
                this.updateSelection();
                this.listItemElement.addStyleClass("hovered");
            } else {
                this.listItemElement.removeStyleClass("hovered");
            }
        }
    },

    get expandedChildrenLimit()
    {
        return this._expandedChildrenLimit;
    },

    set expandedChildrenLimit(x)
    {
        if (this._expandedChildrenLimit === x)
            return;

        this._expandedChildrenLimit = x;
        if (this.treeOutline && !this._updateChildrenInProgress)
            this._updateChildren(true);
    },

    get expandedChildCount()
    {
        var count = this.children.length;
        if (count && this.children[count - 1]._elementCloseTag)
            count--;
        if (count && this.children[count - 1].expandAllButton)
            count--;
        return count;
    },

    showChild: function(index)
    {
        if (this._elementCloseTag)
            return;

        if (index >= this.expandedChildrenLimit) {
            this._expandedChildrenLimit = index + 1;
            this._updateChildren(true);
        }

        // Whether index-th child is visible in the children tree
        return this.expandedChildCount > index;
    },

    createTooltipForImageNode: function(node, callback)
    {
        if (this._elementCloseTag)
            return;

        function createTooltipThenCallback(properties)
        {
            if (!properties) {
                callback();
                return;
            }

            var tooltipText = null;
            if (properties.offsetHeight === properties.naturalHeight && properties.offsetWidth === properties.naturalWidth)
                tooltipText = WebInspector.UIString("%d × %d pixels", properties.offsetWidth, properties.offsetHeight);
            else
                tooltipText = WebInspector.UIString("%d × %d pixels (Natural: %d × %d pixels)", properties.offsetWidth, properties.offsetHeight, properties.naturalWidth, properties.naturalHeight);
            callback(tooltipText);
        }
        var objectProxy = new WebInspector.ObjectProxy(node.injectedScriptId, node.id);
        WebInspector.ObjectProxy.getPropertiesAsync(objectProxy, ["naturalHeight", "naturalWidth", "offsetHeight", "offsetWidth"], createTooltipThenCallback);
    },

    updateSelection: function()
    {
        var listItemElement = this.listItemElement;
        if (!listItemElement)
            return;

        if (document.body.offsetWidth <= 0) {
            // The stylesheet hasn't loaded yet or the window is closed,
            // so we can't calculate what is need. Return early.
            return;
        }

        if (!this.selectionElement) {
            this.selectionElement = document.createElement("div");
            this.selectionElement.className = "selection selected";
            listItemElement.insertBefore(this.selectionElement, listItemElement.firstChild);
        }

        this.selectionElement.style.height = listItemElement.offsetHeight + "px";
    },

    onattach: function()
    {
        if (this._hovered) {
            this.updateSelection();
            this.listItemElement.addStyleClass("hovered");
        }

        this.updateTitle();

        this._preventFollowingLinksOnDoubleClick();
    },

    _preventFollowingLinksOnDoubleClick: function()
    {
        var links = this.listItemElement.querySelectorAll("li > .webkit-html-tag > .webkit-html-attribute > .webkit-html-external-link, li > .webkit-html-tag > .webkit-html-attribute > .webkit-html-resource-link");
        if (!links)
            return;

        for (var i = 0; i < links.length; ++i)
            links[i].preventFollowOnDoubleClick = true;
    },

    onpopulate: function()
    {
        if (this.children.length || this._showInlineText(this.representedObject) || this._elementCloseTag)
            return;

        this.updateChildren();
    },

    updateChildren: function(fullRefresh)
    {
        if (this._elementCloseTag)
            return;

        WebInspector.domAgent.getChildNodesAsync(this.representedObject, this._updateChildren.bind(this, fullRefresh));
    },

    insertChildElement: function(child, index, closingTag)
    {
        var newElement = new WebInspector.ElementsTreeElement(child, closingTag);
        newElement.selectable = this.treeOutline.selectEnabled;
        this.insertChild(newElement, index);
        return newElement;
    },

    moveChild: function(child, targetIndex)
    {
        var wasSelected = child.selected;
        this.removeChild(child);
        this.insertChild(child, targetIndex);
        if (wasSelected)
            child.select();
    },

    _updateChildren: function(fullRefresh)
    {
        if (this._updateChildrenInProgress)
            return;

        this._updateChildrenInProgress = true;
        var focusedNode = this.treeOutline.focusedDOMNode;
        var originalScrollTop;
        if (fullRefresh) {
            var treeOutlineContainerElement = this.treeOutline.element.parentNode;
            originalScrollTop = treeOutlineContainerElement.scrollTop;
            var selectedTreeElement = this.treeOutline.selectedTreeElement;
            if (selectedTreeElement && selectedTreeElement.hasAncestor(this))
                this.select();
            this.removeChildren();
        }

        var treeElement = this;
        var treeChildIndex = 0;
        var elementToSelect;

        function updateChildrenOfNode(node)
        {
            var treeOutline = treeElement.treeOutline;
            var child = node.firstChild;
            while (child) {
                var currentTreeElement = treeElement.children[treeChildIndex];
                if (!currentTreeElement || currentTreeElement.representedObject !== child) {
                    // Find any existing element that is later in the children list.
                    var existingTreeElement = null;
                    for (var i = (treeChildIndex + 1), size = treeElement.expandedChildCount; i < size; ++i) {
                        if (treeElement.children[i].representedObject === child) {
                            existingTreeElement = treeElement.children[i];
                            break;
                        }
                    }

                    if (existingTreeElement && existingTreeElement.parent === treeElement) {
                        // If an existing element was found and it has the same parent, just move it.
                        treeElement.moveChild(existingTreeElement, treeChildIndex);
                    } else {
                        // No existing element found, insert a new element.
                        if (treeChildIndex < treeElement.expandedChildrenLimit) {
                            var newElement = treeElement.insertChildElement(child, treeChildIndex);
                            if (child === focusedNode)
                                elementToSelect = newElement;
                            if (treeElement.expandedChildCount > treeElement.expandedChildrenLimit)
                                treeElement.expandedChildrenLimit++;
                        }
                    }
                }

                child = child.nextSibling;
                ++treeChildIndex;
            }
        }

        // Remove any tree elements that no longer have this node (or this node's contentDocument) as their parent.
        for (var i = (this.children.length - 1); i >= 0; --i) {
            var currentChild = this.children[i];
            var currentNode = currentChild.representedObject;
            var currentParentNode = currentNode.parentNode;

            if (currentParentNode === this.representedObject)
                continue;

            var selectedTreeElement = this.treeOutline.selectedTreeElement;
            if (selectedTreeElement && (selectedTreeElement === currentChild || selectedTreeElement.hasAncestor(currentChild)))
                this.select();

            this.removeChildAtIndex(i);
        }

        updateChildrenOfNode(this.representedObject);
        this.adjustCollapsedRange(false);

        var lastChild = this.children[this.children.length - 1];
        if (this.representedObject.nodeType == Node.ELEMENT_NODE && (!lastChild || !lastChild._elementCloseTag))
            this.insertChildElement(this.representedObject, this.children.length, true);

        // We want to restore the original selection and tree scroll position after a full refresh, if possible.
        if (fullRefresh && elementToSelect) {
            elementToSelect.select();
            if (treeOutlineContainerElement && originalScrollTop <= treeOutlineContainerElement.scrollHeight)
                treeOutlineContainerElement.scrollTop = originalScrollTop;
        }

        delete this._updateChildrenInProgress;
    },

    adjustCollapsedRange: function()
    {
        // Ensure precondition: only the tree elements for node children are found in the tree
        // (not the Expand All button or the closing tag).
        if (this.expandAllButtonElement && this.expandAllButtonElement.__treeElement.parent)
            this.removeChild(this.expandAllButtonElement.__treeElement);

        const node = this.representedObject;
        if (!node.children)
            return;
        const childNodeCount = node.children.length;

        // In case some nodes from the expanded range were removed, pull some nodes from the collapsed range into the expanded range at the bottom.
        for (var i = this.expandedChildCount, limit = Math.min(this.expandedChildrenLimit, childNodeCount); i < limit; ++i)
            this.insertChildElement(node.children[i], i);

        const expandedChildCount = this.expandedChildCount;
        if (childNodeCount > this.expandedChildCount) {
            var targetButtonIndex = expandedChildCount;
            if (!this.expandAllButtonElement) {
                var title = "<button class=\"show-all-nodes\" value=\"\" />";
                var item = new TreeElement(title, null, false);
                item.selectable = false;
                item.expandAllButton = true;
                this.insertChild(item, targetButtonIndex);
                this.expandAllButtonElement = item.listItemElement.firstChild;
                this.expandAllButtonElement.__treeElement = item;
                this.expandAllButtonElement.addEventListener("click", this.handleLoadAllChildren.bind(this), false);
            } else if (!this.expandAllButtonElement.__treeElement.parent)
                this.insertChild(this.expandAllButtonElement.__treeElement, targetButtonIndex);
            this.expandAllButtonElement.textContent = WebInspector.UIString("Show All Nodes (%d More)", childNodeCount - expandedChildCount);
        } else if (this.expandAllButtonElement)
            delete this.expandAllButtonElement;
    },

    handleLoadAllChildren: function()
    {
        this.expandedChildrenLimit = Math.max(this.representedObject._childNodeCount, this.expandedChildrenLimit + WebInspector.ElementsTreeElement.InitialChildrenLimit);
    },

    onexpand: function()
    {
        if (this._elementCloseTag)
            return;

        this.updateTitle();
        this.treeOutline.updateSelection();
    },

    oncollapse: function()
    {
        if (this._elementCloseTag)
            return;

        this.updateTitle();
        this.treeOutline.updateSelection();
    },

    onreveal: function()
    {
        if (this.listItemElement)
            this.listItemElement.scrollIntoViewIfNeeded(false);
    },

    onselect: function()
    {
        this.treeOutline.suppressRevealAndSelect = true;
        this.treeOutline.focusedDOMNode = this.representedObject;
        this.updateSelection();
        this.treeOutline.suppressRevealAndSelect = false;
    },

    selectOnMouseDown: function(event)
    {
        TreeElement.prototype.selectOnMouseDown.call(this, event);

        if (this._editing)
            return;

        if (this.treeOutline.showInElementsPanelEnabled) {
            WebInspector.showElementsPanel();
            WebInspector.panels.elements.focusedDOMNode = this.representedObject;
        }

        // Prevent selecting the nearest word on double click.
        if (event.detail >= 2)
            event.preventDefault();
    },

    ondblclick: function(event)
    {
        if (this._editing || this._elementCloseTag)
            return;

        if (this._startEditingTarget(event.target))
            return;

        if (this.hasChildren && !this.expanded)
            this.expand();
    },

    _insertInLastAttributePosition: function(tag, node)
    {
        if (tag.getElementsByClassName("webkit-html-attribute").length > 0)
            tag.insertBefore(node, tag.lastChild);
        else {
            var nodeName = tag.textContent.match(/^<(.*?)>$/)[1];
            tag.textContent = '';
            tag.appendChild(document.createTextNode('<'+nodeName));
            tag.appendChild(node);
            tag.appendChild(document.createTextNode('>'));
        }

        this.updateSelection();
    },

    _startEditingTarget: function(eventTarget)
    {
        if (this.treeOutline.focusedDOMNode != this.representedObject)
            return;

        if (this.representedObject.nodeType != Node.ELEMENT_NODE && this.representedObject.nodeType != Node.TEXT_NODE)
            return false;

        var textNode = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-text-node");
        if (textNode)
            return this._startEditingTextNode(textNode);

        var attribute = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-attribute");
        if (attribute)
            return this._startEditingAttribute(attribute, eventTarget);

        var tagName = eventTarget.enclosingNodeOrSelfWithClass("webkit-html-tag-name");
        if (tagName)
            return this._startEditingTagName(tagName);

        var newAttribute = eventTarget.enclosingNodeOrSelfWithClass("add-attribute");
        if (newAttribute)
            return this._addNewAttribute();

        return false;
    },

    _populateTagContextMenu: function(contextMenu, event)
    {
        var attribute = event.target.enclosingNodeOrSelfWithClass("webkit-html-attribute");
        var newAttribute = event.target.enclosingNodeOrSelfWithClass("add-attribute");

        // Add attribute-related actions.
        contextMenu.appendItem(WebInspector.UIString("Add Attribute"), this._addNewAttribute.bind(this));
        if (attribute && !newAttribute)
            contextMenu.appendItem(WebInspector.UIString("Edit Attribute"), this._startEditingAttribute.bind(this, attribute, event.target));
        contextMenu.appendSeparator();

        // Add free-form node-related actions.
        contextMenu.appendItem(WebInspector.UIString("Edit as HTML"), this._editAsHTML.bind(this));
        contextMenu.appendItem(WebInspector.UIString("Copy as HTML"), this._copyHTML.bind(this));
        contextMenu.appendItem(WebInspector.UIString("Delete Node"), this.remove.bind(this));
    },

    _populateTextContextMenu: function(contextMenu, textNode)
    {
        contextMenu.appendItem(WebInspector.UIString("Edit Text"), this._startEditingTextNode.bind(this, textNode));
    },

    _startEditing: function()
    {
        if (this.treeOutline.focusedDOMNode !== this.representedObject)
            return;

        var listItem = this._listItemNode;

        if (this._canAddAttributes) {
            var attribute = listItem.getElementsByClassName("webkit-html-attribute")[0];
            if (attribute)
                return this._startEditingAttribute(attribute, attribute.getElementsByClassName("webkit-html-attribute-value")[0]);

            return this._addNewAttribute();
        }

        if (this.representedObject.nodeType === Node.TEXT_NODE) {
            var textNode = listItem.getElementsByClassName("webkit-html-text-node")[0];
            if (textNode)
                return this._startEditingTextNode(textNode);
            return;
        }
    },

    _addNewAttribute: function()
    {
        // Cannot just convert the textual html into an element without
        // a parent node. Use a temporary span container for the HTML.
        var container = document.createElement("span");
        container.innerHTML = this._attributeHTML(" ", "");
        var attr = container.firstChild;
        attr.style.marginLeft = "2px"; // overrides the .editing margin rule
        attr.style.marginRight = "2px"; // overrides the .editing margin rule

        var tag = this.listItemElement.getElementsByClassName("webkit-html-tag")[0];
        this._insertInLastAttributePosition(tag, attr);
        return this._startEditingAttribute(attr, attr);
    },

    _triggerEditAttribute: function(attributeName)
    {
        var attributeElements = this.listItemElement.getElementsByClassName("webkit-html-attribute-name");
        for (var i = 0, len = attributeElements.length; i < len; ++i) {
            if (attributeElements[i].textContent === attributeName) {
                for (var elem = attributeElements[i].nextSibling; elem; elem = elem.nextSibling) {
                    if (elem.nodeType !== Node.ELEMENT_NODE)
                        continue;

                    if (elem.hasStyleClass("webkit-html-attribute-value"))
                        return this._startEditingAttribute(elem.parentNode, elem);
                }
            }
        }
    },

    _startEditingAttribute: function(attribute, elementForSelection)
    {
        if (WebInspector.isBeingEdited(attribute))
            return true;

        var attributeNameElement = attribute.getElementsByClassName("webkit-html-attribute-name")[0];
        if (!attributeNameElement)
            return false;

        var attributeName = attributeNameElement.innerText;

        function removeZeroWidthSpaceRecursive(node)
        {
            if (node.nodeType === Node.TEXT_NODE) {
                node.nodeValue = node.nodeValue.replace(/\u200B/g, "");
                return;
            }

            if (node.nodeType !== Node.ELEMENT_NODE)
                return;

            for (var child = node.firstChild; child; child = child.nextSibling)
                removeZeroWidthSpaceRecursive(child);
        }

        // Remove zero-width spaces that were added by nodeTitleInfo.
        removeZeroWidthSpaceRecursive(attribute);

        this._editing = WebInspector.startEditing(attribute, this._attributeEditingCommitted.bind(this), this._editingCancelled.bind(this), attributeName);
        window.getSelection().setBaseAndExtent(elementForSelection, 0, elementForSelection, 1);

        return true;
    },

    _startEditingTextNode: function(textNode)
    {
        if (WebInspector.isBeingEdited(textNode))
            return true;

        this._editing = WebInspector.startEditing(textNode, this._textNodeEditingCommitted.bind(this), this._editingCancelled.bind(this));
        window.getSelection().setBaseAndExtent(textNode, 0, textNode, 1);

        return true;
    },

    _startEditingTagName: function(tagNameElement)
    {
        if (!tagNameElement) {
            tagNameElement = this.listItemElement.getElementsByClassName("webkit-html-tag-name")[0];
            if (!tagNameElement)
                return false;
        }

        var tagName = tagNameElement.textContent;
        if (WebInspector.ElementsTreeElement.EditTagBlacklist[tagName.toLowerCase()])
            return false;

        if (WebInspector.isBeingEdited(tagNameElement))
            return true;

        var closingTagElement = this._distinctClosingTagElement();

        function keyupListener(event)
        {
            if (closingTagElement)
                closingTagElement.textContent = "</" + tagNameElement.textContent + ">";
        }

        function editingComitted(element, newTagName)
        {
            tagNameElement.removeEventListener('keyup', keyupListener, false);
            this._tagNameEditingCommitted.apply(this, arguments);
        }

        function editingCancelled()
        {
            tagNameElement.removeEventListener('keyup', keyupListener, false);
            this._editingCancelled.apply(this, arguments);
        }

        tagNameElement.addEventListener('keyup', keyupListener, false);

        this._editing = WebInspector.startEditing(tagNameElement, editingComitted.bind(this), editingCancelled.bind(this), tagName);
        window.getSelection().setBaseAndExtent(tagNameElement, 0, tagNameElement, 1);
        return true;
    },

    _startEditingAsHTML: function(commitCallback, initialValue)
    {
        if (this._htmlEditElement && WebInspector.isBeingEdited(this._htmlEditElement))
            return true;

        this._htmlEditElement = document.createElement("div");
        this._htmlEditElement.className = "source-code elements-tree-editor";
        this._htmlEditElement.textContent = initialValue;

        // Hide header items.
        var child = this.listItemElement.firstChild;
        while (child) {
            child.style.display = "none";
            child = child.nextSibling;
        }
        // Hide children item.
        if (this._childrenListNode)
            this._childrenListNode.style.display = "none";
        // Append editor.
        this.listItemElement.appendChild(this._htmlEditElement);

        this.updateSelection();

        function commit()
        {
            commitCallback(this._htmlEditElement.textContent);
            dispose.call(this);
        }

        function dispose()
        {
            delete this._editing;

            // Remove editor.
            this.listItemElement.removeChild(this._htmlEditElement);
            delete this._htmlEditElement;
            // Unhide children item.
            if (this._childrenListNode)
                this._childrenListNode.style.removeProperty("display");
            // Unhide header items.
            var child = this.listItemElement.firstChild;
            while (child) {
                child.style.removeProperty("display");
                child = child.nextSibling;
            }

            this.updateSelection();
        }

        this._editing = WebInspector.startEditing(this._htmlEditElement, commit.bind(this), dispose.bind(this), null, true);
    },

    _attributeEditingCommitted: function(element, newText, oldText, attributeName, moveDirection)
    {
        delete this._editing;

        // Before we do anything, determine where we should move
        // next based on the current element's settings
        var moveToAttribute, moveToTagName, moveToNewAttribute;
        if (moveDirection) {
            var found = false;

            // Search for the attribute's position, and then decide where to move to.
            var attributes = this.representedObject.attributes;
            for (var i = 0; i < attributes.length; ++i) {
                if (attributes[i].name === attributeName) {
                    found = true;
                    if (moveDirection === "backward") {
                        if (i === 0)
                            moveToTagName = true;
                        else
                            moveToAttribute = attributes[i - 1].name;
                    } else if (moveDirection === "forward") {
                        if (i === attributes.length - 1)
                            moveToNewAttribute = true;
                        else
                            moveToAttribute = attributes[i + 1].name;
                    }
                }
            }

            // Moving From the "New Attribute" position.
            if (!found) {
                if (moveDirection === "backward" && attributes.length > 0)
                    moveToAttribute = attributes[attributes.length - 1].name;
                else if (moveDirection === "forward" && !/^\s*$/.test(newText))
                    moveToNewAttribute = true;
            }
        }

        function moveToNextAttributeIfNeeded()
        {
            // Cleanup empty new attribute sections.
            if (element.textContent.trim().length === 0)
                element.parentNode.removeChild(element);

            // Make the move.
            if (moveToAttribute)
                this._triggerEditAttribute(moveToAttribute);
            else if (moveToNewAttribute)
                this._addNewAttribute();
            else if (moveToTagName)
                this._startEditingTagName();
        }

        function regenerateStyledAttribute(name, value)
        {
            var previous = element.previousSibling;
            if (!previous || previous.nodeType !== Node.TEXT_NODE)
                element.parentNode.insertBefore(document.createTextNode(" "), element);
            element.outerHTML = this._attributeHTML(name, value);
        }

        var parseContainerElement = document.createElement("span");
        parseContainerElement.innerHTML = "<span " + newText + "></span>";
        var parseElement = parseContainerElement.firstChild;

        if (!parseElement) {
            this._editingCancelled(element, attributeName);
            moveToNextAttributeIfNeeded.call(this);
            return;
        }

        if (!parseElement.hasAttributes()) {
            this.representedObject.removeAttribute(attributeName);
            moveToNextAttributeIfNeeded.call(this);
            return;
        }

        var foundOriginalAttribute = false;
        for (var i = 0; i < parseElement.attributes.length; ++i) {
            var attr = parseElement.attributes[i];
            foundOriginalAttribute = foundOriginalAttribute || attr.name === attributeName;
            try {
                this.representedObject.setAttribute(attr.name, attr.value);
                regenerateStyledAttribute.call(this, attr.name, attr.value);
            } catch(e) {} // ignore invalid attribute (innerHTML doesn't throw errors, but this can)
        }

        if (!foundOriginalAttribute)
            this.representedObject.removeAttribute(attributeName);

        this.treeOutline.focusedNodeChanged(true);

        moveToNextAttributeIfNeeded.call(this);
    },

    _tagNameEditingCommitted: function(element, newText, oldText, tagName, moveDirection)
    {
        delete this._editing;
        var self = this;

        function cancel()
        {
            var closingTagElement = self._distinctClosingTagElement();
            if (closingTagElement)
                closingTagElement.textContent = "</" + tagName + ">";

            self._editingCancelled(element, tagName);
            moveToNextAttributeIfNeeded.call(self);
        }

        function moveToNextAttributeIfNeeded()
        {
            if (moveDirection !== "forward")
                return;

            var attributes = this.representedObject.attributes;
            if (attributes.length > 0)
                this._triggerEditAttribute(attributes[0].name);
            else
                this._addNewAttribute();
        }

        newText = newText.trim();
        if (newText === oldText) {
            cancel();
            return;
        }

        var treeOutline = this.treeOutline;
        var wasExpanded = this.expanded;

        function changeTagNameCallback(nodeId)
        {
            if (nodeId === -1) {
                cancel();
                return;
            }

            // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date.
            WebInspector.panels.elements.updateModifiedNodes();

            WebInspector.updateFocusedNode(nodeId);
            var newTreeItem = treeOutline.findTreeElement(WebInspector.domAgent.nodeForId(nodeId));
            if (wasExpanded)
                newTreeItem.expand();

            moveToNextAttributeIfNeeded.call(newTreeItem);
        }

        var callId = WebInspector.Callback.wrap(changeTagNameCallback);
        InspectorBackend.changeTagName(callId, this.representedObject.id, newText, wasExpanded);
    },

    _textNodeEditingCommitted: function(element, newText)
    {
        delete this._editing;

        var textNode;
        if (this.representedObject.nodeType == Node.ELEMENT_NODE) {
            // We only show text nodes inline in elements if the element only
            // has a single child, and that child is a text node.
            textNode = this.representedObject.firstChild;
        } else if (this.representedObject.nodeType == Node.TEXT_NODE)
            textNode = this.representedObject;

        textNode.nodeValue = newText;

        // Need to restore attributes / node structure.
        this.updateTitle();
    },

    _editingCancelled: function(element, context)
    {
        delete this._editing;

        // Need to restore attributes structure.
        this.updateTitle();
    },

    _distinctClosingTagElement: function()
    {
        // FIXME: Improve the Tree Element / Outline Abstraction to prevent crawling the DOM

        // For an expanded element, it will be the last element with class "close"
        // in the child element list.
        if (this.expanded) {
            var closers = this._childrenListNode.querySelectorAll(".close");
            return closers[closers.length-1];
        }

        // Remaining cases are single line non-expanded elements with a closing
        // tag, or HTML elements without a closing tag (such as <br>). Return
        // null in the case where there isn't a closing tag.
        var tags = this.listItemElement.getElementsByClassName("webkit-html-tag");
        return (tags.length === 1 ? null : tags[tags.length-1]);
    },

    updateTitle: function()
    {
        // If we are editing, return early to prevent canceling the edit.
        // After editing is committed updateTitle will be called.
        if (this._editing)
            return;

        var self = this;
        function callback(tooltipText)
        {
            var title = self._nodeTitleInfo(WebInspector.linkifyURL, tooltipText).title;
            self.title = "<span class=\"highlight\">" + title + "</span>";
            delete self.selectionElement;
            self.updateSelection();
            self._preventFollowingLinksOnDoubleClick();
            self._highlightSearchResults();
        };

        // TODO: Replace with InjectedScriptAccess.getBasicProperties(obj, [names]).
        if (this.representedObject.nodeName.toLowerCase() !== "img")
            callback();
        else
            this.createTooltipForImageNode(this.representedObject, callback);
    },

    _rewriteAttrHref: function(node, hrefValue)
    {
        if (!hrefValue || hrefValue.indexOf("://") > 0)
            return hrefValue;

        for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
            if (frameOwnerCandidate.documentURL) {
                var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, hrefValue);
                if (result)
                    return result;
                break;
            }
        }

        // documentURL not found or has bad value
        for (var url in WebInspector.resourceURLMap) {
            var match = url.match(WebInspector.URLRegExp);
            if (match && match[4] === hrefValue)
                return url;
        }
        return hrefValue;
    },

    _attributeHTML: function(name, value, node, linkify, tooltipText)
    {
        var hasText = (value.length > 0);
        var html = "<span class=\"webkit-html-attribute\"><span class=\"webkit-html-attribute-name\">" + name.escapeHTML() + "</span>";

        if (hasText)
            html += "=\"";

        if (linkify && (name === "src" || name === "href")) {
            value = value.replace(/([\/;:\)\]\}])/g, "$1\u200B");
            html += linkify(this._rewriteAttrHref(node, value), value, "webkit-html-attribute-value", node.nodeName.toLowerCase() === "a", tooltipText);
        } else {
            value = value.escapeHTML().replace(/([\/;:\)\]\}])/g, "$1");
            html += "<span class=\"webkit-html-attribute-value\">" + value + "</span>";
        }

        if (hasText)
            html += "\"";

        html += "</span>";
        return html;
    },

    _tagHTML: function(tagName, isClosingTag, isDistinctTreeElement, linkify, tooltipText)
    {
        var node = this.representedObject;
        var result = "<span class=\"webkit-html-tag" + (isClosingTag && isDistinctTreeElement ? " close" : "")  + "\"><";
        result += "<span " + (isClosingTag ? "" : "class=\"webkit-html-tag-name\"") + ">" + (isClosingTag ? "/" : "") + tagName + "</span>";
        if (!isClosingTag && node.hasAttributes()) {
            for (var i = 0; i < node.attributes.length; ++i) {
                var attr = node.attributes[i];
                result += " " + this._attributeHTML(attr.name, attr.value, node, linkify, tooltipText);
            }
        }
        result += "></span>";

        return result;
    },

    _nodeTitleInfo: function(linkify, tooltipText)
    {
        var node = this.representedObject;
        var info = {title: "", hasChildren: this.hasChildren};

        switch (node.nodeType) {
            case Node.DOCUMENT_NODE:
                info.title = "Document";
                break;

            case Node.DOCUMENT_FRAGMENT_NODE:
                info.title = "Document Fragment";
                break;

            case Node.ELEMENT_NODE:
                var tagName = this.treeOutline.nodeNameToCorrectCase(node.nodeName).escapeHTML();
                if (this._elementCloseTag) {
                    info.title = this._tagHTML(tagName, true, true);
                    info.hasChildren = false;
                    break;
                }

                info.title = this._tagHTML(tagName, false, false, linkify, tooltipText);

                var textChild = onlyTextChild.call(node);
                var showInlineText = textChild && textChild.textContent.length < Preferences.maxInlineTextChildLength;

                if (!this.expanded && (!showInlineText && (this.treeOutline.isXMLMimeType || !WebInspector.ElementsTreeElement.ForbiddenClosingTagElements[tagName]))) {
                    if (this.hasChildren)
                        info.title += "<span class=\"webkit-html-text-node\">…</span>";
                    info.title += this._tagHTML(tagName, true, false);
                }

                // If this element only has a single child that is a text node,
                // just show that text and the closing tag inline rather than
                // create a subtree for them
                if (showInlineText) {
                    info.title += "<span class=\"webkit-html-text-node\">" + textChild.nodeValue.escapeHTML() + "</span>" + this._tagHTML(tagName, true, false);
                    info.hasChildren = false;
                }
                break;

            case Node.TEXT_NODE:
                if (isNodeWhitespace.call(node))
                    info.title = "(whitespace)";
                else {
                    if (node.parentNode && node.parentNode.nodeName.toLowerCase() === "script") {
                        var newNode = document.createElement("span");
                        newNode.textContent = node.textContent;

                        var javascriptSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/javascript");
                        javascriptSyntaxHighlighter.syntaxHighlightNode(newNode);

                        info.title = "<span class=\"webkit-html-text-node webkit-html-js-node\">" + newNode.innerHTML.replace(/^[\n\r]*/, "").replace(/\s*$/, "") + "</span>";
                    } else if (node.parentNode && node.parentNode.nodeName.toLowerCase() === "style") {
                        var newNode = document.createElement("span");
                        newNode.textContent = node.textContent;

                        var cssSyntaxHighlighter = new WebInspector.DOMSyntaxHighlighter("text/css");
                        cssSyntaxHighlighter.syntaxHighlightNode(newNode);

                        info.title = "<span class=\"webkit-html-text-node webkit-html-css-node\">" + newNode.innerHTML.replace(/^[\n\r]*/, "").replace(/\s*$/, "") + "</span>";
                    } else {
                        info.title = "\"<span class=\"webkit-html-text-node\">" + node.nodeValue.escapeHTML() + "</span>\"";
                    }
                }
                break;

            case Node.COMMENT_NODE:
                info.title = "<span class=\"webkit-html-comment\"><!--" + node.nodeValue.escapeHTML() + "--></span>";
                break;

            case Node.DOCUMENT_TYPE_NODE:
                info.title = "<span class=\"webkit-html-doctype\"><!DOCTYPE " + node.nodeName;
                if (node.publicId) {
                    info.title += " PUBLIC \"" + node.publicId + "\"";
                    if (node.systemId)
                        info.title += " \"" + node.systemId + "\"";
                } else if (node.systemId)
                    info.title += " SYSTEM \"" + node.systemId + "\"";
                if (node.internalSubset)
                    info.title += " [" + node.internalSubset + "]";
                info.title += "></span>";
                break;
            default:
                info.title = this.treeOutline.nodeNameToCorrectCase(node.nodeName).collapseWhitespace().escapeHTML();
        }

        return info;
    },

    _showInlineText: function(node)
    {
        if (node.nodeType === Node.ELEMENT_NODE) {
            var textChild = onlyTextChild.call(node);
            if (textChild && textChild.textContent.length < Preferences.maxInlineTextChildLength)
                return true;
        }
        return false;
    },

    remove: function()
    {
        var parentElement = this.parent;
        if (!parentElement)
            return;

        var self = this;
        function removeNodeCallback(removedNodeId)
        {
            // -1 is an error code, which means removing the node from the DOM failed,
            // so we shouldn't remove it from the tree.
            if (removedNodeId === -1)
                return;

            parentElement.removeChild(self);
            parentElement.adjustCollapsedRange(true);
        }

        var callId = WebInspector.Callback.wrap(removeNodeCallback);
        InspectorBackend.removeNode(callId, this.representedObject.id);
    },

    _editAsHTML: function()
    {
        var treeOutline = this.treeOutline;
        var node = this.representedObject;
        var wasExpanded = this.expanded;

        function selectNode(nodeId)
        {
            if (!nodeId)
                return;

            // Select it and expand if necessary. We force tree update so that it processes dom events and is up to date.
            WebInspector.panels.elements.updateModifiedNodes();

            WebInspector.updateFocusedNode(nodeId);
            if (wasExpanded) {
                var newTreeItem = treeOutline.findTreeElement(WebInspector.domAgent.nodeForId(nodeId));
                if (newTreeItem)
                    newTreeItem.expand();
            }
        }

        function commitChange(value)
        {
            InjectedScriptAccess.get(node.injectedScriptId).setOuterHTML(node.id, value, wasExpanded, selectNode.bind(this));
        }

        InjectedScriptAccess.get(node.injectedScriptId).getNodePropertyValue(node.id, "outerHTML", this._startEditingAsHTML.bind(this, commitChange));
    },

    _copyHTML: function()
    {
        InspectorBackend.copyNode(this.representedObject.id);
    },

    _highlightSearchResults: function()
    {
        if (!this._searchQuery)
            return;
        var text = this.listItemElement.textContent;
        var regexObject = createSearchRegex(this._searchQuery);

        var offset = 0;
        var match = regexObject.exec(text);
        while (match) {
            highlightSearchResult(this.listItemElement, offset + match.index, match[0].length);
            offset += match.index + 1;
            text = text.substring(match.index + 1);
            match = regexObject.exec(text);
        }
    }
}

WebInspector.ElementsTreeElement.prototype.__proto__ = TreeElement.prototype;


text:
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

package org.cef.browser;

import org.cef.callback.CefDragData;
import org.cef.callback.CefNativeAdapter;
import org.cef.callback.CefRunFileDialogCallback;
import org.cef.callback.CefStringVisitor;
import org.cef.handler.CefClientHandler;
import org.cef.handler.CefDialogHandler.FileDialogMode;
import org.cef.handler.CefRenderHandler;
import org.cef.handler.CefWindowHandler;
import org.cef.network.CefRequest;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.Vector;

/**
 * This class represents all methods which are connected to the
 * native counterpart CEF.
 * The visibility of this class is "package". To create a new
 * CefBrowser instance, please use CefBrowserFactory.
 */
abstract class CefBrowser_N extends CefNativeAdapter implements CefBrowser {
    private boolean isPending_ = false;

    @Override
    public CefRenderHandler getRenderHandler() {
        return null;
    }

    @Override
    public CefWindowHandler getWindowHandler() {
        return null;
    }

    /**
     * Create a new browser.
     */
    protected void createBrowser(CefClientHandler clientHandler, long windowHandle, String url, boolean transparent, Component canvas, CefRequestContext context) {
        if (getNativeRef("CefBrowser") == 0 && !isPending_) {
            try {
                isPending_ = N_CreateBrowser(clientHandler, windowHandle, url, transparent, canvas, context);
            } catch (UnsatisfiedLinkError err) {
                err.printStackTrace();
            }
        }
    }

    /**
     * Create a new browser as dev tools
     */
    protected final void createDevTools(CefBrowser parent, CefClientHandler clientHandler, long windowHandle, boolean transparent, Component canvas, Point inspectAt) {
        if (getNativeRef("CefBrowser") == 0 && !isPending_) {
            try {
                isPending_ = N_CreateDevTools(parent, clientHandler, windowHandle, transparent, canvas, inspectAt);
            } catch (UnsatisfiedLinkError err) {
                err.printStackTrace();
            }
        }
    }

    /**
     * Returns the native window handle for the specified native surface handle.
     */
    protected final long getWindowHandle(long surfaceHandle) {
        try {
            return N_GetWindowHandle(surfaceHandle);
        } catch (UnsatisfiedLinkError err) {
            err.printStackTrace();
        }
        return 0;
    }

    @Override
    protected void finalize() throws Throwable {
        close();
        super.finalize();
    }

    @Override
    public boolean canGoBack() {
        try {
            return N_CanGoBack();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return false;
    }

    @Override
    public void goBack() {
        try {
            N_GoBack();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public boolean canGoForward() {
        try {
            return N_CanGoForward();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return false;
    }

    @Override
    public void goForward() {
        try {
            N_GoForward();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public boolean isLoading() {
        try {
            return N_IsLoading();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return false;
    }

    @Override
    public void reload() {
        try {
            N_Reload();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void reloadIgnoreCache() {
        try {
            N_ReloadIgnoreCache();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void stopLoad() {
        try {
            N_StopLoad();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public int getIdentifier() {
        try {
            return N_GetIdentifier();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
            return -1;
        }
    }

    @Override
    public boolean isPopup() {
        try {
            return N_IsPopup();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean hasDocument() {
        try {
            return N_HasDocument();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return false;
    }

    public void viewSource() {
        try {
            N_ViewSource();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    public void getSource(CefStringVisitor visitor) {
        try {
            N_GetSource(visitor);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    public void getText(CefStringVisitor visitor) {
        try {
            N_GetText(visitor);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void loadRequest(CefRequest request) {
        try {
            N_LoadRequest(request);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void loadURL(String url) {
        try {
            N_LoadURL(url);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void loadString(String val, String url) {
        try {
            N_LoadString(val, url);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void executeJavaScript(String code, String url, int line) {
        try {
            N_ExecuteJavaScript(code, url, line);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public String getURL() {
        try {
            return N_GetURL();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return "";
    }

    @Override
    public void close() {
        try {
            N_Close();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void setFocus(boolean enable) {
        try {
            N_SetFocus(enable);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void setWindowVisibility(boolean visible) {
        try {
            N_SetWindowVisibility(visible);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public double getZoomLevel() {
        try {
            return N_GetZoomLevel();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
        return 0.0;
    }

    @Override
    public void setZoomLevel(double zoomLevel) {
        try {
            N_SetZoomLevel(zoomLevel);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void runFileDialog(FileDialogMode mode, String title, String defaultFilePath, Vector<String> acceptFilters, int selectedAcceptFilter, CefRunFileDialogCallback callback) {
        try {
            N_RunFileDialog(mode, title, defaultFilePath, acceptFilters, selectedAcceptFilter, callback);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void startDownload(String url) {
        try {
            N_StartDownload(url);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void print() {
        try {
            N_Print();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void find(int identifier, String searchText, boolean forward, boolean matchCase, boolean findNext) {
        try {
            N_Find(identifier, searchText, forward, matchCase, findNext);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void stopFinding(boolean clearSelection) {
        try {
            N_StopFinding(clearSelection);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    protected final void closeDevTools() {
        try {
            N_CloseDevTools();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    @Override
    public void replaceMisspelling(String word) {
        try {
            N_ReplaceMisspelling(word);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Notify that the browser was resized.
     *
     * @param width  The new width of the browser
     * @param height The new height of the browser
     */
    protected final void wasResized(int width, int height) {
        try {
            N_WasResized(width, height);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Invalidate the UI.
     */
    protected final void invalidate() {
        try {
            N_Invalidate();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Send a key event.
     *
     * @param e The event to send.
     */
    protected final void sendKeyEvent(KeyEvent e) {
        try {
            N_SendKeyEvent(e);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Send a mouse event.
     *
     * @param e The event to send.
     */
    protected final void sendMouseEvent(MouseEvent e) {
        try {
            N_SendMouseEvent(e);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Send a mouse wheel event.
     *
     * @param e The event to send.
     */
    protected final void sendMouseWheelEvent(MouseWheelEvent e) {
        try {
            N_SendMouseWheelEvent(e);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Call this method when the user drags the mouse into the web view (before
     * calling DragTargetDragOver/DragTargetLeave/DragTargetDrop).
     * |drag_data| should not contain file contents as this type of data is not
     * allowed to be dragged into the web view. File contents can be removed using
     * CefDragData::ResetFileContents (for example, if |drag_data| comes from
     * CefRenderHandler::StartDragging).
     * This method is only used when window rendering is disabled.
     */
    protected final void dragTargetDragEnter(CefDragData dragData, Point pos, int modifiers, int allowedOps) {
        try {
            N_DragTargetDragEnter(dragData, pos, modifiers, allowedOps);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Call this method each time the mouse is moved across the web view during
     * a drag operation (after calling DragTargetDragEnter and before calling
     * DragTargetDragLeave/DragTargetDrop).
     * This method is only used when window rendering is disabled.
     */
    protected final void dragTargetDragOver(Point pos, int modifiers, int allowedOps) {
        try {
            N_DragTargetDragOver(pos, modifiers, allowedOps);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Call this method when the user drags the mouse out of the web view (after
     * calling DragTargetDragEnter).
     * This method is only used when window rendering is disabled.
     */
    protected final void dragTargetDragLeave() {
        try {
            N_DragTargetDragLeave();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Call this method when the user completes the drag operation by dropping
     * the object onto the web view (after calling DragTargetDragEnter).
     * The object being dropped is |drag_data|, given as an argument to
     * the previous DragTargetDragEnter call.
     * This method is only used when window rendering is disabled.
     */
    protected final void dragTargetDrop(Point pos, int modifiers) {
        try {
            N_DragTargetDrop(pos, modifiers);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Call this method when the drag operation started by a
     * CefRenderHandler.startDragging call has ended either in a drop or
     * by being cancelled. |x| and |y| are mouse coordinates relative to the
     * upper-left corner of the view. If the web view is both the drag source
     * and the drag target then all DragTarget* methods should be called before
     * DragSource* methods.
     * This method is only used when window rendering is disabled.
     */
    protected final void dragSourceEndedAt(Point pos, int operation) {
        try {
            N_DragSourceEndedAt(pos, operation);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    /**
     * Call this method when the drag operation started by a
     * CefRenderHandler.startDragging call has completed. This method may be
     * called immediately without first calling DragSourceEndedAt to cancel a
     * drag operation. If the web view is both the drag source and the drag
     * target then all DragTarget* methods should be called before DragSource*
     * methods.
     * This method is only used when window rendering is disabled.
     */
    protected final void dragSourceSystemDragEnded() {
        try {
            N_DragSourceSystemDragEnded();
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    protected final void updateUI(Rectangle contentRect, Rectangle browserRect) {
        try {
            N_UpdateUI(contentRect, browserRect);
        } catch (UnsatisfiedLinkError ule) {
            ule.printStackTrace();
        }
    }

    private final native boolean N_CreateBrowser(CefClientHandler clientHandler, long windowHandle, String url, boolean transparent, Component canvas, CefRequestContext context);

    private final native boolean N_CreateDevTools(CefBrowser parent, CefClientHandler clientHandler, long windowHandle, boolean transparent, Component canvas, Point inspectAt);

    private final native long N_GetWindowHandle(long surfaceHandle);

    private final native boolean N_CanGoBack();

    private final native void N_GoBack();

    private final native boolean N_CanGoForward();

    private final native void N_GoForward();

    private final native boolean N_IsLoading();

    private final native void N_Reload();

    private final native void N_ReloadIgnoreCache();

    private final native void N_StopLoad();

    private final native int N_GetIdentifier();

    private final native boolean N_IsPopup();

    private final native boolean N_HasDocument();

    private final native void N_ViewSource();

    private final native void N_GetSource(CefStringVisitor visitor);

    private final native void N_GetText(CefStringVisitor visitor);

    private final native void N_LoadRequest(CefRequest request);

    private final native void N_LoadURL(String url);

    private final native void N_LoadString(String val, String url);

    private final native void N_ExecuteJavaScript(String code, String url, int line);

    private final native String N_GetURL();

    private final native void N_Close();

    private final native void N_SetFocus(boolean enable);

    private final native void N_SetWindowVisibility(boolean visible);

    private final native double N_GetZoomLevel();

    private final native void N_SetZoomLevel(double zoomLevel);

    private final native void N_RunFileDialog(FileDialogMode mode, String title, String defaultFilePath, Vector<String> acceptFilters, int selectedAcceptFilter, CefRunFileDialogCallback callback);

    private final native void N_StartDownload(String url);

    private final native void N_Print();

    private final native void N_Find(int identifier, String searchText, boolean forward, boolean matchCase, boolean findNext);

    private final native void N_StopFinding(boolean clearSelection);

    private final native void N_CloseDevTools();

    private final native void N_ReplaceMisspelling(String word);

    private final native void N_WasResized(int width, int height);

    private final native void N_Invalidate();

    private final native void N_SendKeyEvent(KeyEvent e);

    private final native void N_SendMouseEvent(MouseEvent e);

    private final native void N_SendMouseWheelEvent(MouseWheelEvent e);

    private final native void N_DragTargetDragEnter(CefDragData dragData, Point pos, int modifiers, int allowed_ops);

    private final native void N_DragTargetDragOver(Point pos, int modifiers, int allowed_ops);

    private final native void N_DragTargetDragLeave();

    private final native void N_DragTargetDrop(Point pos, int modifiers);

    private final native void N_DragSourceEndedAt(Point pos, int operation);

    private final native void N_DragSourceSystemDragEnded();

    private final native void N_UpdateUI(Rectangle contentRect, Rectangle browserRect);
}

redpajama_set_name: RedPajamaGithub


text:
This field can be used to pass additional arguments to clang scan-build.  The arguments will appear before the xcodebuild sub command.
You can view the assembled command by viewing the job's build console.

scan-build uses the 'clang' executable relative to itself for static analysis by default.

--use-analyzer Xcode using the 'clang' packaged with Xcode (on OS X)

--use-analyzer [path to clang] to use the 'clang' from 'path to clang' or $PATH if no path specified.


text:
#import "Controller.h"
#import "SCEvents.h"
#import "SCEvent.h"

static NSString *SCEventsDownloadsDirectory = @"Downloads";

@implementation Controller

/**
 * Sets up the event listener using SCEvents and sets its delegate to this controller.
 * The event stream is started by calling startWatchingPaths: while passing the paths
 * to be watched.
 */
- (void)setupEventListener
{
	if (_events) return;

	_events = [[SCEvents alloc] init];

	[_events setDelegate:self];

	NSMutableArray *paths = [NSMutableArray arrayWithObject:NSHomeDirectory()];
	NSMutableArray *excludePaths = [NSMutableArray arrayWithObject:[NSHomeDirectory() stringByAppendingPathComponent:SCEventsDownloadsDirectory]];

	// Set the paths to be excluded
	[_events setExcludedPaths:excludePaths];

	// Start receiving events
	[_events startWatchingPaths:paths];

	// Display a description of the stream
	NSLog(@"%@", [_events streamDescription]);
}

/**
 * This is the only method to be implemented to conform to the SCEventListenerProtocol.
 * As this is only an example the event received is simply printed to the console.
 *
 * @param pathwatcher The SCEvents instance that received the event
 * @param event       The actual event
 */
- (void)pathWatcher:(SCEvents *)pathWatcher eventOccurred:(SCEvent *)event
{
	NSLog(@"%@", event);
}

#pragma mark -

- (void)dealloc
{
	[_events release], _events = nil;

	[super dealloc];
}

@end


text:
I know, I know...another trigger framework. Bear with me. ;)

## Overview

Triggers should (IMO) be logicless. Putting logic into your triggers creates un-testable, difficult-to-maintain code. It's widely accepted that a best-practice is to move trigger logic into a handler class.

This trigger framework bundles a single **TriggerHandler** base class that you can inherit from in all of your trigger handlers. The base class includes context-specific methods that are automatically called when a trigger is executed.

The base class also provides a secondary role as a supervisor for Trigger execution. It acts like a watchdog, monitoring trigger activity and providing an api for controlling certain aspects of execution and control flow.

But the most important part of this framework is that it's minimal and simple to use.

## Usage

To create a trigger handler, you simply need to create a class that inherits from **TriggerHandler.cls**. Here is an example for creating an Opportunity trigger handler.

```java
public class OpportunityTriggerHandler extends TriggerHandler {
```

In your trigger handler, to add logic to any of the trigger contexts, you only need to override them in your trigger handler. Here is how we would add logic to a `beforeUpdate` trigger.

```java
public class OpportunityTriggerHandler extends TriggerHandler {

  public override void beforeUpdate() {
    for(Opportunity o : (List<Opportunity>) Trigger.new) {
      // do something
    }
  }

  // add overrides for other contexts

}
```

**Note:** When referencing the Trigger statics within a class, SObjects are returned versus SObject subclasses like Opportunity, Account, etc. This means that you must cast when you reference them in your trigger handler. You could do this in your constructor if you wanted.

```java
public class OpportunityTriggerHandler extends TriggerHandler {

  private Map<Id, Opportunity> newOppMap;

  public OpportunityTriggerHandler() {
    this.newOppMap = (Map<Id, Opportunity>) Trigger.newMap;
  }

  public override void afterUpdate() {
    //
  }

}
```

To use the trigger handler, you only need to construct an instance of your trigger handler within the trigger handler itself and call the `run()` method. Here is an example of the Opportunity trigger.

```java
trigger OpportunityTrigger on Opportunity (before insert, before update) {
  new OpportunityTriggerHandler().run();
}
```

## Cool Stuff

### Max Loop Count

To prevent recursion, you can set a max loop count for Trigger Handler. If this max is exceeded, and exception will be thrown. A great use case is when you want to ensure that your trigger runs once and only once within a single execution. Example:

```java
public class OpportunityTriggerHandler extends TriggerHandler {

  public OpportunityTriggerHandler() {
    this.setMaxLoopCount(1);
  }

  public override void afterUpdate() {
    List<Opportunity> opps = [SELECT Id FROM Opportunity WHERE Id IN :Trigger.newMap.keySet()];
    update opps; // this will throw after this update
  }

}
```

### Bypass API

What if you want to tell other trigger handlers to halt execution? That's easy with the bypass api. Example.

```java
public class OpportunityTriggerHandler extends TriggerHandler {

  public override void afterUpdate() {
    List<Opportunity> opps = [SELECT Id, AccountId FROM Opportunity WHERE Id IN :Trigger.newMap.keySet()];

    Account acc = [SELECT Id, Name FROM Account WHERE Id = :opps.get(0).AccountId];

    TriggerHandler.bypass('AccountTriggerHandler');

    acc.Name = 'No Trigger';
    update acc; // won't invoke the AccountTriggerHandler

    TriggerHandler.clearBypass('AccountTriggerHandler');

    acc.Name = 'With Trigger';
    update acc; // will invoke the AccountTriggerHandler

  }

}
```

## Overridable Methods

Here are all of the methods that you can override. All of the context possibilities are supported.

* `beforeInsert()`
* `beforeUpdate()`
* `beforeDelete()`
* `afterInsert()`
* `afterUpdate()`
* `afterDelete()`
* `afterUndelete()`


text:
package org.jhaws.common.web.wicket.renderer;

import org.apache.wicket.extensions.markup.html.form.select.IOptionRenderer;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

public class EnumOptionRenderer<T extends Enum<? super T>> implements IOptionRenderer<T> {
    private static final long serialVersionUID = 3093280303783185203L;

    public EnumOptionRenderer() {
        super();
    }

    @Override
    public String getDisplayValue(T object) {
        return object == null ? null : object.name();
    }

    @Override
    public IModel<T> getModel(T value) {
        return Model.of(value);
    }
}


text:
namespace liquidpp
{

template<int Step, int Initial>
struct IncrementBase : public Tag
{
   std::string keyName;

   static std::string generateKeyName(string_view variableName)
   {
      std::string var;
      var.reserve(variableName.size());
      var += '\0';
      var += static_cast<char>(Step);
      var += static_cast<char>(Initial);
      var.append(variableName.data(), variableName.size());
      return var;
   }

   IncrementBase(Tag&& tag)
     : Tag(std::move(tag))
   {
      auto tokens = Expression::splitTokens(value);
      if (tokens.size() != 1)
         throw Exception("Invalid parameter count!", value);

      keyName = generateKeyName(tokens[0]);
   }

   void render(Context& context, std::string& res) const override final
   {
      auto& dsc = context.documentScopeContext();

      std::intmax_t numVal = Initial;
      auto val = dsc.get(keyName);
      if (val.isIntegral())
         numVal = val.integralValue();

      res += boost::lexical_cast<std::string>(numVal);
      numVal += Step;
      dsc.set(keyName, numVal);
   }
};

using Increment = IncrementBase<1, 0>;
using Decrement = IncrementBase<-1, -1>;

}


text:
window.google = window.google || {};
google.maps = google.maps || {};

// Assumes that GEE_BASE_URL has been defined.
(function() {
  function getScript(src) {
    document.write('<script src="' + src +
                   '" type="text/javascript"></script>');
  }

  google.maps.Load = function(apiLoad) {
    /* http://mt0.google.com/vt */    apiLoad([,[,,,],['en-US',,,,,,GEE_BASE_URL+'/maps/api/icons/',],[GEE_BASE_URL+'/maps/mapfiles/390/v3','internal'],[0],0.0,,,,,], loadScriptTime);
  };
  var loadScriptTime = (new Date).getTime();
  getScript(GEE_BASE_URL+'/maps/mapfiles/390/v3/main.js');
})();


text:
package com.arm.wlauto.uiauto.facebook;

import android.app.Activity;
import android.os.Bundle;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;

import com.arm.wlauto.uiauto.BaseUiAutomation;

public class UiAutomation extends BaseUiAutomation {

    public static String TAG = "facebook";

    /*
     * The 'runUiAutomation' method implements the following activities
     * Login to facebook account.
     * Send a message.
     * Check latest notification.
     * Search particular user account and visit his/her facebook account.
     * Go to find friends.
     * Update the facebook status
     */
    public void runUiAutomation() throws Exception {
        final int timeout = 5;
        UiSelector selector = new UiSelector();

        UiObject logInButton = new UiObject(selector
             .className("android.widget.Button").index(3).text("Log In"));

        UiObject emailField = new UiObject(selector
        .className("android.widget.EditText").index(1));
        emailField.clearTextField();
        emailField.setText("abkksathe@gmail.com");

        UiObject passwordField = new UiObject(selector
             .className("android.widget.EditText").index(2));
        passwordField.clearTextField();
        passwordField.setText("highelymotivated");

        logInButton.clickAndWaitForNewWindow(timeout);

        sleep(timeout);

        //Click on message logo
        UiObject messageLogo = new UiObject(new UiSelector()
             .className("android.widget.RelativeLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(3)
             .childSelector(new UiSelector()
             .className("android.widget.RelativeLayout").index(1)
             .childSelector(new UiSelector()
             .className("android.widget.ImageButton").index(0)))));
        messageLogo.clickAndWaitForNewWindow(timeout);

        //send message
        UiObject clickMessage = new UiObject(new UiSelector()
            .className("android.support.v4.view.ViewPager").index(0)
            .childSelector(new UiSelector()
            .className("android.widget.RelativeLayout").index(1)));
        clickMessage.clickAndWaitForNewWindow(timeout);

        sleep(timeout);

        UiObject sendMessage = new UiObject(new UiSelector()
            .className("android.widget.FrameLayout").index(4)
            .childSelector(new UiSelector()
            .className("android.widget.LinearLayout").index(2))
            .childSelector(new UiSelector()
            .className("android.widget.EditText").index(0)
            .text("Write a message")));
        sendMessage.click();

        sleep(timeout);

        UiObject editMessage = new UiObject(new UiSelector()
            .className("android.widget.EditText").text("Write a message"));

        editMessage.setText("Hi how are you?????");

        UiObject sendButton = new UiObject(new UiSelector()
             .className("android.widget.TextView").text("Send"));
        sendButton.click();

        getUiDevice().pressDPadDown();
        sleep(timeout);
        getUiDevice().pressBack();
        sleep(timeout);
        getUiDevice().pressBack();

        //Check for notifications
        UiObject clickNotificationsLogo = new UiObject(new UiSelector()
             .className("android.widget.RelativeLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(3)
             .childSelector(new UiSelector()
             .className("android.widget.RelativeLayout").index(2)
             .childSelector(new UiSelector()
             .className("android.widget.ImageButton").index(0)))));
        clickNotificationsLogo.clickAndWaitForNewWindow(timeout);

        //Click on latest notification
        UiObject clickNotify = new UiObject(new UiSelector()
             .className("android.support.v4.view.ViewPager").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(1)));
        clickNotify.clickAndWaitForNewWindow(timeout);

        sleep(timeout);
        getUiDevice().pressBack();
        sleep(timeout);
        getUiDevice().pressBack();

        //Search for the facebook account
        UiObject clickBar = new UiObject(new UiSelector()
             .className("android.widget.ImageButton").index(0)
             .description("Main navigation menu"));
        clickBar.clickAndWaitForNewWindow(timeout);

        UiObject clickSearch = new UiObject(new UiSelector()
             .className("android.widget.FrameLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.FrameLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.FrameLayout").index(1)
             .childSelector(new UiSelector()
             .className("android.widget.EditText").index(1)
             .text("Search"))))));
        clickSearch.clickAndWaitForNewWindow(timeout);

        UiObject editSearch = new UiObject(new UiSelector()
             .className("android.widget.EditText").index(0).text("Search"));

        editSearch.clearTextField();
        editSearch.setText("amol kamble");
        sleep(timeout);

        UiObject clickOnSearchResult = new UiObject(new UiSelector()
             .className("android.webkit.WebView").index(0));
        clickOnSearchResult.clickTopLeft();

        sleep(2 * timeout);

        getUiDevice().pressBack();
        sleep(timeout);
        getUiDevice().pressBack();

        clickBar.click();

        sleep(timeout);

        //Click on find friends
        UiObject clickFriends = new UiObject(new UiSelector()
             .className("android.widget.FrameLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.FrameLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.FrameLayout").index(1)
             .childSelector(new UiSelector()
             .className("android.widget.RelativeLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.ListView").index(2)))))));

        UiObject friends = clickFriends.getChild(new UiSelector()
             .className("android.widget.RelativeLayout").index(3));
        friends.click();
        sleep(timeout);

        //Update the status
        UiObject updateStatus = new UiObject(new UiSelector()
             .className("android.widget.FrameLayout").index(1)
             .childSelector(new UiSelector()
             .className("android.widget.FrameLayout").index(1)
             .childSelector(new UiSelector()
             .className("android.widget.RelativeLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(0)))))));

        updateStatus.clickAndWaitForNewWindow(timeout);

        UiObject editUpdateStatus = new UiObject(new UiSelector()
             .className("android.widget.EditText")
             .text("What's on your mind?"));
        editUpdateStatus.clearTextField();
        editUpdateStatus.setText("hellllooooooo its done!!");

        UiObject clickPost = new UiObject(new UiSelector()
             .className("android.widget.RelativeLayout").index(0)
             .childSelector(new UiSelector()
             .className("android.widget.LinearLayout").index(3)));
        clickPost.clickAndWaitForNewWindow(timeout);
        getUiDevice().pressHome();
    }

    //disable update using playstore
    public void disableUpdate() throws UiObjectNotFoundException {

        UiObject accountSelect = new UiObject(new UiSelector()
                 .className("android.widget.Button").text("Accept"));

        if (accountSelect.exists())
             accountSelect.click();

        UiObject moreOptions = new UiObject(new UiSelector()
                 .className("android.widget.ImageButton")
                 .description("More options"));
        moreOptions.click();

        UiObject settings = new UiObject(new UiSelector()
                 .className("android.widget.TextView").text("Settings"));
        settings.clickAndWaitForNewWindow();

        UiObject autoUpdate = new UiObject(new UiSelector()
                 .className("android.widget.TextView")
                 .text("Auto-update apps"));

        autoUpdate.clickAndWaitForNewWindow();

        UiObject clickAutoUpdate = new UiObject(new UiSelector()
                  .className("android.widget.CheckedTextView")
                  .text("Do not auto-update apps"));

        clickAutoUpdate.clickAndWaitForNewWindow();

        getUiDevice().pressBack();
        getUiDevice().pressHome();
    }
}


text:
--------------------------------
-- @function [parent=#CheckBox] loadTextureBackGroundSelected
-- @param self
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype

--------------------------------
-- @function [parent=#CheckBox] loadTextureBackGroundDisabled
-- @param self
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype

--------------------------------
-- @function [parent=#CheckBox] addEventListener
-- @param self
-- @param #function func

--------------------------------
-- @function [parent=#CheckBox] loadTextureFrontCross
-- @param self
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype

--------------------------------
-- @function [parent=#CheckBox] loadTextures
-- @param self
-- @param #string str
-- @param #string str
-- @param #string str
-- @param #string str
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype

--------------------------------
-- @function [parent=#CheckBox] loadTextureBackGround
-- @param self
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype

--------------------------------
-- @function [parent=#CheckBox] setSelectedState
-- @param self
-- @param #bool bool

--------------------------------
-- @function [parent=#CheckBox] loadTextureFrontCrossDisabled
-- @param self
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype

--------------------------------
-- overload function: create(string, string, string, string, string, ccui.Widget::TextureResType)
--
-- overload function: create()
--
-- @function [parent=#CheckBox] create
-- @param self
-- @param #string str
-- @param #string str
-- @param #string str
-- @param #string str
-- @param #string str
-- @param #ccui.Widget::TextureResType texturerestype
-- @return CheckBox#CheckBox ret (retunr value: ccui.CheckBox)

--------------------------------
-- @function [parent=#CheckBox] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)

--------------------------------
-- @function [parent=#CheckBox] getVirtualRenderer
-- @param self
-- @return Node#Node ret (return value: cc.Node)

--------------------------------
-- @function [parent=#CheckBox] getDescription
-- @param self
-- @return string#string ret (return value: string)

--------------------------------
-- @function [parent=#CheckBox] getVirtualRendererSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- @function [parent=#CheckBox] CheckBox
-- @param self

return nil


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Class ProductController | Demo Json Service</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Packages

RestApi

Objects

Services

Classes

ProductController

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

				Package

Class

				Tree

				Todo

Class ProductController

Demo product service.

Here you can add a short overview or tutorial of how provided methods can be
utilized by the consumer.

You can even use HTML markup, at least whatever apigen accepts.

CBJsonController

ProductController

		Package: RestApi\Services

				Author:
				Konstantinos Filios <konfilios@gmail.com>

		Located at controllers/ProductController.php

Methods summary

			 public
			ProductJson[]

		#
		actionFindProduct( ProductQueryJson <var>$queryJson</var> )

Find products.

Find products.

Parameters

<var>$queryJson</var>

ProductQueryJson
$queryJson Query criteria

Returns

					ProductJson[]
Matching products

		Demo Json Service API documentation generated by ApiGen 2.8.0


text:
package net.jawr.web.resource.bundle.generator;

import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.jawr.web.JawrConstant;
import net.jawr.web.config.JawrConfig;
import net.jawr.web.resource.bundle.generator.variant.VariantResourceGenerator;
import net.jawr.web.resource.bundle.variant.VariantSet;
import net.jawr.web.resource.handler.reader.ResourceReaderHandler;
import net.jawr.web.resource.handler.reader.TextResourceReader;

/**
 * This class defines the wrapper class for resource generator in text resource
 * reader.
 *
 * @author Ibrahim Chaehoi
 */
public class ResourceGeneratorReaderWrapper implements TextResourceReader {

	/** The resource generator wrapped */
	private TextResourceGenerator generator;

	/** The resource handler */
	private ResourceReaderHandler rsHandler;

	/** The Jawr config */
	private JawrConfig config;

	/**
	 * Constructor
	 *
	 * @param generator
	 *            the generator
	 */
	public ResourceGeneratorReaderWrapper(TextResourceGenerator generator,
			ResourceReaderHandler rsHandler, JawrConfig config) {
		this.generator = generator;
		this.config = config;
		this.rsHandler = rsHandler;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.jawr.web.resource.handler.ResourceReader#getResource(java.lang.String
	 * )
	 */
	public Reader getResource(String resourceName) {

		return getResource(resourceName, false);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.jawr.web.resource.handler.ResourceReader#getResource(java.lang.String
	 * , boolean)
	 */
	public Reader getResource(String resourceName, boolean processingBundle) {

		Locale locale = null;
		String path = generator.getResolver().getResourcePath(resourceName);

		Map<String, String> contextVariants = new HashMap<String, String>();
		Map<String, VariantSet> variantSets = new HashMap<String, VariantSet>();
		if (generator instanceof VariantResourceGenerator
				|| generator instanceof LocaleAwareResourceGenerator) {

			int variantSuffixIdx = path.indexOf("@");
			if (variantSuffixIdx != -1) {

				String variantKey = path.substring(path
						.indexOf('@') + 1);

				// Remove variant suffix
				path = path.substring(0, variantSuffixIdx);

				String[] variants = variantKey.split("@");
				if (generator instanceof VariantResourceGenerator) {
					variantSets = ((VariantResourceGenerator) generator)
							.getAvailableVariants(path);
				} else { // instanceof LocaleAwareResourceGenerator
					List<String> availableLocales = ((LocaleAwareResourceGenerator) generator)
							.getAvailableLocales(path);
					if (availableLocales != null) {
						variantSets.put(JawrConstant.LOCALE_VARIANT_TYPE,
								new VariantSet(
										JawrConstant.LOCALE_VARIANT_TYPE, "",
										availableLocales));
					}
				}

				// Sort the variant types
				List<String> variantTypes = new ArrayList<String>(
						variantSets.keySet());
				Collections.sort(variantTypes);
				int nbVariants = variants.length;

				for (int i = 0; i < nbVariants; i++) {
					String variantType = variantTypes.get(i);
					String variantValue = variants[i];
					contextVariants.put(variantType, variantValue);
					if (variantType == JawrConstant.LOCALE_VARIANT_TYPE) {
						// Resourcebundle should be doing this for me...
						String[] params = variantValue.split("_");
						switch (params.length) {
						case 3:
							locale = new Locale(params[0], params[1], params[2]);
							break;
						case 2:
							locale = new Locale(params[0], params[1]);
							break;
						default:
							locale = new Locale(variantValue);
						}
					}
				}
			}
		}

		GeneratorContext context = new GeneratorContext(config, path);
		context.setVariantMap(contextVariants);
		context.setVariantSets(variantSets);

		context.setLocale(locale);
		context.setResourceReaderHandler(rsHandler);
		context.setProcessingBundle(processingBundle);

		return generator.createResource(context);
	}

}


text:
package org.apache.commons.scxml2.env.jexl;

import org.apache.commons.scxml2.Builtin;
import org.apache.commons.scxml2.SCXMLExpressionException;
import org.apache.commons.scxml2.XPathBuiltin;

/**
 * Global JEXL namespace functor, providing the standard SCXML In() operator and the Commons SCXML extensions
 * for Data() and Location() to support XPath datamodel access.
 */
public final class JexlBuiltin {
    /**
     * The context currently in use for evaluation.
     */
    private final JexlContext context;

    /**
     * Creates a new instance, wraps the context.
     * @param ctxt the context in use
     */
    public JexlBuiltin(final JexlContext ctxt) {
        context = ctxt;
    }

    /**
     * Provides the SCXML standard In() predicate for SCXML documents.
     * @param state The State ID to compare with
     * @return true if this state is currently active
     */
    public boolean In(final String state) {
        return Builtin.isMember(context, state);
    }

    /**
     * Provides the Commons SCXML Data() predicate extension for SCXML documents.
     * @param expression the XPath expression
     * @return the data matching the expression
     * @throws SCXMLExpressionException A malformed expression exception
     */
    public Object Data(final String expression) throws SCXMLExpressionException {
        return XPathBuiltin.eval(context, expression);
    }

    /**
     * Provides the Commons SCXML Location() predicate extension for SCXML documents.
     * @param expression the XPath expression
     * @return the location matching the expression
     * @throws SCXMLExpressionException A malformed expression exception
     */
    public Object Location(final String expression) throws SCXMLExpressionException {
        return XPathBuiltin.evalLocation(context, expression);
    }
}


text:
require 'ads_common/savon_service'
require 'dfp_api/v201505/product_template_service_registry'

module DfpApi; module V201505; module ProductTemplateService
  class ProductTemplateService < AdsCommon::SavonService
    def initialize(config, endpoint)
      namespace = 'https://www.google.com/apis/ads/publisher/v201505'
      super(config, endpoint, namespace, :v201505)
    end

    def create_product_templates(*args, &block)
      return execute_action('create_product_templates', args, &block)
    end

    def get_product_templates_by_statement(*args, &block)
      return execute_action('get_product_templates_by_statement', args, &block)
    end

    def perform_product_template_action(*args, &block)
      return execute_action('perform_product_template_action', args, &block)
    end

    def update_product_templates(*args, &block)
      return execute_action('update_product_templates', args, &block)
    end

    private

    def get_service_registry()
      return ProductTemplateServiceRegistry
    end

    def get_module()
      return DfpApi::V201505::ProductTemplateService
    end
  end
end; end; end