text:
define(['lodash', 'log', 'event_channel',  'alerts', './svg-canvas', './../ast/function-definition', './default-worker',
        'd3utils', 'd3', './worker-declaration-view', './statement-view-factory', './point', './axis',
        './connector-declaration-view', './statement-container', './variable-definitions-pane-view', './function-arguments-view',
        './return-types-pane-view', 'ballerina/ast/ballerina-ast-factory'],
    function (_, log, EventChannel, Alerts, SVGCanvas, FunctionDefinition, DefaultWorkerView,
              D3Utils, d3, WorkerDeclarationView, StatementViewFactory, Point, Axis,
              ConnectorDeclarationView, StatementContainer, VariablesView, ArgumentsView,
              ReturnTypePaneView, BallerinaASTFactory) {

        /**
         * The view to represent a function definition which is an AST visitor.
         * @param {Object} args - Arguments for creating the view.
         * @param {FunctionDefinition} args.model - The function definition model.
         * @param {Object} args.container - The HTML container to which the view should be added to.
         * @param {Object} [args.viewOptions={}] - Configuration values for the view.
         * @constructor
         * @augments SVGCanvas
         */
        var FunctionDefinitionView = function (args) {
            SVGCanvas.call(this, args);
            this._statementExpressionViewList = [];
            // TODO: Instead of using the parentView use the parent. Fix this from BallerinaView.js and bellow
            this._parentView = _.get(args, "parentView");
            //set panel icon for the function
            this._viewOptions.panelIcon = _.get(args.viewOptions, "cssClass.function_icon");
            //set initial height for the service container svg
            this._totalHeight = 170;
            this._statementContainer = undefined;

            this._defaultWorkerLifeLine = undefined;
            // TODO: Check whether the possibility of adding this to the generic level
            this._workerAndConnectorViews = [];
            //set initial worker margin for the function
            this._workerLifelineMargin = new Axis(0, false);
            // Set the initial height control margin
            this._horizontalMargin = new Axis(0, true);
            this._lifeLineCenterGap = 180;
            this._offsetLastStatementGap = 100;

            if (_.isNil(this._model) || !(this._model instanceof FunctionDefinition)) {
                log.error("Function definition is undefined or is of different type." + this._model);
                throw "Function definition is undefined or is of different type." + this._model;
            }

            if (_.isNil(this._container)) {
                log.error("Container for function definition is undefined." + this._container);
                throw "Container for function definition is undefined." + this._container;
            }
        };

        FunctionDefinitionView.prototype = Object.create(SVGCanvas.prototype);
        FunctionDefinitionView.prototype.constructor = FunctionDefinitionView;

        /**
         * Child remove callback
         * @param {ASTNode} child - removed child
         */
        FunctionDefinitionView.prototype.childRemovedCallback = function (child) {
            var self = this;
            if (BallerinaASTFactory.isStatement(child)) {
                this.getStatementContainer().childStatementRemovedCallback(child);
            } else if (BallerinaASTFactory.isConnectorDeclaration(child) || BallerinaASTFactory.isWorkerDeclaration(child)) {
                var childViewIndex = _.findIndex(this._workerAndConnectorViews, function (view) {
                    return view.getModel().id === child.id;
                });

                if (childViewIndex === 0) {
                    // Deleted the first connector/worker in the list (Addresses both first element scenario and the only element scenario
                    if (!_.isNil(this._workerAndConnectorViews[childViewIndex + 1])) {
                        // Unregister the listening event of the second element on the first element
                        this._workerAndConnectorViews[childViewIndex + 1].stopListening(this._workerAndConnectorViews[childViewIndex].getBoundingBox());
                    }
                } else if (childViewIndex === this._workerAndConnectorViews.length - 1) {
                    // Deleted the last connector/worker when there are more than one worker/ connector
                    this._workerAndConnectorViews[childViewIndex].stopListening(this._workerAndConnectorViews[childViewIndex - 1].getBoundingBox());
                } else {
                    // Deleted connector is in between two other connectors/ workers
                    // Connector being deleted, stop listening to it's previous connector
                    this._workerAndConnectorViews[childViewIndex].stopListening(this._workerAndConnectorViews[childViewIndex - 1].getBoundingBox());
                    this._workerAndConnectorViews[childViewIndex + 1].stopListening(this._workerAndConnectorViews[childViewIndex].getBoundingBox());
                    this._workerAndConnectorViews[childViewIndex + 1].listenTo(this._workerAndConnectorViews[childViewIndex - 1].getBoundingBox(), 'right-edge-moved', function (offset) {
                        self.moveFunctionDefinitionLevelConnector(this, offset);
                    });
                }
                this._workerAndConnectorViews[childViewIndex] = null;
                this._workerAndConnectorViews.splice(childViewIndex, 1);
            }
            // Remove the connector/ worker from the diagram rendering context
            delete this.diagramRenderingContext.getViewModelMap()[child.id];
        };

        FunctionDefinitionView.prototype.setModel = function (model) {
            if (!_.isNil(model) && model instanceof FunctionDefinition) {
                this._model = model;
            } else {
                log.error("Function definition undefined or is of different type." + model);
                throw "Function definition undefined or is of different type." + model;
            }
        };

        FunctionDefinitionView.prototype.setContainer = function (container) {
            if (!_.isNil(container)) {
                this._container = container;
            } else {
                log.error("Container for function definition is undefined." + container);
                throw "Container for function definition is undefined." + container;
            }
        };

        FunctionDefinitionView.prototype.setViewOptions = function (viewOptions) {
            this._viewOptions = viewOptions;
        };

        FunctionDefinitionView.prototype.setChildContainer = function(svg){
            if (!_.isNil(svg)) {
                this._childContainer = svg;
            }
        };

        FunctionDefinitionView.prototype.getModel = function () {
            return this._model;
        };

        FunctionDefinitionView.prototype.getContainer = function () {
            return this._container;
        };

        FunctionDefinitionView.prototype.getViewOptions = function () {
            return this._viewOptions;
        };

        FunctionDefinitionView.prototype.getChildContainer = function(){
            return this._childContainer ;
        };

        FunctionDefinitionView.prototype.canVisitFunctionDefinition = function () {
            return true;
        };

        /**
         * @override
         */
        FunctionDefinitionView.prototype.isAValidNodeForCanvasDropArea = function (node) {
            var nodeFactory = this._model.getFactory();
            // IMPORTANT: override canvas's default validation logic
            // Canvas drop zone is for worker and connector declarations only.
            // Statements should only be allowed on top of function worker's drop zone.
            return nodeFactory.isConnectorDeclaration(node)
                || nodeFactory.isWorkerDeclaration(node);
        };

        /**
         * Calls the render method for a worker declaration.
         * @param {WorkerDeclaration} workerDeclaration - The worker declaration model.
         */
        FunctionDefinitionView.prototype.visitWorkerDeclaration = function (workerDeclaration) {
            var self = this;
            var container = this._rootGroup.node();
            // If the default worker, we skip
            if (!workerDeclaration.isDefaultWorker()) {
                var lastWorkerIndex = this.getLastWorkerLifeLineIndex();
                var newWorkerPosition = lastWorkerIndex === -1 ? 0 : lastWorkerIndex + 1;
                var centerPoint = undefined;
                if (newWorkerPosition === 0) {
                    centerPoint = this._defaultWorkerLifeLine.getTopCenter().clone().move(this._lifeLineCenterGap, 0);
                } else {
                    centerPoint = this._workerAndConnectorViews[lastWorkerIndex].getTopCenter()
                        .clone().move(this._lifeLineCenterGap, 0)
                }
                var lineHeight = this.getDefaultWorker().getBottomCenter().y() - centerPoint.y();
                var workerDeclarationOptions = {
                    model: workerDeclaration,
                    container: container,
                    centerPoint: centerPoint,
                    toolPalette: this.toolPalette,
                    messageManager: this.messageManager,
                    diagramRenderContext: this.getDiagramRenderingContext(),
                    line: {height: lineHeight},
                    title: workerDeclaration.getWorkerName()
                };
                var workerDeclarationView = new WorkerDeclarationView(workerDeclarationOptions);
                workerDeclarationView.setParent(this);
                workerDeclarationView.render();

                // Creating Expression Editor
                var editableProperty = {
                    propertyType: "text",
                    key: "WorkerDeclaration",
                    model: workerDeclarationView._model,
                    getterMethod: workerDeclarationView._model.getWorkerDeclarationStatement,
                    setterMethod: workerDeclarationView._model.setWorkerDeclarationStatement,
                    getDisplayTitle: workerDeclarationView._model.getWorkerName
                };
                workerDeclarationView.createPropertyPane({
                    model: workerDeclarationView._model,
                    lifeLineGroup: workerDeclarationView._rootGroup,
                    editableProperties: editableProperty
                });

                var statementContainer = workerDeclarationView.renderStatementContainer({offset: {top: 40, bottom: 50}});
                this.diagramRenderingContext.getViewModelMap()[workerDeclaration.id] = workerDeclarationView;
                this.listenWorkerToHorizontalMargin(workerDeclarationView);

                // Worker listen to its statement container
                workerDeclarationView.listenTo(statementContainer.getBoundingBox(), 'bottom-edge-moved', function(dy) {
                    var deltaMove = self.getDeltaMove(self.getDeepestChild(workerDeclarationView, dy), dy);
                    // Bellow logic is for properly align all the workers and the connectors
                    // Statement Container expands. we move the horizontal line
                    workerDeclarationView.getBottomCenter().y(workerDeclarationView.getBottomCenter().y() + deltaMove);
                    workerDeclarationView.getBoundingBox().h(workerDeclarationView.getBoundingBox().h() + deltaMove);
                    workerDeclarationView.stopListening(self.getHorizontalMargin());
                    self.getHorizontalMargin().setPosition(self.getHorizontalMargin().getPosition() + deltaMove);
                    self.listenWorkerToHorizontalMargin(workerDeclarationView);
                    // We need to change the height of the statement container, silently. This is because when this
                    // particular event is triggered, bounding box of the statement container has already changed,
                    // before hand we manipulate it with this logic
                    var statementContainerNewH = workerDeclarationView.getBottomCenter().y() - workerDeclarationView.getTopCenter().y();
                    // TODO: re consider stopListening of the following event of the statement container. This is because we silently change the heights
                    self.getStatementContainer().stopListening(self.getStatementContainer().getBoundingBox(), 'height-changed');
                    workerDeclarationView.getStatementContainer().changeHeightSilent(statementContainerNewH);
                    // Re initialize the above disabled event
                    // self.getStatementContainer().listenTo(self.getStatementContainer().getBoundingBox(), 'height-changed', function (offset) {
                    //     self.getStatementContainer()._mainDropZone.attr('height', parseFloat(self.getStatementContainer()._mainDropZone.attr('height')) + offset);
                    // });
                });

                // Set the workerLifeLineMargin to the right edge of the newly added worker
                this.getWorkerLifeLineMargin().setPosition(workerDeclarationView.getBoundingBox().getRight());
                if (lastWorkerIndex === this.getWorkerAndConnectorViews().length -1 &&
                    workerDeclarationView.getBoundingBox().getRight() > this.getBoundingBox().getRight()) {
                    // Worker is added as the last element for the ConnectorWorkerViewList.
                    // Only Connectors are there at the moment
                    this._parentView.getLifeLineMargin().setPosition(this._parentView.getLifeLineMargin().getPosition() + this._lifeLineCenterGap);
                    this.setContentMinWidth(workerDeclarationView.getBoundingBox().getRight());
                    this.setHeadingMinWidth(workerDeclarationView.getBoundingBox().getRight());
                }

                if (_.isEqual(newWorkerPosition, 0)) {
                    workerDeclarationView.listenTo(this.getDefaultWorker().getBoundingBox(), 'right-edge-moved', function (dx) {
                        workerDeclarationView.getBoundingBox().move(dx, 0);
                    });
                }

                statementContainer.listenTo(workerDeclarationView.getBoundingBox(), 'right-edge-moved', function (dx) {
                    statementContainer.getBoundingBox().move(dx, 0);
                });

                this.getWorkerAndConnectorViews().splice(newWorkerPosition, 0, workerDeclarationView);
            }
        };

        /**
         * Rendering the view for function definition.
         * @returns {group} The svg group which contains the elements of the function definition view.
         */
        FunctionDefinitionView.prototype.render = function (diagramRenderingContext) {
            this.setDiagramRenderingContext(diagramRenderingContext);

            // Draws the outlying body of the function.
            this.drawAccordionCanvas(this._viewOptions, this.getModel().getID(), this.getModel().type.toLowerCase(), this.getModel().getFunctionName());

            // Setting the styles for the canvas icon.
            if (!this.getModel().isMainFunction()) {
                this.getPanelIcon().addClass(_.get(this._viewOptions, "cssClass.function_icon", ""));
            } else {
                this.getPanelIcon().addClass(_.get(this._viewOptions, "cssClass.main_function_icon", ""));
            }

            var currentContainer = $('#' + this.getModel().getID());
            this._container = currentContainer;
            this.getBoundingBox().fromTopLeft(new Point(0, 0), currentContainer.width(), currentContainer.height());
            var self = this;

            //Scroll to the added position and highlight the heading
            $(_.get(this._viewOptions, "design_view.container", "")).scrollTop(currentContainer.parent().position().top);
            var hadingBox = $('#' + this.getModel().getID() + "_heading");
            var canvas_heading_new = _.get(this._viewOptions, "cssClass.canvas_heading_new", "");
            var new_drop_timeout = _.get(this._viewOptions, "design_view.new_drop_timeout", "");
            hadingBox.addClass(canvas_heading_new);
            setTimeout(function(){hadingBox.removeClass(canvas_heading_new)}, new_drop_timeout);

            if (!this.getModel().isMainFunction()) {
                $(this.getTitle()).text(this.getModel().getFunctionName())
                    .on("change paste keyup", function () {
                        self.getModel().setFunctionName($(this).text());
                    }).on("click", function (event) {
                    event.stopPropagation();
                }).keypress(function (e) {
                    var enteredKey = e.which || e.charCode || e.keyCode;
                    // Disabling enter key
                    if (enteredKey == 13) {
                        event.stopPropagation();
                        return false;
                    }

                    var newServiceName = $(this).text() + String.fromCharCode(enteredKey);

                    try {
                        self.getModel().setFunctionName(newServiceName);
                    } catch (error) {
                        Alerts.error(error);
                        event.stopPropagation();
                        return false;
                    }
                });
            } else {
                // Making the main function title non editable.
                $(this.getTitle()).removeAttr("contenteditable");
            }

            // Creating default worker
            var defaultWorkerOpts = {};
            _.set(defaultWorkerOpts, 'container', this._rootGroup.node());
            _.set(defaultWorkerOpts, 'title', 'FunctionWorker');
            _.set(defaultWorkerOpts, 'centerPoint', new Point(200, 80));

            // Check whether there is already created default worker and otherwise we create a new one
            if (_.isUndefined(this._defaultWorkerLifeLine)) {
                this._defaultWorkerLifeLine = new DefaultWorkerView(defaultWorkerOpts);
            }
            this._defaultWorkerLifeLine.render();

            // Set the workerLifeLineMargin to the end of the default worker
            this.getHorizontalMargin().setPosition(this._defaultWorkerLifeLine.getBoundingBox().getBottom());
            this.getWorkerLifeLineMargin().setPosition(this._defaultWorkerLifeLine.getBoundingBox().getRight());
            this.listenTo(this.getHorizontalMargin(), 'moved', function (dy) {
                self._defaultWorkerLifeLine.getBottomCenter().y(self._defaultWorkerLifeLine.getBottomCenter().y() + dy);
                // Silently increase the bounding box of the worker. Because this size change is due to the
                // horizontal margin movement, in other sense, for balancing with the other connectors/ workers' height
                // therefore we need to manually change the bbox height and the drop zone size of the statement container
                self.getStatementContainer().getBoundingBox().h(self.getStatementContainer().getBoundingBox().h() + dy, true);
                self.getStatementContainer().changeDropZoneHeight(dy);
                self._totalHeight = this.getHorizontalMargin().getPosition() + 85;
                self.setSVGHeight(this._totalHeight);
            });

            this._totalHeight = this.getHorizontalMargin().getPosition() + 85;
            this.setSVGHeight(this._totalHeight);
            this.renderStatementContainer();

            // TODO: change this accordingly, after the worker declaration introduced
            this.getWorkerLifeLineMargin().listenTo(this.getStatementContainer().getBoundingBox(), 'right-edge-moved', function (dx) {
                self.getWorkerLifeLineMargin().setPosition(self.getWorkerLifeLineMargin().getPosition() + dx);
            });

            this.getModel().accept(this);
            //Removing all the registered 'child-added' event listeners for this model.
            //This is needed because we are not unregistering registered event while the diagram element deletion.
            //Due to that, sometimes we are having two or more view elements listening to the 'child-added' event of same model.
            this.getModel().off('child-added');
            this.getModel().on('child-added', function (child) {
                self.visit(child);
                self.getModel().trigger("child-visited", child);

                // Show/Hide scrolls.
                self._showHideScrolls(self._container, self.getChildContainer().node().ownerSVGElement);
            });

            var operationsPane = this.getOperationsPane();

            var operationButtons = [];

            this.setSVGWidth(this._container.width());

            if (!this.getModel().isMainFunction()) {
                // Creating return type icon.
                var panelReturnTypeIcon = $("<i/>", {
                    class: "fw fw-export pull-right right-icon-clickable hoverable",
                    title: "Return Types"
                }).appendTo(operationsPane).tooltip();

                $(panelReturnTypeIcon).click(function (event) {
                    event.stopPropagation();
                });

                operationButtons.push(panelReturnTypeIcon);

                // Adding separator for return type icon.
                $("<span class='pull-right canvas-operations-separator'>|</span>").appendTo(operationsPane);

                var returnTypeProperties = {
                    model: this._model,
                    activatorElement: panelReturnTypeIcon,
                    paneAppendElement: this.getChildContainer().node().ownerSVGElement.parentElement,
                    viewOptions: {
                        position: new Point(parseInt($(this.getChildContainer().node().ownerSVGElement.parentElement).width()),
                            0)
                    },
                    view: this
                };

                this._returnTypePaneView = new ReturnTypePaneView(returnTypeProperties);

                // Creating return type pane.
                this._returnTypePaneView.createReturnTypePane(diagramRenderingContext);

            }

            // Creating arguments icon.
            var panelArgumentsIcon = $("<i/>", {
                class: "fw fw-import pull-right right-icon-clickable hoverable",
                title: "Arguments"
            }).appendTo(operationsPane).tooltip();

            $(panelArgumentsIcon).click(function (event) {
                event.stopPropagation();
            });

            operationButtons.push(panelArgumentsIcon);

            // Adding separator for arguments icon.
            $("<span class='pull-right canvas-operations-separator'>|</span>").appendTo(operationsPane);

            var argumentsProperties = {
                model: this._model,
                activatorElement: panelArgumentsIcon,
                paneAppendElement: this.getChildContainer().node().ownerSVGElement.parentElement,
                viewOptions: {
                    position: {
                        left: parseInt($(this.getChildContainer().node().ownerSVGElement.parentElement).width()),
                        top: 0
                    }
                },
                disableEditing: this.getModel().isMainFunction()
            };

            // Creating arguments pane.
            ArgumentsView.createArgumentsPane(argumentsProperties, diagramRenderingContext);

            // Closing the shown pane when another operation button is clicked.
            _.forEach(operationButtons, function (button) {
                button.click(function () {
                    _.forEach(operationButtons, function (buttonToClick) {
                        if (button !== buttonToClick && $(buttonToClick).data("showing-pane") == "true") {
                            $(buttonToClick).click();
                        }
                    });
                });
            });
        };

        /**
         * Shows and hide the custom scrolls depending on the amount scrolled.
         * @param {Element} container - The container of the SVG. i.e the parent of the SVG.
         * @param {Element} svgElement - The SVG element.
         */
        FunctionDefinitionView.prototype._showHideScrolls = function (container, svgElement) {
            // Creating scroll panes.
            var leftScroll = $(this.getChildContainer().node().ownerSVGElement.parentElement)
                .find(".service-left-scroll").get(0);
            var rightScroll = $(this.getChildContainer().node().ownerSVGElement.parentElement)
                .find(".service-right-scroll").get(0);

            // Setting heights of the scrolls.
            $(leftScroll).height($(container).height());
            $(rightScroll).height($(container).height());

            // Positioning the arrows of the scrolls to the middle.
            $(leftScroll).find("i").css("padding-top", ($(container).height() / 2) - (parseInt($(leftScroll).find("i").css("font-size"), 10) / 2) + "px");
            $(rightScroll).find("i").css("padding-top", ($(container).height() / 2) - (parseInt($(rightScroll).find("i").css("font-size"), 10) / 2) + "px");

            // Showing/Hiding scrolls.
            if (parseInt($(container).width(), 10) >= parseInt($(svgElement).width(), 10)) {
                // If the svg width is less than or equal to the container, then no need to show the arrows.
                $(leftScroll).hide();
                $(rightScroll).hide();
            } else {
                // If the svg width is greater than the width of the container...
                if ($(container).scrollLeft() == 0) {
                    // When scrollLeft is 0, means that it is already scrolled to the left corner.
                    $(rightScroll).show();
                    $(leftScroll).hide();
                } else if (Math.abs(parseInt($(container).scrollLeft()) -
                        (parseInt($(svgElement).width(), 10) -
                        parseInt($(container).width(), 10))) < 5) {
                    $(leftScroll).show();
                    $(rightScroll).hide();
                } else {
                    $(leftScroll).show();
                    $(rightScroll).show();
                }
            }
        };

        /**
         * Render statement container
         */
        FunctionDefinitionView.prototype.renderStatementContainer = function(){
            var statementContainerOpts = {};
            _.set(statementContainerOpts, 'model', this._model);
            _.set(statementContainerOpts, 'topCenter', this._defaultWorkerLifeLine.getTopCenter());
            _.set(statementContainerOpts, 'bottomCenter', this._defaultWorkerLifeLine.getBottomCenter());
            _.set(statementContainerOpts, 'width', this._defaultWorkerLifeLine.width());
            _.set(statementContainerOpts, 'container', this._defaultWorkerLifeLine.getContentArea().node());
            _.set(statementContainerOpts, 'toolPalette', this.toolPalette);
            _.set(statementContainerOpts, 'offset', {top: 40, bottom: 40});
            this._statementContainer = new StatementContainer(statementContainerOpts);
            var self = this;

            this.listenTo(this._statementContainer.getBoundingBox(), 'bottom-edge-moved', function(dy){

                var deltaMove = this.getDeltaMove(this.getDeepestChild(this, dy), dy);
                // Statement Container expands. we move the horizontal line
                self._defaultWorkerLifeLine.getBottomCenter().y(self._defaultWorkerLifeLine.getBottomCenter().y() + deltaMove);
                // self._defaultWorker.getBoundingBox().h(self._defaultWorker.getBoundingBox().h() + dy);
                self.stopListening(self.getHorizontalMargin());
                self.getHorizontalMargin().setPosition(self.getHorizontalMargin().getPosition() + deltaMove);
                self.getBoundingBox().h(this.getBoundingBox().h() + deltaMove);
                // We need to change the height of the statement container, silently. This is because when this
                // particular event is triggered, bounding box of the statement container has already changed,
                // before hand we manipulate it with this logic
                var statementContainerNewH = self._defaultWorkerLifeLine.getBottomCenter().y() - self._defaultWorkerLifeLine.getTopCenter().y();
                // TODO: re consider stopListening of the following event of the statement container. This is because we silently change the heights
                self.getStatementContainer().stopListening(self.getStatementContainer().getBoundingBox(), 'height-changed');
                self.getStatementContainer().changeHeightSilent(statementContainerNewH);
                self._totalHeight = this.getHorizontalMargin().getPosition() + 85;
                self.setSVGHeight(this._totalHeight);
                // Re initialize the above disabled event
                // self.getStatementContainer().listenTo(self.getStatementContainer().getBoundingBox(), 'height-changed', function (offset) {
                //     self.getStatementContainer()._mainDropZone.attr('height', parseFloat(self.getStatementContainer()._mainDropZone.attr('height')) + offset);
                // });
                self.listenTo(self.getHorizontalMargin(), 'moved', function (dy) {
                    self._defaultWorkerLifeLine.getBottomCenter().y(self._defaultWorkerLifeLine.getBottomCenter().y() + dy);
                    // Silently increase the bounding box of the worker. Because this size change is due to the
                    // horizontal margin movement, in other sense, for balancing with the other connectors/ workers' height
                    // therefore we need to manually change the bbox height and the drop zone size of the statement container
                    self.getStatementContainer().getBoundingBox().h(self.getStatementContainer().getBoundingBox().h() + dy, true);
                    self.getStatementContainer().changeDropZoneHeight(dy);
                    self._totalHeight = self.getHorizontalMargin().getPosition() + 85;
                    self.setSVGHeight(self._totalHeight);
                });
            }, this);

            /* When the width of the statement container's bounding box changes, width of this resource definition's
             bounding box should also change.*/
            this._statementContainer.getBoundingBox().on('right-edge-moved', function (dw) {
                this._defaultWorkerLifeLine.getBoundingBox().zoomWidth(this._statementContainer.getBoundingBox().w());
            }, this);
            this._statementContainer.render(this.diagramRenderingContext);
        };

        FunctionDefinitionView.prototype.defaultWorkerHeightChanged = function (dy) {
            this._defaultWorkerLifeLine.getBottomCenter().y(this._statementContainer.getBoundingBox().getBottom());
            this.getBoundingBox().h(this.getBoundingBox().h() + dy);
            this._totalHeight = this._totalHeight + dy;
            this.setSVGHeight(this._totalHeight);
        };

        /**
         * @param {BallerinaStatementView} statement
         */
        FunctionDefinitionView.prototype.visitStatement = function (statement) {
            var args = {model: statement, container: this._rootGroup.node(), viewOptions: {},
                toolPalette: this.toolPalette, messageManager: this.messageManager, parent: this};
            this._statementContainer.renderStatement(statement, args);
        };

        /**
         * This function will skip comment views rendering
         * @param commentStatement
         */
        FunctionDefinitionView.prototype.visitCommentStatement = function (commentStatement) {
        };

        /**
         * Calls the render method for a connector declaration.
         * @param connectorDeclaration
         */
        FunctionDefinitionView.prototype.visitConnectorDeclaration = function (connectorDeclaration) {
            var lastLifeLine = this.getLastLifeLine();
            var lastConnectorLifeLine = this.getWorkerAndConnectorViews()[this.getLastConnectorLifeLineIndex()];
            var self = this;
            // TODO: Get these values from the constants
            var offsetBetweenLifeLines = 50;
            var connectorContainer = this.getChildContainer().node(),
                connectorOpts = {
                    model: connectorDeclaration,
                    container: connectorContainer,
                    parentView: this,
                    lineHeight: this._defaultWorkerLifeLine.getTopCenter()
                                .absDistInYFrom(this._defaultWorkerLifeLine.getBottomCenter()),
                    messageManager: this.messageManager,
                    centerPoint: lastLifeLine.getTopCenter().clone().move(this._lifeLineCenterGap, 0)
                },
                connectorDeclarationView;

            connectorDeclarationView = new ConnectorDeclarationView(connectorOpts);
            this.diagramRenderingContext.getViewModelMap()[connectorDeclaration.id] = connectorDeclarationView;
            connectorDeclarationView.setParent(this);
            connectorDeclarationView.render();

            connectorDeclarationView.createPropertyPane();

            if (_.isNil(lastConnectorLifeLine)) {
                // This is the first connector we are adding
                connectorDeclarationView.listenTo(this.getWorkerLifeLineMargin(), 'moved', function (offset) {
                    self.moveFunctionDefinitionLevelConnector(this, offset);
                });
            } else {
                // There are already added connectors
                // Previously added connector stop listening to bounding box move.
                // Based on this event we increase the service container width
                lastConnectorLifeLine.stopListening(lastConnectorLifeLine.getBoundingBox(), 'right-edge-moved');
                connectorDeclarationView.listenTo(lastConnectorLifeLine.getBoundingBox(), 'right-edge-moved', function (offset) {
                    self.moveFunctionDefinitionLevelConnector(this, offset);
                });
            }

            /* If the adding connector (connectorDeclarationView) goes out of this function definition's view,
             then we need to expand this function definition's view. */
            if (connectorDeclarationView.getBoundingBox().getRight() > this.getBoundingBox().getRight()) {
                this._parentView.getLifeLineMargin().setPosition(this._parentView.getLifeLineMargin().getPosition()
                    + this._lifeLineCenterGap);
            }

            var connectorBBox = connectorDeclarationView.getBoundingBox();
            connectorDeclarationView.listenTo(connectorBBox, 'right-edge-moved', function (offset) {
                if (connectorBBox.getRight() > self.getBoundingBox().getRight()) {
                    self._parentView.getLifeLineMargin().setPosition(self._parentView.getLifeLineMargin().getPosition() + self._lifeLineCenterGap);
                }
            }, connectorDeclarationView);

            connectorDeclarationView.listenTo(this.getHorizontalMargin(), 'moved', function (dy) {
                connectorDeclarationView.getBoundingBox().h(connectorDeclarationView.getBoundingBox().h() + dy);
            });

            this._workerAndConnectorViews.push(connectorDeclarationView);
        };

        /**
         * @inheritDoc
         * @returns {_defaultWorker}
         */
        FunctionDefinitionView.prototype.getDefaultWorkerLifeLine = function () {
            return this._defaultWorkerLifeLine;
        };

        /**
         * @inheritDoc
         * @returns [_workerAndConnectorViews]
         */
        FunctionDefinitionView.prototype.getWorkerAndConnectorViews = function () {
            return this._workerAndConnectorViews;
        };

        FunctionDefinitionView.prototype.getChildContainer = function () {
            return this.getRootGroup();
        };

        /**
         * Return statement container
         * @return {StatementContainerView}
         */
        FunctionDefinitionView.prototype.getStatementContainer = function () {
            return this._statementContainer;
        };

        FunctionDefinitionView.prototype.moveFunctionDefinitionLevelConnector = function (connectorView, offset) {
            connectorView.getBoundingBox().move(offset, 0);
        };

        /**
         * Set the horizontal margin
         * @param {Axis} horizontalMargin - horizontal margin
         */
        FunctionDefinitionView.prototype.setHorizontalMargin = function (horizontalMargin) {
            this._horizontalMargin = horizontalMargin;
        };

        /**
         * Get the horizontal margin
         * @return {Axis|*}
         */
        FunctionDefinitionView.prototype.getHorizontalMargin = function () {
            return this._horizontalMargin;
        };

        /**
         * Get the worker lifeline margin
         * @return {Axis}
         */
        FunctionDefinitionView.prototype.getWorkerLifeLineMargin = function () {
            return this._workerLifelineMargin;
        };

        /**
         * Set the worker lifeline margin
         * @param {Axis} workerLifeLineMargin
         */
        FunctionDefinitionView.prototype.setWorkerLifeLineMargin = function (workerLifeLineMargin) {
            this._workerLifelineMargin = workerLifeLineMargin;
        };

        /**
         * Get the last lifeline
         * @return {lifeLine} LifeLine
         */
        FunctionDefinitionView.prototype.getLastLifeLine = function () {
            if(this.getWorkerAndConnectorViews().length > 0 ){
                return _.last(this.getWorkerAndConnectorViews());
            }
            else{
                return this.getDefaultWorker();
            }
        };

        FunctionDefinitionView.prototype.getDefaultWorker = function () {
            return this._defaultWorkerLifeLine;
        };

        FunctionDefinitionView.prototype.getWorkerAndConnectorViews = function () {
            return this._workerAndConnectorViews;
        };

        /**
         * Set Minimum width of the content area
         * @param {number} minWidth - Minimum width
         */
        FunctionDefinitionView.prototype.setContentMinWidth = function (minWidth) {
            this._viewOptions.contentMinWidth = minWidth;
        };

        FunctionDefinitionView.prototype.getLastConnectorLifeLineIndex = function () {
            var index = _.findLastIndex(this.getWorkerAndConnectorViews(), function (lifeLine) {
                return lifeLine instanceof ConnectorDeclarationView;
            });
            return index;
        };

        FunctionDefinitionView.prototype.getLastWorkerLifeLineIndex = function () {
            var index = _.findLastIndex(this.getWorkerAndConnectorViews(), function (lifeLine) {
                return lifeLine instanceof WorkerDeclarationView;
            });
            return index;
        };

        FunctionDefinitionView.prototype.listenWorkerToHorizontalMargin = function (workerDeclarationView) {
            workerDeclarationView.listenTo(this.getHorizontalMargin(), 'moved', function (dy) {
                workerDeclarationView.getBottomCenter().y(workerDeclarationView.getBottomCenter().y() + dy);
                workerDeclarationView.getBoundingBox().h(workerDeclarationView.getBoundingBox().h() + dy);
                // Silently increase the bounding box of the worker. Because this size change is due to the
                // horizontal margin movement, in other sense, for balancing with the other connectors/ workers' height
                // therefore we need to manually change the bbox height and the drop zone size of the statement container
                workerDeclarationView.getStatementContainer().getBoundingBox().h(workerDeclarationView.getStatementContainer().getBoundingBox().h() + dy, true);
                workerDeclarationView.getStatementContainer().changeDropZoneHeight(dy);
            });
        };

        FunctionDefinitionView.prototype.getDeltaMove = function (deepestChild, dy) {
            var deltaMove = 0;
            if (dy > 0) {
                deltaMove = dy;
            } else {
                if (_.isNil(deepestChild)) {
                    deltaMove = dy;
                } else {
                    deltaMove = -(this.getHorizontalMargin().getPosition() -
                    this.getDiagramRenderingContext().getViewOfModel(deepestChild).getBoundingBox().getBottom() - this._offsetLastStatementGap);
                }
            }
            return deltaMove;
        };

        // TODO: Need to generalize this method, since functionDefinition, actionDefinition and resourceDefinition uses this
        FunctionDefinitionView.prototype.getDeepestChild = function (currentWorker, dy) {
            var self = this;
            var lastChildArr = [];

            this.getWorkerAndConnectorViews().forEach(function (worker) {
                if (worker instanceof WorkerDeclarationView) {
                    // if (worker.getModel().id === currentWorker.getModel().id && dy < 0) {
                    //     // TODO: Refactor logic
                    //     // Child we are removing, have not removed from the view list yet
                    //     lastChildArr.push(worker.getStatementContainer().getManagedStatements()[worker.getStatementContainer().getManagedStatements() - 2]);
                    // } else {
                    //     lastChildArr.push(_.last(worker.getStatementContainer().getManagedStatements()));
                    // }
                    // TODO: We need to rewrite this logic due to the current limitation of the element remove in statement container
                    lastChildArr.push(_.last(worker.getStatementContainer().getManagedStatements()));
                }
            });

            var sortedLastChildArr = _.sortBy(lastChildArr, function (child) {
                var stmtView = _.isNil(child) ? undefined : self.getDiagramRenderingContext().getViewOfModel(child);
                return _.isNil(stmtView) ? -1 : stmtView.getBoundingBox().getBottom();
            });

            var deepestChildStatement = _.last(sortedLastChildArr);
            var defaultWorkerLastChild = _.last(this.getStatementContainer().getManagedStatements());

            if (!_.isNil(deepestChildStatement) && _.isNil(defaultWorkerLastChild)) {
                return deepestChildStatement;
            } else if (!_.isNil(deepestChildStatement) && !_.isNil(defaultWorkerLastChild)) {
                if (this.getDiagramRenderingContext().getViewOfModel(deepestChildStatement).getBoundingBox().getBottom()
                    > this.getDiagramRenderingContext().getViewOfModel(defaultWorkerLastChild).getBoundingBox().getBottom()) {
                    return deepestChildStatement;
                } else {
                    return defaultWorkerLastChild;
                }
            } else {
                return defaultWorkerLastChild;
            }
        };

        return FunctionDefinitionView;
    });


