Java Code Examples for com.intellij.openapi.vfs.VirtualFile#getUserData()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getUserData() . 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: WeaveEditor.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Language substituteLanguage(@NotNull Project project, @NotNull VirtualFile file) {
    Language language = null;

    if (file != null) {
        //logger.debug("*** VFile is " + file);
        String newDataType = file.getUserData(WeaveEditor.newFileDataTypeKey);
        //logger.debug("*** newDataType is " + newDataType);
        if (newDataType != null) {
            language = WeaveEditor.getLanguage(newDataType);
            //logger.debug("*** Resolved Language is " + language);
        }
    }

    return language;
}
 
Example 2
Source File: LastUnchangedContentTracker.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Long getLastSavedStamp(VirtualFile file) {
  Long l = file.getUserData(LAST_TS_KEY);
  if (l == null) {
    try {
      final DataInputStream stream = LAST_TS_ATTR.readAttribute(file);
      if (stream != null) {
        try {
          l = stream.readLong();
        }
        finally {
          stream.close();
        }
      }
    }
    catch (IOException e) {
      LOG.info(e);
    }
  }
  return l;
}
 
Example 3
Source File: LightFileDocumentManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Document getCachedDocument(@Nonnull VirtualFile file) {
  if (myCachedDocumentKey != null) {
    return file.getUserData(myCachedDocumentKey);
  }
  return null;
}
 
Example 4
Source File: DocumentUndoProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isUndoable(@Nonnull UndoManagerImpl undoManager, @Nonnull Document document) {
  DocumentReference ref = DocumentReferenceManager.getInstance().create(document);
  VirtualFile file = ref.getFile();

  // Allow undo even from refresh if requested
  if (file != null && file.getUserData(UndoConstants.FORCE_RECORD_UNDO) == Boolean.TRUE) {
    return true;
  }
  return !UndoManagerImpl.isRefresh() || undoManager.isUndoOrRedoAvailable(ref);
}
 
Example 5
Source File: PushedFilePropertiesUpdaterImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T> void updateValue(final Project project, final VirtualFile fileOrDir, final T value, final FilePropertyPusher<T> pusher) {
  final T oldValue = fileOrDir.getUserData(pusher.getFileDataKey());
  if (value != oldValue) {
    fileOrDir.putUserData(pusher.getFileDataKey(), value);
    try {
      pusher.persistAttribute(project, fileOrDir, value);
    }
    catch (IOException e) {
      LOG.error(e);
    }
  }
}
 
Example 6
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 7
Source File: MockFileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Document getDocument(@Nonnull VirtualFile file) {
  Document document = file.getUserData(MOCK_DOC_KEY);
  if (document == null) {
    if (file.isDirectory() || isBinaryWithoutDecompiler(file)) return null;

    CharSequence text = LoadTextUtil.loadText(file);
    document = myFactory.fun(text);
    document.putUserData(MOCK_VIRTUAL_FILE_KEY, file);
    document = file.putUserDataIfAbsent(MOCK_DOC_KEY, document);
  }
  return document;
}
 
Example 8
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 9
Source File: GraphQLIntrospectionEditorTabTitleProvider.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Nullable
@Override
public String getEditorTabTitle(@NotNull Project project, @NotNull VirtualFile file) {
    Boolean isIntrospectionSDL = file.getUserData(GraphQLSchemaKeys.IS_GRAPHQL_INTROSPECTION_SDL);
    if (Boolean.TRUE.equals(isIntrospectionSDL)) {
        return "GraphQL Schema (" + StringUtils.substringAfterLast(file.getName(), "/") + ")";
    }
    return null;
}
 
