-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgui-widgets.lua
521 lines (487 loc) · 12.7 KB
/
gui-widgets.lua
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
local started = false
local clientChannel = nil
local kvStore = {}
local downloads = {}
local placements = {}
local nextId=1
local namespaceId = nil
local uv = vim.loop
local Path = require'plenary.path'
local Job = require'plenary.job'
local Assert = require'luassert.assert'
local Base64 = require'base64'
local synID = vim.fn.synID
local synIDtrans = vim.fn.synIDtrans
local synIDattr = vim.fn.synIDattr
local function start()
if started then
return
end
namespaceId = vim.api.nvim_create_namespace("GuiWidget")
started = true
end
local function attach(chan)
clientChannel = chan
end
-- taken from plenary/path.lua, should be exposed imo..
local function _is_uri (filename)
return string.match(filename, "^%w+://") ~= nil
end
local function _read_file(path, cb)
-- tried plenary.async, coros don't work here yet.
uv.fs_open(path, "r", 438, function(err, fd)
Assert(not err, err)
uv.fs_fstat(fd, function(err, stat)
Assert(not err, err)
uv.fs_read(fd, stat.size, 0, function(err, data)
Assert(not err, err)
uv.fs_close(fd, function(err)
Assert(not err, err)
cb(data)
end)
end)
end)
end)
end
local function _make_tmpfile(template, cb)
local tmp
if Path.path.sep == '/' then
tmp = '/tmp'
else
tmp = os.getenv('TEMP')
end
template = tostring(Path:new(tmp) / template)
uv.fs_mkstemp(template,function(err,fd,path)
Assert(not err, err)
uv.fs_close(fd, function(err)
Assert(not err, err)
cb(path)
end)
end)
end
local function _download_file(url, cb)
local curl
if Path.path.sep == '/' then
curl = 'curl'
else
local prog = Path:new(vim.v.progpath)
curl = tostring(prog:parent() / "curl.exe")
end
_make_tmpfile('gui-widgets.downloadXXXXXX',function(path)
Job:new({
command = curl;
args = {url; '-o'; path};
enable_handlers = true;
on_exit = function(job, code, signal)
Assert(code == 0, 'curl exited with non-zero code ' .. code)
-- TODO check signal
cb(path)
end;
}):start()
end)
end
local function request(id)
local val = kvStore[id]
if clientChannel == nil or val == nil then
return
end
if val.path ~= nil then
_read_file(val.path, function(data)
vim.rpcnotify(clientChannel, "GuiWidgetPut", {
id = id;
mime = val.mime;
data = data;
}) end)
elseif val.data ~= nil then
vim.rpcnotify(clientChannel, "GuiWidgetPut", {
id = id;
mime = val.mime;
data = val.data;
})
end
end
-- param path: a path to the resource to put, can be a local file or url
-- param mime: the mime type of the resource
-- return: a non-negative integer representing the id of the resource
local function put_file(path, mime)
local id = nextId
nextId = nextId + 1
local function _do_put_file(p)
kvStore[id] = {
path = p;
mime = mime;
}
-- push it to the client right away
request(id)
end
if path:find('http://', 1, true) == 1 or path:find('https://', 1, true) == 1 then
local d = downloads[path]
if d == nil then
_download_file(path, function(tmp_path)
downloads[path] = tmp_path
_do_put_file(tmp_path)
end)
else
_do_put_file(d)
end
else
_do_put_file(path)
end
return id
end
local function put_data(data, mime)
local id = nextId
nextId = nextId + 1
kvStore[id] = {
data = data;
mime = mime;
}
-- push it to the client right away
request(id)
return id
end
local function put_base64(data, mime)
local bin = Base64.decode(data)
return put_data(bin, mime)
end
-- param id: a resource id, or an array
local function del(widgets)
if type(widgets) ~= "table" then
widgets = { widgets }
end
for _,i in pairs(widgets) do
table.remove(kvStore, i)
end
vim.rpcnotify(clientChannel, "GuiWidgetDelete", widgets)
end
local function _buf(buf)
if type(buf) == "string" then
buf = tonumber(buf)
elseif buf == 0 or buf == nil then
buf = vim.api.nvim_get_current_buf()
end
return buf
end
-- caller ensures opt is either nil or a table
-- adds ['mouse']=true if related opts are set
local function check_mouse_opt(opt)
if opt == nil then
return
end
local has_mouse = false
for k,v in pairs(opt) do
if k:find('clicked',1,true) == 1
or k:find('released',1,true) == 1
then
has_mouse = true
break
end
end
if has_mouse then
opt['mouse'] = true
end
end
-- place non-positive id to unplace
local function place(id, bufnr, row, col, w, h, opt)
bufnr = _buf(bufnr)
local mark = vim.api.nvim_buf_set_extmark(bufnr, namespaceId, row, col, {
virt_text={{'','IncSearch'}},
virt_text_pos='overlay',
ui_watched=true
})
Assert(opt == nil or ((type(opt) == 'table') and not vim.tbl_islist(opt)),
'opt should be a dictionary')
check_mouse_opt(opt)
-- TODO remove
local tbl = placements[bufnr]
local opt_virt_lines = opt['virt-lines']
if tbl == nil then
tbl = { }
placements[bufnr] = tbl
end
tbl[mark] = { id, w, h, opt }
if h > 1 and opt_virt_lines then
local lines = {}
for i=1,h-1 do
lines[i] = {{'','Normal'}}
end
vim.api.nvim_buf_set_extmark(bufnr, namespaceId, row, 1, {
virt_lines=lines
})
end
return mark
end
local function update_view(buf)
if clientChannel == nil then
return
end
buf = _buf(buf)
local marks = vim.api.nvim_buf_get_extmarks(buf, namespaceId, 0, -1, {})
local tbl = placements[buf]
if tbl == nil then
return
end
local widgets = {}
local idx = 1
for _,m in pairs(marks) do
local w = tbl[m[1]]
if w then
-- [ mark_id res_id w h, opt ]
widgets[idx] = { m[1], w[1], w[2], w[3], w[4] }
idx = idx + 1
end
end
vim.rpcnotify(clientChannel, "GuiWidgetUpdateView", {
buf = buf;
widgets = widgets;
})
end
-- Sample opt data:
-- {
-- ['clicked-widget']=w2;
-- ['clicked-exec']='silent call VsimToggleColor()';
-- ['released-widget']=w1;
-- ['halign']='center';
-- ['valign']='center';
-- ['stretch']='uniform';
-- }
local function mouse_event(buf, mark, ev)
local tbl = placements[buf]
if tbl == nil then
return
end
local p = tbl[mark]
if p == nil then
return
end
local opt = p[4]
if ev == 'down' then
local click_exec = opt['clicked-exec']
if click_exec ~= nil then
vim.api.nvim_exec(click_exec, false)
end
local click_widget = opt['clicked-widget']
if click_widget ~= nil then
p[1] = click_widget
update_view(buf)
end
elseif ev == 'up' then
local release_widget = opt['released-widget']
if release_widget ~= nil then
p[1] = release_widget
update_view(buf)
end
else
end
end
local function mouse_up(buf, mark)
print('mouse up ' .. buf .. ', ' .. mark)
mouse_event(buf, mark, 'up')
end
local function mouse_down(buf, mark)
print('mouse down ' .. buf .. ', ' .. mark)
mouse_event(buf, mark, 'down')
end
local function clear_view(buf)
if clientChannel == nil then
return
end
buf = _buf(buf)
local tbl = placements[buf]
if tbl == nil then
return
end
local widgets = {}
for _, p in pairs(tbl) do
widgets[#widgets+1] = p[1] -- widget id
end
del(widgets)
placements[buf] = {}
vim.api.nvim_buf_clear_namespace(buf, namespaceId, 0, -1)
end
local _hdr_mkd_levelRegexpDict = {
[1] = vim.regex [[^[^:alnum:]*\(#[^#]\@=\|.\+\n\=+$\)]];
[2] = vim.regex [[^[^:alnum:]*\(##[^#]\@=\|.\+\n-+$\)]];
[3] = vim.regex [[^[^:alnum:]*###[^#]\@=]];
[4] = vim.regex [[^[^:alnum:]*####[^#]\@=]];
[5] = vim.regex [[^[^:alnum:]*#####[^#]\@=]];
[6] = vim.regex [[^[^:alnum:]*######[^#]\@=]];
}
-- note the reversed order
local _hdr_levelRegexpDict = {
[1] = vim.regex [[^[^:alnum:]*=[^=]\+=]];
[2] = vim.regex [[^[^:alnum:]*==[^=]\+==]];
[3] = vim.regex [[^[^:alnum:]*===[^=]\+===]];
[4] = vim.regex [[^[^:alnum:]*====[^=]\+====]];
[5] = vim.regex [[^[^:alnum:]*=====[^=]\+=====]];
[6] = vim.regex [[^[^:alnum:]*======[^=]\+======]];
}
local _hdr_levelScaleDict = {
[1] = 2.0;
[2] = 1.8;
[3] = 1.6;
[4] = 1.2;
[5] = 1.1;
[6] = 1.0;
}
local _hdr_levelLineDict = {
[1] = 2;
[2] = 2;
[3] = 2;
[4] = 1;
[5] = 1;
[6] = 1;
}
local _img_Regexp = vim.regex '!\\[[^\\]]*\\]([^)]*)'
local _math_Regexp = vim.regex '\\$[^$]*\\$'
local _cpp_ish = { ['c']=true; ['cpp']=true; ['objc']=true; ['objcpp']=true; ['cs']=true; ['fsharp']=true; ['cuda']=true; ['asm']=true; }
-- from: https://gist.github.com/liukun/f9ce7d6d14fa45fe9b924a3eed5c3d99
local function _char_to_hex(c)
return string.format("%%%02X", string.byte(c))
end
local function _urlencode(url)
if url == nil then
return
end
url = url:gsub("\n", "\r\n")
url = url:gsub("([^%w ])", _char_to_hex)
url = url:gsub(" ", "+")
return url
end
local function refresh_buf(buf)
if clientChannel == nil then return end
buf = _buf(buf)
clear_view(buf)
local nlines = vim.api.nvim_buf_line_count(buf)
local filetype = vim.api.nvim_buf_get_option(buf, 'filetype')
local is_mkd = filetype == 'markdown'
local commentstring = vim.api.nvim_buf_get_option(buf, 'commentstring')
local hash_is_comment = (commentstring:find('#',1,true)==1)
local cpp_ish = (_cpp_ish[filetype] ~= nil)
local function check_pos(r,c)
if is_mkd then return true end
if not r or not c then return false end
local synid = synID(r+1,c+1,1)
synid = synIDtrans(synid)
local name = synIDattr(synid, 'name')
return name == 'Comment'
end
local function process_headers(i)
local level,s,e
local is_mkd_hdr = false
if is_mkd or (not hash_is_comment and not cpp_ish) then
for lev=1,6 do
local regex = _hdr_mkd_levelRegexpDict[lev]
local s__, e__ = regex:match_line(buf, i)
if s__ ~= nil then
s = s__
e = e__
level = lev
is_mkd_hdr = true
else
break
end
end
end
if not level then
for lev=1,6 do
local regex = _hdr_levelRegexpDict[lev]
local s__, e__ = regex:match_line(buf, i)
if s__ ~= nil then
s = s__
e = e__
level = lev
else
break
end
end
end
if not level or not check_pos(i,s) then
return
end
local line = vim.api.nvim_buf_get_lines(buf,i,i+1,false)[1]
local s_ = s + 1
if is_mkd_hdr then
s_ = line:find('#', s_, true)
line = line:sub(s_ + level)
else
s_ = line:find('=', s_, true)
line = line:sub(s_ + level, e - level)
end
local w = put_data(line, 'text/plain')
local size = _hdr_levelScaleDict[level]
local h = _hdr_levelLineDict[level]
place(w, buf, i, s_-1, 3 * #line, h, {
['text-font']='Arial';
['text-scale']=size;
['text-hlid']='Normal';
['hide']='cursorline';
['virt-lines']=true;
})
end
local function process_imgs(i)
local s,e = _img_Regexp:match_line(buf, i)
if s == nil or not check_pos(i,s) then return end
local line = vim.api.nvim_buf_get_lines(buf,i,i+1,false)[1]
local s_ = line:find('(', s + 1, true) + 1
local e_ = e - 1
local path = Path:new(line:sub(s_, e_))
if not _is_uri(tostring(path)) and not path:is_absolute() then
local bufpath = Path:new(vim.api.nvim_buf_get_name(buf))
path = bufpath:parent() / path
end
local w = put_file(tostring(path), 'image/*')
local img_end = i
for j=i+1,i+24 do
local line_below = vim.api.nvim_buf_get_lines(buf,j,j+1,false)[1]
if line_below == '' then
img_end = j
else
break
end
end
place(w, buf, i, s, 80, img_end - i + 1, {
['halign']='left';
['valign']='top';
['stretch']='uniform';
['hide']='cursorline';
})
end
local function process_math(i)
local s,e = _math_Regexp:match_line(buf, i)
if s == nil or not check_pos(i, s) then return end
local line = vim.api.nvim_buf_get_lines(buf,i,i+1,false)[1]
local s_ = line:find('$', s + 1, true) + 1
local e_ = e - 1
local path = 'https://render.githubusercontent.com/render/math?math='.._urlencode(line:sub(s_, e_))
local w = put_file(path, 'image/svg')
place(w, buf, i, s, e - s, 1, {
['halign']='center';
['valign']='center';
['stretch']='uniform';
['hide']='cursor';
['svg-themed']=true;
})
end
for i=0,nlines-1 do
process_headers(i)
process_imgs(i)
process_math(i)
end
update_view(buf)
end
return {
start = start;
attach = attach;
request = request;
put_file = put_file;
put_data = put_data;
put_base64 = put_base64;
del = del;
place = place;
update_view = update_view;
clear_view = clear_view;
mouse_up = mouse_up;
mouse_down = mouse_down;
refresh_buf = refresh_buf;
}