Search in sources :

Example 11 with VisibleForTesting

use of com.android.annotations.VisibleForTesting in project android by JetBrains.

the class ProjectStructureUsageTracker method trackProjectStructure.

@VisibleForTesting
void trackProjectStructure(@NotNull Module[] modules) {
    AndroidModuleModel appModel = null;
    AndroidModuleModel libModel = null;
    int appCount = 0;
    int libCount = 0;
    List<GradleLibrary> gradleLibraries = new ArrayList<>();
    for (Module module : modules) {
        AndroidModuleModel androidModel = AndroidModuleModel.get(module);
        if (androidModel != null) {
            if (androidModel.getProjectType() == PROJECT_TYPE_LIBRARY) {
                libModel = androidModel;
                libCount++;
                continue;
            }
            appModel = androidModel;
            appCount++;
            GradleLibrary gradleLibrary = trackExternalDependenciesInAndroidApp(androidModel);
            if (gradleLibrary != null) {
                gradleLibraries.add(gradleLibrary);
            }
        }
    }
    // Ideally we would like to get data from an "app" module, but if the project does not have one (which would be unusual, we can use
    // an Android library one.)
    AndroidModuleModel model = appModel != null ? appModel : libModel;
    if (model != null) {
        List<GradleAndroidModule> gradleAndroidModules = new ArrayList<>();
        List<GradleNativeAndroidModule> gradleNativeAndroidModules = new ArrayList<>();
        String appId = AndroidStudioUsageTracker.anonymizeUtf8(model.getApplicationId());
        AndroidProject androidProject = model.getAndroidProject();
        GradleVersion gradleVersion = GradleVersions.getInstance().getGradleVersion(myProject);
        if (gradleVersion == null) {
            gradleVersion = new GradleVersion(0, 0, 0);
        }
        GradleModule gradleModule = GradleModule.newBuilder().setTotalModuleCount(modules.length).setAppModuleCount(appCount).setLibModuleCount(libCount).build();
        for (Module module : modules) {
            AndroidModuleModel androidModel = AndroidModuleModel.get(module);
            if (androidModel != null) {
                gradleAndroidModules.add(GradleAndroidModule.newBuilder().setModuleName(AndroidStudioUsageTracker.anonymizeUtf8(module.getName())).setSigningConfigCount(androidModel.getAndroidProject().getSigningConfigs().size()).setIsLibrary(androidModel.getProjectType() == PROJECT_TYPE_LIBRARY).setBuildTypeCount(androidModel.getBuildTypeNames().size()).setFlavorCount(androidModel.getProductFlavorNames().size()).setFlavorDimension(getFlavorDimensions(androidModel).size()).build());
            }
            boolean shouldReportNative = false;
            NdkModuleModel ndkModuleModel = NdkModuleModel.get(module);
            NativeBuildSystemType buildSystemType = NativeBuildSystemType.UNKNOWN_NATIVE_BUILD_SYSTEM_TYPE;
            String moduleName = "";
            if (ndkModuleModel != null) {
                shouldReportNative = true;
                if (ndkModuleModel.modelVersionIsAtLeast("2.2.0")) {
                    for (String buildSystem : ndkModuleModel.getAndroidProject().getBuildSystems()) {
                        buildSystemType = stringToBuildSystemType(buildSystem);
                    }
                } else {
                    buildSystemType = NativeBuildSystemType.GRADLE_EXPERIMENTAL;
                }
                moduleName = AndroidStudioUsageTracker.anonymizeUtf8(ndkModuleModel.getModuleName());
            } else if (androidModel != null && areNativeLibrariesPresent(androidModel.getAndroidProject())) {
                shouldReportNative = true;
                if (AndroidPluginGeneration.find(module) == COMPONENT) {
                    buildSystemType = NativeBuildSystemType.GRADLE_EXPERIMENTAL;
                } else {
                    buildSystemType = NativeBuildSystemType.NDK_COMPILE;
                }
            }
            if (shouldReportNative) {
                gradleNativeAndroidModules.add(GradleNativeAndroidModule.newBuilder().setModuleName(moduleName).setBuildSystemType(buildSystemType).build());
            }
        }
        UsageTracker.getInstance().log(AndroidStudioEvent.newBuilder().setCategory(EventCategory.GRADLE).setKind(AndroidStudioEvent.EventKind.GRADLE_BUILD_DETAILS).setGradleBuildDetails(GradleBuildDetails.newBuilder().setAppId(appId).setAndroidPluginVersion(androidProject.getModelVersion()).setGradleVersion(gradleVersion.toString()).setUserEnabledIr(InstantRunSettings.isInstantRunEnabled()).setModelSupportsIr(InstantRunGradleUtils.modelSupportsInstantRun(model)).setVariantSupportsIr(InstantRunGradleUtils.variantSupportsInstantRun(model)).addAllLibraries(gradleLibraries).addModules(gradleModule).addAllAndroidModules(gradleAndroidModules).addAllNativeAndroidModules(gradleNativeAndroidModules)));
    }
}
Also used : NativeBuildSystemType(com.google.wireless.android.sdk.stats.GradleNativeAndroidModule.NativeBuildSystemType) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) Module(com.intellij.openapi.module.Module) GradleVersion(com.android.ide.common.repository.GradleVersion) NdkModuleModel(com.android.tools.idea.gradle.project.model.NdkModuleModel) VisibleForTesting(com.android.annotations.VisibleForTesting)

