Search in sources :

Example 21 with Disposable

use of com.intellij.openapi.Disposable in project kotlin by JetBrains.

the class ExecuteKotlinScriptMojo method executeScriptFile.

private void executeScriptFile(File scriptFile) throws MojoExecutionException {
    initCompiler();
    Disposable rootDisposable = Disposer.newDisposable();
    try {
        MavenPluginLogMessageCollector messageCollector = new MavenPluginLogMessageCollector(getLog());
        CompilerConfiguration configuration = new CompilerConfiguration();
        configuration.put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector);
        List<File> deps = new ArrayList<File>();
        deps.addAll(PathUtil.getJdkClassesRoots());
        deps.addAll(getDependenciesForScript());
        for (File item : deps) {
            if (item.exists()) {
                configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, new JvmClasspathRoot(item));
                getLog().debug("Adding to classpath: " + item.getAbsolutePath());
            } else {
                getLog().debug("Skipping non-existing dependency: " + item.getAbsolutePath());
            }
        }
        configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, new KotlinSourceRoot(scriptFile.getAbsolutePath()));
        configuration.put(CommonConfigurationKeys.MODULE_NAME, JvmAbi.DEFAULT_MODULE_NAME);
        K2JVMCompiler.Companion.configureScriptDefinitions(scriptTemplates.toArray(new String[scriptTemplates.size()]), configuration, messageCollector, new HashMap<String, Object>());
        KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForProduction(rootDisposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
        GenerationState state = KotlinToJVMBytecodeCompiler.INSTANCE.analyzeAndGenerate(environment);
        if (state == null) {
            throw new ScriptExecutionException(scriptFile, "compile error");
        }
        GeneratedClassLoader classLoader = new GeneratedClassLoader(state.getFactory(), getClass().getClassLoader());
        KtScript script = environment.getSourceFiles().get(0).getScript();
        FqName nameForScript = script.getFqName();
        try {
            Class<?> klass = classLoader.loadClass(nameForScript.asString());
            ExecuteKotlinScriptMojo.INSTANCE = this;
            if (ReflectionUtilKt.tryConstructClassFromStringArgs(klass, scriptArguments) == null)
                throw new ScriptExecutionException(scriptFile, "unable to construct script");
        } catch (ClassNotFoundException e) {
            throw new ScriptExecutionException(scriptFile, "internal error", e);
        }
    } finally {
        rootDisposable.dispose();
        ExecuteKotlinScriptMojo.INSTANCE = null;
    }
}
Also used : Disposable(com.intellij.openapi.Disposable) KtScript(org.jetbrains.kotlin.psi.KtScript) KotlinSourceRoot(org.jetbrains.kotlin.config.KotlinSourceRoot) FqName(org.jetbrains.kotlin.name.FqName) ArrayList(java.util.ArrayList) GenerationState(org.jetbrains.kotlin.codegen.state.GenerationState) JvmClasspathRoot(org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot) GeneratedClassLoader(org.jetbrains.kotlin.codegen.GeneratedClassLoader) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) File(java.io.File)

Example 22 with Disposable

use of com.intellij.openapi.Disposable in project kotlin by JetBrains.

the class ResolveDescriptorsFromExternalLibraries method parseLibraryFileChunk.