text:
/*
 * vim:ts=4:sw=4:expandtab
 *
 * i3 - an improved dynamic tiling window manager
 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
 *
 * include/configuration.h: Contains all structs/variables for the configurable
 * part of i3 as well as functions handling the configuration file (calling
 * the parser (src/config_parse.c) with the correct path, switching key
 * bindings mode).
 *
 */
#pragma once

#include "queue.h"
#include "i3.h"

typedef struct IncludedFile IncludedFile;
typedef struct Config Config;
typedef struct Barconfig Barconfig;
extern char *current_configpath;
extern char *current_config;
extern Config config;
extern SLIST_HEAD(modes_head, Mode) modes;
extern TAILQ_HEAD(barconfig_head, Barconfig) barconfigs;
extern TAILQ_HEAD(includedfiles_head, IncludedFile) included_files;

/**
 * Used during the config file lexing/parsing to keep the state of the lexer
 * in order to provide useful error messages in yyerror().
 *
 */
struct context {
    bool has_errors;
    bool has_warnings;

    int line_number;
    char *line_copy;
    const char *filename;

    char *compact_error;

    /* These are the same as in YYLTYPE */
    int first_column;
    int last_column;
};

/**
 * Part of the struct Config. It makes sense to group colors for background,
 * border and text as every element in i3 has them (window decorations, bar).
 *
 */
