001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.plugins; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.io.File; 007import java.io.IOException; 008import java.io.InputStream; 009import java.lang.reflect.Constructor; 010import java.net.URL; 011import java.nio.file.Files; 012import java.nio.file.InvalidPathException; 013import java.text.MessageFormat; 014import java.util.ArrayList; 015import java.util.Collection; 016import java.util.LinkedList; 017import java.util.List; 018import java.util.Locale; 019import java.util.Map; 020import java.util.Optional; 021import java.util.TreeMap; 022import java.util.jar.Attributes; 023import java.util.jar.JarInputStream; 024import java.util.jar.Manifest; 025 026import javax.swing.ImageIcon; 027 028import org.openstreetmap.josm.data.Preferences; 029import org.openstreetmap.josm.data.Version; 030import org.openstreetmap.josm.tools.ImageProvider; 031import org.openstreetmap.josm.tools.LanguageInfo; 032import org.openstreetmap.josm.tools.Logging; 033import org.openstreetmap.josm.tools.Platform; 034import org.openstreetmap.josm.tools.PlatformManager; 035import org.openstreetmap.josm.tools.Utils; 036 037/** 038 * Encapsulate general information about a plugin. This information is available 039 * without the need of loading any class from the plugin jar file. 040 * 041 * @author imi 042 * @since 153 043 */ 044public class PluginInformation { 045 046 /** The plugin jar file. */ 047 public File file; 048 /** The plugin name. */ 049 public String name; 050 /** The lowest JOSM version required by this plugin (from plugin list). **/ 051 public int mainversion; 052 /** The lowest JOSM version required by this plugin (from locally available jar). **/ 053 public int localmainversion; 054 /** The lowest Java version required by this plugin (from plugin list). **/ 055 public int minjavaversion; 056 /** The lowest Java version required by this plugin (from locally available jar). **/ 057 public int localminjavaversion; 058 /** The plugin class name. */ 059 public String className; 060 /** Determines if the plugin is an old version loaded for incompatibility with latest JOSM (from plugin list) */ 061 public boolean oldmode; 062 /** The list of required plugins, separated by ';' (from plugin list). */ 063 public String requires; 064 /** The list of required plugins, separated by ';' (from locally available jar). */ 065 public String localrequires; 066 /** The plugin platform on which it is meant to run (windows, osx, unixoid). */ 067 public String platform; 068 /** The virtual plugin provided by this plugin, if native for a given platform. */ 069 public String provides; 070 /** The plugin link (for documentation). */ 071 public String link; 072 /** The plugin description. */ 073 public String description; 074 /** Determines if the plugin must be loaded early or not. */ 075 public boolean early; 076 /** The plugin author. */ 077 public String author; 078 /** The plugin stage, determining the loading sequence order of plugins. */ 079 public int stage = 50; 080 /** The plugin version (from plugin list). **/ 081 public String version; 082 /** The plugin version (from locally available jar). **/ 083 public String localversion; 084 /** The plugin download link. */ 085 public String downloadlink; 086 /** The plugin icon path inside jar. */ 087 public String iconPath; 088 /** The plugin icon. */ 089 private ImageProvider icon; 090 /** Plugin can be loaded at any time and not just at start. */ 091 public boolean canloadatruntime; 092 /** The libraries referenced in Class-Path manifest attribute. */ 093 public List<URL> libraries = new LinkedList<>(); 094 /** All manifest attributes. */ 095 public final Map<String, String> attr = new TreeMap<>(); 096 /** Invalid manifest entries */ 097 final List<String> invalidManifestEntries = new ArrayList<>(); 098 /** Empty icon for these plugins which have none */ 099 private static final ImageIcon emptyIcon = ImageProvider.getEmpty(ImageProvider.ImageSizes.LARGEICON); 100 101 /** 102 * Creates a plugin information object by reading the plugin information from 103 * the manifest in the plugin jar. 104 * 105 * The plugin name is derived from the file name. 106 * 107 * @param file the plugin jar file 108 * @throws PluginException if reading the manifest fails 109 */ 110 public PluginInformation(File file) throws PluginException { 111 this(file, file.getName().substring(0, file.getName().length()-4)); 112 } 113 114 /** 115 * Creates a plugin information object for the plugin with name {@code name}. 116 * Information about the plugin is extracted from the manifest file in the plugin jar 117 * {@code file}. 118 * @param file the plugin jar 119 * @param name the plugin name 120 * @throws PluginException if reading the manifest file fails 121 */ 122 public PluginInformation(File file, String name) throws PluginException { 123 if (!PluginHandler.isValidJar(file)) { 124 throw new PluginException(tr("Invalid jar file ''{0}''", file)); 125 } 126 this.name = name; 127 this.file = file; 128 try ( 129 InputStream fis = Files.newInputStream(file.toPath()); 130 JarInputStream jar = new JarInputStream(fis) 131 ) { 132 Manifest manifest = jar.getManifest(); 133 if (manifest == null) 134 throw new PluginException(tr("The plugin file ''{0}'' does not include a Manifest.", file.toString())); 135 scanManifest(manifest, false); 136 libraries.add(0, Utils.fileToURL(file)); 137 } catch (IOException | InvalidPathException e) { 138 throw new PluginException(name, e); 139 } 140 } 141 142 /** 143 * Creates a plugin information object by reading plugin information in Manifest format 144 * from the input stream {@code manifestStream}. 145 * 146 * @param manifestStream the stream to read the manifest from 147 * @param name the plugin name 148 * @param url the download URL for the plugin 149 * @throws PluginException if the plugin information can't be read from the input stream 150 */ 151 public PluginInformation(InputStream manifestStream, String name, String url) throws PluginException { 152 this.name = name; 153 try { 154 Manifest manifest = new Manifest(); 155 manifest.read(manifestStream); 156 if (url != null) { 157 downloadlink = url; 158 } 159 scanManifest(manifest, url != null); 160 } catch (IOException e) { 161 throw new PluginException(name, e); 162 } 163 } 164 165 /** 166 * Updates the plugin information of this plugin information object with the 167 * plugin information in a plugin information object retrieved from a plugin 168 * update site. 169 * 170 * @param other the plugin information object retrieved from the update site 171 */ 172 public void updateFromPluginSite(PluginInformation other) { 173 this.mainversion = other.mainversion; 174 this.minjavaversion = other.minjavaversion; 175 this.className = other.className; 176 this.requires = other.requires; 177 this.provides = other.provides; 178 this.platform = other.platform; 179 this.link = other.link; 180 this.description = other.description; 181 this.early = other.early; 182 this.author = other.author; 183 this.stage = other.stage; 184 this.version = other.version; 185 this.downloadlink = other.downloadlink; 186 this.icon = other.icon; 187 this.iconPath = other.iconPath; 188 this.canloadatruntime = other.canloadatruntime; 189 this.libraries = other.libraries; 190 this.attr.clear(); 191 this.attr.putAll(other.attr); 192 this.invalidManifestEntries.clear(); 193 this.invalidManifestEntries.addAll(other.invalidManifestEntries); 194 } 195 196 /** 197 * Updates the plugin information of this plugin information object with the 198 * plugin information in a plugin information object retrieved from a plugin jar. 199 * 200 * @param other the plugin information object retrieved from the jar file 201 * @since 5601 202 */ 203 public void updateFromJar(PluginInformation other) { 204 updateLocalInfo(other); 205 if (other.icon != null) { 206 this.icon = other.icon; 207 } 208 this.early = other.early; 209 this.className = other.className; 210 this.canloadatruntime = other.canloadatruntime; 211 this.libraries = other.libraries; 212 this.stage = other.stage; 213 this.file = other.file; 214 } 215 216 private void scanManifest(Manifest manifest, boolean oldcheck) { 217 String lang = LanguageInfo.getLanguageCodeManifest(); 218 Attributes attr = manifest.getMainAttributes(); 219 className = attr.getValue("Plugin-Class"); 220 String s = Optional.ofNullable(attr.getValue(lang+"Plugin-Link")).orElseGet(() -> attr.getValue("Plugin-Link")); 221 if (s != null && !Utils.isValidUrl(s)) { 222 Logging.info(tr("Invalid URL ''{0}'' in plugin {1}", s, name)); 223 s = null; 224 } 225 link = s; 226 platform = attr.getValue("Plugin-Platform"); 227 provides = attr.getValue("Plugin-Provides"); 228 requires = attr.getValue("Plugin-Requires"); 229 s = attr.getValue(lang+"Plugin-Description"); 230 if (s == null) { 231 s = attr.getValue("Plugin-Description"); 232 if (s != null) { 233 try { 234 s = tr(s); 235 } catch (IllegalArgumentException e) { 236 Logging.debug(e); 237 Logging.info(tr("Invalid plugin description ''{0}'' in plugin {1}", s, name)); 238 } 239 } 240 } else { 241 s = MessageFormat.format(s, (Object[]) null); 242 } 243 description = s; 244 early = Boolean.parseBoolean(attr.getValue("Plugin-Early")); 245 String stageStr = attr.getValue("Plugin-Stage"); 246 stage = stageStr == null ? 50 : Integer.parseInt(stageStr); 247 version = attr.getValue("Plugin-Version"); 248 s = attr.getValue("Plugin-Mainversion"); 249 if (s != null) { 250 try { 251 mainversion = Integer.parseInt(s); 252 } catch (NumberFormatException e) { 253 Logging.warn(tr("Invalid plugin main version ''{0}'' in plugin {1}", s, name)); 254 Logging.trace(e); 255 } 256 } else { 257 Logging.warn(tr("Missing plugin main version in plugin {0}", name)); 258 } 259 s = attr.getValue("Plugin-Minimum-Java-Version"); 260 if (s != null) { 261 try { 262 minjavaversion = Integer.parseInt(s); 263 } catch (NumberFormatException e) { 264 Logging.warn(tr("Invalid Java version ''{0}'' in plugin {1}", s, name)); 265 Logging.trace(e); 266 } 267 } 268 author = attr.getValue("Author"); 269 iconPath = attr.getValue("Plugin-Icon"); 270 if (iconPath != null) { 271 if (file != null) { 272 // extract icon from the plugin jar file 273 icon = new ImageProvider(iconPath).setArchive(file).setMaxSize(ImageProvider.ImageSizes.LARGEICON).setOptional(true); 274 } else if (iconPath.startsWith("data:")) { 275 icon = new ImageProvider(iconPath).setMaxSize(ImageProvider.ImageSizes.LARGEICON).setOptional(true); 276 } 277 } 278 canloadatruntime = Boolean.parseBoolean(attr.getValue("Plugin-Canloadatruntime")); 279 int myv = Version.getInstance().getVersion(); 280 for (Map.Entry<Object, Object> entry : attr.entrySet()) { 281 String key = ((Attributes.Name) entry.getKey()).toString(); 282 if (key.endsWith("_Plugin-Url")) { 283 try { 284 int mv = Integer.parseInt(key.substring(0, key.length()-11)); 285 String v = (String) entry.getValue(); 286 int i = v.indexOf(';'); 287 if (i <= 0) { 288 invalidManifestEntries.add(key); 289 } else if (oldcheck && 290 mv <= myv && (mv > mainversion || mainversion > myv)) { 291 downloadlink = v.substring(i+1); 292 mainversion = mv; 293 version = v.substring(0, i); 294 oldmode = true; 295 } 296 } catch (NumberFormatException | IndexOutOfBoundsException e) { 297 invalidManifestEntries.add(key); 298 Logging.error(e); 299 } 300 } 301 } 302 303 String classPath = attr.getValue(Attributes.Name.CLASS_PATH); 304 if (classPath != null) { 305 for (String entry : classPath.split(" ")) { 306 File entryFile; 307 if (new File(entry).isAbsolute() || file == null) { 308 entryFile = new File(entry); 309 } else { 310 entryFile = new File(file.getParent(), entry); 311 } 312 313 libraries.add(Utils.fileToURL(entryFile)); 314 } 315 } 316 for (Object o : attr.keySet()) { 317 this.attr.put(o.toString(), attr.getValue(o.toString())); 318 } 319 } 320 321 /** 322 * Replies the description as HTML document, including a link to a web page with 323 * more information, provided such a link is available. 324 * 325 * @return the description as HTML document 326 */ 327 public String getDescriptionAsHtml() { 328 StringBuilder sb = new StringBuilder(128); 329 sb.append("<html><body>") 330 .append(description == null ? tr("no description available") : Utils.escapeReservedCharactersHTML(description)); 331 if (link != null) { 332 sb.append(" <a href=\"").append(link).append("\">").append(tr("More info...")).append("</a>"); 333 } 334 if (downloadlink != null 335 && !downloadlink.startsWith("http://svn.openstreetmap.org/applications/editors/josm/dist/") 336 && !downloadlink.startsWith("https://svn.openstreetmap.org/applications/editors/josm/dist/") 337 && !downloadlink.startsWith("http://trac.openstreetmap.org/browser/applications/editors/josm/dist/") 338 && !downloadlink.startsWith("https://github.com/JOSM/")) { 339 sb.append("<p> </p><p>").append(tr("<b>Plugin provided by an external source:</b> {0}", downloadlink)).append("</p>"); 340 } 341 sb.append("</body></html>"); 342 return sb.toString(); 343 } 344 345 /** 346 * Loads and instantiates the plugin. 347 * 348 * @param klass the plugin class 349 * @param classLoader the class loader for the plugin 350 * @return the instantiated and initialized plugin 351 * @throws PluginException if the plugin cannot be loaded or instanciated 352 * @since 12322 353 */ 354 public PluginProxy load(Class<?> klass, PluginClassLoader classLoader) throws PluginException { 355 try { 356 Constructor<?> c = klass.getConstructor(PluginInformation.class); 357 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); 358 Thread.currentThread().setContextClassLoader(classLoader); 359 try { 360 return new PluginProxy(c.newInstance(this), this, classLoader); 361 } finally { 362 Thread.currentThread().setContextClassLoader(contextClassLoader); 363 } 364 } catch (ReflectiveOperationException e) { 365 throw new PluginException(name, e); 366 } 367 } 368 369 /** 370 * Loads the class of the plugin. 371 * 372 * @param classLoader the class loader to use 373 * @return the loaded class 374 * @throws PluginException if the class cannot be loaded 375 */ 376 public Class<?> loadClass(ClassLoader classLoader) throws PluginException { 377 if (className == null) 378 return null; 379 try { 380 return Class.forName(className, true, classLoader); 381 } catch (NoClassDefFoundError | ClassNotFoundException | ClassCastException e) { 382 throw new PluginException(name, e); 383 } 384 } 385 386 /** 387 * Try to find a plugin after some criterias. Extract the plugin-information 388 * from the plugin and return it. The plugin is searched in the following way: 389 *<ol> 390 *<li>first look after an MANIFEST.MF in the package org.openstreetmap.josm.plugins.<plugin name> 391 * (After removing all fancy characters from the plugin name). 392 * If found, the plugin is loaded using the bootstrap classloader.</li> 393 *<li>If not found, look for a jar file in the user specific plugin directory 394 * (~/.josm/plugins/<plugin name>.jar)</li> 395 *<li>If not found and the environment variable JOSM_RESOURCES + "/plugins/" exist, look there.</li> 396 *<li>Try for the java property josm.resources + "/plugins/" (set via java -Djosm.plugins.path=...)</li> 397 *<li>If the environment variable ALLUSERSPROFILE and APPDATA exist, look in 398 * ALLUSERSPROFILE/<the last stuff from APPDATA>/JOSM/plugins. 399 * (*sic* There is no easy way under Windows to get the All User's application 400 * directory)</li> 401 *<li>Finally, look in some typical unix paths:<ul> 402 * <li>/usr/local/share/josm/plugins/</li> 403 * <li>/usr/local/lib/josm/plugins/</li> 404 * <li>/usr/share/josm/plugins/</li> 405 * <li>/usr/lib/josm/plugins/</li></ul></li> 406 *</ol> 407 * If a plugin class or jar file is found earlier in the list but seem not to 408 * be working, an PluginException is thrown rather than continuing the search. 409 * This is so JOSM can detect broken user-provided plugins and do not go silently 410 * ignore them. 411 * 412 * The plugin is not initialized. If the plugin is a .jar file, it is not loaded 413 * (only the manifest is extracted). In the classloader-case, the class is 414 * bootstraped (e.g. static {} - declarations will run. However, nothing else is done. 415 * 416 * @param pluginName The name of the plugin (in all lowercase). E.g. "lang-de" 417 * @return Information about the plugin or <code>null</code>, if the plugin 418 * was nowhere to be found. 419 * @throws PluginException In case of broken plugins. 420 */ 421 public static PluginInformation findPlugin(String pluginName) throws PluginException { 422 String name = pluginName; 423 name = name.replaceAll("[-. ]", ""); 424 try (InputStream manifestStream = Utils.getResourceAsStream( 425 PluginInformation.class, "/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF")) { 426 if (manifestStream != null) { 427 return new PluginInformation(manifestStream, pluginName, null); 428 } 429 } catch (IOException e) { 430 Logging.warn(e); 431 } 432 433 Collection<String> locations = getPluginLocations(); 434 435 String[] nameCandidates = new String[] { 436 pluginName, 437 pluginName + "-" + PlatformManager.getPlatform().getPlatform().name().toLowerCase(Locale.ENGLISH)}; 438 for (String s : locations) { 439 for (String nameCandidate: nameCandidates) { 440 File pluginFile = new File(s, nameCandidate + ".jar"); 441 if (pluginFile.exists()) { 442 return new PluginInformation(pluginFile); 443 } 444 } 445 } 446 return null; 447 } 448 449 /** 450 * Returns all possible plugin locations. 451 * @return all possible plugin locations. 452 */ 453 public static Collection<String> getPluginLocations() { 454 Collection<String> locations = Preferences.getAllPossiblePreferenceDirs(); 455 Collection<String> all = new ArrayList<>(locations.size()); 456 for (String s : locations) { 457 all.add(s+"plugins"); 458 } 459 return all; 460 } 461 462 /** 463 * Replies true if the plugin with the given information is most likely outdated with 464 * respect to the referenceVersion. 465 * 466 * @param referenceVersion the reference version. Can be null if we don't know a 467 * reference version 468 * 469 * @return true, if the plugin needs to be updated; false, otherweise 470 */ 471 public boolean isUpdateRequired(String referenceVersion) { 472 if (this.downloadlink == null) return false; 473 if (this.version == null && referenceVersion != null) 474 return true; 475 return this.version != null && !this.version.equals(referenceVersion); 476 } 477 478 /** 479 * Replies true if this this plugin should be updated/downloaded because either 480 * it is not available locally (its local version is null) or its local version is 481 * older than the available version on the server. 482 * 483 * @return true if the plugin should be updated 484 */ 485 public boolean isUpdateRequired() { 486 if (this.downloadlink == null) return false; 487 if (this.localversion == null) return true; 488 return isUpdateRequired(this.localversion); 489 } 490 491 protected boolean matches(String filter, String value) { 492 if (filter == null) return true; 493 if (value == null) return false; 494 return value.toLowerCase(Locale.ENGLISH).contains(filter.toLowerCase(Locale.ENGLISH)); 495 } 496 497 /** 498 * Replies true if either the name, the description, or the version match (case insensitive) 499 * one of the words in filter. Replies true if filter is null. 500 * 501 * @param filter the filter expression 502 * @return true if this plugin info matches with the filter 503 */ 504 public boolean matches(String filter) { 505 if (filter == null) return true; 506 String[] words = filter.split("\\s+"); 507 for (String word: words) { 508 if (matches(word, name) 509 || matches(word, description) 510 || matches(word, version) 511 || matches(word, localversion)) 512 return true; 513 } 514 return false; 515 } 516 517 /** 518 * Replies the name of the plugin. 519 * @return The plugin name 520 */ 521 public String getName() { 522 return name; 523 } 524 525 /** 526 * Sets the name 527 * @param name Plugin name 528 */ 529 public void setName(String name) { 530 this.name = name; 531 } 532 533 /** 534 * Replies the plugin icon, scaled to LARGE_ICON size. 535 * @return the plugin icon, scaled to LARGE_ICON size. 536 */ 537 public ImageIcon getScaledIcon() { 538 ImageIcon img = (icon != null) ? icon.get() : null; 539 if (img == null) 540 return emptyIcon; 541 return img; 542 } 543 544 @Override 545 public final String toString() { 546 return getName(); 547 } 548 549 private static List<String> getRequiredPlugins(String pluginList) { 550 List<String> requiredPlugins = new ArrayList<>(); 551 if (pluginList != null) { 552 for (String s : pluginList.split(";")) { 553 String plugin = s.trim(); 554 if (!plugin.isEmpty()) { 555 requiredPlugins.add(plugin); 556 } 557 } 558 } 559 return requiredPlugins; 560 } 561 562 /** 563 * Replies the list of plugins required by the up-to-date version of this plugin. 564 * @return List of plugins required. Empty if no plugin is required. 565 * @since 5601 566 */ 567 public List<String> getRequiredPlugins() { 568 return getRequiredPlugins(requires); 569 } 570 571 /** 572 * Replies the list of plugins required by the local instance of this plugin. 573 * @return List of plugins required. Empty if no plugin is required. 574 * @since 5601 575 */ 576 public List<String> getLocalRequiredPlugins() { 577 return getRequiredPlugins(localrequires); 578 } 579 580 /** 581 * Updates the local fields 582 * ({@link #localversion}, {@link #localmainversion}, {@link #localminjavaversion}, {@link #localrequires}) 583 * to values contained in the up-to-date fields 584 * ({@link #version}, {@link #mainversion}, {@link #minjavaversion}, {@link #requires}) 585 * of the given PluginInformation. 586 * @param info The plugin information to get the data from. 587 * @since 5601 588 */ 589 public void updateLocalInfo(PluginInformation info) { 590 if (info != null) { 591 this.localversion = info.version; 592 this.localmainversion = info.mainversion; 593 this.localminjavaversion = info.minjavaversion; 594 this.localrequires = info.requires; 595 } 596 } 597 598 /** 599 * Determines if this plugin can be run on the current platform. 600 * @return {@code true} if this plugin can be run on the current platform 601 * @since 14384 602 */ 603 public boolean isForCurrentPlatform() { 604 try { 605 return platform == null || PlatformManager.getPlatform().getPlatform() == Platform.valueOf(platform.toUpperCase(Locale.ENGLISH)); 606 } catch (IllegalArgumentException e) { 607 Logging.warn(e); 608 return true; 609 } 610 } 611}