Java Code Examples for consulo.disposer.Disposable#newDisposable()

The following examples show how to use consulo.disposer.Disposable#newDisposable() . 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: ActionTracer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public JComponent getComponent() {
  if (myComponent == null) {
    myText = new JTextArea();
    final JBScrollPane log = new JBScrollPane(myText);
    final AnAction clear = new AnAction("Clear", "Clear log", AllIcons.General.Reset) {
      @Override
      public void actionPerformed(AnActionEvent e) {
        myText.setText(null);
      }
    };
    myComponent = new JPanel(new BorderLayout());
    final DefaultActionGroup group = new DefaultActionGroup();
    group.add(clear);
    myComponent.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true).getComponent(), BorderLayout.NORTH);
    myComponent.add(log);

    myListenerDisposable = Disposable.newDisposable();
    Application.get().getMessageBus().connect(myListenerDisposable).subscribe(AnActionListener.TOPIC, this);
  }

  return myComponent;
}
 
Example 2
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateOnPsiChanges(@Nonnull LightweightHint hint, @Nonnull Info info, @Nonnull Consumer<? super String> textConsumer, @Nonnull String oldText, @Nonnull Editor editor) {
  if (!hint.isVisible()) return;
  Disposable hintDisposable = Disposable.newDisposable("CtrlMouseHandler.TooltipProvider.updateOnPsiChanges");
  hint.addHintListener(__ -> Disposer.dispose(hintDisposable));
  myProject.getMessageBus().connect(hintDisposable).subscribe(PsiModificationTracker.TOPIC, () -> ReadAction.nonBlocking(() -> {
    try {
      DocInfo newDocInfo = info.getInfo();
      return (Runnable)() -> {
        if (newDocInfo.text != null && !oldText.equals(newDocInfo.text)) {
          updateText(newDocInfo.text, textConsumer, hint, editor);
        }
      };
    }
    catch (IndexNotReadyException e) {
      showDumbModeNotification(myProject);
      return createDisposalContinuation();
    }
  }).finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run).withDocumentsCommitted(myProject).expireWith(hintDisposable).expireWhen(() -> !info.isValid(editor.getDocument()))
          .coalesceBy(hint).submit(AppExecutorUtil.getAppExecutorService()));
}
 