struct Colortriple {
    color_t border;
    color_t background;
    color_t text;
    color_t indicator;
    color_t child_border;
};

/**
 * Holds a user-assigned variable for parsing the configuration file. The key
 * is replaced by value in every following line of the file.
 *
 */
struct Variable {
    char *key;
    char *value;
    char *next_match;

    SLIST_ENTRY(Variable) variables;
};

/**
 * List entry struct for an included file.
 *
 */
struct IncludedFile {
    char *path;

    TAILQ_ENTRY(IncludedFile) files;
};

/**
 * The configuration file can contain multiple sets of bindings. Apart from the
 * default set (name == "default"), you can specify other sets and change the
 * currently active set of bindings by using the "mode <name>" command.
 *
 */
struct Mode {
    char *name;
    bool pango_markup;
    struct bindings_head *bindings;

    SLIST_ENTRY(Mode) modes;
};

/**
 * Holds part of the configuration (the part which is not already in dedicated
 * structures in include/data.h).
 *
 */
struct Config {
    const char *terminal;
    i3Font font;

    char *ipc_socket_path;
    char *restart_state_path;

    layout_t default_layout;
    int container_stack_limit;
    int container_stack_limit_value;
    int default_border_width;
    int default_floating_border_width;

    /** Default orientation for new containers */
    int default_orientation;