private static boolean parseLibraryFileChunk(File jar, String libDescription, ZipInputStream zip, int classesPerChunk) throws IOException {
    Disposable junk = new Disposable() {

        @Override
        public void dispose() {
        }
    };
    KotlinCoreEnvironment environment;
    if (jar != null) {
        environment = KotlinCoreEnvironment.createForTests(junk, KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK, KotlinTestUtils.getAnnotationsJar(), jar), EnvironmentConfigFiles.JVM_CONFIG_FILES);
    } else {
        CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, TestJdkKind.FULL_JDK);
        environment = KotlinCoreEnvironment.createForTests(junk, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
        if (!findRtJar().equals(jar)) {
            throw new RuntimeException("rt.jar mismatch: " + jar + ", " + findRtJar());
        }
    }
    ModuleDescriptor module = JvmResolveUtil.analyze(environment).getModuleDescriptor();
    boolean hasErrors;
    try {
        hasErrors = false;
        for (int count = 0; count < classesPerChunk; ) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                break;
            }
            if (count == 0) {
                System.err.println("chunk from " + entry.getName());
            }
            System.err.println(entry.getName());
            String entryName = entry.getName();
            if (!entryName.endsWith(".class")) {
                continue;
            }
            if (entryName.matches("(.*/|)package-info\\.class")) {
                continue;
            }
            if (entryName.contains("$")) {
                continue;
            }
            String className = entryName.substring(0, entryName.length() - ".class".length()).replace("/", ".");
            try {
                ClassDescriptor clazz = DescriptorUtilsKt.resolveTopLevelClass(module, new FqName(className), NoLookupLocation.FROM_TEST);
                if (clazz == null) {
                    throw new IllegalStateException("class not found by name " + className + " in " + libDescription);
                }
                DescriptorUtils.getAllDescriptors(clazz.getDefaultType().getMemberScope());
            } catch (Exception e) {
                System.err.println("failed to resolve " + className);
                e.printStackTrace();
                //throw new RuntimeException("failed to resolve " + className + ": " + e, e);
                hasErrors = true;
            }
            ++count;
        }
    } finally {
        Disposer.dispose(junk);
    }
    return hasErrors;
}
Also used : Disposable(com.intellij.openapi.Disposable) ClassDescriptor(org.jetbrains.kotlin.descriptors.ClassDescriptor) FqName(org.jetbrains.kotlin.name.FqName) ZipEntry(java.util.zip.ZipEntry) ModuleDescriptor(org.jetbrains.kotlin.descriptors.ModuleDescriptor) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration)

Example 23 with Disposable

use of com.intellij.openapi.Disposable in project intellij-community by JetBrains.

the class ExternalSystemUtil method runTask.

