com.intellij.openapi.vfs.newvfs.events.VFileEvent Java Examples

The following examples show how to use com.intellij.openapi.vfs.newvfs.events.VFileEvent. 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: GeneratedFilesListener.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
public void after(List<? extends VFileEvent> events) {
  IntervalLogger logger = new IntervalLogger(LOG);

  final boolean found =
      events.stream()
          .filter(VFileCreateEvent.class::isInstance)
          .map(VFileEvent::getFile)
          .filter(file -> file != null && file.isValid())
          .map(file -> FileUtil.toSystemIndependentName(file.getPath()))
          .anyMatch(GeneratedFilesListener::isOutput);
  logger.logStep("finding created paths: " + found);
  if (!found) return;

  // Wait for indexing
  final Runnable job =
      () -> {
        logger.logStep("start of removing files");
        ComponentsCacheService.getInstance(project).invalidate();
      };
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    job.run();
  } else {
    DumbService.getInstance(project).smartInvokeLater(job);
  }
}
 
Example #2
Source File: GeneratedFilesListenerTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void after_Remove() throws IOException {
  final Project project = testHelper.getFixture().getProject();
  final GeneratedFilesListener listener = new GeneratedFilesListener(project);
  final PsiFile file = testHelper.configure("LayoutSpec.java");
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            final PsiClass cls = PsiTreeUtil.findChildOfType(file, PsiClass.class);
            // Add file to cache
            final ComponentsCacheService service = ComponentsCacheService.getInstance(project);
            service.maybeUpdate(cls, false);
            final PsiClass component = service.getComponent("Layout");
            assertThat(component).isNotNull();

            // Mock file created and found on disk
            final VFileEvent mockEvent = mockEvent();
            PsiSearchUtils.addMock("Layout", cls);
            listener.after(Collections.singletonList(mockEvent));
            // Ensure cache is cleaned
            final PsiClass component2 = service.getComponent("Layout");
            assertThat(component2).isNull();
          });
}
 
Example #3
Source File: JarMappings.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public JarMappings(Project project) {
  this.project = project;

  project.getMessageBus().connect().subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {
    @Override
    public void after(@NotNull List<? extends VFileEvent> events) {
      events.forEach(event -> {
        if (event instanceof VFileContentChangeEvent &&
            event.getFile() != null &&
            event.getFile().equals(librariesFile())) {
          librariesFileIsUpToDate = false;
        }
      });
    }
  });
}
 
Example #4
Source File: FileBasedIndexImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public AsyncFileListener.ChangeApplier prepareChange(@Nonnull List<? extends VFileEvent> events) {
  boolean shouldCleanup = ContainerUtil.exists(events, ChangedFilesCollector::memoryStorageCleaningNeeded);
  ChangeApplier superApplier = super.prepareChange(events);

  return new AsyncFileListener.ChangeApplier() {
    @Override
    public void beforeVfsChange() {
      if (shouldCleanup) {
        myManager.cleanupMemoryStorage(false);
      }
      superApplier.beforeVfsChange();
    }

    @Override
    public void afterVfsChange() {
      superApplier.afterVfsChange();
      if (myManager.myInitialized) ensureUpToDateAsync();
    }
  };
}
 
Example #5
Source File: AsyncEventSupport.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void processEvents(List<? extends VFileEvent> events, @Nullable List<? extends AsyncFileListener.ChangeApplier> appliers) {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  if (appliers != null) {
    beforeVfsChange(appliers);
    ourSuppressAppliers = true;
  }
  try {
    PersistentFS.getInstance().processEvents(events);
  }
  finally {
    ourSuppressAppliers = false;
  }
  if (appliers != null) {
    afterVfsChange(appliers);
  }
}
 
Example #6
Source File: VirtualFilePointerTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testManyPointersUpdatePerformance() throws IOException {
  LoggingListener listener = new LoggingListener();
  final List<VFileEvent> events = new ArrayList<VFileEvent>();
  final File ioTempDir = createTempDirectory();
  final VirtualFile temp = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioTempDir);
  for (int i=0; i<100000; i++) {
    myVirtualFilePointerManager.create(VfsUtilCore.pathToUrl("/a/b/c/d/" + i), disposable, listener);
    String name = "xxx" + (i % 20);
    events.add(new VFileCreateEvent(this, temp, name, true, null, null, true, null));
  }
  PlatformTestUtil.startPerformanceTest("vfp update", 10000, new ThrowableRunnable() {
    @Override
    public void run() throws Throwable {
      for (int i=0; i<100; i++) {
        // simulate VFS refresh events since launching the actual refresh is too slow
        AsyncFileListener.ChangeApplier applier = myVirtualFilePointerManager.prepareChange(events);
        applier.beforeVfsChange();
        applier.afterVfsChange();
      }
    }
  }).assertTiming();
}
 
