Java Code Examples for com.intellij.openapi.util.Disposer

The following are top voted examples for showing how to use com.intellij.openapi.util.Disposer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: idea-php-class-templates   File: PhpNewClassDialog.java   View source code 6 votes vote down vote up
public PhpNewClassDialog(@NotNull Project project, @Nullable PsiDirectory directory) {
    super(project);

    this.myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);

    Disposer.register(this.getDisposable(), new Disposable() {
        public void dispose() {
            PhpNewClassDialog.this.myAlarm.cancelAllRequests();
            PhpNewClassDialog.this.myDisposed = true;
        }
    });

    this.myProperties = new Properties();

    this.myProject = project;
    this.myDirectory = directory;

    init();
}
 
Example 2
Project: educational-plugin   File: StudyStepicUserWidget.java   View source code 6 votes vote down vote up
public void showComponent(RelativePoint point) {
  myPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(this, this)
    .setRequestFocus(true)
    .setCancelOnOtherWindowOpen(true)
    .setCancelOnClickOutside(true)
    .setShowBorder(true)
    .createPopup();

  Disposer.register(ApplicationManager.getApplication(), new Disposable() {
    @Override
    public void dispose() {
      Disposer.dispose(myPopup);
    }
  });

  myPopup.show(point);
}
 
Example 3
Project: educational-plugin   File: StudyToolWindowFactory.java   View source code 6 votes vote down vote up
@Override
public void createToolWindowContent(@NotNull final Project project, @NotNull final ToolWindow toolWindow) {
  toolWindow.setIcon(EducationalCoreIcons.TaskDescription);
  final Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course != null) {
    final StudyToolWindow studyToolWindow;
    if (StudyUtils.hasJavaFx() && StudySettings.getInstance().shouldUseJavaFx()) {
      studyToolWindow = new StudyJavaFxToolWindow();
    }
    else {
      studyToolWindow = new StudySwingToolWindow();
    }
    studyToolWindow.init(project, true);
    final ContentManager contentManager = toolWindow.getContentManager();
    final Content content = contentManager.getFactory().createContent(studyToolWindow, null, false);
    contentManager.addContent(content);
    Disposer.register(project, studyToolWindow);
  }
}
 
Example 4
Project: intellij-ce-playground   File: SliceManager.java   View source code 6 votes vote down vote up
public void runInterruptibly(@NotNull ProgressIndicator progress,
                             @NotNull Runnable onCancel,
                             @NotNull Runnable runnable) throws ProcessCanceledException {
  Disposable disposable = addPsiListener(progress);
  try {
    progress.checkCanceled();
    ProgressManager.getInstance().executeProcessUnderProgress(runnable, progress);
  }
  catch (ProcessCanceledException e) {
    progress.cancel();
    //reschedule for later
    onCancel.run();
    throw e;
  }
  finally {
    Disposer.dispose(disposable);
  }
}
 
Example 5
Project: fastdex   File: DeviceChooserDialog.java   View source code 6 votes vote down vote up
public DeviceChooserDialog(@NotNull AndroidFacet facet,
                           @NotNull IAndroidTarget projectTarget,
                           boolean multipleSelection,
                           @Nullable String[] selectedSerials,
                           @Nullable Predicate<IDevice> filter) {
    super(facet.getModule().getProject(), true);
    setTitle(AndroidBundle.message("choose.device.dialog.title"));

    getOKAction().setEnabled(false);

    myDeviceChooser = new DeviceChooser(multipleSelection, getOKAction(), facet, projectTarget, filter);
    Disposer.register(myDisposable, myDeviceChooser);
    myDeviceChooser.addListener(new DeviceChooserListener() {
        @Override
        public void selectedDevicesChanged() {
            updateOkButton();

            if (deviceChooserListener != null) {
                deviceChooserListener.selectedDevicesChanged();
            }
        }
    });

    init();
    myDeviceChooser.init(selectedSerials);
}
 
