summaryrefslogtreecommitdiff
path: root/src/placeView.js
blob: e62b7be9c24124281ad4e58a9a26c89f446bc5e3 (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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/* -*- Mode: JS2; indent-tabs-mode: nil; js2-basic-offset: 4 -*- */
/* vim: set et ts=4 sw=4: */
/*
 * Copyright (c) 2014 Damián Nohales
 *
 * 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: Damián Nohales <damiannohales@gmail.com>
 */

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

const Format = imports.format;

import {Application} from './application.js';
import {Overpass} from './overpass.js';
import {Place} from './place.js';
import * as PlaceIcons from './placeIcons.js';
import {PlaceViewImage} from './placeViewImage.js';
import {PlaceButtons} from './placeButtons.js';
import {PlaceFormatter} from './placeFormatter.js';
import {PlaceStore} from './placeStore.js';
import * as Translations from './translations.js';
import * as Utils from './utils.js';
import * as Wikipedia from './wikipedia.js';

// maximum dimension of thumbnails to fetch from Wikipedia
const THUMBNAIL_FETCH_SIZE = 360;

// Unicode left-to-right marker
const LRM = '\u200E';

export class PlaceView extends Gtk.Box {

    constructor({place, mapView, inlineMode, ...params}) {
        /* inlineMode is used in PlaceBar for inline current location details.
           It hides the title box and decreases the start margin on the rows. */

        super(params);

        this._place = place;
        this._inlineMode = !!inlineMode;

        let ui = Utils.getUIObject('place-view', [ 'bubble-main-box',
                                                   'bubble-spinner',
                                                   'bubble-thumbnail',
                                                   'thumbnail-separator',
                                                   'label-title',
                                                   'native-name',
                                                   'address-label',
                                                   'bubble-main-stack',
                                                   'bubble-content-area',
                                                   'place-buttons',
                                                   'send-to-button-alt',
                                                   'title-box' ]);
        this._title = ui.labelTitle;
        this._nativeName = ui.nativeName;
        this._thumbnail = ui.bubbleThumbnail;
        this._thumbnailSeparator = ui.thumbnailSeparator;
        this._content = ui.bubbleContentArea;
        this._mainStack = ui.bubbleMainStack;
        this._spinner = ui.bubbleSpinner;
        this._mainBox = ui.bubbleMainBox;
        this._addressLabel = ui.addressLabel;

        this.append(this._mainStack);

        let placeButtons = new PlaceButtons({ place: this._place,
                                              mapView: mapView });
        placeButtons.connect('place-edited', this._onPlaceEdited.bind(this));
        ui.placeButtons.append(placeButtons);

        if (this.place.isCurrentLocation) {
            /* Current Location bubbles have a slightly different layout, to
               avoid awkward whitespace */

            /* hide the normal button area */
            ui.placeButtons.visible = false;

            /* show the top-end-corner share button instead */
            ui.sendToButtonAlt.visible = true;
            placeButtons.initSendToButton(ui.sendToButtonAlt);

            /* adjust some margins */
            ui.titleBox.margin = 12;
            ui.titleBox.marginStart = 18;
            ui.titleBox.spacing = 18;
        }

        this.loading = true;

        this._placeDetails = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL,
                                           visible: true,
                                           hexpand: true });
        this.content.attach(this._placeDetails, 0, 0, 1, 1);

        if (this.place.isCurrentLocation) {
            this._populate(this.place);
        } else {
            let overpass = new Overpass();

            /* use a property binding from the Overpass instance to avoid
             * accessing this object after the underlying GObject has
             * been finalized */
            overpass.bind_property('place', this, 'overpass-place',
                                   GObject.BindingFlags.DEFAULT);
            this.connect('notify::overpass-place', () => this._onInfoAdded());

            if (Application.placeStore.exists(this.place, null)) {

                // If the place is stale, update from Overpass.
                if (Application.placeStore.isStale(this.place)) {
                    overpass.addInfo(this.place);
                } else {
                    this._place = Application.placeStore.get(this.place);
                    this._populate(this.place);
                }
            } else if (this.place.store && !this.place.prefilled) {
                overpass.addInfo(this.place);
            } else {
                this._populate(this.place);
            }
        }

        if (this._inlineMode) {
            ui.titleBox.hide();
        }

        this.updatePlaceDetails();

        this._place.connect('notify::location', () => this._updateLocation());
    }

    get place() {
        return this._place;
    }

    get content() {
        return this._content;
    }

    get thumbnail() {
        return this._thumbnail.pixbuf;
    }

    set thumbnail(val) {
        if (val) {
            this._thumbnail.pixbuf = val;
            this._thumbnail.visible = true;
            this._thumbnailSeparator.visible = true;
        }
    }

    get loading() {
        return this._spinner.spinning;
    }
    set loading(val) {
        this._mainStack.set_visible_child(val ? this._spinner : this._mainBox);
        this._spinner.spinning = val;
    }

    updatePlaceDetails() {
        let place = this.place;
        let formatter = new PlaceFormatter(place);

        let address = formatter.rows.map((row) => {
            row = row.map(function(prop) {
                return GLib.markup_escape_text(place[prop], -1);
            });
            return row.join(', ');
        });
        if (address.length > 0) {
            this._addressLabel.label = address.join('\n');
            this._addressLabel.show();
        } else {
            this._addressLabel.hide();
        }

        this._title.label = formatter.title;

        /* hide native name by default, so that it is only shown when it
         * should, in case it changed when re-applying changes from Overpass.
         * This could happen if the locale changed since last run.
         */
        this._nativeName.visible = false;

        /* show native name unless it's equal to the localized name, or
         * if the localized name is a substring of the native name, as can
         * be the case in e.g. duo-lingual native names, such as is used in
         * Brussels of the form "French name - Dutch name"
         */
        if (place.nativeName && !place.nativeName.includes(place.name)) {
            this._nativeName.label = place.nativeName;

            /* only show native name if there's installed fonts capable of
             * showing it
             */
            if (this._nativeName.get_layout().get_unknown_glyphs_count() === 0)
                this._nativeName.visible = true;
        }
    }

    _onInfoAdded() {
        this._populate(this.place);
        if (Application.placeStore.exists(this.place, null))
            Application.placeStore.updatePlace(this.place);
        else
            Application.placeStore.addPlace(this.place, PlaceStore.PlaceType.RECENT);
    }

    _formatWikiLink(wiki) {
        let lang = Wikipedia.getLanguage(wiki);
        let article = Wikipedia.getArticle(wiki);

        return `https://${lang}.wikipedia.org/wiki/${article}`;
    }

    _createContent(place) {
        let content = [];

        if (place.isCurrentLocation) {
            let coordinates = place.location.latitude.toFixed(5)
                              + ', '
                              + place.location.longitude.toFixed(5);
            let accuracyDescription = Utils.getAccuracyDescription(this.place.location.accuracy);

            content.push({ label: _("Coordinates"),
                           icon: 'map-marker-symbolic',
                           info: coordinates });

            content.push({ label: _("Accuracy"),
                           icon: 'find-location-symbolic',
                           /* Translators: %s can be "Unknown", "Exact" or "%f km" (or ft/mi/m) */
                           info: _("Accuracy: %s").format(accuracyDescription) });
        }

        if (place.website) {
            if (Utils.isValidWebsite(place.website)) {
                content.push({ label: _("Website"),
                               icon: 'web-browser-symbolic',
                               info: GLib.markup_escape_text(place.website, -1),
                               linkUrl: place.website });
            }
        }

        if (place.phone) {
            /* since the phone numbers are typically always rendered
             * left-to-right, insert an explicit LRM char to avoid issues
             * with phone numbers in international format starting with a +
             * which is considered a "weak" character to determine Unicode
             * text direction
             */
            let phone = { label: _("Phone number"),
                          icon: 'phone-oldschool-symbolic',
                          info: LRM + GLib.markup_escape_text(place.phone, -1) };

            if (Utils.uriSchemeSupported('tel')) {
                /* RFC3966 only allows "-", '.", "(", and ")" as visual
                 * separator characters in a global phone number, no space */
                phone.linkUrl = `tel:${place.phone.replace(/\s+/g, '')}`;
            }

            content.push(phone);
        }

        if (place.email && Utils.isValidEmail(place.email)) {
            content.push({ label: _("E-mail"),
                           icon: 'mail-unread-symbolic',
                           info: GLib.markup_escape_text(place.email, -1),
                           linkUrl: `mailto:${place.email}` });
        }

        if (place.isEatingAndDrinking) {
            switch (place.takeaway) {
                case 'yes':
                    /* Translators:
                     * The establishment offers customers to purchase meals
                     * (or similar) to be consumed elsewhere
                     */
                    content.push({ info: _("Offers takeaway"),
                                   icon: PlaceIcons.getIconForPlace(place) });
                    break;
                case 'no':
                    /* Translators:
                     * The establishment only offers customers to purchase
                     * meals (or similar) to be consumed on-premise.
                     */
                    content.push({ info: _("Does not offer takeaway"),
                                   icon: PlaceIcons.getIconForPlace(place) });
                    break;
                case 'only':
                    /* Translators:
                     * The establishment only offers customers to purchase
                     * meals (or similar) to be consumed elsewhere. E.g.
                     * there is no seating on-premise for eating/drinking
                     */
                    content.push({ info: _("Only offers takeaway"),
                                   icon: PlaceIcons.getIconForPlace(place) });
                    break;
            }
        }

        if (place.openingHours) {
            content.push({ label: _("Opening hours"),
                           icon: 'emoji-recent-symbolic',
                           grid: Translations.translateOpeningHours(place.openingHours) });
        }

        switch(place.internetAccess) {
            case 'yes':
                /* Translators:
                 * There is public internet access but the particular kind is unknown.
                 */
                content.push({ info: _("Public internet access"),
                               icon: 'network-wireless-signal-excellent-symbolic' });
                break;

            case 'no':
                /* Translators:
                 * no internet access is offered in a place where
                 * someone might expect it.
                 */
                content.push({ info: _("No internet access"),
                               icon: 'network-wireless-offline-symbolic' });
                break;

            case 'wlan':
                /* Translators:
                 * This means a WLAN Hotspot, also known as wireless, wifi or Wi-Fi.
                 */
                content.push({ info: _("Public Wi-Fi"),
                               icon: 'network-wireless-signal-excellent-symbolic' });
                break;

            case 'wired':
                /* Translators:
                 * This means a a place where you can plug in your laptop with ethernet.
                 */
                content.push({ info: _("Wired internet access"),
                               icon: 'network-wired-symbolic' });
                break;

            case 'terminal':
                /* Translators:
                 * Like internet cafe or library where the computer is given.
                 */
                content.push({ info: _("Computers available for use"),
                               icon: 'computer-symbolic' });
                break;

            case 'service':
                /* Translators:
                 * This means there is personnel which helps you in case of problems.
                 */
                content.push({ info: _("Internet assistance available"),
                               icon: 'computer-symbolic' });
                break;
        }

        if (place.toilets === 'no') {
            content.push({ info: _("No toilets available"),
                           icon: 'no-toilets-symbolic' });
        } else if (place.toilets === 'yes') {
            content.push({ info: _("Toilets available"),
                           icon: 'toilets-symbolic' });
        }

        switch(place.wheelchair) {
            case 'yes':
                /* Translators:
                 * This means wheelchairs have full unrestricted access.
                 */
                content.push({ info: _("Wheelchair accessible"),
                               icon: 'wheelchair-symbolic' });
                break;

            case 'limited':
                /* Translators:
                 * This means wheelchairs have partial access (e.g some areas
                 * can be accessed and others not, areas requiring assistance
                 * by someone pushing up a steep gradient).
                 */
                content.push({ info: _("Limited wheelchair accessibility"),
                               icon: 'wheelchair-limited-symbolic'  });
                break;

            case 'no':
                /* Translators:
                 * This means wheelchairs have no unrestricted access
                 * (e.g. stair only access).
                 */
                content.push({ info: _("Not wheelchair accessible"),
                               icon: 'no-wheelchair-symbolic'  });
                break;

            case 'designated':
                /* Translators:
                 * This means that the way or area is designated or purpose built
                 * for wheelchairs (e.g. elevators designed for wheelchair access
                 * only). This is rarely used.
                 */
                content.push({ info: _("Designated for wheelchair users"),
                               icon: 'wheelchair-symbolic'  });
                break;
        }

        if (place.population) {
            /* TODO: this is a bit of a work-around to re-interpret the population,
             * stored as a string into an integer to convert back to a locale-
             * formatted string. Ideally it should be kept as an integer value
             * in the Place class. But this will also need to be handled by the
             * PlaceStore, possible in a backwards-compatible way
             */
            content.push({ label: _("Population"),
                           icon: 'system-users-symbolic',
                           info: Utils.prettyPopulation(parseInt(place.population)) });
        }

        /* The default value for a place's altitude is -G_MAXDOUBLE, so we can
         * compare to an impossibly low altitude to see if one is set */
        if (place.location.altitude > -1000000000.0) {
            let alt  = place.location.altitude;
            let info;

            if (alt > 0) {
                info = Utils.prettyDistance(alt, true);
            } else if (alt < 0) {
                /**
                 * Translators: this is a label indicating an altitude below
                 * sea level, where the %s placeholder is the altitude relative
                 * to mean sea level in the "negative direction"
                 */
                info = _("%s below sea level").
                            format(Utils.prettyDistance(-alt, true));
            } else {
                /**
                 * Translators: this indicates a place is located at (or very
                 * close to) mean sea level
                 */
                info = _("At sea level");
            }

            content.push({ label: _("Altitude"),
                           icon: 'mountain-symbolic',
                           info: info });
        }

        if (place.religion) {
            content.push({ label: _("Religion:"),
                           info: Translations.translateReligion(place.religion) });
        }

        if (place.wiki && Wikipedia.isValidWikipedia(place.wiki) ||
            place.wikidata && Wikipedia.isValidWikidata(place.wikidata)) {
            content.push({ type: 'wikipedia', info: '' });
        }

        return content;
    }

    _attachContent(content) {
        content.forEach(({ type, label, icon, linkUrl, info, grid }) => {
            let separator = new Gtk.Separator({ visible: true });
            separator.get_style_context().add_class('no-margin-separator');
            this._placeDetails.append(separator);

            let box = new Gtk.Box({ orientation: Gtk.Orientation.HORIZONTAL,
                                    visible: true,
                                    marginStart: 12,
                                    marginEnd: 12,
                                    marginTop: 6,
                                    marginBottom: 6,
                                    spacing: 12 });

            if (this._inlineMode) {
                box.marginStart = 6;
            }

            if (icon) {
                let widget = new Gtk.Image({ icon_name: icon,
                                             visible: true,
                                             valign: Gtk.Align.START,
                                             halign: Gtk.Align.END });

                if (label) {
                    widget.tooltip_markup = label;
                }

                box.append(widget);
            } else if (label) {
                let widget = new Gtk.Label({ label: label.italics(),
                                             visible: true,
                                             use_markup: true,
                                             yalign: 0,
                                             halign: Gtk.Align.END });
                box.append(widget);
            }

            if (linkUrl) {
                let uri = GLib.markup_escape_text(linkUrl, -1);
                /* double-escape the tooltip text, as GTK treats it as markup */
                let tooltipText = GLib.markup_escape_text(uri, -1);
                info = `<a href="${uri}" title="${tooltipText}">${info}</a>`;
            }

            let widget;

            if (grid) {
                widget = new Gtk.Grid({ visible:        true,
                                        column_spacing: 6 });

                for (let i = 0; i < grid.length; i++) {
                    let row = grid[i];

                    for (let j = 0; j < row.length; j++) {
                        let label = new Gtk.Label({ label:   row[j],
                                                    visible: true,
                                                    xalign:  0,
                                                    hexpand: false,
                                                    wrap: true,
                                                    halign:  Gtk.Align.FILL });

                        if (j === 1) {
                            /* set tabular digits for the second column to get
                             * aligned times
                             */
                            let attrList = Pango.AttrList.new();
                            let tnum = Pango.AttrFontFeatures.new('tnum');

                            attrList.insert(tnum);
                            label.set_attributes(attrList);
                        }

                        widget.attach(label, j, i, 1, 1);
                    }
                }
            } else {
                widget = new Gtk.Label({ label: info,
                                         visible: true,
                                         use_markup: true,
                                         max_width_chars: 30,
                                         wrap: true,
                                         xalign: 0,
                                         hexpand: true,
                                         halign: Gtk.Align.FILL });

                if (type === 'wikipedia') {
                    box.marginTop = 12;
                    box.marginBottom = 18;
                    this._wikipediaLabel = widget;
                }
            }

            box.append(widget);
            this._placeDetails.append(box);
        });
    }

    _populate(place) {
        // refresh place view
        this._clearView();

        let content = this._createContent(place);
        this._attachContent(content);

        if (place.wikidata && Wikipedia.isValidWikidata(place.wikidata)) {
            let defaultArticle =
                place.wiki && Wikipedia.isValidWikipedia(place.wiki) ?
                place.wiki : null;

            this._requestWikidata(place.wikidata, defaultArticle);
        } else if (place.wiki && Wikipedia.isValidWikipedia(place.wiki)) {
            this._requestWikipedia(place.wiki);
        }

        this.updatePlaceDetails();
        this.loading = false;
    }

    _requestWikipedia(wiki) {
        Wikipedia.fetchArticleInfo(wiki,
                                   THUMBNAIL_FETCH_SIZE,
                                   this._onWikiMetadataComplete.bind(this),
                                   this._onThumbnailComplete.bind(this));
    }

    _requestWikidata(wikidata, defaultArticle) {
        Wikipedia.fetchArticleInfoForWikidata(
            wikidata, defaultArticle, THUMBNAIL_FETCH_SIZE,
            this._onWikiMetadataComplete.bind(this),
            this._onThumbnailComplete.bind(this));
    }

    _onThumbnailComplete(thumbnail) {
        this.thumbnail = thumbnail;
    }

    _onWikiMetadataComplete(wiki, metadata) {
        if (metadata.extract) {
            let text = GLib.markup_escape_text(metadata.extract, -1);
            let link = this._formatWikiLink(wiki);

            /* If the text goes past some number of characters (see
             * wikipedia.js), it is ellipsized with '...'
             * GNOME HIG says to use U+2026 HORIZONTAL ELLIPSIS instead.
             * Also, trim whitespace. */
            text = text.replace(/\s*\.\.\.\s*$/, '…');

            let uri = GLib.markup_escape_text(link, -1);
            /* double-escape the tooltip text, as GTK treats it as markup */
            let tooltipText = GLib.markup_escape_text(uri, -1);

            /* Translators: This is the text for the "Wikipedia" link at the end
               of summaries */
            this._wikipediaLabel.label = `${text} <a href="${uri}" title="${tooltipText}">${ _("Wikipedia") }</a>`;
        }
    }

    // clear the view widgets to be able to re-populate an updated place
    _clearView() {
        let details = [];

        for (let detail of this._placeDetails) {
            details.push(detail);
        }

        for (let detail of details) {
            this._placeDetails.remove(detail);
        }
    }

    // called when the place's location changes (e.g. for the current location)
    _updateLocation() {
        this._populate(this.place);
    }

    /* called when the place is edited via the OSM edit dialog */
    _onPlaceEdited() {
        this._populate(this._place);
    }
}

GObject.registerClass({
    Properties: {
        'overpass-place': GObject.ParamSpec.object('overpass-place',
                                                   'Overpass Place',
                                                   'The place as filled in by Overpass',
                                                   GObject.ParamFlags.READABLE |
                                                   GObject.ParamFlags.WRITABLE,
                                                   GeocodeGlib.Place)
    }
}, PlaceView);