source: josm/trunk/src/org/openstreetmap/josm/plugins/PluginHandler.java@ 13173

Last change on this file since 13173 was 13173, checked in by Don-vip, 6 years ago

see #15310 - remove most of deprecated APIs

  • Property svn:eol-style set to native
File size: 67.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.plugins;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.Component;
9import java.awt.Font;
10import java.awt.GraphicsEnvironment;
11import java.awt.GridBagConstraints;
12import java.awt.GridBagLayout;
13import java.awt.Insets;
14import java.awt.event.ActionEvent;
15import java.io.File;
16import java.io.FilenameFilter;
17import java.io.IOException;
18import java.net.URL;
19import java.net.URLClassLoader;
20import java.security.AccessController;
21import java.security.PrivilegedAction;
22import java.util.ArrayList;
23import java.util.Arrays;
24import java.util.Collection;
25import java.util.Collections;
26import java.util.Comparator;
27import java.util.HashMap;
28import java.util.HashSet;
29import java.util.Iterator;
30import java.util.LinkedList;
31import java.util.List;
32import java.util.Locale;
33import java.util.Map;
34import java.util.Map.Entry;
35import java.util.Set;
36import java.util.TreeSet;
37import java.util.concurrent.ExecutionException;
38import java.util.concurrent.FutureTask;
39import java.util.concurrent.TimeUnit;
40import java.util.jar.JarFile;
41import java.util.stream.Collectors;
42
43import javax.swing.AbstractAction;
44import javax.swing.BorderFactory;
45import javax.swing.Box;
46import javax.swing.JButton;
47import javax.swing.JCheckBox;
48import javax.swing.JLabel;
49import javax.swing.JOptionPane;
50import javax.swing.JPanel;
51import javax.swing.JScrollPane;
52import javax.swing.UIManager;
53
54import org.openstreetmap.josm.Main;
55import org.openstreetmap.josm.actions.RestartAction;
56import org.openstreetmap.josm.data.PreferencesUtils;
57import org.openstreetmap.josm.data.Version;
58import org.openstreetmap.josm.gui.HelpAwareOptionPane;
59import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
60import org.openstreetmap.josm.gui.MainApplication;
61import org.openstreetmap.josm.gui.download.DownloadSelection;
62import org.openstreetmap.josm.gui.preferences.PreferenceSettingFactory;
63import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
64import org.openstreetmap.josm.gui.progress.ProgressMonitor;
65import org.openstreetmap.josm.gui.util.GuiHelper;
66import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
67import org.openstreetmap.josm.gui.widgets.JosmTextArea;
68import org.openstreetmap.josm.io.OfflineAccessException;
69import org.openstreetmap.josm.io.OnlineResource;
70import org.openstreetmap.josm.spi.preferences.Config;
71import org.openstreetmap.josm.tools.GBC;
72import org.openstreetmap.josm.tools.I18n;
73import org.openstreetmap.josm.tools.ImageProvider;
74import org.openstreetmap.josm.tools.Logging;
75import org.openstreetmap.josm.tools.SubclassFilteredCollection;
76import org.openstreetmap.josm.tools.Utils;
77
78/**
79 * PluginHandler is basically a collection of static utility functions used to bootstrap
80 * and manage the loaded plugins.
81 * @since 1326
82 */
83public final class PluginHandler {
84
85 /**
86 * Deprecated plugins that are removed on start
87 */
88 static final Collection<DeprecatedPlugin> DEPRECATED_PLUGINS;
89 static {
90 String inCore = tr("integrated into main program");
91
92 DEPRECATED_PLUGINS = Arrays.asList(
93 new DeprecatedPlugin("mappaint", inCore),
94 new DeprecatedPlugin("unglueplugin", inCore),
95 new DeprecatedPlugin("lang-de", inCore),
96 new DeprecatedPlugin("lang-en_GB", inCore),
97 new DeprecatedPlugin("lang-fr", inCore),
98 new DeprecatedPlugin("lang-it", inCore),
99 new DeprecatedPlugin("lang-pl", inCore),
100 new DeprecatedPlugin("lang-ro", inCore),
101 new DeprecatedPlugin("lang-ru", inCore),
102 new DeprecatedPlugin("ewmsplugin", inCore),
103 new DeprecatedPlugin("ywms", inCore),
104 new DeprecatedPlugin("tways-0.2", inCore),
105 new DeprecatedPlugin("geotagged", inCore),
106 new DeprecatedPlugin("landsat", tr("replaced by new {0} plugin", "lakewalker")),
107 new DeprecatedPlugin("namefinder", inCore),
108 new DeprecatedPlugin("waypoints", inCore),
109 new DeprecatedPlugin("slippy_map_chooser", inCore),
110 new DeprecatedPlugin("tcx-support", tr("replaced by new {0} plugin", "dataimport")),
111 new DeprecatedPlugin("usertools", inCore),
112 new DeprecatedPlugin("AgPifoJ", inCore),
113 new DeprecatedPlugin("utilsplugin", inCore),
114 new DeprecatedPlugin("ghost", inCore),
115 new DeprecatedPlugin("validator", inCore),
116 new DeprecatedPlugin("multipoly", inCore),
117 new DeprecatedPlugin("multipoly-convert", inCore),
118 new DeprecatedPlugin("remotecontrol", inCore),
119 new DeprecatedPlugin("imagery", inCore),
120 new DeprecatedPlugin("slippymap", inCore),
121 new DeprecatedPlugin("wmsplugin", inCore),
122 new DeprecatedPlugin("ParallelWay", inCore),
123 new DeprecatedPlugin("dumbutils", tr("replaced by new {0} plugin", "utilsplugin2")),
124 new DeprecatedPlugin("ImproveWayAccuracy", inCore),
125 new DeprecatedPlugin("Curves", tr("replaced by new {0} plugin", "utilsplugin2")),
126 new DeprecatedPlugin("epsg31287", inCore),
127 new DeprecatedPlugin("licensechange", tr("no longer required")),
128 new DeprecatedPlugin("restart", inCore),
129 new DeprecatedPlugin("wayselector", inCore),
130 new DeprecatedPlugin("openstreetbugs", inCore),
131 new DeprecatedPlugin("nearclick", tr("no longer required")),
132 new DeprecatedPlugin("notes", inCore),
133 new DeprecatedPlugin("mirrored_download", inCore),
134 new DeprecatedPlugin("ImageryCache", inCore),
135 new DeprecatedPlugin("commons-imaging", tr("replaced by new {0} plugin", "apache-commons")),
136 new DeprecatedPlugin("missingRoads", tr("replaced by new {0} plugin", "ImproveOsm")),
137 new DeprecatedPlugin("trafficFlowDirection", tr("replaced by new {0} plugin", "ImproveOsm")),
138 new DeprecatedPlugin("kendzi3d-jogl", tr("replaced by new {0} plugin", "jogl")),
139 new DeprecatedPlugin("josm-geojson", tr("replaced by new {0} plugin", "geojson")),
140 new DeprecatedPlugin("proj4j", inCore),
141 new DeprecatedPlugin("OpenStreetView", tr("replaced by new {0} plugin", "OpenStreetCam")),
142 new DeprecatedPlugin("imageryadjust", inCore),
143 new DeprecatedPlugin("walkingpapers", tr("replaced by new {0} plugin", "fieldpapers")),
144 new DeprecatedPlugin("czechaddress", tr("no longer required")),
145 new DeprecatedPlugin("kendzi3d_Improved_by_Andrei", tr("no longer required"))
146 );
147 }
148
149 private PluginHandler() {
150 // Hide default constructor for utils classes
151 }
152
153 static final class PluginInformationAction extends AbstractAction {
154 private final PluginInformation info;
155
156 PluginInformationAction(PluginInformation info) {
157 super(tr("Information"));
158 this.info = info;
159 }
160
161 /**
162 * Returns plugin information text.
163 * @return plugin information text
164 */
165 public String getText() {
166 StringBuilder b = new StringBuilder();
167 for (Entry<String, String> e : info.attr.entrySet()) {
168 b.append(e.getKey());
169 b.append(": ");
170 b.append(e.getValue());
171 b.append('\n');
172 }
173 return b.toString();
174 }
175
176 @Override
177 public void actionPerformed(ActionEvent event) {
178 String text = getText();
179 JosmTextArea a = new JosmTextArea(10, 40);
180 a.setEditable(false);
181 a.setText(text);
182 a.setCaretPosition(0);
183 if (!GraphicsEnvironment.isHeadless()) {
184 JOptionPane.showMessageDialog(Main.parent, new JScrollPane(a), tr("Plugin information"),
185 JOptionPane.INFORMATION_MESSAGE);
186 }
187 }
188 }
189
190 /**
191 * Description of a deprecated plugin
192 */
193 public static class DeprecatedPlugin implements Comparable<DeprecatedPlugin> {
194 /** Plugin name */
195 public final String name;
196 /** Short explanation about deprecation, can be {@code null} */
197 public final String reason;
198
199 /**
200 * Constructs a new {@code DeprecatedPlugin} with a given reason.
201 * @param name The plugin name
202 * @param reason The reason about deprecation
203 */
204 public DeprecatedPlugin(String name, String reason) {
205 this.name = name;
206 this.reason = reason;
207 }
208
209 @Override
210 public int hashCode() {
211 final int prime = 31;
212 int result = prime + ((name == null) ? 0 : name.hashCode());
213 return prime * result + ((reason == null) ? 0 : reason.hashCode());
214 }
215
216 @Override
217 public boolean equals(Object obj) {
218 if (this == obj)
219 return true;
220 if (obj == null)
221 return false;
222 if (getClass() != obj.getClass())
223 return false;
224 DeprecatedPlugin other = (DeprecatedPlugin) obj;
225 if (name == null) {
226 if (other.name != null)
227 return false;
228 } else if (!name.equals(other.name))
229 return false;
230 if (reason == null) {
231 if (other.reason != null)
232 return false;
233 } else if (!reason.equals(other.reason))
234 return false;
235 return true;
236 }
237
238 @Override
239 public int compareTo(DeprecatedPlugin o) {
240 int d = name.compareTo(o.name);
241 if (d == 0)
242 d = reason.compareTo(o.reason);
243 return d;
244 }
245 }
246
247 /**
248 * ClassLoader that makes the addURL method of URLClassLoader public.
249 *
250 * Like URLClassLoader, but allows to add more URLs after construction.
251 */
252 public static class DynamicURLClassLoader extends URLClassLoader {
253
254 /**
255 * Constructs a new {@code DynamicURLClassLoader}.
256 * @param urls the URLs from which to load classes and resources
257 * @param parent the parent class loader for delegation
258 */
259 public DynamicURLClassLoader(URL[] urls, ClassLoader parent) {
260 super(urls, parent);
261 }
262
263 @Override
264 public void addURL(URL url) {
265 super.addURL(url);
266 }
267 }
268
269 /**
270 * List of unmaintained plugins. Not really up-to-date as the vast majority of plugins are not maintained after a few months, sadly...
271 */
272 static final List<String> UNMAINTAINED_PLUGINS = Collections.unmodifiableList(Arrays.asList(
273 "NanoLog", // See https://trac.openstreetmap.org/changeset/29404/subversion
274 "irsrectify", // See https://trac.openstreetmap.org/changeset/29404/subversion
275 "surveyor2", // See https://trac.openstreetmap.org/changeset/29404/subversion
276 "gpsbabelgui",
277 "Intersect_way",
278 "ContourOverlappingMerge", // See #11202, #11518, https://github.com/bularcasergiu/ContourOverlappingMerge/issues/1
279 "LaneConnector", // See #11468, #11518, https://github.com/TrifanAdrian/LanecConnectorPlugin/issues/1
280 "Remove.redundant.points" // See #11468, #11518, https://github.com/bularcasergiu/RemoveRedundantPoints (not even created an issue...)
281 ));
282
283 /**
284 * Default time-based update interval, in days (pluginmanager.time-based-update.interval)
285 */
286 public static final int DEFAULT_TIME_BASED_UPDATE_INTERVAL = 30;
287
288 /**
289 * All installed and loaded plugins (resp. their main classes)
290 */
291 static final Collection<PluginProxy> pluginList = new LinkedList<>();
292
293 /**
294 * All exceptions that occured during plugin loading
295 */
296 static final Map<String, Throwable> pluginLoadingExceptions = new HashMap<>();
297
298 /**
299 * Class loader to locate resources from plugins.
300 * @see #getJoinedPluginResourceCL()
301 */
302 private static DynamicURLClassLoader joinedPluginResourceCL;
303
304 /**
305 * Add here all ClassLoader whose resource should be searched.
306 */
307 private static final List<ClassLoader> sources = new LinkedList<>();
308 static {
309 try {
310 sources.add(ClassLoader.getSystemClassLoader());
311 sources.add(PluginHandler.class.getClassLoader());
312 } catch (SecurityException ex) {
313 Logging.debug(ex);
314 sources.add(ImageProvider.class.getClassLoader());
315 }
316 }
317
318 private static PluginDownloadTask pluginDownloadTask;
319
320 /**
321 * Returns the list of currently installed and loaded plugins.
322 * @return the list of currently installed and loaded plugins
323 * @since 10982
324 */
325 public static List<PluginInformation> getPlugins() {
326 return pluginList.stream().map(PluginProxy::getPluginInformation).collect(Collectors.toList());
327 }
328
329 /**
330 * Returns all ClassLoaders whose resource should be searched.
331 * @return all ClassLoaders whose resource should be searched
332 */
333 public static Collection<ClassLoader> getResourceClassLoaders() {
334 return Collections.unmodifiableCollection(sources);
335 }
336
337 /**
338 * Removes deprecated plugins from a collection of plugins. Modifies the
339 * collection <code>plugins</code>.
340 *
341 * Also notifies the user about removed deprecated plugins
342 *
343 * @param parent The parent Component used to display warning popup
344 * @param plugins the collection of plugins
345 */
346 static void filterDeprecatedPlugins(Component parent, Collection<String> plugins) {
347 Set<DeprecatedPlugin> removedPlugins = new TreeSet<>();
348 for (DeprecatedPlugin depr : DEPRECATED_PLUGINS) {
349 if (plugins.contains(depr.name)) {
350 plugins.remove(depr.name);
351 PreferencesUtils.removeFromList(Config.getPref(), "plugins", depr.name);
352 removedPlugins.add(depr);
353 }
354 }
355 if (removedPlugins.isEmpty())
356 return;
357
358 // notify user about removed deprecated plugins
359 //
360 StringBuilder sb = new StringBuilder(32);
361 sb.append("<html>")
362 .append(trn(
363 "The following plugin is no longer necessary and has been deactivated:",
364 "The following plugins are no longer necessary and have been deactivated:",
365 removedPlugins.size()))
366 .append("<ul>");
367 for (DeprecatedPlugin depr: removedPlugins) {
368 sb.append("<li>").append(depr.name);
369 if (depr.reason != null) {
370 sb.append(" (").append(depr.reason).append(')');
371 }
372 sb.append("</li>");
373 }
374 sb.append("</ul></html>");
375 if (!GraphicsEnvironment.isHeadless()) {
376 JOptionPane.showMessageDialog(
377 parent,
378 sb.toString(),
379 tr("Warning"),
380 JOptionPane.WARNING_MESSAGE
381 );
382 }
383 }
384
385 /**
386 * Removes unmaintained plugins from a collection of plugins. Modifies the
387 * collection <code>plugins</code>. Also removes the plugin from the list
388 * of plugins in the preferences, if necessary.
389 *
390 * Asks the user for every unmaintained plugin whether it should be removed.
391 * @param parent The parent Component used to display warning popup
392 *
393 * @param plugins the collection of plugins
394 */
395 static void filterUnmaintainedPlugins(Component parent, Collection<String> plugins) {
396 for (String unmaintained : UNMAINTAINED_PLUGINS) {
397 if (!plugins.contains(unmaintained)) {
398 continue;
399 }
400 String msg = tr("<html>Loading of the plugin \"{0}\" was requested."
401 + "<br>This plugin is no longer developed and very likely will produce errors."
402 +"<br>It should be disabled.<br>Delete from preferences?</html>",
403 Utils.escapeReservedCharactersHTML(unmaintained));
404 if (confirmDisablePlugin(parent, msg, unmaintained)) {
405 PreferencesUtils.removeFromList(Config.getPref(), "plugins", unmaintained);
406 plugins.remove(unmaintained);
407 }
408 }
409 }
410
411 /**
412 * Checks whether the locally available plugins should be updated and
413 * asks the user if running an update is OK. An update is advised if
414 * JOSM was updated to a new version since the last plugin updates or
415 * if the plugins were last updated a long time ago.
416 *
417 * @param parent the parent component relative to which the confirmation dialog
418 * is to be displayed
419 * @return true if a plugin update should be run; false, otherwise
420 */
421 public static boolean checkAndConfirmPluginUpdate(Component parent) {
422 if (!checkOfflineAccess()) {
423 Logging.info(tr("{0} not available (offline mode)", tr("Plugin update")));
424 return false;
425 }
426 String message = null;
427 String togglePreferenceKey = null;
428 int v = Version.getInstance().getVersion();
429 if (Config.getPref().getInt("pluginmanager.version", 0) < v) {
430 message =
431 "<html>"
432 + tr("You updated your JOSM software.<br>"
433 + "To prevent problems the plugins should be updated as well.<br><br>"
434 + "Update plugins now?"
435 )
436 + "</html>";
437 togglePreferenceKey = "pluginmanager.version-based-update.policy";
438 } else {
439 long tim = System.currentTimeMillis();
440 long last = Config.getPref().getLong("pluginmanager.lastupdate", 0);
441 Integer maxTime = Config.getPref().getInt("pluginmanager.time-based-update.interval", DEFAULT_TIME_BASED_UPDATE_INTERVAL);
442 long d = TimeUnit.MILLISECONDS.toDays(tim - last);
443 if ((last <= 0) || (maxTime <= 0)) {
444 Config.getPref().put("pluginmanager.lastupdate", Long.toString(tim));
445 } else if (d > maxTime) {
446 message =
447 "<html>"
448 + tr("Last plugin update more than {0} days ago.", d)
449 + "</html>";
450 togglePreferenceKey = "pluginmanager.time-based-update.policy";
451 }
452 }
453 if (message == null) return false;
454
455 UpdatePluginsMessagePanel pnlMessage = new UpdatePluginsMessagePanel();
456 pnlMessage.setMessage(message);
457 pnlMessage.initDontShowAgain(togglePreferenceKey);
458
459 // check whether automatic update at startup was disabled
460 //
461 String policy = Config.getPref().get(togglePreferenceKey, "ask").trim().toLowerCase(Locale.ENGLISH);
462 switch(policy) {
463 case "never":
464 if ("pluginmanager.version-based-update.policy".equals(togglePreferenceKey)) {
465 Logging.info(tr("Skipping plugin update after JOSM upgrade. Automatic update at startup is disabled."));
466 } else if ("pluginmanager.time-based-update.policy".equals(togglePreferenceKey)) {
467 Logging.info(tr("Skipping plugin update after elapsed update interval. Automatic update at startup is disabled."));
468 }
469 return false;
470
471 case "always":
472 if ("pluginmanager.version-based-update.policy".equals(togglePreferenceKey)) {
473 Logging.info(tr("Running plugin update after JOSM upgrade. Automatic update at startup is enabled."));
474 } else if ("pluginmanager.time-based-update.policy".equals(togglePreferenceKey)) {
475 Logging.info(tr("Running plugin update after elapsed update interval. Automatic update at startup is disabled."));
476 }
477 return true;
478
479 case "ask":
480 break;
481
482 default:
483 Logging.warn(tr("Unexpected value ''{0}'' for preference ''{1}''. Assuming value ''ask''.", policy, togglePreferenceKey));
484 }
485
486 ButtonSpec[] options = new ButtonSpec[] {
487 new ButtonSpec(
488 tr("Update plugins"),
489 ImageProvider.get("dialogs", "refresh"),
490 tr("Click to update the activated plugins"),
491 null /* no specific help context */
492 ),
493 new ButtonSpec(
494 tr("Skip update"),
495 ImageProvider.get("cancel"),
496 tr("Click to skip updating the activated plugins"),
497 null /* no specific help context */
498 )
499 };
500
501 int ret = HelpAwareOptionPane.showOptionDialog(
502 parent,
503 pnlMessage,
504 tr("Update plugins"),
505 JOptionPane.WARNING_MESSAGE,
506 null,
507 options,
508 options[0],
509 ht("/Preferences/Plugins#AutomaticUpdate")
510 );
511
512 if (pnlMessage.isRememberDecision()) {
513 switch(ret) {
514 case 0:
515 Config.getPref().put(togglePreferenceKey, "always");
516 break;
517 case JOptionPane.CLOSED_OPTION:
518 case 1:
519 Config.getPref().put(togglePreferenceKey, "never");
520 break;
521 default: // Do nothing
522 }
523 } else {
524 Config.getPref().put(togglePreferenceKey, "ask");
525 }
526 return ret == 0;
527 }
528
529 private static boolean checkOfflineAccess() {
530 if (Main.isOffline(OnlineResource.ALL)) {
531 return false;
532 }
533 if (Main.isOffline(OnlineResource.JOSM_WEBSITE)) {
534 for (String updateSite : Main.pref.getPluginSites()) {
535 try {
536 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(updateSite, Main.getJOSMWebsite());
537 } catch (OfflineAccessException e) {
538 Logging.trace(e);
539 return false;
540 }
541 }
542 }
543 return true;
544 }
545
546 /**
547 * Alerts the user if a plugin required by another plugin is missing, and offer to download them &amp; restart JOSM
548 *
549 * @param parent The parent Component used to display error popup
550 * @param plugin the plugin
551 * @param missingRequiredPlugin the missing required plugin
552 */
553 private static void alertMissingRequiredPlugin(Component parent, String plugin, Set<String> missingRequiredPlugin) {
554 StringBuilder sb = new StringBuilder(48);
555 sb.append("<html>")
556 .append(trn("Plugin {0} requires a plugin which was not found. The missing plugin is:",
557 "Plugin {0} requires {1} plugins which were not found. The missing plugins are:",
558 missingRequiredPlugin.size(),
559 Utils.escapeReservedCharactersHTML(plugin),
560 missingRequiredPlugin.size()))
561 .append(Utils.joinAsHtmlUnorderedList(missingRequiredPlugin))
562 .append("</html>");
563 ButtonSpec[] specs = new ButtonSpec[] {
564 new ButtonSpec(
565 tr("Download and restart"),
566 ImageProvider.get("restart"),
567 trn("Click to download missing plugin and restart JOSM",
568 "Click to download missing plugins and restart JOSM",
569 missingRequiredPlugin.size()),
570 null /* no specific help text */
571 ),
572 new ButtonSpec(
573 tr("Continue"),
574 ImageProvider.get("ok"),
575 trn("Click to continue without this plugin",
576 "Click to continue without these plugins",
577 missingRequiredPlugin.size()),
578 null /* no specific help text */
579 )
580 };
581 if (0 == HelpAwareOptionPane.showOptionDialog(
582 parent,
583 sb.toString(),
584 tr("Error"),
585 JOptionPane.ERROR_MESSAGE,
586 null, /* no special icon */
587 specs,
588 specs[0],
589 ht("/Plugin/Loading#MissingRequiredPlugin"))) {
590 downloadRequiredPluginsAndRestart(parent, missingRequiredPlugin);
591 }
592 }
593
594 private static void downloadRequiredPluginsAndRestart(final Component parent, final Set<String> missingRequiredPlugin) {
595 // Update plugin list
596 final ReadRemotePluginInformationTask pluginInfoDownloadTask = new ReadRemotePluginInformationTask(
597 Main.pref.getOnlinePluginSites());
598 MainApplication.worker.submit(pluginInfoDownloadTask);
599
600 // Continuation
601 MainApplication.worker.submit(() -> {
602 // Build list of plugins to download
603 Set<PluginInformation> toDownload = new HashSet<>(pluginInfoDownloadTask.getAvailablePlugins());
604 toDownload.removeIf(info -> !missingRequiredPlugin.contains(info.getName()));
605 // Check if something has still to be downloaded
606 if (!toDownload.isEmpty()) {
607 // download plugins
608 final PluginDownloadTask task = new PluginDownloadTask(parent, toDownload, tr("Download plugins"));
609 MainApplication.worker.submit(task);
610 MainApplication.worker.submit(() -> {
611 // restart if some plugins have been downloaded
612 if (!task.getDownloadedPlugins().isEmpty()) {
613 // update plugin list in preferences
614 Set<String> plugins = new HashSet<>(Config.getPref().getList("plugins"));
615 for (PluginInformation plugin : task.getDownloadedPlugins()) {
616 plugins.add(plugin.name);
617 }
618 Config.getPref().putList("plugins", new ArrayList<>(plugins));
619 // restart
620 try {
621 RestartAction.restartJOSM();
622 } catch (IOException e) {
623 Logging.error(e);
624 }
625 } else {
626 Logging.warn("No plugin downloaded, restart canceled");
627 }
628 });
629 } else {
630 Logging.warn("No plugin to download, operation canceled");
631 }
632 });
633 }
634
635 private static void alertJOSMUpdateRequired(Component parent, String plugin, int requiredVersion) {
636 HelpAwareOptionPane.showOptionDialog(
637 parent,
638 tr("<html>Plugin {0} requires JOSM version {1}. The current JOSM version is {2}.<br>"
639 +"You have to update JOSM in order to use this plugin.</html>",
640 plugin, Integer.toString(requiredVersion), Version.getInstance().getVersionString()
641 ),
642 tr("Warning"),
643 JOptionPane.WARNING_MESSAGE,
644 ht("/Plugin/Loading#JOSMUpdateRequired")
645 );
646 }
647
648 /**
649 * Checks whether all preconditions for loading the plugin <code>plugin</code> are met. The
650 * current JOSM version must be compatible with the plugin and no other plugins this plugin
651 * depends on should be missing.
652 *
653 * @param parent The parent Component used to display error popup
654 * @param plugins the collection of all loaded plugins
655 * @param plugin the plugin for which preconditions are checked
656 * @return true, if the preconditions are met; false otherwise
657 */
658 public static boolean checkLoadPreconditions(Component parent, Collection<PluginInformation> plugins, PluginInformation plugin) {
659
660 // make sure the plugin is compatible with the current JOSM version
661 //
662 int josmVersion = Version.getInstance().getVersion();
663 if (plugin.localmainversion > josmVersion && josmVersion != Version.JOSM_UNKNOWN_VERSION) {
664 alertJOSMUpdateRequired(parent, plugin.name, plugin.localmainversion);
665 return false;
666 }
667
668 // Add all plugins already loaded (to include early plugins when checking late ones)
669 Collection<PluginInformation> allPlugins = new HashSet<>(plugins);
670 for (PluginProxy proxy : pluginList) {
671 allPlugins.add(proxy.getPluginInformation());
672 }
673
674 return checkRequiredPluginsPreconditions(parent, allPlugins, plugin, true);
675 }
676
677 /**
678 * Checks if required plugins preconditions for loading the plugin <code>plugin</code> are met.
679 * No other plugins this plugin depends on should be missing.
680 *
681 * @param parent The parent Component used to display error popup. If parent is
682 * null, the error popup is suppressed
683 * @param plugins the collection of all loaded plugins
684 * @param plugin the plugin for which preconditions are checked
685 * @param local Determines if the local or up-to-date plugin dependencies are to be checked.
686 * @return true, if the preconditions are met; false otherwise
687 * @since 5601
688 */
689 public static boolean checkRequiredPluginsPreconditions(Component parent, Collection<PluginInformation> plugins,
690 PluginInformation plugin, boolean local) {
691
692 String requires = local ? plugin.localrequires : plugin.requires;
693
694 // make sure the dependencies to other plugins are not broken
695 //
696 if (requires != null) {
697 Set<String> pluginNames = new HashSet<>();
698 for (PluginInformation pi: plugins) {
699 pluginNames.add(pi.name);
700 }
701 Set<String> missingPlugins = new HashSet<>();
702 List<String> requiredPlugins = local ? plugin.getLocalRequiredPlugins() : plugin.getRequiredPlugins();
703 for (String requiredPlugin : requiredPlugins) {
704 if (!pluginNames.contains(requiredPlugin)) {
705 missingPlugins.add(requiredPlugin);
706 }
707 }
708 if (!missingPlugins.isEmpty()) {
709 if (parent != null) {
710 alertMissingRequiredPlugin(parent, plugin.name, missingPlugins);
711 }
712 return false;
713 }
714 }
715 return true;
716 }
717
718 /**
719 * Get class loader to locate resources from plugins.
720 *
721 * It joins URLs of all plugins, to find images, etc.
722 * (Not for loading Java classes - each plugin has a separate {@link PluginClassLoader}
723 * for that purpose.)
724 * @return class loader to locate resources from plugins
725 */
726 private static synchronized DynamicURLClassLoader getJoinedPluginResourceCL() {
727 if (joinedPluginResourceCL == null) {
728 joinedPluginResourceCL = AccessController.doPrivileged((PrivilegedAction<DynamicURLClassLoader>)
729 () -> new DynamicURLClassLoader(new URL[0], PluginHandler.class.getClassLoader()));
730 sources.add(0, joinedPluginResourceCL);
731 }
732 return joinedPluginResourceCL;
733 }
734
735 /**
736 * Add more plugins to the joined plugin resource class loader.
737 *
738 * @param plugins the plugins to add
739 */
740 private static void extendJoinedPluginResourceCL(Collection<PluginInformation> plugins) {
741 // iterate all plugins and collect all libraries of all plugins:
742 File pluginDir = Main.pref.getPluginsDirectory();
743 DynamicURLClassLoader cl = getJoinedPluginResourceCL();
744
745 for (PluginInformation info : plugins) {
746 if (info.libraries == null) {
747 continue;
748 }
749 for (URL libUrl : info.libraries) {
750 cl.addURL(libUrl);
751 }
752 File pluginJar = new File(pluginDir, info.name + ".jar");
753 I18n.addTexts(pluginJar);
754 URL pluginJarUrl = Utils.fileToURL(pluginJar);
755 cl.addURL(pluginJarUrl);
756 }
757 }
758
759 /**
760 * Loads and instantiates the plugin described by <code>plugin</code> using
761 * the class loader <code>pluginClassLoader</code>.
762 *
763 * @param parent The parent component to be used for the displayed dialog
764 * @param plugin the plugin
765 * @param pluginClassLoader the plugin class loader
766 */
767 private static void loadPlugin(Component parent, PluginInformation plugin, PluginClassLoader pluginClassLoader) {
768 String msg = tr("Could not load plugin {0}. Delete from preferences?", plugin.name);
769 try {
770 Class<?> klass = plugin.loadClass(pluginClassLoader);
771 if (klass != null) {
772 Logging.info(tr("loading plugin ''{0}'' (version {1})", plugin.name, plugin.localversion));
773 PluginProxy pluginProxy = plugin.load(klass, pluginClassLoader);
774 pluginList.add(pluginProxy);
775 MainApplication.addAndFireMapFrameListener(pluginProxy);
776 }
777 msg = null;
778 } catch (PluginException e) {
779 pluginLoadingExceptions.put(plugin.name, e);
780 Logging.error(e);
781 if (e.getCause() instanceof ClassNotFoundException) {
782 msg = tr("<html>Could not load plugin {0} because the plugin<br>main class ''{1}'' was not found.<br>"
783 + "Delete from preferences?</html>", Utils.escapeReservedCharactersHTML(plugin.name), plugin.className);
784 }
785 } catch (RuntimeException e) { // NOPMD
786 pluginLoadingExceptions.put(plugin.name, e);
787 Logging.error(e);
788 }
789 if (msg != null && confirmDisablePlugin(parent, msg, plugin.name)) {
790 PreferencesUtils.removeFromList(Config.getPref(), "plugins", plugin.name);
791 }
792 }
793
794 /**
795 * Loads the plugin in <code>plugins</code> from locally available jar files into memory.
796 *
797 * @param parent The parent component to be used for the displayed dialog
798 * @param plugins the list of plugins
799 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null.
800 */
801 public static void loadPlugins(Component parent, Collection<PluginInformation> plugins, ProgressMonitor monitor) {
802 if (monitor == null) {
803 monitor = NullProgressMonitor.INSTANCE;
804 }
805 try {
806 monitor.beginTask(tr("Loading plugins ..."));
807 monitor.subTask(tr("Checking plugin preconditions..."));
808 List<PluginInformation> toLoad = new LinkedList<>();
809 for (PluginInformation pi: plugins) {
810 if (checkLoadPreconditions(parent, plugins, pi)) {
811 toLoad.add(pi);
812 }
813 }
814 // sort the plugins according to their "staging" equivalence class. The
815 // lower the value of "stage" the earlier the plugin should be loaded.
816 //
817 toLoad.sort(Comparator.comparingInt(o -> o.stage));
818 if (toLoad.isEmpty())
819 return;
820
821 Map<PluginInformation, PluginClassLoader> classLoaders = new HashMap<>();
822 for (PluginInformation info : toLoad) {
823 PluginClassLoader cl = AccessController.doPrivileged((PrivilegedAction<PluginClassLoader>)
824 () -> new PluginClassLoader(
825 info.libraries.toArray(new URL[0]),
826 PluginHandler.class.getClassLoader(),
827 null));
828 classLoaders.put(info, cl);
829 }
830
831 // resolve dependencies
832 for (PluginInformation info : toLoad) {
833 PluginClassLoader cl = classLoaders.get(info);
834 DEPENDENCIES:
835 for (String depName : info.getLocalRequiredPlugins()) {
836 for (PluginInformation depInfo : toLoad) {
837 if (depInfo.getName().equals(depName)) {
838 cl.addDependency(classLoaders.get(depInfo));
839 continue DEPENDENCIES;
840 }
841 }
842 for (PluginProxy proxy : pluginList) {
843 if (proxy.getPluginInformation().getName().equals(depName)) {
844 cl.addDependency(proxy.getClassLoader());
845 continue DEPENDENCIES;
846 }
847 }
848 Logging.error("unable to find dependency " + depName + " for plugin " + info.getName());
849 }
850 }
851
852 extendJoinedPluginResourceCL(toLoad);
853 ImageProvider.addAdditionalClassLoaders(getResourceClassLoaders());
854 monitor.setTicksCount(toLoad.size());
855 for (PluginInformation info : toLoad) {
856 monitor.setExtraText(tr("Loading plugin ''{0}''...", info.name));
857 loadPlugin(parent, info, classLoaders.get(info));
858 monitor.worked(1);
859 }
860 } finally {
861 monitor.finishTask();
862 }
863 }
864
865 /**
866 * Loads plugins from <code>plugins</code> which have the flag {@link PluginInformation#early} set to true.
867 *
868 * @param parent The parent component to be used for the displayed dialog
869 * @param plugins the collection of plugins
870 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null.
871 */
872 public static void loadEarlyPlugins(Component parent, Collection<PluginInformation> plugins, ProgressMonitor monitor) {
873 List<PluginInformation> earlyPlugins = new ArrayList<>(plugins.size());
874 for (PluginInformation pi: plugins) {
875 if (pi.early) {
876 earlyPlugins.add(pi);
877 }
878 }
879 loadPlugins(parent, earlyPlugins, monitor);
880 }
881
882 /**
883 * Loads plugins from <code>plugins</code> which have the flag {@link PluginInformation#early} set to false.
884 *
885 * @param parent The parent component to be used for the displayed dialog
886 * @param plugins the collection of plugins
887 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null.
888 */
889 public static void loadLatePlugins(Component parent, Collection<PluginInformation> plugins, ProgressMonitor monitor) {
890 List<PluginInformation> latePlugins = new ArrayList<>(plugins.size());
891 for (PluginInformation pi: plugins) {
892 if (!pi.early) {
893 latePlugins.add(pi);
894 }
895 }
896 loadPlugins(parent, latePlugins, monitor);
897 }
898
899 /**
900 * Loads locally available plugin information from local plugin jars and from cached
901 * plugin lists.
902 *
903 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null.
904 * @return the list of locally available plugin information
905 *
906 */
907 private static Map<String, PluginInformation> loadLocallyAvailablePluginInformation(ProgressMonitor monitor) {
908 if (monitor == null) {
909 monitor = NullProgressMonitor.INSTANCE;
910 }
911 try {
912 ReadLocalPluginInformationTask task = new ReadLocalPluginInformationTask(monitor);
913 try {
914 task.run();
915 } catch (RuntimeException e) { // NOPMD
916 Logging.error(e);
917 return null;
918 }
919 Map<String, PluginInformation> ret = new HashMap<>();
920 for (PluginInformation pi: task.getAvailablePlugins()) {
921 ret.put(pi.name, pi);
922 }
923 return ret;
924 } finally {
925 monitor.finishTask();
926 }
927 }
928
929 private static void alertMissingPluginInformation(Component parent, Collection<String> plugins) {
930 StringBuilder sb = new StringBuilder();
931 sb.append("<html>")
932 .append(trn("JOSM could not find information about the following plugin:",
933 "JOSM could not find information about the following plugins:",
934 plugins.size()))
935 .append(Utils.joinAsHtmlUnorderedList(plugins))
936 .append(trn("The plugin is not going to be loaded.",
937 "The plugins are not going to be loaded.",
938 plugins.size()))
939 .append("</html>");
940 HelpAwareOptionPane.showOptionDialog(
941 parent,
942 sb.toString(),
943 tr("Warning"),
944 JOptionPane.WARNING_MESSAGE,
945 ht("/Plugin/Loading#MissingPluginInfos")
946 );
947 }
948
949 /**
950 * Builds the set of plugins to load. Deprecated and unmaintained plugins are filtered
951 * out. This involves user interaction. This method displays alert and confirmation
952 * messages.
953 *
954 * @param parent The parent component to be used for the displayed dialog
955 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null.
956 * @return the set of plugins to load (as set of plugin names)
957 */
958 public static List<PluginInformation> buildListOfPluginsToLoad(Component parent, ProgressMonitor monitor) {
959 if (monitor == null) {
960 monitor = NullProgressMonitor.INSTANCE;
961 }
962 try {
963 monitor.beginTask(tr("Determining plugins to load..."));
964 Set<String> plugins = new HashSet<>(Config.getPref().getList("plugins", new LinkedList<String>()));
965 Logging.debug("Plugins list initialized to {0}", plugins);
966 String systemProp = System.getProperty("josm.plugins");
967 if (systemProp != null) {
968 plugins.addAll(Arrays.asList(systemProp.split(",")));
969 Logging.debug("josm.plugins system property set to '{0}'. Plugins list is now {1}", systemProp, plugins);
970 }
971 monitor.subTask(tr("Removing deprecated plugins..."));
972 filterDeprecatedPlugins(parent, plugins);
973 monitor.subTask(tr("Removing unmaintained plugins..."));
974 filterUnmaintainedPlugins(parent, plugins);
975 Logging.debug("Plugins list is finally set to {0}", plugins);
976 Map<String, PluginInformation> infos = loadLocallyAvailablePluginInformation(monitor.createSubTaskMonitor(1, false));
977 List<PluginInformation> ret = new LinkedList<>();
978 if (infos != null) {
979 for (Iterator<String> it = plugins.iterator(); it.hasNext();) {
980 String plugin = it.next();
981 if (infos.containsKey(plugin)) {
982 ret.add(infos.get(plugin));
983 it.remove();
984 }
985 }
986 }
987 if (!plugins.isEmpty()) {
988 alertMissingPluginInformation(parent, plugins);
989 }
990 return ret;
991 } finally {
992 monitor.finishTask();
993 }
994 }
995
996 private static void alertFailedPluginUpdate(Component parent, Collection<PluginInformation> plugins) {
997 StringBuilder sb = new StringBuilder(128);
998 sb.append("<html>")
999 .append(trn(
1000 "Updating the following plugin has failed:",
1001 "Updating the following plugins has failed:",
1002 plugins.size()))
1003 .append("<ul>");
1004 for (PluginInformation pi: plugins) {
1005 sb.append("<li>").append(Utils.escapeReservedCharactersHTML(pi.name)).append("</li>");
1006 }
1007 sb.append("</ul>")
1008 .append(trn(
1009 "Please open the Preference Dialog after JOSM has started and try to update it manually.",
1010 "Please open the Preference Dialog after JOSM has started and try to update them manually.",
1011 plugins.size()))
1012 .append("</html>");
1013 HelpAwareOptionPane.showOptionDialog(
1014 parent,
1015 sb.toString(),
1016 tr("Plugin update failed"),
1017 JOptionPane.ERROR_MESSAGE,
1018 ht("/Plugin/Loading#FailedPluginUpdated")
1019 );
1020 }
1021
1022 private static Set<PluginInformation> findRequiredPluginsToDownload(
1023 Collection<PluginInformation> pluginsToUpdate, List<PluginInformation> allPlugins, Set<PluginInformation> pluginsToDownload) {
1024 Set<PluginInformation> result = new HashSet<>();
1025 for (PluginInformation pi : pluginsToUpdate) {
1026 for (String name : pi.getRequiredPlugins()) {
1027 try {
1028 PluginInformation installedPlugin = PluginInformation.findPlugin(name);
1029 if (installedPlugin == null) {
1030 // New required plugin is not installed, find its PluginInformation
1031 PluginInformation reqPlugin = null;
1032 for (PluginInformation pi2 : allPlugins) {
1033 if (pi2.getName().equals(name)) {
1034 reqPlugin = pi2;
1035 break;
1036 }
1037 }
1038 // Required plugin is known but not already on download list
1039 if (reqPlugin != null && !pluginsToDownload.contains(reqPlugin)) {
1040 result.add(reqPlugin);
1041 }
1042 }
1043 } catch (PluginException e) {
1044 Logging.warn(tr("Failed to find plugin {0}", name));
1045 Logging.error(e);
1046 }
1047 }
1048 }
1049 return result;
1050 }
1051
1052 /**
1053 * Updates the plugins in <code>plugins</code>.
1054 *
1055 * @param parent the parent component for message boxes
1056 * @param pluginsWanted the collection of plugins to update. Updates all plugins if {@code null}
1057 * @param monitor the progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null.
1058 * @param displayErrMsg if {@code true}, a blocking error message is displayed in case of I/O exception.
1059 * @return the list of plugins to load
1060 * @throws IllegalArgumentException if plugins is null
1061 */
1062 public static Collection<PluginInformation> updatePlugins(Component parent,
1063 Collection<PluginInformation> pluginsWanted, ProgressMonitor monitor, boolean displayErrMsg) {
1064 Collection<PluginInformation> plugins = null;
1065 pluginDownloadTask = null;
1066 if (monitor == null) {
1067 monitor = NullProgressMonitor.INSTANCE;
1068 }
1069 try {
1070 monitor.beginTask("");
1071
1072 // try to download the plugin lists
1073 ReadRemotePluginInformationTask task1 = new ReadRemotePluginInformationTask(
1074 monitor.createSubTaskMonitor(1, false),
1075 Main.pref.getOnlinePluginSites(), displayErrMsg
1076 );
1077 task1.run();
1078 List<PluginInformation> allPlugins = task1.getAvailablePlugins();
1079
1080 try {
1081 plugins = buildListOfPluginsToLoad(parent, monitor.createSubTaskMonitor(1, false));
1082 // If only some plugins have to be updated, filter the list
1083 if (pluginsWanted != null && !pluginsWanted.isEmpty()) {
1084 final Collection<String> pluginsWantedName = Utils.transform(pluginsWanted, piw -> piw.name);
1085 plugins = SubclassFilteredCollection.filter(plugins, pi -> pluginsWantedName.contains(pi.name));
1086 }
1087 } catch (RuntimeException e) { // NOPMD
1088 Logging.warn(tr("Failed to download plugin information list"));
1089 Logging.error(e);
1090 // don't abort in case of error, continue with downloading plugins below
1091 }
1092
1093 // filter plugins which actually have to be updated
1094 Collection<PluginInformation> pluginsToUpdate = new ArrayList<>();
1095 if (plugins != null) {
1096 for (PluginInformation pi: plugins) {
1097 if (pi.isUpdateRequired()) {
1098 pluginsToUpdate.add(pi);
1099 }
1100 }
1101 }
1102
1103 if (!pluginsToUpdate.isEmpty()) {
1104
1105 Set<PluginInformation> pluginsToDownload = new HashSet<>(pluginsToUpdate);
1106
1107 if (allPlugins != null) {
1108 // Updated plugins may need additional plugin dependencies currently not installed
1109 //
1110 Set<PluginInformation> additionalPlugins = findRequiredPluginsToDownload(pluginsToUpdate, allPlugins, pluginsToDownload);
1111 pluginsToDownload.addAll(additionalPlugins);
1112
1113 // Iterate on required plugins, if they need themselves another plugins (i.e A needs B, but B needs C)
1114 while (!additionalPlugins.isEmpty()) {
1115 // Install the additional plugins to load them later
1116 if (plugins != null)
1117 plugins.addAll(additionalPlugins);
1118 additionalPlugins = findRequiredPluginsToDownload(additionalPlugins, allPlugins, pluginsToDownload);
1119 pluginsToDownload.addAll(additionalPlugins);
1120 }
1121 }
1122
1123 // try to update the locally installed plugins
1124 pluginDownloadTask = new PluginDownloadTask(
1125 monitor.createSubTaskMonitor(1, false),
1126 pluginsToDownload,
1127 tr("Update plugins")
1128 );
1129
1130 try {
1131 pluginDownloadTask.run();
1132 } catch (RuntimeException e) { // NOPMD
1133 Logging.error(e);
1134 alertFailedPluginUpdate(parent, pluginsToUpdate);
1135 return plugins;
1136 }
1137
1138 // Update Plugin info for downloaded plugins
1139 refreshLocalUpdatedPluginInfo(pluginDownloadTask.getDownloadedPlugins());
1140
1141 // notify user if downloading a locally installed plugin failed
1142 if (!pluginDownloadTask.getFailedPlugins().isEmpty()) {
1143 alertFailedPluginUpdate(parent, pluginDownloadTask.getFailedPlugins());
1144 return plugins;
1145 }
1146 }
1147 } finally {
1148 monitor.finishTask();
1149 }
1150 if (pluginsWanted == null) {
1151 // if all plugins updated, remember the update because it was successful
1152 Config.getPref().putInt("pluginmanager.version", Version.getInstance().getVersion());
1153 Config.getPref().put("pluginmanager.lastupdate", Long.toString(System.currentTimeMillis()));
1154 }
1155 return plugins;
1156 }
1157
1158 /**
1159 * Ask the user for confirmation that a plugin shall be disabled.
1160 *
1161 * @param parent The parent component to be used for the displayed dialog
1162 * @param reason the reason for disabling the plugin
1163 * @param name the plugin name
1164 * @return true, if the plugin shall be disabled; false, otherwise
1165 */
1166 public static boolean confirmDisablePlugin(Component parent, String reason, String name) {
1167 ButtonSpec[] options = new ButtonSpec[] {
1168 new ButtonSpec(
1169 tr("Disable plugin"),
1170 ImageProvider.get("dialogs", "delete"),
1171 tr("Click to delete the plugin ''{0}''", name),
1172 null /* no specific help context */
1173 ),
1174 new ButtonSpec(
1175 tr("Keep plugin"),
1176 ImageProvider.get("cancel"),
1177 tr("Click to keep the plugin ''{0}''", name),
1178 null /* no specific help context */
1179 )
1180 };
1181 return 0 == HelpAwareOptionPane.showOptionDialog(
1182 parent,
1183 reason,
1184 tr("Disable plugin"),
1185 JOptionPane.WARNING_MESSAGE,
1186 null,
1187 options,
1188 options[0],
1189 null // FIXME: add help topic
1190 );
1191 }
1192
1193 /**
1194 * Returns the plugin of the specified name.
1195 * @param name The plugin name
1196 * @return The plugin of the specified name, if installed and loaded, or {@code null} otherwise.
1197 */
1198 public static Object getPlugin(String name) {
1199 for (PluginProxy plugin : pluginList) {
1200 if (plugin.getPluginInformation().name.equals(name))
1201 return plugin.getPlugin();
1202 }
1203 return null;
1204 }
1205
1206 /**
1207 * Returns the plugin class loader for the plugin of the specified name.
1208 * @param name The plugin name
1209 * @return The plugin class loader for the plugin of the specified name, if
1210 * installed and loaded, or {@code null} otherwise.
1211 * @since 12323
1212 */
1213 public static PluginClassLoader getPluginClassLoader(String name) {
1214 for (PluginProxy plugin : pluginList) {
1215 if (plugin.getPluginInformation().name.equals(name))
1216 return plugin.getClassLoader();
1217 }
1218 return null;
1219 }
1220
1221 public static void addDownloadSelection(List<DownloadSelection> downloadSelections) {
1222 for (PluginProxy p : pluginList) {
1223 p.addDownloadSelection(downloadSelections);
1224 }
1225 }
1226
1227 public static Collection<PreferenceSettingFactory> getPreferenceSetting() {
1228 Collection<PreferenceSettingFactory> settings = new ArrayList<>();
1229 for (PluginProxy plugin : pluginList) {
1230 settings.add(new PluginPreferenceFactory(plugin));
1231 }
1232 return settings;
1233 }
1234
1235 /**
1236 * Installs downloaded plugins. Moves files with the suffix ".jar.new" to the corresponding
1237 * ".jar" files.
1238 *
1239 * If {@code dowarn} is true, this methods emits warning messages on the console if a downloaded
1240 * but not yet installed plugin .jar can't be be installed. If {@code dowarn} is false, the
1241 * installation of the respective plugin is silently skipped.
1242 *
1243 * @param dowarn if true, warning messages are displayed; false otherwise
1244 */
1245 public static void installDownloadedPlugins(boolean dowarn) {
1246 File pluginDir = Main.pref.getPluginsDirectory();
1247 if (!pluginDir.exists() || !pluginDir.isDirectory() || !pluginDir.canWrite())
1248 return;
1249
1250 final File[] files = pluginDir.listFiles((FilenameFilter) (dir, name) -> name.endsWith(".jar.new"));
1251 if (files == null)
1252 return;
1253
1254 for (File updatedPlugin : files) {
1255 final String filePath = updatedPlugin.getPath();
1256 File plugin = new File(filePath.substring(0, filePath.length() - 4));
1257 String pluginName = updatedPlugin.getName().substring(0, updatedPlugin.getName().length() - 8);
1258 if (plugin.exists() && !plugin.delete() && dowarn) {
1259 Logging.warn(tr("Failed to delete outdated plugin ''{0}''.", plugin.toString()));
1260 Logging.warn(tr("Failed to install already downloaded plugin ''{0}''. " +
1261 "Skipping installation. JOSM is still going to load the old plugin version.",
1262 pluginName));
1263 continue;
1264 }
1265 try {
1266 // Check the plugin is a valid and accessible JAR file before installing it (fix #7754)
1267 new JarFile(updatedPlugin).close();
1268 } catch (IOException e) {
1269 if (dowarn) {
1270 Logging.log(Logging.LEVEL_WARN, tr("Failed to install plugin ''{0}'' from temporary download file ''{1}''. {2}",
1271 plugin.toString(), updatedPlugin.toString(), e.getLocalizedMessage()), e);
1272 }
1273 continue;
1274 }
1275 // Install plugin
1276 if (!updatedPlugin.renameTo(plugin) && dowarn) {
1277 Logging.warn(tr("Failed to install plugin ''{0}'' from temporary download file ''{1}''. Renaming failed.",
1278 plugin.toString(), updatedPlugin.toString()));
1279 Logging.warn(tr("Failed to install already downloaded plugin ''{0}''. " +
1280 "Skipping installation. JOSM is still going to load the old plugin version.",
1281 pluginName));
1282 }
1283 }
1284 }
1285
1286 /**
1287 * Determines if the specified file is a valid and accessible JAR file.
1288 * @param jar The file to check
1289 * @return true if file can be opened as a JAR file.
1290 * @since 5723
1291 */
1292 public static boolean isValidJar(File jar) {
1293 if (jar != null && jar.exists() && jar.canRead()) {
1294 try {
1295 new JarFile(jar).close();
1296 } catch (IOException e) {
1297 Logging.warn(e);
1298 return false;
1299 }
1300 return true;
1301 } else if (jar != null) {
1302 Logging.warn("Invalid jar file ''"+jar+"'' (exists: "+jar.exists()+", canRead: "+jar.canRead()+')');
1303 }
1304 return false;
1305 }
1306
1307 /**
1308 * Replies the updated jar file for the given plugin name.
1309 * @param name The plugin name to find.
1310 * @return the updated jar file for the given plugin name. null if not found or not readable.
1311 * @since 5601
1312 */
1313 public static File findUpdatedJar(String name) {
1314 File pluginDir = Main.pref.getPluginsDirectory();
1315 // Find the downloaded file. We have tried to install the downloaded plugins
1316 // (PluginHandler.installDownloadedPlugins). This succeeds depending on the platform.
1317 File downloadedPluginFile = new File(pluginDir, name + ".jar.new");
1318 if (!isValidJar(downloadedPluginFile)) {
1319 downloadedPluginFile = new File(pluginDir, name + ".jar");
1320 if (!isValidJar(downloadedPluginFile)) {
1321 return null;
1322 }
1323 }
1324 return downloadedPluginFile;
1325 }
1326
1327 /**
1328 * Refreshes the given PluginInformation objects with new contents read from their corresponding jar file.
1329 * @param updatedPlugins The PluginInformation objects to update.
1330 * @since 5601
1331 */
1332 public static void refreshLocalUpdatedPluginInfo(Collection<PluginInformation> updatedPlugins) {
1333 if (updatedPlugins == null) return;
1334 for (PluginInformation pi : updatedPlugins) {
1335 File downloadedPluginFile = findUpdatedJar(pi.name);
1336 if (downloadedPluginFile == null) {
1337 continue;
1338 }
1339 try {
1340 pi.updateFromJar(new PluginInformation(downloadedPluginFile, pi.name));
1341 } catch (PluginException e) {
1342 Logging.error(e);
1343 }
1344 }
1345 }
1346
1347 private static int askUpdateDisableKeepPluginAfterException(PluginProxy plugin) {
1348 final ButtonSpec[] options = new ButtonSpec[] {
1349 new ButtonSpec(
1350 tr("Update plugin"),
1351 ImageProvider.get("dialogs", "refresh"),
1352 tr("Click to update the plugin ''{0}''", plugin.getPluginInformation().name),
1353 null /* no specific help context */
1354 ),
1355 new ButtonSpec(
1356 tr("Disable plugin"),
1357 ImageProvider.get("dialogs", "delete"),
1358 tr("Click to disable the plugin ''{0}''", plugin.getPluginInformation().name),
1359 null /* no specific help context */
1360 ),
1361 new ButtonSpec(
1362 tr("Keep plugin"),
1363 ImageProvider.get("cancel"),
1364 tr("Click to keep the plugin ''{0}''", plugin.getPluginInformation().name),
1365 null /* no specific help context */
1366 )
1367 };
1368
1369 final StringBuilder msg = new StringBuilder(256);
1370 msg.append("<html>")
1371 .append(tr("An unexpected exception occurred that may have come from the ''{0}'' plugin.",
1372 Utils.escapeReservedCharactersHTML(plugin.getPluginInformation().name)))
1373 .append("<br>");
1374 if (plugin.getPluginInformation().author != null) {
1375 msg.append(tr("According to the information within the plugin, the author is {0}.",
1376 Utils.escapeReservedCharactersHTML(plugin.getPluginInformation().author)))
1377 .append("<br>");
1378 }
1379 msg.append(tr("Try updating to the newest version of this plugin before reporting a bug."))
1380 .append("</html>");
1381
1382 try {
1383 FutureTask<Integer> task = new FutureTask<>(() -> HelpAwareOptionPane.showOptionDialog(
1384 Main.parent,
1385 msg.toString(),
1386 tr("Update plugins"),
1387 JOptionPane.QUESTION_MESSAGE,
1388 null,
1389 options,
1390 options[0],
1391 ht("/ErrorMessages#ErrorInPlugin")
1392 ));
1393 GuiHelper.runInEDT(task);
1394 return task.get();
1395 } catch (InterruptedException | ExecutionException e) {
1396 Logging.warn(e);
1397 }
1398 return -1;
1399 }
1400
1401 /**
1402 * Replies the plugin which most likely threw the exception <code>ex</code>.
1403 *
1404 * @param ex the exception
1405 * @return the plugin; null, if the exception probably wasn't thrown from a plugin
1406 */
1407 private static PluginProxy getPluginCausingException(Throwable ex) {
1408 PluginProxy err = null;
1409 List<StackTraceElement> stack = new ArrayList<>();
1410 Set<Throwable> seen = new HashSet<>();
1411 Throwable current = ex;
1412 while (current != null) {
1413 seen.add(current);
1414 stack.addAll(Arrays.asList(current.getStackTrace()));
1415 Throwable cause = current.getCause();
1416 if (cause != null && seen.contains(cause)) {
1417 break; // circular refernce
1418 }
1419 current = cause;
1420 }
1421
1422 // remember the error position, as multiple plugins may be involved, we search the topmost one
1423 int pos = stack.size();
1424 for (PluginProxy p : pluginList) {
1425 String baseClass = p.getPluginInformation().className;
1426 baseClass = baseClass.substring(0, baseClass.lastIndexOf('.'));
1427 for (int elpos = 0; elpos < pos; ++elpos) {
1428 if (stack.get(elpos).getClassName().startsWith(baseClass)) {
1429 pos = elpos;
1430 err = p;
1431 }
1432 }
1433 }
1434 return err;
1435 }
1436
1437 /**
1438 * Checks whether the exception <code>e</code> was thrown by a plugin. If so,
1439 * conditionally updates or deactivates the plugin, but asks the user first.
1440 *
1441 * @param e the exception
1442 * @return plugin download task if the plugin has been updated to a newer version, {@code null} if it has been disabled or kept as it
1443 */
1444 public static PluginDownloadTask updateOrdisablePluginAfterException(Throwable e) {
1445 PluginProxy plugin = null;
1446 // Check for an explicit problem when calling a plugin function
1447 if (e instanceof PluginException) {
1448 plugin = ((PluginException) e).plugin;
1449 }
1450 if (plugin == null) {
1451 plugin = getPluginCausingException(e);
1452 }
1453 if (plugin == null)
1454 // don't know what plugin threw the exception
1455 return null;
1456
1457 Set<String> plugins = new HashSet<>(Config.getPref().getList("plugins"));
1458 final PluginInformation pluginInfo = plugin.getPluginInformation();
1459 if (!plugins.contains(pluginInfo.name))
1460 // plugin not activated ? strange in this context but anyway, don't bother
1461 // the user with dialogs, skip conditional deactivation
1462 return null;
1463
1464 switch (askUpdateDisableKeepPluginAfterException(plugin)) {
1465 case 0:
1466 // update the plugin
1467 updatePlugins(Main.parent, Collections.singleton(pluginInfo), null, true);
1468 return pluginDownloadTask;
1469 case 1:
1470 // deactivate the plugin
1471 plugins.remove(plugin.getPluginInformation().name);
1472 Config.getPref().putList("plugins", new ArrayList<>(plugins));
1473 GuiHelper.runInEDTAndWait(() -> JOptionPane.showMessageDialog(
1474 Main.parent,
1475 tr("The plugin has been removed from the configuration. Please restart JOSM to unload the plugin."),
1476 tr("Information"),
1477 JOptionPane.INFORMATION_MESSAGE
1478 ));
1479 return null;
1480 default:
1481 // user doesn't want to deactivate the plugin
1482 return null;
1483 }
1484 }
1485
1486 /**
1487 * Returns the list of loaded plugins as a {@code String} to be displayed in status report. Useful for bug reports.
1488 * @return The list of loaded plugins
1489 */
1490 public static Collection<String> getBugReportInformation() {
1491 final Collection<String> pl = new TreeSet<>(Config.getPref().getList("plugins", new LinkedList<>()));
1492 for (final PluginProxy pp : pluginList) {
1493 PluginInformation pi = pp.getPluginInformation();
1494 pl.remove(pi.name);
1495 pl.add(pi.name + " (" + (pi.localversion != null && !pi.localversion.isEmpty()
1496 ? pi.localversion : "unknown") + ')');
1497 }
1498 return pl;
1499 }
1500
1501 /**
1502 * Returns the list of loaded plugins as a {@code JPanel} to be displayed in About dialog.
1503 * @return The list of loaded plugins (one "line" of Swing components per plugin)
1504 */
1505 public static JPanel getInfoPanel() {
1506 JPanel pluginTab = new JPanel(new GridBagLayout());
1507 for (final PluginProxy p : pluginList) {
1508 final PluginInformation info = p.getPluginInformation();
1509 String name = info.name
1510 + (info.version != null && !info.version.isEmpty() ? " Version: " + info.version : "");
1511 pluginTab.add(new JLabel(name), GBC.std());
1512 pluginTab.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL));
1513 pluginTab.add(new JButton(new PluginInformationAction(info)), GBC.eol());
1514
1515 JosmTextArea description = new JosmTextArea(info.description == null ? tr("no description available")
1516 : info.description);
1517 description.setEditable(false);
1518 description.setFont(new JLabel().getFont().deriveFont(Font.ITALIC));
1519 description.setLineWrap(true);
1520 description.setWrapStyleWord(true);
1521 description.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
1522 description.setBackground(UIManager.getColor("Panel.background"));
1523 description.setCaretPosition(0);
1524
1525 pluginTab.add(description, GBC.eop().fill(GBC.HORIZONTAL));
1526 }
1527 return pluginTab;
1528 }
1529
1530 /**
1531 * Returns the set of deprecated and unmaintained plugins.
1532 * @return set of deprecated and unmaintained plugins names.
1533 * @since 8938
1534 */
1535 public static Set<String> getDeprecatedAndUnmaintainedPlugins() {
1536 Set<String> result = new HashSet<>(DEPRECATED_PLUGINS.size() + UNMAINTAINED_PLUGINS.size());
1537 for (DeprecatedPlugin dp : DEPRECATED_PLUGINS) {
1538 result.add(dp.name);
1539 }
1540 result.addAll(UNMAINTAINED_PLUGINS);
1541 return result;
1542 }
1543
1544 private static class UpdatePluginsMessagePanel extends JPanel {
1545 private final JMultilineLabel lblMessage = new JMultilineLabel("");
1546 private final JCheckBox cbDontShowAgain = new JCheckBox(
1547 tr("Do not ask again and remember my decision (go to Preferences->Plugins to change it later)"));
1548
1549 UpdatePluginsMessagePanel() {
1550 build();
1551 }
1552
1553 protected final void build() {
1554 setLayout(new GridBagLayout());
1555 GridBagConstraints gc = new GridBagConstraints();
1556 gc.anchor = GridBagConstraints.NORTHWEST;
1557 gc.fill = GridBagConstraints.BOTH;
1558 gc.weightx = 1.0;
1559 gc.weighty = 1.0;
1560 gc.insets = new Insets(5, 5, 5, 5);
1561 add(lblMessage, gc);
1562 lblMessage.setFont(lblMessage.getFont().deriveFont(Font.PLAIN));
1563
1564 gc.gridy = 1;
1565 gc.fill = GridBagConstraints.HORIZONTAL;
1566 gc.weighty = 0.0;
1567 add(cbDontShowAgain, gc);
1568 cbDontShowAgain.setFont(cbDontShowAgain.getFont().deriveFont(Font.PLAIN));
1569 }
1570
1571 public void setMessage(String message) {
1572 lblMessage.setText(message);
1573 }
1574
1575 public void initDontShowAgain(String preferencesKey) {
1576 String policy = Config.getPref().get(preferencesKey, "ask");
1577 policy = policy.trim().toLowerCase(Locale.ENGLISH);
1578 cbDontShowAgain.setSelected(!"ask".equals(policy));
1579 }
1580
1581 public boolean isRememberDecision() {
1582 return cbDontShowAgain.isSelected();
1583 }
1584 }
1585}
Note: See TracBrowser for help on using the repository browser.