com.intellij.openapi.ui.popup.util.BaseListPopupStep Java Examples

The following examples show how to use com.intellij.openapi.ui.popup.util.BaseListPopupStep. 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: PopupFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public ListPopup createConfirmation(String title, final String yesText, String noText, final Runnable onYes, final Runnable onNo, int defaultOptionIndex) {
  final BaseListPopupStep<String> step = new BaseListPopupStep<String>(title, yesText, noText) {
    @Override
    public PopupStep onChosen(String selectedValue, final boolean finalChoice) {
      return doFinalStep(selectedValue.equals(yesText) ? onYes : onNo);
    }

    @Override
    public void canceled() {
      onNo.run();
    }

    @Override
    public boolean isMnemonicsNavigationEnabled() {
      return true;
    }
  };
  step.setDefaultOptionIndex(defaultOptionIndex);

  final Application app = ApplicationManager.getApplication();
  return app == null || !app.isUnitTestMode() ? new ListPopupImpl(step) : new MockConfirmation(step, yesText);
}
 
Example #2
Source File: PickAction.java    From otto-intellij-plugin with Apache License 2.0 6 votes vote down vote up
public static void startPicker(Type[] displayedTypes, RelativePoint relativePoint,
                               final Callback callback) {

  ListPopup listPopup = JBPopupFactory.getInstance()
      .createListPopup(new BaseListPopupStep<Type>("Select Type", displayedTypes) {
        @NotNull @Override public String getTextFor(Type value) {
          return value.toString();
        }

        @Override public PopupStep onChosen(Type selectedValue, boolean finalChoice) {
          callback.onTypeChose(selectedValue);
          return super.onChosen(selectedValue, finalChoice);
        }
      });

  listPopup.show(relativePoint);
}
 
Example #3
Source File: LibraryEditingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static BaseListPopupStep<LibraryType> createChooseTypeStep(final ClasspathPanel classpathPanel,
                                                                  final ParameterizedRunnable<LibraryType> action) {
  return new BaseListPopupStep<LibraryType>(IdeBundle.message("popup.title.select.library.type"), getSuitableTypes(classpathPanel)) {
        @Nonnull
        @Override
        public String getTextFor(LibraryType value) {
          String createActionName = value != null ? value.getCreateActionName() : null;
          return createActionName != null ? createActionName : IdeBundle.message("create.default.library.type.action.name");
        }

        @Override
        public Icon getIconFor(LibraryType aValue) {
          return aValue != null ? TargetAWT.to(aValue.getIcon()) : AllIcons.Nodes.PpLib;
        }

        @Override
        public PopupStep onChosen(final LibraryType selectedValue, boolean finalChoice) {
          return doFinalStep(new Runnable() {
            @Override
            public void run() {
              action.run(selectedValue);
            }
          });
        }
      };
}
 
Example #4
Source File: ProjectConfigurationProblem.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void fix(final JComponent contextComponent, RelativePoint relativePoint) {
  JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationErrorQuickFix>(null, myDescription.getFixes()) {
    @Nonnull
    @Override
    public String getTextFor(ConfigurationErrorQuickFix value) {
      return value.getActionName();
    }

    @Override
    public PopupStep onChosen(final ConfigurationErrorQuickFix selectedValue, boolean finalChoice) {
      return doFinalStep(new Runnable() {
        @Override
        public void run() {
          selectedValue.performFix();
        }
      });
    }
  }).show(relativePoint);
}
 
Example #5
Source File: ExpressionInputComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void showHistory() {
  List<XExpression> expressions = myExpressionEditor.getRecentExpressions();
  if (!expressions.isEmpty()) {
    ListPopupImpl popup = new ListPopupImpl(new BaseListPopupStep<XExpression>(null, expressions) {
      @Override
      public PopupStep onChosen(XExpression selectedValue, boolean finalChoice) {
        myExpressionEditor.setExpression(selectedValue);
        myExpressionEditor.requestFocusInEditor();
        return FINAL_CHOICE;
      }
    }) {
      @Override
      protected ListCellRenderer getListElementRenderer() {
        return new ColoredListCellRenderer<XExpression>() {
          @Override
          protected void customizeCellRenderer(@Nonnull JList list, XExpression value, int index, boolean selected, boolean hasFocus) {
            append(value.getExpression());
          }
        };
      }
    };
    popup.getList().setFont(EditorUtil.getEditorFont());
    popup.showUnderneathOf(myExpressionEditor.getEditorComponent());
  }
}
 
