Пример #1
0
  @Override
  @NotNull
  public StubTree getStubTree() {
    ApplicationManager.getApplication().assertReadAccessAllowed();

    StubTree stubTree = SoftReference.dereference(myStub);
    if (stubTree != null) return stubTree;

    // build newStub out of lock to avoid deadlock
    StubTree newStubTree =
        (StubTree) StubTreeLoader.getInstance().readOrBuild(getProject(), getVirtualFile(), this);
    if (newStubTree == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("No stub for class file in index: " + getVirtualFile().getPresentableUrl());
      }
      newStubTree = new StubTree(new PsiJavaFileStubImpl("corrupted_class_files", true));
    }

    synchronized (myStubLock) {
      stubTree = SoftReference.dereference(myStub);
      if (stubTree != null) return stubTree;

      stubTree = newStubTree;

      @SuppressWarnings("unchecked")
      PsiFileStubImpl<PsiFile> fileStub = (PsiFileStubImpl) stubTree.getRoot();
      fileStub.setPsi(this);

      myStub = new SoftReference<StubTree>(stubTree);
    }

    return stubTree;
  }
Пример #2
0
 private static RefCountHolder getInstance(
     @NotNull PsiFile file, @NotNull ProgressIndicator indicator, boolean acquire) {
   HolderReference ref = file.getUserData(REF_COUNT_HOLDER_IN_FILE_KEY);
   RefCountHolder holder = com.intellij.reference.SoftReference.dereference(ref);
   if (holder == null && acquire) {
     holder = new RefCountHolder(file);
     HolderReference newRef = new HolderReference(holder);
     while (true) {
       boolean replaced =
           ((UserDataHolderEx) file).replace(REF_COUNT_HOLDER_IN_FILE_KEY, ref, newRef);
       if (replaced) {
         ref = newRef;
         break;
       }
       ref = file.getUserData(REF_COUNT_HOLDER_IN_FILE_KEY);
       RefCountHolder newHolder = com.intellij.reference.SoftReference.dereference(ref);
       if (newHolder != null) {
         holder = newHolder;
         break;
       }
     }
   }
   if (ref != null) {
     if (acquire) {
       ref.acquire(indicator);
     } else {
       ref.release(indicator);
     }
   }
   return holder;
 }
Пример #3
0
  public static PsiCodeBlock getOrCreatePsiCodeBlock(GrOpenBlock block) {
    if (block == null) return null;

    final SoftReference<PsiCodeBlock> ref = block.getUserData(PSI_CODE_BLOCK);
    final PsiCodeBlock body = ref == null ? null : ref.get();
    if (body != null) return body;
    final GrSyntheticCodeBlock newBody = new GrSyntheticCodeBlock(block);
    block.putUserData(PSI_CODE_BLOCK, new SoftReference<PsiCodeBlock>(newBody));
    return newBody;
  }
Пример #4
0
  public static PsiTypeElement getOrCreateTypeElement(GrTypeElement typeElement) {
    if (typeElement == null) return null;

    final SoftReference<PsiTypeElement> ref = typeElement.getUserData(PSI_TYPE_ELEMENT);
    final PsiTypeElement element = ref == null ? null : ref.get();
    if (element != null) return element;
    final GrSyntheticTypeElement newTypeElement = new GrSyntheticTypeElement(typeElement);
    typeElement.putUserData(PSI_TYPE_ELEMENT, new SoftReference<PsiTypeElement>(newTypeElement));
    return newTypeElement;
  }
Пример #5
0
  public static PsiExpression getOrCreatePisExpression(GrExpression expr) {
    if (expr == null) return null;

    final SoftReference<PsiExpression> ref = expr.getUserData(PSI_EXPRESSION);
    final PsiExpression element = ref == null ? null : ref.get();
    if (element != null) return element;
    final GrSyntheticExpression newExpr = new GrSyntheticExpression(expr);
    expr.putUserData(PSI_EXPRESSION, new SoftReference<PsiExpression>(newExpr));
    return newExpr;
  }
 @Nullable
 public AndroidTargetData getTargetData(@NotNull IAndroidTarget target) {
   final SoftReference<AndroidTargetData> targetDataRef = myTargetDatas.get(target);
   AndroidTargetData targetData = targetDataRef != null ? targetDataRef.get() : null;
   if (targetData == null) {
     targetData = new AndroidTargetData(this, target);
     myTargetDatas.put(target, new SoftReference<AndroidTargetData>(targetData));
   }
   return targetData;
 }
  @Override
  public boolean isSoftWrappingEnabled() {
    if (!myUseSoftWraps
        || (!myEditor.myUseNewRendering && myEditor.isOneLineMode())
        || myEditor.isPurePaintingMode()) {
      return false;
    }

    // We check that current thread is EDT because attempt to retrieve information about visible
    // area width may fail otherwise
    Application application = ApplicationManager.getApplication();
    Thread lastEdt = myLastEdt.get();
    Thread currentThread = Thread.currentThread();
    if (lastEdt != currentThread) {
      if (application.isDispatchThread()) {
        myLastEdt = new SoftReference<Thread>(currentThread);
      } else {
        myLastEdt = new SoftReference<Thread>(null);
        return false;
      }
    }

    Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea();
    return visibleArea.width > 0 && visibleArea.height > 0;
  }
