Search in sources :

Example 1 with GradleSyncState

use of com.android.tools.idea.gradle.project.sync.GradleSyncState in project android by JetBrains.

the class BuildVariantView method updateContents.

public void updateContents() {
    GradleSyncState syncState = GradleSyncState.getInstance(myProject);
    if (syncState.isSyncInProgress() && !syncState.isSyncSkipped()) {
        projectImportStarted();
        return;
    }
    final List<Object[]> rows = Lists.newArrayList();
    final List<BuildVariantItem[]> variantNamesPerRow = Lists.newArrayList();
    for (Module module : getGradleModulesWithAndroidProjects()) {
        AndroidFacet androidFacet = AndroidFacet.getInstance(module);
        NdkFacet ndkFacet = NdkFacet.getInstance(module);
        // getGradleModules() returns only relevant modules.
        assert androidFacet != null || ndkFacet != null;
        String variantName = null;
        if (androidFacet != null) {
            JpsAndroidModuleProperties facetProperties = androidFacet.getProperties();
            variantName = facetProperties.SELECTED_BUILD_VARIANT;
        }
        BuildVariantItem[] variantNames = getVariantItems(module);
        if (variantNames != null) {
            if (androidFacet != null) {
                AndroidModuleModel androidModel = AndroidModuleModel.get(module);
                // AndroidModel may be null when applying a quick fix (e.g. "Fix Gradle version")
                if (androidModel != null) {
                    variantName = androidModel.getSelectedVariant().getName();
                }
            } else {
                // As only the modules backed by either AndroidGradleModel or NativeAndroidGradleModel are shown in the Build Variants View,
                // when a module is not backed by AndroidGradleModel, it surely contains a valid NativeAndroidGradleModel.
                NdkModuleModel ndkModuleModel = NdkModuleModel.get(module);
                if (ndkModuleModel != null) {
                    variantName = ndkModuleModel.getSelectedVariant().getName();
                }
            }
            variantNamesPerRow.add(variantNames);
        }
        if (variantName != null) {
            Object[] row = { module, variantName };
            rows.add(row);
        }
    }
    Runnable setModelTask = () -> getVariantsTable().setModel(rows, variantNamesPerRow);
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread()) {
        setModelTask.run();
    } else {
        application.invokeLater(setModelTask);
    }
}
Also used : NdkFacet(com.android.tools.idea.gradle.project.facet.ndk.NdkFacet) JpsAndroidModuleProperties(org.jetbrains.jps.android.model.impl.JpsAndroidModuleProperties) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) Module(com.intellij.openapi.module.Module) NdkModuleModel(com.android.tools.idea.gradle.project.model.NdkModuleModel) Application(com.intellij.openapi.application.Application)

Example 2 with GradleSyncState

use of com.android.tools.idea.gradle.project.sync.GradleSyncState in project android by JetBrains.

the class GradleVersionsTest method simulateGradleSyncStateReturnNullGradleVersion.

private void simulateGradleSyncStateReturnNullGradleVersion() {
    GradleSyncState syncState = mock(GradleSyncState.class);
    IdeComponents.replaceService(getProject(), GradleSyncState.class, syncState);
    GradleSyncSummary summary = mock(GradleSyncSummary.class);
    when(summary.getGradleVersion()).thenReturn(null);
    when(syncState.getSummary()).thenReturn(summary);
}
Also used : GradleSyncSummary(com.android.tools.idea.gradle.project.sync.GradleSyncSummary) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState)

Example 3 with GradleSyncState

use of com.android.tools.idea.gradle.project.sync.GradleSyncState in project android by JetBrains.

the class DataBindingScopeTest method testAccessFromInaccessibleScope.