Example #6
Source File: ShowFilePathAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static ListPopup createPopup(List<VirtualFile> files, List<Image> icons) {
  final BaseListPopupStep<VirtualFile> step = new BaseListPopupStep<VirtualFile>("File Path", files, icons.stream().map(TargetAWT::to).collect(Collectors.toList())) {
    @Nonnull
    @Override
    public String getTextFor(final VirtualFile value) {
      return value.getPresentableName();
    }

    @Override
    public PopupStep onChosen(final VirtualFile selectedValue, final boolean finalChoice) {
      final File selectedFile = new File(getPresentableUrl(selectedValue));
      if (selectedFile.exists()) {
        Application.get().executeOnPooledThread((Runnable)() -> openFile(selectedFile));
      }
      return FINAL_CHOICE;
    }
  };

  return JBPopupFactory.getInstance().createListPopup(step);
}
 
Example #7
Source File: DocumentIntention.java    From weex-language-support with MIT License 6 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement psiElement) throws IncorrectOperationException {

    JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("Chosen", "Document", "Sample") {

        @Override
        public PopupStep onChosen(String selectedValue, boolean finalChoice) {

            if ("Document".equals(selectedValue)) {
                openDocument(psiElement.getText());
            } else if ("Sample".equals(selectedValue)) {
                openSample(project, editor);
            }

            return super.onChosen(selectedValue, finalChoice);
        }
    }).showInBestPositionFor(editor);
}
 
Example #8
Source File: IdeKeyEventDispatcher.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static ListPopupStep buildStep(@Nonnull final List<Pair<AnAction, KeyStroke>> actions, final DataContext ctx) {
  return new BaseListPopupStep<Pair<AnAction, KeyStroke>>("Choose an action", ContainerUtil.findAll(actions, pair -> {
    final AnAction action = pair.getFirst();
    final Presentation presentation = action.getTemplatePresentation().clone();
    AnActionEvent event = new AnActionEvent(null, ctx, ActionPlaces.UNKNOWN, presentation, ActionManager.getInstance(), 0);

    ActionUtil.performDumbAwareUpdate(LaterInvocator.isInModalContext(), action, event, true);
    return presentation.isEnabled() && presentation.isVisible();
  })) {
    @Override
    public PopupStep onChosen(Pair<AnAction, KeyStroke> selectedValue, boolean finalChoice) {
      invokeAction(selectedValue.getFirst(), ctx);
      return FINAL_CHOICE;
    }
  };
}
 
Example #9
Source File: PickTypeAction.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public void startPickTypes(RelativePoint relativePoint, PsiParameter[] psiParameters,
    final Callback callback) {
  if (psiParameters.length == 0) return;

  ListPopup listPopup = JBPopupFactory.getInstance()
      .createListPopup(new BaseListPopupStep<PsiParameter>("Select Type", psiParameters) {
        @NotNull @Override public String getTextFor(PsiParameter value) {
          StringBuilder builder = new StringBuilder();

          Set<String> annotations = PsiConsultantImpl.getQualifierAnnotations(value);
          for (String annotation : annotations) {
            String trimmed = annotation.substring(annotation.lastIndexOf(".") + 1);
            builder.append("@").append(trimmed).append(" ");
          }

          PsiClass notLazyOrProvider = PsiConsultantImpl.checkForLazyOrProvider(value);
          return builder.append(notLazyOrProvider.getName()).toString();
        }

        @Override public PopupStep onChosen(PsiParameter selectedValue, boolean finalChoice) {
          callback.onParameterChosen(selectedValue);
          return super.onChosen(selectedValue, finalChoice);
        }
      });

  listPopup.show(relativePoint);
}
 
