/**
   * Emulates pressing <code>Enter</code> at current caret position.
   *
   * @param editor target editor
   * @param project target project
   * @param shifts two-elements array which is expected to be filled with the following info: 1. The
   *     first element holds added lines number; 2. The second element holds added symbols number;
   */
  private static void emulateEnter(
      @NotNull final Editor editor, @NotNull Project project, int[] shifts) {
    final DataContext dataContext = prepareContext(editor.getComponent(), project);
    int caretOffset = editor.getCaretModel().getOffset();
    Document document = editor.getDocument();
    SelectionModel selectionModel = editor.getSelectionModel();
    int startSelectionOffset = 0;
    int endSelectionOffset = 0;
    boolean restoreSelection = selectionModel.hasSelection();
    if (restoreSelection) {
      startSelectionOffset = selectionModel.getSelectionStart();
      endSelectionOffset = selectionModel.getSelectionEnd();
      selectionModel.removeSelection();
    }
    int textLengthBeforeWrap = document.getTextLength();
    int lineCountBeforeWrap = document.getLineCount();

    DataManager.getInstance()
        .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true);
    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    try {
      Runnable command =
          new Runnable() {
            @Override
            public void run() {
              EditorActionManager.getInstance()
                  .getActionHandler(IdeActions.ACTION_EDITOR_ENTER)
                  .execute(editor, dataContext);
            }
          };
      if (commandProcessor.getCurrentCommand() == null) {
        commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null);
      } else {
        command.run();
      }
    } finally {
      DataManager.getInstance()
          .saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null);
    }
    int symbolsDiff = document.getTextLength() - textLengthBeforeWrap;
    if (restoreSelection) {
      int newSelectionStart = startSelectionOffset;
      int newSelectionEnd = endSelectionOffset;
      if (startSelectionOffset >= caretOffset) {
        newSelectionStart += symbolsDiff;
      }
      if (endSelectionOffset >= caretOffset) {
        newSelectionEnd += symbolsDiff;
      }
      selectionModel.setSelection(newSelectionStart, newSelectionEnd);
    }
    shifts[0] = document.getLineCount() - lineCountBeforeWrap;
    shifts[1] = symbolsDiff;
  }
 @Override
 public boolean isEnabled(Editor editor, DataContext dataContext) {
   Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(editor.getComponent()));
   return project != null;
 }
 public void restart() {
   final Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(myDescriptor.getComponent()));
   if (ExecutorRegistry.getInstance()
       .isStarting(project, myExecutor.getId(), myRunner.getRunnerId())) {
     return;
   }
   try {
     final ExecutionEnvironment old = myEnvironment;
     myRunner.execute(
         myExecutor,
         new ExecutionEnvironment(
             old.getRunProfile(),
             old.getExecutionTarget(),
             project,
             old.getRunnerSettings(),
             old.getConfigurationSettings(),
             myDescriptor,
             old.getRunnerAndConfigurationSettings()));
   } catch (RunCanceledByUserException ignore) {
   } catch (ExecutionException e1) {
     Messages.showErrorDialog(
         project, e1.getMessage(), ExecutionBundle.message("restart.error.message.title"));
   }
 }
  protected GeneralCommandLine createCommandLine() throws ExecutionException {

    return createFromJavaParameters(
        getJavaParameters(),
        CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()),
        true);
  }
