com.intellij.reference.SoftReference Java Examples

The following examples show how to use com.intellij.reference.SoftReference. 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: Divider.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void divideInsideAndOutsideInOneRoot(@Nonnull PsiFile root,
                                            @Nonnull TextRange restrictRange,
                                            @Nonnull TextRange priorityRange,
                                            @Nonnull Processor<DividedElements> processor) {
  long modificationStamp = root.getModificationStamp();
  DividedElements cached = SoftReference.dereference(root.getUserData(DIVIDED_ELEMENTS_KEY));
  DividedElements elements;
  if (cached == null || cached.modificationStamp != modificationStamp || !cached.restrictRange.equals(restrictRange) || !cached.priorityRange.contains(priorityRange)) {
    elements = new DividedElements(modificationStamp, root, restrictRange, priorityRange);
    divideInsideAndOutsideInOneRoot(root, restrictRange, priorityRange, elements.inside, elements.insideRanges, elements.outside,
                                    elements.outsideRanges, elements.parents,
                                    elements.parentRanges, true);
    root.putUserData(DIVIDED_ELEMENTS_KEY, new java.lang.ref.SoftReference<>(elements));
  }
  else {
    elements = cached;
  }
  processor.process(elements);
}
 
Example #2
Source File: SwingValidator.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean validateValue(Component awtComponent, V value, boolean silence) {
  for (ValidableComponent.Validator<V> validator : myValidators) {
    ValidableComponent.ValidationInfo validationInfo = validator.validateValue(value);
    if (validationInfo != null) {
      if(!silence) {
        doShowPopup((JComponent)awtComponent, validationInfo);
      }
      return false;
    }
    else {
      JBPopup popup = SoftReference.dereference(myLastPopup);
      if(popup != null) {
        popup.cancel();
        myLastPopup = null;
      }
    }
  }
  return true;
}
 
Example #3
Source File: DesktopToolWindowPanelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private Pair<BufferedImage, Reference<BufferedImage>> getImage(@Nullable Reference<BufferedImage> imageRef) {
  LOG.assertTrue(UISettings.getInstance().getAnimateWindows());
  Window awtWindow = TargetAWT.to(myIdeFrame.getWindow());
  BufferedImage image = SoftReference.dereference(imageRef);
  if (image == null || image.getWidth(null) < getWidth() || image.getHeight(null) < getHeight()) {
    final int width = Math.max(Math.max(1, getWidth()), awtWindow.getWidth());
    final int height = Math.max(Math.max(1, getHeight()), awtWindow.getHeight());
    if (SystemInfo.isWindows) {
      image = awtWindow.getGraphicsConfiguration().createCompatibleImage(width, height);
    }
    else {
      // Under Linux we have found that images created by createCompatibleImage(),
      // createVolatileImage(), etc extremely slow for rendering. TrueColor buffered image
      // is MUCH faster.
      // On Mac we create a retina-compatible image

      image = UIUtil.createImage(getGraphics(), width, height, BufferedImage.TYPE_INT_RGB);
    }
    imageRef = new SoftReference<>(image);
  }
  return Pair.create(image, imageRef);
}
 
Example #4
Source File: EditorHighlighterCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static EditorHighlighter getEditorHighlighterForCachesBuilding(Document document) {
  if (document == null) {
    return null;
  }
  final WeakReference<EditorHighlighter> editorHighlighterWeakReference = document.getUserData(ourSomeEditorSyntaxHighlighter);
  final EditorHighlighter someEditorHighlighter = SoftReference.dereference(editorHighlighterWeakReference);

  if (someEditorHighlighter instanceof LexerEditorHighlighter &&
      ((LexerEditorHighlighter)someEditorHighlighter).isValid()
          ) {
    return someEditorHighlighter;
  }
  document.putUserData(ourSomeEditorSyntaxHighlighter, null);
  return null;
}
 
Example #5
Source File: DocumentImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * makes range marker without creating document (which could be expensive)
 */
