RegionChooserBrowser.java 6.35 KB
Newer Older
eric.duminil's avatar
eric.duminil committed
1
2
3
4
5
6
7
8
package eu.simstadt.regionchooser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Eric Duminil's avatar
Eric Duminil committed
9
import java.util.logging.Logger;
eric.duminil's avatar
eric.duminil committed
10
import java.util.prefs.Preferences;
11
import java.util.stream.Stream;
12
import org.locationtech.jts.io.ParseException;
eric.duminil's avatar
eric.duminil committed
13
14
import com.ximpleware.NavException;
import com.ximpleware.XPathParseException;
15
import eu.simstadt.regionchooser.fast_xml_parser.ConvexHullCalculator;
16
import javafx.application.Platform;
eric.duminil's avatar
eric.duminil committed
17
18
19
20
21
22
23
24
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.concurrent.Worker.State;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
25
import javafx.stage.DirectoryChooser;
eric.duminil's avatar
eric.duminil committed
26
27
28
29
30
31
32
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import netscape.javascript.JSObject;


public class RegionChooserBrowser extends Region
{
Eric Duminil's avatar
Eric Duminil committed
33
	private static final Logger LOGGER = Logger.getLogger(RegionChooserBrowser.class.getName());
34
	private static final String PREF_RECENT_REPOSITORY = "RECENT_REPOSITORY";
35
	private static final int BUFFER = 1024;
Eric Duminil's avatar
Eric Duminil committed
36

eric.duminil's avatar
eric.duminil committed
37
38
39
40
41
42
43
44
45
	/**
	 * JavaFX Backend for RegionChooser. Inside simstadt_openlayers.js frontend, this class is available as `fxapp`.
	 */
	public class JavaScriptFXBridge
	{
		private Path repo;

		public JavaScriptFXBridge() {
			Preferences userPrefs = Preferences.userRoot().node("/eu/simstadt/desktop");
46
			String repoString = userPrefs.get(PREF_RECENT_REPOSITORY, "../TestRepository");
Eric Duminil's avatar
Eric Duminil committed
47
			repo = Paths.get(repoString);
eric.duminil's avatar
eric.duminil committed
48
49
		}

50
51
52
53
		/**
		 * Launches a background thread in which the hull gets extracted for every CityGML file. The hull gets sent back
		 * to the JS app in order to be displayed.
		 * 
Eric Duminil's avatar
Eric Duminil committed
54
55
		 * NOTE: To be very honest, I don't really understand concurrency in JavaFX. Eric
		 * 
56
57
58
59
60
61
62
		 */
		public void refreshHulls() {
			//NOTE: Could add progress bar?
			Task<Void> task = new Task<Void>() {
				@Override
				public Void call() throws IOException {
					ConvexHullCalculator.extractHullsForEveryCityGML(repo,
Eric Duminil's avatar
Eric Duminil committed
63
							hullKML -> Platform.runLater(() -> jsApp.call("addCityGmlHull", hullKML)));
64
65
66
67
					return null;
				}
			};

68
69
70
71
			task.setOnRunning(e -> {
				jsApp.call("display", "Importing citgyml. Please wait.");
				jsApp.call("init");
			});
72

Eric Duminil's avatar
Eric Duminil committed
73
			task.setOnSucceeded(e -> jsApp.call("ready"));
74
75

			new Thread(task).start();
76
77
		}

78
		public void downloadRegionFromCityGMLs(String wktPolygon, String project, String csvCitygmls, String srsName)
79
				throws IOException, ParseException, XPathParseException, NavException {
80
			//NOTE: It doesn't seem possible to pass arrays or list from JS to Java. So csvCitygmls contains names separated by ;
81
82
83
84
			Path[] paths = Stream.of(csvCitygmls.split(";")).map(s -> citygmlPath(project, s)).toArray(Path[]::new);

			StringBuilder sb = RegionExtractor.selectRegionDirectlyFromCityGML(wktPolygon, srsName, paths);

Eric Duminil's avatar
Eric Duminil committed
85
86
			File buildingIdsFile = selectSaveFileWithDialog(project,
					csvCitygmls.replace(";", "_").replace(".gml", ""), "selected_region");
eric.duminil's avatar
eric.duminil committed
87
			if (buildingIdsFile != null) {
Eric Duminil's avatar
Eric Duminil committed
88
				try (BufferedWriter writer = Files.newBufferedWriter(buildingIdsFile.toPath())) {
89
90
91
92
93
94
					char[] chars = new char[BUFFER];
					for (int aPosStart = 0; aPosStart < sb.length(); aPosStart += BUFFER) {
						int chunk = Math.min(BUFFER, sb.length() - aPosStart);
						sb.getChars(aPosStart, aPosStart + chunk, chars, 0);
						writer.write(chars, 0, chunk);
					}
Eric Duminil's avatar
Eric Duminil committed
95
				}
eric.duminil's avatar
eric.duminil committed
96
97
98
			}
		}

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
		public void selectRepository() {
			Preferences userPrefs = Preferences.userRoot().node("/eu/simstadt/desktop");
			String currentRepo = userPrefs.get(PREF_RECENT_REPOSITORY, "../TestRepository");

			DirectoryChooser fileChooser = new DirectoryChooser();
			Stage mainStage = (Stage) RegionChooserBrowser.this.getScene().getWindow();
			fileChooser.setTitle("Select Repository");
			fileChooser.setInitialDirectory(new File(currentRepo));
			File repoLocation = fileChooser.showDialog(mainStage);

			if (repoLocation != null) {
				repo = repoLocation.toPath();
				userPrefs.put(PREF_RECENT_REPOSITORY, repo.toAbsolutePath().toString());
				LOGGER.info("Repository was set to " + repo);
				refreshHulls();
			} else {
				LOGGER.warning("No repository chosen.");
			}
		}

eric.duminil's avatar
eric.duminil committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
		private File selectSaveFileWithDialog(String project, String citygml, String suffix) {
			Stage mainStage = (Stage) RegionChooserBrowser.this.getScene().getWindow();
			FileChooser fileChooser = new FileChooser();
			fileChooser.setTitle("Save CITYGML ids");
			if (project != null) {
				fileChooser.setInitialDirectory(repo.resolve(project + ".proj").toFile());
			} else {
				fileChooser.setInitialDirectory(repo.toFile());
			}
			if (suffix.isEmpty()) {
				fileChooser.setInitialFileName(citygml);
			} else {
				fileChooser.setInitialFileName(citygml.replace(".", "_" + suffix + "."));
			}
			FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("GML files (*.gml)", "*.gml");
			fileChooser.getExtensionFilters().add(extFilter);
			return fileChooser.showSaveDialog(mainStage);
		}

