com.intellij.openapi.compiler.CompilerManager Java Examples

The following examples show how to use com.intellij.openapi.compiler.CompilerManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractRefactoringPanel.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
/**
 * Compiles the project and runs the task only if there are no compilation errors.
 */
private static void runAfterCompilationCheck(ProjectInfo projectInfo, Task task) {
    ApplicationManager.getApplication().invokeLater(() -> {
        List<PsiClass> classes = projectInfo.getClasses();

        if (!classes.isEmpty()) {
            VirtualFile[] virtualFiles = classes.stream()
                    .map(classObject -> classObject.getContainingFile().getVirtualFile()).toArray(VirtualFile[]::new);
            Project project = projectInfo.getProject();

            CompilerManager compilerManager = CompilerManager.getInstance(project);
            CompileStatusNotification callback = (aborted, errors, warnings, compileContext) -> {
                if (errors == 0 && !aborted) {
                    ProgressManager.getInstance().run(task);
                } else {
                    task.onCancel();
                    AbstractRefactoringPanel.showCompilationErrorNotification(project);
                }
            };
            CompileScope compileScope = compilerManager.createFilesCompileScope(virtualFiles);
            compilerManager.make(compileScope, callback);
        } else {
            ProgressManager.getInstance().run(task);
        }
    });
}
 
Example #2
Source File: ModuleChunk.java    From consulo with Apache License 2.0 6 votes vote down vote up
private VirtualFile[] filterRoots(VirtualFile[] roots, Project project, final int sourcesFilter) {
  final List<VirtualFile> filteredRoots = new ArrayList<VirtualFile>(roots.length);
  for (final VirtualFile root : roots) {
    if (sourcesFilter != ALL_SOURCES) {
      if (myContext.isInTestSourceContent(root)) {
        if ((sourcesFilter & TEST_SOURCES) == 0) {
          continue;
        }
      }
      else {
        if ((sourcesFilter & SOURCES) == 0) {
          continue;
        }
      }
    }
    if (CompilerManager.getInstance(project).isExcludedFromCompilation(root)) {
      continue;
    }
    filteredRoots.add(root);
  }
  return VfsUtil.toVirtualFileArray(filteredRoots);
}
 
Example #3
Source File: PackageFileAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static List<VirtualFile> getFilesToPackage(@Nonnull AnActionEvent e, @Nonnull Project project) {
  final VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
  if (files == null) return Collections.emptyList();

  List<VirtualFile> result = new ArrayList<VirtualFile>();
  ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final CompilerManager compilerManager = CompilerManager.getInstance(project);
  for (VirtualFile file : files) {
    if (file == null || file.isDirectory() ||
        fileIndex.isInSourceContent(file) && compilerManager.isCompilableFileType(file.getFileType())) {
      return Collections.emptyList();
    }
    final Collection<? extends Artifact> artifacts = ArtifactBySourceFileFinder.getInstance(project).findArtifacts(file);
    for (Artifact artifact : artifacts) {
      if (!StringUtil.isEmpty(artifact.getOutputPath())) {
        result.add(file);
        break;
      }
    }
  }
  return result;
}
 
Example #4
Source File: MakeModuleAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
protected void doAction(DataContext dataContext, Project project) {
  Module[] modules = dataContext.getData(LangDataKeys.MODULE_CONTEXT_ARRAY);
  Module module;
  if (modules == null) {
    module = dataContext.getData(LangDataKeys.MODULE);
    if (module == null) {
      return;
    }
    modules = new Module[]{module};
  }
  try {
    CompilerManager.getInstance(project).make(modules[0].getProject(), modules, null);
  }
  catch (Exception e) {
    LOG.error(e);
  }
}
 
Example #5
Source File: CreateIpaAction.java    From robovm-idea with GNU General Public License v2.0 6 votes vote down vote up
public void actionPerformed(final AnActionEvent e) {
    final CreateIpaDialog dialog = new CreateIpaDialog(e.getProject());
    dialog.show();
    if(dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
        // create IPA
        IpaConfig ipaConfig = dialog.getIpaConfig();
        CompileScope scope = CompilerManager.getInstance(e.getProject()).createModuleCompileScope(ipaConfig.module, true);
        scope.putUserData(IPA_CONFIG_KEY, ipaConfig);
        CompilerManager.getInstance(e.getProject()).compile(scope, new CompileStatusNotification() {
            @Override
            public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
                RoboVmPlugin.logInfo(e.getProject(), "IPA creation complete, %d errors, %d warnings", errors, warnings);
            }
        });
    }
}
 
