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

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#putUserData() . These examples are extracted from open source projects. 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
private void updateTab(@NotNull JBTabsPaneImpl tabsPane, int index, WeaveIdentifier identifier, @NotNull WeaveDataType dataType) {
    Icon icon = iconsMap.containsKey(dataType.getText()) ? iconsMap.get(dataType.getText()) : AllIcons.FileTypes.Any_type;

    String title = (identifier == null ? "output" : identifier.getName());

    tabsPane.setTitleAt(index, title);
    tabsPane.setIconAt(index, icon);
    contentTypes.put(title, dataType.getText());

    VirtualFile vfile = inputOutputFiles.get(title);
    if (vfile != null) {
        vfile.putUserData(newFileDataTypeKey, dataType.getText());
        FileContentUtilCore.reparseFiles(vfile);
    }

    Editor oldEditor = editors.get(title);
    FileType newType = fileTypes.containsKey(dataType.getText()) ? fileTypes.get(dataType.getText()) : FileTypes.UNKNOWN;
    ((EditorEx) oldEditor).setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(project, newType));
}
 
Example 2
Source Project: aem-ide-tooling-4-intellij   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean visitFile(VirtualFile file) {
    file.putUserData(MODIFICATION_DATE_KEY, null);
    if(file instanceof NewVirtualFile) {
        final DataOutputStream os = MODIFICATION_STAMP_FILE_ATTRIBUTE.writeAttribute(file);
        try {
            try {
                IOUtil.writeString(StringUtil.notNullize("0"), os);
            } finally {
                os.close();
            }
        } catch(IOException e) {
            // Ignore it but we might need to throw an exception
            String message = e.getMessage();
        }
    }
    return recursive;
}
 
Example 3
Source Project: consulo   File: FileManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setViewProvider(@Nonnull final VirtualFile virtualFile, @Nullable final FileViewProvider fileViewProvider) {
  FileViewProvider prev = getRawCachedViewProvider(virtualFile);
  if (prev == fileViewProvider) return;
  if (prev != null) {
    DebugUtil.performPsiModification(null, () -> markInvalidated(prev));
  }

  if (fileViewProvider == null) {
    getVFileToViewProviderMap().remove(virtualFile);
  }
  else if (virtualFile instanceof LightVirtualFile) {
    virtualFile.putUserData(myPsiHardRefKey, fileViewProvider);
  }
  else {
    getVFileToViewProviderMap().put(virtualFile, fileViewProvider);
  }
}
 
Example 4
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 5
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
private static void saveContentReference(VirtualFile file, int contentId) {
  if (contentId == 0) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("saveContentReference without content for file = " + file);
    }
    return; // content not loaded yet, nothing to save
  }

  LOG.assertTrue(contentId > 0, contentId);

  if (LOG.isDebugEnabled()) {
    LOG.debug("saveContentReference file = " + file + ", id = " + contentId);
  }

  long stamp = file.getTimeStamp();
  try {
    final DataOutputStream contentStream = ACQUIRED_CONTENT_ATTR.writeAttribute(file);
    try {
      contentStream.writeInt(contentId);
    }
    finally {
      contentStream.close();
    }

    final DataOutputStream tsStream = LAST_TS_ATTR.writeAttribute(file);
    try {
      tsStream.writeLong(stamp);
    }
    finally {
      tsStream.close();
    }

    file.putUserData(LAST_TS_KEY, stamp);
  }
  catch (IOException e) {
    LOG.info(e);
  }
}
 
Example 7
public static void setParams(VirtualFile file, String params) {
    file.putUserData(MY_KEY, params);
    if (file instanceof NewVirtualFile) {
        try (DataOutputStream os = QUERY_PARAMS_FILE_ATTRIBUTE.writeAttribute(file)) {
            IOUtil.writeString(StringUtil.notNullize(params), os);
        } catch (IOException e) {
        }
    }
}
 
