diff --git a/README.md b/README.md
index 3b9af47..e2fa4a3 100644
--- a/README.md
+++ b/README.md
@@ -171,6 +171,8 @@ require("flutter-tools").setup {} -- use defaults
- `FlutterRename` - Rename a symbol and update imports if `lsp.settings.renameFilesWithClasses == "always"`.
- `FlutterLogClear` - Clears the log buffer.
- `FlutterLogToggle` - Toggles the log buffer.
+- `FlutterWidgetPreview [dir]` - Starts the [widget previewer](https://docs.flutter.dev/tools/widget-previewer) for the current project (the pub workspace root in a workspace), or for `dir`, and opens it. When it is already running, opens it again.
+- `FlutterWidgetPreviewStop` - Stops the widget previewer.
@@ -182,6 +184,21 @@ such as `:FlutterRun --flavor `, `:FlutterRun --dart-define=API_URL=https
+### `FlutterWidgetPreview`
+
+Runs `flutter widget-preview start` (Flutter 3.38+, Neovim 0.12+) and connects it to Neovim:
+
+- The previewer reuses the running dart language server instead of starting a second analysis server,
+ and the DevTools server started with `FlutterDevTools`, if any.
+- The previewer's "filter by selected file" option follows the Dart buffer you are editing.
+- Selecting a widget in the previewer's widget inspector, or a stack frame of a failing preview,
+ jumps to the code in Neovim.
+
+The previewer opens in your default browser, themed after your colorscheme. Set
+`widget_preview.web_server = false` to let Flutter launch it in its own Chrome window instead.
+
+
+
## `FlutterOutline`
The outline window allows you to see the high level layout of the current buffer.
@@ -264,6 +281,9 @@ require("flutter-tools").setup {
autostart = false, -- autostart devtools server if not detected
auto_open_browser = false, -- Automatically opens devtools in the browser
},
+ widget_preview = {
+ web_server = true, -- open the widget previewer with vim.ui.open; false lets Flutter launch its own Chrome
+ },
outline = {
open_cmd = "30vnew", -- command to use to open the outline buffer
auto_open = false -- if true this will open the outline automatically when it is first populated
diff --git a/lua/flutter-tools.lua b/lua/flutter-tools.lua
index 3f0a5c5..e71ac66 100644
--- a/lua/flutter-tools.lua
+++ b/lua/flutter-tools.lua
@@ -13,6 +13,7 @@ local lsp = lazy.require("flutter-tools.lsp") ---@module "flutter-tools.lsp"
local outline = lazy.require("flutter-tools.outline") ---@module "flutter-tools.outline"
local devices = lazy.require("flutter-tools.devices") ---@module "flutter-tools.devices"
local utils = lazy.require("flutter-tools.utils") ---@module "flutter-tools.utils"
+local widget_preview = lazy.require("flutter-tools.widget_preview") ---@module "flutter-tools.widget_preview"
local api = vim.api
@@ -49,6 +50,13 @@ local function setup_commands()
command("FlutterPubUpgrade", function(data) commands.pub_upgrade_command(data.args) end, {
nargs = "*",
})
+ --- Widget preview
+ command(
+ "FlutterWidgetPreview",
+ function(data) widget_preview.show(data.args) end,
+ { nargs = "?", complete = "dir" }
+ )
+ command("FlutterWidgetPreviewStop", widget_preview.stop)
--- Log
command("FlutterLogClear", log.clear)
command("FlutterLogToggle", log.toggle)
@@ -117,7 +125,10 @@ local function setup_autocommands()
autocmd({ "VimLeavePre" }, {
group = AUGROUP,
pattern = { "*" },
- callback = function() dev_tools.stop() end,
+ callback = function()
+ dev_tools.stop()
+ if package.loaded["flutter-tools.widget_preview"] then widget_preview.on_exit() end
+ end,
})
end
diff --git a/lua/flutter-tools/config.lua b/lua/flutter-tools/config.lua
index 6d1b6de..b0613f0 100644
--- a/lua/flutter-tools/config.lua
+++ b/lua/flutter-tools/config.lua
@@ -43,6 +43,7 @@ local utils = lazy.require("flutter-tools.utils") ---@module "flutter-tools.util
---@field outline? {auto_open: boolean, open_cmd?: string}
---@field dev_log? flutter.DevLogOpts
---@field dev_tools? {autostart: boolean, auto_open_browser: boolean}
+---@field widget_preview? {web_server: boolean}
---@field analyzer_web_port? number
local M = {}
@@ -148,6 +149,9 @@ local config = {
autostart = false,
auto_open_browser = false,
},
+ widget_preview = {
+ web_server = true,
+ },
}
local deprecations = {
diff --git a/lua/flutter-tools/dtd/client.lua b/lua/flutter-tools/dtd/client.lua
new file mode 100644
index 0000000..4321ac4
--- /dev/null
+++ b/lua/flutter-tools/dtd/client.lua
@@ -0,0 +1,204 @@
+local lazy = require("flutter-tools.lazy")
+local executable = lazy.require("flutter-tools.executable") ---@module "flutter-tools.executable"
+local websocket = lazy.require("flutter-tools.utils.websocket") ---@module "flutter-tools.utils.websocket"
+
+--- JSON-RPC client for a Dart Tooling Daemon (DTD) process owned by this plugin.
+--- Mirrors Dart-Code's src/shared/services/tooling_daemon.ts.
+local M = {}
+
+local METHOD_NOT_FOUND = -32601
+local INTERNAL_ERROR = -32603
+
+---@class flutter.DtdError
+---@field code integer
+---@field message string
+
+---@type vim.SystemObj?
+local process = nil
+
+---@type {uri: string, secret: string}?
+local details = nil
+
+---@type flutter.WebSocket?
+local socket = nil
+
+---@type fun(err: string?)[]
+local on_ready = {}
+
+local next_id = 0
+
+---@type table
+local pending = {}
+
+---@type table
+local services = {}
+
+local function send(message)
+ if socket then socket:send(vim.json.encode(message)) end
+end
+
+---@param err string?
+local function flush_ready(err)
+ local callbacks = on_ready
+ on_ready = {}
+ for _, callback in ipairs(callbacks) do
+ callback(err)
+ end
+end
+
+local function disconnect()
+ if socket then socket:close() end
+ socket = nil
+ details = nil
+ pending = {}
+ services = {}
+end
+
+---@param message table
+local function handle_request(message)
+ if message.id == nil then return end
+ local handler = services[message.method]
+ if not handler then
+ return send({
+ jsonrpc = "2.0",
+ id = message.id,
+ error = { code = METHOD_NOT_FOUND, message = "Unknown method " .. message.method },
+ })
+ end
+ local ok, result = pcall(handler, message.params or {})
+ if ok then return send({ jsonrpc = "2.0", id = message.id, result = result }) end
+ local err = type(result) == "table" and result
+ or { code = INTERNAL_ERROR, message = tostring(result) }
+ send({ jsonrpc = "2.0", id = message.id, error = err })
+end
+
+---@param text string
+local function handle_message(text)
+ local ok, message = pcall(vim.json.decode, text, { luanil = { object = true, array = true } })
+ if not ok or type(message) ~= "table" then return end
+
+ if message.method then
+ handle_request(message)
+ elseif message.id ~= nil and pending[message.id] then
+ local callback = pending[message.id]
+ pending[message.id] = nil
+ callback(message.error, message.result)
+ end
+end
+
+---@param daemon {uri: string, secret: string}
+local function connect(daemon)
+ websocket.connect(daemon.uri, {
+ on_open = function(ws)
+ socket = ws
+ details = daemon
+ flush_ready(nil)
+ end,
+ on_message = handle_message,
+ on_close = function(err)
+ local was_connected = details ~= nil
+ disconnect()
+ if not was_connected then
+ flush_ready(err or "Connection to the Dart Tooling Daemon closed")
+ end
+ end,
+ })
+end
+
+---@param line string
+---@return {uri: string, secret: string}?
+local function parse_details(line)
+ local ok, json = pcall(vim.json.decode, line)
+ local daemon = ok and type(json) == "table" and json.tooling_daemon_details
+ if type(daemon) == "table" and daemon.uri and daemon.trusted_client_secret then
+ return { uri = daemon.uri, secret = daemon.trusted_client_secret }
+ end
+end
+
+---Starts the daemon and connects to it, or reuses the running one.
+---@param callback fun(err: string?)
+function M.start(callback)
+ if details then return callback(nil) end
+ table.insert(on_ready, callback)
+ if #on_ready > 1 then return end
+
+ executable.dart(function(dart_bin)
+ local stdout = ""
+ local found = false
+ local ok, obj = pcall(
+ vim.system,
+ { dart_bin, "tooling-daemon", "--machine" },
+ {
+ stdout = function(_, data)
+ if not data or found then return end
+ stdout = stdout .. data
+ for line in stdout:gmatch("[^\n]+") do
+ local daemon = parse_details(line)
+ if daemon then
+ found = true
+ vim.schedule(function() connect(daemon) end)
+ return
+ end
+ end
+ end,
+ },
+ vim.schedule_wrap(function(result)
+ process = nil
+ local was_connected = details ~= nil
+ disconnect()
+ if not was_connected then
+ flush_ready(("Dart Tooling Daemon exited with code %d"):format(result.code))
+ end
+ end)
+ )
+ if not ok then return flush_ready(tostring(obj)) end
+ process = obj
+ end)
+end
+
+function M.stop()
+ disconnect()
+ if process then process:kill("sigterm") end
+ process = nil
+end
+
+---@return string?
+function M.uri() return details and details.uri end
+
+---@return string?
+function M.secret() return details and details.secret end
+
+---@param method string
+---@param params table?
+---@param callback fun(err: flutter.DtdError?, result: any)?
+function M.request(method, params, callback)
+ if not socket then
+ if callback then
+ callback({ code = INTERNAL_ERROR, message = "Not connected to the Dart Tooling Daemon" })
+ end
+ return
+ end
+ next_id = next_id + 1
+ pending[next_id] = callback or function() end
+ send({ jsonrpc = "2.0", id = next_id, method = method, params = params })
+end
+
+---Registers `service.method` for other DTD clients to call. `handler` returns a table with a
+---`type` field, or raises a {@link flutter.DtdError}.
+---@param service string
+---@param method string
+---@param handler fun(params: table): table
+function M.register_service(service, method, handler)
+ M.request("registerService", { service = service, method = method }, function(err)
+ if not err then services[service .. "." .. method] = handler end
+ end)
+end
+
+---@param stream string
+---@param kind string
+---@param data table
+function M.post_event(stream, kind, data)
+ M.request("postEvent", { streamId = stream, eventKind = kind, eventData = data })
+end
+
+return M
diff --git a/lua/flutter-tools/dtd/init.lua b/lua/flutter-tools/dtd/init.lua
new file mode 100644
index 0000000..6ea2838
--- /dev/null
+++ b/lua/flutter-tools/dtd/init.lua
@@ -0,0 +1,353 @@
+local lazy = require("flutter-tools.lazy")
+local client = lazy.require("flutter-tools.dtd.client") ---@module "flutter-tools.dtd.client"
+local lsp_utils = lazy.require("flutter-tools.lsp.utils") ---@module "flutter-tools.lsp.utils"
+local lsp = lazy.require("flutter-tools.lsp") ---@module "flutter-tools.lsp"
+
+--- Connects Neovim to the Dart Tooling Daemon the way Dart-Code does in
+--- src/extension/dart/tooling_daemon.ts: shares the workspace roots and the analysis server,
+--- and provides the `Editor` service that tools such as the widget previewer call.
+local M = {}
+
+local api = vim.api
+local uv = vim.uv
+
+local EDITOR = "Editor"
+local ACTIVE_LOCATION_DELAY_MS = 200
+local LSP_INIT_POLL_MS = 100
+local LSP_INIT_TIMEOUT_MS = 30000
+local LSP_START_TIMEOUT_MS = 10000
+local ALREADY_CONNECTED_TO_DTD = -32015
+local UNSUPPORTED_URI_SCHEME = 144
+
+local augroup = api.nvim_create_augroup("FlutterToolsDtd", { clear = true })
+
+---@type string?
+local integrated_uri = nil
+
+---DTD uri each dartls client is attached to, or false if it is attached elsewhere.
+---@type table
+local lsp_connections = {}
+
+---Callbacks waiting on a connection attempt that is still in flight, per client.
+---@type table
+local lsp_connecting = {}
+
+---@type table
+local active_location = { selections = {} }
+
+---@type uv.uv_timer_t?
+local location_timer = nil
+
+---@param win integer
+---@return boolean
+local function is_real_editor(win)
+ local buf = api.nvim_win_get_buf(win)
+ return api.nvim_win_get_config(win).relative == "" and vim.bo[buf].buftype == ""
+end
+
+---@param buf integer
+---@param row integer 1-based
+---@param col integer 0-based byte column
+local function position(buf, row, col)
+ local line = api.nvim_buf_get_lines(buf, row - 1, row, false)[1] or ""
+ return { line = row - 1, character = vim.str_utfindex(line, "utf-16", math.min(col, #line)) }
+end
+
+---@param buf integer
+---@return string?
+local function file_uri(buf)
+ local name = api.nvim_buf_get_name(buf)
+ if name == "" or name:match("^%a[%w+.-]*://") then return nil end
+ return vim.uri_from_fname(name)
+end
+
+---@param win integer
+local function get_active_location(win)
+ local buf = api.nvim_win_get_buf(win)
+ local cursor = api.nvim_win_get_cursor(win)
+ local active = position(buf, cursor[1], cursor[2])
+ local anchor = active
+ if api.nvim_get_mode().mode:match("^[vV\22]") then
+ local visual_start = vim.fn.getpos("v")
+ anchor = position(buf, visual_start[2], visual_start[3] - 1)
+ end
+ local uri = file_uri(buf)
+ return {
+ textDocument = uri and { uri = uri, version = vim.b[buf].changedtick } or nil,
+ selections = { { active = active, anchor = anchor } },
+ }
+end
+
+local function update_active_location()
+ local win = api.nvim_get_current_win()
+ if not is_real_editor(win) then return end
+ active_location = get_active_location(win)
+ client.post_event(EDITOR, "activeLocationChanged", active_location)
+end
+
+local function queue_active_location_update()
+ if not location_timer then location_timer = assert(uv.new_timer()) end
+ location_timer:stop()
+ location_timer:start(ACTIVE_LOCATION_DELAY_MS, 0, vim.schedule_wrap(update_active_location))
+end
+
+---@return integer
+local function editor_window()
+ local current = api.nvim_get_current_win()
+ if is_real_editor(current) then return current end
+ for _, win in ipairs(api.nvim_tabpage_list_wins(0)) do
+ if is_real_editor(win) then return win end
+ end
+ return current
+end
+
+---Opens `uri` at a 1-based `line` and `column`, falling back to the first non-blank character
+---when the column is missing or past the end of the line.
+---@param params {uri: string, line: integer?, column: integer?}
+local function navigate_to_code(params)
+ local fname = vim.uri_to_fname(params.uri)
+ local buf = vim.fn.bufadd(fname)
+ vim.fn.bufload(buf)
+ local row = math.max((params.line or 1) - 1, 0)
+ local text = api.nvim_buf_get_lines(buf, row, row + 1, false)[1] or ""
+ local character
+ if params.line and params.column and params.column <= vim.str_utfindex(text, "utf-16") then
+ character = math.max(params.column - 1, 0)
+ else
+ character = vim.str_utfindex(text, "utf-16", (text:find("%S") or 1) - 1)
+ end
+ local pos = { line = row, character = character }
+ api.nvim_set_current_win(editor_window())
+ vim.lsp.util.show_document(
+ { uri = params.uri, range = { start = pos, ["end"] = pos } },
+ "utf-16",
+ { focus = true }
+ )
+end
+
+local function register_editor_service()
+ client.register_service(
+ EDITOR,
+ "getActiveLocation",
+ function() return vim.tbl_extend("force", active_location, { type = "ActiveLocation" }) end
+ )
+ client.register_service(EDITOR, "navigateToCode", function(params)
+ local scheme = params.uri and params.uri:match("^(%a[%w+.-]*):")
+ if scheme ~= "file" then
+ error({
+ code = UNSUPPORTED_URI_SCHEME,
+ message = ("Unsupported URI scheme: %s"):format(scheme),
+ })
+ end
+ vim.schedule(function() navigate_to_code(params) end)
+ return { type = "Success" }
+ end)
+end
+
+---@return vim.lsp.Client[]
+local function dartls_clients() return vim.lsp.get_clients({ name = lsp_utils.SERVER_NAME }) end
+
+local function send_workspace_roots()
+ local roots = {}
+ for _, lsp_client in ipairs(dartls_clients()) do
+ for _, folder in ipairs(lsp_client.workspace_folders or {}) do
+ roots[folder.uri] = true
+ end
+ if lsp_client.root_dir then roots[vim.uri_from_fname(lsp_client.root_dir)] = true end
+ end
+ client.request(
+ "FileSystem.setIDEWorkspaceRoots",
+ { secret = client.secret(), roots = vim.tbl_keys(roots) }
+ )
+end
+
+---@param lsp_client vim.lsp.Client
+---@param callback fun()
+local function when_initialized(lsp_client, callback)
+ if lsp_client.initialized then return callback() end
+ local timer = assert(uv.new_timer())
+ local elapsed = 0
+ timer:start(
+ LSP_INIT_POLL_MS,
+ LSP_INIT_POLL_MS,
+ vim.schedule_wrap(function()
+ elapsed = elapsed + LSP_INIT_POLL_MS
+ if lsp_client.initialized or lsp_client:is_stopped() or elapsed >= LSP_INIT_TIMEOUT_MS then
+ timer:stop()
+ timer:close()
+ callback()
+ end
+ end)
+ )
+end
+
+---An analysis server can only attach to one DTD in its lifetime, and rejects requests until it
+---is initialized.
+---@param lsp_client vim.lsp.Client
+---@param callback fun()
+local function connect_lsp(lsp_client, callback)
+ local id = lsp_client.id
+ if lsp_connections[id] ~= nil then return callback() end
+ if lsp_connecting[id] then return table.insert(lsp_connecting[id], callback) end
+ lsp_connecting[id] = { callback }
+
+ local function finish()
+ local callbacks = lsp_connecting[id] or {}
+ lsp_connecting[id] = nil
+ for _, waiting in ipairs(callbacks) do
+ waiting()
+ end
+ end
+
+ when_initialized(lsp_client, function()
+ if not lsp_client.initialized then return finish() end
+ local uri = client.uri()
+ lsp_client:request("dart/connectToDtd", { uri = uri }, function(err)
+ if not err then
+ lsp_connections[id] = uri
+ elseif err.code == ALREADY_CONNECTED_TO_DTD then
+ lsp_connections[id] = false
+ end
+ finish()
+ end)
+ end)
+end
+
+---The plugin starts dartls asynchronously, so a Dart buffer may not have its client yet.
+---@param callback fun()
+local function when_dartls_started(callback)
+ if #dartls_clients() > 0 or vim.bo.filetype ~= "dart" then return callback() end
+ local done = false
+ local function finish()
+ if done then return end
+ done = true
+ callback()
+ end
+ api.nvim_create_autocmd("LspAttach", {
+ group = augroup,
+ callback = function(args)
+ local lsp_client = vim.lsp.get_client_by_id(args.data.client_id)
+ if lsp_client and lsp_client.name == lsp_utils.SERVER_NAME then
+ finish()
+ return true
+ end
+ end,
+ })
+ vim.defer_fn(finish, LSP_START_TIMEOUT_MS)
+end
+
+---@param callback fun()
+local function connect_all_lsps(callback)
+ local remaining = 1
+ local function done()
+ remaining = remaining - 1
+ if remaining == 0 then callback() end
+ end
+ for _, lsp_client in ipairs(dartls_clients()) do
+ remaining = remaining + 1
+ connect_lsp(lsp_client, done)
+ end
+ done()
+end
+
+local function create_autocmds()
+ api.nvim_clear_autocmds({ group = augroup })
+ api.nvim_create_autocmd(
+ { "BufEnter", "WinEnter", "CursorMoved", "CursorMovedI", "ModeChanged" },
+ {
+ group = augroup,
+ callback = queue_active_location_update,
+ }
+ )
+ api.nvim_create_autocmd("LspAttach", {
+ group = augroup,
+ callback = function(args)
+ local lsp_client = vim.lsp.get_client_by_id(args.data.client_id)
+ if not lsp_client or lsp_client.name ~= lsp_utils.SERVER_NAME then return end
+ connect_lsp(lsp_client, function() end)
+ send_workspace_roots()
+ end,
+ })
+end
+
+---Starts the daemon, if needed, and waits until the dartls clients are attached to it.
+---@param callback fun(err: string?)
+function M.start(callback)
+ client.start(function(err)
+ if err then return callback(err) end
+ if integrated_uri ~= client.uri() then
+ integrated_uri = client.uri()
+ register_editor_service()
+ create_autocmds()
+ send_workspace_roots()
+ update_active_location()
+ end
+ when_dartls_started(function()
+ connect_all_lsps(function() callback(nil) end)
+ end)
+ end)
+end
+
+function M.stop()
+ api.nvim_clear_autocmds({ group = augroup })
+ if location_timer then location_timer:stop() end
+ integrated_uri = nil
+ client.stop()
+end
+
+---@return string?
+function M.uri() return client.uri() end
+
+---@return vim.lsp.Client[]
+local function shared_lsp_clients()
+ return vim.tbl_filter(
+ function(lsp_client) return lsp_connections[lsp_client.id] == client.uri() end,
+ dartls_clients()
+ )
+end
+
+---Tools query the shared analysis server once on startup, and it answers with no results until
+---its first analysis has finished, so they must not start before that.
+---@param callback fun()
+function M.when_analyzed(callback)
+ local remaining = 1
+ local function done()
+ remaining = remaining - 1
+ if remaining == 0 then callback() end
+ end
+ for _, lsp_client in ipairs(shared_lsp_clients()) do
+ remaining = remaining + 1
+ lsp.when_analyzed(lsp_client.id, done)
+ end
+ done()
+end
+
+---@param lsp_client vim.lsp.Client
+---@param dir string
+---@return boolean
+local function analyzes(lsp_client, dir)
+ local real_dir = uv.fs_realpath(dir) or dir
+ local roots = vim.tbl_map(
+ function(folder) return vim.uri_to_fname(folder.uri) end,
+ lsp_client.workspace_folders or {}
+ )
+ if lsp_client.root_dir then table.insert(roots, lsp_client.root_dir) end
+ for _, root in ipairs(roots) do
+ if vim.fs.relpath(uv.fs_realpath(root) or root, real_dir) then return true end
+ end
+ return false
+end
+
+---Whether tools connecting to the daemon would analyze `dir` correctly: either a dartls client
+---serving `dir` provides the analysis server, or none does and the tool starts its own.
+---@param dir string
+---@return boolean
+function M.can_analyze(dir)
+ local shared = shared_lsp_clients()
+ for _, lsp_client in ipairs(shared) do
+ if analyzes(lsp_client, dir) then return true end
+ end
+ return #shared == 0
+end
+
+return M
diff --git a/lua/flutter-tools/lsp/init.lua b/lua/flutter-tools/lsp/init.lua
index 38da84a..1887cfb 100644
--- a/lua/flutter-tools/lsp/init.lua
+++ b/lua/flutter-tools/lsp/init.lua
@@ -35,6 +35,38 @@ local function create_debug_log(level)
end
end
+local ANALYZING_TOKEN = "ANALYZING"
+
+---@type table
+local analysis_state = {}
+
+---@type table
+local analysis_waiters = {}
+
+---@param client_id integer
+local function track_analysis(client_id, kind)
+ local state = analysis_state[client_id] or { analyzed = false, analyzing = false }
+ analysis_state[client_id] = state
+ state.analyzing = kind ~= "end"
+ if kind ~= "end" then return end
+ state.analyzed = true
+ local waiters = analysis_waiters[client_id] or {}
+ analysis_waiters[client_id] = nil
+ for _, waiter in ipairs(waiters) do
+ waiter()
+ end
+end
+
+---Calls `callback` once the client is idle after its first analysis.
+---@param client_id integer
+---@param callback fun()
+function M.when_analyzed(client_id, callback)
+ local state = analysis_state[client_id]
+ if state and state.analyzed and not state.analyzing then return callback() end
+ analysis_waiters[client_id] = analysis_waiters[client_id] or {}
+ table.insert(analysis_waiters[client_id], callback)
+end
+
---Handle progress notifications from the server
---@param err table
---@param result table
@@ -45,6 +77,9 @@ local function handle_progress(err, result, ctx)
if api.nvim_get_mode().mode ~= "i" then vim.lsp.handlers["$/progress"](err, result, ctx) end
-- NOTE: this event gets called whenever the analysis server has completed some work
-- rather than just when the server has started.
+ if result and result.token == ANALYZING_TOKEN and result.value then
+ track_analysis(ctx.client_id, result.value.kind)
+ end
if result and result.value and result.value.kind == "end" then
utils.emit_event(utils.events.LSP_ANALYSIS_COMPLETED)
end
diff --git a/lua/flutter-tools/utils/websocket.lua b/lua/flutter-tools/utils/websocket.lua
new file mode 100644
index 0000000..29dc1ba
--- /dev/null
+++ b/lua/flutter-tools/utils/websocket.lua
@@ -0,0 +1,241 @@
+local bit = require("bit")
+
+local uv = vim.uv
+
+local M = {}
+
+local OPCODE = {
+ CONTINUATION = 0x0,
+ TEXT = 0x1,
+ CLOSE = 0x8,
+ PING = 0x9,
+ PONG = 0xA,
+}
+
+local CONNECT_TIMEOUT_MS = 5000
+
+-- string.char(unpack(t)) is limited by the number of arguments Lua accepts
+local CHUNK_SIZE = 4096
+
+---@param bytes integer[]
+---@return string
+local function bytes_to_string(bytes)
+ local parts = {}
+ for i = 1, #bytes, CHUNK_SIZE do
+ parts[#parts + 1] = string.char(unpack(bytes, i, math.min(i + CHUNK_SIZE - 1, #bytes)))
+ end
+ return table.concat(parts)
+end
+
+---@param value integer
+---@param count integer
+---@return string
+local function big_endian(value, count)
+ local bytes = {}
+ for i = count, 1, -1 do
+ bytes[i] = value % 256
+ value = math.floor(value / 256)
+ end
+ return bytes_to_string(bytes)
+end
+
+---@param count integer
+---@return integer[]
+local function random_bytes(count)
+ local bytes = {}
+ for i = 1, count do
+ bytes[i] = math.random(0, 255)
+ end
+ return bytes
+end
+
+---@param opcode integer
+---@param payload string
+---@return string
+function M.encode_frame(opcode, payload)
+ local len = #payload
+ local header
+ if len < 126 then
+ header = string.char(0x80 + opcode, 0x80 + len)
+ elseif len < 0x10000 then
+ header = string.char(0x80 + opcode, 0x80 + 126) .. big_endian(len, 2)
+ else
+ header = string.char(0x80 + opcode, 0x80 + 127) .. big_endian(len, 8)
+ end
+ local mask = random_bytes(4)
+ local masked = {}
+ for i = 1, len do
+ masked[i] = bit.bxor(payload:byte(i), mask[(i - 1) % 4 + 1])
+ end
+ return header .. bytes_to_string(mask) .. bytes_to_string(masked)
+end
+
+---Decodes as many complete frames as `buffer` holds.
+---@param buffer string
+---@return {fin: boolean, opcode: integer, payload: string}[] frames
+---@return string rest bytes belonging to an incomplete frame
+function M.decode_frames(buffer)
+ local frames = {}
+ local pos = 1
+ while true do
+ if #buffer - pos + 1 < 2 then break end
+ local b1, b2 = buffer:byte(pos, pos + 1)
+ local offset = pos + 2
+ local len = b2 % 128
+ if len == 126 then
+ if #buffer < offset + 1 then break end
+ local h, l = buffer:byte(offset, offset + 1)
+ len = h * 256 + l
+ offset = offset + 2
+ elseif len == 127 then
+ if #buffer < offset + 7 then break end
+ len = 0
+ for i = 0, 7 do
+ len = len * 256 + buffer:byte(offset + i)
+ end
+ offset = offset + 8
+ end
+ local mask
+ if b2 >= 128 then
+ if #buffer < offset + 3 then break end
+ mask = { buffer:byte(offset, offset + 3) }
+ offset = offset + 4
+ end
+ if #buffer < offset + len - 1 then break end
+ local payload = buffer:sub(offset, offset + len - 1)
+ if mask then
+ local bytes = {}
+ for i = 1, len do
+ bytes[i] = bit.bxor(payload:byte(i), mask[(i - 1) % 4 + 1])
+ end
+ payload = bytes_to_string(bytes)
+ end
+ frames[#frames + 1] = { fin = b1 >= 128, opcode = b1 % 16, payload = payload }
+ pos = offset + len
+ end
+ return frames, buffer:sub(pos)
+end
+
+---@class flutter.WebSocket
+---@field private tcp uv.uv_tcp_t
+---@field private closed boolean
+local WebSocket = {}
+WebSocket.__index = WebSocket
+
+---@param text string
+function WebSocket:send(text)
+ if self.closed then return end
+ self.tcp:write(M.encode_frame(OPCODE.TEXT, text))
+end
+
+function WebSocket:close()
+ if self.closed then return end
+ self.closed = true
+ if not self.tcp:is_closing() then
+ self.tcp:write(M.encode_frame(OPCODE.CLOSE, ""))
+ self.tcp:shutdown(function() self.tcp:close() end)
+ end
+end
+
+---@class flutter.WebSocketOpts
+---@field on_open fun(ws: flutter.WebSocket)
+---@field on_message fun(text: string)
+---@field on_close fun(err: string?)
+
+---Connects to a `ws://` url. Callbacks are invoked on the main loop.
+---@param url string
+---@param opts flutter.WebSocketOpts
+function M.connect(url, opts)
+ local host, port, resource = url:match("^ws://([^:/]+):(%d+)(/?.*)$")
+ if not host then return opts.on_close("Unsupported websocket url: " .. url) end
+ if resource == "" then resource = "/" end
+
+ local on_open = vim.schedule_wrap(opts.on_open)
+ local on_message = vim.schedule_wrap(opts.on_message)
+ local on_close = vim.schedule_wrap(opts.on_close)
+
+ local tcp = assert(uv.new_tcp())
+ local timer = assert(uv.new_timer())
+ local ws = setmetatable({ tcp = tcp, closed = false }, WebSocket)
+
+ local function fail(err)
+ if not timer:is_closing() then timer:close() end
+ if not tcp:is_closing() then tcp:close() end
+ if ws.closed then return end
+ ws.closed = true
+ on_close(err)
+ end
+
+ timer:start(CONNECT_TIMEOUT_MS, 0, function() fail("Timed out connecting to " .. url) end)
+
+ local function handshake()
+ local key = vim.base64.encode(bytes_to_string(random_bytes(16)))
+ tcp:write(table.concat({
+ ("GET %s HTTP/1.1"):format(resource),
+ ("Host: %s:%s"):format(host, port),
+ "Upgrade: websocket",
+ "Connection: Upgrade",
+ "Sec-WebSocket-Key: " .. key,
+ "Sec-WebSocket-Version: 13",
+ "",
+ "",
+ }, "\r\n"))
+
+ local buffer = ""
+ local handshake_done = false
+ local fragments = {}
+
+ tcp:read_start(function(read_err, chunk)
+ if read_err then return fail(read_err) end
+ if not chunk then return fail(nil) end
+ buffer = buffer .. chunk
+
+ if not handshake_done then
+ local header_end = buffer:find("\r\n\r\n", 1, true)
+ if not header_end then return end
+ local status = buffer:match("^HTTP/1%.1 (%d+)")
+ if status ~= "101" then
+ return fail("Websocket handshake failed: " .. buffer:sub(1, header_end))
+ end
+ handshake_done = true
+ timer:close()
+ buffer = buffer:sub(header_end + 4)
+ on_open(ws)
+ end
+
+ local frames
+ frames, buffer = M.decode_frames(buffer)
+ for _, frame in ipairs(frames) do
+ if frame.opcode == OPCODE.PING then
+ tcp:write(M.encode_frame(OPCODE.PONG, frame.payload))
+ elseif frame.opcode == OPCODE.CLOSE then
+ ws:close()
+ on_close(nil)
+ return
+ elseif frame.opcode == OPCODE.TEXT or frame.opcode == OPCODE.CONTINUATION then
+ fragments[#fragments + 1] = frame.payload
+ if frame.fin then
+ local message = table.concat(fragments)
+ fragments = {}
+ on_message(message)
+ end
+ end
+ end
+ end)
+ end
+
+ uv.getaddrinfo(host, port, { socktype = "stream" }, function(resolve_err, addresses)
+ if resolve_err or not addresses or #addresses == 0 then
+ return fail("Unable to resolve " .. host)
+ end
+ if ws.closed then return end
+ tcp:connect(addresses[1].addr, addresses[1].port, function(connect_err)
+ if connect_err then return fail(connect_err) end
+ handshake()
+ end)
+ end)
+
+ return ws
+end
+
+return M
diff --git a/lua/flutter-tools/widget_preview.lua b/lua/flutter-tools/widget_preview.lua
new file mode 100644
index 0000000..eb3d307
--- /dev/null
+++ b/lua/flutter-tools/widget_preview.lua
@@ -0,0 +1,268 @@
+local lazy = require("flutter-tools.lazy")
+local ui = lazy.require("flutter-tools.ui") ---@module "flutter-tools.ui"
+local config = lazy.require("flutter-tools.config") ---@module "flutter-tools.config"
+local executable = lazy.require("flutter-tools.executable") ---@module "flutter-tools.executable"
+local dtd = lazy.require("flutter-tools.dtd") ---@module "flutter-tools.dtd"
+local dev_tools = lazy.require("flutter-tools.dev_tools") ---@module "flutter-tools.dev_tools"
+local path = lazy.require("flutter-tools.utils.path") ---@module "flutter-tools.utils.path"
+
+--- Runs `flutter widget-preview start`, mirroring Dart-Code's
+--- src/extension/flutter/widget_preview_server.ts.
+local M = {}
+
+local api = vim.api
+
+local ANALYSIS_TIMEOUT_MS = 120000
+local OUTPUT_LINES_ON_FAILURE = 15
+
+---@class flutter.WidgetPreviewState
+---@field job vim.SystemObj?
+---@field pid integer? process reported by the `widget_preview.initializing` event
+---@field url string?
+---@field started boolean
+---@field cancelled boolean
+---@field output string[] recent output, shown if the previewer fails
+---@field dir string
+---@field progress_id (integer|string)?
+
+---@type flutter.WidgetPreviewState?
+local state = nil
+
+---@param color integer?
+---@return string?
+local function to_hex(color)
+ if color then return ("#%06x"):format(color) end
+end
+
+---@param url string
+---@return string
+local function with_theme(url)
+ local normal = api.nvim_get_hl(0, { name = "Normal", link = false })
+ local params = { "theme=" .. (vim.o.background == "light" and "light" or "dark") }
+ for key, color in pairs({
+ backgroundColor = to_hex(normal.bg),
+ foregroundColor = to_hex(normal.fg),
+ }) do
+ params[#params + 1] = key .. "=" .. vim.uri_encode(color)
+ end
+ return url .. (url:find("?", 1, true) and "&" or "?") .. table.concat(params, "&")
+end
+
+---@param url string
+local function open_browser(url)
+ local _, err = vim.ui.open(with_theme(url))
+ if err then ui.notify(err, ui.ERROR) end
+end
+
+---@param current flutter.WidgetPreviewState
+---@param message string
+---@param status "running"|"success"|"failed"
+local function report(current, message, status)
+ current.progress_id = api.nvim_echo({ { message } }, status ~= "running", {
+ id = current.progress_id,
+ kind = "progress",
+ source = "flutter-tools",
+ title = "Widget preview",
+ status = status,
+ })
+end
+
+---@param current flutter.WidgetPreviewState
+---@param line string
+local function record(current, line)
+ if vim.trim(line) == "" then return end
+ table.insert(current.output, line)
+ if #current.output > OUTPUT_LINES_ON_FAILURE then table.remove(current.output, 1) end
+end
+
+---@param current flutter.WidgetPreviewState
+---@param event {event: string, params: table?}
+local function handle_event(current, event)
+ local params = event.params or {}
+ if event.event == "widget_preview.initializing" then
+ current.pid = params.pid
+ elseif event.event == "widget_preview.started" then
+ current.started = true
+ current.url = params.url
+ if config.widget_preview.web_server then open_browser(params.url) end
+ report(current, "Running at " .. params.url, "success")
+ elseif event.event == "widget_preview.logMessage" then
+ if params.level == "error" then
+ ui.notify(params.message, ui.ERROR)
+ else
+ record(current, params.message)
+ if params.level == "status" and not current.started then
+ report(current, params.message, "running")
+ end
+ end
+ end
+end
+
+---@param current flutter.WidgetPreviewState
+---@param line string
+local function handle_stdout(current, line)
+ if vim.startswith(line, "[{") and vim.endswith(line, "}]") then
+ local ok, events = pcall(vim.json.decode, line, { luanil = { object = true, array = true } })
+ if ok and type(events) == "table" then
+ for _, event in ipairs(events) do
+ if type(event) == "table" then handle_event(current, event) end
+ end
+ return
+ end
+ end
+ record(current, line)
+end
+
+---@param current flutter.WidgetPreviewState
+---@param on_line fun(current: flutter.WidgetPreviewState, line: string)
+local function line_reader(current, on_line)
+ local pending = ""
+ return function(_, data)
+ if not data then return end
+ pending = pending .. data
+ for line in pending:gmatch("([^\n]*)\n") do
+ vim.schedule(function() on_line(current, line) end)
+ end
+ pending = pending:match("[^\n]*$")
+ end
+end
+
+---@param current flutter.WidgetPreviewState
+---@param dir string
+---@param dtd_uri string?
+local function run(current, dir, dtd_uri)
+ executable.flutter(function(flutter_bin)
+ if current.cancelled then return end
+ local args = { flutter_bin, "widget-preview", "start", "--machine" }
+ if config.widget_preview.web_server then table.insert(args, "--web-server") end
+ if dtd_uri then vim.list_extend(args, { "--dtd-url", dtd_uri }) end
+ local devtools_url = dev_tools.get_url()
+ if devtools_url then vim.list_extend(args, { "--devtools-server-address", devtools_url }) end
+
+ local ok, job = pcall(
+ vim.system,
+ args,
+ {
+ cwd = dir,
+ stdout = line_reader(current, handle_stdout),
+ stderr = line_reader(current, record),
+ },
+ vim.schedule_wrap(function(result)
+ if state == current then state = nil end
+ if current.cancelled then return report(current, "Stopped", "success") end
+ if result.code == 0 then return report(current, "Exited", "success") end
+ report(current, ("Exited with code %d"):format(result.code), "failed")
+ ui.notify(
+ vim.list_extend(
+ { ("Widget preview exited with code %d"):format(result.code) },
+ current.output
+ ),
+ ui.ERROR
+ )
+ end)
+ )
+ if not ok then
+ if state == current then state = nil end
+ report(current, "Failed to start", "failed")
+ return ui.notify(tostring(job), ui.ERROR)
+ end
+ current.job = job
+ report(current, "Building the preview, the first start can take a while", "running")
+ end)
+end
+
+---Runs from the pub workspace root so previews from every package are included.
+---@param dir string?
+---@return string?
+local function resolve_project_dir(dir)
+ if dir and dir ~= "" then return vim.fs.normalize(vim.fn.fnamemodify(dir, ":p")) end
+ local start = vim.fn.expand("%:p:h")
+ return path.find_root({ "pubspec.yaml" }, start ~= "" and start or vim.fn.getcwd())
+end
+
+---@param current flutter.WidgetPreviewState
+local function reveal(current)
+ if not current.url then return ui.notify("Widget preview is still starting") end
+ if not config.widget_preview.web_server then
+ return ui.notify("The widget preview is running in the Chrome window Flutter opened")
+ end
+ open_browser(current.url)
+end
+
+---Starts the widget previewer, or shows the running one.
+---@param dir string?
+function M.show(dir)
+ if vim.fn.has("nvim-0.12") == 0 then
+ return ui.notify("Widget preview requires Neovim 0.12 or newer", ui.ERROR)
+ end
+ local project_dir = resolve_project_dir(dir)
+ if state then
+ if project_dir and project_dir ~= state.dir then
+ return ui.notify(
+ ("Widget preview is running for %s, stop it first"):format(state.dir),
+ ui.WARN
+ )
+ end
+ return reveal(state)
+ end
+ if not project_dir then return ui.notify("Unable to find a Flutter project", ui.ERROR) end
+
+ ---@type flutter.WidgetPreviewState
+ local current = { started = false, cancelled = false, output = {}, dir = project_dir }
+ state = current
+ report(current, "Starting", "running")
+ dtd.start(function(err)
+ if err then
+ ui.notify("Unable to start the Dart Tooling Daemon: " .. err, ui.WARN)
+ return run(current, project_dir, nil)
+ end
+ if not dtd.can_analyze(project_dir) then
+ ui.notify(
+ "The dart language server does not analyze "
+ .. project_dir
+ .. ", so the preview will not follow the editor",
+ ui.WARN
+ )
+ return run(current, project_dir, nil)
+ end
+ local waiting = true
+ local function run_once()
+ if not waiting then return end
+ waiting = false
+ run(current, project_dir, dtd.uri())
+ end
+ vim.defer_fn(function()
+ if waiting and not current.cancelled then
+ ui.notify("Timed out waiting for the dart language server to analyze the project", ui.WARN)
+ end
+ run_once()
+ end, ANALYSIS_TIMEOUT_MS)
+ dtd.when_analyzed(run_once)
+ if waiting then
+ report(current, "Waiting for the dart language server to finish analysis", "running")
+ end
+ end)
+end
+
+function M.stop()
+ local current = state
+ if not current then return end
+ current.cancelled = true
+ if current.job then
+ current.job:kill("sigterm")
+ if current.pid then pcall(vim.uv.kill, current.pid, "sigterm") end
+ else
+ state = nil
+ report(current, "Stopped", "success")
+ end
+end
+
+---@return boolean
+function M.is_running() return state ~= nil end
+
+function M.on_exit()
+ M.stop()
+ dtd.stop()
+end
+
+return M
diff --git a/tests/websocket_spec.lua b/tests/websocket_spec.lua
new file mode 100644
index 0000000..7b18b21
--- /dev/null
+++ b/tests/websocket_spec.lua
@@ -0,0 +1,34 @@
+local websocket = require("flutter-tools.utils.websocket")
+
+local TEXT = 0x1
+
+describe("websocket frames", function()
+ for _, size in ipairs({ 0, 5, 125, 126, 65535, 65536, 70000 }) do
+ it(("round-trips a %d byte payload"):format(size), function()
+ local payload = string.rep("ab", math.ceil(size / 2)):sub(1, size)
+ local frames, rest = websocket.decode_frames(websocket.encode_frame(TEXT, payload))
+ assert.are.same({ { fin = true, opcode = TEXT, payload = payload } }, frames)
+ assert.are.equal("", rest)
+ end)
+ end
+
+ it("keeps an incomplete frame for the next read", function()
+ local frame = websocket.encode_frame(TEXT, string.rep("x", 300))
+ local frames, rest = websocket.decode_frames(frame:sub(1, 100))
+ assert.are.same({}, frames)
+ frames, rest = websocket.decode_frames(rest .. frame:sub(101))
+ assert.are.equal(300, #frames[1].payload)
+ assert.are.equal("", rest)
+ end)
+
+ it("decodes several frames from one read", function()
+ local data = websocket.encode_frame(TEXT, "one") .. websocket.encode_frame(TEXT, "two")
+ local frames = websocket.decode_frames(data)
+ assert.are.same({ "one", "two" }, vim.tbl_map(function(f) return f.payload end, frames))
+ end)
+
+ it("decodes unmasked server frames", function()
+ local frames = websocket.decode_frames(string.char(0x81, 0x02) .. "hi")
+ assert.are.equal("hi", frames[1].payload)
+ end)
+end)