    /** By default, focus follows mouse. If the user explicitly wants to
     * turn this off (and instead rely only on the keyboard for changing
     * focus), we allow them to do this with this relatively special option.
     * It is not planned to add any different focus models. */
    bool disable_focus_follows_mouse;

    /** By default, when switching focus to a window on a different output
     * (e.g. focusing a window on workspace 3 on output VGA-1, coming from
     * workspace 2 on LVDS-1), the mouse cursor is warped to the center of
     * that window.
     *
     * With the mouse_warping option, you can control when the mouse cursor
     * should be warped. "none" disables warping entirely, whereas "output"
     * is the default behavior described above. */
    warping_t mouse_warping;

    /** Remove borders if they are adjacent to the screen edge.
     * This is useful if you are reaching scrollbar on the edge of the
     * screen or do not want to waste a single pixel of displayspace.
     * By default, this is disabled. */
    hide_edge_borders_mode_t hide_edge_borders;

    /** By default, a workspace bar is drawn at the bottom of the screen.
     * If you want to have a more fancy bar, it is recommended to replace
     * the whole bar by dzen2, for example using the i3-wsbar script which
     * comes with i3. Thus, you can turn it off entirely. */
    bool disable_workspace_bar;

    /** When focus wrapping is enabled (the default), attempting to
     * move focus past the edge of the screen (in other words, in a
     * direction in which there are no more containers to focus) will
     * cause the focus to wrap to the opposite edge of the current
     * container. When it is disabled, nothing happens; the current
     * focus is preserved.
     *
     * Additionally, focus wrapping may be forced. Think of the
     * following layout: Horizontal workspace with a tabbed con on the
     * left of the screen and a terminal on the right of the
     * screen. You are in the second container in the tabbed container
     * and focus to the right. By default, i3 will set focus to the
     * terminal on the right. If you are in the first container in the
     * tabbed container however, focusing to the left will
     * wrap. Setting focus_wrapping to FOCUS_WRAPPING_FORCE forces i3
     * to always wrap, which will result in you having to use "focus
     * parent" more often. */
    focus_wrapping_t focus_wrapping;