Beispiel #5
0
  public void testDevkitCreation() throws InvocationTargetException, InterruptedException {
    Frame frame = MPSDataKeys.FRAME.getData(DataManager.getInstance().getDataContext());
    Assert.assertNotNull("Main frame not found", frame);

    final NewDevKitDialog dialog = new NewDevKitDialog(null);
    dialog.setProject(myCreatedProject);

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            dialog.showDialog();
          }
        });
    flushAWT();

    JTextField nameField = findTextField("Name");
    getHelper().sendString(new StringEventData(this, nameField, "myDev"));
    flushAWT();
    PathField pathField = findPathField("Path");
    boolean correctSuffix = pathField.getPath().endsWith(nameField.getText());
    Assert.assertTrue("Devkit suffix is not added to path", correctSuffix);

    pressButton(dialog, "OK");
    flushAWT();

    final DevKit devKit = dialog.getResult();
    Assert.assertNotNull("Devkit is not created", devKit);

    boolean isImported = myCreatedProject.getProjectModules(DevKit.class).contains(devKit);
    Assert.assertTrue("Devkit is not imported into project", isImported);
  }
 private void installSubcomponents() {
   int decorationStyle = getWindowDecorationStyle();
   if (decorationStyle == JRootPane.FRAME) {
     createActions();
     myMenuBar = createMenuBar();
     if (myRootPane instanceof IdeRootPane) {
       myIdeMenu = new IdeMenuBar(ActionManagerEx.getInstanceEx(), DataManager.getInstance());
       add(myIdeMenu);
     }
     add(myMenuBar);
     createButtons();
     add(myIconifyButton);
     add(myToggleButton);
     add(myCloseButton);
   } else if (decorationStyle == JRootPane.PLAIN_DIALOG
       || decorationStyle == JRootPane.INFORMATION_DIALOG
       || decorationStyle == JRootPane.ERROR_DIALOG
       || decorationStyle == JRootPane.COLOR_CHOOSER_DIALOG
       || decorationStyle == JRootPane.FILE_CHOOSER_DIALOG
       || decorationStyle == JRootPane.QUESTION_DIALOG
       || decorationStyle == JRootPane.WARNING_DIALOG) {
     createActions();
     createButtons();
     add(myCloseButton);
   }
 }
  private void handlePopup(final MouseEvent e) {
    if (e.getClickCount() != 1 || !e.isPopupTrigger()) return;

    if (e.getX() < 0
        || e.getX() >= e.getComponent().getWidth()
        || e.getY() < 0
        || e.getY() >= e.getComponent().getHeight()) return;

    String place = myTabs.getPopupPlace();
    place = place != null ? place : ActionPlaces.UNKNOWN;
    myTabs.myPopupInfo = myInfo;

    final DefaultActionGroup toShow = new DefaultActionGroup();
    if (myTabs.getPopupGroup() != null) {
      toShow.addAll(myTabs.getPopupGroup());
      toShow.addSeparator();
    }

    JBTabsImpl tabs =
        JBTabsImpl.NAVIGATION_ACTIONS_KEY.getData(
            DataManager.getInstance().getDataContext(e.getComponent(), e.getX(), e.getY()));
    if (tabs == myTabs && myTabs.myAddNavigationGroup) {
      toShow.addAll(myTabs.myNavigationActions);
    }

    if (toShow.getChildrenCount() == 0) return;

    myTabs.myActivePopup =
        myTabs.myActionManager.createActionPopupMenu(place, toShow).getComponent();
    myTabs.myActivePopup.addPopupMenuListener(myTabs.myPopupListener);

    myTabs.myActivePopup.addPopupMenuListener(myTabs);
    myTabs.myActivePopup.show(e.getComponent(), e.getX(), e.getY());
  }
  public final IdeFrameImpl allocateFrame(final Project project) {
    LOG.assertTrue(!myProject2Frame.containsKey(project));

    final IdeFrameImpl frame;
    if (myProject2Frame.containsKey(null)) {
      frame = myProject2Frame.get(null);
      myProject2Frame.remove(null);
      myProject2Frame.put(project, frame);
      frame.setProject(project);
    } else {
      frame =
          new IdeFrameImpl(
              (ApplicationInfoEx) ApplicationInfo.getInstance(),
              ActionManagerEx.getInstanceEx(),
              UISettings.getInstance(),
              DataManager.getInstance(),
              ApplicationManager.getApplication());
      final Rectangle bounds = ProjectFrameBounds.getInstance(project).getBounds();
      if (bounds != null) {
        frame.setBounds(bounds);
      } else if (myFrameBounds != null) {
        frame.setBounds(myFrameBounds);
      }
      frame.setExtendedState(myFrameExtendedState);
      frame.setProject(project);
      myProject2Frame.put(project, frame);
      frame.setVisible(true);
    }

    frame.addWindowListener(myActivationListener);

    myEventDispatcher.getMulticaster().frameCreated(frame);

    return frame;
  }
