libtmux 0.1.0.alpha.1 → 0.1.0.alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,354 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "libtmux/errors"
4
+ require "libtmux/capabilities"
5
+
6
+ module LibTmux
7
+ module Internal
8
+ # Refuses literal native commands that a connected tmux release mishandles.
9
+ #
10
+ # The guard reads the argv a caller submits: command separators, option
11
+ # clusters and the abbreviations tmux resolves. Tmux command strings nested
12
+ # in another command (if-shell and run-shell -C bodies, brace blocks) and
13
+ # command-alias contents are not read, so a command this guard refuses must
14
+ # not be nested there. The command table is a superset across releases, so
15
+ # an abbreviation that is ambiguous on any supported release counts as
16
+ # ambiguous.
17
+ module NativeGuard
18
+ COMMANDS = [
19
+ "attach-session", "bind-key", "break-pane", "capture-pane", "choose-buffer",
20
+ "choose-client", "choose-tree", "clear-history", "clear-prompt-history", "clock-mode",
21
+ "command-prompt", "confirm-before", "copy-mode", "customize-mode", "delete-buffer",
22
+ "detach-client", "display-menu", "display-message", "display-popup", "display-panes",
23
+ "find-window", "has-session", "if-shell", "join-pane", "kill-pane", "kill-server",
24
+ "kill-session", "kill-window", "last-pane", "last-window", "link-window", "list-buffers",
25
+ "list-clients", "list-commands", "list-keys", "list-panes", "list-sessions",
26
+ "list-windows", "load-buffer", "lock-client", "lock-server", "lock-session", "move-pane",
27
+ "move-window", "new-pane", "new-session", "new-window", "next-layout", "next-window",
28
+ "paste-buffer", "pipe-pane", "previous-layout", "previous-window", "refresh-client",
29
+ "rename-session", "rename-window", "resize-pane", "resize-window", "respawn-pane",
30
+ "respawn-window", "rotate-window", "run-shell", "save-buffer", "select-layout",
31
+ "select-pane", "select-window", "send-keys", "send-prefix", "server-access",
32
+ "set-buffer", "set-environment", "set-hook", "set-option", "set-window-option",
33
+ "show-buffer", "show-environment", "show-hooks", "show-messages", "show-options",
34
+ "show-prompt-history", "show-window-options", "source-file", "split-window",
35
+ "start-server", "suspend-client", "swap-pane", "swap-window", "switch-client",
36
+ "switch-mode", "unbind-key", "unlink-window", "wait-for"
37
+ ].freeze
38
+ ALIASES = {
39
+ "attach" => "attach-session",
40
+ "bind" => "bind-key",
41
+ "breakp" => "break-pane",
42
+ "capturep" => "capture-pane",
43
+ "clearhist" => "clear-history",
44
+ "clearphist" => "clear-prompt-history",
45
+ "confirm" => "confirm-before",
46
+ "deleteb" => "delete-buffer",
47
+ "detach" => "detach-client",
48
+ "display" => "display-message",
49
+ "displayp" => "display-panes",
50
+ "findw" => "find-window",
51
+ "has" => "has-session",
52
+ "if" => "if-shell",
53
+ "joinp" => "join-pane",
54
+ "killp" => "kill-pane",
55
+ "killw" => "kill-window",
56
+ "last" => "last-window",
57
+ "lastp" => "last-pane",
58
+ "linkw" => "link-window",
59
+ "loadb" => "load-buffer",
60
+ "lock" => "lock-server",
61
+ "lockc" => "lock-client",
62
+ "locks" => "lock-session",
63
+ "ls" => "list-sessions",
64
+ "lsb" => "list-buffers",
65
+ "lsc" => "list-clients",
66
+ "lscm" => "list-commands",
67
+ "lsk" => "list-keys",
68
+ "lsp" => "list-panes",
69
+ "lsw" => "list-windows",
70
+ "menu" => "display-menu",
71
+ "movep" => "move-pane",
72
+ "movew" => "move-window",
73
+ "new" => "new-session",
74
+ "newp" => "new-pane",
75
+ "neww" => "new-window",
76
+ "next" => "next-window",
77
+ "nextl" => "next-layout",
78
+ "pasteb" => "paste-buffer",
79
+ "pipep" => "pipe-pane",
80
+ "popup" => "display-popup",
81
+ "prev" => "previous-window",
82
+ "prevl" => "previous-layout",
83
+ "refresh" => "refresh-client",
84
+ "rename" => "rename-session",
85
+ "renamew" => "rename-window",
86
+ "resizep" => "resize-pane",
87
+ "resizew" => "resize-window",
88
+ "respawnp" => "respawn-pane",
89
+ "respawnw" => "respawn-window",
90
+ "rotatew" => "rotate-window",
91
+ "run" => "run-shell",
92
+ "saveb" => "save-buffer",
93
+ "selectl" => "select-layout",
94
+ "selectp" => "select-pane",
95
+ "selectw" => "select-window",
96
+ "send" => "send-keys",
97
+ "set" => "set-option",
98
+ "setb" => "set-buffer",
99
+ "setenv" => "set-environment",
100
+ "setw" => "set-window-option",
101
+ "show" => "show-options",
102
+ "showb" => "show-buffer",
103
+ "showenv" => "show-environment",
104
+ "showmsgs" => "show-messages",
105
+ "showphist" => "show-prompt-history",
106
+ "showw" => "show-window-options",
107
+ "source" => "source-file",
108
+ "splitw" => "split-window",
109
+ "start" => "start-server",
110
+ "suspendc" => "suspend-client",
111
+ "swapp" => "swap-pane",
112
+ "swapw" => "swap-window",
113
+ "switchc" => "switch-client",
114
+ "unbind" => "unbind-key",
115
+ "unlinkw" => "unlink-window",
116
+ "wait" => "wait-for"
117
+ }.freeze
118
+ OPTIONS = {
119
+ "delete-buffer" => "b:",
120
+ "set-buffer" => "ab:t:n:w",
121
+ "break-pane" => "abdPF:n:s:t:",
122
+ "split-window" => "bc:de:fF:hIl:p:Pt:vZ",
123
+ "select-layout" => "Enopt:",
124
+ "new-session" => "Ac:dDe:EF:f:n:Ps:t:x:Xy:",
125
+ "new-window" => "abc:de:F:kn:PSt:",
126
+ "rename-session" => "t:",
127
+ "rename-window" => "t:",
128
+ "refresh-client" => "A:B:cC:Df:F:lLRSt:U"
129
+ }.freeze
130
+ PRESETS = %w[even-horizontal even-vertical main-horizontal main-vertical tiled].freeze
131
+ private_constant :COMMANDS, :ALIASES, :OPTIONS, :PRESETS
132
+ module_function
133
+
134
+ # +repaired_break+ marks a typed break-pane that renames its window after
135
+ # the move, which exact tmux 3.7 requires.
136
+ def check(argv, release, repaired_break: false)
137
+ check_items(items(argv), release, repaired_break: repaired_break)
138
+ end
139
+
140
+ # Checks one raw command line, as a control connection sends it. A line
141
+ # is a tmux command string, so quotes, backslashes and braces group
142
+ # words the way tmux parses them before the same rules apply.
143
+ def check_line(line, release)
144
+ check_items(parse_line(line), release)
145
+ end
146
+
147
+ def check_items(items, release, repaired_break: false)
148
+ items.each do |item|
149
+ command = resolve(item.first)
150
+ case command
151
+ when "delete-buffer"
152
+ gate = Internal::Capabilities.capability("buffer-delete-named")
153
+ refuse("exact named-buffer deletion", gate.since, release) if !gate.available?(release) && flags(item, command).key?("b")
154
+ when "set-buffer"
155
+ given = flags(item, command)
156
+ gate = Internal::Capabilities.capability("buffer-rename")
157
+ refuse("exact named-buffer rename", gate.since, release) if !gate.available?(release) && given.key?("b") && given.key?("n")
158
+ when "break-pane"
159
+ if Internal::Capabilities.workaround("break-pane-misnames-windows").applies?(release) && !(repaired_break && flags(item, command).key?("n"))
160
+ refuse_raw_break(release)
161
+ end
162
+ when "split-window"
163
+ if Internal::Capabilities.workaround("split-window-percent-size").applies?(release) && flags(item, command).key?("p")
164
+ raise UnsupportedFeatureError.new("split-window -p is broken on tmux #{release.text}; use -l with a percentage",
165
+ phase: :admission, delivery: :not_sent)
166
+ end
167
+ when "select-layout"
168
+ check_layout(item, command, release)
169
+ when "new-session"
170
+ given = flags(item, command)
171
+ check_name(given["s"], release)
172
+ check_name(given["n"], release)
173
+ when "new-window"
174
+ check_name(flags(item, command)["n"], release)
175
+ when "rename-session", "rename-window"
176
+ check_name(operands(item, command).first, release)
177
+ when "refresh-client"
178
+ # tmux 3.3a stops when it asks an attached xterm-256color or
179
+ # tmux-256color terminal for its clipboard, and 3.4 through 3.6
180
+ # stop when that client leaves before its terminal answers.
181
+ gate = Internal::Capabilities.capability("clipboard-query")
182
+ refuse("refresh-client -l", gate.since, release) if !gate.available?(release) && flags(item, command).key?("l")
183
+ end
184
+ end
185
+ nil
186
+ end
187
+
188
+ # tmux joins arguments into commands: a bare ";" or a trailing ";" ends
189
+ # one, and a trailing "\\;" is a literal semicolon.
190
+ def items(argv)
191
+ result = [[]]
192
+ argv.each do |argument|
193
+ if argument == ";"
194
+ result << []
195
+ elsif argument.end_with?(";") && !argument.end_with?("\\;")
196
+ result.last << argument.delete_suffix(";") unless argument == ";"
197
+ result << []
198
+ else
199
+ result.last << argument
200
+ end
201
+ end
202
+ result.reject(&:empty?)
203
+ end
204
+
205
+ # Splits a command string into commands of words. A bare or trailing
206
+ # unquoted ";" ends a command, a backslash makes the next character
207
+ # literal, quotes group words, and a brace block stays one word.
208
+ def parse_line(line)
209
+ result = [[]]
210
+ word = quote = nil
211
+ depth = 0
212
+ chars = line.each_char.to_a
213
+ index = 0
214
+ finish = lambda do
215
+ result.last << word if word
216
+ word = nil
217
+ end
218
+ while index < chars.length
219
+ char = chars[index]
220
+ if depth.positive?
221
+ word << char
222
+ depth += 1 if char == "{"
223
+ depth -= 1 if char == "}"
224
+ elsif quote == "'"
225
+ char == "'" ? quote = nil : word << char
226
+ elsif quote == '"'
227
+ if char == '"'
228
+ quote = nil
229
+ elsif char == "\\" && index + 1 < chars.length
230
+ index += 1
231
+ word << chars[index]
232
+ else
233
+ word << char
234
+ end
235
+ else
236
+ case char
237
+ when /\s/ then finish.call
238
+ when "'", '"'
239
+ word ||= +""
240
+ quote = char
241
+ when "\\"
242
+ word ||= +""
243
+ index += 1
244
+ word << chars[index] if index < chars.length
245
+ when ";"
246
+ finish.call
247
+ result << []
248
+ when "{"
249
+ if word.nil?
250
+ word = +"{"
251
+ depth = 1
252
+ else
253
+ word << char
254
+ end
255
+ when "#"
256
+ break if word.nil?
257
+
258
+ word << char
259
+ else
260
+ (word ||= +"") << char
261
+ end
262
+ end
263
+ index += 1
264
+ end
265
+ finish.call
266
+ result.reject(&:empty?)
267
+ end
268
+
269
+ def resolve(name)
270
+ return name if COMMANDS.include?(name)
271
+ return ALIASES.fetch(name) if ALIASES.key?(name)
272
+
273
+ matches = COMMANDS.select { |command| command.start_with?(name) }
274
+ matches.length == 1 ? matches.first : nil
275
+ end
276
+
277
+ def flags(item, command)
278
+ spec = OPTIONS.fetch(command)
279
+ given = {}
280
+ rest = item.drop(1)
281
+ until rest.empty?
282
+ token = rest.shift
283
+ break if token == "--" || !token.start_with?("-") || token == "-"
284
+
285
+ token[1..].each_char.with_index(1) do |flag, index|
286
+ position = spec.index(flag)
287
+ next unless position
288
+
289
+ if spec[position + 1] == ":"
290
+ given[flag] = token[(index + 1)..].empty? ? rest.shift : token[(index + 1)..]
291
+ break
292
+ end
293
+ given[flag] = true
294
+ end
295
+ end
296
+ given
297
+ end
298
+
299
+ def operands(item, command)
300
+ spec = OPTIONS.fetch(command)
301
+ rest = item.drop(1)
302
+ until rest.empty?
303
+ token = rest.first
304
+ return rest.drop(1) if token == "--"
305
+ return rest if !token.start_with?("-") || token == "-"
306
+
307
+ rest.shift
308
+ token[1..].each_char.with_index(1) do |flag, index|
309
+ position = spec.index(flag)
310
+ next unless position && spec[position + 1] == ":"
311
+
312
+ rest.shift if token[(index + 1)..].empty?
313
+ break
314
+ end
315
+ end
316
+ rest
317
+ end
318
+
319
+ # tmux 3.3a faults on a header that is not four hex digits and a comma, so
320
+ # only checksummed layouts and built-in names pass before 3.4.
321
+ def check_layout(item, command, release)
322
+ return if Internal::Capabilities.capability("layout-without-checksum").available?(release)
323
+
324
+ given = flags(item, command)
325
+ return if given.key?("E") || given.key?("n") || given.key?("p")
326
+
327
+ layout = operands(item, command).first
328
+ return if layout.nil? || layout.match?(/\A[0-9a-fA-F]{4},[\s\S]+/)
329
+ return if !given.key?("o") && PRESETS.count { |name| name.start_with?(layout) } == 1
330
+
331
+ raise UnsupportedFeatureError.new("an invalid layout is refused before dispatch on tmux #{release.text}; " \
332
+ "use a unique built-in layout name or a serialized layout", phase: :admission, delivery: :not_sent)
333
+ end
334
+
335
+ def check_name(name, release)
336
+ return unless name.is_a?(String) && name.match?(/[:.]/)
337
+ return unless Internal::Capabilities.workaround("name-separators-rejected").applies?(release)
338
+
339
+ raise UnsupportedFeatureError.new("tmux 3.7 rejects ':' and '.' in session and window names",
340
+ phase: :admission, delivery: :not_sent)
341
+ end
342
+
343
+ def refuse(what, floor, release)
344
+ raise UnsupportedFeatureError.new("#{what} requires tmux #{floor} or newer (connected version #{release.text})",
345
+ phase: :admission, delivery: :not_sent)
346
+ end
347
+
348
+ def refuse_raw_break(release)
349
+ raise UnsupportedFeatureError.new("break-pane is unsafe on tmux #{release.text}; use Pane#break_out, " \
350
+ "which names the window, or upgrade to 3.7a", phase: :admission, delivery: :not_sent)
351
+ end
352
+ end
353
+ end
354
+ end
@@ -345,10 +345,30 @@ module LibTmux
345
345
  reposition("move-pane", other, direction: direction, before: before, timeout: timeout, cancel: cancel)