Example #6
Source File: GaugeRefactorHandler.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
void compileAndRefactor(String currentStepText, String newStepText, @Nullable RefactorStatusCallback refactorStatusCallback) {
    refactorStatusCallback.onStatusChange("Compiling...");
    TransactionId contextTransaction = TransactionGuard.getInstance().getContextTransaction();
    CompilerManager.getInstance(project).make((aborted, errors, warnings, context) -> {
        if (errors > 0) {
            refactorStatusCallback.onFinish(new RefactoringStatus(false, "Please fix all errors before refactoring."));
            return;
        }
        refactor(currentStepText, newStepText, contextTransaction, context, refactorStatusCallback);
    });
}
 
Example #7
Source File: CompilerExcludedConfigurable.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public CompilerExcludedConfigurable(final Project project) {
  CompilerManager compilerManager = CompilerManager.getInstance(project);

  myConfigurable = new ExcludedEntriesConfigurable(project, new FileChooserDescriptor(true, true, false, false, false, true),
                                                   compilerManager.getExcludedEntriesConfiguration());
}
 
Example #8
Source File: RoboVmPlugin.java    From robovm-idea with GNU General Public License v2.0 5 votes vote down vote up
private static void compileIfChanged(VirtualFileEvent event, final Project project) {
    if(!RoboVmGlobalConfig.isCompileOnSave()) {
        return;
    }
    VirtualFile file = event.getFile();
    Module module = null;
    for(Module m: ModuleManager.getInstance(project).getModules()) {
        if(ModuleRootManager.getInstance(m).getFileIndex().isInContent(file)) {
            module = m;
            break;
        }
    }

    if(module != null) {
        if(isRoboVmModule(module)) {
            final Module foundModule = module;
            OrderEntry orderEntry = ModuleRootManager.getInstance(module).getFileIndex().getOrderEntryForFile(file);
            if(orderEntry != null && orderEntry.getFiles(OrderRootType.SOURCES).length != 0) {
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        if(!CompilerManager.getInstance(project).isCompilationActive()) {
                            CompileScope scope = CompilerManager.getInstance(project).createModuleCompileScope(foundModule, true);
                            CompilerManager.getInstance(project).compile(scope, null);
                        }
                    }
                });
            }
        }
    }
}
 
Example #9
Source File: BuildArtifactAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void doBuild(@Nonnull Project project, final @Nonnull List<ArtifactPopupItem> items, boolean rebuild) {
  final Set<Artifact> artifacts = getArtifacts(items, project);
  final CompileScope scope = ArtifactCompileScope.createArtifactsScope(project, artifacts, rebuild);

  ArtifactsWorkspaceSettings.getInstance(project).setArtifactsToBuild(artifacts);
  if (!rebuild) {
    //in external build we can set 'rebuild' flag per target type
    CompilerManager.getInstance(project).make(scope, null);
  }
  else {
    CompilerManager.getInstance(project).compile(scope, null);
  }
}
 
Example #10
Source File: ArtifactCompileScope.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static CompileScope createScopeWithArtifacts(final CompileScope baseScope,
                                                    @Nonnull Collection<Artifact> artifacts,
                                                    boolean useCustomContentId,
                                                    final boolean forceArtifactBuild) {
  baseScope.putUserData(ARTIFACTS_KEY, artifacts.toArray(new Artifact[artifacts.size()]));
  if (useCustomContentId) {
    baseScope.putUserData(CompilerManager.CONTENT_ID_KEY, ARTIFACTS_CONTENT_ID_KEY);
  }
  if (forceArtifactBuild) {
    baseScope.putUserData(FORCE_ARTIFACT_BUILD, Boolean.TRUE);
  }
  return baseScope;
}
 
Example #11
Source File: ExcludeFromCompileAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  VirtualFile file = getSelectedFile();

  if (file != null && file.isValid()) {
    ExcludeEntryDescription description = new ExcludeEntryDescription(file, false, true, myProject);
    CompilerManager.getInstance(myProject).getExcludedEntriesConfiguration().addExcludeEntryDescription(description);
    FileStatusManager.getInstance(myProject).fileStatusesChanged();
  }
}
 
