Codebase list gnome-maps / feb76c24-716e-4fcd-b3e1-357626f6d9cc/main src / application.js
feb76c24-716e-4fcd-b3e1-357626f6d9cc/main

Tree @feb76c24-716e-4fcd-b3e1-357626f6d9cc/main (Download .tar.gz)

application.js @feb76c24-716e-4fcd-b3e1-357626f6d9cc/mainraw · history · blame

  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
/* -*- Mode: JS2; indent-tabs-mode: nil; js2-basic-offset: 4 -*- */
/* vim: set et ts=4 sw=4: */
/*
 * Copyright (c) 2011, 2012, 2013 Red Hat, Inc.
 *
 * GNOME Maps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * GNOME Maps is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with GNOME Maps; if not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Cosimo Cecchi <cosimoc@redhat.com>
 *         Zeeshan Ali (Khattak) <zeeshanak@gnome.org>
 */

const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Geocode = imports.gi.GeocodeGlib;
const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;
const GtkClutter = imports.gi.GtkClutter;
const Hdy = imports.gi.Handy;
const WebKit2 = imports.gi.WebKit2;

const CheckIn = imports.checkIn;
const ContactPlace = imports.contactPlace;
const Format = imports.format;
const Geoclue = imports.geoclue;
const GeocodeFactory = imports.geocode;
const MainWindow = imports.mainWindow;
const Maps = imports.gi.GnomeMaps;
const OSMEdit = imports.osmEdit;
const OSMTypeSearchEntry = imports.osmTypeSearchEntry;
const PlaceStore = imports.placeStore;
const RoutingDelegator = imports.routingDelegator;
const RouteQuery = imports.routeQuery;
const Settings = imports.settings;
const Utils = imports.utils;
const URIS = imports.uris;

// used globally
var application = null;
var settings = null;
var placeStore = null;
var routingDelegator = null;
var geoclue = null;
var networkMonitor = null;
var checkInManager = null;
var contactStore = null;
var osmEdit = null;
var normalStartup = true;
var routeQuery = null;

const _ensuredTypes = [WebKit2.WebView,
                       OSMTypeSearchEntry.OSMTypeSearchEntry];