Example 6
Project: intellij-ce-playground   File: IdeStatusBarImpl.java   View source code 6 votes vote down vote up
@Override
public StatusBar createChild() {
  final IdeStatusBarImpl bar = new IdeStatusBarImpl(this);
  myChildren.add(bar);
  Disposer.register(bar, new Disposable() {
    @Override
    public void dispose() {
      myChildren.remove(bar);
    }
  });

  for (String eachId : myOrderedWidgets) {
    WidgetBean eachBean = myWidgetMap.get(eachId);
    if (eachBean.widget instanceof StatusBarWidget.Multiframe) {
      StatusBarWidget copy = ((StatusBarWidget.Multiframe)eachBean.widget).copy();
      bar.addWidget(copy, eachBean.position);
    }
  }

  return bar;
}
 
Example 7
Project: intellij-ce-playground   File: AndroidTestCase.java   View source code 6 votes vote down vote up
public void registerAllowedRoots(List<String> roots, @NotNull Disposable disposable) {
  final List<String> newRoots = new ArrayList<String>(roots);
  newRoots.removeAll(myAllowedRoots);

  final String[] newRootsArray = ArrayUtil.toStringArray(newRoots);
  VfsRootAccess.allowRootAccess(newRootsArray);
  myAllowedRoots.addAll(newRoots);

  Disposer.register(disposable, new Disposable() {
    @Override
    public void dispose() {
      VfsRootAccess.disallowRootAccess(newRootsArray);
      myAllowedRoots.removeAll(newRoots);
    }
  });
}
 
Example 8
Project: intellij-ce-playground   File: AntExplorer.java   View source code 6 votes vote down vote up
public void dispose() {
  final KeymapListener listener = myKeymapListener;
  if (listener != null) {
    myKeymapListener = null;
    listener.stopListen();
  }

  final AntExplorerTreeBuilder builder = myBuilder;
  if (builder != null) {
    Disposer.dispose(builder);
    myBuilder = null;
  }

  final Tree tree = myTree;
  if (tree != null) {
    ToolTipManager.sharedInstance().unregisterComponent(tree);
    for (KeyStroke keyStroke : tree.getRegisteredKeyStrokes()) {
      tree.unregisterKeyboardAction(keyStroke);
    }
    myTree = null;
  }

  myProject = null;
  myConfig = null;
}
 
Example 9
Project: intellij-ce-playground   File: FrameWrapper.java   View source code 6 votes vote down vote up
public void dispose() {
  if (myDisposing) return;
  myDisposing = true;

  MouseGestureManager.getInstance().remove(this);

  if (myShown && myDimensionKey != null) {
    WindowStateService.getInstance().saveStateFor(myProject, myDimensionKey, this);
  }

  Disposer.dispose(FrameWrapper.this);
  myDatas.clear();
  myProject = null;
  myPreferedFocus = null;

  if (myFocusTrackback != null) {
    myFocusTrackback.restoreFocus();
  }
  if (myComponent != null && myFocusWatcher != null) {
    myFocusWatcher.deinstall(myComponent);
  }
  myFocusWatcher = null;
  myFocusedCallback = null;

  super.dispose();
}
 
Example 10
Project: intellij-ce-playground   File: MergeTool.java   View source code 6 votes vote down vote up
private static void showDialog(MergeRequestImpl data) {
  if (LOG.isDebugEnabled()) {
    LOG.debug("MergeTool - dialog");
  }
  DialogBuilder builder = new DialogBuilder(data.getProject());
  builder.setDimensionServiceKey(data.getGroupKey());
  builder.setTitle(data.getWindowTitle());
  Disposable parent = Disposer.newDisposable();
  builder.addDisposable(parent);
  MergePanel2 mergePanel = createMergeComponent(data, builder, parent);
  builder.setCenterPanel(mergePanel.getComponent());
  builder.setPreferredFocusComponent(mergePanel.getPreferredFocusedComponent());
  builder.setHelpId(data.getHelpId());
  int result = builder.show();
  MergeRequestImpl lastData = mergePanel.getMergeRequest();
  if (lastData != null) {
    lastData.setResult(result);
  }
}
 
Example 11
Project: intellij-ce-playground   File: UsageViewTest.java   View source code 6 votes vote down vote up
public void testUsageViewDoesNotHoldPsiFilesOrDocuments() throws Exception {
  PsiFile psiFile = myFixture.addFileToProject("X.java", "public class X{} //iuggjhfg");
  Usage[] usages = new Usage[100];
  for (int i = 0; i < usages.length; i++) {
    usages[i] = createUsage(psiFile,i);
  }

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, usages, new UsageViewPresentation(), null);

  Disposer.register(getTestRootDisposable(), usageView);

  ((EncodingManagerImpl)EncodingManager.getInstance()).clearDocumentQueue();
  FileDocumentManager.getInstance().saveAllDocuments();
  UIUtil.dispatchAllInvocationEvents();

  LeakHunter.checkLeak(usageView, PsiFileImpl.class);
  LeakHunter.checkLeak(usageView, Document.class);
}
 
