/**
   * 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 RunContentDescriptor(
      final ExecutionConsole executionConsole,
      final ProcessHandler processHandler,
      final JComponent component,
      final String displayName,
      final Icon icon) {
    myExecutionConsole = executionConsole;
    myProcessHandler = processHandler;
    myComponent = component;
    myDisplayName = displayName;
    myIcon = icon;
    myHelpId =
        myExecutionConsole instanceof HelpIdProvider
            ? ((HelpIdProvider) myExecutionConsole).getHelpId()
            : null;
    DataManager.registerDataProvider(
        myComponent,
        new DataProvider() {

          @Override
          public Object getData(@NonNls final String dataId) {
            if (RunContentManager.RUN_CONTENT_DESCRIPTOR.is(dataId)) {
              return RunContentDescriptor.this;
            }
            return null;
          }
        });
  }
Exemple #4
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);
    }
 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);
  }
Exemple #7
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 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());
  }
 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);
   }
 }
  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;
  }
 @NotNull
 public static ConfigurationContext getFromContext(DataContext dataContext) {
   final ConfigurationContext context = new ConfigurationContext(dataContext);
   final DataManager dataManager = DataManager.getInstance();
   ConfigurationContext sharedContext =
       dataManager.loadFromDataContext(dataContext, SHARED_CONTEXT);
   if (sharedContext == null
       || sharedContext.getLocation() == null
       || context.getLocation() == null
       || !Comparing.equal(
           sharedContext.getLocation().getPsiElement(), context.getLocation().getPsiElement())) {
     sharedContext = context;
     dataManager.saveInDataContext(dataContext, SHARED_CONTEXT, sharedContext);
   }
   return sharedContext;
 }
 @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));
 }
 @Override
 public void execute(Editor editor, DataContext dataContext) {
   Project project =
       PlatformDataKeys.PROJECT.getData(
           DataManager.getInstance().getDataContext(editor.getComponent()));
   FindUtil.replace(project, editor);
 }
 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 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());
   }
 }
Exemple #19
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);
   }
 }
Exemple #22
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());
 }
Exemple #24
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);
  }
    @Override
    public PopupStep onChosen(
        ActionItem actionChoice, boolean finalChoice, final int eventModifiers) {
      if (!actionChoice.isEnabled()) return FINAL_CHOICE;
      final AnAction action = actionChoice.getAction();
      DataManager mgr = DataManager.getInstance();

      final DataContext dataContext =
          myContext != null ? mgr.getDataContext(myContext) : mgr.getDataContext();

      if (action instanceof ActionGroup
          && (!finalChoice || !((ActionGroup) action).canBePerformed(dataContext))) {
        return createActionsStep(
            (ActionGroup) action,
            dataContext,
            myEnableMnemonics,
            true,
            myShowDisabledActions,
            null,
            myContext,
            false,
            myPreselectActionCondition,
            false);
      } else {
        myFinalRunnable =
            new Runnable() {
              @Override
              public void run() {
                action.actionPerformed(
                    new AnActionEvent(
                        null,
                        dataContext,
                        ActionPlaces.UNKNOWN,
                        action.getTemplatePresentation().clone(),
                        ActionManager.getInstance(),
                        eventModifiers));
              }
            };
        return FINAL_CHOICE;
      }
    }
    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);
      }
    }
 ChooseByNamePanel(
     ChooseByNameModel model, boolean checkboxVisible, ChooseByNameItemProvider provider) {
   super(
       MPSCommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()),
       model,
       provider,
       null,
       "",
       false,
       0);
   myCheckboxVisible = checkboxVisible;
 }
Exemple #28
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);
 }
 @Override
 public void dispose() {
   if (myExecutionConsole != null) {
     Disposer.dispose(myExecutionConsole);
     myExecutionConsole = null;
   }
   if (myComponent != null) {
     DataManager.removeDataProvider(myComponent);
     myComponent = null;
   }
   myRestarter = null;
 }