Example 12 with VisibleForTesting

use of com.android.annotations.VisibleForTesting in project android by JetBrains.

the class ImportSourceLocationStep method checkPath.

@NotNull
@VisibleForTesting
protected PathValidationResult checkPath(@NotNull String path) {
    path = path.trim();
    if (Strings.isNullOrEmpty(path)) {
        return PageStatus.EMPTY_PATH.result();
    }
    VirtualFile vfile = VfsUtil.findFileByIoFile(new File(path), false);
    if (vfile == null || !vfile.exists()) {
        return PageStatus.DOES_NOT_EXIST.result();
    } else if (isProjectOrModule(vfile)) {
        return PageStatus.IS_PROJECT_OR_MODULE.result();
    }
    ModuleImporter kind = ModuleImporter.importerForLocation(myContext, vfile);
    if (!kind.isValid()) {
        return PageStatus.NOT_ADT_OR_GRADLE.result();
    }
    return new PathValidationResult(PageStatus.OK, vfile, kind, null);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ModuleImporter(com.android.tools.idea.gradle.project.ModuleImporter) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) VisibleForTesting(com.android.annotations.VisibleForTesting) NotNull(org.jetbrains.annotations.NotNull)

Example 13 with VisibleForTesting

use of com.android.annotations.VisibleForTesting in project android by JetBrains.

the class CaptureService method finalizeCaptureFileSynchronous.

/**
   * ONLY VISIBLE FOR TESTS. Closes the file and synchronously returns the generate {@code Capture}.
   *
   * @param captureHandle is the handle returned by {@link #startCaptureFile(Class)}
   * @return the generated {@code Capture} for the given {@code CaptureHandle}
   * @throws InterruptedException if something interrupts this thread when waiting for the close to finish on the async thread
   * @throws IOException          if there is a problem generating the Capture
   */
@VisibleForTesting
@NotNull
Capture finalizeCaptureFileSynchronous(@NotNull CaptureHandle captureHandle) throws InterruptedException, IOException {
    final CountDownLatch latch = new CountDownLatch(1);
    closeCaptureFileInternal(captureHandle, new Runnable() {

        @Override
        public void run() {
            latch.countDown();
        }
    });
    latch.await();
    return createCapture(captureHandle);
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) VisibleForTesting(com.android.annotations.VisibleForTesting) NotNull(org.jetbrains.annotations.NotNull)

Example 14 with VisibleForTesting

use of com.android.annotations.VisibleForTesting in project android by JetBrains.

the class SdkQuickfixUtils method createDialog.

