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