Example 12
Project: intellij-ce-playground   File: TodoPanel.java   View source code 6 votes vote down vote up
/**
 * @param currentFileMode if <code>true</code> then view doesn't have "Group By Packages" and "Flatten Packages"
 *                        actions.
 */
TodoPanel(Project project, TodoPanelSettings settings, boolean currentFileMode, Content content) {
  super(false, true);

  myProject = project;
  mySettings = settings;
  myCurrentFileMode = currentFileMode;
  myContent = content;

  DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode());
  myTree = new Tree(model);
  myTreeExpander = new MyTreeExpander();
  myOccurenceNavigator = new MyOccurenceNavigator();
  initUI();
  myTodoTreeBuilder = createTreeBuilder(myTree, model, myProject);
  Disposer.register(myProject, myTodoTreeBuilder);
  updateTodoFilter();
  myTodoTreeBuilder.setShowPackages(mySettings.arePackagesShown);
  myTodoTreeBuilder.setShowModules(mySettings.areModulesShown);
  myTodoTreeBuilder.setFlattenPackages(mySettings.areFlattenPackages);

  myVisibilityWatcher = new MyVisibilityWatcher();
  myVisibilityWatcher.install(this);
}
 
Example 13
Project: intellij-ce-playground   File: EditorView.java   View source code 6 votes vote down vote up
public EditorView(EditorImpl editor) {
  myFontRenderContext = createFontRenderContext();
  myEditor = editor;
  myDocument = editor.getDocument();
  
  myPainter = new EditorPainter(this);
  myMapper = new EditorCoordinateMapper(this);
  mySizeManager = new EditorSizeManager(this);
  myTextLayoutCache = new TextLayoutCache(this);
  myLogicalPositionCache = new LogicalPositionCache(this);
  myTabFragment = new TabFragment(this);
  
  Disposer.register(this, myLogicalPositionCache);
  Disposer.register(this, myTextLayoutCache);
  Disposer.register(this, mySizeManager);
}
 
Example 14
Project: intellij-ce-playground   File: AbstractTreeNode.java   View source code 6 votes vote down vote up
protected boolean acceptFilter(@Nullable Pair<PackageSetBase, NamedScopesHolder> filter, boolean showOnlyFilteredItems) {
  boolean apply = false;
  if (children != null && filter != null) {
    for (Iterator it = children.iterator(); it.hasNext(); ) {
      AbstractTreeNode node = (AbstractTreeNode)it.next();
      if (node.acceptFilter(filter, showOnlyFilteredItems)) {
        apply = true;
      }
      else if (showOnlyFilteredItems) {
        if (node instanceof Disposable) {
          Disposer.dispose((Disposable)node);
        }
        it.remove();
      }
    }
    applyFilter(apply);
  }
  return apply;
}
 
Example 15
Project: intellij-ce-playground   File: ExecutionHelper.java   View source code 6 votes vote down vote up
private static void openMessagesView(@NotNull final ErrorViewPanel errorTreeView,
                                     @NotNull final Project myProject,
                                     @NotNull final String tabDisplayName) {
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(myProject, new Runnable() {
    @Override
    public void run() {
      final MessageView messageView = ServiceManager.getService(myProject, MessageView.class);
      final Content content = ContentFactory.SERVICE.getInstance().createContent(errorTreeView, tabDisplayName, true);
      messageView.getContentManager().addContent(content);
      Disposer.register(content, errorTreeView);
      messageView.getContentManager().setSelectedContent(content);
      removeContents(content, myProject, tabDisplayName);
    }
  }, "Open message view", null);
}
 