Example 3
Source File: MergeTool.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void showDialog(MergeRequestImpl data) {
  DialogBuilder builder = new DialogBuilder(data.getProject());
  builder.setDimensionServiceKey(data.getGroupKey());
  builder.setTitle(data.getWindowTitle());
  Disposable parent = Disposable.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 4
Source File: HistoryEntry.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static HistoryEntry createHeavy(@Nonnull Project project, @Nonnull Element e) throws InvalidDataException {
  if (project.isDisposed()) return createLight(project, e);

  EntryData entryData = parseEntry(project, e);

  Disposable disposable = Disposable.newDisposable();
  VirtualFilePointer pointer = VirtualFilePointerManager.getInstance().create(entryData.url, disposable, null);

  HistoryEntry entry = new HistoryEntry(pointer, entryData.selectedProvider, disposable);
  for (Pair<FileEditorProvider, FileEditorState> state : entryData.providerStates) {
    entry.putState(state.first, state.second);
  }
  return entry;
}
 
Example 5
Source File: MessageBusImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public MessageBusImpl(@Nonnull InjectingContainerOwner owner, @Nonnull MessageBusImpl parentBus) {
  myOwner = owner;
  myConnectionDisposable = Disposable.newDisposable(myOwner.toString());
  myParentBus = parentBus;
  myRootBus = parentBus.myRootBus;
  synchronized (parentBus.myChildBuses) {
    myOrder = parentBus.nextOrder();
    parentBus.myChildBuses.add(this);
  }
  LOG.assertTrue(parentBus.myChildBuses.contains(this));
  myRootBus.clearSubscriberCache();
  // only for project
  myLazyConnection = parentBus.myParentBus == null ? connect() : null;
}
 
Example 6
Source File: ExtensionEditor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiredUIAccess
@SuppressWarnings("deprecation")
private JComponent createConfigurationPanel(final @Nonnull MutableModuleExtension extension) {
  myConfigurablePanelExtension = extension;
  @RequiredUIAccess Runnable updateOnCheck = () -> extensionChanged(extension);

  Disposable uiDisposable = Disposable.newDisposable("module extension: " + extension.getId());

  JComponent result = null;

  if (extension instanceof SwingMutableModuleExtension) {
    result = ((SwingMutableModuleExtension)extension).createConfigurablePanel(uiDisposable, updateOnCheck);
  }
  else {
    Component component = extension.createConfigurationComponent(uiDisposable, updateOnCheck);

    if (component != null) {
      if (component instanceof Layout) {
        component.removeBorders();

        component.addBorders(BorderStyle.EMPTY, null, 5);
      }

      result = (JComponent)TargetAWT.to(component);
    }
  }

  if (result != null) {
    myExtensionDisposables.put(result, uiDisposable);
  }

  return result;
}
 
Example 7
Source File: FindPopupPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
FindPopupPanel(@Nonnull FindUIHelper helper) {
  myHelper = helper;
  myProject = myHelper.getProject();
  myDisposable = Disposable.newDisposable();
  myPreviewUpdater = new Alarm(myDisposable);
  myScopeUI = FindPopupScopeUIProvider.getInstance().create(this);
  myComponentValidator = new ComponentValidator(myDisposable) {
    @Override
    public void updateInfo(@Nullable ValidationInfo info) {
      if (info != null && info.component == mySearchComponent) {
        super.updateInfo(null);
      }
      else {
        super.updateInfo(info);
      }
    }
  };

  Disposer.register(myDisposable, () -> {
    finishPreviousPreviewSearch();
    if (mySearchRescheduleOnCancellationsAlarm != null) Disposer.dispose(mySearchRescheduleOnCancellationsAlarm);
    if (myUsagePreviewPanel != null) Disposer.dispose(myUsagePreviewPanel);
  });

  initComponents();
  initByModel();

  //FindUtil.triggerUsedOptionsStats("FindInPath", myHelper.getModel());
}
 
Example 8
Source File: DelayedDocumentWatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void activate() {
  if (myConnection == null) {
    myListenerDisposable = Disposable.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(() -> myDocumentSavingInProgress = false, ModalityState.any());
      }
    });
  }
}
 
Example 9
Source File: MessageBusImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private MessageBusImpl(@Nonnull InjectingContainerOwner owner) {
  myOwner = owner;
  myConnectionDisposable = Disposable.newDisposable(myOwner.toString());
  myOrder = ArrayUtil.EMPTY_INT_ARRAY;
  myRootBus = (RootBus)this;
  myLazyConnection = connect();
}
 
Example 10
Source File: ProgressStripe.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ProgressStripe(@Nonnull JComponent targetComponent, @Nonnull Disposable parent, int startDelayMs) {
  super(new BorderLayout());
  myPanel = new JBPanel(new BorderLayout());
  myPanel.setOpaque(false);
  myPanel.add(targetComponent);

  myCreateLoadingDecorator = () -> {
    Disposable disposable = Disposable.newDisposable();
    Disposer.register(parent, disposable);
    return new MyLoadingDecorator(targetComponent, myPanel, disposable, startDelayMs);
  };
  createLoadingDecorator();
}
 
Example 11
Source File: TextEditorBasedStructureViewModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public final void addEditorPositionListener(@Nonnull FileEditorPositionListener listener) {
  if (myEditor != null && myListeners.isEmpty()) {
    myEditorCaretListenerDisposable = Disposable.newDisposable();
    EditorFactory.getInstance().getEventMulticaster().addCaretListener(myEditorCaretListener, myEditorCaretListenerDisposable);
  }
  myListeners.add(listener);
}
 