Example #12
Source File: CompileAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
protected void doAction(DataContext dataContext, Project project) {
  final Module module = dataContext.getData(LangDataKeys.MODULE_CONTEXT);
  if (module != null) {
    CompilerManager.getInstance(project).compile(module, null);
  }
  else {
    VirtualFile[] files = getCompilableFiles(project, dataContext.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY));
    if (files.length > 0) {
      CompilerManager.getInstance(project).compile(files, null);
    }
  }

}
 
Example #13
Source File: CompileAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static VirtualFile[] getCompilableFiles(Project project, VirtualFile[] files) {
  if (files == null || files.length == 0) {
    return VirtualFile.EMPTY_ARRAY;
  }
  final PsiManager psiManager = PsiManager.getInstance(project);
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final CompilerManager compilerManager = CompilerManager.getInstance(project);
  final List<VirtualFile> filesToCompile = new ArrayList<VirtualFile>();
  for (final VirtualFile file : files) {
    if (!fileIndex.isInSourceContent(file)) {
      continue;
    }
    if (!file.isInLocalFileSystem()) {
      continue;
    }
    if (file.isDirectory()) {
      final PsiDirectory directory = psiManager.findDirectory(file);
      if (directory == null || PsiPackageManager.getInstance(project).findAnyPackage(directory) == null) {
        continue;
      }
    }
    else {
      FileType fileType = file.getFileType();
      if (!(compilerManager.isCompilableFileType(fileType) || isCompilableResourceFile(project, file))) {
        continue;
      }
    }
    filesToCompile.add(file);
  }
  return VfsUtil.toVirtualFileArray(filesToCompile);
}
 
Example #14
Source File: CompileProjectAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
protected void doAction(DataContext dataContext, final Project project) {
  CompilerManager.getInstance(project).rebuild(new CompileStatusNotification() {
    @Override
    public void finished(boolean aborted, int errors, int warnings, final CompileContext compileContext) {
      if (aborted) return;

      String text = getTemplatePresentation().getText();
      LocalHistory.getInstance().putSystemLabel(project, errors == 0
                                     ? CompilerBundle.message("rebuild.lvcs.label.no.errors", text)
                                     : CompilerBundle.message("rebuild.lvcs.label.with.errors", text));
    }
  });
}
 
Example #15
Source File: CompileActionBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void update(@Nonnull final AnActionEvent e) {
  super.update(e);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (project == null || !project.isInitialized()) {
    e.getPresentation().setEnabled(false);
  }
  else {
    e.getPresentation().setEnabled(!CompilerManager.getInstance(project).isCompilationActive());
  }
}
 
Example #16
Source File: CompileStepBeforeRun.java    From consulo with Apache License 2.0 4 votes vote down vote up
static AsyncResult<Void> doMake(UIAccess uiAccess, final Project myProject, final RunConfiguration configuration, final boolean ignoreErrors) {
  if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
    return AsyncResult.rejected();
  }

  if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase)configuration).excludeCompileBeforeLaunchOption()) {
    return AsyncResult.resolved();
  }

  final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
  AsyncResult<Void> result = AsyncResult.undefined();
  try {
    final CompileStatusNotification callback = (aborted, errors, warnings, compileContext) -> {
      if ((errors == 0 || ignoreErrors) && !aborted) {
        result.setDone();
      }
      else {
        result.setRejected();
      }
    };

    TransactionGuard.submitTransaction(myProject, () -> {
      CompileScope scope;
      final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
      if (Comparing.equal(Boolean.TRUE.toString(), System.getProperty(MAKE_PROJECT_ON_RUN_KEY))) {
        // user explicitly requested whole-project make
        scope = compilerManager.createProjectCompileScope();
      }
      else {
        final Module[] modules = runConfiguration.getModules();
        if (modules.length > 0) {
          for (Module module : modules) {
            if (module == null) {
              LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + runConfiguration.getClass().getName());
            }
          }
          scope = compilerManager.createModulesCompileScope(modules, true);
        }
        else {
          scope = compilerManager.createProjectCompileScope();
        }
      }

      if (!myProject.isDisposed()) {
        compilerManager.make(scope, callback);
      }
      else {
        result.setRejected();
      }
    });
  }
  catch (Exception e) {
    result.rejectWithThrowable(e);
  }

  return result;
}
 
