summaryrefslogtreecommitdiff
path: root/src/placeEntry.js
blob: f08bf468a1a6ff307458fb620d618f2758bc1d11 (plain)
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
/* -*- Mode: JS2; indent-tabs-mode: nil; js2-basic-offset: 4 -*- */
/* vim: set et ts=4 sw=4: */
/*
 * Copyright (c) 2013,2014 Jonas Danielsson, Mattias Bengtsson.
 *
 * 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: Jonas Danielsson <jonas@threetimestwo.org>
 *         Mattias Bengtsson <mattias.jc.bengtsson@gmail.com>
 */

import gettext from 'gettext';

import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import GeocodeGlib from 'gi://GeocodeGlib';
import Gio from 'gi://Gio';
import Gtk from 'gi://Gtk';

import {Application} from './application.js';
import * as GeocodeFactory from './geocode.js';
import {Location} from './location.js';
import {Place} from './place.js';
import {PlaceStore} from './placeStore.js';
import {PlacePopover} from './placePopover.js';
import * as URIS from './uris.js';
import * as Utils from './utils.js';

const _ = gettext.gettext;

// minimum number of characters to start completion
const MIN_CHARS_COMPLETION = 3;

// pattern matching CJK ideographic characters
const IDEOGRAPH_PATTERN = /[\u3300-\u9fff]/

export class PlaceEntry extends Gtk.SearchEntry {

    set place(p) {
        if (!this._place && !p)
            return;

        /* if this entry belongs to a routing query entry, don't notify when
         * setting the same place, otherwise it will trigger twice when
         * initiating from the context menu
         */
        if (!this._matchRoute && this._place && p && this._locEquals(this._place, p))
            return;

        if (p) {
            if (p.name)
                this._placeText = p.name;
            else
                this._placeText = '%.5f, %.5f'.format(p.location.latitude,
                                                      p.location.longitude);
        } else {
            this._placeText = '';
        }

        this.text = this._placeText;

        this._place = p;
        this.notify('place');
    }

    get place() {
        return this._place;
    }

    get popover() {
        return this._popover;
    }

    constructor(props) {
        let numVisible = props.num_visible ?? 6;
        delete props.num_visible;
        let mapView = props.mapView;
        delete props.mapView;

        if (!props.loupe)
            props.primary_icon_name = null;
        delete props.loupe;

        let maxChars = props.maxChars;
        delete props.maxChars;

        let matchRoute = props.matchRoute ?? false;
        delete props.matchRoute;

        super(props);

        this._mapView = mapView;
        this._matchRoute = matchRoute;
        this._filter = new Gtk.TreeModelFilter({ child_model: Application.placeStore });
        this._filter.set_visible_func(this._completionVisibleFunc.bind(this));

        this._popover = this._createPopover(numVisible, maxChars);

        this.connect('search-changed', this._onSearchChanged.bind(this));

        this._cache = {};

        // clear cache when view moves, as result are location-dependent
        this._mapView.view.connect('notify::latitude', () => this._cache = {});
        // clear cache when zoom level changes, to allow limiting location bias
        this._mapView.view.connect('notify::zoom-level', () => this._cache =  {});
    }

    _onSearchChanged() {
        if (this._parse())
            return;

        // wait for an ongoing search
        if (this._cancellable)
            return;

        /* start search if more than the threshold number of characters have
         * been entered, or if the first character is in the ideographic CJK
         * block, as for these, shorter strings could be meaningful
         */
        if ((this.text.length >= MIN_CHARS_COMPLETION ||
             (this.text.length > 0 && this.text[0].match(IDEOGRAPH_PATTERN))) &&
            this.text !== this._placeText) {
            let cachedResults = this._cache[this.text];

            if (cachedResults) {
                this.updateResults(cachedResults, this.text, true);
            } else {
                // if no previous search has been performed, show spinner
                if (!this._previousSearch ||
                    this._previousSearch.length < MIN_CHARS_COMPLETION ||
                    this._placeText) {
                    this._popover.showSpinner();
                }
                this._placeText = '';
                this._doSearch();
            }
        } else {
            this._popover.hide();
            if (this.text.length === 0)
                this.place = null;
            this._previousSearch = null;
        }
    }

    _locEquals(placeA, placeB) {
        if (!placeA.location || !placeB.location)
            return false;

        return (placeA.location.latitude === placeB.location.latitude &&
                placeA.location.longitude === placeB.location.longitude);
    }

    _createPopover(numVisible, maxChars) {
        let popover = new PlacePopover({ num_visible:   numVisible,
                                         relative_to:   this,
                                         maxChars:      maxChars });

        this.connect('size-allocate', (widget, allocation) => {
            // Magic number to make the alignment pixel perfect.
            let width_request = allocation.width + 20;
            // set at least 320 px width to avoid too narrow in the sidebar
            popover.width_request = Math.max(width_request, 320);
        });

        popover.connect('selected', (widget, place) => {
            this.place = place;
            popover.hide();
        });

        return popover;
    }