346
346
  end
347
347
 
348
+ # Exact tmux 3.7 ignores -n on break-pane and crashes without it, so the
349
+ # name is applied again afterwards. Before 3.6 a sole pane's break prints
350
+ # no ID, so the window is read back from the pane.
348
351
  def break_out(session:, name:, timeout: 5.0, cancel: nil)
352
+ budget = server.__send__(:operation_budget, timeout, cancel)
349
353
  destination = server.__send__(:target, session, :session)
350
- server.__send__(:create_entity, :window, ["break-pane", "-d", "-P", "-F", server.__send__(:id_format, :window),
351
- "-s", target, "-t", "#{destination}:", "-n", server.__send__(:literal_name, name)], timeout: timeout, cancel: cancel)
354
+ literal = server.__send__(:literal_name, name)
355
+ repaired = Internal::Capabilities.workaround("break-pane-misnames-windows").applies?(server.__send__(:tmux_release))
356
+ result = server.__send__(:execute_typed, ["break-pane", "-d", "-P", "-F", server.__send__(:id_format, :window),
357
+ "-s", target, "-t", "#{destination}:", "-n", literal], repaired_break: repaired, **budget.options)
358
+ id = result.stdout.empty? ? nil : result.stdout
359
+ if id.nil?
360
+ located = server.__send__(:execute_typed, ["list-panes", "-t", target, "-F", server.__send__(:id_format, :window)],
361
+ **budget.options)
362
+ id = located.stdout.lines.first.to_s
363
+ end
364
+ rows = Internal::Metadata.decode(id, fields: 1, max_rows: 1)
365
+ raise ProtocolError.new("tmux did not return the broken-out window ID", delivery: :observed, phase: :decode) unless rows.length == 1
366
+
367
+ window = server.__send__(:build_entity, :window, rows.first.first)
368
+ if repaired
369
+ server.__send__(:execute_typed, ["rename-window", "-t", window.id, "--", literal], **budget.options)
370
+ end
371
+ window
352
372
  end