Example #17
Source File: ExtendedPlatformServices.java    From CppTools with Apache License 2.0 4 votes vote down vote up
public static void registerCompilerStuff(Project project) {
  CompilerManager.getInstance(project).addCompilableFileType(CppSupportLoader.CPP_FILETYPE);
  CompilerManager.getInstance(project).addCompiler(new CppCompiler());
}
 
Example #18
Source File: CompilerTask.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void run(@Nonnull final ProgressIndicator indicator) {
  myIndicator = indicator;

  indicator.setIndeterminate(false);

  final Semaphore semaphore = ((CompilerManagerImpl)CompilerManager.getInstance(myProject)).getCompilationSemaphore();
  boolean acquired = false;
  try {

    try {
      while (!acquired) {
        acquired = semaphore.tryAcquire(300, TimeUnit.MILLISECONDS);
        if (!acquired && !myWaitForPreviousSession) {
          return;
        }
        if (indicator.isCanceled()) {
          // give up obtaining the semaphore,
          // let compile work begin in order to stop gracefuly on cancel event
          break;
        }
      }
    }
    catch (InterruptedException ignored) {
    }

    if (!isHeadless()) {
      addIndicatorDelegate();
    }
    myCompileWork.run();
  }
  finally {
    try {
      indicator.stop();
    }
    finally {
      if (acquired) {
        semaphore.release();
      }
    }
  }
}
 
Example #19
Source File: CompileDirtyAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
protected void doAction(DataContext dataContext, Project project) {
  CompilerManager.getInstance(project).make(null);
}
 
Example #20
Source File: CompileAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
public void update(@Nonnull AnActionEvent event) {
  super.update(event);
  Presentation presentation = event.getPresentation();
  if (!presentation.isEnabled()) {
    return;
  }
  DataContext dataContext = event.getDataContext();

  presentation.setText(ActionsBundle.actionText(IdeActions.ACTION_COMPILE));
  presentation.setVisible(true);

  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    presentation.setEnabled(false);
    return;
  }

  final Module module = dataContext.getData(LangDataKeys.MODULE_CONTEXT);

  final VirtualFile[] files = getCompilableFiles(project, dataContext.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY));
  if (module == null && files.length == 0) {
    presentation.setEnabled(false);
    presentation.setVisible(!ActionPlaces.isPopupPlace(event.getPlace()));
    return;
  }

  String elementDescription = null;
  if (module != null) {
    elementDescription = CompilerBundle.message("action.compile.description.module", module.getName());
  }
  else {
    PsiPackage aPackage = null;
    if (files.length == 1) {
      final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(files[0]);
      if (directory != null) {
        aPackage = PsiPackageManager.getInstance(project).findAnyPackage(directory);
      }
    }
    else {
      PsiElement element = dataContext.getData(LangDataKeys.PSI_ELEMENT);
      if (element instanceof PsiPackage) {
        aPackage = (PsiPackage)element;
      }
    }

    if (aPackage != null) {
      String name = aPackage.getQualifiedName();
      if (name.length() == 0) {
        //noinspection HardCodedStringLiteral
        name = "<default>";
      }
      elementDescription = "'" + name + "'";
    }
    else if (files.length == 1) {
      final VirtualFile file = files[0];
      FileType fileType = file.getFileType();
      if (CompilerManager.getInstance(project).isCompilableFileType(fileType) || isCompilableResourceFile(project, file)) {
        elementDescription = "'" + file.getName() + "'";
      }
      else {
        if (!ActionPlaces.MAIN_MENU.equals(event.getPlace())) {
          // the action should be invisible in popups for non-java files
          presentation.setEnabled(false);
          presentation.setVisible(false);
          return;
        }
      }
    }
    else {
      elementDescription = CompilerBundle.message("action.compile.description.selected.files");
    }
  }

  if (elementDescription == null) {
    presentation.setEnabled(false);
    return;
  }

  presentation.setText(createPresentationText(elementDescription), true);
  presentation.setEnabled(true);
}
 
Example #21
Source File: ArtifactsCompiler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@javax.annotation.Nullable
public static ArtifactsCompiler getInstance(@Nonnull Project project) {
  final ArtifactsCompiler[] compilers = CompilerManager.getInstance(project).getCompilers(ArtifactsCompiler.class);
  return compilers.length == 1 ? compilers[0] : null;
}
 