Beispiel #9
0
    public void navigate(final Project project) {
      DefaultPsiElementListCellRenderer renderer = new DefaultPsiElementListCellRenderer();

      final JList list = new JList(myPsiFiles);
      list.setCellRenderer(renderer);

      renderer.installSpeedSearch(list);

      final Runnable runnable =
          new Runnable() {
            public void run() {
              int[] ids = list.getSelectedIndices();
              if (ids == null || ids.length == 0) return;
              Object[] selectedElements = list.getSelectedValues();
              for (Object element : selectedElements) {
                Navigatable descriptor = EditSourceUtil.getDescriptor((PsiElement) element);
                if (descriptor != null && descriptor.canNavigate()) {
                  descriptor.navigate(true);
                }
              }
            }
          };

      final Editor editor =
          PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext());

      new PopupChooserBuilder(list)
          .setTitle("Choose file")
          .setItemChoosenCallback(runnable)
          .createPopup()
          .showInBestPositionFor(editor);
    }
 @Override
 public void showSettings() {
   Content selectedContent = UsageViewManager.getInstance(myProject).getSelectedContent(true);
   JComponent component = selectedContent == null ? null : selectedContent.getComponent();
   FindInProjectManager findInProjectManager = FindInProjectManager.getInstance(myProject);
   findInProjectManager.findInProject(DataManager.getInstance().getDataContext(component));
 }
 protected static DataContext getCurrentEditorDataContext() {
   final DataContext defaultContext = DataManager.getInstance().getDataContext();
   return new DataContext() {
     @Override
     @Nullable
     public Object getData(@NonNls String dataId) {
       if (CommonDataKeys.EDITOR.is(dataId)) {
         return getEditor();
       }
       if (CommonDataKeys.PROJECT.is(dataId)) {
         return getProject();
       }
       if (CommonDataKeys.PSI_FILE.is(dataId)) {
         return getFile();
       }
       if (CommonDataKeys.PSI_ELEMENT.is(dataId)) {
         PsiFile file = getFile();
         if (file == null) return null;
         Editor editor = getEditor();
         if (editor == null) return null;
         return file.findElementAt(editor.getCaretModel().getOffset());
       }
       return defaultContext.getData(dataId);
     }
   };
 }
 @Override
 public void execute(Editor editor, DataContext dataContext) {
   Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(editor.getComponent()));
   FindUtil.replace(project, editor);
 }
 @Override
 public boolean canStartDragging(DnDAction action, Point dragOrigin) {
   if ((action.getActionId() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) return false;
   final Object[] elements = getSelectedElements();
   final PsiElement[] psiElements = getSelectedPSIElements();
   DataContext dataContext = DataManager.getInstance().getDataContext(myTree);
   return psiElements.length > 0 || canDragElements(elements, dataContext, action.getActionId());
 }
  private boolean navigateInRequestedEditor() {
    DataContext ctx = DataManager.getInstance().getDataContext();
    Editor e = NAVIGATE_IN_EDITOR.getData(ctx);
    if (e == null) return false;
    if (FileDocumentManager.getInstance().getFile(e.getDocument()) != myFile) return false;

    navigateIn(e);
    return true;
  }
 @NotNull
 private static FindUsagesOptions getDefaultOptions(@NotNull FindUsagesHandler handler) {
   FindUsagesOptions options =
       handler.getFindUsagesOptions(DataManager.getInstance().getDataContext());
   // by default, scope in FindUsagesOptions is copied from the FindSettings, but we need a default
   // one
   options.searchScope = FindUsagesManager.getMaximalScope(handler);
   return options;
 }
 public static void performTypingAction(Editor editor, char c) {
   EditorActionManager actionManager = EditorActionManager.getInstance();
   if (c == BACKSPACE_FAKE_CHAR) {
     EditorActionHandler actionHandler =
         actionManager.getActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE);
     actionHandler.execute(editor, DataManager.getInstance().getDataContext());
   } else if (c == SMART_ENTER_FAKE_CHAR) {
     EditorActionHandler actionHandler =
         actionManager.getActionHandler(IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT);
     actionHandler.execute(editor, DataManager.getInstance().getDataContext());
   } else if (c == '\n') {
     EditorActionHandler actionHandler =
         actionManager.getActionHandler(IdeActions.ACTION_EDITOR_ENTER);
     actionHandler.execute(editor, DataManager.getInstance().getDataContext());
   } else {
     TypedAction action = actionManager.getTypedAction();
     action.actionPerformed(editor, c, DataManager.getInstance().getDataContext());
   }
 }