Example 16
Project: intellij-ce-playground   File: DelayedDocumentWatcher.java   View source code 6 votes vote down vote up
public void activate() {
  if (myConnection == null) {
    myListenerDisposable = Disposer.newDisposable();
    Disposer.register(myProject, myListenerDisposable);
    EditorFactory.getInstance().getEventMulticaster().addDocumentListener(myListener, myListenerDisposable);
    myConnection = ApplicationManager.getApplication().getMessageBus().connect(myProject);
    myConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() {
      @Override
      public void beforeAllDocumentsSaving() {
        myDocumentSavingInProgress = true;
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            myDocumentSavingInProgress = false;
          }
        }, ModalityState.any());
      }
    });
  }
}
 
Example 17
Project: intellij-ce-playground   File: CodeStyleAbstractPanel.java   View source code 6 votes vote down vote up
protected CodeStyleAbstractPanel(@Nullable Language defaultLanguage,
                                 @Nullable CodeStyleSettings currentSettings,
                                 @NotNull CodeStyleSettings settings)
{
  Disposer.register(this, myDiffCalculator);
  myCurrentSettings = currentSettings;
  mySettings = settings;
  myDefaultLanguage = defaultLanguage;
  myEditor = createEditor();

  if (myEditor != null) {
    myUpdateAlarm.setActivationComponent(myEditor.getComponent());
  }
  myUserActivityWatcher.addUserActivityListener(new UserActivityListener() {
    @Override
    public void stateChanged() {
      somethingChanged();
    }
  });

  updatePreview(true);
}
 
Example 18
Project: intellij-ce-playground   File: XDebuggerManagerImpl.java   View source code 6 votes vote down vote up
public void removeSession(@NotNull final XDebugSessionImpl session) {
  XDebugSessionTab sessionTab = session.getSessionTab();
  mySessions.remove(session.getDebugProcess().getProcessHandler());
  if (sessionTab != null) {
    RunContentDescriptor descriptor = sessionTab.getRunContentDescriptor();
    if (descriptor != null) {
      // in test-mode RunContentWithExecutorListener.contentRemoved events are not sent (see RunContentManagerImpl.showRunContent)
      // so we make sure the mySessions and mySessionData are cleared correctly when session is disposed
      Disposer.register(descriptor, new Disposable() {
        @Override
        public void dispose() {
          mySessions.remove(session.getDebugProcess().getProcessHandler());
        }
      });
    }

    if (!myProject.isDisposed() && !ApplicationManager.getApplication().isUnitTestMode() && XDebuggerSettingsManager.getInstanceImpl().getGeneralSettings().isHideDebuggerOnProcessTermination()) {
      ExecutionManager.getInstance(myProject).getContentManager().hideRunContent(DefaultDebugExecutor.getDebugExecutorInstance(), descriptor);
    }
  }
  if (myActiveSession.compareAndSet(session, null)) {
    onActiveSessionChanged();
  }
}
 
Example 19
Project: intellij-ce-playground   File: ToDoTreeStructureTest.java   View source code 6 votes vote down vote up
public void testToDo1() throws Exception {
   AllTodosTreeBuilder all = new AllTodosTreeBuilder(new Tree(), new DefaultTreeModel(new DefaultMutableTreeNode()), myProject);
   all.init();

   AbstractTreeStructure structure = all.getTreeStructure();
   ((TodoTreeStructure)structure).setFlattenPackages(true);
   ProjectViewTestUtil.assertStructureEqual(structure,
                                            "Root\n" +
                                            " Summary\n" +
                                            "  package2 toDoFileCount=1,toDoItemCount=2\n" +
                                            "   JavaClass.java\n" +
                                            "    Item: (62,78)\n" +
                                            "    Item: (145,162)\n",
                                            myPrintInfo);

   checkOccurrences(all, new String[]{"Item: (62,78)", "Item: (145,162)"});
   Disposer.dispose(all);
}
 
Example 20
Project: intellij-ce-playground   File: BrowseRepositoryAction.java   View source code 6 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  Project project = e.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    RepositoryBrowserDialog dialog = new RepositoryBrowserDialog(ProjectManager.getInstance().getDefaultProject());
    dialog.show();
  }
  else {
    ToolWindowManager manager = ToolWindowManager.getInstance(project);
    ToolWindow w = manager.getToolWindow(REPOSITORY_BROWSER_TOOLWINDOW);
    if (w == null) {
      RepositoryToolWindowPanel component = new RepositoryToolWindowPanel(project);
      w = manager.registerToolWindow(REPOSITORY_BROWSER_TOOLWINDOW, true, ToolWindowAnchor.BOTTOM, project, true);
      final Content content = ContentFactory.SERVICE.getInstance().createContent(component, "", false);
      Disposer.register(content, component);
      w.getContentManager().addContent(content);
    }
    w.show(null);
    w.activate(null);
  }
}
 
