From a32241ac513c05272b00e94c1600ba3ecbe4a896 Mon Sep 17 00:00:00 2001 From: Guillaume Beraudo Date: Wed, 8 May 2019 12:07:06 +0200 Subject: [PATCH] Put upgraded js, views, templates, ... --- geoportal/config.yaml | 17 +- geoportal/geoportailv3_geoportal/__init__.py | 10 + .../scripts/__init__.py | 12 + .../geoportailv3_geoportal/scripts/db2es.py | 7 +- .../finalize_c2c_23_data_adaptations.py | 82 ++ .../scripts/layers2es.py | 30 +- .../scripts/tooltips2pot.py | 44 +- .../static-ngeo/js/CoordinateStringService.js | 24 +- .../static-ngeo/js/ExclusionManager.js | 25 +- .../static-ngeo/js/Geocoding.js | 4 +- .../static-ngeo/js/GetElevationService.js | 4 +- .../js/GetLayerForCatalogNodeFactory.js | 11 +- .../static-ngeo/js/GetShorturlService.js | 2 +- .../static-ngeo/js/GetWmsLayerFactory.js | 6 +- .../static-ngeo/js/GetWmtsLayerFactory.js | 8 +- .../static-ngeo/js/LayerOpacityManager.js | 4 +- .../static-ngeo/js/LayerPermalinkManager.js | 267 ++-- .../static-ngeo/js/LocationControl.js | 34 +- .../static-ngeo/js/Mymaps.js | 94 +- .../static-ngeo/js/OfflineDownloader.js | 7 +- .../static-ngeo/js/Routing.js | 50 +- .../static-ngeo/js/ScalesService.js | 4 +- .../static-ngeo/js/StateManager.js | 4 +- .../static-ngeo/js/Themes.js | 92 +- .../static-ngeo/js/WmsHelper.js | 11 +- .../static-ngeo/js/WmtsHelper.js | 5 +- .../static-ngeo/js/apps/Controllermain.js | 1069 +++++++++++++++++ .../static-ngeo/js/apps/main.html.ejs | 342 ++++++ .../BackgroundlayerController.js | 4 +- .../js/catalog/CatalogController.js | 10 +- .../static-ngeo/js/draw/DrawController.js | 109 +- .../static-ngeo/js/draw/DrawnFeatures.js | 8 +- .../static-ngeo/js/draw/FeatureHash.js | 23 +- .../static-ngeo/js/draw/FeaturePopup.js | 17 +- .../js/draw/FeaturePopupController.js | 36 +- .../static-ngeo/js/draw/RouteControl.js | 17 +- .../static-ngeo/js/index.js | 5 + .../js/infobar/ElevationController.js | 2 +- .../static-ngeo/js/interaction/ClipLine.js | 67 +- .../static-ngeo/js/interaction/DrawRoute.js | 81 +- .../js/interaction/ModifyCircle.js | 110 +- .../js/layermanager/LayermanagerController.js | 7 +- .../js/locationinfo/LocationInfoOverlay.js | 13 +- .../js/locationinfo/LocationinfoController.js | 32 +- .../static-ngeo/js/main.js | 24 +- .../static-ngeo/js/map/MapController.js | 6 +- .../js/measure/MeasureController.js | 40 +- .../static-ngeo/js/module.js | 114 +- .../static-ngeo/js/mymaps/MymapsController.js | 13 +- .../static-ngeo/js/mymaps/mymaps.html | 2 +- .../static-ngeo/js/offline/Configuration.js | 13 +- .../static-ngeo/js/olcs/Extent.js | 4 +- .../static-ngeo/js/olcs/Lux3DManager.js | 6 +- .../static-ngeo/js/olcs/ZoomToExtent.js | 3 +- .../static-ngeo/js/olcs/toggle3d.js | 2 +- .../static-ngeo/js/print/PrintController.js | 110 +- .../static-ngeo/js/print/Printservice.js | 57 +- .../js/profile/ProfileController.js | 8 +- .../static-ngeo/js/projections.js | 16 +- .../static-ngeo/js/query/QueryController.js | 46 +- .../js/routing/RoutingController.js | 91 +- .../static-ngeo/js/search/SearchController.js | 88 +- .../static-ngeo/js/share/ShareController.js | 1 - .../static-ngeo/js/share/share.html | 3 - .../static-ngeo/js/slider/SliderController.js | 27 +- .../static-ngeo/js/slider/slider.html | 3 + .../js/streetview/StreetviewController.js | 54 +- .../themeswitcher/ThemeswitcherController.js | 74 +- .../static-ngeo/less/geoportailv3.api.less | 3 + .../static-ngeo/less/geoportailv3.less | 2 - .../static-ngeo/less/layout.less | 4 + .../static-ngeo/webfonts/statec.eot | Bin 0 -> 1600 bytes .../static-ngeo/webfonts/statec.svg | 11 + .../static-ngeo/webfonts/statec.ttf | Bin 0 -> 1436 bytes .../static-ngeo/webfonts/statec.woff | Bin 0 -> 1512 bytes .../templates/geoportailv3.appcache | 43 +- .../templates/index.html | 528 -------- .../views/authentication.py | 73 +- .../geoportailv3_geoportal/views/casipo.py | 4 +- .../geoportailv3_geoportal/views/download.py | 29 +- .../geoportailv3_geoportal/views/feedback.py | 14 +- .../views/fulltextsearch.py | 18 +- .../geoportailv3_geoportal/views/geocode.py | 37 +- .../views/getfeatureinfo.py | 31 +- .../geoportailv3_geoportal/views/jsapi.py | 2 +- .../geoportailv3_geoportal/views/legends.py | 17 +- .../views/luxprintproxy.py | 67 +- .../geoportailv3_geoportal/views/luxthemes.py | 3 +- .../geoportailv3_geoportal/views/mymaps.py | 331 ++--- geoportal/geoportailv3_geoportal/views/pag.py | 17 +- geoportal/geoportailv3_geoportal/views/pds.py | 6 +- .../geoportailv3_geoportal/views/ping.py | 18 + .../geoportailv3_geoportal/views/profile.py | 66 +- geoportal/geoportailv3_geoportal/views/qr.py | 4 +- .../geoportailv3_geoportal/views/routing.py | 23 +- geoportal/geoportailv3_geoportal/views/wms.py | 28 +- geoportal/package.json | 140 ++- ldap/etc/ldap/prepopulate/20-users.ldif | 2 +- 98 files changed, 3226 insertions(+), 1910 deletions(-) create mode 100644 geoportal/geoportailv3_geoportal/scripts/finalize_c2c_23_data_adaptations.py create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/js/apps/Controllermain.js create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/js/apps/main.html.ejs create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/js/slider/slider.html create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.eot create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.svg create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.ttf create mode 100644 geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.woff delete mode 100644 geoportal/geoportailv3_geoportal/templates/index.html create mode 100644 geoportal/geoportailv3_geoportal/views/ping.py diff --git a/geoportal/config.yaml b/geoportal/config.yaml index 2bf2d2028..b13bf3631 100644 --- a/geoportal/config.yaml +++ b/geoportal/config.yaml @@ -121,6 +121,16 @@ vars: arguments: {db: 0, distributed_lock: true, host: '{REDIS_HOST}', port: '{REDIS_PORT}', redis_expiration_time: 86400} backend: dogpile.cache.redis + pds: + staging_url: + prod_url: + fme_token: + owncloud_internal_url: + owncloud_external_url: + owncloud_user: + owncloud_password: + smtp_server: + bcc_address: casipo: {bcc_address: null, fme_token: null, owncloud_external_url: null, owncloud_internal_url: null, owncloud_password: null, owncloud_user: null, prod_url: null, smtp_server: null, staging_url: null} @@ -306,7 +316,9 @@ vars: hooks: {} host: '{VISIBLE_WEB_HOST}' host_forward_host: [] - https_proxy: {unauthorized_ips: '10.0.0.0/8, 127.0.0.1'} + https_proxy: + unauthorized_ips: '10.0.0.0/8, 127.0.0.1' + authorized_hosts: 'ws.geoportal.lu, ws.geoportail.lu, wms.inspire.geoportail.lu, wms.inspire.geoportal.lu' interfaces: [main] interfaces_config: main: @@ -390,6 +402,9 @@ vars: ogcproxy_enable: false overview_map: {base_layer: basemap_2015_global, show: false} package: geoportailv3 + anf: + email: + map_id: pag: { bcc_address: null, file_server: null, fme_token: null, owncloud_external_url: null, owncloud_internal_url: null, owncloud_password: null, owncloud_user: null, prod_url: null, diff --git a/geoportal/geoportailv3_geoportal/__init__.py b/geoportal/geoportailv3_geoportal/__init__.py index 8fb22bbae..b4a8b296a 100644 --- a/geoportal/geoportailv3_geoportal/__init__.py +++ b/geoportal/geoportailv3_geoportal/__init__.py @@ -130,6 +130,12 @@ def main(global_config, **settings): request_method="GET" ) + config.add_route( + "generate_symbol_file", + "/mymaps/generate_symbol_file", + request_method="GET" + ) + config.add_route( "mymaps_getpublicmaps", "/mymaps/public_maps", @@ -281,6 +287,10 @@ def main(global_config, **settings): "feedback", "/feedback" ) + config.add_route( + "feedbackanf", + "/feedbackanf" + ) # pag routes config.add_route( "pag_url", diff --git a/geoportal/geoportailv3_geoportal/scripts/__init__.py b/geoportal/geoportailv3_geoportal/scripts/__init__.py index e69de29bb..46fde18d6 100644 --- a/geoportal/geoportailv3_geoportal/scripts/__init__.py +++ b/geoportal/geoportailv3_geoportal/scripts/__init__.py @@ -0,0 +1,12 @@ +from pyramid.paster import get_app +from logging.config import fileConfig +import os + + +def get_session(app_config, app_name): + fileConfig(app_config, defaults=os.environ) + get_app(app_config, app_name, options=os.environ) + + # must be done afterwe have loaded the project config + from c2cgeoportal_commons.models import DBSession + return DBSession() diff --git a/geoportal/geoportailv3_geoportal/scripts/db2es.py b/geoportal/geoportailv3_geoportal/scripts/db2es.py index 51b68b148..00454f084 100644 --- a/geoportal/geoportailv3_geoportal/scripts/db2es.py +++ b/geoportal/geoportailv3_geoportal/scripts/db2es.py @@ -9,7 +9,8 @@ from elasticsearch import helpers from elasticsearch.helpers import BulkIndexError from elasticsearch.exceptions import ConnectionTimeout -from geoportailv3.lib.search import get_elasticsearch, get_index, ensure_index +from geoportailv3_geoportal.lib.search import get_elasticsearch, get_index, \ + ensure_index """ Utility functions for importing data into Elasticsearch from database @@ -61,7 +62,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'ri', ['reset', 'index']) except getopt.GetoptError as err: - print str(err) + print(str(err)) sys.exit(2) index = False reset = False @@ -99,7 +100,7 @@ def main(): chunk_size=multiple, raise_on_error=True) except (BulkIndexError, ConnectionTimeout) as e: - print "\n %s" % e + print("\n {}".format(e)) if not results: statuslog("\n") break diff --git a/geoportal/geoportailv3_geoportal/scripts/finalize_c2c_23_data_adaptations.py b/geoportal/geoportailv3_geoportal/scripts/finalize_c2c_23_data_adaptations.py new file mode 100644 index 000000000..d9549ad0c --- /dev/null +++ b/geoportal/geoportailv3_geoportal/scripts/finalize_c2c_23_data_adaptations.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- + +import os +import os.path +import argparse +import warnings +import transaction + +from sqlalchemy import text +from . import get_session + + +def main(): + app_config = "production.ini" + app_name = "app" + + if not os.path.isfile(app_config): + "Cannot find config file: {0!s}".format(app_config) + 0 + + # Ignores pyramid deprecation warnings + warnings.simplefilter("ignore", DeprecationWarning) + + session = get_session(app_config, app_name) + from c2cgeoportal_commons.models import DBSession, main, static + from c2cgeoportal_commons.models.main import OGCSERVER_TYPE_MAPSERVER, \ + OGCSERVER_TYPE_GEOSERVER,OGCSERVER_AUTH_NOAUTH, OGCServer, Metadata, \ + TreeItem, TreeGroup, LayerGroup, LayerWMS, RestrictionArea, Interface + from geoportailv3_geoportal.models import LuxLayerInternalWMS + + + + # Restriction area must have a name. + for r_area in session.query(RestrictionArea).all(): + if r_area.name is None: + r_area.name = 'restrictionarea-{}'.format(r_area.id) + session.add(r_area) + ###### select * from geov3.restrictionarea where name is null or name = ''; + ###### do we need a unique name? + + + transaction.commit() + + # Create new ogc_server if not already exists based on url in LuxLayerInternalWMS. + for luxwms in session.query(LuxLayerInternalWMS).distinct(LuxLayerInternalWMS.url).all(): + url = luxwms.url + if url is not None: + type = OGCSERVER_TYPE_GEOSERVER if 'arcgis' in url else OGCSERVER_TYPE_MAPSERVER + already_exists = session.query(OGCServer).filter(OGCServer.url == url).one_or_none() + if already_exists is None: + ogc_server = OGCServer( + name=url, + description='Generated during migration to GMF 2.3', + url=url, + type_=type, + image_type='image/png', + auth=OGCSERVER_AUTH_NOAUTH, + ) + session.add(ogc_server) + + transaction.commit() + + + + # Set correct ogc_server for LuxLayerInternalWMS with url. + for luxwms in session.query(LuxLayerInternalWMS).all(): + url = luxwms.url + if url is not None: + ogc_server = session.query(OGCServer).filter(OGCServer.url == url).one() + layer_wms = session.query(LayerWMS).filter(LayerWMS.id == luxwms.id).one() + layer_wms.ogc_server_id = ogc_server.id + session.add(layer_wms) + + transaction.commit() + + + + # End note: + # Now the the column 'url' in LuxLayerInternalWMS must be manually removed. + + +if __name__ == "__main__": + main() diff --git a/geoportal/geoportailv3_geoportal/scripts/layers2es.py b/geoportal/geoportailv3_geoportal/scripts/layers2es.py index 5a20f79f7..43e5b1697 100644 --- a/geoportal/geoportailv3_geoportal/scripts/layers2es.py +++ b/geoportal/geoportailv3_geoportal/scripts/layers2es.py @@ -37,11 +37,13 @@ import yaml import requests import json +import os from argparse import ArgumentParser from pyramid.paster import get_app, bootstrap from pyramid.i18n import TranslationStringFactory, make_localizer from pyramid.interfaces import ITranslationDirectories -from geoportailv3.lib.search import get_elasticsearch, get_index, ensure_index +from geoportailv3_geoportal.lib.search import get_elasticsearch, get_index, \ + ensure_index from elasticsearch import helpers from elasticsearch.helpers import BulkIndexError from elasticsearch.exceptions import ConnectionTimeout @@ -126,7 +128,7 @@ def main(): app_name = options.app_name if app_name is None and "#" in app_config: app_config, app_name = app_config.split("#", 1) - get_app(app_config, name=app_name) + get_app(app_config, name=app_name, options=os.environ) Import(options) @@ -138,29 +140,32 @@ def __init__(self, options): self.layers = [] settings = {} - with open(".build/config.yaml") as f: + with open("config.yaml") as f: settings = yaml.load(f) - self.languages = settings["available_locale_names"] - exluded_themes_string = settings["excluded_themes_from_search"] + self.languages = settings["vars"]["available_locale_names"] + exluded_themes_string = settings["vars"]["excluded_themes_from_search"] exluded_themes = [] if exluded_themes_string is not None: exluded_themes = exluded_themes_string.split(",") # must be done only once we have loaded the project config - from c2cgeoportal.models import DBSession, Interface, Theme, Role + from c2cgeoportal_commons.models import DBSession + from c2cgeoportal_commons.models.main import Interface, Theme, Role self.session = DBSession() self._ = {} self.metadata_service_url = \ 'http://shop.geoportail.lu/Portail/inspire/webservices/getMD.jsp' - registry = bootstrap(self.options.app_config)['registry'] - request = bootstrap(self.options.app_config)['request'] + + with bootstrap(self.options.app_config, options=os.environ) as env: + registry = env['registry'] + request = env['request'] self.es_layer_index = get_index(request) + '_layers' self.tdirs = registry.queryUtility(ITranslationDirectories, default=[]) - self.tsf = TranslationStringFactory('geoportailv3-client') + self.tsf = TranslationStringFactory('geoportailv3_geoportal-client') self.interfaces = self.session.query(Interface).filter( Interface.name.in_(options.interfaces) @@ -231,7 +236,7 @@ def _add_fts(self, item, interface, action, role): 'description': '', 'metadata_name': '' } - for metadata in item.ui_metadata: + for metadata in item.metadatas: if metadata.name == 'metadata_id': params = dict( uid=metadata.value, @@ -240,6 +245,7 @@ def _add_fts(self, item, interface, action, role): try: resp = requests.get(url=self.metadata_service_url, params=params) + data = {} try: data = json.loads(resp.text) except: @@ -279,7 +285,7 @@ def _add_folder(self, group, interface, role): return self._add_group(group, interface, self.options.folders, role) def _add_group(self, group, interface, export, role): - from c2cgeoportal.models import LayerGroup + from c2cgeoportal_commons.models.main import LayerGroup fill = False if hasattr(group, 'children'): @@ -307,7 +313,7 @@ def _layer_visible(self, layer, role): return False def _add_layer(self, layer, interface, role): - from c2cgeoportal.models import LayerV1 + from c2cgeoportal_commons.models.main import LayerV1 if isinstance(layer, LayerV1): return False diff --git a/geoportal/geoportailv3_geoportal/scripts/tooltips2pot.py b/geoportal/geoportailv3_geoportal/scripts/tooltips2pot.py index b4890a6dc..bb503c426 100644 --- a/geoportal/geoportailv3_geoportal/scripts/tooltips2pot.py +++ b/geoportal/geoportailv3_geoportal/scripts/tooltips2pot.py @@ -1,15 +1,16 @@ # -*- coding: utf-8 -*- -import sqlahelper +import codecs import traceback import sys -import urllib2 +import urllib.request +import urllib.parse import re import polib -import os.path +import os from os import path from pyramid.paster import bootstrap -from urllib import urlencode from geojson import loads as geojson_loads +from . import get_session def _get_url_with_token(url): @@ -24,10 +25,11 @@ def _get_url_with_token(url): token = urllib2.urlopen(tokenurl, None, 15).read() return baseurl + "token=" + token except: - print url + print(url) traceback.print_exc(file=sys.stdout) return None +TIMEOUT=15 def _get_external_data(url, bbox=None, layer=None): body = {'f': 'pjson', @@ -55,13 +57,14 @@ def _get_external_data(url, bbox=None, layer=None): separator = "?" if url.find(separator) > 0: separator = "&" - query = '%s%s%s' % (url, separator, urlencode(body)) + query = '%s%s%s' % (url, separator, urllib.parse.urlencode(body)) try: - result = urllib2.urlopen(query, None, 15) + print('Requesting %s' % query) + result = urllib.request.urlopen(query, None, TIMEOUT) content = result.read() except: - print query + print(query) traceback.print_exc(file=sys.stdout) return [] @@ -70,12 +73,12 @@ def _get_external_data(url, bbox=None, layer=None): except: return [] if 'fieldAliases' not in esricoll: - print("Error with the layer: %s using query : %s response: %s" - % (layer, query, esricoll)) + print(("Error with the layer: %s using query : %s response: %s" + % (layer, query, esricoll))) return [] else: return dict((value, key) - for key, value in esricoll['fieldAliases'].iteritems()) + for key, value in esricoll['fieldAliases'].items()) def remove_attributes(attributes, attributes_to_remove, @@ -101,13 +104,11 @@ def is_in_po(po, search): def main(): # pragma: nocover - env = bootstrap("development.ini") - from geoportailv3.models import LuxGetfeatureDefinition - - package = env["registry"].settings["package"] - directory = "%s/locale/" % package - destination = path.join(directory, "%s-tooltips.pot" % package) + destination = "/tmp/tooltips.pot" + session = get_session('development.ini', 'app') + from c2cgeoportal_commons.models import DBSession, DBSessions + from geoportailv3_geoportal.models import LuxGetfeatureDefinition if not os.path.isfile(destination): po = polib.POFile() po.metadata = { @@ -118,22 +119,21 @@ def main(): # pragma: nocover else: po = polib.pofile(destination, encoding="utf-8") - dbsession = sqlahelper.get_session() - results = dbsession.query(LuxGetfeatureDefinition).\ + results = session.query(LuxGetfeatureDefinition).\ filter(LuxGetfeatureDefinition.remote_template == False).filter( LuxGetfeatureDefinition.template.in_ (['default.html', 'default_table.html', 'feedbackanf.html'])).all() # noqa fields = [] + print("%d results" % len(results)) for result in results: - engine = sqlahelper.get_engine(result.engine_gfi) + engine = DBSessions[result.engine_gfi] first_row = None if result.query is not None and len(result.query) > 0: if "SELECT" in result.query.upper(): first_row = engine.execute(result.query).first() else: - first_row =\ - engine.execute("SELECT * FROM " + result.query).first() + first_row = engine.execute("SELECT * FROM " + result.query).first() if result.rest_url is not None and len(result.rest_url) > 0: first_row = _get_external_data( result.rest_url, diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/CoordinateStringService.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/CoordinateStringService.js index 1c8427fd4..2666abe2e 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/CoordinateStringService.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/CoordinateStringService.js @@ -9,9 +9,9 @@ let exports = {}; */ import appModule from './module.js'; -import olCoordinate from 'ol/coordinate.js'; -import olProj from 'ol/proj.js'; -import olString from 'ol/string.js'; +import {format} from 'ol/coordinate.js'; +import {transform} from 'ol/proj.js'; +import {padNumber} from 'ol/string.js'; /** @@ -35,16 +35,16 @@ function service() { var str = ''; if (targetEpsgCode === 'EPSG:3263*') { var lonlat = /** @type {ol.Coordinate} */ - (olProj.transform(coordinate, sourceEpsgCode, 'EPSG:4326')); + (transform(coordinate, sourceEpsgCode, 'EPSG:4326')); targetEpsgCode = Math.floor(lonlat[0]) >= 6 ? 'EPSG:32632' : 'EPSG:32631'; } - coordinate = olProj.transform(coordinate, sourceEpsgCode, targetEpsgCode); + coordinate = transform(coordinate, sourceEpsgCode, targetEpsgCode); switch (targetEpsgCode) { default: case 'EPSG:2169': - str = olCoordinate.format(coordinate, '{x} E | {y} N', 0); + str = format(coordinate, '{x} E | {y} N', 0); break; case 'EPSG:4326': if (opt_DMS) { @@ -58,14 +58,14 @@ function service() { var xhdmm = hdmm.split(' ').slice(3, 6).join(' '); str = xhdmm + ' | ' + yhdmm; } else { - str = olCoordinate.format(coordinate, ' {x} E | {y} N', 5); + str = format(coordinate, ' {x} E | {y} N', 5); } break; case 'EPSG:32632': - str = olCoordinate.format(coordinate, '{x} | {y} (UTM32N)', 0); + str = format(coordinate, '{x} | {y} (UTM32N)', 0); break; case 'EPSG:32631': - str = olCoordinate.format(coordinate, '{x} | {y} (UTM31N)', 0); + str = format(coordinate, '{x} | {y} (UTM31N)', 0); break; } return str; @@ -109,8 +109,8 @@ function service() { var normalizedDegrees = ((degrees + 180) % 360) - 180; var x = Math.abs(3600 * normalizedDegrees); return Math.floor(x / 3600) + '\u00b0 ' + - olString.padNumber(Math.floor((x / 60) % 60), 2) + '\u2032 ' + - olString.padNumber(Math.floor(x % 60), 2) + ',' + + padNumber(Math.floor((x / 60) % 60), 2) + '\u2032 ' + + padNumber(Math.floor(x % 60), 2) + ',' + Math.floor((x - (x < 0 ? Math.ceil(x) : Math.floor(x))) * 10) + '\u2033 ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0); } @@ -128,7 +128,7 @@ function service() { var m = (dd - Math.floor(dd)) * 60; var res = Math.floor(dd) + '\u00b0 ' + - olString.padNumber(Math.floor(m), 2) + ',' + + padNumber(Math.floor(m), 2) + ',' + Math.floor((m - Math.floor(m)) * 100000) + '\u2032 ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0); return res; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/ExclusionManager.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/ExclusionManager.js index 6b0979c8b..e528bfab2 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/ExclusionManager.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/ExclusionManager.js @@ -8,12 +8,14 @@ import appModule from './module.js'; import appNotifyNotificationType from './NotifyNotificationType.js'; -import olBase from 'ol.js'; -import olObservable from 'ol/Observable.js'; -import olObject from 'ol/Object.js'; -import olEvents from 'ol/events.js'; + +import {unByKey} from 'ol/Observable.js'; +import {getChangeEventType} from 'ol/Object.js'; +import {listen} from 'ol/events.js'; import olLayerProperty from 'ol/layer/Property.js'; import olCollectionEventType from 'ol/CollectionEventType.js'; +import {getUid} from 'ol/index.js'; + /** * @param {angularGettext.Catalog} gettextCatalog Gettext catalog. @@ -163,7 +165,7 @@ exports.prototype.init = function(map) { // listen on layers being added to the map // base layers switch should fire the event as well - olEvents.listen(map.getLayers(), olCollectionEventType.ADD, + listen(map.getLayers(), olCollectionEventType.ADD, /** * @param {ol.Collection.Event} e Collection event. */ @@ -172,26 +174,25 @@ exports.prototype.init = function(map) { this.checkForLayerExclusion_(map, layer); // listen on opacity change - var key = olEvents.listen(layer, - olObject.getChangeEventType(olLayerProperty.OPACITY), + var key = listen(layer, + getChangeEventType(olLayerProperty.OPACITY), function(e) { this.checkForLayerExclusion_(map, layer); }, this); - layerOpacityListenerKeys[olBase.getUid(layer)] = key; + layerOpacityListenerKeys[getUid(layer)] = key; }, this); // remove any listener on opacity change when layer is removed from map - olEvents.listen(map.getLayers(), olCollectionEventType.REMOVE, + listen(map.getLayers(), olCollectionEventType.REMOVE, /** * @param {ol.Collection.Event} e Collection event. */ function(e) { var layer = /** @type {ol.layer.Layer} */ (e.element); - console.assert(olBase.getUid(layer) in layerOpacityListenerKeys); - olObservable.unByKey(layerOpacityListenerKeys[olBase.getUid(layer)]); + console.assert(getUid(layer) in layerOpacityListenerKeys); + unByKey(layerOpacityListenerKeys[getUid(layer)]); }, this); }; - appModule.service('appExclusionManager', exports); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/Geocoding.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/Geocoding.js index 01bcce8c0..87e2ff60b 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/Geocoding.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/Geocoding.js @@ -7,7 +7,7 @@ */ import appModule from './module.js'; -import olProj from 'ol/proj.js'; +import {transform} from 'ol/proj.js'; /** * @constructor @@ -43,7 +43,7 @@ const exports = function($http, reverseGeocodingServiceUrl, geocodingServiceUrl) */ exports.prototype.reverseGeocode = function(coordinate) { var lonlat = /** @type {ol.Coordinate} */ - (olProj.transform(coordinate, + (transform(coordinate, 'EPSG:3857', 'EPSG:2169')); return this.$http_.get(this.reverseGeocodingServiceUrl_, { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetElevationService.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetElevationService.js index eccad6c2c..9456cd62d 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetElevationService.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetElevationService.js @@ -9,7 +9,7 @@ let exports = {}; */ import appModule from './module.js'; -import olProj from 'ol/proj.js'; +import {transform} from 'ol/proj.js'; /** @@ -29,7 +29,7 @@ function service($http, gettextCatalog, elevationServiceUrl) { */ function getElevation(coordinate) { var lonlat = /** @type {ol.Coordinate} */ - (olProj.transform(coordinate, + (transform(coordinate, 'EPSG:3857', 'EPSG:2169')); return $http.get(elevationServiceUrl, { params: { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetLayerForCatalogNodeFactory.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetLayerForCatalogNodeFactory.js index c470e2802..53e98c4c1 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetLayerForCatalogNodeFactory.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetLayerForCatalogNodeFactory.js @@ -30,8 +30,7 @@ const layerCache_ = {}; * @private * @ngInject */ -function factory(appGetWmtsLayer, appGetWmsLayer, - appGetDevice) { +function factory(appGetWmtsLayer, appGetWmsLayer, appGetDevice) { return getLayerForCatalogNode; /** @@ -48,17 +47,15 @@ function factory(appGetWmtsLayer, appGetWmsLayer, if (layerCacheKey in layerCache_) { return layerCache_[layerCacheKey]; } - if (type.indexOf('WMS') != -1) { + if (type.indexOf('WMS') !== -1) { console.assert('name' in node); console.assert('layers' in node); console.assert('imageType' in node); - layer = appGetWmsLayer(node['name'], node['layers'], node['imageType'], - node['url']); + layer = appGetWmsLayer(node['name'], node['layers'], node['imageType'], node['url']); } else if (type == 'WMTS') { console.assert('name' in node); console.assert('imageType' in node); - var hasRetina = (node['metadata']['hasRetina'] === 'true' && - appGetDevice.isHiDpi()); + var hasRetina = (node['metadata']['hasRetina'] === 'true' && appGetDevice.isHiDpi()); layer = appGetWmtsLayer(node['name'], node['imageType'], hasRetina); } else { return null; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetShorturlService.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetShorturlService.js index b209d936c..f2768913b 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetShorturlService.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetShorturlService.js @@ -22,7 +22,7 @@ import appModule from './module.js'; function service($http, ngeoLocation, shorturlServiceUrl) { return ( /** - * @param {ol.Coordinate=} opt_coordinate + * @param {ol.Coordinate=} opt_coordinate coordinates. * @return {!angular.$q.Promise} Promise providing the short URL. */ function getShorturl(opt_coordinate) { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmsLayerFactory.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmsLayerFactory.js index 9a6ecbdc0..35cac1292 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmsLayerFactory.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmsLayerFactory.js @@ -29,15 +29,13 @@ function factory(proxyWmsUrl, remoteProxyWms, /** * @param {string} name WMS layer name. - * @param {string} layers Comma-separated list of layer names for that WMS - * layer. + * @param {string} layers Comma-separated list of layer names for that WMS layer. * @param {string} imageType Image type (e.g. "image/png"). * @param {string=} opt_url WMS URL. * @return {ol.layer.Image} The layer. */ function getWmsLayer(name, layers, imageType, opt_url) { - var url = opt_url !== undefined ? - opt_url : proxyWmsUrl; + var url = opt_url || proxyWmsUrl; var optSource = { url: url, hidpi: appGetDevice.isHiDpi(), diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmtsLayerFactory.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmtsLayerFactory.js index 98099f843..eaefe3a68 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmtsLayerFactory.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/GetWmtsLayerFactory.js @@ -11,8 +11,8 @@ let exports = {}; import appModule from './module.js'; import appOlcsExtent from './olcs/Extent.js'; import ngeoMiscDecorate from 'ngeo/misc/decorate.js'; -import olExtent from 'ol/extent.js'; -import olProj from 'ol/proj.js'; +import {getTopLeft} from 'ol/extent.js'; +import {get as getProjection} from 'ol/proj.js'; import olLayerTile from 'ol/layer/Tile.js'; import olSourceWMTS from 'ol/source/WMTS.js'; import olSourceWMTSRequestEncoding from 'ol/source/WMTSRequestEncoding.js'; @@ -60,7 +60,7 @@ function factory(requestScheme) { retinaExtension + '/{TileMatrixSet}/{TileMatrix}/{TileCol}/{TileRow}.' + imageExt; } - var projection = olProj.get('EPSG:3857'); + var projection = getProjection('EPSG:3857'); var extent = projection.getExtent(); var layer = new olLayerTile({ 'olcs.extent': appOlcsExtent, @@ -73,7 +73,7 @@ function factory(requestScheme) { requestEncoding: olSourceWMTSRequestEncoding.REST, projection: projection, tileGrid: new olTilegridWMTS({ - origin: olExtent.getTopLeft(extent), + origin: getTopLeft(extent), extent: extent, resolutions: [156543.033928, 78271.516964, 39135.758482, 19567.879241, 9783.9396205, diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerOpacityManager.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerOpacityManager.js index 1bd6fe59a..246a1d732 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerOpacityManager.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerOpacityManager.js @@ -16,7 +16,7 @@ import appModule from './module.js'; import olCollectionEventType from 'ol/CollectionEventType.js'; -import olEvents from 'ol/events.js'; +import {listen} from 'ol/events.js'; /** * @constructor @@ -31,7 +31,7 @@ const exports = function() { */ exports.prototype.init = function(map) { var layers = map.getLayers(); - olEvents.listen(layers, olCollectionEventType.ADD, + listen(layers, olCollectionEventType.ADD, /** * @param {ol.CollectionEventType} evt Collection event. */ diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerPermalinkManager.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerPermalinkManager.js index 4bd8a3cb2..e413b49a5 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerPermalinkManager.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/LayerPermalinkManager.js @@ -9,9 +9,8 @@ import appModule from './module.js'; import appNotifyNotificationType from './NotifyNotificationType.js'; import appEventsThemesEventType from './events/ThemesEventType.js'; -import olEvents from 'ol/events.js'; -import olObjectEventType from 'ol/ObjectEventType.js'; -import olArray from 'ol/array.js'; +import {listen, unlistenByKey} from 'ol/events.js'; +import {extend as arrayExtend} from 'ol/array.js'; /** * @constructor @@ -148,7 +147,7 @@ exports.V2_BGLAYER_TO_V3_ = { */ exports.prototype.unListenProtertyChange_ = function() { this.layersListenerKeys_.forEach(function(key) { - olEvents.unlistenByKey(key); + unlistenByKey(key); }); this.layersListenerKeys_.length = 0; }; @@ -161,8 +160,8 @@ exports.prototype.unListenProtertyChange_ = function() { */ exports.prototype.listenProtertyChange = function(layers) { layers.forEach(function(layer) { - this.layersListenerKeys_.push(olEvents.listen( - layer, olObjectEventType.PROPERTYCHANGE, + this.layersListenerKeys_.push(listen( + layer, 'propertychange', function() { this.onLayerUpdate_(layers); }, this) @@ -205,11 +204,10 @@ exports.prototype.onLayerUpdate_ = function(layers) { /** * @param {Array.} layerIds The ids. * @param {Array.} opacities The opacities. - * @param {Array.} flatCatalogue The catalog. + * @param {Array.} flatCatalog The catalog. * @private */ -exports.prototype.applyLayerStateToMap_ = function( - layerIds, opacities, flatCatalogue) { +exports.prototype.applyLayerStateToMap_ = function(layerIds, opacities, flatCatalog) { layerIds.reverse(); opacities.reverse(); this.unavailableLayerIndex_.forEach(function(elem, index) { @@ -225,7 +223,7 @@ exports.prototype.applyLayerStateToMap_ = function( layerIds.forEach( function(layerId, layerIndex) { if (typeof layerId == 'number' && !isNaN(layerId)) { - var node = flatCatalogue.find(function(catItem) { + var node = flatCatalog.find(function(catItem) { return catItem.id === layerId; }); if (node !== undefined && node !== null) { @@ -425,7 +423,7 @@ exports.prototype.splitLayers_ = */ exports.prototype.removeWatchers_ = function() { if (this.backgroundLayerMgrLstn_ !== null) { - olEvents.unlistenByKey(this.backgroundLayerMgrLstn_); + unlistenByKey(this.backgroundLayerMgrLstn_); this.backgroundLayerMgrLstn_ = null; } if (typeof this.scopeWatcher_ == 'function') { @@ -441,7 +439,7 @@ exports.prototype.removeWatchers_ = function() { */ exports.prototype.setupWatchers_ = function(selectedLayers) { - this.backgroundLayerMgrLstn_ = olEvents.listen(this.backgroundLayerMgr_, 'change', + this.backgroundLayerMgrLstn_ = listen(this.backgroundLayerMgr_, 'change', function() { var bgLayer = this.backgroundLayerMgr_.get(this.map_); this.stateManager_.updateState({ @@ -469,7 +467,7 @@ exports.getAllChildren_ = function(element) { var array = []; for (var i = 0; i < element.length; i++) { if (element[i].hasOwnProperty('children')) { - olArray.extend(array, exports.getAllChildren_( + arrayExtend(array, exports.getAllChildren_( element[i].children) ); } else { @@ -486,157 +484,144 @@ exports.getAllChildren_ = function(element) { * @param {ol.Map} map The map. * @param {Array.} selectedLayers The selected layers. */ -exports.prototype.init = - function(scope, map, selectedLayers) { +exports.prototype.init = function(scope, map, selectedLayers) { /** * @type {angular.Scope} */ - this.scope_ = scope; + this.scope_ = scope; /** * @type {ol.Map} * @private */ - this.map_ = map; + this.map_ = map; /** * @type {number} * @private */ - this.initialVersion_ = this.stateManager_.getVersion(); + this.initialVersion_ = this.stateManager_.getVersion(); /** * @type {boolean} * @private */ - this.initialized_ = false; + this.initialized_ = false; // Wait for themes to load before adding layers from state - olEvents.listen(this.appThemes_, appEventsThemesEventType.LOAD, - function(evt) { - this.appThemes_.getBgLayers().then( - function(bgLayers) { - var stateBgLayerLabel, stateBgLayerOpacity; - var mapId = this.ngeoLocation_.getParam('map_id'); - if (!this.initialized_) { - stateBgLayerLabel = - this.stateManager_.getInitialValue('bgLayer'); - stateBgLayerOpacity = - this.stateManager_.getInitialValue('bgOpacity'); - if ((stateBgLayerLabel !== undefined && stateBgLayerLabel !== null) || - ((stateBgLayerOpacity !== undefined && stateBgLayerOpacity !== null) && - parseInt(stateBgLayerOpacity, 0) === 0)) { - if (this.initialVersion_ === 2 && - stateBgLayerLabel !== undefined && stateBgLayerLabel !== null) { - stateBgLayerLabel = exports.V2_BGLAYER_TO_V3_[stateBgLayerLabel]; - if (stateBgLayerLabel === undefined) { - stateBgLayerLabel = exports.V2_BGLAYER_TO_V3_['webbasemap']; - } - } else if (this.initialVersion_ === 2 && - parseInt(stateBgLayerOpacity, 0) === 0) { - stateBgLayerLabel = 'orthogr_2013_global'; - } + listen(this.appThemes_, appEventsThemesEventType.LOAD, (_) => { + this.initBgLayers_().then(() =>{ + this.initFlatCatalog_(selectedLayers); + }) + }); +}; + +exports.prototype.initBgLayers_ = function() { + return this.appThemes_.getBgLayers().then((bgLayers) => { + var stateBgLayerLabel, stateBgLayerOpacity; + var mapId = this.ngeoLocation_.getParam('map_id'); + if (!this.initialized_) { + stateBgLayerLabel = this.stateManager_.getInitialValue('bgLayer'); + stateBgLayerOpacity = this.stateManager_.getInitialValue('bgOpacity'); + if ((stateBgLayerLabel !== undefined && stateBgLayerLabel !== null) || + ((stateBgLayerOpacity !== undefined && stateBgLayerOpacity !== null) && parseInt(stateBgLayerOpacity, 0) === 0)) { + if (this.initialVersion_ === 2 && stateBgLayerLabel !== undefined && stateBgLayerLabel !== null) { + stateBgLayerLabel = exports.V2_BGLAYER_TO_V3_[stateBgLayerLabel]; + } else if (this.initialVersion_ === 2 && parseInt(stateBgLayerOpacity, 0) === 0) { + stateBgLayerLabel = 'orthogr_2013_global'; + } + } else { + if (mapId === undefined) { + stateBgLayerLabel = 'basemap_2015_global'; + } else { + if (this.appTheme_.getCurrentTheme() === 'tourisme') { + stateBgLayerLabel = 'topo_bw_jpeg'; + } else { + stateBgLayerLabel = 'topogr_global'; + } + } + stateBgLayerOpacity = 0; + } + } else { + stateBgLayerLabel = this.ngeoLocation_.getParam('bgLayer'); + stateBgLayerOpacity = this.ngeoLocation_.getParam('bgOpacity'); + } + var hasBgLayerInUrl = (this.ngeoLocation_.getParam('bgLayer') !== undefined); + if (mapId === undefined || hasBgLayerInUrl) { + var layer = /** @type {ol.layer.Base} */ (bgLayers.find(layer => layer.get('label') === stateBgLayerLabel)); + this.backgroundLayerMgr_.set(this.map_, layer); + } + }); +} + +/** + * @param {Array.} selectedLayers The selected layers. + */ +exports.prototype.initFlatCatalog_ = function(selectedLayers) { + return this.appThemes_.getThemesPromise().then((root) => { + const flatCatalog = this.appThemes_.flatCatalog; + const ogcServers = root.ogcServers; + /** + * @type {Array.|undefined} + */ + var layerIds = []; + /** + * @type {Array.|undefined} + */ + var opacities = []; + if (!this.initialized_) { + if (this.initialVersion_ === 2) { + var layerString = this.stateManager_.getInitialValue('layers'); + if (layerString) { + var layers = layerString.split(','); + layers.forEach(stateLayerLabel => { + var layer = flatCatalog.find(catalogueLayer => catalogueLayer['name'] === stateLayerLabel); + layerIds.push(layer['id']); + }); + } + var opacitiesString = this.stateManager_.getInitialValue('layers_opacity'); + var visibilitiesString = this.stateManager_.getInitialValue('layers_visibility'); + if (opacitiesString !== undefined && opacitiesString !== null && + visibilitiesString !== undefined && visibilitiesString !== null && + visibilitiesString && opacitiesString) { + var visibilities = visibilitiesString.split(','); + opacitiesString.split(',').forEach( + function(opacity, index) { + if (visibilities[index] === 'true') { + opacities.push(parseFloat(opacity)); } else { - if (mapId === undefined) { - stateBgLayerLabel = 'basemap_2015_global'; - } else { - if (this.appTheme_.getCurrentTheme() === 'tourisme') { - stateBgLayerLabel = 'topo_bw_jpeg'; - } else { - stateBgLayerLabel = 'topogr_global'; - } - } - stateBgLayerOpacity = 0; + opacities.push(0); } - } else { - stateBgLayerLabel = this.ngeoLocation_.getParam('bgLayer'); - stateBgLayerOpacity = - this.ngeoLocation_.getParam('bgOpacity'); - } - var hasBgLayerInUrl = (this.ngeoLocation_.getParam('bgLayer') !== undefined); - if (mapId === undefined || hasBgLayerInUrl) { - var layer = /** @type {ol.layer.Base} */ - (bgLayers.find(function(layer) { - return layer.get('label') === stateBgLayerLabel; - })); - this.backgroundLayerMgr_.set(this.map_, layer); - } - this.appThemes_.getFlatCatalog().then( - function(flatCatalogue) { - /** - * @type {Array.|undefined} - */ - var layerIds = []; - /** - * @type {Array.|undefined} - */ - var opacities = []; - if (!this.initialized_) { - if (this.initialVersion_ === 2) { - var layerString = this.stateManager_. - getInitialValue('layers'); - if (layerString) { - var layers = layerString.split(','); - layers.forEach( - function(stateLayerLabel) { - var layer = flatCatalogue.find( - function(catalogueLayer) { - return catalogueLayer['name'] === - stateLayerLabel; - }, this); - layerIds.push(layer['id']); - }, this); - } - var opacitiesString = this.stateManager_. - getInitialValue('layers_opacity'); - var visibilitiesString = this.stateManager_. - getInitialValue('layers_visibility'); - if (opacitiesString !== undefined && opacitiesString !== null && - visibilitiesString !== undefined && visibilitiesString !== null && - visibilitiesString && - opacitiesString) { - var visibilities = visibilitiesString.split(','); - opacitiesString.split(',').forEach( - function(opacity, index) { - if (visibilities[index] === 'true') { - opacities.push(parseFloat(opacity)); - } else { - opacities.push(0); - } - }); - } - layerIds.reverse(); - opacities.reverse(); - - this.stateManager_.deleteParam('layers_indices'); - this.stateManager_.deleteParam('layers_opacity'); - this.stateManager_.deleteParam('layers_visibility'); - this.stateManager_.deleteParam('bgOpacity'); - - } else { - layerIds = this.getStateValue_('layers'); - opacities = this.getStateValue_('opacities'); - } - this.initialized_ = true; - } else { - layerIds = this.splitLayers_( - this.ngeoLocation_.getParam('layers'), '-'); - opacities = this.splitNumbers_( - this.ngeoLocation_.getParam('opacities'), '-'); - } - this.removeWatchers_(); - if (layerIds !== undefined && opacities !== undefined && - layerIds.length > 0 && - layerIds.length === opacities.length) { - this.applyLayerStateToMap_(layerIds, opacities, - flatCatalogue); - } - this.setupWatchers_(selectedLayers); - }.bind(this)); - }.bind(this)); - }, this); - }; + }); + } + layerIds.reverse(); + opacities.reverse(); + + this.stateManager_.deleteParam('layers_indices'); + this.stateManager_.deleteParam('layers_opacity'); + this.stateManager_.deleteParam('layers_visibility'); + this.stateManager_.deleteParam('bgOpacity'); + } else { + layerIds = this.getStateValue_('layers'); + opacities = this.getStateValue_('opacities'); + } + this.initialized_ = true; + } else { + layerIds = this.splitLayers_( + this.ngeoLocation_.getParam('layers'), '-'); + opacities = this.splitNumbers_( + this.ngeoLocation_.getParam('opacities'), '-'); + } + this.removeWatchers_(); + if (layerIds !== undefined && opacities !== undefined && + layerIds.length > 0 && + layerIds.length === opacities.length) { + this.applyLayerStateToMap_(layerIds, opacities, flatCatalog, ogcServers); + } + this.setupWatchers_(selectedLayers); + }); +} appModule.service('appLayerPermalinkManager', exports); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/LocationControl.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/LocationControl.js index 4e52e3146..ec80b99b5 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/LocationControl.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/LocationControl.js @@ -7,15 +7,15 @@ */ import appNotifyNotificationType from './NotifyNotificationType.js'; -import olBase from 'ol.js'; -import olCss from 'ol/css.js'; +import {inherits} from 'ol/index.js'; +import {CLASS_CONTROL, CLASS_UNSELECTABLE} from 'ol/css.js'; import olControlControl from 'ol/control/Control.js'; -import olEvents from 'ol/events.js'; +import {listen} from 'ol/events.js'; import olFeature from 'ol/Feature.js'; import olGeomPoint from 'ol/geom/Point.js'; import olGeolocation from 'ol/Geolocation.js'; import olGeolocationProperty from 'ol/GeolocationProperty.js'; -import olObject from 'ol/Object.js'; +import {getChangeEventType} from 'ol/Object.js'; /** * @constructor @@ -84,8 +84,8 @@ const exports = function(options) { button.setAttribute('type', 'button'); button.setAttribute('title', tipLabel); - var cssClasses = className + ' ' + olCss.CLASS_UNSELECTABLE + ' ' + - olCss.CLASS_CONTROL + ' ' + 'tracker-off'; + var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + + CLASS_CONTROL + ' ' + 'tracker-off'; /** * @type {!Element} @@ -94,10 +94,10 @@ const exports = function(options) { this.element.setAttribute('class', cssClasses); this.element.appendChild(button); - olEvents.listen(button, olEvents.EventType.CLICK, + listen(button, 'click', this.handleClick_, this); - olEvents.listen(button, olEvents.EventType.MOUSEOUT, function() { + listen(button, 'mouseout', function() { this.blur(); }); olControlControl.call(this, { @@ -107,7 +107,7 @@ const exports = function(options) { }; -olBase.inherits(exports, olControlControl); +inherits(exports, olControlControl); /** @@ -157,8 +157,8 @@ exports.prototype.initGeoLocation_ = function() { }) }); - olEvents.listen(this.geolocation_, - olObject.getChangeEventType(olGeolocationProperty.TRACKING), + listen(this.geolocation_, + getChangeEventType(olGeolocationProperty.TRACKING), /** * @param {ol.Object.Event} e Object event. */ @@ -172,8 +172,8 @@ exports.prototype.initGeoLocation_ = function() { } }, this); - olEvents.listen(this.geolocation_, - olObject.getChangeEventType(olGeolocationProperty.POSITION), + listen(this.geolocation_, + getChangeEventType(olGeolocationProperty.POSITION), /** * @param {ol.Object.Event} e Object event. */ @@ -184,8 +184,8 @@ exports.prototype.initGeoLocation_ = function() { this.getMap().getView().setCenter(position); }, this); - olEvents.listen(this.geolocation_, - olObject.getChangeEventType(olGeolocationProperty.ACCURACY_GEOMETRY), + listen(this.geolocation_, + getChangeEventType(olGeolocationProperty.ACCURACY_GEOMETRY), /** * @param {ol.Object.Event} e Object event. */ @@ -194,8 +194,8 @@ exports.prototype.initGeoLocation_ = function() { this.geolocation_.getAccuracyGeometry()); }, this); - olEvents.listen(this.geolocation_, - olEvents.EventType.ERROR, + listen(this.geolocation_, + 'error', function(e) { this.featureOverlay_.clear(); if (e.message && e.message.length > 0) { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/Mymaps.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/Mymaps.js index 215f543c1..9a834160f 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/Mymaps.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/Mymaps.js @@ -9,14 +9,14 @@ import appModule from './module.js'; import appNotifyNotificationType from './NotifyNotificationType.js'; -import olObj from 'ol/obj.js'; +import {assign} from 'ol/obj.js'; import olFormatGeoJSON from 'ol/format/GeoJSON.js'; import olGeomLineString from 'ol/geom/LineString.js'; import olGeomMultiPoint from 'ol/geom/MultiPoint.js'; import olGeomPolygon from 'ol/geom/Polygon.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomPoint from 'ol/geom/Point.js'; -import olProj from 'ol/proj.js'; +import {transform} from 'ol/proj.js'; import olStyleCircle from 'ol/style/Circle.js'; import olStyleFill from 'ol/style/Fill.js'; import olStyleIcon from 'ol/style/Icon.js'; @@ -41,13 +41,21 @@ import olStyleStyle from 'ol/style/Style.js'; * @param {ngeo.map.BackgroundLayerMgr} ngeoBackgroundLayerMgr The background layer * manager. * @param {ngeo.offline.NetworkStatus} ngeoNetworkStatus ngeo Network Status. + * @param {string} appImagesPath Path the the static images. * @param {string} arrowUrl URL to the arrow. * @param {string} arrowModelUrl URL to the Cesium arrow model. * @ngInject */ const exports = function($http, mymapsMapsUrl, mymapsUrl, appStateManager, appUserManager, appNotify, appGetLayerForCatalogNode, gettextCatalog, - appThemes, appTheme, ngeoBackgroundLayerMgr, ngeoNetworkStatus, arrowUrl, arrowModelUrl) { + appThemes, appTheme, ngeoBackgroundLayerMgr, ngeoNetworkStatus, + appImagesPath, arrowUrl, arrowModelUrl) { + /** + * @type {string} + * @private + */ + this.whiteArrowUrl_ = appImagesPath + 'arrow.png'; + /** * @type {string} * @private @@ -656,8 +664,8 @@ exports.prototype.updateLayers = function() { .then(function(flatCatalogue) { curMapLayers.forEach(function(item, layerIndex) { var node = flatCatalogue.find( - function(catalogueLayer) { - return catalogueLayer['name'] === item; + function(catalogLayer) { + return catalogLayer['name'] === item; }); if (node) { var layer = this.getLayerFunc_(node); @@ -1265,7 +1273,7 @@ exports.prototype.createStyleFunction = function(curMap) { var fillStyle = new olStyleFill(); var symbolUrl = this.mymapsSymbolUrl_; - var arrowUrl = this.arrowUrl_; + var whiteArrowUrl = this.whiteArrowUrl_; const arrowModelUrl = this.arrowModelUrl_; const colorStringToRgba = (colorString, opacity = 1) => { @@ -1275,21 +1283,24 @@ exports.prototype.createStyleFunction = function(curMap) { return [r, g, b, opacity]; }; - return function(resolution) { + return function(feature, _) { // clear the styles styles.length = 0; - if (this.get('__editable__') && this.get('__selected__')) { + if (typeof feature == "number") { + feature = this; // older OpenLayers version + } + if (feature.get('__editable__') && feature.get('__selected__')) { styles.push(vertexStyle); } - var order = this.get('display_order'); + var order = feature.get('display_order'); if (order === undefined) { order = 0; } - var color = this.get('color') || '#FF0000'; + var color = feature.get('color') || '#FF0000'; var rgbColor = colorStringToRgba(color, 1); - var opacity = this.get('opacity'); + var opacity = feature.get('opacity'); if (opacity === undefined) { opacity = 1; } @@ -1297,14 +1308,14 @@ exports.prototype.createStyleFunction = function(curMap) { rgbaColor[3] = opacity; fillStyle.setColor(rgbaColor); - if (this.getGeometry().getType() === olGeomGeometryType.LINE_STRING && - this.get('showOrientation') === true) { + if (feature.getGeometry().getType() === olGeomGeometryType.LINE_STRING && + feature.get('showOrientation') === true) { var prevArrow, distance; - var arrowColor = this.get('arrowcolor'); + var arrowColor = feature.get('arrowcolor'); if (arrowColor === undefined || arrowColor === null) { arrowColor = color; } - this.getGeometry().forEachSegment(function(start, end) { + feature.getGeometry().forEachSegment(function(start, end) { var arrowPoint = new olGeomPoint( [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2]); var dx = end[0] - start[0]; @@ -1318,13 +1329,14 @@ exports.prototype.createStyleFunction = function(curMap) { distance = Math.sqrt(w * w + h * h); } if (!prevArrow || distance > 600) { - var src = arrowUrl + '?color=' + arrowColor.replace('#', ''); + var src = whiteArrowUrl; const rotation = Math.PI / 2 - Math.atan2(dy, dx); // arrows styles.push(new olStyleStyle({ geometry: arrowPoint, zIndex: order, image: new olStyleIcon(/** @type {olx.style.IconOptions} */ ({ + color: arrowColor, rotation, src })) @@ -1332,7 +1344,7 @@ exports.prototype.createStyleFunction = function(curMap) { const modelColor = colorStringToRgba(arrowColor, 1); arrowPoint.set('olcs_model', () => { const coordinates = arrowPoint.getCoordinates(); - const center = olProj.transform(coordinates, 'EPSG:3857', 'EPSG:4326'); + const center = transform(coordinates, 'EPSG:3857', 'EPSG:4326'); return { cesiumOptions: { url: arrowModelUrl, @@ -1354,8 +1366,8 @@ exports.prototype.createStyleFunction = function(curMap) { }); } var lineDash; - if (this.get('linestyle')) { - switch (this.get('linestyle')) { + if (feature.get('linestyle')) { + switch (feature.get('linestyle')) { case 'dashed': lineDash = [10, 10]; break; @@ -1368,9 +1380,9 @@ exports.prototype.createStyleFunction = function(curMap) { } var stroke; - var featureStroke = this.get('stroke'); + var featureStroke = feature.get('stroke'); if (featureStroke > 0) { - if (!this.get('__editable__') && this.get('__selected__')) { + if (!feature.get('__editable__') && feature.get('__selected__')) { featureStroke = featureStroke + 3; } stroke = new olStyleStroke({ @@ -1380,8 +1392,8 @@ exports.prototype.createStyleFunction = function(curMap) { }); } - var featureSize = this.get('size'); - if (!this.get('__editable__') && this.get('__selected__')) { + var featureSize = feature.get('size'); + if (!feature.get('__editable__') && feature.get('__selected__')) { featureSize = featureSize + 3; } var imageOptions = { @@ -1393,51 +1405,51 @@ exports.prototype.createStyleFunction = function(curMap) { radius: featureSize }; var image = null; - if (this.get('symbolId')) { - olObj.assign(imageOptions, { - src: symbolUrl + this.get('symbolId') + '?scale=' + featureSize, + if (feature.get('symbolId')) { + assign(imageOptions, { + src: symbolUrl + feature.get('symbolId') + '?scale=' + featureSize, scale: 1, - rotation: this.get('angle') + rotation: feature.get('angle') }); image = new olStyleIcon(imageOptions); } else { - var shape = this.get('shape'); + var shape = feature.get('shape'); if (!shape) { - this.set('shape', 'circle'); + feature.set('shape', 'circle'); shape = 'circle'; } if (shape === 'circle') { image = new olStyleCircle(imageOptions); } else if (shape === 'square') { - olObj.assign(imageOptions, { + assign(imageOptions, { points: 4, angle: Math.PI / 4, - rotation: this.get('angle') + rotation: feature.get('angle') }); image = new olStyleRegularShape( /** @type {olx.style.RegularShapeOptions} */ (imageOptions)); } else if (shape === 'triangle') { - olObj.assign(imageOptions, ({ + assign(imageOptions, ({ points: 3, angle: 0, - rotation: this.get('angle') + rotation: feature.get('angle') })); image = new olStyleRegularShape( /** @type {olx.style.RegularShapeOptions} */ (imageOptions)); } else if (shape === 'star') { - olObj.assign(imageOptions, ({ + assign(imageOptions, ({ points: 5, angle: Math.PI / 4, - rotation: this.get('angle'), + rotation: feature.get('angle'), radius2: featureSize })); image = new olStyleRegularShape( /** @type {olx.style.RegularShapeOptions} */ (imageOptions)); - } else if (this.get('shape') == 'cross') { - olObj.assign(imageOptions, ({ + } else if (feature.get('shape') == 'cross') { + assign(imageOptions, ({ points: 4, angle: 0, - rotation: this.get('angle'), + rotation: feature.get('angle'), radius2: 0 })); image = new olStyleRegularShape( @@ -1445,13 +1457,13 @@ exports.prototype.createStyleFunction = function(curMap) { } } - if (this.get('isLabel')) { + if (feature.get('isLabel')) { return [new olStyleStyle({ text: new olStyleText(/** @type {olx.style.TextOptions} */ ({ - text: this.get('name'), + text: feature.get('name'), textAlign: 'left', font: 'normal ' + featureSize + 'px Sans-serif', - rotation: this.get('angle'), + rotation: feature.get('angle'), fill: new olStyleFill({ color: rgbColor }), diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/OfflineDownloader.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/OfflineDownloader.js index 4525354d6..a581cbbc6 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/OfflineDownloader.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/OfflineDownloader.js @@ -2,12 +2,12 @@ * @module app.OfflineDownloader */ import appModule from './module.js'; -import downloader from 'ngeo/offline/Downloader.js'; +import Downloader from 'ngeo/offline/Downloader.js'; /** * @extends {ngeo.offline.Downloader} */ -const OfflineDownloader = class extends downloader { +const OfflineDownloader = class extends Downloader { /** * @ngInject * @param {ngeo.offline.Configuration} ngeoOfflineConfiguration A service for customizing offline behaviour. @@ -38,7 +38,8 @@ const OfflineDownloader = class extends downloader { save(extent, map) { this.appMymapsOffline_.save(); var piwik = /** @type {Piwik} */ (this.window_['_paq']); - piwik.push(['setDocumentTitle', + piwik.push([ + 'setDocumentTitle', 'saveOfflineMap' ]); piwik.push(['trackPageView']); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/Routing.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/Routing.js index fa9f0b655..53ebea778 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/Routing.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/Routing.js @@ -7,10 +7,16 @@ */ import appModule from './module.js'; -import olBase from 'ol.js'; -import olStyle from 'ol/style.js'; +import Collection from 'ol/Collection.js'; +import Feature from 'ol/Feature.js'; +import Style from 'ol/style/Style.js'; +import Circle from 'ol/style/Circle.js'; +import Stroke from 'ol/style/Stroke.js'; +import Fill from 'ol/style/Fill.js'; +import Text from 'ol/style/Text.js'; import olGeomPoint from 'ol/geom/Point.js'; import olFormatGeoJSON from 'ol/format/GeoJSON.js'; +import {transform} from 'ol/proj.js'; /** * @constructor @@ -33,8 +39,8 @@ const exports = function($http, routingServiceUrl, gettextCatalog, * @type {ol.style.Style} * @private */ - this.roadStyle_ = new olStyle.Style({ - stroke: new olStyle.Stroke({ + this.roadStyle_ = new Style({ + stroke: new Stroke({ color: [255, 0, 0], width: 5 }) @@ -86,18 +92,18 @@ const exports = function($http, routingServiceUrl, gettextCatalog, /** * @type {ol.Collection} */ - this.routeFeatures = new olBase.Collection(); + this.routeFeatures = new Collection(); this.routeOverlay.setFeatures(this.routeFeatures); /** * @type {ngeo.map.FeatureOverlay} */ this.stepsOverlay = ngeoFeatureOverlayMgr.getFeatureOverlay(); - var fillStyle = new olStyle.Fill({ + var fillStyle = new Fill({ color: [41, 128, 185] }); - var strokeStyle = new olStyle.Stroke({ + var strokeStyle = new Stroke({ color: [255, 255, 255], width: 3 }); @@ -106,11 +112,11 @@ const exports = function($http, routingServiceUrl, gettextCatalog, * @type {ol.style.Style} * @private */ - this.stepStyle_ = new olStyle.Style({ + this.stepStyle_ = new Style({ fill: fillStyle, zIndex: 0, stroke: strokeStyle, - image: new olStyle.Circle({ + image: new Circle({ radius: 7, fill: fillStyle, stroke: strokeStyle @@ -121,7 +127,7 @@ const exports = function($http, routingServiceUrl, gettextCatalog, /** * @type {ol.Collection} */ - this.stepFeatures = new olBase.Collection(); + this.stepFeatures = new Collection(); this.stepsOverlay.setFeatures(this.stepFeatures); this.stepsOverlay.setStyle(this.stepStyle_); @@ -133,7 +139,7 @@ const exports = function($http, routingServiceUrl, gettextCatalog, /** * @type {ol.Collection} */ - this.features = new olBase.Collection(); + this.features = new Collection(); this.routingOverlay.setFeatures(this.features); /** @@ -179,39 +185,39 @@ exports.prototype.reorderRoute = function() { exports.prototype.insertFeatureAt = function(feature, routeNumber) { feature.setStyle(function() { var styles = []; - var fillStyle = new olStyle.Fill({ + var fillStyle = new Fill({ color: [255, 255, 255] }); - var strokeStyle = new olStyle.Stroke({ + var strokeStyle = new Stroke({ color: [41, 128, 185], width: 3 }); - styles.push(new olStyle.Style({ + styles.push(new Style({ zIndex: 1, fill: fillStyle, stroke: strokeStyle, - image: new olStyle.Circle({ + image: new Circle({ radius: 15, fill: fillStyle, stroke: strokeStyle }) })); - var text = this.get('name'); + var text = feature.get('name'); if (text === undefined) { text = ''; } - styles.push(new olStyle.Style({ + styles.push(new Style({ zIndex: 2, - text: new olStyle.Text(/** @type {olx.style.TextOptions} */ ({ + text: new Text(/** @type {olx.style.TextOptions} */ ({ text: text, textAlign: 'center', font: 'normal 10px Sans-serif', - fill: new olStyle.Fill({ + fill: new Fill({ color: [41, 128, 185] }), - stroke: new olStyle.Stroke({ + stroke: new Stroke({ color: [255, 255, 255], width: 2 }) @@ -225,7 +231,7 @@ exports.prototype.insertFeatureAt = function(feature, routeNumber) { if (routeNumber > featuresLength) { var j; for (j = featuresLength; j < routeNumber; ++j) { - var blankFeature = new olBase.Feature(); + var blankFeature = new Feature(); blankFeature.set('name', '' + j); this.features.insertAt(j, blankFeature); } @@ -274,7 +280,7 @@ exports.prototype.getRoute = function() { var geom = feature.getGeometry(); if (geom instanceof olGeomPoint) { var lonlat = /** @type {ol.Coordinate} */ - (olBase.proj.transform(geom.getFirstCoordinate(), + (transform(geom.getFirstCoordinate(), 'EPSG:3857', 'EPSG:4326')); waypoints.push(lonlat[1] + ',' + lonlat[0]); } diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/ScalesService.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/ScalesService.js index b62d51912..78cd0d6e4 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/ScalesService.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/ScalesService.js @@ -7,7 +7,7 @@ */ import appModule from './module.js'; -import olObj from 'ol/obj.js'; +import {assign} from 'ol/obj.js'; /** * @constructor @@ -41,7 +41,7 @@ const exports = function($sce) { /** * @type {Object.} */ - this.scales = olObj.assign({}, this.origScales); + this.scales = assign({}, this.origScales); }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/StateManager.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/StateManager.js index 71f262b93..76c7491ab 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/StateManager.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/StateManager.js @@ -8,7 +8,7 @@ */ import appModule from './module.js'; -import olMath from 'ol/math.js'; +import {clamp} from 'ol/math.js'; import appNotifyNotificationType from './NotifyNotificationType.js'; /** @@ -113,7 +113,7 @@ const exports = function(ngeoLocation, appNotify, gettextCatalog) { this.initialState_[key] = ngeoLocation.getParam(key); } this.version_ = this.initialState_.hasOwnProperty('version') ? - olMath.clamp(+this.initialState_['version'], 2, 3) : 2; + clamp(+this.initialState_['version'], 2, 3) : 2; } var mapId = this.ngeoLocation_.getParam('map_id'); if (mapId === undefined && diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/Themes.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/Themes.js index 8d922e287..f12580d67 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/Themes.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/Themes.js @@ -8,24 +8,26 @@ */ import appModule from './module.js'; -import olBase from 'ol.js'; -import olArray from 'ol/array.js'; + +import {extend as arrayExtend} from 'ol/array.js'; import olEventsEventTarget from 'ol/events/EventTarget.js'; import appEventsThemesEventType from './events/ThemesEventType.js'; +import {inherits} from 'ol/index.js'; + /** * @constructor * @extends {ol.events.EventTarget} * @param {angular.$window} $window Window. * @param {angular.$http} $http Angular http service. - * @param {string} treeUrl URL to "themes" web service. + * @param {string} gmfTreeUrl URL to "themes" web service. * @param {string} isThemePrivateUrl URL to check if theme is public. * @param {app.GetWmtsLayer} appGetWmtsLayer Get WMTS layer function. * @param {app.backgroundlayer.BlankLayer} appBlankLayer Blank Layer service. * @param {app.GetDevice} appGetDevice The device service. * @ngInject */ -const exports = function($window, $http, treeUrl, isThemePrivateUrl, +const exports = function($window, $http, gmfTreeUrl, isThemePrivateUrl, appGetWmtsLayer, appBlankLayer, appGetDevice) { olEventsEventTarget.call(this); @@ -57,7 +59,7 @@ const exports = function($window, $http, treeUrl, isThemePrivateUrl, * @type {string} * @private */ - this.treeUrl_ = treeUrl; + this.treeUrl_ = gmfTreeUrl; /** * @type {string} @@ -70,9 +72,11 @@ const exports = function($window, $http, treeUrl, isThemePrivateUrl, * @private */ this.promise_ = null; + + this.flatCatalog = null; }; -olBase.inherits(exports, olEventsEventTarget); +inherits(exports, olEventsEventTarget); /** @@ -119,7 +123,7 @@ exports.prototype.getBgLayers = function() { */ (function(data) { var bgLayers = data['background_layers'].map(function(item) { - var hasRetina = item['metadata']['hasRetina'] === 'true' && this.isHiDpi_; + var hasRetina = !!item['metadata']['hasRetina'] && this.isHiDpi_; console.assert('name' in item); console.assert('imageType' in item); var layer = this.getWmtsLayer_( @@ -162,20 +166,12 @@ exports.prototype.getThemeObject = function(themeName) { /** - * Get an array of theme objects. + * Get the promise resolving to the themes root object. * @return {angular.$q.Promise} Promise. */ -exports.prototype.getThemesObject = function() { +exports.prototype.getThemesPromise = function() { console.assert(this.promise_ !== null); - return this.promise_.then( - /** - * @param {app.ThemesResponse} data The "themes" web service response. - * @return {Array.} The themes object. - */ - function(data) { - var themes = data['themes']; - return themes; - }); + return this.promise_; }; @@ -188,15 +184,21 @@ exports.prototype.loadThemes = function(roleId) { this.promise_ = this.$http_.get(this.treeUrl_, { params: (roleId !== undefined) ? {'role': roleId} : {}, cache: false - }).then( - /** - * @param {angular.$http.Response} resp Ajax response. - * @return {Object} The "themes" web service response. - */ - (function(resp) { - this.dispatchEvent(appEventsThemesEventType.LOAD); - return /** @type {app.ThemesResponse} */ (resp.data); - }).bind(this)); + }).then((resp) => { + const root = /** @type {app.ThemesResponse} */ (resp.data); + const themes = root.themes; + const flatCatalogue = []; + for (var i = 0; i < themes.length; i++) { + const theme = themes[i]; + const children = this.getAllChildren_(theme.children, theme.name, root.ogcServers); + arrayExtend(flatCatalogue, children); + } + + this.flatCatalog = flatCatalogue; + + this.dispatchEvent(appEventsThemesEventType.LOAD); + return root; + }); return this.promise_; }; @@ -217,20 +219,28 @@ exports.prototype.isThemePrivate = function(themeId) { /** * @param {Array} element The element. * @param {string} theme Theme name. + * @param {Object} ogcServers All OGC servers definitions. + * @param {Object} lastOgcServer The last OGC server. * @return {Array} array The children. * @private */ -exports.prototype.getAllChildren_ = function(element, theme) { +exports.prototype.getAllChildren_ = function(elements, theme, ogcServers, lastOgcServer) { var array = []; - for (var i = 0; i < element.length; i++) { - if (element[i].hasOwnProperty('children')) { - olArray.extend(array, this.getAllChildren_( - element[i].children, theme) + for (var i = 0; i < elements.length; i++) { + const element = elements[i]; + if (element.hasOwnProperty('children')) { + arrayExtend(array, this.getAllChildren_( + element.children, theme, ogcServers, element.ogcServer || lastOgcServer) ); } else { - // element[i].id = element[i].id; - element[i].theme = theme; - array.push(element[i]); + // Rewrite url to match the behaviour of c2cgeoportal 1.6 + const ogcServer = element.ogcServer || lastOgcServer; + if (ogcServer) { + const def = ogcServers[ogcServer]; + element.url = def.credential ? null : def.url; + } + element.theme = theme; + array.push(element); } } return array; @@ -242,17 +252,7 @@ exports.prototype.getAllChildren_ = function(element, theme) { * @return {angular.$q.Promise} Promise. */ exports.prototype.getFlatCatalog = function() { - return this.getThemesObject().then( - function(themes) { - var flatCatalogue = []; - for (var i = 0; i < themes.length; i++) { - var theme = themes[i]; - olArray.extend(flatCatalogue, - this.getAllChildren_(theme.children, theme.name) - ); - } - return flatCatalogue; - }.bind(this)); + return this.promise_.then(() => this.flatCatalog); }; appModule.service('appThemes', exports); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/WmsHelper.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/WmsHelper.js index 563b20b70..4f98d91ed 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/WmsHelper.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/WmsHelper.js @@ -13,10 +13,11 @@ import ngeoMiscDecorate from 'ngeo/misc/decorate.js'; import olFormatWMSCapabilities from 'ol/format/WMSCapabilities.js'; import olLayerImage from 'ol/layer/Image.js'; import olLayerTile from 'ol/layer/Tile.js'; -import olProj from 'ol/proj.js'; +import {get as getProjection} from 'ol/proj.js'; import olSourceImageWMS from 'ol/source/ImageWMS.js'; import olSourceTileWMS from 'ol/source/TileWMS.js'; -import olBase from 'ol.js'; +import {getUid} from 'ol/index.js'; + /** * @constructor @@ -165,7 +166,7 @@ exports.prototype.buildChildLayers_ = function(wms, layer, wmsVersion, if (!layer['Name']) { layer['isInvalid'] = true; } - layer['uid'] = olBase.getUid(layer).toString(); + layer['uid'] = getUid(layer).toString(); if (!layer['isInvalid']) { layer['wmsUrl'] = wms; layer['wmsVersion'] = wmsVersion; @@ -478,9 +479,9 @@ exports.prototype.createWmsLayers = function(map, layer) { }); } if (has3857) { - newLayer.getSource().set('olcs.projection', olProj.get('EPSG:3857')); + newLayer.getSource().set('olcs.projection', getProjection('EPSG:3857')); } else if (hasWGS84) { - newLayer.getSource().set('olcs.projection', olProj.get('EPSG:4326')); + newLayer.getSource().set('olcs.projection', getProjection('EPSG:4326')); } newLayer.set('label', layer['Title']); var curMatadata = {'isExternalWms': true, diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/WmtsHelper.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/WmtsHelper.js index b6d290d75..4a77972b7 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/WmtsHelper.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/WmtsHelper.js @@ -13,7 +13,8 @@ import ngeoMiscDecorate from 'ngeo/misc/decorate.js'; import olFormatWMTSCapabilities from 'ol/format/WMTSCapabilities.js'; import olLayerTile from 'ol/layer/Tile.js'; import olSourceWMTS from 'ol/source/WMTS.js'; -import olBase from 'ol.js'; +import {getUid} from 'ol/index.js'; + /** * @constructor @@ -147,7 +148,7 @@ exports.prototype.buildChildLayers_ = function(wmts, capabilities) { var options = olSourceWMTS.optionsFromCapabilities(capabilities, wmtsConfig); layer['options'] = options; layer['isInvalid'] = false; - layer['uid'] = olBase.getUid(layer).toString(); + layer['uid'] = getUid(layer).toString(); if (!layer['isInvalid']) { layer['wmtsUrl'] = wmts; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/apps/Controllermain.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/apps/Controllermain.js new file mode 100644 index 000000000..02ebc15c2 --- /dev/null +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/apps/Controllermain.js @@ -0,0 +1,1069 @@ +/** + * @module app.apps.Controllermain + */ +/** + * @fileoverview This file defines the controller class for the application's + * main controller (created using "ng-controller" in the page). + * + * In particular, this controller creates the OpenLayers map, and makes it + * available in the controller for use from other parts (directives) of the + * application. It also defines the behavior of elements of the HTML page (the + * management of the sidebar for example). + */ + +import 'jquery'; +import 'bootstrap'; +import 'angular'; +import 'angular-gettext'; +import 'angular-dynamic-locale'; + +import appModule from '../module.js'; +import appLocationControl from '../LocationControl.js'; +import appMap from '../Map.js'; +import olFeature from 'ol/Feature.js'; +import olGeomPoint from 'ol/geom/Point.js'; +import {defaults as interactionDefaults} from 'ol/interaction.js'; +import LayerGroup from 'ol/layer/Group'; +import olLayerVector from 'ol/layer/Vector.js'; +import ngeoMiscSyncArrays from 'ngeo/misc/syncArrays.js'; +import olView from 'ol/View.js'; +import olControlAttribution from 'ol/control/Attribution.js'; +import olControlFullScreen from 'ol/control/FullScreen.js'; +import olControlOverviewMap from 'ol/control/OverviewMap.js'; +import olControlZoom from 'ol/control/Zoom.js'; +import appOlcsZoomToExtent from '../olcs/ZoomToExtent.js'; +import appOlcsLux3DManager from '../olcs/Lux3DManager.js'; +import {transform, transformExtent} from 'ol/proj.js'; +import {toRadians} from 'ol/math.js'; + +import '../../less/geoportailv3.less' + + /* eslint-disable no-unused-vars */ + import appAskredirectAskredirectDirective from '../askredirect/askredirectDirective.js'; + import appAskredirectAskredirectController from '../askredirect/AskredirectController.js'; + import appAuthenticationAuthenticationDirective from '../authentication/authenticationDirective.js'; + import appAuthenticationAuthenticationController from '../authentication/AuthenticationController.js'; + import appBackgroundlayerBackgroundlayerDirective from '../backgroundlayer/backgroundlayerDirective.js'; + import appBackgroundlayerBackgroundlayerController from '../backgroundlayer/BackgroundlayerController.js'; + import appBackgroundlayerBlankLayer from '../backgroundlayer/BlankLayer.js'; + import appCatalogCatalogController from '../catalog/CatalogController.js'; + import appCatalogCatalogDirective from '../catalog/catalogDirective.js'; + import appDrawDrawDirective from '../draw/drawDirective.js'; + import appDrawDrawController from '../draw/DrawController.js'; + import appDrawDrawnFeatures from '../draw/DrawnFeatures.js'; + import appDrawFeatureHash from '../draw/FeatureHash.js'; + import appDrawFeaturePopup from '../draw/FeaturePopup.js'; + import appDrawFeaturePopupController from '../draw/FeaturePopupController.js'; + import appDrawFeaturePopupDirective from '../draw/featurePopupDirective.js'; + import appDrawRouteControl from '../draw/RouteControl.js'; + + //const appDrawRouteControlOptions = goog.require('app.draw.RouteControlOptions'); + import appDrawSelectedFeatures from '../draw/SelectedFeaturesService.js'; + + import appDrawStyleEditingController from '../draw/StyleEditingController.js'; + import appDrawStyleEditingDirective from '../draw/styleEditingDirective.js'; + import appDrawSymbolSelectorController from '../draw/SymbolSelectorController.js'; + import appDrawSymbolSelectorDirective from '../draw/symbolSelectorDirective.js'; + import appExclusionManager from '../ExclusionManager.js'; + import appExternaldataExternalDataDirective from '../externaldata/externalDataDirective.js'; + import appExternaldataExternalDataController from '../externaldata/ExternalDataController.js'; + import appFeedbackFeedbackDirective from '../feedback/feedbackDirective.js'; + import appFeedbackFeedbackController from '../feedback/FeedbackController.js'; + import appInfobarElevationDirective from '../infobar/elevationDirective.js'; + import appInfobarElevationController from '../infobar/ElevationController.js'; + import appInfobarInfobarController from '../infobar/InfobarController.js'; + import appInfobarInfobarDirective from '../infobar/infobarDirective.js'; + import appInfobarProjectionselectorDirective from '../infobar/projectionselectorDirective.js'; + import appInfobarProjectionselectorController from '../infobar/ProjectionselectorController.js'; + import appInfobarScalelineDirective from '../infobar/scalelineDirective.js'; + import appInfobarScalelineController from '../infobar/ScalelineController.js'; + import appInfobarScaleselectorDirective from '../infobar/scaleselectorDirective.js'; + import appInfobarScaleselectorController from '../infobar/ScaleselectorController.js'; + import appLayerinfoLayerinfoDirective from '../layerinfo/layerinfoDirective.js'; + import appLayerinfoLayerinfoController from '../layerinfo/LayerinfoController.js'; + import appLocationinfoLocationInfoOverlay from '../locationinfo/LocationInfoOverlay.js'; + import appLayerinfoShowLayerinfo from '../layerinfo/ShowLayerinfoFactory.js'; + import appLayermanagerLayermanagerDirective from '../layermanager/layermanagerDirective.js'; + import appLayermanagerLayermanagerController from '../layermanager/LayermanagerController.js'; + import appLayerlegendsLayerlegendsDirective from '../layerlegends/layerlegendsDirective.js'; + import appLayerlegendsLayerlegendsController from '../layerlegends/LayerlegendsController.js'; + import appLocationinfoLocationinfoDirective from '../locationinfo/locationinfoDirective.js'; + import appLocationinfoLocationinfoController from '../locationinfo/LocationinfoController.js'; + import appLotChasse from '../LotChasse.js'; + import appMapMapDirective from '../map/mapDirective.js'; + import appMapMapController from '../map/MapController.js'; + import appMainController from '../apps/Controllermain.js'; + import appMymapsFilereaderDirective from '../mymaps/filereaderDirective.js'; + import appMeasureMeasureController from '../measure/MeasureController.js'; + import appMeasureMeasureDirective from '../measure/MeasureDirective.js'; + import appMymapsMymapsDirective from '../mymaps/mymapsDirective.js'; + import appMymapsMymapsController from '../mymaps/MymapsController.js'; + import appNotify from '../NotifyFactory.js'; + import appPrintPrintDirective from '../print/printDirective.js'; + import appPrintPrintController from '../print/PrintController.js'; + import appPrintPrintservice from '../print/Printservice.js'; + import appProfileProfileDirective from '../profile/profileDirective.js'; + import appProfileProfileController from '../profile/ProfileController.js'; + import appQueryPagreportDirective from '../query/pagreportDirective.js'; + import appQueryPagreportController from '../query/PagreportController.js'; + import appQueryCasiporeportDirective from '../query/casiporeportDirective.js'; + import appQueryCasiporeportController from '../query/CasiporeportController.js'; + import appQueryPdsreportDirective from '../query/pdsreportDirective.js'; + import appQueryPdsreportController from '../query/PdsreportController.js'; + + //const appQueryQueryStyles = goog.require('app.query.QueryStyles'); + import appQueryQueryDirective from '../query/queryDirective.js'; + + import appQueryQueryController from '../query/QueryController.js'; + import appResizemapDirective from '../resizemapDirective.js'; + import appRoutingRoutingController from '../routing/RoutingController.js'; + import appRoutingRoutingDirective from '../routing/routingDirective.js'; + import appSearchSearchDirective from '../search/searchDirective.js'; + import appSearchSearchController from '../search/SearchController.js'; + import appShareShareDirective from '../share/ShareDirective.js'; + import appShareShareController from '../share/ShareController.js'; + import appShareShorturlDirective from '../share/shorturlDirective.js'; + import appShareShorturlController from '../share/ShorturlController.js'; + import appSliderSliderDirective from '../slider/SliderDirective.js'; + import appSliderSliderController from '../slider/SliderController.js'; + import appStreetviewStreetviewDirective from '../streetview/streetviewDirective.js'; + import appStreetviewStreetviewController from '../streetview/StreetviewController.js'; + import appThemeswitcherThemeswitcherDirective from '../themeswitcher/themeswitcherDirective.js'; + import appThemeswitcherThemeswitcherController from '../themeswitcher/ThemeswitcherController.js'; + import appActivetool from '../Activetool.js'; + import appCoordinateString from '../CoordinateStringService.js'; + import appExport from '../Export.js'; + import appGeocoding from '../Geocoding.js'; + import appGetDevice from '../GetDevice.js'; + import appGetElevation from '../GetElevationService.js'; + import appGetLayerForCatalogNode from '../GetLayerForCatalogNodeFactory.js'; + import appGetProfile from '../GetProfileService.js'; + import appGetShorturl from '../GetShorturlService.js'; + import appGetWmsLayer from '../GetWmsLayerFactory.js'; + import appGetWmtsLayer from '../GetWmtsLayerFactory.js'; + import appLayerOpacityManager from '../LayerOpacityManager.js'; + import appLayerPermalinkManager from '../LayerPermalinkManager.js'; + + // const appLocationControlOptions = goog.require('app.LocationControlOptions'); + //const appMapsResponse = goog.require('app.MapsResponse'); + import appMymaps from '../Mymaps.js'; + + import appMymapsOffline from '../MymapsOffline.js'; + import appOlcsToggle3d from '../olcs/toggle3d.js'; + import appOlcsExtent from '../olcs/Extent.js'; + import appProjections from '../projections.js'; + import appRouting from '../Routing.js'; + import appScalesService from '../ScalesService.js'; + import appStateManager from '../StateManager.js'; + import appTheme from '../Theme.js'; + import appThemes from '../Themes.js'; + + //const appThemesResponse = goog.require('app.ThemesResponse'); + import appUserManager from '../UserManager.js'; + + import appWmsHelper from '../WmsHelper.js'; + import appWmtsHelper from '../WmtsHelper.js'; + import appMiscFile from '../misc/file.js'; + + import OfflineDownloader from '../OfflineDownloader.js'; + import OfflineRestorer from '../OfflineRestorer.js'; + /* eslint-enable no-unused-vars */ + + +/** + * @param {angular.Scope} $scope Scope. + * @param {ngeo.map.FeatureOverlayMgr} ngeoFeatureOverlayMgr Feature overlay + * manager. + * @param {ngeo.map.BackgroundLayerMgr} ngeoBackgroundLayerMgr Background layer + * manager. + * @param {ngeo.offline.ServiceManager} ngeoOfflineServiceManager offline service manager service. + * @param {angularGettext.Catalog} gettextCatalog Gettext catalog. + * @param {app.ExclusionManager} appExclusionManager Exclusion manager service. + * @param {app.LayerOpacityManager} appLayerOpacityManager Layer opacity. + * @param {app.LayerPermalinkManager} appLayerPermalinkManager Permalink + * service. + * @param {app.Mymaps} appMymaps Mymaps service. + * @param {app.StateManager} appStateManager The state service. + * @param {app.Themes} appThemes Themes service. + * @param {app.Theme} appTheme the current theme service. + * @param {app.UserManager} appUserManager The user manager service. + * @param {app.draw.DrawnFeatures} appDrawnFeatures Drawn features service. + * @param {Object.} langUrls URLs to translation files. + * @param {Array.} maxExtent Constraining extent. + * @param {Array.} defaultExtent Default geographical extent. + * @param {ngeo.statemanager.Location} ngeoLocation ngeo location service. + * @param {app.Export} appExport The export GPX/KML service. + * @param {app.GetDevice} appGetDevice The device service. + * @param {boolean} appOverviewMapShow Add or not the overview control. + * @param {string} appOverviewMapBaseLayer The layer displayed in overview. + * @param {app.Notify} appNotify Notify service. + * @param {angular.$window} $window Window. + * @param {app.draw.SelectedFeatures} appSelectedFeatures Selected features service. + * @param {angular.$locale} $locale The locale service. + * @param {app.Routing} appRouting The routing service. + * @param {Document} $document Document. + * @param {string} cesiumURL The Cesium script URL. + * @param {angular.Scope} $rootScope Angular root scope. + * @param {ngeo.olcs.Service} ngeoOlcsService The service. + * @param {Array} tiles3dLayers 3D tiles layers. + * @param {string} tiles3dUrl 3D tiles server url. + * @param {ngeo.offline.NetworkStatus} ngeoNetworkStatus ngeo network status service. + * @param {ngeo.offline.Mode} ngeoOfflineMode Offline mode manager. + * @constructor + * @export + * @ngInject + */ +const MainController = function( + $scope, ngeoFeatureOverlayMgr, ngeoBackgroundLayerMgr, ngeoOfflineServiceManager, + gettextCatalog, appExclusionManager, appLayerOpacityManager, + appLayerPermalinkManager, appMymaps, appStateManager, appThemes, appTheme, + appUserManager, appDrawnFeatures, langUrls, maxExtent, defaultExtent, + ngeoLocation, appExport, appGetDevice, + appOverviewMapShow, appOverviewMapBaseLayer, appNotify, $window, + appSelectedFeatures, $locale, appRouting, $document, cesiumURL, + $rootScope, ngeoOlcsService, tiles3dLayers, tiles3dUrl, ngeoNetworkStatus, ngeoOfflineMode, + appOfflineDownloader, appOfflineRestorer) { + /** + * @type {boolean} + * @export + */ + this.activeLayersComparator = false; + + /** + * @type {Document} + * @private + */ + this.$document_ = $document; + + /** + * @type {app.Routing} + * @export + */ + this.appRouting_ = appRouting; + + /** + * @type {angular.$locale} + * @private + */ + this.locale_ = $locale; + + /** + * @type {ol.Collection} + * @private + */ + this.selectedFeatures_ = appSelectedFeatures; + + /** + * @type {angular.$window} + * @private + */ + this.window_ = $window; + + /** + * @type {app.Notify} + * @private + */ + this.notify_ = appNotify; + + /** + * @private + * @type {app.GetDevice} + */ + this.appGetDevice_ = appGetDevice; + + /** + * @type {app.Export} + * @private + */ + this.appExport_ = appExport; + + /** + * @type {ngeo.statemanager.Location} + * @private + */ + this.ngeoLocation_ = ngeoLocation; + + /** + * @type {ngeo.map.BackgroundLayerMgr} + * @private + */ + this.backgroundLayerMgr_ = ngeoBackgroundLayerMgr; + + /** + * @type {app.draw.DrawnFeatures} + * @private + */ + this.drawnFeatures_ = appDrawnFeatures; + + /** + * @type {app.UserManager} + * @private + */ + this.appUserManager_ = appUserManager; + + /** + * @type {angular.Scope} + * @private + */ + this.scope_ = $scope; + + /** + * @type {app.StateManager} + * @private + */ + this.stateManager_ = appStateManager; + + /** + * @type {app.Themes} + * @private + */ + this.appThemes_ = appThemes; + + /** + * @type {app.Theme} + * @private + */ + this.appTheme_ = appTheme; + + /** + * @type {ngeo.offline.NetworkStatus} + * @private + */ + this.networkStatus_ = ngeoNetworkStatus; + + /** + * @type {ngeo.offline.Mode} + * @export + */ + this.offlineMode = ngeoOfflineMode; + + /** + * @private + * @type {Array} + */ + this.tiles3dLayers_ = tiles3dLayers; + + /** + * @private + * @type {string} + */ + this.tiles3dUrl_ = tiles3dUrl; + + /** + * @type {ngeo.offline.NetworkStatus} + * @export + */ + this.ngeoNetworkStatus = ngeoNetworkStatus; + + /** + * @type {ol.Extent} + * @private + */ + this.maxExtent_ = + transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); + + /** + * @type {angularGettext.Catalog} + * @private + */ + this.gettextCatalog_ = gettextCatalog; + + /** + * @type {Object.} + * @private + */ + this.langUrls_ = langUrls; + + /** + * @type {Array.} + * @private + */ + this.defaultExtent_ = defaultExtent; + + /** + * @type {boolean} + */ + this['hasRoutingResult'] = false; + + /** + * @type {boolean} + */ + this['sidebarActive'] = false; + + /** + * @type {boolean} + */ + this['languageOpen'] = false; + + /** + * @type {boolean} + */ + this['drawOpen'] = false; + + /** + * @type {boolean} + */ + this['drawOpenMobile'] = false; + + /** + * @type {boolean} + */ + this['infosOpen'] = false; + + /** + * @type {boolean} + */ + this['feedbackOpen'] = false; + + /** + * @type {boolean} + */ + this['legendsOpen'] = false; + + /** + * @type {boolean} + */ + this['routingOpen'] = false; + + /** + * @type {boolean} + */ + this['layersOpen'] = false; + + /** + * @type {boolean} + */ + this['measureOpen'] = false; + + /** + * @type {boolean} + */ + this['mymapsOpen'] = false; + + /** + * @type {boolean} + */ + this['printOpen'] = false; + + /** + * @type {boolean} + */ + this['shareOpen'] = false; + + /** + * @type {boolean} + */ + this['shareMymapsChecked'] = false; + + /** + * @type {boolean} + */ + this['shareShowLongUrl'] = false; + + /** + * @type {boolean} + */ + this['userOpen'] = false; + + /** + * @type {boolean} + */ + this['infosHiddenContent'] = false; + + /** + * @type {boolean} + */ + this['showRedirect'] = false; + + /** + * @type {string|undefined} + */ + this['infosAppSelector'] = undefined; + + /** + * @type {Array} + */ + this['selectedLayers'] = []; + + /** + * Set to true to display the change icon in Mymaps. + * @type {boolean} + */ + this['layersChanged'] = false; + + const initial3dTilesVisibleValue = appStateManager.getInitialValue('3dtiles_visible'); + + /** + * @export + */ + this.debugOffline = ngeoLocation.hasParam('debugOffline'); + + /** + * True if no initial state is defined. + * @type {boolean} + * @export + */ + this.tiles3dVisible = initial3dTilesVisibleValue !== undefined ? initial3dTilesVisibleValue === 'true' : true; + + /** + * @type {app.Mymaps} + * @private + */ + this.appMymaps_ = appMymaps; + this.appUserManager_.getUserInfo(); + + /** + * @const {!app.Map} + * @private + */ + this.map_ = this.createMap_(); + + /** + * @const {?app.olcs.Lux3DManager} + * @export + */ + this.ol3dm_ = this.createCesiumManager_(cesiumURL, $rootScope); + this.ol3dm_.on('load', () => { + this.ol3dm_.init3dTiles(this.tiles3dVisible); + }); + + ngeoOlcsService.initialize(this.ol3dm_); + $scope.$watch(() => this.is3dEnabled(), this.enable3dCallback_.bind(this)); + this.map_.set('ol3dm', this.ol3dm_); + + // Add the zoom to extent control in a second step since it depends on ol3dm. + this.map_.addControl(new appOlcsZoomToExtent(this.defaultExtent_, this.ol3dm_)); + + this.initLanguage_(); + + this.initMymaps_(); + + this.manageSelectedLayers_($scope); + + appExclusionManager.init(this.map_); + appLayerOpacityManager.init(this.map_); + ngeoFeatureOverlayMgr.init(this.map_); + appLayerPermalinkManager.init($scope, this.map_, this['selectedLayers']); + $scope.$watch(function() { + return appLayerPermalinkManager.hasUnavailableLayers(); + }.bind(this), function(newVal, oldVal) { + if (newVal !== null && oldVal !== null && newVal !== oldVal && newVal === true) { + this['userOpen'] = true; + } + }.bind(this)); + + this.appExport_.init(this.map_); + + this.addLocationControl_(ngeoFeatureOverlayMgr); + + this.manageUserRoleChange_($scope); + this.loadThemes_().then(function() { + this.appThemes_.getBgLayers().then( + function(bgLayers) { + if (appOverviewMapShow) { + var layer = /** @type {ol.layer.Base} */ + (bgLayers.find(function(layer) { + return layer.get('label') === appOverviewMapBaseLayer; + })); + this.map_.addControl( + new olControlOverviewMap( + {layers: [layer], + collapseLabel: '\u00BB', + label: '\u00AB'})); + } + }.bind(this)); + var urlLocationInfo = appStateManager.getInitialValue('crosshair'); + var infoOpen = urlLocationInfo !== undefined && urlLocationInfo !== null && + urlLocationInfo === 'true'; + this['layersOpen'] = (!this.appGetDevice_.testEnv('xs') && + !this['routingOpen'] && + this.ngeoLocation_.getParam('map_id') === undefined && + !infoOpen && + this.stateManager_.getValueFromLocalStorage('layersOpen') !== 'false') ? + true : false; + this['mymapsOpen'] = (!this.appGetDevice_.testEnv('xs') && + this.ngeoLocation_.getParam('map_id') !== undefined && + !infoOpen) ? true : false; + $scope.$watch(function() { + return this['layersOpen']; + }.bind(this), function(newVal) { + if (newVal === false) { + $('app-catalog .themes-switcher').collapse('show'); + $('app-themeswitcher #themes-content').collapse('hide'); + } + }.bind(this)); + this.activeLayersComparator = (this.ngeoLocation_.getParam('lc') === 'true'); + + $scope.$watch(function() { + return this.sidebarOpen(); + }.bind(this), function(newVal) { + this.stateManager_.updateStorage({ + 'layersOpen': newVal + }); + if (this['mymapsOpen'] && this.appGetDevice_.testEnv('xs') && + this.selectedFeatures_.getLength() > 0) { + var feature = this.selectedFeatures_.getArray()[0]; + feature.set('__refreshProfile__', true); + } + }.bind(this)); + + this.appThemes_.getThemeObject( + this.appTheme_.getCurrentTheme()).then(function() { + var zoom = Number(appStateManager.getInitialValue('zoom')); + if (zoom > 19) { + this.map_.getView().setZoom(zoom); + } + }.bind(this)); + }.bind(this)); + var waypoints = appStateManager.getInitialValue('waypoints'); + if (waypoints !== undefined && waypoints !== null) { + this['routingOpen'] = true; + var criteria = parseInt(appStateManager.getInitialValue('criteria'), 10); + var transportMode = parseInt( + appStateManager.getInitialValue('transportMode'), 10); + this.appRouting_.criteria = criteria; + this.appRouting_.transportMode = transportMode; + var coordinates = waypoints.split(','); + var i = 0; + var routeNumber = 1; + this.appRouting_.routesOrder.splice(0, this.appRouting_.routesOrder.length); + for (i = 0; i < coordinates.length; i = i + 2) { + var position = [ + parseFloat(coordinates[i + 1]), parseFloat(coordinates[i])]; + var feature = new olFeature({ + geometry: new olGeomPoint((transform(position, 'EPSG:4326', 'EPSG:3857'))) + }); + feature.set('label', '' + routeNumber); + this.appRouting_.insertFeatureAt(feature, routeNumber); + this.appRouting_.routesOrder.push(routeNumber - 1); + routeNumber++; + } + if (i > 1) { + var labels = appStateManager.getInitialValue('labels'); + this.appRouting_.routes = labels.split('||'); + this.appRouting_.getRoute(); + } + } + + $scope.$watch(this.isDisconnectedOrOffline.bind(this), (offline) => { + if (offline) { + if (this.sidebarOpen() && !this['layersOpen'] && !this['mymapsOpen']) { + this.closeSidebar(); + this['layersOpen'] = true; + } + this.showTab('a[href=\'#mylayers\']'); + } + }); + + ngeoOfflineServiceManager.setSaveService(appOfflineDownloader); + ngeoOfflineServiceManager.setRestoreService(appOfflineRestorer); +}; + + +/** + * @private + * @param {boolean} active 3d state + */ +MainController.prototype.enable3dCallback_ = function(active) { + if (!active) { + return; + } + var piwik = /** @type {Piwik} */ (this.window_['_paq']); + piwik.push(['setDocumentTitle', 'enable3d']); + piwik.push(['trackPageView']); + + this['drawOpen'] = false; + this['drawOpenMobile'] = false; + this['measureOpen'] = false; + this['printOpen'] = false; +}; + +/** + * @param {ngeo.map.FeatureOverlayMgr} featureOverlayMgr Feature overlay manager. + * @private + */ +MainController.prototype.addLocationControl_ = function(featureOverlayMgr) { + var isActive = false; + var activateGeoLocation = this.ngeoLocation_.getParam('tracking'); + if (activateGeoLocation && 'true' === activateGeoLocation) { + isActive = true; + this.ngeoLocation_.deleteParam('tracking'); + } + var locationControl = new appLocationControl(/** @type {app.LocationControlOptions} */({ + label: '\ue800', + featureOverlayMgr: featureOverlayMgr, + notify: this.notify_, + gettextCatalog: this.gettextCatalog_, + scope: this.scope_, + window: this.window_ + })); + this.map_.addControl(locationControl); + if (isActive) { + this.map_.once('change:view', (e) => { + locationControl.handleCenterToLocation(); + }); + } + }; + + +/** + * @private + * @return {!app.Map} The extended ol.Map. + */ +MainController.prototype.createMap_ = function() { + var interactions = interactionDefaults({ + altShiftDragRotate: false, + pinchRotate: false, + constrainResolution: true + }); + var map = this['map'] = new appMap({ + logo: false, + controls: [ + new olControlZoom({zoomInLabel: '\ue032', zoomOutLabel: '\ue033'}), + // the zoom to extent control will be added later since it depends on ol3dm + new olControlFullScreen({label: '\ue01c', labelActive: '\ue02c'}), + new olControlAttribution({collapsible: false, + collapsed: false, className: 'geoportailv3-attribution'}) + ], + interactions: interactions, + keyboardEventTarget: document, + loadTilesWhileInteracting: true, + loadTilesWhileAnimating: true, + view: new olView({ + maxZoom: 19, + minZoom: 8, + enableRotation: false, + extent: this.maxExtent_ + }) + }); + return map; +}; + + +/** + * @private + * @param {string} cesiumURL The Cesium URL + * @param {angular.Scope} $rootScope The root scope + * @return {!app.olcs.Lux3DManager} The created manager. + */ +MainController.prototype.createCesiumManager_ = function(cesiumURL, $rootScope) { + // [minx, miny, maxx, maxy] + console.assert(this.map_ !== null && this.map_ !== undefined); + const cameraExtentInRadians = [5.31, 49.38, 6.64, 50.21].map(toRadians); + return new appOlcsLux3DManager(cesiumURL, cameraExtentInRadians, this.map_, this.ngeoLocation_, + $rootScope, this.tiles3dLayers_, this.tiles3dUrl_); +}; + + +/** + * @export + * @return {boolean} Whether 3D is active. + */ +MainController.prototype.is3dEnabled = function() { + return this.ol3dm_.is3dEnabled(); +}; + + +/** + * Register a watcher on "roleId" to reload the themes when the role id + * changes. + * @param {angular.Scope} scope Scope. + * @private + */ +MainController.prototype.manageUserRoleChange_ = function(scope) { + scope.$watch(function() { + return this.appUserManager_.roleId; + }.bind(this), function(newVal, oldVal) { + if (newVal === null && oldVal === null) { + // This happens at init time. We don't want to reload the themes + // at this point, as the constructor already loaded them. + return; + } + this.loadThemes_(); + if (this.appMymaps_.isMymapsSelected()) { + this.appMymaps_.loadMapInformation(); + } + }.bind(this)); +}; + + +/** + * @private + * @return {?angular.$q.Promise} Promise. + */ +MainController.prototype.loadThemes_ = function() { + return this.appThemes_.loadThemes(this.appUserManager_.roleId); +}; + + +/** + * @param {angular.Scope} scope Scope + * @private + */ +MainController.prototype.manageSelectedLayers_ = + function(scope) { + ngeoMiscSyncArrays( + this.map_.getLayers().getArray(), + this['selectedLayers'], true, scope, + function(layer) { + if (layer instanceof olLayerVector && layer.get('altitudeMode') === 'clampToGround') { + return false; + } + if (layer instanceof LayerGroup && layer.get('groupName') === 'background') { + return false; + } + return this.map_.getLayers().getArray().indexOf(layer) !== 0; + }.bind(this) + ); + scope.$watchCollection(function() { + return this['selectedLayers']; + }.bind(this), function(newSelectedLayers, oldSelectedLayers) { + this.map_.render(); + this.compareLayers_(); + + if (newSelectedLayers.length > oldSelectedLayers.length) { + var nbLayersAdded = + newSelectedLayers.length - oldSelectedLayers.length; + for (var i = 0; i < nbLayersAdded; i++) { + var layer = this['selectedLayers'][i]; + var piwik = /** @type {Piwik} */ (this.window_['_paq']); + piwik.push(['setDocumentTitle', + 'LayersAdded/' + layer.get('label') + ]); + piwik.push(['trackPageView']); + } + } + }.bind(this)); + }; + +/** + * @export + */ +MainController.prototype.openFeedback = function() { + if (this.sidebarOpen()) { + this.closeSidebar(); + this['feedbackOpen'] = true; + } else { + this['feedbackOpen'] = true; + } +}; + +/** + * @export + */ +MainController.prototype.closeSidebar = function() { + this['mymapsOpen'] = this['layersOpen'] = this['infosOpen'] = + this['feedbackOpen'] = this['legendsOpen'] = this['routingOpen'] = false; +}; + + +/** + * @return {boolean} `true` if the sidebar should be open, otherwise `false`. + * @export + */ +MainController.prototype.sidebarOpen = function() { + return this['mymapsOpen'] || this['layersOpen'] || this['infosOpen'] || + this['legendsOpen'] || this['feedbackOpen'] || this['routingOpen']; +}; + + +/** + * @param {string} lang Language code. + * @param {boolean=} track track page view + * @export + */ +MainController.prototype.switchLanguage = function(lang, track) { + if (typeof track !== 'boolean') { + track = true; + } + console.assert(lang in this.langUrls_); + this.gettextCatalog_.setCurrentLanguage(lang); + this.gettextCatalog_.loadRemote(this.langUrls_[lang]); + this.locale_.NUMBER_FORMATS.GROUP_SEP = ' '; + this['lang'] = lang; + + var piwik = /** @type {Piwik} */ (this.window_['_paq']); + piwik.push(['setCustomVariable', 1, 'Language', this['lang']]); + if (track) { + piwik.push(['trackPageView']); + } +}; + + +/** + * @return {string} the current theme. + * @export + */ +MainController.prototype.getCurrentTheme = function() { + return this.appTheme_.getCurrentTheme(); +}; + +/** + * @return {string} the current theme. + * @export + */ +MainController.prototype.getEncodedCurrentTheme = function() { + return this.appTheme_.encodeThemeName(this.appTheme_.getCurrentTheme()); +}; + +/** + * @private + */ +MainController.prototype.initLanguage_ = function() { + this.scope_.$watch(function() { + return this['lang']; + }.bind(this), function(newValue) { + this.stateManager_.updateState({ + 'lang': newValue + }); + }.bind(this)); + + var urlLanguage = /** @type {string|undefined} */ + (this.stateManager_.getInitialValue('lang')); + + if (urlLanguage !== undefined && urlLanguage in this.langUrls_) { + this.switchLanguage(urlLanguage, false); + return; + } else { + // if there is no information about language preference, + // fallback to french + this.switchLanguage('fr', false); + return; + } +}; + + +/** + * @private + */ +MainController.prototype.initMymaps_ = function() { + var mapId = this.ngeoLocation_.getParam('map_id'); + + this.appMymaps_.mapProjection = this.map_.getView().getProjection(); + if (mapId !== undefined) { + this.appMymaps_.setCurrentMapId(mapId, + this.drawnFeatures_.getCollection()).then( + function(features) { + var x = this.stateManager_.getInitialValue('X'); + var y = this.stateManager_.getInitialValue('Y'); + + if (x === undefined && y === undefined && + this.drawnFeatures_.getCollection().getLength() > 0) { + this.map_.getView().fit(this.drawnFeatures_.getExtent(), { + size: /** @type {ol.Size} */ (this.map_.getSize()) + }); + } + }.bind(this)); + } else { + this.appMymaps_.clear(); + } + this.appMymaps_.map = this.map_; + this.appMymaps_.layersChanged = this['layersChanged']; + this.map_.getLayerGroup().on('change', () => { + this.compareLayers_(); + }); +}; + + +/** + * Compare the layers of mymaps with selected layers + * and set layersChanged to true if there there is a difference + * between the displayed layers and the mymaps layers + * @private + */ +MainController.prototype.compareLayers_ = function() { + if (this.appMymaps_.isEditable()) { + this['layersChanged'] = false; + var backgroundLayer = this.backgroundLayerMgr_.get(this.map_); + if (backgroundLayer && + this.appMymaps_.mapBgLayer !== backgroundLayer.get('label')) { + this['layersChanged'] = true; + } else { + if (this['selectedLayers'].length !== this.appMymaps_.mapLayers.length) { + this['layersChanged'] = true; + } else { + var selectedLabels = []; + var selectedOpacities = []; + this['selectedLayers'].forEach(function(item) { + selectedLabels.push(item.get('label')); + selectedOpacities.push('' + item.getOpacity()); + }); + selectedLabels.reverse(); + selectedOpacities.reverse(); + if (selectedLabels.join(',') !== this.appMymaps_.mapLayers.join(',')) { + this['layersChanged'] = true; + } else { + if (selectedOpacities.join(',') !== + this.appMymaps_.mapLayersOpacities.join(',')) { + this['layersChanged'] = true; + } + } + } + } + } else { + this['layersChanged'] = false; + } +}; + + +/** + * @param {string} selector JQuery selector for the tab link. + * @export + */ +MainController.prototype.showTab = function(selector) { + $(selector).tab('show'); +}; + + +/** + * @export + */ +MainController.prototype.toggleThemeSelector = function() { + var layerTree = $('app-catalog .themes-switcher'); + var themesSwitcher = $('app-themeswitcher #themes-content'); + var themeTab = $('#catalog'); + if (this['layersOpen']) { + if (themesSwitcher.hasClass('in') && themeTab.hasClass('active')) { + this['layersOpen'] = false; + } else { + this.showTab('a[href=\'#catalog\']'); + themesSwitcher.collapse('show'); + layerTree.collapse('hide'); + } + } else { + this['layersOpen'] = true; + this.showTab('a[href=\'#catalog\']'); + themesSwitcher.collapse('show'); + layerTree.collapse('hide'); + } +}; + +/** + * @export + */ +MainController.prototype.toggleTiles3dVisibility = function() { + this.tiles3dVisible = !this.tiles3dVisible; + this.ol3dm_.set3dTilesetVisible(this.tiles3dVisible); + this.stateManager_.updateState({ + '3dtiles_visible': this.tiles3dVisible + }); + if (this.tiles3dVisible) { + var piwik = /** @type {Piwik} */ (this.window_['_paq']); + piwik.push(['setDocumentTitle', '3dtiles_visible']); + piwik.push(['trackPageView']); + } +}; + +/** + * Check if disconnected or offline mode enabled. + * @return {boolean} the state. + * @export + */ +MainController.prototype.isDisconnectedOrOffline = function() { + return this.offlineMode.isEnabled() || !!this.networkStatus_.isDisconnected(); +}; + +appModule.controller('MainController', MainController); + + +export default MainController; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/apps/main.html.ejs b/geoportal/geoportailv3_geoportal/static-ngeo/js/apps/main.html.ejs new file mode 100644 index 000000000..d240c036a --- /dev/null +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/apps/main.html.ejs @@ -0,0 +1,342 @@ + + + + + + + + + + + + " /> + + <% for (var css in htmlWebpackPlugin.files.css) { %> + + <% } %> + + + + + + + + + + + + +
+ +
+ +
+ +
+ + + +
+
+
+
+
+
+
{{mainCtrl.selectedLayers[0].get('label') | translate}}
+
+ + +
+
+ + + + <% for (var chunk in htmlWebpackPlugin.files.chunks) { %> + + <% } %> + + + + + + + + + diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/backgroundlayer/BackgroundlayerController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/backgroundlayer/BackgroundlayerController.js index 3b37e8081..b473c4a24 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/backgroundlayer/BackgroundlayerController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/backgroundlayer/BackgroundlayerController.js @@ -18,7 +18,7 @@ */ import appModule from '../module.js'; -import olEvents from 'ol/events.js'; +import {listen} from 'ol/events.js'; /** * @constructor @@ -46,7 +46,7 @@ const exports = function(ngeoBackgroundLayerMgr, appThemes) { this.setLayer(this['bgLayer']); }).bind(this)); - olEvents.listen(this.backgroundLayerMgr_, 'change', + listen(this.backgroundLayerMgr_, 'change', function() { this['bgLayer'] = this.backgroundLayerMgr_.get(this['map']); }, this); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/catalog/CatalogController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/catalog/CatalogController.js index 729ecfc07..fd338095a 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/catalog/CatalogController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/catalog/CatalogController.js @@ -19,8 +19,8 @@ import appModule from '../module.js'; import appEventsThemesEventType from '../events/ThemesEventType.js'; -import olEvents from 'ol/events.js'; -import olProj from 'ol/proj.js'; +import {listen} from 'ol/events.js'; +import {transformExtent} from 'ol/proj.js'; import olView from 'ol/View.js'; /** @@ -49,7 +49,7 @@ const exports = function($scope, appThemes, appTheme, * @private */ this.maxExtent_ = - olProj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); + transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); /** * @type {app.ScalesService} @@ -75,7 +75,7 @@ const exports = function($scope, appThemes, appTheme, */ this.getLayerFunc_ = appGetLayerForCatalogNode; - olEvents.listen(appThemes, appEventsThemesEventType.LOAD, + listen(appThemes, appEventsThemesEventType.LOAD, /** * @param {ol.events.Event} evt Event. */ @@ -132,7 +132,7 @@ exports.prototype.setThemeZooms = function(tree) { if (tree !== null) { console.assert('metadata' in tree); if (tree['metadata']['resolutions']) { - var resolutions = tree['metadata']['resolutions'].split(','); + var resolutions = tree['metadata']['resolutions']; maxZoom = resolutions.length + 7; } var map = this['map']; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawController.js index 4cbd29721..a0b86a38d 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawController.js @@ -20,24 +20,24 @@ import appInteractionDrawRoute from '../interaction/DrawRoute.js'; import appInteractionClipLine from '../interaction/ClipLine.js'; import appInteractionModifyCircle from '../interaction/ModifyCircle.js'; import appNotifyNotificationType from '../NotifyNotificationType.js'; -import ngeoInteractionMeasure from 'ngeo/interaction/Measure.js'; +import ngeoInteractionTranslate from 'ngeo/interaction/Translate.js'; import ngeoMiscDecorate from 'ngeo/misc/decorate.js'; import olCollectionEventType from 'ol/CollectionEventType.js'; import olFeature from 'ol/Feature.js'; -import olObject from 'ol/Object.js'; -import olObservable from 'ol/Observable.js'; +import {getChangeEventType} from 'ol/Object.js'; +import {unByKey} from 'ol/Observable.js'; import olOverlay from 'ol/Overlay.js'; -import olEvents from 'ol/events.js'; -import olExtent from 'ol/extent.js'; -import olProj from 'ol/proj.js'; +import {listen} from 'ol/events.js'; +import {getCenter} from 'ol/extent.js'; +import {transform} from 'ol/proj.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomLineString from 'ol/geom/LineString.js'; -import olGeomPolygon from 'ol/geom/Polygon.js'; -import olInteraction from 'ol/interaction.js'; +import {fromCircle} from 'ol/geom/Polygon.js'; import olInteractionDraw from 'ol/interaction/Draw.js'; import olInteractionModify from 'ol/interaction/Modify.js'; import olInteractionSelect from 'ol/interaction/Select.js'; -import olInteractionTranslate from 'ol/interaction/Translate.js'; +import {noModifierKeys, singleClick} from 'ol/events/condition.js'; +import {getDistance as haversineDistance, getArea} from 'ol/sphere.js'; /** * @param {!angular.Scope} $scope Scope. @@ -226,10 +226,10 @@ const exports = function($scope, drawPoint.setActive(false); ngeoMiscDecorate.interaction(drawPoint); this.map.addInteraction(drawPoint); - olEvents.listen(drawPoint, olObject.getChangeEventType( - olInteraction.Property.ACTIVE), + listen(drawPoint, getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(drawPoint, olInteraction.DrawEventType.DRAWEND, + listen(drawPoint, 'drawend', this.onDrawEnd_, this); var drawLabel = new olInteractionDraw({ @@ -245,10 +245,10 @@ const exports = function($scope, drawLabel.setActive(false); ngeoMiscDecorate.interaction(drawLabel); this.map.addInteraction(drawLabel); - olEvents.listen(drawLabel, olObject.getChangeEventType( - olInteraction.Property.ACTIVE), + listen(drawLabel, getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(drawLabel, olInteraction.DrawEventType.DRAWEND, + listen(drawLabel, 'drawend', this.onDrawEnd_, this); this.drawnFeatures_.drawLineInteraction = new appInteractionDrawRoute({ @@ -267,12 +267,12 @@ const exports = function($scope, this.drawLine.setActive(false); ngeoMiscDecorate.interaction(this.drawLine); this.map.addInteraction(this.drawLine); - olEvents.listen(this.drawLine, olObject.getChangeEventType( - olInteraction.Property.ACTIVE), + listen(this.drawLine, getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(this.drawLine, olInteraction.DrawEventType.DRAWEND, + listen(this.drawLine, 'drawend', this.onDrawEnd_, this); - olEvents.listen(this.drawLine, olInteraction.DrawEventType.DRAWSTART, + listen(this.drawLine, 'drawstart', this.onDrawLineStart_, this); var drawPolygon = new olInteractionDraw({ @@ -288,12 +288,12 @@ const exports = function($scope, drawPolygon.setActive(false); ngeoMiscDecorate.interaction(drawPolygon); this.map.addInteraction(drawPolygon); - olEvents.listen(drawPolygon, olObject.getChangeEventType( - olInteraction.Property.ACTIVE), + listen(drawPolygon, getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(drawPolygon, olInteraction.DrawEventType.DRAWEND, + listen(drawPolygon, 'drawend', this.onDrawEnd_, this); - olEvents.listen(drawPolygon, olInteraction.DrawEventType.DRAWSTART, + listen(drawPolygon, 'drawstart', this.onDrawPolygonStart_, this); var drawCircle = new olInteractionDraw({ @@ -309,12 +309,12 @@ const exports = function($scope, drawCircle.setActive(false); ngeoMiscDecorate.interaction(drawCircle); this.map.addInteraction(drawCircle); - olEvents.listen(drawCircle, olObject.getChangeEventType( - olInteraction.Property.ACTIVE), + listen(drawCircle, getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(drawCircle, olInteraction.DrawEventType.DRAWEND, + listen(drawCircle, 'drawend', this.onDrawEnd_, this); - olEvents.listen(drawCircle, olInteraction.DrawEventType.DRAWSTART, + listen(drawCircle, 'drawstart', this.onDrawCircleStart_, this); // Watch the "active" property, and disable the draw interactions @@ -356,7 +356,7 @@ const exports = function($scope, this.drawnFeatures_.selectInteraction.setActive(false); appFeaturePopup.init(this.map); - olEvents.listen(appSelectedFeatures, olCollectionEventType.ADD, + listen(appSelectedFeatures, olCollectionEventType.ADD, /** * @param {ol.Collection.Event} evt The event. */ @@ -371,14 +371,14 @@ const exports = function($scope, } if (!this.featurePopup_.isDocked) { this.featurePopup_.show(feature, this.map, - olExtent.getCenter(feature.getGeometry().getExtent())); + getCenter(feature.getGeometry().getExtent())); } this.gotoAnchor( 'feature-' + this.drawnFeatures_.getArray().indexOf(feature)); this.scope_.$applyAsync(); }).bind(this)); - olEvents.listen(appSelectedFeatures, olCollectionEventType.REMOVE, + listen(appSelectedFeatures, olCollectionEventType.REMOVE, /** * @param {ol.Collection.Event} evt The event. */ @@ -400,7 +400,7 @@ const exports = function($scope, features: appSelectedFeatures, pixelTolerance: 20, deleteCondition: function(event) { - return olEvents.condition.noModifierKeys(event) && olEvents.condition.singleClick(event); + return noModifierKeys(event) && singleClick(event); } }); @@ -410,8 +410,8 @@ const exports = function($scope, }); this.drawnFeatures_.clipLineInteraction.setActive(false); this.map.addInteraction(this.drawnFeatures_.clipLineInteraction); - olEvents.listen(this.drawnFeatures_.clipLineInteraction, - olInteraction.ModifyEventType.MODIFYEND, this.onClipLineEnd_, this); + listen(this.drawnFeatures_.clipLineInteraction, + 'modifyend', this.onClipLineEnd_, this); this.drawnFeatures_.modifyCircleInteraction = new appInteractionModifyCircle({ @@ -424,22 +424,21 @@ const exports = function($scope, this.modifyCircleInteraction_ = this.drawnFeatures_.modifyCircleInteraction; this.map.addInteraction(this.drawnFeatures_.modifyCircleInteraction); this.modifyCircleInteraction_.setActive(false); - olEvents.listen(this.modifyCircleInteraction_, - olInteraction.ModifyEventType.MODIFYEND, this.onFeatureModifyEnd_, this); + listen(this.modifyCircleInteraction_, + 'modifyend', this.onFeatureModifyEnd_, this); this.map.addInteraction(this.drawnFeatures_.modifyInteraction); - olEvents.listen(this.drawnFeatures_.modifyInteraction, - olInteraction.ModifyEventType.MODIFYEND, this.onFeatureModifyEnd_, this); + listen(this.drawnFeatures_.modifyInteraction, + 'modifyend', this.onFeatureModifyEnd_, this); - this.drawnFeatures_.translateInteraction = new olInteractionTranslate({ + this.drawnFeatures_.translateInteraction = new ngeoInteractionTranslate({ features: appSelectedFeatures }); this.drawnFeatures_.translateInteraction.setActive(false); this.map.addInteraction(this.drawnFeatures_.translateInteraction); - olEvents.listen( - this.drawnFeatures_.translateInteraction, - olInteraction.TranslateEventType.TRANSLATEEND, + listen( + this.drawnFeatures_.translateInteraction, 'translateend', /** * @param {ol.interaction.Translate.Event} evt The event. */ @@ -449,7 +448,7 @@ const exports = function($scope, this.drawnFeatures_.drawFeaturesInUrl(this.featureStyleFunction_); - olEvents.listen(this.map, olEvents.EventType.KEYDOWN, + listen(this.map, 'keydown', this.keyboardHandler_, this); }; @@ -550,8 +549,8 @@ exports.prototype.onDrawPolygonStart_ = function(event) { var proj = this.map.getView().getProjection(); - this.changeEventKey_ = olEvents.listen(geometry, - olEvents.EventType.CHANGE, + this.changeEventKey_ = listen(geometry, + 'change', function() { var verticesCount = geometry.getCoordinates()[0].length; var coord = null; @@ -579,8 +578,8 @@ exports.prototype.onDrawLineStart_ = function(event) { console.assert(geometry !== undefined); var proj = this.map.getView().getProjection(); - this.changeEventKey_ = olEvents.listen(geometry, - olEvents.EventType.CHANGE, + this.changeEventKey_ = listen(geometry, + 'change', function() { var coord = geometry.getLastCoordinate(); if (coord !== null) { @@ -604,8 +603,8 @@ exports.prototype.onDrawCircleStart_ = function(event) { console.assert(geometry !== undefined); var proj = this.map.getView().getProjection(); - this.changeEventKey_ = olEvents.listen(geometry, - olEvents.EventType.CHANGE, + this.changeEventKey_ = listen(geometry, + 'change', function() { var coord = geometry.getLastCoordinate(); var center = geometry.getCenter(); @@ -631,9 +630,9 @@ exports.prototype.getFormattedLength = var length = 0; var coordinates = lineString.getCoordinates(); for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) { - var c1 = olProj.transform(coordinates[i], projection, 'EPSG:4326'); - var c2 = olProj.transform(coordinates[i + 1], projection, 'EPSG:4326'); - length += ngeoInteractionMeasure.SPHERE_WGS84.haversineDistance(c1, c2); + var c1 = transform(coordinates[i], projection, 'EPSG:4326'); + var c2 = transform(coordinates[i + 1], projection, 'EPSG:4326'); + length += haversineDistance(c1, c2); } var output; if (length > 1000) { @@ -657,8 +656,7 @@ exports.prototype.getFormattedLength = exports.prototype.getFormattedArea = function(polygon, projection) { var geom = /** @type {ol.geom.Polygon} */ ( polygon.clone().transform(projection, 'EPSG:4326')); - var coordinates = geom.getLinearRing(0).getCoordinates(); - var area = Math.abs(ngeoInteractionMeasure.SPHERE_WGS84.geodesicArea(coordinates)); + var area = Math.abs(getArea(geom)); var output; if (area > 1000000) { output = parseFloat((area / 1000000).toPrecision(3)) + @@ -678,7 +676,7 @@ exports.prototype.onDrawEnd_ = function(event) { this.removeMeasureTooltip_(); if (this.changeEventKey_ !== null) { - olObservable.unByKey(this.changeEventKey_); + unByKey(this.changeEventKey_); this.changeEventKey_ = null; } if (this.drawnFeatures_.continuingLine) { @@ -690,8 +688,7 @@ exports.prototype.onDrawEnd_ = function(event) { if (feature.getGeometry().getType() === olGeomGeometryType.CIRCLE) { var featureGeom = /** @type {ol.geom.Circle} */ (feature.getGeometry()); feature.set('isCircle', true); - feature.setGeometry( - olGeomPolygon.fromCircle(featureGeom, 64) + feature.setGeometry(fromCircle(featureGeom, 64) ); } diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawnFeatures.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawnFeatures.js index c2a3945bd..34cc8115b 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawnFeatures.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/DrawnFeatures.js @@ -11,7 +11,7 @@ import appDrawFeatureHash from '../draw/FeatureHash.js'; import olLayerVector from 'ol/layer/Vector.js'; import olSourceVector from 'ol/source/Vector.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; -import olExtent from 'ol/extent.js'; +import {createEmpty, extend} from 'ol/extent.js'; import olCollection from 'ol/Collection.js'; /** @@ -62,7 +62,7 @@ const exports = function(ngeoLocation, appMymaps, ngeoFeatureOverlayMgr) { this.clipLineInteraction; /** - * @type {ol.interaction.Translate} + * @type {ngeo.interaction.Translate} */ this.translateInteraction; @@ -463,10 +463,10 @@ exports.prototype.activateModifyIfNeeded = function(feature) { * @return {ol.Extent} The extent of all features */ exports.prototype.getExtent = function() { - var extent = olExtent.createEmpty(); + var extent = createEmpty(); this.features.forEach(function(feature) { if (feature.getGeometry()) { - extent = olExtent.extend(extent, feature.getGeometry().getExtent()); + extent = extend(extent, feature.getGeometry().getExtent()); } }, this); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeatureHash.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeatureHash.js index 3afe41cbc..193f50682 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeatureHash.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeatureHash.js @@ -3,12 +3,12 @@ */ import ngeoFormatFeatureProperties from 'ngeo/format/FeatureProperties.js'; import ngeoUtils from 'ngeo/utils.js'; -import olBase from 'ol.js'; + import olFeature from 'ol/Feature.js'; -import olArray from 'ol/array.js'; -import olColor from 'ol/color.js'; +import {includes as arrayIncludes} from 'ol/array.js'; +import {asArray as colorAsArray} from 'ol/color.js'; import olFormatTextFeature from 'ol/format/TextFeature.js'; -import olFormatFeature from 'ol/format/Feature.js'; +import {transformWithOptions} from 'ol/format/Feature.js'; import olGeomGeometryLayout from 'ol/geom/GeometryLayout.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomLineString from 'ol/geom/LineString.js'; @@ -22,6 +22,7 @@ import olStyleFill from 'ol/style/Fill.js'; import olStyleStroke from 'ol/style/Stroke.js'; import olStyleStyle from 'ol/style/Style.js'; import olStyleText from 'ol/style/Text.js'; +import {inherits} from 'ol/index.js'; /** @@ -135,7 +136,7 @@ const exports = function(opt_options) { }; -olBase.inherits(exports, olFormatTextFeature); +inherits(exports, olFormatTextFeature); /** @@ -352,7 +353,7 @@ exports.encodeStyleFill_ = function(fillStyle, encodedStyles, opt_propertyName) var fillColor = fillStyle.getColor(); if (fillColor !== null) { console.assert(Array.isArray(fillColor), 'only supporting fill colors'); - var fillColorRgba = olColor.asArray(/** @type {Array} */ (fillColor)); + var fillColorRgba = colorAsArray(/** @type {Array} */ (fillColor)); console.assert(Array.isArray(fillColorRgba), 'fill color must be an array'); var fillColorHex = ngeoUtils.rgbArrayToHex(/** @type {!Array} */ (fillColorRgba)); if (encodedStyles.length > 0) { @@ -375,7 +376,7 @@ exports.encodeStyleStroke_ = function(strokeStyle, encodedStyles) { var strokeColor = strokeStyle.getColor(); if (strokeColor !== null) { console.assert(Array.isArray(strokeColor)); - var strokeColorRgba = olColor.asArray(/** @type {Array} */ (strokeColor)); + var strokeColorRgba = colorAsArray(/** @type {Array} */ (strokeColor)); console.assert(Array.isArray(strokeColorRgba), 'only supporting stroke colors'); var strokeColorHex = ngeoUtils.rgbArrayToHex(/** @type {!Array} */ (strokeColorRgba)); if (encodedStyles.length > 0) { @@ -721,10 +722,10 @@ exports.castValue_ = function(key, value) { 'showMeasure' ]; - if (olArray.includes(numProperties, key)) { + if (arrayIncludes(numProperties, key)) { return +value; - } else if (olArray.includes(boolProperties, key)) { - return (value === 'true') ? true : false; + } else if (arrayIncludes(boolProperties, key)) { + return value === 'true'; } else { return value; } @@ -1225,7 +1226,7 @@ exports.prototype.writeGeometryText = function(geometry, opt_options) { geometry.getType()]; console.assert(geometryWriter !== undefined); var transformedGeometry = /** @type {ol.geom.Geometry} */ - (olFormatFeature.transformWithOptions(geometry, true, opt_options)); + (transformWithOptions(geometry, true, opt_options)); this.prevX_ = 0; this.prevY_ = 0; return geometryWriter.call(this, transformedGeometry); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopup.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopup.js index 731ba990b..b7ef894b6 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopup.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopup.js @@ -7,11 +7,10 @@ import appModule from '../module.js'; import olOverlay from 'ol/Overlay.js'; -import olObservable from 'ol/Observable.js'; -import olEvents from 'ol/events.js'; +import {unByKey} from 'ol/Observable.js'; +import {listen, listenOnce} from 'ol/events.js'; import olGeomLineString from 'ol/geom/LineString.js'; import ngeoInteractionMeasure from 'ngeo/interaction/Measure.js'; -import olMapBrowserEventType from 'ol/MapBrowserEventType.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomPoint from 'ol/geom/Point.js'; import olGeomPolygon from 'ol/geom/Polygon.js'; @@ -133,13 +132,13 @@ exports.prototype.init = function(map) { * @param {angular.JQLite} element The element. */ exports.prototype.setDraggable = function(element) { - this.mousedownEvent_ = olEvents.listen(element[0], 'mousedown', + this.mousedownEvent_ = listen(element[0], 'mousedown', function(event) { this.element_.css({'transform': 'scale(1.1)', 'transition': 'transform .3s'}); if (this.mousemoveEvent_ !== null) { - this.mousemoveEvent_ = olEvents.listen(this.map, - olMapBrowserEventType.POINTERMOVE, function(e) { + this.mousemoveEvent_ = listen(this.map, + 'pointermove', function(e) { if (!this.startingDragPoint_) { this.startingAnchorPoint_ = this.overlay_.getPosition(); this.startingDragPoint_ = e.coordinate; @@ -152,14 +151,14 @@ exports.prototype.setDraggable = function(element) { this.startingDragPoint_[1]]); }.bind(this)); } - olEvents.listenOnce(this.$document_[0], + listenOnce(this.$document_[0], 'mouseup', function() { this.element_.css({'transform': 'scale(1)'}); this.startingAnchorPoint_ = null; this.startingDragPoint_ = null; if (this.mousemoveEvent_) { - olObservable.unByKey(this.mousemoveEvent_); + unByKey(this.mousemoveEvent_); } this.mousemoveEvent_ = null; }.bind(this)); @@ -213,7 +212,7 @@ exports.prototype.hide = function() { delete this.scope_['feature']; delete this.scope_['map']; this.overlay_.setPosition(undefined); - olObservable.unByKey(this.mousedownEvent_); + unByKey(this.mousedownEvent_); this.mousedownEvent_ = null; }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopupController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopupController.js index f77a9b97e..abb91983d 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopupController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/FeaturePopupController.js @@ -7,17 +7,16 @@ import appModule from '../module.js'; import appMiscFile from '../misc/file.js'; -import olEvents from 'ol/events.js'; -import olExtent from 'ol/extent.js'; -import olProj from 'ol/proj.js'; +import {listen, unlistenByKey} from 'ol/events.js'; +import {getCenter} from 'ol/extent.js'; +import {transform, getPointResolution, METERS_PER_UNIT} from 'ol/proj.js'; import olFormatKML from 'ol/format/KML.js'; import olGeomCircle from 'ol/geom/Circle.js'; import olGeomPoint from 'ol/geom/Point.js'; -import olGeomPolygon from 'ol/geom/Polygon.js'; +import {fromCircle} from 'ol/geom/Polygon.js'; import olGeomLineString from 'ol/geom/LineString.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; -import olInteraction from 'ol/interaction.js'; -import ngeoInteractionMeasure from 'ngeo/interaction/Measure.js'; +import {getDistance as haversineDistance} from 'ol/sphere.js'; /** * @constructor @@ -254,8 +253,8 @@ const exports = function($scope, $sce, appFeaturePopup, * @type {ol.EventsKey} * @private */ - this.event_ = olEvents.listen(this.drawnFeatures_.modifyInteraction, - olInteraction.ModifyEventType.MODIFYEND, this.updateFeature_, this); + this.event_ = listen(this.drawnFeatures_.modifyInteraction, + 'modifyend', this.updateFeature_, this); this.unwatch4_ = $scope.$watch(function() { return this.image; @@ -282,7 +281,7 @@ const exports = function($scope, $sce, appFeaturePopup, }.bind(this)); $scope.$on('$destroy', function() { - olEvents.unlistenByKey(this.event_); + unlistenByKey(this.event_); this.unwatch1_(); this.unwatch2_(); this.unwatch3_(); @@ -321,11 +320,11 @@ exports.prototype.getCircleRadius = function() { this.feature.getGeometry().getType() === olGeomGeometryType.POLYGON && this.isCircle()) { var geom = /** @type {ol.geom.Polygon} **/ (this.feature.getGeometry()); - var center = olExtent.getCenter(geom.getExtent()); + var center = getCenter(geom.getExtent()); var projection = this.map.getView().getProjection(); - var p1 = olProj.transform(center, projection, 'EPSG:4326'); - var p2 = olProj.transform(geom.getLastCoordinate(), projection, 'EPSG:4326'); - return Math.round(ngeoInteractionMeasure.SPHERE_WGS84.haversineDistance(p1, p2)); + var p1 = transform(center, projection, 'EPSG:4326'); + var p2 = transform(geom.getLastCoordinate(), projection, 'EPSG:4326'); + return Math.round(haversineDistance(p1, p2)); } return 0; }; @@ -351,15 +350,14 @@ exports.prototype.setFeatureCircleRadius = function(feature, radius) { feature.getGeometry().getType() === olGeomGeometryType.POLYGON && this.isCircle()) { var geom = /** @type {ol.geom.Polygon} **/ (feature.getGeometry()); - var center = olExtent.getCenter(geom.getExtent()); + var center = getCenter(geom.getExtent()); var projection = this.map.getView().getProjection(); var resolution = this.map.getView().getResolution(); - var pointResolution = olProj.getPointResolution(projection, /** @type {number} */ (resolution), center); + var pointResolution = getPointResolution(projection, /** @type {number} */ (resolution), center); var resolutionFactor = resolution / pointResolution; - radius = (radius / olProj.METERS_PER_UNIT.m) * resolutionFactor; + radius = (radius / METERS_PER_UNIT.m) * resolutionFactor; var featureGeom = new olGeomCircle(center, radius); - feature.setGeometry( - olGeomPolygon.fromCircle(featureGeom, 64) + feature.setGeometry(fromCircle(featureGeom, 64) ); } }; @@ -509,7 +507,7 @@ exports.prototype.getRadius = function() { this.isCircle()) { var geom = /** @type {ol.geom.Polygon} **/ (this.feature.getGeometry()); console.assert(geom !== null && geom !== undefined); - var center = olExtent.getCenter(geom.getExtent()); + var center = getCenter(geom.getExtent()); var line = new olGeomLineString([center, geom.getLastCoordinate()]); return this.appFeaturePopup_.formatRadius(line); } else { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/RouteControl.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/RouteControl.js index 12f4ed11c..106d35ce9 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/RouteControl.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/draw/RouteControl.js @@ -6,10 +6,11 @@ * */ -import olBase from 'ol.js'; -import olCss from 'ol/css.js'; + +import {CLASS_UNSELECTABLE, CLASS_CONTROL} from 'ol/css.js'; import olControlControl from 'ol/control/Control.js'; -import olEvents from 'ol/events.js'; +import {listen} from 'ol/events.js'; +import {inherits} from 'ol/index.js'; /** * @constructor @@ -36,8 +37,8 @@ const exports = function(options) { button.setAttribute('type', 'button'); button.setAttribute('title', tipLabel); - var cssClasses = className + ' ' + olCss.CLASS_UNSELECTABLE + ' ' + - olCss.CLASS_CONTROL + ' ' + + var cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + + CLASS_CONTROL + ' ' + (this.drawLineInteraction_.getMapMatching() ? 'route-on' : ''); /** @@ -47,10 +48,10 @@ const exports = function(options) { this.element.setAttribute('class', cssClasses); this.element.appendChild(button); - olEvents.listen(button, olEvents.EventType.CLICK, + listen(button, 'click', this.handleClick_, this); - olEvents.listen(button, olEvents.EventType.MOUSEOUT, function() { + listen(button, 'mouseout', function() { this.blur(); }); @@ -61,7 +62,7 @@ const exports = function(options) { }; -olBase.inherits(exports, olControlControl); +inherits(exports, olControlControl); /** diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/index.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/index.js index 0de2340a8..eb552b8f9 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/index.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/index.js @@ -1,5 +1,10 @@ /* eslint-disable */ +goog.require('app.query.casiporeportDirective'); +goog.require('app.draw.FeatureHash'); +goog.require('app.layerinfo.layerinfoDirective'); + + /** * @typedef {{themes: Array., background_layers: Array.}} */ diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/infobar/ElevationController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/infobar/ElevationController.js index a2f835785..4c2a2a62c 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/infobar/ElevationController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/infobar/ElevationController.js @@ -44,7 +44,7 @@ const exports = function($http, ngeoDebounce, appGetElevation) { return; } this.getElevation_(e.coordinate).then( - (elevation) => (this['elevation'] = elevation['formattedElevation']) + elevation => this['elevation'] = elevation['formattedElevation'] ); }, 300, true), this); }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ClipLine.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ClipLine.js index ae23378f5..a164a0c7c 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ClipLine.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ClipLine.js @@ -1,24 +1,25 @@ /** * @module app.interaction.ClipLine */ -import olBase from 'ol.js'; + +import ngeoInteractionCommon from 'ngeo/interaction/common.js'; import olCollection from 'ol/Collection.js'; import olFeature from 'ol/Feature.js'; -import olMapBrowserEventType from 'ol/MapBrowserEventType.js'; import olMapBrowserPointerEvent from 'ol/MapBrowserPointerEvent.js'; -import olCoordinate from 'ol/coordinate.js'; -import olEvents from 'ol/events.js'; -import olExtent from 'ol/extent.js'; +import {closestOnSegment, equals, squaredDistance, squaredDistanceToSegment} from 'ol/coordinate.js'; +import {listen, unlisten} from 'ol/events.js'; +import {buffer, boundingExtent, createOrUpdateFromCoordinate} from 'ol/extent.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomPoint from 'ol/geom/Point.js'; import olInteractionInteraction from 'ol/interaction/Interaction.js'; -import olInteractionModify from 'ol/interaction/Modify.js'; -import olInteractionPointer from 'ol/interaction/Pointer.js'; -import olInteractionModifyEventType from 'ol/interaction/ModifyEventType.js'; +import {ModifyEvent} from 'ol/interaction/Modify.js'; +import olInteractionPointer, {handleEvent as pointerHandleEvent} from 'ol/interaction/Pointer.js'; import olLayerVector from 'ol/layer/Vector.js'; import olSourceVector from 'ol/source/Vector.js'; import olStructsRBush from 'ol/structs/RBush.js'; -import olStyleStyle from 'ol/style/Style.js'; +import {inherits} from 'ol/index.js'; +import ViewHint from 'ol/ViewHint.js'; + /** * @classdesc @@ -107,14 +108,12 @@ const exports = function(options) { this.features_ = /** @type {!ol.Collection.} */ (options.features); this.features_.forEach(this.addFeature_, this); - olEvents.listen(this.features_, olBase.CollectionEventType.ADD, - this.handleFeatureAdd_, this); - olEvents.listen(this.features_, olBase.CollectionEventType.REMOVE, - this.handleFeatureRemove_, this); + listen(this.features_, 'add', this.handleFeatureAdd_, this); + listen(this.features_, 'remove', this.handleFeatureRemove_, this); }; -olBase.inherits(exports, olInteractionPointer); +inherits(exports, olInteractionPointer); /** @@ -132,7 +131,7 @@ exports.prototype.addFeature_ = function(feature) { this.handlePointerAtPixel_(this.lastPixel_, map); } } - olEvents.listen(feature, olEvents.EventType.CHANGE, + listen(feature, 'change', this.handleFeatureChange_, this); } }; @@ -150,7 +149,7 @@ exports.prototype.removeFeature_ = function(feature) { this.overlay_.getSource().removeFeature(this.vertexFeature_); this.vertexFeature_ = null; } - olEvents.unlisten(feature, olEvents.EventType.CHANGE, + unlisten(feature, 'change', this.handleFeatureChange_, this); }; @@ -235,7 +234,7 @@ exports.prototype.writeLineStringGeometry_ = function(feature, geometry) { index: i, segment: segment }); - this.rBush_.insert(olExtent.boundingExtent(segment), segmentData); + this.rBush_.insert(boundingExtent(segment), segmentData); } }; @@ -296,15 +295,15 @@ exports.handleDownEvent_ = function(evt) { if (vertexFeature) { var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); var vertex = geometry.getCoordinates(); - var vertexExtent = olExtent.boundingExtent([vertex]); + var vertexExtent = boundingExtent([vertex]); var segmentDataMatches = this.rBush_.getInExtent(vertexExtent); segmentDataMatches.sort(exports.compareIndexes_); for (var i = 0, ii = segmentDataMatches.length; i < ii; ++i) { var segmentDataMatch = segmentDataMatches[i]; if (segmentDataMatch.feature !== undefined && this.features_.getArray().indexOf(segmentDataMatch.feature) >= 0) { - var closestVertex = olCoordinate.closestOnSegment(vertex, segmentDataMatch.segment); - if (!olCoordinate.equals(closestVertex, vertex)) { + var closestVertex = closestOnSegment(vertex, segmentDataMatch.segment); + if (!equals(closestVertex, vertex)) { continue; } this.features_.remove(segmentDataMatch.feature); @@ -323,8 +322,8 @@ exports.handleDownEvent_ = function(evt) { this.features_.push(feature1); this.features_.push(feature2); - this.dispatchEvent(new olInteractionModify.Event( - olInteractionModifyEventType.MODIFYEND, new olCollection([feature1, feature2, segmentDataMatch.feature]), evt)); + this.dispatchEvent(new ModifyEvent( + 'modifyend', new olCollection([feature1, feature2, segmentDataMatch.feature]), evt)); this.modified_ = true; } } @@ -347,13 +346,13 @@ exports.handleEvent = function(mapBrowserEvent) { return true; } - if (!mapBrowserEvent.map.getView().getHints()[olBase.ViewHint.INTERACTING] && - mapBrowserEvent.type == olMapBrowserEventType.POINTERMOVE && + if (!mapBrowserEvent.map.getView().getHints()[ViewHint.INTERACTING] && + mapBrowserEvent.type == 'pointermove' && !this.handlingDownUpSequence) { this.handlePointerMove_(mapBrowserEvent); } - return olInteractionPointer.handleEvent.call(this, mapBrowserEvent); + return pointerHandleEvent.call(this, mapBrowserEvent); }; @@ -399,12 +398,12 @@ exports.prototype.handlePointerAtPixel_ = function(pixel, map) { } var pixelCoordinate = map.getCoordinateFromPixel(pixel); var sortByDistance = function(a, b) { - return olCoordinate.squaredDistanceToSegment(pixelCoordinate, a.segment) - - olCoordinate.squaredDistanceToSegment(pixelCoordinate, b.segment); + return squaredDistanceToSegment(pixelCoordinate, a.segment) - + squaredDistanceToSegment(pixelCoordinate, b.segment); }; - var box = olExtent.buffer( - olExtent.createOrUpdateFromCoordinate(pixelCoordinate), + var box = buffer( + createOrUpdateFromCoordinate(pixelCoordinate), map.getView().getResolution() * this.pixelTolerance_); var rBush = this.rBush_; @@ -413,15 +412,15 @@ exports.prototype.handlePointerAtPixel_ = function(pixel, map) { nodes.sort(sortByDistance); var node = nodes[0]; var closestSegment = node.segment; - var vertex = (olCoordinate.closestOnSegment(pixelCoordinate, + var vertex = (closestOnSegment(pixelCoordinate, closestSegment)); var vertexPixel = map.getPixelFromCoordinate(vertex); - if (Math.sqrt(olCoordinate.squaredDistance(pixel, vertexPixel)) <= + if (Math.sqrt(squaredDistance(pixel, vertexPixel)) <= this.pixelTolerance_) { var pixel1 = map.getPixelFromCoordinate(closestSegment[0]); var pixel2 = map.getPixelFromCoordinate(closestSegment[1]); - var squaredDist1 = olCoordinate.squaredDistance(vertexPixel, pixel1); - var squaredDist2 = olCoordinate.squaredDistance(vertexPixel, pixel2); + var squaredDist1 = squaredDistance(vertexPixel, pixel1); + var squaredDist2 = squaredDistance(vertexPixel, pixel2); var dist = Math.sqrt(Math.min(squaredDist1, squaredDist2)); this.snappedToVertex_ = dist <= this.pixelTolerance_; if (this.snappedToVertex_) { @@ -444,7 +443,7 @@ exports.prototype.handlePointerAtPixel_ = function(pixel, map) { * @return {ol.StyleFunction} Styles. */ exports.getDefaultStyleFunction = function() { - var style = olStyleStyle.createDefaultEditing(); + var style = ngeoInteractionCommon.getDefaultModifyStyleFunction(); return function(feature, resolution) { return style[olGeomGeometryType.POINT]; }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/DrawRoute.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/DrawRoute.js index 6e934cddd..d89095a33 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/DrawRoute.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/DrawRoute.js @@ -1,25 +1,37 @@ /** * @module app.interaction.DrawRoute */ -import olBase from 'ol.js'; + +import {createEditingStyle} from 'ol/style/Style.js'; import olFeature from 'ol/Feature.js'; import olMapBrowserEventType from 'ol/MapBrowserEventType.js'; -import olObject from 'ol/Object.js'; -import olEvents from 'ol/events.js'; +import {getChangeEventType} from 'ol/Object.js'; +import {listen} from 'ol/events.js'; import olEventsEvent from 'ol/events/Event.js'; -import olEventsCondition from 'ol/events/condition.js'; +import {noModifierKeys, always, shiftKeyOnly} from 'ol/events/condition.js'; import olFormatGeoJSON from 'ol/format/GeoJSON.js'; -import olFunctions from 'ol/functions.js'; +import {TRUE, FALSE} from 'ol/functions.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomLineString from 'ol/geom/LineString.js'; import olGeomPoint from 'ol/geom/Point.js'; import olGeomPolygon from 'ol/geom/Polygon.js'; -import olInteractionDrawEventType from 'ol/interaction/DrawEventType.js'; -import olInteractionPointer from 'ol/interaction/Pointer.js'; -import olInteractionProperty from 'ol/interaction/Property.js'; +import olInteractionPointer, {handleEvent as pointerHandleEvent} from 'ol/interaction/Pointer.js'; import olLayerVector from 'ol/layer/Vector.js'; import olSourceVector from 'ol/source/Vector.js'; -import olStyleStyle from 'ol/style/Style.js'; +import {inherits} from 'ol/index.js'; +import {transform} from 'ol/proj.js'; + + +/** + * @return {ol.StyleFunction} Styles. + */ +function getDefaultStyleFunction() { + var styles = createEditingStyle(); + return function(feature, resolution) { + return styles[feature.getGeometry().getType()]; + }; +}; + /** * @classdesc @@ -132,7 +144,7 @@ const exports = function(options) { * @private * @type {ol.EventsConditionType} */ - this.finishCondition_ = options.finishCondition ? options.finishCondition : olFunctions.TRUE; + this.finishCondition_ = options.finishCondition ? options.finishCondition : TRUE; /** * @private @@ -248,8 +260,7 @@ const exports = function(options) { useSpatialIndex: false, wrapX: options.wrapX ? options.wrapX : false }), - style: options.style ? options.style : - exports.getDefaultStyleFunction() + style: options.style ? options.style : getDefaultStyleFunction() }); /** @@ -264,7 +275,7 @@ const exports = function(options) { * @type {ol.EventsConditionType} */ this.condition_ = options.condition ? - options.condition : olEventsCondition.noModifierKeys; + options.condition : noModifierKeys; /** * @private @@ -272,30 +283,19 @@ const exports = function(options) { */ this.freehandCondition_; if (options.freehand) { - this.freehandCondition_ = olEventsCondition.always; + this.freehandCondition_ = always; } else { this.freehandCondition_ = options.freehandCondition ? - options.freehandCondition : olEventsCondition.shiftKeyOnly; + options.freehandCondition : shiftKeyOnly; } - olEvents.listen(this, - olObject.getChangeEventType(olInteractionProperty.ACTIVE), + listen(this, + getChangeEventType('active'), this.updateState_, this); }; -olBase.inherits(exports, olInteractionPointer); - - -/** - * @return {ol.StyleFunction} Styles. - */ -exports.getDefaultStyleFunction = function() { - var styles = olStyleStyle.createDefaultEditing(); - return function(feature, resolution) { - return styles[feature.getGeometry().getType()]; - }; -}; +inherits(exports, olInteractionPointer); /** @@ -323,12 +323,12 @@ exports.handleEvent = function(event) { this.addToDrawing_(event); pass = false; } else if (event.type === - olMapBrowserEventType.POINTERMOVE) { + 'pointermove') { pass = this.handlePointerMove_(event); } else if (event.type === olMapBrowserEventType.DBLCLICK) { pass = false; } - return olInteractionPointer.handleEvent.call(this, event) && pass; + return pointerHandleEvent.call(this, event) && pass; }; @@ -507,7 +507,7 @@ exports.prototype.startDrawing_ = function(event) { this.sketchFeature_.setGeometry(geometry); this.updateSketchFeatures_(); this.dispatchEvent(new exports.Event( - olInteractionDrawEventType.DRAWSTART, this.sketchFeature_)); + 'drawstart', this.sketchFeature_)); }; @@ -581,8 +581,8 @@ exports.prototype.addToDrawing_ = function(event) { } else { var last = coordinates[coordinates.length - 1]; if (coordinates.length > 2) { - var penultimate = olBase.proj.transform(coordinates[coordinates.length - 2], 'EPSG:3857', 'EPSG:4326'); - var antepenultimate = olBase.proj.transform(coordinates[coordinates.length - 3], 'EPSG:3857', 'EPSG:4326'); + var penultimate = transform(coordinates[coordinates.length - 2], 'EPSG:3857', 'EPSG:4326'); + var antepenultimate = transform(coordinates[coordinates.length - 3], 'EPSG:3857', 'EPSG:4326'); var waypoints = antepenultimate[1] + ',' + antepenultimate[0] + ',' + penultimate[1] + ',' + penultimate[0]; if (waypoints !== this.lastWaypoints_ && !this.isRequestingRoute_) { this.lastWaypoints_ = waypoints; @@ -712,7 +712,7 @@ exports.prototype.removeLastPoint = function() { /** * Stop drawing and add the sketch feature to the target layer. - * The {@link ol.interaction.DrawEventType.DRAWEND} event is dispatched before + * The drawend event is dispatched before * inserting the feature. * @api */ @@ -720,8 +720,7 @@ exports.prototype.finishDrawing = function() { var sketchFeature = this.abortDrawing_(); // First dispatch event to allow full set up of feature - this.dispatchEvent(new exports.Event( - olInteractionDrawEventType.DRAWEND, sketchFeature)); + this.dispatchEvent(new exports.Event('drawend', sketchFeature)); // Then insert feature if (this.features_) { @@ -769,14 +768,14 @@ exports.prototype.extend = function(feature) { this.sketchCoords_.push(last.slice()); this.updateSketchFeatures_(); this.dispatchEvent(new exports.Event( - olInteractionDrawEventType.DRAWSTART, this.sketchFeature_)); + 'drawstart', this.sketchFeature_)); }; /** * @inheritDoc */ -exports.prototype.shouldStopEvent = olFunctions.FALSE; +exports.prototype.shouldStopEvent = FALSE; /** @@ -858,7 +857,7 @@ exports.Mode_ = { * @constructor * @extends {ol.events.Event} * @implements {oli.DrawEvent} - * @param {ol.interaction.DrawEventType} type Type. + * @param {string} type Type. * @param {ol.Feature} feature The feature drawn. */ exports.Event = function(type, feature) { @@ -873,7 +872,7 @@ exports.Event = function(type, feature) { this.feature = feature; }; -olBase.inherits(exports.Event, olEventsEvent); +inherits(exports.Event, olEventsEvent); export default exports; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ModifyCircle.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ModifyCircle.js index 7792365c7..ccc10e0e0 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ModifyCircle.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/interaction/ModifyCircle.js @@ -1,35 +1,38 @@ /** * @module app.interaction.ModifyCircle */ -import olBase from 'ol.js'; +import ngeoInteractionCommon from 'ngeo/interaction/common.js'; +import ViewHint from 'ol/ViewHint.js'; import olFeature from 'ol/Feature.js'; -import olMapBrowserEventType from 'ol/MapBrowserEventType.js'; import olMapBrowserPointerEvent from 'ol/MapBrowserPointerEvent.js'; -import olCoordinate from 'ol/coordinate.js'; -import olEvents from 'ol/events.js'; -import olExtent from 'ol/extent.js'; +import {equals, squaredDistanceToSegment, closestOnSegment, squaredDistance} from 'ol/coordinate.js'; +import {listen, unlisten} from 'ol/events.js'; +import {boundingExtent, getCenter} from 'ol/extent.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomCircle from 'ol/geom/Circle.js'; import olGeomLineString from 'ol/geom/LineString.js'; import olGeomPoint from 'ol/geom/Point.js'; -import olGeomPolygon from 'ol/geom/Polygon.js'; -import olInteraction from 'ol/interaction.js'; -import olInteractionModify from 'ol/interaction/Modify.js'; -import olInteractionPointer from 'ol/interaction/Pointer.js'; +import {fromCircle} from 'ol/geom/Polygon.js'; +import Interaction from 'ol/interaction/Interaction.js'; +import {ModifyEvent} from 'ol/interaction/Modify.js'; +import olInteractionPointer, {handleEvent as pointerHandleEvent} from 'ol/interaction/Pointer.js'; import olLayerVector from 'ol/layer/Vector.js'; import olSourceVector from 'ol/source/Vector.js'; import olStructsRBush from 'ol/structs/RBush.js'; -import olStyleStyle from 'ol/style/Style.js'; +import {inherits, getUid} from 'ol/index.js'; /** - * @typedef {{depth: (Array.|undefined), + * @typedef {{ + * depth: (Array.|undefined), * feature: ol.Feature, * geometry: ol.geom.SimpleGeometry, * index: (number|undefined), - * segment: Array.}} + * segment: Array. + * }} */ -olInteraction.SegmentDataType; +// eslint-disable-next-line no-unused-vars +let SegmentDataType; /** @@ -72,7 +75,7 @@ const exports = function(options) { /** * Segment RTree for each layer - * @type {ol.structs.RBush.} + * @type {ol.structs.RBush.} * @private */ this.rBush_ = new olStructsRBush(); @@ -128,14 +131,14 @@ const exports = function(options) { this.features_ = /** @type {!ol.Collection.} */ (options.features); this.features_.forEach(this.addFeature_, this); - olEvents.listen(this.features_, olBase.CollectionEventType.ADD, + listen(this.features_, 'add', this.handleFeatureAdd_, this); - olEvents.listen(this.features_, olBase.CollectionEventType.REMOVE, + listen(this.features_, 'remove', this.handleFeatureRemove_, this); }; -olBase.inherits(exports, olInteractionPointer); +inherits(exports, olInteractionPointer); /** @@ -152,7 +155,7 @@ exports.prototype.addFeature_ = function(feature) { if (map) { this.handlePointerAtPixel_(this.lastPixel_, map); } - olEvents.listen(feature, olEvents.EventType.CHANGE, + listen(feature, 'change', this.handleFeatureChange_, this); } }; @@ -165,8 +168,8 @@ exports.prototype.addFeature_ = function(feature) { exports.prototype.willModifyFeatures_ = function(evt) { if (!this.modified_) { this.modified_ = true; - this.dispatchEvent(new olInteractionModify.Event( - olInteraction.ModifyEventType.MODIFYSTART, this.features_, evt)); + this.dispatchEvent(new ModifyEvent( + 'modifystart', this.features_, evt)); } }; @@ -183,7 +186,7 @@ exports.prototype.removeFeature_ = function(feature) { this.overlay_.getSource().removeFeature(this.vertexFeature_); this.vertexFeature_ = null; } - olEvents.unlisten(feature, olEvents.EventType.CHANGE, + unlisten(feature, 'change', this.handleFeatureChange_, this); }; @@ -194,10 +197,10 @@ exports.prototype.removeFeature_ = function(feature) { */ exports.prototype.removeFeatureSegmentData_ = function(feature) { var rBush = this.rBush_; - var /** @type {Array.} */ nodesToRemove = []; + var /** @type {Array.} */ nodesToRemove = []; rBush.forEach( /** - * @param {ol.interaction.SegmentDataType} node RTree node. + * @param {SegmentDataType} node RTree node. */ function(node) { if (feature === node.feature) { @@ -215,7 +218,7 @@ exports.prototype.removeFeatureSegmentData_ = function(feature) { */ exports.prototype.setMap = function(map) { this.overlay_.setMap(map); - olInteraction.Interaction.prototype.setMap.call(this, map); + Interaction.prototype.setMap.call(this, map); }; @@ -266,14 +269,14 @@ exports.prototype.writeCircleGeometry_ = function(feature, geometry) { coordinates = rings[j]; for (i = 0, ii = coordinates.length - 1; i < ii; ++i) { segment = coordinates.slice(i, i + 2); - segmentData = /** @type {ol.interaction.SegmentDataType} */ ({ + segmentData = /** @type {SegmentDataType} */ ({ feature: feature, geometry: geometry, depth: [j], index: i, segment: segment }); - this.rBush_.insert(olExtent.boundingExtent(segment), segmentData); + this.rBush_.insert(boundingExtent(segment), segmentData); } } }; @@ -300,8 +303,8 @@ exports.prototype.createOrUpdateVertexFeature_ = /** - * @param {ol.interaction.SegmentDataType} a The first segment data. - * @param {ol.interaction.SegmentDataType} b The second segment data. + * @param {SegmentDataType} a The first segment data. + * @param {SegmentDataType} b The second segment data. * @return {number} The difference in indexes. * @private */ @@ -324,14 +327,14 @@ exports.handleDownEvent_ = function(evt) { if (vertexFeature) { var geometry = /** @type {ol.geom.Point} */ (vertexFeature.getGeometry()); var vertex = geometry.getCoordinates(); - var vertexExtent = olExtent.boundingExtent([vertex]); + var vertexExtent = boundingExtent([vertex]); var segmentDataMatches = this.rBush_.getInExtent(vertexExtent); var componentSegments = {}; segmentDataMatches.sort(exports.compareIndexes_); for (var i = 0, ii = segmentDataMatches.length; i < ii; ++i) { var segmentDataMatch = segmentDataMatches[i]; var segment = segmentDataMatch.segment; - var uid = olBase.getUid(segmentDataMatch.feature); + var uid = getUid(segmentDataMatch.feature); var depth = segmentDataMatch.depth; if (depth) { uid += '-' + depth.join('-'); // separate feature components @@ -339,11 +342,11 @@ exports.handleDownEvent_ = function(evt) { if (!componentSegments[uid]) { componentSegments[uid] = new Array(2); } - if (olCoordinate.equals(segment[0], vertex) && + if (equals(segment[0], vertex) && !componentSegments[uid][0]) { this.dragSegments_.push([segmentDataMatch, 0]); componentSegments[uid][0] = segmentDataMatch; - } else if (olCoordinate.equals(segment[1], vertex) && + } else if (equals(segment[1], vertex) && !componentSegments[uid][1]) { this.dragSegments_.push([segmentDataMatch, 1]); componentSegments[uid][1] = segmentDataMatch; @@ -364,7 +367,7 @@ exports.handleDragEvent_ = function(evt) { var vertex = evt.coordinate; var geometry = /** @type {ol.geom.Polygon}*/ (this.dragSegments_[0][0].geometry); - var center = olExtent.getCenter(geometry.getExtent()); + var center = getCenter(geometry.getExtent()); var line = new olGeomLineString([center, vertex]); @@ -373,7 +376,7 @@ exports.handleDragEvent_ = function(evt) { * @type {ol.geom.Circle} */ var circle = new olGeomCircle(center, line.getLength()); - var coordinates = olGeomPolygon.fromCircle(circle, 64).getCoordinates(); + var coordinates = fromCircle(circle, 64).getCoordinates(); this.setGeometryCoordinates_(geometry, coordinates); this.createOrUpdateVertexFeature_(vertex); @@ -392,8 +395,8 @@ exports.handleUpEvent_ = function(evt) { this.dragSegments_[0][0].geometry); if (this.modified_) { - this.dispatchEvent(new olInteractionModify.Event( - olInteraction.ModifyEventType.MODIFYEND, this.features_, evt)); + this.dispatchEvent(new ModifyEvent( + 'modifyend', this.features_, evt)); this.modified_ = false; } return false; @@ -414,14 +417,13 @@ exports.handleEvent = function(mapBrowserEvent) { } var handled; - if (!mapBrowserEvent.map.getView().getHints()[olBase.ViewHint.INTERACTING] && - mapBrowserEvent.type == olMapBrowserEventType.POINTERMOVE && + if (!mapBrowserEvent.map.getView().getHints()[ViewHint.INTERACTING] && + mapBrowserEvent.type == 'pointermove' && !this.handlingDownUpSequence) { this.handlePointerMove_(mapBrowserEvent); } - return olInteractionPointer.handleEvent.call(this, mapBrowserEvent) && - !handled; + return pointerHandleEvent.call(this, mapBrowserEvent) && !handled; }; @@ -443,15 +445,15 @@ exports.prototype.handlePointerMove_ = function(evt) { exports.prototype.handlePointerAtPixel_ = function(pixel, map) { var pixelCoordinate = map.getCoordinateFromPixel(pixel); var sortByDistance = function(a, b) { - return olCoordinate.squaredDistanceToSegment(pixelCoordinate, a.segment) - - olCoordinate.squaredDistanceToSegment(pixelCoordinate, b.segment); + return squaredDistanceToSegment(pixelCoordinate, a.segment) - + squaredDistanceToSegment(pixelCoordinate, b.segment); }; var lowerLeft = map.getCoordinateFromPixel( [pixel[0] - this.pixelTolerance_, pixel[1] + this.pixelTolerance_]); var upperRight = map.getCoordinateFromPixel( [pixel[0] + this.pixelTolerance_, pixel[1] - this.pixelTolerance_]); - var box = olExtent.boundingExtent([lowerLeft, upperRight]); + var box = boundingExtent([lowerLeft, upperRight]); var rBush = this.rBush_; var nodes = rBush.getInExtent(box); @@ -459,15 +461,15 @@ exports.prototype.handlePointerAtPixel_ = function(pixel, map) { nodes.sort(sortByDistance); var node = nodes[0]; var closestSegment = node.segment; - var vertex = (olCoordinate.closestOnSegment(pixelCoordinate, + var vertex = (closestOnSegment(pixelCoordinate, closestSegment)); var vertexPixel = map.getPixelFromCoordinate(vertex); - if (Math.sqrt(olCoordinate.squaredDistance(pixel, vertexPixel)) <= + if (Math.sqrt(squaredDistance(pixel, vertexPixel)) <= this.pixelTolerance_) { var pixel1 = map.getPixelFromCoordinate(closestSegment[0]); var pixel2 = map.getPixelFromCoordinate(closestSegment[1]); - var squaredDist1 = olCoordinate.squaredDistance(vertexPixel, pixel1); - var squaredDist2 = olCoordinate.squaredDistance(vertexPixel, pixel2); + var squaredDist1 = squaredDistance(vertexPixel, pixel1); + var squaredDist2 = squaredDistance(vertexPixel, pixel2); var dist = Math.sqrt(Math.min(squaredDist1, squaredDist2)); this.snappedToVertex_ = dist <= this.pixelTolerance_; if (this.snappedToVertex_) { @@ -475,15 +477,15 @@ exports.prototype.handlePointerAtPixel_ = function(pixel, map) { closestSegment[1] : closestSegment[0]; this.createOrUpdateVertexFeature_(vertex); var vertexSegments = {}; - vertexSegments[olBase.getUid(closestSegment)] = true; + vertexSegments[getUid(closestSegment)] = true; var segment; for (var i = 1, ii = nodes.length; i < ii; ++i) { segment = nodes[i].segment; - if ((olCoordinate.equals(closestSegment[0], segment[0]) && - olCoordinate.equals(closestSegment[1], segment[1]) || - (olCoordinate.equals(closestSegment[0], segment[1]) && - olCoordinate.equals(closestSegment[1], segment[0])))) { - vertexSegments[olBase.getUid(segment)] = true; + if ((equals(closestSegment[0], segment[0]) && + equals(closestSegment[1], segment[1]) || + (equals(closestSegment[0], segment[1]) && + equals(closestSegment[1], segment[0])))) { + vertexSegments[getUid(segment)] = true; } else { break; } @@ -516,7 +518,7 @@ exports.prototype.setGeometryCoordinates_ = * @return {ol.StyleFunction} Styles. */ exports.getDefaultStyleFunction = function() { - var style = olStyleStyle.createDefaultEditing(); + var style = ngeoInteractionCommon.getDefaultModifyStyleFunction(); return function(feature, resolution) { return style[olGeomGeometryType.POINT]; }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/layermanager/LayermanagerController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/layermanager/LayermanagerController.js index 6cf99e413..dcaac3f43 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/layermanager/LayermanagerController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/layermanager/LayermanagerController.js @@ -18,7 +18,8 @@ */ import appModule from '../module.js'; -import olBase from 'ol.js'; +import {getUid} from 'ol/index.js'; + /** * @param {ngeo.statemanager.Location} ngeoLocation Location service. @@ -33,7 +34,7 @@ const exports = function(ngeoLocation) { */ this.ngeoLocation_ = ngeoLocation; - this['uid'] = olBase.getUid(this); + this['uid'] = getUid(this); /** * Hash array to keep track of opacities set on layers. @@ -72,7 +73,7 @@ exports.prototype.reorderCallback = function(element, layers) { exports.prototype.changeVisibility = function(layer) { var currentOpacity = layer.getOpacity(); var newOpacity; - var uid = olBase.getUid(layer); + var uid = getUid(layer); if (currentOpacity === 0) { if (this.opacities_[uid] !== undefined) { newOpacity = this.opacities_[uid]; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationInfoOverlay.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationInfoOverlay.js index 790fd8d55..2087feea4 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationInfoOverlay.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationInfoOverlay.js @@ -7,7 +7,10 @@ */ import appModule from '../module.js'; -import olStyle from 'ol/style.js'; +import Style from 'ol/style/Style.js'; +import Circle from 'ol/style/Circle.js'; +import Stroke from 'ol/style/Stroke.js'; +import Fill from 'ol/style/Fill.js'; /** * @constructor @@ -23,15 +26,15 @@ const exports = function(ngeoFeatureOverlayMgr) { */ this.featureOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay(); - var defaultFill = new olStyle.Fill({ + var defaultFill = new Fill({ color: [255, 255, 0, 0.6] }); - var circleStroke = new olStyle.Stroke({ + var circleStroke = new Stroke({ color: [255, 155, 55, 1], width: 3 }); - var pointStyle = new olStyle.Circle({ + var pointStyle = new Circle({ radius: 10, fill: defaultFill, stroke: circleStroke @@ -44,7 +47,7 @@ const exports = function(ngeoFeatureOverlayMgr) { * @return {Array.} Array of styles. */ function(feature, resolution) { - return [new olStyle.Style({ + return [new Style({ image: pointStyle })]; }); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationinfoController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationinfoController.js index b5f533371..593c70d65 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationinfoController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/locationinfo/LocationinfoController.js @@ -7,17 +7,17 @@ import appModule from '../module.js'; import olFeature from 'ol/Feature.js'; -import olEvents from 'ol/events.js'; +import {listen} from 'ol/events.js'; import olGeomPoint from 'ol/geom/Point.js'; import olLayerVector from 'ol/layer/Vector.js'; -import olProj from 'ol/proj.js'; +import {transform, transformExtent} from 'ol/proj.js'; import olSourceVector from 'ol/source/Vector.js'; import olStyleCircle from 'ol/style/Circle.js'; import olStyleFill from 'ol/style/Fill.js'; import olStyleStroke from 'ol/style/Stroke.js'; import olStyleStyle from 'ol/style/Style.js'; import olMapBrowserEventType from 'ol/MapBrowserEventType.js'; -import olExtent from 'ol/extent.js'; +import {intersects} from 'ol/extent.js'; /** * @constructor @@ -74,7 +74,7 @@ const exports = function( * @type {ol.Extent} * @private */ - this.lidarExtent_ = olProj.transformExtent( + this.lidarExtent_ = transformExtent( bboxLidar, bboxSrsLidar, this['map'].getView().getProjection()); /** @@ -309,7 +309,7 @@ const exports = function( if (x !== undefined && y !== undefined) { var coordinate = version === 3 ? /** @type {ol.Coordinate} */ ([x, y]) : - /** @type {ol.Coordinate} */ (olProj.transform([y, x], 'EPSG:2169', + /** @type {ol.Coordinate} */ (transform([y, x], 'EPSG:2169', this['map'].getView().getProjection())); this.setClickCordinate_(coordinate); this.loadInfoPane_(); @@ -322,10 +322,10 @@ const exports = function( } } if (this.ngeoLocation_.getParam('address') !== undefined) { - this.appThemes_.getFlatCatalog().then(function(flatCatalogue) { - var node = flatCatalogue.find( - function(catalogueLayer) { - return catalogueLayer['name'] === 'addresses'; + this.appThemes_.getFlatCatalog().then(function(flatCatalog) { + var node = flatCatalog.find( + function(catalogLayer) { + return catalogLayer['name'] === 'addresses'; }, this); if (node !== undefined && node !== null) { var layer = this.getLayerFunc_(node); @@ -340,7 +340,7 @@ const exports = function( var results = data['results']; if (results !== undefined && results.length > 0) { var coordinates = /** @type {ol.Coordinate} */ - (olProj.transform( + (transform( results[0]['geom']['coordinates'], 'EPSG:2169', this['map'].getView().getProjection())); this['map'].getView().setZoom(17); @@ -364,7 +364,7 @@ const exports = function( this.loadInfoPane_(); }.bind(this)); - olEvents.listen(this['map'], olMapBrowserEventType.POINTERDOWN, + listen(this['map'], olMapBrowserEventType.POINTERDOWN, function(event) { if (!appSelectedFeatures.getLength()) { if (event.originalEvent.which === 3) { // if right mouse click @@ -384,13 +384,13 @@ const exports = function( } }.bind(this), this); - olEvents.listen(this['map'], olMapBrowserEventType.POINTERUP, + listen(this['map'], olMapBrowserEventType.POINTERUP, function(event) { $timeout.cancel(holdPromise); startPixel = null; }.bind(this), this); - olEvents.listen(this['map'], olMapBrowserEventType.POINTERMOVE, + listen(this['map'], 'pointermove', function(event) { if (startPixel) { var pixel = event.pixel; @@ -466,9 +466,9 @@ exports.prototype.setClickCordinate_ = function(eventOrCoordinate) { eventOrCoordinate.preventDefault(); this.clickCoordinate = this['map'].getEventCoordinate(eventOrCoordinate); } - this.clickCoordinateLuref_ = olProj.transform( + this.clickCoordinateLuref_ = transform( this.clickCoordinate, this['map'].getView().getProjection(), 'EPSG:2169'); - this.clickCoordinate4326_ = olProj.transform( + this.clickCoordinate4326_ = transform( this.clickCoordinate, this['map'].getView().getProjection(), 'EPSG:4326'); }; @@ -492,7 +492,7 @@ exports.prototype.loadInfoPane_ = this['elevation'] = elevation['formattedElevation']; this.rawElevation_ = elevation['rawElevation']; if (this.lidarDemoUrl_ !== undefined && - this.lidarDemoUrl_.length > 0 && olExtent.intersects( + this.lidarDemoUrl_.length > 0 && intersects( feature.getGeometry().getExtent(), this.lidarExtent_)) { this.isInBoxOfLidar = true; } else { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/main.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/main.js index 44150f266..466410fae 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/main.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/main.js @@ -13,6 +13,7 @@ let exports = {}; * by the HTML page. */ + /* eslint-disable no-unused-vars */ import appAskredirectAskredirectDirective from './askredirect/askredirectDirective.js'; import appAskredirectAskredirectController from './askredirect/AskredirectController.js'; import appAuthenticationAuthenticationDirective from './authentication/authenticationDirective.js'; @@ -22,8 +23,6 @@ import appBackgroundlayerBackgroundlayerController from './backgroundlayer/Backg import appBackgroundlayerBlankLayer from './backgroundlayer/BlankLayer.js'; import appCatalogCatalogController from './catalog/CatalogController.js'; import appCatalogCatalogDirective from './catalog/catalogDirective.js'; -import appImageuploadImguploadController from './imageupload/ImguploadController.js'; -import appImageuploadImguploadDirective from './imageupload/ImguploadDirective.js'; import appDrawDrawDirective from './draw/drawDirective.js'; import appDrawDrawController from './draw/DrawController.js'; import appDrawDrawnFeatures from './draw/DrawnFeatures.js'; @@ -34,7 +33,7 @@ import appDrawFeaturePopupDirective from './draw/featurePopupDirective.js'; import appDrawRouteControl from './draw/RouteControl.js'; //const appDrawRouteControlOptions = goog.require('app.draw.RouteControlOptions'); -import appDrawSelectedFeaturesService from './draw/SelectedFeaturesService.js'; +import appDrawSelectedFeatures from './draw/SelectedFeaturesService.js'; import appDrawStyleEditingController from './draw/StyleEditingController.js'; import appDrawStyleEditingDirective from './draw/styleEditingDirective.js'; @@ -60,7 +59,7 @@ import appInfobarScaleselectorController from './infobar/ScaleselectorController import appLayerinfoLayerinfoDirective from './layerinfo/layerinfoDirective.js'; import appLayerinfoLayerinfoController from './layerinfo/LayerinfoController.js'; import appLocationinfoLocationInfoOverlay from './locationinfo/LocationInfoOverlay.js'; -import appLayerinfoShowLayerinfoFactory from './layerinfo/ShowLayerinfoFactory.js'; +import appLayerinfoShowLayerinfo from './layerinfo/ShowLayerinfoFactory.js'; import appLayermanagerLayermanagerDirective from './layermanager/layermanagerDirective.js'; import appLayermanagerLayermanagerController from './layermanager/LayermanagerController.js'; import appLayerlegendsLayerlegendsDirective from './layerlegends/layerlegendsDirective.js'; @@ -75,7 +74,7 @@ import appMeasureMeasureController from './measure/MeasureController.js'; import appMeasureMeasureDirective from './measure/MeasureDirective.js'; import appMymapsMymapsDirective from './mymaps/mymapsDirective.js'; import appMymapsMymapsController from './mymaps/MymapsController.js'; -import appNotifyFactory from './NotifyFactory.js'; +import appNotify from './NotifyFactory.js'; import appPrintPrintDirective from './print/printDirective.js'; import appPrintPrintController from './print/PrintController.js'; import appPrintPrintservice from './print/Printservice.js'; @@ -108,16 +107,16 @@ import appStreetviewStreetviewController from './streetview/StreetviewController import appThemeswitcherThemeswitcherDirective from './themeswitcher/themeswitcherDirective.js'; import appThemeswitcherThemeswitcherController from './themeswitcher/ThemeswitcherController.js'; import appActivetool from './Activetool.js'; -import appCoordinateStringService from './CoordinateStringService.js'; +import appCoordinateString from './CoordinateStringService.js'; import appExport from './Export.js'; import appGeocoding from './Geocoding.js'; import appGetDevice from './GetDevice.js'; -import appGetElevationService from './GetElevationService.js'; -import appGetLayerForCatalogNodeFactory from './GetLayerForCatalogNodeFactory.js'; -import appGetProfileService from './GetProfileService.js'; -import appGetShorturlService from './GetShorturlService.js'; -import appGetWmsLayerFactory from './GetWmsLayerFactory.js'; -import appGetWmtsLayerFactory from './GetWmtsLayerFactory.js'; +import appGetElevation from './GetElevationService.js'; +import appGetLayerForCatalogNode from './GetLayerForCatalogNodeFactory.js'; +import appGetProfile from './GetProfileService.js'; +import appGetShorturl from './GetShorturlService.js'; +import appGetWmsLayer from './GetWmsLayerFactory.js'; +import appGetWmtsLayer from './GetWmtsLayerFactory.js'; import appLayerOpacityManager from './LayerOpacityManager.js'; import appLayerPermalinkManager from './LayerPermalinkManager.js'; import appLocationControl from './LocationControl.js'; @@ -148,5 +147,6 @@ import appWmtsHelper from './WmtsHelper.js'; import appMiscFile from './misc/file.js'; import appLotChasse from './LotChasse.js'; +/* eslint-enable no-unused-vars */ export default exports; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/map/MapController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/map/MapController.js index 6b76f2a18..70c2b40e7 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/map/MapController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/map/MapController.js @@ -11,7 +11,7 @@ import appModule from '../module.js'; import olMapProperty from 'ol/MapProperty.js'; -import olProj from 'ol/proj.js'; +import {getTransform, transform} from 'ol/proj.js'; /** * @param {app.StateManager} appStateManager State manager service. @@ -20,7 +20,7 @@ import olProj from 'ol/proj.js'; * @ngInject */ const exports = function(appStateManager, ngeoDebounce) { - var lurefToWebMercatorFn = olProj.getTransform('EPSG:2169', 'EPSG:3857'); + var lurefToWebMercatorFn = getTransform('EPSG:2169', 'EPSG:3857'); /** @type {ol.Map} */ var map = this['map']; @@ -49,7 +49,7 @@ const exports = function(appStateManager, ngeoDebounce) { viewCenter = version === 3 ? [+x, +y] : lurefToWebMercatorFn([+y, +x], undefined, 2); } else { - viewCenter = olProj.transform([6, 49.7], 'EPSG:4326', 'EPSG:3857'); + viewCenter = transform([6, 49.7], 'EPSG:4326', 'EPSG:3857'); } view.setCenter(viewCenter); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/measure/MeasureController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/measure/MeasureController.js index 7f46c8cdb..6ef6c76cc 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/measure/MeasureController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/measure/MeasureController.js @@ -19,10 +19,9 @@ import ngeoMiscDecorate from 'ngeo/misc/decorate.js'; import ngeoInteractionMeasureArea from 'ngeo/interaction/MeasureArea.js'; import ngeoInteractionMeasureAzimut from 'ngeo/interaction/MeasureAzimut.js'; import ngeoInteractionMeasureLength from 'ngeo/interaction/MeasureLength.js'; -import olObject from 'ol/Object.js'; -import olEvents from 'ol/events.js'; -import olInteractionProperty from 'ol/interaction/Property.js'; -import olProj from 'ol/proj.js'; +import {getChangeEventType} from 'ol/Object.js'; +import {listen} from 'ol/events.js'; +import {transform} from 'ol/proj.js'; import olStyleCircle from 'ol/style/Circle.js'; import olStyleFill from 'ol/style/Fill.js'; import olStyleStroke from 'ol/style/Stroke.js'; @@ -34,6 +33,7 @@ import olStyleStyle from 'ol/style/Style.js'; * @param {angular.$http} $http Angular http service. * @param {angular.$compile} $compile The compile provider. * @param {gettext} gettext Gettext service. + * @param {!angularGettext.Catalog} gettextCatalog Gettext catalog. * @param {app.GetProfile} appGetProfile The profile service. * interaction service. * @param {string} elevationServiceUrl The url of the service. @@ -44,7 +44,7 @@ import olStyleStyle from 'ol/style/Style.js'; * @ngInject */ const exports = function($scope, $q, $http, $compile, gettext, - appGetProfile, elevationServiceUrl, + gettextCatalog, appGetProfile, elevationServiceUrl, appActivetool, $filter) { /** @@ -119,7 +119,7 @@ const exports = function($scope, $q, $http, $compile, gettext, 'Double-click or click last point to finish'); var measureProfile = new ngeoInteractionMeasureLength( $filter('ngeoUnitPrefix'), - { + gettextCatalog, { startMsg: $compile('
' + helpMsg + '
')($scope)[0], continueMsg: $compile('
' + contMsg + '
')($scope)[0], sketchStyle: sketchStyle @@ -136,7 +136,7 @@ const exports = function($scope, $q, $http, $compile, gettext, helpMsg = gettext('Click to start drawing length'); var measureLength = new ngeoInteractionMeasureLength( $filter('ngeoUnitPrefix'), - { + gettextCatalog, { startMsg: $compile('
' + helpMsg + '
')($scope)[0], continueMsg: $compile('
' + contMsg + '
')($scope)[0], sketchStyle: sketchStyle @@ -161,7 +161,7 @@ const exports = function($scope, $q, $http, $compile, gettext, 'Double-click or click last point to finish'); var measureArea = new ngeoInteractionMeasureArea( $filter('ngeoUnitPrefix'), - { + gettextCatalog, { startMsg: $compile('
' + helpMsg + '
')($scope)[0], continueMsg: $compile('
' + contMsg + '
')($scope)[0], sketchStyle: sketchStyle, @@ -198,7 +198,7 @@ const exports = function($scope, $q, $http, $compile, gettext, ngeoMiscDecorate.interaction(measureAzimut); this.map_.addInteraction(measureAzimut); - olEvents.listen(measureAzimut, 'measureend', + listen(measureAzimut, 'measureend', function(evt) { var geometryCollection = /** @type {ol.geom.GeometryCollection} */ @@ -220,7 +220,7 @@ const exports = function($scope, $q, $http, $compile, gettext, }.bind(this)); }.bind(this)); - olEvents.listen(measureProfile, 'measureend', + listen(measureProfile, 'measureend', function(evt) { var geom = /** @type {ol.geom.LineString} */ (evt.detail.feature.getGeometry()); @@ -230,7 +230,7 @@ const exports = function($scope, $q, $http, $compile, gettext, }.bind(this)); }, this); - olEvents.listen(measureProfile, olObject.getChangeEventType('active'), + listen(measureProfile, getChangeEventType('active'), /** * @param {ol.Object.Event} evt Change active event. */ @@ -256,17 +256,17 @@ const exports = function($scope, $q, $http, $compile, gettext, this.appActivetool_.measureActive = false; } }.bind(this)); - olEvents.listen(this['measureLength'], olObject.getChangeEventType( - olInteractionProperty.ACTIVE), + listen(this['measureLength'], getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(this['measureArea'], olObject.getChangeEventType( - olInteractionProperty.ACTIVE), + listen(this['measureArea'], getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(this['measureAzimut'], olObject.getChangeEventType( - olInteractionProperty.ACTIVE), + listen(this['measureAzimut'], getChangeEventType( + 'active'), this.onChangeActive_, this); - olEvents.listen(this['measureProfile'], olObject.getChangeEventType( - olInteractionProperty.ACTIVE), + listen(this['measureProfile'], getChangeEventType( + 'active'), this.onChangeActive_, this); }; @@ -294,7 +294,7 @@ exports.prototype.onChangeActive_ = function(event) { */ exports.prototype.getElevation_ = function(coordinates) { var eastnorth = - /** @type {ol.Coordinate} */ (olProj.transform( + /** @type {ol.Coordinate} */ (transform( coordinates, this.map_.getView().getProjection(), 'EPSG:2169')); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/module.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/module.js index 24f56178f..2b5537c65 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/module.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/module.js @@ -7,8 +7,8 @@ * module. */ -import olHas from 'ol/has.js'; -import ngeoBase from 'ngeo.js'; +import {TOUCH} from 'ol/has.js'; + import ngeoDatasourceModule from 'ngeo/datasource/module.js'; import ngeoDownloadModule from 'ngeo/download/module.js'; import ngeoDrawModule from 'ngeo/draw/module.js'; @@ -33,10 +33,13 @@ import ngeoStatemanagerLocation from 'ngeo/statemanager/Location.js'; import ngeoStatemanagerModule from 'ngeo/statemanager/module.js'; import ngeoStatemanagerWfsPermalink from 'ngeo/statemanager/WfsPermalink.js'; +const fakeGmfAbstractAppControllerModule = angular.module('GmfAbstractAppControllerModule', []); + /** * @type {!angular.Module} */ -const exports = angular.module('app', [ +const exports = angular.module('Appmain', [ + fakeGmfAbstractAppControllerModule.name, ngeoDatasourceModule.name, ngeoDownloadModule.name, ngeoDrawModule.name, @@ -59,7 +62,7 @@ const exports = angular.module('app', [ ngeoStatemanagerModule.name, ngeoStatemanagerWfsPermalink.module.name, 'gettext']).run(function() { - if (!olHas.TOUCH) { + if (!TOUCH) { document.body.classList.add('no-touch'); } }); @@ -70,13 +73,6 @@ const exports = angular.module('app', [ exports.config(ngeoStatemanagerLocation.MockProvider); -// activate pre-assigning bindings -// See https://toddmotto.com/angular-1-6-is-here#component-and-oninit -exports.config(['$compileProvider', function($compileProvider) { - $compileProvider.preAssignBindingsEnabled(true); -}]); - - // Strict Contextual Escaping (SCE) configuration exports.config(['$sceDelegateProvider', function($sceDelegateProvider) { $sceDelegateProvider.resourceUrlWhitelist([ @@ -97,6 +93,9 @@ exports.config(['$httpProvider', function($httpProvider) { request: function(config) { if (config.method == 'GET' && config.url.indexOf('geoportailv3.json') === -1 && // static files already have cache control + config.url.indexOf('templatecache/') !== 0 && // template cache URLs should not be tempered (see below) + config.url.indexOf('fr.json') !== -1 && config.url.indexOf('de.json') !== -1 && + config.url.indexOf('lb.json') !== -1 && config.url.indexOf('en.json') !== -1 && config.url.indexOf('.html') === -1) { var separator = config.url.indexOf('?') === -1 ? '?' : '&'; config.url = config.url + separator + 'noCache=' + new Date().getTime(); @@ -106,4 +105,97 @@ exports.config(['$httpProvider', function($httpProvider) { }); +exports.constant('ngeoLayertreeTemplateUrl', 'templatecache/ngeoLayertreeTemplateUrl'); +exports.constant('ngeoPopupTemplateUrl', 'templatecache/ngeoPopupTemplateUrl'); +exports.constant('ngeoScaleselectorTemplateUrl', 'templatecache/ngeoScaleselectorTemplateUrl'); +exports.constant('ngeoOfflineTestUrl', '/ping'); +exports.constant('ngeoOfflineTemplateUrl', () => 'templatecache/ngeoOfflineTemplateUrl'); +exports.constant('ngeoOlcsControls3dTemplateUrl', 'templatecache/ngeoOlcsControls3dTemplateUrl'); +exports.constant('appBackgroundlayerTemplateUrl', 'templatecache/appBackgroundlayerTemplateUrl'); +exports.constant('appLayermanagerTemplateUrl', 'templatecache/appLayermanagerTemplateUrl'); +exports.constant('appLayerlegendsTemplateUrl', 'templatecache/appLayerlegendsTemplateUrl'); +exports.constant('appStreetviewTemplateUrl', 'templatecache/appStreetviewTemplateUrl'); +exports.constant('appSliderTemplateUrl', 'templatecache/appSliderTemplateUrl'); +exports.constant('appMeasureTemplateUrl', 'templatecache/appMeasureTemplateUrl'); +exports.constant('appDrawTemplateUrl', 'templatecache/appDrawTemplateUrl'); +exports.constant('appFeaturePopupTemplateUrl', 'templatecache/appFeaturePopupTemplateUrl'); +exports.constant('appStyleEditingTemplateUrl', 'templatecache/appStyleEditingTemplateUrl'); +exports.constant('appSymbolSelectorTemplateUrl', 'templatecache/appSymbolSelectorTemplateUrl'); +exports.constant('appLayerinfoTemplateUrl', 'templatecache/appLayerinfoTemplateUrl'); +exports.constant('appAuthenticationTemplateUrl', 'templatecache/appAuthenticationTemplateUrl'); +exports.constant('appInfobarTemplateUrl', 'templatecache/appInfobarTemplateUrl'); +exports.constant('appProjectionselectorTemplateUrl', 'templatecache/appProjectionselectorTemplateUrl'); +exports.constant('appMapTemplateUrl', 'templatecache/appMapTemplateUrl'); +exports.constant('appThemeswitcherTemplateUrl', 'templatecache/appThemeswitcherTemplateUrl'); +exports.constant('appProfileTemplateUrl', 'templatecache/appProfileTemplateUrl'); +exports.constant('appPrintTemplateUrl', 'templatecache/appPrintTemplateUrl'); +exports.constant('appSearchTemplateUrl', 'templatecache/appSearchTemplateUrl'); +exports.constant('appShareTemplateUrl', 'templatecache/appShareTemplateUrl'); +exports.constant('appShorturlTemplateUrl', 'templatecache/appShorturlTemplateUrl'); +exports.constant('appQueryTemplateUrl', 'templatecache/appQueryTemplateUrl'); +exports.constant('appLocationinfoTemplateUrl', 'templatecache/appLocationinfoTemplateUrl'); +exports.constant('appMymapsTemplateUrl', 'templatecache/appMymapsTemplateUrl'); +exports.constant('appRoutingTemplateUrl', 'templatecache/appRoutingTemplateUrl'); +exports.constant('appPagreportTemplateUrl', 'templatecache/appPagreportTemplateUrl'); +exports.constant('appCasiporeportTemplateUrl', 'templatecache/appCasiporeportTemplateUrl'); +exports.constant('appPdsreportTemplateUrl', 'templatecache/appPdsreportTemplateUrl'); +exports.constant('appExternalDataTemplateUrl', 'templatecache/appExternalDataTemplateUrl'); +exports.constant('appWmsTreeTemplateUrl', 'templatecache/appWmsTreeTemplateUrl'); +exports.constant('appWmtsTreeTemplateUrl', 'templatecache/appWmtsTreeTemplateUrl'); +exports.constant('appFeedbackTemplateUrl', 'templatecache/appFeedbackTemplateUrl'); +exports.constant('appAskredirectTemplateUrl', 'templatecache/appAskredirectTemplateUrl'); + +/** + * @ngInject + * @param {any} $templateCache The template cache + */ +function templateRunner($templateCache) { + $templateCache.put('templatecache/ngeoLayertreeTemplateUrl', require('./catalog/layertree.html')); + $templateCache.put('templatecache/ngeoPopupTemplateUrl', require('./layerinfo/popup.html')); + $templateCache.put('templatecache/ngeoScaleselectorTemplateUrl', require('./infobar/scaleselector.html')); + $templateCache.put('templatecache/ngeoOfflineTemplateUrl', require('./offlineNgeoComponent.html')); // # FIXME was a function + $templateCache.put('templatecache/ngeoOlcsControls3dTemplateUrl', require('./olcs/controls3d.html')); + $templateCache.put('templatecache/appBackgroundlayerTemplateUrl', require('./backgroundlayer/backgroundlayer.html')); + $templateCache.put('templatecache/appLayermanagerTemplateUrl', require('./layermanager/layermanager.html')); + $templateCache.put('templatecache/appLayerlegendsTemplateUrl', require('./layerlegends/layerlegends.html')); + $templateCache.put('templatecache/appStreetviewTemplateUrl', require('./streetview/streetview.html')); + $templateCache.put('templatecache/appSliderTemplateUrl', require('./slider/slider.html')); + $templateCache.put('templatecache/appMeasureTemplateUrl', require('./measure/measure.html')); + $templateCache.put('templatecache/appDrawTemplateUrl', require('./draw/draw.html')); + $templateCache.put('templatecache/appFeaturePopupTemplateUrl', require('./draw/featurepopup.html')); + $templateCache.put('templatecache/appStyleEditingTemplateUrl', require('./draw/styleediting.html')); + $templateCache.put('templatecache/appSymbolSelectorTemplateUrl', require('./draw/symbolselector.html')); + $templateCache.put('templatecache/appLayerinfoTemplateUrl', require('./layerinfo/layerinfo.html')); + $templateCache.put('templatecache/appAuthenticationTemplateUrl', require('./authentication/authentication.html')); + $templateCache.put('templatecache/appInfobarTemplateUrl', require('./infobar/infobar.html')); + $templateCache.put('templatecache/appProjectionselectorTemplateUrl', require('./infobar/projectionselector.html')); + $templateCache.put('templatecache/appMapTemplateUrl', require('./map/map.html')); + $templateCache.put('templatecache/appThemeswitcherTemplateUrl', require('./themeswitcher/themes.html')); + $templateCache.put('templatecache/appProfileTemplateUrl', require('./profile/profile.html')); + $templateCache.put('templatecache/appPrintTemplateUrl', require('./print/print.html')); + $templateCache.put('templatecache/appSearchTemplateUrl', require('./search/search.html')); + $templateCache.put('templatecache/appShareTemplateUrl', require('./share/share.html')); + $templateCache.put('templatecache/appShorturlTemplateUrl', require('./share/shorturl.html')); + $templateCache.put('templatecache/appQueryTemplateUrl', require('./query/info.html')); + $templateCache.put('templatecache/appLocationinfoTemplateUrl', require('./locationinfo/locationinfo.html')); + $templateCache.put('templatecache/appMymapsTemplateUrl', require('./mymaps/mymaps.html')); + $templateCache.put('templatecache/appRoutingTemplateUrl', require('./routing/routing.html')); + $templateCache.put('templatecache/appPagreportTemplateUrl', require('./query/pagreport.html')); + $templateCache.put('templatecache/appCasiporeportTemplateUrl', require('./query/casiporeport.html')); + $templateCache.put('templatecache/appPdsreportTemplateUrl', require('./query/pdsreport.html')); + $templateCache.put('templatecache/appExternalDataTemplateUrl', require('./externaldata/externaldata.html')); + $templateCache.put('templatecache/appWmsTreeTemplateUrl', require('./externaldata/wmstree.html')); + $templateCache.put('templatecache/appWmtsTreeTemplateUrl', require('./externaldata/wmtstree.html')); + $templateCache.put('templatecache/appFeedbackTemplateUrl', require('./feedback/feedback.html')); + $templateCache.put('templatecache/appAskredirectTemplateUrl', require('./askredirect/askredirect.html')); +} + +// activate pre-assigning bindings +// See https://toddmotto.com/angular-1-6-is-here#component-and-oninit +exports.config(['$compileProvider', function($compileProvider) { + $compileProvider.preAssignBindingsEnabled(true); +}]); + +exports.run(templateRunner); + export default exports; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/MymapsController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/MymapsController.js index 33aeeeb1c..52cad963d 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/MymapsController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/MymapsController.js @@ -13,7 +13,7 @@ import appModule from '../module.js'; import appMiscFile from '../misc/file.js'; import appNotifyNotificationType from '../NotifyNotificationType.js'; -import olExtent from 'ol/extent.js'; +import {extend} from 'ol/extent.js'; import olFormatGPX from 'ol/format/GPX.js'; import olFormatKML from 'ol/format/KML.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; @@ -597,7 +597,7 @@ exports.prototype.importGpx = function() { featuresToSave.push(feature); } if (gpxExtent) { - olExtent.extend(gpxExtent, curGeometry.getExtent()); + extend(gpxExtent, curGeometry.getExtent()); } else { gpxExtent = curGeometry.getExtent(); } @@ -663,7 +663,7 @@ exports.prototype.importKml = function(kml) { var curGeometry = feature.getGeometry(); if (curGeometry !== null) { if (kmlExtent) { - olExtent.extend(kmlExtent, curGeometry.getExtent()); + extend(kmlExtent, curGeometry.getExtent()); } else { kmlExtent = curGeometry.getExtent(); } @@ -724,11 +724,6 @@ exports.prototype.sanitizeFeature_ = function(feature) { feature.unset('__selected__', true); } - var color = /** @type {string} */ (feature.get('color')); - if (color === undefined) { - feature.set('color', '#FF0000'); - } - var opacity = /** @type {string} */ (feature.get('opacity')); if (opacity === undefined) { opacity = 0.2; @@ -1339,7 +1334,7 @@ exports.prototype.selectMymaps = function(map) { this.drawnFeatures_.getCollection().forEach(function(feature) { if (feature.get('__map_id__')) { if (extent !== undefined) { - extent = olExtent.extend(extent, feature.getGeometry().getExtent()); + extent = extend(extent, feature.getGeometry().getExtent()); } else { extent = feature.getGeometry().getExtent(); } diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/mymaps.html b/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/mymaps.html index 0b546c6d5..21fd97072 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/mymaps.html +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/mymaps/mymaps.html @@ -199,7 +199,7 @@ -
    +
    • {{ feature.get('name') }}
    • diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/offline/Configuration.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/offline/Configuration.js index 19bd7ece6..ee2a5c392 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/offline/Configuration.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/offline/Configuration.js @@ -1,7 +1,7 @@ /** * @module app.offline.Configuration */ -import olBase from 'ol.js'; +import {boundingExtent, getWidth, getCenter, buffer} from 'ol/extent.js'; import olLayerVector from 'ol/layer/Vector.js'; import ngeoOfflineModule from 'ngeo/offline/module.js'; import NgeoConfiguration from 'ngeo/offline/Configuration.js'; @@ -56,7 +56,7 @@ const exports = class extends NgeoConfiguration { console.log(msg, key, start); promise.then( () => console.log('OK', msg, key, new Date() - start), - (err) => console.log('ERROR', msg, key, err, new Date() - start) + err => console.log('ERROR', msg, key, err, new Date() - start) ); return promise; } @@ -102,7 +102,7 @@ const exports = class extends NgeoConfiguration { if (this.isBgLayer_(layer, map)) { const zooms = [8, 9, 10, 11, 12, 13, 14, 15, ...zoomRange.filter(dz => dz > 15)]; const view = map.getView(); - const userExtentSideInMeters = olBase.extent.getWidth(userExtent); + const userExtentSideInMeters = getWidth(userExtent); const fakeViewportSideInPixels = 2 * 1024; return zooms.map((z) => { const resolution = view.getResolutionForZoom(z); @@ -110,11 +110,12 @@ const exports = class extends NgeoConfiguration { let extent = userExtent; if (fakeViewportSideInMeters > userExtentSideInMeters) { // the fake viewport at this resolution covers a bigger area than the user extent - extent = olBase.extent.boundingExtent([olBase.extent.getCenter(userExtent)]); - olBase.extent.buffer(extent, fakeViewportSideInMeters / 2, extent); + extent = boundingExtent([getCenter(userExtent)]); + buffer(extent, fakeViewportSideInMeters / 2, extent); } + const zoom = z; return { - zoom: z, + zoom, extent }; }); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Extent.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Extent.js index a33ab9426..fc0f75d19 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Extent.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Extent.js @@ -1,13 +1,13 @@ /** * @module app.olcs.Extent */ -import olProj from 'ol/proj.js'; +import {transformExtent} from 'ol/proj.js'; /** * The OpenLayers extent used in 3D to restrict the area rendered by Cesium. * @type {ol.Extent} */ -const exports = olProj.transformExtent([5.31, 49.38, 6.64, 50.21], 'EPSG:4326', 'EPSG:3857'); +const exports = transformExtent([5.31, 49.38, 6.64, 50.21], 'EPSG:4326', 'EPSG:3857'); export default exports; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Lux3DManager.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Lux3DManager.js index f3eb18702..8f58e0d1c 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Lux3DManager.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/Lux3DManager.js @@ -3,6 +3,8 @@ */ import ngeoOlcsManager from 'ngeo/olcs/Manager.js'; +import OLCesium from 'olcs/OLCesium.js' + const exports = class extends ngeoOlcsManager { /** * @@ -89,7 +91,7 @@ const exports = class extends ngeoOlcsManager { const map = /** @type {!ol.Map} */ (this.map); const niceIlluminationDate = Cesium.JulianDate['fromDate'](new Date('June 21, 2018 12:00:00 GMT+0200')); const time = () => niceIlluminationDate; - const ol3d = new olcs.OLCesium({map, time, sceneOptions}); + const ol3d = new OLCesium({map, time, sceneOptions}); const scene = ol3d.getCesiumScene(); @@ -135,7 +137,7 @@ const exports = class extends ngeoOlcsManager { * @param {boolean} visible Visibility. */ set3dTilesetVisible(visible) { - this.tilesets3d.forEach((tileset) => tileset.show = visible); + this.tilesets3d.forEach(tileset => tileset.show = visible); } /** diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/ZoomToExtent.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/ZoomToExtent.js index 40878d735..1bb5d9956 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/ZoomToExtent.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/ZoomToExtent.js @@ -9,7 +9,8 @@ const exports = class extends olControlZoomToExtent { * @param {app.olcs.Lux3DManager} ol3dm Manager getter */ constructor(extent, ol3dm) { - super({label: '\ue01b', extent}); + const label = '\ue01b'; + super({label, extent}); /** * @const {app.olcs.Lux3DManager} * @private diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/toggle3d.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/toggle3d.js index 0b805c67a..4e218ef6c 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/toggle3d.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/olcs/toggle3d.js @@ -35,7 +35,7 @@ const toggle3d = { ` }; -angular.module('app').component('appToggle3d', toggle3d); +angular.module('Appmain').component('appToggle3d', toggle3d); export default exports; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/print/PrintController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/print/PrintController.js index cadcd60df..85be82722 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/print/PrintController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/print/PrintController.js @@ -15,11 +15,12 @@ import appModule from '../module.js'; import appPrintPrintservice from '../print/Printservice.js'; -import olArray from 'ol/array.js'; -import olEasing from 'ol/easing.js'; -import olEvents from 'ol/events.js'; -import olObservable from 'ol/Observable.js'; -import olProj from 'ol/proj.js'; +import {includes as arrayIncludes} from 'ol/array.js'; +import {easeOut} from 'ol/easing.js'; +import {listen} from 'ol/events.js'; +import {unByKey} from 'ol/Observable.js'; +import {getPointResolution} from 'ol/proj.js'; +import LayerGroup from 'ol/layer/Group.js'; import olRenderEventType from 'ol/render/EventType.js'; /** @@ -41,6 +42,8 @@ import olRenderEventType from 'ol/render/EventType.js'; * @param {ngeo.map.BackgroundLayerMgr} ngeoBackgroundLayerMgr Background layer * @param {angular.$http} $http Angular $http service. * @param {ngeo.map.LayerHelper} ngeoLayerHelper Ngeo Layer Helper. + * @param {string} appImagesPath Path the the static images. + * @param {string} arrowUrl URL to the arrow. * @constructor * @export * @ngInject @@ -49,7 +52,8 @@ const exports = function($scope, $window, $timeout, $q, gettextCatalog, ngeoFeatureOverlayMgr, ngeoPrintUtils, appThemes, appTheme, appFeaturePopup, appGetShorturl, printServiceUrl, qrServiceUrl, appSelectedFeatures, - ngeoBackgroundLayerMgr, $http, ngeoLayerHelper) { + ngeoBackgroundLayerMgr, $http, ngeoLayerHelper, appImagesPath, + arrowUrl) { /** * @type {ngeo.map.BackgroundLayerMgr} @@ -79,8 +83,7 @@ const exports = function($scope, $window, $timeout, $q, gettextCatalog, * @type {ol.Map} * @private */ - this.map_ = this['map']; - console.assert(this.map_ !== undefined && this.map_ !== null); + this.map_; /** * @type {angular.$timeout} @@ -110,7 +113,7 @@ const exports = function($scope, $window, $timeout, $q, gettextCatalog, * @type {ngeo.print.Service} * @private */ - this.print_ = new appPrintPrintservice(printServiceUrl, $http, ngeoLayerHelper); + this.print_ = new appPrintPrintservice(printServiceUrl, $http, ngeoLayerHelper, appImagesPath, arrowUrl); /** * @type {ngeo.print.Utils} @@ -265,10 +268,10 @@ const exports = function($scope, $window, $timeout, $q, gettextCatalog, this.featurePopup_.hide(); this.useOptimalScale_(); console.assert(postcomposeListenerKey === null); - postcomposeListenerKey = olEvents.listen(this.map_, + postcomposeListenerKey = listen(this.map_, olRenderEventType.POSTCOMPOSE, postcomposeListener); } else if (postcomposeListenerKey !== null) { - olObservable.unByKey(postcomposeListenerKey); + unByKey(postcomposeListenerKey); postcomposeListenerKey = null; } this.map_.render(); @@ -288,7 +291,7 @@ const exports = function($scope, $window, $timeout, $q, gettextCatalog, * @type {Array.} * @private */ -exports.DEFAULT_MAP_SCALES_ = [1500, 2500, 5000, 10000, 15000, +const DEFAULT_MAP_SCALES = [1500, 2500, 5000, 10000, 15000, 20000, 25000, 50000, 80000, 100000, 125000, 200000, 250000, 400000]; @@ -333,7 +336,7 @@ exports.getViewCenterResolution_ = function(view) { console.assert(viewCenter !== undefined); console.assert(viewProjection !== null); console.assert(viewResolution !== undefined); - return olProj.getPointResolution(viewProjection, /** @type{number} */(viewResolution), /** @type{Array} */(viewCenter)); + return getPointResolution(viewProjection, /** @type{number} */(viewResolution), /** @type{Array} */(viewCenter)); }; @@ -414,6 +417,13 @@ exports.prototype.changeLayout = function(newLayout) { this.map_.render(); }; +/** + * @export + */ +exports.prototype.$onInit = function() { + this.map_ = this['map']; + console.assert(this.map_ !== undefined && this.map_ !== null); +}; /** * @param {number} newScale The new scale. @@ -441,7 +451,7 @@ exports.prototype.changeScale = function(newScale) { console.assert(newResolution >= optimalResolution); view.animate({ duration: 250, - easing: olEasing.easeOut, + easing: easeOut, resolution: currentResolution }); } @@ -502,6 +512,24 @@ exports.prototype.print = function(format) { } }); + function recursiveGetLayerAttributions(layer, dataOwners) { + if (layer instanceof LayerGroup) { + layer.getLayers().forEach(l => recursiveGetLayerAttributions(l, dataOwners)); + } else { + let source = undefined; + if (/** @type {Object} */ (layer).getSource instanceof Function) { + source = /** @type {Object} */ (layer).getSource(); + } + if (source != undefined) { + const attributions = source.getAttributions(); + if (attributions !== null) { + const htmls = attributions(); + dataOwners.push(...htmls); + } + } + } + } + this.getShorturl_().then( /** * @param {string} shorturl The short URL. @@ -511,26 +539,12 @@ exports.prototype.print = function(format) { this['printing'] = true; var format = curFormat; var dataOwners = []; - map.getLayers().forEach(function(layer) { - var source = undefined; - if (/** @type{Object} */ (layer).getSource instanceof Function) { - source = /** @type{Object} */ (layer).getSource(); - } - if (source != undefined) { - var attributions = source.getAttributions(); - if (attributions !== null) { - attributions.forEach(function(attribution) { - dataOwners.push(attribution.getHTML()); - }.bind(this)); - } - } - }); + recursiveGetLayerAttributions(map.getLayerGroup(), dataOwners); var routingAttributions = this.featureOverlayLayer_.getSource().getAttributions(); - if (routingAttributions !== undefined && routingAttributions !== null) { - routingAttributions.forEach(function(attribution) { - dataOwners.push(attribution.getHTML()); - }, this); + if (routingAttributions) { + const htmls = routingAttributions(); + dataOwners.push(...htmls); } //Remove duplicates. dataOwners = dataOwners.filter(function(item, pos, self) { @@ -754,28 +768,20 @@ exports.prototype.setScales_ = function() { /** * @param {Object} tree Tree object for the theme. */ - (function(tree) { + tree => { var scales; - if (tree === null) { + if (!tree) { this.needScaleRefresh = true; } - if (tree !== null && tree['metadata']['print_scales']) { - var printScalesStr = tree['metadata']['print_scales']; - scales = printScalesStr.trim().split(',').map( - /** - * @param {string} scale Scale value as a string. - * @return {number} Scale value as a number. - */ - function(scale) { - return +scale; - }); - scales.sort((a, b) => a - b); + if (tree && tree['metadata']['print_scales']) { + scales = tree['metadata']['print_scales'].map(s => +s); + scales.sort((a, b) => a - b); // sort numerically } else { - scales = exports.DEFAULT_MAP_SCALES_; + scales = DEFAULT_MAP_SCALES; } this['scales'] = scales; var scale = this['scale']; - if (scale != -1) { + if (scale !== -1) { // find nearest scale to current scale scale = exports.findNearestScale_(scales, scale); if (scale != this['scale']) { @@ -783,7 +789,7 @@ exports.prototype.setScales_ = function() { this.map_.render(); } } - }).bind(this)); + }); }; @@ -857,7 +863,7 @@ exports.prototype.getCSSStyles_ = function(parentElement) { // Add Parent element Id and Classes to the list selectorTextArr.push('#' + parentElement.id); for (var c1 = 0; c1 < parentElement.classList.length; c1++) { - if (!olArray.includes(selectorTextArr, '.' + parentElement.classList[c1])) { + if (!arrayIncludes(selectorTextArr, '.' + parentElement.classList[c1])) { selectorTextArr.push('.' + parentElement.classList[c1]); } } @@ -865,12 +871,12 @@ exports.prototype.getCSSStyles_ = function(parentElement) { var nodes = parentElement.getElementsByTagName('*'); for (var i1 = 0; i1 < nodes.length; i1++) { var id = nodes[i1].id; - if (!olArray.includes(selectorTextArr, '#' + id)) { + if (!arrayIncludes(selectorTextArr, '#' + id)) { selectorTextArr.push('#' + id); } var classes = nodes[i1].classList; for (var c2 = 0; c2 < classes.length; c2++) { - if (!olArray.includes(selectorTextArr, '.' + classes[c2])) { + if (!arrayIncludes(selectorTextArr, '.' + classes[c2])) { selectorTextArr.push('.' + classes[c2]); } } @@ -893,7 +899,7 @@ exports.prototype.getCSSStyles_ = function(parentElement) { var cssRules = s.cssRules; for (var r1 = 0; r1 < cssRules.length; r1++) { - if (olArray.includes(selectorTextArr, cssRules[r1].selectorText)) { + if (arrayIncludes(selectorTextArr, cssRules[r1].selectorText)) { extractedCSSText += cssRules[r1].cssText; } } diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/print/Printservice.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/print/Printservice.js index 345a386c7..24ac413c7 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/print/Printservice.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/print/Printservice.js @@ -2,17 +2,57 @@ * @module app.print.Printservice */ import ngeoPrintService from 'ngeo/print/Service.js'; -import olArray from 'ol/array.js'; -import olObj from 'ol/obj.js'; -import olMath from 'ol/math.js'; +import {stableSort} from 'ol/array.js'; +import {assign} from 'ol/obj.js'; +import {toDegrees} from 'ol/math.js'; + +import VectorEncoder from 'ngeo/print/VectorEncoder.js'; + +function rgbToHex(r, g, b) { + return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); +} + +class AppVectorEncoder extends VectorEncoder { + /** + * @param {string} appImagesPath Path the the static images. + * @param {string} arrowUrl URL to the arrow. + */ + constructor(appImagesPath, arrowUrl) { + super(); + this.whiteArrowUrl_ = appImagesPath + 'arrow.png'; + this.arrowUrl_ = arrowUrl; + } + + /** + * @param {Array.} symbolizers Array of MapFish Print symbolizers. + * @param {!ol.style.Image} imageStyle Image style. + * @protected + * @override + */ + encodeVectorStylePoint(symbolizers, imageStyle) { + const len = symbolizers.length; + super.encodeVectorStylePoint(symbolizers, imageStyle); + const newLen = symbolizers.length; + if (newLen > len) { + const last = symbolizers[newLen - 1]; + if (last.externalGraphic === this.whiteArrowUrl_) { + const rgba = imageStyle.getColor(); + const color = rgbToHex(rgba[0], rgba[1], rgba[2]); + last.externalGraphic = `${this.arrowUrl_}?color=${color}`; + } + } + } +} const exports = class extends ngeoPrintService { /** * @param {string} url URL to MapFish print web service. * @param {angular.$http} $http Angular $http service. * @param {ngeo.map.LayerHelper} ngeoLayerHelper Ngeo Layer Helper service. + * @param {string} appImagesPath Path the the static images. + * @param {string} arrowUrl URL to the arrow. */ - constructor(url, $http, ngeoLayerHelper) { + constructor(url, $http, ngeoLayerHelper, appImagesPath, arrowUrl) { super(url, $http, ngeoLayerHelper); /** * @type {ngeo.map.LayerHelper} @@ -20,7 +60,10 @@ const exports = class extends ngeoPrintService { */ this.ngeoLayerHelper2_ = ngeoLayerHelper; + // Replace encoder with our own + this.vectorEncoder = new AppVectorEncoder(appImagesPath, arrowUrl); } + /** * @override */ @@ -36,7 +79,7 @@ const exports = class extends ngeoPrintService { const attributes = /** @type {!MapFishPrintAttributes} */ ({ map: specMap }); - olObj.assign(attributes, customAttributes); + assign(attributes, customAttributes); const spec = /** @type {MapFishPrintSpec} */ ({ attributes, @@ -58,7 +101,7 @@ const exports = class extends ngeoPrintService { const viewCenter = view.getCenter(); const viewProjection = view.getProjection(); const viewResolution = view.getResolution(); - const viewRotation = object.rotation || olMath.toDegrees(view.getRotation()); + const viewRotation = object.rotation || toDegrees(view.getRotation()); console.assert(viewCenter !== undefined); console.assert(viewProjection !== undefined); @@ -73,7 +116,7 @@ const exports = class extends ngeoPrintService { console.assert(mapLayerGroup !== undefined && mapLayerGroup !== null); let layers = this.ngeoLayerHelper2_.getFlatLayers(mapLayerGroup); - olArray.stableSort(layers, (layer_a, layer_b) => layer_a.getZIndex() - layer_b.getZIndex()); + stableSort(layers, (layer_a, layer_b) => layer_a.getZIndex() - layer_b.getZIndex()); layers = layers.slice().reverse(); layers.forEach((layer) => { diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/profile/ProfileController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/profile/ProfileController.js index 895074c41..6a61708c6 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/profile/ProfileController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/profile/ProfileController.js @@ -17,9 +17,8 @@ */ import appModule from '../module.js'; -import olEvents from 'ol/events.js'; +import {listen, unlistenByKey} from 'ol/events.js'; import olFeature from 'ol/Feature.js'; -import olMapBrowserEventType from 'ol/MapBrowserEventType.js'; import olOverlay from 'ol/Overlay.js'; import olGeomGeometryLayout from 'ol/geom/GeometryLayout.js'; import olGeomLineString from 'ol/geom/LineString.js'; @@ -27,7 +26,6 @@ import olGeomPoint from 'ol/geom/Point.js'; import olStyleCircle from 'ol/style/Circle.js'; import olStyleFill from 'ol/style/Fill.js'; import olStyleStyle from 'ol/style/Style.js'; -import olProj from 'ol/proj.js'; /** * @constructor @@ -162,7 +160,7 @@ const exports = function($scope, ngeoFeatureOverlayMgr, echocsvUrl, * @type {ol.EventsKey} * @private */ - this.event_ = olEvents.listen(this['map'], olMapBrowserEventType.POINTERMOVE, + this.event_ = listen(this['map'], 'pointermove', /** * @param {ol.MapBrowserPointerEvent} evt Map browser event. */ @@ -256,7 +254,7 @@ const exports = function($scope, ngeoFeatureOverlayMgr, echocsvUrl, }.bind(this)); this.scope_.$on('$destroy', function() { - olEvents.unlistenByKey(this.event_); + unlistenByKey(this.event_); this.unwatchProfileData(); }.bind(this)); }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/projections.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/projections.js index 7287f14dc..8c6e7e845 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/projections.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/projections.js @@ -1,21 +1,23 @@ /** * @module app.projections */ -let exports = {}; -import olProj from 'ol/proj.js'; + +import {get as getProjection} from 'ol/proj.js'; +import {register} from 'ol/proj/proj4.js'; +import proj4 from 'proj4'; proj4.defs('EPSG:32632', '+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs'); -olProj.get('EPSG:32632').setExtent([166021.44, 0.00, 833978.55, 9329005.18]); proj4.defs('EPSG:32631', '+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs'); -olProj.get('EPSG:32631').setExtent([166021.44, 0.00, 833978.55, 9329005.18]); proj4.defs('EPSG:2169', '+proj=tmerc +lat_0=49.83333333333334 +lon_0=6.166666666666667 ' + '+k=1 +x_0=80000 +y_0=100000 +ellps=intl ' + '+towgs84=-189.681,18.3463,-42.7695,-0.33746,-3.09264,2.53861,0.4598 ' + - '+units=m +no_defs"'); -olProj.get('EPSG:2169').setExtent([48225.17, 56225.60, 105842.04, 139616.40]); + '+units=m +no_defs'); +register(proj4); -export default exports; +getProjection('EPSG:32632').setExtent([166021.44, 0.00, 833978.55, 9329005.18]); +getProjection('EPSG:32631').setExtent([166021.44, 0.00, 833978.55, 9329005.18]); +getProjection('EPSG:2169').setExtent([48225.17, 56225.60, 105842.04, 139616.40]); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/query/QueryController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/query/QueryController.js index 22597db7a..eaee191a4 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/query/QueryController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/query/QueryController.js @@ -3,13 +3,14 @@ */ import appModule from '../module.js'; import appNotifyNotificationType from '../NotifyNotificationType.js'; -import olBase from 'ol.js'; -import olExtent from 'ol/extent.js'; +import {listen} from 'ol/events.js'; +import {extend as arrayExtend} from 'ol/array.js'; +import {extend as extentExtend} from 'ol/extent.js'; import olFormatGeoJSON from 'ol/format/GeoJSON.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; import olGeomMultiLineString from 'ol/geom/MultiLineString.js'; import olLayerVector from 'ol/layer/Vector.js'; -import olProj from 'ol/proj.js'; +import {transform} from 'ol/proj.js'; import olSourceVector from 'ol/source/Vector.js'; import olStyleCircle from 'ol/style/Circle.js'; import olStyleFill from 'ol/style/Fill.js'; @@ -371,8 +372,8 @@ const exports = function($sce, $timeout, $scope, $http, } }.bind(this)); - olBase.events.listen(this.map_.getLayers(), - olBase.CollectionEventType.REMOVE, + listen(this.map_.getLayers(), + 'remove', /** * @param {ol.Collection.Event} e Collection event. */ @@ -383,8 +384,8 @@ const exports = function($sce, $timeout, $scope, $http, }, this); - olBase.events.listen(this.map_, - olBase.MapBrowserEventType.POINTERDOWN, function(evt) { + listen(this.map_, + 'pointerdown', function(evt) { this.isLongPress_ = false; this.startPixel_ = evt.pixel; this.pointerDownTime_ = new Date().getTime(); @@ -392,8 +393,8 @@ const exports = function($sce, $timeout, $scope, $http, $timeout.cancel(holdPromise); }, this); - olBase.events.listen(this.map_, - olBase.MapBrowserEventType.POINTERUP, function(evt) { + listen(this.map_, + 'pointerup', function(evt) { $timeout.cancel(holdPromise); var tempTime = new Date().getTime(); if ((tempTime - this.pointerUpTime_) <= 499) { @@ -440,7 +441,7 @@ const exports = function($sce, $timeout, $scope, $http, }.bind(this), 500, false); }, this); - olBase.events.listen(this.map_, olBase.MapBrowserEventType.POINTERMOVE, + listen(this.map_, 'pointermove', function(evt) { if (evt.dragging || this.isQuerying_) { return; @@ -453,9 +454,7 @@ const exports = function($sce, $timeout, $scope, $http, if (layer !== undefined && layer !== null) { var metadata = layer.get('metadata'); if (metadata !== undefined && metadata !== null) { - if (metadata['is_queryable'] !== undefined && metadata['is_queryable'] !== null && - metadata['is_queryable'] && - layer.getVisible() && layer.getOpacity() > 0) { + if (metadata['is_queryable'] && layer.getVisible() && layer.getOpacity() > 0) { return true; } } @@ -587,7 +586,7 @@ exports.getAllChildren_ = function(element) { var array = []; for (var i = 0; i < element.length; i++) { if (element[i].hasOwnProperty('children')) { - olBase.array.extend(array, exports.getAllChildren_( + arrayExtend(array, exports.getAllChildren_( element[i].children) ); } else { @@ -675,8 +674,7 @@ exports.prototype.singleclickEvent_ = function(evt, infoMymaps) { for (var i = layers.length - 1; i >= 0; i--) { var metadata = layers[i].get('metadata'); if (metadata !== undefined && metadata !== null) { - if (metadata['is_queryable'] == 'true' && - layers[i].getVisible() && layers[i].getOpacity() > 0) { + if (metadata['is_queryable'] && layers[i].getVisible() && layers[i].getOpacity() > 0) { var queryableId = layers[i].get('queryable_id'); layersList.push(queryableId); layerLabel[queryableId] = layers[i].get('label'); @@ -688,7 +686,7 @@ exports.prototype.singleclickEvent_ = function(evt, infoMymaps) { var bigBuffer = 20 * resolution; var smallBuffer = 1 * resolution; - var point = olProj.transform(evt.coordinate, + var point = transform(evt.coordinate, this.map_.getView().getProjection(), 'EPSG:2169'); var big_box = [ [point[0] - bigBuffer, point[1] + bigBuffer], @@ -839,9 +837,8 @@ exports.prototype.showInfo_ = function(shiftKey, resp, layerLabel, } this.lastHighlightedFeatures_ = []; for (var i = 0; i < this.responses_.length; i++) { - this.lastHighlightedFeatures_.push.apply( - this.lastHighlightedFeatures_, - this.responses_[i].features + this.lastHighlightedFeatures_.push( + ...this.responses_[i].features ); } this.highlightFeatures_(this.lastHighlightedFeatures_, fit); @@ -1076,7 +1073,7 @@ exports.prototype.highlightFeatures_ = function(features, fit) { if (jsonFeatures.length > 0) { var extent = jsonFeatures[0].getGeometry().getExtent(); for (var i = 0; i < jsonFeatures.length; ++i) { - extent = olExtent.extend(extent, + extent = extentExtend(extent, jsonFeatures[i].getGeometry().getExtent()); var curFeature = jsonFeatures[i]; if (curFeature.getGeometry().getType() == @@ -1185,15 +1182,12 @@ exports.prototype.getQrCodeForMymapsUrl = function(mapId) { /** * Check if the value is empty. - * @param {*} value The value to test. + * @param {?string | undefined} value The value to test. * @return {boolean} True if is empty. * @export */ exports.prototype.isEmpty = function(value) { - if (value === undefined || value === null) { - return true; - } - return String(value).length === 0; + return !value; }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/routing/RoutingController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/routing/RoutingController.js index 349a71cf4..1f07e0a3c 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/routing/RoutingController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/routing/RoutingController.js @@ -15,13 +15,23 @@ import appModule from '../module.js'; import appNotifyNotificationType from '../NotifyNotificationType.js'; import ngeoSearchCreateGeoJSONBloodhound from 'ngeo/search/createGeoJSONBloodhound.js'; -import olBase from 'ol.js'; +import {get as projGet, transform, transformExtent} from 'ol/proj.js'; import olGeomPoint from 'ol/geom/Point.js'; import olGeomGeometryType from 'ol/geom/GeometryType.js'; -import olStyle from 'ol/style.js'; -import olInteraction from 'ol/interaction.js'; -import olEvents from 'ol/events.js'; +import Style from 'ol/style/Style.js'; +import Circle from 'ol/style/Circle.js'; +import Fill from 'ol/style/Fill.js'; +import Select from 'ol/interaction/Select.js'; +import Modify from 'ol/interaction/Modify.js'; +import {listen} from 'ol/events.js'; +import {getCenter, containsCoordinate} from 'ol/extent'; import olFormatGeoJSON from 'ol/format/GeoJSON.js'; +import {includes as arrayIncludes} from 'ol/array.js'; +import Collection from 'ol/Collection.js'; +import Feature from 'ol/Feature.js'; +import Geolocation from 'ol/Geolocation.js'; +import Overlay from 'ol/Overlay.js'; +import {click, pointerMove} from 'ol/events/condition.js'; /** * @param {angular.Scope} $scope Angular root scope. @@ -96,7 +106,7 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, * @private */ this.maxExtent_ = - olBase.proj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); + transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); /** * @type {app.CoordinateString} @@ -249,7 +259,7 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, select: function(event, suggestion) { var feature = /** @type {ol.Feature} */ (suggestion); var geometry = feature.getGeometry(); - feature.setGeometry(new olGeomPoint(olBase.extent.getCenter( + feature.setGeometry(new olGeomPoint(getCenter( geometry.getExtent()))); var routeNumber = parseInt($(event.currentTarget).attr('route-number'), 10); this.appRouting.insertFeatureAt(feature, routeNumber); @@ -268,10 +278,10 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, this.highlightOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay(); this.highlightOverlay_.setStyle( - new olStyle.Style({ - image: new olStyle.Circle({ + new Style({ + image: new Circle({ radius: 6, - fill: new olStyle.Fill({color: '#ff0000'}) + fill: new Fill({color: '#ff0000'}) }) })); /** @@ -293,7 +303,7 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, * @type {ol.Collection} * @private */ - this.modyfyFeaturesCollection_ = new olBase.Collection(); + this.modyfyFeaturesCollection_ = new Collection(); /** * Due to https://github.com/openlayers/openlayers/issues/7483 @@ -301,9 +311,9 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, * @type {ol.interaction.Select} * @private */ - this.selectInteraction_ = new olInteraction.Select({ + this.selectInteraction_ = new Select({ features: this.modyfyFeaturesCollection_, - condition: olEvents.condition.click, + condition: click, filter: function(feature, layer) { return this.appRouting.stepFeatures.getArray().indexOf(feature) != -1; }.bind(this) @@ -316,8 +326,8 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, * @type {ol.interaction.Select} * @private */ - this.selectInteractionPM_ = new olInteraction.Select({ - condition: olEvents.condition.pointerMove, + this.selectInteractionPM_ = new Select({ + condition: pointerMove, filter: function(feature, layer) { return this.appRouting.stepFeatures.getArray().indexOf(feature) != -1; }.bind(this) @@ -326,37 +336,37 @@ const exports = function($scope, gettextCatalog, poiSearchServiceUrl, this.map.addInteraction(this.selectInteractionPM_); this.selectInteractionPM_.setActive(false); - olEvents.listen(this.selectInteractionPM_, 'select', + listen(this.selectInteractionPM_, 'select', this.showHideTooltip_, this); /** * @type {ol.interaction.Modify} * @private */ - this.modifyInteraction_ = new olInteraction.Modify({ + this.modifyInteraction_ = new Modify({ features: this.modyfyFeaturesCollection_ }); this.map.addInteraction(this.modifyInteraction_); this.modifyInteraction_.setActive(true); - olEvents.listen(this.modifyInteraction_, - olInteraction.ModifyEventType.MODIFYEND, this.modifyEndStepFeature_, this); + listen(this.modifyInteraction_, + 'modifyend', this.modifyEndStepFeature_, this); /** * @type {ol.source.Vector} * @private */ this.source_ = ngeoFeatureOverlayMgr.getLayer().getSource(); - olEvents.listen(this.appRouting.routeFeatures, olBase.CollectionEventType.ADD, + listen(this.appRouting.routeFeatures, 'add', this.showRoute_, this); - olEvents.listen(this.appRouting.routeFeatures, olBase.CollectionEventType.REMOVE, + listen(this.appRouting.routeFeatures, 'remove', this.removeRoute_, this); /** * @type {ol.Geolocation} * @private */ - this.geolocation_ = new olBase.Geolocation({ + this.geolocation_ = new Geolocation({ projection: this.map.getView().getProjection(), trackingOptions: /** @type {GeolocationPositionOptions} */ ({ enableHighAccuracy: true, @@ -421,8 +431,7 @@ exports.prototype.whereAmI = function(step) { if (this.window_.location.protocol !== 'https:') { this['showRedirect'] = true; } else { - olEvents.listen(this.geolocation_, - olBase.Object.getChangeEventType(olBase.GeolocationProperty.POSITION), + listen(this.geolocation_, 'change:position', /** * @param {ol.Object.Event} e Object event. */ @@ -430,7 +439,7 @@ exports.prototype.whereAmI = function(step) { this.geolocation_.setTracking(false); var position = /** @type {ol.Coordinate} */ (this.geolocation_.getPosition()); - var feature = new olBase.Feature({ + var feature = new Feature({ geometry: new olGeomPoint(position) }); var label = this.coordinateString_( @@ -456,7 +465,7 @@ exports.prototype.showHideTooltip_ = function(e) { var feature = selectedFeatures.getArray()[0]; var geometry = /** @type {ol.Coordinate} */ (feature.getGeometry().getFirstCoordinate()); - var newFeature = new olBase.Feature({ + var newFeature = new Feature({ geometry: new olGeomPoint(geometry) }); this.highlightOverlay_.addFeature(newFeature); @@ -477,7 +486,7 @@ exports.prototype.createTooltip_ = function(position, text) { this.tooltipElement_ = document.createElement('div'); this.tooltipElement_.classList.add('tooltip'); this.tooltipElement_.innerHTML = text; - this.tooltipOverlay_ = new olBase.Overlay({ + this.tooltipOverlay_ = new Overlay({ element: this.tooltipElement_, offset: [15, 0], positioning: 'center-left' @@ -571,7 +580,7 @@ exports.prototype.createAndInitPOIBloodhound_ = (parsedResponse); return geojsonFormat.readFeatures(featureCollection, { - featureProjection: olBase.proj.get('EPSG:3857'), + featureProjection: projGet('EPSG:3857'), dataProjection: undefined }); } @@ -621,7 +630,7 @@ exports.prototype.clearRoute = function(routeIdx) { this.appRouting.reorderRoute(); } else { this.appRouting.routes[routeIdx] = ''; - var blankFeature = new olBase.Feature(); + var blankFeature = new Feature(); blankFeature.set('name', '' + (routeIdx + 1)); this.appRouting.features.setAt(routeIdx, blankFeature); } @@ -708,8 +717,8 @@ exports.prototype.showRoute_ = function() { this.routeDesc.forEach(function(description) { var coordinate = [description.lon, description.lat]; var geometry = /** @type {ol.Coordinate} */ - (olBase.proj.transform(coordinate, 'EPSG:4326', curView.getProjection())); - var stepFeature = new olBase.Feature({ + (transform(coordinate, 'EPSG:4326', curView.getProjection())); + var stepFeature = new Feature({ geometry: new olGeomPoint(geometry) }); cumulativeDistance += description.distance; @@ -734,7 +743,7 @@ exports.prototype.showRoute_ = function() { */ exports.prototype.center = function(lon, lat) { var curView = this.map.getView(); - var coordinate = olBase.proj.transform([lon, lat], 'EPSG:4326', curView.getProjection()); + var coordinate = transform([lon, lat], 'EPSG:4326', curView.getProjection()); curView.setCenter(coordinate); }; @@ -748,8 +757,8 @@ exports.prototype.highlightPosition = function(lon, lat, text) { var coordinate = [lon, lat]; var curView = this.map.getView(); var geometry = /** @type {ol.Coordinate} */ - (olBase.proj.transform(coordinate, 'EPSG:4326', curView.getProjection())); - var feature = new olBase.Feature({ + (transform(coordinate, 'EPSG:4326', curView.getProjection())); + var feature = new Feature({ geometry: new olGeomPoint(geometry) }); this.highlightOverlay_.clear(); @@ -950,12 +959,12 @@ exports.prototype.matchCoordinate_ = var northing = undefined; if (epsgKey === 'EPSG:4326' || epsgKey === 'EPSG:2169') { if ((m[2] !== undefined && m[2] !== null) && (m[4] !== undefined && m[4] !== null)) { - if (olBase.array.includes(northArray, m[2].toUpperCase()) && - olBase.array.includes(eastArray, m[4].toUpperCase())) { + if (arrayIncludes(northArray, m[2].toUpperCase()) && + arrayIncludes(eastArray, m[4].toUpperCase())) { easting = parseFloat(m[3].replace(',', '.')); northing = parseFloat(m[1].replace(',', '.')); - } else if (olBase.array.includes(northArray, m[4].toUpperCase()) && - olBase.array.includes(eastArray, m[2].toUpperCase())) { + } else if (arrayIncludes(northArray, m[4].toUpperCase()) && + arrayIncludes(eastArray, m[2].toUpperCase())) { easting = parseFloat(m[1].replace(',', '.')); northing = parseFloat(m[3].replace(',', '.')); } @@ -1006,12 +1015,12 @@ exports.prototype.matchCoordinate_ = (new olGeomPoint([northing, easting]) .transform(epsgCode, mapEpsgCode)); var feature = /** @type {ol.Feature} */ (null); - if (olBase.extent.containsCoordinate( + if (containsCoordinate( this.maxExtent_, point.getCoordinates())) { - feature = new olBase.Feature(point); - } else if (epsgCode === 'EPSG:4326' && olBase.extent.containsCoordinate( + feature = new Feature(point); + } else if (epsgCode === 'EPSG:4326' && containsCoordinate( this.maxExtent_, flippedPoint.getCoordinates())) { - feature = new olBase.Feature(flippedPoint); + feature = new Feature(flippedPoint); } if (feature !== null) { var resultPoint = diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/search/SearchController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/search/SearchController.js index f7447c27e..5956389fe 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/search/SearchController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/search/SearchController.js @@ -17,11 +17,11 @@ import appModule from '../module.js'; import appEventsThemesEventType from '../events/ThemesEventType.js'; import ngeoSearchCreateGeoJSONBloodhound from 'ngeo/search/createGeoJSONBloodhound.js'; -import olArray from 'ol/array.js'; +import {includes as arrayIncludes, extend as arrayExtend} from 'ol/array.js'; import olCollectionEventType from 'ol/CollectionEventType.js'; -import olEvents from 'ol/events.js'; -import olExtent from 'ol/extent.js'; -import olProj from 'ol/proj.js'; +import {listen} from 'ol/events.js'; +import {getCenter, containsCoordinate} from 'ol/extent.js'; +import {transformExtent, get} from 'ol/proj.js'; import olFeature from 'ol/Feature.js'; import olFormatGeoJSON from 'ol/format/GeoJSON.js'; import olGeomPoint from 'ol/geom/Point.js'; @@ -29,6 +29,7 @@ import olStyleCircle from 'ol/style/Circle.js'; import olStyleFill from 'ol/style/Fill.js'; import olStyleStyle from 'ol/style/Style.js'; import olStyleStroke from 'ol/style/Stroke.js'; +import Fuse from 'fuse.js'; /** * @ngInject @@ -147,7 +148,7 @@ const exports = function($scope, $window, $compile, * @private */ this.maxExtent_ = - olProj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); + transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857'); /** * @type {Array.} @@ -259,7 +260,7 @@ const exports = function($scope, $window, $compile, appThemes, backgroundLayerEngine, this.gettextCatalog); }.bind(this)); - olEvents.listen(appThemes, appEventsThemesEventType.LOAD, + listen(appThemes, appEventsThemesEventType.LOAD, /** * @param {ol.events.Event} evt Event */ @@ -323,29 +324,34 @@ const exports = function($scope, $window, $compile, * @return {string} The result. * @this {TypeaheadDataset} */ - display: function(suggestion) { - suggestion['dataset'] = this.name; - return suggestion['translatedName']; + display(suggestion) { + if (suggestion) { + suggestion['dataset'] = this.name; + return suggestion['translatedName']; + } }, templates: /** @type {TypeaheadTemplates} */({ - header: function() { + header() { return '
      ' + this.gettextCatalog.getString('Background Layers') + '
      '; - }.bind(this), + }, suggestion: /** * @param {app.search.BackgroundLayerSuggestion} suggestion The suggestion. * @return {*} The result. */ - (function(suggestion) { - var scope = $scope.$new(true); - scope['object'] = suggestion; - var html = '

      ' + suggestion['translatedName']; - html += ' (' + this.gettextCatalog.getString('Background') + ') '; - html += '

      '; - return $compile(html)(scope); - }).bind(this) + (suggestion => { + if (suggestion) { + var scope = $scope.$new(true); + scope['object'] = suggestion; + var html = '

      ' + suggestion['translatedName']; + html += ' (' + this.gettextCatalog.getString('Background') + ') '; + html += '

      '; + return $compile(html)(scope); + } + + }) }) }, { name: 'pois', @@ -394,9 +400,11 @@ const exports = function($scope, $window, $compile, * @return {(string|*)} The result. * @this {TypeaheadDataset} */ - display: function(suggestion) { - suggestion['dataset'] = this.name; - return gettextCatalog.getString(suggestion.name); + display(suggestion) { + if (suggestion) { + suggestion['dataset'] = this.name; + return gettextCatalog.getString(suggestion.name); + } }, templates: /** @type {TypeaheadTemplates} */({ header: function() { @@ -455,9 +463,11 @@ const exports = function($scope, $window, $compile, * @return {(string|*)} The result. * @this {TypeaheadDataset} */ - display: function(suggestion) { - suggestion['dataset'] = this.name; - return gettextCatalog.getString(suggestion.name); + display(suggestion) { + if (suggestion) { + suggestion['dataset'] = this.name; + return gettextCatalog.getString(suggestion.name); + } }, templates: /** @type {TypeaheadTemplates} */({ header: function() { @@ -481,7 +491,7 @@ const exports = function($scope, $window, $compile, select: exports.selected_.bind(this) }); - olEvents.listen(this['map'].getLayers(), + listen(this['map'].getLayers(), olCollectionEventType.ADD, /** * @param {ol.Collection.Event} e Collection event. @@ -562,12 +572,12 @@ exports.prototype.matchCoordinate_ = var northing = undefined; if (epsgKey === 'EPSG:4326' || epsgKey === 'EPSG:2169') { if ((m[2] !== undefined && m[2] !== null) && (m[4] !== undefined && m[4] !== null)) { - if (olArray.includes(northArray, m[2].toUpperCase()) && - olArray.includes(eastArray, m[4].toUpperCase())) { + if (arrayIncludes(northArray, m[2].toUpperCase()) && + arrayIncludes(eastArray, m[4].toUpperCase())) { easting = parseFloat(m[3].replace(',', '.')); northing = parseFloat(m[1].replace(',', '.')); - } else if (olArray.includes(northArray, m[4].toUpperCase()) && - olArray.includes(eastArray, m[2].toUpperCase())) { + } else if (arrayIncludes(northArray, m[4].toUpperCase()) && + arrayIncludes(eastArray, m[2].toUpperCase())) { easting = parseFloat(m[1].replace(',', '.')); northing = parseFloat(m[3].replace(',', '.')); } @@ -618,10 +628,10 @@ exports.prototype.matchCoordinate_ = (new olGeomPoint([northing, easting]) .transform(epsgCode, mapEpsgCode)); var feature = /** @type {ol.Feature} */ (null); - if (olExtent.containsCoordinate( + if (containsCoordinate( this.maxExtent_, point.getCoordinates())) { feature = new olFeature(point); - } else if (epsgCode === 'EPSG:4326' && olExtent.containsCoordinate( + } else if (epsgCode === 'EPSG:4326' && containsCoordinate( this.maxExtent_, flippedPoint.getCoordinates())) { feature = new olFeature(flippedPoint); } @@ -709,7 +719,7 @@ exports.prototype.createAndInitPOIBloodhound_ = (parsedResponse); return geojsonFormat.readFeatures(featureCollection, { - featureProjection: olProj.get('EPSG:3857'), + featureProjection: get('EPSG:3857'), dataProjection: undefined }); } @@ -750,7 +760,7 @@ exports.prototype.createAndInitLayerBloodhoundEngine_ = result['themes'].push(element.theme); }.bind(this)); - result['showThemeLink'] = !olArray.includes( + result['showThemeLink'] = !arrayIncludes( result['themes'], this.appTheme_.getCurrentTheme()); }.bind(this)); @@ -830,7 +840,7 @@ exports.prototype.createLocalAllLayerData_ = this.appThemes_.getFlatCatalog().then( function(flatCatalogue) { this.layers_ = []; - olArray.extend(this.layers_, flatCatalogue); + arrayExtend(this.layers_, flatCatalogue); }.bind(this)); }; @@ -903,10 +913,10 @@ exports.selected_ = if (dataset === 'coordinates') { features.push(feature); } else if (dataset === 'pois') { - if (!(olArray.includes(this.appExcludeThemeLayerSearch_, + if (!(arrayIncludes(this.appExcludeThemeLayerSearch_, this.appTheme_.getCurrentTheme()) && feature.get('layer_name') === 'Parcelle')) { - if (olArray.includes(this.showGeom_, feature.get('layer_name'))) { + if (arrayIncludes(this.showGeom_, feature.get('layer_name'))) { features.push(feature); } var layers = /** @type {Array} */ @@ -916,7 +926,7 @@ exports.selected_ = }.bind(this)); } else { feature.setGeometry( - new olGeomPoint(olExtent.getCenter( + new olGeomPoint(getCenter( featureGeometry.getExtent()))); features.push(feature); } @@ -941,7 +951,7 @@ exports.selected_ = * @export */ exports.prototype.addRoutePoint = function(suggestion) { - var coordinate = olExtent.getCenter(suggestion.getGeometry().getExtent()); + var coordinate = getCenter(suggestion.getGeometry().getExtent()); var feature = /** @type {ol.Feature} */ (new olFeature(new olGeomPoint(coordinate))); feature.set('label', suggestion.get('label')); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/share/ShareController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/share/ShareController.js index 160e4b722..1ff26a018 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/share/ShareController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/share/ShareController.js @@ -31,7 +31,6 @@ const exports = function($window, gettext, gettextCatalog) { this.services_ = { 'facebook': {url: 'https://www.facebook.com/dialog/feed'}, 'twitter': {url: 'https://www.twitter.com/intent/tweet'}, - 'googlePlus': {url: 'https://plus.google.com/share'} }; /** diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/share/share.html b/geoportal/geoportailv3_geoportal/static-ngeo/js/share/share.html index 3994861c0..532887bc5 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/share/share.html +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/share/share.html @@ -7,9 +7,6 @@ Twitter
    • - Google Plus -
    • -
    • Email
    diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/SliderController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/SliderController.js index 2759b20ef..d1995575d 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/SliderController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/SliderController.js @@ -2,7 +2,8 @@ * @module app.slider.SliderController */ import appModule from '../module.js'; -import olBase from 'ol.js'; +import {listen, listenOnce} from 'ol/events.js'; +import {unByKey} from 'ol/Observable.js'; /** * @param {angular.JQLite} $element Element. @@ -113,18 +114,18 @@ exports.prototype.activate = function(active) { } this.moveLine_(); - this.mapResizeEvent_ = olBase.events.listen(this.map_, 'change:size', this.moveLine_, this); - this.mousedownEvent_ = olBase.events.listen(this.element_[0], 'mousedown', + this.mapResizeEvent_ = listen(this.map_, 'change:size', this.moveLine_, this); + this.mousedownEvent_ = listen(this.element_[0], 'mousedown', function(event) { this.isDragging_ = true; if (this.mousemoveEvent_ === null) { - this.mousemoveEvent_ = olBase.events.listen(this.map_, - olBase.MapBrowserEventType.POINTERMOVE, this.drag_, this); + this.mousemoveEvent_ = listen(this.map_, + 'pointermove', this.drag_, this); } - olBase.events.listenOnce(this.$document_[0], + listenOnce(this.$document_[0], 'mouseup', function() { if (this.mousemoveEvent_) { - olBase.Observable.unByKey(this.mousemoveEvent_); + unByKey(this.mousemoveEvent_); } this.isDragging_ = false; this.mousemoveEvent_ = null; @@ -133,7 +134,7 @@ exports.prototype.activate = function(active) { var layer = this['layers'][0]; if (layer !== undefined) { - this.precomposeEvent_ = olBase.events.listen(layer, 'precompose', function(event) { + this.precomposeEvent_ = listen(layer, 'precompose', function(event) { if (this['layers'][0] === layer) { var ratio = this.ngeoLocation_.getParam('sliderRatio'); var ctx = event.context; @@ -147,7 +148,7 @@ exports.prototype.activate = function(active) { } }, this); - this.postcomposeEvent_ = olBase.events.listen(layer, 'postcompose', function(event) { + this.postcomposeEvent_ = listen(layer, 'postcompose', function(event) { if (this['layers'][0] === layer) { var ctx = event.context; ctx.restore(); @@ -158,16 +159,16 @@ exports.prototype.activate = function(active) { } } else { if (this.mousedownEvent_) { - olBase.Observable.unByKey(this.mousedownEvent_); + unByKey(this.mousedownEvent_); } if (this.mapResizeEvent_) { - olBase.Observable.unByKey(this.mapResizeEvent_); + unByKey(this.mapResizeEvent_); } if (this.precomposeEvent_ !== null) { - olBase.Observable.unByKey(this.precomposeEvent_); + unByKey(this.precomposeEvent_); } if (this.postcomposeEvent_ !== null) { - olBase.Observable.unByKey(this.postcomposeEvent_); + unByKey(this.postcomposeEvent_); } } this.map_.render(); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/slider.html b/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/slider.html new file mode 100644 index 000000000..6da18c1c3 --- /dev/null +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/slider/slider.html @@ -0,0 +1,3 @@ +
    +FIXME: slider.html is missing +
    diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/streetview/StreetviewController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/streetview/StreetviewController.js index 6a96c492e..88fc8db38 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/streetview/StreetviewController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/streetview/StreetviewController.js @@ -13,10 +13,18 @@ */ import appModule from '../module.js'; -import olBase from 'ol.js'; +import {fromLonLat, toLonLat} from 'ol/proj.js'; import olGeomPoint from 'ol/geom/Point.js'; -import olInteraction from 'ol/interaction.js'; -import olStyle from 'ol/style.js'; +import Select from 'ol/interaction/Select.js'; +import Style from 'ol/style/Style.js'; +import Icon from 'ol/style/Icon.js'; +import {containsCoordinate} from 'ol/extent.js'; +import {listen} from 'ol/events.js'; +import {equals as arrayEquals} from 'ol/array.js'; +import Collection from 'ol/Collection.js'; +import Feature from 'ol/Feature.js'; +import {getUid} from 'ol/index.js'; + /** * @ngInject @@ -51,7 +59,7 @@ const exports = function($element, $scope, ngeoFeatureOverlayMgr, */ this.locationInfoOverlay_ = appLocationInfoOverlay; - this['uid'] = olBase.getUid(this); + this['uid'] = getUid(this); /** * @type {string} @@ -101,7 +109,7 @@ const exports = function($element, $scope, ngeoFeatureOverlayMgr, * @type {!ol.Feature} * @private */ - this.feature_ = new olBase.Feature(); + this.feature_ = new Feature(); /** * @type {ngeo.map.FeatureOverlay} @@ -113,7 +121,7 @@ const exports = function($element, $scope, ngeoFeatureOverlayMgr, * @type {ol.Collection} * @private */ - this.features_ = new olBase.Collection(); + this.features_ = new Collection(); this.featureOverlay_.setFeatures(this.features_); /** @@ -196,7 +204,7 @@ const exports = function($element, $scope, ngeoFeatureOverlayMgr, * @type {ol.interaction.Select} * @private */ - this.selectSingleClick_ = new olInteraction.Select({ + this.selectSingleClick_ = new Select({ filter: function(feature, layer) { return this.features_.getArray().indexOf(feature) != -1; }.bind(this) @@ -300,7 +308,7 @@ exports.prototype.$onInit = function() { } } }.bind(this)); - olBase.events.listen(this.map_, olBase.MapBrowserEventType.POINTERMOVE, function(evt) { + listen(this.map_, 'pointermove', function(evt) { if (this.isActive()) { var pixel = this.map_.getEventPixel(evt.originalEvent); @@ -327,7 +335,7 @@ exports.prototype.handleLocationChange_ = function(location, oldLocation) { // (1) No need to do anything if the old value equals the new value if (this.isInitialised_ && (location === oldLocation || ( Array.isArray(location) && Array.isArray(oldLocation) && - olBase.array.equals(location, oldLocation) + arrayEquals(location, oldLocation) ))) { return; } @@ -388,15 +396,15 @@ exports.prototype.handleReadyChange_ = function(ready, oldReady) { exports.prototype.createStyleFunction = function() { var arrowPath = this.arrowPath_; var imagePath = this.appImagesPath_; - return function(resolution) { - if (this.get('isDirection')) { - var curZoom = this.get('zoom'); + return function(feature, resolution) { + if (feature.get('isDirection')) { + var curZoom = feature.get('zoom'); if (curZoom < 1) { curZoom = 1; } else if (curZoom > 4) { curZoom = 4; } - var curPitch = Math.abs(this.get('pitch')); + var curPitch = Math.abs(feature.get('pitch')); var pitch = 0; if (curPitch >= 0 && curPitch <= 23) { pitch = 0; @@ -408,20 +416,20 @@ exports.prototype.createStyleFunction = function() { pitch = 3; } var directionArrowPath = imagePath + '/direction_sv_zl' + curZoom + '_p' + pitch + '.png'; - return [new olStyle.Style({ - image: new olStyle.Icon(/** @type {olx.style.IconOptions} */({ + return [new Style({ + image: new Icon(/** @type {olx.style.IconOptions} */({ src: directionArrowPath, - rotation: this.get('heading') * Math.PI / 180 + rotation: feature.get('heading') * Math.PI / 180 })) })]; } - return [new olStyle.Style({ - image: new olStyle.Icon(/** @type {olx.style.IconOptions} */({ + return [new Style({ + image: new Icon(/** @type {olx.style.IconOptions} */({ anchor: [0.5, 50], anchorXUnits: 'fraction', anchorYUnits: 'pixels', src: arrowPath, - rotation: this.get('heading') * Math.PI / 180 + rotation: feature.get('heading') * Math.PI / 180 })) })]; }; @@ -466,7 +474,7 @@ exports.prototype.style_ = function() { this.locationInfoOverlay_.clear(); if (navigationLinks !== undefined) { navigationLinks.forEach(function(link) { - var curFeature = new olBase.Feature(); + var curFeature = new Feature(); curFeature.setGeometry(this.point_); curFeature.set('heading', link.heading); curFeature.set('pano', link.pano); @@ -490,7 +498,7 @@ exports.prototype.handlePanoramaPositionChange_ = function() { this.point_.setCoordinates(this.location); this.scope_.$apply(); - if (!olBase.extent.containsCoordinate(this.map_.getView().calculateExtent(this.map_.getSize()), this.location)) { + if (!containsCoordinate(this.map_.getView().calculateExtent(this.map_.getSize()), this.location)) { this.map_.getView().setCenter(this.location); } this.panoramaPositionChanging_ = false; @@ -502,7 +510,7 @@ exports.prototype.handlePanoramaPositionChange_ = function() { * @return {ol.Coordinate} Map view projection coordinate. */ exports.prototype.fromLonLat_ = function(lonLat) { - return olBase.proj.fromLonLat( + return fromLonLat( lonLat, this.map_.getView().getProjection() ); @@ -513,7 +521,7 @@ exports.prototype.fromLonLat_ = function(lonLat) { * @return {ol.Coordinate} LonLat coordinate. */ exports.prototype.toLonLat_ = function(coordinate) { - return olBase.proj.toLonLat( + return toLonLat( coordinate, this.map_.getView().getProjection() ); diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/js/themeswitcher/ThemeswitcherController.js b/geoportal/geoportailv3_geoportal/static-ngeo/js/themeswitcher/ThemeswitcherController.js index 1af56157a..3b0c5cb56 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/js/themeswitcher/ThemeswitcherController.js +++ b/geoportal/geoportailv3_geoportal/static-ngeo/js/themeswitcher/ThemeswitcherController.js @@ -10,7 +10,7 @@ import appModule from '../module.js'; import appNotifyNotificationType from '../NotifyNotificationType.js'; import appEventsThemesEventType from '../events/ThemesEventType.js'; -import olEvents from 'ol/events.js'; +import {listen} from 'ol/events.js'; /** * @constructor @@ -57,7 +57,7 @@ const exports = function(gettextCatalog, ngeoLocation, */ this.appNotify_ = appNotify; - olEvents.listen(appThemes, appEventsThemesEventType.LOAD, + listen(appThemes, appEventsThemesEventType.LOAD, /** * @param {ol.events.Event} evt Event. */ @@ -101,43 +101,39 @@ exports.prototype.encodeThemeName = function(theme) { * @private */ exports.prototype.setThemes_ = function() { - this.appThemes_.getThemesObject().then( - /** - * Keep only the themes dedicated to the theme switcher - * @param {Array.} themes Array of theme objects. - */ - (function(themes) { - this['themes'] = themes.filter(function(object) { - return 'true' == object['metadata']['display_in_switcher']; - }); - // Check whether the current theme is valid or is protected; - // and if it's not, use the default theme. - // A theme is valid if it is present in the list of themes. - // A theme is protected if the related WS returns true - var curTheme = themes.find(function(theme) { - return theme['name'] == this.appTheme_.getCurrentTheme(); - }, this); - if (curTheme !== undefined) { - var themeIndex = themes.indexOf(curTheme); - if (themeIndex < 0) { - this.appThemes_.isThemePrivate(this.appTheme_.getCurrentTheme()) - .then( - /** - * @param {angular.$http.Response} resp Ajax response. - */ - (function(resp) { - if (resp.data['is_private'] === true) { - this.appNotify_(this.translate_. - getString(this.privateThemeMsg_, {}), - appNotifyNotificationType.WARNING); - this['userOpen'] = true; - } else { - this.switchTheme(this.appTheme_.getDefaultTheme()); - } - }).bind(this)); - } - } - }).bind(this)); + this.appThemes_.getThemesPromise().then((root) => { + const themes = root.themes; + this['themes'] = themes.filter(function(object) { + return object['metadata']['display_in_switcher'] === true; + }); + // Check whether the current theme is valid or is protected; + // and if it's not, use the default theme. + // A theme is valid if it is present in the list of themes. + // A theme is protected if the related WS returns true + var curTheme = themes.find(function(theme) { + return theme['name'] == this.appTheme_.getCurrentTheme(); + }, this); + if (curTheme !== undefined) { + var themeIndex = themes.indexOf(curTheme); + if (themeIndex < 0) { + this.appThemes_.isThemePrivate(this.appTheme_.getCurrentTheme()) + .then( + /** + * @param {angular.$http.Response} resp Ajax response. + */ + (function(resp) { + if (resp.data['is_private'] === true) { + this.appNotify_(this.translate_. + getString(this.privateThemeMsg_, {}), + appNotifyNotificationType.WARNING); + this['userOpen'] = true; + } else { + this.switchTheme(this.appTheme_.getDefaultTheme()); + } + }).bind(this)); + } + } + }); }; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.api.less b/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.api.less index b131c5781..cf2188593 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.api.less +++ b/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.api.less @@ -37,6 +37,9 @@ .ol-attribution li { display: block; } + .ol-collapsed { + display: none + } .ol-attribution.ol-uncollapsible { height: auto; } diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.less b/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.less index 7f2f995c1..526fe348a 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.less +++ b/geoportal/geoportailv3_geoportal/static-ngeo/less/geoportailv3.less @@ -30,8 +30,6 @@ url('../webfonts/28867F_0_0.ttf') format('truetype'); } -@fa-font-path: "fonts" ; - body { font-family: 'DINNextLTPro-Condensed', Arial, sans-serif; } diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/less/layout.less b/geoportal/geoportailv3_geoportal/static-ngeo/less/layout.less index 1c2b04115..c5775e44f 100644 --- a/geoportal/geoportailv3_geoportal/static-ngeo/less/layout.less +++ b/geoportal/geoportailv3_geoportal/static-ngeo/less/layout.less @@ -76,6 +76,10 @@ app-map > div { } } +.ol-collapsed { + display: none +} + .close-panel { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background: none; diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.eot b/geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.eot new file mode 100644 index 0000000000000000000000000000000000000000..e89927713b768df02d7139a9f9dac61b00f45da9 GIT binary patch literal 1600 zcmaJ>UuaWT82`R|?w=&JX}h*b@y~Xf?lyMVIFmGSV`_23Ri;cjDVqIk7!39{6nq$>P=v__dm4jHUlcZBL6AMn2VqV2JNI5^Qo=qs_xt^R z=ljk%_nz;5<2uoo8WEF1t;V#Ber(hA21eppQw=tM9(IJK6Pu_6n4n7$LJ96U%<_hUCgf?32uP@jrBh*JBwAE6Q-S& z^CSfED&Y$&YsybhE_$9HQHp~yuE`k3Znbfu8j1DBI*khqOg{VgGR~9_cQ?7?cFcJm zTe@7Oz3?Fl;BpmcW{nyfjRrL2`j{KPM^)rCugk=U>T1$Z9NE|0kmqs#uXWIlMoruo zmvD1^WYP$Y(S9n^8TyDmqtEdoefm&rcr2YsB_l>Un@L6^{X_9~V%tc|2s83`GrK;X z;Q!!oI?MYR%f7@MAI==$Oj7P41N&2BS)(V_6OX!CLx4tBKKNE_U?3*PHOo3-S&t74 zdVKJzWqmMgJytGm3gAD|tO-Tsc>S*49aMvwFvLQ=W^@OF-FjyyXFRmPfe}?`x0zYf zm4Cj2cP_u_^nMc>2n$^}sSD1uQginn9K5qD8i_=Ay)J1q7W>hoyyhJ(_WfuCHhS>3 zP+5uB?-{zH;1CP-KXt>}(*Jli`F3UU1bpH5w< zA5=!C-TUQK>fyGDE7M(XJfRMhIqbI&hx(p-{}%Btp@uv|4Y)N)Uc9*9R4HDB=FNCS zrh((1f`w2GFVbIbhDKkYI;1^Y*(LrXOyBzJG8xdk%2R+(`d9#Ge5?X5`B=lM{XW*A zzvJT&ZKd z + + +Generated by IcoMoon + + + + + + + \ No newline at end of file diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.ttf b/geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.ttf new file mode 100644 index 0000000000000000000000000000000000000000..7ca041c9603bbbf9c6c7e630142af52c2fb05ede GIT binary patch literal 1436 zcmaJ>Uuaup6#t$3-9JgX{6xpn^ddKInsB6My&5wm5<(eBb%~&N<&X z=icw!KmhdMZ74i-{N+8F{)dbwX}QdGvRH9yiMb!%17s)pD`jW3Mm<38=}38b7^{9HPgb2uY4d1woBU7af4AnYHrOY{IOF-D6yyR7K-<*5r{#R0<#%Ky>cw@4 zu4+ z<+GW%l`G^kiTKEPx|^|Uq;2&H&+ifOb$VLv!HHZ!_6gHICX$}W@0WbWtKkKXWM>N2 zV0JK_@K22sS_N;DE2+`Zl()XH?bmJl&i=80k6p6u*Cy;c+W7|pWnO4B9Xx?v7P z^{AmNwbE)@1Ci)}+1o4m0If)5Qdh=R5iv~dpRcIhi!ZoCpT$P|l&Re8Id@)b`nAW# zuI*05(5B}7`;~0=*GCS2Jm3G^U+CeOQ?9=; zK73z?x5#gaGZYACz@JG3@#EZTy}(}+)oSP|z#tP`(=*kIO?5Sz5W6yg{j##wLH^(ZZU^aNNVE{9kVKObV9 z_)Lfm#5u)5yh;0s5XX?ir%Oe*;<{BVp$HchE*I6gQhjyFttR(QXE28n>R4p}9n7;A z)5vr^)zx^SR9;(l>MUAfqia}(gL>D}?tc{n`yy jFEdTm@5n)edV#i6*x-J|e}H4b1F*;7pQZCw9>D(s4gB02 literal 0 HcmV?d00001 diff --git a/geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.woff b/geoportal/geoportailv3_geoportal/static-ngeo/webfonts/statec.woff new file mode 100644 index 0000000000000000000000000000000000000000..ff3753f1d8a13c1c344beff27539132cdee7c4f4 GIT binary patch literal 1512 zcmaJ>UuauZ82`R|?w=-I+tjv6(N@!Rx3RKzEJ+g;-O7}1V~)Wbh52B2m)<3XCbvyf zwt~Ki%7$)FLYY1Y1K(u6$#77{911?|Wt$8(*o1|_@WqFLP5hm6F15_y3E%mCzu)=3 z^PPLocXQ_G%nUJMSdXbw`LDqZiJl)v-`|}f;tuF1rS-gEy;iJvOVG;T$E77^Z+%ws zR;2b5xQvw+D=n^_hIRw?K-z)njk{&vnz7;pimHJsC z6O{U;MTv$NgCgQg$#*DwmCcHG7In=exVB!pSoJDCv}x4*RNDG`kdjHQZa_4ORNz`v0$W(r~LG z?u)N*`~5iSI8D)BTB0-bF?~*7ph&+xni`wR<+GW%lPlyiiTJ>1x}DfI(sjBS`Ma5w zPfzj|9Lp7WFJs$RnA2nVeVot88ZvMoJ5_Lcv%Tqr${Gc93UcCWslmaNv>#me1J`}J zZ$$HvE3SKD%zbKHcrJh+<=7I2$?4`@I~Fk`mT<&!v*E-#A~CzGi}M;SbH}(Ttn18d z*~Z^L!Uvb$3HrW^4t5J$1ljY!oY7FVM@DY$O2p%dU2jU7NTq(&l-KpqQa?|`F(&q3 z7bY9&=I@Se7&ydo^RewXc9*+@3lc1|Gj4WrjytT)Pngd=yYz1J3YYs1Mx)$(z^Ak4 zoBNH4Id#9B&HnMy!Efez-ujC=)we)*J{*<(ANueX<@bggR|7qudQyKoB<^qP6dhsd zoiveY;KPbV(G4%tpDM$mFZF-J*3LRX&)xKWxG$3fNq3$Bd@{rWI3HpYcs0Zpb{z<@ z4gGM4qx2%3lf7<6pmbwJV*|JpVgdYih)v*+LTphSU9976=*L1Fr5s&eC}UfrKho?1&DDh5Yzwn>^%wd<%}!ZuZPB9H3u^UzMw8s % if 'skip_appcache' in settings: @@ -14,23 +26,32 @@ CACHE MANIFEST % endif CACHE: -${request.static_url('geoportailv3:static/build/build.js')} -${request.static_url('geoportailv3:static/build/locale/fr/geoportailv3.json')} -${request.static_url('geoportailv3:static/build/build.min.css')} -${request.static_url('geoportailv3:static/images/gov-light.png')} + +/dynamic.js?interface=main +/getuserinfo +${main_js_url} +${main_css_url} +${gov_light_url} +${request.static_url('geoportailv3_geoportal:static-ngeo/images/arrow.png')} +% for stuff_url in built_stuffs_urls: +${stuff_url} +% endfor + +% for lang in ['fr', 'en', 'lb', 'de']: +${request.static_url('geoportailv3_geoportal:static-ngeo/build/' + lang + '.json')} +% endfor % for font in fonts: -${request.static_url('geoportailv3:static/build/fonts/' + font)} +${request.static_url('geoportailv3_geoportal:static-ngeo/fonts/' + font)} % endfor % for webfont in webfonts: -${request.static_url('geoportailv3:static/webfonts/' + webfont)} +${request.static_url('geoportailv3_geoportal:static-ngeo/webfonts/' + webfont)} % endfor -${request.static_url('geoportailv3:static/build/fonts/fontawesome-webfont.woff2')}?v=4.7.0 NETWORK: * FALLBACK: /theme/main /theme/main -/themes ${request.route_url('themes', _query={'version': '2', 'background': 'bglayers', 'interface': 'desktop', 'catalogue': 'true', 'min_levels': '1'})} +/themes ${request.route_url('themes', _query={'version': '2', 'background': 'background', 'interface': 'desktop', 'catalogue': 'true', 'min_levels': '1'})} ${request.route_url('mymaps_getallcategories')} ${request.route_url('mymaps_getallcategories')} /predefined_wms /predefined_wms diff --git a/geoportal/geoportailv3_geoportal/templates/index.html b/geoportal/geoportailv3_geoportal/templates/index.html deleted file mode 100644 index c3db27132..000000000 --- a/geoportal/geoportailv3_geoportal/templates/index.html +++ /dev/null @@ -1,528 +0,0 @@ -## -*- coding: utf-8 -*- -<% - settings = request.registry.settings - proxy_wms_url = settings.get('proxy_wms_url') - node_modules_path = settings.get('node_modules_path') - closure_library_path = settings.get('closure_library_path') - exclude_theme_layer_search = settings.get('exclude_theme_layer_search') - authtkt_cookie_name = settings.get('authtkt_cookie_name') - overview_map_show = settings.get('overview_map')['show'] - overview_map_base_layer = settings.get('overview_map')['base_layer'] - lidar = settings.get('lidar') - show_anf_link = 'ng-hide' - if 'show_link' in settings.get('anf') and settings.get('anf')['show_link'] == True: - show_anf_link = 'ng-show' -%>\ - - - - - - - - - - - - - - - - - - -% if debug: - -% else: - - % endif - - - - -
    - -
    - -
    - -
    - - - -
    -
    -
    -
    -
    -
    -
    {{mainCtrl.selectedLayers[0].get('label') | translate}}
    -
    - - -
    -
    - - -% if debug: - - - - - - - - - - - - - - - - - - - - - - -% else: - -% endif - - - - - - - - - diff --git a/geoportal/geoportailv3_geoportal/views/authentication.py b/geoportal/geoportailv3_geoportal/views/authentication.py index b8c6aaccd..cab58a8b3 100644 --- a/geoportal/geoportailv3_geoportal/views/authentication.py +++ b/geoportal/geoportailv3_geoportal/views/authentication.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- from pyramid.view import view_config -from pyramid_ldap import get_ldap_connector +from pyramid_ldap3 import get_ldap_connector from pyramid.security import unauthenticated_userid -from geoportailv3.portail import Connections -from geoportailv3.portail import PortailSession -import ldap +from geoportailv3_geoportal.portail import Connections +from c2cgeoportal_commons.models import DBSession +import ldap3 as ldap import logging log = logging.getLogger(__name__) @@ -23,13 +23,11 @@ def ldap_user_validator(request, username, password): if data is not None: connection.action = "CONNECT" - PortailSession.add(connection) - PortailSession.commit() - return data[0] + DBSession.add(connection) + return username else: connection.action = "CONNECT ERROR" - PortailSession.add(connection) - PortailSession.commit() + DBSession.add(connection) return None @@ -41,51 +39,68 @@ def ldap_user_validator(request, username, password): def get_user_from_request(request): - from c2cgeoportal.models import DBSession, Role + from c2cgeoportal_commons.models import DBSession + from c2cgeoportal_commons.models.main import Role class O(object): pass username = unauthenticated_userid(request) if username is not None: + default_mymaps_role = int(request.registry.settings['default_mymaps_role']) user = O() user.id = 0 user.username = username user.email = None - user.is_admin = False - user.mymaps_role = 999 + user.is_mymaps_admin = False + user.mymaps_role = default_mymaps_role user.ogc_role = -1 user.sn = None - + user.is_password_changed = None + user.role_name = None connector = get_ldap_connector(request) cm = connector.manager # 0 means 'Tous publics' roletheme = 0 with cm.connection() as conn: - result = conn.search_s('ou=portail,dc=act,dc=lu', - ldap.SCOPE_SUBTREE, '(login=%s)' % username) + ldap_settings = request.registry.settings['ldap'] + base_dn = ldap_settings['base_dn'] + filter_tmpl = ldap_settings['filter_tmpl'].replace('%(login)s', username) + message_id = conn.search( + base_dn, filter_tmpl, ldap.SUBTREE, + ldap.DEREF_ALWAYS, ldap.ALL_ATTRIBUTES) + result = conn.get_response(message_id)[0] + if len(result) == 1: - if 'roleTheme' in result[0][1]: - roletheme = result[0][1]['roleTheme'][0] - if 'mail' in result[0][1]: - user.mail = result[0][1]['mail'][0] - if 'sn' in result[0][1]: - user.sn = result[0][1]['sn'][0] + obj = result[0]['raw_attributes'] + if 'roleTheme' in obj: + # This is the plain c2cgeoportal role used for authentication. + # Notably in the admin interface. + # The role with name role_admin has id 645. + roletheme = obj['roleTheme'][0].decode() + if 'mail' in obj: + user.mail = obj['mail'][0].decode() + if 'sn' in obj: + user.sn = obj['sn'][0].decode() else: user.sn = user.mail - if 'isMymapsAdmin' in result[0][1]: - user.is_admin =\ - "TRUE" == (result[0][1]['isMymapsAdmin'][0]).upper() - if 'roleMymaps' in result[0][1]: - user.mymaps_role = int(result[0][1]['roleMymaps'][0]) - if 'roleOGC' in result[0][1]: - user.ogc_role = result[0][1]['roleOGC'][0] + if 'isMymapsAdmin' in obj: + user.is_mymaps_admin = "TRUE" == obj['isMymapsAdmin'][0].upper().decode() + if 'roleMymaps' in obj: + # This role is used for myMaps. + user.mymaps_role = int(obj['roleMymaps'][0]) + if 'roleOGC' in obj: + # This role is used by the print proxy and internal WMS proxy. + user.ogc_role = int(obj['roleOGC'][0]) try: + # Loading the plain c2cgeoportal role used for authentication. user.role = DBSession.query(Role).filter_by(id=roletheme).one() except Exception as e: + # Fallback to the "Tous publics" role user.role = DBSession.query(Role).filter_by(id=0).one() log.exception(e) + user.role_name = user.role.name user.functionalities = [] return user @@ -109,5 +124,5 @@ def get_user_info(self): "sn": getattr( self.request.user, 'sn', self.request.user.username), - "is_admin": getattr(self.request.user, 'is_admin', False)} + "is_admin": getattr(self.request.user, 'is_mymaps_admin', False)} return {} diff --git a/geoportal/geoportailv3_geoportal/views/casipo.py b/geoportal/geoportailv3_geoportal/views/casipo.py index 310b9c442..cf776ff16 100644 --- a/geoportal/geoportailv3_geoportal/views/casipo.py +++ b/geoportal/geoportailv3_geoportal/views/casipo.py @@ -7,7 +7,7 @@ import shutil import os import smtplib -import urllib2 +import urllib.request from email.mime.text import MIMEText import time import sys @@ -35,7 +35,7 @@ def __download(self, num): num, self.config["casipo"]["fme_token"]) try: - f = urllib2.urlopen(url, None, 1800) + f = urllib.request.urlopen(url, None, 1800) data = f self.filename = '/tmp/%s_%s.pdf' % (num, str(int(time.time()))) with open(self.filename, 'wb') as fp: diff --git a/geoportal/geoportailv3_geoportal/views/download.py b/geoportal/geoportailv3_geoportal/views/download.py index 2006f0bc2..d6618b2bb 100644 --- a/geoportal/geoportailv3_geoportal/views/download.py +++ b/geoportal/geoportailv3_geoportal/views/download.py @@ -3,18 +3,13 @@ from pyramid.response import Response from pyramid.httpexceptions import HTTPBadRequest from pyramid.httpexceptions import HTTPUnauthorized -from geoportailv3.portail import MesurageDownload, SketchDownload -from geoportailv3.portail import PortailSession -from geoportailv3.models import LuxDownloadUrl, LuxMeasurementDirectory -from c2cgeoportal.models import DBSession -from PyPDF2 import PdfFileReader +from geoportailv3_geoportal.portail import MesurageDownload, SketchDownload +from geoportailv3_geoportal.models import LuxDownloadUrl, LuxMeasurementDirectory +from c2cgeoportal_commons.models import DBSession import logging import mimetypes -import geoportailv3.PF -import urllib2 -import subprocess -import tempfile -import os +import geoportailv3_geoportal.PF +import urllib.request log = logging.getLogger(__name__) @@ -37,7 +32,7 @@ def download_generic(self): return HTTPUnauthorized() url = entry.url + filename try: - data = urllib2.urlopen(url, None, 1800) + data = urllib.request.urlopen(url, None, 1800) except Exception as e: log.exception(e) data = None @@ -57,6 +52,8 @@ def download_generic(self): @view_config(route_name='download_sketch') def download_sketch(self): + if self.request.user is None: + return HTTPUnauthorized() filename = self.request.params.get('name', None) if filename is None: return HTTPBadRequest() @@ -96,7 +93,7 @@ def download_measurement(self): if filename is None or townname is None: return HTTPBadRequest("parameters are missing") - pf = geoportailv3.PF.PF() + pf = geoportailv3_geoportal.PF.PF() if not pf._is_download_authorized( townname, self.request.user, self.request.referer): @@ -155,8 +152,8 @@ def _log_download_sketch_stats(self, filename, town): sketch_download.filename = filename sketch_download.directory = town - PortailSession.add(sketch_download) - PortailSession.commit() + DBSession.add(sketch_download) + DBSession.commit() def _log_download_measurement_stats(self, filename, town, parcel): mesurage_download = MesurageDownload() @@ -170,5 +167,5 @@ def _log_download_measurement_stats(self, filename, town, parcel): mesurage_download.commune = town mesurage_download.parcelle = parcel - PortailSession.add(mesurage_download) - PortailSession.commit() + DBSession.add(mesurage_download) + DBSession.commit() diff --git a/geoportal/geoportailv3_geoportal/views/feedback.py b/geoportal/geoportailv3_geoportal/views/feedback.py index 78e022f52..1b021249b 100644 --- a/geoportal/geoportailv3_geoportal/views/feedback.py +++ b/geoportal/geoportailv3_geoportal/views/feedback.py @@ -2,13 +2,13 @@ from pyramid.i18n import get_localizer, TranslationStringFactory from pyramid.view import view_config from pyramid.httpexceptions import HTTPNotFound -from turbomail import Message -from geoportailv3.mymaps import Map, Feature - +from geoportailv3_geoportal.mymaps import Map, Feature +import geojson +from marrow.mailer import Message import geojson import bleach import logging - +from c2cgeoportal_commons.models import DBSessions _ = TranslationStringFactory("geoportailv3-server") log = logging.getLogger(__name__) @@ -20,6 +20,8 @@ def __init__(self, request): self.request = request self.config = self.request.registry.settings self.localizer = get_localizer(self.request) + self.db_mymaps = DBSessions['mymaps'] + @view_config(route_name='feedback', renderer='json') def feedback(self): @@ -56,7 +58,7 @@ def feedbackanf(self): try: vars = self.request.json_body map_id = self.config['anf']['map_id'] - map = self.request.db_mymaps.query(Map).get(map_id) + map = self.db_mymaps.query(Map).get(map_id) if map is None: return HTTPNotFound() sanitized_description = bleach.clean(vars['description']) @@ -88,7 +90,7 @@ def feedbackanf(self): log.exception(e) if obj is not None: map.features.append(obj) - self.request.db_mymaps.commit() + self.db_mymaps.commit() html_body = u"

    L\'utilisateur {4} " \ u"a remarqué le problème suivant:

    {1}

    " \ diff --git a/geoportal/geoportailv3_geoportal/views/fulltextsearch.py b/geoportal/geoportailv3_geoportal/views/fulltextsearch.py index bd868ca10..9a52a6bed 100644 --- a/geoportal/geoportailv3_geoportal/views/fulltextsearch.py +++ b/geoportal/geoportailv3_geoportal/views/fulltextsearch.py @@ -3,7 +3,10 @@ from pyramid.view import view_config from geojson import Feature, FeatureCollection from shapely.geometry import shape -from geoportailv3.lib.search import get_elasticsearch, get_index +from geoportailv3_geoportal.lib.search import get_elasticsearch, get_index +import os +import json +import geojson class FullTextSearchView(object): @@ -33,6 +36,10 @@ def fulltextsearch(self): if limit > maxlimit: limit = maxlimit + if os.environ.get('FAKE_FULLTEXT_SEARCH', None) == '1': + fake_response = '{"type": "FeatureCollection", "features": [{"geometry": {"type": "Polygon", "coordinates": [[[6.069344907, 49.5609585166], [6.0691568068, 49.654826971], [6.2036803238, 49.6548627478], [6.2036103715, 49.560994175], [6.069344907, 49.5609585166]]]}, "properties": {"layer_name": "Commune", "label": "Luxembourg"}, "type": "Feature", "bbox": [6.0691568068, 49.5609585166, 6.2036803238, 49.6548627478], "id": "3712765"}, {"geometry": {"type": "Polygon", "coordinates": [[[5.9270670114, 50.0512449024], [5.9269772374, 50.0692253411], [5.954912626, 50.0692797917], [5.9549919612, 50.0512993185], [5.9270670114, 50.0512449024]]]}, "properties": {"layer_name": "Localité", "label": "FAKE: Lullange (L\u00ebllgen)"}, "type": "Feature", "bbox": [5.9269772374, 50.0512449024, 5.9549919612, 50.0692797917], "id": "3015351"}, {"geometry": {"type": "Point", "coordinates": [6.0385391523, 49.8992727652]}, "properties": {"layer_name": "editus_poi_292", "label": "FAKE: RFX LU [Kehmen] (Garage)"}, "type": "Feature", "bbox": {}, "id": "3943529"}, {"geometry": {"type": "Polygon", "coordinates": [[[5.8781311725, 49.8994824237], [5.8780236843, 49.9174632643], [5.9058711934, 49.9175293601], [5.9059683315, 49.8995484776], [5.8781311725, 49.8994824237]]]}, "properties": {"layer_name": "Localité", "label": "Lultzhausen (L\u00eblz)"}, "type": "Feature", "bbox": [5.8780236843, 49.8994824237, 5.9059683315, 49.9175293601], "id": "3015352"}, {"geometry": {"type": "Polygon", "coordinates": [[[6.1307043487, 49.6913873587], [6.1306908729, 49.7093690745], [6.1584195338, 49.7093744989], [6.1584227788, 49.6913927796], [6.1307043487, 49.6913873587]]]}, "properties": {"layer_name": "Localité", "label": "FAKE: Lorentzweiler (Luerenzweiler)"}, "type": "Feature", "bbox": [6.1306908729, 49.6913873587, 6.1584227788, 49.7093744989], "id": "3015350"}, {"geometry": {"type": "Point", "coordinates": [6.1260755554, 49.5341675239]}, "properties": {"layer_name": "editus_poi_293", "label": "Ferra-Lu Sàrl [Livange] (Menuiserie)"}, "type": "Feature", "bbox": {}, "id": "3948238"}, {"geometry": {"type": "Polygon", "coordinates": [[[6.0374612588, 49.5476811355], [6.0373496005, 49.5897910773], [6.1042912589, 49.5898468242], [6.1043453603, 49.5477367999], [6.0374612588, 49.5476811355]]]}, "properties": {"layer_name": "Commune", "label": "Leudelange"}, "type": "Feature", "bbox": [6.0373496005, 49.5476811355, 6.1043453603, 49.5898468242], "id": "3712759"}, {"geometry": {"type": "Polygon", "coordinates": [[[6.1201290384, 49.5916379191], [6.1201117205, 49.609619944], [6.1477837563, 49.6096278959], [6.1477909001, 49.5916458659], [6.1201290384, 49.5916379191]]]}, "properties": {"layer_name": "Localité", "label": "Luxembourg-Gare (Gare)"}, "type": "Feature", "bbox": [6.1201117205, 49.5916379191, 6.1477909001, 49.6096278959], "id": "3015354"}]}' # noqa + return geojson.loads(fake_response) + try: layer = self.request.params.get('layer') except: @@ -171,6 +178,10 @@ def layersearch(self): if limit > maxlimit: limit = maxlimit + if os.environ.get('FAKE_LAYERSEARCH', None) == '1': + fake_response = '[{"layer_id": 370, "name": "luxembourg_on_horse", "language": "de"}, {"layer_id": 563, "name": "eau_new_Luftdruck", "language": "de"}, {"layer_id": 748, "name": "aero_1994_30k", "language": "de"}, {"layer_id": 229, "name": "aero_1951_25k", "language": "de"}, {"layer_id": 738, "name": "luref_graticules", "language": "en"}, {"layer_id": 341, "name": "aero_1951_10k", "language": "de"}, {"layer_id": 615, "name": "eau_new_Luftfeucht", "language": "de"}, {"layer_id": 140, "name": "aero_1963_20k", "language": "de"}]' # noqa + return json.loads(fake_response) + query_body = { "query": { "bool": { @@ -249,6 +260,11 @@ def cmssearch(self): if limit > maxlimit: limit = maxlimit + if os.environ.get('FAKE_CMSSEARCH', None) == '1': + fake_response = \ +'[{"url": "/fr/questions/payer-par-domiciliation/", "text": " Avec l\'introduction du système de paiement SEPA dans 32 pays européens à partir du 1er février 2014, il est maintenant possible de payer vos factures par domiciliation. Le SEPA Direct Debit (SDD) garantit au consommateur un droit de remboursement systématique, au cours de huit semaines (8) après le débit du compte du consommateur. Votre facture sera émise à la première journée de travail du mois, reprenant l\'énumération des bulletins de livraisons de la période précédente. Vous avez une semaine pour vérifier si le détail correspond avec les livraisons fournies. Après ce délai, le fichier de domiciliations sera envoyé à la société CETREL qui exécutera le prélèvement le 15e jour du mois. Si vous êtes intéressé par la domiciliation, vous pouvez télécharger ici , que nous vous prions de renvoyer dûment complété et signé à l\'adresse: Administration du Cadastre et de la Topographie Service de la comptabilité B.P. 1761 L-1017 Luxembourg Pour avoir plus d\'informations concernant le déroulement de l\'encaissement automatique, n\'hésitez pas à contacter notre service de comptabilité au 44901-258. Pour avoir plus d\'informations sur le SEPA Direct Debit (SDD), veuillez consulter le formulaire de demande d\'accès au service SEPA ABBL. Demander la domiciliation de vos factures ", "language": "fr", "title": "FAKE: Payer par Domiciliation"}]' # noqa + return json.loads(fake_response) + query_body = { "query": { "bool": { diff --git a/geoportal/geoportailv3_geoportal/views/geocode.py b/geoportal/geoportailv3_geoportal/views/geocode.py index 4c8ca380e..4218d4f20 100644 --- a/geoportal/geoportailv3_geoportal/views/geocode.py +++ b/geoportal/geoportailv3_geoportal/views/geocode.py @@ -6,7 +6,8 @@ from geojson import loads as geojson_loads from geoalchemy2 import func from geoalchemy2.elements import WKTElement, WKBElement -from geoportailv3.geocode import Address, WKPOI, Neighbourhood, Parcel +from geoportailv3_geoportal.geocode import Address, WKPOI, Neighbourhood, Parcel +from c2cgeoportal_commons.models import DBSessions from shapely.wkt import loads from geojson import dumps as geojson_dumps from geoalchemy2.shape import to_shape @@ -14,6 +15,8 @@ import re import difflib +import os +import json import logging log = logging.getLogger(__name__) @@ -24,6 +27,7 @@ class Geocode(object): def __init__(self, request): self.request = request self.returnParcelInfo = False + self.db_ecadastre = DBSessions['ecadastre'] # View used to get an adress from a coordinate. @view_config(route_name="reverse_geocode", renderer="json") @@ -43,9 +47,12 @@ def reverse(self): "y": northing }, srid=2169), Address.geom) + if os.environ.get('FAKE_REVERSE_GEOCODING') == '1': + return json.loads('{"count": 1, "results": [{"id_caclr_street": "461", "distance": 33.7389366951768, "street": "Rue Jean-Pierre Brasseur", "postal_code": "1258", "id_caclr_bat": "21478", "geom": {"type": "Point", "coordinates": [76302.2077999998, 75334.6180995487]}, "locality": "Luxembourg", "number": "16"}]}') # noqa + results = [] - for feature in self.request.db_ecadastre.query( + for feature in self.db_ecadastre.query( Address.id_caclr_rue.label("id_caclr_rue"), Address.id_caclr_bat.label("id_caclr_bat"), Address.rue.label("rue"), @@ -178,12 +185,12 @@ def get_zips_code_from_locality(self, locality, p_session): def encoded_locality_result(self, locality): locality_info = self.get_best_locality_name( - locality, self.request.db_ecadastre, True) + locality, self.db_ecadastre, True) if locality_info is not None: if locality_info['locality'] is None: locality_info['locality'] = "" if locality_info['geom'] is None: - features = self.request.db_ecadastre.query((func.ST_AsText( + features = self.db_ecadastre.query((func.ST_AsText( func.ST_Centroid( func.ST_Collect(Address.geom)))).label("geom"), Address.localite).filter( @@ -226,7 +233,7 @@ def encoded_locality_result(self, locality): return self.encoded_country_result() def encoded_post_code_result(self, p_zip): - features = self.request.db_ecadastre.query( + features = self.db_ecadastre.query( (func.ST_AsText(func.ST_Centroid(func.ST_Collect(Address.geom)))). label("geom"), Address.localite).\ @@ -268,7 +275,7 @@ def encoded_post_code_result(self, p_zip): return self.encoded_country_result() def encoded_post_code_locality_result(self, p_zip, p_locality): - features = self.request.db_ecadastre.query( + features = self.db_ecadastre.query( (func.ST_AsText(func.ST_Centroid(func.ST_Collect(Address.geom)))). label("geom"), Address.localite).\ filter(" lower(code_postal) = lower('" + p_zip + "')").\ @@ -285,7 +292,7 @@ def encoded_post_code_locality_result(self, p_zip, p_locality): if res.localite is None: res.localite = '' - features = self.request.db_ecadastre.query( + features = self.db_ecadastre.query( (func.ST_AsText(func.ST_Centroid( func.ST_Collect(Address.geom)))). label("geom"), Address.localite).\ @@ -398,7 +405,7 @@ def encode_result(self, feature): "id_caclr_building": str(caclr_bat) }} if hasattr(feature, 'cle_parcelle') and self.returnParcelInfo is True: - label = self.request.db_ecadastre.query( + label = self.db_ecadastre.query( Parcel).get(feature.cle_parcelle) resp['parcel'] = { @@ -412,7 +419,7 @@ def transform_to_latlon(self, x, y): geomwgs = func.ST_AsText(func.ST_Centroid(func.ST_Transform( WKTElement( 'POINT(%(x)s %(y)s)' % {"x": x, "y": y}, 2169), 4326))) - result = self.request.db_ecadastre.query(geomwgs.label( + result = self.db_ecadastre.query(geomwgs.label( "geom"), WKPOI.geom.label("geom2")).first() if isinstance(result.geom, unicode) or\ isinstance(result.geom, str): @@ -420,7 +427,7 @@ def transform_to_latlon(self, x, y): return result except Exception as e: log.exception(e) - self.request.db_ecadastre.rollback() + transaction.abort() return None # Returns true if zip code exists in database @@ -678,7 +685,7 @@ def search_in_well_known_poi_table( feature.accuracy = 7 results.append(self.encode_result(feature)) except: - p_session.rollback() + transaction.abort() log.error("Zip code is not correct: " + p_zip) if len(results) == 0 and p_locality is not None: for feature in\ @@ -708,7 +715,7 @@ def search_in_well_known_poi_table( except Exception as e: log.exception(e) - p_session.rollback() + transaction.abort() return results @@ -1089,7 +1096,7 @@ def search(self): results = self.start_search( 0.7, p_num, p_street, p_zip, p_locality, p_country, - self.request.db_ecadastre) + self.db_ecadastre) results = self.keep_the_best_result(results, p_street) if results is not None and p_zip is not None and\ @@ -1111,7 +1118,7 @@ def search(self): except Exception as e: log.exception(e) - self.request.db_ecadastre.rollback() + transaction.abort() results = [self.encoded_country_result()] if 'cb' not in self.request.params: @@ -1630,7 +1637,7 @@ def _split_address(self, address): 'locality': locality} def get_locality_from_zip(self, p_zip): - features = self.request.db_ecadastre.query(Address.localite).filter( + features = self.db_ecadastre.query(Address.localite).filter( " lower(code_postal) = lower('" + p_zip + "')").\ group_by(Address.localite).all() diff --git a/geoportal/geoportailv3_geoportal/views/getfeatureinfo.py b/geoportal/geoportailv3_geoportal/views/getfeatureinfo.py index 19e81c0e3..8304443c7 100644 --- a/geoportal/geoportailv3_geoportal/views/getfeatureinfo.py +++ b/geoportal/geoportailv3_geoportal/views/getfeatureinfo.py @@ -1,13 +1,13 @@ # -*- coding: utf-8 -*- import logging -import urllib2 import re -from urllib import urlencode +import urllib.request +from urllib.parse import urlencode from pyramid.renderers import render from pyramid.view import view_config -from geoportailv3.models import LuxGetfeatureDefinition -from geoportailv3.models import LuxLayerInternalWMS, LuxDownloadUrl +from geoportailv3_geoportal.models import LuxGetfeatureDefinition +from geoportailv3_geoportal.models import LuxLayerInternalWMS, LuxDownloadUrl from mako.template import Template from pyramid.httpexceptions import HTTPBadRequest, HTTPBadGateway from pyramid.i18n import get_localizer, TranslationStringFactory @@ -17,7 +17,8 @@ from geojson import loads as geojson_loads from shapely.geometry import asShape, box from shapely.geometry.polygon import LinearRing -from c2cgeoportal.models import DBSession, RestrictionArea, Role, Layer +from c2cgeoportal_commons.models import DBSession, DBSessions +from c2cgeoportal_commons.models.main import RestrictionArea, Role, Layer from shapely.geometry import MultiLineString, mapping, shape log = logging.getLogger(__name__) @@ -61,12 +62,12 @@ def download_resource(self): return HTTPBadRequest("Attribute is not a valid url") timeout = 15 try: - f = urllib2.urlopen(url, None, timeout) + f = urllib.request.urlopen(url, None, timeout) data = f.read() except: try: # Retry to get the result - f = urllib2.urlopen(url, None, timeout) + f = urllib.request.urlopen(url, None, timeout) data = f.read() except Exception as e: log.exception(e) @@ -90,7 +91,7 @@ def get_remote_template(self): if (luxgetfeaturedefinitions[0].template is not None and len(luxgetfeaturedefinitions[0].template) > 0): - f = urllib2.urlopen(luxgetfeaturedefinitions[0].template, None, 15) + f = urllib.request.urlopen(luxgetfeaturedefinitions[0].template, None, 15) return Response(f.read()) return HTTPBadRequest() @@ -433,7 +434,7 @@ def get_info(self, fid, coordinates_big_box, coordinates_small_box, r['remote_template']: data = "" try: - url_remote = urllib2.urlopen( + url_remote = urllib.request.urlopen( l_template + "&render=apiv3", None, 15) data = url_remote.read() except Exception as e: @@ -733,8 +734,8 @@ def get_additional_info_for_ng95(self, layer_id, rows): def get_info_from_pf(self, layer_id, rows, measurements=True, attributes_to_remove=""): - import geoportailv3.PF - pf = geoportailv3.PF.PF() + import geoportailv3_geoportal.PF + pf = geoportailv3_geoportal.PF.PF() features = [] for row in rows: geometry = geojson_loads(row['st_asgeojson']) @@ -837,7 +838,7 @@ def _ogc_getfeatureinfo( content = "" try: - result = urllib2.urlopen(query, None, 15) + result = urllib.request.urlopen(query, None, 15) content = result.read() except Exception as e: log.exception(e) @@ -954,7 +955,7 @@ def _get_external_data(self, layer_id, url, id_column='objectid', separator = '&' query = '%s%s%s' % (url, separator, urlencode(body)) try: - result = urllib2.urlopen(query, None, 15) + result = urllib.request.urlopen(query, None, 15) content = result.read() except Exception as e: log.exception(e) @@ -1045,11 +1046,11 @@ def _get_url_with_token(self, url): tokenurl = baseurl.split('rest/')[0] +\ 'tokens?username=%s&password=%s'\ % (user_password[0], user_password[1]) - token = urllib2.urlopen(tokenurl, None, 15).read() + token = urllib.request.urlopen(tokenurl, None, 15).read() return baseurl + "token=" + token except Exception as e: log.exception(e) return None def _get_session(self, engine_name): - return getattr(self.request, 'db_' + engine_name) + return DBSessions[engine_name] diff --git a/geoportal/geoportailv3_geoportal/views/jsapi.py b/geoportal/geoportailv3_geoportal/views/jsapi.py index 27d679965..95a2d73ec 100644 --- a/geoportal/geoportailv3_geoportal/views/jsapi.py +++ b/geoportal/geoportailv3_geoportal/views/jsapi.py @@ -1,7 +1,7 @@ from pyramid.view import view_config import logging -from c2cgeoportal.views.entry import Entry +from c2cgeoportal_geoportal.views.entry import Entry log = logging.getLogger(__name__) diff --git a/geoportal/geoportailv3_geoportal/views/legends.py b/geoportal/geoportailv3_geoportal/views/legends.py index 888435cc6..18f2317f6 100644 --- a/geoportal/geoportailv3_geoportal/views/legends.py +++ b/geoportal/geoportailv3_geoportal/views/legends.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- from pyramid.view import view_config from pyramid.response import Response -from cStringIO import StringIO +from io import StringIO from bs4 import BeautifulSoup import weasyprint -import urllib2 +import urllib.request import httplib2 @@ -48,16 +48,17 @@ def get_html(self): "id=%s:legend:%s&do=export_html" % \ (lang, name) - f = urllib2.urlopen(httplib2.iri2uri(url), None, 15) + f = urllib.request.urlopen(httplib2.iri2uri(url), None, 15) data = f.read() data = data.replace( - "/lib/exe/fetch.php", - "https://wiki.geoportail.lu/lib/exe/fetch.php") + b"/lib/exe/fetch.php", + b"https://wiki.geoportail.lu/lib/exe/fetch.php") data = data.replace( - "src=\"img/", "src=\"https://wiki.geoportail.lu/img/") + b"src=\"img/", + b"src=\"https://wiki.geoportail.lu/img/") data = data.replace( - "/lib/exe/detail.php", - "https://wiki.geoportail.lu/lib/exe/detail.php") + b"/lib/exe/detail.php", + b"https://wiki.geoportail.lu/lib/exe/detail.php") soup = BeautifulSoup(data, "lxml") a_tags = soup.find_all("a") diff --git a/geoportal/geoportailv3_geoportal/views/luxprintproxy.py b/geoportal/geoportailv3_geoportal/views/luxprintproxy.py index 1507e0299..2dc227c83 100644 --- a/geoportal/geoportailv3_geoportal/views/luxprintproxy.py +++ b/geoportal/geoportailv3_geoportal/views/luxprintproxy.py @@ -45,13 +45,14 @@ # as representing official policies, # either expressed or implied, of the FreeBSD Project. +import os import json import logging import re import random -import urllib -import urllib2 -from cStringIO import StringIO +import urllib.parse +import urllib.request +from io import BytesIO from datetime import datetime from pyramid.i18n import get_localizer, TranslationStringFactory @@ -62,12 +63,13 @@ from PyPDF2 import PdfFileMerger import weasyprint -from c2cgeoportal.models import RestrictionArea, Role, Layer -from c2cgeoportal.views.printproxy import PrintProxy -from c2cgeoportal.lib.caching import NO_CACHE, get_region +from c2cgeoportal_commons.models import DBSession +from c2cgeoportal_commons.models.main import RestrictionArea, Role, Layer +from c2cgeoportal_geoportal.views.printproxy import PrintProxy +from c2cgeoportal_geoportal.lib.caching import NO_CACHE, get_region -from geoportailv3.models import DBSession, LuxPrintJob -from geoportailv3.models import LuxPrintServers, LuxLayerInternalWMS +from geoportailv3_geoportal.models import LuxPrintJob, LuxPrintServers, \ + LuxLayerInternalWMS _ = TranslationStringFactory("geoportailv3-server") log = logging.getLogger(__name__) @@ -80,14 +82,17 @@ class LuxPrintProxy(PrintProxy): def lux_report_create(self): token = self.config["authtkt_secret"] print_servers = DBSession.query(LuxPrintServers).all() - print_urls = [print_server.url for print_server in print_servers] - urllib2.getproxies = lambda: {} + if os.environ.get('FAKE_PRINT_URLS'): + print_urls = os.environ.get('FAKE_PRINT_URLS').split(',') + else: + print_urls = [print_server.url for print_server in print_servers] + urllib.request.getproxies = lambda: {} valid_print_urls = [] if print_urls is not None and len(print_urls) > 0: for url in print_urls: try: test_url = url.replace("/print/geoportailv3", "") - urllib2.urlopen(test_url) + urllib.request.urlopen(test_url) valid_print_urls.append(url) except Exception as e: log.exception(e) @@ -122,8 +127,8 @@ def lux_report_create(self): not self._is_authorized(internal_wms): return HTTPUnauthorized() if "longUrl" in spec["attributes"]: - opener = urllib2.build_opener(urllib2.HTTPHandler()) - data = urllib.urlencode({"url": spec["attributes"]["longUrl"]}) + opener = urllib.request.build_opener(urllib.request.HTTPHandler()) + data = urllib.parse.urlencode({"url": spec["attributes"]["longUrl"]}) content = opener.open( "https://map.geoportail.lu/wsgi/short/create", data=data).read() @@ -135,7 +140,7 @@ def lux_report_create(self): job = LuxPrintJob() job.spec = json.dumps(spec) - self.request.body = job.spec + self.request.body = str.encode(job.spec) resp, content = self._proxy("%s/report.%s" % ( print_url, @@ -208,7 +213,7 @@ def _create_legend_from_image(self, url, title, access_constraints): log.info("Get legend from URL:\n%s." % url) - legend_buffer = StringIO() + legend_buffer = BytesIO() html_access_constraints = "" if access_constraints is not None and\ len(access_constraints) > 0: @@ -247,7 +252,7 @@ def _get_legend(self, name, lang): (lang, name) log.info("Get legend from URL:\n%s." % url) - legend_buffer = StringIO() + legend_buffer = BytesIO() weasyprint.HTML(url).write_pdf( legend_buffer, stylesheets=[css] @@ -277,22 +282,22 @@ def lux_report_get(self): attributes["firstPagesUrls"] is not None and\ len(attributes["firstPagesUrls"]) > 0: attributes["firstPagesUrls"].reverse() - for page_url in attributes["firstPagesUrls"]: + for pageUrl in attributes["firstPagesUrls"]: try: merger = PdfFileMerger(strict=False) - if page_url['type'].lower() == 'pdf': - opener = urllib2.build_opener( - urllib2.HTTPHandler()) - pdf_content = opener.open(page_url['url']).read() - merger.append(StringIO(pdf_content)) + if pageUrl['type'].lower() == 'pdf': + opener = urllib.request.build_opener( + urllib.request.HTTPHandler()) + pdf_content = opener.open(pageUrl['url']).read() + merger.append(BytesIO(pdf_content)) else: - first_page = StringIO() - weasyprint.HTML(page_url['url']).write_pdf( + first_page = BytesIO() + weasyprint.HTML(pageUrl['url']).write_pdf( first_page ) merger.append(first_page) - merger.append(StringIO(content)) - content = StringIO() + merger.append(BytesIO(content)) + content = BytesIO() merger.write(content) content = content.getvalue() except Exception as e: @@ -301,7 +306,7 @@ def lux_report_get(self): if is_pdf and "legend" in attributes and\ attributes["legend"] is not None: merger = PdfFileMerger(strict=False) - merger.append(StringIO(content)) + merger.append(BytesIO(content)) lang = attributes.get("lang") @@ -323,7 +328,7 @@ def lux_report_get(self): elif "name" in item and item["name"] is not None: merger.append(self._get_legend(item["name"], lang)) - content = StringIO() + content = BytesIO() merger.write(content) content = content.getvalue() @@ -368,15 +373,15 @@ def lux_report_get(self): ".s-e {transform: rotate(45deg);} " ) merger = PdfFileMerger(strict=False) - merger.append(StringIO(content)) - query_results = StringIO() + merger.append(BytesIO(content)) + query_results = BytesIO() weasyprint.HTML(string=attributes["queryResults"]).write_pdf( query_results, stylesheets=[css] ) merger.append(query_results) - content = StringIO() + content = BytesIO() merger.write(content) content = content.getvalue() diff --git a/geoportal/geoportailv3_geoportal/views/luxthemes.py b/geoportal/geoportailv3_geoportal/views/luxthemes.py index 2b8b47253..9cac73d57 100644 --- a/geoportal/geoportailv3_geoportal/views/luxthemes.py +++ b/geoportal/geoportailv3_geoportal/views/luxthemes.py @@ -1,5 +1,6 @@ from pyramid.view import view_config -from c2cgeoportal.models import DBSession, Theme +from c2cgeoportal_commons.models import DBSession +from c2cgeoportal_commons.models.main import Theme import logging log = logging.getLogger(__name__) diff --git a/geoportal/geoportailv3_geoportal/views/mymaps.py b/geoportal/geoportailv3_geoportal/views/mymaps.py index f614b81d9..c19f0bc4a 100644 --- a/geoportal/geoportailv3_geoportal/views/mymaps.py +++ b/geoportal/geoportailv3_geoportal/views/mymaps.py @@ -3,35 +3,38 @@ import stat import uuid import imghdr -import ldap - +import ldap3 as ldap import geojson +import transaction + +from sqlalchemy.sql import text try: from json import dumps as json_dumps except: from simplejson import dumps as json_dumps -from turbomail import Message -from geoportailv3.mymaps import Category, Map, Feature, Role, Symbols, Images,\ +from marrow.mailer import Message +from geoportailv3_geoportal.mymaps import Category, Map, Feature, Role, Symbols, Images,\ RoleCategories, MapUser, CategoryUser from pyramid.httpexceptions import HTTPBadRequest, HTTPInternalServerError from pyramid.httpexceptions import HTTPNotFound, HTTPUnauthorized -from pyramid_ldap import get_ldap_connector +from pyramid_ldap3 import get_ldap_connector from pyramid.response import Response from pyramid.view import view_config from PIL import Image -from cStringIO import StringIO +from io import BytesIO from sqlalchemy.orm import make_transient from sqlalchemy import and_, or_, func from shapely.wkt import loads from shapely.ops import linemerge from shapely.geometry import Point, LineString -from c2cgeoportal.lib.caching import set_common_headers, NO_CACHE +from c2cgeoportal_geoportal.lib.caching import set_common_headers, NO_CACHE +from c2cgeoportal_commons.models import DBSessions import logging -import urllib2 +import urllib.request import json log = logging.getLogger(__name__) @@ -48,6 +51,8 @@ class Mymaps(object): def __init__(self, request): self.request = request self.config = self.request.registry.settings + self.db_mymaps = DBSessions['mymaps'] + self.db_pgroute = DBSessions['pgroute'] @view_config(route_name="get_arrow_color") def get_arrow_color(self): @@ -64,20 +69,20 @@ def get_arrow_color(self): # gets the default one, colorizes it and saves it if not os.path.exists(temp_file_path): url = self.request.static_url( - 'geoportailv3:static/images/arrow.png') - orig_arrow = urllib2.urlopen(url, None, 15) + 'geoportailv3_geoportal:static-ngeo/images/arrow.png') + orig_arrow = urllib.request.urlopen(url, None, 15) content = orig_arrow.read() - image = Image.open(StringIO(content)) + image = Image.open(BytesIO(content)) pixdata = image.load() - for y in xrange(image.size[1]): - for x in xrange(image.size[0]): + for y in range(image.size[1]): + for x in range(image.size[0]): if pixdata[x, y] == (255, 255, 255, 255): pixdata[x, y] =\ tuple(int(color[i:i+2], 16) for i in (0, 2, 4)) image.save(temp_file_path) - f = open(temp_file_path, "r") + f = open(temp_file_path, "rb") return Response(f.read(), headers={'Content-Type': 'image/png'}) @@ -165,10 +170,10 @@ def getroute(self): wp1=waypoints[1], wp0=waypoints[0]) try: - lines = self.request.db_pgroute.execute(lines_sql) + lines = self.db_pgroute.execute(lines_sql) except Exception as e: log.exception(e) - self.request.db_pgroute.rollback() + transaction.abort() lines = [] the_line = fallback_line new_line = None @@ -237,7 +242,7 @@ def getroute_old(self): criteria + "&transport_mode=" + transport_mode + "&waypoints=" +\ waypoints timeout = 15 - f = urllib2.urlopen(url, None, timeout) + f = urllib.request.urlopen(url, None, timeout) data = f.read() headers = {"Content-Type": f.info()['Content-Type']} return Response(data, headers=headers) @@ -277,27 +282,27 @@ def exportgpxkml(self): def categories(self): if self.request.user is None: return HTTPUnauthorized() - if getattr(self.request.user, 'is_admin', False): + if getattr(self.request.user, 'is_mymaps_admin', False): unique_categ = [] categories = [] for usercateg in self.getuserscategories(): for categ in usercateg['categories']: if categ not in unique_categ: unique_categ.append(categ) - query = self.request.db_mymaps.query(Category).\ + query = self.db_mymaps.query(Category).\ filter(Category.id == categ).all() for category in query: categories.append(category.todict()) return categories - return Category.belonging_to(self.request.user, self.request.db_mymaps) + return Category.belonging_to(self.request.user, self.db_mymaps) @view_config(route_name="mymaps_getallcategories", renderer="json") def allcategories(self): - return Category.all(self.request.db_mymaps) + return Category.all(self.db_mymaps) @view_config(route_name="mymaps_getpublicmaps", renderer='json') def public_maps(self): - query = self.request.db_mymaps.query(Map).filter(Map.public == True) # noqa + query = self.db_mymaps.query(Map).filter(Map.public == True) # noqa category = None if 'category' in self.request.params and\ @@ -314,10 +319,10 @@ def public_maps(self): 'public': map.public, 'create_date': map.create_date, 'update_date': map.update_date, - 'last_feature_update': self.request.db_mymaps.query( + 'last_feature_update': self.db_mymaps.query( func.max(Feature.update_date)).filter( Feature.map_id == map.uuid).one()[0] - if self.request.db_mymaps.query( + if self.db_mymaps.query( func.max(Feature.update_date)). filter(Feature.map_id == map.uuid).one()[0] is not None else map.update_date, @@ -326,8 +331,8 @@ def public_maps(self): @view_config(route_name="mymaps_getpublicategories", renderer='json') def public_categories(self): - db_mymaps = self.request.db_mymaps - categories = self.request.db_mymaps.query(Category) + db_mymaps = self.db_mymaps + categories = self.db_mymaps.query(Category) categories = categories.filter(Category.id != 999).\ filter(Category.id.in_( db_mymaps.query(RoleCategories.category_id).filter( @@ -338,7 +343,7 @@ def public_categories(self): categories = categories.order_by("name asc") categ = [] for category in categories.all(): - map_cnt = db_mymaps.query(Map.uuid).\ + map_cnt = db_mymaps.query(Map).\ filter(Map.public == True).filter( # noqa func.coalesce(Map.category_id, 999) == category.id).\ join(Feature).group_by(Map).count() @@ -351,33 +356,37 @@ def public_categories(self): @view_config(route_name="mymaps_getmaps", renderer='json') def maps(self): - session = self.request.db_mymaps + session = self.db_mymaps user = self.request.user if user is None: return HTTPUnauthorized() + is_mymaps_admin = getattr(user, 'is_mymaps_admin', False) owner = None if 'owner' in self.request.params and\ len(self.request.params['owner']) > 0: owner = self.request.params['owner'] - if not getattr(user, 'is_admin', False): + if not is_mymaps_admin: owner = user.username query = None category = None if 'category' in self.request.params and\ - self.request.params['category'] > 0: + int(self.request.params['category']) > 0: category = int(self.request.params["category"]) - user_role = session.query(Role).get( - getattr(user, 'mymaps_role', user.role.id)) + user_role_id = getattr(user, 'mymaps_role', user.role.id) + user_role = session.query(Role).get(user_role_id) + if user_role is None: - user_role = session.query(Role).get(999) + settings = self.request.registry.settings + default_mymaps_role = int(settings['default_mymaps_role']) + user_role = session.query(Role).get(default_mymaps_role) + allowed_categories = [c.id for c in user_role.categories] if allowed_categories is not None and len(allowed_categories) > 0: if owner is None: - if getattr(user, 'is_admin', False) and getattr( - user, 'mymaps_role', user.role.id) == 1: + if is_mymaps_admin and user_role_id == 1: if category is not None: if category not in allowed_categories: return HTTPUnauthorized() @@ -395,8 +404,7 @@ def maps(self): func.lower(Map.user_login) == func.lower(user.username) )) - if getattr(user, 'is_admin', False) and getattr( - user, 'mymaps_role', user.role.id) != 1: + if is_mymaps_admin and user_role_id != 1: if category is not None: if category in allowed_categories: query = session.query(Map.uuid).filter( @@ -429,8 +437,7 @@ def maps(self): func.lower(user.username) )) # noqa else: - if getattr(user, 'is_admin', False) and getattr( - user, 'mymaps_role', user.role.id) == 1: + if is_mymaps_admin and user_role_id == 1: if category is not None: if owner != user.username and\ category not in allowed_categories: @@ -451,9 +458,7 @@ def maps(self): filter(func.lower(Map.user_login) == func.lower(user.username)) - if getattr(user, 'is_admin', False) and getattr( - user, 'mymaps_role', user.role.id) != 1\ - and owner == user.username: + if is_mymaps_admin and user_role_id != 1 and owner == user.username: if category is not None: query = session.query(Map.uuid).filter( and_(func.coalesce(Map.category_id, 999) == @@ -464,9 +469,7 @@ def maps(self): query = session.query(Map.uuid).\ filter(func.lower(Map.user_login) == func.lower(user.username)) - if getattr(user, 'is_admin', False) and getattr( - user, 'mymaps_role', user.role.id) != 1\ - and owner != user.username: + if is_mymaps_admin and user_role_id != 1 and owner != user.username: if category is not None: if category in allowed_categories: query = session.query(Map.uuid).filter( @@ -480,8 +483,7 @@ def maps(self): query = session.query(Map.uuid).filter( and_(Map.public == True, func.lower(Map.user_login) == func.lower(owner))) # noqa - if not getattr(user, 'is_admin', False) and\ - owner == user.username: + if not is_mymaps_admin and owner == user.username: if category is not None: query = session.query(Map.uuid).filter( and_(func.coalesce(Map.category_id, 999) == @@ -505,8 +507,8 @@ def maps(self): func.lower(owner)) ))))) - db_mymaps = self.request.db_mymaps - maps = query.order_by("category_id asc,title asc").all() + db_mymaps = self.db_mymaps + maps = query.order_by(text("category_id asc,title asc")).all() return [{'title': map.title, 'uuid': map.uuid, 'public': map.public, @@ -528,12 +530,12 @@ def getuserscategories(self): user = self.request.user if user is None: return HTTPUnauthorized() - user_role = self.request.db_mymaps.query(Role).get( + user_role = self.db_mymaps.query(Role).get( getattr(user, 'mymaps_role', user.role.id)) - if getattr(user, 'is_admin', False) and getattr( + if getattr(user, 'is_mymaps_admin', False) and getattr( user, 'mymaps_role', user.role.id) == 1: - users = self.request.db_mymaps.query( + users = self.db_mymaps.query( func.lower(Map.user_login).label("user_login"), func.coalesce(Map.category_id, 999).label("category_id")).\ filter(func.coalesce(Map.category_id, 999).in_( @@ -553,9 +555,9 @@ def getuserscategories(self): 'categories': user_categories[cur_user]} for cur_user in user_categories] - if getattr(user, 'is_admin', False) and getattr( + if getattr(user, 'is_mymaps_admin', False) and getattr( user, 'mymaps_role', user.role.id) != 1: - users = self.request.db_mymaps.query( + users = self.db_mymaps.query( func.lower(Map.user_login).label("user_login"), func.coalesce(Map.category_id, 999).label("category_id")).\ filter((and_(func.coalesce(Map.category_id, 999).in_( @@ -579,7 +581,7 @@ def getuserscategories(self): 'categories': user_categories[cur_user]} for cur_user in user_categories] - categies_id = self.request.db_mymaps.query( + categies_id = self.db_mymaps.query( func.coalesce(Map.category_id, 999).label("category_id")).\ filter(func.lower(Map.user_login) == func.lower(user.username)).\ group_by(func.coalesce(Map.category_id, 999)).all() # noqa @@ -590,11 +592,11 @@ def getuserscategories(self): @view_config(route_name="mymaps_features") def features(self): id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).get(id) + map = self.db_mymaps.query(Map).get(id) if map is None: return HTTPNotFound() - features = self.request.db_mymaps.query(Feature).filter( + features = self.db_mymaps.query(Feature).filter( Feature.map_id == map.uuid).order_by(Feature.display_order).all() if 'cb' in self.request.params: headers = {'Content-Type': 'text/javascript; charset=utf-8'} @@ -611,7 +613,7 @@ def features(self): @view_config(route_name="mymaps_map_info") def map_info(self): id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).filter(Map.uuid == id).first() + map = self.db_mymaps.query(Map).filter(Map.uuid == id).first() if map is None: return HTTPNotFound() @@ -640,7 +642,7 @@ def create(self): @view_config(route_name="mymaps_copy", renderer='json') def copy(self): id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).get(id) + map = self.db_mymaps.query(Map).get(id) user = self.request.user if user is None: return HTTPUnauthorized() @@ -648,15 +650,15 @@ def copy(self): if map is None: return HTTPNotFound() - self.request.db_mymaps.expunge(map) + self.db_mymaps.expunge(map) make_transient(map) map.uuid = None params = self.request.params if 'title' in params: - map.title = unicode(params.get('title')) + map.title = str(params.get('title')) if 'description' in params: - map.description = unicode(params.get('description')) + map.description = str(params.get('description')) map.public = False map.user_login = user.username map.category_id = None @@ -666,24 +668,24 @@ def copy(self): trigger_fme = False if 'public' in params: - str = unicode(params.get('public')) - if str.lower() == u'true': + public_str = str(params.get('public')) + if public_str.lower() == u'true': map.public = True trigger_fme = True map.create_date = None map.update_date = None - self.request.db_mymaps.add(map) - self.request.db_mymaps.commit() + self.db_mymaps.add(map) + self.db_mymaps.flush() if map.uuid is not None: - features = self.request.db_mymaps.query(Feature).filter( + features = self.db_mymaps.query(Feature).filter( Feature.map_id == id).all() for f in features: - self.request.db_mymaps.expunge(f) + self.db_mymaps.expunge(f) make_transient(f) f.id = None map.features.append(f) - self.request.db_mymaps.commit() + self.db_mymaps.flush() try: if trigger_fme: self.notify_at_save(map, map.user_login, map.uuid, map.title, @@ -696,7 +698,7 @@ def copy(self): @view_config(route_name="mymaps_update", renderer='json') def update(self): id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).get(id) + map = self.db_mymaps.query(Map).get(id) if map is None: return HTTPNotFound() @@ -715,15 +717,15 @@ def rate(self): if rating < 0 or rating > 5: return HTTPBadRequest('Rating value should be between 0 and 5') - map = self.request.db_mymaps.query(Map).get(id) + map = self.db_mymaps.query(Map).get(id) if map is None: return HTTPBadRequest('Map does not exist') map.rating = ((map.rating * map.rating_count + rating) / (map.rating_count + 1)) map.rating_count = map.rating_count + 1 try: - self.request.db_mymaps.add(map) - self.request.db_mymaps.commit() + self.db_mymaps.add(map) + transaction.commit() return { 'success': True, 'rating': map.rating, @@ -734,7 +736,7 @@ def rate(self): @view_config(route_name="mymaps_save_feature", renderer='json') def save_feature(self): - db_mymaps = self.request.db_mymaps + db_mymaps = self.db_mymaps try: map_id = self.request.matchdict.get("map_id") map = db_mymaps.query(Map).get(map_id) @@ -762,19 +764,19 @@ def save_feature(self): obj.id = feature_id map.features.append(obj) - db_mymaps.commit() - + db_mymaps.add(obj) + db_mymaps.flush() return {'success': True, 'id': obj.id} except Exception as e: log.exception(e) - db_mymaps.rollback() + transaction.abort() return {'success': False, 'id': None} @view_config(route_name="mymaps_save_features", renderer='json') def save_features(self): try: map_id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).get(map_id) + map = self.db_mymaps.query(Map).get(map_id) if map is None: return HTTPNotFound() @@ -799,24 +801,25 @@ def save_features(self): log.exception(e) if obj is not None: if feature_id: - cur_feature = self.request.db_mymaps.query(Feature).\ + cur_feature = self.db_mymaps.query(Feature).\ get(feature_id) - self.request.db_mymaps.delete(cur_feature) + self.db_mymaps.delete(cur_feature) obj.id = feature_id map.features.append(obj) - self.request.db_mymaps.commit() + + transaction.commit() return {'success': True} except Exception as e: log.exception(e) - self.request.db_mymaps.rollback() + transaction.abort() return {'success': False} @view_config(route_name="mymaps_save_order", renderer='json') def save_order(self): - db_mymaps = self.request.db_mymaps + db_mymaps = self.db_mymaps map_id = self.request.matchdict.get("map_id") map = db_mymaps.query(Map).get(map_id) if map is None: @@ -834,10 +837,10 @@ def save_order(self): try: cur_feature = db_mymaps.query(Feature).get(feature_id) cur_feature.display_order = display_order - db_mymaps.commit() + transaction.commit() except Exception as e: log.exception(e) - db_mymaps.rollback() + transaction.abort() return {'success': False} return {'success': True} @@ -845,19 +848,19 @@ def save_order(self): def delete_feature(self): id = self.request.matchdict.get("feature_id") - feature = self.request.db_mymaps.query(Feature).get(id) + feature = self.db_mymaps.query(Feature).get(id) if feature is None: return HTTPNotFound() - map = self.request.db_mymaps.query(Map).get(feature.map_id) + map = self.db_mymaps.query(Map).get(feature.map_id) if map is None: return HTTPNotFound() if not self.has_write_permission(self.request.user, map): return HTTPUnauthorized() - self.request.db_mymaps.delete(feature) - self.request.db_mymaps.commit() + self.db_mymaps.delete(feature) + transaction.commit() return {'success': True} @@ -866,14 +869,14 @@ def has_write_permission(self, user, map): return False if map.user_login.lower() != user.username.lower(): user = self.request.user - map_count = self.request.db_mymaps.query(MapUser).filter( + map_count = self.db_mymaps.query(MapUser).filter( MapUser.read_only == False).filter( # noqa func.lower(MapUser.user_login) == func.lower(user.username))\ .filter(MapUser.map_uuid == map.uuid).count() if map_count > 0: return True - map_count = self.request.db_mymaps.query(CategoryUser).filter( + map_count = self.db_mymaps.query(CategoryUser).filter( CategoryUser.read_only == False).filter( # noqa func.lower(CategoryUser.user_login) == func.lower(user.username))\ @@ -882,9 +885,9 @@ def has_write_permission(self, user, map): if map_count > 0: return True - if not getattr(user, 'is_admin', False): + if not getattr(user, 'is_mymaps_admin', False): return False - user_role = self.request.db_mymaps.query(Role).get(getattr( + user_role = self.db_mymaps.query(Role).get(getattr( user, 'mymaps_role', user.role.id)) if map.category is None and 999 in\ [cat.id for cat in user_role.categories]: @@ -898,22 +901,22 @@ def has_write_permission(self, user, map): def delete(self): id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).get(id) + map = self.db_mymaps.query(Map).get(id) if map is None: return HTTPNotFound() if not self.has_write_permission(self.request.user, map): return HTTPUnauthorized() # Remove the shared users - self.request.db_mymaps.query(MapUser).\ + self.db_mymaps.query(MapUser).\ filter(MapUser.map_uuid == map.uuid).delete() # remove the features associated to the map - features = self.request.db_mymaps.query(Feature).filter( + features = self.db_mymaps.query(Feature).filter( Feature.map_id == map.uuid).all() for f in features: - self.request.db_mymaps.delete(f) - self.request.db_mymaps.delete(map) - self.request.db_mymaps.commit() + self.db_mymaps.delete(f) + self.db_mymaps.delete(map) + transaction.commit() return {'success': True} @@ -921,18 +924,18 @@ def delete(self): def delete_all_features(self): id = self.request.matchdict.get("map_id") - map = self.request.db_mymaps.query(Map).get(id) + map = self.db_mymaps.query(Map).get(id) if map is None: return HTTPNotFound() if not self.has_write_permission(self.request.user, map): return HTTPUnauthorized() # remove the features associated to the map - features = self.request.db_mymaps.query(Feature).filter( + features = self.db_mymaps.query(Feature).filter( Feature.map_id == map.uuid).all() for f in features: - self.request.db_mymaps.delete(f) - self.request.db_mymaps.commit() + self.db_mymaps.delete(f) + transaction.commit() return {'success': True} @@ -957,48 +960,49 @@ def save(self, map, id=None): except ValueError: return HTTPBadRequest() if 'title' in params: - map.title = unicode(params.get('title')) + map.title = str(params.get('title')) if 'description' in params: - map.description = unicode(params.get('description')) + map.description = str(params.get('description')) if 'theme' in params: - map.theme = unicode(params.get('theme')) + map.theme = str(params.get('theme')) if 'bgLayer' in params: - map.bg_layer = unicode(params.get('bgLayer')) + map.bg_layer = str(params.get('bgLayer')) if 'bgOpacity' in params: map.bg_opacity = params.get('bgOpacity')\ if params.get('bgOpacity') != '' else 100 if 'layers' in params: - map.layers = unicode(params.get('layers')) + map.layers = str(params.get('layers')) if 'layers_indices' in params: - map.layers_indices = unicode(params.get('layers_indices')) + map.layers_indices = str(params.get('layers_indices')) if 'layers_opacity' in params: - map.layers_opacity = unicode(params.get('layers_opacity')) + map.layers_opacity = str(params.get('layers_opacity')) if 'layers_visibility' in params: - map.layers_visibility = unicode(params.get('layers_visibility')) + map.layers_visibility = str(params.get('layers_visibility')) if 'selectedNode' in params: map.selected_node =\ - unicode(params.get('selectedNode')) + str(params.get('selectedNode')) if 'category_id' in params: cat = params.get('category_id') map.category_id = None if cat == '' else cat trigger_fme = False if 'public' in params: - str = unicode(params.get('public')) - if str == u'true': + strstr = str(params.get('public')) + if strstr == u'true': if not map.public: trigger_fme = True map.public = True - elif str == u'false': + elif strstr == u'false': map.public = False if 'label' in params: - map.label = unicode(params.get('label')) + map.label = str(params.get('label')) try: - self.request.db_mymaps.add(map) - self.request.db_mymaps.commit() + self.db_mymaps.add(map) + self.db_mymaps.flush() except Exception as e: log.exception(e) return {'success': False} + try: if trigger_fme: self.notify_at_save(map, map.user_login, map.uuid, map.title, @@ -1011,12 +1015,11 @@ def save(self, map, id=None): @view_config(route_name="mymaps_map", renderer='json') def map(self): id = self.request.matchdict.get("map_id") - map = Map.get(id, self.request.db_mymaps) + map = Map.get(id, self.db_mymaps) if map is None: return HTTPNotFound() params = dict(map) - params["is_editable"] = self.has_write_permission( - self.request.user, map) + params["is_editable"] = self.has_write_permission(self.request.user, map) if 'cb' in self.request.params: headers = {'Content-Type': 'text/javascript; charset=utf-8'} @@ -1030,9 +1033,9 @@ def map(self): @view_config(route_name="mymaps_get_image") def image(self): filename = self.request.matchdict.get("filename") - if self.request.db_mymaps.query(Images).\ + if self.db_mymaps.query(Images).\ filter(Images.name == filename).count() > 0: - cur_file = self.request.db_mymaps.query(Images).\ + cur_file = self.db_mymaps.query(Images).\ filter(Images.name == filename).one() the_image = cur_file.image lower_file_name = cur_file.name.lower() @@ -1108,15 +1111,15 @@ def upload_image(self): cur_file.name = image_name cur_file.image = f_image.read() cur_file.login_owner = user - self.request.db_mymaps.add(cur_file) - self.request.db_mymaps.commit() + self.db_mymaps.add(cur_file) + transaction.commit() cur_file = Images() cur_file.name = thumbnail_name cur_file.image = f_thumbnail.read() cur_file.login_owner = user - self.request.db_mymaps.add(cur_file) - self.request.db_mymaps.commit() + self.db_mymaps.add(cur_file) + transaction.commit() except: return {'success': False, 'msg': 'Bad image'} @@ -1131,6 +1134,7 @@ def upload_image(self): 'image': '/mymaps/images/' + image_name, 'thumbnail': '/mymaps/images/' + thumbnail_name} + @view_config(route_name="generate_symbol_file") def generate_symbol_file(self): @@ -1142,7 +1146,7 @@ def generate_symbol_file(self): if not os.path.exists(dir): os.mkdir(dir) symbolsmap = "" - for symbol in self.request.db_mymaps.query(Symbols).all(): + for symbol in self.db_mymaps.query(Symbols).all(): _, ext = os.path.splitext(symbol.symbol_name) symbolsmap = symbolsmap + """ SYMBOL @@ -1160,7 +1164,8 @@ def generate_symbol_file(self): script_file.write('sh %s %s \n' % (script_ms, dir + "/" + "/symbols.map")) - for symbol in self.request.db_mymaps.query(Symbols).\ + + for symbol in self.db_mymaps.query(Symbols).\ filter(Symbols.synchronized == False).all(): # noqa _, ext = os.path.splitext(symbol.symbol_name) @@ -1171,7 +1176,7 @@ def generate_symbol_file(self): the_file.write(symbol.symbol) the_file.close() symbol.synchronized = True - self.request.db_mymaps.commit() + transaction.commit() script_file.write('sh %s %s remove \n' % (script_ms, dir + "/" + the_name)) script_file.close() @@ -1188,7 +1193,7 @@ def get_symbol(self): scale = 100 try: - symbol = self.request.db_mymaps.query(Symbols).\ + symbol = self.db_mymaps.query(Symbols).\ filter(Symbols.id == id).one() try: headers = {'Content-Type': 'application/octet-stream', @@ -1233,7 +1238,7 @@ def get_symbol(self): img = Image.new('RGBA', (40, 40)) ImageDraw.Draw(img) - buf = StringIO() + buf = BytesIO() img.save(buf, 'GIF', transparency=0) content = buf.getvalue() buf.close() @@ -1247,7 +1252,7 @@ def get_symbols(self): try: symbol_type = self.request.params.get('symboltype', 'pixmap') if symbol_type == 'public': - for symbol in self.request.db_mymaps.query(Symbols).\ + for symbol in self.db_mymaps.query(Symbols).\ filter(Symbols.is_public == True).all(): # noqa results.append({'id': symbol.id, 'name': symbol.symbol_name, @@ -1259,7 +1264,7 @@ def get_symbols(self): user = self.request.user if user is None: return HTTPUnauthorized() - for symbol in self.request.db_mymaps.query(Symbols).\ + for symbol in self.db_mymaps.query(Symbols).\ filter(func.lower(Symbols.login_owner) == func.lower(user.username)).all(): results.append({'id': symbol.id, @@ -1340,8 +1345,8 @@ def upload_symbol(self): cur_file.login_owner = username cur_file.is_public = False - self.request.db_mymaps.add(cur_file) - self.request.db_mymaps.commit() + self.db_mymaps.add(cur_file) + transaction.commit() if os.path.exists(temp_file_path): os.remove(temp_file_path) @@ -1352,7 +1357,7 @@ def upload_symbol(self): self.generate_symbol_file() except Exception as e: log.exception(e) - self.request.db_mymaps.rollback() + transaction.abort() return {'success': 'true', 'description': 'file added', @@ -1403,33 +1408,33 @@ def comment(self): def strip_accents(self, string): import unicodedata - return unicodedata.normalize('NFKD', unicode(string)).\ + return unicodedata.normalize('NFKD', str(string)).\ encode('ASCII', 'ignore').replace(' ', '_') def get_user_info(self, user): - connector = get_ldap_connector(self.request) - cm = connector.manager - with cm.connection() as conn: - dn_list = conn.search_s('ou=portail,dc=act,dc=lu', - ldap.SCOPE_SUBTREE, '(login=%s)' % user) - if len(dn_list) != 1: - return HTTPInternalServerError() - - dn = dn_list[0][0] - attributes = conn.search_s(dn, - ldap.SCOPE_BASE, - '(objectClass=*)', - ['mail']) - if len(attributes) == 0 or len(attributes[0]) != 2: - return HTTPInternalServerError() - attributes = attributes[0][1] - if 'mail' not in attributes or len(attributes['mail']) == 0: - return HTTPNotFound() - mail_address = attributes['mail'][0] - if not mail_address: - return HTTPNotFound() - - return (user, mail_address) + connector = get_ldap_connector(self.request) + cm = connector.manager + with cm.connection() as conn: + dn_list = conn.search_s('ou=portail,dc=act,dc=lu', + ldap.SUBTREE, '(login=%s)' % user) + if len(dn_list) != 1: + return HTTPInternalServerError() + + dn = dn_list[0][0] + attributes = conn.search_s(dn, + ldap.SCOPE_BASE, + '(objectClass=*)', + ['mail']) + if len(attributes) == 0 or len(attributes[0]) != 2: + return HTTPInternalServerError() + attributes = attributes[0][1] + if 'mail' not in attributes or len(attributes['mail']) == 0: + return HTTPNotFound() + mail_address = attributes['mail'][0] + if not mail_address: + return HTTPNotFound() + + return (user, mail_address) def notify_at_save(self, map, username, id, name, category): @@ -1450,6 +1455,6 @@ def notify_at_save(self, map, username, id, name, category): data = {'email_to': admin_email, 'subscriber_content': email_content, 'email_cc': email_cc} - req = urllib2.Request(url) + req = urllib.request.Request(url) req.add_header('Content-Type', 'application/json') - urllib2.urlopen(req, json.dumps(data)) + urllib.request.urlopen(req, json.dumps(data)) diff --git a/geoportal/geoportailv3_geoportal/views/pag.py b/geoportal/geoportailv3_geoportal/views/pag.py index 7f06ee1db..40bb3e229 100644 --- a/geoportal/geoportailv3_geoportal/views/pag.py +++ b/geoportal/geoportailv3_geoportal/views/pag.py @@ -7,12 +7,12 @@ import shutil import os import smtplib -import urllib2 +import urllib.request from email.mime.text import MIMEText import time import sys -from geoportailv3.portail import PortailSession -from geoportailv3.portail import PagDownload +from geoportailv3_geoportal.portail import PagDownload +from c2cgeoportal_commons.models import DBSession _ = TranslationStringFactory("geoportailv3-server") log = logging.getLogger(__name__) @@ -37,7 +37,7 @@ def __download(self, num): num, self.config["pag"]["fme_token"]) try: - f = urllib2.urlopen(url, None, 1800) + f = urllib.request.urlopen(url, None, 1800) data = f self.filename = '/tmp/%s_%s.pdf' % (num, str(int(time.time()))) with open(self.filename, 'wb') as fp: @@ -89,11 +89,10 @@ def __log_download_stats(self, objectids, download_link): pag_download.objectids = objectids pag_download.download_link = download_link try: - PortailSession.add(pag_download) - PortailSession.commit() + DBSession.add(pag_download) except Exception as e: log.exception(e) - PortailSession.rollback() + transaction.abort() @view_config(route_name='pag_files') def pag_files(self, ): @@ -104,9 +103,9 @@ def pag_files(self, ): folder = "PartieGraphique" url = "%s/%s/%s" % (self.config["pag"]["file_server"], folder, _file) try: - req = urllib2.Request(url) + req = urllib.request.Request(url) req.add_header('Cache-Control', 'max-age=0') - f = urllib2.urlopen(req, None, 15) + f = urllib.request.urlopen(req, None, 15) data = f.read() except: log.error(sys.exc_info()[0]) diff --git a/geoportal/geoportailv3_geoportal/views/pds.py b/geoportal/geoportailv3_geoportal/views/pds.py index 6d89c3dde..e1bd85d51 100644 --- a/geoportal/geoportailv3_geoportal/views/pds.py +++ b/geoportal/geoportailv3_geoportal/views/pds.py @@ -6,7 +6,7 @@ import shutil import os import smtplib -import urllib2 +import urllib.request from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText @@ -32,7 +32,7 @@ def __download(self, num): num ) try: - f = urllib2.urlopen(url, None, 1800) + f = urllib.request.urlopen(url, None, 1800) data = f filename = '/tmp/%s_%s.pdf' % (num, str(int(time.time()))) with open(filename, 'wb') as fp: @@ -69,7 +69,7 @@ def __send_mail(self, email, files): msg['BCC'] = bcc mails.append(bcc) else: - print "no bcc_address in" + str(self.config["pds"]) + print("no bcc_address in" + str(self.config["pds"])) msg['Subject'] = 'Attestation PDS ' msg['From'] = me msg['To'] = you diff --git a/geoportal/geoportailv3_geoportal/views/ping.py b/geoportal/geoportailv3_geoportal/views/ping.py new file mode 100644 index 000000000..8398a5fd8 --- /dev/null +++ b/geoportal/geoportailv3_geoportal/views/ping.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +from pyramid.response import Response +from pyramid.view import view_config +from c2cgeoportal_geoportal.lib.caching import set_common_headers, NO_CACHE + +class Ping(object): + + def __init__(self, request): + self.request = request + + @view_config(route_name="ping") + def ping(self): + response = self.request.response + response.text = "pong" + + return set_common_headers( + self.request, "ping", NO_CACHE + ) diff --git a/geoportal/geoportailv3_geoportal/views/profile.py b/geoportal/geoportailv3_geoportal/views/profile.py index a93fed989..e2c3b3147 100644 --- a/geoportal/geoportailv3_geoportal/views/profile.py +++ b/geoportal/geoportailv3_geoportal/views/profile.py @@ -1,12 +1,12 @@ -# -*- coding: utf-8 -*- -from c2cgeoportal.lib.caching import set_common_headers, NO_CACHE -from pyramid.httpexceptions import HTTPBadRequest +# -*- coding: utf-8 -*- +from c2cgeoportal_geoportal.lib.caching import set_common_headers, NO_CACHE +from c2cgeoportal_geoportal.views.raster import Raster +from pyramid.httpexceptions import HTTPBadRequest from pyramid.view import view_config from pyramid.response import Response from pyramid.i18n import TranslationStringFactory -from c2cgeoportal.views.raster import Raster -from shapely.ops import linemerge - +from shapely.ops import linemerge + import geojson import math from decimal import Decimal @@ -93,22 +93,22 @@ def _create_geom(self, request_geom): geom = geojson.loads( request_geom, object_hook=geojson.GeoJSON.to_instance) - if geom.type == "MultiLineString": - # In case of MultiLineString try to merge - # the different components - lines_to_merge = [] - for line in geom.coordinates: - lines_to_merge.append(line) - merged_lines = linemerge(lines_to_merge) - if merged_lines.geom_type == "MultiLineString": - for line in merged_lines.geoms: - lines.append(geojson.loads( - geojson.dumps(line), - object_hook=geojson.GeoJSON.to_instance)) - else: - lines.append(geojson.loads( - geojson.dumps(merged_lines), - object_hook=geojson.GeoJSON.to_instance)) + if geom.type == "MultiLineString": + # In case of MultiLineString try to merge + # the different components + lines_to_merge = [] + for line in geom.coordinates: + lines_to_merge.append(line) + merged_lines = linemerge(lines_to_merge) + if merged_lines.geom_type == "MultiLineString": + for line in merged_lines.geoms: + lines.append(geojson.loads( + geojson.dumps(line), + object_hook=geojson.GeoJSON.to_instance)) + else: + lines.append(geojson.loads( + geojson.dumps(merged_lines), + object_hook=geojson.GeoJSON.to_instance)) if geom.type == "LineString": lines.append(geom) @@ -123,7 +123,7 @@ def _create_geom(self, request_geom): # C'est celle qui a son premier ou dernier point # le plus loin de tous les autres points. for i in range(len(lines)): - shortest_distance = None + shortest_distance = 999999999 is_reverse_loc = False for j in range(len(lines)): if i == j: @@ -132,8 +132,7 @@ def _create_geom(self, request_geom): lines[j].coordinates[0]) dist1b = self._dist(lines[i].coordinates[0], lines[j].coordinates[-1]) - if shortest_distance is None \ - or dist1a < shortest_distance or dist1b: + if dist1a < shortest_distance or dist1b: shortest_distance = dist1a is_reverse_loc = False if dist1b < shortest_distance: @@ -150,8 +149,7 @@ def _create_geom(self, request_geom): lines[j].coordinates[0]) dist1b = self._dist(lines[i].coordinates[-1], lines[j].coordinates[-1]) - if shortest_distance is None \ - or dist1a < shortest_distance or dist1b: + if dist1a < shortest_distance or dist1b: shortest_distance = dist1a is_reverse_loc = True if dist1b < shortest_distance: @@ -172,7 +170,7 @@ def _create_geom(self, request_geom): list(ordered_lines[-1].coordinates)[::-1] while (len(lines) > 0): - shortest_dist = None + shortest_dist = 999999999 line_index = None i = 0 for line in lines: @@ -184,7 +182,7 @@ def _create_geom(self, request_geom): if d1a >= d1b: line.coordinates = list(line.coordinates)[::-1] d1 = d1b - if shortest_dist is None or d1 <= shortest_dist: + if d1 <= shortest_dist: shortest_dist = d1 line_index = i i = i + 1 @@ -198,11 +196,11 @@ def _compute_points(self): geoms = self._create_geom(self.request.params["geom"]) points = [] rasters = self.rasters - nb_points = int(self.request.params["nbPoints"]) / len(geoms) + nb_points = int(self.request.params["nbPoints"]) / len(geoms) dist = 0 for geom in geoms: - coords = self._create_points(geom.coordinates, nb_points) - prev_coord = None + coords = self._create_points(geom.coordinates, nb_points) + prev_coord = None for coord in coords: if prev_coord is not None: @@ -213,7 +211,7 @@ def _compute_points(self): for ref in rasters.keys(): value = self._get_raster_value( self.rasters[ref], - ref, coord[0], coord[1]) + ref, coord[0], coord[1]) if value is not None and value != 0: values[ref] = value @@ -228,7 +226,7 @@ def _compute_points(self): "x": coord[0], "y": coord[1] }) - prev_coord = coord + prev_coord = coord return rasters.keys(), points diff --git a/geoportal/geoportailv3_geoportal/views/qr.py b/geoportal/geoportailv3_geoportal/views/qr.py index 230f727a0..63e5aea1b 100644 --- a/geoportal/geoportailv3_geoportal/views/qr.py +++ b/geoportal/geoportailv3_geoportal/views/qr.py @@ -1,9 +1,9 @@ from pyramid.view import view_config from pyramid.response import Response from pyramid.httpexceptions import HTTPBadRequest, HTTPNotAcceptable +from io import BytesIO import logging import qrcode -import StringIO import re log = logging.getLogger(__name__) @@ -35,7 +35,7 @@ def getqrcode(self): qr.add_data(url) qr.make(fit=True) im = qr.make_image() - output = StringIO.StringIO() + output = BytesIO() im.save(output) headers = {"Content-Type": 'image/png'} return Response(output.getvalue(), headers=headers) diff --git a/geoportal/geoportailv3_geoportal/views/routing.py b/geoportal/geoportailv3_geoportal/views/routing.py index dd1b7597a..834c8c416 100644 --- a/geoportal/geoportailv3_geoportal/views/routing.py +++ b/geoportal/geoportailv3_geoportal/views/routing.py @@ -3,14 +3,15 @@ # reviewed by koje # reviewed by mire -from geoportailv3.mapquestrouter import MapquestRouter -from geoportailv3.graphhopperrouter import GraphhopperRouter +from geoportailv3_geoportal.routing.mapquestrouter import MapquestRouter +from geoportailv3_geoportal.routing.graphhopperrouter import GraphhopperRouter from pyramid.view import view_config -from urllib2 import HTTPError +from urllib.error import HTTPError from pyramid.httpexceptions import HTTPBadRequest -from geoportailv3.portail import PortailSession -from geoportailv3.portail import RoutingStats +from geoportailv3_geoportal.portail import RoutingStats +from c2cgeoportal_commons.models import DBSession +import transaction import logging log = logging.getLogger(__name__) @@ -75,14 +76,14 @@ def get_route(self): routing_stats = RoutingStats() routing_stats.transport_mode = transport_mode routing_stats.transport_criteria = criteria - PortailSession.add(routing_stats) - PortailSession.commit() + DBSession.add(routing_stats) + transaction.commit() except Exception as e: log.exception(e) - PortailSession.rollback() + transaction.abort() if routing_success: - json = { + json_response = { "type": "FeatureCollection", "features": [ {'type': "Feature", @@ -94,7 +95,7 @@ def get_route(self): 'attribution': r.attribution}, 'geometry': r.geom}]} else: - json = {'success': routing_success, + json_response = {'success': routing_success, 'geometry': None, 'desc': [], 'dist': 0, @@ -102,7 +103,7 @@ def get_route(self): 'errorMessages': r.errorMessages, 'attribution': r.attribution} - return json + return json_response def __setup_router( self, coords, lang, transport_mode, criteria, diff --git a/geoportal/geoportailv3_geoportal/views/wms.py b/geoportal/geoportailv3_geoportal/views/wms.py index a780b480c..39761a9f8 100644 --- a/geoportal/geoportailv3_geoportal/views/wms.py +++ b/geoportal/geoportailv3_geoportal/views/wms.py @@ -1,14 +1,14 @@ from ipaddr import IPv4Network from pyramid.view import view_config -from geoportailv3.models import LuxLayerInternalWMS, LuxPredefinedWms -from c2cgeoportal.models import DBSession, RestrictionArea, Role, Layer +from geoportailv3_geoportal.models import LuxLayerInternalWMS, LuxPredefinedWms +from c2cgeoportal_commons.models import DBSession +from c2cgeoportal_commons.models.main import RestrictionArea, Role, Layer from pyramid.response import Response from pyramid.httpexceptions import HTTPBadGateway, HTTPBadRequest from pyramid.httpexceptions import HTTPNotFound, HTTPUnauthorized -from urlparse import urlparse import logging -import urllib -import urllib2 +import urllib.request +import urllib.parse import socket import base64 @@ -40,7 +40,7 @@ def _check_ip(self, client_ip): return False def _check_ip_for_httpsproxy(self, url): - parsedurl = urlparse(url) + parsedurl = urllib.parse.urlparse(url) hostname = parsedurl.netloc.split(":") remote_ip = IPv4Network(socket.gethostbyname(hostname[0])).ip config = self.request.registry.settings @@ -124,12 +124,12 @@ def internal_proxy_wms(self): if param.lower() != 'layers': param_wms = param_wms + param + "=" + \ - urllib2.quote( + urllib.parse.quote( self.request.params.get(param, '').encode('utf-8') ) + "&" else: param_wms = param_wms + param + "=" + \ - urllib2.quote(internal_wms.layers.encode('utf-8')) + "&" + urllib.parse.quote(internal_wms.layers.encode('utf-8')) + "&" # TODO : Specific action when user is logged in ? # Forward authorization to the remote host @@ -153,16 +153,16 @@ def internal_proxy_wms(self): url = remote_host + separator + param_wms[:-1] timeout = 15 - url_request = urllib2.Request(url) + url_request = urllib.request.Request(url) if base64user is not None: url_request.add_header("Authorization", "Basic %s" % base64user) try: - f = urllib2.urlopen(url_request, None, timeout) + f = urllib.request.urlopen(url_request, None, timeout) data = f.read() except: try: # Retry to get the result - f = urllib2.urlopen(url_request, None, timeout) + f = urllib.request.urlopen(url_request, None, timeout) data = f.read() except Exception as e: log.exception(e) @@ -197,7 +197,7 @@ def proxy(self): for key in self.request.params.keys(): if not (key == "url"): params_dict[key] = self.request.params.get(key) - params = urllib.urlencode(params_dict) + params = urllib.parse.urlencode(params_dict) separator = "?" if "?" in url: separator = "&" @@ -205,12 +205,12 @@ def proxy(self): timeout = 15 try: - f = urllib2.urlopen(url, None, timeout) + f = urllib.request.urlopen(url, None, timeout) data = f.read() except: try: # Retry to get the result - f = urllib2.urlopen(url, None, timeout) + f = urllib.request.urlopen(url, None, timeout) data = f.read() except Exception as e: log.exception(e) diff --git a/geoportal/package.json b/geoportal/package.json index 590bbeeaa..8a217b370 100644 --- a/geoportal/package.json +++ b/geoportal/package.json @@ -1,64 +1,104 @@ { - "name": "geoportailv3", - "version": "0.0.1", - "description": "Pyramid Closure Project", + "name": "lux", + "version": "2.3.0", + "description": "Luxembourg webmap", "scripts": {}, - "license": "BSD", - "dependencies": { - "acorn": "^5.0.3", - "async": "^2.3.0", - "fuse.js": "git+https://github.com/petzlux/Fuse.git#master", - "send": "^0.15.0" + "repository": { + "type": "git", + "url": "git://github.com/Geoportail-Luxembourg/geoportailv3.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/Geoportail-Luxembourg/geoportailv3/issues" }, "devDependencies": { - "@camptocamp/cesium": "1.43.1", - "@camptocamp/closure-util": "https://api.github.com/repos/camptocamp/closure-util/tarball/1cd7d30", - "angular": "1.6.6", - "angular-animate": "1.6.6", - "angular-dynamic-locale": "0.1.32", + "@camptocamp/babel-plugin-angularjs-annotate": "0.8.2", + "@camptocamp/cesium": "1.45.0", + "angular": "1.6.10", + "angular-animate": "1.6.10", + "angular-dynamic-locale": "0.1.36", "angular-float-thead": "0.1.2", - "angular-gettext": "2.3.10", - "angular-gettext-tools": "2.3.6", - "angular-sanitize": "1.6.6", - "angular-touch": "1.6.6", + "angular-gettext": "2.3.11", + "angular-gettext-tools": "2.3.9", + "angular-jsdoc": "1.5.0", + "angular-mocks": "1.6.10", + "angular-sanitize": "1.6.10", + "angular-touch": "1.6.10", "angular-ui-date": "1.1.1", "angular-ui-slider": "0.4.0", - "babel-polyfill": "6.26.0", + "async": "2.6.1", + "babel-core": "6.26.0", + "babel-loader": "7.1.4", + "babel-preset-env": "1.6.1", "bootstrap": "3.3.7", - "corejs-typeahead": "1.1.1", - "d3": "4.7.4", - "eslint": "3.18.0", - "eslint-config-openlayers": "7.0.0", - "eslint-plugin-googshift": "git+https://github.com/gberaudo/eslint-plugin-googshift#master", - "floatthead": "1.4.2", + "commander": "2.15.1", + "console-control-strings": "1.1.0", + "copy-webpack-plugin": "4.5.1", + "corejs-typeahead": "1.2.1", + "coveralls": "3.0.1", + "css-loader": "0.28.11", + "d3-array": "1.2.1", + "d3-axis": "1.0.8", + "d3-scale": "1.0.7", + "d3-selection": "1.3.0", + "d3-shape": "1.2.0", + "d3-transition": "1.1.1", + "d3-zoom": "1.7.1", + "eslint": "4.19.1", + "eslint-config-openlayers": "9.1.0", + "eslint-plugin-googshift": "0.9.3", + "expose-loader": "0.7.5", + "extract-text-webpack-plugin": "4.0.0-alpha.0", + "file-loader": "1.1.11", + "file-saver": "1.3.8", + "floatthead": "2.1.2", "font-awesome": "4.7.0", - "fs-extra": "^4.0.2", - "fuse": "git+https://github.com/petzlux/Fuse#master", - "gaze": "1.1.2", - "googshift": "^0.9.10", - "jquery": "3.2.1", + "fs-extra": "6.0.1", + "fuse.js": "1.3.1", + "hard-source-webpack-plugin": "0.6.12", + "html-loader": "0.5.5", + "html-webpack-plugin": "3.2.0", + "istanbul-instrumenter-loader": "3.0.1", + "jasmine-core": "2.99.0", + "jquery": "3.3.1", + "jquery-datetimepicker": "2.5.19", + "jquery-mousewheel": "3.1.13", + "jquery-ui": "1.12.1", "jquery-ui-touch-punch": "0.2.3", - "js-autocomplete": "^1.0.3", - "jsdoc": "^3.4.3", - "jsdom": "^9.9.1", - "jszip": "3.1.3", - "less": "2.7.1", + "jsdoc": "3.5.5", + "jsdom": "11.10.0", + "jsts": "1.6.0", + "karma": "2.0.2", + "karma-chrome-launcher": "2.2.0", + "karma-coverage": "1.1.2", + "karma-coverage-istanbul-reporter": "2.0.1", + "karma-jasmine": "1.1.1", + "karma-sourcemap-loader": "0.3.7", + "karma-webpack": "3.0.0", + "less": "2.7.2", + "less-loader": "4.1.0", "less-plugin-autoprefix": "1.5.1", "less-plugin-clean-css": "1.5.1", - "localforage": "1.7.1", - "ngeo": "https://api.github.com/repos/camptocamp/ngeo/tarball/898a436", - "nomnom": "1.8.1", - "ol-cesium": "https://api.github.com/repos/openlayers/ol-cesium/tarball/9bc93a85a2cf25fbec11905597f3c5cbc18acea5", - "olcs": "0.0.2", - "openlayers": "https://api.github.com/repos/openlayers/openlayers/tarball/72ca7b2", - "phantomjs": "~1.9.7-5", - "phantomjs-prebuilt": "2.1.12", + "localforage": "1.7.3", + "ls": "0.2.1", + "moment": "2.22.1", + "ngeo": "https://api.github.com/repos/camptocamp/ngeo/tarball/2580af7e", + "ol-cesium": "2.0.0", + "openlayers": "https://api.github.com/repos/openlayers/openlayers/tarball/f284b95cb897b3ce1b49b985b58ebe1ca76be1fe", + "phantomjs-polyfill-string-includes": "1.0.0", + "phantomjs-prebuilt": "2.1.16", "proj4": "2.4.4", - "promise-polyfill": "5.2.1", - "temp": "0.8.3", - "typeahead.js": "~0.11.1", - "url-polyfill": "1.0.11", - "walk": "2.3.9", - "whatwg-fetch": "1.0.0" - } + "raven-js": "3.24.2", + "svg2ttf": "4.1.0", + "ttf2eot": "2.0.0", + "ttf2woff": "2.0.1", + "uglify-js": "3.3.27", + "uglifyjs-webpack-plugin": "1.2.5", + "url-loader": "1.0.1", + "webpack": "4.8.2", + "webpack-cli": "2.1.2", + "webpack-dev-server": "3.1.4", + "webpack-merge": "4.1.2" + }, + "dependencies": {} } diff --git a/ldap/etc/ldap/prepopulate/20-users.ldif b/ldap/etc/ldap/prepopulate/20-users.ldif index b6ba79711..56edd8831 100644 --- a/ldap/etc/ldap/prepopulate/20-users.ldif +++ b/ldap/etc/ldap/prepopulate/20-users.ldif @@ -19,7 +19,7 @@ mail: cc2c@example.com o: 2 postalCode: 1470 rca: FALSE -roleMymaps: 0 +roleMymaps: 645 roleOGC: 0 roleTheme: 645 sn: test user