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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{ffi::OsString, fmt, ops::Deref, ptr};

use glib::{prelude::*, subclass::prelude::*, translate::*, ExitCode, VariantDict};
use libc::{c_char, c_int, c_void};

use crate::Application;

pub struct ArgumentList {
    pub(crate) ptr: *mut *mut *mut c_char,
    items: Vec<OsString>,
}

impl ArgumentList {
    pub(crate) fn new(arguments: *mut *mut *mut c_char) -> Self {
        Self {
            ptr: arguments,
            items: unsafe { FromGlibPtrContainer::from_glib_none(ptr::read(arguments)) },
        }
    }

    pub(crate) fn refresh(&mut self) {
        self.items = unsafe { FromGlibPtrContainer::from_glib_none(ptr::read(self.ptr)) };
    }

    // remove the item at index `idx` and shift the raw array
    pub fn remove(&mut self, idx: usize) {
        unsafe {
            let n_args = glib::ffi::g_strv_length(*self.ptr) as usize;
            assert_eq!(n_args, self.items.len());
            assert!(idx < n_args);

            self.items.remove(idx);

            glib::ffi::g_free(*(*self.ptr).add(idx) as *mut c_void);

            for i in idx..n_args - 1 {
                ptr::write((*self.ptr).add(i), *(*self.ptr).add(i + 1))
            }
            ptr::write((*self.ptr).add(n_args - 1), ptr::null_mut());
        }
    }
}

impl Deref for ArgumentList {
    type Target = [OsString];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.items.as_slice()
    }
}

impl fmt::Debug for ArgumentList {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.items.fmt(formatter)
    }
}

impl From<ArgumentList> for Vec<OsString> {
    fn from(list: ArgumentList) -> Vec<OsString> {
        list.items
    }
}

pub trait ApplicationImpl: ObjectImpl + ApplicationImplExt {
    /// Activates the application.
    ///
    /// In essence, this results in the #GApplication::activate signal being
    /// emitted in the primary instance.
    ///
    /// The application must be registered before calling this function.
    fn activate(&self) {
        self.parent_activate()
    }

    /// invoked on the primary instance after 'activate', 'open',
    ///     'command-line' or any action invocation, gets the 'platform data' from
    ///     the calling instance
    fn after_emit(&self, platform_data: &glib::Variant) {
        self.parent_after_emit(platform_data)
    }

    /// invoked on the primary instance before 'activate', 'open',
    ///     'command-line' or any action invocation, gets the 'platform data' from
    ///     the calling instance
    fn before_emit(&self, platform_data: &glib::Variant) {
        self.parent_before_emit(platform_data)
    }

    /// invoked on the primary instance when a command-line is
    ///   not handled locally
    fn command_line(&self, command_line: &crate::ApplicationCommandLine) -> ExitCode {
        self.parent_command_line(command_line)
    }

    /// This virtual function is always invoked in the local instance. It
    /// gets passed a pointer to a [`None`]-terminated copy of @argv and is
    /// expected to remove arguments that it handled (shifting up remaining
    /// arguments).
    ///
    /// The last argument to local_command_line() is a pointer to the @status
    /// variable which can used to set the exit status that is returned from
    /// g_application_run().
    ///
    /// See g_application_run() for more details on #GApplication startup.
    /// ## `arguments`
    /// array of command line arguments
    ///
    /// # Returns
    ///
    /// [`true`] if the commandline has been completely handled
    ///
    /// ## `exit_status`
    /// exit status to fill after processing the command line.
    fn local_command_line(&self, arguments: &mut ArgumentList) -> Option<ExitCode> {
        self.parent_local_command_line(arguments)
    }

    /// Opens the given files.
    ///
    /// In essence, this results in the #GApplication::open signal being emitted
    /// in the primary instance.
    ///
    /// @n_files must be greater than zero.
    ///
    /// @hint is simply passed through to the ::open signal.  It is
    /// intended to be used by applications that have multiple modes for
    /// opening files (eg: "view" vs "edit", etc).  Unless you have a need
    /// for this functionality, you should use "".
    ///
    /// The application must be registered before calling this function
    /// and it must have the [`ApplicationFlags::HANDLES_OPEN`][crate::ApplicationFlags::HANDLES_OPEN] flag set.
    /// ## `files`
    /// an array of #GFiles to open
    /// ## `hint`
    /// a hint (or ""), but never [`None`]
    fn open(&self, files: &[crate::File], hint: &str) {
        self.parent_open(files, hint)
    }

    /// Used to be invoked on the primary instance when the use
    ///     count of the application drops to zero (and after any inactivity
    ///     timeout, if requested). Not used anymore since 2.32
    fn quit_mainloop(&self) {
        self.parent_quit_mainloop()
    }

