<commit_before>/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

// Import
var DrawingObjectsController = AscFormat.DrawingObjectsController;
var HANDLE_EVENT_MODE_HANDLE = AscFormat.HANDLE_EVENT_MODE_HANDLE;
var MOVE_DELTA = AscFormat.MOVE_DELTA;

var History = AscCommon.History;

DrawingObjectsController.prototype.getTheme = function()
{
    return this.drawingObjects.getTheme();
};

DrawingObjectsController.prototype.getDrawingArray = function()
{
    return this.drawingObjects.getDrawingsForController();
};

DrawingObjectsController.prototype.isViewMode = function()
{
    return this.drawingObjects.isViewerMode();
};

DrawingObjectsController.prototype.recalculateCurPos = function(bUpdateX, bUpdateY){
    var oTargetDocContent = this.getTargetDocContent(undefined, true);
    if(oTargetDocContent){
        oTargetDocContent.RecalculateCurPos(bUpdateX, bUpdateY);
        editor.WordControl.m_oLogicDocument.NeedUpdateTargetForCollaboration = true;
    }
};

DrawingObjectsController.prototype.getColorMap = function()
{

    if(this.drawingObjects )
    {
        if(this.drawingObjects.clrMap)
        {
            return this.drawingObjects.clrMap;
        }
        else if(this.drawingObjects.Layout )
        {
            if(this.drawingObjects.Layout.clrMap)
            {
                return this.drawingObjects.Layout.clrMap;
            }
            else if(this.drawingObjects.Layout.Master)
            {
                if(this.drawingObjects.Layout.Master.clrMap)
                {
                    return this.drawingObjects.Layout.Master.clrMap;
                }
            }
        }
        else if(this.drawingObjects.Master )
        {
            if(this.drawingObjects.Master.clrMap)
            {
                return this.drawingObjects.Master.clrMap;
            }
        }
    }
    return AscFormat.G_O_DEFAULT_COLOR_MAP;
};

DrawingObjectsController.prototype.handleOleObjectDoubleClick = function(drawing, oleObject, e, x, y, pageIndex)
{
    var oPresentation = editor && editor.WordControl && editor.WordControl.m_oLogicDocument;
    if(oPresentation && false === editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(AscCommon.changestype_Drawing_Props))
    {
        var pluginData = new Asc.CPluginData();
        pluginData.setAttribute("data", oleObject.m_sData);
        pluginData.setAttribute("guid", oleObject.m_sApplicationId);
        pluginData.setAttribute("width", oleObject.extX);
        pluginData.setAttribute("height", oleObject.extY);
        pluginData.setAttribute("widthPix", oleObject.m_nPixWidth);
        pluginData.setAttribute("heightPix", oleObject.m_nPixHeight);
        pluginData.setAttribute("objectId", oleObject.Id);
        editor.asc_pluginRun(oleObject.m_sApplicationId, 0, pluginData);
    }
    this.clearTrackObjects();
    this.clearPreTrackObjects();
    this.changeCurrentState(new AscFormat.NullState(this));
    oPresentation.OnMouseUp(e, x, y, pageIndex);
};

DrawingObjectsController.prototype.checkSelectedObjectsAndCallback = function(callback, args, bNoSendProps, nHistoryPointType, aAdditionaObjects)
{
    var check_type = AscCommon.changestype_Drawing_Props, comment;
    if(this.drawingObjects.slideComments)
    {
        comment = this.drawingObjects.slideComments.getSelectedComment();
        if(comment)
        {
            check_type = AscCommon.changestype_MoveComment;
            comment = comment.Get_Id();
        }
    }
    if(editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(check_type, comment, undefined, aAdditionaObjects) === false)
    {
        var nPointType = AscFormat.isRealNumber(nHistoryPointType) ? nHistoryPointType : AscDFH.historydescription_CommonControllerCheckSelected;
        History.Create_NewPoint(nPointType);
        callback.apply(this, args);
        this.startRecalculate();
    }
};
DrawingObjectsController.prototype.startRecalculate = function()
{
    editor.WordControl.m_oLogicDocument.Recalculate();
//    editor.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
};

DrawingObjectsController.prototype.getDrawingObjects = function()
{
    return this.drawingObjects.cSld.spTree;
};

DrawingObjectsController.prototype.paragraphFormatPaste = function( CopyTextPr, CopyParaPr, Bool )
{
    var _this = this;
    this.checkSelectedObjectsAndCallback(function()
    {
        this.applyTextFunction(CDocumentContent.prototype.PasteFormatting, CTable.prototype.PasteFormatting, [CopyTextPr, CopyParaPr, Bool]);
    }, [CopyTextPr, CopyParaPr, Bool], false, AscDFH.historydescription_Presentation_ParaFormatPaste);
};

DrawingObjectsController.prototype.paragraphFormatPaste2 = function()
{
    return this.paragraphFormatPaste(editor.WordControl.m_oLogicDocument.CopyTextPr, null, true);
};
DrawingObjectsController.prototype.getDrawingDocument = function()
{
    return editor.WordControl.m_oDrawingDocument;
};

DrawingObjectsController.prototype.onMouseDown = function(e, x, y)
{
    var ret = this.curState.onMouseDown(e, x, y, 0);
    if(e.ClickCount < 2)
    {
        this.updateOverlay();
        this.updateSelectionState();
    }
    return ret;
};

DrawingObjectsController.prototype.OnMouseDown = DrawingObjectsController.prototype.onMouseDown;

DrawingObjectsController.prototype.onMouseMove = function(e, x, y)
{
    this.curState.onMouseMove(e, x, y, 0);
};
DrawingObjectsController.prototype.OnMouseMove = DrawingObjectsController.prototype.onMouseMove;

DrawingObjectsController.prototype.onMouseUp = function(e, x, y)
{
    this.curState.onMouseUp(e, x, y, 0);
};
DrawingObjectsController.prototype.OnMouseUp = DrawingObjectsController.prototype.onMouseUp;

DrawingObjectsController.prototype.convertPixToMM = function(pix)
{
    return editor.WordControl.m_oDrawingDocument.GetMMPerDot(pix);
};

DrawingObjectsController.prototype.resetSelect = function()
{
    this.checkChartTextSelection(true);
    this.resetSelection();
    this.clearPreTrackObjects();
    this.clearTrackObjects();
    this.changeCurrentState(new AscFormat.NullState(this));
};

DrawingObjectsController.prototype.checkSelectedObjectsAndFireCallback = function(callback, args)
{
    var check_type = AscCommon.changestype_Drawing_Props, comment;
    if(this.drawingObjects.slideComments)
    {
        comment = this.drawingObjects.slideComments.getSelectedComment();
        if(comment)
        {
            check_type = AscCommon.changestype_MoveComment;
            comment = comment.Get_Id();
        }
    }
    if(editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(check_type, comment) === false)
    {
        callback.apply(this, args);
        this.startRecalculate();
    }
};

DrawingObjectsController.prototype.showChartSettings  =  function()
{
    editor.asc_doubleClickOnChart(this.getChartObject());
    this.changeCurrentState(new AscFormat.NullState(this));
};
DrawingObjectsController.prototype.getColorMapOverride  =  function()
{
    return this.drawingObjects.Get_ColorMap();
};
DrawingObjectsController.prototype.editChart = function(binary)
{
    var chart_space = this.getChartSpace2(binary, null);
    chart_space.setParent(this.drawingObjects);
    var by_types, i;
    by_types = AscFormat.getObjectsByTypesFromArr(this.selectedObjects, true);
    var aSelectedCharts = [];
    for(i = 0; i < by_types.charts.length; ++i)
    {
        if(by_types.charts[i].selected)
        {
            aSelectedCharts.push(by_types.charts[i]);
        }
    }
    if(aSelectedCharts.length === 1)
    {
        if(aSelectedCharts[0].group)
        {
            var parent_group = aSelectedCharts[0].group;
            var major_group = aSelectedCharts[0].getMainGroup();
            for(i = parent_group.spTree.length -1; i > -1; --i)
            {
                if(parent_group.spTree[i] === aSelectedCharts[0])
                {
                    parent_group.removeFromSpTreeByPos(i);
                    chart_space.setGroup(parent_group);
                    chart_space.spPr.xfrm.setOffX(aSelectedCharts[0].spPr.xfrm.offX);
                    chart_space.spPr.xfrm.setOffY(aSelectedCharts[0].spPr.xfrm.offY);
                    parent_group.addToSpTree(i, chart_space);
                    parent_group.updateCoordinatesAfterInternalResize();
                    major_group.recalculate();
                    if(this.selection.groupSelection)
                    {
                        this.selection.groupSelection.resetSelection();
                        this.selection.groupSelection.selectObject(chart_space, this.drawingObjects.num);
                    }
                    this.startRecalculate();
                    this.sendGraphicObjectProps();
                    return;
                }
            }
        }
        else
        {
            chart_space.spPr.xfrm.setOffX(aSelectedCharts[0].x);
            chart_space.spPr.xfrm.setOffY(aSelectedCharts[0].y);
            var pos = aSelectedCharts[0].deleteDrawingBase();
            chart_space.addToDrawingObjects(pos);
            chart_space.setTitle(binary["cTitle"]);
            chart_space.setDescription(binary["cDescription"]);
            this.resetSelection();
            this.selectObject(chart_space, this.drawingObjects.num);
            this.startRecalculate();
            this.sendGraphicObjectProps();
            this.updateOverlay();
        }
    }
};

DrawingObjectsController.prototype.handleSlideComments  =  function(e, x, y, pageIndex)
{

    if(!this.drawingObjects.slideComments){
        return;
    }
    var comments = this.drawingObjects.slideComments.comments, i, index_selected = -1;
    var ret = {result: null, selectedIndex: -1};
    if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
    {

        editor.asc_hideComments();
        for(i = comments.length - 1; i > -1; --i)
        {
            if(comments[i].selected)
            {
                index_selected = i;
            }
            comments[i].selected = false;
        }
    }

    for(i = comments.length - 1; i > -1; --i)
    {
        if(comments[i].hit(x, y))
        {
            if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
            {
                this.resetSelection();
                comments[i].selected = true;
                this.addPreTrackObject(new AscFormat.MoveComment(comments[i]));
                this.changeCurrentState(new PreMoveCommentState(this, x, y, comments[i]));
                if(i !== index_selected)
                {
                    this.drawingObjects.showDrawingObjects(true);
                }
                ret.result = true;
                ret.selectedIndex = index_selected;
                return ret;
            }
            else
            {
                ret.result = {objectId: comments[i], cursorType: "move"};
                ret.selectedIndex = index_selected;
                return ret;
            }
        }
    }
    if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
    {
        ret.result = false;
        ret.selectedIndex = index_selected;
        if(-1 !== index_selected)
        {
            this.drawingObjects.showDrawingObjects(true);
        }
        return ret;
    }
    else
    {
        ret.result = null;
        ret.selectedIndex = index_selected;
        return ret;
    }

};

function PreMoveCommentState(drawingObjects, startX, startY, comment)
{
    this.drawingObjects = drawingObjects;
    this.startX = startX;
    this.startY = startY;
    this.comment = comment;
}

