summaryrefslogtreecommitdiff
path: root/yazi/plugins/clipboard.yazi/main.lua
blob: 0849adc8de966fe38733f4b94f20a344263710e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
local get_yanked_paths = ya.sync(function(state)
	local paths = {}
	for _, v in pairs(cx.yanked) do
		if not v.is_regular then
			goto continue
		end
		table.insert(paths, tostring(v))
		::continue::
	end
	return paths
end)

local get_cwd = ya.sync(function(state)
	return tostring(cx.active.current.cwd)
end)

local M = {
	notify_unknown_display_server = false,
}

function M:entry(job)
	ya.dbg("Clipboard", "args", job.args)
	self.notify_unknown_display_server = job.args.notify_unknown_display_server or false

	if job.args.action == "copy" then
		return self:copy()
	elseif job.args.action == "paste" then
		return self:paste()
	else
		return self:notify_error("Unknown action: " .. tostring(job.args.action))
	end
end

function M:copy()
	local paths = get_yanked_paths()
	ya.dbg("Clipboard", "files", paths)
	if #paths == 0 then
		return self:notify_error("No files to copy")
	end

	local cmd, err = nil, nil
	local args = paths
	if ya.target_os() == "linux" then
		cmd, err = self:copy_linux_cmd()
		if cmd then
			args = {}
			for _, p in ipairs(paths) do
				table.insert(args, self:path_to_file_uri(p))
			end
		end
	elseif ya.target_os() == "macos" then
		cmd, err = self:copy_macos_cmd()
	else
		err = "Unsupported OS: " .. ya.target_os()
	end
	if not self.notify_unknown_display_server and err == "Unknown display server" then
		return
	end
	if err then
		return self:notify_error("Copy failed: " .. err)
	end

	ya.dbg("Clipboard", "cmd", cmd)
	local cmd = Command("sh"):arg({ "-c", cmd, "--" }):arg(args)
	local output, err = cmd:output()
	if err then
		ya.err("Clipboard", "cmd failed", err)
		return self:notify_error("Run command failed: " .. tostring(err))
	end
	if output then
		ya.dbg("Clipboard", "cmd output", output.status.code, output.stdout, output.stderr)
	end
end

function M:copy_linux_cmd()
	if self:linux_display_server() == "x11" then
		return self:copy_x11_cmd()
	elseif self:linux_display_server() == "wayland" then
		return self:copy_wayland_cmd()
	else
		return nil, "Unknown display server"
	end
end

function M:copy_macos_cmd()
	-- Generated by GPT-5-Codex
	cmd = [[osascript - "$@" <<END_SCRIPT
use framework "Foundation"
use framework "AppKit"
use scripting additions

on run argv
  set pasteboard to (current application's NSPasteboard's generalPasteboard())
  pasteboard's clearContents()

  set urlArray to (current application's NSMutableArray's array())
  repeat with path in argv
    set nsPath to (current application's NSString's stringWithString_(path))
    set nsURL to (current application's |NSURL|'s fileURLWithPath_(nsPath))
    (urlArray's addObject_(nsURL))
  end repeat
  pasteboard's writeObjects_(urlArray)

  set previousDelimiters to AppleScript's text item delimiters
  set AppleScript's text item delimiters to linefeed
  set joinedPaths to (argv as text)
  set AppleScript's text item delimiters to previousDelimiters

  set joinedString to (current application's NSString's stringWithString_(joinedPaths))
  pasteboard's setString_forType_(joinedString, current application's NSPasteboardTypeString)
end run
END_SCRIPT]]
	return cmd, nil
end

function M:linux_display_server()
	local xdg_session_type = os.getenv("XDG_SESSION_TYPE")
	if xdg_session_type == "wayland" or xdg_session_type == "x11" then
		return xdg_session_type
	end
	if os.getenv("WAYLAND_DISPLAY") then
		return "wayland"
	end
	if os.getenv("DISPLAY") then
		return "x11"
	end

	return "unknown"
end

function M:copy_x11_cmd()
	local status, err = Command("which"):arg("xclip"):status()
	if err then
		ya.err("Clipboard", "which xclip failed", err)
		return nil, "xclip not found"
	end
	if not (status and status.success) then
		return nil, "xclip not found"
	end
	return [[printf '%s\r\n' "$@" | xclip -i -selection clipboard -t text/uri-list]], nil
