com.intellij.openapi.util.Disposer Java Examples

The following examples show how to use com.intellij.openapi.util.Disposer. 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: PerfMemoryPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
PerfMemoryPanel(@NotNull FlutterApp app, @NotNull Disposable parentDisposable) {
  setLayout(new BorderLayout());
  setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), MEMORY_TAB_LABEL));
  setMinimumSize(new Dimension(0, PerfMemoryPanel.HEIGHT));
  setPreferredSize(new Dimension(Short.MAX_VALUE, PerfMemoryPanel.HEIGHT));

  final JPanel heapDisplay = HeapDisplay.createJPanelView(parentDisposable, app);
  add(heapDisplay, BorderLayout.CENTER);

  if (app.getVMServiceManager() != null) {
    app.getVMServiceManager().getHeapMonitor().addPollingClient();
  }

  Disposer.register(parentDisposable, () -> {
    if (app.getVMServiceManager() != null) {
      app.getVMServiceManager().getHeapMonitor().removePollingClient();
    }
  });
}
 
Example #2
Source File: RoutesView.java    From railways with MIT License 6 votes vote down vote up
public void removeModulePane(Module module) {
    // Find corresponding content by module...
    for (RoutesViewPane pane : myPanes)
        if (pane.getModule() == module) {
            // ... and remove it from panels list.
            myContentManager.removeContent(pane.getContent(), true);
            myPanes.remove(pane);

            // Remove contributor
            ChooseByRouteRegistry.getInstance(myProject)
                    .removeContributor(pane.getRoutesManager());

            Disposer.dispose(pane);
            break;
        }
}
 
Example #3
Source File: FlutterWidgetPerf.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void dispose() {
  if (isDisposed) {
    return;
  }

  this.isDisposed = true;

  if (uiAnimationTimer.isRunning()) {
    uiAnimationTimer.stop();
  }
  Disposer.dispose(perfProvider);

  AsyncUtils.invokeLater(() -> {
    clearModels();

    for (EditorPerfModel decorations : editorDecorations.values()) {
      Disposer.dispose(decorations);
    }
    editorDecorations.clear();
    perfListeners.clear();
  });
}
 
Example #4
Source File: FlutterViewMessages.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void sendDebugActive(@NotNull Project project,
                                   @NotNull FlutterApp app,
                                   @NotNull VmService vmService) {
  final MessageBus bus = project.getMessageBus();
  final FlutterDebugNotifier publisher = bus.syncPublisher(FLUTTER_DEBUG_TOPIC);

  assert (app.getFlutterDebugProcess() != null);

  final VMServiceManager vmServiceManager = new VMServiceManager(app, vmService);
  Disposer.register(app.getFlutterDebugProcess().getVmServiceWrapper(), vmServiceManager);
  app.setVmServices(vmService, vmServiceManager);
  publisher.debugActive(new FlutterDebugEvent(app, vmService));

  // TODO(pq): consider pushing into perf service.
  app.getFlutterLog().listenToVm(vmService);
}
 
Example #5
Source File: FlutterConsole.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
static FlutterConsole create(@NotNull Project project, @Nullable Module module) {
  final TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
  builder.setViewer(true);
  if (module != null) {
    builder.addFilter(new FlutterConsoleFilter(module));
  }
  final ConsoleView view = builder.getConsole();

  final SimpleToolWindowPanel panel = new SimpleToolWindowPanel(false, true);
  panel.setContent(view.getComponent());

  final String title = module != null ? "[" + module.getName() + "] Flutter" : "Flutter";
  final Content content = ContentFactory.SERVICE.getInstance().createContent(panel.getComponent(), title, true);
  Disposer.register(content, view);

  return new FlutterConsole(view, content, project, module);
}
 
Example #6
Source File: CacheComponent.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
@Override
public void dispose() {
    if (!disposed) {
        this.disposed = true;
        Disposer.dispose(this);
        changelistMap = null;
        fileMap = null;
        queryHandler = null;
        pendingHandler = null;
        updateListener = null;

        int postReleaseCount = ACTIVE_COUNT.decrementAndGet();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Disposed " + this + " for " + project + "; " + postReleaseCount
                    + " total still in memory");
        }
    }
}
 
