| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | |
| 12 | "github.com/sirupsen/logrus" |
| 13 | "github.com/spf13/cobra" |
| 14 | |
| 15 | "github.com/lima-vm/lima/v2/pkg/hostagent/api/client" |
| 16 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 17 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 18 | "github.com/lima-vm/lima/v2/pkg/store" |
| 19 | ) |
| 20 | |
| 21 | func newScreenshotCommand() *cobra.Command { |
| 22 | cmd := &cobra.Command{ |
| 23 | Use: "screenshot INSTANCE", |
| 24 | Short: "Capture a screenshot of the VM display", |
| 25 | Args: WrapArgsError(cobra.ExactArgs(1)), |
| 26 | RunE: screenshotAction, |
| 27 | GroupID: advancedCommand, |
| 28 | } |
| 29 | cmd.Flags().StringP("output", "o", "", "Output path; extension must be .png or .bmp (default: INSTANCE-screenshot.png)") |
| 30 | return cmd |
| 31 | } |
| 32 | |
| 33 | func screenshotAction(cmd *cobra.Command, args []string) error { |
| 34 | instName := args[0] |
| 35 | |
| 36 | ctx := cmd.Context() |
| 37 | inst, err := store.Inspect(ctx, instName) |
| 38 | if err != nil { |
| 39 | return err |
| 40 | } |
| 41 | if inst.Status != limatype.StatusRunning { |
| 42 | return fmt.Errorf("instance %q is not running (status: %s)", instName, inst.Status) |
| 43 | } |
| 44 | |
| 45 | outputPath, _ := cmd.Flags().GetString("output") |
| 46 | if outputPath == "" { |
| 47 | outputPath = instName + "-screenshot.png" |
| 48 | } |
| 49 | |
| 50 | var format string |
| 51 | switch strings.ToLower(filepath.Ext(outputPath)) { |
| 52 | case ".png": |
| 53 | format = "png" |
| 54 | case ".bmp": |
| 55 | format = "bmp" |
| 56 | default: |
| 57 | return fmt.Errorf("unsupported output extension %q: must be .png or .bmp", filepath.Ext(outputPath)) |
| 58 | } |
| 59 | |
| 60 | haSock := filepath.Join(inst.Dir, filenames.HostAgentSock) |
| 61 | haClient, err := client.NewHostAgentClient(haSock) |
| 62 | if err != nil { |
| 63 | return fmt.Errorf("failed to connect to hostagent: %w", err) |
| 64 | } |
| 65 | |
| 66 | data, err := haClient.Screenshot(ctx, format) |
| 67 | if err != nil { |
| 68 | return fmt.Errorf("screenshot failed: %w", err) |
| 69 | } |
| 70 | |
| 71 | if err := os.WriteFile(outputPath, data, 0o644); err != nil { |
| 72 | return fmt.Errorf("failed to write %q: %w", outputPath, err) |
| 73 | } |
| 74 | logrus.Infof("Screenshot saved to %q (%d bytes)", outputPath, len(data)) |
| 75 | return nil |
| 76 | } |