Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.


<hr/>
Expand All @@ -182,6 +184,21 @@ such as `:FlutterRun --flavor <tasty>`, `:FlutterRun --dart-define=API_URL=https

<hr/>

### `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.

<hr/>

## `FlutterOutline`

The outline window allows you to see the high level layout of the current buffer.
Expand Down Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion lua/flutter-tools.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions lua/flutter-tools/config.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand Down Expand Up @@ -148,6 +149,9 @@ local config = {
autostart = false,
auto_open_browser = false,
},
widget_preview = {
web_server = true,
},
}

local deprecations = {
Expand Down
204 changes: 204 additions & 0 deletions lua/flutter-tools/dtd/client.lua
Original file line number Diff line number Diff line change
@@ -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<integer, fun(err: flutter.DtdError?, result: any)>
local pending = {}

---@type table<string, fun(params: table): 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
Loading
Loading