summaryrefslogtreecommitdiff
path: root/src/placeEntry.js
blob: a1c4501ac34a3100f7da8ade6604a256c076b60d (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
/* -*- 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>
 */

const _ = imports.gettext.gettext;

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 Application = imports.application;
const GeocodeFactory = imports.geocode;
const Location = imports.location;
const Place = imports.place;
const PlaceStore = imports.placeStore;
const PlacePopover = imports.placePopover;
const Utils = imports.utils;

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

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

var PlaceEntry = GObject.registerClass({
    Properties: {
        'place': GObject.ParamSpec.object('place',
                                          'Place',
                                          'The selected place',
                                          GObject.ParamFlags.READABLE |
                                          GObject.ParamFlags.WRITABLE,
                                          Geocode.Place)
    }
}, 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;
    }

    _init(props) {
        let numVisible = props.num_visible || 6;
        delete props.num_visible;
        this._mapView = props.mapView;
        delete props.mapView;

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

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

        this._matchRoute = props.matchRoute || false;
        delete props.matchRoute;

        super._init(props);

        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 = {});
    }

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

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

        /* start search if more than the threashold 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);
            } 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.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;
    }

    _parse() {
        let parsed = false;

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

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

            parsed = true;
        }

        let parsedLocation = Place.Place.parseCoordinates(this.text);
        if (parsedLocation) {
            this.place = new Place.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;
        GeocodeFactory.getGeocoder().search(this.text,
                                            this._mapView.view.latitude,
                                            this._mapView.view.longitude,
                                            this._cancellable,
                                            (places, error) => {
            this._cancellable = null;
            this._updateResults(places);

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

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

    _updateResults(places) {
        if (!places) {
                this.place = null;
                this._popover.showNoResult();
                return;
        }

        let completedPlaces = [];


        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, this.text);
        this._popover.showResult();
    }
});