Example 8
Source Project: intellij   File: BlazeRClass.java    License: Apache License 2.0 5 votes vote down vote up
public BlazeRClass(PsiManager psiManager, AndroidFacet androidFacet, String packageName) {
  super(
      psiManager,
      new ResourcesSource() {
        @Override
        public String getPackageName() {
          return packageName;
        }

        @Override
        public LocalResourceRepository getResourceRepository() {
          return ResourceRepositoryManager.getAppResources(androidFacet);
        }

        @Override
        public ResourceNamespace getResourceNamespace() {
          return ResourceNamespace.RES_AUTO;
        }

        @Override
        public AndroidLightField.FieldModifier getFieldModifier() {
          return AndroidLightField.FieldModifier.NON_FINAL;
        }

        @Override
        public boolean isPublic(ResourceType resourceType, String resourceName) {
          return true;
        }
      });
  this.androidFacet = androidFacet;
  setModuleInfo(getModule(), false);
  VirtualFile virtualFile = myFile.getViewProvider().getVirtualFile();
  virtualFile.putUserData(
      MODULE_POINTER_KEY, ModulePointerManager.getInstance(getProject()).create(getModule()));
  virtualFile.putUserData(LIGHT_CLASS_KEY, ResourceRepositoryRClass.class);
}
 
Example 9
Source Project: intellij   File: BlazeRClass.java    License: Apache License 2.0 5 votes vote down vote up
public BlazeRClass(PsiManager psiManager, AndroidFacet androidFacet, String packageName) {
  super(
      psiManager,
      new ResourcesSource() {
        @Override
        public String getPackageName() {
          return packageName;
        }

        @Override
        public LocalResourceRepository getResourceRepository() {
          return ResourceRepositoryManager.getAppResources(androidFacet);
        }

        @Override
        public ResourceNamespace getResourceNamespace() {
          return ResourceNamespace.RES_AUTO;
        }

        @Override
        public AndroidLightField.FieldModifier getFieldModifier() {
          return AndroidLightField.FieldModifier.NON_FINAL;
        }

        @Override
        public boolean isPublic(ResourceType resourceType, String resourceName) {
          return true;
        }
      });
  this.androidFacet = androidFacet;
  setModuleInfo(getModule(), false);
  VirtualFile virtualFile = myFile.getViewProvider().getVirtualFile();
  virtualFile.putUserData(
      MODULE_POINTER_KEY, ModulePointerManager.getInstance(getProject()).create(getModule()));
  virtualFile.putUserData(LIGHT_CLASS_KEY, ResourceRepositoryRClass.class);
}
 
Example 10
Source Project: consulo   File: FileTypeManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void cacheAutoDetectedFileType(@Nonnull VirtualFile file, @Nonnull FileType fileType) {
  boolean wasAutodetectedAsText = fileType == PlainTextFileType.INSTANCE;
  boolean wasAutodetectedAsBinary = fileType == UnknownFileType.INSTANCE;

  int flags = BitUtil.set(0, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
  flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
  writeFlagsToCache(file, flags);
  if (file instanceof VirtualFileWithId) {
    int id = ((VirtualFileWithId)file).getId();
    flags = BitUtil.set(flags, AUTO_DETECT_WAS_RUN_MASK, true);
    flags = BitUtil.set(flags, ATTRIBUTES_WERE_LOADED_MASK, true);
    packedFlags.set(id, flags);

    if (wasAutodetectedAsText || wasAutodetectedAsBinary) {
      file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
      if (toLog()) {
        log("F: cacheAutoDetectedFileType(" + file.getName() + ") " +
            "cached to " + fileType.getName() +
            " flags = " + readableFlags(flags) +
            "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
      }
      return;
    }
  }
  file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, fileType);
  if (toLog()) {
    log("F: cacheAutoDetectedFileType(" + file.getName() + ") " +
        "cached to " + fileType.getName() +
        " flags = " + readableFlags(flags) +
        "; getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY): " + file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY));
  }
}
 
Example 11
Source Project: consulo   File: FileUndoProvider.java    License: Apache License 2.0 5 votes vote down vote up
private void beforeFileDeletion(@Nonnull VFileDeleteEvent e) {
  VirtualFile file = e.getFile();
  if (!shouldProcess(e, file)) {
    invalidateActionsFor(file);
    return;
  }
  if (isUndoable(e, file)) {
    file.putUserData(DELETION_WAS_UNDOABLE, createDocumentReference(file));
  }
  else {
    registerNonUndoableAction(file);
  }
}
 
