1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::File;
use crate::InputStream;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem;
use std::mem::transmute;

glib::wrapper! {
    /// [`ApplicationCommandLine`][crate::ApplicationCommandLine] represents a command-line invocation of
    /// an application. It is created by [`Application`][crate::Application] and emitted
    /// in the `signal::Application::command-line` signal and virtual function.
    ///
    /// The class contains the list of arguments that the program was invoked
    /// with. It is also possible to query if the commandline invocation was
    /// local (ie: the current process is running in direct response to the
    /// invocation) or remote (ie: some other process forwarded the
    /// commandline to this process).
    ///
    /// The GApplicationCommandLine object can provide the `argc` and `argv`
    /// parameters for use with the `GOptionContext` command-line parsing API,
    /// with the [`ApplicationCommandLineExt::arguments()`][crate::prelude::ApplicationCommandLineExt::arguments()] function. See
    /// [gapplication-example-cmdline3.c][gapplication-example-cmdline3]
    /// for an example.
    ///
    /// The exit status of the originally-invoked process may be set and
    /// messages can be printed to stdout or stderr of that process. The
    /// lifecycle of the originally-invoked process is tied to the lifecycle
    /// of this object (ie: the process exits when the last reference is
    /// dropped).
    ///
    /// The main use for [`ApplicationCommandLine`][crate::ApplicationCommandLine] (and the
    /// `signal::Application::command-line` signal) is 'Emacs server' like use cases:
    /// You can set the `EDITOR` environment variable to have e.g. git use
    /// your favourite editor to edit commit messages, and if you already
    /// have an instance of the editor running, the editing will happen
    /// in the running instance, instead of opening a new one. An important
    /// aspect of this use case is that the process that gets started by git
    /// does not return until the editing is done.
    ///
    /// Normally, the commandline is completely handled in the
    /// `signal::Application::command-line` handler. The launching instance exits
    /// once the signal handler in the primary instance has returned, and
    /// the return value of the signal handler becomes the exit status
    /// of the launching instance.
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    /// static int
    /// command_line (GApplication            *application,
    ///               GApplicationCommandLine *cmdline)
    /// {
    ///   gchar **argv;
    ///   gint argc;
    ///   gint i;
    ///
    ///   argv = g_application_command_line_get_arguments (cmdline, &argc);
    ///
    ///   g_application_command_line_print (cmdline,
    ///                                     "This text is written back\n"
    ///                                     "to stdout of the caller\n");
    ///
    ///   for (i = 0; i < argc; i++)
    ///     g_print ("argument %d: %s\n", i, argv[i]);
    ///
    ///   g_strfreev (argv);
    ///
    ///   return 0;
    /// }
    /// ```
    /// The complete example can be found here:
    /// [gapplication-example-cmdline.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline.c)
    ///
    /// In more complicated cases, the handling of the commandline can be
    /// split between the launcher and the primary instance.
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    /// static gboolean
    ///  test_local_cmdline (GApplication   *application,
    ///                      gchar        ***arguments,
    ///                      gint           *exit_status)
    /// {
    ///   gint i, j;
    ///   gchar **argv;
    ///
    ///   argv = *arguments;
    ///
    ///   if (argv[0] == NULL)
    ///     {
    ///       *exit_status = 0;
    ///       return FALSE;
    ///     }
    ///
    ///   i = 1;
    ///   while (argv[i])
    ///     {
    ///       if (g_str_has_prefix (argv[i], "--local-"))
    ///         {
    ///           g_print ("handling argument %s locally\n", argv[i]);
    ///           g_free (argv[i]);
    ///           for (j = i; argv[j]; j++)
    ///             argv[j] = argv[j + 1];
    ///         }
    ///       else
    ///         {
    ///           g_print ("not handling argument %s locally\n", argv[i]);
    ///           i++;
    ///         }
    ///     }
    ///
    ///   *exit_status = 0;
    ///
    ///   return FALSE;
    /// }
    ///
    /// static void
    /// test_application_class_init (TestApplicationClass *class)
    /// {
    ///   G_APPLICATION_CLASS (class)->local_command_line = test_local_cmdline;
    ///
    ///   ...
    /// }
    /// ```
    /// In this example of split commandline handling, options that start
    /// with `--local-` are handled locally, all other options are passed
    /// to the `signal::Application::command-line` handler which runs in the primary
    /// instance.
    ///
    /// The complete example can be found here:
    /// [gapplication-example-cmdline2.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline2.c)
    ///
    /// If handling the commandline requires a lot of work, it may
    /// be better to defer it.
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    /// static gboolean
    /// my_cmdline_handler (gpointer data)
    /// {
    ///   GApplicationCommandLine *cmdline = data;
    ///
    ///   // do the heavy lifting in an idle
    ///
    ///   g_application_command_line_set_exit_status (cmdline, 0);
    ///   g_object_unref (cmdline); // this releases the application
    ///
    ///   return G_SOURCE_REMOVE;
    /// }
    ///
    /// static int
    /// command_line (GApplication            *application,
    ///               GApplicationCommandLine *cmdline)
    /// {
    ///   // keep the application running until we are done with this commandline
    ///   g_application_hold (application);
    ///
    ///   g_object_set_data_full (G_OBJECT (cmdline),
    ///                           "application", application,
    ///                           (GDestroyNotify)g_application_release);
    ///
    ///   g_object_ref (cmdline);
    ///   g_idle_add (my_cmdline_handler, cmdline);
    ///
    ///   return 0;
    /// }
    /// ```
    /// In this example the commandline is not completely handled before
    /// the `signal::Application::command-line` handler returns. Instead, we keep
    /// a reference to the [`ApplicationCommandLine`][crate::ApplicationCommandLine] object and handle it
    /// later (in this example, in an idle). Note that it is necessary to
    /// hold the application until you are done with the commandline.
    ///
    /// The complete example can be found here:
    /// [gapplication-example-cmdline3.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gapplication-example-cmdline3.c)
    ///
    /// # Implements
    ///
    /// [`ApplicationCommandLineExt`][trait@crate::prelude::ApplicationCommandLineExt], [`trait@glib::ObjectExt`]
    #[doc(alias = "GApplicationCommandLine")]
    pub struct ApplicationCommandLine(Object<ffi::GApplicationCommandLine, ffi::GApplicationCommandLineClass>);

    match fn {
        type_ => || ffi::g_application_command_line_get_type(),
    }
}

