<commit_before>/**
 *
 */
Ext.define('OpenEMap.view.Map' ,{
    extend: 'GeoExt.panel.Map',
    border: false,
    anchor: '100% 100%',
    constructor: function(config) {
        this.initDefaultLayers(config.config);

        var printProvider = Ext.create('GeoExt.data.MapfishPrintProvider', {
            url: "/print/pdf",
            autoLoad: true,
            timeout: 60*1000,
            listeners: {
                /*"loadcapabilities": function(printProvider, capabilities) {
                    // NOTE: need to override to test locally...
                    capabilities.createURL = "/print/pdf/create.json";
                },*/
                "encodelayer": function(printProvider, layer, encodedLayer) {
                    if (encodedLayer && encodedLayer.baseURL) {
                        encodedLayer.baseURL = encodedLayer.baseURL.replace('gwc/service/', '');
                    }
                }/*,
                "beforedownload": function(printProvider, url) {
                    console.log("beforedownload");
                }*/
            }
        });

        var printExtent = Ext.create('GeoExt.plugins.PrintExtent', {
            printProvider: printProvider
        });

        this.encode = function(layout) {
            var page = printExtent.addPage();
            if (layout) {
                var record = printProvider.layouts.findRecord('name', layout);
                printProvider.setLayout(record);
            }
            var json = printProvider.encode(printExtent.map, printExtent.pages);
            printExtent.removePage(page);
            return json;
        }

        printProvider.encode = function(map, pages, options) {
            if(map instanceof GeoExt.MapPanel) {
                map = map.map;
            }
            pages = pages instanceof Array ? pages : [pages];
            options = options || {};
            if(this.fireEvent("beforeprint", this, map, pages, options) === false) {
                return;
            }

            var jsonData = Ext.apply({
                units: map.getUnits(),
                srs: map.baseLayer.projection.getCode(),
                layout: this.layout.get("name"),
                dpi: this.dpi.get("value")
            }, this.customParams);

            var pagesLayer = pages[0].feature.layer;
            var encodedLayers = [];

            // ensure that the baseLayer is the first one in the encoded list
            var layers = map.layers.concat();

            Ext.Array.remove(layers, map.baseLayer);
            Ext.Array.insert(layers, 0, [map.baseLayer]);

            Ext.each(layers, function(layer){
                if(layer !== pagesLayer && layer.getVisibility() === true) {
                    var enc = this.encodeLayer(layer);
                    enc && encodedLayers.push(enc);
                }
            }, this);
            jsonData.layers = encodedLayers;

            var encodedPages = [];
            Ext.each(pages, function(page) {

                encodedPages.push(Ext.apply({
                    center: [page.center.lon, page.center.lat],
                    scale: page.scale.get("value"),
                    rotation: page.rotation
                }, page.customParams));
            }, this);
            jsonData.pages = encodedPages;

            if (options.overview) {
                var encodedOverviewLayers = [];
                Ext.each(options.overview.layers, function(layer) {
                    var enc = this.encodeLayer(layer);
                    enc && encodedOverviewLayers.push(enc);
                }, this);
                jsonData.overviewLayers = encodedOverviewLayers;
            }

            if(options.legend && !(this.fireEvent("beforeencodelegend", this, jsonData, options.legend) === false)) {
                var legend = options.legend;
                var rendered = legend.rendered;
                if (!rendered) {
                    legend = legend.cloneConfig({
                        renderTo: document.body,
                        hidden: true
                    });
                }
                var encodedLegends = [];
                legend.items && legend.items.each(function(cmp) {
                    if(!cmp.hidden) {
                        var encFn = this.encoders.legends[cmp.getXType()];
                        // MapFish Print doesn't currently support per-page
                        // legends, so we use the scale of the first page.
                        encodedLegends = encodedLegends.concat(
                            encFn.call(this, cmp, jsonData.pages[0].scale));
                    }
                }, this);
                if (!rendered) {
                    legend.destroy();
                }
                jsonData.legends = encodedLegends;
            }

            return jsonData;
        }

        config.plugins = [printExtent];

        this.callParent(arguments);

        this.layers.add(this.searchLayer);
        this.layers.add(this.drawLayer);
        this.layers.add(this.measureLayer);
        this.layers.add(this.measureLayerSegmentsLayer);

        this.selectControl = new OpenLayers.Control.SelectFeature(this.drawLayer);
        this.map.addControl(this.selectControl);
    },
    unselectAll: function() {
        this.drawLayer.selectedFeatures.forEach(function(feature) {
            this.selectControl.unselect(feature);
        }, this);
    },
    parseStyle: function(style) {
        var template = {
                "Point": {
                    pointRadius: 4,
                    graphicName: "square",
                    fillColor: "#e8ffee",
                    fillOpacity: 0.9,
                    strokeWidth: 1,
                    strokeOpacity: 1,
                    strokeColor: "#29bf4c"
                },
                "Line": {
                    strokeWidth: 3,
                    strokeColor: "#29bf4c",
                    strokeOpacity: 1
                },
                "Polygon": {
                    strokeWidth: 3,
                    strokeOpacity: 1,
                    strokeColor: "#29bf4c",
                    fillColor: "#e8ffee",
                    fillOpacity: 0.9
                }
            };

        var createSymbolizer = function(style) {
            var clone = Ext.clone(template);
            if (style["Point"]) {
                Ext.apply(clone["Point"], style["Point"]);
                Ext.apply(clone["Line"], style["Line"]);
                Ext.apply(clone["Polygon"], style["Polygon"]);
                if (style.labelSegments){
                    Ext.apply(clone["labelSegments"], style["labelSegments"]);
                }
                if (style.labelLength){
                    Ext.apply(clone["labelLength"], style["labelLength"]);
                }
            } else {
                Ext.apply(clone["Point"], style);
                Ext.apply(clone["Line"], style);
                Ext.apply(clone["Polygon"], style);
            }
            return clone;
        };

        var defaultStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: template})]});
        var selectStyle;
        var temporaryStyle;
        var measureStyle;
        if (style) {
            if (style["default"]) {
                defaultStyle = createSymbolizer(style["default"]);
                defaultStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: defaultStyle})]});
            }
            if (style["select"]) {
                selectStyle = createSymbolizer(style["select"]);
                selectStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: selectStyle})]});
            }
            if (style["temporary"]) {
                temporaryStyle = createSymbolizer(style["temporary"]);
                temporaryStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: temporaryStyle})]});
            }
            if (style["labelLength"]){
                measureStyle = createSymbolizer(style);
                measureStyle = new OpenLayers.Style(null, {rules: [new OpenLayers.Rule({symbolizer: measureStyle}) ] });

            }
            if (!style["default"]) {
                defaultStyle = createSymbolizer(style);
                defaultStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: defaultStyle})]});
            }
        }

        var map = {
            "default": defaultStyle
        };
        if (selectStyle) {
            map["select"] = selectStyle;
        }
        if (temporaryStyle) {
            map["temporary"] = temporaryStyle;
        }

        if (measureStyle){
            map["default"] = measureStyle;
        }

        var styleMap = new OpenLayers.StyleMap(map);

        return styleMap;
    },
    initDefaultLayers: function(config) {
        if (!config.drawStyle) {
            config.drawStyle = {
                    "default": {
                        "Point": {
                            pointRadius: 4,
                            graphicName: "square",
                            fillColor: "#ffffff",
                            fillOpacity: 1,
                            strokeWidth: 1,
                            strokeOpacity: 1,
                            strokeColor: "#2969bf"
                        },
                        "Line": {
                            strokeWidth: 3,
                            strokeColor: "#2969bf",
                            strokeOpacity: 1
                        },
                        "Polygon": {
                            strokeWidth: 3,
                            strokeOpacity: 1,
                            strokeColor: "#2969bf",
                            fillOpacity: 0
                        }
                    },
                    "select": {
                        strokeWidth: 3,
                        strokeOpacity: 1,
                        fillColor: "#deecff",
                        fillOpacity: 0.9,
                        strokeColor: "#2969bf"
                    },
                    "temporary": {
                        strokeWidth: 3,
                        strokeOpacity: 0.75,
                        fillColor: "#ff00ff",
                        fillOpacity: 0,
                        strokeColor: "#ff00ff"
                    }
            };
        }

        this.drawLayer = new OpenLayers.Layer.Vector('Drawings', {
            displayInLayerSwitcher: false,
            styleMap: this.parseStyle(config.drawStyle)
        });

        if (config.autoClearDrawLayer) {
            this.drawLayer.events.register('beforefeatureadded', this, function() {
                this.drawLayer.destroyFeatures();
            });
        }

        function onFeatureadded(e) {
            var feature = e.feature;
            this.selectControl.select(feature);
        }

        function onBeforefeaturemodified(e) {
            var feature = e.feature;
            this.selectControl.select(feature);
        }

        function onAfterfeaturemodified(e) {
            var feature = e.feature;
            //this.selectControl.unselect(feature);
        }

        //this.drawLayer.events.register('featureadded', this, onFeatureadded);
        this.drawLayer.events.register('beforefeaturemodified', this, onBeforefeaturemodified);
        this.drawLayer.events.register('afterfeaturemodified', this, onAfterfeaturemodified);

        var searchStyle = {
                "Point": {
                    pointRadius: 4,
                    graphicName: "square",
                    fillColor: "#ffffff",
                    fillOpacity: 1,
                    strokeWidth: 1,
                    strokeOpacity: 1,
                    strokeColor: "#2969bf"
                },
                "Line": {
                    strokeWidth: 3,
                    strokeColor: "#2969bf",
                    strokeOpacity: 1
                },
                "Polygon": {
                    strokeDashstyle: 'dot',
                    strokeWidth: 3,
                    strokeOpacity: 1,
                    strokeColor: "#f58d1e",
                    fillOpacity: 0
                }
        };

        this.searchLayer = new OpenLayers.Layer.Vector('Searchresult', {
            displayInLayerSwitcher: false,
            styleMap: this.parseStyle(searchStyle)
        });

        var measureStyle = {
            "Point": {
                //pointRadius: 4,
                //graphicName: 'square',
                //fillColor: 'white',
                //fillOpacity: 1,
                //strokeWidth: 1,
                //strokeOpacity: 1,
                //strokeColor: '#333333',
                label: '${measure} ${units}',
                fontSize: '12px',
                fontColor: '#800517',
                fontFamily: 'Verdana',
                labelOutlineColor: '#eeeeee',
                labelAlign: 'cm',
                labelOutlineWidth: 2
            },
            "Line": {
                strokeWidth: 3,
                strokeOpacity: 1,
                strokeColor: '#666666',
                strokeDashstyle: 'solid'
            },
            "Polygon": {
                strokeWidth: 2,
                strokeOpacity: 1,
                strokeColor: '#FFFFFF',
                strokeDashstyle: 'solid',
                fillColor: 'white',
                fillOpacity: 0.3
            },
            labelSegments: {
                label: '${measure} ${units}',
                fontSize: '12px',
                fontColor: '#800517',
                fontFamily: 'Verdana',
                labelOutlineColor: '#eeeeee',
                labelAlign: 'cm',
                labelOutlineWidth: 2
            },
            labelLength: {
                label: '${measure} ${units}\n',
                fontSize: '12px',
                fontWeight: 'bold',
                fontColor: '#800517',
                fontFamily: 'Verdana',
                labelOutlineColor: '#eeeeee',
                labelAlign: 'lb',
                labelOutlineWidth: 3
            }
        };

        this.measureLayer = new OpenLayers.Layer.Vector('MeasureLayer',{
        	displayInLayerSwitcher : false,
            styleMap : this.parseStyle(measureStyle)
        });

        this.measureLayerSegmentsLayer = new OpenLayers.Layer.Vector('MeasureLayerSegmentsLayer',{
            displayInLayerSwitcher : false,
            styleMap : this.parseStyle(measureStyle)
        });
    }
});
<commit_msg>Prefer canvas renderer (#79)<commit_after>/**
 *
 */
Ext.define('OpenEMap.view.Map' ,{
    extend: 'GeoExt.panel.Map',
    border: false,
    anchor: '100% 100%',
    constructor: function(config) {
        this.initDefaultLayers(config.config);

        var printProvider = Ext.create('GeoExt.data.MapfishPrintProvider', {
            url: "/print/pdf",
            autoLoad: true,
            timeout: 60*1000,
            listeners: {
                /*"loadcapabilities": function(printProvider, capabilities) {
                    // NOTE: need to override to test locally...
                    capabilities.createURL = "/print/pdf/create.json";
                },*/
                "encodelayer": function(printProvider, layer, encodedLayer) {
                    if (encodedLayer && encodedLayer.baseURL) {
                        encodedLayer.baseURL = encodedLayer.baseURL.replace('gwc/service/', '');
                    }
                }/*,
                "beforedownload": function(printProvider, url) {
                    console.log("beforedownload");
                }*/
            }
        });

        var printExtent = Ext.create('GeoExt.plugins.PrintExtent', {
            printProvider: printProvider
        });

        this.encode = function(layout) {
            var page = printExtent.addPage();
            if (layout) {
                var record = printProvider.layouts.findRecord('name', layout);
                printProvider.setLayout(record);
            }
            var json = printProvider.encode(printExtent.map, printExtent.pages);
            printExtent.removePage(page);
            return json;
        }

        printProvider.encode = function(map, pages, options) {
            if(map instanceof GeoExt.MapPanel) {
                map = map.map;
            }
            pages = pages instanceof Array ? pages : [pages];
            options = options || {};
            if(this.fireEvent("beforeprint", this, map, pages, options) === false) {
                return;
            }

            var jsonData = Ext.apply({
                units: map.getUnits(),
                srs: map.baseLayer.projection.getCode(),
                layout: this.layout.get("name"),
                dpi: this.dpi.get("value")
            }, this.customParams);

            var pagesLayer = pages[0].feature.layer;
            var encodedLayers = [];

            // ensure that the baseLayer is the first one in the encoded list
            var layers = map.layers.concat();

            Ext.Array.remove(layers, map.baseLayer);
            Ext.Array.insert(layers, 0, [map.baseLayer]);

            Ext.each(layers, function(layer){
                if(layer !== pagesLayer && layer.getVisibility() === true) {
                    var enc = this.encodeLayer(layer);
                    enc && encodedLayers.push(enc);
                }
            }, this);
            jsonData.layers = encodedLayers;

            var encodedPages = [];
            Ext.each(pages, function(page) {

                encodedPages.push(Ext.apply({
                    center: [page.center.lon, page.center.lat],
                    scale: page.scale.get("value"),
                    rotation: page.rotation
                }, page.customParams));
            }, this);
            jsonData.pages = encodedPages;

            if (options.overview) {
                var encodedOverviewLayers = [];
                Ext.each(options.overview.layers, function(layer) {
                    var enc = this.encodeLayer(layer);
                    enc && encodedOverviewLayers.push(enc);
                }, this);
                jsonData.overviewLayers = encodedOverviewLayers;
            }

            if(options.legend && !(this.fireEvent("beforeencodelegend", this, jsonData, options.legend) === false)) {
                var legend = options.legend;
                var rendered = legend.rendered;
                if (!rendered) {
                    legend = legend.cloneConfig({
                        renderTo: document.body,
                        hidden: true
                    });
                }
                var encodedLegends = [];
                legend.items && legend.items.each(function(cmp) {
                    if(!cmp.hidden) {
                        var encFn = this.encoders.legends[cmp.getXType()];
                        // MapFish Print doesn't currently support per-page
                        // legends, so we use the scale of the first page.
                        encodedLegends = encodedLegends.concat(
                            encFn.call(this, cmp, jsonData.pages[0].scale));
                    }
                }, this);
                if (!rendered) {
                    legend.destroy();
                }
                jsonData.legends = encodedLegends;
            }

            return jsonData;
        }

        config.plugins = [printExtent];

        this.callParent(arguments);

        this.layers.add(this.searchLayer);
        this.layers.add(this.drawLayer);
        this.layers.add(this.measureLayer);
        this.layers.add(this.measureLayerSegmentsLayer);

        this.selectControl = new OpenLayers.Control.SelectFeature(this.drawLayer);
        this.map.addControl(this.selectControl);
    },
    unselectAll: function() {
        this.drawLayer.selectedFeatures.forEach(function(feature) {
            this.selectControl.unselect(feature);
        }, this);
    },
    parseStyle: function(style) {
        var template = {
                "Point": {
                    pointRadius: 4,
                    graphicName: "square",
                    fillColor: "#e8ffee",
                    fillOpacity: 0.9,
                    strokeWidth: 1,
                    strokeOpacity: 1,
                    strokeColor: "#29bf4c"
                },
                "Line": {
                    strokeWidth: 3,
                    strokeColor: "#29bf4c",
                    strokeOpacity: 1
                },
                "Polygon": {
                    strokeWidth: 3,
                    strokeOpacity: 1,
                    strokeColor: "#29bf4c",
                    fillColor: "#e8ffee",
                    fillOpacity: 0.9
                }
            };

        var createSymbolizer = function(style) {
            var clone = Ext.clone(template);
            if (style["Point"]) {
                Ext.apply(clone["Point"], style["Point"]);
                Ext.apply(clone["Line"], style["Line"]);
                Ext.apply(clone["Polygon"], style["Polygon"]);
                if (style.labelSegments){
                    Ext.apply(clone["labelSegments"], style["labelSegments"]);
                }
                if (style.labelLength){
                    Ext.apply(clone["labelLength"], style["labelLength"]);
                }
            } else {
                Ext.apply(clone["Point"], style);
                Ext.apply(clone["Line"], style);
                Ext.apply(clone["Polygon"], style);
            }
            return clone;
        };

        var defaultStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: template})]});
        var selectStyle;
        var temporaryStyle;
        var measureStyle;
        if (style) {
            if (style["default"]) {
                defaultStyle = createSymbolizer(style["default"]);
                defaultStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: defaultStyle})]});
            }
            if (style["select"]) {
                selectStyle = createSymbolizer(style["select"]);
                selectStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: selectStyle})]});
            }
            if (style["temporary"]) {
                temporaryStyle = createSymbolizer(style["temporary"]);
                temporaryStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: temporaryStyle})]});
            }
            if (style["labelLength"]){
                measureStyle = createSymbolizer(style);
                measureStyle = new OpenLayers.Style(null, {rules: [new OpenLayers.Rule({symbolizer: measureStyle}) ] });

            }
            if (!style["default"]) {
                defaultStyle = createSymbolizer(style);
                defaultStyle = new OpenLayers.Style(null, {rules: [ new OpenLayers.Rule({symbolizer: defaultStyle})]});
            }
        }

        var map = {
            "default": defaultStyle
        };
        if (selectStyle) {
            map["select"] = selectStyle;
        }
        if (temporaryStyle) {
            map["temporary"] = temporaryStyle;
        }

        if (measureStyle){
            map["default"] = measureStyle;
        }

        var styleMap = new OpenLayers.StyleMap(map);

        return styleMap;
    },
    initDefaultLayers: function(config) {
        if (!config.drawStyle) {
            config.drawStyle = {
                    "default": {
                        "Point": {
                            pointRadius: 4,
                            graphicName: "square",
                            fillColor: "#ffffff",
                            fillOpacity: 1,
                            strokeWidth: 1,
                            strokeOpacity: 1,
                            strokeColor: "#2969bf"
                        },
                        "Line": {
                            strokeWidth: 3,
                            strokeColor: "#2969bf",
                            strokeOpacity: 1
                        },
                        "Polygon": {
                            strokeWidth: 3,
                            strokeOpacity: 1,
                            strokeColor: "#2969bf",
                            fillOpacity: 0
                        }
                    },
                    "select": {
                        strokeWidth: 3,
                        strokeOpacity: 1,
                        fillColor: "#deecff",
                        fillOpacity: 0.9,
                        strokeColor: "#2969bf"
                    },
                    "temporary": {
                        strokeWidth: 3,
                        strokeOpacity: 0.75,
                        fillColor: "#ff00ff",
                        fillOpacity: 0,
                        strokeColor: "#ff00ff"
                    }
            };
        }

        this.drawLayer = new OpenLayers.Layer.Vector('Drawings', {
            displayInLayerSwitcher: false,
            styleMap: this.parseStyle(config.drawStyle),
            renderers: ["Canvas", "SVG", "VML"]
        });

        if (config.autoClearDrawLayer) {
            this.drawLayer.events.register('beforefeatureadded', this, function() {
                this.drawLayer.destroyFeatures();
            });
        }

        function onFeatureadded(e) {
            var feature = e.feature;
            this.selectControl.select(feature);
        }

        function onBeforefeaturemodified(e) {
            var feature = e.feature;
            this.selectControl.select(feature);
        }

        function onAfterfeaturemodified(e) {
            var feature = e.feature;
            //this.selectControl.unselect(feature);
        }

        //this.drawLayer.events.register('featureadded', this, onFeatureadded);
        this.drawLayer.events.register('beforefeaturemodified', this, onBeforefeaturemodified);
        this.drawLayer.events.register('afterfeaturemodified', this, onAfterfeaturemodified);

        var searchStyle = {
                "Point": {
                    pointRadius: 4,
                    graphicName: "square",
                    fillColor: "#ffffff",
                    fillOpacity: 1,
                    strokeWidth: 1,
                    strokeOpacity: 1,
                    strokeColor: "#2969bf"
                },
                "Line": {
                    strokeWidth: 3,
                    strokeColor: "#2969bf",
                    strokeOpacity: 1
                },
                "Polygon": {
                    strokeDashstyle: 'dot',
                    strokeWidth: 3,
                    strokeOpacity: 1,
                    strokeColor: "#f58d1e",
                    fillOpacity: 0
                }
        };

        this.searchLayer = new OpenLayers.Layer.Vector('Searchresult', {
            displayInLayerSwitcher: false,
            styleMap: this.parseStyle(searchStyle),
            renderers: ["Canvas", "SVG", "VML"]
        });

        var measureStyle = {
            "Point": {
                //pointRadius: 4,
                //graphicName: 'square',
                //fillColor: 'white',
                //fillOpacity: 1,
                //strokeWidth: 1,
                //strokeOpacity: 1,
                //strokeColor: '#333333',
                label: '${measure} ${units}',
                fontSize: '12px',
                fontColor: '#800517',
                fontFamily: 'Verdana',
                labelOutlineColor: '#eeeeee',
                labelAlign: 'cm',
                labelOutlineWidth: 2
            },
            "Line": {
                strokeWidth: 3,
                strokeOpacity: 1,
                strokeColor: '#666666',
                strokeDashstyle: 'solid'
            },
            "Polygon": {
                strokeWidth: 2,
                strokeOpacity: 1,
                strokeColor: '#FFFFFF',
                strokeDashstyle: 'solid',
                fillColor: 'white',
                fillOpacity: 0.3
            },
            labelSegments: {
                label: '${measure} ${units}',
                fontSize: '12px',
                fontColor: '#800517',
                fontFamily: 'Verdana',
                labelOutlineColor: '#eeeeee',
                labelAlign: 'cm',
                labelOutlineWidth: 2
            },
            labelLength: {
                label: '${measure} ${units}\n',
                fontSize: '12px',
                fontWeight: 'bold',
                fontColor: '#800517',
                fontFamily: 'Verdana',
                labelOutlineColor: '#eeeeee',
                labelAlign: 'lb',
                labelOutlineWidth: 3
            }
        };

        this.measureLayer = new OpenLayers.Layer.Vector('MeasureLayer',{
        	displayInLayerSwitcher : false,
            styleMap : this.parseStyle(measureStyle),
            renderers: ["Canvas", "SVG", "VML"]
        });

        this.measureLayerSegmentsLayer = new OpenLayers.Layer.Vector('MeasureLayerSegmentsLayer',{
            displayInLayerSwitcher : false,
            styleMap : this.parseStyle(measureStyle)
        });
    }
});
<|endoftext|>