@Nonnull
static RangeMarker createRangeMarkerForVirtualFile(@Nonnull VirtualFile file, int startOffset, int endOffset, int startLine, int startCol, int endLine, int endCol, boolean persistent) {
  RangeMarkerImpl marker = persistent ? new PersistentRangeMarker(file, startOffset, endOffset, startLine, startCol, endLine, endCol, false) : new RangeMarkerImpl(file, startOffset, endOffset, false);
  Key<Reference<RangeMarkerTree<RangeMarkerEx>>> key = persistent ? PERSISTENT_RANGE_MARKERS_KEY : RANGE_MARKERS_KEY;
  RangeMarkerTree<RangeMarkerEx> tree;
  while (true) {
    Reference<RangeMarkerTree<RangeMarkerEx>> oldRef = file.getUserData(key);
    tree = SoftReference.dereference(oldRef);
    if (tree != null) break;
    tree = new RangeMarkerTree<>();
    RMTreeReference reference = new RMTreeReference(tree, file);
    if (file.replace(key, oldRef, reference)) break;
  }
  tree.addInterval(marker, startOffset, endOffset, false, false, false, 0);

  return marker;

}
 
Example #6
Source File: ShowImplementationsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateInBackground(Editor editor,
                                @Nullable PsiElement element,
                                @Nonnull ImplementationViewComponent component,
                                String title,
                                @Nonnull AbstractPopup popup,
                                @Nonnull Ref<UsageView> usageView) {
  final ImplementationsUpdaterTask updaterTask = SoftReference.dereference(myTaskRef);
  if (updaterTask != null) {
    updaterTask.cancelTask();
  }

  if (element == null) return; //already found
  final ImplementationsUpdaterTask task = new ImplementationsUpdaterTask(element, editor, title, isIncludeAlwaysSelf(), component);
  task.init(popup, new ImplementationViewComponentUpdater(component, isIncludeAlwaysSelf() ? 1 : 0), usageView);

  myTaskRef = new WeakReference<>(task);
  ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, new BackgroundableProcessIndicator(task));
}
 
Example #7
Source File: SmartPointerManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public <E extends PsiElement> SmartPsiElementPointer<E> createSmartPsiElementPointer(@Nonnull E element, PsiFile containingFile, boolean forInjected) {
  ensureValid(element, containingFile);
  SmartPointerTracker.processQueue();
  ensureMyProject(containingFile != null ? containingFile.getProject() : element.getProject());
  SmartPsiElementPointerImpl<E> pointer = getCachedPointer(element);
  if (pointer != null &&
      (!(pointer.getElementInfo() instanceof SelfElementInfo) || ((SelfElementInfo)pointer.getElementInfo()).isForInjected() == forInjected) &&
      pointer.incrementAndGetReferenceCount(1) > 0) {
    return pointer;
  }

  pointer = new SmartPsiElementPointerImpl<>(this, element, containingFile, forInjected);
  if (containingFile != null) {
    trackPointer(pointer, containingFile.getViewProvider().getVirtualFile());
  }
  element.putUserData(CACHED_SMART_POINTER_KEY, new SoftReference<>(pointer));
  return pointer;
}
 
Example #8
Source File: UsageInfo2UsageAdapter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private TextChunk[] initChunks() {
  PsiFile psiFile = getPsiFile();
  Document document = psiFile == null ? null : PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);
  TextChunk[] chunks;
  if (document == null) {
    // element over light virtual file
    PsiElement element = getElement();
    if (element == null) {
      chunks = new TextChunk[]{new TextChunk(SimpleTextAttributes.ERROR_ATTRIBUTES.toTextAttributes(), UsageViewBundle.message("node.invalid"))};
    }
    else {
      chunks = new TextChunk[]{new TextChunk(new TextAttributes(), element.getText())};
    }
  }
  else {
    chunks = ChunkExtractor.extractChunks(psiFile, this);
  }

  myTextChunks = new SoftReference<>(chunks);
  return chunks;
}
 
