summaryrefslogtreecommitdiff
path: root/src/transitPlan.js
blob: d30f9db8f7f8dfa7be11accb3633e38636ff6323 (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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/* -*- Mode: JS2; indent-tabs-mode: nil; js2-basic-offset: 4 -*- */
/* vim: set et ts=4 sw=4: */
/*
 * Copyright (c) 2017 Marcus Lundblad
 *
 * 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: Marcus Lundblad <ml@update.uu.se>
 */

const _ = imports.gettext.gettext;
const ngettext = imports.gettext.ngettext;

const Champlain = imports.gi.Champlain;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;

const HVT = imports.hvt;

// in org.gnome.desktop.interface
const CLOCK_FORMAT_KEY = 'clock-format';

let _desktopSettings = new Gio.Settings({ schema_id: 'org.gnome.desktop.interface' });
let clockFormat = _desktopSettings.get_string(CLOCK_FORMAT_KEY);

/*
 * These constants corresponds to the routeType attribute of transit legs
 * in original GTFS specification.
 */
var RouteType = {
    NON_TRANSIT: -1,
    TRAM:        0,
    SUBWAY:      1,
    TRAIN:       2,
    BUS:         3,
    FERRY:       4,
    /* Cable car referres to street-level cabel cars, where the propulsive
     * cable runs in a slot between the tracks beneeth the car
     * https://en.wikipedia.org/wiki/Cable_car_%28railway%29
     * For example the cable cars in San Fransisco
     * https://en.wikipedia.org/wiki/San_Francisco_cable_car_system
     */
    CABLE_CAR:   5,
    /* Gondola referres to a suspended cable car, typically aerial cable cars
     * where the car is suspended from the cable
     * https://en.wikipedia.org/wiki/Gondola_lift
     * For example the "Emirates Air Line" in London
     * https://en.wikipedia.org/wiki/Emirates_Air_Line_%28cable_car%29
     */
    GONDOLA:     6,
    /* Funicular referres to a railway system designed for steep inclines,
     * https://en.wikipedia.org/wiki/Funicular
     */
    FUNICULAR:   7
};

/* extra time to add to the first itinerary leg when it's a walking leg */
const WALK_SLACK = 120;

function _printTimeWithTZOffset(time, offset) {
    let utcTimeWithOffset = (time + offset) / 1000;
    let date = GLib.DateTime.new_from_unix_utc(utcTimeWithOffset);

    if (clockFormat === '24h')
        return date.format('%R');
    else
        return date.format('%r');
}

var DEFAULT_ROUTE_COLOR = '4c4c4c';
var DEFAULT_ROUTE_TEXT_COLOR = 'ffffff';

var Plan = GObject.registerClass({
    Signals: {
        'update': {},
        'reset': {},
        'no-more-results': {},
        'itinerary-selected': { param_types: [GObject.TYPE_OBJECT] },
        'itinerary-deselected': {},
        'error': { param_types: [GObject.TYPE_STRING] }
    }
}, class Plan extends GObject.Object {

    _init(params) {
        super._init(params);
        this.reset();
    }

    get itineraries() {
        return this._itineraries;
    }

    get selectedItinerary() {
        return this._selectedItinerary;
    }

    update(itineraries) {
        this._itineraries = itineraries;
        this.bbox = this._createBBox();
        this.emit('update');
    }

    reset() {
        this._itineraries = [];
        this.bbox = null;
        this._selectedItinerary = null;
        this.emit('reset');
    }

    noMoreResults() {
        this.emit('no-more-results');
    }

    selectItinerary(itinerary) {
        this._selectedItinerary = itinerary;
        this.emit('itinerary-selected', itinerary);
    }

    deselectItinerary() {
        this._selectedItinerary = null;
        this.emit('itinerary-deselected');
    }

    error(msg) {
        this.emit('error', msg);
    }

    noRouteFound() {
        this.emit('error', _("No route found."));
    }

    noTimetable() {
        this.emit('error', _("No timetable data found for this route."));
    }

    requestFailed() {
        this.emit('error', _("Route request failed."));
    }

    _createBBox() {
        let bbox = new Champlain.BoundingBox();
        this._itineraries.forEach(function(itinerary) {
            bbox.compose(itinerary.bbox);
        });
        return bbox;
    }
});

var Itinerary = GObject.registerClass(
class Itinerary extends GObject.Object {

    _init(params) {
        this._duration = params.duration;
        delete params.duration;

        this._departure = params.departure;
        delete params.departure;

        this._arrival = params.arrival;
        delete params.arrival;

        this._transfers = params.transfers;
        delete params.transfers;

        this._legs = params.legs;
        delete params.legs;

        super._init(params);

        this.bbox = this._createBBox();
    }

    get duration() {
        return this._duration;
    }

    get departure() {
        return this._departure;
    }

    get arrival() {
        return this._arrival;
    }

    get transfers() {
        return this._transfers;
    }

    get legs() {
        return this._legs;
    }

    /* adjust timings of the legs of the itinerary, using the real duration of
     * walking legs, also sets the timezone offsets according to adjacent
     * transit legs
     */
    _adjustLegTimings() {
        if (this.legs.length === 1 && !this.legs[0].transit) {
            /* if there is only one leg, and it's a walking one, just need to
             * adjust the arrival time
             */
            let leg = this.legs[0];
            leg.arrival = leg.departure + leg.duration * 1000;

            return;
        }

        for (let i = 0; i < this.legs.length; i++) {
            let leg = this.legs[i];

            if (!leg.transit) {
                if (i === 0) {
                    /* for the first leg subtract the walking time plus a
                     * safty slack from the departure time of the following
                     * leg
                     */
                    let nextLeg = this.legs[i + 1];
                    leg.departure =
                        nextLeg.departure - leg.duration * 1000 - WALK_SLACK;
                    leg.arrival = leg.departure + leg.duration * 1000;
                    // use the timezone offset from the first transit leg
                    leg.agencyTimezoneOffset = nextLeg.agencyTimezoneOffset;
                } else {
                    /* for walking legs in the middle or at the end, just add
                     * the actual walking walk duration to the arrival time of
                     * the previous leg
                     */
                    let previousLeg = this.legs[i - 1];
                    leg.departure = previousLeg.arrival;
                    leg.arrival = previousLeg.arrival + leg.duration * 1000;
                    // use the timezone offset of the previous (transit) leg
                    leg.agencyTimezoneOffset = previousLeg.agencyTimezoneOffset;
                }
            }
        }
    }

    _createBBox() {
        let bbox = new Champlain.BoundingBox();

        this._legs.forEach(function(leg) {
            bbox.compose(leg.bbox);
        });

        return bbox;
    }

    prettyPrintTimeInterval() {
        /* Translators: this is a format string for showing a departure and
         * arrival time, like:
         * "12:00 – 13:03" where the placeholder %s are the actual times,
         * these could be rearranged if needed.
         */
        return _("%s \u2013 %s").format(this._getDepartureTime(),
                                        this._getArrivalTime());
    }

    _getDepartureTime() {
        /* take the itinerary departure time and offset using the timezone
         * offset of the first leg */
        return _printTimeWithTZOffset(this.departure,
                                      this.legs[0].agencyTimezoneOffset);
    }

    _getArrivalTime() {
        /* take the itinerary departure time and offset using the timezone
         * offset of the last leg */
        let lastLeg = this.legs[this.legs.length - 1];
        return _printTimeWithTZOffset(this.arrival,
                                      lastLeg.agencyTimezoneOffset);
    }

    prettyPrintDuration() {
        let mins = this.duration / 60;

        if (mins < 60) {
            /* translators: this is an indication for a trip duration of
             * less than an hour, with only the minutes part, using plural forms
             * as appropriate
             */
            return ngettext("%d minute", "%d minutes", mins).format(mins);
        } else {
            let hours = Math.floor(mins / 60);

            mins = mins % 60;

            if (mins === 0) {
                /* translators: this is an indication for a trip duration,
                 * where the duration is an exact number of hours (i.e. no
                 * minutes part), using plural forms as appropriate
                 */
                return ngettext("%d hour", "%d hours", hours).format(hours);
            } else {
                /* translators: this is an indication for a trip duration
                 * where the duration contains an hour and minute part, it's
                 * pluralized on the hours part
                 */
                return ngettext("%d:%02d hour", "%d:%02d hours", hours).format(hours, mins);
            }
        }
    }

    adjustTimings() {
        this._adjustLegTimings();
        this._departure = this._legs[0].departure;
        this._arrival = this._legs[this._legs.length - 1].arrival;
        this._duration = (this._arrival - this._departure) / 1000;
    }

    _getTransitDepartureLeg() {
        for (let i = 0; i < this._legs.length; i++) {
            let leg = this._legs[i];

            if (leg.transit)
                return leg;
        }

        throw new Error('no transit leg found');
    }

    _getTransitArrivalLeg() {
        for (let i = this._legs.length - 1; i >= 0; i--) {
            let leg = this._legs[i];

            if (leg.transit)
                return leg;
        }

        throw new Error('no transit leg found');
    }

    /* gets the departure time of the first transit leg */
    get transitDepartureTime() {
        return this._getTransitDepartureLeg().departure;
    }

    /* gets the timezone offset of the first transit leg */
    get transitDepartureTimezoneOffset() {
        return this._getTransitDepartureLeg().timezoneOffset;
    }

    /* gets the arrival time of the final transit leg */
    get transitArrivalTime() {
        return this._getTransitArrivalLeg().arrival;
    }

    /* gets the timezone offset of the final transit leg */
    get transitArrivalTimezoneOffset() {
        return this._getTransitArrivalLeg().timezoneOffset;
    }
});

var Leg = class Leg {

    constructor(params) {
        this._route = params.route;
        delete params.route;

        this._routeType = params.routeType;
        delete params.routeType;

        this._departure = params.departure;
        delete params.departure;

        this._arrival = params.arrival;
        delete params.arrival;

        this._polyline = params.polyline;
        delete params.polyline;

        this._fromCoordinate = params.fromCoordinate;
        delete params.fromCoordinate;

        this._toCoordinate = params.toCoordinate;
        delete params.toCoordinate;

        this._from = params.from;
        delete params.from;

        this._to = params.to;
        delete params.to;

        this._intermediateStops = params.intermediateStops;
        delete params.intermediateStops;

        this._headsign = params.headsign;
        delete params.headsign;

        this._isTransit = params.isTransit;
        delete params.isTransit;

        this._walkingInstructions = params.walkingInstructions;
        delete params.walkingInstructions;

        this._distance = params.distance;
        delete params.distance;

        this._duration = params.duration;
        delete params.duration;

        this._agencyName = params.agencyName;
        delete params.agencyName;

        this._agencyUrl = params.agencyUrl;
        delete params.agencyUrl;

        this._agencyTimezoneOffset = params.agencyTimezoneOffset;
        delete params.agencyTimezoneOffset;

        this._color = params.color;
        delete params.color;

        this._textColor = params.textColor;
        delete params.textColor;

        this._tripShortName = params.tripShortName;
        delete params.tripShortName;

        this.bbox = this._createBBox();

        this._compactRoute = null;
    }

    get route() {
        return this._route;
    }

    // try to get a shortened route name, suitable for overview rendering
    get compactRoute() {
        if (this._compactRoute)
            return this._compactRoute;

        if (this._route.startsWith(this._agencyName)) {
            /* if the agency name is a prefix of the route name, display the
             * agency name in the overview, this way we get a nice "transition"
             * into the expanded route showing the full route name
             */
            this._compactRoute = this._agencyName;
        } else if (this._tripShortName &&
                   (this._agencyName.length < this._tripShortName.length)) {
            /* if the agency name is shorter than the trip short name,
             * which can sometimes be a more "internal" number, like a
             * "train number", which is less known by the general public,
             * prefer the agency name */
            this._compactRoute = this._agencyName;
        } else if (this._tripShortName && this._tripShortName.length <= 6) {
            /* if the above conditions are unmet, use the trip short name
             * as a fallback if it was shorter than the original route name */
            this._compactRoute = this._tripShortName;
        } else if (this._color) {
            /* as a fallback when the route has a defined color,
             * use an empty compact label to get a colored badge */
            this._compactRoute = '';
        } else {
            /* if none of the above is true, use the original route name,
             * and rely on label ellipsization */
            this._compactRoute = this._route;
        }

        return this._compactRoute;
    }

    get routeType() {
        return this._routeType;
    }

    get departure() {
        return this._departure;
    }

    set departure(departure) {
        this._departure = departure;
    }

    get arrival() {
        return this._arrival;
    }

    get timezoneOffset() {
        return this._agencyTimezoneOffset;
    }

    set arrival(arrival) {
        this._arrival = arrival;
    }

    get polyline() {
        return this._polyline;
    }

    get fromCoordinate() {
        return this._fromCoordinate;
    }

    get toCoordinate() {
        return this._toCoordinate;
    }

    get from() {
        return this._from;
    }

    get to() {
        return this._to;
    }

    get intermediateStops() {
        return this._intermediateStops;
    }

    get headsign() {
        return this._headsign;
    }

    get transit() {
        return this._isTransit;
    }

    get distance() {
        return this._distance;
    }

    get duration() {
        return this._duration;
    }

    get agencyName() {
        return this._agencyName;
    }

    get agencyUrl() {
        return this._agencyUrl;
    }

    get agencyTimezoneOffset() {
        return this._agencyTimezoneOffset;
    }

    set agencyTimezoneOffset(tzOffset) {
        this._agencyTimezoneOffset = tzOffset;
    }

    get color() {
        return this._color || DEFAULT_ROUTE_COLOR;
    }

    get textColor() {
        return this._textColor || DEFAULT_ROUTE_TEXT_COLOR;
    }

    get tripShortName() {
        return this._tripShortName;
    }

    _createBBox() {
        let bbox = new Champlain.BoundingBox();

        this.polyline.forEach(function({ latitude, longitude }) {
            bbox.extend(latitude, longitude);
        });

        return bbox;
    }

    get iconName() {
        if (this._isTransit) {
            let type = this._routeType;
            switch (type) {
                /* special case HVT codes */
                case HVT.CABLE_CAR:
                    return 'route-transit-cablecar-symbolic';
                default:
                    let hvtSupertype = HVT.supertypeOf(type);

                    if (hvtSupertype !== -1)
                        type = hvtSupertype;

                    switch (type) {
                        case RouteType.TRAM:
                        case HVT.TRAM_SERVICE:
                            return 'route-transit-tram-symbolic';

                        case RouteType.SUBWAY:
                        case HVT.METRO_SERVICE:
                        case HVT.URBAN_RAILWAY_SERVICE:
                        case HVT.UNDERGROUND_SERVICE:
                            return 'route-transit-subway-symbolic';

                        case RouteType.TRAIN:
                        case HVT.RAILWAY_SERVICE:
                        case HVT.SUBURBAN_RAILWAY_SERVICE:
                            return 'route-transit-train-symbolic';

                        case RouteType.BUS:
                        case HVT.BUS_SERVICE:
                        case HVT.COACH_SERVICE:
                        case HVT.TROLLEYBUS_SERVICE:
                            /* TODO: handle a special case icon for trolleybus */
                            return 'route-transit-bus-symbolic';

                        case RouteType.FERRY:
                        case HVT.WATER_TRANSPORT_SERVICE:
                        case HVT.FERRY_SERVICE:
                            return 'route-transit-ferry-symbolic';

                        case RouteType.CABLE_CAR:
                            return 'route-transit-cablecar-symbolic';

                        case RouteType.GONDOLA:
                        case HVT.TELECABIN_SERVICE:
                            return 'route-transit-gondolalift-symbolic';

                        case RouteType.FUNICULAR:
                        case HVT.FUNICULAR_SERVICE:
                            return 'route-transit-funicular-symbolic';

                        case HVT.TAXI_SERVICE:
                            /* TODO: should we have a dedicated taxi icon? */
                            return 'route-car-symbolic';
                        default:
                            /* use a fallback question mark icon in case of some future,
                             * for now unknown mode appears */
                            return 'dialog-question-symbolic';
                    }
            }
        } else {
            return 'route-pedestrian-symbolic';
        }
    }

    get walkingInstructions() {
        return this._walkingInstructions;
    }

    /* Pretty print timing for a transit leg, set params.isStart: true when
     * printing for the starting leg of an itinerary.
     * For starting walking legs, only the departure time will be printed,
     * otherwise the departure and arrival time of the leg (i.e. transit ride
     * or an in-between walking section) will be printed.
     */
    prettyPrintTime(params) {
        if (!this.transit && params.isStart) {
            return this.prettyPrintDepartureTime();
        } else {
            /* Translators: this is a format string for showing a departure and
             * arrival time in a more compact manner to show in the instruction
             * list for an itinerary, like:
             * "12:00–13:03" where the placeholder %s are the actual times,
             * these could be rearranged if needed.
             */
            return _("%s\u2013%s").format(this.prettyPrintDepartureTime(),
                                          this.prettyPrintArrivalTime());
        }
    }

    prettyPrintDepartureTime() {
        /* take the itinerary departure time and offset using the timezone
         * offset of the first leg
         */
        return _printTimeWithTZOffset(this.departure, this.agencyTimezoneOffset);
    }

    prettyPrintArrivalTime() {
        /* take the itinerary departure time and offset using the timezone
         * offset of the last leg
         */
        return _printTimeWithTZOffset(this.arrival, this.agencyTimezoneOffset);
    }
};

var Stop = class Stop {

    constructor(params) {
        this._name = params.name;
        delete params.name;

        this._arrival = params.arrival;
        delete params.arrival;

        this._departure = params.departure;
        delete params.departure;

        this._agencyTimezoneOffset = params.agencyTimezoneOffset;
        delete params.agencyTimezoneOffset;

        this._coordinate = params.coordinate;
        delete params.coordinate;
    }

    get name() {
        return this._name;
    }

    get coordinate() {
        return this._coordinate;
    }

    prettyPrint(params) {
        if (params.isFinal) {
            /* take the stop arrival time and offset using the timezone
             * offset of the last leg
             */
            return _printTimeWithTZOffset(this._arrival,
                                          this._agencyTimezoneOffset);
        } else {
            /* take the stop departure time and offset using the timezone
             * offset of the first leg
             */
            return _printTimeWithTZOffset(this._departure,
                                          this._agencyTimezoneOffset);
        }
    }
};

function sortItinerariesByDepartureAsc(first, second) {
    return first.departure > second.departure;
}

function sortItinerariesByArrivalDesc(first, second) {
    return first.arrival < second.arrival;
}