Пример #8
0
 private void clearStub(@NotNull String reason) {
   StubTree stubHolder = SoftReference.dereference(myStub);
   if (stubHolder != null) {
     ((PsiFileStubImpl<?>) stubHolder.getRoot()).clearPsi(reason);
   }
   myStub = null;
 }
 private static ResourceBundle getBundle() {
   ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle);
   if (bundle == null) {
     bundle = ResourceBundle.getBundle(BUNDLE);
     ourBundle = new SoftReference<ResourceBundle>(bundle);
   }
   return bundle;
 }
 @Nullable
 private TIntIntHashMap getNewToOldLineMapping(final long date) {
   if (myNewToOldLines == null) {
     myNewToOldLines = doGetLineMapping(date, false);
     if (myNewToOldLines == null) return null;
   }
   return myNewToOldLines.get();
 }
 @Nullable
 private TIntIntHashMap getOldToNewLineMapping(final long date) {
   if (myOldToNewLines == null) {
     myOldToNewLines = doGetLineMapping(date, true);
     if (myOldToNewLines == null) return null;
   }
   return myOldToNewLines.get();
 }
Пример #12
0
  @Nullable
  private StubTree derefStub() {
    if (myStub == null) return null;

    synchronized (PsiLock.LOCK) {
      return SoftReference.dereference(myStub);
    }
  }
  @NotNull
  public static AndroidDependenciesCache getInstance(@NotNull Module module) {
    AndroidDependenciesCache cache = SoftReference.dereference(module.getUserData(KEY));

    if (cache == null) {
      cache = new AndroidDependenciesCache(module);
      module.putUserData(KEY, new SoftReference<AndroidDependenciesCache>(cache));
    }
    return cache;
  }
  public PsiJavaPackage findPackage(@NotNull String qualifiedName, GlobalSearchScope searchScope) {
    PackageCache cache = SoftReference.dereference(packageCache);
    if (cache == null) {
      packageCache = new SoftReference<PackageCache>(cache = new PackageCache());
    }

    Pair<String, GlobalSearchScope> key =
        new Pair<String, GlobalSearchScope>(qualifiedName, searchScope);
    PsiJavaPackage aPackage = cache.packageInScopeCache.get(key);
    if (aPackage != null) {
      return aPackage;
    }

    KotlinPsiElementFinderWrapper[] finders = filteredFinders();

    Boolean packageFoundInAllScope = cache.hasPackageInAllScopeCache.get(qualifiedName);
    if (packageFoundInAllScope != null) {
      if (!packageFoundInAllScope.booleanValue()) return null;

      // Package was found in AllScope with some of finders but is absent in packageCache for
      // current scope.
      // We check only finders that depend on scope.
      for (KotlinPsiElementFinderWrapper finder : finders) {
        if (!finder.isSameResultForAnyScope()) {
          aPackage = finder.findPackage(qualifiedName, searchScope);
          if (aPackage != null) {
            return ConcurrencyUtil.cacheOrGet(cache.packageInScopeCache, key, aPackage);
          }
        }
      }
    } else {
      for (KotlinPsiElementFinderWrapper finder : finders) {
        aPackage = finder.findPackage(qualifiedName, searchScope);

        if (aPackage != null) {
          return ConcurrencyUtil.cacheOrGet(cache.packageInScopeCache, key, aPackage);
        }
      }

      boolean found = false;
      for (KotlinPsiElementFinderWrapper finder : finders) {
        if (!finder.isSameResultForAnyScope()) {
          aPackage = finder.findPackage(qualifiedName, GlobalSearchScope.allScope(project));
          if (aPackage != null) {
            found = true;
            break;
          }
        }
      }

      cache.hasPackageInAllScopeCache.put(qualifiedName, found);
    }

    return null;
  }
