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
95Flags:
96 -clipboard copy PNG with wl-copy; no file unless -file is given (shot, screenshot)
97 -debug enable debug logging (all commands)
98 -output NAME output name (all except stop, status, outputs)
99 -file PATH new file to write; optional for shot, rec; screenshot requires it unless -clipboard; record requires it
100 -region X,Y,WxH output-local logical region; default is the full output (screenshot, record)
101 -fps N frames per second, 1..%d (rec, record, default %d)
102 -size WxH scaled video size, both even, at most %d each (rec, record, default source size)
103 -duration D encoded video length such as 30s; 0 records until stopped (rec, record)
104`, ports.MaxFPS, DefaultFPS, ports.MaxDimension)
105}
106
107// Parse parses args (without the program name). Help requests print Usage to
108// out and return flag.ErrHelp; other failures wrap ErrUsage.
109func Parse(args []string, out io.Writer) (Options, error) {
110 if out == nil {
111 out = io.Discard
112 }
113 opts := Options{Command: AllInOne}
114 if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
115 switch cmd := Command(args[0]); cmd {
116 case Shot, Rec, Stop, Status, Outputs, Screenshot, Record:
117 opts.Command = cmd
118 args = args[1:]
119 default:
120 return Options{}, usageErr("unknown command %q", args[0])
121 }
122 }
123
124 scripted := opts.Command == Screenshot || opts.Command == Record
125 interactive := opts.Command == Shot || opts.Command == Rec
126 video := opts.Command == Record || opts.Command == Rec
127
128 fs := flag.NewFlagSet("nefercap "+string(opts.Command), flag.ContinueOnError)
129 fs.SetOutput(io.Discard)
130 fs.BoolVar(&opts.Debug, "debug", false, "")
131 var region, size string
132 fps := DefaultFPS
133 if scripted || interactive {
134 fs.StringVar(&opts.Output, "output", "", "")
135 fs.StringVar(&opts.Path, "file", "", "")
136 }
137 if scripted {
138 fs.StringVar(®ion, "region", "", "")
139 }
140 if opts.Command == Shot || opts.Command == Screenshot {
141 fs.BoolVar(&opts.Clipboard, "clipboard", false, "")
142 }
143 if video {
144 fs.IntVar(&fps, "fps", DefaultFPS, "")
145 fs.StringVar(&size, "size", "", "")
146 fs.DurationVar(&opts.Duration, "duration", 0, "")
147 }
148
149 if err := fs.Parse(args); err != nil {
150 if errors.Is(err, flag.ErrHelp) {
151 _, _ = io.WriteString(out, Usage())
152 return Options{}, flag.ErrHelp
153 }
154 if opts.Command == AllInOne {
155 return Options{}, errAllInOneFlags
156 }
157 return Options{}, fmt.Errorf("%w: %w", ErrUsage, err)
158 }
159 if fs.NArg() > 0 {
160 return Options{}, usageErr("unexpected argument %q", fs.Arg(0))
161 }
162 if !scripted && !interactive {
163 return opts, nil
164 }
165
166 if scripted && opts.Path == "" && !opts.Clipboard {
167 return Options{}, usageErr("-file is required")
168 }
169 if interactive || opts.Clipboard {
170 // Set explicitly so "-file ''" is rejected rather than treated as auto.
171 explicit := false
172 fs.Visit(func(f *flag.Flag) { explicit = explicit || f.Name == "file" })
173 if explicit && opts.Path == "" {
174 return Options{}, usageErr("-file must not be empty")
175 }
176 }
177 if region != "" {
178 r, err := parseRegion(region)
179 if err != nil {
180 return Options{}, usageErr("invalid -region %q: %v", region, err)
181 }
182 opts.Region = r
183 }
184 if video {
185 if fps < 1 || fps > ports.MaxFPS {
186 return Options{}, usageErr("invalid -fps %d: must be 1..%d", fps, ports.MaxFPS)
187 }
188 opts.Video.FPS = fps
189 if size != "" {
190 w, h, err := parseSize(size)
191 if err != nil {
192 return Options{}, usageErr("invalid -size %q: %v", size, err)
193 }
194 if w%2 != 0 || h%2 != 0 {
195 return Options{}, usageErr("invalid -size %q: width and height must be even", size)
196 }
197 if w > ports.MaxDimension || h > ports.MaxDimension || w*ports.BytesPerPixel > ports.MaxFrameBytes/h {
198 return Options{}, usageErr("invalid -size %q: exceeds frame limits", size)
199 }
200 opts.Video.Width, opts.Video.Height = w, h
201 }
202 if opts.Duration < 0 {
203 return Options{}, usageErr("invalid -duration %s: must not be negative", opts.Duration)
204 }
205 }
206 return opts, nil
207}
208
209// usageError is a usage error that prints without the generic prefix.
210type usageError string
211
212func (e usageError) Error() string { return string(e) }
213func (e usageError) Is(target error) bool { return target == ErrUsage }
214
215const 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")
216
217func usageErr(format string, a ...any) error {
218 return fmt.Errorf("%w: %s", ErrUsage, fmt.Sprintf(format, a...))
219}
220
221// parseRegion parses "X,Y,WxH" with nonnegative X,Y and positive W,H, all
222// within int32.
223func parseRegion(s string) (ports.Region, error) {
224 xy, wh, ok := strings.Cut(s, "x")
225 parts := strings.Split(xy, ",")
226 if !ok || len(parts) != 3 {
227 return ports.Region{}, errors.New("want X,Y,WxH")
228 }
229 h, err := parseInt(wh, 1)
230 if err != nil {
231 return ports.Region{}, err
232 }
233 x, err := parseInt(parts[0], 0)
234 if err != nil {
235 return ports.Region{}, err
236 }
237 y, err := parseInt(parts[1], 0)
238 if err != nil {
239 return ports.Region{}, err
240 }
241 w, err := parseInt(parts[2], 1)
242 if err != nil {
243 return ports.Region{}, err
244 }
245 if int64(x)+int64(w) > math.MaxInt32 || int64(y)+int64(h) > math.MaxInt32 {
246 return ports.Region{}, errors.New("region exceeds int32 bounds")
247 }
248 return ports.Region{X: x, Y: y, Width: w, Height: h}, nil
249}
250
251func parseSize(s string) (w, h int, err error) {
252 ws, hs, ok := strings.Cut(s, "x")
253 if !ok {
254 return 0, 0, errors.New("want WxH")
255 }
256 if w, err = parseInt(ws, 1); err != nil {
257 return 0, 0, err
258 }
259 if h, err = parseInt(hs, 1); err != nil {
260 return 0, 0, err
261 }
262 return w, h, nil
263}
264
265// parseInt accepts plain decimal digits only, at least min, at most MaxInt32.
266func parseInt(s string, min int) (int, error) {
267 if s == "" || strings.TrimLeft(s, "0123456789") != "" {
268 return 0, fmt.Errorf("%q is not a decimal number", s)
269 }
270 v, err := strconv.ParseInt(s, 10, 32)
271 if err != nil {
272 return 0, fmt.Errorf("%q is out of range", s)
273 }
274 if int(v) < min {
275 return 0, fmt.Errorf("%q must be at least %d", s, min)
276 }
277 return int(v), nil
278}