end

function M:copy_wayland_cmd()
	local status, err = Command("which"):arg("wl-copy"):status()
	if err then
		ya.err("Clipboard", "which wl-copy failed", err)
		return nil, "wl-copy not found"
	end
	if not (status and status.success) then
		return nil, "wl-copy not found"
	end
	return [[printf '%s\r\n' "$@" | wl-copy -t text/uri-list]], nil
end

function M:paste()
	local paths, err = nil, nil
	if ya.target_os() == "linux" then
		paths, err = self:paste_linux()
	elseif ya.target_os() == "macos" then
		paths, err = self:paste_macos()
	else
		err = "Unsupported OS: " .. ya.target_os()
	end
	if not self.notify_unknown_display_server and err == "Unknown display server" then
		return
	end
	if err then
		return self:notify_error("Paste failed: " .. err)
	end
	if not paths or #paths == 0 then
		return self:notify_error("No files in clipboard")
	end

	ya.dbg("Clipboard", "paste paths", paths)

	local cwd_url = Url(get_cwd())
	local copied = 0
	local skipped = 0
	local errors = {}
	local apply_all = nil
	for _, src in ipairs(paths) do
		local name = src:match("[^/]+$")
		if name then
			local dest_url = cwd_url:join(name)
			local dest = tostring(dest_url)

			local existing = fs.cha(dest_url)
			if existing then
				local choice = apply_all
				if not choice then
					choice, apply_all = self:ask_conflict(name, #paths > 1)
				end
				if choice == "skip" then
					skipped = skipped + 1
					goto continue
				elseif choice == "rename" then
					dest = self:unique_name(cwd_url, name)
				end
			end

			local ok, copy_err = self:copy_path(src, dest)
			if ok then
				copied = copied + 1
			else
				ya.err("Clipboard", "copy failed", src, tostring(copy_err))
				table.insert(errors, name .. ": " .. tostring(copy_err))
			end
			::continue::
		end
	end

	if copied > 0 or skipped > 0 then
		local parts = {}
		if copied > 0 then
			table.insert(parts, "Pasted " .. copied .. " file(s)")
		end
		if skipped > 0 then
			table.insert(parts, "Skipped " .. skipped .. " file(s)")
		end
		ya.notify({
			title = "Clipboard",
			content = table.concat(parts, ", "),
			timeout = 3,
			level = "info",
		})
	end
	if #errors > 0 then
		self:notify_error("Failed to paste:\n" .. table.concat(errors, "\n"))
	end
end

function M:ask_conflict(name, multiple)
	local prompt = name .. " exists: (o)verwrite (r)ename (s)kip"
	if multiple then
		prompt = prompt .. " (O/R/S=apply to all)"
	end
	local value, event = ya.input({
		title = prompt,
		pos = { "center", w = #prompt + 4 },
	})
	if event ~= 1 or not value or value == "" then
		return "skip", nil
	end
	local c = value:sub(1, 1)
	local apply_all = nil
	if multiple and c == c:upper() then
		c = c:lower()
		if c == "o" then
			apply_all = "overwrite"
		elseif c == "r" then
			apply_all = "rename"
		elseif c == "s" then
			apply_all = "skip"
		end
	end
	if c == "o" then
		return "overwrite", apply_all
	elseif c == "r" then
		return "rename", apply_all
	else
		return "skip", apply_all
	end
end

function M:unique_name(cwd_url, name)
	local base, ext = name:match("^(.+)(%.[^.]+)$")
	if not base then
		base = name
		ext = ""
	end
	local i = 1
	while true do
		local candidate = base .. " (" .. i .. ")" .. ext
		local candidate_url = cwd_url:join(candidate)
		if not fs.cha(candidate_url) then
			return tostring(candidate_url)
		end
		i = i + 1
	end
end

function M:copy_path(src, dest)
	local src_url = Url(src)
	local dest_url = Url(dest)
	local cha, err = fs.cha(src_url)
	if not cha then
		return false, "cannot stat: " .. tostring(err)
	end

	if cha.is_dir then
		return self:copy_dir(src_url, dest_url)
	else
		local ok, copy_err = fs.copy(src_url, dest_url)
		if ok then
			return true, nil
		else
			return false, tostring(copy_err)
		end
	end
end

function M:copy_dir(src_url, dest_url)
	local ok, err = fs.create("dir_all", dest_url)
	if not ok then
		return false, "mkdir failed: " .. tostring(err)
	end

	local entries, read_err = fs.read_dir(src_url, {})
	if not entries then
		return false, "read_dir failed: " .. tostring(read_err)
	end

	for _, entry in ipairs(entries) do
		local child_dest = dest_url:join(entry.name)
		if entry.cha.is_dir then
			local ok, dir_err = self:copy_dir(entry.url, child_dest)
			if not ok then
				return false, dir_err
			end
		else
			local ok, copy_err = fs.copy(entry.url, child_dest)
			if not ok then
				return false, tostring(copy_err)
			end
		end
	end

	return true, nil
end

function M:paste_macos()
	local cmd = Command("osascript"):arg({
		"-e",
		[[
use framework "Foundation"
use framework "AppKit"
use scripting additions

set pasteboard to (current application's NSPasteboard's generalPasteboard())
set urlArray to (pasteboard's readObjectsForClasses_options_({current application's |NSURL|}, missing value))

if urlArray is missing value then return ""

set pathList to {}
repeat with u in urlArray
  set end of pathList to (u's |path|() as text)
end repeat

set AppleScript's text item delimiters to (character id 0)
return pathList as text
]],
	})
	local output, err = cmd:output()
	if err then
		ya.err("Clipboard", "paste macos failed", err)
		return nil, "osascript failed: " .. tostring(err)
	end
	if not output or output.status.code ~= 0 then
		return nil, "osascript exited with code " .. tostring(output and output.status.code)
	end

	local stdout = output.stdout
	if not stdout then
		return {}, nil
	end
	stdout = stdout:gsub("%s+$", "")
	if stdout == "" then
		return {}, nil
	end
	local paths = {}
	for path in stdout:gmatch("[^%z]+") do
		path = path:gsub("%s+$", "")
		if path ~= "" then
			table.insert(paths, path)
		end
	end
	return paths, nil
end

function M:paste_linux()
	if self:linux_display_server() == "x11" then
		return self:paste_x11()
	elseif self:linux_display_server() == "wayland" then
		return self:paste_wayland()
	else
		return nil, "Unknown display server"
	end
end

function M:paste_x11()
	local status, err = Command("which"):arg("xclip"):status()
	if err or not (status and status.success) then
		return nil, "xclip not found"
	end
	local output, err = Command("xclip"):arg({ "-o", "-selection", "clipboard", "-t", "text/uri-list" }):output()
	if err then
		return nil, "xclip failed: " .. tostring(err)
	end
	if not output or output.status.code ~= 0 then
		return {}, nil
	end
	return self:parse_uri_list(output.stdout), nil
end

function M:paste_wayland()
	local status, err = Command("which"):arg("wl-paste"):status()
	if err or not (status and status.success) then
		return nil, "wl-paste not found"
	end
	local output, err = Command("wl-paste"):arg({ "-t", "text/uri-list" }):output()
	if err then
		return nil, "wl-paste failed: " .. tostring(err)
	end
	if not output or output.status.code ~= 0 then
		return {}, nil
	end
	return self:parse_uri_list(output.stdout), nil
end

function M:parse_uri_list(text)
	if not text or text == "" then
		return {}
	end
	local paths = {}
	for line in text:gmatch("[^\r\n]+") do
		if line:sub(1, 1) ~= "#" then
			local path = line:match("^file://[^/]*(/.+)")
			if path then
				path = path:gsub("%%(%x%x)", function(hex)
					return string.char(tonumber(hex, 16))
				end)
				table.insert(paths, path)
			end
		end
	end
	return paths
end

function M:path_to_file_uri(path)
	local encoded = path:gsub("([^A-Za-z0-9/_.~-])", function(c)
		return string.format("%%%02X", string.byte(c))
	end)
	return "file://" .. encoded
end

function M:notify_error(msg)
	ya.notify({ title = "Clipboard", content = msg, timeout = 6.5, level = "error" })
end

return M