Example #7
Source File: ExternalLibraryManager.java    From intellij with Apache License 2.0 6 votes vote down vote up
ExternalLibraryManager(Project project) {
  this.project = project;
  this.duringBlazeSync = false;
  this.libraries = ImmutableMap.of();
  AsyncVfsEventsPostProcessor.getInstance()
      .addListener(
          events -> {
            if (duringBlazeSync || libraries.isEmpty()) {
              return;
            }
            ImmutableList<VirtualFile> deletedFiles =
                events.stream()
                    .filter(VFileDeleteEvent.class::isInstance)
                    .map(VFileEvent::getFile)
                    .collect(toImmutableList());
            if (!deletedFiles.isEmpty()) {
              libraries.values().forEach(library -> library.removeInvalidFiles(deletedFiles));
            }
          },
          project);
}
 
Example #8
Source File: RefreshSessionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void fireEventsInWriteAction(List<? extends VFileEvent> events, @Nullable List<? extends AsyncFileListener.ChangeApplier> appliers) {
  final VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance();

  manager.fireBeforeRefreshStart(myIsAsync);
  try {
    AsyncEventSupport.processEvents(events, appliers);
  }
  catch (AssertionError e) {
    if (FileStatusMap.CHANGES_NOT_ALLOWED_DURING_HIGHLIGHTING.equals(e.getMessage())) {
      throw new AssertionError("VFS changes are not allowed during highlighting", myStartTrace);
    }
    throw e;
  }
  finally {
    try {
      manager.fireAfterRefreshFinish(myIsAsync);
    }
    finally {
      if (myFinishRunnable != null) {
        myFinishRunnable.run();
      }
    }
  }
}
 
Example #9
Source File: RefreshQueueImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void tryProcessingEvents(@Nonnull RefreshSessionImpl session, @Nullable TransactionId transaction) {
  List<? extends VFileEvent> events = ContainerUtil.filter(session.getEvents(), e -> {
    VirtualFile file = e instanceof VFileCreateEvent ? ((VFileCreateEvent)e).getParent() : e.getFile();
    return file == null || file.isValid();
  });

  List<AsyncFileListener.ChangeApplier> appliers = AsyncEventSupport.runAsyncListeners(events);

  long stamp = myWriteActionCounter.get();
  TransactionGuard.getInstance().submitTransaction(ApplicationManager.getApplication(), transaction, () -> {
    if (stamp == myWriteActionCounter.get()) {
      session.fireEvents(events, appliers);
    }
    else {
      scheduleAsynchronousPreprocessing(session, transaction);
    }
  });
}
 
Example #10
Source File: ExternalSystemAutoImporter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void after(@Nonnull List<? extends VFileEvent> events) {
  boolean scheduleRefresh = false;
  for (VFileEvent event : events) {
    String changedPath = event.getPath();
    for (MyEntry entry : myAutoImportAware) {
      String projectPath = entry.aware.getAffectedExternalProjectPath(changedPath, myProject);
      if (projectPath == null) {
        continue;
      }
      ExternalProjectSettings projectSettings = entry.systemSettings.getLinkedProjectSettings(projectPath);
      if (projectSettings != null && projectSettings.isUseAutoImport()) {
        addPath(entry.externalSystemId, projectPath);
        scheduleRefresh = true;
        break;
      }
    }
  }
  if (scheduleRefresh) {
    myVfsAlarm.cancelAllRequests();
    myVfsAlarm.addRequest(myFilesRequest, ExternalSystemConstants.AUTO_IMPORT_DELAY_MILLIS);
  }
}
 
Example #11
Source File: FileContentUtilCore.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public static void reparseFiles(@Nonnull final Collection<? extends VirtualFile> files) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      // files must be processed under one write action to prevent firing event for invalid files.
      final Set<VFilePropertyChangeEvent> events = new THashSet<VFilePropertyChangeEvent>();
      for (VirtualFile file : files) {
        saveOrReload(file, events);
      }

      BulkFileListener publisher = ApplicationManager.getApplication().getMessageBus().syncPublisher(VirtualFileManager.VFS_CHANGES);
      List<VFileEvent> eventList = new ArrayList<VFileEvent>(events);
      publisher.before(eventList);
      publisher.after(eventList);
    }
  });
}
 
