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