PreMoveCommentState.prototype =
{
    onMouseDown: function(e, x, y, pageIndex)
    {
        if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
        {
            return true;
        }
        else
        {
            return {objectId: this.comment, cursorType: "move"}
        }
    },

    onMouseMove: function(e, x, y, pageIndex)
    {
        if(Math.abs(this.startX - x) < MOVE_DELTA && Math.abs(this.startY - y) < MOVE_DELTA)
            return;
        this.drawingObjects.swapTrackObjects();
        this.drawingObjects.changeCurrentState(new MoveCommentState(this.drawingObjects, this.startX, this.startY, this.comment));
        this.drawingObjects.onMouseMove(e, x, y);
    },

    onMouseUp: function(e, x, y, pageIndex)
    {
        var Coords = editor.WordControl.m_oDrawingDocument.ConvertCoordsToCursorWR_Comment( this.comment.x, this.comment.y, this.drawingObjects.num);
        editor.sync_HideComment();
        editor.sync_ShowComment(this.comment.Id, Coords.X, Coords.Y );
        editor.WordControl.m_oLogicDocument.noShowContextMenu = true;
        this.drawingObjects.clearPreTrackObjects();
        this.drawingObjects.changeCurrentState(new AscFormat.NullState(this.drawingObjects));
    }
};

function MoveCommentState(drawingObjects, startX, startY, comment)
{
    this.drawingObjects = drawingObjects;
    this.startX = startX;
    this.startY = startY;
    this.comment = comment;
}

MoveCommentState.prototype =
{
    onMouseDown: function(e, x, y, pageIndex)
    {
        if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
        {
            return true;
        }
        else
        {
            return {objectId: this.comment, cursorType: "move"}
        }
    },

    onMouseMove: function(e, x, y, pageIndex)
    {
        var dx = x - this.startX;
        var dy = y - this.startY;
        this.drawingObjects.arrTrackObjects[0].track(dx, dy);
        this.drawingObjects.updateOverlay();
    },

    onMouseUp: function(e, x, y, pageIndex)
    {
        if(editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(AscCommon.changestype_MoveComment, this.comment.Get_Id(), editor.WordControl.m_oLogicDocument.IsEditCommentsMode()) === false)
        {
            History.Create_NewPoint(AscDFH.historydescription_Presentation_MoveComments);
            var tracks = this.drawingObjects.arrTrackObjects;
            for(var i = 0; i < tracks.length; ++i)
            {
                tracks[i].trackEnd();
            }
            this.drawingObjects.startRecalculate();
            this.drawingObjects.drawingObjects.showDrawingObjects();
        }
        this.drawingObjects.clearTrackObjects();
        this.drawingObjects.updateOverlay();
        this.drawingObjects.changeCurrentState(new AscFormat.NullState(this.drawingObjects));

    }
};
<commit_msg>[pe] Fix error<commit_after>/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

// Import
var DrawingObjectsController = AscFormat.DrawingObjectsController;
var HANDLE_EVENT_MODE_HANDLE = AscFormat.HANDLE_EVENT_MODE_HANDLE;
var MOVE_DELTA = AscFormat.MOVE_DELTA;

var History = AscCommon.History;

DrawingObjectsController.prototype.getTheme = function()
{
    return this.drawingObjects.getTheme();
};

DrawingObjectsController.prototype.getDrawingArray = function()
{
    return this.drawingObjects.getDrawingsForController();
};

DrawingObjectsController.prototype.isViewMode = function()
{
    return this.drawingObjects.isViewerMode();
};

DrawingObjectsController.prototype.recalculateCurPos = function(bUpdateX, bUpdateY){
    var oTargetDocContent = this.getTargetDocContent(undefined, true);
    if(oTargetDocContent){
        oTargetDocContent.RecalculateCurPos(bUpdateX, bUpdateY);
        editor.WordControl.m_oLogicDocument.NeedUpdateTargetForCollaboration = true;
    }
};

DrawingObjectsController.prototype.getColorMap = function()
{

    if(this.drawingObjects )
    {
        if(this.drawingObjects.clrMap)
        {
            return this.drawingObjects.clrMap;
        }
        else if(this.drawingObjects.Layout )
        {
            if(this.drawingObjects.Layout.clrMap)
            {
                return this.drawingObjects.Layout.clrMap;
            }
            else if(this.drawingObjects.Layout.Master)
            {
                if(this.drawingObjects.Layout.Master.clrMap)
                {
                    return this.drawingObjects.Layout.Master.clrMap;
                }
            }
        }
        else if(this.drawingObjects.Master )
        {
            if(this.drawingObjects.Master.clrMap)
            {
                return this.drawingObjects.Master.clrMap;
            }
        }
    }
    return AscFormat.G_O_DEFAULT_COLOR_MAP;
};

DrawingObjectsController.prototype.handleOleObjectDoubleClick = function(drawing, oleObject, e, x, y, pageIndex)
{
    var oPresentation = editor && editor.WordControl && editor.WordControl.m_oLogicDocument;
    if(oPresentation && false === editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(AscCommon.changestype_Drawing_Props))
    {
        var pluginData = new Asc.CPluginData();
        pluginData.setAttribute("data", oleObject.m_sData);
        pluginData.setAttribute("guid", oleObject.m_sApplicationId);
        pluginData.setAttribute("width", oleObject.extX);
        pluginData.setAttribute("height", oleObject.extY);
        pluginData.setAttribute("widthPix", oleObject.m_nPixWidth);
        pluginData.setAttribute("heightPix", oleObject.m_nPixHeight);
        pluginData.setAttribute("objectId", oleObject.Id);
        editor.asc_pluginRun(oleObject.m_sApplicationId, 0, pluginData);
    }
    this.clearTrackObjects();
    this.clearPreTrackObjects();
    this.changeCurrentState(new AscFormat.NullState(this));
    oPresentation.OnMouseUp(e, x, y, pageIndex);
};

DrawingObjectsController.prototype.checkSelectedObjectsAndCallback = function(callback, args, bNoSendProps, nHistoryPointType, aAdditionaObjects)
{
    var check_type = AscCommon.changestype_Drawing_Props, comment;
    if(this.drawingObjects.slideComments)
    {
        comment = this.drawingObjects.slideComments.getSelectedComment();
        if(comment)
        {
            check_type = AscCommon.changestype_MoveComment;
            comment = comment.Get_Id();
        }
    }
    if(editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(check_type, comment, undefined, aAdditionaObjects) === false)
    {
        var nPointType = AscFormat.isRealNumber(nHistoryPointType) ? nHistoryPointType : AscDFH.historydescription_CommonControllerCheckSelected;
        History.Create_NewPoint(nPointType);
        callback.apply(this, args);
        this.startRecalculate();
    }
};
DrawingObjectsController.prototype.startRecalculate = function()
{
    editor.WordControl.m_oLogicDocument.Recalculate();
//    editor.WordControl.m_oLogicDocument.Document_UpdateInterfaceState();
};

DrawingObjectsController.prototype.getDrawingObjects = function()
{
    return this.drawingObjects.cSld.spTree;
};

DrawingObjectsController.prototype.paragraphFormatPaste = function( CopyTextPr, CopyParaPr, Bool )
{
    var _this = this;
    this.checkSelectedObjectsAndCallback(function()
    {
        this.applyTextFunction(CDocumentContent.prototype.PasteFormatting, CTable.prototype.PasteFormatting, [CopyTextPr, CopyParaPr, Bool]);
    }, [CopyTextPr, CopyParaPr, Bool], false, AscDFH.historydescription_Presentation_ParaFormatPaste);
};

DrawingObjectsController.prototype.paragraphFormatPaste2 = function()
{
    return this.paragraphFormatPaste(editor.WordControl.m_oLogicDocument.CopyTextPr, null, true);
};
DrawingObjectsController.prototype.getDrawingDocument = function()
{
    return editor.WordControl.m_oDrawingDocument;
};

DrawingObjectsController.prototype.onMouseDown = function(e, x, y)
{
    var ret = this.curState.onMouseDown(e, x, y, 0);
    if(e.ClickCount < 2)
    {
        this.updateOverlay();
        this.updateSelectionState();
    }
    return ret;
};

DrawingObjectsController.prototype.OnMouseDown = DrawingObjectsController.prototype.onMouseDown;

DrawingObjectsController.prototype.onMouseMove = function(e, x, y)
{
    this.curState.onMouseMove(e, x, y, 0);
};
DrawingObjectsController.prototype.OnMouseMove = DrawingObjectsController.prototype.onMouseMove;

DrawingObjectsController.prototype.onMouseUp = function(e, x, y)
{
    this.curState.onMouseUp(e, x, y, 0);
};
DrawingObjectsController.prototype.OnMouseUp = DrawingObjectsController.prototype.onMouseUp;

DrawingObjectsController.prototype.convertPixToMM = function(pix)
{
    return editor.WordControl.m_oDrawingDocument.GetMMPerDot(pix);
};

DrawingObjectsController.prototype.resetSelect = function()
{
    this.checkChartTextSelection(true);
    this.resetSelection();
    this.clearPreTrackObjects();
    this.clearTrackObjects();
    this.changeCurrentState(new AscFormat.NullState(this));
};

DrawingObjectsController.prototype.checkSelectedObjectsAndFireCallback = function(callback, args)
{
    var check_type = AscCommon.changestype_Drawing_Props, comment;
    if(this.drawingObjects.slideComments)
    {
        comment = this.drawingObjects.slideComments.getSelectedComment();
        if(comment)
        {
            check_type = AscCommon.changestype_MoveComment;
            comment = comment.Get_Id();
        }
    }
    if(editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(check_type, comment) === false)
    {
        callback.apply(this, args);
        this.startRecalculate();
    }
};

DrawingObjectsController.prototype.showChartSettings  =  function()
{
    editor.asc_doubleClickOnChart(this.getChartObject());
    this.changeCurrentState(new AscFormat.NullState(this));
};
DrawingObjectsController.prototype.getColorMapOverride  =  function()
{
    return this.drawingObjects.Get_ColorMap();
};
DrawingObjectsController.prototype.editChart = function(binary)
{
    var chart_space = this.getChartSpace2(binary, null);
    chart_space.setParent(this.drawingObjects);
    var by_types, i;
    by_types = AscFormat.getObjectsByTypesFromArr(this.selectedObjects, true);
    var aSelectedCharts = [];
    for(i = 0; i < by_types.charts.length; ++i)
    {
        if(by_types.charts[i].selected)
        {
            aSelectedCharts.push(by_types.charts[i]);
        }
    }
    if(aSelectedCharts.length === 1)
    {
        if(aSelectedCharts[0].group)
        {
            var parent_group = aSelectedCharts[0].group;
            var major_group = aSelectedCharts[0].getMainGroup();
            for(i = parent_group.spTree.length -1; i > -1; --i)
            {
                if(parent_group.spTree[i] === aSelectedCharts[0])
                {
                    parent_group.removeFromSpTreeByPos(i);
                    chart_space.setGroup(parent_group);
                    chart_space.spPr.xfrm.setOffX(aSelectedCharts[0].spPr.xfrm.offX);
                    chart_space.spPr.xfrm.setOffY(aSelectedCharts[0].spPr.xfrm.offY);
                    parent_group.addToSpTree(i, chart_space);
                    parent_group.updateCoordinatesAfterInternalResize();
                    major_group.recalculate();
                    if(this.selection.groupSelection)
                    {
                        this.selection.groupSelection.resetSelection();
                        this.selection.groupSelection.selectObject(chart_space, this.drawingObjects.num);
                    }
                    this.startRecalculate();
                    return;
                }
            }
        }
        else
        {
            chart_space.spPr.xfrm.setOffX(aSelectedCharts[0].x);
            chart_space.spPr.xfrm.setOffY(aSelectedCharts[0].y);
            var pos = aSelectedCharts[0].deleteDrawingBase();
            chart_space.addToDrawingObjects(pos);
            chart_space.setTitle(binary["cTitle"]);
            chart_space.setDescription(binary["cDescription"]);
            this.resetSelection();
            this.selectObject(chart_space, this.drawingObjects.num);
            this.startRecalculate();
            this.updateOverlay();
        }
    }
};