    /// Used to be invoked on the primary instance from
    ///     g_application_run() if the use-count is non-zero. Since 2.32,
    ///     GApplication is iterating the main context directly and is not
    ///     using @run_mainloop anymore
    fn run_mainloop(&self) {
        self.parent_run_mainloop()
    }

    /// invoked only on the registered primary instance immediately
    ///      after the main loop terminates
    fn shutdown(&self) {
        self.parent_shutdown()
    }

    /// invoked on the primary instance immediately after registration
    fn startup(&self) {
        self.parent_startup()
    }

    /// invoked locally after the parsing of the commandline
    ///  options has occurred. Since: 2.40
    fn handle_local_options(&self, options: &VariantDict) -> ExitCode {
        self.parent_handle_local_options(options)
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::ApplicationImplExt> Sealed for T {}
}

pub trait ApplicationImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_activate(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .activate
                .expect("No parent class implementation for \"activate\"");
            f(self.obj().unsafe_cast_ref::<Application>().to_glib_none().0)
        }
    }

    fn parent_after_emit(&self, platform_data: &glib::Variant) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .after_emit
                .expect("No parent class implementation for \"after_emit\"");
            f(
                self.obj().unsafe_cast_ref::<Application>().to_glib_none().0,
                platform_data.to_glib_none().0,
            )
        }
    }

    fn parent_before_emit(&self, platform_data: &glib::Variant) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .before_emit
                .expect("No parent class implementation for \"before_emit\"");
            f(
                self.obj().unsafe_cast_ref::<Application>().to_glib_none().0,
                platform_data.to_glib_none().0,
            )
        }
    }

    fn parent_command_line(&self, command_line: &crate::ApplicationCommandLine) -> ExitCode {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .command_line
                .expect("No parent class implementation for \"command_line\"");
            f(
                self.obj().unsafe_cast_ref::<Application>().to_glib_none().0,
                command_line.to_glib_none().0,
            )
            .into()
        }
    }

    fn parent_local_command_line(&self, arguments: &mut ArgumentList) -> Option<ExitCode> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .local_command_line
                .expect("No parent class implementation for \"local_command_line\"");

            let mut exit_status = 0;
            let res = f(
                self.obj().unsafe_cast_ref::<Application>().to_glib_none().0,
                arguments.ptr,
                &mut exit_status,
            );
            arguments.refresh();

            match res {
                glib::ffi::GFALSE => None,
                _ => Some(exit_status.into()),
            }
        }
    }

    fn parent_open(&self, files: &[crate::File], hint: &str) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .open
                .expect("No parent class implementation for \"open\"");
            f(
                self.obj().unsafe_cast_ref::<Application>().to_glib_none().0,
                files.to_glib_none().0,
                files.len() as i32,
                hint.to_glib_none().0,
            )
        }
    }

    fn parent_quit_mainloop(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .quit_mainloop
                .expect("No parent class implementation for \"quit_mainloop\"");
            f(self.obj().unsafe_cast_ref::<Application>().to_glib_none().0)
        }
    }

    fn parent_run_mainloop(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .run_mainloop
                .expect("No parent class implementation for \"run_mainloop\"");
            f(self.obj().unsafe_cast_ref::<Application>().to_glib_none().0)
        }
    }

    fn parent_shutdown(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .shutdown
                .expect("No parent class implementation for \"shutdown\"");
            f(self.obj().unsafe_cast_ref::<Application>().to_glib_none().0)
        }
    }

    fn parent_startup(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            let f = (*parent_class)
                .startup
                .expect("No parent class implementation for \"startup\"");
            f(self.obj().unsafe_cast_ref::<Application>().to_glib_none().0)
        }
    }

    fn parent_handle_local_options(&self, options: &VariantDict) -> ExitCode {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GApplicationClass;
            if let Some(f) = (*parent_class).handle_local_options {
                f(
                    self.obj().unsafe_cast_ref::<Application>().to_glib_none().0,
                    options.to_glib_none().0,
                )
                .into()
            } else {
                // Continue default handling
                ExitCode::from(-1)
            }
        }
    }
}

impl<T: ApplicationImpl> ApplicationImplExt for T {}

unsafe impl<T: ApplicationImpl> IsSubclassable<T> for Application {
    fn class_init(class: &mut ::glib::Class<Self>) {
        Self::parent_class_init::<T>(class);

        let klass = class.as_mut();
        klass.activate = Some(application_activate::<T>);
        klass.after_emit = Some(application_after_emit::<T>);
        klass.before_emit = Some(application_before_emit::<T>);
        klass.command_line = Some(application_command_line::<T>);
        klass.local_command_line = Some(application_local_command_line::<T>);
        klass.open = Some(application_open::<T>);
        klass.quit_mainloop = Some(application_quit_mainloop::<T>);
        klass.run_mainloop = Some(application_run_mainloop::<T>);
        klass.shutdown = Some(application_shutdown::<T>);
        klass.startup = Some(application_startup::<T>);
        klass.handle_local_options = Some(application_handle_local_options::<T>);
    }
}