353
373
 
354
374
  def respawn(command:, kill: false, cwd: nil, environment: {}, timeout: 5.0, cancel: nil)
data/lib/libtmux/owned.rb CHANGED
@@ -49,6 +49,9 @@ module LibTmux
49
49
  if @endpoint.socket_path.bytesize > 103
50
50
  raise UnsupportedFeatureError.new("owned Unix socket path exceeds the platform limit", phase: :startup)
51
51
  end
52
+ Internal::TmuxVersion.executable(@endpoint.executable) do |argv|
53
+ ProcessExecutor.new.run(argv, timeout: deadline - clock, cancel: cancel)
54
+ end
52
55
  @readiness = SocketReadiness.new(@directory)
53
56
  @child = OwnedChild.new
54
57
  pid = nil
@@ -104,14 +104,17 @@ module LibTmux
104
104
  @drain_timeout = drain_timeout
105
105
  end
106
106
 
107
- def run(argv, input: "".b, env: {}, timeout: 5.0, cancel: nil)
108
- Execution.new(argv, input, env, timeout, cancel, @limits, @cleanup_timeout, @drain_timeout).call
107
+ # +discard_stdout+ gives the child the null device for stdout, so the
108
+ # result reports no stdout and the call does not wait for a descriptor
109
+ # that a daemon older than tmux 3.2 keeps open after its client exits.
110
+ def run(argv, input: "".b, env: {}, timeout: 5.0, cancel: nil, discard_stdout: false)
111
+ Execution.new(argv, input, env, timeout, cancel, @limits, @cleanup_timeout, @drain_timeout, discard_stdout).call
109
112
  end