DrawingObjectsController.prototype.handleSlideComments  =  function(e, x, y, pageIndex)
{

    if(!this.drawingObjects.slideComments){
        return;
    }
    var comments = this.drawingObjects.slideComments.comments, i, index_selected = -1;
    var ret = {result: null, selectedIndex: -1};
    if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
    {

        editor.asc_hideComments();
        for(i = comments.length - 1; i > -1; --i)
        {
            if(comments[i].selected)
            {
                index_selected = i;
            }
            comments[i].selected = false;
        }
    }

    for(i = comments.length - 1; i > -1; --i)
    {
        if(comments[i].hit(x, y))
        {
            if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
            {
                this.resetSelection();
                comments[i].selected = true;
                this.addPreTrackObject(new AscFormat.MoveComment(comments[i]));
                this.changeCurrentState(new PreMoveCommentState(this, x, y, comments[i]));
                if(i !== index_selected)
                {
                    this.drawingObjects.showDrawingObjects(true);
                }
                ret.result = true;
                ret.selectedIndex = index_selected;
                return ret;
            }
            else
            {
                ret.result = {objectId: comments[i], cursorType: "move"};
                ret.selectedIndex = index_selected;
                return ret;
            }
        }
    }
    if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
    {
        ret.result = false;
        ret.selectedIndex = index_selected;
        if(-1 !== index_selected)
        {
            this.drawingObjects.showDrawingObjects(true);
        }
        return ret;
    }
    else
    {
        ret.result = null;
        ret.selectedIndex = index_selected;
        return ret;
    }

};

function PreMoveCommentState(drawingObjects, startX, startY, comment)
{
    this.drawingObjects = drawingObjects;
    this.startX = startX;
    this.startY = startY;
    this.comment = comment;
}

PreMoveCommentState.prototype =
{
    onMouseDown: function(e, x, y, pageIndex)
    {
        if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
        {
            return true;
        }
        else
        {
            return {objectId: this.comment, cursorType: "move"}
        }
    },

    onMouseMove: function(e, x, y, pageIndex)
    {
        if(Math.abs(this.startX - x) < MOVE_DELTA && Math.abs(this.startY - y) < MOVE_DELTA)
            return;
        this.drawingObjects.swapTrackObjects();
        this.drawingObjects.changeCurrentState(new MoveCommentState(this.drawingObjects, this.startX, this.startY, this.comment));
        this.drawingObjects.onMouseMove(e, x, y);
    },

    onMouseUp: function(e, x, y, pageIndex)
    {
        var Coords = editor.WordControl.m_oDrawingDocument.ConvertCoordsToCursorWR_Comment( this.comment.x, this.comment.y, this.drawingObjects.num);
        editor.sync_HideComment();
        editor.sync_ShowComment(this.comment.Id, Coords.X, Coords.Y );
        editor.WordControl.m_oLogicDocument.noShowContextMenu = true;
        this.drawingObjects.clearPreTrackObjects();
        this.drawingObjects.changeCurrentState(new AscFormat.NullState(this.drawingObjects));
    }
};

function MoveCommentState(drawingObjects, startX, startY, comment)
{
    this.drawingObjects = drawingObjects;
    this.startX = startX;
    this.startY = startY;
    this.comment = comment;
}

MoveCommentState.prototype =
{
    onMouseDown: function(e, x, y, pageIndex)
    {
        if(this.handleEventMode === HANDLE_EVENT_MODE_HANDLE)
        {
            return true;
        }
        else
        {
            return {objectId: this.comment, cursorType: "move"}
        }
    },

    onMouseMove: function(e, x, y, pageIndex)
    {
        var dx = x - this.startX;
        var dy = y - this.startY;
        this.drawingObjects.arrTrackObjects[0].track(dx, dy);
        this.drawingObjects.updateOverlay();
    },

    onMouseUp: function(e, x, y, pageIndex)
    {
        if(editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(AscCommon.changestype_MoveComment, this.comment.Get_Id(), editor.WordControl.m_oLogicDocument.IsEditCommentsMode()) === false)
        {
            History.Create_NewPoint(AscDFH.historydescription_Presentation_MoveComments);
            var tracks = this.drawingObjects.arrTrackObjects;
            for(var i = 0; i < tracks.length; ++i)
            {
                tracks[i].trackEnd();
            }
            this.drawingObjects.startRecalculate();
            this.drawingObjects.drawingObjects.showDrawingObjects();
        }
        this.drawingObjects.clearTrackObjects();
        this.drawingObjects.updateOverlay();
        this.drawingObjects.changeCurrentState(new AscFormat.NullState(this.drawingObjects));

    }
};
<|endoftext|>


<commit_before>/*! Graphics2D Layers 1.0
 *  Author: Keyten aka Dmitriy Miroshnichenko
 *  License: MIT / LGPL
 */
(function(window, $, undefined){

	$.app = function(query, width, height){
		return new App( document.querySelector(query), width, height );
	}

	function App(container, width, height){
		this.layers = [];
		this.container = container;
		this._width  = width;
		this._height = height;
		this.listeners = {};
	}
	App.prototype = {
		layer : function(index){
			if(index === undefined)
				index = this.layers.length;
			if(!this.layers[index]){ // create a layer
				var canvas = document.createElement('canvas');
				canvas.width  = this._width;
				canvas.height = this._height;

				canvas.style.position = 'absolute';

				canvas.style.zIndex = index; // i hope, it's a number
				this.container.appendChild(canvas);
				return this.layers[index] = new Layer(canvas, this);
			}
			else { // return
				return this.layers[index];
			}
		},

		on : $.Context.prototype.on,

		listener : function(event){
			if(this.listeners[event])
				return;

			this.listeners[event] = [];

			var container = this.container;
			container.addEventListener(event, function(e){
				var coords = $.util.coordsOfElement(this.layers[0].canvas),
					element;

				e.contextX = e.clientX - coords.x;
				e.contextY = e.clientY - coords.y;

				for(var l = this.layers.length-1; l+1; l--){
					if(element = this.layers[l].getObjectInPoint(e.contextX, e.contextY))
						break;
				}

				e.targetObject = element;

				if(element && element.fire)
					element.fire(event, e);

				this.fire(event, e);
			}.bind(this));

			if(event == 'mouseover' || event == 'mouseout')
				this.listenerSpecial('mouseover', 'mouseout', 'hover', 'mousemove'),
				this.listener(event == 'mouseover' ? 'mouseout' : 'mouseover');
			else if(event == 'focus' || event == 'blur')
				this.listenerSpecial('focus', 'blur', 'focus', 'mousedown');

			return this.listeners[event];
		},
		listenerSpecial : $.Context.prototype.listenerSpecial,

		fire : $.Context.prototype.fire,

		width : function(value){
			if(value === undefined)
				return this.layers[0].canvas.width;
			this.layers.forEach(function(layer){
				layer.canvas.width = value;
				layer.update();
			});
			return this;
		},

		height : function(value){
			if(value === undefined)
				return this.layers[0].canvas.height;
			this.layers.forEach(function(layer){
				layer.canvas.height = value;
				layer.update();
			});
			return this;
		},
	};

	var Layer = new $.Class($.Context, {
		initialize : function(canvas, app){
			$.Context.apply(this, arguments);
			this.container = app.container;
			this.app = app;
		},

		listener : function(event){
			return this.app.listener(event);
		},

		listenerSpecial : function(over, out, name, baseevent){
			return this.app.listenerSpecial(over, out, name, baseevent);
		},

		z : function(){
			return Number(this.canvas.style.zIndex);
		},

		isVisible : function(){
			return this.canvas.style.visibility != 'hidden';
		},

		hide : function(){
			this.canvas.style.visibility = 'hidden';
			return this;
		},

		show : function(){
			this.canvas.style.visibility = 'visible';
			return this;
		},

		opacity : function(value){
			if(value === undefined)
				return this.canvas.style.opacity || 1;
			this.canvas.style.opacity = value;
			return this;
		},

		toDataURL : function(type){
			return this.canvas.toDataURL(type);
		}
	});

})(window, Graphics2D);<commit_msg>Layer plugin fixes<commit_after>/*! Graphics2D Layers 1.0
 *  Author: Keyten aka Dmitriy Miroshnichenko
 *  License: MIT / LGPL
 */