Beispiel #17
0
 @Override
 @Nullable
 public Object getData(DataProvider dataProvider) {
   Project project = MPSCommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext());
   if (project == null) {
     IdeFrame[] frames = WindowManager.getInstance().getAllFrames();
     return frames.length == 0 ? null : frames[0];
   }
   return WindowManager.getInstance().getFrame(project);
 }
 private static void restart(@Nullable JComponent component) {
   if (component != null) {
     ExecutionEnvironment environment =
         LangDataKeys.EXECUTION_ENVIRONMENT.getData(
             DataManager.getInstance().getDataContext(component));
     if (environment != null) {
       restart(environment);
     }
   }
 }
 public static void type(char c, @NotNull Editor editor, Project project) {
   if (c == '\n') {
     executeAction(IdeActions.ACTION_EDITOR_ENTER, editor, project);
   } else {
     EditorActionManager actionManager = EditorActionManager.getInstance();
     final DataContext dataContext = DataManager.getInstance().getDataContext();
     TypedAction action = actionManager.getTypedAction();
     action.actionPerformed(editor, c, dataContext);
   }
 }
Beispiel #20
0
 private void selectAll(Component focusOwner) {
   if (focusOwner instanceof TextComponent) {
     ((TextComponent) focusOwner).selectAll();
   } else {
     Editor editor =
         PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext(focusOwner));
     if (editor != null) {
       editor.getSelectionModel().setSelection(0, editor.getDocument().getTextLength());
     }
   }
 }
 private static SearchContext createSearchContext() {
   AnActionEvent event =
       new AnActionEvent(
           null,
           DataManager.getInstance().getDataContext(),
           "",
           new DefaultActionGroup().getTemplatePresentation(),
           ActionManager.getInstance(),
           0);
   return SearchContext.buildFromDataContext(event.getDataContext());
 }