Example 12
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
private boolean waitInOtherThread(int millis, boolean canChangeDocument) throws Throwable {
  Disposable disposable = Disposable.newDisposable();
  // last hope protection against PsiModificationTrackerImpl.incCounter() craziness (yes, Kotlin)
  myProject.getMessageBus().connect(disposable).subscribe(PsiModificationTracker.TOPIC, () -> {
    throw new IllegalStateException("You must not perform PSI modifications from inside highlighting");
  });
  if (!canChangeDocument) {
    myProject.getMessageBus().connect(disposable).subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, new DaemonListener() {
      @Override
      public void daemonCancelEventOccurred(@Nonnull String reason) {
        throw new IllegalStateException("You must not cancel daemon inside highlighting test: " + reason);
      }
    });
  }

  try {
    Future<Boolean> future = ApplicationManager.getApplication().executeOnPooledThread(() -> {
      try {
        return myPassExecutorService.waitFor(millis);
      }
      catch (Throwable e) {
        throw new RuntimeException(e);
      }
    });
    return future.get();
  }
  finally {
    Disposer.dispose(disposable);
  }
}
 
Example 13
Source File: LoadingDecoratorTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  IconLoader.activate();

  final JFrame frame = new JFrame();
  frame.getContentPane().setLayout(new BorderLayout());

  final JPanel content = new JPanel(new BorderLayout());

  final LoadingDecorator loadingTree = new LoadingDecorator(new JComboBox(), Disposable.newDisposable(), -1);

  content.add(loadingTree.getComponent(), BorderLayout.CENTER);

  final JCheckBox loadingCheckBox = new JCheckBox("Loading");
  loadingCheckBox.addActionListener(new ActionListener() {
    public void actionPerformed(final ActionEvent e) {
      if (loadingTree.isLoading()) {
        loadingTree.stopLoading();
      } else {
        loadingTree.startLoading(false);
      }
    }
  });

  content.add(loadingCheckBox, BorderLayout.SOUTH);


  frame.getContentPane().add(content, BorderLayout.CENTER);

  frame.setBounds(300, 300, 300, 300);
  frame.show();
}
 
Example 14
Source File: PlatformUltraLiteTestFixture.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void setUp() {
  final Application application = ApplicationManager.getApplication();
  if (application == null) {
    myAppDisposable = Disposable.newDisposable();
    ApplicationManager.setApplication(new MockApplication(myAppDisposable), myAppDisposable);
  }
}
 
Example 15
Source File: MockApplicationTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  myRootDisposable = Disposable.newDisposable();

  LightApplicationBuilder.create(myRootDisposable).build();
}
 
Example 16
Source File: OnePixelDivider.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void init() {
  myGlassPane = IdeGlassPaneUtil.find(this);
  myDisposable = Disposable.newDisposable();
  myGlassPane.addMouseMotionPreprocessor(myListener, myDisposable);
  myGlassPane.addMousePreprocessor(myListener, myDisposable);
}
 
Example 17
Source File: ParameterInfoTaskRunnerUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static Consumer<Boolean> startProgressAndCreateStopAction(Project project, String progressTitle, AtomicReference<CancellablePromise<?>> promiseRef, Editor editor) {
  AtomicReference<Consumer<Boolean>> stopActionRef = new AtomicReference<>();

  Consumer<Boolean> originalStopAction = (cancel) -> {
    stopActionRef.set(null);
    if (cancel) {
      CancellablePromise<?> promise = promiseRef.get();
      if (promise != null) {
        promise.cancel();
      }
    }
  };

  if (progressTitle == null) {
    stopActionRef.set(originalStopAction);
  }
  else {
    final Disposable disposable = Disposable.newDisposable();
    Disposer.register(project, disposable);

    JBLoadingPanel loadingPanel = new JBLoadingPanel(null, panel -> new LoadingDecorator(panel, disposable, 0, false, new AsyncProcessIcon("ShowParameterInfo")) {
      @Override
      protected NonOpaquePanel customizeLoadingLayer(JPanel parent, JLabel text, AsyncProcessIcon icon) {
        parent.setLayout(new FlowLayout(FlowLayout.LEFT));
        final NonOpaquePanel result = new NonOpaquePanel();
        result.add(icon);
        parent.add(result);
        return result;
      }
    });
    loadingPanel.add(new JBLabel(EmptyIcon.ICON_18));
    loadingPanel.add(new JBLabel(progressTitle));

    ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(loadingPanel, null).setProject(project).setCancelCallback(() -> {
      Consumer<Boolean> stopAction = stopActionRef.get();
      if (stopAction != null) {
        stopAction.accept(true);
      }
      return true;
    });
    JBPopup popup = builder.createPopup();
    Disposer.register(disposable, popup);
    ScheduledFuture<?> showPopupFuture = EdtScheduledExecutorService.getInstance().schedule(() -> {
      if (!popup.isDisposed() && !popup.isVisible() && !editor.isDisposed()) {
        RelativePoint popupPosition = JBPopupFactory.getInstance().guessBestPopupLocation(editor);
        loadingPanel.startLoading();
        popup.show(popupPosition);
      }
    }, ModalityState.defaultModalityState(), DEFAULT_PROGRESS_POPUP_DELAY_MS, TimeUnit.MILLISECONDS);

    stopActionRef.set((cancel) -> {
      try {
        loadingPanel.stopLoading();
        originalStopAction.accept(cancel);
      }
      finally {
        showPopupFuture.cancel(false);
        UIUtil.invokeLaterIfNeeded(() -> {
          if (popup.isVisible()) {
            popup.setUiVisible(false);
          }
          Disposer.dispose(disposable);
        });
      }
    });
  }

  return stopActionRef.get();
}
 