Example 10
Source File: Util.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
public static long getModificationStamp(VirtualFile file) {
    long ret = -1;
    Long temporary = file.getUserData(Util.MODIFICATION_DATE_KEY);
    if(temporary == null || temporary <= 0) {
        if(file instanceof NewVirtualFile) {
            final DataInputStream is = MODIFICATION_STAMP_FILE_ATTRIBUTE.readAttribute(file);
            if(is != null) {
                try {
                    try {
                        if(is.available() > 0) {
                            String value = IOUtil.readString(is);
                            ret = convertToLong(value, ret);
                            if(ret > 0) {
                                file.putUserData(Util.MODIFICATION_DATE_KEY, ret);
                            }
                        }
                    } finally {
                        is.close();
                    }
                } catch(IOException e) {
                    // Ignore it but we might need to throw an exception
                    String message = e.getMessage();
                }
            }
        }
    } else {
        ret = temporary;
    }
    return ret;
}
 
Example 11
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 12
Source File: CsvStorageHelper.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public static String getRelativeFileUrl(Project project, VirtualFile virtualFile) {
    if (project == null || virtualFile == null) {
        return null;
    }
    String url = virtualFile.getUserData(RELATIVE_FILE_URL);
    if (url == null && project.getBasePath() != null) {
        String projectDir = PathUtil.getLocalPath(project.getBasePath());
        url = PathUtil.getLocalPath(virtualFile.getPath())
                .replaceFirst("^" + Pattern.quote(projectDir), "");
        virtualFile.putUserData(RELATIVE_FILE_URL, url);
    }
    return url;
}
 
Example 13
Source File: GraphQLConfigPackageSet.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
/**
 * Gets whether a file is included.
 * Based on graphl-config: https://github.com/kamilkisiela/graphql-config/blob/b6785a7f0c1b84010cd6e9b94797796254d527b9/src/GraphQLProjectConfig.ts#L56
 * Note: Scratch files are always considered to be included since they are associated with a configuration package set but have a path that lies the project sources
 */
public boolean includesVirtualFile(@NotNull VirtualFile file) {
    if(file.getFileType() == ScratchFileType.INSTANCE) {
        // if a scratch file has been associated with a configuration it is considered to be included
        return true;
    }
    if(file.equals(configEntryFile.getVirtualFile())) {
        // the "entry" file is always considered included
        return true;
    }
    if(JsonFileType.INSTANCE.equals(file.getFileType())) {
        // the only JSON file that can be considered included is an introspection JSON file referenced as schemaPath
        if (schemaFilePath == null && Boolean.TRUE.equals(file.getUserData(GraphQLSchemaKeys.IS_GRAPHQL_INTROSPECTION_JSON))) {
            // new file created from introspection, so update schemaFilePath accordingly
            updateSchemaFilePath();
        }
        return file.getPath().equals(schemaFilePath);
    }
    final PsiFile jsonIntrospectionFile = file.getUserData(GraphQLSchemaKeys.GRAPHQL_INTROSPECTION_SDL_TO_JSON);
    if (jsonIntrospectionFile != null && jsonIntrospectionFile.getVirtualFile() != null) {
        // the file is the in-memory SDL derived from a JSON introspection file, so it's included if the JSON file is set as the schemaPath
        return jsonIntrospectionFile.getVirtualFile().getPath().equals(schemaFilePath);
    }

    String inclusionPath = file.getPath();
    if (file instanceof LightVirtualFile) {
        // the light file is potentially derived from a file on disk, so we should use the physical path to check for inclusion
        final VirtualFile originalFile = ((LightVirtualFile) file).getOriginalFile();
        if (originalFile != null) {
            inclusionPath = originalFile.getPath();
        }
    }

    return includesFilePath.computeIfAbsent(inclusionPath, filePath -> {
        if (filePath.equals(schemaFilePath)) {
            // fast-path for always including the schema file if present
            return true;
        }
        final String relativePath;
        if (filePath.startsWith(configBaseDirPath)) {
            relativePath = StringUtils.removeStart(filePath, configBaseDirPath);
        } else {
            // the file is outside the config base dir, so it's not included
            return false;
        }
        return (!hasIncludes || matchesGlobs(relativePath, this.configData.includes)) && !matchesGlobs(relativePath, this.configData.excludes);
    });
}
 
Example 14
Source File: ComponentScope.java    From litho with Apache License 2.0 4 votes vote down vote up
private static boolean containsInternal(VirtualFile file) {
  return StdFileTypes.JAVA.equals(file.getFileType()) && file.getUserData(KEY) != null;
}
 
