Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Live attribute view on map

Christian Bauer1d215c661f54
diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.java b/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.java
index 8ce5c56dc..e4e91f708 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.java
@@ -25,9 +25,9 @@ import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
-import com.google.gwt.user.client.ui.PopupPanel;
import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.widget.AbstractAppPanel;
+import org.openremote.manager.client.widget.PopupPanel;
import javax.inject.Inject;
diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.ui.xml
index 277c473b0..247007441 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/app/dialog/DialogImpl.ui.xml
@@ -31,8 +31,8 @@
}
</ui:style>
- <g:PopupPanel glassEnabled="false" addStyleNames="{style.popup} {widgetStyle.PopupPanel}">
- <g:FlowPanel ui:field="mainPanel" styleName="flex layout vertical">
+ <w:PopupPanel glassEnabled="false" addStyleNames="{style.popup} {widgetStyle.PopupPanel}">
+ <g:FlowPanel ui:field="mainPanel" styleName="layout vertical">
<g:FlowPanel styleName="layout horizontal {style.header} {widgetStyle.PopupPanelHeader}">
<g:Label ui:field="headerLabel"/>
</g:FlowPanel>
@@ -45,6 +45,6 @@
addStyleNames="{style.footer} {widgetStyle.PopupPanelFooter}">
</g:FlowPanel>
</g:FlowPanel>
- </g:PopupPanel>
+ </w:PopupPanel>
</ui:UiBinder>
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java
index 9f2a18a3b..7ad2d5398 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java
@@ -24,7 +24,7 @@ import elemental.json.JsonObject;
import org.openremote.manager.client.assets.attributes.AttributesEditor;
import org.openremote.manager.client.assets.browser.BrowserTreeNode;
import org.openremote.manager.client.widget.FormView;
-import org.openremote.manager.shared.map.GeoJSON;
+import org.openremote.model.geo.GeoJSON;
import org.openremote.model.asset.AssetType;
import java.util.Date;
@@ -33,6 +33,8 @@ public interface AssetEdit extends FormView, IsWidget {
interface Presenter {
+ void onMapReady();
+
void onParentSelection(BrowserTreeNode treeNode);
void centerMap();
@@ -72,7 +74,7 @@ public interface AssetEdit extends FormView, IsWidget {
void hideMapPopup();
- void showFeaturesSelection(GeoJSON mapFeatures);
+ void showDroppedPin(GeoJSON geoFeature);
void flyTo(double[] coordinates);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
index b86c95ad0..858851000 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
@@ -29,7 +29,6 @@ import org.openremote.manager.client.assets.tenant.AssetsTenantPlace;
import org.openremote.manager.client.event.ShowFailureEvent;
import org.openremote.manager.client.event.ShowSuccessEvent;
import org.openremote.manager.client.interop.elemental.JsonObjectMapper;
-import org.openremote.manager.client.map.MapView;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.map.MapResource;
import org.openremote.manager.shared.security.Tenant;
@@ -121,17 +120,8 @@ public class AssetEditActivity
view::initialiseMap,
ex -> handleRequestException(ex, environment)
);
- }
-
- asset = null;
- if (assetId != null) {
- assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
- this.asset = loadedAsset;
- assetBrowserPresenter.selectAsset(asset);
- startEditAsset();
- });
} else {
- startCreateAsset();
+ onMapReady();
}
}
@@ -145,6 +135,21 @@ public class AssetEditActivity
view.setPresenter(null);
}
+
+ @Override
+ public void onMapReady() {
+ asset = null;
+ if (assetId != null) {
+ assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
+ this.asset = loadedAsset;
+ assetBrowserPresenter.selectAsset(asset);
+ startEditAsset();
+ });
+ } else {
+ startCreateAsset();
+ }
+ }
+
@Override
public void onParentSelection(BrowserTreeNode treeNode) {
if (treeNode instanceof TenantTreeNode) {
@@ -294,7 +299,7 @@ public class AssetEditActivity
view.setName(asset.getName());
view.setCreatedOn(asset.getCreatedOn());
view.setLocation(asset.getCoordinates());
- view.showFeaturesSelection(MapView.getFeature(asset));
+ view.showDroppedPin(asset.getGeoFeature(20));
view.flyTo(asset.getCoordinates());
view.enableCreate(assetId == null);
view.enableUpdate(assetId != null);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java
index b53b87bd4..707f8b53a 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java
@@ -39,7 +39,7 @@ import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.widget.*;
import org.openremote.manager.client.widget.Hyperlink;
import org.openremote.manager.client.widget.PushButton;
-import org.openremote.manager.shared.map.GeoJSON;
+import org.openremote.model.geo.GeoJSON;
import org.openremote.model.Constants;
import org.openremote.model.asset.AssetType;
@@ -91,6 +91,9 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
@UiField
Hyperlink viewAssetLink;
+ @UiField
+ Hyperlink createAssetLink;
+
/* ############################################################################ */
@UiField
@@ -211,6 +214,8 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
sidebarContainer.clear();
headlineLabel.setText(null);
viewAssetLink.setVisible(false);
+ viewAssetLink.setTargetHistoryToken("");
+ createAssetLink.setVisible(false);
setFormBusy(true);
nameGroup.setError(false);
nameInput.setReadOnly(false);
@@ -225,7 +230,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
typeListBox.setEnabled(true);
typeInput.setVisible(false);
customTypeInfoLabel.setVisible(false);
- showFeaturesSelection(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
hideMapPopup();
setOpaque(false);
attributesEditorContainer.clear();
@@ -245,7 +250,11 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
mapWidget.setVisible(!busy);
if (!busy)
mapWidget.resize();
- viewAssetLink.setVisible(viewAssetLink.getTargetHistoryToken() != null && !busy);
+ viewAssetLink.setVisible(
+ viewAssetLink.getTargetHistoryToken() != null
+ && viewAssetLink.getTargetHistoryToken().length() > 0
+ && !busy
+ );
}
@Override
@@ -294,10 +303,12 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
@Override
public void initialiseMap(JsonObject mapOptions) {
mapWidget.initialise(mapOptions, () -> {
- });
- mapWidget.addNavigationControl();
- mapWidget.setClickListener((lng, lat) -> {
- presenter.onMapClicked(lng, lat);
+ mapWidget.addNavigationControl();
+ mapWidget.setClickListener((lng, lat) -> {
+ presenter.onMapClicked(lng, lat);
+ });
+ if (presenter != null)
+ presenter.onMapReady();
});
}
@@ -308,22 +319,30 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
@Override
public void showMapPopup(double lng, double lat, String text) {
- mapWidget.showPopup(lng, lat, text);
+ if (mapWidget.isMapReady()) {
+ mapWidget.showPopup(lng, lat, text);
+ }
}
@Override
public void hideMapPopup() {
- mapWidget.hidePopup();
+ if (mapWidget.isMapReady()) {
+ mapWidget.hidePopup();
+ }
}
@Override
- public void showFeaturesSelection(GeoJSON mapFeatures) {
- mapWidget.showFeatures(MapWidget.FEATURES_SOURCE_SELECTION, mapFeatures);
+ public void showDroppedPin(GeoJSON geoFeature) {
+ if (mapWidget.isMapReady()) {
+ mapWidget.showFeature(MapWidget.FEATURE_SOURCE_DROPPED_PIN, geoFeature);
+ }
}
@Override
public void flyTo(double[] coordinates) {
- mapWidget.flyTo(coordinates);
+ if (mapWidget.isMapReady()) {
+ mapWidget.flyTo(coordinates);
+ }
}
@UiHandler("centerMapButton")
@@ -402,6 +421,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
public void enableCreate(boolean enable) {
createButton.setVisible(enable);
headlineLabel.setText(enable ? managerMessages.createAsset() : managerMessages.editAsset());
+ createAssetLink.setVisible(!enable);
}
@Override
@@ -409,6 +429,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
viewAssetLink.setVisible(enable);
updateButton.setVisible(enable);
headlineLabel.setText(enable ? managerMessages.editAsset() : managerMessages.createAsset());
+ createAssetLink.setVisible(enable);
}
@Override
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml
index 67de141cb..7a40eb2a5 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml
@@ -72,8 +72,10 @@
text="{managerMessages.viewAsset}"/>
<w:Hyperlink
+ ui:field="createAssetLink"
addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"
icon="plus-square"
+ visible="false"
targetHistoryToken="assetEdit:"
text="{managerMessages.createAsset}"/>
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java
index 173b98c8c..fa5659ac8 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java
@@ -23,7 +23,7 @@ import com.google.gwt.user.client.ui.IsWidget;
import elemental.json.JsonObject;
import org.openremote.manager.client.assets.attributes.AttributesBrowser;
import org.openremote.manager.client.assets.browser.BrowserTreeNode;
-import org.openremote.manager.shared.map.GeoJSON;
+import org.openremote.model.geo.GeoJSON;
import java.util.Date;
@@ -31,6 +31,8 @@ public interface AssetView extends IsWidget {
interface Presenter {
+ void onMapReady();
+
void centerMap();
}
@@ -52,7 +54,7 @@ public interface AssetView extends IsWidget {
void setLocation(double[] coordinates);
- void showFeaturesSelection(GeoJSON mapFeatures);
+ void showDroppedPin(GeoJSON geoFeature);
void flyTo(double[] coordinates);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
index a66f30dd9..315f857e8 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
@@ -28,10 +28,9 @@ import org.openremote.manager.client.assets.browser.AssetBrowser;
import org.openremote.manager.client.assets.browser.AssetBrowserSelection;
import org.openremote.manager.client.assets.browser.AssetTreeNode;
import org.openremote.manager.client.assets.browser.TenantTreeNode;
-import org.openremote.manager.client.assets.datapoint.NumberDatapointArrayMapper;
import org.openremote.manager.client.assets.tenant.AssetsTenantPlace;
+import org.openremote.manager.client.datapoint.NumberDatapointArrayMapper;
import org.openremote.manager.client.interop.elemental.JsonObjectMapper;
-import org.openremote.manager.client.map.MapView;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.datapoint.AssetDatapointResource;
import org.openremote.manager.shared.http.EntityWriter;
@@ -120,8 +119,22 @@ public class AssetViewActivity
view::initialiseMap,
ex -> handleRequestException(ex, environment)
);
+ } else {
+ onMapReady();
}
+ }
+
+ @Override
+ public void onStop() {
+ super.onStop();
+ if (attributesBrowser != null) {
+ attributesBrowser.close();
+ }
+ view.setPresenter(null);
+ }
+ @Override
+ public void onMapReady() {
asset = null;
if (assetId != null) {
assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
@@ -144,15 +157,6 @@ public class AssetViewActivity
}
}
- @Override
- public void onStop() {
- super.onStop();
- if (attributesBrowser != null) {
- attributesBrowser.close();
- }
- view.setPresenter(null);
- }
-
@Override
public void centerMap() {
view.flyTo(asset.getCoordinates());
@@ -163,7 +167,7 @@ public class AssetViewActivity
view.setName(asset.getName());
view.setCreatedOn(asset.getCreatedOn());
view.setLocation(asset.getCoordinates());
- view.showFeaturesSelection(MapView.getFeature(asset));
+ view.showDroppedPin(asset.getGeoFeature(20));
view.flyTo(asset.getCoordinates());
view.setType(asset.getType());
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
index ac7c24109..463aec2f8 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
@@ -38,7 +38,7 @@ import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.style.WidgetStyle;
import org.openremote.manager.client.widget.*;
import org.openremote.manager.client.widget.Hyperlink;
-import org.openremote.manager.shared.map.GeoJSON;
+import org.openremote.model.geo.GeoJSON;
import org.openremote.model.Constants;
import org.openremote.model.asset.AssetType;
@@ -171,7 +171,7 @@ public class AssetViewImpl extends Composite implements AssetView {
locationGroup.setVisible(false);
locationOutput.setCoordinates(null, null);
mapWidget.setVisible(false);
- showFeaturesSelection(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
typeLabel.setText(null);
attributesBrowserContainer.clear();
attributesBrowser = null;
@@ -236,8 +236,10 @@ public class AssetViewImpl extends Composite implements AssetView {
@Override
public void initialiseMap(JsonObject mapOptions) {
mapWidget.initialise(mapOptions, () -> {
+ mapWidget.addNavigationControl();
+ if (presenter != null)
+ presenter.onMapReady();
});
- mapWidget.addNavigationControl();
}
@Override
@@ -246,13 +248,17 @@ public class AssetViewImpl extends Composite implements AssetView {
}
@Override
- public void showFeaturesSelection(GeoJSON mapFeatures) {
- mapWidget.showFeatures(MapWidget.FEATURES_SOURCE_SELECTION, mapFeatures);
+ public void showDroppedPin(GeoJSON geoFeature) {
+ if (mapWidget.isMapReady()) {
+ mapWidget.showFeature(MapWidget.FEATURE_SOURCE_DROPPED_PIN, geoFeature);
+ }
}
@Override
public void flyTo(double[] coordinates) {
- mapWidget.flyTo(coordinates);
+ if (mapWidget.isMapReady()) {
+ mapWidget.flyTo(coordinates);
+ }
}
@UiHandler("centerMapButton")
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
index 4892955f0..be2c0d8bd 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
@@ -19,17 +19,11 @@
*/
package org.openremote.manager.client.assets.attributes;
-import com.google.gwt.canvas.client.Canvas;
-import com.google.gwt.i18n.client.DateTimeFormat;
-import com.google.gwt.text.shared.AbstractRenderer;
-import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
-import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import org.openremote.manager.client.Environment;
-import org.openremote.manager.client.interop.chartjs.Chart;
-import org.openremote.manager.client.interop.chartjs.ChartUtil;
+import org.openremote.manager.client.datapoint.DatapointBrowser;
import org.openremote.manager.client.widget.*;
import org.openremote.model.*;
import org.openremote.model.asset.Asset;
@@ -40,14 +34,8 @@ import org.openremote.model.datapoint.NumberDatapoint;
import org.openremote.model.event.bus.EventRegistration;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
-import java.util.stream.Collectors;
-
-import static com.google.gwt.dom.client.Style.Unit.EM;
-import static com.google.gwt.dom.client.Style.Unit.PX;
public abstract class AttributesBrowser
extends AttributesView<AttributesBrowser.Container, AttributesBrowser.Style, AssetAttributes, AssetAttribute> {
@@ -144,6 +132,8 @@ public abstract class AttributesBrowser
FormGroup formGroup) {
Widget datapointBrowser = createDatapointBrowser(attribute);
if (datapointBrowser != null) {
+ FormSectionLabel sectionLabel = new FormSectionLabel(environment.getMessages().historicalData());
+ formGroup.addExtension(sectionLabel);
formGroup.addExtension(datapointBrowser);
} else {
formGroup.showDisabledExtensionToggle();
@@ -243,7 +233,7 @@ public abstract class AttributesBrowser
if (attributeFormGroup != null) {
DatapointBrowser datapointBrowser = attributeFormGroup.getExtensionOfType(DatapointBrowser.class);
if (datapointBrowser != null) {
- datapointBrowser.updateChart(System.currentTimeMillis());
+ datapointBrowser.refresh(System.currentTimeMillis());
}
}
}
@@ -253,172 +243,14 @@ public abstract class AttributesBrowser
return null;
if (!(attribute.getType() == AttributeType.DECIMAL || attribute.getType() == AttributeType.INTEGER))
return null;
- return new DatapointBrowser(attribute);
- }
-
- /* ####################################################################### */
-
- class DatapointBrowser extends FlowPanel {
-
- final AssetAttribute attribute;
- Chart chart;
- DatapointInterval interval;
- long timestamp;
- FormValueListBox<DatapointInterval> intervalListBox;
- FormOutputText timeOutput;
- FormButton nextButton;
-
- public DatapointBrowser(AssetAttribute attribute) {
- this.attribute = attribute;
- this.interval = DatapointInterval.HOUR;
- this.timestamp = System.currentTimeMillis();
-
- setStyleName("layout vertical");
-
- addAttachHandler(event -> {
- if (event.isAttached()) {
- createChart();
- } else {
- destroyChart();
- }
- });
- }
-
- void createChart() {
- FormSectionLabel sectionLabel = new FormSectionLabel(environment.getMessages().historicalData());
- add(sectionLabel);
-
- Canvas canvas = Canvas.createIfSupported();
- if (canvas == null) {
- add(new Label(environment.getMessages().canvasNotSupported()));
- return;
+ return new DatapointBrowser(environment.getMessages(), 850, 250) {
+ @Override
+ protected void queryDatapoints(DatapointInterval interval,
+ long timestamp,
+ Consumer<NumberDatapoint[]> consumer) {
+ getNumberDatapoints(attribute, interval, timestamp, consumer);
}
-
- FlowPanel chartFormPanel = new FlowPanel();
- chartFormPanel.setStyleName("layout vertical center or-FormGroup");
- add(chartFormPanel);
-
- canvas.getCanvasElement().setWidth(850);
- canvas.getCanvasElement().setHeight(250);
- FlowPanel canvasContainer = new FlowPanel();
- canvasContainer.setWidth("850px");
- canvasContainer.setHeight("250px");
- canvasContainer.add(canvas);
-
- chartFormPanel.add(canvasContainer);
-
- Form controlForm = new Form();
- controlForm.getElement().getStyle().setWidth(850, PX);
- controlForm.getElement().getStyle().setMarginTop(0.4, EM);
- controlForm.getElement().getStyle().setMarginBottom(0.4, EM);
- chartFormPanel.add(controlForm);
-
- FormGroup controlFormGroup = new FormGroup();
- controlForm.add(controlFormGroup);
-
- FormLabel controlFormLabel = new FormLabel(environment.getMessages().showChartAggregatedFor());
- controlFormGroup.addFormLabel(controlFormLabel);
-
- FormField controlFormField = new FormField();
- controlFormGroup.addFormField(controlFormField);
- intervalListBox = new FormValueListBox<>(
- new AbstractRenderer<DatapointInterval>() {
- @Override
- public String render(DatapointInterval interval) {
- return environment.getMessages().datapointInterval(interval.name());
- }
- }
- );
- intervalListBox.addValueChangeHandler(event -> {
- updateChart(timestamp);
- });
- intervalListBox.setValue(interval);
- intervalListBox.setAcceptableValues(Arrays.asList(DatapointInterval.values()));
- intervalListBox.setEnabled(true);
- controlFormField.add(intervalListBox);
-
- FormGroupActions controlFormActions = new FormGroupActions();
- controlFormGroup.addFormGroupActions(controlFormActions);
-
- timeOutput = new FormOutputText();
- timeOutput.addStyleName("flex");
- timeOutput.getElement().getStyle().setFontSize(0.8, EM);
- controlFormActions.add(timeOutput);
-
- FormButton previousButton = new FormButton();
- previousButton.setIcon("arrow-circle-left");
- previousButton.setText(environment.getMessages().previous());
- previousButton.addClickHandler(event -> updateChart(calculateTimestamp(true)));
- controlFormActions.add(previousButton);
-
- nextButton = new FormButton();
- nextButton.setIcon("arrow-circle-right");
- nextButton.setText(environment.getMessages().next());
- nextButton.addClickHandler(event -> updateChart(calculateTimestamp(false)));
- controlFormActions.add(nextButton);
-
- chart = ChartUtil.createLineChart(canvas.getContext2d());
-
- updateChart(timestamp);
- }
-
- long calculateTimestamp(boolean subtract) {
- long hour = 1000 * 60 * 60;
- long day = hour * 24;
- long week = day * 7;
- long month = day * 30;
- long year = day * 365;
- switch (intervalListBox.getValue()) {
- case HOUR:
- return subtract ? (timestamp - hour) : (timestamp + hour);
- case DAY:
- return subtract ? (timestamp - day) : (timestamp + day);
- case WEEK:
- return subtract ? (timestamp - week) : (timestamp + week);
- case MONTH:
- return subtract ? (timestamp - month) : (timestamp + month);
- case YEAR:
- return subtract ? (timestamp - year) : (timestamp + year);
- default:
- throw new IllegalArgumentException("Unsupported time period: " + intervalListBox.getValue());
- }
- }
-
- void updateChart(long timestamp) {
- if (chart == null) {
- return;
- }
-
- this.timestamp = timestamp;
- this.interval = intervalListBox.getValue();
-
- timeOutput.setText(
- DateTimeFormat.getFormat(Constants.DEFAULT_DATETIME_FORMAT).format(new Date(timestamp))
- );
-
- getNumberDatapoints(
- attribute,
- interval,
- timestamp,
- numberDatapoints -> {
- ChartUtil.update(
- chart,
- ChartUtil.convertLabels(numberDatapoints),
- ChartUtil.convertData(numberDatapoints)
- );
- });
- }
-
- void destroyChart() {
- if (chart != null) {
- chart.destroy();
- }
- chart = null;
- intervalListBox = null;
- timeOutput = null;
- nextButton = null;
- clear();
- }
+ };
}
/* ####################################################################### */
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java
index 05f3d46f8..bb861f04d 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java
@@ -31,7 +31,6 @@ import org.openremote.manager.client.event.ShowInfoEvent;
import org.openremote.manager.client.event.ShowSuccessEvent;
import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.util.CollectionsUtil;
-import org.openremote.manager.client.util.TextUtil;
import org.openremote.manager.client.widget.*;
import org.openremote.model.AttributeType;
import org.openremote.model.Constants;
@@ -40,6 +39,7 @@ import org.openremote.model.MetaItem;
import org.openremote.model.asset.AbstractAssetAttribute;
import org.openremote.model.asset.AbstractAssetAttributes;
import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.util.TextUtil;
import java.util.*;
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeCell.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeCell.java
index bf23479b7..2f27e2878 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeCell.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeCell.java
@@ -26,7 +26,7 @@ import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.SafeHtmlRenderer;
-import org.openremote.manager.client.util.TextUtil;
+import org.openremote.model.util.TextUtil;
class AssetTreeCell extends AbstractSafeHtmlCell<BrowserTreeNode> {
diff --git a/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java
new file mode 100644
index 000000000..f5a615fad
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java
@@ -0,0 +1,208 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.datapoint;
+
+import com.google.gwt.canvas.client.Canvas;
+import com.google.gwt.i18n.client.DateTimeFormat;
+import com.google.gwt.text.shared.AbstractRenderer;
+import com.google.gwt.user.client.ui.FlowPanel;
+import com.google.gwt.user.client.ui.Label;
+import org.openremote.manager.client.i18n.ManagerMessages;
+import org.openremote.manager.client.interop.chartjs.Chart;
+import org.openremote.manager.client.interop.chartjs.ChartUtil;
+import org.openremote.manager.client.widget.*;
+import org.openremote.model.Constants;
+import org.openremote.model.Consumer;
+import org.openremote.model.datapoint.DatapointInterval;
+import org.openremote.model.datapoint.NumberDatapoint;
+
+import java.util.Arrays;
+import java.util.Date;
+
+import static com.google.gwt.dom.client.Style.Unit.EM;
+import static com.google.gwt.dom.client.Style.Unit.PX;
+
+public abstract class DatapointBrowser extends FlowPanel {
+
+ final ManagerMessages messages;
+ final int width;
+ final int height;
+
+ DatapointInterval interval;
+ long timestamp;
+
+ Chart chart;
+ FormValueListBox<DatapointInterval> intervalListBox;
+ FormOutputText timeOutput;
+ FormButton nextButton;
+
+ public DatapointBrowser(ManagerMessages messages, int width, int height) {
+ this(messages, width, height, DatapointInterval.HOUR, System.currentTimeMillis());
+ }
+
+ public DatapointBrowser(ManagerMessages messages, int width, int height, DatapointInterval interval, long timestamp) {
+ this.messages = messages;
+ this.width = width;
+ this.height = height;
+ this.interval = interval;
+ this.timestamp = timestamp;
+
+ setStyleName("layout vertical center or-DatapointBrowser");
+
+ addAttachHandler(event -> {
+ if (event.isAttached()) {
+ createChart();
+ } else {
+ destroyChart();
+ }
+ });
+ }
+
+ public void refresh(long timestamp) {
+ if (chart == null) {
+ return;
+ }
+ refresh(timestamp, intervalListBox.getValue());
+ }
+
+ public void refresh(long timestamp, DatapointInterval interval) {
+ if (chart == null) {
+ return;
+ }
+
+ this.timestamp = timestamp;
+ this.interval = interval;
+
+ timeOutput.setText(
+ DateTimeFormat.getFormat(Constants.DEFAULT_DATETIME_FORMAT).format(new Date(timestamp))
+ );
+
+ queryDatapoints(interval, timestamp, numberDatapoints -> ChartUtil.update(
+ chart,
+ ChartUtil.convertLabels(numberDatapoints),
+ ChartUtil.convertData(numberDatapoints)
+ ));
+ }
+
+ protected void createChart() {
+
+ Canvas canvas = Canvas.createIfSupported();
+ if (canvas == null) {
+ add(new Label(messages.canvasNotSupported()));
+ return;
+ }
+
+ canvas.getCanvasElement().setWidth(width);
+ canvas.getCanvasElement().setHeight(height);
+ FlowPanel canvasContainer = new FlowPanel();
+ canvasContainer.setWidth(width + "px");
+ canvasContainer.setHeight(height + "px");
+ canvasContainer.add(canvas);
+ add(canvasContainer);
+
+ Form controlForm = new Form();
+ controlForm.getElement().getStyle().setWidth(width, PX);
+ controlForm.getElement().getStyle().setMarginTop(0.4, EM);
+ add(controlForm);
+
+ FormGroup controlFormGroup = new FormGroup();
+ controlForm.add(controlFormGroup);
+
+ FormLabel controlFormLabel = new FormLabel(messages.showChartAggregatedFor());
+ controlFormGroup.addFormLabel(controlFormLabel);
+
+ FormField controlFormField = new FormField();
+ controlFormGroup.addFormField(controlFormField);
+ intervalListBox = new FormValueListBox<>(
+ new AbstractRenderer<DatapointInterval>() {
+ @Override
+ public String render(DatapointInterval interval) {
+ return messages.datapointInterval(interval.name());
+ }
+ }
+ );
+ intervalListBox.addValueChangeHandler(event -> refresh(timestamp));
+ intervalListBox.setValue(interval);
+ intervalListBox.setAcceptableValues(Arrays.asList(DatapointInterval.values()));
+ intervalListBox.setEnabled(true);
+ controlFormField.add(intervalListBox);
+
+ FormGroupActions controlFormActions = new FormGroupActions();
+ controlFormGroup.addFormGroupActions(controlFormActions);
+
+ timeOutput = new FormOutputText();
+ timeOutput.addStyleName("flex");
+ timeOutput.getElement().getStyle().setFontSize(0.8, EM);
+ controlFormActions.add(timeOutput);
+
+ FormButton previousButton = new FormButton();
+ previousButton.setIcon("arrow-circle-left");
+ previousButton.setText(messages.previous());
+ previousButton.addClickHandler(event -> refresh(calculateTimestamp(true)));
+ controlFormActions.add(previousButton);
+
+ nextButton = new FormButton();
+ nextButton.setIcon("arrow-circle-right");
+ nextButton.setText(messages.next());
+ nextButton.addClickHandler(event -> refresh(calculateTimestamp(false)));
+ controlFormActions.add(nextButton);
+
+ chart = ChartUtil.createLineChart(canvas.getContext2d());
+
+ refresh(timestamp);
+ }
+
+ protected long calculateTimestamp(boolean subtract) {
+ long hour = 1000 * 60 * 60;
+ long day = hour * 24;
+ long week = day * 7;
+ long month = day * 30;
+ long year = day * 365;
+ switch (intervalListBox.getValue()) {
+ case HOUR:
+ return subtract ? (timestamp - hour) : (timestamp + hour);
+ case DAY:
+ return subtract ? (timestamp - day) : (timestamp + day);
+ case WEEK:
+ return subtract ? (timestamp - week) : (timestamp + week);
+ case MONTH:
+ return subtract ? (timestamp - month) : (timestamp + month);
+ case YEAR:
+ return subtract ? (timestamp - year) : (timestamp + year);
+ default:
+ throw new IllegalArgumentException("Unsupported time period: " + intervalListBox.getValue());
+ }
+ }
+
+ protected void destroyChart() {
+ if (chart != null) {
+ chart.destroy();
+ }
+ chart = null;
+ intervalListBox = null;
+ timeOutput = null;
+ nextButton = null;
+ clear();
+ }
+
+ abstract protected void queryDatapoints(DatapointInterval interval,
+ long timestamp,
+ Consumer<NumberDatapoint[]> consumer);
+}
\ No newline at end of file
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/datapoint/NumberDatapointArrayMapper.java b/manager/client/src/main/java/org/openremote/manager/client/datapoint/NumberDatapointArrayMapper.java
similarity index 96%
rename from manager/client/src/main/java/org/openremote/manager/client/assets/datapoint/NumberDatapointArrayMapper.java
rename to manager/client/src/main/java/org/openremote/manager/client/datapoint/NumberDatapointArrayMapper.java
index aac5f656e..d1ad7da51 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/datapoint/NumberDatapointArrayMapper.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/datapoint/NumberDatapointArrayMapper.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.client.assets.datapoint;
+package org.openremote.manager.client.datapoint;
import com.github.nmorel.gwtjackson.client.ObjectMapper;
import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapboxMap.java b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapboxMap.java
index e56b41134..f8314cb7c 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapboxMap.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapboxMap.java
@@ -23,7 +23,6 @@ import com.google.gwt.core.client.JavaScriptObject;
import elemental.dom.Node;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
-import elemental.json.JsonValue;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java
index 458182834..b291837ea 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java
@@ -23,28 +23,38 @@ import com.google.gwt.user.client.ui.AcceptsOneWidget;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.assets.AssetBrowsingActivity;
import org.openremote.manager.client.assets.AssetMapper;
+import org.openremote.manager.client.assets.asset.AssetViewPlace;
import org.openremote.manager.client.assets.browser.AssetBrowser;
import org.openremote.manager.client.assets.browser.AssetBrowserSelection;
import org.openremote.manager.client.assets.browser.AssetTreeNode;
import org.openremote.manager.client.assets.browser.TenantTreeNode;
-import org.openremote.manager.shared.security.Tenant;
-import org.openremote.model.event.bus.EventBus;
-import org.openremote.model.event.bus.EventRegistration;
import org.openremote.manager.client.interop.elemental.JsonObjectMapper;
import org.openremote.manager.client.mvp.AppActivity;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.map.MapResource;
+import org.openremote.manager.shared.security.Tenant;
+import org.openremote.model.AttributeEvent;
+import org.openremote.model.Pair;
import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetAttributes;
+import org.openremote.model.event.bus.EventBus;
+import org.openremote.model.event.bus.EventRegistration;
+import org.openremote.model.geo.GeoJSON;
import javax.inject.Inject;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.List;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;
public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapView.Presenter {
+ private static final Logger LOG = Logger.getLogger(MapActivity.class.getName());
+
final MapView view;
final AssetResource assetResource;
final AssetMapper assetMapper;
@@ -52,8 +62,9 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
final JsonObjectMapper jsonObjectMapper;
String assetId;
+ String realmId;
Asset asset;
- String realm;
+ List<AssetAttribute> dashboardAttributes = new ArrayList<>();
@Inject
public MapActivity(Environment environment,
@@ -79,7 +90,7 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
assetId = mapAssetPlace.getAssetId();
} else if (place instanceof MapTenantPlace) {
MapTenantPlace mapTenantPlace = (MapTenantPlace) place;
- realm = mapTenantPlace.getRealmId();
+ realmId = mapTenantPlace.getRealmId();
}
return this;
}
@@ -101,69 +112,100 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
}
}));
+ registrations.add(environment.getEventBus().register(
+ AttributeEvent.class,
+ event -> {
+ if (asset == null
+ || !event.getEntityId().equals(asset.getId())
+ || dashboardAttributes.stream().noneMatch(attribute -> attribute.getName().equals(event.getAttributeName())))
+ return;
+
+ dashboardAttributes.stream()
+ .filter(attribute -> attribute.getName().equals(event.getAttributeName())).findFirst().get()
+ .setValueUnchecked(
+ event.getValue(), event.getTimestamp()
+ );
+ showAssetInfoItems();
+ }
+ ));
+
if (!view.isMapInitialised()) {
environment.getRequestService().execute(
jsonObjectMapper,
mapResource::getSettings,
200,
- mapSettings -> {
- view.initialiseMap(mapSettings);
- if (asset != null) {
- showAssetOnMap();
- }
- },
+ view::initialiseMap,
ex -> handleRequestException(ex, environment)
);
+ } else {
+ onMapReady();
}
+ }
- hideAssetOnMap();
+ @Override
+ public void onStop() {
+ super.onStop();
+ view.setPresenter(null);
- asset = null;
+ if (asset != null && asset.hasGeoFeature() || dashboardAttributes.size() > 0) {
+ environment.getEventService().unsubscribe(
+ AttributeEvent.class
+ );
+ }
+ }
+
+ @Override
+ public void onMapReady() {
if (assetId != null) {
assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
this.asset = loadedAsset;
- if (asset != null) {
- assetBrowserPresenter.selectAsset(asset);
- showAssetOnMap();
+ this.dashboardAttributes = new AssetAttributes(asset).get().stream()
+ .filter(AssetAttribute::isShowOnDashboard).collect(Collectors.toList());
+ assetBrowserPresenter.selectAsset(asset);
+ view.setAssetViewHistoryToken(environment.getPlaceHistoryMapper().getToken(
+ new AssetViewPlace(assetId)
+ ));
+ showAssetOnMap();
+ if (asset.hasGeoFeature() || dashboardAttributes.size() > 0) {
+ showAssetInfoItems();
+ environment.getEventService().subscribe(
+ AttributeEvent.class,
+ new AttributeEvent.EntityIdFilter(asset.getId())
+ );
}
});
- } else if (realm != null) {
- view.showInfo("TODO: Tenant map not implemented");
+ } else if (realmId != null) {
+ // TODO: Tenant map not implemented
}
}
- @Override
- public void onStop() {
- super.onStop();
- view.setPresenter(null);
- }
-
protected void showAssetOnMap() {
- if (asset != null && asset.getCoordinates() != null) {
- if (asset.getCreatedOn() != null && asset.getCoordinates().length == 2) {
- // TODO: This assumes 0 is Lng and 1 is Lat, which is true for PostGIS backend
- // TODO: Because Lat/Lng is the 'right way', we flip it here for display
- // TODO: Rounding to 5 decimals gives us precision of about 1 meter, should be enough
- view.showInfo("Location: " + (
- round(asset.getCoordinates()[1], 5) + " " + round(asset.getCoordinates()[0], 5) + " Lat|Lng"
- )
- );
- } else {
- view.showInfo(null);
- }
- view.showFeaturesSelection(MapView.getFeature(asset));
+ if (asset.hasGeoFeature()) {
+ GeoJSON geoFeature = asset.getGeoFeature(30);
+ view.showDroppedPin(geoFeature);
view.flyTo(asset.getCoordinates());
- } else {
- view.showInfo(null);
}
}
- protected void hideAssetOnMap() {
- view.hideFeaturesSelection();
- }
+ protected void showAssetInfoItems() {
+ List<Pair<String, String>> infoItems = dashboardAttributes.stream()
+ .map(attribute -> new Pair<>(attribute.getLabel(), format(attribute.getFormat(), attribute.getValueAsString())))
+ .collect(Collectors.toList());
+ if (asset.hasGeoFeature()) {
+ infoItems.add(0, new Pair<>(
+ environment.getMessages().location(),
+ asset.getCoordinatesLabel()
+ ));
- protected String round(double d, int places) {
- return new BigDecimal(d).setScale(places, RoundingMode.HALF_UP).toString();
+ }
+ view.showInfoItems(infoItems);
}
+ protected native static String format(String formatString, String value) /*-{
+ if (formatString === null)
+ return value;
+ return $wnd.sprintf(formatString, value);
+ }-*/;
+
+
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java
index 3da12dfa1..a06887e81 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java
@@ -20,13 +20,21 @@
package org.openremote.manager.client.map;
import com.google.gwt.core.client.GWT;
+import com.google.gwt.dom.client.Style;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.client.ui.InlineLabel;
-import com.google.gwt.user.client.ui.PopupPanel;
+import com.google.gwt.user.client.ui.FlowPanel;
+import com.google.gwt.user.client.ui.HTMLPanel;
+import com.google.gwt.user.client.ui.Label;
+import elemental.client.Browser;
import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.style.WidgetStyle;
import org.openremote.manager.client.widget.AbstractAppPanel;
+import org.openremote.manager.client.widget.FormLabel;
+import org.openremote.manager.client.widget.PopupPanel;
+import org.openremote.model.Pair;
+
+import java.util.List;
public class MapInfoPanel extends AbstractAppPanel {
@@ -40,25 +48,43 @@ public class MapInfoPanel extends AbstractAppPanel {
WidgetStyle widgetStyle;
@UiField
- InlineLabel infoLabel;
+ HTMLPanel panel;
+
+ @UiField
+ FlowPanel contentPanel;
public MapInfoPanel() {
super(GWT.create(UI.class));
}
- public void addStyleName(String styleName) {
- getPopupPanel().addStyleName(styleName);
- }
+ public void setItems(List<Pair<String, String>> infoItems) {
+ contentPanel.clear();
- public void init() {
- infoLabel.setText(null);
- }
+ for (Pair<String, String> infoItem : infoItems) {
+ FormLabel keyLabel = new FormLabel(infoItem.key);
+ keyLabel.addStyleName("flex");
- public void setInfoText(String text) {
- infoLabel.setText(text);
- }
+ Label valueLabel = new Label(infoItem.value);
+ valueLabel.getElement().getStyle().setFontSize(1.4, Style.Unit.EM);
+
+ FlowPanel itemPanel = new FlowPanel();
+ itemPanel.setStyleName("layout horizontal center");
+ itemPanel.getElement().getStyle().setWhiteSpace(Style.WhiteSpace.NOWRAP);
+ itemPanel.getElement().getStyle().setMargin(0.2, Style.Unit.EM);
+ itemPanel.add(keyLabel);
+ itemPanel.add(valueLabel);
+ contentPanel.add(itemPanel);
+ }
+
+ // Show up to 6 items, then start scrolling
+ panel.setHeight(Math.min((infoItems.size() * 2.5), 15) + "em");
- public String getInfoText() {
- return infoLabel.getText();
+ // If the panel is already shown, "blink" it so users know there is an update
+ if (isShowing()) {
+ contentPanel.addStyleName(widgetStyle.HighlightBackground());
+ Browser.getWindow().setTimeout(() -> {
+ contentPanel.removeStyleName(widgetStyle.HighlightBackground());
+ }, 250);
+ }
}
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml
index dbbdefb97..251e3bfc1 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.ui.xml
@@ -10,19 +10,26 @@
z-index: 10;
}
+ .panel {
+ width: 30em;
+ }
+
.content {
overflow: auto;
padding: 0.4em;
}
</ui:style>
- <g:PopupPanel glassEnabled="false" addStyleNames="{style.popup} {widgetStyle.PopupPanel}">
- <g:HTMLPanel styleName="flex layout vertical"
- addStyleNames="{style.content} {widgetStyle.PopupPanelContent}">
+ <w:PopupPanel glassEnabled="false" styleName="{style.popup} {widgetStyle.PopupPanel}">
+ <g:HTMLPanel ui:field="panel"
+ styleName="layout vertical {style.panel}">
- <g:InlineLabel ui:field="infoLabel"/>
+ <g:FlowPanel ui:field="contentPanel"
+ styleName="flex layout vertical"
+ addStyleNames="{style.content} {widgetStyle.PopupPanelContent}"/>
</g:HTMLPanel>
- </g:PopupPanel>
+
+ </w:PopupPanel>
</ui:UiBinder>
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java
index e5285874e..e562e15bc 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java
@@ -21,52 +21,28 @@ package org.openremote.manager.client.map;
import com.google.gwt.user.client.ui.IsWidget;
import elemental.json.JsonObject;
-import org.openremote.manager.client.util.TextUtil;
-import org.openremote.manager.shared.map.GeoJSON;
-import org.openremote.manager.shared.map.GeoJSONFeature;
-import org.openremote.manager.shared.map.GeoJSONGeometry;
-import org.openremote.model.asset.Asset;
+import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.Pair;
-public interface MapView extends IsWidget {
-
- static GeoJSON getFeature(Asset asset) {
- if (asset == null
- || asset.getId() == null
- || asset.getName() == null
- || asset.getCoordinates() == null)
- return GeoJSON.EMPTY_FEATURE_COLLECTION;
+import java.util.List;
- return new GeoJSON().setType("FeatureCollection").setFeatures(
- new GeoJSONFeature().setType("Feature")
- .setProperty("id", asset.getId())
- .setProperty("title", TextUtil.ellipsize(asset.getName(), 20))
- .setGeometry(
- new GeoJSONGeometry().setPoint(
- asset.getCoordinates()
- )
- )
- );
- }
+public interface MapView extends IsWidget {
interface Presenter {
+ void onMapReady();
}
void setPresenter(Presenter presenter);
+ void setAssetViewHistoryToken(String token);
+
void initialiseMap(JsonObject mapOptions);
boolean isMapInitialised();
- void showInfo(String text);
-
- void showFeaturesAll(GeoJSON mapFeatures);
-
- void hideFeaturesAll();
-
- void showFeaturesSelection(GeoJSON mapFeatures);
-
- void hideFeaturesSelection();
+ void showDroppedPin(GeoJSON geoFeature);
void flyTo(double[] coordinates);
+ void showInfoItems(List<Pair<String, String>> infoItems);
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java
index 868285a6a..75f069834 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java
@@ -25,15 +25,19 @@ import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
-import com.google.gwt.user.client.ui.Label;
import com.google.inject.Provider;
+import elemental.client.Browser;
import elemental.json.JsonObject;
import org.openremote.manager.client.assets.browser.AssetBrowser;
+import org.openremote.manager.client.style.WidgetStyle;
import org.openremote.manager.client.widget.FlexSplitPanel;
+import org.openremote.manager.client.widget.Hyperlink;
import org.openremote.manager.client.widget.MapWidget;
-import org.openremote.manager.shared.map.GeoJSON;
+import org.openremote.model.Pair;
+import org.openremote.model.geo.GeoJSON;
import javax.inject.Inject;
+import java.util.List;
import java.util.logging.Logger;
public class MapViewImpl extends Composite implements MapView {
@@ -45,17 +49,17 @@ public class MapViewImpl extends Composite implements MapView {
public interface Style extends CssResource {
- String mapLoadingLabel();
-
String navItem();
String mapControls();
String mapWidget();
- String infoPanel();
}
+ @UiField
+ WidgetStyle widgetStyle;
+
@UiField
Style style;
@@ -65,12 +69,15 @@ public class MapViewImpl extends Composite implements MapView {
@UiField
HTMLPanel sidebarContainer;
+ @UiField
+ Hyperlink viewAssetLink;
+
@UiField
MapWidget mapWidget;
final AssetBrowser assetBrowser;
final Provider<MapInfoPanel> infoPanelProvider;
- final MapInfoPanel infoPanel;
+ MapInfoPanel infoPanel;
Presenter presenter;
@@ -84,34 +91,46 @@ public class MapViewImpl extends Composite implements MapView {
splitPanel.setOnResize(() -> {
mapWidget.resize();
- showInfoPanel();
+ if (infoPanel != null)
+ infoPanel.resize();
});
-
- infoPanel = infoPanelProvider.get();
- infoPanel.addStyleName(style.infoPanel());
}
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
+
+ // Reset state
+ sidebarContainer.clear();
+ viewAssetLink.setVisible(false);
+ viewAssetLink.setTargetHistoryToken("");
+ showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ if (infoPanel != null) {
+ infoPanel.hide();
+ infoPanel = null;
+ }
+
if (presenter != null) {
assetBrowser.asWidget().removeFromParent();
sidebarContainer.add(assetBrowser.asWidget());
- } else {
- sidebarContainer.clear();
- hideFeaturesAll();
- hideFeaturesSelection();
- infoPanel.hide();
- infoPanel.init();
+ }
+ }
+
+ @Override
+ public void setAssetViewHistoryToken(String token) {
+ if (token != null) {
+ viewAssetLink.setTargetHistoryToken(token);
+ viewAssetLink.setVisible(true);
}
}
@Override
public void initialiseMap(JsonObject mapOptions) {
mapWidget.initialise(mapOptions, () -> {
- showInfoPanel();
+ mapWidget.addNavigationControl();
+ if (presenter != null)
+ presenter.onMapReady();
});
- mapWidget.addNavigationControl();
}
@Override
@@ -120,44 +139,33 @@ public class MapViewImpl extends Composite implements MapView {
}
@Override
- public void showInfo(String text) {
- infoPanel.setInfoText(text);
- if (text != null && !infoPanel.isShowing()) {
- showInfoPanel();
- } else if (text == null) {
- infoPanel.hide();
- infoPanel.init();
+ public void showDroppedPin(GeoJSON geoFeature) {
+ if (mapWidget.isMapReady()) {
+ mapWidget.showFeature(MapWidget.FEATURE_SOURCE_DROPPED_PIN, geoFeature);
}
}
@Override
- public void showFeaturesAll(GeoJSON mapFeatures) {
- mapWidget.showFeatures(MapWidget.FEATURES_SOURCE_ALL, mapFeatures);
- }
-
- @Override
- public void hideFeaturesAll() {
- showFeaturesAll(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ public void flyTo(double[] coordinates) {
+ if (mapWidget.isMapReady()) {
+ mapWidget.flyTo(coordinates);
+ }
}
@Override
- public void showFeaturesSelection(GeoJSON mapFeatures) {
- mapWidget.showFeatures(MapWidget.FEATURES_SOURCE_SELECTION, mapFeatures);
- }
+ public void showInfoItems(List<Pair<String, String>> infoItems) {
+ if (!mapWidget.isMapReady())
+ return;
- @Override
- public void hideFeaturesSelection() {
- showFeaturesSelection(GeoJSON.EMPTY_FEATURE_COLLECTION);
- }
+ if (infoPanel == null) {
+ infoPanel = infoPanelProvider.get();
+ }
- @Override
- public void flyTo(double[] coordinates) {
- mapWidget.flyTo(coordinates);
- }
+ infoPanel.setItems(infoItems);
- protected void showInfoPanel() {
- if (mapWidget.isInitialised() && infoPanel.getInfoText() != null && !infoPanel.getInfoText().isEmpty()) {
+ mapWidget.resize();
+ Browser.getWindow().setTimeout(() -> {
infoPanel.showBottomRightOf(mapWidget, 10, 30);
- }
+ }, 100);
}
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml
index 7760f22af..6ec5f9b46 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml
@@ -14,21 +14,9 @@
height: 100%;
}
- .mapLoadingLabel {
- margin: 0.4em;
- text-align: right;
- font-weight: bold;
- }
-
.mapControls {
z-index: 1;
}
-
- .infoPanel {
- width: 20em;
- height: 2em;
- text-align: center;
- }
</ui:style>
<w:FlexSplitPanel ui:field="splitPanel"
@@ -48,6 +36,13 @@
<g:HTMLPanel
styleName="layout horizontal center end-justified {style.mapControls} {widgetStyle.SecondaryNavHorizontal}">
+ <w:Hyperlink
+ ui:field="viewAssetLink"
+ addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"
+ icon="eye"
+ visible="false"
+ text="{managerMessages.viewAsset}"/>
+
<w:Hyperlink
addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"
icon="plus-square"
diff --git a/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java b/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java
index d7fae5a96..e756f2da2 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java
@@ -22,9 +22,9 @@ package org.openremote.manager.client.toast;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
-import com.google.gwt.user.client.ui.PopupPanel;
import org.openremote.manager.client.style.WidgetStyle;
import org.openremote.manager.client.widget.MessagesIcon;
+import org.openremote.manager.client.widget.PopupPanel;
import javax.inject.Inject;
import java.util.Collection;
diff --git a/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.java b/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.java
index a148cd7e7..8b08cd1b3 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.java
@@ -27,10 +27,10 @@ import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Label;
-import com.google.gwt.user.client.ui.PopupPanel;
import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.widget.AbstractAppPanel;
import org.openremote.manager.client.widget.Hyperlink;
+import org.openremote.manager.client.widget.PopupPanel;
import javax.inject.Inject;
diff --git a/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.ui.xml
index 9f26a7ac0..db9c983f7 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/user/UserControlsImpl.ui.xml
@@ -33,8 +33,8 @@
}
</ui:style>
- <g:PopupPanel glassEnabled="false" addStyleNames="{style.popup} {widgetStyle.PopupPanel}">
- <g:HTMLPanel styleName="flex layout vertical {style.panel}">
+ <w:PopupPanel glassEnabled="false" styleName="{style.popup} {widgetStyle.PopupPanel}">
+ <g:HTMLPanel styleName="layout vertical {style.panel}">
<g:HTMLPanel
styleName="layout horizontal {style.header} {widgetStyle.PopupPanelHeader}">
<g:Label ui:field="userLabel"/>
@@ -58,6 +58,6 @@
<w:PushButton ui:field="logoutButton" icon="sign-out" text="{managerMessages.logout}"/>
</g:HTMLPanel>
</g:HTMLPanel>
- </g:PopupPanel>
+ </w:PopupPanel>
</ui:UiBinder>
diff --git a/manager/client/src/main/java/org/openremote/manager/client/util/TextUtil.java b/manager/client/src/main/java/org/openremote/manager/client/util/TextUtil.java
deleted file mode 100644
index 97d489705..000000000
--- a/manager/client/src/main/java/org/openremote/manager/client/util/TextUtil.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.client.util;
-
-public class TextUtil {
-
- private final static String NON_THIN = "[^iIl1\\.,']";
-
- private static int textWidth(String str) {
- return str.length() - str.replaceAll(NON_THIN, "").length() / 2;
- }
-
- public static String ellipsize(String text, int max) {
- if (textWidth(text) <= max)
- return text;
- // Start by chopping off at the word before max
- // This is an over-approximation due to thin-characters...
- int end = text.lastIndexOf(' ', max - 3);
- // Just one long word. Chop it off.
- if (end == -1)
- return text.substring(0, max - 3) + "...";
- // Step forward as long as textWidth allows.
- int newEnd = end;
- do {
- end = newEnd;
- newEnd = text.indexOf(' ', end + 1);
-
- // No more spaces.
- if (newEnd == -1)
- newEnd = text.length();
- } while (textWidth(text.substring(0, newEnd) + "...") < max);
- return text.substring(0, end) + "...";
- }
-}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/AbstractAppPanel.java b/manager/client/src/main/java/org/openremote/manager/client/widget/AbstractAppPanel.java
index 485071bc8..4d8f2edad 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/widget/AbstractAppPanel.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/AbstractAppPanel.java
@@ -19,13 +19,18 @@
*/
package org.openremote.manager.client.widget;
+import com.google.gwt.dom.client.Style;
+import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.Window;
-import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.UIObject;
+import java.util.logging.Logger;
+
public abstract class AbstractAppPanel implements AppPanel {
+ private static final Logger LOG = Logger.getLogger(AbstractAppPanel.class.getName());
+
final protected PopupPanel popupPanel;
protected UIObject target;
@@ -36,12 +41,26 @@ public abstract class AbstractAppPanel implements AppPanel {
protected UIObject bottomRightTarget;
protected UIObject topLeftTarget;
+ protected HandlerRegistration windowHandlerRegistration;
+
public AbstractAppPanel(UiBinder<PopupPanel, AbstractAppPanel> binder) {
this.popupPanel = binder.createAndBindUi(this);
+
+ popupPanel.getElement().getStyle().setOverflow(Style.Overflow.AUTO);
+
popupPanel.setAutoHideOnHistoryEventsEnabled(true);
popupPanel.setGlassStyleName("or-PopupPanelGlass");
+ popupPanel.addAttachHandler(event -> {
+ if (event.isAttached()) {
+ windowHandlerRegistration = Window.addResizeHandler(e -> resize());
+ } else if (windowHandlerRegistration != null) {
+ windowHandlerRegistration.removeHandler();
+ windowHandlerRegistration = null;
+ }
+ });
+
popupPanel.addCloseHandler(event -> {
if (target != null) {
popupPanel.removeAutoHidePartner(target.getElement());
@@ -49,17 +68,6 @@ public abstract class AbstractAppPanel implements AppPanel {
}
});
- Window.addResizeHandler(event -> {
- if (isShowing()) {
- if (target != null) {
- popupPanel.showRelativeTo(target);
- } else if (bottomRightTarget != null) {
- showBottomRightOf(bottomRightTarget, marginRight, marginBottom);
- } else if (topLeftTarget != null) {
- showTopLeftOf(topLeftTarget, marginTop, marginLeft);
- }
- }
- });
}
public PopupPanel getPopupPanel() {
@@ -146,4 +154,19 @@ public abstract class AbstractAppPanel implements AppPanel {
public void showCenter() {
popupPanel.center();
}
+
+ @Override
+ public void resize() {
+ if (isShowing()) {
+ if (target != null) {
+ popupPanel.showRelativeTo(target);
+ } else if (bottomRightTarget != null) {
+ showBottomRightOf(bottomRightTarget, marginRight, marginBottom);
+ } else if (topLeftTarget != null) {
+ showTopLeftOf(topLeftTarget, marginTop, marginLeft);
+ } else {
+ showCenter();
+ }
+ }
+ }
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/AppPanel.java b/manager/client/src/main/java/org/openremote/manager/client/widget/AppPanel.java
index 3d78d10e8..e2c511680 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/widget/AppPanel.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/AppPanel.java
@@ -41,4 +41,6 @@ public interface AppPanel {
void hide();
+ void resize();
+
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java b/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java
index 8ff93308d..9d8597548 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java
@@ -25,12 +25,13 @@ import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.FlowPanel;
+import elemental.client.Browser;
import elemental.js.util.*;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import org.openremote.manager.client.interop.mapbox.*;
-import org.openremote.manager.shared.map.GeoJSON;
+import org.openremote.model.geo.GeoJSON;
import java.util.HashMap;
import java.util.Map;
@@ -45,18 +46,18 @@ public class MapWidget extends ComplexPanel {
}
// Feature IDs
- public static final String FEATURES_SOURCE_ALL = "features-source-all";
- public static final String FEATURES_LAYER_ALL = "features-layer-all";
- public static final String FEATURES_SOURCE_SELECTION = "features-source-selection";
- public static final String FEATURES_LAYER_SELECTION = "features-layer-selection";
+ public static final String FEATURE_SOURCE_CIRCLE = "feature-source-circle";
+ public static final String FEATURE_LAYER_CIRCLE = "feature-layer-circle";
+ public static final String FEATURE_SOURCE_DROPPED_PIN = "feature-source-dropped-pin";
+ public static final String FEATURE_LAYER_DROPPED_PIN = "feature-layer-dropped-pin";
// Render a circle on location
@SuppressWarnings("GwtInconsistentSerializableClass")
- static final public JsMapFromStringTo<Object> LAYER_ALL = JsMapFromStringTo.create();
+ static final public JsMapFromStringTo<Object> LAYER_CIRCLE = JsMapFromStringTo.create();
// Render a dropped pin and feature title on location
@SuppressWarnings("GwtInconsistentSerializableClass")
- static final public JsMapFromStringTo<Object> LAYER_SELECTION = JsMapFromStringTo.create();
+ static final public JsMapFromStringTo<Object> LAYER_DROPPED_PIN = JsMapFromStringTo.create();
static {
{
@@ -69,11 +70,11 @@ public class MapWidget extends ComplexPanel {
// TODO Add color to theme settings
paint.put("circle-color", "rgb(73, 169, 66)");
- LAYER_ALL.put("id", FEATURES_LAYER_ALL);
- LAYER_ALL.put("type", "circle");
- LAYER_ALL.put("source", FEATURES_SOURCE_ALL);
- LAYER_ALL.put("layout", layout);
- LAYER_ALL.put("paint", paint);
+ LAYER_CIRCLE.put("id", FEATURE_LAYER_CIRCLE);
+ LAYER_CIRCLE.put("type", "circle");
+ LAYER_CIRCLE.put("source", FEATURE_SOURCE_CIRCLE);
+ LAYER_CIRCLE.put("layout", layout);
+ LAYER_CIRCLE.put("paint", paint);
}
{
JsMapFromStringTo<Object> layout = JsMapFromStringTo.create();
@@ -115,11 +116,11 @@ public class MapWidget extends ComplexPanel {
paint.put("text-halo-width", 4.0);
paint.put("text-halo-blur", 4.0);
- LAYER_SELECTION.put("id", FEATURES_LAYER_SELECTION);
- LAYER_SELECTION.put("type", "symbol");
- LAYER_SELECTION.put("source", FEATURES_SOURCE_SELECTION);
- LAYER_SELECTION.put("layout", layout);
- LAYER_SELECTION.put("paint", paint);
+ LAYER_DROPPED_PIN.put("id", FEATURE_LAYER_DROPPED_PIN);
+ LAYER_DROPPED_PIN.put("type", "symbol");
+ LAYER_DROPPED_PIN.put("source", FEATURE_SOURCE_DROPPED_PIN);
+ LAYER_DROPPED_PIN.put("layout", layout);
+ LAYER_DROPPED_PIN.put("paint", paint);
}
}
@@ -129,6 +130,7 @@ public class MapWidget extends ComplexPanel {
protected ClickListener clickListener;
protected Popup popup;
protected MapboxMap mapboxMap;
+ protected boolean mapReady;
// These sources can be initialized late, as we have to consider async arriving currentFeaturesData
protected boolean featuresReady = false;
@@ -169,11 +171,13 @@ public class MapWidget extends ComplexPanel {
add(host, (Element) getElement());
mapOptions.put("container", hostElementId);
+ mapOptions.put("attributionControl", false);
mapboxMap = new MapboxMap(mapOptions);
mapboxMap.on(EventType.LOAD, eventData -> {
host.setVisible(true);
resize();
+ mapReady = true;
if (onLoad != null)
onLoad.run();
addFeaturesOnLoad();
@@ -186,6 +190,14 @@ public class MapWidget extends ComplexPanel {
});
}
+ public boolean isMapReady() {
+ return mapReady;
+ }
+
+ public boolean isFeaturesReady() {
+ return featuresReady;
+ }
+
public void addNavigationControl() {
if (mapboxMap == null)
return;
@@ -196,6 +208,8 @@ public class MapWidget extends ComplexPanel {
if (mapboxMap == null)
return;
mapboxMap.resize();
+ // This is not reliable, so do it again a bit later
+ Browser.getWindow().setTimeout(() -> mapboxMap.resize(), 200);
}
public void setOpaque(boolean opaque) {
@@ -242,11 +256,11 @@ public class MapWidget extends ComplexPanel {
return;
LOG.fine("Adding GeoJSON feature sources and layers on map load");
- JsonObject sourceOptionsSelection = prepareSourceOptions(FEATURES_SOURCE_SELECTION);
- mapboxMap.addSource(FEATURES_SOURCE_SELECTION, sourceOptionsSelection);
- mapboxMap.addLayer(LAYER_SELECTION);
+ JsonObject sourceOptionsSelection = prepareSourceOptions(FEATURE_SOURCE_DROPPED_PIN);
+ mapboxMap.addSource(FEATURE_SOURCE_DROPPED_PIN, sourceOptionsSelection);
+ mapboxMap.addLayer(LAYER_DROPPED_PIN);
- JsonObject sourceOptionsAll = prepareSourceOptions(FEATURES_SOURCE_ALL);
+ JsonObject sourceOptionsAll = prepareSourceOptions(FEATURE_SOURCE_CIRCLE);
sourceOptionsAll.put("maxzoom", Json.create(20));
sourceOptionsAll.put("buffer", Json.create(128));
sourceOptionsAll.put("tolerance", Json.create(0.375));
@@ -257,15 +271,15 @@ public class MapWidget extends ComplexPanel {
// TODO something weird is going on with JS interop, this helps for now
sourceOptionsAll = Json.parse(sourceOptionsAll.toJson());
- mapboxMap.addSource(FEATURES_SOURCE_ALL, sourceOptionsAll);
- mapboxMap.addLayer(LAYER_ALL, FEATURES_LAYER_SELECTION);
+ mapboxMap.addSource(FEATURE_SOURCE_CIRCLE, sourceOptionsAll);
+ mapboxMap.addLayer(LAYER_CIRCLE, FEATURE_LAYER_DROPPED_PIN);
featuresReady = true;
}
- public void showFeatures(String featureSourceId, GeoJSON mapFeatures) {
- LOG.fine("Showing features on source " + featureSourceId + ": " + mapFeatures);
- JsonObject data = mapFeatures.getJsonObject();
+ public void showFeature(String featureSourceId, GeoJSON geoFeature) {
+ LOG.fine("Showing feature on source " + featureSourceId + ": " + geoFeature);
+ JsonObject data = geoFeature.getJsonObject();
currentFeatureSourceData.put(featureSourceId, data);
if (featuresReady) {
data = currentFeatureSourceData.remove(featureSourceId);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.java b/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.java
new file mode 100644
index 000000000..a51646f17
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.java
@@ -0,0 +1,1445 @@
+/*
+ * Copyright 2009 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.openremote.manager.client.widget;
+
+import com.google.gwt.animation.client.Animation;
+import com.google.gwt.core.client.GWT;
+import com.google.gwt.dom.client.Document;
+import com.google.gwt.dom.client.Element;
+import com.google.gwt.dom.client.EventTarget;
+import com.google.gwt.dom.client.NativeEvent;
+import com.google.gwt.dom.client.Style;
+import com.google.gwt.dom.client.Style.Display;
+import com.google.gwt.dom.client.Style.Position;
+import com.google.gwt.dom.client.Style.Unit;
+import com.google.gwt.event.logical.shared.CloseEvent;
+import com.google.gwt.event.logical.shared.CloseHandler;
+import com.google.gwt.event.logical.shared.HasCloseHandlers;
+import com.google.gwt.event.logical.shared.ResizeEvent;
+import com.google.gwt.event.logical.shared.ResizeHandler;
+import com.google.gwt.event.logical.shared.ValueChangeEvent;
+import com.google.gwt.event.logical.shared.ValueChangeHandler;
+import com.google.gwt.event.shared.HandlerRegistration;
+import com.google.gwt.i18n.client.LocaleInfo;
+import com.google.gwt.user.client.DOM;
+import com.google.gwt.user.client.Event;
+import com.google.gwt.user.client.Event.NativePreviewEvent;
+import com.google.gwt.user.client.Event.NativePreviewHandler;
+import com.google.gwt.user.client.EventPreview;
+import com.google.gwt.user.client.History;
+import com.google.gwt.user.client.Timer;
+import com.google.gwt.user.client.Window;
+import com.google.gwt.user.client.ui.*;
+import com.google.gwt.user.client.ui.impl.PopupImpl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A panel that can "pop up" over other widgets. It overlays the browser's
+ * client area (and any previously-created popups).
+ *
+ * <p>
+ * A PopupPanel should not generally be added to other panels; rather, it should
+ * be shown and hidden using the {@link #show()} and {@link #hide()} methods.
+ * </p>
+ * <p>
+ * The width and height of the PopupPanel cannot be explicitly set; they are
+ * determined by the PopupPanel's widget. Calls to {@link #setWidth(String)} and
+ * {@link #setHeight(String)} will call these methods on the PopupPanel's
+ * widget.
+ * </p>
+ * <p>
+ * <img class='gallery' src='doc-files/PopupPanel.png'/>
+ * </p>
+ *
+ * <p>
+ * The PopupPanel can be optionally displayed with a "glass" element behind it,
+ * which is commonly used to gray out the widgets behind it. It can be enabled
+ * using {@link #setGlassEnabled(boolean)}. It has a default style name of
+ * "gwt-PopupPanelGlass", which can be changed using
+ * {@link #setGlassStyleName(String)}.
+ * </p>
+ *
+ * <p>
+ * <h3>Example</h3>
+ * {@example com.google.gwt.examples.PopupPanelExample}
+ * </p>
+ * <h3>CSS Style Rules</h3>
+ * <dl>
+ * <dt>.gwt-PopupPanel</dt>
+ * <dd>the outside of the popup</dd>
+ * <dt>.gwt-PopupPanel .popupContent</dt>
+ * <dd>the wrapper around the content</dd>
+ * <dt>.gwt-PopupPanelGlass</dt>
+ * <dd>the glass background behind the popup</dd>
+ * </dl>
+ */
+@SuppressWarnings("deprecation")
+public class PopupPanel extends SimplePanel implements SourcesPopupEvents,
+ EventPreview, HasAnimation, HasCloseHandlers<PopupPanel> {
+
+ /**
+ * A callback that is used to set the position of a {@link PopupPanel} right
+ * before it is shown.
+ */
+ public interface PositionCallback {
+
+ /**
+ * Provides the opportunity to set the position of the PopupPanel right
+ * before the PopupPanel is shown. The offsetWidth and offsetHeight values
+ * of the PopupPanel are made available to allow for positioning based on
+ * its size.
+ *
+ * @param offsetWidth the offsetWidth of the PopupPanel
+ * @param offsetHeight the offsetHeight of the PopupPanel
+ * @see PopupPanel#setPopupPositionAndShow(PositionCallback)
+ */
+ void setPosition(int offsetWidth, int offsetHeight);
+ }
+
+ /**
+ * The type of animation to use when opening the popup.
+ *
+ * <ul>
+ * <li>CENTER - Expand from the center of the popup</li>
+ * <li>ONE_WAY_CORNER - Expand from the top left corner, do not animate hiding</li>
+ * <li>ROLL_DOWN - Expand from the top to the bottom, do not animate hiding</li>
+ * </ul>
+ */
+ public static enum AnimationType {
+ CENTER, ONE_WAY_CORNER, ROLL_DOWN
+ }
+
+ /**
+ * An {@link Animation} used to enlarge the popup into view.
+ */
+ static class ResizeAnimation extends Animation {
+ /**
+ * The {@link PopupPanel} being affected.
+ */
+ private PopupPanel curPanel = null;
+
+ /**
+ * Indicates whether or not the {@link PopupPanel} is in the process of
+ * unloading. If the popup is unloading, then the animation just does
+ * cleanup.
+ */
+ private boolean isUnloading;
+
+ /**
+ * The offset height and width of the current {@link PopupPanel}.
+ */
+ private int offsetHeight, offsetWidth = -1;
+
+ /**
+ * A boolean indicating whether we are showing or hiding the popup.
+ */
+ private boolean showing;
+
+ /**
+ * The timer used to delay the show animation.
+ */
+ private Timer showTimer;
+
+ /**
+ * A boolean indicating whether the glass element is currently attached.
+ */
+ private boolean glassShowing;
+
+ private HandlerRegistration resizeRegistration;
+
+ /**
+ * Create a new {@link ResizeAnimation}.
+ *
+ * @param panel the panel to affect
+ */
+ public ResizeAnimation(PopupPanel panel) {
+ this.curPanel = panel;
+ }
+
+ /**
+ * Open or close the content. This method always called immediately after
+ * the PopupPanel showing state has changed, so we base the animation on the
+ * current state.
+ *
+ * @param showing true if the popup is showing, false if not
+ */
+ public void setState(boolean showing, boolean isUnloading) {
+ // Immediately complete previous open/close animation
+ this.isUnloading = isUnloading;
+ cancel();
+
+ // If there is a pending timer to start a show animation, then just cancel
+ // the timer and complete the show operation.
+ if (showTimer != null) {
+ showTimer.cancel();
+ showTimer = null;
+ onComplete();
+ }
+
+ // Update the logical state.
+ curPanel.showing = showing;
+ curPanel.updateHandlers();
+
+ // Determine if we need to animate
+ boolean animate = !isUnloading && curPanel.isAnimationEnabled;
+ if (curPanel.animType != AnimationType.CENTER && !showing) {
+ animate = false;
+ }
+
+ // Open the new item
+ this.showing = showing;
+ if (animate) {
+ // impl.onShow takes some time to complete, so we do it before starting
+ // the animation. If we move this to onStart, the animation will look
+ // choppy or not run at all.
+ if (showing) {
+ maybeShowGlass();
+
+ // Set the position attribute, and then attach to the DOM. Otherwise,
+ // the PopupPanel will appear to 'jump' from its static/relative
+ // position to its absolute position (issue #1231).
+ curPanel.getElement().getStyle().setProperty("position", "absolute");
+ if (curPanel.topPosition != -1) {
+ curPanel.setPopupPosition(curPanel.leftPosition,
+ curPanel.topPosition);
+ }
+ impl.setClip(curPanel.getElement(), getRectString(0, 0, 0, 0));
+ RootPanel.get().add(curPanel);
+
+ // Wait for the popup panel and iframe to be attached before running
+ // the animation. We use a Timer instead of a DeferredCommand so we
+ // can cancel it if the popup is hidden synchronously.
+ showTimer = new Timer() {
+ @Override
+ public void run() {
+ showTimer = null;
+ ResizeAnimation.this.run(ANIMATION_DURATION);
+ }
+ };
+ showTimer.schedule(1);
+ } else {
+ run(ANIMATION_DURATION);
+ }
+ } else {
+ onInstantaneousRun();
+ }
+ }
+
+ @Override
+ protected void onComplete() {
+ if (!showing) {
+ maybeShowGlass();
+ if (!isUnloading) {
+ RootPanel.get().remove(curPanel);
+ }
+ }
+ impl.setClip(curPanel.getElement(), "rect(auto, auto, auto, auto)");
+ curPanel.getElement().getStyle().setProperty("overflow", "auto"); // TODO: In the history of the web, has "visible overflow" ever been desirable?
+ }
+
+ @Override
+ protected void onStart() {
+ offsetHeight = curPanel.getOffsetHeight();
+ offsetWidth = curPanel.getOffsetWidth();
+ curPanel.getElement().getStyle().setProperty("overflow", "hidden");
+ super.onStart();
+ }
+
+ @Override
+ protected void onUpdate(double progress) {
+ if (!showing) {
+ progress = 1.0 - progress;
+ }
+
+ // Determine the clipping size
+ int top = 0;
+ int left = 0;
+ int right = 0;
+ int bottom = 0;
+ int height = (int) (progress * offsetHeight);
+ int width = (int) (progress * offsetWidth);
+ switch (curPanel.animType) {
+ case ROLL_DOWN:
+ right = offsetWidth;
+ bottom = height;
+ break;
+ case CENTER:
+ top = (offsetHeight - height) >> 1;
+ left = (offsetWidth - width) >> 1;
+ right = left + width;
+ bottom = top + height;
+ break;
+ case ONE_WAY_CORNER:
+ if (LocaleInfo.getCurrentLocale().isRTL()) {
+ left = offsetWidth - width;
+ }
+ right = left + width;
+ bottom = top + height;
+ break;
+ }
+ // Set the rect clipping
+ impl.setClip(curPanel.getElement(), getRectString(top, right, bottom,
+ left));
+ }
+
+ /**
+ * Returns a rect string.
+ */
+ private String getRectString(int top, int right, int bottom, int left) {
+ return "rect(" + top + "px, " + right + "px, " + bottom + "px, " + left
+ + "px)";
+ }
+
+ /**
+ * Show or hide the glass.
+ */
+ private void maybeShowGlass() {
+ if (showing) {
+ if (curPanel.isGlassEnabled) {
+ Document.get().getBody().appendChild(curPanel.glass);
+
+ resizeRegistration = Window.addResizeHandler(curPanel.glassResizer);
+ curPanel.glassResizer.onResize(null);
+
+ glassShowing = true;
+ }
+ } else if (glassShowing) {
+ Document.get().getBody().removeChild(curPanel.glass);
+
+ resizeRegistration.removeHandler();
+ resizeRegistration = null;
+
+ glassShowing = false;
+ }
+ }
+
+ private void onInstantaneousRun() {
+ maybeShowGlass();
+ if (showing) {
+ // Set the position attribute, and then attach to the DOM. Otherwise,
+ // the PopupPanel will appear to 'jump' from its static/relative
+ // position to its absolute position (issue #1231).
+ curPanel.getElement().getStyle().setProperty("position", "absolute");
+ if (curPanel.topPosition != -1) {
+ curPanel.setPopupPosition(curPanel.leftPosition, curPanel.topPosition);
+ }
+ RootPanel.get().add(curPanel);
+ } else {
+ if (!isUnloading) {
+ RootPanel.get().remove(curPanel);
+ }
+ }
+ curPanel.getElement().getStyle().setProperty("overflow", "visible"); // TODO: In the history of the web, has "visible overflow" ever been desirable?
+ }
+ }
+
+ /**
+ * The duration of the animation.
+ */
+ private static final int ANIMATION_DURATION = 200;
+
+ /**
+ * The default style name.
+ */
+ private static final String DEFAULT_STYLENAME = "or-PopupPanel";
+
+ private static final PopupImpl impl = GWT.create(PopupImpl.class);
+
+ /**
+ * Window resize handler used to keep the glass the proper size.
+ */
+ private ResizeHandler glassResizer = new ResizeHandler() {
+ public void onResize(ResizeEvent event) {
+ Style style = glass.getStyle();
+
+ int winWidth = Window.getClientWidth();
+ int winHeight = Window.getClientHeight();
+
+ // Hide the glass while checking the document size. Otherwise it would
+ // interfere with the measurement.
+ style.setDisplay(Display.NONE);
+ style.setWidth(0, Unit.PX);
+ style.setHeight(0, Unit.PX);
+
+ int width = Document.get().getScrollWidth();
+ int height = Document.get().getScrollHeight();
+
+ // Set the glass size to the larger of the window's client size or the
+ // document's scroll size.
+ style.setWidth(Math.max(width, winWidth), Unit.PX);
+ style.setHeight(Math.max(height, winHeight), Unit.PX);
+
+ // The size is set. Show the glass again.
+ style.setDisplay(Display.BLOCK);
+ }
+ };
+
+ private AnimationType animType = AnimationType.CENTER;
+
+ private boolean autoHide, previewAllNativeEvents, modal, showing;
+ private boolean autoHideOnHistoryEvents;
+
+ private List<Element> autoHidePartners;
+
+ // Used to track requested size across changing child widgets
+ private String desiredHeight;
+
+ private String desiredWidth;
+
+ /**
+ * The glass element.
+ */
+ private Element glass;
+
+ private String glassStyleName = "or-PopupPanelGlass";
+
+ /**
+ * A boolean indicating that a glass element should be used.
+ */
+ private boolean isGlassEnabled;
+
+ private boolean isAnimationEnabled = false;
+
+ // the left style attribute in pixels
+ private int leftPosition = -1;
+
+ private HandlerRegistration nativePreviewHandlerRegistration;
+ private HandlerRegistration historyHandlerRegistration;
+
+ /**
+ * The {@link ResizeAnimation} used to open and close the {@link PopupPanel}s.
+ */
+ private ResizeAnimation resizeAnimation = new ResizeAnimation(this);
+
+ // The top style attribute in pixels
+ private int topPosition = -1;
+
+ /**
+ * Creates an empty popup panel. A child widget must be added to it before it
+ * is shown.
+ */
+ public PopupPanel() {
+ super();
+ super.getContainerElement().appendChild(impl.createElement());
+
+ // Default position of popup should be in the upper-left corner of the
+ // window. By setting a default position, the popup will not appear in
+ // an undefined location if it is shown before its position is set.
+ setPopupPosition(0, 0);
+ setStyleName(DEFAULT_STYLENAME);
+ setStyleName(getContainerElement(), "layout vertical");
+ }
+
+ /**
+ * Creates an empty popup panel, specifying its "auto-hide" property.
+ *
+ * @param autoHide <code>true</code> if the popup should be automatically
+ * hidden when the user clicks outside of it or the history token
+ * changes.
+ */
+ public PopupPanel(boolean autoHide) {
+ this();
+ this.autoHide = autoHide;
+ this.autoHideOnHistoryEvents = autoHide;
+ }
+
+ /**
+ * Creates an empty popup panel, specifying its "auto-hide" and "modal"
+ * properties.
+ *
+ * @param autoHide <code>true</code> if the popup should be automatically
+ * hidden when the user clicks outside of it or the history token
+ * changes.
+ * @param modal <code>true</code> if keyboard or mouse events that do not
+ * target the PopupPanel or its children should be ignored
+ */
+ public PopupPanel(boolean autoHide, boolean modal) {
+ this(autoHide);
+ this.modal = modal;
+ }
+
+ /**
+ * Mouse events that occur within an autoHide partner will not hide a panel
+ * set to autoHide.
+ *
+ * @param partner the auto hide partner to add
+ */
+ public void addAutoHidePartner(Element partner) {
+ assert partner != null : "partner cannot be null";
+ if (autoHidePartners == null) {
+ autoHidePartners = new ArrayList<Element>();
+ }
+ autoHidePartners.add(partner);
+ }
+
+ public HandlerRegistration addCloseHandler(CloseHandler<PopupPanel> handler) {
+ return addHandler(handler, CloseEvent.getType());
+ }
+
+ /**
+ * @deprecated Use {@link #addCloseHandler} instead
+ */
+ @Deprecated
+ public void addPopupListener(final PopupListener listener) {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Centers the popup in the browser window and shows it. If the popup was
+ * already showing, then the popup is centered.
+ */
+ public void center() {
+ boolean initiallyShowing = showing;
+ boolean initiallyAnimated = isAnimationEnabled;
+
+ if (!initiallyShowing) {
+ setVisible(false);
+ setAnimationEnabled(false);
+ show();
+ }
+
+ // If left/top are set from a previous center() call, and our content
+ // has changed, we may get a bogus getOffsetWidth because our new content
+ // is wrapping (giving a lower offset width) then it would without the
+ // previous left. Setting left/top back to 0 avoids this.
+ Element elem = getElement();
+ elem.getStyle().setPropertyPx("left", 0);
+ elem.getStyle().setPropertyPx("top", 0);
+
+ int left = (Window.getClientWidth() - getOffsetWidth()) >> 1;
+ int top = (Window.getClientHeight() - getOffsetHeight()) >> 1;
+ setPopupPosition(Math.max(Window.getScrollLeft() + left, 0), Math.max(
+ Window.getScrollTop() + top, 0));
+
+ if (!initiallyShowing) {
+ setAnimationEnabled(initiallyAnimated);
+ // Run the animation. The popup is already visible, so we can skip the
+ // call to setState.
+ if (initiallyAnimated) {
+ impl.setClip(getElement(), "rect(0px, 0px, 0px, 0px)");
+ setVisible(true);
+ resizeAnimation.run(ANIMATION_DURATION);
+ } else {
+ setVisible(true);
+ }
+ }
+ }
+
+ /**
+ * Gets the style name to be used on the glass element. By default, this is
+ * "gwt-PopupPanelGlass".
+ *
+ * @return the glass element's style name
+ */
+ public String getGlassStyleName() {
+ return glassStyleName;
+ }
+
+ /**
+ * Gets the panel's offset height in pixels. Calls to
+ * {@link #setHeight(String)} before the panel's child widget is set will not
+ * influence the offset height.
+ *
+ * @return the object's offset height
+ */
+ @Override
+ public int getOffsetHeight() {
+ return super.getOffsetHeight();
+ }
+
+ /**
+ * Gets the panel's offset width in pixels. Calls to {@link #setWidth(String)}
+ * before the panel's child widget is set will not influence the offset width.
+ *
+ * @return the object's offset width
+ */
+ @Override
+ public int getOffsetWidth() {
+ return super.getOffsetWidth();
+ }
+
+ /**
+ * Gets the popup's left position relative to the browser's client area.
+ *
+ * @return the popup's left position
+ */
+ public int getPopupLeft() {
+ return getElement().getAbsoluteLeft();
+ }
+
+ /**
+ * Gets the popup's top position relative to the browser's client area.
+ *
+ * @return the popup's top position
+ */
+ public int getPopupTop() {
+ return getElement().getAbsoluteTop();
+ }
+
+ @Override
+ public String getTitle() {
+ return getContainerElement().getPropertyString("title");
+ }
+
+ /**
+ * Hides the popup and detaches it from the page. This has no effect if it is
+ * not currently showing.
+ */
+ public void hide() {
+ hide(false);
+ }
+
+ /**
+ * Hides the popup and detaches it from the page. This has no effect if it is
+ * not currently showing.
+ *
+ * @param autoClosed the value that will be passed to
+ * {@link CloseHandler#onClose(CloseEvent)} when the popup is closed
+ */
+ public void hide(boolean autoClosed) {
+ if (!isShowing()) {
+ return;
+ }
+ resizeAnimation.setState(false, false);
+ CloseEvent.fire(this, this, autoClosed);
+ }
+
+ public boolean isAnimationEnabled() {
+ return isAnimationEnabled;
+ }
+
+ /**
+ * Returns <code>true</code> if the popup should be automatically hidden when
+ * the user clicks outside of it.
+ *
+ * @return true if autoHide is enabled, false if disabled
+ */
+ public boolean isAutoHideEnabled() {
+ return autoHide;
+ }
+
+ /**
+ * Returns <code>true</code> if the popup should be automatically hidden when
+ * the history token changes, such as when the user presses the browser's back
+ * button.
+ *
+ * @return true if enabled, false if disabled
+ */
+ public boolean isAutoHideOnHistoryEventsEnabled() {
+ return autoHideOnHistoryEvents;
+ }
+
+ /**
+ * Returns <code>true</code> if a glass element will be displayed under the
+ * {@link PopupPanel}.
+ *
+ * @return true if enabled
+ */
+ public boolean isGlassEnabled() {
+ return isGlassEnabled;
+ }
+
+ /**
+ * Returns <code>true</code> if keyboard or mouse events that do not target
+ * the PopupPanel or its children should be ignored.
+ *
+ * @return true if popup is modal, false if not
+ */
+ public boolean isModal() {
+ return modal;
+ }
+
+ /**
+ * Returns <code>true</code> if the popup should preview all native events,
+ * even if the event has already been consumed by another popup.
+ *
+ * @return true if previewAllNativeEvents is enabled, false if disabled
+ */
+ public boolean isPreviewingAllNativeEvents() {
+ return previewAllNativeEvents;
+ }
+
+ /**
+ * Determines whether or not this popup is showing.
+ *
+ * @return <code>true</code> if the popup is showing
+ * @see #show()
+ * @see #hide()
+ */
+ public boolean isShowing() {
+ return showing;
+ }
+
+ /**
+ * Determines whether or not this popup is visible. Note that this just checks
+ * the <code>visibility</code> style attribute, which is set in the
+ * {@link #setVisible(boolean)} method. If you want to know if the popup is
+ * attached to the page, use {@link #isShowing()} instead.
+ *
+ * @return <code>true</code> if the object is visible
+ * @see #setVisible(boolean)
+ */
+ @Override
+ public boolean isVisible() {
+ return !"hidden".equals(getElement().getStyle().getProperty("visibility"));
+ }
+
+ /**
+ * @deprecated Use {@link #onPreviewNativeEvent} instead
+ */
+ @Deprecated
+ public boolean onEventPreview(Event event) {
+ return true;
+ }
+
+ /**
+ * Popups get an opportunity to preview keyboard events before they are passed
+ * to a widget contained by the Popup.
+ *
+ * @param key the key code of the depressed key
+ * @param modifiers keyboard modifiers, as specified in
+ * {@link com.google.gwt.event.dom.client.KeyCodes}.
+ * @return <code>false</code> to suppress the event
+ * @deprecated Use {@link #onPreviewNativeEvent} instead
+ */
+ @Deprecated
+ public boolean onKeyDownPreview(char key, int modifiers) {
+ return true;
+ }
+
+ /**
+ * Popups get an opportunity to preview keyboard events before they are passed
+ * to a widget contained by the Popup.
+ *
+ * @param key the unicode character pressed
+ * @param modifiers keyboard modifiers, as specified in
+ * {@link com.google.gwt.event.dom.client.KeyCodes}.
+ * @return <code>false</code> to suppress the event
+ * @deprecated Use {@link #onPreviewNativeEvent} instead
+ */
+ @Deprecated
+ public boolean onKeyPressPreview(char key, int modifiers) {
+ return true;
+ }
+
+ /**
+ * Popups get an opportunity to preview keyboard events before they are passed
+ * to a widget contained by the Popup.
+ *
+ * @param key the key code of the released key
+ * @param modifiers keyboard modifiers, as specified in
+ * {@link com.google.gwt.event.dom.client.KeyCodes}.
+ * @return <code>false</code> to suppress the event
+ * @deprecated Use {@link #onPreviewNativeEvent} instead
+ */
+ @Deprecated
+ public boolean onKeyUpPreview(char key, int modifiers) {
+ return true;
+ }
+
+ /**
+ * Remove an autoHide partner.
+ *
+ * @param partner the auto hide partner to remove
+ */
+ public void removeAutoHidePartner(Element partner) {
+ assert partner != null : "partner cannot be null";
+ if (autoHidePartners != null) {
+ autoHidePartners.remove(partner);
+ }
+ }
+
+ /**
+ * @deprecated Use the {@link HandlerRegistration#removeHandler} method on the
+ * object returned by {@link #addCloseHandler} instead
+ */
+ @Deprecated
+ public void removePopupListener(PopupListener listener) {
+ throw new UnsupportedOperationException();
+ }
+
+ public void setAnimationEnabled(boolean enable) {
+ isAnimationEnabled = enable;
+ }
+
+ /**
+ * Enable or disable the autoHide feature. When enabled, the popup will be
+ * automatically hidden when the user clicks outside of it.
+ *
+ * @param autoHide true to enable autoHide, false to disable
+ */
+ public void setAutoHideEnabled(boolean autoHide) {
+ this.autoHide = autoHide;
+ }
+
+ /**
+ * Enable or disable autoHide on history change events. When enabled, the
+ * popup will be automatically hidden when the history token changes, such as
+ * when the user presses the browser's back button. Disabled by default.
+ *
+ * @param enabled true to enable, false to disable
+ */
+ public void setAutoHideOnHistoryEventsEnabled(boolean enabled) {
+ this.autoHideOnHistoryEvents = enabled;
+ }
+
+ /**
+ * When enabled, the background will be blocked with a semi-transparent pane
+ * the next time it is shown. If the PopupPanel is already visible, the glass
+ * will not be displayed until it is hidden and shown again.
+ *
+ * @param enabled true to enable, false to disable
+ */
+ public void setGlassEnabled(boolean enabled) {
+ this.isGlassEnabled = enabled;
+ if (enabled && glass == null) {
+ glass = Document.get().createDivElement();
+ glass.setClassName(glassStyleName);
+
+ glass.getStyle().setPosition(Position.ABSOLUTE);
+ glass.getStyle().setLeft(0, Unit.PX);
+ glass.getStyle().setTop(0, Unit.PX);
+ }
+ }
+
+ /**
+ * Sets the style name to be used on the glass element. By default, this is
+ * "gwt-PopupPanelGlass".
+ *
+ * @param glassStyleName the glass element's style name
+ */
+ public void setGlassStyleName(String glassStyleName) {
+ this.glassStyleName = glassStyleName;
+ if (glass != null) {
+ glass.setClassName(glassStyleName);
+ }
+ }
+
+ /**
+ * Sets the height of the panel's child widget. If the panel's child widget
+ * has not been set, the height passed in will be cached and used to set the
+ * height immediately after the child widget is set.
+ *
+ * <p>
+ * Note that subclasses may have a different behavior. A subclass may decide
+ * not to change the height of the child widget. It may instead decide to
+ * change the height of an internal panel widget, which contains the child
+ * widget.
+ * </p>
+ *
+ * @param height the object's new height, in CSS units (e.g. "10px", "1em")
+ */
+ @Override
+ public void setHeight(String height) {
+ desiredHeight = height;
+ maybeUpdateSize();
+ // If the user cleared the size, revert to not trying to control children.
+ if (height.length() == 0) {
+ desiredHeight = null;
+ }
+ }
+
+ /**
+ * When the popup is modal, keyboard or mouse events that do not target the
+ * PopupPanel or its children will be ignored.
+ *
+ * @param modal true to make the popup modal
+ */
+ public void setModal(boolean modal) {
+ this.modal = modal;
+ }
+
+ /**
+ * Sets the popup's position relative to the browser's client area. The
+ * popup's position may be set before calling {@link #show()}.
+ *
+ * @param left the left position, in pixels
+ * @param top the top position, in pixels
+ */
+ public void setPopupPosition(int left, int top) {
+ // Save the position of the popup
+ leftPosition = left;
+ topPosition = top;
+
+ // Account for the difference between absolute position and the
+ // body's positioning context.
+ left -= Document.get().getBodyOffsetLeft();
+ top -= Document.get().getBodyOffsetTop();
+
+ // Set the popup's position manually, allowing setPopupPosition() to be
+ // called before show() is called (so a popup can be positioned without it
+ // 'jumping' on the screen).
+ Element elem = getElement();
+ elem.getStyle().setPropertyPx("left", left);
+ elem.getStyle().setPropertyPx("top", top);
+ }
+
+ /**
+ * Sets the popup's position using a {@link PositionCallback}, and shows the
+ * popup. The callback allows positioning to be performed based on the
+ * offsetWidth and offsetHeight of the popup, which are normally not available
+ * until the popup is showing. By positioning the popup before it is shown,
+ * the popup will not jump from its original position to the new position.
+ *
+ * @param callback the callback to set the position of the popup
+ * @see PositionCallback#setPosition(int offsetWidth, int offsetHeight)
+ */
+ public void setPopupPositionAndShow(PositionCallback callback) {
+ setVisible(false);
+ show();
+ callback.setPosition(getOffsetWidth(), getOffsetHeight());
+ setVisible(true);
+ }
+
+ /**
+ * <p>
+ * When enabled, the popup will preview all native events, even if another
+ * popup was opened after this one.
+ * </p>
+ * <p>
+ * If autoHide is enabled, enabling this feature will cause the popup to
+ * autoHide even if another non-modal popup was shown after it. If this
+ * feature is disabled, the popup will only autoHide if it was the last popup
+ * opened.
+ * </p>
+ *
+ * @param previewAllNativeEvents true to enable, false to disable
+ */
+ public void setPreviewingAllNativeEvents(boolean previewAllNativeEvents) {
+ this.previewAllNativeEvents = previewAllNativeEvents;
+ }
+
+ @Override
+ public void setTitle(String title) {
+ Element containerElement = getContainerElement();
+ if (title == null || title.length() == 0) {
+ containerElement.removeAttribute("title");
+ } else {
+ containerElement.setAttribute("title", title);
+ }
+ }
+
+ /**
+ * Sets whether this object is visible. This method just sets the
+ * <code>visibility</code> style attribute. You need to call {@link #show()}
+ * to actually attached/detach the {@link PopupPanel} to the page.
+ *
+ * @param visible <code>true</code> to show the object, <code>false</code> to
+ * hide it
+ * @see #show()
+ * @see #hide()
+ */
+ @Override
+ public void setVisible(boolean visible) {
+ // We use visibility here instead of UIObject's default of display
+ // Because the panel is absolutely positioned, this will not create
+ // "holes" in displayed contents and it allows normal layout passes
+ // to occur so the size of the PopupPanel can be reliably determined.
+ getElement().getStyle().setProperty("visibility", visible ? "visible" : "hidden");
+
+ // If the PopupImpl creates an iframe shim, it's also necessary to hide it
+ // as well.
+ if (glass != null) {
+ glass.getStyle().setProperty("visibility", visible ? "visible" : "hidden");
+ }
+ }
+
+ @Override
+ public void setWidget(Widget w) {
+ super.setWidget(w);
+ maybeUpdateSize();
+ }
+
+ /**
+ * Sets the width of the panel's child widget. If the panel's child widget has
+ * not been set, the width passed in will be cached and used to set the width
+ * immediately after the child widget is set.
+ *
+ * <p>
+ * Note that subclasses may have a different behavior. A subclass may decide
+ * not to change the width of the child widget. It may instead decide to
+ * change the width of an internal panel widget, which contains the child
+ * widget.
+ * </p>
+ *
+ * @param width the object's new width, in CSS units (e.g. "10px", "1em")
+ */
+ @Override
+ public void setWidth(String width) {
+ desiredWidth = width;
+ maybeUpdateSize();
+ // If the user cleared the size, revert to not trying to control children.
+ if (width.length() == 0) {
+ desiredWidth = null;
+ }
+ }
+
+ /**
+ * Shows the popup and attach it to the page. It must have a child widget
+ * before this method is called.
+ */
+ public void show() {
+ if (showing) {
+ return;
+ } else if (isAttached()) {
+ // The popup is attached directly to another panel, so we need to remove
+ // it from its parent before showing it. This is a weird use case, but
+ // since PopupPanel is a Widget, its legal.
+ this.removeFromParent();
+ }
+ resizeAnimation.setState(true, false);
+ }
+
+ /**
+ * Normally, the popup is positioned directly below the relative target, with
+ * its left edge aligned with the left edge of the target. Depending on the
+ * width and height of the popup and the distance from the target to the
+ * bottom and right edges of the window, the popup may be displayed directly
+ * above the target, and/or its right edge may be aligned with the right edge
+ * of the target.
+ *
+ * @param target the target to show the popup below
+ */
+ public final void showRelativeTo(final UIObject target) {
+ // Set the position of the popup right before it is shown.
+ setPopupPositionAndShow(new PositionCallback() {
+ public void setPosition(int offsetWidth, int offsetHeight) {
+ position(target, offsetWidth, offsetHeight);
+ }
+ });
+ }
+
+ @Override
+ protected com.google.gwt.user.client.Element getContainerElement() {
+ return impl.getContainerElement(getPopupImplElement()).cast();
+ }
+
+ /**
+ * Get the glass element used by this {@link PopupPanel}. The element is not
+ * created until it is enabled via {@link #setGlassEnabled(boolean)}.
+ *
+ * @return the glass element, or null if not created
+ */
+ protected Element getGlassElement() {
+ return glass;
+ }
+
+ @Override
+ protected com.google.gwt.user.client.Element getStyleElement() {
+ return impl.getStyleElement(getPopupImplElement()).cast();
+ }
+
+ protected void onPreviewNativeEvent(NativePreviewEvent event) {
+ // Cancel the event based on the deprecated onEventPreview() method
+ if (event.isFirstHandler()
+ && !onEventPreview(Event.as(event.getNativeEvent()))) {
+ event.cancel();
+ }
+ }
+
+ @Override
+ protected void onUnload() {
+ super.onUnload();
+
+ // Just to be sure, we perform cleanup when the popup is unloaded (i.e.
+ // removed from the DOM). This is normally taken care of in hide(), but it
+ // can be missed if someone removes the popup directly from the RootPanel.
+ if (isShowing()) {
+ resizeAnimation.setState(false, true);
+ }
+ }
+
+ /**
+ * We control size by setting our child widget's size. However, if we don't
+ * currently have a child, we record the size the user wanted so that when we
+ * do get a child, we can set it correctly. Until size is explicitly cleared,
+ * any child put into the popup will be given that size.
+ */
+ void maybeUpdateSize() {
+ // For subclasses of PopupPanel, we want the default behavior of setWidth
+ // and setHeight to change the dimensions of PopupPanel's child widget.
+ // We do this because PopupPanel's child widget is the first widget in
+ // the hierarchy which provides structure to the panel. DialogBox is
+ // an example of this. We want to set the dimensions on DialogBox's
+ // FlexTable, which is PopupPanel's child widget. However, it is not
+ // DialogBox's child widget. To make sure that we are actually getting
+ // PopupPanel's child widget, we have to use super.getWidget().
+ Widget w = super.getWidget();
+ if (w != null) {
+ if (desiredHeight != null) {
+ w.setHeight(desiredHeight);
+ }
+ if (desiredWidth != null) {
+ w.setWidth(desiredWidth);
+ }
+ }
+ }
+
+ /**
+ * Sets the animation used to animate this popup. Used by gwt-incubator to
+ * allow DropDownPanel to override the default popup animation. Not protected
+ * because the exact API may change in gwt 1.6.
+ *
+ * @param animation the animation to use for this popup
+ */
+ void setAnimation(ResizeAnimation animation) {
+ resizeAnimation = animation;
+ }
+
+ /**
+ * Set the type of animation to use when opening and closing the popup.
+ *
+ * @see AnimationType
+ * @param type the type of animation to use
+ */
+ public void setAnimationType(AnimationType type) {
+ animType = type != null ? type : AnimationType.CENTER;
+ }
+
+ /**
+ * Get the type of animation to use when opening and closing the popup.
+ *
+ * @see AnimationType
+ * @return the type of animation used
+ */
+ public AnimationType getAnimationType() {
+ return animType;
+ }
+
+ /**
+ * Remove focus from an Element.
+ *
+ * @param elt The Element on which <code>blur()</code> will be invoked
+ */
+ private native void blur(Element elt) /*-{
+ // Issue 2390: blurring the body causes IE to disappear to the background
+ if (elt.blur && elt != $doc.body) {
+ elt.blur();
+ }
+ }-*/;
+
+ /**
+ * Does the event target one of the partner elements?
+ *
+ * @param event the native event
+ * @return true if the event targets a partner
+ */
+ private boolean eventTargetsPartner(NativeEvent event) {
+ if (autoHidePartners == null) {
+ return false;
+ }
+
+ EventTarget target = event.getEventTarget();
+ if (Element.is(target)) {
+ for (Element elem : autoHidePartners) {
+ if (elem.isOrHasChild(Element.as(target))) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Does the event target this popup?
+ *
+ * @param event the native event
+ * @return true if the event targets the popup
+ */
+ private boolean eventTargetsPopup(NativeEvent event) {
+ EventTarget target = event.getEventTarget();
+ if (Element.is(target)) {
+ return getElement().isOrHasChild(Element.as(target));
+ }
+ return false;
+ }
+
+ /**
+ * Get the element that {@link PopupImpl} uses. PopupImpl creates an element
+ * that goes inside of the outer element, so all methods in PopupImpl are
+ * relative to the first child of the outer element, not the outer element
+ * itself.
+ *
+ * @return the Element that {@link PopupImpl} creates and expects
+ */
+ private com.google.gwt.user.client.Element getPopupImplElement() {
+ return DOM.getFirstChild(super.getContainerElement());
+ }
+
+ /**
+ * Positions the popup, called after the offset width and height of the popup
+ * are known.
+ *
+ * @param relativeObject the ui object to position relative to
+ * @param offsetWidth the drop down's offset width
+ * @param offsetHeight the drop down's offset height
+ */
+ private void position(final UIObject relativeObject, int offsetWidth,
+ int offsetHeight) {
+ // Calculate left position for the popup. The computation for
+ // the left position is bidi-sensitive.
+
+ int textBoxOffsetWidth = relativeObject.getOffsetWidth();
+
+ // Compute the difference between the popup's width and the
+ // textbox's width
+ int offsetWidthDiff = offsetWidth - textBoxOffsetWidth;
+
+ int left;
+
+ if (LocaleInfo.getCurrentLocale().isRTL()) { // RTL case
+
+ int textBoxAbsoluteLeft = relativeObject.getAbsoluteLeft();
+
+ // Right-align the popup. Note that this computation is
+ // valid in the case where offsetWidthDiff is negative.
+ left = textBoxAbsoluteLeft - offsetWidthDiff;
+
+ // If the suggestion popup is not as wide as the text box, always
+ // align to the right edge of the text box. Otherwise, figure out whether
+ // to right-align or left-align the popup.
+ if (offsetWidthDiff > 0) {
+
+ // Make sure scrolling is taken into account, since
+ // box.getAbsoluteLeft() takes scrolling into account.
+ int windowRight = Window.getClientWidth() + Window.getScrollLeft();
+ int windowLeft = Window.getScrollLeft();
+
+ // Compute the left value for the right edge of the textbox
+ int textBoxLeftValForRightEdge = textBoxAbsoluteLeft
+ + textBoxOffsetWidth;
+
+ // Distance from the right edge of the text box to the right edge
+ // of the window
+ int distanceToWindowRight = windowRight - textBoxLeftValForRightEdge;
+
+ // Distance from the right edge of the text box to the left edge of the
+ // window
+ int distanceFromWindowLeft = textBoxLeftValForRightEdge - windowLeft;
+
+ // If there is not enough space for the overflow of the popup's
+ // width to the right of the text box and there IS enough space for the
+ // overflow to the right of the text box, then left-align the popup.
+ // However, if there is not enough space on either side, stick with
+ // right-alignment.
+ if (distanceFromWindowLeft < offsetWidth
+ && distanceToWindowRight >= offsetWidthDiff) {
+ // Align with the left edge of the text box.
+ left = textBoxAbsoluteLeft;
+ }
+ }
+ } else { // LTR case
+
+ // Left-align the popup.
+ left = relativeObject.getAbsoluteLeft();
+
+ // If the suggestion popup is not as wide as the text box, always align to
+ // the left edge of the text box. Otherwise, figure out whether to
+ // left-align or right-align the popup.
+ if (offsetWidthDiff > 0) {
+ // Make sure scrolling is taken into account, since
+ // box.getAbsoluteLeft() takes scrolling into account.
+ int windowRight = Window.getClientWidth() + Window.getScrollLeft();
+ int windowLeft = Window.getScrollLeft();
+
+ // Distance from the left edge of the text box to the right edge
+ // of the window
+ int distanceToWindowRight = windowRight - left;
+
+ // Distance from the left edge of the text box to the left edge of the
+ // window
+ int distanceFromWindowLeft = left - windowLeft;
+
+ // If there is not enough space for the overflow of the popup's
+ // width to the right of hte text box, and there IS enough space for the
+ // overflow to the left of the text box, then right-align the popup.
+ // However, if there is not enough space on either side, then stick with
+ // left-alignment.
+ if (distanceToWindowRight < offsetWidth
+ && distanceFromWindowLeft >= offsetWidthDiff) {
+ // Align with the right edge of the text box.
+ left -= offsetWidthDiff;
+ }
+ }
+ }
+
+ // Calculate top position for the popup
+
+ int top = relativeObject.getAbsoluteTop();
+
+ // Make sure scrolling is taken into account, since
+ // box.getAbsoluteTop() takes scrolling into account.
+ int windowTop = Window.getScrollTop();
+ int windowBottom = Window.getScrollTop() + Window.getClientHeight();
+
+ // Distance from the top edge of the window to the top edge of the
+ // text box
+ int distanceFromWindowTop = top - windowTop;
+
+ // Distance from the bottom edge of the window to the bottom edge of
+ // the text box
+ int distanceToWindowBottom = windowBottom
+ - (top + relativeObject.getOffsetHeight());
+
+ // If there is not enough space for the popup's height below the text
+ // box and there IS enough space for the popup's height above the text
+ // box, then position the popup above the text box. However, if there
+ // is not enough space on either side, then stick with displaying the
+ // popup below the text box.
+ if (distanceToWindowBottom < offsetHeight
+ && distanceFromWindowTop >= offsetHeight) {
+ top -= offsetHeight;
+ } else {
+ // Position above the text box
+ top += relativeObject.getOffsetHeight();
+ }
+ setPopupPosition(left, top);
+ }
+
+ /**
+ * Preview the {@link NativePreviewEvent}.
+ *
+ * @param event the {@link NativePreviewEvent}
+ */
+ private void previewNativeEvent(NativePreviewEvent event) {
+ // If the event has been canceled or consumed, ignore it
+ if (event.isCanceled() || (!previewAllNativeEvents && event.isConsumed())) {
+ // We need to ensure that we cancel the event even if its been consumed so
+ // that popups lower on the stack do not auto hide
+ if (modal) {
+ event.cancel();
+ }
+ return;
+ }
+
+ // Fire the event hook and return if the event is canceled
+ onPreviewNativeEvent(event);
+ if (event.isCanceled()) {
+ return;
+ }
+
+ // If the event targets the popup or the partner, consume it
+ Event nativeEvent = Event.as(event.getNativeEvent());
+ boolean eventTargetsPopupOrPartner = eventTargetsPopup(nativeEvent)
+ || eventTargetsPartner(nativeEvent);
+ if (eventTargetsPopupOrPartner) {
+ event.consume();
+ }
+
+ // Cancel the event if it doesn't target the modal popup. Note that the
+ // event can be both canceled and consumed.
+ if (modal) {
+ event.cancel();
+ }
+
+ // Switch on the event type
+ int type = nativeEvent.getTypeInt();
+ switch (type) {
+ case Event.ONKEYDOWN: {
+ if (!onKeyDownPreview((char) nativeEvent.getKeyCode(),
+ KeyboardListenerCollection.getKeyboardModifiers(nativeEvent))) {
+ event.cancel();
+ }
+ return;
+ }
+ case Event.ONKEYUP: {
+ if (!onKeyUpPreview((char) nativeEvent.getKeyCode(),
+ KeyboardListenerCollection.getKeyboardModifiers(nativeEvent))) {
+ event.cancel();
+ }
+ return;
+ }
+ case Event.ONKEYPRESS: {
+ if (!onKeyPressPreview((char) nativeEvent.getKeyCode(),
+ KeyboardListenerCollection.getKeyboardModifiers(nativeEvent))) {
+ event.cancel();
+ }
+ return;
+ }
+
+ case Event.ONMOUSEDOWN:
+ case Event.ONTOUCHSTART:
+ // Don't eat events if event capture is enabled, as this can
+ // interfere with dialog dragging, for example.
+ if (DOM.getCaptureElement() != null) {
+ event.consume();
+ return;
+ }
+
+ if (!eventTargetsPopupOrPartner && autoHide) {
+ hide(true);
+ return;
+ }
+ break;
+ case Event.ONMOUSEUP:
+ case Event.ONMOUSEMOVE:
+ case Event.ONCLICK:
+ case Event.ONDBLCLICK:
+ case Event.ONTOUCHEND: {
+ // Don't eat events if event capture is enabled, as this can
+ // interfere with dialog dragging, for example.
+ if (DOM.getCaptureElement() != null) {
+ event.consume();
+ return;
+ }
+ break;
+ }
+
+ case Event.ONFOCUS: {
+ Element target = nativeEvent.getTarget();
+ if (modal && !eventTargetsPopupOrPartner && (target != null)) {
+ blur(target);
+ event.cancel();
+ return;
+ }
+ break;
+ }
+ }
+ }
+
+ /**
+ * Register or unregister the handlers used by {@link PopupPanel}.
+ */
+ private void updateHandlers() {
+ // Remove any existing handlers.
+ if (nativePreviewHandlerRegistration != null) {
+ nativePreviewHandlerRegistration.removeHandler();
+ nativePreviewHandlerRegistration = null;
+ }
+ if (historyHandlerRegistration != null) {
+ historyHandlerRegistration.removeHandler();
+ historyHandlerRegistration = null;
+ }
+
+ // Create handlers if showing.
+ if (showing) {
+ nativePreviewHandlerRegistration = Event.addNativePreviewHandler(new NativePreviewHandler() {
+ public void onPreviewNativeEvent(NativePreviewEvent event) {
+ previewNativeEvent(event);
+ }
+ });
+ historyHandlerRegistration = History.addValueChangeHandler(new ValueChangeHandler<String>() {
+ public void onValueChange(ValueChangeEvent<String> event) {
+ if (autoHideOnHistoryEvents) {
+ hide();
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/manager/client/src/main/webapp/3rdparty/sprintf/1.0.3/sprintf.min.js b/manager/client/src/main/webapp/3rdparty/sprintf/1.0.3/sprintf.min.js
new file mode 100644
index 000000000..dc61e51ad
--- /dev/null
+++ b/manager/client/src/main/webapp/3rdparty/sprintf/1.0.3/sprintf.min.js
@@ -0,0 +1,4 @@
+/*! sprintf-js | Alexandru Marasteanu <[email protected]> (http://alexei.ro/) | BSD-3-Clause */
+
+!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i<j[2].length;i++){if(!g.hasOwnProperty(j[2][i]))throw new Error(b("[sprintf] property '%s' does not exist",j[2][i]));g=g[j[2][i]]}else g=j[1]?f[j[1]]:f[n++];if("function"==c(g)&&(g=g()),e.not_string.test(j[8])&&e.not_json.test(j[8])&&"number"!=c(g)&&isNaN(g))throw new TypeError(b("[sprintf] expecting number but found %s",c(g)));switch(e.number.test(j[8])&&(r=g>=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"j":g=JSON.stringify(g,null,j[6]?parseInt(j[6]):0);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"g":g=j[7]?parseFloat(g).toPrecision(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}e.json.test(j[8])?q[q.length]=g:(!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g)}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window);
+//# sourceMappingURL=sprintf.min.map
\ No newline at end of file
diff --git a/manager/client/src/main/webapp/css/style.html b/manager/client/src/main/webapp/css/style.html
index 03882af01..4a4658238 100644
--- a/manager/client/src/main/webapp/css/style.html
+++ b/manager/client/src/main/webapp/css/style.html
@@ -535,4 +535,8 @@
.or-HighlightBackground {
}
+ .or-DatapointBrowser {
+ padding: 0.4em;
+ }
+
</style>
\ No newline at end of file
diff --git a/manager/client/src/main/webapp/css/theme.html b/manager/client/src/main/webapp/css/theme.html
index d29bce0a9..3bef5c844 100644
--- a/manager/client/src/main/webapp/css/theme.html
+++ b/manager/client/src/main/webapp/css/theme.html
@@ -365,4 +365,8 @@
border-color: transparent;
}
+ .or-DatapointBrowser {
+ background-color: var(--theme-white);
+ }
+
</style>
\ No newline at end of file
diff --git a/manager/client/src/main/webapp/index.html b/manager/client/src/main/webapp/index.html
index 554d5a3f7..24a986746 100644
--- a/manager/client/src/main/webapp/index.html
+++ b/manager/client/src/main/webapp/index.html
@@ -58,6 +58,8 @@
load.js("/static/3rdparty/chart-js/2.5.0/Chart.js"),
+ load.js("/static/3rdparty/sprintf/1.0.3/sprintf.min.js"),
+
load.import("/static/css/style.html"),
load.import("/static/css/theme.html"),
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index 973d38574..141a18845 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
@@ -246,6 +246,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
thing = assetStorageService.find(thingId, true);
thingAttributes = new AssetAttributes(thing);
ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
+ assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")));
assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")
.setValueAsDecimal(0.11).setValueTimestamp(now.minusDays(80).toEpochSecond() * 1000)));
assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")
@@ -287,7 +288,6 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")
.setValueAsDecimal(12.01).setValueTimestamp(now.toEpochSecond() * 1000 - 500)));
-
// ################################ Demo assets for 'customerA' realm ###################################
ServerAsset smartHome = new ServerAsset();
diff --git a/model/src/main/java/org/openremote/model/AttributeEvent.java b/model/src/main/java/org/openremote/model/AttributeEvent.java
index 35119933c..aec1f75c7 100644
--- a/model/src/main/java/org/openremote/model/AttributeEvent.java
+++ b/model/src/main/java/org/openremote/model/AttributeEvent.java
@@ -28,6 +28,29 @@ import org.openremote.model.event.shared.SharedEvent;
*/
public class AttributeEvent extends SharedEvent {
+ /**
+ * Processing of the attribute event depends on where the event originated from.
+ *
+ * TODO Use this as header in Camel messages for conditional routing
+ */
+ public enum Source {
+
+ /**
+ * The event was created by a client, it's a write request/actuator message.
+ */
+ SOUTHBOUND,
+
+ /**
+ * The event was created by internal processing, for example, as a rule consequence.
+ */
+ PROCESSING,
+
+ /**
+ * The event was created by a protocol, it's a value change on a sensor.
+ */
+ NORTHBOUND
+ }
+
static public class EntityIdFilter extends EventFilter<AttributeEvent> {
public static final String FILTER_TYPE = "attribute-entity-id";
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
index 140f1f49f..f6b232ccb 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
@@ -86,6 +86,18 @@ public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribut
return firstMetaItem(assetMeta.getName());
}
+ public String getLabel() {
+ return hasMetaItem(LABEL) ? firstMetaItem(LABEL).getValueAsString() : getName();
+ }
+
+ public String getFormat() {
+ return hasMetaItem(FORMAT) ? firstMetaItem(FORMAT).getValueAsString() : null;
+ }
+
+ public boolean isShowOnDashboard() {
+ return hasMetaItem(SHOWN_ON_DASHBOARD) && firstMetaItem(SHOWN_ON_DASHBOARD).isValueTrue();
+ }
+
public boolean isProtected() {
return hasMetaItem(PROTECTED) && firstMetaItem(PROTECTED).isValueTrue();
}
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index 7ad3ed8ca..37f9d4d82 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -22,10 +22,16 @@ package org.openremote.model.asset;
import elemental.json.JsonObject;
import org.hibernate.annotations.Formula;
import org.openremote.model.IdentifiableEntity;
+import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.geo.GeoJSONFeature;
+import org.openremote.model.geo.GeoJSONGeometry;
+import org.openremote.model.util.TextUtil;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
@@ -217,7 +223,7 @@ public class Asset implements IdentifiableEntity {
protected long version;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition= "TIMESTAMP WITH TIME ZONE")
+ @Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
@org.hibernate.annotations.CreationTimestamp
protected Date createdOn = new Date();
@@ -476,6 +482,32 @@ public class Asset implements IdentifiableEntity {
this.attributes = attributes;
}
+ /**
+ * This assumes {@link #getCoordinates} array index 0 is Lng and index 1 is Lat,
+ * which is true for PostGIS backend. Because Lat/Lng is the 'right way', we flip
+ * it here for display. Rounding to 5 decimal places gives us precision of about 1 meter.
+ */
+ public String getCoordinatesLabel() {
+ return
+ new BigDecimal(getCoordinates()[1]).setScale(5, RoundingMode.HALF_UP) + " " +
+ new BigDecimal(getCoordinates()[0]).setScale(5, RoundingMode.HALF_UP) + " Lat|Lng";
+ }
+
+ public boolean hasGeoFeature() {
+ return getCoordinates() != null && getCoordinates().length == 2;
+ }
+
+ public GeoJSON getGeoFeature(int maxNameLength) {
+ if (!hasGeoFeature())
+ return GeoJSON.EMPTY_FEATURE_COLLECTION;
+ return new GeoJSON().setType("FeatureCollection").setFeatures(
+ new GeoJSONFeature().setType("Feature")
+ .setProperty("id", getId())
+ .setProperty("title", TextUtil.ellipsize(getName(), maxNameLength))
+ .setGeometry(new GeoJSONGeometry().setPoint(getCoordinates()))
+ );
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 738556c11..e1eeeaa6b 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -49,7 +49,12 @@ public enum AssetMeta {
LABEL(ASSET_META_NAMESPACE + ":label", new Access(true, true, true), JsonType.STRING),
/**
- * Format string that can be used to render the attribute value, see {@link java.util.Formatter}.
+ * If there is a dashboard, some kind of attribute overview, should this attribute be shown.
+ */
+ SHOWN_ON_DASHBOARD(ASSET_META_NAMESPACE + ":showOnDashboard", new Access(true, true, true), JsonType.BOOLEAN),
+
+ /**
+ * Format string that can be used to render the attribute value, see https://github.com/alexei/sprintf.js.
*/
FORMAT(ASSET_META_NAMESPACE + ":format", new Access(true, false, true), JsonType.STRING),
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSON.java b/model/src/main/java/org/openremote/model/geo/GeoJSON.java
similarity index 98%
rename from manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSON.java
rename to model/src/main/java/org/openremote/model/geo/GeoJSON.java
index e0281f866..49c79f025 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSON.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSON.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.shared.map;
+package org.openremote.model.geo;
import elemental.json.Json;
import elemental.json.JsonArray;
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSONFeature.java b/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
similarity index 98%
rename from manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSONFeature.java
rename to model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
index 136f53933..eb6ec9b87 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSONFeature.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.shared.map;
+package org.openremote.model.geo;
import elemental.json.Json;
import elemental.json.JsonObject;
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSONGeometry.java b/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
similarity index 97%
rename from manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSONGeometry.java
rename to model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
index c096f9a9f..edf013982 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/map/GeoJSONGeometry.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.manager.shared.map;
+package org.openremote.model.geo;
import elemental.json.Json;
import elemental.json.JsonArray;
diff --git a/model/src/main/java/org/openremote/model/util/TextUtil.java b/model/src/main/java/org/openremote/model/util/TextUtil.java
index 2aee21db3..8daf219c3 100644
--- a/model/src/main/java/org/openremote/model/util/TextUtil.java
+++ b/model/src/main/java/org/openremote/model/util/TextUtil.java
@@ -124,4 +124,33 @@ public class TextUtil {
name = name.toLowerCase(Locale.ROOT);
return name;
}
+
+ private final static String PROPORTIONAL_FONT_THIN_CHARS = "[^iIl1\\.,']";
+
+ private static int textWidth(String str) {
+ return str.length() - str.replaceAll(PROPORTIONAL_FONT_THIN_CHARS, "").length() / 2;
+ }
+
+ public static String ellipsize(String text, int max) {
+ if (textWidth(text) <= max)
+ return text;
+ // Start by chopping off at the word before max
+ // This is an over-approximation due to thin-characters...
+ int end = text.lastIndexOf(' ', max - 3);
+ // Just one long word. Chop it off.
+ if (end == -1)
+ return text.substring(0, max - 3) + "...";
+ // Step forward as long as textWidth allows.
+ int newEnd = end;
+ do {
+ end = newEnd;
+ newEnd = text.indexOf(' ', end + 1);
+
+ // No more spaces.
+ if (newEnd == -1)
+ newEnd = text.length();
+ } while (textWidth(text.substring(0, newEnd) + "...") < max);
+ return text.substring(0, end) + "...";
+ }
+
}