    _completionVisibleFunc(model, iter) {
        let place = model.get_value(iter, PlaceStore.Columns.PLACE);
        let type = model.get_value(iter, PlaceStore.Columns.TYPE);

        if (type !== PlaceStore.PlaceType.CONTACT &&
            type !== PlaceStore.PlaceType.RECENT_ROUTE ||
            (!this._matchRoute && type === PlaceStore.PlaceType.RECENT_ROUTE))
            return false;

        if (place !== null)
            return place.match(this.text);
        else
            return false;
    }

    /**
     * Returns true if two locations are equal when rounded to displayes
     * coordinate precision
     */
    _roundedLocEquals(locA, locB) {
        return '%.5f, %.5f'.format(locA.latitude, locA.longitude) ===
               '%.5f, %.5f'.format(locB.latitude, locB.longitude)
    }

    _parse() {
        let parsed = false;

        if (this.text.startsWith('geo:')) {
            let location = new GeocodeGlib.Location();

            try {
                location.set_from_uri(this.text);
                this.place = new Place({ location: location });
            } catch(e) {
                let msg = _("Failed to parse Geo URI");
                Utils.showDialog(msg, Gtk.MessageType.ERROR, this.get_toplevel());
            }

            parsed = true;
        }

        if (this.text.startsWith('maps:')) {
            let query = URIS.parseMapsURI(this.text);

            if (query) {
                this.text = query;
            } else {
                let msg = _("Failed to parse Maps URI");
                Utils.showDialog(msg, Gtk.MessageType.ERROR, this.get_toplevel());
            }

            parsed = true;
        }

        let parsedLocation = Place.parseCoordinates(this.text);
        if (parsedLocation) {
            /* if the place was a parsed OSM coordinate URL, it will have
             * gotten re-written as bare coordinates and trigger a search-changed,
             * in this case don't re-set the place, as it will loose the zoom
             * level from the URL if set
             */
            if (!this.place ||
                !this._roundedLocEquals(parsedLocation, this.place.location))
                this.place = new Place({ location: parsedLocation });
            parsed = true;
        }

        if (this.text.startsWith('http://') ||
            this.text.startsWith('https://')) {
            if (this._cancellable)
                this._cancellable.cancel();
            this._cancellable = null;
            Place.parseHttpURL(this.text, (place, error) => {
                if (place)
                    this.place = place;
                else
                    Utils.showDialog(error,
                                     Gtk.MessageType.ERROR, this.get_toplevel());
            });

            /* don't cancel ongoing search, as we have started an async
             * operation looking up the OSM object
             */
            return true;
        }

        if (parsed && this._cancellable)
            this._cancellable.cancel();

        return parsed;
    }

    _doSearch() {
        if (this._cancellable)
            this._cancellable.cancel();
        this._cancellable = new Gio.Cancellable();
        this._previousSearch = this.text;

        /* as a stop-gap solution for the location bias tuning issues
         * in Photon (https://github.com/komoot/photon/issues/600),
         * for now search "globally" (e.g. without location bias) for
         * zoom levels above 17, to still allow focused search nearby
         */
        let lat = this._mapView.view.zoom_level > 17 ?
                  this._mapView.view.latitude : null;
        let lon = this._mapView.view.zoom_level > 17 ?
                  this._mapView.view.longitude : null;

        GeocodeFactory.getGeocoder().search(this.text, lat, lon,
                                            this._cancellable,
                                            (places, error) => {
            this._cancellable = null;

            if (error) {
                this.place = null;
                this._popover.showError();
            } else {
                this.updateResults(places, this.text, true);

                // cache results for later
                this._cache[this._previousSearch] = places;
            }

            // if search input has been updated, trigger a refresh
            if (this.text !== this._previousSearch)
                this._onSearchChanged();
        });
    }

    /**
     * Update results popover
     * places array of places from search result
     * searchText original search string to highlight in results
     * includeContactsAndRoute whether to include contacts and recent routes
     *                         among results
     */
    updateResults(places, searchText, includeContactsAndRoutes) {
        if (!places) {
                this.place = null;
                this._popover.showNoResult();
                return;
        }

        let completedPlaces = [];


        if (includeContactsAndRoutes) {
            this._filter.refilter();
            this._filter.foreach((model, path, iter) => {
                let place = model.get_value(iter, PlaceStore.Columns.PLACE);
                let type = model.get_value(iter, PlaceStore.Columns.TYPE);

                completedPlaces.push({ place: place, type: type });
            });
        }

        let placeStore = Application.placeStore;

        places.forEach((place) => {
            let type;

            if (placeStore.exists(place, PlaceStore.PlaceType.RECENT))
                type = PlaceStore.PlaceType.RECENT;
            else if (placeStore.exists(place, PlaceStore.PlaceType.FAVORITE))
                type = PlaceStore.PlaceType.FAVORITE;
            else
                type = PlaceStore.PlaceType.ANY;

            completedPlaces.push({ place: place, type: type });
        });

        this._popover.updateResult(completedPlaces, searchText);
        this._popover.showResult();
    }
}

GObject.registerClass({
    Properties: {
        'place': GObject.ParamSpec.object('place',
                                          'Place',
                                          'The selected place',
                                          GObject.ParamFlags.READABLE |
                                          GObject.ParamFlags.WRITABLE,
                                          GeocodeGlib.Place)
    }
}, PlaceEntry);