source: josm/trunk/src/org/openstreetmap/josm/gui/io/SaveLayersDialog.java@ 16267

Last change on this file since 16267 was 16267, checked in by simon04, 4 years ago

Use non-optional ImageResource without null check

  • Property svn:eol-style set to native
File size: 28.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.BorderLayout;
8import java.awt.Component;
9import java.awt.Dimension;
10import java.awt.Graphics2D;
11import java.awt.GraphicsEnvironment;
12import java.awt.GridBagConstraints;
13import java.awt.GridBagLayout;
14import java.awt.Image;
15import java.awt.event.ActionEvent;
16import java.awt.event.WindowAdapter;
17import java.awt.event.WindowEvent;
18import java.awt.image.BufferedImage;
19import java.beans.PropertyChangeEvent;
20import java.beans.PropertyChangeListener;
21import java.util.ArrayList;
22import java.util.List;
23import java.util.concurrent.CancellationException;
24import java.util.concurrent.ExecutionException;
25import java.util.concurrent.ExecutorService;
26import java.util.concurrent.Executors;
27import java.util.concurrent.Future;
28
29import javax.swing.AbstractAction;
30import javax.swing.DefaultListCellRenderer;
31import javax.swing.ImageIcon;
32import javax.swing.JButton;
33import javax.swing.JDialog;
34import javax.swing.JLabel;
35import javax.swing.JList;
36import javax.swing.JOptionPane;
37import javax.swing.JPanel;
38import javax.swing.JScrollPane;
39import javax.swing.ListCellRenderer;
40import javax.swing.WindowConstants;
41import javax.swing.event.TableModelEvent;
42import javax.swing.event.TableModelListener;
43
44import org.openstreetmap.josm.actions.SessionSaveAsAction;
45import org.openstreetmap.josm.actions.UploadAction;
46import org.openstreetmap.josm.gui.ExceptionDialogUtil;
47import org.openstreetmap.josm.gui.MainApplication;
48import org.openstreetmap.josm.gui.io.SaveLayersModel.Mode;
49import org.openstreetmap.josm.gui.layer.AbstractModifiableLayer;
50import org.openstreetmap.josm.gui.layer.Layer;
51import org.openstreetmap.josm.gui.progress.ProgressMonitor;
52import org.openstreetmap.josm.gui.progress.swing.SwingRenderingProgressMonitor;
53import org.openstreetmap.josm.gui.util.GuiHelper;
54import org.openstreetmap.josm.gui.util.WindowGeometry;
55import org.openstreetmap.josm.tools.GBC;
56import org.openstreetmap.josm.tools.ImageProvider;
57import org.openstreetmap.josm.tools.InputMapUtils;
58import org.openstreetmap.josm.tools.Logging;
59import org.openstreetmap.josm.tools.UserCancelException;
60import org.openstreetmap.josm.tools.Utils;
61
62/**
63 * Dialog that pops up when the user closes a layer with modified data.
64 *
65 * It asks for confirmation that all modification should be discarded and offers
66 * to save the layers to file or upload to server, depending on the type of layer.
67 */
68public class SaveLayersDialog extends JDialog implements TableModelListener {
69
70 /**
71 * The cause for requesting an action on unsaved modifications
72 */
73 public enum Reason {
74 /** deleting a layer */
75 DELETE,
76 /** exiting JOSM */
77 EXIT,
78 /** restarting JOSM */
79 RESTART
80 }
81
82 private enum UserAction {
83 /** save/upload layers was successful, proceed with operation */
84 PROCEED,
85 /** save/upload of layers was not successful or user canceled operation */
86 CANCEL
87 }
88
89 private final SaveLayersModel model = new SaveLayersModel();
90 private UserAction action = UserAction.CANCEL;
91 private final UploadAndSaveProgressRenderer pnlUploadLayers = new UploadAndSaveProgressRenderer();
92
93 private final SaveAndProceedAction saveAndProceedAction = new SaveAndProceedAction();
94 private final SaveSessionAction saveSessionAction = new SaveSessionAction();
95 private final DiscardAndProceedAction discardAndProceedAction = new DiscardAndProceedAction();
96 private final CancelAction cancelAction = new CancelAction();
97 private transient SaveAndUploadTask saveAndUploadTask;
98
99 private final JButton saveAndProceedActionButton = new JButton(saveAndProceedAction);
100
101 /**
102 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) before data layers deletion.
103 *
104 * @param selectedLayers The layers to check. Only instances of {@link AbstractModifiableLayer} are considered.
105 * @param reason the cause for requesting an action on unsaved modifications
106 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations.
107 * {@code false} if the user cancels.
108 * @since 11093
109 */
110 public static boolean saveUnsavedModifications(Iterable<? extends Layer> selectedLayers, Reason reason) {
111 if (!GraphicsEnvironment.isHeadless()) {
112 SaveLayersDialog dialog = new SaveLayersDialog(MainApplication.getMainFrame());
113 List<AbstractModifiableLayer> layersWithUnmodifiedChanges = new ArrayList<>();
114 for (Layer l: selectedLayers) {
115 if (!(l instanceof AbstractModifiableLayer)) {
116 continue;
117 }
118 AbstractModifiableLayer odl = (AbstractModifiableLayer) l;
119 if (odl.isModified() &&
120 ((!odl.isSavable() && !odl.isUploadable()) ||
121 odl.requiresSaveToFile() ||
122 (odl.requiresUploadToServer() && !odl.isUploadDiscouraged()))) {
123 layersWithUnmodifiedChanges.add(odl);
124 }
125 }
126 dialog.prepareForSavingAndUpdatingLayers(reason);
127 if (!layersWithUnmodifiedChanges.isEmpty()) {
128 dialog.getModel().populate(layersWithUnmodifiedChanges);
129 dialog.setVisible(true);
130 switch(dialog.getUserAction()) {
131 case PROCEED: return true;
132 case CANCEL:
133 default: return false;
134 }
135 }
136 dialog.closeDialog();
137 }
138
139 return true;
140 }
141
142 /**
143 * Constructs a new {@code SaveLayersDialog}.
144 * @param parent parent component
145 */
146 public SaveLayersDialog(Component parent) {
147 super(GuiHelper.getFrameForComponent(parent), ModalityType.DOCUMENT_MODAL);
148 build();
149 }
150
151 /**
152 * builds the GUI
153 */
154 protected void build() {
155 WindowGeometry geometry = WindowGeometry.centerOnScreen(new Dimension(650, 300));
156 geometry.applySafe(this);
157 getContentPane().setLayout(new BorderLayout());
158
159 SaveLayersTable table = new SaveLayersTable(model);
160 JScrollPane pane = new JScrollPane(table);
161 model.addPropertyChangeListener(table);
162 table.getModel().addTableModelListener(this);
163
164 getContentPane().add(pane, BorderLayout.CENTER);
165 getContentPane().add(buildButtonRow(), BorderLayout.SOUTH);
166
167 addWindowListener(new WindowClosingAdapter());
168 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
169 }
170
171 /**
172 * builds the button row
173 *
174 * @return the panel with the button row
175 */
176 protected JPanel buildButtonRow() {
177 JPanel pnl = new JPanel(new GridBagLayout());
178
179 model.addPropertyChangeListener(saveAndProceedAction);
180 pnl.add(saveAndProceedActionButton, GBC.std(0, 0).insets(5, 5, 0, 0).fill(GBC.HORIZONTAL));
181
182 pnl.add(new JButton(saveSessionAction), GBC.std(1, 0).insets(5, 5, 5, 0).fill(GBC.HORIZONTAL));
183
184 model.addPropertyChangeListener(discardAndProceedAction);
185 pnl.add(new JButton(discardAndProceedAction), GBC.std(0, 1).insets(5, 5, 0, 5).fill(GBC.HORIZONTAL));
186
187 pnl.add(new JButton(cancelAction), GBC.std(1, 1).insets(5, 5, 5, 5).fill(GBC.HORIZONTAL));
188
189 JPanel pnl2 = new JPanel(new BorderLayout());
190 pnl2.add(pnlUploadLayers, BorderLayout.CENTER);
191 model.addPropertyChangeListener(pnlUploadLayers);
192 pnl2.add(pnl, BorderLayout.SOUTH);
193 return pnl2;
194 }
195
196 public void prepareForSavingAndUpdatingLayers(final Reason reason) {
197 switch (reason) {
198 case EXIT:
199 setTitle(tr("Unsaved changes - Save/Upload before exiting?"));
200 break;
201 case DELETE:
202 setTitle(tr("Unsaved changes - Save/Upload before deleting?"));
203 break;
204 case RESTART:
205 setTitle(tr("Unsaved changes - Save/Upload before restarting?"));
206 break;
207 }
208 this.saveAndProceedAction.initForReason(reason);
209 this.discardAndProceedAction.initForReason(reason);
210 }
211
212 public UserAction getUserAction() {
213 return this.action;
214 }
215
216 public SaveLayersModel getModel() {
217 return model;
218 }
219
220 protected void launchSafeAndUploadTask() {
221 ProgressMonitor monitor = new SwingRenderingProgressMonitor(pnlUploadLayers);
222 monitor.beginTask(tr("Uploading and saving modified layers ..."));
223 this.saveAndUploadTask = new SaveAndUploadTask(model, monitor);
224 new Thread(saveAndUploadTask, saveAndUploadTask.getClass().getName()).start();
225 }
226
227 protected void cancelSafeAndUploadTask() {
228 if (this.saveAndUploadTask != null) {
229 this.saveAndUploadTask.cancel();
230 }
231 model.setMode(Mode.EDITING_DATA);
232 }
233
234 private static class LayerListWarningMessagePanel extends JPanel {
235 static final class LayerCellRenderer implements ListCellRenderer<SaveLayerInfo> {
236 private final DefaultListCellRenderer def = new DefaultListCellRenderer();
237
238 @Override
239 public Component getListCellRendererComponent(JList<? extends SaveLayerInfo> list, SaveLayerInfo info, int index,
240 boolean isSelected, boolean cellHasFocus) {
241 def.setIcon(info.getLayer().getIcon());
242 def.setText(info.getName());
243 return def;
244 }
245 }
246
247 private final JLabel lblMessage = new JLabel();
248 private final JList<SaveLayerInfo> lstLayers = new JList<>();
249
250 LayerListWarningMessagePanel(String msg, List<SaveLayerInfo> infos) {
251 super(new GridBagLayout());
252 build();
253 lblMessage.setText(msg);
254 lstLayers.setListData(infos.toArray(new SaveLayerInfo[0]));
255 }
256
257 protected void build() {
258 GridBagConstraints gc = new GridBagConstraints();
259 gc.gridx = 0;
260 gc.gridy = 0;
261 gc.fill = GridBagConstraints.HORIZONTAL;
262 gc.weightx = 1.0;
263 gc.weighty = 0.0;
264 add(lblMessage, gc);
265 lblMessage.setHorizontalAlignment(JLabel.LEFT);
266 lstLayers.setCellRenderer(new LayerCellRenderer());
267 gc.gridx = 0;
268 gc.gridy = 1;
269 gc.fill = GridBagConstraints.HORIZONTAL;
270 gc.weightx = 1.0;
271 gc.weighty = 1.0;
272 add(lstLayers, gc);
273 }
274 }
275
276 private static void warn(String msg, List<SaveLayerInfo> infos, String title) {
277 JPanel panel = new LayerListWarningMessagePanel(msg, infos);
278 JOptionPane.showConfirmDialog(MainApplication.getMainFrame(), panel, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
279 }
280
281 protected static void warnLayersWithConflictsAndUploadRequest(List<SaveLayerInfo> infos) {
282 warn(trn("<html>{0} layer has unresolved conflicts.<br>"
283 + "Either resolve them first or discard the modifications.<br>"
284 + "Layer with conflicts:</html>",
285 "<html>{0} layers have unresolved conflicts.<br>"
286 + "Either resolve them first or discard the modifications.<br>"
287 + "Layers with conflicts:</html>",
288 infos.size(),
289 infos.size()),
290 infos, tr("Unsaved data and conflicts"));
291 }
292
293 protected static void warnLayersWithoutFilesAndSaveRequest(List<SaveLayerInfo> infos) {
294 warn(trn("<html>{0} layer needs saving but has no associated file.<br>"
295 + "Either select a file for this layer or discard the changes.<br>"
296 + "Layer without a file:</html>",
297 "<html>{0} layers need saving but have no associated file.<br>"
298 + "Either select a file for each of them or discard the changes.<br>"
299 + "Layers without a file:</html>",
300 infos.size(),
301 infos.size()),
302 infos, tr("Unsaved data and missing associated file"));
303 }
304
305 protected static void warnLayersWithIllegalFilesAndSaveRequest(List<SaveLayerInfo> infos) {
306 warn(trn("<html>{0} layer needs saving but has an associated file<br>"
307 + "which cannot be written.<br>"
308 + "Either select another file for this layer or discard the changes.<br>"
309 + "Layer with a non-writable file:</html>",
310 "<html>{0} layers need saving but have associated files<br>"
311 + "which cannot be written.<br>"
312 + "Either select another file for each of them or discard the changes.<br>"
313 + "Layers with non-writable files:</html>",
314 infos.size(),
315 infos.size()),
316 infos, tr("Unsaved data non-writable files"));
317 }
318
319 static boolean confirmSaveLayerInfosOK(SaveLayersModel model) {
320 List<SaveLayerInfo> layerInfos = model.getLayersWithConflictsAndUploadRequest();
321 if (!layerInfos.isEmpty()) {
322 warnLayersWithConflictsAndUploadRequest(layerInfos);
323 return false;
324 }
325
326 layerInfos = model.getLayersWithoutFilesAndSaveRequest();
327 if (!layerInfos.isEmpty()) {
328 warnLayersWithoutFilesAndSaveRequest(layerInfos);
329 return false;
330 }
331
332 layerInfos = model.getLayersWithIllegalFilesAndSaveRequest();
333 if (!layerInfos.isEmpty()) {
334 warnLayersWithIllegalFilesAndSaveRequest(layerInfos);
335 return false;
336 }
337
338 return true;
339 }
340
341 protected void setUserAction(UserAction action) {
342 this.action = action;
343 }
344
345 /**
346 * Closes this dialog and frees all native screen resources.
347 */
348 public void closeDialog() {
349 setVisible(false);
350 saveSessionAction.destroy();
351 dispose();
352 }
353
354 class WindowClosingAdapter extends WindowAdapter {
355 @Override
356 public void windowClosing(WindowEvent e) {
357 cancelAction.cancel();
358 }
359 }
360
361 class CancelAction extends AbstractAction {
362 CancelAction() {
363 putValue(NAME, tr("Cancel"));
364 putValue(SHORT_DESCRIPTION, tr("Close this dialog and resume editing in JOSM"));
365 new ImageProvider("cancel").getResource().attachImageIcon(this, true);
366 InputMapUtils.addEscapeAction(getRootPane(), this);
367 }
368
369 protected void cancelWhenInEditingModel() {
370 setUserAction(UserAction.CANCEL);
371 closeDialog();
372 }
373
374 public void cancel() {
375 switch(model.getMode()) {
376 case EDITING_DATA: cancelWhenInEditingModel();
377 break;
378 case UPLOADING_AND_SAVING: cancelSafeAndUploadTask();
379 break;
380 }
381 }
382
383 @Override
384 public void actionPerformed(ActionEvent e) {
385 cancel();
386 }
387 }
388
389 class DiscardAndProceedAction extends AbstractAction implements PropertyChangeListener {
390 DiscardAndProceedAction() {
391 initForReason(Reason.EXIT);
392 }
393
394 public void initForReason(Reason reason) {
395 switch (reason) {
396 case EXIT:
397 putValue(NAME, tr("Exit now!"));
398 putValue(SHORT_DESCRIPTION, tr("Exit JOSM without saving. Unsaved changes are lost."));
399 new ImageProvider("exit").getResource().attachImageIcon(this, true);
400 break;
401 case RESTART:
402 putValue(NAME, tr("Restart now!"));
403 putValue(SHORT_DESCRIPTION, tr("Restart JOSM without saving. Unsaved changes are lost."));
404 new ImageProvider("restart").getResource().attachImageIcon(this, true);
405 break;
406 case DELETE:
407 putValue(NAME, tr("Delete now!"));
408 putValue(SHORT_DESCRIPTION, tr("Delete layers without saving. Unsaved changes are lost."));
409 new ImageProvider("dialogs", "delete").getResource().attachImageIcon(this, true);
410 break;
411 }
412 }
413
414 @Override
415 public void actionPerformed(ActionEvent e) {
416 setUserAction(UserAction.PROCEED);
417 closeDialog();
418 }
419
420 @Override
421 public void propertyChange(PropertyChangeEvent evt) {
422 if (evt.getPropertyName().equals(SaveLayersModel.MODE_PROP)) {
423 Mode mode = (Mode) evt.getNewValue();
424 switch(mode) {
425 case EDITING_DATA: setEnabled(true);
426 break;
427 case UPLOADING_AND_SAVING: setEnabled(false);
428 break;
429 }
430 }
431 }
432 }
433
434 class SaveSessionAction extends SessionSaveAsAction {
435
436 SaveSessionAction() {
437 super(false, false);
438 }
439
440 @Override
441 public void actionPerformed(ActionEvent e) {
442 try {
443 saveSession();
444 setUserAction(UserAction.PROCEED);
445 closeDialog();
446 } catch (UserCancelException ignore) {
447 Logging.trace(ignore);
448 }
449 }
450 }
451
452 final class SaveAndProceedAction extends AbstractAction implements PropertyChangeListener {
453 private static final int ICON_SIZE = 24;
454 private static final String BASE_ICON = "BASE_ICON";
455 private final transient Image save = getImage("save", false);
456 private final transient Image upld = getImage("upload", false);
457 private final transient Image saveDis = getImage("save", true);
458 private final transient Image upldDis = getImage("upload", true);
459
460 SaveAndProceedAction() {
461 initForReason(Reason.EXIT);
462 }
463
464 Image getImage(String name, boolean disabled) {
465 ImageIcon img = new ImageProvider(name).setDisabled(disabled).setOptional(true).get();
466 return img != null ? img.getImage() : null;
467 }
468
469 public void initForReason(Reason reason) {
470 switch (reason) {
471 case EXIT:
472 putValue(NAME, tr("Perform actions before exiting"));
473 putValue(SHORT_DESCRIPTION, tr("Exit JOSM with saving. Unsaved changes are uploaded and/or saved."));
474 putValue(BASE_ICON, ImageProvider.getIfAvailable("exit"));
475 break;
476 case RESTART:
477 putValue(NAME, tr("Perform actions before restarting"));
478 putValue(SHORT_DESCRIPTION, tr("Restart JOSM with saving. Unsaved changes are uploaded and/or saved."));
479 putValue(BASE_ICON, ImageProvider.getIfAvailable("restart"));
480 break;
481 case DELETE:
482 putValue(NAME, tr("Perform actions before deleting"));
483 putValue(SHORT_DESCRIPTION, tr("Save/Upload layers before deleting. Unsaved changes are not lost."));
484 putValue(BASE_ICON, ImageProvider.getIfAvailable("dialogs", "delete"));
485 break;
486 }
487 redrawIcon();
488 }
489
490 public void redrawIcon() {
491 ImageIcon base = ((ImageIcon) getValue(BASE_ICON));
492 BufferedImage newIco = new BufferedImage(ICON_SIZE*3, ICON_SIZE, BufferedImage.TYPE_4BYTE_ABGR);
493 Graphics2D g = newIco.createGraphics();
494 // CHECKSTYLE.OFF: SingleSpaceSeparator
495 g.drawImage(model.getLayersToUpload().isEmpty() ? upldDis : upld, ICON_SIZE*0, 0, ICON_SIZE, ICON_SIZE, null);
496 g.drawImage(model.getLayersToSave().isEmpty() ? saveDis : save, ICON_SIZE*1, 0, ICON_SIZE, ICON_SIZE, null);
497 if (base != null) {
498 g.drawImage(base.getImage(), ICON_SIZE*2, 0, ICON_SIZE, ICON_SIZE, null);
499 }
500 // CHECKSTYLE.ON: SingleSpaceSeparator
501 putValue(SMALL_ICON, new ImageIcon(newIco));
502 }
503
504 @Override
505 public void actionPerformed(ActionEvent e) {
506 if (!confirmSaveLayerInfosOK(model))
507 return;
508 launchSafeAndUploadTask();
509 }
510
511 @Override
512 public void propertyChange(PropertyChangeEvent evt) {
513 if (evt.getPropertyName().equals(SaveLayersModel.MODE_PROP)) {
514 SaveLayersModel.Mode mode = (SaveLayersModel.Mode) evt.getNewValue();
515 switch(mode) {
516 case EDITING_DATA: setEnabled(true);
517 break;
518 case UPLOADING_AND_SAVING: setEnabled(false);
519 break;
520 }
521 }
522 }
523 }
524
525 /**
526 * This is the asynchronous task which uploads modified layers to the server and
527 * saves them to files, if requested by the user.
528 *
529 */
530 protected class SaveAndUploadTask implements Runnable {
531
532 private final SaveLayersModel model;
533 private final ProgressMonitor monitor;
534 private final ExecutorService worker;
535 private boolean canceled;
536 private AbstractIOTask currentTask;
537
538 public SaveAndUploadTask(SaveLayersModel model, ProgressMonitor monitor) {
539 this.model = model;
540 this.monitor = monitor;
541 this.worker = Executors.newSingleThreadExecutor(Utils.newThreadFactory(getClass() + "-%d", Thread.NORM_PRIORITY));
542 }
543
544 protected void uploadLayers(List<SaveLayerInfo> toUpload) {
545 for (final SaveLayerInfo layerInfo: toUpload) {
546 AbstractModifiableLayer layer = layerInfo.getLayer();
547 if (canceled) {
548 model.setUploadState(layer, UploadOrSaveState.CANCELED);
549 continue;
550 }
551 monitor.subTask(tr("Preparing layer ''{0}'' for upload ...", layerInfo.getName()));
552
553 if (!UploadAction.checkPreUploadConditions(layer)) {
554 model.setUploadState(layer, UploadOrSaveState.FAILED);
555 continue;
556 }
557
558 AbstractUploadDialog dialog = layer.getUploadDialog();
559 if (dialog != null) {
560 dialog.setVisible(true);
561 if (dialog.isCanceled()) {
562 model.setUploadState(layer, UploadOrSaveState.CANCELED);
563 continue;
564 }
565 dialog.rememberUserInput();
566 }
567
568 currentTask = layer.createUploadTask(monitor);
569 if (currentTask == null) {
570 model.setUploadState(layer, UploadOrSaveState.FAILED);
571 continue;
572 }
573 Future<?> currentFuture = worker.submit(currentTask);
574 try {
575 // wait for the asynchronous task to complete
576 currentFuture.get();
577 } catch (CancellationException e) {
578 Logging.trace(e);
579 model.setUploadState(layer, UploadOrSaveState.CANCELED);
580 } catch (InterruptedException | ExecutionException e) {
581 Logging.error(e);
582 model.setUploadState(layer, UploadOrSaveState.FAILED);
583 ExceptionDialogUtil.explainException(e);
584 }
585 if (currentTask.isCanceled()) {
586 model.setUploadState(layer, UploadOrSaveState.CANCELED);
587 } else if (currentTask.isFailed()) {
588 Logging.error(currentTask.getLastException());
589 ExceptionDialogUtil.explainException(currentTask.getLastException());
590 model.setUploadState(layer, UploadOrSaveState.FAILED);
591 } else {
592 model.setUploadState(layer, UploadOrSaveState.OK);
593 }
594 currentTask = null;
595 }
596 }
597
598 protected void saveLayers(List<SaveLayerInfo> toSave) {
599 for (final SaveLayerInfo layerInfo: toSave) {
600 if (canceled) {
601 model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.CANCELED);
602 continue;
603 }
604 // Check save preconditions earlier to avoid a blocking reentring call to EDT (see #10086)
605 if (layerInfo.isDoCheckSaveConditions()) {
606 if (!layerInfo.getLayer().checkSaveConditions()) {
607 continue;
608 }
609 layerInfo.setDoCheckSaveConditions(false);
610 }
611 currentTask = new SaveLayerTask(layerInfo, monitor);
612 Future<?> currentFuture = worker.submit(currentTask);
613
614 try {
615 // wait for the asynchronous task to complete
616 //
617 currentFuture.get();
618 } catch (CancellationException e) {
619 Logging.trace(e);
620 model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.CANCELED);
621 } catch (InterruptedException | ExecutionException e) {
622 Logging.error(e);
623 model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.FAILED);
624 ExceptionDialogUtil.explainException(e);
625 }
626 if (currentTask.isCanceled()) {
627 model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.CANCELED);
628 } else if (currentTask.isFailed()) {
629 if (currentTask.getLastException() != null) {
630 Logging.error(currentTask.getLastException());
631 ExceptionDialogUtil.explainException(currentTask.getLastException());
632 }
633 model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.FAILED);
634 } else {
635 model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.OK);
636 }
637 this.currentTask = null;
638 }
639 }
640
641 protected void warnBecauseOfUnsavedData() {
642 int numProblems = model.getNumCancel() + model.getNumFailed();
643 if (numProblems == 0)
644 return;
645 Logging.warn(numProblems + " problems occurred during upload/save");
646 String msg = trn(
647 "<html>An upload and/or save operation of one layer with modifications<br>"
648 + "was canceled or has failed.</html>",
649 "<html>Upload and/or save operations of {0} layers with modifications<br>"
650 + "were canceled or have failed.</html>",
651 numProblems,
652 numProblems
653 );
654 JOptionPane.showMessageDialog(
655 MainApplication.getMainFrame(),
656 msg,
657 tr("Incomplete upload and/or save"),
658 JOptionPane.WARNING_MESSAGE
659 );
660 }
661
662 @Override
663 public void run() {
664 GuiHelper.runInEDTAndWait(() -> {
665 model.setMode(SaveLayersModel.Mode.UPLOADING_AND_SAVING);
666 List<SaveLayerInfo> toUpload = model.getLayersToUpload();
667 if (!toUpload.isEmpty()) {
668 uploadLayers(toUpload);
669 }
670 List<SaveLayerInfo> toSave = model.getLayersToSave();
671 if (!toSave.isEmpty()) {
672 saveLayers(toSave);
673 }
674 model.setMode(SaveLayersModel.Mode.EDITING_DATA);
675 if (model.hasUnsavedData()) {
676 warnBecauseOfUnsavedData();
677 model.setMode(Mode.EDITING_DATA);
678 if (canceled) {
679 setUserAction(UserAction.CANCEL);
680 closeDialog();
681 }
682 } else {
683 setUserAction(UserAction.PROCEED);
684 closeDialog();
685 }
686 });
687 worker.shutdownNow();
688 }
689
690 public void cancel() {
691 if (currentTask != null) {
692 currentTask.cancel();
693 }
694 worker.shutdown();
695 canceled = true;
696 }
697 }
698
699 @Override
700 public void tableChanged(TableModelEvent e) {
701 boolean dis = model.getLayersToSave().isEmpty() && model.getLayersToUpload().isEmpty();
702 if (saveAndProceedActionButton != null) {
703 saveAndProceedActionButton.setEnabled(!dis);
704 }
705 saveAndProceedAction.redrawIcon();
706 }
707}
Note: See TracBrowser for help on using the repository browser.