libtmux 0.1.0.alpha.2 → 0.1.0

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,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module LibTmux
6
+ module Internal
7
+ # What the connected tmux daemon can do, in one table. Each gate in the
8
+ # library reads its release floor or affected releases from here, and
9
+ # the root capabilities.json manifest for the docs site is generated
10
+ # from the same records, so behavior and documentation cannot diverge.
11
+ # Quirks that need no caller decision stay out of the table. It sits
12
+ # beside TmuxVersion, which holds the supported minimum.
13
+ module Capabilities
14
+ SCHEMA = "libtmux-capabilities/1"
15
+ PORT = "ruby"
16
+ ERROR = "LibTmux::UnsupportedFeatureError"
17
+
18
+ # A tmux command and the single-letter flags a record depends on.
19
+ Command = Data.define(:command, :flags) do
20
+ def initialize(command:, flags: [])
21
+ super(command: command, flags: flags.freeze)
22
+ end
23
+
24
+ def to_h
25
+ flags.empty? ? {"command" => command} : {"command" => command, "flags" => flags}
26
+ end
27
+ end
28
+
29
+ # Something the library can do from tmux release +since+ on. Below it,
30
+ # or on an +except+ release, +handling+ says what the library does.
31
+ Capability = Data.define(:id, :name, :summary, :since, :handling, :error, :apis, :commands, :except) do
32
+ def initialize(id:, name:, summary:, since:, handling:, apis:, commands:, error: nil, except: [])
33
+ super(id: id, name: name, summary: summary, since: since, handling: handling, error: error,
34
+ apis: apis.freeze, commands: commands.freeze, except: except.freeze)
35
+ end
36
+
37
+ # True when +release+ (an Internal::TmuxVersion::Release) offers it.
38
+ def available?(release)
39
+ release >= Internal::TmuxVersion.parse(since) && !except.include?(release.text)
40
+ end
41
+
42
+ def to_h
43
+ {"id" => id, "name" => name, "summary" => summary, "since" => since,
44
+ "handling" => handling.to_s}.tap do |hash|
45
+ hash["error"] = error if error
46
+ hash["except"] = except unless except.empty?
47
+ hash["apis"] = apis
48
+ hash["commands"] = commands.map(&:to_h)
49
+ end
50
+ end
51
+ end
52
+
53
+ # A defect on exact tmux releases that the library refuses or repairs.
54
+ Workaround = Data.define(:id, :name, :summary, :releases, :handling, :apis, :commands) do
55
+ def initialize(id:, name:, summary:, releases:, handling:, apis:, commands:)
56
+ super(id: id, name: name, summary: summary, releases: releases.freeze, handling: handling,
57
+ apis: apis.freeze, commands: commands.freeze)
58
+ end
59
+
60
+ # True when +release+ is one of the affected releases.
61
+ def applies?(release)
62
+ releases.include?(release.text)
63
+ end
64
+
65
+ def to_h
66
+ {"id" => id, "name" => name, "summary" => summary, "releases" => releases,
67
+ "handling" => handling.to_s, "apis" => apis, "commands" => commands.map(&:to_h)}
68
+ end
69
+ end
70
+
71
+ CAPABILITIES = [
72
+ Capability.new(id: "control-mode", name: "Control mode", since: "3.7", handling: :refuse, error: ERROR,
73
+ summary: "Attach a library-managed control client and stream events.",
74
+ apis: ["LibTmux::Server#open_control", "LibTmux::ControlConnection.open"],
75
+ commands: [Command.new(command: "attach-session")]),
76
+ Capability.new(id: "buffer-delete-named", name: "Named buffer deletion", since: "3.4", handling: :refuse, error: ERROR,
77
+ summary: "Delete one paste buffer by name without risking another buffer.",
78
+ apis: ["LibTmux::Server#delete_buffer", "LibTmux::Server#run"],
79
+ commands: [Command.new(command: "delete-buffer", flags: ["-b"])]),
80
+ Capability.new(id: "buffer-rename", name: "Buffer rename", since: "3.4", handling: :refuse, error: ERROR,
81
+ summary: "Rename a paste buffer without risking another buffer.",
82
+ apis: ["LibTmux::Server#run"],
83
+ commands: [Command.new(command: "set-buffer", flags: ["-b", "-n"])]),
84
+ Capability.new(id: "layout-without-checksum", name: "Layouts without a checksum", since: "3.4",
85
+ handling: :refuse, error: ERROR,
86
+ summary: "Apply a layout string or a named layout that tmux validates before use.",
87
+ apis: ["LibTmux::Window#select_layout", "LibTmux::Server#run"],
88
+ commands: [Command.new(command: "select-layout")]),
89
+ Capability.new(id: "layout-mirrored-main", name: "Mirrored main layouts", since: "3.5",
90
+ handling: :refuse, error: ERROR,
91
+ summary: "Apply main-horizontal-mirrored and main-vertical-mirrored.",
92
+ apis: ["LibTmux::Window#select_layout"],
93
+ commands: [Command.new(command: "select-layout")]),
94
+ Capability.new(id: "layout-json", name: "JSON layout strings", since: "3.8-rc2",
95
+ handling: :refuse, error: ERROR,
96
+ summary: "Apply a layout saved in the JSON form tmux reports.",
97
+ apis: ["LibTmux::Window#select_layout"],
98
+ commands: [Command.new(command: "select-layout")]),
99
+ Capability.new(id: "clipboard-query", name: "Clipboard query", since: "3.6a", handling: :refuse, error: ERROR,
100
+ summary: "Ask an attached client's terminal for its clipboard with refresh-client -l.",
101
+ apis: ["LibTmux::Server#run", "LibTmux::ControlConnection#exchange"],
102
+ commands: [Command.new(command: "refresh-client", flags: ["-l"])])
103
+ ].freeze
104
+
105
+ WORKAROUNDS = [
106
+ Workaround.new(id: "break-pane-misnames-windows", name: "break-pane window naming", releases: ["3.7"],
107
+ handling: :repair,
108
+ summary: "break-pane gets the new window wrong on exactly tmux 3.7; Pane#break_out names it again, and raw break-pane is refused. A nested break-pane is not checked and stops an exact 3.7 daemon: name every one with -n, which avoids the crash while 3.7 still ignores the name, or upgrade to 3.7a.",
109
+ apis: ["LibTmux::Pane#break_out", "LibTmux::Server#run", "LibTmux::ControlConnection#exchange"],
110
+ commands: [Command.new(command: "break-pane")]),
111
+ Workaround.new(id: "split-window-percent-size", name: "split-window -p", releases: ["3.4"],
112
+ handling: :refuse,
113
+ summary: "split-window -p is broken on tmux 3.4; use -l N%.",
114
+ apis: ["LibTmux::Server#run"],
115
+ commands: [Command.new(command: "split-window", flags: ["-p"])]),
116
+ Workaround.new(id: "name-separators-rejected", name: "Colon and dot in names", releases: ["3.7"],
117
+ handling: :refuse,
118
+ summary: "tmux 3.7 rejects ':' and '.' in session and window names; the library refuses them before dispatch, typed or raw.",
119
+ apis: ["LibTmux::Server#new_session", "LibTmux::Session#new_window", "LibTmux::Session#rename",
120
+ "LibTmux::Window#rename", "LibTmux::Server#run"],
121
+ commands: [Command.new(command: "new-session", flags: ["-s"]), Command.new(command: "new-window", flags: ["-n"]),
122
+ Command.new(command: "rename-session"), Command.new(command: "rename-window")])
123
+ ].freeze
124
+
125
+ module_function
126
+
127
+ # The record gating +id+; raises KeyError for an id the registry lacks.
128
+ def capability(id) = CAPABILITIES.find { |entry| entry.id == id } || raise(KeyError, "no capability #{id}")
129
+
130
+ def workaround(id) = WORKAROUNDS.find { |entry| entry.id == id } || raise(KeyError, "no workaround #{id}")
131
+
132
+ # The manifest the docs site reads. The floor is the supported minimum.
133
+ def manifest
134
+ {"schema" => SCHEMA, "port" => PORT, "floor" => {"minimum" => Internal::TmuxVersion::MINIMUM},
135
+ "capabilities" => CAPABILITIES.map(&:to_h), "workarounds" => WORKAROUNDS.map(&:to_h)}
136
+ end
137
+
138
+ # The exact text of capabilities.json: deterministic, with a final newline.
139
+ def manifest_json = "#{JSON.pretty_generate(manifest)}\n"
140
+ end
141
+ end
142
+ end
@@ -48,11 +48,7 @@ module LibTmux
48
48
  private