Example 15
Source File: TrailingSpacesStripper.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void strip(@Nonnull final Document document) {
  if (!document.isWritable()) return;
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile file = fileDocumentManager.getFile(document);
  if (file == null || !file.isValid() || Boolean.TRUE.equals(DISABLE_FOR_FILE_KEY.get(file))) return;

  final EditorSettingsExternalizable settings = EditorSettingsExternalizable.getInstance();
  if (settings == null) return;

  final String overrideStripTrailingSpacesData = file.getUserData(OVERRIDE_STRIP_TRAILING_SPACES_KEY);
  final Boolean overrideEnsureNewlineData = file.getUserData(OVERRIDE_ENSURE_NEWLINE_KEY);
  @EditorSettingsExternalizable.StripTrailingSpaces
  String stripTrailingSpaces = overrideStripTrailingSpacesData != null ? overrideStripTrailingSpacesData : settings.getStripTrailingSpaces();
  final boolean doStrip = !stripTrailingSpaces.equals(EditorSettingsExternalizable.STRIP_TRAILING_SPACES_NONE);
  final boolean ensureEOL = overrideEnsureNewlineData != null ? overrideEnsureNewlineData.booleanValue() : settings.isEnsureNewLineAtEOF();

  if (doStrip) {
    final boolean inChangedLinesOnly = !stripTrailingSpaces.equals(EditorSettingsExternalizable.STRIP_TRAILING_SPACES_WHOLE);
    boolean success = strip(document, inChangedLinesOnly, settings.isKeepTrailingSpacesOnCaretLine());
    if (!success) {
      myDocumentsToStripLater.add(document);
    }
  }

  final int lines = document.getLineCount();
  if (ensureEOL && lines > 0) {
    final int start = document.getLineStartOffset(lines - 1);
    final int end = document.getLineEndOffset(lines - 1);
    if (start != end) {
      final CharSequence content = document.getCharsSequence();
      ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(document, null) {
        @Override
        public void run() {
          CommandProcessor.getInstance().runUndoTransparentAction(() -> {
            if (CharArrayUtil.containsOnlyWhiteSpaces(content.subSequence(start, end)) && doStrip) {
              document.deleteString(start, end);
            }
            else {
              document.insertString(end, "\n");
            }
          });
        }
      });
    }
  }
}
 
Example 16
Source File: LazyRangeMarkerFactoryImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
static WeakList<LazyMarker> getMarkers(@Nonnull VirtualFile file) {
  return file.getUserData(LazyRangeMarkerFactoryImpl.LAZY_MARKERS_KEY);
}
 
Example 17
Source File: EditorsSplitters.java    From consulo with Apache License 2.0 4 votes vote down vote up
static boolean isOpenedInBulk(@Nonnull VirtualFile file) {
  return file.getUserData(OPENED_IN_BULK) != null;
}
 
Example 18
Source File: SmartPointerTracker.java    From consulo with Apache License 2.0 4 votes vote down vote up
private boolean isActual(@Nonnull VirtualFile file, @Nonnull Key<SmartPointerTracker> key) {
  return file.getUserData(key) == this;
}
 
Example 19
Source File: FileManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
private FileViewProvider getRawCachedViewProvider(@Nonnull VirtualFile file) {
  ConcurrentMap<VirtualFile, FileViewProvider> map = myVFileToViewProviderMap.get();
  FileViewProvider viewProvider = map == null ? null : map.get(file);
  return viewProvider == null ? file.getUserData(myPsiHardRefKey) : viewProvider;
}
 
Example 20
Source File: SmartPointerTracker.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void assertActual(@Nonnull VirtualFile file, @Nonnull Key<SmartPointerTracker> refKey) {
  if (!isActual(file, refKey)) {
    SmartPointerTracker another = file.getUserData(refKey);
    throw new AssertionError("Smart pointer list mismatch:" + " size=" + size + ", ref.key=" + refKey + (another != null ? "; has another pointer list with size " + another.size : ""));
  }
}