Example #12
Source File: LatteFileListener.java    From intellij-latte with MIT License 5 votes vote down vote up
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
    for (VFileEvent event : events) {
        VirtualFile file = event.getFile();
        if (!(file instanceof XmlFile) || !file.getName().equals("latte-intellij.xml") || file.isValid()) {
            continue;
        }

        XmlDocument document = ((XmlFile) file).getDocument();
        if (document == null || document.getRootTag() == null) {
            continue;
        }

        LatteXmlFileData.VendorResult vendorResult = LatteXmlFileDataFactory.getVendor(document);
        if (vendorResult == null) {
            continue;
        }

        List<Project> projects = new ArrayList<>();
        Project project = ProjectUtil.guessProjectForContentFile(file);
        if (project != null) {
            projects.add(project);
        } else {
            Collections.addAll(projects, ProjectManager.getInstance().getOpenProjects());
        }

        LatteIndexUtil.notifyRemovedFiles(projects);
    }
}
 
Example #13
Source File: QuarkusLanguageClient.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private void filter(VFileEvent event, Set<String> uris) {
  VirtualFile file = event.getFile();
  if (file != null && file.exists() && "java".equalsIgnoreCase(file.getExtension())) {
    Module module = ProjectFileIndex.getInstance(getProject()).getModuleForFile(file);
    if (module != null && (event instanceof VFileCreateEvent || event instanceof VFileContentChangeEvent || event instanceof VFileDeleteEvent)) {
      uris.add(PsiUtilsImpl.getProjectURI(module));
    }
  }
}
 
Example #14
Source File: RootIndex.java    From consulo with Apache License 2.0 5 votes vote down vote up
boolean resetOnEvents(@Nonnull List<? extends VFileEvent> events) {
  for (VFileEvent event : events) {
    VirtualFile file = event.getFile();
    if (file == null || file.isDirectory()) {
      return true;
    }
  }
  return false;
}
 
Example #15
Source File: IdeaGateway.java    From consulo with Apache License 2.0 5 votes vote down vote up
VfsEventDispatchContext(List<? extends VFileEvent> events, boolean beforeEvents) {
  myEvents = events;
  myBeforeEvents = beforeEvents;
  myPreviousContext = ourCurrentEventDispatchContext.get();
  if (myPreviousContext != null) {
    myFilterData = myPreviousContext.myFilterData;
  }
  ourCurrentEventDispatchContext.set(this);
}
 
Example #16
Source File: RefreshSessionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
void fireEvents(@Nonnull List<? extends VFileEvent> events, @Nullable List<? extends AsyncFileListener.ChangeApplier> appliers) {
  try {
    if ((myFinishRunnable != null || !events.isEmpty()) && !ApplicationManager.getApplication().isDisposed()) {
      if (LOG.isDebugEnabled()) LOG.debug("events are about to fire: " + events);
      WriteAction.run(() -> fireEventsInWriteAction(events, appliers));
    }
  }
  finally {
    mySemaphore.up();
  }
}
 
Example #17
Source File: AsyncEventSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<AsyncFileListener.ChangeApplier> runAsyncListeners(@Nonnull List<? extends VFileEvent> events) {
  if (events.isEmpty()) return Collections.emptyList();

  if (LOG.isDebugEnabled()) {
    LOG.debug("Processing " + events);
  }

  List<AsyncFileListener.ChangeApplier> appliers = new ArrayList<>();
  List<AsyncFileListener> allListeners = ContainerUtil.concat(EP_NAME.getExtensionList(), ((VirtualFileManagerImpl)VirtualFileManager.getInstance()).getAsyncFileListeners());
  for (AsyncFileListener listener : allListeners) {
    ProgressManager.checkCanceled();
    long startNs = System.nanoTime();
    boolean canceled = false;
    try {
      ReadAction.run(() -> ContainerUtil.addIfNotNull(appliers, listener.prepareChange(events)));
    }
    catch (ProcessCanceledException e) {
      canceled = true;
      throw e;
    }
    catch (Throwable e) {
      LOG.error(e);
    }
    finally {
      long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
      if (elapsedMs > 10_000) {
        LOG.warn(listener + " took too long (" + elapsedMs + "ms) on " + events.size() + " events" + (canceled ? ", canceled" : ""));
      }
    }
  }
  return appliers;
}
 
