1// Package cli parses the command line into capture options.
2package cli
3
4import (
5 "errors"
6 "flag"
7 "fmt"
8 "io"
9 "math"
10 "strconv"
11 "strings"
12 "time"
13
14 "github.com/bnema/nefercap/internal/ports"
15)
16
17// Command is the selected subcommand.
18type Command string
19
20const (
21 // AllInOne is the command-less invocation: it stops an active recording,
22 // otherwise opens the selector where Tab switches between shot and rec.
23 // It is never named on the command line and takes no capture flags.
24 AllInOne Command = "all-in-one"
25 // Shot and Rec pick a target with the layer-shell selector; Rec toggles:
26 // while a recording is active it stops that recording instead. Their mode
27 // is fixed: no Tab toggle.
28 Shot Command = "shot"
29 Rec Command = "rec"
30 Stop Command = "stop"
31 Status Command = "status"
32 // Outputs, Screenshot and Record never open the selector. Outputs needs
33 // no -file; Screenshot requires it unless clipboard-only, Record always.
34 Outputs Command = "outputs"
35 Screenshot Command = "screenshot"
36 Record Command = "record"
37)
38
39// DefaultFPS is the recording frame rate when -fps is not given.
40const DefaultFPS = 30
41
42// ErrUsage wraps every command-line usage error.
43var ErrUsage = errors.New("usage error")
44
45// Options is the parsed command line. Video is set only for Record and Rec.
46// Path is optional for Shot and Rec, where an empty Path lets the caller
47// choose one. Clipboard with an empty Path means clipboard only.
48type Options struct {
49 Command Command
50 Output string // output name; empty lets the caller choose
51 Region ports.Region
52 Path string
53 Video ports.VideoSettings
54 Duration time.Duration
55 Debug bool
56 Clipboard bool
57}
58
59// Usage describes the command line.
60func Usage() string {
61 return fmt.Sprintf(`Usage: nefercap [command] [flags]
62
63 (no command) all-in-one: stop an active recording, else open the selector
64 in shot mode; Tab switches shot <-> rec. Takes no flags but
65 -debug; settings come from the config file.
66
67Interactive commands (layer-shell selector over the connected outputs):
68 shot select what to capture and save a PNG; fixed mode
69 rec select what to record; run again while recording to stop it
70 stop stop the active recording
71 status print the recording state
72
73Selector keys and mouse:
74 drag select a region, accepted when the left button is released
75 click capture the whole monitor; after w, the current workspace
76 r back to region selection
77 m choose the whole monitor, Enter confirms
78 w choose the current workspace when known, click or Enter confirms
79 1..9 pick that whole monitor from any overlay
80 g toggle full-monitor center and thirds guides (on by default)
81 Tab switch shot <-> rec (all-in-one only)
82 Escape cancel
83
84Config: $XDG_CONFIG_HOME/nefercap/config (default ~/.config/nefercap/config)
85 selector.grid = off hide guides on startup; G still toggles them
86 screenshot.dir = ~/Pictures/Shots absolute or ~/ path; default XDG Pictures/Screenshots
87 screenshot.output = file+clipboard file (default), file+clipboard or clipboard
88 video.dir = ~/Videos absolute or ~/ path; default XDG Videos
89
90Script commands (never open the selector):
91 outputs list outputs
92 screenshot save a PNG screenshot
93 record record silent video until interrupted or target video length is reached
94
95Other:
96 version print the nefercap version
97
98Flags:
99 -clipboard copy PNG with wl-copy; no file unless -file is given (shot, screenshot)
100 -debug enable debug logging (all commands)
101 -output NAME output name (all except stop, status, outputs)
102 -file PATH new file to write; optional for shot, rec; screenshot requires it unless -clipboard; record requires it
103 -region X,Y,WxH output-local logical region; default is the full output (screenshot, record)
104 -fps N frames per second, 1..%d (rec, record, default %d)
105 -size WxH scaled video size, both even, at most %d each (rec, record, default source size)
106 -duration D encoded video length such as 30s; 0 records until stopped (rec, record)
107`, ports.MaxFPS, DefaultFPS, ports.MaxDimension)
108}
109
110// Parse parses args (without the program name). Help requests print Usage to
111// out and return flag.ErrHelp; other failures wrap ErrUsage.
112func Parse(args []string, out io.Writer) (Options, error) {
113 if out == nil {
114 out = io.Discard
115 }
116 opts := Options{Command: AllInOne}
117 if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
118 switch cmd := Command(args[0]); cmd {
119 case Shot, Rec, Stop, Status, Outputs, Screenshot, Record:
120 opts.Command = cmd
121 args = args[1:]
122 default:
123 return Options{}, usageErr("unknown command %q", args[0])
124 }
125 }
126
127 scripted := opts.Command == Screenshot || opts.Command == Record
128 interactive := opts.Command == Shot || opts.Command == Rec
129 video := opts.Command == Record || opts.Command == Rec
130
131 fs := flag.NewFlagSet("nefercap "+string(opts.Command), flag.ContinueOnError)
132 fs.SetOutput(io.Discard)
133 fs.BoolVar(&opts.Debug, "debug", false, "")
134 var region, size string
135 fps := DefaultFPS
136 if scripted || interactive {
137 fs.StringVar(&opts.Output, "output", "", "")
138 fs.StringVar(&opts.Path, "file", "", "")
139 }
140 if scripted {
141 fs.StringVar(®ion, "region", "", "")
142 }
143 if opts.Command == Shot || opts.Command == Screenshot {
144 fs.BoolVar(&opts.Clipboard, "clipboard", false, "")
145 }
146 if video {
147 fs.IntVar(&fps, "fps", DefaultFPS, "")
148 fs.StringVar(&size, "size", "", "")
149 fs.DurationVar(&opts.Duration, "duration", 0, "")
150 }
151
152 if err := fs.Parse(args); err != nil {
153 if errors.Is(err, flag.ErrHelp) {
154 _, _ = io.WriteString(out, Usage())
155 return Options{}, flag.ErrHelp
156 }
157 if opts.Command == AllInOne {
158 return Options{}, errAllInOneFlags
159 }
160 return Options{}, fmt.Errorf("%w: %w", ErrUsage, err)
161 }
162 if fs.NArg() > 0 {
163 return Options{}, usageErr("unexpected argument %q", fs.Arg(0))
164 }
165 if !scripted && !interactive {
166 return opts, nil
167 }
168
169 if scripted && opts.Path == "" && !opts.Clipboard {
170 return Options{}, usageErr("-file is required")
171 }
172 if interactive || opts.Clipboard {
173 // Set explicitly so "-file ''" is rejected rather than treated as auto.
174 explicit := false
175 fs.Visit(func(f *flag.Flag) { explicit = explicit || f.Name == "file" })
176 if explicit && opts.Path == "" {
177 return Options{}, usageErr("-file must not be empty")
178 }
179 }
180 if region != "" {
181 r, err := parseRegion(region)
182 if err != nil {
183 return Options{}, usageErr("invalid -region %q: %v", region, err)
184 }
185 opts.Region = r
186 }
187 if video {
188 if fps < 1 || fps > ports.MaxFPS {
189 return Options{}, usageErr("invalid -fps %d: must be 1..%d", fps, ports.MaxFPS)
190 }
191 opts.Video.FPS = fps
192 if size != "" {
193 w, h, err := parseSize(size)
194 if err != nil {
195 return Options{}, usageErr("invalid -size %q: %v", size, err)
196 }
197 if w%2 != 0 || h%2 != 0 {
198 return Options{}, usageErr("invalid -size %q: width and height must be even", size)
199 }
200 if w > ports.MaxDimension || h > ports.MaxDimension || w*ports.BytesPerPixel > ports.MaxFrameBytes/h {
201 return Options{}, usageErr("invalid -size %q: exceeds frame limits", size)
202 }
203 opts.Video.Width, opts.Video.Height = w, h
204 }
205 if opts.Duration < 0 {
206 return Options{}, usageErr("invalid -duration %s: must not be negative", opts.Duration)
207 }
208 }
209 return opts, nil
210}
211
212// usageError is a usage error that prints without the generic prefix.
213type usageError string
214
215func (e usageError) Error() string { return string(e) }
216func (e usageError) Is(target error) bool { return target == ErrUsage }
217
218const errAllInOneFlags = usageError("nefercap: all-in-one mode takes no flags except -debug; it reads $XDG_CONFIG_HOME/nefercap/config (default ~/.config/nefercap/config); use shot, rec, screenshot or record for per-run overrides")
219
220func usageErr(format string, a ...any) error {
221 return fmt.Errorf("%w: %s", ErrUsage, fmt.Sprintf(format, a...))
222}
223
224// parseRegion parses "X,Y,WxH" with nonnegative X,Y and positive W,H, all
225// within int32.
226func parseRegion(s string) (ports.Region, error) {
227 xy, wh, ok := strings.Cut(s, "x")
228 parts := strings.Split(xy, ",")
229 if !ok || len(parts) != 3 {
230 return ports.Region{}, errors.New("want X,Y,WxH")
231 }
232 h, err := parseInt(wh, 1)
233 if err != nil {
234 return ports.Region{}, err
235 }
236 x, err := parseInt(parts[0], 0)
237 if err != nil {
238 return ports.Region{}, err
239 }
240 y, err := parseInt(parts[1], 0)
241 if err != nil {
242 return ports.Region{}, err
243 }
244 w, err := parseInt(parts[2], 1)
245 if err != nil {
246 return ports.Region{}, err
247 }
248 if int64(x)+int64(w) > math.MaxInt32 || int64(y)+int64(h) > math.MaxInt32 {
249 return ports.Region{}, errors.New("region exceeds int32 bounds")
250 }
251 return ports.Region{X: x, Y: y, Width: w, Height: h}, nil
252}
253
254func parseSize(s string) (w, h int, err error) {
255 ws, hs, ok := strings.Cut(s, "x")
256 if !ok {
257 return 0, 0, errors.New("want WxH")
258 }
259 if w, err = parseInt(ws, 1); err != nil {
260 return 0, 0, err
261 }
262 if h, err = parseInt(hs, 1); err != nil {
263 return 0, 0, err
264 }
265 return w, h, nil
266}
267
268// parseInt accepts plain decimal digits only, at least min, at most MaxInt32.
269func parseInt(s string, min int) (int, error) {
270 if s == "" || strings.TrimLeft(s, "0123456789") != "" {
271 return 0, fmt.Errorf("%q is not a decimal number", s)
272 }
273 v, err := strconv.ParseInt(s, 10, 32)
274 if err != nil {
275 return 0, fmt.Errorf("%q is out of range", s)
276 }
277 if int(v) < min {
278 return 0, fmt.Errorf("%q must be at least %d", s, min)
279 }
280 return int(v), nil
281}