public void testAccessFromInaccessibleScope() throws Exception {
    loadProject(PROJECT_WITH_DATA_BINDING_AND_SIMPLE_LIB);
    // temporary fix until test model can detect dependencies properly
    GradleInvocationResult assembleDebug = invokeGradleTasks(getProject(), "assembleDebug");
    GradleSyncState syncState = GradleSyncState.getInstance(getProject());
    assertFalse(syncState.isSyncNeeded().toBoolean());
    assertTrue(myAndroidFacet.isDataBindingEnabled());
    assertTrue(myModules.hasModule("lib"));
    assertTrue(myModules.hasModule("lib2"));
    // app depends on lib depends on lib2
    // trigger initialization
    myAndroidFacet.getModuleResources(true);
    JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(getProject());
    String appBindingClassName = "com.android.example.appwithdatabinding.databinding.ActivityMainBinding";
    assertNotNull(javaPsiFacade.findClass(appBindingClassName, myAndroidFacet.getModule().getModuleWithDependenciesScope()));
    assertNull(javaPsiFacade.findClass(appBindingClassName, myModules.getModule("lib").getModuleWithDependenciesScope()));
    assertNull(javaPsiFacade.findClass(appBindingClassName, myModules.getModule("lib2").getModuleWithDependenciesScope()));
    // only exists in lib
    String libLayoutBindingClassName = "com.foo.bar.databinding.LibLayoutBinding";
    assertNotNull(javaPsiFacade.findClass(libLayoutBindingClassName, myAndroidFacet.getModule().getModuleWithDependenciesScope()));
    assertNotNull(javaPsiFacade.findClass(libLayoutBindingClassName, myModules.getModule("lib").getModuleWithDependenciesScope()));
    assertNull(javaPsiFacade.findClass(libLayoutBindingClassName, myModules.getModule("lib2").getModuleWithDependenciesScope()));
    // only exists in lib2
    String lib2LayoutBindingClassName = "com.foo.bar2.databinding.Lib2LayoutBinding";
    assertNotNull(javaPsiFacade.findClass(lib2LayoutBindingClassName, myAndroidFacet.getModule().getModuleWithDependenciesScope()));
    assertNotNull(javaPsiFacade.findClass(lib2LayoutBindingClassName, myModules.getModule("lib").getModuleWithDependenciesScope()));
    assertNotNull(javaPsiFacade.findClass(lib2LayoutBindingClassName, myModules.getModule("lib2").getModuleWithDependenciesScope()));
}
Also used : JavaPsiFacade(com.intellij.psi.JavaPsiFacade) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState)

Example 4 with GradleSyncState

use of com.android.tools.idea.gradle.project.sync.GradleSyncState in project android by JetBrains.

the class GeneratedCodeMatchTest method testGeneratedCodeMatch.