(function(window, $, undefined){

	$.app = function(query, width, height){
		return new App( document.querySelector(query), width, height );
	};

	function App(container, width, height){
		this.layers = [];
		this.container = container;
		this._width  = width;
		this._height = height;
		this.listeners = {};
	}
	App.prototype = {
		layer : function(index){
			if(index === undefined)
				index = this.layers.length;
			if(!this.layers[index]){ // create a layer
				var canvas = document.createElement('canvas');
				canvas.width  = this._width;
				canvas.height = this._height;

				canvas.style.position = 'absolute';

				canvas.style.zIndex = index; // i hope, it's a number
				this.container.appendChild(canvas);
				return this.layers[index] = new Layer(canvas, this);
			}
			else { // return
				return this.layers[index];
			}
		},

		on : $.Context.prototype.on,

		listener : function(event){
			if(this.listeners[event])
				return;

			this.listeners[event] = [];

			var container = this.container;
			container.addEventListener(event, function(e){
				var coords = $.util.coordsOfElement(this.layers[0].canvas),
					element;

				e.contextX = e.clientX - coords.x;
				e.contextY = e.clientY - coords.y;

				for(var l = this.layers.length-1; l+1; l--){
					if(element = this.layers[l].getObjectInPoint(e.contextX, e.contextY))
						break;
				}

				e.targetObject = element;

				if(element && element.fire)
					element.fire(event, e);

				this.fire(event, e);
			}.bind(this));

			if(event == 'mouseover' || event == 'mouseout'){
				this.listenerSpecial('mouseover', 'mouseout', 'hover', 'mousemove');
				this.listener(event == 'mouseover' ? 'mouseout' : 'mouseover');
			}
			else if(event == 'focus' || event == 'blur')
				this.listenerSpecial('focus', 'blur', 'focus', 'mousedown');

			return this.listeners[event];
		},
		listenerSpecial : $.Context.prototype.listenerSpecial,

		fire : $.Context.prototype.fire,

		width : function(value){
			if(value === undefined)
				return this.layers[0].canvas.width;
			this.layers.forEach(function(layer){
				layer.canvas.width = value;
				layer.update();
			});
			return this;
		},

		height : function(value){
			if(value === undefined)
				return this.layers[0].canvas.height;
			this.layers.forEach(function(layer){
				layer.canvas.height = value;
				layer.update();
			});
			return this;
		},
	};

	var Layer = new $.Class($.Context, {
		initialize : function(canvas, app){
			$.Context.apply(this, arguments);
			this.container = app.container;
			this.app = app;
		},

		listener : function(event){
			return this.app.listener(event);
		},

		listenerSpecial : function(over, out, name, baseevent){
			return this.app.listenerSpecial(over, out, name, baseevent);
		},

		z : function(){
			return Number(this.canvas.style.zIndex);
		},

		isVisible : function(){
			return this.canvas.style.visibility != 'hidden';
		},

		hide : function(){
			this.canvas.style.visibility = 'hidden';
			return this;
		},

		show : function(){
			this.canvas.style.visibility = 'visible';
			return this;
		},

		opacity : function(value){
			if(value === undefined)
				return this.canvas.style.opacity || 1;
			this.canvas.style.opacity = value;
			return this;
		},

		toDataURL : function(type){
			return this.canvas.toDataURL(type);
		}
	});

})(window, Graphics2D);<|endoftext|>


<commit_before>var BY, BX, T, BDY, BDX;
var Pb, Bot, Pa, Bota;
var PtsA = 0,
  PtsB = 0;

function setup() {
  background(0);
  createCanvas(1080, 720);
  BY = height / 2;
  BX = width / 2;
  BDY = random(-7, 7);
  BDX = 1;
  T = random(1, 10);
  Pb = height / 2 - 15;
  Pa = height / 2 - 15;
  slider = createSlider(0, 20, 3, 0, 3, 6, 10, 15, 20);
  a = createA(href="/pong","Pong");
}

function draw() {
  background(0);
  textSize(20);
  fill(255);
  text("©Javi", width - 55, height - 10);

  //puntos
  textSize(100);
  fill(255);
  text(PtsA, width * 0.25, height / 2);
  text(PtsB, width * 0.75, height / 2);

  //jugadores
  fill(255);
  rect(width - 15, Pa, 15, 60);
  rect(0, Pb, 15, 60);

  //linea centro
  rect(width / 2 - 5, 0, 10, height);

  //pelota
  fill(150, 0, 0);
  ellipse(BX, BY, 50, 50);

  //bot 2
  if (Pa < 0) {
    Pa = 2;
  }

  if (Pa > height - 60) {
    Pa = height - 62;
  }

  if (BX > width / 2) {
    if (Bota == 0) {
      Pa = BY - 30;
    } else {
      if (Pa > BY) {
        Pa = Pa - (T + slider.value());
      }
      if (Pa < BY) {
        Pa = Pa + (T + slider.value());
      }
      if (Pa < BY + 30 && Pa > BY - 30) {
        Bota = 0;
      }
    }
  }
  //bot
  if (Pb < 0) {
    Pb = 2;
  }

  if (Pb > height - 60) {
    Pb = height - 62;
  }

  if (BX < width / 2) {
    if (Bot == 0) {
      Pb = BY - 30;
    } else {
      if (Pb > BY) {
        Pb = Pb - (T + slider.value());
      }
      if (Pb < BY) {
        Pb = Pb + (T + slider.value());
      }
      if (Pb < BY + 30 && Pb > BY - 30) {
        Bot = 0;
      }
    }
  }

  //direccion pelota
  if (BDX == 1) {
    BX = BX - slider.value();
  }
  if (BDX == 2) {
    BX = BX + slider.value();
  }

  //pelota arriba/abajo
  if (slider.value() > 0) {
    BY = BY - BDY;
  }

  //choque
  if (BY < 25 || BY > height - 25) {
    BDY = BDY * -1;
  }
  if (BX > width - 25 && BY < Pa + 60 && BY > Pa) {
    BDX = 1;
    BDY = random(-7, 7);
    T = T - 1;
    Bot = 1;
    Bota = 1;
  }
  if (BX < 25 && BY < Pb + 60 && BY > Pb) {
    BDX = 2;
    T = T - 1;
    BDY = random(-7, 7);
    Bot = 1;
    Bota = 1;
  }

  //reset
  if (BX < 0) {
    PtsB = PtsB + 1;
    BY = height / 2;
    BX = width / 2;
    BDY = random(-7, 7);
    BDX = 2;
    T = random(1, 10);
  }
  if (BX > width) {
    PtsA = PtsA + 1;
    BY = height / 2;
    BX = width / 2;
    BDY = random(-7, 7);
    BDX = 1;
    T = random(1, 10);
  }
}
<commit_msg>Update sketch.js<commit_after>var BY, BX, T, BDY, BDX;
var Pb, Bot, Pa, Bota;
var PtsA = 0,
  PtsB = 0;

function setup() {
  background(0);
  createCanvas(1080, 720);
  BY = height / 2;
  BX = width / 2;
  BDY = random(-7, 7);
  BDX = 1;
  T = random(1, 10);
  Pb = height / 2 - 15;
  Pa = height / 2 - 15;
  slider = createSlider(0, 20, 3, 0, 3, 6, 10, 15, 20);
  a = createA(href = "/PongBot", "Bot");
  a = createA(href = "", " ");
  a.style("color", "white");
  a = createA(href = "/Pong2P", "Pong");
  a.style("color", "purple");
}

function draw() {
  background(0);
  textSize(20);
  fill(255);
  text("©Javi", width - 55, height - 10);

  //puntos
  textSize(100);
  fill(255);
  text(PtsA, width * 0.25, height / 2);
  text(PtsB, width * 0.75, height / 2);

  //jugadores
  fill(255);
  rect(width - 15, Pa, 15, 60);
  rect(0, Pb, 15, 60);

  //linea centro
  rect(width / 2 - 5, 0, 10, height);

  //pelota
  fill(150, 0, 0);
  ellipse(BX, BY, 50, 50);

  //bot 2
  if (Pa < 0) {
    Pa = 2;
  }

  if (Pa > height - 60) {
    Pa = height - 62;
  }

  if (BX > width / 2) {
    if (Bota == 0) {
      Pa = BY - 30;
    } else {
      if (Pa > BY) {
        Pa = Pa - (T + slider.value());
      }
      if (Pa < BY) {
        Pa = Pa + (T + slider.value());
      }
      if (Pa < BY + 30 && Pa > BY - 30) {
        Bota = 0;
      }
    }
  }
  //bot
  if (Pb < 0) {
    Pb = 2;
  }

  if (Pb > height - 60) {
    Pb = height - 62;
  }

  if (BX < width / 2) {
    if (Bot == 0) {
      Pb = BY - 30;
    } else {
      if (Pb > BY) {
        Pb = Pb - (T + slider.value());
      }
      if (Pb < BY) {
        Pb = Pb + (T + slider.value());
      }
      if (Pb < BY + 30 && Pb > BY - 30) {
        Bot = 0;
      }
    }
  }

  //direccion pelota
  if (BDX == 1) {
    BX = BX - slider.value();
  }
  if (BDX == 2) {
    BX = BX + slider.value();
  }

  //pelota arriba/abajo
  if (slider.value() > 0) {
    BY = BY - BDY;
  }

  //choque
  if (BY < 25 || BY > height - 25) {
    BDY = BDY * -1;
  }
  if (BX > width - 25 && BY < Pa + 60 && BY > Pa) {
    BDX = 1;
    BDY = random(-7, 7);
    T = T - 1;
    Bot = 1;
    Bota = 1;
  }
  if (BX < 25 && BY < Pb + 60 && BY > Pb) {
    BDX = 2;
    T = T - 1;
    BDY = random(-7, 7);
    Bot = 1;
    Bota = 1;
  }

  //reset
  if (BX < 0) {
    PtsB = PtsB + 1;
    BY = height / 2;
    BX = width / 2;
    BDY = random(-7, 7);
    BDX = 2;
    T = random(1, 10);
  }
  if (BX > width) {
    PtsA = PtsA + 1;
    BY = height / 2;
    BX = width / 2;
    BDY = random(-7, 7);
    BDX = 1;
    T = random(1, 10);
  }
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.util.concurrent',
  name: 'AbstractAssembly',
  //abstract: true,
  // TODO?: Could provide a reset() method if wanted to make reusable to avoid GC.

  /**
   * Abstract implementation of Assembly interface.
   * Provides concurrency support.
   **/

  implements: [
    'foam.util.concurrent.Assembly'
  ],

  properties: [
    {
      name: 'isCompleted',
      class: 'Boolean',
      synchronized: true,
      value: false,
      documentation: 'True once endJob() has executed.'
    },
    {
      name: 'last',
      class: 'Boolean',
      value: true,
      documentation: 'True if no new Assembly is waiting for this task to complete.'
    },
  ],

  methods: [
    {
      name: 'requestLocks',
      javaCode: `
        // Template method, override in subclass if desired
        return null;
      `
    },
    {
      name: 'executeUnderLock',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'startJob',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'executeJob',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'endJob',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'isLast',
      type: 'boolean',
      synchronized: true,
      javaCode: `
        return getLast();
      `
    },
    {
      name: 'complete',
      synchronized: true,
      javaCode: `
         setIsCompleted(true);
         notify();
      `
    },
    {
      name: 'waitToComplete',
      synchronized: true,
      javaCode: `
         while ( ! getIsCompleted() ) {
           try {
             wait();
           } catch (InterruptedException e) {
             // NOP
           }
         }
      `
    }
  ]

})
<commit_msg>Last set to synchronized<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.util.concurrent',
  name: 'AbstractAssembly',
  //abstract: true,
  // TODO?: Could provide a reset() method if wanted to make reusable to avoid GC.

  /**
   * Abstract implementation of Assembly interface.
   * Provides concurrency support.
   **/

  implements: [
    'foam.util.concurrent.Assembly'
  ],

  properties: [
    {
      name: 'isCompleted',
      class: 'Boolean',
      synchronized: true,
      value: false,
      documentation: 'True once endJob() has executed.'
    },
    {
      name: 'last',
      class: 'Boolean',
      synchronized: true,
      value: true,
      documentation: 'True if no new Assembly is waiting for this task to complete.'
    },
  ],

  methods: [
    {
      name: 'requestLocks',
      javaCode: `
        // Template method, override in subclass if desired
        return null;
      `
    },
    {
      name: 'executeUnderLock',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'startJob',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'executeJob',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'endJob',
      javaCode: `
        // Template method, override in subclass if desired
      `
    },
    {
      name: 'isLast',
      type: 'boolean',
      synchronized: true,
      javaCode: `
        return getLast();
      `
    },
    {
      name: 'complete',
      synchronized: true,
      javaCode: `
         setIsCompleted(true);
         notify();
      `
    },
    {
      name: 'waitToComplete',
      synchronized: true,
      javaCode: `
         while ( ! getIsCompleted() ) {
           try {
             wait();
           } catch (InterruptedException e) {
             // NOP
           }
         }
      `
    }
  ]

})
<|endoftext|>