		public void log(String text) {
Eric Duminil's avatar
Eric Duminil committed
139
			LOGGER.info(text);
eric.duminil's avatar
eric.duminil committed
140
141
		}

142
143
144
145
		public void warning(String text) {
			LOGGER.warning(text);
		}

eric.duminil's avatar
eric.duminil committed
146
147
148
149
150
151
152
153
		private Path citygmlPath(String project, String citygml) {
			return repo.resolve(project + ".proj").resolve(citygml);
		}

	}

	final WebView browser = new WebView();
	final WebEngine webEngine = browser.getEngine();
154
	final JavaScriptFXBridge fxapp = new JavaScriptFXBridge();
155
	private JSObject jsApp;
eric.duminil's avatar
eric.duminil committed
156
157
158
159
160
161
162
163
164
165

	public RegionChooserBrowser() {
		//apply the styles
		getStyleClass().add("browser");
		String url = RegionChooserFX.class.getResource("website/index.html").toExternalForm();
		webEngine.load(url); // load the web page
		// process page loading
		webEngine.getLoadWorker().stateProperty().addListener(
				(ObservableValue<? extends State> ov, State oldState, State newState) -> {
					if (newState == State.SUCCEEDED) {
166
167
						jsApp = (JSObject) webEngine.executeScript("regionChooser");
						jsApp.call("setFxApp", fxapp);
168
						fxapp.refreshHulls();
eric.duminil's avatar
eric.duminil committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
					}
				});
		//add the web view to the scene
		getChildren().add(browser);
	}

	@Override
	protected void layoutChildren() {
		double w = getWidth();
		double h = getHeight();
		layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
	}

	@Override
	protected double computePrefWidth(double height) {
184
		return 1024;
eric.duminil's avatar
eric.duminil committed
185
186
187
188
	}

	@Override
	protected double computePrefHeight(double width) {
189
		return 720;
eric.duminil's avatar
eric.duminil committed
190
191
	}
}