110
113
 
111
114
  class Execution
112
115
  CHUNK_BYTES = 16_384
113
116
 
114
- def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain_timeout)
117
+ def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain_timeout, discard_stdout)
115
118
  @started = monotonic
116
119
  unless argv.is_a?(Array) && !argv.empty? && argv.all? { |argument| argument.is_a?(String) && !argument.include?("\0") }
117
120
  raise ArgumentError, "argv must contain strings without NUL"
@@ -130,6 +133,7 @@ module LibTmux
130
133
  @limits = limits
131
134
  @cleanup_timeout = cleanup_timeout
132
135
  @drain_timeout = drain_timeout
136
+ @discard_stdout = discard_stdout
133
137
  @process_wait = ProcessWait.new
134
138
  @owned = []
135
139
  @buffers = {stdout: +"".b, stderr: +"".b}
@@ -180,7 +184,12 @@ module LibTmux
180
184
 
181
185
  def spawn
182
186
  child_input, @input_writer = pipe
183
- @output_reader, child_output = pipe
187
+ if @discard_stdout
188
+ child_output = File.open(File::NULL, "wb")
189
+ @owned << child_output
190
+ else
191
+ @output_reader, child_output = pipe
192
+ end
184
193
  @error_reader, child_error = pipe
185
194
  @child = OwnedChild.new(@process_wait)
