From 51d3e458870093f106bc847d350f2bbba562c4e1 Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Sun, 22 Oct 2023 09:47:31 +0200 Subject: [PATCH] Cleanup (minor optimization; typos; formatting) GitOrigin-RevId: 3c575325bd9fb128aa6c5ab135bbb7e3cf431e77 --- .../src/SaveAndSyncHandlerImpl.kt | 92 +++++++++---------- .../intellij/openapi/vfs/SavingRequestor.java | 5 +- .../openapi/vfs/VirtualFileEvent.java | 3 +- .../vfs/newvfs/events/VFileCreateEvent.java | 4 +- .../openapi/vfs/newvfs/events/VFileEvent.java | 6 +- .../events/VFilePropertyChangeEvent.java | 6 +- .../intellij/util/FileContentUtilCore.java | 4 +- .../openapi/vfs/newvfs/VfsImplUtil.java | 2 +- .../src/com/intellij/ide/GeneralSettings.kt | 47 ++++------ .../util/indexing/UnindexedFilesScanner.java | 4 +- .../ide/GeneralSettingsConfigurable.kt | 48 +++++----- .../openapi/vfs/newvfs/RefreshWorker.java | 8 +- .../vfs/newvfs/impl/VirtualDirectoryImpl.java | 20 ++-- .../newvfs/monitoring/VfsUsageCollector.java | 43 ++------- 14 files changed, 129 insertions(+), 163 deletions(-) diff --git a/platform/configuration-store-impl/src/SaveAndSyncHandlerImpl.kt b/platform/configuration-store-impl/src/SaveAndSyncHandlerImpl.kt index 4be1fb5c37c0..ffe534c3feb9 100644 --- a/platform/configuration-store-impl/src/SaveAndSyncHandlerImpl.kt +++ b/platform/configuration-store-impl/src/SaveAndSyncHandlerImpl.kt @@ -70,52 +70,52 @@ internal class SaveAndSyncHandlerImpl(private val coroutineScope: CoroutineScope private val forceExecuteImmediatelyState = AtomicBoolean() init { + coroutineScope.launch(CoroutineName("refresh requests flow processing") + ModalityState.nonModal().asContextElement()) { + // not collectLatest - wait for previous execution + refreshRequests + .debounce(300.milliseconds) + .collect { + val eventPublisher = eventPublisher + withContext(Dispatchers.EDT) { + blockingContext { + eventPublisher.beforeRefresh() + refreshOpenFiles() + maybeRefresh(ModalityState.nonModal()) + } + } + } + } + + coroutineScope.launch(CoroutineName("save requests flow processing")) { + // not collectLatest - wait for previous execution + saveRequests + .collect { + val forceExecuteImmediately = forceExecuteImmediatelyState.compareAndSet(true, false) + if (!forceExecuteImmediately) { + delay(300.milliseconds) + } + + if (blockSaveOnFrameDeactivationCount.get() != 0) { + return@collect + } + + val job = currentJob.updateAndGet { oldJob -> + oldJob?.cancel() + launch(start = CoroutineStart.LAZY) { processTasks(forceExecuteImmediately = forceExecuteImmediately) } + }!! + try { + if (job.start()) { + job.join() + } + } + catch (_: CancellationException) { } + finally { + currentJob.compareAndSet(job, null) + } + } + } + coroutineScope.launch { - launch(CoroutineName("refresh requests flow processing") + ModalityState.nonModal().asContextElement()) { - // not collectLatest - wait for previous execution - refreshRequests - .debounce(300.milliseconds) - .collect { - val eventPublisher = eventPublisher - withContext(Dispatchers.EDT) { - blockingContext { - eventPublisher.beforeRefresh() - refreshOpenFiles() - maybeRefresh(ModalityState.nonModal()) - } - } - } - } - - launch(CoroutineName("save requests flow processing")) { - // not collectLatest - wait for previous execution - saveRequests - .collect { - val forceExecuteImmediately = forceExecuteImmediatelyState.compareAndSet(true, false) - if (!forceExecuteImmediately) { - delay(300.milliseconds) - } - - if (blockSaveOnFrameDeactivationCount.get() != 0) { - return@collect - } - - val job = currentJob.updateAndGet { oldJob -> - oldJob?.cancel() - launch(start = CoroutineStart.LAZY) { processTasks(forceExecuteImmediately = forceExecuteImmediately) } - }!! - try { - if (job.start()) { - job.join() - } - } - catch (_: CancellationException) { } - finally { - currentJob.compareAndSet(job, null) - } - } - } - listenIdleAndActivate() } @@ -351,7 +351,7 @@ internal class SaveAndSyncHandlerImpl(private val coroutineScope: CoroutineScope session.addAllFiles(*ManagingFS.getInstance().localRoots) refreshSession.getAndSet(session)?.cancel() session.launch() - LOG.debug("vfs refreshed") + LOG.debug("VFS refresh started") } override fun refreshOpenFiles() { diff --git a/platform/core-api/src/com/intellij/openapi/vfs/SavingRequestor.java b/platform/core-api/src/com/intellij/openapi/vfs/SavingRequestor.java index ff3e1bb90697..b0fb1949fd85 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/SavingRequestor.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/SavingRequestor.java @@ -1,8 +1,7 @@ -// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. +// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vfs; /** * Marker interface for the requestor to label VFS events as coming from a save operation. */ -public interface SavingRequestor { -} +public interface SavingRequestor { } diff --git a/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileEvent.java b/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileEvent.java index 51380ee46d1d..27cb89bfe807 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileEvent.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileEvent.java @@ -17,7 +17,6 @@ public class VirtualFileEvent extends EventObject { private final Object myRequestor; private final VirtualFile myFile; private final VirtualFile myParent; - private final long myOldModificationStamp; private final long myNewModificationStamp; @@ -49,7 +48,7 @@ public class VirtualFileEvent extends EventObject { } /** - * Returns the parent of the virtual file, or {@code null} if the file is a root directory + * Returns the parent of the virtual file, or {@code null} if the file is a root directory, * or it was not possible to determine the parent (depends on the specific VFS implementation). */ public @Nullable VirtualFile getParent() { diff --git a/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileCreateEvent.java b/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileCreateEvent.java index f2d6d2470d70..47ee2800b846 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileCreateEvent.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileCreateEvent.java @@ -11,7 +11,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class VFileCreateEvent extends VFileEvent { - private final @NotNull VirtualFile myParent; + private final VirtualFile myParent; private final boolean myDirectory; private final FileAttributes myAttributes; private final String mySymlinkTarget; @@ -72,7 +72,7 @@ public final class VFileCreateEvent extends VFileEvent { return mySymlinkTarget; } - /** @return true if the newly created file is a directory which has no children. */ + /** @return {@code true} if the newly created file is a directory that has no children. */ public boolean isEmptyDirectory() { return isDirectory() && myChildren != null && myChildren.length == 0; } diff --git a/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileEvent.java b/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileEvent.java index d1b8655cb2d5..f51bfcfb69fe 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileEvent.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFileEvent.java @@ -52,11 +52,11 @@ public abstract class VFileEvent { protected abstract @NotNull String computePath(); /** - * Returns the VirtualFile which this event belongs to. - * In some cases it may be null - it is not guaranteed that there is such file. + * Returns the {@link VirtualFile} which this event belongs to. + * In some cases, it may be {@code null} - it is not guaranteed that the file exists. *

* NB: Use this method with caution, because {@link VFileCreateEvent#getFile()} needs - * {@link VirtualFile#findChild(String)} which may be a performance leak. + * {@link VirtualFile#findChild(String)} which may be a performance hit. */ public abstract @Nullable VirtualFile getFile(); diff --git a/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFilePropertyChangeEvent.java b/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFilePropertyChangeEvent.java index 2f3902810825..2d72179cbf8e 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFilePropertyChangeEvent.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/newvfs/events/VFilePropertyChangeEvent.java @@ -53,9 +53,9 @@ public final class VFilePropertyChangeEvent extends VFileEvent { switch (propertyName) { case VirtualFile.PROP_NAME: if (oldValue == null) throw new IllegalArgumentException("oldName must not be null"); - if (!(oldValue instanceof String)) throw new IllegalArgumentException("oldName must be String, got "+oldValue); + if (!(oldValue instanceof String)) throw new IllegalArgumentException("oldName must be String, got " + oldValue); if (newValue == null) throw new IllegalArgumentException("newName must not be null"); - if (!(newValue instanceof String)) throw new IllegalArgumentException("newName must be String, got "+newValue); + if (!(newValue instanceof String)) throw new IllegalArgumentException("newName must be String, got " + newValue); break; case VirtualFile.PROP_ENCODING: if (oldValue == null) throw new IllegalArgumentException("oldCharset must not be null"); @@ -175,7 +175,7 @@ public final class VFilePropertyChangeEvent extends VFileEvent { return getPathWithFileName(myNewValue); } - /** Replaces file name in {@code myFile} path with {@code fileName}, if an event is a rename event; leaves path as is otherwise */ + /** Replaces file name in {@code myFile} path with {@code fileName}, if an event is a rename event; leaves the path as is otherwise */ private @NotNull String getPathWithFileName(Object fileName) { if (VirtualFile.PROP_NAME.equals(myPropertyName)) { // fileName must be String, according to `checkPropertyValuesCorrect` implementation diff --git a/platform/core-api/src/com/intellij/util/FileContentUtilCore.java b/platform/core-api/src/com/intellij/util/FileContentUtilCore.java index 2396a22ffcd3..e1ebfae5bfd5 100644 --- a/platform/core-api/src/com/intellij/util/FileContentUtilCore.java +++ b/platform/core-api/src/com/intellij/util/FileContentUtilCore.java @@ -18,7 +18,7 @@ public final class FileContentUtilCore { public static final String FORCE_RELOAD_REQUESTOR = "FileContentUtilCore.saveOrReload"; /** - * Forces a reparse of the specified array of files. + * Forces reparsing the specified files. * * @param files the files to reparse. */ @@ -27,7 +27,7 @@ public final class FileContentUtilCore { } /** - * Forces a reparse of the specified collection of files. + * Forces reparsing the specified files. * * @param files the files to reparse. */ diff --git a/platform/ide-core-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java b/platform/ide-core-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java index 0284151c2d1b..6d8b615c5240 100644 --- a/platform/ide-core-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java +++ b/platform/ide-core-impl/src/com/intellij/openapi/vfs/newvfs/VfsImplUtil.java @@ -184,7 +184,7 @@ public final class VfsImplUtil { public record PathFromRoot(@NotNull NewVirtualFile root, @NotNull String pathFromRoot) {} /** - * @return (file system root, relative path inside that root) or null if the path is invalid or the root is not found + * Returns a (file system root, relative path inside that root) pair, or {@code null} when the path is invalid or the root is not found. * For example, {@code extractRootFromPath(LocalFileSystem.getInstance, "C:/temp")} -> ("C:", "/temp") * {@code extractRootFromPath(JarFileSystem.getInstance, "/temp/temp.jar!/com/foo/bar")} -> ("/temp/temp.jar!/", "/com/foo/bar") */ diff --git a/platform/ide-core/src/com/intellij/ide/GeneralSettings.kt b/platform/ide-core/src/com/intellij/ide/GeneralSettings.kt index 408387c00212..3555ff7868e1 100644 --- a/platform/ide-core/src/com/intellij/ide/GeneralSettings.kt +++ b/platform/ide-core/src/com/intellij/ide/GeneralSettings.kt @@ -19,7 +19,6 @@ import org.jetbrains.annotations.SystemDependent private const val SHOW_TIPS_ON_STARTUP_DEFAULT_VALUE_PROPERTY = "ide.show.tips.on.startup.default.value" private const val CONFIGURED_PROPERTY = "GeneralSettings.initiallyConfigured" -@Suppress("unused", "EnumEntryName") @State(name = "GeneralSettings", storages = [Storage(GeneralSettings.IDE_GENERAL_XML)], category = SettingsCategory.SYSTEM) class GeneralSettings : PersistentStateComponent { private var state = GeneralSettingsState() @@ -29,10 +28,7 @@ class GeneralSettings : PersistentStateComponent { get() = state.browserPath var isShowTipsOnStartup: Boolean - get() { - return state.showTipsOnStartup - ?: java.lang.Boolean.parseBoolean(System.getProperty(SHOW_TIPS_ON_STARTUP_DEFAULT_VALUE_PROPERTY, "true")) - } + get() = state.showTipsOnStartup ?: System.getProperty(SHOW_TIPS_ON_STARTUP_DEFAULT_VALUE_PROPERTY, "true").toBoolean() set(value) { state.showTipsOnStartup = value } @@ -49,6 +45,12 @@ class GeneralSettings : PersistentStateComponent { state.autoSyncFiles = value } + var isBackgroundSync: Boolean + get() = state.backgroundSyncFiles + set(value) { + state.backgroundSyncFiles = value + } + var isSaveOnFrameDeactivation: Boolean get() = state.autoSaveFiles set(value) { @@ -74,13 +76,10 @@ class GeneralSettings : PersistentStateComponent { state.isUseSafeWrite = value } - private val _propertyChangedFlow = MutableSharedFlow(extraBufferCapacity = 16, - onBufferOverflow = BufferOverflow.DROP_OLDEST) - + private val _propertyChangedFlow = MutableSharedFlow(extraBufferCapacity = 16, onBufferOverflow = BufferOverflow.DROP_OLDEST) val propertyChangedFlow: Flow = _propertyChangedFlow.asSharedFlow() - //fun propertyChangedFlow() - + @Suppress("unused") @get:Deprecated("Use {@link GeneralLocalSettings#getUseDefaultBrowser()} instead.") @get:ApiStatus.ScheduledForRemoval val isUseDefaultBrowser: Boolean @@ -105,10 +104,10 @@ class GeneralSettings : PersistentStateComponent { } /** - * [GeneralSettings.OPEN_PROJECT_NEW_WINDOW] if a new project should be opened in new window - * [GeneralSettings.OPEN_PROJECT_SAME_WINDOW] if a new project should be opened in same window - * [GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH] if a new project should be attached - * [GeneralSettings.OPEN_PROJECT_ASK] if a confirmation dialog should be shown + * [OPEN_PROJECT_NEW_WINDOW] if a new project should be opened in new window + * [OPEN_PROJECT_SAME_WINDOW] if a new project should be opened in same window + * [OPEN_PROJECT_SAME_WINDOW_ATTACH] if a new project should be attached + * [OPEN_PROJECT_ASK] if a confirmation dialog should be shown */ @get:OpenNewProjectOption var confirmOpenNewProject: Int @@ -117,7 +116,6 @@ class GeneralSettings : PersistentStateComponent { state.confirmOpenNewProject2 = value } - var processCloseConfirmation: ProcessCloseConfirmation get() = state.processCloseConfirmation set(value) { @@ -158,6 +156,7 @@ class GeneralSettings : PersistentStateComponent { fun defaultConfirmNewProject(): Int = OPEN_PROJECT_ASK } + @Suppress("EnumEntryName") enum class PropertyNames { inactiveTimeout, autoSaveIfInactive, @@ -199,7 +198,7 @@ class GeneralSettings : PersistentStateComponent { this.state = state } - @Suppress("UNUSED_PARAMETER") + @Suppress("unused") @get:Deprecated("unused") @get:Transient @get:ApiStatus.ScheduledForRemoval @@ -207,7 +206,7 @@ class GeneralSettings : PersistentStateComponent { @set:ApiStatus.ScheduledForRemoval var isConfirmExtractFiles: Boolean get() = true - set(value) {} + set(_) {} @MagicConstant(intValues = [OPEN_PROJECT_ASK.toLong(), OPEN_PROJECT_NEW_WINDOW.toLong(), OPEN_PROJECT_SAME_WINDOW.toLong(), OPEN_PROJECT_SAME_WINDOW_ATTACH.toLong()]) internal annotation class OpenNewProjectOption @@ -221,26 +220,22 @@ data class GeneralSettingsState( @field:OptionTag("myDefaultProjectDirectory") @JvmField var defaultProjectDirectory: String? = "", - @JvmField var browserPath: String? = "", - @JvmField var showTipsOnStartup: Boolean? = null, @JvmField var reopenLastProject: Boolean = true, - @JvmField var autoSyncFiles: Boolean = true, - + @JvmField + var backgroundSyncFiles: Boolean = false, @JvmField var autoSaveFiles: Boolean = true, @JvmField var autoSaveIfInactive: Boolean = false, - @JvmField var isUseSafeWrite: Boolean = true, - @JvmField var useDefaultBrowser: Boolean = true, @JvmField @@ -249,17 +244,13 @@ data class GeneralSettingsState( var confirmExit: Boolean = true, @JvmField var isShowWelcomeScreen: Boolean = true, - @ReportValue @JvmField var confirmOpenNewProject2: Int? = null, - @JvmField var processCloseConfirmation: ProcessCloseConfirmation = ProcessCloseConfirmation.ASK, - @JvmField var inactiveTimeout: Int = 15, - @JvmField var supportScreenReaders: Boolean = false ) @@ -268,4 +259,4 @@ enum class ProcessCloseConfirmation { ASK, TERMINATE, DISCONNECT -} \ No newline at end of file +} diff --git a/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesScanner.java b/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesScanner.java index 616608fc66a6..6eca11c57ea1 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesScanner.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesScanner.java @@ -445,7 +445,7 @@ public class UnindexedFilesScanner extends FilesScanningTaskBase { myFutureScanningRequestToken.markSuccessful(); projectIndexingDependenciesService.completeToken(myFutureScanningRequestToken); - List sessions = + List sessions = ContainerUtil.map(IndexableFileScanner.EP_NAME.getExtensionList(), scanner -> scanner.startSession(project)); IndexableFilesDeduplicateFilter indexableFilesDeduplicateFilter = IndexableFilesDeduplicateFilter.create(); @@ -458,7 +458,7 @@ public class UnindexedFilesScanner extends FilesScanningTaskBase { // And some scanning statistics may be tried to be added to the [scanningHistory], // leading to ConcurrentModificationException in the statistics' processor. Ref allTasksFinished = Ref.create(false); - final IndexingReasonExplanationLogger sharedExplanationLogger = new IndexingReasonExplanationLogger(); + IndexingReasonExplanationLogger sharedExplanationLogger = new IndexingReasonExplanationLogger(); List tasks = ContainerUtil.map(providers, provider -> { ScanningStatistics scanningStatistics = new ScanningStatistics(provider.getDebugName()); scanningStatistics.setProviderRoots(provider, project); diff --git a/platform/platform-impl/src/com/intellij/ide/GeneralSettingsConfigurable.kt b/platform/platform-impl/src/com/intellij/ide/GeneralSettingsConfigurable.kt index 2a5fdc488a5b..fe6089ce1afa 100644 --- a/platform/platform-impl/src/com/intellij/ide/GeneralSettingsConfigurable.kt +++ b/platform/platform-impl/src/com/intellij/ide/GeneralSettingsConfigurable.kt @@ -25,6 +25,8 @@ private val myConfirmExit: CheckboxDescriptor get() = CheckboxDescriptor(IdeBundle.message("checkbox.confirm.application.exit"), model::isConfirmExit) private val myChkSyncOnFrameActivation get() = CheckboxDescriptor(IdeBundle.message("checkbox.synchronize.files.on.frame.activation"), model::isSyncOnFrameActivation) +private val myChkSyncInBackground + get() = CheckboxDescriptor(IdeBundle.message("checkbox.synchronize.files.in.background"), model::isBackgroundSync) private val myChkSaveOnFrameDeactivation get() = CheckboxDescriptor(IdeBundle.message("checkbox.save.files.on.frame.deactivation"), model::isSaveOnFrameDeactivation) private val myChkAutoSaveIfInactive @@ -33,36 +35,36 @@ private val myChkUseSafeWrite get() = CheckboxDescriptor(IdeBundle.message("checkbox.safe.write"), model::isUseSafeWrite) internal val allOptionDescriptors: List - get() { - return sequenceOf( + get() = + listOf( myChkReopenLastProject, myConfirmExit, myChkSyncOnFrameActivation, + myChkSyncInBackground, myChkSaveOnFrameDeactivation, myChkAutoSaveIfInactive, myChkUseSafeWrite ) - .map { it.asUiOptionDescriptor() } - .toList() - } + .map(CheckboxDescriptor::asUiOptionDescriptor) /** - * To provide additional options in General section register implementation of {@link SearchableConfigurable} in the plugin.xml: - *

- * <extensions defaultExtensionNs="com.intellij">
- *   <generalOptionsProvider instance="class-name"/>
- * </extensions> - *

- * A new instance of the specified class will be created each time then the Settings dialog is opened + * To provide additional options in General section register implementation of [SearchableConfigurable] in the 'plugin.xml': + * ``` + * + * + * + * ``` + * A new instance of the specified class will be created each time then the Settings dialog is opened. */ -private class GeneralSettingsConfigurable: BoundCompositeSearchableConfigurable( - IdeBundle.message("title.general"), - "preferences.general" -), SearchableConfigurable { +@Suppress("unused") +private class GeneralSettingsConfigurable : + BoundCompositeSearchableConfigurable(IdeBundle.message("title.general"), "preferences.general"), + SearchableConfigurable +{ private val model = GeneralSettings.getInstance().state - override fun createPanel(): DialogPanel { - return panel { + override fun createPanel(): DialogPanel = + panel { row { checkBox(myConfirmExit) } @@ -123,6 +125,9 @@ private class GeneralSettingsConfigurable: BoundCompositeSearchableConfigurable< row { checkBox(myChkSyncOnFrameActivation) } + row { + checkBox(myChkSyncInBackground) + } row { comment(IdeBundle.message("label.autosave.comment")) { HelpManager.getInstance().invokeHelp("autosave") @@ -134,13 +139,10 @@ private class GeneralSettingsConfigurable: BoundCompositeSearchableConfigurable< appendDslConfigurable(configurable) } } - } override fun getId(): String = helpTopic!! - override fun createConfigurables(): List { - return ConfigurableWrapper.createConfigurables(EP_NAME) - } + override fun createConfigurables(): List = ConfigurableWrapper.createConfigurables(EP_NAME) } -private val EP_NAME = ExtensionPointName("com.intellij.generalOptionsProvider") \ No newline at end of file +private val EP_NAME = ExtensionPointName("com.intellij.generalOptionsProvider") diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshWorker.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshWorker.java index c9ac4645ef44..86c0228b8f25 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshWorker.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/RefreshWorker.java @@ -37,7 +37,6 @@ import com.intellij.util.containers.Stack; import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet; import kotlinx.coroutines.Dispatchers; import kotlinx.coroutines.ExecutorsKt; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; @@ -63,27 +62,28 @@ final class RefreshWorker { private final Set myRoots; private final Queue myRefreshQueue; private final Semaphore mySemaphore; + private final Object myRequestor; private final PersistentFS myPersistence = PersistentFS.getInstance(); private final FSRecordsImpl myPersistencePeer = ((PersistentFSImpl)myPersistence).peer(); - private final Object myRequestor = VFileEvent.REFRESH_REQUESTOR; private volatile boolean myCancelled; private final AtomicInteger myFullScans = new AtomicInteger(), myPartialScans = new AtomicInteger(), myProcessed = new AtomicInteger(); private final AtomicLong myVfsTime = new AtomicLong(), myIoTime = new AtomicLong(); - RefreshWorker(@NotNull Collection<@NotNull NewVirtualFile> refreshRoots, boolean isRecursive) { + RefreshWorker(Collection refreshRoots, boolean isRecursive) { myIsRecursive = isRecursive; myParallel = isRecursive && ourParallelism > 1 && !ApplicationManager.getApplication().isWriteIntentLockAcquired(); myRoots = new HashSet<>(refreshRoots); myRefreshQueue = new LinkedBlockingQueue<>(refreshRoots); mySemaphore = new Semaphore(refreshRoots.size()); + myRequestor = VFileEvent.REFRESH_REQUESTOR; } void cancel() { myCancelled = true; } - @NotNull List scan() { + List scan() { var t = System.nanoTime(); try { var events = new ArrayList(); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java index f7317325d67f..d613d243c088 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java @@ -288,8 +288,8 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { child.markDirty(); } if (isDirectory && child instanceof VirtualDirectoryImpl && isEmptyDirectory) { - // When creating an empty directory, we need to make sure that every file created inside will fire "file created" event - // in order to virtual file pointer manager get those events to update its pointers properly + // When creating an empty directory, we need to make sure that every file created inside it will fire a "file created" event + // for virtual file pointer manager to update its pointers properly // (because currently VirtualFilePointerManager ignores empty directory creation events for performance reasons). ((VirtualDirectoryImpl)child).setAllChildrenLoaded(); } @@ -550,8 +550,8 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { //We come here only from PersistentFSImpl.findFileById(), on a descend phase, there we resolve fileIds to // VFiles. Hence, it must be a child with childId -- because 'this' was collected as .parent during an - // ascend phase. If that is not the case -- either something was changed in between (e.g. children were - // refreshed), or there is an inconsistency in VFS (e.g. children and .parent fall out of sync): + // ascend phase. If that is not the case -- either something was changed in between (e.g., children were + // refreshed), or there is an inconsistency in VFS (e.g., children and .parent fall out of sync): //Actually, after this point we're already in a gray area: even if we manage to find a child by name // with same id, this is already suspicious: how could we miss it while looking by id beforehand? @@ -567,7 +567,7 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { boolean deleted = FSRecords.isDeleted(id); if (!deleted) { THROTTLED_LOG.info(() -> { - int parentId = FSRecords.getParent(id); + @SuppressWarnings("removal") int parentId = FSRecords.getParent(id); IntOpenHashSet childrenInPersistence = new IntOpenHashSet(FSRecords.listIds(id)); IntOpenHashSet childrenInMemory = new IntOpenHashSet(myData.myChildrenIds); int[] childrenNotInPersistent = childrenInMemory.intStream() @@ -597,7 +597,7 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { throw new IOException("Cannot get content of directory: " + this); } - // optimisation: works faster than added.forEach(this::addChild) + // optimization: works faster than added.forEach(this::addChild) @ApiStatus.Internal public void createAndAddChildren(@NotNull List added, boolean markAllChildrenLoaded, @@ -606,8 +606,7 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { for (int i = 0; i < added.size(); i++) { ChildInfo info = added.get(i); assert info.getId() > 0 : info; - @PersistentFS.Attributes - int attributes = info.getFileAttributeFlags(); + @SuppressWarnings("MagicConstant") @PersistentFS.Attributes int attributes = info.getFileAttributeFlags(); boolean isEmptyDirectory = info.getChildren() != null && info.getChildren().length == 0; synchronized (myData) { int[] oldIds = myData.myChildrenIds; @@ -649,8 +648,7 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { ContainerUtil.processSortedListsInOrder(existingChildren, added, byName, true, (nextInfo, mergeResult) -> { if (mergeResult != ContainerUtil.MergeResult.COPIED_FROM_LIST1) { assert nextInfo.getId() > 0 : nextInfo; - @PersistentFS.Attributes - int attributes = nextInfo.getFileAttributeFlags(); + @SuppressWarnings("MagicConstant") @PersistentFS.Attributes int attributes = nextInfo.getFileAttributeFlags(); boolean isEmptyDirectory = nextInfo.getChildren() != null && nextInfo.getChildren().length == 0; myData.removeAdoptedName(nextInfo.getName()); VirtualFileSystemEntry file = createChildImpl(nextInfo.getId(), nextInfo.getNameId(), attributes, isEmptyDirectory); @@ -823,7 +821,7 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { markDirtyRecursivelyInternal(); } - // optimisation: do not travel up unnecessary + // optimization: do not travel up unnecessary private void markDirtyRecursivelyInternal() { for (VirtualFileSystemEntry child : getArraySafely(true)) { child.markDirtyInternal(); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/monitoring/VfsUsageCollector.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/monitoring/VfsUsageCollector.java index 940e446d3fa7..1d3cd81a1d07 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/monitoring/VfsUsageCollector.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/monitoring/VfsUsageCollector.java @@ -12,6 +12,7 @@ import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import java.lang.Enum; import java.lang.Long; import java.util.List; import java.util.stream.Stream; @@ -21,23 +22,17 @@ import static com.intellij.internal.statistic.eventLog.events.EventFields.Enum; import static com.intellij.internal.statistic.eventLog.events.EventFields.Long; import static com.intellij.internal.statistic.eventLog.events.EventFields.*; -import java.lang.Enum; - @ApiStatus.Internal public final class VfsUsageCollector extends CounterUsagesCollector { private static final int DURATION_THRESHOLD_MS = 100; private static final EventLogGroup GROUP_VFS = new EventLogGroup("vfs", 15); + private static final LongEventField FIELD_WAIT_MS = Long("wait_ms"); // -1 for synchronous refresh/events /* ================== EVENT_INITIAL_REFRESH: ====================================================== */ - private static final LongEventField FIELD_WAIT_MS = Long("wait_ms"); // -1 for synchronous refresh/events - - private static final EventId1 EVENT_INITIAL_REFRESH = GROUP_VFS.registerEvent( - "initial_refresh", - DurationMs - ); + private static final EventId1 EVENT_INITIAL_REFRESH = GROUP_VFS.registerEvent("initial_refresh", DurationMs); /* ================== EVENT_REFRESH_SESSION: ====================================================== */ @@ -83,10 +78,7 @@ public final class VfsUsageCollector extends CounterUsagesCollector { /** What causes VFS rebuild (if any) */ private static final EnumEventField FIELD_INITIALIZATION_KIND = Enum("init_kind", VFSInitKind.class); - /** - * How many attempts to init VFS were made. - * In regular caqse, it is only 1 atte22mpt, but could be >1 if VFS was rebuilt. - */ + /** A number of attempts to init VFS. Usually =1, but could be more if VFS was rebuilt. */ private static final IntEventField FIELD_INITIALIZATION_ATTEMPTS = Int("init_attempts"); /** Timestamp current VFS was created & initialized (ms, unix origin) */ private static final LongEventField FIELD_CREATION_TIMESTAMP = Long("creation_timestamp"); @@ -95,18 +87,12 @@ public final class VfsUsageCollector extends CounterUsagesCollector { private static final LongEventField FIELD_TOTAL_INIT_DURATION_MS = Long("init_duration_ms"); private static final StringListEventField FIELD_ERRORS_HAPPENED = StringList( "errors_happened", - Stream.of(VFSInitException.ErrorCategory.values()) - .map(Enum::name) - .toList() + Stream.of(VFSInitException.ErrorCategory.values()).map(Enum::name).toList() ); private static final VarargEventId EVENT_VFS_INITIALIZATION = GROUP_VFS.registerVarargEvent( "initialization", - FIELD_INITIALIZATION_KIND, - FIELD_CREATION_TIMESTAMP, - FIELD_INITIALIZATION_ATTEMPTS, - FIELD_IMPL_VERSION, - FIELD_TOTAL_INIT_DURATION_MS, + FIELD_INITIALIZATION_KIND, FIELD_CREATION_TIMESTAMP, FIELD_INITIALIZATION_ATTEMPTS, FIELD_IMPL_VERSION, FIELD_TOTAL_INIT_DURATION_MS, FIELD_ERRORS_HAPPENED ); @@ -155,7 +141,6 @@ public final class VfsUsageCollector extends CounterUsagesCollector { private static final IntEventField FIELD_HEALTH_CHECK_ATTRIBUTES_ERRORS = Int("attributes_errors"); - private static final VarargEventId EVENT_VFS_HEALTH_CHECK = GROUP_VFS.registerVarargEvent( "health_check", FIELD_HEALTH_CHECK_VFS_CREATION_TIMESTAMP_MS, @@ -194,8 +179,8 @@ public final class VfsUsageCollector extends CounterUsagesCollector { /* ================== EVENT_VFS_ACCUMULATED_ERRORS: ====================================================== */ /** - * Not any errors, but errors that are likely internal VFS errors, i.e. corruptions or - * code bugs. E.g. error due to illegal argument passed from outside is not counted. + * Not any errors, but errors that are likely internal VFS errors, i.e., corruptions or code bugs. + * E.g., error due to illegal argument passed from the outside is not counted. */ private static final IntEventField FIELD_ACCUMULATED_VFS_ERRORS = Int("accumulated_errors"); private static final LongEventField FIELD_TIME_SINCE_STARTUP = Long("time_since_startup_ms"); @@ -203,7 +188,6 @@ public final class VfsUsageCollector extends CounterUsagesCollector { private static final VarargEventId EVENT_VFS_INTERNAL_ERRORS = GROUP_VFS.registerVarargEvent( "internal_errors", FIELD_HEALTH_CHECK_VFS_CREATION_TIMESTAMP_MS, - FIELD_TIME_SINCE_STARTUP, FIELD_ACCUMULATED_VFS_ERRORS ); @@ -220,14 +204,8 @@ public final class VfsUsageCollector extends CounterUsagesCollector { EVENT_INITIAL_REFRESH.log(project, duration); } - public static void logRefreshSession(boolean recursive, - int lfsRoots, - int arcRoots, - int otherRoots, - boolean cancelled, - long wait, - long duration, - int tries) { + public static void logRefreshSession(boolean recursive, int lfsRoots, int arcRoots, int otherRoots, boolean cancelled, + long wait, long duration, int tries) { if (duration >= DURATION_THRESHOLD_MS) { EVENT_REFRESH_SESSION.log( FIELD_REFRESH_RECURSIVE.with(recursive), @@ -280,7 +258,6 @@ public final class VfsUsageCollector extends CounterUsagesCollector { ); } - public static void logVfsHealthCheck(long creationTimestampMs, long checkDurationMs, int fileRecordsChecked,