    /** By default, use the RandR API for multi-monitor setups.
     * Unfortunately, the nVidia binary graphics driver doesn't support
     * this API. Instead, it only support the less powerful Xinerama API,
     * which can be enabled by this option.
     *
     * Note: this option takes only effect on the initial startup (eg.
     * reconfiguration is not possible). On startup, the list of screens
     * is fetched once and never updated. */
    bool force_xinerama;

    /** Don't use RandR 1.5 for querying outputs. */
    bool disable_randr15;

    /** Overwrites output detection (for testing), see src/fake_outputs.c */
    char *fake_outputs;

    /** Automatic workspace back and forth switching. If this is set, a
     * switch to the currently active workspace will switch to the
     * previously focused one instead, making it possible to fast toggle
     * between two workspaces. */
    bool workspace_auto_back_and_forth;

    /** By default, urgency is cleared immediately when switching to another
     * workspace leads to focusing the con with the urgency hint. When having
     * multiple windows on that workspace, the user needs to guess which
     * application raised the event. To prevent this, the reset of the urgency
     * flag can be delayed using an urgency timer. */
    float workspace_urgency_timer;

    /** Behavior when a window sends a NET_ACTIVE_WINDOW message. */
    enum {
        /* Focus if the target workspace is visible, set urgency hint otherwise. */
        FOWA_SMART,
        /* Always set the urgency hint. */
        FOWA_URGENT,
        /* Always focus the window. */
        FOWA_FOCUS,
        /* Ignore the request (no focus, no urgency hint). */
        FOWA_NONE
    } focus_on_window_activation;

    /** Specifies whether or not marks should be displayed in the window
     * decoration. Marks starting with a "_" will be ignored either way. */
    bool show_marks;

    /** Title alignment options. */
    enum {
        ALIGN_LEFT,
        ALIGN_CENTER,
        ALIGN_RIGHT
    } title_align;

    /** The default border style for new windows. */
    border_style_t default_border;

    /** The default border style for new floating windows. */
    border_style_t default_floating_border;

    /** The modifier which needs to be pressed in combination with your mouse
     * buttons to do things with floating windows (move, resize) */
    uint32_t floating_modifier;

    /** Maximum and minimum dimensions of a floating window */
    int32_t floating_maximum_width;
    int32_t floating_maximum_height;
    int32_t floating_minimum_width;
    int32_t floating_minimum_height;

    /* Color codes are stored here */
    struct config_client {
        color_t background;
        struct Colortriple focused;
        struct Colortriple focused_inactive;
        struct Colortriple unfocused;
        struct Colortriple urgent;
        struct Colortriple placeholder;
    } client;
    struct config_bar {
        struct Colortriple focused;
        struct Colortriple unfocused;
        struct Colortriple urgent;
    } bar;

    /** What should happen when a new popup is opened during fullscreen mode */
    enum {
        /* display (and focus) the popup when it belongs to the fullscreen
         * window only. */
        PDF_SMART = 0,

        /* leave fullscreen mode unconditionally */
        PDF_LEAVE_FULLSCREEN = 1,

        /* just ignore the popup, that is, don't map it */
        PDF_IGNORE = 2,
    } popup_during_fullscreen;

    /* The number of currently parsed barconfigs */
    int number_barconfigs;
};

/**
 * Holds the status bar configuration (i3bar). One of these structures is
 * created for each 'bar' block in the config.
 *
 */
struct Barconfig {
    /** Automatically generated ID for this bar config. Used by the bar process
     * to request a specific configuration. */
    char *id;

    /** Number of outputs in the outputs array */
    int num_outputs;
    /** Outputs on which this bar should show up on. We use an array for
     * simplicity (since we store just strings). */
    char **outputs;

    /* List of outputs on which the tray is allowed to be shown, in order.
     * The special value "none" disables it (per default, it will be shown) and
     * the special value "primary" enabled it on the primary output. */
    TAILQ_HEAD(tray_outputs_head, tray_output_t) tray_outputs;

    /* Padding around the tray icons. */
    int tray_padding;

    /** Path to the i3 IPC socket. This option is discouraged since programs
     * can find out the path by looking for the I3_SOCKET_PATH property on the
     * root window! */
    char *socket_path;

    /** Bar display mode (hide unless modifier is pressed or show in dock mode or always hide in invisible mode) */
    enum { M_DOCK = 0,
           M_HIDE = 1,
           M_INVISIBLE = 2 } mode;

    /* The current hidden_state of the bar, which indicates whether it is hidden or shown */
    enum { S_HIDE = 0,
           S_SHOW = 1 } hidden_state;

    /** Bar modifier (to show bar when in hide mode). */
    uint32_t modifier;

    TAILQ_HEAD(bar_bindings_head, Barbinding) bar_bindings;

    /** Bar position (bottom by default). */
    enum { P_BOTTOM = 0,
           P_TOP = 1 } position;

    /** Command that should be run to execute i3bar, give a full path if i3bar is not
     * in your $PATH.
     * By default just 'i3bar' is executed. */
    char *i3bar_command;

    /** Command that should be run to get a statusline, for example 'i3status'.
     * Will be passed to the shell. */
    char *status_command;

    /** Font specification for all text rendered on the bar. */
    char *font;

    /** A custom separator to use instead of a vertical line. */
    char *separator_symbol;

    /** Hide workspace buttons? Configuration option is 'workspace_buttons no'
     * but we invert the bool to get the correct default when initializing with
     * zero. */
    bool hide_workspace_buttons;

    /** The minimal width for workspace buttons. */
    int workspace_min_width;

    /** Strip workspace numbers? Configuration option is
     * 'strip_workspace_numbers yes'. */
    bool strip_workspace_numbers;

    /** Strip workspace name? Configuration option is
     * 'strip_workspace_name yes'. */
    bool strip_workspace_name;

    /** Hide mode button? Configuration option is 'binding_mode_indicator no'
     * but we invert the bool for the same reason as hide_workspace_buttons.*/
    bool hide_binding_mode_indicator;

    /** Enable verbose mode? Useful for debugging purposes. */
    bool verbose;

    struct bar_colors {
        char *background;
        char *statusline;
        char *separator;

        char *focused_background;
        char *focused_statusline;
        char *focused_separator;

        char *focused_workspace_border;
        char *focused_workspace_bg;
        char *focused_workspace_text;

        char *active_workspace_border;
        char *active_workspace_bg;
        char *active_workspace_text;

        char *inactive_workspace_border;
        char *inactive_workspace_bg;
        char *inactive_workspace_text;

        char *urgent_workspace_border;
        char *urgent_workspace_bg;
        char *urgent_workspace_text;