Example #10
Source File: ProjectSettingsForm.java    From EclipseCodeFormatter with Apache License 2.0 5 votes vote down vote up
public ListPopup createConfirmation(String title, final String yesText, String noText, final Runnable onYes, final Runnable onNo, int defaultOptionIndex) {

		final BaseListPopupStep<String> step = new BaseListPopupStep<String>(title, new String[]{yesText, noText}) {
			@Override
			public PopupStep onChosen(String selectedValue, final boolean finalChoice) {
				if (selectedValue.equals(yesText)) {
					onYes.run();
				} else {
					onNo.run();
				}
				return FINAL_CHOICE;
			}

			@Override
			public void canceled() {
			}

			@Override
			public boolean isMnemonicsNavigationEnabled() {
				return true;
			}
		};
		step.setDefaultOptionIndex(defaultOptionIndex);

		final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
		return app == null || !app.isUnitTestMode() ? new ListPopupImpl(step) : new MockConfirmation(step, yesText);
	}
 
Example #11
Source File: XDebuggerSmartStepIntoHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static <V extends XSmartStepIntoVariant> void doSmartStepInto(final XSmartStepIntoHandler<V> handler,
                                                                      XSourcePosition position,
                                                                      final XDebugSession session,
                                                                      Editor editor) {
  List<V> variants = handler.computeSmartStepVariants(position);
  if (variants.isEmpty()) {
    session.stepInto();
    return;
  }
  else if (variants.size() == 1) {
    session.smartStepInto(handler, variants.get(0));
    return;
  }

  ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<V>(handler.getPopupTitle(position), variants) {
    @Override
    public Icon getIconFor(V aValue) {
      return TargetAWT.to(aValue.getIcon());
    }

    @Nonnull
    @Override
    public String getTextFor(V value) {
      return value.getText();
    }

    @Override
    public PopupStep onChosen(V selectedValue, boolean finalChoice) {
      session.smartStepInto(handler, selectedValue);
      return FINAL_CHOICE;
    }
  });
  DebuggerUIUtil.showPopupForEditorLine(popup, editor, position.getLine());
}
 
Example #12
Source File: ExportHTMLAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  final ListPopup popup = JBPopupFactory.getInstance().createListPopup(
    new BaseListPopupStep<String>(InspectionsBundle.message("inspection.action.export.popup.title"), new String[]{HTML, XML}) {
      @Override
      public PopupStep onChosen(final String selectedValue, final boolean finalChoice) {
        return doFinalStep(() -> exportHTML(Comparing.strEqual(selectedValue, HTML)));
      }
    });
  InspectionResultsView.showPopup(e, popup);
}
 
Example #13
Source File: GraphQLSchemaEndpointsListNode.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) {

    final String introspect = "Get GraphQL Schema from Endpoint (introspection)";
    final String createScratch = "New GraphQL Scratch File (for query, mutation testing)";
    ListPopup listPopup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("Choose Endpoint Action", introspect, createScratch) {

        @Override
        public PopupStep onChosen(String selectedValue, boolean finalChoice) {
            return doFinalStep(() -> {
                if (introspect.equals(selectedValue)) {
                    GraphQLIntrospectionHelper.getService(myProject).performIntrospectionQueryAndUpdateSchemaPathFile(myProject, endpoint);
                } else if (createScratch.equals(selectedValue)) {
                    final String configBaseDir = endpoint.configPackageSet.getConfigBaseDir().getPresentableUrl();
                    final String text = "# " + GRAPHQLCONFIG_COMMENT + configBaseDir + "!" + Optional.ofNullable(projectKey).orElse("") + "\n\nquery ScratchQuery {\n\n}";
                    final VirtualFile scratchFile = ScratchRootType.getInstance().createScratchFile(myProject, "scratch.graphql", GraphQLLanguage.INSTANCE, text);
                    if (scratchFile != null) {
                        FileEditor[] fileEditors = FileEditorManager.getInstance(myProject).openFile(scratchFile, true);
                        for (FileEditor editor : fileEditors) {
                            if (editor instanceof TextEditor) {
                                final JSGraphQLEndpointsModel endpointsModel = ((TextEditor) editor).getEditor().getUserData(JS_GRAPH_QL_ENDPOINTS_MODEL);
                                if (endpointsModel != null) {
                                    endpointsModel.setSelectedItem(endpoint);
                                }
                            }
                        }
                    }
                }
            });
        }
    });
    if (inputEvent instanceof KeyEvent) {
        listPopup.showInFocusCenter();
    } else if (inputEvent instanceof MouseEvent) {
        listPopup.show(new RelativePoint((MouseEvent) inputEvent));
    }
}
 
