This repository was archived by the owner on Apr 17, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtelepipe.lua
More file actions
executable file
·2138 lines (1970 loc) · 61.9 KB
/
telepipe.lua
File metadata and controls
executable file
·2138 lines (1970 loc) · 61.9 KB
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[ telepipe.lua (graphical command-line shell)
Copyright © 2026 Victoria Lacroix
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ]]--
-- SECTION: Helper functions
local lib = require "telepipelib"
local _ = lib.gettext
local app_title = _ "Telepipe"
local app_id = lib.get_app_id()
local install_prefix = lib.get_install_prefix()
-- Replace's the user's $HOME with the tilde "~" character, a common convention when displaying paths.
function lib.fmtdir(path)
return path:gsub("^" .. os.getenv "HOME", "~", 1)
end
function lib.expanddir(path)
return path:gsub("^~", os.getenv "HOME", 1)
end
function lib.strip(text)
return text:gsub("^%s*", ""):gsub("%s*$", "")
end
function lib.fileexists(path)
local ok, err, code = os.rename(path, path)
if not ok and code == 13 then
-- In Linux, error code 13 when moving a file means that it failed because the directory cannot be made its own child. Any other error means the file does not exist.
return true
end
return ok
end
function lib.isdir(path)
if path == "/" then return true end
-- If the given path points to a directory, then adding a "/" suffix will show the file as still existing.
return lib.fileexists(path .. "/")
end
function lib.unescapeutf(str)
assert(type(str) == "string")
-- Single-quotes need to be escaped, because the string itself will be single-quoted.
str = str:gsub("'", "\\'")
local src = ("return '%s'"):format(str)
local f = assert(load(src))
return f()
end
function lib.unflatpakize(file)
local path
local fileinfo = file:query_info "xattr::document-portal.host-path"
if fileinfo then
path = fileinfo:get_attribute_string "xattr::document-portal.host-path"
path = lib.unescapeutf(path)
end
if not path then
path = file:get_path()
path = lib.unescapeutf(path)
end
if path:match "^/run/host" then
path = path:gsub("^/run/host", "", 1)
end
return path
end
-- Simple class implementation without inheritance.
function lib.newclass(init)
local c = {}
local mt = {}
c.__index = c
function mt:__call(...)
local obj = setmetatable({}, c)
init(obj, ...)
return obj
end
function c:isa(klass)
return getmetatable(self) == klass
end
return setmetatable(c, mt)
end
-- SECTION: Application
if lib.get_is_flatpak() then
-- This app runs in Flatpak, which puts Lua libraries outside of the standard paths. These lines tell Lua to look for libraries where Flatpak has put them.
package.cpath = install_prefix .. "/lib/lua/5.5/?.so;" .. package.cpath
package.path = install_prefix .. "/share/lua/5.5/?.lua;" .. package.path
end
local LuaGObject = require "LuaGObject"
local Adw = LuaGObject.Adw
local Gdk = LuaGObject.Gdk
local Gio = LuaGObject.Gio
local GLib = LuaGObject.GLib
local GObject = LuaGObject.GObject
local Gtk = LuaGObject.Gtk
local app = Adw.Application {
application_id = lib.get_app_id(),
resource_base_path = "/ca/vtrlx/Telepipe", -- Needs to be hardcoded.
flags = { "HANDLES_COMMAND_LINE" }, -- Only for --new-window.
}
app:add_main_option("new-window", string.byte "n", "IN_MAIN", "NONE", "Create a new window.")
local accels = {
["win.focus-cmdbar"] = { "<Ctrl>K" },
["win.new-tab"] = { "<Ctrl>T" },
["win.dup-tab"] = { "<Ctrl><Shift>T" },
["win.close-tab"] = { "<Ctrl>W" },
["win.new-win"] = { "<Ctrl>N" },
["win.overview"] = { "<Ctrl><Shift>O" },
["win.enter-file-path"] = { "<Ctrl>J" },
["win.enter-folder-path"] = { "<Ctrl><Shift>J" },
["win.chdir"] = { "<Ctrl>M" },
["win.open-folder"] = { "<Ctrl>D" },
["win.search"] = { "<Ctrl>F" },
["win.signal-kill"] = { "<Ctrl><Alt>C" },
["win.signal-endinput"] = { "<Ctrl><Alt>D" },
["win.signal-background"] = { "<Ctrl><Alt>Z" },
["win.preferences"] = { "<Ctrl>comma" },
["win.shortcuts"] = { "<Ctrl><Shift>question" },
["win.about"] = { "F1" },
}
for k, v in pairs(accels) do
app:set_accels_for_action(k, v)
end
-- SECTION: GResources
do -- Load and register GResource.
local resource = Gio.Resource.load(install_prefix .. "/data/telepipe.gresource")
assert(resource)
Gio.resources_register(resource)
end -- Load and register GResource.
-- SECTION: Important variables
local windows = {}
local runners = {}
local function get_focused_window()
if not app.active_window then return end
return windows[app.active_window]
end
local function get_focused_runner()
local win = get_focused_window()
if not win then return end
local tabview = win.tabview
if not tabview then return end
local page = tabview.selected_page
if not page then return end
return runners[page.child]
end
-- SECTION: Custom styling
do
local styleman = Adw.StyleManager.get_default()
local display = Gdk.Display.get_default()
local provider = Gtk.CssProvider()
provider:load_from_string [[
/* Even without actions, images will become more opque on hover. This prevents that from happening. */
image.nohover:hover {
opacity: 0.7;
}
]]
Gtk.StyleContext.add_provider_for_display(display, provider, 1000000)
end
-- SECTION: Environment Variables
local envvarmodel = Gtk.StringList()
local validname = "[A-Za-z_][A-Za-z0-9_]*"
local envvars = {}
local confdir = os.getenv "XDG_CONFIG_HOME" .. "/telepipe/"
local envfile = confdir .. "env"
local envfilenext = confdir .. "envnext"
local function mkdir(path)
local file = Gio.File.new_for_path(path)
file:make_directory_with_parents()
end
-- Returns a generator that iterates over all variable names in alphabetical order (as determined by Lua).
local function varnames()
local names = {}
for name in pairs(envvars) do table.insert(names, name) end
table.sort(names)
return coroutine.wrap(function()
for _, name in ipairs(names) do coroutine.yield(name) end
end)
end
local function saveenv()
local env = ""
for name in varnames() do
local value = envvars[name]
env = env .. ("%s=%s\n"):format(name, value)
end
-- This should be guaranteed to work, because of Flatpak.
io.open(envfilenext, "w"):write(env):close()
os.rename(envfilenext, envfile)
end
local function setenv(name, value)
if envvars[name] then
local formatted = ("%s=%s"):format(name, envvars[name])
local index = envvarmodel:find(formatted)
envvarmodel:remove(index)
end
if value then
envvarmodel:append(("%s=%s"):format(name, value))
end
envvars[name] = value
saveenv()
end
local function parseenv(env)
local pattern = ("(%s)=([^\n]*)"):format(validname)
for name, value in env:gmatch(pattern) do
-- Added manually to prevent stomping out the environment.
envvarmodel:append(("%s=%s"):format(name, value))
envvars[name] = value
end
end
local function loadenv()
-- If the "next" file exists, then a partial write wasn't completed.
if lib.fileexists(envfilenext) then
os.rename(envfilenext, envfile)
end
if not lib.fileexists(envfile) then return end
parseenv(io.open(envfile):read "a")
end
do -- Load the configured global environment variables.
if lib.fileexists(confdir) and not lib.isdir(confdir) then
-- Configuration is broken due to external influence. Because this app runs in a Flatpak sandbox, any files inside of it should be expected to be under control of the app, so deleting it shouldn't violate any reasonable user expectations.
os.remove(tallydir)
end
if not lib.fileexists(confdir) then mkdir(confdir) end
loadenv()
end
-- SECTION: Command runner class
local runnermenu = Gio.Menu()
runnermenu:append(_ "Stop Running Command", "win.signal-kill")
runnermenu:append(_ "Close Command Input", "win.signal-endinput")
runnermenu:append(_ "Send to Background", "win.signal-background")
local runner = lib.newclass(function(self, params)
if type(params) ~= "table" then params = {} end
self.env = {}
self.pwd = params.pwd or os.getenv "HOME"
self.outputqueue = ""
local factory = Gtk.SignalListItemFactory {
on_setup = function(_, ...) self:setupitem(...) end,
on_bind = function(_, ...) self:binditem(...) end,
on_unbind = function(_, ...) self:unbinditem(...) end,
on_teardown = function(_, ...) self:teardownitem(...) end,
}
self.prefix = params.prefix or ""
if not params.history then
self.history = {
[self.prefix] = Gtk.StringList(),
}
else
self.history = {}
for prefix, list in pairs(params.history) do
self.history[prefix] = Gtk.StringList()
for i = 1, list.n_items do
local index = i - 1
self.history[prefix]:append(list:get_string(index))
end
end
end
self.listitems = {}
self.histview = Gtk.ListView {
valign = "END",
width_request = 300,
factory = factory,
model = Gtk.NoSelection {
model = self:gethistory(),
},
}
self.matches = {}
self.textview = Gtk.TextView {
extra_css_classes = { "numeric" },
top_margin = 12,
bottom_margin = 12,
left_margin = 18,
right_margin = 18,
pixels_above_lines = 2,
pixels_below_lines = 2,
pixels_inside_wrap = 0,
wrap_mode = Gtk.WrapMode.WORD_CHAR,
}
self.buffer = self.textview.buffer
self.scrolledwin = Gtk.ScrolledWindow {
child = self.textview,
hscrollbar_policy = "NEVER",
}
local vadjust = self.scrolledwin.vadjustment
local oldupper = vadjust.upper
self.doscroll = true
function vadjust.on_value_changed()
-- If the scroll bar is at the bottom of the command output, further output should cause the scroll bar to continue scrolling down.
if vadjust.value >= vadjust.upper - vadjust.page_size then
self.doscroll = true
else
self.doscroll = false
end
end
function vadjust.on_notify.upper()
local upper = vadjust.upper
if self.doscroll then
-- This is a best-guess attempt at determining a good delay for actually scrolling the window down after its upper bound has changed, because the scroll window takes some time to adjust its content size.
local factor = math.floor((vadjust.upper / vadjust.page_size) / 5)
local timeout = math.max(5, math.min(100, factor))
GLib.timeout_add(20, timeout, function()
vadjust.value = math.maxinteger
-- It's very possible that self.doscroll might not get re-enabled due to recalculations of the scrolled window's size, so because this *should* result in scrolling to the bottom, just forcibly enable scrolling now to ensure that it continues after a later resize.
self.doscroll = true
end)
elseif vadjust.upper == vadjust.page_size then
-- If the output was cleared after previously having been scrolled to the top, the value hasn't changed but the bottom has and so automatic scrolling should be reenabled.
self.doscroll = true
end
oldupper = upper
end
if params.buffer then
self.buffer.text = params.buffer.text
end
-- Search
self.searchentry = Gtk.Text {
placeholder_text = _ "Find in output…",
hexpand = true,
on_activate = function()
self:searchnext(self.searchentry.text)
end,
}
function self.searchentry.on_notify.text()
if not self.searchbar.search_mode_enabled then return end
if #self.searchentry.text == 0 then
self.matchlabel.label = ""
self.searchclearbutton.visible = false
return
end
self:findall(self.searchentry.text)
self.searchclearbutton.visible = true
end
self.searchclearbutton = Gtk.Button {
css_name = "image",
icon_name = "tp-clear-symbolic",
margin_start = 12,
visible = false,
on_clicked = function()
self.searchentry.text = ""
self.searchentry:grab_focus()
end,
}
self.matchlabel = Gtk.Label {
extra_css_classes = { "numeric" },
halign = "END",
hexpand = false,
margin_start = 6,
margin_end = 6,
}
function self.matchlabel.on_notify.text()
self.matchlabel.visible = #self.matchlabel.text > 0
end
local searchentrybox = Gtk.Box {
orientation = "HORIZONTAL",
css_name = "entry",
Gtk.Image {
extra_css_classes = { "nohover" },
icon_name = "tp-search-symbolic",
},
self.searchentry,
self.searchclearbutton,
self.matchlabel,
}
local prevmatchbutton = Gtk.Button {
icon_name = "tp-up-symbolic",
tooltip_text = _ "Go to previous match",
on_clicked = function()
self:searchprev(self.searchentry.text)
end,
}
local nextmatchbutton = Gtk.Button {
icon_name = "tp-down-symbolic",
tooltip_text = _ "Go to next match",
on_clicked = function()
self:searchnext(self.searchentry.text)
end,
}
local searchbox = Gtk.Box {
orientation = "HORIZONTAL",
extra_css_classes = { "linked" },
searchentrybox,
prevmatchbutton,
nextmatchbutton,
}
local searchclamp = Adw.Clamp {
orientation = "HORIZONTAL",
child = searchbox,
maximum_size = 600,
}
self.searchbar = Gtk.SearchBar {
child = searchclamp,
search_mode_enabled = false,
show_close_button = true,
}
self.searchbar:connect_entry(self.searchentry)
function self.buffer.on_changed()
if self.searchbar.search_mode_enabled then
self:findall(self.searchentry.text)
end
end
self.chdirbutton = Gtk.Button {
action_name = "win.chdir",
icon_name = "tp-folder-symbolic",
tooltip_text = _ "Select new working directory…",
}
local menupopover = Gtk.PopoverMenu.new_from_model(runnermenu)
menupopover.halign = "START"
self.menubutton = Gtk.MenuButton {
icon_name = "tp-signal-symbolic",
direction = "UP",
tooltip_text = _ "Signal to running command…",
popover = menupopover,
visible = false,
}
local prefixlabel, prefixtooltip = self:getprefixlabel()
self.prefixbutton = Gtk.Button {
tooltip_text = prefixtooltip,
label = prefixlabel,
visible = #self.prefix > 0,
on_clicked = function()
self:switchprefix ""
self:ensurenewlines()
self:putstring "Prefix was cleared."
self:print "\n"
self:grab()
end,
}
self.historybutton = Gtk.MenuButton {
tooltip_text = _ "Command history",
icon_name = "tp-history-symbolic",
visible = self.history[self.prefix].n_items > 0,
direction = "UP",
popover = Gtk.Popover {
halign = "END",
child = Gtk.ScrolledWindow {
child = self.histview,
max_content_height = 300,
propagate_natural_height = true,
hscrollbar_policy = "NEVER",
},
}
}
function self.historybutton.popover.child.child.on_map()
-- This isn't ideal, but there are no good options here.
self.histview.width_request = math.max(300,
math.floor(self.entry.width * 0.75))
scrolled = self.historybutton.popover.child.child
GLib.timeout_add(20, GLib.PRIORITY_DEFAULT, function()
scrolled.vadjustment.value = scrolled.vadjustment.upper
end)
end
self.sendbutton = Gtk.Button {
extra_css_classes = { "suggested-action" },
icon_name = "tp-run-symbolic",
tooltip_text = _ "Run command",
sensitive = false,
on_clicked = function()
self:doactivate()
end,
}
self.entry = Gtk.Text {
extra_css_classes = { "numeric" },
placeholder_text = _ "Run a command…",
hexpand = true,
on_changed = function()
self.sendbutton.sensitive = #self.entry.text > 0
self.clearbutton.visible = #self.entry.text > 0
end,
on_activate = function()
self:doactivate()
end,
}
self.clearbutton = Gtk.Button {
icon_name = "tp-clear-symbolic",
margin_start = 12,
css_name = "image",
can_focus = false,
visible = false,
on_clicked = function()
self.entry.text = ""
self:grab()
end,
}
local entrybox = Gtk.Box {
orientation = "HORIZONTAL",
css_name = "entry",
self.entry,
self.clearbutton,
}
local lbox = Gtk.Box {
orientation = "HORIZONTAL",
extra_css_classes = { "linked" },
self.chdirbutton,
self.prefixbutton,
self.menubutton,
entrybox,
self.historybutton,
}
local box = Gtk.Box {
orientation = "HORIZONTAL",
margin_top = 6,
margin_bottom = 6,
margin_start = 6,
margin_end = 6,
spacing = 6,
lbox,
self.sendbutton,
}
self.toolbarview = Adw.ToolbarView {
content = self.scrolledwin,
bottom_bar_style = "RAISED_BORDER",
bottom_bars = { self.searchbar, box },
}
runners[self.toolbarview] = self
end)
function runner:doactivate()
-- Blank lines are allowed for running apps.
if not self.subproc and #self.entry.text == 0 then return end
local text = self.entry.text
self.entry.text = ""
self:send(text)
end
function runner:grab()
if self.tabview.selected_page ~= self.tabpage then return end
self.entry:set_position(-1)
self.entry:grab_focus_without_selecting()
end
function runner:enterfile(path)
assert(path)
local buffer = self.entry.buffer
local text = buffer.text
local position = self.entry:get_position()
local bound, ins = self.entry:get_selection_bounds()
if bound and ins then
position = math.max(bound, ins)
self.entry:select_region(position, position)
end
if position == -1 and not text:match "%s$" then
position = position + buffer:insert_text(position, " ", -1)
end
if path:match "[%s'\"]" then
-- As a nice bonus, the %q format specifier also escapes quotes.
path = ("%q"):format(path)
end
path = path .. " "
position = position + buffer:insert_text(position, path, -1)
self.entry:select_region(position, position)
end
function runner:selectfiles(dofolders)
local pwd = Gio.File.new_for_path(self.pwd)
local filedialog = Gtk.FileDialog {
initial_folder = pwd,
}
Gio.Async.start(function()
local list
if dofolders then
list = filedialog:async_select_multiple_folders(app.active_window)
else
list = filedialog:async_open_multiple(app.active_window)
end
if not list then return end
for i = 1, list.n_items do
-- Gio's API documents say that ListModel's :get_item() method is not available to language bindings and to use :get_object() instead. That's not the case for LuaGObject, which binds :get_item() and returns the object itself instead of a pointer.
local file = list:get_item(i - 1)
-- The files returned by the dialog are sandboxed by Flatpak, but versions with the real paths are needed for the relative path calculation to work correctly.
file = Gio.File.new_for_path(lib.unflatpakize(file))
local path = pwd:get_relative_path(file)
if not path and not dofolders then
-- The ability to query a file's host path is a little dicey in the case of symlinks to files. What works better is querying the parent's path and then just tacking the file's basename at the end.
local dir = file:get_parent()
path = lib.unflatpakize(dir)
path = path .. "/" .. file:get_basename()
elseif not path then
path = lib.unflatpakize(file)
end
self:enterfile(path)
end
end)() --Call wrapped async context.
end
function runner:getpwdlabel()
return lib.fmtdir(self.pwd)
end
function runner:getprefixlabel(short)
assert(self.prefix and type(self.prefix) == "string")
local tooltip = (_ "Clear prefix %q"):format(self.prefix)
if short and #self.prefix > 0 then
return (self.prefix:match("^%S*"))
elseif #self.prefix > 24 then
local prefixslice = utf8.char(utf8.codepoint(self.prefix, 1, 20))
prefixslice = prefixslice:gsub("%s$", "") -- Strip trailing space.
return prefixslice .. "…", tooltip
else
return self.prefix, tooltip
end
end
function runner:gettitle()
local prefix = self:getprefixlabel(true)
local pwd = self:getpwdlabel()
local pretty = pwd
if #prefix > 0 then
pretty = ("(%s) %s"):format(prefix, pwd)
end
local icon
if self.subproc then
icon = "tp-running-symbolic"
end
return self.commandname, pwd, pretty, icon
end
function runner:updatetitle()
if not self.settitle then return end
self:settitle(self:gettitle())
end
function runner:trychdir()
local pwd = Gio.File.new_for_path(self.pwd)
local filedialog = Gtk.FileDialog {
title = _ "Change Directory",
initial_folder = pwd,
}
Gio.Async.start(function()
self.entry.sensitive = false
self.chdirbutton.visible = false
self.prefixbutton.visible = false
self.menubutton.visible = false
self.historybutton.visible = false
self.sendbutton.sensitive = false
local dir = filedialog:async_select_folder(app.active_window)
if dir then
-- guaranteed to be a dir, so there will be a message
self:ensurenewlines(2)
self:chdir(lib.unflatpakize(dir))
end
self:finish()
end)() --Call wrapped async context.
end
function runner:chdir(path)
if self.subproc then return end
self.pwd = path
self:ensurenewlines(1)
local message = _ "New working directory → %s\n"
self:print(message:format(self:getpwdlabel()))
self:inserthistory("cd " .. self:getpwdlabel())
self:updatetitle()
end
function runner:showfolder()
local launcher = Gio.SubprocessLauncher.new { "STDOUT_SILENCE", "STDERR_SILENCE" }
local subproc = launcher:spawnv {
"flatpak-spawn",
"--host",
"--watch-bus",
"/usr/bin/xdg-open",
self.pwd,
}
end
function runner:putstring(text)
local bound, insert
local first, second = self:gettextiters()
-- If the buffer has a selection that extends to the end of the buffer, it needs to be preserved, so mark it.
if self.buffer:get_has_selection() and second:is_end() then
bound = self.buffer:create_mark(nil, first, true)
insert = self.buffer:create_mark(nil, second, true)
end
local enditer = self.buffer:get_end_iter()
self.buffer:insert(enditer, text, -1)
-- If marks were made to preserve selection, then reselect now and delete those marks.
if bound and insert then
first = self.buffer:get_iter_at_mark(bound)
second = self.buffer:get_iter_at_mark(insert)
self:selecttext(first, second)
self.buffer:delete_mark(bound)
self.buffer:delete_mark(insert)
end
end
function runner:flush()
if #self.outputqueue < 1 then return end
if not self.outputqueue:match "[^\n]" then return end
local output = self.outputqueue
local bel = "\u{07}"
if output:match(bel) and self.tabview.selected_page ~= self.tabpage then
self.tabpage.needs_attention = true
end
output = output:gsub(bel, "")
local newlines = self.outputqueue:match "\n*$"
output = output:gsub("\n*$", "")
if output then
self:putstring(output)
end
self.outputqueue = newlines or ""
end
function runner:print(... items)
local text = table.concat(items, " ")
self.outputqueue = self.outputqueue .. text
local outputcount = #self.outputqueue
GLib.timeout_add(10, 120, function()
-- If the output queue length hasn't changed, then flush it.
if #self.outputqueue == outputcount then
self:flush()
end
end)
end
function runner:ensurenewlines(n)
self:flush()
if not n then n = 2 end
local pattern = ""
for i = 1, n do pattern = pattern .. "\n" end
while #self.buffer.text > 0 and self.buffer.text:sub(-n, -1) ~= pattern do
self:putstring "\n"
end
self.outputqueue = self.outputqueue:match "[^\n].*" or ""
end
function runner:handlepipe(pipe, callback, copyafter)
Gio.Async.start(function()
repeat
-- This is technically a broken implementation. Telepipe uses UTF-8 to encode text, so the last byte(s) of the returned array may be an incomplete code point. In practice, this doesn't really matter as the next read happens nearly-instantly because this async context has maximum io_priority and so the broken code point is fixed in the next write.
local bytes = pipe:async_read_bytes(4096)
if not self.closepipes and #bytes.data > 0 then
callback(bytes.data)
else
pipe:async_close()
end
until pipe:is_closed()
-- Only copy to the clipboard if the underlying process wasn't severed from the application.
if copyafter and not self.closepipes then self:copy() end
end)() -- Call wrapped async context.
end
function runner:copy()
if not self.copyqueue then
return
elseif #self.copyqueue > 0 then
local clipboard = Gdk.Display.get_default():get_clipboard()
clipboard:set(GObject.Value(GObject.Type.STRING, self.copyqueue))
self:ensurenewlines(1)
self:putstring(_ "Copied output to clipboard.")
self:print "\n"
else
self:ensurenewlines(1)
self:putstring(_ "Nothing to copy; Clipboard has not been modified.")
self:print "\n"
end
self.copyqueue = nil
end
function runner:finish()
self.forcedexit = nil
self.commandname = nil
self.closepipes = false
self.subproc = nil
self.allowsever = false
self.chdirbutton.visible = true
self.prefixbutton.visible = #self.prefix > 0
self.menubutton.visible = false
self.historybutton.visible = self:gethistory().n_items > 0
self.entry.sensitive = true
self.entry.placeholder_text = _ "Run a command…"
self.sendbutton.icon_name = "tp-run-symbolic"
self.sendbutton.tooltip_text = _ "Run command"
if #self.entry.text > 0 then self.sendbutton.sensitive = true end
self:updatetitle()
self:grab()
end
function runner:waitend(async)
if not self.subproc then return self:finish() end
local subproc = self.subproc
Gio.Async.start(function()
self.subproc:async_wait()
if self.subproc ~= subproc then return end
local status = math.ceil(self.subproc:get_status() / 256)
if self.forcedexit then
self:ensurenewlines(1)
self:putstring(_ "Command was stopped.")
self:print "\n"
elseif status ~= 0 then
self:ensurenewlines(1)
self:putstring((_ "Exited with status code %d."):format(status))
self:print "\n"
end
self:finish()
end)() -- Call wrapped async context.
end
function runner:gethistory()
assert(self.history[self.prefix])
return self.history[self.prefix]
end
function runner:removehistory(command)
local history = self:gethistory()
repeat
local index = history:find(command)
if index >= history.n_items or index < 0 then break end
history:remove(index)
until false
if history.n_items == 0 then
self.historybutton.visible = false
self.historybutton.popover:popdown()
end
end
function runner:inserthistory(command)
local history = self:gethistory()
self:removehistory(command)
history:append(command)
if history.n_items > 0 then
self.historybutton.visible = true
end
end
function runner:switchprefix(prefix)
assert(type(prefix) == "string")
self.prefix = prefix
if not self.history[self.prefix] then
self.history[self.prefix] = Gtk.StringList()
self:inserthistory("prefix " .. prefix)
end
self.histview.model = Gtk.NoSelection {
model = self:gethistory(),
}
local prefixlabel, prefixtooltip = self:getprefixlabel()
self.prefixbutton.label = prefixlabel
self.prefixbutton.tooltip_text = prefixtooltip
self.prefixbutton.visible = #self.prefix > 0
self:updatetitle()
end
-- ListView handlers.
function runner:setupitem(listitem)
local label = Gtk.Label {
extra_css_classes = { "numeric" },
halign = "START",
hexpand = true,
margin_start = 6,
margin_end = 24,
selectable = true,
wrap = true,
wrap_mode = "WORD_CHAR",
}
-- It is normally a better idea to bind signal handlers in the ::bind signal, after an item is bound. However, LuaGObject kind of makes it a bit of a nightmare to unbind signals. Someone should fix that.
local transferbutton = Gtk.Button {
icon_name = "tp-transfer-symbolic",
tooltip_text = _ "Copy to command entry",
valign = "CENTER",
on_clicked = function()
local command = listitem.item.string
self.historybutton.popover:popdown()
self.historybutton.active = false
self.entry.text = command
self:grab()
end,
}
local deletebutton = Gtk.Button {
icon_name = "tp-delete-symbolic",
extra_css_classes = { "destructive-action" },
tooltip_text = _ "Remove from history",
valign = "CENTER",
on_clicked = function()
local command = listitem.item.string
local history = self:gethistory()
local index = history:find(command)
self:removehistory(command)
GLib.timeout_add(20, GLib.PRIORITY_DEFAULT, function()
if index >= history.n_items then
index = history.n_items - 1
end
if index >= 0 then
self.histview:scroll_to(index)
end
end)
end,
}
listitem.child = Gtk.Box {
orientation = "HORIZONTAL",
halign = "FILL",
spacing = 12,
margin_top = 6,
margin_bottom = 6,
margin_start = 6,
margin_end = 6,
label,
Gtk.Box {
orientation = "HORIZONTAL",
spacing = 12,
margin_start = 12,
margin_end = 12,
halign = "END",
transferbutton,
deletebutton,
},
}
end
function runner:binditem(listitem)
-- Because the label is the box's first child, it's easy to find.
listitem.child.children[1].label = listitem.item.string
end
function runner:unbinditem(listitem)
-- Same as in :binditem().
listitem.child.children[1].label = ""
end
function runner:teardownitem(listitem)
-- Everything should just get GC'd at this point, so no need to do anything.
end
-- Execution
function runner:getenv(name)
return self.env[name] or envvars[name] or ""
end
function runner:getexecargs(command)
-- Basic flatpak-spawn parameters
local args = {
"flatpak-spawn",
"--host",
("--directory=%s"):format(self.pwd),
"--watch-bus",
}
-- Environment variables
for name, value in pairs(envvars) do
table.insert(args, ("--env=%s=%s"):format(name, value))
end
for name, value in pairs(self.env) do
table.insert(args, ("--env=%s=%s"):format(name, value))
end
-- The shell command itself
local shell = self:getenv "SHELL"
if #shell == 0 then
-- If not explicitly configured, get the shell from Telepipe's environment.
shell = os.getenv "SHELL" or os.getenv "shell"
end
if #shell == 0 or shell:sub(1, 1) ~= "/" then
-- Shell param needs to be an absolute path, so if it doesn't exist it must be set, otherwise Telepipe cannot execute commands.
shell = "/bin/bash"
end
table.insert(args, shell)
table.insert(args, "-c")
table.insert(args, command)
return args
end
function runner:tryexec(command)
command = lib.strip(command)
if #command == 0 then return end