Example #9
Source File: ImagePreviewComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"AutoUnboxing"})
private static boolean refresh(@Nonnull VirtualFile file) throws IOException {
  Long loadedTimeStamp = file.getUserData(TIMESTAMP_KEY);
  SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
  if (loadedTimeStamp == null || loadedTimeStamp < file.getTimeStamp() || SoftReference.dereference(imageRef) == null) {
    try {
      final byte[] content = file.contentsToByteArray();
      InputStream inputStream = new ByteArrayInputStream(content, 0, content.length);
      ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream);
      try {
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
        if (imageReaders.hasNext()) {
          ImageReader imageReader = imageReaders.next();
          try {
            file.putUserData(FORMAT_KEY, imageReader.getFormatName());
            ImageReadParam param = imageReader.getDefaultReadParam();
            imageReader.setInput(imageInputStream, true, true);
            int minIndex = imageReader.getMinIndex();
            BufferedImage image = imageReader.read(minIndex, param);
            file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<BufferedImage>(image));
            return true;
          }
          finally {
            imageReader.dispose();
          }
        }
      }
      finally {
        imageInputStream.close();
      }
    }
    finally {
      // We perform loading no more needed
      file.putUserData(TIMESTAMP_KEY, System.currentTimeMillis());
    }
  }
  return false;
}
 