Example #14
Source File: ArtifactErrorPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ArtifactErrorPanel(final ArtifactEditorImpl artifactEditor) {
  myErrorLabel.setIcon(AllIcons.RunConfigurations.ConfigurationWarning);
  new UiNotifyConnector(myMainPanel, new Activatable.Adapter() {
    @Override
    public void showNotify() {
      if (myErrorText != null) {
        myErrorLabel.setText(myErrorText);
        myErrorText = null;
      }
    }
  });
  myFixButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      if (!myCurrentQuickFixes.isEmpty()) {
        if (myCurrentQuickFixes.size() == 1) {
          performFix(ContainerUtil.getFirstItem(myCurrentQuickFixes, null), artifactEditor);
        }
        else {
          JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationErrorQuickFix>(null, myCurrentQuickFixes) {
            @Nonnull
            @Override
            public String getTextFor(ConfigurationErrorQuickFix value) {
              return value.getActionName();
            }

            @Override
            public PopupStep onChosen(ConfigurationErrorQuickFix selectedValue, boolean finalChoice) {
              performFix(selectedValue, artifactEditor);
              return FINAL_CHOICE;
            }
          }).showUnderneathOf(myFixButton);
        }
      }
    }
  });
  clearError();
}
 
Example #15
Source File: PopupListElementRenderer.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void customizeComponent(JList<? extends E> list, E value, boolean isSelected) {
  ListPopupStep<Object> step = myPopup.getListStep();
  boolean isSelectable = step.isSelectable(value);
  myTextLabel.setEnabled(isSelectable);
  if (step instanceof BaseListPopupStep) {
    Color bg = ((BaseListPopupStep<E>)step).getBackgroundFor(value);
    Color fg = ((BaseListPopupStep<E>)step).getForegroundFor(value);
    if (!isSelected && fg != null) myTextLabel.setForeground(fg);
    if (!isSelected && bg != null) UIUtil.setBackgroundRecursively(myComponent, bg);
    if (bg != null && mySeparatorComponent.isVisible() && myCurrentIndex > 0) {
      E prevValue = list.getModel().getElementAt(myCurrentIndex - 1);
      // separator between 2 colored items shall get color too
      if (Comparing.equal(bg, ((BaseListPopupStep<E>)step).getBackgroundFor(prevValue))) {
        myRendererComponent.setBackground(bg);
      }
    }
  }

  if (step.isMnemonicsNavigationEnabled()) {
    MnemonicNavigationFilter<Object> filter = step.getMnemonicNavigationFilter();
    int pos = filter == null ? -1 : filter.getMnemonicPos(value);
    if (pos != -1) {
      String text = myTextLabel.getText();
      text = text.substring(0, pos) + text.substring(pos + 1);
      myTextLabel.setText(text);
      myTextLabel.setDisplayedMnemonicIndex(pos);
    }
  }
  else {
    myTextLabel.setDisplayedMnemonicIndex(-1);
  }

  if (step.hasSubstep(value) && isSelectable) {
    myNextStepLabel.setVisible(true);
    final boolean isDark = ColorUtil.isDark(UIUtil.getListSelectionBackground());
    myNextStepLabel.setIcon(isSelected ? isDark ? AllIcons.Icons.Ide.NextStepInverted : AllIcons.Icons.Ide.NextStep : AllIcons.Icons.Ide.NextStepGrayed);
  }
  else {
    myNextStepLabel.setVisible(false);
    //myNextStepLabel.setIcon(PopupIcons.EMPTY_ICON);
  }

  setSelected(myComponent, isSelected && isSelectable);
  setSelected(myTextLabel, isSelected && isSelectable);
  setSelected(myNextStepLabel, isSelected && isSelectable);

  if (myShortcutLabel != null) {
    myShortcutLabel.setEnabled(isSelectable);
    myShortcutLabel.setText("");
    if (value instanceof ShortcutProvider) {
      ShortcutSet set = ((ShortcutProvider)value).getShortcut();
      if (set != null) {
        Shortcut shortcut = ArrayUtil.getFirstElement(set.getShortcuts());
        if (shortcut != null) {
          myShortcutLabel.setText("     " + KeymapUtil.getShortcutText(shortcut));
        }
      }
    }
    setSelected(myShortcutLabel, isSelected && isSelectable);
    myShortcutLabel.setForeground(isSelected && isSelectable ? UIManager.getColor("MenuItem.acceleratorSelectionForeground") : UIManager.getColor("MenuItem.acceleratorForeground"));
  }
}
 