186
195
  @exit_reader = @child.reader
@@ -198,7 +207,8 @@ module LibTmux
198
207
  end
199
208
 
200
209
  def communicate
201
- reading = {@output_reader => :stdout, @error_reader => :stderr}
210
+ reading = {@error_reader => :stderr}
211
+ reading[@output_reader] = :stdout if @output_reader
202
212
  loop do
203
213
  return result if @status && reading.empty?
204
214
 
@@ -4,9 +4,102 @@ require_relative "endpoint"
4
4
  require_relative "process"
5
5
  require_relative "metadata"
6
6
  require_relative "entity"
7
+ require_relative "tmux_version"
8
+ require_relative "native_guard"
7
9
 
8
10
  module LibTmux
9
11
  # Connects to an existing endpoint. Closing retires clients, never the daemon.
12
+ #
13
+ # A server is bound to one tmux executable and one Unix socket. It keeps a
14
+ # private link to the socket it bound, so commands never reach a different
15
+ # daemon that later takes over the same path. An {EntityRef} is valid only on
16
+ # the server that issued it; another server raises {TargetNotFoundError}.
17
+ #
18
+ # Methods that run a tmux command take `timeout:` and `cancel:`. The typed
19
+ # methods raise {CommandError} when tmux rejects a command, and a listing
20
+ # that fails raises, so an empty array means tmux answered with nothing to
21
+ # list. {#run} and {#run_group} answer their result whatever tmux's exit
22
+ # status. `max_requests:` bounds concurrent commands and `max_controls:`
23
+ # bounds control connections; a call past either limit raises
24
+ # {CapacityError} instead of waiting. After {#close} the server refuses new
25
+ # requests with {ClosedError}, and {#diagnostics} still answers. A forked
26
+ # child can close an inherited server but cannot use it.
27
+ #
28
+ # # What is on here
29
+ #
30
+ # The methods fall into the groups below. A {Session}, {Window}, or {Pane}
31
+ # carries the operations on that one thing.
32
+ #
33
+ # **Connecting.** {#initialize Server.new} and {Server.open} bind an endpoint
34
+ # that already exists; {Server.open} with a block closes the server when the
35
+ # block ends. {Server.start} starts a private daemon instead, creates no
36
+ # session, and owns the daemon's exit. {#endpoint} answers the {Endpoint}
37
+ # and {#owned?} says whether this server started its daemon. {#diagnostics}
38
+ # reports the request and control slots in use, and the limits. {#close}
39
+ # retires the server's clients; on an owned server it also stops the daemon.
40
+ # {#open_control} opens a {ControlConnection} to a session.
41
+ #
42
+ # **Finding one thing.** {#session}, {#window}, {#pane}, and {#window_link}
43
+ # wrap an {EntityRef} in a handle without running a command. Take the ref
44
+ # from a handle or a snapshot record. A ref of the wrong kind raises
45
+ # {TargetNotFoundError}; one whose entity has gone fails at its first
46
+ # command.
47
+ #
48
+ # **Listing everything.** {#list_sessions}, {#list_windows}, and
49
+ # {#list_panes} answer frozen arrays of handles in numeric ID order, and
50
+ # {#list_window_links} answers every {WindowLink}. {#list_clients} answers
51
+ # one hash per client. {#snapshot} captures the session, window, and pane
52
+ # tree, and clients with `clients: true`, as one validated {Snapshot}.
53
+ #
54
+ # **Querying things and getting around.** {#search_panes} filters the panes
55
+ # of a snapshot with `where:`, a hash of criteria or a {FilterExpr}, and
56
+ # answers a {Selection}; {#explain_panes} answers the plan for a query
57
+ # without running tmux. A {Selection} narrows with {Selection#where},
58
+ # {Selection#select}, {Selection#filter}, and {Selection#reject}, tests with
59
+ # {Selection#exists?}, and takes a single match with {Selection#one}, which
60
+ # raises {NoMatchError} or {MultipleMatchesError} otherwise, or
61
+ # {Selection#one_or_nil}. Build and compose criteria with
62
+ # {FilterExpr.build}, {FilterExpr#and}, {FilterExpr#or}, {FilterExpr#not},
63
+ # and {FilterExpr.from_json}.
64
+ #
65
+ # A {Snapshot} answers relational questions without another command:
66
+ # {Snapshot#sessions}, {Snapshot#windows}, {Snapshot#panes}, and
67
+ # {Snapshot#clients}. Its records follow relations by name: a
68
+ # {SessionSnapshot} reaches `windows`, `panes`, and `current_window`, a
69
+ # {WindowSnapshot} reaches `panes` and `active_pane`, and a {PaneSnapshot}
70
+ # reaches its `window`. {Entity#snapshot} reads one handle back as a record,
71
+ # and {CapturedRecord#ref} with {#session}, {#window}, or {#pane} turns a
72
+ # record into a handle. Live handles go down one command at a time with
73
+ # {Session#list_windows}, {Session#list_panes}, and {Window#list_panes}, and
74
+ # back up with {Entity#server}.
75
+ #
76
+ # **Changing things.** {#new_session} starts a detached session running
77
+ # `command:`, an argv array rather than a shell string, and answers the
78
+ # {Session} or, with `receipt: true`, a {CreationReceipt}. {#kill} stops the
79
+ # tmux server, which {#close} does only for an owned server.
80
+ # {#switch_client} points the client named by `client:` at a session.
81
+ #
82
+ # **Options and hooks.** {#options} answers {Options} at server scope, or at
83
+ # the global session or window scope. {#hooks} answers {Hooks} at the global
84
+ # session or window scope. {#environment}, {#set_environment}, and
85
+ # {#unset_environment} read, set, and unset one variable in the server's
86
+ # global environment.
87
+ #
88
+ # **Everything else tmux keeps.** Paste buffers: {#list_buffers},
89
+ # {#read_buffer}, {#write_buffer}, and {#delete_buffer}. {#source_file}
90
+ # loads a configuration file. {#display} expands a tmux format; the argument
91
+ # is a format, not literal text. {#wait_for} waits on, signals, locks, or
92
+ # unlocks a channel, as `action:` says.
93
+ #
94
+ # **Things that need a terminal.** {#attach} runs an interactive client on a
95
+ # TTY the caller supplies and keeps, blocks until that client exits, and
96
+ # answers a {TerminalResult}. Cancelling detaches the client and does not
97
+ # stop pane commands.
98
+ #
99
+ # Anything else tmux can do is reachable through {#run}, which runs one
100
+ # command from an argv array and keeps tmux's separators and format
101
+ # semantics, or {#run_group}, which runs several in one tmux invocation. A
102
+ # {GroupResult} cannot attribute the client's final status to a single step.
10
103
  class Server