Example #22
Source File: CompilerIconDescriptorUpdater.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Deprecated
public static boolean isExcluded(final VirtualFile vFile, final Project project) {
  return vFile != null &&
         FileIndexFacade.getInstance(project).isInSource(vFile) &&
         CompilerManager.getInstance(project).isExcludedFromCompilation(vFile);
}
 
Example #23
Source File: CompilerIconDescriptorUpdater.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Inject
public CompilerIconDescriptorUpdater(FileIndexFacade fileIndexFacade, CompilerManager compilerManager) {
  myFileIndexFacade = fileIndexFacade;
  myCompilerManager = compilerManager;
}
 
Example #24
Source File: RoboVmPlugin.java    From robovm-idea with GNU General Public License v2.0 4 votes vote down vote up
public static void initializeProject(final Project project) {
    // setup a compile task if there isn't one yet
    boolean found = false;
    for (CompileTask task : CompilerManager.getInstance(project).getAfterTasks()) {
        if (task instanceof RoboVmCompileTask) {
            found = true;
            break;
        }
    }
    if (!found) {
        CompilerManager.getInstance(project).addAfterTask(new RoboVmCompileTask());
    }

    // hook ito the message bus so we get to know if a storyboard/xib
    // file is opened
    project.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new RoboVmFileEditorManagerListener(project));

    // initialize our tool window to which we
    // log all messages
    UIUtil.invokeLaterIfNeeded(new Runnable() {
        @Override
        public void run() {
            if (project.isDisposed()) {
                return;
            }
            ToolWindow toolWindow = ToolWindowManager.getInstance(project).registerToolWindow(ROBOVM_TOOLWINDOW_ID, false, ToolWindowAnchor.BOTTOM, project, true);
            ConsoleView consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole();
            Content content = toolWindow.getContentManager().getFactory().createContent(consoleView.getComponent(), "Console", true);
            toolWindow.getContentManager().addContent(content);
            toolWindow.setIcon(RoboVmIcons.ROBOVM_SMALL);
            consoleViews.put(project, consoleView);
            toolWindows.put(project, toolWindow);
            logInfo(project, "RoboVM plugin initialized");
        }
    });

    // initialize virtual file change listener so we can
    // trigger recompiles on file saves
    VirtualFileListener listener = new VirtualFileAdapter() {
        @Override
        public void contentsChanged(@NotNull VirtualFileEvent event) {
            compileIfChanged(event, project);
        }
    };
    VirtualFileManager.getInstance().addVirtualFileListener(listener);
    fileListeners.put(project, listener);
}
 
Example #25
Source File: ContentResourceChangeListener.java    From aem-ide-tooling-4-intellij with Apache License 2.0 4 votes vote down vote up
private void executeMakeInUIThread(final VirtualFileEvent event) {
    if(project.isInitialized() && !project.isDisposed() && project.isOpen()) {
        final CompilerManager compilerManager = CompilerManager.getInstance(project);
        if(!compilerManager.isCompilationActive() &&
            !compilerManager.isExcludedFromCompilation(event.getFile()) // &&
        ) {
            // Check first if there are no errors in the code
            CodeSmellDetector codeSmellDetector = CodeSmellDetector.getInstance(project);
            boolean isOk = true;
            if(codeSmellDetector != null) {
                List<CodeSmellInfo> codeSmellInfoList = codeSmellDetector.findCodeSmells(Arrays.asList(event.getFile()));
                for(CodeSmellInfo codeSmellInfo: codeSmellInfoList) {
                    if(codeSmellInfo.getSeverity() == HighlightSeverity.ERROR) {
                        isOk = false;
                        break;
                    }
                }
            }
            if(isOk) {
                // Changed file found in module. Make it.
                final ToolWindow tw = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW);
                final boolean isShown = tw != null && tw.isVisible();
                compilerManager.compile(
                    new VirtualFile[]{event.getFile()},
                    new CompileStatusNotification() {
                        @Override
                        public void finished(boolean b, int i, int i1, CompileContext compileContext) {
                            if (tw != null && tw.isVisible()) {
                                // Close / Hide the Build Message Window after we did the build if it wasn't shown
                                if(!isShown) {
                                    tw.hide(null);
                                }
                            }
                        }
                    }
                );
            } else {
                MessageManager messageManager = ComponentProvider.getComponent(project, MessageManager.class);
                if(messageManager != null) {
                    messageManager.sendErrorNotification(
                        "server.update.file.change.with.error",
                        event.getFile()
                    );
                }
            }
        }
    }
}