public void testGeneratedCodeMatch() throws Exception {
    loadProject(PROJECT_WITH_DATA_BINDING);
    // temporary fix until test model can detect dependencies properly
    GradleInvocationResult assembleDebug = invokeGradleTasks(getProject(), "assembleDebug");
    assertTrue(StringUtil.join(assembleDebug.getCompilerMessages(Message.Kind.ERROR), "\n"), assembleDebug.isBuildSuccessful());
    GradleSyncState syncState = GradleSyncState.getInstance(getProject());
    assertFalse(syncState.isSyncNeeded().toBoolean());
    assertTrue(myAndroidFacet.isDataBindingEnabled());
    // trigger initialization
    myAndroidFacet.getModuleResources(true);
    File classesOut = new File(getProject().getBaseDir().getPath(), "/app/build/intermediates/classes/debug");
    //noinspection unchecked
    Collection<File> classes = FileUtils.listFiles(classesOut, new String[] { "class" }, true);
    assertTrue("if we cannot find any class, something is wrong with the test", classes.size() > 0);
    ClassReader viewDataBindingClass = findViewDataBindingClass();
    Set<String> baseClassInfo = collectDescriptionSet(viewDataBindingClass, new HashSet<>());
    JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(getProject());
    Set<String> missingClasses = new HashSet<>();
    Map<String, ClassReader> klassMap = classes.stream().map((file) -> {
        try {
            return new ClassReader(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
        return null;
    }).filter(kls -> kls != null).collect(Collectors.toMap(kls -> kls.getClassName(), kls -> kls));
    Map<ClassReader, ClassReader> superClassLookup = klassMap.values().stream().filter(kls -> klassMap.containsKey(kls.getSuperName())).collect(Collectors.toMap(kls -> kls, kls -> klassMap.get(kls.getSuperName())));
    int verifiedClassCount = 0;
    for (ClassReader classReader : klassMap.values()) {
        if (!shouldVerify(viewDataBindingClass, classReader, superClassLookup)) {
            continue;
        }
        verifiedClassCount++;
        String className = classReader.getClassName();
        PsiClass psiClass = javaPsiFacade.findClass(className.replace("/", "."), myAndroidFacet.getModule().getModuleWithDependenciesAndLibrariesScope(false));
        if (psiClass == null) {
            missingClasses.add(className);
            continue;
        }
        assertNotNull(psiClass);
        String asmInfo = collectDescriptions(classReader, baseClassInfo);
        String psiInfo = collectDescriptions(psiClass);
        assertEquals(className, asmInfo, psiInfo);
    }
    assertTrue("test sanity, should be able to find some data binding generated classes", verifiedClassCount > 3);
    assertEquals("These classes are missing", "", StringUtil.join(missingClasses, "\n"));
}
Also used : Iterables(com.google.common.collect.Iterables) java.util(java.util) SdkConstants(com.android.SdkConstants) StringUtil(com.intellij.openapi.util.text.StringUtil) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) ContainerUtil(com.intellij.util.containers.ContainerUtil) AndroidLibrary(com.android.builder.model.AndroidLibrary) Collectors(java.util.stream.Collectors) File(java.io.File) Predicate(com.google.common.base.Predicate) PROJECT_WITH_DATA_BINDING(com.android.tools.idea.testing.TestProjectPaths.PROJECT_WITH_DATA_BINDING) Message(com.android.ide.common.blame.Message) org.jetbrains.org.objectweb.asm(org.jetbrains.org.objectweb.asm) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) AndroidGradleTestCase(com.android.tools.idea.testing.AndroidGradleTestCase) com.intellij.psi(com.intellij.psi) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) NotNull(org.jetbrains.annotations.NotNull) ZipEntry(java.util.zip.ZipEntry) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) Joiner(com.google.common.base.Joiner) IOException(java.io.IOException) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 5 with GradleSyncState

use of com.android.tools.idea.gradle.project.sync.GradleSyncState in project android by JetBrains.

the class MakeBeforeRunTaskProvider method executeTask.