Example 12
Source Project: consulo   File: FileUndoProvider.java    License: Apache License 2.0 5 votes vote down vote up
private void fileDeleted(@Nonnull VFileDeleteEvent e) {
  VirtualFile f = e.getFile();
  if (!shouldProcess(e, f)) return;

  DocumentReference ref = f.getUserData(DELETION_WAS_UNDOABLE);
  if (ref != null) {
    registerUndoableAction(ref);
    f.putUserData(DELETION_WAS_UNDOABLE, null);
  }
}
 
Example 13
private void handleBeforeEvent(VFileEvent event) {
  if (event instanceof VFileContentChangeEvent) {
    beforeContentsChange((VFileContentChangeEvent)event);
  }
  else if (event instanceof VFilePropertyChangeEvent && ((VFilePropertyChangeEvent)event).isRename() || event instanceof VFileMoveEvent) {
    VirtualFile f = Objects.requireNonNull(event.getFile());
    f.putUserData(WAS_VERSIONED_KEY, myGateway.isVersioned(f));
  }
  else if (event instanceof VFileDeleteEvent) {
    beforeFileDeletion((VFileDeleteEvent)event);
  }
}
 
Example 14
Source Project: consulo   File: PostfixLiveTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static PsiFile copyFile(@Nonnull PsiFile file, @Nonnull StringBuilder fileContentWithoutKey) {
  final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(file.getProject());
  PsiFile copy = psiFileFactory.createFileFromText(file.getName(), file.getFileType(), fileContentWithoutKey);
  VirtualFile vFile = copy.getVirtualFile();
  if (vFile != null) {
    vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
  }
  return copy;
}
 
Example 15
Source Project: litho   File: ComponentScope.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Includes {@link VirtualFile} of the given {@link PsiFile} in the scope and returns included
 * file.
 */
public static VirtualFile include(PsiFile file) {
  final VirtualFile vf = getVirtualFile(file);
  vf.putUserData(KEY, true);
  return vf;
}
 
Example 16
Source Project: consulo   File: DesktopEditorsSplitters.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected JPanel processFiles(@Nonnull List<Element> fileElements, final JPanel context, Element parent, UIAccess uiAccess) {
  final Ref<DesktopEditorWindow> windowRef = new Ref<>();
  UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
    DesktopEditorWindow editorWindow = context == null ? createEditorWindow() : findWindowWith(context);
    windowRef.set(editorWindow);
    if (editorWindow != null) {
      updateTabSizeLimit(editorWindow, parent.getAttributeValue(JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY.toString()));
    }
  });

  final DesktopEditorWindow window = windowRef.get();
  LOG.assertTrue(window != null);
  VirtualFile focusedFile = null;

  for (int i = 0; i < fileElements.size(); i++) {
    final Element file = fileElements.get(i);
    Element historyElement = file.getChild(HistoryEntry.TAG);
    String fileName = historyElement.getAttributeValue(HistoryEntry.FILE_ATTR);
    Activity activity = StartUpMeasurer.startActivity(PathUtil.getFileName(fileName), ActivityCategory.REOPENING_EDITOR);
    VirtualFile virtualFile = null;
    try {
      final FileEditorManagerImpl fileEditorManager = getManager();
      final HistoryEntry entry = HistoryEntry.createLight(fileEditorManager.getProject(), historyElement);
      virtualFile = entry.getFile();
      if (virtualFile == null) throw new InvalidDataException("No file exists: " + entry.getFilePointer().getUrl());
      virtualFile.putUserData(OPENED_IN_BULK, Boolean.TRUE);
      VirtualFile finalVirtualFile = virtualFile;
      Document document = ReadAction.compute(() -> finalVirtualFile.isValid() ? FileDocumentManager.getInstance().getDocument(finalVirtualFile) : null);

      boolean isCurrentTab = Boolean.valueOf(file.getAttributeValue(CURRENT_IN_TAB)).booleanValue();
      FileEditorOpenOptions openOptions = new FileEditorOpenOptions().withPin(Boolean.valueOf(file.getAttributeValue(PINNED))).withIndex(i).withReopeningEditorsOnStartup();

      fileEditorManager.openFileImpl4(uiAccess, window, virtualFile, entry, openOptions);
      if (isCurrentTab) {
        focusedFile = virtualFile;
      }
      if (document != null) {
        // This is just to make sure document reference is kept on stack till this point
        // so that document is available for folding state deserialization in HistoryEntry constructor
        // and that document will be created only once during file opening
        document.putUserData(DUMMY_KEY, null);
      }
      updateProgress();
    }
    catch (InvalidDataException e) {
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        LOG.error(e);
      }
    }
    finally {
      if (virtualFile != null) virtualFile.putUserData(OPENED_IN_BULK, null);
    }
    activity.end();
  }
  if (focusedFile != null) {
    getManager().addSelectionRecord(focusedFile, window);
    VirtualFile finalFocusedFile = focusedFile;
    uiAccess.giveAndWaitIfNeed(() -> {
      EditorWithProviderComposite editor = window.findFileComposite(finalFocusedFile);
      if (editor != null) {
        window.setEditor(editor, true, true);
      }
    });
  }
  else {
    ToolWindowManager manager = ToolWindowManager.getInstance(getManager().getProject());
    manager.invokeLater(() -> {
      if (null == manager.getActiveToolWindowId()) {
        ToolWindow toolWindow = manager.getToolWindow(ToolWindowId.PROJECT_VIEW);
        if (toolWindow != null) toolWindow.activate(null);
      }
    });
  }
  return window.myPanel;
}
 