<commit_before>TileMill = {};
TileMill.addLayer = function(options) {
  var layerName = '';
  if (options.id) {
    layerName = '#' + options.id + ' ';
  }
  if (options.classes.length) {
    layerName += '.' + options.classes.join(', .');
  }
  var checkbox = $('<input class="checkbox" type="checkbox" />');
  var li = $('
')
    .append($('

'))
    .append(checkbox)
    .append($('Inspect').click(function() {
      $('#layers').hide();
      $('#inspector').show();
      return false;
    }))
    .append($('Edit').click(function() {
      var options = $(this).parents('li').data('tilemill');
      if ($('#popup-layer').is(':hidden')) {
        $('#popup, #popup-layer, #popup-backdrop, #popup-header').show();
        $('#popup-layer input:not(.submit)').val('');
        $('#popup-layer input.submit').val('Save').data('li', $(this).parents('li'));
        $('#popup-layer input#classes').val(options.classes.join(' '));
        $('#popup-layer input#id').val(options.id);
        $('#popup-layer input#srs').val(options.srs);
        $('#popup-layer input#dataSource').val(options.dataSource);
        $('#popup-header h2').text('Edit layer');
      }
    }))
    .append($('' + layerName + ''));
  if (options.status == 'true') {
    checkbox[0].checked = true;
  }
  $('#layers ul.sidebar-content').prepend(li.data('tilemill', options));
};

TileMill.initMap = function(hosts, layername, type) {
  // @TODO: have these options be passed by TileMill to point to TileLiteLive.
  var hosts = hosts || [ "http://a.tile.mapbox.com/","http://b.tile.mapbox.com/", "http://c.tile.mapbox.com/", "http://d.tile.mapbox.com/" ],
      layername = layername || 'world-light',
      type = type || 'png';

  if (!$('#map-preview').is('.inited')) {
    $('#map-preview').addClass('inited');
    var options = {
      projection: new OpenLayers.Projection("EPSG:900913"),
      displayProjection: new OpenLayers.Projection("EPSG:4326"),
      units: "m",
      numZoomLevels: 12,
      maxResolution: 156543.0339,
      maxExtent: new OpenLayers.Bounds(
        -20037500,
        -20037500,
        20037500,
        20037500
      ),
      controls: []
    };
    var map = new OpenLayers.Map('map-preview', options);
    var layer = new OpenLayers.Layer.TMS("Preview", hosts, {layername: layername, type: type});
    map.addLayers([ layer ]);

    // Set the map's initial center point
    map.setCenter(new OpenLayers.LonLat(0, 0), 2);

    // Add control
    var control = new OpenLayers.Control.Navigation({ 'zoomWheelEnabled': true });
    map.addControl(control);
    control.activate();
  }
  // Update map.
  else {
  }
};

TileMill.initColors = function() {
  $('#farbtastic').farbtastic({callback:'input#color', width:200, height:200});
  $('#color-picker a.color-picker').click(function() {
    $('#farbtastic').toggle('fast');
  });
};

TileMill.save = function() {
  var mml = TileMill.mml();
  $.post('/projects/mml', {
    'id': window.project_id,
    'data': mml,
  });

}

TileMill.mml = function() {
  var output = ['<' + '?xml version="1.0" encoding="utf-8"?>',
  '<!DOCTYPE Map[',
  '  <!ENTITY srs900913 "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs">',
  '  <!ENTITY srsWGS84 "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">',
  ']>',
  '<Map srs="&srs900913;">'];
  $('#layers ul.sidebar-content li').each(function() {
    var layer = $(this).data('tilemill'), l = '  <Layer';
    if (layer.id) {
      l += ' id="' + layer.id + '"';
    }
    if (layer.classes) {
      l += ' class="' + layer.classes.join(' ') + '"';
    }
    if (layer.classes) {
      l += ' class="' + layer.classes.join(' ') + '"';
    }
    if (!layer.srs) {
      layer.srs = '900913';
    }
    l += ' srs="&srs' + (layer.srs == '900913' ? '900913' : 'WGS84') + ';"';
    l += '>';
    output.push(l);
    output.push('    <Datasource>');
    output.push('      <Parameter name="file">' + layer.dataSource + '</Parameter>');
    output.push('      <Parameter name="type">shape</Parameter>');
    output.push('    </Datasource>');
    output.push('  </Layer>');
  });
  output.push('</Map>');
  return output.join("\n");
}

TileMill.mss = function(file, callback) {
  $.get('/projects/mss', {'project_id': project_id, 'filename': file}, callback);
}

$(function() {
  $(mml).find('Layer').each(function() {
    status = $(this).attr('status');
    if (status == 'undefined') {
      status = true;
    }
    else if (status == 'on') {
      status = true;
    }
    else {
      status = false;
    }
    classes = []
    if ($(this).attr('class')) {
      classes = $(this).attr('class').split(' ');
    }
    TileMill.addLayer({
      classes: classes,
      id: $(this).attr('id'),
      status: status,
      dataSource: $(this).find('Datasource Parameter[name=file]').text(),
      srs: $(this).attr('srs').replace({'&srs': '', ';': ''})
    });
  });
  $('#layers ul.sidebar-content').sortable({
    axis: 'y',
    handle: 'div.handle',
  });

  $('a.inspector-close').click(function() {
    $('#layers').show();
    $('#inspector').hide();
    return false;
  });

  TileMill.initMap();
  TileMill.initColors();

  $('a#layers-add').click(function() {
    if ($('#popup-layer').is(':hidden')) {
      $('#popup, #popup-layer, #popup-backdrop, #popup-header').show();
      $('#popup-layer input:not(.submit)').val('');
      $('#popup-layer').addClass('new');
      $('#popup-layer input.submit').text('Add layer');
      $('#popup-header').text('Add layer');
    }
    return false;
  });

  $('#popup-layer input.submit').click(function() {
    var layer = {
      classes: $('#popup-layer input#classes').val().split(' '),
      id: $('#popup-layer input#id').val(),
      dataSource: $('#popup-layer input#dataSource').val(),
      srs: $('#popup-layer input#srs').val(),
      status: 'true'
    };
    if ($('#popup-layer').is('.new')) {
      TileMill.addLayer(layer);
    }
    else {
      var layerName = '';
      if (layer.id) {
        layerName = '#' + layer.id + ' ';
      }
      if (layer.classes) {
        layerName += '.' + layer.classes.join(', .');
      }
      li = $(this).data('li');
      $(li).find('label').text(layerName).data('tilemill', layer);
    }
    $('#popup, #popup > div, #popup-backdrop, #popup-header').hide();
    $('#popup-layer').removeClass('new');
    return false;
  })

  $('a#popup-close').click(function() {
    $('#popup, #popup > div, #popup-backdrop, #popup-header').hide();
    $('#popup-layer').removeClass('new');
  });
});
<commit_msg>Save changes with the save button<commit_after>TileMill = {};
TileMill.addLayer = function(options) {
  var layerName = '';
  if (options.id) {
    layerName = '#' + options.id + ' ';
  }
  if (options.classes.length) {
    layerName += '.' + options.classes.join(', .');
  }
  var checkbox = $('<input class="checkbox" type="checkbox" />');
  var li = $('
')
    .append($('

'))
    .append(checkbox)
    .append($('Inspect').click(function() {
      $('#layers').hide();
      $('#inspector').show();
      return false;
    }))
    .append($('Edit').click(function() {
      var options = $(this).parents('li').data('tilemill');
      if ($('#popup-layer').is(':hidden')) {
        $('#popup, #popup-layer, #popup-backdrop, #popup-header').show();
        $('#popup-layer input:not(.submit)').val('');
        $('#popup-layer input.submit').val('Save').data('li', $(this).parents('li'));
        $('#popup-layer input#classes').val(options.classes.join(' '));
        $('#popup-layer input#id').val(options.id);
        $('#popup-layer input#srs').val(options.srs);
        $('#popup-layer input#dataSource').val(options.dataSource);
        $('#popup-header h2').text('Edit layer');
      }
    }))
    .append($('' + layerName + ''));
  if (options.status == 'true') {
    checkbox[0].checked = true;
  }
  $('#layers ul.sidebar-content').prepend(li.data('tilemill', options));
};

TileMill.initMap = function(hosts, layername, type) {
  // @TODO: have these options be passed by TileMill to point to TileLiteLive.
  var hosts = hosts || [ "http://a.tile.mapbox.com/","http://b.tile.mapbox.com/", "http://c.tile.mapbox.com/", "http://d.tile.mapbox.com/" ],
      layername = layername || 'world-light',
      type = type || 'png';

  if (!$('#map-preview').is('.inited')) {
    $('#map-preview').addClass('inited');
    var options = {
      projection: new OpenLayers.Projection("EPSG:900913"),
      displayProjection: new OpenLayers.Projection("EPSG:4326"),
      units: "m",
      numZoomLevels: 12,
      maxResolution: 156543.0339,
      maxExtent: new OpenLayers.Bounds(
        -20037500,
        -20037500,
        20037500,
        20037500
      ),
      controls: []
    };
    var map = new OpenLayers.Map('map-preview', options);
    var layer = new OpenLayers.Layer.TMS("Preview", hosts, {layername: layername, type: type});
    map.addLayers([ layer ]);

    // Set the map's initial center point
    map.setCenter(new OpenLayers.LonLat(0, 0), 2);

    // Add control
    var control = new OpenLayers.Control.Navigation({ 'zoomWheelEnabled': true });
    map.addControl(control);
    control.activate();
  }
  // Update map.
  else {
  }
};

TileMill.initColors = function() {
  $('#farbtastic').farbtastic({callback:'input#color', width:200, height:200});
  $('#color-picker a.color-picker').click(function() {
    $('#farbtastic').toggle('fast');
  });
};

TileMill.save = function() {
  var mml = TileMill.mml();
  $.post('/projects/mml', {
    'id': window.project_id,
    'data': mml,
  });

}

TileMill.mml = function() {
  var output = ['<' + '?xml version="1.0" encoding="utf-8"?>',
  '<!DOCTYPE Map[',
  '  <!ENTITY srs900913 "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs">',
  '  <!ENTITY srsWGS84 "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">',
  ']>',
  '<Map srs="&srs900913;">'];
  $('#layers ul.sidebar-content li').each(function() {
    var layer = $(this).data('tilemill'), l = '  <Layer';
    if (layer.id) {
      l += ' id="' + layer.id + '"';
    }
    if (layer.classes) {
      l += ' class="' + layer.classes.join(' ') + '"';
    }
    if (layer.classes) {
      l += ' class="' + layer.classes.join(' ') + '"';
    }
    if (!layer.srs) {
      layer.srs = '900913';
    }
    l += ' srs="&srs' + (layer.srs == '900913' ? '900913' : 'WGS84') + ';"';
    l += '>';
    output.push(l);
    output.push('    <Datasource>');
    output.push('      <Parameter name="file">' + layer.dataSource + '</Parameter>');
    output.push('      <Parameter name="type">shape</Parameter>');
    output.push('    </Datasource>');
    output.push('  </Layer>');
  });
  output.push('</Map>');
  return output.join("\n");
}

TileMill.mss = function(file, callback) {
  $.get('/projects/mss', {'project_id': project_id, 'filename': file}, callback);
}

$(function() {
  $(mml).find('Layer').each(function() {
    status = $(this).attr('status');
    if (status == 'undefined') {
      status = true;
    }
    else if (status == 'on') {
      status = true;
    }
    else {
      status = false;
    }
    classes = []
    if ($(this).attr('class')) {
      classes = $(this).attr('class').split(' ');
    }
    TileMill.addLayer({
      classes: classes,
      id: $(this).attr('id'),
      status: status,
      dataSource: $(this).find('Datasource Parameter[name=file]').text(),
      srs: $(this).attr('srs').replace({'&srs': '', ';': ''})
    });
  });
  $('#layers ul.sidebar-content').sortable({
    axis: 'y',
    handle: 'div.handle',
  });

  $('a.inspector-close').click(function() {
    $('#layers').show();
    $('#inspector').hide();
    return false;
  });

  TileMill.initMap();
  TileMill.initColors();

  $('a#layers-add').click(function() {
    if ($('#popup-layer').is(':hidden')) {
      $('#popup, #popup-layer, #popup-backdrop, #popup-header').show();
      $('#popup-layer input:not(.submit)').val('');
      $('#popup-layer').addClass('new');
      $('#popup-layer input.submit').text('Add layer');
      $('#popup-header').text('Add layer');
    }
    return false;
  });

  $('#popup-layer input.submit').click(function() {
    var layer = {
      classes: $('#popup-layer input#classes').val().split(' '),
      id: $('#popup-layer input#id').val(),
      dataSource: $('#popup-layer input#dataSource').val(),
      srs: $('#popup-layer input#srs').val(),
      status: 'true'
    };
    if ($('#popup-layer').is('.new')) {
      TileMill.addLayer(layer);
    }
    else {
      var layerName = '';
      if (layer.id) {
        layerName = '#' + layer.id + ' ';
      }
      if (layer.classes) {
        layerName += '.' + layer.classes.join(', .');
      }
      li = $(this).data('li');
      $(li).find('label').text(layerName).end().data('tilemill', layer);
    }
    $('#popup, #popup > div, #popup-backdrop, #popup-header').hide();
    $('#popup-layer').removeClass('new');
    return false;
  })

  $('a#popup-close').click(function() {
    $('#popup, #popup > div, #popup-backdrop, #popup-header').hide();
    $('#popup-layer').removeClass('new');
  });

  $('div#header a.save').click(function() {
    TileMill.save();
    return false;
  });
});
<|endoftext|>


<commit_before>/**********************************************************************
    Freeciv-web - the web version of Freeciv. http://play.freeciv.org/
    Copyright (C) 2009-2016  The Freeciv-web project

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

***********************************************************************/

var container;
var camera, scene, renderer;
var group;
var mouseX = 0, mouseY = 0;
var controls;
var clock = null;
var dirLight;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var active_globeview = false;
var fullmap_canvas = null;

/**************************************************************************
  Renders the world map on a globe using Three.js, with a loading message.
**************************************************************************/
function init_globe_view()
{
  $.blockUI({ message: "
Creating 3D globe view of map. Please wait.
" });
  setTimeout(show_globe_view, 100);
  keyboard_input = false;
}

/**************************************************************************
  Renders the world map on a globe using Three.js.
**************************************************************************/
function show_globe_view()
{
  // reset dialog page.
  $("#globe_view_dialog").remove();
  $("

").appendTo("div#game_page");

  // load Three.js dynamically.
  $.ajax({
    async: false,
    url: "/javascript/libs/three.min.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/Projector.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/CanvasRenderer.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/Detector.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/FlyControls.js",
    dataType: "script"
  });

  $("#globe_view_dialog").html("

"
                               + "Controls: WASD move, R|F up | down, "
                               + "Q|E roll, up|down pitch, left|right yaw");

  $("#globe_view_dialog").attr("title", server_settings['metamessage']['val']);
  $("#globe_view_dialog").dialog({
			bgiframe: true,
			modal: true,
			width: "98%",
                        height: is_small_screen() ? $(window).height()-30 : $(window).height() - 10,
                        close : function(){
                          close_globe_view_dialog();
                        }
                     });

  $("#globe_view_dialog").dialog('open');

  // step 1: render whole map on a canvas using the Freeciv-web renderer.
  var tmpmap_canvas = document.createElement('canvas');
  var w = map['xsize'] * tileset_tile_width * 0.9;
  var h = map['ysize'] * tileset_tile_height * 1.4;

  tmpmap_canvas.width = w;
  tmpmap_canvas.height = h;

  mapview['width'] = w;
  mapview['height'] = h;
  mapview['store_width'] = w;
  mapview['store_height'] = h;

  center_tile_mapcanvas(map_pos_to_tile(map['xsize']/2, map['ysize']/2));

  mapview_canvas = tmpmap_canvas;
  mapview_canvas_ctx = mapview_canvas.getContext("2d");
  mapview_canvas_ctx.font = canvas_text_font;

  update_map_canvas_full();

  // step 2: change aspect ratio of map so that width = height,
  // rendering the result on a new canvas.
  var scaledmap_canvas = document.createElement('canvas');
  scaledmap_canvas.width = w;
  scaledmap_canvas.height = w;
  var scaledmap_ctx = scaledmap_canvas.getContext("2d");
  scaledmap_ctx.drawImage(tmpmap_canvas, 0,0, w, h, 0, 0, w, w);

  tmp_canvas = null;

  // step 3: rotate the image -41 degrees and render the result on a new canvas.
  // The canvas width and height must be a size in the power of 2, eg. 4096 and 2048.
  fullmap_canvas = document.createElement('canvas');
  fullmap_canvas.width = 4096;
  fullmap_canvas.height = 2048;
  fullmap_ctx = fullmap_canvas.getContext("2d");
  var x = fullmap_canvas.width * 0.5;
  var y = fullmap_canvas.height * 0.48;
  fullmap_ctx.translate(x, y);
  fullmap_ctx.rotate(-41 * Math.PI / 180);
  fullmap_ctx.drawImage(scaledmap_canvas, 0, 0, w, w, -4096 * 0.52, -2048 * 0.5 - 850, 4096, 4096 - 400);
  fullmap_ctx.rotate(41 * Math.PI / 180);
  fullmap_ctx.translate(-x, -y);

  // step 4: clip away left and right part of image, to make it look better.
  fullmap_ctx.drawImage(fullmap_canvas, 4096 * 0.1, 0, 4096 - 4096 * 0.1, 2048, 0, 0, 4096 * 1.22, 2048);

  // result: the fullmap_canvas now contains the image which will be rendered on a sphere.

  scaledmap_canvas = null;

  active_globeview = true;

  globe_view_init();
  globe_view_animate();

  $.unblockUI();

  // prevent array keys from scrolling window.
  window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
  }, false);

}

/**************************************************************************
  ...
**************************************************************************/
function close_globe_view_dialog()
{
  active_globeview = false;
  setup_window_size();
  set_default_mapview_active();
  center_tile_mapcanvas(map_pos_to_tile(map['xsize']/2, map['ysize']/2));
  setTimeout(set_default_mapview_active, 1000);
  keyboard_input = true;
  $(".setting_button").tooltip("destroy");
}

/**************************************************************************
  Init of Three.js rendering of the map on a 3d globe.
**************************************************************************/
function globe_view_init() {

  clock = new THREE.Clock();

  container = document.getElementById( 'globe_container' );
  var width = $("#globe_view_dialog").width() - 20;
  var height = $("#globe_view_dialog").height() - 26;
  if (width > height + 350) width = height + 350;

  camera = new THREE.PerspectiveCamera( 60, width / height, 1, 2000 );
  camera.position.z = 580;

  controls = new THREE.FlyControls(camera);
  controls.movementSpeed = 80;
  controls.domElement = container;
  controls.rollSpeed = Math.PI / 24;
  controls.autoForward = false;
  controls.dragToLook = false;

  scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2( 0x000000, 0.00000025 );

  group = new THREE.Group();
  scene.add( group );

  var geometry = new THREE.SphereGeometry( 300, 36, 36 );

  var texture = new THREE.Texture(fullmap_canvas);
  texture.needsUpdate = true;

  var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
  var mesh = new THREE.Mesh( geometry, material );
  group.add( mesh );

  renderer = Detector.webgl? new THREE.WebGLRenderer(): new THREE.CanvasRenderer();
  renderer.setClearColor(0x0a0a0a);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(width, height);

  container.appendChild(renderer.domElement);

  document.addEventListener('mousemove', onDocumentMouseMove, false);

  window.addEventListener('resize', onWindowResize, false);

}

/**************************************************************************
  ...
**************************************************************************/
function onWindowResize() {

  var width = $("#globe_view_dialog").width() - 20;
  var height = $("#globe_view_dialog").height() - 26;
  if (width > height + 350) width = height + 350;

  windowHalfX = $("#globe_view_dialog").width() / 2;
  windowHalfY = $("#globe_view_dialog").height() / 2;

  camera.aspect = width / height;
  camera.updateProjectionMatrix();

  renderer.setSize( width, height);

}

/**************************************************************************
  ...
**************************************************************************/
function onDocumentMouseMove( event ) {

  mouseX = ( event.clientX - windowHalfX );
  mouseY = ( event.clientY - windowHalfY );

}

/**************************************************************************
  ...
**************************************************************************/
function globe_view_animate() {
  if (!active_globeview) return;

  requestAnimationFrame( globe_view_animate );

  globe_view_render();

}

/**************************************************************************
  ...
**************************************************************************/
function globe_view_render() {

  var delta = clock.getDelta();

  group.rotation.y -= 0.001;

  controls.update( delta );

  renderer.render( scene, camera );

}

<commit_msg>Decrease globe rotation speed.<commit_after>/**********************************************************************
    Freeciv-web - the web version of Freeciv. http://play.freeciv.org/
    Copyright (C) 2009-2016  The Freeciv-web project

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

***********************************************************************/

var container;
var camera, scene, renderer;
var group;
var mouseX = 0, mouseY = 0;
var controls;
var clock = null;
var dirLight;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var active_globeview = false;
var fullmap_canvas = null;

/**************************************************************************
  Renders the world map on a globe using Three.js, with a loading message.
**************************************************************************/
function init_globe_view()
{
  $.blockUI({ message: "
Creating 3D globe view of map. Please wait.
" });
  setTimeout(show_globe_view, 100);
  keyboard_input = false;
}

/**************************************************************************
  Renders the world map on a globe using Three.js.
**************************************************************************/
function show_globe_view()
{
  // reset dialog page.
  $("#globe_view_dialog").remove();
  $("

").appendTo("div#game_page");

  // load Three.js dynamically.
  $.ajax({
    async: false,
    url: "/javascript/libs/three.min.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/Projector.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/CanvasRenderer.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/Detector.js",
    dataType: "script"
  });
  $.ajax({
    async: false,
    url: "/javascript/libs/FlyControls.js",
    dataType: "script"
  });

  $("#globe_view_dialog").html("

"
                               + "Controls: WASD move, R|F up | down, "
                               + "Q|E roll, up|down pitch, left|right yaw");

  $("#globe_view_dialog").attr("title", server_settings['metamessage']['val']);
  $("#globe_view_dialog").dialog({
			bgiframe: true,
			modal: true,
			width: "98%",
                        height: is_small_screen() ? $(window).height()-30 : $(window).height() - 10,
                        close : function(){
                          close_globe_view_dialog();
                        }
                     });

  $("#globe_view_dialog").dialog('open');

  // step 1: render whole map on a canvas using the Freeciv-web renderer.
  var tmpmap_canvas = document.createElement('canvas');
  var w = map['xsize'] * tileset_tile_width * 0.9;
  var h = map['ysize'] * tileset_tile_height * 1.4;

  tmpmap_canvas.width = w;
  tmpmap_canvas.height = h;

  mapview['width'] = w;
  mapview['height'] = h;
  mapview['store_width'] = w;
  mapview['store_height'] = h;

  center_tile_mapcanvas(map_pos_to_tile(map['xsize']/2, map['ysize']/2));

  mapview_canvas = tmpmap_canvas;
  mapview_canvas_ctx = mapview_canvas.getContext("2d");
  mapview_canvas_ctx.font = canvas_text_font;

  update_map_canvas_full();

  // step 2: change aspect ratio of map so that width = height,
  // rendering the result on a new canvas.
  var scaledmap_canvas = document.createElement('canvas');
  scaledmap_canvas.width = w;
  scaledmap_canvas.height = w;
  var scaledmap_ctx = scaledmap_canvas.getContext("2d");
  scaledmap_ctx.drawImage(tmpmap_canvas, 0,0, w, h, 0, 0, w, w);

  tmp_canvas = null;

  // step 3: rotate the image -41 degrees and render the result on a new canvas.
  // The canvas width and height must be a size in the power of 2, eg. 4096 and 2048.
  fullmap_canvas = document.createElement('canvas');
  fullmap_canvas.width = 4096;
  fullmap_canvas.height = 2048;
  fullmap_ctx = fullmap_canvas.getContext("2d");
  var x = fullmap_canvas.width * 0.5;
  var y = fullmap_canvas.height * 0.48;
  fullmap_ctx.translate(x, y);
  fullmap_ctx.rotate(-41 * Math.PI / 180);
  fullmap_ctx.drawImage(scaledmap_canvas, 0, 0, w, w, -4096 * 0.52, -2048 * 0.5 - 850, 4096, 4096 - 400);
  fullmap_ctx.rotate(41 * Math.PI / 180);
  fullmap_ctx.translate(-x, -y);

  // step 4: clip away left and right part of image, to make it look better.
  fullmap_ctx.drawImage(fullmap_canvas, 4096 * 0.1, 0, 4096 - 4096 * 0.1, 2048, 0, 0, 4096 * 1.22, 2048);

  // result: the fullmap_canvas now contains the image which will be rendered on a sphere.

  scaledmap_canvas = null;

  active_globeview = true;

  globe_view_init();
  globe_view_animate();

  $.unblockUI();

  // prevent array keys from scrolling window.
  window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
  }, false);

}

/**************************************************************************
  ...
**************************************************************************/
function close_globe_view_dialog()
{
  active_globeview = false;
  setup_window_size();
  set_default_mapview_active();
  center_tile_mapcanvas(map_pos_to_tile(map['xsize']/2, map['ysize']/2));
  setTimeout(set_default_mapview_active, 1000);
  keyboard_input = true;
  $(".setting_button").tooltip("destroy");
}

/**************************************************************************
  Init of Three.js rendering of the map on a 3d globe.
**************************************************************************/
function globe_view_init() {

  clock = new THREE.Clock();

  container = document.getElementById( 'globe_container' );
  var width = $("#globe_view_dialog").width() - 20;
  var height = $("#globe_view_dialog").height() - 26;
  if (width > height + 350) width = height + 350;

  camera = new THREE.PerspectiveCamera( 60, width / height, 1, 2000 );
  camera.position.z = 580;

  controls = new THREE.FlyControls(camera);
  controls.movementSpeed = 80;
  controls.domElement = container;
  controls.rollSpeed = Math.PI / 24;
  controls.autoForward = false;
  controls.dragToLook = false;

  scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2( 0x000000, 0.00000025 );

  group = new THREE.Group();
  scene.add( group );

  var geometry = new THREE.SphereGeometry( 300, 36, 36 );

  var texture = new THREE.Texture(fullmap_canvas);
  texture.needsUpdate = true;

  var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
  var mesh = new THREE.Mesh( geometry, material );
  group.add( mesh );

  renderer = Detector.webgl? new THREE.WebGLRenderer(): new THREE.CanvasRenderer();
  renderer.setClearColor(0x0a0a0a);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(width, height);

  container.appendChild(renderer.domElement);

  document.addEventListener('mousemove', onDocumentMouseMove, false);

  window.addEventListener('resize', onWindowResize, false);

}

/**************************************************************************
  ...
**************************************************************************/
function onWindowResize() {

  var width = $("#globe_view_dialog").width() - 20;
  var height = $("#globe_view_dialog").height() - 26;
  if (width > height + 350) width = height + 350;

  windowHalfX = $("#globe_view_dialog").width() / 2;
  windowHalfY = $("#globe_view_dialog").height() / 2;

  camera.aspect = width / height;
  camera.updateProjectionMatrix();

  renderer.setSize( width, height);

}

/**************************************************************************
  ...
**************************************************************************/
function onDocumentMouseMove( event ) {

  mouseX = ( event.clientX - windowHalfX );
  mouseY = ( event.clientY - windowHalfY );

}

/**************************************************************************
  ...
**************************************************************************/
function globe_view_animate() {
  if (!active_globeview) return;

  requestAnimationFrame( globe_view_animate );

  globe_view_render();

}

/**************************************************************************
  ...
**************************************************************************/
function globe_view_render() {

  var delta = clock.getDelta();

  group.rotation.y -= 0.0005;

  controls.update(delta);

  renderer.render(scene, camera);

}

<|endoftext|>


<commit_before>import {
  getUsers as getUsersAJAX,
  getRoles as getRolesAJAX,
  createUser as createUserAJAX,
  deleteRole as deleteRoleAJAX,
  deleteUser as deleteUserAJAX,
  updateRoleUsers as updateRoleUsersAJAX,
  updateRolePermissions as updateRolePermissionsAJAX,
} from 'src/admin/apis'
import {killQuery as killQueryProxy} from 'shared/apis/metaQuery'
import {publishNotification} from 'src/shared/actions/notifications';

import {ADMIN_NOTIFICATION_DELAY} from 'shared/constants'

export const loadUsers = ({users}) => ({
  type: 'LOAD_USERS',
  payload: {
    users,
  },
})

export const loadRoles = ({roles}) => ({
  type: 'LOAD_ROLES',
  payload: {
    roles,
  },
})

export const loadPermissions = ({permissions}) => ({
  type: 'LOAD_PERMISSIONS',
  payload: {
    permissions,
  },
})

export const addUser = () => ({
  type: 'ADD_USER',
})

export const createUserSuccess = (user, createdUser) => ({
  type: 'CREATE_USER_SUCCESS',
  payload: {
    user,
    createdUser,
  },
})

export const editUser = (user, updates) => ({
  type: 'EDIT_USER',
  payload: {
    user,
    updates,
  },
})

export const killQuery = (queryID) => ({
  type: 'KILL_QUERY',
  payload: {
    queryID,
  },
})

export const setQueryToKill = (queryIDToKill) => ({
  type: 'SET_QUERY_TO_KILL',
  payload: {
    queryIDToKill,
  },
})

export const loadQueries = (queries) => ({
  type: 'LOAD_QUERIES',
  payload: {
    queries,
  },
})

export const deleteRole = (role) => ({
  type: 'DELETE_ROLE',
  payload: {
    role,
  },
})

export const deleteUser = (user) => ({
  type: 'DELETE_USER',
  payload: {
    user,
  },
})

export const filterRoles = (text) => ({
  type: 'FILTER_ROLES',
  payload: {
    text,
  },
})

export const filterUsers = (text) => ({
  type: 'FILTER_USERS',
  payload: {
    text,
  },
})

// async actions
export const loadUsersAsync = (url) => async (dispatch) => {
  const {data} = await getUsersAJAX(url)
  dispatch(loadUsers(data))
}

export const loadRolesAsync = (url) => async (dispatch) => {
  const {data} = await getRolesAJAX(url)
  dispatch(loadRoles(data))
}

export const createUserAsync = (url, user) => async (dispatch) => {
  try {
    const {data} = await createUserAJAX(url, user)
    dispatch(publishNotification('success', 'User created successfully'))
    dispatch(createUserSuccess(user, data))
  } catch (error) {
    // undo optimistic update
    dispatch(publishNotification('error', `Failed to create user: ${error.data.message}`))
    setTimeout(() => dispatch(deleteUser(user)), ADMIN_NOTIFICATION_DELAY)
  }
}

export const killQueryAsync = (source, queryID) => (dispatch) => {
  // optimistic update
  dispatch(killQuery(queryID))
  dispatch(setQueryToKill(null))

  // kill query on server
  killQueryProxy(source, queryID)
}

export const deleteRoleAsync = (role, addFlashMessage) => (dispatch) => {
  // optimistic update
  dispatch(deleteRole(role))

  // delete role on server
  deleteRoleAJAX(role.links.self, addFlashMessage, role.name)
}

export const deleteUserAsync = (user, addFlashMessage) => (dispatch) => {
  // optimistic update
  dispatch(deleteUser(user))

  // delete user on server
  deleteUserAJAX(user.links.self, addFlashMessage, user.name)
}

export const updateRoleUsersAsync = (role, users) => async (dispatch) => {
  try {
    await updateRoleUsersAJAX(role.links.self, users)
    dispatch(publishNotification('success', 'Role users updated'))
  } catch (error) {
    dispatch(publishNotification('error', `Failed to update role: ${error.data.message}`))
  }
}

export const updateRolePermissionsAsync = (role, permissions) => async (dispatch) => {
  try {
    await updateRolePermissionsAJAX(role.links.self, permissions)
    dispatch(publishNotification('success', 'Role permissions updated'))
  } catch (error) {
    dispatch(publishNotification('error', `Failed to updated role:  ${error.data.message}`))
  }
}
<commit_msg>Introduce loadPermissionsAsync action creator<commit_after>import {
  getUsers as getUsersAJAX,
  getRoles as getRolesAJAX,
  getPermissions as getPermissionsAJAX,
  createUser as createUserAJAX,
  deleteRole as deleteRoleAJAX,
  deleteUser as deleteUserAJAX,
  updateRoleUsers as updateRoleUsersAJAX,
  updateRolePermissions as updateRolePermissionsAJAX,
} from 'src/admin/apis'
import {killQuery as killQueryProxy} from 'shared/apis/metaQuery'
import {publishNotification} from 'src/shared/actions/notifications';

import {ADMIN_NOTIFICATION_DELAY} from 'shared/constants'

export const loadUsers = ({users}) => ({
  type: 'LOAD_USERS',
  payload: {
    users,
  },
})

export const loadRoles = ({roles}) => ({
  type: 'LOAD_ROLES',
  payload: {
    roles,
  },
})

export const loadPermissions = ({permissions}) => ({
  type: 'LOAD_PERMISSIONS',
  payload: {
    permissions,
  },
})

export const addUser = () => ({
  type: 'ADD_USER',
})

export const createUserSuccess = (user, createdUser) => ({
  type: 'CREATE_USER_SUCCESS',
  payload: {
    user,
    createdUser,
  },
})

export const editUser = (user, updates) => ({
  type: 'EDIT_USER',
  payload: {
    user,
    updates,
  },
})

export const killQuery = (queryID) => ({
  type: 'KILL_QUERY',
  payload: {
    queryID,
  },
})

export const setQueryToKill = (queryIDToKill) => ({
  type: 'SET_QUERY_TO_KILL',
  payload: {
    queryIDToKill,
  },
})

export const loadQueries = (queries) => ({
  type: 'LOAD_QUERIES',
  payload: {
    queries,
  },
})

export const deleteRole = (role) => ({
  type: 'DELETE_ROLE',
  payload: {
    role,
  },
})

export const deleteUser = (user) => ({
  type: 'DELETE_USER',
  payload: {
    user,
  },
})

export const filterRoles = (text) => ({
  type: 'FILTER_ROLES',
  payload: {
    text,
  },
})

export const filterUsers = (text) => ({
  type: 'FILTER_USERS',
  payload: {
    text,
  },
})

// async actions
export const loadUsersAsync = (url) => async (dispatch) => {
  const {data} = await getUsersAJAX(url)
  dispatch(loadUsers(data))
}

export const loadRolesAsync = (url) => async (dispatch) => {
  const {data} = await getRolesAJAX(url)
  dispatch(loadRoles(data))
}

export const loadPermissionsAsync = (url) => async (dispatch) => {
  const {data} = await getPermissionsAJAX(url)
  dispatch(loadPermissions(data))
}

export const createUserAsync = (url, user) => async (dispatch) => {
  try {
    const {data} = await createUserAJAX(url, user)
    dispatch(publishNotification('success', 'User created successfully'))
    dispatch(createUserSuccess(user, data))
  } catch (error) {
    // undo optimistic update
    dispatch(publishNotification('error', `Failed to create user: ${error.data.message}`))
    setTimeout(() => dispatch(deleteUser(user)), ADMIN_NOTIFICATION_DELAY)
  }
}

export const killQueryAsync = (source, queryID) => (dispatch) => {
  // optimistic update
  dispatch(killQuery(queryID))
  dispatch(setQueryToKill(null))

  // kill query on server
  killQueryProxy(source, queryID)
}

export const deleteRoleAsync = (role, addFlashMessage) => (dispatch) => {
  // optimistic update
  dispatch(deleteRole(role))

  // delete role on server
  deleteRoleAJAX(role.links.self, addFlashMessage, role.name)
}

export const deleteUserAsync = (user, addFlashMessage) => (dispatch) => {
  // optimistic update
  dispatch(deleteUser(user))

  // delete user on server
  deleteUserAJAX(user.links.self, addFlashMessage, user.name)
}

export const updateRoleUsersAsync = (role, users) => async (dispatch) => {
  try {
    await updateRoleUsersAJAX(role.links.self, users)
    dispatch(publishNotification('success', 'Role users updated'))
  } catch (error) {
    dispatch(publishNotification('error', `Failed to update role: ${error.data.message}`))
  }
}

export const updateRolePermissionsAsync = (role, permissions) => async (dispatch) => {
  try {
    await updateRolePermissionsAJAX(role.links.self, permissions)
    dispatch(publishNotification('success', 'Role permissions updated'))
  } catch (error) {
    dispatch(publishNotification('error', `Failed to updated role:  ${error.data.message}`))
  }
}
<|endoftext|>


<commit_before>'use strict';

/*
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('../../errors'),
	Group = mongoose.model('Group'),
	User = mongoose.model('User'),
	MyResponse = require('../../../custom_objects/MyResponse'),
	serverJSON = require('../../../local_files/ui/server.ui.json'),
	Helper = require('../../../custom_objects/Helper'),
	util = require('util'),
	_ = require('lodash');

/**
 * Create a Group
 */
exports.create = function(req, res) {

	var group = new Group(req.body);
	console.log('original group: ' + group);
	var myResponse = new MyResponse();
	//var data = _.merge(group,{admins: req.user,createdBy : req.user},Helper.cleanMergeObj);
	//_.extend(group,data);

	//detect if group with this name has already been created
	console.log(JSON.stringify(req.body,null,4));

	var createdByID = null;
	//running test cases
	console.log('createdByType: ' + typeof req.body.createdBy);
	if(typeof req.body.createdBy !== 'undefined')
	{
		createdByID = mongoose.Types.ObjectId(req.body.createdBy);
		req.user = User.findById(req.body.createdBy);
		console.log('req.user: ' + req.user.username);
	}
	else
		createdByID = req.user;

	var query = {
		createdBy:  createdByID,
		name: group.name
	};

	Helper.find(Group,query,function(err,mod) {

		if(err)
		{
			myResponse.transformMongooseError(Group.errPath,String(err));
			Helper.output(Group,null,myResponse,res);
		}
		else if(!mod)
		{
			myResponse.addMessages(serverJSON.api.groups.name.invalid);
			Helper.output(Group,null,myResponse,res);
		}
		else if(mod.length !== 0)
		{
			myResponse.addMessages(serverJSON.api.groups.name.duplicate);
			Helper.output(Group,null,myResponse,res);
		}
		else
		{
			group.createdBy = createdByID;

			//don't run if running test cases
			if(typeof req.body.createdBy === 'undefined')
				group.admins.push(createdByID);

			group.save(function(err) {
				console.log('in save');

				if (err) {
					console.log('error: ' + err);
					myResponse.transformMongooseError(Group.errPath,String(err));
					Helper.output(Group,group,myResponse,res);
				}
				else {
					//don't run this if running test cases
					if(typeof req.body.createdBy !== 'undefined')
					{
						Helper.output(Group,group,myResponse,res);
						return;
					}
					req.user.createdGroups.push(group._id);
					req.user.save(function(userErr) {
						if (userErr) {
							console.log('userErr: ' + userErr);
							myResponse.transformMongooseError(User.errPath,String(err));
							Helper.output(User,null,myResponse,res);
						}
						else
							Helper.output(Group,group,myResponse,res);
					});
				*/
				}
			});
		}
	});
};

/**
 * Show the current Group
 */
exports.read = function(req, res) {

	var groupID = req.params.groupId;
	var query = {
		_id : groupID
	};

	Helper.find(Group,query, function(err,mod) {

		var myResponse = new MyResponse();
		var group = mod[0];

		if (err) {
			console.log('error: ' + err);
			myResponse.transformMongooseError(Group.errPath,String(err));
		}
		else if(mod.length === 0)
		{
			myResponse.addMessages(serverJSON.api.groups._id.exist);
		}

		Helper.output(Group,group,myResponse,res);
	});
};

/**
 * Update a Group
 */
exports.update = function(req, res) {

	var myResponse = new MyResponse();
	var id = req.params.groupId;

	Group.findOne({_id: id}, function(err,group) {

		var myResponse = new MyResponse();
		console.log(err);
		if(err)
		{
			console.log(err);
			myResponse.transformMongooseError(Group.errPath,String(err));
			Helper.output(Group,group,myResponse,res);
		}
		else if(!group)
		{
			myResponse.addMessages(serverJSON.api.groups._id.invalid);
			Helper.output(Group,group,myResponse,res);
		}
		else
		{
			var data = _.merge(group,req.body,Helper.cleanMergeObj);
			_.extend(group,data);

			group.updated = Date.now();

			group.save(function(err) {
				console.log('in save');

				if (err) {
					console.log('error: ' + err);
					myResponse.transformMongooseError(Group.errPath,String(err));
				}
					Helper.output(Group,group,myResponse,res);
			});
		}
	});
};

/**
 * Delete an Group
 */
exports.delete = function(req, res) {

	var id = req.params.groupId;
	console.log('group id: ' + id);
	var myResponse = new MyResponse();

	Group.findOne({_id: id}, function(err,group) {

		var myResponse = new MyResponse();

		if(err)
		{
			console.log(err);
			myResponse.transformMongooseError(Group.errPath,String(err));
			Helper.output(Group,group,myResponse,res);
		}
		else if(!group)
		{
			myResponse.addMessages(serverJSON.api.groups._id.invalid);
			myResponse.setError(res);
			Helper.output(Group,group,myResponse,res);
		}
		else
		{
			group.remove(function(err) {
				if (err) {
					console.log('error: ' + err);
					myResponse.transformMongooseError(Group.errPath,String(err));
				}
				Helper.output(Group,group,myResponse,res);
			});
		}
	});
};

/**
 * List of Groups
 */
exports.list = function(req, res) { Group.find().sort('-created').exec(function(err, groups) {

		var myResponse = new MyResponse();

		var groupName = req.query.group_name;
		console.log('groupName: ' + groupName);
		if(groupName)
		{
			var regex = ".*"+groupName+".*";
			console.log('regex: ' + regex);

			var query = {
				name:
				{
					$regex: new RegExp(regex,'i')
				}
			};

			Helper.find(Group,query,function(err,mod) {

				if (err) {
					myResponse.transformMongooseError(Group.errPath,String(err));
					Helper.output(Group,null,myResponse,res);
				}
				else if(!mod) {
					myResponse.addMessages(serverJSON.api.events._id.exist);
					Helper.output(Group,null,myResponse,res);
				}
				else
				{
					Helper.output(Group,mod,myResponse,res);
				}
			});
		}
		//Show all events if none are found in the DB
		else
		{
			if (err) {
				myResponse.transformMongooseError(Group.errPath,String(err));
			}

			Helper.output(Group,groups,myResponse,res);
		}
	});
};

/**
 * Group middleware
 */
exports.groupByID = function(req, res, next, id) {

	var myResponse = new MyResponse();

	if(!mongoose.Types.ObjectId.isValid(id))
	{
		myResponse.addMessages(serverJSON.api.groups._id.invalid);
		Helper.output(Group,null,myResponse,res);
		return;
	}

	Group.findById(id).populate('user', 'displayName').exec(function(err, group) {
		//if (err) return next(err);
		//if (! group) return next(new Error('Failed to load Group ' + id));
		req.group = group ;

		next();
	});
};

/**
 * Group authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.group.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>fixed syntax error with leftover group comment symbol<commit_after>'use strict';

/*
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('../../errors'),
	Group = mongoose.model('Group'),
	User = mongoose.model('User'),
	MyResponse = require('../../../custom_objects/MyResponse'),
	serverJSON = require('../../../local_files/ui/server.ui.json'),
	Helper = require('../../../custom_objects/Helper'),
	util = require('util'),
	_ = require('lodash');

/**
 * Create a Group
 */
exports.create = function(req, res) {

	var group = new Group(req.body);
	console.log('original group: ' + group);
	var myResponse = new MyResponse();
	//var data = _.merge(group,{admins: req.user,createdBy : req.user},Helper.cleanMergeObj);
	//_.extend(group,data);

	//detect if group with this name has already been created
	console.log(JSON.stringify(req.body,null,4));

	var createdByID = null;
	//running test cases
	console.log('createdByType: ' + typeof req.body.createdBy);
	if(typeof req.body.createdBy !== 'undefined')
	{
		createdByID = mongoose.Types.ObjectId(req.body.createdBy);
		req.user = User.findById(req.body.createdBy);
		console.log('req.user: ' + req.user.username);
	}
	else
		createdByID = req.user;

	var query = {
		createdBy:  createdByID,
		name: group.name
	};

	Helper.find(Group,query,function(err,mod) {

		if(err)
		{
			myResponse.transformMongooseError(Group.errPath,String(err));
			Helper.output(Group,null,myResponse,res);
		}
		else if(!mod)
		{
			myResponse.addMessages(serverJSON.api.groups.name.invalid);
			Helper.output(Group,null,myResponse,res);
		}
		else if(mod.length !== 0)
		{
			myResponse.addMessages(serverJSON.api.groups.name.duplicate);
			Helper.output(Group,null,myResponse,res);
		}
		else
		{
			group.createdBy = createdByID;

			//don't run if running test cases
			if(typeof req.body.createdBy === 'undefined')
				group.admins.push(createdByID);

			group.save(function(err) {
				console.log('in save');

				if (err) {
					console.log('error: ' + err);
					myResponse.transformMongooseError(Group.errPath,String(err));
					Helper.output(Group,group,myResponse,res);
				}
				else {
					//don't run this if running test cases
					if(typeof req.body.createdBy !== 'undefined')
					{
						Helper.output(Group,group,myResponse,res);
						return;
					}
					req.user.createdGroups.push(group._id);
					req.user.save(function(userErr) {
						if (userErr) {
							console.log('userErr: ' + userErr);
							myResponse.transformMongooseError(User.errPath,String(err));
							Helper.output(User,null,myResponse,res);
						}
						else
							Helper.output(Group,group,myResponse,res);
					});
				}
			});
		}
	});
};

/**
 * Show the current Group
 */
exports.read = function(req, res) {

	var groupID = req.params.groupId;
	var query = {
		_id : groupID
	};

	Helper.find(Group,query, function(err,mod) {

		var myResponse = new MyResponse();
		var group = mod[0];

		if (err) {
			console.log('error: ' + err);
			myResponse.transformMongooseError(Group.errPath,String(err));
		}
		else if(mod.length === 0)
		{
			myResponse.addMessages(serverJSON.api.groups._id.exist);
		}

		Helper.output(Group,group,myResponse,res);
	});
};

/**
 * Update a Group
 */
exports.update = function(req, res) {

	var myResponse = new MyResponse();
	var id = req.params.groupId;

	Group.findOne({_id: id}, function(err,group) {

		var myResponse = new MyResponse();
		console.log(err);
		if(err)
		{
			console.log(err);
			myResponse.transformMongooseError(Group.errPath,String(err));
			Helper.output(Group,group,myResponse,res);
		}
		else if(!group)
		{
			myResponse.addMessages(serverJSON.api.groups._id.invalid);
			Helper.output(Group,group,myResponse,res);
		}
		else
		{
			var data = _.merge(group,req.body,Helper.cleanMergeObj);
			_.extend(group,data);

			group.updated = Date.now();

			group.save(function(err) {
				console.log('in save');

				if (err) {
					console.log('error: ' + err);
					myResponse.transformMongooseError(Group.errPath,String(err));
				}
					Helper.output(Group,group,myResponse,res);
			});
		}
	});
};

/**
 * Delete an Group
 */
exports.delete = function(req, res) {

	var id = req.params.groupId;
	console.log('group id: ' + id);
	var myResponse = new MyResponse();

	Group.findOne({_id: id}, function(err,group) {

		var myResponse = new MyResponse();

		if(err)
		{
			console.log(err);
			myResponse.transformMongooseError(Group.errPath,String(err));
			Helper.output(Group,group,myResponse,res);
		}
		else if(!group)
		{
			myResponse.addMessages(serverJSON.api.groups._id.invalid);
			myResponse.setError(res);
			Helper.output(Group,group,myResponse,res);
		}
		else
		{
			group.remove(function(err) {
				if (err) {
					console.log('error: ' + err);
					myResponse.transformMongooseError(Group.errPath,String(err));
				}
				Helper.output(Group,group,myResponse,res);
			});
		}
	});
};

/**
 * List of Groups
 */
exports.list = function(req, res) { Group.find().sort('-created').exec(function(err, groups) {

		var myResponse = new MyResponse();

		var groupName = req.query.group_name;
		console.log('groupName: ' + groupName);
		if(groupName)
		{
			var regex = ".*"+groupName+".*";
			console.log('regex: ' + regex);

			var query = {
				name:
				{
					$regex: new RegExp(regex,'i')
				}
			};

			Helper.find(Group,query,function(err,mod) {

				if (err) {
					myResponse.transformMongooseError(Group.errPath,String(err));
					Helper.output(Group,null,myResponse,res);
				}
				else if(!mod) {
					myResponse.addMessages(serverJSON.api.events._id.exist);
					Helper.output(Group,null,myResponse,res);
				}
				else
				{
					Helper.output(Group,mod,myResponse,res);
				}
			});
		}
		//Show all events if none are found in the DB
		else
		{
			if (err) {
				myResponse.transformMongooseError(Group.errPath,String(err));
			}

			Helper.output(Group,groups,myResponse,res);
		}
	});
};

/**
 * Group middleware
 */
exports.groupByID = function(req, res, next, id) {

	var myResponse = new MyResponse();

	if(!mongoose.Types.ObjectId.isValid(id))
	{
		myResponse.addMessages(serverJSON.api.groups._id.invalid);
		Helper.output(Group,null,myResponse,res);
		return;
	}

	Group.findById(id).populate('user', 'displayName').exec(function(err, group) {
		//if (err) return next(err);
		//if (! group) return next(new Error('Failed to load Group ' + id));
		req.group = group ;

		next();
	});
};

/**
 * Group authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.group.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>import assign from 'lodash/assign'
import filter from 'lodash/filter'
import forEach from 'lodash/forEach'
import humanFormat from 'human-format'
import isArray from 'lodash/isArray'
import isFunction from 'lodash/isFunction'
import mapValues from 'lodash/mapValues'
import pick from 'lodash/fp/pick'
import { connect } from 'react-redux'
import { createSelector } from 'reselect'
import { PropTypes } from 'react'

import * as actions from '../../store/actions'

// ===================================================================

const _normalizeMapStateToProps = (mapper) => {
  if (isFunction(mapper)) {
    return mapper
  }

  if (isArray(mapper)) {
    return pick(mapper)
  }

  mapper = mapValues(mapper, _normalizeMapStateToProps)
  return (state, props) => mapValues(mapper, (fn) => fn(state, props))
}

export const connectStore = (mapStateToProps) => connect(
  _normalizeMapStateToProps(mapStateToProps),
  actions
)

// -------------------------------------------------------------------

export const createFilter = (
  collectionSelector,
  filterSelector,
  valueGetter
) => createSelector(
  collectionSelector,
  filterSelector,
  (collection, filter_) => {
    if (!filter_) {
      return collection
    }

    filter_ = String(filter_).toLowerCase()
    return filter(
      collection,
      (item) => String(valueGetter(item)).toLowerCase().indexOf(filter_) !== -1
    )
  }
)

// -------------------------------------------------------------------

const osToFamily = (function (osByFamily) {
  const osToFamily = Object.create(null)

  forEach(osByFamily, (list, family) => {
    forEach((list, os) => {
      osToFamily[os] = family
    })
  })

  return osToFamily
})({
  linux: [
    'coreos'
  ],
  centos: [
    'centos'
  ],
  debian: [
    'debian'
  ],
  fedora: [
    'fedora'
  ],
  gentoo: [
    'gentoo'
  ],
  oracle: [
    'oracle'
  ],
  redhat: [
    'redhat',
    'rhel'
  ],
  ubuntu: [
    'ubuntu'
  ],
  solaris: [
    'solaris'
  ],
  freebsd: [
    'freebsd'
  ],
  netbsd: [
    'netbsd'
  ],
  osx: [
    'osx'
  ],
  'linux-mint': [
    'linux-mint'
  ],
  suse: [
    'sles',
    'suse'
  ],
  windows: [
    'windows'
  ]
})

export const osFamily = (osName) => osToFamily[osName.toLowerCase()] || 'other'

// -------------------------------------------------------------------

// Invoke a function and returns it result.
// All parameters are forwarded.
//
// Why using `invoke()`?
// - avoid tedious IIFE syntax
// - avoid declaring variables in the common scope
// - monkey-patching
//
// ```js
// const sum = invoke(1, 2, (a, b) => a + b)
//
// eventEmitter.emit = invoke(eventEmitter.emit, (emit) => function (event) {
//   if (event === 'foo') {
//     throw new Error('event foo is disabled')
//   }
//
//   return emit.apply(this, arguments)
// })
// ```
export function invoke () {
  const n = arguments.length - 1
  const fn = arguments[n]
  const args = new Array(n)
  for (let i = 0; i < n; ++i) {
    args[i] = arguments[i]
  }

  return fn.apply(undefined, args)
}

// -------------------------------------------------------------------

export const propTypes = (types) => (target) => {
  target.propTypes = types

  return target
}
assign(propTypes, PropTypes)

// -------------------------------------------------------------------

export const formatSize = (bytes) => humanFormat(bytes, { scale: 'binary', unit: 'B' })

export const parseSize = (size) => {
  let bytes = humanFormat.parse.raw(size, { scale: 'binary' })
  if (bytes.unit && bytes.unit !== 'B') {
    bytes = humanFormat.parse.raw(size)

    if (bytes.unit && bytes.unit !== 'B') {
      throw new Error('invalid size: ' + size)
    }
  }
  return Math.floor(bytes.value * bytes.factor)
}
<commit_msg>fix osfamily<commit_after>import assign from 'lodash/assign'
import filter from 'lodash/filter'
import forEach from 'lodash/forEach'
import humanFormat from 'human-format'
import isArray from 'lodash/isArray'
import isFunction from 'lodash/isFunction'
import mapValues from 'lodash/mapValues'
import pick from 'lodash/fp/pick'
import { connect } from 'react-redux'
import { createSelector } from 'reselect'
import { PropTypes } from 'react'

import * as actions from '../../store/actions'

// ===================================================================

const _normalizeMapStateToProps = (mapper) => {
  if (isFunction(mapper)) {
    return mapper
  }

  if (isArray(mapper)) {
    return pick(mapper)
  }

  mapper = mapValues(mapper, _normalizeMapStateToProps)
  return (state, props) => mapValues(mapper, (fn) => fn(state, props))
}

export const connectStore = (mapStateToProps) => connect(
  _normalizeMapStateToProps(mapStateToProps),
  actions
)

// -------------------------------------------------------------------

export const createFilter = (
  collectionSelector,
  filterSelector,
  valueGetter
) => createSelector(
  collectionSelector,
  filterSelector,
  (collection, filter_) => {
    if (!filter_) {
      return collection
    }

    filter_ = String(filter_).toLowerCase()
    return filter(
      collection,
      (item) => String(valueGetter(item)).toLowerCase().indexOf(filter_) !== -1
    )
  }
)

// -------------------------------------------------------------------

const osToFamily = (function (osByFamily) {
  const osToFamily = Object.create(null)

  forEach(osByFamily, (list, family) => {
    forEach(list, (os) => {
      osToFamily[os] = family
    })
  })

  return osToFamily
})({
  linux: [
    'coreos'
  ],
  centos: [
    'centos'
  ],
  debian: [
    'debian'
  ],
  fedora: [
    'fedora'
  ],
  gentoo: [
    'gentoo'
  ],
  oracle: [
    'oracle'
  ],
  redhat: [
    'redhat',
    'rhel'
  ],
  ubuntu: [
    'ubuntu'
  ],
  solaris: [
    'solaris'
  ],
  freebsd: [
    'freebsd'
  ],
  netbsd: [
    'netbsd'
  ],
  osx: [
    'osx'
  ],
  'linux-mint': [
    'linux-mint'
  ],
  suse: [
    'sles',
    'suse'
  ],
  windows: [
    'windows'
  ]
})

export const osFamily = (osName) => osToFamily[osName.toLowerCase()] || 'other'

// -------------------------------------------------------------------

// Invoke a function and returns it result.
// All parameters are forwarded.
//
// Why using `invoke()`?
// - avoid tedious IIFE syntax
// - avoid declaring variables in the common scope
// - monkey-patching
//
// ```js
// const sum = invoke(1, 2, (a, b) => a + b)
//
// eventEmitter.emit = invoke(eventEmitter.emit, (emit) => function (event) {
//   if (event === 'foo') {
//     throw new Error('event foo is disabled')
//   }
//
//   return emit.apply(this, arguments)
// })
// ```
export function invoke () {
  const n = arguments.length - 1
  const fn = arguments[n]
  const args = new Array(n)
  for (let i = 0; i < n; ++i) {
    args[i] = arguments[i]
  }

  return fn.apply(undefined, args)
}

// -------------------------------------------------------------------

export const propTypes = (types) => (target) => {
  target.propTypes = types

  return target
}
assign(propTypes, PropTypes)

// -------------------------------------------------------------------

export const formatSize = (bytes) => humanFormat(bytes, { scale: 'binary', unit: 'B' })

export const parseSize = (size) => {
  let bytes = humanFormat.parse.raw(size, { scale: 'binary' })
  if (bytes.unit && bytes.unit !== 'B') {
    bytes = humanFormat.parse.raw(size)

    if (bytes.unit && bytes.unit !== 'B') {
      throw new Error('invalid size: ' + size)
    }
  }
  return Math.floor(bytes.value * bytes.factor)
}
<|endoftext|>