        char *binding_mode_border;
        char *binding_mode_bg;
        char *binding_mode_text;
    } colors;

    TAILQ_ENTRY(Barconfig) configs;
};

/**
 * Defines a mouse command to be executed instead of the default behavior when
 * clicking on the non-statusline part of i3bar.
 *
 */
struct Barbinding {
    /** The button to be used (e.g., 1 for "button1"). */
    int input_code;

    /** The command which is to be executed for this button. */
    char *command;

    /** If true, the command will be executed after the button is released. */
    bool release;

    TAILQ_ENTRY(Barbinding) bindings;
};

struct tray_output_t {
    char *output;

    TAILQ_ENTRY(tray_output_t) tray_outputs;
};

typedef enum {
    C_VALIDATE,
    C_LOAD,
    C_RELOAD,
} config_load_t;

/**
 * (Re-)loads the configuration file (sets useful defaults before).
 *
 * If you specify override_configpath, only this path is used to look for a
 * configuration file.
 *
 * load_type specifies the type of loading: C_VALIDATE is used to only verify
 * the correctness of the config file (used with the flag -C). C_LOAD will load
 * the config for normal use and display errors in the nagbar. C_RELOAD will
 * also clear the previous config.
 */
bool load_configuration(const char *override_configfile, config_load_t load_type);

/**
 * Ungrabs all keys, to be called before re-grabbing the keys because of a
 * mapping_notify event or a configuration file reload
 *
 */
void ungrab_all_keys(xcb_connection_t *conn);

redpajama_set_name: RedPajamaGithub


text:
/*************************************************************************/
/*  sample_library_editor_plugin.cpp                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "sample_library_editor_plugin.h"

#include "io/resource_loader.h"
#include "globals.h"
#include "tools/editor/editor_settings.h"
#include "scene/main/viewport.h"
#include "sample_editor_plugin.h"

void SampleLibraryEditor::_input_event(InputEvent p_event) {

}

void SampleLibraryEditor::_notification(int p_what) {

	if (p_what==NOTIFICATION_PROCESS) {
		if (is_playing && !player->is_active()) {
			TreeItem *tl=last_sample_playing->cast_to<TreeItem>();
			tl->set_button(0,0,get_icon("Play","EditorIcons"));
			is_playing = false;
			set_process(false);
		}
	}

	if (p_what==NOTIFICATION_ENTER_TREE) {
		load->set_icon( get_icon("Folder","EditorIcons") );
		load->set_tooltip(TTR("Open Sample File(s)"));
	}

	if (p_what==NOTIFICATION_READY) {

//		NodePath("/root")->connect("node_removed", this,"_node_removed",Vector<Variant>(),true);
	}

	if (p_what==NOTIFICATION_DRAW) {

	}
}

void SampleLibraryEditor::_file_load_request(const DVector<String>& p_path) {

	for(int i=0;i<p_path.size();i++) {

		String path = p_path[i];
		Ref<Sample> sample = ResourceLoader::load(path,"Sample");
		if (sample.is_null()) {
			dialog->set_text(TTR("ERROR: Couldn't load sample!"));
			dialog->set_title(TTR("Error!"));
			//dialog->get_cancel()->set_text(TTR("Close"));
			dialog->get_ok()->set_text(TTR("Close"));
			dialog->popup_centered_minsize();
			return; ///beh should show an error i guess
		}
		String basename = path.get_file().basename();
		String name=basename;
		int counter=0;
		while(sample_library->has_sample(name)) {
			counter++;
			name=basename+"_"+itos(counter);
		}

		undo_redo->create_action(TTR("Add Sample"));
		undo_redo->add_do_method(sample_library.operator->(),"add_sample",name,sample);
		undo_redo->add_undo_method(sample_library.operator->(),"remove_sample",name);
		undo_redo->add_do_method(this,"_update_library");
		undo_redo->add_undo_method(this,"_update_library");
		undo_redo->commit_action();
	}
}

void SampleLibraryEditor::_load_pressed() {

	file->popup_centered_ratio();

}

void SampleLibraryEditor::_button_pressed(Object *p_item,int p_column, int p_id) {

	TreeItem *ti=p_item->cast_to<TreeItem>();
	String name = ti->get_text(0);

	if (p_column==0) { // Play/Stop

		String btn_type;
		if(!is_playing) {
			is_playing = true;
			btn_type = TTR("Stop");
			player->play(name,true);
			last_sample_playing = p_item;
			set_process(true);
		} else {
			player->stop_all();
			if(last_sample_playing != p_item){
				TreeItem *tl=last_sample_playing->cast_to<TreeItem>();
				tl->set_button(p_column,0,get_icon("Play","EditorIcons"));
				btn_type = TTR("Stop");
				player->play(name,true);
				last_sample_playing = p_item;
			} else {
				btn_type = TTR("Play");
				is_playing = false;
			}
		}
		ti->set_button(p_column,0,get_icon(btn_type,"EditorIcons"));
	} else if (p_column==1) { // Edit

		get_tree()->get_root()->get_child(0)->call("_resource_selected",sample_library->get_sample(name));
	} else if (p_column==5) { // Delete

		ti->select(0);
		_delete_pressed();
	}

}

void SampleLibraryEditor::_item_edited() {

	if (!tree->get_selected())
		return;

	TreeItem *s = tree->get_selected();

	if (tree->get_selected_column()==0) { // Name
		// renamed
		String old_name=s->get_metadata(0);
		String new_name=s->get_text(0);
		if (old_name==new_name)
			return;

		if (new_name=="" || new_name.find("\\")!=-1 || new_name.find("/")!=-1 || sample_library->has_sample(new_name)) {

			s->set_text(0,old_name);
			return;
		}

		Ref<Sample> samp = sample_library->get_sample(old_name);
		undo_redo->create_action(TTR("Rename Sample"));
		undo_redo->add_do_method(sample_library.operator->(),"remove_sample",old_name);
		undo_redo->add_do_method(sample_library.operator->(),"add_sample",new_name,samp);
		undo_redo->add_undo_method(sample_library.operator->(),"remove_sample",new_name);
		undo_redo->add_undo_method(sample_library.operator->(),"add_sample",old_name,samp);
		undo_redo->add_do_method(this,"_update_library");
		undo_redo->add_undo_method(this,"_update_library");
		undo_redo->commit_action();

	} else if (tree->get_selected_column()==3) { // Volume dB

		StringName n = s->get_text(0);
		sample_library->sample_set_volume_db(n,s->get_range(3));

	} else if (tree->get_selected_column()==4) { // Pitch scale

		StringName n = s->get_text(0);
		sample_library->sample_set_pitch_scale(n,s->get_range(4));

	}

}

void SampleLibraryEditor::_delete_pressed() {

	if (!tree->get_selected())
		return;

	String to_remove = tree->get_selected()->get_text(0);
	undo_redo->create_action(TTR("Delete Sample"));
	undo_redo->add_do_method(sample_library.operator->(),"remove_sample",to_remove);
	undo_redo->add_undo_method(sample_library.operator->(),"add_sample",to_remove,sample_library->get_sample(to_remove));
	undo_redo->add_do_method(this,"_update_library");
	undo_redo->add_undo_method(this,"_update_library");
	undo_redo->commit_action();
}

void SampleLibraryEditor::_update_library() {

	player->stop_all();

	tree->clear();
	tree->set_hide_root(true);
	TreeItem *root = tree->create_item(NULL);

	List<StringName> names;
	sample_library->get_sample_list(&names);
	names.sort_custom<StringName::AlphCompare>();

	for(List<StringName>::Element *E=names.front();E;E=E->next()) {

		TreeItem *ti = tree->create_item(root);

		// Name + Play/Stop
		ti->set_cell_mode(0,TreeItem::CELL_MODE_STRING);
		ti->set_editable(0,true);
		ti->set_selectable(0,true);
		ti->set_text(0,E->get());
		ti->set_metadata(0,E->get());
		ti->add_button(0,get_icon("Play","EditorIcons"));

		Ref<Sample> smp = sample_library->get_sample(E->get());

		// Preview/edit
		Ref<ImageTexture> preview( memnew( ImageTexture ));
		preview->create(128,16,Image::FORMAT_RGB);
		SampleEditor::generate_preview_texture(smp,preview);
		ti->set_cell_mode(1,TreeItem::CELL_MODE_ICON);
		ti->set_selectable(1,false);
		ti->set_editable(1,false);
		ti->set_icon(1,preview);
		ti->add_button(1,get_icon("Edit","EditorIcons"));

		// Format
		ti->set_cell_mode(2,TreeItem::CELL_MODE_STRING);
		ti->set_editable(2,false);
		ti->set_selectable(2,false);
		ti->set_text(2,String()+/*itos(smp->get_length())+" frames ("+String::num(smp->get_length()/(float)smp->get_mix_rate(),2)+" smp), "+*/(smp->get_format()==Sample::FORMAT_PCM16?"16 Bits, ":(smp->get_format()==Sample::FORMAT_PCM8?"8 bits, ":TTR("IMA-ADPCM,")))+(smp->is_stereo()?"Stereo":"Mono"));

		// Volume dB
		ti->set_cell_mode(3,TreeItem::CELL_MODE_RANGE);
		ti->set_range_config(3,-60,24,0.01);
		ti->set_selectable(3,true);
		ti->set_editable(3,true);
		ti->set_range(3,sample_library->sample_get_volume_db(E->get()));

		// Pitch scale
		ti->set_cell_mode(4,TreeItem::CELL_MODE_RANGE);
		ti->set_range_config(4,0.01,100,0.01);
		ti->set_selectable(4,true);
		ti->set_editable(4,true);
		ti->set_range(4,sample_library->sample_get_pitch_scale(E->get()));

		// Delete
		ti->set_cell_mode(5,TreeItem::CELL_MODE_STRING);
		ti->add_button(5,get_icon("Remove","EditorIcons"));

	}

	//player->add_sample("default",sample);
}