49
49
 
50
50
  def acquire_server_info(budget)
51
- rows = read(budget, :server, 1, ["display-message", "-p", framing(%w[version pid start_time])], 3)
52
- unless rows.length == 1
53
- raise ProtocolError.new("invalid capture server metadata", delivery: :observed, phase: :capture)
54
- end
55
- version, pid, start_time = rows.first
51
+ version, pid, start_time = read_identity(budget)
56
52
  version = version.dup.force_encoding(Encoding::UTF_8)
57
53
  begin
58
54
  TmuxVersion.require_supported(version)
@@ -66,6 +62,20 @@ module LibTmux
66
62
  capabilities: {metadata: :byte_counted, field_baseline: TmuxVersion::MINIMUM}}
67
63
  end
68
64
 
65
+ # The identity travels in the probe's error text so that no user hook fires.
66
+ def read_identity(budget)
67
+ started_at = monotonic
68
+ remaining = check_budget(budget)
69
+ argv, marker = TmuxVersion.identity_argv(%w[version pid start_time])
70
+ result = @server.run(argv, timeout: remaining, cancel: budget.fetch(:cancel))
71
+ values = TmuxVersion.parse_identity(result, marker, 3)
72
+ budget[:bytes] += result.stderr.bytesize
73
+ budget[:rows] += 1
74
+ budget.fetch(:reads) << {source: :server, attempt: 1, started_at: started_at, finished_at: monotonic,
75
+ bytes: result.stderr.bytesize, rows: 1}
76
+ values
77
+ end
78
+
69
79
  def acquire_rows(budget, attempt, clients)
