Java Code Examples for com.intellij.openapi.project.DumbService#getInstance()

The following examples show how to use com.intellij.openapi.project.DumbService#getInstance() . 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: SQLGeneratorAction.java    From CodeGen with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {

    Project project = PsiUtil.getProject(anActionEvent);
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService.showDumbModeNotification(CodeGenBundle.message("codegen.plugin.is.not.available.during.indexing"));
        return;
    }

    JFrame frame = new JFrame();
    SqlEditorPanel sqlPane = new SqlEditorPanel(new IdeaContext(project));
    frame.setContentPane(sqlPane.getRootComponent());
    MyDialogWrapper frameWrapper = new MyDialogWrapper(project, frame.getRootPane());
    frameWrapper.setActionOperator(sqlPane);
    frameWrapper.setTitle("CodeGen-SQL");
    frameWrapper.setSize(600, 400);
    frameWrapper.setResizable(false);
    frameWrapper.show();
}
 
Example 2
Source File: CreateTemplateInPackageAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private T checkOrCreate(String newName, PsiDirectory directory, String templateName) throws IncorrectOperationException {
  PsiDirectory dir = directory;
  String className = removeExtension(templateName, newName);

  if (className.contains(".")) {
    String[] names = className.split("\\.");

    for (int i = 0; i < names.length - 1; i++) {
      dir = CreateFileAction.findOrCreateSubdirectory(dir, names[i]);
    }

    className = names[names.length - 1];
  }

  DumbService service = DumbService.getInstance(dir.getProject());
  service.setAlternativeResolveEnabled(true);
  try {
    return doCreate(dir, className, templateName);
  }
  finally {
    service.setAlternativeResolveEnabled(false);
  }
}
 
Example 3
Source File: AnalysisScope.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void commitAndRunInSmartMode(final Runnable runnable, final Project project) {
  while (true) {
    final DumbService dumbService = DumbService.getInstance(project);
    dumbService.waitForSmartMode();
    boolean passed = PsiDocumentManager.getInstance(project).commitAndRunReadAction(new Computable<Boolean>() {
      @Override
      public Boolean compute() {
        if (dumbService.isDumb()) return false;
        runnable.run();
        return true;
      }
    });
    if (passed) {
      break;
    }
  }
}
 
Example 4
Source File: DocGenerateAction.java    From CodeMaker with Apache License 2.0 6 votes vote down vote up
/**
 * @see com.intellij.openapi.actionSystem.AnAction#actionPerformed(com.intellij.openapi.actionSystem.AnActionEvent)
 */
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService.showDumbModeNotification("CodeMaker plugin is not available during indexing");
        return;
    }
    PsiFile javaFile = e.getData(CommonDataKeys.PSI_FILE);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (javaFile == null || editor == null) {
        return;
    }
    List<PsiClass> classes = CodeMakerUtil.getClasses(javaFile);
    PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(project);
    for (PsiClass psiClass : classes) {
        for (PsiMethod psiMethod : PsiTreeUtil.getChildrenOfTypeAsList(psiClass, PsiMethod.class)) {
            createDocForMethod(psiMethod, psiElementFactory);
        }
    }

}
 
Example 5
Source File: FileGeneratorAction.java    From CodeGen with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = PsiUtil.getProject(e);
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService.showDumbModeNotification(CodeGenBundle.message("codegen.plugin.is.not.available.during.indexing"));
        return;
    }
    IdeaContext ideaContext = new IdeaContext(project);
    // 获取所有模板, 渲染选择控件
    // TODO: 是否需要自定义参数的表格
    List<CodeRoot> codeRoots =  SettingManager.getInstance().getTemplates().getRoots();
    SelectGroupPanel selectGroupPanel = new SelectGroupPanel(codeRoots, project);
    MyDialogWrapper frameWrapper = new MyDialogWrapper(project, selectGroupPanel.getRootPanel());
    frameWrapper.setActionOperator(new FileGeneratorActionOperator(ideaContext, selectGroupPanel));
    frameWrapper.setTitle("CodeGen-Files");
    frameWrapper.setSize(600, 400);
    frameWrapper.setResizable(false);
    frameWrapper.show();
}
 