@VisibleForTesting
@Nullable
static ModelWizardDialog createDialog(@Nullable Project project, @Nullable Component parent, @Nullable Collection<String> requestedPaths, @Nullable Collection<UpdatablePackage> requestedPackages, @Nullable Collection<LocalPackage> requestedUninstalls, @Nullable AndroidSdkHandler sdkHandler, boolean backgroundable) {
    if (sdkHandler == null) {
        return null;
    }
    RepoManager mgr = sdkHandler.getSdkManager(REPO_LOGGER);
    if (mgr.getLocalPath() == null) {
        String title = "SDK Problem";
        String msg = "<html>" + "Your Android SDK is missing or out of date." + "<br>" + "You can configure your SDK via <b>Configure | Project Defaults | Project Structure | SDKs</b></html>";
        Messages.showErrorDialog(msg, title);
        return null;
    }
    List<String> unknownPaths = new ArrayList<>();
    List<UpdatablePackage> resolvedPackages;
    mgr.loadSynchronously(0, new StudioLoggerProgressIndicator(SdkQuickfixUtils.class), new StudioDownloader(), StudioSettingsController.getInstance());
    RepositoryPackages packages = mgr.getPackages();
    if (requestedPackages == null) {
        requestedPackages = new ArrayList<>();
    }
    requestedPackages.addAll(lookupPaths(requestedPaths, packages, unknownPaths));
    try {
        resolvedPackages = resolve(requestedPackages, packages);
    } catch (PackageResolutionException e) {
        Messages.showErrorDialog(e.getMessage(), "Error Resolving Packages");
        return null;
    }
    Set<LocalPackage> resolvedUninstalls = new HashSet<>();
    if (requestedUninstalls != null) {
        resolvedUninstalls.addAll(requestedUninstalls);
        // We don't want to uninstall something required by a package we're installing
        resolvedPackages.forEach(updatable -> resolvedUninstalls.remove(updatable.getLocal()));
    }
    List<UpdatablePackage> unavailableDownloads = Lists.newArrayList();
    verifyAvailability(resolvedPackages, unavailableDownloads);
    // If there were requests we didn't understand or can't download, show an error.
    if (!unknownPaths.isEmpty() || !unavailableDownloads.isEmpty()) {
        String title = "Packages Unavailable";
        HtmlBuilder builder = new HtmlBuilder();
        builder.openHtmlBody().add(String.format("%1$s packages are not available for download!", resolvedPackages.isEmpty() ? "All" : "Some")).newline().newline().add("The following packages are not available:").beginList();
        for (UpdatablePackage p : unavailableDownloads) {
            builder.listItem().add(p.getRepresentative().getDisplayName());
        }
        for (String p : unknownPaths) {
            builder.listItem().add("Package id " + p);
        }
        builder.endList().closeHtmlBody();
        Messages.showErrorDialog(builder.getHtml(), title);
    }
    // If everything was removed, don't continue.
    if (resolvedPackages.isEmpty() && resolvedUninstalls.isEmpty()) {
        return null;
    }
    List<RemotePackage> installRequests = resolvedPackages.stream().map(UpdatablePackage::getRemote).collect(Collectors.toList());
    ModelWizard.Builder wizardBuilder = new ModelWizard.Builder();
    wizardBuilder.addStep(new LicenseAgreementStep(new LicenseAgreementModel(mgr.getLocalPath()), installRequests));
    InstallSelectedPackagesStep installStep = new InstallSelectedPackagesStep(resolvedPackages, resolvedUninstalls, sdkHandler, backgroundable);
    wizardBuilder.addStep(installStep);
    ModelWizard wizard = wizardBuilder.build();
    String title = "SDK Quickfix Installation";
    return new StudioWizardDialogBuilder(wizard, title, parent).setProject(project).setModalityType(DialogWrapper.IdeModalityType.IDE).setCancellationPolicy(ModelWizardDialog.CancellationPolicy.CAN_CANCEL_UNTIL_CAN_FINISH).build();
}
Also used : HtmlBuilder(com.android.utils.HtmlBuilder) StudioWizardDialogBuilder(com.android.tools.idea.ui.wizard.StudioWizardDialogBuilder) RepositoryPackages(com.android.repository.impl.meta.RepositoryPackages) ModelWizard(com.android.tools.idea.wizard.model.ModelWizard) HtmlBuilder(com.android.utils.HtmlBuilder) StudioDownloader(com.android.tools.idea.sdk.StudioDownloader) StudioLoggerProgressIndicator(com.android.tools.idea.sdk.progress.StudioLoggerProgressIndicator) StudioWizardDialogBuilder(com.android.tools.idea.ui.wizard.StudioWizardDialogBuilder) VisibleForTesting(com.android.annotations.VisibleForTesting) Nullable(org.jetbrains.annotations.Nullable)