Example #16
Source File: PopupFactoryImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public JBPopup createMessage(String text) {
  return createListPopup(new BaseListPopupStep<>(null, text));
}
 
Example #17
Source File: GoalEditor.java    From MavenHelper with Apache License 2.0 4 votes vote down vote up
@NotNull
private ListPopup newListPopup(ListItem[] goalsAsStrings, boolean shortcut) {
	BaseListPopupStep<ListItem> listPopupStep = new ListItemBaseListPopupStep(goalsAsStrings, shortcut);
	return JBPopupFactory.getInstance().createListPopup(listPopupStep);
}
 
Example #18
Source File: AddUsingAction.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
@RequiredUIAccess
public boolean execute()
{
	PsiDocumentManager.getInstance(myProject).commitAllDocuments();

	NamespaceReference firstCount = myElements.size() == 1 ? ContainerUtil.getFirstItem(myElements) : null;

	if(firstCount != null)
	{
		execute0(ContainerUtil.getFirstItem(myElements));
	}
	else
	{
		BaseListPopupStep<NamespaceReference> step = new BaseListPopupStep<NamespaceReference>(DotNetBundle.message("add.using"), myElements.toArray(new NamespaceReference[myElements.size()]))
		{
			@Override
			public Icon getIconFor(NamespaceReference aValue)
			{
				return AllIcons.Nodes.Package;
			}

			@Nonnull
			@Override
			public String getTextFor(NamespaceReference value)
			{
				return formatMessage(value);
			}

			@Override
			@RequiredUIAccess

			public PopupStep onChosen(final NamespaceReference selectedValue, boolean finalChoice)
			{
				execute0(selectedValue);
				return FINAL_CHOICE;
			}
		};

		JBPopupFactory.getInstance().createListPopup(step).showInBestPositionFor(myEditor);
	}

	return true;
}
 
Example #19
Source File: SurroundElementWithAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final LayoutTreeComponent treeComponent = myArtifactEditor.getLayoutTreeComponent();
  final LayoutTreeSelection selection = treeComponent.getSelection();
  final CompositePackagingElement<?> parent = selection.getCommonParentElement();
  if (parent == null) return;
  final PackagingElementNode<?> parentNode = selection.getNodes().get(0).getParentNode();
  if (parentNode == null) return;

  if (!treeComponent.checkCanModifyChildren(parent, parentNode, selection.getNodes())) {
    return;
  }

  final CompositePackagingElementType<?>[] types = PackagingElementFactory.getInstance(e.getProject()).getCompositeElementTypes();
  final List<PackagingElement<?>> selected = selection.getElements();
  if (types.length == 1) {
    surroundWith(types[0], parent, selected, treeComponent);
  }
  else {
    JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<CompositePackagingElementType>("Surround With...", types) {
      @Override
      public Icon getIconFor(CompositePackagingElementType aValue) {
        return TargetAWT.to(aValue.getIcon());
      }

      @Nonnull
      @Override
      public String getTextFor(CompositePackagingElementType value) {
        return value.getPresentableName();
      }

      @Override
      public PopupStep onChosen(final CompositePackagingElementType selectedValue, boolean finalChoice) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            surroundWith(selectedValue, parent, selected, treeComponent);
          }
        });
        return FINAL_CHOICE;
      }
    }).showInBestPositionFor(e.getDataContext());
  }
}
 