Beispiel #22
0
  protected DialogWrapperPeerImpl(
      @NotNull DialogWrapper wrapper,
      @Nullable Project project,
      boolean canBeParent,
      @NotNull DialogWrapper.IdeModalityType ideModalityType) {
    myWrapper = wrapper;
    myTypeAheadCallback = myWrapper.isTypeAheadEnabled() ? new ActionCallback() : null;
    myWindowManager = null;
    Application application = ApplicationManager.getApplication();
    if (application != null && application.hasComponent(WindowManager.class)) {
      myWindowManager = (WindowManagerEx) WindowManager.getInstance();
    }

    Window window = null;
    if (myWindowManager != null) {

      if (project == null) {
        //noinspection deprecation
        project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext());
      }

      myProject = project;

      window = myWindowManager.suggestParentWindow(project);
      if (window == null) {
        Window focusedWindow = myWindowManager.getMostRecentFocusedWindow();
        if (focusedWindow instanceof IdeFrameImpl) {
          window = focusedWindow;
        }
      }
      if (window == null) {
        IdeFrame[] frames = myWindowManager.getAllProjectFrames();
        for (IdeFrame frame : frames) {
          if (frame instanceof IdeFrameImpl && ((IdeFrameImpl) frame).isActive()) {
            window = (IdeFrameImpl) frame;
            break;
          }
        }
      }
    }

    Window owner;
    if (window != null) {
      owner = window;
    } else {
      if (!isHeadless()) {
        owner = JOptionPane.getRootFrame();
      } else {
        owner = null;
      }
    }

    createDialog(owner, canBeParent, ideModalityType);
  }
 public static void invokeNamedAction(final String actionId) {
   final AnAction action = ActionManager.getInstance().getAction(actionId);
   assertNotNull(action);
   final Presentation presentation = new Presentation();
   @SuppressWarnings("deprecation")
   final DataContext context = DataManager.getInstance().getDataContext();
   final AnActionEvent event =
       new AnActionEvent(null, context, "", presentation, ActionManager.getInstance(), 0);
   action.update(event);
   Assert.assertTrue(presentation.isEnabled());
   action.actionPerformed(event);
 }
Beispiel #24
0
 ChooseByNamePanel(
     ChooseByNameModel model, boolean checkboxVisible, ChooseByNameItemProvider provider) {
   super(
       MPSCommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()),
       model,
       provider,
       null,
       "",
       false,
       0);
   myCheckboxVisible = checkboxVisible;
 }
Beispiel #25
0
  public MacrosDialog(Component parent) {
    super(parent, true);
    MacroManager.getInstance().cacheMacrosPreview(DataManager.getInstance().getDataContext(parent));
    setTitle(IdeBundle.message("title.macros"));
    setOKButtonText(IdeBundle.message("button.insert"));

    myMacrosModel = new DefaultListModel();
    myMacrosList = new JList(myMacrosModel);
    myPreviewTextarea = new JTextArea();

    init();
  }
 @NotNull
 private static DataContext createEditorContext(@NotNull Editor editor) {
   Object e = editor;
   Object hostEditor =
       editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
   Map<String, Object> map =
       ContainerUtil.newHashMap(
           Pair.create(CommonDataKeys.HOST_EDITOR.getName(), hostEditor),
           Pair.createNonNull(CommonDataKeys.EDITOR.getName(), e));
   DataContext parent = DataManager.getInstance().getDataContext(editor.getContentComponent());
   return SimpleDataContext.getSimpleContext(map, parent);
 }
    protected void scrollToSource(Component tree) {
      if (myAbstractTreeBuilder == null) return;
      myAutoscrollFeedback = true;

      Navigatable editSourceDescriptor =
          PlatformDataKeys.NAVIGATABLE.getData(DataManager.getInstance().getDataContext(getTree()));
      if (myFileEditor != null
          && editSourceDescriptor != null
          && editSourceDescriptor.canNavigateToSource()) {
        editSourceDescriptor.navigate(false);
      }
    }