Пример #15
0
  public StubTree calcStubTree() {
    FileElement fileElement = calcTreeElement();
    synchronized (myStubFromTreeLock) {
      SoftReference<StubTree> ref = fileElement.getUserData(STUB_TREE_IN_PARSED_TREE);
      StubTree tree = SoftReference.dereference(ref);

      if (tree == null) {
        ApplicationManager.getApplication().assertReadAccessAllowed();
        IElementType contentElementType = getContentElementType();
        if (!(contentElementType instanceof IStubFileElementType)) {
          VirtualFile vFile = getVirtualFile();
          String message =
              "ContentElementType: "
                  + contentElementType
                  + "; file: "
                  + this
                  + "\n\t"
                  + "Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = "
                  + Boolean.TRUE.equals(getUserData(BUILDING_STUB))
                  + "\n\t"
                  + "getTreeElement() = "
                  + getTreeElement()
                  + "\n\t"
                  + "vFile instanceof VirtualFileWithId = "
                  + (vFile instanceof VirtualFileWithId)
                  + "\n\t"
                  + "StubUpdatingIndex.canHaveStub(vFile) = "
                  + StubTreeLoader.getInstance().canHaveStub(vFile);
          rebuildStub();
          throw new AssertionError(message);
        }

        StubElement currentStubTree =
            ((IStubFileElementType) contentElementType).getBuilder().buildStubTree(this);
        if (currentStubTree == null) {
          throw new AssertionError(
              "Stub tree wasn't built for " + contentElementType + "; file: " + this);
        }

        tree = new StubTree((PsiFileStub) currentStubTree);
        tree.setDebugInfo("created in calcStubTree");
        try {
          TreeUtil.bindStubsToTree(this, tree);
        } catch (TreeUtil.StubBindingException e) {
          rebuildStub();
          throw new RuntimeException("Stub and PSI element type mismatch in " + getName(), e);
        }

        fileElement.putUserData(STUB_TREE_IN_PARSED_TREE, new SoftReference<StubTree>(tree));
      }

      return tree;
    }
  }
    public String getContent() throws VcsException {
      final String s = com.intellij.reference.SoftReference.dereference(myContent);
      if (s != null) {
        return s;
      }

      final String loaded = myLoader.convert(myPointer);
      myContent = new SoftReference<String>(loaded);

      return loaded;
    }
  private static PsiFile createFileCopy(PsiFile file, long caret, long selEnd) {
    final VirtualFile virtualFile = file.getVirtualFile();
    boolean mayCacheCopy =
        file.isPhysical()
            &&
            // we don't want to cache code fragment copies even if they appear to be physical
            virtualFile != null
            && virtualFile.isInLocalFileSystem();
    long combinedOffsets = caret + (selEnd << 32);
    if (mayCacheCopy) {
      final Trinity<PsiFile, Document, Long> cached =
          SoftReference.dereference(file.getUserData(FILE_COPY_KEY));
      if (cached != null
          && cached.first.getClass().equals(file.getClass())
          && isCopyUpToDate(cached.second, cached.first)) {
        final PsiFile copy = cached.first;
        if (copy.getViewProvider().getModificationStamp()
                > file.getViewProvider().getModificationStamp()
            && cached.third.longValue() != combinedOffsets) {
          // the copy PSI might have some caches that are not cleared on its modification because
          // there are no events in the copy
          //   so, clear all the caches
          // hopefully it's a rare situation that the user invokes completion in different parts of
          // the file
          //   without modifying anything physical in between
          ((PsiModificationTrackerImpl) file.getManager().getModificationTracker()).incCounter();
        }
        final Document document = cached.second;
        assert document != null;
        file.putUserData(
            FILE_COPY_KEY,
            new SoftReference<Trinity<PsiFile, Document, Long>>(
                Trinity.create(copy, document, combinedOffsets)));

        Document originalDocument = file.getViewProvider().getDocument();
        assert originalDocument != null;
        assert originalDocument.getTextLength() == file.getTextLength() : originalDocument;
        document.setText(originalDocument.getImmutableCharSequence());
        return copy;
      }
    }

    final PsiFile copy = (PsiFile) file.copy();
    if (mayCacheCopy) {
      final Document document = copy.getViewProvider().getDocument();
      assert document != null;
      file.putUserData(
          FILE_COPY_KEY,
          new SoftReference<Trinity<PsiFile, Document, Long>>(
              Trinity.create(copy, document, combinedOffsets)));
    }
    return copy;
  }