Example 15 with VisibleForTesting

use of com.android.annotations.VisibleForTesting in project android by JetBrains.

the class IconPreviewFactory method load.

/**
   * Load preview images for each component into a file cache.
   * Each combination of theme, device density, and API level will have its own cache.
   *
   * @param configuration a hardware configuration to generate previews for
   * @param palette a palette with the components to generate previews of
   * @param reload if true replace the existing preview images
   * @param requestedIds for testing only: gather the IDs of the components whose previews were requested
   * @param generatedIds for testing only: gather the IDs of the components whose preview images where generated
   * @return true if the images were loaded, false if they already existed
   */
@VisibleForTesting
boolean load(@NotNull final Configuration configuration, @NotNull final Palette palette, boolean reload, @Nullable final List<String> requestedIds, @Nullable final List<String> generatedIds) {
    File cacheDir = getPreviewCacheDirForConfiguration(configuration);
    String[] files = cacheDir.list();
    if (files != null && files.length > 0) {
        // The previews have already been generated.
        if (!reload) {
            return false;
        }
        FileUtil.delete(cacheDir);
    }
    ApplicationManager.getApplication().runReadAction(new Computable<Void>() {

        @Override
        public Void compute() {
            List<StringBuilder> sources = Lists.newArrayList();
            loadSources(sources, requestedIds, palette.getItems());
            for (StringBuilder source : sources) {
                String preview = String.format(LINEAR_LAYOUT, CONTAINER_ID, source);
                addResultToCache(renderImage(myExecutorService, myRenderTimeoutSeconds, getRenderTask(configuration), preview), generatedIds, configuration);
            }
            return null;
        }
    });
    return true;
}
Also used : List(java.util.List) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) VisibleForTesting(com.android.annotations.VisibleForTesting)

Aggregations

VisibleForTesting (com.android.annotations.VisibleForTesting)32 VirtualFile (com.intellij.openapi.vfs.VirtualFile)10 File (java.io.File)7 NotNull (org.jetbrains.annotations.NotNull)7 Module (com.intellij.openapi.module.Module)5 ResourceType (com.android.resources.ResourceType)3 StudioLoggerProgressIndicator (com.android.tools.idea.sdk.progress.StudioLoggerProgressIndicator)3 Nullable (com.android.annotations.Nullable)2 GradleVersion (com.android.ide.common.repository.GradleVersion)2 Revision (com.android.repository.Revision)2 Device (com.android.sdklib.devices.Device)2 ModuleImporter (com.android.tools.idea.gradle.project.ModuleImporter)2 GradleFacet (com.android.tools.idea.gradle.project.facet.gradle.GradleFacet)2 NdkModuleModel (com.android.tools.idea.gradle.project.model.NdkModuleModel)2 VfsUtil.findFileByIoFile (com.intellij.openapi.vfs.VfsUtil.findFileByIoFile)2 PsiFile (com.intellij.psi.PsiFile)2 BufferedImage (java.awt.image.BufferedImage)2 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)2 Nullable (org.jetbrains.annotations.Nullable)2 ApiObjectFactory (com.android.build.gradle.internal.ApiObjectFactory)1