Example #10
Source File: CppBundle.java    From CppTools with Apache License 2.0 5 votes vote down vote up
private static ResourceBundle getBundle() {
  ResourceBundle bundle = null;
  if (ourBundle != null) bundle = ourBundle.get();
  if (bundle == null) {
    bundle = ResourceBundle.getBundle(BUNDLE);
    ourBundle = new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 
Example #11
Source File: DesktopAsyncDataContext.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected Object calcData(@Nonnull Key dataId, Component focused) {
  try (AccessToken ignored = ProhibitAWTEvents.start("getData")) {
    for (WeakReference<Component> reference : myHierarchy) {
      Component component = SoftReference.dereference(reference);
      if (component == null) continue;
      DataProvider dataProvider = myProviders.get(component);
      if (dataProvider == null) continue;
      Object data = getDataManager().getDataFromProvider(dataProvider, dataId, null);
      if (data != null) return data;
    }
  }
  return null;
}
 
Example #12
Source File: TabbedContentTabLabel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void removeNotify() {
  super.removeNotify();
  JBPopup popup = SoftReference.dereference(myPopupReference);
  if (popup != null) {
    Disposer.dispose(popup);
    myPopupReference = null;
  }
}
 
Example #13
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void cacheResults(@Nonnull PsiElement from, @Nullable PsiElement upUntil, @Nonnull PsiFile hostFile, @Nullable InjectionResult result) {
  Getter<InjectionResult> cachedRef = result == null || result.isEmpty() ? getEmptyInjectionResult(hostFile) : new SoftReference<>(result);
  for (PsiElement e = from; e != upUntil && e != null; e = e.getParent()) {
    ProgressManager.checkCanceled();
    e.putUserData(INJECTED_PSI, cachedRef);
  }
}
 
Example #14
Source File: ImagePreviewComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static JComponent getPreviewComponent(@Nullable final PsiElement parent) {
  if (parent == null) {
    return null;
  }
  final PsiReference[] references = parent.getReferences();
  for (final PsiReference reference : references) {
    final PsiElement fileItem = reference.resolve();
    if (fileItem instanceof PsiFileSystemItem) {
      final PsiFileSystemItem item = (PsiFileSystemItem)fileItem;
      if (!item.isDirectory()) {
        final VirtualFile file = item.getVirtualFile();
        if (file != null && supportedExtensions.contains(file.getExtension())) {
          try {
            refresh(file);
            SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
            final BufferedImage image = SoftReference.dereference(imageRef);
            if (image != null) {
              return new ImagePreviewComponent(image, file.getLength());
            }
          }
          catch (IOException ignored) {
            // nothing
          }
        }
      }
    }
  }

  return null;
}
 
Example #15
Source File: LeafElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getText() {
  CharSequence text = myText;
  if (text.length() > 1000 && !(text instanceof String)) { // e.g. a large text file
    String cachedText = SoftReference.dereference(getUserData(CACHED_TEXT));
    if (cachedText == null) {
      cachedText = text.toString();
      putUserData(CACHED_TEXT, new SoftReference<>(cachedText));
    }
    return cachedText;
  }

  return text.toString();
}
 
Example #16
Source File: ApiDebuggerBundle.java    From ApiDebugger with Apache License 2.0 5 votes vote down vote up
private static ResourceBundle getBundle() {
    ResourceBundle bundle = SoftReference.dereference(mBundleReference);
    if (bundle == null) {
        bundle = ResourceBundle.getBundle(BUNDLE);
        mBundleReference = new java.lang.ref.SoftReference<>(bundle);
    }
    return bundle;
}
 
Example #17
Source File: XDebuggerEditorBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected XDebuggerEditorBase(final Project project,
                              @Nonnull XDebuggerEditorsProvider debuggerEditorsProvider,
                              @Nonnull EvaluationMode mode,
                              @Nullable @NonNls String historyId,
                              final @Nullable XSourcePosition sourcePosition) {
  myProject = project;
  myDebuggerEditorsProvider = debuggerEditorsProvider;
  myMode = mode;
  myHistoryId = historyId;
  mySourcePosition = sourcePosition;

  myChooseFactory.setToolTipText(XDebuggerBundle.message("xdebugger.evaluate.language.hint"));
  myChooseFactory.setBorder(JBUI.Borders.empty(0, 3, 0, 3));
  new ClickListener() {
    @Override
    public boolean onClick(@Nonnull MouseEvent e, int clickCount) {
      if (myChooseFactory.isEnabled()) {
        ListPopup oldPopup = SoftReference.dereference(myPopup);
        if (oldPopup != null && !oldPopup.isDisposed()) {
          oldPopup.cancel();
          myPopup = null;
          return true;
        }
        ListPopup popup = createLanguagePopup();
        popup.showUnderneathOf(myChooseFactory);
        myPopup = new WeakReference<>(popup);
        return true;
      }
      return false;
    }
  }.installOn(myChooseFactory);
}
 
Example #18
Source File: DocumentationManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void restorePopupBehavior() {
  super.restorePopupBehavior();
  Component previouslyFocused = SoftReference.dereference(myFocusedBeforePopup);
  if (previouslyFocused != null && previouslyFocused.isShowing()) {
    UIUtil.runWhenFocused(previouslyFocused, () -> updateComponent(true));
    IdeFocusManager.getInstance(myProject).requestFocus(previouslyFocused, true);
  }
}
 
Example #19
Source File: FileTrees.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void forEachCachedPsi(Consumer<? super StubBasedPsiElementBase> consumer) {
  ContainerUtil.process(myRefToPsi, ref -> {
    StubBasedPsiElementBase psi = SoftReference.dereference(ref);
    if (psi != null) {
      consumer.accept(psi);
    }
    return true;
  });
}
 
Example #20
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
private DataContext getDataContext() {
  Component referenceComponent;
  if (myReferenceComponent == null) {
    referenceComponent = IdeFocusManager.getInstance(myManager.myProject).getFocusOwner();
    myReferenceComponent = new WeakReference<>(referenceComponent);
  }
  else {
    referenceComponent = SoftReference.dereference(myReferenceComponent);
    if (referenceComponent == null || !referenceComponent.isShowing()) referenceComponent = myHint.getComponent();
  }
  return DataManager.getInstance().getDataContext(referenceComponent);
}
 
Example #21
Source File: LazyParseableElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public CharSequence getChars() {
  CharSequence text = myText();
  if (text == null) {
    // use super.getText() instead of super.getChars() to avoid extra myText() call
    text = super.getText();
    myText = new SoftReference<>(text);
  }
  return text;
}
 
Example #22
Source File: LazyParseableElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getText() {
  CharSequence text = myText();
  if (text != null) {
    return text.toString();
  }
  String s = super.getText();
  myText = new SoftReference<>(s);
  return s;
}
 
Example #23
Source File: ContentRevisionCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
public byte[] getBytes(FilePath path, VcsRevisionNumber number, @Nonnull VcsKey vcsKey, @Nonnull UniqueType type) {
  synchronized (myLock) {
    final SoftReference<byte[]> reference = myCache.get(new Key(path, number, vcsKey, type));
    return SoftReference.dereference(reference);
  }
}
 
Example #24
Source File: SmartPointerManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static <E extends PsiElement> SmartPsiElementPointerImpl<E> getCachedPointer(@Nonnull E element) {
  Reference<SmartPsiElementPointerImpl<?>> data = element.getUserData(CACHED_SMART_POINTER_KEY);
  SmartPsiElementPointerImpl<?> cachedPointer = SoftReference.dereference(data);
  if (cachedPointer != null) {
    PsiElement cachedElement = cachedPointer.getElement();
    if (cachedElement != element) {
      return null;
    }
  }
  //noinspection unchecked
  return (SmartPsiElementPointerImpl<E>)cachedPointer;
}
 
Example #25
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public FrozenDocument freeze() {
  FrozenDocument frozen = myFrozen;
  if (frozen == null) {
    synchronized (myLineSetLock) {
      frozen = myFrozen;
      if (frozen == null) {
        myFrozen = frozen = new FrozenDocument(myText, myLineSet, myModificationStamp, SoftReference.dereference(myTextString));
      }
    }
  }
  return frozen;
}
 
Example #26
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private String doGetText() {
  String s = SoftReference.dereference(myTextString);
  if (s == null) {
    myTextString = new SoftReference<>(s = myText.toString());
  }
  return s;
}
 
Example #27
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void getSaveRMTree(@Nonnull VirtualFile f, @Nonnull Key<Reference<RangeMarkerTree<RangeMarkerEx>>> key, @Nonnull RangeMarkerTree<RangeMarkerEx> tree) {
  RMTreeReference freshRef = new RMTreeReference(tree, f);
  Reference<RangeMarkerTree<RangeMarkerEx>> oldRef;
  do {
    oldRef = f.getUserData(key);
  }
  while (!f.replace(key, oldRef, freshRef));
  RangeMarkerTree<RangeMarkerEx> oldTree = SoftReference.dereference(oldRef);

  if (oldTree == null) {
    // no tree was saved in virtual file before. happens when created new document.
    // or the old tree got gc-ed, because no reachable markers retaining it are left alive. good riddance.
    return;
  }

  // old tree was saved in the virtual file. Have to transfer markers from there.
  TextRange myDocumentRange = new TextRange(0, getTextLength());
  oldTree.processAll(r -> {
    if (r.isValid() && myDocumentRange.contains(r)) {
      registerRangeMarker(r, r.getStartOffset(), r.getEndOffset(), r.isGreedyToLeft(), r.isGreedyToRight(), 0);
    }
    else {
      ((RangeMarkerImpl)r).invalidate("document was gc-ed and re-created");
    }
    return true;
  });
}
 
Example #28
Source File: FrozenDocument.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getText() {
  String s = SoftReference.dereference(myTextString);
  if (s == null) {
    myTextString = new SoftReference<>(s = myText.toString());
  }
  return s;
}
 
Example #29
Source File: FrozenDocument.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private LineSet getLineSet() {
  LineSet lineSet = SoftReference.dereference(myLineSet);
  if (lineSet == null) {
    myLineSet = new SoftReference<>(lineSet = LineSet.createLineSet(myText));
  }
  return lineSet;
}
 
Example #30
Source File: RecursionManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
MemoizedValue getMemoizedValue(MyKey realKey) {
  List<SoftReference<MemoizedValue>> refs = intermediateCache.get(realKey);
  if (refs != null) {
    for (SoftReference<MemoizedValue> ref : refs) {
      MemoizedValue value = SoftReference.dereference(ref);
      if (value != null && value.isActual(this)) {
        return value;
      }
    }
  }
  return null;
}