Example #7
Source File: StableWidgetTracker.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public StableWidgetTracker(
  InspectorService.Location initialLocation,
  FlutterDartAnalysisServer flutterAnalysisServer,
  Project project,
  Disposable parentDisposable
) {
  Disposer.register(parentDisposable, this);
  converter = new OutlineOffsetConverter(project, initialLocation.getFile());
  currentOutlines = new EventStream<>(ImmutableList.of());
  this.flutterAnalysisServer = flutterAnalysisServer;
  this.initialLocation = initialLocation;

  final DartAnalysisServerService analysisServerService = DartAnalysisServerService.getInstance(project);
  currentFilePath = FileUtil.toSystemDependentName(initialLocation.getFile().getPath());
  flutterAnalysisServer.addOutlineListener(currentFilePath, outlineListener);
}
 
Example #8
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void init41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //ProjectManagerImpl.initProject(path, this, true, null, null);
    Method method = ReflectionUtil
      .getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
                         ProgressIndicator.class);
    assert (method != null);
    try {
      method.invoke(null, path, this, true, null, null);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #9
Source File: ServiceHelper.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static <T> void registerComponentInstance(
    MutablePicoContainer container, Class<T> key, T implementation, Disposable parentDisposable) {
  Object old;
  try {
    old = container.getComponentInstance(key);
  } catch (UnsatisfiableDependenciesException e) {
    old = null;
  }
  container.unregisterComponent(key.getName());
  container.registerComponentInstance(key.getName(), implementation);
  Object finalOld = old;
  Disposer.register(
      parentDisposable,
      () -> {
        container.unregisterComponent(key.getName());
        if (finalOld != null) {
          container.registerComponentInstance(key.getName(), finalOld);
        }
      });
}
 
Example #10
Source File: BlazeCommandRunConfigurationSettingsEditorTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void testEditorApplyToAndResetFromMatches() throws ConfigurationException {
  BlazeCommandRunConfigurationSettingsEditor editor =
      new BlazeCommandRunConfigurationSettingsEditor(configuration);
  Label label = Label.create("//package:rule");
  configuration.setTarget(label);

  editor.resetFrom(configuration);
  BlazeCommandRunConfiguration readConfiguration =
      type.getFactory().createTemplateConfiguration(getProject());
  editor.applyEditorTo(readConfiguration);

  assertThat(readConfiguration.getTargets()).containsExactly(label);

  Disposer.dispose(editor);
}
 
Example #11
Source File: FlutterModuleBuilder.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public ModuleWizardStep getCustomOptionsStep(final WizardContext context, final Disposable parentDisposable) {
  if (!context.isCreatingNewProject()) {
    myProject = context.getProject();
  }
  myStep = new FlutterModuleWizardStep(context);
  mySettingsFields = new FlutterCreateAdditionalSettingsFields(new FlutterCreateAdditionalSettings(), this::getFlutterSdk, myProject);
  Disposer.register(parentDisposable, myStep);
  return myStep;
}
 
Example #12
Source File: BoolServiceExtensionCheckbox.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void dispose() {
  if (currentValueSubscription != null) {
    Disposer.dispose(currentValueSubscription);
    currentValueSubscription = null;
  }
}
 
Example #13
Source File: GradleDependencyFetcherTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@BeforeClass
public static void setUp() {
  Disposable disposable = Disposer.newDisposable();
  ApplicationManager.setApplication(new MockApplication(disposable), disposable);
  Extensions.registerAreaClass("IDEA_PROJECT", null);
  ourProject = new MockProject(ApplicationManager.getApplication().getPicoContainer(), disposable);
}
 
Example #14
Source File: JavaSourceFolderProviderTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private ContentEntry getContentEntry(VirtualFile root) {
  ContentEntry entry =
      ModuleRootManager.getInstance(testFixture.getModule())
          .getModifiableModel()
          .addContentEntry(root);
  if (entry instanceof Disposable) {
    // need to dispose the content entry and child disposables before the TestFixture is disposed
    Disposer.register(thisClassDisposable, (Disposable) entry);
  }
  return entry;
}
 
Example #15
Source File: AllInPackageTestContextProviderTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Before
public final void before() {
  // disposed prior to calling parent class's @After methods
  Disposable thisClassDisposable = Disposer.newDisposable();

  projectViewManager = new MockProjectViewManager(getProject(), thisClassDisposable);
  errorCollector = new ErrorCollector();
  context = new BlazeContext();
  context.addOutputSink(IssueOutput.class, errorCollector);
}
 
Example #16
Source File: BlazeSyncIntegrationTestCase.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Before
public void doSetup() {
  thisClassDisposable = Disposer.newDisposable();
  projectViewManager = new MockProjectViewManager(getProject(), thisClassDisposable);
  new MockBlazeVcsHandler(thisClassDisposable);
  blazeInfoData = new MockBlazeInfoRunner();
  blazeIdeInterface = new MockBlazeIdeInterface();
  eventLogger = new MockEventLoggingService(thisClassDisposable);
  if (isLightTestCase()) {
    moduleMocker = new ProjectModuleMocker(getProject(), thisClassDisposable);
  }
  registerApplicationService(BlazeInfoRunner.class, blazeInfoData);
  registerApplicationService(BlazeIdeInterface.class, blazeIdeInterface);

  errorCollector = new ErrorCollector();

  fileSystem.createDirectory(projectDataDirectory.getPath() + "/.blaze/modules");

  // absolute file paths depend on #isLightTestCase, so can't be determined statically
  String outputBase = fileSystem.createDirectory("output_base").getPath();
  execRoot = fileSystem.createDirectory("execroot/root").getPath();
  String outputPath = execRoot + "/blaze-out";
  String blazeBin = String.format("%s/%s/bin", outputPath, DEFAULT_CONFIGURATION);
  String blazeGenfiles = String.format("%s/%s/genfiles", outputPath, DEFAULT_CONFIGURATION);
  String blazeTestlogs = String.format("%s/%s/testlogs", outputPath, DEFAULT_CONFIGURATION);

  blazeInfoData.setResults(
      ImmutableMap.<String, String>builder()
          .put(BlazeInfo.blazeBinKey(Blaze.getBuildSystem(getProject())), blazeBin)
          .put(BlazeInfo.blazeGenfilesKey(Blaze.getBuildSystem(getProject())), blazeGenfiles)
          .put(BlazeInfo.blazeTestlogsKey(Blaze.getBuildSystem(getProject())), blazeTestlogs)
          .put(BlazeInfo.EXECUTION_ROOT_KEY, execRoot)
          .put(BlazeInfo.OUTPUT_BASE_KEY, outputBase)
          .put(BlazeInfo.OUTPUT_PATH_KEY, outputPath)
          .put(BlazeInfo.PACKAGE_PATH_KEY, workspaceRoot.toString())
          .build());
}
 
Example #17
Source File: ORFileEditorListener.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Override
public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile sourceFile) {
    ServiceManager.getService(m_project, InsightManager.class).downloadRincewindIfNeeded(sourceFile);

    FileType fileType = sourceFile.getFileType();
    if (FileHelper.isCompilable(fileType)) {
        FileEditor selectedEditor = source.getSelectedEditor(sourceFile);
        Document document = FileDocumentManager.getInstance().getDocument(sourceFile);
        if (selectedEditor instanceof TextEditor && document != null) {
            InsightUpdateQueue insightUpdateQueue = new InsightUpdateQueue(m_project, sourceFile);
            Disposer.register(selectedEditor, insightUpdateQueue);
            document.addDocumentListener(new ORDocumentEventListener(insightUpdateQueue), selectedEditor);

            ORPropertyChangeListener propertyChangeListener = new ORPropertyChangeListener(sourceFile, document, insightUpdateQueue);
            selectedEditor.addPropertyChangeListener(propertyChangeListener);
            Disposer.register(selectedEditor, () -> {
                selectedEditor.removePropertyChangeListener(propertyChangeListener);
            });

            // Store the queue in the document, for easy access
            document.putUserData(INSIGHT_QUEUE, insightUpdateQueue);

            // Initial query when opening the editor
            insightUpdateQueue.queue(m_project, document);

            m_queues.add(insightUpdateQueue);
        }
    }

    m_openedFiles.add(sourceFile);
}
 