Beispiel #28
0
  private void doInit(
      final List<SModelReference> options, @Nullable List<SModelReference> nonProjectModels) {
    setModal(true);
    myModels.addAll(options);
    if (nonProjectModels != null) {
      myNonProjectModels.addAll(nonProjectModels);
    }

    DataContext dataContext = DataManager.getInstance().getDataContext();
    final Project project = MPSDataKeys.PROJECT.getData(dataContext);

    BaseModelModel goToModelModel =
        new BaseModelModel(project) {
          public NavigationItem doGetNavigationItem(final SModelReference modelReference) {
            return new BaseModelItem(modelReference) {
              public void navigate(boolean requestFocus) {}
            };
          }

          @Override
          public SModelReference[] find(boolean checkboxState) {
            if (checkboxState) {
              return myNonProjectModels.toArray(new SModelReference[myNonProjectModels.size()]);
            } else {
              return myModels.toArray(new SModelReference[myModels.size()]);
            }
          }

          public SModelReference[] find(IScope scope) {
            throw new UnsupportedOperationException("must not be used");
          }

          @Override
          public boolean loadInitialCheckBoxState() {
            return false;
          }
        };

    myChooser =
        MpsPopupFactory.createPanelForPackage(goToModelModel, !myNonProjectModels.isEmpty());
    myChooser.invoke(
        new Callback() {
          public void elementChosen(Object element) {
            if (!myOkDone) {
              myOkDone = true;
              onOk();
            }
          }
        },
        ModalityState.current(),
        myIsMultipleSelection);
  }
  private void showActionsPopup() {
    DataManager.getInstance()
        .getDataContextFromFocus()
        .doWhenDone(
            new AsyncResult.Handler<DataContext>() {
              public void run(DataContext context) {
                QuickActionProvider provider = QuickActionProvider.KEY.getData(context);
                if (provider == null) return;

                List<AnAction> actions = provider.getActions(true);
                if (actions != null && actions.size() > 0) {
                  DefaultActionGroup group = new DefaultActionGroup();
                  for (AnAction each : actions) {
                    group.add(each);
                  }

                  boolean firstParent = true;
                  Component eachParent = provider.getComponent().getParent();
                  while (eachParent != null) {
                    if (eachParent instanceof QuickActionProvider) {
                      QuickActionProvider eachProvider = (QuickActionProvider) eachParent;
                      if (firstParent) {
                        group.addSeparator();
                        firstParent = false;
                      }
                      List<AnAction> eachActionList = eachProvider.getActions(false);
                      if (eachActionList.size() > 0) {
                        group.add(new Group(eachActionList, eachProvider.getName()));
                      }
                      if (eachProvider.isCycleRoot()) break;
                    }
                    eachParent = eachParent.getParent();
                  }

                  JBPopupFactory.getInstance()
                      .createActionGroupPopup(
                          null,
                          group,
                          context,
                          JBPopupFactory.ActionSelectionAid.ALPHA_NUMBERING,
                          true,
                          new Runnable() {
                            public void run() {
                              myActiveProvider = null;
                            }
                          },
                          -1)
                      .showInFocusCenter();
                }
              }
            });
  }
  private void chooseRootAndAnnotateExternally(
      @NotNull final PsiModifierListOwner listOwner,
      @NotNull final String annotationFQName,
      @NotNull final PsiFile fromFile,
      @NotNull final Project project,
      @NotNull final String packageName,
      final VirtualFile virtualFile,
      @NotNull VirtualFile[] virtualFiles,
      final PsiNameValuePair[] value) {
    if (virtualFiles.length > 1) {
      JBPopupFactory.getInstance()
          .createListPopup(
              new BaseListPopupStep<VirtualFile>("Annotation Roots", virtualFiles) {
                @Override
                public PopupStep onChosen(
                    @NotNull final VirtualFile file, final boolean finalChoice) {
                  annotateExternally(
                      file,
                      listOwner,
                      project,
                      packageName,
                      virtualFile,
                      annotationFQName,
                      fromFile,
                      value);
                  return FINAL_CHOICE;
                }

                @NotNull
                @Override
                public String getTextFor(@NotNull final VirtualFile value) {
                  return value.getPresentableUrl();
                }

                @Override
                public Icon getIconFor(final VirtualFile aValue) {
                  return ICON;
                }
              })
          .showInBestPositionFor(DataManager.getInstance().getDataContext());
    } else {
      annotateExternally(
          virtualFiles[0],
          listOwner,
          project,
          packageName,
          virtualFile,
          annotationFQName,
          fromFile,
          value);
    }
  }