11
104
  attr_reader :endpoint
12
105
 
@@ -42,7 +135,8 @@ module LibTmux
42
135
  result
43
136
  end
44
137
 
45
- def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "tmux", max_requests: 32, max_controls: 4, close_timeout: 0.5)
138
+ def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "tmux", max_requests: 32, max_controls: 4, close_timeout: 0.5,
139
+ version_timeout: 5.0)
46
140
  if endpoint && (socket_path || socket_name || executable != "tmux")
47
141
  raise ArgumentError, "endpoint cannot be combined with socket or executable options"
48
142
  end
@@ -57,6 +151,10 @@ module LibTmux
57
151
  raise ArgumentError, "close_timeout must be positive and finite"
58
152
  end
59
153
 
154
+ unless version_timeout.is_a?(Numeric) && version_timeout.finite? && version_timeout.positive?
155
+ raise ArgumentError, "version_timeout must be positive and finite"
156
+ end
157
+
60
158
  @endpoint = endpoint || Endpoint.new(socket_path: socket_path, socket_name: socket_name, executable: executable)
61
159
  @owner_pid = Process.pid
62
160
  @max_requests = max_requests
@@ -69,19 +167,30 @@ module LibTmux
69
167
  @closed = false
70
168
  @executor = Internal::ProcessExecutor.new