70
80
  sessions = catalog_read(budget, :session, attempt, ["list-sessions"])
71
81
  if sessions.empty?
@@ -2,6 +2,9 @@
2
2
 
3
3
  require "libtmux/endpoint"
4
4
  require "libtmux/child"
5
+ require "libtmux/process"
6
+ require "libtmux/tmux_version"
7
+ require "libtmux/native_guard"
5
8
 
6
9
  module LibTmux
7
10
  class GuardedBlock
@@ -386,6 +389,11 @@ module LibTmux
386
389
  begin
387
390
  process_wait = Internal::ProcessWait.new
388
391
  prefix = binding.command_prefix
392
+ release = binding.release || Internal::TmuxVersion.connected(prefix) do |probe|
393
+ Internal::ProcessExecutor.new.run(probe, timeout: 5.0)
394
+ end
395
+ Internal::TmuxVersion.require_control(release)
396
+ @release = release
389
397
  @pin = Internal::SocketIdentity.new(Endpoint.new(socket_path: prefix.last, executable: prefix.first))
390
398
  @wake_reader, @wake_writer = pipe
391
399
  input_reader, @input = pipe
@@ -435,6 +443,9 @@ module LibTmux
435
443
  end
436
444
  raise CapacityError.new("control command exceeds its byte limit", phase: :admission) if line.bytesize > @max_command
437
445
 
446
+ # A raw line reaches the daemon like Server#run's argv, so it gets the
447
+ # same literal-command refusals.
448
+ Internal::NativeGuard.check_line(line, @release)
438
449
  deadline, request, result, error = clock + timeout, nil, nil, nil
439
450
  begin
440
451
  Thread.handle_interrupt(Exception => :never) do
@@ -76,7 +76,7 @@ module LibTmux
76
76
  module Internal
77
77
  # Keep the socket inode alive and route through it; PID timestamps can repeat.
78
78
  class SocketIdentity
79
- attr_reader :key
79
+ attr_reader :key, :release
80
80
 
81
81
  def initialize(endpoint)
82
82
  @endpoint = endpoint
@@ -119,6 +119,11 @@ module LibTmux
119
119
  end
120
120
  end
121
121
 
122
+ # Records the daemon release that the server version check read through this route.
123
+ def record_release(release)
124
+ @release = release
125
+ end
126
+
122
127
  def command_prefix
123
128
  @mutex.synchronize do
124
129
  if @closed || Process.pid != @owner_pid
@@ -136,18 +136,27 @@ module LibTmux
136
136
  budget = server.__send__(:operation_budget, timeout, cancel)
137
137
  # Older tmux can access an invalid pointer for a malformed layout header.
138
138
  # tmux 3.8-rc2 and later report and accept saved layouts as JSON.
139
- saved = /\A[0-9a-fA-F]{4},/.match?(value) ||
140
- (value.start_with?("{") && server.__send__(:tmux_release) >= Internal::TmuxVersion.parse("3.8-rc2"))
139
+ saved = /\A[0-9a-fA-F]{4},/.match?(value)
140
+ if !saved && value.start_with?("{")
141
+ json = Internal::Capabilities.capability("layout-json")
142
+ release = server.__send__(:tmux_release)
143
+ unless json.available?(release)
144
+ raise UnsupportedFeatureError.new("JSON layouts require tmux #{json.since} or newer " \
145
+ "(connected version #{release.text})", phase: :admission, delivery: :not_sent)
146
+ end
147
+ saved = true
148
+ end
141
149
  unless LAYOUTS.include?(value) || saved
142
150
  choices = (LAYOUTS + MIRRORED_LAYOUTS).select { |name| name.start_with?(value) }
143
151
  raise ArgumentError, "layout must be a native name or a saved layout" if value.empty? || choices.empty?
144
152
 
145
153
  if choices.any? { |name| MIRRORED_LAYOUTS.include?(name) }
146
154
  release = server.__send__(:tmux_release)
147
- if release < Internal::TmuxVersion.parse("3.5")
155
+ mirrored = Internal::Capabilities.capability("layout-mirrored-main")
156
+ unless mirrored.available?(release)
148
157
  choices &= LAYOUTS
149
158
  if choices.empty?
150
- raise UnsupportedFeatureError.new("mirrored layouts require tmux 3.5+", phase: :admission)
159
+ raise UnsupportedFeatureError.new("mirrored layouts require tmux #{mirrored.since}+", phase: :admission)
151
160
  end
152
161
  end
153
162
  end
@@ -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)