void SampleLibraryEditor::edit(Ref<SampleLibrary> p_sample_library) {

	sample_library=p_sample_library;

	if (!sample_library.is_null()) {
		player->set_sample_library(sample_library);
		_update_library();
	} else {

		hide();
	}

}

Variant SampleLibraryEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {

	TreeItem*ti =tree->get_item_at_pos(p_point);
	if (!ti)
		return Variant();

	String name = ti->get_metadata(0);

	RES res = sample_library->get_sample(name);
	if (!res.is_valid())
		return Variant();

	return EditorNode::get_singleton()->drag_resource(res,p_from);

}

bool SampleLibraryEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const {

	Dictionary d = p_data;

	if (!d.has("type"))
		return false;

	if (d.has("from") && (Object*)(d["from"])==tree)
		return false;

	if (String(d["type"])=="resource" && d.has("resource")) {
		RES r=d["resource"];

		Ref<Sample> sample = r;

		if (sample.is_valid()) {

			return true;
		}
	}

	if (String(d["type"])=="files") {

		Vector<String> files = d["files"];

		if (files.size()==0)
			return false;

		for(int i=0;i<files.size();i++) {
			String file = files[0];
			String ftype = EditorFileSystem::get_singleton()->get_file_type(file);

			if (ftype!="Sample") {
				return false;
			}

		}

		return true;

	}
	return false;
}

void SampleLibraryEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) {

	if (!can_drop_data_fw(p_point,p_data,p_from))
		return;

	Dictionary d = p_data;

	if (!d.has("type"))
		return;

	if (String(d["type"])=="resource" && d.has("resource")) {
		RES r=d["resource"];

		Ref<Sample> sample = r;

		if (sample.is_valid()) {

			String basename;
			if (sample->get_name()!="") {
				basename=sample->get_name();
			} else if (sample->get_path().is_resource_file()) {
				basename = sample->get_path().basename();
			} else {
				basename="Sample";
			}

			String name=basename;
			int counter=0;
			while(sample_library->has_sample(name)) {
				counter++;
				name=basename+"_"+itos(counter);
			}

			undo_redo->create_action(TTR("Add Sample"));
			undo_redo->add_do_method(sample_library.operator->(),"add_sample",name,sample);
			undo_redo->add_undo_method(sample_library.operator->(),"remove_sample",name);
			undo_redo->add_do_method(this,"_update_library");
			undo_redo->add_undo_method(this,"_update_library");
			undo_redo->commit_action();
		}
	}

	if (String(d["type"])=="files") {

		DVector<String> files = d["files"];

		_file_load_request(files);

	}

}

void SampleLibraryEditor::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("_input_event"),&SampleLibraryEditor::_input_event);
	ObjectTypeDB::bind_method(_MD("_load_pressed"),&SampleLibraryEditor::_load_pressed);
	ObjectTypeDB::bind_method(_MD("_item_edited"),&SampleLibraryEditor::_item_edited);
	ObjectTypeDB::bind_method(_MD("_delete_pressed"),&SampleLibraryEditor::_delete_pressed);
	ObjectTypeDB::bind_method(_MD("_file_load_request"),&SampleLibraryEditor::_file_load_request);
	ObjectTypeDB::bind_method(_MD("_update_library"),&SampleLibraryEditor::_update_library);
	ObjectTypeDB::bind_method(_MD("_button_pressed"),&SampleLibraryEditor::_button_pressed);

	ObjectTypeDB::bind_method(_MD("get_drag_data_fw"), &SampleLibraryEditor::get_drag_data_fw);
	ObjectTypeDB::bind_method(_MD("can_drop_data_fw"), &SampleLibraryEditor::can_drop_data_fw);
	ObjectTypeDB::bind_method(_MD("drop_data_fw"), &SampleLibraryEditor::drop_data_fw);

}

SampleLibraryEditor::SampleLibraryEditor() {

	player = memnew(SamplePlayer);
	add_child(player);
	add_style_override("panel", get_stylebox("panel","Panel"));

	load = memnew( Button );
	load->set_pos(Point2( 5, 5 ));
	load->set_size( Size2(1,1 ) );
	add_child(load);

	file = memnew( EditorFileDialog );
	add_child(file);
	List<String> extensions;
	ResourceLoader::get_recognized_extensions_for_type("Sample",&extensions);
	for(int i=0;i<extensions.size();i++)
		file->add_filter("*."+extensions[i]);
	file->set_mode(EditorFileDialog::MODE_OPEN_FILES);

	tree = memnew( Tree );
	tree->set_columns(6);
	add_child(tree);
	tree->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,5);
	tree->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,5);
	tree->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,30);
	tree->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,5);
	tree->set_column_titles_visible(true);
	tree->set_column_title(0,TTR("Name"));
	tree->set_column_title(1,TTR("Preview"));
	tree->set_column_title(2,TTR("Format"));
	tree->set_column_title(3,"dB");
	tree->set_column_title(4,"Pitch");
	tree->set_column_title(5,"");

	tree->set_column_min_width(1,150);
	tree->set_column_min_width(2,100);
	tree->set_column_min_width(3,50);
	tree->set_column_min_width(4,50);
	tree->set_column_min_width(5,32);
	tree->set_column_expand(1,false);
	tree->set_column_expand(2,false);
	tree->set_column_expand(3,false);
	tree->set_column_expand(4,false);
	tree->set_column_expand(5,false);

	tree->set_drag_forwarding(this);

	dialog = memnew( ConfirmationDialog );
	add_child( dialog );

	tree->connect("button_pressed",this,"_button_pressed");
	load->connect("pressed", this,"_load_pressed");
	file->connect("files_selected", this,"_file_load_request");
	tree->connect("item_edited", this,"_item_edited");

}

void SampleLibraryEditorPlugin::edit(Object *p_object) {

	sample_library_editor->set_undo_redo(&get_undo_redo());
	SampleLibrary * s = p_object->cast_to<SampleLibrary>();
	if (!s)
		return;

	sample_library_editor->edit(Ref<SampleLibrary>(s));
}

bool SampleLibraryEditorPlugin::handles(Object *p_object) const {

	return p_object->is_type("SampleLibrary");
}

void SampleLibraryEditorPlugin::make_visible(bool p_visible) {

	if (p_visible) {
		//sample_library_editor->show();
		button->show();
		editor->make_bottom_panel_item_visible(sample_library_editor);
//		sample_library_editor->set_process(true);
	} else {

		if (sample_library_editor->is_visible())
			editor->hide_bottom_panel();
		button->hide();

//		sample_library_editor->set_process(false);
	}

}

SampleLibraryEditorPlugin::SampleLibraryEditorPlugin(EditorNode *p_node) {

	editor=p_node;
	sample_library_editor = memnew( SampleLibraryEditor );

	//editor->get_viewport()->add_child(sample_library_editor);
	sample_library_editor->set_custom_minimum_size(Size2(0,250));
	button=p_node->add_bottom_panel_item("SampleLibrary",sample_library_editor);
	button->hide();

	//sample_library_editor->set_area_as_parent_rect();
//	sample_library_editor->set_anchor( MARGIN_TOP, Control::ANCHOR_END);
//	sample_library_editor->set_margin( MARGIN_TOP, 120 );
	//sample_library_editor->hide();

}

SampleLibraryEditorPlugin::~SampleLibraryEditorPlugin()
{
}


text:
BASE_DIR  = $(CURDIR)/pkg
SRC_DIR   = $(BASE_DIR)/checkout/src/github.com/hashicorp/consul
DISTRO   ?= $(shell lsb_release -sc)
REVISION ?= 1~$(DISTRO)1~ppa1
MODIFIER ?=
CHANGE   ?= "New upstream release."
PBUILDER ?= cowbuilder
PBUILDER_BASE ?= $$HOME/pbuilder/$(DISTRO)-base.cow
PPA      ?=

build: build_src
	mkdir -p $(BASE_DIR)/buildresult
	cd $(BASE_DIR) && sudo $(PBUILDER) --build consul_$(VERSION)-$(REVISION).dsc \
	--basepath=$(PBUILDER_BASE) \
	--buildresult buildresult

build_src: prepare_src
	cd $(PKG_DIR) && debuild -S

prepare_src: $(SRC_DIR) get_current_version create_upstream_tarball
	rsync -qav --delete debian/ $(PKG_DIR)/debian
	$(eval CREATE = $(shell test -f debian/changelog || echo "--create "))
	test $(CURRENT_VERSION)_ != $(VERSION)-$(REVISION)_ && \
	  debchange -c $(PKG_DIR)/debian/changelog $(CREATE)\
        --package consul \
        --newversion $(VERSION)-$(REVISION) \
        --distribution $(DISTRO) \
        --controlmaint \
        $(CHANGE) || exit 0

create_upstream_tarball: get_new_version
	if [ ! -f pkg/consul_$(VERSION).orig.tar.gz ]; then \
	  rm -rf $(PKG_DIR); \
	  rsync -qav --delete $(BASE_DIR)/checkout/ $(PKG_DIR); \
	  export GOPATH=$(PKG_DIR) && make -C $(PKG_DIR)/src/github.com/hashicorp/consul deps; \
	  make -C $(PKG_DIR)/src/github.com/hashicorp/consul/ui dist; \
	  tar czf pkg/consul_$(VERSION).orig.tar.gz -C $(BASE_DIR) consul-$(VERSION); \
	fi