71
169
  @pin = Internal::SocketIdentity.new(@endpoint)
170
+ begin
171
+ @release = Internal::TmuxVersion.connected(@pin.command_prefix) { |argv| @executor.run(argv, timeout: version_timeout, discard_stdout: true) }
172
+ @pin.record_release(@release)
173
+ argv, marker = Internal::TmuxVersion.fence_check_argv
174
+ Internal::TmuxVersion.verify_fence(@executor.run(@pin.command_prefix + argv, timeout: version_timeout), marker)
175
+ rescue Exception
176
+ @pin.close
177
+ raise
178
+ end
179
+ end
180
+
181
+ # The daemon's release text, such as "3.7d" or "next-3.9".
182
+ def tmux_version
183
+ @release.text
184
+ end
185
+
186
+ # True when the checked daemon accepts control clients (tmux 3.7 and newer).
187
+ def supports_control?
188
+ Internal::Capabilities.capability("control-mode").available?(@release)
72
189
  end
73
190
 
74
191
  # Raw tmux arguments retain tmux's separators and format semantics.
75
192
  def run(argv, input: "".b, timeout: 5.0, cancel: nil)
76
- ensure_owner
77
- started = monotonic
78
- validate_argv(argv)
79
- raise ArgumentError, "raw commands cannot override endpoint flags" if argv.first.start_with?("-")
80
- raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite?
81
- perform_request(cancel: cancel) do |view|
82
- @executor.run(@pin.command_prefix + argv, input: input,
83
- timeout: timeout - (monotonic - started), cancel: view)
84
- end
193
+ dispatch(argv, input: input, timeout: timeout, cancel: cancel)
85
194
  end