Example 18
Source File: StructureTreeModel.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated Please use {@link #StructureTreeModel(AbstractTreeStructure, Disposable)}
 */
@Deprecated
//@ApiStatus.ScheduledForRemoval(inVersion = "2019.3")
public StructureTreeModel(@Nonnull Structure structure) {
  this(structure, Disposable.newDisposable());
}
 
Example 19
Source File: StructureTreeModel.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated Please use {@link #StructureTreeModel(AbstractTreeStructure, Comparator, Disposable)}
 */
@Deprecated
//@ApiStatus.ScheduledForRemoval(inVersion = "2019.3")
public StructureTreeModel(@Nonnull Structure structure, @Nonnull Comparator<? super NodeDescriptor> comparator) {
  this(structure, comparator, Disposable.newDisposable());
}
 
Example 20
Source File: ContentUtilEx.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void addTabbedContent(@Nonnull ContentManager manager,
                                    @Nonnull JComponent contentComponent,
                                    @Nonnull String groupPrefix,
                                    @Nonnull String tabName,
                                    boolean select,
                                    @Nullable Disposable childDisposable) {
  if (PropertiesComponent.getInstance().getBoolean(TabbedContent.SPLIT_PROPERTY_PREFIX + groupPrefix)) {
    final Content content = ContentFactory.getInstance().createContent(contentComponent, getFullName(groupPrefix, tabName), true);
    content.putUserData(Content.TABBED_CONTENT_KEY, Boolean.TRUE);
    content.putUserData(Content.TAB_GROUP_NAME_KEY, groupPrefix);

    for (Content c : manager.getContents()) {
      if (c.getComponent() == contentComponent) {
        if (select) {
          manager.setSelectedContent(c);
        }
        return;
      }
    }
    addContent(manager, content, select);

    registerDisposable(content, childDisposable, contentComponent);

    return;
  }

  TabbedContent tabbedContent = findTabbedContent(manager, groupPrefix);

  if (tabbedContent == null) {
    final Disposable disposable = Disposable.newDisposable();
    tabbedContent = new TabbedContentImpl(contentComponent, tabName, true, groupPrefix);
    ContentsUtil.addOrReplaceContent(manager, tabbedContent, select);
    Disposer.register(tabbedContent, disposable);
  }
  else {
    for (Pair<String, JComponent> tab : new ArrayList<>(tabbedContent.getTabs())) {
      if (Comparing.equal(tab.second, contentComponent)) {
        tabbedContent.removeContent(tab.second);
      }
    }
    if (select) {
      manager.setSelectedContent(tabbedContent, true, true);
    }
    tabbedContent.addContent(contentComponent, tabName, true);
  }

  registerDisposable(tabbedContent, childDisposable, contentComponent);
}