@Override
public boolean executeTask(DataContext context, RunConfiguration configuration, ExecutionEnvironment env, MakeBeforeRunTask task) {
    if (!AndroidProjectInfo.getInstance(myProject).requiresAndroidModel() || !isDirectGradleInvocationEnabled(myProject)) {
        CompileStepBeforeRun regularMake = new CompileStepBeforeRun(myProject);
        return regularMake.executeTask(context, configuration, env, new CompileStepBeforeRun.MakeBeforeRunTask());
    }
    AtomicReference<String> errorMsgRef = new AtomicReference<>();
    if (AndroidGradleBuildConfiguration.getInstance(myProject).SYNC_PROJECT_BEFORE_BUILD) {
        // If the model needs a sync, we need to sync "synchronously" before running.
        // See: https://code.google.com/p/android/issues/detail?id=70718
        GradleSyncState syncState = GradleSyncState.getInstance(myProject);
        if (syncState.isSyncNeeded() != ThreeState.NO) {
            GradleSyncInvoker.Request request = new GradleSyncInvoker.Request().setRunInBackground(false);
            GradleSyncInvoker.getInstance().requestProjectSync(myProject, request, new GradleSyncListener.Adapter() {

                @Override
                public void syncFailed(@NotNull Project project, @NotNull String errorMessage) {
                    errorMsgRef.set(errorMessage);
                }
            });
        }
    }
    String errorMsg = errorMsgRef.get();
    if (errorMsg != null) {
        // Sync failed. There is no point on continuing, because most likely the model is either not there, or has stale information,
        // including the path of the APK.
        LOG.info("Unable to launch '" + TASK_NAME + "' task. Project sync failed with message: " + errorMsg);
        return false;
    }
    if (myProject.isDisposed()) {
        return false;
    }
    // Some configurations (e.g. native attach) don't require a build while running the configuration
    if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase) configuration).excludeCompileBeforeLaunchOption()) {
        return true;
    }
    // Note: this before run task provider may be invoked from a context such as Java unit tests, in which case it doesn't have
    // the android run config context
    AndroidRunConfigContext runConfigContext = env.getCopyableUserData(AndroidRunConfigContext.KEY);
    DeviceFutures deviceFutures = runConfigContext == null ? null : runConfigContext.getTargetDevices();
    List<AndroidDevice> targetDevices = deviceFutures == null ? Collections.emptyList() : deviceFutures.getDevices();
    List<String> cmdLineArgs = getCommonArguments(configuration, targetDevices);
    BeforeRunBuilder builder = createBuilder(env, getModules(myProject, context, configuration), configuration, runConfigContext, task.getGoal());
    try {
        boolean success = builder.build(GradleTaskRunner.newRunner(myProject), cmdLineArgs);
        LOG.info("Gradle invocation complete, success = " + success);
        return success;
    } catch (InvocationTargetException e) {
        LOG.info("Unexpected error while launching gradle before run tasks", e);
        return false;
    } catch (InterruptedException e) {
        LOG.info("Interrupted while launching gradle before run tasks");
        Thread.currentThread().interrupt();
        return false;
    }
}
Also used : GradleSyncInvoker(com.android.tools.idea.gradle.project.sync.GradleSyncInvoker) AtomicReference(java.util.concurrent.atomic.AtomicReference) InvocationTargetException(java.lang.reflect.InvocationTargetException) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) RunConfigurationBase(com.intellij.execution.configurations.RunConfigurationBase) AndroidProject(com.android.builder.model.AndroidProject) Project(com.intellij.openapi.project.Project) ApkProjects.isApkProject(com.android.tools.idea.apk.ApkProjects.isApkProject) GradleSyncListener(com.android.tools.idea.gradle.project.sync.GradleSyncListener) CompileStepBeforeRun(com.intellij.compiler.options.CompileStepBeforeRun)

Aggregations

GradleSyncState (com.android.tools.idea.gradle.project.sync.GradleSyncState)15 Project (com.intellij.openapi.project.Project)6 GradleInvocationResult (com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult)2 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)2 NdkModuleModel (com.android.tools.idea.gradle.project.model.NdkModuleModel)2 GradleSyncSummary (com.android.tools.idea.gradle.project.sync.GradleSyncSummary)2 Module (com.intellij.openapi.module.Module)2 NotNull (org.jetbrains.annotations.NotNull)2 SdkConstants (com.android.SdkConstants)1 VisibleForTesting (com.android.annotations.VisibleForTesting)1 AndroidLibrary (com.android.builder.model.AndroidLibrary)1 AndroidProject (com.android.builder.model.AndroidProject)1 Message (com.android.ide.common.blame.Message)1 GradleVersion (com.android.ide.common.repository.GradleVersion)1 ApkProjects.isApkProject (com.android.tools.idea.apk.ApkProjects.isApkProject)1 AndroidPluginGeneration (com.android.tools.idea.gradle.plugin.AndroidPluginGeneration)1 AndroidPluginVersionUpdater (com.android.tools.idea.gradle.plugin.AndroidPluginVersionUpdater)1 AndroidGradleBuildConfiguration (com.android.tools.idea.gradle.project.build.compiler.AndroidGradleBuildConfiguration)1 GradleFacet (com.android.tools.idea.gradle.project.facet.gradle.GradleFacet)1 NdkFacet (com.android.tools.idea.gradle.project.facet.ndk.NdkFacet)1