diff --git a/src/lib/editorFile.js b/src/lib/editorFile.js index cdab50507..180c5ca5a 100644 --- a/src/lib/editorFile.js +++ b/src/lib/editorFile.js @@ -23,12 +23,11 @@ import { detectEol, normalizeEol } from "utils/eol"; import haptic from "utils/haptic"; import helpers from "utils/helpers"; import loadMimeTypes from "utils/mimeTypes"; -import Path from "utils/Path"; import { readRemoteFilePreview } from "utils/remoteFilePreview"; import Url from "utils/Url"; import config from "./config"; -import { isInitialPluginLoadComplete } from "./loadPlugins"; import openFolder from "./openFolder"; +import recommendModePlugin from "./recommendModePlugin"; import runLazily from "./runLazily"; import saveFile from "./saveFile"; import appSettings from "./settings"; @@ -304,22 +303,6 @@ function createSessionProxy(state, file) { }); } -function maybeRecommendLanguageModeExtension(file, modeInfo) { - if (appSettings.value.recommendExtensions === false) return; - if (!isInitialPluginLoadComplete()) return; - if (modeInfo?.name !== "text" || modeInfo.supportsFile(file.filename)) return; - if (helpers.isBinary(file.filename || file.uri)) return; - - void import("./languageModeRecommendations").then( - ({ default: recommend }) => { - recommend(file, modeInfo); - }, - (error) => { - console.warn("Failed to load language mode recommendations.", error); - }, - ); -} - /** * @typedef {'run'|'save'|'change'|'focus'|'blur'|'close'|'rename'|'load'|'loadError'|'loadStart'|'loadEnd'|'changeMode'|'changeEncoding'|'changeReadOnly'} FileEvents */ @@ -1604,13 +1587,7 @@ export default class EditorFile { this.#emit("changemode", event); if (event.defaultPrevented) return; - if (!mode) { - const ext = Path.extname(this.filename); - const modes = helpers.parseJSON(localStorage.modeassoc); - if (modes?.[ext]) { - mode = modes[ext]; - } - } + if (!mode) mode = helpers.getAssociatedMode(this.filename); let modeInfo = mode ? getMode(mode) : null; if (!modeInfo) { @@ -1632,7 +1609,7 @@ export default class EditorFile { this.__cmCachedLanguageSignature = null; } if (options.recommend !== false) { - maybeRecommendLanguageModeExtension(this, modeInfo); + recommendModePlugin(this.filename, modeInfo); } // sets file icon diff --git a/src/lib/languageModeRecommendations.js b/src/lib/languageModeRecommendations.js index 2783cc2b2..9f851f89e 100644 --- a/src/lib/languageModeRecommendations.js +++ b/src/lib/languageModeRecommendations.js @@ -1,8 +1,10 @@ import { getModeForPath } from "cm/modelist"; import notificationManager from "lib/notificationManager"; +import { isBinaryFile } from "utils/binaryExtensions"; import Path from "utils/Path"; import Url from "utils/Url"; import config from "./config"; +import fileTypeHandler from "./fileTypeHandler"; let instance = null; @@ -38,8 +40,13 @@ function hasPlainTextFallback(modeInfo, filename) { return modeInfo?.name === "text" && !modeInfo.supportsFile(filename); } +function hasBinaryFileHandler(filename) { + return isBinaryFile(filename) && !!fileTypeHandler.getFileHandler(filename); +} + export function shouldRecommendLanguageModeExtension(filename, modeInfo) { if (!hasPlainTextFallback(modeInfo, filename)) return false; + if (hasBinaryFileHandler(filename)) return false; const keyword = getLanguageModeRecommendationSearchKeyword(filename); if (!keyword) return false; @@ -89,10 +96,7 @@ class LanguageModeRecommendations { return availability; } - recommend(file, modeInfo) { - if (!file || file.type !== "editor") return; - - const filename = file.filename || ""; + recommend(filename, modeInfo) { if (!shouldRecommendLanguageModeExtension(filename, modeInfo)) return; const keyword = getLanguageModeRecommendationSearchKeyword(filename); @@ -119,8 +123,9 @@ class LanguageModeRecommendations { async showRecommendation(keyword, filename) { const hasPlugins = await this.getPluginAvailability(keyword); - // If a plugin registered the mode while the lookup was pending, suppress - // this stale recommendation and leave the keyword eligible for future checks. + // If a plugin registered the mode or a file handler while the lookup was + // pending, suppress this stale recommendation and leave the keyword + // eligible for future checks. if ( !shouldRecommendLanguageModeExtension(filename, getModeForPath(filename)) ) { @@ -165,6 +170,6 @@ function getLanguageModeRecommendations() { return instance; } -export default function recommendLanguageModeExtension(file, modeInfo) { - getLanguageModeRecommendations().recommend(file, modeInfo); +export default function recommendLanguageModeExtension(filename, modeInfo) { + getLanguageModeRecommendations().recommend(filename, modeInfo); } diff --git a/src/lib/loadPlugins.js b/src/lib/loadPlugins.js index 0bf8f746e..287e3126f 100644 --- a/src/lib/loadPlugins.js +++ b/src/lib/loadPlugins.js @@ -38,6 +38,7 @@ const PLUGIN_LOAD_TIMEOUT = 15000; const PLUGIN_DISABLE_TIMEOUT = 60000; let pluginDisabledUpdateQueue = Promise.resolve(); let initialPluginLoadComplete = false; +const initialPluginLoadWaiters = []; /** Plugins still loading in the background after PLUGIN_LOAD_TIMEOUT. */ const SLOW_PLUGIN_LOADS = new Set(); let handlerHistoryPending = false; @@ -126,6 +127,7 @@ export default async function loadPlugins(loadOnlyTheme = false) { } finally { if (!loadOnlyTheme) { initialPluginLoadComplete = true; + for (const resolve of initialPluginLoadWaiters.splice(0)) resolve(); } } } @@ -134,6 +136,11 @@ export function isInitialPluginLoadComplete() { return initialPluginLoadComplete; } +export function waitForInitialPluginLoad() { + if (initialPluginLoadComplete) return Promise.resolve(); + return new Promise((resolve) => initialPluginLoadWaiters.push(resolve)); +} + export async function loadPluginWithTimeout(pluginId, justInstalled = false) { const pluginState = { settled: false }; const pluginLoadPromise = loadPlugin(pluginId, justInstalled) diff --git a/src/lib/openFile.js b/src/lib/openFile.js index e435218b4..fd9fdd25a 100644 --- a/src/lib/openFile.js +++ b/src/lib/openFile.js @@ -12,6 +12,7 @@ import EditorFile from "./editorFile"; import { promoteSessionPersistence } from "./fileSessionPersistence"; import fileTypeHandler from "./fileTypeHandler"; import recents from "./recents"; +import recommendModePlugin from "./recommendModePlugin"; import appSettings from "./settings"; /** Documents opened from other apps that only a plugin handler can show. */ @@ -170,6 +171,7 @@ export default async function openFile(file, options = {}) { const needsDocumentHandler = options.external && EXTERNAL_DOCUMENT_PATTERN.test(name); if (needsDocumentHandler && !customHandler) { + recommendModePlugin(name); throw Object.assign(new Error("Document handler unavailable"), { code: "DOCUMENT_HANDLER_UNAVAILABLE", filename: name, @@ -470,6 +472,10 @@ export default async function openFile(file, options = {}) { return; } + if (helpers.isBinary(name) || helpers.isBinary(uri)) { + recommendModePlugin(name); + } + // Else open a new file // Checks for valid file if (fileInfo.length * 0.000001 > settings.maxFileSize) { diff --git a/src/lib/recommendModePlugin.js b/src/lib/recommendModePlugin.js new file mode 100644 index 000000000..c6821d6ca --- /dev/null +++ b/src/lib/recommendModePlugin.js @@ -0,0 +1,32 @@ +import { getMode, getModeForPath } from "cm/modelist"; +import helpers from "utils/helpers"; +import { + isInitialPluginLoadComplete, + waitForInitialPluginLoad, +} from "./loadPlugins"; +import appSettings from "./settings"; + +export default async function recommendModePlugin(filename, modeInfo) { + try { + if (!isInitialPluginLoadComplete()) { + // Editor tabs are checked again by setMode once plugins load. + if (modeInfo) return; + await waitForInitialPluginLoad(); + } + if (appSettings.value.recommendExtensions === false) return; + + const { default: recommend } = await import( + "./languageModeRecommendations" + ); + recommend(filename, modeInfo ?? getFileMode(filename)); + } catch (error) { + console.error("Failed to recommend a language mode plugin.", error); + } +} + +function getFileMode(filename) { + const associatedMode = helpers.getAssociatedMode(filename); + return ( + (associatedMode && getMode(associatedMode)) || getModeForPath(filename) + ); +} diff --git a/src/utils/helpers.js b/src/utils/helpers.js index c44683571..d7d7127c6 100644 --- a/src/utils/helpers.js +++ b/src/utils/helpers.js @@ -224,6 +224,13 @@ export default { return null; } }, + /** + * Mode the user chose for files with this file's extension + * @param {string} filename + */ + getAssociatedMode(filename) { + return this.parseJSON(localStorage.modeassoc)?.[path.extname(filename)]; + }, /** * Checks whether given type is directory or not * @param {'dir'|'directory'|'folder'} type diff --git a/tests/unit/fileSaveEvents.test.js b/tests/unit/fileSaveEvents.test.js index 0a818bf9b..0350fdf49 100644 --- a/tests/unit/fileSaveEvents.test.js +++ b/tests/unit/fileSaveEvents.test.js @@ -41,7 +41,6 @@ function setup() { "utils/Path", "utils/remoteFilePreview", "utils/Url", - "./loadPlugins", "./openFolder", "./runLazily", "cm/editorReadOnly", @@ -52,6 +51,7 @@ function setup() { { ...defaults, "utils/haptic": vi.fn(), + "./recommendModePlugin": vi.fn(), "components/sidebar": { hide: vi.fn() }, "@codemirror/state": { EditorState, EditorSelection }, "cm/editorUtils": { getDocText: (doc) => doc.toString() }, diff --git a/tests/unit/languageModeRecommendations.test.js b/tests/unit/languageModeRecommendations.test.js index 2a9616231..5a2ceebd2 100644 --- a/tests/unit/languageModeRecommendations.test.js +++ b/tests/unit/languageModeRecommendations.test.js @@ -1,6 +1,7 @@ import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; import "cm/supportedModes"; import { getModeForPath } from "cm/modelist"; +import fileTypeHandler from "lib/fileTypeHandler"; import recommendLanguageModeExtension from "lib/languageModeRecommendations"; import notificationManager from "lib/notificationManager"; @@ -19,10 +20,7 @@ globalThis.strings = { }; function recommend(filename) { - recommendLanguageModeExtension( - { type: "editor", filename }, - getModeForPath(filename), - ); + recommendLanguageModeExtension(filename, getModeForPath(filename)); } describe("language mode recommendations", () => { @@ -63,6 +61,41 @@ describe("language mode recommendations", () => { }); }); + it("recommends a plugin for binary documents without a handler", async () => { + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => [{ id: "documents" }], + }); + + recommend("report.pdf"); + + await vi.waitFor(() => { + expect(notificationManager.pushNotification).toHaveBeenCalledOnce(); + }); + }); + + it("stays silent when a handler registers while the lookup is pending", async () => { + let respond; + globalThis.fetch = vi.fn( + () => + new Promise((resolve) => { + respond = resolve; + }), + ); + + recommend("slides.pptx"); + await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalled()); + fileTypeHandler.registerFileHandler("late-documents", { + extensions: ["pptx"], + handleFile: async () => {}, + }); + respond({ ok: true, json: async () => [{ id: "documents" }] }); + await new Promise((resolve) => setTimeout(resolve, 0)); + fileTypeHandler.unregisterFileHandler("late-documents"); + + expect(notificationManager.pushNotification).not.toHaveBeenCalled(); + }); + it.each([ ["network errors", () => Promise.reject(new Error("offline"))], ["server errors", () => Promise.resolve({ ok: false, status: 503 })], diff --git a/tests/unit/openFileCancellation.test.js b/tests/unit/openFileCancellation.test.js index c993a1cd3..f8dad0589 100644 --- a/tests/unit/openFileCancellation.test.js +++ b/tests/unit/openFileCancellation.test.js @@ -40,6 +40,7 @@ describe("openFile cancellation", () => { let titleLoader; let loaderVisible; let languageLoads; + let recommendModePlugin; beforeEach(() => { controller = new AbortController(); @@ -59,6 +60,7 @@ describe("openFile cancellation", () => { decode = vi.fn().mockResolvedValue("target text"); detectEncoding = vi.fn().mockResolvedValue("UTF-8"); handler = { getFileHandler: vi.fn() }; + recommendModePlugin = vi.fn(); recents = { addFile: vi.fn() }; createEditor = vi.fn(function (name, options) { manager.activeFile = { name, ...options }; @@ -89,6 +91,7 @@ describe("openFile cancellation", () => { "./fileSessionPersistence": { promoteSessionPersistence: vi.fn() }, "./fileTypeHandler": { default: handler }, "./recents": { default: recents }, + "./recommendModePlugin": { default: recommendModePlugin }, "./settings": { default: { value: { maxFileSize: 10, defaultFileEncoding: "auto" } }, }, @@ -149,6 +152,9 @@ describe("openFile cancellation", () => { await expect( openFile("content://provider/42", { external: true }), ).rejects.toMatchObject({ code: "DOCUMENT_HANDLER_UNAVAILABLE" }); + expect(recommendModePlugin).toHaveBeenCalledWith( + `Document.${extension.toUpperCase()}`, + ); expect(readFile).not.toHaveBeenCalled(); expect(createEditor).not.toHaveBeenCalled(); expect(loaderVisible).toBe(false); @@ -214,6 +220,15 @@ describe("openFile cancellation", () => { expect(loaderVisible).toBe(false); }); + it("recommends a mode plugin for binary files before rejecting their size", async () => { + stat.mockResolvedValue({ name: "archive.zip", length: 50_000_000 }); + await expect( + openFile("content://provider/archive", { external: true }), + ).rejects.toThrow("File too large"); + expect(recommendModePlugin).toHaveBeenCalledWith("archive.zip"); + expect(readFile).not.toHaveBeenCalled(); + }); + it.each([ ["README", "text/plain"], ["Makefile", undefined], diff --git a/tests/unit/pluginFileRestoration.test.js b/tests/unit/pluginFileRestoration.test.js index 3d85537c8..f26c4dfa5 100644 --- a/tests/unit/pluginFileRestoration.test.js +++ b/tests/unit/pluginFileRestoration.test.js @@ -191,7 +191,7 @@ function setup() { "utils/eol": { detectEol, getEolSeparator, normalizeEol }, "utils/helpers": helpers, "./config": { DEFAULT_FILE_SESSION: "default" }, - "./loadPlugins": { isInitialPluginLoadComplete: () => false }, + "./recommendModePlugin": vi.fn(), "./settings": settings, "./saveFile": saveFile, },