Example #18
Source File: TestUtils.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the platform prefix system property, reverting to the previous value when the supplied
 * parent disposable is disposed.
 */
public static void setPlatformPrefix(Disposable parentDisposable, String platformPrefix) {
  String prevValue = System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY);
  System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, platformPrefix);
  Disposer.register(
      parentDisposable,
      () -> {
        if (prevValue != null) {
          System.setProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prevValue);
        } else {
          System.clearProperty(PlatformUtils.PLATFORM_PREFIX_KEY);
        }
      });
}
 
Example #19
Source File: DartVmServiceDebugProcess.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void stop() {
  myVmConnected = false;

  mapper.shutdown();

  if (myVmServiceWrapper != null) {
    Disposer.dispose(myVmServiceWrapper);
  }
}
 
Example #20
Source File: RPiJavaModuleBuilder.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a custom wizard GUI
 * @param context
 * @param parentDisposable
 * @return
 */
@Nullable
@Override
public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) {
    EmbeddedJavaModuleStep step = new EmbeddedJavaModuleStep(this);
    Disposer.register(parentDisposable, step);
    return step;
}
 
Example #21
Source File: FlutterWidgetPerf.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void harvestInvalidEditors(Set<TextEditor> newEditors) {
  final Iterator<TextEditor> editors = editorDecorations.keySet().iterator();

  while (editors.hasNext()) {
    final TextEditor editor = editors.next();
    if (!editor.isValid() || (newEditors != null && !newEditors.contains(editor))) {
      final EditorPerfModel editorPerfDecorations = editorDecorations.get(editor);
      editors.remove();
      Disposer.dispose(editorPerfDecorations);
    }
  }
}
 