Example #20
Source File: ExternalJavaDocAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void showExternalJavadoc(PsiElement element, PsiElement originalElement, String docUrl, DataContext dataContext) {
  DocumentationProvider provider = DocumentationManager.getProviderFromElement(element);
  if (provider instanceof ExternalDocumentationHandler &&
      ((ExternalDocumentationHandler)provider).handleExternal(element, originalElement)) {
    return;
  }
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  final Component contextComponent = dataContext.getData(PlatformDataKeys.CONTEXT_COMPONENT);
  ApplicationManager.getApplication().executeOnPooledThread(() -> {
    List<String> urls;
    if (StringUtil.isEmptyOrSpaces(docUrl)) {
      ThrowableComputable<List<String>,RuntimeException> action = () -> provider.getUrlFor(element, originalElement);
      urls = AccessRule.read(action);
    }
    else {
      urls = Collections.singletonList(docUrl);
    }
    if (provider instanceof ExternalDocumentationProvider && urls != null && urls.size() > 1) {
      for (String url : urls) {
        List<String> thisUrlList = Collections.singletonList(url);
        String doc = ((ExternalDocumentationProvider)provider).fetchExternalDocumentation(project, element, thisUrlList);
        if (doc != null) {
          urls = thisUrlList;
          break;
        }
      }
    }
    final List<String> finalUrls = urls;
    ApplicationManager.getApplication().invokeLater(() -> {
      if (ContainerUtil.isEmpty(finalUrls)) {
        if (element != null && provider instanceof ExternalDocumentationProvider) {
          ExternalDocumentationProvider externalDocumentationProvider = (ExternalDocumentationProvider)provider;
          if (externalDocumentationProvider.canPromptToConfigureDocumentation(element)) {
            externalDocumentationProvider.promptToConfigureDocumentation(element);
          }
        }
      }
      else if (finalUrls.size() == 1) {
        BrowserUtil.browse(finalUrls.get(0));
      }
      else {
        JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("Choose external documentation root",
                                                                                   ArrayUtil.toStringArray(finalUrls)) {
          @Override
          public PopupStep onChosen(final String selectedValue, final boolean finalChoice) {
            BrowserUtil.browse(selectedValue);
            return FINAL_CHOICE;
          }
        }).showInBestPositionFor(DataManager.getInstance().getDataContext(contextComponent));
      }
    }, ModalityState.NON_MODAL);
  });

}
 
Example #21
Source File: TagTextIntention.java    From weex-language-support with MIT License 4 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {

    Set<String> vars = new HashSet<String>();
    boolean isFunc = false;

    if (guessFunction(element)) {
        vars = WeexFileUtil.getAllFunctionNames(element);
        isFunc = true;
    } else {
        vars = WeexFileUtil.getAllVarNames(element).keySet();
        isFunc = false;
    }
    final boolean isFuncFinal = isFunc;

    ListPopup listPopup = JBPopupFactory.getInstance()
            .createListPopup(new BaseListPopupStep<String>(null, vars.toArray(new String[vars.size()])) {

                @Override
                public Icon getIconFor(String value) {
                    return isFuncFinal ? PlatformIcons.FUNCTION_ICON : PlatformIcons.VARIABLE_ICON;
                }

                @Override
                public PopupStep onChosen(final String selectedValue, final boolean finalChoice) {
                    new WriteCommandAction(project) {
                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            editor.getDocument().insertString(editor.getCaretModel().getOffset(), "{{" + selectedValue + "}}");
                            int start = editor.getSelectionModel().getSelectionStart();
                            int end = editor.getSelectionModel().getSelectionEnd();
                            editor.getDocument().replaceString(start, end, "");
                        }
                    }.execute();
                    return super.onChosen(selectedValue, finalChoice);

                }
            });
    listPopup.setMinimumSize(new Dimension(240, -1));
    listPopup.showInBestPositionFor(editor);
}