impl ApplicationCommandLine {
    pub const NONE: Option<&'static ApplicationCommandLine> = None;
}

/// Trait containing all [`struct@ApplicationCommandLine`] methods.
///
/// # Implementors
///
/// [`ApplicationCommandLine`][struct@crate::ApplicationCommandLine]
pub trait ApplicationCommandLineExt: 'static {
    /// Creates a [`File`][crate::File] corresponding to a filename that was given as part
    /// of the invocation of `self`.
    ///
    /// This differs from [`File::for_commandline_arg()`][crate::File::for_commandline_arg()] in that it
    /// resolves relative pathnames using the current working directory of
    /// the invoking process rather than the local process.
    /// ## `arg`
    /// an argument from `self`
    ///
    /// # Returns
    ///
    /// a new [`File`][crate::File]
    #[doc(alias = "g_application_command_line_create_file_for_arg")]
    fn create_file_for_arg(&self, arg: impl AsRef<std::ffi::OsStr>) -> File;

    /// Gets the list of arguments that was passed on the command line.
    ///
    /// The strings in the array may contain non-UTF-8 data on UNIX (such as
    /// filenames or arguments given in the system locale) but are always in
    /// UTF-8 on Windows.
    ///
    /// If you wish to use the return value with `GOptionContext`, you must
    /// use `g_option_context_parse_strv()`.
    ///
    /// The return value is [`None`]-terminated and should be freed using
    /// `g_strfreev()`.
    ///
    /// # Returns
    ///
    ///
    ///  the string array containing the arguments (the argv)
    #[doc(alias = "g_application_command_line_get_arguments")]
    #[doc(alias = "get_arguments")]
    fn arguments(&self) -> Vec<std::ffi::OsString>;

    /// Gets the working directory of the command line invocation.
    /// The string may contain non-utf8 data.
    ///
    /// It is possible that the remote application did not send a working
    /// directory, so this may be [`None`].
    ///
    /// The return value should not be modified or freed and is valid for as
    /// long as `self` exists.
    ///
    /// # Returns
    ///
    /// the current directory, or [`None`]
    #[doc(alias = "g_application_command_line_get_cwd")]
    #[doc(alias = "get_cwd")]
    fn cwd(&self) -> Option<std::path::PathBuf>;

    /// Gets the contents of the 'environ' variable of the command line
    /// invocation, as would be returned by `g_get_environ()`, ie as a
    /// [`None`]-terminated list of strings in the form 'NAME=VALUE'.
    /// The strings may contain non-utf8 data.
    ///
    /// The remote application usually does not send an environment. Use
    /// [`ApplicationFlags::SEND_ENVIRONMENT`][crate::ApplicationFlags::SEND_ENVIRONMENT] to affect that. Even with this flag
    /// set it is possible that the environment is still not available (due
    /// to invocation messages from other applications).
    ///
    /// The return value should not be modified or freed and is valid for as
    /// long as `self` exists.
    ///
    /// See [`getenv()`][Self::getenv()] if you are only interested
    /// in the value of a single environment variable.
    ///
    /// # Returns
    ///
    ///
    ///  the environment strings, or [`None`] if they were not sent
    #[doc(alias = "g_application_command_line_get_environ")]
    #[doc(alias = "get_environ")]
    fn environ(&self) -> Vec<std::ffi::OsString>;

    /// Gets the exit status of `self`. See
    /// [`set_exit_status()`][Self::set_exit_status()] for more information.
    ///
    /// # Returns
    ///
    /// the exit status
    #[doc(alias = "g_application_command_line_get_exit_status")]
    #[doc(alias = "get_exit_status")]
    fn exit_status(&self) -> i32;

    /// Determines if `self` represents a remote invocation.
    ///
    /// # Returns
    ///
    /// [`true`] if the invocation was remote
    #[doc(alias = "g_application_command_line_get_is_remote")]
    #[doc(alias = "get_is_remote")]
    fn is_remote(&self) -> bool;

    /// Gets the options there were passed to `g_application_command_line()`.
    ///
    /// If you did not override `local_command_line()` then these are the same
    /// options that were parsed according to the `GOptionEntrys` added to the
    /// application with `g_application_add_main_option_entries()` and possibly
    /// modified from your GApplication::handle-local-options handler.
    ///
    /// If no options were sent then an empty dictionary is returned so that
    /// you don't need to check for [`None`].
    ///
    /// # Returns
    ///
    /// a [`glib::VariantDict`][crate::glib::VariantDict] with the options
    #[doc(alias = "g_application_command_line_get_options_dict")]
    #[doc(alias = "get_options_dict")]
    fn options_dict(&self) -> glib::VariantDict;

    /// Gets the platform data associated with the invocation of `self`.
    ///
    /// This is a [`glib::Variant`][struct@crate::glib::Variant] dictionary containing information about the
    /// context in which the invocation occurred. It typically contains
    /// information like the current working directory and the startup
    /// notification ID.
    ///
    /// For local invocation, it will be [`None`].
    ///
    /// # Returns
    ///
    /// the platform data, or [`None`]
    #[doc(alias = "g_application_command_line_get_platform_data")]
    #[doc(alias = "get_platform_data")]
    fn platform_data(&self) -> Option<glib::Variant>;

    /// Gets the stdin of the invoking process.
    ///
    /// The [`InputStream`][crate::InputStream] can be used to read data passed to the standard
    /// input of the invoking process.
    /// This doesn't work on all platforms. Presently, it is only available
    /// on UNIX when using a D-Bus daemon capable of passing file descriptors.
    /// If stdin is not available then [`None`] will be returned. In the
    /// future, support may be expanded to other platforms.
    ///
    /// You must only call this function once per commandline invocation.
    ///
    /// # Returns
    ///
    /// a [`InputStream`][crate::InputStream] for stdin
    #[doc(alias = "g_application_command_line_get_stdin")]
    #[doc(alias = "get_stdin")]
    fn stdin(&self) -> Option<InputStream>;

    /// Gets the value of a particular environment variable of the command
    /// line invocation, as would be returned by `g_getenv()`. The strings may
    /// contain non-utf8 data.
    ///
    /// The remote application usually does not send an environment. Use
    /// [`ApplicationFlags::SEND_ENVIRONMENT`][crate::ApplicationFlags::SEND_ENVIRONMENT] to affect that. Even with this flag
    /// set it is possible that the environment is still not available (due
    /// to invocation messages from other applications).
    ///
    /// The return value should not be modified or freed and is valid for as
    /// long as `self` exists.
    /// ## `name`
    /// the environment variable to get
    ///
    /// # Returns
    ///
    /// the value of the variable, or [`None`] if unset or unsent
    #[doc(alias = "g_application_command_line_getenv")]
    fn getenv(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<glib::GString>;

    //#[doc(alias = "g_application_command_line_print")]
    //fn print(&self, format: &str, : /*Unknown conversion*//*Unimplemented*/Basic: VarArgs);

    //#[doc(alias = "g_application_command_line_printerr")]
    //fn printerr(&self, format: &str, : /*Unknown conversion*//*Unimplemented*/Basic: VarArgs);

    /// Sets the exit status that will be used when the invoking process
    /// exits.
    ///
    /// The return value of the `signal::Application::command-line` signal is
    /// passed to this function when the handler returns. This is the usual
    /// way of setting the exit status.
    ///
    /// In the event that you want the remote invocation to continue running
    /// and want to decide on the exit status in the future, you can use this
    /// call. For the case of a remote invocation, the remote process will
    /// typically exit when the last reference is dropped on `self`. The
    /// exit status of the remote process will be equal to the last value
    /// that was set with this function.
    ///
    /// In the case that the commandline invocation is local, the situation
    /// is slightly more complicated. If the commandline invocation results
    /// in the mainloop running (ie: because the use-count of the application
    /// increased to a non-zero value) then the application is considered to
    /// have been 'successful' in a certain sense, and the exit status is
    /// always zero. If the application use count is zero, though, the exit
    /// status of the local [`ApplicationCommandLine`][crate::ApplicationCommandLine] is used.
    /// ## `exit_status`
    /// the exit status
    #[doc(alias = "g_application_command_line_set_exit_status")]
    fn set_exit_status(&self, exit_status: i32);

    #[doc(alias = "is-remote")]
    fn connect_is_remote_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}