Example 17
/**
 * Resolves the logical configuration base dir for a scratch file that is placed outside the project by IntelliJ
 *
 * @param scratchVirtualFile the scratch file to resolve a configuration dir for
 * @return the resolved configuration base dir or null if none was found
 */
private VirtualFile getConfigBaseDirForScratch(VirtualFile scratchVirtualFile) {

    final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(scratchVirtualFile);

    // by default we'll use the directory of the scratch file
    final Ref<VirtualFile> baseDir = new Ref<>();

    // but look for a GRAPHQLCONFIG_COMMENT to override it
    if (psiFile != null) {
        scratchVirtualFile.putUserData(GRAPHQL_SCRATCH_PROJECT_KEY, null);
        PsiElement element = psiFile.getFirstChild();
        while (element != null) {
            if (element instanceof PsiComment) {
                final String commentText = element.getText().trim();
                if (commentText.contains(GRAPHQLCONFIG_COMMENT)) {
                    String configFileName = StringUtil.substringAfter(commentText, GRAPHQLCONFIG_COMMENT);
                    if (configFileName != null) {
                        if(configFileName.contains("!")) {
                            final String projectKey = StringUtils.substringAfterLast(configFileName, "!");
                            scratchVirtualFile.putUserData(GRAPHQL_SCRATCH_PROJECT_KEY, projectKey);
                            configFileName = StringUtils.substringBeforeLast(configFileName, "!");
                        }
                        final VirtualFile configVirtualFile = scratchVirtualFile.getFileSystem().findFileByPath(configFileName.trim());
                        if (configVirtualFile != null) {
                            if (configVirtualFile.isDirectory()) {
                                baseDir.set(configVirtualFile);
                            } else {
                                baseDir.set(configVirtualFile.getParent());
                            }
                            break;
                        }
                    }
                }
            }
            element = element.getNextSibling();
        }
    }

    if (baseDir.get() == null) {
        // fallback to either:
        // - a single config
        // - the project base dir
        try {
            readLock.lock();
            if (configPathToConfigurations.size() == 1) {
                final VirtualFile singleConfigPath = configPathToConfigurations.keySet().iterator().next();
                baseDir.set(singleConfigPath);
            }
        } finally {
            readLock.unlock();
        }
        if (baseDir.get() == null) {
            baseDir.set(myProject.getBaseDir());
        }
    }

    return baseDir.get();
}
 
Example 18
Source Project: consulo   File: LoadTextUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void clearCharsetAutoDetectionReason(@Nonnull VirtualFile virtualFile) {
  virtualFile.putUserData(CHARSET_WAS_DETECTED_FROM_BYTES, null);
}
 
Example 19
public static void markTouched(VirtualFile file) {
  file.putUserData(VCS_INVALID_FILE_STATUS, Boolean.TRUE);
}
 
Example 20
Source Project: consulo   File: ChangesUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void markInternalOperation(@Nonnull VirtualFile file, boolean set) {
  file.putUserData(INTERNAL_OPERATION_KEY, set);
}