1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Eclipse Public License, Version 1.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.eclipse.org/org/documents/epl-v10.php 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.ide.eclipse.adt.internal.sdk; 18 19 import com.android.annotations.NonNull; 20 import com.android.annotations.Nullable; 21 import com.android.ide.eclipse.adt.AdtPlugin; 22 import com.android.sdklib.BuildToolInfo; 23 import com.android.sdklib.IAndroidTarget; 24 import com.android.sdklib.internal.project.ProjectProperties; 25 import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy; 26 27 import org.eclipse.core.resources.IProject; 28 import org.eclipse.core.runtime.IStatus; 29 import org.eclipse.core.runtime.Status; 30 31 import java.io.File; 32 import java.io.IOException; 33 import java.util.ArrayList; 34 import java.util.Collection; 35 import java.util.Collections; 36 import java.util.HashSet; 37 import java.util.List; 38 import java.util.Set; 39 import java.util.regex.Matcher; 40 41 /** 42 * Centralized state for Android Eclipse project. 43 * <p>This gives raw access to the properties (from <code>project.properties</code>), as well 44 * as direct access to target and library information. 45 * 46 * This also gives access to library information. 47 * 48 * {@link #isLibrary()} indicates if the project is a library. 49 * {@link #hasLibraries()} and {@link #getLibraries()} give access to the libraries through 50 * instances of {@link LibraryState}. A {@link LibraryState} instance is a link between a main 51 * project and its library. Theses instances are owned by the {@link ProjectState}. 52 * 53 * {@link #isMissingLibraries()} will indicate if the project has libraries that are not resolved. 54 * Unresolved libraries are libraries that do not have any matching opened Eclipse project. 55 * When there are missing libraries, the {@link LibraryState} instance for them will return null 56 * for {@link LibraryState#getProjectState()}. 57 * 58 */ 59 public final class ProjectState { 60 61 /** 62 * A class that represents a library linked to a project. 63 * <p/>It does not represent the library uniquely. Instead the {@link LibraryState} is linked 64 * to the main project which is accessible through {@link #getMainProjectState()}. 65 * <p/>If a library is used by two different projects, then there will be two different 66 * instances of {@link LibraryState} for the library. 67 * 68 * @see ProjectState#getLibrary(IProject) 69 */ 70 public final class LibraryState { 71 private String mRelativePath; 72 private ProjectState mProjectState; 73 private String mPath; 74 75 private LibraryState(String relativePath) { 76 mRelativePath = relativePath; 77 } 78 79 /** 80 * Returns the {@link ProjectState} of the main project using this library. 81 */ 82 public ProjectState getMainProjectState() { 83 return ProjectState.this; 84 } 85 86 /** 87 * Closes the library. This resets the IProject from this object ({@link #getProjectState()} will 88 * return <code>null</code>), and updates the main project data so that the library 89 * {@link IProject} object does not show up in the return value of 90 * {@link ProjectState#getFullLibraryProjects()}. 91 */ 92 public void close() { 93 mProjectState.removeParentProject(getMainProjectState()); 94 mProjectState = null; 95 mPath = null; 96 97 getMainProjectState().updateFullLibraryList(); 98 } 99 100 private void setRelativePath(String relativePath) { 101 mRelativePath = relativePath; 102 } 103 104 private void setProject(ProjectState project) { 105 mProjectState = project; 106 mPath = project.getProject().getLocation().toOSString(); 107 mProjectState.addParentProject(getMainProjectState()); 108 109 getMainProjectState().updateFullLibraryList(); 110 } 111 112 /** 113 * Returns the relative path of the library from the main project. 114 * <p/>This is identical to the value defined in the main project's project.properties. 115 */ 116 public String getRelativePath() { 117 return mRelativePath; 118 } 119 120 /** 121 * Returns the {@link ProjectState} item for the library. This can be null if the project 122 * is not actually opened in Eclipse. 123 */ 124 public ProjectState getProjectState() { 125 return mProjectState; 126 } 127 128 /** 129 * Returns the OS-String location of the library project. 130 * <p/>This is based on location of the Eclipse project that matched 131 * {@link #getRelativePath()}. 132 * 133 * @return The project location, or null if the project is not opened in Eclipse. 134 */ 135 public String getProjectLocation() { 136 return mPath; 137 } 138 139 @Override 140 public boolean equals(Object obj) { 141 if (obj instanceof LibraryState) { 142 // the only thing that's always non-null is the relative path. 143 LibraryState objState = (LibraryState)obj; 144 return mRelativePath.equals(objState.mRelativePath) && 145 getMainProjectState().equals(objState.getMainProjectState()); 146 } else if (obj instanceof ProjectState || obj instanceof IProject) { 147 return mProjectState != null && mProjectState.equals(obj); 148 } else if (obj instanceof String) { 149 return normalizePath(mRelativePath).equals(normalizePath((String) obj)); 150 } 151 152 return false; 153 } 154 155 @Override 156 public int hashCode() { 157 return normalizePath(mRelativePath).hashCode(); 158 } 159 } 160 161 private final IProject mProject; 162 private final ProjectProperties mProperties; 163 private IAndroidTarget mTarget; 164 private BuildToolInfo mBuildToolInfo; 165 166 /** 167 * list of libraries. Access to this list must be protected by 168 * <code>synchronized(mLibraries)</code>, but it is important that such code do not call 169 * out to other classes (especially those protected by {@link Sdk#getLock()}.) 170 */ 171 private final ArrayList<LibraryState> mLibraries = new ArrayList<LibraryState>(); 172 /** Cached list of all IProject instances representing the resolved libraries, including 173 * indirect dependencies. This must never be null. */ 174 private List<IProject> mLibraryProjects = Collections.emptyList(); 175 /** 176 * List of parent projects. When this instance is a library ({@link #isLibrary()} returns 177 * <code>true</code>) then this is filled with projects that depends on this project. 178 */ 179 private final ArrayList<ProjectState> mParentProjects = new ArrayList<ProjectState>(); 180 181 ProjectState(IProject project, ProjectProperties properties) { 182 if (project == null || properties == null) { 183 throw new NullPointerException(); 184 } 185 186 mProject = project; 187 mProperties = properties; 188 189 // load the libraries 190 synchronized (mLibraries) { 191 int index = 1; 192 while (true) { 193 String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index++); 194 String rootPath = mProperties.getProperty(propName); 195 196 if (rootPath == null) { 197 break; 198 } 199 200 mLibraries.add(new LibraryState(convertPath(rootPath))); 201 } 202 } 203 } 204 205 public IProject getProject() { 206 return mProject; 207 } 208 209 public ProjectProperties getProperties() { 210 return mProperties; 211 } 212 213 public @Nullable String getProperty(@NonNull String name) { 214 if (mProperties != null) { 215 return mProperties.getProperty(name); 216 } 217 218 return null; 219 } 220 221 public void setTarget(IAndroidTarget target) { 222 mTarget = target; 223 } 224 225 /** 226 * Returns the project's target's hash string. 227 * <p/>If {@link #getTarget()} returns a valid object, then this returns the value of 228 * {@link IAndroidTarget#hashString()}. 229 * <p/>Otherwise this will return the value of the property 230 * {@link ProjectProperties#PROPERTY_TARGET} from {@link #getProperties()} (if valid). 231 * @return the target hash string or null if not found. 232 */ 233 public String getTargetHashString() { 234 if (mTarget != null) { 235 return mTarget.hashString(); 236 } 237 238 return mProperties.getProperty(ProjectProperties.PROPERTY_TARGET); 239 } 240 241 public IAndroidTarget getTarget() { 242 return mTarget; 243 } 244 245 public void setBuildToolInfo(BuildToolInfo buildToolInfo) { 246 mBuildToolInfo = buildToolInfo; 247 } 248 249 public BuildToolInfo getBuildToolInfo() { 250 return mBuildToolInfo; 251 } 252 253 /** 254 * Returns the build tools version from the project's properties. 255 * @return the value or null 256 */ 257 @Nullable 258 public String getBuildToolInfoVersion() { 259 return mProperties.getProperty(ProjectProperties.PROPERTY_BUILD_TOOLS); 260 } 261 262 public static class LibraryDifference { 263 public boolean removed = false; 264 public boolean added = false; 265 266 public boolean hasDiff() { 267 return removed || added; 268 } 269 } 270 271 /** 272 * Reloads the content of the properties. 273 * <p/>This also reset the reference to the target as it may have changed, therefore this 274 * should be followed by a call to {@link Sdk#loadTarget(ProjectState)}. 275 * 276 * <p/>If the project libraries changes, they are updated to a certain extent.<br> 277 * Removed libraries are removed from the state list, and added to the {@link LibraryDifference} 278 * object that is returned so that they can be processed.<br> 279 * Added libraries are added to the state (as new {@link LibraryState} objects), but their 280 * IProject is not resolved. {@link ProjectState#needs(ProjectState)} should be called 281 * afterwards to properly initialize the libraries. 282 * 283 * @return an instance of {@link LibraryDifference} describing the change in libraries. 284 */ 285 public LibraryDifference reloadProperties() { 286 mTarget = null; 287 mProperties.reload(); 288 289 // compare/reload the libraries. 290 291 // if the order change it won't impact the java part, so instead try to detect removed/added 292 // libraries. 293 294 LibraryDifference diff = new LibraryDifference(); 295 296 synchronized (mLibraries) { 297 List<LibraryState> oldLibraries = new ArrayList<LibraryState>(mLibraries); 298 mLibraries.clear(); 299 300 // load the libraries 301 int index = 1; 302 while (true) { 303 String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index++); 304 String rootPath = mProperties.getProperty(propName); 305 306 if (rootPath == null) { 307 break; 308 } 309 310 // search for a library with the same path (not exact same string, but going 311 // to the same folder). 312 String convertedPath = convertPath(rootPath); 313 boolean found = false; 314 for (int i = 0 ; i < oldLibraries.size(); i++) { 315 LibraryState libState = oldLibraries.get(i); 316 if (libState.equals(convertedPath)) { 317 // it's a match. move it back to mLibraries and remove it from the 318 // old library list. 319 found = true; 320 mLibraries.add(libState); 321 oldLibraries.remove(i); 322 break; 323 } 324 } 325 326 if (found == false) { 327 diff.added = true; 328 mLibraries.add(new LibraryState(convertedPath)); 329 } 330 } 331 332 // whatever's left in oldLibraries is removed. 333 diff.removed = oldLibraries.size() > 0; 334 335 // update the library with what IProjet are known at the time. 336 updateFullLibraryList(); 337 } 338 339 return diff; 340 } 341 342 /** 343 * Returns the list of {@link LibraryState}. 344 */ 345 public List<LibraryState> getLibraries() { 346 synchronized (mLibraries) { 347 return Collections.unmodifiableList(mLibraries); 348 } 349 } 350 351 /** 352 * Returns all the <strong>resolved</strong> library projects, including indirect dependencies. 353 * The list is ordered to match the library priority order for resource processing with 354 * <code>aapt</code>. 355 * <p/>If some dependencies are not resolved (or their projects is not opened in Eclipse), 356 * they will not show up in this list. 357 * @return the resolved projects as an unmodifiable list. May be an empty. 358 */ 359 public List<IProject> getFullLibraryProjects() { 360 return mLibraryProjects; 361 } 362 363 /** 364 * Returns whether this is a library project. 365 */ 366 public boolean isLibrary() { 367 String value = mProperties.getProperty(ProjectProperties.PROPERTY_LIBRARY); 368 return value != null && Boolean.valueOf(value); 369 } 370 371 /** 372 * Returns whether the project depends on one or more libraries. 373 */ 374 public boolean hasLibraries() { 375 synchronized (mLibraries) { 376 return mLibraries.size() > 0; 377 } 378 } 379 380 /** 381 * Returns whether the project is missing some required libraries. 382 */ 383 public boolean isMissingLibraries() { 384 synchronized (mLibraries) { 385 for (LibraryState state : mLibraries) { 386 if (state.getProjectState() == null) { 387 return true; 388 } 389 } 390 } 391 392 return false; 393 } 394 395 /** 396 * Returns the {@link LibraryState} object for a given {@link IProject}. 397 * </p>This can only return a non-null object if the link between the main project's 398 * {@link IProject} and the library's {@link IProject} was done. 399 * 400 * @return the matching LibraryState or <code>null</code> 401 * 402 * @see #needs(ProjectState) 403 */ 404 public LibraryState getLibrary(IProject library) { 405 synchronized (mLibraries) { 406 for (LibraryState state : mLibraries) { 407 ProjectState ps = state.getProjectState(); 408 if (ps != null && ps.getProject().equals(library)) { 409 return state; 410 } 411 } 412 } 413 414 return null; 415 } 416 417 /** 418 * Returns the {@link LibraryState} object for a given <var>name</var>. 419 * </p>This can only return a non-null object if the link between the main project's 420 * {@link IProject} and the library's {@link IProject} was done. 421 * 422 * @return the matching LibraryState or <code>null</code> 423 * 424 * @see #needs(IProject) 425 */ 426 public LibraryState getLibrary(String name) { 427 synchronized (mLibraries) { 428 for (LibraryState state : mLibraries) { 429 ProjectState ps = state.getProjectState(); 430 if (ps != null && ps.getProject().getName().equals(name)) { 431 return state; 432 } 433 } 434 } 435 436 return null; 437 } 438 439 440 /** 441 * Returns whether a given library project is needed by the receiver. 442 * <p/>If the library is needed, this finds the matching {@link LibraryState}, initializes it 443 * so that it contains the library's {@link IProject} object (so that 444 * {@link LibraryState#getProjectState()} does not return null) and then returns it. 445 * 446 * @param libraryProject the library project to check. 447 * @return a non null object if the project is a library dependency, 448 * <code>null</code> otherwise. 449 * 450 * @see LibraryState#getProjectState() 451 */ 452 public LibraryState needs(ProjectState libraryProject) { 453 // compute current location 454 File projectFile = mProject.getLocation().toFile(); 455 456 // get the location of the library. 457 File libraryFile = libraryProject.getProject().getLocation().toFile(); 458 459 // loop on all libraries and check if the path match 460 synchronized (mLibraries) { 461 for (LibraryState state : mLibraries) { 462 if (state.getProjectState() == null) { 463 File library = new File(projectFile, state.getRelativePath()); 464 try { 465 File absPath = library.getCanonicalFile(); 466 if (absPath.equals(libraryFile)) { 467 state.setProject(libraryProject); 468 return state; 469 } 470 } catch (IOException e) { 471 // ignore this library 472 } 473 } 474 } 475 } 476 477 return null; 478 } 479 480 /** 481 * Returns whether the project depends on a given <var>library</var> 482 * @param library the library to check. 483 * @return true if the project depends on the library. This is not affected by whether the link 484 * was done through {@link #needs(ProjectState)}. 485 */ 486 public boolean dependsOn(ProjectState library) { 487 synchronized (mLibraries) { 488 for (LibraryState state : mLibraries) { 489 if (state != null && state.getProjectState() != null && 490 library.getProject().equals(state.getProjectState().getProject())) { 491 return true; 492 } 493 } 494 } 495 496 return false; 497 } 498 499 500 /** 501 * Updates a library with a new path. 502 * <p/>This method acts both as a check and an action. If the project does not depend on the 503 * given <var>oldRelativePath</var> then no action is done and <code>null</code> is returned. 504 * <p/>If the project depends on the library, then the project is updated with the new path, 505 * and the {@link LibraryState} for the library is returned. 506 * <p/>Updating the project does two things:<ul> 507 * <li>Update LibraryState with new relative path and new {@link IProject} object.</li> 508 * <li>Update the main project's <code>project.properties</code> with the new relative path 509 * for the changed library.</li> 510 * </ul> 511 * 512 * @param oldRelativePath the old library path relative to this project 513 * @param newRelativePath the new library path relative to this project 514 * @param newLibraryState the new {@link ProjectState} object. 515 * @return a non null object if the project depends on the library. 516 * 517 * @see LibraryState#getProjectState() 518 */ 519 public LibraryState updateLibrary(String oldRelativePath, String newRelativePath, 520 ProjectState newLibraryState) { 521 // compute current location 522 File projectFile = mProject.getLocation().toFile(); 523 524 // loop on all libraries and check if the path matches 525 synchronized (mLibraries) { 526 for (LibraryState state : mLibraries) { 527 if (state.getProjectState() == null) { 528 try { 529 // oldRelativePath may not be the same exact string as the 530 // one in the project properties (trailing separator could be different 531 // for instance). 532 // Use java.io.File to deal with this and also do a platform-dependent 533 // path comparison 534 File library1 = new File(projectFile, oldRelativePath); 535 File library2 = new File(projectFile, state.getRelativePath()); 536 if (library1.getCanonicalPath().equals(library2.getCanonicalPath())) { 537 // save the exact property string to replace. 538 String oldProperty = state.getRelativePath(); 539 540 // then update the LibraryPath. 541 state.setRelativePath(newRelativePath); 542 state.setProject(newLibraryState); 543 544 // update the project.properties file 545 IStatus status = replaceLibraryProperty(oldProperty, newRelativePath); 546 if (status != null) { 547 if (status.getSeverity() != IStatus.OK) { 548 // log the error somehow. 549 } 550 } else { 551 // This should not happen since the library wouldn't be here in the 552 // first place 553 } 554 555 // return the LibraryState object. 556 return state; 557 } 558 } catch (IOException e) { 559 // ignore this library 560 } 561 } 562 } 563 } 564 565 return null; 566 } 567 568 569 private void addParentProject(ProjectState parentState) { 570 mParentProjects.add(parentState); 571 } 572 573 private void removeParentProject(ProjectState parentState) { 574 mParentProjects.remove(parentState); 575 } 576 577 public List<ProjectState> getParentProjects() { 578 return Collections.unmodifiableList(mParentProjects); 579 } 580 581 /** 582 * Computes the transitive closure of projects referencing this project as a 583 * library project 584 * 585 * @return a collection (in any order) of project states for projects that 586 * directly or indirectly include this project state's project as a 587 * library project 588 */ 589 public Collection<ProjectState> getFullParentProjects() { 590 Set<ProjectState> result = new HashSet<ProjectState>(); 591 addParentProjects(result, this); 592 return result; 593 } 594 595 /** Adds all parent projects of the given project, transitively, into the given parent set */ 596 private static void addParentProjects(Set<ProjectState> parents, ProjectState state) { 597 for (ProjectState s : state.mParentProjects) { 598 if (!parents.contains(s)) { 599 parents.add(s); 600 addParentProjects(parents, s); 601 } 602 } 603 } 604 605 /** 606 * Update the value of a library dependency. 607 * <p/>This loops on all current dependency looking for the value to replace and then replaces 608 * it. 609 * <p/>This both updates the in-memory {@link #mProperties} values and on-disk 610 * project.properties file. 611 * @param oldValue the old value to replace 612 * @param newValue the new value to set. 613 * @return the status of the replacement. If null, no replacement was done (value not found). 614 */ 615 private IStatus replaceLibraryProperty(String oldValue, String newValue) { 616 int index = 1; 617 while (true) { 618 String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index++); 619 String rootPath = mProperties.getProperty(propName); 620 621 if (rootPath == null) { 622 break; 623 } 624 625 if (rootPath.equals(oldValue)) { 626 // need to update the properties. Get a working copy to change it and save it on 627 // disk since ProjectProperties is read-only. 628 ProjectPropertiesWorkingCopy workingCopy = mProperties.makeWorkingCopy(); 629 workingCopy.setProperty(propName, newValue); 630 try { 631 workingCopy.save(); 632 633 // reload the properties with the new values from the disk. 634 mProperties.reload(); 635 } catch (Exception e) { 636 return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format( 637 "Failed to save %1$s for project %2$s", 638 mProperties.getType() .getFilename(), mProject.getName()), 639 e); 640 641 } 642 return Status.OK_STATUS; 643 } 644 } 645 646 return null; 647 } 648 649 /** 650 * Update the full library list, including indirect dependencies. The result is returned by 651 * {@link #getFullLibraryProjects()}. 652 */ 653 void updateFullLibraryList() { 654 ArrayList<IProject> list = new ArrayList<IProject>(); 655 synchronized (mLibraries) { 656 buildFullLibraryDependencies(mLibraries, list); 657 } 658 659 mLibraryProjects = Collections.unmodifiableList(list); 660 } 661 662 /** 663 * Resolves a given list of libraries, finds out if they depend on other libraries, and 664 * returns a full list of all the direct and indirect dependencies in the proper order (first 665 * is higher priority when calling aapt). 666 * @param inLibraries the libraries to resolve 667 * @param outLibraries where to store all the libraries. 668 */ 669 private void buildFullLibraryDependencies(List<LibraryState> inLibraries, 670 ArrayList<IProject> outLibraries) { 671 // loop in the inverse order to resolve dependencies on the libraries, so that if a library 672 // is required by two higher level libraries it can be inserted in the correct place 673 for (int i = inLibraries.size() - 1 ; i >= 0 ; i--) { 674 LibraryState library = inLibraries.get(i); 675 676 // get its libraries if possible 677 ProjectState libProjectState = library.getProjectState(); 678 if (libProjectState != null) { 679 List<LibraryState> dependencies = libProjectState.getLibraries(); 680 681 // build the dependencies for those libraries 682 buildFullLibraryDependencies(dependencies, outLibraries); 683 684 // and add the current library (if needed) in front (higher priority) 685 if (outLibraries.contains(libProjectState.getProject()) == false) { 686 outLibraries.add(0, libProjectState.getProject()); 687 } 688 } 689 } 690 } 691 692 693 /** 694 * Converts a path containing only / by the proper platform separator. 695 */ 696 private String convertPath(String path) { 697 return path.replaceAll("/", Matcher.quoteReplacement(File.separator)); //$NON-NLS-1$ 698 } 699 700 /** 701 * Normalizes a relative path. 702 */ 703 private String normalizePath(String path) { 704 path = convertPath(path); 705 if (path.endsWith("/")) { //$NON-NLS-1$ 706 path = path.substring(0, path.length() - 1); 707 } 708 return path; 709 } 710 711 @Override 712 public boolean equals(Object obj) { 713 if (obj instanceof ProjectState) { 714 return mProject.equals(((ProjectState) obj).mProject); 715 } else if (obj instanceof IProject) { 716 return mProject.equals(obj); 717 } 718 719 return false; 720 } 721 722 @Override 723 public int hashCode() { 724 return mProject.hashCode(); 725 } 726 727 @Override 728 public String toString() { 729 return mProject.getName(); 730 } 731 } 732