impl<O: IsA<ApplicationCommandLine>> ApplicationCommandLineExt for O {
    fn create_file_for_arg(&self, arg: impl AsRef<std::ffi::OsStr>) -> File {
        unsafe {
            from_glib_full(ffi::g_application_command_line_create_file_for_arg(
                self.as_ref().to_glib_none().0,
                arg.as_ref().to_glib_none().0,
            ))
        }
    }

    fn arguments(&self) -> Vec<std::ffi::OsString> {
        unsafe {
            let mut argc = mem::MaybeUninit::uninit();
            let ret = FromGlibContainer::from_glib_full_num(
                ffi::g_application_command_line_get_arguments(
                    self.as_ref().to_glib_none().0,
                    argc.as_mut_ptr(),
                ),
                argc.assume_init() as _,
            );
            ret
        }
    }

    fn cwd(&self) -> Option<std::path::PathBuf> {
        unsafe {
            from_glib_none(ffi::g_application_command_line_get_cwd(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn environ(&self) -> Vec<std::ffi::OsString> {
        unsafe {
            FromGlibPtrContainer::from_glib_none(ffi::g_application_command_line_get_environ(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn exit_status(&self) -> i32 {
        unsafe { ffi::g_application_command_line_get_exit_status(self.as_ref().to_glib_none().0) }
    }

    fn is_remote(&self) -> bool {
        unsafe {
            from_glib(ffi::g_application_command_line_get_is_remote(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn options_dict(&self) -> glib::VariantDict {
        unsafe {
            from_glib_none(ffi::g_application_command_line_get_options_dict(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn platform_data(&self) -> Option<glib::Variant> {
        unsafe {
            from_glib_full(ffi::g_application_command_line_get_platform_data(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn stdin(&self) -> Option<InputStream> {
        unsafe {
            from_glib_full(ffi::g_application_command_line_get_stdin(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn getenv(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<glib::GString> {
        unsafe {
            from_glib_none(ffi::g_application_command_line_getenv(
                self.as_ref().to_glib_none().0,
                name.as_ref().to_glib_none().0,
            ))
        }
    }

    //fn print(&self, format: &str, : /*Unknown conversion*//*Unimplemented*/Basic: VarArgs) {
    //    unsafe { TODO: call ffi:g_application_command_line_print() }
    //}

    //fn printerr(&self, format: &str, : /*Unknown conversion*//*Unimplemented*/Basic: VarArgs) {
    //    unsafe { TODO: call ffi:g_application_command_line_printerr() }
    //}

    fn set_exit_status(&self, exit_status: i32) {
        unsafe {
            ffi::g_application_command_line_set_exit_status(
                self.as_ref().to_glib_none().0,
                exit_status,
            );
        }
    }

    fn connect_is_remote_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_is_remote_trampoline<
            P: IsA<ApplicationCommandLine>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GApplicationCommandLine,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(ApplicationCommandLine::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::is-remote\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_is_remote_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl fmt::Display for ApplicationCommandLine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("ApplicationCommandLine")
    }
}