import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
import { localize2WithPath, localizeWithPath } from '../../../../nls.js';
import { OS, isWindows } from '../../../../base/common/platform.js';
import { extname, basename as basename$1, isAbsolute } from '../../../../base/common/path.js';
import { basename, basenameOrAuthority, joinPath, isEqualOrParent, distinctParents } from '../../../../base/common/resources.js';
import { URI } from '../../../../base/common/uri.js';
import { toErrorMessage } from '../../../../base/common/errorMessage.js';
import { Action } from '../../../../base/common/actions.js';
import { dispose } from '../../../../base/common/lifecycle.js';
import { VIEWLET_ID, VIEW_ID, UndoConfirmLevel } from '../common/files.js';
import { IFileService } from '../../../../platform/files/common/files.service.js';
import { EditorResourceAccessor, SideBySideEditor } from '../../../common/editor.js';
import { ItemActivation } from '../../../../platform/quickinput/common/quickInput.js';
import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.service.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { IHostService } from '../../../services/host/browser/host.service.js';
import { SAVE_ALL_IN_GROUP_COMMAND_ID, REVEAL_IN_EXPLORER_COMMAND_ID, NEW_UNTITLED_FILE_COMMAND_ID } from './fileConstants.js';
import { ITextModelService } from '../../../../editor/common/services/resolverService.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.service.js';
import { IClipboardService } from '../../../../platform/clipboard/common/clipboardService.service.js';
import { ILanguageService } from '../../../../editor/common/languages/language.js';
import { IModelService } from '../../../../editor/common/services/model.js';
import { CommandsRegistry } from '../../../../platform/commands/common/commands.js';
import { ICommandService } from '../../../../platform/commands/common/commands.service.js';
import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js';
import { Schemas } from '../../../../base/common/network.js';
import { getFileNamesMessage } from '../../../../platform/dialogs/common/dialogs.js';
import { IDialogService } from '../../../../platform/dialogs/common/dialogs.service.js';
import '../../../../platform/notification/common/notification.js';
import { INotificationService } from '../../../../platform/notification/common/notification.service.js';
import { IEditorService } from '../../../services/editor/common/editorService.service.js';
import { Constants } from '../../../../base/common/uint.js';
import { CLOSE_EDITORS_AND_GROUP_COMMAND_ID } from '../../../browser/parts/editor/editorCommands.js';
import { coalesce } from '../../../../base/common/arrays.js';
import { NewExplorerItem } from '../common/explorerModel.js';
import { getErrorMessage } from '../../../../base/common/errors.js';
import { triggerUpload } from '../../../../base/browser/dom.js';
import { IFilesConfigurationService } from '../../../services/filesConfiguration/common/filesConfigurationService.service.js';
import { IWorkingCopyService } from '../../../services/workingCopy/common/workingCopyService.service.js';
import { timeout } from '../../../../base/common/async.js';
import { IWorkingCopyFileService } from '../../../services/workingCopy/common/workingCopyFileService.service.js';
import { Codicon } from '../../../../base/common/codicons.js';
import { ThemeIcon } from '../../../../base/common/themables.js';
import { ViewContainerLocation } from '../../../common/views.js';
import { IViewsService } from '../../../services/views/common/viewsService.service.js';
import { trim, rtrim } from '../../../../base/common/strings.js';
import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.service.js';
import { ResourceFileEdit } from '../../../../editor/browser/services/bulkEditService.js';
import { IExplorerService } from './files.service.js';
import { FileDownload, BrowserFileUpload } from './fileImportExport.js';
import { IPaneCompositePartService } from '../../../services/panecomposite/browser/panecomposite.service.js';
import { IRemoteAgentService } from '../../../services/remote/common/remoteAgentService.service.js';
import { IPathService } from '../../../services/path/common/pathService.service.js';
import { Action2 } from '../../../../platform/actions/common/actions.js';
import { ActiveEditorContext, EmptyWorkspaceSupportContext, ActiveEditorCanToggleReadonlyContext } from '../../../common/contextkeys.js';
import { KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js';
import { KeyChord, KeyMod as KeyMod$1, KeyCode } from '../../../../base/common/keyCodes.js';
import { Categories } from '../../../../platform/action/common/actionCommonCategories.js';
import { VSBuffer } from '../../../../base/common/buffer.js';
import Severity$1 from '../../../../base/common/severity.js';
const _moduleId = "vs/workbench/contrib/files/browser/fileActions";
const NEW_FILE_COMMAND_ID = 'explorer.newFile';
const NEW_FILE_LABEL = ( localize2WithPath(_moduleId, 0, "New File..."));
const NEW_FOLDER_COMMAND_ID = 'explorer.newFolder';
const NEW_FOLDER_LABEL = ( localize2WithPath(_moduleId, 1, "New Folder..."));
const TRIGGER_RENAME_LABEL = ( localizeWithPath(_moduleId, 2, "Rename..."));
const MOVE_FILE_TO_TRASH_LABEL = ( localizeWithPath(_moduleId, 3, "Delete"));
const COPY_FILE_LABEL = ( localizeWithPath(_moduleId, 4, "Copy"));
const PASTE_FILE_LABEL = ( localizeWithPath(_moduleId, 5, "Paste"));
const FileCopiedContext = ( (new RawContextKey('fileCopied', false)));
const DOWNLOAD_COMMAND_ID = 'explorer.download';
const DOWNLOAD_LABEL = ( localizeWithPath(_moduleId, 6, "Download..."));
const UPLOAD_COMMAND_ID = 'explorer.upload';
const UPLOAD_LABEL = ( localizeWithPath(_moduleId, 7, "Upload..."));
const CONFIRM_DELETE_SETTING_KEY = 'explorer.confirmDelete';
const MAX_UNDO_FILE_SIZE = 5000000;
function onError(notificationService, error) {
    if (error.message === 'string') {
        error = error.message;
    }
    notificationService.error(toErrorMessage(error, false));
}
async function refreshIfSeparator(value, explorerService) {
    if (value && ((value.indexOf('/') >= 0) || (value.indexOf('\\') >= 0))) {
        await explorerService.refresh();
    }
}
async function deleteFiles(explorerService, workingCopyFileService, dialogService, configurationService, elements, useTrash, skipConfirm = false, ignoreIfNotExists = false) {
    let primaryButton;
    if (useTrash) {
        primaryButton = isWindows ? ( localizeWithPath(_moduleId, 8, "&&Move to Recycle Bin")) : ( localizeWithPath(_moduleId, 9, "&&Move to Trash"));
    }
    else {
        primaryButton = ( localizeWithPath(_moduleId, 10, "&&Delete"));
    }
    const distinctElements = distinctParents(elements, e => e.resource);
    const dirtyWorkingCopies = ( (new Set()));
    for (const distinctElement of distinctElements) {
        for (const dirtyWorkingCopy of workingCopyFileService.getDirty(distinctElement.resource)) {
            dirtyWorkingCopies.add(dirtyWorkingCopy);
        }
    }
    let confirmed = true;
    if (dirtyWorkingCopies.size) {
        let message;
        if (distinctElements.length > 1) {
            message = ( localizeWithPath(
                _moduleId,
                11,
                "You are deleting files with unsaved changes. Do you want to continue?"
            ));
        }
        else if (distinctElements[0].isDirectory) {
            if (dirtyWorkingCopies.size === 1) {
                message = ( localizeWithPath(
                    _moduleId,
                    12,
                    "You are deleting a folder {0} with unsaved changes in 1 file. Do you want to continue?",
                    distinctElements[0].name
                ));
            }
            else {
                message = ( localizeWithPath(
                    _moduleId,
                    13,
                    "You are deleting a folder {0} with unsaved changes in {1} files. Do you want to continue?",
                    distinctElements[0].name,
                    dirtyWorkingCopies.size
                ));
            }
        }
        else {
            message = ( localizeWithPath(
                _moduleId,
                14,
                "You are deleting {0} with unsaved changes. Do you want to continue?",
                distinctElements[0].name
            ));
        }
        const response = await dialogService.confirm({
            type: 'warning',
            message,
            detail: ( localizeWithPath(_moduleId, 15, "Your changes will be lost if you don't save them.")),
            primaryButton
        });
        if (!response.confirmed) {
            confirmed = false;
        }
        else {
            skipConfirm = true;
        }
    }
    if (!confirmed) {
        return;
    }
    let confirmation;
    const deleteDetail = ( (distinctElements.some(e => e.isDirectory))) ? ( localizeWithPath(_moduleId, 16, "This action is irreversible!")) :
        distinctElements.length > 1 ? ( localizeWithPath(_moduleId, 17, "You can restore these files using the Undo command.")) : ( localizeWithPath(_moduleId, 18, "You can restore this file using the Undo command."));
    if (skipConfirm || (useTrash && configurationService.getValue(CONFIRM_DELETE_SETTING_KEY) === false)) {
        confirmation = { confirmed: true };
    }
    else if (useTrash) {
        let { message, detail } = getMoveToTrashMessage(distinctElements);
        detail += detail ? '\n' : '';
        if (isWindows) {
            detail += distinctElements.length > 1 ? ( localizeWithPath(_moduleId, 19, "You can restore these files from the Recycle Bin.")) : ( localizeWithPath(_moduleId, 20, "You can restore this file from the Recycle Bin."));
        }
        else {
            detail += distinctElements.length > 1 ? ( localizeWithPath(_moduleId, 21, "You can restore these files from the Trash.")) : ( localizeWithPath(_moduleId, 22, "You can restore this file from the Trash."));
        }
        confirmation = await dialogService.confirm({
            message,
            detail,
            primaryButton,
            checkbox: {
                label: ( localizeWithPath(_moduleId, 23, "Do not ask me again"))
            }
        });
    }
    else {
        let { message, detail } = getDeleteMessage(distinctElements);
        detail += detail ? '\n' : '';
        detail += deleteDetail;
        confirmation = await dialogService.confirm({
            type: 'warning',
            message,
            detail,
            primaryButton
        });
    }
    if (confirmation.confirmed && confirmation.checkboxChecked === true) {
        await configurationService.updateValue(CONFIRM_DELETE_SETTING_KEY, false);
    }
    if (!confirmation.confirmed) {
        return;
    }
    try {
        const resourceFileEdits = ( (distinctElements.map(e => ( (new ResourceFileEdit(
            e.resource,
            undefined,
            { recursive: true, folder: e.isDirectory, ignoreIfNotExists, skipTrashBin: !useTrash, maxSize: MAX_UNDO_FILE_SIZE }
        ))))));
        const options = {
            undoLabel: distinctElements.length > 1 ? ( localizeWithPath(_moduleId, 24, "Delete {0} files", distinctElements.length)) : ( localizeWithPath(_moduleId, 25, "Delete {0}", distinctElements[0].name)),
            progressLabel: distinctElements.length > 1 ? ( localizeWithPath(_moduleId, 26, "Deleting {0} files", distinctElements.length)) : ( localizeWithPath(_moduleId, 27, "Deleting {0}", distinctElements[0].name)),
        };
        await explorerService.applyBulkEdit(resourceFileEdits, options);
    }
    catch (error) {
        let errorMessage;
        let detailMessage;
        let primaryButton;
        if (useTrash) {
            errorMessage = isWindows ? ( localizeWithPath(
                _moduleId,
                28,
                "Failed to delete using the Recycle Bin. Do you want to permanently delete instead?"
            )) : ( localizeWithPath(
                _moduleId,
                29,
                "Failed to delete using the Trash. Do you want to permanently delete instead?"
            ));
            detailMessage = deleteDetail;
            primaryButton = ( localizeWithPath(_moduleId, 30, "&&Delete Permanently"));
        }
        else {
            errorMessage = toErrorMessage(error, false);
            primaryButton = ( localizeWithPath(_moduleId, 31, "&&Retry"));
        }
        const res = await dialogService.confirm({
            type: 'warning',
            message: errorMessage,
            detail: detailMessage,
            primaryButton
        });
        if (res.confirmed) {
            if (useTrash) {
                useTrash = false;
            }
            skipConfirm = true;
            ignoreIfNotExists = true;
            return deleteFiles(explorerService, workingCopyFileService, dialogService, configurationService, elements, useTrash, skipConfirm, ignoreIfNotExists);
        }
    }
}
function getMoveToTrashMessage(distinctElements) {
    if (containsBothDirectoryAndFile(distinctElements)) {
        return {
            message: ( localizeWithPath(
                _moduleId,
                32,
                "Are you sure you want to delete the following {0} files/directories and their contents?",
                distinctElements.length
            )),
            detail: getFileNamesMessage(( (distinctElements.map(e => e.resource))))
        };
    }
    if (distinctElements.length > 1) {
        if (distinctElements[0].isDirectory) {
            return {
                message: ( localizeWithPath(
                    _moduleId,
                    33,
                    "Are you sure you want to delete the following {0} directories and their contents?",
                    distinctElements.length
                )),
                detail: getFileNamesMessage(( (distinctElements.map(e => e.resource))))
            };
        }
        return {
            message: ( localizeWithPath(
                _moduleId,
                34,
                "Are you sure you want to delete the following {0} files?",
                distinctElements.length
            )),
            detail: getFileNamesMessage(( (distinctElements.map(e => e.resource))))
        };
    }
    if (distinctElements[0].isDirectory && !distinctElements[0].isSymbolicLink) {
        return { message: ( localizeWithPath(
            _moduleId,
            35,
            "Are you sure you want to delete '{0}' and its contents?",
            distinctElements[0].name
        )), detail: '' };
    }
    return { message: ( localizeWithPath(
        _moduleId,
        36,
        "Are you sure you want to delete '{0}'?",
        distinctElements[0].name
    )), detail: '' };
}
function getDeleteMessage(distinctElements) {
    if (containsBothDirectoryAndFile(distinctElements)) {
        return {
            message: ( localizeWithPath(
                _moduleId,
                37,
                "Are you sure you want to permanently delete the following {0} files/directories and their contents?",
                distinctElements.length
            )),
            detail: getFileNamesMessage(( (distinctElements.map(e => e.resource))))
        };
    }
    if (distinctElements.length > 1) {
        if (distinctElements[0].isDirectory) {
            return {
                message: ( localizeWithPath(
                    _moduleId,
                    38,
                    "Are you sure you want to permanently delete the following {0} directories and their contents?",
                    distinctElements.length
                )),
                detail: getFileNamesMessage(( (distinctElements.map(e => e.resource))))
            };
        }
        return {
            message: ( localizeWithPath(
                _moduleId,
                39,
                "Are you sure you want to permanently delete the following {0} files?",
                distinctElements.length
            )),
            detail: getFileNamesMessage(( (distinctElements.map(e => e.resource))))
        };
    }
    if (distinctElements[0].isDirectory) {
        return { message: ( localizeWithPath(
            _moduleId,
            40,
            "Are you sure you want to permanently delete '{0}' and its contents?",
            distinctElements[0].name
        )), detail: '' };
    }
    return { message: ( localizeWithPath(
        _moduleId,
        41,
        "Are you sure you want to permanently delete '{0}'?",
        distinctElements[0].name
    )), detail: '' };
}
function containsBothDirectoryAndFile(distinctElements) {
    const directory = distinctElements.find(element => element.isDirectory);
    const file = distinctElements.find(element => !element.isDirectory);
    return !!directory && !!file;
}
async function findValidPasteFileTarget(explorerService, fileService, dialogService, targetFolder, fileToPaste, incrementalNaming) {
    let name = typeof fileToPaste.resource === 'string' ? fileToPaste.resource : basenameOrAuthority(fileToPaste.resource);
    let candidate = joinPath(targetFolder.resource, name);
    if (incrementalNaming === 'disabled') {
        const canOverwrite = await askForOverwrite(fileService, dialogService, candidate);
        if (!canOverwrite) {
            return;
        }
    }
    while (!fileToPaste.allowOverwrite) {
        if (!explorerService.findClosest(candidate)) {
            break;
        }
        if (incrementalNaming !== 'disabled') {
            name = incrementFileName(name, !!fileToPaste.isDirectory, incrementalNaming);
        }
        candidate = joinPath(targetFolder.resource, name);
    }
    return candidate;
}
function incrementFileName(name, isFolder, incrementalNaming) {
    if (incrementalNaming === 'simple') {
        let namePrefix = name;
        let extSuffix = '';
        if (!isFolder) {
            extSuffix = extname(name);
            namePrefix = basename$1(name, extSuffix);
        }
        const suffixRegex = /^(.+ copy)( \d+)?$/;
        if (suffixRegex.test(namePrefix)) {
            return namePrefix.replace(suffixRegex, (match, g1, g2) => {
                const number = (g2 ? parseInt(g2) : 1);
                return number === 0
                    ? `${g1}`
                    : (number < Constants.MAX_SAFE_SMALL_INTEGER
                        ? `${g1} ${number + 1}`
                        : `${g1}${g2} copy`);
            }) + extSuffix;
        }
        return `${namePrefix} copy${extSuffix}`;
    }
    const separators = '[\\.\\-_]';
    const maxNumber = Constants.MAX_SAFE_SMALL_INTEGER;
    const suffixFileRegex = RegExp('(.*' + separators + ')(\\d+)(\\..*)$');
    if (!isFolder && name.match(suffixFileRegex)) {
        return name.replace(suffixFileRegex, (match, g1, g2, g3) => {
            const number = parseInt(g2);
            return number < maxNumber
                ? g1 + String(number + 1).padStart(g2.length, '0') + g3
                : `${g1}${g2}.1${g3}`;
        });
    }
    const prefixFileRegex = RegExp('(\\d+)(' + separators + '.*)(\\..*)$');
    if (!isFolder && name.match(prefixFileRegex)) {
        return name.replace(prefixFileRegex, (match, g1, g2, g3) => {
            const number = parseInt(g1);
            return number < maxNumber
                ? String(number + 1).padStart(g1.length, '0') + g2 + g3
                : `${g1}${g2}.1${g3}`;
        });
    }
    const prefixFileNoNameRegex = RegExp('(\\d+)(\\..*)$');
    if (!isFolder && name.match(prefixFileNoNameRegex)) {
        return name.replace(prefixFileNoNameRegex, (match, g1, g2) => {
            const number = parseInt(g1);
            return number < maxNumber
                ? String(number + 1).padStart(g1.length, '0') + g2
                : `${g1}.1${g2}`;
        });
    }
    const lastIndexOfDot = name.lastIndexOf('.');
    if (!isFolder && lastIndexOfDot >= 0) {
        return `${name.substr(0, lastIndexOfDot)}.1${name.substr(lastIndexOfDot)}`;
    }
    const noNameNoExtensionRegex = RegExp('(\\d+)$');
    if (!isFolder && lastIndexOfDot === -1 && name.match(noNameNoExtensionRegex)) {
        return name.replace(noNameNoExtensionRegex, (match, g1) => {
            const number = parseInt(g1);
            return number < maxNumber
                ? String(number + 1).padStart(g1.length, '0')
                : `${g1}.1`;
        });
    }
    const noExtensionRegex = RegExp('(.*)(\\d*)$');
    if (!isFolder && lastIndexOfDot === -1 && name.match(noExtensionRegex)) {
        return name.replace(noExtensionRegex, (match, g1, g2) => {
            let number = parseInt(g2);
            if (isNaN(number)) {
                number = 0;
            }
            return number < maxNumber
                ? g1 + String(number + 1).padStart(g2.length, '0')
                : `${g1}${g2}.1`;
        });
    }
    if (isFolder && name.match(/(\d+)$/)) {
        return name.replace(/(\d+)$/, (match, ...groups) => {
            const number = parseInt(groups[0]);
            return number < maxNumber
                ? String(number + 1).padStart(groups[0].length, '0')
                : `${groups[0]}.1`;
        });
    }
    if (isFolder && name.match(/^(\d+)/)) {
        return name.replace(/^(\d+)(.*)$/, (match, ...groups) => {
            const number = parseInt(groups[0]);
            return number < maxNumber
                ? String(number + 1).padStart(groups[0].length, '0') + groups[1]
                : `${groups[0]}${groups[1]}.1`;
        });
    }
    return `${name}.1`;
}
async function askForOverwrite(fileService, dialogService, targetResource) {
    const exists = await fileService.exists(targetResource);
    if (!exists) {
        return true;
    }
    const { confirmed } = await dialogService.confirm({
        type: Severity$1.Warning,
        message: ( localizeWithPath(
            _moduleId,
            42,
            "A file or folder with the name '{0}' already exists in the destination folder. Do you want to replace it?",
            basename$1(targetResource.path)
        )),
        primaryButton: ( localizeWithPath(_moduleId, 43, "&&Replace"))
    });
    return confirmed;
}
class GlobalCompareResourcesAction extends Action2 {
    static { this.ID = 'workbench.files.action.compareFileWith'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 44, "Compare Active File With...")); }
    constructor() {
        super({
            id: GlobalCompareResourcesAction.ID,
            title: GlobalCompareResourcesAction.LABEL,
            f1: true,
            category: Categories.File,
            precondition: ActiveEditorContext,
            metadata: {
                description: ( localize2WithPath(
                    _moduleId,
                    45,
                    "Opens a picker to select a file to diff with the active editor."
                ))
            }
        });
    }
    async run(accessor) {
        const editorService = accessor.get(IEditorService);
        const textModelService = accessor.get(ITextModelService);
        const quickInputService = accessor.get(IQuickInputService);
        const activeInput = editorService.activeEditor;
        const activeResource = EditorResourceAccessor.getOriginalUri(activeInput);
        if (activeResource && textModelService.canHandleResource(activeResource)) {
            const picks = await quickInputService.quickAccess.pick('', { itemActivation: ItemActivation.SECOND });
            if (picks?.length === 1) {
                const resource = picks[0].resource;
                if (URI.isUri(resource) && textModelService.canHandleResource(resource)) {
                    editorService.openEditor({
                        original: { resource: activeResource },
                        modified: { resource: resource },
                        options: { pinned: true }
                    });
                }
            }
        }
    }
}
class ToggleAutoSaveAction extends Action2 {
    static { this.ID = 'workbench.action.toggleAutoSave'; }
    constructor() {
        super({
            id: ToggleAutoSaveAction.ID,
            title: ( localize2WithPath(_moduleId, 46, "Toggle Auto Save")),
            f1: true,
            category: Categories.File,
            metadata: { description: ( localize2WithPath(
                _moduleId,
                47,
                "Toggle the ability to save files automatically after typing"
            )) }
        });
    }
    run(accessor) {
        const filesConfigurationService = accessor.get(IFilesConfigurationService);
        return filesConfigurationService.toggleAutoSave();
    }
}
let BaseSaveAllAction = class BaseSaveAllAction extends Action {
    constructor(id, label, commandService, notificationService, workingCopyService) {
        super(id, label);
        this.commandService = commandService;
        this.notificationService = notificationService;
        this.workingCopyService = workingCopyService;
        this.lastDirtyState = this.workingCopyService.hasDirty;
        this.enabled = this.lastDirtyState;
        this.registerListeners();
    }
    registerListeners() {
        this._register(this.workingCopyService.onDidChangeDirty(workingCopy => this.updateEnablement(workingCopy)));
    }
    updateEnablement(workingCopy) {
        const hasDirty = workingCopy.isDirty() || this.workingCopyService.hasDirty;
        if (this.lastDirtyState !== hasDirty) {
            this.enabled = hasDirty;
            this.lastDirtyState = this.enabled;
        }
    }
    async run(context) {
        try {
            await this.doRun(context);
        }
        catch (error) {
            onError(this.notificationService, error);
        }
    }
};
BaseSaveAllAction = ( (__decorate([
    ( (__param(2, ICommandService))),
    ( (__param(3, INotificationService))),
    ( (__param(4, IWorkingCopyService)))
], BaseSaveAllAction)));
class SaveAllInGroupAction extends BaseSaveAllAction {
    static { this.ID = 'workbench.files.action.saveAllInGroup'; }
    static { this.LABEL = ( localizeWithPath(_moduleId, 48, "Save All in Group")); }
    get class() {
        return 'explorer-action ' + ThemeIcon.asClassName(Codicon.saveAll);
    }
    doRun(context) {
        return this.commandService.executeCommand(SAVE_ALL_IN_GROUP_COMMAND_ID, {}, context);
    }
}
let CloseGroupAction = class CloseGroupAction extends Action {
    static { this.ID = 'workbench.files.action.closeGroup'; }
    static { this.LABEL = ( localizeWithPath(_moduleId, 49, "Close Group")); }
    constructor(id, label, commandService) {
        super(id, label, ThemeIcon.asClassName(Codicon.closeAll));
        this.commandService = commandService;
    }
    run(context) {
        return this.commandService.executeCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, {}, context);
    }
};
CloseGroupAction = ( (__decorate([
    ( (__param(2, ICommandService)))
], CloseGroupAction)));
class FocusFilesExplorer extends Action2 {
    static { this.ID = 'workbench.files.action.focusFilesExplorer'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 50, "Focus on Files Explorer")); }
    constructor() {
        super({
            id: FocusFilesExplorer.ID,
            title: FocusFilesExplorer.LABEL,
            f1: true,
            category: Categories.File,
            metadata: {
                description: ( localize2WithPath(_moduleId, 51, "Moves focus to the file explorer view container."))
            }
        });
    }
    async run(accessor) {
        const paneCompositeService = accessor.get(IPaneCompositePartService);
        await paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true);
    }
}
class ShowActiveFileInExplorer extends Action2 {
    static { this.ID = 'workbench.files.action.showActiveFileInExplorer'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 52, "Reveal Active File in Explorer View")); }
    constructor() {
        super({
            id: ShowActiveFileInExplorer.ID,
            title: ShowActiveFileInExplorer.LABEL,
            f1: true,
            category: Categories.File,
            metadata: {
                description: ( localize2WithPath(
                    _moduleId,
                    53,
                    "Reveals and selects the active file within the explorer view."
                ))
            }
        });
    }
    async run(accessor) {
        const commandService = accessor.get(ICommandService);
        const editorService = accessor.get(IEditorService);
        const resource = EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
        if (resource) {
            commandService.executeCommand(REVEAL_IN_EXPLORER_COMMAND_ID, resource);
        }
    }
}
class OpenActiveFileInEmptyWorkspace extends Action2 {
    static { this.ID = 'workbench.action.files.showOpenedFileInNewWindow'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 54, "Open Active File in New Empty Workspace")); }
    constructor() {
        super({
            id: OpenActiveFileInEmptyWorkspace.ID,
            title: OpenActiveFileInEmptyWorkspace.LABEL,
            f1: true,
            category: Categories.File,
            precondition: EmptyWorkspaceSupportContext,
            metadata: {
                description: ( localize2WithPath(
                    _moduleId,
                    55,
                    "Opens the active file in a new window with no folders open."
                ))
            }
        });
    }
    async run(accessor) {
        const editorService = accessor.get(IEditorService);
        const hostService = accessor.get(IHostService);
        const dialogService = accessor.get(IDialogService);
        const fileService = accessor.get(IFileService);
        const fileResource = EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
        if (fileResource) {
            if (fileService.hasProvider(fileResource)) {
                hostService.openWindow([{ fileUri: fileResource }], { forceNewWindow: true });
            }
            else {
                dialogService.error(( localizeWithPath(_moduleId, 56, "The active editor must contain an openable resource.")));
            }
        }
    }
}
function validateFileName(pathService, item, name, os) {
    name = getWellFormedFileName(name);
    if (!name || name.length === 0 || /^\s+$/.test(name)) {
        return {
            content: ( localizeWithPath(_moduleId, 57, "A file or folder name must be provided.")),
            severity: Severity$1.Error
        };
    }
    if (name[0] === '/' || name[0] === '\\') {
        return {
            content: ( localizeWithPath(_moduleId, 58, "A file or folder name cannot start with a slash.")),
            severity: Severity$1.Error
        };
    }
    const names = coalesce(name.split(/[\\/]/));
    const parent = item.parent;
    if (name !== item.name) {
        const child = parent?.getChild(name);
        if (child && child !== item) {
            return {
                content: ( localizeWithPath(
                    _moduleId,
                    59,
                    "A file or folder **{0}** already exists at this location. Please choose a different name.",
                    name
                )),
                severity: Severity$1.Error
            };
        }
    }
    if (( (names.some(folderName => !pathService.hasValidBasename(item.resource, os, folderName))))) {
        const escapedName = name.replace(/\*/g, '\\*');
        return {
            content: ( localizeWithPath(
                _moduleId,
                60,
                "The name **{0}** is not valid as a file or folder name. Please choose a different name.",
                trimLongName(escapedName)
            )),
            severity: Severity$1.Error
        };
    }
    if (( (names.some(name => /^\s|\s$/.test(name))))) {
        return {
            content: ( localizeWithPath(
                _moduleId,
                61,
                "Leading or trailing whitespace detected in file or folder name."
            )),
            severity: Severity$1.Warning
        };
    }
    return null;
}
function trimLongName(name) {
    if (name?.length > 255) {
        return `${name.substr(0, 255)}...`;
    }
    return name;
}
function getWellFormedFileName(filename) {
    if (!filename) {
        return filename;
    }
    filename = trim(filename, '\t');
    filename = rtrim(filename, '/');
    filename = rtrim(filename, '\\');
    return filename;
}
class CompareNewUntitledTextFilesAction extends Action2 {
    static { this.ID = 'workbench.files.action.compareNewUntitledTextFiles'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 62, "Compare New Untitled Text Files")); }
    constructor() {
        super({
            id: CompareNewUntitledTextFilesAction.ID,
            title: CompareNewUntitledTextFilesAction.LABEL,
            f1: true,
            category: Categories.File,
            metadata: {
                description: ( localize2WithPath(_moduleId, 63, "Opens a new diff editor with two untitled files."))
            }
        });
    }
    async run(accessor) {
        const editorService = accessor.get(IEditorService);
        await editorService.openEditor({
            original: { resource: undefined },
            modified: { resource: undefined },
            options: { pinned: true }
        });
    }
}
class CompareWithClipboardAction extends Action2 {
    static { this.ID = 'workbench.files.action.compareWithClipboard'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 64, "Compare Active File with Clipboard")); }
    static { this.SCHEME_COUNTER = 0; }
    constructor() {
        super({
            id: CompareWithClipboardAction.ID,
            title: CompareWithClipboardAction.LABEL,
            f1: true,
            category: Categories.File,
            keybinding: { primary: KeyChord(KeyMod$1.CtrlCmd | KeyCode.KeyK, KeyCode.KeyC), weight: KeybindingWeight.WorkbenchContrib },
            metadata: {
                description: ( localize2WithPath(
                    _moduleId,
                    65,
                    "Opens a new diff editor to compare the active file with the contents of the clipboard."
                ))
            }
        });
    }
    async run(accessor) {
        const editorService = accessor.get(IEditorService);
        const instantiationService = accessor.get(IInstantiationService);
        const textModelService = accessor.get(ITextModelService);
        const fileService = accessor.get(IFileService);
        const resource = EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
        const scheme = `clipboardCompare${CompareWithClipboardAction.SCHEME_COUNTER++}`;
        if (resource && (fileService.hasProvider(resource) || resource.scheme === Schemas.untitled)) {
            if (!this.registrationDisposal) {
                const provider = instantiationService.createInstance(ClipboardContentProvider);
                this.registrationDisposal = textModelService.registerTextModelContentProvider(scheme, provider);
            }
            const name = basename(resource);
            const editorLabel = ( localizeWithPath(_moduleId, 66, "Clipboard ↔ {0}", name));
            await editorService.openEditor({
                original: { resource: resource.with({ scheme }) },
                modified: { resource: resource },
                label: editorLabel,
                options: { pinned: true }
            }).finally(() => {
                dispose(this.registrationDisposal);
                this.registrationDisposal = undefined;
            });
        }
    }
    dispose() {
        dispose(this.registrationDisposal);
        this.registrationDisposal = undefined;
    }
}
let ClipboardContentProvider = class ClipboardContentProvider {
    constructor(clipboardService, languageService, modelService) {
        this.clipboardService = clipboardService;
        this.languageService = languageService;
        this.modelService = modelService;
    }
    async provideTextContent(resource) {
        const text = await this.clipboardService.readText();
        const model = this.modelService.createModel(text, this.languageService.createByFilepathOrFirstLine(resource), resource);
        return model;
    }
};
ClipboardContentProvider = ( (__decorate([
    ( (__param(0, IClipboardService))),
    ( (__param(1, ILanguageService))),
    ( (__param(2, IModelService)))
], ClipboardContentProvider)));
function onErrorWithRetry(notificationService, error, retry) {
    notificationService.prompt(Severity$1.Error, toErrorMessage(error, false), [{
            label: ( localizeWithPath(_moduleId, 67, "Retry")),
            run: () => retry()
        }]);
}
async function openExplorerAndCreate(accessor, isFolder) {
    const explorerService = accessor.get(IExplorerService);
    const fileService = accessor.get(IFileService);
    const configService = accessor.get(IConfigurationService);
    const filesConfigService = accessor.get(IFilesConfigurationService);
    const editorService = accessor.get(IEditorService);
    const viewsService = accessor.get(IViewsService);
    const notificationService = accessor.get(INotificationService);
    const remoteAgentService = accessor.get(IRemoteAgentService);
    const commandService = accessor.get(ICommandService);
    const pathService = accessor.get(IPathService);
    const wasHidden = !viewsService.isViewVisible(VIEW_ID);
    const view = await viewsService.openView(VIEW_ID, true);
    if (wasHidden) {
        await timeout(500);
    }
    if (!view) {
        if (isFolder) {
            throw ( (new Error('Open a folder or workspace first.')));
        }
        return commandService.executeCommand(NEW_UNTITLED_FILE_COMMAND_ID);
    }
    const stats = explorerService.getContext(false);
    const stat = stats.length > 0 ? stats[0] : undefined;
    let folder;
    if (stat) {
        folder = stat.isDirectory ? stat : (stat.parent || explorerService.roots[0]);
    }
    else {
        folder = explorerService.roots[0];
    }
    if (folder.isReadonly) {
        throw ( (new Error('Parent folder is readonly.')));
    }
    const newStat = ( (new NewExplorerItem(fileService, configService, filesConfigService, folder, isFolder)));
    folder.addChild(newStat);
    const onSuccess = async (value) => {
        try {
            const resourceToCreate = joinPath(folder.resource, value);
            if (value.endsWith('/')) {
                isFolder = true;
            }
            await explorerService.applyBulkEdit([( (new ResourceFileEdit(undefined, resourceToCreate, { folder: isFolder })))], {
                undoLabel: ( localizeWithPath(_moduleId, 68, "Create {0}", value)),
                progressLabel: ( localizeWithPath(_moduleId, 69, "Creating {0}", value)),
                confirmBeforeUndo: true
            });
            await refreshIfSeparator(value, explorerService);
            if (isFolder) {
                await explorerService.select(resourceToCreate, true);
            }
            else {
                await editorService.openEditor({ resource: resourceToCreate, options: { pinned: true } });
            }
        }
        catch (error) {
            onErrorWithRetry(notificationService, error, () => onSuccess(value));
        }
    };
    const os = (await remoteAgentService.getEnvironment())?.os ?? OS;
    await explorerService.setEditable(newStat, {
        validationMessage: value => validateFileName(pathService, newStat, value, os),
        onFinish: async (value, success) => {
            folder.removeChild(newStat);
            await explorerService.setEditable(newStat, null);
            if (success) {
                onSuccess(value);
            }
        }
    });
}
CommandsRegistry.registerCommand({
    id: NEW_FILE_COMMAND_ID,
    handler: async (accessor) => {
        await openExplorerAndCreate(accessor, false);
    }
});
CommandsRegistry.registerCommand({
    id: NEW_FOLDER_COMMAND_ID,
    handler: async (accessor) => {
        await openExplorerAndCreate(accessor, true);
    }
});
const renameHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const notificationService = accessor.get(INotificationService);
    const remoteAgentService = accessor.get(IRemoteAgentService);
    const pathService = accessor.get(IPathService);
    const configurationService = accessor.get(IConfigurationService);
    const stats = explorerService.getContext(false);
    const stat = stats.length > 0 ? stats[0] : undefined;
    if (!stat) {
        return;
    }
    const os = (await remoteAgentService.getEnvironment())?.os ?? OS;
    await explorerService.setEditable(stat, {
        validationMessage: value => validateFileName(pathService, stat, value, os),
        onFinish: async (value, success) => {
            if (success) {
                const parentResource = stat.parent.resource;
                const targetResource = joinPath(parentResource, value);
                if (( (stat.resource.toString())) !== ( (targetResource.toString()))) {
                    try {
                        await explorerService.applyBulkEdit([( (new ResourceFileEdit(stat.resource, targetResource)))], {
                            confirmBeforeUndo: configurationService.getValue().explorer.confirmUndo === UndoConfirmLevel.Verbose,
                            undoLabel: ( localizeWithPath(_moduleId, 70, "Rename {0} to {1}", stat.name, value)),
                            progressLabel: ( localizeWithPath(_moduleId, 71, "Renaming {0} to {1}", stat.name, value)),
                        });
                        await refreshIfSeparator(value, explorerService);
                    }
                    catch (e) {
                        notificationService.error(e);
                    }
                }
            }
            await explorerService.setEditable(stat, null);
        }
    });
};
const moveFileToTrashHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const stats = explorerService.getContext(true).filter(s => !s.isRoot);
    if (stats.length) {
        await deleteFiles(accessor.get(IExplorerService), accessor.get(IWorkingCopyFileService), accessor.get(IDialogService), accessor.get(IConfigurationService), stats, true);
    }
};
const deleteFileHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const stats = explorerService.getContext(true).filter(s => !s.isRoot);
    if (stats.length) {
        await deleteFiles(accessor.get(IExplorerService), accessor.get(IWorkingCopyFileService), accessor.get(IDialogService), accessor.get(IConfigurationService), stats, false);
    }
};
let pasteShouldMove = false;
const copyFileHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const stats = explorerService.getContext(true);
    if (stats.length > 0) {
        await explorerService.setToCopy(stats, false);
        pasteShouldMove = false;
    }
};
const cutFileHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const stats = explorerService.getContext(true);
    if (stats.length > 0) {
        await explorerService.setToCopy(stats, true);
        pasteShouldMove = true;
    }
};
const downloadFileHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const notificationService = accessor.get(INotificationService);
    const instantiationService = accessor.get(IInstantiationService);
    const context = explorerService.getContext(true);
    const explorerItems = context.length ? context : explorerService.roots;
    const downloadHandler = instantiationService.createInstance(FileDownload);
    try {
        await downloadHandler.download(explorerItems);
    }
    catch (error) {
        notificationService.error(error);
        throw error;
    }
};
CommandsRegistry.registerCommand({
    id: DOWNLOAD_COMMAND_ID,
    handler: downloadFileHandler
});
const uploadFileHandler = async (accessor) => {
    const explorerService = accessor.get(IExplorerService);
    const notificationService = accessor.get(INotificationService);
    const instantiationService = accessor.get(IInstantiationService);
    const context = explorerService.getContext(false);
    const element = context.length ? context[0] : explorerService.roots[0];
    try {
        const files = await triggerUpload();
        if (files) {
            const browserUpload = instantiationService.createInstance(BrowserFileUpload);
            await browserUpload.upload(element, files);
        }
    }
    catch (error) {
        notificationService.error(error);
        throw error;
    }
};
CommandsRegistry.registerCommand({
    id: UPLOAD_COMMAND_ID,
    handler: uploadFileHandler
});
const pasteFileHandler = async (accessor, fileList) => {
    const clipboardService = accessor.get(IClipboardService);
    const explorerService = accessor.get(IExplorerService);
    const fileService = accessor.get(IFileService);
    const notificationService = accessor.get(INotificationService);
    const editorService = accessor.get(IEditorService);
    const configurationService = accessor.get(IConfigurationService);
    const uriIdentityService = accessor.get(IUriIdentityService);
    const dialogService = accessor.get(IDialogService);
    const hostService = accessor.get(IHostService);
    const context = explorerService.getContext(false);
    const hasNativeFilesToPaste = fileList && fileList.length > 0;
    const confirmPasteNative = hasNativeFilesToPaste && configurationService.getValue('explorer.confirmPasteNative');
    const toPaste = await getFilesToPaste(fileList, clipboardService, hostService);
    if (confirmPasteNative && toPaste.files.length >= 1) {
        const message = toPaste.files.length > 1 ?
            ( localizeWithPath(
                _moduleId,
                72,
                "Are you sure you want to paste the following {0} items?",
                toPaste.files.length
            )) :
            ( localizeWithPath(
                _moduleId,
                73,
                "Are you sure you want to paste '{0}'?",
                basename$1(toPaste.type === 'paths' ? toPaste.files[0].fsPath : toPaste.files[0].name)
            ));
        const detail = toPaste.files.length > 1 ? getFileNamesMessage(( (toPaste.files.map(item => {
            if (URI.isUri(item)) {
                return item.fsPath;
            }
            if (toPaste.type === 'paths') {
                const path = hostService.getPathForFile(item);
                if (path) {
                    return path;
                }
            }
            return item.name;
        })))) : undefined;
        const confirmation = await dialogService.confirm({
            message,
            detail,
            checkbox: {
                label: ( localizeWithPath(_moduleId, 23, "Do not ask me again"))
            },
            primaryButton: ( localizeWithPath(_moduleId, 74, "&&Paste"))
        });
        if (!confirmation.confirmed) {
            return;
        }
        if (confirmation.checkboxChecked === true) {
            await configurationService.updateValue('explorer.confirmPasteNative', false);
        }
    }
    const element = context.length ? context[0] : explorerService.roots[0];
    const incrementalNaming = configurationService.getValue().explorer.incrementalNaming;
    const editableItem = explorerService.getEditable();
    if (editableItem) {
        return;
    }
    try {
        let targets = [];
        if (toPaste.type === 'paths') {
            const sourceTargetPairs = coalesce(await Promise.all(( (toPaste.files.map(async (fileToPaste) => {
                if (( (element.resource.toString())) !== ( (fileToPaste.toString())) && isEqualOrParent(element.resource, fileToPaste)) {
                    throw ( (new Error(
                        localizeWithPath(_moduleId, 75, "File to paste is an ancestor of the destination folder")
                    )));
                }
                const fileToPasteStat = await fileService.stat(fileToPaste);
                let target;
                if (uriIdentityService.extUri.isEqual(element.resource, fileToPaste)) {
                    target = element.parent;
                }
                else {
                    target = element.isDirectory ? element : element.parent;
                }
                const targetFile = await findValidPasteFileTarget(explorerService, fileService, dialogService, target, { resource: fileToPaste, isDirectory: fileToPasteStat.isDirectory, allowOverwrite: pasteShouldMove || incrementalNaming === 'disabled' }, incrementalNaming);
                if (!targetFile) {
                    return undefined;
                }
                return { source: fileToPaste, target: targetFile };
            })))));
            if (sourceTargetPairs.length >= 1) {
                if (pasteShouldMove) {
                    const resourceFileEdits = ( (sourceTargetPairs.map(
                        pair => ( (new ResourceFileEdit(pair.source, pair.target, { overwrite: incrementalNaming === 'disabled' })))
                    )));
                    const options = {
                        confirmBeforeUndo: configurationService.getValue().explorer.confirmUndo === UndoConfirmLevel.Verbose,
                        progressLabel: sourceTargetPairs.length > 1 ? ( localizeWithPath(_moduleId, 76, "Moving {0} files", sourceTargetPairs.length))
                            : ( localizeWithPath(
                            _moduleId,
                            77,
                            "Moving {0}",
                            basenameOrAuthority(sourceTargetPairs[0].target)
                        )),
                        undoLabel: sourceTargetPairs.length > 1 ? ( localizeWithPath(_moduleId, 78, "Move {0} files", sourceTargetPairs.length))
                            : ( localizeWithPath(
                            _moduleId,
                            79,
                            "Move {0}",
                            basenameOrAuthority(sourceTargetPairs[0].target)
                        ))
                    };
                    await explorerService.applyBulkEdit(resourceFileEdits, options);
                }
                else {
                    const resourceFileEdits = ( (sourceTargetPairs.map(pair => ( (new ResourceFileEdit(
                        pair.source,
                        pair.target,
                        { copy: true, overwrite: incrementalNaming === 'disabled' }
                    ))))));
                    await applyCopyResourceEdit(( (sourceTargetPairs.map(pair => pair.target))), resourceFileEdits);
                }
            }
            targets = ( (sourceTargetPairs.map(pair => pair.target)));
        }
        else {
            const targetAndEdits = coalesce(await Promise.all(( (toPaste.files.map(async (file) => {
                const target = element.isDirectory ? element : element.parent;
                const targetFile = await findValidPasteFileTarget(explorerService, fileService, dialogService, target, { resource: file.name, isDirectory: false, allowOverwrite: pasteShouldMove || incrementalNaming === 'disabled' }, incrementalNaming);
                if (!targetFile) {
                    return;
                }
                return {
                    target: targetFile,
                    edit: ( (new ResourceFileEdit(undefined, targetFile, {
                        overwrite: incrementalNaming === 'disabled',
                        contents: (async () => VSBuffer.wrap(( (new Uint8Array(await file.arrayBuffer())))))(),
                    })))
                };
            })))));
            await applyCopyResourceEdit(( (targetAndEdits.map(pair => pair.target))), ( (targetAndEdits.map(pair => pair.edit))));
            targets = ( (targetAndEdits.map(pair => pair.target)));
        }
        if (targets.length) {
            const firstTarget = targets[0];
            await explorerService.select(firstTarget);
            if (targets.length === 1) {
                const item = explorerService.findClosest(firstTarget);
                if (item && !item.isDirectory) {
                    await editorService.openEditor({ resource: item.resource, options: { pinned: true, preserveFocus: true } });
                }
            }
        }
    }
    catch (e) {
        onError(notificationService, ( (new Error(( localizeWithPath(
            _moduleId,
            80,
            "The file(s) to paste have been deleted or moved since you copied them. {0}",
            getErrorMessage(e)
        ))))));
    }
    finally {
        if (pasteShouldMove) {
            await explorerService.setToCopy([], false);
            pasteShouldMove = false;
        }
    }
    async function applyCopyResourceEdit(targets, resourceFileEdits) {
        const undoLevel = configurationService.getValue().explorer.confirmUndo;
        const options = {
            confirmBeforeUndo: undoLevel === UndoConfirmLevel.Default || undoLevel === UndoConfirmLevel.Verbose,
            progressLabel: targets.length > 1 ? ( localizeWithPath(_moduleId, 81, "Copying {0} files", targets.length))
                : ( localizeWithPath(_moduleId, 82, "Copying {0}", basenameOrAuthority(targets[0]))),
            undoLabel: targets.length > 1 ? ( localizeWithPath(_moduleId, 83, "Paste {0} files", targets.length))
                : ( localizeWithPath(_moduleId, 84, "Paste {0}", basenameOrAuthority(targets[0])))
        };
        await explorerService.applyBulkEdit(resourceFileEdits, options);
    }
};
async function getFilesToPaste(fileList, clipboardService, hostService) {
    if (fileList && fileList.length > 0) {
        const resources = ( (( ([...fileList].map(file => hostService.getPathForFile(file)))).filter(filePath => !!filePath && isAbsolute(filePath)).map((filePath) => URI.file(filePath))));
        if (resources.length) {
            return { type: 'paths', files: resources, };
        }
        return { type: 'data', files: [...fileList].filter(file => !hostService.getPathForFile(file)) };
    }
    else {
        return { type: 'paths', files: distinctParents(await clipboardService.readResources(), resource => resource) };
    }
}
const openFilePreserveFocusHandler = async (accessor) => {
    const editorService = accessor.get(IEditorService);
    const explorerService = accessor.get(IExplorerService);
    const stats = explorerService.getContext(true);
    await editorService.openEditors(( (stats.filter(s => !s.isDirectory).map(s => ({
        resource: s.resource,
        options: { preserveFocus: true }
    })))));
};
class BaseSetActiveEditorReadonlyInSession extends Action2 {
    constructor(id, title, newReadonlyState) {
        super({
            id,
            title,
            f1: true,
            category: Categories.File,
            precondition: ActiveEditorCanToggleReadonlyContext
        });
        this.newReadonlyState = newReadonlyState;
    }
    async run(accessor) {
        const editorService = accessor.get(IEditorService);
        const filesConfigurationService = accessor.get(IFilesConfigurationService);
        const fileResource = EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
        if (!fileResource) {
            return;
        }
        await filesConfigurationService.updateReadonly(fileResource, this.newReadonlyState);
    }
}
class SetActiveEditorReadonlyInSession extends BaseSetActiveEditorReadonlyInSession {
    static { this.ID = 'workbench.action.files.setActiveEditorReadonlyInSession'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 85, "Set Active Editor Read-only in Session")); }
    constructor() {
        super(SetActiveEditorReadonlyInSession.ID, SetActiveEditorReadonlyInSession.LABEL, true);
    }
}
class SetActiveEditorWriteableInSession extends BaseSetActiveEditorReadonlyInSession {
    static { this.ID = 'workbench.action.files.setActiveEditorWriteableInSession'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 86, "Set Active Editor Writeable in Session")); }
    constructor() {
        super(SetActiveEditorWriteableInSession.ID, SetActiveEditorWriteableInSession.LABEL, false);
    }
}
class ToggleActiveEditorReadonlyInSession extends BaseSetActiveEditorReadonlyInSession {
    static { this.ID = 'workbench.action.files.toggleActiveEditorReadonlyInSession'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 87, "Toggle Active Editor Read-only in Session")); }
    constructor() {
        super(ToggleActiveEditorReadonlyInSession.ID, ToggleActiveEditorReadonlyInSession.LABEL, 'toggle');
    }
}
class ResetActiveEditorReadonlyInSession extends BaseSetActiveEditorReadonlyInSession {
    static { this.ID = 'workbench.action.files.resetActiveEditorReadonlyInSession'; }
    static { this.LABEL = ( localize2WithPath(_moduleId, 88, "Reset Active Editor Read-only in Session")); }
    constructor() {
        super(ResetActiveEditorReadonlyInSession.ID, ResetActiveEditorReadonlyInSession.LABEL, 'reset');
    }
}
export { COPY_FILE_LABEL, CloseGroupAction, CompareNewUntitledTextFilesAction, CompareWithClipboardAction, DOWNLOAD_COMMAND_ID, DOWNLOAD_LABEL, FileCopiedContext, FocusFilesExplorer, GlobalCompareResourcesAction, MOVE_FILE_TO_TRASH_LABEL, NEW_FILE_COMMAND_ID, NEW_FILE_LABEL, NEW_FOLDER_COMMAND_ID, NEW_FOLDER_LABEL, OpenActiveFileInEmptyWorkspace, PASTE_FILE_LABEL, ResetActiveEditorReadonlyInSession, SaveAllInGroupAction, SetActiveEditorReadonlyInSession, SetActiveEditorWriteableInSession, ShowActiveFileInExplorer, TRIGGER_RENAME_LABEL, ToggleActiveEditorReadonlyInSession, ToggleAutoSaveAction, UPLOAD_COMMAND_ID, UPLOAD_LABEL, copyFileHandler, cutFileHandler, deleteFileHandler, findValidPasteFileTarget, incrementFileName, moveFileToTrashHandler, openFilePreserveFocusHandler, pasteFileHandler, renameHandler, validateFileName };