Example 6
Source File: DBGeneratorAction.java    From CodeGen with MIT License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = PsiUtil.getProject(e);
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService.showDumbModeNotification(CodeGenBundle.message("codegen.plugin.is.not.available.during.indexing"));
        return;
    }

    Iterator<DbElement> iterator = DatabaseView.getSelectedElements(e.getDataContext(), DbElement.class).iterator();

    List<DbTable> tables = new ArrayList<>();
    while (iterator.hasNext()) {
        DbElement table = iterator.next();
        if (table instanceof DbTable) {
            tables.add((DbTable) table);
        }
    }

    ColumnEditorFrame frame = new ColumnEditorFrame();
    frame.newColumnEditorByDb(new IdeaContext(project), tables);
    MyDialogWrapper frameWrapper = new MyDialogWrapper(project, frame.getRootPane());
    frameWrapper.setActionOperator(frame);
    frameWrapper.setTitle("CodeGen-DB");
    frameWrapper.setSize(800, 550);
    frameWrapper.setResizable(false);
    frameWrapper.show();
}
 
Example 7
Source File: GenerateApiTableHtmlAction.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService
            .showDumbModeNotification("CodeMaker plugin is not available during indexing");
        return;
    }
    PsiFile javaFile = e.getData(CommonDataKeys.PSI_FILE);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (javaFile == null || editor == null) {
        return;
    }
    List<PsiClass> classes = CodeMakerUtil.getClasses(javaFile);
    StringBuilder table = new StringBuilder(128);
    table.append("<table border=\"1\">");
    for (PsiClass psiClass : classes) {
        for (ClassEntry.Field field : CodeMakerUtil.getAllFields(psiClass)) {
            if (field.getModifier().contains("static")) {
                continue;
            }
            table.append("<tr>");
            table.append("<th>").append(field.getName()).append("</th>");
            table.append("<th>").append(StringEscapeUtils.escapeHtml(field.getType()))
                .append("</th>");
            table.append("<th>").append(StringEscapeUtils.escapeHtml(field.getComment()))
                .append("</th>");
            table.append("</tr>");
        }
    }
    table.append("</table>");
    CopyPasteManager.getInstance()
        .setContents(new SimpleTransferable(table.toString(), DataFlavor.allHtmlFlavor));
}
 
Example 8
Source File: GenerateApiTableMarkdownAction.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService
            .showDumbModeNotification("CodeMaker plugin is not available during indexing");
        return;
    }
    PsiFile javaFile = e.getData(CommonDataKeys.PSI_FILE);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (javaFile == null || editor == null) {
        return;
    }
    List<PsiClass> classes = CodeMakerUtil.getClasses(javaFile);
    StringBuilder table = new StringBuilder(128);
    table.append("|     |     |     |\n");
    table.append("| --- | --- | --- |\n");
    for (PsiClass psiClass : classes) {
        for (ClassEntry.Field field : CodeMakerUtil.getAllFields(psiClass)) {
            if (field.getModifier().contains("static")) {
                continue;
            }
            table.append("|").append(field.getName());
            table.append("|").append(CodeMakerUtil.escapeMarkdown(field.getType()));
            table.append("|").append(CodeMakerUtil.escapeMarkdown(field.getComment()))
                .append("|\n");
        }
    }
    CopyPasteManager.getInstance()
        .setContents(new SimpleTransferable(table.toString(), DataFlavor.stringFlavor));
}
 
Example 9
Source File: BlazeAndroidSyncListener.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void afterSync(
    Project project,
    BlazeContext context,
    SyncMode syncMode,
    SyncResult syncResult,
    ImmutableSet<Integer> buildIds) {
  if (syncResult.successful()) {
    DumbService dumbService = DumbService.getInstance(project);
    dumbService.queueTask(new ResourceFolderRegistry.PopulateCachesTask(project));
  }
}
 
Example 10
Source File: DefaultHighlightVisitor.java    From consulo with Apache License 2.0 5 votes vote down vote up
DefaultHighlightVisitor(@Nonnull Project project,
                        boolean highlightErrorElements,
                        boolean runAnnotators,
                        boolean batchMode,
                        @Nonnull CachedAnnotators cachedAnnotators) {
  myProject = project;
  myHighlightErrorElements = highlightErrorElements;
  myRunAnnotators = runAnnotators;
  myCachedAnnotators = cachedAnnotators;
  myErrorFilters = HighlightErrorFilter.EP_NAME.getExtensions(project);
  myDumbService = DumbService.getInstance(project);
  myBatchMode = batchMode;
}
 