Example 21
Project: intellij-ce-playground   File: LineStatusTrackerDrawing.java   View source code 6 votes vote down vote up
private static void installEditorHighlighters(@NotNull Range range,
                                              @NotNull Editor editor,
                                              @NotNull LineStatusTracker tracker,
                                              @Nullable List<DiffFragment> wordDiff,
                                              @NotNull Disposable parentDisposable) {
  if (wordDiff == null) return;
  final List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();

  int currentStartShift = tracker.getCurrentTextRange(range).getStartOffset();
  for (DiffFragment fragment : wordDiff) {
    int currentStart = currentStartShift + fragment.getStartOffset2();
    int currentEnd = currentStartShift + fragment.getEndOffset2();
    TextDiffType type = getDiffType(fragment);

    highlighters.addAll(DiffDrawUtil.createInlineHighlighter(editor, currentStart, currentEnd, type));
  }

  Disposer.register(parentDisposable, new Disposable() {
    @Override
    public void dispose() {
      for (RangeHighlighter highlighter : highlighters) {
        highlighter.dispose();
      }
    }
  });
}
 
Example 22
Project: intellij-ce-playground   File: PythonSdkDetailsStep.java   View source code 6 votes vote down vote up
private void optionSelected(final String selectedValue) {
  if (!MORE.equals(selectedValue) && myMore != null)
    Disposer.dispose(myMore.getDisposable());
  if (LOCAL.equals(selectedValue)) {
    createLocalSdk();
  }
  else if (REMOTE.equals(selectedValue)) {
    createRemoteSdk();
  }
  else if (VIRTUALENV.equals(selectedValue)) {
    createVirtualEnvSdk();
  }
  else if (CONDA.equals(selectedValue)) {
    createCondaEnvSdk();
  }
  else if (myMore != null) {
    myMore.show();
  }
}
 
Example 23
Project: intellij-ce-playground   File: SocketLock.java   View source code 6 votes vote down vote up
public void dispose() {
  log("enter: dispose()");

  BuiltInServer server = myServer;
  if (server == null) return;

  try {
    Disposer.dispose(server);
  }
  finally {
    try {
      underLocks(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          FileUtil.delete(new File(myConfigPath, PORT_FILE));
          FileUtil.delete(new File(mySystemPath, PORT_FILE));
          return null;
        }
      });
    }
    catch (Exception e) {
      Logger.getInstance(SocketLock.class).warn(e);
    }
  }
}
 
Example 24
Project: intellij-ce-playground   File: ActionMenu.java   View source code 6 votes vote down vote up
private UsabilityHelper(Component component, @NotNull Disposable disposable) {
  Disposer.register(disposable, this);
  myCallbackAlarm = new SingleAlarm(new Runnable() {
    @Override
    public void run() {
      Disposer.dispose(myCallbackAlarm);
      myCallbackAlarm = null;
      if (myEventToRedispatch != null) {
        IdeEventQueue.getInstance().dispatchEvent(myEventToRedispatch);
      }
    }
  }, 50, this);
  myComponent = component;
  PointerInfo info = MouseInfo.getPointerInfo();
  myLastMousePoint = info != null ? info.getLocation() : null;
  if (myLastMousePoint != null) {
    Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.COMPONENT_EVENT_MASK);
    IdeEventQueue.getInstance().addDispatcher(this, this);
  }
}
 
Example 25
Project: intellij-ce-playground   File: ZipAndQueue.java   View source code 6 votes vote down vote up
public ZipAndQueue(final Project project, final int interval, final String title, final Runnable runnable) {
  final int correctedInterval = interval <= 0 ? 300 : interval;
  myZipperUpdater = new ZipperUpdater(correctedInterval, project);
  myQueue = new BackgroundTaskQueue(project, title);
  myInZipper = new Runnable() {
    @Override
    public void run() {
      myQueue.run(myInvokedOnQueue);
    }
  };
  myInvokedOnQueue = new Task.Backgroundable(project, title, false, BackgroundFromStartOption.getInstance()) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      runnable.run();
    }
  };
  Disposer.register(project, new Disposable() {
    @Override
    public void dispose() {
      myZipperUpdater.stop();
    }
  });
}
 