<commit_before>const blueprintHelper = require('ember-frost-core/blueprint-helper')

module.exports = {
  afterInstall: function (options) {
    const addonsToAdd = [
      {name: 'ember-cli-moment-shim', target: '3.3.3'},
      {name: 'ember-frost-core', target: '1.23.10'},
      {name: 'ember-pikaday-shim', target: '0.1.0'}
    ]

    // Get the packages installed in the consumer app/addon. Packages that are already installed in the consumer within
    // the required semver range will not be re-installed or have blueprints re-run.
    const consumerPackages = blueprintHelper.consumer.getPackages(options)

    // Get the packages to install (not already installed) from a list of potential packages
    return blueprintHelper.packageHandler.getPkgsToInstall(addonsToAdd, consumerPackages).then((pkgsToInstall) => {
      if (pkgsToInstall.length !== 0) {
        // Call the blueprint hook
        return this.addAddonsToProject({
          packages: pkgsToInstall
        })
      }
    }).then(() => {
      return this.addBowerPackagesToProject([
        {name: 'clockpicker-seconds', target: '~0.1.6'}
      ])
    })
  },

  normalizeEntityName: function () {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  }
}
<commit_msg>update blueprint core<commit_after>const blueprintHelper = require('ember-frost-core/blueprint-helper')

module.exports = {
  afterInstall: function (options) {
    const addonsToAdd = [
      {name: 'ember-cli-moment-shim', target: '3.3.3'},
      {name: 'ember-frost-core', target: '^3.0.1'},
      {name: 'ember-pikaday-shim', target: '0.1.0'}
    ]

    // Get the packages installed in the consumer app/addon. Packages that are already installed in the consumer within
    // the required semver range will not be re-installed or have blueprints re-run.
    const consumerPackages = blueprintHelper.consumer.getPackages(options)

    // Get the packages to install (not already installed) from a list of potential packages
    return blueprintHelper.packageHandler.getPkgsToInstall(addonsToAdd, consumerPackages).then((pkgsToInstall) => {
      if (pkgsToInstall.length !== 0) {
        // Call the blueprint hook
        return this.addAddonsToProject({
          packages: pkgsToInstall
        })
      }
    }).then(() => {
      return this.addBowerPackagesToProject([
        {name: 'clockpicker-seconds', target: '~0.1.6'}
      ])
    })
  },

  normalizeEntityName: function () {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  }
}
<|endoftext|>


<commit_before>pc.extend(pc.gfx.shaderChunks, (function () {
    return {
        defaultGamma: pc.gfx.shaderChunks.gamma1_0PS,
        defaultTonemapping: pc.gfx.shaderChunks.tonemappingNonePS,
        defaultSpecular: pc.gfx.shaderChunks.lightSpecularPhongPS,
        defaultFresnel: pc.gfx.shaderChunks.fresnelSimplePS
    };
}()));

<commit_msg>forgot this file<commit_after>pc.extend(pc.gfx.shaderChunks, (function () {
    return {
        defaultGamma: pc.gfx.shaderChunks.gamma1_0PS,
        defaultTonemapping: pc.gfx.shaderChunks.tonemappingNonePS
    };
}()));

<|endoftext|>


<commit_before>/*
 *
 */
var processMarketOfferings = function (offerings, market) {
    'use strict';

    // populate the Trade object
    Trade.details(offerings, market.charAt(0).toUpperCase() + market.substring(1));

    // display markets, submarket, underlyings corresponding to market selected
    displayListElements('contract_market_nav', Trade.markets());
    displayListElements('contract_form_name_nav', Object.keys(Trade.contractForms()));
    displayOptions('submarket',Trade.submarkets());
    displayOptions('underlying', Trade.underlyings());

    // get the underlying selected
    var underlying = document.getElementById('underlying').value;
    sessionStorage.setItem('underlying', underlying);

    // get the contract details based on underlying as market has changed
    TradeSocket.send({ contracts_for: underlying, type: 'contracts_for' });
};

var processContractFormOfferings = function (contracts) {
    'use strict';

    Contract.details(contracts, Trade.form(), Trade.barrier());

    displayDurations('duration_units', Contract.durations(), Trade.form(), Trade.barrier());

    durationPopulate();

    displayStartDates('date_start', Contract.startDates());
    displayBarriers(Contract.barriers(), Trade.form());

    TradeSocket.send({ currencies: 1, type: "currencies" });
};

var processForgetPriceIds = function () {
    var priceIds = document.getElementsByClassName('contract_price_id'), id;
    for (var i = 0, len = priceIds.length; i < len; i++) {
        id = priceIds[i].id;
        TradeSocket.send({ forget: priceIds[i].id });
    }
};

var processPriceRequest = function () {
    processForgetPriceIds();
    for (var typeOfContract in Contract.contractType()[Trade.form()]) {
        if(Contract.contractType()[Trade.form()].hasOwnProperty(typeOfContract)) {
            TradeSocket.send(Price.proposal(typeOfContract));
        }
    }
};
<commit_msg>use price mapping object for forget ids rather than accessing dom<commit_after>/*
 *
 */
var processMarketOfferings = function (offerings, market) {
    'use strict';

    // populate the Trade object
    Trade.details(offerings, market.charAt(0).toUpperCase() + market.substring(1));

    // display markets, submarket, underlyings corresponding to market selected
    displayListElements('contract_market_nav', Trade.markets());
    displayListElements('contract_form_name_nav', Object.keys(Trade.contractForms()));
    displayOptions('submarket',Trade.submarkets());
    displayOptions('underlying', Trade.underlyings());

    // get the underlying selected
    var underlying = document.getElementById('underlying').value;
    sessionStorage.setItem('underlying', underlying);

    // get the contract details based on underlying as market has changed
    TradeSocket.send({ contracts_for: underlying, type: 'contracts_for' });
};

var processContractFormOfferings = function (contracts) {
    'use strict';

    Contract.details(contracts, Trade.form(), Trade.barrier());

    displayDurations('duration_units', Contract.durations(), Trade.form(), Trade.barrier());

    durationPopulate();

    displayStartDates('date_start', Contract.startDates());
    displayBarriers(Contract.barriers(), Trade.form());

    TradeSocket.send({ currencies: 1, type: "currencies" });
};

var processForgetPriceIds = function () {
    var priceIds = Object.keys(Price.idDisplayMapping());
    for (var i = 0, len = priceIds.length; i < len; i++) {
        TradeSocket.send({ forget: priceIds[i] });
    }
};

var processPriceRequest = function () {
    processForgetPriceIds();
    Price.clearMapping();
    for (var typeOfContract in Contract.contractType()[Trade.form()]) {
        if(Contract.contractType()[Trade.form()].hasOwnProperty(typeOfContract)) {
            TradeSocket.send(Price.proposal(typeOfContract));
        }
    }
};
<|endoftext|>


<commit_before>function createPlugin (appName, hotReloadService) {

  function Plugin (window, host) {
    this.window = window;
    this.host = host;
  }
  Plugin.identifier = 'ember-hot-reload';
  Plugin.version = '1.0'; // Just following the example, this might not be even used
  Plugin.prototype.reload = function(path) {
    const cancelableEvent = { modulePath: path, cancel: false};
    hotReloadService.trigger('willLiveReload', cancelableEvent);
    if (cancelableEvent.cancel) {   // Only hotreload if someone canceled the regular reload
      // Reloading app.js will fire Application.create unless we set this.
      // TODO: make sure this doesn't break tests
      window.runningTests = true;
      var tags = document.getElementsByTagName('script');
      for (var i = tags.length; i >= 0; i--){
        if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(appName) !== -1) {
          tags[i].parentNode.removeChild(tags[i]);
        }
      }
      var script = document.createElement('script');
      script.onload = function() {
        setTimeout(function() {
          window.runningTests = false;
          hotReloadService.trigger('willHotReload', path);
        }, 10);
      };
      script.type = 'text/javascript';
      script.src = `/assets/${appName}.js`;
      document.body.appendChild(script);

      return true;
    }
    return false;
  };
  Plugin.prototype.analyze = function() {
    return {
      disable: false
    };
  };

  return Plugin;
}

function lookup (appInstance, fullName) {
  if (appInstance.lookup) {
    return appInstance.lookup(fullName);
  }
  return appInstance.application.__container__.lookup(fullName);
}

function getAppName (appInstance) {
  if (appInstance.base) {
    return appInstance.base.name;
  }
  // TODO: would this work in 2.4+?
  return appInstance.application.name;
}

export function initialize(appInstance) {
  if (!window.LiveReload) {
    return;
  }
  let appName = getAppName(appInstance);
  if (appName === 'ember-cli-hot-loader') {
    // TODO: find a better way to support other addons using the dummy app
    appName = 'dummy';
  }
  const Plugin = createPlugin(appName, lookup(appInstance, 'service:hot-reload'));
  window.LiveReload.addPlugin(Plugin);
}

export default {
  name: 'hot-loader-livereload-plugin',
  initialize
};
<commit_msg>Updates the live reload plugin to use the rootURL if available<commit_after>/* global require */

function createPlugin (appName, hotReloadService, rootURL) {

  function Plugin (window, host) {
    this.window = window;
    this.host = host;
  }
  Plugin.identifier = 'ember-hot-reload';
  Plugin.version = '1.0'; // Just following the example, this might not be even used
  Plugin.prototype.reload = function(path) {
    const cancelableEvent = { modulePath: path, cancel: false};
    hotReloadService.trigger('willLiveReload', cancelableEvent);
    if (cancelableEvent.cancel) {   // Only hotreload if someone canceled the regular reload
      // Reloading app.js will fire Application.create unless we set this.
      // TODO: make sure this doesn't break tests
      window.runningTests = true;
      var tags = document.getElementsByTagName('script');
      for (var i = tags.length; i >= 0; i--){
        if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(appName) !== -1) {
          tags[i].parentNode.removeChild(tags[i]);
        }
      }
      var script = document.createElement('script');
      script.onload = function() {
        setTimeout(function() {
          window.runningTests = false;
          hotReloadService.trigger('willHotReload', path);
        }, 10);
      };
      script.type = 'text/javascript';
      script.src = `${rootURL}assets/${appName}.js`;
      document.body.appendChild(script);

      return true;
    }
    return false;
  };
  Plugin.prototype.analyze = function() {
    return {
      disable: false
    };
  };

  return Plugin;
}

function lookup (appInstance, fullName) {
  if (appInstance.lookup) {
    return appInstance.lookup(fullName);
  }
  return appInstance.application.__container__.lookup(fullName);
}

function getAppName (appInstance) {
  if (appInstance.base) {
    return appInstance.base.name;
  }
  // TODO: would this work in 2.4+?
  return appInstance.application.name;
}