var Application = GObject.registerClass({
    Properties: {
        'connected': GObject.ParamSpec.boolean('connected',
                                               '',
                                               '',
                                               GObject.ParamFlags.READABLE |
                                               GObject.ParamFlags.WRITABLE),
        'selected-place': GObject.ParamSpec.object('selected-place',
                                                   'Selected Place',
                                                   'The selected place',
                                                   GObject.ParamFlags.READABLE |
                                                   GObject.ParamFlags.WRITABLE,
                                                   Geocode.Place),
        'adaptive-mode': GObject.ParamSpec.boolean('adaptive-mode',
                                                   'Adaptive Move',
                                                   'Whether the main window is in adaptive (narrow) mode',
                                                   GObject.ParamFlags.READABLE |
                                                   GObject.ParamFlags.WRITABLE),
    },
}, class Application extends Gtk.Application {

    set connected(p) {
        this._connected = p;
        this.notify('connected');
    }

    get connected() {
        return this._connected;
    }

    _init() {
        /* Translators: This is the program name. */
        GLib.set_application_name(_("Maps"));

        /* Needed to be able to use in UI files */
        _ensuredTypes.forEach((type) => GObject.type_ensure(type));

        super._init({ application_id: pkg.name,
                      flags: Gio.ApplicationFlags.HANDLES_OPEN |
                             Gio.ApplicationFlags.HANDLES_COMMAND_LINE });
        this._connected = false;

        this.add_main_option('local',
                             0,
                             GLib.OptionFlags.NONE,
                             GLib.OptionArg.FILENAME,
                             _("A path to a local tiles directory structure"),
                             null);
        this.add_main_option('local-tile-size',
                             0,
                             GLib.OptionFlags.NONE,
                             GLib.OptionArg.INT,
                             _("Tile size for local tiles directory"),
                             null);

        this.add_main_option('version', 'v'.charCodeAt(0), GLib.OptionFlags.NONE, GLib.OptionArg.NONE,
                             _("Show the version of the program"), null);

        this.add_main_option('force-online',
                             0,
                             GLib.OptionFlags.NONE,
                             GLib.OptionArg.NONE,
                             _("Ignore network availability"),
                             null);

        this.add_main_option('search',
                             'S'.charCodeAt(0),
                             GLib.OptionFlags.NONE,
                             GLib.OptionArg.STRING,
                             _("Search for places"),
                             null);

        /* due to https://gitlab.gnome.org/GNOME/gjs/-/issues/330 the
         * description for the remaining args needs to be passed as both
         * description and arg_description
         */
        this.add_main_option(GLib.OPTION_REMAINING,
                             0,
                             0,
                             GLib.OptionArg.STRING_ARRAY,
                             _("[FILE…|URI]"),
                             _("[FILE…|URI]"));
    }

    _checkNetwork() {
        this.connected =
            this._forceOnline ||
            networkMonitor.connectivity === Gio.NetworkConnectivity.FULL;
    }

    _showContact(id) {
        contactStore.lookup(id, (contact) => {
            this.mark_busy();
            if (!contact) {
                this.unmark_busy();
                return;
            }
            contact.geocode(() => {
                this.unmark_busy();
                this._mainWindow.mapView.showContact(contact);
            });
        });
    }

    _onShowContactActivate(action, parameter) {
        this._createWindow();
        this._checkNetwork();
        this._mainWindow.present();

        let id = parameter.deep_unpack();

        if (contactStore.state === Maps.ContactStoreState.LOADED) {
            this. _showContact(id);
        } else {
            Utils.once(contactStore, 'notify::state', () => {
                if (contactStore.state === Maps.ContactStoreState.LOADED)
                    this._showContact(id);
            });
        }
    }

    _onOsmAccountSetupActivate() {
        let dialog = osmEdit.createAccountDialog(this._mainWindow, false);

        dialog.show();
        dialog.connect('response', () => dialog.destroy());
    }

    _onSearchActivate(action, parameter) {
        this._createWindow();
        this._mainWindow.present();

        let query = parameter.deep_unpack();
        let mapView = this._mainWindow.mapView;

        if (mapView.view.realized)
            this._openSearchQuery(query);
        else
            mapView.view.connect('notify::realized',
                                 this._openSearchQuery.bind(this, query));
    }

    _addContacts() {
        let contacts = contactStore.get_contacts();

        this._addContactsRecursive(contacts, 0);
    }

    _addContactsRecursive(contacts, index) {
        if (index < contacts.length) {
            let contact = contacts[index];

            contact.geocode(() => {
                contact.get_places().forEach((p) => {
                    if (!p.location)
                        return

                    Utils.debug('Adding contact address: ' + p.name);
                    let place = new ContactPlace.ContactPlace({ place: p,
                                                                contact: contact });
                    placeStore.addPlace(place, PlaceStore.PlaceType.CONTACT);
                });

                this._addContactsRecursive(contacts, index + 1);
            });
        }
    }

    _initPlaceStore() {
        placeStore = new PlaceStore.PlaceStore({
            recentPlacesLimit: settings.get('recent-places-limit'),
            recentRoutesLimit: settings.get('recent-routes-limit')
        });
        try {
            placeStore.load();
        } catch (e) {
            log('Failed to parse Maps places file, ' +
                'subsequent writes will overwrite the file!');
        }

        if (contactStore.state === Maps.ContactStoreState.LOADED) {
            this._addContacts();
        } else {
            Utils.once(contactStore, 'notify::state', () => {
                if (contactStore.state === Maps.ContactStoreState.LOADED)
                    this._addContacts();
            });
        }
    }

    vfunc_startup() {
        super.vfunc_startup();

        GtkClutter.init(null);
        Hdy.init();

        Utils.loadStyleSheet(Gio.file_new_for_uri('resource:///org/gnome/Maps/application.css'));

        application = this;
        this._initServices();

        Utils.addActions(this, {
            'show-contact': {
                paramType: 's',
                onActivate: this._onShowContactActivate.bind(this)
            },
            'osm-account-setup': {
                onActivate: this._onOsmAccountSetupActivate.bind(this)
            },
            'search': {
                paramType: 's',
                onActivate: this._onSearchActivate.bind(this)
            },
            'quit': {
                onActivate: () => this.quit(),
                accels: ['<Primary>Q']
            }
        }, settings);


        this._styleManager = Hdy.StyleManager.get_default();
        this._styleManager.set_color_scheme(Hdy.ColorScheme.PREFER_LIGHT);

        Gtk.IconTheme.get_default().append_search_path(GLib.build_filenamev([pkg.pkgdatadir,
                                                                             'icons']));
        this._initPlaceStore();
    }

    _initServices() {
        settings         = Settings.getSettings('org.gnome.Maps');
        routeQuery       = new RouteQuery.RouteQuery();
        routingDelegator = new RoutingDelegator.RoutingDelegator({ query: routeQuery });
        geoclue          = new Geoclue.Geoclue();
        networkMonitor   = Gio.NetworkMonitor.get_default();
        networkMonitor.connect('network-changed',
                               this._checkNetwork.bind(this));
        checkInManager = new CheckIn.CheckInManager();
        contactStore = new Maps.ContactStore();
        contactStore.load();
        osmEdit = new OSMEdit.OSMEdit();
    }

    _createWindow() {
        if (this._mainWindow)
            return;

        this._mainWindow = new MainWindow.MainWindow({ application: this });
        this._mainWindow.connect('destroy', () => this._onWindowDestroy());
        if (GLib.getenv('MAPS_DEBUG') === 'focus') {
            this._mainWindow.connect('set-focus', (window, widget) => {
                log('* focus widget: %s'.format(widget));
            });
        }
    }

    vfunc_dbus_register(connection, path) {
        super.vfunc_dbus_register(connection, path);
        return true;
    }

    vfunc_dbus_unregister(connection, path) {
        super.vfunc_dbus_unregister(connection, path);
    }

    vfunc_activate() {
        this._createWindow();
        this._checkNetwork();
        this._mainWindow.present();
    }

    _openInternal(files) {
        if (!this._mainWindow || !this._mainWindow.mapView.view.realized)
            return;

        let uri = files[0].get_uri();
        let scheme = GLib.uri_parse_scheme(uri);

        if (scheme === 'geo') {
            // we get a URI that looks like geo:///lat,lon, remove slashes
            let geoURI = uri.replace(/\//g, '');
            this._mainWindow.mapView.goToGeoURI(geoURI);
        } else if (scheme === 'http' || scheme === 'https') {
            this._mainWindow.mapView.goToHttpURL(uri);
        } else if (scheme === 'maps') {
            // we get a URI that looks like maps:///q=Search, remove slashes
            let mapsURI = uri.replace(/\//g, '');
            this._openMapsUri(mapsURI);
        } else {
            this._mainWindow.mapView.openShapeLayers(files);
        }
    }

    _openMapsUri(uri) {
        let query = URIS.parseMapsURI(uri);

        if (query)
            this._openSearchQuery(query);
        else
            this._invalidMapsUri(uri);
    }

    _openSearchQuery(query) {
        let cancellable = new Gio.Cancellable();

        /* unless there's exactly one place (which should be focused) in
         * the results, let the stored location be used on startup
         */
        normalStartup = true;
        this.connect('shutdown', () => cancellable.cancel());
        GeocodeFactory.getGeocoder().search(query, null, null, cancellable,
                                            (places, error) => {
            if (error) {
                Utils.showDialog(_("An error has occurred"),
                                 Gtk.MessageType.ERROR, this._mainWindow);
            } else {
                // clear search entry
                this._mainWindow.placeEntry.text = '';

                if (places) {
                    /* if there's only one place in results, show it directly
                     * with it's bubble, otherwise present the results in the
                     * search popover
                     */
                    if (places?.length === 1) {
                        /* don't use the stored location on startup, as we're
                         * zooming in directly on the place
                         */
                        normalStartup = false;
                        this._mainWindow.mapView.showPlace(places[0], true);
                    } else {
                        this._mainWindow.placeEntry.grab_focus();
                        this._mainWindow.placeEntry.updateResults(places, query,
                                                                  false);
                    }
                } else {
                    Utils.showDialog(_("No results found"),
                                     Gtk.MessageType.INFO, this._mainWindow);
                }
            }
        });
    }

    _invalidMapsUri(uri) {
        Utils.showDialog(_("Invalid maps: URI: %s").format(uri),
                         Gtk.MessageType.ERROR, this._mainWindow);
    }

    vfunc_open(files) {
        /* unless the first argument is a maps: URI with a search query
         * we should not perform the normal startup behavior of going to
         * the stored location, as shape layers, directly addressed OSM
         * objects, and geo: URIs will override the startup location
         */
        let uri = files[0].get_uri();

        if (GLib.uri_parse_scheme(uri) !== 'maps')
            normalStartup = false;

        this.activate();

        let mapView = this._mainWindow.mapView;
        if (mapView.view.realized)
            this._openInternal(files);
        else
            mapView.view.connect('notify::realized',
                                 this._openInternal.bind(this, files));
    }

    vfunc_command_line(cmdline) {
        let options = cmdline.get_options_dict();

        if (options.contains('local')) {
            let variant = options.lookup_value('local', null);
            this.local_tile_path = variant.deep_unpack();
            normalStartup = false;
            if (options.contains('local-tile-size')) {
                variant = options.lookup_value('local-tile-size', null);
                this.local_tile_size = variant.deep_unpack();
            }
        } else if (options.contains('version')) {
            print(pkg.version);
            /* quit the invoked process after printing the version number
             * leaving the running instance unaffected
             */
            return 0;
        } else if (options.contains('force-online')) {
            this._forceOnline = true;
        }

        let remaining = options.lookup(GLib.OPTION_REMAINING, null);
        let files = [];

        // when given the search CLI argument, insert URI as first file
        if (options.contains('search')) {
            let query = options.lookup_value('search', null).deep_unpack();

            files = [Gio.File.new_for_uri(`maps:q=${query}`)];
        }

        if (remaining) {
            remaining.forEach((r) => {
                let path = r.get_string()[0];

                if (path.startsWith('geo:') || path.startsWith('http://') ||
                    path.startsWith('https://') || path.startsWith('maps:')) {
                    files.push(Gio.File.new_for_uri(path));
                } else {
                    files.push(Gio.File.new_for_path(path));
                }
            });
        }

        if (files.length > 0)
            this.open(files, '');
        else
            this.activate();

        return 0;
    }

    _onWindowDestroy(window) {
        this._mainWindow = null;
    }
});