[Technology] GTK and Rust: "This application can not open files"

If you're writing a simple GTK application in Rust (e.g. with gtk4-rs) and you get this error

GLib-GIO-CRITICAL **: 13:39:45.953: This application can not open files.

and go "But I'm not opening any files, and I didn't ask to?!", you might want to be more explicit about that.

It might be because you're taking command-line arguments intended for other purposes, but gtk4 for Rust's Application::run() 'helpfully' collects any CLI arguments on your behalf without being asked to, even though you did not provide them directly (e.g. with Application::run_with_args()).

So, if you'd like to parse some CLI arguments for other reasons, you'll need to explicitly not provide them to your GTK application, or you'll need to pretend to handle them.

Approach 1: Explicitly ignore arguments

Instead of running your Application `app` like this:

let exit_code : ExitCode = app.run ();

 Be explicit, like this:

let no_args : [&str; 0] = [];
let exit_code : ExitCode = app.run_with_args (&no_args);

Approach 2: Claim to handle files (and then don't!)

let app : Application = Application::builder ()
  .application_id (APP_ID)
  .flags (ApplicationFlags::HANDLES_OPEN)
  .build ();
app.connect_open (open_cb);
let exit_code : ExitCode = app.run ();


pub fn open_cb (_app : &Application, _files : &[File], _hint: &str) { }

This can be unintuitive, because in C, if you don't claim to handle opening of files, and don't explicitly provide argc/argv to g_application_run (), it does not assume you want to handle open.  But C is a bit like approach 1, in that you are explicitly not providing them, since you have to pass 0 and NULL for argc and argv respectively.

Simple C application

This will simply and naively pop-up a window that shows the text provided in argv[1].

#include <gtk/gtk.h>

int activate (GApplication *app, gpointer *user_data) {
  GtkWidget *window = gtk_application_window_new (GTK_APPLICATION (app));
  gtk_window_set_title (GTK_WINDOW (window), "Demo");
  gtk_window_set_default_size (GTK_WINDOW (window), 600, 400);

  GtkWidget *label = gtk_label_new ((char*)user_data);

  gtk_window_set_child (GTK_WINDOW (window), label);

  gtk_window_present (GTK_WINDOW (window));

int main (int argc, char **argv) {
  GtkApplication *app = gtk_application_new ("org.kosmokaryote.test20240415.C", G_APPLICATION_DEFAULT_FLAGS);
  g_signal_connect (G_APPLICATION (app), "activate", G_CALLBACK (activate), argv[1]);
  return g_application_run (G_APPLICATION (app), 0, NULL);

Compiled with:

gcc `pkg-config --cflags --libs gtk4`  main.c   -o main

Corresponding Rust

cargo new test
cargo add gtk4 --features v4_12
use gtk4::{Application,gio::ApplicationFlags, glib::ExitCode, prelude::*, ApplicationWindow, Label};
use std::env::{self, Args};

fn activate (app : &Application) {
    let mut args : Args = env::args ();
    let window : ApplicationWindow = ApplicationWindow::builder ()
        .application (app)
        .title ("Demo")
        .default_width (600)
        .default_height (400)
        .build ();

    let label : Label = match args.nth (1) {
        Some(s) => Label::new (Some (s.as_str ())),
        None => Label::new (None)

    window.set_child (Some(&label));

    window.present ();

fn main() -> ExitCode {
    let app : Application = Application::new (Some ("org.kosmokaryote.test20240415.Rust"), ApplicationFlags::FLAGS_NONE);
    app.connect_activate (activate);
    // app.run ()
    let no_args : [&str; 0] = [];
    app.run_with_args (&no_args)

Keine Kommentare:

Kommentar veröffentlichen

Dieses Blog durchsuchen


#Technology #GNOME gnome gxml fedora bugs linux vala google #General firefox security gsoc GUADEC android bug xml fedora 18 javascript libxml2 programming web blogger encryption fedora 17 gdom git emacs libgdata memory mozilla open source serialisation upgrade web development API Spain containers design evolution fedora 16 fedora 20 fedora 22 fedup file systems friends future glib gnome shell internet luks music performance phone photos php podman preupgrade tablet testing typescript yum #Microblog Network Manager adb apache art automation bash brno catastrophe css data loss debian debugging deja-dup disaster docker emusic errors ext4 facebook fedora 19 gee gir gitlab gitorious gmail gobject google talk google+ gtk html libxml mail microsoft mtp mysql namespaces nautilus nextcloud owncloud picasaweb pitivi ptp python raspberry pi resizing rpm school selinux signal sms speech dispatcher systemd technology texting time management uoguelph usability video web design youtube #Tech Air Canada C Electron Element Empathy Europe GError GNOME 3 GNOME Files Go Google Play Music Grimes IRC Mac OS X Mario Kart Memento Nintendo Nintendo Switch PEAP Selenium Splatoon UI VPN Xiki accessibility advertising ai albums anaconda anonymity apple ask asus eee top automake autonomous automobiles b43 backup battery berlin bit rot broadcom browsers browsing canada canadian english cars chrome clarity comments communication compiler complaints computer computers configuration console constructive criticism cron cropping customisation dataloss dconf debug symbols design patterns desktop summit development discoverability distribution diy dnf documentation drm duplicity e-mail efficiency email english environment estate experimenting ext3 fedora 11 festival file formats firejail flac flatpak forgottotagit freedom friendship fuse galaxy nexus galton gay rights gdb german germany gimp gio gjs gnome software gnome-control-center google assistant google calendar google chrome google hangouts google reader gqe graphviz growth gtest gtg gvfs gvfs metadata hard drive hard drives hardware help hp humour ide identity instagram installation instant messaging integration intel interactivity introspection jabber java java 13 jobs kernel keyboard language language servers languages law learning lenovo letsencrypt libreoffice librpm life livecd liveusb login lsp macbook maintainership mariadb mario matrix memory leaks messaging mounting mouse netflix new zealand node nodelist numix obama oci ogg oggenc oh the humanity open open standards openoffice optimisation org-mode organisation package management packagekit paint shedding parallelism pdo perl pipelight privacy productivity progress progressive web apps pumpkin pwa pyright quality recursion redhat refactoring repairs report rhythmbox rust sandboxes scheduling screenshots self-navigating car shell sleep smartphones software software engineering speed sql ssd synergy tabs test tests themes thesis tracker travel triumf turtles tv tweak twist typing university update usb user experience valadoc video editing volunteering vpnc waf warm wayland weather web apps website wifi wiki wireless wishes work xinput xmpp xorg xpath
Powered by Blogger.