Example 26
Project: logviewer   File: LogSourceManager.java   View source code 5 votes vote down vote up
/**
 * Initiailzes the {@link LogSourceManager} with the given project, context and listener
 *
 * @param project                  Project instance
 * @param deviceContext            DeviceContext to notify about source changes
 * @param logSourceManagerListener Listener for notifications
 */
public LogSourceManager(Project project, DeviceContext deviceContext, LogSourceManagerListener logSourceManagerListener) {
    this.project = project;
    this.deviceContext = deviceContext;
    this.deviceLogSourcesMap = new ConcurrentHashMap<>();
    this.fileLogSourcesMap = new ConcurrentHashMap<>();
    this.logSourceManagerListener = logSourceManagerListener;
    observeForDeviceChange();
    Disposer.register(project, this);
}
 
Example 27
Project: intellij-postfix-templates   File: CptPluginConfigurable.java   View source code 5 votes vote down vote up
@Override
public void disposeUIResources() {
	if (form != null) {
		Disposer.dispose(form);
	}
	form = null;
}
 
Example 28
Project: intellij-bpmn-editor   File: BPMNPaletteToolWindowManager.java   View source code 5 votes vote down vote up
protected BPMNPaletteToolWindowManager(Project project, FileEditorManager fileEditorManager) {
    super(project);

    myFileEditorManager = fileEditorManager;
    palette = new BPMNPalette(project);
    Disposer.register(myProject, palette);
}
 
Example 29
Project: hybris-integration-intellij-idea-plugin   File: HybrisProjectApplicationComponent.java   View source code 5 votes vote down vote up
@Override
public void initComponent() {
    disposable = Disposer.newDisposable();
    Disposer.register(disposable, projectManagerListener);

    ApplicationManager.getApplication().getMessageBus().connect(disposable).subscribe(
        ProjectManager.TOPIC,
        projectManagerListener
    );
}
 
Example 30
Project: educational-plugin   File: StudyShowHintAction.java   View source code 5 votes vote down vote up
private static void showHintPopUp(Project project, StudyState studyState, Editor editor, StudyToolWindow hintComponent) {
  final JBPopup popup =
    JBPopupFactory.getInstance().createComponentPopupBuilder(hintComponent, hintComponent)
      .setDimensionServiceKey(project, "StudyHint", false)
      .setResizable(true)
      .setMovable(true)
      .setRequestFocus(true)
      .setTitle(studyState.getTask().getName())
      .createPopup();
  Disposer.register(popup, hintComponent);

  final Component focusOwner = IdeFocusManager.getInstance(project).getFocusOwner();
  DataContext dataContext = DataManager.getInstance().getDataContext(focusOwner);
  PopupPositionManager.positionPopupInBestPosition(popup, editor, dataContext);
}
 
Example 31
Project: educational-plugin   File: CCShowPreview.java   View source code 5 votes vote down vote up
private static void showPreviewDialog(@NotNull Project project, @NotNull TaskFile taskFile) {
  final FrameWrapper showPreviewFrame = new FrameWrapper(project);
  final LightVirtualFile userFile = new LightVirtualFile(taskFile.name, taskFile.text);
  showPreviewFrame.setTitle(userFile.getName());
  LabeledEditor labeledEditor = new LabeledEditor(null);
  final EditorFactory factory = EditorFactory.getInstance();
  Document document = FileDocumentManager.getInstance().getDocument(userFile);
  if (document == null) {
    return;
  }
  final EditorEx createdEditor = (EditorEx)factory.createEditor(document, project, userFile, true);
  Disposer.register(project, () -> factory.releaseEditor(createdEditor));
  for (AnswerPlaceholder answerPlaceholder : taskFile.getActivePlaceholders()) {
    if (answerPlaceholder.getActiveSubtaskInfo().isNeedInsertText()) {
      answerPlaceholder.setLength(answerPlaceholder.getTaskText().length());
    }
    Integer minIndex = Collections.min(answerPlaceholder.getSubtaskInfos().keySet());
    answerPlaceholder.setUseLength(minIndex >= answerPlaceholder.getActiveSubtaskIndex());
    EduAnswerPlaceholderPainter.drawAnswerPlaceholder(createdEditor, answerPlaceholder, JBColor.BLUE);
  }
  JPanel header = new JPanel();
  header.setLayout(new BoxLayout(header, BoxLayout.Y_AXIS));
  header.setBorder(new EmptyBorder(10, 10, 10, 10));
  header.add(new JLabel("Read-only preview."));
  String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
  header.add(new JLabel(String.format("Created %s.", timeStamp)));
  JComponent editorComponent = createdEditor.getComponent();
  labeledEditor.setComponent(editorComponent, header);
  createdEditor.setCaretVisible(false);
  createdEditor.setCaretEnabled(false);
  showPreviewFrame.setComponent(labeledEditor);
  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    showPreviewFrame.setSize(new Dimension(500, 500));
    showPreviewFrame.show();
  }
}
 