$(SRC_DIR):
	git clone https://github.com/hashicorp/consul.git $(SRC_DIR)

get_current_version:
	$(eval CURRENT_VERSION = $(shell test -f debian/changelog && \
		dpkg-parsechangelog | grep Version | awk '{print $$2}'))
	@echo "--> Current package version: $(CURRENT_VERSION)"

get_new_version:
	cd $(SRC_DIR) && git fetch origin --tags
	$(eval LATEST_TAG = $(shell if [ -z "$(VERSION)" ]; then \
			cd $(SRC_DIR) && git tag | tail -n1; \
		else \
			echo "v$(VERSION)"; \
		fi))
	cd $(SRC_DIR) && git checkout tags/$(LATEST_TAG)
	$(eval VERSION = $(subst v,,$(LATEST_TAG))$(MODIFIER))
	$(eval PKG_DIR = $(BASE_DIR)/consul-$(VERSION))
	@echo "--> New package version: $(VERSION)-$(REVISION)"

clean:
	rm -rf pkg/*

upload: get_new_version
	@if test -z "$(PPA)"; then echo "Usage: make upload PPA=<user>/<ppa>"; exit 1; fi
	dput -f ppa:$(PPA) $(BASE_DIR)/consul_$(VERSION)-$(REVISION)_source.changes
	cp $(BASE_DIR)/consul-$(VERSION)/debian/changelog debian


text:
package main

import (
	ud "github.com/hiromaily/golibs/unixdomainsocket"
)

func main() {
	//server / listener
	server := ud.NewServer()
	err := server.Open()
	if err != nil {
		panic(err)
	}

	// wait shutdown by signal
	close := make(chan error)
	server.WaitShutdown(close)

	// handle request from client
	server.Run()

	//wait from shutdown
	err = <-close
	if err != nil {
		panic(err)
	}
}


text:
#include "TestDevice.h"

#undef UECHO_TEST_VERBOSE

void uecho_test_printrequest(uEchoMessage* msg)
{
  uEchoProperty* prop;
  size_t opc, n;

  opc = uecho_message_getopc(msg);
  printf("%s %2X %2X %04X %06X %06X %02X %ld ",
      uecho_message_getsourceaddress(msg),
      uecho_message_getehd1(msg),
      uecho_message_getehd2(msg),
      uecho_message_gettid(msg),
      uecho_message_getsourceobjectcode(msg),
      uecho_message_getdestinationobjectcode(msg),
      uecho_message_getesv(msg),
      opc);

  for (n = 0; n < opc; n++) {
    prop = uecho_message_getproperty(msg, n);
    printf("%02X(%ld)", uecho_property_getcode(prop), uecho_property_getdatasize(prop));
  }

  printf("\n");
}

void uecho_test_object_messagelitener(uEchoObject* obj, uEchoMessage* msg)
{
#if defined(UECHO_TEST_VERBOSE)
  uecho_test_printrequest(msg);
#endif
}

bool uecho_test_property_requesthandler(uEchoObject* obj, uEchoProperty* prop, uEchoEsv esv, size_t pdc, byte* edt)
{
#if defined(UECHO_TEST_VERBOSE)
  byte status;

  printf("%02X %02X (%d)\n",
      esv,
      uecho_property_getcode(prop),
      pdc);
#endif

  if (pdc != 1)
    return false;

#if defined(UECHO_TEST_VERBOSE)
  status = edt[0];
  switch (status) {
  case UECHO_TEST_PROPERTY_SWITCH_ON:
    printf("POWER = %02X\n", status);
    break;
  case UECHO_TEST_PROPERTY_SWITCH_OFF:
    printf("POWER = %02X\n", status);
    break;
  }
#endif

  return true;
}

uEchoObject* uecho_test_createtestdevice()
{
  uEchoObject* obj = uecho_device_new();

  uecho_object_setmanufacturercode(obj, UECHO_TEST_MANCODE);
  uecho_object_setcode(obj, UECHO_TEST_OBJECTCODE);

  byte prop[32];

  // Operation status property
  uecho_object_setproperty(obj, UECHO_TEST_PROPERTY_SWITCHCODE, uEchoPropertyAttrReadWrite);
  prop[0] = UECHO_TEST_PROPERTY_SWITCH_ON;
  uecho_object_setpropertydata(obj, UECHO_TEST_PROPERTY_SWITCHCODE, prop, 1);

  // Set object listner

  uecho_object_setmessagelistener(obj, uecho_test_object_messagelitener);

  // Set property observer

  uecho_object_setpropertywriterequesthandler(obj, UECHO_TEST_PROPERTY_SWITCHCODE, uecho_test_property_requesthandler);

  return obj;
}

uEchoNode* uecho_test_createtestnode()
{
  uEchoNode* node = uecho_node_new();
  uEchoObject* dev = uecho_test_createtestdevice();
  uecho_node_addobject(node, dev);
  return node;
}


text:
import {Cell, CellState} from './Cell'
import {Field} from './Field'
import {InputHandler} from './Inputhandler'
import {GameSettings, GameSetting} from './GameSetting'

export {Cell, CellState, Field, InputHandler, GameSettings, GameSetting}


text:
:host {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.demo-section + .demo-section {
  margin-top: 16px;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>PureMVC: PureMVC.Interfaces.IView Interface Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Packages

Classes

Files

Class List

Class Hierarchy

Class Members

PureMVC.Interfaces.IView

PureMVC.Interfaces.IView Interface Reference
The interface definition for a PureMVC View.
More...

Inheritance diagram for PureMVC.Interfaces.IView:

<map name="PureMVC.Interfaces.IView_map">
<area href="class_pure_m_v_c_1_1_core_1_1_view.html" alt="PureMVC.Core.View" shape="rect" coords="0,56,163,80">
</map>

List of all members.

Public Member Functions

void 	RegisterObserver (string notificationName, IObserver observer)

void 	RemoveObserver (string notificationName, object notifyContext)

 	Remove a group of observers from the observer list for a given Notification name.

void 	NotifyObservers (INotification note)

 	Notify the IObservers for a particular INotification.

void 	RegisterMediator (IMediator mediator)

IMediator 	RetrieveMediator (string mediatorName)

 	Retrieve an IMediator from the View.

IMediator 	RemoveMediator (string mediatorName)

 	Remove an IMediator from the View.

bool 	HasMediator (string mediatorName)

 	Check if a Mediator is registered or not.

Detailed Description

The interface definition for a PureMVC View.

In PureMVC, IView implementors assume these responsibilities:

Maintain a cache of IMediator instances

Provide methods for registering, retrieving, and removing IMediators

Managing the observer lists for each INotification in the application

Providing a method for attaching IObservers to an INotification's observer list

Providing a method for broadcasting an INotification

Notifying the IObservers of a given INotification when it broadcast

PureMVC.Interfaces.IMediator PureMVC.Interfaces.IObserver PureMVC.Interfaces.INotification

Member Function Documentation

          bool PureMVC.Interfaces.IView.HasMediator
          (
          string
           mediatorName
           )

Check if a Mediator is registered or not.

Parameters:

	mediatorName 	The name of the IMediator instance to check for

Returns:

whether a Mediator is registered with the given mediatorName.

Implemented in PureMVC.Core.View.

          void PureMVC.Interfaces.IView.NotifyObservers
          (
          INotification
           note
           )

Notify the IObservers for a particular INotification.

Parameters:

	note 	The INotification to notify IObservers of

All previously attached IObservers for this INotification's list are notified and are passed a reference to the INotification in the order in which they were registered

Implemented in PureMVC.Core.View.

          void PureMVC.Interfaces.IView.RegisterMediator
          (
          IMediator
           mediator
           )

Register an IMediator instance with the View

Parameters:

	mediator 	A a reference to the IMediator instance

Registers the IMediator so that it can be retrieved by name, and further interrogates the IMediator for its INotification interests

If the IMediator returns any INotification names to be notified about, an Observer is created encapsulating the IMediator instance's handleNotification method and registering it as an Observer for all INotifications the IMediator is interested in

Implemented in PureMVC.Core.View.

          void PureMVC.Interfaces.IView.RegisterObserver
          (
          string
           notificationName,

          IObserver
           observer

          )

Register an IObserver to be notified of INotifications with a given name

Parameters:

	notificationName 	The name of the INotifications to notify this IObserver of

	observer 	The IObserver to register

Implemented in PureMVC.Core.View.

          IMediator PureMVC.Interfaces.IView.RemoveMediator
          (
          string
           mediatorName
           )

Remove an IMediator from the View.

Parameters:

	mediatorName 	The name of the IMediator instance to be removed

Implemented in PureMVC.Core.View.

          void PureMVC.Interfaces.IView.RemoveObserver
          (
          string
           notificationName,

          object
           notifyContext

          )

Remove a group of observers from the observer list for a given Notification name.

Parameters:

	notificationName 	which observer list to remove from

	notifyContext 	removed the observers with this object as their notifyContext

Implemented in PureMVC.Core.View.

          IMediator PureMVC.Interfaces.IView.RetrieveMediator
          (
          string
           mediatorName
           )

Retrieve an IMediator from the View.

Parameters:

	mediatorName 	The name of the IMediator instance to retrieve

Returns:

The IMediator instance previously registered with the given mediatorName

Implemented in PureMVC.Core.View.

The documentation for this interface was generated from the following file:

PureMVC/Interfaces/IView.cs

<address style="text-align: right;">Generated on Tue Jul 6 20:46:36 2010 for PureMVC by

 1.5.8 </address>