public static void runTask(@NotNull final ExternalSystemTaskExecutionSettings taskSettings, @NotNull final String executorId, @NotNull final Project project, @NotNull final ProjectSystemId externalSystemId, @Nullable final TaskCallback callback, @NotNull final ProgressExecutionMode progressExecutionMode, boolean activateToolWindowBeforeRun) {
    ExecutionEnvironment environment = createExecutionEnvironment(project, externalSystemId, taskSettings, executorId);
    if (environment == null)
        return;
    RunnerAndConfigurationSettings runnerAndConfigurationSettings = environment.getRunnerAndConfigurationSettings();
    assert runnerAndConfigurationSettings != null;
    runnerAndConfigurationSettings.setActivateToolWindowBeforeRun(activateToolWindowBeforeRun);
    final TaskUnderProgress task = new TaskUnderProgress() {

        @Override
        public void execute(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            final Semaphore targetDone = new Semaphore();
            final Ref<Boolean> result = new Ref<>(false);
            final Disposable disposable = Disposer.newDisposable();
            project.getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() {

                public void processStartScheduled(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
                    if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                        targetDone.down();
                    }
                }

                public void processNotStarted(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
                    if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                        targetDone.up();
                    }
                }

                public void processStarted(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal, @NotNull final ProcessHandler handler) {
                    if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                        handler.addProcessListener(new ProcessAdapter() {

                            public void processTerminated(ProcessEvent event) {
                                result.set(event.getExitCode() == 0);
                                targetDone.up();
                            }
                        });
                    }
                }
            });
            try {
                ApplicationManager.getApplication().invokeAndWait(() -> {
                    try {
                        environment.getRunner().execute(environment);
                    } catch (ExecutionException e) {
                        targetDone.up();
                        LOG.error(e);
                    }
                }, ModalityState.defaultModalityState());
            } catch (Exception e) {
                LOG.error(e);
                Disposer.dispose(disposable);
                return;
            }
            targetDone.waitFor();
            Disposer.dispose(disposable);
            if (callback != null) {
                if (result.get()) {
                    callback.onSuccess();
                } else {
                    callback.onFailure();
                }
            }
        }
    };
    final String title = AbstractExternalSystemTaskConfigurationType.generateName(project, taskSettings);
    switch(progressExecutionMode) {
        case NO_PROGRESS_SYNC:
            task.execute(new EmptyProgressIndicator());
            break;
        case MODAL_SYNC:
            new Task.Modal(project, title, true) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    task.execute(indicator);
                }
            }.queue();
            break;
        case NO_PROGRESS_ASYNC:
            ApplicationManager.getApplication().executeOnPooledThread(() -> task.execute(new EmptyProgressIndicator()));
            break;
        case IN_BACKGROUND_ASYNC:
            new Task.Backgroundable(project, title) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    task.execute(indicator);
                }
            }.queue();
            break;
        case START_IN_FOREGROUND_ASYNC:
            new Task.Backgroundable(project, title, true, PerformInBackgroundOption.DEAF) {

                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    task.execute(indicator);
                }
            }.queue();
    }
}
Also used : Disposable(com.intellij.openapi.Disposable) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) Task(com.intellij.openapi.progress.Task) ExternalSystemResolveProjectTask(com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProcessEvent(com.intellij.execution.process.ProcessEvent) Semaphore(com.intellij.util.concurrency.Semaphore) NotNull(org.jetbrains.annotations.NotNull) ImportCanceledException(com.intellij.openapi.externalSystem.service.ImportCanceledException) IOException(java.io.IOException) Ref(com.intellij.openapi.util.Ref) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ProcessHandler(com.intellij.execution.process.ProcessHandler)

Example 24 with Disposable

use of com.intellij.openapi.Disposable in project intellij-community by JetBrains.

the class CamelHumpMatcher method forceStartMatching.

/**
   * In an ideal world, all tests would use the same settings as production, i.e. middle matching.
   * If you see a usage of this method which can be easily removed (i.e. it's easy to make a test pass without it
   * by modifying test expectations slightly), please do it
   */
@TestOnly
@Deprecated
public static void forceStartMatching(Disposable parent) {
    ourForceStartMatching = true;
    Disposer.register(parent, new Disposable() {

        @Override
        public void dispose() {
            //noinspection AssignmentToStaticFieldFromInstanceMethod
            ourForceStartMatching = false;
        }
    });
}
Also used : Disposable(com.intellij.openapi.Disposable) TestOnly(org.jetbrains.annotations.TestOnly)

Example 25 with Disposable

use of com.intellij.openapi.Disposable in project intellij-community by JetBrains.

the class RunnerLayoutUiImpl method addListener.

@NotNull
@Override
public RunnerLayoutUi addListener(@NotNull final ContentManagerListener listener, @NotNull final Disposable parent) {
    final ContentManager mgr = getContentManager();
    mgr.addContentManagerListener(listener);
    Disposer.register(parent, new Disposable() {

        @Override
        public void dispose() {
            mgr.removeContentManagerListener(listener);
        }
    });
    return this;
}
Also used : Disposable(com.intellij.openapi.Disposable) ContentManager(com.intellij.ui.content.ContentManager) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Disposable (com.intellij.openapi.Disposable)282 NotNull (org.jetbrains.annotations.NotNull)52 Test (org.junit.Test)25 Project (com.intellij.openapi.project.Project)18 TestOnly (org.jetbrains.annotations.TestOnly)17 ArrayList (java.util.ArrayList)13 VirtualFile (com.intellij.openapi.vfs.VirtualFile)11 RelativePoint (com.intellij.ui.awt.RelativePoint)11 Nullable (org.jetbrains.annotations.Nullable)10 Document (com.intellij.openapi.editor.Document)9 File (java.io.File)9 ProcessHandler (com.intellij.execution.process.ProcessHandler)6 Editor (com.intellij.openapi.editor.Editor)6 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)6 VirtualFilePointer (com.intellij.openapi.vfs.pointers.VirtualFilePointer)6 Content (com.intellij.ui.content.Content)6 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)5 Alarm (com.intellij.util.Alarm)5 ActionEvent (java.awt.event.ActionEvent)5 ListSelectionEvent (javax.swing.event.ListSelectionEvent)5