Example #18
Source File: VcsRootScanner.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void after(@Nonnull List<? extends VFileEvent> events) {
  for (VFileEvent event : events) {
    String filePath = event.getPath();
    for (VcsRootChecker checker : myCheckers) {
      if (checker.isVcsDir(filePath)) {
        scheduleScan();
        break;
      }
    }
  }
}
 
Example #19
Source File: ScratchTreeStructureProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static VirtualFile getNewParent(@Nonnull VFileEvent e) {
  if (e instanceof VFileMoveEvent) {
    return ((VFileMoveEvent)e).getNewParent();
  }
  else if (e instanceof VFileCopyEvent) {
    return ((VFileCopyEvent)e).getNewParent();
  }
  else if (e instanceof VFileCreateEvent) {
    return ((VFileCreateEvent)e).getParent();
  }
  else {
    return Objects.requireNonNull(e.getFile()).getParent();
  }
}
 
Example #20
Source File: ScratchTreeStructureProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isDirectory(@Nonnull VFileEvent e) {
  if (e instanceof VFileCreateEvent) {
    return ((VFileCreateEvent)e).isDirectory();
  }
  else {
    return Objects.requireNonNull(e.getFile()).isDirectory();
  }
}
 
Example #21
Source File: QuarkusLanguageClient.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
  Set<String> uris = new HashSet<>();
  events.forEach(event -> filter(event, uris));
  if (!uris.isEmpty()) {
    sendPropertiesChangeEvent(MicroProfilePropertiesScope.sources, uris);
  }
}
 
Example #22
Source File: FastBuildChangedFilesService.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void after(List<? extends VFileEvent> events) {
  ListenableFuture<Void> submit =
      executor.submit(
          () -> {
            synchronized (FastBuildChangedFilesService.this) {
              if (!isCollecting()) {
                return null;
              }

              ImmutableSet<File> changedFiles =
                  events.stream()
                      // We don't want to compile deleted files
                      .filter(event -> !(event instanceof VFileDeleteEvent))
                      .map(VFileEvent::getPath)
                      .filter(f -> f.endsWith(".java"))
                      .map(File::new)
                      .collect(toImmutableSet());

              if (changedFiles.isEmpty()) {
                return null;
              }
              // TODO(b/145386688): Access should be guarded by enclosing instance
              // 'com.google.idea.blaze.java.fastbuild.FastBuildChangedFilesService' of 'data',
              // which is not accessible in this scope
              labelData.values().forEach(data -> data.updateChangedSources(changedFiles));
              return null;
            }
          });
  Futures.addCallback(submit, new LogErrorCallback(), executor);
}
 
Example #23
Source File: FileWatch.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
  final Set<FileWatch> todo = new LinkedHashSet<>();
  synchronized (subscriptions) {
    for (VFileEvent event : events) {
      subscriptions.addWatchesForFile(todo, event.getFile());
    }
  }

  // Deliver changes synchronously, but after releasing the lock in case
  // the callback subscribes/unsubscribes.
  for (FileWatch w : todo) {
    w.fireEvent();
  }
}
 
Example #24
Source File: BulkSymbolTableBuildingChangeListener.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void after(List<? extends VFileEvent> events) {
  if (!enabled) {
    return;
  }
  for (VFileEvent event : events) {
    VirtualFile modifiedFile = null;
    // Skip delete events.
    if (event instanceof VFileContentChangeEvent || event instanceof VFileCreateEvent) {
      modifiedFile = event.getFile();
    } else if (event instanceof VFileCopyEvent) {
      VFileCopyEvent copyEvent = (VFileCopyEvent) event;
      modifiedFile = copyEvent.getNewParent();
    } else if (event instanceof VFileMoveEvent) {
      VFileMoveEvent moveEvent = (VFileMoveEvent) event;
      modifiedFile = moveEvent.getNewParent();
    } else if (event instanceof VFilePropertyChangeEvent) {
      VFilePropertyChangeEvent propEvent = (VFilePropertyChangeEvent) event;
      // Check for file renames (sometimes we get property change events without the name
      // actually changing though)
      if (propEvent.getPropertyName().equals(VirtualFile.PROP_NAME)
          && !propEvent.getOldValue().equals(propEvent.getNewValue())) {
        modifiedFile = propEvent.getFile();
      }
    }
    if (SymbolTableProvider.isSourceFile(project, modifiedFile)) {
      queueChange(modifiedFile);
    }
  }
}
 