Example #22
Source File: FlutterAppManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private FlutterAppManager(@NotNull Project project) {
  this.project = project;

  Disposer.register(project, this);

  task = JobScheduler.getScheduler().scheduleWithFixedDelay(
    this::updateActiveApp, 1, 1, TimeUnit.SECONDS);
}
 
Example #23
Source File: Refreshable.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Asynchronously shuts down the Refreshable.
 *
 * <p>Sets the published value to null and cancels any background tasks.
 *
 * <p>Also sets the state to CLOSED and notifies subscribers. Removes subscribers after delivering the last event.
 */
public void close() {
  if (!publisher.close()) {
    return; // already closed.
  }

  // Cancel any running create task.
  schedule.reschedule(null);

  // Remove from dispose tree. Calls close() again, harmlessly.
  Disposer.dispose(disposeNode);
}
 
Example #24
Source File: BlazeProblemsView.java    From intellij with Apache License 2.0 5 votes vote down vote up
public BlazeProblemsView(Project project) {
  this.project = project;
  this.toolWindowId = Blaze.getBuildSystem(project).getName() + " Problems";
  uiFuture =
      new FutureTask<>(
          () -> {
            BlazeProblemsViewPanel panel = new BlazeProblemsViewPanel(project);
            Disposer.register(project, () -> Disposer.dispose(panel));
            createToolWindow(project, ToolWindowManager.getInstance(project), panel);
            return panel;
          });
  UIUtil.invokeLaterIfNeeded(uiFuture);
}
 
Example #25
Source File: VMServiceManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void addRegisteredExtensionRPCs(Isolate isolate, boolean attach) {
  // If attach was called, there is a risk we may never receive a
  // Flutter.Frame or Flutter.FirstFrame event so we need to query the
  // framework to determine if a frame has already been rendered.
  // This check would be safe to do outside of attach mode but is not needed.
  if (attach && isolate.getExtensionRPCs() != null && !firstFrameEventReceived) {
    final Set<String> bindingLibraryNames = new HashSet<>();
    bindingLibraryNames.add("package:flutter/src/widgets/binding.dart");

    final EvalOnDartLibrary flutterLibrary = new EvalOnDartLibrary(
      bindingLibraryNames,
      vmService,
      this
    );
    flutterLibrary.eval("WidgetsBinding.instance.debugDidSendFirstFrameEvent", null, null).whenCompleteAsync((v, e) -> {
      // If there is an error we assume the first frame has been received.
      final boolean didSendFirstFrameEvent = e == null ||
                                             v == null ||
                                             Objects.equals(v.getValueAsString(), "true");
      if (didSendFirstFrameEvent) {
        onFrameEventReceived();
      }
      Disposer.dispose(flutterLibrary);
    });
  }
  if (isolate.getExtensionRPCs() != null) {
    for (String extension : isolate.getExtensionRPCs()) {
      addServiceExtension(extension);
    }
  }
}
 