Example 32
Project: intellij-plugin   File: SeedStackStructure.java   View source code 5 votes vote down vote up
SeedStackStructure(Project project, SimpleTree tree) {
    this.project = project;

    tree.setRootVisible(true);
    tree.setShowsRootHandles(true);

    rootNode = new RootNode();
    treeBuilder = new SimpleTreeBuilder(tree, (DefaultTreeModel) tree.getModel(), this, null);
    Disposer.register(this.project, treeBuilder);

    treeBuilder.initRoot();
}
 
Example 33
Project: manifold-ij   File: HotSwapComponent.java   View source code 5 votes vote down vote up
@Override
public void sessionDetached( DebuggerSession session )
{
  if( !getHotSwappableDebugSessions().isEmpty() )
  {
    return;
  }

  final MessageBusConnection conn = _conn;
  if( conn != null )
  {
    Disposer.dispose( conn );
    _conn = null;
  }
}
 
Example 34
Project: GravSupport   File: GravModuleBuilder.java   View source code 5 votes vote down vote up
@Override
@Nullable
public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) {
    setProject(context.getProject());
    GravIntroWizardStep step = new GravIntroWizardStep(this);
    Disposer.register(parentDisposable, step);
    return step;
}
 
Example 35
Project: MultiHighlight   File: ColorPreviewPanel.java   View source code 5 votes vote down vote up
public ColorPreviewPanel() {
    final EditorFactory editorFactory = EditorFactory.getInstance();
    myEditor = (EditorEx) editorFactory.createViewer(editorFactory.createDocument(""));

    final EditorSettings settings = myEditor.getSettings();
    settings.setLineNumbersShown(true);
    settings.setWhitespacesShown(true);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setFoldingOutlineShown(false);
    settings.setAdditionalColumnsCount(0);
    settings.setAdditionalLinesCount(0);
    settings.setRightMarginShown(true);
    settings.setRightMargin(60);

    /** {@link FontEditorPreview#installTrafficLights(EditorEx)} */
    TrafficLightRenderer renderer = new TrafficLightRenderer(null, null, null) {

        private final DaemonCodeAnalyzerStatus status = new DaemonCodeAnalyzerStatus();

        {
            status.errorAnalyzingFinished = true;
            status.errorCount = new int[]{ 0 };
        }

        @NotNull
        @Override
        protected DaemonCodeAnalyzerStatus getDaemonCodeAnalyzerStatus(
                @NotNull SeverityRegistrar severityRegistrar) {
            return status;
        }
    };

    Disposer.register((Disposable) myEditor.getCaretModel(), renderer);
    EditorMarkupModel markupModel = (EditorMarkupModel) myEditor.getMarkupModel();
    markupModel.setErrorStripeRenderer(renderer);
    markupModel.setErrorStripeVisible(true);
}
 
Example 36
Project: intellij-ce-playground   File: BaseTestsOutputConsoleView.java   View source code 5 votes vote down vote up
public BaseTestsOutputConsoleView(final TestConsoleProperties properties, final AbstractTestProxy unboundOutputRoot) {
  myProperties = properties;

  myConsole = new TestsConsoleBuilderImpl(properties.getProject(),
                                          myProperties.getScope(),
                                          !properties.isEditable(),
                                          properties.isUsePredefinedMessageFilter()).getConsole();
  myPrinter = new TestsOutputConsolePrinter(this, properties, unboundOutputRoot);
  myProperties.setConsole(this);

  Disposer.register(this, myProperties);
  Disposer.register(this, myConsole);
}
 