unsafe extern "C" fn application_activate<T: ApplicationImpl>(ptr: *mut ffi::GApplication) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.activate()
}

unsafe extern "C" fn application_after_emit<T: ApplicationImpl>(
    ptr: *mut ffi::GApplication,
    platform_data: *mut glib::ffi::GVariant,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.after_emit(&from_glib_borrow(platform_data))
}
unsafe extern "C" fn application_before_emit<T: ApplicationImpl>(
    ptr: *mut ffi::GApplication,
    platform_data: *mut glib::ffi::GVariant,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.before_emit(&from_glib_borrow(platform_data))
}
unsafe extern "C" fn application_command_line<T: ApplicationImpl>(
    ptr: *mut ffi::GApplication,
    command_line: *mut ffi::GApplicationCommandLine,
) -> i32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.command_line(&from_glib_borrow(command_line)).into()
}
unsafe extern "C" fn application_local_command_line<T: ApplicationImpl>(
    ptr: *mut ffi::GApplication,
    arguments: *mut *mut *mut c_char,
    exit_status: *mut i32,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let mut args = ArgumentList::new(arguments);
    let res = imp.local_command_line(&mut args).map(i32::from);
    args.refresh();

    match res {
        Some(ret) => {
            *exit_status = ret;
            glib::ffi::GTRUE
        }
        None => glib::ffi::GFALSE,
    }
}
unsafe extern "C" fn application_open<T: ApplicationImpl>(
    ptr: *mut ffi::GApplication,
    files: *mut *mut ffi::GFile,
    num_files: i32,
    hint: *const c_char,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let files: Vec<crate::File> = FromGlibContainer::from_glib_none_num(files, num_files as usize);
    imp.open(files.as_slice(), &glib::GString::from_glib_borrow(hint))
}
unsafe extern "C" fn application_quit_mainloop<T: ApplicationImpl>(ptr: *mut ffi::GApplication) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.quit_mainloop()
}
unsafe extern "C" fn application_run_mainloop<T: ApplicationImpl>(ptr: *mut ffi::GApplication) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.run_mainloop()
}
unsafe extern "C" fn application_shutdown<T: ApplicationImpl>(ptr: *mut ffi::GApplication) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.shutdown()
}
unsafe extern "C" fn application_startup<T: ApplicationImpl>(ptr: *mut ffi::GApplication) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.startup()
}

unsafe extern "C" fn application_handle_local_options<T: ApplicationImpl>(
    ptr: *mut ffi::GApplication,
    options: *mut glib::ffi::GVariantDict,
) -> c_int {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.handle_local_options(&from_glib_borrow(options)).into()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::*;

    const EXIT_STATUS: i32 = 20;

    mod imp {
        use super::*;

        #[derive(Default)]
        pub struct SimpleApplication;

        #[glib::object_subclass]
        impl ObjectSubclass for SimpleApplication {
            const NAME: &'static str = "SimpleApplication";
            type Type = super::SimpleApplication;
            type ParentType = Application;
        }

        impl ObjectImpl for SimpleApplication {}

        impl ApplicationImpl for SimpleApplication {
            fn command_line(&self, cmd_line: &crate::ApplicationCommandLine) -> ExitCode {
                let arguments = cmd_line.arguments();

                // NOTE: on windows argc and argv are ignored, even if the arguments
                // were passed explicitly.
                //
                // Source: https://gitlab.gnome.org/GNOME/glib/-/blob/e64a93269d09302d7a4facbc164b7fe9c2ad0836/gio/gapplication.c#L2513-2515
                #[cfg(not(target_os = "windows"))]
                assert_eq!(arguments.to_vec(), &["--global-1", "--global-2"]);

                EXIT_STATUS.into()
            }

            fn local_command_line(&self, arguments: &mut ArgumentList) -> Option<ExitCode> {
                let mut rm = Vec::new();

                for (i, line) in arguments.iter().enumerate() {
                    // TODO: we need https://github.com/rust-lang/rust/issues/49802
                    let l = line.to_str().unwrap();
                    if l.starts_with("--local-") {
                        rm.push(i)
                    }
                }

                rm.reverse();

                for i in rm.iter() {
                    arguments.remove(*i);
                }

                None
            }
        }
    }

    glib::wrapper! {
        pub struct SimpleApplication(ObjectSubclass<imp::SimpleApplication>)
        @implements crate::Application;
    }

    #[test]
    fn test_simple_application() {
        let app = glib::Object::builder::<SimpleApplication>()
            .property("application-id", "org.gtk-rs.SimpleApplication")
            .property("flags", crate::ApplicationFlags::empty())
            .build();

        app.set_inactivity_timeout(10000);

        assert_eq!(
            app.run_with_args(&["--local-1", "--global-1", "--local-2", "--global-2"]),
            EXIT_STATUS.into()
        );
    }
}