Example #26
Source File: MessageBusClient.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@NotNull
public static ProjectClient forProject(@NotNull Project project, @NotNull Disposable owner) {
    ProjectClient ret = new ProjectClient(project.getMessageBus().connect(owner));
    // Just to be sure...
    Disposer.register(owner, ret::close);
    return ret;
}
 
Example #27
Source File: WindowEditorOps.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
public final void releaseEditor(final Project project, final Editor editor) {
if (editor != null) {
    Disposer.register(project, new Disposable() {
        public void dispose() {
            EditorFactory.getInstance().releaseEditor(editor);
        }
    });
    }
}
 
Example #28
Source File: DeviceSelectorAction.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void update(final AnActionEvent e) {
  // Suppress device actions in all but the toolbars.
  final String place = e.getPlace();
  if (!Objects.equals(place, ActionPlaces.NAVIGATION_BAR_TOOLBAR) && !Objects.equals(place, ActionPlaces.MAIN_TOOLBAR)) {
    e.getPresentation().setVisible(false);
    return;
  }

  // Only show device menu when the device daemon process is running.
  final Project project = e.getProject();
  if (!isSelectorVisible(project)) {
    e.getPresentation().setVisible(false);
    return;
  }

  super.update(e);

  if (!knownProjects.contains(project)) {
    knownProjects.add(project);
    Disposer.register(project, () -> knownProjects.remove(project));

    DeviceService.getInstance(project).addListener(() -> update(project, e.getPresentation()));

    // Listen for android device changes, and rebuild the menu if necessary.
    AndroidEmulatorManager.getInstance(project).addListener(() -> update(project, e.getPresentation()));

    update(project, e.getPresentation());
  }
}
 
Example #29
Source File: VMServiceManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void addRegisteredExtensionRPCs(Isolate isolate, boolean attach) {
  // If attach was called, there is a risk we may never receive a
  // Flutter.Frame or Flutter.FirstFrame event so we need to query the
  // framework to determine if a frame has already been rendered.
  // This check would be safe to do outside of attach mode but is not needed.
  if (attach && isolate.getExtensionRPCs() != null && !firstFrameEventReceived) {
    final Set<String> bindingLibraryNames = new HashSet<>();
    bindingLibraryNames.add("package:flutter/src/widgets/binding.dart");

    final EvalOnDartLibrary flutterLibrary = new EvalOnDartLibrary(
      bindingLibraryNames,
      vmService,
      this
    );
    flutterLibrary.eval("WidgetsBinding.instance.debugDidSendFirstFrameEvent", null, null).whenCompleteAsync((v, e) -> {
      // If there is an error we assume the first frame has been received.
      final boolean didSendFirstFrameEvent = e == null ||
                                             v == null ||
                                             Objects.equals(v.getValueAsString(), "true");
      if (didSendFirstFrameEvent) {
        onFrameEventReceived();
      }
      Disposer.dispose(flutterLibrary);
    });
  }
  if (isolate.getExtensionRPCs() != null) {
    for (String extension : isolate.getExtensionRPCs()) {
      addServiceExtension(extension);
    }
  }
}
 
Example #30
Source File: BlazeProjectDataManagerImpl.java    From intellij with Apache License 2.0 5 votes vote down vote up
public BlazeProjectDataManagerImpl(Project project) {
  this.project = project;
  writeDataExecutor =
      MoreExecutors.listeningDecorator(
          Executors.newSingleThreadExecutor(
              ConcurrencyUtil.namedDaemonThreadPoolFactory(BlazeProjectDataManagerImpl.class)));
  Disposer.register(project, writeDataExecutor::shutdown);
}