function getRootUrl (appName) {
  let modulePath = `${appName}/config/environment`;
  if (require._eak_seen[modulePath]) {
    return require(modulePath).default.rootURL || '/';
  }
  return '/';
}

export function initialize(appInstance) {
  if (!window.LiveReload) {
    return;
  }
  let appName = getAppName(appInstance);
  if (appName === 'ember-cli-hot-loader') {
    // TODO: find a better way to support other addons using the dummy app
    appName = 'dummy';
  }
  let rootURL = getRootUrl(appName);
  const Plugin = createPlugin(appName, lookup(appInstance, 'service:hot-reload'), rootURL);
  window.LiveReload.addPlugin(Plugin);
}

export default {
  name: 'hot-loader-livereload-plugin',
  initialize
};
<|endoftext|>


<commit_before>import React from 'react'
import { hashHistory } from 'react-router'
import { path } from 'ramda'
import ListItem from 'react-md/lib/Lists/ListItem'
import FontIcon from 'react-md/lib/FontIcons'

const isActive = (url) => {
  const loc = window.location.hash.substr(1)
  if (url.length > 1) {
    return loc.includes(url)
  }

  return url === loc
}

export default (config) => {
  if (!config) return null
  return [
    <ListItem
      key='Dashboard'
      active={isActive('/')}
      onClick={() => hashHistory.push('/')}
      leftIcon={<FontIcon >home</FontIcon >}
      primaryText={'Dashboard'}
    />,

    // Analytics

      {config.analytics &&
      <ListItem
        primaryText={'Analytics'}
        defaultOpen
        leftIcon={<FontIcon >blur_linear</FontIcon >}
        nestedItems={[
          path(['analytics', 'messages', 'enabled'], config) && <ListItem
            key='Messages'
            active={isActive('/messages')}
            onClick={() => hashHistory.push('/messages')}
            leftIcon={<FontIcon >drafts</FontIcon >}
            primaryText={'Messages'}
          />
        ]}
      />}

,

    // Infrastructure

      {config.cluster &&
      <ListItem
        primaryText={'Infrastructure'}
        leftIcon={<FontIcon >developer_board</FontIcon >}
        defaultOpen
        nestedItems={[
          path(['cluster', 'nodes', 'enabled'], config) && <ListItem
            key='Nodes'
            active={isActive('/nodes')}
            onClick={() => hashHistory.push('/nodes')}
            leftIcon={<FontIcon >device_hub</FontIcon >}
            primaryText={'Nodes'}
          />,
          path(['infrastructure', 'services', 'wsdl', 'enabled'], config) && <ListItem
            key='WSDL'
            active={isActive('/wsdl')}
            onClick={() => hashHistory.push('/wsdl')}
            leftIcon={<FontIcon >device_hub</FontIcon >}
            primaryText={'WSDL'}
          />
        ]}
      />}

,

    // Configuration
    <ListItem
      key='Configuration'
      primaryText={'Configuration'}
      leftIcon={<FontIcon >build</FontIcon >}
      defaultOpen
      nestedItems={[
        path(['configuration', 'systemParams', 'enabled'], config) && <ListItem
          key='params'
          active={isActive('/config-params')}
          onClick={() => hashHistory.push('/config-params')}
          leftIcon={<FontIcon >extension</FontIcon >}
          primaryText={'Config Params'}
        />,
        path(['configuration', 'logging', 'enabled'], config) && <ListItem
          key='logging'
          onClick={() => hashHistory.push('/config-logging')}
          active={isActive('/config-logging')}
          leftIcon={<FontIcon >info</FontIcon >}
          primaryText={'Config Logging'}
        />,
        path(['configuration', 'environment', 'enabled'], config) && <ListItem
          key='properties'
          onClick={() => hashHistory.push('/environment-properties')}
          active={isActive('/environment-properties')}
          leftIcon={<FontIcon >filter_hdr</FontIcon >}
          primaryText={'Environment Properties'}
        />,
        path(['configuration', 'alerts', 'enabled'], config) && <ListItem
          key='alerts'
          onClick={() => hashHistory.push('/alerts')}
          active={isActive('/alerts')}
          leftIcon={<FontIcon >notifications_active</FontIcon >}
          primaryText={'Alerts'}
        />,
        path(['configuration', 'errorCodeCatalog', 'enabled'], config) && <ListItem
          key='errors'
          onClick={() => hashHistory.push('/errors-overview')}
          active={isActive('/errors-overview')}
          leftIcon={<FontIcon >bug_report</FontIcon >}
          primaryText={'Errors Overview'}
        />
      ]}
    />,

    { divider: true },

    // External

      {path(['externalLinks', 'enabled'], config) &&
      <ListItem
        primaryText={'External'}
        leftIcon={<FontIcon >link</FontIcon >}
        nestedItems={
          config.externalLinks.items.map(({ title, link, enabled }) => {
            if (!enabled) return null
            return (
              <ListItem
                key={title}
                onClick={() => window.open(link, '_blank')}
                leftIcon={<FontIcon >keyboard_arrow_right</FontIcon >}
                primaryText={title}
              />)
          })
        }
      />}

,

    // Changes

      {path(['changes', 'enabled'], config) && <ListItem
        active={isActive('/changes')}
        onClick={() => hashHistory.push('/changes')}
        leftIcon={<FontIcon >merge_type</FontIcon >}
        primaryText={'Changes'}
      />}

  ]
}
<commit_msg>ERR052 renamed wsdl<commit_after>import React from 'react'
import { hashHistory } from 'react-router'
import { path } from 'ramda'
import ListItem from 'react-md/lib/Lists/ListItem'
import FontIcon from 'react-md/lib/FontIcons'

const isActive = (url) => {
  const loc = window.location.hash.substr(1)
  if (url.length > 1) {
    return loc.includes(url)
  }

  return url === loc
}

export default (config) => {
  if (!config) return null
  return [
    <ListItem
      key='Dashboard'
      active={isActive('/')}
      onClick={() => hashHistory.push('/')}
      leftIcon={<FontIcon >home</FontIcon >}
      primaryText={'Dashboard'}
    />,

    // Analytics

      {config.analytics &&
      <ListItem
        primaryText={'Analytics'}
        defaultOpen
        leftIcon={<FontIcon >blur_linear</FontIcon >}
        nestedItems={[
          path(['analytics', 'messages', 'enabled'], config) && <ListItem
            key='Messages'
            active={isActive('/messages')}
            onClick={() => hashHistory.push('/messages')}
            leftIcon={<FontIcon >drafts</FontIcon >}
            primaryText={'Messages'}
          />
        ]}
      />}

,

    // Infrastructure

      {config.cluster &&
      <ListItem
        primaryText={'Infrastructure'}
        leftIcon={<FontIcon >developer_board</FontIcon >}
        defaultOpen
        nestedItems={[
          path(['cluster', 'nodes', 'enabled'], config) && <ListItem
            key='Nodes'
            active={isActive('/nodes')}
            onClick={() => hashHistory.push('/nodes')}
            leftIcon={<FontIcon >device_hub</FontIcon >}
            primaryText={'Nodes'}
          />,
          path(['infrastructure', 'services', 'wsdl', 'enabled'], config) && <ListItem
            key='WSDL'
            active={isActive('/wsdl')}
            onClick={() => hashHistory.push('/wsdl')}
            leftIcon={<FontIcon >device_hub</FontIcon >}
            primaryText={'Input web services overview'}
          />
        ]}
      />}

,

    // Configuration
    <ListItem
      key='Configuration'
      primaryText={'Configuration'}
      leftIcon={<FontIcon >build</FontIcon >}
      defaultOpen
      nestedItems={[
        path(['configuration', 'systemParams', 'enabled'], config) && <ListItem
          key='params'
          active={isActive('/config-params')}
          onClick={() => hashHistory.push('/config-params')}
          leftIcon={<FontIcon >extension</FontIcon >}
          primaryText={'Config Params'}
        />,
        path(['configuration', 'logging', 'enabled'], config) && <ListItem
          key='logging'
          onClick={() => hashHistory.push('/config-logging')}
          active={isActive('/config-logging')}
          leftIcon={<FontIcon >info</FontIcon >}
          primaryText={'Config Logging'}
        />,
        path(['configuration', 'environment', 'enabled'], config) && <ListItem
          key='properties'
          onClick={() => hashHistory.push('/environment-properties')}
          active={isActive('/environment-properties')}
          leftIcon={<FontIcon >filter_hdr</FontIcon >}
          primaryText={'Environment Properties'}
        />,
        path(['configuration', 'alerts', 'enabled'], config) && <ListItem
          key='alerts'
          onClick={() => hashHistory.push('/alerts')}
          active={isActive('/alerts')}
          leftIcon={<FontIcon >notifications_active</FontIcon >}
          primaryText={'Alerts'}
        />,
        path(['configuration', 'errorCodeCatalog', 'enabled'], config) && <ListItem
          key='errors'
          onClick={() => hashHistory.push('/errors-overview')}
          active={isActive('/errors-overview')}
          leftIcon={<FontIcon >bug_report</FontIcon >}
          primaryText={'Errors Overview'}
        />
      ]}
    />,

    { divider: true },

    // External

      {path(['externalLinks', 'enabled'], config) &&
      <ListItem
        primaryText={'External'}
        leftIcon={<FontIcon >link</FontIcon >}
        nestedItems={
          config.externalLinks.items.map(({ title, link, enabled }) => {
            if (!enabled) return null
            return (
              <ListItem
                key={title}
                onClick={() => window.open(link, '_blank')}
                leftIcon={<FontIcon >keyboard_arrow_right</FontIcon >}
                primaryText={title}
              />)
          })
        }
      />}

,

    // Changes

      {path(['changes', 'enabled'], config) && <ListItem
        active={isActive('/changes')}
        onClick={() => hashHistory.push('/changes')}
        leftIcon={<FontIcon >merge_type</FontIcon >}
        primaryText={'Changes'}
      />}

  ]
}
<|endoftext|>