Пример #18
0
  private FileElement derefTreeElement() {
    Getter<FileElement> pointer = myTreeElementPointer;
    FileElement treeElement = SoftReference.deref(pointer);
    if (treeElement != null) return treeElement;

    synchronized (PsiLock.LOCK) {
      if (myTreeElementPointer == pointer) {
        myTreeElementPointer = null;
      }
    }
    return null;
  }
Пример #19
0
  @Override
  public String getText() {
    if (myText.length() > 1000 && !(myText instanceof String)) { // e.g. a large text file
      String text = SoftReference.dereference(getUserData(CACHED_TEXT));
      if (text == null) {
        text = myText.toString();
        putUserData(CACHED_TEXT, new SoftReference<String>(text));
      }
      return text;
    }

    return myText.toString();
  }
Пример #20
0
  /**
   * Load image data for file and put user data attributes into file.
   *
   * @param file File
   * @return true if file image is loaded.
   * @throws java.io.IOException if image can not be loaded
   */
  private static boolean refresh(@NotNull VirtualFile file) throws IOException {
    Long loadedTimeStamp = file.getUserData(TIMESTAMP_KEY);
    SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
    if (loadedTimeStamp == null
        || loadedTimeStamp.longValue() != file.getTimeStamp()
        || SoftReference.dereference(imageRef) == null) {
      try {
        final byte[] content = file.contentsToByteArray();

        if (ICO_FORMAT.equalsIgnoreCase(file.getExtension())) {
          try {
            final BufferedImage image =
                ICO_IMAGE_PARSER.getBufferedImage(new ByteSourceArray(content), null);
            file.putUserData(FORMAT_KEY, ICO_FORMAT);
            file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image));
            return true;
          } catch (ImageReadException ignore) {
          }
        }

        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<>(image));
              return true;
            } finally {
              imageReader.dispose();
            }
          }
        } finally {
          imageInputStream.close();
        }
      } finally {
        // We perform loading no more needed
        file.putUserData(TIMESTAMP_KEY, file.getTimeStamp());
      }
    }
    return false;
  }
 @NotNull
 @Override
 public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state)
     throws ParserException {
   if (myKey != state.getKey()) {
     myKey = state.getKey();
     myCache.clear();
   }
   final SoftReference<Pair<R, State>> ref = myCache.get(state.getPos());
   final Pair<R, State> cached = SoftReference.dereference(ref);
   if (cached != null) {
     return cached;
   }
   final Pair<R, State> result = myParser.parse(tokens, state);
   myCache.put(state.getPos(), new SoftReference<Pair<R, State>>(result));
   return result;
 }
Пример #22
0
 private PsiClass[] getCachedClassInDumbMode(String name) {
   Map<String, PsiClass[]> map = SoftReference.dereference(myClassCache);
   if (map == null) {
     map = new HashMap<String, PsiClass[]>();
     for (PsiClass psiClass : getClasses(new EverythingGlobalScope(getProject()))) {
       String psiClassName = psiClass.getName();
       if (psiClassName != null) {
         PsiClass[] existing = map.get(psiClassName);
         map.put(
             psiClassName,
             existing == null ? new PsiClass[] {psiClass} : ArrayUtil.append(existing, psiClass));
       }
     }
     myClassCache = new SoftReference<Map<String, PsiClass[]>>(map);
   }
   PsiClass[] classes = map.get(name);
   return classes == null ? PsiClass.EMPTY_ARRAY : classes;
 }
  @Nullable
  private SoftReference<TIntIntHashMap> doGetLineMapping(final long date, boolean oldToNew) {
    final VirtualFile f = getVirtualFile();
    final byte[] oldContent;
    synchronized (LOCK) {
      if (myOldContent == null) {
        if (ApplicationManager.getApplication().isDispatchThread()) return null;
        final LocalHistory localHistory = LocalHistory.getInstance();
        byte[] byteContent =
            localHistory.getByteContent(
                f,
                new FileRevisionTimestampComparator() {
                  public boolean isSuitable(long revisionTimestamp) {
                    return revisionTimestamp < date;
                  }
                });

        if (byteContent == null && f.getTimeStamp() > date) {
          byteContent = loadFromVersionControl(date, f);
        }
        myOldContent = new SoftReference<byte[]>(byteContent);
      }
      oldContent = myOldContent.get();
    }

    if (oldContent == null) return null;
    String[] coveredLines = getCoveredLines(oldContent, f);
    final Document document = myDocument;
    if (document == null) return null;
    String[] currentLines = getUpToDateLines(document);

    String[] oldLines = oldToNew ? coveredLines : currentLines;
    String[] newLines = oldToNew ? currentLines : coveredLines;

    Diff.Change change;
    try {
      change = Diff.buildChanges(oldLines, newLines);
    } catch (FilesTooBigForDiffException e) {
      LOG.info(e);
      return null;
    }
    return new SoftReference<TIntIntHashMap>(
        getCoverageVersionToCurrentLineMapping(change, oldLines.length));
  }