Example #25
Source File: FileExperimentLoader.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void after(List<? extends VFileEvent> events) {
  if (events.stream().anyMatch(this::isExperimentsFile)) {
    logger.info("Scheduling experiments file refresh on " + file);
    ApplicationManager.getApplication()
        .executeOnPooledThread(
            () -> {
              reloadExperiments();
              ExperimentService.getInstance().notifyExperimentsChanged();
            });
  }
}
 
Example #26
Source File: FileWatch.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
  final Set<FileWatch> todo = new LinkedHashSet<>();
  synchronized (subscriptions) {
    for (VFileEvent event : events) {
      subscriptions.addWatchesForFile(todo, event.getFile());
    }
  }

  // Deliver changes synchronously, but after releasing the lock in case
  // the callback subscribes/unsubscribes.
  for (FileWatch w : todo) {
    w.fireEvent();
  }
}
 
Example #27
Source File: GeneratedFilesListenerTest.java    From litho with Apache License 2.0 5 votes vote down vote up
private VFileEvent mockEvent() {
  final VFileEvent event = Mockito.mock(VFileCreateEvent.class);
  VirtualFile mockFile = Mockito.mock(VirtualFile.class);
  when(mockFile.isValid()).thenReturn(true);
  when(mockFile.getPath()).thenReturn(GeneratedFilesListener.BUCK_OUT_BASE);
  when(event.getFile()).thenReturn(mockFile);
  return event;
}
 
Example #28
Source File: FileWatch.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void before(@NotNull List<? extends VFileEvent> events) {
}
 
Example #29
Source File: VcsDirtyScopeVfsListener.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public ChangeApplier prepareChange(@Nonnull List<? extends VFileEvent> events) {
  if (myForbid || !myVcsManager.hasAnyMappings()) return null;
  final FilesAndDirs dirtyFilesAndDirs = new FilesAndDirs();
  // collect files and directories - sources of events
  for (VFileEvent event : events) {
    ProgressManager.checkCanceled();

    final boolean isDirectory;
    if (event instanceof VFileCreateEvent) {
      if (!((VFileCreateEvent)event).getParent().isInLocalFileSystem()) {
        continue;
      }
      isDirectory = ((VFileCreateEvent)event).isDirectory();
    }
    else {
      final VirtualFile file = Objects.requireNonNull(event.getFile(), "All events but VFileCreateEvent have @NotNull getFile()");
      if (!file.isInLocalFileSystem()) {
        continue;
      }
      isDirectory = file.isDirectory();
    }

    if (event instanceof VFileMoveEvent) {
      add(myVcsManager, dirtyFilesAndDirs, VcsUtil.getFilePath(((VFileMoveEvent)event).getOldPath(), isDirectory));
      add(myVcsManager, dirtyFilesAndDirs, VcsUtil.getFilePath(((VFileMoveEvent)event).getNewPath(), isDirectory));
    }
    else if (event instanceof VFilePropertyChangeEvent && ((VFilePropertyChangeEvent)event).isRename()) {
      // if a file was renamed, then the file is dirty and its parent directory is dirty too;
      // if a directory was renamed, all its children are recursively dirty, the parent dir is also dirty but not recursively.
      FilePath oldPath = VcsUtil.getFilePath(((VFilePropertyChangeEvent)event).getOldPath(), isDirectory);
      FilePath newPath = VcsUtil.getFilePath(((VFilePropertyChangeEvent)event).getNewPath(), isDirectory);
      // the file is dirty recursively
      add(myVcsManager, dirtyFilesAndDirs, oldPath);
      add(myVcsManager, dirtyFilesAndDirs, newPath);
      FilePath parentPath = oldPath.getParentPath();
      if (parentPath != null) {
        addAsFiles(myVcsManager, dirtyFilesAndDirs, parentPath); // directory is dirty alone
      }
    }
    else {
      add(myVcsManager, dirtyFilesAndDirs, VcsUtil.getFilePath(event.getPath(), isDirectory));
    }
  }

  return new ChangeApplier() {
    @Override
    public void afterVfsChange() {
      markDirtyOnPooled(dirtyFilesAndDirs);
    }
  };
}
 
Example #30
Source File: FileBasedIndexImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean memoryStorageCleaningNeeded(@Nonnull VFileEvent event) {
  Object requestor = event.getRequestor();
  return requestor instanceof FileDocumentManager || requestor instanceof PsiManager || requestor == LocalHistory.VFS_EVENT_REQUESTOR;
}