0

I'm trying to read command line args using clap, then use the parsed results to drive a backened whose progress is displayed by a gtk App (just using the app as the easiest way to display a changing graphical window, maybe there's a better way.)

MRE:

main.rs:

use clap::Parser;
use gtk::{prelude::*, Application};

#[derive(Parser, Debug)]
//#[command(author, version, about, long_about = None)]
struct Example {
    #[arg(long)]
    words: String,
    number: Option<usize>,
}
fn main() {
    let config = Example::parse();
    println!("{:?}", config);
    let app = Application::builder()
        .application_id("org.scratch.Scratch")
        .build();
    gtk::init().expect("GTK init failed");
    app.run();
}

Cargo.toml:

[package]
name = "scratch"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

gtk = "*"
clap = { version = "4.1.4", features = ["derive"] }

and then do:

cargo run --release -- --words Red

When I do this, I get:

Example { words: "Red", number: None }
Unknown option --words

If I comment out the app.run(); call, the program runs as expected.

To me this says that clap is reading the arguments but leaving them in place, and then GTK is panicking because it doesn't know what to do with them. Right? Presumably I either need to tell GTK not to look at the command line or tell clap (or rust) to flush it. How do I do either?

Bonus question: This isn't the only issue I'm having with GTK. What other options do I have? I just need a draw surface I can draw colored rectangles (or better... pixels?) on a loop.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39
  • https://gtk-rs.org/gtk3-rs/stable/latest/docs/gtk/struct.Application.html#method.run_with_args ? https://gtk-rs.org/gtk3-rs/stable/latest/docs/gtk_sys/fn.gtk_init_with_args.html ? look the doc ! – Stargateur Jan 28 '23 at 17:27

1 Answers1

4

Found an answer at setup rust + gtk::Application to ignore --config argument : Just do the run call like:

 let empty: Vec<String> = vec![];
    app.run_with_args(&empty);

instead of app.run().

This explicitly passes no args to the GTK app, rather than passing through the actual command line args used to call your program.

(Maybe this should be closed as a duplicate, but it took me a bunch of time to figure out the MRE before I could find this, so I'm hoping maybe this question will be an easier signpost for the next guy. It was not at all clear when all I had was an "unknown option" error with no obvious source.)

Edward Peters
  • 3,623
  • 2
  • 16
  • 39
  • 1
    Thank you, it was easier for the next guy. This is exactly what I ran into, and this is the only reference to it I could find (or at least, the first reference I found) – russell Feb 10 '23 at 23:56