<commit_before>(function($,$TD){
  //
  // Constant: List of valid font size classes.
  //
  var fontSizeClasses = [ "txt-base-smallest", "txt-base-small", "txt-base-medium", "txt-base-large", "txt-base-largest" ];

  //
  // Variable: Says whether TweetDick events was initialized.
  //
  var isInitialized = false;

  //
  // Variable: Previous font size class in the  tag.
  //
  var prevFontSizeClass;

  //
  // Function: Initializes TweetDick events. Called after the website app is loaded.
  //
  var initializeTweetDick = function(){
    // Settings button hook
    $("[data-action='settings-menu']").click(function(){
      setTimeout(function(){
        var menu = $(".js-dropdown-content").children("ul").first();
        if (menu.length == 0)return;

        menu.children(".drp-h-divider").last().after('
TweetDick

');

        var tweetDickBtn = menu.children("[data-tweetdick]").first();

        tweetDickBtn.on("click","a",function(){
          $TD.openSettingsMenu();
        });

        tweetDickBtn.hover(function(){
          $(this).addClass("is-selected");
        },function(){
          $(this).removeClass("is-selected");
        });
      },0);
    });

    // Tweet notifications
    (function(){
      var columns = $(".js-app-columns").first();

      var refreshColumnObservers = function(){
        columns.children().each(function(){
          registerTweetObserverForColumn($(this));
        });
      };

      new MutationObserver(refreshColumnObservers).observe(columns[0],{
        childList: true
      });

      refreshColumnObservers();
    })();

    isInitialized = true;
  };

  //
  // Function: Registers an observer to a TweetDeck column, which reports new tweets.
  //
  var registerTweetObserverForColumn = function(column){
    if (column[0].hasAttribute("data-tweetdick-observed"))return;

    var mid = column;
    mid = mid.children().first();
    mid = mid.children().first();
    mid = mid.children(".js-column-content").first();
    mid = mid.children(".js-column-scroller").first();

    var container = mid.children(".js-chirp-container").first();
    if (container.length == 0)return;

    new MutationObserver(function(mutations){
      // TODO check if popups are enabled first

      Array.prototype.forEach.call(mutations,function(mutation){
        Array.prototype.forEach.call(mutation.addedNodes,function(node){
          if (node.tagName != "ARTICLE")return;

          onNewTweet(column,node);
        });
      });
    }).observe(container[0],{
      childList: true
    });

    column[0].setAttribute("data-tweetdick-observed","");
  };

  //
  // Function: Event callback for a new tweet.
  //
  var onNewTweet = function(column, tweet){
    var html = $(tweet.outerHTML);
    html.find("footer:first").remove();

    $TD.onTweetPopup(html.html(),""); // TODO
  };

  //
  // Function: Retrieves the font size using  class attribute.
  //
  var getFontSizeClass = function(){
    for(var index = 0; index < fontSizeClasses.length; index++){
      if (document.documentElement.classList.contains(fontSizeClasses[index])){
        return fontSizeClasses[index];
      }
    }

    return fontSizeClasses[0];
  };

  //
  // Function: Retrieves the tags to be put into  for notification HTML code.
  //
  var getNotificationHeadContents = function(){
    var tags = [];

    $(document.head).children("link[rel='stylesheet'],meta[charset],meta[http-equiv]").each(function(){
      tags.push($(this)[0].outerHTML);
    });

    return tags.join("");
  };

  //
  // Block: Observe the app
 element and initialize TweetDick whenever possible.
  //
  var app = $("body").children(".js-app");

  new MutationObserver(function(mutations){
    if (isInitialized && app.hasClass("is-hidden")){
      isInitialized = false;
    }
    else if (!isInitialized && !app.hasClass("is-hidden")){
      initializeTweetDick();
    }
  }).observe(app[0],{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe changes in  class to update font size.
  //
  new MutationObserver(function(mutations){
    var fsClass = getFontSizeClass();

    if (fsClass != prevFontSizeClass){
      prevFontSizeClass = fsClass;
      $TD.loadFontSizeClass(fsClass);
    }
  }).observe(document.documentElement,{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe stylesheet swapping.
  //
  new MutationObserver(function(mutations){
    $TD.loadNotificationHeadContents(getNotificationHeadContents());
  }).observe(document.head.querySelector("[http-equiv='Default-Style']"),{
    attributes: true,
    attributeFilter: [ "content" ]
  });

  $TD.loadNotificationHeadContents(getNotificationHeadContents());
})($,$TD);
<commit_msg>Fix TweetDeck load notification triggers<commit_after>(function($,$TD){
  //
  // Constant: List of valid font size classes.
  //
  var fontSizeClasses = [ "txt-base-smallest", "txt-base-small", "txt-base-medium", "txt-base-large", "txt-base-largest" ];

  //
  // Variable: Says whether TweetDick events was initialized.
  //
  var isInitialized = false;

  //
  // Variable: Previous font size class in the  tag.
  //
  var prevFontSizeClass;

  //
  // Function: Initializes TweetDick events. Called after the website app is loaded.
  //
  var initializeTweetDick = function(){
    // Settings button hook
    $("[data-action='settings-menu']").click(function(){
      setTimeout(function(){
        var menu = $(".js-dropdown-content").children("ul").first();
        if (menu.length == 0)return;

        menu.children(".drp-h-divider").last().after('
TweetDick

');

        var tweetDickBtn = menu.children("[data-tweetdick]").first();

        tweetDickBtn.on("click","a",function(){
          $TD.openSettingsMenu();
        });

        tweetDickBtn.hover(function(){
          $(this).addClass("is-selected");
        },function(){
          $(this).removeClass("is-selected");
        });
      },0);
    });

    // Tweet notifications
    (function(){
      var columns = $(".js-app-columns").first();

      var refreshColumnObservers = function(){
        columns.children().each(function(){
          registerTweetObserverForColumn($(this));
        });
      };

      new MutationObserver(refreshColumnObservers).observe(columns[0],{
        childList: true
      });

      refreshColumnObservers();
    })();

    isInitialized = true;
  };

  //
  // Function: Registers an observer to a TweetDeck column, which reports new tweets.
  //
  var registerTweetObserverForColumn = function(column){
    if (column[0].hasAttribute("data-tweetdick-observed"))return;

    var mid = column;
    mid = mid.children().first();
    mid = mid.children().first();
    mid = mid.children(".js-column-content").first();
    mid = mid.children(".js-column-scroller").first();

    var container = mid.children(".js-chirp-container").first();
    if (container.length == 0)return;

    new MutationObserver(function(mutations){
      if (!container[0].hasAttribute("data-tweetdeck-loaded")){
        container[0].setAttribute("data-tweetdeck-loaded","");
        return;
      }
      // TODO check if popups are enabled first

      Array.prototype.forEach.call(mutations,function(mutation){
        Array.prototype.forEach.call(mutation.addedNodes,function(node){
          if (node.tagName != "ARTICLE")return;

          onNewTweet(column,node);
        });
      });
    }).observe(container[0],{
      childList: true
    });

    column[0].setAttribute("data-tweetdick-observed","");
  };

  //
  // Function: Event callback for a new tweet.
  //
  var onNewTweet = function(column, tweet){
    var html = $(tweet.outerHTML);
    html.find("footer:first").remove();

    $TD.onTweetPopup(html.html(),""); // TODO
  };

  //
  // Function: Retrieves the font size using  class attribute.
  //
  var getFontSizeClass = function(){
    for(var index = 0; index < fontSizeClasses.length; index++){
      if (document.documentElement.classList.contains(fontSizeClasses[index])){
        return fontSizeClasses[index];
      }
    }

    return fontSizeClasses[0];
  };

  //
  // Function: Retrieves the tags to be put into  for notification HTML code.
  //
  var getNotificationHeadContents = function(){
    var tags = [];

    $(document.head).children("link[rel='stylesheet'],meta[charset],meta[http-equiv]").each(function(){
      tags.push($(this)[0].outerHTML);
    });

    return tags.join("");
  };

  //
  // Block: Observe the app
 element and initialize TweetDick whenever possible.
  //
  var app = $("body").children(".js-app");

  new MutationObserver(function(mutations){
    if (isInitialized && app.hasClass("is-hidden")){
      isInitialized = false;
    }
    else if (!isInitialized && !app.hasClass("is-hidden")){
      initializeTweetDick();
    }
  }).observe(app[0],{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe changes in  class to update font size.
  //
  new MutationObserver(function(mutations){
    var fsClass = getFontSizeClass();

    if (fsClass != prevFontSizeClass){
      prevFontSizeClass = fsClass;
      $TD.loadFontSizeClass(fsClass);
    }
  }).observe(document.documentElement,{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe stylesheet swapping.
  //
  new MutationObserver(function(mutations){
    $TD.loadNotificationHeadContents(getNotificationHeadContents());
  }).observe(document.head.querySelector("[http-equiv='Default-Style']"),{
    attributes: true,
    attributeFilter: [ "content" ]
  });

  $TD.loadNotificationHeadContents(getNotificationHeadContents());
})($,$TD);
<|endoftext|>


<commit_before>function loadCreateScreen(parentUrl, collectionId, type, collectionData) {
    var isDataVis = false; // Flag for template to show correct options in select

    // Load data vis creator or ordinary publisher creator
    if (collectionData && collectionData.collectionOwner == "DATA_VISUALISATION") {
        isDataVis = true;
        type = 'visualisation';
    }

    var html = templates.workCreate({"dataVis": isDataVis});

    $('.workspace-menu').html(html);
    loadCreator(parentUrl, collectionId, type, collectionData);
    $('#pagetype').focus();
}
<commit_msg>Fix create screen for visualisation<commit_after>function loadCreateScreen(parentUrl, collectionId, type, collectionData) {
    var isDataVis = type === "visualisation"; // Flag for template to show correct options in select
    var html = templates.workCreate({"dataVis": isDataVis});

    $('.workspace-menu').html(html);
    loadCreator(parentUrl, collectionId, type, collectionData);
    $('#pagetype').focus();
}
<|endoftext|>


<commit_before>var Data = {};

Data.CLUBS = 'clubs';

Data.getUserClubs = function () {
	if (!Ti.App.Properties.hasProperty(Data.CLUBS)){
  	Data.setUserClubs({});
	}
	return JSON.parse(Ti.App.Properties.getString(Data.CLUBS));
};

Data.setUserClubs = function (clubs) {
  Ti.App.Properties.setString(Data.CLUBS, JSON.stringify(clubs));
};

Data.subscribeToClub = function(clubName) {
  var clubs = Data.getUserClubs();
  clubs[clubName] = clubName;
  Data.setUserClubs(clubs);
};

Data.unsubscribeToClub = function(clubname){
  var clubs = Data.getUserClubs();
  delete clubs[clubName];
  Data.setUserClubs(clubs);
};

Data.removeAllClubs = function(){
	Ti.App.Properties.removeProperty(Data.CLUBS);
};
<commit_msg>Fixed typo<commit_after>var Data = {};

Data.CLUBS = 'clubs';

Data.getUserClubs = function () {
	if (!Ti.App.Properties.hasProperty(Data.CLUBS)){
  	Data.setUserClubs({});
	}
	return JSON.parse(Ti.App.Properties.getString(Data.CLUBS));
};

Data.setUserClubs = function (clubs) {
  Ti.App.Properties.setString(Data.CLUBS, JSON.stringify(clubs));
};

Data.subscribeToClub = function(clubName) {
  var clubs = Data.getUserClubs();
  clubs[clubName] = clubName;
  Data.setUserClubs(clubs);
};

Data.unsubscribeToClub = function(clubName){
  var clubs = Data.getUserClubs();
  delete clubs[clubName];
  Data.setUserClubs(clubs);
};

Data.removeAllClubs = function(){
	Ti.App.Properties.removeProperty(Data.CLUBS);
};
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var chrome = chrome || {};
(function () {
  native function GetChromeHidden();
  native function AttachEvent(eventName);
  native function DetachEvent(eventName);

  var chromeHidden = GetChromeHidden();

  // Event object.  If opt_eventName is provided, this object represents
  // the unique instance of that named event, and dispatching an event
  // with that name will route through this object's listeners.
  //
  // Example:
  //   chrome.tabs.onChanged = new chrome.Event("tab-changed");
  //   chrome.tabs.onChanged.addListener(function(data) { alert(data); });
  //   chromeHidden.Event.dispatch("tab-changed", "hi");
  // will result in an alert dialog that says 'hi'.
  chrome.Event = function(opt_eventName, opt_argSchemas) {
    this.eventName_ = opt_eventName;
    this.listeners_ = [];

    // Validate event parameters if we are in debug.
    if (opt_argSchemas &&
        chromeHidden.validateCallbacks &&
        chromeHidden.validate) {

      this.validate_ = function(args) {
        try {
          chromeHidden.validate(args, opt_argSchemas);
        } catch (exception) {
          return "Event validation error during " + opt_eventName + " -- " +
                 exception;
        }
      }
    }
  };

  // A map of event names to the event object that is registered to that name.
  var attachedNamedEvents = {};

  // An array of all attached event objects, used for detaching on unload.
  var allAttachedEvents = [];

  chromeHidden.Event = {};

  // Dispatches a named event with the given JSON array, which is deserialized
  // before dispatch. The JSON array is the list of arguments that will be
  // sent with the event callback.
  chromeHidden.Event.dispatchJSON = function(name, args) {
    if (attachedNamedEvents[name]) {
      if (args) {
        args = JSON.parse(args);
      }
      return attachedNamedEvents[name].dispatch.apply(
          attachedNamedEvents[name], args);
    }
  };

  // Dispatches a named event with the given arguments, supplied as an array.
  chromeHidden.Event.dispatch = function(name, args) {
    if (attachedNamedEvents[name]) {
      attachedNamedEvents[name].dispatch.apply(
          attachedNamedEvents[name], args);
    }
  };

  // Test if a named event has any listeners.
  chromeHidden.Event.hasListener = function(name) {
    return (attachedNamedEvents[name] &&
            attachedNamedEvents[name].listeners_.length > 0);
  }

  // Registers a callback to be called when this event is dispatched.
  chrome.Event.prototype.addListener = function(cb) {
    this.listeners_.push(cb);
    if (this.listeners_.length == 1) {
      this.attach_();
    }
  };

  // Unregisters a callback.
  chrome.Event.prototype.removeListener = function(cb) {
    var idx = this.findListener_(cb);
    if (idx == -1) {
      return;
    }

    this.listeners_.splice(idx, 1);
    if (this.listeners_.length == 0) {
      this.detach_();
    }
  };

  // Test if the given callback is registered for this event.
  chrome.Event.prototype.hasListener = function(cb) {
    return this.findListener_(cb) > -1;
  };

  // Test if any callbacks are registered for this event.
  chrome.Event.prototype.hasListeners = function(cb) {
    return this.listeners_.length > 0;
  };

  // Returns the index of the given callback if registered, or -1 if not
  // found.
  chrome.Event.prototype.findListener_ = function(cb) {
    for (var i = 0; i < this.listeners_.length; i++) {
      if (this.listeners_[i] == cb) {
        return i;
      }
    }

    return -1;
  };

  // Dispatches this event object to all listeners, passing all supplied
  // arguments to this function each listener.
  chrome.Event.prototype.dispatch = function(varargs) {
    var args = Array.prototype.slice.call(arguments);
    if (this.validate_) {
      var validationErrors = this.validate_(args);
      if (validationErrors) {
        return validationErrors;
      }
    }
    for (var i = 0; i < this.listeners_.length; i++) {
      try {
        this.listeners_[i].apply(null, args);
      } catch (e) {
        console.error(e);
      }
    }
  };

  // Attaches this event object to its name.  Only one object can have a given
  // name.
  chrome.Event.prototype.attach_ = function() {
    AttachEvent(this.eventName_);
    allAttachedEvents[allAttachedEvents.length] = this;
    if (!this.eventName_)
      return;

    if (attachedNamedEvents[this.eventName_]) {
      throw new Error("chrome.Event '" + this.eventName_ +
                      "' is already attached.");
    }

    attachedNamedEvents[this.eventName_] = this;
  };

  // Detaches this event object from its name.
  chrome.Event.prototype.detach_ = function() {
    var i = allAttachedEvents.indexOf(this);
    if (i >= 0)
      delete allAttachedEvents[i];
    DetachEvent(this.eventName_);
    if (!this.eventName_)
      return;

    if (!attachedNamedEvents[this.eventName_]) {
      throw new Error("chrome.Event '" + this.eventName_ +
                      "' is not attached.");
    }

    delete attachedNamedEvents[this.eventName_];
  };

  // Special load events: we don't use the DOM unload because that slows
  // down tab shutdown.  On the other hand, onUnload might not always fire,
  // since Chrome will terminate renderers on shutdown (SuddenTermination).
  chromeHidden.onLoad = new chrome.Event();
  chromeHidden.onUnload = new chrome.Event();

  chromeHidden.dispatchOnLoad = function(extensionId) {
    chromeHidden.onLoad.dispatch(extensionId);
  }

  chromeHidden.dispatchOnUnload = function() {
    chromeHidden.onUnload.dispatch();
    for (var i in allAttachedEvents)
      allAttachedEvents[i].detach_();
  }

  chromeHidden.dispatchError = function(msg) {
    console.error(msg);
  }
})();
<commit_msg>For Siggi, from http://codereview.chromium.org/375002/show<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var chrome = chrome || {};
(function () {
  native function GetChromeHidden();
  native function AttachEvent(eventName);
  native function DetachEvent(eventName);

  var chromeHidden = GetChromeHidden();

  // Event object.  If opt_eventName is provided, this object represents
  // the unique instance of that named event, and dispatching an event
  // with that name will route through this object's listeners.
  //
  // Example:
  //   chrome.tabs.onChanged = new chrome.Event("tab-changed");
  //   chrome.tabs.onChanged.addListener(function(data) { alert(data); });
  //   chromeHidden.Event.dispatch("tab-changed", "hi");
  // will result in an alert dialog that says 'hi'.
  chrome.Event = function(opt_eventName, opt_argSchemas) {
    this.eventName_ = opt_eventName;
    this.listeners_ = [];

    // Validate event parameters if we are in debug.
    if (opt_argSchemas &&
        chromeHidden.validateCallbacks &&
        chromeHidden.validate) {

      this.validate_ = function(args) {
        try {
          chromeHidden.validate(args, opt_argSchemas);
        } catch (exception) {
          return "Event validation error during " + opt_eventName + " -- " +
                 exception;
        }
      }
    }
  };

  // A map of event names to the event object that is registered to that name.
  var attachedNamedEvents = {};

  // An array of all attached event objects, used for detaching on unload.
  var allAttachedEvents = [];

  chromeHidden.Event = {};

  // Dispatches a named event with the given JSON array, which is deserialized
  // before dispatch. The JSON array is the list of arguments that will be
  // sent with the event callback.
  chromeHidden.Event.dispatchJSON = function(name, args) {
    if (attachedNamedEvents[name]) {
      if (args) {
        args = JSON.parse(args);
      }
      return attachedNamedEvents[name].dispatch.apply(
          attachedNamedEvents[name], args);
    }
  };

  // Dispatches a named event with the given arguments, supplied as an array.
  chromeHidden.Event.dispatch = function(name, args) {
    if (attachedNamedEvents[name]) {
      attachedNamedEvents[name].dispatch.apply(
          attachedNamedEvents[name], args);
    }
  };

  // Test if a named event has any listeners.
  chromeHidden.Event.hasListener = function(name) {
    return (attachedNamedEvents[name] &&
            attachedNamedEvents[name].listeners_.length > 0);
  }

  // Registers a callback to be called when this event is dispatched.
  chrome.Event.prototype.addListener = function(cb) {
    this.listeners_.push(cb);
    if (this.listeners_.length == 1) {
      this.attach_();
    }
  };

  // Unregisters a callback.
  chrome.Event.prototype.removeListener = function(cb) {
    var idx = this.findListener_(cb);
    if (idx == -1) {
      return;
    }

    this.listeners_.splice(idx, 1);
    if (this.listeners_.length == 0) {
      this.detach_();
    }
  };

  // Test if the given callback is registered for this event.
  chrome.Event.prototype.hasListener = function(cb) {
    return this.findListener_(cb) > -1;
  };

  // Test if any callbacks are registered for this event.
  chrome.Event.prototype.hasListeners = function(cb) {
    return this.listeners_.length > 0;
  };

  // Returns the index of the given callback if registered, or -1 if not
  // found.
  chrome.Event.prototype.findListener_ = function(cb) {
    for (var i = 0; i < this.listeners_.length; i++) {
      if (this.listeners_[i] == cb) {
        return i;
      }
    }

    return -1;
  };

  // Dispatches this event object to all listeners, passing all supplied
  // arguments to this function each listener.
  chrome.Event.prototype.dispatch = function(varargs) {
    var args = Array.prototype.slice.call(arguments);
    if (this.validate_) {
      var validationErrors = this.validate_(args);
      if (validationErrors) {
        return validationErrors;
      }
    }
    for (var i = 0; i < this.listeners_.length; i++) {
      try {
        this.listeners_[i].apply(null, args);
      } catch (e) {
        console.error(e);
      }
    }
  };

  // Attaches this event object to its name.  Only one object can have a given
  // name.
  chrome.Event.prototype.attach_ = function() {
    AttachEvent(this.eventName_);
    allAttachedEvents[allAttachedEvents.length] = this;
    if (!this.eventName_)
      return;

    if (attachedNamedEvents[this.eventName_]) {
      throw new Error("chrome.Event '" + this.eventName_ +
                      "' is already attached.");
    }

    attachedNamedEvents[this.eventName_] = this;
  };

  // Detaches this event object from its name.
  chrome.Event.prototype.detach_ = function() {
    var i = allAttachedEvents.indexOf(this);
    if (i >= 0)
      delete allAttachedEvents[i];
    DetachEvent(this.eventName_);
    if (!this.eventName_)
      return;

    if (!attachedNamedEvents[this.eventName_]) {
      throw new Error("chrome.Event '" + this.eventName_ +
                      "' is not attached.");
    }

    delete attachedNamedEvents[this.eventName_];
  };

  // Special load events: we don't use the DOM unload because that slows
  // down tab shutdown.  On the other hand, onUnload might not always fire,
  // since Chrome will terminate renderers on shutdown (SuddenTermination).
  chromeHidden.onLoad = new chrome.Event();
  chromeHidden.onUnload = new chrome.Event();

  chromeHidden.dispatchOnLoad = function(extensionId) {
    chromeHidden.onLoad.dispatch(extensionId);
  }

  chromeHidden.dispatchOnUnload = function() {
    chromeHidden.onUnload.dispatch();
    for (var i = 0; i < allAttachedEvents.length; ++i) {
      var event = allAttachedEvents[i];
      if (event)
        event.detach_();
    }
  }

  chromeHidden.dispatchError = function(msg) {
    console.error(msg);
  }
})();
<|endoftext|>