Example 11
Source File: ShowParameterInfoHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static ParameterInfoHandler[] getHandlers(Project project, final Language... languages) {
  Set<ParameterInfoHandler> handlers = new LinkedHashSet<>();
  DumbService dumbService = DumbService.getInstance(project);
  for (final Language language : languages) {
    handlers.addAll(dumbService.filterByDumbAwareness(LanguageParameterInfo.INSTANCE.allForLanguage(language)));
  }
  if (handlers.isEmpty()) return null;
  return handlers.toArray(new ParameterInfoHandler[0]);
}
 
Example 12
Source File: CodeGeneratorAction.java    From code-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    Project project = anActionEvent.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService.showDumbModeNotification("CodeGenerator plugin is not available during indexing");
        return;
    }

    SelectPathDialog dialog = new SelectPathDialog(project, templateSettings.getTemplateGroupMap());
    dialog.show();
    if (dialog.isOK()) {
        String basePackage = dialog.getBasePackage();
        String outputPath = dialog.getOutputPath();
        String templateGroup = dialog.getTemplateGroup();

        PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);
        if (Objects.isNull(psiFile) || !(psiFile instanceof PsiJavaFile)) {
            return;
        }

        PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
        PsiClass[] psiClasses = psiJavaFile.getClasses();
        try {
            Map<String, Template> templateMap = templateSettings.getTemplateGroup(templateGroup).getTemplateMap();
            Entity entity = buildClassEntity(psiClasses[0]);
            TemplateUtils.generate(templateMap, entity, basePackage, outputPath);
        } catch (Exception e) {
            Messages.showMessageDialog(project, e.getMessage(), "Generate Failed", null);
            return;
        }
        Messages.showMessageDialog(project, "Code generation successful", "Success", null);
    }
}
 
Example 13
Source File: GenerateCodeFromApiTableAction.java    From CodeMaker with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService
            .showDumbModeNotification("CodeMaker plugin is not available during indexing");
        return;
    }
    PsiFile javaFile = e.getData(CommonDataKeys.PSI_FILE);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (javaFile == null || editor == null) {
        return;
    }
    Transferable transferable = CopyPasteManager.getInstance().getContents();
    if (transferable == null) {
        return;
    }
    try {
        String table = (String) transferable.getTransferData(DataFlavor.stringFlavor);
        List<String> tableList = Splitter.onPattern("\n|\t|\r\n").splitToList(table);
        PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(project);
        int mod = tableList.size() % 3;
        int end = tableList.size() - mod;

        for (int i = 0; i < end; i++) {
            String fieldName = tableList.get(i);
            String fieldType = tableList.get(++i);
            String fieldComment = tableList.get(++i);
            PsiField psiField = psiElementFactory.createField(fieldName,
                PsiType.getTypeByName(fieldType, project, GlobalSearchScope.allScope(project)));
            Map<String, Object> map = Maps.newHashMap();
            map.put("comment", fieldComment);
            String vm = "/**\n" + " * ${comment}\n" + " */";
            if (settings.getCodeTemplate("FieldComment.vm") != null) {
                vm = settings.getCodeTemplate("FieldComment.vm").getCodeTemplate();
            }
            String fieldDocComment = VelocityUtil.evaluate(vm, map);
            PsiDocComment docComment = psiElementFactory
                .createDocCommentFromText(fieldDocComment);
            psiField.addBefore(docComment, psiField.getFirstChild());
            WriteCommandAction writeCommandAction = new FieldWriteAction(project,
                CodeMakerUtil.getClasses(javaFile).get(0), psiField, javaFile);
            RunResult result = writeCommandAction.execute();
            if (result.hasException()) {
                LOGGER.error(result.getThrowable());
                Messages.showErrorDialog("CodeMaker plugin is not available, cause: "
                                         + result.getThrowable().getMessage(),
                    "CodeMaker plugin");
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ex);
    }
}
 