Пример #24
0
  @Override
  public void onContentReload() {
    ApplicationManager.getApplication().assertWriteAccessAllowed();

    synchronized (myStubLock) {
      StubTree stubTree = SoftReference.dereference(myStub);
      myStub = null;
      if (stubTree != null) {
        //noinspection unchecked
        ((PsiFileStubImpl) stubTree.getRoot()).clearPsi("cls onContentReload");
      }
    }

    ClsPackageStatementImpl packageStatement = new ClsPackageStatementImpl(this);
    synchronized (myMirrorLock) {
      putUserData(CLS_DOCUMENT_LINK_KEY, null);
      myMirrorFileElement = null;
      myPackageStatement = packageStatement;
    }

    myLanguageLevel = null;
  }
Пример #25
0
  @NotNull
  private PsiClass[] getCachedClassesByName(@NotNull String name) {
    if (DumbService.getInstance(getProject()).isDumb()) {
      return getCachedClassInDumbMode(name);
    }

    Map<String, PsiClass[]> map = SoftReference.dereference(myClassCache);
    if (map == null) {
      myClassCache =
          new SoftReference<Map<String, PsiClass[]>>(
              map = new ConcurrentSoftValueHashMap<String, PsiClass[]>());
    }
    PsiClass[] classes = map.get(name);
    if (classes != null) {
      return classes;
    }

    final String qName = getQualifiedName();
    final String classQName = !qName.isEmpty() ? qName + "." + name : name;
    map.put(
        name,
        classes = getFacade().findClasses(classQName, new EverythingGlobalScope(getProject())));
    return classes;
  }
Пример #26
0
 private CfmlLangDictionary getProjectDictionary() {
   String languageLevel = getLanguageLevel();
   CfmlLangDictionary dictionary;
   if (languageLevel.equals(CfmlLanguage.CF8)) {
     dictionary = SoftReference.dereference(myCF8Dictionary);
     if (dictionary == null) {
       synchronized (CfmlLangInfo.class) {
         dictionary = SoftReference.dereference(myCF8Dictionary);
         if (dictionary == null) {
           dictionary = new CfmlLangDictionary("scopes.txt", "cf8_tags.xml");
           myCF8Dictionary = new SoftReference<CfmlLangDictionary>(dictionary);
         }
       }
     }
   } else if (languageLevel.equals(CfmlLanguage.RAILO)) {
     dictionary = SoftReference.dereference(myRailoDictionary);
     if (dictionary == null) {
       synchronized (CfmlLangInfo.class) {
         dictionary = SoftReference.dereference(myRailoDictionary);
         if (dictionary == null) {
           dictionary = new CfmlLangDictionary("scopes.txt", "Railo_tags.xml");
           myRailoDictionary = new SoftReference<CfmlLangDictionary>(dictionary);
         }
       }
     }
   } else /*if (languageLevel.equals(CfmlLanguage.CF9))*/ {
     dictionary = SoftReference.dereference(myCF9Dictionary);
     if (dictionary == null) {
       synchronized (CfmlLangInfo.class) {
         dictionary = SoftReference.dereference(myCF9Dictionary);
         if (dictionary == null) {
           dictionary = new CfmlLangDictionary("scopes.txt", "tags.xml");
           myCF9Dictionary = new SoftReference<CfmlLangDictionary>(dictionary);
         }
       }
     }
   }
   return dictionary;
 }
 private <T extends PsiExpression> PsiType getCachedType(T expr) {
   Reference<PsiType> reference = myCalculatedTypes.get(expr);
   return SoftReference.dereference(reference);
 }
Пример #28
0
 @Nullable
 private Project getProject() {
   return SoftReference.dereference(myProject);
 }
Пример #29
0
 @Nullable
 public Balloon getBalloon() {
   return SoftReference.dereference(myBalloonRef);
 }
Пример #30
0
 @Nullable
 public static BufferedImage getImage(@NotNull VirtualFile file) throws IOException {
   refresh(file);
   SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
   return SoftReference.dereference(imageRef);
 }