86
195
 
87
196
  def close
@@ -283,6 +392,10 @@ module LibTmux
283
392
  end
284
393
  private_constant :CancellationView
285
394
 
395
+ def tmux_release
396
+ with_bound_endpoint { |_endpoint, _pin, release| release }
397
+ end
398
+
286
399
  def monotonic
287
400
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
288
401
  end
@@ -298,7 +411,7 @@ module LibTmux
298
411
  ensure_owner
299
412
  @mutex.synchronize do
300
413
  ensure_open
301
- yield @endpoint, @pin
414
+ yield @endpoint, @pin, @release
302
415
  end
303
416
  end
304
417
 
@@ -390,8 +503,25 @@ module LibTmux
390
503
  end
391
504
  end
392
505
 
393
- def execute_typed(arguments, **options)
394
- result = run(encode_arguments(arguments), **options)
506
+ # Library operations that repair exact tmux 3.7's break-pane say so here.
507
+ def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false)
508
+ ensure_owner
509
+ started = monotonic
510
+ validate_argv(argv)
511
+ raise ArgumentError, "raw commands cannot override endpoint flags" if argv.first.start_with?("-")
512
+ raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite?
513
+ Internal::NativeGuard.check(argv, @release, repaired_break: repaired_break)
514
+ perform_request(cancel: cancel) do |view|
515
+ fence, marker = Internal::TmuxVersion.fence(@release)
516
+ result = @executor.run(@pin.command_prefix + fence + argv, input: input,
517
+ timeout: timeout - (monotonic - started), cancel: view)
518
+ Internal::TmuxVersion.check_fence(result, marker, @release)
519
+ end
520
+ end
521
+
522
+ def execute_typed(arguments, repaired_break: false, **options)
523
+ arguments = encode_arguments(arguments)
524
+ result = repaired_break ? dispatch(arguments, repaired_break: true, **options) : run(arguments, **options)
395
525
  raise CommandError.new(result: result, phase: :command) unless result.success?
396
526
 
397
527
  result
@@ -407,6 +537,12 @@ module LibTmux
407
537
  unless name.is_a?(String) && !name.empty? && !name.include?("\0")
408
538
  raise ArgumentError, "name must be a nonempty String without NUL"
409
539
  end
540
+ # Exact tmux 3.7 rejects these in session and window names, so the
541
+ # refusal comes before any effect.
542
+ if Internal::Capabilities.workaround("name-separators-rejected").applies?(@release) && name.match?(/[:.]/)
543
+ raise UnsupportedFeatureError.new("tmux 3.7 rejects ':' and '.' in session and window names",
544
+ phase: :admission, delivery: :not_sent)
545
+ end
410
546
  name.gsub("#", "##")
411
547
  end
412
548