Example 37
Project: intellij-ce-playground   File: HgVcs.java   View source code 5 votes vote down vote up
@Override
public void deactivate() {
  if (myHgRemoteStatusUpdater != null) {
    myHgRemoteStatusUpdater.deactivate();
    myHgRemoteStatusUpdater = null;
  }
  if (myStatusWidget != null) {
    myStatusWidget.deactivate();
    myStatusWidget = null;
  }
  if (myIncomingWidget != null) {
    myIncomingWidget.deactivate();
    myIncomingWidget = null;
  }
  if (myOutgoingWidget != null) {
    myOutgoingWidget.deactivate();
    myOutgoingWidget = null;
  }
  if (messageBusConnection != null) {
    messageBusConnection.disconnect();
  }

  if (myVFSListener != null) {
    Disposer.dispose(myVFSListener);
    myVFSListener = null;
  }

  super.deactivate();
}
 
Example 38
Project: intellij-ce-playground   File: CoreCommandProcessor.java   View source code 5 votes vote down vote up
@Override
public void addCommandListener(@NotNull final CommandListener listener, @NotNull Disposable parentDisposable) {
  addCommandListener(listener);
  Disposer.register(parentDisposable, new Disposable() {
    @Override
    public void dispose() {
      removeCommandListener(listener);
    }
  });
}
 
Example 39
Project: intellij-ce-playground   File: IdeStatusBarImpl.java   View source code 5 votes vote down vote up
@Override
public void addWidget(@NotNull final StatusBarWidget widget, @NotNull String anchor, @NotNull final Disposable parentDisposable) {
  addWidget(widget, anchor);
  Disposer.register(parentDisposable, new Disposable() {
    @Override
    public void dispose() {
      removeWidget(widget.ID());
    }
  });
}
 
Example 40
Project: intellij-ce-playground   File: LineStatusTrackerDrawing.java   View source code 5 votes vote down vote up
@NotNull
private static ActionToolbar buildToolbar(@NotNull Range range,
                                          @NotNull Editor editor,
                                          @NotNull LineStatusTracker tracker,
                                          @NotNull Disposable parentDisposable) {
  final DefaultActionGroup group = new DefaultActionGroup();

  final ShowPrevChangeMarkerAction localShowPrevAction = new ShowPrevChangeMarkerAction(tracker.getPrevRange(range), tracker, editor);
  final ShowNextChangeMarkerAction localShowNextAction = new ShowNextChangeMarkerAction(tracker.getNextRange(range), tracker, editor);
  final RollbackLineStatusRangeAction rollback = new RollbackLineStatusRangeAction(tracker, range, editor);
  final ShowLineStatusRangeDiffAction showDiff = new ShowLineStatusRangeDiffAction(tracker, range, editor);
  final CopyLineStatusRangeAction copyRange = new CopyLineStatusRangeAction(tracker, range);

  group.add(localShowPrevAction);
  group.add(localShowNextAction);
  group.add(rollback);
  group.add(showDiff);
  group.add(copyRange);

  JComponent editorComponent = editor.getComponent();
  EmptyAction.setupAction(localShowPrevAction, "VcsShowPrevChangeMarker", editorComponent);
  EmptyAction.setupAction(localShowNextAction, "VcsShowNextChangeMarker", editorComponent);
  EmptyAction.setupAction(rollback, IdeActions.SELECTED_CHANGES_ROLLBACK, editorComponent);
  EmptyAction.setupAction(showDiff, "ChangesView.Diff", editorComponent);
  EmptyAction.setupAction(copyRange, IdeActions.ACTION_COPY, editorComponent);

  final List<AnAction> actionList = ActionUtil.getActions(editorComponent);
  Disposer.register(parentDisposable, new Disposable() {
    @Override
    public void dispose() {
      actionList.remove(localShowPrevAction);
      actionList.remove(localShowNextAction);
      actionList.remove(rollback);
      actionList.remove(showDiff);
      actionList.remove(copyRange);
    }
  });

  return ActionManager.getInstance().createActionToolbar(ActionPlaces.FILEHISTORY_VIEW_TOOLBAR, group, true);
}