Example 14
Source File: CodeMakerAction.java    From CodeMaker with Apache License 2.0 4 votes vote down vote up
/**
 * @see com.intellij.openapi.actionSystem.AnAction#actionPerformed(com.intellij.openapi.actionSystem.AnActionEvent)
 */
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    Project project = anActionEvent.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService.showDumbModeNotification("CodeMaker plugin is not available during indexing");
        return;
    }
    CodeTemplate codeTemplate = settings.getCodeTemplate(templateKey);

    PsiElement psiElement = anActionEvent.getData(LangDataKeys.PSI_ELEMENT);
    if (!(psiElement instanceof PsiClass)) {
        Messages.showMessageDialog(project, "Please focus on a class", "Generate Failed", null);
        return;
    }
    log.info("current pisElement: " + psiElement.getClass().getName() + "(" + psiElement + ")");

    PsiClass psiClass = (PsiClass) psiElement;
    String language = psiElement.getLanguage().getID().toLowerCase();
    List<ClassEntry> selectClasses = getClasses(project, codeTemplate.getClassNumber(), psiClass);

    if (selectClasses.size() < 1) {
        Messages.showMessageDialog(project, "No Classes found", "Generate Failed", null);
        return;
    }

    try {
        ClassEntry currentClass = selectClasses.get(0);
        GeneratedSource generated = generateSource(codeTemplate, selectClasses, currentClass);
        DestinationChooser.Destination destination = chooseDestination(currentClass, project, psiElement);
        if (destination instanceof DestinationChooser.FileDestination) {
            saveToFile(anActionEvent, language, generated.className, generated.content, currentClass, (DestinationChooser.FileDestination) destination, codeTemplate.getFileEncoding());
        }
        else if(destination == DestinationChooser.ShowSourceDestination) {
            showSource(project, codeTemplate.getTargetLanguage(), generated.className, generated.content);
        }

    } catch (Exception e) {
        Messages.showMessageDialog(project, e.getMessage(), "Generate Failed", null);
    }
}
 
Example 15
Source File: PsiSearchHelperImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Inject
public PsiSearchHelperImpl(@Nonnull PsiManager manager) {
  myManager = (PsiManagerEx)manager;
  myDumbService = DumbService.getInstance(myManager.getProject());
}
 
Example 16
Source File: StartupManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void runPostStartupActivities(UIAccess uiAccess) {
  if (postStartupActivityPassed()) {
    return;
  }

  final Application app = myApplication;

  if (!app.isHeadlessEnvironment()) {
    checkFsSanity();
    checkProjectRoots();
  }

  runActivities(uiAccess, myDumbAwarePostStartupActivities, Phases.PROJECT_DUMB_POST_STARTUP);

  DumbService dumbService = DumbService.getInstance(myProject);
  dumbService.runWhenSmart(new Runnable() {
    @Override
    public void run() {
      app.assertIsDispatchThread();

      // myDumbAwarePostStartupActivities might be non-empty if new activities were registered during dumb mode
      runActivities(uiAccess, myDumbAwarePostStartupActivities, Phases.PROJECT_DUMB_POST_STARTUP);

      while (true) {
        List<Consumer<UIAccess>> dumbUnaware = takeDumbUnawareStartupActivities();
        if (dumbUnaware.isEmpty()) {
          break;
        }

        // queue each activity in smart mode separately so that if one of them starts the dumb mode, the next ones just wait for it to finish
        for (Consumer<UIAccess> activity : dumbUnaware) {
          dumbService.runWhenSmart(() -> runActivity(uiAccess, activity));
        }
      }

      if (dumbService.isDumb()) {
        // return here later to process newly submitted activities (if any) and set myPostStartupActivitiesPassed
        dumbService.runWhenSmart(this);
      }
      else {
        //noinspection SynchronizeOnThis
        synchronized (this) {
          myPostStartupActivitiesPassed = true;
        }
      }
    }
  });
}
 
Example 17
Source File: CompositeInputFilter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public CompositeInputFilter(@Nonnull Project project) {
  myDumbService = DumbService.getInstance(project);
}
 
Example 18
Source File: CompositeFilter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public CompositeFilter(@Nonnull Project project, @Nonnull List<? extends Filter> filters) {
  myDumbService = DumbService.getInstance(project);
  myFilters = new ArrayList<>(filters);
  myFilters.forEach(filter -> myIsAnyHeavy |= filter instanceof FilterMixin);
}
 
Example 19
Source File: ShowExpressionTypeHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static Set<ExpressionTypeProvider> getHandlers(final Project project, Language... languages) {
  DumbService dumbService = DumbService.getInstance(project);
  return JBIterable.of(languages).flatten(language -> dumbService.filterByDumbAwareness(LanguageExpressionTypes.INSTANCE.allForLanguage(language))).addAllTo(new LinkedHashSet<>());
}